processedCustomMaterial.cpp 18 KB

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