Object.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  1. //
  2. // Copyright (c) 2008-2017 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. // ATOMIC BEGIN
  26. #include "../Resource/XMLElement.h"
  27. // ATOMIC END
  28. #if ATOMIC_CXX11
  29. #include <functional>
  30. #endif
  31. namespace Atomic
  32. {
  33. class Context;
  34. class EventHandler;
  35. /// Type info.
  36. class ATOMIC_API TypeInfo
  37. {
  38. public:
  39. /// Construct.
  40. TypeInfo(const char* typeName, const TypeInfo* baseTypeInfo);
  41. /// Destruct.
  42. ~TypeInfo();
  43. /// Check current type is type of specified type.
  44. bool IsTypeOf(StringHash type) const;
  45. /// Check current type is type of specified type.
  46. bool IsTypeOf(const TypeInfo* typeInfo) const;
  47. /// Check current type is type of specified class type.
  48. template<typename T> bool IsTypeOf() const { return IsTypeOf(T::GetTypeInfoStatic()); }
  49. /// Return type.
  50. StringHash GetType() const { return type_; }
  51. /// Return type name.
  52. const String& GetTypeName() const { return typeName_;}
  53. /// Return base type info.
  54. const TypeInfo* GetBaseTypeInfo() const { return baseTypeInfo_; }
  55. private:
  56. /// Type.
  57. StringHash type_;
  58. /// Type name.
  59. String typeName_;
  60. /// Base class type info.
  61. const TypeInfo* baseTypeInfo_;
  62. };
  63. #define ATOMIC_OBJECT(typeName, baseTypeName) \
  64. public: \
  65. typedef typeName ClassName; \
  66. typedef baseTypeName BaseClassName; \
  67. virtual Atomic::StringHash GetType() const { return GetTypeInfoStatic()->GetType(); } \
  68. virtual const Atomic::String& GetTypeName() const { return GetTypeInfoStatic()->GetTypeName(); } \
  69. virtual const Atomic::TypeInfo* GetTypeInfo() const { return GetTypeInfoStatic(); } \
  70. static Atomic::StringHash GetTypeStatic() { return GetTypeInfoStatic()->GetType(); } \
  71. static const Atomic::String& GetTypeNameStatic() { return GetTypeInfoStatic()->GetTypeName(); } \
  72. static const Atomic::TypeInfo* GetTypeInfoStatic() { static const Atomic::TypeInfo typeInfoStatic(#typeName, BaseClassName::GetTypeInfoStatic()); return &typeInfoStatic; } \
  73. virtual Atomic::StringHash GetBaseType() const { return GetBaseTypeStatic(); } \
  74. virtual Atomic::ClassID GetClassID() const { return GetClassIDStatic(); } \
  75. static Atomic::ClassID GetClassIDStatic() { static const int typeID = 0; return (Atomic::ClassID) &typeID; } \
  76. static Atomic::StringHash GetBaseTypeStatic() { static const Atomic::StringHash baseTypeStatic(#baseTypeName); return baseTypeStatic; }
  77. /// Base class for objects with type identification, subsystem access and event sending/receiving capability.
  78. class ATOMIC_API Object : public RefCounted
  79. {
  80. friend class Context;
  81. public:
  82. /// Construct.
  83. Object(Context* context);
  84. /// Destruct. Clean up self from event sender & receiver structures.
  85. virtual ~Object();
  86. /// Return type hash.
  87. virtual StringHash GetType() const = 0;
  88. /// Return type name.
  89. virtual const String& GetTypeName() const = 0;
  90. /// Return type info.
  91. virtual const TypeInfo* GetTypeInfo() const = 0;
  92. /// Handle event.
  93. virtual void OnEvent(Object* sender, StringHash eventType, VariantMap& eventData);
  94. /// Return type info static.
  95. static const TypeInfo* GetTypeInfoStatic() { return 0; }
  96. /// Check current type is type of specified type.
  97. static bool IsTypeOf(StringHash type);
  98. /// Check current type is type of specified type.
  99. static bool IsTypeOf(const TypeInfo* typeInfo);
  100. /// Check current type is type of specified class.
  101. template<typename T> static bool IsTypeOf() { return IsTypeOf(T::GetTypeInfoStatic()); }
  102. /// Check current instance is type of specified type.
  103. bool IsInstanceOf(StringHash type) const;
  104. /// Check current instance is type of specified type.
  105. bool IsInstanceOf(const TypeInfo* typeInfo) const;
  106. /// Check current instance is type of specified class.
  107. template<typename T> bool IsInstanceOf() const { return IsInstanceOf(T::GetTypeInfoStatic()); }
  108. /// Subscribe to an event that can be sent by any sender.
  109. void SubscribeToEvent(StringHash eventType, EventHandler* handler);
  110. /// Subscribe to a specific sender's event.
  111. void SubscribeToEvent(Object* sender, StringHash eventType, EventHandler* handler);
  112. #ifdef ATOMIC_CXX11
  113. /// Subscribe to an event that can be sent by any sender.
  114. void SubscribeToEvent(StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=0);
  115. /// Subscribe to a specific sender's event.
  116. void SubscribeToEvent(Object* sender, StringHash eventType, const std::function<void(StringHash, VariantMap&)>& function, void* userData=0);
  117. #endif
  118. /// Unsubscribe from an event.
  119. void UnsubscribeFromEvent(StringHash eventType);
  120. /// Unsubscribe from a specific sender's event.
  121. void UnsubscribeFromEvent(Object* sender, StringHash eventType);
  122. /// Unsubscribe from a specific sender's events.
  123. void UnsubscribeFromEvents(Object* sender);
  124. /// Unsubscribe from all events.
  125. void UnsubscribeFromAllEvents();
  126. /// Unsubscribe from all events except those listed, and optionally only those with userdata (script registered events.)
  127. void UnsubscribeFromAllEventsExcept(const PODVector<StringHash>& exceptions, bool onlyUserData);
  128. /// Send event to all subscribers.
  129. void SendEvent(StringHash eventType);
  130. /// Send event with parameters to all subscribers.
  131. void SendEvent(StringHash eventType, VariantMap& eventData);
  132. /// Return a preallocated map for event data. Used for optimization to avoid constant re-allocation of event data maps.
  133. VariantMap& GetEventDataMap() const;
  134. #if ATOMIC_CXX11
  135. /// Send event with variadic parameter pairs to all subscribers. The parameter pairs is a list of paramID and paramValue separated by comma, one pair after another.
  136. template <typename... Args> void SendEvent(StringHash eventType, Args... args)
  137. {
  138. SendEvent(eventType, GetEventDataMap().Populate(args...));
  139. }
  140. #endif
  141. /// Return execution context.
  142. Context* GetContext() const { return context_; }
  143. /// Return global variable based on key
  144. const Variant& GetGlobalVar(StringHash key) const;
  145. /// Return all global variables
  146. const VariantMap& GetGlobalVars() const;
  147. /// Set global variable with the respective key and value
  148. void SetGlobalVar(StringHash key, const Variant& value);
  149. /// Return subsystem by type.
  150. Object* GetSubsystem(StringHash type) const;
  151. /// Return active event sender. Null outside event handling.
  152. Object* GetEventSender() const;
  153. /// Return active event handler. Null outside event handling.
  154. EventHandler* GetEventHandler() const;
  155. /// Return whether has subscribed to an event without specific sender.
  156. bool HasSubscribedToEvent(StringHash eventType) const;
  157. /// Return whether has subscribed to a specific sender's event.
  158. bool HasSubscribedToEvent(Object* sender, StringHash eventType) const;
  159. /// Return whether has subscribed to any event.
  160. bool HasEventHandlers() const { return !eventHandlers_.Empty(); }
  161. /// Template version of returning a subsystem.
  162. template <class T> T* GetSubsystem() const;
  163. /// Return object category. Categories are (optionally) registered along with the object factory. Return an empty string if the object category is not registered.
  164. const String& GetCategory() const;
  165. // ATOMIC BEGIN
  166. virtual bool IsObject() const { return true; }
  167. /// Unsubscribe from event for specific receiver (where the event handler isn't necessarily in the subscribed object)
  168. void UnsubscribeFromEventReceiver(Object* receiver);
  169. static ClassID GetClassIDStatic() { static const int typeID = 0; return (ClassID) &typeID; }
  170. static const Atomic::String& GetTypeNameStatic() { static const Atomic::String typeNameStatic("Object"); return typeNameStatic; }
  171. // ATOMIC END
  172. protected:
  173. /// Execution context.
  174. Context* context_;
  175. private:
  176. /// Find the first event handler with no specific sender.
  177. EventHandler* FindEventHandler(StringHash eventType, EventHandler** previous = 0) const;
  178. /// Find the first event handler with specific sender.
  179. EventHandler* FindSpecificEventHandler(Object* sender, EventHandler** previous = 0) const;
  180. /// Find the first event handler with specific sender and event type.
  181. EventHandler* FindSpecificEventHandler(Object* sender, StringHash eventType, EventHandler** previous = 0) const;
  182. /// Remove event handlers related to a specific sender.
  183. void RemoveEventSender(Object* sender);
  184. /// Event handlers. Sender is null for non-specific handlers.
  185. LinkedList<EventHandler> eventHandlers_;
  186. };
  187. template <class T> T* Object::GetSubsystem() const { return static_cast<T*>(GetSubsystem(T::GetTypeStatic())); }
  188. /// Base class for object factories.
  189. class ATOMIC_API ObjectFactory : public RefCounted
  190. {
  191. ATOMIC_REFCOUNTED(ObjectFactory)
  192. public:
  193. /// Construct.
  194. ObjectFactory(Context* context) :
  195. context_(context)
  196. {
  197. assert(context_);
  198. }
  199. // ATOMIC BEGIN
  200. /// Create an object. Implemented in templated subclasses.
  201. virtual SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY) = 0;
  202. // ATOMIC END
  203. /// Return execution context.
  204. Context* GetContext() const { return context_; }
  205. /// Return type info of objects created by this factory.
  206. const TypeInfo* GetTypeInfo() const { return typeInfo_; }
  207. /// Return type hash of objects created by this factory.
  208. StringHash GetType() const { return typeInfo_->GetType(); }
  209. // ATOMIC BEGIN
  210. // RefCounted in Atomic carry typename with GetTypeName, so renamed to GetFactoryType
  211. /// Return type name of objects created by this factory.
  212. const String& GetFactoryTypeName() const { return typeInfo_->GetTypeName(); }
  213. // ATOMIC END
  214. protected:
  215. /// Execution context.
  216. Context* context_;
  217. /// Type info.
  218. const TypeInfo* typeInfo_;
  219. };
  220. /// Template implementation of the object factory.
  221. template <class T> class ObjectFactoryImpl : public ObjectFactory
  222. {
  223. public:
  224. /// Construct.
  225. ObjectFactoryImpl(Context* context) :
  226. ObjectFactory(context)
  227. {
  228. typeInfo_ = T::GetTypeInfoStatic();
  229. }
  230. // ATOMIC BEGIN
  231. /// Create an object of the specific type.
  232. virtual SharedPtr<Object> CreateObject(const XMLElement& source = XMLElement::EMPTY) { return SharedPtr<Object>(new T(context_)); }
  233. // ATOMIC END
  234. };
  235. /// Internal helper class for invoking event handler functions.
  236. class ATOMIC_API EventHandler : public LinkedListNode
  237. {
  238. public:
  239. /// Construct with specified receiver and userdata.
  240. EventHandler(Object* receiver, void* userData = 0) :
  241. receiver_(receiver),
  242. sender_(0),
  243. userData_(userData)
  244. {
  245. }
  246. /// Destruct.
  247. virtual ~EventHandler() { }
  248. /// Set sender and event type.
  249. void SetSenderAndEventType(Object* sender, StringHash eventType)
  250. {
  251. sender_ = sender;
  252. eventType_ = eventType;
  253. }
  254. /// Invoke event handler function.
  255. virtual void Invoke(VariantMap& eventData) = 0;
  256. /// Return a unique copy of the event handler.
  257. virtual EventHandler* Clone() const = 0;
  258. /// Return event receiver.
  259. Object* GetReceiver() const { return receiver_; }
  260. /// Return event sender. Null if the handler is non-specific.
  261. Object* GetSender() const { return sender_; }
  262. /// Return event type.
  263. const StringHash& GetEventType() const { return eventType_; }
  264. /// Return userdata.
  265. void* GetUserData() const { return userData_; }
  266. protected:
  267. /// Event receiver.
  268. Object* receiver_;
  269. /// Event sender.
  270. Object* sender_;
  271. /// Event type.
  272. StringHash eventType_;
  273. /// Userdata.
  274. void* userData_;
  275. };
  276. /// Template implementation of the event handler invoke helper (stores a function pointer of specific class.)
  277. template <class T> class EventHandlerImpl : public EventHandler
  278. {
  279. public:
  280. typedef void (T::*HandlerFunctionPtr)(StringHash, VariantMap&);
  281. /// Construct with receiver and function pointers and userdata.
  282. EventHandlerImpl(T* receiver, HandlerFunctionPtr function, void* userData = 0) :
  283. EventHandler(receiver, userData),
  284. function_(function)
  285. {
  286. assert(receiver_);
  287. assert(function_);
  288. }
  289. /// Invoke event handler function.
  290. virtual void Invoke(VariantMap& eventData)
  291. {
  292. T* receiver = static_cast<T*>(receiver_);
  293. (receiver->*function_)(eventType_, eventData);
  294. }
  295. /// Return a unique copy of the event handler.
  296. virtual EventHandler* Clone() const
  297. {
  298. return new EventHandlerImpl(static_cast<T*>(receiver_), function_, userData_);
  299. }
  300. private:
  301. /// Class-specific pointer to handler function.
  302. HandlerFunctionPtr function_;
  303. };
  304. #if ATOMIC_CXX11
  305. /// Template implementation of the event handler invoke helper (std::function instance).
  306. class EventHandler11Impl : public EventHandler
  307. {
  308. public:
  309. /// Construct with receiver and function pointers and userdata.
  310. EventHandler11Impl(std::function<void(StringHash, VariantMap&)> function, void* userData = 0) :
  311. EventHandler(0, userData),
  312. function_(function)
  313. {
  314. assert(function_);
  315. }
  316. /// Invoke event handler function.
  317. virtual void Invoke(VariantMap& eventData)
  318. {
  319. function_(eventType_, eventData);
  320. }
  321. /// Return a unique copy of the event handler.
  322. virtual EventHandler* Clone() const
  323. {
  324. return new EventHandler11Impl(function_, userData_);
  325. }
  326. private:
  327. /// Class-specific pointer to handler function.
  328. std::function<void(StringHash, VariantMap&)> function_;
  329. };
  330. #endif
  331. /// Register event names.
  332. struct ATOMIC_API EventNameRegistrar
  333. {
  334. /// Register an event name for hash reverse mapping.
  335. static StringHash RegisterEventName(const char* eventName);
  336. /// Return Event name or empty string if not found.
  337. static const String& GetEventName(StringHash eventID);
  338. /// Return Event name map.
  339. static HashMap<StringHash, String>& GetEventNameMap();
  340. };
  341. /// Describe an event's hash ID and begin a namespace in which to define its parameters.
  342. #define ATOMIC_EVENT(eventID, eventName) static const Atomic::StringHash eventID(Atomic::EventNameRegistrar::RegisterEventName(#eventName)); namespace eventName
  343. /// Describe an event's parameter hash ID. Should be used inside an event namespace.
  344. #define ATOMIC_PARAM(paramID, paramName) static const Atomic::StringHash paramID(#paramName)
  345. /// Convenience macro to construct an EventHandler that points to a receiver object and its member function.
  346. #define ATOMIC_HANDLER(className, function) (new Atomic::EventHandlerImpl<className>(this, &className::function))
  347. /// Convenience macro to construct an EventHandler that points to a receiver object and its member function, and also defines a userdata pointer.
  348. #define ATOMIC_HANDLER_USERDATA(className, function, userData) (new Atomic::EventHandlerImpl<className>(this, &className::function, userData))
  349. }