deferred.cpp 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898
  1. /*
  2. * Copyright 2011-2019 Branimir Karadzic. 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 "bounds.h"
  10. namespace
  11. {
  12. constexpr bgfx::ViewId kRenderPassGeometry = 0;
  13. constexpr bgfx::ViewId kRenderPassLight = 1;
  14. constexpr bgfx::ViewId kRenderPassCombine = 2;
  15. constexpr bgfx::ViewId kRenderPassDebugLights = 3;
  16. constexpr bgfx::ViewId kRenderPassDebugGBuffer = 4;
  17. static float s_texelHalf = 0.0f;
  18. struct PosNormalTangentTexcoordVertex
  19. {
  20. float m_x;
  21. float m_y;
  22. float m_z;
  23. uint32_t m_normal;
  24. uint32_t m_tangent;
  25. int16_t m_u;
  26. int16_t m_v;
  27. static void init()
  28. {
  29. ms_layout
  30. .begin()
  31. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  32. .add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true)
  33. .add(bgfx::Attrib::Tangent, 4, bgfx::AttribType::Uint8, true, true)
  34. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Int16, true, true)
  35. .end();
  36. }
  37. static bgfx::VertexLayout ms_layout;
  38. };
  39. bgfx::VertexLayout PosNormalTangentTexcoordVertex::ms_layout;
  40. struct PosTexCoord0Vertex
  41. {
  42. float m_x;
  43. float m_y;
  44. float m_z;
  45. float m_u;
  46. float m_v;
  47. static void init()
  48. {
  49. ms_layout
  50. .begin()
  51. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  52. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  53. .end();
  54. }
  55. static bgfx::VertexLayout ms_layout;
  56. };
  57. bgfx::VertexLayout PosTexCoord0Vertex::ms_layout;
  58. struct DebugVertex
  59. {
  60. float m_x;
  61. float m_y;
  62. float m_z;
  63. uint32_t m_abgr;
  64. static void init()
  65. {
  66. ms_layout
  67. .begin()
  68. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  69. .add(bgfx::Attrib::Color0, 4, bgfx::AttribType::Uint8, true)
  70. .end();
  71. }
  72. static bgfx::VertexLayout ms_layout;
  73. };
  74. bgfx::VertexLayout DebugVertex::ms_layout;
  75. static PosNormalTangentTexcoordVertex s_cubeVertices[24] =
  76. {
  77. {-1.0f, 1.0f, 1.0f, encodeNormalRgba8( 0.0f, 0.0f, 1.0f), 0, 0, 0 },
  78. { 1.0f, 1.0f, 1.0f, encodeNormalRgba8( 0.0f, 0.0f, 1.0f), 0, 0x7fff, 0 },
  79. {-1.0f, -1.0f, 1.0f, encodeNormalRgba8( 0.0f, 0.0f, 1.0f), 0, 0, 0x7fff },
  80. { 1.0f, -1.0f, 1.0f, encodeNormalRgba8( 0.0f, 0.0f, 1.0f), 0, 0x7fff, 0x7fff },
  81. {-1.0f, 1.0f, -1.0f, encodeNormalRgba8( 0.0f, 0.0f, -1.0f), 0, 0, 0 },
  82. { 1.0f, 1.0f, -1.0f, encodeNormalRgba8( 0.0f, 0.0f, -1.0f), 0, 0x7fff, 0 },
  83. {-1.0f, -1.0f, -1.0f, encodeNormalRgba8( 0.0f, 0.0f, -1.0f), 0, 0, 0x7fff },
  84. { 1.0f, -1.0f, -1.0f, encodeNormalRgba8( 0.0f, 0.0f, -1.0f), 0, 0x7fff, 0x7fff },
  85. {-1.0f, 1.0f, 1.0f, encodeNormalRgba8( 0.0f, 1.0f, 0.0f), 0, 0, 0 },
  86. { 1.0f, 1.0f, 1.0f, encodeNormalRgba8( 0.0f, 1.0f, 0.0f), 0, 0x7fff, 0 },
  87. {-1.0f, 1.0f, -1.0f, encodeNormalRgba8( 0.0f, 1.0f, 0.0f), 0, 0, 0x7fff },
  88. { 1.0f, 1.0f, -1.0f, encodeNormalRgba8( 0.0f, 1.0f, 0.0f), 0, 0x7fff, 0x7fff },
  89. {-1.0f, -1.0f, 1.0f, encodeNormalRgba8( 0.0f, -1.0f, 0.0f), 0, 0, 0 },
  90. { 1.0f, -1.0f, 1.0f, encodeNormalRgba8( 0.0f, -1.0f, 0.0f), 0, 0x7fff, 0 },
  91. {-1.0f, -1.0f, -1.0f, encodeNormalRgba8( 0.0f, -1.0f, 0.0f), 0, 0, 0x7fff },
  92. { 1.0f, -1.0f, -1.0f, encodeNormalRgba8( 0.0f, -1.0f, 0.0f), 0, 0x7fff, 0x7fff },
  93. { 1.0f, -1.0f, 1.0f, encodeNormalRgba8( 1.0f, 0.0f, 0.0f), 0, 0, 0 },
  94. { 1.0f, 1.0f, 1.0f, encodeNormalRgba8( 1.0f, 0.0f, 0.0f), 0, 0x7fff, 0 },
  95. { 1.0f, -1.0f, -1.0f, encodeNormalRgba8( 1.0f, 0.0f, 0.0f), 0, 0, 0x7fff },
  96. { 1.0f, 1.0f, -1.0f, encodeNormalRgba8( 1.0f, 0.0f, 0.0f), 0, 0x7fff, 0x7fff },
  97. {-1.0f, -1.0f, 1.0f, encodeNormalRgba8(-1.0f, 0.0f, 0.0f), 0, 0, 0 },
  98. {-1.0f, 1.0f, 1.0f, encodeNormalRgba8(-1.0f, 0.0f, 0.0f), 0, 0x7fff, 0 },
  99. {-1.0f, -1.0f, -1.0f, encodeNormalRgba8(-1.0f, 0.0f, 0.0f), 0, 0, 0x7fff },
  100. {-1.0f, 1.0f, -1.0f, encodeNormalRgba8(-1.0f, 0.0f, 0.0f), 0, 0x7fff, 0x7fff },
  101. };
  102. static const uint16_t s_cubeIndices[36] =
  103. {
  104. 0, 2, 1,
  105. 1, 2, 3,
  106. 4, 5, 6,
  107. 5, 7, 6,
  108. 8, 10, 9,
  109. 9, 10, 11,
  110. 12, 13, 14,
  111. 13, 15, 14,
  112. 16, 18, 17,
  113. 17, 18, 19,
  114. 20, 21, 22,
  115. 21, 23, 22,
  116. };
  117. void screenSpaceQuad(float _textureWidth, float _textureHeight, float _texelHalf, bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
  118. {
  119. if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_layout) )
  120. {
  121. bgfx::TransientVertexBuffer vb;
  122. bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_layout);
  123. PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
  124. const float minx = -_width;
  125. const float maxx = _width;
  126. const float miny = 0.0f;
  127. const float maxy = _height*2.0f;
  128. const float texelHalfW = _texelHalf/_textureWidth;
  129. const float texelHalfH = _texelHalf/_textureHeight;
  130. const float minu = -1.0f + texelHalfW;
  131. const float maxu = 1.0f + texelHalfH;
  132. const float zz = 0.0f;
  133. float minv = texelHalfH;
  134. float maxv = 2.0f + texelHalfH;
  135. if (_originBottomLeft)
  136. {
  137. float temp = minv;
  138. minv = maxv;
  139. maxv = temp;
  140. minv -= 1.0f;
  141. maxv -= 1.0f;
  142. }
  143. vertex[0].m_x = minx;
  144. vertex[0].m_y = miny;
  145. vertex[0].m_z = zz;
  146. vertex[0].m_u = minu;
  147. vertex[0].m_v = minv;
  148. vertex[1].m_x = maxx;
  149. vertex[1].m_y = miny;
  150. vertex[1].m_z = zz;
  151. vertex[1].m_u = maxu;
  152. vertex[1].m_v = minv;
  153. vertex[2].m_x = maxx;
  154. vertex[2].m_y = maxy;
  155. vertex[2].m_z = zz;
  156. vertex[2].m_u = maxu;
  157. vertex[2].m_v = maxv;
  158. bgfx::setVertexBuffer(0, &vb);
  159. }
  160. }
  161. class ExampleDeferred : public entry::AppI
  162. {
  163. public:
  164. ExampleDeferred(const char* _name, const char* _description)
  165. : entry::AppI(_name, _description)
  166. {
  167. }
  168. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  169. {
  170. Args args(_argc, _argv);
  171. m_width = _width;
  172. m_height = _height;
  173. m_debug = BGFX_DEBUG_TEXT;
  174. m_reset = BGFX_RESET_VSYNC;
  175. bgfx::Init init;
  176. init.type = args.m_type;
  177. init.vendorId = args.m_pciId;
  178. init.resolution.width = m_width;
  179. init.resolution.height = m_height;
  180. init.resolution.reset = m_reset;
  181. bgfx::init(init);
  182. // Enable m_debug text.
  183. bgfx::setDebug(m_debug);
  184. // Set palette color for index 0
  185. bgfx::setPaletteColor(0, UINT32_C(0x00000000) );
  186. // Set palette color for index 1
  187. bgfx::setPaletteColor(1, UINT32_C(0x303030ff) );
  188. // Set geometry pass view clear state.
  189. bgfx::setViewClear(kRenderPassGeometry
  190. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  191. , 1.0f
  192. , 0
  193. , 1
  194. );
  195. // Set light pass view clear state.
  196. bgfx::setViewClear(kRenderPassLight
  197. , BGFX_CLEAR_COLOR|BGFX_CLEAR_DEPTH
  198. , 1.0f
  199. , 0
  200. , 0
  201. );
  202. // Create vertex stream declaration.
  203. PosNormalTangentTexcoordVertex::init();
  204. PosTexCoord0Vertex::init();
  205. DebugVertex::init();
  206. calcTangents(s_cubeVertices
  207. , BX_COUNTOF(s_cubeVertices)
  208. , PosNormalTangentTexcoordVertex::ms_layout
  209. , s_cubeIndices
  210. , BX_COUNTOF(s_cubeIndices)
  211. );
  212. // Create static vertex buffer.
  213. m_vbh = bgfx::createVertexBuffer(
  214. bgfx::makeRef(s_cubeVertices, sizeof(s_cubeVertices) )
  215. , PosNormalTangentTexcoordVertex::ms_layout
  216. );
  217. // Create static index buffer.
  218. m_ibh = bgfx::createIndexBuffer(bgfx::makeRef(s_cubeIndices, sizeof(s_cubeIndices) ) );
  219. // Create texture sampler uniforms.
  220. s_texColor = bgfx::createUniform("s_texColor", bgfx::UniformType::Sampler);
  221. s_texNormal = bgfx::createUniform("s_texNormal", bgfx::UniformType::Sampler);
  222. s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler);
  223. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Sampler);
  224. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler);
  225. s_light = bgfx::createUniform("s_light", bgfx::UniformType::Sampler);
  226. u_mtx = bgfx::createUniform("u_mtx", bgfx::UniformType::Mat4);
  227. u_lightPosRadius = bgfx::createUniform("u_lightPosRadius", bgfx::UniformType::Vec4);
  228. u_lightRgbInnerR = bgfx::createUniform("u_lightRgbInnerR", bgfx::UniformType::Vec4);
  229. // Create program from shaders.
  230. m_geomProgram = loadProgram("vs_deferred_geom", "fs_deferred_geom");
  231. m_lightProgram = loadProgram("vs_deferred_light", "fs_deferred_light");
  232. m_combineProgram = loadProgram("vs_deferred_combine", "fs_deferred_combine");
  233. m_debugProgram = loadProgram("vs_deferred_debug", "fs_deferred_debug");
  234. m_lineProgram = loadProgram("vs_deferred_debug_line", "fs_deferred_debug_line");
  235. m_useTArray = false;
  236. m_useUav = false;
  237. if (0 != (BGFX_CAPS_TEXTURE_2D_ARRAY & bgfx::getCaps()->supported) )
  238. {
  239. m_lightTaProgram = loadProgram("vs_deferred_light", "fs_deferred_light_ta");
  240. }
  241. else
  242. {
  243. m_lightTaProgram = BGFX_INVALID_HANDLE;
  244. }
  245. if (0 != (BGFX_CAPS_FRAMEBUFFER_RW & bgfx::getCaps()->supported) )
  246. {
  247. m_lightUavProgram = loadProgram("vs_deferred_light", "fs_deferred_light_uav");
  248. m_clearUavProgram = loadProgram("vs_deferred_light", "fs_deferred_clear_uav");
  249. }
  250. else
  251. {
  252. m_lightUavProgram = BGFX_INVALID_HANDLE;
  253. m_clearUavProgram = BGFX_INVALID_HANDLE;
  254. }
  255. // Load diffuse texture.
  256. m_textureColor = loadTexture("textures/fieldstone-rgba.dds");
  257. // Load normal texture.
  258. m_textureNormal = loadTexture("textures/fieldstone-n.dds");
  259. m_gbufferTex[0].idx = bgfx::kInvalidHandle;
  260. m_gbufferTex[1].idx = bgfx::kInvalidHandle;
  261. m_gbufferTex[2].idx = bgfx::kInvalidHandle;
  262. m_gbuffer.idx = bgfx::kInvalidHandle;
  263. m_lightBuffer.idx = bgfx::kInvalidHandle;
  264. // Imgui.
  265. imguiCreate();
  266. m_timeOffset = bx::getHPCounter();
  267. const bgfx::RendererType::Enum renderer = bgfx::getRendererType();
  268. s_texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f;
  269. // Get renderer capabilities info.
  270. m_caps = bgfx::getCaps();
  271. m_oldWidth = 0;
  272. m_oldHeight = 0;
  273. m_oldReset = m_reset;
  274. m_scrollArea = 0;
  275. m_numLights = 512;
  276. m_lightAnimationSpeed = 0.3f;
  277. m_animateMesh = true;
  278. m_showScissorRects = false;
  279. m_showGBuffer = true;
  280. cameraCreate();
  281. cameraSetPosition({ 0.0f, 0.0f, -15.0f });
  282. cameraSetVerticalAngle(0.0f);
  283. }
  284. virtual int shutdown() override
  285. {
  286. // Cleanup.
  287. cameraDestroy();
  288. imguiDestroy();
  289. if (bgfx::isValid(m_gbuffer) )
  290. {
  291. bgfx::destroy(m_gbuffer);
  292. bgfx::destroy(m_lightBuffer);
  293. }
  294. bgfx::destroy(m_ibh);
  295. bgfx::destroy(m_vbh);
  296. bgfx::destroy(m_geomProgram);
  297. bgfx::destroy(m_lightProgram);
  298. if (bgfx::isValid(m_lightTaProgram) )
  299. {
  300. bgfx::destroy(m_lightTaProgram);
  301. }
  302. if (bgfx::isValid(m_lightUavProgram) )
  303. {
  304. bgfx::destroy(m_lightUavProgram);
  305. bgfx::destroy(m_clearUavProgram);
  306. }
  307. bgfx::destroy(m_combineProgram);
  308. bgfx::destroy(m_debugProgram);
  309. bgfx::destroy(m_lineProgram);
  310. bgfx::destroy(m_textureColor);
  311. bgfx::destroy(m_textureNormal);
  312. bgfx::destroy(s_texColor);
  313. bgfx::destroy(s_texNormal);
  314. bgfx::destroy(s_albedo);
  315. bgfx::destroy(s_normal);
  316. bgfx::destroy(s_depth);
  317. bgfx::destroy(s_light);
  318. bgfx::destroy(u_lightPosRadius);
  319. bgfx::destroy(u_lightRgbInnerR);
  320. bgfx::destroy(u_mtx);
  321. // Shutdown bgfx.
  322. bgfx::shutdown();
  323. return 0;
  324. }
  325. bool update() override
  326. {
  327. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  328. {
  329. imguiBeginFrame(m_mouseState.m_mx
  330. , m_mouseState.m_my
  331. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  332. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  333. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  334. , m_mouseState.m_mz
  335. , uint16_t(m_width)
  336. , uint16_t(m_height)
  337. );
  338. showExampleDialog(this);
  339. int64_t now = bx::getHPCounter();
  340. static int64_t last = now;
  341. const int64_t frameTime = now - last;
  342. last = now;
  343. const double freq = double(bx::getHPFrequency() );
  344. const float deltaTime = float(frameTime/freq);
  345. float time = (float)( (now-m_timeOffset)/freq);
  346. if (2 > m_caps->limits.maxFBAttachments)
  347. {
  348. // When multiple render targets (MRT) is not supported by GPU,
  349. // implement alternative code path that doesn't use MRT.
  350. bool blink = uint32_t(time*3.0f)&1;
  351. bgfx::dbgTextPrintf(0, 0, blink ? 0x4f : 0x04, " MRT not supported by GPU. ");
  352. // Set view 0 default viewport.
  353. bgfx::setViewRect(0, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  354. // This dummy draw call is here to make sure that view 0 is cleared
  355. // if no other draw calls are submitted to view 0.
  356. bgfx::touch(0);
  357. }
  358. else
  359. {
  360. if (m_oldWidth != m_width
  361. || m_oldHeight != m_height
  362. || m_oldReset != m_reset
  363. || m_oldUseTArray != m_useTArray
  364. || m_oldUseUav != m_useUav
  365. || !bgfx::isValid(m_gbuffer) )
  366. {
  367. // Recreate variable size render targets when resolution changes.
  368. m_oldWidth = m_width;
  369. m_oldHeight = m_height;
  370. m_oldReset = m_reset;
  371. m_oldUseTArray = m_useTArray;
  372. m_oldUseUav = m_useUav;
  373. if (bgfx::isValid(m_gbuffer) )
  374. {
  375. bgfx::destroy(m_gbuffer);
  376. m_gbufferTex[0].idx = bgfx::kInvalidHandle;
  377. m_gbufferTex[1].idx = bgfx::kInvalidHandle;
  378. m_gbufferTex[2].idx = bgfx::kInvalidHandle;
  379. }
  380. const uint64_t tsFlags = 0
  381. | BGFX_SAMPLER_MIN_POINT
  382. | BGFX_SAMPLER_MAG_POINT
  383. | BGFX_SAMPLER_MIP_POINT
  384. | BGFX_SAMPLER_U_CLAMP
  385. | BGFX_SAMPLER_V_CLAMP
  386. ;
  387. bgfx::Attachment gbufferAt[3];
  388. if (m_useTArray)
  389. {
  390. m_gbufferTex[0] = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 2, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT | tsFlags);
  391. gbufferAt[0].init(m_gbufferTex[0], bgfx::Access::Write, 0);
  392. gbufferAt[1].init(m_gbufferTex[0], bgfx::Access::Write, 1);
  393. }
  394. else
  395. {
  396. m_gbufferTex[0] = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT | tsFlags);
  397. m_gbufferTex[1] = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT | tsFlags);
  398. gbufferAt[0].init(m_gbufferTex[0]);
  399. gbufferAt[1].init(m_gbufferTex[1]);
  400. }
  401. m_gbufferTex[2] = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::D24S8, BGFX_TEXTURE_RT | tsFlags);
  402. gbufferAt[2].init(m_gbufferTex[2]);
  403. m_gbuffer = bgfx::createFrameBuffer(BX_COUNTOF(gbufferAt), gbufferAt, true);
  404. if (bgfx::isValid(m_lightBuffer) )
  405. {
  406. bgfx::destroy(m_lightBuffer);
  407. }
  408. if (m_useUav)
  409. {
  410. bgfx::Attachment lightAt[2];
  411. bgfx::TextureHandle target = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT | tsFlags);
  412. m_lightBufferTex = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_COMPUTE_WRITE | tsFlags);
  413. lightAt[0].init(target);
  414. lightAt[1].init(m_lightBufferTex, bgfx::Access::ReadWrite);
  415. m_lightBuffer = bgfx::createFrameBuffer(BX_COUNTOF(lightAt), lightAt, true);
  416. }
  417. else
  418. {
  419. m_lightBufferTex = bgfx::createTexture2D(uint16_t(m_width), uint16_t(m_height), false, 1, bgfx::TextureFormat::BGRA8, BGFX_TEXTURE_RT | tsFlags);
  420. m_lightBuffer = bgfx::createFrameBuffer(1, &m_lightBufferTex, true);
  421. }
  422. }
  423. ImGui::SetNextWindowPos(
  424. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  425. , ImGuiCond_FirstUseEver
  426. );
  427. ImGui::SetNextWindowSize(
  428. ImVec2(m_width / 5.0f, m_height / 3.0f)
  429. , ImGuiCond_FirstUseEver
  430. );
  431. ImGui::Begin("Settings"
  432. , NULL
  433. , 0
  434. );
  435. ImGui::SliderInt("Num lights", &m_numLights, 1, 2048);
  436. ImGui::Checkbox("Show G-Buffer.", &m_showGBuffer);
  437. ImGui::Checkbox("Show light scissor.", &m_showScissorRects);
  438. if (bgfx::isValid(m_lightTaProgram) )
  439. {
  440. ImGui::Checkbox("Use texture array frame buffer.", &m_useTArray);
  441. }
  442. else
  443. {
  444. ImGui::Text("Texture array frame buffer is not supported.");
  445. }
  446. if (bgfx::isValid(m_lightUavProgram) )
  447. {
  448. ImGui::Checkbox("Use UAV frame buffer attachment.", &m_useUav);
  449. }
  450. else
  451. {
  452. ImGui::Text("UAV frame buffer attachment is not supported.");
  453. }
  454. ImGui::Checkbox("Animate mesh.", &m_animateMesh);
  455. ImGui::SliderFloat("Anim.speed", &m_lightAnimationSpeed, 0.0f, 0.4f);
  456. ImGui::End();
  457. // Update camera.
  458. cameraUpdate(deltaTime, m_mouseState);
  459. float view[16];
  460. cameraGetViewMtx(view);
  461. // Setup views
  462. float vp[16];
  463. float invMvp[16];
  464. {
  465. bgfx::setViewRect(kRenderPassGeometry, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  466. bgfx::setViewRect(kRenderPassLight, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  467. bgfx::setViewRect(kRenderPassCombine, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  468. bgfx::setViewRect(kRenderPassDebugLights, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  469. bgfx::setViewRect(kRenderPassDebugGBuffer, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  470. bgfx::setViewFrameBuffer(kRenderPassLight, m_lightBuffer);
  471. float proj[16];
  472. bx::mtxProj(proj, 60.0f, float(m_width)/float(m_height), 0.1f, 100.0f, m_caps->homogeneousDepth);
  473. bgfx::setViewFrameBuffer(kRenderPassGeometry, m_gbuffer);
  474. bgfx::setViewTransform(kRenderPassGeometry, view, proj);
  475. bx::mtxMul(vp, view, proj);
  476. bx::mtxInverse(invMvp, vp);
  477. const bgfx::Caps* caps = bgfx::getCaps();
  478. bx::mtxOrtho(proj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 100.0f, 0.0f, caps->homogeneousDepth);
  479. bgfx::setViewTransform(kRenderPassLight, NULL, proj);
  480. bgfx::setViewTransform(kRenderPassCombine, NULL, proj);
  481. const float aspectRatio = float(m_height)/float(m_width);
  482. const float size = 10.0f;
  483. bx::mtxOrtho(proj, -size, size, size*aspectRatio, -size*aspectRatio, 0.0f, 1000.0f, 0.0f, caps->homogeneousDepth);
  484. bgfx::setViewTransform(kRenderPassDebugGBuffer, NULL, proj);
  485. bx::mtxOrtho(proj, 0.0f, (float)m_width, 0.0f, (float)m_height, 0.0f, 1000.0f, 0.0f, caps->homogeneousDepth);
  486. bgfx::setViewTransform(kRenderPassDebugLights, NULL, proj);
  487. }
  488. const uint32_t dim = 11;
  489. const float offset = (float(dim-1) * 3.0f) * 0.5f;
  490. // Draw into geometry pass.
  491. for (uint32_t yy = 0; yy < dim; ++yy)
  492. {
  493. for (uint32_t xx = 0; xx < dim; ++xx)
  494. {
  495. float mtx[16];
  496. if (m_animateMesh)
  497. {
  498. bx::mtxRotateXY(mtx, time*1.023f + xx*0.21f, time*0.03f + yy*0.37f);
  499. }
  500. else
  501. {
  502. bx::mtxIdentity(mtx);
  503. }
  504. mtx[12] = -offset + float(xx)*3.0f;
  505. mtx[13] = -offset + float(yy)*3.0f;
  506. mtx[14] = 0.0f;
  507. // Set transform for draw call.
  508. bgfx::setTransform(mtx);
  509. // Set vertex and index buffer.
  510. bgfx::setVertexBuffer(0, m_vbh);
  511. bgfx::setIndexBuffer(m_ibh);
  512. // Bind textures.
  513. bgfx::setTexture(0, s_texColor, m_textureColor);
  514. bgfx::setTexture(1, s_texNormal, m_textureNormal);
  515. // Set render states.
  516. bgfx::setState(0
  517. | BGFX_STATE_WRITE_RGB
  518. | BGFX_STATE_WRITE_A
  519. | BGFX_STATE_WRITE_Z
  520. | BGFX_STATE_DEPTH_TEST_LESS
  521. | BGFX_STATE_MSAA
  522. );
  523. // Submit primitive for rendering to view 0.
  524. bgfx::submit(kRenderPassGeometry, m_geomProgram);
  525. }
  526. }
  527. // Clear UAV texture
  528. if (m_useUav)
  529. {
  530. screenSpaceQuad( (float)m_width, (float)m_height, s_texelHalf, m_caps->originBottomLeft);
  531. bgfx::setState(0
  532. | BGFX_STATE_WRITE_RGB
  533. | BGFX_STATE_WRITE_A
  534. );
  535. bgfx::submit(kRenderPassLight, m_clearUavProgram);
  536. }
  537. // Draw lights into light buffer.
  538. for (int32_t light = 0; light < m_numLights; ++light)
  539. {
  540. Sphere lightPosRadius;
  541. float lightTime = time * m_lightAnimationSpeed * (bx::sin(light/float(m_numLights) * bx::kPiHalf ) * 0.5f + 0.5f);
  542. lightPosRadius.center.x = bx::sin( ( (lightTime + light*0.47f) + bx::kPiHalf*1.37f ) )*offset;
  543. lightPosRadius.center.y = bx::cos( ( (lightTime + light*0.69f) + bx::kPiHalf*1.49f ) )*offset;
  544. lightPosRadius.center.z = bx::sin( ( (lightTime + light*0.37f) + bx::kPiHalf*1.57f ) )*2.0f;
  545. lightPosRadius.radius = 2.0f;
  546. Aabb aabb;
  547. toAabb(aabb, lightPosRadius);
  548. const bx::Vec3 box[8] =
  549. {
  550. { aabb.min.x, aabb.min.y, aabb.min.z },
  551. { aabb.min.x, aabb.min.y, aabb.max.z },
  552. { aabb.min.x, aabb.max.y, aabb.min.z },
  553. { aabb.min.x, aabb.max.y, aabb.max.z },
  554. { aabb.max.x, aabb.min.y, aabb.min.z },
  555. { aabb.max.x, aabb.min.y, aabb.max.z },
  556. { aabb.max.x, aabb.max.y, aabb.min.z },
  557. { aabb.max.x, aabb.max.y, aabb.max.z },
  558. };
  559. bx::Vec3 xyz = bx::mulH(box[0], vp);
  560. bx::Vec3 min = xyz;
  561. bx::Vec3 max = xyz;
  562. for (uint32_t ii = 1; ii < 8; ++ii)
  563. {
  564. xyz = bx::mulH(box[ii], vp);
  565. min = bx::min(min, xyz);
  566. max = bx::max(max, xyz);
  567. }
  568. // Cull light if it's fully behind camera.
  569. if (max.z >= 0.0f)
  570. {
  571. const float x0 = bx::clamp( (min.x * 0.5f + 0.5f) * m_width, 0.0f, (float)m_width);
  572. const float y0 = bx::clamp( (min.y * 0.5f + 0.5f) * m_height, 0.0f, (float)m_height);
  573. const float x1 = bx::clamp( (max.x * 0.5f + 0.5f) * m_width, 0.0f, (float)m_width);
  574. const float y1 = bx::clamp( (max.y * 0.5f + 0.5f) * m_height, 0.0f, (float)m_height);
  575. if (m_showScissorRects)
  576. {
  577. bgfx::TransientVertexBuffer tvb;
  578. bgfx::TransientIndexBuffer tib;
  579. if (bgfx::allocTransientBuffers(&tvb, DebugVertex::ms_layout, 4, &tib, 8) )
  580. {
  581. uint32_t abgr = 0x8000ff00;
  582. DebugVertex* vertex = (DebugVertex*)tvb.data;
  583. vertex->m_x = x0;
  584. vertex->m_y = y0;
  585. vertex->m_z = 0.0f;
  586. vertex->m_abgr = abgr;
  587. ++vertex;
  588. vertex->m_x = x1;
  589. vertex->m_y = y0;
  590. vertex->m_z = 0.0f;
  591. vertex->m_abgr = abgr;
  592. ++vertex;
  593. vertex->m_x = x1;
  594. vertex->m_y = y1;
  595. vertex->m_z = 0.0f;
  596. vertex->m_abgr = abgr;
  597. ++vertex;
  598. vertex->m_x = x0;
  599. vertex->m_y = y1;
  600. vertex->m_z = 0.0f;
  601. vertex->m_abgr = abgr;
  602. uint16_t* indices = (uint16_t*)tib.data;
  603. *indices++ = 0;
  604. *indices++ = 1;
  605. *indices++ = 1;
  606. *indices++ = 2;
  607. *indices++ = 2;
  608. *indices++ = 3;
  609. *indices++ = 3;
  610. *indices++ = 0;
  611. bgfx::setVertexBuffer(0, &tvb);
  612. bgfx::setIndexBuffer(&tib);
  613. bgfx::setState(0
  614. | BGFX_STATE_WRITE_RGB
  615. | BGFX_STATE_PT_LINES
  616. | BGFX_STATE_BLEND_ALPHA
  617. );
  618. bgfx::submit(kRenderPassDebugLights, m_lineProgram);
  619. }
  620. }
  621. uint8_t val = light&7;
  622. float lightRgbInnerR[4] =
  623. {
  624. val & 0x1 ? 1.0f : 0.25f,
  625. val & 0x2 ? 1.0f : 0.25f,
  626. val & 0x4 ? 1.0f : 0.25f,
  627. 0.8f,
  628. };
  629. // Draw light.
  630. bgfx::setUniform(u_lightPosRadius, &lightPosRadius);
  631. bgfx::setUniform(u_lightRgbInnerR, lightRgbInnerR);
  632. bgfx::setUniform(u_mtx, invMvp);
  633. const uint16_t scissorHeight = uint16_t(y1-y0);
  634. bgfx::setScissor(uint16_t(x0), uint16_t(m_height-scissorHeight-y0), uint16_t(x1-x0), uint16_t(scissorHeight) );
  635. bgfx::setTexture(0, s_normal, bgfx::getTexture(m_gbuffer, 1) );
  636. bgfx::setTexture(1, s_depth, bgfx::getTexture(m_gbuffer, 2) );
  637. bgfx::setState(0
  638. | BGFX_STATE_WRITE_RGB
  639. | BGFX_STATE_WRITE_A
  640. | BGFX_STATE_BLEND_ADD
  641. );
  642. screenSpaceQuad( (float)m_width, (float)m_height, s_texelHalf, m_caps->originBottomLeft);
  643. if (bgfx::isValid(m_lightTaProgram)
  644. && m_useTArray)
  645. {
  646. bgfx::submit(kRenderPassLight, m_lightTaProgram);
  647. }
  648. else if (bgfx::isValid(m_lightUavProgram)
  649. && m_useUav)
  650. {
  651. bgfx::submit(kRenderPassLight, m_lightUavProgram);
  652. }
  653. else
  654. {
  655. bgfx::submit(kRenderPassLight, m_lightProgram);
  656. }
  657. }
  658. }
  659. // Combine color and light buffers.
  660. bgfx::setTexture(0, s_albedo, m_gbufferTex[0]);
  661. bgfx::setTexture(1, s_light, m_lightBufferTex);
  662. bgfx::setState(0
  663. | BGFX_STATE_WRITE_RGB
  664. | BGFX_STATE_WRITE_A
  665. );
  666. screenSpaceQuad( (float)m_width, (float)m_height, s_texelHalf, m_caps->originBottomLeft);
  667. bgfx::submit(kRenderPassCombine, m_combineProgram);
  668. if (m_showGBuffer)
  669. {
  670. const float aspectRatio = float(m_width)/float(m_height);
  671. // Draw m_debug m_gbuffer.
  672. for (uint32_t ii = 0; ii < BX_COUNTOF(m_gbufferTex); ++ii)
  673. {
  674. float mtx[16];
  675. bx::mtxSRT(mtx
  676. , aspectRatio, 1.0f, 1.0f
  677. , 0.0f, 0.0f, 0.0f
  678. , -7.9f - BX_COUNTOF(m_gbufferTex)*0.1f*0.5f + ii*2.1f*aspectRatio, 4.0f, 0.0f
  679. );
  680. bgfx::setTransform(mtx);
  681. bgfx::setVertexBuffer(0, m_vbh);
  682. bgfx::setIndexBuffer(m_ibh, 0, 6);
  683. bgfx::setTexture(0, s_texColor, m_gbufferTex[ii]);
  684. bgfx::setState(BGFX_STATE_WRITE_RGB);
  685. bgfx::submit(kRenderPassDebugGBuffer, m_debugProgram);
  686. }
  687. }
  688. }
  689. imguiEndFrame();
  690. // Advance to next frame. Rendering thread will be kicked to
  691. // process submitted rendering primitives.
  692. bgfx::frame();
  693. return true;
  694. }
  695. return false;
  696. }
  697. bgfx::VertexBufferHandle m_vbh;
  698. bgfx::IndexBufferHandle m_ibh;
  699. bgfx::UniformHandle s_texColor;
  700. bgfx::UniformHandle s_texNormal;
  701. bgfx::UniformHandle s_albedo;
  702. bgfx::UniformHandle s_normal;
  703. bgfx::UniformHandle s_depth;
  704. bgfx::UniformHandle s_light;
  705. bgfx::UniformHandle u_mtx;
  706. bgfx::UniformHandle u_lightPosRadius;
  707. bgfx::UniformHandle u_lightRgbInnerR;
  708. bgfx::ProgramHandle m_geomProgram;
  709. bgfx::ProgramHandle m_lightProgram;
  710. bgfx::ProgramHandle m_lightTaProgram;
  711. bgfx::ProgramHandle m_lightUavProgram;
  712. bgfx::ProgramHandle m_clearUavProgram;
  713. bgfx::ProgramHandle m_combineProgram;
  714. bgfx::ProgramHandle m_debugProgram;
  715. bgfx::ProgramHandle m_lineProgram;
  716. bgfx::TextureHandle m_textureColor;
  717. bgfx::TextureHandle m_textureNormal;
  718. bgfx::TextureHandle m_gbufferTex[3];
  719. bgfx::TextureHandle m_lightBufferTex;
  720. bgfx::FrameBufferHandle m_gbuffer;
  721. bgfx::FrameBufferHandle m_lightBuffer;
  722. uint32_t m_width;
  723. uint32_t m_height;
  724. uint32_t m_debug;
  725. uint32_t m_reset;
  726. uint32_t m_oldWidth;
  727. uint32_t m_oldHeight;
  728. uint32_t m_oldReset;
  729. bool m_useTArray;
  730. bool m_oldUseTArray;
  731. bool m_useUav;
  732. bool m_oldUseUav;
  733. int32_t m_scrollArea;
  734. int32_t m_numLights;
  735. float m_lightAnimationSpeed;
  736. bool m_animateMesh;
  737. bool m_showScissorRects;
  738. bool m_showGBuffer;
  739. entry::MouseState m_mouseState;
  740. const bgfx::Caps* m_caps;
  741. int64_t m_timeOffset;
  742. };
  743. } // namespace
  744. ENTRY_IMPLEMENT_MAIN(ExampleDeferred, "21-deferred", "MRT rendering and deferred shading.");