advancedLightBinManager.cpp 37 KB

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