advancedLightBinManager.cpp 37 KB

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