]> git.tdb.fi Git - libs/game.git/commitdiff
Make it possible to retrieve components and systems of a particular type
authorMikko Rasa <tdb@tdb.fi>
Tue, 25 Oct 2022 21:17:06 +0000 (00:17 +0300)
committerMikko Rasa <tdb@tdb.fi>
Tue, 25 Oct 2022 21:17:06 +0000 (00:17 +0300)
source/game/entity.h
source/game/handle.h
source/game/stage.h

index c28cbe5075b94567709ba562f33698097e959e29..c4cf83c119b26bce36fce09ac1238be2bebcd1d2 100644 (file)
@@ -36,6 +36,11 @@ public:
        void add_component(Handle<Component>);
        void remove_component(Handle<Component>);
 
+       template<typename T>
+       Handle<T> get_component();
+
+       Handle<Transform> get_transform() const { return transform; }
+
        void add_child(Handle<Entity>);
        void remove_child(Handle<Entity>);
 
@@ -43,10 +48,18 @@ public:
        Handle<Entity> get_root();
        const std::vector<Handle<Entity>> &get_children() const { return children; }
        Stage &get_stage();
-       Handle<Transform> get_transform() const { return transform; }
 };
 
 
+template<typename T>
+inline Handle<T> Entity::get_component()
+{
+       for(Handle<Component> c: components)
+               if(Handle<T> tc = dynamic_handle_cast<T>(c))
+                       return tc;
+       return nullptr;
+}
+
 inline Handle<Entity> Entity::get_root()
 {
        Handle<Entity> e = Handle<Entity>::from_object(this);
index 2e544c7238e75ca7d5418c9f5c7a05c65e61081e..b08bcf8e4f903028894702e8085df47174ce640f 100644 (file)
@@ -39,6 +39,13 @@ public:
        bool operator==(const Handle &other) const = default;
 };
 
+template<typename T, typename U>
+       requires std::is_base_of_v<U, T>
+Handle<T> dynamic_handle_cast(Handle<U> h)
+{
+       return Handle<T>::from_object(dynamic_cast<T *>(h.get()));
+}
+
 } // namespace Msp::Game
 
 #endif
index 80e7a4b72c25e51141d43718c6bed196ffdf712c..d7793e22f60ec21fd52acab1b8af9aafbe2f4d94 100644 (file)
@@ -45,22 +45,34 @@ public:
 
        const std::vector<std::unique_ptr<System>> &get_systems() const { return systems; }
 
+       template<typename T>
+       T *get_system() const;
+
        void tick(Time::TimeDelta);
 };
 
 template<typename T, typename F>
-void Stage::iterate_objects(const F &func)
+inline void Stage::iterate_objects(const F &func)
 {
        pools.get_pool<T>().iterate_objects(func);
 }
 
 template<typename T, typename... Args>
-T &Stage::add_system(Args &&... args)
+inline T &Stage::add_system(Args &&... args)
 {
        systems.emplace_back(std::make_unique<T>(*this, std::forward<Args>(args)...));
        return static_cast<T &>(*systems.back());
 }
 
+template<typename T>
+inline T *Stage::get_system() const
+{
+       for(const auto &s: systems)
+               if(T *ts = dynamic_cast<T *>(s.get()))
+                       return ts;
+       return nullptr;
+}
+
 } // namespace Msp::Game
 
 #endif