terrCellMaterial.cpp 30 KB

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