assao.cpp 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  1. /*
  2. * Copyright 2018 Attila Kocsis. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx/blob/master/LICENSE
  4. */
  5. /*
  6. * Reference(s):
  7. * - ASSAO is a SSAO implementation tuned for scalability and flexibility.
  8. * https://web.archive.org/web/20181214222937/https://software.intel.com/en-us/articles/adaptive-screen-space-ambient-occlusion
  9. * https://github.com/GameTechDev/ASSAO
  10. */
  11. #include <common.h>
  12. #include <camera.h>
  13. #include <bgfx_utils.h>
  14. #include <imgui/imgui.h>
  15. #include <bx/rng.h>
  16. #include <bx/os.h>
  17. #define USE_ASSAO 0
  18. namespace
  19. {
  20. // Render passes
  21. #define RENDER_PASS_GBUFFER 0 // GBuffer for normals and albedo
  22. #define RENDER_PASS_COMBINE 1 // Directional light and final result
  23. // Gbuffer has multiple render targets
  24. #define GBUFFER_RT_NORMAL 0
  25. #define GBUFFER_RT_COLOR 1
  26. #define GBUFFER_RT_DEPTH 2
  27. // Random meshes we draw
  28. #define MODEL_COUNT 120 // In this demo, a model is a mesh plus a transform
  29. #define SAMPLER_POINT_CLAMP (BGFX_SAMPLER_POINT|BGFX_SAMPLER_UVW_CLAMP)
  30. #define SAMPLER_POINT_MIRROR (BGFX_SAMPLER_POINT|BGFX_SAMPLER_UVW_MIRROR)
  31. #define SAMPLER_LINEAR_CLAMP (BGFX_SAMPLER_UVW_CLAMP)
  32. #define SSAO_DEPTH_MIP_LEVELS 4
  33. static const char * s_meshPaths[] =
  34. {
  35. "meshes/cube.bin",
  36. "meshes/orb.bin",
  37. "meshes/column.bin",
  38. "meshes/bunny_decimated.bin",
  39. "meshes/tree.bin",
  40. "meshes/hollowcube.bin"
  41. };
  42. static const float s_meshScale[] =
  43. {
  44. 0.25f,
  45. 0.5f,
  46. 0.05f,
  47. 0.5f,
  48. 0.05f,
  49. 0.25f
  50. };
  51. // Vertex layout 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. // Utility function to draw a screen space quad for deferred rendering
  71. void screenSpaceQuad(bool _originBottomLeft, float _width = 1.0f, float _height = 1.0f)
  72. {
  73. if (3 == bgfx::getAvailTransientVertexBuffer(3, PosTexCoord0Vertex::ms_layout))
  74. {
  75. bgfx::TransientVertexBuffer vb;
  76. bgfx::allocTransientVertexBuffer(&vb, 3, PosTexCoord0Vertex::ms_layout);
  77. PosTexCoord0Vertex* vertex = (PosTexCoord0Vertex*)vb.data;
  78. const float minx = -_width;
  79. const float maxx = _width;
  80. const float miny = 0.0f;
  81. const float maxy = _height * 2.0f;
  82. const float minu = -1.0f;
  83. const float maxu = 1.0f;
  84. const float zz = 0.0f;
  85. float minv = 0.0f;
  86. float maxv = 2.0f;
  87. if (_originBottomLeft)
  88. {
  89. float temp = minv;
  90. minv = maxv;
  91. maxv = temp;
  92. minv -= 1.0f;
  93. maxv -= 1.0f;
  94. }
  95. vertex[0].m_x = minx;
  96. vertex[0].m_y = miny;
  97. vertex[0].m_z = zz;
  98. vertex[0].m_u = minu;
  99. vertex[0].m_v = minv;
  100. vertex[1].m_x = maxx;
  101. vertex[1].m_y = miny;
  102. vertex[1].m_z = zz;
  103. vertex[1].m_u = maxu;
  104. vertex[1].m_v = minv;
  105. vertex[2].m_x = maxx;
  106. vertex[2].m_y = maxy;
  107. vertex[2].m_z = zz;
  108. vertex[2].m_u = maxu;
  109. vertex[2].m_v = maxv;
  110. bgfx::setVertexBuffer(0, &vb);
  111. }
  112. }
  113. struct Settings
  114. {
  115. float m_radius; // [0.0, ~ ] World (view) space size of the occlusion sphere.
  116. float m_shadowMultiplier; // [0.0, 5.0] Effect strength linear multiplier
  117. float m_shadowPower; // [0.5, 5.0] Effect strength pow modifier
  118. float m_shadowClamp; // [0.0, 1.0] Effect max limit (applied after multiplier but before blur)
  119. float m_horizonAngleThreshold; // [0.0, 0.2] Limits self-shadowing (makes the sampling area less of a hemisphere, more of a spherical cone, to avoid self-shadowing and various artifacts due to low tessellation and depth buffer imprecision, etc.)
  120. float m_fadeOutFrom; // [0.0, ~ ] Distance to start start fading out the effect.
  121. float m_fadeOutTo; // [0.0, ~ ] Distance at which the effect is faded out.
  122. int32_t m_qualityLevel; // [ -1, 3 ] Effect quality; -1 - lowest (low, half res checkerboard), 0 - low, 1 - medium, 2 - high, 3 - very high / adaptive; each quality level is roughly 2x more costly than the previous, except the q3 which is variable but, in general, above q2.
  123. float m_adaptiveQualityLimit; // [0.0, 1.0] (only for Quality Level 3)
  124. int32_t m_blurPassCount; // [ 0, 6] Number of edge-sensitive smart blur passes to apply. Quality 0 is an exception with only one 'dumb' blur pass used.
  125. float m_sharpness; // [0.0, 1.0] (How much to bleed over edges; 1: not at all, 0.5: half-half; 0.0: completely ignore edges)
  126. float m_temporalSupersamplingAngleOffset; // [0.0, PI] Used to rotate sampling kernel; If using temporal AA / supersampling, suggested to rotate by ( (frame%3)/3.0*PI ) or similar. Kernel is already symmetrical, which is why we use PI and not 2*PI.
  127. float m_temporalSupersamplingRadiusOffset; // [0.0, 2.0] Used to scale sampling kernel; If using temporal AA / supersampling, suggested to scale by ( 1.0f + (((frame%3)-1.0)/3.0)*0.1 ) or similar.
  128. float m_detailShadowStrength; // [0.0, 5.0] Used for high-res detail AO using neighboring depth pixels: adds a lot of detail but also reduces temporal stability (adds aliasing).
  129. bool m_generateNormals; // [true/false] If true normals will be generated from depth.
  130. Settings()
  131. {
  132. m_radius = 1.2f;
  133. m_shadowMultiplier = 1.0f;
  134. m_shadowPower = 1.50f;
  135. m_shadowClamp = 0.98f;
  136. m_horizonAngleThreshold = 0.06f;
  137. m_fadeOutFrom = 50.0f;
  138. m_fadeOutTo = 200.0f;
  139. m_adaptiveQualityLimit = 0.45f;
  140. m_qualityLevel = 3;
  141. m_blurPassCount = 2;
  142. m_sharpness = 0.98f;
  143. m_temporalSupersamplingAngleOffset = 0.0f;
  144. m_temporalSupersamplingRadiusOffset = 1.0f;
  145. m_detailShadowStrength = 0.5f;
  146. m_generateNormals = true;
  147. }
  148. };
  149. struct Uniforms
  150. {
  151. enum { NumVec4 = 19 };
  152. void init()
  153. {
  154. u_params = bgfx::createUniform("u_params", bgfx::UniformType::Vec4, NumVec4);
  155. }
  156. void submit()
  157. {
  158. bgfx::setUniform(u_params, m_params, NumVec4);
  159. }
  160. void destroy()
  161. {
  162. bgfx::destroy(u_params);
  163. }
  164. union
  165. {
  166. struct
  167. {
  168. /* 0 */ struct { float m_viewportPixelSize[2]; float m_halfViewportPixelSize[2]; };
  169. /* 1 */ struct { float m_depthUnpackConsts[2]; float m_unused0[2]; };
  170. /* 2 */ struct { float m_ndcToViewMul[2]; float m_ndcToViewAdd[2]; };
  171. /* 3 */ struct { float m_perPassFullResCoordOffset[2]; float m_perPassFullResUVOffset[2]; };
  172. /* 4 */ struct { float m_viewport2xPixelSize[2]; float m_viewport2xPixelSize_x_025[2]; };
  173. /* 5 */ struct { float m_effectRadius; float m_effectShadowStrength; float m_effectShadowPow; float m_effectShadowClamp; };
  174. /* 6 */ struct { float m_effectFadeOutMul; float m_effectFadeOutAdd; float m_effectHorizonAngleThreshold; float m_effectSamplingRadiusNearLimitRec; };
  175. /* 7 */ struct { float m_depthPrecisionOffsetMod; float m_negRecEffectRadius; float m_loadCounterAvgDiv; float m_adaptiveSampleCountLimit; };
  176. /* 8 */ struct { float m_invSharpness; float m_passIndex; float m_quarterResPixelSize[2]; };
  177. /* 9-13 */ struct { float m_patternRotScaleMatrices[5][4]; };
  178. /* 14 */ struct { float m_normalsUnpackMul; float m_normalsUnpackAdd; float m_detailAOStrength; float m_layer; };
  179. /* 15-18 */ struct { float m_normalsWorldToViewspaceMatrix[16]; };
  180. };
  181. float m_params[NumVec4 * 4];
  182. };
  183. bgfx::UniformHandle u_params;
  184. };
  185. void vec2Set(float* _v, float _x, float _y)
  186. {
  187. _v[0] = _x;
  188. _v[1] = _y;
  189. }
  190. void vec4Set(float* _v, float _x, float _y, float _z, float _w)
  191. {
  192. _v[0] = _x;
  193. _v[1] = _y;
  194. _v[2] = _z;
  195. _v[3] = _w;
  196. }
  197. void vec4iSet(int32_t* _v, int32_t _x, int32_t _y, int32_t _z, int32_t _w)
  198. {
  199. _v[0] = _x;
  200. _v[1] = _y;
  201. _v[2] = _z;
  202. _v[3] = _w;
  203. }
  204. static const int32_t cMaxBlurPassCount = 6;
  205. class ExampleASSAO : public entry::AppI
  206. {
  207. public:
  208. ExampleASSAO(const char* _name, const char* _description, const char* _url)
  209. : entry::AppI(_name, _description, _url)
  210. , m_currFrame(UINT32_MAX)
  211. , m_enableSSAO(true)
  212. , m_enableTexturing(true)
  213. , m_framebufferGutter(true)
  214. {
  215. }
  216. void init(int32_t _argc, const char* const* _argv, uint32_t _width, uint32_t _height) override
  217. {
  218. Args args(_argc, _argv);
  219. m_width = _width;
  220. m_height = _height;
  221. m_debug = BGFX_DEBUG_NONE;
  222. m_reset = BGFX_RESET_VSYNC;
  223. bgfx::Init init;
  224. init.type = args.m_type;
  225. init.vendorId = args.m_pciId;
  226. init.platformData.nwh = entry::getNativeWindowHandle(entry::kDefaultWindowHandle);
  227. init.platformData.ndt = entry::getNativeDisplayHandle();
  228. init.platformData.type = entry::getNativeWindowHandleType();
  229. init.resolution.width = m_width;
  230. init.resolution.height = m_height;
  231. init.resolution.reset = m_reset;
  232. bgfx::init(init);
  233. // Enable debug text.
  234. bgfx::setDebug(m_debug);
  235. // Labeling for renderdoc captures, etc
  236. bgfx::setViewName(RENDER_PASS_GBUFFER, "gbuffer");
  237. bgfx::setViewName(RENDER_PASS_COMBINE, "post combine");
  238. // Set up screen clears
  239. bgfx::setViewClear(RENDER_PASS_GBUFFER
  240. , BGFX_CLEAR_COLOR | BGFX_CLEAR_DEPTH
  241. , 0
  242. , 1.0f
  243. , 0
  244. );
  245. // Create uniforms
  246. u_combineParams = bgfx::createUniform("u_combineParams", bgfx::UniformType::Vec4, 2);
  247. u_rect = bgfx::createUniform("u_rect", bgfx::UniformType::Vec4); // viewport/scissor rect for compute
  248. m_uniforms.init();
  249. // Create texture sampler uniforms (used when we bind textures)
  250. s_normal = bgfx::createUniform("s_normal", bgfx::UniformType::Sampler); // Normal gbuffer
  251. s_depth = bgfx::createUniform("s_depth", bgfx::UniformType::Sampler); // Normal gbuffer
  252. s_color = bgfx::createUniform("s_color", bgfx::UniformType::Sampler); // Color (albedo) gbuffer
  253. s_albedo = bgfx::createUniform("s_albedo", bgfx::UniformType::Sampler);
  254. s_ao = bgfx::createUniform("s_ao", bgfx::UniformType::Sampler);
  255. s_blurInput = bgfx::createUniform("s_blurInput", bgfx::UniformType::Sampler);
  256. s_finalSSAO = bgfx::createUniform("s_finalSSAO", bgfx::UniformType::Sampler);
  257. s_depthSource = bgfx::createUniform("s_depthSource", bgfx::UniformType::Sampler);
  258. s_viewspaceDepthSource = bgfx::createUniform("s_viewspaceDepthSource", bgfx::UniformType::Sampler);
  259. s_viewspaceDepthSourceMirror = bgfx::createUniform("s_viewspaceDepthSourceMirror", bgfx::UniformType::Sampler);
  260. s_importanceMap = bgfx::createUniform("s_importanceMap", bgfx::UniformType::Sampler);
  261. // Create program from shaders.
  262. m_gbufferProgram = loadProgram("vs_assao_gbuffer", "fs_assao_gbuffer"); // Gbuffer
  263. m_combineProgram = loadProgram("vs_assao", "fs_assao_deferred_combine");
  264. m_prepareDepthsProgram = loadProgram("cs_assao_prepare_depths", NULL);
  265. m_prepareDepthsAndNormalsProgram = loadProgram("cs_assao_prepare_depths_and_normals", NULL);
  266. m_prepareDepthsHalfProgram = loadProgram("cs_assao_prepare_depths_half", NULL);
  267. m_prepareDepthsAndNormalsHalfProgram = loadProgram("cs_assao_prepare_depths_and_normals_half", NULL);
  268. m_prepareDepthMipProgram = loadProgram("cs_assao_prepare_depth_mip", NULL);
  269. m_generateQ0Program = loadProgram("cs_assao_generate_q0", NULL);
  270. m_generateQ1Program = loadProgram("cs_assao_generate_q1", NULL);
  271. m_generateQ2Program = loadProgram("cs_assao_generate_q2", NULL);
  272. m_generateQ3Program = loadProgram("cs_assao_generate_q3", NULL);
  273. m_generateQ3BaseProgram = loadProgram("cs_assao_generate_q3base", NULL);
  274. m_smartBlurProgram = loadProgram("cs_assao_smart_blur", NULL);
  275. m_smartBlurWideProgram = loadProgram("cs_assao_smart_blur_wide", NULL);
  276. m_nonSmartBlurProgram = loadProgram("cs_assao_non_smart_blur", NULL);
  277. m_applyProgram = loadProgram("cs_assao_apply", NULL);
  278. m_nonSmartApplyProgram = loadProgram("cs_assao_non_smart_apply", NULL);
  279. m_nonSmartHalfApplyProgram = loadProgram("cs_assao_non_smart_half_apply", NULL);
  280. m_generateImportanceMapProgram = loadProgram("cs_assao_generate_importance_map", NULL);
  281. m_postprocessImportanceMapAProgram = loadProgram("cs_assao_postprocess_importance_map_a", NULL);
  282. m_postprocessImportanceMapBProgram = loadProgram("cs_assao_postprocess_importance_map_b", NULL);
  283. m_loadCounterClearProgram = loadProgram("cs_assao_load_counter_clear", NULL);
  284. // Load some meshes
  285. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  286. {
  287. m_meshes[ii] = meshLoad(s_meshPaths[ii]);
  288. }
  289. // Randomly create some models
  290. bx::RngMwc mwc; // Random number generator
  291. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  292. {
  293. Model& model = m_models[ii];
  294. model.mesh = 1 + mwc.gen() % (BX_COUNTOF(s_meshPaths) - 1);
  295. model.position[0] = (((mwc.gen() % 256)) - 128.0f) / 20.0f;
  296. model.position[1] = 0;
  297. model.position[2] = (((mwc.gen() % 256)) - 128.0f) / 20.0f;
  298. }
  299. // Load ground. We'll just use the cube since I don't have a ground model right now
  300. m_ground = meshLoad("meshes/cube.bin");
  301. m_groundTexture = loadTexture("textures/fieldstone-rgba.dds");
  302. const bgfx::Memory* mem = bgfx::alloc(4);
  303. bx::memSet(mem->data, 0xc0, 4);
  304. m_modelTexture = bgfx::createTexture2D(1,1, false, 1, bgfx::TextureFormat::RGBA8, 0, mem);
  305. m_recreateFrameBuffers = false;
  306. createFramebuffers();
  307. m_loadCounter = bgfx::createDynamicIndexBuffer(1, BGFX_BUFFER_COMPUTE_READ_WRITE | BGFX_BUFFER_INDEX32);
  308. // Vertex layout
  309. PosTexCoord0Vertex::init();
  310. // Init camera
  311. cameraCreate();
  312. cameraSetPosition({ 0.0f, 1.5f, 0.0f });
  313. cameraSetVerticalAngle(-0.3f);
  314. m_fovY = 60.0f;
  315. imguiCreate();
  316. m_frameTime.reset();
  317. }
  318. int32_t shutdown() override
  319. {
  320. for (uint32_t ii = 0; ii < BX_COUNTOF(s_meshPaths); ++ii)
  321. {
  322. meshUnload(m_meshes[ii]);
  323. }
  324. meshUnload(m_ground);
  325. bgfx::destroy(m_groundTexture);
  326. bgfx::destroy(m_modelTexture);
  327. // Cleanup.
  328. bgfx::destroy(m_gbufferProgram);
  329. bgfx::destroy(m_combineProgram);
  330. bgfx::destroy(m_prepareDepthsProgram);
  331. bgfx::destroy(m_prepareDepthsAndNormalsProgram);
  332. bgfx::destroy(m_prepareDepthsHalfProgram);
  333. bgfx::destroy(m_prepareDepthsAndNormalsHalfProgram);
  334. bgfx::destroy(m_prepareDepthMipProgram);
  335. bgfx::destroy(m_generateQ0Program);
  336. bgfx::destroy(m_generateQ1Program);
  337. bgfx::destroy(m_generateQ2Program);
  338. bgfx::destroy(m_generateQ3Program);
  339. bgfx::destroy(m_generateQ3BaseProgram);
  340. bgfx::destroy(m_smartBlurProgram);
  341. bgfx::destroy(m_smartBlurWideProgram);
  342. bgfx::destroy(m_nonSmartBlurProgram);
  343. bgfx::destroy(m_applyProgram);
  344. bgfx::destroy(m_nonSmartApplyProgram);
  345. bgfx::destroy(m_nonSmartHalfApplyProgram);
  346. bgfx::destroy(m_generateImportanceMapProgram);
  347. bgfx::destroy(m_postprocessImportanceMapAProgram);
  348. bgfx::destroy(m_postprocessImportanceMapBProgram);
  349. bgfx::destroy(m_loadCounterClearProgram);
  350. bgfx::destroy(m_combineProgram);
  351. m_uniforms.destroy();
  352. bgfx::destroy(u_combineParams);
  353. bgfx::destroy(u_rect);
  354. bgfx::destroy(s_normal);
  355. bgfx::destroy(s_depth);
  356. bgfx::destroy(s_color);
  357. bgfx::destroy(s_albedo);
  358. bgfx::destroy(s_ao);
  359. bgfx::destroy(s_blurInput);
  360. bgfx::destroy(s_finalSSAO);
  361. bgfx::destroy(s_depthSource);
  362. bgfx::destroy(s_viewspaceDepthSource);
  363. bgfx::destroy(s_viewspaceDepthSourceMirror);
  364. bgfx::destroy(s_importanceMap);
  365. bgfx::destroy(m_loadCounter);
  366. destroyFramebuffers();
  367. cameraDestroy();
  368. imguiDestroy();
  369. // Shutdown bgfx.
  370. bgfx::shutdown();
  371. return 0;
  372. }
  373. bool update() override
  374. {
  375. if (!entry::processEvents(m_width, m_height, m_debug, m_reset, &m_mouseState))
  376. {
  377. m_frameTime.frame();
  378. const float deltaTime = bx::toSeconds<float>(m_frameTime.getDeltaTime() );
  379. const bgfx::Caps* caps = bgfx::getCaps();
  380. if (m_size[0] != (int32_t)m_width + 2*m_border
  381. || m_size[1] != (int32_t)m_height + 2*m_border
  382. || m_recreateFrameBuffers)
  383. {
  384. destroyFramebuffers();
  385. createFramebuffers();
  386. m_recreateFrameBuffers = false;
  387. }
  388. // Update camera
  389. cameraUpdate(deltaTime*0.15f, m_mouseState, ImGui::MouseOverArea() );
  390. // Set up matrices for gbuffer
  391. cameraGetViewMtx(m_view);
  392. bx::mtxProj(m_proj, m_fovY, float(m_size[0]) / float(m_size[1]), 0.1f, 100.0f, bgfx::getCaps()->homogeneousDepth);
  393. bx::mtxProj(m_proj2, m_fovY, float(m_size[0]) / float(m_size[1]), 0.1f, 100.0f, false);
  394. bgfx::setViewRect(RENDER_PASS_GBUFFER, 0, 0, uint16_t(m_size[0]), uint16_t(m_size[1]));
  395. bgfx::setViewTransform(RENDER_PASS_GBUFFER, m_view, m_proj);
  396. // Make sure when we draw it goes into gbuffer and not backbuffer
  397. bgfx::setViewFrameBuffer(RENDER_PASS_GBUFFER, m_gbuffer);
  398. // Draw everything into g-buffer
  399. drawAllModels(RENDER_PASS_GBUFFER, m_gbufferProgram);
  400. // Set up transform matrix for fullscreen quad
  401. #if USE_ASSAO == 1
  402. float orthoProj[16];
  403. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  404. bgfx::setViewTransform(RENDER_PASS_COMBINE, NULL, orthoProj);
  405. bgfx::setViewRect(RENDER_PASS_COMBINE, 0, 0, uint16_t(m_width), uint16_t(m_height));
  406. // Bind vertex buffer and draw quad
  407. screenSpaceQuad(caps->originBottomLeft);
  408. //bgfx::submit(RENDER_PASS_COMBINE, m_combineProgram);
  409. bgfx::touch(RENDER_PASS_COMBINE);
  410. BX_UNUSED(orthoProj, caps)
  411. #endif
  412. // ASSAO passes
  413. #if USE_ASSAO == 0
  414. updateUniforms(0);
  415. bgfx::ViewId view = 2;
  416. bgfx::setViewName(view, "ASSAO");
  417. {
  418. bgfx::setTexture(0, s_depthSource, bgfx::getTexture(m_gbuffer, GBUFFER_RT_DEPTH), SAMPLER_POINT_CLAMP);
  419. m_uniforms.submit();
  420. if (m_settings.m_generateNormals)
  421. {
  422. bgfx::setImage(5, m_normals, 0, bgfx::Access::Write, bgfx::TextureFormat::RGBA8);
  423. }
  424. if (m_settings.m_qualityLevel < 0)
  425. {
  426. for (int32_t j = 0; j < 2; ++j)
  427. {
  428. bgfx::setImage((uint8_t)(j + 1), m_halfDepths[j == 0 ? 0 : 3], 0, bgfx::Access::Write, bgfx::TextureFormat::R16F);
  429. }
  430. bgfx::dispatch(view, m_settings.m_generateNormals ? m_prepareDepthsAndNormalsHalfProgram : m_prepareDepthsHalfProgram, (m_halfSize[0] + 7) / 8, (m_halfSize[1] + 7) / 8);
  431. }
  432. else
  433. {
  434. for(int32_t j = 0; j < 4; ++j)
  435. {
  436. bgfx::setImage((uint8_t)(j+1), m_halfDepths[j], 0, bgfx::Access::Write, bgfx::TextureFormat::R16F);
  437. }
  438. bgfx::dispatch(view, m_settings.m_generateNormals ? m_prepareDepthsAndNormalsProgram : m_prepareDepthsProgram, (m_halfSize[0] + 7) / 8, (m_halfSize[1] + 7) / 8);
  439. }
  440. }
  441. // only do mipmaps for higher quality levels (not beneficial on quality level 1, and detrimental on quality level 0)
  442. if (m_settings.m_qualityLevel > 1)
  443. {
  444. uint16_t mipWidth = (uint16_t)m_halfSize[0];
  445. uint16_t mipHeight = (uint16_t)m_halfSize[1];
  446. for (uint8_t i = 1; i < SSAO_DEPTH_MIP_LEVELS; i++)
  447. {
  448. mipWidth = (uint16_t)bx::max(1, mipWidth >> 1);
  449. mipHeight = (uint16_t)bx::max(1, mipHeight >> 1);
  450. for (uint8_t j = 0; j < 4; ++j)
  451. {
  452. bgfx::setImage(j, m_halfDepths[j], i-1, bgfx::Access::Read, bgfx::TextureFormat::R16F);
  453. bgfx::setImage(j + 4, m_halfDepths[j], i, bgfx::Access::Write, bgfx::TextureFormat::R16F);
  454. }
  455. m_uniforms.submit();
  456. float rect[4] = { 0.0f, 0.0f, (float)mipWidth, (float)mipHeight };
  457. bgfx::setUniform(u_rect, rect);
  458. bgfx::dispatch(view, m_prepareDepthMipProgram, (mipWidth + 7) / 8, (mipHeight + 7) / 8);
  459. }
  460. }
  461. // for adaptive quality, importance map pass
  462. for (int32_t ssaoPass = 0; ssaoPass < 2; ++ssaoPass)
  463. {
  464. if (ssaoPass == 0
  465. && m_settings.m_qualityLevel < 3)
  466. {
  467. continue;
  468. }
  469. bool adaptiveBasePass = (ssaoPass == 0);
  470. BX_UNUSED(adaptiveBasePass);
  471. int32_t passCount = 4;
  472. int32_t halfResNumX = (m_halfResOutScissorRect[2] - m_halfResOutScissorRect[0] + 7) / 8;
  473. int32_t halfResNumY = (m_halfResOutScissorRect[3] - m_halfResOutScissorRect[1] + 7) / 8;
  474. float halfResRect[4] = { (float)m_halfResOutScissorRect[0], (float)m_halfResOutScissorRect[1], (float)m_halfResOutScissorRect[2], (float)m_halfResOutScissorRect[3] };
  475. for (int32_t pass = 0; pass < passCount; pass++)
  476. {
  477. if (m_settings.m_qualityLevel < 0
  478. && (pass == 1 || pass == 2) )
  479. {
  480. continue;
  481. }
  482. int32_t blurPasses = m_settings.m_blurPassCount;
  483. blurPasses = bx::min(blurPasses, cMaxBlurPassCount);
  484. if (m_settings.m_qualityLevel == 3)
  485. {
  486. // if adaptive, at least one blur pass needed as the first pass needs to read the final texture results - kind of awkward
  487. if (adaptiveBasePass)
  488. {
  489. blurPasses = 0;
  490. }
  491. else
  492. {
  493. blurPasses = bx::max(1, blurPasses);
  494. }
  495. }
  496. else if (m_settings.m_qualityLevel <= 0)
  497. {
  498. // just one blur pass allowed for minimum quality
  499. blurPasses = bx::min(1, m_settings.m_blurPassCount);
  500. }
  501. updateUniforms(pass);
  502. bgfx::TextureHandle pPingRT = m_pingPongHalfResultA;
  503. bgfx::TextureHandle pPongRT = m_pingPongHalfResultB;
  504. // Generate
  505. {
  506. bgfx::setImage(6, blurPasses == 0 ? m_finalResults : pPingRT, 0, bgfx::Access::Write, bgfx::TextureFormat::RG8);
  507. bgfx::setUniform(u_rect, halfResRect);
  508. bgfx::setTexture(0, s_viewspaceDepthSource, m_halfDepths[pass], SAMPLER_POINT_CLAMP);
  509. bgfx::setTexture(1, s_viewspaceDepthSourceMirror, m_halfDepths[pass], SAMPLER_POINT_MIRROR);
  510. if (m_settings.m_generateNormals)
  511. bgfx::setImage(2, m_normals,0, bgfx::Access::Read, bgfx::TextureFormat::RGBA8);
  512. else
  513. bgfx::setImage(2, bgfx::getTexture(m_gbuffer, GBUFFER_RT_NORMAL), 0, bgfx::Access::Read, bgfx::TextureFormat::RGBA8);
  514. if (!adaptiveBasePass && (m_settings.m_qualityLevel == 3))
  515. {
  516. bgfx::setBuffer(3, m_loadCounter, bgfx::Access::Read);
  517. bgfx::setTexture(4, s_importanceMap, m_importanceMap, SAMPLER_LINEAR_CLAMP);
  518. bgfx::setImage(5, m_finalResults, 0, bgfx::Access::Read, bgfx::TextureFormat::RG8);
  519. }
  520. bgfx::ProgramHandle programs[5] = { m_generateQ0Program, m_generateQ1Program , m_generateQ2Program , m_generateQ3Program , m_generateQ3BaseProgram };
  521. int32_t programIndex = bx::max(0, (!adaptiveBasePass) ? (m_settings.m_qualityLevel) : (4));
  522. m_uniforms.m_layer = blurPasses == 0 ? (float)pass : 0.0f;
  523. m_uniforms.submit();
  524. bgfx::dispatch(view, programs[programIndex], halfResNumX, halfResNumY);
  525. }
  526. // Blur
  527. if (blurPasses > 0)
  528. {
  529. int32_t wideBlursRemaining = bx::max(0, blurPasses - 2);
  530. for (int32_t i = 0; i < blurPasses; i++)
  531. {
  532. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  533. bgfx::touch(view);
  534. m_uniforms.m_layer = ((i == (blurPasses - 1)) ? (float)pass : 0.0f);
  535. m_uniforms.submit();
  536. bgfx::setUniform(u_rect, halfResRect);
  537. bgfx::setImage(0, i == (blurPasses - 1) ? m_finalResults : pPongRT, 0, bgfx::Access::Write, bgfx::TextureFormat::RG8);
  538. bgfx::setTexture(1, s_blurInput, pPingRT, m_settings.m_qualityLevel > 0 ? SAMPLER_POINT_MIRROR : SAMPLER_LINEAR_CLAMP);
  539. if (m_settings.m_qualityLevel > 0)
  540. {
  541. if (wideBlursRemaining > 0)
  542. {
  543. bgfx::dispatch(view, m_smartBlurWideProgram, halfResNumX, halfResNumY);
  544. wideBlursRemaining--;
  545. }
  546. else
  547. {
  548. bgfx::dispatch(view, m_smartBlurProgram, halfResNumX, halfResNumY);
  549. }
  550. }
  551. else
  552. {
  553. bgfx::dispatch(view, m_nonSmartBlurProgram, halfResNumX, halfResNumY); // just for quality level 0 (and -1)
  554. }
  555. bgfx::TextureHandle temp = pPingRT;
  556. pPingRT = pPongRT;
  557. pPongRT = temp;
  558. }
  559. }
  560. }
  561. if (ssaoPass == 0 && m_settings.m_qualityLevel == 3)
  562. { // Generate importance map
  563. m_uniforms.submit();
  564. bgfx::setImage(0, m_importanceMap, 0, bgfx::Access::Write, bgfx::TextureFormat::R8);
  565. bgfx::setTexture(1, s_finalSSAO, m_finalResults, SAMPLER_POINT_CLAMP);
  566. bgfx::dispatch(view, m_generateImportanceMapProgram, (m_quarterSize[0] + 7) / 8, (m_quarterSize[1] + 7) / 8);
  567. m_uniforms.submit();
  568. bgfx::setImage(0, m_importanceMapPong, 0, bgfx::Access::Write, bgfx::TextureFormat::R8);
  569. bgfx::setTexture(1, s_importanceMap, m_importanceMap);
  570. bgfx::dispatch(view, m_postprocessImportanceMapAProgram, (m_quarterSize[0] + 7) / 8, (m_quarterSize[1] + 7) / 8);
  571. bgfx::setBuffer(0, m_loadCounter, bgfx::Access::ReadWrite);
  572. bgfx::dispatch(view, m_loadCounterClearProgram, 1,1);
  573. m_uniforms.submit();
  574. bgfx::setImage(0, m_importanceMap, 0, bgfx::Access::Write, bgfx::TextureFormat::R8);
  575. bgfx::setTexture(1, s_importanceMap, m_importanceMapPong);
  576. bgfx::setBuffer(2, m_loadCounter, bgfx::Access::ReadWrite);
  577. bgfx::dispatch(view, m_postprocessImportanceMapBProgram, (m_quarterSize[0]+7) / 8, (m_quarterSize[1]+7) / 8);
  578. ++view;
  579. }
  580. }
  581. // Apply
  582. {
  583. // select 4 deinterleaved AO textures (texture array)
  584. bgfx::setImage(0, m_aoMap, 0, bgfx::Access::Write, bgfx::TextureFormat::R8);
  585. bgfx::setTexture(1, s_finalSSAO, m_finalResults);
  586. m_uniforms.submit();
  587. float rect[4] = {(float)m_fullResOutScissorRect[0], (float)m_fullResOutScissorRect[1], (float)m_fullResOutScissorRect[2], (float)m_fullResOutScissorRect[3] };
  588. bgfx::setUniform(u_rect, rect);
  589. bgfx::ProgramHandle program;
  590. if (m_settings.m_qualityLevel < 0)
  591. program = m_nonSmartHalfApplyProgram;
  592. else if (m_settings.m_qualityLevel == 0)
  593. program = m_nonSmartApplyProgram;
  594. else
  595. program = m_applyProgram;
  596. bgfx::dispatch(view, program, (m_fullResOutScissorRect[2]- m_fullResOutScissorRect[0] + 7) / 8,
  597. (m_fullResOutScissorRect[3] - m_fullResOutScissorRect[1] + 7) / 8);
  598. ++view;
  599. }
  600. { // combine
  601. bgfx::setViewFrameBuffer(view, BGFX_INVALID_HANDLE);
  602. bgfx::setViewName(view, "Combine");
  603. bgfx::setViewRect(view, 0, 0, (uint16_t)m_width, (uint16_t)m_height);
  604. float orthoProj[16];
  605. bx::mtxOrtho(orthoProj, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, caps->homogeneousDepth);
  606. bgfx::setViewTransform(view, NULL, orthoProj);
  607. bgfx::setTexture(0, s_color, bgfx::getTexture(m_gbuffer, GBUFFER_RT_COLOR), SAMPLER_POINT_CLAMP);
  608. bgfx::setTexture(1, s_normal, bgfx::getTexture(m_gbuffer, GBUFFER_RT_NORMAL), SAMPLER_POINT_CLAMP);
  609. bgfx::setTexture(2, s_ao, m_aoMap, SAMPLER_POINT_CLAMP);
  610. m_uniforms.submit();
  611. float combineParams[8] = { m_enableTexturing ? 1.0f : 0.0f, m_enableSSAO ? 1.0f : 0.0f, 0.0f,0.0f,
  612. (float)(m_size[0]-2*m_border) / (float)m_size[0], (float)(m_size[1] - 2 * m_border) / (float)m_size[1],
  613. (float)m_border / (float)m_size[0], (float)m_border / (float)m_size[1] };
  614. bgfx::setUniform(u_combineParams, combineParams, 2);
  615. screenSpaceQuad(caps->originBottomLeft);
  616. bgfx::setState(BGFX_STATE_WRITE_RGB | BGFX_STATE_WRITE_A | BGFX_STATE_DEPTH_TEST_ALWAYS);
  617. bgfx::submit(view, m_combineProgram);
  618. ++view;
  619. }
  620. #endif
  621. // Draw UI
  622. imguiBeginFrame(m_mouseState.m_mx
  623. , m_mouseState.m_my
  624. , (m_mouseState.m_buttons[entry::MouseButton::Left] ? IMGUI_MBUT_LEFT : 0)
  625. | (m_mouseState.m_buttons[entry::MouseButton::Right] ? IMGUI_MBUT_RIGHT : 0)
  626. | (m_mouseState.m_buttons[entry::MouseButton::Middle] ? IMGUI_MBUT_MIDDLE : 0)
  627. , m_mouseState.m_mz
  628. , uint16_t(m_width)
  629. , uint16_t(m_height)
  630. );
  631. showExampleDialog(this);
  632. ImGui::SetNextWindowPos(
  633. ImVec2(m_width - m_width / 4.0f - 10.0f, 10.0f)
  634. , ImGuiCond_FirstUseEver
  635. );
  636. ImGui::SetNextWindowSize(
  637. ImVec2(m_width / 4.0f, m_height / 1.3f)
  638. , ImGuiCond_FirstUseEver
  639. );
  640. ImGui::Begin("Settings"
  641. , NULL
  642. , 0
  643. );
  644. ImGui::PushItemWidth(ImGui::GetWindowWidth() * 0.5f);
  645. ImGui::Checkbox("Enable SSAO", &m_enableSSAO);
  646. ImGui::Checkbox("Enable Texturing & Lighting", &m_enableTexturing);
  647. ImGui::Separator();
  648. int32_t quality = m_settings.m_qualityLevel + 1;
  649. if (ImGui::Combo("Quality Level", &quality, "Lowest (Half Resolution)\0Low\0Medium\0High\0Adaptive\0\0"))
  650. {
  651. m_settings.m_qualityLevel = quality - 1;
  652. }
  653. ImGui::Checkbox("Generate Normals", &m_settings.m_generateNormals);
  654. if (ImGui::Checkbox("Framebuffer Gutter", &m_framebufferGutter))
  655. {
  656. m_recreateFrameBuffers = true;
  657. }
  658. ImGui::SliderFloat("Effect Radius", &m_settings.m_radius, 0.0f, 4.0f);
  659. ImGui::SliderFloat("Effect Strength", &m_settings.m_shadowMultiplier, 0.0f, 5.0f);
  660. ImGui::SliderFloat("Effect Power", &m_settings.m_shadowPower, 0.5f, 4.0f);
  661. ImGui::SliderFloat("Effect Max Limit", &m_settings.m_shadowClamp, 0.0f, 1.0f);
  662. ImGui::SliderFloat("Horizon Angle Threshold", &m_settings.m_horizonAngleThreshold, 0.0f, 0.2f);
  663. ImGui::SliderFloat("Fade Out From", &m_settings.m_fadeOutFrom, 0.0f, 100.0f);
  664. ImGui::SliderFloat("Fade Out To", &m_settings.m_fadeOutTo, 0.0f, 300.0f);
  665. if (m_settings.m_qualityLevel == 3)
  666. {
  667. ImGui::SliderFloat("Adaptive Quality Limit", &m_settings.m_adaptiveQualityLimit, 0.0f, 1.0f);
  668. }
  669. ImGui::SliderInt("Blur Pass Count", &m_settings.m_blurPassCount, 0, 6);
  670. ImGui::SliderFloat("Sharpness", &m_settings.m_sharpness, 0.0f, 1.0f);
  671. ImGui::SliderFloat("Temporal Supersampling Angle Offset", &m_settings.m_temporalSupersamplingAngleOffset, 0.0f, bx::kPi);
  672. ImGui::SliderFloat("Temporal Supersampling Radius Offset", &m_settings.m_temporalSupersamplingRadiusOffset, 0.0f, 2.0f);
  673. ImGui::SliderFloat("Detail Shadow Strength", &m_settings.m_detailShadowStrength, 0.0f, 4.0f);
  674. ImGui::End();
  675. imguiEndFrame();
  676. // Advance to next frame. Rendering thread will be kicked to
  677. // process submitted rendering primitives.
  678. m_currFrame = bgfx::frame();
  679. return true;
  680. }
  681. return false;
  682. }
  683. void drawAllModels(uint8_t _pass, bgfx::ProgramHandle _program)
  684. {
  685. for (uint32_t ii = 0; ii < BX_COUNTOF(m_models); ++ii)
  686. {
  687. const Model& model = m_models[ii];
  688. // Set up transform matrix for each model
  689. float scale = s_meshScale[model.mesh];
  690. float mtx[16];
  691. bx::mtxSRT(mtx
  692. , scale
  693. , scale
  694. , scale
  695. , 0.0f
  696. , 0.0f
  697. , 0.0f
  698. , model.position[0]
  699. , model.position[1]
  700. , model.position[2]
  701. );
  702. // Submit mesh to gbuffer
  703. bgfx::setTexture(0, s_albedo, m_modelTexture);
  704. meshSubmit(m_meshes[model.mesh], _pass, _program, mtx);
  705. }
  706. // Draw ground
  707. float mtxScale[16];
  708. const float scale = 10.0f;
  709. bx::mtxScale(mtxScale, scale, scale, scale);
  710. float mtxTrans[16];
  711. bx::mtxTranslate(mtxTrans
  712. , 0.0f
  713. , -10.0f
  714. , 0.0f
  715. );
  716. float mtx[16];
  717. bx::mtxMul(mtx, mtxScale, mtxTrans);
  718. bgfx::setTexture(0, s_albedo, m_groundTexture);
  719. meshSubmit(m_ground, _pass, _program, mtx);
  720. }
  721. void createFramebuffers()
  722. {
  723. // update resolution and camera FOV if there's border expansion
  724. const int32_t drawResolutionBorderExpansionFactor = 12; // will be expanded by Height / expansionFactor
  725. const float fovY = 60.0f;
  726. m_border = 0;
  727. if (m_framebufferGutter)
  728. {
  729. m_border = (bx::min(m_width, m_height) / drawResolutionBorderExpansionFactor) / 2 * 2;
  730. int32_t expandedSceneResolutionY = m_height + m_border * 2;
  731. float yScaleDueToBorder = (expandedSceneResolutionY * 0.5f) / (float)(m_height * 0.5f);
  732. float nonExpandedTan = bx::tan(bx::toRad(fovY / 2.0f));
  733. m_fovY = bx::toDeg(bx::atan(nonExpandedTan * yScaleDueToBorder) * 2.0f);
  734. }
  735. else
  736. {
  737. m_fovY = fovY;
  738. }
  739. m_size[0] = m_width + 2 * m_border;
  740. m_size[1] = m_height + 2 * m_border;
  741. m_halfSize[0] = (m_size[0] + 1) / 2;
  742. m_halfSize[1] = (m_size[1] + 1) / 2;
  743. m_quarterSize[0] = (m_halfSize[0] + 1) / 2;
  744. m_quarterSize[1] = (m_halfSize[1] + 1) / 2;
  745. vec4iSet(m_fullResOutScissorRect, m_border, m_border, m_width + m_border, m_height + m_border);
  746. vec4iSet(m_halfResOutScissorRect, m_fullResOutScissorRect[0] / 2, m_fullResOutScissorRect[1] / 2, (m_fullResOutScissorRect[2] + 1) / 2, (m_fullResOutScissorRect[3] + 1) / 2);
  747. int32_t blurEnlarge = cMaxBlurPassCount + bx::max(0, cMaxBlurPassCount - 2); // +1 for max normal blurs, +2 for wide blurs
  748. vec4iSet(m_halfResOutScissorRect, bx::max(0, m_halfResOutScissorRect[0] - blurEnlarge), bx::max(0, m_halfResOutScissorRect[1] - blurEnlarge),
  749. bx::min(m_halfSize[0], m_halfResOutScissorRect[2] + blurEnlarge), bx::min(m_halfSize[1], m_halfResOutScissorRect[3] + blurEnlarge));
  750. // Make gbuffer and related textures
  751. const uint64_t tsFlags = 0
  752. | BGFX_TEXTURE_RT
  753. | BGFX_SAMPLER_MIN_POINT
  754. | BGFX_SAMPLER_MAG_POINT
  755. | BGFX_SAMPLER_MIP_POINT
  756. | BGFX_SAMPLER_U_CLAMP
  757. | BGFX_SAMPLER_V_CLAMP
  758. ;
  759. bgfx::TextureHandle gbufferTex[3];
  760. gbufferTex[GBUFFER_RT_NORMAL] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, tsFlags);
  761. gbufferTex[GBUFFER_RT_COLOR] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::BGRA8, tsFlags);
  762. gbufferTex[GBUFFER_RT_DEPTH] = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::D32F, tsFlags);
  763. m_gbuffer = bgfx::createFrameBuffer(BX_COUNTOF(gbufferTex), gbufferTex, true);
  764. for (int32_t i = 0; i < 4; i++)
  765. {
  766. m_halfDepths[i] = bgfx::createTexture2D(uint16_t(m_halfSize[0]), uint16_t(m_halfSize[1]), true, 1, bgfx::TextureFormat::R16F, BGFX_TEXTURE_COMPUTE_WRITE | SAMPLER_POINT_CLAMP);
  767. }
  768. m_pingPongHalfResultA = bgfx::createTexture2D(uint16_t(m_halfSize[0]), uint16_t(m_halfSize[1]), false, 2, bgfx::TextureFormat::RG8, BGFX_TEXTURE_COMPUTE_WRITE);
  769. m_pingPongHalfResultB = bgfx::createTexture2D(uint16_t(m_halfSize[0]), uint16_t(m_halfSize[1]), false, 2, bgfx::TextureFormat::RG8, BGFX_TEXTURE_COMPUTE_WRITE);
  770. m_finalResults = bgfx::createTexture2D(uint16_t(m_halfSize[0]), uint16_t(m_halfSize[1]), false, 4, bgfx::TextureFormat::RG8, BGFX_TEXTURE_COMPUTE_WRITE | SAMPLER_LINEAR_CLAMP);
  771. m_normals = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::RGBA8, BGFX_TEXTURE_COMPUTE_WRITE);
  772. m_importanceMap = bgfx::createTexture2D(uint16_t(m_quarterSize[0]), uint16_t(m_quarterSize[1]), false, 1, bgfx::TextureFormat::R8, BGFX_TEXTURE_COMPUTE_WRITE | SAMPLER_LINEAR_CLAMP);
  773. m_importanceMapPong = bgfx::createTexture2D(uint16_t(m_quarterSize[0]), uint16_t(m_quarterSize[1]), false, 1, bgfx::TextureFormat::R8, BGFX_TEXTURE_COMPUTE_WRITE | SAMPLER_LINEAR_CLAMP);
  774. m_aoMap = bgfx::createTexture2D(uint16_t(m_size[0]), uint16_t(m_size[1]), false, 1, bgfx::TextureFormat::R8, BGFX_TEXTURE_COMPUTE_WRITE | SAMPLER_POINT_CLAMP);
  775. }
  776. void destroyFramebuffers()
  777. {
  778. bgfx::destroy(m_gbuffer);
  779. for (uint32_t ii = 0; ii < BX_COUNTOF(m_halfDepths); ++ii)
  780. {
  781. bgfx::destroy(m_halfDepths[ii]);
  782. }
  783. bgfx::destroy(m_pingPongHalfResultA);
  784. bgfx::destroy(m_pingPongHalfResultB);
  785. bgfx::destroy(m_finalResults);
  786. bgfx::destroy(m_normals);
  787. bgfx::destroy(m_aoMap);
  788. bgfx::destroy(m_importanceMap);
  789. bgfx::destroy(m_importanceMapPong);
  790. }
  791. void updateUniforms(int32_t _pass)
  792. {
  793. vec2Set(m_uniforms.m_viewportPixelSize, 1.0f / (float)m_size[0], 1.0f / (float)m_size[1]);
  794. vec2Set(m_uniforms.m_halfViewportPixelSize, 1.0f / (float)m_halfSize[0], 1.0f / (float)m_halfSize[1]);
  795. vec2Set(m_uniforms.m_viewport2xPixelSize, m_uniforms.m_viewportPixelSize[0] * 2.0f, m_uniforms.m_viewportPixelSize[1] * 2.0f);
  796. vec2Set(m_uniforms.m_viewport2xPixelSize_x_025, m_uniforms.m_viewport2xPixelSize[0] * 0.25f, m_uniforms.m_viewport2xPixelSize[1] * 0.25f);
  797. float depthLinearizeMul = -m_proj2[3*4+2]; // float depthLinearizeMul = ( clipFar * clipNear ) / ( clipFar - clipNear );
  798. float depthLinearizeAdd = m_proj2[2*4+2]; // float depthLinearizeAdd = clipFar / ( clipFar - clipNear );
  799. // correct the handedness issue. need to make sure this below is correct, but I think it is.
  800. if (depthLinearizeMul * depthLinearizeAdd < 0)
  801. {
  802. depthLinearizeAdd = -depthLinearizeAdd;
  803. }
  804. vec2Set(m_uniforms.m_depthUnpackConsts, depthLinearizeMul, depthLinearizeAdd);
  805. float tanHalfFOVY = 1.0f / m_proj2[1*4+1]; // = tanf( drawContext.Camera.GetYFOV( ) * 0.5f );
  806. float tanHalfFOVX = 1.0F / m_proj2[0]; // = tanHalfFOVY * drawContext.Camera.GetAspect( );
  807. if (bgfx::getRendererType() == bgfx::RendererType::OpenGL)
  808. {
  809. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * 2.0f);
  810. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * -1.0f);
  811. }
  812. else
  813. {
  814. vec2Set(m_uniforms.m_ndcToViewMul, tanHalfFOVX * 2.0f, tanHalfFOVY * -2.0f);
  815. vec2Set(m_uniforms.m_ndcToViewAdd, tanHalfFOVX * -1.0f, tanHalfFOVY * 1.0f);
  816. }
  817. m_uniforms.m_effectRadius = bx::clamp(m_settings.m_radius, 0.0f, 100000.0f);
  818. m_uniforms.m_effectShadowStrength = bx::clamp(m_settings.m_shadowMultiplier * 4.3f, 0.0f, 10.0f);
  819. m_uniforms.m_effectShadowPow = bx::clamp(m_settings.m_shadowPower, 0.0f, 10.0f);
  820. m_uniforms.m_effectShadowClamp = bx::clamp(m_settings.m_shadowClamp, 0.0f, 1.0f);
  821. m_uniforms.m_effectFadeOutMul = -1.0f / (m_settings.m_fadeOutTo - m_settings.m_fadeOutFrom);
  822. m_uniforms.m_effectFadeOutAdd = m_settings.m_fadeOutFrom / (m_settings.m_fadeOutTo - m_settings.m_fadeOutFrom) + 1.0f;
  823. m_uniforms.m_effectHorizonAngleThreshold = bx::clamp(m_settings.m_horizonAngleThreshold, 0.0f, 1.0f);
  824. // 1.2 seems to be around the best trade off - 1.0 means on-screen radius will stop/slow growing when the camera is at 1.0 distance, so, depending on FOV, basically filling up most of the screen
  825. // This setting is viewspace-dependent and not screen size dependent intentionally, so that when you change FOV the effect stays (relatively) similar.
  826. float effectSamplingRadiusNearLimit = (m_settings.m_radius * 1.2f);
  827. // if the depth precision is switched to 32bit float, this can be set to something closer to 1 (0.9999 is fine)
  828. m_uniforms.m_depthPrecisionOffsetMod = 0.9992f;
  829. // used to get average load per pixel; 9.0 is there to compensate for only doing every 9th InterlockedAdd in PSPostprocessImportanceMapB for performance reasons
  830. m_uniforms.m_loadCounterAvgDiv = 9.0f / (float)(m_quarterSize[0] * m_quarterSize[1] * 255.0);
  831. // Special settings for lowest quality level - just nerf the effect a tiny bit
  832. if (m_settings.m_qualityLevel <= 0)
  833. {
  834. effectSamplingRadiusNearLimit *= 1.50f;
  835. if (m_settings.m_qualityLevel < 0)
  836. {
  837. m_uniforms.m_effectRadius *= 0.8f;
  838. }
  839. }
  840. effectSamplingRadiusNearLimit /= tanHalfFOVY; // to keep the effect same regardless of FOV
  841. m_uniforms.m_effectSamplingRadiusNearLimitRec = 1.0f / effectSamplingRadiusNearLimit;
  842. m_uniforms.m_adaptiveSampleCountLimit = m_settings.m_adaptiveQualityLimit;
  843. m_uniforms.m_negRecEffectRadius = -1.0f / m_uniforms.m_effectRadius;
  844. if (bgfx::getCaps()->originBottomLeft)
  845. {
  846. vec2Set(m_uniforms.m_perPassFullResCoordOffset, (float)(_pass % 2), 1.0f-(float)(_pass / 2));
  847. vec2Set(m_uniforms.m_perPassFullResUVOffset, ((_pass % 2) - 0.0f) / m_size[0], (1.0f-((_pass / 2) - 0.0f)) / m_size[1]);
  848. }
  849. else
  850. {
  851. vec2Set(m_uniforms.m_perPassFullResCoordOffset, (float)(_pass % 2), (float)(_pass / 2));
  852. vec2Set(m_uniforms.m_perPassFullResUVOffset, ((_pass % 2) - 0.0f) / m_size[0], ((_pass / 2) - 0.0f) / m_size[1]);
  853. }
  854. m_uniforms.m_invSharpness = bx::clamp(1.0f - m_settings.m_sharpness, 0.0f, 1.0f);
  855. m_uniforms.m_passIndex = (float)_pass;
  856. vec2Set(m_uniforms.m_quarterResPixelSize, 1.0f / (float)m_quarterSize[0], 1.0f / (float)m_quarterSize[1]);
  857. float additionalAngleOffset = m_settings.m_temporalSupersamplingAngleOffset; // if using temporal supersampling approach (like "Progressive Rendering Using Multi-frame Sampling" from GPU Pro 7, etc.)
  858. float additionalRadiusScale = m_settings.m_temporalSupersamplingRadiusOffset; // if using temporal supersampling approach (like "Progressive Rendering Using Multi-frame Sampling" from GPU Pro 7, etc.)
  859. const int32_t subPassCount = 5;
  860. for (int32_t subPass = 0; subPass < subPassCount; subPass++)
  861. {
  862. int32_t a = _pass;
  863. int32_t b = subPass;
  864. int32_t spmap[5]{ 0, 1, 4, 3, 2 };
  865. b = spmap[subPass];
  866. float ca, sa;
  867. float angle0 = ((float)a + (float)b / (float)subPassCount) * (3.1415926535897932384626433832795f) * 0.5f;
  868. angle0 += additionalAngleOffset;
  869. ca = bx::cos(angle0);
  870. sa = bx::sin(angle0);
  871. float scale = 1.0f + (a - 1.5f + (b - (subPassCount - 1.0f) * 0.5f) / (float)subPassCount) * 0.07f;
  872. scale *= additionalRadiusScale;
  873. vec4Set(m_uniforms.m_patternRotScaleMatrices[subPass], scale * ca, scale * -sa, -scale * sa, -scale * ca);
  874. }
  875. m_uniforms.m_normalsUnpackMul = 2.0f;
  876. m_uniforms.m_normalsUnpackAdd = -1.0f;
  877. m_uniforms.m_detailAOStrength = m_settings.m_detailShadowStrength;
  878. if (m_settings.m_generateNormals)
  879. {
  880. bx::mtxIdentity(m_uniforms.m_normalsWorldToViewspaceMatrix);
  881. }
  882. else
  883. {
  884. bx::mtxTranspose(m_uniforms.m_normalsWorldToViewspaceMatrix, m_view);
  885. }
  886. }
  887. uint32_t m_width;
  888. uint32_t m_height;
  889. uint32_t m_debug;
  890. uint32_t m_reset;
  891. entry::MouseState m_mouseState;
  892. Uniforms m_uniforms;
  893. // Resource handles
  894. bgfx::ProgramHandle m_gbufferProgram;
  895. bgfx::ProgramHandle m_combineProgram;
  896. bgfx::ProgramHandle m_prepareDepthsProgram;
  897. bgfx::ProgramHandle m_prepareDepthsAndNormalsProgram;
  898. bgfx::ProgramHandle m_prepareDepthsHalfProgram;
  899. bgfx::ProgramHandle m_prepareDepthsAndNormalsHalfProgram;
  900. bgfx::ProgramHandle m_prepareDepthMipProgram;
  901. bgfx::ProgramHandle m_generateQ0Program;
  902. bgfx::ProgramHandle m_generateQ1Program;
  903. bgfx::ProgramHandle m_generateQ2Program;
  904. bgfx::ProgramHandle m_generateQ3Program;
  905. bgfx::ProgramHandle m_generateQ3BaseProgram;
  906. bgfx::ProgramHandle m_smartBlurProgram;
  907. bgfx::ProgramHandle m_smartBlurWideProgram;
  908. bgfx::ProgramHandle m_nonSmartBlurProgram;
  909. bgfx::ProgramHandle m_applyProgram;
  910. bgfx::ProgramHandle m_nonSmartApplyProgram;
  911. bgfx::ProgramHandle m_nonSmartHalfApplyProgram;
  912. bgfx::ProgramHandle m_generateImportanceMapProgram;
  913. bgfx::ProgramHandle m_postprocessImportanceMapAProgram;
  914. bgfx::ProgramHandle m_postprocessImportanceMapBProgram;
  915. bgfx::ProgramHandle m_loadCounterClearProgram;
  916. bgfx::FrameBufferHandle m_gbuffer;
  917. // Shader uniforms
  918. bgfx::UniformHandle u_rect;
  919. bgfx::UniformHandle u_combineParams;
  920. // Uniforms to identify texture samples
  921. bgfx::UniformHandle s_normal;
  922. bgfx::UniformHandle s_depth;
  923. bgfx::UniformHandle s_color;
  924. bgfx::UniformHandle s_albedo;
  925. bgfx::UniformHandle s_ao;
  926. bgfx::UniformHandle s_blurInput;
  927. bgfx::UniformHandle s_finalSSAO;
  928. bgfx::UniformHandle s_depthSource;
  929. bgfx::UniformHandle s_viewspaceDepthSource;
  930. bgfx::UniformHandle s_viewspaceDepthSourceMirror;
  931. bgfx::UniformHandle s_importanceMap;
  932. // Various render targets
  933. bgfx::TextureHandle m_halfDepths[4];
  934. bgfx::TextureHandle m_pingPongHalfResultA;
  935. bgfx::TextureHandle m_pingPongHalfResultB;
  936. bgfx::TextureHandle m_finalResults;
  937. bgfx::TextureHandle m_aoMap;
  938. bgfx::TextureHandle m_normals;
  939. // Only needed for quality level 3 (adaptive quality)
  940. bgfx::TextureHandle m_importanceMap;
  941. bgfx::TextureHandle m_importanceMapPong;
  942. bgfx::DynamicIndexBufferHandle m_loadCounter;
  943. struct Model
  944. {
  945. uint32_t mesh; // Index of mesh in m_meshes
  946. float position[3];
  947. };
  948. Model m_models[MODEL_COUNT];
  949. Mesh* m_meshes[BX_COUNTOF(s_meshPaths)];
  950. Mesh* m_ground;
  951. bgfx::TextureHandle m_groundTexture;
  952. bgfx::TextureHandle m_modelTexture;
  953. uint32_t m_currFrame;
  954. // UI
  955. Settings m_settings;
  956. bool m_enableSSAO;
  957. bool m_enableTexturing;
  958. float m_fovY;
  959. bool m_framebufferGutter;
  960. bool m_recreateFrameBuffers;
  961. float m_view[16];
  962. float m_proj[16];
  963. float m_proj2[16];
  964. int32_t m_size[2];
  965. int32_t m_halfSize[2];
  966. int32_t m_quarterSize[2];
  967. int32_t m_fullResOutScissorRect[4];
  968. int32_t m_halfResOutScissorRect[4];
  969. int32_t m_border;
  970. FrameTime m_frameTime;
  971. };
  972. } // namespace
  973. ENTRY_IMPLEMENT_MAIN(
  974. ExampleASSAO
  975. , "39-assao"
  976. , "Adaptive Screen Space Ambient Occlusion."
  977. , "https://bkaradzic.github.io/bgfx/examples.html#assao"
  978. );