renderDeferredMgr.cpp 40 KB

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