BsShadowRendering.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsShadowRendering.h"
  4. #include "BsRendererView.h"
  5. #include "BsRendererScene.h"
  6. #include "Renderer/BsLight.h"
  7. #include "Renderer/BsRendererUtility.h"
  8. #include "Material/BsGpuParamsSet.h"
  9. #include "Mesh/BsMesh.h"
  10. #include "Renderer/BsCamera.h"
  11. #include "Utility/BsBitwise.h"
  12. #include "RenderAPI/BsVertexDataDesc.h"
  13. namespace bs { namespace ct
  14. {
  15. ShadowParamsDef gShadowParamsDef;
  16. ShadowDepthNormalMat::ShadowDepthNormalMat()
  17. { }
  18. void ShadowDepthNormalMat::_initVariations(ShaderVariations& variations)
  19. {
  20. // No defines
  21. }
  22. void ShadowDepthNormalMat::bind(const SPtr<GpuParamBlockBuffer>& shadowParams)
  23. {
  24. mParamsSet->setParamBlockBuffer("ShadowParams", shadowParams);
  25. gRendererUtility().setPass(mMaterial);
  26. }
  27. void ShadowDepthNormalMat::setPerObjectBuffer(const SPtr<GpuParamBlockBuffer>& perObjectParams)
  28. {
  29. mParamsSet->setParamBlockBuffer("PerObject", perObjectParams);
  30. gRendererUtility().setPassParams(mParamsSet);
  31. }
  32. ShadowDepthDirectionalMat::ShadowDepthDirectionalMat()
  33. { }
  34. void ShadowDepthDirectionalMat::_initVariations(ShaderVariations& variations)
  35. {
  36. // No defines
  37. }
  38. void ShadowDepthDirectionalMat::bind(const SPtr<GpuParamBlockBuffer>& shadowParams)
  39. {
  40. mParamsSet->setParamBlockBuffer("ShadowParams", shadowParams);
  41. gRendererUtility().setPass(mMaterial);
  42. }
  43. void ShadowDepthDirectionalMat::setPerObjectBuffer(const SPtr<GpuParamBlockBuffer>& perObjectParams)
  44. {
  45. mParamsSet->setParamBlockBuffer("PerObject", perObjectParams);
  46. gRendererUtility().setPassParams(mParamsSet);
  47. }
  48. ShadowCubeMatricesDef gShadowCubeMatricesDef;
  49. ShadowCubeMasksDef gShadowCubeMasksDef;
  50. ShadowDepthCubeMat::ShadowDepthCubeMat()
  51. { }
  52. void ShadowDepthCubeMat::_initVariations(ShaderVariations& variations)
  53. {
  54. // No defines
  55. }
  56. void ShadowDepthCubeMat::bind(const SPtr<GpuParamBlockBuffer>& shadowParams,
  57. const SPtr<GpuParamBlockBuffer>& shadowCubeMatrices)
  58. {
  59. mParamsSet->setParamBlockBuffer("ShadowParams", shadowParams);
  60. mParamsSet->setParamBlockBuffer("ShadowCubeMatrices", shadowCubeMatrices);
  61. gRendererUtility().setPass(mMaterial);
  62. }
  63. void ShadowDepthCubeMat::setPerObjectBuffer(const SPtr<GpuParamBlockBuffer>& perObjectParams,
  64. const SPtr<GpuParamBlockBuffer>& shadowCubeMasks)
  65. {
  66. mParamsSet->setParamBlockBuffer("PerObject", perObjectParams);
  67. mParamsSet->setParamBlockBuffer("ShadowCubeMasks", shadowCubeMasks);
  68. gRendererUtility().setPassParams(mParamsSet);
  69. }
  70. ShadowProjectParamsDef gShadowProjectParamsDef;
  71. ShadowProjectVertParamsDef gShadowProjectVertParamsDef;
  72. ShaderVariation ShadowProjectStencilMat::VAR_Dir_ZFailStencil = ShaderVariation({
  73. ShaderVariation::Param("NEEDS_TRANSFORM", true),
  74. ShaderVariation::Param("USE_ZFAIL_STENCIL", true)
  75. });
  76. ShaderVariation ShadowProjectStencilMat::VAR_Dir_NoZFailStencil = ShaderVariation({
  77. ShaderVariation::Param("NEEDS_TRANSFORM", true)
  78. });
  79. ShaderVariation ShadowProjectStencilMat::VAR_NoDir_ZFailStencil = ShaderVariation({
  80. ShaderVariation::Param("NEEDS_TRANSFORM", false),
  81. ShaderVariation::Param("USE_ZFAIL_STENCIL", true)
  82. });
  83. ShaderVariation ShadowProjectStencilMat::VAR_NoDir_NoZFailStencil = ShaderVariation({
  84. ShaderVariation::Param("NEEDS_TRANSFORM", false)
  85. });
  86. ShadowProjectStencilMat::ShadowProjectStencilMat()
  87. {
  88. SPtr<GpuParams> params = mParamsSet->getGpuParams();
  89. mVertParams = gShadowProjectVertParamsDef.createBuffer();
  90. if(params->hasParamBlock(GPT_VERTEX_PROGRAM, "VertParams"))
  91. params->setParamBlockBuffer(GPT_VERTEX_PROGRAM, "VertParams", mVertParams);
  92. }
  93. void ShadowProjectStencilMat::_initVariations(ShaderVariations& variations)
  94. {
  95. variations.add(VAR_Dir_ZFailStencil);
  96. variations.add(VAR_Dir_NoZFailStencil);
  97. variations.add(VAR_NoDir_ZFailStencil);
  98. variations.add(VAR_NoDir_NoZFailStencil);
  99. }
  100. void ShadowProjectStencilMat::bind(const SPtr<GpuParamBlockBuffer>& perCamera)
  101. {
  102. Vector4 lightPosAndScale(0, 0, 0, 1);
  103. gShadowProjectVertParamsDef.gPositionAndScale.set(mVertParams, lightPosAndScale);
  104. mParamsSet->setParamBlockBuffer("PerCamera", perCamera);
  105. gRendererUtility().setPass(mMaterial);
  106. gRendererUtility().setPassParams(mParamsSet);
  107. }
  108. ShadowProjectStencilMat* ShadowProjectStencilMat::getVariation(bool directional, bool useZFailStencil)
  109. {
  110. if(directional)
  111. {
  112. // Always uses z-fail stencil
  113. return get(VAR_Dir_ZFailStencil);
  114. }
  115. else
  116. {
  117. if (useZFailStencil)
  118. return get(VAR_NoDir_ZFailStencil);
  119. else
  120. return get(VAR_NoDir_NoZFailStencil);
  121. }
  122. }
  123. #define VARIATION(QUALITY) \
  124. ShaderVariation ShadowProjectMat::VAR_Q##QUALITY##_Dir_MSAA = ShaderVariation({ \
  125. ShaderVariation::Param("SHADOW_QUALITY", QUALITY), \
  126. ShaderVariation::Param("FADE_PLANE", true), \
  127. ShaderVariation::Param("NEEDS_TRANSFORM", false), \
  128. ShaderVariation::Param("MSAA_COUNT", 2) \
  129. }); \
  130. ShaderVariation ShadowProjectMat::VAR_Q##QUALITY##_Dir_NoMSAA = ShaderVariation({ \
  131. ShaderVariation::Param("SHADOW_QUALITY", QUALITY), \
  132. ShaderVariation::Param("FADE_PLANE", true), \
  133. ShaderVariation::Param("NEEDS_TRANSFORM", false), \
  134. ShaderVariation::Param("MSAA_COUNT", 1) \
  135. }); \
  136. ShaderVariation ShadowProjectMat::VAR_Q##QUALITY##_NoDir_MSAA = ShaderVariation({ \
  137. ShaderVariation::Param("SHADOW_QUALITY", QUALITY), \
  138. ShaderVariation::Param("NEEDS_TRANSFORM", true), \
  139. ShaderVariation::Param("MSAA_COUNT", 2) \
  140. }); \
  141. ShaderVariation ShadowProjectMat::VAR_Q##QUALITY##_NoDir_NoMSAA = ShaderVariation({ \
  142. ShaderVariation::Param("SHADOW_QUALITY", QUALITY), \
  143. ShaderVariation::Param("NEEDS_TRANSFORM", true), \
  144. ShaderVariation::Param("MSAA_COUNT", 1) \
  145. }); \
  146. VARIATION(1)
  147. VARIATION(2)
  148. VARIATION(3)
  149. VARIATION(4)
  150. #undef VARIATION
  151. ShadowProjectMat::ShadowProjectMat()
  152. : mGBufferParams(mMaterial, mParamsSet)
  153. {
  154. SPtr<GpuParams> params = mParamsSet->getGpuParams();
  155. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gShadowTex", mShadowMapParam);
  156. if(params->hasSamplerState(GPT_FRAGMENT_PROGRAM, "gShadowSampler"))
  157. params->getSamplerStateParam(GPT_FRAGMENT_PROGRAM, "gShadowSampler", mShadowSamplerParam);
  158. else
  159. params->getSamplerStateParam(GPT_FRAGMENT_PROGRAM, "gShadowTex", mShadowSamplerParam);
  160. SAMPLER_STATE_DESC desc;
  161. desc.minFilter = FO_POINT;
  162. desc.magFilter = FO_POINT;
  163. desc.mipFilter = FO_POINT;
  164. desc.addressMode.u = TAM_CLAMP;
  165. desc.addressMode.v = TAM_CLAMP;
  166. desc.addressMode.w = TAM_CLAMP;
  167. mSamplerState = SamplerState::create(desc);
  168. mVertParams = gShadowProjectVertParamsDef.createBuffer();
  169. if(params->hasParamBlock(GPT_VERTEX_PROGRAM, "VertParams"))
  170. params->setParamBlockBuffer(GPT_VERTEX_PROGRAM, "VertParams", mVertParams);
  171. }
  172. void ShadowProjectMat::_initVariations(ShaderVariations& variations)
  173. {
  174. #define VARIATION(QUALITY) \
  175. variations.add(VAR_Q##QUALITY##_Dir_MSAA); \
  176. variations.add(VAR_Q##QUALITY##_Dir_NoMSAA); \
  177. variations.add(VAR_Q##QUALITY##_NoDir_MSAA); \
  178. variations.add(VAR_Q##QUALITY##_NoDir_NoMSAA); \
  179. VARIATION(1)
  180. VARIATION(2)
  181. VARIATION(3)
  182. VARIATION(4)
  183. #undef VARIATION
  184. }
  185. void ShadowProjectMat::bind(const ShadowProjectParams& params)
  186. {
  187. Vector4 lightPosAndScale(Vector3(0.0f, 0.0f, 0.0f), 1.0f);
  188. gShadowProjectVertParamsDef.gPositionAndScale.set(mVertParams, lightPosAndScale);
  189. TextureSurface surface;
  190. surface.face = params.shadowMapFace;
  191. mGBufferParams.bind(params.gbuffer);
  192. mShadowMapParam.set(params.shadowMap, surface);
  193. mShadowSamplerParam.set(mSamplerState);
  194. mParamsSet->setParamBlockBuffer("Params", params.shadowParams);
  195. mParamsSet->setParamBlockBuffer("PerCamera", params.perCamera);
  196. gRendererUtility().setPass(mMaterial);
  197. gRendererUtility().setPassParams(mParamsSet);
  198. }
  199. ShadowProjectMat* ShadowProjectMat::getVariation(UINT32 quality, bool directional, bool MSAA)
  200. {
  201. #define BIND_MAT(QUALITY) \
  202. { \
  203. if(directional) \
  204. if (MSAA) \
  205. return get(VAR_Q##QUALITY##_Dir_MSAA); \
  206. else \
  207. return get(VAR_Q##QUALITY##_Dir_NoMSAA); \
  208. else \
  209. if (MSAA) \
  210. return get(VAR_Q##QUALITY##_NoDir_MSAA); \
  211. else \
  212. return get(VAR_Q##QUALITY##_NoDir_NoMSAA); \
  213. }
  214. if(quality <= 1)
  215. BIND_MAT(1)
  216. else if(quality == 2)
  217. BIND_MAT(2)
  218. else if(quality == 3)
  219. BIND_MAT(3)
  220. else // 4 or higher
  221. BIND_MAT(4)
  222. #undef BIND_MAT
  223. }
  224. ShadowProjectOmniParamsDef gShadowProjectOmniParamsDef;
  225. #define VARIATION(QUALITY) \
  226. ShaderVariation ShadowProjectOmniMat::VAR_Q##QUALITY##_Inside_MSAA = ShaderVariation({ \
  227. ShaderVariation::Param("SHADOW_QUALITY", QUALITY), \
  228. ShaderVariation::Param("VIEWER_INSIDE_VOLUME", true), \
  229. ShaderVariation::Param("NEEDS_TRANSFORM", true), \
  230. ShaderVariation::Param("MSAA_COUNT", 2) \
  231. }); \
  232. ShaderVariation ShadowProjectOmniMat::VAR_Q##QUALITY##_Inside_NoMSAA = ShaderVariation({ \
  233. ShaderVariation::Param("SHADOW_QUALITY", QUALITY), \
  234. ShaderVariation::Param("VIEWER_INSIDE_VOLUME", true), \
  235. ShaderVariation::Param("NEEDS_TRANSFORM", true), \
  236. ShaderVariation::Param("MSAA_COUNT", 1) \
  237. }); \
  238. ShaderVariation ShadowProjectOmniMat::VAR_Q##QUALITY##_Outside_MSAA = ShaderVariation({ \
  239. ShaderVariation::Param("SHADOW_QUALITY", QUALITY), \
  240. ShaderVariation::Param("NEEDS_TRANSFORM", true), \
  241. ShaderVariation::Param("MSAA_COUNT", 2) \
  242. }); \
  243. ShaderVariation ShadowProjectOmniMat::VAR_Q##QUALITY##_Outside_NoMSAA = ShaderVariation({ \
  244. ShaderVariation::Param("SHADOW_QUALITY", QUALITY), \
  245. ShaderVariation::Param("NEEDS_TRANSFORM", true), \
  246. ShaderVariation::Param("MSAA_COUNT", 1) \
  247. }); \
  248. VARIATION(1)
  249. VARIATION(2)
  250. VARIATION(3)
  251. VARIATION(4)
  252. #undef VARIATION
  253. ShadowProjectOmniMat::ShadowProjectOmniMat()
  254. : mGBufferParams(mMaterial, mParamsSet)
  255. {
  256. SPtr<GpuParams> params = mParamsSet->getGpuParams();
  257. params->getTextureParam(GPT_FRAGMENT_PROGRAM, "gShadowCubeTex", mShadowMapParam);
  258. if(params->hasSamplerState(GPT_FRAGMENT_PROGRAM, "gShadowCubeSampler"))
  259. params->getSamplerStateParam(GPT_FRAGMENT_PROGRAM, "gShadowCubeSampler", mShadowSamplerParam);
  260. else
  261. params->getSamplerStateParam(GPT_FRAGMENT_PROGRAM, "gShadowCubeTex", mShadowSamplerParam);
  262. SAMPLER_STATE_DESC desc;
  263. desc.minFilter = FO_LINEAR;
  264. desc.magFilter = FO_LINEAR;
  265. desc.mipFilter = FO_POINT;
  266. desc.addressMode.u = TAM_CLAMP;
  267. desc.addressMode.v = TAM_CLAMP;
  268. desc.addressMode.w = TAM_CLAMP;
  269. desc.comparisonFunc = CMPF_GREATER_EQUAL;
  270. mSamplerState = SamplerState::create(desc);
  271. mVertParams = gShadowProjectVertParamsDef.createBuffer();
  272. if(params->hasParamBlock(GPT_VERTEX_PROGRAM, "VertParams"))
  273. params->setParamBlockBuffer(GPT_VERTEX_PROGRAM, "VertParams", mVertParams);
  274. }
  275. void ShadowProjectOmniMat::_initVariations(ShaderVariations& variations)
  276. {
  277. #define VARIATION(QUALITY) \
  278. variations.add(VAR_Q##QUALITY##_Inside_MSAA); \
  279. variations.add(VAR_Q##QUALITY##_Inside_NoMSAA); \
  280. variations.add(VAR_Q##QUALITY##_Outside_MSAA); \
  281. variations.add(VAR_Q##QUALITY##_Outside_NoMSAA); \
  282. VARIATION(1)
  283. VARIATION(2)
  284. VARIATION(3)
  285. VARIATION(4)
  286. #undef VARIATION
  287. }
  288. void ShadowProjectOmniMat::bind(const ShadowProjectParams& params)
  289. {
  290. Vector4 lightPosAndScale(params.light.getTransform().getPosition(), params.light.getAttenuationRadius());
  291. gShadowProjectVertParamsDef.gPositionAndScale.set(mVertParams, lightPosAndScale);
  292. mGBufferParams.bind(params.gbuffer);
  293. mShadowMapParam.set(params.shadowMap);
  294. mShadowSamplerParam.set(mSamplerState);
  295. mParamsSet->setParamBlockBuffer("Params", params.shadowParams);
  296. mParamsSet->setParamBlockBuffer("PerCamera", params.perCamera);
  297. gRendererUtility().setPass(mMaterial);
  298. gRendererUtility().setPassParams(mParamsSet);
  299. }
  300. ShadowProjectOmniMat* ShadowProjectOmniMat::getVariation(UINT32 quality, bool inside, bool MSAA)
  301. {
  302. #define BIND_MAT(QUALITY) \
  303. { \
  304. if(inside) \
  305. if (MSAA) \
  306. return get(VAR_Q##QUALITY##_Inside_MSAA); \
  307. else \
  308. return get(VAR_Q##QUALITY##_Inside_NoMSAA); \
  309. else \
  310. if (MSAA) \
  311. return get(VAR_Q##QUALITY##_Outside_MSAA); \
  312. else \
  313. return get(VAR_Q##QUALITY##_Outside_NoMSAA); \
  314. }
  315. if(quality <= 1)
  316. BIND_MAT(1)
  317. else if(quality == 2)
  318. BIND_MAT(2)
  319. else if(quality == 3)
  320. BIND_MAT(3)
  321. else // 4 or higher
  322. BIND_MAT(4)
  323. #undef BIND_MAT
  324. }
  325. void ShadowInfo::updateNormArea(UINT32 atlasSize)
  326. {
  327. normArea.x = area.x / (float)atlasSize;
  328. normArea.y = area.y / (float)atlasSize;
  329. normArea.width = area.width / (float)atlasSize;
  330. normArea.height = area.height / (float)atlasSize;
  331. }
  332. ShadowMapAtlas::ShadowMapAtlas(UINT32 size)
  333. : mLayout(0, 0, size, size, true), mLastUsedCounter(0)
  334. {
  335. mAtlas = GpuResourcePool::instance().get(
  336. POOLED_RENDER_TEXTURE_DESC::create2D(SHADOW_MAP_FORMAT, size, size, TU_DEPTHSTENCIL));
  337. }
  338. ShadowMapAtlas::~ShadowMapAtlas()
  339. {
  340. GpuResourcePool::instance().release(mAtlas);
  341. }
  342. bool ShadowMapAtlas::addMap(UINT32 size, Rect2I& area, UINT32 border)
  343. {
  344. UINT32 sizeWithBorder = size + border * 2;
  345. UINT32 x, y;
  346. if (!mLayout.addElement(sizeWithBorder, sizeWithBorder, x, y))
  347. return false;
  348. area.width = area.height = size;
  349. area.x = x + border;
  350. area.y = y + border;
  351. mLastUsedCounter = 0;
  352. return true;
  353. }
  354. void ShadowMapAtlas::clear()
  355. {
  356. mLayout.clear();
  357. mLastUsedCounter++;
  358. }
  359. bool ShadowMapAtlas::isEmpty() const
  360. {
  361. return mLayout.isEmpty();
  362. }
  363. SPtr<Texture> ShadowMapAtlas::getTexture() const
  364. {
  365. return mAtlas->texture;
  366. }
  367. SPtr<RenderTexture> ShadowMapAtlas::getTarget() const
  368. {
  369. return mAtlas->renderTexture;
  370. }
  371. ShadowMapBase::ShadowMapBase(UINT32 size)
  372. : mSize(size), mIsUsed(false), mLastUsedCounter (0)
  373. { }
  374. SPtr<Texture> ShadowMapBase::getTexture() const
  375. {
  376. return mShadowMap->texture;
  377. }
  378. ShadowCubemap::ShadowCubemap(UINT32 size)
  379. :ShadowMapBase(size)
  380. {
  381. mShadowMap = GpuResourcePool::instance().get(
  382. POOLED_RENDER_TEXTURE_DESC::createCube(SHADOW_MAP_FORMAT, size, size, TU_DEPTHSTENCIL));
  383. }
  384. ShadowCubemap::~ShadowCubemap()
  385. {
  386. GpuResourcePool::instance().release(mShadowMap);
  387. }
  388. SPtr<RenderTexture> ShadowCubemap::getTarget() const
  389. {
  390. return mShadowMap->renderTexture;
  391. }
  392. ShadowCascadedMap::ShadowCascadedMap(UINT32 size)
  393. :ShadowMapBase(size)
  394. {
  395. mShadowMap = GpuResourcePool::instance().get(POOLED_RENDER_TEXTURE_DESC::create2D(SHADOW_MAP_FORMAT, size, size,
  396. TU_DEPTHSTENCIL, 0, false, NUM_CASCADE_SPLITS));
  397. RENDER_TEXTURE_DESC rtDesc;
  398. rtDesc.depthStencilSurface.texture = mShadowMap->texture;
  399. rtDesc.depthStencilSurface.numFaces = 1;
  400. for (UINT32 i = 0; i < NUM_CASCADE_SPLITS; ++i)
  401. {
  402. rtDesc.depthStencilSurface.face = i;
  403. mTargets[i] = RenderTexture::create(rtDesc);
  404. }
  405. }
  406. ShadowCascadedMap::~ShadowCascadedMap()
  407. {
  408. GpuResourcePool::instance().release(mShadowMap);
  409. }
  410. SPtr<RenderTexture> ShadowCascadedMap::getTarget(UINT32 cascadeIdx) const
  411. {
  412. return mTargets[cascadeIdx];
  413. }
  414. const UINT32 ShadowRendering::MAX_ATLAS_SIZE = 8192;
  415. const UINT32 ShadowRendering::MAX_UNUSED_FRAMES = 60;
  416. const UINT32 ShadowRendering::MIN_SHADOW_MAP_SIZE = 32;
  417. const UINT32 ShadowRendering::SHADOW_MAP_FADE_SIZE = 64;
  418. const UINT32 ShadowRendering::SHADOW_MAP_BORDER = 4;
  419. const float ShadowRendering::CASCADE_FRACTION_FADE = 0.1f;
  420. ShadowRendering::ShadowRendering(UINT32 shadowMapSize)
  421. : mShadowMapSize(shadowMapSize)
  422. {
  423. SPtr<VertexDataDesc> vertexDesc = VertexDataDesc::create();
  424. vertexDesc->addVertElem(VET_FLOAT3, VES_POSITION);
  425. mPositionOnlyVD = VertexDeclaration::create(vertexDesc);
  426. // Create plane index and vertex buffers
  427. {
  428. VERTEX_BUFFER_DESC vbDesc;
  429. vbDesc.numVerts = 8;
  430. vbDesc.usage = GBU_DYNAMIC;
  431. vbDesc.vertexSize = mPositionOnlyVD->getProperties().getVertexSize(0);
  432. mPlaneVB = VertexBuffer::create(vbDesc);
  433. INDEX_BUFFER_DESC ibDesc;
  434. ibDesc.indexType = IT_32BIT;
  435. ibDesc.numIndices = 12;
  436. mPlaneIB = IndexBuffer::create(ibDesc);
  437. UINT32 indices[] =
  438. {
  439. // Far plane, back facing
  440. 4, 7, 6,
  441. 4, 6, 5,
  442. // Near plane, front facing
  443. 0, 1, 2,
  444. 0, 2, 3
  445. };
  446. mPlaneIB->writeData(0, sizeof(indices), indices);
  447. }
  448. // Create frustum index and vertex buffers
  449. {
  450. VERTEX_BUFFER_DESC vbDesc;
  451. vbDesc.numVerts = 8;
  452. vbDesc.usage = GBU_DYNAMIC;
  453. vbDesc.vertexSize = mPositionOnlyVD->getProperties().getVertexSize(0);
  454. mFrustumVB = VertexBuffer::create(vbDesc);
  455. INDEX_BUFFER_DESC ibDesc;
  456. ibDesc.indexType = IT_32BIT;
  457. ibDesc.numIndices = 36;
  458. mFrustumIB = IndexBuffer::create(ibDesc);
  459. mFrustumIB->writeData(0, sizeof(AABox::CUBE_INDICES), AABox::CUBE_INDICES);
  460. }
  461. }
  462. void ShadowRendering::setShadowMapSize(UINT32 size)
  463. {
  464. if (mShadowMapSize == size)
  465. return;
  466. mCascadedShadowMaps.clear();
  467. mDynamicShadowMaps.clear();
  468. mShadowCubemaps.clear();
  469. }
  470. void ShadowRendering::renderShadowMaps(RendererScene& scene, const RendererViewGroup& viewGroup,
  471. const FrameInfo& frameInfo)
  472. {
  473. // Note: Currently all shadows are dynamic and are rebuilt every frame. I should later added support for static
  474. // shadow maps which can be used for immovable lights. Such a light can then maintain a set of shadow maps,
  475. // one of which is static and only effects the static geometry, while the rest are per-object shadow maps used
  476. // for dynamic objects. Then only a small subset of geometry needs to be redrawn, instead of everything.
  477. // Note: Add support for per-object shadows and a way to force a renderable to use per-object shadows. This can be
  478. // used for adding high quality shadows on specific objects (e.g. important characters during cinematics).
  479. const SceneInfo& sceneInfo = scene.getSceneInfo();
  480. const VisibilityInfo& visibility = viewGroup.getVisibilityInfo();
  481. // Clear all transient data from last frame
  482. mShadowInfos.clear();
  483. mSpotLightShadows.resize(sceneInfo.spotLights.size());
  484. mRadialLightShadows.resize(sceneInfo.radialLights.size());
  485. mDirectionalLightShadows.resize(sceneInfo.directionalLights.size());
  486. mSpotLightShadowOptions.clear();
  487. mRadialLightShadowOptions.clear();
  488. // Clear all dynamic light atlases
  489. for (auto& entry : mCascadedShadowMaps)
  490. entry.clear();
  491. for (auto& entry : mDynamicShadowMaps)
  492. entry.clear();
  493. for (auto& entry : mShadowCubemaps)
  494. entry.clear();
  495. // Determine shadow map sizes and sort them
  496. UINT32 shadowInfoCount = 0;
  497. for (UINT32 i = 0; i < (UINT32)sceneInfo.spotLights.size(); ++i)
  498. {
  499. const RendererLight& light = sceneInfo.spotLights[i];
  500. mSpotLightShadows[i].startIdx = shadowInfoCount;
  501. mSpotLightShadows[i].numShadows = 0;
  502. // Note: I'm using visibility across all views, while I could be using visibility for every view individually,
  503. // if I kept that information somewhere
  504. if (!light.internal->getCastsShadow() || !visibility.spotLights[i])
  505. continue;
  506. ShadowMapOptions options;
  507. options.lightIdx = i;
  508. float maxFadePercent;
  509. calcShadowMapProperties(light, viewGroup, SHADOW_MAP_BORDER, options.mapSize, options.fadePercents, maxFadePercent);
  510. // Don't render shadow maps that will end up nearly completely faded out
  511. if (maxFadePercent < 0.005f)
  512. continue;
  513. mSpotLightShadowOptions.push_back(options);
  514. shadowInfoCount++; // For now, always a single fully dynamic shadow for a single light, but that may change
  515. }
  516. for (UINT32 i = 0; i < (UINT32)sceneInfo.radialLights.size(); ++i)
  517. {
  518. const RendererLight& light = sceneInfo.radialLights[i];
  519. mRadialLightShadows[i].startIdx = shadowInfoCount;
  520. mRadialLightShadows[i].numShadows = 0;
  521. // Note: I'm using visibility across all views, while I could be using visibility for every view individually,
  522. // if I kept that information somewhere
  523. if (!light.internal->getCastsShadow() || !visibility.radialLights[i])
  524. continue;
  525. ShadowMapOptions options;
  526. options.lightIdx = i;
  527. float maxFadePercent;
  528. calcShadowMapProperties(light, viewGroup, 0, options.mapSize, options.fadePercents, maxFadePercent);
  529. // Don't render shadow maps that will end up nearly completely faded out
  530. if (maxFadePercent < 0.005f)
  531. continue;
  532. mRadialLightShadowOptions.push_back(options);
  533. shadowInfoCount++; // For now, always a single fully dynamic shadow for a single light, but that may change
  534. }
  535. // Sort spot lights by size so they fit neatly in the texture atlas
  536. std::sort(mSpotLightShadowOptions.begin(), mSpotLightShadowOptions.end(),
  537. [](const ShadowMapOptions& a, const ShadowMapOptions& b) { return a.mapSize > b.mapSize; } );
  538. // Reserve space for shadow infos
  539. mShadowInfos.resize(shadowInfoCount);
  540. // Deallocate unused textures (must be done before rendering shadows, in order to ensure indices don't change)
  541. for(auto iter = mDynamicShadowMaps.begin(); iter != mDynamicShadowMaps.end(); ++iter)
  542. {
  543. if(iter->getLastUsedCounter() >= MAX_UNUSED_FRAMES)
  544. {
  545. // These are always populated in order, so we can assume all following atlases are also empty
  546. mDynamicShadowMaps.erase(iter, mDynamicShadowMaps.end());
  547. break;
  548. }
  549. }
  550. for(auto iter = mCascadedShadowMaps.begin(); iter != mCascadedShadowMaps.end();)
  551. {
  552. if (iter->getLastUsedCounter() >= MAX_UNUSED_FRAMES)
  553. iter = mCascadedShadowMaps.erase(iter);
  554. else
  555. ++iter;
  556. }
  557. for(auto iter = mShadowCubemaps.begin(); iter != mShadowCubemaps.end();)
  558. {
  559. if (iter->getLastUsedCounter() >= MAX_UNUSED_FRAMES)
  560. iter = mShadowCubemaps.erase(iter);
  561. else
  562. ++iter;
  563. }
  564. // Render shadow maps
  565. for (UINT32 i = 0; i < (UINT32)sceneInfo.directionalLights.size(); ++i)
  566. {
  567. const RendererLight& light = sceneInfo.directionalLights[i];
  568. if (!light.internal->getCastsShadow())
  569. return;
  570. UINT32 numViews = viewGroup.getNumViews();
  571. mDirectionalLightShadows[i].viewShadows.resize(numViews);
  572. for (UINT32 j = 0; j < numViews; ++j)
  573. renderCascadedShadowMaps(*viewGroup.getView(j), i, scene, frameInfo);
  574. }
  575. for(auto& entry : mSpotLightShadowOptions)
  576. {
  577. UINT32 lightIdx = entry.lightIdx;
  578. renderSpotShadowMap(sceneInfo.spotLights[lightIdx], entry, scene, frameInfo);
  579. }
  580. for (auto& entry : mRadialLightShadowOptions)
  581. {
  582. UINT32 lightIdx = entry.lightIdx;
  583. renderRadialShadowMap(sceneInfo.radialLights[lightIdx], entry, scene, frameInfo);
  584. }
  585. }
  586. /**
  587. * Generates a frustum from the provided view-projection matrix.
  588. *
  589. * @param[in] invVP Inverse of the view-projection matrix to use for generating the frustum.
  590. * @param[out] worldFrustum Generated frustum planes, in world space.
  591. * @return Individual vertices of the frustum corners, in world space. Ordered using the
  592. * AABox::CornerEnum.
  593. */
  594. std::array<Vector3, 8> getFrustum(const Matrix4& invVP, ConvexVolume& worldFrustum)
  595. {
  596. std::array<Vector3, 8> output;
  597. RenderAPI& rapi = RenderAPI::instance();
  598. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  599. float flipY = 1.0f;
  600. if (rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown))
  601. flipY = -1.0f;
  602. AABox frustumCube(
  603. Vector3(-1, -1 * flipY, rapiInfo.getMinimumDepthInputValue()),
  604. Vector3(1, 1 * flipY, rapiInfo.getMaximumDepthInputValue())
  605. );
  606. for(size_t i = 0; i < output.size(); i++)
  607. {
  608. Vector3 corner = frustumCube.getCorner((AABox::Corner)i);
  609. output[i] = invVP.multiply(corner);
  610. }
  611. Vector<Plane> planes(6);
  612. planes[FRUSTUM_PLANE_NEAR] = Plane(output[AABox::NEAR_LEFT_BOTTOM], output[AABox::NEAR_RIGHT_BOTTOM], output[AABox::NEAR_RIGHT_TOP]);
  613. planes[FRUSTUM_PLANE_FAR] = Plane(output[AABox::FAR_LEFT_BOTTOM], output[AABox::FAR_LEFT_TOP], output[AABox::FAR_RIGHT_TOP]);
  614. planes[FRUSTUM_PLANE_LEFT] = Plane(output[AABox::NEAR_LEFT_BOTTOM], output[AABox::NEAR_LEFT_TOP], output[AABox::FAR_LEFT_TOP]);
  615. planes[FRUSTUM_PLANE_RIGHT] = Plane(output[AABox::FAR_RIGHT_TOP], output[AABox::NEAR_RIGHT_TOP], output[AABox::NEAR_RIGHT_BOTTOM]);
  616. planes[FRUSTUM_PLANE_TOP] = Plane(output[AABox::NEAR_LEFT_TOP], output[AABox::NEAR_RIGHT_TOP], output[AABox::FAR_RIGHT_TOP]);
  617. planes[FRUSTUM_PLANE_BOTTOM] = Plane(output[AABox::NEAR_LEFT_BOTTOM], output[AABox::FAR_LEFT_BOTTOM], output[AABox::FAR_RIGHT_BOTTOM]);
  618. worldFrustum = ConvexVolume(planes);
  619. return output;
  620. }
  621. /**
  622. * Converts a point in mixed space (clip_x, clip_y, view_z, view_w) to UV coordinates on a shadow map (x, y),
  623. * and normalized linear depth from the shadow caster's perspective (z).
  624. */
  625. Matrix4 createMixedToShadowUVMatrix(const Matrix4& viewP, const Matrix4& viewInvVP, const Rect2& shadowMapArea,
  626. float depthScale, float depthOffset, const Matrix4& shadowViewProj)
  627. {
  628. // Projects a point from (clip_x, clip_y, view_z, view_w) into clip space
  629. Matrix4 mixedToShadow = Matrix4::IDENTITY;
  630. mixedToShadow[2][2] = viewP[2][2];
  631. mixedToShadow[2][3] = viewP[2][3];
  632. mixedToShadow[3][2] = viewP[3][2];
  633. mixedToShadow[3][3] = 0.0f;
  634. // Projects a point in clip space back to homogeneus world space
  635. mixedToShadow = viewInvVP * mixedToShadow;
  636. // Projects a point in world space to shadow clip space
  637. mixedToShadow = shadowViewProj * mixedToShadow;
  638. // Convert shadow clip space coordinates to UV coordinates relative to the shadow map rectangle, and normalize
  639. // depth
  640. RenderAPI& rapi = RenderAPI::instance();
  641. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  642. float flipY = -1.0f;
  643. // Either of these flips the Y axis, but if they're both true they cancel out
  644. if (rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp) ^ rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown))
  645. flipY = -flipY;
  646. Matrix4 shadowMapTfrm
  647. (
  648. shadowMapArea.width * 0.5f, 0, 0, shadowMapArea.x + 0.5f * shadowMapArea.width,
  649. 0, flipY * shadowMapArea.height * 0.5f, 0, shadowMapArea.y + 0.5f * shadowMapArea.height,
  650. 0, 0, depthScale, depthOffset,
  651. 0, 0, 0, 1
  652. );
  653. return shadowMapTfrm * mixedToShadow;
  654. }
  655. void ShadowRendering::renderShadowOcclusion(const RendererView& view, UINT32 shadowQuality,
  656. const RendererLight& rendererLight, GBufferTextures gbuffer) const
  657. {
  658. const Light* light = rendererLight.internal;
  659. UINT32 lightIdx = light->getRendererId();
  660. auto viewProps = view.getProperties();
  661. const Matrix4& viewP = viewProps.projTransform;
  662. Matrix4 viewInvVP = viewProps.viewProjTransform.inverse();
  663. SPtr<GpuParamBlockBuffer> perViewBuffer = view.getPerViewBuffer();
  664. RenderAPI& rapi = RenderAPI::instance();
  665. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  666. // TODO - Calculate and set a scissor rectangle for the light
  667. SPtr<GpuParamBlockBuffer> shadowParamBuffer = gShadowProjectParamsDef.createBuffer();
  668. SPtr<GpuParamBlockBuffer> shadowOmniParamBuffer = gShadowProjectOmniParamsDef.createBuffer();
  669. UINT32 viewIdx = view.getViewIdx();
  670. Vector<const ShadowInfo*> shadowInfos;
  671. if(light->getType() == LightType::Radial)
  672. {
  673. const LightShadows& shadows = mRadialLightShadows[lightIdx];
  674. for(UINT32 i = 0; i < shadows.numShadows; ++i)
  675. {
  676. UINT32 shadowIdx = shadows.startIdx + i;
  677. const ShadowInfo& shadowInfo = mShadowInfos[shadowIdx];
  678. if (shadowInfo.fadePerView[viewIdx] < 0.005f)
  679. continue;
  680. for(UINT32 j = 0; j < 6; j++)
  681. gShadowProjectOmniParamsDef.gFaceVPMatrices.set(shadowOmniParamBuffer, shadowInfo.shadowVPTransforms[j], j);
  682. gShadowProjectOmniParamsDef.gDepthBias.set(shadowOmniParamBuffer, shadowInfo.depthBias);
  683. gShadowProjectOmniParamsDef.gFadePercent.set(shadowOmniParamBuffer, shadowInfo.fadePerView[viewIdx]);
  684. gShadowProjectOmniParamsDef.gInvResolution.set(shadowOmniParamBuffer, 1.0f / shadowInfo.area.width);
  685. const Transform& tfrm = light->getTransform();
  686. Vector4 lightPosAndRadius(tfrm.getPosition(), light->getAttenuationRadius());
  687. gShadowProjectOmniParamsDef.gLightPosAndRadius.set(shadowOmniParamBuffer, lightPosAndRadius);
  688. // Reduce shadow quality based on shadow map resolution for spot lights
  689. UINT32 effectiveShadowQuality = getShadowQuality(shadowQuality, shadowInfo.area.width, 2);
  690. // Check if viewer is inside the light bounds
  691. //// Expand the light bounds slightly to handle the case when the near plane is intersecting the light volume
  692. float lightRadius = light->getAttenuationRadius() + viewProps.nearPlane * 3.0f;
  693. bool viewerInsideVolume = (tfrm.getPosition() - viewProps.viewOrigin).length() < lightRadius;
  694. SPtr<Texture> shadowMap = mShadowCubemaps[shadowInfo.textureIdx].getTexture();
  695. ShadowProjectParams shadowParams(*light, shadowMap, 0, shadowOmniParamBuffer, perViewBuffer, gbuffer);
  696. ShadowProjectOmniMat* mat = ShadowProjectOmniMat::getVariation(effectiveShadowQuality, viewerInsideVolume,
  697. viewProps.numSamples > 1);
  698. mat->bind(shadowParams);
  699. gRendererUtility().draw(gRendererUtility().getRadialLightStencil());
  700. }
  701. }
  702. else // Directional & spot
  703. {
  704. shadowInfos.clear();
  705. bool isCSM = light->getType() == LightType::Directional;
  706. if(!isCSM)
  707. {
  708. const LightShadows& shadows = mSpotLightShadows[lightIdx];
  709. for (UINT32 i = 0; i < shadows.numShadows; ++i)
  710. {
  711. UINT32 shadowIdx = shadows.startIdx + i;
  712. const ShadowInfo& shadowInfo = mShadowInfos[shadowIdx];
  713. if (shadowInfo.fadePerView[viewIdx] < 0.005f)
  714. continue;
  715. shadowInfos.push_back(&shadowInfo);
  716. }
  717. }
  718. else // Directional
  719. {
  720. const LightShadows& shadows = mDirectionalLightShadows[lightIdx].viewShadows[viewIdx];
  721. if (shadows.numShadows > 0)
  722. {
  723. UINT32 mapIdx = shadows.startIdx;
  724. const ShadowCascadedMap& cascadedMap = mCascadedShadowMaps[mapIdx];
  725. // Render cascades in far to near order.
  726. // Note: If rendering other non-cascade maps they should be rendered after cascades.
  727. for (INT32 i = NUM_CASCADE_SPLITS - 1; i >= 0; i--)
  728. shadowInfos.push_back(&cascadedMap.getShadowInfo(i));
  729. }
  730. }
  731. for(auto& shadowInfo : shadowInfos)
  732. {
  733. float depthScale, depthOffset;
  734. // Depth range scale is already baked into the ortho projection matrix, so avoid doing it here
  735. if (isCSM)
  736. {
  737. // Need to map from NDC depth to [0, 1]
  738. depthScale = 1.0f / (rapiInfo.getMaximumDepthInputValue() - rapiInfo.getMinimumDepthInputValue());
  739. depthOffset = -rapiInfo.getMinimumDepthInputValue() * depthScale;
  740. }
  741. else
  742. {
  743. depthScale = 1.0f / shadowInfo->depthRange;
  744. depthOffset = 0.0f;
  745. }
  746. Matrix4 mixedToShadowUV = createMixedToShadowUVMatrix(viewP, viewInvVP, shadowInfo->normArea,
  747. depthScale, depthOffset, shadowInfo->shadowVPTransform);
  748. Vector2 shadowMapSize((float)shadowInfo->area.width, (float)shadowInfo->area.height);
  749. float transitionScale = getFadeTransition(*light, shadowInfo->subjectBounds.getRadius(),
  750. shadowInfo->depthRange, shadowInfo->area.width);
  751. gShadowProjectParamsDef.gFadePlaneDepth.set(shadowParamBuffer, shadowInfo->depthFade);
  752. gShadowProjectParamsDef.gMixedToShadowSpace.set(shadowParamBuffer, mixedToShadowUV);
  753. gShadowProjectParamsDef.gShadowMapSize.set(shadowParamBuffer, shadowMapSize);
  754. gShadowProjectParamsDef.gShadowMapSizeInv.set(shadowParamBuffer, 1.0f / shadowMapSize);
  755. gShadowProjectParamsDef.gSoftTransitionScale.set(shadowParamBuffer, transitionScale);
  756. if(isCSM)
  757. gShadowProjectParamsDef.gFadePercent.set(shadowParamBuffer, 1.0f);
  758. else
  759. gShadowProjectParamsDef.gFadePercent.set(shadowParamBuffer, shadowInfo->fadePerView[viewIdx]);
  760. if(shadowInfo->fadeRange == 0.0f)
  761. gShadowProjectParamsDef.gInvFadePlaneRange.set(shadowParamBuffer, 0.0f);
  762. else
  763. gShadowProjectParamsDef.gInvFadePlaneRange.set(shadowParamBuffer, 1.0f / shadowInfo->fadeRange);
  764. // Generate a stencil buffer to avoid evaluating pixels without any receiver geometry in the shadow area
  765. std::array<Vector3, 8> frustumVertices;
  766. UINT32 effectiveShadowQuality = shadowQuality;
  767. if(!isCSM)
  768. {
  769. ConvexVolume shadowFrustum;
  770. frustumVertices = getFrustum(shadowInfo->shadowVPTransform.inverse(), shadowFrustum);
  771. // Check if viewer is inside the frustum. Frustum is slightly expanded so that if the near plane is
  772. // intersecting the shadow frustum, it is counted as inside. This needs to be conservative as the code
  773. // for handling viewer outside the frustum will not properly render intersections with the near plane.
  774. bool viewerInsideFrustum = shadowFrustum.contains(viewProps.viewOrigin, viewProps.nearPlane * 3.0f);
  775. ShadowProjectStencilMat* mat = ShadowProjectStencilMat::getVariation(false, viewerInsideFrustum);
  776. mat->bind(perViewBuffer);
  777. drawFrustum(frustumVertices);
  778. // Reduce shadow quality based on shadow map resolution for spot lights
  779. effectiveShadowQuality = getShadowQuality(shadowQuality, shadowInfo->area.width, 2);
  780. }
  781. else
  782. {
  783. // Need to generate near and far planes to clip the geometry within the current CSM slice.
  784. // Note: If the render API supports built-in depth bound tests that could be used instead.
  785. Vector3 near = viewProps.projTransform.multiply(Vector3(0, 0, -shadowInfo->depthNear));
  786. Vector3 far = viewProps.projTransform.multiply(Vector3(0, 0, -shadowInfo->depthFar));
  787. ShadowProjectStencilMat* mat = ShadowProjectStencilMat::getVariation(true, true);
  788. mat->bind(perViewBuffer);
  789. drawNearFarPlanes(near.z, far.z, shadowInfo->cascadeIdx != 0);
  790. }
  791. SPtr<Texture> shadowMap;
  792. UINT32 shadowMapFace = 0;
  793. if(!isCSM)
  794. shadowMap = mDynamicShadowMaps[shadowInfo->textureIdx].getTexture();
  795. else
  796. {
  797. shadowMap = mCascadedShadowMaps[shadowInfo->textureIdx].getTexture();
  798. shadowMapFace = shadowInfo->cascadeIdx;
  799. }
  800. ShadowProjectParams shadowParams(*light, shadowMap, shadowMapFace, shadowParamBuffer, perViewBuffer,
  801. gbuffer);
  802. ShadowProjectMat* mat = ShadowProjectMat::getVariation(effectiveShadowQuality, isCSM, viewProps.numSamples > 1);
  803. mat->bind(shadowParams);
  804. if (!isCSM)
  805. drawFrustum(frustumVertices);
  806. else
  807. gRendererUtility().drawScreenQuad();
  808. }
  809. }
  810. }
  811. void ShadowRendering::renderCascadedShadowMaps(const RendererView& view, UINT32 lightIdx, RendererScene& scene,
  812. const FrameInfo& frameInfo)
  813. {
  814. UINT32 viewIdx = view.getViewIdx();
  815. LightShadows& lightShadows = mDirectionalLightShadows[lightIdx].viewShadows[viewIdx];
  816. if (!view.getRenderSettings().enableShadows)
  817. {
  818. lightShadows.startIdx = -1;
  819. lightShadows.numShadows = 0;
  820. return;
  821. }
  822. // Note: Currently I'm using spherical bounds for the cascaded frustum which might result in non-optimal usage
  823. // of the shadow map. A different approach would be to generate a bounding box and then both adjust the aspect
  824. // ratio (and therefore dimensions) of the shadow map, as well as rotate the camera so the visible area best fits
  825. // in the map. It remains to be seen if this is viable.
  826. const SceneInfo& sceneInfo = scene.getSceneInfo();
  827. const RendererLight& rendererLight = sceneInfo.directionalLights[lightIdx];
  828. Light* light = rendererLight.internal;
  829. RenderAPI& rapi = RenderAPI::instance();
  830. const Transform& tfrm = light->getTransform();
  831. Vector3 lightDir = -tfrm.getRotation().zAxis();
  832. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  833. ShadowInfo shadowInfo;
  834. shadowInfo.lightIdx = lightIdx;
  835. shadowInfo.textureIdx = -1;
  836. UINT32 mapSize = std::min(mShadowMapSize, MAX_ATLAS_SIZE);
  837. shadowInfo.area = Rect2I(0, 0, mapSize, mapSize);
  838. shadowInfo.updateNormArea(mapSize);
  839. for (UINT32 i = 0; i < (UINT32)mCascadedShadowMaps.size(); i++)
  840. {
  841. ShadowCascadedMap& shadowMap = mCascadedShadowMaps[i];
  842. if (!shadowMap.isUsed() && shadowMap.getSize() == mapSize)
  843. {
  844. shadowInfo.textureIdx = i;
  845. shadowMap.markAsUsed();
  846. break;
  847. }
  848. }
  849. if (shadowInfo.textureIdx == (UINT32)-1)
  850. {
  851. shadowInfo.textureIdx = (UINT32)mCascadedShadowMaps.size();
  852. mCascadedShadowMaps.push_back(ShadowCascadedMap(mapSize));
  853. ShadowCascadedMap& shadowMap = mCascadedShadowMaps.back();
  854. shadowMap.markAsUsed();
  855. }
  856. ShadowCascadedMap& shadowMap = mCascadedShadowMaps[shadowInfo.textureIdx];
  857. Quaternion lightRotation(BsIdentity);
  858. lightRotation.lookRotation(-tfrm.getRotation().zAxis());
  859. Matrix4 viewMat = Matrix4::view(tfrm.getPosition(), lightRotation);
  860. for (UINT32 i = 0; i < NUM_CASCADE_SPLITS; ++i)
  861. {
  862. Sphere frustumBounds;
  863. ConvexVolume cascadeCullVolume = getCSMSplitFrustum(view, -lightDir, i, NUM_CASCADE_SPLITS, frustumBounds);
  864. // Move the light at the boundary of the subject frustum, so we don't waste depth range
  865. Vector3 frustumCenterViewSpace = viewMat.multiply(frustumBounds.getCenter());
  866. float minSubjectDepth = -frustumCenterViewSpace.z - frustumBounds.getRadius();
  867. float maxSubjectDepth = minSubjectDepth + frustumBounds.getRadius() * 2.0f;
  868. shadowInfo.depthRange = maxSubjectDepth - minSubjectDepth;
  869. Vector3 offsetLightPos = tfrm.getPosition() + lightDir * minSubjectDepth;
  870. Matrix4 offsetViewMat = Matrix4::view(offsetLightPos, lightRotation);
  871. float orthoSize = frustumBounds.getRadius() * 0.5f;
  872. Matrix4 proj = Matrix4::projectionOrthographic(-orthoSize, orthoSize, orthoSize, -orthoSize, 0.0f,
  873. shadowInfo.depthRange);
  874. RenderAPI::instance().convertProjectionMatrix(proj, proj);
  875. shadowInfo.cascadeIdx = i;
  876. shadowInfo.shadowVPTransform = proj * offsetViewMat;
  877. // Determine split range
  878. float splitNear = getCSMSplitDistance(view, i, NUM_CASCADE_SPLITS);
  879. float splitFar = getCSMSplitDistance(view, i + 1, NUM_CASCADE_SPLITS);
  880. shadowInfo.depthNear = splitNear;
  881. shadowInfo.depthFade = splitFar;
  882. shadowInfo.subjectBounds = frustumBounds;
  883. if ((UINT32)(i + 1) < NUM_CASCADE_SPLITS)
  884. shadowInfo.fadeRange = CASCADE_FRACTION_FADE * (shadowInfo.depthFade - shadowInfo.depthNear);
  885. else
  886. shadowInfo.fadeRange = 0.0f;
  887. shadowInfo.depthFar = shadowInfo.depthFade + shadowInfo.fadeRange;
  888. shadowInfo.depthBias = getDepthBias(*light, frustumBounds.getRadius(), shadowInfo.depthRange, mapSize);
  889. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, shadowInfo.depthBias);
  890. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / shadowInfo.depthRange);
  891. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, shadowInfo.shadowVPTransform);
  892. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  893. rapi.setRenderTarget(shadowMap.getTarget(i));
  894. rapi.clearRenderTarget(FBT_DEPTH);
  895. ShadowDepthDirectionalMat* depthDirMat = ShadowDepthDirectionalMat::get();
  896. depthDirMat->bind(shadowParamsBuffer);
  897. for (UINT32 j = 0; j < sceneInfo.renderables.size(); j++)
  898. {
  899. if (!cascadeCullVolume.intersects(sceneInfo.renderableCullInfos[j].bounds.getSphere()))
  900. continue;
  901. scene.prepareRenderable(j, frameInfo);
  902. RendererObject* renderable = sceneInfo.renderables[j];
  903. depthDirMat->setPerObjectBuffer(renderable->perObjectParamBuffer);
  904. for (auto& element : renderable->elements)
  905. {
  906. if (element.morphVertexDeclaration == nullptr)
  907. gRendererUtility().draw(element.mesh, element.subMesh);
  908. else
  909. gRendererUtility().drawMorph(element.mesh, element.subMesh, element.morphShapeBuffer,
  910. element.morphVertexDeclaration);
  911. }
  912. }
  913. shadowMap.setShadowInfo(i, shadowInfo);
  914. }
  915. lightShadows.startIdx = shadowInfo.textureIdx;
  916. lightShadows.numShadows = 1;
  917. }
  918. void ShadowRendering::renderSpotShadowMap(const RendererLight& rendererLight, const ShadowMapOptions& options,
  919. RendererScene& scene, const FrameInfo& frameInfo)
  920. {
  921. Light* light = rendererLight.internal;
  922. const SceneInfo& sceneInfo = scene.getSceneInfo();
  923. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  924. ShadowInfo mapInfo;
  925. mapInfo.fadePerView = options.fadePercents;
  926. mapInfo.lightIdx = options.lightIdx;
  927. mapInfo.cascadeIdx = -1;
  928. bool foundSpace = false;
  929. for (UINT32 i = 0; i < (UINT32)mDynamicShadowMaps.size(); i++)
  930. {
  931. ShadowMapAtlas& atlas = mDynamicShadowMaps[i];
  932. if (atlas.addMap(options.mapSize, mapInfo.area, SHADOW_MAP_BORDER))
  933. {
  934. mapInfo.textureIdx = i;
  935. foundSpace = true;
  936. break;
  937. }
  938. }
  939. if (!foundSpace)
  940. {
  941. mapInfo.textureIdx = (UINT32)mDynamicShadowMaps.size();
  942. mDynamicShadowMaps.push_back(ShadowMapAtlas(MAX_ATLAS_SIZE));
  943. ShadowMapAtlas& atlas = mDynamicShadowMaps.back();
  944. atlas.addMap(options.mapSize, mapInfo.area, SHADOW_MAP_BORDER);
  945. }
  946. mapInfo.updateNormArea(MAX_ATLAS_SIZE);
  947. ShadowMapAtlas& atlas = mDynamicShadowMaps[mapInfo.textureIdx];
  948. RenderAPI& rapi = RenderAPI::instance();
  949. rapi.setRenderTarget(atlas.getTarget());
  950. rapi.setViewport(mapInfo.normArea);
  951. rapi.clearViewport(FBT_DEPTH);
  952. mapInfo.depthNear = 0.05f;
  953. mapInfo.depthFar = light->getAttenuationRadius();
  954. mapInfo.depthFade = mapInfo.depthFar;
  955. mapInfo.fadeRange = 0.0f;
  956. mapInfo.depthRange = mapInfo.depthFar - mapInfo.depthNear;
  957. mapInfo.depthBias = getDepthBias(*light, light->getBounds().getRadius(), mapInfo.depthRange, options.mapSize);
  958. mapInfo.subjectBounds = light->getBounds();
  959. Quaternion lightRotation(BsIdentity);
  960. lightRotation.lookRotation(-light->getTransform().getRotation().zAxis());
  961. Matrix4 view = Matrix4::view(rendererLight.getShiftedLightPosition(), lightRotation);
  962. Matrix4 proj = Matrix4::projectionPerspective(light->getSpotAngle(), 1.0f, 0.05f, light->getAttenuationRadius());
  963. ConvexVolume localFrustum = ConvexVolume(proj);
  964. RenderAPI::instance().convertProjectionMatrix(proj, proj);
  965. mapInfo.shadowVPTransform = proj * view;
  966. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, mapInfo.depthBias);
  967. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / mapInfo.depthRange);
  968. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, mapInfo.shadowVPTransform);
  969. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  970. ShadowDepthNormalMat* depthNormalMat = ShadowDepthNormalMat::get();
  971. depthNormalMat->bind(shadowParamsBuffer);
  972. const Vector<Plane>& frustumPlanes = localFrustum.getPlanes();
  973. Matrix4 worldMatrix = view.transpose();
  974. Vector<Plane> worldPlanes(frustumPlanes.size());
  975. UINT32 j = 0;
  976. for (auto& plane : frustumPlanes)
  977. {
  978. worldPlanes[j] = worldMatrix.multiplyAffine(plane);
  979. j++;
  980. }
  981. ConvexVolume worldFrustum(worldPlanes);
  982. for (UINT32 i = 0; i < sceneInfo.renderables.size(); i++)
  983. {
  984. if (!worldFrustum.intersects(sceneInfo.renderableCullInfos[i].bounds.getSphere()))
  985. continue;
  986. scene.prepareRenderable(i, frameInfo);
  987. RendererObject* renderable = sceneInfo.renderables[i];
  988. depthNormalMat->setPerObjectBuffer(renderable->perObjectParamBuffer);
  989. for (auto& element : renderable->elements)
  990. {
  991. if (element.morphVertexDeclaration == nullptr)
  992. gRendererUtility().draw(element.mesh, element.subMesh);
  993. else
  994. gRendererUtility().drawMorph(element.mesh, element.subMesh, element.morphShapeBuffer,
  995. element.morphVertexDeclaration);
  996. }
  997. }
  998. // Restore viewport
  999. rapi.setViewport(Rect2(0.0f, 0.0f, 1.0f, 1.0f));
  1000. LightShadows& lightShadows = mSpotLightShadows[options.lightIdx];
  1001. mShadowInfos[lightShadows.startIdx + lightShadows.numShadows] = mapInfo;
  1002. lightShadows.numShadows++;
  1003. }
  1004. void ShadowRendering::renderRadialShadowMap(const RendererLight& rendererLight,
  1005. const ShadowMapOptions& options, RendererScene& scene, const FrameInfo& frameInfo)
  1006. {
  1007. Light* light = rendererLight.internal;
  1008. const SceneInfo& sceneInfo = scene.getSceneInfo();
  1009. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  1010. SPtr<GpuParamBlockBuffer> shadowCubeMatricesBuffer = gShadowCubeMatricesDef.createBuffer();
  1011. SPtr<GpuParamBlockBuffer> shadowCubeMasksBuffer = gShadowCubeMasksDef.createBuffer();
  1012. ShadowInfo mapInfo;
  1013. mapInfo.lightIdx = options.lightIdx;
  1014. mapInfo.textureIdx = -1;
  1015. mapInfo.fadePerView = options.fadePercents;
  1016. mapInfo.cascadeIdx = -1;
  1017. mapInfo.area = Rect2I(0, 0, options.mapSize, options.mapSize);
  1018. mapInfo.updateNormArea(options.mapSize);
  1019. for (UINT32 i = 0; i < (UINT32)mShadowCubemaps.size(); i++)
  1020. {
  1021. ShadowCubemap& cubemap = mShadowCubemaps[i];
  1022. if (!cubemap.isUsed() && cubemap.getSize() == options.mapSize)
  1023. {
  1024. mapInfo.textureIdx = i;
  1025. cubemap.markAsUsed();
  1026. break;
  1027. }
  1028. }
  1029. if (mapInfo.textureIdx == (UINT32)-1)
  1030. {
  1031. mapInfo.textureIdx = (UINT32)mShadowCubemaps.size();
  1032. mShadowCubemaps.push_back(ShadowCubemap(options.mapSize));
  1033. ShadowCubemap& cubemap = mShadowCubemaps.back();
  1034. cubemap.markAsUsed();
  1035. }
  1036. ShadowCubemap& cubemap = mShadowCubemaps[mapInfo.textureIdx];
  1037. mapInfo.depthNear = 0.05f;
  1038. mapInfo.depthFar = light->getAttenuationRadius();
  1039. mapInfo.depthFade = mapInfo.depthFar;
  1040. mapInfo.fadeRange = 0.0f;
  1041. mapInfo.depthRange = mapInfo.depthFar - mapInfo.depthNear;
  1042. mapInfo.depthBias = getDepthBias(*light, light->getBounds().getRadius(), mapInfo.depthRange, options.mapSize);
  1043. mapInfo.subjectBounds = light->getBounds();
  1044. Matrix4 proj = Matrix4::projectionPerspective(Degree(90.0f), 1.0f, 0.05f, light->getAttenuationRadius());
  1045. ConvexVolume localFrustum(proj);
  1046. RenderAPI& rapi = RenderAPI::instance();
  1047. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  1048. rapi.convertProjectionMatrix(proj, proj);
  1049. // Render cubemaps upside down if necessary
  1050. Matrix4 adjustedProj = proj;
  1051. if(rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp))
  1052. {
  1053. // All big APIs use the same cubemap sampling coordinates, as well as the same face order. But APIs that
  1054. // use bottom-up UV coordinates require the cubemap faces to be stored upside down in order to get the same
  1055. // behaviour. APIs that use an upside-down NDC Y axis have the same problem as the rendered image will be
  1056. // upside down, but this is handled by the projection matrix. If both of those are enabled, then the effect
  1057. // cancels out.
  1058. adjustedProj[1][1] = -proj[1][1];
  1059. }
  1060. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, mapInfo.depthBias);
  1061. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / mapInfo.depthRange);
  1062. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, Matrix4::IDENTITY);
  1063. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  1064. Matrix4 viewOffsetMat = Matrix4::translation(-light->getTransform().getPosition());
  1065. ConvexVolume frustums[6];
  1066. Vector<Plane> boundingPlanes;
  1067. for (UINT32 i = 0; i < 6; i++)
  1068. {
  1069. // Calculate view matrix
  1070. Vector3 forward;
  1071. Vector3 up = Vector3::UNIT_Y;
  1072. switch (i)
  1073. {
  1074. case CF_PositiveX:
  1075. forward = Vector3::UNIT_X;
  1076. break;
  1077. case CF_NegativeX:
  1078. forward = -Vector3::UNIT_X;
  1079. break;
  1080. case CF_PositiveY:
  1081. forward = Vector3::UNIT_Y;
  1082. up = -Vector3::UNIT_Z;
  1083. break;
  1084. case CF_NegativeY:
  1085. forward = -Vector3::UNIT_Y;
  1086. up = Vector3::UNIT_Z;
  1087. break;
  1088. case CF_PositiveZ:
  1089. forward = Vector3::UNIT_Z;
  1090. break;
  1091. case CF_NegativeZ:
  1092. forward = -Vector3::UNIT_Z;
  1093. break;
  1094. }
  1095. Vector3 right = Vector3::cross(up, forward);
  1096. Matrix3 viewRotationMat = Matrix3(right, up, -forward);
  1097. Matrix4 view = Matrix4(viewRotationMat) * viewOffsetMat;
  1098. mapInfo.shadowVPTransforms[i] = proj * view;
  1099. Matrix4 shadowViewProj = adjustedProj * view;
  1100. gShadowCubeMatricesDef.gFaceVPMatrices.set(shadowCubeMatricesBuffer, shadowViewProj, i);
  1101. // Calculate world frustum for culling
  1102. const Vector<Plane>& frustumPlanes = localFrustum.getPlanes();
  1103. Matrix4 worldMatrix = view.transpose();
  1104. Vector<Plane> worldPlanes(frustumPlanes.size());
  1105. UINT32 j = 0;
  1106. for (auto& plane : frustumPlanes)
  1107. {
  1108. worldPlanes[j] = worldMatrix.multiplyAffine(plane);
  1109. j++;
  1110. }
  1111. frustums[i] = ConvexVolume(worldPlanes);
  1112. // Register far plane of all frustums
  1113. boundingPlanes.push_back(worldPlanes.back());
  1114. }
  1115. rapi.setRenderTarget(cubemap.getTarget());
  1116. rapi.clearRenderTarget(FBT_DEPTH);
  1117. ShadowDepthCubeMat* depthCubeMat = ShadowDepthCubeMat::get();
  1118. depthCubeMat->bind(shadowParamsBuffer, shadowCubeMatricesBuffer);
  1119. // First cull against a global volume
  1120. ConvexVolume boundingVolume(boundingPlanes);
  1121. for (UINT32 i = 0; i < sceneInfo.renderables.size(); i++)
  1122. {
  1123. const Sphere& bounds = sceneInfo.renderableCullInfos[i].bounds.getSphere();
  1124. if (!boundingVolume.intersects(bounds))
  1125. continue;
  1126. scene.prepareRenderable(i, frameInfo);
  1127. for(UINT32 j = 0; j < 6; j++)
  1128. {
  1129. int mask = frustums[j].intersects(bounds) ? 1 : 0;
  1130. gShadowCubeMasksDef.gFaceMasks.set(shadowCubeMasksBuffer, mask, j);
  1131. }
  1132. RendererObject* renderable = sceneInfo.renderables[i];
  1133. depthCubeMat->setPerObjectBuffer(renderable->perObjectParamBuffer, shadowCubeMasksBuffer);
  1134. for (auto& element : renderable->elements)
  1135. {
  1136. if (element.morphVertexDeclaration == nullptr)
  1137. gRendererUtility().draw(element.mesh, element.subMesh);
  1138. else
  1139. gRendererUtility().drawMorph(element.mesh, element.subMesh, element.morphShapeBuffer,
  1140. element.morphVertexDeclaration);
  1141. }
  1142. }
  1143. LightShadows& lightShadows = mRadialLightShadows[options.lightIdx];
  1144. mShadowInfos[lightShadows.startIdx + lightShadows.numShadows] = mapInfo;
  1145. lightShadows.numShadows++;
  1146. }
  1147. void ShadowRendering::calcShadowMapProperties(const RendererLight& light, const RendererViewGroup& viewGroup,
  1148. UINT32 border, UINT32& size, SmallVector<float, 4>& fadePercents, float& maxFadePercent) const
  1149. {
  1150. const static float SHADOW_TEXELS_PER_PIXEL = 1.0f;
  1151. // Find a view in which the light has the largest radius
  1152. float maxMapSize = 0.0f;
  1153. maxFadePercent = 0.0f;
  1154. for (int i = 0; i < (int)viewGroup.getNumViews(); ++i)
  1155. {
  1156. const RendererView& view = *viewGroup.getView(i);
  1157. const RendererViewProperties& viewProps = view.getProperties();
  1158. const RenderSettings& viewSettings = view.getRenderSettings();
  1159. if(!viewSettings.enableShadows)
  1160. fadePercents.push_back(0.0f);
  1161. {
  1162. // Approximation for screen space sphere radius: screenSize * 0.5 * cot(fov) * radius / Z, where FOV is the
  1163. // largest one
  1164. //// First get sphere depth
  1165. const Matrix4& viewVP = viewProps.viewProjTransform;
  1166. float depth = viewVP.multiply(Vector4(light.internal->getTransform().getPosition(), 1.0f)).w;
  1167. // This is just 1/tan(fov), for both horz. and vert. FOV
  1168. float viewScaleX = viewProps.projTransform[0][0];
  1169. float viewScaleY = viewProps.projTransform[1][1];
  1170. float screenScaleX = viewScaleX * viewProps.viewRect.width * 0.5f;
  1171. float screenScaleY = viewScaleY * viewProps.viewRect.height * 0.5f;
  1172. float screenScale = std::max(screenScaleX, screenScaleY);
  1173. //// Calc radius (clamp if too close to avoid massive numbers)
  1174. float radiusNDC = light.internal->getBounds().getRadius() / std::max(depth, 1.0f);
  1175. //// Radius of light bounds in percent of the view surface, multiplied by screen size in pixels
  1176. float radiusScreen = radiusNDC * screenScale;
  1177. float optimalMapSize = SHADOW_TEXELS_PER_PIXEL * radiusScreen;
  1178. maxMapSize = std::max(maxMapSize, optimalMapSize);
  1179. // Determine if the shadow should fade out
  1180. float fadePercent = Math::lerp01(optimalMapSize, (float)MIN_SHADOW_MAP_SIZE, (float)SHADOW_MAP_FADE_SIZE);
  1181. fadePercents.push_back(fadePercent);
  1182. maxFadePercent = std::max(maxFadePercent, fadePercent);
  1183. }
  1184. }
  1185. // If light fully (or nearly fully) covers the screen, use full shadow map resolution, otherwise
  1186. // scale it down to smaller power of two, while clamping to minimal allowed resolution
  1187. UINT32 effectiveMapSize = Bitwise::nextPow2((UINT32)maxMapSize);
  1188. effectiveMapSize = Math::clamp(effectiveMapSize, MIN_SHADOW_MAP_SIZE, mShadowMapSize);
  1189. // Leave room for border
  1190. size = std::max(effectiveMapSize - 2 * border, 1u);
  1191. }
  1192. void ShadowRendering::drawNearFarPlanes(float near, float far, bool drawNear) const
  1193. {
  1194. RenderAPI& rapi = RenderAPI::instance();
  1195. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  1196. float flipY = rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown) ? -1.0f : 1.0f;
  1197. // Update VB with new vertices
  1198. Vector3 vertices[8] =
  1199. {
  1200. // Near plane
  1201. { -1.0f, -1.0f * flipY, near },
  1202. { 1.0f, -1.0f * flipY, near },
  1203. { 1.0f, 1.0f * flipY, near },
  1204. { -1.0f, 1.0f * flipY, near },
  1205. // Far plane
  1206. { -1.0f, -1.0f * flipY, far },
  1207. { 1.0f, -1.0f * flipY, far },
  1208. { 1.0f, 1.0f * flipY, far },
  1209. { -1.0f, 1.0f * flipY, far },
  1210. };
  1211. mPlaneVB->writeData(0, sizeof(vertices), vertices, BWT_DISCARD);
  1212. // Draw the mesh
  1213. rapi.setVertexDeclaration(mPositionOnlyVD);
  1214. rapi.setVertexBuffers(0, &mPlaneVB, 1);
  1215. rapi.setIndexBuffer(mPlaneIB);
  1216. rapi.setDrawOperation(DOT_TRIANGLE_LIST);
  1217. rapi.drawIndexed(0, drawNear ? 12 : 6, 0, drawNear ? 8 : 4);
  1218. }
  1219. void ShadowRendering::drawFrustum(const std::array<Vector3, 8>& corners) const
  1220. {
  1221. RenderAPI& rapi = RenderAPI::instance();
  1222. // Update VB with new vertices
  1223. mFrustumVB->writeData(0, sizeof(Vector3) * 8, corners.data(), BWT_DISCARD);
  1224. // Draw the mesh
  1225. rapi.setVertexDeclaration(mPositionOnlyVD);
  1226. rapi.setVertexBuffers(0, &mFrustumVB, 1);
  1227. rapi.setIndexBuffer(mFrustumIB);
  1228. rapi.setDrawOperation(DOT_TRIANGLE_LIST);
  1229. rapi.drawIndexed(0, 36, 0, 8);
  1230. }
  1231. UINT32 ShadowRendering::getShadowQuality(UINT32 requestedQuality, UINT32 shadowMapResolution, UINT32 minAllowedQuality)
  1232. {
  1233. static const UINT32 TARGET_RESOLUTION = 512;
  1234. // If shadow map resolution is smaller than some target resolution drop the number of PCF samples (shadow quality)
  1235. // so that the penumbra better matches with larger sized shadow maps.
  1236. while(requestedQuality > minAllowedQuality && shadowMapResolution < TARGET_RESOLUTION)
  1237. {
  1238. shadowMapResolution *= 2;
  1239. requestedQuality = std::max(requestedQuality - 1, 1U);
  1240. }
  1241. return requestedQuality;
  1242. }
  1243. ConvexVolume ShadowRendering::getCSMSplitFrustum(const RendererView& view, const Vector3& lightDir, UINT32 cascade,
  1244. UINT32 numCascades, Sphere& outBounds)
  1245. {
  1246. // Determine split range
  1247. float splitNear = getCSMSplitDistance(view, cascade, numCascades);
  1248. float splitFar = getCSMSplitDistance(view, cascade + 1, numCascades);
  1249. // Calculate the eight vertices of the split frustum
  1250. auto& viewProps = view.getProperties();
  1251. const Matrix4& projMat = viewProps.projTransform;
  1252. float aspect;
  1253. float nearHalfWidth, nearHalfHeight;
  1254. float farHalfWidth, farHalfHeight;
  1255. if(viewProps.projType == PT_PERSPECTIVE)
  1256. {
  1257. aspect = fabs(projMat[0][0] / projMat[1][1]);
  1258. float tanHalfFOV = 1.0f / projMat[0][0];
  1259. nearHalfWidth = splitNear * tanHalfFOV;
  1260. nearHalfHeight = nearHalfWidth * aspect;
  1261. farHalfWidth = splitFar * tanHalfFOV;
  1262. farHalfHeight = farHalfWidth * aspect;
  1263. }
  1264. else
  1265. {
  1266. aspect = projMat[0][0] / projMat[1][1];
  1267. nearHalfWidth = farHalfWidth = projMat[0][0] / 4.0f;
  1268. nearHalfHeight = farHalfHeight = projMat[1][1] / 4.0f;
  1269. }
  1270. const Matrix4& viewMat = viewProps.viewTransform;
  1271. Vector3 cameraRight = Vector3(viewMat[0]);
  1272. Vector3 cameraUp = Vector3(viewMat[1]);
  1273. const Vector3& viewOrigin = viewProps.viewOrigin;
  1274. const Vector3& viewDir = viewProps.viewDirection;
  1275. Vector3 frustumVerts[] =
  1276. {
  1277. viewOrigin + viewDir * splitNear - cameraRight * nearHalfWidth + cameraUp * nearHalfHeight, // Near, left, top
  1278. viewOrigin + viewDir * splitNear + cameraRight * nearHalfWidth + cameraUp * nearHalfHeight, // Near, right, top
  1279. viewOrigin + viewDir * splitNear + cameraRight * nearHalfWidth - cameraUp * nearHalfHeight, // Near, right, bottom
  1280. viewOrigin + viewDir * splitNear - cameraRight * nearHalfWidth - cameraUp * nearHalfHeight, // Near, left, bottom
  1281. viewOrigin + viewDir * splitFar - cameraRight * farHalfWidth + cameraUp * farHalfHeight, // Far, left, top
  1282. viewOrigin + viewDir * splitFar + cameraRight * farHalfWidth + cameraUp * farHalfHeight, // Far, right, top
  1283. viewOrigin + viewDir * splitFar + cameraRight * farHalfWidth - cameraUp * farHalfHeight, // Far, right, bottom
  1284. viewOrigin + viewDir * splitFar - cameraRight * farHalfWidth - cameraUp * farHalfHeight, // Far, left, bottom
  1285. };
  1286. // Calculate the bounding sphere of the frustum
  1287. float diagonalNearSq = nearHalfWidth * nearHalfWidth + nearHalfHeight * nearHalfHeight;
  1288. float diagonalFarSq = farHalfWidth * farHalfWidth + farHalfHeight * farHalfHeight;
  1289. float length = splitFar - splitNear;
  1290. float offset = (diagonalNearSq - diagonalFarSq) / (2 * length) + length * 0.5f;
  1291. float distToCenter = Math::clamp(splitFar - offset, splitNear, splitFar);
  1292. Vector3 center = viewOrigin + viewDir * distToCenter;
  1293. float radius = 0.0f;
  1294. for (auto& entry : frustumVerts)
  1295. radius = std::max(radius, center.squaredDistance(entry));
  1296. radius = std::max((float)sqrt(radius), 1.0f);
  1297. outBounds = Sphere(center, radius);
  1298. // Generate light frustum planes
  1299. Plane viewPlanes[6];
  1300. viewPlanes[FRUSTUM_PLANE_NEAR] = Plane(frustumVerts[0], frustumVerts[1], frustumVerts[2]);
  1301. viewPlanes[FRUSTUM_PLANE_FAR] = Plane(frustumVerts[5], frustumVerts[4], frustumVerts[7]);
  1302. viewPlanes[FRUSTUM_PLANE_LEFT] = Plane(frustumVerts[4], frustumVerts[0], frustumVerts[3]);
  1303. viewPlanes[FRUSTUM_PLANE_RIGHT] = Plane(frustumVerts[1], frustumVerts[5], frustumVerts[6]);
  1304. viewPlanes[FRUSTUM_PLANE_TOP] = Plane(frustumVerts[4], frustumVerts[5], frustumVerts[1]);
  1305. viewPlanes[FRUSTUM_PLANE_BOTTOM] = Plane(frustumVerts[3], frustumVerts[2], frustumVerts[6]);
  1306. Vector<Plane> lightVolume;
  1307. //// Add camera's planes facing towards the lights (forming the back of the volume)
  1308. for(auto& entry : viewPlanes)
  1309. {
  1310. if (entry.normal.dot(lightDir) < 0.0f)
  1311. lightVolume.push_back(entry);
  1312. }
  1313. //// Determine edge planes by testing adjacent planes with different facing
  1314. ////// Pairs of frustum planes that share an edge
  1315. UINT32 adjacentPlanes[][2] =
  1316. {
  1317. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_LEFT },
  1318. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_RIGHT },
  1319. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_TOP },
  1320. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_BOTTOM },
  1321. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_LEFT },
  1322. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_RIGHT },
  1323. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_TOP },
  1324. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_BOTTOM },
  1325. { FRUSTUM_PLANE_LEFT, FRUSTUM_PLANE_TOP },
  1326. { FRUSTUM_PLANE_TOP, FRUSTUM_PLANE_RIGHT },
  1327. { FRUSTUM_PLANE_RIGHT, FRUSTUM_PLANE_BOTTOM },
  1328. { FRUSTUM_PLANE_BOTTOM, FRUSTUM_PLANE_LEFT },
  1329. };
  1330. ////// Vertex indices of edges on the boundary between two planes
  1331. UINT32 sharedEdges[][2] =
  1332. {
  1333. { 3, 0 },{ 1, 2 },{ 0, 1 },{ 2, 3 },
  1334. { 4, 7 },{ 6, 5 },{ 5, 4 },{ 7, 6 },
  1335. { 4, 0 },{ 5, 1 },{ 6, 2 },{ 7, 3 }
  1336. };
  1337. for(UINT32 i = 0; i < 12; i++)
  1338. {
  1339. const Plane& planeA = viewPlanes[adjacentPlanes[i][0]];
  1340. const Plane& planeB = viewPlanes[adjacentPlanes[i][1]];
  1341. float dotA = planeA.normal.dot(lightDir);
  1342. float dotB = planeB.normal.dot(lightDir);
  1343. if((dotA * dotB) < 0.0f)
  1344. {
  1345. const Vector3& vertA = frustumVerts[sharedEdges[i][0]];
  1346. const Vector3& vertB = frustumVerts[sharedEdges[i][1]];
  1347. Vector3 vertC = vertA + lightDir;
  1348. if (dotA < 0.0f)
  1349. lightVolume.push_back(Plane(vertA, vertB, vertC));
  1350. else
  1351. lightVolume.push_back(Plane(vertB, vertA, vertC));
  1352. }
  1353. }
  1354. return ConvexVolume(lightVolume);
  1355. }
  1356. float ShadowRendering::getCSMSplitDistance(const RendererView& view, UINT32 index, UINT32 numCascades)
  1357. {
  1358. // Determines the size of each subsequent cascade split. Value of 1 means the cascades will be linearly split.
  1359. // Value of 2 means each subsequent split will be twice the size of the previous one. Valid range is roughly
  1360. // [1, 4].
  1361. // Note: Make this an adjustable property?
  1362. const static float DISTRIBUTON_EXPONENT = 3.0f;
  1363. // First determine the scale of the split, relative to the entire range
  1364. float scaleModifier = 1.0f;
  1365. float scale = 0.0f;
  1366. float totalScale = 0.0f;
  1367. //// Split 0 corresponds to near plane
  1368. if (index > 0)
  1369. {
  1370. for (UINT32 i = 0; i < numCascades; i++)
  1371. {
  1372. if (i < index)
  1373. scale += scaleModifier;
  1374. totalScale += scaleModifier;
  1375. scaleModifier *= DISTRIBUTON_EXPONENT;
  1376. }
  1377. scale = scale / totalScale;
  1378. }
  1379. // Calculate split distance in Z
  1380. auto& viewProps = view.getProperties();
  1381. float near = viewProps.nearPlane;
  1382. float far = viewProps.farPlane;
  1383. return near + (far - near) * scale;
  1384. }
  1385. float ShadowRendering::getDepthBias(const Light& light, float radius, float depthRange, UINT32 mapSize)
  1386. {
  1387. const static float RADIAL_LIGHT_BIAS = 0.005f;
  1388. const static float SPOT_DEPTH_BIAS = 0.1f;
  1389. const static float DIR_DEPTH_BIAS = 5.0f;
  1390. const static float DEFAULT_RESOLUTION = 512.0f;
  1391. // Increase bias if map size smaller than some resolution
  1392. float resolutionScale;
  1393. if (light.getType() == LightType::Directional)
  1394. resolutionScale = radius / (float)mapSize;
  1395. else
  1396. resolutionScale = DEFAULT_RESOLUTION / (float)mapSize;
  1397. // Adjust range because in shader we compare vs. clip space depth
  1398. float rangeScale;
  1399. if (light.getType() == LightType::Radial)
  1400. rangeScale = 1.0f;
  1401. else
  1402. rangeScale = 1.0f / depthRange;
  1403. float defaultBias = 1.0f;
  1404. switch(light.getType())
  1405. {
  1406. case LightType::Directional:
  1407. defaultBias = DIR_DEPTH_BIAS;
  1408. break;
  1409. case LightType::Radial:
  1410. defaultBias = RADIAL_LIGHT_BIAS;
  1411. break;
  1412. case LightType::Spot:
  1413. defaultBias = SPOT_DEPTH_BIAS;
  1414. break;
  1415. default:
  1416. break;
  1417. }
  1418. return defaultBias * light.getShadowBias() * resolutionScale * rangeScale;
  1419. }
  1420. float ShadowRendering::getFadeTransition(const Light& light, float radius, float depthRange, UINT32 mapSize)
  1421. {
  1422. const static float SPOT_LIGHT_SCALE = 1000.0f;
  1423. const static float DIR_LIGHT_SCALE = 5000000.0f;
  1424. // Note: Currently fade transitions are only used in spot & directional (non omni-directional) lights, so no need
  1425. // to account for radial light type.
  1426. if (light.getType() == LightType::Directional)
  1427. {
  1428. // Reduce the size of the transition region when shadow map resolution is higher
  1429. float resolutionScale = 1.0f / (float)mapSize;
  1430. // Reduce the size of the transition region when the depth range is larger
  1431. float rangeScale = 1.0f / depthRange;
  1432. // Increase the size of the transition region for larger lights
  1433. float radiusScale = radius;
  1434. return light.getShadowBias() * DIR_LIGHT_SCALE * rangeScale * resolutionScale * radiusScale;
  1435. }
  1436. else
  1437. return light.getShadowBias() * SPOT_LIGHT_SCALE;
  1438. }
  1439. }}