1 #ifndef MSP_GAME_OWNED_H_
2 #define MSP_GAME_OWNED_H_
15 class Owned: public Handle<T>
20 template<typename P, typename... Args>
21 Owned(Handle<P>, Args &&...);
23 template<typename P, typename... Args>
24 Owned(P &parent, Args &&... args): Owned(Handle<P>::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 P, typename... Args>
40 Owned<T>::Owned(Handle<P> parent, Args &&... args)
43 throw std::invalid_argument("Owned::Owned");
45 Stage &stage = get_stage(*parent);
46 Pool<T> &pool = stage.get_pools().template get_pool<T>();
47 this->ptr = pool.create(parent, std::forward<Args>(args)...);
48 if constexpr(std::is_base_of_v<Component, T>)
50 parent->add_component(*this);
51 stage.get_event_source().emit<Events::ComponentCreated>(*this);
55 parent->add_child(*this);
56 stage.get_event_source().emit<Events::EntityCreated>(*this);
61 Owned<T> &Owned<T>::operator=(Owned &&other)
65 this->ptr = other.ptr;
73 Stage &Owned<T>::get_stage(O &obj)
75 if constexpr(std::is_base_of_v<Component, O>)
76 return get_stage(*obj.get_entity());
78 return obj.get_stage();
82 void Owned<T>::destroy()
88 Stage &stage = get_stage(*obj);
90 if constexpr(std::is_base_of_v<Component, T>)
92 stage.get_event_source().emit<Events::ComponentDestroyed>(*this);
93 obj->get_entity()->remove_component(*this);
95 else if(auto parent = obj->get_parent().get())
97 stage.get_event_source().emit<Events::EntityDestroyed>(*this);
98 parent->remove_child(*this);
101 Pool<T> &pool = stage.get_pools().template get_pool<T>();
102 pool.destroy(this->ptr);
105 } // namespace Msp::Game