HzbGenerator.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. // Copyright (C) 2009-present, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #include <AnKi/Renderer/Utils/HzbGenerator.h>
  6. #include <AnKi/Renderer/Renderer.h>
  7. #include <AnKi/Util/Tracer.h>
  8. #if ANKI_COMPILER_GCC_COMPATIBLE
  9. # pragma GCC diagnostic push
  10. # pragma GCC diagnostic ignored "-Wunused-function"
  11. # pragma GCC diagnostic ignored "-Wignored-qualifiers"
  12. #elif ANKI_COMPILER_MSVC
  13. # pragma warning(push)
  14. # pragma warning(disable : 4505)
  15. #endif
  16. #define A_CPU
  17. #include <ThirdParty/FidelityFX/ffx_a.h>
  18. #include <ThirdParty/FidelityFX/ffx_spd.h>
  19. #if ANKI_COMPILER_GCC_COMPATIBLE
  20. # pragma GCC diagnostic pop
  21. #elif ANKI_COMPILER_MSVC
  22. # pragma warning(pop)
  23. #endif
  24. namespace anki {
  25. // 7 +----+ 6
  26. // /| /|
  27. // 3 +----+2|
  28. // | *--| + 5
  29. // |/4 |/
  30. // 0 +----+ 1
  31. static constexpr U16 kBoxIndices[] = {1, 2, 5, 2, 6, 5, 0, 4, 3, 4, 7, 3, 3, 7, 2, 7, 6, 2, 0, 1, 4, 1, 5, 4, 0, 3, 1, 3, 2, 1, 4, 5, 7, 5, 6, 7};
  32. Error HzbGenerator::init()
  33. {
  34. {
  35. SamplerInitInfo sinit("HzbReductionMax");
  36. sinit.m_addressing = SamplingAddressing::kClamp;
  37. sinit.m_mipmapFilter = SamplingFilter::kMax;
  38. sinit.m_minMagFilter = SamplingFilter::kMax;
  39. m_maxSampler = GrManager::getSingleton().newSampler(sinit);
  40. }
  41. ANKI_CHECK(loadShaderProgram("ShaderBinaries/HzbGenPyramid.ankiprogbin", {{"REDUCTION_TYPE", 1}, {"MIN_MAX_SAMPLER", m_maxSampler.isCreated()}},
  42. m_genPyramidProg, m_genPyramidGrProg));
  43. ANKI_CHECK(loadShaderProgram("ShaderBinaries/HzbMaxDepth.ankiprogbin", m_maxDepthProg, m_maxDepthGrProg));
  44. ANKI_CHECK(loadShaderProgram("ShaderBinaries/HzbMaxDepthProject.ankiprogbin", m_maxBoxProg, m_maxBoxGrProg));
  45. if(GrManager::getSingleton().getDeviceCapabilities().m_structuredBufferNaturalAlignment)
  46. {
  47. m_counterBufferElementSize = sizeof(U32);
  48. }
  49. else
  50. {
  51. m_counterBufferElementSize = max<U32>(sizeof(U32), GrManager::getSingleton().getDeviceCapabilities().m_structuredBufferBindOffsetAlignment);
  52. }
  53. BufferInitInfo buffInit("HzbCounterBuffer");
  54. buffInit.m_size = m_counterBufferElementSize * kCounterBufferElementCount;
  55. buffInit.m_usage = BufferUsageBit::kUavCompute | BufferUsageBit::kCopyDestination;
  56. m_counterBuffer = GrManager::getSingleton().newBuffer(buffInit);
  57. // Zero counter buffer
  58. zeroBuffer(m_counterBuffer.get());
  59. // Boxes buffer
  60. buffInit = BufferInitInfo("HzbBoxIndices");
  61. buffInit.m_size = sizeof(kBoxIndices);
  62. buffInit.m_usage = BufferUsageBit::kVertexOrIndex;
  63. buffInit.m_mapAccess = BufferMapAccessBit::kWrite;
  64. m_boxIndexBuffer = GrManager::getSingleton().newBuffer(buffInit);
  65. void* mappedMem = m_boxIndexBuffer->map(0, kMaxPtrSize, BufferMapAccessBit::kWrite);
  66. memcpy(mappedMem, kBoxIndices, sizeof(kBoxIndices));
  67. m_boxIndexBuffer->unmap();
  68. return Error::kNone;
  69. }
  70. void HzbGenerator::populateRenderGraphInternal(ConstWeakArray<DispatchInput> dispatchInputs, CString customName, RenderGraphBuilder& rgraph)
  71. {
  72. const U32 dispatchCount = dispatchInputs.getSize();
  73. if(m_crntFrame != getRenderer().getFrameCount())
  74. {
  75. m_crntFrame = getRenderer().getFrameCount();
  76. m_counterBufferCrntElementCount = 0;
  77. }
  78. const U32 counterBufferElement = m_counterBufferCrntElementCount;
  79. m_counterBufferCrntElementCount += dispatchCount;
  80. ANKI_ASSERT(counterBufferElement < kCounterBufferElementCount);
  81. NonGraphicsRenderPass& pass = rgraph.newNonGraphicsRenderPass((customName.isEmpty()) ? "HZB generation" : customName);
  82. Array<DispatchInput, kMaxShadowCascades> dispatchInputsCopy;
  83. for(U32 i = 0; i < dispatchCount; ++i)
  84. {
  85. const TextureSubresourceDesc firstMipSubresource = TextureSubresourceDesc::firstSurface(DepthStencilAspectBit::kDepth);
  86. pass.newTextureDependency(dispatchInputs[i].m_srcDepthRt, TextureUsageBit::kSrvCompute, firstMipSubresource);
  87. pass.newTextureDependency(dispatchInputs[i].m_dstHzbRt, TextureUsageBit::kUavCompute);
  88. dispatchInputsCopy[i] = dispatchInputs[i];
  89. }
  90. pass.setWork([this, dispatchInputsCopy, dispatchCount, counterBufferElement](RenderPassWorkContext& rgraphCtx) {
  91. ANKI_TRACE_SCOPED_EVENT(HzbGeneration);
  92. CommandBuffer& cmdb = *rgraphCtx.m_commandBuffer;
  93. cmdb.bindShaderProgram(m_genPyramidGrProg.get());
  94. cmdb.bindSampler(0, 0, m_maxSampler.isCreated() ? m_maxSampler.get() : getRenderer().getSamplers().m_trilinearClamp.get());
  95. for(U32 dispatch = 0; dispatch < dispatchCount; ++dispatch)
  96. {
  97. const DispatchInput& in = dispatchInputsCopy[dispatch];
  98. const U8 hzbMipCount =
  99. min(kMaxMipsSinglePassDownsamplerCanProduce, computeMaxMipmapCount2d(in.m_dstHzbRtSize.x(), in.m_dstHzbRtSize.y()));
  100. const U8 mipsToCompute = hzbMipCount;
  101. varAU2(dispatchThreadGroupCountXY);
  102. varAU2(workGroupOffset); // needed if Left and Top are not 0,0
  103. varAU2(numWorkGroupsAndMips);
  104. varAU4(rectInfo) = initAU4(0, 0, in.m_dstHzbRtSize.x() * 2, in.m_dstHzbRtSize.y() * 2);
  105. SpdSetup(dispatchThreadGroupCountXY, workGroupOffset, numWorkGroupsAndMips, rectInfo, mipsToCompute);
  106. struct Constants
  107. {
  108. Vec2 m_invSrcTexSize;
  109. U32 m_threadGroupCount;
  110. U32 m_mipmapCount;
  111. } pc;
  112. pc.m_invSrcTexSize = 1.0f / Vec2(in.m_dstHzbRtSize * 2);
  113. pc.m_threadGroupCount = numWorkGroupsAndMips[0];
  114. pc.m_mipmapCount = numWorkGroupsAndMips[1];
  115. cmdb.setFastConstants(&pc, sizeof(pc));
  116. for(U8 mip = 0; mip < kMaxMipsSinglePassDownsamplerCanProduce; ++mip)
  117. {
  118. TextureSubresourceDesc subresource = TextureSubresourceDesc::firstSurface();
  119. if(mip < mipsToCompute)
  120. {
  121. subresource.m_mipmap = mip;
  122. }
  123. else
  124. {
  125. subresource.m_mipmap = 0; // Put something random
  126. }
  127. rgraphCtx.bindUav(1 + mip, 0, in.m_dstHzbRt, subresource);
  128. }
  129. cmdb.bindUav(0, 0,
  130. BufferView(m_counterBuffer.get())
  131. .incrementOffset((counterBufferElement + dispatch) * m_counterBufferElementSize)
  132. .setRange(sizeof(U32)));
  133. rgraphCtx.bindSrv(0, 0, in.m_srcDepthRt, TextureSubresourceDesc::firstSurface(DepthStencilAspectBit::kDepth));
  134. cmdb.dispatchCompute(dispatchThreadGroupCountXY[0], dispatchThreadGroupCountXY[1], 1);
  135. }
  136. });
  137. }
  138. void HzbGenerator::populateRenderGraph(RenderTargetHandle srcDepthRt, UVec2 srcDepthRtSize, RenderTargetHandle dstHzbRt, UVec2 dstHzbRtSize,
  139. RenderGraphBuilder& rgraph, CString customName)
  140. {
  141. DispatchInput in;
  142. in.m_dstHzbRt = dstHzbRt;
  143. in.m_dstHzbRtSize = dstHzbRtSize;
  144. in.m_srcDepthRt = srcDepthRt;
  145. in.m_srcDepthRtSize = srcDepthRtSize;
  146. populateRenderGraphInternal({&in, 1}, customName, rgraph);
  147. }
  148. void HzbGenerator::populateRenderGraphDirectionalLight(const HzbDirectionalLightInput& in, RenderGraphBuilder& rgraph)
  149. {
  150. const U32 cascadeCount = in.m_cascadeCount;
  151. ANKI_ASSERT(cascadeCount > 0);
  152. // Generate a temp RT with the max depth of each 64x64 tile of the depth buffer
  153. RenderTargetHandle maxDepthRt;
  154. constexpr U32 kTileSize = 64;
  155. const UVec2 maxDepthRtSize = (in.m_depthBufferRtSize + kTileSize - 1) / kTileSize;
  156. {
  157. RenderTargetDesc maxDepthRtDescr("HZB max tile depth");
  158. maxDepthRtDescr.m_width = maxDepthRtSize.x();
  159. maxDepthRtDescr.m_height = maxDepthRtSize.y();
  160. maxDepthRtDescr.m_format = Format::kR32_Sfloat;
  161. maxDepthRtDescr.bake();
  162. maxDepthRt = rgraph.newRenderTarget(maxDepthRtDescr);
  163. NonGraphicsRenderPass& pass = rgraph.newNonGraphicsRenderPass("HZB max tile depth");
  164. pass.newTextureDependency(in.m_depthBufferRt, TextureUsageBit::kSrvCompute, DepthStencilAspectBit::kDepth);
  165. pass.newTextureDependency(maxDepthRt, TextureUsageBit::kUavCompute);
  166. pass.setWork([this, depthBufferRt = in.m_depthBufferRt, maxDepthRt, maxDepthRtSize](RenderPassWorkContext& rgraphCtx) {
  167. ANKI_TRACE_SCOPED_EVENT(HzbGenerationDepthTile);
  168. CommandBuffer& cmdb = *rgraphCtx.m_commandBuffer;
  169. rgraphCtx.bindSrv(0, 0, depthBufferRt, TextureSubresourceDesc::firstSurface(DepthStencilAspectBit::kDepth));
  170. cmdb.bindSampler(0, 0, getRenderer().getSamplers().m_trilinearClamp.get());
  171. rgraphCtx.bindUav(0, 0, maxDepthRt);
  172. cmdb.bindShaderProgram(m_maxDepthGrProg.get());
  173. cmdb.dispatchCompute(maxDepthRtSize.x(), maxDepthRtSize.y(), 1);
  174. });
  175. }
  176. // Project a box for each tile on each cascade's HZB
  177. Array<RenderTargetHandle, kMaxShadowCascades> depthRts;
  178. for(U32 i = 0; i < cascadeCount; ++i)
  179. {
  180. const HzbDirectionalLightInput::Cascade& cascade = in.m_cascades[i];
  181. // Compute the cascade's min and max depth as seen by the camera
  182. F32 cascadeMinDepth, cascadeMaxDepth;
  183. {
  184. if(i > 0)
  185. {
  186. // Do the reverse of computeShadowCascadeIndex2 to find the actual distance of this cascade. computeShadowCascadeIndex2 makes the min
  187. // distance of a cascade to become even less. See https://www.desmos.com/calculator/g1ibye6ebg
  188. // F = ((x-m)/(M-m))^16 and solving for x we have the new minDist
  189. const F32 m = (i >= 2) ? in.m_cascades[i - 2].m_cascadeMaxDistance : 0.0f; // Prev cascade min dist
  190. const F32 M = in.m_cascades[i - 1].m_cascadeMaxDistance; // Prev cascade max dist
  191. constexpr F32 F = 0.01f; // Desired factor
  192. const F32 minDist = pow(F, 1.0f / 16.0f) * (M - m) + m;
  193. ANKI_ASSERT(minDist < M);
  194. Vec4 v4 = in.m_cameraProjectionMatrix * Vec4(0.0f, 0.0f, -minDist, 1.0f);
  195. cascadeMinDepth = saturate(v4.z() / v4.w());
  196. }
  197. else
  198. {
  199. cascadeMinDepth = 0.0f;
  200. }
  201. const F32 maxDist = cascade.m_cascadeMaxDistance;
  202. const Vec4 v4 = in.m_cameraProjectionMatrix * Vec4(0.0f, 0.0f, -maxDist, 1.0f);
  203. cascadeMaxDepth = saturate(v4.z() / v4.w());
  204. ANKI_ASSERT(cascadeMinDepth <= cascadeMaxDepth);
  205. }
  206. RenderTargetDesc depthRtDescr(generateTempPassName("HZB boxes depth cascade:%u", i));
  207. depthRtDescr.m_width = cascade.m_hzbRtSize.x() * 2;
  208. depthRtDescr.m_height = cascade.m_hzbRtSize.y() * 2;
  209. depthRtDescr.m_format = Format::kD16_Unorm;
  210. depthRtDescr.bake();
  211. depthRts[i] = rgraph.newRenderTarget(depthRtDescr);
  212. GraphicsRenderPass& pass = rgraph.newGraphicsRenderPass("HZB boxes");
  213. GraphicsRenderPassTargetDesc depthRt(depthRts[i]);
  214. depthRt.m_subresource.m_depthStencilAspect = DepthStencilAspectBit::kDepth;
  215. depthRt.m_clearValue.m_depthStencil.m_depth = 0.0f;
  216. depthRt.m_loadOperation = RenderTargetLoadOperation::kClear;
  217. pass.setRenderpassInfo({}, &depthRt);
  218. pass.newTextureDependency(maxDepthRt, TextureUsageBit::kSrvPixel);
  219. pass.newTextureDependency(depthRts[i], TextureUsageBit::kRtvDsvWrite, DepthStencilAspectBit::kDepth);
  220. pass.setWork([this, maxDepthRt, invViewProjMat = in.m_cameraInverseViewProjectionMatrix,
  221. lightViewProjMat = cascade.m_projectionMatrix * Mat4(cascade.m_viewMatrix, Vec4(0.0f, 0.0f, 0.0f, 1.0f)),
  222. viewport = cascade.m_hzbRtSize * 2, maxDepthRtSize, cascadeMinDepth, cascadeMaxDepth](RenderPassWorkContext& rgraphCtx) {
  223. ANKI_TRACE_SCOPED_EVENT(HzbGenerationDirLight);
  224. CommandBuffer& cmdb = *rgraphCtx.m_commandBuffer;
  225. cmdb.setDepthCompareOperation(CompareOperation::kGreater);
  226. cmdb.setViewport(0, 0, viewport.x(), viewport.y());
  227. cmdb.bindShaderProgram(m_maxBoxGrProg.get());
  228. rgraphCtx.bindSrv(0, 0, maxDepthRt);
  229. struct Constants
  230. {
  231. Mat4 m_reprojectionMat;
  232. F32 m_cascadeMinDepth;
  233. F32 m_cascadeMaxDepth;
  234. F32 m_padding0;
  235. F32 m_padding1;
  236. } consts;
  237. consts.m_reprojectionMat = lightViewProjMat * invViewProjMat;
  238. consts.m_cascadeMinDepth = cascadeMinDepth;
  239. consts.m_cascadeMaxDepth = cascadeMaxDepth;
  240. cmdb.setFastConstants(&consts, sizeof(consts));
  241. cmdb.bindIndexBuffer(BufferView(m_boxIndexBuffer.get()), IndexType::kU16);
  242. cmdb.drawIndexed(PrimitiveTopology::kTriangles, sizeof(kBoxIndices) / sizeof(kBoxIndices[0]), maxDepthRtSize.x() * maxDepthRtSize.y());
  243. // Restore state
  244. cmdb.setDepthCompareOperation(CompareOperation::kLess);
  245. });
  246. }
  247. // Generate the HZBs
  248. Array<DispatchInput, kMaxShadowCascades> inputs;
  249. for(U32 i = 0; i < cascadeCount; ++i)
  250. {
  251. const HzbDirectionalLightInput::Cascade& cascade = in.m_cascades[i];
  252. inputs[i].m_dstHzbRt = cascade.m_hzbRt;
  253. inputs[i].m_dstHzbRtSize = cascade.m_hzbRtSize;
  254. inputs[i].m_srcDepthRt = depthRts[i];
  255. inputs[i].m_srcDepthRtSize = cascade.m_hzbRtSize * 2;
  256. }
  257. populateRenderGraphInternal({&inputs[0], cascadeCount}, "HZB generation shadow cascades", rgraph);
  258. }
  259. } // end namespace anki