renderPrePassMgr.cpp 40 KB

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