ShadowMapping.cpp 27 KB

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