drawindirect.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. bgfx::Init init;
  120. init.type = args.m_type;
  121. init.vendorId = args.m_pciId;
  122. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  123. init.platformData.ndt = entry::getNativeDisplayHandle();
  124. init.resolution.width = m_width;
  125. init.resolution.height = m_height;
  126. init.resolution.reset = m_reset;
  127. bgfx::init(init);
  128. // Enable debug text.
  129. bgfx::setDebug(m_debug);
  130. // Set view 0 clear state.
  131. bgfx::setViewClear(0
  132. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  133. , 0x303030ff
  134. , 1.0f
  135. , 0
  136. );
  137. // Create vertex stream declaration.
  138. PosColorVertex::init();
  139. ObjectInstance::init();
  140. RenderInstance::init();
  141. // Create static vertex buffer.
  142. m_vbh = bgfx::createVertexBuffer(
  143. bgfx::makeRef(s_multiMeshVertices, sizeof(s_multiMeshVertices) )
  144. , PosColorVertex::ms_layout
  145. );
  146. // Create static index buffer.
  147. m_ibh = bgfx::createIndexBuffer(
  148. bgfx::makeRef(s_multiMeshIndices, sizeof(s_multiMeshIndices) )
  149. );
  150. // Create program from shaders.
  151. m_program = loadProgram("vs_instancing", "fs_instancing"); // These are reused from 05-instancing
  152. m_indirect_program = BGFX_INVALID_HANDLE;
  153. m_indirect_buffer_handle = BGFX_INVALID_HANDLE;
  154. m_object_list_buffer = BGFX_INVALID_HANDLE;
  155. u_drawParams = bgfx::createUniform("u_drawParams", bgfx::UniformType::Vec4);
  156. const bool computeSupported = !!(BGFX_CAPS_DRAW_INDIRECT & bgfx::getCaps()->supported);
  157. const bool instancingSupported = !!(BGFX_CAPS_INSTANCING & bgfx::getCaps()->supported);
  158. if (computeSupported && instancingSupported)
  159. {
  160. // Set up indirect program
  161. // This is a barebones program that populates the indirect buffer handle with draw requests
  162. m_indirect_program = bgfx::createProgram(loadShader("cs_drawindirect"), true);
  163. m_indirect_buffer_handle = bgfx::createIndirectBuffer(m_nDrawElements);
  164. const bgfx::Memory * mem = bgfx::alloc(sizeof(ObjectInstance) * m_nDrawElements);
  165. ObjectInstance* objs = (ObjectInstance*) mem->data;
  166. for (uint32_t ii = 0; ii < m_nDrawElements; ++ii)
  167. {
  168. if (ii % 2)
  169. {
  170. // Tetrahedron
  171. objs[ii].m_vertexOffset = 8;
  172. objs[ii].m_vertexCount = 4; // m_vertexCount is unused in compute shader, its only here for completeness
  173. objs[ii].m_indexOffset = 36;
  174. objs[ii].m_indexCount = 12;
  175. }
  176. else
  177. {
  178. // Cube
  179. objs[ii].m_vertexOffset = 0;
  180. objs[ii].m_vertexCount = 8;
  181. objs[ii].m_indexOffset = 0;
  182. objs[ii].m_indexCount = 36;
  183. }
  184. }
  185. // This is a list of objects to be rendered via the indirect program
  186. m_object_list_buffer = bgfx::createVertexBuffer(mem, ObjectInstance::ms_layout, BGFX_BUFFER_COMPUTE_READ);
  187. // This is the instance buffer used for rendering.
  188. // You could instead use a dynamic instance buffer when rendering (use bgfx::allocInstanceDataBuffer in draw loop)
  189. m_instance_buffer = bgfx::createDynamicVertexBuffer(m_nDrawElements, RenderInstance::ms_layout, BGFX_BUFFER_COMPUTE_WRITE);
  190. }
  191. m_timeOffset = bx::getHPCounter();
  192. imguiCreate();
  193. }
  194. int shutdown() override
  195. {
  196. imguiDestroy();
  197. // Cleanup.
  198. bgfx::destroy(m_ibh);
  199. bgfx::destroy(m_vbh);
  200. bgfx::destroy(m_program);
  201. if (bgfx::isValid(m_indirect_program))
  202. {
  203. bgfx::destroy(m_indirect_program);
  204. }
  205. if (bgfx::isValid(m_indirect_buffer_handle))
  206. {
  207. bgfx::destroy(m_indirect_buffer_handle);
  208. }
  209. if (bgfx::isValid(m_object_list_buffer))
  210. {
  211. bgfx::destroy(m_object_list_buffer);
  212. }
  213. if (bgfx::isValid(m_instance_buffer))
  214. {
  215. bgfx::destroy(m_instance_buffer);
  216. }
  217. bgfx::destroy(u_drawParams);
  218. // Shutdown bgfx.
  219. bgfx::shutdown();
  220. return 0;
  221. }
  222. bool update() override
  223. {
  224. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  225. {
  226. imguiBeginFrame(m_mouseState.m_mx
  227. , m_mouseState.m_my
  228. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  229. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  230. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  231. , m_mouseState.m_mz
  232. , uint16_t(m_width)
  233. , uint16_t(m_height)
  234. );
  235. showExampleDialog(this);
  236. ImGui::SetNextWindowPos(
  237. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  238. , ImGuiCond_FirstUseEver
  239. );
  240. ImGui::SetNextWindowSize(
  241. ImVec2(m_width / 5.0f, m_height / 2.0f)
  242. , ImGuiCond_FirstUseEver
  243. );
  244. ImGui::Begin("Settings"
  245. , NULL
  246. , 0
  247. );
  248. ImGui::Text("%d draw calls", bgfx::getStats()->numDraw);
  249. ImGui::Text("%d objects drawn", m_sideSize*m_sideSize);
  250. ImGui::Text("Grid Side Size:");
  251. ImGui::SliderInt("##size", (int*)&m_sideSize, 1, s_maxSideSize);
  252. ImGui::End();
  253. imguiEndFrame();
  254. // Set view 0 default viewport.
  255. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  256. // This dummy draw call is here to make sure that view 0 is cleared
  257. // if no other draw calls are submitted to view 0.
  258. bgfx::touch(0);
  259. const bx::Vec3 at = { 0.0f, 0.0f, 0.0f };
  260. const bx::Vec3 eye = { 0.0f, 0.0f, -35.0f };
  261. // Set view and projection matrix for view 0.
  262. {
  263. float view[16];
  264. bx::mtxLookAt(view, eye, at);
  265. float proj[16];
  266. bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 500.0f, bgfx::getCaps()->homogeneousDepth);
  267. bgfx::setViewTransform(0, view, proj);
  268. // Set view 0 default viewport.
  269. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  270. }
  271. float time = (float)( (bx::getHPCounter() - m_timeOffset)/double(bx::getHPFrequency() ) );
  272. // Get renderer capabilities info.
  273. const bool computeSupported = !!(BGFX_CAPS_DRAW_INDIRECT & bgfx::getCaps()->supported);
  274. const bool instancingSupported = !!(BGFX_CAPS_INSTANCING & bgfx::getCaps()->supported);
  275. if (computeSupported && instancingSupported)
  276. {
  277. // Build indirect buffer & prepare instance buffer
  278. // NOTE: IF you are rendering static data then
  279. // this could be done once on startup and results stored
  280. // This is done here for demonstration purposes
  281. // The model matrix for each instance is also set on compute
  282. // you could modify this to, eg, do frustrum culling on the GPU
  283. float ud[4] = { float(m_nDrawElements), float(m_sideSize), float(time), 0 };
  284. bgfx::setUniform(u_drawParams, ud);
  285. bgfx::setBuffer(0, m_object_list_buffer, bgfx::Access::Read);
  286. bgfx::setBuffer(1, m_indirect_buffer_handle, bgfx::Access::Write);
  287. bgfx::setBuffer(2, m_instance_buffer, bgfx::Access::Write);
  288. bgfx::dispatch(0, m_indirect_program);
  289. // Submit our 1 draw call
  290. // Set vertex and index buffer.
  291. bgfx::setIndexBuffer(m_ibh);
  292. bgfx::setVertexBuffer(0, m_vbh);
  293. bgfx::setInstanceDataBuffer(m_instance_buffer, 0, m_sideSize*m_sideSize);
  294. // Set render states.
  295. bgfx::setState(BGFX_STATE_DEFAULT);
  296. // Submit primitive for rendering to view 0.
  297. // note that this submission requires the draw count
  298. bgfx::submit(0, m_program, m_indirect_buffer_handle, 0, uint16_t(m_sideSize*m_sideSize));
  299. }
  300. else
  301. {
  302. // Compute/Instancing is not supported
  303. bool blink = uint32_t(time*3.0f)&1;
  304. bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " Compute/Instancing is not supported by GPU. ");
  305. }
  306. // Advance to next frame. Rendering thread will be kicked to
  307. // process submitted rendering primitives.
  308. bgfx::frame();
  309. return true;
  310. }
  311. return false;
  312. }
  313. entry::MouseState m_mouseState;
  314. uint32_t m_width;
  315. uint32_t m_height;
  316. uint32_t m_debug;
  317. uint32_t m_reset;
  318. uint32_t m_sideSize;
  319. uint32_t m_nDrawElements;
  320. bgfx::VertexBufferHandle m_vbh;
  321. bgfx::IndexBufferHandle m_ibh;
  322. bgfx::ProgramHandle m_program;
  323. bgfx::IndirectBufferHandle m_indirect_buffer_handle;
  324. bgfx::ProgramHandle m_indirect_program;
  325. bgfx::VertexBufferHandle m_object_list_buffer;
  326. bgfx::DynamicVertexBufferHandle m_instance_buffer;
  327. bgfx::UniformHandle u_drawParams;
  328. int64_t m_timeOffset;
  329. };
  330. } // namespace
  331. ENTRY_IMPLEMENT_MAIN(
  332. DrawIndirect
  333. , "48-drawindirect"
  334. , "Simple example of indirect rendering to render multiple different meshes with 1 draw call"
  335. , "https://bkaradzic.github.io/bgfx/examples.html#drawindirect"
  336. );