BsShadowRendering.cpp 63 KB

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