BsRenderCompositor.cpp 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883
  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,
  1137. TU_DEPTHSTENCIL, 1, false));
  1138. RenderAPI& rapi = RenderAPI::instance();
  1139. rapi.setRenderTarget(output->renderTexture);
  1140. rapi.clearRenderTarget(FBT_STENCIL);
  1141. gRendererUtility().blit(sceneDepthNode->depthTex->texture, Rect2I::EMPTY, false, true);
  1142. mPassThrough = false;
  1143. }
  1144. else
  1145. {
  1146. output = sceneDepthNode->depthTex;
  1147. mPassThrough = true;
  1148. }
  1149. }
  1150. void RCNodeResolvedSceneDepth::clear()
  1151. {
  1152. GpuResourcePool& resPool = GpuResourcePool::instance();
  1153. if (!mPassThrough)
  1154. resPool.release(output);
  1155. else
  1156. output = nullptr;
  1157. mPassThrough = false;
  1158. }
  1159. SmallVector<StringID, 4> RCNodeResolvedSceneDepth::getDependencies(const RendererView& view)
  1160. {
  1161. // GBuffer require because it renders the base pass (populates the depth buffer)
  1162. return { RCNodeSceneDepth::getNodeId(), RCNodeGBuffer::getNodeId() };
  1163. }
  1164. void RCNodeHiZ::render(const RenderCompositorNodeInputs& inputs)
  1165. {
  1166. GpuResourcePool& resPool = GpuResourcePool::instance();
  1167. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1168. RCNodeResolvedSceneDepth* resolvedSceneDepth = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[0]);
  1169. UINT32 width = viewProps.viewRect.width;
  1170. UINT32 height = viewProps.viewRect.height;
  1171. UINT32 size = Bitwise::nextPow2(std::max(width, height));
  1172. UINT32 numMips = PixelUtil::getMaxMipmaps(size, size, 1, PF_R32F);
  1173. size = 1 << numMips;
  1174. // Note: Use the 32-bit buffer here as 16-bit causes too much banding (most of the scene gets assigned 4-5 different
  1175. // depth values).
  1176. // - When I add UNORM 16-bit format I should be able to switch to that
  1177. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_R32F, size, size, TU_RENDERTARGET, 1, false, 1,
  1178. numMips));
  1179. Rect2 srcRect = viewProps.nrmViewRect;
  1180. // If viewport size is odd, adjust UV
  1181. srcRect.width += (viewProps.viewRect.width % 2) * (1.0f / viewProps.viewRect.width);
  1182. srcRect.height += (viewProps.viewRect.height % 2) * (1.0f / viewProps.viewRect.height);
  1183. // Generate first mip
  1184. RENDER_TEXTURE_DESC rtDesc;
  1185. rtDesc.colorSurfaces[0].texture = output->texture;
  1186. rtDesc.colorSurfaces[0].mipLevel = 0;
  1187. SPtr<RenderTexture> rt = RenderTexture::create(rtDesc);
  1188. Rect2 destRect;
  1189. bool downsampledFirstMip = false; // Not used currently
  1190. if (downsampledFirstMip)
  1191. {
  1192. // Make sure that 1 pixel in HiZ maps to a 2x2 block in source
  1193. destRect = Rect2(0, 0,
  1194. Math::ceilToInt(viewProps.viewRect.width / 2.0f) / (float)size,
  1195. Math::ceilToInt(viewProps.viewRect.height / 2.0f) / (float)size);
  1196. BuildHiZMat* material = BuildHiZMat::get();
  1197. material->execute(resolvedSceneDepth->output->texture, 0, srcRect, destRect, rt);
  1198. }
  1199. else // First level is just a copy of the depth buffer
  1200. {
  1201. destRect = Rect2(0, 0,
  1202. viewProps.viewRect.width / (float)size,
  1203. viewProps.viewRect.height / (float)size);
  1204. RenderAPI& rapi = RenderAPI::instance();
  1205. rapi.setRenderTarget(rt);
  1206. rapi.setViewport(destRect);
  1207. Rect2I srcAreaInt;
  1208. srcAreaInt.x = (INT32)(srcRect.x * viewProps.viewRect.width);
  1209. srcAreaInt.y = (INT32)(srcRect.y * viewProps.viewRect.height);
  1210. srcAreaInt.width = (UINT32)(srcRect.width * viewProps.viewRect.width);
  1211. srcAreaInt.height = (UINT32)(srcRect.height * viewProps.viewRect.height);
  1212. gRendererUtility().blit(resolvedSceneDepth->output->texture, srcAreaInt);
  1213. rapi.setViewport(Rect2(0, 0, 1, 1));
  1214. }
  1215. // Generate remaining mip levels
  1216. for(UINT32 i = 1; i <= numMips; i++)
  1217. {
  1218. rtDesc.colorSurfaces[0].mipLevel = i;
  1219. rt = RenderTexture::create(rtDesc);
  1220. BuildHiZMat* material = BuildHiZMat::get();
  1221. material->execute(output->texture, i - 1, destRect, destRect, rt);
  1222. }
  1223. }
  1224. void RCNodeHiZ::clear()
  1225. {
  1226. GpuResourcePool& resPool = GpuResourcePool::instance();
  1227. resPool.release(output);
  1228. }
  1229. SmallVector<StringID, 4> RCNodeHiZ::getDependencies(const RendererView& view)
  1230. {
  1231. // Note: This doesn't actually use any gbuffer textures, but node is a dependency because it renders to the depth
  1232. // buffer. In order to avoid keeping gbuffer textures alive I could separate out the base pass into its own node
  1233. // perhaps. But at the moment it doesn't matter, as anything using HiZ also needs gbuffer.
  1234. return { RCNodeResolvedSceneDepth::getNodeId(), RCNodeGBuffer::getNodeId() };
  1235. }
  1236. void RCNodeSSAO::render(const RenderCompositorNodeInputs& inputs)
  1237. {
  1238. /** Maximum valid depth range within samples in a sample set. In meters. */
  1239. static const float DEPTH_RANGE = 1.0f;
  1240. GpuResourcePool& resPool = GpuResourcePool::instance();
  1241. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1242. const AmbientOcclusionSettings& settings = inputs.view.getRenderSettings().ambientOcclusion;
  1243. RCNodeResolvedSceneDepth* resolvedDepthNode = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[0]);
  1244. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[1]);
  1245. SPtr<Texture> sceneDepth = resolvedDepthNode->output->texture;
  1246. SPtr<Texture> sceneNormals = gbufferNode->normalTex->texture;
  1247. const TextureProperties& normalsProps = sceneNormals->getProperties();
  1248. SPtr<PooledRenderTexture> resolvedNormals;
  1249. RenderAPI& rapi = RenderAPI::instance();
  1250. if(sceneNormals->getProperties().getNumSamples() > 1)
  1251. {
  1252. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(normalsProps.getFormat(),
  1253. normalsProps.getWidth(), normalsProps.getHeight(), TU_RENDERTARGET);
  1254. resolvedNormals = resPool.get(desc);
  1255. rapi.setRenderTarget(resolvedNormals->renderTexture);
  1256. gRendererUtility().blit(sceneNormals);
  1257. sceneNormals = resolvedNormals->texture;
  1258. }
  1259. // Multiple downsampled AO levels are used to minimize cache trashing. Downsampled AO targets use larger radius,
  1260. // whose contents are then blended with the higher level.
  1261. UINT32 quality = settings.quality;
  1262. UINT32 numDownsampleLevels = 0;
  1263. if (quality > 1)
  1264. numDownsampleLevels = 1;
  1265. else if (quality > 2)
  1266. numDownsampleLevels = 2;
  1267. SSAODownsampleMat* downsample = SSAODownsampleMat::get();
  1268. SPtr<PooledRenderTexture> setupTex0;
  1269. if(numDownsampleLevels > 0)
  1270. {
  1271. Vector2I downsampledSize(
  1272. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 2)),
  1273. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 2))
  1274. );
  1275. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, downsampledSize.x,
  1276. downsampledSize.y, TU_RENDERTARGET);
  1277. setupTex0 = GpuResourcePool::instance().get(desc);
  1278. downsample->execute(inputs.view, sceneDepth, sceneNormals, setupTex0->renderTexture, DEPTH_RANGE);
  1279. }
  1280. SPtr<PooledRenderTexture> setupTex1;
  1281. if(numDownsampleLevels > 1)
  1282. {
  1283. Vector2I downsampledSize(
  1284. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 4)),
  1285. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 4))
  1286. );
  1287. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, downsampledSize.x,
  1288. downsampledSize.y, TU_RENDERTARGET);
  1289. setupTex1 = GpuResourcePool::instance().get(desc);
  1290. downsample->execute(inputs.view, sceneDepth, sceneNormals, setupTex1->renderTexture, DEPTH_RANGE);
  1291. }
  1292. SSAOTextureInputs textures;
  1293. textures.sceneDepth = sceneDepth;
  1294. textures.sceneNormals = sceneNormals;
  1295. textures.randomRotations = RendererTextures::ssaoRandomization4x4;
  1296. SPtr<PooledRenderTexture> downAOTex1;
  1297. if(numDownsampleLevels > 1)
  1298. {
  1299. textures.aoSetup = setupTex1->texture;
  1300. Vector2I downsampledSize(
  1301. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 4)),
  1302. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 4))
  1303. );
  1304. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, downsampledSize.x,
  1305. downsampledSize.y, TU_RENDERTARGET);
  1306. downAOTex1 = GpuResourcePool::instance().get(desc);
  1307. SSAOMat* ssaoMat = SSAOMat::getVariation(false, false, quality);
  1308. ssaoMat->execute(inputs.view, textures, downAOTex1->renderTexture, settings);
  1309. GpuResourcePool::instance().release(setupTex1);
  1310. setupTex1 = nullptr;
  1311. }
  1312. SPtr<PooledRenderTexture> downAOTex0;
  1313. if(numDownsampleLevels > 0)
  1314. {
  1315. textures.aoSetup = setupTex0->texture;
  1316. if(downAOTex1)
  1317. textures.aoDownsampled = downAOTex1->texture;
  1318. Vector2I downsampledSize(
  1319. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.width, 2)),
  1320. std::max(1, Math::divideAndRoundUp((INT32)viewProps.viewRect.height, 2))
  1321. );
  1322. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, downsampledSize.x,
  1323. downsampledSize.y, TU_RENDERTARGET);
  1324. downAOTex0 = GpuResourcePool::instance().get(desc);
  1325. bool upsample = numDownsampleLevels > 1;
  1326. SSAOMat* ssaoMat = SSAOMat::getVariation(upsample, false, quality);
  1327. ssaoMat->execute(inputs.view, textures, downAOTex0->renderTexture, settings);
  1328. if(upsample)
  1329. {
  1330. GpuResourcePool::instance().release(downAOTex1);
  1331. downAOTex1 = nullptr;
  1332. }
  1333. }
  1334. UINT32 width = viewProps.viewRect.width;
  1335. UINT32 height = viewProps.viewRect.height;
  1336. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, width, height, TU_RENDERTARGET));
  1337. {
  1338. if(setupTex0)
  1339. textures.aoSetup = setupTex0->texture;
  1340. if(downAOTex0)
  1341. textures.aoDownsampled = downAOTex0->texture;
  1342. bool upsample = numDownsampleLevels > 0;
  1343. SSAOMat* ssaoMat = SSAOMat::getVariation(upsample, true, quality);
  1344. ssaoMat->execute(inputs.view, textures, output->renderTexture, settings);
  1345. }
  1346. if(resolvedNormals)
  1347. {
  1348. GpuResourcePool::instance().release(resolvedNormals);
  1349. resolvedNormals = nullptr;
  1350. }
  1351. if(numDownsampleLevels > 0)
  1352. {
  1353. GpuResourcePool::instance().release(setupTex0);
  1354. GpuResourcePool::instance().release(downAOTex0);
  1355. }
  1356. // Blur the output
  1357. // Note: If I implement temporal AA then this can probably be avoided. I can instead jitter the sample offsets
  1358. // each frame, and averaging them out should yield blurred AO.
  1359. if(quality > 1) // On level 0 we don't blur at all, on level 1 we use the ad-hoc blur in shader
  1360. {
  1361. const RenderTargetProperties& rtProps = output->renderTexture->getProperties();
  1362. POOLED_RENDER_TEXTURE_DESC desc = POOLED_RENDER_TEXTURE_DESC::create2D(PF_R8, rtProps.getWidth(),
  1363. rtProps.getHeight(), TU_RENDERTARGET);
  1364. SPtr<PooledRenderTexture> blurIntermediateTex = GpuResourcePool::instance().get(desc);
  1365. SSAOBlurMat* blurHorz = SSAOBlurMat::getVariation(true);
  1366. SSAOBlurMat* blurVert = SSAOBlurMat::getVariation(false);
  1367. blurHorz->execute(inputs.view, output->texture, sceneDepth, blurIntermediateTex->renderTexture, DEPTH_RANGE);
  1368. blurVert->execute(inputs.view, blurIntermediateTex->texture, sceneDepth, output->renderTexture, DEPTH_RANGE);
  1369. GpuResourcePool::instance().release(blurIntermediateTex);
  1370. }
  1371. }
  1372. void RCNodeSSAO::clear()
  1373. {
  1374. GpuResourcePool& resPool = GpuResourcePool::instance();
  1375. resPool.release(output);
  1376. }
  1377. SmallVector<StringID, 4> RCNodeSSAO::getDependencies(const RendererView& view)
  1378. {
  1379. return { RCNodeResolvedSceneDepth::getNodeId(), RCNodeGBuffer::getNodeId() };
  1380. }
  1381. RCNodeSSR::~RCNodeSSR()
  1382. {
  1383. deallocOutputs();
  1384. }
  1385. void RCNodeSSR::render(const RenderCompositorNodeInputs& inputs)
  1386. {
  1387. const ScreenSpaceReflectionsSettings& settings = inputs.view.getRenderSettings().screenSpaceReflections;
  1388. if (settings.enabled)
  1389. {
  1390. RenderAPI& rapi = RenderAPI::instance();
  1391. RCNodeSceneDepth* sceneDepthNode = static_cast<RCNodeSceneDepth*>(inputs.inputNodes[0]);
  1392. RCNodeLightAccumulation* lightAccumNode = static_cast<RCNodeLightAccumulation*>(inputs.inputNodes[1]);
  1393. RCNodeGBuffer* gbufferNode = static_cast<RCNodeGBuffer*>(inputs.inputNodes[2]);
  1394. RCNodeHiZ* hiZNode = static_cast<RCNodeHiZ*>(inputs.inputNodes[3]);
  1395. RCNodeResolvedSceneDepth* resolvedSceneDepthNode = static_cast<RCNodeResolvedSceneDepth*>(inputs.inputNodes[4]);
  1396. GpuResourcePool& resPool = GpuResourcePool::instance();
  1397. const RendererViewProperties& viewProps = inputs.view.getProperties();
  1398. UINT32 width = viewProps.viewRect.width;
  1399. UINT32 height = viewProps.viewRect.height;
  1400. SPtr<Texture> hiZ = hiZNode->output->texture;
  1401. // This will be executing before scene color is resolved, so get the light accum buffer instead
  1402. SPtr<Texture> sceneColor = lightAccumNode->lightAccumulationTex->texture;
  1403. // Resolve multiple samples if MSAA is used
  1404. SPtr<PooledRenderTexture> resolvedSceneColor;
  1405. if(viewProps.numSamples > 1)
  1406. {
  1407. resolvedSceneColor = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width, height,
  1408. TU_RENDERTARGET));
  1409. rapi.setRenderTarget(resolvedSceneColor->renderTexture);
  1410. gRendererUtility().blit(sceneColor);
  1411. sceneColor = resolvedSceneColor->texture;
  1412. }
  1413. GBufferTextures gbuffer;
  1414. gbuffer.albedo = gbufferNode->albedoTex->texture;
  1415. gbuffer.normals = gbufferNode->normalTex->texture;
  1416. gbuffer.roughMetal = gbufferNode->roughMetalTex->texture;
  1417. gbuffer.depth = sceneDepthNode->depthTex->texture;
  1418. SSRStencilMat* stencilMat = SSRStencilMat::getVariation(viewProps.numSamples > 1);
  1419. // Note: Making the assumption that the stencil buffer is clear at this point
  1420. rapi.setRenderTarget(resolvedSceneDepthNode->output->renderTexture);
  1421. stencilMat->execute(inputs.view, gbuffer, settings);
  1422. SPtr<PooledRenderTexture> traceOutput = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width,
  1423. height, TU_RENDERTARGET));
  1424. RENDER_TEXTURE_DESC traceRtDesc;
  1425. traceRtDesc.colorSurfaces[0].texture = traceOutput->texture;
  1426. traceRtDesc.depthStencilSurface.texture = resolvedSceneDepthNode->output->texture;
  1427. SPtr<RenderTexture> traceRt = RenderTexture::create(traceRtDesc);
  1428. rapi.setRenderTarget(traceRt);
  1429. rapi.clearRenderTarget(FBT_COLOR);
  1430. SSRTraceMat* traceMat = SSRTraceMat::getVariation(settings.quality, viewProps.numSamples > 1);
  1431. traceMat->execute(inputs.view, gbuffer, sceneColor, hiZ, settings, traceRt);
  1432. if (resolvedSceneColor)
  1433. {
  1434. resPool.release(resolvedSceneColor);
  1435. resolvedSceneColor = nullptr;
  1436. }
  1437. if (mPrevFrame)
  1438. {
  1439. output = resPool.get(POOLED_RENDER_TEXTURE_DESC::create2D(PF_RGBA16F, width, height, TU_RENDERTARGET));
  1440. rapi.setRenderTarget(output->renderTexture);
  1441. rapi.clearRenderTarget(FBT_COLOR);
  1442. SSRResolveMat* resolveMat = SSRResolveMat::getVariation(viewProps.numSamples > 1);
  1443. resolveMat->execute(inputs.view, mPrevFrame->texture, traceOutput->texture, sceneDepthNode->depthTex->texture,
  1444. output->renderTexture);
  1445. resPool.release(traceOutput);
  1446. }
  1447. else
  1448. output = traceOutput;
  1449. RenderAPI::instance().setRenderTarget(nullptr);
  1450. }
  1451. else
  1452. deallocOutputs();
  1453. }
  1454. void RCNodeSSR::clear()
  1455. {
  1456. GpuResourcePool& resPool = GpuResourcePool::instance();
  1457. if(mPrevFrame)
  1458. resPool.release(mPrevFrame);
  1459. mPrevFrame = output;
  1460. output = nullptr;
  1461. }
  1462. void RCNodeSSR::deallocOutputs()
  1463. {
  1464. GpuResourcePool& resPool = GpuResourcePool::instance();
  1465. if(mPrevFrame)
  1466. {
  1467. resPool.release(mPrevFrame);
  1468. mPrevFrame = nullptr;
  1469. }
  1470. }
  1471. SmallVector<StringID, 4> RCNodeSSR::getDependencies(const RendererView& view)
  1472. {
  1473. SmallVector<StringID, 4> deps;
  1474. if (view.getRenderSettings().screenSpaceReflections.enabled)
  1475. {
  1476. deps.push_back(RCNodeSceneDepth::getNodeId());
  1477. deps.push_back(RCNodeLightAccumulation::getNodeId());
  1478. deps.push_back(RCNodeGBuffer::getNodeId());
  1479. deps.push_back(RCNodeHiZ::getNodeId());
  1480. deps.push_back(RCNodeResolvedSceneDepth::getNodeId());
  1481. if (view.getProperties().numSamples > 1)
  1482. deps.push_back(RCNodeUnflattenLightAccum::getNodeId());
  1483. }
  1484. return deps;
  1485. }
  1486. }}