]> git.tdb.fi Git - libs/game.git/blob - source/game/stage.h
Add a view sub-library, including a Camera component
[libs/game.git] / source / game / stage.h
1 #ifndef MSP_GAME_STAGE_H_
2 #define MSP_GAME_STAGE_H_
3
4 #include <memory>
5 #include <msp/datafile/collection.h>
6 #include <msp/time/timedelta.h>
7 #include "eventbus.h"
8 #include "events.h"
9 #include "eventsource.h"
10 #include "handle.h"
11
12 namespace Msp::Game {
13
14 class Camera;
15 class Root;
16 class System;
17
18 class Stage
19 {
20 public:
21         using EventSource = Game::EventSource<Events::EntityCreated, Events::EntityDestroyed,
22                 Events::ComponentCreated, Events::ComponentDestroyed, Events::CameraChanged>;
23
24 private:
25         DataFile::Collection &resources;
26         PoolPool pools;
27         EventBus event_bus;
28         EventSource event_source;
29         EventObserver event_observer;
30         /* Use unique_ptr because there's only one root per stage so it's pointless
31         to put it in a pool. */
32         std::unique_ptr<Root> root;
33         std::vector<std::unique_ptr<System>> systems;
34         Handle<Camera> active_camera;
35
36 public:
37         Stage(DataFile::Collection &);
38         ~Stage();
39
40         DataFile::Collection &get_resources() const { return resources; }
41         PoolPool &get_pools() { return pools; }
42         EventBus &get_event_bus() { return event_bus; }
43         EventSource &get_event_source() { return event_source; }
44         Handle<Root> get_root() { return Handle<Root>::from_object(root.get()); }
45
46         template<typename T, typename F>
47         void iterate_objects(const F &);
48
49         template<typename T, typename... Args>
50         T &add_system(Args &&...);
51
52         void remove_system(System &);
53         const std::vector<std::unique_ptr<System>> &get_systems() const { return systems; }
54
55         template<typename T>
56         T *get_system() const;
57
58         void set_active_camera(Handle<Camera>);
59         Handle<Camera> get_active_camera() const { return active_camera; }
60
61         void tick(Time::TimeDelta);
62 };
63
64 template<typename T, typename F>
65 inline void Stage::iterate_objects(const F &func)
66 {
67         pools.get_pool<T>().iterate_objects(func);
68 }
69
70 template<typename T, typename... Args>
71 inline T &Stage::add_system(Args &&... args)
72 {
73         systems.emplace_back(std::make_unique<T>(*this, std::forward<Args>(args)...));
74         return static_cast<T &>(*systems.back());
75 }
76
77 template<typename T>
78 inline T *Stage::get_system() const
79 {
80         for(const auto &s: systems)
81                 if(T *ts = dynamic_cast<T *>(s.get()))
82                         return ts;
83         return nullptr;
84 }
85
86 } // namespace Msp::Game
87
88 #endif