instancing.cpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. /*
  2. * Copyright 2011-2025 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include "common.h"
  6. #include "bgfx_utils.h"
  7. #include "imgui/imgui.h"
  8. namespace
  9. {
  10. struct PosColorVertex
  11. {
  12. float m_x;
  13. float m_y;
  14. float m_z;
  15. uint32_t m_abgr;
  16. static void init()
  17. {
  18. ms_layout
  19. .begin()
  20. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  21. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  22. .end();
  23. };
  24. static bgfx::VertexLayout ms_layout;
  25. };
  26. bgfx::VertexLayout PosColorVertex::ms_layout;
  27. static PosColorVertex s_cubeVertices[8] =
  28. {
  29. {-1.0f, 1.0f, 1.0f, 0xff000000 },
  30. { 1.0f, 1.0f, 1.0f, 0xff0000ff },
  31. {-1.0f, -1.0f, 1.0f, 0xff00ff00 },
  32. { 1.0f, -1.0f, 1.0f, 0xff00ffff },
  33. {-1.0f, 1.0f, -1.0f, 0xffff0000 },
  34. { 1.0f, 1.0f, -1.0f, 0xffff00ff },
  35. {-1.0f, -1.0f, -1.0f, 0xffffff00 },
  36. { 1.0f, -1.0f, -1.0f, 0xffffffff },
  37. };
  38. static const uint16_t s_cubeIndices[36] =
  39. {
  40. 0, 1, 2, // 0
  41. 1, 3, 2,
  42. 4, 6, 5, // 2
  43. 5, 6, 7,
  44. 0, 2, 4, // 4
  45. 4, 2, 6,
  46. 1, 5, 3, // 6
  47. 5, 7, 3,
  48. 0, 4, 1, // 8
  49. 4, 5, 1,
  50. 2, 3, 6, // 10
  51. 6, 3, 7,
  52. };
  53. class ExampleInstancing : public entry::AppI
  54. {
  55. public:
  56. ExampleInstancing(const char* _name, const char* _description, const char* _url)
  57. : entry::AppI(_name, _description, _url)
  58. {
  59. }
  60. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  61. {
  62. Args args(_argc, _argv);
  63. m_width = _width;
  64. m_height = _height;
  65. m_debug = BGFX_DEBUG_TEXT;
  66. m_reset = BGFX_RESET_VSYNC;
  67. m_useInstancing = true;
  68. m_lastFrameMissing = 0;
  69. m_sideSize = 11;
  70. bgfx::Init init;
  71. init.type = args.m_type;
  72. init.vendorId = args.m_pciId;
  73. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  74. init.platformData.ndt = entry::getNativeDisplayHandle();
  75. init.platformData.type = entry::getNativeWindowHandleType();
  76. init.resolution.width = m_width;
  77. init.resolution.height = m_height;
  78. init.resolution.reset = m_reset;
  79. bgfx::init(init);
  80. // Enable debug text.
  81. bgfx::setDebug(m_debug);
  82. // Set view 0 clear state.
  83. bgfx::setViewClear(0
  84. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  85. , 0x303030ff
  86. , 1.0f
  87. , 0
  88. );
  89. // Create vertex stream declaration.
  90. PosColorVertex::init();
  91. // Create static vertex buffer.
  92. m_vbh = bgfx::createVertexBuffer(
  93. bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
  94. , PosColorVertex::ms_layout
  95. );
  96. // Create static index buffer.
  97. m_ibh = bgfx::createIndexBuffer(
  98. bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) )
  99. );
  100. // Create program from shaders.
  101. m_program = loadProgram("vs_instancing", "fs_instancing");
  102. m_program_non_instanced = loadProgram("vs_cubes", "fs_cubes");
  103. m_timeOffset = bx::getHPCounter();
  104. imguiCreate();
  105. }
  106. int shutdown() override
  107. {
  108. imguiDestroy();
  109. // Cleanup.
  110. bgfx::destroy(m_ibh);
  111. bgfx::destroy(m_vbh);
  112. bgfx::destroy(m_program);
  113. bgfx::destroy(m_program_non_instanced);
  114. // Shutdown bgfx.
  115. bgfx::shutdown();
  116. return 0;
  117. }
  118. bool update() override
  119. {
  120. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  121. {
  122. imguiBeginFrame(m_mouseState.m_mx
  123. , m_mouseState.m_my
  124. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  125. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  126. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  127. , m_mouseState.m_mz
  128. , uint16_t(m_width)
  129. , uint16_t(m_height)
  130. );
  131. showExampleDialog(this);
  132. ImGui::SetNextWindowPos(
  133. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  134. , ImGuiCond_FirstUseEver
  135. );
  136. ImGui::SetNextWindowSize(
  137. ImVec2(m_width / 5.0f, m_height / 2.0f)
  138. , ImGuiCond_FirstUseEver
  139. );
  140. ImGui::Begin("Settings"
  141. , NULL
  142. , 0
  143. );
  144. // Get renderer capabilities info.
  145. const bgfx::Caps* caps = bgfx::getCaps();
  146. // Check if instancing is supported.
  147. const bool instancingSupported = 0 != (BGFX_CAPS_INSTANCING & caps->supported);
  148. m_useInstancing &= instancingSupported;
  149. ImGui::Text("%d draw calls", bgfx::getStats()->numDraw);
  150. ImGui::PushEnabled(instancingSupported);
  151. ImGui::Checkbox("Use Instancing", &m_useInstancing);
  152. ImGui::PopEnabled();
  153. ImGui::Text("Grid Side Size:");
  154. ImGui::SliderInt("##size", (int*)&m_sideSize, 1, 512);
  155. if (m_lastFrameMissing > 0)
  156. {
  157. ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "Couldn't draw %d cubes last frame", m_lastFrameMissing);
  158. }
  159. if (bgfx::getStats()->numDraw >= bgfx::getCaps()->limits.maxDrawCalls)
  160. {
  161. ImGui::TextColored(ImVec4(1.0f, 0.0f, 0.0f, 1.0f), "Draw call limit reached!");
  162. }
  163. ImGui::End();
  164. imguiEndFrame();
  165. // Set view 0 default viewport.
  166. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  167. // This dummy draw call is here to make sure that view 0 is cleared
  168. // if no other draw calls are submitted to view 0.
  169. bgfx::touch(0);
  170. float time = (float)( (bx::getHPCounter() - m_timeOffset)/double(bx::getHPFrequency() ) );
  171. if (!instancingSupported)
  172. {
  173. // When instancing is not supported by GPU, implement alternative
  174. // code path that doesn't use instancing.
  175. bool blink = uint32_t(time*3.0f)&1;
  176. bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " Instancing is not supported by GPU. ");
  177. m_useInstancing = false;
  178. }
  179. const bx::Vec3 at = { 0.0f, 0.0f, 0.0f };
  180. const bx::Vec3 eye = { 0.0f, 0.0f, -35.0f };
  181. // Set view and projection matrix for view 0.
  182. {
  183. float view[16];
  184. bx::mtxLookAt(view, eye, at);
  185. float proj[16];
  186. bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  187. bgfx::setViewTransform(0, view, proj);
  188. // Set view 0 default viewport.
  189. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  190. }
  191. m_lastFrameMissing = 0;
  192. if (m_useInstancing)
  193. {
  194. // 80 bytes stride = 64 bytes for 4x4 matrix + 16 bytes for RGBA color.
  195. const uint16_t instanceStride = 80;
  196. // to total number of instances to draw
  197. uint32_t totalCubes = m_sideSize * m_sideSize;
  198. // figure out how big of a buffer is available
  199. uint32_t drawnCubes = bgfx::getAvailInstanceDataBuffer(totalCubes, instanceStride);
  200. // save how many we couldn't draw due to buffer room so we can display it
  201. m_lastFrameMissing = totalCubes - drawnCubes;
  202. bgfx::InstanceDataBuffer idb;
  203. bgfx::allocInstanceDataBuffer(&idb, drawnCubes, instanceStride);
  204. uint8_t* data = idb.data;
  205. for (uint32_t ii = 0; ii < drawnCubes; ++ii)
  206. {
  207. uint32_t yy = ii / m_sideSize;
  208. uint32_t xx = ii % m_sideSize;
  209. float* mtx = (float*)data;
  210. bx::mtxRotateXY(mtx, time + xx * 0.21f, time + yy * 0.37f);
  211. mtx[12] = -15.0f + float(xx) * 3.0f;
  212. mtx[13] = -15.0f + float(yy) * 3.0f;
  213. mtx[14] = 0.0f;
  214. float* color = (float*)&data[64];
  215. color[0] = bx::sin(time + float(xx) / 11.0f) * 0.5f + 0.5f;
  216. color[1] = bx::cos(time + float(yy) / 11.0f) * 0.5f + 0.5f;
  217. color[2] = bx::sin(time * 3.0f) * 0.5f + 0.5f;
  218. color[3] = 1.0f;
  219. data += instanceStride;
  220. }
  221. // Set vertex and index buffer.
  222. bgfx::setVertexBuffer(0, m_vbh);
  223. bgfx::setIndexBuffer(m_ibh);
  224. // Set instance data buffer.
  225. bgfx::setInstanceDataBuffer(&idb);
  226. // Set render states.
  227. bgfx::setState(BGFX_STATE_DEFAULT);
  228. // Submit primitive for rendering to view 0.
  229. bgfx::submit(0, m_program);
  230. }
  231. else
  232. {
  233. // non-instanced path
  234. for (uint32_t yy = 0; yy < m_sideSize; ++yy)
  235. {
  236. for (uint32_t xx = 0; xx < m_sideSize; ++xx)
  237. {
  238. float mtx[16];
  239. bx::mtxRotateXY(mtx, time + xx * 0.21f, time + yy * 0.37f);
  240. mtx[12] = -15.0f + float(xx) * 3.0f;
  241. mtx[13] = -15.0f + float(yy) * 3.0f;
  242. mtx[14] = 0.0f;
  243. // Set model matrix for rendering.
  244. bgfx::setTransform(mtx);
  245. // Set vertex and index buffer.
  246. bgfx::setVertexBuffer(0, m_vbh);
  247. bgfx::setIndexBuffer(m_ibh);
  248. // Set render states.
  249. bgfx::setState(BGFX_STATE_DEFAULT);
  250. // Submit primitive for rendering to view 0.
  251. bgfx::submit(0, m_program_non_instanced);
  252. }
  253. }
  254. }
  255. // Advance to next frame. Rendering thread will be kicked to
  256. // process submitted rendering primitives.
  257. bgfx::frame();
  258. return true;
  259. }
  260. return false;
  261. }
  262. entry::MouseState m_mouseState;
  263. uint32_t m_width;
  264. uint32_t m_height;
  265. uint32_t m_debug;
  266. uint32_t m_reset;
  267. bool m_useInstancing;
  268. uint32_t m_lastFrameMissing;
  269. uint32_t m_sideSize;
  270. bgfx::VertexBufferHandle m_vbh;
  271. bgfx::IndexBufferHandle m_ibh;
  272. bgfx::ProgramHandle m_program;
  273. bgfx::ProgramHandle m_program_non_instanced;
  274. int64_t m_timeOffset;
  275. };
  276. } // namespace
  277. ENTRY_IMPLEMENT_MAIN(
  278. ExampleInstancing
  279. , "05-instancing"
  280. , "Geometry instancing."
  281. , "https://bkaradzic.github.io/bgfx/examples.html#instancing"
  282. );