screen_space_shadows.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /*
  2. * Copyright 2021 elven cache. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. /*
  6. * Implement screen space shadows as bgfx example. Goal is to explore various
  7. * options and parameters.
  8. *
  9. * radius
  10. * ======
  11. * Use radius/shadow distance defined in screen space pixels or world units.
  12. *
  13. * In world uints, the screen distance will shrink as objects get farther away.
  14. * This can provide more natural looking shadows and fade out the effect at a
  15. * distance, leaving screen space shadows as an added detail effect near the
  16. * camera.
  17. *
  18. * Screen space units mean that objects will cast the same length of shadow
  19. * regardless of how far they are away from the camera. Pull back the camera
  20. * and objects' shadows will appear to grow. On the other hand, this can be
  21. * desired because it will allow objects at the horizon like hills and trees to
  22. * cast a shadow. Depending on your scene, such far objects may be outside of
  23. * the area affected by regular shadow maps. Even with multiple cascades, you
  24. * may not be able to afford shadow maps across the entire scene.
  25. *
  26. * This sample does not put effort into avoiding the initial pixel or avoiding
  27. * resampling the same value if the step size is relatively smaller than the
  28. * sampled distance in screen space. May want to set a minimum distance so each
  29. * sample covers a unique value or take care to select a neighboring pixel for
  30. * the first sample.
  31. *
  32. * soft contact shadows
  33. * ====================
  34. * If hard screen space shadows are added to a scene that already has soft
  35. * shadows via shadow maps, the hard edge can look out of place. Additionally,
  36. * it is common for screen space shadows to not quite line up with other
  37. * shadows. This is because the depth buffer does not specify thickness,
  38. * leaving some pixels incorrectly occluded. For example, you would not want
  39. * some thin feature like a pipe to cast a shadow as if you were seeing the
  40. * side of a metal wall.
  41. *
  42. * These soft contact shadows are an attempt to minimize the problems described
  43. * above. By adding a smoother falloff, they may blend into the scene better.
  44. * Inspired by screen space ambient occlusion, this sample takes into account
  45. * distance from shadowed pixel to its occluders.
  46. *
  47. * - hard If there's any occluder found, mark the source pixel as shadowed.
  48. *
  49. * - soft Modulate shadow by distance to the first occluder. Assuming a
  50. * nearby pixel is closer and more likely to represent an accurate
  51. * shadow, it is darker. If the first pixel to be an occluder is far
  52. * away, it should likely cast a softer shadow.
  53. *
  54. * - very In addition to the same modulation used by soft mode, also
  55. * soft reduce the occlusion contribution from pixels that are farther
  56. * away. This sample compares the depth difference to the shadow
  57. * radius, a 1D distance, instead of comparing the actually
  58. * distance in 3D space.
  59. */
  60. #include <common.h>
  61. #include <camera.h>
  62. #include <bgfx_utils.h>
  63. #include <imgui/imgui.h>
  64. #include <bx/rng.h>
  65. #include <bx/os.h>
  66. namespace {
  67. // Gbuffer has multiple render targets
  68. #define GBUFFER_RT_COLOR 0
  69. #define GBUFFER_RT_NORMAL 1
  70. #define GBUFFER_RT_DEPTH 2
  71. #define GBUFFER_RENDER_TARGETS 3
  72. #define MODEL_COUNT 100
  73. static const char * s_meshPaths[] =
  74. {
  75. "meshes/unit_sphere.bin",
  76. "meshes/column.bin",
  77. "meshes/tree.bin",
  78. "meshes/hollowcube.bin",
  79. "meshes/bunny.bin"
  80. };
  81. static const float s_meshScale[] =
  82. {
  83. 0.25f,
  84. 0.05f,
  85. 0.15f,
  86. 0.25f,
  87. 0.25f
  88. };
  89. // Vertex decl for our screen space quad (used in deferred rendering)
  90. struct PosTexCoord0Vertex
  91. {
  92. float m_x;
  93. float m_y;
  94. float m_z;
  95. float m_u;
  96. float m_v;
  97. static void init()
  98. {
  99. ms_layout
  100. .begin()
  101. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  102. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  103. .end();
  104. }
  105. static bgfx::VertexLayout ms_layout;
  106. };
  107. bgfx::VertexLayout PosTexCoord0Vertex::ms_layout;
  108. struct Uniforms
  109. {
  110. enum { NumVec4 = 12 };
  111. void init() {
  112. u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, NumVec4);
  113. };
  114. void submit() const {
  115. bgfx::setUniform(u_params, m_params, NumVec4);
  116. }
  117. void destroy() {
  118. bgfx::destroy(u_params);
  119. }
  120. union
  121. {
  122. struct
  123. {
  124. /* 0 */ struct { float m_frameIdx; float m_shadowRadius; float m_shadowSteps; float m_useNoiseOffset; };
  125. /* 1 */ struct { float m_depthUnpackConsts[2]; float m_contactShadowsMode; float m_useScreenSpaceRadius; };
  126. /* 2 */ struct { float m_ndcToViewMul[2]; float m_ndcToViewAdd[2]; };
  127. /* 3 */ struct { float m_lightPosition[3]; float m_displayShadows; };
  128. /* 4-7 */ struct { float m_worldToView[16]; }; // built-in u_view will be transform for quad during screen passes
  129. /* 8-11 */ struct { float m_viewToProj[16]; }; // built-in u_proj will be transform for quad during screen passes
  130. };
  131. float m_params[NumVec4 * 4];
  132. };
  133. bgfx::UniformHandle u_params;
  134. };
  135. struct RenderTarget
  136. {
  137. void init(uint32_t _width, uint32_t _height, bgfx::TextureFormat::Enum _format, uint64_t _flags)
  138. {
  139. m_texture = bgfx::createTexture2D(uint16_t(_width), uint16_t(_height), false, 1, _format, _flags);
  140. const bool destroyTextures = true;
  141. m_buffer = bgfx::createFrameBuffer(1, &m_texture, destroyTextures);
  142. }
  143. void destroy()
  144. {
  145. // also responsible for destroying texture
  146. bgfx::destroy(m_buffer);
  147. }
  148. bgfx::TextureHandle m_texture;
  149. bgfx::FrameBufferHandle m_buffer;
  150. };
  151. void screenSpaceQuad(bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
  152. {
  153. if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_layout))
  154. {
  155. bgfx::TransientVertexBuffer vb;
  156. bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_layout);
  157. PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
  158. const float minx = -_width;
  159. const float maxx = _width;
  160. const float miny = 0.0f;
  161. const float maxy = _height * 2.0f;
  162. const float minu = -1.0f;
  163. const float maxu = 1.0f;
  164. const float zz = 0.0f;
  165. float minv = 0.0f;
  166. float maxv = 2.0f;
  167. if (_originBottomLeft)
  168. {
  169. float temp = minv;
  170. minv = maxv;
  171. maxv = temp;
  172. minv -= 1.0f;
  173. maxv -= 1.0f;
  174. }
  175. vertex[0].m_x = minx;
  176. vertex[0].m_y = miny;
  177. vertex[0].m_z = zz;
  178. vertex[0].m_u = minu;
  179. vertex[0].m_v = minv;
  180. vertex[1].m_x = maxx;
  181. vertex[1].m_y = miny;
  182. vertex[1].m_z = zz;
  183. vertex[1].m_u = maxu;
  184. vertex[1].m_v = minv;
  185. vertex[2].m_x = maxx;
  186. vertex[2].m_y = maxy;
  187. vertex[2].m_z = zz;
  188. vertex[2].m_u = maxu;
  189. vertex[2].m_v = maxv;
  190. bgfx::setVertexBuffer(0, &vb);
  191. }
  192. }
  193. void vec2Set(float* _v, float _x, float _y)
  194. {
  195. _v[0] = _x;
  196. _v[1] = _y;
  197. }
  198. void mat4Set(float * _m, const float * _src)
  199. {
  200. const uint32_t MAT4_FLOATS = 16;
  201. for (uint32_t ii = 0; ii < MAT4_FLOATS; ++ii) {
  202. _m[ii] = _src[ii];
  203. }
  204. }
  205. class ExampleScreenSpaceShadows : public entry::AppI
  206. {
  207. public:
  208. ExampleScreenSpaceShadows(const char* _name, const char* _description)
  209. : entry::AppI(_name, _description)
  210. , m_currFrame(UINT32_MAX)
  211. {
  212. }
  213. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  214. {
  215. Args args(_argc, _argv);
  216. m_width = _width;
  217. m_height = _height;
  218. m_debug = BGFX_DEBUG_NONE;
  219. m_reset = BGFX_RESET_VSYNC;
  220. bgfx::Init init;
  221. init.type = args.m_type;
  222. init.vendorId = args.m_pciId;
  223. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  224. init.platformData.ndt = entry::getNativeDisplayHandle();
  225. init.platformData.type = entry::getNativeWindowHandleType(entry::kDefaultWindowHandle);
  226. init.resolution.width = m_width;
  227. init.resolution.height = m_height;
  228. init.resolution.reset = m_reset;
  229. bgfx::init(init);
  230. // Enable debug text.
  231. bgfx::setDebug(m_debug);
  232. // Create uniforms
  233. m_uniforms.init();
  234. // Create texture sampler uniforms (used when we bind textures)
  235. s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler); // Model's source albedo
  236. s_color = bgfx::createUniform("s_color", bgfx::UniformType::Sampler); // Color (albedo) gbuffer, default color input
  237. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Sampler); // Normal gbuffer, Model's source normal
  238. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler); // Depth gbuffer
  239. s_shadows = bgfx::createUniform("s_shadows", bgfx::UniformType::Sampler);
  240. // Create program from shaders.
  241. m_gbufferProgram = loadProgram("vs_sss_gbuffer", "fs_sss_gbuffer"); // Fill gbuffer
  242. m_sphereProgram = loadProgram("vs_sss_gbuffer", "fs_sss_unlit");
  243. m_linearDepthProgram = loadProgram("vs_sss_screenquad", "fs_sss_linear_depth");
  244. m_shadowsProgram = loadProgram("vs_sss_screenquad", "fs_screen_space_shadows");
  245. m_combineProgram = loadProgram("vs_sss_screenquad", "fs_sss_deferred_combine"); // Compute lighting from gbuffer
  246. // Load some meshes
  247. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  248. {
  249. m_meshes[ii] = meshLoad(s_meshPaths[ii]);
  250. }
  251. // sphere is first mesh
  252. m_lightModel.mesh = 0;
  253. // Randomly create some models
  254. bx::RngMwc mwc;
  255. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  256. {
  257. Model& model = m_models[ii];
  258. model.mesh = mwc.gen() % BX_COUNTOF(s_meshPaths);
  259. model.position[0] = (((mwc.gen() % 256)) - 128.0f) / 20.0f;
  260. model.position[1] = 0;
  261. model.position[2] = (((mwc.gen() % 256)) - 128.0f) / 20.0f;
  262. }
  263. // Load ground, just use the cube
  264. m_ground = meshLoad("meshes/cube.bin");
  265. m_groundTexture = loadTexture("textures/fieldstone-rgba.dds");
  266. m_normalTexture = loadTexture("textures/fieldstone-n.dds");
  267. m_recreateFrameBuffers = false;
  268. createFramebuffers();
  269. // Vertex decl
  270. PosTexCoord0Vertex::init();
  271. // Init camera
  272. cameraCreate();
  273. cameraSetPosition({ 0.0f, 1.5f, -4.0f });
  274. cameraSetVerticalAngle(-0.3f);
  275. m_fovY = 60.0f;
  276. cameraGetViewMtx(m_view);
  277. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  278. // Track whether previous results are valid
  279. m_havePrevious = false;
  280. imguiCreate();
  281. }
  282. int32_t shutdown() override
  283. {
  284. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  285. {
  286. meshUnload(m_meshes[ii]);
  287. }
  288. meshUnload(m_ground);
  289. bgfx::destroy(m_normalTexture);
  290. bgfx::destroy(m_groundTexture);
  291. bgfx::destroy(m_gbufferProgram);
  292. bgfx::destroy(m_sphereProgram);
  293. bgfx::destroy(m_linearDepthProgram);
  294. bgfx::destroy(m_shadowsProgram);
  295. bgfx::destroy(m_combineProgram);
  296. m_uniforms.destroy();
  297. bgfx::destroy(s_albedo);
  298. bgfx::destroy(s_color);
  299. bgfx::destroy(s_normal);
  300. bgfx::destroy(s_depth);
  301. bgfx::destroy(s_shadows);
  302. destroyFramebuffers();
  303. cameraDestroy();
  304. imguiDestroy();
  305. bgfx::shutdown();
  306. return 0;
  307. }
  308. bool update() override
  309. {
  310. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  311. {
  312. // skip processing when minimized, otherwise crashing
  313. if (0 == m_width
  314. || 0 == m_height)
  315. {
  316. return true;
  317. }
  318. // Update frame timer
  319. int64_t now = bx::getHPCounter();
  320. static int64_t last = now;
  321. const int64_t frameTime = now - last;
  322. last = now;
  323. const double freq = double(bx::getHPFrequency());
  324. const float deltaTime = float(frameTime / freq);
  325. const bgfx::Caps* caps = bgfx::getCaps();
  326. if (m_size[0] != (int32_t)m_width
  327. || m_size[1] != (int32_t)m_height
  328. || m_recreateFrameBuffers)
  329. {
  330. destroyFramebuffers();
  331. createFramebuffers();
  332. m_recreateFrameBuffers = false;
  333. }
  334. // rotate light
  335. const float rotationSpeed = m_moveLight ? 0.75f : 0.0f;
  336. m_lightRotation += deltaTime * rotationSpeed;
  337. if (bx::kPi2 < m_lightRotation)
  338. {
  339. m_lightRotation -= bx::kPi2;
  340. }
  341. m_lightModel.position[0] = bx::cos(m_lightRotation) * 3.0f;
  342. m_lightModel.position[1] = 1.5f;
  343. m_lightModel.position[2] = bx::sin(m_lightRotation) * 3.0f;
  344. // Update camera
  345. cameraUpdate(deltaTime*0.15f, m_mouseState, ImGui::MouseOverArea() );
  346. // Set up matrices for gbuffer
  347. cameraGetViewMtx(m_view);
  348. updateUniforms();
  349. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, caps->homogeneousDepth);
  350. bx::mtxProj(m_proj2, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, false);
  351. bgfx::ViewId view = 0;
  352. // Draw everything into gbuffer
  353. {
  354. bgfx::setViewName(view, "gbuffer");
  355. bgfx::setViewClear(view
  356. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  357. , 0
  358. , 1.0f
  359. , 0
  360. );
  361. bgfx::setViewRect(view, 0, 0, uint16_t(m_size[0]), uint16_t(m_size[1]));
  362. bgfx::setViewTransform(view, m_view, m_proj);
  363. // Make sure when we draw it goes into gbuffer and not backbuffer
  364. bgfx::setViewFrameBuffer(view, m_gbuffer);
  365. bgfx::setState(0
  366. | BGFX_STATE_WRITE_RGB
  367. | BGFX_STATE_WRITE_A
  368. | BGFX_STATE_WRITE_Z
  369. | BGFX_STATE_DEPTH_TEST_LESS
  370. );
  371. drawAllModels(view, m_gbufferProgram, m_uniforms);
  372. // draw sphere to visualize light
  373. {
  374. const float scale = s_meshScale[m_lightModel.mesh];
  375. float mtx[16];
  376. bx::mtxSRT(mtx
  377. , scale
  378. , scale
  379. , scale
  380. , 0.0f
  381. , 0.0f
  382. , 0.0f
  383. , m_lightModel.position[0]
  384. , m_lightModel.position[1]
  385. , m_lightModel.position[2]
  386. );
  387. m_uniforms.submit();
  388. meshSubmit(m_meshes[m_lightModel.mesh], view, m_sphereProgram, mtx);
  389. }
  390. ++view;
  391. }
  392. float orthoProj[16];
  393. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  394. {
  395. // clear out transform stack
  396. float identity[16];
  397. bx::mtxIdentity(identity);
  398. bgfx::setTransform(identity);
  399. }
  400. // Convert depth to linear depth for shadow depth compare
  401. {
  402. bgfx::setViewName(view, "linear depth");
  403. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  404. bgfx::setViewTransform(view, NULL, orthoProj);
  405. bgfx::setViewFrameBuffer(view, m_linearDepth.m_buffer);
  406. bgfx::setState(0
  407. | BGFX_STATE_WRITE_RGB
  408. | BGFX_STATE_WRITE_A
  409. | BGFX_STATE_DEPTH_TEST_ALWAYS
  410. );
  411. bgfx::setTexture(0, s_depth, m_gbufferTex[GBUFFER_RT_DEPTH]);
  412. m_uniforms.submit();
  413. screenSpaceQuad(caps->originBottomLeft);
  414. bgfx::submit(view, m_linearDepthProgram);
  415. ++view;
  416. }
  417. // Do screen space shadows
  418. {
  419. bgfx::setViewName(view, "screen space shadows");
  420. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  421. bgfx::setViewTransform(view, NULL, orthoProj);
  422. bgfx::setViewFrameBuffer(view, m_shadows.m_buffer);
  423. bgfx::setState(0
  424. | BGFX_STATE_WRITE_RGB
  425. | BGFX_STATE_WRITE_A
  426. | BGFX_STATE_DEPTH_TEST_ALWAYS
  427. );
  428. bgfx::setTexture(0, s_depth, m_linearDepth.m_texture);
  429. m_uniforms.submit();
  430. screenSpaceQuad(caps->originBottomLeft);
  431. bgfx::submit(view, m_shadowsProgram);
  432. ++view;
  433. }
  434. // Shade gbuffer
  435. {
  436. bgfx::setViewName(view, "combine");
  437. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  438. bgfx::setViewTransform(view, NULL, orthoProj);
  439. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  440. bgfx::setState(0
  441. | BGFX_STATE_WRITE_RGB
  442. | BGFX_STATE_WRITE_A
  443. | BGFX_STATE_DEPTH_TEST_ALWAYS
  444. );
  445. bgfx::setTexture(0, s_color, m_gbufferTex[GBUFFER_RT_COLOR]);
  446. bgfx::setTexture(1, s_normal, m_gbufferTex[GBUFFER_RT_NORMAL]);
  447. bgfx::setTexture(2, s_depth, m_linearDepth.m_texture);
  448. bgfx::setTexture(3, s_shadows, m_shadows.m_texture);
  449. m_uniforms.submit();
  450. screenSpaceQuad(caps->originBottomLeft);
  451. bgfx::submit(view, m_combineProgram);
  452. ++view;
  453. }
  454. // Draw UI
  455. imguiBeginFrame(m_mouseState.m_mx
  456. , m_mouseState.m_my
  457. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  458. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  459. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  460. , m_mouseState.m_mz
  461. , uint16_t(m_width)
  462. , uint16_t(m_height)
  463. );
  464. showExampleDialog(this);
  465. ImGui::SetNextWindowPos(
  466. ImVec2(m_width - m_width / 4.0f - 10.0f, 10.0f)
  467. , ImGuiCond_FirstUseEver
  468. );
  469. ImGui::SetNextWindowSize(
  470. ImVec2(m_width / 4.0f, m_height / 2.3f)
  471. , ImGuiCond_FirstUseEver
  472. );
  473. ImGui::Begin("Settings"
  474. , NULL
  475. , 0
  476. );
  477. ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
  478. {
  479. ImGui::Text("shadow controls:");
  480. ImGui::Checkbox("screen space radius", &m_useScreenSpaceRadius);
  481. if (ImGui::IsItemHovered())
  482. ImGui::SetTooltip("define radius in pixels or world units");
  483. if (m_useScreenSpaceRadius)
  484. {
  485. ImGui::SliderFloat("radius in pixels", &m_shadowRadiusPixels, 1.0f, 100.0f);
  486. }
  487. else
  488. {
  489. ImGui::SliderFloat("radius in world units", &m_shadowRadius, 1e-3f, 1.0f);
  490. }
  491. ImGui::SliderInt("shadow steps", &m_shadowSteps, 1, 64);
  492. if (ImGui::IsItemHovered())
  493. ImGui::SetTooltip("number of steps/samples to take between shaded pixel and radius");
  494. ImGui::Combo("contact shadows mode", &m_contactShadowsMode, "hard\0soft\0very soft\0\0");
  495. if (ImGui::IsItemHovered())
  496. {
  497. ImGui::BeginTooltip();
  498. ImGui::Text("hard");
  499. ImGui::BulletText("any occluder, fully shadowed");
  500. ImGui::Text("soft");
  501. ImGui::BulletText("modulate shadow by distance to first occluder");
  502. ImGui::Text("very soft");
  503. ImGui::BulletText("also reduce each shadow contribution by distance");
  504. ImGui::EndTooltip();
  505. }
  506. ImGui::Checkbox("add random offset to initial position", &m_useNoiseOffset);
  507. if (ImGui::IsItemHovered())
  508. ImGui::SetTooltip("hide banding with noise");
  509. ImGui::Checkbox("use different offset each frame", &m_dynamicNoise);
  510. ImGui::Separator();
  511. ImGui::Text("scene controls:");
  512. ImGui::Checkbox("display shadows only", &m_displayShadows);
  513. ImGui::Checkbox("move light", &m_moveLight);
  514. }
  515. ImGui::End();
  516. imguiEndFrame();
  517. // Advance to next frame. Rendering thread will be kicked to
  518. // process submitted rendering primitives.
  519. m_currFrame = bgfx::frame();
  520. return true;
  521. }
  522. return false;
  523. }
  524. void drawAllModels(bgfx::ViewId _pass, bgfx::ProgramHandle _program, const Uniforms & _uniforms)
  525. {
  526. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  527. {
  528. const Model& model = m_models[ii];
  529. // Set up transform matrix for each model
  530. const float scale = s_meshScale[model.mesh];
  531. float mtx[16];
  532. bx::mtxSRT(mtx
  533. , scale
  534. , scale
  535. , scale
  536. , 0.0f
  537. , 0.0f
  538. , 0.0f
  539. , model.position[0]
  540. , model.position[1]
  541. , model.position[2]
  542. );
  543. // Submit mesh to gbuffer
  544. bgfx::setTexture(0, s_albedo, m_groundTexture);
  545. bgfx::setTexture(1, s_normal, m_normalTexture);
  546. _uniforms.submit();
  547. meshSubmit(m_meshes[model.mesh], _pass, _program, mtx);
  548. }
  549. // Draw ground
  550. float mtxScale[16];
  551. const float scale = 10.0f;
  552. bx::mtxScale(mtxScale, scale, scale, scale);
  553. float mtxTranslate[16];
  554. bx::mtxTranslate(mtxTranslate
  555. , 0.0f
  556. , -10.0f
  557. , 0.0f
  558. );
  559. float mtx[16];
  560. bx::mtxMul(mtx, mtxScale, mtxTranslate);
  561. bgfx::setTexture(0, s_albedo, m_groundTexture);
  562. bgfx::setTexture(1, s_normal, m_normalTexture);
  563. _uniforms.submit();
  564. meshSubmit(m_ground, _pass, _program, mtx);
  565. }
  566. void createFramebuffers()
  567. {
  568. m_size[0] = m_width;
  569. m_size[1] = m_height;
  570. const uint64_t pointSampleFlags = 0
  571. | BGFX_TEXTURE_RT
  572. | BGFX_SAMPLER_U_CLAMP
  573. | BGFX_SAMPLER_V_CLAMP
  574. | BGFX_SAMPLER_MIN_POINT
  575. | BGFX_SAMPLER_MAG_POINT
  576. | BGFX_SAMPLER_MIP_POINT
  577. ;
  578. m_gbufferTex[GBUFFER_RT_COLOR] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, pointSampleFlags);
  579. m_gbufferTex[GBUFFER_RT_NORMAL] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, pointSampleFlags);
  580. m_gbufferTex[GBUFFER_RT_DEPTH] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::D32F, pointSampleFlags);
  581. m_gbuffer = bgfx::createFrameBuffer(BX_COUNTOF(m_gbufferTex), m_gbufferTex, true);
  582. m_linearDepth.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, pointSampleFlags);
  583. m_shadows.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, pointSampleFlags);
  584. }
  585. // all buffers set to destroy their textures
  586. void destroyFramebuffers()
  587. {
  588. bgfx::destroy(m_gbuffer);
  589. m_linearDepth.destroy();
  590. m_shadows.destroy();
  591. }
  592. void updateUniforms()
  593. {
  594. m_uniforms.m_displayShadows = m_displayShadows ? 1.0f : 0.0f;
  595. m_uniforms.m_frameIdx = m_dynamicNoise
  596. ? float(m_currFrame % 8)
  597. : 0.0f;
  598. m_uniforms.m_shadowRadius = m_useScreenSpaceRadius ? m_shadowRadiusPixels : m_shadowRadius;
  599. m_uniforms.m_shadowSteps = float(m_shadowSteps);
  600. m_uniforms.m_useNoiseOffset = m_useNoiseOffset ? 1.0f : 0.0f;
  601. m_uniforms.m_contactShadowsMode = float(m_contactShadowsMode);
  602. m_uniforms.m_useScreenSpaceRadius = m_useScreenSpaceRadius ? 1.0f : 0.0f;
  603. mat4Set(m_uniforms.m_worldToView, m_view);
  604. mat4Set(m_uniforms.m_viewToProj, m_proj);
  605. // from assao sample, cs_assao_prepare_depths.sc
  606. {
  607. // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
  608. // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
  609. // correct the handedness issue. need to make sure this below is correct, but I think it is.
  610. float depthLinearizeMul = -m_proj2[3*4+2];
  611. float depthLinearizeAdd = m_proj2[2*4+2];
  612. if (depthLinearizeMul * depthLinearizeAdd < 0)
  613. {
  614. depthLinearizeAdd = -depthLinearizeAdd;
  615. }
  616. vec2Set(m_uniforms.m_depthUnpackConsts, depthLinearizeMul, depthLinearizeAdd);
  617. float tanHalfFOVY = 1.0f / m_proj2[1*4+1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
  618. float tanHalfFOVX = 1.0F / m_proj2[0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
  619. if (bgfx::getRendererType() == bgfx::RendererType::OpenGL)
  620. {
  621. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * 2.0f);
  622. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * -1.0f);
  623. }
  624. else
  625. {
  626. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f);
  627. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f);
  628. }
  629. }
  630. {
  631. float lightPosition[4];
  632. bx::memCopy(lightPosition, m_lightModel.position, 3*sizeof(float));
  633. lightPosition[3] = 1.0f;
  634. float viewSpaceLightPosition[4];
  635. bx::vec4MulMtx(viewSpaceLightPosition, lightPosition, m_view);
  636. bx::memCopy(m_uniforms.m_lightPosition, viewSpaceLightPosition, 3*sizeof(float));
  637. }
  638. }
  639. uint32_t m_width;
  640. uint32_t m_height;
  641. uint32_t m_debug;
  642. uint32_t m_reset;
  643. entry::MouseState m_mouseState;
  644. // Resource handles
  645. bgfx::ProgramHandle m_gbufferProgram;
  646. bgfx::ProgramHandle m_sphereProgram;
  647. bgfx::ProgramHandle m_linearDepthProgram;
  648. bgfx::ProgramHandle m_shadowsProgram;
  649. bgfx::ProgramHandle m_combineProgram;
  650. // Shader uniforms
  651. Uniforms m_uniforms;
  652. // Uniforms to identify texture samplers
  653. bgfx::UniformHandle s_albedo;
  654. bgfx::UniformHandle s_color;
  655. bgfx::UniformHandle s_normal;
  656. bgfx::UniformHandle s_depth;
  657. bgfx::UniformHandle s_shadows;
  658. bgfx::FrameBufferHandle m_gbuffer;
  659. bgfx::TextureHandle m_gbufferTex[GBUFFER_RENDER_TARGETS];
  660. RenderTarget m_linearDepth;
  661. RenderTarget m_shadows;
  662. struct Model
  663. {
  664. uint32_t mesh; // Index of mesh in m_meshes
  665. float position[3];
  666. };
  667. Model m_lightModel;
  668. Model m_models[MODEL_COUNT];
  669. Mesh* m_meshes[BX_COUNTOF(s_meshPaths)];
  670. Mesh* m_ground;
  671. bgfx::TextureHandle m_groundTexture;
  672. bgfx::TextureHandle m_normalTexture;
  673. uint32_t m_currFrame;
  674. float m_lightRotation = 0.0f;
  675. float m_fovY = 60.0f;
  676. bool m_recreateFrameBuffers = false;
  677. bool m_havePrevious = false;
  678. float m_view[16];
  679. float m_proj[16];
  680. float m_proj2[16];
  681. int32_t m_size[2];
  682. // UI parameters
  683. bool m_displayShadows = false;
  684. bool m_useNoiseOffset = true;
  685. bool m_dynamicNoise = true;
  686. float m_shadowRadius = 0.25f;
  687. float m_shadowRadiusPixels = 25.0f;
  688. int32_t m_shadowSteps = 8;
  689. bool m_moveLight = true;
  690. int32_t m_contactShadowsMode = 0;
  691. bool m_useScreenSpaceRadius = false;
  692. };
  693. } // namespace
  694. ENTRY_IMPLEMENT_MAIN(
  695. ExampleScreenSpaceShadows
  696. , "44-sss"
  697. , "Screen Space Shadows."
  698. );