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