renderPrePassMgr.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852
  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 "renderInstance/renderPrePassMgr.h"
  24. #include "gfx/gfxTransformSaver.h"
  25. #include "materials/sceneData.h"
  26. #include "materials/materialManager.h"
  27. #include "materials/materialFeatureTypes.h"
  28. #include "core/util/safeDelete.h"
  29. #include "shaderGen/featureMgr.h"
  30. #include "shaderGen/HLSL/depthHLSL.h"
  31. #include "shaderGen/GLSL/depthGLSL.h"
  32. #include "shaderGen/conditionerFeature.h"
  33. #include "shaderGen/shaderGenVars.h"
  34. #include "scene/sceneRenderState.h"
  35. #include "gfx/gfxStringEnumTranslate.h"
  36. #include "gfx/gfxDebugEvent.h"
  37. #include "materials/customMaterialDefinition.h"
  38. #include "lighting/advanced/advancedLightManager.h"
  39. #include "lighting/advanced/advancedLightBinManager.h"
  40. #include "terrain/terrCell.h"
  41. #include "renderInstance/renderTerrainMgr.h"
  42. #include "terrain/terrCellMaterial.h"
  43. #include "math/mathUtils.h"
  44. #include "math/util/matrixSet.h"
  45. const MatInstanceHookType PrePassMatInstanceHook::Type( "PrePass" );
  46. const String RenderPrePassMgr::BufferName("prepass");
  47. const RenderInstType RenderPrePassMgr::RIT_PrePass("PrePass");
  48. IMPLEMENT_CONOBJECT(RenderPrePassMgr);
  49. ConsoleDocClass( RenderPrePassMgr,
  50. "@brief The render bin which performs a z+normals prepass used in Advanced Lighting.\n\n"
  51. "This render bin is used in Advanced Lighting to gather all opaque mesh render instances "
  52. "and render them to the g-buffer for use in lighting the scene and doing effects.\n\n"
  53. "PostEffect and other shaders can access the output of this bin by using the #prepass "
  54. "texture target name. See the edge anti-aliasing post effect for an example.\n\n"
  55. "@see game/core/scripts/client/postFx/edgeAA.cs\n"
  56. "@ingroup RenderBin\n" );
  57. RenderPrePassMgr::RenderSignal& RenderPrePassMgr::getRenderSignal()
  58. {
  59. static RenderSignal theSignal;
  60. return theSignal;
  61. }
  62. RenderPrePassMgr::RenderPrePassMgr( bool gatherDepth,
  63. GFXFormat format )
  64. : Parent( RIT_PrePass,
  65. 0.01f,
  66. 0.01f,
  67. format,
  68. Point2I( Parent::DefaultTargetSize, Parent::DefaultTargetSize),
  69. gatherDepth ? Parent::DefaultTargetChainLength : 0 ),
  70. mPrePassMatInstance( NULL )
  71. {
  72. notifyType( RenderPassManager::RIT_Decal );
  73. notifyType( RenderPassManager::RIT_Mesh );
  74. notifyType( RenderPassManager::RIT_Terrain );
  75. notifyType( RenderPassManager::RIT_Object );
  76. // We want a full-resolution buffer
  77. mTargetSizeType = RenderTexTargetBinManager::WindowSize;
  78. if(getTargetChainLength() > 0)
  79. GFXShader::addGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  80. mNamedTarget.registerWithName( BufferName );
  81. _registerFeatures();
  82. }
  83. RenderPrePassMgr::~RenderPrePassMgr()
  84. {
  85. GFXShader::removeGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  86. _unregisterFeatures();
  87. SAFE_DELETE( mPrePassMatInstance );
  88. }
  89. void RenderPrePassMgr::_registerFeatures()
  90. {
  91. ConditionerFeature *cond = new LinearEyeDepthConditioner( getTargetFormat() );
  92. FEATUREMGR->registerFeature( MFT_PrePassConditioner, cond );
  93. mNamedTarget.setConditioner( cond );
  94. }
  95. void RenderPrePassMgr::_unregisterFeatures()
  96. {
  97. mNamedTarget.setConditioner( NULL );
  98. FEATUREMGR->unregisterFeature(MFT_PrePassConditioner);
  99. }
  100. bool RenderPrePassMgr::setTargetSize(const Point2I &newTargetSize)
  101. {
  102. bool ret = Parent::setTargetSize( newTargetSize );
  103. mNamedTarget.setViewport( GFX->getViewport() );
  104. return ret;
  105. }
  106. bool RenderPrePassMgr::_updateTargets()
  107. {
  108. PROFILE_SCOPE(RenderPrePassMgr_updateTargets);
  109. bool ret = Parent::_updateTargets();
  110. // check for an output conditioner, and update it's format
  111. ConditionerFeature *outputConditioner = dynamic_cast<ConditionerFeature *>(FEATUREMGR->getByType(MFT_PrePassConditioner));
  112. if( outputConditioner && outputConditioner->setBufferFormat(mTargetFormat) )
  113. {
  114. // reload materials, the conditioner needs to alter the generated shaders
  115. }
  116. // Attach the light info buffer as a second render target, if there is
  117. // lightmapped geometry in the scene.
  118. AdvancedLightBinManager *lightBin;
  119. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) &&
  120. lightBin->MRTLightmapsDuringPrePass() &&
  121. lightBin->isProperlyAdded() )
  122. {
  123. // Update the size of the light bin target here. This will call _updateTargets
  124. // on the light bin
  125. ret &= lightBin->setTargetSize( mTargetSize );
  126. if ( ret )
  127. {
  128. // Sanity check
  129. AssertFatal(lightBin->getTargetChainLength() == mTargetChainLength, "Target chain length mismatch");
  130. // Attach light info buffer to Color1 for each target in the chain
  131. for ( U32 i = 0; i < mTargetChainLength; i++ )
  132. {
  133. GFXTexHandle lightInfoTex = lightBin->getTargetTexture(0, i);
  134. mTargetChain[i]->attachTexture(GFXTextureTarget::Color1, lightInfoTex);
  135. }
  136. }
  137. }
  138. return ret;
  139. }
  140. void RenderPrePassMgr::_createPrePassMaterial()
  141. {
  142. SAFE_DELETE(mPrePassMatInstance);
  143. const GFXVertexFormat *vertexFormat = getGFXVertexFormat<GFXVertexPNTTB>();
  144. MatInstance* prepassMat = static_cast<MatInstance*>(MATMGR->createMatInstance("AL_DefaultPrePassMaterial", vertexFormat));
  145. AssertFatal( prepassMat, "TODO: Handle this better." );
  146. mPrePassMatInstance = new PrePassMatInstance(prepassMat, this);
  147. mPrePassMatInstance->init( MATMGR->getDefaultFeatures(), vertexFormat);
  148. delete prepassMat;
  149. }
  150. void RenderPrePassMgr::setPrePassMaterial( PrePassMatInstance *mat )
  151. {
  152. SAFE_DELETE(mPrePassMatInstance);
  153. mPrePassMatInstance = mat;
  154. }
  155. void RenderPrePassMgr::addElement( RenderInst *inst )
  156. {
  157. PROFILE_SCOPE( RenderPrePassMgr_addElement )
  158. // Skip out if this bin is disabled.
  159. if ( gClientSceneGraph->getCurrentRenderState() &&
  160. gClientSceneGraph->getCurrentRenderState()->disableAdvancedLightingBins() )
  161. return;
  162. // First what type of render instance is it?
  163. const bool isDecalMeshInst = inst->type == RenderPassManager::RIT_Decal;
  164. const bool isMeshInst = inst->type == RenderPassManager::RIT_Mesh;
  165. const bool isTerrainInst = inst->type == RenderPassManager::RIT_Terrain;
  166. // Get the material if its a mesh.
  167. BaseMatInstance* matInst = NULL;
  168. if ( isMeshInst || isDecalMeshInst )
  169. matInst = static_cast<MeshRenderInst*>(inst)->matInst;
  170. if (matInst)
  171. {
  172. // Skip decals if they don't have normal maps.
  173. if (isDecalMeshInst && !matInst->hasNormalMap())
  174. return;
  175. // If its a custom material and it refracts... skip it.
  176. if (matInst->isCustomMaterial() &&
  177. static_cast<CustomMaterial*>(matInst->getMaterial())->mRefract)
  178. return;
  179. // Make sure we got a prepass material.
  180. matInst = getPrePassMaterial(matInst);
  181. if (!matInst || !matInst->isValid())
  182. return;
  183. }
  184. // We're gonna add it to the bin... get the right element list.
  185. Vector< MainSortElem > *elementList;
  186. if ( isMeshInst || isDecalMeshInst )
  187. elementList = &mElementList;
  188. else if ( isTerrainInst )
  189. elementList = &mTerrainElementList;
  190. else
  191. elementList = &mObjectElementList;
  192. elementList->increment();
  193. MainSortElem &elem = elementList->last();
  194. elem.inst = inst;
  195. // Store the original key... we might need it.
  196. U32 originalKey = elem.key;
  197. // Sort front-to-back first to get the most fillrate savings.
  198. const F32 invSortDistSq = F32_MAX - inst->sortDistSq;
  199. elem.key = *((U32*)&invSortDistSq);
  200. // Next sort by pre-pass material if its a mesh... use the original sort key.
  201. if (isMeshInst && matInst)
  202. elem.key2 = matInst->getStateHint();
  203. else
  204. elem.key2 = originalKey;
  205. }
  206. void RenderPrePassMgr::sort()
  207. {
  208. PROFILE_SCOPE( RenderPrePassMgr_sort );
  209. Parent::sort();
  210. dQsort( mTerrainElementList.address(), mTerrainElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  211. dQsort( mObjectElementList.address(), mObjectElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  212. }
  213. void RenderPrePassMgr::clear()
  214. {
  215. Parent::clear();
  216. mTerrainElementList.clear();
  217. mObjectElementList.clear();
  218. }
  219. void RenderPrePassMgr::render( SceneRenderState *state )
  220. {
  221. PROFILE_SCOPE(RenderPrePassMgr_render);
  222. // Take a look at the SceneRenderState and see if we should skip drawing the pre-pass
  223. if ( state->disableAdvancedLightingBins() )
  224. return;
  225. // NOTE: We don't early out here when the element list is
  226. // zero because we need the prepass to be cleared.
  227. // Automagically save & restore our viewport and transforms.
  228. GFXTransformSaver saver;
  229. GFXDEBUGEVENT_SCOPE( RenderPrePassMgr_Render, ColorI::RED );
  230. // Tell the superclass we're about to render
  231. const bool isRenderingToTarget = _onPreRender(state);
  232. // Clear all the buffers to white so that the
  233. // default depth is to the far plane.
  234. GFX->clear( GFXClearTarget | GFXClearZBuffer | GFXClearStencil, ColorI::WHITE, 1.0f, 0);
  235. // Restore transforms
  236. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  237. matrixSet.restoreSceneViewProjection();
  238. const MatrixF worldViewXfm = GFX->getWorldMatrix();
  239. // Setup the default prepass material for object instances.
  240. if ( !mPrePassMatInstance )
  241. _createPrePassMaterial();
  242. if ( mPrePassMatInstance )
  243. {
  244. matrixSet.setWorld(MatrixF::Identity);
  245. mPrePassMatInstance->setTransforms(matrixSet, state);
  246. }
  247. // Signal start of pre-pass
  248. getRenderSignal().trigger( state, this, true );
  249. // First do a loop and render all the terrain... these are
  250. // usually the big blockers in a scene and will save us fillrate
  251. // on the smaller meshes and objects.
  252. // The terrain doesn't need any scene graph data
  253. // in the the prepass... so just clear it.
  254. SceneData sgData;
  255. sgData.init( state, SceneData::PrePassBin );
  256. Vector< MainSortElem >::const_iterator itr = mTerrainElementList.begin();
  257. for ( ; itr != mTerrainElementList.end(); itr++ )
  258. {
  259. TerrainRenderInst *ri = static_cast<TerrainRenderInst*>( itr->inst );
  260. TerrainCellMaterial *mat = ri->cellMat->getPrePassMat();
  261. GFX->setPrimitiveBuffer( ri->primBuff );
  262. GFX->setVertexBuffer( ri->vertBuff );
  263. mat->setTransformAndEye( *ri->objectToWorldXfm,
  264. worldViewXfm,
  265. GFX->getProjectionMatrix(),
  266. state->getFarPlane() );
  267. while ( mat->setupPass( state, sgData ) )
  268. GFX->drawPrimitive( ri->prim );
  269. }
  270. // Next render all the meshes.
  271. itr = mElementList.begin();
  272. for ( ; itr != mElementList.end(); )
  273. {
  274. MeshRenderInst *ri = static_cast<MeshRenderInst*>( itr->inst );
  275. // Get the prepass material.
  276. BaseMatInstance *mat = getPrePassMaterial( ri->matInst );
  277. // Set up SG data proper like and flag it
  278. // as a pre-pass render
  279. setupSGData( ri, sgData );
  280. Vector< MainSortElem >::const_iterator meshItr, endOfBatchItr = itr;
  281. while ( mat->setupPass( state, sgData ) )
  282. {
  283. meshItr = itr;
  284. for ( ; meshItr != mElementList.end(); meshItr++ )
  285. {
  286. MeshRenderInst *passRI = static_cast<MeshRenderInst*>( meshItr->inst );
  287. // Check to see if we need to break this batch.
  288. //
  289. // NOTE: We're comparing the non-prepass materials
  290. // here so we don't incur the cost of looking up the
  291. // prepass hook on each inst.
  292. //
  293. if ( newPassNeeded( ri, passRI ) )
  294. break;
  295. // Set up SG data for this instance.
  296. setupSGData( passRI, sgData );
  297. matrixSet.setWorld(*passRI->objectToWorld);
  298. matrixSet.setView(*passRI->worldToCamera);
  299. matrixSet.setProjection(*passRI->projection);
  300. mat->setSceneInfo(state, sgData);
  301. mat->setTransforms(matrixSet, state);
  302. // If we're instanced then don't render yet.
  303. if ( mat->isInstanced() )
  304. {
  305. // Let the material increment the instance buffer, but
  306. // break the batch if it runs out of room for more.
  307. if ( !mat->stepInstance() )
  308. {
  309. meshItr++;
  310. break;
  311. }
  312. continue;
  313. }
  314. // Setup the vertex and index buffers.
  315. mat->setBuffers( passRI->vertBuff, passRI->primBuff );
  316. // Render this sucker.
  317. if ( passRI->prim )
  318. GFX->drawPrimitive( *passRI->prim );
  319. else
  320. GFX->drawPrimitive( passRI->primBuffIndex );
  321. }
  322. // Draw the instanced batch.
  323. if ( mat->isInstanced() )
  324. {
  325. // Sets the buffers including the instancing stream.
  326. mat->setBuffers( ri->vertBuff, ri->primBuff );
  327. if ( ri->prim )
  328. GFX->drawPrimitive( *ri->prim );
  329. else
  330. GFX->drawPrimitive( ri->primBuffIndex );
  331. }
  332. endOfBatchItr = meshItr;
  333. } // while( mat->setupPass(state, sgData) )
  334. // Force the increment if none happened, otherwise go to end of batch.
  335. itr = ( itr == endOfBatchItr ) ? itr + 1 : endOfBatchItr;
  336. }
  337. // The final loop is for object render instances.
  338. itr = mObjectElementList.begin();
  339. for ( ; itr != mObjectElementList.end(); itr++ )
  340. {
  341. ObjectRenderInst *ri = static_cast<ObjectRenderInst*>( itr->inst );
  342. if ( ri->renderDelegate )
  343. ri->renderDelegate( ri, state, mPrePassMatInstance );
  344. }
  345. // Signal end of pre-pass
  346. getRenderSignal().trigger( state, this, false );
  347. if(isRenderingToTarget)
  348. _onPostRender();
  349. }
  350. const GFXStateBlockDesc & RenderPrePassMgr::getOpaqueStenciWriteDesc( bool lightmappedGeometry /*= true*/ )
  351. {
  352. static bool sbInit = false;
  353. static GFXStateBlockDesc sOpaqueStaticLitStencilWriteDesc;
  354. static GFXStateBlockDesc sOpaqueDynamicLitStencilWriteDesc;
  355. if(!sbInit)
  356. {
  357. sbInit = true;
  358. // Build the static opaque stencil write/test state block descriptions
  359. sOpaqueStaticLitStencilWriteDesc.stencilDefined = true;
  360. sOpaqueStaticLitStencilWriteDesc.stencilEnable = true;
  361. sOpaqueStaticLitStencilWriteDesc.stencilWriteMask = 0x03;
  362. sOpaqueStaticLitStencilWriteDesc.stencilMask = 0x03;
  363. sOpaqueStaticLitStencilWriteDesc.stencilRef = RenderPrePassMgr::OpaqueStaticLitMask;
  364. sOpaqueStaticLitStencilWriteDesc.stencilPassOp = GFXStencilOpReplace;
  365. sOpaqueStaticLitStencilWriteDesc.stencilFailOp = GFXStencilOpKeep;
  366. sOpaqueStaticLitStencilWriteDesc.stencilZFailOp = GFXStencilOpKeep;
  367. sOpaqueStaticLitStencilWriteDesc.stencilFunc = GFXCmpAlways;
  368. // Same only dynamic
  369. sOpaqueDynamicLitStencilWriteDesc = sOpaqueStaticLitStencilWriteDesc;
  370. sOpaqueDynamicLitStencilWriteDesc.stencilRef = RenderPrePassMgr::OpaqueDynamicLitMask;
  371. }
  372. return (lightmappedGeometry ? sOpaqueStaticLitStencilWriteDesc : sOpaqueDynamicLitStencilWriteDesc);
  373. }
  374. const GFXStateBlockDesc & RenderPrePassMgr::getOpaqueStencilTestDesc()
  375. {
  376. static bool sbInit = false;
  377. static GFXStateBlockDesc sOpaqueStencilTestDesc;
  378. if(!sbInit)
  379. {
  380. // Build opaque test
  381. sbInit = true;
  382. sOpaqueStencilTestDesc.stencilDefined = true;
  383. sOpaqueStencilTestDesc.stencilEnable = true;
  384. sOpaqueStencilTestDesc.stencilWriteMask = 0xFE;
  385. sOpaqueStencilTestDesc.stencilMask = 0x03;
  386. sOpaqueStencilTestDesc.stencilRef = 0;
  387. sOpaqueStencilTestDesc.stencilPassOp = GFXStencilOpKeep;
  388. sOpaqueStencilTestDesc.stencilFailOp = GFXStencilOpKeep;
  389. sOpaqueStencilTestDesc.stencilZFailOp = GFXStencilOpKeep;
  390. sOpaqueStencilTestDesc.stencilFunc = GFXCmpLess;
  391. }
  392. return sOpaqueStencilTestDesc;
  393. }
  394. //------------------------------------------------------------------------------
  395. //------------------------------------------------------------------------------
  396. ProcessedPrePassMaterial::ProcessedPrePassMaterial( Material& mat, const RenderPrePassMgr *prePassMgr )
  397. : Parent(mat), mPrePassMgr(prePassMgr)
  398. {
  399. }
  400. void ProcessedPrePassMaterial::_determineFeatures( U32 stageNum,
  401. MaterialFeatureData &fd,
  402. const FeatureSet &features )
  403. {
  404. Parent::_determineFeatures( stageNum, fd, features );
  405. // Find this for use down below...
  406. bool bEnableMRTLightmap = false;
  407. AdvancedLightBinManager *lightBin;
  408. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) )
  409. bEnableMRTLightmap = lightBin->MRTLightmapsDuringPrePass();
  410. // If this material has a lightmap or tonemap (texture or baked vertex color),
  411. // it must be static. Otherwise it is dynamic.
  412. mIsLightmappedGeometry = ( fd.features.hasFeature( MFT_ToneMap ) ||
  413. fd.features.hasFeature( MFT_LightMap ) ||
  414. fd.features.hasFeature( MFT_VertLit ) ||
  415. ( bEnableMRTLightmap && fd.features.hasFeature( MFT_IsTranslucent ) ||
  416. fd.features.hasFeature( MFT_ForwardShading ) ||
  417. fd.features.hasFeature( MFT_IsTranslucentZWrite ) ) );
  418. // Integrate proper opaque stencil write state
  419. mUserDefined.addDesc( mPrePassMgr->getOpaqueStenciWriteDesc( mIsLightmappedGeometry ) );
  420. FeatureSet newFeatures;
  421. // These are always on for prepass.
  422. newFeatures.addFeature( MFT_EyeSpaceDepthOut );
  423. newFeatures.addFeature( MFT_PrePassConditioner );
  424. #ifndef TORQUE_DEDICATED
  425. for ( U32 i=0; i < fd.features.getCount(); i++ )
  426. {
  427. const FeatureType &type = fd.features.getAt( i );
  428. // Turn on the diffuse texture only if we
  429. // have alpha test.
  430. if ( type == MFT_AlphaTest )
  431. {
  432. newFeatures.addFeature( MFT_AlphaTest );
  433. newFeatures.addFeature( MFT_DiffuseMap );
  434. }
  435. else if ( type == MFT_IsTranslucentZWrite )
  436. {
  437. newFeatures.addFeature( MFT_IsTranslucentZWrite );
  438. newFeatures.addFeature( MFT_DiffuseMap );
  439. }
  440. // Always allow these.
  441. else if ( type == MFT_IsDXTnm ||
  442. type == MFT_TexAnim ||
  443. type == MFT_NormalMap ||
  444. type == MFT_DetailNormalMap ||
  445. type == MFT_AlphaTest ||
  446. type == MFT_Parallax ||
  447. type == MFT_InterlacedPrePass ||
  448. type == MFT_Visibility ||
  449. type == MFT_UseInstancing ||
  450. type == MFT_DiffuseVertColor )
  451. newFeatures.addFeature( type );
  452. // Add any transform features.
  453. else if ( type.getGroup() == MFG_PreTransform ||
  454. type.getGroup() == MFG_Transform ||
  455. type.getGroup() == MFG_PostTransform )
  456. newFeatures.addFeature( type );
  457. }
  458. // If there is lightmapped geometry support, add the MRT light buffer features
  459. if(bEnableMRTLightmap)
  460. {
  461. // If this material has a lightmap, pass it through, and flag it to
  462. // send it's output to RenderTarget1
  463. if( fd.features.hasFeature( MFT_ToneMap ) )
  464. {
  465. newFeatures.addFeature( MFT_ToneMap );
  466. newFeatures.addFeature( MFT_LightbufferMRT );
  467. }
  468. else if( fd.features.hasFeature( MFT_LightMap ) )
  469. {
  470. newFeatures.addFeature( MFT_LightMap );
  471. newFeatures.addFeature( MFT_LightbufferMRT );
  472. }
  473. else if( fd.features.hasFeature( MFT_VertLit ) )
  474. {
  475. // Flag un-tone-map if necesasary
  476. if( fd.features.hasFeature( MFT_DiffuseMap ) )
  477. newFeatures.addFeature( MFT_VertLitTone );
  478. newFeatures.addFeature( MFT_VertLit );
  479. newFeatures.addFeature( MFT_LightbufferMRT );
  480. }
  481. else
  482. {
  483. // If this object isn't lightmapped, add a zero-output feature to it
  484. newFeatures.addFeature( MFT_RenderTarget1_Zero );
  485. }
  486. }
  487. #endif
  488. // Set the new features.
  489. fd.features = newFeatures;
  490. }
  491. U32 ProcessedPrePassMaterial::getNumStages()
  492. {
  493. // Return 1 stage so this material gets processed for sure
  494. return 1;
  495. }
  496. void ProcessedPrePassMaterial::addStateBlockDesc(const GFXStateBlockDesc& desc)
  497. {
  498. GFXStateBlockDesc prePassStateBlock = desc;
  499. // Adjust color writes if this is a pure z-fill pass
  500. const bool pixelOutEnabled = mPrePassMgr->getTargetChainLength() > 0;
  501. if ( !pixelOutEnabled )
  502. {
  503. prePassStateBlock.colorWriteDefined = true;
  504. prePassStateBlock.colorWriteRed = pixelOutEnabled;
  505. prePassStateBlock.colorWriteGreen = pixelOutEnabled;
  506. prePassStateBlock.colorWriteBlue = pixelOutEnabled;
  507. prePassStateBlock.colorWriteAlpha = pixelOutEnabled;
  508. }
  509. // Never allow the alpha test state when rendering
  510. // the prepass as we use the alpha channel for the
  511. // depth information... MFT_AlphaTest will handle it.
  512. prePassStateBlock.alphaDefined = true;
  513. prePassStateBlock.alphaTestEnable = false;
  514. // If we're translucent then we're doing prepass blending
  515. // which never writes to the depth channels.
  516. const bool isTranslucent = getMaterial()->isTranslucent();
  517. if ( isTranslucent )
  518. {
  519. prePassStateBlock.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  520. prePassStateBlock.setColorWrites( true, true, false, false );
  521. }
  522. // Enable z reads, but only enable zwrites if we're not translucent.
  523. prePassStateBlock.setZReadWrite( true, isTranslucent ? false : true );
  524. // Pass to parent
  525. Parent::addStateBlockDesc(prePassStateBlock);
  526. }
  527. PrePassMatInstance::PrePassMatInstance(MatInstance* root, const RenderPrePassMgr *prePassMgr)
  528. : Parent(*root->getMaterial()), mPrePassMgr(prePassMgr)
  529. {
  530. mFeatureList = root->getRequestedFeatures();
  531. mVertexFormat = root->getVertexFormat();
  532. mUserObject = root->getUserObject();
  533. }
  534. PrePassMatInstance::~PrePassMatInstance()
  535. {
  536. }
  537. ProcessedMaterial* PrePassMatInstance::getShaderMaterial()
  538. {
  539. return new ProcessedPrePassMaterial(*mMaterial, mPrePassMgr);
  540. }
  541. bool PrePassMatInstance::init( const FeatureSet &features,
  542. const GFXVertexFormat *vertexFormat )
  543. {
  544. return Parent::init( features, vertexFormat );
  545. }
  546. PrePassMatInstanceHook::PrePassMatInstanceHook( MatInstance *baseMatInst,
  547. const RenderPrePassMgr *prePassMgr )
  548. : mHookedPrePassMatInst(NULL), mPrePassManager(prePassMgr)
  549. {
  550. // If the material is a custom material then
  551. // hope that using DefaultPrePassMaterial gives
  552. // them a good prepass.
  553. if ( baseMatInst->isCustomMaterial() )
  554. {
  555. MatInstance* dummyInst = static_cast<MatInstance*>( MATMGR->createMatInstance( "AL_DefaultPrePassMaterial", baseMatInst->getVertexFormat() ) );
  556. mHookedPrePassMatInst = new PrePassMatInstance( dummyInst, prePassMgr );
  557. mHookedPrePassMatInst->init( dummyInst->getRequestedFeatures(), baseMatInst->getVertexFormat());
  558. delete dummyInst;
  559. return;
  560. }
  561. // Create the prepass material instance.
  562. mHookedPrePassMatInst = new PrePassMatInstance(baseMatInst, prePassMgr);
  563. mHookedPrePassMatInst->getFeaturesDelegate() = baseMatInst->getFeaturesDelegate();
  564. // Get the features, but remove the instancing feature if the
  565. // original material didn't end up using it.
  566. FeatureSet features = baseMatInst->getRequestedFeatures();
  567. if ( !baseMatInst->isInstanced() )
  568. features.removeFeature( MFT_UseInstancing );
  569. // Initialize the material.
  570. mHookedPrePassMatInst->init(features, baseMatInst->getVertexFormat());
  571. }
  572. PrePassMatInstanceHook::~PrePassMatInstanceHook()
  573. {
  574. SAFE_DELETE(mHookedPrePassMatInst);
  575. }
  576. //------------------------------------------------------------------------------
  577. //------------------------------------------------------------------------------
  578. void LinearEyeDepthConditioner::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd )
  579. {
  580. // find depth
  581. ShaderFeature *depthFeat = FEATUREMGR->getByType( MFT_EyeSpaceDepthOut );
  582. AssertFatal( depthFeat != NULL, "No eye space depth feature found!" );
  583. Var *depth = (Var*) LangElement::find(depthFeat->getOutputVarName());
  584. AssertFatal( depth, "Something went bad with ShaderGen. The depth should be already generated by the EyeSpaceDepthOut feature." );
  585. MultiLine *meta = new MultiLine;
  586. meta->addStatement( assignOutput( depth ) );
  587. output = meta;
  588. }
  589. Var *LinearEyeDepthConditioner::_conditionOutput( Var *unconditionedOutput, MultiLine *meta )
  590. {
  591. Var *retVar = NULL;
  592. String fracMethodName = (GFX->getAdapterType() == OpenGL) ? "fract" : "frac";
  593. switch(getBufferFormat())
  594. {
  595. case GFXFormatR8G8B8A8:
  596. retVar = new Var;
  597. retVar->setType("float4");
  598. retVar->setName("_ppDepth");
  599. meta->addStatement( new GenOp( " // depth conditioner: packing to rgba\r\n" ) );
  600. meta->addStatement( new GenOp(
  601. avar( " @ = %s(@ * (255.0/256) * float4(1, 255, 255 * 255, 255 * 255 * 255));\r\n", fracMethodName.c_str() ),
  602. new DecOp(retVar), unconditionedOutput ) );
  603. break;
  604. default:
  605. retVar = unconditionedOutput;
  606. meta->addStatement( new GenOp( " // depth conditioner: no conditioning\r\n" ) );
  607. break;
  608. }
  609. AssertFatal( retVar != NULL, avar( "Cannot condition output to buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  610. return retVar;
  611. }
  612. Var *LinearEyeDepthConditioner::_unconditionInput( Var *conditionedInput, MultiLine *meta )
  613. {
  614. String float4Typename = (GFX->getAdapterType() == OpenGL) ? "vec4" : "float4";
  615. Var *retVar = conditionedInput;
  616. if(getBufferFormat() != GFXFormat_COUNT)
  617. {
  618. retVar = new Var;
  619. retVar->setType(float4Typename.c_str());
  620. retVar->setName("_ppDepth");
  621. meta->addStatement( new GenOp( avar( " @ = %s(0, 0, 1, 1);\r\n", float4Typename.c_str() ), new DecOp(retVar) ) );
  622. switch(getBufferFormat())
  623. {
  624. case GFXFormatR32F:
  625. case GFXFormatR16F:
  626. meta->addStatement( new GenOp( " // depth conditioner: float texture\r\n" ) );
  627. meta->addStatement( new GenOp( " @.w = @.r;\r\n", retVar, conditionedInput ) );
  628. break;
  629. case GFXFormatR8G8B8A8:
  630. meta->addStatement( new GenOp( " // depth conditioner: unpacking from rgba\r\n" ) );
  631. meta->addStatement( new GenOp(
  632. avar( " @.w = dot(@ * (256.0/255), %s(1, 1 / 255, 1 / (255 * 255), 1 / (255 * 255 * 255)));\r\n", float4Typename.c_str() )
  633. , retVar, conditionedInput ) );
  634. break;
  635. default:
  636. AssertFatal(false, "LinearEyeDepthConditioner::_unconditionInput - Unrecognized buffer format");
  637. }
  638. }
  639. return retVar;
  640. }
  641. Var* LinearEyeDepthConditioner::printMethodHeader( MethodType methodType, const String &methodName, Stream &stream, MultiLine *meta )
  642. {
  643. const bool isCondition = ( methodType == ConditionerFeature::ConditionMethod );
  644. Var *retVal = NULL;
  645. // The uncondition method inputs are changed
  646. if( isCondition )
  647. retVal = Parent::printMethodHeader( methodType, methodName, stream, meta );
  648. else
  649. {
  650. Var *methodVar = new Var;
  651. methodVar->setName(methodName);
  652. if (GFX->getAdapterType() == OpenGL)
  653. methodVar->setType("vec4");
  654. else
  655. methodVar->setType("inline float4");
  656. DecOp *methodDecl = new DecOp(methodVar);
  657. Var *prepassSampler = new Var;
  658. prepassSampler->setName("prepassSamplerVar");
  659. prepassSampler->setType("sampler2D");
  660. DecOp *prepassSamplerDecl = new DecOp(prepassSampler);
  661. Var *screenUV = new Var;
  662. screenUV->setName("screenUVVar");
  663. if (GFX->getAdapterType() == OpenGL)
  664. screenUV->setType("vec2");
  665. else
  666. screenUV->setType("float2");
  667. DecOp *screenUVDecl = new DecOp(screenUV);
  668. Var *bufferSample = new Var;
  669. bufferSample->setName("bufferSample");
  670. if (GFX->getAdapterType() == OpenGL)
  671. bufferSample->setType("vec4");
  672. else
  673. bufferSample->setType("float4");
  674. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  675. meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) );
  676. meta->addStatement( new GenOp( "{\r\n" ) );
  677. meta->addStatement( new GenOp( " // Sampler g-buffer\r\n" ) );
  678. // The linear depth target has no mipmaps, so use tex2dlod when
  679. // possible so that the shader compiler can optimize.
  680. meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) );
  681. if (GFX->getAdapterType() == OpenGL)
  682. meta->addStatement( new GenOp( " @ = textureLod(@, @, 0); \r\n", bufferSampleDecl, prepassSampler, screenUV) );
  683. else
  684. meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  685. meta->addStatement( new GenOp( " #else\r\n" ) );
  686. if (GFX->getAdapterType() == OpenGL)
  687. meta->addStatement( new GenOp( " @ = texture(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV) );
  688. else
  689. meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  690. meta->addStatement( new GenOp( " #endif\r\n\r\n" ) );
  691. // We don't use this way of passing var's around, so this should cause a crash
  692. // if something uses this improperly
  693. retVal = bufferSample;
  694. }
  695. return retVal;
  696. }