]> git.tdb.fi Git - libs/game.git/blob - source/game/stage.h
d2d05dd986a1c2f21a1f9f59f9a1116d7b330448
[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 Root;
15 class System;
16
17 class Stage
18 {
19 public:
20         using EventSource = Game::EventSource<Events::EntityCreated, Events::EntityDestroyed,
21                 Events::ComponentCreated, Events::ComponentDestroyed>;
22
23 private:
24         DataFile::Collection &resources;
25         PoolPool pools;
26         EventBus event_bus;
27         EventSource event_source;
28         /* Use unique_ptr because there's only one root per stage so it's pointless
29         to put it in a pool. */
30         std::unique_ptr<Root> root;
31         std::vector<std::unique_ptr<System>> systems;
32
33 public:
34         Stage(DataFile::Collection &);
35         ~Stage();
36
37         DataFile::Collection &get_resources() const { return resources; }
38         PoolPool &get_pools() { return pools; }
39         EventBus &get_event_bus() { return event_bus; }
40         EventSource &get_event_source() { return event_source; }
41         Handle<Root> get_root() { return Handle<Root>::from_object(root.get()); }
42
43         template<typename T, typename F>
44         void iterate_objects(const F &);
45
46         template<typename T, typename... Args>
47         T &add_system(Args &&...);
48
49         void remove_system(System &);
50         const std::vector<std::unique_ptr<System>> &get_systems() const { return systems; }
51
52         template<typename T>
53         T *get_system() const;
54
55         void tick(Time::TimeDelta);
56 };
57
58 template<typename T, typename F>
59 inline void Stage::iterate_objects(const F &func)
60 {
61         pools.get_pool<T>().iterate_objects(func);
62 }
63
64 template<typename T, typename... Args>
65 inline T &Stage::add_system(Args &&... args)
66 {
67         systems.emplace_back(std::make_unique<T>(*this, std::forward<Args>(args)...));
68         return static_cast<T &>(*systems.back());
69 }
70
71 template<typename T>
72 inline T *Stage::get_system() const
73 {
74         for(const auto &s: systems)
75                 if(T *ts = dynamic_cast<T *>(s.get()))
76                         return ts;
77         return nullptr;
78 }
79
80 } // namespace Msp::Game
81
82 #endif