renderDeferredMgr.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167
  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. //-JR
  355. //push along any overriden fields that are instance-specific as well
  356. //mat->setCustomShaderHandles()
  357. // If we're instanced then don't render yet.
  358. if ( mat->isInstanced() )
  359. {
  360. // Let the material increment the instance buffer, but
  361. // break the batch if it runs out of room for more.
  362. if ( !mat->stepInstance() )
  363. {
  364. meshItr++;
  365. break;
  366. }
  367. continue;
  368. }
  369. bool dirty = false;
  370. // set the lightmaps if different
  371. if( passRI->lightmap && passRI->lightmap != lastLM )
  372. {
  373. sgData.lightmap = passRI->lightmap;
  374. lastLM = passRI->lightmap;
  375. dirty = true;
  376. }
  377. // set the cubemap if different.
  378. if ( passRI->cubemap != lastCubemap )
  379. {
  380. sgData.cubemap = passRI->cubemap;
  381. lastCubemap = passRI->cubemap;
  382. dirty = true;
  383. }
  384. if ( passRI->reflectTex != lastReflectTex )
  385. {
  386. sgData.reflectTex = passRI->reflectTex;
  387. lastReflectTex = passRI->reflectTex;
  388. dirty = true;
  389. }
  390. // Update accumulation texture if it changed.
  391. // Note: accumulation texture can be NULL, and must be updated.
  392. if (passRI->accuTex != lastAccuTex)
  393. {
  394. sgData.accuTex = passRI->accuTex;
  395. lastAccuTex = passRI->accuTex;
  396. dirty = true;
  397. }
  398. if ( dirty )
  399. mat->setTextureStages( state, sgData );
  400. // Setup the vertex and index buffers.
  401. mat->setBuffers( passRI->vertBuff, passRI->primBuff );
  402. // Render this sucker.
  403. if ( passRI->prim )
  404. GFX->drawPrimitive( *passRI->prim );
  405. else
  406. GFX->drawPrimitive( passRI->primBuffIndex );
  407. }
  408. // Draw the instanced batch.
  409. if ( mat->isInstanced() )
  410. {
  411. // Sets the buffers including the instancing stream.
  412. mat->setBuffers( ri->vertBuff, ri->primBuff );
  413. if ( ri->prim )
  414. GFX->drawPrimitive( *ri->prim );
  415. else
  416. GFX->drawPrimitive( ri->primBuffIndex );
  417. }
  418. endOfBatchItr = meshItr;
  419. } // while( mat->setupPass(state, sgData) )
  420. // Force the increment if none happened, otherwise go to end of batch.
  421. itr = ( itr == endOfBatchItr ) ? itr + 1 : endOfBatchItr;
  422. }
  423. // The final loop is for object render instances.
  424. itr = mObjectElementList.begin();
  425. for ( ; itr != mObjectElementList.end(); itr++ )
  426. {
  427. ObjectRenderInst *ri = static_cast<ObjectRenderInst*>( itr->inst );
  428. if ( ri->renderDelegate )
  429. ri->renderDelegate( ri, state, mDeferredMatInstance );
  430. }
  431. // Signal end of pre-pass
  432. getRenderSignal().trigger( state, this, false );
  433. if(isRenderingToTarget)
  434. _onPostRender();
  435. }
  436. const GFXStateBlockDesc & RenderDeferredMgr::getOpaqueStenciWriteDesc( bool lightmappedGeometry /*= true*/ )
  437. {
  438. static bool sbInit = false;
  439. static GFXStateBlockDesc sOpaqueStaticLitStencilWriteDesc;
  440. static GFXStateBlockDesc sOpaqueDynamicLitStencilWriteDesc;
  441. if(!sbInit)
  442. {
  443. sbInit = true;
  444. // Build the static opaque stencil write/test state block descriptions
  445. sOpaqueStaticLitStencilWriteDesc.stencilDefined = true;
  446. sOpaqueStaticLitStencilWriteDesc.stencilEnable = true;
  447. sOpaqueStaticLitStencilWriteDesc.stencilWriteMask = 0x03;
  448. sOpaqueStaticLitStencilWriteDesc.stencilMask = 0x03;
  449. sOpaqueStaticLitStencilWriteDesc.stencilRef = RenderDeferredMgr::OpaqueStaticLitMask;
  450. sOpaqueStaticLitStencilWriteDesc.stencilPassOp = GFXStencilOpReplace;
  451. sOpaqueStaticLitStencilWriteDesc.stencilFailOp = GFXStencilOpKeep;
  452. sOpaqueStaticLitStencilWriteDesc.stencilZFailOp = GFXStencilOpKeep;
  453. sOpaqueStaticLitStencilWriteDesc.stencilFunc = GFXCmpAlways;
  454. // Same only dynamic
  455. sOpaqueDynamicLitStencilWriteDesc = sOpaqueStaticLitStencilWriteDesc;
  456. sOpaqueDynamicLitStencilWriteDesc.stencilRef = RenderDeferredMgr::OpaqueDynamicLitMask;
  457. }
  458. return (lightmappedGeometry ? sOpaqueStaticLitStencilWriteDesc : sOpaqueDynamicLitStencilWriteDesc);
  459. }
  460. const GFXStateBlockDesc & RenderDeferredMgr::getOpaqueStencilTestDesc()
  461. {
  462. static bool sbInit = false;
  463. static GFXStateBlockDesc sOpaqueStencilTestDesc;
  464. if(!sbInit)
  465. {
  466. // Build opaque test
  467. sbInit = true;
  468. sOpaqueStencilTestDesc.stencilDefined = true;
  469. sOpaqueStencilTestDesc.stencilEnable = true;
  470. sOpaqueStencilTestDesc.stencilWriteMask = 0xFE;
  471. sOpaqueStencilTestDesc.stencilMask = 0x03;
  472. sOpaqueStencilTestDesc.stencilRef = 0;
  473. sOpaqueStencilTestDesc.stencilPassOp = GFXStencilOpKeep;
  474. sOpaqueStencilTestDesc.stencilFailOp = GFXStencilOpKeep;
  475. sOpaqueStencilTestDesc.stencilZFailOp = GFXStencilOpKeep;
  476. sOpaqueStencilTestDesc.stencilFunc = GFXCmpLess;
  477. }
  478. return sOpaqueStencilTestDesc;
  479. }
  480. //------------------------------------------------------------------------------
  481. //------------------------------------------------------------------------------
  482. ProcessedDeferredMaterial::ProcessedDeferredMaterial( Material& mat, const RenderDeferredMgr *deferredMgr )
  483. : Parent(mat), mDeferredMgr(deferredMgr)
  484. {
  485. }
  486. void ProcessedDeferredMaterial::_determineFeatures( U32 stageNum,
  487. MaterialFeatureData &fd,
  488. const FeatureSet &features )
  489. {
  490. Parent::_determineFeatures( stageNum, fd, features );
  491. // Find this for use down below...
  492. bool bEnableMRTLightmap = false;
  493. AdvancedLightBinManager *lightBin;
  494. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) )
  495. bEnableMRTLightmap = lightBin->MRTLightmapsDuringDeferred();
  496. // If this material has a lightmap or tonemap (texture or baked vertex color),
  497. // it must be static. Otherwise it is dynamic.
  498. mIsLightmappedGeometry = ( fd.features.hasFeature( MFT_ToneMap ) ||
  499. fd.features.hasFeature( MFT_LightMap ) ||
  500. fd.features.hasFeature( MFT_VertLit ) ||
  501. ( bEnableMRTLightmap && (fd.features.hasFeature( MFT_IsTranslucent ) ||
  502. fd.features.hasFeature( MFT_ForwardShading ) ||
  503. fd.features.hasFeature( MFT_IsTranslucentZWrite) ) ) );
  504. // Integrate proper opaque stencil write state
  505. mUserDefined.addDesc( mDeferredMgr->getOpaqueStenciWriteDesc( mIsLightmappedGeometry ) );
  506. FeatureSet newFeatures;
  507. // These are always on for deferred.
  508. newFeatures.addFeature( MFT_EyeSpaceDepthOut );
  509. newFeatures.addFeature( MFT_DeferredConditioner );
  510. #ifndef TORQUE_DEDICATED
  511. //tag all materials running through deferred as deferred
  512. newFeatures.addFeature(MFT_isDeferred);
  513. // Deferred Shading : Diffuse
  514. if (mStages[stageNum].getTex( MFT_DiffuseMap ))
  515. {
  516. newFeatures.addFeature(MFT_DiffuseMap);
  517. }
  518. newFeatures.addFeature( MFT_DiffuseColor );
  519. // Deferred Shading : Specular
  520. if( mStages[stageNum].getTex( MFT_SpecularMap ) )
  521. {
  522. newFeatures.addFeature( MFT_DeferredSpecMap );
  523. }
  524. else if ( mMaterial->mPixelSpecular[stageNum] )
  525. {
  526. newFeatures.addFeature( MFT_DeferredSpecVars );
  527. }
  528. else
  529. newFeatures.addFeature(MFT_DeferredEmptySpec);
  530. // Deferred Shading : Material Info Flags
  531. newFeatures.addFeature( MFT_DeferredMatInfoFlags );
  532. for ( U32 i=0; i < fd.features.getCount(); i++ )
  533. {
  534. const FeatureType &type = fd.features.getAt( i );
  535. // Turn on the diffuse texture only if we
  536. // have alpha test.
  537. if ( type == MFT_AlphaTest )
  538. {
  539. newFeatures.addFeature( MFT_AlphaTest );
  540. newFeatures.addFeature( MFT_DiffuseMap );
  541. }
  542. else if ( type == MFT_IsTranslucentZWrite )
  543. {
  544. newFeatures.addFeature( MFT_IsTranslucentZWrite );
  545. newFeatures.addFeature( MFT_DiffuseMap );
  546. }
  547. // Always allow these.
  548. else if ( type == MFT_IsBC3nm ||
  549. type == MFT_IsBC5nm ||
  550. type == MFT_TexAnim ||
  551. type == MFT_NormalMap ||
  552. type == MFT_DetailNormalMap ||
  553. type == MFT_AlphaTest ||
  554. type == MFT_Parallax ||
  555. type == MFT_InterlacedDeferred ||
  556. type == MFT_Visibility ||
  557. type == MFT_UseInstancing ||
  558. type == MFT_DiffuseVertColor ||
  559. type == MFT_DetailMap ||
  560. type == MFT_DiffuseMapAtlas)
  561. newFeatures.addFeature( type );
  562. // Add any transform features.
  563. else if ( type.getGroup() == MFG_PreTransform ||
  564. type.getGroup() == MFG_Transform ||
  565. type.getGroup() == MFG_PostTransform )
  566. newFeatures.addFeature( type );
  567. }
  568. if (mMaterial->mAccuEnabled[stageNum])
  569. {
  570. newFeatures.addFeature(MFT_AccuMap);
  571. mHasAccumulation = true;
  572. }
  573. // we need both diffuse and normal maps + sm3 to have an accu map
  574. if (newFeatures[MFT_AccuMap] &&
  575. (!newFeatures[MFT_DiffuseMap] ||
  576. !newFeatures[MFT_NormalMap] ||
  577. GFX->getPixelShaderVersion() < 3.0f)) {
  578. AssertWarn(false, "SAHARA: Using an Accu Map requires SM 3.0 and a normal map.");
  579. newFeatures.removeFeature(MFT_AccuMap);
  580. mHasAccumulation = false;
  581. }
  582. // if we still have the AccuMap feature, we add all accu constant features
  583. if (newFeatures[MFT_AccuMap]) {
  584. // add the dependencies of the accu map
  585. newFeatures.addFeature(MFT_AccuScale);
  586. newFeatures.addFeature(MFT_AccuDirection);
  587. newFeatures.addFeature(MFT_AccuStrength);
  588. newFeatures.addFeature(MFT_AccuCoverage);
  589. newFeatures.addFeature(MFT_AccuSpecular);
  590. // now remove some features that are not compatible with this
  591. newFeatures.removeFeature(MFT_UseInstancing);
  592. }
  593. // If there is lightmapped geometry support, add the MRT light buffer features
  594. if(bEnableMRTLightmap)
  595. {
  596. // If this material has a lightmap, pass it through, and flag it to
  597. // send it's output to RenderTarget3
  598. if( fd.features.hasFeature( MFT_ToneMap ) )
  599. {
  600. newFeatures.addFeature( MFT_ToneMap );
  601. newFeatures.addFeature( MFT_LightbufferMRT );
  602. }
  603. else if( fd.features.hasFeature( MFT_LightMap ) )
  604. {
  605. newFeatures.addFeature( MFT_LightMap );
  606. newFeatures.addFeature( MFT_LightbufferMRT );
  607. }
  608. else if( fd.features.hasFeature( MFT_VertLit ) )
  609. {
  610. // Flag un-tone-map if necesasary
  611. if( fd.features.hasFeature( MFT_DiffuseMap ) )
  612. newFeatures.addFeature( MFT_VertLitTone );
  613. newFeatures.addFeature( MFT_VertLit );
  614. newFeatures.addFeature( MFT_LightbufferMRT );
  615. }
  616. else
  617. {
  618. // If this object isn't lightmapped, add a zero-output feature to it
  619. newFeatures.addFeature( MFT_RenderTarget3_Zero );
  620. }
  621. }
  622. // cubemaps only available on stage 0 for now - bramage
  623. if ( stageNum < 1 &&
  624. ( ( mMaterial->mCubemapData && mMaterial->mCubemapData->mCubemap ) ||
  625. mMaterial->mDynamicCubemap ) )
  626. newFeatures.addFeature( MFT_CubeMap );
  627. #endif
  628. // Set the new features.
  629. fd.features = newFeatures;
  630. }
  631. U32 ProcessedDeferredMaterial::getNumStages()
  632. {
  633. // Loops through all stages to determine how many
  634. // stages we actually use.
  635. //
  636. // The first stage is always active else we shouldn't be
  637. // creating the material to begin with.
  638. U32 numStages = 1;
  639. U32 i;
  640. for( i=1; i<Material::MAX_STAGES; i++ )
  641. {
  642. // Assume stage is inactive
  643. bool stageActive = false;
  644. // Cubemaps only on first stage
  645. if( i == 0 )
  646. {
  647. // If we have a cubemap the stage is active
  648. if( mMaterial->mCubemapData || mMaterial->mDynamicCubemap )
  649. {
  650. numStages++;
  651. continue;
  652. }
  653. }
  654. // If we have a texture for the a feature the
  655. // stage is active.
  656. if ( mStages[i].hasValidTex() )
  657. stageActive = true;
  658. // If this stage has specular lighting, it's active
  659. if ( mMaterial->mPixelSpecular[i] )
  660. stageActive = true;
  661. // If this stage has diffuse color, it's active
  662. if ( mMaterial->mDiffuse[i].alpha > 0 &&
  663. mMaterial->mDiffuse[i] != LinearColorF::WHITE )
  664. stageActive = true;
  665. // If we have a Material that is vertex lit
  666. // then it may not have a texture
  667. if( mMaterial->mVertLit[i] )
  668. stageActive = true;
  669. // Increment the number of active stages
  670. numStages += stageActive;
  671. }
  672. return numStages;
  673. }
  674. void ProcessedDeferredMaterial::addStateBlockDesc(const GFXStateBlockDesc& desc)
  675. {
  676. GFXStateBlockDesc deferredStateBlock = desc;
  677. // Adjust color writes if this is a pure z-fill pass
  678. const bool pixelOutEnabled = mDeferredMgr->getTargetChainLength() > 0;
  679. if ( !pixelOutEnabled )
  680. {
  681. deferredStateBlock.colorWriteDefined = true;
  682. deferredStateBlock.colorWriteRed = pixelOutEnabled;
  683. deferredStateBlock.colorWriteGreen = pixelOutEnabled;
  684. deferredStateBlock.colorWriteBlue = pixelOutEnabled;
  685. deferredStateBlock.colorWriteAlpha = pixelOutEnabled;
  686. }
  687. // Never allow the alpha test state when rendering
  688. // the deferred as we use the alpha channel for the
  689. // depth information... MFT_AlphaTest will handle it.
  690. deferredStateBlock.alphaDefined = true;
  691. deferredStateBlock.alphaTestEnable = false;
  692. // If we're translucent then we're doing deferred blending
  693. // which never writes to the depth channels.
  694. const bool isTranslucent = getMaterial()->isTranslucent();
  695. if ( isTranslucent )
  696. {
  697. deferredStateBlock.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  698. deferredStateBlock.setColorWrites(false, false, false, true);
  699. }
  700. // Enable z reads, but only enable zwrites if we're not translucent.
  701. deferredStateBlock.setZReadWrite( true, isTranslucent ? false : true );
  702. // Pass to parent
  703. Parent::addStateBlockDesc(deferredStateBlock);
  704. }
  705. DeferredMatInstance::DeferredMatInstance(MatInstance* root, const RenderDeferredMgr *deferredMgr)
  706. : Parent(*root->getMaterial()), mDeferredMgr(deferredMgr)
  707. {
  708. mFeatureList = root->getRequestedFeatures();
  709. mVertexFormat = root->getVertexFormat();
  710. mUserObject = root->getUserObject();
  711. }
  712. DeferredMatInstance::~DeferredMatInstance()
  713. {
  714. }
  715. ProcessedMaterial* DeferredMatInstance::getShaderMaterial()
  716. {
  717. return new ProcessedDeferredMaterial(*mMaterial, mDeferredMgr);
  718. }
  719. bool DeferredMatInstance::init( const FeatureSet &features,
  720. const GFXVertexFormat *vertexFormat )
  721. {
  722. bool vaild = Parent::init(features, vertexFormat);
  723. if (mMaterial && mMaterial->mDiffuseMapFilename[0].isNotEmpty() && mMaterial->mDiffuseMapFilename[0].substr(0, 1).equal("#"))
  724. {
  725. String texTargetBufferName = mMaterial->mDiffuseMapFilename[0].substr(1, mMaterial->mDiffuseMapFilename[0].length() - 1);
  726. NamedTexTarget *texTarget = NamedTexTarget::find(texTargetBufferName);
  727. RenderPassData* rpd = getPass(0);
  728. if (rpd)
  729. {
  730. rpd->mTexSlot[0].texTarget = texTarget;
  731. rpd->mTexType[0] = Material::TexTarget;
  732. rpd->mSamplerNames[0] = "diffuseMap";
  733. }
  734. }
  735. return vaild;
  736. }
  737. DeferredMatInstanceHook::DeferredMatInstanceHook( MatInstance *baseMatInst,
  738. const RenderDeferredMgr *deferredMgr )
  739. : mHookedDeferredMatInst(NULL), mDeferredManager(deferredMgr)
  740. {
  741. // If the material is a custom material then
  742. // hope that using DefaultDeferredMaterial gives
  743. // them a good deferred.
  744. if ( baseMatInst->isCustomMaterial() )
  745. {
  746. MatInstance* dummyInst = static_cast<MatInstance*>( MATMGR->createMatInstance( "AL_DefaultDeferredMaterial", baseMatInst->getVertexFormat() ) );
  747. mHookedDeferredMatInst = new DeferredMatInstance( dummyInst, deferredMgr );
  748. mHookedDeferredMatInst->init( dummyInst->getRequestedFeatures(), baseMatInst->getVertexFormat());
  749. delete dummyInst;
  750. return;
  751. }
  752. // Create the deferred material instance.
  753. mHookedDeferredMatInst = new DeferredMatInstance(baseMatInst, deferredMgr);
  754. mHookedDeferredMatInst->getFeaturesDelegate() = baseMatInst->getFeaturesDelegate();
  755. // Get the features, but remove the instancing feature if the
  756. // original material didn't end up using it.
  757. FeatureSet features = baseMatInst->getRequestedFeatures();
  758. if ( !baseMatInst->isInstanced() )
  759. features.removeFeature( MFT_UseInstancing );
  760. // Initialize the material.
  761. mHookedDeferredMatInst->init(features, baseMatInst->getVertexFormat());
  762. }
  763. DeferredMatInstanceHook::~DeferredMatInstanceHook()
  764. {
  765. SAFE_DELETE(mHookedDeferredMatInst);
  766. }
  767. //------------------------------------------------------------------------------
  768. //------------------------------------------------------------------------------
  769. void LinearEyeDepthConditioner::processPix( Vector<ShaderComponent*> &componentList, const MaterialFeatureData &fd )
  770. {
  771. // find depth
  772. ShaderFeature *depthFeat = FEATUREMGR->getByType( MFT_EyeSpaceDepthOut );
  773. AssertFatal( depthFeat != NULL, "No eye space depth feature found!" );
  774. Var *depth = (Var*) LangElement::find(depthFeat->getOutputVarName());
  775. AssertFatal( depth, "Something went bad with ShaderGen. The depth should be already generated by the EyeSpaceDepthOut feature." );
  776. MultiLine *meta = new MultiLine;
  777. meta->addStatement( assignOutput( depth ) );
  778. output = meta;
  779. }
  780. Var *LinearEyeDepthConditioner::_conditionOutput( Var *unconditionedOutput, MultiLine *meta )
  781. {
  782. Var *retVar = NULL;
  783. String fracMethodName = (GFX->getAdapterType() == OpenGL) ? "fract" : "frac";
  784. switch(getBufferFormat())
  785. {
  786. case GFXFormatR8G8B8A8:
  787. retVar = new Var;
  788. retVar->setType("float4");
  789. retVar->setName("_ppDepth");
  790. meta->addStatement( new GenOp( " // depth conditioner: packing to rgba\r\n" ) );
  791. meta->addStatement( new GenOp(
  792. avar( " @ = %s(@ * (255.0/256) * float4(1, 255, 255 * 255, 255 * 255 * 255));\r\n", fracMethodName.c_str() ),
  793. new DecOp(retVar), unconditionedOutput ) );
  794. break;
  795. default:
  796. retVar = unconditionedOutput;
  797. meta->addStatement( new GenOp( " // depth conditioner: no conditioning\r\n" ) );
  798. break;
  799. }
  800. AssertFatal( retVar != NULL, avar( "Cannot condition output to buffer format: %s", GFXStringTextureFormat[getBufferFormat()] ) );
  801. return retVar;
  802. }
  803. Var *LinearEyeDepthConditioner::_unconditionInput( Var *conditionedInput, MultiLine *meta )
  804. {
  805. String float4Typename = (GFX->getAdapterType() == OpenGL) ? "vec4" : "float4";
  806. Var *retVar = conditionedInput;
  807. if(getBufferFormat() != GFXFormat_COUNT)
  808. {
  809. retVar = new Var;
  810. retVar->setType(float4Typename.c_str());
  811. retVar->setName("_ppDepth");
  812. meta->addStatement( new GenOp( avar( " @ = %s(0, 0, 1, 1);\r\n", float4Typename.c_str() ), new DecOp(retVar) ) );
  813. switch(getBufferFormat())
  814. {
  815. case GFXFormatR32F:
  816. case GFXFormatR16F:
  817. meta->addStatement( new GenOp( " // depth conditioner: float texture\r\n" ) );
  818. meta->addStatement( new GenOp( " @.w = @.r;\r\n", retVar, conditionedInput ) );
  819. break;
  820. case GFXFormatR8G8B8A8:
  821. meta->addStatement( new GenOp( " // depth conditioner: unpacking from rgba\r\n" ) );
  822. meta->addStatement( new GenOp(
  823. avar( " @.w = dot(@ * (256.0/255), %s(1, 1 / 255, 1 / (255 * 255), 1 / (255 * 255 * 255)));\r\n", float4Typename.c_str() )
  824. , retVar, conditionedInput ) );
  825. break;
  826. default:
  827. AssertFatal(false, "LinearEyeDepthConditioner::_unconditionInput - Unrecognized buffer format");
  828. }
  829. }
  830. return retVar;
  831. }
  832. Var* LinearEyeDepthConditioner::printMethodHeader( MethodType methodType, const String &methodName, Stream &stream, MultiLine *meta )
  833. {
  834. const bool isCondition = ( methodType == ConditionerFeature::ConditionMethod );
  835. Var *retVal = NULL;
  836. // The uncondition method inputs are changed
  837. if( isCondition )
  838. retVal = Parent::printMethodHeader( methodType, methodName, stream, meta );
  839. else
  840. {
  841. Var *methodVar = new Var;
  842. methodVar->setName(methodName);
  843. if (GFX->getAdapterType() == OpenGL)
  844. methodVar->setType("vec4");
  845. else
  846. methodVar->setType("inline float4");
  847. DecOp *methodDecl = new DecOp(methodVar);
  848. Var *deferredSampler = new Var;
  849. deferredSampler->setName("deferredSamplerVar");
  850. deferredSampler->setType("sampler2D");
  851. DecOp *deferredSamplerDecl = NULL;
  852. Var *deferredTex = NULL;
  853. DecOp *deferredTexDecl = NULL;
  854. if (GFX->getAdapterType() == Direct3D11)
  855. {
  856. deferredSampler->setType("SamplerState");
  857. deferredTex = new Var;
  858. deferredTex->setName("deferredTexVar");
  859. deferredTex->setType("Texture2D");
  860. deferredTexDecl = new DecOp(deferredTex);
  861. }
  862. deferredSamplerDecl = new DecOp(deferredSampler);
  863. Var *screenUV = new Var;
  864. screenUV->setName("screenUVVar");
  865. if (GFX->getAdapterType() == OpenGL)
  866. screenUV->setType("vec2");
  867. else
  868. screenUV->setType("float2");
  869. DecOp *screenUVDecl = new DecOp(screenUV);
  870. Var *bufferSample = new Var;
  871. bufferSample->setName("bufferSample");
  872. if (GFX->getAdapterType() == OpenGL)
  873. bufferSample->setType("vec4");
  874. else
  875. bufferSample->setType("float4");
  876. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  877. meta->addStatement( new GenOp( "@(@, @)\r\n", methodDecl, deferredSamplerDecl, screenUVDecl ) );
  878. meta->addStatement( new GenOp( "{\r\n" ) );
  879. meta->addStatement( new GenOp( " // Sampler g-buffer\r\n" ) );
  880. // The linear depth target has no mipmaps, so use tex2dlod when
  881. // possible so that the shader compiler can optimize.
  882. meta->addStatement( new GenOp( " #if TORQUE_SM >= 30\r\n" ) );
  883. if (GFX->getAdapterType() == OpenGL)
  884. meta->addStatement( new GenOp( " @ = textureLod(@, @, 0); \r\n", bufferSampleDecl, deferredSampler, screenUV) );
  885. else
  886. meta->addStatement( new GenOp( " @ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, deferredSampler, screenUV ) );
  887. meta->addStatement( new GenOp( " #else\r\n" ) );
  888. if (GFX->getAdapterType() == OpenGL)
  889. meta->addStatement( new GenOp( " @ = texture(@, @);\r\n", bufferSampleDecl, deferredSampler, screenUV) );
  890. else
  891. meta->addStatement( new GenOp( " @ = tex2D(@, @);\r\n", bufferSampleDecl, deferredSampler, screenUV ) );
  892. meta->addStatement( new GenOp( " #endif\r\n\r\n" ) );
  893. // We don't use this way of passing var's around, so this should cause a crash
  894. // if something uses this improperly
  895. retVal = bufferSample;
  896. }
  897. return retVal;
  898. }
  899. void RenderDeferredMgr::_initShaders()
  900. {
  901. if ( mClearGBufferShader ) return;
  902. // Find ShaderData
  903. ShaderData *shaderData;
  904. mClearGBufferShader = Sim::findObject( "ClearGBufferShader", shaderData ) ? shaderData->getShader() : NULL;
  905. if ( !mClearGBufferShader )
  906. Con::errorf( "RenderDeferredMgr::_initShaders - could not find ClearGBufferShader" );
  907. // Create StateBlocks
  908. GFXStateBlockDesc desc;
  909. desc.setCullMode( GFXCullNone );
  910. desc.setBlend( false );
  911. desc.setZReadWrite( false, false );
  912. desc.samplersDefined = true;
  913. for (int i = 0; i < TEXTURE_STAGE_COUNT; i++)
  914. {
  915. desc.samplers[i].addressModeU = GFXAddressWrap;
  916. desc.samplers[i].addressModeV = GFXAddressWrap;
  917. desc.samplers[i].addressModeW = GFXAddressWrap;
  918. desc.samplers[i].magFilter = GFXTextureFilterLinear;
  919. desc.samplers[i].minFilter = GFXTextureFilterLinear;
  920. desc.samplers[i].mipFilter = GFXTextureFilterLinear;
  921. desc.samplers[i].textureColorOp = GFXTOPModulate;
  922. }
  923. mStateblock = GFX->createStateBlock( desc );
  924. // Set up shader constants.
  925. mShaderConsts = mClearGBufferShader->allocConstBuffer();
  926. mSpecularStrengthSC = mClearGBufferShader->getShaderConstHandle( "$specularStrength" );
  927. mSpecularPowerSC = mClearGBufferShader->getShaderConstHandle( "$specularPower" );
  928. }
  929. void RenderDeferredMgr::clearBuffers()
  930. {
  931. // Clear z-buffer.
  932. GFX->clear( GFXClearTarget | GFXClearZBuffer | GFXClearStencil, ColorI::ZERO, 1.0f, 0);
  933. if ( !mClearGBufferShader )
  934. return;
  935. GFXTransformSaver saver;
  936. // Clear the g-buffer.
  937. RectI box(-1, -1, 3, 3);
  938. GFX->setWorldMatrix( MatrixF::Identity );
  939. GFX->setViewMatrix( MatrixF::Identity );
  940. GFX->setProjectionMatrix( MatrixF::Identity );
  941. GFX->setShader(mClearGBufferShader);
  942. GFX->setStateBlock(mStateblock);
  943. Point2F nw(-0.5,-0.5);
  944. Point2F ne(0.5,-0.5);
  945. GFXVertexBufferHandle<GFXVertexPC> verts(GFX, 4, GFXBufferTypeVolatile);
  946. verts.lock();
  947. F32 ulOffset = 0.5f - GFX->getFillConventionOffset();
  948. Point2F upperLeft(-1.0, -1.0);
  949. Point2F lowerRight(1.0, 1.0);
  950. verts[0].point.set( upperLeft.x+nw.x+ulOffset, upperLeft.y+nw.y+ulOffset, 0.0f );
  951. verts[1].point.set( lowerRight.x+ne.x, upperLeft.y+ne.y+ulOffset, 0.0f );
  952. verts[2].point.set( upperLeft.x-ne.x+ulOffset, lowerRight.y-ne.y, 0.0f );
  953. verts[3].point.set( lowerRight.x-nw.x, lowerRight.y-nw.y, 0.0f );
  954. verts.unlock();
  955. GFX->setVertexBuffer( verts );
  956. GFX->drawPrimitive( GFXTriangleStrip, 0, 2 );
  957. GFX->setShader(NULL);
  958. }