RenderingThread.cpp 6.9 KB

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