materialManager.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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 "materials/materialManager.h"
  24. #include "materials/matInstance.h"
  25. #include "materials/materialFeatureTypes.h"
  26. #include "lighting/lightManager.h"
  27. #include "core/util/safeDelete.h"
  28. #include "shaderGen/shaderGen.h"
  29. #include "core/module.h"
  30. #include "console/consoleTypes.h"
  31. #include "console/engineAPI.h"
  32. #include "gui/controls/guiTreeViewCtrl.h"
  33. MODULE_BEGIN( MaterialManager )
  34. MODULE_INIT_BEFORE( GFX )
  35. MODULE_SHUTDOWN_BEFORE( GFX )
  36. MODULE_INIT
  37. {
  38. MaterialManager::createSingleton();
  39. }
  40. MODULE_SHUTDOWN
  41. {
  42. MaterialManager::deleteSingleton();
  43. }
  44. MODULE_END;
  45. MaterialManager::MaterialManager()
  46. {
  47. VECTOR_SET_ASSOCIATION( mMatInstanceList );
  48. mDt = 0.0f;
  49. mAccumTime = 0.0f;
  50. mLastTime = 0;
  51. mWarningInst = NULL;
  52. GFXDevice::getDeviceEventSignal().notify( this, &MaterialManager::_handleGFXEvent );
  53. // Make sure we get activation signals
  54. // and that we're the last to get them.
  55. LightManager::smActivateSignal.notify( this, &MaterialManager::_onLMActivate, 9999 );
  56. mMaterialSet = NULL;
  57. mUsingDeferred = false;
  58. mFlushAndReInit = false;
  59. mDefaultAnisotropy = 1;
  60. Con::addVariable( "$pref::Video::defaultAnisotropy", TypeS32, &mDefaultAnisotropy,
  61. "@brief Global variable defining the default anisotropy value.\n\n"
  62. "Controls the default anisotropic texture filtering level for all materials, including the terrain. "
  63. "This value can be changed at runtime to see its affect without reloading.\n\n "
  64. "@ingroup Materials");
  65. Con::NotifyDelegate callabck( this, &MaterialManager::_updateDefaultAnisotropy );
  66. Con::addVariableNotify( "$pref::Video::defaultAnisotropy", callabck );
  67. Con::NotifyDelegate callabck2( this, &MaterialManager::_onDisableMaterialFeature );
  68. Con::setVariable( "$pref::Video::disableNormalMapping", "false" );
  69. Con::addVariableNotify( "$pref::Video::disableNormalMapping", callabck2 );
  70. Con::setVariable( "$pref::Video::disableCubemapping", "false" );
  71. Con::addVariableNotify( "$pref::Video::disableCubemapping", callabck2 );
  72. Con::setVariable( "$pref::Video::disableParallaxMapping", "false" );
  73. Con::addVariableNotify( "$pref::Video::disableParallaxMapping", callabck2 );
  74. }
  75. MaterialManager::~MaterialManager()
  76. {
  77. GFXDevice::getDeviceEventSignal().remove( this, &MaterialManager::_handleGFXEvent );
  78. LightManager::smActivateSignal.remove( this, &MaterialManager::_onLMActivate );
  79. SAFE_DELETE( mWarningInst );
  80. #ifndef TORQUE_SHIPPING
  81. DebugMaterialMap::Iterator itr = mMeshDebugMaterialInsts.begin();
  82. for ( ; itr != mMeshDebugMaterialInsts.end(); itr++ )
  83. delete itr->value;
  84. #endif
  85. }
  86. void MaterialManager::_onLMActivate( const char *lm, bool activate )
  87. {
  88. if ( !activate )
  89. return;
  90. // Since the light manager usually swaps shadergen features
  91. // and changes system wide shader defines we need to completely
  92. // flush and rebuild all the material instances.
  93. mFlushAndReInit = true;
  94. }
  95. void MaterialManager::_updateDefaultAnisotropy()
  96. {
  97. // Update all the materials.
  98. Vector<BaseMatInstance*>::iterator iter = mMatInstanceList.begin();
  99. for ( ; iter != mMatInstanceList.end(); iter++ )
  100. (*iter)->updateStateBlocks();
  101. }
  102. Material * MaterialManager::allocateAndRegister(const String &objectName, const String &mapToName)
  103. {
  104. Material *newMat = new Material();
  105. if ( mapToName.isNotEmpty() )
  106. newMat->mMapTo = mapToName;
  107. bool registered = newMat->registerObject(objectName );
  108. AssertFatal( registered, "Unable to register material" );
  109. if (registered)
  110. Sim::getRootGroup()->addObject( newMat );
  111. else
  112. {
  113. delete newMat;
  114. newMat = NULL;
  115. }
  116. return newMat;
  117. }
  118. Material * MaterialManager::getMaterialDefinitionByName(const String &matName)
  119. {
  120. // Get the material
  121. Material * foundMat;
  122. if(!Sim::findObject(matName, foundMat))
  123. {
  124. Con::errorf("MaterialManager: Unable to find material '%s'", matName.c_str());
  125. return NULL;
  126. }
  127. return foundMat;
  128. }
  129. Material* MaterialManager::getMaterialDefinitionByMapTo(const String& mapTo)
  130. {
  131. // Get the material
  132. Material* foundMat = nullptr;
  133. for (SimSet::iterator itr = mMaterialSet->begin(); itr != mMaterialSet->end(); ++itr)
  134. {
  135. // Fetch our listed materials.
  136. Material* materialDef = dynamic_cast<Material*>(*itr);
  137. if (materialDef && materialDef->mMapTo.compare(mapTo, 0U, String::NoCase) == 0)
  138. {
  139. //We have a match, so keep it and bail the loop
  140. foundMat = materialDef;
  141. break;
  142. }
  143. }
  144. return foundMat;
  145. }
  146. BaseMatInstance* MaterialManager::createMatInstance(const String &matName)
  147. {
  148. BaseMaterialDefinition* mat = NULL;
  149. if (Sim::findObject(matName, mat))
  150. return mat->createMatInstance();
  151. return NULL;
  152. }
  153. BaseMatInstance* MaterialManager::createMatInstance( const String &matName,
  154. const GFXVertexFormat *vertexFormat )
  155. {
  156. return createMatInstance( matName, getDefaultFeatures(), vertexFormat );
  157. }
  158. BaseMatInstance* MaterialManager::createMatInstance( const String &matName,
  159. const FeatureSet& features,
  160. const GFXVertexFormat *vertexFormat )
  161. {
  162. BaseMatInstance* mat = createMatInstance(matName);
  163. if (mat)
  164. {
  165. mat->init( features, vertexFormat );
  166. return mat;
  167. }
  168. return NULL;
  169. }
  170. BaseMatInstance * MaterialManager::createWarningMatInstance()
  171. {
  172. Material *warnMat = static_cast<Material*>(Sim::findObject("WarningMaterial"));
  173. BaseMatInstance *warnMatInstance = NULL;
  174. if( warnMat != NULL )
  175. {
  176. warnMatInstance = warnMat->createMatInstance();
  177. GFXStateBlockDesc desc;
  178. desc.setCullMode(GFXCullNone);
  179. warnMatInstance->addStateBlockDesc(desc);
  180. warnMatInstance->init( getDefaultFeatures(),
  181. getGFXVertexFormat<GFXVertexPNTTB>() );
  182. }
  183. else
  184. Con::errorf("WarningMaterial Not Found!");
  185. return warnMatInstance;
  186. }
  187. // Gets the global warning material instance, callers should not free this copy
  188. BaseMatInstance * MaterialManager::getWarningMatInstance()
  189. {
  190. if (!mWarningInst)
  191. mWarningInst = createWarningMatInstance();
  192. return mWarningInst;
  193. }
  194. #ifndef TORQUE_SHIPPING
  195. BaseMatInstance * MaterialManager::createMeshDebugMatInstance(const LinearColorF &meshColor)
  196. {
  197. String meshDebugStr = String::ToString( "Torque_MeshDebug_%d", meshColor.getRGBAPack() );
  198. Material *debugMat;
  199. if (!Sim::findObject(meshDebugStr,debugMat))
  200. {
  201. debugMat = allocateAndRegister( meshDebugStr );
  202. debugMat->mDiffuse[0] = meshColor;
  203. debugMat->mEmissive[0] = true;
  204. }
  205. BaseMatInstance *debugMatInstance = NULL;
  206. if( debugMat != NULL )
  207. {
  208. debugMatInstance = debugMat->createMatInstance();
  209. GFXStateBlockDesc desc;
  210. desc.setCullMode(GFXCullNone);
  211. desc.fillMode = GFXFillWireframe;
  212. debugMatInstance->addStateBlockDesc(desc);
  213. // Disable fog and other stuff.
  214. FeatureSet debugFeatures;
  215. debugFeatures.addFeature( MFT_DiffuseColor );
  216. debugMatInstance->init( debugFeatures, getGFXVertexFormat<GFXVertexPCN>() );
  217. }
  218. return debugMatInstance;
  219. }
  220. // Gets the global material instance for a given color, callers should not free this copy
  221. BaseMatInstance *MaterialManager::getMeshDebugMatInstance(const LinearColorF &meshColor)
  222. {
  223. DebugMaterialMap::Iterator itr = mMeshDebugMaterialInsts.find( meshColor.getRGBAPack() );
  224. BaseMatInstance *inst = NULL;
  225. if ( itr == mMeshDebugMaterialInsts.end() )
  226. inst = createMeshDebugMatInstance( meshColor );
  227. else
  228. inst = itr->value;
  229. mMeshDebugMaterialInsts.insert( meshColor.getRGBAPack(), inst );
  230. return inst;
  231. }
  232. #endif
  233. void MaterialManager::mapMaterial(const String & textureName, const String & materialName)
  234. {
  235. if (getMapEntry(textureName).isNotEmpty())
  236. {
  237. if (!textureName.equal("unmapped_mat", String::NoCase))
  238. Con::warnf(ConsoleLogEntry::General, "Warning, overwriting material for: %s", textureName.c_str());
  239. }
  240. mMaterialMap[String::ToLower(textureName)] = materialName;
  241. }
  242. String MaterialManager::getMapEntry(const String & textureName) const
  243. {
  244. MaterialMap::ConstIterator iter = mMaterialMap.find(String::ToLower(textureName));
  245. if ( iter == mMaterialMap.end() )
  246. return String();
  247. return iter->value;
  248. }
  249. void MaterialManager::flushAndReInitInstances()
  250. {
  251. // Clear the flag if its set.
  252. mFlushAndReInit = false;
  253. // Check to see if any shader preferences have changed.
  254. recalcFeaturesFromPrefs();
  255. // First we flush all the shader gen shaders which will
  256. // invalidate all GFXShader* to them.
  257. SHADERGEN->flushProceduralShaders();
  258. mFlushSignal.trigger();
  259. // First do a pass deleting all hooks as they can contain
  260. // materials themselves. This means we have to restart the
  261. // loop every time we delete any hooks... lame.
  262. Vector<BaseMatInstance*>::iterator iter = mMatInstanceList.begin();
  263. while ( iter != mMatInstanceList.end() )
  264. {
  265. if ( (*iter)->deleteAllHooks() != 0 )
  266. {
  267. // Restart the loop.
  268. iter = mMatInstanceList.begin();
  269. continue;
  270. }
  271. iter++;
  272. }
  273. // Now do a pass re-initializing materials.
  274. iter = mMatInstanceList.begin();
  275. for ( ; iter != mMatInstanceList.end(); iter++ )
  276. (*iter)->reInit();
  277. }
  278. // Used in the materialEditor. This flushes the material preview object so it can be reloaded easily.
  279. void MaterialManager::flushInstance( BaseMaterialDefinition *target )
  280. {
  281. Vector<BaseMatInstance*>::iterator iter = mMatInstanceList.begin();
  282. while ( iter != mMatInstanceList.end() )
  283. {
  284. if ( (*iter)->getMaterial() == target )
  285. {
  286. (*iter)->deleteAllHooks();
  287. return;
  288. }
  289. iter++;
  290. }
  291. }
  292. void MaterialManager::reInitInstance( BaseMaterialDefinition *target )
  293. {
  294. Vector<BaseMatInstance*>::iterator iter = mMatInstanceList.begin();
  295. for ( ; iter != mMatInstanceList.end(); iter++ )
  296. {
  297. if ( (*iter)->getMaterial() == target )
  298. (*iter)->reInit();
  299. }
  300. }
  301. void MaterialManager::updateTime()
  302. {
  303. U32 curTime = Sim::getCurrentTime();
  304. if(curTime > mLastTime)
  305. {
  306. mDt = (curTime - mLastTime) / 1000.0f;
  307. mLastTime = curTime;
  308. mAccumTime += mDt;
  309. }
  310. else
  311. mDt = 0.0f;
  312. }
  313. SimSet * MaterialManager::getMaterialSet()
  314. {
  315. if(!mMaterialSet)
  316. mMaterialSet = static_cast<SimSet*>( Sim::findObject( "MaterialSet" ) );
  317. AssertFatal( mMaterialSet, "MaterialSet not found" );
  318. return mMaterialSet;
  319. }
  320. void MaterialManager::dumpMaterialInstances( BaseMaterialDefinition *target ) const
  321. {
  322. if ( !mMatInstanceList.size() )
  323. return;
  324. if ( target )
  325. Con::printf( "--------------------- %s MatInstances ---------------------", target->getName() );
  326. else
  327. Con::printf( "--------------------- MatInstances %d ---------------------", mMatInstanceList.size() );
  328. for( U32 i=0; i<mMatInstanceList.size(); i++ )
  329. {
  330. BaseMatInstance *inst = mMatInstanceList[i];
  331. if ( target && inst->getMaterial() != target )
  332. continue;
  333. inst->dumpShaderInfo();
  334. Con::printf( "" );
  335. }
  336. Con::printf( "---------------------- Dump complete ----------------------");
  337. }
  338. void MaterialManager::getMaterialInstances(BaseMaterialDefinition* target, GuiTreeViewCtrl* materailInstanceTree)
  339. {
  340. if (!mMatInstanceList.size())
  341. return;
  342. if (!target)
  343. {
  344. Con::errorf("Can't form a list without a specific MaterialDefinition");
  345. return;
  346. }
  347. if (!materailInstanceTree)
  348. {
  349. Con::errorf("Requires a valid GuiTreeViewCtrl object to populate data into!");
  350. return;
  351. }
  352. U32 matItem = materailInstanceTree->insertItem(0, target->getName());
  353. for (U32 i = 0; i < mMatInstanceList.size(); i++)
  354. {
  355. BaseMatInstance* inst = mMatInstanceList[i];
  356. if (target && inst->getMaterial() != target)
  357. continue;
  358. inst->getShaderInfo(materailInstanceTree, matItem);
  359. }
  360. }
  361. void MaterialManager::_track( MatInstance *matInstance )
  362. {
  363. mMatInstanceList.push_back( matInstance );
  364. }
  365. void MaterialManager::_untrack( MatInstance *matInstance )
  366. {
  367. mMatInstanceList.remove( matInstance );
  368. }
  369. void MaterialManager::recalcFeaturesFromPrefs()
  370. {
  371. mDefaultFeatures.clear();
  372. FeatureType::addDefaultTypes( &mDefaultFeatures );
  373. mExclusionFeatures.setFeature( MFT_NormalMap,
  374. Con::getBoolVariable( "$pref::Video::disableNormalMapping", false ) );
  375. mExclusionFeatures.setFeature( MFT_CubeMap,
  376. Con::getBoolVariable( "$pref::Video::disableCubemapping", false ) );
  377. mExclusionFeatures.setFeature( MFT_Parallax,
  378. Con::getBoolVariable( "$pref::Video::disableParallaxMapping", false ) );
  379. }
  380. bool MaterialManager::_handleGFXEvent( GFXDevice::GFXDeviceEventType event_ )
  381. {
  382. switch ( event_ )
  383. {
  384. case GFXDevice::deInit:
  385. recalcFeaturesFromPrefs();
  386. break;
  387. case GFXDevice::deDestroy :
  388. SAFE_DELETE( mWarningInst );
  389. break;
  390. case GFXDevice::deStartOfFrame:
  391. if ( mFlushAndReInit )
  392. flushAndReInitInstances();
  393. break;
  394. default:
  395. break;
  396. }
  397. return true;
  398. }
  399. DefineEngineFunction( reInitMaterials, void, (),,
  400. "@brief Flushes all procedural shaders and re-initializes all active material instances.\n\n"
  401. "@ingroup Materials")
  402. {
  403. MATMGR->flushAndReInitInstances();
  404. }
  405. DefineEngineFunction( addMaterialMapping, void, (const char * texName, const char * matName), , "(string texName, string matName)\n"
  406. "@brief Maps the given texture to the given material.\n\n"
  407. "Generates a console warning before overwriting.\n\n"
  408. "Material maps are used by terrain and interiors for triggering "
  409. "effects when an object moves onto a terrain "
  410. "block or interior surface using the associated texture.\n\n"
  411. "@ingroup Materials")
  412. {
  413. MATMGR->mapMaterial(texName, matName);
  414. }
  415. DefineEngineFunction( getMaterialMapping, const char*, (const char * texName), , "(string texName)\n"
  416. "@brief Returns the name of the material mapped to this texture.\n\n"
  417. "If no materials are found, an empty string is returned.\n\n"
  418. "@param texName Name of the texture\n\n"
  419. "@ingroup Materials")
  420. {
  421. return MATMGR->getMapEntry(texName).c_str();
  422. }
  423. DefineEngineFunction( dumpMaterialInstances, void, (), ,
  424. "@brief Dumps a formatted list of currently allocated material instances to the console.\n\n"
  425. "@ingroup Materials")
  426. {
  427. MATMGR->dumpMaterialInstances();
  428. }
  429. DefineEngineFunction(getMaterialInstances, void, (BaseMaterialDefinition* target, GuiTreeViewCtrl* tree), (nullAsType<BaseMaterialDefinition*>(), nullAsType<GuiTreeViewCtrl*>()),
  430. "@brief Dumps a formatted list of currently allocated material instances to the console.\n\n"
  431. "@ingroup Materials")
  432. {
  433. if (target == nullptr || tree == nullptr)
  434. return;
  435. MATMGR->getMaterialInstances(target, tree);
  436. }
  437. DefineEngineFunction( getMapEntry, const char*, (const char * texName), ,
  438. "@hide")
  439. {
  440. return MATMGR->getMapEntry( String(texName) );
  441. }