processedMaterial.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  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/processedMaterial.h"
  24. #include "materials/sceneData.h"
  25. #include "materials/materialParameters.h"
  26. #include "materials/matTextureTarget.h"
  27. #include "materials/materialFeatureTypes.h"
  28. #include "materials/materialManager.h"
  29. #include "scene/sceneRenderState.h"
  30. #include "gfx/gfxPrimitiveBuffer.h"
  31. #include "gfx/gfxTextureManager.h"
  32. #include "gfx/sim/cubemapData.h"
  33. RenderPassData::RenderPassData()
  34. {
  35. reset();
  36. }
  37. void RenderPassData::reset()
  38. {
  39. for( U32 i = 0; i < Material::MAX_TEX_PER_PASS; ++ i )
  40. {
  41. destructInPlace( &mTexSlot[ i ] );
  42. mSamplerNames[ i ].clear();
  43. }
  44. dMemset( &mTexSlot, 0, sizeof(mTexSlot) );
  45. dMemset( &mTexType, 0, sizeof(mTexType) );
  46. mCubeMap = NULL;
  47. mNumTex = mNumTexReg = mStageNum = 0;
  48. mGlow = false;
  49. mBlendOp = Material::None;
  50. mFeatureData.clear();
  51. for (U32 i = 0; i < STATE_MAX; i++)
  52. mRenderStates[i] = NULL;
  53. }
  54. String RenderPassData::describeSelf() const
  55. {
  56. String desc;
  57. // Now write all the textures.
  58. String texName;
  59. for ( U32 i=0; i < Material::MAX_TEX_PER_PASS; i++ )
  60. {
  61. if ( mTexType[i] == Material::TexTarget )
  62. texName = ( mTexSlot[i].texTarget ) ? mTexSlot[i].texTarget->getName() : "null_texTarget";
  63. else if ( mTexType[i] == Material::Cube && mCubeMap )
  64. texName = mCubeMap->getPath();
  65. else if ( mTexSlot[i].texObject )
  66. texName = mTexSlot[i].texObject->getPath();
  67. else
  68. continue;
  69. desc += String::ToString( "TexSlot %d: %d, %s\n", i, mTexType[i], texName.c_str() );
  70. }
  71. // Write out the first render state which is the
  72. // basis for all the other states and shoud be
  73. // enough to define the pass uniquely.
  74. desc += mRenderStates[0]->getDesc().describeSelf();
  75. return desc;
  76. }
  77. ProcessedMaterial::ProcessedMaterial()
  78. : mMaterial( NULL ),
  79. mCurrentParams( NULL ),
  80. mHasSetStageData( false ),
  81. mHasGlow( false ),
  82. mHasAccumulation( false ),
  83. mMaxStages( 0 ),
  84. mVertexFormat( NULL ),
  85. mUserObject( NULL )
  86. {
  87. VECTOR_SET_ASSOCIATION( mPasses );
  88. }
  89. ProcessedMaterial::~ProcessedMaterial()
  90. {
  91. T3D::for_each( mPasses.begin(), mPasses.end(), T3D::delete_pointer() );
  92. }
  93. void ProcessedMaterial::_setBlendState(Material::BlendOp blendOp, GFXStateBlockDesc& desc )
  94. {
  95. switch( blendOp )
  96. {
  97. case Material::Add:
  98. {
  99. desc.blendSrc = GFXBlendOne;
  100. desc.blendDest = GFXBlendOne;
  101. break;
  102. }
  103. case Material::AddAlpha:
  104. {
  105. desc.blendSrc = GFXBlendSrcAlpha;
  106. desc.blendDest = GFXBlendOne;
  107. break;
  108. }
  109. case Material::Mul:
  110. {
  111. desc.blendSrc = GFXBlendDestColor;
  112. desc.blendDest = GFXBlendInvSrcAlpha;
  113. break;
  114. }
  115. case Material::LerpAlpha:
  116. {
  117. desc.blendSrc = GFXBlendSrcAlpha;
  118. desc.blendDest = GFXBlendInvSrcAlpha;
  119. break;
  120. }
  121. case Material::Sub:
  122. {
  123. desc.blendOp = GFXBlendOpSubtract;
  124. desc.blendSrc = GFXBlendOne;
  125. desc.blendDest = GFXBlendOne;
  126. break;
  127. }
  128. default:
  129. {
  130. // default to LerpAlpha
  131. desc.blendSrc = GFXBlendSrcAlpha;
  132. desc.blendDest = GFXBlendInvSrcAlpha;
  133. break;
  134. }
  135. }
  136. }
  137. void ProcessedMaterial::setBuffers(GFXVertexBufferHandleBase* vertBuffer, GFXPrimitiveBufferHandle* primBuffer)
  138. {
  139. GFX->setVertexBuffer( *vertBuffer );
  140. GFX->setPrimitiveBuffer( *primBuffer );
  141. }
  142. bool ProcessedMaterial::stepInstance()
  143. {
  144. AssertFatal( false, "ProcessedMaterial::stepInstance() - This type of material doesn't support instancing!" );
  145. return false;
  146. }
  147. String ProcessedMaterial::_getTexturePath(const String& filename)
  148. {
  149. // if '/', then path is specified, use it.
  150. if( filename.find('/') != String::NPos )
  151. {
  152. return filename;
  153. }
  154. // otherwise, construct path
  155. return mMaterial->getPath() + filename;
  156. }
  157. GFXTexHandle ProcessedMaterial::_createTexture( const char* filename, GFXTextureProfile *profile)
  158. {
  159. return GFXTexHandle( _getTexturePath(filename), profile, avar("%s() - NA (line %d)", __FUNCTION__, __LINE__) );
  160. }
  161. GFXTexHandle ProcessedMaterial::_createCompositeTexture(const char *filenameR, const char *filenameG, const char *filenameB, const char *filenameA, U32 inputKey[4], GFXTextureProfile *profile)
  162. {
  163. return GFXTexHandle(_getTexturePath(filenameR), _getTexturePath(filenameG), _getTexturePath(filenameB), _getTexturePath(filenameA), inputKey, profile, avar("%s() - NA (line %d)", __FUNCTION__, __LINE__));
  164. }
  165. void ProcessedMaterial::addStateBlockDesc(const GFXStateBlockDesc& sb)
  166. {
  167. mUserDefined = sb;
  168. }
  169. void ProcessedMaterial::_initStateBlockTemplates(GFXStateBlockDesc& stateTranslucent, GFXStateBlockDesc& stateGlow, GFXStateBlockDesc& stateReflect)
  170. {
  171. // Translucency
  172. stateTranslucent.blendDefined = true;
  173. stateTranslucent.blendEnable = mMaterial->mTranslucentBlendOp != Material::None;
  174. _setBlendState(mMaterial->mTranslucentBlendOp, stateTranslucent);
  175. stateTranslucent.zDefined = true;
  176. stateTranslucent.zWriteEnable = mMaterial->mTranslucentZWrite;
  177. stateTranslucent.alphaDefined = true;
  178. stateTranslucent.alphaTestEnable = mMaterial->mAlphaTest;
  179. stateTranslucent.alphaTestRef = mMaterial->mAlphaRef;
  180. stateTranslucent.alphaTestFunc = GFXCmpGreaterEqual;
  181. stateTranslucent.samplersDefined = true;
  182. stateTranslucent.samplers[0].textureColorOp = GFXTOPModulate;
  183. stateTranslucent.samplers[0].alphaOp = GFXTOPModulate;
  184. stateTranslucent.samplers[0].alphaArg1 = GFXTATexture;
  185. stateTranslucent.samplers[0].alphaArg2 = GFXTADiffuse;
  186. // Glow
  187. stateGlow.zDefined = true;
  188. stateGlow.zWriteEnable = false;
  189. // Reflect
  190. stateReflect.cullDefined = true;
  191. stateReflect.cullMode = mMaterial->mDoubleSided ? GFXCullNone : GFXCullCW;
  192. }
  193. void ProcessedMaterial::_initRenderPassDataStateBlocks()
  194. {
  195. for (U32 pass = 0; pass < mPasses.size(); pass++)
  196. _initRenderStateStateBlocks( mPasses[pass] );
  197. }
  198. void ProcessedMaterial::_initPassStateBlock( RenderPassData *rpd, GFXStateBlockDesc &result )
  199. {
  200. if ( rpd->mBlendOp != Material::None )
  201. {
  202. result.blendDefined = true;
  203. result.blendEnable = true;
  204. _setBlendState( rpd->mBlendOp, result );
  205. }
  206. if (mMaterial && mMaterial->isDoubleSided())
  207. {
  208. result.cullDefined = true;
  209. result.cullMode = GFXCullNone;
  210. }
  211. if(mMaterial && mMaterial->mAlphaTest)
  212. {
  213. result.alphaDefined = true;
  214. result.alphaTestEnable = mMaterial->mAlphaTest;
  215. result.alphaTestRef = mMaterial->mAlphaRef;
  216. result.alphaTestFunc = GFXCmpGreaterEqual;
  217. }
  218. result.samplersDefined = true;
  219. NamedTexTarget *texTarget;
  220. U32 maxAnisotropy = 1;
  221. if (mMaterial && mMaterial->mUseAnisotropic[ rpd->mStageNum ] )
  222. maxAnisotropy = MATMGR->getDefaultAnisotropy();
  223. for( U32 i=0; i < rpd->mNumTex; i++ )
  224. {
  225. U32 currTexFlag = rpd->mTexType[i];
  226. switch( currTexFlag )
  227. {
  228. default:
  229. {
  230. result.samplers[i].textureColorOp = GFXTOPModulate;
  231. result.samplers[i].addressModeU = GFXAddressWrap;
  232. result.samplers[i].addressModeV = GFXAddressWrap;
  233. if ( maxAnisotropy > 1 )
  234. {
  235. result.samplers[i].minFilter = GFXTextureFilterAnisotropic;
  236. result.samplers[i].magFilter = GFXTextureFilterAnisotropic;
  237. result.samplers[i].maxAnisotropy = maxAnisotropy;
  238. }
  239. else
  240. {
  241. result.samplers[i].minFilter = GFXTextureFilterLinear;
  242. result.samplers[i].magFilter = GFXTextureFilterLinear;
  243. }
  244. break;
  245. }
  246. case Material::Cube:
  247. case Material::SGCube:
  248. case Material::NormalizeCube:
  249. {
  250. result.samplers[i].addressModeU = GFXAddressClamp;
  251. result.samplers[i].addressModeV = GFXAddressClamp;
  252. result.samplers[i].addressModeW = GFXAddressClamp;
  253. result.samplers[i].minFilter = GFXTextureFilterLinear;
  254. result.samplers[i].magFilter = GFXTextureFilterLinear;
  255. break;
  256. }
  257. case Material::TexTarget:
  258. {
  259. texTarget = mPasses[0]->mTexSlot[i].texTarget;
  260. if ( texTarget )
  261. texTarget->setupSamplerState( &result.samplers[i] );
  262. break;
  263. }
  264. }
  265. }
  266. // The deferred will take care of writing to the
  267. // zbuffer, so we don't have to by default.
  268. if ( MATMGR->getDeferredEnabled() &&
  269. !mFeatures.hasFeature(MFT_ForwardShading))
  270. result.setZReadWrite( result.zEnable, false );
  271. result.addDesc(mUserDefined);
  272. }
  273. /// Creates the default state blocks for a list of render states
  274. void ProcessedMaterial::_initRenderStateStateBlocks( RenderPassData *rpd )
  275. {
  276. GFXStateBlockDesc stateTranslucent;
  277. GFXStateBlockDesc stateGlow;
  278. GFXStateBlockDesc stateReflect;
  279. GFXStateBlockDesc statePass;
  280. _initStateBlockTemplates( stateTranslucent, stateGlow, stateReflect );
  281. _initPassStateBlock( rpd, statePass );
  282. // Ok, we've got our templates set up, let's combine them together based on state and
  283. // create our state blocks.
  284. for (U32 i = 0; i < RenderPassData::STATE_MAX; i++)
  285. {
  286. GFXStateBlockDesc stateFinal;
  287. if (i & RenderPassData::STATE_REFLECT)
  288. stateFinal.addDesc(stateReflect);
  289. if (i & RenderPassData::STATE_TRANSLUCENT)
  290. stateFinal.addDesc(stateTranslucent);
  291. if (i & RenderPassData::STATE_GLOW)
  292. stateFinal.addDesc(stateGlow);
  293. stateFinal.addDesc(statePass);
  294. if (i & RenderPassData::STATE_WIREFRAME)
  295. stateFinal.fillMode = GFXFillWireframe;
  296. GFXStateBlockRef sb = GFX->createStateBlock(stateFinal);
  297. rpd->mRenderStates[i] = sb;
  298. }
  299. }
  300. U32 ProcessedMaterial::_getRenderStateIndex( const SceneRenderState *sceneState,
  301. const SceneData &sgData )
  302. {
  303. // Based on what the state of the world is, get our render state block
  304. U32 currState = 0;
  305. // NOTE: We should only use per-material or per-pass hints to
  306. // change the render state. This is importaint because we
  307. // only change the state blocks between material passes.
  308. //
  309. // For example sgData.visibility would be bad to use
  310. // in here without changing how RenderMeshMgr works.
  311. if ( sgData.binType == SceneData::GlowBin )
  312. currState |= RenderPassData::STATE_GLOW;
  313. if ( sceneState && sceneState->isReflectPass() )
  314. currState |= RenderPassData::STATE_REFLECT;
  315. if ( sgData.binType != SceneData::DeferredBin &&
  316. mMaterial->isTranslucent() )
  317. currState |= RenderPassData::STATE_TRANSLUCENT;
  318. if ( sgData.wireframe )
  319. currState |= RenderPassData::STATE_WIREFRAME;
  320. return currState;
  321. }
  322. void ProcessedMaterial::_setRenderState( const SceneRenderState *state,
  323. const SceneData& sgData,
  324. U32 pass )
  325. {
  326. // Make sure we have the pass
  327. if ( pass >= mPasses.size() )
  328. return;
  329. U32 currState = _getRenderStateIndex( state, sgData );
  330. GFX->setStateBlock(mPasses[pass]->mRenderStates[currState]);
  331. }
  332. void ProcessedMaterial::_setStageData()
  333. {
  334. // Only do this once
  335. if (mHasSetStageData)
  336. return;
  337. mHasSetStageData = true;
  338. U32 i;
  339. // Load up all the textures for every possible stage
  340. for (i = 0; i < Material::MAX_STAGES; i++)
  341. {
  342. // DiffuseMap
  343. if (mMaterial->mDiffuseMapFilename[i].isNotEmpty())
  344. {
  345. mStages[i].setTex(MFT_DiffuseMap, _createTexture(mMaterial->mDiffuseMapFilename[i], &GFXStaticTextureSRGBProfile));
  346. if (!mStages[i].getTex(MFT_DiffuseMap))
  347. {
  348. //If we start with a #, we're probably actually attempting to hit a named target and it may not get a hit on the first pass. So we'll
  349. //pass on the error rather than spamming the console
  350. if (!mMaterial->mDiffuseMapFilename[i].startsWith("#"))
  351. mMaterial->logError("Failed to load diffuse map %s for stage %i", _getTexturePath(mMaterial->mDiffuseMapFilename[i]).c_str(), i);
  352. // Load a debug texture to make it clear to the user
  353. // that the texture for this stage was missing.
  354. mStages[i].setTex(MFT_DiffuseMap, _createTexture(GFXTextureManager::getMissingTexturePath().c_str(), &GFXStaticTextureSRGBProfile));
  355. }
  356. }
  357. else if (mMaterial->mDiffuseMapAsset[i] && !mMaterial->mDiffuseMapAsset[i].isNull())
  358. {
  359. mStages[i].setTex(MFT_DiffuseMap, mMaterial->mDiffuseMapAsset[i]->getImage());
  360. if (!mStages[i].getTex(MFT_DiffuseMap))
  361. {
  362. // Load a debug texture to make it clear to the user
  363. // that the texture for this stage was missing.
  364. mStages[i].setTex(MFT_DiffuseMap, _createTexture(GFXTextureManager::getMissingTexturePath().c_str(), &GFXStaticTextureSRGBProfile));
  365. }
  366. }
  367. // OverlayMap
  368. if (mMaterial->mOverlayMapFilename[i].isNotEmpty())
  369. {
  370. mStages[i].setTex(MFT_OverlayMap, _createTexture(mMaterial->mOverlayMapFilename[i], &GFXStaticTextureSRGBProfile));
  371. if (!mStages[i].getTex(MFT_OverlayMap))
  372. mMaterial->logError("Failed to load overlay map %s for stage %i", _getTexturePath(mMaterial->mOverlayMapFilename[i]).c_str(), i);
  373. }
  374. // LightMap
  375. if (mMaterial->mLightMapFilename[i].isNotEmpty())
  376. {
  377. mStages[i].setTex(MFT_LightMap, _createTexture(mMaterial->mLightMapFilename[i], &GFXStaticTextureSRGBProfile));
  378. if (!mStages[i].getTex(MFT_LightMap))
  379. mMaterial->logError("Failed to load light map %s for stage %i", _getTexturePath(mMaterial->mLightMapFilename[i]).c_str(), i);
  380. }
  381. // ToneMap
  382. if (mMaterial->mToneMapFilename[i].isNotEmpty())
  383. {
  384. mStages[i].setTex(MFT_ToneMap, _createTexture(mMaterial->mToneMapFilename[i], &GFXStaticTextureProfile));
  385. if (!mStages[i].getTex(MFT_ToneMap))
  386. mMaterial->logError("Failed to load tone map %s for stage %i", _getTexturePath(mMaterial->mToneMapFilename[i]).c_str(), i);
  387. }
  388. // DetailMap
  389. if (mMaterial->mDetailMapFilename[i].isNotEmpty())
  390. {
  391. mStages[i].setTex(MFT_DetailMap, _createTexture(mMaterial->mDetailMapFilename[i], &GFXStaticTextureProfile));
  392. if (!mStages[i].getTex(MFT_DetailMap))
  393. mMaterial->logError("Failed to load detail map %s for stage %i", _getTexturePath(mMaterial->mDetailMapFilename[i]).c_str(), i);
  394. }
  395. // NormalMap
  396. if (mMaterial->mNormalMapFilename[i].isNotEmpty())
  397. {
  398. mStages[i].setTex(MFT_NormalMap, _createTexture(mMaterial->mNormalMapFilename[i], &GFXNormalMapProfile));
  399. if (!mStages[i].getTex(MFT_NormalMap))
  400. mMaterial->logError("Failed to load normal map %s for stage %i", _getTexturePath(mMaterial->mNormalMapFilename[i]).c_str(), i);
  401. }
  402. // Detail Normal Map
  403. if (mMaterial->mDetailNormalMapFilename[i].isNotEmpty())
  404. {
  405. mStages[i].setTex(MFT_DetailNormalMap, _createTexture(mMaterial->mDetailNormalMapFilename[i], &GFXNormalMapProfile));
  406. if (!mStages[i].getTex(MFT_DetailNormalMap))
  407. mMaterial->logError("Failed to load normal map %s for stage %i", _getTexturePath(mMaterial->mDetailNormalMapFilename[i]).c_str(), i);
  408. }
  409. GFXTextureProfile* profile = &GFXStaticTextureProfile;
  410. if (mMaterial->mIsSRGb[i])
  411. profile = &GFXStaticTextureSRGBProfile;
  412. // SpecularMap
  413. if (mMaterial->mSpecularMapFilename[i].isNotEmpty())
  414. {
  415. mStages[i].setTex(MFT_SpecularMap, _createTexture(mMaterial->mSpecularMapFilename[i], profile));
  416. if (!mStages[i].getTex(MFT_SpecularMap))
  417. mMaterial->logError("Failed to load specular map %s for stage %i", _getTexturePath(mMaterial->mSpecularMapFilename[i]).c_str(), i);
  418. }
  419. else
  420. {
  421. if (mMaterial->mRoughMapFilename[i].isNotEmpty() && mMaterial->mMetalMapFilename[i].isNotEmpty())
  422. {
  423. U32 inputKey[4];
  424. inputKey[0] = mMaterial->mSmoothnessChan[i];
  425. inputKey[1] = mMaterial->mAOChan[i];
  426. inputKey[2] = mMaterial->mMetalChan[i];
  427. inputKey[3] = NULL;
  428. mStages[i].setTex(MFT_SpecularMap, _createCompositeTexture(mMaterial->mRoughMapFilename[i], mMaterial->mAOMapFilename[i],
  429. mMaterial->mMetalMapFilename[i], "",
  430. inputKey, profile));
  431. if (!mStages[i].getTex(MFT_SpecularMap))
  432. mMaterial->logError("Failed to load specular map %s for stage %i", _getTexturePath(mMaterial->mSpecularMapFilename[i]).c_str(), i);
  433. }
  434. }
  435. }
  436. mMaterial->mCubemapData = dynamic_cast<CubemapData*>(Sim::findObject(mMaterial->mCubemapName));
  437. if (!mMaterial->mCubemapData)
  438. mMaterial->mCubemapData = NULL;
  439. // If we have a cubemap put it on stage 0 (cubemaps only supported on stage 0)
  440. if (mMaterial->mCubemapData)
  441. {
  442. mMaterial->mCubemapData->createMap();
  443. mStages[0].setCubemap(mMaterial->mCubemapData->mCubemap);
  444. if (!mStages[0].getCubemap())
  445. mMaterial->logError("Failed to load cubemap");
  446. }
  447. }