BsCommandQueue.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. #pragma once
  2. #include "BsCorePrerequisites.h"
  3. #include "BsAsyncOp.h"
  4. #include <functional>
  5. namespace BansheeEngine
  6. {
  7. /** @cond INTERNAL */
  8. /** @addtogroup CoreThread
  9. * @{
  10. */
  11. /**
  12. * Command queue policy that provides no synchonization. Should be used with command queues that are used on a single
  13. * thread only.
  14. */
  15. class CommandQueueNoSync
  16. {
  17. public:
  18. CommandQueueNoSync() {}
  19. virtual ~CommandQueueNoSync() {}
  20. bool isValidThread(BS_THREAD_ID_TYPE ownerThread) const
  21. {
  22. return BS_THREAD_CURRENT_ID == ownerThread;
  23. }
  24. void lock() { };
  25. void unlock() { }
  26. };
  27. /**
  28. * Command queue policy that provides synchonization. Should be used with command queues that are used on multiple
  29. * threads.
  30. */
  31. class CommandQueueSync
  32. {
  33. public:
  34. CommandQueueSync()
  35. :mLock(mCommandQueueMutex, BS_DEFER_LOCK)
  36. { }
  37. virtual ~CommandQueueSync() {}
  38. bool isValidThread(BS_THREAD_ID_TYPE ownerThread) const
  39. {
  40. return true;
  41. }
  42. void lock()
  43. {
  44. mLock.lock();
  45. };
  46. void unlock()
  47. {
  48. mLock.unlock();
  49. }
  50. private:
  51. BS_MUTEX(mCommandQueueMutex);
  52. BS_LOCK_TYPE mLock;
  53. };
  54. /**
  55. * Represents a single queued command in the command list. Contains all the data for executing the command and checking
  56. * up on the command status.
  57. */
  58. struct QueuedCommand
  59. {
  60. #if BS_DEBUG_MODE
  61. QueuedCommand(std::function<void(AsyncOp&)> _callback, UINT32 _debugId, const AsyncOpSyncDataPtr& asyncOpSyncData,
  62. bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  63. :callbackWithReturnValue(_callback), debugId(_debugId), returnsValue(true),
  64. notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(asyncOpSyncData)
  65. { }
  66. QueuedCommand(std::function<void()> _callback, UINT32 _debugId, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  67. :callback(_callback), debugId(_debugId), returnsValue(false), notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(AsyncOpEmpty())
  68. { }
  69. UINT32 debugId;
  70. #else
  71. QueuedCommand(std::function<void(AsyncOp&)> _callback, const AsyncOpSyncDataPtr& asyncOpSyncData,
  72. bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  73. :callbackWithReturnValue(_callback), returnsValue(true), notifyWhenComplete(_notifyWhenComplete),
  74. callbackId(_callbackId), asyncOp(asyncOpSyncData)
  75. { }
  76. QueuedCommand(std::function<void()> _callback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  77. :callback(_callback), returnsValue(false), notifyWhenComplete(_notifyWhenComplete), callbackId(_callbackId), asyncOp(AsyncOpEmpty())
  78. { }
  79. #endif
  80. ~QueuedCommand()
  81. { }
  82. QueuedCommand(const QueuedCommand& source)
  83. {
  84. callback = source.callback;
  85. callbackWithReturnValue = source.callbackWithReturnValue;
  86. asyncOp = source.asyncOp;
  87. returnsValue = source.returnsValue;
  88. callbackId = source.callbackId;
  89. notifyWhenComplete = source.notifyWhenComplete;
  90. #if BS_DEBUG_MODE
  91. debugId = source.debugId;
  92. #endif
  93. }
  94. QueuedCommand& operator=(const QueuedCommand& rhs)
  95. {
  96. callback = rhs.callback;
  97. callbackWithReturnValue = rhs.callbackWithReturnValue;
  98. asyncOp = rhs.asyncOp;
  99. returnsValue = rhs.returnsValue;
  100. callbackId = rhs.callbackId;
  101. notifyWhenComplete = rhs.notifyWhenComplete;
  102. #if BS_DEBUG_MODE
  103. debugId = rhs.debugId;
  104. #endif
  105. return *this;
  106. }
  107. std::function<void()> callback;
  108. std::function<void(AsyncOp&)> callbackWithReturnValue;
  109. AsyncOp asyncOp;
  110. bool returnsValue;
  111. UINT32 callbackId;
  112. bool notifyWhenComplete;
  113. };
  114. /** Contains a list of commands you may queue for later execution on the core thread. */
  115. class BS_CORE_EXPORT CommandQueueBase
  116. {
  117. public:
  118. /**
  119. * Constructor.
  120. *
  121. * @param[in] threadId Identifier for the thread the command queue will be getting commands from.
  122. */
  123. CommandQueueBase(BS_THREAD_ID_TYPE threadId);
  124. virtual ~CommandQueueBase();
  125. /**
  126. * Gets the thread identifier the command queue is used on.
  127. *
  128. * @note If the command queue is using a synchonized access policy generally this is not relevant as it may be
  129. * used on multiple threads.
  130. */
  131. BS_THREAD_ID_TYPE getThreadId() const { return mMyThreadId; }
  132. /**
  133. * Executes all provided commands one by one in order. To get the commands you should call flush().
  134. *
  135. * @param[in] notifyCallback Callback that will be called if a command that has @p notifyOnComplete flag set.
  136. * The callback will receive @p callbackId of the command.
  137. */
  138. void playbackWithNotify(Queue<QueuedCommand>* commands, std::function<void(UINT32)> notifyCallback);
  139. /** Executes all provided commands one by one in order. To get the commands you should call flush(). */
  140. void playback(Queue<QueuedCommand>* commands);
  141. /**
  142. * Allows you to set a breakpoint that will trigger when the specified command is executed.
  143. *
  144. * @param[in] queueIdx Zero-based index of the queue the command was queued on.
  145. * @param[in] commandIdx Zero-based index of the command.
  146. *
  147. * @note
  148. * This is helpful when you receive an error on the executing thread and you cannot tell from where was the command
  149. * that caused the error queued from. However you can make a note of the queue and command index and set a
  150. * breakpoint so that it gets triggered next time you run the program. At that point you can know exactly which part
  151. * of code queued the command by examining the stack trace.
  152. */
  153. static void addBreakpoint(UINT32 queueIdx, UINT32 commandIdx);
  154. /**
  155. * Queue up a new command to execute. Make sure the provided function has all of its parameters properly bound.
  156. * Last parameter must be unbound and of AsyncOp& type. This is used to signal that the command is completed, and
  157. * also for storing the return value.
  158. *
  159. * @param[in] _notifyWhenComplete (optional) Call the notify method (provided in the call to playback())
  160. * when the command is complete.
  161. * @param[in] _callbackId (optional) Identifier for the callback so you can then later find it
  162. * if needed.
  163. *
  164. * @return Async operation object that you can continuously check until the command
  165. * completes. After it completes AsyncOp::isResolved() will return true and return
  166. * data will be valid (if the callback provided any).
  167. *
  168. * @note
  169. * Callback method also needs to call AsyncOp::markAsResolved once it is done processing. (If it doesn't it will
  170. * still be called automatically, but the return value will default to nullptr)
  171. */
  172. AsyncOp queueReturn(std::function<void(AsyncOp&)> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0);
  173. /**
  174. * Queue up a new command to execute. Make sure the provided function has all of its parameters properly bound.
  175. * Provided command is not expected to return a value. If you wish to return a value from the callback use the
  176. * queueReturn() which accepts an AsyncOp parameter.
  177. *
  178. * @param[in] _notifyWhenComplete (optional) Call the notify method (provided in the call to playback())
  179. * when the command is complete.
  180. * @param[in] _callbackId (optional) Identifier for the callback so you can then later find
  181. * it if needed.
  182. */
  183. void queue(std::function<void()> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0);
  184. /**
  185. * Returns a copy of all queued commands and makes room for new ones. Must be called from the thread that created
  186. * the command queue. Returned commands must be passed to playback() method.
  187. */
  188. Queue<QueuedCommand>* flush();
  189. /** Cancels all currently queued commands. */
  190. void cancelAll();
  191. /** Returns true if no commands are queued. */
  192. bool isEmpty();
  193. protected:
  194. /**
  195. * Helper method that throws an "Invalid thread" exception. Used primarily so we can avoid including Exception
  196. * include in this header.
  197. */
  198. void throwInvalidThreadException(const String& message) const;
  199. private:
  200. Queue<QueuedCommand>* mCommands;
  201. Stack<Queue<QueuedCommand>*> mEmptyCommandQueues; /**< List of empty queues for reuse. */
  202. AsyncOpSyncDataPtr mAsyncOpSyncData;
  203. BS_THREAD_ID_TYPE mMyThreadId;
  204. // Various variables that allow for easier debugging by allowing us to trigger breakpoints
  205. // when a certain command was queued.
  206. #if BS_DEBUG_MODE
  207. struct QueueBreakpoint
  208. {
  209. class HashFunction
  210. {
  211. public:
  212. size_t operator()(const QueueBreakpoint &key) const;
  213. };
  214. class EqualFunction
  215. {
  216. public:
  217. bool operator()(const QueueBreakpoint &a, const QueueBreakpoint &b) const;
  218. };
  219. QueueBreakpoint(UINT32 _queueIdx, UINT32 _commandIdx)
  220. :queueIdx(_queueIdx), commandIdx(_commandIdx)
  221. { }
  222. UINT32 queueIdx;
  223. UINT32 commandIdx;
  224. inline size_t operator()(const QueueBreakpoint& v) const;
  225. };
  226. UINT32 mMaxDebugIdx;
  227. UINT32 mCommandQueueIdx;
  228. static UINT32 MaxCommandQueueIdx;
  229. static UnorderedSet<QueueBreakpoint, QueueBreakpoint::HashFunction, QueueBreakpoint::EqualFunction> SetBreakpoints;
  230. BS_STATIC_MUTEX(CommandQueueBreakpointMutex);
  231. /** Checks if the specified command has a breakpoint and throw an assert if it does. */
  232. static void breakIfNeeded(UINT32 queueIdx, UINT32 commandIdx);
  233. #endif
  234. };
  235. /**
  236. * @copydoc CommandQueueBase
  237. *
  238. * Use SyncPolicy to choose whether you want command queue be synchonized or not. Synchonized command queues may be
  239. * used across multiple threads and non-synchonized only on one.
  240. */
  241. template<class SyncPolicy = CommandQueueNoSync>
  242. class CommandQueue : public CommandQueueBase, public SyncPolicy
  243. {
  244. public:
  245. /** @copydoc CommandQueueBase::CommandQueueBase */
  246. CommandQueue(BS_THREAD_ID_TYPE threadId)
  247. :CommandQueueBase(threadId)
  248. { }
  249. ~CommandQueue()
  250. { }
  251. /** @copydoc CommandQueueBase::queueReturn */
  252. AsyncOp queueReturn(std::function<void(AsyncOp&)> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  253. {
  254. #if BS_DEBUG_MODE
  255. #if BS_THREAD_SUPPORT != 0
  256. if(!isValidThread(getThreadId()))
  257. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  258. #endif
  259. #endif
  260. lock();
  261. AsyncOp asyncOp = CommandQueueBase::queueReturn(commandCallback, _notifyWhenComplete, _callbackId);
  262. unlock();
  263. return asyncOp;
  264. }
  265. /** @copydoc CommandQueueBase::queue */
  266. void queue(std::function<void()> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  267. {
  268. #if BS_DEBUG_MODE
  269. #if BS_THREAD_SUPPORT != 0
  270. if(!isValidThread(getThreadId()))
  271. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  272. #endif
  273. #endif
  274. lock();
  275. CommandQueueBase::queue(commandCallback, _notifyWhenComplete, _callbackId);
  276. unlock();
  277. }
  278. /** @copydoc CommandQueueBase::flush */
  279. BansheeEngine::Queue<QueuedCommand>* flush()
  280. {
  281. #if BS_DEBUG_MODE
  282. #if BS_THREAD_SUPPORT != 0
  283. if(!isValidThread(getThreadId()))
  284. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  285. #endif
  286. #endif
  287. lock();
  288. BansheeEngine::Queue<QueuedCommand>* commands = CommandQueueBase::flush();
  289. unlock();
  290. return commands;
  291. }
  292. /** @copydoc CommandQueueBase::cancelAll */
  293. void cancelAll()
  294. {
  295. #if BS_DEBUG_MODE
  296. #if BS_THREAD_SUPPORT != 0
  297. if(!isValidThread(getThreadId()))
  298. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  299. #endif
  300. #endif
  301. lock();
  302. CommandQueueBase::cancelAll();
  303. unlock();
  304. }
  305. /** @copydoc CommandQueueBase::isEmpty */
  306. bool isEmpty()
  307. {
  308. #if BS_DEBUG_MODE
  309. #if BS_THREAD_SUPPORT != 0
  310. if(!isValidThread(getThreadId()))
  311. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  312. #endif
  313. #endif
  314. lock();
  315. bool empty = CommandQueueBase::isEmpty();
  316. unlock();
  317. return empty;
  318. }
  319. };
  320. /** @} */
  321. /** @endcond */
  322. }