terrCellMaterial.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935
  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 "terrain/terrCellMaterial.h"
  24. #include "terrain/terrData.h"
  25. #include "terrain/terrCell.h"
  26. #include "materials/materialFeatureTypes.h"
  27. #include "materials/materialManager.h"
  28. #include "terrain/terrFeatureTypes.h"
  29. #include "terrain/terrMaterial.h"
  30. #include "renderInstance/renderDeferredMgr.h"
  31. #include "shaderGen/shaderGen.h"
  32. #include "shaderGen/featureMgr.h"
  33. #include "scene/sceneRenderState.h"
  34. #include "materials/sceneData.h"
  35. #include "gfx/util/screenspace.h"
  36. #include "lighting/advanced/advancedLightBinManager.h"
  37. S32 sgMaxTerrainMaterialsPerPass = 3;
  38. AFTER_MODULE_INIT( MaterialManager )
  39. {
  40. Con::NotifyDelegate callabck( &TerrainCellMaterial::_updateDefaultAnisotropy );
  41. Con::addVariableNotify( "$pref::Video::defaultAnisotropy", callabck );
  42. }
  43. Vector<TerrainCellMaterial*> TerrainCellMaterial::smAllMaterials;
  44. Vector<String> _initSamplerNames()
  45. {
  46. Vector<String> samplerNames;
  47. samplerNames.push_back("$baseTexMap");
  48. samplerNames.push_back("$layerTex");
  49. //samplerNames.push_back("$macrolayerTex");
  50. samplerNames.push_back("$lightMapTex");
  51. samplerNames.push_back("$lightInfoBuffer");
  52. for(int i = 0; i < sgMaxTerrainMaterialsPerPass; ++i)
  53. {
  54. samplerNames.push_back(avar("$normalMap%d",i));
  55. samplerNames.push_back(avar("$detailMap%d",i));
  56. //samplerNames.push_back(avar("$macroMap%d", i));
  57. samplerNames.push_back(avar("$compositeMap%d", i));
  58. }
  59. return samplerNames;
  60. }
  61. const Vector<String> TerrainCellMaterial::mSamplerNames = _initSamplerNames();
  62. TerrainCellMaterial::TerrainCellMaterial()
  63. : mTerrain( NULL ),
  64. mCurrPass( 0 ),
  65. mDeferredMat( NULL ),
  66. mReflectMat( NULL ),
  67. mMaterials(0)
  68. {
  69. smAllMaterials.push_back( this );
  70. }
  71. TerrainCellMaterial::~TerrainCellMaterial()
  72. {
  73. SAFE_DELETE( mDeferredMat );
  74. SAFE_DELETE( mReflectMat );
  75. smAllMaterials.remove( this );
  76. }
  77. void TerrainCellMaterial::_updateDefaultAnisotropy()
  78. {
  79. // TODO: We need to split the stateblock initialization
  80. // from the shader constant lookup and pass setup in a
  81. // future version of terrain materials.
  82. //
  83. // For now use some custom code in a horrible loop to
  84. // change the anisotropy directly and fast.
  85. //
  86. const U32 maxAnisotropy = MATMGR->getDefaultAnisotropy();
  87. Vector<TerrainCellMaterial*>::iterator iter = smAllMaterials.begin();
  88. for ( ; iter != smAllMaterials.end(); iter++ )
  89. {
  90. for ( U32 p=0; p < (*iter)->mPasses.size(); p++ )
  91. {
  92. Pass &pass = (*iter)->mPasses[p];
  93. // Start from the existing state block.
  94. GFXStateBlockDesc desc = pass.stateBlock->getDesc();
  95. for ( U32 m=0; m < pass.materials.size(); m++ )
  96. {
  97. const MaterialInfo *matInfo = pass.materials[m];
  98. if ( matInfo->detailTexConst->isValid() )
  99. {
  100. const S32 sampler = matInfo->detailTexConst->getSamplerRegister();
  101. if ( maxAnisotropy > 1 )
  102. {
  103. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  104. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  105. }
  106. else
  107. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  108. }
  109. if ( matInfo->macroTexConst->isValid() )
  110. {
  111. const S32 sampler = matInfo->macroTexConst->getSamplerRegister();
  112. if ( maxAnisotropy > 1 )
  113. {
  114. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  115. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  116. }
  117. else
  118. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  119. }
  120. if ( matInfo->normalTexConst->isValid() )
  121. {
  122. const S32 sampler = matInfo->normalTexConst->getSamplerRegister();
  123. if ( maxAnisotropy > 1 )
  124. {
  125. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  126. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  127. }
  128. else
  129. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  130. }
  131. if (matInfo->compositeTexConst->isValid())
  132. {
  133. const S32 sampler = matInfo->compositeTexConst->getSamplerRegister();
  134. if (maxAnisotropy > 1)
  135. {
  136. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  137. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  138. }
  139. else
  140. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  141. }
  142. } // for ( U32 m=0; m < pass.materials.size(); m++ )
  143. // Set the updated stateblock.
  144. desc.setCullMode( GFXCullCCW );
  145. pass.stateBlock = GFX->createStateBlock( desc );
  146. //reflection
  147. desc.setCullMode( GFXCullCW );
  148. pass.reflectionStateBlock = GFX->createStateBlock(desc);
  149. // Create the wireframe state blocks.
  150. GFXStateBlockDesc wireframe( desc );
  151. wireframe.fillMode = GFXFillWireframe;
  152. wireframe.setCullMode( GFXCullCCW );
  153. pass.wireframeStateBlock = GFX->createStateBlock( wireframe );
  154. } // for ( U32 p=0; i < (*iter)->mPasses.size(); p++ )
  155. }
  156. }
  157. void TerrainCellMaterial::setTransformAndEye( const MatrixF &modelXfm,
  158. const MatrixF &viewXfm,
  159. const MatrixF &projectXfm,
  160. F32 farPlane )
  161. {
  162. PROFILE_SCOPE( TerrainCellMaterial_SetTransformAndEye );
  163. MatrixF modelViewProj = projectXfm * viewXfm * modelXfm;
  164. MatrixF invViewXfm( viewXfm );
  165. invViewXfm.inverse();
  166. Point3F eyePos = invViewXfm.getPosition();
  167. MatrixF invModelXfm( modelXfm );
  168. invModelXfm.inverse();
  169. Point3F objEyePos = eyePos;
  170. invModelXfm.mulP( objEyePos );
  171. VectorF vEye = invViewXfm.getForwardVector();
  172. vEye.normalize( 1.0f / farPlane );
  173. for ( U32 i=0; i < mPasses.size(); i++ )
  174. {
  175. Pass &pass = mPasses[i];
  176. pass.consts->setSafe( pass.modelViewProjConst, modelViewProj );
  177. if( pass.viewToObj->isValid() || pass.worldViewOnly->isValid() )
  178. {
  179. MatrixF worldViewOnly = viewXfm * modelXfm;
  180. pass.consts->setSafe( pass.worldViewOnly, worldViewOnly );
  181. if( pass.viewToObj->isValid() )
  182. {
  183. worldViewOnly.affineInverse();
  184. pass.consts->set( pass.viewToObj, worldViewOnly);
  185. }
  186. }
  187. pass.consts->setSafe( pass.eyePosWorldConst, eyePos );
  188. pass.consts->setSafe( pass.eyePosConst, objEyePos );
  189. pass.consts->setSafe( pass.objTransConst, modelXfm );
  190. pass.consts->setSafe( pass.worldToObjConst, invModelXfm );
  191. pass.consts->setSafe( pass.vEyeConst, vEye );
  192. }
  193. }
  194. TerrainCellMaterial* TerrainCellMaterial::getDeferredMat()
  195. {
  196. if ( !mDeferredMat )
  197. {
  198. mDeferredMat = new TerrainCellMaterial();
  199. mDeferredMat->init( mTerrain, mMaterials, true, false, mMaterials == 0 );
  200. }
  201. return mDeferredMat;
  202. }
  203. TerrainCellMaterial* TerrainCellMaterial::getReflectMat()
  204. {
  205. if ( !mReflectMat )
  206. {
  207. mReflectMat = new TerrainCellMaterial();
  208. mReflectMat->init( mTerrain, mMaterials, false, true, true );
  209. }
  210. return mReflectMat;
  211. }
  212. void TerrainCellMaterial::init( TerrainBlock *block,
  213. U64 activeMaterials,
  214. bool deferredMat,
  215. bool reflectMat,
  216. bool baseOnly )
  217. {
  218. // This isn't allowed for now.
  219. AssertFatal( !( deferredMat && reflectMat ), "TerrainCellMaterial::init - We shouldn't get deferred and reflection in the same material!" );
  220. mTerrain = block;
  221. mMaterials = activeMaterials;
  222. Vector<MaterialInfo*> materials;
  223. for ( U32 i = 0; i < 64; i++ )
  224. {
  225. if ( !( mMaterials & ((U64)1 << i ) ) )
  226. continue;
  227. TerrainMaterial *mat = block->getMaterial( i );
  228. MaterialInfo *info = new MaterialInfo();
  229. info->layerId = i;
  230. info->mat = mat;
  231. materials.push_back( info );
  232. }
  233. mCurrPass = 0;
  234. mPasses.clear();
  235. // Ok... loop till we successfully generate all
  236. // the shader passes for the materials.
  237. while ( materials.size() > 0 || baseOnly )
  238. {
  239. mPasses.increment();
  240. if ( !_createPass( &materials,
  241. &mPasses.last(),
  242. mPasses.size() == 1,
  243. deferredMat,
  244. reflectMat,
  245. baseOnly ) )
  246. {
  247. Con::errorf( "TerrainCellMaterial::init - Failed to create pass!" );
  248. // The pass failed to be generated... give up.
  249. mPasses.last().materials.clear();
  250. mPasses.clear();
  251. T3D::for_each( materials.begin(), materials.end(), T3D::delete_pointer() );
  252. return;
  253. }
  254. if ( baseOnly )
  255. break;
  256. }
  257. // Cleanup any remaining matinfo.
  258. T3D::for_each( materials.begin(), materials.end(), T3D::delete_pointer() );
  259. // If we have attached mats then update them too.
  260. if ( mDeferredMat )
  261. mDeferredMat->init( mTerrain, mMaterials, true, false, baseOnly );
  262. if ( mReflectMat )
  263. mReflectMat->init( mTerrain, mMaterials, false, true, baseOnly );
  264. }
  265. bool TerrainCellMaterial::_createPass( Vector<MaterialInfo*> *materials,
  266. Pass *pass,
  267. bool firstPass,
  268. bool deferredMat,
  269. bool reflectMat,
  270. bool baseOnly )
  271. {
  272. if ( GFX->getPixelShaderVersion() < 3.0f )
  273. baseOnly = true;
  274. // NOTE: At maximum we only try to combine sgMaxTerrainMaterialsPerPass materials
  275. // into a single pass. This is sub-optimal for the simplest
  276. // cases, but the most common case results in much fewer
  277. // shader generation failures and permutations leading to
  278. // faster load time and less hiccups during gameplay.
  279. U32 matCount = getMin( sgMaxTerrainMaterialsPerPass, materials->size() );
  280. Vector<GFXTexHandle> normalMaps;
  281. // See if we're currently running under the
  282. // basic lighting manager.
  283. //
  284. // TODO: This seems ugly... we should trigger
  285. // features like this differently in the future.
  286. //
  287. bool useBLM = dStrcmp( LIGHTMGR->getId(), "BLM" ) == 0;
  288. // Do we need to disable normal mapping?
  289. const bool disableNormalMaps = MATMGR->getExclusionFeatures().hasFeature( MFT_NormalMap ) || useBLM;
  290. // How about parallax?
  291. const bool disableParallaxMaps = GFX->getPixelShaderVersion() < 3.0f ||
  292. MATMGR->getExclusionFeatures().hasFeature( MFT_Parallax );
  293. // Has advanced lightmap support been enabled for deferred.
  294. bool advancedLightmapSupport = false;
  295. if ( deferredMat )
  296. {
  297. // This sucks... but it works.
  298. AdvancedLightBinManager *lightBin;
  299. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) )
  300. advancedLightmapSupport = lightBin->MRTLightmapsDuringDeferred();
  301. }
  302. // Loop till we create a valid shader!
  303. while( true )
  304. {
  305. FeatureSet features;
  306. features.addFeature( MFT_VertTransform );
  307. features.addFeature( MFT_TerrainBaseMap );
  308. if ( deferredMat )
  309. {
  310. features.addFeature( MFT_EyeSpaceDepthOut );
  311. features.addFeature( MFT_DeferredConditioner );
  312. features.addFeature(MFT_isDeferred);
  313. if ( advancedLightmapSupport )
  314. features.addFeature( MFT_RenderTarget3_Zero );
  315. }
  316. else
  317. {
  318. features.addFeature( MFT_RTLighting );
  319. // The HDR feature is always added... it will compile out
  320. // if HDR is not enabled in the engine.
  321. features.addFeature( MFT_HDROut );
  322. }
  323. features.addFeature(MFT_DeferredTerrainBlankInfoMap);
  324. // Enable lightmaps and fogging if we're in BL.
  325. if ( reflectMat || useBLM )
  326. {
  327. features.addFeature( MFT_Fog );
  328. features.addFeature( MFT_ForwardShading );
  329. }
  330. if ( useBLM )
  331. features.addFeature( MFT_TerrainLightMap );
  332. // The additional passes need to be lerp blended into the
  333. // target to maintain the results of the previous passes.
  334. if (!firstPass && deferredMat)
  335. features.addFeature( MFT_TerrainAdditive );
  336. normalMaps.clear();
  337. pass->materials.clear();
  338. // Now add all the material layer features.
  339. for ( U32 i=0; i < matCount && !baseOnly; i++ )
  340. {
  341. TerrainMaterial *mat = (*materials)[i]->mat;
  342. if ( mat == NULL )
  343. continue;
  344. // We only include materials that
  345. // have more than a base texture.
  346. if ( mat->getDetailSize() <= 0 ||
  347. mat->getDetailDistance() <= 0 ||
  348. mat->getDetailMap().isEmpty() )
  349. continue;
  350. S32 featureIndex = pass->materials.size();
  351. // check for macro detail texture
  352. if ( !(mat->getMacroSize() <= 0 || mat->getMacroDistance() <= 0 || mat->getMacroMap().isEmpty() ) )
  353. {
  354. if(deferredMat)
  355. features.addFeature(MFT_isDeferred, featureIndex);
  356. features.addFeature( MFT_TerrainMacroMap, featureIndex );
  357. }
  358. if(deferredMat)
  359. features.addFeature(MFT_isDeferred, featureIndex);
  360. features.addFeature( MFT_TerrainDetailMap, featureIndex );
  361. if (!(mat->getCompositeMap().isEmpty()))
  362. {
  363. if (deferredMat)
  364. features.addFeature(MFT_isDeferred, featureIndex);
  365. features.addFeature(MFT_TerrainCompositeMap, featureIndex);
  366. features.removeFeature(MFT_DeferredTerrainBlankInfoMap);
  367. }
  368. if (mat->getInvertSmoothness())
  369. features.addFeature(MFT_InvertSmoothness);
  370. pass->materials.push_back( (*materials)[i] );
  371. normalMaps.increment();
  372. // Skip normal maps if we need to.
  373. if ( !disableNormalMaps && mat->getNormalMap().isNotEmpty() )
  374. {
  375. features.addFeature( MFT_TerrainNormalMap, featureIndex );
  376. normalMaps.last().set( mat->getNormalMap(),
  377. &GFXNormalMapProfile, "TerrainCellMaterial::_createPass() - NormalMap" );
  378. GFXFormat normalFmt = normalMaps.last().getFormat();
  379. if ( normalFmt == GFXFormatBC3 )
  380. features.addFeature( MFT_IsBC3nm, featureIndex );
  381. else if ( normalFmt == GFXFormatBC5)
  382. features.addFeature( MFT_IsBC5nm, featureIndex);
  383. // Do we need and can we do parallax mapping?
  384. if ( !disableParallaxMaps &&
  385. mat->getParallaxScale() > 0.0f &&
  386. !mat->useSideProjection() )
  387. features.addFeature( MFT_TerrainParallaxMap, featureIndex );
  388. }
  389. // Is this layer got side projection?
  390. if ( mat->useSideProjection() )
  391. features.addFeature( MFT_TerrainSideProject, featureIndex );
  392. }
  393. MaterialFeatureData featureData;
  394. featureData.features = features;
  395. featureData.materialFeatures = features;
  396. Vector<CustomShaderFeatureData*> customFeatures;
  397. // Check to see how many vertex shader output
  398. // registers we're gonna need.
  399. U32 numTex = 0;
  400. U32 numTexReg = 0;
  401. for ( U32 i=0; i < features.getCount(); i++ )
  402. {
  403. S32 index;
  404. const FeatureType &type = features.getAt( i, &index );
  405. ShaderFeature* sf = FEATUREMGR->getByType( type );
  406. if ( !sf )
  407. continue;
  408. sf->setProcessIndex( index );
  409. ShaderFeature::Resources res = sf->getResources( featureData );
  410. numTex += res.numTex;
  411. numTexReg += res.numTexReg;
  412. }
  413. // Can we build the shader?
  414. //
  415. // NOTE: The 10 is sort of an abitrary SM 3.0
  416. // limit. Its really supposed to be 11, but that
  417. // always fails to compile so far.
  418. //
  419. if ( numTex < GFX->getNumSamplers() &&
  420. numTexReg <= 10 )
  421. {
  422. // NOTE: We really shouldn't be getting errors building the shaders,
  423. // but we can generate more instructions than the ps_2_x will allow.
  424. //
  425. // There is no way to deal with this case that i know of other than
  426. // letting the compile fail then recovering by trying to build it
  427. // with fewer materials.
  428. //
  429. // We normally disable the shader error logging so that the user
  430. // isn't fooled into thinking there is a real bug. That is until
  431. // we get down to a single material. If a single material case
  432. // fails it means it cannot generate any passes at all!
  433. const bool logErrors = true;// matCount == 1;
  434. GFXShader::setLogging( logErrors, true );
  435. pass->shader = SHADERGEN->getShader( featureData, customFeatures, getGFXVertexFormat<TerrVertex>(), NULL, mSamplerNames );
  436. }
  437. // If we got a shader then we can continue.
  438. if ( pass->shader )
  439. break;
  440. // If the material count is already 1 then this
  441. // is a real shader error... give up!
  442. if ( matCount <= 1 )
  443. return false;
  444. // If we failed we next try half the input materials
  445. // so that we can more quickly arrive at a valid shader.
  446. matCount -= matCount / 2;
  447. }
  448. // Setup the constant buffer.
  449. pass->consts = pass->shader->allocConstBuffer();
  450. // Prepare the basic constants.
  451. pass->modelViewProjConst = pass->shader->getShaderConstHandle( "$modelview" );
  452. pass->worldViewOnly = pass->shader->getShaderConstHandle( "$worldViewOnly" );
  453. pass->viewToObj = pass->shader->getShaderConstHandle( "$viewToObj" );
  454. pass->eyePosWorldConst = pass->shader->getShaderConstHandle( "$eyePosWorld" );
  455. pass->eyePosConst = pass->shader->getShaderConstHandle( "$eyePos" );
  456. pass->vEyeConst = pass->shader->getShaderConstHandle( "$vEye" );
  457. pass->layerSizeConst = pass->shader->getShaderConstHandle( "$layerSize" );
  458. pass->objTransConst = pass->shader->getShaderConstHandle( "$objTrans" );
  459. pass->worldToObjConst = pass->shader->getShaderConstHandle( "$worldToObj" );
  460. pass->lightInfoBufferConst = pass->shader->getShaderConstHandle( "$lightInfoBuffer" );
  461. pass->baseTexMapConst = pass->shader->getShaderConstHandle( "$baseTexMap" );
  462. pass->layerTexConst = pass->shader->getShaderConstHandle( "$layerTex" );
  463. pass->fogDataConst = pass->shader->getShaderConstHandle( "$fogData" );
  464. pass->fogColorConst = pass->shader->getShaderConstHandle( "$fogColor" );
  465. pass->lightMapTexConst = pass->shader->getShaderConstHandle( "$lightMapTex" );
  466. pass->oneOverTerrainSize = pass->shader->getShaderConstHandle( "$oneOverTerrainSize" );
  467. pass->squareSize = pass->shader->getShaderConstHandle( "$squareSize" );
  468. pass->lightParamsConst = pass->shader->getShaderConstHandle( "$rtParamslightInfoBuffer" );
  469. // Now prepare the basic stateblock.
  470. GFXStateBlockDesc desc;
  471. if ( !firstPass )
  472. {
  473. desc.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  474. // If this is the deferred then we don't want to
  475. // write to the last two color channels (where
  476. // depth is usually encoded).
  477. //
  478. // This trick works in combination with the
  479. // MFT_TerrainAdditive feature to lerp the
  480. // output normal with the previous pass.
  481. //
  482. if ( deferredMat )
  483. desc.setColorWrites( true, true, true, false );
  484. }
  485. // We write to the zbuffer if this is a deferred
  486. // material or if the deferred is disabled.
  487. desc.setZReadWrite( true, !MATMGR->getDeferredEnabled() ||
  488. deferredMat ||
  489. reflectMat );
  490. desc.samplersDefined = true;
  491. if ( pass->baseTexMapConst->isValid() )
  492. desc.samplers[pass->baseTexMapConst->getSamplerRegister()] = GFXSamplerStateDesc::getWrapLinear();
  493. if ( pass->layerTexConst->isValid() )
  494. desc.samplers[pass->layerTexConst->getSamplerRegister()] = GFXSamplerStateDesc::getClampPoint();
  495. if ( pass->lightInfoBufferConst->isValid() )
  496. desc.samplers[pass->lightInfoBufferConst->getSamplerRegister()] = GFXSamplerStateDesc::getClampPoint();
  497. if ( pass->lightMapTexConst->isValid() )
  498. desc.samplers[pass->lightMapTexConst->getSamplerRegister()] = GFXSamplerStateDesc::getWrapLinear();
  499. const U32 maxAnisotropy = MATMGR->getDefaultAnisotropy();
  500. // Finally setup the material specific shader
  501. // constants and stateblock state.
  502. //
  503. // NOTE: If this changes be sure to check TerrainCellMaterial::_updateDefaultAnisotropy
  504. // to see if it needs the same changes.
  505. //
  506. for ( U32 i=0; i < pass->materials.size(); i++ )
  507. {
  508. MaterialInfo *matInfo = pass->materials[i];
  509. matInfo->detailInfoVConst = pass->shader->getShaderConstHandle( avar( "$detailScaleAndFade%d", i ) );
  510. matInfo->detailInfoPConst = pass->shader->getShaderConstHandle( avar( "$detailIdStrengthParallax%d", i ) );
  511. matInfo->detailTexConst = pass->shader->getShaderConstHandle( avar( "$detailMap%d", i ) );
  512. if ( matInfo->detailTexConst->isValid() )
  513. {
  514. const S32 sampler = matInfo->detailTexConst->getSamplerRegister();
  515. desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
  516. desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
  517. desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
  518. if ( maxAnisotropy > 1 )
  519. {
  520. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  521. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  522. }
  523. else
  524. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  525. matInfo->detailTex.set( matInfo->mat->getDetailMap(),
  526. &GFXStaticTextureProfile, "TerrainCellMaterial::_createPass() - DetailMap" );
  527. }
  528. matInfo->compositeTexConst = pass->shader->getShaderConstHandle(avar("$compositeMap%d", i));
  529. if (matInfo->compositeTexConst->isValid())
  530. {
  531. GFXTextureProfile* profile = &GFXStaticTextureProfile;
  532. if (matInfo->mat->getIsSRGB())
  533. profile = &GFXStaticTextureSRGBProfile;
  534. matInfo->compositeTex.set(matInfo->mat->getCompositeMap(),
  535. profile, "TerrainCellMaterial::_createPass() - CompositeMap");
  536. const S32 sampler = matInfo->compositeTexConst->getSamplerRegister();
  537. desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
  538. desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
  539. desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
  540. if (maxAnisotropy > 1)
  541. {
  542. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  543. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  544. }
  545. else
  546. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  547. }
  548. matInfo->macroInfoVConst = pass->shader->getShaderConstHandle( avar( "$macroScaleAndFade%d", i ) );
  549. matInfo->macroInfoPConst = pass->shader->getShaderConstHandle( avar( "$macroIdStrengthParallax%d", i ) );
  550. matInfo->macroTexConst = pass->shader->getShaderConstHandle( avar( "$macroMap%d", i ) );
  551. if ( matInfo->macroTexConst->isValid() )
  552. {
  553. const S32 sampler = matInfo->macroTexConst->getSamplerRegister();
  554. desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
  555. desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
  556. desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
  557. if ( maxAnisotropy > 1 )
  558. {
  559. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  560. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  561. }
  562. else
  563. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  564. matInfo->macroTex.set( matInfo->mat->getMacroMap(),
  565. &GFXStaticTextureProfile, "TerrainCellMaterial::_createPass() - MacroMap" );
  566. }
  567. //end macro texture
  568. matInfo->normalTexConst = pass->shader->getShaderConstHandle( avar( "$normalMap%d", i ) );
  569. if ( matInfo->normalTexConst->isValid() )
  570. {
  571. const S32 sampler = matInfo->normalTexConst->getSamplerRegister();
  572. desc.samplers[sampler] = GFXSamplerStateDesc::getWrapLinear();
  573. desc.samplers[sampler].magFilter = GFXTextureFilterLinear;
  574. desc.samplers[sampler].mipFilter = GFXTextureFilterLinear;
  575. if ( maxAnisotropy > 1 )
  576. {
  577. desc.samplers[sampler].minFilter = GFXTextureFilterAnisotropic;
  578. desc.samplers[sampler].maxAnisotropy = maxAnisotropy;
  579. }
  580. else
  581. desc.samplers[sampler].minFilter = GFXTextureFilterLinear;
  582. matInfo->normalTex = normalMaps[i];
  583. }
  584. }
  585. // Remove the materials we processed and leave the
  586. // ones that remain for the next pass.
  587. for ( U32 i=0; i < matCount; i++ )
  588. {
  589. MaterialInfo *matInfo = materials->first();
  590. if ( baseOnly || pass->materials.find_next( matInfo ) == -1 )
  591. delete matInfo;
  592. materials->pop_front();
  593. }
  594. // If we're doing deferred it requires some
  595. // special stencil settings for it to work.
  596. if ( deferredMat )
  597. desc.addDesc( RenderDeferredMgr::getOpaqueStenciWriteDesc( false ) );
  598. desc.setCullMode( GFXCullCCW );
  599. pass->stateBlock = GFX->createStateBlock(desc);
  600. //reflection stateblock
  601. desc.setCullMode( GFXCullCW );
  602. pass->reflectionStateBlock = GFX->createStateBlock(desc);
  603. // Create the wireframe state blocks.
  604. GFXStateBlockDesc wireframe( desc );
  605. wireframe.fillMode = GFXFillWireframe;
  606. wireframe.setCullMode( GFXCullCCW );
  607. pass->wireframeStateBlock = GFX->createStateBlock( wireframe );
  608. return true;
  609. }
  610. void TerrainCellMaterial::_updateMaterialConsts( Pass *pass )
  611. {
  612. PROFILE_SCOPE( TerrainCellMaterial_UpdateMaterialConsts );
  613. for ( U32 j=0; j < pass->materials.size(); j++ )
  614. {
  615. MaterialInfo *matInfo = pass->materials[j];
  616. F32 detailSize = matInfo->mat->getDetailSize();
  617. F32 detailScale = 1.0f;
  618. if ( !mIsZero( detailSize ) )
  619. detailScale = mTerrain->getWorldBlockSize() / detailSize;
  620. // Scale the distance by the global scalar.
  621. const F32 distance = mTerrain->smDetailScale * matInfo->mat->getDetailDistance();
  622. // NOTE: The negation of the y scale is to make up for
  623. // my mistake early in development and passing the wrong
  624. // y texture coord into the system.
  625. //
  626. // This negation fixes detail, normal, and parallax mapping
  627. // without harming the layer id blending code.
  628. //
  629. // Eventually we should rework this to correct this little
  630. // mistake, but there isn't really a hurry to.
  631. //
  632. Point4F detailScaleAndFade( detailScale,
  633. -detailScale,
  634. distance,
  635. 0 );
  636. if ( !mIsZero( distance ) )
  637. detailScaleAndFade.w = 1.0f / distance;
  638. Point3F detailIdStrengthParallax( matInfo->layerId,
  639. matInfo->mat->getDetailStrength(),
  640. matInfo->mat->getParallaxScale() );
  641. pass->consts->setSafe( matInfo->detailInfoVConst, detailScaleAndFade );
  642. pass->consts->setSafe( matInfo->detailInfoPConst, detailIdStrengthParallax );
  643. // macro texture info
  644. F32 macroSize = matInfo->mat->getMacroSize();
  645. F32 macroScale = 1.0f;
  646. if ( !mIsZero( macroSize ) )
  647. macroScale = mTerrain->getWorldBlockSize() / macroSize;
  648. // Scale the distance by the global scalar.
  649. const F32 macroDistance = mTerrain->smDetailScale * matInfo->mat->getMacroDistance();
  650. Point4F macroScaleAndFade( macroScale,
  651. -macroScale,
  652. macroDistance,
  653. 0 );
  654. if ( !mIsZero( macroDistance ) )
  655. macroScaleAndFade.w = 1.0f / macroDistance;
  656. Point3F macroIdStrengthParallax( matInfo->layerId,
  657. matInfo->mat->getMacroStrength(),
  658. 0 );
  659. pass->consts->setSafe( matInfo->macroInfoVConst, macroScaleAndFade );
  660. pass->consts->setSafe( matInfo->macroInfoPConst, macroIdStrengthParallax );
  661. }
  662. }
  663. bool TerrainCellMaterial::setupPass( const SceneRenderState *state,
  664. const SceneData &sceneData )
  665. {
  666. PROFILE_SCOPE( TerrainCellMaterial_SetupPass );
  667. if ( mCurrPass >= mPasses.size() )
  668. {
  669. mCurrPass = 0;
  670. return false;
  671. }
  672. Pass &pass = mPasses[mCurrPass];
  673. _updateMaterialConsts( &pass );
  674. if ( pass.baseTexMapConst->isValid() )
  675. GFX->setTexture( pass.baseTexMapConst->getSamplerRegister(), mTerrain->mBaseTex.getPointer() );
  676. if ( pass.layerTexConst->isValid() )
  677. GFX->setTexture( pass.layerTexConst->getSamplerRegister(), mTerrain->mLayerTex.getPointer() );
  678. if ( pass.lightMapTexConst->isValid() )
  679. GFX->setTexture( pass.lightMapTexConst->getSamplerRegister(), mTerrain->getLightMapTex() );
  680. if ( sceneData.wireframe )
  681. GFX->setStateBlock( pass.wireframeStateBlock );
  682. else if ( state->isReflectPass( ))
  683. GFX->setStateBlock( pass.reflectionStateBlock );
  684. else
  685. GFX->setStateBlock( pass.stateBlock );
  686. GFX->setShader( pass.shader );
  687. GFX->setShaderConstBuffer( pass.consts );
  688. // Let the light manager prepare any light stuff it needs.
  689. LIGHTMGR->setLightInfo( NULL,
  690. NULL,
  691. sceneData,
  692. state,
  693. mCurrPass,
  694. pass.consts );
  695. for ( U32 i=0; i < pass.materials.size(); i++ )
  696. {
  697. MaterialInfo *matInfo = pass.materials[i];
  698. if ( matInfo->detailTexConst->isValid() )
  699. GFX->setTexture( matInfo->detailTexConst->getSamplerRegister(), matInfo->detailTex );
  700. if ( matInfo->macroTexConst->isValid() )
  701. GFX->setTexture( matInfo->macroTexConst->getSamplerRegister(), matInfo->macroTex );
  702. if ( matInfo->normalTexConst->isValid() )
  703. GFX->setTexture( matInfo->normalTexConst->getSamplerRegister(), matInfo->normalTex );
  704. if ( matInfo->compositeTexConst->isValid() )
  705. GFX->setTexture( matInfo->compositeTexConst->getSamplerRegister(), matInfo->compositeTex );
  706. }
  707. pass.consts->setSafe( pass.layerSizeConst, (F32)mTerrain->mLayerTex.getWidth() );
  708. if ( pass.oneOverTerrainSize->isValid() )
  709. {
  710. F32 oneOverTerrainSize = 1.0f / mTerrain->getWorldBlockSize();
  711. pass.consts->set( pass.oneOverTerrainSize, oneOverTerrainSize );
  712. }
  713. pass.consts->setSafe( pass.squareSize, mTerrain->getSquareSize() );
  714. if ( pass.fogDataConst->isValid() )
  715. {
  716. Point3F fogData;
  717. fogData.x = sceneData.fogDensity;
  718. fogData.y = sceneData.fogDensityOffset;
  719. fogData.z = sceneData.fogHeightFalloff;
  720. pass.consts->set( pass.fogDataConst, fogData );
  721. }
  722. pass.consts->setSafe( pass.fogColorConst, sceneData.fogColor );
  723. if ( pass.lightInfoBufferConst->isValid() &&
  724. pass.lightParamsConst->isValid() )
  725. {
  726. if ( !mLightInfoTarget )
  727. mLightInfoTarget = NamedTexTarget::find( "diffuseLighting" );
  728. GFXTextureObject *texObject = mLightInfoTarget->getTexture();
  729. // TODO: Sometimes during reset of the light manager we get a
  730. // NULL texture here. This is corrected on the next frame, but
  731. // we should still investigate why that happens.
  732. if ( texObject )
  733. {
  734. GFX->setTexture( pass.lightInfoBufferConst->getSamplerRegister(), texObject );
  735. const Point3I &targetSz = texObject->getSize();
  736. const RectI &targetVp = mLightInfoTarget->getViewport();
  737. Point4F rtParams;
  738. ScreenSpace::RenderTargetParameters(targetSz, targetVp, rtParams);
  739. pass.consts->setSafe( pass.lightParamsConst, rtParams );
  740. }
  741. }
  742. ++mCurrPass;
  743. return true;
  744. }
  745. BaseMatInstance* TerrainCellMaterial::getShadowMat()
  746. {
  747. // Find our material which has some settings
  748. // defined on it in script.
  749. Material *mat = MATMGR->getMaterialDefinitionByName( "AL_DefaultShadowMaterial" );
  750. // Create the material instance adding the feature which
  751. // handles rendering terrain cut outs.
  752. FeatureSet features = MATMGR->getDefaultFeatures();
  753. BaseMatInstance *matInst = mat->createMatInstance();
  754. if ( !matInst->init( features, getGFXVertexFormat<TerrVertex>() ) )
  755. {
  756. delete matInst;
  757. matInst = NULL;
  758. }
  759. return matInst;
  760. }