screen_space_shadows.cpp 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846
  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(float _textureWidth, float _textureHeight, float _texelHalf, 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 texelHalfW = _texelHalf / _textureWidth;
  163. const float texelHalfH = _texelHalf / _textureHeight;
  164. const float minu = -1.0f + texelHalfW;
  165. const float maxu = 1.0f + texelHalfW;
  166. const float zz = 0.0f;
  167. float minv = texelHalfH;
  168. float maxv = 2.0f + texelHalfH;
  169. if (_originBottomLeft)
  170. {
  171. float temp = minv;
  172. minv = maxv;
  173. maxv = temp;
  174. minv -= 1.0f;
  175. maxv -= 1.0f;
  176. }
  177. vertex[0].m_x = minx;
  178. vertex[0].m_y = miny;
  179. vertex[0].m_z = zz;
  180. vertex[0].m_u = minu;
  181. vertex[0].m_v = minv;
  182. vertex[1].m_x = maxx;
  183. vertex[1].m_y = miny;
  184. vertex[1].m_z = zz;
  185. vertex[1].m_u = maxu;
  186. vertex[1].m_v = minv;
  187. vertex[2].m_x = maxx;
  188. vertex[2].m_y = maxy;
  189. vertex[2].m_z = zz;
  190. vertex[2].m_u = maxu;
  191. vertex[2].m_v = maxv;
  192. bgfx::setVertexBuffer(0, &vb);
  193. }
  194. }
  195. void vec2Set(float* _v, float _x, float _y)
  196. {
  197. _v[0] = _x;
  198. _v[1] = _y;
  199. }
  200. void mat4Set(float * _m, const float * _src)
  201. {
  202. const uint32_t MAT4_FLOATS = 16;
  203. for (uint32_t ii = 0; ii < MAT4_FLOATS; ++ii) {
  204. _m[ii] = _src[ii];
  205. }
  206. }
  207. class ExampleScreenSpaceShadows : public entry::AppI
  208. {
  209. public:
  210. ExampleScreenSpaceShadows(const char* _name, const char* _description)
  211. : entry::AppI(_name, _description)
  212. , m_currFrame(UINT32_MAX)
  213. , m_texelHalf(0.0f)
  214. {
  215. }
  216. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  217. {
  218. Args args(_argc, _argv);
  219. m_width = _width;
  220. m_height = _height;
  221. m_debug = BGFX_DEBUG_NONE;
  222. m_reset = BGFX_RESET_VSYNC;
  223. bgfx::Init init;
  224. init.type = args.m_type;
  225. init.vendorId = args.m_pciId;
  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. // Get renderer capabilities info.
  281. const bgfx::RendererType::Enum renderer = bgfx::getRendererType();
  282. m_texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f;
  283. imguiCreate();
  284. }
  285. int32_t shutdown() override
  286. {
  287. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  288. {
  289. meshUnload(m_meshes[ii]);
  290. }
  291. meshUnload(m_ground);
  292. bgfx::destroy(m_normalTexture);
  293. bgfx::destroy(m_groundTexture);
  294. bgfx::destroy(m_gbufferProgram);
  295. bgfx::destroy(m_sphereProgram);
  296. bgfx::destroy(m_linearDepthProgram);
  297. bgfx::destroy(m_shadowsProgram);
  298. bgfx::destroy(m_combineProgram);
  299. m_uniforms.destroy();
  300. bgfx::destroy(s_albedo);
  301. bgfx::destroy(s_color);
  302. bgfx::destroy(s_normal);
  303. bgfx::destroy(s_depth);
  304. bgfx::destroy(s_shadows);
  305. destroyFramebuffers();
  306. cameraDestroy();
  307. imguiDestroy();
  308. bgfx::shutdown();
  309. return 0;
  310. }
  311. bool update() override
  312. {
  313. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  314. {
  315. // skip processing when minimized, otherwise crashing
  316. if (0 == m_width || 0 == m_height)
  317. {
  318. return true;
  319. }
  320. // Update frame timer
  321. int64_t now = bx::getHPCounter();
  322. static int64_t last = now;
  323. const int64_t frameTime = now - last;
  324. last = now;
  325. const double freq = double(bx::getHPFrequency());
  326. const float deltaTime = float(frameTime / freq);
  327. const bgfx::Caps* caps = bgfx::getCaps();
  328. if (m_size[0] != (int32_t)m_width
  329. || m_size[1] != (int32_t)m_height
  330. || m_recreateFrameBuffers)
  331. {
  332. destroyFramebuffers();
  333. createFramebuffers();
  334. m_recreateFrameBuffers = false;
  335. }
  336. // rotate light
  337. const float rotationSpeed = m_moveLight ? 0.75f : 0.0f;
  338. m_lightRotation += deltaTime * rotationSpeed;
  339. if (bx::kPi2 < m_lightRotation)
  340. {
  341. m_lightRotation -= bx::kPi2;
  342. }
  343. m_lightModel.position[0] = bx::cos(m_lightRotation) * 3.0f;
  344. m_lightModel.position[1] = 1.5f;
  345. m_lightModel.position[2] = bx::sin(m_lightRotation) * 3.0f;
  346. // Update camera
  347. cameraUpdate(deltaTime*0.15f, m_mouseState, ImGui::MouseOverArea() );
  348. // Set up matrices for gbuffer
  349. cameraGetViewMtx(m_view);
  350. updateUniforms();
  351. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, caps->homogeneousDepth);
  352. bx::mtxProj(m_proj2, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, false);
  353. bgfx::ViewId view = 0;
  354. // Draw everything into gbuffer
  355. {
  356. bgfx::setViewName(view, "gbuffer");
  357. bgfx::setViewClear(view
  358. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  359. , 0
  360. , 1.0f
  361. , 0
  362. );
  363. bgfx::setViewRect(view, 0, 0, uint16_t(m_size[0]), uint16_t(m_size[1]));
  364. bgfx::setViewTransform(view, m_view, m_proj);
  365. // Make sure when we draw it goes into gbuffer and not backbuffer
  366. bgfx::setViewFrameBuffer(view, m_gbuffer);
  367. bgfx::setState(0
  368. | BGFX_STATE_WRITE_RGB
  369. | BGFX_STATE_WRITE_A
  370. | BGFX_STATE_WRITE_Z
  371. | BGFX_STATE_DEPTH_TEST_LESS
  372. );
  373. drawAllModels(view, m_gbufferProgram, m_uniforms);
  374. // draw sphere to visualize light
  375. {
  376. const float scale = s_meshScale[m_lightModel.mesh];
  377. float mtx[16];
  378. bx::mtxSRT(mtx
  379. , scale
  380. , scale
  381. , scale
  382. , 0.0f
  383. , 0.0f
  384. , 0.0f
  385. , m_lightModel.position[0]
  386. , m_lightModel.position[1]
  387. , m_lightModel.position[2]
  388. );
  389. m_uniforms.submit();
  390. meshSubmit(m_meshes[m_lightModel.mesh], view, m_sphereProgram, mtx);
  391. }
  392. ++view;
  393. }
  394. float orthoProj[16];
  395. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  396. {
  397. // clear out transform stack
  398. float identity[16];
  399. bx::mtxIdentity(identity);
  400. bgfx::setTransform(identity);
  401. }
  402. // Convert depth to linear depth for shadow depth compare
  403. {
  404. bgfx::setViewName(view, "linear depth");
  405. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  406. bgfx::setViewTransform(view, NULL, orthoProj);
  407. bgfx::setViewFrameBuffer(view, m_linearDepth.m_buffer);
  408. bgfx::setState(0
  409. | BGFX_STATE_WRITE_RGB
  410. | BGFX_STATE_WRITE_A
  411. | BGFX_STATE_DEPTH_TEST_ALWAYS
  412. );
  413. bgfx::setTexture(0, s_depth, m_gbufferTex[GBUFFER_RT_DEPTH]);
  414. m_uniforms.submit();
  415. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  416. bgfx::submit(view, m_linearDepthProgram);
  417. ++view;
  418. }
  419. // Do screen space shadows
  420. {
  421. bgfx::setViewName(view, "screen space shadows");
  422. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  423. bgfx::setViewTransform(view, NULL, orthoProj);
  424. bgfx::setViewFrameBuffer(view, m_shadows.m_buffer);
  425. bgfx::setState(0
  426. | BGFX_STATE_WRITE_RGB
  427. | BGFX_STATE_WRITE_A
  428. | BGFX_STATE_DEPTH_TEST_ALWAYS
  429. );
  430. bgfx::setTexture(0, s_depth, m_linearDepth.m_texture);
  431. m_uniforms.submit();
  432. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  433. bgfx::submit(view, m_shadowsProgram);
  434. ++view;
  435. }
  436. // Shade gbuffer
  437. {
  438. bgfx::setViewName(view, "combine");
  439. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  440. bgfx::setViewTransform(view, NULL, orthoProj);
  441. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  442. bgfx::setState(0
  443. | BGFX_STATE_WRITE_RGB
  444. | BGFX_STATE_WRITE_A
  445. | BGFX_STATE_DEPTH_TEST_ALWAYS
  446. );
  447. bgfx::setTexture(0, s_color, m_gbufferTex[GBUFFER_RT_COLOR]);
  448. bgfx::setTexture(1, s_normal, m_gbufferTex[GBUFFER_RT_NORMAL]);
  449. bgfx::setTexture(2, s_depth, m_linearDepth.m_texture);
  450. bgfx::setTexture(3, s_shadows, m_shadows.m_texture);
  451. m_uniforms.submit();
  452. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  453. bgfx::submit(view, m_combineProgram);
  454. ++view;
  455. }
  456. // Draw UI
  457. imguiBeginFrame(m_mouseState.m_mx
  458. , m_mouseState.m_my
  459. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  460. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  461. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  462. , m_mouseState.m_mz
  463. , uint16_t(m_width)
  464. , uint16_t(m_height)
  465. );
  466. showExampleDialog(this);
  467. ImGui::SetNextWindowPos(
  468. ImVec2(m_width - m_width / 4.0f - 10.0f, 10.0f)
  469. , ImGuiCond_FirstUseEver
  470. );
  471. ImGui::SetNextWindowSize(
  472. ImVec2(m_width / 4.0f, m_height / 2.3f)
  473. , ImGuiCond_FirstUseEver
  474. );
  475. ImGui::Begin("Settings"
  476. , NULL
  477. , 0
  478. );
  479. ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
  480. {
  481. ImGui::Text("shadow controls:");
  482. ImGui::Checkbox("screen space radius", &m_useScreenSpaceRadius);
  483. if (ImGui::IsItemHovered())
  484. ImGui::SetTooltip("define radius in pixels or world units");
  485. if (m_useScreenSpaceRadius)
  486. {
  487. ImGui::SliderFloat("radius in pixels", &m_shadowRadiusPixels, 1.0f, 100.0f);
  488. }
  489. else
  490. {
  491. ImGui::SliderFloat("radius in world units", &m_shadowRadius, 1e-3f, 1.0f);
  492. }
  493. ImGui::SliderInt("shadow steps", &m_shadowSteps, 1, 64);
  494. if (ImGui::IsItemHovered())
  495. ImGui::SetTooltip("number of steps/samples to take between shaded pixel and radius");
  496. ImGui::Combo("contact shadows mode", &m_contactShadowsMode, "hard\0soft\0very soft\0\0");
  497. if (ImGui::IsItemHovered())
  498. {
  499. ImGui::BeginTooltip();
  500. ImGui::Text("hard");
  501. ImGui::BulletText("any occluder, fully shadowed");
  502. ImGui::Text("soft");
  503. ImGui::BulletText("modulate shadow by distance to first occluder");
  504. ImGui::Text("very soft");
  505. ImGui::BulletText("also reduce each shadow contribution by distance");
  506. ImGui::EndTooltip();
  507. }
  508. ImGui::Checkbox("add random offset to initial position", &m_useNoiseOffset);
  509. if (ImGui::IsItemHovered())
  510. ImGui::SetTooltip("hide banding with noise");
  511. ImGui::Checkbox("use different offset each frame", &m_dynamicNoise);
  512. ImGui::Separator();
  513. ImGui::Text("scene controls:");
  514. ImGui::Checkbox("display shadows only", &m_displayShadows);
  515. ImGui::Checkbox("move light", &m_moveLight);
  516. }
  517. ImGui::End();
  518. imguiEndFrame();
  519. // Advance to next frame. Rendering thread will be kicked to
  520. // process submitted rendering primitives.
  521. m_currFrame = bgfx::frame();
  522. return true;
  523. }
  524. return false;
  525. }
  526. void drawAllModels(bgfx::ViewId _pass, bgfx::ProgramHandle _program, const Uniforms & _uniforms)
  527. {
  528. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  529. {
  530. const Model& model = m_models[ii];
  531. // Set up transform matrix for each model
  532. const float scale = s_meshScale[model.mesh];
  533. float mtx[16];
  534. bx::mtxSRT(mtx
  535. , scale
  536. , scale
  537. , scale
  538. , 0.0f
  539. , 0.0f
  540. , 0.0f
  541. , model.position[0]
  542. , model.position[1]
  543. , model.position[2]
  544. );
  545. // Submit mesh to gbuffer
  546. bgfx::setTexture(0, s_albedo, m_groundTexture);
  547. bgfx::setTexture(1, s_normal, m_normalTexture);
  548. _uniforms.submit();
  549. meshSubmit(m_meshes[model.mesh], _pass, _program, mtx);
  550. }
  551. // Draw ground
  552. float mtxScale[16];
  553. const float scale = 10.0f;
  554. bx::mtxScale(mtxScale, scale, scale, scale);
  555. float mtxTranslate[16];
  556. bx::mtxTranslate(mtxTranslate
  557. , 0.0f
  558. , -10.0f
  559. , 0.0f
  560. );
  561. float mtx[16];
  562. bx::mtxMul(mtx, mtxScale, mtxTranslate);
  563. bgfx::setTexture(0, s_albedo, m_groundTexture);
  564. bgfx::setTexture(1, s_normal, m_normalTexture);
  565. _uniforms.submit();
  566. meshSubmit(m_ground, _pass, _program, mtx);
  567. }
  568. void createFramebuffers()
  569. {
  570. m_size[0] = m_width;
  571. m_size[1] = m_height;
  572. const uint64_t pointSampleFlags = 0
  573. | BGFX_TEXTURE_RT
  574. | BGFX_SAMPLER_U_CLAMP
  575. | BGFX_SAMPLER_V_CLAMP
  576. | BGFX_SAMPLER_MIN_POINT
  577. | BGFX_SAMPLER_MAG_POINT
  578. | BGFX_SAMPLER_MIP_POINT
  579. ;
  580. m_gbufferTex[GBUFFER_RT_COLOR] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, pointSampleFlags);
  581. m_gbufferTex[GBUFFER_RT_NORMAL] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, pointSampleFlags);
  582. m_gbufferTex[GBUFFER_RT_DEPTH] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::D32F, pointSampleFlags);
  583. m_gbuffer = bgfx::createFrameBuffer(BX_COUNTOF(m_gbufferTex), m_gbufferTex, true);
  584. m_linearDepth.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, pointSampleFlags);
  585. m_shadows.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, pointSampleFlags);
  586. }
  587. // all buffers set to destroy their textures
  588. void destroyFramebuffers()
  589. {
  590. bgfx::destroy(m_gbuffer);
  591. m_linearDepth.destroy();
  592. m_shadows.destroy();
  593. }
  594. void updateUniforms()
  595. {
  596. m_uniforms.m_displayShadows = m_displayShadows ? 1.0f : 0.0f;
  597. m_uniforms.m_frameIdx = m_dynamicNoise
  598. ? float(m_currFrame % 8)
  599. : 0.0f;
  600. m_uniforms.m_shadowRadius = m_useScreenSpaceRadius ? m_shadowRadiusPixels : m_shadowRadius;
  601. m_uniforms.m_shadowSteps = float(m_shadowSteps);
  602. m_uniforms.m_useNoiseOffset = m_useNoiseOffset ? 1.0f : 0.0f;
  603. m_uniforms.m_contactShadowsMode = float(m_contactShadowsMode);
  604. m_uniforms.m_useScreenSpaceRadius = m_useScreenSpaceRadius ? 1.0f : 0.0f;
  605. mat4Set(m_uniforms.m_worldToView, m_view);
  606. mat4Set(m_uniforms.m_viewToProj, m_proj);
  607. // from assao sample, cs_assao_prepare_depths.sc
  608. {
  609. // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
  610. // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
  611. // correct the handedness issue. need to make sure this below is correct, but I think it is.
  612. float depthLinearizeMul = -m_proj2[3*4+2];
  613. float depthLinearizeAdd = m_proj2[2*4+2];
  614. if (depthLinearizeMul * depthLinearizeAdd < 0)
  615. {
  616. depthLinearizeAdd = -depthLinearizeAdd;
  617. }
  618. vec2Set(m_uniforms.m_depthUnpackConsts, depthLinearizeMul, depthLinearizeAdd);
  619. float tanHalfFOVY = 1.0f / m_proj2[1*4+1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
  620. float tanHalfFOVX = 1.0F / m_proj2[0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
  621. if (bgfx::getRendererType() == bgfx::RendererType::OpenGL)
  622. {
  623. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * 2.0f);
  624. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * -1.0f);
  625. }
  626. else
  627. {
  628. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f);
  629. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f);
  630. }
  631. }
  632. {
  633. float lightPosition[4];
  634. bx::memCopy(lightPosition, m_lightModel.position, 3*sizeof(float));
  635. lightPosition[3] = 1.0f;
  636. float viewSpaceLightPosition[4];
  637. bx::vec4MulMtx(viewSpaceLightPosition, lightPosition, m_view);
  638. bx::memCopy(m_uniforms.m_lightPosition, viewSpaceLightPosition, 3*sizeof(float));
  639. }
  640. }
  641. uint32_t m_width;
  642. uint32_t m_height;
  643. uint32_t m_debug;
  644. uint32_t m_reset;
  645. entry::MouseState m_mouseState;
  646. // Resource handles
  647. bgfx::ProgramHandle m_gbufferProgram;
  648. bgfx::ProgramHandle m_sphereProgram;
  649. bgfx::ProgramHandle m_linearDepthProgram;
  650. bgfx::ProgramHandle m_shadowsProgram;
  651. bgfx::ProgramHandle m_combineProgram;
  652. // Shader uniforms
  653. Uniforms m_uniforms;
  654. // Uniforms to identify texture samplers
  655. bgfx::UniformHandle s_albedo;
  656. bgfx::UniformHandle s_color;
  657. bgfx::UniformHandle s_normal;
  658. bgfx::UniformHandle s_depth;
  659. bgfx::UniformHandle s_shadows;
  660. bgfx::FrameBufferHandle m_gbuffer;
  661. bgfx::TextureHandle m_gbufferTex[GBUFFER_RENDER_TARGETS];
  662. RenderTarget m_linearDepth;
  663. RenderTarget m_shadows;
  664. struct Model
  665. {
  666. uint32_t mesh; // Index of mesh in m_meshes
  667. float position[3];
  668. };
  669. Model m_lightModel;
  670. Model m_models[MODEL_COUNT];
  671. Mesh* m_meshes[BX_COUNTOF(s_meshPaths)];
  672. Mesh* m_ground;
  673. bgfx::TextureHandle m_groundTexture;
  674. bgfx::TextureHandle m_normalTexture;
  675. uint32_t m_currFrame;
  676. float m_lightRotation = 0.0f;
  677. float m_texelHalf = 0.0f;
  678. float m_fovY = 60.0f;
  679. bool m_recreateFrameBuffers = false;
  680. bool m_havePrevious = false;
  681. float m_view[16];
  682. float m_proj[16];
  683. float m_proj2[16];
  684. int32_t m_size[2];
  685. // UI parameters
  686. bool m_displayShadows = false;
  687. bool m_useNoiseOffset = true;
  688. bool m_dynamicNoise = true;
  689. float m_shadowRadius = 0.25f;
  690. float m_shadowRadiusPixels = 25.0f;
  691. int32_t m_shadowSteps = 8;
  692. bool m_moveLight = true;
  693. int32_t m_contactShadowsMode = 0;
  694. bool m_useScreenSpaceRadius = false;
  695. };
  696. } // namespace
  697. ENTRY_IMPLEMENT_MAIN(
  698. ExampleScreenSpaceShadows
  699. , "44-sss"
  700. , "Screen Space Shadows."
  701. );