1 #ifndef MSP_GAME_OWNED_H_
2 #define MSP_GAME_OWNED_H_
15 class Owned: public Handle<T>
20 template<typename... Args>
21 Owned(Handle<Entity>, Args &&...);
23 template<typename... Args>
24 Owned(Entity &parent, Args &&... args): Owned(Handle<Entity>::from_object(&parent), std::forward<Args>(args)...) { }
26 Owned(Owned &&other): Handle<T>(other) { other.ptr = nullptr; }
27 Owned &operator=(Owned &&other);
28 ~Owned() { destroy(); }
32 static Stage &get_stage(O &);
39 template<typename... Args>
40 Owned<T>::Owned(Handle<Entity> parent, Args &&... args)
43 throw std::invalid_argument("Owned::Owned");
45 using DependentEntity = std::conditional_t<sizeof(T), Entity, Entity>;
46 Handle<DependentEntity> dparent = parent;
48 Pool<T> &pool = get_stage(*dparent).get_pools().template get_pool<T>();
49 this->ptr = pool.create(parent, std::forward<Args>(args)...);
50 if constexpr(std::is_base_of_v<Component, T>)
51 dparent->add_component(*this);
53 dparent->add_child(*this);
57 Owned<T> &Owned<T>::operator=(Owned &&other)
61 this->ptr = other.ptr;
69 Stage &Owned<T>::get_stage(O &obj)
71 using DependentRoot = std::conditional_t<sizeof(T), Root, Root>;
72 if constexpr(std::is_base_of_v<Component, O>)
73 return get_stage(*obj.get_entity());
74 else if constexpr(std::is_base_of_v<Entity, O>)
75 return dynamic_cast<DependentRoot &>(*obj.get_root()).get_stage();
81 void Owned<T>::destroy()
87 Pool<T> &pool = get_stage(*obj).get_pools().template get_pool<T>();
89 if constexpr(std::is_base_of_v<Component, T>)
90 obj->get_entity()->remove_component(*this);
91 else if(auto parent = obj->get_parent().get())
92 parent->remove_child(*this);
94 pool.destroy(this->ptr);
97 } // namespace Msp::Game