nbody.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462
  1. /*
  2. * Copyright 2014 Stanlo Slasinski. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "common.h"
  6. #include "bgfx_utils.h"
  7. #include "imgui/imgui.h"
  8. #include "camera.h"
  9. #include <bgfx/bgfx.h>
  10. namespace
  11. {
  12. static const char* s_shapeNames[] =
  13. {
  14. "Point",
  15. "Sphere",
  16. "Box",
  17. "Donut"
  18. };
  19. struct ParamsData
  20. {
  21. float timeStep;
  22. int32_t dispatchSize;
  23. float gravity;
  24. float damping;
  25. float particleIntensity;
  26. float particleSize;
  27. int32_t baseSeed;
  28. float particlePower;
  29. float initialSpeed;
  30. int32_t initialShape;
  31. float maxAccel;
  32. };
  33. void initializeParams(int32_t _mode, ParamsData* _params)
  34. {
  35. switch(_mode)
  36. {
  37. case 0:
  38. _params->timeStep = 0.0067f;
  39. _params->dispatchSize = 32;
  40. _params->gravity = 0.069f;
  41. _params->damping = 0.0f;
  42. _params->particleIntensity = 0.35f;
  43. _params->particleSize = 0.925f;
  44. _params->baseSeed = 0;
  45. _params->particlePower = 5.0f;
  46. _params->initialSpeed = 122.6f;
  47. _params->initialShape = 0;
  48. _params->maxAccel = 30.0;
  49. break;
  50. case 1:
  51. _params->timeStep = 0.0157f;
  52. _params->dispatchSize = 32;
  53. _params->gravity = 0.109f;
  54. _params->damping = 0.25f;
  55. _params->particleIntensity = 0.64f;
  56. _params->particleSize = 0.279f;
  57. _params->baseSeed = 57;
  58. _params->particlePower = 3.5f;
  59. _params->initialSpeed = 3.2f;
  60. _params->initialShape = 1;
  61. _params->maxAccel = 100.0;
  62. break;
  63. case 2:
  64. _params->timeStep = 0.02f;
  65. _params->dispatchSize = 32;
  66. _params->gravity = 0.24f;
  67. _params->damping = 0.12f;
  68. _params->particleIntensity = 1.0f;
  69. _params->particleSize = 1.0f;
  70. _params->baseSeed = 23;
  71. _params->particlePower = 4.0f;
  72. _params->initialSpeed = 31.1f;
  73. _params->initialShape = 2;
  74. _params->maxAccel = 39.29f;
  75. break;
  76. case 3:
  77. _params->timeStep = 0.0118f;
  78. _params->dispatchSize = 32;
  79. _params->gravity = 0.141f;
  80. _params->damping = 1.0f;
  81. _params->particleIntensity = 0.64f;
  82. _params->particleSize = 0.28f;
  83. _params->baseSeed = 60;
  84. _params->particlePower = 1.97f;
  85. _params->initialSpeed = 69.7f;
  86. _params->initialShape = 3;
  87. _params->maxAccel = 3.21f;
  88. break;
  89. }
  90. }
  91. static const float s_quadVertices[] =
  92. {
  93. 1.0f, 1.0f,
  94. -1.0f, 1.0f,
  95. -1.0f, -1.0f,
  96. 1.0f, -1.0f,
  97. };
  98. static const uint16_t s_quadIndices[] = { 0, 1, 2, 2, 3, 0, };
  99. const uint32_t kThreadGroupUpdateSize = 512;
  100. const uint32_t kMaxParticleCount = 32 * 1024;
  101. class ExampleNbody : public entry::AppI
  102. {
  103. public:
  104. ExampleNbody(const char* _name, const char* _description)
  105. : entry::AppI(_name, _description)
  106. {
  107. }
  108. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  109. {
  110. Args args(_argc, _argv);
  111. m_width = _width;
  112. m_height = _height;
  113. m_debug = BGFX_DEBUG_NONE;
  114. m_reset = BGFX_RESET_VSYNC;
  115. bgfx::Init init;
  116. init.type = args.m_type;
  117. init.vendorId = args.m_pciId;
  118. init.resolution.width = m_width;
  119. init.resolution.height = m_height;
  120. init.resolution.reset = m_reset;
  121. bgfx::init(init);
  122. // Enable debug text.
  123. bgfx::setDebug(m_debug);
  124. // Set view 0 clear state.
  125. bgfx::setViewClear(0
  126. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  127. , 0x303030ff
  128. , 1.0f
  129. , 0
  130. );
  131. const bgfx::Caps* caps = bgfx::getCaps();
  132. m_computeSupported = !!(caps->supported & BGFX_CAPS_COMPUTE);
  133. m_indirectSupported = !!(caps->supported & BGFX_CAPS_DRAW_INDIRECT);
  134. imguiCreate();
  135. if (m_computeSupported)
  136. {
  137. bgfx::VertexDecl quadVertexDecl;
  138. quadVertexDecl.begin()
  139. .add(bgfx::Attrib::Position, 2, bgfx::AttribType::Float)
  140. .end();
  141. // Create static vertex buffer.
  142. m_vbh = bgfx::createVertexBuffer(
  143. // Static data can be passed with bgfx::makeRef
  144. bgfx::makeRef(s_quadVertices, sizeof(s_quadVertices) )
  145. , quadVertexDecl
  146. );
  147. // Create static index buffer.
  148. m_ibh = bgfx::createIndexBuffer(
  149. // Static data can be passed with bgfx::makeRef
  150. bgfx::makeRef(s_quadIndices, sizeof(s_quadIndices) )
  151. );
  152. // Create particle program from shaders.
  153. m_particleProgram = loadProgram("vs_particle", "fs_particle");
  154. // Setup compute buffers
  155. bgfx::VertexDecl computeVertexDecl;
  156. computeVertexDecl.begin()
  157. .add(bgfx::Attrib::TexCoord0, 4, bgfx::AttribType::Float)
  158. .end();
  159. m_currPositionBuffer0 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE);
  160. m_currPositionBuffer1 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE);
  161. m_prevPositionBuffer0 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE);
  162. m_prevPositionBuffer1 = bgfx::createDynamicVertexBuffer(1 << 15, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ_WRITE);
  163. u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, 3);
  164. m_initInstancesProgram = bgfx::createProgram(loadShader("cs_init_instances"), true);
  165. m_updateInstancesProgram = bgfx::createProgram(loadShader("cs_update_instances"), true);
  166. m_indirectProgram = BGFX_INVALID_HANDLE;
  167. m_indirectBuffer = BGFX_INVALID_HANDLE;
  168. if (m_indirectSupported)
  169. {
  170. m_indirectProgram = bgfx::createProgram(loadShader("cs_indirect"), true);
  171. m_indirectBuffer = bgfx::createIndirectBuffer(2);
  172. }
  173. initializeParams(0, &m_paramsData);
  174. bgfx::setUniform(u_params, &m_paramsData, 3);
  175. bgfx::setBuffer(0, m_prevPositionBuffer0, bgfx::Access::Write);
  176. bgfx::setBuffer(1, m_currPositionBuffer0, bgfx::Access::Write);
  177. bgfx::dispatch(0, m_initInstancesProgram, kMaxParticleCount / kThreadGroupUpdateSize, 1, 1);
  178. float initialPos[3] = { 0.0f, 0.0f, -45.0f };
  179. cameraCreate();
  180. cameraSetPosition(initialPos);
  181. cameraSetVerticalAngle(0.0f);
  182. m_useIndirect = false;
  183. m_timeOffset = bx::getHPCounter();
  184. }
  185. }
  186. virtual int shutdown() override
  187. {
  188. // Cleanup.
  189. cameraDestroy();
  190. imguiDestroy();
  191. if (m_computeSupported)
  192. {
  193. if (m_indirectSupported)
  194. {
  195. bgfx::destroy(m_indirectProgram);
  196. bgfx::destroy(m_indirectBuffer);
  197. }
  198. bgfx::destroy(u_params);
  199. bgfx::destroy(m_currPositionBuffer0);
  200. bgfx::destroy(m_currPositionBuffer1);
  201. bgfx::destroy(m_prevPositionBuffer0);
  202. bgfx::destroy(m_prevPositionBuffer1);
  203. bgfx::destroy(m_updateInstancesProgram);
  204. bgfx::destroy(m_initInstancesProgram);
  205. bgfx::destroy(m_ibh);
  206. bgfx::destroy(m_vbh);
  207. bgfx::destroy(m_particleProgram);
  208. }
  209. // Shutdown bgfx.
  210. bgfx::shutdown();
  211. return 0;
  212. }
  213. bool update() override
  214. {
  215. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  216. {
  217. imguiBeginFrame(
  218. m_mouseState.m_mx
  219. , m_mouseState.m_my
  220. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  221. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  222. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  223. , m_mouseState.m_mz
  224. , uint16_t(m_width)
  225. , uint16_t(m_height)
  226. );
  227. showExampleDialog(this
  228. , !m_computeSupported
  229. ? "Compute is not supported."
  230. : NULL
  231. );
  232. int64_t now = bx::getHPCounter();
  233. static int64_t last = now;
  234. const int64_t frameTime = now - last;
  235. last = now;
  236. const double freq = double(bx::getHPFrequency() );
  237. const float deltaTime = float(frameTime/freq);
  238. // Set view 0 default viewport.
  239. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  240. if (m_computeSupported)
  241. {
  242. ImGui::SetNextWindowPos(
  243. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  244. , ImGuiCond_FirstUseEver
  245. );
  246. ImGui::SetNextWindowSize(
  247. ImVec2(m_width / 5.0f, m_height / 1.5f)
  248. , ImGuiCond_FirstUseEver
  249. );
  250. ImGui::Begin("Settings"
  251. , NULL
  252. , 0
  253. );
  254. bool reset = false;
  255. int32_t shape = m_paramsData.initialShape;
  256. if (ImGui::Combo("Initial shape", &shape, s_shapeNames, BX_COUNTOF(s_shapeNames) ) )
  257. {
  258. // Modify parameters and reset if shape is changed
  259. initializeParams(shape, &m_paramsData);
  260. reset = true;
  261. }
  262. ImGui::SliderInt("Random seed", &m_paramsData.baseSeed, 0, 100);
  263. if (ImGui::Button("Reset") )
  264. {
  265. reset = true;
  266. }
  267. ImGui::Separator();
  268. ImGui::SliderInt("Particle count (x512)", &m_paramsData.dispatchSize, 1, 64);
  269. ImGui::SliderFloat("Gravity", &m_paramsData.gravity, 0.0f, 0.3f);
  270. ImGui::SliderFloat("Damping", &m_paramsData.damping, 0.0f, 1.0f);
  271. ImGui::SliderFloat("Max acceleration", &m_paramsData.maxAccel, 0.0f, 100.0f);
  272. ImGui::SliderFloat("Time step", &m_paramsData.timeStep, 0.0f, 0.02f);
  273. ImGui::Separator();
  274. ImGui::SliderFloat("Particle intensity", &m_paramsData.particleIntensity, 0.0f, 1.0f);
  275. ImGui::SliderFloat("Particle size", &m_paramsData.particleSize, 0.0f, 1.0f);
  276. ImGui::SliderFloat("Particle power", &m_paramsData.particlePower, 0.001f, 16.0f);
  277. ImGui::Separator();
  278. if (m_indirectSupported)
  279. {
  280. ImGui::Checkbox("Use draw/dispatch indirect", &m_useIndirect);
  281. }
  282. ImGui::End();
  283. if (reset)
  284. {
  285. bgfx::setBuffer(0, m_prevPositionBuffer0, bgfx::Access::Write);
  286. bgfx::setBuffer(1, m_currPositionBuffer0, bgfx::Access::Write);
  287. bgfx::setUniform(u_params, &m_paramsData, 3);
  288. bgfx::dispatch(0, m_initInstancesProgram, kMaxParticleCount / kThreadGroupUpdateSize, 1, 1);
  289. }
  290. if (m_useIndirect)
  291. {
  292. bgfx::setUniform(u_params, &m_paramsData, 3);
  293. bgfx::setBuffer(0, m_indirectBuffer, bgfx::Access::Write);
  294. bgfx::dispatch(0, m_indirectProgram);
  295. }
  296. bgfx::setBuffer(0, m_prevPositionBuffer0, bgfx::Access::Read);
  297. bgfx::setBuffer(1, m_currPositionBuffer0, bgfx::Access::Read);
  298. bgfx::setBuffer(2, m_prevPositionBuffer1, bgfx::Access::Write);
  299. bgfx::setBuffer(3, m_currPositionBuffer1, bgfx::Access::Write);
  300. bgfx::setUniform(u_params, &m_paramsData, 3);
  301. if (m_useIndirect)
  302. {
  303. bgfx::dispatch(0, m_updateInstancesProgram, m_indirectBuffer, 1);
  304. }
  305. else
  306. {
  307. bgfx::dispatch(0, m_updateInstancesProgram, uint16_t(m_paramsData.dispatchSize), 1, 1);
  308. }
  309. bx::xchg(m_currPositionBuffer0, m_currPositionBuffer1);
  310. bx::xchg(m_prevPositionBuffer0, m_prevPositionBuffer1);
  311. // Update camera.
  312. cameraUpdate(deltaTime, m_mouseState);
  313. float view[16];
  314. cameraGetViewMtx(view);
  315. // Set view and projection matrix for view 0.
  316. {
  317. float proj[16];
  318. bx::mtxProj(
  319. proj
  320. , 90.0f
  321. , float(m_width)/float(m_height)
  322. , 0.1f
  323. , 10000.0f
  324. , bgfx::getCaps()->homogeneousDepth
  325. );
  326. bgfx::setViewTransform(0, view, proj);
  327. // Set view 0 default viewport.
  328. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  329. }
  330. // Set vertex and index buffer.
  331. bgfx::setVertexBuffer(0, m_vbh);
  332. bgfx::setIndexBuffer(m_ibh);
  333. bgfx::setInstanceDataBuffer(m_currPositionBuffer0
  334. , 0
  335. , m_paramsData.dispatchSize * kThreadGroupUpdateSize
  336. );
  337. // Set render states.
  338. bgfx::setState(0
  339. | BGFX_STATE_WRITE_RGB
  340. | BGFX_STATE_BLEND_ADD
  341. | BGFX_STATE_DEPTH_TEST_ALWAYS
  342. );
  343. // Submit primitive for rendering to view 0.
  344. if (m_useIndirect)
  345. {
  346. bgfx::submit(0, m_particleProgram, m_indirectBuffer, 0);
  347. }
  348. else
  349. {
  350. bgfx::submit(0, m_particleProgram);
  351. }
  352. }
  353. imguiEndFrame();
  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. bool m_useIndirect;
  367. bool m_computeSupported;
  368. bool m_indirectSupported;
  369. ParamsData m_paramsData;
  370. bgfx::VertexBufferHandle m_vbh;
  371. bgfx::IndexBufferHandle m_ibh;
  372. bgfx::ProgramHandle m_particleProgram;
  373. bgfx::ProgramHandle m_indirectProgram;
  374. bgfx::ProgramHandle m_initInstancesProgram;
  375. bgfx::ProgramHandle m_updateInstancesProgram;
  376. bgfx::IndirectBufferHandle m_indirectBuffer;
  377. bgfx::DynamicVertexBufferHandle m_currPositionBuffer0;
  378. bgfx::DynamicVertexBufferHandle m_currPositionBuffer1;
  379. bgfx::DynamicVertexBufferHandle m_prevPositionBuffer0;
  380. bgfx::DynamicVertexBufferHandle m_prevPositionBuffer1;
  381. bgfx::UniformHandle u_params;
  382. int64_t m_timeOffset;
  383. };
  384. } // namespace
  385. ENTRY_IMPLEMENT_MAIN(ExampleNbody, "24-nbody", "N-body simulation with compute shaders using buffers.");