advancedLightBinManager.cpp 33 KB

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