renderDeferredMgr.cpp 41 KB

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