Object.h 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //
  2. // Copyright (c) 2008-2015 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "../Container/LinkedList.h"
  24. #include "../Core/Variant.h"
  25. #include "../Resource/XMLElement.h"
  26. namespace Atomic
  27. {
  28. class Context;
  29. class EventHandler;
  30. #define OBJECT(typeName) \
  31. public: \
  32. typedef typeName ClassName; \
  33. virtual Atomic::StringHash GetType() const { return GetTypeStatic(); } \
  34. virtual Atomic::StringHash GetBaseType() const { return GetBaseTypeStatic(); } \
  35. virtual const Atomic::String& GetTypeName() const { return GetTypeNameStatic(); } \
  36. static Atomic::StringHash GetTypeStatic() { static const Atomic::StringHash typeStatic(#typeName); return typeStatic; } \
  37. static const Atomic::String& GetTypeNameStatic() { static const Atomic::String typeNameStatic(#typeName); return typeNameStatic; } \
  38. #define BASEOBJECT(typeName) \
  39. public: \
  40. static Atomic::StringHash GetBaseTypeStatic() { static const Atomic::StringHash baseTypeStatic(#typeName); return baseTypeStatic; } \
  41. /// Base class for objects with type identification, subsystem access and event sending/receiving capability.
  42. class ATOMIC_API Object : public RefCounted
  43. {
  44. BASEOBJECT(Object);
  45. friend class Context;
  46. public:
  47. /// Construct.
  48. Object(Context* context);
  49. /// Destruct. Clean up self from event sender & receiver structures.
  50. virtual ~Object();
  51. /// Return type hash.
  52. virtual Atomic::StringHash GetType() const = 0;
  53. /// Return base class type hash.
  54. virtual Atomic::StringHash GetBaseType() const = 0;
  55. /// Return type name.
  56. virtual const Atomic::String& GetTypeName() const = 0;
  57. /// Handle event.
  58. virtual void OnEvent(Object* sender, StringHash eventType, VariantMap& eventData);
  59. /// Subscribe to an event that can be sent by any sender.
  60. void SubscribeToEvent(StringHash eventType, EventHandler* handler);
  61. /// Subscribe to a specific sender's event.
  62. void SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler);
  63. /// Unsubscribe from an event.
  64. void UnsubscribeFromEvent(StringHash eventType);
  65. /// Unsubscribe from a specific sender's event.
  66. void UnsubscribeFromEvent(Object* sender, StringHash eventType);
  67. /// Unsubscribe from a specific sender's events.
  68. void UnsubscribeFromEvents(Object* sender);
  69. /// Unsubscribe from all events.
  70. void UnsubscribeFromAllEvents();
  71. /// Unsubscribe from all events except those listed, and optionally only those with userdata (script registered events.)
  72. void UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData);
  73. /// Send event to all subscribers.
  74. void SendEvent(StringHash eventType);
  75. /// Send event with parameters to all subscribers.
  76. void SendEvent(StringHash eventType, VariantMap& eventData);
  77. /// Return a preallocated map for event data. Used for optimization to avoid constant re-allocation of event data maps.
  78. VariantMap& GetEventDataMap() const;
  79. /// Return execution context.
  80. Context* GetContext() const { return context_; }
  81. /// Return subsystem by type.
  82. Object* GetSubsystem(StringHash type) const;
  83. /// Return active event sender. Null outside event handling.
  84. Object* GetEventSender() const;
  85. /// Return active event handler. Null outside event handling.
  86. EventHandler* GetEventHandler() const;
  87. /// Return whether has subscribed to an event without specific sender.
  88. bool HasSubscribedToEvent(StringHash eventType) const;
  89. /// Return whether has subscribed to a specific sender's event.
  90. bool HasSubscribedToEvent(Object* sender, StringHash eventType) const;
  91. /// Return whether has subscribed to any event.
  92. bool HasEventHandlers() const { return !eventHandlers_.Empty(); }
  93. /// Template version of returning a subsystem.
  94. template <class T> T* GetSubsystem() const;
  95. /// Return object category. Categories are (optionally) registered along with the object factory. Return an empty string if the object category is not registered.
  96. const String& GetCategory() const;
  97. virtual bool IsObject() const { return true; }
  98. static const Atomic::String& GetTypeNameStatic() { static const Atomic::String typeNameStatic("Object"); return typeNameStatic; }
  99. protected:
  100. /// Execution context.
  101. Context* context_;
  102. private:
  103. /// Find the first event handler with no specific sender.
  104. EventHandler* FindEventHandler(StringHash eventType, EventHandler** previous = 0) const;
  105. /// Find the first event handler with specific sender.
  106. EventHandler* FindSpecificEventHandler(Object* sender, EventHandler** previous = 0) const;
  107. /// Find the first event handler with specific sender and event type.
  108. EventHandler* FindSpecificEventHandler(Object* sender, StringHash eventType, EventHandler** previous = 0) const;
  109. /// Remove event handlers related to a specific sender.
  110. void RemoveEventSender(Object* sender);
  111. /// Event handlers. Sender is null for non-specific handlers.
  112. LinkedList<EventHandler> eventHandlers_;
  113. };
  114. template <class T> T* Object::GetSubsystem() const { return static_cast<T*>(GetSubsystem(T::GetTypeStatic())); }
  115. /// Base class for object factories.
  116. class ATOMIC_API ObjectFactory : public RefCounted
  117. {
  118. public:
  119. /// Construct.
  120. ObjectFactory(Context* context) :
  121. context_(context)
  122. {
  123. assert(context_);
  124. }
  125. /// Create an object. Implemented in templated subclasses.
  126. virtual SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY) = 0;
  127. /// Return execution context.
  128. Context* GetContext() const { return context_; }
  129. /// Return type hash of objects created by this factory.
  130. StringHash GetType() const { return type_; }
  131. /// Return base type hash of objects created by this factory.
  132. StringHash GetBaseType() const { return baseType_; }
  133. /// Return type name of objects created by this factory.
  134. const String& GetTypeName() const { return typeName_; }
  135. protected:
  136. /// Execution context.
  137. Context* context_;
  138. /// Object type.
  139. StringHash type_;
  140. /// Object base type.
  141. StringHash baseType_;
  142. /// Object type name.
  143. String typeName_;
  144. };
  145. /// Template implementation of the object factory.
  146. template <class T> class ObjectFactoryImpl : public ObjectFactory
  147. {
  148. public:
  149. /// Construct.
  150. ObjectFactoryImpl(Context* context) :
  151. ObjectFactory(context)
  152. {
  153. type_ = T::GetTypeStatic();
  154. baseType_ = T::GetBaseTypeStatic();
  155. typeName_ = T::GetTypeNameStatic();
  156. }
  157. /// Create an object of the specific type.
  158. virtual SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY) { return SharedPtr<Object>(new T(context_)); }
  159. };
  160. /// Internal helper class for invoking event handler functions.
  161. class ATOMIC_API EventHandler : public LinkedListNode
  162. {
  163. public:
  164. /// Construct with specified receiver.
  165. EventHandler(Object* receiver) :
  166. receiver_(receiver),
  167. sender_(0),
  168. userData_(0)
  169. {
  170. assert(receiver_);
  171. }
  172. /// Construct with specified receiver and userdata.
  173. EventHandler(Object* receiver, void* userData) :
  174. receiver_(receiver),
  175. sender_(0),
  176. userData_(userData)
  177. {
  178. assert(receiver_);
  179. }
  180. /// Destruct.
  181. virtual ~EventHandler() { }
  182. /// Set sender and event type.
  183. void SetSenderAndEventType(Object* sender, StringHash eventType)
  184. {
  185. sender_ = sender;
  186. eventType_ = eventType;
  187. }
  188. /// Invoke event handler function.
  189. virtual void Invoke(VariantMap& eventData) = 0;
  190. /// Return a unique copy of the event handler.
  191. virtual EventHandler* Clone() const = 0;
  192. /// Return event receiver.
  193. Object* GetReceiver() const { return receiver_; }
  194. /// Return event sender. Null if the handler is non-specific.
  195. Object* GetSender() const { return sender_; }
  196. /// Return event type.
  197. const StringHash& GetEventType() const { return eventType_; }
  198. /// Return userdata.
  199. void* GetUserData() const { return userData_; }
  200. protected:
  201. /// Event receiver.
  202. Object* receiver_;
  203. /// Event sender.
  204. Object* sender_;
  205. /// Event type.
  206. StringHash eventType_;
  207. /// Userdata.
  208. void* userData_;
  209. };
  210. /// Template implementation of the event handler invoke helper (stores a function pointer of specific class.)
  211. template <class T> class EventHandlerImpl : public EventHandler
  212. {
  213. public:
  214. typedef void (T::*HandlerFunctionPtr)(StringHash, VariantMap&);
  215. /// Construct with receiver and function pointers.
  216. EventHandlerImpl(T* receiver, HandlerFunctionPtr function) :
  217. EventHandler(receiver),
  218. function_(function)
  219. {
  220. assert(function_);
  221. }
  222. /// Construct with receiver and function pointers and userdata.
  223. EventHandlerImpl(T* receiver, HandlerFunctionPtr function, void* userData) :
  224. EventHandler(receiver, userData),
  225. function_(function)
  226. {
  227. assert(function_);
  228. }
  229. /// Invoke event handler function.
  230. virtual void Invoke(VariantMap& eventData)
  231. {
  232. T* receiver = static_cast<T*>(receiver_);
  233. (receiver->*function_)(eventType_, eventData);
  234. }
  235. /// Return a unique copy of the event handler.
  236. virtual EventHandler* Clone() const
  237. {
  238. return new EventHandlerImpl(static_cast<T*>(receiver_), function_, userData_);
  239. }
  240. private:
  241. /// Class-specific pointer to handler function.
  242. HandlerFunctionPtr function_;
  243. };
  244. /// Describe an event's hash ID and begin a namespace in which to define its parameters.
  245. #define EVENT(eventID, eventName) static const Atomic::StringHash eventID(#eventName); namespace eventName
  246. /// Describe an event's parameter hash ID. Should be used inside an event namespace.
  247. #define PARAM(paramID, paramName) static const Atomic::StringHash paramID(#paramName)
  248. /// Convenience macro to construct an EventHandler that points to a receiver object and its member function.
  249. #define HANDLER(className, function) (new Atomic::EventHandlerImpl<className>(this, &className::function))
  250. /// Convenience macro to construct an EventHandler that points to a receiver object and its member function, and also defines a userdata pointer.
  251. #define HANDLER_USERDATA(className, function, userData) (new Atomic::EventHandlerImpl<className>(this, &className::function, userData))
  252. }