BsCoreObject.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. #pragma once
  2. #include "BsCorePrerequisites.h"
  3. #include "BsCoreObjectCore.h"
  4. #include "BsAsyncOp.h"
  5. namespace BansheeEngine
  6. {
  7. /**
  8. * @brief This class provides some common functionality that all low-level objects
  9. * used on the core thread need to implement.
  10. *
  11. * @note This involves initializing, keeping track of, and releasing GPU resources.
  12. * All core GPU objects are initialized on the core thread, and destroyed on the core thread,
  13. * so majority of these methods will just schedule object initialization/destruction.
  14. * Non-GPU core objects can normally be initialized on the caller thread.
  15. */
  16. class BS_CORE_EXPORT CoreObject
  17. {
  18. protected:
  19. /**
  20. * @brief Values that represent current state of the object
  21. */
  22. enum Flags
  23. {
  24. CGO_INITIALIZED = 0x01, /**< Object has been fully initialized and may be used. */
  25. CGO_INIT_ON_CORE_THREAD = 0x02, /**< Object requires initialization on core thread. */
  26. CGO_SCHEDULED_FOR_INIT = 0x04, /**< Object has been scheduled for initialization but core thread has not completed it yet. */
  27. CGO_SCHEDULED_FOR_DELETE = 0x08 /**< Object has been scheduled for deletion but core thread has not completed it yet. */
  28. };
  29. public:
  30. /**
  31. * @brief Constructs a new core object.
  32. *
  33. * @param requiresGpuInit (optional) If true the objects initialize_internal and destroy_internal methods
  34. * will be called from the core thread asynchronously. Otherwise they will be called
  35. * by the caller thread synchronously.
  36. */
  37. CoreObject(bool requiresGpuInit = true);
  38. virtual ~CoreObject();
  39. /**
  40. * @brief Frees all the data held by this object.
  41. *
  42. * @note If is created with "CGO_INIT_ON_CORE_THREAD" flag destruction is not done immediately,
  43. * and is instead just scheduled on the core thread.
  44. * Unless called from core thread in which case it is executed immediately.
  45. * Objects without "CGO_INIT_ON_CORE_THREAD" flag are destructed immediately.
  46. */
  47. virtual void destroy();
  48. /**
  49. * @brief Initializes all the internal resources of this object. Should be called by the
  50. * factory creation methods automatically after construction and not by user directly.
  51. *
  52. * @note If is created with "CGO_INIT_ON_CORE_THREAD" flag initialization is not done immediately,
  53. * and is instead just scheduled on the core thread.
  54. * Unless called from core thread in which case it is executed immediately.
  55. * Objects without "CGO_INIT_ON_CORE_THREAD" flag are initialized immediately.
  56. */
  57. virtual void initialize();
  58. /**
  59. * @brief Returns true if the object has been properly initialized. You are not
  60. * allowed to call any methods on the resource until you are sure resource is initialized.
  61. *
  62. * @note Normally CPU objects are initialized on creation and this will never be false, and GPU
  63. * objects are initialized when the core thread processes them.
  64. */
  65. bool isInitialized() const { return (mFlags & CGO_INITIALIZED) != 0; }
  66. /**
  67. * @brief Blocks the current thread until the resource is fully initialized.
  68. *
  69. * @note If you call this without calling initialize first a deadlock will occur.
  70. * You should not call this from core thread.
  71. */
  72. void synchronize();
  73. /**
  74. * @brief Internal method. Sets a shared this pointer to this object. This MUST be called immediately after construction.
  75. *
  76. * @note Called automatically by the factory creation methods so user should not call this manually.
  77. */
  78. void _setThisPtr(std::shared_ptr<CoreObject> ptrThis);
  79. /**
  80. * @brief Returns an unique identifier for this object.
  81. */
  82. UINT64 getInternalID() const { return mInternalID; }
  83. /**
  84. * @brief Internal method. Schedules the object to be destroyed, and then deleted.
  85. */
  86. template<class T, class MemAlloc>
  87. static void _deleteDelayed(CoreObject* obj)
  88. {
  89. _deleteDelayedInternal(obj);
  90. if(obj->isInitialized())
  91. {
  92. std::shared_ptr<CoreObject> thisPtr(obj);
  93. obj->_setThisPtr(thisPtr);
  94. obj->destroy();
  95. }
  96. else
  97. {
  98. bs_delete<MemAlloc, T>((T*)obj);
  99. }
  100. }
  101. /**
  102. * @brief Returns a shared_ptr version of "this" pointer.
  103. */
  104. SPtr<CoreObject> getThisPtr() const { return mThis.lock(); }
  105. /**
  106. * @brief Returns an object that contains a core thread specific implementation
  107. * of this CoreObject.
  108. *
  109. * @note Thread safe to retrieve, but its data is only valid on the core thread.
  110. */
  111. SPtr<CoreObjectCore> getCore() const { return mCoreSpecific; }
  112. protected:
  113. /**
  114. * @brief Frees all of the objects dynamically allocated memory. All derived classes that have something to free
  115. * should do it here instead of their destructor. All derived classes need to call this base method when they're done.
  116. *
  117. * @note For objects with "CGO_INIT_ON_CORE_THREAD" flag this is scheduled to be executed on the core thread,
  118. * so normally you want to destroy all GPU specific resources here.
  119. */
  120. virtual void destroy_internal();
  121. /**
  122. * @brief Initializes all the internal resources of this object. Needs to be called before doing
  123. * any operations with the object. All derived classes also need to call this base method.
  124. *
  125. * @note For objects with "CGO_INIT_ON_CORE_THREAD" flag this is scheduled to be executed on the core thread,
  126. * so normally you want to initialize all GPU specific resources here.
  127. */
  128. virtual void initialize_internal();
  129. /**
  130. * @brief Performs some internal checks when an object is being deleted.
  131. */
  132. static void _deleteDelayedInternal(CoreObject* obj);
  133. /**
  134. * @brief Queues a command to be executed on the core thread, without a return value.
  135. *
  136. * @note Requires a shared pointer to the object this function will be executed on, in order to
  137. * make sure the object is not deleted before the command executes. Can be null if the
  138. * function is static or global.
  139. */
  140. static void queueGpuCommand(std::shared_ptr<CoreObject>& obj, std::function<void()> func);
  141. /**
  142. * @brief Queues a command to be executed on the core thread, with a return value in the form of AsyncOp.
  143. *
  144. * @see AsyncOp
  145. *
  146. * @note Requires a shared pointer to the object this function will be executed on, in order to
  147. * make sure the object is not deleted before the command executes. Can be null if the
  148. * function is static or global.
  149. */
  150. static AsyncOp queueReturnGpuCommand(std::shared_ptr<CoreObject>& obj, std::function<void(AsyncOp&)> func);
  151. bool isScheduledToBeInitialized() const { return (mFlags & CGO_SCHEDULED_FOR_INIT) != 0; }
  152. bool isScheduledToBeDeleted() const { return (mFlags & CGO_SCHEDULED_FOR_DELETE) != 0; }
  153. bool requiresInitOnCoreThread() const { return (mFlags & CGO_INIT_ON_CORE_THREAD) != 0; }
  154. void setIsInitialized(bool initialized) { mFlags = initialized ? mFlags | CGO_INITIALIZED : mFlags & ~CGO_INITIALIZED; }
  155. void setScheduledToBeInitialized(bool scheduled) { mFlags = scheduled ? mFlags | CGO_SCHEDULED_FOR_INIT : mFlags & ~CGO_SCHEDULED_FOR_INIT; }
  156. void setScheduledToBeDeleted(bool scheduled) { mFlags = scheduled ? mFlags | CGO_SCHEDULED_FOR_DELETE : mFlags & ~CGO_SCHEDULED_FOR_DELETE; }
  157. private:
  158. friend class CoreObjectManager;
  159. volatile UINT8 mFlags;
  160. UINT32 mCoreDirtyFlags;
  161. UINT64 mInternalID; // ID == 0 is not a valid ID
  162. std::weak_ptr<CoreObject> mThis;
  163. BS_STATIC_THREAD_SYNCHRONISER(mCoreGpuObjectLoadedCondition)
  164. BS_STATIC_MUTEX(mCoreGpuObjectLoadedMutex)
  165. /**
  166. * @brief Queues object initialization command on the core thread. The command is added to the
  167. * primary core thread queue and will be executed as soon as the core thread is ready.
  168. */
  169. static void queueInitializeGpuCommand(std::shared_ptr<CoreObject>& obj);
  170. /**
  171. * @brief Queues object destruction command on the core thread. The command is added to the
  172. * core thread accessor of this thread and will be executed after accessor commands
  173. * are submitted and any previously queued commands are executed.
  174. *
  175. * @note It is up to the caller to ensure no other accessors attempt to use this object.
  176. */
  177. static void queueDestroyGpuCommand(std::shared_ptr<CoreObject>& obj);
  178. /**
  179. * @brief Helper wrapper method used for queuing commands with no return value on the core thread.
  180. */
  181. static void executeGpuCommand(std::shared_ptr<CoreObject> obj, std::function<void()> func);
  182. /**
  183. * @brief Helper wrapper method used for queuing commands with a return value on the core thread.
  184. */
  185. static void executeReturnGpuCommand(std::shared_ptr<CoreObject> obj, std::function<void(AsyncOp&)> func, AsyncOp& op);
  186. protected:
  187. /************************************************************************/
  188. /* CORE OBJECT SYNC */
  189. /************************************************************************/
  190. /**
  191. * @brief Creates an object that contains core thread specific data and methods
  192. * for this CoreObject. Can be null if such object is not required.
  193. */
  194. virtual SPtr<CoreObjectCore> createCore() const { return nullptr; }
  195. /**
  196. * @brief Marks the core data as dirty. This causes the syncToCore()
  197. * method to trigger the next time objects are synced between core and sim threads.
  198. *
  199. * @param flags Optional flags in case you want to signal that only part of the
  200. * internal data is dirty. syncFromCore() will be called regardless
  201. * and it's up to the implementation to read the flags value if needed.
  202. */
  203. void markCoreDirty(UINT32 flags = 0xFFFFFFFF) { mCoreDirtyFlags = flags; }
  204. /**
  205. * @brief Marks the core data as clean. Normally called right after syncToCore()
  206. * has been called.
  207. */
  208. void markCoreClean() { mCoreDirtyFlags = 0; }
  209. /**
  210. * @brief Checks is the core dirty flag set. This is used by external systems
  211. * to know when internal data has changed and core thread potentially needs to be notified.
  212. */
  213. bool isCoreDirty() const { return mCoreDirtyFlags != 0; }
  214. /**
  215. * @brief Copy internal dirty data to a memory buffer that will be used
  216. * for updating core thread version of that data.
  217. *
  218. * @note This generally happens at the end of every sim thread frame. Synced data becomes
  219. * available to the core thread the start of the next core thread frame.
  220. */
  221. virtual CoreSyncData syncToCore(FrameAlloc* allocator) { return CoreSyncData(); }
  222. /**
  223. * @brief Update internal data from provided memory buffer that
  224. * was populated with data from the core thread.
  225. *
  226. * @note This generally happens at the start of every sim thread frame. Provided data
  227. * is from a previous core thread frame.
  228. */
  229. virtual void syncFromCore(const CoreSyncData& data) { }
  230. protected:
  231. SPtr<CoreObjectCore> mCoreSpecific;
  232. };
  233. /**
  234. * @brief Creates a new core object using the specified allocators and returns a shared pointer to it.
  235. *
  236. * @note All core thread object shared pointers must be created using this method or its overloads
  237. * and you should not create them manually.
  238. */
  239. template<class Type, class MainAlloc, class PtrDataAlloc, class... Args>
  240. std::shared_ptr<Type> bs_core_ptr(Args &&...args)
  241. {
  242. return std::shared_ptr<Type>(bs_new<Type, MainAlloc>(std::forward<Args>(args)...),
  243. &CoreObject::_deleteDelayed<Type, MainAlloc>, StdAlloc<Type, PtrDataAlloc>());
  244. }
  245. /**
  246. * @brief Creates a new core object using the specified allocator and returns a shared pointer to it.
  247. *
  248. * @note All core thread object shared pointers must be created using this method or its overloads
  249. * and you should not create them manually.
  250. */
  251. template<class Type, class MainAlloc, class... Args>
  252. std::shared_ptr<Type> bs_core_ptr(Args &&...args)
  253. {
  254. return std::shared_ptr<Type>(bs_new<Type, MainAlloc>(std::forward<Args>(args)...),
  255. &CoreObject::_deleteDelayed<Type, MainAlloc>, StdAlloc<Type, GenAlloc>());
  256. }
  257. /**
  258. * @brief Creates a new core object and returns a shared pointer to it.
  259. *
  260. * @note All core thread object shared pointers must be created using this method or its overloads
  261. * and you should not create them manually.
  262. */
  263. template<class Type, class... Args>
  264. std::shared_ptr<Type> bs_core_ptr(Args &&...args)
  265. {
  266. return std::shared_ptr<Type>(bs_new<Type, GenAlloc>(std::forward<Args>(args)...),
  267. &CoreObject::_deleteDelayed<Type, GenAlloc>, StdAlloc<Type, GenAlloc>());
  268. }
  269. /**
  270. * @brief Creates a core object shared pointer using a previously constructed object.
  271. *
  272. * @note All core thread object shared pointers must be created using this method or its overloads
  273. * and you should not create them manually.
  274. */
  275. template<class Type, class MainAlloc>
  276. std::shared_ptr<Type> bs_core_ptr(Type* data)
  277. {
  278. return std::shared_ptr<Type>(data, &CoreObject::_deleteDelayed<Type, MainAlloc>, StdAlloc<Type, GenAlloc>());
  279. }
  280. /**
  281. * @brief Creates a core object shared pointer using a previously constructed object.
  282. *
  283. * @note All core thread object shared pointers must be created using this method or its overloads
  284. * and you should not create them manually.
  285. */
  286. template<class Type, class MainAlloc, class PtrDataAlloc>
  287. std::shared_ptr<Type> bs_core_ptr(Type* data)
  288. {
  289. return std::shared_ptr<Type>(data, &CoreObject::_deleteDelayed<Type, MainAlloc>, StdAlloc<Type, PtrDataAlloc>());
  290. }
  291. }