drawindirect.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*
  2. * Copyright 2022-2022 Liam Twigger. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. // Draw Indirect
  6. // Render multiple different objects with one draw command. This example shows a minimal implementation of indirect drawing
  7. // Reading References:
  8. // https://litasa.github.io/blog/2017/09/04/OpenGL-MultiDrawIndirect-with-Individual-Textures
  9. // https://cpp-rendering.io/indirect-rendering/
  10. #include "common.h"
  11. #include "bgfx_utils.h"
  12. #include "imgui/imgui.h"
  13. namespace
  14. {
  15. struct PosColorVertex
  16. {
  17. float m_x;
  18. float m_y;
  19. float m_z;
  20. uint32_t m_abgr;
  21. static void init()
  22. {
  23. ms_layout
  24. .begin()
  25. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  26. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  27. .end();
  28. };
  29. static bgfx::VertexLayout ms_layout;
  30. };
  31. bgfx::VertexLayout PosColorVertex::ms_layout;
  32. struct ObjectInstance {
  33. float m_vertexOffset;
  34. float m_vertexCount;
  35. float m_indexOffset;
  36. float m_indexCount;
  37. static void init()
  38. {
  39. ms_layout
  40. .begin()
  41. .add(bgfx::Attrib::TexCoord0, 4, bgfx::AttribType::Float)
  42. .end();
  43. };
  44. static bgfx::VertexLayout ms_layout;
  45. };
  46. bgfx::VertexLayout ObjectInstance::ms_layout;
  47. struct RenderInstance {
  48. float m_mtx[16];
  49. float m_color[4];
  50. static void init()
  51. {
  52. ms_layout
  53. .begin()
  54. .add(bgfx::Attrib::TexCoord0, 4, bgfx::AttribType::Float)
  55. .add(bgfx::Attrib::TexCoord1, 4, bgfx::AttribType::Float)
  56. .add(bgfx::Attrib::TexCoord2, 4, bgfx::AttribType::Float)
  57. .add(bgfx::Attrib::TexCoord3, 4, bgfx::AttribType::Float)
  58. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Float)
  59. .end();
  60. };
  61. static bgfx::VertexLayout ms_layout;
  62. };
  63. bgfx::VertexLayout RenderInstance::ms_layout;
  64. static PosColorVertex s_multiMeshVertices[12] =
  65. {
  66. // Cube Model
  67. {-1.0f, 1.0f, 1.0f, 0xff000000 },
  68. { 1.0f, 1.0f, 1.0f, 0xff0000ff },
  69. {-1.0f, -1.0f, 1.0f, 0xff00ff00 },
  70. { 1.0f, -1.0f, 1.0f, 0xff00ffff },
  71. {-1.0f, 1.0f, -1.0f, 0xffff0000 },
  72. { 1.0f, 1.0f, -1.0f, 0xffff00ff },
  73. {-1.0f, -1.0f, -1.0f, 0xffffff00 },
  74. { 1.0f, -1.0f, -1.0f, 0xffffffff },
  75. // Tetrahedron Model (offset = 8)
  76. { 1.0f, 1.0f, 1.0f, 0xff0000ff },
  77. { 1.0f, -1.0f, -1.0f, 0xff000000 },
  78. {-1.0f, 1.0f, -1.0f, 0xff00ff00 },
  79. {-1.0f, -1.0f, 1.0f, 0xff00ffff },
  80. };
  81. static const uint16_t s_multiMeshIndices[48] =
  82. {
  83. // Cube Indicies
  84. 0, 1, 2, // 0
  85. 1, 3, 2,
  86. 4, 6, 5, // 2
  87. 5, 6, 7,
  88. 0, 2, 4, // 4
  89. 4, 2, 6,
  90. 1, 5, 3, // 6
  91. 5, 7, 3,
  92. 0, 4, 1, // 8
  93. 4, 5, 1,
  94. 2, 3, 6, // 10
  95. 6, 3, 7,
  96. // Tetrahedron Indices (offset = 36)
  97. 0, 2, 1,
  98. 1, 2, 3,
  99. 0, 3, 2,
  100. 1, 3, 0,
  101. };
  102. static const uint32_t s_maxSideSize = 81;
  103. class DrawIndirect : public entry::AppI
  104. {
  105. public:
  106. DrawIndirect(const char* _name, const char* _description, const char* _url)
  107. : entry::AppI(_name, _description, _url)
  108. {
  109. }
  110. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  111. {
  112. Args args(_argc, _argv);
  113. m_width = _width;
  114. m_height = _height;
  115. m_debug = BGFX_DEBUG_TEXT;
  116. m_reset = BGFX_RESET_VSYNC;
  117. m_sideSize = 11;
  118. m_nDrawElements = s_maxSideSize*s_maxSideSize;
  119. m_useIndirectCount = false;
  120. bgfx::Init init;
  121. init.type = args.m_type;
  122. init.vendorId = args.m_pciId;
  123. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  124. init.platformData.ndt = entry::getNativeDisplayHandle();
  125. init.resolution.width = m_width;
  126. init.resolution.height = m_height;
  127. init.resolution.reset = m_reset;
  128. bgfx::init(init);
  129. // Enable debug text.
  130. bgfx::setDebug(m_debug);
  131. // Set view 0 clear state.
  132. bgfx::setViewClear(0
  133. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  134. , 0x303030ff
  135. , 1.0f
  136. , 0
  137. );
  138. // Create vertex stream declaration.
  139. PosColorVertex::init();
  140. ObjectInstance::init();
  141. RenderInstance::init();
  142. // Create static vertex buffer.
  143. m_vbh = bgfx::createVertexBuffer(
  144. bgfx::makeRef(s_multiMeshVertices, sizeof(s_multiMeshVertices) )
  145. , PosColorVertex::ms_layout
  146. );
  147. // Create static index buffer.
  148. m_ibh = bgfx::createIndexBuffer(
  149. bgfx::makeRef(s_multiMeshIndices, sizeof(s_multiMeshIndices) )
  150. );
  151. // Create program from shaders.
  152. m_program = loadProgram("vs_instancing", "fs_instancing"); // These are reused from 05-instancing
  153. m_indirect_program = BGFX_INVALID_HANDLE;
  154. m_indirect_count_program = BGFX_INVALID_HANDLE;
  155. m_indirect_buffer_handle = BGFX_INVALID_HANDLE;
  156. m_indirect_count_buffer_handle = BGFX_INVALID_HANDLE;
  157. m_object_list_buffer = BGFX_INVALID_HANDLE;
  158. u_drawParams = bgfx::createUniform("u_drawParams", bgfx::UniformType::Vec4);
  159. const bool computeSupported = !!(BGFX_CAPS_COMPUTE & bgfx::getCaps()->supported);
  160. const bool indirectSupported = !!(BGFX_CAPS_DRAW_INDIRECT & bgfx::getCaps()->supported);
  161. const bool instancingSupported = !!(BGFX_CAPS_INSTANCING & bgfx::getCaps()->supported);
  162. if (computeSupported && indirectSupported && instancingSupported)
  163. {
  164. // Set up indirect program
  165. // This is a barebones program that populates the indirect buffer handle with draw requests
  166. m_indirect_program = bgfx::createProgram(loadShader("cs_drawindirect"), true);
  167. m_indirect_buffer_handle = bgfx::createIndirectBuffer(m_nDrawElements);
  168. const bool indirectCountSupported = !!(BGFX_CAPS_DRAW_INDIRECT_COUNT & bgfx::getCaps()->supported);
  169. if (indirectCountSupported)
  170. {
  171. m_useIndirectCount = true;
  172. m_indirect_count_program = bgfx::createProgram(loadShader("cs_drawindirect_count"), true);
  173. const bgfx::Memory * mem = bgfx::alloc(sizeof(uint32_t));
  174. *(uint32_t *)mem->data = 0;
  175. m_indirect_count_buffer_handle = bgfx::createIndexBuffer(mem, BGFX_BUFFER_INDEX32 | BGFX_BUFFER_COMPUTE_WRITE | BGFX_BUFFER_DRAW_INDIRECT);
  176. }
  177. const bgfx::Memory * mem = bgfx::alloc(sizeof(ObjectInstance) * m_nDrawElements);
  178. ObjectInstance* objs = (ObjectInstance*) mem->data;
  179. for (uint32_t ii = 0; ii < m_nDrawElements; ++ii)
  180. {
  181. if (ii % 2)
  182. {
  183. // Tetrahedron
  184. objs[ii].m_vertexOffset = 8;
  185. objs[ii].m_vertexCount = 4; // m_vertexCount is unused in compute shader, its only here for completeness
  186. objs[ii].m_indexOffset = 36;
  187. objs[ii].m_indexCount = 12;
  188. }
  189. else
  190. {
  191. // Cube
  192. objs[ii].m_vertexOffset = 0;
  193. objs[ii].m_vertexCount = 8;
  194. objs[ii].m_indexOffset = 0;
  195. objs[ii].m_indexCount = 36;
  196. }
  197. }
  198. // This is a list of objects to be rendered via the indirect program
  199. m_object_list_buffer = bgfx::createVertexBuffer(mem, ObjectInstance::ms_layout, BGFX_BUFFER_COMPUTE_READ);
  200. // This is the instance buffer used for rendering.
  201. // You could instead use a dynamic instance buffer when rendering (use bgfx::allocInstanceDataBuffer in draw loop)
  202. m_instance_buffer = bgfx::createDynamicVertexBuffer(m_nDrawElements, RenderInstance::ms_layout, BGFX_BUFFER_COMPUTE_WRITE);
  203. }
  204. m_timeOffset = bx::getHPCounter();
  205. imguiCreate();
  206. }
  207. int shutdown() override
  208. {
  209. imguiDestroy();
  210. // Cleanup.
  211. bgfx::destroy(m_ibh);
  212. bgfx::destroy(m_vbh);
  213. bgfx::destroy(m_program);
  214. if (bgfx::isValid(m_indirect_program))
  215. {
  216. bgfx::destroy(m_indirect_program);
  217. }
  218. if (bgfx::isValid(m_indirect_count_program))
  219. {
  220. bgfx::destroy(m_indirect_count_program);
  221. }
  222. if (bgfx::isValid(m_indirect_buffer_handle))
  223. {
  224. bgfx::destroy(m_indirect_buffer_handle);
  225. }
  226. if (bgfx::isValid(m_indirect_count_buffer_handle))
  227. {
  228. bgfx::destroy(m_indirect_count_buffer_handle);
  229. }
  230. if (bgfx::isValid(m_object_list_buffer))
  231. {
  232. bgfx::destroy(m_object_list_buffer);
  233. }
  234. if (bgfx::isValid(m_instance_buffer))
  235. {
  236. bgfx::destroy(m_instance_buffer);
  237. }
  238. bgfx::destroy(u_drawParams);
  239. // Shutdown bgfx.
  240. bgfx::shutdown();
  241. return 0;
  242. }
  243. bool update() override
  244. {
  245. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  246. {
  247. // Get renderer capabilities info.
  248. const bool computeSupported = !!(BGFX_CAPS_COMPUTE & bgfx::getCaps()->supported);
  249. const bool indirectSupported = !!(BGFX_CAPS_DRAW_INDIRECT & bgfx::getCaps()->supported);
  250. const bool indirectCountSupported = !!(BGFX_CAPS_DRAW_INDIRECT_COUNT & bgfx::getCaps()->supported);
  251. const bool instancingSupported = !!(BGFX_CAPS_INSTANCING & bgfx::getCaps()->supported);
  252. imguiBeginFrame(m_mouseState.m_mx
  253. , m_mouseState.m_my
  254. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  255. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  256. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  257. , m_mouseState.m_mz
  258. , uint16_t(m_width)
  259. , uint16_t(m_height)
  260. );
  261. showExampleDialog(this);
  262. ImGui::SetNextWindowPos(
  263. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  264. , ImGuiCond_FirstUseEver
  265. );
  266. ImGui::SetNextWindowSize(
  267. ImVec2(m_width / 5.0f, m_height / 2.0f)
  268. , ImGuiCond_FirstUseEver
  269. );
  270. ImGui::Begin("Settings"
  271. , NULL
  272. , 0
  273. );
  274. ImGui::Text("%d draw calls", bgfx::getStats()->numDraw);
  275. ImGui::Text("%d objects drawn", m_sideSize*m_sideSize);
  276. ImGui::Text("Grid Side Size:");
  277. ImGui::SliderInt("##size", (int*)&m_sideSize, 1, s_maxSideSize);
  278. ImGui::BeginDisabled(!indirectCountSupported);
  279. ImGui::Checkbox("Indirect Count", &m_useIndirectCount);
  280. ImGui::EndDisabled();
  281. if (!indirectCountSupported && ImGui::IsItemHovered(ImGuiHoveredFlags_AllowWhenDisabled) )
  282. {
  283. ImGui::SetTooltip("Indirect Count is not supported by GPU.");
  284. }
  285. ImGui::End();
  286. imguiEndFrame();
  287. // Set view 0 default viewport.
  288. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  289. // This dummy draw call is here to make sure that view 0 is cleared
  290. // if no other draw calls are submitted to view 0.
  291. bgfx::touch(0);
  292. const bx::Vec3 at = { 0.0f, 0.0f, 0.0f };
  293. const bx::Vec3 eye = { 0.0f, 0.0f, -35.0f };
  294. // Set view and projection matrix for view 0.
  295. {
  296. float view[16];
  297. bx::mtxLookAt(view, eye, at);
  298. float proj[16];
  299. bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 500.0f, bgfx::getCaps()->homogeneousDepth);
  300. bgfx::setViewTransform(0, view, proj);
  301. // Set view 0 default viewport.
  302. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  303. }
  304. float time = (float)( (bx::getHPCounter() - m_timeOffset)/double(bx::getHPFrequency() ) );
  305. if (computeSupported && indirectSupported && instancingSupported)
  306. {
  307. // Build indirect buffer & prepare instance buffer
  308. // NOTE: IF you are rendering static data then
  309. // this could be done once on startup and results stored
  310. // This is done here for demonstration purposes
  311. // The model matrix for each instance is also set on compute
  312. // you could modify this to, eg, do frustrum culling on the GPU
  313. float ud[4] = { float(m_nDrawElements), float(m_sideSize), float(time), 0 };
  314. uint32_t numToDraw = (m_sideSize*m_sideSize);
  315. bgfx::setUniform(u_drawParams, ud);
  316. bgfx::setBuffer(0, m_object_list_buffer, bgfx::Access::Read);
  317. bgfx::setBuffer(1, m_indirect_buffer_handle, bgfx::Access::Write);
  318. bgfx::setBuffer(2, m_instance_buffer, bgfx::Access::Write);
  319. // Dispatch the call. We are using 64 local threads on the GPU to process the object list
  320. // So lets dispatch ceil(numToDraw/64) workgroups of 64 local threads
  321. if (m_useIndirectCount)
  322. {
  323. bgfx::setBuffer(3, m_indirect_count_buffer_handle, bgfx::Access::Write);
  324. bgfx::dispatch(0, m_indirect_count_program, uint32_t(numToDraw/64 + 1), 1, 1);
  325. }
  326. else
  327. {
  328. bgfx::dispatch(0, m_indirect_program, uint32_t(numToDraw/64 + 1), 1, 1);
  329. }
  330. // Submit our 1 draw call
  331. // Set vertex and index buffer.
  332. bgfx::setIndexBuffer(m_ibh);
  333. bgfx::setVertexBuffer(0, m_vbh);
  334. bgfx::setInstanceDataBuffer(m_instance_buffer, 0, numToDraw);
  335. // Set render states.
  336. bgfx::setState(BGFX_STATE_DEFAULT);
  337. // Submit primitive for rendering to view 0.
  338. if (m_useIndirectCount)
  339. {
  340. // With indirect count, the number of draws is read from a buffer
  341. bgfx::submit(0, m_program, m_indirect_buffer_handle, 0, m_indirect_count_buffer_handle);
  342. }
  343. else
  344. {
  345. bgfx::submit(0, m_program, m_indirect_buffer_handle, 0, uint16_t(numToDraw));
  346. }
  347. }
  348. else
  349. {
  350. // Compute/Indirect/Instancing is not supported
  351. bool blink = uint32_t(time*3.0f)&1;
  352. bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " Compute/Indirect/Instancing is not supported by GPU. ");
  353. }
  354. // Advance to next frame. Rendering thread will be kicked to
  355. // process submitted rendering primitives.
  356. bgfx::frame();
  357. return true;
  358. }
  359. return false;
  360. }
  361. entry::MouseState m_mouseState;
  362. uint32_t m_width;
  363. uint32_t m_height;
  364. uint32_t m_debug;
  365. uint32_t m_reset;
  366. uint32_t m_sideSize;
  367. uint32_t m_nDrawElements;
  368. bool m_useIndirectCount;
  369. bgfx::VertexBufferHandle m_vbh;
  370. bgfx::IndexBufferHandle m_ibh;
  371. bgfx::ProgramHandle m_program;
  372. bgfx::IndirectBufferHandle m_indirect_buffer_handle;
  373. bgfx::IndexBufferHandle m_indirect_count_buffer_handle;
  374. bgfx::ProgramHandle m_indirect_program;
  375. bgfx::ProgramHandle m_indirect_count_program;
  376. bgfx::VertexBufferHandle m_object_list_buffer;
  377. bgfx::DynamicVertexBufferHandle m_instance_buffer;
  378. bgfx::UniformHandle u_drawParams;
  379. int64_t m_timeOffset;
  380. };
  381. } // namespace
  382. ENTRY_IMPLEMENT_MAIN(
  383. DrawIndirect
  384. , "48-drawindirect"
  385. , "Simple example of indirect rendering to render multiple different meshes with 1 draw call"
  386. , "https://bkaradzic.github.io/bgfx/examples.html#drawindirect"
  387. );