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(Owned<P> &p, Args &&... a): Owned(static_cast<Handle<P> &>(p), std::forward<Args>(a)...) { }
26 template<typename P, typename... Args>
27 requires(!std::is_const_v<P>)
28 Owned(P &parent, Args &&... args): Owned(Handle<P>::from_object(&parent), std::forward<Args>(args)...) { }
30 Owned(Owned &&other): Handle<T>(other) { other.ptr = nullptr; }
31 Owned &operator=(Owned &&other);
32 ~Owned() { destroy(); }
36 static Stage &get_stage(O &);
43 template<typename P, typename... Args>
44 Owned<T>::Owned(Handle<P> parent, Args &&... args)
47 throw std::invalid_argument("Owned::Owned");
49 Stage &stage = get_stage(*parent);
50 Pool<T> &pool = stage.get_pools().get_pool<T>();
51 this->ptr = pool.create(parent, std::forward<Args>(args)...);
52 if constexpr(std::is_base_of_v<Component, T>)
54 parent->add_component(*this);
55 stage.get_event_source().emit<Events::ComponentCreated>(*this);
59 parent->add_child(*this);
60 stage.get_event_source().emit<Events::EntityCreated>(*this);
65 Owned<T> &Owned<T>::operator=(Owned &&other)
69 this->ptr = other.ptr;
77 Stage &Owned<T>::get_stage(O &obj)
79 if constexpr(std::is_base_of_v<Component, O>)
80 return get_stage(*obj.get_entity());
82 return obj.get_stage();
86 void Owned<T>::destroy()
92 Stage &stage = get_stage(*obj);
94 if constexpr(std::is_base_of_v<Component, T>)
96 stage.get_event_source().emit<Events::ComponentDestroyed>(*this);
97 obj->get_entity()->remove_component(*this);
99 else if(auto parent = obj->get_parent().get())
101 stage.get_event_source().emit<Events::EntityDestroyed>(*this);
102 parent->remove_child(*this);
105 Pool<T> &pool = stage.get_pools().get_pool<T>();
106 pool.destroy(this->ptr);
109 } // namespace Msp::Game