assao.cpp 44 KB

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