BsCommandQueue.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  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. }
  87. QueuedCommand& operator=(const QueuedCommand& rhs)
  88. {
  89. callback = rhs.callback;
  90. callbackWithReturnValue = rhs.callbackWithReturnValue;
  91. asyncOp = rhs.asyncOp;
  92. returnsValue = rhs.returnsValue;
  93. callbackId = rhs.callbackId;
  94. notifyWhenComplete = rhs.notifyWhenComplete;
  95. return *this;
  96. }
  97. std::function<void()> callback;
  98. std::function<void(AsyncOp&)> callbackWithReturnValue;
  99. AsyncOp asyncOp;
  100. bool returnsValue;
  101. UINT32 callbackId;
  102. bool notifyWhenComplete;
  103. };
  104. /**
  105. * @brief Contains a list of commands you may queue for later execution on the core thread.
  106. */
  107. class BS_CORE_EXPORT CommandQueueBase
  108. {
  109. public:
  110. /**
  111. * @brief Constructor.
  112. *
  113. * @param threadId Identifier for the thread the command queue will be getting commands from.
  114. */
  115. CommandQueueBase(BS_THREAD_ID_TYPE threadId);
  116. virtual ~CommandQueueBase();
  117. /**
  118. * @brief Gets the thread identifier the command queue is used on.
  119. *
  120. * @note If the command queue is using a synchonized access policy generally this
  121. * is not relevant as it may be used on multiple threads.
  122. */
  123. BS_THREAD_ID_TYPE getThreadId() const { return mMyThreadId; }
  124. /**
  125. * @brief Executes all provided commands one by one in order. To get the commands you should call flush().
  126. *
  127. * @param notifyCallback Callback that will be called if a command that has "notifyOnComplete" flag set.
  128. * The callback will receive "callbackId" of the command.
  129. */
  130. void playbackWithNotify(Queue<QueuedCommand>* commands, std::function<void(UINT32)> notifyCallback);
  131. /**
  132. * @brief Executes all provided commands one by one in order. To get the commands you should call flush().
  133. */
  134. void playback(Queue<QueuedCommand>* commands);
  135. /**
  136. * @brief Allows you to set a breakpoint that will trigger when the specified command is executed.
  137. *
  138. * @note This is helpful when you receive an error on the executing thread and you cannot tell from where was
  139. * the command that caused the error queued from. However you can make a note of the queue and command index
  140. * and set a breakpoint so that it gets triggered next time you run the program. At that point you can know
  141. * exactly which part of code queued the command by examining the stack trace.
  142. *
  143. * @param queueIdx Zero-based index of the queue the command was queued on.
  144. * @param commandIdx Zero-based index of the command.
  145. */
  146. static void addBreakpoint(UINT32 queueIdx, UINT32 commandIdx);
  147. /**
  148. * @brief Queue up a new command to execute. Make sure the provided function has all of its
  149. * parameters properly bound. Last parameter must be unbound and of AsyncOp& type.
  150. * This is used to signal that the command is completed, and also for storing the return
  151. * value.
  152. *
  153. * @note Callback method also needs to call AsyncOp::markAsResolved once it is done
  154. * processing. (If it doesn't it will still be called automatically, but the return
  155. * value will default to nullptr)
  156. *
  157. * @param _notifyWhenComplete (optional) Call the notify method (provided in the call to CommandQueue::playback)
  158. * when the command is complete.
  159. * @param _callbackId (optional) Identifier for the callback so you can then later find it
  160. * if needed.
  161. *
  162. * @return Async operation object that you can continuously check until the command completes. After
  163. * it completes AsyncOp::isResolved will return true and return data will be valid (if
  164. * the callback provided any).
  165. */
  166. AsyncOp queueReturn(std::function<void(AsyncOp&)> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0);
  167. /**
  168. * @brief Queue up a new command to execute. Make sure the provided function has all of its
  169. * parameters properly bound. Provided command is not expected to return a value. If you
  170. * wish to return a value from the callback use the queueReturn which accepts an AsyncOp parameter.
  171. *
  172. * @param _notifyWhenComplete (optional) Call the notify method (provided in the call to CommandQueue::playback)
  173. * when the command is complete.
  174. * @param _callbackId (optional) Identifier for the callback so you can then later find
  175. * it if needed.
  176. */
  177. void queue(std::function<void()> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0);
  178. /**
  179. * @brief Returns a copy of all queued commands and makes room for new ones. Must be called from the thread
  180. * that created the command queue. Returned commands MUST be passed to "playback" method.
  181. */
  182. BansheeEngine::Queue<QueuedCommand>* flush();
  183. /**
  184. * @brief Cancels all currently queued commands.
  185. */
  186. void cancelAll();
  187. /**
  188. * @brief Returns true if no commands are queued.
  189. */
  190. bool isEmpty();
  191. protected:
  192. /**
  193. * @brief Helper method that throws an "Invalid thread" exception. Used primarily
  194. * so we can avoid including Exception include in this header.
  195. */
  196. void throwInvalidThreadException(const String& message) const;
  197. private:
  198. BansheeEngine::Queue<QueuedCommand>* mCommands;
  199. Stack<BansheeEngine::Queue<QueuedCommand>*> mEmptyCommandQueues; // List of empty queues for reuse
  200. BS_THREAD_ID_TYPE mMyThreadId;
  201. // Various variables that allow for easier debugging by allowing us to trigger breakpoints
  202. // when a certain command was queued.
  203. #if BS_DEBUG_MODE
  204. struct QueueBreakpoint
  205. {
  206. class HashFunction
  207. {
  208. public:
  209. size_t operator()(const QueueBreakpoint &key) const;
  210. };
  211. class EqualFunction
  212. {
  213. public:
  214. bool operator()(const QueueBreakpoint &a, const QueueBreakpoint &b) const;
  215. };
  216. QueueBreakpoint(UINT32 _queueIdx, UINT32 _commandIdx)
  217. :queueIdx(_queueIdx), commandIdx(_commandIdx)
  218. { }
  219. UINT32 queueIdx;
  220. UINT32 commandIdx;
  221. inline size_t operator()(const QueueBreakpoint& v) const;
  222. };
  223. UINT32 mMaxDebugIdx;
  224. UINT32 mCommandQueueIdx;
  225. AsyncOpSyncDataPtr mAsyncOpSyncData;
  226. static UINT32 MaxCommandQueueIdx;
  227. static UnorderedSet<QueueBreakpoint, QueueBreakpoint::HashFunction, QueueBreakpoint::EqualFunction> SetBreakpoints;
  228. BS_STATIC_MUTEX(CommandQueueBreakpointMutex);
  229. /**
  230. * @brief Checks if the specified command has a breakpoint and throw an assert if it does.
  231. */
  232. static void breakIfNeeded(UINT32 queueIdx, UINT32 commandIdx);
  233. #endif
  234. };
  235. /**
  236. * @copydoc CommandQueueBase
  237. *
  238. * @brief Use SyncPolicy to choose whether you want command queue be synchonized or not. Synchonized
  239. * command queues may be 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. /**
  246. * @copydoc CommandQueueBase::CommandQueueBase
  247. */
  248. CommandQueue(BS_THREAD_ID_TYPE threadId)
  249. :CommandQueueBase(threadId)
  250. { }
  251. ~CommandQueue()
  252. { }
  253. /**
  254. * @copydoc CommandQueueBase::queueReturn
  255. */
  256. AsyncOp queueReturn(std::function<void(AsyncOp&)> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  257. {
  258. #if BS_DEBUG_MODE
  259. #if BS_THREAD_SUPPORT != 0
  260. if(!isValidThread(getThreadId()))
  261. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  262. #endif
  263. #endif
  264. lock();
  265. AsyncOp asyncOp = CommandQueueBase::queueReturn(commandCallback, _notifyWhenComplete, _callbackId);
  266. unlock();
  267. return asyncOp;
  268. }
  269. /**
  270. * @copydoc CommandQueueBase::queue
  271. */
  272. void queue(std::function<void()> commandCallback, bool _notifyWhenComplete = false, UINT32 _callbackId = 0)
  273. {
  274. #if BS_DEBUG_MODE
  275. #if BS_THREAD_SUPPORT != 0
  276. if(!isValidThread(getThreadId()))
  277. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  278. #endif
  279. #endif
  280. lock();
  281. CommandQueueBase::queue(commandCallback, _notifyWhenComplete, _callbackId);
  282. unlock();
  283. }
  284. /**
  285. * @copydoc CommandQueueBase::flush
  286. */
  287. BansheeEngine::Queue<QueuedCommand>* flush()
  288. {
  289. #if BS_DEBUG_MODE
  290. #if BS_THREAD_SUPPORT != 0
  291. if(!isValidThread(getThreadId()))
  292. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  293. #endif
  294. #endif
  295. lock();
  296. BansheeEngine::Queue<QueuedCommand>* commands = CommandQueueBase::flush();
  297. unlock();
  298. return commands;
  299. }
  300. /**
  301. * @copydoc CommandQueueBase::cancelAll
  302. */
  303. void cancelAll()
  304. {
  305. #if BS_DEBUG_MODE
  306. #if BS_THREAD_SUPPORT != 0
  307. if(!isValidThread(getThreadId()))
  308. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  309. #endif
  310. #endif
  311. lock();
  312. CommandQueueBase::cancelAll();
  313. unlock();
  314. }
  315. /**
  316. * @copydoc CommandQueueBase::isEmpty
  317. */
  318. bool isEmpty()
  319. {
  320. #if BS_DEBUG_MODE
  321. #if BS_THREAD_SUPPORT != 0
  322. if(!isValidThread(getThreadId()))
  323. throwInvalidThreadException("Command queue accessed outside of its creation thread.");
  324. #endif
  325. #endif
  326. lock();
  327. bool empty = CommandQueueBase::isEmpty();
  328. unlock();
  329. return empty;
  330. }
  331. };
  332. }