pssmLightShadowMap.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "lighting/shadowMap/pssmLightShadowMap.h"
  24. #include "lighting/common/lightMapParams.h"
  25. #include "console/console.h"
  26. #include "scene/sceneManager.h"
  27. #include "scene/sceneRenderState.h"
  28. #include "lighting/lightManager.h"
  29. #include "gfx/gfxDevice.h"
  30. #include "gfx/gfxTransformSaver.h"
  31. #include "gfx/util/gfxFrustumSaver.h"
  32. #include "renderInstance/renderPassManager.h"
  33. #include "gui/controls/guiBitmapCtrl.h"
  34. #include "lighting/shadowMap/shadowMapManager.h"
  35. #include "materials/shaderData.h"
  36. #include "ts/tsShapeInstance.h"
  37. #include "console/consoleTypes.h"
  38. AFTER_MODULE_INIT( Sim )
  39. {
  40. Con::addVariable( "$pref::PSSM::detailAdjustScale",
  41. TypeF32, &PSSMLightShadowMap::smDetailAdjustScale,
  42. "@brief Scales the model LOD when rendering into the PSSM shadow.\n"
  43. "Use this to reduce the draw calls when rendering the shadow by having "
  44. "meshes LOD out nearer to the camera than normal.\n"
  45. "@see $pref::TS::detailAdjust\n"
  46. "@ingroup AdvancedLighting" );
  47. Con::addVariable( "$pref::PSSM::smallestVisiblePixelSize",
  48. TypeF32, &PSSMLightShadowMap::smSmallestVisiblePixelSize,
  49. "@brief The smallest pixel size an object can be and still be rendered into the PSSM shadow.\n"
  50. "Use this to force culling of small objects which contribute little to the final shadow.\n"
  51. "@see $pref::TS::smallestVisiblePixelSize\n"
  52. "@ingroup AdvancedLighting" );
  53. }
  54. F32 PSSMLightShadowMap::smDetailAdjustScale = 0.85f;
  55. F32 PSSMLightShadowMap::smSmallestVisiblePixelSize = 25.0f;
  56. PSSMLightShadowMap::PSSMLightShadowMap( LightInfo *light )
  57. : LightShadowMap( light ),
  58. mNumSplits( 0 )
  59. {
  60. mIsViewDependent = true;
  61. }
  62. void PSSMLightShadowMap::_setNumSplits( U32 numSplits, U32 texSize )
  63. {
  64. AssertFatal( numSplits > 0 && numSplits <= MAX_SPLITS,
  65. "PSSMLightShadowMap::_setNumSplits() - Splits must be between 1 and 4!" );
  66. releaseTextures();
  67. mNumSplits = numSplits;
  68. mTexSize = texSize;
  69. F32 texWidth, texHeight;
  70. // If the split count is less than 4 then do a
  71. // 1xN layout of shadow maps...
  72. if ( mNumSplits < 4 )
  73. {
  74. texHeight = texSize;
  75. texWidth = texSize * mNumSplits;
  76. for ( U32 i = 0; i < 4; i++ )
  77. {
  78. mViewports[i].extent.set(texSize, texSize);
  79. mViewports[i].point.set(texSize*i, 0);
  80. }
  81. }
  82. else
  83. {
  84. // ... with 4 splits do a 2x2.
  85. texWidth = texHeight = texSize * 2;
  86. for ( U32 i = 0; i < 4; i++ )
  87. {
  88. F32 xOff = (i == 1 || i == 3) ? 0.5f : 0.0f;
  89. F32 yOff = (i > 1) ? 0.5f : 0.0f;
  90. mViewports[i].extent.set( texSize, texSize );
  91. mViewports[i].point.set( xOff * texWidth, yOff * texHeight );
  92. }
  93. }
  94. mShadowMapTex.set( texWidth, texHeight,
  95. ShadowMapFormat, &ShadowMapProfile,
  96. "PSSMLightShadowMap" );
  97. }
  98. void PSSMLightShadowMap::_calcSplitPos(const Frustum& currFrustum)
  99. {
  100. const F32 nearDist = 0.01f; // TODO: Should this be adjustable or different?
  101. const F32 farDist = currFrustum.getFarDist();
  102. for ( U32 i = 1; i < mNumSplits; i++ )
  103. {
  104. F32 step = (F32) i / (F32) mNumSplits;
  105. F32 logSplit = nearDist * mPow(farDist / nearDist, step);
  106. F32 linearSplit = nearDist + (farDist - nearDist) * step;
  107. mSplitDist[i] = mLerp( linearSplit, logSplit, mClampF( mLogWeight, 0.0f, 1.0f ) );
  108. }
  109. mSplitDist[0] = nearDist;
  110. mSplitDist[mNumSplits] = farDist;
  111. }
  112. Box3F PSSMLightShadowMap::_calcClipSpaceAABB(const Frustum& f, const MatrixF& transform, F32 farDist)
  113. {
  114. // Calculate frustum center
  115. Point3F center(0,0,0);
  116. for (U32 i = 0; i < 8; i++)
  117. {
  118. const Point3F& pt = f.getPoints()[i];
  119. center += pt;
  120. }
  121. center /= 8;
  122. // Calculate frustum bounding sphere radius
  123. F32 radius = 0.0f;
  124. for (U32 i = 0; i < 8; i++)
  125. radius = getMax(radius, (f.getPoints()[i] - center).lenSquared());
  126. radius = mFloor( mSqrt(radius) );
  127. // Now build box for sphere
  128. Box3F result;
  129. Point3F radiusBox(radius, radius, radius);
  130. result.minExtents = center - radiusBox;
  131. result.maxExtents = center + radiusBox;
  132. // Transform to light projection space
  133. transform.mul(result);
  134. return result;
  135. }
  136. // This "rounds" the projection matrix to remove subtexel movement during shadow map
  137. // rasterization. This is here to reduce shadow shimmering.
  138. void PSSMLightShadowMap::_roundProjection(const MatrixF& lightMat, const MatrixF& cropMatrix, Point3F &offset, U32 splitNum)
  139. {
  140. // Round to the nearest shadowmap texel, this helps reduce shimmering
  141. MatrixF currentProj = GFX->getProjectionMatrix();
  142. currentProj = cropMatrix * currentProj * lightMat;
  143. // Project origin to screen.
  144. Point4F originShadow4F(0,0,0,1);
  145. currentProj.mul(originShadow4F);
  146. Point2F originShadow(originShadow4F.x / originShadow4F.w, originShadow4F.y / originShadow4F.w);
  147. // Convert to texture space (0..shadowMapSize)
  148. F32 t = mNumSplits < 4 ? mShadowMapTex->getWidth() / mNumSplits : mShadowMapTex->getWidth() / 2;
  149. Point2F texelsToTexture(t / 2.0f, mShadowMapTex->getHeight() / 2.0f);
  150. if (mNumSplits >= 4) texelsToTexture.y *= 0.5f;
  151. originShadow.convolve(texelsToTexture);
  152. // Clamp to texel boundary
  153. Point2F originRounded;
  154. originRounded.x = mFloor(originShadow.x + 0.5f);
  155. originRounded.y = mFloor(originShadow.y + 0.5f);
  156. // Subtract origin to get an offset to recenter everything on texel boundaries
  157. originRounded -= originShadow;
  158. // Convert back to texels (0..1) and offset
  159. originRounded.convolveInverse(texelsToTexture);
  160. offset.x += originRounded.x;
  161. offset.y += originRounded.y;
  162. }
  163. void PSSMLightShadowMap::_render( RenderPassManager* renderPass,
  164. const SceneRenderState *diffuseState )
  165. {
  166. PROFILE_SCOPE(PSSMLightShadowMap_render);
  167. const ShadowMapParams *params = mLight->getExtended<ShadowMapParams>();
  168. const LightMapParams *lmParams = mLight->getExtended<LightMapParams>();
  169. const bool bUseLightmappedGeometry = lmParams ? !lmParams->representedInLightmap || lmParams->includeLightmappedGeometryInShadow : true;
  170. const U32 texSize = getBestTexSize( params->numSplits < 4 ? params->numSplits : 2 );
  171. if ( mShadowMapTex.isNull() ||
  172. mNumSplits != params->numSplits ||
  173. mTexSize != texSize )
  174. _setNumSplits( params->numSplits, texSize );
  175. mLogWeight = params->logWeight;
  176. Frustum fullFrustum( diffuseState->getCameraFrustum() );
  177. fullFrustum.cropNearFar(fullFrustum.getNearDist(), params->shadowDistance);
  178. GFXFrustumSaver frustSaver;
  179. GFXTransformSaver saver;
  180. // Set our render target
  181. GFX->pushActiveRenderTarget();
  182. mTarget->attachTexture( GFXTextureTarget::Color0, mShadowMapTex );
  183. mTarget->attachTexture( GFXTextureTarget::DepthStencil,
  184. _getDepthTarget( mShadowMapTex->getWidth(), mShadowMapTex->getHeight() ) );
  185. GFX->setActiveRenderTarget( mTarget );
  186. GFX->clear( GFXClearStencil | GFXClearZBuffer | GFXClearTarget, ColorI(255,255,255), 1.0f, 0 );
  187. // Calculate our standard light matrices
  188. MatrixF lightMatrix;
  189. calcLightMatrices( lightMatrix, diffuseState->getCameraFrustum() );
  190. lightMatrix.inverse();
  191. MatrixF lightViewProj = GFX->getProjectionMatrix() * lightMatrix;
  192. // TODO: This is just retrieving the near and far calculated
  193. // in calcLightMatrices... we should make that clear.
  194. F32 pnear, pfar;
  195. GFX->getFrustum( NULL, NULL, NULL, NULL, &pnear, &pfar, NULL );
  196. // Set our view up
  197. GFX->setWorldMatrix(lightMatrix);
  198. MatrixF toLightSpace = lightMatrix; // * invCurrentView;
  199. _calcSplitPos(fullFrustum);
  200. mWorldToLightProj = GFX->getProjectionMatrix() * toLightSpace;
  201. // Apply the PSSM
  202. const F32 savedSmallestVisible = TSShapeInstance::smSmallestVisiblePixelSize;
  203. const F32 savedDetailAdjust = TSShapeInstance::smDetailAdjust;
  204. TSShapeInstance::smDetailAdjust *= smDetailAdjustScale;
  205. TSShapeInstance::smSmallestVisiblePixelSize = smSmallestVisiblePixelSize;
  206. for (U32 i = 0; i < mNumSplits; i++)
  207. {
  208. GFXTransformSaver saver;
  209. // Calculate a sub-frustum
  210. Frustum subFrustum(fullFrustum);
  211. subFrustum.cropNearFar(mSplitDist[i], mSplitDist[i+1]);
  212. // Calculate our AABB in the light's clip space.
  213. Box3F clipAABB = _calcClipSpaceAABB(subFrustum, lightViewProj, fullFrustum.getFarDist());
  214. // Calculate our crop matrix
  215. Point3F scale(2.0f / (clipAABB.maxExtents.x - clipAABB.minExtents.x),
  216. 2.0f / (clipAABB.maxExtents.y - clipAABB.minExtents.y),
  217. 1.0f);
  218. // TODO: This seems to produce less "pops" of the
  219. // shadow resolution as the camera spins around and
  220. // it should produce pixels that are closer to being
  221. // square.
  222. //
  223. // Still is it the right thing to do?
  224. //
  225. scale.y = scale.x = ( getMin( scale.x, scale.y ) );
  226. //scale.x = mFloor(scale.x);
  227. //scale.y = mFloor(scale.y);
  228. Point3F offset( -0.5f * (clipAABB.maxExtents.x + clipAABB.minExtents.x) * scale.x,
  229. -0.5f * (clipAABB.maxExtents.y + clipAABB.minExtents.y) * scale.y,
  230. 0.0f );
  231. MatrixF cropMatrix(true);
  232. cropMatrix.scale(scale);
  233. cropMatrix.setPosition(offset);
  234. _roundProjection(lightMatrix, cropMatrix, offset, i);
  235. cropMatrix.setPosition(offset);
  236. // Save scale/offset for shader computations
  237. mScaleProj[i].set(scale);
  238. mOffsetProj[i].set(offset);
  239. // Adjust the far plane to the max z we got (maybe add a little to deal with split overlap)
  240. bool isOrtho;
  241. {
  242. F32 left, right, bottom, top, nearDist, farDist;
  243. GFX->getFrustum(&left, &right, &bottom, &top, &nearDist, &farDist,&isOrtho);
  244. // BTRTODO: Fix me!
  245. farDist = clipAABB.maxExtents.z;
  246. if (!isOrtho)
  247. GFX->setFrustum(left, right, bottom, top, nearDist, farDist);
  248. else
  249. {
  250. // Calculate a new far plane, add a fudge factor to avoid bringing
  251. // the far plane in too close.
  252. F32 newFar = pfar * clipAABB.maxExtents.z + 1.0f;
  253. mFarPlaneScalePSSM[i] = (pfar - pnear) / (newFar - pnear);
  254. GFX->setOrtho(left, right, bottom, top, pnear, newFar, true);
  255. }
  256. }
  257. // Crop matrix multiply needs to be post-projection.
  258. MatrixF alightProj = GFX->getProjectionMatrix();
  259. alightProj = cropMatrix * alightProj;
  260. // Set our new projection
  261. GFX->setProjectionMatrix(alightProj);
  262. // Render into the quad of the shadow map we are using.
  263. GFX->setViewport(mViewports[i]);
  264. SceneManager* sceneManager = diffuseState->getSceneManager();
  265. // The frustum is currently the full size and has not had
  266. // cropping applied.
  267. //
  268. // We make that adjustment here.
  269. const Frustum& uncroppedFrustum = GFX->getFrustum();
  270. Frustum croppedFrustum;
  271. scale *= 0.5f;
  272. croppedFrustum.set(
  273. isOrtho,
  274. uncroppedFrustum.getNearLeft() / scale.x,
  275. uncroppedFrustum.getNearRight() / scale.x,
  276. uncroppedFrustum.getNearTop() / scale.y,
  277. uncroppedFrustum.getNearBottom() / scale.y,
  278. uncroppedFrustum.getNearDist(),
  279. uncroppedFrustum.getFarDist(),
  280. uncroppedFrustum.getTransform()
  281. );
  282. MatrixF camera = GFX->getWorldMatrix();
  283. camera.inverse();
  284. croppedFrustum.setTransform( camera );
  285. // Setup the scene state and use the diffuse state
  286. // camera position and screen metrics values so that
  287. // lod is done the same as in the diffuse pass.
  288. SceneRenderState shadowRenderState
  289. (
  290. sceneManager,
  291. SPT_Shadow,
  292. SceneCameraState( diffuseState->getViewport(), croppedFrustum,
  293. GFX->getWorldMatrix(), GFX->getProjectionMatrix() ),
  294. renderPass
  295. );
  296. shadowRenderState.getMaterialDelegate().bind( this, &LightShadowMap::getShadowMaterial );
  297. shadowRenderState.renderNonLightmappedMeshes( true );
  298. shadowRenderState.renderLightmappedMeshes( bUseLightmappedGeometry );
  299. shadowRenderState.setDiffuseCameraTransform( diffuseState->getCameraTransform() );
  300. shadowRenderState.setWorldToScreenScale( diffuseState->getWorldToScreenScale() );
  301. U32 objectMask = SHADOW_TYPEMASK;
  302. if ( i == mNumSplits-1 && params->lastSplitTerrainOnly )
  303. objectMask = TerrainObjectType;
  304. sceneManager->renderSceneNoLights( &shadowRenderState, objectMask );
  305. _debugRender( &shadowRenderState );
  306. }
  307. // Restore the original TS lod settings.
  308. TSShapeInstance::smSmallestVisiblePixelSize = savedSmallestVisible;
  309. TSShapeInstance::smDetailAdjust = savedDetailAdjust;
  310. // Release our render target
  311. mTarget->resolve();
  312. GFX->popActiveRenderTarget();
  313. }
  314. void PSSMLightShadowMap::setShaderParameters(GFXShaderConstBuffer* params, LightingShaderConstants* lsc)
  315. {
  316. PROFILE_SCOPE( PSSMLightShadowMap_setShaderParameters );
  317. if ( lsc->mTapRotationTexSC->isValid() )
  318. GFX->setTexture( lsc->mTapRotationTexSC->getSamplerRegister(),
  319. SHADOWMGR->getTapRotationTex() );
  320. const ShadowMapParams *p = mLight->getExtended<ShadowMapParams>();
  321. Point4F sx(Point4F::Zero),
  322. sy(Point4F::Zero),
  323. ox(Point4F::Zero),
  324. oy(Point4F::Zero),
  325. aXOff(Point4F::Zero),
  326. aYOff(Point4F::Zero);
  327. for (U32 i = 0; i < mNumSplits; i++)
  328. {
  329. sx[i] = mScaleProj[i].x;
  330. sy[i] = mScaleProj[i].y;
  331. ox[i] = mOffsetProj[i].x;
  332. oy[i] = mOffsetProj[i].y;
  333. }
  334. Point2F shadowMapAtlas;
  335. if (mNumSplits < 4)
  336. {
  337. shadowMapAtlas.x = 1.0f / (F32)mNumSplits;
  338. shadowMapAtlas.y = 1.0f;
  339. // 1xmNumSplits
  340. for (U32 i = 0; i < mNumSplits; i++)
  341. aXOff[i] = (F32)i * shadowMapAtlas.x;
  342. }
  343. else
  344. {
  345. shadowMapAtlas.set(0.5f, 0.5f);
  346. // 2x2
  347. for (U32 i = 0; i < mNumSplits; i++)
  348. {
  349. if (i == 1 || i == 3)
  350. aXOff[i] = 0.5f;
  351. if (i > 1)
  352. aYOff[i] = 0.5f;
  353. }
  354. }
  355. params->setSafe(lsc->mScaleXSC, sx);
  356. params->setSafe(lsc->mScaleYSC, sy);
  357. params->setSafe(lsc->mOffsetXSC, ox);
  358. params->setSafe(lsc->mOffsetYSC, oy);
  359. params->setSafe(lsc->mAtlasXOffsetSC, aXOff);
  360. params->setSafe(lsc->mAtlasYOffsetSC, aYOff);
  361. params->setSafe(lsc->mAtlasScaleSC, shadowMapAtlas);
  362. Point4F lightParams( mLight->getRange().x, p->overDarkFactor.x, 0.0f, 0.0f );
  363. params->setSafe( lsc->mLightParamsSC, lightParams );
  364. params->setSafe( lsc->mFarPlaneScalePSSM, mFarPlaneScalePSSM);
  365. Point2F fadeStartLength(p->fadeStartDist, 0.0f);
  366. if (fadeStartLength.x == 0.0f)
  367. {
  368. // By default, lets fade the last half of the last split.
  369. fadeStartLength.x = (mSplitDist[mNumSplits-1] + mSplitDist[mNumSplits]) / 2.0f;
  370. }
  371. fadeStartLength.y = 1.0f / (mSplitDist[mNumSplits] - fadeStartLength.x);
  372. params->setSafe( lsc->mFadeStartLength, fadeStartLength);
  373. params->setSafe( lsc->mOverDarkFactorPSSM, p->overDarkFactor);
  374. // The softness is a factor of the texel size.
  375. params->setSafe( lsc->mShadowSoftnessConst, p->shadowSoftness * ( 1.0f / mTexSize ) );
  376. }