BsShadowRendering.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799
  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.arraySlice = 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.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. Vector4 lightPosAndRadius(light->getPosition(), light->getAttenuationRadius());
  686. gShadowProjectOmniParamsDef.gLightPosAndRadius.set(shadowOmniParamBuffer, lightPosAndRadius);
  687. // Reduce shadow quality based on shadow map resolution for spot lights
  688. UINT32 effectiveShadowQuality = getShadowQuality(shadowQuality, shadowInfo.area.width, 2);
  689. // Check if viewer is inside the light bounds
  690. //// Expand the light bounds slightly to handle the case when the near plane is intersecting the light volume
  691. float lightRadius = light->getAttenuationRadius() + viewProps.nearPlane * 3.0f;
  692. bool viewerInsideVolume = (light->getPosition() - viewProps.viewOrigin).length() < lightRadius;
  693. SPtr<Texture> shadowMap = mShadowCubemaps[shadowInfo.textureIdx].getTexture();
  694. ShadowProjectParams shadowParams(*light, shadowMap, 0, shadowOmniParamBuffer, perViewBuffer, gbuffer);
  695. ShadowProjectOmniMat* mat = ShadowProjectOmniMat::getVariation(effectiveShadowQuality, viewerInsideVolume,
  696. viewProps.numSamples > 1);
  697. mat->bind(shadowParams);
  698. gRendererUtility().draw(gRendererUtility().getRadialLightStencil());
  699. }
  700. }
  701. else // Directional & spot
  702. {
  703. shadowInfos.clear();
  704. bool isCSM = light->getType() == LightType::Directional;
  705. if(!isCSM)
  706. {
  707. const LightShadows& shadows = mSpotLightShadows[lightIdx];
  708. for (UINT32 i = 0; i < shadows.numShadows; ++i)
  709. {
  710. UINT32 shadowIdx = shadows.startIdx + i;
  711. const ShadowInfo& shadowInfo = mShadowInfos[shadowIdx];
  712. if (shadowInfo.fadePerView[viewIdx] < 0.005f)
  713. continue;
  714. shadowInfos.push_back(&shadowInfo);
  715. }
  716. }
  717. else // Directional
  718. {
  719. const LightShadows& shadows = mDirectionalLightShadows[lightIdx].viewShadows[viewIdx];
  720. if (shadows.numShadows > 0)
  721. {
  722. UINT32 mapIdx = shadows.startIdx;
  723. const ShadowCascadedMap& cascadedMap = mCascadedShadowMaps[mapIdx];
  724. // Render cascades in far to near order.
  725. // Note: If rendering other non-cascade maps they should be rendered after cascades.
  726. for (INT32 i = NUM_CASCADE_SPLITS - 1; i >= 0; i--)
  727. shadowInfos.push_back(&cascadedMap.getShadowInfo(i));
  728. }
  729. }
  730. for(auto& shadowInfo : shadowInfos)
  731. {
  732. float depthScale, depthOffset;
  733. // Depth range scale is already baked into the ortho projection matrix, so avoid doing it here
  734. if (isCSM)
  735. {
  736. // Need to map from NDC depth to [0, 1]
  737. depthScale = 1.0f / (rapiInfo.getMaximumDepthInputValue() - rapiInfo.getMinimumDepthInputValue());
  738. depthOffset = -rapiInfo.getMinimumDepthInputValue() * depthScale;
  739. }
  740. else
  741. {
  742. depthScale = 1.0f / shadowInfo->depthRange;
  743. depthOffset = 0.0f;
  744. }
  745. Matrix4 mixedToShadowUV = createMixedToShadowUVMatrix(viewP, viewInvVP, shadowInfo->normArea,
  746. depthScale, depthOffset, shadowInfo->shadowVPTransform);
  747. Vector2 shadowMapSize((float)shadowInfo->area.width, (float)shadowInfo->area.height);
  748. float transitionScale = getFadeTransition(*light, shadowInfo->subjectBounds.getRadius(),
  749. shadowInfo->depthRange, shadowInfo->area.width);
  750. gShadowProjectParamsDef.gFadePlaneDepth.set(shadowParamBuffer, shadowInfo->depthFade);
  751. gShadowProjectParamsDef.gMixedToShadowSpace.set(shadowParamBuffer, mixedToShadowUV);
  752. gShadowProjectParamsDef.gShadowMapSize.set(shadowParamBuffer, shadowMapSize);
  753. gShadowProjectParamsDef.gShadowMapSizeInv.set(shadowParamBuffer, 1.0f / shadowMapSize);
  754. gShadowProjectParamsDef.gSoftTransitionScale.set(shadowParamBuffer, transitionScale);
  755. if(isCSM)
  756. gShadowProjectParamsDef.gFadePercent.set(shadowParamBuffer, 1.0f);
  757. else
  758. gShadowProjectParamsDef.gFadePercent.set(shadowParamBuffer, shadowInfo->fadePerView[viewIdx]);
  759. if(shadowInfo->fadeRange == 0.0f)
  760. gShadowProjectParamsDef.gInvFadePlaneRange.set(shadowParamBuffer, 0.0f);
  761. else
  762. gShadowProjectParamsDef.gInvFadePlaneRange.set(shadowParamBuffer, 1.0f / shadowInfo->fadeRange);
  763. // Generate a stencil buffer to avoid evaluating pixels without any receiver geometry in the shadow area
  764. std::array<Vector3, 8> frustumVertices;
  765. UINT32 effectiveShadowQuality = shadowQuality;
  766. if(!isCSM)
  767. {
  768. ConvexVolume shadowFrustum;
  769. frustumVertices = getFrustum(shadowInfo->shadowVPTransform.inverse(), shadowFrustum);
  770. // Check if viewer is inside the frustum. Frustum is slightly expanded so that if the near plane is
  771. // intersecting the shadow frustum, it is counted as inside. This needs to be conservative as the code
  772. // for handling viewer outside the frustum will not properly render intersections with the near plane.
  773. bool viewerInsideFrustum = shadowFrustum.contains(viewProps.viewOrigin, viewProps.nearPlane * 3.0f);
  774. ShadowProjectStencilMat* mat = ShadowProjectStencilMat::getVariation(false, viewerInsideFrustum);
  775. mat->bind(perViewBuffer);
  776. drawFrustum(frustumVertices);
  777. // Reduce shadow quality based on shadow map resolution for spot lights
  778. effectiveShadowQuality = getShadowQuality(shadowQuality, shadowInfo->area.width, 2);
  779. }
  780. else
  781. {
  782. // Need to generate near and far planes to clip the geometry within the current CSM slice.
  783. // Note: If the render API supports built-in depth bound tests that could be used instead.
  784. Vector3 near = viewProps.projTransform.multiply(Vector3(0, 0, -shadowInfo->depthNear));
  785. Vector3 far = viewProps.projTransform.multiply(Vector3(0, 0, -shadowInfo->depthFar));
  786. ShadowProjectStencilMat* mat = ShadowProjectStencilMat::getVariation(true, true);
  787. mat->bind(perViewBuffer);
  788. drawNearFarPlanes(near.z, far.z, shadowInfo->cascadeIdx != 0);
  789. }
  790. SPtr<Texture> shadowMap;
  791. UINT32 shadowMapFace = 0;
  792. if(!isCSM)
  793. shadowMap = mDynamicShadowMaps[shadowInfo->textureIdx].getTexture();
  794. else
  795. {
  796. shadowMap = mCascadedShadowMaps[shadowInfo->textureIdx].getTexture();
  797. shadowMapFace = shadowInfo->cascadeIdx;
  798. }
  799. ShadowProjectParams shadowParams(*light, shadowMap, shadowMapFace, shadowParamBuffer, perViewBuffer,
  800. gbuffer);
  801. ShadowProjectMat* mat = ShadowProjectMat::getVariation(effectiveShadowQuality, isCSM, viewProps.numSamples > 1);
  802. mat->bind(shadowParams);
  803. if (!isCSM)
  804. drawFrustum(frustumVertices);
  805. else
  806. gRendererUtility().drawScreenQuad();
  807. }
  808. }
  809. }
  810. void ShadowRendering::renderCascadedShadowMaps(const RendererView& view, UINT32 lightIdx, RendererScene& scene,
  811. const FrameInfo& frameInfo)
  812. {
  813. UINT32 viewIdx = view.getViewIdx();
  814. LightShadows& lightShadows = mDirectionalLightShadows[lightIdx].viewShadows[viewIdx];
  815. if (!view.getRenderSettings().enableShadows)
  816. {
  817. lightShadows.startIdx = -1;
  818. lightShadows.numShadows = 0;
  819. return;
  820. }
  821. // Note: Currently I'm using spherical bounds for the cascaded frustum which might result in non-optimal usage
  822. // of the shadow map. A different approach would be to generate a bounding box and then both adjust the aspect
  823. // ratio (and therefore dimensions) of the shadow map, as well as rotate the camera so the visible area best fits
  824. // in the map. It remains to be seen if this is viable.
  825. const SceneInfo& sceneInfo = scene.getSceneInfo();
  826. const RendererLight& rendererLight = sceneInfo.directionalLights[lightIdx];
  827. Light* light = rendererLight.internal;
  828. RenderAPI& rapi = RenderAPI::instance();
  829. Vector3 lightDir = -light->getRotation().zAxis();
  830. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  831. ShadowInfo shadowInfo;
  832. shadowInfo.lightIdx = lightIdx;
  833. shadowInfo.textureIdx = -1;
  834. UINT32 mapSize = std::min(mShadowMapSize, MAX_ATLAS_SIZE);
  835. shadowInfo.area = Rect2I(0, 0, mapSize, mapSize);
  836. shadowInfo.updateNormArea(mapSize);
  837. for (UINT32 i = 0; i < (UINT32)mCascadedShadowMaps.size(); i++)
  838. {
  839. ShadowCascadedMap& shadowMap = mCascadedShadowMaps[i];
  840. if (!shadowMap.isUsed() && shadowMap.getSize() == mapSize)
  841. {
  842. shadowInfo.textureIdx = i;
  843. shadowMap.markAsUsed();
  844. break;
  845. }
  846. }
  847. if (shadowInfo.textureIdx == (UINT32)-1)
  848. {
  849. shadowInfo.textureIdx = (UINT32)mCascadedShadowMaps.size();
  850. mCascadedShadowMaps.push_back(ShadowCascadedMap(mapSize));
  851. ShadowCascadedMap& shadowMap = mCascadedShadowMaps.back();
  852. shadowMap.markAsUsed();
  853. }
  854. ShadowCascadedMap& shadowMap = mCascadedShadowMaps[shadowInfo.textureIdx];
  855. Quaternion lightRotation(BsIdentity);
  856. lightRotation.lookRotation(-light->getRotation().zAxis());
  857. Matrix4 viewMat = Matrix4::view(light->getPosition(), lightRotation);
  858. for (UINT32 i = 0; i < NUM_CASCADE_SPLITS; ++i)
  859. {
  860. Sphere frustumBounds;
  861. ConvexVolume cascadeCullVolume = getCSMSplitFrustum(view, -lightDir, i, NUM_CASCADE_SPLITS, frustumBounds);
  862. // Move the light at the boundary of the subject frustum, so we don't waste depth range
  863. Vector3 frustumCenterViewSpace = viewMat.multiply(frustumBounds.getCenter());
  864. float minSubjectDepth = -frustumCenterViewSpace.z - frustumBounds.getRadius();
  865. float maxSubjectDepth = minSubjectDepth + frustumBounds.getRadius() * 2.0f;
  866. shadowInfo.depthRange = maxSubjectDepth - minSubjectDepth;
  867. Vector3 offsetLightPos = light->getPosition() + lightDir * minSubjectDepth;
  868. Matrix4 offsetViewMat = Matrix4::view(offsetLightPos, lightRotation);
  869. float orthoSize = frustumBounds.getRadius() * 0.5f;
  870. Matrix4 proj = Matrix4::projectionOrthographic(-orthoSize, orthoSize, orthoSize, -orthoSize, 0.0f,
  871. shadowInfo.depthRange);
  872. RenderAPI::instance().convertProjectionMatrix(proj, proj);
  873. shadowInfo.cascadeIdx = i;
  874. shadowInfo.shadowVPTransform = proj * offsetViewMat;
  875. // Determine split range
  876. float splitNear = getCSMSplitDistance(view, i, NUM_CASCADE_SPLITS);
  877. float splitFar = getCSMSplitDistance(view, i + 1, NUM_CASCADE_SPLITS);
  878. shadowInfo.depthNear = splitNear;
  879. shadowInfo.depthFade = splitFar;
  880. shadowInfo.subjectBounds = frustumBounds;
  881. if ((UINT32)(i + 1) < NUM_CASCADE_SPLITS)
  882. shadowInfo.fadeRange = CASCADE_FRACTION_FADE * (shadowInfo.depthFade - shadowInfo.depthNear);
  883. else
  884. shadowInfo.fadeRange = 0.0f;
  885. shadowInfo.depthFar = shadowInfo.depthFade + shadowInfo.fadeRange;
  886. shadowInfo.depthBias = getDepthBias(*light, frustumBounds.getRadius(), shadowInfo.depthRange, mapSize);
  887. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, shadowInfo.depthBias);
  888. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / shadowInfo.depthRange);
  889. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, shadowInfo.shadowVPTransform);
  890. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  891. rapi.setRenderTarget(shadowMap.getTarget(i));
  892. rapi.clearRenderTarget(FBT_DEPTH);
  893. ShadowDepthDirectionalMat* depthDirMat = ShadowDepthDirectionalMat::get();
  894. depthDirMat->bind(shadowParamsBuffer);
  895. for (UINT32 j = 0; j < sceneInfo.renderables.size(); j++)
  896. {
  897. if (!cascadeCullVolume.intersects(sceneInfo.renderableCullInfos[j].bounds.getSphere()))
  898. continue;
  899. scene.prepareRenderable(j, frameInfo);
  900. RendererObject* renderable = sceneInfo.renderables[j];
  901. depthDirMat->setPerObjectBuffer(renderable->perObjectParamBuffer);
  902. for (auto& element : renderable->elements)
  903. {
  904. if (element.morphVertexDeclaration == nullptr)
  905. gRendererUtility().draw(element.mesh, element.subMesh);
  906. else
  907. gRendererUtility().drawMorph(element.mesh, element.subMesh, element.morphShapeBuffer,
  908. element.morphVertexDeclaration);
  909. }
  910. }
  911. shadowMap.setShadowInfo(i, shadowInfo);
  912. }
  913. lightShadows.startIdx = shadowInfo.textureIdx;
  914. lightShadows.numShadows = 1;
  915. }
  916. void ShadowRendering::renderSpotShadowMap(const RendererLight& rendererLight, const ShadowMapOptions& options,
  917. RendererScene& scene, const FrameInfo& frameInfo)
  918. {
  919. Light* light = rendererLight.internal;
  920. const SceneInfo& sceneInfo = scene.getSceneInfo();
  921. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  922. ShadowInfo mapInfo;
  923. mapInfo.fadePerView = options.fadePercents;
  924. mapInfo.lightIdx = options.lightIdx;
  925. mapInfo.cascadeIdx = -1;
  926. bool foundSpace = false;
  927. for (UINT32 i = 0; i < (UINT32)mDynamicShadowMaps.size(); i++)
  928. {
  929. ShadowMapAtlas& atlas = mDynamicShadowMaps[i];
  930. if (atlas.addMap(options.mapSize, mapInfo.area, SHADOW_MAP_BORDER))
  931. {
  932. mapInfo.textureIdx = i;
  933. foundSpace = true;
  934. break;
  935. }
  936. }
  937. if (!foundSpace)
  938. {
  939. mapInfo.textureIdx = (UINT32)mDynamicShadowMaps.size();
  940. mDynamicShadowMaps.push_back(ShadowMapAtlas(MAX_ATLAS_SIZE));
  941. ShadowMapAtlas& atlas = mDynamicShadowMaps.back();
  942. atlas.addMap(options.mapSize, mapInfo.area, SHADOW_MAP_BORDER);
  943. }
  944. mapInfo.updateNormArea(MAX_ATLAS_SIZE);
  945. ShadowMapAtlas& atlas = mDynamicShadowMaps[mapInfo.textureIdx];
  946. RenderAPI& rapi = RenderAPI::instance();
  947. rapi.setRenderTarget(atlas.getTarget());
  948. rapi.setViewport(mapInfo.normArea);
  949. rapi.clearViewport(FBT_DEPTH);
  950. mapInfo.depthNear = 0.05f;
  951. mapInfo.depthFar = light->getAttenuationRadius();
  952. mapInfo.depthFade = mapInfo.depthFar;
  953. mapInfo.fadeRange = 0.0f;
  954. mapInfo.depthRange = mapInfo.depthFar - mapInfo.depthNear;
  955. mapInfo.depthBias = getDepthBias(*light, light->getBounds().getRadius(), mapInfo.depthRange, options.mapSize);
  956. mapInfo.subjectBounds = light->getBounds();
  957. Quaternion lightRotation(BsIdentity);
  958. lightRotation.lookRotation(-light->getRotation().zAxis());
  959. Matrix4 view = Matrix4::view(rendererLight.getShiftedLightPosition(), lightRotation);
  960. Matrix4 proj = Matrix4::projectionPerspective(light->getSpotAngle(), 1.0f, 0.05f, light->getAttenuationRadius());
  961. ConvexVolume localFrustum = ConvexVolume(proj);
  962. RenderAPI::instance().convertProjectionMatrix(proj, proj);
  963. mapInfo.shadowVPTransform = proj * view;
  964. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, mapInfo.depthBias);
  965. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / mapInfo.depthRange);
  966. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, mapInfo.shadowVPTransform);
  967. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  968. ShadowDepthNormalMat* depthNormalMat = ShadowDepthNormalMat::get();
  969. depthNormalMat->bind(shadowParamsBuffer);
  970. const Vector<Plane>& frustumPlanes = localFrustum.getPlanes();
  971. Matrix4 worldMatrix = view.transpose();
  972. Vector<Plane> worldPlanes(frustumPlanes.size());
  973. UINT32 j = 0;
  974. for (auto& plane : frustumPlanes)
  975. {
  976. worldPlanes[j] = worldMatrix.multiplyAffine(plane);
  977. j++;
  978. }
  979. ConvexVolume worldFrustum(worldPlanes);
  980. for (UINT32 i = 0; i < sceneInfo.renderables.size(); i++)
  981. {
  982. if (!worldFrustum.intersects(sceneInfo.renderableCullInfos[i].bounds.getSphere()))
  983. continue;
  984. scene.prepareRenderable(i, frameInfo);
  985. RendererObject* renderable = sceneInfo.renderables[i];
  986. depthNormalMat->setPerObjectBuffer(renderable->perObjectParamBuffer);
  987. for (auto& element : renderable->elements)
  988. {
  989. if (element.morphVertexDeclaration == nullptr)
  990. gRendererUtility().draw(element.mesh, element.subMesh);
  991. else
  992. gRendererUtility().drawMorph(element.mesh, element.subMesh, element.morphShapeBuffer,
  993. element.morphVertexDeclaration);
  994. }
  995. }
  996. // Restore viewport
  997. rapi.setViewport(Rect2(0.0f, 0.0f, 1.0f, 1.0f));
  998. LightShadows& lightShadows = mSpotLightShadows[options.lightIdx];
  999. mShadowInfos[lightShadows.startIdx + lightShadows.numShadows] = mapInfo;
  1000. lightShadows.numShadows++;
  1001. }
  1002. void ShadowRendering::renderRadialShadowMap(const RendererLight& rendererLight,
  1003. const ShadowMapOptions& options, RendererScene& scene, const FrameInfo& frameInfo)
  1004. {
  1005. Light* light = rendererLight.internal;
  1006. const SceneInfo& sceneInfo = scene.getSceneInfo();
  1007. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  1008. SPtr<GpuParamBlockBuffer> shadowCubeMatricesBuffer = gShadowCubeMatricesDef.createBuffer();
  1009. SPtr<GpuParamBlockBuffer> shadowCubeMasksBuffer = gShadowCubeMasksDef.createBuffer();
  1010. ShadowInfo mapInfo;
  1011. mapInfo.lightIdx = options.lightIdx;
  1012. mapInfo.textureIdx = -1;
  1013. mapInfo.fadePerView = options.fadePercents;
  1014. mapInfo.cascadeIdx = -1;
  1015. mapInfo.area = Rect2I(0, 0, options.mapSize, options.mapSize);
  1016. mapInfo.updateNormArea(options.mapSize);
  1017. for (UINT32 i = 0; i < (UINT32)mShadowCubemaps.size(); i++)
  1018. {
  1019. ShadowCubemap& cubemap = mShadowCubemaps[i];
  1020. if (!cubemap.isUsed() && cubemap.getSize() == options.mapSize)
  1021. {
  1022. mapInfo.textureIdx = i;
  1023. cubemap.markAsUsed();
  1024. break;
  1025. }
  1026. }
  1027. if (mapInfo.textureIdx == (UINT32)-1)
  1028. {
  1029. mapInfo.textureIdx = (UINT32)mShadowCubemaps.size();
  1030. mShadowCubemaps.push_back(ShadowCubemap(options.mapSize));
  1031. ShadowCubemap& cubemap = mShadowCubemaps.back();
  1032. cubemap.markAsUsed();
  1033. }
  1034. ShadowCubemap& cubemap = mShadowCubemaps[mapInfo.textureIdx];
  1035. mapInfo.depthNear = 0.05f;
  1036. mapInfo.depthFar = light->getAttenuationRadius();
  1037. mapInfo.depthFade = mapInfo.depthFar;
  1038. mapInfo.fadeRange = 0.0f;
  1039. mapInfo.depthRange = mapInfo.depthFar - mapInfo.depthNear;
  1040. mapInfo.depthBias = getDepthBias(*light, light->getBounds().getRadius(), mapInfo.depthRange, options.mapSize);
  1041. mapInfo.subjectBounds = light->getBounds();
  1042. Matrix4 proj = Matrix4::projectionPerspective(Degree(90.0f), 1.0f, 0.05f, light->getAttenuationRadius());
  1043. ConvexVolume localFrustum(proj);
  1044. RenderAPI& rapi = RenderAPI::instance();
  1045. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  1046. rapi.convertProjectionMatrix(proj, proj);
  1047. // Render cubemaps upside down if necessary
  1048. Matrix4 adjustedProj = proj;
  1049. if(rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp))
  1050. {
  1051. // All big APIs use the same cubemap sampling coordinates, as well as the same face order. But APIs that
  1052. // use bottom-up UV coordinates require the cubemap faces to be stored upside down in order to get the same
  1053. // behaviour. APIs that use an upside-down NDC Y axis have the same problem as the rendered image will be
  1054. // upside down, but this is handled by the projection matrix. If both of those are enabled, then the effect
  1055. // cancels out.
  1056. adjustedProj[1][1] = -proj[1][1];
  1057. }
  1058. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, mapInfo.depthBias);
  1059. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / mapInfo.depthRange);
  1060. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, Matrix4::IDENTITY);
  1061. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  1062. Matrix4 viewOffsetMat = Matrix4::translation(-light->getPosition());
  1063. ConvexVolume frustums[6];
  1064. Vector<Plane> boundingPlanes;
  1065. for (UINT32 i = 0; i < 6; i++)
  1066. {
  1067. // Calculate view matrix
  1068. Vector3 forward;
  1069. Vector3 up = Vector3::UNIT_Y;
  1070. switch (i)
  1071. {
  1072. case CF_PositiveX:
  1073. forward = Vector3::UNIT_X;
  1074. break;
  1075. case CF_NegativeX:
  1076. forward = -Vector3::UNIT_X;
  1077. break;
  1078. case CF_PositiveY:
  1079. forward = Vector3::UNIT_Y;
  1080. up = -Vector3::UNIT_Z;
  1081. break;
  1082. case CF_NegativeY:
  1083. forward = -Vector3::UNIT_Y;
  1084. up = Vector3::UNIT_Z;
  1085. break;
  1086. case CF_PositiveZ:
  1087. forward = Vector3::UNIT_Z;
  1088. break;
  1089. case CF_NegativeZ:
  1090. forward = -Vector3::UNIT_Z;
  1091. break;
  1092. }
  1093. Vector3 right = Vector3::cross(up, forward);
  1094. Matrix3 viewRotationMat = Matrix3(right, up, -forward);
  1095. Matrix4 view = Matrix4(viewRotationMat) * viewOffsetMat;
  1096. mapInfo.shadowVPTransforms[i] = proj * view;
  1097. Matrix4 shadowViewProj = adjustedProj * view;
  1098. gShadowCubeMatricesDef.gFaceVPMatrices.set(shadowCubeMatricesBuffer, shadowViewProj, i);
  1099. // Calculate world frustum for culling
  1100. const Vector<Plane>& frustumPlanes = localFrustum.getPlanes();
  1101. Matrix4 worldMatrix = view.transpose();
  1102. Vector<Plane> worldPlanes(frustumPlanes.size());
  1103. UINT32 j = 0;
  1104. for (auto& plane : frustumPlanes)
  1105. {
  1106. worldPlanes[j] = worldMatrix.multiplyAffine(plane);
  1107. j++;
  1108. }
  1109. frustums[i] = ConvexVolume(worldPlanes);
  1110. // Register far plane of all frustums
  1111. boundingPlanes.push_back(worldPlanes.back());
  1112. }
  1113. rapi.setRenderTarget(cubemap.getTarget());
  1114. rapi.clearRenderTarget(FBT_DEPTH);
  1115. ShadowDepthCubeMat* depthCubeMat = ShadowDepthCubeMat::get();
  1116. depthCubeMat->bind(shadowParamsBuffer, shadowCubeMatricesBuffer);
  1117. // First cull against a global volume
  1118. ConvexVolume boundingVolume(boundingPlanes);
  1119. for (UINT32 i = 0; i < sceneInfo.renderables.size(); i++)
  1120. {
  1121. const Sphere& bounds = sceneInfo.renderableCullInfos[i].bounds.getSphere();
  1122. if (!boundingVolume.intersects(bounds))
  1123. continue;
  1124. scene.prepareRenderable(i, frameInfo);
  1125. for(UINT32 j = 0; j < 6; j++)
  1126. {
  1127. int mask = frustums[j].intersects(bounds) ? 1 : 0;
  1128. gShadowCubeMasksDef.gFaceMasks.set(shadowCubeMasksBuffer, mask, j);
  1129. }
  1130. RendererObject* renderable = sceneInfo.renderables[i];
  1131. depthCubeMat->setPerObjectBuffer(renderable->perObjectParamBuffer, shadowCubeMasksBuffer);
  1132. for (auto& element : renderable->elements)
  1133. {
  1134. if (element.morphVertexDeclaration == nullptr)
  1135. gRendererUtility().draw(element.mesh, element.subMesh);
  1136. else
  1137. gRendererUtility().drawMorph(element.mesh, element.subMesh, element.morphShapeBuffer,
  1138. element.morphVertexDeclaration);
  1139. }
  1140. }
  1141. LightShadows& lightShadows = mRadialLightShadows[options.lightIdx];
  1142. mShadowInfos[lightShadows.startIdx + lightShadows.numShadows] = mapInfo;
  1143. lightShadows.numShadows++;
  1144. }
  1145. void ShadowRendering::calcShadowMapProperties(const RendererLight& light, const RendererViewGroup& viewGroup,
  1146. UINT32 border, UINT32& size, SmallVector<float, 4>& fadePercents, float& maxFadePercent) const
  1147. {
  1148. const static float SHADOW_TEXELS_PER_PIXEL = 1.0f;
  1149. // Find a view in which the light has the largest radius
  1150. float maxMapSize = 0.0f;
  1151. maxFadePercent = 0.0f;
  1152. for (int i = 0; i < (int)viewGroup.getNumViews(); ++i)
  1153. {
  1154. const RendererView& view = *viewGroup.getView(i);
  1155. const RendererViewProperties& viewProps = view.getProperties();
  1156. const RenderSettings& viewSettings = view.getRenderSettings();
  1157. if(!viewSettings.enableShadows)
  1158. fadePercents.push_back(0.0f);
  1159. {
  1160. // Approximation for screen space sphere radius: screenSize * 0.5 * cot(fov) * radius / Z, where FOV is the
  1161. // largest one
  1162. //// First get sphere depth
  1163. const Matrix4& viewVP = viewProps.viewProjTransform;
  1164. float depth = viewVP.multiply(Vector4(light.internal->getPosition(), 1.0f)).w;
  1165. // This is just 1/tan(fov), for both horz. and vert. FOV
  1166. float viewScaleX = viewProps.projTransform[0][0];
  1167. float viewScaleY = viewProps.projTransform[1][1];
  1168. float screenScaleX = viewScaleX * viewProps.viewRect.width * 0.5f;
  1169. float screenScaleY = viewScaleY * viewProps.viewRect.height * 0.5f;
  1170. float screenScale = std::max(screenScaleX, screenScaleY);
  1171. //// Calc radius (clamp if too close to avoid massive numbers)
  1172. float radiusNDC = light.internal->getBounds().getRadius() / std::max(depth, 1.0f);
  1173. //// Radius of light bounds in percent of the view surface, multiplied by screen size in pixels
  1174. float radiusScreen = radiusNDC * screenScale;
  1175. float optimalMapSize = SHADOW_TEXELS_PER_PIXEL * radiusScreen;
  1176. maxMapSize = std::max(maxMapSize, optimalMapSize);
  1177. // Determine if the shadow should fade out
  1178. float fadePercent = Math::lerp01(optimalMapSize, (float)MIN_SHADOW_MAP_SIZE, (float)SHADOW_MAP_FADE_SIZE);
  1179. fadePercents.push_back(fadePercent);
  1180. maxFadePercent = std::max(maxFadePercent, fadePercent);
  1181. }
  1182. }
  1183. // If light fully (or nearly fully) covers the screen, use full shadow map resolution, otherwise
  1184. // scale it down to smaller power of two, while clamping to minimal allowed resolution
  1185. UINT32 effectiveMapSize = Bitwise::nextPow2((UINT32)maxMapSize);
  1186. effectiveMapSize = Math::clamp(effectiveMapSize, MIN_SHADOW_MAP_SIZE, mShadowMapSize);
  1187. // Leave room for border
  1188. size = std::max(effectiveMapSize - 2 * border, 1u);
  1189. }
  1190. void ShadowRendering::drawNearFarPlanes(float near, float far, bool drawNear) const
  1191. {
  1192. RenderAPI& rapi = RenderAPI::instance();
  1193. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  1194. float flipY = rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown) ? -1.0f : 1.0f;
  1195. // Update VB with new vertices
  1196. Vector3 vertices[8] =
  1197. {
  1198. // Near plane
  1199. { -1.0f, -1.0f * flipY, near },
  1200. { 1.0f, -1.0f * flipY, near },
  1201. { 1.0f, 1.0f * flipY, near },
  1202. { -1.0f, 1.0f * flipY, near },
  1203. // Far plane
  1204. { -1.0f, -1.0f * flipY, far },
  1205. { 1.0f, -1.0f * flipY, far },
  1206. { 1.0f, 1.0f * flipY, far },
  1207. { -1.0f, 1.0f * flipY, far },
  1208. };
  1209. mPlaneVB->writeData(0, sizeof(vertices), vertices, BWT_DISCARD);
  1210. // Draw the mesh
  1211. rapi.setVertexDeclaration(mPositionOnlyVD);
  1212. rapi.setVertexBuffers(0, &mPlaneVB, 1);
  1213. rapi.setIndexBuffer(mPlaneIB);
  1214. rapi.setDrawOperation(DOT_TRIANGLE_LIST);
  1215. rapi.drawIndexed(0, drawNear ? 12 : 6, 0, drawNear ? 8 : 4);
  1216. }
  1217. void ShadowRendering::drawFrustum(const std::array<Vector3, 8>& corners) const
  1218. {
  1219. RenderAPI& rapi = RenderAPI::instance();
  1220. // Update VB with new vertices
  1221. mFrustumVB->writeData(0, sizeof(Vector3) * 8, corners.data(), BWT_DISCARD);
  1222. // Draw the mesh
  1223. rapi.setVertexDeclaration(mPositionOnlyVD);
  1224. rapi.setVertexBuffers(0, &mFrustumVB, 1);
  1225. rapi.setIndexBuffer(mFrustumIB);
  1226. rapi.setDrawOperation(DOT_TRIANGLE_LIST);
  1227. rapi.drawIndexed(0, 36, 0, 8);
  1228. }
  1229. UINT32 ShadowRendering::getShadowQuality(UINT32 requestedQuality, UINT32 shadowMapResolution, UINT32 minAllowedQuality)
  1230. {
  1231. static const UINT32 TARGET_RESOLUTION = 512;
  1232. // If shadow map resolution is smaller than some target resolution drop the number of PCF samples (shadow quality)
  1233. // so that the penumbra better matches with larger sized shadow maps.
  1234. while(requestedQuality > minAllowedQuality && shadowMapResolution < TARGET_RESOLUTION)
  1235. {
  1236. shadowMapResolution *= 2;
  1237. requestedQuality = std::max(requestedQuality - 1, 1U);
  1238. }
  1239. return requestedQuality;
  1240. }
  1241. ConvexVolume ShadowRendering::getCSMSplitFrustum(const RendererView& view, const Vector3& lightDir, UINT32 cascade,
  1242. UINT32 numCascades, Sphere& outBounds)
  1243. {
  1244. // Determine split range
  1245. float splitNear = getCSMSplitDistance(view, cascade, numCascades);
  1246. float splitFar = getCSMSplitDistance(view, cascade + 1, numCascades);
  1247. // Calculate the eight vertices of the split frustum
  1248. auto& viewProps = view.getProperties();
  1249. const Matrix4& projMat = viewProps.projTransform;
  1250. float aspect;
  1251. float nearHalfWidth, nearHalfHeight;
  1252. float farHalfWidth, farHalfHeight;
  1253. if(viewProps.projType == PT_PERSPECTIVE)
  1254. {
  1255. aspect = fabs(projMat[0][0] / projMat[1][1]);
  1256. float tanHalfFOV = 1.0f / projMat[0][0];
  1257. nearHalfWidth = splitNear * tanHalfFOV;
  1258. nearHalfHeight = nearHalfWidth * aspect;
  1259. farHalfWidth = splitFar * tanHalfFOV;
  1260. farHalfHeight = farHalfWidth * aspect;
  1261. }
  1262. else
  1263. {
  1264. aspect = projMat[0][0] / projMat[1][1];
  1265. nearHalfWidth = farHalfWidth = projMat[0][0] / 4.0f;
  1266. nearHalfHeight = farHalfHeight = projMat[1][1] / 4.0f;
  1267. }
  1268. const Matrix4& viewMat = viewProps.viewTransform;
  1269. Vector3 cameraRight = Vector3(viewMat[0]);
  1270. Vector3 cameraUp = Vector3(viewMat[1]);
  1271. const Vector3& viewOrigin = viewProps.viewOrigin;
  1272. const Vector3& viewDir = viewProps.viewDirection;
  1273. Vector3 frustumVerts[] =
  1274. {
  1275. viewOrigin + viewDir * splitNear - cameraRight * nearHalfWidth + cameraUp * nearHalfHeight, // Near, left, top
  1276. viewOrigin + viewDir * splitNear + cameraRight * nearHalfWidth + cameraUp * nearHalfHeight, // Near, right, top
  1277. viewOrigin + viewDir * splitNear + cameraRight * nearHalfWidth - cameraUp * nearHalfHeight, // Near, right, bottom
  1278. viewOrigin + viewDir * splitNear - cameraRight * nearHalfWidth - cameraUp * nearHalfHeight, // Near, left, bottom
  1279. viewOrigin + viewDir * splitFar - cameraRight * farHalfWidth + cameraUp * farHalfHeight, // Far, left, top
  1280. viewOrigin + viewDir * splitFar + cameraRight * farHalfWidth + cameraUp * farHalfHeight, // Far, right, top
  1281. viewOrigin + viewDir * splitFar + cameraRight * farHalfWidth - cameraUp * farHalfHeight, // Far, right, bottom
  1282. viewOrigin + viewDir * splitFar - cameraRight * farHalfWidth - cameraUp * farHalfHeight, // Far, left, bottom
  1283. };
  1284. // Calculate the bounding sphere of the frustum
  1285. float diagonalNearSq = nearHalfWidth * nearHalfWidth + nearHalfHeight * nearHalfHeight;
  1286. float diagonalFarSq = farHalfWidth * farHalfWidth + farHalfHeight * farHalfHeight;
  1287. float length = splitFar - splitNear;
  1288. float offset = (diagonalNearSq - diagonalFarSq) / (2 * length) + length * 0.5f;
  1289. float distToCenter = Math::clamp(splitFar - offset, splitNear, splitFar);
  1290. Vector3 center = viewOrigin + viewDir * distToCenter;
  1291. float radius = 0.0f;
  1292. for (auto& entry : frustumVerts)
  1293. radius = std::max(radius, center.squaredDistance(entry));
  1294. radius = std::max((float)sqrt(radius), 1.0f);
  1295. outBounds = Sphere(center, radius);
  1296. // Generate light frustum planes
  1297. Plane viewPlanes[6];
  1298. viewPlanes[FRUSTUM_PLANE_NEAR] = Plane(frustumVerts[0], frustumVerts[1], frustumVerts[2]);
  1299. viewPlanes[FRUSTUM_PLANE_FAR] = Plane(frustumVerts[5], frustumVerts[4], frustumVerts[7]);
  1300. viewPlanes[FRUSTUM_PLANE_LEFT] = Plane(frustumVerts[4], frustumVerts[0], frustumVerts[3]);
  1301. viewPlanes[FRUSTUM_PLANE_RIGHT] = Plane(frustumVerts[1], frustumVerts[5], frustumVerts[6]);
  1302. viewPlanes[FRUSTUM_PLANE_TOP] = Plane(frustumVerts[4], frustumVerts[5], frustumVerts[1]);
  1303. viewPlanes[FRUSTUM_PLANE_BOTTOM] = Plane(frustumVerts[3], frustumVerts[2], frustumVerts[6]);
  1304. Vector<Plane> lightVolume;
  1305. //// Add camera's planes facing towards the lights (forming the back of the volume)
  1306. for(auto& entry : viewPlanes)
  1307. {
  1308. if (entry.normal.dot(lightDir) < 0.0f)
  1309. lightVolume.push_back(entry);
  1310. }
  1311. //// Determine edge planes by testing adjacent planes with different facing
  1312. ////// Pairs of frustum planes that share an edge
  1313. UINT32 adjacentPlanes[][2] =
  1314. {
  1315. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_LEFT },
  1316. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_RIGHT },
  1317. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_TOP },
  1318. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_BOTTOM },
  1319. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_LEFT },
  1320. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_RIGHT },
  1321. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_TOP },
  1322. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_BOTTOM },
  1323. { FRUSTUM_PLANE_LEFT, FRUSTUM_PLANE_TOP },
  1324. { FRUSTUM_PLANE_TOP, FRUSTUM_PLANE_RIGHT },
  1325. { FRUSTUM_PLANE_RIGHT, FRUSTUM_PLANE_BOTTOM },
  1326. { FRUSTUM_PLANE_BOTTOM, FRUSTUM_PLANE_LEFT },
  1327. };
  1328. ////// Vertex indices of edges on the boundary between two planes
  1329. UINT32 sharedEdges[][2] =
  1330. {
  1331. { 3, 0 },{ 1, 2 },{ 0, 1 },{ 2, 3 },
  1332. { 4, 7 },{ 6, 5 },{ 5, 4 },{ 7, 6 },
  1333. { 4, 0 },{ 5, 1 },{ 6, 2 },{ 7, 3 }
  1334. };
  1335. for(UINT32 i = 0; i < 12; i++)
  1336. {
  1337. const Plane& planeA = viewPlanes[adjacentPlanes[i][0]];
  1338. const Plane& planeB = viewPlanes[adjacentPlanes[i][1]];
  1339. float dotA = planeA.normal.dot(lightDir);
  1340. float dotB = planeB.normal.dot(lightDir);
  1341. if((dotA * dotB) < 0.0f)
  1342. {
  1343. const Vector3& vertA = frustumVerts[sharedEdges[i][0]];
  1344. const Vector3& vertB = frustumVerts[sharedEdges[i][1]];
  1345. Vector3 vertC = vertA + lightDir;
  1346. if (dotA < 0.0f)
  1347. lightVolume.push_back(Plane(vertA, vertB, vertC));
  1348. else
  1349. lightVolume.push_back(Plane(vertB, vertA, vertC));
  1350. }
  1351. }
  1352. return ConvexVolume(lightVolume);
  1353. }
  1354. float ShadowRendering::getCSMSplitDistance(const RendererView& view, UINT32 index, UINT32 numCascades)
  1355. {
  1356. // Determines the size of each subsequent cascade split. Value of 1 means the cascades will be linearly split.
  1357. // Value of 2 means each subsequent split will be twice the size of the previous one. Valid range is roughly
  1358. // [1, 4].
  1359. // Note: Make this an adjustable property?
  1360. const static float DISTRIBUTON_EXPONENT = 3.0f;
  1361. // First determine the scale of the split, relative to the entire range
  1362. float scaleModifier = 1.0f;
  1363. float scale = 0.0f;
  1364. float totalScale = 0.0f;
  1365. //// Split 0 corresponds to near plane
  1366. if (index > 0)
  1367. {
  1368. for (UINT32 i = 0; i < numCascades; i++)
  1369. {
  1370. if (i < index)
  1371. scale += scaleModifier;
  1372. totalScale += scaleModifier;
  1373. scaleModifier *= DISTRIBUTON_EXPONENT;
  1374. }
  1375. scale = scale / totalScale;
  1376. }
  1377. // Calculate split distance in Z
  1378. auto& viewProps = view.getProperties();
  1379. float near = viewProps.nearPlane;
  1380. float far = viewProps.farPlane;
  1381. return near + (far - near) * scale;
  1382. }
  1383. float ShadowRendering::getDepthBias(const Light& light, float radius, float depthRange, UINT32 mapSize)
  1384. {
  1385. const static float RADIAL_LIGHT_BIAS = 0.005f;
  1386. const static float SPOT_DEPTH_BIAS = 0.1f;
  1387. const static float DIR_DEPTH_BIAS = 5.0f;
  1388. const static float DEFAULT_RESOLUTION = 512.0f;
  1389. // Increase bias if map size smaller than some resolution
  1390. float resolutionScale;
  1391. if (light.getType() == LightType::Directional)
  1392. resolutionScale = radius / (float)mapSize;
  1393. else
  1394. resolutionScale = DEFAULT_RESOLUTION / (float)mapSize;
  1395. // Adjust range because in shader we compare vs. clip space depth
  1396. float rangeScale;
  1397. if (light.getType() == LightType::Radial)
  1398. rangeScale = 1.0f;
  1399. else
  1400. rangeScale = 1.0f / depthRange;
  1401. float defaultBias = 1.0f;
  1402. switch(light.getType())
  1403. {
  1404. case LightType::Directional:
  1405. defaultBias = DIR_DEPTH_BIAS;
  1406. break;
  1407. case LightType::Radial:
  1408. defaultBias = RADIAL_LIGHT_BIAS;
  1409. break;
  1410. case LightType::Spot:
  1411. defaultBias = SPOT_DEPTH_BIAS;
  1412. break;
  1413. default:
  1414. break;
  1415. }
  1416. return defaultBias * light.getShadowBias() * resolutionScale * rangeScale;
  1417. }
  1418. float ShadowRendering::getFadeTransition(const Light& light, float radius, float depthRange, UINT32 mapSize)
  1419. {
  1420. const static float SPOT_LIGHT_SCALE = 1000.0f;
  1421. const static float DIR_LIGHT_SCALE = 5000000.0f;
  1422. // Note: Currently fade transitions are only used in spot & directional (non omni-directional) lights, so no need
  1423. // to account for radial light type.
  1424. if (light.getType() == LightType::Directional)
  1425. {
  1426. // Reduce the size of the transition region when shadow map resolution is higher
  1427. float resolutionScale = 1.0f / (float)mapSize;
  1428. // Reduce the size of the transition region when the depth range is larger
  1429. float rangeScale = 1.0f / depthRange;
  1430. // Increase the size of the transition region for larger lights
  1431. float radiusScale = radius;
  1432. return light.getShadowBias() * DIR_LIGHT_SCALE * rangeScale * resolutionScale * radiusScale;
  1433. }
  1434. else
  1435. return light.getShadowBias() * SPOT_LIGHT_SCALE;
  1436. }
  1437. }}