renderDeferredMgr.cpp 38 KB

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