RenderingThread.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // Copyright (C) 2009-2017, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <anki/gr/gl/RenderingThread.h>
  6. #include <anki/gr/gl/CommandBufferImpl.h>
  7. #include <anki/gr/GrManager.h>
  8. #include <anki/gr/gl/GrManagerImpl.h>
  9. #include <anki/gr/gl/GlState.h>
  10. #include <anki/gr/Fence.h>
  11. #include <anki/gr/gl/FenceImpl.h>
  12. #include <anki/util/Logger.h>
  13. #include <anki/core/Trace.h>
  14. #include <cstdlib>
  15. namespace anki
  16. {
  17. /// Sync rendering thread command.
  18. class SyncCommand final : public GlCommand
  19. {
  20. public:
  21. RenderingThread* m_renderingThread;
  22. SyncCommand(RenderingThread* renderingThread)
  23. : m_renderingThread(renderingThread)
  24. {
  25. }
  26. ANKI_USE_RESULT Error operator()(GlState&)
  27. {
  28. m_renderingThread->m_syncBarrier.wait();
  29. return Error::NONE;
  30. }
  31. };
  32. /// Swap buffers command.
  33. class SwapBuffersCommand final : public GlCommand
  34. {
  35. public:
  36. RenderingThread* m_renderingThread;
  37. SwapBuffersCommand(RenderingThread* renderingThread)
  38. : m_renderingThread(renderingThread)
  39. {
  40. }
  41. ANKI_USE_RESULT Error operator()(GlState&)
  42. {
  43. m_renderingThread->swapBuffersInternal();
  44. return Error::NONE;
  45. }
  46. };
  47. /// Empty command
  48. class EmptyCommand final : public GlCommand
  49. {
  50. public:
  51. ANKI_USE_RESULT Error operator()(GlState&)
  52. {
  53. return Error::NONE;
  54. }
  55. };
  56. RenderingThread::RenderingThread(GrManagerImpl* manager)
  57. : m_manager(manager)
  58. , m_tail(0)
  59. , m_head(0)
  60. , m_renderingThreadSignal(0)
  61. , m_thread("anki_gl")
  62. {
  63. ANKI_ASSERT(m_manager);
  64. }
  65. RenderingThread::~RenderingThread()
  66. {
  67. m_queue.destroy(m_manager->getAllocator());
  68. }
  69. void RenderingThread::flushCommandBuffer(CommandBufferPtr cmdb, FencePtr* fence)
  70. {
  71. // Create a fence
  72. if(fence)
  73. {
  74. FencePtr& f = *fence;
  75. FenceImpl* fenceImpl = m_manager->getAllocator().newInstance<FenceImpl>(m_manager.get());
  76. f.reset(fenceImpl);
  77. class CreateFenceCmd final : public GlCommand
  78. {
  79. public:
  80. FencePtr m_fence;
  81. CreateFenceCmd(FencePtr fence)
  82. : m_fence(fence)
  83. {
  84. }
  85. Error operator()(GlState&)
  86. {
  87. static_cast<FenceImpl&>(*m_fence).m_fence = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0);
  88. return Error::NONE;
  89. }
  90. };
  91. static_cast<CommandBufferImpl&>(*cmdb).pushBackNewCommand<CreateFenceCmd>(f);
  92. }
  93. static_cast<CommandBufferImpl&>(*cmdb).makeImmutable();
  94. {
  95. LockGuard<Mutex> lock(m_mtx);
  96. // Set commands
  97. U64 diff = m_tail - m_head;
  98. if(diff < m_queue.getSize())
  99. {
  100. U64 idx = m_tail % m_queue.getSize();
  101. m_queue[idx] = cmdb;
  102. ++m_tail;
  103. }
  104. else
  105. {
  106. ANKI_GL_LOGW("Rendering queue too small");
  107. }
  108. m_condVar.notifyOne(); // Wake the thread
  109. }
  110. }
  111. void RenderingThread::finishCommandBuffer(CommandBufferPtr commands)
  112. {
  113. flushCommandBuffer(commands, nullptr);
  114. syncClientServer();
  115. }
  116. void RenderingThread::start()
  117. {
  118. ANKI_ASSERT(m_tail == 0 && m_head == 0);
  119. m_queue.create(m_manager->getAllocator(), QUEUE_SIZE);
  120. // Swap buffers stuff
  121. m_swapBuffersCommands = m_manager->newCommandBuffer(CommandBufferInitInfo());
  122. static_cast<CommandBufferImpl&>(*m_swapBuffersCommands).pushBackNewCommand<SwapBuffersCommand>(this);
  123. // Just in case noone swaps
  124. static_cast<CommandBufferImpl&>(*m_swapBuffersCommands).makeExecuted();
  125. m_manager->pinContextToCurrentThread(false);
  126. // Start thread
  127. m_thread.start(this, threadCallback);
  128. // Create sync command buffer
  129. m_syncCommands = m_manager->newCommandBuffer(CommandBufferInitInfo());
  130. static_cast<CommandBufferImpl&>(*m_syncCommands).pushBackNewCommand<SyncCommand>(this);
  131. m_emptyCmdb = m_manager->newCommandBuffer(CommandBufferInitInfo());
  132. static_cast<CommandBufferImpl&>(*m_emptyCmdb).pushBackNewCommand<EmptyCommand>();
  133. }
  134. void RenderingThread::stop()
  135. {
  136. syncClientServer();
  137. m_renderingThreadSignal = 1;
  138. flushCommandBuffer(m_emptyCmdb, nullptr);
  139. Error err = m_thread.join();
  140. (void)err;
  141. }
  142. void RenderingThread::prepare()
  143. {
  144. m_manager->pinContextToCurrentThread(true);
  145. // Ignore the first error
  146. glGetError();
  147. ANKI_GL_LOGI("OpenGL async thread started: OpenGL version \"%s\", GLSL version \"%s\"",
  148. reinterpret_cast<const char*>(glGetString(GL_VERSION)),
  149. reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION)));
  150. // Get thread id
  151. m_serverThreadId = Thread::getCurrentThreadId();
  152. // Init state
  153. m_manager->getState().initRenderThread();
  154. }
  155. void RenderingThread::finish()
  156. {
  157. // Iterate the queue and release the refcounts
  158. for(U i = 0; i < m_queue.getSize(); i++)
  159. {
  160. if(m_queue[i].isCreated())
  161. {
  162. // Fake that it's executed to avoid warnings
  163. static_cast<CommandBufferImpl&>(*m_queue[i]).makeExecuted();
  164. // Release
  165. m_queue[i] = CommandBufferPtr();
  166. }
  167. }
  168. // Cleanup GL
  169. m_manager->getState().destroy();
  170. // Cleanup
  171. glFinish();
  172. m_manager->pinContextToCurrentThread(false);
  173. }
  174. Error RenderingThread::threadCallback(ThreadCallbackInfo& info)
  175. {
  176. RenderingThread* thread = static_cast<RenderingThread*>(info.m_userData);
  177. thread->threadLoop();
  178. return Error::NONE;
  179. }
  180. void RenderingThread::threadLoop()
  181. {
  182. prepare();
  183. while(1)
  184. {
  185. CommandBufferPtr cmd;
  186. // Wait for something
  187. {
  188. LockGuard<Mutex> lock(m_mtx);
  189. while(m_tail == m_head)
  190. {
  191. m_condVar.wait(m_mtx);
  192. }
  193. // Check signals
  194. if(m_renderingThreadSignal == 1)
  195. {
  196. // Requested to stop
  197. break;
  198. }
  199. U64 idx = m_head % m_queue.getSize();
  200. // Pop a command
  201. cmd = m_queue[idx];
  202. m_queue[idx] = CommandBufferPtr(); // Insert empty cmd buffer
  203. ++m_head;
  204. }
  205. ANKI_TRACE_START_EVENT(GL_THREAD);
  206. Error err = static_cast<CommandBufferImpl&>(*cmd).executeAllCommands();
  207. ANKI_TRACE_STOP_EVENT(GL_THREAD);
  208. if(err)
  209. {
  210. ANKI_GL_LOGE("Error in rendering thread. Aborting");
  211. abort();
  212. }
  213. }
  214. finish();
  215. }
  216. void RenderingThread::syncClientServer()
  217. {
  218. // Lock because there is only one barrier. If multiple threads call
  219. // syncClientServer all of them will hit the same barrier.
  220. LockGuard<SpinLock> lock(m_syncLock);
  221. flushCommandBuffer(m_syncCommands, nullptr);
  222. m_syncBarrier.wait();
  223. }
  224. void RenderingThread::swapBuffersInternal()
  225. {
  226. ANKI_TRACE_START_EVENT(SWAP_BUFFERS);
  227. // Do the swap buffers
  228. m_manager->swapBuffers();
  229. // Notify the main thread that we are done
  230. {
  231. LockGuard<Mutex> lock(m_frameMtx);
  232. m_frameWait = false;
  233. m_frameCondVar.notifyOne();
  234. }
  235. ANKI_TRACE_STOP_EVENT(SWAP_BUFFERS);
  236. }
  237. void RenderingThread::swapBuffers()
  238. {
  239. ANKI_TRACE_START_EVENT(SWAP_BUFFERS);
  240. // Wait for the rendering thread to finish swap buffers...
  241. {
  242. LockGuard<Mutex> lock(m_frameMtx);
  243. while(m_frameWait)
  244. {
  245. m_frameCondVar.wait(m_frameMtx);
  246. }
  247. m_frameWait = true;
  248. }
  249. // ...and then flush a new swap buffers
  250. flushCommandBuffer(m_swapBuffersCommands, nullptr);
  251. ANKI_TRACE_STOP_EVENT(SWAP_BUFFERS);
  252. }
  253. } // end namespace anki