Object.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  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. virtual Atomic::ClassID GetClassID() const { return GetClassIDStatic(); } \
  39. static Atomic::ClassID GetClassIDStatic() { static const int typeID = 0; return (Atomic::ClassID) &typeID; }
  40. #define BASEOBJECT(typeName) \
  41. public: \
  42. static Atomic::StringHash GetBaseTypeStatic() { static const Atomic::StringHash baseTypeStatic(#typeName); return baseTypeStatic; } \
  43. /// Base class for objects with type identification, subsystem access and event sending/receiving capability.
  44. class ATOMIC_API Object : public RefCounted
  45. {
  46. BASEOBJECT(Object);
  47. friend class Context;
  48. public:
  49. /// Construct.
  50. Object(Context* context);
  51. /// Destruct. Clean up self from event sender & receiver structures.
  52. virtual ~Object();
  53. /// Return type hash.
  54. virtual Atomic::StringHash GetType() const = 0;
  55. /// Return base class type hash.
  56. virtual Atomic::StringHash GetBaseType() const = 0;
  57. /// Return type name.
  58. virtual const Atomic::String& GetTypeName() const = 0;
  59. /// Handle event.
  60. virtual void OnEvent(Object* sender, StringHash eventType, VariantMap& eventData);
  61. /// Subscribe to an event that can be sent by any sender.
  62. void SubscribeToEvent(StringHash eventType, EventHandler* handler);
  63. /// Subscribe to a specific sender's event.
  64. void SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler);
  65. /// Unsubscribe from an event.
  66. void UnsubscribeFromEvent(StringHash eventType);
  67. /// Unsubscribe from a specific sender's event.
  68. void UnsubscribeFromEvent(Object* sender, StringHash eventType);
  69. /// Unsubscribe from a specific sender's events.
  70. void UnsubscribeFromEvents(Object* sender);
  71. /// Unsubscribe from all events.
  72. void UnsubscribeFromAllEvents();
  73. /// Unsubscribe from all events except those listed, and optionally only those with userdata (script registered events.)
  74. void UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData);
  75. /// Send event to all subscribers.
  76. void SendEvent(StringHash eventType);
  77. /// Send event with parameters to all subscribers.
  78. void SendEvent(StringHash eventType, VariantMap& eventData);
  79. /// Return a preallocated map for event data. Used for optimization to avoid constant re-allocation of event data maps.
  80. VariantMap& GetEventDataMap() const;
  81. /// Return execution context.
  82. Context* GetContext() const { return context_; }
  83. /// Return subsystem by type.
  84. Object* GetSubsystem(StringHash type) const;
  85. /// Return active event sender. Null outside event handling.
  86. Object* GetEventSender() const;
  87. /// Return active event handler. Null outside event handling.
  88. EventHandler* GetEventHandler() const;
  89. /// Return whether has subscribed to an event without specific sender.
  90. bool HasSubscribedToEvent(StringHash eventType) const;
  91. /// Return whether has subscribed to a specific sender's event.
  92. bool HasSubscribedToEvent(Object* sender, StringHash eventType) const;
  93. /// Return whether has subscribed to any event.
  94. bool HasEventHandlers() const { return !eventHandlers_.Empty(); }
  95. /// Template version of returning a subsystem.
  96. template <class T> T* GetSubsystem() const;
  97. /// Return object category. Categories are (optionally) registered along with the object factory. Return an empty string if the object category is not registered.
  98. const String& GetCategory() const;
  99. virtual bool IsObject() const { return true; }
  100. static ClassID GetClassIDStatic() { static const int typeID = 0; return (ClassID) &typeID; }
  101. static const Atomic::String& GetTypeNameStatic() { static const Atomic::String typeNameStatic("Object"); return typeNameStatic; }
  102. protected:
  103. /// Execution context.
  104. Context* context_;
  105. private:
  106. /// Find the first event handler with no specific sender.
  107. EventHandler* FindEventHandler(StringHash eventType, EventHandler** previous = 0) const;
  108. /// Find the first event handler with specific sender.
  109. EventHandler* FindSpecificEventHandler(Object* sender, EventHandler** previous = 0) const;
  110. /// Find the first event handler with specific sender and event type.
  111. EventHandler* FindSpecificEventHandler(Object* sender, StringHash eventType, EventHandler** previous = 0) const;
  112. /// Remove event handlers related to a specific sender.
  113. void RemoveEventSender(Object* sender);
  114. /// Event handlers. Sender is null for non-specific handlers.
  115. LinkedList<EventHandler> eventHandlers_;
  116. };
  117. template <class T> T* Object::GetSubsystem() const { return static_cast<T*>(GetSubsystem(T::GetTypeStatic())); }
  118. /// Base class for object factories.
  119. class ATOMIC_API ObjectFactory : public RefCounted
  120. {
  121. REFCOUNTED(ObjectFactory)
  122. public:
  123. /// Construct.
  124. ObjectFactory(Context* context) :
  125. context_(context)
  126. {
  127. assert(context_);
  128. }
  129. /// Create an object. Implemented in templated subclasses.
  130. virtual SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY) = 0;
  131. /// Return execution context.
  132. Context* GetContext() const { return context_; }
  133. /// Return type hash of objects created by this factory.
  134. StringHash GetType() const { return type_; }
  135. /// Return base type hash of objects created by this factory.
  136. StringHash GetBaseType() const { return baseType_; }
  137. /// Return type name of objects created by this factory.
  138. const String& GetTypeName() const { return typeName_; }
  139. protected:
  140. /// Execution context.
  141. Context* context_;
  142. /// Object type.
  143. StringHash type_;
  144. /// Object base type.
  145. StringHash baseType_;
  146. /// Object type name.
  147. String typeName_;
  148. };
  149. /// Template implementation of the object factory.
  150. template <class T> class ObjectFactoryImpl : public ObjectFactory
  151. {
  152. public:
  153. /// Construct.
  154. ObjectFactoryImpl(Context* context) :
  155. ObjectFactory(context)
  156. {
  157. type_ = T::GetTypeStatic();
  158. baseType_ = T::GetBaseTypeStatic();
  159. typeName_ = T::GetTypeNameStatic();
  160. }
  161. /// Create an object of the specific type.
  162. virtual SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY) { return SharedPtr<Object>(new T(context_)); }
  163. };
  164. /// Internal helper class for invoking event handler functions.
  165. class ATOMIC_API EventHandler : public LinkedListNode
  166. {
  167. public:
  168. /// Construct with specified receiver.
  169. EventHandler(Object* receiver) :
  170. receiver_(receiver),
  171. sender_(0),
  172. userData_(0)
  173. {
  174. assert(receiver_);
  175. }
  176. /// Construct with specified receiver and userdata.
  177. EventHandler(Object* receiver, void* userData) :
  178. receiver_(receiver),
  179. sender_(0),
  180. userData_(userData)
  181. {
  182. assert(receiver_);
  183. }
  184. /// Destruct.
  185. virtual ~EventHandler() { }
  186. /// Set sender and event type.
  187. void SetSenderAndEventType(Object* sender, StringHash eventType)
  188. {
  189. sender_ = sender;
  190. eventType_ = eventType;
  191. }
  192. /// Invoke event handler function.
  193. virtual void Invoke(VariantMap& eventData) = 0;
  194. /// Return a unique copy of the event handler.
  195. virtual EventHandler* Clone() const = 0;
  196. /// Return event receiver.
  197. Object* GetReceiver() const { return receiver_; }
  198. /// Return event sender. Null if the handler is non-specific.
  199. Object* GetSender() const { return sender_; }
  200. /// Return event type.
  201. const StringHash& GetEventType() const { return eventType_; }
  202. /// Return userdata.
  203. void* GetUserData() const { return userData_; }
  204. protected:
  205. /// Event receiver.
  206. Object* receiver_;
  207. /// Event sender.
  208. Object* sender_;
  209. /// Event type.
  210. StringHash eventType_;
  211. /// Userdata.
  212. void* userData_;
  213. };
  214. /// Template implementation of the event handler invoke helper (stores a function pointer of specific class.)
  215. template <class T> class EventHandlerImpl : public EventHandler
  216. {
  217. public:
  218. typedef void (T::*HandlerFunctionPtr)(StringHash, VariantMap&);
  219. /// Construct with receiver and function pointers.
  220. EventHandlerImpl(T* receiver, HandlerFunctionPtr function) :
  221. EventHandler(receiver),
  222. function_(function)
  223. {
  224. assert(function_);
  225. }
  226. /// Construct with receiver and function pointers and userdata.
  227. EventHandlerImpl(T* receiver, HandlerFunctionPtr function, void* userData) :
  228. EventHandler(receiver, userData),
  229. function_(function)
  230. {
  231. assert(function_);
  232. }
  233. /// Invoke event handler function.
  234. virtual void Invoke(VariantMap& eventData)
  235. {
  236. T* receiver = static_cast<T*>(receiver_);
  237. (receiver->*function_)(eventType_, eventData);
  238. }
  239. /// Return a unique copy of the event handler.
  240. virtual EventHandler* Clone() const
  241. {
  242. return new EventHandlerImpl(static_cast<T*>(receiver_), function_, userData_);
  243. }
  244. private:
  245. /// Class-specific pointer to handler function.
  246. HandlerFunctionPtr function_;
  247. };
  248. /// Describe an event's hash ID and begin a namespace in which to define its parameters.
  249. #define EVENT(eventID, eventName) static const Atomic::StringHash eventID(#eventName); namespace eventName
  250. /// Describe an event's parameter hash ID. Should be used inside an event namespace.
  251. #define PARAM(paramID, paramName) static const Atomic::StringHash paramID(#paramName)
  252. /// Convenience macro to construct an EventHandler that points to a receiver object and its member function.
  253. #define HANDLER(className, function) (new Atomic::EventHandlerImpl<className>(this, &className::function))
  254. /// Convenience macro to construct an EventHandler that points to a receiver object and its member function, and also defines a userdata pointer.
  255. #define HANDLER_USERDATA(className, function, userData) (new Atomic::EventHandlerImpl<className>(this, &className::function, userData))
  256. }