BsCoreObject.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #pragma once
  4. #include "BsCorePrerequisites.h"
  5. #include "BsCoreObjectCore.h"
  6. #include "BsAsyncOp.h"
  7. namespace BansheeEngine
  8. {
  9. /** @addtogroup CoreThread
  10. * @{
  11. */
  12. /**
  13. * Core objects provides functionality for dealing with objects that need to exist on both simulation and core thread.
  14. * It handles cross-thread initialization, destruction as well as syncing data between the two threads.
  15. *
  16. * It also provides a standardized way to initialize/destroy objects, and a way to specify dependant CoreObject%s. For
  17. * those purposes it might also be used for objects that only exist on the core thread.
  18. *
  19. * @note CoreObjectCore is a counterpart to CoreObject that is used exclusively on the core thread. CoreObject on the
  20. * other hand should be used exclusively on the simulation thread. Types that exist on both threads need to
  21. * implement both of these.
  22. */
  23. class BS_CORE_EXPORT CoreObject
  24. {
  25. protected:
  26. /** Values that represent current state of the core object */
  27. enum Flags
  28. {
  29. CGO_DESTROYED = 0x01, /**< Object has been destroyed and shouldn't be used. */
  30. CGO_INIT_ON_CORE_THREAD = 0x02 /**< Object requires initialization on core thread. */
  31. };
  32. public:
  33. /**
  34. * Frees all the data held by this object.
  35. *
  36. * @note
  37. * If this object require initialization on core thread destruction is not done immediately, and is
  38. * instead just scheduled on the core thread. Otherwise the object is destroyed immediately.
  39. */
  40. virtual void destroy();
  41. /**
  42. * Initializes all the internal resources of this object. Must be called right after construction. Generally you
  43. * should call this from a factory method to avoid the issue where user forgets to call it.
  44. *
  45. * @note
  46. * If this object require initialization on core thread initialization is not done immediately, and is instead just
  47. * scheduled on the core thread. Otherwise the object is initialized immediately.
  48. */
  49. virtual void initialize();
  50. /** Returns true if the object has been destroyed. Destroyed object should not be used. */
  51. bool isDestroyed() const { return (mFlags & CGO_DESTROYED) != 0; }
  52. /**
  53. * Blocks the current thread until the resource is fully initialized.
  54. *
  55. * @note
  56. * If you call this without calling initialize first a deadlock will occur. You should not call this from core thread.
  57. */
  58. void blockUntilCoreInitialized() const;
  59. /** Returns an unique identifier for this object. */
  60. UINT64 getInternalID() const { return mInternalID; }
  61. /** Returns a shared_ptr version of "this" pointer. */
  62. SPtr<CoreObject> getThisPtr() const { return mThis.lock(); }
  63. /**
  64. * Returns an object that contains a core thread specific implementation of this CoreObject. Null is a valid return
  65. * value in case object requires no core thread implementation.
  66. *
  67. * @note Thread safe to retrieve, but its data is only valid on the core thread.
  68. */
  69. SPtr<CoreObjectCore> getCore() const { return mCoreSpecific; }
  70. /**
  71. * Ensures all dirty syncable data is send to the core thread counterpart of this object (if any).
  72. *
  73. * @note Call this if you have modified the object and need to make sure core thread has an up to date version.
  74. * Normally this is done automatically at the end of a frame.
  75. */
  76. void syncToCore(CoreAccessor& accessor);
  77. public: // ***** INTERNAL ******
  78. /** @name Internal
  79. * @{
  80. */
  81. /**
  82. * Sets a shared this pointer to this object. This must be called immediately after construction, but before
  83. * initialize().
  84. *
  85. * @note Internal method.
  86. * @note This should be called by the factory creation methods so user doesn't have to call it manually.
  87. */
  88. void _setThisPtr(std::shared_ptr<CoreObject> ptrThis);
  89. /**
  90. * Schedules the object to be destroyed, and then deleted.
  91. *
  92. * @note Internal method.
  93. */
  94. template<class T, class MemAlloc>
  95. static void _delete(CoreObject* obj)
  96. {
  97. if (!obj->isDestroyed())
  98. obj->destroy();
  99. bs_delete<T, MemAlloc>((T*)obj);
  100. }
  101. /** @} */
  102. protected:
  103. /**
  104. * Constructs a new core object.
  105. *
  106. * @param[in] requiresCoreInit (optional) Determines if the CoreObjectCore counterpart of this object
  107. * (if it has any, see createCore()) requires initialization and destruction on the
  108. * core thread.
  109. */
  110. CoreObject(bool requiresCoreInit = true);
  111. virtual ~CoreObject();
  112. /**
  113. * Queues a command to be executed on the core thread, without a return value.
  114. *
  115. * @note
  116. * Requires a shared pointer to the object this function will be executed on, in order to make sure the object is
  117. * not deleted before the command executes. Can be null if the function is static or global.
  118. */
  119. static void queueGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void()> func);
  120. /**
  121. * Queues a command to be executed on the core thread, with a return value in the form of AsyncOp.
  122. *
  123. * @see AsyncOp
  124. *
  125. * @note
  126. * Requires a shared pointer to the object this function will be executed on, in order to make sure the object is
  127. * not deleted before the command executes. Can be null if the function is static or global.
  128. */
  129. static AsyncOp queueReturnGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void(AsyncOp&)> func);
  130. bool requiresInitOnCoreThread() const { return (mFlags & CGO_INIT_ON_CORE_THREAD) != 0; }
  131. void setIsDestroyed(bool destroyed) { mFlags = destroyed ? mFlags | CGO_DESTROYED : mFlags & ~CGO_DESTROYED; }
  132. private:
  133. friend class CoreObjectManager;
  134. volatile UINT8 mFlags;
  135. UINT32 mCoreDirtyFlags;
  136. UINT64 mInternalID; // ID == 0 is not a valid ID
  137. std::weak_ptr<CoreObject> mThis;
  138. /**
  139. * Queues object initialization command on the core thread. The command is added to the primary core thread queue
  140. * and will be executed as soon as the core thread is ready.
  141. */
  142. static void queueInitializeGpuCommand(const SPtr<CoreObjectCore>& obj);
  143. /**
  144. * Queues object destruction command on the core thread. The command is added to the core thread accessor of this
  145. * thread and will be executed after accessor commands are submitted and any previously queued commands are executed.
  146. *
  147. * @note It is up to the caller to ensure no other accessors attempt to use this object.
  148. */
  149. static void queueDestroyGpuCommand(const SPtr<CoreObjectCore>& obj);
  150. /** Helper wrapper method used for queuing commands with no return value on the core thread. */
  151. static void executeGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void()> func);
  152. /** Helper wrapper method used for queuing commands with a return value on the core thread. */
  153. static void executeReturnGpuCommand(const SPtr<CoreObjectCore>& obj, std::function<void(AsyncOp&)> func, AsyncOp& op);
  154. protected:
  155. /************************************************************************/
  156. /* CORE OBJECT SYNC */
  157. /************************************************************************/
  158. /**
  159. * Creates an object that contains core thread specific data and methods for this CoreObject. Can be null if such
  160. * object is not required.
  161. */
  162. virtual SPtr<CoreObjectCore> createCore() const { return nullptr; }
  163. /**
  164. * Marks the core data as dirty. This causes the syncToCore() method to trigger the next time objects are synced
  165. * between core and sim threads.
  166. *
  167. * @param[in] flags (optional) Flags in case you want to signal that only part of the internal data is dirty.
  168. * syncToCore() will be called regardless and it's up to the implementation to read
  169. * the flags value if needed.
  170. */
  171. void markCoreDirty(UINT32 flags = 0xFFFFFFFF);
  172. /** Marks the core data as clean. Normally called right after syncToCore() has been called. */
  173. void markCoreClean() { mCoreDirtyFlags = 0; }
  174. /**
  175. * Notifies the core object manager that this object is dependant on some other CoreObject(s), and the dependencies
  176. * changed since the last call to this method. This will trigger a call to getCoreDependencies() to collect the
  177. * new dependencies.
  178. */
  179. void markDependenciesDirty();
  180. /**
  181. * Checks is the core dirty flag set. This is used by external systems to know when internal data has changed and
  182. * core thread potentially needs to be notified.
  183. */
  184. bool isCoreDirty() const { return mCoreDirtyFlags != 0; }
  185. /**
  186. * Returns the exact value of the internal flag that signals whether an object needs to be synced with the core thread.
  187. */
  188. UINT32 getCoreDirtyFlags() const { return mCoreDirtyFlags; }
  189. /**
  190. * Copy internal dirty data to a memory buffer that will be used for updating core thread version of that data.
  191. *
  192. * @note
  193. * This generally happens at the end of every sim thread frame. Synced data becomes available to the core thread
  194. * the start of the next core thread frame.
  195. */
  196. virtual CoreSyncData syncToCore(FrameAlloc* allocator) { return CoreSyncData(); }
  197. /**
  198. * Populates the provided array with all core objects that this core object depends upon. Dependencies are required
  199. * for syncing to the core thread, so the system can be aware to update the dependant objects if a dependency is
  200. * marked as dirty (for example updating a camera's viewport should also trigger an update on camera so it has
  201. * a chance to potentially update its data).
  202. */
  203. virtual void getCoreDependencies(Vector<CoreObject*>& dependencies) { }
  204. protected:
  205. SPtr<CoreObjectCore> mCoreSpecific;
  206. };
  207. /**
  208. * Creates a new core object using the specified allocators and returns a shared pointer to it.
  209. *
  210. * @note
  211. * All core thread object shared pointers must be created using this method or its overloads and you should not create
  212. * them manually.
  213. */
  214. template<class Type, class MainAlloc, class PtrDataAlloc, class... Args>
  215. std::shared_ptr<Type> bs_core_ptr_new(Args &&...args)
  216. {
  217. return std::shared_ptr<Type>(bs_new<Type, MainAlloc>(std::forward<Args>(args)...),
  218. &CoreObject::_delete<Type, MainAlloc>, StdAlloc<Type, PtrDataAlloc>());
  219. }
  220. /**
  221. * Creates a new core object using the specified allocator and returns a shared pointer to it.
  222. *
  223. * @note
  224. * All core thread object shared pointers must be created using this method or its overloads and you should not create
  225. * them manually.
  226. */
  227. template<class Type, class MainAlloc, class... Args>
  228. std::shared_ptr<Type> bs_core_ptr_new(Args &&...args)
  229. {
  230. return std::shared_ptr<Type>(bs_new<Type, MainAlloc>(std::forward<Args>(args)...),
  231. &CoreObject::_delete<Type, MainAlloc>, StdAlloc<Type, GenAlloc>());
  232. }
  233. /**
  234. * Creates a new core object and returns a shared pointer to it.
  235. *
  236. * @note
  237. * All core thread object shared pointers must be created using this method or its overloads and you should not create
  238. * them manually.
  239. */
  240. template<class Type, class... Args>
  241. std::shared_ptr<Type> bs_core_ptr_new(Args &&...args)
  242. {
  243. return std::shared_ptr<Type>(bs_new<Type, GenAlloc>(std::forward<Args>(args)...),
  244. &CoreObject::_delete<Type, GenAlloc>, StdAlloc<Type, GenAlloc>());
  245. }
  246. /**
  247. * Creates a core object shared pointer using a previously constructed object.
  248. *
  249. * @note
  250. * All core thread object shared pointers must be created using this method or its overloads and you should not create
  251. * them manually.
  252. */
  253. template<class Type, class MainAlloc = GenAlloc, class PtrDataAlloc = GenAlloc>
  254. std::shared_ptr<Type> bs_core_ptr(Type* data)
  255. {
  256. return std::shared_ptr<Type>(data, &CoreObject::_delete<Type, MainAlloc>, StdAlloc<Type, PtrDataAlloc>());
  257. }
  258. /** @} */
  259. }