processedCustomMaterial.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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/processedCustomMaterial.h"
  24. #include "gfx/sim/cubemapData.h"
  25. #include "materials/sceneData.h"
  26. #include "shaderGen/shaderGenVars.h"
  27. #include "scene/sceneRenderState.h"
  28. #include "materials/customMaterialDefinition.h"
  29. #include "materials/shaderData.h"
  30. #include "materials/materialManager.h"
  31. #include "materials/matTextureTarget.h"
  32. #include "materials/materialFeatureTypes.h"
  33. #include "materials/materialParameters.h"
  34. #include "gfx/sim/gfxStateBlockData.h"
  35. #include "core/util/safeDelete.h"
  36. #include "gfx/genericConstBuffer.h"
  37. #include "console/simFieldDictionary.h"
  38. #include "console/propertyParsing.h"
  39. #include "gfx/util/screenspace.h"
  40. #include "scene/reflectionManager.h"
  41. ProcessedCustomMaterial::ProcessedCustomMaterial(Material &mat)
  42. {
  43. mMaterial = &mat;
  44. AssertFatal(dynamic_cast<CustomMaterial*>(mMaterial), "Incompatible Material type!");
  45. mCustomMaterial = static_cast<CustomMaterial*>(mMaterial);
  46. mHasSetStageData = false;
  47. mHasGlow = false;
  48. mMaxStages = 0;
  49. mMaxTex = 0;
  50. }
  51. ProcessedCustomMaterial::~ProcessedCustomMaterial()
  52. {
  53. }
  54. void ProcessedCustomMaterial::_setStageData()
  55. {
  56. // Only do this once
  57. if ( mHasSetStageData )
  58. return;
  59. mHasSetStageData = true;
  60. ShaderRenderPassData* rpd = _getRPD(0);
  61. mConditionerMacros.clear();
  62. // Loop through all the possible textures, set the right flags, and load them if needed
  63. for(U32 i=0; i<CustomMaterial::MAX_TEX_PER_PASS; i++ )
  64. {
  65. rpd->mTexType[i] = Material::NoTexture; // Set none as the default in case none of the cases below catch it.
  66. String filename = mCustomMaterial->mTexFilename[i];
  67. if(filename.isEmpty())
  68. continue;
  69. if(filename.equal(String("$dynamiclight"), String::NoCase))
  70. {
  71. rpd->mTexType[i] = Material::DynamicLight;
  72. mMaxTex = i+1;
  73. continue;
  74. }
  75. if(filename.equal(String("$dynamiclightmask"), String::NoCase))
  76. {
  77. rpd->mTexType[i] = Material::DynamicLightMask;
  78. mMaxTex = i+1;
  79. continue;
  80. }
  81. if(filename.equal(String("$lightmap"), String::NoCase))
  82. {
  83. rpd->mTexType[i] = Material::Lightmap;
  84. mMaxTex = i+1;
  85. continue;
  86. }
  87. if(filename.equal(String("$cubemap"), String::NoCase))
  88. {
  89. if( mCustomMaterial->mCubemapData )
  90. {
  91. rpd->mTexType[i] = Material::Cube;
  92. mMaxTex = i+1;
  93. }
  94. else
  95. {
  96. mCustomMaterial->logError( "Could not find CubemapData - %s", mCustomMaterial->mCubemapName.c_str());
  97. }
  98. continue;
  99. }
  100. if(filename.equal(String("$dynamicCubemap"), String::NoCase))
  101. {
  102. rpd->mTexType[i] = Material::SGCube;
  103. mMaxTex = i+1;
  104. continue;
  105. }
  106. if(filename.equal(String("$backbuff"), String::NoCase))
  107. {
  108. rpd->mTexType[i] = Material::BackBuff;
  109. mMaxTex = i+1;
  110. continue;
  111. }
  112. if(filename.equal(String("$reflectbuff"), String::NoCase))
  113. {
  114. rpd->mTexType[i] = Material::ReflectBuff;
  115. mMaxTex = i+1;
  116. continue;
  117. }
  118. if(filename.equal(String("$miscbuff"), String::NoCase))
  119. {
  120. rpd->mTexType[i] = Material::Misc;
  121. mMaxTex = i+1;
  122. continue;
  123. }
  124. // Check for a RenderTexTargetBin assignment
  125. if (filename.substr( 0, 1 ).equal("#"))
  126. {
  127. String texTargetBufferName = filename.substr(1, filename.length() - 1);
  128. NamedTexTarget *texTarget = NamedTexTarget::find( texTargetBufferName );
  129. rpd->mTexSlot[i].texTarget = texTarget;
  130. // Get the conditioner macros.
  131. if ( texTarget )
  132. texTarget->getShaderMacros( &mConditionerMacros );
  133. rpd->mTexType[i] = Material::TexTarget;
  134. mMaxTex = i+1;
  135. continue;
  136. }
  137. rpd->mTexSlot[i].texObject = _createTexture( filename, &GFXDefaultStaticDiffuseProfile );
  138. if ( !rpd->mTexSlot[i].texObject )
  139. {
  140. mMaterial->logError("Failed to load texture %s", _getTexturePath(filename).c_str());
  141. continue;
  142. }
  143. rpd->mTexType[i] = Material::Standard;
  144. mMaxTex = i+1;
  145. }
  146. // We only get one cubemap
  147. if( mCustomMaterial->mCubemapData )
  148. {
  149. mCustomMaterial->mCubemapData->createMap();
  150. rpd->mCubeMap = mMaterial->mCubemapData->mCubemap; // BTRTODO ?
  151. if ( !rpd->mCubeMap )
  152. mMaterial->logError("Failed to load cubemap");
  153. }
  154. // If this has a output target defined, it may be writing
  155. // to a tex target bin with a conditioner, so search for
  156. // one and add its macros.
  157. if ( mCustomMaterial->mOutputTarget.isNotEmpty() )
  158. {
  159. NamedTexTarget *texTarget = NamedTexTarget::find( mCustomMaterial->mOutputTarget );
  160. if ( texTarget )
  161. texTarget->getShaderMacros( &mConditionerMacros );
  162. }
  163. // Copy the glow state over.
  164. mHasGlow = mCustomMaterial->mGlow[0];
  165. }
  166. bool ProcessedCustomMaterial::init( const FeatureSet &features,
  167. const GFXVertexFormat *vertexFormat,
  168. const MatFeaturesDelegate &featuresDelegate )
  169. {
  170. // If we don't have a shader data... we have nothing to do.
  171. if ( !mCustomMaterial->mShaderData )
  172. return true;
  173. // Custom materials only do one pass at the moment... so
  174. // add one for the stage data to fill in.
  175. ShaderRenderPassData *rpd = new ShaderRenderPassData();
  176. mPasses.push_back( rpd );
  177. _setStageData();
  178. _initPassStateBlocks();
  179. mStateHint.clear();
  180. // Note: We don't use the vertex format in a custom
  181. // material at all right now.
  182. //
  183. // Maybe we can add some required semantics and
  184. // validate that the format fits the shader?
  185. // Build a composite list of shader macros from
  186. // the conditioner and the user defined lists.
  187. Vector<GFXShaderMacro> macros;
  188. macros.merge( mConditionerMacros );
  189. macros.merge( mUserMacros );
  190. // Ask the shader data to give us a shader instance.
  191. rpd->shader = mCustomMaterial->mShaderData->getShader( macros );
  192. if ( !rpd->shader )
  193. {
  194. delete rpd;
  195. mPasses.clear();
  196. return false;
  197. }
  198. rpd->shaderHandles.init( rpd->shader, mCustomMaterial );
  199. _initMaterialParameters();
  200. mDefaultParameters = allocMaterialParameters();
  201. setMaterialParameters( mDefaultParameters, 0 );
  202. mStateHint.init( this );
  203. return true;
  204. }
  205. void ProcessedCustomMaterial::_initPassStateBlock( RenderPassData *rpd, GFXStateBlockDesc &result )
  206. {
  207. Parent::_initPassStateBlock( rpd, result );
  208. if (mCustomMaterial->getStateBlockData())
  209. result.addDesc(mCustomMaterial->getStateBlockData()->getState());
  210. }
  211. void ProcessedCustomMaterial::_initPassStateBlocks()
  212. {
  213. AssertFatal(mHasSetStageData, "State data must be set before initializing state block!");
  214. ShaderRenderPassData* rpd = _getRPD(0);
  215. _initRenderStateStateBlocks( rpd );
  216. }
  217. bool ProcessedCustomMaterial::_hasCubemap(U32 pass)
  218. {
  219. // If the material doesn't have a cubemap, we don't
  220. if( mMaterial->mCubemapData ) return true;
  221. else return false;
  222. }
  223. bool ProcessedCustomMaterial::setupPass( SceneRenderState *state, const SceneData& sgData, U32 pass )
  224. {
  225. PROFILE_SCOPE( ProcessedCustomMaterial_SetupPass );
  226. // Make sure we have a pass.
  227. if ( pass >= mPasses.size() )
  228. return false;
  229. ShaderRenderPassData* rpd = _getRPD( pass );
  230. U32 currState = _getRenderStateIndex( state, sgData );
  231. GFX->setStateBlock(rpd->mRenderStates[currState]);
  232. // activate shader
  233. if ( rpd->shader )
  234. GFX->setShader( rpd->shader );
  235. else
  236. GFX->disableShaders();
  237. // Set our textures
  238. setTextureStages( state, sgData, pass );
  239. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  240. GFX->setShaderConstBuffer(shaderConsts);
  241. // Set our shader constants.
  242. _setTextureTransforms(pass);
  243. _setShaderConstants(state, sgData, pass);
  244. LightManager* lm = state ? LIGHTMGR : NULL;
  245. if (lm)
  246. lm->setLightInfo(this, NULL, sgData, state, pass, shaderConsts);
  247. shaderConsts->setSafe(rpd->shaderHandles.mAccumTimeSC, MATMGR->getTotalTime());
  248. return true;
  249. }
  250. void ProcessedCustomMaterial::setTextureStages( SceneRenderState *state, const SceneData &sgData, U32 pass )
  251. {
  252. LightManager* lm = state ? LIGHTMGR : NULL;
  253. ShaderRenderPassData* rpd = _getRPD(pass);
  254. ShaderConstHandles* handles = _getShaderConstHandles(pass);
  255. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  256. const NamedTexTarget *texTarget;
  257. GFXTextureObject *texObject;
  258. for( U32 i=0; i<mMaxTex; i++ )
  259. {
  260. U32 currTexFlag = rpd->mTexType[i];
  261. if ( !lm || !lm->setTextureStage(sgData, currTexFlag, i, shaderConsts, handles ) )
  262. {
  263. GFXShaderConstHandle* handle = handles->mTexHandlesSC[i];
  264. if ( !handle->isValid() )
  265. continue;
  266. S32 samplerRegister = handle->getSamplerRegister();
  267. switch( currTexFlag )
  268. {
  269. case 0:
  270. default:
  271. break;
  272. case Material::Mask:
  273. case Material::Standard:
  274. case Material::Bump:
  275. case Material::Detail:
  276. {
  277. GFX->setTexture( samplerRegister, rpd->mTexSlot[i].texObject );
  278. break;
  279. }
  280. case Material::Lightmap:
  281. {
  282. GFX->setTexture( samplerRegister, sgData.lightmap );
  283. break;
  284. }
  285. case Material::Cube:
  286. {
  287. GFX->setCubeTexture( samplerRegister, rpd->mCubeMap );
  288. break;
  289. }
  290. case Material::SGCube:
  291. {
  292. GFX->setCubeTexture( samplerRegister, sgData.cubemap );
  293. break;
  294. }
  295. case Material::BackBuff:
  296. {
  297. GFX->setTexture( samplerRegister, sgData.backBuffTex );
  298. //if ( sgData.reflectTex )
  299. // GFX->setTexture( samplerRegister, sgData.reflectTex );
  300. //else
  301. //{
  302. // GFXTextureObject *refractTex = REFLECTMGR->getRefractTex( true );
  303. // GFX->setTexture( samplerRegister, refractTex );
  304. //}
  305. break;
  306. }
  307. case Material::ReflectBuff:
  308. {
  309. GFX->setTexture( samplerRegister, sgData.reflectTex );
  310. break;
  311. }
  312. case Material::Misc:
  313. {
  314. GFX->setTexture( samplerRegister, sgData.miscTex );
  315. break;
  316. }
  317. case Material::TexTarget:
  318. {
  319. texTarget = rpd->mTexSlot[i].texTarget;
  320. if ( !texTarget )
  321. {
  322. GFX->setTexture( samplerRegister, NULL );
  323. break;
  324. }
  325. texObject = texTarget->getTexture();
  326. // If no texture is available then map the default 2x2
  327. // black texture to it. This at least will ensure that
  328. // we get consistant behavior across GPUs and platforms.
  329. if ( !texObject )
  330. texObject = GFXTexHandle::ZERO;
  331. if ( handles->mRTParamsSC[samplerRegister]->isValid() && texObject )
  332. {
  333. const Point3I &targetSz = texObject->getSize();
  334. const RectI &targetVp = texTarget->getViewport();
  335. Point4F rtParams;
  336. ScreenSpace::RenderTargetParameters(targetSz, targetVp, rtParams);
  337. shaderConsts->set(handles->mRTParamsSC[samplerRegister], rtParams);
  338. }
  339. GFX->setTexture( samplerRegister, texObject );
  340. break;
  341. }
  342. }
  343. }
  344. }
  345. }
  346. template <typename T>
  347. void ProcessedCustomMaterial::setMaterialParameter(MaterialParameters* param,
  348. MaterialParameterHandle* handle,
  349. const String& value)
  350. {
  351. T typedValue;
  352. if (PropertyInfo::default_scan(value, typedValue))
  353. {
  354. param->set(handle, typedValue);
  355. } else {
  356. Con::errorf("Error setting %s, parse error: %s", handle->getName().c_str(), value.c_str());
  357. }
  358. }
  359. void ProcessedCustomMaterial::setMatrixParameter(MaterialParameters* param,
  360. MaterialParameterHandle* handle,
  361. const String& value, GFXShaderConstType matrixType)
  362. {
  363. MatrixF result(true);
  364. F32* m = result;
  365. switch (matrixType)
  366. {
  367. case GFXSCT_Float2x2 :
  368. dSscanf(value.c_str(),"%g %g %g %g",
  369. m[result.idx(0,0)], m[result.idx(0,1)],
  370. m[result.idx(1,0)], m[result.idx(1,1)]);
  371. break;
  372. case GFXSCT_Float3x3 :
  373. dSscanf(value.c_str(),"%g %g %g %g %g %g %g %g %g",
  374. m[result.idx(0,0)], m[result.idx(0,1)], m[result.idx(0,2)],
  375. m[result.idx(1,0)], m[result.idx(1,1)], m[result.idx(1,2)],
  376. m[result.idx(2,0)], m[result.idx(2,1)], m[result.idx(2,2)]);
  377. break;
  378. default:
  379. AssertFatal(false, "Invalid type!");
  380. break;
  381. }
  382. }
  383. // BTRTODO: Support arrays!?
  384. MaterialParameters* ProcessedCustomMaterial::allocMaterialParameters()
  385. {
  386. MaterialParameters* ret = Parent::allocMaterialParameters();
  387. // See if any of the dynamic fields match up with shader constants we have.
  388. SimFieldDictionary* fields = mMaterial->getFieldDictionary();
  389. if (!fields || fields->getNumFields() == 0)
  390. return ret;
  391. const Vector<GFXShaderConstDesc>& consts = ret->getShaderConstDesc();
  392. for (U32 i = 0; i < consts.size(); i++)
  393. {
  394. // strip the dollar sign from the front.
  395. String stripped(consts[i].name);
  396. stripped.erase(0, 1);
  397. SimFieldDictionary::Entry* field = fields->findDynamicField(stripped);
  398. if (field)
  399. {
  400. MaterialParameterHandle* handle = getMaterialParameterHandle(consts[i].name);
  401. switch (consts[i].constType)
  402. {
  403. case GFXSCT_Float :
  404. setMaterialParameter<F32>(ret, handle, field->value);
  405. break;
  406. case GFXSCT_Float2:
  407. setMaterialParameter<Point2F>(ret, handle, field->value);
  408. break;
  409. case GFXSCT_Float3:
  410. setMaterialParameter<Point3F>(ret, handle, field->value);
  411. break;
  412. case GFXSCT_Float4:
  413. setMaterialParameter<Point4F>(ret, handle, field->value);
  414. break;
  415. case GFXSCT_Float2x2:
  416. case GFXSCT_Float3x3:
  417. setMatrixParameter(ret, handle, field->value, consts[i].constType);
  418. break;
  419. case GFXSCT_Float4x4:
  420. setMaterialParameter<MatrixF>(ret, handle, field->value);
  421. break;
  422. case GFXSCT_Int:
  423. setMaterialParameter<S32>(ret, handle, field->value);
  424. break;
  425. case GFXSCT_Int2:
  426. setMaterialParameter<Point2I>(ret, handle, field->value);
  427. break;
  428. case GFXSCT_Int3:
  429. setMaterialParameter<Point3I>(ret, handle, field->value);
  430. break;
  431. case GFXSCT_Int4:
  432. setMaterialParameter<Point4I>(ret, handle, field->value);
  433. break;
  434. // Do we want to ignore these?
  435. case GFXSCT_Sampler:
  436. case GFXSCT_SamplerCube:
  437. default:
  438. break;
  439. }
  440. }
  441. }
  442. return ret;
  443. }