1 /// contains the Scene class 2 module ysge.scene; 3 4 import ysge.project; 5 public import ysge.objects.simpleBox; 6 7 /// individual scene containing objects 8 class Scene { 9 GameObject[] objects; 10 UIElement[] ui; 11 SDL_Color bg; 12 Vec2!int camera; 13 bool cameraFollowsObject; 14 Vec2!int* cameraFollow; 15 16 /// called when this scene is set as the project's current scene 17 abstract void Init(Project parent); 18 /// run every frame 19 abstract void Update(Project parent); 20 /// run when an event is created 21 abstract void HandleEvent(Project parent, SDL_Event e); 22 23 /// makes the camera follow an object 24 void CameraFollowObject(SimpleBox obj) { 25 cameraFollowsObject = true; 26 cameraFollow = cast(Vec2!int*) &obj.box; 27 } 28 29 /// stops the camera from following an object 30 void StopFollowingObject() { 31 cameraFollowsObject = false; 32 cameraFollow = null; 33 } 34 35 /// adds a game object to the scene's object array 36 void AddObject(GameObject object) { 37 objects ~= object; 38 } 39 40 /// adds a UI element to the scene 41 void AddUI(UIElement element) { 42 ui ~= element; 43 } 44 45 /** 46 * makes the camera follow an object if enabled 47 * should not be called by the user 48 */ 49 void UpdateCamera(Project parent) { 50 if (cameraFollowsObject) { 51 auto screenRes = parent.GetResolution(); 52 Vec2!int pos = Vec2!int(cameraFollow.x, cameraFollow.y); 53 Vec2!int size = Vec2!int(cameraFollow.x, cameraFollow.y); 54 55 camera.x = pos.x - (screenRes.x / 2); 56 camera.y = pos.y - (screenRes.y / 2); 57 } 58 } 59 60 /** 61 * calls the update function of all objects in the scene 62 * should not be called by the user 63 */ 64 void UpdateObjects(Project parent) { 65 foreach (ref object ; objects) { 66 object.Update(parent); 67 } 68 } 69 70 /** 71 * sends event to UI elements 72 * should not be called by the user 73 */ 74 bool HandleUIEvent(Project parent, SDL_Event e) { 75 foreach (ref element ; ui) { 76 if (element.HandleEvent(parent, e)) { 77 return true; 78 } 79 } 80 return false; 81 } 82 83 /// render the scene, should not be called by the user 84 void Render(Project parent) { 85 SDL_SetRenderDrawColor(parent.renderer, bg.r, bg.g, bg.b, bg.a); 86 SDL_RenderClear(parent.renderer); 87 88 foreach (ref object ; objects) { 89 object.Render(parent); 90 } 91 92 foreach (ref element ; ui) { 93 element.Render(parent); 94 } 95 96 SDL_RenderPresent(parent.renderer); 97 } 98 }