renderDeferredMgr.cpp 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091
  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. const String RenderDeferredMgr::LightMapBufferName("diffuseLighting");
  57. IMPLEMENT_CONOBJECT(RenderDeferredMgr);
  58. ConsoleDocClass( RenderDeferredMgr,
  59. "@brief The render bin which performs a z+normals deferred used in Advanced Lighting.\n\n"
  60. "This render bin is used in Advanced Lighting to gather all opaque mesh render instances "
  61. "and render them to the g-buffer for use in lighting the scene and doing effects.\n\n"
  62. "PostEffect and other shaders can access the output of this bin by using the #deferred "
  63. "texture target name. See the edge anti-aliasing post effect for an example.\n\n"
  64. "@see game/core/scripts/client/postFx/edgeAA.cs\n"
  65. "@ingroup RenderBin\n" );
  66. RenderDeferredMgr::RenderSignal& RenderDeferredMgr::getRenderSignal()
  67. {
  68. static RenderSignal theSignal;
  69. return theSignal;
  70. }
  71. RenderDeferredMgr::RenderDeferredMgr( bool gatherDepth,
  72. GFXFormat format )
  73. : Parent( RIT_Deferred,
  74. 0.01f,
  75. 0.01f,
  76. format,
  77. Point2I( Parent::DefaultTargetSize, Parent::DefaultTargetSize),
  78. gatherDepth ? Parent::DefaultTargetChainLength : 0 ),
  79. mDeferredMatInstance( NULL )
  80. {
  81. notifyType( RenderPassManager::RIT_Decal );
  82. notifyType( RenderPassManager::RIT_DecalRoad );
  83. notifyType( RenderPassManager::RIT_Mesh );
  84. notifyType( RenderPassManager::RIT_Terrain );
  85. notifyType( RenderPassManager::RIT_Object );
  86. notifyType( RenderPassManager::RIT_Probes );
  87. // We want a full-resolution buffer
  88. mTargetSizeType = RenderTexTargetBinManager::WindowSize;
  89. if(getTargetChainLength() > 0)
  90. GFXShader::addGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  91. mNamedTarget.registerWithName( BufferName );
  92. mColorTarget.registerWithName( ColorBufferName );
  93. mMatInfoTarget.registerWithName( MatInfoBufferName );
  94. mLightMapTarget.registerWithName( LightMapBufferName );
  95. _registerFeatures();
  96. }
  97. RenderDeferredMgr::~RenderDeferredMgr()
  98. {
  99. GFXShader::removeGlobalMacro( "TORQUE_LINEAR_DEPTH" );
  100. mColorTarget.release();
  101. mMatInfoTarget.release();
  102. mLightMapTarget.release();
  103. _unregisterFeatures();
  104. SAFE_DELETE( mDeferredMatInstance );
  105. }
  106. void RenderDeferredMgr::_registerFeatures()
  107. {
  108. ConditionerFeature *cond = new LinearEyeDepthConditioner( getTargetFormat() );
  109. FEATUREMGR->registerFeature( MFT_DeferredConditioner, cond );
  110. mNamedTarget.setConditioner( cond );
  111. }
  112. void RenderDeferredMgr::_unregisterFeatures()
  113. {
  114. mNamedTarget.setConditioner( NULL );
  115. FEATUREMGR->unregisterFeature(MFT_DeferredConditioner);
  116. }
  117. bool RenderDeferredMgr::setTargetSize(const Point2I &newTargetSize)
  118. {
  119. bool ret = Parent::setTargetSize( newTargetSize );
  120. mNamedTarget.setViewport( GFX->getViewport() );
  121. mColorTarget.setViewport( GFX->getViewport() );
  122. mMatInfoTarget.setViewport( GFX->getViewport() );
  123. mLightMapTarget.setViewport( GFX->getViewport() );
  124. return ret;
  125. }
  126. bool RenderDeferredMgr::_updateTargets()
  127. {
  128. PROFILE_SCOPE(RenderDeferredMgr_updateTargets);
  129. bool ret = Parent::_updateTargets();
  130. // check for an output conditioner, and update it's format
  131. ConditionerFeature *outputConditioner = dynamic_cast<ConditionerFeature *>(FEATUREMGR->getByType(MFT_DeferredConditioner));
  132. if( outputConditioner && outputConditioner->setBufferFormat(mTargetFormat) )
  133. {
  134. // reload materials, the conditioner needs to alter the generated shaders
  135. }
  136. // TODO: these formats should be passed in and not hard-coded
  137. const GFXFormat colorFormat = GFXFormatR8G8B8A8_SRGB;
  138. const GFXFormat matInfoFormat = GFXFormatR8G8B8A8;
  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. &GFXRenderTargetSRGBProfile, 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() != matInfoFormat || mMatInfoTex.getWidthHeight() != mTargetSize || GFX->recentlyReset())
  152. {
  153. mMatInfoTarget.release();
  154. mMatInfoTex.set(mTargetSize.x, mTargetSize.y, matInfoFormat,
  155. &GFXRenderTargetProfile, 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. if (mLightMapTex.getFormat() != GFXFormatR16G16B16A16F || mLightMapTex.getWidthHeight() != mTargetSize || GFX->recentlyReset())
  162. {
  163. mLightMapTarget.release();
  164. mLightMapTex.set(mTargetSize.x, mTargetSize.y, GFXFormatR16G16B16A16F,
  165. &GFXRenderTargetProfile, avar("%s() - (line %d)", __FUNCTION__, __LINE__),
  166. 1, GFXTextureManager::AA_MATCH_BACKBUFFER);
  167. mLightMapTarget.setTexture(mLightMapTex);
  168. for (U32 i = 0; i < mTargetChainLength; i++)
  169. mTargetChain[i]->attachTexture(GFXTextureTarget::Color3, mLightMapTarget.getTexture());
  170. }
  171. GFX->finalizeReset();
  172. return ret;
  173. }
  174. void RenderDeferredMgr::_createDeferredMaterial()
  175. {
  176. SAFE_DELETE(mDeferredMatInstance);
  177. const GFXVertexFormat *vertexFormat = getGFXVertexFormat<GFXVertexPNTTB>();
  178. MatInstance* deferredMat = static_cast<MatInstance*>(MATMGR->createMatInstance("AL_DefaultDeferredMaterial", vertexFormat));
  179. AssertFatal( deferredMat, "TODO: Handle this better." );
  180. mDeferredMatInstance = new DeferredMatInstance(deferredMat, this);
  181. mDeferredMatInstance->init( MATMGR->getDefaultFeatures(), vertexFormat);
  182. delete deferredMat;
  183. }
  184. void RenderDeferredMgr::setDeferredMaterial( DeferredMatInstance *mat )
  185. {
  186. SAFE_DELETE(mDeferredMatInstance);
  187. mDeferredMatInstance = mat;
  188. }
  189. void RenderDeferredMgr::addElement( RenderInst *inst )
  190. {
  191. PROFILE_SCOPE( RenderDeferredMgr_addElement )
  192. // Skip out if this bin is disabled.
  193. if ( gClientSceneGraph->getCurrentRenderState() &&
  194. gClientSceneGraph->getCurrentRenderState()->disableAdvancedLightingBins() )
  195. return;
  196. // First what type of render instance is it?
  197. const bool isDecalMeshInst = ((inst->type == RenderPassManager::RIT_Decal)||(inst->type == RenderPassManager::RIT_DecalRoad));
  198. const bool isMeshInst = inst->type == RenderPassManager::RIT_Mesh;
  199. const bool isTerrainInst = inst->type == RenderPassManager::RIT_Terrain;
  200. const bool isProbeInst = inst->type == RenderPassManager::RIT_Probes;
  201. // Get the material if its a mesh.
  202. BaseMatInstance* matInst = NULL;
  203. if ( isMeshInst || isDecalMeshInst )
  204. matInst = static_cast<MeshRenderInst*>(inst)->matInst;
  205. if (matInst)
  206. {
  207. // If its a custom material and it refracts... skip it.
  208. if (matInst->isCustomMaterial() &&
  209. static_cast<CustomMaterial*>(matInst->getMaterial())->mRefract)
  210. return;
  211. // Make sure we got a deferred material.
  212. matInst = getDeferredMaterial(matInst);
  213. if (!matInst || !matInst->isValid())
  214. return;
  215. }
  216. // We're gonna add it to the bin... get the right element list.
  217. Vector< MainSortElem > *elementList;
  218. if ( isMeshInst || isDecalMeshInst )
  219. elementList = &mElementList;
  220. else if ( isTerrainInst )
  221. elementList = &mTerrainElementList;
  222. else if (isProbeInst)
  223. elementList = &mProbeElementList;
  224. else
  225. elementList = &mObjectElementList;
  226. elementList->increment();
  227. MainSortElem &elem = elementList->last();
  228. elem.inst = inst;
  229. // Store the original key... we might need it.
  230. U32 originalKey = elem.key;
  231. // Sort front-to-back first to get the most fillrate savings.
  232. const F32 invSortDistSq = F32_MAX - inst->sortDistSq;
  233. elem.key = *((U32*)&invSortDistSq);
  234. // Next sort by pre-pass material if its a mesh... use the original sort key.
  235. if (isMeshInst && matInst)
  236. elem.key2 = matInst->getStateHint();
  237. else
  238. elem.key2 = originalKey;
  239. }
  240. void RenderDeferredMgr::sort()
  241. {
  242. PROFILE_SCOPE( RenderDeferredMgr_sort );
  243. Parent::sort();
  244. dQsort( mTerrainElementList.address(), mTerrainElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  245. dQsort( mObjectElementList.address(), mObjectElementList.size(), sizeof(MainSortElem), cmpKeyFunc);
  246. }
  247. void RenderDeferredMgr::clear()
  248. {
  249. Parent::clear();
  250. mProbeElementList.clear();
  251. mTerrainElementList.clear();
  252. mObjectElementList.clear();
  253. }
  254. void RenderDeferredMgr::render( SceneRenderState *state )
  255. {
  256. PROFILE_SCOPE(RenderDeferredMgr_render);
  257. // Take a look at the SceneRenderState and see if we should skip drawing the pre-pass
  258. if ( state->disableAdvancedLightingBins() )
  259. return;
  260. // NOTE: We don't early out here when the element list is
  261. // zero because we need the deferred to be cleared.
  262. // Automagically save & restore our viewport and transforms.
  263. GFXTransformSaver saver;
  264. GFXDEBUGEVENT_SCOPE( RenderDeferredMgr_Render, ColorI::RED );
  265. // Tell the superclass we're about to render
  266. const bool isRenderingToTarget = _onPreRender(state);
  267. // Clear z-buffer and g-buffer.
  268. GFX->clear(GFXClearTarget | GFXClearZBuffer | GFXClearStencil, ColorI::ZERO, 1.0f, 0);
  269. GFX->clearColorAttachment(0, LinearColorF::ONE);
  270. GFX->clearColorAttachment(1, LinearColorF::ZERO);
  271. GFX->clearColorAttachment(2, LinearColorF::ZERO);
  272. GFX->clearColorAttachment(3, LinearColorF::ZERO);
  273. // Restore transforms
  274. MatrixSet &matrixSet = getRenderPass()->getMatrixSet();
  275. matrixSet.restoreSceneViewProjection();
  276. const MatrixF worldViewXfm = GFX->getWorldMatrix();
  277. // Setup the default deferred material for object instances.
  278. if ( !mDeferredMatInstance )
  279. _createDeferredMaterial();
  280. if ( mDeferredMatInstance )
  281. {
  282. matrixSet.setWorld(MatrixF::Identity);
  283. mDeferredMatInstance->setTransforms(matrixSet, state);
  284. }
  285. // Signal start of pre-pass
  286. getRenderSignal().trigger( state, this, true );
  287. // First do a loop and render all the terrain... these are
  288. // usually the big blockers in a scene and will save us fillrate
  289. // on the smaller meshes and objects.
  290. // The terrain doesn't need any scene graph data
  291. // in the the deferred... so just clear it.
  292. SceneData sgData;
  293. sgData.init( state, SceneData::DeferredBin );
  294. Vector< MainSortElem >::const_iterator itr = mTerrainElementList.begin();
  295. for ( ; itr != mTerrainElementList.end(); itr++ )
  296. {
  297. TerrainRenderInst *ri = static_cast<TerrainRenderInst*>( itr->inst );
  298. TerrainCellMaterial *mat = ri->cellMat->getDeferredMat();
  299. GFX->setPrimitiveBuffer( ri->primBuff );
  300. GFX->setVertexBuffer( ri->vertBuff );
  301. mat->setTransformAndEye( *ri->objectToWorldXfm,
  302. worldViewXfm,
  303. GFX->getProjectionMatrix(),
  304. state->getFarPlane() );
  305. while ( mat->setupPass( state, sgData ) )
  306. GFX->drawPrimitive( ri->prim );
  307. }
  308. // init loop data
  309. GFXTextureObject *lastLM = NULL;
  310. GFXCubemap *lastCubemap = NULL;
  311. GFXTextureObject *lastReflectTex = NULL;
  312. GFXTextureObject *lastAccuTex = NULL;
  313. // Next render all the meshes.
  314. itr = mElementList.begin();
  315. for ( ; itr != mElementList.end(); )
  316. {
  317. MeshRenderInst *ri = static_cast<MeshRenderInst*>( itr->inst );
  318. // Get the deferred material.
  319. BaseMatInstance *mat = getDeferredMaterial( ri->matInst );
  320. // Set up SG data proper like and flag it
  321. // as a pre-pass render
  322. setupSGData( ri, sgData );
  323. Vector< MainSortElem >::const_iterator meshItr, endOfBatchItr = itr;
  324. while ( mat->setupPass( state, sgData ) )
  325. {
  326. meshItr = itr;
  327. for ( ; meshItr != mElementList.end(); meshItr++ )
  328. {
  329. MeshRenderInst *passRI = static_cast<MeshRenderInst*>( meshItr->inst );
  330. // Check to see if we need to break this batch.
  331. //
  332. // NOTE: We're comparing the non-deferred materials
  333. // here so we don't incur the cost of looking up the
  334. // deferred hook on each inst.
  335. //
  336. if ( newPassNeeded( ri, passRI ) )
  337. break;
  338. // Set up SG data for this instance.
  339. setupSGData( passRI, sgData );
  340. mat->setSceneInfo(state, sgData);
  341. matrixSet.setWorld(*passRI->objectToWorld);
  342. matrixSet.setView(*passRI->worldToCamera);
  343. matrixSet.setProjection(*passRI->projection);
  344. mat->setTransforms(matrixSet, state);
  345. // Setup HW skinning transforms if applicable
  346. if (mat->usesHardwareSkinning())
  347. {
  348. mat->setNodeTransforms(passRI->mNodeTransforms, passRI->mNodeTransformCount);
  349. }
  350. // If we're instanced then don't render yet.
  351. if ( mat->isInstanced() )
  352. {
  353. // Let the material increment the instance buffer, but
  354. // break the batch if it runs out of room for more.
  355. if ( !mat->stepInstance() )
  356. {
  357. meshItr++;
  358. break;
  359. }
  360. continue;
  361. }
  362. bool dirty = false;
  363. // set the lightmaps if different
  364. if( passRI->lightmap && passRI->lightmap != lastLM )
  365. {
  366. sgData.lightmap = passRI->lightmap;
  367. lastLM = passRI->lightmap;
  368. dirty = true;
  369. }
  370. // set the cubemap if different.
  371. if ( passRI->cubemap != lastCubemap )
  372. {
  373. sgData.cubemap = passRI->cubemap;
  374. lastCubemap = passRI->cubemap;
  375. dirty = true;
  376. }
  377. if ( passRI->reflectTex != lastReflectTex )
  378. {
  379. sgData.reflectTex = passRI->reflectTex;
  380. lastReflectTex = passRI->reflectTex;
  381. dirty = true;
  382. }
  383. // Update accumulation texture if it changed.
  384. // Note: accumulation texture can be NULL, and must be updated.
  385. if (passRI->accuTex != lastAccuTex)
  386. {
  387. sgData.accuTex = passRI->accuTex;
  388. lastAccuTex = passRI->accuTex;
  389. dirty = true;
  390. }
  391. if ( dirty )
  392. mat->setTextureStages( state, sgData );
  393. // Setup the vertex and index buffers.
  394. mat->setBuffers( passRI->vertBuff, passRI->primBuff );
  395. // Render this sucker.
  396. if ( passRI->prim )
  397. GFX->drawPrimitive( *passRI->prim );
  398. else
  399. GFX->drawPrimitive( passRI->primBuffIndex );
  400. }
  401. // Draw the instanced batch.
  402. if ( mat->isInstanced() )
  403. {
  404. // Sets the buffers including the instancing stream.
  405. mat->setBuffers( ri->vertBuff, ri->primBuff );
  406. if ( ri->prim )
  407. GFX->drawPrimitive( *ri->prim );
  408. else
  409. GFX->drawPrimitive( ri->primBuffIndex );
  410. }
  411. endOfBatchItr = meshItr;
  412. } // while( mat->setupPass(state, sgData) )
  413. // Force the increment if none happened, otherwise go to end of batch.
  414. itr = ( itr == endOfBatchItr ) ? itr + 1 : endOfBatchItr;
  415. }
  416. // The final loop is for object render instances.
  417. itr = mObjectElementList.begin();
  418. for ( ; itr != mObjectElementList.end(); itr++ )
  419. {
  420. ObjectRenderInst *ri = static_cast<ObjectRenderInst*>( itr->inst );
  421. if ( ri->renderDelegate )
  422. ri->renderDelegate( ri, state, mDeferredMatInstance );
  423. }
  424. // Signal end of pre-pass
  425. getRenderSignal().trigger( state, this, false );
  426. if(isRenderingToTarget)
  427. _onPostRender();
  428. }
  429. const GFXStateBlockDesc & RenderDeferredMgr::getOpaqueStenciWriteDesc( bool lightmappedGeometry /*= true*/ )
  430. {
  431. static bool sbInit = false;
  432. static GFXStateBlockDesc sOpaqueStaticLitStencilWriteDesc;
  433. static GFXStateBlockDesc sOpaqueDynamicLitStencilWriteDesc;
  434. if(!sbInit)
  435. {
  436. sbInit = true;
  437. // Build the static opaque stencil write/test state block descriptions
  438. sOpaqueStaticLitStencilWriteDesc.stencilDefined = true;
  439. sOpaqueStaticLitStencilWriteDesc.stencilEnable = true;
  440. sOpaqueStaticLitStencilWriteDesc.stencilWriteMask = 0x03;
  441. sOpaqueStaticLitStencilWriteDesc.stencilMask = 0x03;
  442. sOpaqueStaticLitStencilWriteDesc.stencilRef = RenderDeferredMgr::OpaqueStaticLitMask;
  443. sOpaqueStaticLitStencilWriteDesc.stencilPassOp = GFXStencilOpReplace;
  444. sOpaqueStaticLitStencilWriteDesc.stencilFailOp = GFXStencilOpKeep;
  445. sOpaqueStaticLitStencilWriteDesc.stencilZFailOp = GFXStencilOpKeep;
  446. sOpaqueStaticLitStencilWriteDesc.stencilFunc = GFXCmpAlways;
  447. // Same only dynamic
  448. sOpaqueDynamicLitStencilWriteDesc = sOpaqueStaticLitStencilWriteDesc;
  449. sOpaqueDynamicLitStencilWriteDesc.stencilRef = RenderDeferredMgr::OpaqueDynamicLitMask;
  450. }
  451. return (lightmappedGeometry ? sOpaqueStaticLitStencilWriteDesc : sOpaqueDynamicLitStencilWriteDesc);
  452. }
  453. const GFXStateBlockDesc & RenderDeferredMgr::getOpaqueStencilTestDesc()
  454. {
  455. static bool sbInit = false;
  456. static GFXStateBlockDesc sOpaqueStencilTestDesc;
  457. if(!sbInit)
  458. {
  459. // Build opaque test
  460. sbInit = true;
  461. sOpaqueStencilTestDesc.stencilDefined = true;
  462. sOpaqueStencilTestDesc.stencilEnable = true;
  463. sOpaqueStencilTestDesc.stencilWriteMask = 0xFE;
  464. sOpaqueStencilTestDesc.stencilMask = 0x03;
  465. sOpaqueStencilTestDesc.stencilRef = 0;
  466. sOpaqueStencilTestDesc.stencilPassOp = GFXStencilOpKeep;
  467. sOpaqueStencilTestDesc.stencilFailOp = GFXStencilOpKeep;
  468. sOpaqueStencilTestDesc.stencilZFailOp = GFXStencilOpKeep;
  469. sOpaqueStencilTestDesc.stencilFunc = GFXCmpLess;
  470. }
  471. return sOpaqueStencilTestDesc;
  472. }
  473. //------------------------------------------------------------------------------
  474. //------------------------------------------------------------------------------
  475. ProcessedDeferredMaterial::ProcessedDeferredMaterial( Material& mat, const RenderDeferredMgr *deferredMgr )
  476. : Parent(mat), mDeferredMgr(deferredMgr)
  477. {
  478. }
  479. void ProcessedDeferredMaterial::_determineFeatures( U32 stageNum,
  480. MaterialFeatureData &fd,
  481. const FeatureSet &features )
  482. {
  483. Parent::_determineFeatures( stageNum, fd, features );
  484. // Find this for use down below...
  485. bool bEnableMRTLightmap = false;
  486. AdvancedLightBinManager *lightBin;
  487. if ( Sim::findObject( "AL_LightBinMgr", lightBin ) )
  488. bEnableMRTLightmap = lightBin->MRTLightmapsDuringDeferred();
  489. // If this material has a lightmap or tonemap (texture or baked vertex color),
  490. // it must be static. Otherwise it is dynamic.
  491. mIsLightmappedGeometry = ( fd.features.hasFeature( MFT_ToneMap ) ||
  492. fd.features.hasFeature( MFT_LightMap ) ||
  493. fd.features.hasFeature( MFT_VertLit ) ||
  494. ( bEnableMRTLightmap && (fd.features.hasFeature( MFT_IsTranslucent ) ||
  495. fd.features.hasFeature( MFT_ForwardShading ) ||
  496. fd.features.hasFeature( MFT_IsTranslucentZWrite) ) ) );
  497. // Integrate proper opaque stencil write state
  498. mUserDefined.addDesc( mDeferredMgr->getOpaqueStenciWriteDesc( mIsLightmappedGeometry ) );
  499. FeatureSet newFeatures;
  500. // These are always on for deferred.
  501. newFeatures.addFeature( MFT_EyeSpaceDepthOut );
  502. newFeatures.addFeature( MFT_DeferredConditioner );
  503. #ifndef TORQUE_DEDICATED
  504. //tag all materials running through deferred as deferred
  505. newFeatures.addFeature(MFT_isDeferred);
  506. // Deferred Shading : Diffuse
  507. if (mStages[stageNum].getTex( MFT_DiffuseMap ))
  508. {
  509. newFeatures.addFeature(MFT_DiffuseMap);
  510. }
  511. newFeatures.addFeature( MFT_DiffuseColor );
  512. if (mMaterial->mInvertSmoothness[stageNum])
  513. newFeatures.addFeature(MFT_InvertSmoothness);
  514. // Deferred Shading : Specular
  515. if( mStages[stageNum].getTex( MFT_SpecularMap ) )
  516. {
  517. newFeatures.addFeature( MFT_DeferredSpecMap );
  518. }
  519. else
  520. newFeatures.addFeature( MFT_DeferredSpecVars );
  521. // Deferred Shading : Material Info Flags
  522. newFeatures.addFeature( MFT_DeferredMatInfoFlags );
  523. for ( U32 i=0; i < fd.features.getCount(); i++ )
  524. {
  525. const FeatureType &type = fd.features.getAt( i );
  526. // Turn on the diffuse texture only if we
  527. // have alpha test.
  528. if ( type == MFT_AlphaTest )
  529. {
  530. newFeatures.addFeature( MFT_AlphaTest );
  531. newFeatures.addFeature( MFT_DiffuseMap );
  532. }
  533. else if ( type == MFT_IsTranslucentZWrite )
  534. {
  535. newFeatures.addFeature( MFT_IsTranslucentZWrite );
  536. newFeatures.addFeature( MFT_DiffuseMap );
  537. }
  538. // Always allow these.
  539. else if ( type == MFT_IsBC3nm ||
  540. type == MFT_IsBC5nm ||
  541. type == MFT_TexAnim ||
  542. type == MFT_NormalMap ||
  543. type == MFT_DetailNormalMap ||
  544. type == MFT_AlphaTest ||
  545. type == MFT_Parallax ||
  546. type == MFT_InterlacedDeferred ||
  547. type == MFT_Visibility ||
  548. type == MFT_UseInstancing ||
  549. type == MFT_DiffuseVertColor ||
  550. type == MFT_DetailMap ||
  551. type == MFT_DiffuseMapAtlas)
  552. newFeatures.addFeature( type );
  553. // Add any transform features.
  554. else if ( type.getGroup() == MFG_PreTransform ||
  555. type.getGroup() == MFG_Transform ||
  556. type.getGroup() == MFG_PostTransform )
  557. newFeatures.addFeature( type );
  558. }
  559. if (mMaterial->mAccuEnabled[stageNum])
  560. {
  561. newFeatures.addFeature(MFT_AccuMap);
  562. mHasAccumulation = true;
  563. }
  564. // we need both diffuse and normal maps + sm3 to have an accu map
  565. if (newFeatures[MFT_AccuMap] &&
  566. (!newFeatures[MFT_DiffuseMap] ||
  567. !newFeatures[MFT_NormalMap] ||
  568. GFX->getPixelShaderVersion() < 3.0f)) {
  569. AssertWarn(false, "SAHARA: Using an Accu Map requires SM 3.0 and a normal map.");
  570. newFeatures.removeFeature(MFT_AccuMap);
  571. mHasAccumulation = false;
  572. }
  573. // if we still have the AccuMap feature, we add all accu constant features
  574. if (newFeatures[MFT_AccuMap]) {
  575. // add the dependencies of the accu map
  576. newFeatures.addFeature(MFT_AccuScale);
  577. newFeatures.addFeature(MFT_AccuDirection);
  578. newFeatures.addFeature(MFT_AccuStrength);
  579. newFeatures.addFeature(MFT_AccuCoverage);
  580. newFeatures.addFeature(MFT_AccuSpecular);
  581. // now remove some features that are not compatible with this
  582. newFeatures.removeFeature(MFT_UseInstancing);
  583. }
  584. // If there is lightmapped geometry support, add the MRT light buffer features
  585. if(bEnableMRTLightmap)
  586. {
  587. // If this material has a lightmap, pass it through, and flag it to
  588. // send it's output to RenderTarget3
  589. if( fd.features.hasFeature( MFT_ToneMap ) )
  590. {
  591. newFeatures.addFeature( MFT_ToneMap );
  592. newFeatures.addFeature( MFT_LightbufferMRT );
  593. }
  594. else if( fd.features.hasFeature( MFT_LightMap ) )
  595. {
  596. newFeatures.addFeature( MFT_LightMap );
  597. newFeatures.addFeature( MFT_LightbufferMRT );
  598. }
  599. else if( fd.features.hasFeature( MFT_VertLit ) )
  600. {
  601. // Flag un-tone-map if necesasary
  602. if( fd.features.hasFeature( MFT_DiffuseMap ) )
  603. newFeatures.addFeature( MFT_VertLitTone );
  604. newFeatures.addFeature( MFT_VertLit );
  605. newFeatures.addFeature( MFT_LightbufferMRT );
  606. }
  607. else
  608. {
  609. // If this object isn't lightmapped, add a zero-output feature to it
  610. newFeatures.addFeature( MFT_RenderTarget3_Zero );
  611. }
  612. }
  613. // cubemaps only available on stage 0 for now - bramage
  614. if ( stageNum < 1 &&
  615. ( ( mMaterial->mCubemapData && mMaterial->mCubemapData->mCubemap ) ||
  616. mMaterial->mDynamicCubemap ) )
  617. {
  618. if (!mMaterial->mDynamicCubemap)
  619. fd.features.addFeature(MFT_StaticCubemap);
  620. newFeatures.addFeature( MFT_CubeMap );
  621. }
  622. if (mMaterial->mVertLit[stageNum])
  623. newFeatures.addFeature(MFT_VertLit);
  624. if (mMaterial->mMinnaertConstant[stageNum] > 0.0f)
  625. newFeatures.addFeature(MFT_MinnaertShading);
  626. if (mMaterial->mSubSurface[stageNum])
  627. newFeatures.addFeature(MFT_SubSurface);
  628. #endif
  629. // Set the new features.
  630. fd.features = newFeatures;
  631. }
  632. U32 ProcessedDeferredMaterial::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] != LinearColorF::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 ProcessedDeferredMaterial::addStateBlockDesc(const GFXStateBlockDesc& desc)
  676. {
  677. GFXStateBlockDesc deferredStateBlock = desc;
  678. // Adjust color writes if this is a pure z-fill pass
  679. const bool pixelOutEnabled = mDeferredMgr->getTargetChainLength() > 0;
  680. if ( !pixelOutEnabled )
  681. {
  682. deferredStateBlock.colorWriteDefined = true;
  683. deferredStateBlock.colorWriteRed = pixelOutEnabled;
  684. deferredStateBlock.colorWriteGreen = pixelOutEnabled;
  685. deferredStateBlock.colorWriteBlue = pixelOutEnabled;
  686. deferredStateBlock.colorWriteAlpha = pixelOutEnabled;
  687. }
  688. // Never allow the alpha test state when rendering
  689. // the deferred as we use the alpha channel for the
  690. // depth information... MFT_AlphaTest will handle it.
  691. deferredStateBlock.alphaDefined = true;
  692. deferredStateBlock.alphaTestEnable = false;
  693. // If we're translucent then we're doing deferred blending
  694. // which never writes to the depth channels.
  695. const bool isTranslucent = getMaterial()->isTranslucent();
  696. if ( isTranslucent )
  697. {
  698. deferredStateBlock.setBlend( true, GFXBlendSrcAlpha, GFXBlendInvSrcAlpha );
  699. deferredStateBlock.setColorWrites(false, false, false, true);
  700. }
  701. // Enable z reads, but only enable zwrites if we're not translucent.
  702. deferredStateBlock.setZReadWrite( true, isTranslucent ? false : true );
  703. // Pass to parent
  704. Parent::addStateBlockDesc(deferredStateBlock);
  705. }
  706. DeferredMatInstance::DeferredMatInstance(MatInstance* root, const RenderDeferredMgr *deferredMgr)
  707. : Parent(*root->getMaterial()), mDeferredMgr(deferredMgr)
  708. {
  709. mFeatureList = root->getRequestedFeatures();
  710. mVertexFormat = root->getVertexFormat();
  711. mUserObject = root->getUserObject();
  712. }
  713. DeferredMatInstance::~DeferredMatInstance()
  714. {
  715. }
  716. ProcessedMaterial* DeferredMatInstance::getShaderMaterial()
  717. {
  718. return new ProcessedDeferredMaterial(*mMaterial, mDeferredMgr);
  719. }
  720. bool DeferredMatInstance::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. DeferredMatInstanceHook::DeferredMatInstanceHook( MatInstance *baseMatInst,
  739. const RenderDeferredMgr *deferredMgr )
  740. : mHookedDeferredMatInst(NULL), mDeferredManager(deferredMgr)
  741. {
  742. // If the material is a custom material then
  743. // hope that using DefaultDeferredMaterial gives
  744. // them a good deferred.
  745. if ( baseMatInst->isCustomMaterial() )
  746. {
  747. MatInstance* dummyInst = static_cast<MatInstance*>( MATMGR->createMatInstance( "AL_DefaultDeferredMaterial", baseMatInst->getVertexFormat() ) );
  748. mHookedDeferredMatInst = new DeferredMatInstance( dummyInst, deferredMgr );
  749. mHookedDeferredMatInst->init( dummyInst->getRequestedFeatures(), baseMatInst->getVertexFormat());
  750. delete dummyInst;
  751. return;
  752. }
  753. // Create the deferred material instance.
  754. mHookedDeferredMatInst = new DeferredMatInstance(baseMatInst, deferredMgr);
  755. mHookedDeferredMatInst->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. mHookedDeferredMatInst->init(features, baseMatInst->getVertexFormat());
  763. }
  764. DeferredMatInstanceHook::~DeferredMatInstanceHook()
  765. {
  766. SAFE_DELETE(mHookedDeferredMatInst);
  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 *deferredSampler = new Var;
  850. deferredSampler->setName("deferredSamplerVar");
  851. deferredSampler->setType("sampler2D");
  852. DecOp *deferredSamplerDecl = NULL;
  853. Var *deferredTex = NULL;
  854. DecOp *deferredTexDecl = NULL;
  855. if (GFX->getAdapterType() == Direct3D11)
  856. {
  857. deferredSampler->setType("SamplerState");
  858. deferredTex = new Var;
  859. deferredTex->setName("deferredTexVar");
  860. deferredTex->setType("Texture2D");
  861. deferredTexDecl = new DecOp(deferredTex);
  862. }
  863. deferredSamplerDecl = new DecOp(deferredSampler);
  864. Var *screenUV = new Var;
  865. screenUV->setName("screenUVVar");
  866. if (GFX->getAdapterType() == OpenGL)
  867. screenUV->setType("vec2");
  868. else
  869. screenUV->setType("float2");
  870. DecOp *screenUVDecl = new DecOp(screenUV);
  871. Var *bufferSample = new Var;
  872. bufferSample->setName("bufferSample");
  873. if (GFX->getAdapterType() == OpenGL)
  874. bufferSample->setType("vec4");
  875. else
  876. bufferSample->setType("float4");
  877. DecOp *bufferSampleDecl = new DecOp(bufferSample);
  878. if (deferredTex)
  879. meta->addStatement(new GenOp("@(@, @, @)\r\n", methodDecl, deferredSamplerDecl, deferredTexDecl, screenUVDecl));
  880. else
  881. meta->addStatement(new GenOp("@(@, @)\r\n", methodDecl, deferredSamplerDecl, screenUVDecl));
  882. meta->addStatement(new GenOp("{\r\n"));
  883. meta->addStatement(new GenOp(" // Sampler g-buffer\r\n"));
  884. // The linear depth target has no mipmaps, so use tex2dlod when
  885. // possible so that the shader compiler can optimize.
  886. if (GFX->getAdapterType() == OpenGL)
  887. meta->addStatement(new GenOp("@ = texture2DLod(@, @, 0); \r\n", bufferSampleDecl, deferredSampler, screenUV));
  888. else
  889. {
  890. if (deferredTex)
  891. meta->addStatement(new GenOp("@ = @.SampleLevel(@, @, 0);\r\n", bufferSampleDecl, deferredTex, deferredSampler, screenUV));
  892. else
  893. meta->addStatement(new GenOp("@ = tex2Dlod(@, float4(@,0,0));\r\n", bufferSampleDecl, deferredSampler, screenUV));
  894. }
  895. // We don't use this way of passing var's around, so this should cause a crash
  896. // if something uses this improperly
  897. retVal = bufferSample;
  898. }
  899. return retVal;
  900. }