renderDeferredMgr.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163
  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. IMPLEMENT_CONOBJECT(RenderDeferredMgr);
  57. ConsoleDocClass( RenderDeferredMgr,
  58. "@brief The render bin which performs a z+normals deferred 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 #deferred "
  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. RenderDeferredMgr::RenderSignal& RenderDeferredMgr::getRenderSignal()
  66. {
  67. static RenderSignal theSignal;
  68. return theSignal;
  69. }
  70. RenderDeferredMgr::RenderDeferredMgr( bool gatherDepth,
  71. GFXFormat format )
  72. : Parent( RIT_Deferred,
  73. 0.01f,
  74. 0.01f,
  75. format,
  76. Point2I( Parent::DefaultTargetSize, Parent::DefaultTargetSize),
  77. gatherDepth ? Parent::DefaultTargetChainLength : 0 ),
  78. mDeferredMatInstance( 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. RenderDeferredMgr::~RenderDeferredMgr()
  96. {
  97. GFXShader::removeGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  98. mColorTarget.release();
  99. mMatInfoTarget.release();
  100. _unregisterFeatures();
  101. SAFE_DELETE( mDeferredMatInstance );
  102. }
  103. void RenderDeferredMgr::_registerFeatures()
  104. {
  105. ConditionerFeature *cond = new LinearEyeDepthConditioner( getTargetFormat() );
  106. FEATUREMGR->registerFeature( MFT_DeferredConditioner, cond );
  107. mNamedTarget.setConditioner( cond );
  108. }
  109. void RenderDeferredMgr::_unregisterFeatures()
  110. {
  111. mNamedTarget.setConditioner( NULL );
  112. FEATUREMGR->unregisterFeature(MFT_DeferredConditioner);
  113. }
  114. bool RenderDeferredMgr::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 RenderDeferredMgr::_updateTargets()
  123. {
  124. PROFILE_SCOPE(RenderDeferredMgr_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_DeferredConditioner));
  128. if( outputConditioner && outputConditioner->setBufferFormat(mTargetFormat) )
  129. {
  130. // reload materials, the conditioner needs to alter the generated shaders
  131. }
  132. // TODO: these formats should be passed in and not hard-coded
  133. const GFXFormat colorFormat = GFXFormatR8G8B8A8_SRGB;
  134. const GFXFormat matInfoFormat = GFXFormatR8G8B8A8;
  135. // andrewmac: Deferred Shading Color Buffer
  136. if (mColorTex.getFormat() != colorFormat || mColorTex.getWidthHeight() != mTargetSize || GFX->recentlyReset())
  137. {
  138. mColorTarget.release();
  139. mColorTex.set(mTargetSize.x, mTargetSize.y, colorFormat,
  140. &GFXRenderTargetSRGBProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__),
  141. 1, GFXTextureManager::AA_MATCH_BACKBUFFER);
  142. mColorTarget.setTexture(mColorTex);
  143. for (U32 i = 0; i < mTargetChainLength; i++)
  144. mTargetChain[i]->attachTexture(GFXTextureTarget::Color1, mColorTarget.getTexture());
  145. }
  146. // andrewmac: Deferred Shading Material Info Buffer
  147. if (mMatInfoTex.getFormat() != matInfoFormat || mMatInfoTex.getWidthHeight() != mTargetSize || GFX->recentlyReset())
  148. {
  149. mMatInfoTarget.release();
  150. mMatInfoTex.set(mTargetSize.x, mTargetSize.y, matInfoFormat,
  151. &GFXRenderTargetProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__),
  152. 1, GFXTextureManager::AA_MATCH_BACKBUFFER);
  153. mMatInfoTarget.setTexture(mMatInfoTex);
  154. for (U32 i = 0; i < mTargetChainLength; i++)
  155. mTargetChain[i]->attachTexture(GFXTextureTarget::Color2, mMatInfoTarget.getTexture());
  156. }
  157. GFX->finalizeReset();
  158. // Attach the light info buffer as a second render target, if there is
  159. // lightmapped geometry in the scene.
  160. AdvancedLightBinManager *lightBin;
  161. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) &&
  162. lightBin->MRTLightmapsDuringDeferred() &&
  163. lightBin->isProperlyAdded() )
  164. {
  165. // Update the size of the light bin target here. This will call _updateTargets
  166. // on the light bin
  167. ret &= lightBin->setTargetSize( mTargetSize );
  168. if ( ret )
  169. {
  170. // Sanity check
  171. AssertFatal(lightBin->getTargetChainLength() == mTargetChainLength, "Target chain length mismatch");
  172. // Attach light info buffer to Color1 for each target in the chain
  173. for ( U32 i = 0; i < mTargetChainLength; i++ )
  174. {
  175. GFXTexHandle lightInfoTex = lightBin->getTargetTexture(0, i);
  176. mTargetChain[i]->attachTexture(GFXTextureTarget::Color3, lightInfoTex);
  177. }
  178. }
  179. }
  180. _initShaders();
  181. return ret;
  182. }
  183. void RenderDeferredMgr::_createDeferredMaterial()
  184. {
  185. SAFE_DELETE(mDeferredMatInstance);
  186. const GFXVertexFormat *vertexFormat = getGFXVertexFormat<GFXVertexPNTTB>();
  187. MatInstance* deferredMat = static_cast<MatInstance*>(MATMGR->createMatInstance("AL_DefaultDeferredMaterial", vertexFormat));
  188. AssertFatal( deferredMat, "TODO: Handle this better." );
  189. mDeferredMatInstance = new DeferredMatInstance(deferredMat, this);
  190. mDeferredMatInstance->init( MATMGR->getDefaultFeatures(), vertexFormat);
  191. delete deferredMat;
  192. }
  193. void RenderDeferredMgr::setDeferredMaterial( DeferredMatInstance *mat )
  194. {
  195. SAFE_DELETE(mDeferredMatInstance);
  196. mDeferredMatInstance = mat;
  197. }
  198. void RenderDeferredMgr::addElement( RenderInst *inst )
  199. {
  200. PROFILE_SCOPE( RenderDeferredMgr_addElement )
  201. // Skip out if this bin is disabled.
  202. if ( gClientSceneGraph->getCurrentRenderState() &&
  203. gClientSceneGraph->getCurrentRenderState()->disableAdvancedLightingBins() )
  204. return;
  205. // First what type of render instance is it?
  206. const bool isDecalMeshInst = ((inst->type == RenderPassManager::RIT_Decal)||(inst->type == RenderPassManager::RIT_DecalRoad));
  207. const bool isMeshInst = inst->type == RenderPassManager::RIT_Mesh;
  208. const bool isTerrainInst = inst->type == RenderPassManager::RIT_Terrain;
  209. // Get the material if its a mesh.
  210. BaseMatInstance* matInst = NULL;
  211. if ( isMeshInst || isDecalMeshInst )
  212. matInst = static_cast<MeshRenderInst*>(inst)->matInst;
  213. if (matInst)
  214. {
  215. // Skip decals if they don't have normal maps.
  216. if (isDecalMeshInst && !matInst->hasNormalMap())
  217. return;
  218. // If its a custom material and it refracts... skip it.
  219. if (matInst->isCustomMaterial() &&
  220. static_cast<CustomMaterial*>(matInst->getMaterial())->mRefract)
  221. return;
  222. // Make sure we got a deferred material.
  223. matInst = getDeferredMaterial(matInst);
  224. if (!matInst || !matInst->isValid())
  225. return;
  226. }
  227. // We're gonna add it to the bin... get the right element list.
  228. Vector< MainSortElem > *elementList;
  229. if ( isMeshInst || isDecalMeshInst )
  230. elementList = &mElementList;
  231. else if ( isTerrainInst )
  232. elementList = &mTerrainElementList;
  233. else
  234. elementList = &mObjectElementList;
  235. elementList->increment();
  236. MainSortElem &elem = elementList->last();
  237. elem.inst = inst;
  238. // Store the original key... we might need it.
  239. U32 originalKey = elem.key;
  240. // Sort front-to-back first to get the most fillrate savings.
  241. const F32 invSortDistSq = F32_MAX - inst->sortDistSq;
  242. elem.key = *((U32*)&invSortDistSq);
  243. // Next sort by pre-pass material if its a mesh... use the original sort key.
  244. if (isMeshInst && matInst)
  245. elem.key2 = matInst->getStateHint();
  246. else
  247. elem.key2 = originalKey;
  248. }
  249. void RenderDeferredMgr::sort()
  250. {
  251. PROFILE_SCOPE( RenderDeferredMgr_sort );
  252. Parent::sort();
  253. dQsort( mTerrainElementList.address(), mTerrainElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  254. dQsort( mObjectElementList.address(), mObjectElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  255. }
  256. void RenderDeferredMgr::clear()
  257. {
  258. Parent::clear();
  259. mTerrainElementList.clear();
  260. mObjectElementList.clear();
  261. }
  262. void RenderDeferredMgr::render( SceneRenderState *state )
  263. {
  264. PROFILE_SCOPE(RenderDeferredMgr_render);
  265. // Take a look at the SceneRenderState and see if we should skip drawing the pre-pass
  266. if ( state->disableAdvancedLightingBins() )
  267. return;
  268. // NOTE: We don't early out here when the element list is
  269. // zero because we need the deferred to be cleared.
  270. // Automagically save & restore our viewport and transforms.
  271. GFXTransformSaver saver;
  272. GFXDEBUGEVENT_SCOPE( RenderDeferredMgr_Render, ColorI::RED );
  273. // Tell the superclass we're about to render
  274. const bool isRenderingToTarget = _onPreRender(state);
  275. // Clear all z-buffer, and g-buffer.
  276. clearBuffers();
  277. // Restore transforms
  278. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  279. matrixSet.restoreSceneViewProjection();
  280. const MatrixF worldViewXfm = GFX->getWorldMatrix();
  281. // Setup the default deferred material for object instances.
  282. if ( !mDeferredMatInstance )
  283. _createDeferredMaterial();
  284. if ( mDeferredMatInstance )
  285. {
  286. matrixSet.setWorld(MatrixF::Identity);
  287. mDeferredMatInstance->setTransforms(matrixSet, state);
  288. }
  289. // Signal start of pre-pass
  290. getRenderSignal().trigger( state, this, true );
  291. // First do a loop and render all the terrain... these are
  292. // usually the big blockers in a scene and will save us fillrate
  293. // on the smaller meshes and objects.
  294. // The terrain doesn't need any scene graph data
  295. // in the the deferred... so just clear it.
  296. SceneData sgData;
  297. sgData.init( state, SceneData::DeferredBin );
  298. Vector< MainSortElem >::const_iterator itr = mTerrainElementList.begin();
  299. for ( ; itr != mTerrainElementList.end(); itr++ )
  300. {
  301. TerrainRenderInst *ri = static_cast<TerrainRenderInst*>( itr->inst );
  302. TerrainCellMaterial *mat = ri->cellMat->getDeferredMat();
  303. GFX->setPrimitiveBuffer( ri->primBuff );
  304. GFX->setVertexBuffer( ri->vertBuff );
  305. mat->setTransformAndEye( *ri->objectToWorldXfm,
  306. worldViewXfm,
  307. GFX->getProjectionMatrix(),
  308. state->getFarPlane() );
  309. while ( mat->setupPass( state, sgData ) )
  310. GFX->drawPrimitive( ri->prim );
  311. }
  312. // init loop data
  313. GFXTextureObject *lastLM = NULL;
  314. GFXCubemap *lastCubemap = NULL;
  315. GFXTextureObject *lastReflectTex = NULL;
  316. GFXTextureObject *lastAccuTex = NULL;
  317. // Next render all the meshes.
  318. itr = mElementList.begin();
  319. for ( ; itr != mElementList.end(); )
  320. {
  321. MeshRenderInst *ri = static_cast<MeshRenderInst*>( itr->inst );
  322. // Get the deferred material.
  323. BaseMatInstance *mat = getDeferredMaterial( ri->matInst );
  324. // Set up SG data proper like and flag it
  325. // as a pre-pass render
  326. setupSGData( ri, sgData );
  327. Vector< MainSortElem >::const_iterator meshItr, endOfBatchItr = itr;
  328. while ( mat->setupPass( state, sgData ) )
  329. {
  330. meshItr = itr;
  331. for ( ; meshItr != mElementList.end(); meshItr++ )
  332. {
  333. MeshRenderInst *passRI = static_cast<MeshRenderInst*>( meshItr->inst );
  334. // Check to see if we need to break this batch.
  335. //
  336. // NOTE: We're comparing the non-deferred materials
  337. // here so we don't incur the cost of looking up the
  338. // deferred hook on each inst.
  339. //
  340. if ( newPassNeeded( ri, passRI ) )
  341. break;
  342. // Set up SG data for this instance.
  343. setupSGData( passRI, sgData );
  344. mat->setSceneInfo(state, sgData);
  345. matrixSet.setWorld(*passRI->objectToWorld);
  346. matrixSet.setView(*passRI->worldToCamera);
  347. matrixSet.setProjection(*passRI->projection);
  348. mat->setTransforms(matrixSet, state);
  349. // Setup HW skinning transforms if applicable
  350. if (mat->usesHardwareSkinning())
  351. {
  352. mat->setNodeTransforms(passRI->mNodeTransforms, passRI->mNodeTransformCount);
  353. }
  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 = passRI->accuTex;
  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, mDeferredMatInstance );
  427. }
  428. // Signal end of pre-pass
  429. getRenderSignal().trigger( state, this, false );
  430. if(isRenderingToTarget)
  431. _onPostRender();
  432. }
  433. const GFXStateBlockDesc & RenderDeferredMgr::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 = RenderDeferredMgr::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 = RenderDeferredMgr::OpaqueDynamicLitMask;
  454. }
  455. return (lightmappedGeometry ? sOpaqueStaticLitStencilWriteDesc : sOpaqueDynamicLitStencilWriteDesc);
  456. }
  457. const GFXStateBlockDesc & RenderDeferredMgr::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. ProcessedDeferredMaterial::ProcessedDeferredMaterial( Material& mat, const RenderDeferredMgr *deferredMgr )
  480. : Parent(mat), mDeferredMgr(deferredMgr)
  481. {
  482. }
  483. void ProcessedDeferredMaterial::_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->MRTLightmapsDuringDeferred();
  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( mDeferredMgr->getOpaqueStenciWriteDesc( mIsLightmappedGeometry ) );
  503. FeatureSet newFeatures;
  504. // These are always on for deferred.
  505. newFeatures.addFeature( MFT_EyeSpaceDepthOut );
  506. newFeatures.addFeature( MFT_DeferredConditioner );
  507. #ifndef TORQUE_DEDICATED
  508. //tag all materials running through deferred 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_IsBC3nm ||
  546. type == MFT_IsBC5nm ||
  547. type == MFT_TexAnim ||
  548. type == MFT_NormalMap ||
  549. type == MFT_DetailNormalMap ||
  550. type == MFT_AlphaTest ||
  551. type == MFT_Parallax ||
  552. type == MFT_InterlacedDeferred ||
  553. type == MFT_Visibility ||
  554. type == MFT_UseInstancing ||
  555. type == MFT_DiffuseVertColor ||
  556. type == MFT_DetailMap ||
  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 ProcessedDeferredMaterial::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] != LinearColorF::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 ProcessedDeferredMaterial::addStateBlockDesc(const GFXStateBlockDesc& desc)
  672. {
  673. GFXStateBlockDesc deferredStateBlock = desc;
  674. // Adjust color writes if this is a pure z-fill pass
  675. const bool pixelOutEnabled = mDeferredMgr->getTargetChainLength() > 0;
  676. if ( !pixelOutEnabled )
  677. {
  678. deferredStateBlock.colorWriteDefined = true;
  679. deferredStateBlock.colorWriteRed = pixelOutEnabled;
  680. deferredStateBlock.colorWriteGreen = pixelOutEnabled;
  681. deferredStateBlock.colorWriteBlue = pixelOutEnabled;
  682. deferredStateBlock.colorWriteAlpha = pixelOutEnabled;
  683. }
  684. // Never allow the alpha test state when rendering
  685. // the deferred as we use the alpha channel for the
  686. // depth information... MFT_AlphaTest will handle it.
  687. deferredStateBlock.alphaDefined = true;
  688. deferredStateBlock.alphaTestEnable = false;
  689. // If we're translucent then we're doing deferred blending
  690. // which never writes to the depth channels.
  691. const bool isTranslucent = getMaterial()->isTranslucent();
  692. if ( isTranslucent )
  693. {
  694. deferredStateBlock.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  695. deferredStateBlock.setColorWrites(false, false, false, true);
  696. }
  697. // Enable z reads, but only enable zwrites if we're not translucent.
  698. deferredStateBlock.setZReadWrite( true, isTranslucent ? false : true );
  699. // Pass to parent
  700. Parent::addStateBlockDesc(deferredStateBlock);
  701. }
  702. DeferredMatInstance::DeferredMatInstance(MatInstance* root, const RenderDeferredMgr *deferredMgr)
  703. : Parent(*root->getMaterial()), mDeferredMgr(deferredMgr)
  704. {
  705. mFeatureList = root->getRequestedFeatures();
  706. mVertexFormat = root->getVertexFormat();
  707. mUserObject = root->getUserObject();
  708. }
  709. DeferredMatInstance::~DeferredMatInstance()
  710. {
  711. }
  712. ProcessedMaterial* DeferredMatInstance::getShaderMaterial()
  713. {
  714. return new ProcessedDeferredMaterial(*mMaterial, mDeferredMgr);
  715. }
  716. bool DeferredMatInstance::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. DeferredMatInstanceHook::DeferredMatInstanceHook( MatInstance *baseMatInst,
  735. const RenderDeferredMgr *deferredMgr )
  736. : mHookedDeferredMatInst(NULL), mDeferredManager(deferredMgr)
  737. {
  738. // If the material is a custom material then
  739. // hope that using DefaultDeferredMaterial gives
  740. // them a good deferred.
  741. if ( baseMatInst->isCustomMaterial() )
  742. {
  743. MatInstance* dummyInst = static_cast<MatInstance*>( MATMGR->createMatInstance( "AL_DefaultDeferredMaterial", baseMatInst->getVertexFormat() ) );
  744. mHookedDeferredMatInst = new DeferredMatInstance( dummyInst, deferredMgr );
  745. mHookedDeferredMatInst->init( dummyInst->getRequestedFeatures(), baseMatInst->getVertexFormat());
  746. delete dummyInst;
  747. return;
  748. }
  749. // Create the deferred material instance.
  750. mHookedDeferredMatInst = new DeferredMatInstance(baseMatInst, deferredMgr);
  751. mHookedDeferredMatInst->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. mHookedDeferredMatInst->init(features, baseMatInst->getVertexFormat());
  759. }
  760. DeferredMatInstanceHook::~DeferredMatInstanceHook()
  761. {
  762. SAFE_DELETE(mHookedDeferredMatInst);
  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 *deferredSampler = new Var;
  846. deferredSampler->setName("deferredSamplerVar");
  847. deferredSampler->setType("sampler2D");
  848. DecOp *deferredSamplerDecl = NULL;
  849. Var *deferredTex = NULL;
  850. DecOp *deferredTexDecl = NULL;
  851. if (GFX->getAdapterType() == Direct3D11)
  852. {
  853. deferredSampler->setType("SamplerState");
  854. deferredTex = new Var;
  855. deferredTex->setName("deferredTexVar");
  856. deferredTex->setType("Texture2D");
  857. deferredTexDecl = new DecOp(deferredTex);
  858. }
  859. deferredSamplerDecl = new DecOp(deferredSampler);
  860. Var *screenUV = new Var;
  861. screenUV->setName("screenUVVar");
  862. if (GFX->getAdapterType() == OpenGL)
  863. screenUV->setType("vec2");
  864. else
  865. screenUV->setType("float2");
  866. DecOp *screenUVDecl = new DecOp(screenUV);
  867. Var *bufferSample = new Var;
  868. bufferSample->setName("bufferSample");
  869. if (GFX->getAdapterType() == OpenGL)
  870. bufferSample->setType("vec4");
  871. else
  872. bufferSample->setType("float4");
  873. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  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. meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) );
  880. if (GFX->getAdapterType() == OpenGL)
  881. meta->addStatement( new GenOp( " @ = textureLod(@, @, 0); \r\n", bufferSampleDecl, deferredSampler, screenUV) );
  882. else
  883. meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, deferredSampler, screenUV ) );
  884. meta->addStatement( new GenOp( " #else\r\n" ) );
  885. if (GFX->getAdapterType() == OpenGL)
  886. meta->addStatement( new GenOp( " @ = texture(@, @);\r\n", bufferSampleDecl, deferredSampler, screenUV) );
  887. else
  888. meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, deferredSampler, screenUV ) );
  889. meta->addStatement( new GenOp( " #endif\r\n\r\n" ) );
  890. // We don't use this way of passing var's around, so this should cause a crash
  891. // if something uses this improperly
  892. retVal = bufferSample;
  893. }
  894. return retVal;
  895. }
  896. void RenderDeferredMgr::_initShaders()
  897. {
  898. if ( mClearGBufferShader ) return;
  899. // Find ShaderData
  900. ShaderData *shaderData;
  901. mClearGBufferShader = Sim::findObject( "ClearGBufferShader", shaderData ) ? shaderData->getShader() : NULL;
  902. if ( !mClearGBufferShader )
  903. Con::errorf( "RenderDeferredMgr::_initShaders - could not find ClearGBufferShader" );
  904. // Create StateBlocks
  905. GFXStateBlockDesc desc;
  906. desc.setCullMode( GFXCullNone );
  907. desc.setBlend( false );
  908. desc.setZReadWrite( false, false );
  909. desc.samplersDefined = true;
  910. for (int i = 0; i < TEXTURE_STAGE_COUNT; i++)
  911. {
  912. desc.samplers[i].addressModeU = GFXAddressWrap;
  913. desc.samplers[i].addressModeV = GFXAddressWrap;
  914. desc.samplers[i].addressModeW = GFXAddressWrap;
  915. desc.samplers[i].magFilter = GFXTextureFilterLinear;
  916. desc.samplers[i].minFilter = GFXTextureFilterLinear;
  917. desc.samplers[i].mipFilter = GFXTextureFilterLinear;
  918. desc.samplers[i].textureColorOp = GFXTOPModulate;
  919. }
  920. mStateblock = GFX->createStateBlock( desc );
  921. // Set up shader constants.
  922. mShaderConsts = mClearGBufferShader->allocConstBuffer();
  923. mSpecularStrengthSC = mClearGBufferShader->getShaderConstHandle( "$specularStrength" );
  924. mSpecularPowerSC = mClearGBufferShader->getShaderConstHandle( "$specularPower" );
  925. }
  926. void RenderDeferredMgr::clearBuffers()
  927. {
  928. // Clear z-buffer.
  929. GFX->clear( GFXClearTarget | GFXClearZBuffer | GFXClearStencil, ColorI::ZERO, 1.0f, 0);
  930. if ( !mClearGBufferShader )
  931. return;
  932. GFXTransformSaver saver;
  933. // Clear the g-buffer.
  934. RectI box(-1, -1, 3, 3);
  935. GFX->setWorldMatrix( MatrixF::Identity );
  936. GFX->setViewMatrix( MatrixF::Identity );
  937. GFX->setProjectionMatrix( MatrixF::Identity );
  938. GFX->setShader(mClearGBufferShader);
  939. GFX->setStateBlock(mStateblock);
  940. Point2F nw(-0.5,-0.5);
  941. Point2F ne(0.5,-0.5);
  942. GFXVertexBufferHandle<GFXVertexPC> verts(GFX, 4, GFXBufferTypeVolatile);
  943. verts.lock();
  944. F32 ulOffset = 0.5f - GFX->getFillConventionOffset();
  945. Point2F upperLeft(-1.0, -1.0);
  946. Point2F lowerRight(1.0, 1.0);
  947. verts[0].point.set( upperLeft.x+nw.x+ulOffset, upperLeft.y+nw.y+ulOffset, 0.0f );
  948. verts[1].point.set( lowerRight.x+ne.x, upperLeft.y+ne.y+ulOffset, 0.0f );
  949. verts[2].point.set( upperLeft.x-ne.x+ulOffset, lowerRight.y-ne.y, 0.0f );
  950. verts[3].point.set( lowerRight.x-nw.x, lowerRight.y-nw.y, 0.0f );
  951. verts.unlock();
  952. GFX->setVertexBuffer( verts );
  953. GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
  954. GFX->setShader(NULL);
  955. }