BsCommandQueue.h 12 KB

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