processedCustomMaterial.cpp 18 KB

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