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. }
  563. void ShadowRendering::renderShadowMaps(RendererScene& scene, const RendererViewGroup& viewGroup,
  564. const FrameInfo& frameInfo)
  565. {
  566. // Note: Currently all shadows are dynamic and are rebuilt every frame. I should later added support for static
  567. // shadow maps which can be used for immovable lights. Such a light can then maintain a set of shadow maps,
  568. // one of which is static and only effects the static geometry, while the rest are per-object shadow maps used
  569. // for dynamic objects. Then only a small subset of geometry needs to be redrawn, instead of everything.
  570. // Note: Add support for per-object shadows and a way to force a renderable to use per-object shadows. This can be
  571. // used for adding high quality shadows on specific objects (e.g. important characters during cinematics).
  572. const SceneInfo& sceneInfo = scene.getSceneInfo();
  573. const VisibilityInfo& visibility = viewGroup.getVisibilityInfo();
  574. // Clear all transient data from last frame
  575. mShadowInfos.clear();
  576. mSpotLightShadows.resize(sceneInfo.spotLights.size());
  577. mRadialLightShadows.resize(sceneInfo.radialLights.size());
  578. mDirectionalLightShadows.resize(sceneInfo.directionalLights.size());
  579. mSpotLightShadowOptions.clear();
  580. mRadialLightShadowOptions.clear();
  581. // Clear all dynamic light atlases
  582. for (auto& entry : mCascadedShadowMaps)
  583. entry.clear();
  584. for (auto& entry : mDynamicShadowMaps)
  585. entry.clear();
  586. for (auto& entry : mShadowCubemaps)
  587. entry.clear();
  588. // Determine shadow map sizes and sort them
  589. UINT32 shadowInfoCount = 0;
  590. for (UINT32 i = 0; i < (UINT32)sceneInfo.spotLights.size(); ++i)
  591. {
  592. const RendererLight& light = sceneInfo.spotLights[i];
  593. mSpotLightShadows[i].startIdx = shadowInfoCount;
  594. mSpotLightShadows[i].numShadows = 0;
  595. // Note: I'm using visibility across all views, while I could be using visibility for every view individually,
  596. // if I kept that information somewhere
  597. if (!light.internal->getCastsShadow() || !visibility.spotLights[i])
  598. continue;
  599. ShadowMapOptions options;
  600. options.lightIdx = i;
  601. float maxFadePercent;
  602. calcShadowMapProperties(light, viewGroup, SHADOW_MAP_BORDER, options.mapSize, options.fadePercents, maxFadePercent);
  603. // Don't render shadow maps that will end up nearly completely faded out
  604. if (maxFadePercent < 0.005f)
  605. continue;
  606. mSpotLightShadowOptions.push_back(options);
  607. shadowInfoCount++; // For now, always a single fully dynamic shadow for a single light, but that may change
  608. }
  609. for (UINT32 i = 0; i < (UINT32)sceneInfo.radialLights.size(); ++i)
  610. {
  611. const RendererLight& light = sceneInfo.radialLights[i];
  612. mRadialLightShadows[i].startIdx = shadowInfoCount;
  613. mRadialLightShadows[i].numShadows = 0;
  614. // Note: I'm using visibility across all views, while I could be using visibility for every view individually,
  615. // if I kept that information somewhere
  616. if (!light.internal->getCastsShadow() || !visibility.radialLights[i])
  617. continue;
  618. ShadowMapOptions options;
  619. options.lightIdx = i;
  620. float maxFadePercent;
  621. calcShadowMapProperties(light, viewGroup, 0, options.mapSize, options.fadePercents, maxFadePercent);
  622. // Don't render shadow maps that will end up nearly completely faded out
  623. if (maxFadePercent < 0.005f)
  624. continue;
  625. mRadialLightShadowOptions.push_back(options);
  626. shadowInfoCount++; // For now, always a single fully dynamic shadow for a single light, but that may change
  627. }
  628. // Sort spot lights by size so they fit neatly in the texture atlas
  629. std::sort(mSpotLightShadowOptions.begin(), mSpotLightShadowOptions.end(),
  630. [](const ShadowMapOptions& a, const ShadowMapOptions& b) { return a.mapSize > b.mapSize; } );
  631. // Reserve space for shadow infos
  632. mShadowInfos.resize(shadowInfoCount);
  633. // Deallocate unused textures (must be done before rendering shadows, in order to ensure indices don't change)
  634. for(auto iter = mDynamicShadowMaps.begin(); iter != mDynamicShadowMaps.end(); ++iter)
  635. {
  636. if(iter->getLastUsedCounter() >= MAX_UNUSED_FRAMES)
  637. {
  638. // These are always populated in order, so we can assume all following atlases are also empty
  639. mDynamicShadowMaps.erase(iter, mDynamicShadowMaps.end());
  640. break;
  641. }
  642. }
  643. for(auto iter = mCascadedShadowMaps.begin(); iter != mCascadedShadowMaps.end();)
  644. {
  645. if (iter->getLastUsedCounter() >= MAX_UNUSED_FRAMES)
  646. iter = mCascadedShadowMaps.erase(iter);
  647. else
  648. ++iter;
  649. }
  650. for(auto iter = mShadowCubemaps.begin(); iter != mShadowCubemaps.end();)
  651. {
  652. if (iter->getLastUsedCounter() >= MAX_UNUSED_FRAMES)
  653. iter = mShadowCubemaps.erase(iter);
  654. else
  655. ++iter;
  656. }
  657. // Render shadow maps
  658. for (UINT32 i = 0; i < (UINT32)sceneInfo.directionalLights.size(); ++i)
  659. {
  660. const RendererLight& light = sceneInfo.directionalLights[i];
  661. if (!light.internal->getCastsShadow())
  662. return;
  663. UINT32 numViews = viewGroup.getNumViews();
  664. mDirectionalLightShadows[i].viewShadows.resize(numViews);
  665. for (UINT32 j = 0; j < numViews; ++j)
  666. renderCascadedShadowMaps(*viewGroup.getView(j), i, scene, frameInfo);
  667. }
  668. for(auto& entry : mSpotLightShadowOptions)
  669. {
  670. UINT32 lightIdx = entry.lightIdx;
  671. renderSpotShadowMap(sceneInfo.spotLights[lightIdx], entry, scene, frameInfo);
  672. }
  673. for (auto& entry : mRadialLightShadowOptions)
  674. {
  675. UINT32 lightIdx = entry.lightIdx;
  676. renderRadialShadowMap(sceneInfo.radialLights[lightIdx], entry, scene, frameInfo);
  677. }
  678. }
  679. /**
  680. * Generates a frustum from the provided view-projection matrix.
  681. *
  682. * @param[in] invVP Inverse of the view-projection matrix to use for generating the frustum.
  683. * @param[out] worldFrustum Generated frustum planes, in world space.
  684. * @return Individual vertices of the frustum corners, in world space. Ordered using the
  685. * AABox::CornerEnum.
  686. */
  687. std::array<Vector3, 8> getFrustum(const Matrix4& invVP, ConvexVolume& worldFrustum)
  688. {
  689. std::array<Vector3, 8> output;
  690. RenderAPI& rapi = RenderAPI::instance();
  691. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  692. float flipY = 1.0f;
  693. if (rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown))
  694. flipY = -1.0f;
  695. AABox frustumCube(
  696. Vector3(-1, -1 * flipY, rapiInfo.getMinimumDepthInputValue()),
  697. Vector3(1, 1 * flipY, rapiInfo.getMaximumDepthInputValue())
  698. );
  699. for(size_t i = 0; i < output.size(); i++)
  700. {
  701. Vector3 corner = frustumCube.getCorner((AABox::Corner)i);
  702. output[i] = invVP.multiply(corner);
  703. }
  704. Vector<Plane> planes(6);
  705. planes[FRUSTUM_PLANE_NEAR] = Plane(output[AABox::NEAR_LEFT_BOTTOM], output[AABox::NEAR_RIGHT_BOTTOM], output[AABox::NEAR_RIGHT_TOP]);
  706. planes[FRUSTUM_PLANE_FAR] = Plane(output[AABox::FAR_LEFT_BOTTOM], output[AABox::FAR_LEFT_TOP], output[AABox::FAR_RIGHT_TOP]);
  707. planes[FRUSTUM_PLANE_LEFT] = Plane(output[AABox::NEAR_LEFT_BOTTOM], output[AABox::NEAR_LEFT_TOP], output[AABox::FAR_LEFT_TOP]);
  708. planes[FRUSTUM_PLANE_RIGHT] = Plane(output[AABox::FAR_RIGHT_TOP], output[AABox::NEAR_RIGHT_TOP], output[AABox::NEAR_RIGHT_BOTTOM]);
  709. planes[FRUSTUM_PLANE_TOP] = Plane(output[AABox::NEAR_LEFT_TOP], output[AABox::NEAR_RIGHT_TOP], output[AABox::FAR_RIGHT_TOP]);
  710. planes[FRUSTUM_PLANE_BOTTOM] = Plane(output[AABox::NEAR_LEFT_BOTTOM], output[AABox::FAR_LEFT_BOTTOM], output[AABox::FAR_RIGHT_BOTTOM]);
  711. worldFrustum = ConvexVolume(planes);
  712. return output;
  713. }
  714. /**
  715. * Converts a point in mixed space (clip_x, clip_y, view_z, view_w) to UV coordinates on a shadow map (x, y),
  716. * and normalized linear depth from the shadow caster's perspective (z).
  717. */
  718. Matrix4 createMixedToShadowUVMatrix(const Matrix4& viewP, const Matrix4& viewInvVP, const Rect2& shadowMapArea,
  719. float depthScale, float depthOffset, const Matrix4& shadowViewProj)
  720. {
  721. // Projects a point from (clip_x, clip_y, view_z, view_w) into clip space
  722. Matrix4 mixedToShadow = Matrix4::IDENTITY;
  723. mixedToShadow[2][2] = viewP[2][2];
  724. mixedToShadow[2][3] = viewP[2][3];
  725. mixedToShadow[3][2] = viewP[3][2];
  726. mixedToShadow[3][3] = 0.0f;
  727. // Projects a point in clip space back to homogeneus world space
  728. mixedToShadow = viewInvVP * mixedToShadow;
  729. // Projects a point in world space to shadow clip space
  730. mixedToShadow = shadowViewProj * mixedToShadow;
  731. // Convert shadow clip space coordinates to UV coordinates relative to the shadow map rectangle, and normalize
  732. // depth
  733. RenderAPI& rapi = RenderAPI::instance();
  734. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  735. float flipY = -1.0f;
  736. // Either of these flips the Y axis, but if they're both true they cancel out
  737. if (rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp) ^ rapiInfo.isFlagSet(RenderAPIFeatureFlag::NDCYAxisDown))
  738. flipY = -flipY;
  739. Matrix4 shadowMapTfrm
  740. (
  741. shadowMapArea.width * 0.5f, 0, 0, shadowMapArea.x + 0.5f * shadowMapArea.width,
  742. 0, flipY * shadowMapArea.height * 0.5f, 0, shadowMapArea.y + 0.5f * shadowMapArea.height,
  743. 0, 0, depthScale, depthOffset,
  744. 0, 0, 0, 1
  745. );
  746. return shadowMapTfrm * mixedToShadow;
  747. }
  748. void ShadowRendering::renderShadowOcclusion(const RendererView& view, const RendererLight& rendererLight,
  749. GBufferTextures gbuffer) const
  750. {
  751. UINT32 shadowQuality = view.getRenderSettings().shadowSettings.shadowFilteringQuality;
  752. const Light* light = rendererLight.internal;
  753. UINT32 lightIdx = light->getRendererId();
  754. auto viewProps = view.getProperties();
  755. const Matrix4& viewP = viewProps.projTransform;
  756. Matrix4 viewInvVP = viewProps.viewProjTransform.inverse();
  757. SPtr<GpuParamBlockBuffer> perViewBuffer = view.getPerViewBuffer();
  758. RenderAPI& rapi = RenderAPI::instance();
  759. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  760. // TODO - Calculate and set a scissor rectangle for the light
  761. SPtr<GpuParamBlockBuffer> shadowParamBuffer = gShadowProjectParamsDef.createBuffer();
  762. SPtr<GpuParamBlockBuffer> shadowOmniParamBuffer = gShadowProjectOmniParamsDef.createBuffer();
  763. UINT32 viewIdx = view.getViewIdx();
  764. Vector<const ShadowInfo*> shadowInfos;
  765. if(light->getType() == LightType::Radial)
  766. {
  767. const LightShadows& shadows = mRadialLightShadows[lightIdx];
  768. for(UINT32 i = 0; i < shadows.numShadows; ++i)
  769. {
  770. UINT32 shadowIdx = shadows.startIdx + i;
  771. const ShadowInfo& shadowInfo = mShadowInfos[shadowIdx];
  772. if (shadowInfo.fadePerView[viewIdx] < 0.005f)
  773. continue;
  774. for(UINT32 j = 0; j < 6; j++)
  775. gShadowProjectOmniParamsDef.gFaceVPMatrices.set(shadowOmniParamBuffer, shadowInfo.shadowVPTransforms[j], j);
  776. gShadowProjectOmniParamsDef.gDepthBias.set(shadowOmniParamBuffer, shadowInfo.depthBias);
  777. gShadowProjectOmniParamsDef.gFadePercent.set(shadowOmniParamBuffer, shadowInfo.fadePerView[viewIdx]);
  778. gShadowProjectOmniParamsDef.gInvResolution.set(shadowOmniParamBuffer, 1.0f / shadowInfo.area.width);
  779. const Transform& tfrm = light->getTransform();
  780. Vector4 lightPosAndRadius(tfrm.getPosition(), light->getAttenuationRadius());
  781. gShadowProjectOmniParamsDef.gLightPosAndRadius.set(shadowOmniParamBuffer, lightPosAndRadius);
  782. // Reduce shadow quality based on shadow map resolution for spot lights
  783. UINT32 effectiveShadowQuality = getShadowQuality(shadowQuality, shadowInfo.area.width, 2);
  784. // Check if viewer is inside the light bounds
  785. //// Expand the light bounds slightly to handle the case when the near plane is intersecting the light volume
  786. float lightRadius = light->getAttenuationRadius() + viewProps.nearPlane * 3.0f;
  787. bool viewerInsideVolume = (tfrm.getPosition() - viewProps.viewOrigin).length() < lightRadius;
  788. SPtr<Texture> shadowMap = mShadowCubemaps[shadowInfo.textureIdx].getTexture();
  789. ShadowProjectParams shadowParams(*light, shadowMap, shadowOmniParamBuffer, perViewBuffer, gbuffer);
  790. ShadowProjectOmniMat* mat = ShadowProjectOmniMat::getVariation(effectiveShadowQuality, viewerInsideVolume,
  791. viewProps.numSamples > 1);
  792. mat->bind(shadowParams);
  793. gRendererUtility().draw(gRendererUtility().getSphereStencil());
  794. }
  795. }
  796. else // Directional & spot
  797. {
  798. shadowInfos.clear();
  799. bool isCSM = light->getType() == LightType::Directional;
  800. if(!isCSM)
  801. {
  802. const LightShadows& shadows = mSpotLightShadows[lightIdx];
  803. for (UINT32 i = 0; i < shadows.numShadows; ++i)
  804. {
  805. UINT32 shadowIdx = shadows.startIdx + i;
  806. const ShadowInfo& shadowInfo = mShadowInfos[shadowIdx];
  807. if (shadowInfo.fadePerView[viewIdx] < 0.005f)
  808. continue;
  809. shadowInfos.push_back(&shadowInfo);
  810. }
  811. }
  812. else // Directional
  813. {
  814. const LightShadows& shadows = mDirectionalLightShadows[lightIdx].viewShadows[viewIdx];
  815. if (shadows.numShadows > 0)
  816. {
  817. UINT32 mapIdx = shadows.startIdx;
  818. const ShadowCascadedMap& cascadedMap = mCascadedShadowMaps[mapIdx];
  819. // Render cascades in far to near order.
  820. // Note: If rendering other non-cascade maps they should be rendered after cascades.
  821. for (INT32 i = cascadedMap.getNumCascades() - 1; i >= 0; i--)
  822. shadowInfos.push_back(&cascadedMap.getShadowInfo(i));
  823. }
  824. }
  825. for(auto& shadowInfo : shadowInfos)
  826. {
  827. float depthScale, depthOffset;
  828. // Depth range scale is already baked into the ortho projection matrix, so avoid doing it here
  829. if (isCSM)
  830. {
  831. // Need to map from API-specific clip space depth to [0, 1] range
  832. depthScale = 1.0f / (rapiInfo.getMaximumDepthInputValue() - rapiInfo.getMinimumDepthInputValue());
  833. depthOffset = -rapiInfo.getMinimumDepthInputValue() * depthScale;
  834. }
  835. else
  836. {
  837. depthScale = 1.0f / shadowInfo->depthRange;
  838. depthOffset = 0.0f;
  839. }
  840. SPtr<Texture> shadowMap;
  841. UINT32 shadowMapFace = 0;
  842. if(!isCSM)
  843. shadowMap = mDynamicShadowMaps[shadowInfo->textureIdx].getTexture();
  844. else
  845. {
  846. shadowMap = mCascadedShadowMaps[shadowInfo->textureIdx].getTexture();
  847. shadowMapFace = shadowInfo->cascadeIdx;
  848. }
  849. Matrix4 mixedToShadowUV = createMixedToShadowUVMatrix(viewP, viewInvVP, shadowInfo->normArea,
  850. depthScale, depthOffset, shadowInfo->shadowVPTransform);
  851. auto shadowMapProps = shadowMap->getProperties();
  852. Vector2 shadowMapSize((float)shadowMapProps.getWidth(), (float)shadowMapProps.getHeight());
  853. float transitionScale = getFadeTransition(*light, shadowInfo->subjectBounds.getRadius(),
  854. shadowInfo->depthRange, shadowInfo->area.width);
  855. gShadowProjectParamsDef.gFadePlaneDepth.set(shadowParamBuffer, shadowInfo->depthFade);
  856. gShadowProjectParamsDef.gMixedToShadowSpace.set(shadowParamBuffer, mixedToShadowUV);
  857. gShadowProjectParamsDef.gShadowMapSize.set(shadowParamBuffer, shadowMapSize);
  858. gShadowProjectParamsDef.gShadowMapSizeInv.set(shadowParamBuffer, 1.0f / shadowMapSize);
  859. gShadowProjectParamsDef.gSoftTransitionScale.set(shadowParamBuffer, transitionScale);
  860. if(isCSM)
  861. gShadowProjectParamsDef.gFadePercent.set(shadowParamBuffer, 1.0f);
  862. else
  863. gShadowProjectParamsDef.gFadePercent.set(shadowParamBuffer, shadowInfo->fadePerView[viewIdx]);
  864. if(shadowInfo->fadeRange == 0.0f)
  865. gShadowProjectParamsDef.gInvFadePlaneRange.set(shadowParamBuffer, 0.0f);
  866. else
  867. gShadowProjectParamsDef.gInvFadePlaneRange.set(shadowParamBuffer, 1.0f / shadowInfo->fadeRange);
  868. // Generate a stencil buffer to avoid evaluating pixels without any receiver geometry in the shadow area
  869. std::array<Vector3, 8> frustumVertices;
  870. UINT32 effectiveShadowQuality = shadowQuality;
  871. if(!isCSM)
  872. {
  873. ConvexVolume shadowFrustum;
  874. frustumVertices = getFrustum(shadowInfo->shadowVPTransform.inverse(), shadowFrustum);
  875. // Check if viewer is inside the frustum. Frustum is slightly expanded so that if the near plane is
  876. // intersecting the shadow frustum, it is counted as inside. This needs to be conservative as the code
  877. // for handling viewer outside the frustum will not properly render intersections with the near plane.
  878. bool viewerInsideFrustum = shadowFrustum.contains(viewProps.viewOrigin, viewProps.nearPlane * 3.0f);
  879. ShadowProjectStencilMat* mat = ShadowProjectStencilMat::getVariation(false, viewerInsideFrustum);
  880. mat->bind(perViewBuffer);
  881. drawFrustum(frustumVertices);
  882. // Reduce shadow quality based on shadow map resolution for spot lights
  883. effectiveShadowQuality = getShadowQuality(shadowQuality, shadowInfo->area.width, 2);
  884. }
  885. else
  886. {
  887. // Need to generate near and far planes to clip the geometry within the current CSM slice.
  888. // Note: If the render API supports built-in depth bound tests that could be used instead.
  889. Vector3 near = viewProps.projTransform.multiply(Vector3(0, 0, -shadowInfo->depthNear));
  890. Vector3 far = viewProps.projTransform.multiply(Vector3(0, 0, -shadowInfo->depthFar));
  891. ShadowProjectStencilMat* mat = ShadowProjectStencilMat::getVariation(true, true);
  892. mat->bind(perViewBuffer);
  893. drawNearFarPlanes(near.z, far.z, shadowInfo->cascadeIdx != 0);
  894. }
  895. gShadowProjectParamsDef.gFace.set(shadowParamBuffer, (float)shadowMapFace);
  896. ShadowProjectParams shadowParams(*light, shadowMap, shadowParamBuffer, perViewBuffer, gbuffer);
  897. ShadowProjectMat* mat = ShadowProjectMat::getVariation(effectiveShadowQuality, isCSM, viewProps.numSamples > 1);
  898. mat->bind(shadowParams);
  899. if (!isCSM)
  900. drawFrustum(frustumVertices);
  901. else
  902. gRendererUtility().drawScreenQuad();
  903. }
  904. }
  905. }
  906. void ShadowRendering::renderCascadedShadowMaps(const RendererView& view, UINT32 lightIdx, RendererScene& scene,
  907. const FrameInfo& frameInfo)
  908. {
  909. UINT32 viewIdx = view.getViewIdx();
  910. LightShadows& lightShadows = mDirectionalLightShadows[lightIdx].viewShadows[viewIdx];
  911. if (!view.getRenderSettings().enableShadows)
  912. {
  913. lightShadows.startIdx = -1;
  914. lightShadows.numShadows = 0;
  915. return;
  916. }
  917. // Note: Currently I'm using spherical bounds for the cascaded frustum which might result in non-optimal usage
  918. // of the shadow map. A different approach would be to generate a bounding box and then both adjust the aspect
  919. // ratio (and therefore dimensions) of the shadow map, as well as rotate the camera so the visible area best fits
  920. // in the map. It remains to be seen if this is viable.
  921. // - Note2: Actually both of these will likely have serious negative impact on shadow stability.
  922. const SceneInfo& sceneInfo = scene.getSceneInfo();
  923. const RendererLight& rendererLight = sceneInfo.directionalLights[lightIdx];
  924. Light* light = rendererLight.internal;
  925. RenderAPI& rapi = RenderAPI::instance();
  926. const Transform& tfrm = light->getTransform();
  927. Vector3 lightDir = -tfrm.getRotation().zAxis();
  928. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  929. ShadowInfo shadowInfo;
  930. shadowInfo.lightIdx = lightIdx;
  931. shadowInfo.textureIdx = -1;
  932. UINT32 mapSize = std::min(mShadowMapSize, MAX_ATLAS_SIZE);
  933. shadowInfo.area = Rect2I(0, 0, mapSize, mapSize);
  934. shadowInfo.updateNormArea(mapSize);
  935. UINT32 numCascades = view.getRenderSettings().shadowSettings.numCascades;
  936. for (UINT32 i = 0; i < (UINT32)mCascadedShadowMaps.size(); i++)
  937. {
  938. ShadowCascadedMap& shadowMap = mCascadedShadowMaps[i];
  939. if (!shadowMap.isUsed() && shadowMap.getSize() == mapSize && shadowMap.getNumCascades() == numCascades)
  940. {
  941. shadowInfo.textureIdx = i;
  942. shadowMap.markAsUsed();
  943. break;
  944. }
  945. }
  946. if (shadowInfo.textureIdx == (UINT32)-1)
  947. {
  948. shadowInfo.textureIdx = (UINT32)mCascadedShadowMaps.size();
  949. mCascadedShadowMaps.push_back(ShadowCascadedMap(mapSize, numCascades));
  950. ShadowCascadedMap& shadowMap = mCascadedShadowMaps.back();
  951. shadowMap.markAsUsed();
  952. }
  953. ShadowCascadedMap& shadowMap = mCascadedShadowMaps[shadowInfo.textureIdx];
  954. Quaternion lightRotation(BsIdentity);
  955. lightRotation.lookRotation(lightDir, Vector3::UNIT_Y);
  956. for (UINT32 i = 0; i < numCascades; ++i)
  957. {
  958. Sphere frustumBounds;
  959. ConvexVolume cascadeCullVolume = getCSMSplitFrustum(view, lightDir, i, numCascades, frustumBounds);
  960. // Make sure the size of the projected area is in multiples of shadow map pixel size (for stability)
  961. float worldUnitsPerTexel = frustumBounds.getRadius() * 2.0f / shadowMap.getSize();
  962. float orthoSize = floor(frustumBounds.getRadius() * 2.0f / worldUnitsPerTexel) * worldUnitsPerTexel * 0.5f;
  963. worldUnitsPerTexel = orthoSize * 2.0f / shadowMap.getSize();
  964. // Snap caster origin to the shadow map pixel grid, to ensure shadow map stability
  965. Vector3 casterOrigin = frustumBounds.getCenter();
  966. Matrix4 shadowView = Matrix4::view(Vector3::ZERO, lightRotation);
  967. Vector3 shadowSpaceOrigin = shadowView.multiplyAffine(casterOrigin);
  968. Vector2 snapOffset(fmod(shadowSpaceOrigin.x, worldUnitsPerTexel), fmod(shadowSpaceOrigin.y, worldUnitsPerTexel));
  969. shadowSpaceOrigin.x -= snapOffset.x;
  970. shadowSpaceOrigin.y -= snapOffset.y;
  971. Matrix4 shadowViewInv = shadowView.inverseAffine();
  972. casterOrigin = shadowViewInv.multiplyAffine(shadowSpaceOrigin);
  973. // Move the light so it is centered at the subject frustum, with depth range covering the frustum bounds
  974. shadowInfo.depthRange = frustumBounds.getRadius() * 2.0f;
  975. Vector3 offsetLightPos = casterOrigin - lightDir * frustumBounds.getRadius();
  976. Matrix4 offsetViewMat = Matrix4::view(offsetLightPos, lightRotation);
  977. Matrix4 proj = Matrix4::projectionOrthographic(-orthoSize, orthoSize, orthoSize, -orthoSize, 0.0f,
  978. shadowInfo.depthRange);
  979. RenderAPI::instance().convertProjectionMatrix(proj, proj);
  980. shadowInfo.cascadeIdx = i;
  981. shadowInfo.shadowVPTransform = proj * offsetViewMat;
  982. // Determine split range
  983. float splitNear = getCSMSplitDistance(view, i, numCascades);
  984. float splitFar = getCSMSplitDistance(view, i + 1, numCascades);
  985. shadowInfo.depthNear = splitNear;
  986. shadowInfo.depthFade = splitFar;
  987. shadowInfo.subjectBounds = frustumBounds;
  988. if ((UINT32)(i + 1) < numCascades)
  989. shadowInfo.fadeRange = CASCADE_FRACTION_FADE * (shadowInfo.depthFade - shadowInfo.depthNear);
  990. else
  991. shadowInfo.fadeRange = 0.0f;
  992. shadowInfo.depthFar = shadowInfo.depthFade + shadowInfo.fadeRange;
  993. shadowInfo.depthBias = getDepthBias(*light, frustumBounds.getRadius(), shadowInfo.depthRange, mapSize);
  994. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, shadowInfo.depthBias);
  995. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / shadowInfo.depthRange);
  996. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, shadowInfo.shadowVPTransform);
  997. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  998. rapi.setRenderTarget(shadowMap.getTarget(i));
  999. rapi.clearRenderTarget(FBT_DEPTH);
  1000. ShadowDepthDirectionalMat* depthDirMat = ShadowDepthDirectionalMat::get();
  1001. depthDirMat->bind(shadowParamsBuffer);
  1002. // Render all renderables into the shadow map
  1003. ShadowRenderQueueDirOptions dirOptions(
  1004. cascadeCullVolume,
  1005. shadowParamsBuffer);
  1006. ShadowRenderQueue::execute(scene, frameInfo, dirOptions);
  1007. shadowMap.setShadowInfo(i, shadowInfo);
  1008. }
  1009. lightShadows.startIdx = shadowInfo.textureIdx;
  1010. lightShadows.numShadows = 1;
  1011. }
  1012. void ShadowRendering::renderSpotShadowMap(const RendererLight& rendererLight, const ShadowMapOptions& options,
  1013. RendererScene& scene, const FrameInfo& frameInfo)
  1014. {
  1015. Light* light = rendererLight.internal;
  1016. const SceneInfo& sceneInfo = scene.getSceneInfo();
  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. const SceneInfo& sceneInfo = scene.getSceneInfo();
  1090. SPtr<GpuParamBlockBuffer> shadowParamsBuffer = gShadowParamsDef.createBuffer();
  1091. SPtr<GpuParamBlockBuffer> shadowCubeMatricesBuffer = gShadowCubeMatricesDef.createBuffer();
  1092. SPtr<GpuParamBlockBuffer> shadowCubeMasksBuffer = gShadowCubeMasksDef.createBuffer();
  1093. ShadowInfo mapInfo;
  1094. mapInfo.lightIdx = options.lightIdx;
  1095. mapInfo.textureIdx = -1;
  1096. mapInfo.fadePerView = options.fadePercents;
  1097. mapInfo.cascadeIdx = -1;
  1098. mapInfo.area = Rect2I(0, 0, options.mapSize, options.mapSize);
  1099. mapInfo.updateNormArea(options.mapSize);
  1100. for (UINT32 i = 0; i < (UINT32)mShadowCubemaps.size(); i++)
  1101. {
  1102. ShadowCubemap& cubemap = mShadowCubemaps[i];
  1103. if (!cubemap.isUsed() && cubemap.getSize() == options.mapSize)
  1104. {
  1105. mapInfo.textureIdx = i;
  1106. cubemap.markAsUsed();
  1107. break;
  1108. }
  1109. }
  1110. if (mapInfo.textureIdx == (UINT32)-1)
  1111. {
  1112. mapInfo.textureIdx = (UINT32)mShadowCubemaps.size();
  1113. mShadowCubemaps.push_back(ShadowCubemap(options.mapSize));
  1114. ShadowCubemap& cubemap = mShadowCubemaps.back();
  1115. cubemap.markAsUsed();
  1116. }
  1117. ShadowCubemap& cubemap = mShadowCubemaps[mapInfo.textureIdx];
  1118. mapInfo.depthNear = 0.05f;
  1119. mapInfo.depthFar = light->getAttenuationRadius();
  1120. mapInfo.depthFade = mapInfo.depthFar;
  1121. mapInfo.fadeRange = 0.0f;
  1122. mapInfo.depthRange = mapInfo.depthFar - mapInfo.depthNear;
  1123. mapInfo.depthBias = getDepthBias(*light, light->getBounds().getRadius(), mapInfo.depthRange, options.mapSize);
  1124. mapInfo.subjectBounds = light->getBounds();
  1125. // Note: Projecting on positive Z axis, because cubemaps use a left-handed coordinate system
  1126. Matrix4 proj = Matrix4::projectionPerspective(Degree(90.0f), 1.0f, 0.05f, light->getAttenuationRadius(), true);
  1127. ConvexVolume localFrustum(proj);
  1128. RenderAPI& rapi = RenderAPI::instance();
  1129. const RenderAPIInfo& rapiInfo = rapi.getAPIInfo();
  1130. rapi.convertProjectionMatrix(proj, proj);
  1131. // Render cubemaps upside down if necessary
  1132. Matrix4 adjustedProj = proj;
  1133. if(rapiInfo.isFlagSet(RenderAPIFeatureFlag::UVYAxisUp))
  1134. {
  1135. // All big APIs use the same cubemap sampling coordinates, as well as the same face order. But APIs that
  1136. // use bottom-up UV coordinates require the cubemap faces to be stored upside down in order to get the same
  1137. // behaviour. APIs that use an upside-down NDC Y axis have the same problem as the rendered image will be
  1138. // upside down, but this is handled by the projection matrix. If both of those are enabled, then the effect
  1139. // cancels out.
  1140. adjustedProj[1][1] = -proj[1][1];
  1141. }
  1142. gShadowParamsDef.gDepthBias.set(shadowParamsBuffer, mapInfo.depthBias);
  1143. gShadowParamsDef.gInvDepthRange.set(shadowParamsBuffer, 1.0f / mapInfo.depthRange);
  1144. gShadowParamsDef.gMatViewProj.set(shadowParamsBuffer, Matrix4::IDENTITY);
  1145. gShadowParamsDef.gNDCZToDeviceZ.set(shadowParamsBuffer, RendererView::getNDCZToDeviceZ());
  1146. ConvexVolume frustums[6];
  1147. Vector<Plane> boundingPlanes;
  1148. for (UINT32 i = 0; i < 6; i++)
  1149. {
  1150. // Calculate view matrix
  1151. Vector3 forward;
  1152. Vector3 up = Vector3::UNIT_Y;
  1153. switch (i)
  1154. {
  1155. case CF_PositiveX:
  1156. forward = Vector3::UNIT_X;
  1157. break;
  1158. case CF_NegativeX:
  1159. forward = -Vector3::UNIT_X;
  1160. break;
  1161. case CF_PositiveY:
  1162. forward = Vector3::UNIT_Y;
  1163. up = -Vector3::UNIT_Z;
  1164. break;
  1165. case CF_NegativeY:
  1166. forward = -Vector3::UNIT_Y;
  1167. up = Vector3::UNIT_Z;
  1168. break;
  1169. case CF_PositiveZ:
  1170. forward = Vector3::UNIT_Z;
  1171. break;
  1172. case CF_NegativeZ:
  1173. forward = -Vector3::UNIT_Z;
  1174. break;
  1175. }
  1176. Vector3 right = Vector3::cross(up, forward);
  1177. Matrix3 viewRotationMat = Matrix3(right, up, forward);
  1178. Vector3 lightPos = light->getTransform().getPosition();
  1179. Matrix4 viewOffsetMat = Matrix4::translation(-lightPos);
  1180. Matrix4 view = Matrix4(viewRotationMat.transpose()) * viewOffsetMat;
  1181. mapInfo.shadowVPTransforms[i] = proj * view;
  1182. Matrix4 shadowViewProj = adjustedProj * view;
  1183. gShadowCubeMatricesDef.gFaceVPMatrices.set(shadowCubeMatricesBuffer, shadowViewProj, i);
  1184. // Calculate world frustum for culling
  1185. const Vector<Plane>& frustumPlanes = localFrustum.getPlanes();
  1186. Matrix4 worldMatrix = Matrix4::translation(lightPos) * Matrix4(viewRotationMat);
  1187. Vector<Plane> worldPlanes(frustumPlanes.size());
  1188. UINT32 j = 0;
  1189. for (auto& plane : frustumPlanes)
  1190. {
  1191. worldPlanes[j] = worldMatrix.multiplyAffine(plane);
  1192. j++;
  1193. }
  1194. frustums[i] = ConvexVolume(worldPlanes);
  1195. // Register far plane of all frustums
  1196. boundingPlanes.push_back(worldPlanes.back());
  1197. }
  1198. rapi.setRenderTarget(cubemap.getTarget());
  1199. rapi.clearRenderTarget(FBT_DEPTH);
  1200. // Render all renderables into the shadow map
  1201. ConvexVolume boundingVolume(boundingPlanes);
  1202. ShadowRenderQueueCubeOptions cubeOptions(
  1203. frustums,
  1204. boundingVolume,
  1205. shadowParamsBuffer,
  1206. shadowCubeMatricesBuffer,
  1207. shadowCubeMasksBuffer);
  1208. ShadowRenderQueue::execute(scene, frameInfo, cubeOptions);
  1209. LightShadows& lightShadows = mRadialLightShadows[options.lightIdx];
  1210. mShadowInfos[lightShadows.startIdx + lightShadows.numShadows] = mapInfo;
  1211. lightShadows.numShadows++;
  1212. }
  1213. void ShadowRendering::calcShadowMapProperties(const RendererLight& light, const RendererViewGroup& viewGroup,
  1214. UINT32 border, UINT32& size, SmallVector<float, 6>& fadePercents, float& maxFadePercent) const
  1215. {
  1216. const static float SHADOW_TEXELS_PER_PIXEL = 1.0f;
  1217. // Find a view in which the light has the largest radius
  1218. float maxMapSize = 0.0f;
  1219. maxFadePercent = 0.0f;
  1220. for (int i = 0; i < (int)viewGroup.getNumViews(); ++i)
  1221. {
  1222. const RendererView& view = *viewGroup.getView(i);
  1223. const RendererViewProperties& viewProps = view.getProperties();
  1224. const RenderSettings& viewSettings = view.getRenderSettings();
  1225. if(!viewSettings.enableShadows)
  1226. fadePercents.push_back(0.0f);
  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. // Calculate the eight vertices of the split frustum
  1316. auto& viewProps = view.getProperties();
  1317. const Matrix4& projMat = viewProps.projTransform;
  1318. float aspect;
  1319. float nearHalfWidth, nearHalfHeight;
  1320. float farHalfWidth, farHalfHeight;
  1321. if(viewProps.projType == PT_PERSPECTIVE)
  1322. {
  1323. aspect = fabs(projMat[0][0] / projMat[1][1]);
  1324. float tanHalfFOV = 1.0f / projMat[0][0];
  1325. nearHalfWidth = splitNear * tanHalfFOV;
  1326. nearHalfHeight = nearHalfWidth * aspect;
  1327. farHalfWidth = splitFar * tanHalfFOV;
  1328. farHalfHeight = farHalfWidth * aspect;
  1329. }
  1330. else
  1331. {
  1332. aspect = projMat[0][0] / projMat[1][1];
  1333. nearHalfWidth = farHalfWidth = projMat[0][0] / 4.0f;
  1334. nearHalfHeight = farHalfHeight = projMat[1][1] / 4.0f;
  1335. }
  1336. const Matrix4& viewMat = viewProps.viewTransform;
  1337. Vector3 cameraRight = Vector3(viewMat[0]);
  1338. Vector3 cameraUp = Vector3(viewMat[1]);
  1339. const Vector3& viewOrigin = viewProps.viewOrigin;
  1340. const Vector3& viewDir = viewProps.viewDirection;
  1341. Vector3 frustumVerts[] =
  1342. {
  1343. viewOrigin + viewDir * splitNear - cameraRight * nearHalfWidth + cameraUp * nearHalfHeight, // Near, left, top
  1344. viewOrigin + viewDir * splitNear + cameraRight * nearHalfWidth + cameraUp * nearHalfHeight, // Near, right, top
  1345. viewOrigin + viewDir * splitNear + cameraRight * nearHalfWidth - cameraUp * nearHalfHeight, // Near, right, bottom
  1346. viewOrigin + viewDir * splitNear - cameraRight * nearHalfWidth - cameraUp * nearHalfHeight, // Near, left, bottom
  1347. viewOrigin + viewDir * splitFar - cameraRight * farHalfWidth + cameraUp * farHalfHeight, // Far, left, top
  1348. viewOrigin + viewDir * splitFar + cameraRight * farHalfWidth + cameraUp * farHalfHeight, // Far, right, top
  1349. viewOrigin + viewDir * splitFar + cameraRight * farHalfWidth - cameraUp * farHalfHeight, // Far, right, bottom
  1350. viewOrigin + viewDir * splitFar - cameraRight * farHalfWidth - cameraUp * farHalfHeight, // Far, left, bottom
  1351. };
  1352. // Calculate the bounding sphere of the frustum
  1353. float diagonalNearSq = nearHalfWidth * nearHalfWidth + nearHalfHeight * nearHalfHeight;
  1354. float diagonalFarSq = farHalfWidth * farHalfWidth + farHalfHeight * farHalfHeight;
  1355. float length = splitFar - splitNear;
  1356. float offset = (diagonalNearSq - diagonalFarSq) / (2 * length) + length * 0.5f;
  1357. float distToCenter = Math::clamp(splitFar - offset, splitNear, splitFar);
  1358. Vector3 center = viewOrigin + viewDir * distToCenter;
  1359. float radius = 0.0f;
  1360. for (auto& entry : frustumVerts)
  1361. radius = std::max(radius, center.squaredDistance(entry));
  1362. radius = std::max((float)sqrt(radius), 1.0f);
  1363. outBounds = Sphere(center, radius);
  1364. // Generate light frustum planes
  1365. Plane viewPlanes[6];
  1366. viewPlanes[FRUSTUM_PLANE_NEAR] = Plane(frustumVerts[0], frustumVerts[1], frustumVerts[2]);
  1367. viewPlanes[FRUSTUM_PLANE_FAR] = Plane(frustumVerts[5], frustumVerts[4], frustumVerts[7]);
  1368. viewPlanes[FRUSTUM_PLANE_LEFT] = Plane(frustumVerts[4], frustumVerts[0], frustumVerts[3]);
  1369. viewPlanes[FRUSTUM_PLANE_RIGHT] = Plane(frustumVerts[1], frustumVerts[5], frustumVerts[6]);
  1370. viewPlanes[FRUSTUM_PLANE_TOP] = Plane(frustumVerts[4], frustumVerts[5], frustumVerts[1]);
  1371. viewPlanes[FRUSTUM_PLANE_BOTTOM] = Plane(frustumVerts[3], frustumVerts[2], frustumVerts[6]);
  1372. //// Add camera's planes facing towards the lights (forming the back of the volume)
  1373. Vector<Plane> lightVolume;
  1374. for(auto& entry : viewPlanes)
  1375. {
  1376. if (entry.normal.dot(lightDir) < 0.0f)
  1377. lightVolume.push_back(entry);
  1378. }
  1379. //// Determine edge planes by testing adjacent planes with different facing
  1380. ////// Pairs of frustum planes that share an edge
  1381. UINT32 adjacentPlanes[][2] =
  1382. {
  1383. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_LEFT },
  1384. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_RIGHT },
  1385. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_TOP },
  1386. { FRUSTUM_PLANE_NEAR, FRUSTUM_PLANE_BOTTOM },
  1387. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_LEFT },
  1388. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_RIGHT },
  1389. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_TOP },
  1390. { FRUSTUM_PLANE_FAR, FRUSTUM_PLANE_BOTTOM },
  1391. { FRUSTUM_PLANE_LEFT, FRUSTUM_PLANE_TOP },
  1392. { FRUSTUM_PLANE_TOP, FRUSTUM_PLANE_RIGHT },
  1393. { FRUSTUM_PLANE_RIGHT, FRUSTUM_PLANE_BOTTOM },
  1394. { FRUSTUM_PLANE_BOTTOM, FRUSTUM_PLANE_LEFT },
  1395. };
  1396. ////// Vertex indices of edges on the boundary between two planes
  1397. UINT32 sharedEdges[][2] =
  1398. {
  1399. { 3, 0 },{ 1, 2 },{ 0, 1 },{ 2, 3 },
  1400. { 4, 7 },{ 6, 5 },{ 5, 4 },{ 7, 6 },
  1401. { 4, 0 },{ 5, 1 },{ 6, 2 },{ 7, 3 }
  1402. };
  1403. for(UINT32 i = 0; i < 12; i++)
  1404. {
  1405. const Plane& planeA = viewPlanes[adjacentPlanes[i][0]];
  1406. const Plane& planeB = viewPlanes[adjacentPlanes[i][1]];
  1407. float dotA = planeA.normal.dot(lightDir);
  1408. float dotB = planeB.normal.dot(lightDir);
  1409. if((dotA * dotB) < 0.0f)
  1410. {
  1411. const Vector3& vertA = frustumVerts[sharedEdges[i][0]];
  1412. const Vector3& vertB = frustumVerts[sharedEdges[i][1]];
  1413. Vector3 vertC = vertA + lightDir;
  1414. if (dotA < 0.0f)
  1415. lightVolume.push_back(Plane(vertA, vertB, vertC));
  1416. else
  1417. lightVolume.push_back(Plane(vertB, vertA, vertC));
  1418. }
  1419. }
  1420. return ConvexVolume(lightVolume);
  1421. }
  1422. float ShadowRendering::getCSMSplitDistance(const RendererView& view, UINT32 index, UINT32 numCascades)
  1423. {
  1424. auto& shadowSettings = view.getRenderSettings().shadowSettings;
  1425. float distributionExponent = shadowSettings.cascadeDistributionExponent;
  1426. // First determine the scale of the split, relative to the entire range
  1427. float scaleModifier = 1.0f;
  1428. float scale = 0.0f;
  1429. float totalScale = 0.0f;
  1430. //// Split 0 corresponds to near plane
  1431. if (index > 0)
  1432. {
  1433. for (UINT32 i = 0; i < numCascades; i++)
  1434. {
  1435. if (i < index)
  1436. scale += scaleModifier;
  1437. totalScale += scaleModifier;
  1438. scaleModifier *= distributionExponent;
  1439. }
  1440. scale = scale / totalScale;
  1441. }
  1442. // Calculate split distance in Z
  1443. auto& viewProps = view.getProperties();
  1444. float near = viewProps.nearPlane;
  1445. float far = Math::clamp(shadowSettings.directionalShadowDistance, viewProps.nearPlane, viewProps.farPlane);
  1446. return near + (far - near) * scale;
  1447. }
  1448. float ShadowRendering::getDepthBias(const Light& light, float radius, float depthRange, UINT32 mapSize)
  1449. {
  1450. const static float RADIAL_LIGHT_BIAS = 0.0005f;
  1451. const static float SPOT_DEPTH_BIAS = 0.01f;
  1452. const static float DIR_DEPTH_BIAS = 0.001f; // In clip space units
  1453. const static float DEFAULT_RESOLUTION = 512.0f;
  1454. // Increase bias if map size smaller than some resolution
  1455. float resolutionScale = 1.0f;
  1456. if (light.getType() != LightType::Directional)
  1457. resolutionScale = DEFAULT_RESOLUTION / (float)mapSize;
  1458. // Adjust range because in shader we compare vs. clip space depth
  1459. float rangeScale = 1.0f;
  1460. if (light.getType() == LightType::Spot)
  1461. rangeScale = 1.0f / depthRange;
  1462. auto& apiInfo = RenderAPI::instance().getAPIInfo();
  1463. float deviceDepthRange = apiInfo.getMaximumDepthInputValue() - apiInfo.getMinimumDepthInputValue();
  1464. float defaultBias = 1.0f;
  1465. switch(light.getType())
  1466. {
  1467. case LightType::Directional:
  1468. defaultBias = DIR_DEPTH_BIAS * deviceDepthRange;
  1469. break;
  1470. case LightType::Radial:
  1471. defaultBias = RADIAL_LIGHT_BIAS;
  1472. break;
  1473. case LightType::Spot:
  1474. defaultBias = SPOT_DEPTH_BIAS;
  1475. break;
  1476. default:
  1477. break;
  1478. }
  1479. return defaultBias * light.getShadowBias() * resolutionScale * rangeScale;
  1480. }
  1481. float ShadowRendering::getFadeTransition(const Light& light, float radius, float depthRange, UINT32 mapSize)
  1482. {
  1483. const static float SPOT_LIGHT_SCALE = 1000.0f;
  1484. const static float DIR_LIGHT_SCALE = 50000000.0f;
  1485. // Note: Currently fade transitions are only used in spot & directional (non omni-directional) lights, so no need
  1486. // to account for radial light type.
  1487. if (light.getType() == LightType::Directional)
  1488. {
  1489. // Reduce the size of the transition region when shadow map resolution is higher
  1490. float resolutionScale = 1.0f / (float)mapSize;
  1491. // Reduce the size of the transition region when the depth range is larger
  1492. float rangeScale = 1.0f / depthRange;
  1493. // Increase the size of the transition region for larger lights
  1494. float radiusScale = radius;
  1495. return DIR_LIGHT_SCALE * rangeScale * resolutionScale * radiusScale;
  1496. }
  1497. else
  1498. return fabs(light.getShadowBias()) * SPOT_LIGHT_SCALE;
  1499. }
  1500. }}