BsShadowRendering.cpp 62 KB

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