]> git.tdb.fi Git - libs/game.git/blob - source/game/owned.h
Make the parent handle in Owned templated
[libs/game.git] / source / game / owned.h
1 #ifndef MSP_GAME_OWNED_H_
2 #define MSP_GAME_OWNED_H_
3
4 #include <stdexcept>
5 #include "handle.h"
6 #include "stage.h"
7
8 namespace Msp::Game {
9
10 class Component;
11 class Entity;
12
13 template<typename T>
14 class Owned: public Handle<T>
15 {
16 public:
17         Owned() = default;
18
19         template<typename P, typename... Args>
20         Owned(Handle<P>, Args &&...);
21
22         template<typename P, typename... Args>
23         Owned(P &parent, Args &&... args): Owned(Handle<P>::from_object(&parent), std::forward<Args>(args)...) { }
24
25         Owned(Owned &&other): Handle<T>(other) { other.ptr = nullptr; }
26         Owned &operator=(Owned &&other);
27         ~Owned() { destroy(); }
28
29 private:
30         template<typename O>
31         static Stage &get_stage(O &);
32
33         void destroy();
34 };
35
36
37 template<typename T>
38 template<typename P, typename... Args>
39 Owned<T>::Owned(Handle<P> parent, Args &&... args)
40 {
41         if(!parent)
42                 throw std::invalid_argument("Owned::Owned");
43
44         Pool<T> &pool = get_stage(*parent).get_pools().template get_pool<T>();
45         this->ptr = pool.create(parent, std::forward<Args>(args)...);
46         if constexpr(std::is_base_of_v<Component, T>)
47                 parent->add_component(*this);
48         else
49                 parent->add_child(*this);
50 }
51
52 template<typename T>
53 Owned<T> &Owned<T>::operator=(Owned &&other)
54 {
55         destroy();
56
57         this->ptr = other.ptr;
58         other.ptr = nullptr;
59
60         return *this;
61 }
62
63 template<typename T>
64 template<typename O>
65 Stage &Owned<T>::get_stage(O &obj)
66 {
67         if constexpr(std::is_base_of_v<Component, O>)
68                 return get_stage(*obj.get_entity());
69         else
70                 return obj.get_stage();
71 }
72
73 template<typename T>
74 void Owned<T>::destroy()
75 {
76         T *obj = this->get();
77         if(!obj)
78                 return;
79
80         Pool<T> &pool = get_stage(*obj).get_pools().template get_pool<T>();
81
82         if constexpr(std::is_base_of_v<Component, T>)
83                 obj->get_entity()->remove_component(*this);
84         else if(auto parent = obj->get_parent().get())
85                 parent->remove_child(*this);
86
87         pool.destroy(this->ptr);
88 }
89
90 } // namespace Msp::Game
91
92 #endif