BsRenderCompositor.cpp 63 KB

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