advancedLightBinManager.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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/advanced/advancedLightBinManager.h"
  24. #include "lighting/advanced/advancedLightManager.h"
  25. #include "lighting/advanced/advancedLightBufferConditioner.h"
  26. #include "lighting/shadowMap/shadowMapManager.h"
  27. #include "lighting/shadowMap/shadowMapPass.h"
  28. #include "lighting/shadowMap/lightShadowMap.h"
  29. #include "lighting/common/lightMapParams.h"
  30. #include "renderInstance/renderDeferredMgr.h"
  31. #include "gfx/gfxTransformSaver.h"
  32. #include "scene/sceneManager.h"
  33. #include "scene/sceneRenderState.h"
  34. #include "materials/materialManager.h"
  35. #include "materials/sceneData.h"
  36. #include "core/util/safeDelete.h"
  37. #include "core/util/rgb2luv.h"
  38. #include "gfx/gfxDebugEvent.h"
  39. #include "math/util/matrixSet.h"
  40. #include "console/consoleTypes.h"
  41. #include "gfx/gfxTextureManager.h"
  42. const RenderInstType AdvancedLightBinManager::RIT_LightInfo( "specularLighting" );
  43. const String AdvancedLightBinManager::smBufferName( "specularLighting" );
  44. ShadowFilterMode AdvancedLightBinManager::smShadowFilterMode = ShadowFilterMode_SoftShadowHighQuality;
  45. bool AdvancedLightBinManager::smPSSMDebugRender = false;
  46. bool AdvancedLightBinManager::smUseSSAOMask = false;
  47. ImplementEnumType( ShadowFilterMode,
  48. "The shadow filtering modes for Advanced Lighting shadows.\n"
  49. "@ingroup AdvancedLighting" )
  50. { ShadowFilterMode_None, "None",
  51. "@brief Simple point sampled filtering.\n"
  52. "This is the fastest and lowest quality mode." },
  53. { ShadowFilterMode_SoftShadow, "SoftShadow",
  54. "@brief A variable tap rotated poisson disk soft shadow filter.\n"
  55. "It performs 4 taps to classify the point as in shadow, out of shadow, or along a "
  56. "shadow edge. Samples on the edge get an additional 8 taps to soften them." },
  57. { ShadowFilterMode_SoftShadowHighQuality, "SoftShadowHighQuality",
  58. "@brief A 12 tap rotated poisson disk soft shadow filter.\n"
  59. "It performs all the taps for every point without any early rejection." },
  60. EndImplementEnumType;
  61. // NOTE: The order here matches that of the LightInfo::Type enum.
  62. const String AdvancedLightBinManager::smLightMatNames[] =
  63. {
  64. "AL_PointLightMaterial", // LightInfo::Point
  65. "AL_SpotLightMaterial", // LightInfo::Spot
  66. "AL_VectorLightMaterial", // LightInfo::Vector
  67. "", // LightInfo::Ambient
  68. };
  69. // NOTE: The order here matches that of the LightInfo::Type enum.
  70. const GFXVertexFormat* AdvancedLightBinManager::smLightMatVertex[] =
  71. {
  72. getGFXVertexFormat<AdvancedLightManager::LightVertex>(), // LightInfo::Point
  73. getGFXVertexFormat<AdvancedLightManager::LightVertex>(), // LightInfo::Spot
  74. getGFXVertexFormat<FarFrustumQuadVert>(), // LightInfo::Vector
  75. NULL, // LightInfo::Ambient
  76. };
  77. // NOTE: The order here matches that of the ShadowType enum.
  78. const String AdvancedLightBinManager::smShadowTypeMacro[] =
  79. {
  80. "", // ShadowType_Spot
  81. "", // ShadowType_PSSM,
  82. "SHADOW_PARABOLOID", // ShadowType_Paraboloid,
  83. "SHADOW_DUALPARABOLOID_SINGLE_PASS", // ShadowType_DualParaboloidSinglePass,
  84. "SHADOW_DUALPARABOLOID", // ShadowType_DualParaboloid,
  85. "SHADOW_CUBE", // ShadowType_CubeMap,
  86. };
  87. AdvancedLightBinManager::RenderSignal &AdvancedLightBinManager::getRenderSignal()
  88. {
  89. static RenderSignal theSignal;
  90. return theSignal;
  91. }
  92. IMPLEMENT_CONOBJECT(AdvancedLightBinManager);
  93. ConsoleDocClass( AdvancedLightBinManager,
  94. "@brief Rendering Manager responsible for lighting, shadows, and global variables affecing both.\n\n"
  95. "Should not be exposed to TorqueScript as a game object, meant for internal use only\n\n"
  96. "@ingroup Lighting"
  97. );
  98. AdvancedLightBinManager::AdvancedLightBinManager( AdvancedLightManager *lm /* = NULL */,
  99. ShadowMapManager *sm /* = NULL */,
  100. GFXFormat lightBufferFormat /* = GFXFormatR8G8B8A8 */ )
  101. : RenderTexTargetBinManager( RIT_LightInfo, 1.0f, 1.0f, lightBufferFormat ),
  102. mNumLightsCulled(0),
  103. mLightManager(lm),
  104. mShadowManager(sm),
  105. mConditioner(NULL)
  106. {
  107. // Create an RGB conditioner
  108. mConditioner = new AdvancedLightBufferConditioner( getTargetFormat(),
  109. AdvancedLightBufferConditioner::RGB );
  110. mNamedTarget.setConditioner( mConditioner );
  111. mNamedTarget.registerWithName( smBufferName );
  112. // We want a full-resolution buffer
  113. mTargetSizeType = RenderTexTargetBinManager::WindowSize;
  114. mMRTLightmapsDuringDeferred = true;
  115. Con::NotifyDelegate callback( this, &AdvancedLightBinManager::_deleteLightMaterials );
  116. Con::addVariableNotify( "$pref::Shadows::filterMode", callback );
  117. Con::addVariableNotify( "$AL::PSSMDebugRender", callback );
  118. Con::addVariableNotify( "$AL::UseSSAOMask", callback );
  119. }
  120. AdvancedLightBinManager::~AdvancedLightBinManager()
  121. {
  122. _deleteLightMaterials();
  123. SAFE_DELETE(mConditioner);
  124. Con::NotifyDelegate callback( this, &AdvancedLightBinManager::_deleteLightMaterials );
  125. Con::removeVariableNotify( "$pref::shadows::filterMode", callback );
  126. Con::removeVariableNotify( "$AL::PSSMDebugRender", callback );
  127. Con::removeVariableNotify( "$AL::UseSSAOMask", callback );
  128. }
  129. void AdvancedLightBinManager::consoleInit()
  130. {
  131. Parent::consoleInit();
  132. Con::addVariable( "$pref::shadows::filterMode",
  133. TYPEID<ShadowFilterMode>(), &smShadowFilterMode,
  134. "The filter mode to use for shadows.\n"
  135. "@ingroup AdvancedLighting\n" );
  136. Con::addVariable( "$AL::UseSSAOMask", TypeBool, &smUseSSAOMask,
  137. "Used by the SSAO PostEffect to toggle the sampling of ssaomask "
  138. "texture by the light shaders.\n"
  139. "@ingroup AdvancedLighting\n" );
  140. Con::addVariable( "$AL::PSSMDebugRender", TypeBool, &smPSSMDebugRender,
  141. "Enables debug rendering of the PSSM shadows.\n"
  142. "@ingroup AdvancedLighting\n" );
  143. }
  144. bool AdvancedLightBinManager::setTargetSize(const Point2I &newTargetSize)
  145. {
  146. bool ret = Parent::setTargetSize( newTargetSize );
  147. // We require the viewport to match the default.
  148. mNamedTarget.setViewport( GFX->getViewport() );
  149. return ret;
  150. }
  151. bool AdvancedLightBinManager::_updateTargets()
  152. {
  153. PROFILE_SCOPE(AdvancedLightBinManager_updateTargets);
  154. bool ret = Parent::_updateTargets();
  155. mDiffuseLightingTarget = NamedTexTarget::find("diffuseLighting");
  156. if (mDiffuseLightingTarget.isValid())
  157. {
  158. mDiffuseLightingTex = mDiffuseLightingTarget->getTexture();
  159. for (U32 i = 0; i < mTargetChainLength; i++)
  160. mTargetChain[i]->attachTexture(GFXTextureTarget::Color1, mDiffuseLightingTex);
  161. }
  162. GFX->finalizeReset();
  163. return ret;
  164. }
  165. void AdvancedLightBinManager::addLight( LightInfo *light )
  166. {
  167. // Get the light type.
  168. const LightInfo::Type lightType = light->getType();
  169. AssertFatal( lightType == LightInfo::Point ||
  170. lightType == LightInfo::Spot, "Bogus light type." );
  171. // Find a shadow map for this light, if it has one
  172. ShadowMapParams *lsp = light->getExtended<ShadowMapParams>();
  173. LightShadowMap *lsm = lsp->getShadowMap();
  174. LightShadowMap *dynamicShadowMap = lsp->getShadowMap(true);
  175. // Get the right shadow type.
  176. ShadowType shadowType = ShadowType_None;
  177. if ( light->getCastShadows() &&
  178. lsm && lsm->hasShadowTex() &&
  179. !ShadowMapPass::smDisableShadows )
  180. shadowType = lsm->getShadowType();
  181. // Add the entry
  182. LightBinEntry lEntry;
  183. lEntry.lightInfo = light;
  184. lEntry.shadowMap = lsm;
  185. lEntry.dynamicShadowMap = dynamicShadowMap;
  186. lEntry.lightMaterial = _getLightMaterial( lightType, shadowType, lsp->hasCookieTex() );
  187. if( lightType == LightInfo::Spot )
  188. lEntry.vertBuffer = mLightManager->getConeMesh( lEntry.numPrims, lEntry.primBuffer );
  189. else
  190. lEntry.vertBuffer = mLightManager->getSphereMesh( lEntry.numPrims, lEntry.primBuffer );
  191. // If it's a point light, push front, spot
  192. // light, push back. This helps batches.
  193. Vector<LightBinEntry> &curBin = mLightBin;
  194. if ( light->getType() == LightInfo::Point )
  195. curBin.push_front( lEntry );
  196. else
  197. curBin.push_back( lEntry );
  198. }
  199. void AdvancedLightBinManager::clearAllLights()
  200. {
  201. Con::setIntVariable("lightMetrics::activeLights", mLightBin.size());
  202. Con::setIntVariable("lightMetrics::culledLights", mNumLightsCulled);
  203. mLightBin.clear();
  204. mNumLightsCulled = 0;
  205. }
  206. void AdvancedLightBinManager::render( SceneRenderState *state )
  207. {
  208. PROFILE_SCOPE( AdvancedLightManager_Render );
  209. // Take a look at the SceneRenderState and see if we should skip drawing the pre-pass
  210. if( state->disableAdvancedLightingBins() )
  211. return;
  212. // Automagically save & restore our viewport and transforms.
  213. GFXTransformSaver saver;
  214. if( !mLightManager )
  215. return;
  216. // Get the sunlight. If there's no sun, and no lights in the bins, no draw
  217. LightInfo *sunLight = mLightManager->getSpecialLight( LightManager::slSunLightType, false );
  218. GFXDEBUGEVENT_SCOPE( AdvancedLightBinManager_Render, ColorI::RED );
  219. // Tell the superclass we're about to render
  220. if ( !_onPreRender( state ) )
  221. return;
  222. GFX->clear(GFXClearTarget, ColorI(0, 0, 0, 0), 1.0f, 0);
  223. // Restore transforms
  224. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  225. matrixSet.restoreSceneViewProjection();
  226. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  227. // Set up the SG Data
  228. SceneData sgData;
  229. sgData.init( state );
  230. // There are cases where shadow rendering is disabled.
  231. const bool disableShadows = /*state->isReflectPass() || */ShadowMapPass::smDisableShadows;
  232. // Pick the right material for rendering the sunlight... we only
  233. // cast shadows when its enabled and we're not in a reflection.
  234. LightMaterialInfo *vectorMatInfo;
  235. if ( sunLight &&
  236. sunLight->getCastShadows() &&
  237. !disableShadows &&
  238. sunLight->getExtended<ShadowMapParams>() )
  239. vectorMatInfo = _getLightMaterial( LightInfo::Vector, ShadowType_PSSM, false );
  240. else
  241. vectorMatInfo = _getLightMaterial( LightInfo::Vector, ShadowType_None, false );
  242. // Initialize and set the per-frame parameters after getting
  243. // the vector light material as we use lazy creation.
  244. _setupPerFrameParameters( state );
  245. // Draw sunlight/ambient
  246. if ( sunLight && vectorMatInfo )
  247. {
  248. GFXDEBUGEVENT_SCOPE( AdvancedLightBinManager_Render_Sunlight, ColorI::RED );
  249. // Set up SG data
  250. setupSGData( sgData, state, sunLight );
  251. vectorMatInfo->setLightParameters( sunLight, state, worldToCameraXfm );
  252. // Set light holds the active shadow map.
  253. mShadowManager->setLightShadowMapForLight( sunLight );
  254. // Set geometry
  255. GFX->setVertexBuffer( mFarFrustumQuadVerts );
  256. GFX->setPrimitiveBuffer( NULL );
  257. vectorMatInfo->matInstance->mSpecialLight = true;
  258. // Render the material passes
  259. while( vectorMatInfo->matInstance->setupPass( state, sgData ) )
  260. {
  261. vectorMatInfo->matInstance->setSceneInfo( state, sgData );
  262. vectorMatInfo->matInstance->setTransforms( matrixSet, state );
  263. GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
  264. }
  265. }
  266. // Blend the lights in the bin to the light buffer
  267. for( LightBinIterator itr = mLightBin.begin(); itr != mLightBin.end(); itr++ )
  268. {
  269. LightBinEntry& curEntry = *itr;
  270. LightInfo *curLightInfo = curEntry.lightInfo;
  271. LightMaterialInfo *curLightMat = curEntry.lightMaterial;
  272. const U32 numPrims = curEntry.numPrims;
  273. const U32 numVerts = curEntry.vertBuffer->mNumVerts;
  274. ShadowMapParams *lsp = curLightInfo->getExtended<ShadowMapParams>();
  275. // Skip lights which won't affect the scene.
  276. if ( !curLightMat || curLightInfo->getBrightness() <= 0.001f )
  277. continue;
  278. GFXDEBUGEVENT_SCOPE( AdvancedLightBinManager_Render_Light, ColorI::RED );
  279. setupSGData( sgData, state, curLightInfo );
  280. curLightMat->setLightParameters( curLightInfo, state, worldToCameraXfm );
  281. mShadowManager->setLightShadowMap( curEntry.shadowMap );
  282. mShadowManager->setLightDynamicShadowMap( curEntry.dynamicShadowMap );
  283. // Set geometry
  284. GFX->setVertexBuffer( curEntry.vertBuffer );
  285. GFX->setPrimitiveBuffer( curEntry.primBuffer );
  286. lsp->getOcclusionQuery()->begin();
  287. curLightMat->matInstance->mSpecialLight = false;
  288. // Render the material passes
  289. while( curLightMat->matInstance->setupPass( state, sgData ) )
  290. {
  291. // Set transforms
  292. matrixSet.setWorld(*sgData.objTrans);
  293. curLightMat->matInstance->setTransforms(matrixSet, state);
  294. curLightMat->matInstance->setSceneInfo(state, sgData);
  295. if(curEntry.primBuffer)
  296. GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, numVerts, 0, numPrims);
  297. else
  298. GFX->drawPrimitive(GFXTriangleList, 0, numPrims);
  299. }
  300. lsp->getOcclusionQuery()->end();
  301. }
  302. // Set NULL for active shadow map (so nothing gets confused)
  303. mShadowManager->setLightShadowMap(NULL);
  304. mShadowManager->setLightDynamicShadowMap(NULL);
  305. GFX->setVertexBuffer( NULL );
  306. GFX->setPrimitiveBuffer( NULL );
  307. // Fire off a signal to let others know that light-bin rendering is ending now
  308. getRenderSignal().trigger(state, this);
  309. // Finish up the rendering
  310. _onPostRender();
  311. }
  312. AdvancedLightBinManager::LightMaterialInfo* AdvancedLightBinManager::_getLightMaterial( LightInfo::Type lightType,
  313. ShadowType shadowType,
  314. bool useCookieTex )
  315. {
  316. PROFILE_SCOPE( AdvancedLightBinManager_GetLightMaterial );
  317. // Build the key.
  318. const LightMatKey key( lightType, shadowType, useCookieTex );
  319. // See if we've already built this one.
  320. LightMatTable::Iterator iter = mLightMaterials.find( key );
  321. if ( iter != mLightMaterials.end() )
  322. return iter->value;
  323. // If we got here we need to build a material for
  324. // this light+shadow combination.
  325. LightMaterialInfo *info = NULL;
  326. // First get the light material name and make sure
  327. // this light has a material in the first place.
  328. const String &lightMatName = smLightMatNames[ lightType ];
  329. if ( lightMatName.isNotEmpty() )
  330. {
  331. Vector<GFXShaderMacro> shadowMacros;
  332. // Setup the shadow type macros for this material.
  333. if ( shadowType == ShadowType_None )
  334. shadowMacros.push_back( GFXShaderMacro( "NO_SHADOW" ) );
  335. else
  336. {
  337. shadowMacros.push_back( GFXShaderMacro( smShadowTypeMacro[ shadowType ] ) );
  338. // Do we need to do shadow filtering?
  339. if ( smShadowFilterMode != ShadowFilterMode_None )
  340. {
  341. shadowMacros.push_back( GFXShaderMacro( "SOFTSHADOW" ) );
  342. const F32 SM = GFX->getPixelShaderVersion();
  343. if ( SM >= 3.0f && smShadowFilterMode == ShadowFilterMode_SoftShadowHighQuality )
  344. shadowMacros.push_back( GFXShaderMacro( "SOFTSHADOW_HIGH_QUALITY" ) );
  345. }
  346. }
  347. if ( useCookieTex )
  348. shadowMacros.push_back( GFXShaderMacro( "USE_COOKIE_TEX" ) );
  349. // Its safe to add the PSSM debug macro to all the materials.
  350. if ( smPSSMDebugRender )
  351. shadowMacros.push_back( GFXShaderMacro( "PSSM_DEBUG_RENDER" ) );
  352. // If its a vector light see if we can enable SSAO.
  353. if ( lightType == LightInfo::Vector && smUseSSAOMask )
  354. shadowMacros.push_back( GFXShaderMacro( "USE_SSAO_MASK" ) );
  355. // Now create the material info object.
  356. info = new LightMaterialInfo( lightMatName, smLightMatVertex[ lightType ], shadowMacros );
  357. }
  358. // Push this into the map and return it.
  359. mLightMaterials.insertUnique( key, info );
  360. return info;
  361. }
  362. void AdvancedLightBinManager::_deleteLightMaterials()
  363. {
  364. LightMatTable::Iterator iter = mLightMaterials.begin();
  365. for ( ; iter != mLightMaterials.end(); iter++ )
  366. delete iter->value;
  367. mLightMaterials.clear();
  368. }
  369. void AdvancedLightBinManager::_setupPerFrameParameters( const SceneRenderState *state )
  370. {
  371. PROFILE_SCOPE( AdvancedLightBinManager_SetupPerFrameParameters );
  372. const Frustum &frustum = state->getCameraFrustum();
  373. MatrixF invCam( frustum.getTransform() );
  374. invCam.inverse();
  375. const Point3F *wsFrustumPoints = frustum.getPoints();
  376. const Point3F& cameraPos = frustum.getPosition();
  377. // Perform a camera offset. We need to manually perform this offset on the sun (or vector) light's
  378. // polygon, which is at the far plane.
  379. Point3F cameraOffsetPos = cameraPos;
  380. // Now build the quad for drawing full-screen vector light
  381. // passes.... this is a volatile VB and updates every frame.
  382. FarFrustumQuadVert verts[4];
  383. {
  384. verts[0].point.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraPos);
  385. invCam.mulP(wsFrustumPoints[Frustum::FarTopLeft], &verts[0].normal);
  386. verts[0].texCoord.set(-1.0, 1.0);
  387. verts[0].tangent.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraOffsetPos);
  388. verts[1].point.set(wsFrustumPoints[Frustum::FarTopRight] - cameraPos);
  389. invCam.mulP(wsFrustumPoints[Frustum::FarTopRight], &verts[1].normal);
  390. verts[1].texCoord.set(1.0, 1.0);
  391. verts[1].tangent.set(wsFrustumPoints[Frustum::FarTopRight] - cameraOffsetPos);
  392. verts[2].point.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraPos);
  393. invCam.mulP(wsFrustumPoints[Frustum::FarBottomLeft], &verts[2].normal);
  394. verts[2].texCoord.set(-1.0, -1.0);
  395. verts[2].tangent.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos);
  396. verts[3].point.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraPos);
  397. invCam.mulP(wsFrustumPoints[Frustum::FarBottomRight], &verts[3].normal);
  398. verts[3].texCoord.set(1.0, -1.0);
  399. verts[3].tangent.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraOffsetPos);
  400. }
  401. mFarFrustumQuadVerts.set( GFX, 4 );
  402. dMemcpy( mFarFrustumQuadVerts.lock(), verts, sizeof( verts ) );
  403. mFarFrustumQuadVerts.unlock();
  404. PlaneF farPlane(wsFrustumPoints[Frustum::FarBottomLeft], wsFrustumPoints[Frustum::FarTopLeft], wsFrustumPoints[Frustum::FarTopRight]);
  405. PlaneF vsFarPlane(verts[0].normal, verts[1].normal, verts[2].normal);
  406. // Parameters calculated, assign them to the materials
  407. LightMatTable::Iterator iter = mLightMaterials.begin();
  408. for ( ; iter != mLightMaterials.end(); iter++ )
  409. {
  410. if ( iter->value )
  411. iter->value->setViewParameters( frustum.getNearDist(),
  412. frustum.getFarDist(),
  413. frustum.getPosition(),
  414. farPlane,
  415. vsFarPlane);
  416. }
  417. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  418. //matrixSet.restoreSceneViewProjection();
  419. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  420. MatrixF inverseViewMatrix = worldToCameraXfm;
  421. //inverseViewMatrix.fullInverse();
  422. //inverseViewMatrix.transpose();
  423. //MatrixF inverseViewMatrix = MatrixF::Identity;
  424. }
  425. void AdvancedLightBinManager::setupSGData( SceneData &data, const SceneRenderState* state, LightInfo *light )
  426. {
  427. PROFILE_SCOPE( AdvancedLightBinManager_setupSGData );
  428. data.lights[0] = light;
  429. data.ambientLightColor = state->getAmbientLightColor();
  430. data.objTrans = &MatrixF::Identity;
  431. if ( light )
  432. {
  433. if ( light->getType() == LightInfo::Point )
  434. {
  435. // The point light volume gets some flat spots along
  436. // the perimiter mostly visible in the constant and
  437. // quadradic falloff modes.
  438. //
  439. // To account for them slightly increase the scale
  440. // instead of greatly increasing the polycount.
  441. mLightMat = light->getTransform();
  442. mLightMat.scale( light->getRange() * 1.01f );
  443. data.objTrans = &mLightMat;
  444. }
  445. else if ( light->getType() == LightInfo::Spot )
  446. {
  447. mLightMat = light->getTransform();
  448. // Rotate it to face down the -y axis.
  449. MatrixF scaleRotateTranslate( EulerF( M_PI_F / -2.0f, 0.0f, 0.0f ) );
  450. // Calculate the radius based on the range and angle.
  451. F32 range = light->getRange().x;
  452. F32 radius = range * mSin( mDegToRad( light->getOuterConeAngle() ) * 0.5f );
  453. // NOTE: This fudge makes the cone a little bigger
  454. // to remove the facet egde of the cone geometry.
  455. radius *= 1.1f;
  456. // Use the scale to distort the cone to
  457. // match our radius and range.
  458. scaleRotateTranslate.scale( Point3F( radius, radius, range ) );
  459. // Apply the transform and set the position.
  460. mLightMat *= scaleRotateTranslate;
  461. mLightMat.setPosition( light->getPosition() );
  462. data.objTrans = &mLightMat;
  463. }
  464. }
  465. }
  466. void AdvancedLightBinManager::MRTLightmapsDuringDeferred( bool val )
  467. {
  468. // Do not enable if the GFX device can't do MRT's
  469. if ( GFX->getNumRenderTargets() < 2 )
  470. val = false;
  471. if ( mMRTLightmapsDuringDeferred != val )
  472. {
  473. mMRTLightmapsDuringDeferred = val;
  474. // Reload materials to cause a feature recalculation on deferred materials
  475. if(mLightManager->isActive())
  476. MATMGR->flushAndReInitInstances();
  477. RenderDeferredMgr *deferred;
  478. if ( Sim::findObject( "AL_DeferredBin", deferred ) && deferred->getTargetTexture( 0 ) )
  479. deferred->updateTargets();
  480. }
  481. }
  482. AdvancedLightBinManager::LightMaterialInfo::LightMaterialInfo( const String &matName,
  483. const GFXVertexFormat *vertexFormat,
  484. const Vector<GFXShaderMacro> &macros )
  485. : matInstance(NULL),
  486. zNearFarInvNearFar(NULL),
  487. farPlane(NULL),
  488. vsFarPlane(NULL),
  489. negFarPlaneDotEye(NULL),
  490. lightPosition(NULL),
  491. lightDirection(NULL),
  492. lightColor(NULL),
  493. lightAttenuation(NULL),
  494. lightRange(NULL),
  495. lightAmbient(NULL),
  496. lightTrilight(NULL),
  497. lightSpotParams(NULL)
  498. {
  499. Material *mat = MATMGR->getMaterialDefinitionByName( matName );
  500. if ( !mat )
  501. return;
  502. matInstance = new LightMatInstance( *mat );
  503. for ( U32 i=0; i < macros.size(); i++ )
  504. matInstance->addShaderMacro( macros[i].name, macros[i].value );
  505. matInstance->init( MATMGR->getDefaultFeatures(), vertexFormat );
  506. lightDirection = matInstance->getMaterialParameterHandle("$lightDirection");
  507. lightAmbient = matInstance->getMaterialParameterHandle("$lightAmbient");
  508. lightTrilight = matInstance->getMaterialParameterHandle("$lightTrilight");
  509. lightSpotParams = matInstance->getMaterialParameterHandle("$lightSpotParams");
  510. lightAttenuation = matInstance->getMaterialParameterHandle("$lightAttenuation");
  511. lightRange = matInstance->getMaterialParameterHandle("$lightRange");
  512. lightPosition = matInstance->getMaterialParameterHandle("$lightPosition");
  513. farPlane = matInstance->getMaterialParameterHandle("$farPlane");
  514. vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane");
  515. negFarPlaneDotEye = matInstance->getMaterialParameterHandle("$negFarPlaneDotEye");
  516. zNearFarInvNearFar = matInstance->getMaterialParameterHandle("$zNearFarInvNearFar");
  517. lightColor = matInstance->getMaterialParameterHandle("$lightColor");
  518. lightBrightness = matInstance->getMaterialParameterHandle("$lightBrightness");
  519. }
  520. AdvancedLightBinManager::LightMaterialInfo::~LightMaterialInfo()
  521. {
  522. SAFE_DELETE(matInstance);
  523. }
  524. void AdvancedLightBinManager::LightMaterialInfo::setViewParameters( const F32 _zNear,
  525. const F32 _zFar,
  526. const Point3F &_eyePos,
  527. const PlaneF &_farPlane,
  528. const PlaneF &_vsFarPlane)
  529. {
  530. MaterialParameters *matParams = matInstance->getMaterialParameters();
  531. matParams->setSafe( farPlane, *((const Point4F *)&_farPlane) );
  532. matParams->setSafe( vsFarPlane, *((const Point4F *)&_vsFarPlane) );
  533. if ( negFarPlaneDotEye->isValid() )
  534. {
  535. // -dot( farPlane, eyePos )
  536. const F32 negFarPlaneDotEyeVal = -( mDot( *((const Point3F *)&_farPlane), _eyePos ) + _farPlane.d );
  537. matParams->set( negFarPlaneDotEye, negFarPlaneDotEyeVal );
  538. }
  539. matParams->setSafe( zNearFarInvNearFar, Point4F( _zNear, _zFar, 1.0f / _zNear, 1.0f / _zFar ) );
  540. }
  541. void AdvancedLightBinManager::LightMaterialInfo::setLightParameters( const LightInfo *lightInfo, const SceneRenderState* renderState, const MatrixF &worldViewOnly )
  542. {
  543. MaterialParameters *matParams = matInstance->getMaterialParameters();
  544. // Set color in the right format, set alpha to the luminance value for the color.
  545. LinearColorF col = lightInfo->getColor();
  546. // TODO: The specularity control of the light
  547. // is being scaled by the overall lumiance.
  548. //
  549. // Not sure if this may be the source of our
  550. // bad specularity results maybe?
  551. //
  552. const Point3F colorToLumiance( 0.3576f, 0.7152f, 0.1192f );
  553. F32 lumiance = mDot(*((const Point3F *)&lightInfo->getColor()), colorToLumiance );
  554. col.alpha *= lumiance;
  555. matParams->setSafe( lightColor, col );
  556. matParams->setSafe( lightBrightness, lightInfo->getBrightness() );
  557. switch( lightInfo->getType() )
  558. {
  559. case LightInfo::Vector:
  560. {
  561. VectorF lightDir = lightInfo->getDirection();
  562. worldViewOnly.mulV(lightDir);
  563. lightDir.normalize();
  564. matParams->setSafe( lightDirection, lightDir );
  565. // Set small number for alpha since it represents existing specular in
  566. // the vector light. This prevents a divide by zero.
  567. LinearColorF ambientColor = renderState->getAmbientLightColor();
  568. ambientColor.alpha = 0.00001f;
  569. matParams->setSafe( lightAmbient, ambientColor );
  570. // If no alt color is specified, set it to the average of
  571. // the ambient and main color to avoid artifacts.
  572. //
  573. // TODO: Trilight disabled until we properly implement it
  574. // in the light info!
  575. //
  576. //LinearColorF lightAlt = lightInfo->getAltColor();
  577. LinearColorF lightAlt( LinearColorF::BLACK ); // = lightInfo->getAltColor();
  578. if ( lightAlt.red == 0.0f && lightAlt.green == 0.0f && lightAlt.blue == 0.0f )
  579. lightAlt = (lightInfo->getColor() + renderState->getAmbientLightColor()) / 2.0f;
  580. LinearColorF trilightColor = lightAlt;
  581. matParams->setSafe(lightTrilight, trilightColor);
  582. }
  583. break;
  584. case LightInfo::Spot:
  585. {
  586. const F32 outerCone = lightInfo->getOuterConeAngle();
  587. const F32 innerCone = getMin( lightInfo->getInnerConeAngle(), outerCone );
  588. const F32 outerCos = mCos( mDegToRad( outerCone / 2.0f ) );
  589. const F32 innerCos = mCos( mDegToRad( innerCone / 2.0f ) );
  590. Point4F spotParams( outerCos,
  591. innerCos - outerCos,
  592. mCos( mDegToRad( outerCone ) ),
  593. 0.0f );
  594. matParams->setSafe( lightSpotParams, spotParams );
  595. VectorF lightDir = lightInfo->getDirection();
  596. worldViewOnly.mulV(lightDir);
  597. lightDir.normalize();
  598. matParams->setSafe( lightDirection, lightDir );
  599. }
  600. // Fall through
  601. case LightInfo::Point:
  602. {
  603. const F32 radius = lightInfo->getRange().x;
  604. matParams->setSafe( lightRange, radius );
  605. Point3F lightPos;
  606. worldViewOnly.mulP(lightInfo->getPosition(), &lightPos);
  607. matParams->setSafe( lightPosition, lightPos );
  608. // Get the attenuation falloff ratio and normalize it.
  609. Point3F attenRatio = lightInfo->getExtended<ShadowMapParams>()->attenuationRatio;
  610. F32 total = attenRatio.x + attenRatio.y + attenRatio.z;
  611. if ( total > 0.0f )
  612. attenRatio /= total;
  613. Point2F attenParams( ( 1.0f / radius ) * attenRatio.y,
  614. ( 1.0f / ( radius * radius ) ) * attenRatio.z );
  615. matParams->setSafe( lightAttenuation, attenParams );
  616. break;
  617. }
  618. default:
  619. AssertFatal( false, "Bad light type!" );
  620. break;
  621. }
  622. }
  623. bool LightMatInstance::setupPass( SceneRenderState *state, const SceneData &sgData )
  624. {
  625. // Go no further if the material failed to initialize properly.
  626. if ( !mProcessedMaterial ||
  627. mProcessedMaterial->getNumPasses() == 0 )
  628. return false;
  629. U32 reflectStatus = Base;
  630. if (state->isReflectPass())
  631. reflectStatus = Reflecting;
  632. // Fetch the lightmap params
  633. const LightMapParams *lmParams = sgData.lights[0]->getExtended<LightMapParams>();
  634. // If no Lightmap params, let parent handle it
  635. if(lmParams == NULL)
  636. return Parent::setupPass(state, sgData);
  637. // Defaults
  638. bool bRetVal = true;
  639. // What render pass is this...
  640. if(mCurPass == -1)
  641. {
  642. // First pass, reset this flag
  643. mInternalPass = false;
  644. // Pass call to parent
  645. bRetVal = Parent::setupPass(state, sgData);
  646. }
  647. else
  648. {
  649. // If this light is represented in a lightmap, it has already done it's
  650. // job for non-lightmapped geometry. Now render the lightmapped geometry
  651. // pass (specular + shadow-darkening)
  652. if(!mInternalPass && lmParams->representedInLightmap)
  653. mInternalPass = true;
  654. else
  655. return Parent::setupPass(state, sgData);
  656. }
  657. // Set up the shader constants we need to...
  658. if(mLightMapParamsSC->isValid())
  659. {
  660. // If this is an internal pass, special case the parameters
  661. if(mInternalPass)
  662. {
  663. AssertFatal( lmParams->shadowDarkenColor.alpha == -1.0f, "Assumption failed, check unpack code!" );
  664. getMaterialParameters()->set( mLightMapParamsSC, lmParams->shadowDarkenColor );
  665. }
  666. else
  667. getMaterialParameters()->set( mLightMapParamsSC, LinearColorF::WHITE );
  668. }
  669. // Now override stateblock with our own
  670. if(!mInternalPass)
  671. {
  672. // If this is not an internal pass, and this light is represented in lightmaps
  673. // than only effect non-lightmapped geometry for this pass
  674. if (lmParams->representedInLightmap)
  675. {
  676. GFX->setStateBlock(mLitState[StaticLightNonLMGeometry][reflectStatus]);
  677. }
  678. else // This is a normal, dynamic light.
  679. {
  680. if (mSpecialLight)
  681. GFX->setStateBlock(mLitState[SunLight][reflectStatus]);
  682. else
  683. GFX->setStateBlock(mLitState[DynamicLight][reflectStatus]);
  684. }
  685. }
  686. else // Internal pass, this is the add-specular/multiply-darken-color pass
  687. GFX->setStateBlock(mLitState[StaticLightLMGeometry][reflectStatus]);
  688. return bRetVal;
  689. }
  690. bool LightMatInstance::init( const FeatureSet &features, const GFXVertexFormat *vertexFormat )
  691. {
  692. bool success = Parent::init(features, vertexFormat);
  693. // If the initialization failed don't continue.
  694. if ( !success || !mProcessedMaterial || mProcessedMaterial->getNumPasses() == 0 )
  695. return false;
  696. mLightMapParamsSC = getMaterialParameterHandle("$lightMapParams");
  697. // Grab the state block for the first render pass (since this mat instance
  698. // inserts a pass after the first pass)
  699. AssertFatal(mProcessedMaterial->getNumPasses() > 0, "No passes created! Ohnoes");
  700. const RenderPassData *rpd = mProcessedMaterial->getPass(0);
  701. AssertFatal(rpd, "No render pass data!");
  702. AssertFatal(rpd->mRenderStates[0], "No render state 0!");
  703. // Get state block desc for normal (not wireframe, not translucent, not glow, etc)
  704. // render state
  705. GFXStateBlockDesc litState = rpd->mRenderStates[0]->getDesc();
  706. // Create state blocks for each of the 3 possible combos in setupPass
  707. //DynamicLight State: This will effect lightmapped and non-lightmapped geometry
  708. // in the same way.
  709. litState.separateAlphaBlendDefined = true;
  710. litState.separateAlphaBlendEnable = false;
  711. litState.stencilMask = RenderDeferredMgr::OpaqueDynamicLitMask | RenderDeferredMgr::OpaqueStaticLitMask;
  712. litState.setCullMode(GFXCullCW);
  713. mLitState[DynamicLight][Base] = GFX->createStateBlock(litState);
  714. litState.setCullMode(GFXCullCCW);
  715. mLitState[DynamicLight][Reflecting] = GFX->createStateBlock(litState);
  716. litState.separateAlphaBlendDefined = true;
  717. litState.separateAlphaBlendEnable = false;
  718. litState.stencilMask = RenderDeferredMgr::OpaqueDynamicLitMask | RenderDeferredMgr::OpaqueStaticLitMask;
  719. litState.setCullMode(GFXCullCCW);
  720. mLitState[SunLight][Base] = GFX->createStateBlock(litState);
  721. litState.setCullMode(GFXCullCCW);
  722. mLitState[SunLight][Reflecting] = GFX->createStateBlock(litState);
  723. // StaticLightNonLMGeometry State: This will treat non-lightmapped geometry
  724. // in the usual way, but will not effect lightmapped geometry.
  725. litState.separateAlphaBlendDefined = true;
  726. litState.separateAlphaBlendEnable = false;
  727. litState.stencilMask = RenderDeferredMgr::OpaqueDynamicLitMask;
  728. litState.setCullMode(GFXCullCW);
  729. mLitState[StaticLightNonLMGeometry][Base] = GFX->createStateBlock(litState);
  730. litState.setCullMode(GFXCullCCW);
  731. mLitState[StaticLightNonLMGeometry][Reflecting] = GFX->createStateBlock(litState);
  732. // StaticLightLMGeometry State: This will add specular information (alpha) but
  733. // multiply-darken color information.
  734. litState.blendDest = GFXBlendSrcColor;
  735. litState.blendSrc = GFXBlendZero;
  736. litState.stencilMask = RenderDeferredMgr::OpaqueStaticLitMask;
  737. litState.separateAlphaBlendDefined = true;
  738. litState.separateAlphaBlendEnable = true;
  739. litState.separateAlphaBlendSrc = GFXBlendOne;
  740. litState.separateAlphaBlendDest = GFXBlendOne;
  741. litState.separateAlphaBlendOp = GFXBlendOpAdd;
  742. litState.setCullMode(GFXCullCW);
  743. mLitState[StaticLightLMGeometry][Base] = GFX->createStateBlock(litState);
  744. litState.setCullMode(GFXCullCCW);
  745. mLitState[StaticLightLMGeometry][Reflecting] = GFX->createStateBlock(litState);
  746. return true;
  747. }