]> git.tdb.fi Git - libs/game.git/blob - source/game/entity.h
Provide a way to request events for existing entities and components
[libs/game.git] / source / game / entity.h
1 #ifndef MSP_GAME_ENTITY_H_
2 #define MSP_GAME_ENTITY_H_
3
4 #include "handle.h"
5 #include "owned.h"
6
7 namespace Msp::Game {
8
9 class Component;
10 class Stage;
11 class Transform;
12 struct TransformValues;
13
14 class hierarchy_error: public std::logic_error
15 {
16 public:
17         hierarchy_error(): std::logic_error("hierarchy error") { }
18 };
19
20 class Entity
21 {
22 public:
23         enum TransformTag { NO_TRANSFORM };
24
25 private:
26         Handle<Entity> parent;
27         std::vector<Handle<Component>> components;
28         std::vector<Handle<Entity>> children;
29         Owned<Transform> transform;
30
31 public:
32         Entity(Handle<Entity>, TransformTag);
33         Entity(Handle<Entity>, const TransformValues &);
34         virtual ~Entity();
35
36         void add_component(Handle<Component>);
37         void remove_component(Handle<Component>);
38         const std::vector<Handle<Component>> &get_components() const { return components; }
39
40         template<typename T>
41         Handle<T> get_component();
42
43         Handle<Transform> get_transform() const { return transform; }
44
45         void add_child(Handle<Entity>);
46         void remove_child(Handle<Entity>);
47
48         Handle<Entity> get_parent() const { return parent; }
49         Handle<Entity> get_root();
50         const std::vector<Handle<Entity>> &get_children() const { return children; }
51         Stage &get_stage();
52 };
53
54
55 template<typename T>
56 inline Handle<T> Entity::get_component()
57 {
58         for(Handle<Component> c: components)
59                 if(Handle<T> tc = dynamic_handle_cast<T>(c))
60                         return tc;
61         return nullptr;
62 }
63
64 inline Handle<Entity> Entity::get_root()
65 {
66         Handle<Entity> e = Handle<Entity>::from_object(this);
67         while(Handle<Entity> p = e->get_parent())
68                 e = p;
69         return e;
70 }
71
72 } // namespace Msp::Game
73
74 #endif