advancedLightBinManager.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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. "", // 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. if (curEntry.lightInfo->getType() >= LightInfo::Vector)
  291. continue;
  292. LightMaterialInfo *curLightMat = curEntry.lightMaterial;
  293. const U32 numPrims = curEntry.numPrims;
  294. const U32 numVerts = curEntry.vertBuffer->mNumVerts;
  295. ShadowMapParams *lsp = curLightInfo->getExtended<ShadowMapParams>();
  296. // Skip lights which won't affect the scene.
  297. if ( !curLightMat || curLightInfo->getBrightness() <= 0.001f )
  298. continue;
  299. GFXDEBUGEVENT_SCOPE( AdvancedLightBinManager_Render_Light, ColorI::RED );
  300. setupSGData( sgData, state, curLightInfo );
  301. curLightMat->setLightParameters( curLightInfo, state );
  302. mShadowManager->setLightShadowMap( curEntry.shadowMap );
  303. // Set geometry
  304. GFX->setVertexBuffer( curEntry.vertBuffer );
  305. GFX->setPrimitiveBuffer( curEntry.primBuffer );
  306. lsp->getOcclusionQuery()->begin();
  307. curLightMat->matInstance->mSpecialLight = false;
  308. // Render the material passes
  309. while( curLightMat->matInstance->setupPass( state, sgData ) )
  310. {
  311. // Set transforms
  312. matrixSet.setWorld(*sgData.objTrans);
  313. curLightMat->matInstance->setTransforms(matrixSet, state);
  314. curLightMat->matInstance->setSceneInfo(state, sgData);
  315. if(curEntry.primBuffer)
  316. GFX->drawIndexedPrimitive(GFXTriangleList, 0, 0, numVerts, 0, numPrims);
  317. else
  318. GFX->drawPrimitive(GFXTriangleList, 0, numPrims);
  319. }
  320. lsp->getOcclusionQuery()->end();
  321. }
  322. // Set NULL for active shadow map (so nothing gets confused)
  323. mShadowManager->setLightShadowMap(NULL);
  324. GFX->setVertexBuffer( NULL );
  325. GFX->setPrimitiveBuffer( NULL );
  326. // Fire off a signal to let others know that light-bin rendering is ending now
  327. getRenderSignal().trigger(state, this);
  328. // Finish up the rendering
  329. //_onPostRender();
  330. GFX->popActiveRenderTarget();
  331. }
  332. AdvancedLightBinManager::LightMaterialInfo* AdvancedLightBinManager::_getLightMaterial( LightInfo::Type lightType,
  333. ShadowType shadowType,
  334. bool useCookieTex )
  335. {
  336. PROFILE_SCOPE( AdvancedLightBinManager_GetLightMaterial );
  337. // Build the key.
  338. const LightMatKey key( lightType, shadowType, useCookieTex );
  339. // See if we've already built this one.
  340. LightMatTable::Iterator iter = mLightMaterials.find( key );
  341. if ( iter != mLightMaterials.end() )
  342. return iter->value;
  343. // If we got here we need to build a material for
  344. // this light+shadow combination.
  345. LightMaterialInfo *info = NULL;
  346. // First get the light material name and make sure
  347. // this light has a material in the first place.
  348. const String &lightMatName = smLightMatNames[ lightType ];
  349. if ( lightMatName.isNotEmpty() )
  350. {
  351. Vector<GFXShaderMacro> shadowMacros;
  352. // Setup the shadow type macros for this material.
  353. if ( shadowType == ShadowType_None )
  354. shadowMacros.push_back( GFXShaderMacro( "NO_SHADOW" ) );
  355. else
  356. {
  357. shadowMacros.push_back( GFXShaderMacro( smShadowTypeMacro[ shadowType ] ) );
  358. // Do we need to do shadow filtering?
  359. if ( smShadowFilterMode != ShadowFilterMode_None )
  360. {
  361. shadowMacros.push_back( GFXShaderMacro( "SOFTSHADOW" ) );
  362. const F32 SM = GFX->getPixelShaderVersion();
  363. if ( SM >= 3.0f && smShadowFilterMode == ShadowFilterMode_SoftShadowHighQuality )
  364. shadowMacros.push_back( GFXShaderMacro( "SOFTSHADOW_HIGH_QUALITY" ) );
  365. }
  366. }
  367. if ( useCookieTex )
  368. shadowMacros.push_back( GFXShaderMacro( "USE_COOKIE_TEX" ) );
  369. // Its safe to add the PSSM debug macro to all the materials.
  370. if ( smPSSMDebugRender )
  371. shadowMacros.push_back( GFXShaderMacro( "PSSM_DEBUG_RENDER" ) );
  372. if( smDiffuseLightViz )
  373. shadowMacros.push_back(GFXShaderMacro("DIFFUSE_LIGHT_VIZ"));
  374. else if (smSpecularLightViz)
  375. shadowMacros.push_back(GFXShaderMacro("SPECULAR_LIGHT_VIZ"));
  376. else if (smDetailLightingViz)
  377. shadowMacros.push_back(GFXShaderMacro("DETAIL_LIGHTING_VIZ"));
  378. // Now create the material info object.
  379. info = new LightMaterialInfo( lightMatName, smLightMatVertex[ lightType ], shadowMacros );
  380. }
  381. // Push this into the map and return it.
  382. mLightMaterials.insertUnique( key, info );
  383. return info;
  384. }
  385. void AdvancedLightBinManager::_deleteLightMaterials()
  386. {
  387. LightMatTable::Iterator iter = mLightMaterials.begin();
  388. for ( ; iter != mLightMaterials.end(); iter++ )
  389. delete iter->value;
  390. mLightMaterials.clear();
  391. }
  392. void AdvancedLightBinManager::_setupPerFrameParameters( const SceneRenderState *state )
  393. {
  394. PROFILE_SCOPE( AdvancedLightBinManager_SetupPerFrameParameters );
  395. const Frustum &frustum = state->getCameraFrustum();
  396. MatrixF invCam( frustum.getTransform() );
  397. invCam.inverse();
  398. const Point3F *wsFrustumPoints = frustum.getPoints();
  399. const Point3F& cameraPos = frustum.getPosition();
  400. // Perform a camera offset. We need to manually perform this offset on the sun (or vector) light's
  401. // polygon, which is at the far plane.
  402. Point3F cameraOffsetPos = cameraPos;
  403. // Now build the quad for drawing full-screen vector light
  404. // passes.... this is a volatile VB and updates every frame.
  405. FarFrustumQuadVert verts[4];
  406. {
  407. verts[0].point.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraPos);
  408. invCam.mulP(wsFrustumPoints[Frustum::FarTopLeft], &verts[0].normal);
  409. verts[0].texCoord.set(-1.0, 1.0);
  410. verts[0].tangent.set(wsFrustumPoints[Frustum::FarTopLeft] - cameraOffsetPos);
  411. verts[1].point.set(wsFrustumPoints[Frustum::FarTopRight] - cameraPos);
  412. invCam.mulP(wsFrustumPoints[Frustum::FarTopRight], &verts[1].normal);
  413. verts[1].texCoord.set(1.0, 1.0);
  414. verts[1].tangent.set(wsFrustumPoints[Frustum::FarTopRight] - cameraOffsetPos);
  415. verts[2].point.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraPos);
  416. invCam.mulP(wsFrustumPoints[Frustum::FarBottomLeft], &verts[2].normal);
  417. verts[2].texCoord.set(-1.0, -1.0);
  418. verts[2].tangent.set(wsFrustumPoints[Frustum::FarBottomLeft] - cameraOffsetPos);
  419. verts[3].point.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraPos);
  420. invCam.mulP(wsFrustumPoints[Frustum::FarBottomRight], &verts[3].normal);
  421. verts[3].texCoord.set(1.0, -1.0);
  422. verts[3].tangent.set(wsFrustumPoints[Frustum::FarBottomRight] - cameraOffsetPos);
  423. }
  424. mFarFrustumQuadVerts.set( GFX, 4 );
  425. dMemcpy( mFarFrustumQuadVerts.lock(), verts, sizeof( verts ) );
  426. mFarFrustumQuadVerts.unlock();
  427. PlaneF farPlane(wsFrustumPoints[Frustum::FarBottomLeft], wsFrustumPoints[Frustum::FarTopLeft], wsFrustumPoints[Frustum::FarTopRight]);
  428. PlaneF vsFarPlane(verts[0].normal, verts[1].normal, verts[2].normal);
  429. // Parameters calculated, assign them to the materials
  430. LightMatTable::Iterator iter = mLightMaterials.begin();
  431. for ( ; iter != mLightMaterials.end(); iter++ )
  432. {
  433. if ( iter->value )
  434. iter->value->setViewParameters( frustum.getNearDist(),
  435. frustum.getFarDist(),
  436. frustum.getPosition(),
  437. farPlane,
  438. vsFarPlane);
  439. }
  440. }
  441. void AdvancedLightBinManager::setupSGData( SceneData &data, const SceneRenderState* state, LightInfo *light )
  442. {
  443. PROFILE_SCOPE( AdvancedLightBinManager_setupSGData );
  444. data.lights[0] = light;
  445. data.ambientLightColor = state->getAmbientLightColor();
  446. data.objTrans = &MatrixF::Identity;
  447. if ( light )
  448. {
  449. if ( light->getType() == LightInfo::Point )
  450. {
  451. // The point light volume gets some flat spots along
  452. // the perimiter mostly visible in the constant and
  453. // quadradic falloff modes.
  454. //
  455. // To account for them slightly increase the scale
  456. // instead of greatly increasing the polycount.
  457. mLightMat = light->getTransform();
  458. mLightMat.scale( light->getRange() * 1.01f );
  459. data.objTrans = &mLightMat;
  460. }
  461. else if ( light->getType() == LightInfo::Spot )
  462. {
  463. mLightMat = light->getTransform();
  464. // Rotate it to face down the -y axis.
  465. MatrixF scaleRotateTranslate( EulerF( M_PI_F / -2.0f, 0.0f, 0.0f ) );
  466. // Calculate the radius based on the range and angle.
  467. F32 range = light->getRange().x;
  468. F32 radius = range * mSin( mDegToRad( light->getOuterConeAngle() ) * 0.5f );
  469. // NOTE: This fudge makes the cone a little bigger
  470. // to remove the facet egde of the cone geometry.
  471. radius *= 1.1f;
  472. // Use the scale to distort the cone to
  473. // match our radius and range.
  474. scaleRotateTranslate.scale( Point3F( radius, radius, range ) );
  475. // Apply the transform and set the position.
  476. mLightMat *= scaleRotateTranslate;
  477. mLightMat.setPosition( light->getPosition() );
  478. data.objTrans = &mLightMat;
  479. }
  480. }
  481. }
  482. void AdvancedLightBinManager::MRTLightmapsDuringDeferred( bool val )
  483. {
  484. // Do not enable if the GFX device can't do MRT's
  485. if ( GFX->getNumRenderTargets() < 2 )
  486. val = false;
  487. if ( mMRTLightmapsDuringDeferred != val )
  488. {
  489. mMRTLightmapsDuringDeferred = val;
  490. // Reload materials to cause a feature recalculation on deferred materials
  491. if(mLightManager->isActive())
  492. MATMGR->flushAndReInitInstances();
  493. RenderDeferredMgr *deferred;
  494. if ( Sim::findObject( "AL_DeferredBin", deferred ) && deferred->getTargetTexture( 0 ) )
  495. deferred->updateTargets();
  496. }
  497. }
  498. AdvancedLightBinManager::LightMaterialInfo::LightMaterialInfo( const String &matName,
  499. const GFXVertexFormat *vertexFormat,
  500. const Vector<GFXShaderMacro> &macros )
  501. : matInstance(NULL),
  502. zNearFarInvNearFar(NULL),
  503. farPlane(NULL),
  504. vsFarPlane(NULL),
  505. negFarPlaneDotEye(NULL),
  506. lightPosition(NULL),
  507. lightDirection(NULL),
  508. lightColor(NULL),
  509. lightRange(NULL),
  510. lightInvSqrRange(NULL),
  511. lightAmbient(NULL),
  512. lightSpotParams(NULL)
  513. {
  514. Material *mat = MATMGR->getMaterialDefinitionByName( matName );
  515. if ( !mat )
  516. return;
  517. matInstance = new LightMatInstance( *mat );
  518. for ( U32 i=0; i < macros.size(); i++ )
  519. matInstance->addShaderMacro( macros[i].name, macros[i].value );
  520. matInstance->init( MATMGR->getDefaultFeatures(), vertexFormat );
  521. lightDirection = matInstance->getMaterialParameterHandle("$lightDirection");
  522. lightAmbient = matInstance->getMaterialParameterHandle("$lightAmbient");
  523. lightSpotParams = matInstance->getMaterialParameterHandle("$lightSpotParams");
  524. lightRange = matInstance->getMaterialParameterHandle("$lightRange");
  525. lightInvSqrRange = matInstance->getMaterialParameterHandle("$lightInvSqrRange");
  526. lightPosition = matInstance->getMaterialParameterHandle("$lightPosition");
  527. farPlane = matInstance->getMaterialParameterHandle("$farPlane");
  528. vsFarPlane = matInstance->getMaterialParameterHandle("$vsFarPlane");
  529. negFarPlaneDotEye = matInstance->getMaterialParameterHandle("$negFarPlaneDotEye");
  530. zNearFarInvNearFar = matInstance->getMaterialParameterHandle("$zNearFarInvNearFar");
  531. lightColor = matInstance->getMaterialParameterHandle("$lightColor");
  532. lightBrightness = matInstance->getMaterialParameterHandle("$lightBrightness");
  533. }
  534. AdvancedLightBinManager::LightMaterialInfo::~LightMaterialInfo()
  535. {
  536. SAFE_DELETE(matInstance);
  537. }
  538. void AdvancedLightBinManager::LightMaterialInfo::setViewParameters( const F32 _zNear,
  539. const F32 _zFar,
  540. const Point3F &_eyePos,
  541. const PlaneF &_farPlane,
  542. const PlaneF &_vsFarPlane)
  543. {
  544. MaterialParameters *matParams = matInstance->getMaterialParameters();
  545. matParams->setSafe( farPlane, *((const Point4F *)&_farPlane) );
  546. matParams->setSafe( vsFarPlane, *((const Point4F *)&_vsFarPlane) );
  547. if ( negFarPlaneDotEye->isValid() )
  548. {
  549. // -dot( farPlane, eyePos )
  550. const F32 negFarPlaneDotEyeVal = -( mDot( *((const Point3F *)&_farPlane), _eyePos ) + _farPlane.d );
  551. matParams->set( negFarPlaneDotEye, negFarPlaneDotEyeVal );
  552. }
  553. matParams->setSafe( zNearFarInvNearFar, Point4F( _zNear, _zFar, 1.0f / _zNear, 1.0f / _zFar ) );
  554. }
  555. void AdvancedLightBinManager::LightMaterialInfo::setLightParameters( const LightInfo *lightInfo, const SceneRenderState* renderState )
  556. {
  557. MaterialParameters *matParams = matInstance->getMaterialParameters();
  558. matParams->setSafe( lightColor, lightInfo->getColor() );
  559. matParams->setSafe( lightBrightness, lightInfo->getBrightness() );
  560. switch( lightInfo->getType() )
  561. {
  562. case LightInfo::Vector:
  563. {
  564. matParams->setSafe( lightDirection, lightInfo->getDirection());
  565. matParams->setSafe( lightAmbient, renderState->getAmbientLightColor());
  566. }
  567. break;
  568. case LightInfo::Spot:
  569. {
  570. const F32 outerCone = lightInfo->getOuterConeAngle();
  571. const F32 innerCone = getMin(lightInfo->getInnerConeAngle(), outerCone);
  572. const F32 outerCos = mCos(mDegToRad(outerCone / 2.0f));
  573. const F32 innerCos = mCos(mDegToRad(innerCone / 2.0f));
  574. Point2F spotParams(outerCos,innerCos - outerCos);
  575. matParams->setSafe( lightSpotParams, spotParams );
  576. matParams->setSafe( lightDirection, lightInfo->getDirection());
  577. matParams->setSafe( lightPosition, lightInfo->getPosition());
  578. const F32 radius = lightInfo->getRange().x;
  579. const F32 invSqrRadius = 1.0f / mSquared(radius);
  580. matParams->setSafe(lightRange, radius);
  581. matParams->setSafe(lightInvSqrRange, invSqrRadius);
  582. }
  583. break;
  584. case LightInfo::Point:
  585. {
  586. matParams->setSafe(lightPosition, lightInfo->getPosition());
  587. const F32 radius = lightInfo->getRange().x;
  588. const F32 invSqrRadius = 1.0f / (radius * radius);
  589. matParams->setSafe( lightRange, radius);
  590. matParams->setSafe( lightInvSqrRange, invSqrRadius);
  591. }
  592. break;
  593. default:
  594. AssertFatal( false, "Bad light type!" );
  595. break;
  596. }
  597. }
  598. bool LightMatInstance::setupPass( SceneRenderState *state, const SceneData &sgData )
  599. {
  600. // Go no further if the material failed to initialize properly.
  601. if ( !mProcessedMaterial ||
  602. mProcessedMaterial->getNumPasses() == 0 )
  603. return false;
  604. U32 reflectStatus = Base;
  605. if (state->isReflectPass())
  606. reflectStatus = Reflecting;
  607. // Fetch the lightmap params
  608. const LightMapParams *lmParams = sgData.lights[0]->getExtended<LightMapParams>();
  609. // If no Lightmap params, let parent handle it
  610. if(lmParams == NULL)
  611. return Parent::setupPass(state, sgData);
  612. // Defaults
  613. bool bRetVal = true;
  614. // What render pass is this...
  615. if(mCurPass == -1)
  616. {
  617. // First pass, reset this flag
  618. mInternalPass = false;
  619. // Pass call to parent
  620. bRetVal = Parent::setupPass(state, sgData);
  621. }
  622. else
  623. {
  624. // If this light is represented in a lightmap, it has already done it's
  625. // job for non-lightmapped geometry. Now render the lightmapped geometry
  626. // pass (specular + shadow-darkening)
  627. if(!mInternalPass && lmParams->representedInLightmap)
  628. mInternalPass = true;
  629. else
  630. return Parent::setupPass(state, sgData);
  631. }
  632. // Set up the shader constants we need to...
  633. if(mLightMapParamsSC->isValid())
  634. {
  635. // If this is an internal pass, special case the parameters
  636. if(mInternalPass)
  637. {
  638. AssertFatal( lmParams->shadowDarkenColor.alpha == -1.0f, "Assumption failed, check unpack code!" );
  639. getMaterialParameters()->set( mLightMapParamsSC, lmParams->shadowDarkenColor );
  640. }
  641. else
  642. getMaterialParameters()->set( mLightMapParamsSC, LinearColorF::WHITE );
  643. }
  644. // Now override stateblock with our own
  645. if(!mInternalPass)
  646. {
  647. // If this is not an internal pass, and this light is represented in lightmaps
  648. // than only effect non-lightmapped geometry for this pass
  649. if (lmParams->representedInLightmap)
  650. {
  651. GFX->setStateBlock(mLitState[StaticLightNonLMGeometry][reflectStatus]);
  652. }
  653. else // This is a normal, dynamic light.
  654. {
  655. if (mSpecialLight)
  656. GFX->setStateBlock(mLitState[SunLight][reflectStatus]);
  657. else
  658. GFX->setStateBlock(mLitState[DynamicLight][reflectStatus]);
  659. }
  660. }
  661. else // Internal pass, this is the add-specular/multiply-darken-color pass
  662. GFX->setStateBlock(mLitState[StaticLightLMGeometry][reflectStatus]);
  663. return bRetVal;
  664. }
  665. bool LightMatInstance::init( const FeatureSet &features, const GFXVertexFormat *vertexFormat )
  666. {
  667. bool success = Parent::init(features, vertexFormat);
  668. // If the initialization failed don't continue.
  669. if ( !success || !mProcessedMaterial || mProcessedMaterial->getNumPasses() == 0 )
  670. return false;
  671. mLightMapParamsSC = getMaterialParameterHandle("$lightMapParams");
  672. // Grab the state block for the first render pass (since this mat instance
  673. // inserts a pass after the first pass)
  674. AssertFatal(mProcessedMaterial->getNumPasses() > 0, "No passes created! Ohnoes");
  675. const RenderPassData *rpd = mProcessedMaterial->getPass(0);
  676. AssertFatal(rpd, "No render pass data!");
  677. AssertFatal(rpd->mRenderStates[0], "No render state 0!");
  678. // Get state block desc for normal (not wireframe, not translucent, not glow, etc)
  679. // render state
  680. GFXStateBlockDesc litState = rpd->mRenderStates[0]->getDesc();
  681. // Create state blocks for each of the 3 possible combos in setupPass
  682. //DynamicLight State: This will effect lightmapped and non-lightmapped geometry
  683. // in the same way.
  684. litState.separateAlphaBlendDefined = true;
  685. litState.separateAlphaBlendEnable = false;
  686. litState.stencilMask = RenderDeferredMgr::OpaqueDynamicLitMask | RenderDeferredMgr::OpaqueStaticLitMask;
  687. litState.setCullMode(GFXCullCW);
  688. mLitState[DynamicLight][Base] = GFX->createStateBlock(litState);
  689. litState.setCullMode(GFXCullCCW);
  690. mLitState[DynamicLight][Reflecting] = GFX->createStateBlock(litState);
  691. litState.separateAlphaBlendDefined = true;
  692. litState.separateAlphaBlendEnable = false;
  693. litState.stencilMask = RenderDeferredMgr::OpaqueDynamicLitMask | RenderDeferredMgr::OpaqueStaticLitMask;
  694. litState.setCullMode(GFXCullCCW);
  695. mLitState[SunLight][Base] = GFX->createStateBlock(litState);
  696. litState.setCullMode(GFXCullCCW);
  697. mLitState[SunLight][Reflecting] = GFX->createStateBlock(litState);
  698. // StaticLightNonLMGeometry State: This will treat non-lightmapped geometry
  699. // in the usual way, but will not effect lightmapped geometry.
  700. litState.separateAlphaBlendDefined = true;
  701. litState.separateAlphaBlendEnable = false;
  702. litState.stencilMask = RenderDeferredMgr::OpaqueDynamicLitMask;
  703. litState.setCullMode(GFXCullCW);
  704. mLitState[StaticLightNonLMGeometry][Base] = GFX->createStateBlock(litState);
  705. litState.setCullMode(GFXCullCCW);
  706. mLitState[StaticLightNonLMGeometry][Reflecting] = GFX->createStateBlock(litState);
  707. // StaticLightLMGeometry State: This will add specular information (alpha) but
  708. // multiply-darken color information.
  709. litState.blendDest = GFXBlendSrcColor;
  710. litState.blendSrc = GFXBlendZero;
  711. litState.stencilMask = RenderDeferredMgr::OpaqueStaticLitMask;
  712. litState.separateAlphaBlendDefined = true;
  713. litState.separateAlphaBlendEnable = true;
  714. litState.separateAlphaBlendSrc = GFXBlendOne;
  715. litState.separateAlphaBlendDest = GFXBlendOne;
  716. litState.separateAlphaBlendOp = GFXBlendOpAdd;
  717. litState.setCullMode(GFXCullCW);
  718. mLitState[StaticLightLMGeometry][Base] = GFX->createStateBlock(litState);
  719. litState.setCullMode(GFXCullCCW);
  720. mLitState[StaticLightLMGeometry][Reflecting] = GFX->createStateBlock(litState);
  721. return true;
  722. }