feat: added htrace

This commit is contained in:
Chris
2026-01-02 23:27:08 -05:00
parent dfff4e6f1d
commit 20f1fbb211
203 changed files with 17634 additions and 0 deletions

View File

@@ -0,0 +1,110 @@
//pipelinedefine
#define H_URP
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Data.Public;
using HTraceSSGI.Scripts.Passes.Shared;
using HTraceSSGI.Scripts.Extensions;
using HTraceSSGI.Scripts.Globals;
using HTraceSSGI.Scripts.Infrastructure.URP;
using HTraceSSGI.Scripts.Wrappers;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
#if UNITY_2023_3_OR_NEWER
using UnityEngine.Rendering.RenderGraphModule;
#endif
namespace HTraceSSGI.Scripts.Passes.URP
{
internal class FinalPassURP : ScriptableRenderPass
{
private ScriptableRenderer _renderer;
#region --------------------------- Non Render Graph ---------------------------
protected internal void Initialize(ScriptableRenderer renderer)
{
_renderer = renderer;
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
{
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
{
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
var cmd = CommandBufferPool.Get(HNames.HTRACE_FINAL_PASS_NAME);
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
if (profile.GeneralSettings.DebugMode != DebugMode.None && profile.GeneralSettings.DebugMode != DebugMode.DirectLighting)
{
Blitter.BlitCameraTexture(cmd, SSGI.DebugOutput.rt, _renderer.cameraColorTargetHandle);
}
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
CommandBufferPool.Release(cmd);
}
#endregion --------------------------- Non Render Graph ---------------------------
#region --------------------------- Render Graph ---------------------------
#if UNITY_2023_3_OR_NEWER
private class PassData
{
public TextureHandle ColorTexture;
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
using (var builder = renderGraph.AddUnsafePass<PassData>(HNames.HTRACE_FINAL_PASS_NAME, out var passData, new ProfilingSampler(HNames.HTRACE_FINAL_PASS_NAME)))
{
UniversalResourceData resourceData = frameData.Get<UniversalResourceData>();
UniversalRenderingData universalRenderingData = frameData.Get<UniversalRenderingData>();
builder.AllowGlobalStateModification(true);
builder.AllowPassCulling(false);
passData.ColorTexture = universalRenderingData.renderingMode == RenderingMode.Deferred ? resourceData.activeColorTexture : resourceData.cameraColor;
builder.SetRenderFunc((PassData data, UnsafeGraphContext context) => ExecutePass(data, context));
}
}
private static void ExecutePass(PassData data, UnsafeGraphContext rgContext)
{
var cmd = CommandBufferHelpers.GetNativeCommandBuffer(rgContext.cmd);
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
if (profile.GeneralSettings.DebugMode != DebugMode.None && profile.GeneralSettings.DebugMode != DebugMode.DirectLighting)
{
Blitter.BlitCameraTexture(cmd, SSGI.DebugOutput.rt, data.ColorTexture);
}
}
#endif
#endregion --------------------------- Render Graph ---------------------------
#region --------------------------- Shared ---------------------------
protected internal void Dispose()
{
}
#endregion --------------------------- Shared ---------------------------
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 38d0808db5cb55c4b820dedf6eaec8aa
timeCreated: 1729952288
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Passes/URP/FinalPassURP.cs
uploadId: 840002

View File

@@ -0,0 +1,498 @@
//pipelinedefine
#define H_URP
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Data.Public;
using HTraceSSGI.Scripts.Extensions;
using HTraceSSGI.Scripts.Globals;
using HTraceSSGI.Scripts.Infrastructure.URP;
using HTraceSSGI.Scripts.Wrappers;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RendererUtils;
using UnityEngine.Rendering.Universal;
#if UNITY_2023_3_OR_NEWER
using UnityEngine.Rendering.RenderGraphModule;
#endif
namespace HTraceSSGI.Scripts.Passes.URP
{
internal class GBufferPassURP : ScriptableRenderPass
{
// Texture Names
private const string _Dummy = "_Dummy";
private const string _DepthPyramid = "_DepthPyramid";
private const string _ForwardGBuffer0 = "_ForwardGBuffer0";
private const string _ForwardGBuffer1 = "_ForwardGBuffer1";
private const string _ForwardGBuffer2 = "_ForwardGBuffer2";
private const string _ForwardGBuffer3 = "_ForwardGBuffer3";
private const string _ForwardRenderLayerMask = "_ForwardRenderLayerMask";
private const string _ForwardGBufferDepth = "_ForwardGBufferDepth";
// Materials & Computes
internal static ComputeShader HDepthPyramid = null;
// Samplers
internal static readonly ProfilingSampler GBufferProfilingSampler = new("GBuffer");
private static readonly ProfilingSampler DepthPyramidGenerationProfilingSampler = new ProfilingSampler("Depth Pyramid Generation");
// Textures
internal static RTWrapper Dummy = new RTWrapper();
internal static RTWrapper ForwardGBuffer0 = new RTWrapper();
internal static RTWrapper ForwardGBuffer1 = new RTWrapper();
internal static RTWrapper ForwardGBuffer2 = new RTWrapper();
internal static RTWrapper ForwardGBuffer3 = new RTWrapper();
internal static RTWrapper ForwardRenderLayerMask = new RTWrapper();
internal static RTWrapper ForwardGBufferDepth = new RTWrapper();
internal static RTWrapper DepthPyramidRT = new RTWrapper();
// MRT Arrays
internal static RenderTargetIdentifier[] GBufferMRT = null;
// Misc
internal static RenderStateBlock ForwardGBufferRenderStateBlock = new RenderStateBlock(RenderStateMask.Nothing);
#region --------------------------- Non Render Graph ---------------------------
private ScriptableRenderer _renderer;
protected internal void Initialize(ScriptableRenderer renderer)
{
_renderer = renderer;
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
{
Setup(renderingData.cameraData.camera, renderingData.cameraData.renderScale, renderingData.cameraData.cameraTargetDescriptor);
}
private static void Setup(Camera camera, float renderScale, RenderTextureDescriptor desc)
{
if (HDepthPyramid == null) HDepthPyramid = HExtensions.LoadComputeShader("HDepthPyramid");
int width = (int)(camera.scaledPixelWidth * renderScale);
int height = (int)(camera.scaledPixelHeight * renderScale);
if (desc.width != width || desc.height != height)
desc = new RenderTextureDescriptor(width, height);
desc.depthBufferBits = 0; // Color and depth cannot be combined in RTHandles
desc.stencilFormat = GraphicsFormat.None;
desc.depthStencilFormat = GraphicsFormat.None;
desc.msaaSamples = 1;
desc.bindMS = false;
var graphicsFormatRenderingLayerMask = GraphicsFormat.R8G8B8A8_UNorm;
#if UNITY_6000_2_OR_NEWER
graphicsFormatRenderingLayerMask = GraphicsFormat.R8G8_UInt;
#endif
ForwardGBuffer0.ReAllocateIfNeeded(_ForwardGBuffer0, ref desc, graphicsFormat: GraphicsFormat.R8G8B8A8_SRGB);
ForwardGBuffer1.ReAllocateIfNeeded(_ForwardGBuffer1, ref desc, graphicsFormat: GraphicsFormat.R8G8B8A8_UNorm);
ForwardGBuffer2.ReAllocateIfNeeded(_ForwardGBuffer2, ref desc, graphicsFormat: GraphicsFormat.R8G8B8A8_SNorm);
ForwardGBuffer3.ReAllocateIfNeeded(_ForwardGBuffer3, ref desc, graphicsFormat: GraphicsFormat.B10G11R11_UFloatPack32);
ForwardRenderLayerMask.ReAllocateIfNeeded(_ForwardRenderLayerMask, ref desc, graphicsFormat: graphicsFormatRenderingLayerMask);
DepthPyramidRT.ReAllocateIfNeeded(_DepthPyramid, ref desc, graphicsFormat: GraphicsFormat.R16_SFloat, useMipMap: true);
RenderTextureDescriptor depthDesc = desc;
depthDesc.depthBufferBits = 32;
depthDesc.depthStencilFormat = GraphicsFormat.None;
ForwardGBufferDepth.ReAllocateIfNeeded(_ForwardGBufferDepth, ref depthDesc, graphicsFormat: GraphicsFormat.R16_SFloat, useMipMap: false, enableRandomWrite: false);
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
{
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
Camera camera = renderingData.cameraData.camera;
var cmd = CommandBufferPool.Get(HNames.HTRACE_GBUFFER_PASS_NAME);
int width = (int)(camera.scaledPixelWidth * renderingData.cameraData.renderScale);
int height = (int)(camera.scaledPixelHeight * renderingData.cameraData.renderScale);
var nativeGBuffer0 = Shader.GetGlobalTexture(HShaderParams._GBuffer0);
var nativeGBuffer1 = Shader.GetGlobalTexture(HShaderParams._GBuffer1);
var nativeGBuffer2 = Shader.GetGlobalTexture(HShaderParams._GBuffer2);
var renderLayerMaskTexture = Shader.GetGlobalTexture(HShaderParams._CameraRenderingLayersTexture);
var screenSpaceOcclusionTexture = Shader.GetGlobalTexture(HShaderParams.g_ScreenSpaceOcclusionTexture);
// Set Depth, Color and SSAO to HTrace passes
cmd.SetGlobalTexture(HShaderParams.g_HTraceColor, _renderer.cameraColorTargetHandle);
cmd.SetGlobalTexture(HShaderParams.g_HTraceDepth, _renderer.cameraDepthTargetHandle);
cmd.SetGlobalTexture(HShaderParams.g_HTraceSSAO, screenSpaceOcclusionTexture == null ? Texture2D.whiteTexture : screenSpaceOcclusionTexture);
GBufferGenerationNonRenderGraph(cmd, width, height, nativeGBuffer0, nativeGBuffer1, nativeGBuffer2, renderLayerMaskTexture, _renderer.cameraColorTargetHandle, _renderer.cameraDepthTargetHandle, ref context, ref renderingData);
GenerateDepthPyramidShared(cmd, width, height, DepthPyramidRT.rt);
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
CommandBufferPool.Release(cmd);
}
private static void GBufferGenerationNonRenderGraph(CommandBuffer cmd, int width, int height, Texture nativeGBuffer0, Texture nativeGBuffer1,
Texture nativeGBuffer2, Texture renderLayerMask, RTHandle cameraColorBuffer, RTHandle cameraDepthBuffer,
ref ScriptableRenderContext context, ref RenderingData renderingData)
{
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
var camera = renderingData.cameraData.camera;
using (new ProfilingScope(cmd, GBufferProfilingSampler))
{
// Set sky probe management
SphericalHarmonicsL2 ambientProbe = RenderSettings.ambientProbe;
cmd.SetGlobalVector(HShaderParams.H_SHAr, new Vector4(ambientProbe[0, 3], ambientProbe[0, 1], ambientProbe[0, 2], ambientProbe[0, 0] - ambientProbe[0, 6]));
cmd.SetGlobalVector(HShaderParams.H_SHAg, new Vector4(ambientProbe[1, 3], ambientProbe[1, 1], ambientProbe[1, 2], ambientProbe[1, 0] - ambientProbe[1, 6]));
cmd.SetGlobalVector(HShaderParams.H_SHAb, new Vector4(ambientProbe[2, 3], ambientProbe[2, 1], ambientProbe[2, 2], ambientProbe[2, 0] - ambientProbe[2, 6]));
cmd.SetGlobalVector(HShaderParams.H_SHBr, new Vector4(ambientProbe[0, 4], ambientProbe[0, 5], ambientProbe[0, 6] * 3, ambientProbe[0, 7]));
cmd.SetGlobalVector(HShaderParams.H_SHBg, new Vector4(ambientProbe[1, 4], ambientProbe[1, 5], ambientProbe[1, 6] * 3, ambientProbe[1, 7]));
cmd.SetGlobalVector(HShaderParams.H_SHBb, new Vector4(ambientProbe[2, 4], ambientProbe[2, 5], ambientProbe[2, 6] * 3, ambientProbe[2, 7]));
cmd.SetGlobalVector(HShaderParams.H_SHC, new Vector4(ambientProbe[0, 8], ambientProbe[1, 8], ambientProbe[2, 8], 1));
// Check if GBuffer is valid (e.g. Forward / wrong scale / is not set, etc.)
bool RequestForwardGBufferRender = false;
if (nativeGBuffer0 == null || nativeGBuffer1 == null || nativeGBuffer2 == null)
{ RequestForwardGBufferRender = true; }
else if ( nativeGBuffer0.width != width || nativeGBuffer0.height != height) // CameraDepthBuffer.rtHandleProperties.currentViewportSize.x
{ RequestForwardGBufferRender = true; }
// Set Render Layer Mask to black dummy in case it's disabled as a feature and we can't render it
if (renderLayerMask == null)
renderLayerMask = Texture2D.blackTexture;// Dummy.rt;
// RequestForwardGBufferRender = true;
// GBuffer can't be rendered because its resolution doesn't match the resolution of Unity's depth buffer. Happens when switching between Scene and Game windows
if (ForwardGBuffer0.rt.rt.width != cameraDepthBuffer.rt.width || ForwardGBuffer0.rt.rt.height != cameraDepthBuffer.rt.height)
{
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer0, ForwardGBuffer0.rt);
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer1, ForwardGBuffer1.rt);
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer2, ForwardGBuffer2.rt);
cmd.SetGlobalTexture(HShaderParams.g_HTraceRenderLayerMask, ForwardRenderLayerMask.rt);
return;
}
// Set GBuffer to HTrace passes if valid or render it otherwise
if (RequestForwardGBufferRender == false)
{
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer0, nativeGBuffer0);
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer1, nativeGBuffer1);
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer2, nativeGBuffer2);
cmd.SetGlobalTexture(HShaderParams.g_HTraceRenderLayerMask, renderLayerMask);
}
else
{
if (HRendererURP.RenderGraphEnabled)
GBufferMRT = new RenderTargetIdentifier[] { ForwardGBuffer0.rt, ForwardGBuffer1.rt, ForwardGBuffer2.rt, ForwardGBuffer3.rt, ForwardGBufferDepth.rt, ForwardRenderLayerMask.rt };
else
GBufferMRT = new RenderTargetIdentifier[] { ForwardGBuffer0.rt, ForwardGBuffer1.rt, ForwardGBuffer2.rt, ForwardGBuffer3.rt, ForwardRenderLayerMask.rt };
// If CameraDepthBuffer.rt doesn't work for any reason - we can replace it with our ForwardGBufferDepth.rt, but GBuffer rendering performance will suffer.
CoreUtils.SetRenderTarget(cmd, GBufferMRT, cameraDepthBuffer.rt);
CullingResults cullingResults = renderingData.cullResults;
int layerMask = camera.cullingMask;
ForwardGBufferRenderStateBlock.depthState = new DepthState(false, CompareFunction.LessEqual);
ForwardGBufferRenderStateBlock.mask |= RenderStateMask.Depth;
var renderList = new UnityEngine.Rendering.RendererUtils.RendererListDesc(HShaderParams.UniversalGBufferTag, cullingResults, camera)
{
rendererConfiguration = PerObjectData.None,
renderQueueRange = RenderQueueRange.opaque,
sortingCriteria = SortingCriteria.OptimizeStateChanges,
layerMask = layerMask,
stateBlock = ForwardGBufferRenderStateBlock,
};
// Cache the current keyword state set by Unity
bool RenderLayerKeywordState = Shader.IsKeywordEnabled(HShaderParams._WRITE_RENDERING_LAYERS);
// If we don't need render layers we do not touch the keyword at all
#if UNITY_2023_3_OR_NEWER
if (profile.GeneralSettings.ExcludeReceivingMask != 0 || profile.GeneralSettings.ExcludeCastingMask != 0)
CoreUtils.SetKeyword(cmd, HShaderParams._WRITE_RENDERING_LAYERS, true);
#endif
CoreUtils.DrawRendererList(context, cmd, context.CreateRendererList(renderList));
// If we altered the keyword, we restore it to the original state
#if UNITY_2023_3_OR_NEWER
if (profile.GeneralSettings.ExcludeReceivingMask != 0 || profile.GeneralSettings.ExcludeCastingMask != 0)
CoreUtils.SetKeyword(cmd, HShaderParams._WRITE_RENDERING_LAYERS, RenderLayerKeywordState);
#endif
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer0, ForwardGBuffer0.rt);
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer1, ForwardGBuffer1.rt);
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer2, ForwardGBuffer2.rt);
cmd.SetGlobalTexture(HShaderParams.g_HTraceRenderLayerMask, ForwardRenderLayerMask.rt);
}
}
}
#endregion --------------------------- Non Render Graph ---------------------------
#region --------------------------- Render Graph ---------------------------
#if UNITY_2023_3_OR_NEWER
private class PassData
{
public TextureHandle[] GBufferTextures;
public TextureHandle SSAOTexture;
public TextureHandle ColorTexture;
public TextureHandle DepthTexture;
public TextureHandle NormalsTexture;
public RendererListHandle ForwardGBufferRendererListHandle;
public UniversalCameraData UniversalCameraData;
public TextureHandle ForwardGBuffer0Texture;
public TextureHandle ForwardGBuffer1Texture;
public TextureHandle ForwardGBuffer2Texture;
public TextureHandle ForwardGBuffer3Texture;
public TextureHandle ForwardRenderLayerMaskTexture;
public TextureHandle DepthPyramidTexture;
public TextureHandle DepthPyramidIntermediateTexture;
public TextureHandle ForwardGBufferDepthTexture;
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
using (var builder = renderGraph.AddUnsafePass<PassData>(HNames.HTRACE_GBUFFER_PASS_NAME, out var passData, new ProfilingSampler(HNames.HTRACE_GBUFFER_PASS_NAME)))
{
UniversalResourceData resourceData = frameData.Get<UniversalResourceData>();
UniversalCameraData universalCameraData = frameData.Get<UniversalCameraData>();
UniversalRenderingData universalRenderingData = frameData.Get<UniversalRenderingData>();
UniversalLightData lightData = frameData.Get<UniversalLightData>();
builder.AllowGlobalStateModification(true);
builder.AllowPassCulling(false);
TextureHandle colorTexture = universalRenderingData.renderingMode == RenderingMode.Deferred ? resourceData.activeColorTexture : resourceData.cameraColor;
TextureHandle depthTexture = universalRenderingData.renderingMode == RenderingMode.Deferred ? resourceData.activeDepthTexture : resourceData.cameraDepth;
TextureHandle normalsTexture = resourceData.cameraNormalsTexture;
builder.UseTexture(depthTexture, AccessFlags.Read);
builder.UseTexture(normalsTexture, AccessFlags.Read);
passData.NormalsTexture = resourceData.cameraNormalsTexture;
passData.ColorTexture = colorTexture;
passData.DepthTexture = depthTexture;
passData.UniversalCameraData = universalCameraData;
passData.GBufferTextures = resourceData.gBuffer;
passData.SSAOTexture = resourceData.ssaoTexture;
if (HDepthPyramid == null) HDepthPyramid = HExtensions.LoadComputeShader("HDepthPyramid");
TextureHandle colorTextureHandle = resourceData.cameraColor;
TextureDesc desc = colorTextureHandle.GetDescriptor(renderGraph);
desc.clearBuffer = false;
TextureHandle depthTextureHandle = resourceData.cameraDepthTexture;
TextureDesc descDepth = depthTextureHandle.GetDescriptor(renderGraph);
descDepth.clearBuffer = false;
var graphicsFormatRenderingLayerMask = GraphicsFormat.R8G8B8A8_UNorm;
#if UNITY_6000_2_OR_NEWER
graphicsFormatRenderingLayerMask = GraphicsFormat.R8G8_UInt;
#endif
passData.ForwardGBuffer0Texture = ExtensionsURP.CreateTexture(_ForwardGBuffer0, renderGraph, ref desc, format: GraphicsFormat.R8G8B8A8_SRGB);
builder.UseTexture(passData.ForwardGBuffer0Texture, AccessFlags.Write);
passData.ForwardGBuffer1Texture = ExtensionsURP.CreateTexture(_ForwardGBuffer1, renderGraph, ref desc, format: GraphicsFormat.R8G8B8A8_UNorm);
builder.UseTexture(passData.ForwardGBuffer1Texture, AccessFlags.Write);
passData.ForwardGBuffer2Texture = ExtensionsURP.CreateTexture(_ForwardGBuffer2, renderGraph, ref desc, format: GraphicsFormat.R8G8B8A8_SNorm);
builder.UseTexture(passData.ForwardGBuffer2Texture, AccessFlags.Write);
passData.ForwardGBuffer3Texture = ExtensionsURP.CreateTexture(_ForwardGBuffer3, renderGraph, ref desc, format: GraphicsFormat.B10G11R11_UFloatPack32);
builder.UseTexture(passData.ForwardGBuffer3Texture, AccessFlags.Write);
passData.ForwardRenderLayerMaskTexture = ExtensionsURP.CreateTexture(_ForwardRenderLayerMask, renderGraph, ref desc, format: graphicsFormatRenderingLayerMask);
builder.UseTexture(passData.ForwardRenderLayerMaskTexture, AccessFlags.Write);
passData.DepthPyramidTexture = ExtensionsURP.CreateTexture(_DepthPyramid, renderGraph, ref desc, format: GraphicsFormat.R16_SFloat, useMipMap: true);
builder.UseTexture(passData.DepthPyramidTexture, AccessFlags.Write);
desc.width /= 16;
desc.height /= 16;
passData.ForwardGBufferDepthTexture = ExtensionsURP.CreateTexture(_ForwardGBufferDepth, renderGraph, ref descDepth, format: GraphicsFormat.R16_SFloat, useMipMap: false, enableRandomWrite: false);
builder.UseTexture(passData.ForwardGBufferDepthTexture, AccessFlags.Write);
if (universalRenderingData.renderingMode == RenderingMode.Deferred
#if UNITY_6000_1_OR_NEWER
|| universalRenderingData.renderingMode == RenderingMode.DeferredPlus
#endif
)
{
if (resourceData.ssaoTexture.IsValid())
builder.UseTexture(resourceData.ssaoTexture, AccessFlags.Read);
builder.UseTexture(resourceData.gBuffer[0], AccessFlags.Read);
builder.UseTexture(resourceData.gBuffer[1], AccessFlags.Read);
builder.UseTexture(resourceData.gBuffer[2], AccessFlags.Read);
builder.UseTexture(resourceData.gBuffer[3], AccessFlags.Read);
if (resourceData.gBuffer.Length >= 6 && resourceData.gBuffer[5].IsValid())
builder.UseTexture(resourceData.gBuffer[5], AccessFlags.Read);
}
CullingResults cullingResults = universalRenderingData.cullResults;
ShaderTagId tags = new ShaderTagId("UniversalGBuffer");
int layerMask = universalCameraData.camera.cullingMask;
ForwardGBufferRenderStateBlock.depthState = new DepthState(false, CompareFunction.LessEqual);
ForwardGBufferRenderStateBlock.mask |= RenderStateMask.Depth;
RendererListDesc rendererListDesc = new RendererListDesc(tags, cullingResults, universalCameraData.camera)
{
rendererConfiguration = PerObjectData.None,
renderQueueRange = RenderQueueRange.opaque,
sortingCriteria = SortingCriteria.OptimizeStateChanges,
layerMask = layerMask,
stateBlock = ForwardGBufferRenderStateBlock,
};
passData.ForwardGBufferRendererListHandle = renderGraph.CreateRendererList(rendererListDesc);
builder.UseRendererList(passData.ForwardGBufferRendererListHandle);
builder.SetRenderFunc((PassData data, UnsafeGraphContext context) => ExecutePass(data, context));
}
}
private static void ExecutePass(PassData data, UnsafeGraphContext rgContext)
{
var cmd = CommandBufferHelpers.GetNativeCommandBuffer(rgContext.cmd);
int width = (int)(data.UniversalCameraData.camera.scaledPixelWidth * data.UniversalCameraData.renderScale);
int height = (int)(data.UniversalCameraData.camera.scaledPixelHeight * data.UniversalCameraData.renderScale);
// Set Depth, Color and SSAO to HTrace passes
cmd.SetGlobalTexture(HShaderParams.g_HTraceDepth, data.DepthTexture);
cmd.SetGlobalTexture(HShaderParams.g_HTraceColor, data.ColorTexture);
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer2, data.NormalsTexture);
cmd.SetGlobalTexture(HShaderParams.g_HTraceSSAO, data.SSAOTexture.IsValid() ? data.SSAOTexture : Texture2D.whiteTexture);
var nativeGBuffer0 = data.GBufferTextures[0];
var nativeGBuffer1 = data.GBufferTextures[1];
var nativeGBuffer2 = data.GBufferTextures[2];
Texture renderLayerMaskTexture = data.GBufferTextures.Length >= 6 ? data.GBufferTextures[5] : null;
GBufferGenerationRenderGraph(cmd, data, width, height, nativeGBuffer0, nativeGBuffer1, nativeGBuffer2, renderLayerMaskTexture);
GenerateDepthPyramidShared(cmd, width, height, data.DepthPyramidTexture);
}
private static void GBufferGenerationRenderGraph(CommandBuffer cmd, PassData data, int width, int height, Texture nativeGBuffer0, Texture nativeGBuffer1,
Texture nativeGBuffer2, Texture renderLayerMask)
{
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
using (new ProfilingScope(cmd, GBufferProfilingSampler))
{
// Sky probe management
SphericalHarmonicsL2 ambientProbe = RenderSettings.ambientProbe;
cmd.SetGlobalVector(HShaderParams.H_SHAr, new Vector4(ambientProbe[0, 3], ambientProbe[0, 1], ambientProbe[0, 2], ambientProbe[0, 0] - ambientProbe[0, 6]));
cmd.SetGlobalVector(HShaderParams.H_SHAg, new Vector4(ambientProbe[1, 3], ambientProbe[1, 1], ambientProbe[1, 2], ambientProbe[1, 0] - ambientProbe[1, 6]));
cmd.SetGlobalVector(HShaderParams.H_SHAb, new Vector4(ambientProbe[2, 3], ambientProbe[2, 1], ambientProbe[2, 2], ambientProbe[2, 0] - ambientProbe[2, 6]));
cmd.SetGlobalVector(HShaderParams.H_SHBr, new Vector4(ambientProbe[0, 4], ambientProbe[0, 5], ambientProbe[0, 6] * 3, ambientProbe[0, 7]));
cmd.SetGlobalVector(HShaderParams.H_SHBg, new Vector4(ambientProbe[1, 4], ambientProbe[1, 5], ambientProbe[1, 6] * 3, ambientProbe[1, 7]));
cmd.SetGlobalVector(HShaderParams.H_SHBb, new Vector4(ambientProbe[2, 4], ambientProbe[2, 5], ambientProbe[2, 6] * 3, ambientProbe[2, 7]));
cmd.SetGlobalVector(HShaderParams.H_SHC, new Vector4(ambientProbe[0, 8], ambientProbe[1, 8], ambientProbe[2, 8], 1));
// Check if GBuffer is valid (e.g. Forward / wrong scale / is not set, etc.)
bool requestForwardGBufferRender = false;
if (nativeGBuffer0 == null || nativeGBuffer1 == null || nativeGBuffer2 == null)
{ requestForwardGBufferRender = true; }
else if ( nativeGBuffer0.width != width || nativeGBuffer0.height != height) // CameraDepthBuffer.rtHandleProperties.currentViewportSize.x
{ requestForwardGBufferRender = true; }
// Set Render Layer Mask to black dummy in case it's disabled as a feature and we can't render it
if (renderLayerMask == null)
renderLayerMask = Texture2D.blackTexture; // HRenderer.EmptyTexture;
// RequestForwardGBufferRender = true;
// Set GBuffer to HTrace passes if valid or render it otherwise
if (requestForwardGBufferRender == false)
{
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer0, nativeGBuffer0);
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer1, nativeGBuffer1);
// cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer2, nativeGBuffer2);
cmd.SetGlobalTexture(HShaderParams.g_HTraceRenderLayerMask, renderLayerMask);
}
else
{
if (HRendererURP.RenderGraphEnabled)
GBufferMRT = new RenderTargetIdentifier[] { data.ForwardGBuffer0Texture, data.ForwardGBuffer1Texture, data.ForwardGBuffer2Texture, data.ForwardGBuffer3Texture, data.ForwardGBufferDepthTexture, data.ForwardRenderLayerMaskTexture };
else
GBufferMRT = new RenderTargetIdentifier[] { data.ForwardGBuffer0Texture, data.ForwardGBuffer1Texture, data.ForwardGBuffer2Texture, data.ForwardGBuffer3Texture, data.ForwardRenderLayerMaskTexture };
// If CameraDepthBuffer.rt doesn't work for any reason - we can replace it with our ForwardGBufferDepth.rt, but GBuffer rendering performance will suffer.
CoreUtils.SetRenderTarget(cmd, GBufferMRT, data.DepthTexture, ClearFlag.None);
// Cache the current keyword state set by Unity
bool RenderLayerKeywordState = Shader.IsKeywordEnabled(HShaderParams._WRITE_RENDERING_LAYERS);
// If we don't need render layers we do not touch the keyword at all
#if UNITY_2023_3_OR_NEWER
if (profile.GeneralSettings.ExcludeReceivingMask != 0 || profile.GeneralSettings.ExcludeCastingMask != 0)
CoreUtils.SetKeyword(cmd, HShaderParams._WRITE_RENDERING_LAYERS, true);
#endif
cmd.DrawRendererList(data.ForwardGBufferRendererListHandle);
// If we altered the keyword, we restore it to the original state
#if UNITY_2023_3_OR_NEWER
if (profile.GeneralSettings.ExcludeReceivingMask != 0 || profile.GeneralSettings.ExcludeCastingMask != 0)
CoreUtils.SetKeyword(cmd, HShaderParams._WRITE_RENDERING_LAYERS, RenderLayerKeywordState);
#endif
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer0, data.ForwardGBuffer0Texture);
cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer1, data.ForwardGBuffer1Texture);
// cmd.SetGlobalTexture(HShaderParams.g_HTraceGBuffer2, data.ForwardGBuffer2Texture);
cmd.SetGlobalTexture(HShaderParams.g_HTraceRenderLayerMask, data.ForwardRenderLayerMaskTexture);
}
}
}
#endif
#endregion --------------------------- Render Graph ---------------------------
#region --------------------------- Shared ---------------------------
private static void GenerateDepthPyramidShared(CommandBuffer cmd, int width, int height, RTHandle depthPyramidTexture)
{
using (new ProfilingScope(cmd, DepthPyramidGenerationProfilingSampler))
{
int generate_depth_pyramid_kernel = HDepthPyramid.FindKernel("GenerateDepthPyramid");
cmd.SetComputeTextureParam(HDepthPyramid, generate_depth_pyramid_kernel, HShaderParams._DepthPyramid_OutputMIP0, depthPyramidTexture, 0);
cmd.SetComputeTextureParam(HDepthPyramid, generate_depth_pyramid_kernel, HShaderParams._DepthPyramid_OutputMIP1, depthPyramidTexture, 1);
cmd.SetComputeTextureParam(HDepthPyramid, generate_depth_pyramid_kernel, HShaderParams._DepthPyramid_OutputMIP2, depthPyramidTexture, 2);
cmd.SetComputeTextureParam(HDepthPyramid, generate_depth_pyramid_kernel, HShaderParams._DepthPyramid_OutputMIP3, depthPyramidTexture, 3);
cmd.SetComputeTextureParam(HDepthPyramid, generate_depth_pyramid_kernel, HShaderParams._DepthPyramid_OutputMIP4, depthPyramidTexture, 4);
cmd.DispatchCompute(HDepthPyramid, generate_depth_pyramid_kernel, Mathf.CeilToInt(width / 16.0f), Mathf.CeilToInt(height / 16.0f), HRenderer.TextureXrSlices);
cmd.SetGlobalTexture(HShaderParams.g_HTraceDepthPyramidSSGI, depthPyramidTexture);
}
}
protected internal void Dispose()
{
Dummy?.HRelease();
ForwardGBuffer0?.HRelease();
ForwardGBuffer1?.HRelease();
ForwardGBuffer2?.HRelease();
ForwardGBuffer3?.HRelease();
ForwardRenderLayerMask?.HRelease();
ForwardGBufferDepth?.HRelease();
DepthPyramidRT?.HRelease();
}
#endregion --------------------------- Shared ---------------------------
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: fd63347b53844f7fa3fdc1ef13ff65ba
timeCreated: 1757347187
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Passes/URP/GBufferPassURP.cs
uploadId: 840002

View File

@@ -0,0 +1,345 @@
//pipelinedefine
#define H_URP
using System;
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Extensions;
using HTraceSSGI.Scripts.Globals;
using HTraceSSGI.Scripts.Wrappers;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
#if UNITY_2023_3_OR_NEWER
using UnityEngine.Rendering.RenderGraphModule;
#else
using UnityEngine.Experimental.Rendering.RenderGraphModule;
#endif
namespace HTraceSSGI.Scripts.Passes.URP
{
internal class MotionVectorsURP : ScriptableRenderPass
{
// Texture Names
const string _ObjectMotionVectorsColorURP = "_ObjectMotionVectorsColorURP";
const string _ObjectMotionVectorsDepthURP = "_ObjectMotionVectorsDepthURP";
const string _CustomCameraMotionVectorsURP_0 = "_CustomCameraMotionVectorsURP_0";
const string _CustomCameraMotionVectorsURP_1 = "_CustomCameraMotionVectorsURP_1";
const string _MotionVectorsTagID = "MotionVectors";
// Shader Properties
private static readonly int _ObjectMotionVectorsColor = Shader.PropertyToID("_ObjectMotionVectors");
private static readonly int _ObjectMotionVectorsDepth = Shader.PropertyToID("_ObjectMotionVectorsDepth");
private static readonly int _BiasOffset = Shader.PropertyToID("_BiasOffset");
// Textures
internal static RTWrapper[] CustomCameraMotionVectorsURP = new RTWrapper[2] {new RTWrapper(), new RTWrapper()};
internal static RTWrapper ObjectMotionVectorsColorURP = new RTWrapper();
internal static RTWrapper ObjectMotionVectorsDepthURP = new RTWrapper();
// Materials
private static Material MotionVectorsMaterial_URP;
private static ProfilingSampler ObjectMVProfilingSampler = new ProfilingSampler(HNames.HTRACE_OBJECTS_MV_PASS_NAME);
private static ProfilingSampler MVProfilingSampler = new ProfilingSampler(HNames.HTRACE_CAMERA_MV_PASS_NAME);
#region --------------------------- Non Render Graph ---------------------------
private ScriptableRenderer _renderer;
private static int _historyCameraIndex;
protected internal void Initialize(ScriptableRenderer renderer)
{
_renderer = renderer;
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
{
Setup(renderingData.cameraData.camera, renderingData.cameraData.renderScale, renderingData.cameraData.cameraTargetDescriptor);
}
private static void Setup(Camera camera, float renderScale, RenderTextureDescriptor desc)
{
if (MotionVectorsMaterial_URP == null) MotionVectorsMaterial_URP = new Material(Shader.Find($"Hidden/{HNames.ASSET_NAME}/MotionVectorsURP"));
int width = (int)(camera.scaledPixelWidth * renderScale);
int height = (int)(camera.scaledPixelHeight * renderScale);
if (desc.width != width || desc.height != height)
desc = new RenderTextureDescriptor(width, height);
desc.depthBufferBits = 0; // Color and depth cannot be combined in RTHandles
desc.stencilFormat = GraphicsFormat.None;
desc.depthStencilFormat = GraphicsFormat.None;
desc.msaaSamples = 1;
desc.bindMS = false;
desc.enableRandomWrite = true;
RenderTextureDescriptor depthDesc = desc;
depthDesc.depthBufferBits = 32;
depthDesc.enableRandomWrite = false;
depthDesc.colorFormat = RenderTextureFormat.Depth;
CustomCameraMotionVectorsURP[0].ReAllocateIfNeeded(_CustomCameraMotionVectorsURP_0, ref desc, graphicsFormat: GraphicsFormat.R16G16_SFloat);
CustomCameraMotionVectorsURP[1].ReAllocateIfNeeded(_CustomCameraMotionVectorsURP_1, ref desc, graphicsFormat: GraphicsFormat.R8_SNorm);
ObjectMotionVectorsColorURP.ReAllocateIfNeeded(_ObjectMotionVectorsColorURP, ref desc, graphicsFormat: GraphicsFormat.R16G16_SFloat);
ObjectMotionVectorsDepthURP.ReAllocateIfNeeded(_ObjectMotionVectorsDepthURP, ref depthDesc, enableRandomWrite: false);
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
{
ConfigureInput(ScriptableRenderPassInput.Motion | ScriptableRenderPassInput.Depth);
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
var cmd = CommandBufferPool.Get(HNames.HTRACE_MV_PASS_NAME);
Camera camera = renderingData.cameraData.camera;
RenderMotionVectorsNonRenderGraph(cmd, camera, ref renderingData, ref context);
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
CommandBufferPool.Release(cmd);
}
private void RenderMotionVectorsNonRenderGraph(CommandBuffer cmd, Camera camera, ref RenderingData renderingData, ref ScriptableRenderContext context)
{
void RenderObjectsMotionVectors(ref RenderingData renderingData, ref ScriptableRenderContext context)
{
#if UNITY_2023_3_OR_NEWER
if (camera.cameraType == CameraType.SceneView)
return;
#endif
CoreUtils.SetRenderTarget(cmd, ObjectMotionVectorsColorURP.rt, ClearFlag.All, Color.clear);
CoreUtils.SetRenderTarget(cmd, ObjectMotionVectorsDepthURP.rt, ClearFlag.All, Color.clear);
#if UNITY_2023_1_OR_NEWER
// We'll write not only to our own Color, but also to our own Depth target to use it later (in Camera MV) to compose per-object mv
CoreUtils.SetRenderTarget(cmd, ObjectMotionVectorsColorURP.rt, ObjectMotionVectorsDepthURP.rt);
#else
// Prior to 2023 camera motion vectors are rendered directly on objects, so we write to both motion mask and motion vectors via MRT
RenderTargetIdentifier[] motionVectorsMRT = { CustomCameraMotionVectorsURP[0].rt, CustomCameraMotionVectorsURP[1].rt,};
CoreUtils.SetRenderTarget(cmd, motionVectorsMRT, ObjectMotionVectorsDepthURP.rt);
#endif // UNITY_2023_1_OR_NEWER
CullingResults cullingResults = renderingData.cullResults;
ShaderTagId[] tags
#if UNITY_2023_1_OR_NEWER
= {new ShaderTagId("MotionVectors")};
#else
= {new ShaderTagId("Meta")};
#endif // UNITY_2023_1_OR_NEWER
var renderList = new UnityEngine.Rendering.RendererUtils.RendererListDesc(tags, cullingResults, camera)
{
rendererConfiguration = PerObjectData.MotionVectors,
renderQueueRange = RenderQueueRange.opaque,
sortingCriteria = SortingCriteria.CommonOpaque,
layerMask = camera.cullingMask,
overrideMaterial
#if UNITY_2023_1_OR_NEWER
= null,
#else
= MotionVectorsMaterial_URP,
overrideMaterialPassIndex = 1,
// If somethingis wrong with our custom shader we can always use the standard one (and ShaderPass = 0) instead
// Material ObjectMotionVectorsMaterial = new Material(Shader.Find("Hidden/Universal Render Pipeline/ObjectMotionVectors"));
// overrideMaterialPassIndex = 0,
#endif //UNITY_2023_1_OR_NEWER
};
CoreUtils.DrawRendererList(context, cmd, context.CreateRendererList(renderList));
#if !UNITY_2023_1_OR_NEWER
// Prior to 2023 camera motion vectors are rendered directly on objects, so we will finish mv calculation here and won't execute camera mv
cmd.SetGlobalTexture(HShaderParams.g_HTraceMotionVectors, CustomCameraMotionVectorsURP[0].rt);
cmd.SetGlobalTexture(HShaderParams.g_HTraceMotionMask, CustomCameraMotionVectorsURP[1].rt);
#endif // UNITY_2023_1_OR_NEWER
}
void RenderCameraMotionVectors()
{
#if UNITY_2023_1_OR_NEWER
float DepthBiasOffset = 0;
#if UNITY_2023_1_OR_NEWER
DepthBiasOffset = 0.00099f;
#endif // UNITY_2023_1_OR_NEWER
#if UNITY_6000_0_OR_NEWER
DepthBiasOffset = 0;
#endif // UNITY_6000_0_OR_NEWER
// Target target[0] is set as a Depth Buffer, just because this method requires Depth, but we don't care for it in the fullscreen pass
RenderTargetIdentifier[] motionVectorsMRT = { CustomCameraMotionVectorsURP[0].rt, CustomCameraMotionVectorsURP[1].rt};
CoreUtils.SetRenderTarget(cmd, motionVectorsMRT, motionVectorsMRT[0]);
MotionVectorsMaterial_URP.SetTexture(_ObjectMotionVectorsColor, ObjectMotionVectorsColorURP.rt);
MotionVectorsMaterial_URP.SetTexture(_ObjectMotionVectorsDepth, ObjectMotionVectorsDepthURP.rt);
MotionVectorsMaterial_URP.SetFloat(_BiasOffset, DepthBiasOffset);
cmd.DrawProcedural(Matrix4x4.identity, MotionVectorsMaterial_URP, 0, MeshTopology.Triangles, 3, 1);
// This restores color camera color target (.SetRenderTarget can be used for Forward + any Depth Priming, but doesn't work in Deferred)
#pragma warning disable CS0618
ConfigureTarget(_renderer.cameraColorTargetHandle);
#pragma warning restore CS0618
cmd.SetGlobalTexture(HShaderParams.g_HTraceMotionVectors, CustomCameraMotionVectorsURP[0].rt);
cmd.SetGlobalTexture(HShaderParams.g_HTraceMotionMask, CustomCameraMotionVectorsURP[1].rt);
#endif // UNITY_2023_1_OR_NEWER
}
RenderObjectsMotionVectors(ref renderingData, ref context);
RenderCameraMotionVectors();
}
#endregion --------------------------- Non Render Graph ---------------------------
#region --------------------------- Render Graph ---------------------------
#if UNITY_2023_3_OR_NEWER
private class ObjectMVPassData
{
public RendererListHandle RendererListHandle;
}
private class CameraMVPassData
{
public TextureHandle ObjectMotionVectorsColor;
public TextureHandle ObjectMotionVectorsDepth;
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
UniversalCameraData universalCameraData = frameData.Get<UniversalCameraData>();
ConfigureInput(ScriptableRenderPassInput.Motion | ScriptableRenderPassInput.Depth);
using (IRasterRenderGraphBuilder builder = renderGraph.AddRasterRenderPass<ObjectMVPassData>(HNames.HTRACE_OBJECTS_MV_PASS_NAME, out var passData, ObjectMVProfilingSampler))
{
UniversalResourceData resourceData = frameData.Get<UniversalResourceData>();
UniversalRenderingData universalRenderingData = frameData.Get<UniversalRenderingData>();
builder.AllowGlobalStateModification(true);
builder.AllowPassCulling(false);
TextureHandle depthTexture = resourceData.activeDepthTexture;
TextureHandle motionVectorsTexture = resourceData.motionVectorColor;
if (motionVectorsTexture.IsValid())
builder.UseTexture(motionVectorsTexture, AccessFlags.Read);
AddRendererList(renderGraph, universalCameraData, universalRenderingData, passData, builder);
// This was previously colorTexture.GetDescriptor(renderGraph);
TextureDesc descDepth = depthTexture.GetDescriptor(renderGraph);
descDepth.colorFormat = GraphicsFormat.R16G16_SFloat;
descDepth.name = _ObjectMotionVectorsColorURP;
TextureHandle objectMotionVectorsColorTexHandle = renderGraph.CreateTexture(descDepth);
builder.SetRenderAttachment(objectMotionVectorsColorTexHandle, 0);
builder.SetRenderAttachmentDepth(depthTexture, AccessFlags.ReadWrite);
//if (motionVectorsTexture.IsValid()) //seems to work fine without this
builder.SetGlobalTextureAfterPass(motionVectorsTexture, HShaderParams.g_HTraceMotionVectors);
builder.SetGlobalTextureAfterPass(objectMotionVectorsColorTexHandle, HShaderParams.g_HTraceMotionMask);
builder.SetRenderFunc((ObjectMVPassData data, RasterGraphContext context) =>
{
RasterCommandBuffer cmd = context.cmd;
cmd.ClearRenderTarget(false, true, Color.black);
cmd.DrawRendererList(data.RendererListHandle);
});
}
// Render Graph + Game View - no need to render camera mv, as they are already available to us in this combination
if (universalCameraData.cameraType == CameraType.Game)
return;
using (IRasterRenderGraphBuilder builder = renderGraph.AddRasterRenderPass<CameraMVPassData>(HNames.HTRACE_CAMERA_MV_PASS_NAME, out var passData, MVProfilingSampler))
{
UniversalResourceData resourceData = frameData.Get<UniversalResourceData>();
builder.AllowGlobalStateModification(true);
builder.AllowPassCulling(false);
TextureHandle colorTexture = resourceData.activeColorTexture;
if (MotionVectorsMaterial_URP == null) MotionVectorsMaterial_URP = new Material(Shader.Find($"Hidden/{HNames.ASSET_NAME}/MotionVectorsURP"));
TextureDesc desc = colorTexture.GetDescriptor(renderGraph);
desc.colorFormat = GraphicsFormat.R16G16_SFloat;
desc.name = _CustomCameraMotionVectorsURP_0;
TextureHandle cameraMotionVectorsColorTexHandle = renderGraph.CreateTexture(desc);
builder.SetRenderAttachment(cameraMotionVectorsColorTexHandle, 0);
builder.SetGlobalTextureAfterPass(cameraMotionVectorsColorTexHandle, HShaderParams.g_HTraceMotionVectors);
builder.SetRenderFunc((CameraMVPassData data, RasterGraphContext context) =>
{
RasterCommandBuffer cmd = context.cmd;
MotionVectorsMaterial_URP.SetTexture(_ObjectMotionVectorsColor, context.defaultResources.blackTexture);
MotionVectorsMaterial_URP.SetTexture(_ObjectMotionVectorsDepth, context.defaultResources.whiteTexture);
MotionVectorsMaterial_URP.SetFloat(_BiasOffset, 0);
cmd.DrawProcedural(Matrix4x4.identity, MotionVectorsMaterial_URP, 0, MeshTopology.Triangles, 3, 1);
});
}
}
private static void AddRendererList(RenderGraph renderGraph, UniversalCameraData universalCameraData, UniversalRenderingData universalRenderingData, ObjectMVPassData objectMvPassData, IRasterRenderGraphBuilder builder)
{
RenderStateBlock ForwardGBufferRenderStateBlock = new RenderStateBlock(RenderStateMask.Nothing);
ForwardGBufferRenderStateBlock.depthState = new DepthState(false, CompareFunction.LessEqual); // Probably CompareFunction.Less ?
ForwardGBufferRenderStateBlock.mask |= RenderStateMask.Depth;
ShaderTagId motionVectorsShaderTag = new ShaderTagId(_MotionVectorsTagID);
var renderList = new UnityEngine.Rendering.RendererUtils.RendererListDesc(motionVectorsShaderTag, universalRenderingData.cullResults, universalCameraData.camera)
{
rendererConfiguration = PerObjectData.MotionVectors,
renderQueueRange = RenderQueueRange.opaque,
sortingCriteria = SortingCriteria.CommonOpaque,
stateBlock = ForwardGBufferRenderStateBlock,
};
objectMvPassData.RendererListHandle = renderGraph.CreateRendererList(renderList);
builder.UseRendererList(objectMvPassData.RendererListHandle);
}
#endif
#endregion --------------------------- Render Graph ---------------------------
#region --------------------------- Share ---------------------------
protected internal void Dispose()
{
CustomCameraMotionVectorsURP[0]?.HRelease();
CustomCameraMotionVectorsURP[1]?.HRelease();
ObjectMotionVectorsColorURP?.HRelease();
ObjectMotionVectorsDepthURP?.HRelease();
}
#endregion --------------------------- Share ---------------------------
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 603fb045f7d843da93b9e3f0435072b7
timeCreated: 1757339660
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Passes/URP/MotionVectorsURP.cs
uploadId: 840002

View File

@@ -0,0 +1,225 @@
//pipelinedefine
#define H_URP
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Extensions.CameraHistorySystem;
using HTraceSSGI.Scripts.Globals;
using HTraceSSGI.Scripts.Passes.Shared;
using HTraceSSGI.Scripts.Wrappers;
using Unity.Collections;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RendererUtils;
using UnityEngine.Rendering.Universal;
#if UNITY_2023_3_OR_NEWER
using UnityEngine.Rendering.RenderGraphModule;
#else
using UnityEngine.Experimental.Rendering.RenderGraphModule;
#endif
namespace HTraceSSGI.Scripts.Passes.URP
{
internal class PrePassURP : ScriptableRenderPass
{
private static Vector4 s_HRenderScalePrevious = Vector4.one;
private struct HistoryCameraData : ICameraHistoryData
{
private int hash;
public Matrix4x4 previousViewProjMatrix;
public Matrix4x4 previousInvViewProjMatrix;
public int GetHash() => hash;
public void SetHash(int hashIn) => this.hash = hashIn;
}
private static readonly CameraHistorySystem<HistoryCameraData> CameraHistorySystem = new CameraHistorySystem<HistoryCameraData>();
private static int s_FrameCount = 0;
#region --------------------------- Non Render Graph ---------------------------
private ScriptableRenderer _renderer;
protected internal void Initialize(ScriptableRenderer renderer)
{
_renderer = renderer;
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
{
Camera camera = renderingData.cameraData.camera;
CameraHistorySystem.UpdateCameraHistoryIndex(camera.GetHashCode());
CameraHistorySystem.UpdateCameraHistoryData();
CameraHistorySystem.GetCameraData().SetHash(camera.GetHashCode());
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
{
ConfigureInput(ScriptableRenderPassInput.Depth); // | ScriptableRenderPassInput.Normal);
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
var cmd = CommandBufferPool.Get(HNames.HTRACE_PRE_PASS_NAME);
Camera camera = renderingData.cameraData.camera;
// -------------- HRenderScale -----------------
// Unity's _RTHandleScale in URP always (1,1,1,1)? We need to overwrite it anyway...
cmd.SetGlobalVector(HShaderParams.HRenderScalePrevious, s_HRenderScalePrevious);
//s_HRenderScalePrevious = new Vector4(RTHandles.rtHandleProperties.rtHandleScale.x, RTHandles.rtHandleProperties.rtHandleScale.y, 1 / RTHandles.rtHandleProperties.rtHandleScale.x, 1 / RTHandles.rtHandleProperties.rtHandleScale.y); //we don't needed it more
cmd.SetGlobalVector(HShaderParams.HRenderScale, s_HRenderScalePrevious);
// -------------- Matrix -----------------
Matrix4x4 projMatrix = GL.GetGPUProjectionMatrix(camera.projectionMatrix, true); //renderingData.cameraData.GetGPUProjectionMatrix();
Matrix4x4 viewMatrix = renderingData.cameraData.GetViewMatrix();
Matrix4x4 viewProjMatrix = projMatrix * viewMatrix;
Matrix4x4 invViewProjMatrix = Matrix4x4.Inverse(viewProjMatrix);
{
cmd.SetGlobalMatrix(HShaderParams.H_MATRIX_VP, viewProjMatrix);
cmd.SetGlobalMatrix(HShaderParams.H_MATRIX_I_VP, invViewProjMatrix);
ref var previousViewProjMatrix = ref CameraHistorySystem.GetCameraData().previousViewProjMatrix;
cmd.SetGlobalMatrix(HShaderParams.H_MATRIX_PREV_VP, previousViewProjMatrix);
ref var previousInvViewProjMatrix = ref CameraHistorySystem.GetCameraData().previousInvViewProjMatrix;
cmd.SetGlobalMatrix(HShaderParams.H_MATRIX_PREV_I_VP, previousInvViewProjMatrix);
previousViewProjMatrix = viewProjMatrix;
previousInvViewProjMatrix = invViewProjMatrix;
CameraHistorySystem.GetCameraData().SetHash(camera.GetHashCode());
// HistoryCameraData currentData = CameraHistorySystem.GetCameraData();
// currentData.previousViewProjMatrix = viewProjMatrix;
// currentData.previousInvViewProjMatrix = invViewProjMatrix;
// CameraHistorySystem.SetCameraData(currentData);
}
// -------------- Other -----------------
cmd.SetGlobalInt(HShaderParams.FrameCount, s_FrameCount);
s_FrameCount++;
// Unity's blue noise is unreliable, so we'll use ours in all pipelines
HBlueNoise.SetTextures(cmd);
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
CommandBufferPool.Release(cmd);
}
#endregion --------------------------- Non Render Graph ---------------------------
#region --------------------------- Render Graph ---------------------------
#if UNITY_2023_3_OR_NEWER
RTHandle OwenScrambledRTHandle;
RTHandle ScramblingTileXSPPRTHandle;
RTHandle RankingTileXSPPRTHandle;
RTHandle ScramblingTextureRTHandle;
private class PassData
{
public RendererListHandle RendererListHandle;
public UniversalCameraData UniversalCameraData;
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
using (var builder = renderGraph.AddRasterRenderPass<PassData>(HNames.HTRACE_PRE_PASS_NAME, out var passData, new ProfilingSampler(HNames.HTRACE_PRE_PASS_NAME)))
{
UniversalResourceData resourceData = frameData.Get<UniversalResourceData>();
UniversalCameraData universalCameraData = frameData.Get<UniversalCameraData>();
UniversalRenderingData universalRenderingData = frameData.Get<UniversalRenderingData>();
UniversalLightData lightData = frameData.Get<UniversalLightData>();
ConfigureInput(ScriptableRenderPassInput.Depth | ScriptableRenderPassInput.Normal);
builder.AllowGlobalStateModification(true);
builder.AllowPassCulling(false);
passData.UniversalCameraData = universalCameraData;
Camera camera = universalCameraData.camera;
CameraHistorySystem.UpdateCameraHistoryIndex(camera.GetHashCode());
CameraHistorySystem.UpdateCameraHistoryData();
CameraHistorySystem.GetCameraData().SetHash(camera.GetHashCode());
//Blue noise
if (OwenScrambledRTHandle == null) OwenScrambledRTHandle = RTHandles.Alloc(HBlueNoise.OwenScrambledTexture);
TextureHandle owenScrambledTextureHandle = renderGraph.ImportTexture(OwenScrambledRTHandle);
builder.SetGlobalTextureAfterPass(owenScrambledTextureHandle, HBlueNoise.g_OwenScrambledTexture);
if (ScramblingTileXSPPRTHandle == null) ScramblingTileXSPPRTHandle = RTHandles.Alloc(HBlueNoise.ScramblingTileXSPP);
TextureHandle scramblingTileXSPPTextureHandle = renderGraph.ImportTexture(ScramblingTileXSPPRTHandle);
builder.SetGlobalTextureAfterPass(scramblingTileXSPPTextureHandle, HBlueNoise.g_ScramblingTileXSPP);
if (RankingTileXSPPRTHandle == null) RankingTileXSPPRTHandle = RTHandles.Alloc(HBlueNoise.RankingTileXSPP);
TextureHandle rankingTileXSPPTextureHandle = renderGraph.ImportTexture(RankingTileXSPPRTHandle);
builder.SetGlobalTextureAfterPass(rankingTileXSPPTextureHandle, HBlueNoise.g_RankingTileXSPP);
if (ScramblingTextureRTHandle == null) ScramblingTextureRTHandle = RTHandles.Alloc(HBlueNoise.ScramblingTexture);
TextureHandle scramblingTextureHandle = renderGraph.ImportTexture(ScramblingTextureRTHandle);
builder.SetGlobalTextureAfterPass(scramblingTextureHandle, HBlueNoise.g_ScramblingTexture);
builder.SetRenderFunc((PassData data, RasterGraphContext context) => ExecutePass(data, context));
}
}
private static void ExecutePass(PassData data, RasterGraphContext rgContext)
{
var cmd = rgContext.cmd;
Camera camera = data.UniversalCameraData.camera;
// -------------- HRenderScale -----------------
// Unity's _RTHandleScale in URP always (1,1,1,1)? We need to overwrite it anyway...
cmd.SetGlobalVector(HShaderParams.HRenderScalePrevious, s_HRenderScalePrevious);
//s_HRenderScalePrevious = new Vector4(RTHandles.rtHandleProperties.rtHandleScale.x, RTHandles.rtHandleProperties.rtHandleScale.y, 1 / RTHandles.rtHandleProperties.rtHandleScale.x, 1 / RTHandles.rtHandleProperties.rtHandleScale.y); //we don't needed it more
cmd.SetGlobalVector(HShaderParams.HRenderScale, s_HRenderScalePrevious);
// -------------- Matrix -----------------
Matrix4x4 projMatrix = GL.GetGPUProjectionMatrix(camera.projectionMatrix, true); //renderingData.cameraData.GetGPUProjectionMatrix();
Matrix4x4 viewMatrix = data.UniversalCameraData.GetViewMatrix();
Matrix4x4 viewProjMatrix = projMatrix * viewMatrix;
Matrix4x4 invViewProjMatrix = Matrix4x4.Inverse(viewProjMatrix);
{
cmd.SetGlobalMatrix(HShaderParams.H_MATRIX_VP, viewProjMatrix);
cmd.SetGlobalMatrix(HShaderParams.H_MATRIX_I_VP, invViewProjMatrix);
ref var previousViewProjMatrix = ref CameraHistorySystem.GetCameraData().previousViewProjMatrix;
cmd.SetGlobalMatrix(HShaderParams.H_MATRIX_PREV_VP, previousViewProjMatrix);
ref var previousInvViewProjMatrix = ref CameraHistorySystem.GetCameraData().previousInvViewProjMatrix;
cmd.SetGlobalMatrix(HShaderParams.H_MATRIX_PREV_I_VP, previousInvViewProjMatrix);
previousViewProjMatrix = viewProjMatrix;
previousInvViewProjMatrix = invViewProjMatrix;
CameraHistorySystem.GetCameraData().SetHash(camera.GetHashCode());
// HistoryCameraData currentData = CameraHistorySystem.GetCameraData();
// currentData.previousViewProjMatrix = viewProjMatrix;
// currentData.previousInvViewProjMatrix = invViewProjMatrix;
// CameraHistorySystem.SetCameraData(currentData);
}
// -------------- Other -----------------
cmd.SetGlobalInt(HShaderParams.FrameCount, s_FrameCount);
s_FrameCount++;
}
#endif
#endregion --------------------------- Render Graph ---------------------------
protected internal void Dispose()
{
s_FrameCount = 0;
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 1499f9a9fbb1cf242835eeae03872d5d
timeCreated: 1729952288
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Passes/URP/PrePassURP.cs
uploadId: 840002

View File

@@ -0,0 +1,446 @@
//pipelinedefine
#define H_URP
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Data.Public;
using HTraceSSGI.Scripts.Extensions;
using HTraceSSGI.Scripts.Globals;
using HTraceSSGI.Scripts.Passes.Shared;
using HTraceSSGI.Scripts.Wrappers;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
#if UNITY_2023_3_OR_NEWER
using HTraceSSGI.Scripts.Infrastructure.URP;
using UnityEngine.Rendering.RenderGraphModule;
#endif
namespace HTraceSSGI.Scripts.Passes.URP
{
internal class SSGIPassURP : ScriptableRenderPass
{
private static readonly int CameraNormalsTexture = Shader.PropertyToID("_CameraNormalsTexture");
// Texture Names
internal const string _ColorPreviousFrame = "_ColorPreviousFrame";
internal const string _DebugOutput = "_DebugOutput";
internal const string _ColorCopy = "_ColorCopy";
internal const string _ReservoirLuminance = "_ReservoirLuminance";
internal const string _Reservoir = "_Reservoir";
internal const string _ReservoirReprojected = "_ReservoirReprojected";
internal const string _ReservoirSpatial = "_ReservoirSpatial";
internal const string _ReservoirTemporal = "_ReservoirTemporal";
internal const string _SampleCount = "_Samplecount";
internal const string _SamplecountReprojected = "_SamplecountReprojected";
internal const string _TemporalInvalidityFilteredA = "_TemporalInvalidityFilteredA";
internal const string _TemporalInvalidityFilteredB = "_TemporalInvalidityFilteredB";
internal const string _TemporalInvalidityAccumulated = "_TemporalInvalidityAccumulated";
internal const string _TemporalInvalidityReprojected = "_TemporalInvalidityReprojected";
internal const string _SpatialOcclusionAccumulated = "_SpatialOcclusionAccumulated";
internal const string _SpatialOcclusionReprojected = "_SpatialOcclusionReprojected";
internal const string _AmbientOcclusion = "_AmbientOcclusion";
internal const string _AmbientOcclusionGuidance = "_AmbientOcclusionGuidance";
internal const string _AmbientOcclusionInvalidity = "_AmbientOcclusionInvalidity";
internal const string _AmbientOcclusionAccumulated = "_AmbientOcclusionAccumulated";
internal const string _AmbientOcclusionReprojected = "_AmbientOcclusionReprojected";
internal const string _Radiance = "_Radiance";
internal const string _RadianceReprojected = "_RadianceReprojected";
internal const string _RadianceAccumulated = "_RadianceAccumulated";
internal const string _RadianceFiltered = "_RadianceFiltered";
internal const string _RadianceInterpolated = "_RadianceInterpolated";
internal const string _RadianceStabilized = "_RadianceStabilized";
internal const string _RadianceStabilizedReprojected = "_RadianceStabilizedReprojected";
internal const string _RadianceNormalDepth = "_RadianceNormalDepth";
internal const string _ColorReprojected = "_ColorReprojected";
internal const string _NormalDepthHistory = "_NormalDepthHistory";
internal const string _NormalDepthHistoryFullRes = "_NormalDepthHistoryFullRes";
internal const string _DummyBlackTexture = "_DummyBlackTexture";
#region --------------------------- Non Render Graph ---------------------------
private ScriptableRenderer _renderer;
protected internal void Initialize(ScriptableRenderer renderer)
{
_renderer = renderer;
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
{
SSGI.CameraHistorySystem.UpdateCameraHistoryIndex(renderingData.cameraData.camera.GetHashCode());
SSGI.CameraHistorySystem.UpdateCameraHistoryData();
SSGI.CameraHistorySystem.GetCameraData().SetHash(renderingData.cameraData.camera.GetHashCode());
SetupShared(renderingData.cameraData.camera, renderingData.cameraData.renderScale, renderingData.cameraData.cameraTargetDescriptor);
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor)
{
}
#if UNITY_2023_3_OR_NEWER
[System.Obsolete]
#endif
public override void Execute(ScriptableRenderContext context, ref RenderingData renderingData)
{
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
var cmd = CommandBufferPool.Get(HNames.HTRACE_SSGI_PASS_NAME);
Camera camera = renderingData.cameraData.camera;
float renderScale = renderingData.cameraData.renderScale;
int width = (int)(camera.scaledPixelWidth * renderScale);
int height = (int)(camera.scaledPixelHeight * renderScale);
if (Shader.GetGlobalTexture(CameraNormalsTexture) == null)
return;
// ---------------------------------------- AMBIENT LIGHTING OVERRIDE ---------------------------------------- //
using (new ProfilingScope(cmd, SSGI.AmbientLightingOverrideSampler))
{
cmd.SetGlobalFloat(SSGI._IndirectLightingIntensity, profile.SSGISettings.Intensity);
if (profile.GeneralSettings.AmbientOverride)
{
// Copy Color buffer
CoreUtils.SetRenderTarget(cmd, SSGI.ColorCopy_URP.rt);
cmd.DrawProcedural(Matrix4x4.identity, SSGI.ColorCompose_URP, 0, MeshTopology.Triangles, 3, 1);
// Subtract indirect lighting from Color buffer
CoreUtils.SetRenderTarget(cmd, _renderer.cameraColorTargetHandle);
SSGI.ColorCompose_URP.SetTexture(SSGI._ColorCopy, SSGI.ColorCopy_URP.rt);
cmd.DrawProcedural(Matrix4x4.identity, SSGI.ColorCompose_URP, 1, MeshTopology.Triangles, 3, 1);
}
// Early out if we want to prview direct lighting only
if (profile.GeneralSettings.DebugMode == DebugMode.DirectLighting)
{
ConfigureTarget(_renderer.cameraColorTargetHandle);
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
CommandBufferPool.Release(cmd);
return;
}
}
SSGI.Execute(cmd, camera, width, height, _renderer.cameraColorTargetHandle);
// ---------------------------------------- INDIRECT LIGHTING INJECTION ---------------------------------------- //
using (new ProfilingScope(cmd, SSGI.IndirectLightingInjectionSampler))
{
var finalOutput = Mathf.Approximately(profile.SSGISettings.RenderScale, 1.0f) ? SSGI.RadianceFiltered.rt : SSGI.RadianceInterpolated.rt;
cmd.SetGlobalTexture(SSGI._SampleCountSSGI, SSGI.SamplecountReprojected.rt);
cmd.SetGlobalTexture(SSGI._HTraceBufferGI, finalOutput);
// Copy color buffer + indirect lighting (without intensity multiplication) for multibounce
if (profile.GeneralSettings.Multibounce == true)
{
cmd.SetComputeTextureParam(SSGI.HTemporalReprojection, (int)SSGI.HTemporalReprojectionKernels.CopyHistory, SSGI._Radiance_History, _renderer.cameraColorTargetHandle);
cmd.SetComputeTextureParam(SSGI.HTemporalReprojection, (int)SSGI.HTemporalReprojectionKernels.CopyHistory, SSGI._Radiance_Output, SSGI.CameraHistorySystem.GetCameraData().ColorPreviousFrame.rt);
cmd.DispatchCompute(SSGI.HTemporalReprojection, (int)SSGI.HTemporalReprojectionKernels.CopyHistory, Mathf.CeilToInt(width / 8.0f), Mathf.CeilToInt(height / 8.0f), HRenderer.TextureXrSlices);
}
#if UNITY_2023_3_OR_NEWER
if (profile.GeneralSettings.ExcludeReceivingMask != 0)
SSGI.ColorCompose_URP.EnableKeyword(SSGI.USE_RECEIVE_LAYER_MASK);
#endif
// Inject final indirect lighting (with intensity multiplication) into color buffer via additive blending
CoreUtils.SetRenderTarget(cmd, _renderer.cameraColorTargetHandle);
SSGI.ColorCompose_URP.SetInt(SSGI._MetallicIndirectFallback, profile.GeneralSettings.MetallicIndirectFallback ? 1 : 0);
cmd.DrawProcedural(Matrix4x4.identity, SSGI.ColorCompose_URP, 2, MeshTopology.Triangles, 3, 1);
ConfigureTarget(_renderer.cameraColorTargetHandle);
}
SSGI.History.Update();
context.ExecuteCommandBuffer(cmd);
cmd.Clear();
CommandBufferPool.Release(cmd);
return;
}
#endregion --------------------------- Non Render Graph ---------------------------
#region --------------------------- Render Graph ---------------------------
#if UNITY_2023_3_OR_NEWER
private class PassData
{
public UniversalCameraData UniversalCameraData;
public TextureHandle ColorTexture;
public TextureHandle DepthTexture;
}
public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
{
using (var builder = renderGraph.AddUnsafePass<PassData>(HNames.HTRACE_SSGI_PASS_NAME, out var passData, new ProfilingSampler(HNames.HTRACE_SSGI_PASS_NAME)))
{
UniversalResourceData resourceData = frameData.Get<UniversalResourceData>();
UniversalCameraData universalCameraData = frameData.Get<UniversalCameraData>();
UniversalRenderingData universalRenderingData = frameData.Get<UniversalRenderingData>();
UniversalLightData lightData = frameData.Get<UniversalLightData>();
ConfigureInput(ScriptableRenderPassInput.Normal);
builder.AllowGlobalStateModification(true);
builder.AllowPassCulling(false);
RenderTextureDescriptor targetDesc = universalCameraData.cameraTargetDescriptor;
TextureHandle colorTexture = universalRenderingData.renderingMode == RenderingMode.Deferred
#if UNITY_6000_1_OR_NEWER
|| universalRenderingData.renderingMode == RenderingMode.DeferredPlus
#endif
? resourceData.activeColorTexture : resourceData.cameraColor;
TextureHandle depthTexture = universalRenderingData.renderingMode == RenderingMode.Deferred
#if UNITY_6000_1_OR_NEWER
|| universalRenderingData.renderingMode == RenderingMode.DeferredPlus
#endif
? resourceData.activeDepthTexture : resourceData.cameraDepth;
builder.UseTexture(colorTexture, AccessFlags.Write);
builder.UseTexture(resourceData.cameraNormalsTexture);
builder.UseTexture(resourceData.motionVectorColor);
passData.UniversalCameraData = universalCameraData;
passData.ColorTexture = colorTexture;
passData.DepthTexture = depthTexture;
Camera camera = universalCameraData.camera;
SSGI.CameraHistorySystem.UpdateCameraHistoryIndex(camera.GetHashCode());
SSGI.CameraHistorySystem.UpdateCameraHistoryData();
SSGI.CameraHistorySystem.GetCameraData().SetHash(camera.GetHashCode());
SetupShared(camera, universalCameraData.renderScale, universalCameraData.cameraTargetDescriptor);
builder.SetRenderFunc((PassData data, UnsafeGraphContext context) => ExecutePass(data, context));
}
}
private static void ExecutePass(PassData data, UnsafeGraphContext rgContext)
{
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
var cmd = CommandBufferHelpers.GetNativeCommandBuffer(rgContext.cmd);
Camera camera = data.UniversalCameraData.camera;
float renderScale = data.UniversalCameraData.renderScale;
int width = (int)(camera.scaledPixelWidth * renderScale);
int height = (int)(camera.scaledPixelHeight * renderScale);
if (Shader.GetGlobalTexture(CameraNormalsTexture) == null)
return;
// ---------------------------------------- AMBIENT LIGHTING OVERRIDE ---------------------------------------- //
using (new ProfilingScope(cmd, SSGI.AmbientLightingOverrideSampler))
{
cmd.SetGlobalFloat(SSGI._IndirectLightingIntensity, profile.SSGISettings.Intensity);
if (profile.GeneralSettings.AmbientOverride)
{
// Copy Color buffer
CoreUtils.SetRenderTarget(cmd, SSGI.ColorCopy_URP.rt);
cmd.DrawProcedural(Matrix4x4.identity, SSGI.ColorCompose_URP, 0, MeshTopology.Triangles, 3, 1);
// Subtract indirect lighting from Color buffer
CoreUtils.SetRenderTarget(cmd, data.ColorTexture);
SSGI.ColorCompose_URP.SetTexture(SSGI._ColorCopy, SSGI.ColorCopy_URP.rt);
cmd.DrawProcedural(Matrix4x4.identity, SSGI.ColorCompose_URP, 1, MeshTopology.Triangles, 3, 1);
}
// Early out if we want to prview direct lighting only
if (profile.GeneralSettings.DebugMode == DebugMode.DirectLighting)
{
return;
}
}
SSGI.Execute(cmd, camera, width, height, data.ColorTexture);
// ---------------------------------------- INDIRECT LIGHTING INJECTION ---------------------------------------- //
using (new ProfilingScope(cmd, SSGI.IndirectLightingInjectionSampler))
{
cmd.SetGlobalTexture(SSGI._HTraceBufferGI, SSGI.finalOutput);
// Copy color buffer + indirect lighting (without intensity multiplication) for multibounce
if (profile.GeneralSettings.Multibounce == true)
{
cmd.SetComputeTextureParam(SSGI.HTemporalReprojection, (int)SSGI.HTemporalReprojectionKernels.CopyHistory, SSGI._Radiance_History, data.ColorTexture);
cmd.SetComputeTextureParam(SSGI.HTemporalReprojection, (int)SSGI.HTemporalReprojectionKernels.CopyHistory, SSGI._Radiance_Output, SSGI.CameraHistorySystem.GetCameraData().ColorPreviousFrame.rt);
cmd.DispatchCompute(SSGI.HTemporalReprojection, (int)SSGI.HTemporalReprojectionKernels.CopyHistory, Mathf.CeilToInt(width / 8.0f), Mathf.CeilToInt(height / 8.0f), HRenderer.TextureXrSlices);
}
#if UNITY_2023_3_OR_NEWER
if (profile.GeneralSettings.ExcludeReceivingMask != 0)
SSGI.ColorCompose_URP.EnableKeyword(SSGI.USE_RECEIVE_LAYER_MASK);
#endif
// Inject final indirect lighting (with intensity multiplication) into color buffer via additive blending
CoreUtils.SetRenderTarget(cmd, data.ColorTexture);
SSGI.ColorCompose_URP.SetInt(SSGI._MetallicIndirectFallback, profile.GeneralSettings.MetallicIndirectFallback ? 1 : 0);
cmd.DrawProcedural(Matrix4x4.identity, SSGI.ColorCompose_URP, 2, MeshTopology.Triangles, 3, 1);
}
SSGI.History.Update();
}
#endif
#endregion --------------------------- Render Graph ---------------------------
#region ------------------------------------ Shared ------------------------------------
private static void SetupShared(Camera camera, float renderScale, RenderTextureDescriptor desc)
{
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
if (SSGI.HDebug == null) SSGI.HDebug = HExtensions.LoadComputeShader("HDebugSSGI");
if (SSGI.HReSTIR == null) SSGI.HReSTIR = HExtensions.LoadComputeShader("HRestirSSGI");
if (SSGI.HRenderSSGI == null) SSGI.HRenderSSGI = HExtensions.LoadComputeShader("HRenderSSGI");
if (SSGI.HDenoiser == null) SSGI.HDenoiser = HExtensions.LoadComputeShader("HDenoiserSSGI");
if (SSGI.HInterpolation == null) SSGI.HInterpolation = HExtensions.LoadComputeShader("HInterpolationSSGI");
if (SSGI.HCheckerboarding == null) SSGI.HCheckerboarding = HExtensions.LoadComputeShader("HCheckerboardingSSGI");
if (SSGI.PyramidGeneration == null) SSGI.PyramidGeneration = HExtensions.LoadComputeShader("HDepthPyramid");
if (SSGI.HTemporalReprojection == null) SSGI.HTemporalReprojection = HExtensions.LoadComputeShader("HTemporalReprojectionSSGI");
if (SSGI.ColorCompose_URP == null) SSGI.ColorCompose_URP = new Material(Shader.Find($"Hidden/{HNames.ASSET_NAME}/ColorComposeURP"));
int width = (int)(camera.scaledPixelWidth * renderScale);
int height = (int)(camera.scaledPixelHeight * renderScale);
if (desc.width != width || desc.height != height)
desc = new RenderTextureDescriptor(width, height);
// Debug.Log($"All params in cameraTargetDescriptor: width: {desc.width}, height:{desc.height}, volumeDepth: {desc.volumeDepth}, depthBufferBits: {desc.depthBufferBits}, \n" +
// $"graphicsFormat: {desc.graphicsFormat}, colorFormat: {desc.colorFormat}, stencilFormat: {desc.stencilFormat}, msaaSamples: {desc.msaaSamples}, \n" +
// $"useMipMap: {desc.useMipMap}, autoGenerateMips: {desc.autoGenerateMips}, mipCount: {desc.mipCount}, \n" +
// $"enableRandomWrite: {desc.enableRandomWrite}, useDynamicScale: {desc.useDynamicScale}, ");
desc.depthBufferBits = 0; // Color and depth cannot be combined in RTHandles
desc.stencilFormat = GraphicsFormat.None;
desc.depthStencilFormat = GraphicsFormat.None;
desc.msaaSamples = 1;
desc.bindMS = false;
desc.enableRandomWrite = true;
ref var cameraData = ref SSGI.CameraHistorySystem.GetCameraData();
if (cameraData.ColorPreviousFrame == null) cameraData.ColorPreviousFrame = new RTWrapper();
if (cameraData.ReservoirTemporal == null) cameraData.ReservoirTemporal = new RTWrapper();
if (cameraData.SampleCount == null) cameraData.SampleCount = new RTWrapper();
if (cameraData.NormalDepth == null) cameraData.NormalDepth = new RTWrapper();
if (cameraData.NormalDepthFullRes == null) cameraData.NormalDepthFullRes = new RTWrapper();
if (cameraData.Radiance == null) cameraData.Radiance = new RTWrapper();
if (cameraData.RadianceAccumulated == null) cameraData.RadianceAccumulated = new RTWrapper();
if (cameraData.SpatialOcclusionAccumulated == null) cameraData.SpatialOcclusionAccumulated = new RTWrapper();
if (cameraData.TemporalInvalidityAccumulated == null) cameraData.TemporalInvalidityAccumulated = new RTWrapper();
if (cameraData.AmbientOcclusionAccumulated == null) cameraData.AmbientOcclusionAccumulated = new RTWrapper();
cameraData.ColorPreviousFrame.ReAllocateIfNeeded(_ColorPreviousFrame, ref desc, graphicsFormat: GraphicsFormat.B10G11R11_UFloatPack32);
cameraData.ReservoirTemporal.ReAllocateIfNeeded(_ReservoirTemporal, ref desc, graphicsFormat: GraphicsFormat.R32G32B32A32_UInt);
cameraData.TemporalInvalidityAccumulated.ReAllocateIfNeeded(_TemporalInvalidityAccumulated, ref desc, graphicsFormat: GraphicsFormat.R8G8_UNorm);
cameraData.SpatialOcclusionAccumulated.ReAllocateIfNeeded(_SpatialOcclusionAccumulated, ref desc, graphicsFormat: GraphicsFormat.R8_UNorm);
cameraData.AmbientOcclusionAccumulated.ReAllocateIfNeeded(_AmbientOcclusionAccumulated, ref desc, graphicsFormat: GraphicsFormat.R8_UNorm);
cameraData.Radiance.ReAllocateIfNeeded(_Radiance, ref desc, graphicsFormat: profile.DenoisingSettings.RecurrentBlur ? GraphicsFormat.R16G16B16A16_SFloat : GraphicsFormat.B10G11R11_UFloatPack32);
cameraData.RadianceAccumulated.ReAllocateIfNeeded(_RadianceAccumulated, ref desc, graphicsFormat: GraphicsFormat.R16G16B16A16_SFloat);
cameraData.SampleCount.ReAllocateIfNeeded(_SampleCount, ref desc, graphicsFormat: GraphicsFormat.R16_SFloat);
cameraData.NormalDepth.ReAllocateIfNeeded(_NormalDepthHistory, ref desc, graphicsFormat: GraphicsFormat.R32_UInt);
cameraData.NormalDepthFullRes.ReAllocateIfNeeded(_NormalDepthHistoryFullRes, ref desc, graphicsFormat: GraphicsFormat.R32_UInt);
SSGI.ColorCopy_URP.ReAllocateIfNeeded(_ColorCopy, ref desc, graphicsFormat: GraphicsFormat.B10G11R11_UFloatPack32);
SSGI.DebugOutput.ReAllocateIfNeeded(_ColorCopy, ref desc, graphicsFormat: GraphicsFormat.B10G11R11_UFloatPack32);
SSGI.ColorReprojected.ReAllocateIfNeeded(_ColorReprojected, ref desc, graphicsFormat: GraphicsFormat.R32_UInt);
SSGI.Reservoir.ReAllocateIfNeeded(_Reservoir, ref desc, graphicsFormat: GraphicsFormat.R32G32B32A32_UInt);
SSGI.ReservoirReprojected.ReAllocateIfNeeded(_ReservoirReprojected, ref desc, graphicsFormat: GraphicsFormat.R32G32B32A32_UInt);
SSGI.ReservoirSpatial.ReAllocateIfNeeded(_ReservoirSpatial, ref desc, graphicsFormat: GraphicsFormat.R32G32B32A32_UInt);
SSGI.ReservoirLuminance.ReAllocateIfNeeded(_ReservoirLuminance, ref desc, graphicsFormat: GraphicsFormat.R16_SFloat);
SSGI.TemporalInvalidityFilteredA.ReAllocateIfNeeded(_TemporalInvalidityFilteredA, ref desc, graphicsFormat: GraphicsFormat.R8G8_UNorm);
SSGI.TemporalInvalidityFilteredB.ReAllocateIfNeeded(_TemporalInvalidityFilteredB, ref desc, graphicsFormat: GraphicsFormat.R8G8_UNorm);
SSGI.TemporalInvalidityReprojected.ReAllocateIfNeeded(_TemporalInvalidityReprojected, ref desc, graphicsFormat: GraphicsFormat.R8G8_UNorm);
SSGI.SpatialOcclusionReprojected.ReAllocateIfNeeded(_SpatialOcclusionReprojected, ref desc, graphicsFormat: GraphicsFormat.R8_UNorm);
SSGI.AmbientOcclusion.ReAllocateIfNeeded(_AmbientOcclusion, ref desc, graphicsFormat: GraphicsFormat.R8_SNorm);
SSGI.AmbientOcclusionGuidance.ReAllocateIfNeeded(_AmbientOcclusionGuidance, ref desc, graphicsFormat: GraphicsFormat.R8G8_UInt);
SSGI.AmbientOcclusionInvalidity.ReAllocateIfNeeded(_AmbientOcclusionInvalidity, ref desc, graphicsFormat: GraphicsFormat.R8_UNorm);
SSGI.AmbientOcclusionReprojected.ReAllocateIfNeeded(_AmbientOcclusionReprojected, ref desc, graphicsFormat: GraphicsFormat.R8_UNorm);
SSGI.RadianceFiltered.ReAllocateIfNeeded(_RadianceFiltered, ref desc, graphicsFormat: GraphicsFormat.B10G11R11_UFloatPack32);
SSGI.RadianceReprojected.ReAllocateIfNeeded(_RadianceReprojected, ref desc, graphicsFormat: GraphicsFormat.R16G16B16A16_SFloat);
SSGI.RadianceNormalDepth.ReAllocateIfNeeded(_RadianceNormalDepth, ref desc, graphicsFormat: GraphicsFormat.R32G32_UInt);
SSGI.RadianceInterpolated.ReAllocateIfNeeded(_RadianceInterpolated, ref desc, graphicsFormat: GraphicsFormat.B10G11R11_UFloatPack32);
SSGI.RadianceStabilizedReprojected.ReAllocateIfNeeded(_RadianceStabilizedReprojected, ref desc, graphicsFormat: GraphicsFormat.R16G16B16A16_SFloat);
SSGI.RadianceStabilized.ReAllocateIfNeeded(_RadianceStabilized, ref desc, graphicsFormat: GraphicsFormat.R16G16B16A16_SFloat);
SSGI.SamplecountReprojected.ReAllocateIfNeeded(_SamplecountReprojected, ref desc, graphicsFormat: GraphicsFormat.R16_SFloat);
SSGI.DummyBlackTexture.ReAllocateIfNeeded(_DummyBlackTexture, ref desc, graphicsFormat: GraphicsFormat.R8_UNorm);
if (SSGI.PointDistributionBuffer == null) SSGI.PointDistributionBuffer = new ComputeBuffer(32 * 4 * HRenderer.TextureXrSlices, 3 * sizeof(int));
if (SSGI.LuminanceMoments == null) SSGI.LuminanceMoments = new ComputeBuffer(2 * HRenderer.TextureXrSlices, 2 * sizeof(int));
if (SSGI.IndirectArguments == null) SSGI.IndirectArguments = new ComputeBuffer(3 * HRenderer.TextureXrSlices, sizeof(int), ComputeBufferType.IndirectArguments);
if (SSGI.IndirectCoords == null) SSGI.IndirectCoords = new HDynamicBuffer(BufferType.ComputeBuffer, 2 * sizeof(uint), HRenderer.TextureXrSlices, avoidDownscale: false);
SSGI.IndirectCoords.ReAllocIfNeeded(new Vector2Int(width, height));
if (SSGI.RayCounter == null)
{
SSGI.RayCounter = new ComputeBuffer(2 * 1, sizeof(uint));
uint[] zeroArray = new uint[2 * 1];
SSGI.RayCounter.SetData(zeroArray);
}
}
protected internal void Dispose()
{
var historyCameraDataSSGI = SSGI.CameraHistorySystem.GetCameraData();
historyCameraDataSSGI.ColorPreviousFrame?.HRelease();
historyCameraDataSSGI.ReservoirTemporal?.HRelease();
historyCameraDataSSGI.SampleCount?.HRelease();
historyCameraDataSSGI.NormalDepth?.HRelease();
historyCameraDataSSGI.NormalDepthFullRes?.HRelease();
historyCameraDataSSGI.Radiance?.HRelease();
historyCameraDataSSGI.RadianceAccumulated?.HRelease();
historyCameraDataSSGI.SpatialOcclusionAccumulated?.HRelease();
historyCameraDataSSGI.TemporalInvalidityAccumulated?.HRelease();
historyCameraDataSSGI.AmbientOcclusionAccumulated?.HRelease();
SSGI.ColorCopy_URP?.HRelease();
SSGI.DebugOutput?.HRelease();
SSGI.ColorReprojected?.HRelease();
SSGI.Reservoir?.HRelease();
SSGI.ReservoirReprojected?.HRelease();
SSGI.ReservoirSpatial?.HRelease();
SSGI.ReservoirLuminance?.HRelease();
SSGI.TemporalInvalidityFilteredA?.HRelease();
SSGI.TemporalInvalidityFilteredB?.HRelease();
SSGI.TemporalInvalidityReprojected?.HRelease();
SSGI.SpatialOcclusionReprojected?.HRelease();
SSGI.AmbientOcclusion?.HRelease();
SSGI.AmbientOcclusionGuidance?.HRelease();
SSGI.AmbientOcclusionInvalidity?.HRelease();
SSGI.AmbientOcclusionReprojected?.HRelease();
SSGI.RadianceFiltered?.HRelease();
SSGI.RadianceReprojected?.HRelease();
SSGI.RadianceNormalDepth?.HRelease();
SSGI.RadianceInterpolated?.HRelease();
SSGI.RadianceStabilizedReprojected?.HRelease();
SSGI.RadianceStabilized?.HRelease();
SSGI.SamplecountReprojected?.HRelease();
SSGI.DummyBlackTexture?.HRelease();
SSGI.PointDistributionBuffer.HRelease();
SSGI.LuminanceMoments.HRelease();
SSGI.RayCounter.HRelease();
SSGI.IndirectCoords.HRelease();
SSGI.IndirectArguments.HRelease();
SSGI.PointDistributionBuffer = null;
SSGI.LuminanceMoments = null;
SSGI.RayCounter = null;
SSGI.IndirectCoords = null;
SSGI.IndirectArguments = null;
}
#endregion ------------------------------------ Shared ------------------------------------
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 82482812f9bf9de4a878162fdf59954b
timeCreated: 1729952288
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Passes/URP/SSGIPassURP.cs
uploadId: 840002