processedCustomMaterial.cpp 16 KB

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