gpudrivenrendering.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  1. /*
  2. * Copyright 2018 Kostas Anagnostou. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. /*
  6. * Reference(s):
  7. * - Experiments in GPU-based occlusion culling
  8. * https://web.archive.org/web/20180920045301/https://interplayoflight.wordpress.com/2017/11/15/experiments-in-gpu-based-occlusion-culling/
  9. * - Experiments in GPU-based occlusion culling part 2: MultiDrawIndirect and mesh lodding
  10. * https://web.archive.org/web/20180920045332/https://interplayoflight.wordpress.com/2018/01/15/experiments-in-gpu-based-occlusion-culling-part-2-multidrawindirect-and-mesh-lodding/
  11. */
  12. #include "common.h"
  13. #include "bgfx_utils.h"
  14. #include "imgui/imgui.h"
  15. namespace
  16. {
  17. #define RENDER_PASS_HIZ_ID 0
  18. #define RENDER_PASS_HIZ_DOWNSCALE_ID 1
  19. #define RENDER_PASS_OCCLUDE_PROPS_ID 2
  20. #define RENDER_PASS_COMPACT_STREAM_ID 3
  21. #define RENDER_PASS_MAIN_ID 4
  22. struct Camera
  23. {
  24. Camera()
  25. {
  26. reset();
  27. }
  28. void reset()
  29. {
  30. m_target.curr = { 0.0f, 0.0f, 0.0f };
  31. m_target.dest = { 0.0f, 0.0f, 0.0f };
  32. m_pos.curr = { 55.0f, 20.0f, 65.0f };
  33. m_pos.dest = { 55.0f, 20.0f, 65.0f };
  34. m_orbit[0] = 0.0f;
  35. m_orbit[1] = 0.0f;
  36. }
  37. void mtxLookAt(float* _outViewMtx)
  38. {
  39. bx::mtxLookAt(_outViewMtx, m_pos.curr, m_target.curr);
  40. }
  41. void orbit(float _dx, float _dy)
  42. {
  43. m_orbit[0] += _dx;
  44. m_orbit[1] += _dy;
  45. }
  46. void dolly(float _dz)
  47. {
  48. const float cnear = 1.0f;
  49. const float cfar = 100.0f;
  50. const bx::Vec3 toTarget = bx::sub(m_target.dest, m_pos.dest);
  51. const float toTargetLen = bx::length(toTarget);
  52. const float invToTargetLen = 1.0f / (toTargetLen + bx::kFloatMin);
  53. const bx::Vec3 toTargetNorm = bx::mul(toTarget, invToTargetLen);
  54. float delta = toTargetLen * _dz;
  55. float newLen = toTargetLen + delta;
  56. if ( (cnear < newLen || _dz < 0.0f)
  57. && (newLen < cfar || _dz > 0.0f) )
  58. {
  59. m_pos.dest = bx::mad(toTargetNorm, delta, m_pos.dest);
  60. }
  61. }
  62. void consumeOrbit(float _amount)
  63. {
  64. float consume[2];
  65. consume[0] = m_orbit[0] * _amount;
  66. consume[1] = m_orbit[1] * _amount;
  67. m_orbit[0] -= consume[0];
  68. m_orbit[1] -= consume[1];
  69. const bx::Vec3 toPos = bx::sub(m_pos.curr, m_target.curr);
  70. const float toPosLen = bx::length(toPos);
  71. const float invToPosLen = 1.0f / (toPosLen + bx::kFloatMin);
  72. const bx::Vec3 toPosNorm = bx::mul(toPos, invToPosLen);
  73. float ll[2];
  74. bx::toLatLong(&ll[0], &ll[1], toPosNorm);
  75. ll[0] += consume[0];
  76. ll[1] -= consume[1];
  77. ll[1] = bx::clamp(ll[1], 0.02f, 0.98f);
  78. const bx::Vec3 tmp = bx::fromLatLong(ll[0], ll[1]);
  79. const bx::Vec3 diff = bx::mul(bx::sub(tmp, toPosNorm), toPosLen);
  80. m_pos.curr = bx::add(m_pos.curr, diff);
  81. m_pos.dest = bx::add(m_pos.dest, diff);
  82. }
  83. void update(float _dt)
  84. {
  85. const float amount = bx::min(_dt / 0.12f, 1.0f);
  86. consumeOrbit(amount);
  87. m_target.curr = bx::lerp(m_target.curr, m_target.dest, amount);
  88. m_pos.curr = bx::lerp(m_pos.curr, m_pos.dest, amount);
  89. }
  90. void envViewMtx(float* _mtx)
  91. {
  92. const bx::Vec3 toTarget = bx::sub(m_target.curr, m_pos.curr);
  93. const float toTargetLen = bx::length(toTarget);
  94. const float invToTargetLen = 1.0f / (toTargetLen + bx::kFloatMin);
  95. const bx::Vec3 toTargetNorm = bx::mul(toTarget, invToTargetLen);
  96. const bx::Vec3 right = bx::normalize(bx::cross({ 0.0f, 1.0f, 0.0f }, toTargetNorm) );
  97. const bx::Vec3 up = bx::normalize(bx::cross(toTargetNorm, right) );
  98. _mtx[ 0] = right.x;
  99. _mtx[ 1] = right.y;
  100. _mtx[ 2] = right.z;
  101. _mtx[ 3] = 0.0f;
  102. _mtx[ 4] = up.x;
  103. _mtx[ 5] = up.y;
  104. _mtx[ 6] = up.z;
  105. _mtx[ 7] = 0.0f;
  106. _mtx[ 8] = toTargetNorm.x;
  107. _mtx[ 9] = toTargetNorm.y;
  108. _mtx[10] = toTargetNorm.z;
  109. _mtx[11] = 0.0f;
  110. _mtx[12] = 0.0f;
  111. _mtx[13] = 0.0f;
  112. _mtx[14] = 0.0f;
  113. _mtx[15] = 1.0f;
  114. }
  115. struct Interp3f
  116. {
  117. bx::Vec3 curr;
  118. bx::Vec3 dest;
  119. };
  120. Interp3f m_target;
  121. Interp3f m_pos;
  122. float m_orbit[2];
  123. };
  124. struct Mouse
  125. {
  126. Mouse()
  127. : m_dx(0.0f)
  128. , m_dy(0.0f)
  129. , m_prevMx(0.0f)
  130. , m_prevMy(0.0f)
  131. , m_scroll(0)
  132. , m_scrollPrev(0)
  133. {
  134. }
  135. void update(float _mx, float _my, int32_t _mz, uint32_t _width, uint32_t _height)
  136. {
  137. const float widthf = float(int32_t(_width));
  138. const float heightf = float(int32_t(_height));
  139. // Delta movement.
  140. m_dx = float(_mx - m_prevMx) / widthf;
  141. m_dy = float(_my - m_prevMy) / heightf;
  142. m_prevMx = _mx;
  143. m_prevMy = _my;
  144. // Scroll.
  145. m_scroll = _mz - m_scrollPrev;
  146. m_scrollPrev = _mz;
  147. }
  148. float m_dx; // Screen space.
  149. float m_dy;
  150. float m_prevMx;
  151. float m_prevMy;
  152. int32_t m_scroll;
  153. int32_t m_scrollPrev;
  154. };
  155. struct PosVertex
  156. {
  157. float m_x;
  158. float m_y;
  159. float m_z;
  160. static void init()
  161. {
  162. ms_decl
  163. .begin()
  164. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  165. .end();
  166. };
  167. static bgfx::VertexDecl ms_decl;
  168. };
  169. bgfx::VertexDecl PosVertex::ms_decl;
  170. static PosVertex s_cubeVertices[8] =
  171. {
  172. {-0.5f, 0.5f, 0.5f},
  173. { 0.5f, 0.5f, 0.5f},
  174. {-0.5f, -0.5f, 0.5f},
  175. { 0.5f, -0.5f, 0.5f},
  176. {-0.5f, 0.5f, -0.5f},
  177. { 0.5f, 0.5f, -0.5f},
  178. {-0.5f, -0.5f, -0.5f},
  179. { 0.5f, -0.5f, -0.5f},
  180. };
  181. static const uint16_t s_cubeIndices[36] =
  182. {
  183. 0, 1, 2, // 0
  184. 1, 3, 2,
  185. 4, 6, 5, // 2
  186. 5, 6, 7,
  187. 0, 2, 4, // 4
  188. 4, 2, 6,
  189. 1, 5, 3, // 6
  190. 5, 7, 3,
  191. 0, 4, 1, // 8
  192. 4, 5, 1,
  193. 2, 3, 6, // 10
  194. 6, 3, 7,
  195. };
  196. struct RenderPass
  197. {
  198. enum Enum
  199. {
  200. Occlusion = 1 << 0,
  201. MainPass = 1 << 1,
  202. All = Occlusion | MainPass
  203. };
  204. };
  205. // All the per-instance data we store
  206. struct InstanceData
  207. {
  208. float m_world[16];
  209. float m_bboxMin[4];
  210. float m_bboxMax[4];
  211. };
  212. //A description of each prop
  213. struct Prop
  214. {
  215. PosVertex* m_vertices;
  216. uint16_t* m_indices;
  217. InstanceData* m_instances;
  218. bgfx::VertexBufferHandle m_vertexbufferHandle;
  219. bgfx::IndexBufferHandle m_indexbufferHandle;
  220. uint16_t m_noofVertices;
  221. uint16_t m_noofIndices;
  222. uint16_t m_noofInstances;
  223. uint16_t m_materialID;
  224. RenderPass::Enum m_renderPass;
  225. };
  226. //A simplistic material, comprised of a color only
  227. struct Material
  228. {
  229. float m_color[4];
  230. };
  231. inline void setVector4(float* dest, float x, float y, float z, float w)
  232. {
  233. dest[0] = x;
  234. dest[1] = y;
  235. dest[2] = z;
  236. dest[3] = w;
  237. }
  238. //Sets up a prop
  239. void createCubeMesh(Prop& prop)
  240. {
  241. prop.m_noofVertices = 8;
  242. prop.m_noofIndices = 36;
  243. prop.m_vertices = new PosVertex[prop.m_noofVertices];
  244. prop.m_indices = new uint16_t[prop.m_noofIndices];
  245. bx::memCopy(prop.m_vertices, s_cubeVertices, prop.m_noofVertices * PosVertex::ms_decl.getStride());
  246. bx::memCopy(prop.m_indices, s_cubeIndices, prop.m_noofIndices * sizeof(uint16_t));
  247. prop.m_vertexbufferHandle = bgfx::createVertexBuffer(
  248. bgfx::makeRef(prop.m_vertices, prop.m_noofVertices * PosVertex::ms_decl.getStride()),
  249. PosVertex::ms_decl);
  250. prop.m_indexbufferHandle = bgfx::createIndexBuffer(bgfx::makeRef(prop.m_indices, prop.m_noofIndices * sizeof(uint16_t)));
  251. }
  252. //returns a random number between 0 and 1
  253. float rand01()
  254. {
  255. return rand() / (float)RAND_MAX;
  256. }
  257. class GPUDrivenRendering : public entry::AppI
  258. {
  259. public:
  260. GPUDrivenRendering(const char* _name, const char* _description)
  261. : entry::AppI(_name, _description)
  262. {
  263. }
  264. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  265. {
  266. Args args(_argc, _argv);
  267. m_width = _width;
  268. m_height = _height;
  269. //find largest pow of two dims less than backbuffer size
  270. m_hiZwidth = (uint32_t)bx::pow(2.0f, bx::floor(bx::log2(float(m_width ) ) ) );
  271. m_hiZheight = (uint32_t)bx::pow(2.0f, bx::floor(bx::log2(float(m_height) ) ) );
  272. m_debug = BGFX_DEBUG_TEXT;
  273. m_reset = BGFX_RESET_VSYNC;
  274. bgfx::Init init;
  275. init.type = args.m_type;
  276. init.vendorId = args.m_pciId;
  277. init.resolution.width = m_width;
  278. init.resolution.height = m_height;
  279. init.resolution.reset = m_reset;
  280. bgfx::init(init);
  281. // Enable debug text.
  282. bgfx::setDebug(m_debug);
  283. // Create uniforms and samplers.
  284. u_inputRTSize = bgfx::createUniform("u_inputRTSize", bgfx::UniformType::Vec4);
  285. u_cullingConfig = bgfx::createUniform("u_cullingConfig", bgfx::UniformType::Vec4);
  286. u_color = bgfx::createUniform("u_color", bgfx::UniformType::Vec4, 32);
  287. s_texOcclusionDepth = bgfx::createUniform("s_texOcclusionDepth", bgfx::UniformType::Sampler);
  288. //create props
  289. {
  290. m_totalInstancesCount = 0;
  291. // Create vertex stream declaration.
  292. PosVertex::init();
  293. m_noofProps = 0;
  294. m_props = new Prop[s_maxNoofProps];
  295. //first create space for some materials
  296. m_materials = new Material[s_maxNoofProps];
  297. m_noofMaterials = 0;
  298. //add a ground plane
  299. {
  300. Prop& prop = m_props[m_noofProps++];
  301. prop.m_renderPass = RenderPass::MainPass;
  302. createCubeMesh(prop);
  303. prop.m_noofInstances = 1;
  304. prop.m_instances = new InstanceData[prop.m_noofInstances];
  305. bx::mtxSRT(prop.m_instances->m_world
  306. , 100.0f, 0.1f, 100.0f
  307. , 0.0f, 0.0f, 0.0f
  308. , 0.0f, 0.0f, 0.0f
  309. );
  310. float temp[4];
  311. setVector4(temp, -0.5f, -0.5f, -0.5f, 1.0f);
  312. bx::vec4MulMtx(prop.m_instances->m_bboxMin, temp, prop.m_instances->m_world);
  313. setVector4(temp, 0.5f, 0.5f, 0.5f, 1.0f);
  314. bx::vec4MulMtx(prop.m_instances->m_bboxMax, temp, prop.m_instances->m_world);
  315. prop.m_materialID = m_noofMaterials;
  316. setVector4(m_materials[prop.m_materialID].m_color, 0.0f, 0.6f, 0.0f, 1.0f);
  317. m_noofMaterials++;
  318. m_totalInstancesCount += prop.m_noofInstances;
  319. }
  320. //add a few instances of the occluding mesh
  321. {
  322. Prop& prop = m_props[m_noofProps++];
  323. prop.m_renderPass = RenderPass::All;
  324. //create prop
  325. createCubeMesh(prop);
  326. //add a few instances of the wall mesh
  327. prop.m_noofInstances = 25;
  328. prop.m_instances = new InstanceData[prop.m_noofInstances];
  329. for (int i = 0; i < prop.m_noofInstances; i++)
  330. {
  331. //calculate world position
  332. bx::mtxSRT(prop.m_instances[i].m_world
  333. , 40.0f, 10.0f, 0.1f
  334. , 0.0f, ( rand01() * 120.0f - 60.0f) * 3.1459f / 180.0f, 0.0f
  335. , rand01() * 100.0f - 50.0f, 5.0f, rand01() * 100.0f - 50.0f
  336. );
  337. //calculate bounding box and transform to world space
  338. float temp[4];
  339. setVector4(temp, -0.5f, -0.5f, -0.5f, 1.0f);
  340. bx::vec4MulMtx(prop.m_instances[i].m_bboxMin, temp, prop.m_instances[i].m_world );
  341. setVector4(temp, 0.5f, 0.5f, 0.5f, 1.0f);
  342. bx::vec4MulMtx(prop.m_instances[i].m_bboxMax, temp, prop.m_instances[i].m_world );
  343. }
  344. //set the material ID. Will be used in the shader to select the material
  345. prop.m_materialID = m_noofMaterials;
  346. //add a "material" for this prop
  347. setVector4(m_materials[prop.m_materialID].m_color, 0.0f, 0.0f, 1.0f, 0.0f);
  348. m_noofMaterials++;
  349. m_totalInstancesCount += prop.m_noofInstances;
  350. }
  351. //add a few "regular" props
  352. {
  353. //add cubes
  354. {
  355. Prop& prop = m_props[m_noofProps++];
  356. prop.m_renderPass = RenderPass::MainPass;
  357. createCubeMesh(prop);
  358. prop.m_noofInstances = 200;
  359. prop.m_instances = new InstanceData[prop.m_noofInstances];
  360. for (int i = 0; i < prop.m_noofInstances; i++)
  361. {
  362. bx::mtxSRT(prop.m_instances[i].m_world
  363. , 2.0f, 2.0f, 2.0f
  364. , 0.0f, 0.0f, 0.0f
  365. , rand01() * 100.0f - 50.0f, 1.0f, rand01() * 100.0f - 50.0f
  366. );
  367. float temp[4];
  368. setVector4(temp, -0.5f, -0.5f, -0.5f, 1.0f);
  369. bx::vec4MulMtx(prop.m_instances[i].m_bboxMin, temp, prop.m_instances[i].m_world);
  370. setVector4(temp, 0.5f, 0.5f, 0.5f, 1.0f);
  371. bx::vec4MulMtx(prop.m_instances[i].m_bboxMax, temp, prop.m_instances[i].m_world);
  372. }
  373. prop.m_materialID = m_noofMaterials;
  374. setVector4(m_materials[prop.m_materialID].m_color, 1.0f, 1.0f, 0.0f, 1.0f);
  375. m_noofMaterials++;
  376. m_totalInstancesCount += prop.m_noofInstances;
  377. }
  378. //add some more cubes
  379. {
  380. Prop& prop = m_props[m_noofProps++];
  381. prop.m_renderPass = RenderPass::MainPass;
  382. createCubeMesh(prop);
  383. prop.m_noofInstances = 300;
  384. prop.m_instances = new InstanceData[prop.m_noofInstances];
  385. for (int i = 0; i < prop.m_noofInstances; i++)
  386. {
  387. bx::mtxSRT(prop.m_instances[i].m_world
  388. , 2.0f, 4.0f, 2.0f
  389. , 0.0f, 0.0f, 0.0f
  390. , rand01() * 100.0f - 50.0f, 2.0f, rand01() * 100.0f - 50.0f
  391. );
  392. float temp[4];
  393. setVector4(temp, -0.5f, -0.5f, -0.5f, 1.0f);
  394. bx::vec4MulMtx(prop.m_instances[i].m_bboxMin, temp, prop.m_instances[i].m_world );
  395. setVector4(temp, 0.5f, 0.5f, 0.5f, 1.0f);
  396. bx::vec4MulMtx(prop.m_instances[i].m_bboxMax, temp, prop.m_instances[i].m_world);
  397. }
  398. prop.m_materialID = m_noofMaterials;
  399. setVector4(m_materials[prop.m_materialID].m_color, 1.0f, 0.0f, 0.0f, 1.0f);
  400. m_noofMaterials++;
  401. m_totalInstancesCount += prop.m_noofInstances;
  402. }
  403. }
  404. }
  405. //Setup Occlusion pass
  406. {
  407. const uint64_t tsFlags = 0
  408. | BGFX_TEXTURE_RT
  409. | BGFX_SAMPLER_MIN_POINT
  410. | BGFX_SAMPLER_MAG_POINT
  411. | BGFX_SAMPLER_MIP_POINT
  412. | BGFX_SAMPLER_U_CLAMP
  413. | BGFX_SAMPLER_V_CLAMP
  414. ;
  415. // Create buffers for the HiZ pass
  416. m_hiZDepthBuffer = bgfx::createFrameBuffer(uint16_t(m_hiZwidth), uint16_t(m_hiZheight), bgfx::TextureFormat::D32, tsFlags);
  417. bgfx::TextureHandle buffer = bgfx::createTexture2D(uint16_t(m_hiZwidth), uint16_t(m_hiZheight), true, 1, bgfx::TextureFormat::R32F, BGFX_TEXTURE_COMPUTE_WRITE | tsFlags);
  418. m_hiZBuffer = bgfx::createFrameBuffer(1, &buffer, true);
  419. //how many mip will the Hi Z buffer have?
  420. m_noofHiZMips = (uint8_t)(1 + bx::floor(bx::log2(float(bx::max(m_hiZwidth, m_hiZheight) ) ) ) );
  421. // Setup compute shader buffers
  422. //The compute shader will write how many unoccluded instances per drawcall there are here
  423. m_drawcallInstanceCounts = bgfx::createDynamicIndexBuffer(s_maxNoofProps, BGFX_BUFFER_INDEX32 | BGFX_BUFFER_COMPUTE_READ_WRITE);
  424. //the compute shader will write the result of the occlusion test for each instance here
  425. m_instancePredicates = bgfx::createDynamicIndexBuffer(s_maxNoofInstances, BGFX_BUFFER_COMPUTE_READ_WRITE);
  426. //bounding box for each instance, will be fed to the compute shader to calculate occlusion
  427. {
  428. bgfx::VertexDecl computeVertexDecl;
  429. computeVertexDecl.begin()
  430. .add(bgfx::Attrib::TexCoord0, 4, bgfx::AttribType::Float)
  431. .end();
  432. //initialise the buffer with the bounding boxes of all instances
  433. const int sizeOfBuffer = 2 * 4 * m_totalInstancesCount;
  434. float* boundingBoxes = new float[sizeOfBuffer];
  435. float* data = boundingBoxes;
  436. for (uint16_t i = 0; i < m_noofProps; i++)
  437. {
  438. Prop& prop = m_props[i];
  439. const uint32_t numInstances = prop.m_noofInstances;
  440. for (uint32_t j = 0; j < numInstances; j++)
  441. {
  442. bx::memCopy(data, prop.m_instances[j].m_bboxMin, 3 * sizeof(float));
  443. data[3] = (float)i; // store the drawcall ID here to avoid creating a separate buffer
  444. data += 4;
  445. bx::memCopy(data, prop.m_instances[j].m_bboxMax, 3 * sizeof(float));
  446. data += 4;
  447. }
  448. }
  449. const bgfx::Memory* mem = bgfx::makeRef(boundingBoxes, sizeof(float) * sizeOfBuffer);
  450. m_instanceBoundingBoxes = bgfx::createDynamicVertexBuffer(mem, computeVertexDecl, BGFX_BUFFER_COMPUTE_READ);
  451. }
  452. //pre and post occlusion culling instance data buffers
  453. {
  454. bgfx::VertexDecl instanceBufferVertexDecl;
  455. instanceBufferVertexDecl.begin()
  456. .add(bgfx::Attrib::TexCoord0, 4, bgfx::AttribType::Float)
  457. .add(bgfx::Attrib::TexCoord1, 4, bgfx::AttribType::Float)
  458. .add(bgfx::Attrib::TexCoord2, 4, bgfx::AttribType::Float)
  459. .add(bgfx::Attrib::TexCoord3, 4, bgfx::AttribType::Float)
  460. .end();
  461. //initialise the buffer with data for all instances
  462. //Currently we only store a world matrix (16 floats)
  463. const int sizeOfBuffer = 16 * m_totalInstancesCount;
  464. float* instanceData = new float[sizeOfBuffer];
  465. float* data = instanceData;
  466. for (uint16_t ii = 0; ii < m_noofProps; ++ii)
  467. {
  468. Prop& prop = m_props[ii];
  469. const uint32_t numInstances = prop.m_noofInstances;
  470. for (uint32_t jj = 0; jj < numInstances; ++jj)
  471. {
  472. bx::memCopy(data, prop.m_instances[jj].m_world, 16 * sizeof(float) );
  473. data[3] = float(ii); // store the drawcall ID here to avoid creating a separate buffer
  474. data += 16;
  475. }
  476. }
  477. const bgfx::Memory* mem = bgfx::makeRef(instanceData, sizeof(float) * sizeOfBuffer);
  478. //pre occlusion buffer
  479. m_instanceBuffer = bgfx::createVertexBuffer(mem, instanceBufferVertexDecl, BGFX_BUFFER_COMPUTE_READ);
  480. //post occlusion buffer
  481. m_culledInstanceBuffer = bgfx::createDynamicVertexBuffer(4 * m_totalInstancesCount, instanceBufferVertexDecl, BGFX_BUFFER_COMPUTE_WRITE);
  482. }
  483. //we use one "drawcall" per prop to render all its instances
  484. m_indirectBuffer = bgfx::createIndirectBuffer(m_noofProps);
  485. // Create programs from shaders for occlusion pass.
  486. m_programOcclusionPass = loadProgram("vs_gdr_render_occlusion", NULL);
  487. m_programDownscaleHiZ = loadProgram("cs_gdr_downscale_hi_z", NULL);
  488. m_programOccludeProps = loadProgram("cs_gdr_occlude_props", NULL);
  489. m_programStreamCompaction = loadProgram("cs_gdr_stream_compaction", NULL);
  490. // Set view RENDER_PASS_HIZ_ID clear state.
  491. bgfx::setViewClear(RENDER_PASS_HIZ_ID
  492. , BGFX_CLEAR_DEPTH
  493. , 0x0
  494. , 1.0f
  495. , 0
  496. );
  497. }
  498. // Setup Main pass
  499. {
  500. // Set view 0 clear state.
  501. bgfx::setViewClear(RENDER_PASS_MAIN_ID
  502. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  503. , 0x303030ff
  504. , 1.0f
  505. , 0
  506. );
  507. // Create program from shaders.
  508. m_programMainPass = loadProgram("vs_gdr_instanced_indirect_rendering", "fs_gdr_instanced_indirect_rendering");
  509. }
  510. // Create static vertex buffer for all props.
  511. // Calculate how many vertices/indices the master buffers will need.
  512. uint16_t totalNoofVertices = 0;
  513. uint16_t totalNoofIndices = 0;
  514. for (uint16_t i = 0; i < m_noofProps; i++)
  515. {
  516. Prop& prop = m_props[i];
  517. totalNoofVertices += prop.m_noofVertices;
  518. totalNoofIndices += prop.m_noofIndices;
  519. }
  520. // CPU data to fill the master buffers
  521. m_allPropVerticesDataCPU = new PosVertex[totalNoofVertices];
  522. m_allPropIndicesDataCPU = new uint16_t[totalNoofIndices];
  523. m_indirectBufferDataCPU = new uint32_t[m_noofProps * 3];
  524. // Copy data over to the master buffers
  525. PosVertex* propVerticesData = m_allPropVerticesDataCPU;
  526. uint16_t* propIndicesData = m_allPropIndicesDataCPU;
  527. uint16_t vertexBufferOffset = 0;
  528. uint16_t indexBufferOffset = 0;
  529. for (uint16_t i = 0; i < m_noofProps; i++)
  530. {
  531. Prop& prop = m_props[i];
  532. bx::memCopy(propVerticesData, prop.m_vertices, prop.m_noofVertices * sizeof(PosVertex));
  533. bx::memCopy(propIndicesData, prop.m_indices, prop.m_noofIndices * sizeof(uint16_t));
  534. propVerticesData += prop.m_noofVertices;
  535. propIndicesData += prop.m_noofIndices;
  536. m_indirectBufferDataCPU[ i * 3 ] = prop.m_noofIndices;
  537. m_indirectBufferDataCPU[ i * 3 + 1] = indexBufferOffset;
  538. m_indirectBufferDataCPU[ i * 3 + 2] = vertexBufferOffset;
  539. indexBufferOffset += prop.m_noofIndices;
  540. vertexBufferOffset += prop.m_noofVertices;
  541. }
  542. // Create master vertex buffer
  543. m_allPropsVertexbufferHandle = bgfx::createVertexBuffer(
  544. bgfx::makeRef(m_allPropVerticesDataCPU, totalNoofVertices * PosVertex::ms_decl.getStride())
  545. , PosVertex::ms_decl
  546. );
  547. // Create master index buffer.
  548. m_allPropsIndexbufferHandle = bgfx::createIndexBuffer(
  549. bgfx::makeRef(m_allPropIndicesDataCPU, totalNoofIndices * sizeof(uint16_t) )
  550. );
  551. // Create buffer with const drawcall data which will be copied to the indirect buffer later.
  552. m_indirectBufferData = bgfx::createIndexBuffer(
  553. bgfx::makeRef(m_indirectBufferDataCPU, m_noofProps * 3 * sizeof(uint32_t)),
  554. BGFX_BUFFER_COMPUTE_READ | BGFX_BUFFER_INDEX32
  555. );
  556. m_timeOffset = bx::getHPCounter();
  557. m_useIndirect = true;
  558. imguiCreate();
  559. }
  560. int shutdown() override
  561. {
  562. imguiDestroy();
  563. // Cleanup.
  564. bgfx::destroy(m_programMainPass);
  565. bgfx::destroy(m_programOcclusionPass);
  566. bgfx::destroy(m_programDownscaleHiZ);
  567. bgfx::destroy(m_programOccludeProps);
  568. bgfx::destroy(m_programStreamCompaction);
  569. for (uint16_t i = 0; i < m_noofProps; i++)
  570. {
  571. Prop& prop = m_props[i];
  572. bgfx::destroy(prop.m_indexbufferHandle);
  573. bgfx::destroy(prop.m_vertexbufferHandle);
  574. delete[] prop.m_indices;
  575. delete[] prop.m_vertices;
  576. delete[] prop.m_instances;
  577. }
  578. delete[] m_props;
  579. bgfx::destroy(m_hiZDepthBuffer);
  580. bgfx::destroy(m_hiZBuffer);
  581. bgfx::destroy(m_indirectBuffer);
  582. bgfx::destroy(m_indirectBufferData);
  583. bgfx::destroy(m_instanceBoundingBoxes);
  584. bgfx::destroy(m_drawcallInstanceCounts);
  585. bgfx::destroy(m_instancePredicates);
  586. bgfx::destroy(m_instanceBuffer);
  587. bgfx::destroy(m_culledInstanceBuffer);
  588. bgfx::destroy(m_allPropsVertexbufferHandle);
  589. bgfx::destroy(m_allPropsIndexbufferHandle);
  590. bgfx::destroy(s_texOcclusionDepth);
  591. bgfx::destroy(u_inputRTSize);
  592. bgfx::destroy(u_cullingConfig);
  593. bgfx::destroy(u_color);
  594. delete[] m_allPropVerticesDataCPU;
  595. delete[] m_allPropIndicesDataCPU;
  596. delete[] m_indirectBufferDataCPU;
  597. // Shutdown bgfx.
  598. bgfx::shutdown();
  599. return 0;
  600. }
  601. //renders the occluders to a depth buffer
  602. void renderOcclusionBufferPass()
  603. {
  604. // Setup the occlusion pass projection
  605. bx::mtxProj(m_occlusionProj, 60.0f, float(m_hiZwidth) / float(m_hiZheight), 0.1f, 500.0f, bgfx::getCaps()->homogeneousDepth);
  606. bgfx::setViewTransform(RENDER_PASS_HIZ_ID, m_mainView, m_occlusionProj);
  607. bgfx::setViewFrameBuffer(RENDER_PASS_HIZ_ID, m_hiZDepthBuffer);
  608. bgfx::setViewRect(RENDER_PASS_HIZ_ID, 0, 0, uint16_t(m_hiZwidth), uint16_t(m_hiZheight));
  609. const uint16_t instanceStride = sizeof(InstanceData);
  610. // render all instances of the occluder meshes
  611. for (uint16_t i = 0; i < m_noofProps; i++)
  612. {
  613. Prop& prop = m_props[i];
  614. if (prop.m_renderPass & RenderPass::Occlusion)
  615. {
  616. const uint32_t numInstances = prop.m_noofInstances;
  617. // render instances to the occlusion buffer
  618. if (numInstances == bgfx::getAvailInstanceDataBuffer(numInstances, instanceStride))
  619. {
  620. bgfx::InstanceDataBuffer instanceBuffer;
  621. bgfx::allocInstanceDataBuffer(&instanceBuffer, numInstances, instanceStride);
  622. InstanceData *data = (InstanceData *) instanceBuffer.data;
  623. for (uint32_t j = 0; j < numInstances; j++)
  624. {
  625. //we only need the world matrix for the occlusion pass
  626. bx::memCopy(data->m_world, prop.m_instances[j].m_world, sizeof(data->m_world));
  627. data++;
  628. }
  629. // Set vertex and index buffer.
  630. bgfx::setVertexBuffer(0, prop.m_vertexbufferHandle);
  631. bgfx::setIndexBuffer(prop.m_indexbufferHandle);
  632. // Set instance data buffer.
  633. bgfx::setInstanceDataBuffer(&instanceBuffer);
  634. // Set render states.
  635. bgfx::setState(BGFX_STATE_DEFAULT);
  636. // Submit primitive for rendering to view.
  637. bgfx::submit(RENDER_PASS_HIZ_ID, m_programOcclusionPass);
  638. }
  639. }
  640. }
  641. }
  642. // downscale the occluder depth buffer to create a mipmap chain
  643. void renderDownscalePass()
  644. {
  645. uint32_t width = m_hiZwidth;
  646. uint32_t height = m_hiZheight;
  647. for (uint8_t lod = 0; lod < m_noofHiZMips; ++lod)
  648. {
  649. float coordinateScale = lod > 0 ? 2.0f : 1.0f;
  650. float inputRendertargetSize[4] = { (float)width, (float)height, coordinateScale, coordinateScale };
  651. bgfx::setUniform(u_inputRTSize, inputRendertargetSize);
  652. if (lod > 0)
  653. {
  654. // down scale mip 1 onwards
  655. width /= 2;
  656. height /= 2;
  657. bgfx::setImage(0, getTexture(m_hiZBuffer, 0), lod - 1, bgfx::Access::Read);
  658. bgfx::setImage(1, getTexture(m_hiZBuffer, 0), lod, bgfx::Access::Write);
  659. }
  660. else
  661. {
  662. // copy mip zero over to the hi Z buffer.
  663. // We can't currently use blit as it requires same format and CopyResource is not exposed.
  664. bgfx::setImage(0, getTexture(m_hiZDepthBuffer, 0), 0, bgfx::Access::Read);
  665. bgfx::setImage(1, getTexture(m_hiZBuffer, 0), 0, bgfx::Access::Write);
  666. }
  667. bgfx::dispatch(RENDER_PASS_HIZ_DOWNSCALE_ID, m_programDownscaleHiZ, width/16, height/16);
  668. }
  669. }
  670. // perform the occlusion using the mip chain
  671. void renderOccludePropsPass()
  672. {
  673. // run the computer shader to determine visibility of each instance
  674. bgfx::setTexture(0, s_texOcclusionDepth, bgfx::getTexture(m_hiZBuffer, 0) );
  675. bgfx::setBuffer(1, m_instanceBoundingBoxes, bgfx::Access::Read);
  676. bgfx::setBuffer(2, m_drawcallInstanceCounts, bgfx::Access::ReadWrite);
  677. bgfx::setBuffer(3, m_instancePredicates, bgfx::Access::Write);
  678. float inputRendertargetSize[4] = { (float)m_hiZwidth, (float)m_hiZheight, 1.0f/ m_hiZwidth, 1.0f/ m_hiZheight };
  679. bgfx::setUniform(u_inputRTSize, inputRendertargetSize);
  680. // store a rounded-up, power of two instance count for the stream compaction step
  681. float noofInstancesPowOf2 = bx::pow(2.0f, bx::floor(bx::log(m_totalInstancesCount) / bx::log(2.0f) ) + 1.0f);
  682. float cullingConfig[4] =
  683. {
  684. (float)m_totalInstancesCount,
  685. noofInstancesPowOf2,
  686. (float)m_noofHiZMips,
  687. (float)m_noofProps
  688. };
  689. bgfx::setUniform(u_cullingConfig, cullingConfig);
  690. //set the view/projection transforms so that the compute shader can receive the viewProjection matrix automagically
  691. bgfx::setViewTransform(RENDER_PASS_OCCLUDE_PROPS_ID, m_mainView, m_occlusionProj);
  692. uint16_t groupX = bx::max<uint16_t>(m_totalInstancesCount / 64 + 1, 1);
  693. bgfx::dispatch(RENDER_PASS_OCCLUDE_PROPS_ID, m_programOccludeProps, groupX, 1, 1);
  694. // perform stream compaction to remove occluded instances
  695. // the per drawcall data that is constant (noof indices/vertices and offsets to vertex/index buffers)
  696. bgfx::setBuffer(0, m_indirectBufferData, bgfx::Access::Read);
  697. // instance data for all instances (pre culling)
  698. bgfx::setBuffer(1, m_instanceBuffer, bgfx::Access::Read);
  699. // per instance visibility (output of culling pass)
  700. bgfx::setBuffer(2, m_instancePredicates, bgfx::Access::Read);
  701. // how many instances per drawcall
  702. bgfx::setBuffer(3, m_drawcallInstanceCounts, bgfx::Access::ReadWrite);
  703. // drawcall data that will drive drawIndirect
  704. bgfx::setBuffer(4, m_indirectBuffer, bgfx::Access::ReadWrite);
  705. // culled instance data
  706. bgfx::setBuffer(5, m_culledInstanceBuffer, bgfx::Access::Write);
  707. bgfx::setUniform(u_cullingConfig, cullingConfig);
  708. bgfx::dispatch(RENDER_PASS_COMPACT_STREAM_ID, m_programStreamCompaction, 1, 1, 1);
  709. }
  710. // render the unoccluded props to the screen
  711. void renderMainPass()
  712. {
  713. // Set view and projection matrix for view 0.
  714. {
  715. bgfx::setViewTransform(RENDER_PASS_MAIN_ID, m_mainView, m_mainProj);
  716. // Set view 0 default viewport.
  717. bgfx::setViewRect(RENDER_PASS_MAIN_ID, 0, 0, uint16_t(m_width), uint16_t(m_height));
  718. }
  719. // Set render states.
  720. bgfx::setState(BGFX_STATE_DEFAULT);
  721. const uint16_t instanceStride = sizeof(InstanceData);
  722. // Set "material" data (currently a color only)
  723. bgfx::setUniform(u_color, &m_materials[0].m_color, m_noofMaterials);
  724. if (m_useIndirect)
  725. {
  726. // Set vertex and index buffer.
  727. bgfx::setVertexBuffer(0, m_allPropsVertexbufferHandle);
  728. bgfx::setIndexBuffer( m_allPropsIndexbufferHandle);
  729. // Set instance data buffer.
  730. bgfx::setInstanceDataBuffer(m_culledInstanceBuffer, 0, m_totalInstancesCount );
  731. bgfx::submit(RENDER_PASS_MAIN_ID, m_programMainPass, m_indirectBuffer, 0, m_noofProps);
  732. }
  733. else
  734. {
  735. // render all props using regular instancing
  736. for (uint16_t ii = 0; ii < m_noofProps; ++ii)
  737. {
  738. Prop& prop = m_props[ii];
  739. if (prop.m_renderPass & RenderPass::MainPass)
  740. {
  741. const uint32_t numInstances = prop.m_noofInstances;
  742. if (numInstances == bgfx::getAvailInstanceDataBuffer(numInstances, instanceStride))
  743. {
  744. bgfx::InstanceDataBuffer instanceBuffer;
  745. bgfx::allocInstanceDataBuffer(&instanceBuffer, numInstances, instanceStride);
  746. InstanceData *data = (InstanceData *)instanceBuffer.data;
  747. for (uint32_t jj = 0; jj < numInstances; ++jj)
  748. {
  749. //copy world matrix
  750. bx::memCopy(data->m_world, prop.m_instances[jj].m_world, sizeof(data->m_world) );
  751. //pack the material ID into the world transform
  752. data->m_world[3] = float(prop.m_materialID);
  753. data++;
  754. }
  755. // Set vertex and index buffer.
  756. bgfx::setVertexBuffer(0, prop.m_vertexbufferHandle);
  757. bgfx::setIndexBuffer(prop.m_indexbufferHandle);
  758. // Set instance data buffer.
  759. bgfx::setInstanceDataBuffer(&instanceBuffer);
  760. bgfx::submit(RENDER_PASS_MAIN_ID, m_programMainPass);
  761. }
  762. }
  763. }
  764. }
  765. }
  766. bool update() override
  767. {
  768. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  769. {
  770. imguiBeginFrame(m_mouseState.m_mx
  771. , m_mouseState.m_my
  772. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  773. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  774. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  775. , m_mouseState.m_mz
  776. , uint16_t(m_width)
  777. , uint16_t(m_height)
  778. );
  779. showExampleDialog(this);
  780. ImGui::SetNextWindowPos(
  781. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  782. , ImGuiCond_FirstUseEver
  783. );
  784. ImGui::SetNextWindowSize(
  785. ImVec2(m_width / 5.0f, m_height / 6.0f)
  786. , ImGuiCond_FirstUseEver
  787. );
  788. ImGui::Begin("Settings"
  789. , NULL
  790. , 0
  791. );
  792. ImGui::Checkbox("Use Draw Indirect", &m_useIndirect);
  793. ImGui::End();
  794. imguiEndFrame();
  795. // This dummy draw call is here to make sure that view 0 is cleared
  796. // if no other draw calls are submitted to view 0.
  797. bgfx::touch(0);
  798. int64_t now = bx::getHPCounter();
  799. static int64_t last = now;
  800. const int64_t frameTime = now - last;
  801. last = now;
  802. const double freq = double(bx::getHPFrequency());
  803. const float deltaTimeSec = float(double(frameTime) / freq);
  804. // Camera.
  805. const bool mouseOverGui = ImGui::MouseOverArea();
  806. m_mouse.update(float(m_mouseState.m_mx), float(m_mouseState.m_my), m_mouseState.m_mz, m_width, m_height);
  807. if (!mouseOverGui)
  808. {
  809. if (m_mouseState.m_buttons[entry::MouseButton::Left])
  810. {
  811. m_camera.orbit(m_mouse.m_dx, m_mouse.m_dy);
  812. }
  813. else if (m_mouseState.m_buttons[entry::MouseButton::Right])
  814. {
  815. m_camera.dolly(m_mouse.m_dx + m_mouse.m_dy);
  816. }
  817. else if (0 != m_mouse.m_scroll)
  818. {
  819. m_camera.dolly(float(m_mouse.m_scroll)*0.05f);
  820. }
  821. }
  822. m_camera.update(deltaTimeSec);
  823. // Get renderer capabilities info.
  824. const bgfx::Caps* caps = bgfx::getCaps();
  825. // Check if instancing is supported.
  826. if (0 == (BGFX_CAPS_INSTANCING & caps->supported) )
  827. {
  828. // When instancing is not supported by GPU, implement alternative
  829. // code path that doesn't use instancing.
  830. float time = (float)((bx::getHPCounter() - m_timeOffset) / double(bx::getHPFrequency()));
  831. bool blink = uint32_t(time*3.0f)&1;
  832. bgfx::dbgTextPrintf(0, 0, blink ? 0x1f : 0x01, " Instancing is not supported by GPU. ");
  833. }
  834. else
  835. {
  836. // calculate main view and project matrices as they are typically reused between passes.
  837. m_camera.mtxLookAt(m_mainView);
  838. bx::mtxProj(m_mainProj, 60.0f, float(m_width) / float(m_height), 0.1f, 500.0f, bgfx::getCaps()->homogeneousDepth);
  839. //submit drawcalls for all passes
  840. renderOcclusionBufferPass();
  841. renderDownscalePass();
  842. renderOccludePropsPass();
  843. renderMainPass();
  844. }
  845. // Advance to next frame. Rendering thread will be kicked to
  846. // process submitted rendering primitives.
  847. bgfx::frame();
  848. return true;
  849. }
  850. return false;
  851. }
  852. entry::MouseState m_mouseState;
  853. uint32_t m_width;
  854. uint32_t m_height;
  855. uint32_t m_hiZwidth;
  856. uint32_t m_hiZheight;
  857. uint32_t m_debug;
  858. uint32_t m_reset;
  859. float m_mainView[16];
  860. float m_mainProj[16];
  861. float m_occlusionProj[16];
  862. bgfx::ProgramHandle m_programMainPass;
  863. bgfx::ProgramHandle m_programOcclusionPass;
  864. bgfx::ProgramHandle m_programDownscaleHiZ;
  865. bgfx::ProgramHandle m_programOccludeProps;
  866. bgfx::ProgramHandle m_programStreamCompaction;
  867. bgfx::FrameBufferHandle m_hiZDepthBuffer;
  868. bgfx::FrameBufferHandle m_hiZBuffer;
  869. bgfx::IndirectBufferHandle m_indirectBuffer;
  870. bgfx::VertexBufferHandle m_allPropsVertexbufferHandle;
  871. bgfx::IndexBufferHandle m_allPropsIndexbufferHandle;
  872. bgfx::IndexBufferHandle m_indirectBufferData;
  873. PosVertex* m_allPropVerticesDataCPU;
  874. uint16_t* m_allPropIndicesDataCPU;
  875. uint32_t* m_indirectBufferDataCPU;
  876. bgfx::DynamicVertexBufferHandle m_instanceBoundingBoxes;
  877. bgfx::DynamicIndexBufferHandle m_drawcallInstanceCounts;
  878. bgfx::DynamicIndexBufferHandle m_instancePredicates;
  879. bgfx::VertexBufferHandle m_instanceBuffer;
  880. bgfx::DynamicVertexBufferHandle m_culledInstanceBuffer;
  881. bgfx::UniformHandle s_texOcclusionDepth;
  882. bgfx::UniformHandle u_inputRTSize;
  883. bgfx::UniformHandle u_cullingConfig;
  884. bgfx::UniformHandle u_color;
  885. Prop* m_props;
  886. Material* m_materials;
  887. uint16_t m_noofProps;
  888. uint16_t m_noofMaterials;
  889. uint16_t m_totalInstancesCount;
  890. static const uint16_t s_maxNoofProps = 10;
  891. static const uint16_t s_maxNoofInstances = 2048;
  892. int64_t m_timeOffset;
  893. uint8_t m_noofHiZMips;
  894. bool m_useIndirect;
  895. Camera m_camera;
  896. Mouse m_mouse;
  897. };
  898. } // namespace
  899. ENTRY_IMPLEMENT_MAIN(GPUDrivenRendering, "37-gpudrivenrendering", "GPU-Driven Rendering.");