pssmLightShadowMap.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. #include "math/mathUtils.h"
  39. AFTER_MODULE_INIT( Sim )
  40. {
  41. Con::addVariable( "$pref::PSSM::detailAdjustScale",
  42. TypeF32, &PSSMLightShadowMap::smDetailAdjustScale,
  43. "@brief Scales the model LOD when rendering into the PSSM shadow.\n"
  44. "Use this to reduce the draw calls when rendering the shadow by having "
  45. "meshes LOD out nearer to the camera than normal.\n"
  46. "@see $pref::TS::detailAdjust\n"
  47. "@ingroup AdvancedLighting" );
  48. Con::addVariable( "$pref::PSSM::smallestVisiblePixelSize",
  49. TypeF32, &PSSMLightShadowMap::smSmallestVisiblePixelSize,
  50. "@brief The smallest pixel size an object can be and still be rendered into the PSSM shadow.\n"
  51. "Use this to force culling of small objects which contribute little to the final shadow.\n"
  52. "@see $pref::TS::smallestVisiblePixelSize\n"
  53. "@ingroup AdvancedLighting" );
  54. }
  55. F32 PSSMLightShadowMap::smDetailAdjustScale = 0.85f;
  56. F32 PSSMLightShadowMap::smSmallestVisiblePixelSize = 25.0f;
  57. PSSMLightShadowMap::PSSMLightShadowMap( LightInfo *light )
  58. : LightShadowMap( light ),
  59. mNumSplits( 1 ),
  60. mLogWeight(0.91f)
  61. {
  62. for (U32 i = 0; i <= MAX_SPLITS; i++) //% depth distance
  63. mSplitDist[i] = mPow(F32(i/MAX_SPLITS),2.0f);
  64. mIsViewDependent = true;
  65. }
  66. void PSSMLightShadowMap::_setNumSplits( U32 numSplits, U32 texSize )
  67. {
  68. AssertFatal(numSplits > 0 && numSplits <= MAX_SPLITS,
  69. avar("PSSMLightShadowMap::_setNumSplits() - Splits must be between 1 and %d!", MAX_SPLITS));
  70. releaseTextures();
  71. mNumSplits = numSplits;
  72. mTexSize = texSize;
  73. F32 texWidth, texHeight;
  74. // If the split count is less than 4 then do a
  75. // 1xN layout of shadow maps...
  76. if ( mNumSplits < 4 )
  77. {
  78. texHeight = texSize;
  79. texWidth = texSize * mNumSplits;
  80. for ( U32 i = 0; i < 4; i++ )
  81. {
  82. mViewports[i].extent.set(texSize, texSize);
  83. mViewports[i].point.set(texSize*i, 0);
  84. }
  85. }
  86. else
  87. {
  88. // ... with 4 splits do a 2x2.
  89. texWidth = texHeight = texSize * 2;
  90. for ( U32 i = 0; i < 4; i++ )
  91. {
  92. F32 xOff = (i == 1 || i == 3) ? 0.5f : 0.0f;
  93. F32 yOff = (i > 1) ? 0.5f : 0.0f;
  94. mViewports[i].extent.set( texSize, texSize );
  95. mViewports[i].point.set( xOff * texWidth, yOff * texHeight );
  96. }
  97. }
  98. mShadowMapTex.set( texWidth, texHeight,
  99. ShadowMapFormat, &ShadowMapProfile,
  100. "PSSMLightShadowMap" );
  101. }
  102. void PSSMLightShadowMap::_calcSplitPos(const Frustum& currFrustum)
  103. {
  104. const F32 nearDist = 0.01f; // TODO: Should this be adjustable or different?
  105. const F32 farDist = currFrustum.getFarDist();
  106. for ( U32 i = 1; i < mNumSplits; i++ )
  107. {
  108. F32 step = (F32) i / (F32) mNumSplits;
  109. F32 logSplit = nearDist * mPow(farDist / nearDist, step);
  110. F32 linearSplit = nearDist + (farDist - nearDist) * step;
  111. mSplitDist[i] = mLerp( linearSplit, logSplit, mClampF( mLogWeight, 0.0f, 1.0f ) );
  112. }
  113. mSplitDist[0] = nearDist;
  114. mSplitDist[mNumSplits] = farDist;
  115. }
  116. Box3F PSSMLightShadowMap::_calcClipSpaceAABB(const Frustum& f, const MatrixF& transform, F32 farDist)
  117. {
  118. // Calculate frustum center
  119. Point3F center(0,0,0);
  120. for (U32 i = 0; i < 8; i++)
  121. {
  122. const Point3F& pt = f.getPoints()[i];
  123. center += pt;
  124. }
  125. center /= 8;
  126. // Calculate frustum bounding sphere radius
  127. F32 radius = 0.0f;
  128. for (U32 i = 0; i < 8; i++)
  129. radius = getMax(radius, (f.getPoints()[i] - center).lenSquared());
  130. radius = mFloor( mSqrt(radius) );
  131. // Now build box for sphere
  132. Box3F result;
  133. Point3F radiusBox(radius, radius, radius);
  134. result.minExtents = center - radiusBox;
  135. result.maxExtents = center + radiusBox;
  136. // Transform to light projection space
  137. transform.mul(result);
  138. return result;
  139. }
  140. // This "rounds" the projection matrix to remove subtexel movement during shadow map
  141. // rasterization. This is here to reduce shadow shimmering.
  142. void PSSMLightShadowMap::_roundProjection(const MatrixF& lightMat, const MatrixF& cropMatrix, Point3F &offset, U32 splitNum)
  143. {
  144. // Round to the nearest shadowmap texel, this helps reduce shimmering
  145. MatrixF currentProj = GFX->getProjectionMatrix();
  146. currentProj = cropMatrix * currentProj * lightMat;
  147. // Project origin to screen.
  148. Point4F originShadow4F(0,0,0,1);
  149. currentProj.mul(originShadow4F);
  150. Point2F originShadow(originShadow4F.x / originShadow4F.w, originShadow4F.y / originShadow4F.w);
  151. // Convert to texture space (0..shadowMapSize)
  152. F32 t = mNumSplits < 4 ? mShadowMapTex->getWidth() / mNumSplits : mShadowMapTex->getWidth() / 2;
  153. Point2F texelsToTexture(t / 2.0f, mShadowMapTex->getHeight() / 2.0f);
  154. if (mNumSplits >= 4) texelsToTexture.y *= 0.5f;
  155. originShadow.convolve(texelsToTexture);
  156. // Clamp to texel boundary
  157. Point2F originRounded;
  158. originRounded.x = mFloor(originShadow.x + 0.5f);
  159. originRounded.y = mFloor(originShadow.y + 0.5f);
  160. // Subtract origin to get an offset to recenter everything on texel boundaries
  161. originRounded -= originShadow;
  162. // Convert back to texels (0..1) and offset
  163. originRounded.convolveInverse(texelsToTexture);
  164. offset.x += originRounded.x;
  165. offset.y += originRounded.y;
  166. }
  167. void PSSMLightShadowMap::_render( RenderPassManager* renderPass,
  168. const SceneRenderState *diffuseState )
  169. {
  170. PROFILE_SCOPE(PSSMLightShadowMap_render);
  171. const ShadowMapParams *params = mLight->getExtended<ShadowMapParams>();
  172. const LightMapParams *lmParams = mLight->getExtended<LightMapParams>();
  173. const bool bUseLightmappedGeometry = lmParams ? !lmParams->representedInLightmap || lmParams->includeLightmappedGeometryInShadow : true;
  174. const U32 texSize = getBestTexSize( params->numSplits < 4 ? params->numSplits : 2 );
  175. if ( mShadowMapTex.isNull() ||
  176. mNumSplits != params->numSplits ||
  177. mTexSize != texSize )
  178. {
  179. _setNumSplits( params->numSplits, texSize );
  180. mShadowMapDepth = _getDepthTarget( mShadowMapTex->getWidth(), mShadowMapTex->getHeight() );
  181. }
  182. mLogWeight = params->logWeight;
  183. Frustum fullFrustum( diffuseState->getCameraFrustum() );
  184. fullFrustum.cropNearFar(fullFrustum.getNearDist(), params->shadowDistance);
  185. GFXFrustumSaver frustSaver;
  186. GFXTransformSaver saver;
  187. // Set our render target
  188. GFX->pushActiveRenderTarget();
  189. mTarget->attachTexture( GFXTextureTarget::Color0, mShadowMapTex );
  190. mTarget->attachTexture( GFXTextureTarget::DepthStencil, mShadowMapDepth );
  191. GFX->setActiveRenderTarget( mTarget );
  192. GFX->clear( GFXClearStencil | GFXClearZBuffer | GFXClearTarget, ColorI(255,255,255), 1.0f, 0 );
  193. // Calculate our standard light matrices
  194. MatrixF lightMatrix;
  195. calcLightMatrices( lightMatrix, diffuseState->getCameraFrustum() );
  196. lightMatrix.inverse();
  197. MatrixF lightViewProj = GFX->getProjectionMatrix() * lightMatrix;
  198. // TODO: This is just retrieving the near and far calculated
  199. // in calcLightMatrices... we should make that clear.
  200. F32 pnear, pfar;
  201. GFX->getFrustum( NULL, NULL, NULL, NULL, &pnear, &pfar, NULL );
  202. // Set our view up
  203. GFX->setWorldMatrix(lightMatrix);
  204. MatrixF toLightSpace = lightMatrix; // * invCurrentView;
  205. _calcSplitPos(fullFrustum);
  206. mWorldToLightProj = GFX->getProjectionMatrix() * toLightSpace;
  207. // Apply the PSSM
  208. const F32 savedSmallestVisible = TSShapeInstance::smSmallestVisiblePixelSize;
  209. const F32 savedDetailAdjust = TSShapeInstance::smDetailAdjust;
  210. TSShapeInstance::smDetailAdjust *= smDetailAdjustScale;
  211. TSShapeInstance::smSmallestVisiblePixelSize = smSmallestVisiblePixelSize;
  212. Vector< Vector<PlaneF> > _extraCull;
  213. _calcPlanesCullForShadowCasters( _extraCull, fullFrustum, mLight->getDirection() );
  214. for (U32 i = 0; i < mNumSplits; i++)
  215. {
  216. GFXTransformSaver splitSaver;
  217. // Calculate a sub-frustum
  218. Frustum subFrustum(fullFrustum);
  219. subFrustum.cropNearFar(mSplitDist[i], mSplitDist[i+1]);
  220. // Calculate our AABB in the light's clip space.
  221. Box3F clipAABB = _calcClipSpaceAABB(subFrustum, lightViewProj, fullFrustum.getFarDist());
  222. // Calculate our crop matrix
  223. Point3F scale(2.0f / (clipAABB.maxExtents.x - clipAABB.minExtents.x),
  224. 2.0f / (clipAABB.maxExtents.y - clipAABB.minExtents.y),
  225. 1.0f);
  226. // TODO: This seems to produce less "pops" of the
  227. // shadow resolution as the camera spins around and
  228. // it should produce pixels that are closer to being
  229. // square.
  230. //
  231. // Still is it the right thing to do?
  232. //
  233. scale.y = scale.x = ( getMin( scale.x, scale.y ) );
  234. //scale.x = mFloor(scale.x);
  235. //scale.y = mFloor(scale.y);
  236. Point3F offset( -0.5f * (clipAABB.maxExtents.x + clipAABB.minExtents.x) * scale.x,
  237. -0.5f * (clipAABB.maxExtents.y + clipAABB.minExtents.y) * scale.y,
  238. 0.0f );
  239. MatrixF cropMatrix(true);
  240. cropMatrix.scale(scale);
  241. cropMatrix.setPosition(offset);
  242. _roundProjection(lightMatrix, cropMatrix, offset, i);
  243. cropMatrix.setPosition(offset);
  244. // Save scale/offset for shader computations
  245. mScaleProj[i].set(scale);
  246. mOffsetProj[i].set(offset);
  247. // Adjust the far plane to the max z we got (maybe add a little to deal with split overlap)
  248. bool isOrtho;
  249. {
  250. F32 left, right, bottom, top, nearDist, farDist;
  251. GFX->getFrustum(&left, &right, &bottom, &top, &nearDist, &farDist,&isOrtho);
  252. // BTRTODO: Fix me!
  253. farDist = clipAABB.maxExtents.z;
  254. if (!isOrtho)
  255. GFX->setFrustum(left, right, bottom, top, nearDist, farDist);
  256. else
  257. {
  258. // Calculate a new far plane, add a fudge factor to avoid bringing
  259. // the far plane in too close.
  260. F32 newFar = pfar * clipAABB.maxExtents.z + 1.0f;
  261. mFarPlaneScalePSSM[i] = (pfar - pnear) / (newFar - pnear);
  262. GFX->setOrtho(left, right, bottom, top, pnear, newFar, true);
  263. }
  264. }
  265. // Crop matrix multiply needs to be post-projection.
  266. MatrixF alightProj = GFX->getProjectionMatrix();
  267. alightProj = cropMatrix * alightProj;
  268. // Set our new projection
  269. GFX->setProjectionMatrix(alightProj);
  270. // Render into the quad of the shadow map we are using.
  271. GFX->setViewport(mViewports[i]);
  272. SceneManager* sceneManager = diffuseState->getSceneManager();
  273. // The frustum is currently the full size and has not had
  274. // cropping applied.
  275. //
  276. // We make that adjustment here.
  277. const Frustum& uncroppedFrustum = GFX->getFrustum();
  278. Frustum croppedFrustum;
  279. scale *= 0.5f;
  280. croppedFrustum.set(
  281. isOrtho,
  282. uncroppedFrustum.getNearLeft() / scale.x,
  283. uncroppedFrustum.getNearRight() / scale.x,
  284. uncroppedFrustum.getNearTop() / scale.y,
  285. uncroppedFrustum.getNearBottom() / scale.y,
  286. uncroppedFrustum.getNearDist(),
  287. uncroppedFrustum.getFarDist(),
  288. uncroppedFrustum.getTransform()
  289. );
  290. MatrixF camera = GFX->getWorldMatrix();
  291. camera.inverse();
  292. croppedFrustum.setTransform( camera );
  293. // Setup the scene state and use the diffuse state
  294. // camera position and screen metrics values so that
  295. // lod is done the same as in the diffuse pass.
  296. SceneRenderState shadowRenderState
  297. (
  298. sceneManager,
  299. SPT_Shadow,
  300. SceneCameraState( diffuseState->getViewport(), croppedFrustum,
  301. GFX->getWorldMatrix(), GFX->getProjectionMatrix() ),
  302. renderPass
  303. );
  304. shadowRenderState.getMaterialDelegate().bind( this, &LightShadowMap::getShadowMaterial );
  305. shadowRenderState.renderNonLightmappedMeshes( true );
  306. shadowRenderState.renderLightmappedMeshes( bUseLightmappedGeometry );
  307. shadowRenderState.setDiffuseCameraTransform( diffuseState->getCameraTransform() );
  308. shadowRenderState.setWorldToScreenScale( diffuseState->getWorldToScreenScale() );
  309. PlaneSetF planeSet( _extraCull[i].address(), _extraCull[i].size() );
  310. shadowRenderState.getCullingState().setExtraPlanesCull( planeSet );
  311. U32 objectMask = SHADOW_TYPEMASK;
  312. if ( i == mNumSplits-1 && params->lastSplitTerrainOnly )
  313. objectMask = TerrainObjectType;
  314. sceneManager->renderSceneNoLights( &shadowRenderState, objectMask );
  315. shadowRenderState.getCullingState().clearExtraPlanesCull();
  316. _debugRender( &shadowRenderState );
  317. }
  318. // Restore the original TS lod settings.
  319. TSShapeInstance::smSmallestVisiblePixelSize = savedSmallestVisible;
  320. TSShapeInstance::smDetailAdjust = savedDetailAdjust;
  321. // Release our render target
  322. mTarget->resolve();
  323. GFX->popActiveRenderTarget();
  324. }
  325. void PSSMLightShadowMap::setShaderParameters(GFXShaderConstBuffer* params, LightingShaderConstants* lsc)
  326. {
  327. PROFILE_SCOPE( PSSMLightShadowMap_setShaderParameters );
  328. AssertFatal(mNumSplits > 0 && mNumSplits <= MAX_SPLITS,
  329. avar("PSSMLightShadowMap::_setNumSplits() - Splits must be between 1 and %d!", MAX_SPLITS));
  330. if ( lsc->mTapRotationTexSC->isValid() )
  331. GFX->setTexture( lsc->mTapRotationTexSC->getSamplerRegister(),
  332. SHADOWMGR->getTapRotationTex() );
  333. const ShadowMapParams *p = mLight->getExtended<ShadowMapParams>();
  334. Point4F sx(Point4F::Zero),
  335. sy(Point4F::Zero),
  336. ox(Point4F::Zero),
  337. oy(Point4F::Zero),
  338. aXOff(Point4F::Zero),
  339. aYOff(Point4F::Zero);
  340. for (U32 i = 0; i < mNumSplits; i++)
  341. {
  342. sx[i] = mScaleProj[i].x;
  343. sy[i] = mScaleProj[i].y;
  344. ox[i] = mOffsetProj[i].x;
  345. oy[i] = mOffsetProj[i].y;
  346. }
  347. Point2F shadowMapAtlas;
  348. if (mNumSplits < 4)
  349. {
  350. shadowMapAtlas.x = 1.0f / (F32)mNumSplits;
  351. shadowMapAtlas.y = 1.0f;
  352. // 1xmNumSplits
  353. for (U32 i = 0; i < mNumSplits; i++)
  354. aXOff[i] = (F32)i * shadowMapAtlas.x;
  355. }
  356. else
  357. {
  358. shadowMapAtlas.set(0.5f, 0.5f);
  359. // 2x2
  360. for (U32 i = 0; i < mNumSplits; i++)
  361. {
  362. if (i == 1 || i == 3)
  363. aXOff[i] = 0.5f;
  364. if (i > 1)
  365. aYOff[i] = 0.5f;
  366. }
  367. }
  368. // These values change based on static/dynamic.
  369. params->setSafe(lsc->mScaleXSC, sx);
  370. params->setSafe(lsc->mScaleYSC, sy);
  371. params->setSafe(lsc->mOffsetXSC, ox);
  372. params->setSafe(lsc->mOffsetYSC, oy);
  373. params->setSafe(lsc->mFarPlaneScalePSSM, mFarPlaneScalePSSM);
  374. params->setSafe(lsc->mAtlasXOffsetSC, aXOff);
  375. params->setSafe(lsc->mAtlasYOffsetSC, aYOff);
  376. params->setSafe(lsc->mAtlasScaleSC, shadowMapAtlas);
  377. Point4F lightParams( mLight->getRange().x, p->overDarkFactor.x, 0.0f, 0.0f );
  378. params->setSafe( lsc->mLightParamsSC, lightParams );
  379. Point2F fadeStartLength(p->fadeStartDist, 0.0f);
  380. if (fadeStartLength.x == 0.0f)
  381. {
  382. // By default, lets fade the last half of the last split.
  383. fadeStartLength.x = (mSplitDist[mNumSplits-1] + mSplitDist[mNumSplits]) / 2.0f;
  384. }
  385. fadeStartLength.y = 1.0f / (mSplitDist[mNumSplits] - fadeStartLength.x);
  386. params->setSafe( lsc->mFadeStartLength, fadeStartLength);
  387. params->setSafe( lsc->mOverDarkFactorPSSM, p->overDarkFactor);
  388. // The softness is a factor of the texel size.
  389. params->setSafe( lsc->mShadowSoftnessConst, p->shadowSoftness * ( 1.0f / mTexSize ) );
  390. }
  391. void PSSMLightShadowMap::_calcPlanesCullForShadowCasters(Vector< Vector<PlaneF> > &out, const Frustum &viewFrustum, const Point3F &_ligthDir)
  392. {
  393. #define ENABLE_CULL_ASSERT
  394. PROFILE_SCOPE(PSSMLightShadowMap_render_getCullFrustrum);
  395. Point3F ligthDir = _ligthDir;
  396. PlaneF lightFarPlane, lightNearPlane;
  397. MatrixF lightFarPlaneMat(true);
  398. MatrixF invLightFarPlaneMat(true);
  399. // init data
  400. {
  401. ligthDir.normalize();
  402. Point3F viewDir = viewFrustum.getTransform().getForwardVector();
  403. viewDir.normalize();
  404. const Point3F viewPosition = viewFrustum.getPosition();
  405. const F32 viewDistance = viewFrustum.getBounds().len();
  406. lightNearPlane = PlaneF(viewPosition + (viewDistance * -ligthDir), ligthDir);
  407. const Point3F lightFarPlanePos = viewPosition + (viewDistance * ligthDir);
  408. lightFarPlane = PlaneF(lightFarPlanePos, -ligthDir);
  409. lightFarPlaneMat = MathUtils::createOrientFromDir(-ligthDir);
  410. lightFarPlaneMat.setPosition(lightFarPlanePos);
  411. lightFarPlaneMat.invertTo(&invLightFarPlaneMat);
  412. }
  413. Vector<Point2F> projVertices;
  414. //project all frustum vertices into plane
  415. // all vertices are 2d and local to far plane
  416. projVertices.setSize(8);
  417. for (int i = 0; i < 8; ++i) //
  418. {
  419. const Point3F &point = viewFrustum.getPoints()[i];
  420. #ifdef ENABLE_CULL_ASSERT
  421. AssertFatal( PlaneF::Front == lightNearPlane.whichSide(point), "" );
  422. AssertFatal( PlaneF::Front == lightFarPlane.whichSide(point), "" );
  423. #endif
  424. Point3F localPoint(lightFarPlane.project(point));
  425. invLightFarPlaneMat.mulP(localPoint);
  426. projVertices[i] = Point2F(localPoint.x, localPoint.z);
  427. }
  428. //create hull arround projected proints
  429. Vector<Point2F> hullVerts;
  430. MathUtils::mBuildHull2D(projVertices, hullVerts);
  431. Vector<PlaneF> planes;
  432. planes.push_back(lightNearPlane);
  433. planes.push_back(lightFarPlane);
  434. //build planes
  435. for (int i = 0; i < (hullVerts.size() - 1); ++i)
  436. {
  437. Point2F pos2D = (hullVerts[i] + hullVerts[i + 1]) / 2;
  438. Point3F pos3D(pos2D.x, 0, pos2D.y);
  439. Point3F pos3DA(hullVerts[i].x, 0, hullVerts[i].y);
  440. Point3F pos3DB(hullVerts[i + 1].x, 0, hullVerts[i + 1].y);
  441. // move hull points to 3d space
  442. lightFarPlaneMat.mulP(pos3D);
  443. lightFarPlaneMat.mulP(pos3DA);
  444. lightFarPlaneMat.mulP(pos3DB);
  445. PlaneF plane(pos3D, MathUtils::mTriangleNormal(pos3DB, pos3DA, (pos3DA - ligthDir)));
  446. planes.push_back(plane);
  447. }
  448. //recalculate planes for each splits
  449. for (int split = 0; split < mNumSplits; ++split)
  450. {
  451. Frustum subFrustum(viewFrustum);
  452. subFrustum.cropNearFar(mSplitDist[split], mSplitDist[split + 1]);
  453. subFrustum.setFarDist(getMin(subFrustum.getFarDist()*2.5f, viewFrustum.getFarDist()));
  454. subFrustum.update();
  455. Vector<PlaneF> subPlanes = planes;
  456. for (int planeIdx = 0; planeIdx < subPlanes.size(); ++planeIdx)
  457. {
  458. PlaneF &plane = subPlanes[planeIdx];
  459. F32 minDist = 0;
  460. //calculate near vertex distance
  461. for (int vertexIdx = 0; vertexIdx < 8; ++vertexIdx)
  462. {
  463. Point3F point = subFrustum.getPoints()[vertexIdx];
  464. minDist = getMin(plane.distToPlane(point), minDist);
  465. }
  466. // move plane to near vertex
  467. Point3F newPos = plane.getPosition() + (plane.getNormal() * minDist);
  468. plane = PlaneF(newPos, plane.getNormal());
  469. #ifdef ENABLE_CULL_ASSERT
  470. for(int x = 0; x < 8; ++x)
  471. {
  472. AssertFatal( PlaneF::Back != plane.whichSide( subFrustum.getPoints()[x] ), "");
  473. }
  474. #endif
  475. }
  476. out.push_back(subPlanes);
  477. }
  478. #undef ENABLE_CULL_ASSERT
  479. }