BsShadowRendering.cpp 62 KB

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