processedShaderMaterial.cpp 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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/processedShaderMaterial.h"
  24. #include "core/util/safeDelete.h"
  25. #include "gfx/sim/cubemapData.h"
  26. #include "gfx/gfxShader.h"
  27. #include "gfx/genericConstBuffer.h"
  28. #include "gfx/gfxPrimitiveBuffer.h"
  29. #include "scene/sceneRenderState.h"
  30. #include "shaderGen/shaderFeature.h"
  31. #include "shaderGen/shaderGenVars.h"
  32. #include "shaderGen/featureMgr.h"
  33. #include "shaderGen/shaderGen.h"
  34. #include "materials/sceneData.h"
  35. #include "materials/materialFeatureTypes.h"
  36. #include "materials/materialManager.h"
  37. #include "materials/shaderMaterialParameters.h"
  38. #include "materials/matTextureTarget.h"
  39. #include "gfx/util/screenspace.h"
  40. #include "math/util/matrixSet.h"
  41. #include "renderInstance/renderProbeMgr.h"
  42. #include "ts/tsRenderState.h"
  43. // We need to include customMaterialDefinition for ShaderConstHandles::init
  44. #include "materials/customMaterialDefinition.h"
  45. #include "gui/controls/guiTreeViewCtrl.h"
  46. #include "ts/tsShape.h"
  47. ///
  48. /// ShaderConstHandles
  49. ///
  50. void ShaderConstHandles::init( GFXShader *shader, Vector<CustomShaderFeatureData*> customFeatureData, CustomMaterial* mat /*=NULL*/)
  51. {
  52. mDiffuseColorSC = shader->getShaderConstHandle("$diffuseMaterialColor");
  53. mTexMatSC = shader->getShaderConstHandle(ShaderGenVars::texMat);
  54. mToneMapTexSC = shader->getShaderConstHandle(ShaderGenVars::toneMap);
  55. mSpecularColorSC = shader->getShaderConstHandle(ShaderGenVars::specularColor);
  56. mSmoothnessSC = shader->getShaderConstHandle(ShaderGenVars::smoothness);
  57. mMetalnessSC = shader->getShaderConstHandle(ShaderGenVars::metalness);
  58. mAccuScaleSC = shader->getShaderConstHandle("$accuScale");
  59. mAccuDirectionSC = shader->getShaderConstHandle("$accuDirection");
  60. mAccuStrengthSC = shader->getShaderConstHandle("$accuStrength");
  61. mAccuCoverageSC = shader->getShaderConstHandle("$accuCoverage");
  62. mAccuSpecularSC = shader->getShaderConstHandle("$accuSpecular");
  63. mParallaxInfoSC = shader->getShaderConstHandle("$parallaxInfo");
  64. mFogDataSC = shader->getShaderConstHandle(ShaderGenVars::fogData);
  65. mFogColorSC = shader->getShaderConstHandle(ShaderGenVars::fogColor);
  66. mDetailScaleSC = shader->getShaderConstHandle(ShaderGenVars::detailScale);
  67. mVisiblitySC = shader->getShaderConstHandle(ShaderGenVars::visibility);
  68. mColorMultiplySC = shader->getShaderConstHandle(ShaderGenVars::colorMultiply);
  69. mAlphaTestValueSC = shader->getShaderConstHandle(ShaderGenVars::alphaTestValue);
  70. mModelViewProjSC = shader->getShaderConstHandle(ShaderGenVars::modelview);
  71. mWorldViewOnlySC = shader->getShaderConstHandle(ShaderGenVars::worldViewOnly);
  72. mWorldToCameraSC = shader->getShaderConstHandle(ShaderGenVars::worldToCamera);
  73. mCameraToWorldSC = shader->getShaderConstHandle(ShaderGenVars::cameraToWorld);
  74. mWorldToObjSC = shader->getShaderConstHandle(ShaderGenVars::worldToObj);
  75. mViewToObjSC = shader->getShaderConstHandle(ShaderGenVars::viewToObj);
  76. mCubeTransSC = shader->getShaderConstHandle(ShaderGenVars::cubeTrans);
  77. mCubeMipsSC = shader->getShaderConstHandle(ShaderGenVars::cubeMips);
  78. mObjTransSC = shader->getShaderConstHandle(ShaderGenVars::objTrans);
  79. mCubeEyePosSC = shader->getShaderConstHandle(ShaderGenVars::cubeEyePos);
  80. mEyePosSC = shader->getShaderConstHandle(ShaderGenVars::eyePos);
  81. mEyePosWorldSC = shader->getShaderConstHandle(ShaderGenVars::eyePosWorld);
  82. m_vEyeSC = shader->getShaderConstHandle(ShaderGenVars::vEye);
  83. mEyeMatSC = shader->getShaderConstHandle(ShaderGenVars::eyeMat);
  84. mOneOverFarplane = shader->getShaderConstHandle(ShaderGenVars::oneOverFarplane);
  85. mAccumTimeSC = shader->getShaderConstHandle(ShaderGenVars::accumTime);
  86. mMinnaertConstantSC = shader->getShaderConstHandle(ShaderGenVars::minnaertConstant);
  87. mSubSurfaceParamsSC = shader->getShaderConstHandle(ShaderGenVars::subSurfaceParams);
  88. mDiffuseAtlasParamsSC = shader->getShaderConstHandle(ShaderGenVars::diffuseAtlasParams);
  89. mDiffuseAtlasTileSC = shader->getShaderConstHandle(ShaderGenVars::diffuseAtlasTileParams);
  90. mBumpAtlasParamsSC = shader->getShaderConstHandle(ShaderGenVars::bumpAtlasParams);
  91. mBumpAtlasTileSC = shader->getShaderConstHandle(ShaderGenVars::bumpAtlasTileParams);
  92. mRTSizeSC = shader->getShaderConstHandle( "$targetSize" );
  93. mOneOverRTSizeSC = shader->getShaderConstHandle( "$oneOverTargetSize" );
  94. mDetailBumpStrength = shader->getShaderConstHandle( "$detailBumpStrength" );
  95. mViewProjSC = shader->getShaderConstHandle( "$viewProj" );
  96. // MFT_ImposterVert
  97. mImposterUVs = shader->getShaderConstHandle( "$imposterUVs" );
  98. mImposterLimits = shader->getShaderConstHandle( "$imposterLimits" );
  99. for (S32 i = 0; i < TEXTURE_STAGE_COUNT; ++i)
  100. mRTParamsSC[i] = shader->getShaderConstHandle( String::ToString( "$rtParams%d", i ) );
  101. // MFT_HardwareSkinning
  102. mNodeTransforms = shader->getShaderConstHandle( "$nodeTransforms" );
  103. // Clear any existing texture handles.
  104. dMemset( mTexHandlesSC, 0, sizeof( mTexHandlesSC ) );
  105. if(mat)
  106. {
  107. for (S32 i = 0; i < Material::MAX_TEX_PER_PASS; ++i)
  108. mTexHandlesSC[i] = shader->getShaderConstHandle(mat->mSamplerNames[i]);
  109. }
  110. // Deferred Shading
  111. mMatInfoFlagsSC = shader->getShaderConstHandle(ShaderGenVars::matInfoFlags);
  112. //custom features
  113. for (U32 f = 0; f < customFeatureData.size(); ++f)
  114. {
  115. for (U32 i = 0; i < customFeatureData[f]->mAddedShaderConstants.size(); ++i)
  116. {
  117. customHandleData newSC;
  118. newSC.handle = shader->getShaderConstHandle(String("$") + String(customFeatureData[f]->mAddedShaderConstants[i]));
  119. newSC.handleName = customFeatureData[f]->mAddedShaderConstants[i];
  120. mCustomHandles.push_back(newSC);
  121. }
  122. }
  123. }
  124. ///
  125. /// ShaderRenderPassData
  126. ///
  127. void ShaderRenderPassData::reset()
  128. {
  129. Parent::reset();
  130. shader = NULL;
  131. for ( U32 i=0; i < featureShaderHandles.size(); i++ )
  132. delete featureShaderHandles[i];
  133. featureShaderHandles.clear();
  134. }
  135. String ShaderRenderPassData::describeSelf() const
  136. {
  137. // First write the shader identification.
  138. String desc = String::ToString( "%s\n", shader->describeSelf().c_str() );
  139. // Let the parent get the rest.
  140. desc += Parent::describeSelf();
  141. return desc;
  142. }
  143. ///
  144. /// ProcessedShaderMaterial
  145. ///
  146. ProcessedShaderMaterial::ProcessedShaderMaterial()
  147. : mDefaultParameters( NULL ),
  148. mInstancingState( NULL )
  149. {
  150. VECTOR_SET_ASSOCIATION( mShaderConstDesc );
  151. VECTOR_SET_ASSOCIATION( mParameterHandles );
  152. }
  153. ProcessedShaderMaterial::ProcessedShaderMaterial(Material &mat)
  154. : mDefaultParameters( NULL ),
  155. mInstancingState( NULL )
  156. {
  157. VECTOR_SET_ASSOCIATION( mShaderConstDesc );
  158. VECTOR_SET_ASSOCIATION( mParameterHandles );
  159. mMaterial = &mat;
  160. }
  161. ProcessedShaderMaterial::~ProcessedShaderMaterial()
  162. {
  163. SAFE_DELETE(mInstancingState);
  164. SAFE_DELETE(mDefaultParameters);
  165. for (U32 i = 0; i < mParameterHandles.size(); i++)
  166. SAFE_DELETE(mParameterHandles[i]);
  167. }
  168. //
  169. // Material init
  170. //
  171. bool ProcessedShaderMaterial::init( const FeatureSet &features,
  172. const GFXVertexFormat *vertexFormat,
  173. const MatFeaturesDelegate &featuresDelegate )
  174. {
  175. // Load our textures
  176. _setStageData();
  177. // Determine how many stages we use
  178. mMaxStages = getNumStages();
  179. mVertexFormat = vertexFormat;
  180. mFeatures.clear();
  181. mStateHint.clear();
  182. SAFE_DELETE(mInstancingState);
  183. for( U32 i=0; i<mMaxStages; i++ )
  184. {
  185. MaterialFeatureData fd;
  186. // Determine the features of this stage
  187. _determineFeatures( i, fd, features );
  188. // Let the delegate poke at the features.
  189. if ( featuresDelegate )
  190. featuresDelegate( this, i, fd, features );
  191. // Create the passes for this stage
  192. if ( fd.features.isNotEmpty() )
  193. if( !_createPasses( fd, i, features ) )
  194. return false;
  195. }
  196. _initRenderPassDataStateBlocks();
  197. _initMaterialParameters();
  198. mDefaultParameters = allocMaterialParameters();
  199. setMaterialParameters( mDefaultParameters, 0 );
  200. mStateHint.init( this );
  201. // Enable instancing if we have it.
  202. if ( mFeatures.hasFeature( MFT_UseInstancing ) )
  203. {
  204. mInstancingState = new InstancingState();
  205. mInstancingState->setFormat( _getRPD( 0 )->shader->getInstancingFormat(), mVertexFormat );
  206. }
  207. if (mMaterial && mMaterial->mDiffuseMapFilename[0].isNotEmpty() && mMaterial->mDiffuseMapFilename[0].substr(0, 1).equal("#"))
  208. {
  209. String texTargetBufferName = mMaterial->mDiffuseMapFilename[0].substr(1, mMaterial->mDiffuseMapFilename[0].length() - 1);
  210. NamedTexTarget *texTarget = NamedTexTarget::find(texTargetBufferName);
  211. RenderPassData* rpd = getPass(0);
  212. if (rpd)
  213. {
  214. rpd->mTexSlot[0].texTarget = texTarget;
  215. rpd->mTexType[0] = Material::TexTarget;
  216. rpd->mSamplerNames[0] = "diffuseMap";
  217. }
  218. }
  219. return true;
  220. }
  221. U32 ProcessedShaderMaterial::getNumStages()
  222. {
  223. // Loops through all stages to determine how many
  224. // stages we actually use.
  225. //
  226. // The first stage is always active else we shouldn't be
  227. // creating the material to begin with.
  228. U32 numStages = 1;
  229. U32 i;
  230. for( i=1; i<Material::MAX_STAGES; i++ )
  231. {
  232. // Assume stage is inactive
  233. bool stageActive = false;
  234. // Cubemaps only on first stage
  235. if( i == 0 )
  236. {
  237. // If we have a cubemap the stage is active
  238. if( mMaterial->mCubemapData || mMaterial->mDynamicCubemap )
  239. {
  240. numStages++;
  241. continue;
  242. }
  243. }
  244. // If we have a texture for the a feature the
  245. // stage is active.
  246. if ( mStages[i].hasValidTex() )
  247. stageActive = true;
  248. // If this stage has diffuse color, it's active
  249. if ( mMaterial->mDiffuse[i].alpha > 0 &&
  250. mMaterial->mDiffuse[i] != LinearColorF::WHITE )
  251. stageActive = true;
  252. // If we have a Material that is vertex lit
  253. // then it may not have a texture
  254. if( mMaterial->mVertLit[i] )
  255. stageActive = true;
  256. // Increment the number of active stages
  257. numStages += stageActive;
  258. }
  259. return numStages;
  260. }
  261. void ProcessedShaderMaterial::_determineFeatures( U32 stageNum,
  262. MaterialFeatureData &fd,
  263. const FeatureSet &features )
  264. {
  265. PROFILE_SCOPE( ProcessedShaderMaterial_DetermineFeatures );
  266. const F32 shaderVersion = GFX->getPixelShaderVersion();
  267. AssertFatal(shaderVersion > 0.0 , "Cannot create a shader material if we don't support shaders");
  268. bool lastStage = stageNum == (mMaxStages-1);
  269. // First we add all the features which the
  270. // material has defined.
  271. if (mMaterial->mInvertSmoothness[stageNum])
  272. fd.features.addFeature(MFT_InvertSmoothness);
  273. if ( mMaterial->isTranslucent() )
  274. {
  275. // Note: This is for decal blending into the deferred
  276. // for AL... it probably needs to be made clearer.
  277. if ( mMaterial->mTranslucentBlendOp == Material::LerpAlpha &&
  278. mMaterial->mTranslucentZWrite )
  279. fd.features.addFeature( MFT_IsTranslucentZWrite );
  280. else
  281. {
  282. fd.features.addFeature( MFT_IsTranslucent );
  283. fd.features.addFeature( MFT_ForwardShading );
  284. }
  285. }
  286. // TODO: This sort of sucks... BL should somehow force this
  287. // feature on from the outside and not this way.
  288. if ( dStrcmp( LIGHTMGR->getId(), "BLM" ) == 0 )
  289. fd.features.addFeature( MFT_ForwardShading );
  290. // Disabling the InterlacedDeferred feature for now. It is not ready for prime-time
  291. // and it should not be triggered off of the DoubleSided parameter. [2/5/2010 Pat]
  292. /*if ( mMaterial->isDoubleSided() )
  293. {
  294. fd.features.addFeature( MFT_InterlacedDeferred );
  295. }*/
  296. // Allow instancing if it was requested and the card supports
  297. // SM 3.0 or above.
  298. //
  299. // We also disable instancing for non-single pass materials
  300. // and glowing materials because its untested/unimplemented.
  301. //
  302. if ( features.hasFeature( MFT_UseInstancing ) &&
  303. mMaxStages == 1 &&
  304. !mMaterial->mGlow[0] &&
  305. shaderVersion >= 3.0f )
  306. fd.features.addFeature( MFT_UseInstancing );
  307. if ( mMaterial->mAlphaTest )
  308. fd.features.addFeature( MFT_AlphaTest );
  309. if (mMaterial->mEmissive[stageNum])
  310. {
  311. fd.features.addFeature(MFT_IsEmissive);
  312. }
  313. else
  314. {
  315. fd.features.addFeature(MFT_RTLighting);
  316. if (mMaterial->isTranslucent())
  317. fd.features.addFeature(MFT_ReflectionProbes);
  318. }
  319. if ( mMaterial->mAnimFlags[stageNum] )
  320. fd.features.addFeature( MFT_TexAnim );
  321. if ( mMaterial->mVertLit[stageNum] )
  322. fd.features.addFeature( MFT_VertLit );
  323. // cubemaps only available on stage 0 for now - bramage
  324. if ( stageNum < 1 && mMaterial->isTranslucent() &&
  325. ( ( mMaterial->mCubemapData && mMaterial->mCubemapData->mCubemap ) ||
  326. mMaterial->mDynamicCubemap ) && !features.hasFeature(MFT_ReflectionProbes))
  327. {
  328. fd.features.addFeature( MFT_CubeMap );
  329. }
  330. if (features.hasFeature(MFT_SkyBox))
  331. {
  332. fd.features.addFeature(MFT_StaticCubemap);
  333. fd.features.addFeature(MFT_CubeMap);
  334. fd.features.addFeature(MFT_SkyBox);
  335. fd.features.removeFeature(MFT_ReflectionProbes);
  336. }
  337. fd.features.addFeature( MFT_Visibility );
  338. if ( lastStage &&
  339. ( !gClientSceneGraph->usePostEffectFog() ||
  340. fd.features.hasFeature( MFT_IsTranslucent ) ||
  341. fd.features.hasFeature( MFT_ForwardShading )) )
  342. fd.features.addFeature( MFT_Fog );
  343. if ( mMaterial->mMinnaertConstant[stageNum] > 0.0f )
  344. fd.features.addFeature( MFT_MinnaertShading );
  345. if ( mMaterial->mSubSurface[stageNum] )
  346. fd.features.addFeature( MFT_SubSurface );
  347. if ( !mMaterial->mCellLayout[stageNum].isZero() )
  348. {
  349. fd.features.addFeature( MFT_DiffuseMapAtlas );
  350. if ( mMaterial->mNormalMapAtlas )
  351. fd.features.addFeature( MFT_NormalMapAtlas );
  352. }
  353. // Grab other features like normal maps, base texture, etc.
  354. FeatureSet mergeFeatures;
  355. mStages[stageNum].getFeatureSet( &mergeFeatures );
  356. fd.features.merge( mergeFeatures );
  357. if ( fd.features[ MFT_NormalMap ] )
  358. {
  359. if ( mStages[stageNum].getTex( MFT_NormalMap )->mFormat == GFXFormatBC3 &&
  360. !mStages[stageNum].getTex( MFT_NormalMap )->mHasTransparency )
  361. fd.features.addFeature( MFT_IsBC3nm );
  362. else if ( mStages[stageNum].getTex(MFT_NormalMap)->mFormat == GFXFormatBC5 &&
  363. !mStages[stageNum].getTex(MFT_NormalMap)->mHasTransparency )
  364. fd.features.addFeature( MFT_IsBC5nm );
  365. }
  366. // Now for some more advanced features that we
  367. // cannot do on SM 2.0 and below.
  368. if ( shaderVersion > 2.0f )
  369. {
  370. if ( mMaterial->mParallaxScale[stageNum] > 0.0f &&
  371. fd.features[ MFT_NormalMap ] )
  372. fd.features.addFeature( MFT_Parallax );
  373. }
  374. // Without realtime lighting and on lower end
  375. // shader models disable the specular map.
  376. if ( !fd.features[ MFT_RTLighting ] || shaderVersion == 2.0 )
  377. fd.features.removeFeature( MFT_SpecularMap );
  378. // If we have a specular map then make sure we
  379. // have per-pixel specular enabled.
  380. if( fd.features[ MFT_SpecularMap ] )
  381. {
  382. // Check for an alpha channel on the specular map. If it has one (and it
  383. // has values less than 255) than the artist has put the gloss map into
  384. // the alpha channel.
  385. if( mStages[stageNum].getTex( MFT_SpecularMap )->mHasTransparency )
  386. fd.features.addFeature( MFT_GlossMap );
  387. }
  388. if ( mMaterial->mAccuEnabled[stageNum] )
  389. {
  390. mHasAccumulation = true;
  391. }
  392. // we need both diffuse and normal maps + sm3 to have an accu map
  393. if( fd.features[ MFT_AccuMap ] &&
  394. ( !fd.features[ MFT_DiffuseMap ] ||
  395. !fd.features[ MFT_NormalMap ] ||
  396. GFX->getPixelShaderVersion() < 3.0f ) ) {
  397. AssertWarn(false, "SAHARA: Using an Accu Map requires SM 3.0 and a normal map.");
  398. fd.features.removeFeature( MFT_AccuMap );
  399. mHasAccumulation = false;
  400. }
  401. // Without a base texture use the diffuse color
  402. // feature to ensure some sort of output.
  403. if (!fd.features[MFT_DiffuseMap])
  404. {
  405. fd.features.addFeature( MFT_DiffuseColor );
  406. // No texture coords... no overlay.
  407. fd.features.removeFeature( MFT_OverlayMap );
  408. }
  409. // If we have a diffuse map and the alpha on the diffuse isn't
  410. // zero and the color isn't pure white then multiply the color.
  411. else if ( mMaterial->mDiffuse[stageNum].alpha > 0.0f &&
  412. mMaterial->mDiffuse[stageNum] != LinearColorF::WHITE )
  413. fd.features.addFeature( MFT_DiffuseColor );
  414. // If lightmaps or tonemaps are enabled or we
  415. // don't have a second UV set then we cannot
  416. // use the overlay texture.
  417. if ( fd.features[MFT_LightMap] ||
  418. fd.features[MFT_ToneMap] ||
  419. mVertexFormat->getTexCoordCount() < 2 )
  420. fd.features.removeFeature( MFT_OverlayMap );
  421. // If tonemaps are enabled don't use lightmap
  422. if ( fd.features[MFT_ToneMap] || mVertexFormat->getTexCoordCount() < 2 )
  423. fd.features.removeFeature( MFT_LightMap );
  424. // Don't allow tonemaps if we don't have a second UV set
  425. if ( mVertexFormat->getTexCoordCount() < 2 )
  426. fd.features.removeFeature( MFT_ToneMap );
  427. // Always add the HDR output feature.
  428. //
  429. // It will be filtered out if it was disabled
  430. // for this material creation below.
  431. //
  432. // Also the shader code will evaluate to a nop
  433. // if HDR is not enabled in the scene.
  434. //
  435. fd.features.addFeature( MFT_HDROut );
  436. // If vertex color is enabled on the material's stage and
  437. // color is present in vertex format, add diffuse vertex
  438. // color feature.
  439. if ( mMaterial->mVertColor[ stageNum ] &&
  440. mVertexFormat->hasColor() )
  441. fd.features.addFeature( MFT_DiffuseVertColor );
  442. // Allow features to add themselves.
  443. for ( U32 i = 0; i < FEATUREMGR->getFeatureCount(); i++ )
  444. {
  445. const FeatureInfo &info = FEATUREMGR->getAt( i );
  446. info.feature->determineFeature( mMaterial,
  447. mVertexFormat,
  448. stageNum,
  449. *info.type,
  450. features,
  451. &fd );
  452. }
  453. // Need to add the Hardware Skinning feature if its used
  454. if ( features.hasFeature( MFT_HardwareSkinning ) )
  455. {
  456. fd.features.addFeature( MFT_HardwareSkinning );
  457. }
  458. // Now disable any features that were
  459. // not part of the input feature handle.
  460. fd.features.filter( features );
  461. }
  462. bool ProcessedShaderMaterial::_createPasses( MaterialFeatureData &stageFeatures, U32 stageNum, const FeatureSet &features )
  463. {
  464. // Creates passes for the given stage
  465. ShaderRenderPassData passData;
  466. U32 texIndex = 0;
  467. for( U32 featureIDx=0; featureIDx < FEATUREMGR->getFeatureCount(); featureIDx++ )
  468. {
  469. const FeatureInfo &info = FEATUREMGR->getAt(featureIDx);
  470. if ( !stageFeatures.features.hasFeature( *info.type ) )
  471. continue;
  472. U32 numTexReg = info.feature->getResources( stageFeatures ).numTexReg;
  473. // adds pass if blend op changes for feature
  474. _setPassBlendOp( info.feature, passData, texIndex, stageFeatures, stageNum, features );
  475. // Add pass if num tex reg is going to be too high
  476. if( passData.mNumTexReg + numTexReg > GFX->getNumSamplers() )
  477. {
  478. if( !_addPass( passData, texIndex, stageFeatures, stageNum, features ) )
  479. return false;
  480. _setPassBlendOp( info.feature, passData, texIndex, stageFeatures, stageNum, features );
  481. }
  482. passData.mNumTexReg += numTexReg;
  483. passData.mFeatureData.features.addFeature( *info.type );
  484. #if defined(TORQUE_DEBUG) && defined( TORQUE_OPENGL)
  485. U32 oldTexNumber = texIndex;
  486. #endif
  487. info.feature->setTexData( mStages[stageNum], stageFeatures, passData, texIndex );
  488. #if defined(TORQUE_DEBUG) && defined( TORQUE_OPENGL)
  489. if(oldTexNumber != texIndex)
  490. {
  491. for(int texNum = oldTexNumber; texNum < texIndex; texNum++)
  492. {
  493. AssertFatal(passData.mSamplerNames[ oldTexNumber ].isNotEmpty(), avar( "ERROR: ShaderGen feature %s don't set used sampler name", info.feature->getName().c_str()) );
  494. }
  495. }
  496. #endif
  497. // Add pass if tex units are maxed out
  498. if( texIndex > GFX->getNumSamplers() )
  499. {
  500. if( !_addPass( passData, texIndex, stageFeatures, stageNum, features ) )
  501. return false;
  502. _setPassBlendOp( info.feature, passData, texIndex, stageFeatures, stageNum, features );
  503. }
  504. }
  505. #if defined(TORQUE_DEBUG) && defined( TORQUE_OPENGL)
  506. for(int samplerIDx = 0; samplerIDx < texIndex; samplerIDx++)
  507. {
  508. AssertFatal(passData.mSamplerNames[samplerIDx].isNotEmpty(),"");
  509. }
  510. #endif
  511. const FeatureSet &passFeatures = passData.mFeatureData.codify();
  512. if ( passFeatures.isNotEmpty() )
  513. {
  514. mFeatures.merge( passFeatures );
  515. if( !_addPass( passData, texIndex, stageFeatures, stageNum, features ) )
  516. {
  517. mFeatures.clear();
  518. return false;
  519. }
  520. }
  521. return true;
  522. }
  523. void ProcessedShaderMaterial::_initMaterialParameters()
  524. {
  525. // Cleanup anything left first.
  526. SAFE_DELETE( mDefaultParameters );
  527. for ( U32 i = 0; i < mParameterHandles.size(); i++ )
  528. SAFE_DELETE( mParameterHandles[i] );
  529. // Gather the shaders as they all need to be
  530. // passed to the ShaderMaterialParameterHandles.
  531. Vector<GFXShader*> shaders;
  532. shaders.setSize( mPasses.size() );
  533. for ( U32 i = 0; i < mPasses.size(); i++ )
  534. shaders[i] = _getRPD(i)->shader;
  535. // Run through each shader and prepare its constants.
  536. for ( U32 i = 0; i < mPasses.size(); i++ )
  537. {
  538. const Vector<GFXShaderConstDesc>& desc = shaders[i]->getShaderConstDesc();
  539. Vector<GFXShaderConstDesc>::const_iterator p = desc.begin();
  540. for ( ; p != desc.end(); p++ )
  541. {
  542. // Add this to our list of shader constants
  543. GFXShaderConstDesc d(*p);
  544. mShaderConstDesc.push_back(d);
  545. ShaderMaterialParameterHandle* smph = new ShaderMaterialParameterHandle(d.name, shaders);
  546. mParameterHandles.push_back(smph);
  547. }
  548. }
  549. }
  550. bool ProcessedShaderMaterial::_addPass( ShaderRenderPassData &rpd,
  551. U32 &texIndex,
  552. MaterialFeatureData &fd,
  553. U32 stageNum,
  554. const FeatureSet &features )
  555. {
  556. // Set number of textures, stage, glow, etc.
  557. rpd.mNumTex = texIndex;
  558. rpd.mStageNum = stageNum;
  559. rpd.mGlow |= mMaterial->mGlow[stageNum];
  560. // Copy over features
  561. rpd.mFeatureData.materialFeatures = fd.features;
  562. Vector<String> samplers;
  563. samplers.setSize(Material::MAX_TEX_PER_PASS);
  564. for(int i = 0; i < Material::MAX_TEX_PER_PASS; ++i)
  565. {
  566. samplers[i] = (rpd.mSamplerNames[i].isEmpty() || rpd.mSamplerNames[i][0] == '$') ? rpd.mSamplerNames[i] : "$" + rpd.mSamplerNames[i];
  567. }
  568. // Generate shader
  569. GFXShader::setLogging( true, true );
  570. rpd.shader = SHADERGEN->getShader( rpd.mFeatureData, mMaterial->mCustomShaderFeatures, mVertexFormat, &mUserMacros, samplers );
  571. if( !rpd.shader )
  572. return false;
  573. rpd.shaderHandles.init( rpd.shader, mMaterial->mCustomShaderFeatures);
  574. // If a pass glows, we glow
  575. if( rpd.mGlow )
  576. mHasGlow = true;
  577. ShaderRenderPassData *newPass = new ShaderRenderPassData( rpd );
  578. mPasses.push_back( newPass );
  579. //initSamplerHandles
  580. ShaderConstHandles *handles = _getShaderConstHandles( mPasses.size()-1 );
  581. AssertFatal(handles,"");
  582. for(int i = 0; i < rpd.mNumTex; i++)
  583. {
  584. if(rpd.mSamplerNames[i].isEmpty())
  585. {
  586. handles->mTexHandlesSC[i] = newPass->shader->getShaderConstHandle( String::EmptyString );
  587. handles->mRTParamsSC[i] = newPass->shader->getShaderConstHandle( String::EmptyString );
  588. continue;
  589. }
  590. String samplerName = rpd.mSamplerNames[i];
  591. if( !samplerName.startsWith("$"))
  592. samplerName.insert(0, "$");
  593. GFXShaderConstHandle *handle = newPass->shader->getShaderConstHandle( samplerName );
  594. handles->mTexHandlesSC[i] = handle;
  595. handles->mRTParamsSC[i] = newPass->shader->getShaderConstHandle( String::ToString( "$rtParams%s", samplerName.c_str()+1 ) );
  596. AssertFatal( handle,"");
  597. }
  598. // Give each active feature a chance to create specialized shader consts.
  599. for( U32 i=0; i < FEATUREMGR->getFeatureCount(); i++ )
  600. {
  601. const FeatureInfo &info = FEATUREMGR->getAt( i );
  602. if ( !fd.features.hasFeature( *info.type ) )
  603. continue;
  604. ShaderFeatureConstHandles *fh = info.feature->createConstHandles( rpd.shader, mUserObject );
  605. if ( fh )
  606. newPass->featureShaderHandles.push_back( fh );
  607. }
  608. rpd.reset();
  609. texIndex = 0;
  610. return true;
  611. }
  612. void ProcessedShaderMaterial::_setPassBlendOp( ShaderFeature *sf,
  613. ShaderRenderPassData &passData,
  614. U32 &texIndex,
  615. MaterialFeatureData &stageFeatures,
  616. U32 stageNum,
  617. const FeatureSet &features )
  618. {
  619. if( sf->getBlendOp() == Material::None )
  620. {
  621. return;
  622. }
  623. // set up the current blend operation for multi-pass materials
  624. if( mPasses.size() > 0)
  625. {
  626. // If passData.numTexReg is 0, this is a brand new pass, so set the
  627. // blend operation to the first feature.
  628. if( passData.mNumTexReg == 0 )
  629. {
  630. passData.mBlendOp = sf->getBlendOp();
  631. }
  632. else
  633. {
  634. // numTegReg is more than zero, if this feature
  635. // doesn't have the same blend operation, then
  636. // we need to create yet another pass
  637. if( sf->getBlendOp() != passData.mBlendOp && mPasses[mPasses.size()-1]->mStageNum == stageNum)
  638. {
  639. _addPass( passData, texIndex, stageFeatures, stageNum, features );
  640. passData.mBlendOp = sf->getBlendOp();
  641. }
  642. }
  643. }
  644. }
  645. //
  646. // Runtime / rendering
  647. //
  648. bool ProcessedShaderMaterial::setupPass( SceneRenderState *state, const SceneData &sgData, U32 pass )
  649. {
  650. PROFILE_SCOPE( ProcessedShaderMaterial_SetupPass );
  651. // Make sure we have the pass
  652. if(pass >= mPasses.size())
  653. {
  654. // If we were rendering instanced data tell
  655. // the device to reset that vb stream.
  656. if ( mInstancingState )
  657. GFX->setVertexBuffer( NULL, 1 );
  658. return false;
  659. }
  660. _setRenderState( state, sgData, pass );
  661. // Set shaders
  662. ShaderRenderPassData* rpd = _getRPD(pass);
  663. if( rpd->shader )
  664. {
  665. GFX->setShader( rpd->shader );
  666. GFX->setShaderConstBuffer(_getShaderConstBuffer(pass));
  667. _setShaderConstants(state, sgData, pass);
  668. // If we're instancing then do the initial step to get
  669. // set the vb pointer to the const buffer.
  670. if ( mInstancingState )
  671. stepInstance();
  672. }
  673. else
  674. {
  675. GFX->setupGenericShaders();
  676. GFX->setShaderConstBuffer(NULL);
  677. }
  678. // Set our textures
  679. setTextureStages( state, sgData, pass );
  680. _setTextureTransforms(pass);
  681. return true;
  682. }
  683. void ProcessedShaderMaterial::setTextureStages( SceneRenderState *state, const SceneData &sgData, U32 pass )
  684. {
  685. PROFILE_SCOPE( ProcessedShaderMaterial_SetTextureStages );
  686. ShaderConstHandles *handles = _getShaderConstHandles(pass);
  687. AssertFatal(handles,"");
  688. // Set all of the textures we need to render the give pass.
  689. #ifdef TORQUE_DEBUG
  690. AssertFatal( pass<mPasses.size(), "Pass out of bounds" );
  691. #endif
  692. RenderPassData *rpd = mPasses[pass];
  693. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  694. NamedTexTarget *texTarget;
  695. GFXTextureObject *texObject;
  696. for( U32 i=0; i<rpd->mNumTex; i++ )
  697. {
  698. U32 currTexFlag = rpd->mTexType[i];
  699. if (!LIGHTMGR || !LIGHTMGR->setTextureStage(sgData, currTexFlag, i, shaderConsts, handles))
  700. {
  701. switch( currTexFlag )
  702. {
  703. // If the flag is unset then assume its just
  704. // a regular texture to set... nothing special.
  705. case 0:
  706. default:
  707. GFX->setTexture(i, rpd->mTexSlot[i].texObject);
  708. break;
  709. case Material::NormalizeCube:
  710. GFX->setCubeTexture(i, Material::GetNormalizeCube());
  711. break;
  712. case Material::Lightmap:
  713. GFX->setTexture( i, sgData.lightmap );
  714. break;
  715. case Material::ToneMapTex:
  716. shaderConsts->setSafe(handles->mToneMapTexSC, (S32)i);
  717. GFX->setTexture(i, rpd->mTexSlot[i].texObject);
  718. break;
  719. case Material::Cube:
  720. GFX->setCubeTexture( i, rpd->mCubeMap );
  721. break;
  722. case Material::SGCube:
  723. GFX->setCubeTexture( i, sgData.cubemap );
  724. break;
  725. case Material::BackBuff:
  726. GFX->setTexture( i, sgData.backBuffTex );
  727. break;
  728. case Material::AccuMap:
  729. if ( sgData.accuTex )
  730. GFX->setTexture( i, sgData.accuTex );
  731. else
  732. GFX->setTexture( i, GFXTexHandle::ZERO );
  733. break;
  734. case Material::TexTarget:
  735. {
  736. texTarget = rpd->mTexSlot[i].texTarget;
  737. if ( !texTarget )
  738. {
  739. GFX->setTexture( i, NULL );
  740. break;
  741. }
  742. texObject = texTarget->getTexture();
  743. // If no texture is available then map the default 2x2
  744. // black texture to it. This at least will ensure that
  745. // we get consistant behavior across GPUs and platforms.
  746. if ( !texObject )
  747. texObject = GFXTexHandle::ZERO;
  748. if ( handles->mRTParamsSC[i]->isValid() && texObject )
  749. {
  750. const Point3I &targetSz = texObject->getSize();
  751. const RectI &targetVp = texTarget->getViewport();
  752. Point4F rtParams;
  753. ScreenSpace::RenderTargetParameters(targetSz, targetVp, rtParams);
  754. shaderConsts->set(handles->mRTParamsSC[i], rtParams);
  755. }
  756. GFX->setTexture( i, texObject );
  757. break;
  758. }
  759. }
  760. }
  761. }
  762. }
  763. void ProcessedShaderMaterial::_setTextureTransforms(const U32 pass)
  764. {
  765. PROFILE_SCOPE( ProcessedShaderMaterial_SetTextureTransforms );
  766. ShaderConstHandles* handles = _getShaderConstHandles(pass);
  767. if (handles->mTexMatSC->isValid())
  768. {
  769. MatrixF texMat( true );
  770. mMaterial->updateTimeBasedParams();
  771. F32 waveOffset = _getWaveOffset( pass ); // offset is between 0.0 and 1.0
  772. // handle scroll anim type
  773. if( mMaterial->mAnimFlags[pass] & Material::Scroll )
  774. {
  775. if( mMaterial->mAnimFlags[pass] & Material::Wave )
  776. {
  777. Point3F scrollOffset;
  778. scrollOffset.x = mMaterial->mScrollDir[pass].x * waveOffset;
  779. scrollOffset.y = mMaterial->mScrollDir[pass].y * waveOffset;
  780. scrollOffset.z = 1.0;
  781. texMat.setColumn( 3, scrollOffset );
  782. }
  783. else
  784. {
  785. Point3F offset( mMaterial->mScrollOffset[pass].x,
  786. mMaterial->mScrollOffset[pass].y,
  787. 1.0 );
  788. texMat.setColumn( 3, offset );
  789. }
  790. }
  791. // handle rotation
  792. if( mMaterial->mAnimFlags[pass] & Material::Rotate )
  793. {
  794. if( mMaterial->mAnimFlags[pass] & Material::Wave )
  795. {
  796. F32 rotPos = waveOffset * M_2PI;
  797. texMat.set( EulerF( 0.0, 0.0, rotPos ) );
  798. texMat.setColumn( 3, Point3F( 0.5, 0.5, 0.0 ) );
  799. MatrixF test( true );
  800. test.setColumn( 3, Point3F( mMaterial->mRotPivotOffset[pass].x,
  801. mMaterial->mRotPivotOffset[pass].y,
  802. 0.0 ) );
  803. texMat.mul( test );
  804. }
  805. else
  806. {
  807. texMat.set( EulerF( 0.0, 0.0, mMaterial->mRotPos[pass] ) );
  808. texMat.setColumn( 3, Point3F( 0.5, 0.5, 0.0 ) );
  809. MatrixF test( true );
  810. test.setColumn( 3, Point3F( mMaterial->mRotPivotOffset[pass].x,
  811. mMaterial->mRotPivotOffset[pass].y,
  812. 0.0 ) );
  813. texMat.mul( test );
  814. }
  815. }
  816. // Handle scale + wave offset
  817. if( mMaterial->mAnimFlags[pass] & Material::Scale &&
  818. mMaterial->mAnimFlags[pass] & Material::Wave )
  819. {
  820. F32 wOffset = fabs( waveOffset );
  821. texMat.setColumn( 3, Point3F( 0.5, 0.5, 0.0 ) );
  822. MatrixF temp( true );
  823. temp.setRow( 0, Point3F( wOffset, 0.0, 0.0 ) );
  824. temp.setRow( 1, Point3F( 0.0, wOffset, 0.0 ) );
  825. temp.setRow( 2, Point3F( 0.0, 0.0, wOffset ) );
  826. temp.setColumn( 3, Point3F( -wOffset * 0.5, -wOffset * 0.5, 0.0 ) );
  827. texMat.mul( temp );
  828. }
  829. // handle sequence
  830. if( mMaterial->mAnimFlags[pass] & Material::Sequence )
  831. {
  832. U32 frameNum = (U32)(MATMGR->getTotalTime() * mMaterial->mSeqFramePerSec[pass]);
  833. F32 offset = frameNum * mMaterial->mSeqSegSize[pass];
  834. if ( mMaterial->mAnimFlags[pass] & Material::Scale )
  835. texMat.scale( Point3F( mMaterial->mSeqSegSize[pass], 1.0f, 1.0f ) );
  836. Point3F texOffset = texMat.getPosition();
  837. texOffset.x += offset;
  838. texMat.setPosition( texOffset );
  839. }
  840. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  841. shaderConsts->setSafe(handles->mTexMatSC, texMat);
  842. }
  843. }
  844. //--------------------------------------------------------------------------
  845. // Get wave offset for texture animations using a wave transform
  846. //--------------------------------------------------------------------------
  847. F32 ProcessedShaderMaterial::_getWaveOffset( U32 stage )
  848. {
  849. switch( mMaterial->mWaveType[stage] )
  850. {
  851. case Material::Sin:
  852. {
  853. return mMaterial->mWaveAmp[stage] * mSin( M_2PI * mMaterial->mWavePos[stage] );
  854. break;
  855. }
  856. case Material::Triangle:
  857. {
  858. F32 frac = mMaterial->mWavePos[stage] - mFloor( mMaterial->mWavePos[stage] );
  859. if( frac > 0.0 && frac <= 0.25 )
  860. {
  861. return mMaterial->mWaveAmp[stage] * frac * 4.0;
  862. }
  863. if( frac > 0.25 && frac <= 0.5 )
  864. {
  865. return mMaterial->mWaveAmp[stage] * ( 1.0 - ((frac-0.25)*4.0) );
  866. }
  867. if( frac > 0.5 && frac <= 0.75 )
  868. {
  869. return mMaterial->mWaveAmp[stage] * (frac-0.5) * -4.0;
  870. }
  871. if( frac > 0.75 && frac <= 1.0 )
  872. {
  873. return -mMaterial->mWaveAmp[stage] * ( 1.0 - ((frac-0.75)*4.0) );
  874. }
  875. break;
  876. }
  877. case Material::Square:
  878. {
  879. F32 frac = mMaterial->mWavePos[stage] - mFloor( mMaterial->mWavePos[stage] );
  880. if( frac > 0.0 && frac <= 0.5 )
  881. {
  882. return 0.0;
  883. }
  884. else
  885. {
  886. return mMaterial->mWaveAmp[stage];
  887. }
  888. break;
  889. }
  890. }
  891. return 0.0;
  892. }
  893. void ProcessedShaderMaterial::_setShaderConstants(SceneRenderState * state, const SceneData &sgData, U32 pass)
  894. {
  895. PROFILE_SCOPE( ProcessedShaderMaterial_SetShaderConstants );
  896. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  897. ShaderConstHandles* handles = _getShaderConstHandles(pass);
  898. U32 stageNum = getStageFromPass(pass);
  899. // First we do all the constants which are not
  900. // controlled via the material... we have to
  901. // set these all the time as they could change.
  902. if ( handles->mFogDataSC->isValid() )
  903. {
  904. Point3F fogData;
  905. fogData.x = sgData.fogDensity;
  906. fogData.y = sgData.fogDensityOffset;
  907. fogData.z = sgData.fogHeightFalloff;
  908. shaderConsts->set( handles->mFogDataSC, fogData );
  909. }
  910. shaderConsts->setSafe(handles->mFogColorSC, sgData.fogColor);
  911. if( handles->mOneOverFarplane->isValid() )
  912. {
  913. const F32 &invfp = 1.0f / state->getFarPlane();
  914. Point4F oneOverFP(invfp, invfp, invfp, invfp);
  915. shaderConsts->set( handles->mOneOverFarplane, oneOverFP );
  916. }
  917. shaderConsts->setSafe( handles->mAccumTimeSC, MATMGR->getTotalTime() );
  918. // If the shader constants have not been lost then
  919. // they contain the content from a previous render pass.
  920. //
  921. // In this case we can skip updating the material constants
  922. // which do not change frame to frame.
  923. //
  924. // NOTE: This assumes we're not animating material parameters
  925. // in a way that doesn't cause a shader reload... this isn't
  926. // being done now, but it could change in the future.
  927. //
  928. if ( !shaderConsts->wasLost() )
  929. return;
  930. shaderConsts->setSafe(handles->mSmoothnessSC, mMaterial->mSmoothness[stageNum]);
  931. shaderConsts->setSafe(handles->mMetalnessSC, mMaterial->mMetalness[stageNum]);
  932. shaderConsts->setSafe(handles->mParallaxInfoSC, mMaterial->mParallaxScale[stageNum]);
  933. shaderConsts->setSafe(handles->mMinnaertConstantSC, mMaterial->mMinnaertConstant[stageNum]);
  934. if ( handles->mSubSurfaceParamsSC->isValid() )
  935. {
  936. Point4F subSurfParams;
  937. dMemcpy( &subSurfParams, &mMaterial->mSubSurfaceColor[stageNum], sizeof(LinearColorF) );
  938. subSurfParams.w = mMaterial->mSubSurfaceRolloff[stageNum];
  939. shaderConsts->set(handles->mSubSurfaceParamsSC, subSurfParams);
  940. }
  941. if ( handles->mRTSizeSC->isValid() )
  942. {
  943. const Point2I &resolution = GFX->getActiveRenderTarget()->getSize();
  944. Point2F pixelShaderConstantData;
  945. pixelShaderConstantData.x = resolution.x;
  946. pixelShaderConstantData.y = resolution.y;
  947. shaderConsts->set( handles->mRTSizeSC, pixelShaderConstantData );
  948. }
  949. if ( handles->mOneOverRTSizeSC->isValid() )
  950. {
  951. const Point2I &resolution = GFX->getActiveRenderTarget()->getSize();
  952. Point2F oneOverTargetSize( 1.0f / (F32)resolution.x, 1.0f / (F32)resolution.y );
  953. shaderConsts->set( handles->mOneOverRTSizeSC, oneOverTargetSize );
  954. }
  955. // set detail scale
  956. shaderConsts->setSafe(handles->mDetailScaleSC, mMaterial->mDetailScale[stageNum]);
  957. shaderConsts->setSafe(handles->mDetailBumpStrength, mMaterial->mDetailNormalMapStrength[stageNum]);
  958. // MFT_ImposterVert
  959. if ( handles->mImposterUVs->isValid() )
  960. {
  961. U32 uvCount = getMin( mMaterial->mImposterUVs.size(), 64 ); // See imposter.hlsl
  962. AlignedArray<Point4F> imposterUVs( uvCount, sizeof( Point4F ), (U8*)mMaterial->mImposterUVs.address(), false );
  963. shaderConsts->set( handles->mImposterUVs, imposterUVs );
  964. }
  965. shaderConsts->setSafe( handles->mImposterLimits, mMaterial->mImposterLimits );
  966. // Diffuse
  967. shaderConsts->setSafe(handles->mDiffuseColorSC, mMaterial->mDiffuse[stageNum]);
  968. shaderConsts->setSafe( handles->mAlphaTestValueSC, mClampF( (F32)mMaterial->mAlphaRef / 255.0f, 0.0f, 1.0f ) );
  969. if(handles->mDiffuseAtlasParamsSC)
  970. {
  971. Point4F atlasParams(1.0f / mMaterial->mCellLayout[stageNum].x, // 1 / num_horizontal
  972. 1.0f / mMaterial->mCellLayout[stageNum].y, // 1 / num_vertical
  973. mMaterial->mCellSize[stageNum], // tile size in pixels
  974. getBinLog2(mMaterial->mCellSize[stageNum]) ); // pow of 2 of tile size in pixels 2^9 = 512, 2^10=1024 etc
  975. shaderConsts->setSafe(handles->mDiffuseAtlasParamsSC, atlasParams);
  976. }
  977. if(handles->mBumpAtlasParamsSC)
  978. {
  979. Point4F atlasParams(1.0f / mMaterial->mCellLayout[stageNum].x, // 1 / num_horizontal
  980. 1.0f / mMaterial->mCellLayout[stageNum].y, // 1 / num_vertical
  981. mMaterial->mCellSize[stageNum], // tile size in pixels
  982. getBinLog2(mMaterial->mCellSize[stageNum]) ); // pow of 2 of tile size in pixels 2^9 = 512, 2^10=1024 etc
  983. shaderConsts->setSafe(handles->mBumpAtlasParamsSC, atlasParams);
  984. }
  985. if(handles->mDiffuseAtlasTileSC)
  986. {
  987. // Sanity check the wrap flags
  988. //AssertWarn(mMaterial->mTextureAddressModeU == mMaterial->mTextureAddressModeV, "Addresing mode mismatch, texture atlasing will be confused");
  989. Point4F atlasTileParams( mMaterial->mCellIndex[stageNum].x, // Tile co-ordinate, ie: [0, 3]
  990. mMaterial->mCellIndex[stageNum].y,
  991. 0.0f, 0.0f ); // TODO: Wrap mode flags?
  992. shaderConsts->setSafe(handles->mDiffuseAtlasTileSC, atlasTileParams);
  993. }
  994. if(handles->mBumpAtlasTileSC)
  995. {
  996. // Sanity check the wrap flags
  997. //AssertWarn(mMaterial->mTextureAddressModeU == mMaterial->mTextureAddressModeV, "Addresing mode mismatch, texture atlasing will be confused");
  998. Point4F atlasTileParams( mMaterial->mCellIndex[stageNum].x, // Tile co-ordinate, ie: [0, 3]
  999. mMaterial->mCellIndex[stageNum].y,
  1000. 0.0f, 0.0f ); // TODO: Wrap mode flags?
  1001. shaderConsts->setSafe(handles->mBumpAtlasTileSC, atlasTileParams);
  1002. }
  1003. // Deferred Shading: Determine Material Info Flags
  1004. S32 matInfoFlags =
  1005. (mMaterial->mEmissive[stageNum] ? 1 : 0) | //emissive
  1006. (mMaterial->mSubSurface[stageNum] ? 2 : 0); //subsurface
  1007. mMaterial->mMatInfoFlags[stageNum] = matInfoFlags / 255.0f;
  1008. shaderConsts->setSafe(handles->mMatInfoFlagsSC, mMaterial->mMatInfoFlags[stageNum]);
  1009. if( handles->mAccuScaleSC->isValid() )
  1010. shaderConsts->set( handles->mAccuScaleSC, mMaterial->mAccuScale[stageNum] );
  1011. if( handles->mAccuDirectionSC->isValid() )
  1012. shaderConsts->set( handles->mAccuDirectionSC, mMaterial->mAccuDirection[stageNum] );
  1013. if( handles->mAccuStrengthSC->isValid() )
  1014. shaderConsts->set( handles->mAccuStrengthSC, mMaterial->mAccuStrength[stageNum] );
  1015. if( handles->mAccuCoverageSC->isValid() )
  1016. shaderConsts->set( handles->mAccuCoverageSC, mMaterial->mAccuCoverage[stageNum] );
  1017. if( handles->mAccuSpecularSC->isValid() )
  1018. shaderConsts->set( handles->mAccuSpecularSC, mMaterial->mAccuSpecular[stageNum] );
  1019. }
  1020. bool ProcessedShaderMaterial::_hasCubemap(U32 pass)
  1021. {
  1022. // Only support cubemap on the first stage
  1023. if( mPasses[pass]->mStageNum > 0 )
  1024. return false;
  1025. if( mPasses[pass]->mCubeMap )
  1026. return true;
  1027. return false;
  1028. }
  1029. void ProcessedShaderMaterial::setTransforms(const MatrixSet &matrixSet, SceneRenderState *state, const U32 pass)
  1030. {
  1031. PROFILE_SCOPE( ProcessedShaderMaterial_setTransforms );
  1032. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  1033. ShaderConstHandles* handles = _getShaderConstHandles(pass);
  1034. // The MatrixSet will lazily generate a matrix under the
  1035. // various 'get' methods, so inline the test for a valid
  1036. // shader constant handle to avoid that work when we can.
  1037. if ( handles->mModelViewProjSC->isValid() )
  1038. shaderConsts->set( handles->mModelViewProjSC, matrixSet.getWorldViewProjection() );
  1039. if ( handles->mObjTransSC->isValid() )
  1040. shaderConsts->set( handles->mObjTransSC, matrixSet.getObjectToWorld() );
  1041. if ( handles->mWorldToObjSC->isValid() )
  1042. shaderConsts->set( handles->mWorldToObjSC, matrixSet.getWorldToObject() );
  1043. if ( handles->mWorldToCameraSC->isValid() )
  1044. shaderConsts->set( handles->mWorldToCameraSC, matrixSet.getWorldToCamera() );
  1045. if (handles->mCameraToWorldSC->isValid())
  1046. shaderConsts->set(handles->mCameraToWorldSC, matrixSet.getCameraToWorld());
  1047. if ( handles->mWorldViewOnlySC->isValid() )
  1048. shaderConsts->set( handles->mWorldViewOnlySC, matrixSet.getObjectToCamera() );
  1049. if ( handles->mViewToObjSC->isValid() )
  1050. shaderConsts->set( handles->mViewToObjSC, matrixSet.getCameraToObject() );
  1051. if ( handles->mViewProjSC->isValid() )
  1052. shaderConsts->set( handles->mViewProjSC, matrixSet.getWorldToScreen() );
  1053. if ( handles->mCubeTransSC->isValid() &&
  1054. ( _hasCubemap(pass) || mMaterial->mDynamicCubemap ) )
  1055. {
  1056. // TODO: Could we not remove this constant? Use mObjTransSC and cast to float3x3 instead?
  1057. shaderConsts->set(handles->mCubeTransSC, matrixSet.getObjectToWorld(), GFXSCT_Float3x3);
  1058. }
  1059. if ( handles->m_vEyeSC->isValid() )
  1060. shaderConsts->set( handles->m_vEyeSC, state->getVectorEye() );
  1061. }
  1062. void ProcessedShaderMaterial::setNodeTransforms(const MatrixF *transforms, const U32 transformCount, const U32 pass)
  1063. {
  1064. PROFILE_SCOPE( ProcessedShaderMaterial_setNodeTransforms );
  1065. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  1066. ShaderConstHandles* handles = _getShaderConstHandles(pass);
  1067. if ( handles->mNodeTransforms->isValid() )
  1068. {
  1069. S32 realTransformCount = getMin( transformCount, TSShape::smMaxSkinBones );
  1070. shaderConsts->set( handles->mNodeTransforms, transforms, realTransformCount, GFXSCT_Float4x3 );
  1071. }
  1072. }
  1073. void ProcessedShaderMaterial::setCustomShaderData(Vector<CustomShaderBindingData> &shaderData, const U32 pass)
  1074. {
  1075. PROFILE_SCOPE(ProcessedShaderMaterial_setCustomShaderData);
  1076. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  1077. ShaderConstHandles* handles = _getShaderConstHandles(pass);
  1078. for (U32 i = 0; i < shaderData.size(); i++)
  1079. {
  1080. for (U32 h = 0; h < handles->mCustomHandles.size(); ++h)
  1081. {
  1082. StringTableEntry handleName = shaderData[i].getHandleName();
  1083. bool tmp = true;
  1084. }
  1085. //roll through and try setting our data!
  1086. for (U32 h = 0; h < handles->mCustomHandles.size(); ++h)
  1087. {
  1088. StringTableEntry handleName = shaderData[i].getHandleName();
  1089. StringTableEntry rpdHandleName = handles->mCustomHandles[h].handleName;
  1090. if (handles->mCustomHandles[h].handleName == shaderData[i].getHandleName())
  1091. {
  1092. if (handles->mCustomHandles[h].handle->isValid())
  1093. {
  1094. CustomShaderBindingData::UniformType type = shaderData[i].getType();
  1095. if (type == CustomShaderBindingData::Float)
  1096. shaderConsts->setSafe(handles->mCustomHandles[h].handle, shaderData[i].getFloat());
  1097. else if (type == CustomShaderBindingData::Float2)
  1098. shaderConsts->setSafe(handles->mCustomHandles[h].handle, shaderData[i].getFloat2());
  1099. else if (type == CustomShaderBindingData::Float3)
  1100. shaderConsts->setSafe(handles->mCustomHandles[h].handle, shaderData[i].getFloat3());
  1101. else if (type == CustomShaderBindingData::Float4)
  1102. shaderConsts->setSafe(handles->mCustomHandles[h].handle, shaderData[i].getFloat4());
  1103. break;
  1104. }
  1105. }
  1106. }
  1107. }
  1108. }
  1109. void ProcessedShaderMaterial::setSceneInfo(SceneRenderState * state, const SceneData& sgData, U32 pass)
  1110. {
  1111. PROFILE_SCOPE(ProcessedShaderMaterial_setSceneInfo);
  1112. GFXShaderConstBuffer* shaderConsts = _getShaderConstBuffer(pass);
  1113. ShaderConstHandles* handles = _getShaderConstHandles(pass);
  1114. // Set cubemap stuff here (it's convenient!)
  1115. const Point3F &eyePosWorld = state->getCameraPosition();
  1116. if (_hasCubemap(pass) || mMaterial->mDynamicCubemap)
  1117. {
  1118. if (handles->mCubeEyePosSC->isValid())
  1119. {
  1120. Point3F cubeEyePos = eyePosWorld - sgData.objTrans->getPosition();
  1121. shaderConsts->set(handles->mCubeEyePosSC, cubeEyePos);
  1122. }
  1123. }
  1124. if (sgData.cubemap)
  1125. shaderConsts->setSafe(handles->mCubeMipsSC, (F32)sgData.cubemap->getMipMapLevels());
  1126. else
  1127. shaderConsts->setSafe(handles->mCubeMipsSC, 1.0f);
  1128. shaderConsts->setSafe(handles->mVisiblitySC, sgData.visibility);
  1129. shaderConsts->setSafe(handles->mEyePosWorldSC, eyePosWorld);
  1130. if ( handles->mEyePosSC->isValid() )
  1131. {
  1132. MatrixF tempMat( *sgData.objTrans );
  1133. tempMat.inverse();
  1134. Point3F eyepos;
  1135. tempMat.mulP( eyePosWorld, &eyepos );
  1136. shaderConsts->set(handles->mEyePosSC, eyepos);
  1137. }
  1138. shaderConsts->setSafe(handles->mEyeMatSC, state->getCameraTransform());
  1139. ShaderRenderPassData *rpd = _getRPD(pass);
  1140. for (U32 i = 0; i < rpd->featureShaderHandles.size(); i++)
  1141. rpd->featureShaderHandles[i]->setConsts(state, sgData, shaderConsts);
  1142. LIGHTMGR->setLightInfo(this, mMaterial, sgData, state, pass, shaderConsts);
  1143. //PROBEMGR->setProbeInfo(this, mMaterial, sgData, state, pass, shaderConsts);
  1144. }
  1145. void ProcessedShaderMaterial::setBuffers( GFXVertexBufferHandleBase *vertBuffer, GFXPrimitiveBufferHandle *primBuffer )
  1146. {
  1147. PROFILE_SCOPE(ProcessedShaderMaterial_setBuffers);
  1148. // If we're not instanced then just call the parent.
  1149. if ( !mInstancingState )
  1150. {
  1151. Parent::setBuffers( vertBuffer, primBuffer );
  1152. return;
  1153. }
  1154. PROFILE_SCOPE(ProcessedShaderMaterial_setBuffers_instancing);
  1155. const S32 instCount = mInstancingState->getCount();
  1156. AssertFatal( instCount > 0,
  1157. "ProcessedShaderMaterial::setBuffers - No instances rendered!" );
  1158. // Nothing special here.
  1159. GFX->setPrimitiveBuffer( *primBuffer );
  1160. // Set the first stream the the normal VB and set the
  1161. // correct frequency for the number of instances to render.
  1162. GFX->setVertexBuffer( *vertBuffer, 0, instCount );
  1163. // Get a volatile VB and fill it with the vertex data.
  1164. const GFXVertexFormat *instFormat = mInstancingState->getFormat();
  1165. GFXVertexBufferDataHandle instVB;
  1166. instVB.set( GFX, instFormat->getSizeInBytes(), instFormat, instCount, GFXBufferTypeVolatile );
  1167. U8 *dest = instVB.lock();
  1168. if(!dest) return;
  1169. dMemcpy( dest, mInstancingState->getBuffer(), instFormat->getSizeInBytes() * instCount );
  1170. instVB.unlock();
  1171. // Set the instance vb for streaming.
  1172. GFX->setVertexBuffer( instVB, 1, 1 );
  1173. // Finally set the vertex format which defines
  1174. // both of the streams.
  1175. GFX->setVertexFormat( mInstancingState->getDeclFormat() );
  1176. // Done... reset the count.
  1177. mInstancingState->resetStep();
  1178. }
  1179. bool ProcessedShaderMaterial::stepInstance()
  1180. {
  1181. PROFILE_SCOPE(ProcessedShaderMaterial_stepInstance);
  1182. AssertFatal( mInstancingState, "ProcessedShaderMaterial::stepInstance - This material isn't instanced!" );
  1183. return mInstancingState->step( &_getShaderConstBuffer( 0 )->mInstPtr );
  1184. }
  1185. MaterialParameters* ProcessedShaderMaterial::allocMaterialParameters()
  1186. {
  1187. ShaderMaterialParameters* smp = new ShaderMaterialParameters();
  1188. Vector<GFXShaderConstBufferRef> buffers( __FILE__, __LINE__ );
  1189. buffers.setSize(mPasses.size());
  1190. for (U32 i = 0; i < mPasses.size(); i++)
  1191. buffers[i] = _getRPD(i)->shader->allocConstBuffer();
  1192. // smp now owns these buffers.
  1193. smp->setBuffers(mShaderConstDesc, buffers);
  1194. return smp;
  1195. }
  1196. MaterialParameterHandle* ProcessedShaderMaterial::getMaterialParameterHandle(const String& name)
  1197. {
  1198. // Search our list
  1199. for (U32 i = 0; i < mParameterHandles.size(); i++)
  1200. {
  1201. if (mParameterHandles[i]->getName().equal(name))
  1202. return mParameterHandles[i];
  1203. }
  1204. // If we didn't find it, we have to add it to support shader reloading.
  1205. Vector<GFXShader*> shaders;
  1206. shaders.setSize(mPasses.size());
  1207. for (U32 i = 0; i < mPasses.size(); i++)
  1208. shaders[i] = _getRPD(i)->shader;
  1209. ShaderMaterialParameterHandle* smph = new ShaderMaterialParameterHandle( name, shaders );
  1210. mParameterHandles.push_back(smph);
  1211. return smph;
  1212. }
  1213. /// This is here to deal with the differences between ProcessedCustomMaterials and ProcessedShaderMaterials.
  1214. GFXShaderConstBuffer* ProcessedShaderMaterial::_getShaderConstBuffer( const U32 pass )
  1215. {
  1216. if (mCurrentParams && pass < mPasses.size())
  1217. {
  1218. return static_cast<ShaderMaterialParameters*>(mCurrentParams)->getBuffer(pass);
  1219. }
  1220. return NULL;
  1221. }
  1222. ShaderConstHandles* ProcessedShaderMaterial::_getShaderConstHandles(const U32 pass)
  1223. {
  1224. if (pass < mPasses.size())
  1225. {
  1226. return &_getRPD(pass)->shaderHandles;
  1227. }
  1228. return NULL;
  1229. }
  1230. void ProcessedShaderMaterial::dumpMaterialInfo()
  1231. {
  1232. for ( U32 i = 0; i < getNumPasses(); i++ )
  1233. {
  1234. const ShaderRenderPassData *passData = _getRPD( i );
  1235. if ( passData == NULL )
  1236. continue;
  1237. const GFXShader *shader = passData->shader;
  1238. if ( shader == NULL )
  1239. Con::printf( " [%i] [NULL shader]", i );
  1240. else
  1241. Con::printf( " [%i] %s", i, shader->describeSelf().c_str() );
  1242. }
  1243. }
  1244. void ProcessedShaderMaterial::getMaterialInfo(GuiTreeViewCtrl* tree, U32 item)
  1245. {
  1246. for (U32 i = 0; i < getNumPasses(); i++)
  1247. {
  1248. const ShaderRenderPassData* passData = _getRPD(i);
  1249. if (passData == NULL)
  1250. continue;
  1251. char passStr[64];
  1252. dSprintf(passStr, 64, "Pass Number: %i", i);
  1253. U32 passItem = tree->insertItem(item, passStr);
  1254. const GFXShader * shader = passData->shader;
  1255. if (shader == NULL)
  1256. tree->insertItem(passItem, "[NULL shader]");
  1257. else
  1258. tree->insertItem(passItem, shader->describeSelf().c_str());
  1259. }
  1260. }