renderDeferredMgr.cpp 38 KB

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