deferred.cpp 28 KB

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