bokeh.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976
  1. /*
  2. * Copyright 2021 elven cache. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. /*
  6. * Implement bokeh depth of field as described in the blog post here:
  7. * https://web.archive.org/web/20201215123940/https://blog.tuxedolabs.com/2018/05/04/bokeh-depth-of-field-in-single-pass.html
  8. *
  9. * Additionally, implement the optimizations discussed in the closing paragraph.
  10. * Apply the effect in multiple passes. Calculate the circle of confusion and store
  11. * in the alpha channel while downsampling the image. Then compute depth of field
  12. * at this lower res, storing sample size in alpha. Then composite the blurred image,
  13. * based on the sample size. Compositing the lower res like this can lead to blocky
  14. * edges where there's a depth discontinuity and the blur is just enough. May be
  15. * an area to improve on.
  16. *
  17. * Provide an alternate means of determining radius of current sample when blurring.
  18. * I find the blog post's sample pattern to be difficult to directly reason about. It
  19. * is not obvious, given the parameters, how many samples will be taken. And it can
  20. * be very many samples. Though the results are good. The 'sqrt' pattern chosen here
  21. * looks alright and allows for the number of samples to be set directly. If you are
  22. * going to use this in a project, may be worth exploring additional sample patterns.
  23. * And certainly update the shader to remove the pattern choice from inside the
  24. * sample loop.
  25. */
  26. #include <common.h>
  27. #include <camera.h>
  28. #include <bgfx_utils.h>
  29. #include <imgui/imgui.h>
  30. #include <bx/rng.h>
  31. #include <bx/os.h>
  32. namespace {
  33. #define FRAMEBUFFER_RT_COLOR 0
  34. #define FRAMEBUFFER_RT_DEPTH 1
  35. #define FRAMEBUFFER_RENDER_TARGETS 2
  36. enum Meshes
  37. {
  38. MeshCube = 0,
  39. MeshTree,
  40. MeshHollowCube,
  41. MeshBunny
  42. };
  43. static const char * s_meshPaths[] =
  44. {
  45. "meshes/cube.bin",
  46. "meshes/tree.bin",
  47. "meshes/hollowcube.bin",
  48. "meshes/bunny.bin"
  49. };
  50. static const float s_meshScale[] =
  51. {
  52. 0.45f,
  53. 0.25f,
  54. 0.30f,
  55. 0.25f
  56. };
  57. // Vertex decl for our screen space quad (used in deferred rendering)
  58. struct PosTexCoord0Vertex
  59. {
  60. float m_x;
  61. float m_y;
  62. float m_z;
  63. float m_u;
  64. float m_v;
  65. static void init()
  66. {
  67. ms_layout
  68. .begin()
  69. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  70. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  71. .end();
  72. }
  73. static bgfx::VertexLayout ms_layout;
  74. };
  75. bgfx::VertexLayout PosTexCoord0Vertex::ms_layout;
  76. struct PassUniforms
  77. {
  78. enum { NumVec4 = 4 };
  79. void init() {
  80. u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, NumVec4);
  81. };
  82. void submit() const {
  83. bgfx::setUniform(u_params, m_params, NumVec4);
  84. }
  85. void destroy() {
  86. bgfx::destroy(u_params);
  87. }
  88. union
  89. {
  90. struct
  91. {
  92. /* 0 */ struct { float m_depthUnpackConsts[2]; float m_frameIdx; float m_unused0; };
  93. /* 1 */ struct { float m_ndcToViewMul[2]; float m_ndcToViewAdd[2]; };
  94. /* 2 */ struct { float m_blurSteps; float m_samplePattern; float m_unused3[2]; };
  95. /* 3 */ struct { float m_maxBlurSize; float m_focusPoint; float m_focusScale; float m_radiusScale; };
  96. };
  97. float m_params[NumVec4 * 4];
  98. };
  99. bgfx::UniformHandle u_params;
  100. };
  101. struct ModelUniforms
  102. {
  103. enum { NumVec4 = 2 };
  104. void init() {
  105. u_params = bgfx::createUniform("u_modelParams", bgfx::UniformType::Vec4, NumVec4);
  106. };
  107. void submit() const {
  108. bgfx::setUniform(u_params, m_params, NumVec4);
  109. };
  110. void destroy() {
  111. bgfx::destroy(u_params);
  112. }
  113. union
  114. {
  115. struct
  116. {
  117. /* 0 */ struct { float m_color[3]; float m_unused0; };
  118. /* 1 */ struct { float m_lightPosition[3]; float m_unused1; };
  119. };
  120. float m_params[NumVec4 * 4];
  121. };
  122. bgfx::UniformHandle u_params;
  123. };
  124. struct RenderTarget
  125. {
  126. void init(uint32_t _width, uint32_t _height, bgfx::TextureFormat::Enum _format, uint64_t _flags)
  127. {
  128. m_texture = bgfx::createTexture2D(uint16_t(_width), uint16_t(_height), false, 1, _format, _flags);
  129. const bool destroyTextures = true;
  130. m_buffer = bgfx::createFrameBuffer(1, &m_texture, destroyTextures);
  131. }
  132. void destroy()
  133. {
  134. // also responsible for destroying texture
  135. bgfx::destroy(m_buffer);
  136. }
  137. bgfx::TextureHandle m_texture;
  138. bgfx::FrameBufferHandle m_buffer;
  139. };
  140. void screenSpaceQuad(float _textureWidth, float _textureHeight, float _texelHalf, bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
  141. {
  142. if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_layout))
  143. {
  144. bgfx::TransientVertexBuffer vb;
  145. bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_layout);
  146. PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
  147. const float minx = -_width;
  148. const float maxx = _width;
  149. const float miny = 0.0f;
  150. const float maxy = _height * 2.0f;
  151. const float texelHalfW = _texelHalf / _textureWidth;
  152. const float texelHalfH = _texelHalf / _textureHeight;
  153. const float minu = -1.0f + texelHalfW;
  154. const float maxu = 1.0f + texelHalfW;
  155. const float zz = 0.0f;
  156. float minv = texelHalfH;
  157. float maxv = 2.0f + texelHalfH;
  158. if (_originBottomLeft)
  159. {
  160. float temp = minv;
  161. minv = maxv;
  162. maxv = temp;
  163. minv -= 1.0f;
  164. maxv -= 1.0f;
  165. }
  166. vertex[0].m_x = minx;
  167. vertex[0].m_y = miny;
  168. vertex[0].m_z = zz;
  169. vertex[0].m_u = minu;
  170. vertex[0].m_v = minv;
  171. vertex[1].m_x = maxx;
  172. vertex[1].m_y = miny;
  173. vertex[1].m_z = zz;
  174. vertex[1].m_u = maxu;
  175. vertex[1].m_v = minv;
  176. vertex[2].m_x = maxx;
  177. vertex[2].m_y = maxy;
  178. vertex[2].m_z = zz;
  179. vertex[2].m_u = maxu;
  180. vertex[2].m_v = maxv;
  181. bgfx::setVertexBuffer(0, &vb);
  182. }
  183. }
  184. void vec2Set(float* _v, float _x, float _y)
  185. {
  186. _v[0] = _x;
  187. _v[1] = _y;
  188. }
  189. void vec4Set(float* _v, float _x, float _y, float _z, float _w)
  190. {
  191. _v[0] = _x;
  192. _v[1] = _y;
  193. _v[2] = _z;
  194. _v[3] = _w;
  195. }
  196. class ExampleBokeh : public entry::AppI
  197. {
  198. public:
  199. ExampleBokeh(const char* _name, const char* _description)
  200. : entry::AppI(_name, _description)
  201. , m_currFrame(UINT32_MAX)
  202. , m_texelHalf(0.0f)
  203. {
  204. }
  205. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  206. {
  207. Args args(_argc, _argv);
  208. m_width = _width;
  209. m_height = _height;
  210. m_debug = BGFX_DEBUG_NONE;
  211. m_reset = BGFX_RESET_VSYNC;
  212. bgfx::Init init;
  213. init.type = args.m_type;
  214. init.vendorId = args.m_pciId;
  215. init.resolution.width = m_width;
  216. init.resolution.height = m_height;
  217. init.resolution.reset = m_reset;
  218. bgfx::init(init);
  219. // Enable debug text.
  220. bgfx::setDebug(m_debug);
  221. // Create uniforms for screen passes and models
  222. m_uniforms.init();
  223. m_modelUniforms.init();
  224. // Create texture sampler uniforms (used when we bind textures)
  225. s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler);
  226. s_color = bgfx::createUniform("s_color", bgfx::UniformType::Sampler);
  227. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Sampler);
  228. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler);
  229. s_blurredColor = bgfx::createUniform("s_blurredColor", bgfx::UniformType::Sampler);
  230. // Create program from shaders.
  231. m_forwardProgram = loadProgram("vs_bokeh_forward", "fs_bokeh_forward");
  232. m_gridProgram = loadProgram("vs_bokeh_forward", "fs_bokeh_forward_grid");
  233. m_copyProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_copy");
  234. m_linearDepthProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_linear_depth");
  235. m_dofSinglePassProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_single_pass");
  236. m_dofDownsampleProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_downsample");
  237. m_dofQuarterProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_second_pass");
  238. m_dofCombineProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_combine");
  239. m_dofDebugProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_debug");
  240. // Load some meshes
  241. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  242. {
  243. m_meshes[ii] = meshLoad(s_meshPaths[ii]);
  244. }
  245. m_groundTexture = loadTexture("textures/fieldstone-rgba.dds");
  246. m_normalTexture = loadTexture("textures/fieldstone-n.dds");
  247. m_recreateFrameBuffers = false;
  248. createFramebuffers();
  249. // Vertex decl
  250. PosTexCoord0Vertex::init();
  251. // Init camera
  252. cameraCreate();
  253. cameraSetPosition({ 0.0f, 2.5f, -20.0f });
  254. cameraSetVerticalAngle(-0.3f);
  255. m_fovY = 60.0f;
  256. // Init "prev" matrices, will be same for first frame
  257. cameraGetViewMtx(m_view);
  258. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  259. // Get renderer capabilities info.
  260. const bgfx::RendererType::Enum renderer = bgfx::getRendererType();
  261. m_texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f;
  262. imguiCreate();
  263. }
  264. int32_t shutdown() override
  265. {
  266. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  267. {
  268. meshUnload(m_meshes[ii]);
  269. }
  270. bgfx::destroy(m_normalTexture);
  271. bgfx::destroy(m_groundTexture);
  272. bgfx::destroy(m_forwardProgram);
  273. bgfx::destroy(m_gridProgram);
  274. bgfx::destroy(m_copyProgram);
  275. bgfx::destroy(m_linearDepthProgram);
  276. bgfx::destroy(m_dofSinglePassProgram);
  277. bgfx::destroy(m_dofDownsampleProgram);
  278. bgfx::destroy(m_dofQuarterProgram);
  279. bgfx::destroy(m_dofCombineProgram);
  280. bgfx::destroy(m_dofDebugProgram);
  281. m_uniforms.destroy();
  282. m_modelUniforms.destroy();
  283. bgfx::destroy(s_albedo);
  284. bgfx::destroy(s_color);
  285. bgfx::destroy(s_normal);
  286. bgfx::destroy(s_depth);
  287. bgfx::destroy(s_blurredColor);
  288. destroyFramebuffers();
  289. cameraDestroy();
  290. imguiDestroy();
  291. bgfx::shutdown();
  292. return 0;
  293. }
  294. bool update() override
  295. {
  296. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  297. {
  298. // skip processing when minimized, otherwise crashing
  299. if (0 == m_width || 0 == m_height)
  300. {
  301. return true;
  302. }
  303. // Update frame timer
  304. int64_t now = bx::getHPCounter();
  305. static int64_t last = now;
  306. const int64_t frameTime = now - last;
  307. last = now;
  308. const double freq = double(bx::getHPFrequency());
  309. const float deltaTime = float(frameTime / freq);
  310. const bgfx::Caps* caps = bgfx::getCaps();
  311. if (m_size[0] != (int32_t)m_width
  312. || m_size[1] != (int32_t)m_height
  313. || m_recreateFrameBuffers)
  314. {
  315. destroyFramebuffers();
  316. createFramebuffers();
  317. m_recreateFrameBuffers = false;
  318. }
  319. // update animation time
  320. const float rotationSpeed = 0.75f;
  321. m_animationTime += deltaTime * rotationSpeed;
  322. if (bx::kPi2 < m_animationTime)
  323. {
  324. m_animationTime -= bx::kPi2;
  325. }
  326. // Update camera
  327. cameraUpdate(deltaTime*0.15f, m_mouseState);
  328. cameraGetViewMtx(m_view);
  329. updateUniforms();
  330. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, caps->homogeneousDepth);
  331. bx::mtxProj(m_proj2, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, false);
  332. bgfx::ViewId view = 0;
  333. // Draw models into scene
  334. {
  335. bgfx::setViewName(view, "forward scene");
  336. bgfx::setViewClear(view
  337. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  338. , 0xbbddffff // clear to a sky blue
  339. , 1.0f
  340. , 0
  341. );
  342. bgfx::setViewRect(view, 0, 0, uint16_t(m_size[0]), uint16_t(m_size[1]));
  343. bgfx::setViewTransform(view, m_view, m_proj);
  344. bgfx::setViewFrameBuffer(view, m_frameBuffer);
  345. bgfx::setState(0
  346. | BGFX_STATE_WRITE_RGB
  347. | BGFX_STATE_WRITE_A
  348. | BGFX_STATE_WRITE_Z
  349. | BGFX_STATE_DEPTH_TEST_LESS
  350. );
  351. drawAllModels(view, m_forwardProgram, m_modelUniforms);
  352. ++view;
  353. }
  354. float orthoProj[16];
  355. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  356. {
  357. // clear out transform stack
  358. float identity[16];
  359. bx::mtxIdentity(identity);
  360. bgfx::setTransform(identity);
  361. }
  362. // Convert depth to linear depth for shadow depth compare
  363. {
  364. bgfx::setViewName(view, "linear depth");
  365. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  366. bgfx::setViewTransform(view, NULL, orthoProj);
  367. bgfx::setViewFrameBuffer(view, m_linearDepth.m_buffer);
  368. bgfx::setState(0
  369. | BGFX_STATE_WRITE_RGB
  370. | BGFX_STATE_WRITE_A
  371. | BGFX_STATE_DEPTH_TEST_ALWAYS
  372. );
  373. bgfx::setTexture(0, s_depth, m_frameBufferTex[FRAMEBUFFER_RT_DEPTH]);
  374. m_uniforms.submit();
  375. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  376. bgfx::submit(view, m_linearDepthProgram);
  377. ++view;
  378. }
  379. // optionally, apply dof
  380. const bool useOrDebugDof = m_useBokehDof || m_showDebugVisualization;
  381. if (useOrDebugDof)
  382. {
  383. view = drawDepthOfField(view, m_frameBufferTex[FRAMEBUFFER_RT_COLOR], orthoProj, caps->originBottomLeft);
  384. }
  385. else
  386. {
  387. bgfx::setViewName(view, "display");
  388. bgfx::setViewClear(view
  389. , BGFX_CLEAR_NONE
  390. , 0
  391. , 1.0f
  392. , 0
  393. );
  394. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  395. bgfx::setViewTransform(view, NULL, orthoProj);
  396. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  397. bgfx::setState(0
  398. | BGFX_STATE_WRITE_RGB
  399. | BGFX_STATE_WRITE_A
  400. );
  401. bgfx::setTexture(0, s_color, m_frameBufferTex[FRAMEBUFFER_RT_COLOR]);
  402. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  403. bgfx::submit(view, m_copyProgram);
  404. ++view;
  405. }
  406. // Draw UI
  407. imguiBeginFrame(m_mouseState.m_mx
  408. , m_mouseState.m_my
  409. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  410. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  411. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  412. , m_mouseState.m_mz
  413. , uint16_t(m_width)
  414. , uint16_t(m_height)
  415. );
  416. showExampleDialog(this);
  417. ImGui::SetNextWindowPos(
  418. ImVec2(m_width - m_width / 4.0f - 10.0f, 10.0f)
  419. , ImGuiCond_FirstUseEver
  420. );
  421. ImGui::SetNextWindowSize(
  422. ImVec2(m_width / 4.0f, m_height / 1.6f)
  423. , ImGuiCond_FirstUseEver
  424. );
  425. ImGui::Begin("Settings"
  426. , NULL
  427. , 0
  428. );
  429. ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
  430. {
  431. ImGui::Checkbox("use bokeh dof", &m_useBokehDof);
  432. if (ImGui::IsItemHovered())
  433. ImGui::SetTooltip("turn effect on and off");
  434. ImGui::Checkbox("use single pass at full res", &m_useSinglePassBokehDof);
  435. if (ImGui::IsItemHovered())
  436. {
  437. ImGui::BeginTooltip();
  438. ImGui::Text("calculate in a single pass at full resolution or use");
  439. ImGui::Text("multiple passes to compute at lower res and composite");
  440. ImGui::EndTooltip();
  441. }
  442. ImGui::Checkbox("show debug vis", &m_showDebugVisualization);
  443. if (ImGui::IsItemHovered())
  444. {
  445. ImGui::BeginTooltip();
  446. ImGui::Text("apply coloration to screen. fades from grey to orange with");
  447. ImGui::Text("increasing foreground blur. from grey to blue in background");
  448. ImGui::EndTooltip();
  449. }
  450. ImGui::Separator();
  451. ImGui::Text("blur controls:");
  452. ImGui::SliderFloat("max blur size", &m_maxBlurSize, 10.0f, 50.0f);
  453. if (ImGui::IsItemHovered())
  454. ImGui::SetTooltip("maximum blur size in screen pixels");
  455. ImGui::SliderFloat("focusPoint", &m_focusPoint, 1.0f, 20.0f);
  456. if (ImGui::IsItemHovered())
  457. ImGui::SetTooltip("distance to focus plane");
  458. ImGui::SliderFloat("focusScale", &m_focusScale, 0.0f, 10.0f);
  459. if (ImGui::IsItemHovered())
  460. ImGui::SetTooltip("multiply focus calculation, larger=tighter focus");
  461. ImGui::Separator();
  462. ImGui::Text("sample pattern controls:");
  463. ImGui::Combo("pattern", &m_samplePattern, "original\0sqrt\0\0");
  464. if (ImGui::IsItemHovered())
  465. {
  466. ImGui::BeginTooltip();
  467. ImGui::Text("original");
  468. ImGui::BulletText("pattern descibed by blogpost");
  469. ImGui::Text("sqrt");
  470. ImGui::BulletText("use sqrt instead of linear steps");
  471. ImGui::EndTooltip();
  472. }
  473. if (0 == m_samplePattern)
  474. {
  475. ImGui::SliderFloat("radiusScale", &m_radiusScale, 0.5f, 4.0f);
  476. if (ImGui::IsItemHovered())
  477. ImGui::SetTooltip("controls number of samples taken");
  478. ImGui::TextWrapped(
  479. "in original blog post, sample code has radius increasing by (radiusScale/currentRadius). "
  480. "which should result in smaller steps farther from center. and fewer steps as radiusScale "
  481. "increases. but it's less clear exactly how many steps that is, can be many."
  482. );
  483. const float maxRadius = m_maxBlurSize;
  484. float radius = m_radiusScale;
  485. int counter = 0;
  486. while (radius < maxRadius)
  487. {
  488. ++counter;
  489. radius += m_radiusScale / radius;
  490. }
  491. char buffer[128] = {0};
  492. bx::snprintf(buffer, 128-1, "number of samples taken: %d", counter);
  493. ImGui::Text(buffer);
  494. if (ImGui::IsItemHovered())
  495. ImGui::SetTooltip("number of sample taps as determined by radiusScale");
  496. }
  497. else // 1 == samplePattern
  498. {
  499. ImGui::TextWrapped(
  500. "when using sqrt pattern, take a fixed number of steps. sqrt refers to how the radius "
  501. "is derived. in both cases, the sample pattern is a spiral out from the center."
  502. );
  503. ImGui::SliderFloat("blur steps", &m_blurSteps, 10.f, 100.0f);
  504. }
  505. }
  506. ImGui::End();
  507. imguiEndFrame();
  508. // Advance to next frame. Rendering thread will be kicked to
  509. // process submitted rendering primitives.
  510. m_currFrame = bgfx::frame();
  511. return true;
  512. }
  513. return false;
  514. }
  515. void drawAllModels(bgfx::ViewId _pass, bgfx::ProgramHandle _program, ModelUniforms & _uniforms)
  516. {
  517. const int32_t width = 6;
  518. const int32_t length = 20;
  519. float c0[] = { 72.0f/255.0f, 126.0f/255.0f, 149.0f/255.0f }; // blue
  520. float c1[] = { 235.0f/255.0f, 146.0f/255.0f, 251.0f/255.0f }; // purple
  521. float c2[] = { 199.0f/255.0f, 0.0f/255.0f, 57.0f/255.0f }; // pink
  522. for (int32_t zz = 0; zz < length; ++zz)
  523. {
  524. // make a color gradient, nothing special about this for example
  525. float * ca = c0;
  526. float * cb = c1;
  527. float lerpVal = float(zz) / float(length);
  528. if (0.5f <= lerpVal)
  529. {
  530. ca = c1;
  531. cb = c2;
  532. }
  533. lerpVal = bx::fract(2.0f*lerpVal);
  534. float r = bx::lerp(ca[0], cb[0], lerpVal);
  535. float g = bx::lerp(ca[1], cb[1], lerpVal);
  536. float b = bx::lerp(ca[2], cb[2], lerpVal);
  537. for (int32_t xx = 0; xx < width; ++xx)
  538. {
  539. const float angle = m_animationTime + float(zz)*(bx::kPi2/length) + float(xx)*(bx::kPiHalf/width);
  540. const float posX = 2.0f * xx - width + 1.0f;
  541. const float posY = bx::sin(angle);
  542. const float posZ = 2.0f * zz - length + 1.0f;
  543. const float scale = s_meshScale[MeshHollowCube];
  544. float mtx[16];
  545. bx::mtxSRT(mtx
  546. , scale
  547. , scale
  548. , scale
  549. , 0.0f
  550. , 0.0f
  551. , 0.0f
  552. , posX
  553. , posY
  554. , posZ
  555. );
  556. bgfx::setTexture(0, s_albedo, m_groundTexture);
  557. bgfx::setTexture(1, s_normal, m_normalTexture);
  558. _uniforms.m_color[0] = r;
  559. _uniforms.m_color[1] = g;
  560. _uniforms.m_color[2] = b;
  561. _uniforms.submit();
  562. meshSubmit(m_meshes[MeshHollowCube], _pass, _program, mtx);
  563. }
  564. }
  565. // draw box as ground plane
  566. {
  567. const float posY = -2.0f;
  568. const float scale = length;
  569. float mtx[16];
  570. bx::mtxSRT(mtx
  571. , scale
  572. , scale
  573. , scale
  574. , 0.0f
  575. , 0.0f
  576. , 0.0f
  577. , 0.0f
  578. , -scale + posY
  579. , 0.0f
  580. );
  581. _uniforms.m_color[0] = 0.5f;
  582. _uniforms.m_color[1] = 0.5f;
  583. _uniforms.m_color[2] = 0.5f;
  584. _uniforms.submit();
  585. meshSubmit(m_meshes[MeshCube], _pass, m_gridProgram, mtx);
  586. }
  587. }
  588. bgfx::ViewId drawDepthOfField(bgfx::ViewId _pass, bgfx::TextureHandle _colorTexture, float* _orthoProj, bool _originBottomLeft)
  589. {
  590. bgfx::ViewId view = _pass;
  591. bgfx::TextureHandle lastTex = _colorTexture;
  592. if (m_showDebugVisualization)
  593. {
  594. bgfx::setViewName(view, "bokeh dof debug pass");
  595. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  596. bgfx::setViewTransform(view, NULL, _orthoProj);
  597. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  598. bgfx::setState(0
  599. | BGFX_STATE_WRITE_RGB
  600. | BGFX_STATE_WRITE_A
  601. | BGFX_STATE_DEPTH_TEST_ALWAYS
  602. );
  603. bgfx::setTexture(0, s_color, lastTex);
  604. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  605. m_uniforms.submit();
  606. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  607. bgfx::submit(view, m_dofDebugProgram);
  608. ++view;
  609. }
  610. else if (m_useSinglePassBokehDof)
  611. {
  612. bgfx::setViewName(view, "bokeh dof single pass");
  613. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  614. bgfx::setViewTransform(view, NULL, _orthoProj);
  615. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  616. bgfx::setState(0
  617. | BGFX_STATE_WRITE_RGB
  618. | BGFX_STATE_WRITE_A
  619. | BGFX_STATE_DEPTH_TEST_ALWAYS
  620. );
  621. bgfx::setTexture(0, s_color, lastTex);
  622. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  623. m_uniforms.submit();
  624. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  625. bgfx::submit(view, m_dofSinglePassProgram);
  626. ++view;
  627. }
  628. else
  629. {
  630. unsigned halfWidth = (m_width/2);
  631. unsigned halfHeight = (m_height/2);
  632. bgfx::setViewName(view, "bokeh dof downsample");
  633. bgfx::setViewRect(view, 0, 0, uint16_t(halfWidth), uint16_t(halfHeight));
  634. bgfx::setViewTransform(view, NULL, _orthoProj);
  635. bgfx::setViewFrameBuffer(view, m_dofQuarterInput.m_buffer);
  636. bgfx::setState(0
  637. | BGFX_STATE_WRITE_RGB
  638. | BGFX_STATE_WRITE_A
  639. | BGFX_STATE_DEPTH_TEST_ALWAYS
  640. );
  641. bgfx::setTexture(0, s_color, lastTex);
  642. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  643. m_uniforms.submit();
  644. screenSpaceQuad(float(halfWidth), float(halfHeight), m_texelHalf, _originBottomLeft);
  645. bgfx::submit(view, m_dofDownsampleProgram);
  646. ++view;
  647. lastTex = m_dofQuarterInput.m_texture;
  648. /*
  649. replace the copy with bokeh dof combine
  650. able to read circle of confusion and color from downsample pass
  651. along with full res color and depth?
  652. do we need half res depth? i'm confused about that...
  653. */
  654. bgfx::setViewName(view, "bokeh dof quarter");
  655. bgfx::setViewRect(view, 0, 0, uint16_t(halfWidth), uint16_t(halfHeight));
  656. bgfx::setViewTransform(view, NULL, _orthoProj);
  657. bgfx::setViewFrameBuffer(view, m_dofQuarterOutput.m_buffer);
  658. bgfx::setState(0
  659. | BGFX_STATE_WRITE_RGB
  660. | BGFX_STATE_WRITE_A
  661. | BGFX_STATE_DEPTH_TEST_ALWAYS
  662. );
  663. bgfx::setTexture(0, s_color, lastTex);
  664. m_uniforms.submit();
  665. screenSpaceQuad(float(halfWidth), float(halfHeight), m_texelHalf, _originBottomLeft);
  666. bgfx::submit(view, m_dofQuarterProgram);
  667. ++view;
  668. lastTex = m_dofQuarterOutput.m_texture;
  669. bgfx::setViewName(view, "bokeh dof combine");
  670. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  671. bgfx::setViewTransform(view, NULL, _orthoProj);
  672. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  673. bgfx::setState(0
  674. | BGFX_STATE_WRITE_RGB
  675. | BGFX_STATE_WRITE_A
  676. | BGFX_STATE_DEPTH_TEST_ALWAYS
  677. );
  678. bgfx::setTexture(0, s_color, _colorTexture);
  679. bgfx::setTexture(1, s_blurredColor, lastTex);
  680. m_uniforms.submit();
  681. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  682. bgfx::submit(view, m_dofCombineProgram);
  683. ++view;
  684. }
  685. return view;
  686. }
  687. void createFramebuffers()
  688. {
  689. m_size[0] = m_width;
  690. m_size[1] = m_height;
  691. const uint64_t bilinearFlags = 0
  692. | BGFX_TEXTURE_RT
  693. | BGFX_SAMPLER_U_CLAMP
  694. | BGFX_SAMPLER_V_CLAMP
  695. ;
  696. m_frameBufferTex[FRAMEBUFFER_RT_COLOR] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, bilinearFlags);
  697. m_frameBufferTex[FRAMEBUFFER_RT_DEPTH] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::D24, bilinearFlags);
  698. m_frameBuffer = bgfx::createFrameBuffer(BX_COUNTOF(m_frameBufferTex), m_frameBufferTex, true);
  699. m_linearDepth.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, bilinearFlags);
  700. unsigned halfWidth = m_size[0]/2;
  701. unsigned halfHeight = m_size[1]/2;
  702. m_dofQuarterInput.init(halfWidth, halfHeight, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  703. m_dofQuarterOutput.init(halfWidth, halfHeight, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  704. }
  705. // all buffers set to destroy their textures
  706. void destroyFramebuffers()
  707. {
  708. bgfx::destroy(m_frameBuffer);
  709. m_linearDepth.destroy();
  710. m_dofQuarterInput.destroy();
  711. m_dofQuarterOutput.destroy();
  712. }
  713. void updateUniforms()
  714. {
  715. // from assao sample, cs_assao_prepare_depths.sc
  716. {
  717. // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
  718. // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
  719. // correct the handedness issue. need to make sure this below is correct, but I think it is.
  720. float depthLinearizeMul = -m_proj2[3*4+2];
  721. float depthLinearizeAdd = m_proj2[2*4+2];
  722. if (depthLinearizeMul * depthLinearizeAdd < 0)
  723. {
  724. depthLinearizeAdd = -depthLinearizeAdd;
  725. }
  726. vec2Set(m_uniforms.m_depthUnpackConsts, depthLinearizeMul, depthLinearizeAdd);
  727. float tanHalfFOVY = 1.0f / m_proj2[1*4+1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
  728. float tanHalfFOVX = 1.0F / m_proj2[0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
  729. if (bgfx::getRendererType() == bgfx::RendererType::OpenGL)
  730. {
  731. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * 2.0f);
  732. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * -1.0f);
  733. }
  734. else
  735. {
  736. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f);
  737. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f);
  738. }
  739. }
  740. m_uniforms.m_frameIdx = float(m_currFrame % 8);
  741. {
  742. float lightPosition[] = { 0.0f, 6.0f, 10.0f };
  743. bx::memCopy(m_modelUniforms.m_lightPosition, lightPosition, 3*sizeof(float));
  744. }
  745. // bokeh depth of field
  746. {
  747. // reduce dimensions by half to go along with smaller render target
  748. const float blurScale = (m_useSinglePassBokehDof) ? 1.0f : 0.5f;
  749. m_uniforms.m_blurSteps = m_blurSteps;
  750. m_uniforms.m_samplePattern = float(m_samplePattern);
  751. m_uniforms.m_maxBlurSize = m_maxBlurSize * blurScale;
  752. m_uniforms.m_focusPoint = m_focusPoint;
  753. m_uniforms.m_focusScale = m_focusScale;
  754. m_uniforms.m_radiusScale = m_radiusScale * blurScale;
  755. }
  756. }
  757. uint32_t m_width;
  758. uint32_t m_height;
  759. uint32_t m_debug;
  760. uint32_t m_reset;
  761. entry::MouseState m_mouseState;
  762. // Resource handles
  763. bgfx::ProgramHandle m_forwardProgram;
  764. bgfx::ProgramHandle m_gridProgram;
  765. bgfx::ProgramHandle m_copyProgram;
  766. bgfx::ProgramHandle m_linearDepthProgram;
  767. bgfx::ProgramHandle m_dofSinglePassProgram;
  768. bgfx::ProgramHandle m_dofDownsampleProgram;
  769. bgfx::ProgramHandle m_dofQuarterProgram;
  770. bgfx::ProgramHandle m_dofCombineProgram;
  771. bgfx::ProgramHandle m_dofDebugProgram;
  772. // Shader uniforms
  773. PassUniforms m_uniforms;
  774. ModelUniforms m_modelUniforms;
  775. // Uniforms to indentify texture samplers
  776. bgfx::UniformHandle s_albedo;
  777. bgfx::UniformHandle s_color;
  778. bgfx::UniformHandle s_normal;
  779. bgfx::UniformHandle s_depth;
  780. bgfx::UniformHandle s_blurredColor;
  781. bgfx::FrameBufferHandle m_frameBuffer;
  782. bgfx::TextureHandle m_frameBufferTex[FRAMEBUFFER_RENDER_TARGETS];
  783. RenderTarget m_linearDepth;
  784. RenderTarget m_dofQuarterInput;
  785. RenderTarget m_dofQuarterOutput;
  786. struct Model
  787. {
  788. uint32_t mesh; // Index of mesh in m_meshes
  789. float position[3];
  790. };
  791. Mesh* m_meshes[BX_COUNTOF(s_meshPaths)];
  792. bgfx::TextureHandle m_groundTexture;
  793. bgfx::TextureHandle m_normalTexture;
  794. uint32_t m_currFrame;
  795. float m_lightRotation = 0.0f;
  796. float m_texelHalf = 0.0f;
  797. float m_fovY = 60.0f;
  798. bool m_recreateFrameBuffers = false;
  799. float m_animationTime = 0.0f;
  800. float m_view[16];
  801. float m_proj[16];
  802. float m_proj2[16];
  803. int32_t m_size[2];
  804. // UI parameters
  805. bool m_useBokehDof = true;
  806. bool m_useSinglePassBokehDof = true;
  807. float m_maxBlurSize = 20.0f;
  808. float m_focusPoint = 5.0f;
  809. float m_focusScale = 3.0f;
  810. float m_radiusScale = 3.856f;//0.5f;
  811. float m_blurSteps = 50.0f;
  812. int32_t m_samplePattern = 0;
  813. bool m_showDebugVisualization = false;
  814. };
  815. } // namespace
  816. ENTRY_IMPLEMENT_MAIN(ExampleBokeh, "45-bokeh", "Bokeh Depth of Field");