renderPrePassMgr.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  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 "gfx/gfxCardProfile.h"
  38. #include "materials/customMaterialDefinition.h"
  39. #include "lighting/advanced/advancedLightManager.h"
  40. #include "lighting/advanced/advancedLightBinManager.h"
  41. #include "terrain/terrCell.h"
  42. #include "renderInstance/renderTerrainMgr.h"
  43. #include "terrain/terrCellMaterial.h"
  44. #include "math/mathUtils.h"
  45. #include "math/util/matrixSet.h"
  46. #include "gfx/gfxTextureManager.h"
  47. #include "gfx/primBuilder.h"
  48. #include "gfx/gfxDrawUtil.h"
  49. #include "materials/shaderData.h"
  50. #include "gfx/sim/cubemapData.h"
  51. const MatInstanceHookType PrePassMatInstanceHook::Type( "PrePass" );
  52. const String RenderPrePassMgr::BufferName("prepass");
  53. const RenderInstType RenderPrePassMgr::RIT_PrePass("PrePass");
  54. const String RenderPrePassMgr::ColorBufferName("color");
  55. const String RenderPrePassMgr::MatInfoBufferName("matinfo");
  56. IMPLEMENT_CONOBJECT(RenderPrePassMgr);
  57. ConsoleDocClass( RenderPrePassMgr,
  58. "@brief The render bin which performs a z+normals prepass used in Advanced Lighting.\n\n"
  59. "This render bin is used in Advanced Lighting to gather all opaque mesh render instances "
  60. "and render them to the g-buffer for use in lighting the scene and doing effects.\n\n"
  61. "PostEffect and other shaders can access the output of this bin by using the #prepass "
  62. "texture target name. See the edge anti-aliasing post effect for an example.\n\n"
  63. "@see game/core/scripts/client/postFx/edgeAA.cs\n"
  64. "@ingroup RenderBin\n" );
  65. RenderPrePassMgr::RenderSignal& RenderPrePassMgr::getRenderSignal()
  66. {
  67. static RenderSignal theSignal;
  68. return theSignal;
  69. }
  70. RenderPrePassMgr::RenderPrePassMgr( bool gatherDepth,
  71. GFXFormat format )
  72. : Parent( RIT_PrePass,
  73. 0.01f,
  74. 0.01f,
  75. format,
  76. Point2I( Parent::DefaultTargetSize, Parent::DefaultTargetSize),
  77. gatherDepth ? Parent::DefaultTargetChainLength : 0 ),
  78. mPrePassMatInstance( NULL )
  79. {
  80. notifyType( RenderPassManager::RIT_Decal );
  81. notifyType( RenderPassManager::RIT_DecalRoad );
  82. notifyType( RenderPassManager::RIT_Mesh );
  83. notifyType( RenderPassManager::RIT_Terrain );
  84. notifyType( RenderPassManager::RIT_Object );
  85. // We want a full-resolution buffer
  86. mTargetSizeType = RenderTexTargetBinManager::WindowSize;
  87. if(getTargetChainLength() > 0)
  88. GFXShader::addGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  89. mNamedTarget.registerWithName( BufferName );
  90. mColorTarget.registerWithName( ColorBufferName );
  91. mMatInfoTarget.registerWithName( MatInfoBufferName );
  92. mClearGBufferShader = NULL;
  93. _registerFeatures();
  94. }
  95. RenderPrePassMgr::~RenderPrePassMgr()
  96. {
  97. GFXShader::removeGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  98. mColorTarget.release();
  99. mMatInfoTarget.release();
  100. _unregisterFeatures();
  101. SAFE_DELETE( mPrePassMatInstance );
  102. }
  103. void RenderPrePassMgr::_registerFeatures()
  104. {
  105. ConditionerFeature *cond = new LinearEyeDepthConditioner( getTargetFormat() );
  106. FEATUREMGR->registerFeature( MFT_PrePassConditioner, cond );
  107. mNamedTarget.setConditioner( cond );
  108. }
  109. void RenderPrePassMgr::_unregisterFeatures()
  110. {
  111. mNamedTarget.setConditioner( NULL );
  112. FEATUREMGR->unregisterFeature(MFT_PrePassConditioner);
  113. }
  114. bool RenderPrePassMgr::setTargetSize(const Point2I &newTargetSize)
  115. {
  116. bool ret = Parent::setTargetSize( newTargetSize );
  117. mNamedTarget.setViewport( GFX->getViewport() );
  118. mColorTarget.setViewport( GFX->getViewport() );
  119. mMatInfoTarget.setViewport( GFX->getViewport() );
  120. return ret;
  121. }
  122. bool RenderPrePassMgr::_updateTargets()
  123. {
  124. PROFILE_SCOPE(RenderPrePassMgr_updateTargets);
  125. bool ret = Parent::_updateTargets();
  126. // check for an output conditioner, and update it's format
  127. ConditionerFeature *outputConditioner = dynamic_cast<ConditionerFeature *>(FEATUREMGR->getByType(MFT_PrePassConditioner));
  128. if( outputConditioner && outputConditioner->setBufferFormat(mTargetFormat) )
  129. {
  130. // reload materials, the conditioner needs to alter the generated shaders
  131. }
  132. GFXFormat colorFormat = mTargetFormat;
  133. /*
  134. bool independentMrtBitDepth = GFX->getCardProfiler()->queryProfile("independentMrtBitDepth", false);
  135. //If independent bit depth on a MRT is supported than just use 8bit channels for the albedo color.
  136. if(independentMrtBitDepth)
  137. colorFormat = GFXFormatR8G8B8A8;
  138. */
  139. // andrewmac: Deferred Shading Color Buffer
  140. if (mColorTex.getFormat() != colorFormat || mColorTex.getWidthHeight() != mTargetSize || GFX->recentlyReset())
  141. {
  142. mColorTarget.release();
  143. mColorTex.set(mTargetSize.x, mTargetSize.y, colorFormat,
  144. &GFXDefaultRenderTargetProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__),
  145. 1, GFXTextureManager::AA_MATCH_BACKBUFFER);
  146. mColorTarget.setTexture(mColorTex);
  147. for (U32 i = 0; i < mTargetChainLength; i++)
  148. mTargetChain[i]->attachTexture(GFXTextureTarget::Color1, mColorTarget.getTexture());
  149. }
  150. // andrewmac: Deferred Shading Material Info Buffer
  151. if (mMatInfoTex.getFormat() != colorFormat || mMatInfoTex.getWidthHeight() != mTargetSize || GFX->recentlyReset())
  152. {
  153. mMatInfoTarget.release();
  154. mMatInfoTex.set(mTargetSize.x, mTargetSize.y, colorFormat,
  155. &GFXDefaultRenderTargetProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__),
  156. 1, GFXTextureManager::AA_MATCH_BACKBUFFER);
  157. mMatInfoTarget.setTexture(mMatInfoTex);
  158. for (U32 i = 0; i < mTargetChainLength; i++)
  159. mTargetChain[i]->attachTexture(GFXTextureTarget::Color2, mMatInfoTarget.getTexture());
  160. }
  161. GFX->finalizeReset();
  162. // Attach the light info buffer as a second render target, if there is
  163. // lightmapped geometry in the scene.
  164. AdvancedLightBinManager *lightBin;
  165. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) &&
  166. lightBin->MRTLightmapsDuringPrePass() &&
  167. lightBin->isProperlyAdded() )
  168. {
  169. // Update the size of the light bin target here. This will call _updateTargets
  170. // on the light bin
  171. ret &= lightBin->setTargetSize( mTargetSize );
  172. if ( ret )
  173. {
  174. // Sanity check
  175. AssertFatal(lightBin->getTargetChainLength() == mTargetChainLength, "Target chain length mismatch");
  176. // Attach light info buffer to Color1 for each target in the chain
  177. for ( U32 i = 0; i < mTargetChainLength; i++ )
  178. {
  179. GFXTexHandle lightInfoTex = lightBin->getTargetTexture(0, i);
  180. mTargetChain[i]->attachTexture(GFXTextureTarget::Color3, lightInfoTex);
  181. }
  182. }
  183. }
  184. _initShaders();
  185. return ret;
  186. }
  187. void RenderPrePassMgr::_createPrePassMaterial()
  188. {
  189. SAFE_DELETE(mPrePassMatInstance);
  190. const GFXVertexFormat *vertexFormat = getGFXVertexFormat<GFXVertexPNTTB>();
  191. MatInstance* prepassMat = static_cast<MatInstance*>(MATMGR->createMatInstance("AL_DefaultPrePassMaterial", vertexFormat));
  192. AssertFatal( prepassMat, "TODO: Handle this better." );
  193. mPrePassMatInstance = new PrePassMatInstance(prepassMat, this);
  194. mPrePassMatInstance->init( MATMGR->getDefaultFeatures(), vertexFormat);
  195. delete prepassMat;
  196. }
  197. void RenderPrePassMgr::setPrePassMaterial( PrePassMatInstance *mat )
  198. {
  199. SAFE_DELETE(mPrePassMatInstance);
  200. mPrePassMatInstance = mat;
  201. }
  202. void RenderPrePassMgr::addElement( RenderInst *inst )
  203. {
  204. PROFILE_SCOPE( RenderPrePassMgr_addElement )
  205. // Skip out if this bin is disabled.
  206. if ( gClientSceneGraph->getCurrentRenderState() &&
  207. gClientSceneGraph->getCurrentRenderState()->disableAdvancedLightingBins() )
  208. return;
  209. // First what type of render instance is it?
  210. const bool isDecalMeshInst = ((inst->type == RenderPassManager::RIT_Decal)||(inst->type == RenderPassManager::RIT_DecalRoad));
  211. const bool isMeshInst = inst->type == RenderPassManager::RIT_Mesh;
  212. const bool isTerrainInst = inst->type == RenderPassManager::RIT_Terrain;
  213. // Get the material if its a mesh.
  214. BaseMatInstance* matInst = NULL;
  215. if ( isMeshInst || isDecalMeshInst )
  216. matInst = static_cast<MeshRenderInst*>(inst)->matInst;
  217. if (matInst)
  218. {
  219. // Skip decals if they don't have normal maps.
  220. if (isDecalMeshInst && !matInst->hasNormalMap())
  221. return;
  222. // If its a custom material and it refracts... skip it.
  223. if (matInst->isCustomMaterial() &&
  224. static_cast<CustomMaterial*>(matInst->getMaterial())->mRefract)
  225. return;
  226. // Make sure we got a prepass material.
  227. matInst = getPrePassMaterial(matInst);
  228. if (!matInst || !matInst->isValid())
  229. return;
  230. }
  231. // We're gonna add it to the bin... get the right element list.
  232. Vector< MainSortElem > *elementList;
  233. if ( isMeshInst || isDecalMeshInst )
  234. elementList = &mElementList;
  235. else if ( isTerrainInst )
  236. elementList = &mTerrainElementList;
  237. else
  238. elementList = &mObjectElementList;
  239. elementList->increment();
  240. MainSortElem &elem = elementList->last();
  241. elem.inst = inst;
  242. // Store the original key... we might need it.
  243. U32 originalKey = elem.key;
  244. // Sort front-to-back first to get the most fillrate savings.
  245. const F32 invSortDistSq = F32_MAX - inst->sortDistSq;
  246. elem.key = *((U32*)&invSortDistSq);
  247. // Next sort by pre-pass material if its a mesh... use the original sort key.
  248. if (isMeshInst && matInst)
  249. elem.key2 = matInst->getStateHint();
  250. else
  251. elem.key2 = originalKey;
  252. }
  253. void RenderPrePassMgr::sort()
  254. {
  255. PROFILE_SCOPE( RenderPrePassMgr_sort );
  256. Parent::sort();
  257. dQsort( mTerrainElementList.address(), mTerrainElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  258. dQsort( mObjectElementList.address(), mObjectElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  259. }
  260. void RenderPrePassMgr::clear()
  261. {
  262. Parent::clear();
  263. mTerrainElementList.clear();
  264. mObjectElementList.clear();
  265. }
  266. void RenderPrePassMgr::render( SceneRenderState *state )
  267. {
  268. PROFILE_SCOPE(RenderPrePassMgr_render);
  269. // Take a look at the SceneRenderState and see if we should skip drawing the pre-pass
  270. if ( state->disableAdvancedLightingBins() )
  271. return;
  272. // NOTE: We don't early out here when the element list is
  273. // zero because we need the prepass to be cleared.
  274. // Automagically save & restore our viewport and transforms.
  275. GFXTransformSaver saver;
  276. GFXDEBUGEVENT_SCOPE( RenderPrePassMgr_Render, ColorI::RED );
  277. // Tell the superclass we're about to render
  278. const bool isRenderingToTarget = _onPreRender(state);
  279. // Clear all z-buffer, and g-buffer.
  280. clearBuffers();
  281. // Restore transforms
  282. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  283. matrixSet.restoreSceneViewProjection();
  284. const MatrixF worldViewXfm = GFX->getWorldMatrix();
  285. // Setup the default prepass material for object instances.
  286. if ( !mPrePassMatInstance )
  287. _createPrePassMaterial();
  288. if ( mPrePassMatInstance )
  289. {
  290. matrixSet.setWorld(MatrixF::Identity);
  291. mPrePassMatInstance->setTransforms(matrixSet, state);
  292. }
  293. // Signal start of pre-pass
  294. getRenderSignal().trigger( state, this, true );
  295. // First do a loop and render all the terrain... these are
  296. // usually the big blockers in a scene and will save us fillrate
  297. // on the smaller meshes and objects.
  298. // The terrain doesn't need any scene graph data
  299. // in the the prepass... so just clear it.
  300. SceneData sgData;
  301. sgData.init( state, SceneData::PrePassBin );
  302. Vector< MainSortElem >::const_iterator itr = mTerrainElementList.begin();
  303. for ( ; itr != mTerrainElementList.end(); itr++ )
  304. {
  305. TerrainRenderInst *ri = static_cast<TerrainRenderInst*>( itr->inst );
  306. TerrainCellMaterial *mat = ri->cellMat->getPrePassMat();
  307. GFX->setPrimitiveBuffer( ri->primBuff );
  308. GFX->setVertexBuffer( ri->vertBuff );
  309. mat->setTransformAndEye( *ri->objectToWorldXfm,
  310. worldViewXfm,
  311. GFX->getProjectionMatrix(),
  312. state->getFarPlane() );
  313. while ( mat->setupPass( state, sgData ) )
  314. GFX->drawPrimitive( ri->prim );
  315. }
  316. // init loop data
  317. GFXTextureObject *lastLM = NULL;
  318. GFXCubemap *lastCubemap = NULL;
  319. GFXTextureObject *lastReflectTex = NULL;
  320. GFXTextureObject *lastMiscTex = NULL;
  321. GFXTextureObject *lastAccuTex = NULL;
  322. // Next render all the meshes.
  323. itr = mElementList.begin();
  324. for ( ; itr != mElementList.end(); )
  325. {
  326. MeshRenderInst *ri = static_cast<MeshRenderInst*>( itr->inst );
  327. // Get the prepass material.
  328. BaseMatInstance *mat = getPrePassMaterial( ri->matInst );
  329. // Set up SG data proper like and flag it
  330. // as a pre-pass render
  331. setupSGData( ri, sgData );
  332. Vector< MainSortElem >::const_iterator meshItr, endOfBatchItr = itr;
  333. while ( mat->setupPass( state, sgData ) )
  334. {
  335. meshItr = itr;
  336. for ( ; meshItr != mElementList.end(); meshItr++ )
  337. {
  338. MeshRenderInst *passRI = static_cast<MeshRenderInst*>( meshItr->inst );
  339. // Check to see if we need to break this batch.
  340. //
  341. // NOTE: We're comparing the non-prepass materials
  342. // here so we don't incur the cost of looking up the
  343. // prepass hook on each inst.
  344. //
  345. if ( newPassNeeded( ri, passRI ) )
  346. break;
  347. // Set up SG data for this instance.
  348. setupSGData( passRI, sgData );
  349. mat->setSceneInfo(state, sgData);
  350. matrixSet.setWorld(*passRI->objectToWorld);
  351. matrixSet.setView(*passRI->worldToCamera);
  352. matrixSet.setProjection(*passRI->projection);
  353. mat->setTransforms(matrixSet, state);
  354. // If we're instanced then don't render yet.
  355. if ( mat->isInstanced() )
  356. {
  357. // Let the material increment the instance buffer, but
  358. // break the batch if it runs out of room for more.
  359. if ( !mat->stepInstance() )
  360. {
  361. meshItr++;
  362. break;
  363. }
  364. continue;
  365. }
  366. bool dirty = false;
  367. // set the lightmaps if different
  368. if( passRI->lightmap && passRI->lightmap != lastLM )
  369. {
  370. sgData.lightmap = passRI->lightmap;
  371. lastLM = passRI->lightmap;
  372. dirty = true;
  373. }
  374. // set the cubemap if different.
  375. if ( passRI->cubemap != lastCubemap )
  376. {
  377. sgData.cubemap = passRI->cubemap;
  378. lastCubemap = passRI->cubemap;
  379. dirty = true;
  380. }
  381. if ( passRI->reflectTex != lastReflectTex )
  382. {
  383. sgData.reflectTex = passRI->reflectTex;
  384. lastReflectTex = passRI->reflectTex;
  385. dirty = true;
  386. }
  387. // Update accumulation texture if it changed.
  388. // Note: accumulation texture can be NULL, and must be updated.
  389. if (passRI->accuTex != lastAccuTex)
  390. {
  391. sgData.accuTex = passRI->accuTex;
  392. lastAccuTex = lastAccuTex;
  393. dirty = true;
  394. }
  395. if ( dirty )
  396. mat->setTextureStages( state, sgData );
  397. // Setup the vertex and index buffers.
  398. mat->setBuffers( passRI->vertBuff, passRI->primBuff );
  399. // Render this sucker.
  400. if ( passRI->prim )
  401. GFX->drawPrimitive( *passRI->prim );
  402. else
  403. GFX->drawPrimitive( passRI->primBuffIndex );
  404. }
  405. // Draw the instanced batch.
  406. if ( mat->isInstanced() )
  407. {
  408. // Sets the buffers including the instancing stream.
  409. mat->setBuffers( ri->vertBuff, ri->primBuff );
  410. if ( ri->prim )
  411. GFX->drawPrimitive( *ri->prim );
  412. else
  413. GFX->drawPrimitive( ri->primBuffIndex );
  414. }
  415. endOfBatchItr = meshItr;
  416. } // while( mat->setupPass(state, sgData) )
  417. // Force the increment if none happened, otherwise go to end of batch.
  418. itr = ( itr == endOfBatchItr ) ? itr + 1 : endOfBatchItr;
  419. }
  420. // The final loop is for object render instances.
  421. itr = mObjectElementList.begin();
  422. for ( ; itr != mObjectElementList.end(); itr++ )
  423. {
  424. ObjectRenderInst *ri = static_cast<ObjectRenderInst*>( itr->inst );
  425. if ( ri->renderDelegate )
  426. ri->renderDelegate( ri, state, mPrePassMatInstance );
  427. }
  428. // Signal end of pre-pass
  429. getRenderSignal().trigger( state, this, false );
  430. if(isRenderingToTarget)
  431. _onPostRender();
  432. }
  433. const GFXStateBlockDesc & RenderPrePassMgr::getOpaqueStenciWriteDesc( bool lightmappedGeometry /*= true*/ )
  434. {
  435. static bool sbInit = false;
  436. static GFXStateBlockDesc sOpaqueStaticLitStencilWriteDesc;
  437. static GFXStateBlockDesc sOpaqueDynamicLitStencilWriteDesc;
  438. if(!sbInit)
  439. {
  440. sbInit = true;
  441. // Build the static opaque stencil write/test state block descriptions
  442. sOpaqueStaticLitStencilWriteDesc.stencilDefined = true;
  443. sOpaqueStaticLitStencilWriteDesc.stencilEnable = true;
  444. sOpaqueStaticLitStencilWriteDesc.stencilWriteMask = 0x03;
  445. sOpaqueStaticLitStencilWriteDesc.stencilMask = 0x03;
  446. sOpaqueStaticLitStencilWriteDesc.stencilRef = RenderPrePassMgr::OpaqueStaticLitMask;
  447. sOpaqueStaticLitStencilWriteDesc.stencilPassOp = GFXStencilOpReplace;
  448. sOpaqueStaticLitStencilWriteDesc.stencilFailOp = GFXStencilOpKeep;
  449. sOpaqueStaticLitStencilWriteDesc.stencilZFailOp = GFXStencilOpKeep;
  450. sOpaqueStaticLitStencilWriteDesc.stencilFunc = GFXCmpAlways;
  451. // Same only dynamic
  452. sOpaqueDynamicLitStencilWriteDesc = sOpaqueStaticLitStencilWriteDesc;
  453. sOpaqueDynamicLitStencilWriteDesc.stencilRef = RenderPrePassMgr::OpaqueDynamicLitMask;
  454. }
  455. return (lightmappedGeometry ? sOpaqueStaticLitStencilWriteDesc : sOpaqueDynamicLitStencilWriteDesc);
  456. }
  457. const GFXStateBlockDesc & RenderPrePassMgr::getOpaqueStencilTestDesc()
  458. {
  459. static bool sbInit = false;
  460. static GFXStateBlockDesc sOpaqueStencilTestDesc;
  461. if(!sbInit)
  462. {
  463. // Build opaque test
  464. sbInit = true;
  465. sOpaqueStencilTestDesc.stencilDefined = true;
  466. sOpaqueStencilTestDesc.stencilEnable = true;
  467. sOpaqueStencilTestDesc.stencilWriteMask = 0xFE;
  468. sOpaqueStencilTestDesc.stencilMask = 0x03;
  469. sOpaqueStencilTestDesc.stencilRef = 0;
  470. sOpaqueStencilTestDesc.stencilPassOp = GFXStencilOpKeep;
  471. sOpaqueStencilTestDesc.stencilFailOp = GFXStencilOpKeep;
  472. sOpaqueStencilTestDesc.stencilZFailOp = GFXStencilOpKeep;
  473. sOpaqueStencilTestDesc.stencilFunc = GFXCmpLess;
  474. }
  475. return sOpaqueStencilTestDesc;
  476. }
  477. //------------------------------------------------------------------------------
  478. //------------------------------------------------------------------------------
  479. ProcessedPrePassMaterial::ProcessedPrePassMaterial( Material& mat, const RenderPrePassMgr *prePassMgr )
  480. : Parent(mat), mPrePassMgr(prePassMgr)
  481. {
  482. }
  483. void ProcessedPrePassMaterial::_determineFeatures( U32 stageNum,
  484. MaterialFeatureData &fd,
  485. const FeatureSet &features )
  486. {
  487. Parent::_determineFeatures( stageNum, fd, features );
  488. // Find this for use down below...
  489. bool bEnableMRTLightmap = false;
  490. AdvancedLightBinManager *lightBin;
  491. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) )
  492. bEnableMRTLightmap = lightBin->MRTLightmapsDuringPrePass();
  493. // If this material has a lightmap or tonemap (texture or baked vertex color),
  494. // it must be static. Otherwise it is dynamic.
  495. mIsLightmappedGeometry = ( fd.features.hasFeature( MFT_ToneMap ) ||
  496. fd.features.hasFeature( MFT_LightMap ) ||
  497. fd.features.hasFeature( MFT_VertLit ) ||
  498. ( bEnableMRTLightmap && fd.features.hasFeature( MFT_IsTranslucent ) ||
  499. fd.features.hasFeature( MFT_ForwardShading ) ||
  500. fd.features.hasFeature( MFT_IsTranslucentZWrite ) ) );
  501. // Integrate proper opaque stencil write state
  502. mUserDefined.addDesc( mPrePassMgr->getOpaqueStenciWriteDesc( mIsLightmappedGeometry ) );
  503. FeatureSet newFeatures;
  504. // These are always on for prepass.
  505. newFeatures.addFeature( MFT_EyeSpaceDepthOut );
  506. newFeatures.addFeature( MFT_PrePassConditioner );
  507. #ifndef TORQUE_DEDICATED
  508. //tag all materials running through prepass as deferred
  509. newFeatures.addFeature(MFT_isDeferred);
  510. // Deferred Shading : Diffuse
  511. if (mStages[stageNum].getTex( MFT_DiffuseMap ))
  512. {
  513. newFeatures.addFeature(MFT_DiffuseMap);
  514. }
  515. newFeatures.addFeature( MFT_DiffuseColor );
  516. // Deferred Shading : Specular
  517. if( mStages[stageNum].getTex( MFT_SpecularMap ) )
  518. {
  519. newFeatures.addFeature( MFT_DeferredSpecMap );
  520. }
  521. else if ( mMaterial->mPixelSpecular[stageNum] )
  522. {
  523. newFeatures.addFeature( MFT_DeferredSpecVars );
  524. }
  525. else
  526. newFeatures.addFeature(MFT_DeferredEmptySpec);
  527. // Deferred Shading : Material Info Flags
  528. newFeatures.addFeature( MFT_DeferredMatInfoFlags );
  529. for ( U32 i=0; i < fd.features.getCount(); i++ )
  530. {
  531. const FeatureType &type = fd.features.getAt( i );
  532. // Turn on the diffuse texture only if we
  533. // have alpha test.
  534. if ( type == MFT_AlphaTest )
  535. {
  536. newFeatures.addFeature( MFT_AlphaTest );
  537. newFeatures.addFeature( MFT_DiffuseMap );
  538. }
  539. else if ( type == MFT_IsTranslucentZWrite )
  540. {
  541. newFeatures.addFeature( MFT_IsTranslucentZWrite );
  542. newFeatures.addFeature( MFT_DiffuseMap );
  543. }
  544. // Always allow these.
  545. else if ( type == MFT_IsDXTnm ||
  546. type == MFT_TexAnim ||
  547. type == MFT_NormalMap ||
  548. type == MFT_DetailNormalMap ||
  549. type == MFT_AlphaTest ||
  550. type == MFT_Parallax ||
  551. type == MFT_InterlacedPrePass ||
  552. type == MFT_Visibility ||
  553. type == MFT_UseInstancing ||
  554. type == MFT_DiffuseVertColor ||
  555. type == MFT_DetailMap ||
  556. type == MFT_DetailNormalMap ||
  557. type == MFT_DiffuseMapAtlas)
  558. newFeatures.addFeature( type );
  559. // Add any transform features.
  560. else if ( type.getGroup() == MFG_PreTransform ||
  561. type.getGroup() == MFG_Transform ||
  562. type.getGroup() == MFG_PostTransform )
  563. newFeatures.addFeature( type );
  564. }
  565. if (mMaterial->mAccuEnabled[stageNum])
  566. {
  567. newFeatures.addFeature(MFT_AccuMap);
  568. mHasAccumulation = true;
  569. }
  570. // we need both diffuse and normal maps + sm3 to have an accu map
  571. if (newFeatures[MFT_AccuMap] &&
  572. (!newFeatures[MFT_DiffuseMap] ||
  573. !newFeatures[MFT_NormalMap] ||
  574. GFX->getPixelShaderVersion() < 3.0f)) {
  575. AssertWarn(false, "SAHARA: Using an Accu Map requires SM 3.0 and a normal map.");
  576. newFeatures.removeFeature(MFT_AccuMap);
  577. mHasAccumulation = false;
  578. }
  579. // if we still have the AccuMap feature, we add all accu constant features
  580. if (newFeatures[MFT_AccuMap]) {
  581. // add the dependencies of the accu map
  582. newFeatures.addFeature(MFT_AccuScale);
  583. newFeatures.addFeature(MFT_AccuDirection);
  584. newFeatures.addFeature(MFT_AccuStrength);
  585. newFeatures.addFeature(MFT_AccuCoverage);
  586. newFeatures.addFeature(MFT_AccuSpecular);
  587. // now remove some features that are not compatible with this
  588. newFeatures.removeFeature(MFT_UseInstancing);
  589. }
  590. // If there is lightmapped geometry support, add the MRT light buffer features
  591. if(bEnableMRTLightmap)
  592. {
  593. // If this material has a lightmap, pass it through, and flag it to
  594. // send it's output to RenderTarget3
  595. if( fd.features.hasFeature( MFT_ToneMap ) )
  596. {
  597. newFeatures.addFeature( MFT_ToneMap );
  598. newFeatures.addFeature( MFT_LightbufferMRT );
  599. }
  600. else if( fd.features.hasFeature( MFT_LightMap ) )
  601. {
  602. newFeatures.addFeature( MFT_LightMap );
  603. newFeatures.addFeature( MFT_LightbufferMRT );
  604. }
  605. else if( fd.features.hasFeature( MFT_VertLit ) )
  606. {
  607. // Flag un-tone-map if necesasary
  608. if( fd.features.hasFeature( MFT_DiffuseMap ) )
  609. newFeatures.addFeature( MFT_VertLitTone );
  610. newFeatures.addFeature( MFT_VertLit );
  611. newFeatures.addFeature( MFT_LightbufferMRT );
  612. }
  613. else
  614. {
  615. // If this object isn't lightmapped, add a zero-output feature to it
  616. newFeatures.addFeature( MFT_RenderTarget3_Zero );
  617. }
  618. }
  619. // cubemaps only available on stage 0 for now - bramage
  620. if ( stageNum < 1 &&
  621. ( ( mMaterial->mCubemapData && mMaterial->mCubemapData->mCubemap ) ||
  622. mMaterial->mDynamicCubemap ) )
  623. newFeatures.addFeature( MFT_CubeMap );
  624. #endif
  625. // Set the new features.
  626. fd.features = newFeatures;
  627. }
  628. U32 ProcessedPrePassMaterial::getNumStages()
  629. {
  630. // Loops through all stages to determine how many
  631. // stages we actually use.
  632. //
  633. // The first stage is always active else we shouldn't be
  634. // creating the material to begin with.
  635. U32 numStages = 1;
  636. U32 i;
  637. for( i=1; i<Material::MAX_STAGES; i++ )
  638. {
  639. // Assume stage is inactive
  640. bool stageActive = false;
  641. // Cubemaps only on first stage
  642. if( i == 0 )
  643. {
  644. // If we have a cubemap the stage is active
  645. if( mMaterial->mCubemapData || mMaterial->mDynamicCubemap )
  646. {
  647. numStages++;
  648. continue;
  649. }
  650. }
  651. // If we have a texture for the a feature the
  652. // stage is active.
  653. if ( mStages[i].hasValidTex() )
  654. stageActive = true;
  655. // If this stage has specular lighting, it's active
  656. if ( mMaterial->mPixelSpecular[i] )
  657. stageActive = true;
  658. // If this stage has diffuse color, it's active
  659. if ( mMaterial->mDiffuse[i].alpha > 0 &&
  660. mMaterial->mDiffuse[i] != ColorF::WHITE )
  661. stageActive = true;
  662. // If we have a Material that is vertex lit
  663. // then it may not have a texture
  664. if( mMaterial->mVertLit[i] )
  665. stageActive = true;
  666. // Increment the number of active stages
  667. numStages += stageActive;
  668. }
  669. return numStages;
  670. }
  671. void ProcessedPrePassMaterial::addStateBlockDesc(const GFXStateBlockDesc& desc)
  672. {
  673. GFXStateBlockDesc prePassStateBlock = desc;
  674. // Adjust color writes if this is a pure z-fill pass
  675. const bool pixelOutEnabled = mPrePassMgr->getTargetChainLength() > 0;
  676. if ( !pixelOutEnabled )
  677. {
  678. prePassStateBlock.colorWriteDefined = true;
  679. prePassStateBlock.colorWriteRed = pixelOutEnabled;
  680. prePassStateBlock.colorWriteGreen = pixelOutEnabled;
  681. prePassStateBlock.colorWriteBlue = pixelOutEnabled;
  682. prePassStateBlock.colorWriteAlpha = pixelOutEnabled;
  683. }
  684. // Never allow the alpha test state when rendering
  685. // the prepass as we use the alpha channel for the
  686. // depth information... MFT_AlphaTest will handle it.
  687. prePassStateBlock.alphaDefined = true;
  688. prePassStateBlock.alphaTestEnable = false;
  689. // If we're translucent then we're doing prepass blending
  690. // which never writes to the depth channels.
  691. const bool isTranslucent = getMaterial()->isTranslucent();
  692. if ( isTranslucent )
  693. {
  694. prePassStateBlock.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  695. prePassStateBlock.setColorWrites(false, false, false, true);
  696. }
  697. // Enable z reads, but only enable zwrites if we're not translucent.
  698. prePassStateBlock.setZReadWrite( true, isTranslucent ? false : true );
  699. // Pass to parent
  700. Parent::addStateBlockDesc(prePassStateBlock);
  701. }
  702. PrePassMatInstance::PrePassMatInstance(MatInstance* root, const RenderPrePassMgr *prePassMgr)
  703. : Parent(*root->getMaterial()), mPrePassMgr(prePassMgr)
  704. {
  705. mFeatureList = root->getRequestedFeatures();
  706. mVertexFormat = root->getVertexFormat();
  707. mUserObject = root->getUserObject();
  708. }
  709. PrePassMatInstance::~PrePassMatInstance()
  710. {
  711. }
  712. ProcessedMaterial* PrePassMatInstance::getShaderMaterial()
  713. {
  714. return new ProcessedPrePassMaterial(*mMaterial, mPrePassMgr);
  715. }
  716. bool PrePassMatInstance::init( const FeatureSet &features,
  717. const GFXVertexFormat *vertexFormat )
  718. {
  719. bool vaild = Parent::init(features, vertexFormat);
  720. if (mMaterial && mMaterial->mDiffuseMapFilename[0].isNotEmpty() && mMaterial->mDiffuseMapFilename[0].substr(0, 1).equal("#"))
  721. {
  722. String texTargetBufferName = mMaterial->mDiffuseMapFilename[0].substr(1, mMaterial->mDiffuseMapFilename[0].length() - 1);
  723. NamedTexTarget *texTarget = NamedTexTarget::find(texTargetBufferName);
  724. RenderPassData* rpd = getPass(0);
  725. if (rpd)
  726. {
  727. rpd->mTexSlot[0].texTarget = texTarget;
  728. rpd->mTexType[0] = Material::TexTarget;
  729. rpd->mSamplerNames[0] = "diffuseMap";
  730. }
  731. }
  732. return vaild;
  733. }
  734. PrePassMatInstanceHook::PrePassMatInstanceHook( MatInstance *baseMatInst,
  735. const RenderPrePassMgr *prePassMgr )
  736. : mHookedPrePassMatInst(NULL), mPrePassManager(prePassMgr)
  737. {
  738. // If the material is a custom material then
  739. // hope that using DefaultPrePassMaterial gives
  740. // them a good prepass.
  741. if ( baseMatInst->isCustomMaterial() )
  742. {
  743. MatInstance* dummyInst = static_cast<MatInstance*>( MATMGR->createMatInstance( "AL_DefaultPrePassMaterial", baseMatInst->getVertexFormat() ) );
  744. mHookedPrePassMatInst = new PrePassMatInstance( dummyInst, prePassMgr );
  745. mHookedPrePassMatInst->init( dummyInst->getRequestedFeatures(), baseMatInst->getVertexFormat());
  746. delete dummyInst;
  747. return;
  748. }
  749. // Create the prepass material instance.
  750. mHookedPrePassMatInst = new PrePassMatInstance(baseMatInst, prePassMgr);
  751. mHookedPrePassMatInst->getFeaturesDelegate() = baseMatInst->getFeaturesDelegate();
  752. // Get the features, but remove the instancing feature if the
  753. // original material didn't end up using it.
  754. FeatureSet features = baseMatInst->getRequestedFeatures();
  755. if ( !baseMatInst->isInstanced() )
  756. features.removeFeature( MFT_UseInstancing );
  757. // Initialize the material.
  758. mHookedPrePassMatInst->init(features, baseMatInst->getVertexFormat());
  759. }
  760. PrePassMatInstanceHook::~PrePassMatInstanceHook()
  761. {
  762. SAFE_DELETE(mHookedPrePassMatInst);
  763. }
  764. //------------------------------------------------------------------------------
  765. //------------------------------------------------------------------------------
  766. void LinearEyeDepthConditioner::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd )
  767. {
  768. // find depth
  769. ShaderFeature *depthFeat = FEATUREMGR->getByType( MFT_EyeSpaceDepthOut );
  770. AssertFatal( depthFeat != NULL, "No eye space depth feature found!" );
  771. Var *depth = (Var*) LangElement::find(depthFeat->getOutputVarName());
  772. AssertFatal( depth, "Something went bad with ShaderGen. The depth should be already generated by the EyeSpaceDepthOut feature." );
  773. MultiLine *meta = new MultiLine;
  774. meta->addStatement( assignOutput( depth ) );
  775. output = meta;
  776. }
  777. Var *LinearEyeDepthConditioner::_conditionOutput( Var *unconditionedOutput, MultiLine *meta )
  778. {
  779. Var *retVar = NULL;
  780. String fracMethodName = (GFX->getAdapterType() == OpenGL) ? "fract" : "frac";
  781. switch(getBufferFormat())
  782. {
  783. case GFXFormatR8G8B8A8:
  784. retVar = new Var;
  785. retVar->setType("float4");
  786. retVar->setName("_ppDepth");
  787. meta->addStatement( new GenOp( " // depth conditioner: packing to rgba\r\n" ) );
  788. meta->addStatement( new GenOp(
  789. avar( " @ = %s(@ * (255.0/256) * float4(1, 255, 255 * 255, 255 * 255 * 255));\r\n", fracMethodName.c_str() ),
  790. new DecOp(retVar), unconditionedOutput ) );
  791. break;
  792. default:
  793. retVar = unconditionedOutput;
  794. meta->addStatement( new GenOp( " // depth conditioner: no conditioning\r\n" ) );
  795. break;
  796. }
  797. AssertFatal( retVar != NULL, avar( "Cannot condition output to buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  798. return retVar;
  799. }
  800. Var *LinearEyeDepthConditioner::_unconditionInput( Var *conditionedInput, MultiLine *meta )
  801. {
  802. String float4Typename = (GFX->getAdapterType() == OpenGL) ? "vec4" : "float4";
  803. Var *retVar = conditionedInput;
  804. if(getBufferFormat() != GFXFormat_COUNT)
  805. {
  806. retVar = new Var;
  807. retVar->setType(float4Typename.c_str());
  808. retVar->setName("_ppDepth");
  809. meta->addStatement( new GenOp( avar( " @ = %s(0, 0, 1, 1);\r\n", float4Typename.c_str() ), new DecOp(retVar) ) );
  810. switch(getBufferFormat())
  811. {
  812. case GFXFormatR32F:
  813. case GFXFormatR16F:
  814. meta->addStatement( new GenOp( " // depth conditioner: float texture\r\n" ) );
  815. meta->addStatement( new GenOp( " @.w = @.r;\r\n", retVar, conditionedInput ) );
  816. break;
  817. case GFXFormatR8G8B8A8:
  818. meta->addStatement( new GenOp( " // depth conditioner: unpacking from rgba\r\n" ) );
  819. meta->addStatement( new GenOp(
  820. avar( " @.w = dot(@ * (256.0/255), %s(1, 1 / 255, 1 / (255 * 255), 1 / (255 * 255 * 255)));\r\n", float4Typename.c_str() )
  821. , retVar, conditionedInput ) );
  822. break;
  823. default:
  824. AssertFatal(false, "LinearEyeDepthConditioner::_unconditionInput - Unrecognized buffer format");
  825. }
  826. }
  827. return retVar;
  828. }
  829. Var* LinearEyeDepthConditioner::printMethodHeader( MethodType methodType, const String &methodName, Stream &stream, MultiLine *meta )
  830. {
  831. const bool isCondition = ( methodType == ConditionerFeature::ConditionMethod );
  832. Var *retVal = NULL;
  833. // The uncondition method inputs are changed
  834. if( isCondition )
  835. retVal = Parent::printMethodHeader( methodType, methodName, stream, meta );
  836. else
  837. {
  838. Var *methodVar = new Var;
  839. methodVar->setName(methodName);
  840. if (GFX->getAdapterType() == OpenGL)
  841. methodVar->setType("vec4");
  842. else
  843. methodVar->setType("inline float4");
  844. DecOp *methodDecl = new DecOp(methodVar);
  845. Var *prepassSampler = new Var;
  846. prepassSampler->setName("prepassSamplerVar");
  847. prepassSampler->setType("sampler2D");
  848. DecOp *prepassSamplerDecl = new DecOp(prepassSampler);
  849. Var *screenUV = new Var;
  850. screenUV->setName("screenUVVar");
  851. if (GFX->getAdapterType() == OpenGL)
  852. screenUV->setType("vec2");
  853. else
  854. screenUV->setType("float2");
  855. DecOp *screenUVDecl = new DecOp(screenUV);
  856. Var *bufferSample = new Var;
  857. bufferSample->setName("bufferSample");
  858. if (GFX->getAdapterType() == OpenGL)
  859. bufferSample->setType("vec4");
  860. else
  861. bufferSample->setType("float4");
  862. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  863. meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, prepassSamplerDecl, screenUVDecl ) );
  864. meta->addStatement( new GenOp( "{\r\n" ) );
  865. meta->addStatement( new GenOp( " // Sampler g-buffer\r\n" ) );
  866. // The linear depth target has no mipmaps, so use tex2dlod when
  867. // possible so that the shader compiler can optimize.
  868. meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) );
  869. if (GFX->getAdapterType() == OpenGL)
  870. meta->addStatement( new GenOp( " @ = textureLod(@, @, 0); \r\n", bufferSampleDecl, prepassSampler, screenUV) );
  871. else
  872. meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  873. meta->addStatement( new GenOp( " #else\r\n" ) );
  874. if (GFX->getAdapterType() == OpenGL)
  875. meta->addStatement( new GenOp( " @ = texture(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV) );
  876. else
  877. meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, prepassSampler, screenUV ) );
  878. meta->addStatement( new GenOp( " #endif\r\n\r\n" ) );
  879. // We don't use this way of passing var's around, so this should cause a crash
  880. // if something uses this improperly
  881. retVal = bufferSample;
  882. }
  883. return retVal;
  884. }
  885. void RenderPrePassMgr::_initShaders()
  886. {
  887. if ( mClearGBufferShader ) return;
  888. // Find ShaderData
  889. ShaderData *shaderData;
  890. mClearGBufferShader = Sim::findObject( "ClearGBufferShader", shaderData ) ? shaderData->getShader() : NULL;
  891. if ( !mClearGBufferShader )
  892. Con::errorf( "RenderPrePassMgr::_initShaders - could not find ClearGBufferShader" );
  893. // Create StateBlocks
  894. GFXStateBlockDesc desc;
  895. desc.setCullMode( GFXCullNone );
  896. desc.setBlend( true );
  897. desc.setZReadWrite( false, false );
  898. desc.samplersDefined = true;
  899. desc.samplers[0].addressModeU = GFXAddressWrap;
  900. desc.samplers[0].addressModeV = GFXAddressWrap;
  901. desc.samplers[0].addressModeW = GFXAddressWrap;
  902. desc.samplers[0].magFilter = GFXTextureFilterLinear;
  903. desc.samplers[0].minFilter = GFXTextureFilterLinear;
  904. desc.samplers[0].mipFilter = GFXTextureFilterLinear;
  905. desc.samplers[0].textureColorOp = GFXTOPModulate;
  906. mStateblock = GFX->createStateBlock( desc );
  907. // Set up shader constants.
  908. mShaderConsts = mClearGBufferShader->allocConstBuffer();
  909. mSpecularStrengthSC = mClearGBufferShader->getShaderConstHandle( "$specularStrength" );
  910. mSpecularPowerSC = mClearGBufferShader->getShaderConstHandle( "$specularPower" );
  911. }
  912. void RenderPrePassMgr::clearBuffers()
  913. {
  914. // Clear z-buffer.
  915. GFX->clear( GFXClearTarget | GFXClearZBuffer | GFXClearStencil, ColorI::ZERO, 1.0f, 0);
  916. if ( !mClearGBufferShader )
  917. return;
  918. GFXTransformSaver saver;
  919. // Clear the g-buffer.
  920. RectI box(-1, -1, 3, 3);
  921. GFX->setWorldMatrix( MatrixF::Identity );
  922. GFX->setViewMatrix( MatrixF::Identity );
  923. GFX->setProjectionMatrix( MatrixF::Identity );
  924. GFX->setShader(mClearGBufferShader);
  925. GFX->setStateBlock(mStateblock);
  926. Point2F nw(-0.5,-0.5);
  927. Point2F ne(0.5,-0.5);
  928. GFXVertexBufferHandle<GFXVertexPC> verts(GFX, 4, GFXBufferTypeVolatile);
  929. verts.lock();
  930. F32 ulOffset = 0.5f - GFX->getFillConventionOffset();
  931. Point2F upperLeft(-1.0, -1.0);
  932. Point2F lowerRight(1.0, 1.0);
  933. verts[0].point.set( upperLeft.x+nw.x+ulOffset, upperLeft.y+nw.y+ulOffset, 0.0f );
  934. verts[1].point.set( lowerRight.x+ne.x, upperLeft.y+ne.y+ulOffset, 0.0f );
  935. verts[2].point.set( upperLeft.x-ne.x+ulOffset, lowerRight.y-ne.y, 0.0f );
  936. verts[3].point.set( lowerRight.x-nw.x, lowerRight.y-nw.y, 0.0f );
  937. verts.unlock();
  938. GFX->setVertexBuffer( verts );
  939. GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
  940. GFX->setShader(NULL);
  941. }