bokeh.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966
  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. class ExampleBokeh : public entry::AppI
  190. {
  191. public:
  192. ExampleBokeh(const char* _name, const char* _description)
  193. : entry::AppI(_name, _description)
  194. , m_currFrame(UINT32_MAX)
  195. , m_texelHalf(0.0f)
  196. {
  197. }
  198. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  199. {
  200. Args args(_argc, _argv);
  201. m_width = _width;
  202. m_height = _height;
  203. m_debug = BGFX_DEBUG_NONE;
  204. m_reset = BGFX_RESET_VSYNC;
  205. bgfx::Init init;
  206. init.type = args.m_type;
  207. init.vendorId = args.m_pciId;
  208. init.resolution.width = m_width;
  209. init.resolution.height = m_height;
  210. init.resolution.reset = m_reset;
  211. bgfx::init(init);
  212. // Enable debug text.
  213. bgfx::setDebug(m_debug);
  214. // Create uniforms for screen passes and models
  215. m_uniforms.init();
  216. m_modelUniforms.init();
  217. // Create texture sampler uniforms (used when we bind textures)
  218. s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler);
  219. s_color = bgfx::createUniform("s_color", bgfx::UniformType::Sampler);
  220. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Sampler);
  221. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler);
  222. s_blurredColor = bgfx::createUniform("s_blurredColor", bgfx::UniformType::Sampler);
  223. // Create program from shaders.
  224. m_forwardProgram = loadProgram("vs_bokeh_forward", "fs_bokeh_forward");
  225. m_gridProgram = loadProgram("vs_bokeh_forward", "fs_bokeh_forward_grid");
  226. m_copyProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_copy");
  227. m_linearDepthProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_linear_depth");
  228. m_dofSinglePassProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_single_pass");
  229. m_dofDownsampleProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_downsample");
  230. m_dofQuarterProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_second_pass");
  231. m_dofCombineProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_combine");
  232. m_dofDebugProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_debug");
  233. // Load some meshes
  234. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  235. {
  236. m_meshes[ii] = meshLoad(s_meshPaths[ii]);
  237. }
  238. m_groundTexture = loadTexture("textures/fieldstone-rgba.dds");
  239. m_normalTexture = loadTexture("textures/fieldstone-n.dds");
  240. m_recreateFrameBuffers = false;
  241. createFramebuffers();
  242. // Vertex decl
  243. PosTexCoord0Vertex::init();
  244. // Init camera
  245. cameraCreate();
  246. cameraSetPosition({ 0.0f, 2.5f, -20.0f });
  247. cameraSetVerticalAngle(-0.3f);
  248. m_fovY = 60.0f;
  249. // Init "prev" matrices, will be same for first frame
  250. cameraGetViewMtx(m_view);
  251. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  252. // Get renderer capabilities info.
  253. const bgfx::RendererType::Enum renderer = bgfx::getRendererType();
  254. m_texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f;
  255. imguiCreate();
  256. }
  257. int32_t shutdown() override
  258. {
  259. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  260. {
  261. meshUnload(m_meshes[ii]);
  262. }
  263. bgfx::destroy(m_normalTexture);
  264. bgfx::destroy(m_groundTexture);
  265. bgfx::destroy(m_forwardProgram);
  266. bgfx::destroy(m_gridProgram);
  267. bgfx::destroy(m_copyProgram);
  268. bgfx::destroy(m_linearDepthProgram);
  269. bgfx::destroy(m_dofSinglePassProgram);
  270. bgfx::destroy(m_dofDownsampleProgram);
  271. bgfx::destroy(m_dofQuarterProgram);
  272. bgfx::destroy(m_dofCombineProgram);
  273. bgfx::destroy(m_dofDebugProgram);
  274. m_uniforms.destroy();
  275. m_modelUniforms.destroy();
  276. bgfx::destroy(s_albedo);
  277. bgfx::destroy(s_color);
  278. bgfx::destroy(s_normal);
  279. bgfx::destroy(s_depth);
  280. bgfx::destroy(s_blurredColor);
  281. destroyFramebuffers();
  282. cameraDestroy();
  283. imguiDestroy();
  284. bgfx::shutdown();
  285. return 0;
  286. }
  287. bool update() override
  288. {
  289. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  290. {
  291. // skip processing when minimized, otherwise crashing
  292. if (0 == m_width || 0 == m_height)
  293. {
  294. return true;
  295. }
  296. // Update frame timer
  297. int64_t now = bx::getHPCounter();
  298. static int64_t last = now;
  299. const int64_t frameTime = now - last;
  300. last = now;
  301. const double freq = double(bx::getHPFrequency());
  302. const float deltaTime = float(frameTime / freq);
  303. const bgfx::Caps* caps = bgfx::getCaps();
  304. if (m_size[0] != (int32_t)m_width
  305. || m_size[1] != (int32_t)m_height
  306. || m_recreateFrameBuffers)
  307. {
  308. destroyFramebuffers();
  309. createFramebuffers();
  310. m_recreateFrameBuffers = false;
  311. }
  312. // update animation time
  313. const float rotationSpeed = 0.75f;
  314. m_animationTime += deltaTime * rotationSpeed;
  315. if (bx::kPi2 < m_animationTime)
  316. {
  317. m_animationTime -= bx::kPi2;
  318. }
  319. // Update camera
  320. cameraUpdate(deltaTime*0.15f, m_mouseState);
  321. cameraGetViewMtx(m_view);
  322. updateUniforms();
  323. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, caps->homogeneousDepth);
  324. bx::mtxProj(m_proj2, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, false);
  325. bgfx::ViewId view = 0;
  326. // Draw models into scene
  327. {
  328. bgfx::setViewName(view, "forward scene");
  329. bgfx::setViewClear(view
  330. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  331. , 0xbbddffff // clear to a sky blue
  332. , 1.0f
  333. , 0
  334. );
  335. bgfx::setViewRect(view, 0, 0, uint16_t(m_size[0]), uint16_t(m_size[1]));
  336. bgfx::setViewTransform(view, m_view, m_proj);
  337. bgfx::setViewFrameBuffer(view, m_frameBuffer);
  338. bgfx::setState(0
  339. | BGFX_STATE_WRITE_RGB
  340. | BGFX_STATE_WRITE_A
  341. | BGFX_STATE_WRITE_Z
  342. | BGFX_STATE_DEPTH_TEST_LESS
  343. );
  344. drawAllModels(view, m_forwardProgram, m_modelUniforms);
  345. ++view;
  346. }
  347. float orthoProj[16];
  348. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  349. {
  350. // clear out transform stack
  351. float identity[16];
  352. bx::mtxIdentity(identity);
  353. bgfx::setTransform(identity);
  354. }
  355. // Convert depth to linear depth for shadow depth compare
  356. {
  357. bgfx::setViewName(view, "linear depth");
  358. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  359. bgfx::setViewTransform(view, NULL, orthoProj);
  360. bgfx::setViewFrameBuffer(view, m_linearDepth.m_buffer);
  361. bgfx::setState(0
  362. | BGFX_STATE_WRITE_RGB
  363. | BGFX_STATE_WRITE_A
  364. | BGFX_STATE_DEPTH_TEST_ALWAYS
  365. );
  366. bgfx::setTexture(0, s_depth, m_frameBufferTex[FRAMEBUFFER_RT_DEPTH]);
  367. m_uniforms.submit();
  368. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  369. bgfx::submit(view, m_linearDepthProgram);
  370. ++view;
  371. }
  372. // optionally, apply dof
  373. const bool useOrDebugDof = m_useBokehDof || m_showDebugVisualization;
  374. if (useOrDebugDof)
  375. {
  376. view = drawDepthOfField(view, m_frameBufferTex[FRAMEBUFFER_RT_COLOR], orthoProj, caps->originBottomLeft);
  377. }
  378. else
  379. {
  380. bgfx::setViewName(view, "display");
  381. bgfx::setViewClear(view
  382. , BGFX_CLEAR_NONE
  383. , 0
  384. , 1.0f
  385. , 0
  386. );
  387. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  388. bgfx::setViewTransform(view, NULL, orthoProj);
  389. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  390. bgfx::setState(0
  391. | BGFX_STATE_WRITE_RGB
  392. | BGFX_STATE_WRITE_A
  393. );
  394. bgfx::setTexture(0, s_color, m_frameBufferTex[FRAMEBUFFER_RT_COLOR]);
  395. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  396. bgfx::submit(view, m_copyProgram);
  397. ++view;
  398. }
  399. // Draw UI
  400. imguiBeginFrame(m_mouseState.m_mx
  401. , m_mouseState.m_my
  402. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  403. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  404. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  405. , m_mouseState.m_mz
  406. , uint16_t(m_width)
  407. , uint16_t(m_height)
  408. );
  409. showExampleDialog(this);
  410. ImGui::SetNextWindowPos(
  411. ImVec2(m_width - m_width / 4.0f - 10.0f, 10.0f)
  412. , ImGuiCond_FirstUseEver
  413. );
  414. ImGui::SetNextWindowSize(
  415. ImVec2(m_width / 4.0f, m_height / 1.6f)
  416. , ImGuiCond_FirstUseEver
  417. );
  418. ImGui::Begin("Settings"
  419. , NULL
  420. , 0
  421. );
  422. ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
  423. {
  424. ImGui::Checkbox("use bokeh dof", &m_useBokehDof);
  425. if (ImGui::IsItemHovered())
  426. ImGui::SetTooltip("turn effect on and off");
  427. ImGui::Checkbox("use single pass at full res", &m_useSinglePassBokehDof);
  428. if (ImGui::IsItemHovered())
  429. {
  430. ImGui::BeginTooltip();
  431. ImGui::Text("calculate in a single pass at full resolution or use");
  432. ImGui::Text("multiple passes to compute at lower res and composite");
  433. ImGui::EndTooltip();
  434. }
  435. ImGui::Checkbox("show debug vis", &m_showDebugVisualization);
  436. if (ImGui::IsItemHovered())
  437. {
  438. ImGui::BeginTooltip();
  439. ImGui::Text("apply coloration to screen. fades from grey to orange with");
  440. ImGui::Text("increasing foreground blur. from grey to blue in background");
  441. ImGui::EndTooltip();
  442. }
  443. ImGui::Separator();
  444. ImGui::Text("blur controls:");
  445. ImGui::SliderFloat("max blur size", &m_maxBlurSize, 10.0f, 50.0f);
  446. if (ImGui::IsItemHovered())
  447. ImGui::SetTooltip("maximum blur size in screen pixels");
  448. ImGui::SliderFloat("focusPoint", &m_focusPoint, 1.0f, 20.0f);
  449. if (ImGui::IsItemHovered())
  450. ImGui::SetTooltip("distance to focus plane");
  451. ImGui::SliderFloat("focusScale", &m_focusScale, 0.0f, 10.0f);
  452. if (ImGui::IsItemHovered())
  453. ImGui::SetTooltip("multiply focus calculation, larger=tighter focus");
  454. ImGui::Separator();
  455. ImGui::Text("sample pattern controls:");
  456. ImGui::Combo("pattern", &m_samplePattern, "original\0sqrt\0\0");
  457. if (ImGui::IsItemHovered())
  458. {
  459. ImGui::BeginTooltip();
  460. ImGui::Text("original");
  461. ImGui::BulletText("pattern descibed by blogpost");
  462. ImGui::Text("sqrt");
  463. ImGui::BulletText("use sqrt instead of linear steps");
  464. ImGui::EndTooltip();
  465. }
  466. if (0 == m_samplePattern)
  467. {
  468. ImGui::SliderFloat("radiusScale", &m_radiusScale, 0.5f, 4.0f);
  469. if (ImGui::IsItemHovered())
  470. ImGui::SetTooltip("controls number of samples taken");
  471. ImGui::TextWrapped(
  472. "in original blog post, sample code has radius increasing by (radiusScale/currentRadius). "
  473. "which should result in smaller steps farther from center. and fewer steps as radiusScale "
  474. "increases. but it's less clear exactly how many steps that is, can be many."
  475. );
  476. const float maxRadius = m_maxBlurSize;
  477. float radius = m_radiusScale;
  478. int counter = 0;
  479. while (radius < maxRadius)
  480. {
  481. ++counter;
  482. radius += m_radiusScale / radius;
  483. }
  484. ImGui::Text("number of samples taken: %d", counter);
  485. if (ImGui::IsItemHovered())
  486. ImGui::SetTooltip("number of sample taps as determined by radiusScale");
  487. }
  488. else // 1 == samplePattern
  489. {
  490. ImGui::TextWrapped(
  491. "when using sqrt pattern, take a fixed number of steps. sqrt refers to how the radius "
  492. "is derived. in both cases, the sample pattern is a spiral out from the center."
  493. );
  494. ImGui::SliderFloat("blur steps", &m_blurSteps, 10.f, 100.0f);
  495. }
  496. }
  497. ImGui::End();
  498. imguiEndFrame();
  499. // Advance to next frame. Rendering thread will be kicked to
  500. // process submitted rendering primitives.
  501. m_currFrame = bgfx::frame();
  502. return true;
  503. }
  504. return false;
  505. }
  506. void drawAllModels(bgfx::ViewId _pass, bgfx::ProgramHandle _program, ModelUniforms & _uniforms)
  507. {
  508. const int32_t width = 6;
  509. const int32_t length = 20;
  510. float c0[] = { 72.0f/255.0f, 126.0f/255.0f, 149.0f/255.0f }; // blue
  511. float c1[] = { 235.0f/255.0f, 146.0f/255.0f, 251.0f/255.0f }; // purple
  512. float c2[] = { 199.0f/255.0f, 0.0f/255.0f, 57.0f/255.0f }; // pink
  513. for (int32_t zz = 0; zz < length; ++zz)
  514. {
  515. // make a color gradient, nothing special about this for example
  516. float * ca = c0;
  517. float * cb = c1;
  518. float lerpVal = float(zz) / float(length);
  519. if (0.5f <= lerpVal)
  520. {
  521. ca = c1;
  522. cb = c2;
  523. }
  524. lerpVal = bx::fract(2.0f*lerpVal);
  525. float r = bx::lerp(ca[0], cb[0], lerpVal);
  526. float g = bx::lerp(ca[1], cb[1], lerpVal);
  527. float b = bx::lerp(ca[2], cb[2], lerpVal);
  528. for (int32_t xx = 0; xx < width; ++xx)
  529. {
  530. const float angle = m_animationTime + float(zz)*(bx::kPi2/length) + float(xx)*(bx::kPiHalf/width);
  531. const float posX = 2.0f * xx - width + 1.0f;
  532. const float posY = bx::sin(angle);
  533. const float posZ = 2.0f * zz - length + 1.0f;
  534. const float scale = s_meshScale[MeshHollowCube];
  535. float mtx[16];
  536. bx::mtxSRT(mtx
  537. , scale
  538. , scale
  539. , scale
  540. , 0.0f
  541. , 0.0f
  542. , 0.0f
  543. , posX
  544. , posY
  545. , posZ
  546. );
  547. bgfx::setTexture(0, s_albedo, m_groundTexture);
  548. bgfx::setTexture(1, s_normal, m_normalTexture);
  549. _uniforms.m_color[0] = r;
  550. _uniforms.m_color[1] = g;
  551. _uniforms.m_color[2] = b;
  552. _uniforms.submit();
  553. meshSubmit(m_meshes[MeshHollowCube], _pass, _program, mtx);
  554. }
  555. }
  556. // draw box as ground plane
  557. {
  558. const float posY = -2.0f;
  559. const float scale = length;
  560. float mtx[16];
  561. bx::mtxSRT(mtx
  562. , scale
  563. , scale
  564. , scale
  565. , 0.0f
  566. , 0.0f
  567. , 0.0f
  568. , 0.0f
  569. , -scale + posY
  570. , 0.0f
  571. );
  572. _uniforms.m_color[0] = 0.5f;
  573. _uniforms.m_color[1] = 0.5f;
  574. _uniforms.m_color[2] = 0.5f;
  575. _uniforms.submit();
  576. meshSubmit(m_meshes[MeshCube], _pass, m_gridProgram, mtx);
  577. }
  578. }
  579. bgfx::ViewId drawDepthOfField(bgfx::ViewId _pass, bgfx::TextureHandle _colorTexture, float* _orthoProj, bool _originBottomLeft)
  580. {
  581. bgfx::ViewId view = _pass;
  582. bgfx::TextureHandle lastTex = _colorTexture;
  583. if (m_showDebugVisualization)
  584. {
  585. bgfx::setViewName(view, "bokeh dof debug pass");
  586. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  587. bgfx::setViewTransform(view, NULL, _orthoProj);
  588. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  589. bgfx::setState(0
  590. | BGFX_STATE_WRITE_RGB
  591. | BGFX_STATE_WRITE_A
  592. | BGFX_STATE_DEPTH_TEST_ALWAYS
  593. );
  594. bgfx::setTexture(0, s_color, lastTex);
  595. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  596. m_uniforms.submit();
  597. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  598. bgfx::submit(view, m_dofDebugProgram);
  599. ++view;
  600. }
  601. else if (m_useSinglePassBokehDof)
  602. {
  603. bgfx::setViewName(view, "bokeh dof single pass");
  604. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  605. bgfx::setViewTransform(view, NULL, _orthoProj);
  606. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  607. bgfx::setState(0
  608. | BGFX_STATE_WRITE_RGB
  609. | BGFX_STATE_WRITE_A
  610. | BGFX_STATE_DEPTH_TEST_ALWAYS
  611. );
  612. bgfx::setTexture(0, s_color, lastTex);
  613. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  614. m_uniforms.submit();
  615. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  616. bgfx::submit(view, m_dofSinglePassProgram);
  617. ++view;
  618. }
  619. else
  620. {
  621. unsigned halfWidth = (m_width/2);
  622. unsigned halfHeight = (m_height/2);
  623. bgfx::setViewName(view, "bokeh dof downsample");
  624. bgfx::setViewRect(view, 0, 0, uint16_t(halfWidth), uint16_t(halfHeight));
  625. bgfx::setViewTransform(view, NULL, _orthoProj);
  626. bgfx::setViewFrameBuffer(view, m_dofQuarterInput.m_buffer);
  627. bgfx::setState(0
  628. | BGFX_STATE_WRITE_RGB
  629. | BGFX_STATE_WRITE_A
  630. | BGFX_STATE_DEPTH_TEST_ALWAYS
  631. );
  632. bgfx::setTexture(0, s_color, lastTex);
  633. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  634. m_uniforms.submit();
  635. screenSpaceQuad(float(halfWidth), float(halfHeight), m_texelHalf, _originBottomLeft);
  636. bgfx::submit(view, m_dofDownsampleProgram);
  637. ++view;
  638. lastTex = m_dofQuarterInput.m_texture;
  639. /*
  640. replace the copy with bokeh dof combine
  641. able to read circle of confusion and color from downsample pass
  642. along with full res color and depth?
  643. do we need half res depth? i'm confused about that...
  644. */
  645. bgfx::setViewName(view, "bokeh dof quarter");
  646. bgfx::setViewRect(view, 0, 0, uint16_t(halfWidth), uint16_t(halfHeight));
  647. bgfx::setViewTransform(view, NULL, _orthoProj);
  648. bgfx::setViewFrameBuffer(view, m_dofQuarterOutput.m_buffer);
  649. bgfx::setState(0
  650. | BGFX_STATE_WRITE_RGB
  651. | BGFX_STATE_WRITE_A
  652. | BGFX_STATE_DEPTH_TEST_ALWAYS
  653. );
  654. bgfx::setTexture(0, s_color, lastTex);
  655. m_uniforms.submit();
  656. screenSpaceQuad(float(halfWidth), float(halfHeight), m_texelHalf, _originBottomLeft);
  657. bgfx::submit(view, m_dofQuarterProgram);
  658. ++view;
  659. lastTex = m_dofQuarterOutput.m_texture;
  660. bgfx::setViewName(view, "bokeh dof combine");
  661. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  662. bgfx::setViewTransform(view, NULL, _orthoProj);
  663. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  664. bgfx::setState(0
  665. | BGFX_STATE_WRITE_RGB
  666. | BGFX_STATE_WRITE_A
  667. | BGFX_STATE_DEPTH_TEST_ALWAYS
  668. );
  669. bgfx::setTexture(0, s_color, _colorTexture);
  670. bgfx::setTexture(1, s_blurredColor, lastTex);
  671. m_uniforms.submit();
  672. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  673. bgfx::submit(view, m_dofCombineProgram);
  674. ++view;
  675. }
  676. return view;
  677. }
  678. void createFramebuffers()
  679. {
  680. m_size[0] = m_width;
  681. m_size[1] = m_height;
  682. const uint64_t bilinearFlags = 0
  683. | BGFX_TEXTURE_RT
  684. | BGFX_SAMPLER_U_CLAMP
  685. | BGFX_SAMPLER_V_CLAMP
  686. ;
  687. m_frameBufferTex[FRAMEBUFFER_RT_COLOR] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, bilinearFlags);
  688. m_frameBufferTex[FRAMEBUFFER_RT_DEPTH] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::D32F, bilinearFlags);
  689. m_frameBuffer = bgfx::createFrameBuffer(BX_COUNTOF(m_frameBufferTex), m_frameBufferTex, true);
  690. m_linearDepth.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, bilinearFlags);
  691. unsigned halfWidth = m_size[0]/2;
  692. unsigned halfHeight = m_size[1]/2;
  693. m_dofQuarterInput.init(halfWidth, halfHeight, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  694. m_dofQuarterOutput.init(halfWidth, halfHeight, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  695. }
  696. // all buffers set to destroy their textures
  697. void destroyFramebuffers()
  698. {
  699. bgfx::destroy(m_frameBuffer);
  700. m_linearDepth.destroy();
  701. m_dofQuarterInput.destroy();
  702. m_dofQuarterOutput.destroy();
  703. }
  704. void updateUniforms()
  705. {
  706. // from assao sample, cs_assao_prepare_depths.sc
  707. {
  708. // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
  709. // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
  710. // correct the handedness issue. need to make sure this below is correct, but I think it is.
  711. float depthLinearizeMul = -m_proj2[3*4+2];
  712. float depthLinearizeAdd = m_proj2[2*4+2];
  713. if (depthLinearizeMul * depthLinearizeAdd < 0)
  714. {
  715. depthLinearizeAdd = -depthLinearizeAdd;
  716. }
  717. vec2Set(m_uniforms.m_depthUnpackConsts, depthLinearizeMul, depthLinearizeAdd);
  718. float tanHalfFOVY = 1.0f / m_proj2[1*4+1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
  719. float tanHalfFOVX = 1.0F / m_proj2[0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
  720. if (bgfx::getRendererType() == bgfx::RendererType::OpenGL)
  721. {
  722. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * 2.0f);
  723. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * -1.0f);
  724. }
  725. else
  726. {
  727. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f);
  728. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f);
  729. }
  730. }
  731. m_uniforms.m_frameIdx = float(m_currFrame % 8);
  732. {
  733. float lightPosition[] = { 0.0f, 6.0f, 10.0f };
  734. bx::memCopy(m_modelUniforms.m_lightPosition, lightPosition, 3*sizeof(float));
  735. }
  736. // bokeh depth of field
  737. {
  738. // reduce dimensions by half to go along with smaller render target
  739. const float blurScale = (m_useSinglePassBokehDof) ? 1.0f : 0.5f;
  740. m_uniforms.m_blurSteps = m_blurSteps;
  741. m_uniforms.m_samplePattern = float(m_samplePattern);
  742. m_uniforms.m_maxBlurSize = m_maxBlurSize * blurScale;
  743. m_uniforms.m_focusPoint = m_focusPoint;
  744. m_uniforms.m_focusScale = m_focusScale;
  745. m_uniforms.m_radiusScale = m_radiusScale * blurScale;
  746. }
  747. }
  748. uint32_t m_width;
  749. uint32_t m_height;
  750. uint32_t m_debug;
  751. uint32_t m_reset;
  752. entry::MouseState m_mouseState;
  753. // Resource handles
  754. bgfx::ProgramHandle m_forwardProgram;
  755. bgfx::ProgramHandle m_gridProgram;
  756. bgfx::ProgramHandle m_copyProgram;
  757. bgfx::ProgramHandle m_linearDepthProgram;
  758. bgfx::ProgramHandle m_dofSinglePassProgram;
  759. bgfx::ProgramHandle m_dofDownsampleProgram;
  760. bgfx::ProgramHandle m_dofQuarterProgram;
  761. bgfx::ProgramHandle m_dofCombineProgram;
  762. bgfx::ProgramHandle m_dofDebugProgram;
  763. // Shader uniforms
  764. PassUniforms m_uniforms;
  765. ModelUniforms m_modelUniforms;
  766. // Uniforms to indentify texture samplers
  767. bgfx::UniformHandle s_albedo;
  768. bgfx::UniformHandle s_color;
  769. bgfx::UniformHandle s_normal;
  770. bgfx::UniformHandle s_depth;
  771. bgfx::UniformHandle s_blurredColor;
  772. bgfx::FrameBufferHandle m_frameBuffer;
  773. bgfx::TextureHandle m_frameBufferTex[FRAMEBUFFER_RENDER_TARGETS];
  774. RenderTarget m_linearDepth;
  775. RenderTarget m_dofQuarterInput;
  776. RenderTarget m_dofQuarterOutput;
  777. struct Model
  778. {
  779. uint32_t mesh; // Index of mesh in m_meshes
  780. float position[3];
  781. };
  782. Mesh* m_meshes[BX_COUNTOF(s_meshPaths)];
  783. bgfx::TextureHandle m_groundTexture;
  784. bgfx::TextureHandle m_normalTexture;
  785. uint32_t m_currFrame;
  786. float m_lightRotation = 0.0f;
  787. float m_texelHalf = 0.0f;
  788. float m_fovY = 60.0f;
  789. bool m_recreateFrameBuffers = false;
  790. float m_animationTime = 0.0f;
  791. float m_view[16];
  792. float m_proj[16];
  793. float m_proj2[16];
  794. int32_t m_size[2];
  795. // UI parameters
  796. bool m_useBokehDof = true;
  797. bool m_useSinglePassBokehDof = true;
  798. float m_maxBlurSize = 20.0f;
  799. float m_focusPoint = 5.0f;
  800. float m_focusScale = 3.0f;
  801. float m_radiusScale = 3.856f;//0.5f;
  802. float m_blurSteps = 50.0f;
  803. int32_t m_samplePattern = 0;
  804. bool m_showDebugVisualization = false;
  805. };
  806. } // namespace
  807. ENTRY_IMPLEMENT_MAIN(ExampleBokeh, "45-bokeh", "Bokeh Depth of Field");