BsCommandQueue.h 12 KB

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