Object.h 15 KB

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