BsRenderCompositor.cpp 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "BsRenderCompositor.h"
  4. #include "BsGpuResourcePool.h"
  5. #include "BsRendererView.h"
  6. #include "Renderer/BsRendererUtility.h"
  7. #include "Mesh/BsMesh.h"
  8. #include "RenderAPI/BsGpuBuffer.h"
  9. #include "BsStandardDeferredLighting.h"
  10. #include "BsRenderBeastOptions.h"
  11. #include "Renderer/BsCamera.h"
  12. #include "BsRendererScene.h"
  13. #include "BsRenderBeast.h"
  14. #include "Utility/BsBitwise.h"
  15. #include "BsRendererTextures.h"
  16. #include "BsObjectRendering.h"
  17. #include "Material/BsGpuParamsSet.h"
  18. #include "Renderer/BsRendererExtension.h"
  19. #include "Renderer/BsSkybox.h"
  20. #include "BsLightProbes.h"
  21. namespace bs { namespace ct
  22. {
  23. UnorderedMap<StringID, RenderCompositor::NodeType*> RenderCompositor::mNodeTypes;
  24. RenderCompositor::~RenderCompositor()
  25. {
  26. clear();
  27. }
  28. void RenderCompositor::build(const RendererView& view, const StringID& finalNode)
  29. {
  30. clear();
  31. bs_frame_mark();
  32. {
  33. FrameUnorderedMap<StringID, UINT32> processedNodes;
  34. mIsValid = true;
  35. std::function<bool(const StringID&)> registerNode = [&](const StringID& nodeId)
  36. {
  37. // Find node type
  38. auto iterFind = mNodeTypes.find(nodeId);
  39. if (iterFind == mNodeTypes.end())
  40. {
  41. LOGERR("Cannot find render compositor node of type \"" + String(nodeId.cstr()) + "\".");
  42. return false;
  43. }
  44. NodeType* nodeType = iterFind->second;
  45. // Register current node
  46. auto iterFind2 = processedNodes.find(nodeId);
  47. // New node
  48. if (iterFind2 == processedNodes.end())
  49. {
  50. // Mark it as invalid for now
  51. processedNodes[nodeId] = -1;
  52. }
  53. // Register node dependencies
  54. SmallVector<StringID, 4> depIds = nodeType->getDependencies(view);
  55. for (auto& dep : depIds)
  56. {
  57. if (!registerNode(dep))
  58. return false;
  59. }
  60. // Register current node
  61. UINT32 curIdx;
  62. // New node, properly populate its index
  63. if (iterFind2 == processedNodes.end())
  64. {
  65. iterFind2 = processedNodes.find(nodeId);
  66. curIdx = (UINT32)mNodeInfos.size();
  67. mNodeInfos.push_back(NodeInfo());
  68. processedNodes[nodeId] = curIdx;
  69. NodeInfo& nodeInfo = mNodeInfos.back();
  70. nodeInfo.node = nodeType->create();
  71. nodeInfo.lastUseIdx = -1;
  72. for (auto& depId : depIds)
  73. {
  74. iterFind2 = processedNodes.find(depId);
  75. NodeInfo& depNodeInfo = mNodeInfos[iterFind2->second];
  76. nodeInfo.inputs.push_back(depNodeInfo.node);
  77. }
  78. }
  79. else // Existing node
  80. {
  81. curIdx = iterFind2->second;
  82. // Check if invalid
  83. if (curIdx == -1)
  84. {
  85. LOGERR("Render compositor nodes recursion detected. Node \"" + String(nodeId.cstr()) + "\" " +
  86. "depends on node \"" + String(iterFind->first.cstr()) + "\" which is not available at " +
  87. "this stage.");
  88. return false;
  89. }
  90. }
  91. // Update dependency last use counters
  92. for (auto& dep : depIds)
  93. {
  94. iterFind2 = processedNodes.find(dep);
  95. NodeInfo& depNodeInfo = mNodeInfos[iterFind2->second];
  96. if (depNodeInfo.lastUseIdx == -1)
  97. depNodeInfo.lastUseIdx = curIdx;
  98. else
  99. depNodeInfo.lastUseIdx = std::max(depNodeInfo.lastUseIdx, curIdx);
  100. }
  101. return true;
  102. };
  103. mIsValid = registerNode(finalNode);
  104. if (!mIsValid)
  105. clear();
  106. }
  107. bs_frame_clear();
  108. }
  109. void RenderCompositor::execute(RenderCompositorNodeInputs& inputs) const
  110. {
  111. if (!mIsValid)
  112. return;
  113. bs_frame_mark();
  114. {
  115. FrameVector<const NodeInfo*> activeNodes;
  116. UINT32 idx = 0;
  117. for (auto& entry : mNodeInfos)
  118. {
  119. inputs.inputNodes = entry.inputs;
  120. entry.node->render(inputs);
  121. activeNodes.push_back(&entry);
  122. for (UINT32 i = 0; i < (UINT32)activeNodes.size(); ++i)
  123. {
  124. if (activeNodes[i] == nullptr)
  125. continue;
  126. if (activeNodes[i]->lastUseIdx <= idx)
  127. {
  128. activeNodes[i]->node->clear();
  129. activeNodes[i] = nullptr;
  130. }
  131. }
  132. idx++;
  133. }
  134. }
  135. bs_frame_clear();
  136. if (!mNodeInfos.empty())
  137. mNodeInfos.back().node->clear();
  138. }
  139. void RenderCompositor::clear()
  140. {
  141. for (auto& entry : mNodeInfos)
  142. bs_delete(entry.node);
  143. mNodeInfos.clear();
  144. mIsValid = false;
  145. }
  146. void RCNodeSceneDepth::render(const RenderCompositorNodeInputs& inputs)
  147. {
  148. GpuResourcePool& resPool = GpuResourcePool::instance();
  149. const RendererViewProperties& viewProps = inputs.view.getProperties();
  150. UINT32 width = viewProps.viewRect.width;
  151. UINT32 height = viewProps.viewRect.height;
  152. UINT32 numSamples = viewProps.numSamples;
  153. depthTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_D32_S8X24, width, height, TU_DEPTHSTENCIL,
  154. numSamples, false));
  155. }
  156. void RCNodeSceneDepth::clear()
  157. {
  158. GpuResourcePool& resPool = GpuResourcePool::instance();
  159. resPool.release(depthTex);
  160. }
  161. SmallVector<StringID, 4> RCNodeSceneDepth::getDependencies(const RendererView& view)
  162. {
  163. return {};
  164. }
  165. void RCNodeGBuffer::render(const RenderCompositorNodeInputs& inputs)
  166. {
  167. // Allocate necessary textures & targets
  168. GpuResourcePool& resPool = GpuResourcePool::instance();
  169. const RendererViewProperties& viewProps = inputs.view.getProperties();
  170. UINT32 width = viewProps.viewRect.width;
  171. UINT32 height = viewProps.viewRect.height;
  172. UINT32 numSamples = viewProps.numSamples;
  173. // Note: Consider customizable formats. e.g. for testing if quality can be improved with higher precision normals.
  174. albedoTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA8, width, height, TU_RENDERTARGET,
  175. numSamples, true));
  176. normalTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGB10A2, width, height, TU_RENDERTARGET,
  177. numSamples, false));
  178. roughMetalTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RG16F, width, height, TU_RENDERTARGET,
  179. numSamples, false)); // Note: Metal doesn't need 16-bit float
  180. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[0]);
  181. SPtr<PooledRenderTexture> sceneDepthTex = sceneDepthNode->depthTex;
  182. bool rebuildRT = false;
  183. if (renderTarget != nullptr)
  184. {
  185. rebuildRT |= renderTarget->getColorTexture(0) != albedoTex->texture;
  186. rebuildRT |= renderTarget->getColorTexture(1) != normalTex->texture;
  187. rebuildRT |= renderTarget->getColorTexture(2) != roughMetalTex->texture;
  188. rebuildRT |= renderTarget->getDepthStencilTexture() != sceneDepthTex->texture;
  189. }
  190. else
  191. rebuildRT = true;
  192. if (renderTarget == nullptr || rebuildRT)
  193. {
  194. RENDER_TEXTURE_DESC gbufferDesc;
  195. gbufferDesc.colorSurfaces[0].texture = albedoTex->texture;
  196. gbufferDesc.colorSurfaces[0].face = 0;
  197. gbufferDesc.colorSurfaces[0].numFaces = 1;
  198. gbufferDesc.colorSurfaces[0].mipLevel = 0;
  199. gbufferDesc.colorSurfaces[1].texture = normalTex->texture;
  200. gbufferDesc.colorSurfaces[1].face = 0;
  201. gbufferDesc.colorSurfaces[1].numFaces = 1;
  202. gbufferDesc.colorSurfaces[1].mipLevel = 0;
  203. gbufferDesc.colorSurfaces[2].texture = roughMetalTex->texture;
  204. gbufferDesc.colorSurfaces[2].face = 0;
  205. gbufferDesc.colorSurfaces[2].numFaces = 1;
  206. gbufferDesc.colorSurfaces[2].mipLevel = 0;
  207. gbufferDesc.depthStencilSurface.texture = sceneDepthTex->texture;
  208. gbufferDesc.depthStencilSurface.face = 0;
  209. gbufferDesc.depthStencilSurface.mipLevel = 0;
  210. renderTarget = RenderTexture::create(gbufferDesc);
  211. }
  212. // Prepare all visible objects. Note that this also prepares non-opaque objects.
  213. const VisibilityInfo& visibility = inputs.view.getVisibilityMasks();
  214. UINT32 numRenderables = (UINT32)inputs.scene.renderables.size();
  215. for (UINT32 i = 0; i < numRenderables; i++)
  216. {
  217. if (!visibility.renderables[i])
  218. continue;
  219. RendererObject* rendererObject = inputs.scene.renderables[i];
  220. rendererObject->updatePerCallBuffer(viewProps.viewProjTransform);
  221. for (auto& element : inputs.scene.renderables[i]->elements)
  222. {
  223. if (element.perCameraBindingIdx != -1)
  224. element.params->setParamBlockBuffer(element.perCameraBindingIdx, inputs.view.getPerViewBuffer(), true);
  225. }
  226. }
  227. Camera* sceneCamera = inputs.view.getSceneCamera();
  228. // Trigger pre-base-pass callbacks
  229. if (sceneCamera != nullptr)
  230. {
  231. for(auto& extension : inputs.extPreBasePass)
  232. {
  233. if (extension->check(*sceneCamera))
  234. extension->render(*sceneCamera);
  235. }
  236. }
  237. // Render base pass
  238. RenderAPI& rapi = RenderAPI::instance();
  239. rapi.setRenderTarget(renderTarget);
  240. Rect2 area(0.0f, 0.0f, 1.0f, 1.0f);
  241. rapi.setViewport(area);
  242. // Clear all targets
  243. rapi.clearViewport(FBT_COLOR | FBT_DEPTH | FBT_STENCIL, Color::ZERO, 1.0f, 0);
  244. // Render all visible opaque elements
  245. const Vector<RenderQueueElement>& opaqueElements = inputs.view.getOpaqueQueue()->getSortedElements();
  246. for (auto iter = opaqueElements.begin(); iter != opaqueElements.end(); ++iter)
  247. {
  248. BeastRenderableElement* renderElem = static_cast<BeastRenderableElement*>(iter->renderElem);
  249. SPtr<Material> material = renderElem->material;
  250. if (iter->applyPass)
  251. gRendererUtility().setPass(material, iter->passIdx, renderElem->techniqueIdx);
  252. gRendererUtility().setPassParams(renderElem->params, iter->passIdx);
  253. if(renderElem->morphVertexDeclaration == nullptr)
  254. gRendererUtility().draw(renderElem->mesh, renderElem->subMesh);
  255. else
  256. gRendererUtility().drawMorph(renderElem->mesh, renderElem->subMesh, renderElem->morphShapeBuffer,
  257. renderElem->morphVertexDeclaration);
  258. }
  259. // Trigger post-base-pass callbacks
  260. if (sceneCamera != nullptr)
  261. {
  262. for(auto& extension : inputs.extPostBasePass)
  263. {
  264. if (extension->check(*sceneCamera))
  265. extension->render(*sceneCamera);
  266. }
  267. }
  268. }
  269. void RCNodeGBuffer::clear()
  270. {
  271. GpuResourcePool& resPool = GpuResourcePool::instance();
  272. resPool.release(albedoTex);
  273. resPool.release(normalTex);
  274. resPool.release(roughMetalTex);
  275. }
  276. SmallVector<StringID, 4> RCNodeGBuffer::getDependencies(const RendererView& view)
  277. {
  278. return { RCNodeSceneDepth::getNodeId() };
  279. }
  280. void RCNodeSceneColor::render(const RenderCompositorNodeInputs& inputs)
  281. {
  282. GpuResourcePool& resPool = GpuResourcePool::instance();
  283. const RendererViewProperties& viewProps = inputs.view.getProperties();
  284. UINT32 width = viewProps.viewRect.width;
  285. UINT32 height = viewProps.viewRect.height;
  286. UINT32 numSamples = viewProps.numSamples;
  287. // Note: Consider customizable HDR format via options? e.g. smaller PF_FLOAT_R11G11B10 or larger 32-bit format
  288. sceneColorTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width, height, TU_RENDERTARGET |
  289. TU_LOADSTORE, numSamples, false));
  290. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[0]);
  291. SPtr<PooledRenderTexture> sceneDepthTex = sceneDepthNode->depthTex;
  292. if (viewProps.numSamples > 1)
  293. {
  294. UINT32 bufferNumElements = width * height * viewProps.numSamples;
  295. flattenedSceneColorBuffer = resPool.get(POOLED_STORAGE_BUFFER_DESC::createStandard(BF_16X4F, bufferNumElements));
  296. }
  297. else
  298. flattenedSceneColorBuffer = nullptr;
  299. bool rebuildRT = false;
  300. if (renderTarget != nullptr)
  301. {
  302. rebuildRT |= renderTarget->getColorTexture(0) != sceneColorTex->texture;
  303. rebuildRT |= renderTarget->getDepthStencilTexture() != sceneDepthTex->texture;
  304. }
  305. else
  306. rebuildRT = true;
  307. if (rebuildRT)
  308. {
  309. RENDER_TEXTURE_DESC sceneColorDesc;
  310. sceneColorDesc.colorSurfaces[0].texture = sceneColorTex->texture;
  311. sceneColorDesc.colorSurfaces[0].face = 0;
  312. sceneColorDesc.colorSurfaces[0].numFaces = 1;
  313. sceneColorDesc.colorSurfaces[0].mipLevel = 0;
  314. sceneColorDesc.depthStencilSurface.texture = sceneDepthTex->texture;
  315. sceneColorDesc.depthStencilSurface.face = 0;
  316. sceneColorDesc.depthStencilSurface.numFaces = 1;
  317. sceneColorDesc.depthStencilSurface.mipLevel = 0;
  318. renderTarget = RenderTexture::create(sceneColorDesc);
  319. }
  320. }
  321. void RCNodeSceneColor::clear()
  322. {
  323. GpuResourcePool& resPool = GpuResourcePool::instance();
  324. resPool.release(sceneColorTex);
  325. if (flattenedSceneColorBuffer != nullptr)
  326. resPool.release(flattenedSceneColorBuffer);
  327. }
  328. SmallVector<StringID, 4> RCNodeSceneColor::getDependencies(const RendererView& view)
  329. {
  330. return { RCNodeSceneDepth::getNodeId() };
  331. }
  332. void RCNodeMSAACoverage::render(const RenderCompositorNodeInputs& inputs)
  333. {
  334. GpuResourcePool& resPool = GpuResourcePool::instance();
  335. const RendererViewProperties& viewProps = inputs.view.getProperties();
  336. UINT32 width = viewProps.viewRect.width;
  337. UINT32 height = viewProps.viewRect.height;
  338. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, width, height, TU_RENDERTARGET));
  339. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[0]);
  340. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[1]);
  341. GBufferTextures gbuffer;
  342. gbuffer.albedo = gbufferNode->albedoTex->texture;
  343. gbuffer.normals = gbufferNode->normalTex->texture;
  344. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  345. gbuffer.depth = sceneDepthNode->depthTex->texture;
  346. MSAACoverageMat* mat = MSAACoverageMat::getVariation(viewProps.numSamples);
  347. RenderAPI::instance().setRenderTarget(output->renderTexture);
  348. mat->execute(inputs.view, gbuffer);
  349. }
  350. void RCNodeMSAACoverage::clear()
  351. {
  352. GpuResourcePool& resPool = GpuResourcePool::instance();
  353. resPool.release(output);
  354. }
  355. SmallVector<StringID, 4> RCNodeMSAACoverage::getDependencies(const RendererView& view)
  356. {
  357. return { RCNodeGBuffer::getNodeId(), RCNodeSceneDepth::getNodeId() };
  358. }
  359. void RCNodeLightAccumulation::render(const RenderCompositorNodeInputs& inputs)
  360. {
  361. GpuResourcePool& resPool = GpuResourcePool::instance();
  362. const RendererViewProperties& viewProps = inputs.view.getProperties();
  363. UINT32 width = viewProps.viewRect.width;
  364. UINT32 height = viewProps.viewRect.height;
  365. UINT32 numSamples = viewProps.numSamples;
  366. if (numSamples > 1)
  367. {
  368. UINT32 bufferNumElements = width * height * numSamples;
  369. flattenedLightAccumBuffer =
  370. resPool.get(POOLED_STORAGE_BUFFER_DESC::createStandard(BF_16X4F, bufferNumElements));
  371. SPtr<GpuBuffer> buffer = flattenedLightAccumBuffer->buffer;
  372. auto& bufferProps = buffer->getProperties();
  373. UINT32 bufferSize = bufferProps.getElementSize() * bufferProps.getElementCount();
  374. UINT16* data = (UINT16*)buffer->lock(0, bufferSize, GBL_WRITE_ONLY_DISCARD);
  375. {
  376. memset(data, 0, bufferSize);
  377. }
  378. buffer->unlock();
  379. }
  380. else
  381. flattenedLightAccumBuffer = nullptr;
  382. lightAccumulationTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width,
  383. height, TU_LOADSTORE | TU_RENDERTARGET, numSamples, false));
  384. bool rebuildRT;
  385. if (renderTarget != nullptr)
  386. rebuildRT = renderTarget->getColorTexture(0) != lightAccumulationTex->texture;
  387. else
  388. rebuildRT = true;
  389. if (rebuildRT)
  390. {
  391. RENDER_TEXTURE_DESC lightAccumulationRTDesc;
  392. lightAccumulationRTDesc.colorSurfaces[0].texture = lightAccumulationTex->texture;
  393. lightAccumulationRTDesc.colorSurfaces[0].face = 0;
  394. lightAccumulationRTDesc.colorSurfaces[0].numFaces = 1;
  395. lightAccumulationRTDesc.colorSurfaces[0].mipLevel = 0;
  396. renderTarget = RenderTexture::create(lightAccumulationRTDesc);
  397. }
  398. }
  399. void RCNodeLightAccumulation::clear()
  400. {
  401. GpuResourcePool& resPool = GpuResourcePool::instance();
  402. resPool.release(lightAccumulationTex);
  403. if (flattenedLightAccumBuffer)
  404. resPool.release(flattenedLightAccumBuffer);
  405. }
  406. SmallVector<StringID, 4> RCNodeLightAccumulation::getDependencies(const RendererView& view)
  407. {
  408. return {};
  409. }
  410. void RCNodeTiledDeferredLighting::render(const RenderCompositorNodeInputs& inputs)
  411. {
  412. output = static_cast<RCNodeLightAccumulation*>(inputs.inputNodes[0]);
  413. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[1]);
  414. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[2]);
  415. const RendererViewProperties& viewProps = inputs.view.getProperties();
  416. TiledDeferredLightingMat* tiledDeferredMat = TiledDeferredLightingMat::getVariation(viewProps.numSamples);
  417. GBufferTextures gbuffer;
  418. gbuffer.albedo = gbufferNode->albedoTex->texture;
  419. gbuffer.normals = gbufferNode->normalTex->texture;
  420. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  421. gbuffer.depth = sceneDepthNode->depthTex->texture;
  422. RenderAPI& rapi = RenderAPI::instance();
  423. rapi.setRenderTarget(output->renderTarget, FBT_DEPTH | FBT_STENCIL, RT_COLOR0 | RT_DEPTH_STENCIL);
  424. const VisibleLightData& lightData = inputs.viewGroup.getVisibleLightData();
  425. SPtr<GpuBuffer> flattenedLightAccumBuffer;
  426. if (output->flattenedLightAccumBuffer)
  427. flattenedLightAccumBuffer = output->flattenedLightAccumBuffer->buffer;
  428. tiledDeferredMat->execute(inputs.view, lightData, gbuffer, output->lightAccumulationTex->texture,
  429. flattenedLightAccumBuffer);
  430. }
  431. void RCNodeTiledDeferredLighting::clear()
  432. {
  433. output = nullptr;
  434. }
  435. SmallVector<StringID, 4> RCNodeTiledDeferredLighting::getDependencies(const RendererView& view)
  436. {
  437. return { RCNodeLightAccumulation::getNodeId(), RCNodeGBuffer::getNodeId(), RCNodeSceneDepth::getNodeId() };
  438. }
  439. void RCNodeStandardDeferredLighting::render(const RenderCompositorNodeInputs& inputs)
  440. {
  441. RCNodeTiledDeferredLighting* tileDeferredNode = static_cast<RCNodeTiledDeferredLighting*>(inputs.inputNodes[0]);
  442. output = tileDeferredNode->output;
  443. // If shadows are disabled we handle all lights through tiled deferred
  444. if (!inputs.view.getRenderSettings().enableShadows)
  445. return;
  446. GpuResourcePool& resPool = GpuResourcePool::instance();
  447. const RendererViewProperties& viewProps = inputs.view.getProperties();
  448. UINT32 width = viewProps.viewRect.width;
  449. UINT32 height = viewProps.viewRect.height;
  450. UINT32 numSamples = viewProps.numSamples;
  451. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[1]);
  452. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[2]);
  453. // Allocate light occlusion
  454. SPtr<PooledRenderTexture> lightOcclusionTex = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, width,
  455. height, TU_RENDERTARGET, numSamples, false));
  456. bool rebuildRT = false;
  457. if (mRenderTarget != nullptr)
  458. {
  459. rebuildRT |= mRenderTarget->getColorTexture(0) != lightOcclusionTex->texture;
  460. rebuildRT |= mRenderTarget->getDepthStencilTexture() != sceneDepthNode->depthTex->texture;
  461. }
  462. else
  463. rebuildRT = true;
  464. if (rebuildRT)
  465. {
  466. RENDER_TEXTURE_DESC lightOcclusionRTDesc;
  467. lightOcclusionRTDesc.colorSurfaces[0].texture = lightOcclusionTex->texture;
  468. lightOcclusionRTDesc.colorSurfaces[0].face = 0;
  469. lightOcclusionRTDesc.colorSurfaces[0].numFaces = 1;
  470. lightOcclusionRTDesc.colorSurfaces[0].mipLevel = 0;
  471. lightOcclusionRTDesc.depthStencilSurface.texture = sceneDepthNode->depthTex->texture;
  472. lightOcclusionRTDesc.depthStencilSurface.face = 0;
  473. lightOcclusionRTDesc.depthStencilSurface.numFaces = 1;
  474. lightOcclusionRTDesc.depthStencilSurface.mipLevel = 0;
  475. mRenderTarget = RenderTexture::create(lightOcclusionRTDesc);
  476. }
  477. GBufferTextures gbuffer;
  478. gbuffer.albedo = gbufferNode->albedoTex->texture;
  479. gbuffer.normals = gbufferNode->normalTex->texture;
  480. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  481. gbuffer.depth = sceneDepthNode->depthTex->texture;
  482. const VisibleLightData& lightData = inputs.viewGroup.getVisibleLightData();
  483. const ShadowRendering& shadowRenderer = inputs.viewGroup.getShadowRenderer();
  484. RenderAPI& rapi = RenderAPI::instance();
  485. for (UINT32 i = 0; i < (UINT32)LightType::Count; i++)
  486. {
  487. LightType lightType = (LightType)i;
  488. auto& lights = lightData.getLights(lightType);
  489. UINT32 count = lightData.getNumShadowedLights(lightType);
  490. UINT32 offset = lightData.getNumUnshadowedLights(lightType);
  491. for (UINT32 j = 0; j < count; j++)
  492. {
  493. rapi.setRenderTarget(mRenderTarget, FBT_DEPTH, RT_DEPTH_STENCIL);
  494. Rect2 area(0.0f, 0.0f, 1.0f, 1.0f);
  495. rapi.setViewport(area);
  496. rapi.clearViewport(FBT_COLOR, Color::ZERO);
  497. UINT32 lightIdx = offset + j;
  498. const RendererLight& light = *lights[lightIdx];
  499. shadowRenderer.renderShadowOcclusion(inputs.view, inputs.options.shadowFilteringQuality, light, gbuffer);
  500. rapi.setRenderTarget(output->renderTarget, FBT_DEPTH | FBT_STENCIL, RT_COLOR0 | RT_DEPTH_STENCIL);
  501. StandardDeferred::instance().renderLight(lightType, light, inputs.view, gbuffer,
  502. lightOcclusionTex->texture);
  503. }
  504. }
  505. // Makes sure light accumulation can be read by following passes
  506. rapi.setRenderTarget(nullptr);
  507. resPool.release(lightOcclusionTex);
  508. }
  509. void RCNodeStandardDeferredLighting::clear()
  510. {
  511. output = nullptr;
  512. }
  513. SmallVector<StringID, 4> RCNodeStandardDeferredLighting::getDependencies(const RendererView& view)
  514. {
  515. SmallVector<StringID, 4> deps;
  516. deps.push_back(RCNodeTiledDeferredLighting::getNodeId());
  517. deps.push_back(RCNodeGBuffer::getNodeId());
  518. deps.push_back(RCNodeSceneDepth::getNodeId());
  519. if (view.getProperties().numSamples > 1)
  520. deps.push_back(RCNodeUnflattenLightAccum::getNodeId());
  521. return deps;
  522. }
  523. void RCNodeUnflattenLightAccum::render(const RenderCompositorNodeInputs& inputs)
  524. {
  525. RCNodeLightAccumulation* lightAccumNode = static_cast<RCNodeLightAccumulation*>(inputs.inputNodes[0]);
  526. FlatFramebufferToTextureMat* material = FlatFramebufferToTextureMat::get();
  527. RenderAPI& rapi = RenderAPI::instance();
  528. rapi.setRenderTarget(lightAccumNode->renderTarget, FBT_DEPTH | FBT_STENCIL, RT_COLOR0 | RT_DEPTH_STENCIL);
  529. material->execute(lightAccumNode->flattenedLightAccumBuffer->buffer, lightAccumNode->lightAccumulationTex->texture);
  530. }
  531. void RCNodeUnflattenLightAccum::clear()
  532. {
  533. output = nullptr;
  534. }
  535. SmallVector<StringID, 4> RCNodeUnflattenLightAccum::getDependencies(const RendererView& view)
  536. {
  537. return { RCNodeLightAccumulation::getNodeId() };
  538. }
  539. void RCNodeIndirectLighting::render(const RenderCompositorNodeInputs& inputs)
  540. {
  541. if (!inputs.view.getRenderSettings().enableIndirectLighting)
  542. return;
  543. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[0]);
  544. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[1]);
  545. RCNodeLightAccumulation* lightAccumNode = static_cast <RCNodeLightAccumulation*>(inputs.inputNodes[2]);
  546. SPtr<Texture> ssao;
  547. if (inputs.view.getRenderSettings().ambientOcclusion.enabled)
  548. {
  549. RCNodeSSAO* ssaoNode = static_cast<RCNodeSSAO*>(inputs.inputNodes[4]);
  550. ssao = ssaoNode->output->texture;
  551. }
  552. else
  553. ssao = Texture::WHITE;
  554. GpuResourcePool& resPool = GpuResourcePool::instance();
  555. const RendererViewProperties& viewProps = inputs.view.getProperties();
  556. const LightProbes& lightProbes = inputs.scene.lightProbes;
  557. LightProbesInfo lpInfo = lightProbes.getInfo();
  558. IrradianceEvaluateMat* evaluateMat;
  559. SPtr<PooledRenderTexture> volumeIndices;
  560. if(lightProbes.hasAnyProbes())
  561. {
  562. POOLED_RENDER_TEXTURE_DESC volumeIndicesDesc;
  563. POOLED_RENDER_TEXTURE_DESC depthDesc;
  564. TetrahedraRenderMat::getOutputDesc(inputs.view, volumeIndicesDesc, depthDesc);
  565. volumeIndices = resPool.get(volumeIndicesDesc);
  566. SPtr<PooledRenderTexture> depthTex = resPool.get(depthDesc);
  567. RENDER_TEXTURE_DESC rtDesc;
  568. rtDesc.colorSurfaces[0].texture = volumeIndices->texture;
  569. rtDesc.depthStencilSurface.texture = depthTex->texture;
  570. SPtr<RenderTexture> rt = RenderTexture::create(rtDesc);
  571. RenderAPI& rapi = RenderAPI::instance();
  572. rapi.setRenderTarget(rt);
  573. rapi.clearRenderTarget(FBT_DEPTH);
  574. gRendererUtility().clear(-1);
  575. TetrahedraRenderMat* renderTetrahedra = TetrahedraRenderMat::getVariation(viewProps.numSamples > 1);
  576. renderTetrahedra->execute(inputs.view, sceneDepthNode->depthTex->texture, lpInfo.tetrahedraVolume, rt);
  577. rt = nullptr;
  578. resPool.release(depthTex);
  579. evaluateMat = IrradianceEvaluateMat::getVariation(viewProps.numSamples, false);
  580. }
  581. else // Sky only
  582. {
  583. evaluateMat = IrradianceEvaluateMat::getVariation(viewProps.numSamples, true);
  584. }
  585. GBufferTextures gbuffer;
  586. gbuffer.albedo = gbufferNode->albedoTex->texture;
  587. gbuffer.normals = gbufferNode->normalTex->texture;
  588. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  589. gbuffer.depth = sceneDepthNode->depthTex->texture;
  590. SPtr<Texture> volumeIndicesTex;
  591. if (volumeIndices)
  592. volumeIndicesTex = volumeIndices->texture;
  593. evaluateMat->execute(inputs.view, gbuffer, volumeIndicesTex, lpInfo, inputs.scene.skybox, ssao,
  594. lightAccumNode->renderTarget);
  595. if(volumeIndices)
  596. resPool.release(volumeIndices);
  597. }
  598. void RCNodeIndirectLighting::clear()
  599. {
  600. // Do nothing
  601. }
  602. SmallVector<StringID, 4> RCNodeIndirectLighting::getDependencies(const RendererView& view)
  603. {
  604. SmallVector<StringID, 4> deps;
  605. deps.push_back(RCNodeGBuffer::getNodeId());
  606. deps.push_back(RCNodeSceneDepth::getNodeId());
  607. deps.push_back(RCNodeLightAccumulation::getNodeId());
  608. deps.push_back(RCNodeStandardDeferredLighting::getNodeId());
  609. if(view.getRenderSettings().ambientOcclusion.enabled)
  610. deps.push_back(RCNodeSSAO::getNodeId());
  611. if (view.getProperties().numSamples > 1)
  612. deps.push_back(RCNodeUnflattenLightAccum::getNodeId());
  613. return deps;
  614. }
  615. void RCNodeTiledDeferredIBL::render(const RenderCompositorNodeInputs& inputs)
  616. {
  617. const RenderSettings& rs = inputs.view.getRenderSettings();
  618. RCNodeSceneColor* sceneColorNode = static_cast<RCNodeSceneColor*>(inputs.inputNodes[0]);
  619. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[1]);
  620. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[2]);
  621. RCNodeLightAccumulation* lightAccumNode = static_cast <RCNodeLightAccumulation*>(inputs.inputNodes[3]);
  622. SPtr<Texture> ssr;
  623. if (rs.screenSpaceReflections.enabled)
  624. {
  625. RCNodeSSR* ssrNode = static_cast<RCNodeSSR*>(inputs.inputNodes[5]);
  626. ssr = ssrNode->output->texture;
  627. }
  628. else
  629. ssr = Texture::BLACK;
  630. SPtr<Texture> ssao;
  631. if (rs.ambientOcclusion.enabled)
  632. {
  633. RCNodeSSAO* ssaoNode = static_cast<RCNodeSSAO*>(inputs.inputNodes[6]);
  634. ssao = ssaoNode->output->texture;
  635. }
  636. else
  637. ssao = Texture::WHITE;
  638. const RendererViewProperties& viewProps = inputs.view.getProperties();
  639. TiledDeferredImageBasedLightingMat* material = TiledDeferredImageBasedLightingMat::getVariation(viewProps.numSamples);
  640. TiledDeferredImageBasedLightingMat::Inputs iblInputs;
  641. iblInputs.gbuffer.albedo = gbufferNode->albedoTex->texture;
  642. iblInputs.gbuffer.normals = gbufferNode->normalTex->texture;
  643. iblInputs.gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  644. iblInputs.gbuffer.depth = sceneDepthNode->depthTex->texture;
  645. iblInputs.sceneColorTex = sceneColorNode->sceneColorTex->texture;
  646. iblInputs.lightAccumulation = lightAccumNode->lightAccumulationTex->texture;
  647. iblInputs.preIntegratedGF = RendererTextures::preintegratedEnvGF;
  648. iblInputs.ambientOcclusion = ssao;
  649. iblInputs.ssr = ssr;
  650. if(sceneColorNode->flattenedSceneColorBuffer)
  651. iblInputs.sceneColorBuffer = sceneColorNode->flattenedSceneColorBuffer->buffer;
  652. material->execute(inputs.view, inputs.scene, inputs.viewGroup.getVisibleReflProbeData(), iblInputs);
  653. }
  654. void RCNodeTiledDeferredIBL::clear()
  655. {
  656. output = nullptr;
  657. }
  658. SmallVector<StringID, 4> RCNodeTiledDeferredIBL::getDependencies(const RendererView& view)
  659. {
  660. SmallVector<StringID, 4> deps;
  661. deps.push_back(RCNodeSceneColor::getNodeId());
  662. deps.push_back(RCNodeGBuffer::getNodeId());
  663. deps.push_back(RCNodeSceneDepth::getNodeId());
  664. deps.push_back(RCNodeLightAccumulation::getNodeId());
  665. deps.push_back(RCNodeIndirectLighting::getNodeId());
  666. deps.push_back(RCNodeSSR::getNodeId());
  667. if(view.getRenderSettings().ambientOcclusion.enabled)
  668. deps.push_back(RCNodeSSAO::getNodeId());
  669. return deps;
  670. }
  671. void RCNodeUnflattenSceneColor::render(const RenderCompositorNodeInputs& inputs)
  672. {
  673. RCNodeSceneColor* sceneColorNode = static_cast<RCNodeSceneColor*>(inputs.inputNodes[0]);
  674. FlatFramebufferToTextureMat* material = FlatFramebufferToTextureMat::get();
  675. int readOnlyFlags = FBT_DEPTH | FBT_STENCIL;
  676. RenderAPI& rapi = RenderAPI::instance();
  677. rapi.setRenderTarget(sceneColorNode->renderTarget, readOnlyFlags, RT_COLOR0 | RT_DEPTH_STENCIL);
  678. Rect2 area(0.0f, 0.0f, 1.0f, 1.0f);
  679. rapi.setViewport(area);
  680. material->execute(sceneColorNode->flattenedSceneColorBuffer->buffer, sceneColorNode->sceneColorTex->texture);
  681. }
  682. void RCNodeUnflattenSceneColor::clear()
  683. {
  684. output = nullptr;
  685. }
  686. SmallVector<StringID, 4> RCNodeUnflattenSceneColor::getDependencies(const RendererView& view)
  687. {
  688. return { RCNodeSceneColor::getNodeId() };
  689. }
  690. void RCNodeClusteredForward::render(const RenderCompositorNodeInputs& inputs)
  691. {
  692. const SceneInfo& sceneInfo = inputs.scene;
  693. const RendererViewProperties& viewProps = inputs.view.getProperties();
  694. const VisibleLightData& visibleLightData = inputs.viewGroup.getVisibleLightData();
  695. const VisibleReflProbeData& visibleReflProbeData = inputs.viewGroup.getVisibleReflProbeData();
  696. const LightGrid& lightGrid = inputs.view.getLightGrid();
  697. SPtr<GpuParamBlockBuffer> gridParams;
  698. SPtr<GpuBuffer> gridLightOffsetsAndSize, gridLightIndices;
  699. SPtr<GpuBuffer> gridProbeOffsetsAndSize, gridProbeIndices;
  700. lightGrid.getOutputs(gridLightOffsetsAndSize, gridLightIndices, gridProbeOffsetsAndSize, gridProbeIndices,
  701. gridParams);
  702. // Prepare refl. probe param buffer
  703. ReflProbeParamBuffer reflProbeParamBuffer;
  704. reflProbeParamBuffer.populate(sceneInfo.skybox, visibleReflProbeData, sceneInfo.reflProbeCubemapsTex,
  705. viewProps.renderingReflections);
  706. SPtr<Texture> skyFilteredRadiance;
  707. if(sceneInfo.skybox)
  708. skyFilteredRadiance = sceneInfo.skybox->getFilteredRadiance();
  709. // Prepare objects for rendering
  710. const VisibilityInfo& visibility = inputs.view.getVisibilityMasks();
  711. UINT32 numRenderables = (UINT32)sceneInfo.renderables.size();
  712. for (UINT32 i = 0; i < numRenderables; i++)
  713. {
  714. if (!visibility.renderables[i])
  715. continue;
  716. for (auto& element : sceneInfo.renderables[i]->elements)
  717. {
  718. bool isTransparent = (element.material->getShader()->getFlags() & (UINT32)ShaderFlags::Transparent) != 0;
  719. if (!isTransparent)
  720. continue;
  721. // Note: It would be nice to be able to set this once and keep it, only updating if the buffers actually
  722. // change (e.g. when growing). Although technically the internal systems should be smart enough to
  723. // avoid updates unless objects actually changed.
  724. if (element.gridParamsBindingIdx != -1)
  725. element.params->setParamBlockBuffer(element.gridParamsBindingIdx, gridParams, true);
  726. element.gridLightOffsetsAndSizeParam.set(gridLightOffsetsAndSize);
  727. element.gridLightIndicesParam.set(gridLightIndices);
  728. element.lightsBufferParam.set(visibleLightData.getLightBuffer());
  729. // Image based lighting params
  730. ImageBasedLightingParams& iblParams = element.imageBasedParams;
  731. if (iblParams.reflProbeParamsBindingIdx != -1)
  732. element.params->setParamBlockBuffer(iblParams.reflProbeParamsBindingIdx, reflProbeParamBuffer.buffer);
  733. element.gridProbeOffsetsAndSizeParam.set(gridProbeOffsetsAndSize);
  734. iblParams.reflectionProbeIndicesParam.set(gridProbeIndices);
  735. iblParams.reflectionProbesParam.set(visibleReflProbeData.getProbeBuffer());
  736. iblParams.skyReflectionsTexParam.set(skyFilteredRadiance);
  737. iblParams.ambientOcclusionTexParam.set(Texture::WHITE); // Note: Add SSAO here?
  738. iblParams.ssrTexParam.set(Texture::BLACK); // Note: Add SSR here?
  739. iblParams.reflectionProbeCubemapsTexParam.set(sceneInfo.reflProbeCubemapsTex);
  740. iblParams.preintegratedEnvBRDFParam.set(RendererTextures::preintegratedEnvGF);
  741. }
  742. }
  743. // TODO: Transparent objects cannot receive shadows. In order to support this I'd have to render the light occlusion
  744. // for all lights affecting this object into a single (or a few) textures. I can likely use texture arrays for this,
  745. // or to avoid sampling many textures, perhaps just jam it all in one or few texture channels.
  746. const Vector<RenderQueueElement>& transparentElements = inputs.view.getTransparentQueue()->getSortedElements();
  747. for (auto iter = transparentElements.begin(); iter != transparentElements.end(); ++iter)
  748. {
  749. BeastRenderableElement* renderElem = static_cast<BeastRenderableElement*>(iter->renderElem);
  750. SPtr<Material> material = renderElem->material;
  751. if (iter->applyPass)
  752. gRendererUtility().setPass(material, iter->passIdx, renderElem->techniqueIdx);
  753. gRendererUtility().setPassParams(renderElem->params, iter->passIdx);
  754. if(renderElem->morphVertexDeclaration == nullptr)
  755. gRendererUtility().draw(renderElem->mesh, renderElem->subMesh);
  756. else
  757. gRendererUtility().drawMorph(renderElem->mesh, renderElem->subMesh, renderElem->morphShapeBuffer,
  758. renderElem->morphVertexDeclaration);
  759. }
  760. // Trigger post-lighting callbacks
  761. Camera* sceneCamera = inputs.view.getSceneCamera();
  762. if (sceneCamera != nullptr)
  763. {
  764. for(auto& extension : inputs.extPostLighting)
  765. {
  766. if (extension->check(*sceneCamera))
  767. extension->render(*sceneCamera);
  768. }
  769. }
  770. }
  771. void RCNodeClusteredForward::clear()
  772. {
  773. // Do nothing
  774. }
  775. SmallVector<StringID, 4> RCNodeClusteredForward::getDependencies(const RendererView& view)
  776. {
  777. return { RCNodeSceneColor::getNodeId(), RCNodeSkybox::getNodeId() };
  778. }
  779. void RCNodeSkybox::render(const RenderCompositorNodeInputs& inputs)
  780. {
  781. Skybox* skybox = inputs.scene.skybox;
  782. SPtr<Texture> radiance = skybox ? skybox->getTexture() : nullptr;
  783. if (radiance != nullptr)
  784. {
  785. SkyboxMat* material = SkyboxMat::getVariation(false);
  786. material->bind(inputs.view.getPerViewBuffer());
  787. material->setParams(radiance, Color::White);
  788. }
  789. else
  790. {
  791. Color clearColor = inputs.view.getProperties().clearColor;
  792. SkyboxMat* material = SkyboxMat::getVariation(true);
  793. material->bind(inputs.view.getPerViewBuffer());
  794. material->setParams(nullptr, clearColor);
  795. }
  796. RCNodeSceneColor* sceneColorNode = static_cast<RCNodeSceneColor*>(inputs.inputNodes[1]);
  797. int readOnlyFlags = FBT_DEPTH | FBT_STENCIL;
  798. RenderAPI& rapi = RenderAPI::instance();
  799. rapi.setRenderTarget(sceneColorNode->renderTarget, readOnlyFlags, RT_COLOR0 | RT_DEPTH_STENCIL);
  800. Rect2 area(0.0f, 0.0f, 1.0f, 1.0f);
  801. rapi.setViewport(area);
  802. SPtr<Mesh> mesh = gRendererUtility().getSkyBoxMesh();
  803. gRendererUtility().draw(mesh, mesh->getProperties().getSubMesh(0));
  804. }
  805. void RCNodeSkybox::clear()
  806. { }
  807. SmallVector<StringID, 4> RCNodeSkybox::getDependencies(const RendererView& view)
  808. {
  809. SmallVector<StringID, 4> deps;
  810. deps.push_back(RCNodeTiledDeferredIBL::getNodeId());
  811. deps.push_back(RCNodeSceneColor::getNodeId());
  812. if (view.getProperties().numSamples > 1)
  813. deps.push_back(RCNodeUnflattenSceneColor::getNodeId());
  814. return deps;
  815. }
  816. void RCNodeFinalResolve::render(const RenderCompositorNodeInputs& inputs)
  817. {
  818. const RendererViewProperties& viewProps = inputs.view.getProperties();
  819. SPtr<Texture> input;
  820. if(viewProps.runPostProcessing)
  821. {
  822. RCNodePostProcess* postProcessNode = static_cast<RCNodePostProcess*>(inputs.inputNodes[0]);
  823. // Note: Ideally the last PP effect could write directly to the final target and we could avoid this copy
  824. input = postProcessNode->getLastOutput();
  825. }
  826. else
  827. {
  828. RCNodeSceneColor* sceneColorNode = static_cast<RCNodeSceneColor*>(inputs.inputNodes[0]);
  829. input = sceneColorNode->sceneColorTex->texture;
  830. }
  831. SPtr<RenderTarget> target = viewProps.target;
  832. RenderAPI& rapi = RenderAPI::instance();
  833. rapi.setRenderTarget(target);
  834. rapi.setViewport(viewProps.nrmViewRect);
  835. gRendererUtility().blit(input, Rect2I::EMPTY, viewProps.flipView);
  836. if(viewProps.encodeDepth)
  837. {
  838. RCNodeResolvedSceneDepth* resolvedSceneDepthNode = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[0]);
  839. EncodeDepthMat* encodeDepthMat = EncodeDepthMat::get();
  840. encodeDepthMat->execute(resolvedSceneDepthNode->output->texture, viewProps.depthEncodeNear,
  841. viewProps.depthEncodeFar, target);
  842. }
  843. // Trigger overlay callbacks
  844. Camera* sceneCamera = inputs.view.getSceneCamera();
  845. if (sceneCamera != nullptr)
  846. {
  847. for(auto& extension : inputs.extOverlay)
  848. {
  849. if (extension->check(*sceneCamera))
  850. extension->render(*sceneCamera);
  851. }
  852. }
  853. }
  854. void RCNodeFinalResolve::clear()
  855. { }
  856. SmallVector<StringID, 4> RCNodeFinalResolve::getDependencies(const RendererView& view)
  857. {
  858. const RendererViewProperties& viewProps = view.getProperties();
  859. SmallVector<StringID, 4> deps;
  860. if(viewProps.runPostProcessing)
  861. {
  862. deps.push_back(RCNodePostProcess::getNodeId());
  863. deps.push_back(RCNodeFXAA::getNodeId());
  864. }
  865. else
  866. {
  867. deps.push_back(RCNodeSceneColor::getNodeId());
  868. deps.push_back(RCNodeClusteredForward::getNodeId());
  869. }
  870. if(viewProps.encodeDepth)
  871. deps.push_back(RCNodeResolvedSceneDepth::getNodeId());
  872. return deps;
  873. }
  874. RCNodePostProcess::RCNodePostProcess()
  875. :mOutput(), mAllocated()
  876. { }
  877. void RCNodePostProcess::getAndSwitch(const RendererView& view, SPtr<RenderTexture>& output, SPtr<Texture>& lastFrame) const
  878. {
  879. GpuResourcePool& resPool = GpuResourcePool::instance();
  880. const RendererViewProperties& viewProps = view.getProperties();
  881. UINT32 width = viewProps.viewRect.width;
  882. UINT32 height = viewProps.viewRect.height;
  883. if(!mAllocated[mCurrentIdx])
  884. {
  885. mOutput[mCurrentIdx] = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA8, width, height,
  886. TU_RENDERTARGET, 1, false));
  887. mAllocated[mCurrentIdx] = true;
  888. }
  889. output = mOutput[mCurrentIdx]->renderTexture;
  890. UINT32 otherIdx = (mCurrentIdx + 1) % 2;
  891. if (mAllocated[otherIdx])
  892. lastFrame = mOutput[otherIdx]->texture;
  893. mCurrentIdx = otherIdx;
  894. }
  895. SPtr<Texture> RCNodePostProcess::getLastOutput() const
  896. {
  897. UINT32 otherIdx = (mCurrentIdx + 1) % 2;
  898. if (mAllocated[otherIdx])
  899. return mOutput[otherIdx]->texture;
  900. return nullptr;
  901. }
  902. void RCNodePostProcess::render(const RenderCompositorNodeInputs& inputs)
  903. {
  904. // Do nothing, this is just a helper node
  905. }
  906. void RCNodePostProcess::clear()
  907. {
  908. GpuResourcePool& resPool = GpuResourcePool::instance();
  909. if (mAllocated[0])
  910. resPool.release(mOutput[0]);
  911. if (mAllocated[1])
  912. resPool.release(mOutput[1]);
  913. mAllocated[0] = false;
  914. mAllocated[1] = false;
  915. mCurrentIdx = 0;
  916. }
  917. SmallVector<StringID, 4> RCNodePostProcess::getDependencies(const RendererView& view)
  918. {
  919. return {};
  920. }
  921. RCNodeTonemapping::~RCNodeTonemapping()
  922. {
  923. GpuResourcePool& resPool = GpuResourcePool::instance();
  924. if (mTonemapLUT)
  925. resPool.release(mTonemapLUT);
  926. if (prevEyeAdaptation)
  927. resPool.release(prevEyeAdaptation);
  928. }
  929. void RCNodeTonemapping::render(const RenderCompositorNodeInputs& inputs)
  930. {
  931. GpuResourcePool& resPool = GpuResourcePool::instance();
  932. const RendererViewProperties& viewProps = inputs.view.getProperties();
  933. const RenderSettings& settings = inputs.view.getRenderSettings();
  934. RCNodeSceneColor* sceneColorNode = static_cast<RCNodeSceneColor*>(inputs.inputNodes[0]);
  935. RCNodePostProcess* postProcessNode = static_cast<RCNodePostProcess*>(inputs.inputNodes[2]);
  936. SPtr<Texture> sceneColor = sceneColorNode->sceneColorTex->texture;
  937. bool hdr = settings.enableHDR;
  938. bool msaa = viewProps.numSamples > 1;
  939. if(hdr && settings.enableAutoExposure)
  940. {
  941. // Downsample scene
  942. DownsampleMat* downsampleMat = DownsampleMat::getVariation(1, msaa);
  943. SPtr<PooledRenderTexture> downsampledScene = resPool.get(DownsampleMat::getOutputDesc(sceneColor));
  944. downsampleMat->execute(sceneColor, downsampledScene->renderTexture);
  945. // Generate histogram
  946. SPtr<PooledRenderTexture> eyeAdaptHistogram = resPool.get(
  947. EyeAdaptHistogramMat::getOutputDesc(downsampledScene->texture));
  948. EyeAdaptHistogramMat* eyeAdaptHistogramMat = EyeAdaptHistogramMat::get();
  949. eyeAdaptHistogramMat->execute(downsampledScene->texture, eyeAdaptHistogram->texture, settings.autoExposure);
  950. // Reduce histogram
  951. SPtr<PooledRenderTexture> reducedHistogram = resPool.get(EyeAdaptHistogramReduceMat::getOutputDesc());
  952. SPtr<Texture> prevFrameEyeAdaptation;
  953. if (prevEyeAdaptation != nullptr)
  954. prevFrameEyeAdaptation = prevEyeAdaptation->texture;
  955. EyeAdaptHistogramReduceMat* eyeAdaptHistogramReduce = EyeAdaptHistogramReduceMat::get();
  956. eyeAdaptHistogramReduce->execute(downsampledScene->texture, eyeAdaptHistogram->texture,
  957. prevFrameEyeAdaptation, reducedHistogram->renderTexture);
  958. resPool.release(downsampledScene);
  959. downsampledScene = nullptr;
  960. resPool.release(eyeAdaptHistogram);
  961. eyeAdaptHistogram = nullptr;
  962. // Generate eye adaptation value
  963. eyeAdaptation = resPool.get(EyeAdaptationMat::getOutputDesc());
  964. EyeAdaptationMat* eyeAdaptationMat = EyeAdaptationMat::get();
  965. eyeAdaptationMat->execute(reducedHistogram->texture, eyeAdaptation->renderTexture, inputs.frameInfo.timeDelta,
  966. settings.autoExposure, settings.exposureScale);
  967. resPool.release(reducedHistogram);
  968. reducedHistogram = nullptr;
  969. }
  970. else
  971. {
  972. if(prevEyeAdaptation)
  973. resPool.release(prevEyeAdaptation);
  974. prevEyeAdaptation = nullptr;
  975. eyeAdaptation = nullptr;
  976. }
  977. bool gammaOnly;
  978. bool autoExposure;
  979. if (hdr)
  980. {
  981. if (settings.enableTonemapping)
  982. {
  983. UINT64 latestHash = inputs.view.getRenderSettingsHash();
  984. bool tonemapLUTDirty = mTonemapLastUpdateHash != latestHash;
  985. if (tonemapLUTDirty) // Rebuild LUT if PP settings changed
  986. {
  987. if(mTonemapLUT == nullptr)
  988. mTonemapLUT = resPool.get(CreateTonemapLUTMat::getOutputDesc());
  989. CreateTonemapLUTMat* createLUT = CreateTonemapLUTMat::get();
  990. createLUT->execute(mTonemapLUT->texture, settings);
  991. mTonemapLastUpdateHash = latestHash;
  992. }
  993. gammaOnly = false;
  994. }
  995. else
  996. gammaOnly = true;
  997. autoExposure = settings.enableAutoExposure;
  998. }
  999. else
  1000. {
  1001. gammaOnly = true;
  1002. autoExposure = false;
  1003. }
  1004. if(gammaOnly)
  1005. {
  1006. if(mTonemapLUT)
  1007. {
  1008. resPool.release(mTonemapLUT);
  1009. mTonemapLUT = nullptr;
  1010. }
  1011. }
  1012. TonemappingMat* tonemapping = TonemappingMat::getVariation(gammaOnly, autoExposure, msaa);
  1013. SPtr<RenderTexture> ppOutput;
  1014. SPtr<Texture> ppLastFrame;
  1015. postProcessNode->getAndSwitch(inputs.view, ppOutput, ppLastFrame);
  1016. SPtr<Texture> eyeAdaptationTex;
  1017. if (eyeAdaptation)
  1018. eyeAdaptationTex = eyeAdaptation->texture;
  1019. SPtr<Texture> tonemapLUTTex;
  1020. if (mTonemapLUT)
  1021. tonemapLUTTex = mTonemapLUT->texture;
  1022. tonemapping->execute(sceneColor, eyeAdaptationTex, tonemapLUTTex, ppOutput, settings);
  1023. }
  1024. void RCNodeTonemapping::clear()
  1025. {
  1026. GpuResourcePool& resPool = GpuResourcePool::instance();
  1027. // Save eye adaptation for next frame
  1028. if(prevEyeAdaptation)
  1029. resPool.release(prevEyeAdaptation);
  1030. std::swap(eyeAdaptation, prevEyeAdaptation);
  1031. }
  1032. SmallVector<StringID, 4> RCNodeTonemapping::getDependencies(const RendererView& view)
  1033. {
  1034. return{ RCNodeSceneColor::getNodeId(), RCNodeClusteredForward::getNodeId(), RCNodePostProcess::getNodeId() };
  1035. }
  1036. void RCNodeGaussianDOF::render(const RenderCompositorNodeInputs& inputs)
  1037. {
  1038. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[1]);
  1039. RCNodePostProcess* postProcessNode = static_cast<RCNodePostProcess*>(inputs.inputNodes[2]);
  1040. const DepthOfFieldSettings& settings = inputs.view.getRenderSettings().depthOfField;
  1041. bool near = settings.nearBlurAmount > 0.0f;
  1042. bool far = settings.farBlurAmount > 0.0f;
  1043. bool enabled = settings.enabled && (near || far);
  1044. if(!enabled)
  1045. return;
  1046. GaussianDOFSeparateMat* separateMat = GaussianDOFSeparateMat::getVariation(near, far);
  1047. GaussianDOFCombineMat* combineMat = GaussianDOFCombineMat::getVariation(near, far);
  1048. GaussianBlurMat* blurMat = GaussianBlurMat::get();
  1049. SPtr<RenderTexture> ppOutput;
  1050. SPtr<Texture> ppLastFrame;
  1051. postProcessNode->getAndSwitch(inputs.view, ppOutput, ppLastFrame);
  1052. separateMat->execute(ppLastFrame, sceneDepthNode->depthTex->texture, inputs.view, settings);
  1053. SPtr<PooledRenderTexture> nearTex, farTex;
  1054. if(near && far)
  1055. {
  1056. nearTex = separateMat->getOutput(0);
  1057. farTex = separateMat->getOutput(1);
  1058. }
  1059. else
  1060. {
  1061. if (near)
  1062. nearTex = separateMat->getOutput(0);
  1063. else
  1064. farTex = separateMat->getOutput(0);
  1065. }
  1066. // Blur the out of focus pixels
  1067. // Note: Perhaps set up stencil so I can avoid performing blur on unused parts of the textures?
  1068. const TextureProperties& texProps = nearTex ? nearTex->texture->getProperties() : farTex->texture->getProperties();
  1069. POOLED_RENDER_TEXTURE_DESC tempTexDesc = POOLED_RENDER_TEXTURE_DESC::create2D(texProps.getFormat(),
  1070. texProps.getWidth(), texProps.getHeight(), TU_RENDERTARGET);
  1071. SPtr<PooledRenderTexture> tempTexture = GpuResourcePool::instance().get(tempTexDesc);
  1072. SPtr<Texture> blurredNearTex;
  1073. if(nearTex)
  1074. {
  1075. blurMat->execute(nearTex->texture, settings.nearBlurAmount, tempTexture->renderTexture);
  1076. blurredNearTex = tempTexture->texture;
  1077. }
  1078. SPtr<Texture> blurredFarTex;
  1079. if(farTex)
  1080. {
  1081. // If temporary texture is used up, re-use the original near texture for the blurred result
  1082. if(blurredNearTex)
  1083. {
  1084. blurMat->execute(farTex->texture, settings.farBlurAmount, nearTex->renderTexture);
  1085. blurredFarTex = nearTex->texture;
  1086. }
  1087. else // Otherwise just use the temporary
  1088. {
  1089. blurMat->execute(farTex->texture, settings.farBlurAmount, tempTexture->renderTexture);
  1090. blurredFarTex = tempTexture->texture;
  1091. }
  1092. }
  1093. combineMat->execute(ppLastFrame, blurredNearTex, blurredFarTex,
  1094. sceneDepthNode->depthTex->texture, ppOutput, inputs.view, settings);
  1095. separateMat->release();
  1096. GpuResourcePool::instance().release(tempTexture);
  1097. }
  1098. void RCNodeGaussianDOF::clear()
  1099. {
  1100. // Do nothing
  1101. }
  1102. SmallVector<StringID, 4> RCNodeGaussianDOF::getDependencies(const RendererView& view)
  1103. {
  1104. return { RCNodeTonemapping::getNodeId(), RCNodeSceneDepth::getNodeId(), RCNodePostProcess::getNodeId() };
  1105. }
  1106. void RCNodeFXAA::render(const RenderCompositorNodeInputs& inputs)
  1107. {
  1108. const RenderSettings& settings = inputs.view.getRenderSettings();
  1109. if (!settings.enableFXAA)
  1110. return;
  1111. RCNodePostProcess* postProcessNode = static_cast<RCNodePostProcess*>(inputs.inputNodes[1]);
  1112. SPtr<RenderTexture> ppOutput;
  1113. SPtr<Texture> ppLastFrame;
  1114. postProcessNode->getAndSwitch(inputs.view, ppOutput, ppLastFrame);
  1115. // Note: I could skip executing FXAA over DOF and motion blurred pixels
  1116. FXAAMat* fxaa = FXAAMat::get();
  1117. fxaa->execute(ppLastFrame, ppOutput);
  1118. }
  1119. void RCNodeFXAA::clear()
  1120. {
  1121. // Do nothing
  1122. }
  1123. SmallVector<StringID, 4> RCNodeFXAA::getDependencies(const RendererView& view)
  1124. {
  1125. return { RCNodeGaussianDOF::getNodeId(), RCNodePostProcess::getNodeId() };
  1126. }
  1127. void RCNodeResolvedSceneDepth::render(const RenderCompositorNodeInputs& inputs)
  1128. {
  1129. GpuResourcePool& resPool = GpuResourcePool::instance();
  1130. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1131. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[0]);
  1132. if (viewProps.numSamples > 1)
  1133. {
  1134. UINT32 width = viewProps.viewRect.width;
  1135. UINT32 height = viewProps.viewRect.height;
  1136. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_D32_S8X24, width, height, TU_RENDERTARGET, 1, false));
  1137. RenderAPI& rapi = RenderAPI::instance();
  1138. rapi.setRenderTarget(output->renderTexture);
  1139. rapi.clearRenderTarget(FBT_STENCIL);
  1140. gRendererUtility().blit(sceneDepthNode->depthTex->texture, Rect2I::EMPTY, false, true);
  1141. mPassThrough = false;
  1142. }
  1143. else
  1144. {
  1145. output = sceneDepthNode->depthTex;
  1146. mPassThrough = true;
  1147. }
  1148. }
  1149. void RCNodeResolvedSceneDepth::clear()
  1150. {
  1151. GpuResourcePool& resPool = GpuResourcePool::instance();
  1152. if (!mPassThrough)
  1153. resPool.release(output);
  1154. else
  1155. output = nullptr;
  1156. mPassThrough = false;
  1157. }
  1158. SmallVector<StringID, 4> RCNodeResolvedSceneDepth::getDependencies(const RendererView& view)
  1159. {
  1160. // GBuffer require because it renders the base pass (populates the depth buffer)
  1161. return { RCNodeSceneDepth::getNodeId(), RCNodeGBuffer::getNodeId() };
  1162. }
  1163. void RCNodeHiZ::render(const RenderCompositorNodeInputs& inputs)
  1164. {
  1165. GpuResourcePool& resPool = GpuResourcePool::instance();
  1166. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1167. RCNodeResolvedSceneDepth* resolvedSceneDepth = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[0]);
  1168. UINT32 width = viewProps.viewRect.width;
  1169. UINT32 height = viewProps.viewRect.height;
  1170. UINT32 size = Bitwise::nextPow2(std::max(width, height));
  1171. UINT32 numMips = PixelUtil::getMaxMipmaps(size, size, 1, PF_R32F);
  1172. size = 1 << numMips;
  1173. // Note: Use the 32-bit buffer here as 16-bit causes too much banding (most of the scene gets assigned 4-5 different
  1174. // depth values).
  1175. // - When I add UNORM 16-bit format I should be able to switch to that
  1176. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_R32F, size, size, TU_RENDERTARGET, 1, false, 1,
  1177. numMips));
  1178. Rect2 srcRect = viewProps.nrmViewRect;
  1179. // If viewport size is odd, adjust UV
  1180. srcRect.width += (viewProps.viewRect.width % 2) * (1.0f / viewProps.viewRect.width);
  1181. srcRect.height += (viewProps.viewRect.height % 2) * (1.0f / viewProps.viewRect.height);
  1182. // Generate first mip
  1183. RENDER_TEXTURE_DESC rtDesc;
  1184. rtDesc.colorSurfaces[0].texture = output->texture;
  1185. rtDesc.colorSurfaces[0].mipLevel = 0;
  1186. SPtr<RenderTexture> rt = RenderTexture::create(rtDesc);
  1187. Rect2 destRect;
  1188. bool downsampledFirstMip = false; // Not used currently
  1189. if (downsampledFirstMip)
  1190. {
  1191. // Make sure that 1 pixel in HiZ maps to a 2x2 block in source
  1192. destRect = Rect2(0, 0,
  1193. Math::ceilToInt(viewProps.viewRect.width / 2.0f) / (float)size,
  1194. Math::ceilToInt(viewProps.viewRect.height / 2.0f) / (float)size);
  1195. BuildHiZMat* material = BuildHiZMat::get();
  1196. material->execute(resolvedSceneDepth->output->texture, 0, srcRect, destRect, rt);
  1197. }
  1198. else // First level is just a copy of the depth buffer
  1199. {
  1200. destRect = Rect2(0, 0,
  1201. viewProps.viewRect.width / (float)size,
  1202. viewProps.viewRect.height / (float)size);
  1203. RenderAPI& rapi = RenderAPI::instance();
  1204. rapi.setRenderTarget(rt);
  1205. rapi.setViewport(destRect);
  1206. Rect2I srcAreaInt;
  1207. srcAreaInt.x = (INT32)(srcRect.x * viewProps.viewRect.width);
  1208. srcAreaInt.y = (INT32)(srcRect.y * viewProps.viewRect.height);
  1209. srcAreaInt.width = (UINT32)(srcRect.width * viewProps.viewRect.width);
  1210. srcAreaInt.height = (UINT32)(srcRect.height * viewProps.viewRect.height);
  1211. gRendererUtility().blit(resolvedSceneDepth->output->texture, srcAreaInt);
  1212. rapi.setViewport(Rect2(0, 0, 1, 1));
  1213. }
  1214. // Generate remaining mip levels
  1215. for(UINT32 i = 1; i <= numMips; i++)
  1216. {
  1217. rtDesc.colorSurfaces[0].mipLevel = i;
  1218. rt = RenderTexture::create(rtDesc);
  1219. BuildHiZMat* material = BuildHiZMat::get();
  1220. material->execute(output->texture, i - 1, destRect, destRect, rt);
  1221. }
  1222. }
  1223. void RCNodeHiZ::clear()
  1224. {
  1225. GpuResourcePool& resPool = GpuResourcePool::instance();
  1226. resPool.release(output);
  1227. }
  1228. SmallVector<StringID, 4> RCNodeHiZ::getDependencies(const RendererView& view)
  1229. {
  1230. // Note: This doesn't actually use any gbuffer textures, but node is a dependency because it renders to the depth
  1231. // buffer. In order to avoid keeping gbuffer textures alive I could separate out the base pass into its own node
  1232. // perhaps. But at the moment it doesn't matter, as anything using HiZ also needs gbuffer.
  1233. return { RCNodeResolvedSceneDepth::getNodeId(), RCNodeGBuffer::getNodeId() };
  1234. }
  1235. void RCNodeSSAO::render(const RenderCompositorNodeInputs& inputs)
  1236. {
  1237. /** Maximum valid depth range within samples in a sample set. In meters. */
  1238. static const float DEPTH_RANGE = 1.0f;
  1239. GpuResourcePool& resPool = GpuResourcePool::instance();
  1240. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1241. const AmbientOcclusionSettings& settings = inputs.view.getRenderSettings().ambientOcclusion;
  1242. RCNodeResolvedSceneDepth* resolvedDepthNode = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[0]);
  1243. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[1]);
  1244. SPtr<Texture> sceneDepth = resolvedDepthNode->output->texture;
  1245. SPtr<Texture> sceneNormals = gbufferNode->normalTex->texture;
  1246. const TextureProperties& normalsProps = sceneNormals->getProperties();
  1247. SPtr<PooledRenderTexture> resolvedNormals;
  1248. RenderAPI& rapi = RenderAPI::instance();
  1249. if(sceneNormals->getProperties().getNumSamples() > 1)
  1250. {
  1251. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(normalsProps.getFormat(),
  1252. normalsProps.getWidth(), normalsProps.getHeight(), TU_RENDERTARGET);
  1253. resolvedNormals = resPool.get(desc);
  1254. rapi.setRenderTarget(resolvedNormals->renderTexture);
  1255. gRendererUtility().blit(sceneNormals);
  1256. sceneNormals = resolvedNormals->texture;
  1257. }
  1258. // Multiple downsampled AO levels are used to minimize cache trashing. Downsampled AO targets use larger radius,
  1259. // whose contents are then blended with the higher level.
  1260. UINT32 quality = settings.quality;
  1261. UINT32 numDownsampleLevels = 0;
  1262. if (quality > 1)
  1263. numDownsampleLevels = 1;
  1264. else if (quality > 2)
  1265. numDownsampleLevels = 2;
  1266. SSAODownsampleMat* downsample = SSAODownsampleMat::get();
  1267. SPtr<PooledRenderTexture> setupTex0;
  1268. if(numDownsampleLevels > 0)
  1269. {
  1270. Vector2I downsampledSize(
  1271. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 2)),
  1272. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 2))
  1273. );
  1274. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, downsampledSize.x,
  1275. downsampledSize.y, TU_RENDERTARGET);
  1276. setupTex0 = GpuResourcePool::instance().get(desc);
  1277. downsample->execute(inputs.view, sceneDepth, sceneNormals, setupTex0->renderTexture, DEPTH_RANGE);
  1278. }
  1279. SPtr<PooledRenderTexture> setupTex1;
  1280. if(numDownsampleLevels > 1)
  1281. {
  1282. Vector2I downsampledSize(
  1283. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 4)),
  1284. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 4))
  1285. );
  1286. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, downsampledSize.x,
  1287. downsampledSize.y, TU_RENDERTARGET);
  1288. setupTex1 = GpuResourcePool::instance().get(desc);
  1289. downsample->execute(inputs.view, sceneDepth, sceneNormals, setupTex1->renderTexture, DEPTH_RANGE);
  1290. }
  1291. SSAOTextureInputs textures;
  1292. textures.sceneDepth = sceneDepth;
  1293. textures.sceneNormals = sceneNormals;
  1294. textures.randomRotations = RendererTextures::ssaoRandomization4x4;
  1295. SPtr<PooledRenderTexture> downAOTex1;
  1296. if(numDownsampleLevels > 1)
  1297. {
  1298. textures.aoSetup = setupTex1->texture;
  1299. Vector2I downsampledSize(
  1300. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 4)),
  1301. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 4))
  1302. );
  1303. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, downsampledSize.x,
  1304. downsampledSize.y, TU_RENDERTARGET);
  1305. downAOTex1 = GpuResourcePool::instance().get(desc);
  1306. SSAOMat* ssaoMat = SSAOMat::getVariation(false, false, quality);
  1307. ssaoMat->execute(inputs.view, textures, downAOTex1->renderTexture, settings);
  1308. GpuResourcePool::instance().release(setupTex1);
  1309. setupTex1 = nullptr;
  1310. }
  1311. SPtr<PooledRenderTexture> downAOTex0;
  1312. if(numDownsampleLevels > 0)
  1313. {
  1314. textures.aoSetup = setupTex0->texture;
  1315. if(downAOTex1)
  1316. textures.aoDownsampled = downAOTex1->texture;
  1317. Vector2I downsampledSize(
  1318. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 2)),
  1319. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 2))
  1320. );
  1321. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, downsampledSize.x,
  1322. downsampledSize.y, TU_RENDERTARGET);
  1323. downAOTex0 = GpuResourcePool::instance().get(desc);
  1324. bool upsample = numDownsampleLevels > 1;
  1325. SSAOMat* ssaoMat = SSAOMat::getVariation(upsample, false, quality);
  1326. ssaoMat->execute(inputs.view, textures, downAOTex0->renderTexture, settings);
  1327. if(upsample)
  1328. {
  1329. GpuResourcePool::instance().release(downAOTex1);
  1330. downAOTex1 = nullptr;
  1331. }
  1332. }
  1333. UINT32 width = viewProps.viewRect.width;
  1334. UINT32 height = viewProps.viewRect.height;
  1335. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, width, height, TU_RENDERTARGET));
  1336. {
  1337. if(setupTex0)
  1338. textures.aoSetup = setupTex0->texture;
  1339. if(downAOTex0)
  1340. textures.aoDownsampled = downAOTex0->texture;
  1341. bool upsample = numDownsampleLevels > 0;
  1342. SSAOMat* ssaoMat = SSAOMat::getVariation(upsample, true, quality);
  1343. ssaoMat->execute(inputs.view, textures, output->renderTexture, settings);
  1344. }
  1345. if(resolvedNormals)
  1346. {
  1347. GpuResourcePool::instance().release(resolvedNormals);
  1348. resolvedNormals = nullptr;
  1349. }
  1350. if(numDownsampleLevels > 0)
  1351. {
  1352. GpuResourcePool::instance().release(setupTex0);
  1353. GpuResourcePool::instance().release(downAOTex0);
  1354. }
  1355. // Blur the output
  1356. // Note: If I implement temporal AA then this can probably be avoided. I can instead jitter the sample offsets
  1357. // each frame, and averaging them out should yield blurred AO.
  1358. if(quality > 1) // On level 0 we don't blur at all, on level 1 we use the ad-hoc blur in shader
  1359. {
  1360. const RenderTargetProperties& rtProps = output->renderTexture->getProperties();
  1361. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, rtProps.getWidth(),
  1362. rtProps.getHeight(), TU_RENDERTARGET);
  1363. SPtr<PooledRenderTexture> blurIntermediateTex = GpuResourcePool::instance().get(desc);
  1364. SSAOBlurMat* blurHorz = SSAOBlurMat::getVariation(true);
  1365. SSAOBlurMat* blurVert = SSAOBlurMat::getVariation(false);
  1366. blurHorz->execute(inputs.view, output->texture, sceneDepth, blurIntermediateTex->renderTexture, DEPTH_RANGE);
  1367. blurVert->execute(inputs.view, blurIntermediateTex->texture, sceneDepth, output->renderTexture, DEPTH_RANGE);
  1368. GpuResourcePool::instance().release(blurIntermediateTex);
  1369. }
  1370. }
  1371. void RCNodeSSAO::clear()
  1372. {
  1373. GpuResourcePool& resPool = GpuResourcePool::instance();
  1374. resPool.release(output);
  1375. }
  1376. SmallVector<StringID, 4> RCNodeSSAO::getDependencies(const RendererView& view)
  1377. {
  1378. return { RCNodeResolvedSceneDepth::getNodeId(), RCNodeGBuffer::getNodeId() };
  1379. }
  1380. RCNodeSSR::~RCNodeSSR()
  1381. {
  1382. deallocOutputs();
  1383. }
  1384. void RCNodeSSR::render(const RenderCompositorNodeInputs& inputs)
  1385. {
  1386. const ScreenSpaceReflectionsSettings& settings = inputs.view.getRenderSettings().screenSpaceReflections;
  1387. if (settings.enabled)
  1388. {
  1389. RenderAPI& rapi = RenderAPI::instance();
  1390. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[0]);
  1391. RCNodeLightAccumulation* lightAccumNode = static_cast<RCNodeLightAccumulation*>(inputs.inputNodes[1]);
  1392. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[2]);
  1393. RCNodeHiZ* hiZNode = static_cast<RCNodeHiZ*>(inputs.inputNodes[3]);
  1394. RCNodeResolvedSceneDepth* resolvedSceneDepthNode = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[4]);
  1395. GpuResourcePool& resPool = GpuResourcePool::instance();
  1396. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1397. UINT32 width = viewProps.viewRect.width;
  1398. UINT32 height = viewProps.viewRect.height;
  1399. SPtr<Texture> hiZ = hiZNode->output->texture;
  1400. // This will be executing before scene color is resolved, so get the light accum buffer instead
  1401. SPtr<Texture> sceneColor = lightAccumNode->lightAccumulationTex->texture;
  1402. // Resolve multiple samples if MSAA is used
  1403. SPtr<PooledRenderTexture> resolvedSceneColor;
  1404. if(viewProps.numSamples > 1)
  1405. {
  1406. resolvedSceneColor = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width, height,
  1407. TU_RENDERTARGET));
  1408. rapi.setRenderTarget(resolvedSceneColor->renderTexture);
  1409. gRendererUtility().blit(sceneColor);
  1410. sceneColor = resolvedSceneColor->texture;
  1411. }
  1412. GBufferTextures gbuffer;
  1413. gbuffer.albedo = gbufferNode->albedoTex->texture;
  1414. gbuffer.normals = gbufferNode->normalTex->texture;
  1415. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  1416. gbuffer.depth = sceneDepthNode->depthTex->texture;
  1417. SSRStencilMat* stencilMat = SSRStencilMat::getVariation(viewProps.numSamples > 1);
  1418. // Note: Making the assumption that the stencil buffer is clear at this point
  1419. rapi.setRenderTarget(resolvedSceneDepthNode->output->renderTexture);
  1420. stencilMat->execute(inputs.view, gbuffer, settings);
  1421. SPtr<PooledRenderTexture> traceOutput = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width,
  1422. height, TU_RENDERTARGET));
  1423. RENDER_TEXTURE_DESC traceRtDesc;
  1424. traceRtDesc.colorSurfaces[0].texture = traceOutput->texture;
  1425. traceRtDesc.depthStencilSurface.texture = resolvedSceneDepthNode->output->texture;
  1426. SPtr<RenderTexture> traceRt = RenderTexture::create(traceRtDesc);
  1427. rapi.setRenderTarget(traceRt);
  1428. rapi.clearRenderTarget(FBT_COLOR);
  1429. SSRTraceMat* traceMat = SSRTraceMat::getVariation(settings.quality, viewProps.numSamples > 1);
  1430. traceMat->execute(inputs.view, gbuffer, sceneColor, hiZ, settings, traceRt);
  1431. if (resolvedSceneColor)
  1432. {
  1433. resPool.release(resolvedSceneColor);
  1434. resolvedSceneColor = nullptr;
  1435. }
  1436. if (mPrevFrame)
  1437. {
  1438. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width, height, TU_RENDERTARGET));
  1439. rapi.setRenderTarget(output->renderTexture);
  1440. rapi.clearRenderTarget(FBT_COLOR);
  1441. SSRResolveMat* resolveMat = SSRResolveMat::getVariation(viewProps.numSamples > 1);
  1442. resolveMat->execute(inputs.view, mPrevFrame->texture, traceOutput->texture, sceneDepthNode->depthTex->texture,
  1443. output->renderTexture);
  1444. resPool.release(traceOutput);
  1445. }
  1446. else
  1447. output = traceOutput;
  1448. RenderAPI::instance().setRenderTarget(nullptr);
  1449. }
  1450. else
  1451. deallocOutputs();
  1452. }
  1453. void RCNodeSSR::clear()
  1454. {
  1455. GpuResourcePool& resPool = GpuResourcePool::instance();
  1456. if(mPrevFrame)
  1457. resPool.release(mPrevFrame);
  1458. mPrevFrame = output;
  1459. output = nullptr;
  1460. }
  1461. void RCNodeSSR::deallocOutputs()
  1462. {
  1463. GpuResourcePool& resPool = GpuResourcePool::instance();
  1464. if(mPrevFrame)
  1465. {
  1466. resPool.release(mPrevFrame);
  1467. mPrevFrame = nullptr;
  1468. }
  1469. }
  1470. SmallVector<StringID, 4> RCNodeSSR::getDependencies(const RendererView& view)
  1471. {
  1472. SmallVector<StringID, 4> deps;
  1473. if (view.getRenderSettings().screenSpaceReflections.enabled)
  1474. {
  1475. deps.push_back(RCNodeSceneDepth::getNodeId());
  1476. deps.push_back(RCNodeLightAccumulation::getNodeId());
  1477. deps.push_back(RCNodeGBuffer::getNodeId());
  1478. deps.push_back(RCNodeHiZ::getNodeId());
  1479. deps.push_back(RCNodeResolvedSceneDepth::getNodeId());
  1480. if (view.getProperties().numSamples > 1)
  1481. deps.push_back(RCNodeUnflattenLightAccum::getNodeId());
  1482. }
  1483. return deps;
  1484. }
  1485. }}