bokeh.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  1. /*
  2. * Copyright 2021 elven cache. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  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. MeshHollowCube
  40. };
  41. static const char * s_meshPaths[] =
  42. {
  43. "meshes/cube.bin",
  44. "meshes/hollowcube.bin"
  45. };
  46. static const float s_meshScale[] =
  47. {
  48. 0.45f,
  49. 0.30f
  50. };
  51. // Vertex decl for our screen space quad (used in deferred rendering)
  52. struct PosTexCoord0Vertex
  53. {
  54. float m_x;
  55. float m_y;
  56. float m_z;
  57. float m_u;
  58. float m_v;
  59. static void init()
  60. {
  61. ms_layout
  62. .begin()
  63. .add(bgfx::Attrib::Position, 3, bgfx::AttribType::Float)
  64. .add(bgfx::Attrib::TexCoord0, 2, bgfx::AttribType::Float)
  65. .end();
  66. }
  67. static bgfx::VertexLayout ms_layout;
  68. };
  69. bgfx::VertexLayout PosTexCoord0Vertex::ms_layout;
  70. struct PassUniforms
  71. {
  72. enum { NumVec4 = 4 };
  73. void init() {
  74. u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, NumVec4);
  75. };
  76. void submit() const {
  77. bgfx::setUniform(u_params, m_params, NumVec4);
  78. }
  79. void destroy() {
  80. bgfx::destroy(u_params);
  81. }
  82. union
  83. {
  84. struct
  85. {
  86. /* 0 */ struct { float m_depthUnpackConsts[2]; float m_frameIdx; float m_lobeRotation; };
  87. /* 1 */ struct { float m_ndcToViewMul[2]; float m_ndcToViewAdd[2]; };
  88. /* 2 */ struct { float m_blurSteps; float m_lobeCount; float m_lobeRadiusMin; float m_lobeRadiusDelta2x; };
  89. /* 3 */ struct { float m_maxBlurSize; float m_focusPoint; float m_focusScale; float m_radiusScale; };
  90. };
  91. float m_params[NumVec4 * 4];
  92. };
  93. bgfx::UniformHandle u_params;
  94. };
  95. struct ModelUniforms
  96. {
  97. enum { NumVec4 = 2 };
  98. void init() {
  99. u_params = bgfx::createUniform("u_modelParams", bgfx::UniformType::Vec4, NumVec4);
  100. };
  101. void submit() const {
  102. bgfx::setUniform(u_params, m_params, NumVec4);
  103. };
  104. void destroy() {
  105. bgfx::destroy(u_params);
  106. }
  107. union
  108. {
  109. struct
  110. {
  111. /* 0 */ struct { float m_color[3]; float m_unused0; };
  112. /* 1 */ struct { float m_lightPosition[3]; float m_unused1; };
  113. };
  114. float m_params[NumVec4 * 4];
  115. };
  116. bgfx::UniformHandle u_params;
  117. };
  118. struct RenderTarget
  119. {
  120. void init(uint32_t _width, uint32_t _height, bgfx::TextureFormat::Enum _format, uint64_t _flags)
  121. {
  122. m_texture = bgfx::createTexture2D(uint16_t(_width), uint16_t(_height), false, 1, _format, _flags);
  123. const bool destroyTextures = true;
  124. m_buffer = bgfx::createFrameBuffer(1, &m_texture, destroyTextures);
  125. }
  126. void destroy()
  127. {
  128. // also responsible for destroying texture
  129. bgfx::destroy(m_buffer);
  130. }
  131. bgfx::TextureHandle m_texture;
  132. bgfx::FrameBufferHandle m_buffer;
  133. };
  134. void screenSpaceQuad(float _textureWidth, float _textureHeight, float _texelHalf, bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
  135. {
  136. if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_layout))
  137. {
  138. bgfx::TransientVertexBuffer vb;
  139. bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_layout);
  140. PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
  141. const float minx = -_width;
  142. const float maxx = _width;
  143. const float miny = 0.0f;
  144. const float maxy = _height * 2.0f;
  145. const float texelHalfW = _texelHalf / _textureWidth;
  146. const float texelHalfH = _texelHalf / _textureHeight;
  147. const float minu = -1.0f + texelHalfW;
  148. const float maxu = 1.0f + texelHalfW;
  149. const float zz = 0.0f;
  150. float minv = texelHalfH;
  151. float maxv = 2.0f + texelHalfH;
  152. if (_originBottomLeft)
  153. {
  154. float temp = minv;
  155. minv = maxv;
  156. maxv = temp;
  157. minv -= 1.0f;
  158. maxv -= 1.0f;
  159. }
  160. vertex[0].m_x = minx;
  161. vertex[0].m_y = miny;
  162. vertex[0].m_z = zz;
  163. vertex[0].m_u = minu;
  164. vertex[0].m_v = minv;
  165. vertex[1].m_x = maxx;
  166. vertex[1].m_y = miny;
  167. vertex[1].m_z = zz;
  168. vertex[1].m_u = maxu;
  169. vertex[1].m_v = minv;
  170. vertex[2].m_x = maxx;
  171. vertex[2].m_y = maxy;
  172. vertex[2].m_z = zz;
  173. vertex[2].m_u = maxu;
  174. vertex[2].m_v = maxv;
  175. bgfx::setVertexBuffer(0, &vb);
  176. }
  177. }
  178. void vec2Set(float* _v, float _x, float _y)
  179. {
  180. _v[0] = _x;
  181. _v[1] = _y;
  182. }
  183. class ExampleBokeh : public entry::AppI
  184. {
  185. public:
  186. ExampleBokeh(const char* _name, const char* _description)
  187. : entry::AppI(_name, _description)
  188. , m_currFrame(UINT32_MAX)
  189. , m_texelHalf(0.0f)
  190. {
  191. }
  192. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  193. {
  194. Args args(_argc, _argv);
  195. m_width = _width;
  196. m_height = _height;
  197. m_debug = BGFX_DEBUG_NONE;
  198. m_reset = BGFX_RESET_VSYNC;
  199. bgfx::Init init;
  200. init.type = args.m_type;
  201. init.vendorId = args.m_pciId;
  202. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  203. init.platformData.ndt = entry::getNativeDisplayHandle();
  204. init.resolution.width = m_width;
  205. init.resolution.height = m_height;
  206. init.resolution.reset = m_reset;
  207. bgfx::init(init);
  208. // Enable debug text.
  209. bgfx::setDebug(m_debug);
  210. // Create uniforms for screen passes and models
  211. m_uniforms.init();
  212. m_modelUniforms.init();
  213. // Create texture sampler uniforms (used when we bind textures)
  214. s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler);
  215. s_color = bgfx::createUniform("s_color", bgfx::UniformType::Sampler);
  216. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Sampler);
  217. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler);
  218. s_blurredColor = bgfx::createUniform("s_blurredColor", bgfx::UniformType::Sampler);
  219. // Create program from shaders.
  220. m_forwardProgram = loadProgram("vs_bokeh_forward", "fs_bokeh_forward");
  221. m_gridProgram = loadProgram("vs_bokeh_forward", "fs_bokeh_forward_grid");
  222. m_copyProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_copy");
  223. m_copyLinearToGammaProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_copy_linear_to_gamma");
  224. m_linearDepthProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_linear_depth");
  225. m_dofSinglePassProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_single_pass");
  226. m_dofDownsampleProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_downsample");
  227. m_dofQuarterProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_second_pass");
  228. m_dofCombineProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_combine");
  229. m_dofDebugProgram = loadProgram("vs_bokeh_screenquad", "fs_bokeh_dof_debug");
  230. // Load some meshes
  231. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  232. {
  233. m_meshes[ii] = meshLoad(s_meshPaths[ii]);
  234. }
  235. m_groundTexture = loadTexture("textures/fieldstone-rgba.dds");
  236. m_normalTexture = loadTexture("textures/fieldstone-n.dds");
  237. m_recreateFrameBuffers = false;
  238. createFramebuffers();
  239. // Vertex decl
  240. PosTexCoord0Vertex::init();
  241. // Init camera
  242. cameraCreate();
  243. cameraSetPosition({ 0.0f, 2.5f, -20.0f });
  244. cameraSetVerticalAngle(-0.3f);
  245. m_fovY = 60.0f;
  246. // Init "prev" matrices, will be same for first frame
  247. cameraGetViewMtx(m_view);
  248. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  249. // Get renderer capabilities info.
  250. const bgfx::RendererType::Enum renderer = bgfx::getRendererType();
  251. m_texelHalf = bgfx::RendererType::Direct3D9 == renderer ? 0.5f : 0.0f;
  252. m_bokehTexture.idx = bgfx::kInvalidHandle;
  253. updateDisplayBokehTexture(m_radiusScale, m_maxBlurSize, m_lobeCount, (1.0f-m_lobePinch), 1.0f, m_lobeRotation);
  254. imguiCreate();
  255. }
  256. int32_t shutdown() override
  257. {
  258. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  259. {
  260. meshUnload(m_meshes[ii]);
  261. }
  262. bgfx::destroy(m_normalTexture);
  263. bgfx::destroy(m_groundTexture);
  264. bgfx::destroy(m_bokehTexture);
  265. bgfx::destroy(m_forwardProgram);
  266. bgfx::destroy(m_gridProgram);
  267. bgfx::destroy(m_copyProgram);
  268. bgfx::destroy(m_copyLinearToGammaProgram);
  269. bgfx::destroy(m_linearDepthProgram);
  270. bgfx::destroy(m_dofSinglePassProgram);
  271. bgfx::destroy(m_dofDownsampleProgram);
  272. bgfx::destroy(m_dofQuarterProgram);
  273. bgfx::destroy(m_dofCombineProgram);
  274. bgfx::destroy(m_dofDebugProgram);
  275. m_uniforms.destroy();
  276. m_modelUniforms.destroy();
  277. bgfx::destroy(s_albedo);
  278. bgfx::destroy(s_color);
  279. bgfx::destroy(s_normal);
  280. bgfx::destroy(s_depth);
  281. bgfx::destroy(s_blurredColor);
  282. destroyFramebuffers();
  283. cameraDestroy();
  284. imguiDestroy();
  285. bgfx::shutdown();
  286. return 0;
  287. }
  288. bool update() override
  289. {
  290. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  291. {
  292. // skip processing when minimized, otherwise crashing
  293. if (0 == m_width || 0 == m_height)
  294. {
  295. return true;
  296. }
  297. // Update frame timer
  298. int64_t now = bx::getHPCounter();
  299. static int64_t last = now;
  300. const int64_t frameTime = now - last;
  301. last = now;
  302. const double freq = double(bx::getHPFrequency());
  303. const float deltaTime = float(frameTime / freq);
  304. const bgfx::Caps* caps = bgfx::getCaps();
  305. if (m_size[0] != (int32_t)m_width
  306. || m_size[1] != (int32_t)m_height
  307. || m_recreateFrameBuffers)
  308. {
  309. destroyFramebuffers();
  310. createFramebuffers();
  311. m_recreateFrameBuffers = false;
  312. }
  313. // update animation time
  314. const float rotationSpeed = 0.75f;
  315. m_animationTime += deltaTime * rotationSpeed;
  316. if (bx::kPi2 < m_animationTime)
  317. {
  318. m_animationTime -= bx::kPi2;
  319. }
  320. // Update camera
  321. cameraUpdate(deltaTime*0.15f, m_mouseState, ImGui::MouseOverArea() );
  322. cameraGetViewMtx(m_view);
  323. updateUniforms();
  324. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, caps->homogeneousDepth);
  325. bx::mtxProj(m_proj2, m_fovY, float(m_size[0]) / float(m_size[1]), 0.01f, 100.0f, false);
  326. bgfx::ViewId view = 0;
  327. // Draw models into scene
  328. {
  329. bgfx::setViewName(view, "forward scene");
  330. bgfx::setViewClear(view
  331. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  332. , 0x7fb8ffff // clear to a sky blue
  333. , 1.0f
  334. , 0
  335. );
  336. bgfx::setViewRect(view, 0, 0, uint16_t(m_size[0]), uint16_t(m_size[1]));
  337. bgfx::setViewTransform(view, m_view, m_proj);
  338. bgfx::setViewFrameBuffer(view, m_frameBuffer);
  339. bgfx::setState(0
  340. | BGFX_STATE_WRITE_RGB
  341. | BGFX_STATE_WRITE_A
  342. | BGFX_STATE_WRITE_Z
  343. | BGFX_STATE_DEPTH_TEST_LESS
  344. );
  345. drawAllModels(view, m_forwardProgram, m_modelUniforms);
  346. ++view;
  347. }
  348. float orthoProj[16];
  349. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  350. {
  351. // clear out transform stack
  352. float identity[16];
  353. bx::mtxIdentity(identity);
  354. bgfx::setTransform(identity);
  355. }
  356. // Convert depth to linear depth for shadow depth compare
  357. {
  358. bgfx::setViewName(view, "linear depth");
  359. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  360. bgfx::setViewTransform(view, NULL, orthoProj);
  361. bgfx::setViewFrameBuffer(view, m_linearDepth.m_buffer);
  362. bgfx::setState(0
  363. | BGFX_STATE_WRITE_RGB
  364. | BGFX_STATE_WRITE_A
  365. | BGFX_STATE_DEPTH_TEST_ALWAYS
  366. );
  367. bgfx::setTexture(0, s_depth, m_frameBufferTex[FRAMEBUFFER_RT_DEPTH]);
  368. m_uniforms.submit();
  369. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  370. bgfx::submit(view, m_linearDepthProgram);
  371. ++view;
  372. }
  373. // optionally, apply dof
  374. const bool useOrDebugDof = m_useBokehDof || m_showDebugVisualization;
  375. if (useOrDebugDof)
  376. {
  377. view = drawDepthOfField(view, m_frameBufferTex[FRAMEBUFFER_RT_COLOR], orthoProj, caps->originBottomLeft);
  378. }
  379. else
  380. {
  381. bgfx::setViewName(view, "display");
  382. bgfx::setViewClear(view
  383. , BGFX_CLEAR_NONE
  384. , 0
  385. , 1.0f
  386. , 0
  387. );
  388. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  389. bgfx::setViewTransform(view, NULL, orthoProj);
  390. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  391. bgfx::setState(0
  392. | BGFX_STATE_WRITE_RGB
  393. | BGFX_STATE_WRITE_A
  394. );
  395. bgfx::setTexture(0, s_color, m_frameBufferTex[FRAMEBUFFER_RT_COLOR]);
  396. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, caps->originBottomLeft);
  397. bgfx::submit(view, m_copyLinearToGammaProgram);
  398. ++view;
  399. }
  400. // Draw UI
  401. imguiBeginFrame(m_mouseState.m_mx
  402. , m_mouseState.m_my
  403. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  404. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  405. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  406. , m_mouseState.m_mz
  407. , uint16_t(m_width)
  408. , uint16_t(m_height)
  409. );
  410. showExampleDialog(this);
  411. ImGui::SetNextWindowPos(
  412. ImVec2(m_width - m_width / 4.0f - 10.0f, 10.0f)
  413. , ImGuiCond_FirstUseEver
  414. );
  415. ImGui::SetNextWindowSize(
  416. ImVec2(m_width / 4.0f, m_height / 1.35f)
  417. , ImGuiCond_FirstUseEver
  418. );
  419. ImGui::Begin("Settings"
  420. , NULL
  421. , 0
  422. );
  423. ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
  424. {
  425. ImGui::Checkbox("use bokeh dof", &m_useBokehDof);
  426. if (ImGui::IsItemHovered())
  427. ImGui::SetTooltip("turn effect on and off");
  428. ImGui::Checkbox("use single pass at full res", &m_useSinglePassBokehDof);
  429. if (ImGui::IsItemHovered())
  430. {
  431. ImGui::BeginTooltip();
  432. ImGui::Text("calculate in a single pass at full resolution or use");
  433. ImGui::Text("multiple passes to compute at lower res and composite");
  434. ImGui::EndTooltip();
  435. }
  436. ImGui::Checkbox("show debug vis", &m_showDebugVisualization);
  437. if (ImGui::IsItemHovered())
  438. {
  439. ImGui::BeginTooltip();
  440. ImGui::Text("apply coloration to screen. fades from grey to orange with");
  441. ImGui::Text("increasing foreground blur. from grey to blue in background");
  442. ImGui::EndTooltip();
  443. }
  444. ImGui::Separator();
  445. bool isChanged = false;
  446. ImGui::Text("blur controls:");
  447. isChanged |= ImGui::SliderFloat("max blur size", &m_maxBlurSize, 10.0f, 50.0f);
  448. if (ImGui::IsItemHovered())
  449. ImGui::SetTooltip("maximum blur size in screen pixels");
  450. ImGui::SliderFloat("focusPoint", &m_focusPoint, 1.0f, 20.0f);
  451. if (ImGui::IsItemHovered())
  452. ImGui::SetTooltip("distance to focus plane");
  453. ImGui::SliderFloat("focusScale", &m_focusScale, 0.0f, 10.0f);
  454. if (ImGui::IsItemHovered())
  455. ImGui::SetTooltip("multiply focus calculation, larger=tighter focus");
  456. ImGui::Separator();
  457. ImGui::Text("bokeh shape and sample controls:");
  458. isChanged |= ImGui::SliderFloat("radiusScale", &m_radiusScale, 0.5f, 4.0f);
  459. if (ImGui::IsItemHovered())
  460. ImGui::SetTooltip("controls number of samples taken");
  461. isChanged |= ImGui::SliderInt("lobe count", &m_lobeCount, 1, 8);
  462. if (ImGui::IsItemHovered())
  463. ImGui::SetTooltip("using triangle lobes to emulate aperture blades");
  464. isChanged |= ImGui::SliderFloat("lobe pinch", &m_lobePinch, 0.0f, 1.0f);
  465. if (ImGui::IsItemHovered())
  466. ImGui::SetTooltip("adjust lobe shape, 0=round, 1=starry");
  467. isChanged |= ImGui::SliderFloat("lobe rotation", &m_lobeRotation, -1.0f, 1.0f);
  468. if (isChanged)
  469. {
  470. updateDisplayBokehTexture(m_radiusScale, m_maxBlurSize, m_lobeCount, (1.0f-m_lobePinch), 1.0f, m_lobeRotation);
  471. }
  472. ImGui::Text("number of samples taken: %d", m_sampleCount);
  473. if (ImGui::IsItemHovered())
  474. ImGui::SetTooltip("number of sample taps as determined by radiusScale and maxBlurSize");
  475. ImGui::Image(m_bokehTexture, ImVec2(128.0f, 128.0f) );
  476. }
  477. ImGui::End();
  478. imguiEndFrame();
  479. // Advance to next frame. Rendering thread will be kicked to
  480. // process submitted rendering primitives.
  481. m_currFrame = bgfx::frame();
  482. return true;
  483. }
  484. return false;
  485. }
  486. void drawAllModels(bgfx::ViewId _pass, bgfx::ProgramHandle _program, ModelUniforms & _uniforms)
  487. {
  488. const int32_t width = 6;
  489. const int32_t length = 20;
  490. float c0[] = { 72.0f/255.0f, 126.0f/255.0f, 149.0f/255.0f }; // blue
  491. float c1[] = { 235.0f/255.0f, 146.0f/255.0f, 251.0f/255.0f }; // purple
  492. float c2[] = { 199.0f/255.0f, 0.0f/255.0f, 57.0f/255.0f }; // pink
  493. for (int32_t zz = 0; zz < length; ++zz)
  494. {
  495. // make a color gradient, nothing special about this for example
  496. float * ca = c0;
  497. float * cb = c1;
  498. float lerpVal = float(zz) / float(length);
  499. if (0.5f <= lerpVal)
  500. {
  501. ca = c1;
  502. cb = c2;
  503. }
  504. lerpVal = bx::fract(2.0f*lerpVal);
  505. float r = bx::lerp(ca[0], cb[0], lerpVal);
  506. float g = bx::lerp(ca[1], cb[1], lerpVal);
  507. float b = bx::lerp(ca[2], cb[2], lerpVal);
  508. for (int32_t xx = 0; xx < width; ++xx)
  509. {
  510. const float angle = m_animationTime + float(zz)*(bx::kPi2/length) + float(xx)*(bx::kPiHalf/width);
  511. const float posX = 2.0f * xx - width + 1.0f;
  512. const float posY = bx::sin(angle);
  513. const float posZ = 2.0f * zz - length + 1.0f;
  514. const float scale = s_meshScale[MeshHollowCube];
  515. float mtx[16];
  516. bx::mtxSRT(mtx
  517. , scale
  518. , scale
  519. , scale
  520. , 0.0f
  521. , 0.0f
  522. , 0.0f
  523. , posX
  524. , posY
  525. , posZ
  526. );
  527. bgfx::setTexture(0, s_albedo, m_groundTexture);
  528. bgfx::setTexture(1, s_normal, m_normalTexture);
  529. _uniforms.m_color[0] = r;
  530. _uniforms.m_color[1] = g;
  531. _uniforms.m_color[2] = b;
  532. _uniforms.submit();
  533. meshSubmit(m_meshes[MeshHollowCube], _pass, _program, mtx);
  534. }
  535. }
  536. // draw box as ground plane
  537. {
  538. const float posY = -2.0f;
  539. const float scale = length;
  540. float mtx[16];
  541. bx::mtxSRT(mtx
  542. , scale
  543. , scale
  544. , scale
  545. , 0.0f
  546. , 0.0f
  547. , 0.0f
  548. , 0.0f
  549. , -scale + posY
  550. , 0.0f
  551. );
  552. _uniforms.m_color[0] = 0.5f;
  553. _uniforms.m_color[1] = 0.5f;
  554. _uniforms.m_color[2] = 0.5f;
  555. _uniforms.submit();
  556. meshSubmit(m_meshes[MeshCube], _pass, m_gridProgram, mtx);
  557. }
  558. }
  559. bgfx::ViewId drawDepthOfField(bgfx::ViewId _pass, bgfx::TextureHandle _colorTexture, float* _orthoProj, bool _originBottomLeft)
  560. {
  561. bgfx::ViewId view = _pass;
  562. bgfx::TextureHandle lastTex = _colorTexture;
  563. if (m_showDebugVisualization)
  564. {
  565. bgfx::setViewName(view, "bokeh dof debug pass");
  566. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  567. bgfx::setViewTransform(view, NULL, _orthoProj);
  568. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  569. bgfx::setState(0
  570. | BGFX_STATE_WRITE_RGB
  571. | BGFX_STATE_WRITE_A
  572. | BGFX_STATE_DEPTH_TEST_ALWAYS
  573. );
  574. bgfx::setTexture(0, s_color, lastTex);
  575. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  576. m_uniforms.submit();
  577. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  578. bgfx::submit(view, m_dofDebugProgram);
  579. ++view;
  580. }
  581. else if (m_useSinglePassBokehDof)
  582. {
  583. bgfx::setViewName(view, "bokeh dof single pass");
  584. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  585. bgfx::setViewTransform(view, NULL, _orthoProj);
  586. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  587. bgfx::setState(0
  588. | BGFX_STATE_WRITE_RGB
  589. | BGFX_STATE_WRITE_A
  590. | BGFX_STATE_DEPTH_TEST_ALWAYS
  591. );
  592. bgfx::setTexture(0, s_color, lastTex);
  593. bgfx::setTexture(1, s_depth, m_linearDepth.m_texture);
  594. m_uniforms.submit();
  595. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  596. bgfx::submit(view, m_dofSinglePassProgram);
  597. ++view;
  598. }
  599. else
  600. {
  601. unsigned halfWidth = (m_width/2);
  602. unsigned halfHeight = (m_height/2);
  603. bgfx::setViewName(view, "bokeh dof downsample");
  604. bgfx::setViewRect(view, 0, 0, uint16_t(halfWidth), uint16_t(halfHeight));
  605. bgfx::setViewTransform(view, NULL, _orthoProj);
  606. bgfx::setViewFrameBuffer(view, m_dofQuarterInput.m_buffer);
  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(halfWidth), float(halfHeight), m_texelHalf, _originBottomLeft);
  616. bgfx::submit(view, m_dofDownsampleProgram);
  617. ++view;
  618. lastTex = m_dofQuarterInput.m_texture;
  619. /*
  620. replace the copy with bokeh dof combine
  621. able to read circle of confusion and color from downsample pass
  622. along with full res color and depth?
  623. do we need half res depth? i'm confused about that...
  624. */
  625. bgfx::setViewName(view, "bokeh dof quarter");
  626. bgfx::setViewRect(view, 0, 0, uint16_t(halfWidth), uint16_t(halfHeight));
  627. bgfx::setViewTransform(view, NULL, _orthoProj);
  628. bgfx::setViewFrameBuffer(view, m_dofQuarterOutput.m_buffer);
  629. bgfx::setState(0
  630. | BGFX_STATE_WRITE_RGB
  631. | BGFX_STATE_WRITE_A
  632. | BGFX_STATE_DEPTH_TEST_ALWAYS
  633. );
  634. bgfx::setTexture(0, s_color, lastTex);
  635. m_uniforms.submit();
  636. screenSpaceQuad(float(halfWidth), float(halfHeight), m_texelHalf, _originBottomLeft);
  637. bgfx::submit(view, m_dofQuarterProgram);
  638. ++view;
  639. lastTex = m_dofQuarterOutput.m_texture;
  640. bgfx::setViewName(view, "bokeh dof combine");
  641. bgfx::setViewRect(view, 0, 0, uint16_t(m_width), uint16_t(m_height));
  642. bgfx::setViewTransform(view, NULL, _orthoProj);
  643. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  644. bgfx::setState(0
  645. | BGFX_STATE_WRITE_RGB
  646. | BGFX_STATE_WRITE_A
  647. | BGFX_STATE_DEPTH_TEST_ALWAYS
  648. );
  649. bgfx::setTexture(0, s_color, _colorTexture);
  650. bgfx::setTexture(1, s_blurredColor, lastTex);
  651. m_uniforms.submit();
  652. screenSpaceQuad(float(m_width), float(m_height), m_texelHalf, _originBottomLeft);
  653. bgfx::submit(view, m_dofCombineProgram);
  654. ++view;
  655. }
  656. return view;
  657. }
  658. void createFramebuffers()
  659. {
  660. m_size[0] = m_width;
  661. m_size[1] = m_height;
  662. const uint64_t bilinearFlags = 0
  663. | BGFX_TEXTURE_RT
  664. | BGFX_SAMPLER_U_CLAMP
  665. | BGFX_SAMPLER_V_CLAMP
  666. ;
  667. m_frameBufferTex[FRAMEBUFFER_RT_COLOR] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  668. m_frameBufferTex[FRAMEBUFFER_RT_DEPTH] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::D32F, bilinearFlags);
  669. m_frameBuffer = bgfx::createFrameBuffer(BX_COUNTOF(m_frameBufferTex), m_frameBufferTex, true);
  670. m_linearDepth.init(m_size[0], m_size[1], bgfx::TextureFormat::R16F, bilinearFlags);
  671. unsigned halfWidth = m_size[0]/2;
  672. unsigned halfHeight = m_size[1]/2;
  673. m_dofQuarterInput.init(halfWidth, halfHeight, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  674. m_dofQuarterOutput.init(halfWidth, halfHeight, bgfx::TextureFormat::RGBA16F, bilinearFlags);
  675. }
  676. // all buffers set to destroy their textures
  677. void destroyFramebuffers()
  678. {
  679. bgfx::destroy(m_frameBuffer);
  680. m_linearDepth.destroy();
  681. m_dofQuarterInput.destroy();
  682. m_dofQuarterOutput.destroy();
  683. }
  684. void updateUniforms()
  685. {
  686. // from assao sample, cs_assao_prepare_depths.sc
  687. {
  688. // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
  689. // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
  690. // correct the handedness issue. need to make sure this below is correct, but I think it is.
  691. float depthLinearizeMul = -m_proj2[3*4+2];
  692. float depthLinearizeAdd = m_proj2[2*4+2];
  693. if (depthLinearizeMul * depthLinearizeAdd < 0)
  694. {
  695. depthLinearizeAdd = -depthLinearizeAdd;
  696. }
  697. vec2Set(m_uniforms.m_depthUnpackConsts, depthLinearizeMul, depthLinearizeAdd);
  698. float tanHalfFOVY = 1.0f / m_proj2[1*4+1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
  699. float tanHalfFOVX = 1.0F / m_proj2[0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
  700. if (bgfx::getRendererType() == bgfx::RendererType::OpenGL)
  701. {
  702. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * 2.0f);
  703. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * -1.0f);
  704. }
  705. else
  706. {
  707. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f);
  708. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f);
  709. }
  710. }
  711. m_uniforms.m_frameIdx = float(m_currFrame % 8);
  712. {
  713. float lightPosition[] = { 0.0f, 6.0f, 10.0f };
  714. bx::memCopy(m_modelUniforms.m_lightPosition, lightPosition, 3*sizeof(float));
  715. }
  716. // bokeh depth of field
  717. {
  718. // reduce dimensions by half to go along with smaller render target
  719. const float blurScale = (m_useSinglePassBokehDof) ? 1.0f : 0.5f;
  720. m_uniforms.m_blurSteps = m_blurSteps;
  721. m_uniforms.m_lobeCount = float(m_lobeCount);
  722. m_uniforms.m_lobeRadiusMin = (1.0f - m_lobePinch);
  723. m_uniforms.m_lobeRadiusDelta2x = 2.0f * m_lobePinch;
  724. m_uniforms.m_maxBlurSize = m_maxBlurSize * blurScale;
  725. m_uniforms.m_focusPoint = m_focusPoint;
  726. m_uniforms.m_focusScale = m_focusScale;
  727. m_uniforms.m_radiusScale = m_radiusScale * blurScale;
  728. m_uniforms.m_lobeRotation = m_lobeRotation;
  729. }
  730. }
  731. static float bokehShapeFromAngle (int _lobeCount, float _radiusMin, float _radiusDelta2x, float _rotation, float _theta)
  732. {
  733. // don't shape for 0, 1 blades...
  734. if (_lobeCount <= 1)
  735. {
  736. return 1.0f;
  737. }
  738. // divide edge into some number of lobes
  739. const float invPeriod = float(_lobeCount) / (bx::kPi2);
  740. float periodFraction = bx::fract(_theta * invPeriod + _rotation);
  741. // apply triangle shape to each lobe to approximate blades of a camera aperture
  742. periodFraction = bx::abs(periodFraction - 0.5f);
  743. return periodFraction * _radiusDelta2x + _radiusMin;
  744. }
  745. void updateDisplayBokehTexture(
  746. float _radiusScale,
  747. float _maxBlurSize,
  748. int _lobeCount,
  749. float _lobeRadiusMin,
  750. float _lobeRadiusMax,
  751. float _lobeRotation)
  752. {
  753. if (m_bokehTexture.idx != bgfx::kInvalidHandle)
  754. {
  755. bgfx::destroy(m_bokehTexture);
  756. }
  757. BX_ASSERT(0 < _lobeCount, "");
  758. const int32_t bokehSize = 128;
  759. const bgfx::Memory* mem = bgfx::alloc(bokehSize*bokehSize*4);
  760. bx::memSet(mem->data, 0x00, bokehSize*bokehSize*4);
  761. const float thetaStep = 2.39996323f; // golden angle
  762. float loopValue = _radiusScale;
  763. const float loopEnd = _maxBlurSize;
  764. float theta = 0.0f;
  765. // bokeh shape function multiples this by half later
  766. const float radiusDelta2x = 2.0f * (_lobeRadiusMax - _lobeRadiusMin);
  767. int32_t counter = 0;
  768. while (loopValue < loopEnd)
  769. {
  770. float radius = loopValue;
  771. // apply shape to circular distribution
  772. const float shapeScale = bokehShapeFromAngle(_lobeCount, _lobeRadiusMin, radiusDelta2x, _lobeRotation, theta);
  773. BX_ASSERT(_lobeRadiusMin <= shapeScale, "");
  774. float spiralCoordX = bx::cos(theta) * (radius * shapeScale);
  775. float spiralCoordY = bx::sin(theta) * (radius * shapeScale);
  776. // normalize for texture display
  777. spiralCoordX /= _maxBlurSize;
  778. spiralCoordY /= _maxBlurSize;
  779. // scale from -1,1 into 0,1 normalized texture space
  780. spiralCoordX = spiralCoordX * 0.5f + 0.5f;
  781. spiralCoordY = spiralCoordY * 0.5f + 0.5f;
  782. // convert to pixel coordinates
  783. int32_t pixelCoordX = int32_t(bx::floor(spiralCoordX * float(bokehSize-1) + 0.5f));
  784. int32_t pixelCoordY = int32_t(bx::floor(spiralCoordY * float(bokehSize-1) + 0.5f));
  785. BX_ASSERT(0 <= pixelCoordX, "");
  786. BX_ASSERT(0 <= pixelCoordY, "");
  787. BX_ASSERT(pixelCoordX < bokehSize, "");
  788. BX_ASSERT(pixelCoordY < bokehSize, "");
  789. // plot sample position, track for total samples
  790. uint32_t offset = (pixelCoordY * bokehSize + pixelCoordX) * 4;
  791. mem->data[offset + 0] = 0xff;
  792. mem->data[offset + 1] = 0xff;
  793. mem->data[offset + 2] = 0xff;
  794. mem->data[offset + 3] = 0xff;
  795. ++counter;
  796. theta += thetaStep;
  797. loopValue += (_radiusScale / loopValue);
  798. }
  799. m_sampleCount = counter;
  800. // hoping texture deals with mem
  801. m_bokehTexture = bgfx::createTexture2D(bokehSize, bokehSize, false, 1
  802. , bgfx::TextureFormat::BGRA8
  803. , 0
  804. | BGFX_SAMPLER_MIN_POINT
  805. | BGFX_SAMPLER_MIP_POINT
  806. | BGFX_SAMPLER_MAG_POINT
  807. , mem
  808. );
  809. }
  810. uint32_t m_width;
  811. uint32_t m_height;
  812. uint32_t m_debug;
  813. uint32_t m_reset;
  814. entry::MouseState m_mouseState;
  815. // Resource handles
  816. bgfx::ProgramHandle m_forwardProgram;
  817. bgfx::ProgramHandle m_gridProgram;
  818. bgfx::ProgramHandle m_copyProgram;
  819. bgfx::ProgramHandle m_copyLinearToGammaProgram;
  820. bgfx::ProgramHandle m_linearDepthProgram;
  821. bgfx::ProgramHandle m_dofSinglePassProgram;
  822. bgfx::ProgramHandle m_dofDownsampleProgram;
  823. bgfx::ProgramHandle m_dofQuarterProgram;
  824. bgfx::ProgramHandle m_dofCombineProgram;
  825. bgfx::ProgramHandle m_dofDebugProgram;
  826. // Shader uniforms
  827. PassUniforms m_uniforms;
  828. ModelUniforms m_modelUniforms;
  829. // Uniforms to identify texture samplers
  830. bgfx::UniformHandle s_albedo;
  831. bgfx::UniformHandle s_color;
  832. bgfx::UniformHandle s_normal;
  833. bgfx::UniformHandle s_depth;
  834. bgfx::UniformHandle s_blurredColor;
  835. bgfx::FrameBufferHandle m_frameBuffer;
  836. bgfx::TextureHandle m_frameBufferTex[FRAMEBUFFER_RENDER_TARGETS];
  837. RenderTarget m_linearDepth;
  838. RenderTarget m_dofQuarterInput;
  839. RenderTarget m_dofQuarterOutput;
  840. struct Model
  841. {
  842. uint32_t mesh; // Index of mesh in m_meshes
  843. float position[3];
  844. };
  845. Mesh* m_meshes[BX_COUNTOF(s_meshPaths)];
  846. bgfx::TextureHandle m_groundTexture;
  847. bgfx::TextureHandle m_normalTexture;
  848. bgfx::TextureHandle m_bokehTexture;
  849. uint32_t m_currFrame;
  850. float m_lightRotation = 0.0f;
  851. float m_texelHalf = 0.0f;
  852. float m_fovY = 60.0f;
  853. bool m_recreateFrameBuffers = false;
  854. float m_animationTime = 0.0f;
  855. float m_view[16];
  856. float m_proj[16];
  857. float m_proj2[16];
  858. int32_t m_size[2];
  859. // UI parameters
  860. bool m_useBokehDof = true;
  861. bool m_useSinglePassBokehDof = false;
  862. float m_maxBlurSize = 20.0f;
  863. float m_focusPoint = 5.0f;
  864. float m_focusScale = 3.0f;
  865. float m_radiusScale = 0.5f;
  866. float m_blurSteps = 50.0f;
  867. bool m_showDebugVisualization = false;
  868. int32_t m_lobeCount = 6;
  869. float m_lobePinch = 0.2f;
  870. float m_lobeRotation = 0.0f;
  871. int32_t m_sampleCount = 0;
  872. };
  873. } // namespace
  874. ENTRY_IMPLEMENT_MAIN(ExampleBokeh, "45-bokeh", "Bokeh Depth of Field");