advancedLightBinManager.cpp 34 KB

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