processedCustomMaterial.cpp 18 KB

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