RenderingThread.cpp 6.9 KB

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