advancedLightBinManager.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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/renderPrePassMgr.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. mMRTLightmapsDuringPrePass = 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. // Get the right shadow type.
  160. ShadowType shadowType = ShadowType_None;
  161. if ( light->getCastShadows() &&
  162. lsm && lsm->hasShadowTex() &&
  163. !ShadowMapPass::smDisableShadows )
  164. shadowType = lsm->getShadowType();
  165. // Add the entry
  166. LightBinEntry lEntry;
  167. lEntry.lightInfo = light;
  168. lEntry.shadowMap = lsm;
  169. lEntry.lightMaterial = _getLightMaterial( lightType, shadowType, lsp->hasCookieTex() );
  170. if( lightType == LightInfo::Spot )
  171. lEntry.vertBuffer = mLightManager->getConeMesh( lEntry.numPrims, lEntry.primBuffer );
  172. else
  173. lEntry.vertBuffer = mLightManager->getSphereMesh( lEntry.numPrims, lEntry.primBuffer );
  174. // If it's a point light, push front, spot
  175. // light, push back. This helps batches.
  176. Vector<LightBinEntry> &curBin = mLightBin;
  177. if ( light->getType() == LightInfo::Point )
  178. curBin.push_front( lEntry );
  179. else
  180. curBin.push_back( lEntry );
  181. }
  182. void AdvancedLightBinManager::clearAllLights()
  183. {
  184. Con::setIntVariable("lightMetrics::activeLights", mLightBin.size());
  185. Con::setIntVariable("lightMetrics::culledLights", mNumLightsCulled);
  186. mLightBin.clear();
  187. mNumLightsCulled = 0;
  188. }
  189. void AdvancedLightBinManager::render( SceneRenderState *state )
  190. {
  191. PROFILE_SCOPE( AdvancedLightManager_Render );
  192. // Take a look at the SceneRenderState and see if we should skip drawing the pre-pass
  193. if( state->disableAdvancedLightingBins() )
  194. return;
  195. // Automagically save & restore our viewport and transforms.
  196. GFXTransformSaver saver;
  197. if( !mLightManager )
  198. return;
  199. // Get the sunlight. If there's no sun, and no lights in the bins, no draw
  200. LightInfo *sunLight = mLightManager->getSpecialLight( LightManager::slSunLightType, false );
  201. GFXDEBUGEVENT_SCOPE( AdvancedLightBinManager_Render, ColorI::RED );
  202. // Tell the superclass we're about to render
  203. if ( !_onPreRender( state ) )
  204. return;
  205. // Clear as long as there isn't MRT population of light buffer with lightmap data
  206. if ( !MRTLightmapsDuringPrePass() )
  207. GFX->clear(GFXClearTarget, ColorI(0, 0, 0, 0), 1.0f, 0);
  208. // Restore transforms
  209. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  210. matrixSet.restoreSceneViewProjection();
  211. const MatrixF &worldToCameraXfm = matrixSet.getWorldToCamera();
  212. // Set up the SG Data
  213. SceneData sgData;
  214. sgData.init( state );
  215. // There are cases where shadow rendering is disabled.
  216. const bool disableShadows = state->isReflectPass() || ShadowMapPass::smDisableShadows;
  217. // Pick the right material for rendering the sunlight... we only
  218. // cast shadows when its enabled and we're not in a reflection.
  219. LightMaterialInfo *vectorMatInfo;
  220. if ( sunLight &&
  221. sunLight->getCastShadows() &&
  222. !disableShadows &&
  223. sunLight->getExtended<ShadowMapParams>() )
  224. vectorMatInfo = _getLightMaterial( LightInfo::Vector, ShadowType_PSSM, false );
  225. else
  226. vectorMatInfo = _getLightMaterial( LightInfo::Vector, ShadowType_None, false );
  227. // Initialize and set the per-frame parameters after getting
  228. // the vector light material as we use lazy creation.
  229. _setupPerFrameParameters( state );
  230. // Draw sunlight/ambient
  231. if ( sunLight && vectorMatInfo )
  232. {
  233. GFXDEBUGEVENT_SCOPE( AdvancedLightBinManager_Render_Sunlight, ColorI::RED );
  234. // Set up SG data
  235. setupSGData( sgData, state, sunLight );
  236. vectorMatInfo->setLightParameters( sunLight, state, worldToCameraXfm );
  237. // Set light holds the active shadow map.
  238. mShadowManager->setLightShadowMapForLight( sunLight );
  239. // Set geometry
  240. GFX->setVertexBuffer( mFarFrustumQuadVerts );
  241. GFX->setPrimitiveBuffer( NULL );
  242. // Render the material passes
  243. while( vectorMatInfo->matInstance->setupPass( state, sgData ) )
  244. {
  245. vectorMatInfo->matInstance->setSceneInfo( state, sgData );
  246. vectorMatInfo->matInstance->setTransforms( matrixSet, state );
  247. GFX->drawPrimitive( GFXTriangleFan, 0, 2 );
  248. }
  249. }
  250. // Blend the lights in the bin to the light buffer
  251. for( LightBinIterator itr = mLightBin.begin(); itr != mLightBin.end(); itr++ )
  252. {
  253. LightBinEntry& curEntry = *itr;
  254. LightInfo *curLightInfo = curEntry.lightInfo;
  255. LightMaterialInfo *curLightMat = curEntry.lightMaterial;
  256. const U32 numPrims = curEntry.numPrims;
  257. const U32 numVerts = curEntry.vertBuffer->mNumVerts;
  258. // Skip lights which won't affect the scene.
  259. if ( !curLightMat || curLightInfo->getBrightness() <= 0.001f )
  260. continue;
  261. GFXDEBUGEVENT_SCOPE( AdvancedLightBinManager_Render_Light, ColorI::RED );
  262. setupSGData( sgData, state, curLightInfo );
  263. curLightMat->setLightParameters( curLightInfo, state, worldToCameraXfm );
  264. mShadowManager->setLightShadowMap( curEntry.shadowMap );
  265. // Let the shadow know we're about to render from it.
  266. if ( curEntry.shadowMap )
  267. curEntry.shadowMap->preLightRender();
  268. // Set geometry
  269. GFX->setVertexBuffer( curEntry.vertBuffer );
  270. GFX->setPrimitiveBuffer( curEntry.primBuffer );
  271. // Render the material passes
  272. while( curLightMat->matInstance->setupPass( state, sgData ) )
  273. {
  274. // Set transforms
  275. matrixSet.setWorld(*sgData.objTrans);
  276. curLightMat->matInstance->setTransforms(matrixSet, state);
  277. curLightMat->matInstance->setSceneInfo(state, sgData);
  278. if(curEntry.primBuffer)
  279. GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, numVerts, 0, numPrims);
  280. else
  281. GFX->drawPrimitive(GFXTriangleList, 0, numPrims);
  282. }
  283. // Tell it we're done rendering.
  284. if ( curEntry.shadowMap )
  285. curEntry.shadowMap->postLightRender();
  286. }
  287. // Set NULL for active shadow map (so nothing gets confused)
  288. mShadowManager->setLightShadowMap(NULL);
  289. GFX->setVertexBuffer( NULL );
  290. GFX->setPrimitiveBuffer( NULL );
  291. // Fire off a signal to let others know that light-bin rendering is ending now
  292. getRenderSignal().trigger(state, this);
  293. // Finish up the rendering
  294. _onPostRender();
  295. }
  296. AdvancedLightBinManager::LightMaterialInfo* AdvancedLightBinManager::_getLightMaterial( LightInfo::Type lightType,
  297. ShadowType shadowType,
  298. bool useCookieTex )
  299. {
  300. PROFILE_SCOPE( AdvancedLightBinManager_GetLightMaterial );
  301. // Build the key.
  302. const LightMatKey key( lightType, shadowType, useCookieTex );
  303. // See if we've already built this one.
  304. LightMatTable::Iterator iter = mLightMaterials.find( key );
  305. if ( iter != mLightMaterials.end() )
  306. return iter->value;
  307. // If we got here we need to build a material for
  308. // this light+shadow combination.
  309. LightMaterialInfo *info = NULL;
  310. // First get the light material name and make sure
  311. // this light has a material in the first place.
  312. const String &lightMatName = smLightMatNames[ lightType ];
  313. if ( lightMatName.isNotEmpty() )
  314. {
  315. Vector<GFXShaderMacro> shadowMacros;
  316. // Setup the shadow type macros for this material.
  317. if ( shadowType == ShadowType_None )
  318. shadowMacros.push_back( GFXShaderMacro( "NO_SHADOW" ) );
  319. else
  320. {
  321. shadowMacros.push_back( GFXShaderMacro( smShadowTypeMacro[ shadowType ] ) );
  322. // Do we need to do shadow filtering?
  323. if ( smShadowFilterMode != ShadowFilterMode_None )
  324. {
  325. shadowMacros.push_back( GFXShaderMacro( "SOFTSHADOW" ) );
  326. const F32 SM = GFX->getPixelShaderVersion();
  327. if ( SM >= 3.0f && smShadowFilterMode == ShadowFilterMode_SoftShadowHighQuality )
  328. shadowMacros.push_back( GFXShaderMacro( "SOFTSHADOW_HIGH_QUALITY" ) );
  329. }
  330. }
  331. if ( useCookieTex )
  332. shadowMacros.push_back( GFXShaderMacro( "USE_COOKIE_TEX" ) );
  333. // Its safe to add the PSSM debug macro to all the materials.
  334. if ( smPSSMDebugRender )
  335. shadowMacros.push_back( GFXShaderMacro( "PSSM_DEBUG_RENDER" ) );
  336. // If its a vector light see if we can enable SSAO.
  337. if ( lightType == LightInfo::Vector && smUseSSAOMask )
  338. shadowMacros.push_back( GFXShaderMacro( "USE_SSAO_MASK" ) );
  339. // Now create the material info object.
  340. info = new LightMaterialInfo( lightMatName, smLightMatVertex[ lightType ], shadowMacros );
  341. }
  342. // Push this into the map and return it.
  343. mLightMaterials.insertUnique( key, info );
  344. return info;
  345. }
  346. void AdvancedLightBinManager::_deleteLightMaterials()
  347. {
  348. LightMatTable::Iterator iter = mLightMaterials.begin();
  349. for ( ; iter != mLightMaterials.end(); iter++ )
  350. delete iter->value;
  351. mLightMaterials.clear();
  352. }
  353. void AdvancedLightBinManager::_setupPerFrameParameters( const SceneRenderState *state )
  354. {
  355. PROFILE_SCOPE( AdvancedLightBinManager_SetupPerFrameParameters );
  356. const Frustum &frustum = state->getCameraFrustum();
  357. MatrixF invCam( frustum.getTransform() );
  358. invCam.inverse();
  359. const Point3F *wsFrustumPoints = frustum.getPoints();
  360. const Point3F& cameraPos = frustum.getPosition();
  361. // Perform a camera offset. We need to manually perform this offset on the sun (or vector) light's
  362. // polygon, which is at the far plane.
  363. const Point2F& projOffset = frustum.getProjectionOffset();
  364. Point3F cameraOffsetPos = cameraPos;
  365. if(!projOffset.isZero())
  366. {
  367. // First we need to calculate the offset at the near plane. The projOffset
  368. // given above can be thought of a percent as it ranges from 0..1 (or 0..-1).
  369. F32 nearOffset = frustum.getNearRight() * projOffset.x;
  370. // Now given the near plane distance from the camera we can solve the right
  371. // triangle and calcuate the SIN theta for the offset at the near plane.
  372. // SIN theta = x/y
  373. F32 sinTheta = nearOffset / frustum.getNearDist();
  374. // Finally, we can calcuate the offset at the far plane, which is where our sun (or vector)
  375. // light's polygon is drawn.
  376. F32 farOffset = frustum.getFarDist() * sinTheta;
  377. // We can now apply this far plane offset to the far plane itself, which then compensates
  378. // for the project offset.
  379. MatrixF camTrans = frustum.getTransform();
  380. VectorF offset = camTrans.getRightVector();
  381. offset *= farOffset;
  382. cameraOffsetPos += offset;
  383. }
  384. // Now build the quad for drawing full-screen vector light
  385. // passes.... this is a volatile VB and updates every frame.
  386. FarFrustumQuadVert verts[4];
  387. {
  388. verts[0].point.set( wsFrustumPoints[Frustum::FarBottomLeft] - cameraPos );
  389. invCam.mulP( wsFrustumPoints[Frustum::FarBottomLeft], &verts[0].normal );
  390. verts[0].texCoord.set( -1.0, -1.0 );
  391. verts[0].tangent.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos);
  392. verts[1].point.set( wsFrustumPoints[Frustum::FarTopLeft] - cameraPos );
  393. invCam.mulP( wsFrustumPoints[Frustum::FarTopLeft], &verts[1].normal );
  394. verts[1].texCoord.set( -1.0, 1.0 );
  395. verts[1].tangent.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraOffsetPos);
  396. verts[2].point.set( wsFrustumPoints[Frustum::FarTopRight] - cameraPos );
  397. invCam.mulP( wsFrustumPoints[Frustum::FarTopRight], &verts[2].normal );
  398. verts[2].texCoord.set( 1.0, 1.0 );
  399. verts[2].tangent.set(wsFrustumPoints[Frustum::FarTopRight] - cameraOffsetPos);
  400. verts[3].point.set( wsFrustumPoints[Frustum::FarBottomRight] - cameraPos );
  401. invCam.mulP( wsFrustumPoints[Frustum::FarBottomRight], &verts[3].normal );
  402. verts[3].texCoord.set( 1.0, -1.0 );
  403. verts[3].tangent.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraOffsetPos);
  404. }
  405. mFarFrustumQuadVerts.set( GFX, 4 );
  406. dMemcpy( mFarFrustumQuadVerts.lock(), verts, sizeof( verts ) );
  407. mFarFrustumQuadVerts.unlock();
  408. PlaneF farPlane(wsFrustumPoints[Frustum::FarBottomLeft], wsFrustumPoints[Frustum::FarTopLeft], wsFrustumPoints[Frustum::FarTopRight]);
  409. PlaneF vsFarPlane(verts[0].normal, verts[1].normal, verts[2].normal);
  410. // Parameters calculated, assign them to the materials
  411. LightMatTable::Iterator iter = mLightMaterials.begin();
  412. for ( ; iter != mLightMaterials.end(); iter++ )
  413. {
  414. if ( iter->value )
  415. iter->value->setViewParameters( frustum.getNearDist(),
  416. frustum.getFarDist(),
  417. frustum.getPosition(),
  418. farPlane,
  419. vsFarPlane);
  420. }
  421. }
  422. void AdvancedLightBinManager::setupSGData( SceneData &data, const SceneRenderState* state, LightInfo *light )
  423. {
  424. PROFILE_SCOPE( AdvancedLightBinManager_setupSGData );
  425. data.lights[0] = light;
  426. data.ambientLightColor = state->getAmbientLightColor();
  427. data.objTrans = &MatrixF::Identity;
  428. if ( light )
  429. {
  430. if ( light->getType() == LightInfo::Point )
  431. {
  432. // The point light volume gets some flat spots along
  433. // the perimiter mostly visible in the constant and
  434. // quadradic falloff modes.
  435. //
  436. // To account for them slightly increase the scale
  437. // instead of greatly increasing the polycount.
  438. mLightMat = light->getTransform();
  439. mLightMat.scale( light->getRange() * 1.01f );
  440. data.objTrans = &mLightMat;
  441. }
  442. else if ( light->getType() == LightInfo::Spot )
  443. {
  444. mLightMat = light->getTransform();
  445. // Rotate it to face down the -y axis.
  446. MatrixF scaleRotateTranslate( EulerF( M_PI_F / -2.0f, 0.0f, 0.0f ) );
  447. // Calculate the radius based on the range and angle.
  448. F32 range = light->getRange().x;
  449. F32 radius = range * mSin( mDegToRad( light->getOuterConeAngle() ) * 0.5f );
  450. // NOTE: This fudge makes the cone a little bigger
  451. // to remove the facet egde of the cone geometry.
  452. radius *= 1.1f;
  453. // Use the scale to distort the cone to
  454. // match our radius and range.
  455. scaleRotateTranslate.scale( Point3F( radius, radius, range ) );
  456. // Apply the transform and set the position.
  457. mLightMat *= scaleRotateTranslate;
  458. mLightMat.setPosition( light->getPosition() );
  459. data.objTrans = &mLightMat;
  460. }
  461. }
  462. }
  463. void AdvancedLightBinManager::MRTLightmapsDuringPrePass( bool val )
  464. {
  465. // Do not enable if the GFX device can't do MRT's
  466. if ( GFX->getNumRenderTargets() < 2 )
  467. val = false;
  468. if ( mMRTLightmapsDuringPrePass != val )
  469. {
  470. mMRTLightmapsDuringPrePass = val;
  471. // Reload materials to cause a feature recalculation on prepass materials
  472. if(mLightManager->isActive())
  473. MATMGR->flushAndReInitInstances();
  474. RenderPrePassMgr *prepass;
  475. if ( Sim::findObject( "AL_PrePassBin", prepass ) && prepass->getTargetTexture( 0 ) )
  476. prepass->updateTargets();
  477. }
  478. }
  479. AdvancedLightBinManager::LightMaterialInfo::LightMaterialInfo( const String &matName,
  480. const GFXVertexFormat *vertexFormat,
  481. const Vector<GFXShaderMacro> &macros )
  482. : matInstance(NULL),
  483. zNearFarInvNearFar(NULL),
  484. farPlane(NULL),
  485. vsFarPlane(NULL),
  486. negFarPlaneDotEye(NULL),
  487. lightPosition(NULL),
  488. lightDirection(NULL),
  489. lightColor(NULL),
  490. lightAttenuation(NULL),
  491. lightRange(NULL),
  492. lightAmbient(NULL),
  493. lightTrilight(NULL),
  494. lightSpotParams(NULL)
  495. {
  496. Material *mat = MATMGR->getMaterialDefinitionByName( matName );
  497. if ( !mat )
  498. return;
  499. matInstance = new LightMatInstance( *mat );
  500. for ( U32 i=0; i < macros.size(); i++ )
  501. matInstance->addShaderMacro( macros[i].name, macros[i].value );
  502. matInstance->init( MATMGR->getDefaultFeatures(), vertexFormat );
  503. lightDirection = matInstance->getMaterialParameterHandle("$lightDirection");
  504. lightAmbient = matInstance->getMaterialParameterHandle("$lightAmbient");
  505. lightTrilight = matInstance->getMaterialParameterHandle("$lightTrilight");
  506. lightSpotParams = matInstance->getMaterialParameterHandle("$lightSpotParams");
  507. lightAttenuation = matInstance->getMaterialParameterHandle("$lightAttenuation");
  508. lightRange = matInstance->getMaterialParameterHandle("$lightRange");
  509. lightPosition = matInstance->getMaterialParameterHandle("$lightPosition");
  510. farPlane = matInstance->getMaterialParameterHandle("$farPlane");
  511. vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane");
  512. negFarPlaneDotEye = matInstance->getMaterialParameterHandle("$negFarPlaneDotEye");
  513. zNearFarInvNearFar = matInstance->getMaterialParameterHandle("$zNearFarInvNearFar");
  514. lightColor = matInstance->getMaterialParameterHandle("$lightColor");
  515. lightBrightness = matInstance->getMaterialParameterHandle("$lightBrightness");
  516. }
  517. AdvancedLightBinManager::LightMaterialInfo::~LightMaterialInfo()
  518. {
  519. SAFE_DELETE(matInstance);
  520. }
  521. void AdvancedLightBinManager::LightMaterialInfo::setViewParameters( const F32 _zNear,
  522. const F32 _zFar,
  523. const Point3F &_eyePos,
  524. const PlaneF &_farPlane,
  525. const PlaneF &_vsFarPlane)
  526. {
  527. MaterialParameters *matParams = matInstance->getMaterialParameters();
  528. matParams->setSafe( farPlane, *((const Point4F *)&_farPlane) );
  529. matParams->setSafe( vsFarPlane, *((const Point4F *)&_vsFarPlane) );
  530. if ( negFarPlaneDotEye->isValid() )
  531. {
  532. // -dot( farPlane, eyePos )
  533. const F32 negFarPlaneDotEyeVal = -( mDot( *((const Point3F *)&_farPlane), _eyePos ) + _farPlane.d );
  534. matParams->set( negFarPlaneDotEye, negFarPlaneDotEyeVal );
  535. }
  536. matParams->setSafe( zNearFarInvNearFar, Point4F( _zNear, _zFar, 1.0f / _zNear, 1.0f / _zFar ) );
  537. }
  538. void AdvancedLightBinManager::LightMaterialInfo::setLightParameters( const LightInfo *lightInfo, const SceneRenderState* renderState, const MatrixF &worldViewOnly )
  539. {
  540. MaterialParameters *matParams = matInstance->getMaterialParameters();
  541. // Set color in the right format, set alpha to the luminance value for the color.
  542. ColorF col = lightInfo->getColor();
  543. // TODO: The specularity control of the light
  544. // is being scaled by the overall lumiance.
  545. //
  546. // Not sure if this may be the source of our
  547. // bad specularity results maybe?
  548. //
  549. const Point3F colorToLumiance( 0.3576f, 0.7152f, 0.1192f );
  550. F32 lumiance = mDot(*((const Point3F *)&lightInfo->getColor()), colorToLumiance );
  551. col.alpha *= lumiance;
  552. matParams->setSafe( lightColor, col );
  553. matParams->setSafe( lightBrightness, lightInfo->getBrightness() );
  554. switch( lightInfo->getType() )
  555. {
  556. case LightInfo::Vector:
  557. {
  558. VectorF lightDir = lightInfo->getDirection();
  559. worldViewOnly.mulV(lightDir);
  560. lightDir.normalize();
  561. matParams->setSafe( lightDirection, lightDir );
  562. // Set small number for alpha since it represents existing specular in
  563. // the vector light. This prevents a divide by zero.
  564. ColorF ambientColor = renderState->getAmbientLightColor();
  565. ambientColor.alpha = 0.00001f;
  566. matParams->setSafe( lightAmbient, ambientColor );
  567. // If no alt color is specified, set it to the average of
  568. // the ambient and main color to avoid artifacts.
  569. //
  570. // TODO: Trilight disabled until we properly implement it
  571. // in the light info!
  572. //
  573. //ColorF lightAlt = lightInfo->getAltColor();
  574. ColorF lightAlt( ColorF::BLACK ); // = lightInfo->getAltColor();
  575. if ( lightAlt.red == 0.0f && lightAlt.green == 0.0f && lightAlt.blue == 0.0f )
  576. lightAlt = (lightInfo->getColor() + renderState->getAmbientLightColor()) / 2.0f;
  577. ColorF trilightColor = lightAlt;
  578. matParams->setSafe(lightTrilight, trilightColor);
  579. }
  580. break;
  581. case LightInfo::Spot:
  582. {
  583. const F32 outerCone = lightInfo->getOuterConeAngle();
  584. const F32 innerCone = getMin( lightInfo->getInnerConeAngle(), outerCone );
  585. const F32 outerCos = mCos( mDegToRad( outerCone / 2.0f ) );
  586. const F32 innerCos = mCos( mDegToRad( innerCone / 2.0f ) );
  587. Point4F spotParams( outerCos,
  588. innerCos - outerCos,
  589. mCos( mDegToRad( outerCone ) ),
  590. 0.0f );
  591. matParams->setSafe( lightSpotParams, spotParams );
  592. VectorF lightDir = lightInfo->getDirection();
  593. worldViewOnly.mulV(lightDir);
  594. lightDir.normalize();
  595. matParams->setSafe( lightDirection, lightDir );
  596. }
  597. // Fall through
  598. case LightInfo::Point:
  599. {
  600. const F32 radius = lightInfo->getRange().x;
  601. matParams->setSafe( lightRange, radius );
  602. Point3F lightPos;
  603. worldViewOnly.mulP(lightInfo->getPosition(), &lightPos);
  604. matParams->setSafe( lightPosition, lightPos );
  605. // Get the attenuation falloff ratio and normalize it.
  606. Point3F attenRatio = lightInfo->getExtended<ShadowMapParams>()->attenuationRatio;
  607. F32 total = attenRatio.x + attenRatio.y + attenRatio.z;
  608. if ( total > 0.0f )
  609. attenRatio /= total;
  610. Point2F attenParams( ( 1.0f / radius ) * attenRatio.y,
  611. ( 1.0f / ( radius * radius ) ) * attenRatio.z );
  612. matParams->setSafe( lightAttenuation, attenParams );
  613. break;
  614. }
  615. default:
  616. AssertFatal( false, "Bad light type!" );
  617. break;
  618. }
  619. }
  620. bool LightMatInstance::setupPass( SceneRenderState *state, const SceneData &sgData )
  621. {
  622. // Go no further if the material failed to initialize properly.
  623. if ( !mProcessedMaterial ||
  624. mProcessedMaterial->getNumPasses() == 0 )
  625. return false;
  626. // Fetch the lightmap params
  627. const LightMapParams *lmParams = sgData.lights[0]->getExtended<LightMapParams>();
  628. // If no Lightmap params, let parent handle it
  629. if(lmParams == NULL)
  630. return Parent::setupPass(state, sgData);
  631. // Defaults
  632. bool bRetVal = true;
  633. // What render pass is this...
  634. if(mCurPass == -1)
  635. {
  636. // First pass, reset this flag
  637. mInternalPass = false;
  638. // Pass call to parent
  639. bRetVal = Parent::setupPass(state, sgData);
  640. }
  641. else
  642. {
  643. // If this light is represented in a lightmap, it has already done it's
  644. // job for non-lightmapped geometry. Now render the lightmapped geometry
  645. // pass (specular + shadow-darkening)
  646. if(!mInternalPass && lmParams->representedInLightmap)
  647. mInternalPass = true;
  648. else
  649. return Parent::setupPass(state, sgData);
  650. }
  651. // Set up the shader constants we need to...
  652. if(mLightMapParamsSC->isValid())
  653. {
  654. // If this is an internal pass, special case the parameters
  655. if(mInternalPass)
  656. {
  657. AssertFatal( lmParams->shadowDarkenColor.alpha == -1.0f, "Assumption failed, check unpack code!" );
  658. getMaterialParameters()->set( mLightMapParamsSC, lmParams->shadowDarkenColor );
  659. }
  660. else
  661. getMaterialParameters()->set( mLightMapParamsSC, ColorF::WHITE );
  662. }
  663. // Now override stateblock with our own
  664. if(!mInternalPass)
  665. {
  666. // If this is not an internal pass, and this light is represented in lightmaps
  667. // than only effect non-lightmapped geometry for this pass
  668. if(lmParams->representedInLightmap)
  669. GFX->setStateBlock(mLitState[StaticLightNonLMGeometry]);
  670. else // This is a normal, dynamic light.
  671. GFX->setStateBlock(mLitState[DynamicLight]);
  672. }
  673. else // Internal pass, this is the add-specular/multiply-darken-color pass
  674. GFX->setStateBlock(mLitState[StaticLightLMGeometry]);
  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 = RenderPrePassMgr::OpaqueDynamicLitMask | RenderPrePassMgr::OpaqueStaticLitMask;
  699. mLitState[DynamicLight] = GFX->createStateBlock(litState);
  700. // StaticLightNonLMGeometry State: This will treat non-lightmapped geometry
  701. // in the usual way, but will not effect lightmapped geometry.
  702. litState.separateAlphaBlendDefined = true;
  703. litState.separateAlphaBlendEnable = false;
  704. litState.stencilMask = RenderPrePassMgr::OpaqueDynamicLitMask;
  705. mLitState[StaticLightNonLMGeometry] = GFX->createStateBlock(litState);
  706. // StaticLightLMGeometry State: This will add specular information (alpha) but
  707. // multiply-darken color information.
  708. litState.blendDest = GFXBlendSrcColor;
  709. litState.blendSrc = GFXBlendZero;
  710. litState.stencilMask = RenderPrePassMgr::OpaqueStaticLitMask;
  711. litState.separateAlphaBlendDefined = true;
  712. litState.separateAlphaBlendEnable = true;
  713. litState.separateAlphaBlendSrc = GFXBlendOne;
  714. litState.separateAlphaBlendDest = GFXBlendOne;
  715. litState.separateAlphaBlendOp = GFXBlendOpAdd;
  716. mLitState[StaticLightLMGeometry] = GFX->createStateBlock(litState);
  717. return true;
  718. }