lightShadowMap.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739
  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/lightShadowMap.h"
  24. #include "lighting/shadowMap/shadowMapManager.h"
  25. #include "lighting/shadowMap/shadowMatHook.h"
  26. #include "gfx/gfxDevice.h"
  27. #include "gfx/gfxTextureManager.h"
  28. #include "gfx/gfxOcclusionQuery.h"
  29. #include "gfx/gfxCardProfile.h"
  30. #include "gfx/sim/debugDraw.h"
  31. #include "materials/materialDefinition.h"
  32. #include "materials/baseMatInstance.h"
  33. #include "scene/sceneManager.h"
  34. #include "scene/sceneRenderState.h"
  35. #include "scene/zones/sceneZoneSpace.h"
  36. #include "lighting/lightManager.h"
  37. #include "math/mathUtils.h"
  38. #include "shaderGen/shaderGenVars.h"
  39. #include "core/util/safeDelete.h"
  40. #include "core/stream/bitStream.h"
  41. #include "math/mathIO.h"
  42. #include "materials/shaderData.h"
  43. #include "core/module.h"
  44. // Used for creation in ShadowMapParams::getOrCreateShadowMap()
  45. #include "lighting/shadowMap/singleLightShadowMap.h"
  46. #include "lighting/shadowMap/pssmLightShadowMap.h"
  47. #include "lighting/shadowMap/cubeLightShadowMap.h"
  48. #include "lighting/shadowMap/dualParaboloidLightShadowMap.h"
  49. // Remove this when the shader constants are reworked better
  50. #include "lighting/advanced/advancedLightManager.h"
  51. #include "lighting/advanced/advancedLightBinManager.h"
  52. // TODO: Some cards (Justin's GeForce 7x series) barf on the integer format causing
  53. // filtering artifacts. These can (sometimes) be resolved by switching the format
  54. // to FP16 instead of Int16.
  55. const GFXFormat LightShadowMap::ShadowMapFormat = GFXFormatR32F; // GFXFormatR8G8B8A8;
  56. bool LightShadowMap::smDebugRenderFrustums;
  57. F32 LightShadowMap::smShadowTexScalar = 1.0f;
  58. Vector<LightShadowMap*> LightShadowMap::smUsedShadowMaps;
  59. Vector<LightShadowMap*> LightShadowMap::smShadowMaps;
  60. GFX_ImplementTextureProfile( ShadowMapProfile,
  61. GFXTextureProfile::DiffuseMap,
  62. GFXTextureProfile::PreserveSize |
  63. GFXTextureProfile::RenderTarget |
  64. GFXTextureProfile::Pooled,
  65. GFXTextureProfile::NONE );
  66. GFX_ImplementTextureProfile( ShadowMapZProfile,
  67. GFXTextureProfile::DiffuseMap,
  68. GFXTextureProfile::PreserveSize |
  69. GFXTextureProfile::NoMipmap |
  70. GFXTextureProfile::ZTarget |
  71. GFXTextureProfile::Pooled,
  72. GFXTextureProfile::NONE );
  73. LightShadowMap::LightShadowMap( LightInfo *light )
  74. : mWorldToLightProj( true ),
  75. mTexSize( 0 ),
  76. mLight( light ),
  77. mLastShader( NULL ),
  78. mIsViewDependent( false ),
  79. mLastCull( 0 ),
  80. mLastScreenSize( 0.0f ),
  81. mLastPriority( 0.0f )
  82. {
  83. GFXTextureManager::addEventDelegate( this, &LightShadowMap::_onTextureEvent );
  84. mTarget = GFX->allocRenderToTextureTarget();
  85. smShadowMaps.push_back( this );
  86. }
  87. LightShadowMap::~LightShadowMap()
  88. {
  89. mTarget = NULL;
  90. releaseTextures();
  91. smShadowMaps.remove( this );
  92. smUsedShadowMaps.remove( this );
  93. GFXTextureManager::removeEventDelegate( this, &LightShadowMap::_onTextureEvent );
  94. }
  95. void LightShadowMap::releaseAllTextures()
  96. {
  97. PROFILE_SCOPE( LightShadowMap_ReleaseAllTextures );
  98. for ( U32 i=0; i < smShadowMaps.size(); i++ )
  99. smShadowMaps[i]->releaseTextures();
  100. }
  101. U32 LightShadowMap::releaseUnusedTextures()
  102. {
  103. PROFILE_SCOPE( LightShadowMap_ReleaseUnusedTextures );
  104. const U32 currTime = Sim::getCurrentTime();
  105. const U32 purgeTime = 1000;
  106. for ( U32 i=0; i < smUsedShadowMaps.size(); )
  107. {
  108. LightShadowMap *lsm = smUsedShadowMaps[i];
  109. // If the shadow has not been culled in a while then
  110. // release its textures for other shadows to use.
  111. if ( currTime > ( lsm->mLastCull + purgeTime ) )
  112. {
  113. // Internally this will remove the map from the used
  114. // list, so don't increment the loop.
  115. lsm->releaseTextures();
  116. continue;
  117. }
  118. i++;
  119. }
  120. return smUsedShadowMaps.size();
  121. }
  122. void LightShadowMap::_onTextureEvent( GFXTexCallbackCode code )
  123. {
  124. if ( code == GFXZombify )
  125. releaseTextures();
  126. // We don't initialize here as we want the textures
  127. // to be reallocated when the shadow becomes visible.
  128. }
  129. void LightShadowMap::calcLightMatrices( MatrixF &outLightMatrix, const Frustum &viewFrustum )
  130. {
  131. // Create light matrix, set projection
  132. switch ( mLight->getType() )
  133. {
  134. case LightInfo::Vector :
  135. {
  136. const ShadowMapParams *p = mLight->getExtended<ShadowMapParams>();
  137. // Calculate the bonding box of the shadowed area
  138. // we're interested in... this is the shadow box
  139. // transformed by the frustum transform.
  140. Box3F viewBB( -p->shadowDistance, -p->shadowDistance, -p->shadowDistance,
  141. p->shadowDistance, p->shadowDistance, p->shadowDistance );
  142. viewFrustum.getTransform().mul( viewBB );
  143. // Calculate a light "projection" matrix.
  144. MatrixF lightMatrix = MathUtils::createOrientFromDir(mLight->getDirection());
  145. outLightMatrix = lightMatrix;
  146. static MatrixF rotMat(EulerF( (M_PI_F / 2.0f), 0.0f, 0.0f));
  147. lightMatrix.mul( rotMat );
  148. // This is the box in lightspace
  149. Box3F lightViewBB(viewBB);
  150. lightMatrix.mul(lightViewBB);
  151. // Now, let's position our light based on the lightViewBB
  152. Point3F newLightPos(viewBB.getCenter());
  153. F32 sceneDepth = lightViewBB.maxExtents.z - lightViewBB.minExtents.z;
  154. newLightPos += mLight->getDirection() * ((-sceneDepth / 2.0f)-1.0f); // -1 for the nearplane
  155. outLightMatrix.setPosition(newLightPos);
  156. // Update light info
  157. mLight->setRange( sceneDepth );
  158. mLight->setPosition( newLightPos );
  159. // Set our ortho projection
  160. F32 width = (lightViewBB.maxExtents.x - lightViewBB.minExtents.x) / 2.0f;
  161. F32 height = (lightViewBB.maxExtents.y - lightViewBB.minExtents.y) / 2.0f;
  162. width = getMax(width, height);
  163. GFX->setOrtho(-width, width, -width, width, 1.0f, sceneDepth, true);
  164. // TODO: Width * 2... really isn't that pixels being used as
  165. // meters? Is a real physical metric of scene depth better?
  166. //SceneManager::setVisibleDistance(width * 2.0f);
  167. #if 0
  168. DebugDrawer::get()->drawFrustum(viewFrustum, LinearColorF(1.0f, 0.0f, 0.0f));
  169. DebugDrawer::get()->drawBox(viewBB.minExtents, viewBB.maxExtents, LinearColorF(0.0f, 1.0f, 0.0f));
  170. DebugDrawer::get()->drawBox(lightViewBB.minExtents, lightViewBB.maxExtents, LinearColorF(0.0f, 0.0f, 1.0f));
  171. DebugDrawer::get()->drawBox(newLightPos - Point3F(1,1,1), newLightPos + Point3F(1,1,1), LinearColorF(1,1,0));
  172. DebugDrawer::get()->drawLine(newLightPos, newLightPos + mLight.mDirection*3.0f, LinearColorF(0,1,1));
  173. Point3F a(newLightPos);
  174. Point3F b(newLightPos);
  175. Point3F offset(width, height,0.0f);
  176. a -= offset;
  177. b += offset;
  178. DebugDrawer::get()->drawBox(a, b, LinearColorF(0.5f, 0.5f, 0.5f));
  179. #endif
  180. }
  181. break;
  182. case LightInfo::Spot :
  183. {
  184. outLightMatrix = mLight->getTransform();
  185. F32 fov = mDegToRad( mLight->getOuterConeAngle() );
  186. F32 farDist = mLight->getRange().x;
  187. F32 nearDist = farDist * 0.01f;
  188. F32 left, right, top, bottom;
  189. MathUtils::makeFrustum( &left, &right, &top, &bottom, fov, 1.0f, nearDist );
  190. GFX->setFrustum( left, right, bottom, top, nearDist, farDist );
  191. }
  192. break;
  193. default:
  194. AssertFatal(false, "Unsupported light type!");
  195. }
  196. }
  197. void LightShadowMap::releaseTextures()
  198. {
  199. mShadowMapTex = NULL;
  200. mDebugTarget.setTexture( NULL );
  201. smUsedShadowMaps.remove( this );
  202. }
  203. void LightShadowMap::setDebugTarget( const String &name )
  204. {
  205. mDebugTarget.registerWithName( name );
  206. mDebugTarget.setTexture( mShadowMapTex );
  207. }
  208. GFXTextureObject* LightShadowMap::_getDepthTarget( U32 width, U32 height )
  209. {
  210. // Get a depth texture target from the pooled profile
  211. // which is returned as a temporary.
  212. GFXTexHandle depthTex( width, height, GFXFormatD24S8, &ShadowMapZProfile,
  213. "LightShadowMap::_getDepthTarget()" );
  214. return depthTex;
  215. }
  216. bool LightShadowMap::setTextureStage( U32 currTexFlag, LightingShaderConstants* lsc )
  217. {
  218. if ( currTexFlag == Material::DynamicLight )
  219. {
  220. S32 reg = lsc->mShadowMapSC->getSamplerRegister();
  221. if ( reg != -1 )
  222. GFX->setTexture( reg, mShadowMapTex);
  223. return true;
  224. } else if ( currTexFlag == Material::DynamicLightMask )
  225. {
  226. S32 reg = lsc->mCookieMapSC->getSamplerRegister();
  227. if ( reg != -1 )
  228. {
  229. ShadowMapParams *p = mLight->getExtended<ShadowMapParams>();
  230. if ( lsc->mCookieMapSC->getType() == GFXSCT_SamplerCube )
  231. GFX->setCubeTexture( reg, p->getCookieCubeTex() );
  232. else
  233. GFX->setTexture( reg, p->getCookieTex() );
  234. }
  235. return true;
  236. }
  237. return false;
  238. }
  239. void LightShadowMap::render(RenderPassManager* renderPass, const SceneRenderState *diffuseState)
  240. {
  241. mDebugTarget.setTexture( NULL );
  242. _render( renderPass, diffuseState );
  243. mDebugTarget.setTexture( mShadowMapTex );
  244. // Add it to the used list unless we're been updated.
  245. //AssertFatal( !smUsedShadowMaps.contains( this ), "LightShadowMap::render - Used shadow map inserted twice!" );
  246. if(!smUsedShadowMaps.contains(this))
  247. smUsedShadowMaps.push_back( this );
  248. }
  249. BaseMatInstance* LightShadowMap::getShadowMaterial( BaseMatInstance *inMat ) const
  250. {
  251. // See if we have an existing material hook.
  252. ShadowMaterialHook *hook = static_cast<ShadowMaterialHook*>( inMat->getHook( ShadowMaterialHook::Type ) );
  253. if ( !hook )
  254. {
  255. // Create a hook and initialize it using the incoming material.
  256. hook = new ShadowMaterialHook;
  257. hook->init( inMat );
  258. inMat->addHook( hook );
  259. }
  260. return hook->getShadowMat( getShadowType() );
  261. }
  262. U32 LightShadowMap::getBestTexSize( U32 scale ) const
  263. {
  264. const ShadowMapParams *params = mLight->getExtended<ShadowMapParams>();
  265. // The view dependent shadows don't scale by screen size.
  266. U32 texSize;
  267. if ( isViewDependent() )
  268. texSize = params->texSize;
  269. else
  270. texSize = params->texSize * getMin( 1.0f, mLastScreenSize );
  271. // Apply the shadow texture scale and make
  272. // sure this is a power of 2.
  273. texSize = getNextPow2( texSize * smShadowTexScalar );
  274. // Get the max texture size this card supports and
  275. // scale it down... ensuring the final texSize can
  276. // be scaled up that many times and not go over
  277. // the card maximum.
  278. U32 maxTexSize = GFX->getCardProfiler()->queryProfile( "maxTextureSize", 2048 );
  279. if ( scale > 1 )
  280. maxTexSize >>= ( scale - 1 );
  281. // Never let the shadow texture get smaller than 16x16 as
  282. // it just makes the pool bigger and the fillrate savings
  283. // are less and leass as we get smaller.
  284. texSize = mClamp( texSize, (U32)16, maxTexSize );
  285. // Return it.
  286. return texSize;
  287. }
  288. void LightShadowMap::updatePriority( const SceneRenderState *state, U32 currTimeMs )
  289. {
  290. PROFILE_SCOPE( LightShadowMap_updatePriority );
  291. mLastCull = currTimeMs;
  292. if ( isViewDependent() )
  293. {
  294. mLastScreenSize = 1.0f;
  295. mLastPriority = F32_MAX;
  296. return;
  297. }
  298. const Point3F &camPt = state->getCameraPosition();
  299. F32 range = mLight->getRange().x;
  300. F32 dist;
  301. if ( mLight->getType() == LightInfo::Spot )
  302. {
  303. // We treat the cone as a cylinder to get the
  304. // approximate projection distance.
  305. Point3F endPt = mLight->getPosition() + ( mLight->getDirection() * range );
  306. Point3F nearPt = MathUtils::mClosestPointOnSegment( mLight->getPosition(), endPt, camPt );
  307. dist = ( camPt - nearPt ).len();
  308. F32 radius = range * mSin( mDegToRad( mLight->getOuterConeAngle() * 0.5f ) );
  309. dist -= radius;
  310. }
  311. else
  312. dist = SphereF( mLight->getPosition(), range ).distanceTo( camPt );
  313. // Get the approximate screen size of the light.
  314. mLastScreenSize = state->projectRadius( dist, range );
  315. mLastScreenSize /= state->getViewport().extent.y;
  316. // Update the priority.
  317. mLastPriority = mPow( mLastScreenSize * 50.0f, 2.0f );
  318. mLastPriority *= mLight->getPriority();
  319. }
  320. S32 QSORT_CALLBACK LightShadowMap::cmpPriority( LightShadowMap *const *lsm1, LightShadowMap *const *lsm2 )
  321. {
  322. F32 diff = (*lsm1)->getLastPriority() - (*lsm2)->getLastPriority();
  323. return diff > 0.0f ? -1 : ( diff < 0.0f ? 1 : 0 );
  324. }
  325. void LightShadowMap::_debugRender( SceneRenderState* shadowRenderState )
  326. {
  327. #ifdef TORQUE_DEBUG
  328. // Skip if light does not have debug rendering enabled.
  329. if( !getLightInfo()->isDebugRenderingEnabled() )
  330. return;
  331. DebugDrawer* drawer = DebugDrawer::get();
  332. if( !drawer )
  333. return;
  334. if( smDebugRenderFrustums )
  335. shadowRenderState->getCullingState().debugRenderCullingVolumes();
  336. #endif
  337. }
  338. LightingShaderConstants::LightingShaderConstants()
  339. : mInit( false ),
  340. mShader( NULL ),
  341. mLightParamsSC(NULL),
  342. mLightSpotParamsSC(NULL),
  343. mLightPositionSC(NULL),
  344. mLightDiffuseSC(NULL),
  345. mLightAmbientSC(NULL),
  346. mLightConfigDataSC(NULL),
  347. mLightSpotDirSC(NULL),
  348. mHasVectorLightSC(NULL),
  349. mVectorLightDirectionSC(NULL),
  350. mVectorLightColorSC(NULL),
  351. mVectorLightBrightnessSC(NULL),
  352. mShadowMapSC(NULL),
  353. mShadowMapSizeSC(NULL),
  354. mCookieMapSC(NULL),
  355. mRandomDirsConst(NULL),
  356. mShadowSoftnessConst(NULL),
  357. mAtlasXOffsetSC(NULL),
  358. mAtlasYOffsetSC(NULL),
  359. mAtlasScaleSC(NULL),
  360. mFadeStartLength(NULL),
  361. mOverDarkFactorPSSM(NULL),
  362. mTapRotationTexSC(NULL),
  363. mWorldToLightProjSC(NULL),
  364. mViewToLightProjSC(NULL),
  365. mScaleXSC(NULL),
  366. mScaleYSC(NULL),
  367. mOffsetXSC(NULL),
  368. mOffsetYSC(NULL),
  369. mFarPlaneScalePSSM(NULL)
  370. {
  371. }
  372. LightingShaderConstants::~LightingShaderConstants()
  373. {
  374. if (mShader.isValid())
  375. {
  376. mShader->getReloadSignal().remove( this, &LightingShaderConstants::_onShaderReload );
  377. mShader = NULL;
  378. }
  379. }
  380. void LightingShaderConstants::init(GFXShader* shader)
  381. {
  382. if (mShader.getPointer() != shader)
  383. {
  384. if (mShader.isValid())
  385. mShader->getReloadSignal().remove( this, &LightingShaderConstants::_onShaderReload );
  386. mShader = shader;
  387. mShader->getReloadSignal().notify( this, &LightingShaderConstants::_onShaderReload );
  388. }
  389. mLightParamsSC = shader->getShaderConstHandle("$lightParams");
  390. // NOTE: These are the shader constants used for doing lighting
  391. // during the forward pass. Do not confuse these for the deferred
  392. // lighting constants which are used from AdvancedLightBinManager.
  393. mLightPositionSC = shader->getShaderConstHandle( ShaderGenVars::lightPosition );
  394. mLightDiffuseSC = shader->getShaderConstHandle( ShaderGenVars::lightDiffuse );
  395. mLightAmbientSC = shader->getShaderConstHandle( ShaderGenVars::lightAmbient );
  396. mLightConfigDataSC = shader->getShaderConstHandle( ShaderGenVars::lightConfigData);
  397. mLightSpotDirSC = shader->getShaderConstHandle( ShaderGenVars::lightSpotDir );
  398. mLightSpotParamsSC = shader->getShaderConstHandle(ShaderGenVars::lightSpotParams);
  399. mHasVectorLightSC = shader->getShaderConstHandle(ShaderGenVars::hasVectorLight);
  400. mVectorLightDirectionSC = shader->getShaderConstHandle(ShaderGenVars::vectorLightDirection);
  401. mVectorLightColorSC = shader->getShaderConstHandle(ShaderGenVars::vectorLightColor);
  402. mVectorLightBrightnessSC = shader->getShaderConstHandle(ShaderGenVars::vectorLightBrightness);
  403. mShadowMapSC = shader->getShaderConstHandle("$shadowMap");
  404. mShadowMapSizeSC = shader->getShaderConstHandle("$shadowMapSize");
  405. mCookieMapSC = shader->getShaderConstHandle("$cookieMap");
  406. mShadowSoftnessConst = shader->getShaderConstHandle("$shadowSoftness");
  407. mAtlasXOffsetSC = shader->getShaderConstHandle("$atlasXOffset");
  408. mAtlasYOffsetSC = shader->getShaderConstHandle("$atlasYOffset");
  409. mAtlasScaleSC = shader->getShaderConstHandle("$atlasScale");
  410. mFadeStartLength = shader->getShaderConstHandle("$fadeStartLength");
  411. mOverDarkFactorPSSM = shader->getShaderConstHandle("$overDarkPSSM");
  412. mTapRotationTexSC = shader->getShaderConstHandle( "$gTapRotationTex" );
  413. mWorldToLightProjSC = shader->getShaderConstHandle("$worldToLightProj");
  414. mViewToLightProjSC = shader->getShaderConstHandle("$viewToLightProj");
  415. mScaleXSC = shader->getShaderConstHandle("$scaleX");
  416. mScaleYSC = shader->getShaderConstHandle("$scaleY");
  417. mOffsetXSC = shader->getShaderConstHandle("$offsetX");
  418. mOffsetYSC = shader->getShaderConstHandle("$offsetY");
  419. mFarPlaneScalePSSM = shader->getShaderConstHandle("$farPlaneScalePSSM");
  420. mInit = true;
  421. }
  422. void LightingShaderConstants::_onShaderReload()
  423. {
  424. if (mShader.isValid())
  425. init( mShader );
  426. }
  427. MODULE_BEGIN( ShadowMapParams )
  428. MODULE_INIT_BEFORE( LightMapParams )
  429. MODULE_INIT
  430. {
  431. ShadowMapParams::Type = "ShadowMapParams" ;
  432. }
  433. MODULE_END;
  434. LightInfoExType ShadowMapParams::Type( "" );
  435. ShadowMapParams::ShadowMapParams( LightInfo *light )
  436. : mShadowMap( NULL ),
  437. mLight( light )
  438. {
  439. attenuationRatio.set( 0.0f, 1.0f, 1.0f );
  440. shadowType = ShadowType_Spot;
  441. overDarkFactor.set(2000.0f, 1000.0f, 500.0f, 100.0f);
  442. numSplits = 4;
  443. logWeight = 0.91f;
  444. texSize = 1024;
  445. shadowDistance = 100.0f;
  446. shadowSoftness = 0.2f;
  447. fadeStartDist = 75.0f;
  448. lastSplitTerrainOnly = false;
  449. mQuery = GFX->createOcclusionQuery();
  450. cookie = StringTable->EmptyString();;
  451. _validate();
  452. }
  453. ShadowMapParams::~ShadowMapParams()
  454. {
  455. SAFE_DELETE( mQuery );
  456. SAFE_DELETE( mShadowMap );
  457. }
  458. void ShadowMapParams::_validate()
  459. {
  460. switch ( mLight->getType() )
  461. {
  462. case LightInfo::Spot:
  463. shadowType = ShadowType_Spot;
  464. break;
  465. case LightInfo::Vector:
  466. shadowType = ShadowType_PSSM;
  467. break;
  468. case LightInfo::Point:
  469. if ( shadowType < ShadowType_Paraboloid )
  470. shadowType = ShadowType_DualParaboloidSinglePass;
  471. break;
  472. default:
  473. break;
  474. }
  475. // The texture sizes for shadows should always
  476. // be power of 2 in size.
  477. texSize = getNextPow2( texSize );
  478. // The maximum shadow texture size setting we're
  479. // gonna allow... this doesn't use your hardware
  480. // settings as you may be on a lower end system
  481. // than your target machine.
  482. //
  483. // We apply the hardware specific limits during
  484. // shadow rendering.
  485. //
  486. U32 maxTexSize = 8192;
  487. if ( mLight->getType() == LightInfo::Vector )
  488. {
  489. numSplits = mClamp( numSplits, 1, 4 );
  490. // Adjust the shadow texture size for the PSSM
  491. // based on the split count to keep the total
  492. // shadow texture size within 4096.
  493. if ( numSplits == 2 || numSplits == 4 )
  494. maxTexSize = 8192;
  495. if ( numSplits == 3 )
  496. maxTexSize = 4096;
  497. }
  498. else
  499. numSplits = 1;
  500. // Keep it in a valid range... less than 32 is dumb.
  501. texSize = mClamp( texSize, 32, maxTexSize );
  502. shadowDistance = mClamp(shadowDistance, 25.0f, 10000.0f);
  503. }
  504. LightShadowMap* ShadowMapParams::getOrCreateShadowMap()
  505. {
  506. if (mShadowMap)
  507. return mShadowMap;
  508. if ( !mLight->getCastShadows() )
  509. return NULL;
  510. LightShadowMap* newShadowMap = NULL;
  511. switch ( mLight->getType() )
  512. {
  513. case LightInfo::Spot:
  514. newShadowMap = new SingleLightShadowMap( mLight );
  515. break;
  516. case LightInfo::Vector:
  517. newShadowMap = new PSSMLightShadowMap( mLight );
  518. break;
  519. case LightInfo::Point:
  520. if ( shadowType == ShadowType_CubeMap )
  521. newShadowMap = new CubeLightShadowMap( mLight );
  522. else if ( shadowType == ShadowType_Paraboloid )
  523. newShadowMap = new ParaboloidLightShadowMap( mLight );
  524. else
  525. newShadowMap = new DualParaboloidLightShadowMap( mLight );
  526. break;
  527. default:
  528. break;
  529. }
  530. mShadowMap = newShadowMap;
  531. return mShadowMap;
  532. }
  533. GFXTextureObject* ShadowMapParams::getCookieTex()
  534. {
  535. if ( hasCookieTex() &&
  536. ( mCookieTex.isNull() ||
  537. cookie != StringTable->insert(mCookieTex->getPath().c_str()) ) )
  538. {
  539. mCookieTex.set( cookie,
  540. &GFXStaticTextureSRGBProfile,
  541. "ShadowMapParams::getCookieTex()" );
  542. }
  543. else if (!hasCookieTex())
  544. mCookieTex = NULL;
  545. return mCookieTex.getPointer();
  546. }
  547. GFXCubemap* ShadowMapParams::getCookieCubeTex()
  548. {
  549. if ( hasCookieTex() &&
  550. ( mCookieCubeTex.isNull() ||
  551. cookie != StringTable->insert(mCookieTex->getPath().c_str())) )
  552. {
  553. mCookieCubeTex.set( cookie );
  554. }
  555. else if (!hasCookieTex())
  556. mCookieCubeTex = NULL;
  557. return mCookieCubeTex.getPointer();
  558. }
  559. void ShadowMapParams::set( const LightInfoEx *ex )
  560. {
  561. // TODO: Do we even need this?
  562. }
  563. void ShadowMapParams::packUpdate( BitStream *stream ) const
  564. {
  565. // HACK: We need to work out proper parameter
  566. // validation when any field changes on the light.
  567. ((ShadowMapParams*)this)->_validate();
  568. stream->writeInt( shadowType, 8 );
  569. mathWrite( *stream, attenuationRatio );
  570. stream->write( texSize );
  571. stream->writeString( cookie );
  572. stream->write( numSplits );
  573. stream->write( logWeight );
  574. mathWrite(*stream, overDarkFactor);
  575. stream->write( fadeStartDist );
  576. stream->writeFlag( lastSplitTerrainOnly );
  577. stream->write( shadowDistance );
  578. stream->write( shadowSoftness );
  579. }
  580. void ShadowMapParams::unpackUpdate( BitStream *stream )
  581. {
  582. ShadowType newType = (ShadowType)stream->readInt( 8 );
  583. if ( shadowType != newType )
  584. {
  585. // If the shadow type changes delete the shadow
  586. // map so it can be reallocated on the next render.
  587. shadowType = newType;
  588. SAFE_DELETE( mShadowMap );
  589. }
  590. mathRead( *stream, &attenuationRatio );
  591. stream->read( &texSize );
  592. cookie = stream->readSTString();
  593. stream->read( &numSplits );
  594. stream->read( &logWeight );
  595. mathRead(*stream, &overDarkFactor);
  596. stream->read( &fadeStartDist );
  597. lastSplitTerrainOnly = stream->readFlag();
  598. stream->read( &shadowDistance );
  599. stream->read( &shadowSoftness );
  600. }