CmCommandQueue.h 11 KB

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