2
0

basicLightManager.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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/basic/basicLightManager.h"
  24. #include "platform/platformTimer.h"
  25. #include "console/simSet.h"
  26. #include "console/consoleTypes.h"
  27. #include "core/module.h"
  28. #include "core/util/safeDelete.h"
  29. #include "materials/processedMaterial.h"
  30. #include "shaderGen/shaderFeature.h"
  31. #include "lighting/basic/basicSceneObjectLightingPlugin.h"
  32. #include "shaderGen/shaderGenVars.h"
  33. #include "gfx/gfxShader.h"
  34. #include "materials/sceneData.h"
  35. #include "materials/materialParameters.h"
  36. #include "materials/materialManager.h"
  37. #include "materials/materialFeatureTypes.h"
  38. #include "math/util/frustum.h"
  39. #include "scene/sceneObject.h"
  40. #include "renderInstance/renderDeferredMgr.h"
  41. #include "shaderGen/featureMgr.h"
  42. #include "shaderGen/HLSL/shaderFeatureHLSL.h"
  43. #include "shaderGen/HLSL/bumpHLSL.h"
  44. #include "lighting/basic/blTerrainSystem.h"
  45. #include "lighting/common/projectedShadow.h"
  46. #if defined( TORQUE_OPENGL )
  47. #include "shaderGen/GLSL/shaderFeatureGLSL.h"
  48. #include "shaderGen/GLSL/bumpGLSL.h"
  49. #endif
  50. MODULE_BEGIN( BasicLightManager )
  51. MODULE_SHUTDOWN_AFTER( Scene )
  52. MODULE_INIT
  53. {
  54. ManagedSingleton< BasicLightManager >::createSingleton();
  55. }
  56. MODULE_SHUTDOWN
  57. {
  58. ManagedSingleton< BasicLightManager >::deleteSingleton();
  59. }
  60. MODULE_END;
  61. U32 BasicLightManager::smActiveShadowPlugins = 0;
  62. U32 BasicLightManager::smShadowsUpdated = 0;
  63. U32 BasicLightManager::smElapsedUpdateMs = 0;
  64. F32 BasicLightManager::smProjectedShadowFilterDistance = 40.0f;
  65. static S32 QSORT_CALLBACK comparePluginScores( const void *a, const void *b )
  66. {
  67. const BasicSceneObjectLightingPlugin *A = *((BasicSceneObjectLightingPlugin**)a);
  68. const BasicSceneObjectLightingPlugin *B = *((BasicSceneObjectLightingPlugin**)b);
  69. F32 dif = B->getScore() - A->getScore();
  70. return (S32)mFloor( dif );
  71. }
  72. BasicLightManager::BasicLightManager()
  73. : LightManager( "Basic Lighting", "BLM" ),
  74. mLastShader(NULL),
  75. mLastConstants(NULL)
  76. {
  77. mTimer = PlatformTimer::create();
  78. mTerrainSystem = new blTerrainSystem;
  79. getSceneLightingInterface()->registerSystem( mTerrainSystem );
  80. Con::addVariable( "$BasicLightManagerStats::activePlugins",
  81. TypeS32, &smActiveShadowPlugins,
  82. "The number of active Basic Lighting SceneObjectLightingPlugin objects this frame.\n"
  83. "@ingroup BasicLighting\n" );
  84. Con::addVariable( "$BasicLightManagerStats::shadowsUpdated",
  85. TypeS32, &smShadowsUpdated,
  86. "The number of Basic Lighting shadows updated this frame.\n"
  87. "@ingroup BasicLighting\n" );
  88. Con::addVariable( "$BasicLightManagerStats::elapsedUpdateMs",
  89. TypeS32, &smElapsedUpdateMs,
  90. "The number of milliseconds spent this frame updating Basic Lighting shadows.\n"
  91. "@ingroup BasicLighting\n" );
  92. Con::addVariable( "$BasicLightManager::shadowFilterDistance",
  93. TypeF32, &smProjectedShadowFilterDistance,
  94. "The maximum distance in meters that projected shadows will get soft filtering.\n"
  95. "@ingroup BasicLighting\n" );
  96. Con::addVariable( "$pref::ProjectedShadow::fadeStartPixelSize",
  97. TypeF32, &ProjectedShadow::smFadeStartPixelSize,
  98. "A size in pixels at which BL shadows begin to fade out. "
  99. "This should be a larger value than fadeEndPixelSize.\n"
  100. "@see DecalData\n"
  101. "@ingroup BasicLighting\n" );
  102. Con::addVariable( "$pref::ProjectedShadow::fadeEndPixelSize",
  103. TypeF32, &ProjectedShadow::smFadeEndPixelSize,
  104. "A size in pixels at which BL shadows are fully faded out. "
  105. "This should be a smaller value than fadeStartPixelSize.\n"
  106. "@see DecalData\n"
  107. "@ingroup BasicLighting\n" );
  108. }
  109. BasicLightManager::~BasicLightManager()
  110. {
  111. mLastShader = NULL;
  112. mLastConstants = NULL;
  113. for (LightConstantMap::Iterator i = mConstantLookup.begin(); i != mConstantLookup.end(); i++)
  114. {
  115. if (i->value)
  116. SAFE_DELETE(i->value);
  117. }
  118. mConstantLookup.clear();
  119. if (mTimer)
  120. SAFE_DELETE( mTimer );
  121. SAFE_DELETE( mTerrainSystem );
  122. }
  123. bool BasicLightManager::isCompatible() const
  124. {
  125. // As long as we have some shaders this works.
  126. return GFX->getPixelShaderVersion() > 1.0;
  127. }
  128. void BasicLightManager::activate( SceneManager *sceneManager )
  129. {
  130. Parent::activate( sceneManager );
  131. if( GFX->getAdapterType() == OpenGL )
  132. {
  133. #if defined( TORQUE_OPENGL )
  134. FEATUREMGR->registerFeature( MFT_LightMap, new LightmapFeatGLSL );
  135. FEATUREMGR->registerFeature( MFT_ToneMap, new TonemapFeatGLSL );
  136. FEATUREMGR->registerFeature( MFT_NormalMap, new BumpFeatGLSL );
  137. FEATUREMGR->registerFeature( MFT_RTLighting, new RTLightingFeatGLSL );
  138. FEATUREMGR->registerFeature(MFT_ReflectionProbes, new ReflectionProbeFeatGLSL);
  139. #endif
  140. }
  141. else
  142. {
  143. #if defined( TORQUE_OS_WIN )
  144. FEATUREMGR->registerFeature( MFT_LightMap, new LightmapFeatHLSL );
  145. FEATUREMGR->registerFeature( MFT_ToneMap, new TonemapFeatHLSL );
  146. FEATUREMGR->registerFeature( MFT_NormalMap, new BumpFeatHLSL );
  147. FEATUREMGR->registerFeature( MFT_RTLighting, new RTLightingFeatHLSL );
  148. FEATUREMGR->registerFeature(MFT_ReflectionProbes, new ReflectionProbeFeatHLSL);
  149. #endif
  150. }
  151. FEATUREMGR->unregisterFeature( MFT_MinnaertShading );
  152. FEATUREMGR->unregisterFeature( MFT_SubSurface );
  153. // First look for the deferred bin...
  154. RenderDeferredMgr *deferredBin = _findDeferredRenderBin();
  155. /*
  156. // If you would like to use forward shading, and have a linear depth pre-pass
  157. // than un-comment this code block.
  158. if ( !deferredBin )
  159. {
  160. Vector<GFXFormat> formats;
  161. formats.push_back( GFXFormatR32F );
  162. formats.push_back( GFXFormatR16F );
  163. formats.push_back( GFXFormatR8G8B8A8 );
  164. GFXFormat linearDepthFormat = GFX->selectSupportedFormat( &GFXDefaultRenderTargetProfile,
  165. formats,
  166. true,
  167. false );
  168. // Uncomment this for a no-color-write z-fill pass.
  169. //linearDepthFormat = GFXFormat_COUNT;
  170. deferredBin = new RenderDeferredMgr( linearDepthFormat != GFXFormat_COUNT, linearDepthFormat );
  171. deferredBin->registerObject();
  172. rpm->addManager( deferredBin );
  173. }
  174. */
  175. mDeferredRenderBin = deferredBin;
  176. // If there is a deferred bin
  177. MATMGR->setDeferredEnabled( mDeferredRenderBin.isValid() );
  178. sceneManager->setPostEffectFog( mDeferredRenderBin.isValid() && mDeferredRenderBin->getTargetChainLength() > 0 );
  179. // Tell the material manager that we don't use deferred.
  180. MATMGR->setDeferredEnabled( false );
  181. GFXShader::addGlobalMacro( "TORQUE_BASIC_LIGHTING" );
  182. // Hook into the SceneManager prerender signal.
  183. sceneManager->getPreRenderSignal().notify( this, &BasicLightManager::_onPreRender );
  184. // Last thing... let everyone know we're active.
  185. smActivateSignal.trigger( getId(), true );
  186. }
  187. void BasicLightManager::deactivate()
  188. {
  189. Parent::deactivate();
  190. mLastShader = NULL;
  191. mLastConstants = NULL;
  192. for (LightConstantMap::Iterator i = mConstantLookup.begin(); i != mConstantLookup.end(); i++)
  193. {
  194. if (i->value)
  195. SAFE_DELETE(i->value);
  196. }
  197. mConstantLookup.clear();
  198. if ( mDeferredRenderBin )
  199. mDeferredRenderBin->deleteObject();
  200. mDeferredRenderBin = NULL;
  201. GFXShader::removeGlobalMacro( "TORQUE_BASIC_LIGHTING" );
  202. // Remove us from the prerender signal.
  203. getSceneManager()->getPreRenderSignal().remove( this, &BasicLightManager::_onPreRender );
  204. // Now let everyone know we've deactivated.
  205. smActivateSignal.trigger( getId(), false );
  206. }
  207. void BasicLightManager::_onPreRender( SceneManager *sceneManger, const SceneRenderState *state )
  208. {
  209. // Update all our shadow plugins here!
  210. Vector<BasicSceneObjectLightingPlugin*> *pluginInsts = BasicSceneObjectLightingPlugin::getPluginInstances();
  211. Vector<BasicSceneObjectLightingPlugin*>::const_iterator pluginIter = (*pluginInsts).begin();
  212. for ( ; pluginIter != (*pluginInsts).end(); pluginIter++ )
  213. {
  214. BasicSceneObjectLightingPlugin *plugin = *pluginIter;
  215. plugin->updateShadow( (SceneRenderState*)state );
  216. }
  217. U32 pluginCount = (*pluginInsts).size();
  218. // Sort them by the score.
  219. dQsort( (*pluginInsts).address(), pluginCount, sizeof(BasicSceneObjectLightingPlugin*), comparePluginScores );
  220. mTimer->getElapsedMs();
  221. mTimer->reset();
  222. U32 numUpdated = 0;
  223. U32 targetMs = 5;
  224. S32 updateMs = 0;
  225. pluginIter = (*pluginInsts).begin();
  226. for ( ; pluginIter != (*pluginInsts).end(); pluginIter++ )
  227. {
  228. BasicSceneObjectLightingPlugin *plugin = *pluginIter;
  229. // If we run out of update time then stop.
  230. updateMs = mTimer->getElapsedMs();
  231. if ( updateMs >= targetMs )
  232. break;
  233. // NOTE! Fix this all up to past const SceneRenderState!
  234. plugin->renderShadow( (SceneRenderState*)state );
  235. numUpdated++;
  236. }
  237. smShadowsUpdated = numUpdated;
  238. smActiveShadowPlugins = pluginCount;
  239. smElapsedUpdateMs = updateMs;
  240. }
  241. BasicLightManager::LightingShaderConstants::LightingShaderConstants()
  242. : mInit( false ),
  243. mShader( NULL ),
  244. mLightPosition( NULL ),
  245. mLightDiffuse( NULL ),
  246. mLightAmbient( NULL ),
  247. mLightConfigDataSC( NULL ),
  248. mLightSpotDir( NULL ),
  249. mLightSpotParamsSC( NULL ),
  250. mHasVectorLightSC(NULL),
  251. mVectorLightDirectionSC(NULL),
  252. mVectorLightColorSC(NULL),
  253. mVectorLightBrightnessSC(NULL)
  254. {
  255. }
  256. BasicLightManager::LightingShaderConstants::~LightingShaderConstants()
  257. {
  258. if (mShader.isValid())
  259. {
  260. mShader->getReloadSignal().remove( this, &LightingShaderConstants::_onShaderReload );
  261. mShader = NULL;
  262. }
  263. }
  264. void BasicLightManager::LightingShaderConstants::init(GFXShader* shader)
  265. {
  266. if (mShader.getPointer() != shader)
  267. {
  268. if (mShader.isValid())
  269. mShader->getReloadSignal().remove( this, &LightingShaderConstants::_onShaderReload );
  270. mShader = shader;
  271. mShader->getReloadSignal().notify( this, &LightingShaderConstants::_onShaderReload );
  272. }
  273. mLightPosition = shader->getShaderConstHandle( ShaderGenVars::lightPosition );
  274. mLightDiffuse = shader->getShaderConstHandle( ShaderGenVars::lightDiffuse);
  275. mLightConfigDataSC = shader->getShaderConstHandle( ShaderGenVars::lightConfigData );
  276. mLightAmbient = shader->getShaderConstHandle( ShaderGenVars::lightAmbient );
  277. mLightSpotDir = shader->getShaderConstHandle( ShaderGenVars::lightSpotDir );
  278. mLightSpotParamsSC = shader->getShaderConstHandle( ShaderGenVars::lightSpotParams );
  279. mHasVectorLightSC = shader->getShaderConstHandle(ShaderGenVars::hasVectorLight);
  280. mVectorLightDirectionSC = shader->getShaderConstHandle(ShaderGenVars::vectorLightDirection);
  281. mVectorLightColorSC = shader->getShaderConstHandle(ShaderGenVars::vectorLightColor);
  282. mVectorLightBrightnessSC = shader->getShaderConstHandle(ShaderGenVars::vectorLightBrightness);
  283. mInit = true;
  284. }
  285. void BasicLightManager::LightingShaderConstants::_onShaderReload()
  286. {
  287. if (mShader.isValid())
  288. init( mShader );
  289. }
  290. void BasicLightManager::setLightInfo( ProcessedMaterial* pmat,
  291. const Material* mat,
  292. const SceneData& sgData,
  293. const SceneRenderState *state,
  294. U32 pass,
  295. GFXShaderConstBuffer* shaderConsts )
  296. {
  297. PROFILE_SCOPE( BasicLightManager_SetLightInfo );
  298. GFXShader *shader = shaderConsts->getShader();
  299. // Check to see if this is the same shader. Since we
  300. // sort by material we should get hit repeatedly by the
  301. // same one. This optimization should save us many
  302. // hash table lookups.
  303. if ( mLastShader.getPointer() != shader )
  304. {
  305. LightConstantMap::Iterator iter = mConstantLookup.find(shader);
  306. if ( iter != mConstantLookup.end() )
  307. {
  308. mLastConstants = iter->value;
  309. }
  310. else
  311. {
  312. LightingShaderConstants* lsc = new LightingShaderConstants();
  313. mConstantLookup[shader] = lsc;
  314. mLastConstants = lsc;
  315. }
  316. // Set our new shader
  317. mLastShader = shader;
  318. }
  319. // Make sure that our current lighting constants are initialized
  320. if (!mLastConstants->mInit)
  321. mLastConstants->init(shader);
  322. // NOTE: If you encounter a crash from this point forward
  323. // while setting a shader constant its probably because the
  324. // mConstantLookup has bad shaders/constants in it.
  325. //
  326. // This is a known crash bug that can occur if materials/shaders
  327. // are reloaded and the light manager is not reset.
  328. //
  329. // We should look to fix this by clearing the table.
  330. _update4LightConsts( sgData,
  331. mLastConstants->mLightPosition,
  332. mLastConstants->mLightDiffuse,
  333. mLastConstants->mLightAmbient,
  334. mLastConstants->mLightConfigDataSC,
  335. mLastConstants->mLightSpotDir,
  336. mLastConstants->mLightSpotParamsSC,
  337. mLastConstants->mHasVectorLightSC,
  338. mLastConstants->mVectorLightDirectionSC,
  339. mLastConstants->mVectorLightColorSC,
  340. mLastConstants->mVectorLightBrightnessSC,
  341. shaderConsts );
  342. }