shadowmaps_simple.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526
  1. /*
  2. * Copyright 2013-2014 Dario Manesku. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. #include <string>
  6. #include <vector>
  7. #include <algorithm>
  8. #include "common.h"
  9. #include <bgfx/bgfx.h>
  10. #include <bx/timer.h>
  11. #include <bx/readerwriter.h>
  12. #include <bx/math.h>
  13. #include "entry/entry.h"
  14. #include "bgfx_utils.h"
  15. #include "imgui/imgui.h"
  16. namespace
  17. {
  18. #define RENDER_SHADOW_PASS_ID 0
  19. #define RENDER_SCENE_PASS_ID 1
  20. struct PosNormalVertex
  21. {
  22. float m_x;
  23. float m_y;
  24. float m_z;
  25. uint32_t m_normal;
  26. static void init()
  27. {
  28. ms_layout
  29. .begin()
  30. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  31. .add(bgfx::Attrib::Normal, 4, bgfx::AttribType::Uint8, true, true)
  32. .end();
  33. };
  34. static bgfx::VertexLayout ms_layout;
  35. };
  36. bgfx::VertexLayout PosNormalVertex::ms_layout;
  37. static PosNormalVertex s_hplaneVertices[] =
  38. {
  39. { -1.0f, 0.0f, 1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f) },
  40. { 1.0f, 0.0f, 1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f) },
  41. { -1.0f, 0.0f, -1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f) },
  42. { 1.0f, 0.0f, -1.0f, encodeNormalRgba8(0.0f, 1.0f, 0.0f) },
  43. };
  44. static const uint16_t s_planeIndices[] =
  45. {
  46. 0, 1, 2,
  47. 1, 3, 2,
  48. };
  49. class ExampleShadowmapsSimple : public entry::AppI
  50. {
  51. public:
  52. ExampleShadowmapsSimple(const char* _name, const char* _description, const char* _url)
  53. : entry::AppI(_name, _description, _url)
  54. {
  55. }
  56. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  57. {
  58. Args args(_argc, _argv);
  59. m_width = _width;
  60. m_height = _height;
  61. m_debug = BGFX_DEBUG_NONE;
  62. m_reset = BGFX_RESET_VSYNC;
  63. bgfx::Init init;
  64. init.type = args.m_type;
  65. init.vendorId = args.m_pciId;
  66. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  67. init.platformData.ndt = entry::getNativeDisplayHandle();
  68. init.platformData.type = entry::getNativeWindowHandleType();
  69. init.resolution.width = m_width;
  70. init.resolution.height = m_height;
  71. init.resolution.reset = m_reset;
  72. bgfx::init(init);
  73. // Enable debug text.
  74. bgfx::setDebug(m_debug);
  75. // Uniforms.
  76. s_shadowMap = bgfx::createUniform("s_shadowMap", bgfx::UniformType::Sampler);
  77. u_lightPos = bgfx::createUniform("u_lightPos", bgfx::UniformType::Vec4);
  78. u_lightMtx = bgfx::createUniform("u_lightMtx", bgfx::UniformType::Mat4);
  79. // When using GL clip space depth range [-1, 1] and packing depth into color buffer, we need to
  80. // adjust the depth range to be [0, 1] for writing to the color buffer
  81. u_depthScaleOffset = bgfx::createUniform("u_depthScaleOffset", bgfx::UniformType::Vec4);
  82. // Get renderer capabilities info.
  83. const bgfx::Caps* caps = bgfx::getCaps();
  84. float depthScaleOffset[4] = { 1.0f, 0.0f, 0.0f, 0.0f };
  85. if (caps->homogeneousDepth)
  86. {
  87. depthScaleOffset[0] = 0.5f;
  88. depthScaleOffset[1] = 0.5f;
  89. }
  90. bgfx::setUniform(u_depthScaleOffset, depthScaleOffset);
  91. bgfx::touch(0);
  92. // Create vertex stream declaration.
  93. PosNormalVertex::init();
  94. // Meshes.
  95. m_bunny = meshLoad("meshes/bunny.bin");
  96. m_cube = meshLoad("meshes/cube.bin");
  97. m_hollowcube = meshLoad("meshes/hollowcube.bin");
  98. m_vbh = bgfx::createVertexBuffer(
  99. bgfx::makeRef(s_hplaneVertices, sizeof(s_hplaneVertices) )
  100. , PosNormalVertex::ms_layout
  101. );
  102. m_ibh = bgfx::createIndexBuffer(
  103. bgfx::makeRef(s_planeIndices, sizeof(s_planeIndices) )
  104. );
  105. // Render targets.
  106. m_shadowMapSize = 512;
  107. // Shadow samplers are supported at least partially supported if texture
  108. // compare less equal feature is supported.
  109. m_shadowSamplerSupported = 0 != (caps->supported & BGFX_CAPS_TEXTURE_COMPARE_LEQUAL);
  110. m_useShadowSampler = m_shadowSamplerSupported;
  111. m_shadowMapFB = BGFX_INVALID_HANDLE;
  112. m_progShadow = BGFX_INVALID_HANDLE;
  113. m_progMesh = BGFX_INVALID_HANDLE;
  114. m_state[0] = meshStateCreate();
  115. m_state[0]->m_state = 0;
  116. m_state[0]->m_program = m_progShadow;
  117. m_state[0]->m_viewId = RENDER_SHADOW_PASS_ID;
  118. m_state[0]->m_numTextures = 0;
  119. m_state[1] = meshStateCreate();
  120. m_state[1]->m_state = 0
  121. | BGFX_STATE_WRITE_RGB
  122. | BGFX_STATE_WRITE_A
  123. | BGFX_STATE_WRITE_Z
  124. | BGFX_STATE_DEPTH_TEST_LESS
  125. | BGFX_STATE_CULL_CCW
  126. | BGFX_STATE_MSAA
  127. ;
  128. m_state[1]->m_program = m_progMesh;
  129. m_state[1]->m_viewId = RENDER_SCENE_PASS_ID;
  130. m_state[1]->m_numTextures = 1;
  131. m_state[1]->m_textures[0].m_flags = UINT32_MAX;
  132. m_state[1]->m_textures[0].m_stage = 0;
  133. m_state[1]->m_textures[0].m_sampler = s_shadowMap;
  134. m_state[1]->m_textures[0].m_texture = BGFX_INVALID_HANDLE;
  135. // Set view and projection matrices.
  136. const bx::Vec3 at = { 0.0f, 5.0f, 0.0f };
  137. const bx::Vec3 eye = { 0.0f, 30.0f, -60.0f };
  138. bx::mtxLookAt(m_view, eye, at);
  139. const float aspect = float(int32_t(m_width) ) / float(int32_t(m_height) );
  140. bx::mtxProj(m_proj, 60.0f, aspect, 0.1f, 1000.0f, bgfx::getCaps()->homogeneousDepth);
  141. m_timeOffset = bx::getHPCounter();
  142. imguiCreate();
  143. }
  144. virtual int shutdown() override
  145. {
  146. imguiDestroy();
  147. meshUnload(m_bunny);
  148. meshUnload(m_cube);
  149. meshUnload(m_hollowcube);
  150. meshStateDestroy(m_state[0]);
  151. meshStateDestroy(m_state[1]);
  152. bgfx::destroy(m_vbh);
  153. bgfx::destroy(m_ibh);
  154. bgfx::destroy(m_progShadow);
  155. bgfx::destroy(m_progMesh);
  156. bgfx::destroy(m_shadowMapFB);
  157. bgfx::destroy(s_shadowMap);
  158. bgfx::destroy(u_lightPos);
  159. bgfx::destroy(u_lightMtx);
  160. bgfx::destroy(u_depthScaleOffset);
  161. // Shutdown bgfx.
  162. bgfx::shutdown();
  163. return 0;
  164. }
  165. bool update() override
  166. {
  167. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState) )
  168. {
  169. imguiBeginFrame(m_mouseState.m_mx
  170. , m_mouseState.m_my
  171. , (m_mouseState.m_buttons[entry::MouseButton::Left ] ? IMGUI_MBUT_LEFT : 0)
  172. | (m_mouseState.m_buttons[entry::MouseButton::Right ] ? IMGUI_MBUT_RIGHT : 0)
  173. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  174. , m_mouseState.m_mz
  175. , uint16_t(m_width)
  176. , uint16_t(m_height)
  177. );
  178. showExampleDialog(this);
  179. ImGui::SetNextWindowPos(
  180. ImVec2(m_width - m_width / 5.0f - 10.0f, 10.0f)
  181. , ImGuiCond_FirstUseEver
  182. );
  183. ImGui::SetNextWindowSize(
  184. ImVec2(m_width / 5.0f, m_height / 2.0f)
  185. , ImGuiCond_FirstUseEver
  186. );
  187. ImGui::Begin("Settings"
  188. , NULL
  189. , 0
  190. );
  191. bool shadowSamplerModeChanged = false;
  192. if (m_shadowSamplerSupported)
  193. {
  194. shadowSamplerModeChanged = ImGui::Checkbox("Use Shadow Sampler", &m_useShadowSampler);
  195. }
  196. else
  197. {
  198. ImGui::Text("Shadow sampler is not supported");
  199. }
  200. ImGui::End();
  201. imguiEndFrame();
  202. int64_t now = bx::getHPCounter();
  203. const double freq = double(bx::getHPFrequency() );
  204. float time = float( (now-m_timeOffset)/freq);
  205. if (!bgfx::isValid(m_shadowMapFB)
  206. || shadowSamplerModeChanged)
  207. {
  208. bgfx::TextureHandle shadowMapTexture = BGFX_INVALID_HANDLE;
  209. if (bgfx::isValid(m_progShadow) )
  210. {
  211. bgfx::destroy(m_progShadow);
  212. }
  213. if (bgfx::isValid(m_progMesh) )
  214. {
  215. bgfx::destroy(m_progMesh);
  216. }
  217. if (bgfx::isValid(m_shadowMapFB) )
  218. {
  219. bgfx::destroy(m_shadowMapFB);
  220. }
  221. if (m_useShadowSampler)
  222. {
  223. // Depth textures and shadow samplers are supported.
  224. m_progShadow = loadProgram("vs_sms_shadow", "fs_sms_shadow");
  225. m_progMesh = loadProgram("vs_sms_mesh", "fs_sms_mesh");
  226. bgfx::TextureHandle fbtextures[] =
  227. {
  228. bgfx::createTexture2D(
  229. m_shadowMapSize
  230. , m_shadowMapSize
  231. , false
  232. , 1
  233. , bgfx::TextureFormat::D16
  234. , BGFX_TEXTURE_RT | BGFX_SAMPLER_COMPARE_LEQUAL
  235. ),
  236. };
  237. shadowMapTexture = fbtextures[0];
  238. m_shadowMapFB = bgfx::createFrameBuffer(BX_COUNTOF(fbtextures), fbtextures, true);
  239. }
  240. else
  241. {
  242. // Depth textures and shadow samplers are not supported. Use float
  243. // depth packing into color buffer instead.
  244. m_progShadow = loadProgram("vs_sms_shadow_pd", "fs_sms_shadow_pd");
  245. m_progMesh = loadProgram("vs_sms_mesh", "fs_sms_mesh_pd");
  246. bgfx::TextureHandle fbtextures[] =
  247. {
  248. bgfx::createTexture2D(
  249. m_shadowMapSize
  250. , m_shadowMapSize
  251. , false
  252. , 1
  253. , bgfx::TextureFormat::BGRA8
  254. , BGFX_TEXTURE_RT
  255. ),
  256. bgfx::createTexture2D(
  257. m_shadowMapSize
  258. , m_shadowMapSize
  259. , false
  260. , 1
  261. , bgfx::TextureFormat::D16
  262. , BGFX_TEXTURE_RT_WRITE_ONLY
  263. ),
  264. };
  265. shadowMapTexture = fbtextures[0];
  266. m_shadowMapFB = bgfx::createFrameBuffer(BX_COUNTOF(fbtextures), fbtextures, true);
  267. }
  268. m_state[0]->m_program = m_progShadow;
  269. m_state[0]->m_state = 0
  270. | (m_useShadowSampler ? 0 : BGFX_STATE_WRITE_RGB | BGFX_STATE_WRITE_A)
  271. | BGFX_STATE_WRITE_Z
  272. | BGFX_STATE_DEPTH_TEST_LESS
  273. | BGFX_STATE_CULL_CCW
  274. | BGFX_STATE_MSAA
  275. ;
  276. m_state[1]->m_program = m_progMesh;
  277. m_state[1]->m_textures[0].m_texture = shadowMapTexture;
  278. }
  279. // Setup lights.
  280. float lightPos[4];
  281. lightPos[0] = -bx::cos(time);
  282. lightPos[1] = -1.0f;
  283. lightPos[2] = -bx::sin(time);
  284. lightPos[3] = 0.0f;
  285. bgfx::setUniform(u_lightPos, lightPos);
  286. // Setup instance matrices.
  287. float mtxFloor[16];
  288. bx::mtxSRT(mtxFloor
  289. , 30.0f, 30.0f, 30.0f
  290. , 0.0f, 0.0f, 0.0f
  291. , 0.0f, 0.0f, 0.0f
  292. );
  293. float mtxBunny[16];
  294. bx::mtxSRT(mtxBunny
  295. , 5.0f, 5.0f, 5.0f
  296. , 0.0f, bx::kPi - time, 0.0f
  297. , 15.0f, 5.0f, 0.0f
  298. );
  299. float mtxHollowcube[16];
  300. bx::mtxSRT(mtxHollowcube
  301. , 2.5f, 2.5f, 2.5f
  302. , 0.0f, 1.56f - time, 0.0f
  303. , 0.0f, 10.0f, 0.0f
  304. );
  305. float mtxCube[16];
  306. bx::mtxSRT(mtxCube
  307. , 2.5f, 2.5f, 2.5f
  308. , 0.0f, 1.56f - time, 0.0f
  309. , -15.0f, 5.0f, 0.0f
  310. );
  311. // Define matrices.
  312. float lightView[16];
  313. float lightProj[16];
  314. const bx::Vec3 at = { 0.0f, 0.0f, 0.0f };
  315. const bx::Vec3 eye = { -lightPos[0], -lightPos[1], -lightPos[2] };
  316. bx::mtxLookAt(lightView, eye, at);
  317. const bgfx::Caps* caps = bgfx::getCaps();
  318. const float area = 30.0f;
  319. bx::mtxOrtho(lightProj, -area, area, -area, area, -100.0f, 100.0f, 0.0f, caps->homogeneousDepth);
  320. bgfx::setViewRect(RENDER_SHADOW_PASS_ID, 0, 0, m_shadowMapSize, m_shadowMapSize);
  321. bgfx::setViewFrameBuffer(RENDER_SHADOW_PASS_ID, m_shadowMapFB);
  322. bgfx::setViewTransform(RENDER_SHADOW_PASS_ID, lightView, lightProj);
  323. bgfx::setViewRect(RENDER_SCENE_PASS_ID, 0, 0, uint16_t(m_width), uint16_t(m_height) );
  324. bgfx::setViewTransform(RENDER_SCENE_PASS_ID, m_view, m_proj);
  325. // Clear backbuffer and shadowmap framebuffer at beginning.
  326. bgfx::setViewClear(RENDER_SHADOW_PASS_ID
  327. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  328. , 0x303030ff, 1.0f, 0
  329. );
  330. bgfx::setViewClear(RENDER_SCENE_PASS_ID
  331. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  332. , 0x303030ff, 1.0f, 0
  333. );
  334. // Render.
  335. float mtxShadow[16];
  336. float lightMtx[16];
  337. const float sy = caps->originBottomLeft ? 0.5f : -0.5f;
  338. const float sz = caps->homogeneousDepth ? 0.5f : 1.0f;
  339. const float tz = caps->homogeneousDepth ? 0.5f : 0.0f;
  340. const float mtxCrop[16] =
  341. {
  342. 0.5f, 0.0f, 0.0f, 0.0f,
  343. 0.0f, sy, 0.0f, 0.0f,
  344. 0.0f, 0.0f, sz, 0.0f,
  345. 0.5f, 0.5f, tz, 1.0f,
  346. };
  347. float mtxTmp[16];
  348. bx::mtxMul(mtxTmp, lightProj, mtxCrop);
  349. bx::mtxMul(mtxShadow, lightView, mtxTmp);
  350. // Floor.
  351. bx::mtxMul(lightMtx, mtxFloor, mtxShadow);
  352. uint32_t cached = bgfx::setTransform(mtxFloor);
  353. for (uint32_t pass = 0; pass < 2; ++pass)
  354. {
  355. const MeshState& st = *m_state[pass];
  356. bgfx::setTransform(cached);
  357. for (uint8_t tex = 0; tex < st.m_numTextures; ++tex)
  358. {
  359. const MeshState::Texture& texture = st.m_textures[tex];
  360. bgfx::setTexture(texture.m_stage
  361. , texture.m_sampler
  362. , texture.m_texture
  363. , texture.m_flags
  364. );
  365. }
  366. bgfx::setUniform(u_lightMtx, lightMtx);
  367. bgfx::setIndexBuffer(m_ibh);
  368. bgfx::setVertexBuffer(0, m_vbh);
  369. bgfx::setState(st.m_state);
  370. bgfx::submit(st.m_viewId, st.m_program);
  371. }
  372. // Bunny.
  373. bx::mtxMul(lightMtx, mtxBunny, mtxShadow);
  374. bgfx::setUniform(u_lightMtx, lightMtx);
  375. meshSubmit(m_bunny, &m_state[0], 1, mtxBunny);
  376. bgfx::setUniform(u_lightMtx, lightMtx);
  377. meshSubmit(m_bunny, &m_state[1], 1, mtxBunny);
  378. // Hollow cube.
  379. bx::mtxMul(lightMtx, mtxHollowcube, mtxShadow);
  380. bgfx::setUniform(u_lightMtx, lightMtx);
  381. meshSubmit(m_hollowcube, &m_state[0], 1, mtxHollowcube);
  382. bgfx::setUniform(u_lightMtx, lightMtx);
  383. meshSubmit(m_hollowcube, &m_state[1], 1, mtxHollowcube);
  384. // Cube.
  385. bx::mtxMul(lightMtx, mtxCube, mtxShadow);
  386. bgfx::setUniform(u_lightMtx, lightMtx);
  387. meshSubmit(m_cube, &m_state[0], 1, mtxCube);
  388. bgfx::setUniform(u_lightMtx, lightMtx);
  389. meshSubmit(m_cube, &m_state[1], 1, mtxCube);
  390. // Advance to next frame. Rendering thread will be kicked to
  391. // process submitted rendering primitives.
  392. bgfx::frame();
  393. return true;
  394. }
  395. return false;
  396. }
  397. entry::MouseState m_mouseState;
  398. uint32_t m_width;
  399. uint32_t m_height;
  400. uint32_t m_debug;
  401. uint32_t m_reset;
  402. bgfx::UniformHandle s_shadowMap;
  403. bgfx::UniformHandle u_lightPos;
  404. bgfx::UniformHandle u_lightMtx;
  405. bgfx::UniformHandle u_depthScaleOffset;
  406. Mesh* m_bunny;
  407. Mesh* m_cube;
  408. Mesh* m_hollowcube;
  409. bgfx::VertexBufferHandle m_vbh;
  410. bgfx::IndexBufferHandle m_ibh;
  411. uint16_t m_shadowMapSize;
  412. bgfx::ProgramHandle m_progShadow;
  413. bgfx::ProgramHandle m_progMesh;
  414. bgfx::FrameBufferHandle m_shadowMapFB;
  415. bool m_shadowSamplerSupported;
  416. bool m_useShadowSampler;
  417. MeshState* m_state[2];
  418. float m_view[16];
  419. float m_proj[16];
  420. int64_t m_timeOffset;
  421. };
  422. } // namespace
  423. ENTRY_IMPLEMENT_MAIN(
  424. ExampleShadowmapsSimple
  425. , "15-shadowmaps-simple"
  426. , "Shadow maps example"
  427. , "https://bkaradzic.github.io/bgfx/examples.html#shadowmaps-simple"
  428. );