ShadowMapping.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878
  1. // Copyright (C) 2009-2022, 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/ShadowMapping.h>
  6. #include <AnKi/Renderer/Renderer.h>
  7. #include <AnKi/Renderer/RenderQueue.h>
  8. #include <AnKi/Core/ConfigSet.h>
  9. #include <AnKi/Util/ThreadHive.h>
  10. #include <AnKi/Util/Tracer.h>
  11. namespace anki {
  12. class ShadowMapping::Scratch::WorkItem
  13. {
  14. public:
  15. UVec4 m_viewport;
  16. RenderQueue* m_renderQueue;
  17. U32 m_firstRenderableElement;
  18. U32 m_renderableElementCount;
  19. U32 m_threadPoolTaskIdx;
  20. U32 m_renderQueueElementsLod;
  21. };
  22. class ShadowMapping::Scratch::LightToRenderToScratchInfo
  23. {
  24. public:
  25. UVec4 m_viewport;
  26. RenderQueue* m_renderQueue;
  27. U32 m_drawcallCount;
  28. U32 m_renderQueueElementsLod;
  29. };
  30. class ShadowMapping::Atlas::ResolveWorkItem
  31. {
  32. public:
  33. Vec4 m_uvInBounds; ///< Bounds used to avoid blurring neighbour tiles.
  34. Vec4 m_uvIn; ///< UV + size that point to the scratch buffer.
  35. UVec4 m_viewportOut; ///< Viewport in the atlas RT.
  36. Bool m_blur;
  37. };
  38. ShadowMapping::~ShadowMapping()
  39. {
  40. }
  41. Error ShadowMapping::init()
  42. {
  43. ANKI_R_LOGV("Initializing shadowmapping")
  44. const Error err = initInternal();
  45. if(err)
  46. {
  47. ANKI_R_LOGE("Failed to initialize shadowmapping");
  48. }
  49. else
  50. {
  51. ANKI_R_LOGV("Shadowmapping initialized. Scratch size %ux%u, atlas size %ux%u",
  52. m_scratch.m_tileCountX * m_scratch.m_tileResolution,
  53. m_scratch.m_tileCountY * m_scratch.m_tileResolution,
  54. m_atlas.m_tileCountBothAxis * m_atlas.m_tileResolution,
  55. m_atlas.m_tileCountBothAxis * m_atlas.m_tileResolution);
  56. }
  57. return err;
  58. }
  59. Error ShadowMapping::initScratch()
  60. {
  61. // Init the shadowmaps and FBs
  62. {
  63. m_scratch.m_tileCountX = getConfig().getRShadowMappingScratchTileCountX();
  64. m_scratch.m_tileCountY = getConfig().getRShadowMappingScratchTileCountY();
  65. m_scratch.m_tileResolution = getConfig().getRShadowMappingTileResolution();
  66. // RT
  67. m_scratch.m_rtDescr = m_r->create2DRenderTargetDescription(m_scratch.m_tileResolution * m_scratch.m_tileCountX,
  68. m_scratch.m_tileResolution * m_scratch.m_tileCountY,
  69. m_r->getDepthNoStencilFormat(), "SM scratch");
  70. m_scratch.m_rtDescr.bake();
  71. // FB
  72. m_scratch.m_fbDescr.m_depthStencilAttachment.m_loadOperation = AttachmentLoadOperation::CLEAR;
  73. m_scratch.m_fbDescr.m_depthStencilAttachment.m_clearValue.m_depthStencil.m_depth = 1.0f;
  74. m_scratch.m_fbDescr.m_depthStencilAttachment.m_aspect = DepthStencilAspectBit::kDepth;
  75. m_scratch.m_fbDescr.bake();
  76. }
  77. m_scratch.m_tileAlloc.init(getAllocator(), m_scratch.m_tileCountX, m_scratch.m_tileCountY, MAX_LOD_COUNT, false);
  78. return Error::NONE;
  79. }
  80. Error ShadowMapping::initAtlas()
  81. {
  82. const Bool preferCompute = getConfig().getRPreferCompute();
  83. // Init RT
  84. {
  85. m_atlas.m_tileResolution = getConfig().getRShadowMappingTileResolution();
  86. m_atlas.m_tileCountBothAxis = getConfig().getRShadowMappingTileCountPerRowOrColumn();
  87. // RT
  88. const Format texFormat = (ANKI_EVSM4) ? Format::kR32G32B32A32_Sfloat : Format::kR32G32_Sfloat;
  89. TextureUsageBit usage = TextureUsageBit::kSampledFragment | TextureUsageBit::kSampledCompute;
  90. usage |= (preferCompute) ? TextureUsageBit::kImageComputeWrite : TextureUsageBit::kAllFramebuffer;
  91. TextureInitInfo texinit = m_r->create2DRenderTargetInitInfo(
  92. m_atlas.m_tileResolution * m_atlas.m_tileCountBothAxis,
  93. m_atlas.m_tileResolution * m_atlas.m_tileCountBothAxis, texFormat, usage, "SM atlas");
  94. ClearValue clearVal;
  95. clearVal.m_colorf[0] = 1.0f;
  96. m_atlas.m_tex = m_r->createAndClearRenderTarget(texinit, TextureUsageBit::kSampledFragment, clearVal);
  97. }
  98. // Tiles
  99. m_atlas.m_tileAlloc.init(getAllocator(), m_atlas.m_tileCountBothAxis, m_atlas.m_tileCountBothAxis, MAX_LOD_COUNT,
  100. true);
  101. // Programs and shaders
  102. {
  103. ANKI_CHECK(getResourceManager().loadResource((preferCompute) ? "ShaderBinaries/EvsmCompute.ankiprogbin"
  104. : "ShaderBinaries/EvsmRaster.ankiprogbin",
  105. m_atlas.m_resolveProg));
  106. ShaderProgramResourceVariantInitInfo variantInitInfo(m_atlas.m_resolveProg);
  107. variantInitInfo.addConstant("INPUT_TEXTURE_SIZE", UVec2(m_scratch.m_tileCountX * m_scratch.m_tileResolution,
  108. m_scratch.m_tileCountY * m_scratch.m_tileResolution));
  109. if(!preferCompute)
  110. {
  111. variantInitInfo.addConstant("FB_SIZE", UVec2(m_atlas.m_tileCountBothAxis * m_atlas.m_tileResolution));
  112. }
  113. const ShaderProgramResourceVariant* variant;
  114. m_atlas.m_resolveProg->getOrCreateVariant(variantInitInfo, variant);
  115. m_atlas.m_resolveGrProg = variant->getProgram();
  116. }
  117. m_atlas.m_fbDescr.m_colorAttachmentCount = 1;
  118. m_atlas.m_fbDescr.m_colorAttachments[0].m_loadOperation = AttachmentLoadOperation::LOAD;
  119. m_atlas.m_fbDescr.bake();
  120. return Error::NONE;
  121. }
  122. Error ShadowMapping::initInternal()
  123. {
  124. ANKI_CHECK(initScratch());
  125. ANKI_CHECK(initAtlas());
  126. return Error::NONE;
  127. }
  128. void ShadowMapping::runAtlas(RenderPassWorkContext& rgraphCtx)
  129. {
  130. ANKI_ASSERT(m_atlas.m_resolveWorkItems.getSize());
  131. ANKI_TRACE_SCOPED_EVENT(R_SM);
  132. CommandBufferPtr& cmdb = rgraphCtx.m_commandBuffer;
  133. // Allocate and populate uniforms
  134. EvsmResolveUniforms* uniforms = allocateAndBindStorage<EvsmResolveUniforms*>(
  135. m_atlas.m_resolveWorkItems.getSize() * sizeof(EvsmResolveUniforms), cmdb, 0, 0);
  136. for(U32 i = 0; i < m_atlas.m_resolveWorkItems.getSize(); ++i)
  137. {
  138. EvsmResolveUniforms& uni = uniforms[i];
  139. const Atlas::ResolveWorkItem& workItem = m_atlas.m_resolveWorkItems[i];
  140. uni.m_viewportXY = IVec2(workItem.m_viewportOut.xy());
  141. uni.m_viewportZW = Vec2(workItem.m_viewportOut.zw());
  142. uni.m_uvScale = workItem.m_uvIn.zw();
  143. uni.m_uvTranslation = workItem.m_uvIn.xy();
  144. uni.m_uvMin = workItem.m_uvInBounds.xy();
  145. uni.m_uvMax = workItem.m_uvInBounds.xy() + workItem.m_uvInBounds.zw();
  146. uni.m_blur = workItem.m_blur;
  147. }
  148. cmdb->bindShaderProgram(m_atlas.m_resolveGrProg);
  149. // Continue
  150. cmdb->bindSampler(0, 1, m_r->getSamplers().m_trilinearClamp);
  151. rgraphCtx.bindTexture(0, 2, m_scratch.m_rt, TextureSubresourceInfo(DepthStencilAspectBit::kDepth));
  152. if(getConfig().getRPreferCompute())
  153. {
  154. rgraphCtx.bindImage(0, 3, m_atlas.m_rt);
  155. constexpr U32 workgroupSize = 8;
  156. ANKI_ASSERT(m_atlas.m_tileResolution >= workgroupSize && (m_atlas.m_tileResolution % workgroupSize) == 0);
  157. cmdb->dispatchCompute(m_atlas.m_tileResolution / workgroupSize, m_atlas.m_tileResolution / workgroupSize,
  158. m_atlas.m_resolveWorkItems.getSize());
  159. }
  160. else
  161. {
  162. cmdb->setViewport(0, 0, m_atlas.m_tex->getWidth(), m_atlas.m_tex->getHeight());
  163. cmdb->drawArrays(PrimitiveTopology::kTriangles, 6, m_atlas.m_resolveWorkItems.getSize());
  164. }
  165. }
  166. void ShadowMapping::runShadowMapping(RenderPassWorkContext& rgraphCtx)
  167. {
  168. ANKI_ASSERT(m_scratch.m_workItems.getSize());
  169. ANKI_TRACE_SCOPED_EVENT(R_SM);
  170. CommandBufferPtr& cmdb = rgraphCtx.m_commandBuffer;
  171. const U threadIdx = rgraphCtx.m_currentSecondLevelCommandBufferIndex;
  172. for(Scratch::WorkItem& work : m_scratch.m_workItems)
  173. {
  174. if(work.m_threadPoolTaskIdx != threadIdx)
  175. {
  176. continue;
  177. }
  178. // Set state
  179. cmdb->setViewport(work.m_viewport[0], work.m_viewport[1], work.m_viewport[2], work.m_viewport[3]);
  180. cmdb->setScissor(work.m_viewport[0], work.m_viewport[1], work.m_viewport[2], work.m_viewport[3]);
  181. RenderableDrawerArguments args;
  182. args.m_viewMatrix = work.m_renderQueue->m_viewMatrix;
  183. args.m_cameraTransform = Mat3x4::getIdentity(); // Don't care
  184. args.m_viewProjectionMatrix = work.m_renderQueue->m_viewProjectionMatrix;
  185. args.m_previousViewProjectionMatrix = Mat4::getIdentity(); // Don't care
  186. args.m_sampler = m_r->getSamplers().m_trilinearRepeatAniso;
  187. args.m_minLod = args.m_maxLod = work.m_renderQueueElementsLod;
  188. m_r->getSceneDrawer().drawRange(RenderingTechnique::SHADOW, args,
  189. work.m_renderQueue->m_renderables.getBegin() + work.m_firstRenderableElement,
  190. work.m_renderQueue->m_renderables.getBegin() + work.m_firstRenderableElement
  191. + work.m_renderableElementCount,
  192. cmdb);
  193. }
  194. }
  195. void ShadowMapping::populateRenderGraph(RenderingContext& ctx)
  196. {
  197. ANKI_TRACE_SCOPED_EVENT(R_SM);
  198. // First process the lights
  199. U32 threadCountForScratchPass = 0;
  200. processLights(ctx, threadCountForScratchPass);
  201. // Build the render graph
  202. RenderGraphDescription& rgraph = ctx.m_renderGraphDescr;
  203. if(m_scratch.m_workItems.getSize())
  204. {
  205. // Will have to create render passes
  206. // Scratch pass
  207. {
  208. // Compute render area
  209. const U32 minx = 0, miny = 0;
  210. const U32 height = m_scratch.m_maxViewportHeight;
  211. const U32 width = m_scratch.m_maxViewportWidth;
  212. GraphicsRenderPassDescription& pass = rgraph.newGraphicsRenderPass("SM scratch");
  213. m_scratch.m_rt = rgraph.newRenderTarget(m_scratch.m_rtDescr);
  214. pass.setFramebufferInfo(m_scratch.m_fbDescr, {}, m_scratch.m_rt, {}, minx, miny, width, height);
  215. ANKI_ASSERT(threadCountForScratchPass
  216. && threadCountForScratchPass <= m_r->getThreadHive().getThreadCount());
  217. pass.setWork(threadCountForScratchPass, [this](RenderPassWorkContext& rgraphCtx) {
  218. runShadowMapping(rgraphCtx);
  219. });
  220. TextureSubresourceInfo subresource = TextureSubresourceInfo(DepthStencilAspectBit::kDepth);
  221. pass.newDependency({m_scratch.m_rt, TextureUsageBit::kAllFramebuffer, subresource});
  222. }
  223. // Atlas pass
  224. {
  225. if(ANKI_LIKELY(m_atlas.m_rtImportedOnce))
  226. {
  227. m_atlas.m_rt = rgraph.importRenderTarget(m_atlas.m_tex);
  228. }
  229. else
  230. {
  231. m_atlas.m_rt = rgraph.importRenderTarget(m_atlas.m_tex, TextureUsageBit::kSampledFragment);
  232. m_atlas.m_rtImportedOnce = true;
  233. }
  234. if(getConfig().getRPreferCompute())
  235. {
  236. ComputeRenderPassDescription& pass = rgraph.newComputeRenderPass("EVSM resolve");
  237. pass.setWork([this](RenderPassWorkContext& rgraphCtx) {
  238. runAtlas(rgraphCtx);
  239. });
  240. pass.newDependency(RenderPassDependency(m_scratch.m_rt, TextureUsageBit::kSampledCompute,
  241. TextureSubresourceInfo(DepthStencilAspectBit::kDepth)));
  242. pass.newDependency(RenderPassDependency(m_atlas.m_rt, TextureUsageBit::kImageComputeWrite));
  243. }
  244. else
  245. {
  246. GraphicsRenderPassDescription& pass = rgraph.newGraphicsRenderPass("EVSM resolve");
  247. pass.setFramebufferInfo(m_atlas.m_fbDescr, {m_atlas.m_rt});
  248. pass.setWork([this](RenderPassWorkContext& rgraphCtx) {
  249. runAtlas(rgraphCtx);
  250. });
  251. pass.newDependency(RenderPassDependency(m_scratch.m_rt, TextureUsageBit::kSampledFragment,
  252. TextureSubresourceInfo(DepthStencilAspectBit::kDepth)));
  253. pass.newDependency(RenderPassDependency(m_atlas.m_rt, TextureUsageBit::kFramebufferRead
  254. | TextureUsageBit::kFramebufferWrite));
  255. }
  256. }
  257. }
  258. else
  259. {
  260. // No need for shadowmapping passes, just import the atlas
  261. if(ANKI_LIKELY(m_atlas.m_rtImportedOnce))
  262. {
  263. m_atlas.m_rt = rgraph.importRenderTarget(m_atlas.m_tex);
  264. }
  265. else
  266. {
  267. m_atlas.m_rt = rgraph.importRenderTarget(m_atlas.m_tex, TextureUsageBit::kSampledFragment);
  268. m_atlas.m_rtImportedOnce = true;
  269. }
  270. }
  271. }
  272. Mat4 ShadowMapping::createSpotLightTextureMatrix(const UVec4& viewport) const
  273. {
  274. const F32 atlasSize = F32(m_atlas.m_tileResolution * m_atlas.m_tileCountBothAxis);
  275. #if ANKI_COMPILER_GCC_COMPATIBLE
  276. # pragma GCC diagnostic push
  277. # pragma GCC diagnostic ignored "-Wpedantic" // Because GCC and clang throw an incorrect warning
  278. #endif
  279. const Vec2 uv(F32(viewport[0]) / atlasSize, F32(viewport[1]) / atlasSize);
  280. #if ANKI_COMPILER_GCC_COMPATIBLE
  281. # pragma GCC diagnostic pop
  282. #endif
  283. ANKI_ASSERT(uv >= Vec2(0.0f) && uv <= Vec2(1.0f));
  284. ANKI_ASSERT(viewport[2] == viewport[3]);
  285. const F32 sizeTextureSpace = F32(viewport[2]) / atlasSize;
  286. return Mat4(sizeTextureSpace, 0.0f, 0.0f, uv.x(), 0.0f, sizeTextureSpace, 0.0f, uv.y(), 0.0f, 0.0f, 1.0f, 0.0f,
  287. 0.0f, 0.0f, 0.0f, 1.0f);
  288. }
  289. void ShadowMapping::chooseLod(const Vec4& cameraOrigin, const PointLightQueueElement& light, Bool& blurAtlas,
  290. U32& tileBufferLod, U32& renderQueueElementsLod) const
  291. {
  292. const F32 distFromTheCamera = (cameraOrigin - light.m_worldPosition.xyz0()).getLength() - light.m_radius;
  293. if(distFromTheCamera < getConfig().getLod0MaxDistance())
  294. {
  295. ANKI_ASSERT(m_pointLightsMaxLod == 1);
  296. blurAtlas = true;
  297. tileBufferLod = 1;
  298. renderQueueElementsLod = 0;
  299. }
  300. else
  301. {
  302. blurAtlas = false;
  303. tileBufferLod = 0;
  304. renderQueueElementsLod = MAX_LOD_COUNT - 1;
  305. }
  306. }
  307. void ShadowMapping::chooseLod(const Vec4& cameraOrigin, const SpotLightQueueElement& light, Bool& blurAtlas,
  308. U32& tileBufferLod, U32& renderQueueElementsLod) const
  309. {
  310. // Get some data
  311. const Vec4 coneOrigin = light.m_worldTransform.getTranslationPart().xyz0();
  312. const Vec4 coneDir = -light.m_worldTransform.getZAxis().xyz0();
  313. const F32 coneAngle = light.m_outerAngle;
  314. // Compute the distance from the camera to the light cone
  315. const Vec4 V = cameraOrigin - coneOrigin;
  316. const F32 VlenSq = V.dot(V);
  317. const F32 V1len = V.dot(coneDir);
  318. const F32 distFromTheCamera = cos(coneAngle) * sqrt(VlenSq - V1len * V1len) - V1len * sin(coneAngle);
  319. if(distFromTheCamera < getConfig().getLod0MaxDistance())
  320. {
  321. blurAtlas = true;
  322. tileBufferLod = 2;
  323. renderQueueElementsLod = 0;
  324. }
  325. else if(distFromTheCamera < getConfig().getLod1MaxDistance())
  326. {
  327. blurAtlas = false;
  328. tileBufferLod = 1;
  329. renderQueueElementsLod = MAX_LOD_COUNT - 1;
  330. }
  331. else
  332. {
  333. blurAtlas = false;
  334. tileBufferLod = 0;
  335. renderQueueElementsLod = MAX_LOD_COUNT - 1;
  336. }
  337. }
  338. TileAllocatorResult ShadowMapping::allocateTilesAndScratchTiles(U64 lightUuid, U32 faceCount, const U64* faceTimestamps,
  339. const U32* faceIndices, const U32* drawcallsCount,
  340. const U32* lods, UVec4* atlasTileViewports,
  341. UVec4* scratchTileViewports,
  342. TileAllocatorResult* subResults)
  343. {
  344. ANKI_ASSERT(lightUuid > 0);
  345. ANKI_ASSERT(faceCount > 0);
  346. ANKI_ASSERT(faceTimestamps);
  347. ANKI_ASSERT(faceIndices);
  348. ANKI_ASSERT(drawcallsCount);
  349. ANKI_ASSERT(lods);
  350. TileAllocatorResult res = TileAllocatorResult::ALLOCATION_FAILED;
  351. // Allocate atlas tiles first. They may be cached and that will affect how many scratch tiles we'll need
  352. for(U i = 0; i < faceCount; ++i)
  353. {
  354. Array<U32, 4> tileRanges;
  355. res = m_atlas.m_tileAlloc.allocate(m_r->getGlobalTimestamp(), faceTimestamps[i], lightUuid, faceIndices[i],
  356. drawcallsCount[i], lods[i], tileRanges);
  357. if(res == TileAllocatorResult::ALLOCATION_FAILED)
  358. {
  359. ANKI_R_LOGW("There is not enough space in the shadow atlas for more shadow maps. "
  360. "Increase the r_shadowMappingTileCountPerRowOrColumn or decrease the scene's shadow casters");
  361. // Invalidate cache entries for what we already allocated
  362. for(U j = 0; j < i; ++j)
  363. {
  364. m_atlas.m_tileAlloc.invalidateCache(lightUuid, faceIndices[j]);
  365. }
  366. return res;
  367. }
  368. subResults[i] = res;
  369. // Set viewport
  370. atlasTileViewports[i] = UVec4(tileRanges) * m_atlas.m_tileResolution;
  371. }
  372. // Allocate scratch tiles
  373. for(U i = 0; i < faceCount; ++i)
  374. {
  375. if(subResults[i] == TileAllocatorResult::CACHED)
  376. {
  377. continue;
  378. }
  379. ANKI_ASSERT(subResults[i] == TileAllocatorResult::ALLOCATION_SUCCEEDED);
  380. Array<U32, 4> tileRanges;
  381. res = m_scratch.m_tileAlloc.allocate(m_r->getGlobalTimestamp(), faceTimestamps[i], lightUuid, faceIndices[i],
  382. drawcallsCount[i], lods[i], tileRanges);
  383. if(res == TileAllocatorResult::ALLOCATION_FAILED)
  384. {
  385. ANKI_R_LOGW("Don't have enough space in the scratch shadow mapping buffer. "
  386. "If you see this message too often increase r_shadowMappingScratchTileCountX/Y");
  387. // Invalidate atlas tiles
  388. for(U j = 0; j < faceCount; ++j)
  389. {
  390. m_atlas.m_tileAlloc.invalidateCache(lightUuid, faceIndices[j]);
  391. }
  392. return res;
  393. }
  394. // Fix viewport
  395. scratchTileViewports[i] = UVec4(tileRanges) * m_scratch.m_tileResolution;
  396. // Update the max view width
  397. m_scratch.m_maxViewportWidth =
  398. max(m_scratch.m_maxViewportWidth, scratchTileViewports[i][0] + scratchTileViewports[i][2]);
  399. m_scratch.m_maxViewportHeight =
  400. max(m_scratch.m_maxViewportHeight, scratchTileViewports[i][1] + scratchTileViewports[i][3]);
  401. }
  402. return res;
  403. }
  404. void ShadowMapping::processLights(RenderingContext& ctx, U32& threadCountForScratchPass)
  405. {
  406. // Reset the scratch viewport width
  407. m_scratch.m_maxViewportWidth = 0;
  408. m_scratch.m_maxViewportHeight = 0;
  409. // Vars
  410. const Vec4 cameraOrigin = ctx.m_renderQueue->m_cameraTransform.getTranslationPart().xyz0();
  411. DynamicArrayAuto<Scratch::LightToRenderToScratchInfo> lightsToRender(ctx.m_tempAllocator);
  412. U32 drawcallCount = 0;
  413. DynamicArrayAuto<Atlas::ResolveWorkItem> atlasWorkItems(ctx.m_tempAllocator);
  414. // First thing, allocate an empty tile for empty faces of point lights
  415. UVec4 emptyTileViewport;
  416. {
  417. Array<U32, 4> tileRange;
  418. [[maybe_unused]] const TileAllocatorResult res =
  419. m_atlas.m_tileAlloc.allocate(m_r->getGlobalTimestamp(), 1, MAX_U64, 0, 1, m_pointLightsMaxLod, tileRange);
  420. emptyTileViewport = UVec4(tileRange);
  421. #if ANKI_ENABLE_ASSERTIONS
  422. static Bool firstRun = true;
  423. if(firstRun)
  424. {
  425. ANKI_ASSERT(res == TileAllocatorResult::ALLOCATION_SUCCEEDED);
  426. firstRun = false;
  427. }
  428. else
  429. {
  430. ANKI_ASSERT(res == TileAllocatorResult::CACHED);
  431. }
  432. #endif
  433. }
  434. // Process the directional light first.
  435. if(ctx.m_renderQueue->m_directionalLight.m_shadowCascadeCount > 0)
  436. {
  437. DirectionalLightQueueElement& light = ctx.m_renderQueue->m_directionalLight;
  438. Array<U64, MAX_SHADOW_CASCADES> timestamps;
  439. Array<U32, MAX_SHADOW_CASCADES> cascadeIndices;
  440. Array<U32, MAX_SHADOW_CASCADES> drawcallCounts;
  441. Array<UVec4, MAX_SHADOW_CASCADES> atlasViewports;
  442. Array<UVec4, MAX_SHADOW_CASCADES> scratchViewports;
  443. Array<TileAllocatorResult, MAX_SHADOW_CASCADES> subResults;
  444. Array<U32, MAX_SHADOW_CASCADES> lods;
  445. Array<U32, MAX_SHADOW_CASCADES> renderQueueElementsLods;
  446. Array<Bool, MAX_SHADOW_CASCADES> blurAtlass;
  447. U32 activeCascades = 0;
  448. for(U32 cascade = 0; cascade < light.m_shadowCascadeCount; ++cascade)
  449. {
  450. ANKI_ASSERT(light.m_shadowRenderQueues[cascade]);
  451. if(light.m_shadowRenderQueues[cascade]->m_renderables.getSize() > 0)
  452. {
  453. // Cascade with drawcalls, will need tiles
  454. timestamps[activeCascades] = m_r->getGlobalTimestamp(); // This light is always updated
  455. cascadeIndices[activeCascades] = cascade;
  456. drawcallCounts[activeCascades] = 1; // Doesn't matter
  457. // Change the quality per cascade
  458. blurAtlass[activeCascades] = (cascade <= 1);
  459. lods[activeCascades] = (cascade <= 1) ? (MAX_LOD_COUNT - 1) : (lods[0] - 1);
  460. renderQueueElementsLods[activeCascades] = (cascade == 0) ? 0 : (MAX_LOD_COUNT - 1);
  461. ++activeCascades;
  462. }
  463. }
  464. const Bool allocationFailed =
  465. activeCascades == 0
  466. || allocateTilesAndScratchTiles(light.m_uuid, activeCascades, &timestamps[0], &cascadeIndices[0],
  467. &drawcallCounts[0], &lods[0], &atlasViewports[0], &scratchViewports[0],
  468. &subResults[0])
  469. == TileAllocatorResult::ALLOCATION_FAILED;
  470. if(!allocationFailed)
  471. {
  472. activeCascades = 0;
  473. for(U cascade = 0; cascade < light.m_shadowCascadeCount; ++cascade)
  474. {
  475. if(light.m_shadowRenderQueues[cascade]->m_renderables.getSize() > 0)
  476. {
  477. // Cascade with drawcalls, push some work for it
  478. // Update the texture matrix to point to the correct region in the atlas
  479. light.m_textureMatrices[cascade] =
  480. createSpotLightTextureMatrix(atlasViewports[activeCascades]) * light.m_textureMatrices[cascade];
  481. // Push work
  482. newScratchAndAtlasResloveRenderWorkItems(
  483. atlasViewports[activeCascades], scratchViewports[activeCascades], blurAtlass[activeCascades],
  484. light.m_shadowRenderQueues[cascade], renderQueueElementsLods[activeCascades], lightsToRender,
  485. atlasWorkItems, drawcallCount);
  486. ++activeCascades;
  487. }
  488. else
  489. {
  490. // Empty cascade, point it to the empty tile
  491. light.m_textureMatrices[cascade] =
  492. createSpotLightTextureMatrix(emptyTileViewport) * light.m_textureMatrices[cascade];
  493. }
  494. }
  495. }
  496. else
  497. {
  498. // Light can't be a caster this frame
  499. light.m_shadowCascadeCount = 0;
  500. zeroMemory(light.m_shadowRenderQueues);
  501. }
  502. }
  503. // Process the point lights.
  504. for(PointLightQueueElement& light : ctx.m_renderQueue->m_pointLights)
  505. {
  506. if(!light.hasShadow())
  507. {
  508. continue;
  509. }
  510. // Prepare data to allocate tiles and allocate
  511. Array<U64, 6> timestamps;
  512. Array<U32, 6> faceIndices;
  513. Array<U32, 6> drawcallCounts;
  514. Array<UVec4, 6> atlasViewports;
  515. Array<UVec4, 6> scratchViewports;
  516. Array<TileAllocatorResult, 6> subResults;
  517. Array<U32, 6> lods;
  518. U32 numOfFacesThatHaveDrawcalls = 0;
  519. Bool blurAtlas;
  520. U32 lod, renderQueueElementsLod;
  521. chooseLod(cameraOrigin, light, blurAtlas, lod, renderQueueElementsLod);
  522. for(U32 face = 0; face < 6; ++face)
  523. {
  524. ANKI_ASSERT(light.m_shadowRenderQueues[face]);
  525. if(light.m_shadowRenderQueues[face]->m_renderables.getSize())
  526. {
  527. // Has renderables, need to allocate tiles for it so add it to the arrays
  528. faceIndices[numOfFacesThatHaveDrawcalls] = face;
  529. timestamps[numOfFacesThatHaveDrawcalls] =
  530. light.m_shadowRenderQueues[face]->m_shadowRenderablesLastUpdateTimestamp;
  531. drawcallCounts[numOfFacesThatHaveDrawcalls] = light.m_shadowRenderQueues[face]->m_renderables.getSize();
  532. lods[numOfFacesThatHaveDrawcalls] = lod;
  533. ++numOfFacesThatHaveDrawcalls;
  534. }
  535. }
  536. const Bool allocationFailed =
  537. numOfFacesThatHaveDrawcalls == 0
  538. || allocateTilesAndScratchTiles(light.m_uuid, numOfFacesThatHaveDrawcalls, &timestamps[0], &faceIndices[0],
  539. &drawcallCounts[0], &lods[0], &atlasViewports[0], &scratchViewports[0],
  540. &subResults[0])
  541. == TileAllocatorResult::ALLOCATION_FAILED;
  542. if(!allocationFailed)
  543. {
  544. // All good, update the lights
  545. const F32 atlasResolution = F32(m_atlas.m_tileResolution * m_atlas.m_tileCountBothAxis);
  546. F32 superTileSize = F32(atlasViewports[0][2]); // Should be the same for all tiles and faces
  547. superTileSize -= 1.0f; // Remove 2 half texels to avoid bilinear filtering bleeding
  548. light.m_shadowAtlasTileSize = superTileSize / atlasResolution;
  549. numOfFacesThatHaveDrawcalls = 0;
  550. for(U face = 0; face < 6; ++face)
  551. {
  552. if(light.m_shadowRenderQueues[face]->m_renderables.getSize())
  553. {
  554. // Has drawcalls, asigned it to a tile
  555. const UVec4& atlasViewport = atlasViewports[numOfFacesThatHaveDrawcalls];
  556. const UVec4& scratchViewport = scratchViewports[numOfFacesThatHaveDrawcalls];
  557. // Add a half texel to the viewport's start to avoid bilinear filtering bleeding
  558. light.m_shadowAtlasTileOffsets[face].x() = (F32(atlasViewport[0]) + 0.5f) / atlasResolution;
  559. light.m_shadowAtlasTileOffsets[face].y() = (F32(atlasViewport[1]) + 0.5f) / atlasResolution;
  560. if(subResults[numOfFacesThatHaveDrawcalls] != TileAllocatorResult::CACHED)
  561. {
  562. newScratchAndAtlasResloveRenderWorkItems(
  563. atlasViewport, scratchViewport, blurAtlas, light.m_shadowRenderQueues[face],
  564. renderQueueElementsLod, lightsToRender, atlasWorkItems, drawcallCount);
  565. }
  566. ++numOfFacesThatHaveDrawcalls;
  567. }
  568. else
  569. {
  570. // Doesn't have renderables, point the face to the empty tile
  571. UVec4 atlasViewport = emptyTileViewport;
  572. ANKI_ASSERT(F32(atlasViewport[2]) <= superTileSize && F32(atlasViewport[3]) <= superTileSize);
  573. atlasViewport[2] = U32(superTileSize);
  574. atlasViewport[3] = U32(superTileSize);
  575. light.m_shadowAtlasTileOffsets[face].x() = (F32(atlasViewport[0]) + 0.5f) / atlasResolution;
  576. light.m_shadowAtlasTileOffsets[face].y() = (F32(atlasViewport[1]) + 0.5f) / atlasResolution;
  577. }
  578. }
  579. }
  580. else
  581. {
  582. // Light can't be a caster this frame
  583. zeroMemory(light.m_shadowRenderQueues);
  584. }
  585. }
  586. // Process the spot lights
  587. for(SpotLightQueueElement& light : ctx.m_renderQueue->m_spotLights)
  588. {
  589. if(!light.hasShadow())
  590. {
  591. continue;
  592. }
  593. // Allocate tiles
  594. U32 faceIdx = 0;
  595. TileAllocatorResult subResult = TileAllocatorResult::ALLOCATION_FAILED;
  596. UVec4 atlasViewport;
  597. UVec4 scratchViewport;
  598. const U32 localDrawcallCount = light.m_shadowRenderQueue->m_renderables.getSize();
  599. Bool blurAtlas;
  600. U32 lod, renderQueueElementsLod;
  601. chooseLod(cameraOrigin, light, blurAtlas, lod, renderQueueElementsLod);
  602. const Bool allocationFailed =
  603. localDrawcallCount == 0
  604. || allocateTilesAndScratchTiles(
  605. light.m_uuid, 1, &light.m_shadowRenderQueue->m_shadowRenderablesLastUpdateTimestamp, &faceIdx,
  606. &localDrawcallCount, &lod, &atlasViewport, &scratchViewport, &subResult)
  607. == TileAllocatorResult::ALLOCATION_FAILED;
  608. if(!allocationFailed)
  609. {
  610. // All good, update the light
  611. // Update the texture matrix to point to the correct region in the atlas
  612. light.m_textureMatrix = createSpotLightTextureMatrix(atlasViewport) * light.m_textureMatrix;
  613. if(subResult != TileAllocatorResult::CACHED)
  614. {
  615. newScratchAndAtlasResloveRenderWorkItems(atlasViewport, scratchViewport, blurAtlas,
  616. light.m_shadowRenderQueue, renderQueueElementsLod,
  617. lightsToRender, atlasWorkItems, drawcallCount);
  618. }
  619. }
  620. else
  621. {
  622. // Doesn't have renderables or the allocation failed, won't be a shadow caster
  623. light.m_shadowRenderQueue = nullptr;
  624. }
  625. }
  626. // Split the work that will happen in the scratch buffer
  627. if(lightsToRender.getSize())
  628. {
  629. DynamicArrayAuto<Scratch::WorkItem> workItems(ctx.m_tempAllocator);
  630. Scratch::LightToRenderToScratchInfo* lightToRender = lightsToRender.getBegin();
  631. U32 lightToRenderDrawcallCount = lightToRender->m_drawcallCount;
  632. const Scratch::LightToRenderToScratchInfo* lightToRenderEnd = lightsToRender.getEnd();
  633. const U32 threadCount = computeNumberOfSecondLevelCommandBuffers(drawcallCount);
  634. threadCountForScratchPass = threadCount;
  635. for(U32 taskId = 0; taskId < threadCount; ++taskId)
  636. {
  637. U32 start, end;
  638. splitThreadedProblem(taskId, threadCount, drawcallCount, start, end);
  639. // While there are drawcalls in this task emit new work items
  640. U32 taskDrawcallCount = end - start;
  641. ANKI_ASSERT(taskDrawcallCount > 0 && "Because we used computeNumberOfSecondLevelCommandBuffers()");
  642. while(taskDrawcallCount)
  643. {
  644. ANKI_ASSERT(lightToRender != lightToRenderEnd);
  645. const U32 workItemDrawcallCount = min(lightToRenderDrawcallCount, taskDrawcallCount);
  646. Scratch::WorkItem workItem;
  647. workItem.m_viewport = lightToRender->m_viewport;
  648. workItem.m_renderQueue = lightToRender->m_renderQueue;
  649. workItem.m_firstRenderableElement = lightToRender->m_drawcallCount - lightToRenderDrawcallCount;
  650. workItem.m_renderableElementCount = workItemDrawcallCount;
  651. workItem.m_threadPoolTaskIdx = taskId;
  652. workItem.m_renderQueueElementsLod = lightToRender->m_renderQueueElementsLod;
  653. workItems.emplaceBack(workItem);
  654. // Decrease the drawcall counts for the task and the light
  655. ANKI_ASSERT(taskDrawcallCount >= workItemDrawcallCount);
  656. taskDrawcallCount -= workItemDrawcallCount;
  657. ANKI_ASSERT(lightToRenderDrawcallCount >= workItemDrawcallCount);
  658. lightToRenderDrawcallCount -= workItemDrawcallCount;
  659. // Move to the next light
  660. if(lightToRenderDrawcallCount == 0)
  661. {
  662. ++lightToRender;
  663. lightToRenderDrawcallCount =
  664. (lightToRender != lightToRenderEnd) ? lightToRender->m_drawcallCount : 0;
  665. }
  666. }
  667. }
  668. ANKI_ASSERT(lightToRender == lightToRenderEnd);
  669. ANKI_ASSERT(lightsToRender.getSize() <= workItems.getSize());
  670. // All good, store the work items for the threads to pick up
  671. {
  672. Scratch::WorkItem* items;
  673. U32 itemSize;
  674. U32 itemStorageSize;
  675. workItems.moveAndReset(items, itemSize, itemStorageSize);
  676. ANKI_ASSERT(items && itemSize && itemStorageSize);
  677. m_scratch.m_workItems = WeakArray<Scratch::WorkItem>(items, itemSize);
  678. Atlas::ResolveWorkItem* atlasItems;
  679. atlasWorkItems.moveAndReset(atlasItems, itemSize, itemStorageSize);
  680. ANKI_ASSERT(atlasItems && itemSize && itemStorageSize);
  681. m_atlas.m_resolveWorkItems = WeakArray<Atlas::ResolveWorkItem>(atlasItems, itemSize);
  682. }
  683. }
  684. else
  685. {
  686. m_scratch.m_workItems = WeakArray<Scratch::WorkItem>();
  687. m_atlas.m_resolveWorkItems = WeakArray<Atlas::ResolveWorkItem>();
  688. }
  689. }
  690. void ShadowMapping::newScratchAndAtlasResloveRenderWorkItems(
  691. const UVec4& atlasViewport, const UVec4& scratchVewport, Bool blurAtlas, RenderQueue* lightRenderQueue,
  692. U32 renderQueueElementsLod, DynamicArrayAuto<Scratch::LightToRenderToScratchInfo>& scratchWorkItem,
  693. DynamicArrayAuto<Atlas::ResolveWorkItem>& atlasResolveWorkItem, U32& drawcallCount) const
  694. {
  695. // Scratch work item
  696. {
  697. Scratch::LightToRenderToScratchInfo toRender;
  698. toRender.m_renderQueue = lightRenderQueue;
  699. toRender.m_viewport = scratchVewport;
  700. toRender.m_drawcallCount = lightRenderQueue->m_renderables.getSize();
  701. toRender.m_renderQueueElementsLod = renderQueueElementsLod;
  702. scratchWorkItem.emplaceBack(toRender);
  703. drawcallCount += lightRenderQueue->m_renderables.getSize();
  704. }
  705. // Atlas resolve work items
  706. const U32 tilesX = scratchVewport[2] / m_scratch.m_tileResolution;
  707. const U32 tilesY = scratchVewport[3] / m_scratch.m_tileResolution;
  708. for(U32 x = 0; x < tilesX; ++x)
  709. {
  710. for(U32 y = 0; y < tilesY; ++y)
  711. {
  712. const F32 scratchAtlasWidth = F32(m_scratch.m_tileCountX * m_scratch.m_tileResolution);
  713. const F32 scratchAtlasHeight = F32(m_scratch.m_tileCountY * m_scratch.m_tileResolution);
  714. Atlas::ResolveWorkItem atlasItem;
  715. atlasItem.m_uvInBounds[0] = F32(scratchVewport[0]) / scratchAtlasWidth;
  716. atlasItem.m_uvInBounds[1] = F32(scratchVewport[1]) / scratchAtlasHeight;
  717. atlasItem.m_uvInBounds[2] = F32(scratchVewport[2]) / scratchAtlasWidth;
  718. atlasItem.m_uvInBounds[3] = F32(scratchVewport[3]) / scratchAtlasHeight;
  719. atlasItem.m_uvIn[0] = F32(scratchVewport[0] + scratchVewport[2] / tilesX * x) / scratchAtlasWidth;
  720. atlasItem.m_uvIn[1] = F32(scratchVewport[1] + scratchVewport[3] / tilesY * y) / scratchAtlasHeight;
  721. atlasItem.m_uvIn[2] = F32(scratchVewport[2] / tilesX) / scratchAtlasWidth;
  722. atlasItem.m_uvIn[3] = F32(scratchVewport[3] / tilesY) / scratchAtlasHeight;
  723. atlasItem.m_viewportOut[0] = atlasViewport[0] + atlasViewport[2] / tilesX * x;
  724. atlasItem.m_viewportOut[1] = atlasViewport[1] + atlasViewport[3] / tilesY * y;
  725. atlasItem.m_viewportOut[2] = atlasViewport[2] / tilesX;
  726. atlasItem.m_viewportOut[3] = atlasViewport[3] / tilesY;
  727. atlasItem.m_blur = blurAtlas;
  728. atlasResolveWorkItem.emplaceBack(atlasItem);
  729. }
  730. }
  731. }
  732. } // end namespace anki