HzbGenerator.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. // Copyright (C) 2009-2023, 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. #if ANKI_COMPILER_GCC_COMPATIBLE
  8. # pragma GCC diagnostic push
  9. # pragma GCC diagnostic ignored "-Wunused-function"
  10. # pragma GCC diagnostic ignored "-Wignored-qualifiers"
  11. #elif ANKI_COMPILER_MSVC
  12. # pragma warning(push)
  13. # pragma warning(disable : 4505)
  14. #endif
  15. #define A_CPU
  16. #include <ThirdParty/FidelityFX/ffx_a.h>
  17. #include <ThirdParty/FidelityFX/ffx_spd.h>
  18. #if ANKI_COMPILER_GCC_COMPATIBLE
  19. # pragma GCC diagnostic pop
  20. #elif ANKI_COMPILER_MSVC
  21. # pragma warning(pop)
  22. #endif
  23. namespace anki {
  24. // 7 +----+ 6
  25. // /| /|
  26. // 3 +----+2|
  27. // | *--| + 5
  28. // |/4 |/
  29. // 0 +----+ 1
  30. 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};
  31. Error HzbGenerator::init()
  32. {
  33. if(GrManager::getSingleton().getDeviceCapabilities().m_samplingFilterMinMax)
  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. {
  42. ANKI_CHECK(ResourceManager::getSingleton().loadResource("ShaderBinaries/HzbGenPyramid.ankiprogbin", m_genPyramidProg));
  43. ShaderProgramResourceVariantInitInfo variantInit(m_genPyramidProg);
  44. variantInit.addMutation("REDUCTION_TYPE", 1);
  45. variantInit.addMutation("MIN_MAX_SAMPLER", m_maxSampler.isCreated());
  46. const ShaderProgramResourceVariant* variant;
  47. m_genPyramidProg->getOrCreateVariant(variantInit, variant);
  48. m_genPyramidGrProg.reset(&variant->getProgram());
  49. }
  50. ANKI_CHECK(loadShaderProgram("ShaderBinaries/HzbMaxDepth.ankiprogbin", m_maxDepthProg, m_maxDepthGrProg));
  51. ANKI_CHECK(loadShaderProgram("ShaderBinaries/HzbMaxDepthProject.ankiprogbin", m_maxBoxProg, m_maxBoxGrProg));
  52. m_counterBufferElementSize = max<U32>(sizeof(U32), GrManager::getSingleton().getDeviceCapabilities().m_uavBufferBindOffsetAlignment);
  53. BufferInitInfo buffInit("HzbCounterBuffer");
  54. buffInit.m_size = m_counterBufferElementSize * kCounterBufferElementCount;
  55. buffInit.m_usage = BufferUsageBit::kUavComputeWrite | BufferUsageBit::kTransferDestination;
  56. m_counterBuffer = GrManager::getSingleton().newBuffer(buffInit);
  57. // Zero counter buffer
  58. {
  59. CommandBufferInitInfo cmdbInit;
  60. cmdbInit.m_flags |= CommandBufferFlag::kSmallBatch;
  61. CommandBufferPtr cmdb = GrManager::getSingleton().newCommandBuffer(cmdbInit);
  62. cmdb->fillBuffer(m_counterBuffer.get(), 0, kMaxPtrSize, 0);
  63. FencePtr fence;
  64. cmdb->flush({}, &fence);
  65. fence->clientWait(6.0_sec);
  66. }
  67. buffInit = BufferInitInfo("HzbBoxIndices");
  68. buffInit.m_size = sizeof(kBoxIndices);
  69. buffInit.m_usage = BufferUsageBit::kIndex;
  70. buffInit.m_mapAccess = BufferMapAccessBit::kWrite;
  71. m_boxIndexBuffer = GrManager::getSingleton().newBuffer(buffInit);
  72. void* mappedMem = m_boxIndexBuffer->map(0, kMaxPtrSize, BufferMapAccessBit::kWrite);
  73. memcpy(mappedMem, kBoxIndices, sizeof(kBoxIndices));
  74. m_boxIndexBuffer->unmap();
  75. m_fbDescr.m_depthStencilAttachment.m_aspect = DepthStencilAspectBit::kDepth;
  76. m_fbDescr.m_depthStencilAttachment.m_clearValue.m_depthStencil.m_depth = 0.0f;
  77. m_fbDescr.m_depthStencilAttachment.m_loadOperation = AttachmentLoadOperation::kClear;
  78. m_fbDescr.bake();
  79. return Error::kNone;
  80. }
  81. void HzbGenerator::populateRenderGraphInternal(ConstWeakArray<DispatchInput> dispatchInputs, U32 firstCounterBufferElement, CString customName,
  82. RenderGraphDescription& rgraph) const
  83. {
  84. const U32 dispatchCount = dispatchInputs.getSize();
  85. #if ANKI_ASSERTIONS_ENABLED
  86. if(m_crntFrame != getRenderer().getFrameCount())
  87. {
  88. m_crntFrame = getRenderer().getFrameCount();
  89. m_counterBufferElementUseMask = 0;
  90. }
  91. for(U32 i = 0; i < dispatchCount; ++i)
  92. {
  93. ANKI_ASSERT(!(m_counterBufferElementUseMask & (1 << (firstCounterBufferElement + i))));
  94. m_counterBufferElementUseMask |= (1 << (firstCounterBufferElement + i));
  95. }
  96. #endif
  97. ComputeRenderPassDescription& pass = rgraph.newComputeRenderPass((customName.isEmpty()) ? "HZB generation" : customName);
  98. Array<DispatchInput, kMaxShadowCascades> dispatchInputsCopy;
  99. for(U32 i = 0; i < dispatchCount; ++i)
  100. {
  101. TextureSubresourceInfo firstMipSubresource;
  102. pass.newTextureDependency(dispatchInputs[i].m_srcDepthRt, TextureUsageBit::kSampledCompute, firstMipSubresource);
  103. pass.newTextureDependency(dispatchInputs[i].m_dstHzbRt, TextureUsageBit::kUavComputeWrite);
  104. dispatchInputsCopy[i] = dispatchInputs[i];
  105. }
  106. pass.setWork([this, dispatchInputsCopy, dispatchCount, firstCounterBufferElement](RenderPassWorkContext& rgraphCtx) {
  107. CommandBuffer& cmdb = *rgraphCtx.m_commandBuffer;
  108. cmdb.bindShaderProgram(m_genPyramidGrProg.get());
  109. cmdb.bindSampler(0, 3, m_maxSampler.isCreated() ? m_maxSampler.get() : getRenderer().getSamplers().m_trilinearClamp.get());
  110. for(U32 dispatch = 0; dispatch < dispatchCount; ++dispatch)
  111. {
  112. const DispatchInput& in = dispatchInputsCopy[dispatch];
  113. const U32 hzbMipCount =
  114. min(kMaxMipsSinglePassDownsamplerCanProduce, computeMaxMipmapCount2d(in.m_dstHzbRtSize.x(), in.m_dstHzbRtSize.y()));
  115. const U32 mipsToCompute = hzbMipCount;
  116. varAU2(dispatchThreadGroupCountXY);
  117. varAU2(workGroupOffset); // needed if Left and Top are not 0,0
  118. varAU2(numWorkGroupsAndMips);
  119. varAU4(rectInfo) = initAU4(0, 0, in.m_dstHzbRtSize.x() * 2, in.m_dstHzbRtSize.y() * 2);
  120. SpdSetup(dispatchThreadGroupCountXY, workGroupOffset, numWorkGroupsAndMips, rectInfo, mipsToCompute);
  121. struct Constants
  122. {
  123. Vec2 m_invSrcTexSize;
  124. U32 m_threadGroupCount;
  125. U32 m_mipmapCount;
  126. } pc;
  127. pc.m_invSrcTexSize = 1.0f / Vec2(in.m_dstHzbRtSize * 2);
  128. pc.m_threadGroupCount = numWorkGroupsAndMips[0];
  129. pc.m_mipmapCount = numWorkGroupsAndMips[1];
  130. cmdb.setPushConstants(&pc, sizeof(pc));
  131. for(U32 mip = 0; mip < kMaxMipsSinglePassDownsamplerCanProduce; ++mip)
  132. {
  133. TextureSubresourceInfo subresource;
  134. if(mip < mipsToCompute)
  135. {
  136. subresource.m_firstMipmap = mip;
  137. }
  138. else
  139. {
  140. subresource.m_firstMipmap = 0; // Put something random
  141. }
  142. rgraphCtx.bindUavTexture(0, 0, in.m_dstHzbRt, subresource, mip);
  143. }
  144. cmdb.bindUavBuffer(0, 1, m_counterBuffer.get(), (firstCounterBufferElement + dispatch) * m_counterBufferElementSize, sizeof(U32));
  145. rgraphCtx.bindTexture(0, 2, in.m_srcDepthRt, TextureSubresourceInfo(DepthStencilAspectBit::kDepth));
  146. cmdb.dispatchCompute(dispatchThreadGroupCountXY[0], dispatchThreadGroupCountXY[1], 1);
  147. }
  148. });
  149. }
  150. void HzbGenerator::populateRenderGraph(RenderTargetHandle srcDepthRt, UVec2 srcDepthRtSize, RenderTargetHandle dstHzbRt, UVec2 dstHzbRtSize,
  151. RenderGraphDescription& rgraph, CString customName) const
  152. {
  153. DispatchInput in;
  154. in.m_dstHzbRt = dstHzbRt;
  155. in.m_dstHzbRtSize = dstHzbRtSize;
  156. in.m_srcDepthRt = srcDepthRt;
  157. in.m_srcDepthRtSize = srcDepthRtSize;
  158. populateRenderGraphInternal({&in, 1}, 0, customName, rgraph);
  159. }
  160. void HzbGenerator::populateRenderGraphDirectionalLight(const HzbDirectionalLightInput& in, RenderGraphDescription& rgraph) const
  161. {
  162. const U32 cascadeCount = in.m_cascadeCount;
  163. ANKI_ASSERT(cascadeCount > 0);
  164. // Generate a temp RT with the max depth of each 64x64 tile of the depth buffer
  165. RenderTargetHandle maxDepthRt;
  166. constexpr U32 kTileSize = 64;
  167. const UVec2 maxDepthRtSize = (in.m_depthBufferRtSize + kTileSize - 1) / kTileSize;
  168. {
  169. RenderTargetDescription maxDepthRtDescr("HZB max tile depth");
  170. maxDepthRtDescr.m_width = maxDepthRtSize.x();
  171. maxDepthRtDescr.m_height = maxDepthRtSize.y();
  172. maxDepthRtDescr.m_format = Format::kR32_Sfloat;
  173. maxDepthRtDescr.bake();
  174. maxDepthRt = rgraph.newRenderTarget(maxDepthRtDescr);
  175. ComputeRenderPassDescription& pass = rgraph.newComputeRenderPass("HZB max tile depth");
  176. pass.newTextureDependency(in.m_depthBufferRt, TextureUsageBit::kSampledCompute, DepthStencilAspectBit::kDepth);
  177. pass.newTextureDependency(maxDepthRt, TextureUsageBit::kUavComputeWrite);
  178. pass.setWork([this, depthBufferRt = in.m_depthBufferRt, maxDepthRt, maxDepthRtSize](RenderPassWorkContext& rgraphCtx) {
  179. CommandBuffer& cmdb = *rgraphCtx.m_commandBuffer;
  180. rgraphCtx.bindTexture(0, 0, depthBufferRt, TextureSubresourceInfo(DepthStencilAspectBit::kDepth));
  181. cmdb.bindSampler(0, 1, getRenderer().getSamplers().m_trilinearClamp.get());
  182. rgraphCtx.bindUavTexture(0, 2, maxDepthRt);
  183. cmdb.bindShaderProgram(m_maxDepthGrProg.get());
  184. cmdb.dispatchCompute(maxDepthRtSize.x(), maxDepthRtSize.y(), 1);
  185. });
  186. }
  187. // Project a box for each tile on each cascade's HZB
  188. Array<RenderTargetHandle, kMaxShadowCascades> depthRts;
  189. for(U32 i = 0; i < cascadeCount; ++i)
  190. {
  191. const HzbDirectionalLightInput::Cascade& cascade = in.m_cascades[i];
  192. // Compute the cascade's min and max depth as seen by the camera
  193. F32 cascadeMinDepth, cascadeMaxDepth;
  194. {
  195. if(i > 0)
  196. {
  197. // Do the reverse of computeShadowCascadeIndex2 to find the actual distance of this cascade. computeShadowCascadeIndex2 makes the min
  198. // distance of a cascade to become even less. See https://www.desmos.com/calculator/g1ibye6ebg
  199. // F = ((x-m)/(M-m))^16 and solving for x we have the new minDist
  200. const F32 m = (i >= 2) ? in.m_cascades[i - 2].m_cascadeMaxDistance : 0.0f; // Prev cascade min dist
  201. const F32 M = in.m_cascades[i - 1].m_cascadeMaxDistance; // Prev cascade max dist
  202. constexpr F32 F = 0.01f; // Desired factor
  203. const F32 minDist = pow(F, 1.0f / 16.0f) * (M - m) + m;
  204. ANKI_ASSERT(minDist < M);
  205. Vec4 v4 = in.m_cameraProjectionMatrix * Vec4(0.0f, 0.0f, -minDist, 1.0f);
  206. cascadeMinDepth = saturate(v4.z() / v4.w());
  207. }
  208. else
  209. {
  210. cascadeMinDepth = 0.0f;
  211. }
  212. const F32 maxDist = cascade.m_cascadeMaxDistance;
  213. const Vec4 v4 = in.m_cameraProjectionMatrix * Vec4(0.0f, 0.0f, -maxDist, 1.0f);
  214. cascadeMaxDepth = saturate(v4.z() / v4.w());
  215. ANKI_ASSERT(cascadeMinDepth <= cascadeMaxDepth);
  216. }
  217. RenderTargetDescription depthRtDescr("HZB boxes depth");
  218. depthRtDescr.m_width = cascade.m_hzbRtSize.x() * 2;
  219. depthRtDescr.m_height = cascade.m_hzbRtSize.y() * 2;
  220. depthRtDescr.m_format = Format::kD16_Unorm;
  221. depthRtDescr.bake();
  222. depthRts[i] = rgraph.newRenderTarget(depthRtDescr);
  223. GraphicsRenderPassDescription& pass = rgraph.newGraphicsRenderPass("HZB boxes");
  224. pass.setFramebufferInfo(m_fbDescr, {}, depthRts[i]);
  225. pass.newTextureDependency(maxDepthRt, TextureUsageBit::kSampledFragment);
  226. pass.newTextureDependency(depthRts[i], TextureUsageBit::kFramebufferWrite, DepthStencilAspectBit::kDepth);
  227. pass.setWork([this, maxDepthRt, invViewProjMat = in.m_cameraInverseViewProjectionMatrix,
  228. lightViewProjMat = cascade.m_projectionMatrix * Mat4(cascade.m_viewMatrix, Vec4(0.0f, 0.0f, 0.0f, 1.0f)),
  229. viewport = cascade.m_hzbRtSize * 2, maxDepthRtSize, cascadeMinDepth, cascadeMaxDepth](RenderPassWorkContext& rgraphCtx) {
  230. CommandBuffer& cmdb = *rgraphCtx.m_commandBuffer;
  231. cmdb.setDepthCompareOperation(CompareOperation::kGreater);
  232. cmdb.setViewport(0, 0, viewport.x(), viewport.y());
  233. cmdb.bindShaderProgram(m_maxBoxGrProg.get());
  234. rgraphCtx.bindColorTexture(0, 0, maxDepthRt);
  235. struct Constants
  236. {
  237. Mat4 m_reprojectionMat;
  238. F32 m_cascadeMinDepth;
  239. F32 m_cascadeMaxDepth;
  240. F32 m_padding0;
  241. F32 m_padding1;
  242. } unis;
  243. unis.m_reprojectionMat = lightViewProjMat * invViewProjMat;
  244. unis.m_cascadeMinDepth = cascadeMinDepth;
  245. unis.m_cascadeMaxDepth = cascadeMaxDepth;
  246. cmdb.setPushConstants(&unis, sizeof(unis));
  247. cmdb.bindIndexBuffer(m_boxIndexBuffer.get(), 0, IndexType::kU16);
  248. cmdb.drawIndexed(PrimitiveTopology::kTriangles, sizeof(kBoxIndices) / sizeof(kBoxIndices[0]), maxDepthRtSize.x() * maxDepthRtSize.y());
  249. // Restore state
  250. cmdb.setDepthCompareOperation(CompareOperation::kLess);
  251. });
  252. }
  253. // Generate the HZBs
  254. Array<DispatchInput, kMaxShadowCascades> inputs;
  255. for(U32 i = 0; i < cascadeCount; ++i)
  256. {
  257. const HzbDirectionalLightInput::Cascade& cascade = in.m_cascades[i];
  258. inputs[i].m_dstHzbRt = cascade.m_hzbRt;
  259. inputs[i].m_dstHzbRtSize = cascade.m_hzbRtSize;
  260. inputs[i].m_srcDepthRt = depthRts[i];
  261. inputs[i].m_srcDepthRtSize = cascade.m_hzbRtSize * 2;
  262. }
  263. populateRenderGraphInternal({&inputs[0], cascadeCount}, 1, "HZB generation shadow cascades", rgraph);
  264. }
  265. } // end namespace anki