BsShadowRendering.cpp 62 KB

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