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,3 @@
fileFormatVersion: 2
guid: 1ad0041b45384f34390fd7a858775b12
timeCreated: 1674799562

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7d4c715d58c472f42a3bc5699eeeedcb
timeCreated: 1735034400

View File

@@ -0,0 +1,21 @@
//pipelinedefine
#define H_URP
using System;
using HTraceSSGI.Scripts.Globals;
using UnityEngine;
namespace HTraceSSGI.Scripts.Data.Public
{
[Serializable]
public class DebugSettings
{
public bool ShowBowels = false;
public bool ShowFullDebugLog = false;
public LayerMask HTraceLayer = ~0;
public bool TestCheckBox1;
public bool TestCheckBox2;
public bool TestCheckBox3;
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 5b9df31ca246dfc47be48062d77712a0
timeCreated: 1734159459
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Data/Public/DebugSettings.cs
uploadId: 840002

View File

@@ -0,0 +1,122 @@
//pipelinedefine
#define H_URP
using System;
using HTraceSSGI.Scripts.Extensions;
using HTraceSSGI.Scripts.Globals;
using UnityEngine;
namespace HTraceSSGI.Scripts.Data.Public
{
[Serializable]
public class DenoisingSettings
{
// ----------------------------------------------- DENOISING -----------------------------------------------
[SerializeField]
public BrightnessClamp BrightnessClamp = BrightnessClamp.Automatic;
[SerializeField]
private float _maxValueBrightnessClamp
= 1.0f;
/// <summary>
///
/// </summary>
/// <value>[1.0;30.0]</value>
[HExtensions.HRangeAttribute(1.0f,30.0f)]
public float MaxValueBrightnessClamp
{
get => _maxValueBrightnessClamp;
set
{
if (Mathf.Abs(value - _maxValueBrightnessClamp) < Mathf.Epsilon)
return;
_maxValueBrightnessClamp = HExtensions.Clamp(value, typeof(DenoisingSettings), nameof(DenoisingSettings.MaxValueBrightnessClamp));
}
}
[SerializeField]
private float _maxDeviationBrightnessClamp
= 3.0f;
/// <summary>
///
/// </summary>
/// <value>[1.0;5.0]</value>
[HExtensions.HRangeAttribute(1.0f,5.0f)]
public float MaxDeviationBrightnessClamp
{
get => _maxDeviationBrightnessClamp;
set
{
if (Mathf.Abs(value - _maxDeviationBrightnessClamp) < Mathf.Epsilon)
return;
_maxDeviationBrightnessClamp = HExtensions.Clamp(value, typeof(DenoisingSettings), nameof(DenoisingSettings.MaxDeviationBrightnessClamp));
}
}
// ----------------------------------------------- ReSTIR Validation -----------------------------------------------
[SerializeField]
public bool HalfStepValidation = false;
[SerializeField]
public bool SpatialOcclusionValidation = true;
[SerializeField]
public bool TemporalLightingValidation = true;
[SerializeField]
public bool TemporalOcclusionValidation = true;
// ----------------------------------------------- Spatial -----------------------------------------------
[SerializeField]
private float _spatialRadius = 0.6f;
/// <summary>
///
/// </summary>
/// <value>[0.0;1.0]</value>
[HExtensions.HRangeAttribute(0.0f,1.0f)]
public float SpatialRadius
{
get => _spatialRadius;
set
{
if (Mathf.Abs(value - _spatialRadius) < Mathf.Epsilon)
return;
_spatialRadius = HExtensions.Clamp(value, typeof(DenoisingSettings), nameof(DenoisingSettings.SpatialRadius));
}
}
[SerializeField]
private float _adaptivity = 0.9f;
/// <summary>
///
/// </summary>
/// <value>[0.0;1.0]</value>
[HExtensions.HRangeAttribute(0.0f,1.0f)]
public float Adaptivity
{
get => _adaptivity;
set
{
if (Mathf.Abs(value - _adaptivity) < Mathf.Epsilon)
return;
_adaptivity = HExtensions.Clamp(value, typeof(DenoisingSettings), nameof(DenoisingSettings.Adaptivity));
}
}
[SerializeField]
public bool RecurrentBlur = false;
[SerializeField]
public bool FireflySuppression = true;
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 360288ad30824b8eaa4113b727ffb011
timeCreated: 1741602380
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Data/Public/DenoisingSettings.cs
uploadId: 840002

View File

@@ -0,0 +1,129 @@
//pipelinedefine
#define H_URP
using System;
using HTraceSSGI.Scripts.Extensions;
using UnityEngine;
using HTraceSSGI.Scripts.Globals;
namespace HTraceSSGI.Scripts.Data.Public
{
[Serializable]
public class GeneralSettings
{
public DebugMode DebugMode = DebugMode.None;
public HBuffer HBuffer = HBuffer.Multi;
[SerializeField]
public bool MetallicIndirectFallback = false;
[SerializeField]
public bool AmbientOverride = true;
public bool Multibounce = true;
#if UNITY_2023_3_OR_NEWER
public RenderingLayerMask ExcludeCastingMask = 0;
public RenderingLayerMask ExcludeReceivingMask = 0;
#endif
[SerializeField]
public FallbackType FallbackType = FallbackType.None;
[SerializeField]
private float _skyIntensity = 0.5f;
/// <summary>
///
/// </summary>
/// <value>[0.0;1.0]</value>
[HExtensions.HRangeAttribute(0.0f,1.0f)]
public float SkyIntensity
{
get => _skyIntensity;
set
{
if (Mathf.Abs(value - _skyIntensity) < Mathf.Epsilon)
return;
_skyIntensity = HExtensions.Clamp(value, typeof(GeneralSettings), nameof(GeneralSettings.SkyIntensity));
}
}
[SerializeField]
private float _viewBias = 0.0f;
/// <summary>
///
/// </summary>
/// <value>[0.0;2.0]</value>
[HExtensions.HRangeAttribute(0.0f,2.0f)]
public float ViewBias
{
get => _viewBias;
set
{
if (Mathf.Abs(value - _viewBias) < Mathf.Epsilon)
return;
_viewBias = HExtensions.Clamp(value, typeof(GeneralSettings), nameof(GeneralSettings.ViewBias));
}
}
[SerializeField]
private float _normalBias = 0.33f;
/// <summary>
///
/// </summary>
/// <value>[0.0;4.0]</value>
[HExtensions.HRangeAttribute(0.0f,2.0f)]
public float NormalBias
{
get => _normalBias;
set
{
if (Mathf.Abs(value - _normalBias) < Mathf.Epsilon)
return;
_normalBias = HExtensions.Clamp(value, typeof(GeneralSettings), nameof(GeneralSettings.NormalBias));
}
}
[SerializeField]
private float _samplingNoise = 0.1f;
/// <summary>
///
/// </summary>
/// <value>[0.0;1.0]</value>
[HExtensions.HRangeAttribute(0.0f,1.0f)]
public float SamplingNoise
{
get => _samplingNoise;
set
{
if (Mathf.Abs(value - _samplingNoise) < Mathf.Epsilon)
return;
_samplingNoise = HExtensions.Clamp(value, typeof(GeneralSettings), nameof(GeneralSettings.SamplingNoise));
}
}
[SerializeField]
private float _intensityMultiplier = 1f;
/// <summary>
///
/// </summary>
/// <value>[0.0;1.0]</value>
[HExtensions.HRangeAttribute(0.0f,1.0f)]
public float IntensityMultiplier
{
get => _intensityMultiplier;
set
{
if (Mathf.Abs(value - _intensityMultiplier) < Mathf.Epsilon)
return;
_intensityMultiplier = HExtensions.Clamp(value, typeof(GeneralSettings), nameof(GeneralSettings.IntensityMultiplier));
}
}
public bool DenoiseFallback = true;
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 4af08f11ccfe6994a994a99e74d35b5f
timeCreated: 1674799588
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Data/Public/GeneralSettings.cs
uploadId: 840002

View File

@@ -0,0 +1,246 @@
//pipelinedefine
#define H_URP
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Editor;
using HTraceSSGI.Scripts.Globals;
using UnityEngine;
using UnityEngine.Rendering;
using HTraceSSGI.Scripts.Infrastructure.URP;
namespace HTraceSSGI.Scripts.Data.Public
{
internal static class HTraceSSGIPresetData
{
public static void ApplyPresetVolume(HTraceSSGIVolumeEditorURP hTraceSSGIVolumeEditorUrp, HTraceSSGIPreset preset)
{
var stack = VolumeManager.instance.stack;
HTraceSSGIVolume volume = stack?.GetComponent<HTraceSSGIVolume>();
if (volume == null) return;
HTraceSSGIProfile profile = CreatePresetProfile(HTraceSSGISettings.ActiveProfile, preset);
if (profile == null) return;
// General Settings
hTraceSSGIVolumeEditorUrp.p_DebugMode.value.enumValueIndex = (int)profile.GeneralSettings.DebugMode;
hTraceSSGIVolumeEditorUrp.p_DebugMode.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_FallbackType.value.enumValueIndex = (int)profile.GeneralSettings.FallbackType;
hTraceSSGIVolumeEditorUrp.p_FallbackType.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_SkyIntensity.value.floatValue = profile.GeneralSettings.SkyIntensity;
hTraceSSGIVolumeEditorUrp.p_SkyIntensity.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_DenoiseFallback.value.boolValue = profile.GeneralSettings.DenoiseFallback;
hTraceSSGIVolumeEditorUrp.p_DenoiseFallback.overrideState.boolValue = true;
// Visuals
hTraceSSGIVolumeEditorUrp.p_BackfaceLighting.value.floatValue = profile.SSGISettings.BackfaceLighting;
hTraceSSGIVolumeEditorUrp.p_BackfaceLighting.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_MaxRayLength.value.floatValue = profile.SSGISettings.MaxRayLength;
hTraceSSGIVolumeEditorUrp.p_MaxRayLength.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_ThicknessMode.value.enumValueIndex = (int)profile.SSGISettings.ThicknessMode;
hTraceSSGIVolumeEditorUrp.p_ThicknessMode.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_Thickness.value.floatValue = profile.SSGISettings.Thickness;
hTraceSSGIVolumeEditorUrp.p_Thickness.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_Falloff.value.floatValue = profile.SSGISettings.Falloff;
hTraceSSGIVolumeEditorUrp.p_Falloff.overrideState.boolValue = true;
// Quality - Tracing
hTraceSSGIVolumeEditorUrp.p_RayCount.value.intValue = profile.SSGISettings.RayCount;
hTraceSSGIVolumeEditorUrp.p_RayCount.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_StepCount.value.intValue = profile.SSGISettings.StepCount;
hTraceSSGIVolumeEditorUrp.p_StepCount.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_RefineIntersection.value.boolValue = profile.SSGISettings.RefineIntersection;
hTraceSSGIVolumeEditorUrp.p_RefineIntersection.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_FullResolutionDepth.value.boolValue = profile.SSGISettings.FullResolutionDepth;
hTraceSSGIVolumeEditorUrp.p_FullResolutionDepth.overrideState.boolValue = true;
// Quality - Rendering
hTraceSSGIVolumeEditorUrp.p_Checkerboard.value.boolValue = profile.SSGISettings.Checkerboard;
hTraceSSGIVolumeEditorUrp.p_Checkerboard.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_RenderScale.value.floatValue = profile.SSGISettings.RenderScale;
hTraceSSGIVolumeEditorUrp.p_RenderScale.overrideState.boolValue = true;
// Denoising
hTraceSSGIVolumeEditorUrp.p_BrightnessClamp.value.enumValueIndex = (int)profile.DenoisingSettings.BrightnessClamp;
hTraceSSGIVolumeEditorUrp.p_BrightnessClamp.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_MaxValueBrightnessClamp.value.floatValue = profile.DenoisingSettings.MaxValueBrightnessClamp;
hTraceSSGIVolumeEditorUrp.p_MaxValueBrightnessClamp.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_MaxDeviationBrightnessClamp.value.floatValue = profile.DenoisingSettings.MaxDeviationBrightnessClamp;
hTraceSSGIVolumeEditorUrp.p_MaxDeviationBrightnessClamp.overrideState.boolValue = true;
// Denoising - Temporal Validation
hTraceSSGIVolumeEditorUrp.p_HalfStepValidation.value.boolValue = profile.DenoisingSettings.HalfStepValidation;
hTraceSSGIVolumeEditorUrp.p_HalfStepValidation.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_SpatialOcclusionValidation.value.boolValue = profile.DenoisingSettings.SpatialOcclusionValidation;
hTraceSSGIVolumeEditorUrp.p_SpatialOcclusionValidation.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_TemporalLightingValidation.value.boolValue = profile.DenoisingSettings.TemporalLightingValidation;
hTraceSSGIVolumeEditorUrp.p_TemporalLightingValidation.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_TemporalOcclusionValidation.value.boolValue = profile.DenoisingSettings.TemporalOcclusionValidation;
hTraceSSGIVolumeEditorUrp.p_TemporalOcclusionValidation.overrideState.boolValue = true;
// Denoising - Spatial Filter
hTraceSSGIVolumeEditorUrp.p_SpatialRadius.value.floatValue = profile.DenoisingSettings.SpatialRadius;
hTraceSSGIVolumeEditorUrp.p_SpatialRadius.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_Adaptivity.value.floatValue = profile.DenoisingSettings.Adaptivity;
hTraceSSGIVolumeEditorUrp.p_Adaptivity.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_RecurrentBlur.value.boolValue = profile.DenoisingSettings.RecurrentBlur;
hTraceSSGIVolumeEditorUrp.p_RecurrentBlur.overrideState.boolValue = true;
hTraceSSGIVolumeEditorUrp.p_FireflySuppression.value.boolValue = profile.DenoisingSettings.FireflySuppression;
hTraceSSGIVolumeEditorUrp.p_FireflySuppression.overrideState.boolValue = true;
}
/// <summary>
/// Creates a profile from the specified preset type.
/// </summary>
public static HTraceSSGIProfile CreatePresetProfile(HTraceSSGIProfile activeProfile, HTraceSSGIPreset preset)
{
switch (preset)
{
case HTraceSSGIPreset.Performance:
return CreatePerformancePreset(activeProfile);
case HTraceSSGIPreset.Optimized:
return CreateOptimizedPreset(activeProfile);
case HTraceSSGIPreset.Balanced:
return CreateBalancedPreset(activeProfile);
case HTraceSSGIPreset.Quality:
return CreateQualityPreset(activeProfile);
default:
return null;
}
}
public static HTraceSSGIProfile CreatePerformancePreset(HTraceSSGIProfile activeProfile)
{
var profile = Object.Instantiate(activeProfile);
// Tracing
profile.SSGISettings.RayCount = 2;
profile.SSGISettings.StepCount = 28;
profile.SSGISettings.RefineIntersection = false;
profile.SSGISettings.FullResolutionDepth = false;
// Rendering
profile.SSGISettings.Checkerboard = true;
profile.SSGISettings.RenderScale = 0.5f;
// ReSTIR Validation
profile.DenoisingSettings.HalfStepValidation = true;
profile.DenoisingSettings.SpatialOcclusionValidation = true;
profile.DenoisingSettings.TemporalLightingValidation = false;
profile.DenoisingSettings.TemporalOcclusionValidation = false;
// Spatial Filter
profile.DenoisingSettings.SpatialRadius = 0.65f;
profile.DenoisingSettings.Adaptivity = 0.7f;
profile.DenoisingSettings.RecurrentBlur = true;
profile.DenoisingSettings.FireflySuppression = false;
return profile;
}
public static HTraceSSGIProfile CreateOptimizedPreset(HTraceSSGIProfile activeProfile)
{
var profile = Object.Instantiate(activeProfile);
// Tracing
profile.SSGISettings.RayCount = 3;
profile.SSGISettings.StepCount = 30;
profile.SSGISettings.RefineIntersection = true;
profile.SSGISettings.FullResolutionDepth = false;
// Rendering
profile.SSGISettings.Checkerboard = true;
profile.SSGISettings.RenderScale = 0.75f;
// ReSTIR Validation
profile.DenoisingSettings.HalfStepValidation = true;
profile.DenoisingSettings.SpatialOcclusionValidation = true;
profile.DenoisingSettings.TemporalLightingValidation = true;
profile.DenoisingSettings.TemporalOcclusionValidation = true;
// Spatial Filter
profile.DenoisingSettings.SpatialRadius = 0.6f;
profile.DenoisingSettings.Adaptivity = 0.8f;
profile.DenoisingSettings.RecurrentBlur = true;
profile.DenoisingSettings.FireflySuppression = true;
return profile;
}
public static HTraceSSGIProfile CreateBalancedPreset(HTraceSSGIProfile activeProfile)
{
var profile = Object.Instantiate(activeProfile);
// Tracing
profile.SSGISettings.RayCount = 3;
profile.SSGISettings.StepCount = 32;
profile.SSGISettings.RefineIntersection = true;
profile.SSGISettings.FullResolutionDepth = true;
// Rendering
profile.SSGISettings.Checkerboard = true;
profile.SSGISettings.RenderScale = 1.0f;
// ReSTIR Validation
profile.DenoisingSettings.HalfStepValidation = true;
profile.DenoisingSettings.SpatialOcclusionValidation = true;
profile.DenoisingSettings.TemporalLightingValidation = true;
profile.DenoisingSettings.TemporalOcclusionValidation = true;
// Spatial Filter
profile.DenoisingSettings.SpatialRadius = 0.6f;
profile.DenoisingSettings.Adaptivity = 0.9f;
profile.DenoisingSettings.RecurrentBlur = false;
profile.DenoisingSettings.FireflySuppression = true;
return profile;
}
public static HTraceSSGIProfile CreateQualityPreset(HTraceSSGIProfile activeProfile)
{
var profile = Object.Instantiate(activeProfile);
// Tracing
profile.SSGISettings.RayCount = 4;
profile.SSGISettings.StepCount = 36;
profile.SSGISettings.RefineIntersection = true;
profile.SSGISettings.FullResolutionDepth = true;
// Rendering
profile.SSGISettings.Checkerboard = false;
profile.SSGISettings.RenderScale = 1.0f;
// ReSTIR Validation
profile.DenoisingSettings.HalfStepValidation = false;
profile.DenoisingSettings.SpatialOcclusionValidation = true;
profile.DenoisingSettings.TemporalLightingValidation = true;
profile.DenoisingSettings.TemporalOcclusionValidation = true;
// Spatial Filter
profile.DenoisingSettings.SpatialRadius = 0.6f;
profile.DenoisingSettings.Adaptivity = 0.9f;
profile.DenoisingSettings.RecurrentBlur = false;
profile.DenoisingSettings.FireflySuppression = true;
return profile;
}
}
}

View File

@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 7a3e4f1b8c9d2a5e6f0b1c2d3e4f5a6b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Data/Public/HTraceSSGIPresetData.cs
uploadId: 840002

View File

@@ -0,0 +1,91 @@
using HTraceSSGI.Scripts.Data.Public;
using HTraceSSGI.Scripts.Editor;
using HTraceSSGI.Scripts.Globals;
using UnityEngine;
namespace HTraceSSGI.Scripts.Data.Private
{
[CreateAssetMenu(fileName = "HTraceSSGI Profile", menuName = "HTrace/SSGI Profile", order = 251)]
[HelpURL(HNames.HTRACE_SSGI_DOCUMENTATION_LINK)]
public class HTraceSSGIProfile : ScriptableObject
{
[SerializeField]
public GeneralSettings GeneralSettings = new GeneralSettings();
[SerializeField]
public SSGISettings SSGISettings = new SSGISettings();
[SerializeField]
public DenoisingSettings DenoisingSettings = new DenoisingSettings();
[SerializeField]
public DebugSettings DebugSettings = new DebugSettings();
/// <summary>
/// Applies a preset configuration to this profile.
/// This will overwrite all current settings with the preset values.
/// </summary>
/// <param name="preset">The preset type to apply</param>
public void ApplyPreset(HTraceSSGIPreset preset)
{
var presetProfile = HTraceSSGIPresetData.CreatePresetProfile(this, preset);
if (presetProfile == null)
return;
// Copy all settings from preset profile
CopySettingsFrom(presetProfile);
}
/// <summary>
/// Copies all settings from another profile to this profile.
/// </summary>
/// <param name="sourceProfile">The profile to copy settings from</param>
public void CopySettingsFrom(HTraceSSGIProfile sourceProfile)
{
if (sourceProfile == null)
return;
// Copy General Settings
GeneralSettings.DebugMode = sourceProfile.GeneralSettings.DebugMode;
GeneralSettings.HBuffer = sourceProfile.GeneralSettings.HBuffer;
GeneralSettings.MetallicIndirectFallback = sourceProfile.GeneralSettings.MetallicIndirectFallback;
GeneralSettings.AmbientOverride = sourceProfile.GeneralSettings.AmbientOverride;
GeneralSettings.Multibounce = sourceProfile.GeneralSettings.Multibounce;
#if UNITY_2023_3_OR_NEWER
GeneralSettings.ExcludeCastingMask = sourceProfile.GeneralSettings.ExcludeCastingMask;
GeneralSettings.ExcludeReceivingMask = sourceProfile.GeneralSettings.ExcludeReceivingMask;
#endif
GeneralSettings.FallbackType = sourceProfile.GeneralSettings.FallbackType;
GeneralSettings.SkyIntensity = sourceProfile.GeneralSettings.SkyIntensity;
GeneralSettings.ViewBias = sourceProfile.GeneralSettings.ViewBias;
GeneralSettings.NormalBias = sourceProfile.GeneralSettings.NormalBias;
GeneralSettings.SamplingNoise = sourceProfile.GeneralSettings.SamplingNoise;
GeneralSettings.IntensityMultiplier = sourceProfile.GeneralSettings.IntensityMultiplier;
GeneralSettings.DenoiseFallback = sourceProfile.GeneralSettings.DenoiseFallback;
// Copy SSGI Settings
SSGISettings.BackfaceLighting = sourceProfile.SSGISettings.BackfaceLighting;
SSGISettings.MaxRayLength = sourceProfile.SSGISettings.MaxRayLength;
SSGISettings.ThicknessMode = sourceProfile.SSGISettings.ThicknessMode;
SSGISettings.Thickness = sourceProfile.SSGISettings.Thickness;
SSGISettings.Intensity = sourceProfile.SSGISettings.Intensity;
SSGISettings.Falloff = sourceProfile.SSGISettings.Falloff;
SSGISettings.RayCount = sourceProfile.SSGISettings.RayCount;
SSGISettings.StepCount = sourceProfile.SSGISettings.StepCount;
SSGISettings.RefineIntersection = sourceProfile.SSGISettings.RefineIntersection;
SSGISettings.FullResolutionDepth = sourceProfile.SSGISettings.FullResolutionDepth;
SSGISettings.Checkerboard = sourceProfile.SSGISettings.Checkerboard;
SSGISettings.RenderScale = sourceProfile.SSGISettings.RenderScale;
// Copy Denoising Settings
DenoisingSettings.BrightnessClamp = sourceProfile.DenoisingSettings.BrightnessClamp;
DenoisingSettings.MaxValueBrightnessClamp = sourceProfile.DenoisingSettings.MaxValueBrightnessClamp;
DenoisingSettings.MaxDeviationBrightnessClamp = sourceProfile.DenoisingSettings.MaxDeviationBrightnessClamp;
DenoisingSettings.HalfStepValidation = sourceProfile.DenoisingSettings.HalfStepValidation;
DenoisingSettings.SpatialOcclusionValidation = sourceProfile.DenoisingSettings.SpatialOcclusionValidation;
DenoisingSettings.TemporalLightingValidation = sourceProfile.DenoisingSettings.TemporalLightingValidation;
DenoisingSettings.TemporalOcclusionValidation = sourceProfile.DenoisingSettings.TemporalOcclusionValidation;
DenoisingSettings.SpatialRadius = sourceProfile.DenoisingSettings.SpatialRadius;
DenoisingSettings.Adaptivity = sourceProfile.DenoisingSettings.Adaptivity;
DenoisingSettings.RecurrentBlur = sourceProfile.DenoisingSettings.RecurrentBlur;
DenoisingSettings.FireflySuppression = sourceProfile.DenoisingSettings.FireflySuppression;
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 4cfa758cbcc84a509b4fbdd3a170a992
timeCreated: 1745928800
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Data/Public/HTraceSSGIProfile.cs
uploadId: 840002

View File

@@ -0,0 +1,29 @@
//pipelinedefine
#define H_URP
using HTraceSSGI.Scripts.Data.Private;
using UnityEngine;
namespace HTraceSSGI.Scripts.Data.Public
{
/// <summary>
/// Change global HTrace SSGI settings, only for UseVolumes is disabled in HTrace SSGI Renderer Feature
/// </summary>
public static class HTraceSSGISettings
{
private static HTraceSSGIProfile _cachedProfile;
public static HTraceSSGIProfile ActiveProfile
{
get
{
return _cachedProfile;
}
}
public static void SetProfile(HTraceSSGIProfile profile)
{
_cachedProfile = profile;
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: d8283f6a3aff4a17b9edd5dfb9349cbe
timeCreated: 1761683456
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Data/Public/HTraceSSGISettings.cs
uploadId: 840002

View File

@@ -0,0 +1,187 @@
//pipelinedefine
#define H_URP
using System;
using HTraceSSGI.Scripts.Extensions;
using HTraceSSGI.Scripts.Globals;
using UnityEngine;
namespace HTraceSSGI.Scripts.Data.Public
{
[Serializable]
public class SSGISettings
{
// ----------------------------------------------- Visuals -----------------------------------------------
[SerializeField]
private float _backfaceLighting = 0f;
/// <summary>
///
/// </summary>
/// <value>[0.0;1.0]</value>
[HExtensions.HRangeAttribute(0.0f,1.0f)]
public float BackfaceLighting
{
get => _backfaceLighting;
set
{
if (Mathf.Abs(value - _backfaceLighting) < Mathf.Epsilon)
return;
_backfaceLighting = HExtensions.Clamp(value, typeof(SSGISettings), nameof(SSGISettings.BackfaceLighting));
}
}
[SerializeField]
private float _maxRayLength = 100f;
/// <summary>
///
/// </summary>
/// <value>[0.0;infinity]</value>
[HExtensions.HRangeAttribute(0.0f,float.MaxValue)]
public float MaxRayLength
{
get => _maxRayLength;
set
{
if (Mathf.Abs(value - _maxRayLength) < Mathf.Epsilon)
return;
_maxRayLength = HExtensions.Clamp(value, typeof(SSGISettings), nameof(SSGISettings.MaxRayLength));
}
}
public ThicknessMode ThicknessMode = ThicknessMode.Relative;
[SerializeField]
private float _thickness = 0.35f;
/// <summary>
///
/// </summary>
/// <value>[0.0;1.0]</value>
[HExtensions.HRangeAttribute(0.0f,1.0f)]
public float Thickness
{
get => _thickness;
set
{
if (Mathf.Abs(value - _thickness) < Mathf.Epsilon)
return;
_thickness = HExtensions.Clamp(value, typeof(SSGISettings), nameof(SSGISettings.Thickness));
}
}
[SerializeField]
private float _intensity = 1f;
/// <summary>
///
/// </summary>
/// <value>[0.1;5.0]</value>
[HExtensions.HRangeAttribute(0.1f,5.0f)]
public float Intensity
{
get => _intensity;
set
{
if (Mathf.Abs(value - _intensity) < Mathf.Epsilon)
return;
_intensity = HExtensions.Clamp(value, typeof(SSGISettings), nameof(SSGISettings.Intensity));
}
}
[SerializeField]
private float _falloff = 0.0f;
/// <summary>
///
/// </summary>
/// <value>[0.0;1.0]</value>
[HExtensions.HRangeAttribute(0f,1.0f)]
public float Falloff
{
get => _falloff;
set
{
if (Mathf.Abs(value - _falloff) < Mathf.Epsilon)
return;
_falloff = HExtensions.Clamp(value, typeof(SSGISettings), nameof(SSGISettings.Falloff));
}
}
// ----------------------------------------------- Quality -----------------------------------------------
// ----------------------------------------------- Tracing -----------------------------------------------
[SerializeField]
private int _rayCount = 4;
/// <summary>
///
/// </summary>
/// <value>[2;16]</value>
[HExtensions.HRangeAttribute(2,16)]
public int RayCount
{
get
{
return _rayCount;
}
set
{
if (value == _rayCount)
return;
_rayCount = HExtensions.Clamp(value, typeof(SSGISettings), nameof(SSGISettings.RayCount));
}
}
[SerializeField]
private int _stepCount = 32;
/// <summary>
///
/// </summary>
/// <value>[8;64]</value>
[HExtensions.HRangeAttribute(8,128)]
public int StepCount
{
get => _stepCount;
set
{
if (value == _stepCount)
return;
_stepCount = HExtensions.Clamp(value, typeof(SSGISettings), nameof(SSGISettings.StepCount));
}
}
[SerializeField]
public bool RefineIntersection = true;
[SerializeField]
public bool FullResolutionDepth = true;
// ----------------------------------------------- Rendering -----------------------------------------------
[SerializeField]
public bool Checkerboard = false;
[SerializeField]
private float _renderScale = 1f;
/// <summary>
///
/// </summary>
/// <value>[0.5;1.0]</value>
[HExtensions.HRangeAttribute(0.5f,1.0f)]
public float RenderScale
{
get => _renderScale;
set
{
if (Mathf.Abs(value - _renderScale) < Mathf.Epsilon)
return;
_renderScale = HExtensions.Clamp(value, typeof(SSGISettings), nameof(SSGISettings.RenderScale));
}
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: ae21e1c951f5f51488fabe310b39c1e8
timeCreated: 1731130646
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Data/Public/SSGISettings.cs
uploadId: 840002

View File

@@ -0,0 +1,122 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 11500000, guid: 4881f9a2c4d568047b316028d20a8dca, type: 3}
m_Name: Default
m_EditorClassIdentifier:
singleSceneMode: 1
dialogNoProbeVolumeInSetShown: 0
settings:
m_Version: 1
dilationSettings:
enableDilation: 0
dilationDistance: 0
dilationValidityThreshold: 0
dilationIterations: 0
squaredDistWeighting: 0
virtualOffsetSettings:
useVirtualOffset: 0
validityThreshold: 0
outOfGeoOffset: 0
searchMultiplier: 0
rayOriginBias: -0.001
collisionMask:
serializedVersion: 2
m_Bits: 4294967291
m_SceneGUIDs: []
obsoleteScenesToNotBake: []
m_LightingScenarios:
- Default
cellDescs:
m_Keys:
m_Values: []
m_SerializedPerSceneCellList: []
cellSharedDataAsset:
m_AssetGUID:
m_StreamableAssetPath:
m_ElementSize: 0
m_StreamableCellDescs:
m_Keys:
m_Values: []
m_Asset: {fileID: 0}
scenarios:
m_Keys: []
m_Values: []
cellBricksDataAsset:
m_AssetGUID:
m_StreamableAssetPath:
m_ElementSize: 0
m_StreamableCellDescs:
m_Keys:
m_Values: []
m_Asset: {fileID: 0}
cellSupportDataAsset:
m_AssetGUID:
m_StreamableAssetPath:
m_ElementSize: 0
m_StreamableCellDescs:
m_Keys:
m_Values: []
m_Asset: {fileID: 0}
chunkSizeInBricks: 0
maxCellPosition: {x: 0, y: 0, z: 0}
minCellPosition: {x: 0, y: 0, z: 0}
globalBounds:
m_Center: {x: 0, y: 0, z: 0}
m_Extent: {x: 0, y: 0, z: 0}
bakedSimplificationLevels: 3
bakedMinDistanceBetweenProbes: 1
bakedProbeOcclusion: 0
bakedSkyOcclusionValue: 0
bakedSkyShadingDirectionValue: 0
bakedProbeOffset: {x: 0, y: 0, z: 0}
bakedMaskCount: 1
bakedLayerMasks:
x: 0
y: 0
z: 0
w: 0
maxSHChunkCount: -1
L0ChunkSize: 0
L1ChunkSize: 0
L2TextureChunkSize: 0
ProbeOcclusionChunkSize: 0
sharedValidityMaskChunkSize: 0
sharedSkyOcclusionL0L1ChunkSize: 0
sharedSkyShadingDirectionIndicesChunkSize: 0
sharedDataChunkSize: 0
supportPositionChunkSize: 0
supportValidityChunkSize: 0
supportTouchupChunkSize: 0
supportLayerMaskChunkSize: 0
supportOffsetsChunkSize: 0
supportDataChunkSize: 0
lightingScenario: Default
version: 2
freezePlacement: 0
probeOffset: {x: 0, y: 0, z: 0}
simplificationLevels: 3
minDistanceBetweenProbes: 1
renderersLayerMask:
serializedVersion: 2
m_Bits: 4294967295
minRendererVolumeSize: 0.1
skyOcclusion: 0
skyOcclusionBakingSamples: 2048
skyOcclusionBakingBounces: 2
skyOcclusionAverageAlbedo: 0.6
skyOcclusionBackFaceCulling: 0
skyOcclusionShadingDirection: 0
useRenderingLayers: 0
renderingLayerMasks: []
m_SceneBakeData:
m_Keys: []
m_Values: []

View File

@@ -0,0 +1,15 @@
fileFormatVersion: 2
guid: 3efa5727399f12d458fa48a18a86be8d
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Default.asset
uploadId: 840002

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e230c412c545e65479e9662bc63b1d47
timeCreated: 1674796671

View File

@@ -0,0 +1,305 @@
#if UNITY_EDITOR
using System;
using System.Reflection;
using UnityEditor;
using UnityEngine;
namespace HTraceSSGI.Scripts.Editor
{
public class HDEditorUtilsWrapper
{
#region Public Methods
public static bool EnsureFrameSetting(int frameSettingsField)
{
try
{
Type hdEditorUtilsType = GetHDEditorUtilsType();
if (hdEditorUtilsType == null)
{
return false;
}
Type frameSettingsFieldType = GetFrameSettingsFieldType();
if (frameSettingsFieldType == null)
{
return false;
}
object frameSettingsFieldEnum = Enum.ToObject(frameSettingsFieldType, frameSettingsField);
MethodInfo ensureFrameSettingMethod = hdEditorUtilsType.GetMethod("EnsureFrameSetting",
BindingFlags.NonPublic | BindingFlags.Static,
null,
new Type[] { frameSettingsFieldType },
null);
if (ensureFrameSettingMethod == null)
{
return false;
}
object result = ensureFrameSettingMethod.Invoke(null, new object[] { frameSettingsFieldEnum });
return result != null && (bool)result;
}
catch (Exception ex)
{
return false;
}
}
public static void QualitySettingsHelpBox(string message, MessageType messageType, int expandableGroup, string propertyPath)
{
try
{
Type hdEditorUtilsType = GetHDEditorUtilsType();
if (hdEditorUtilsType == null)
{
return;
}
Type messageTypeEnum = typeof(MessageType);
Type expandableGroupType = GetExpandableGroupType();
if (expandableGroupType == null)
{
return;
}
object messageTypeValue = Enum.ToObject(messageTypeEnum, messageType);
object expandableGroupValue = Enum.ToObject(expandableGroupType, expandableGroup);
MethodInfo qualitySettingsHelpBoxMethod = hdEditorUtilsType.GetMethod("QualitySettingsHelpBox",
BindingFlags.NonPublic | BindingFlags.Static,
null,
new Type[] { typeof(string), messageTypeEnum, expandableGroupType, typeof(string) },
null);
if (qualitySettingsHelpBoxMethod == null)
{
return;
}
qualitySettingsHelpBoxMethod.Invoke(null, new object[] { message, messageTypeValue, expandableGroupValue, propertyPath });
}
catch (Exception ex)
{
//Debug.LogError($"Error calling HDEditorUtils.QualitySettingsHelpBox: {ex.Message}");
}
}
public static void QualitySettingsHelpBoxWithSection(string message, MessageType messageType, int expandableGroup, int expandableSection, string propertyPath)
{
try
{
Type hdEditorUtilsType = GetHDEditorUtilsType();
if (hdEditorUtilsType == null)
{
Debug.LogError("Failed to find HDEditorUtils type");
return;
}
Type messageTypeEnum = typeof(MessageType);
Type expandableGroupType = GetExpandableGroupType();
if (expandableGroupType == null)
{
Debug.LogError("Failed to find ExpandableGroup type");
return;
}
object messageTypeValue = Enum.ToObject(messageTypeEnum, messageType);
object expandableGroupValue = Enum.ToObject(expandableGroupType, expandableGroup);
MethodInfo[] methods = hdEditorUtilsType.GetMethods(BindingFlags.NonPublic | BindingFlags.Static);
MethodInfo genericMethod = null;
foreach (var method in methods)
{
if (method.Name == "QualitySettingsHelpBox" &&
method.IsGenericMethodDefinition &&
method.GetParameters().Length == 5)
{
genericMethod = method;
break;
}
}
if (genericMethod == null)
{
Debug.LogError("Failed to find generic QualitySettingsHelpBox method");
return;
}
Type expandableLightingType = GetExpandableLightingType();
if (expandableLightingType == null)
{
expandableLightingType = expandableGroupType;
}
MethodInfo concreteMethod = genericMethod.MakeGenericMethod(expandableLightingType);
object expandableSectionValue = Enum.ToObject(expandableLightingType, expandableSection);
concreteMethod.Invoke(null, new object[] { message, messageTypeValue, expandableGroupValue, expandableSectionValue, propertyPath });
}
catch (Exception ex)
{
Debug.LogError($"Error calling HDEditorUtils.QualitySettingsHelpBox with section: {ex.Message}");
}
}
#endregion
#region Helper Methods
private static Type GetHDEditorUtilsType()
{
Type hdEditorUtilsType = Type.GetType("UnityEditor.Rendering.HighDefinition.HDEditorUtils, Unity.RenderPipelines.HighDefinition.Editor");
if (hdEditorUtilsType == null)
{
var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
hdEditorUtilsType = assembly.GetType("UnityEditor.Rendering.HighDefinition.HDEditorUtils");
if (hdEditorUtilsType != null) break;
}
}
return hdEditorUtilsType;
}
private static Type GetFrameSettingsFieldType()
{
Type frameSettingsFieldType = Type.GetType("UnityEngine.Rendering.HighDefinition.FrameSettingsField, Unity.RenderPipelines.HighDefinition.Runtime");
if (frameSettingsFieldType == null)
{
var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
frameSettingsFieldType = assembly.GetType("UnityEngine.Rendering.HighDefinition.FrameSettingsField");
if (frameSettingsFieldType != null) break;
}
}
return frameSettingsFieldType;
}
private static Type GetExpandableGroupType()
{
Type hdrpUIType = GetHDRPUIType();
if (hdrpUIType == null) return null;
return hdrpUIType.GetNestedType("ExpandableGroup", BindingFlags.NonPublic | BindingFlags.Public);
}
private static Type GetExpandableLightingType()
{
Type hdrpUIType = GetHDRPUIType();
if (hdrpUIType == null) return null;
return hdrpUIType.GetNestedType("ExpandableLighting", BindingFlags.NonPublic | BindingFlags.Public);
}
private static Type GetHDRPUIType()
{
Type hdrpUIType = Type.GetType("UnityEditor.Rendering.HighDefinition.HDRenderPipelineUI, Unity.RenderPipelines.HighDefinition.Editor");
if (hdrpUIType == null)
{
var assemblies = System.AppDomain.CurrentDomain.GetAssemblies();
foreach (var assembly in assemblies)
{
hdrpUIType = assembly.GetType("UnityEditor.Rendering.HighDefinition.HDRenderPipelineUI");
if (hdrpUIType != null) break;
}
}
return hdrpUIType;
}
public static int GetFrameSettingsFieldValue(string fieldName)
{
try
{
Type frameSettingsFieldType = GetFrameSettingsFieldType();
if (frameSettingsFieldType == null)
return -1;
object enumValue = Enum.Parse(frameSettingsFieldType, fieldName);
return (int)enumValue;
}
catch (Exception ex)
{
Debug.LogError($"Error when get FrameSettingsField.{fieldName}: {ex.Message}");
return -1;
}
}
// internal enum ExpandableGroup
// {
// Rendering = 1 << 4,
// Lighting = 1 << 5,
// LightingTiers = 1 << 6,
// Material = 1 << 7,
// PostProcess = 1 << 8,
// PostProcessTiers = 1 << 9,
// XR = 1 << 10,
// VirtualTexturing = 1 << 11,
// Volumes = 1 << 12
// }
public static int GetExpandableGroupValue(string groupName)
{
try
{
Type expandableGroupType = GetExpandableGroupType();
if (expandableGroupType == null)
return -1;
object enumValue = Enum.Parse(expandableGroupType, groupName);
return (int)enumValue;
}
catch (Exception ex)
{
Debug.LogError($"Error when get ExpandableGroup.{groupName}: {ex.Message}");
return -1;
}
}
// internal enum ExpandableLighting
// {
// Volumetric = 1 << 0,
// ProbeVolume = 1 << 1,
// Cookie = 1 << 2,
// Reflection = 1 << 3,
// Sky = 1 << 4,
// // Illegal index 1 << 5 since parent Lighting section index is using it
// LightLoop = 1 << 6,
// Shadow = 1 << 7
// }
public static int GetExpandableLightingValue(string lightingName)
{
try
{
Type expandableLightingType = GetExpandableLightingType();
if (expandableLightingType == null)
return -1;
object enumValue = Enum.Parse(expandableLightingType, lightingName);
return (int)enumValue;
}
catch (Exception ex)
{
Debug.LogError($"Error when get ExpandableLighting.{lightingName}: {ex.Message}");
return -1;
}
}
#endregion
}
}
#endif

View File

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

View File

@@ -0,0 +1,133 @@
#if UNITY_EDITOR
using UnityEditor;
using UnityEngine;
namespace HTraceSSGI.Scripts.Editor
{
internal static class HEditorStyles
{
public static float defaultLineSpace = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
public static float additionalLineSpace = 10f;
public static float helpBoxHeight = EditorGUIUtility.singleLineHeight * 2;
public static float checkBoxOffsetWidth = 15f;
public static float checkBoxWidth = 15f;
public static float tabOffset = 8f;
// Buttons name
public const string FixButtonName = "Fix";
public const string ChangeButtonName = "Change";
public const string OpenButtonName = "Open";
// Debug Tab
public static GUIContent DebugContent = new GUIContent("Debug");
public static GUIContent hTraceLayerContent = new GUIContent("HTrace Layer", "Excludes objects from HTrace rendering on a per-layer basis");
// Foldout names
public static GUIContent GlobalSettings = new GUIContent("Global Settings");
public static GUIContent PipelineIntegration = new GUIContent("Pipeline Integration");
public static GUIContent Visuals = new GUIContent("Visuals");
public static GUIContent Quality = new GUIContent("Quality");
public static GUIContent Tracing = new GUIContent("Tracing");
public static GUIContent Rendering = new GUIContent("Rendering");
public static GUIContent Denoising = new GUIContent("Denoising");
public static GUIContent ReSTIRValidation = new GUIContent("ReSTIR Validation");
public static GUIContent ValidationTypes = new GUIContent("Validation Types:");
public static GUIContent SpatialFilter = new GUIContent("Spatial Filter");
public static GUIContent Debug = new GUIContent("Debug");
// General Tab
public static GUIContent DebugModeContent = new GUIContent("Debug Mode", "Visualizes the debug mode for different rendering components of H-Trace.");
public static GUIContent HBuffer = new GUIContent("Buffer", "Visualizes the debug mode for different buffers");
// Visuals
public static GUIContent ThicknessMode = new GUIContent("Thickness Mode", "Method for thickness estimation.");
public static GUIContent Thickness = new GUIContent("Thickness", "Virtual object thickness for ray intersections.");
public static GUIContent BackfaceLighting = new GUIContent("Backface Lighting", "");
public static GUIContent MaxRayLength = new GUIContent("Max Ray Length", "Maximum ray distance in meters.");
public static GUIContent FallbackType = new("Fallback", "Method used when a ray misses.");
public static GUIContent SkyIntensity = new("Sky Intensity", "Brightness of Sky used for ray misses.");
public static GUIContent ExcludeCastingMask = new("Exclude Casting", "Prevents objects from casting GI.");
public static GUIContent ExcludeReceivingMask = new("Exclude Receiving", "Prevents objects from receiving screen-space GI.");
public static GUIContent NormalBias = new("APV Normal Bias");
public static GUIContent ViewBias = new("APV View Bias");
public static GUIContent SamplingNoise = new("APV Sampling Noise");
public static GUIContent DenoiseFallback = new("Denoise Fallback", "Includes fallback lighting in denoising.");
public static GUIContent Intensity = new GUIContent("Intensity");
public static GUIContent Falloff = new GUIContent("Falloff", "Softens indirect lighting over distance.");
// Quality tab
// Tracing
public static GUIContent RayCount = new GUIContent("Ray Count", "Number of rays per pixel.");
public static GUIContent StepCount = new GUIContent("Step Count", "Number of steps per ray.");
public static GUIContent RefineIntersection = new GUIContent("Refine Intersection", "Extra check to confirm hits.");
public static GUIContent FullResolutionDepth = new GUIContent("Full Resolution Depth", "Uses full-res depth buffer for tracing.");
//Rendering
public static GUIContent Checkerboard = new GUIContent("Checkerboard");
public static GUIContent RenderScale = new GUIContent("Render Scale", "Local render scale of SSGI.");
// Denoising tab
public static GUIContent BrightnessClamp = new("Brightness Clamp", "Method for clamping brightness at hit point.");
public static GUIContent MaxValueBrightnessClamp = new(" Max Value", "Maximum brightness allowed at hit points.");
public static GUIContent MaxDeviationBrightnessClamp = new(" Max Deviation", "Maximum standard deviation for brightness allowed at hit points.");
// ReSTIR Validation
public static GUIContent HalfStepValidation = new("Half-Step Tracing", "Halves validation ray steps.");
public static GUIContent SpatialOcclusionValidation = new("Spatial Occlusion", "Preserves detail, reduces leaks during blur.");
public static GUIContent TemporalLightingValidation = new("Temporal Lighting", "Reacts faster to changing lights.");
public static GUIContent TemporalOcclusionValidation = new("Temporal Occlusion", "Reacts faster to moving shadows.");
// Spatial Fliter
public static GUIContent SpatialRadius = new GUIContent("Radius", "Width of spatial filter.");
public static GUIContent Adaptivity = new GUIContent("Adaptivity", "Shrinks filter radius in geometry corners to preserve detail.");
public static GUIContent RecurrentBlur = new GUIContent("Recurrent Blur", "Stronger blur with low cost, less temporal reactivity.");
public static GUIContent FireflySuppression = new GUIContent("Firefly Suppression", "Removes bright outliers before denoising.");
public static GUIStyle bold = new GUIStyle()
{
alignment = TextAnchor.MiddleLeft,
margin = new RectOffset(),
padding = new RectOffset(2, 0, 0, 0),
fontSize = 12,
normal = new GUIStyleState()
{
textColor = new Color(0.903f, 0.903f, 0.903f, 1f),
},
fontStyle = FontStyle.Bold,
};
public static GUIStyle hiddenFoldout = new GUIStyle()
{
alignment = TextAnchor.MiddleLeft,
margin = new RectOffset(),
padding = new RectOffset(),
fontSize = 12,
normal = new GUIStyleState()
{
//textColor = new Color(0.703f, 0.703f, 0.703f, 1f), //default color
textColor = new Color(0.500f, 0.500f, 0.500f, 1f),
},
fontStyle = FontStyle.Bold,
};
public static GUIStyle headerFoldout = new GUIStyle()
{
alignment = TextAnchor.MiddleLeft,
margin = new RectOffset(),
padding = new RectOffset(),
fontSize = 12,
normal = new GUIStyleState()
{
textColor = new Color(0.903f, 0.903f, 0.903f, 1f),
},
fontStyle = FontStyle.Bold,
};
//buttons gui styles
public static Color warningBackgroundColor = new Color(1,1, 0);
public static Color warningColor = new Color(1, 1, 1);
public static GUIStyle foldout = EditorStyles.foldout;
}
}
#endif

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 7b0103dbde10dd04eb57da14de01f702
timeCreated: 1675231640
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Editor/HEditorStyles.cs
uploadId: 840002

View File

@@ -0,0 +1,243 @@
#if UNITY_EDITOR
using System;
using UnityEditor;
using UnityEditor.AnimatedValues;
using UnityEngine;
namespace HTraceSSGI.Scripts.Editor
{
public static class HEditorUtils
{
private static GUIStyle s_linkStyle;
private static GUIStyle s_separatorStyle;
public static void DrawLinkRow(params (string label, Action onClick)[] links)
{
if (s_linkStyle == null)
{
s_linkStyle = new GUIStyle(GUI.skin.label)
{
fontStyle = FontStyle.Bold,
fontSize = 10,
alignment = TextAnchor.MiddleLeft,
normal = { textColor = new Color(0.35f, 0.55f, 0.75f) },
hover = { textColor = EditorGUIUtility.isProSkin ? Color.white : Color.black },
// padding = new RectOffset(0, 0, 0, 0),
// margin = new RectOffset(0, 0, 0, 0)
};
}
if (s_separatorStyle == null)
{
s_separatorStyle = new GUIStyle(GUI.skin.label)
{
fontSize = 12,
alignment = TextAnchor.MiddleCenter,
normal = { textColor = new Color(0.9f, 0.9f, 0.9f,1f) },
padding = new RectOffset(0, 0, 1, 0),
margin = new RectOffset(0, 0, 0, 0)
};
}
float maxWidth = EditorGUIUtility.currentViewWidth - 40; // scroll
float currentLineWidth = 0;
GUILayout.BeginVertical();
GUILayout.BeginHorizontal();
for (int i = 0; i < links.Length; i++)
{
var content = new GUIContent(links[i].label);
Vector2 size = s_linkStyle.CalcSize(content);
float neededWidth = size.x + 8; // text + |
// new line
if (currentLineWidth + neededWidth > maxWidth)
{
GUILayout.EndHorizontal();
GUILayout.BeginHorizontal();
currentLineWidth = 0;
}
if (DrawClickableButton(links[i].label, onClick: links[i].onClick))
{
// nothing here
}
currentLineWidth += size.x;
if (i < links.Length - 1)
{
GUILayout.Space(8);
// GUILayout.Label("|", s_separatorStyle, GUILayout.Width(12));
// GUILayout.Space(2);
currentLineWidth += 8; // width |
}
}
GUILayout.EndHorizontal();
GUILayout.EndVertical();
}
public static bool DrawClickableButton(string text, Action onClick = null, GUIStyle baseStyle = null)
{
if (s_linkStyle == null)
{
s_linkStyle = new GUIStyle(baseStyle ?? GUI.skin.label)
{
fontStyle = FontStyle.Bold,
fontSize = 10,
alignment = TextAnchor.MiddleLeft,
normal = { textColor = new Color(0.35f, 0.55f, 0.75f) },
hover = { textColor = EditorGUIUtility.isProSkin ? Color.white : Color.black }
};
}
Rect rect = GUILayoutUtility.GetRect(new GUIContent(text), s_linkStyle, GUILayout.ExpandWidth(false));
bool clicked = GUI.Button(rect, text, s_linkStyle);
EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
if (clicked)
onClick?.Invoke();
return clicked;
}
public static bool DrawClickableLink(string text, string url, bool useEmoji = false, GUIStyle baseStyle = null)
{
if (s_linkStyle == null)
{
s_linkStyle = new GUIStyle(baseStyle ?? GUI.skin.label)
{
fontStyle = FontStyle.Bold,
fontSize = 10,
//normal = { textColor = new Color(0.20f, 0.50f, 0.80f) },
normal = { textColor = new Color(0.35f, 0.55f, 0.75f) },
hover = { textColor = EditorGUIUtility.isProSkin ? Color.white : Color.black }
};
}
if (useEmoji)
text += " \U0001F517"; //\U0001F310
bool clicked = GUILayout.Button(text, s_linkStyle, GUILayout.ExpandWidth(false));
EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link);
if (clicked)
{
Application.OpenURL(url);
}
return clicked;
}
public readonly struct FoldoutScope : IDisposable
{
private readonly bool wasIndent;
public FoldoutScope(AnimBool value, out bool shouldDraw, string label, bool indent = true, SerializedProperty toggle = null)
{
value.target = Foldout(value.target, label, toggle);
shouldDraw = EditorGUILayout.BeginFadeGroup(value.faded);
if (shouldDraw && indent)
{
Indent();
wasIndent = true;
}
else
{
wasIndent = false;
}
}
public void Dispose()
{
if (wasIndent)
EndIndent();
EditorGUILayout.EndFadeGroup();
}
}
public static void HorizontalLine(float height = 1, float width = -1, Vector2 margin = new Vector2())
{
GUILayout.Space(margin.x);
var rect = EditorGUILayout.GetControlRect(false, height);
if (width > -1)
{
var centerX = rect.width / 2;
rect.width = width;
rect.x += centerX - width / 2;
}
Color color = EditorStyles.label.active.textColor;
color.a = 0.5f;
EditorGUI.DrawRect(rect, color);
GUILayout.Space(margin.y);
}
public static bool Foldout(bool value, string label, SerializedProperty toggle = null)
{
bool _value;
EditorGUILayout.BeginVertical(EditorStyles.helpBox);
EditorGUILayout.BeginHorizontal();
if (toggle != null && !toggle.boolValue)
{
EditorGUI.BeginDisabledGroup(true);
_value = EditorGUILayout.Toggle(value, EditorStyles.foldout);
EditorGUI.EndDisabledGroup();
_value = false;
}
else
{
_value = EditorGUILayout.Toggle(value, EditorStyles.foldout);
}
if (toggle != null)
{
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(toggle, GUIContent.none, GUILayout.Width(20));
if (EditorGUI.EndChangeCheck() && toggle.boolValue)
_value = true;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndVertical();
var rect = GUILayoutUtility.GetLastRect();
rect.x += 20;
rect.width -= 20;
if (toggle != null && !toggle.boolValue)
{
EditorGUI.BeginDisabledGroup(true);
EditorGUI.LabelField(rect, label, EditorStyles.boldLabel);
EditorGUI.EndDisabledGroup();
}
else
{
EditorGUI.LabelField(rect, label, EditorStyles.boldLabel);
}
return _value;
}
public static void Indent()
{
EditorGUILayout.BeginHorizontal();
GUILayout.Space(16);
EditorGUILayout.BeginVertical();
}
public static void EndIndent()
{
GUILayout.Space(10);
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
}
}
}
#endif

View File

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

View File

@@ -0,0 +1,140 @@
//pipelinedefine
#define H_URP
#if UNITY_EDITOR
using System.IO;
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Data.Public;
using UnityEditor;
using UnityEngine;
using HTraceSSGI.Scripts.Infrastructure.URP;
namespace HTraceSSGI.Scripts.Editor
{
public enum HTraceSSGIPreset
{
Performance = 1,
Optimized = 2,
Balanced = 3,
Quality = 4,
}
[CustomEditor(typeof(HTraceSSGI))]
public class HTraceSSGIEditor : UnityEditor.Editor
{
private SerializedProperty _profile;
HTraceSSGIProfile _cachedProfile;
UnityEditor.Editor _cachedProfileEditor;
static GUIStyle _boxStyle;
private void OnEnable()
{
_profile = serializedObject.FindProperty("Profile");
}
public override void OnInspectorGUI()
{
if (_boxStyle == null)
{
_boxStyle = new GUIStyle(GUI.skin.box);
_boxStyle.padding = new RectOffset(15, 10, 5, 5);
}
if (HTraceSSGIRendererFeature.IsUseVolumes == true)
{
EditorGUILayout.HelpBox("\"Use Volumes\" checkbox in the HTrace SSGI Renderer feature is enabled, use the HTraceSSGI volume override in your scenes.", MessageType.Warning, wide: true);
return;
}
EditorGUILayout.PropertyField(_profile);
EditorGUILayout.Space(5);
if (_profile.objectReferenceValue != null)
{
if (_cachedProfile != _profile.objectReferenceValue)
{
_cachedProfile = null;
}
if (_cachedProfile == null)
{
_cachedProfile = (HTraceSSGIProfile)_profile.objectReferenceValue;
_cachedProfileEditor = CreateEditor(_profile.objectReferenceValue);
}
EditorGUILayout.BeginVertical();
_cachedProfileEditor.OnInspectorGUI();
EditorGUILayout.Separator();
if (GUILayout.Button("Save As New Profile"))
{
ExportProfile();
}
EditorGUILayout.EndVertical();
}
else
{
EditorGUILayout.HelpBox("Create or assign a profile.", MessageType.Info);
if (GUILayout.Button("New Profile"))
{
CreateProfile();
}
}
serializedObject.ApplyModifiedProperties();
}
void CreateProfile() {
var fp = CreateInstance<HTraceSSGIProfile>();
fp.name = "New HTrace SSGI Profile";
string path = "Assets";
foreach (Object obj in Selection.GetFiltered(typeof(Object), SelectionMode.Assets)) {
path = AssetDatabase.GetAssetPath(obj);
if (File.Exists(path)) {
path = Path.GetDirectoryName(path);
}
break;
}
string fullPath = path + "/" + fp.name + ".asset";
fullPath = AssetDatabase.GenerateUniqueAssetPath(fullPath);
AssetDatabase.CreateAsset(fp, fullPath);
AssetDatabase.SaveAssets();
_profile.objectReferenceValue = fp;
EditorGUIUtility.PingObject(fp);
}
void ExportProfile() {
var fp = (HTraceSSGIProfile)_profile.objectReferenceValue;
var newProfile = Instantiate(fp);
string path = AssetDatabase.GetAssetPath(fp);
string fullPath = path;
if (string.IsNullOrEmpty(path)) {
path = "Assets";
foreach (Object obj in Selection.GetFiltered(typeof(Object), SelectionMode.Assets)) {
path = AssetDatabase.GetAssetPath(obj);
if (File.Exists(path)) {
path = Path.GetDirectoryName(path);
}
break;
}
fullPath = path + "/" + fp.name + ".asset";
}
fullPath = AssetDatabase.GenerateUniqueAssetPath(fullPath);
AssetDatabase.CreateAsset(newProfile, fullPath);
AssetDatabase.SaveAssets();
_profile.objectReferenceValue = newProfile;
EditorGUIUtility.PingObject(fp);
}
}
}
#endif

View File

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

View File

@@ -0,0 +1,456 @@
//pipelinedefine
#define H_URP
#if UNITY_EDITOR
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Data.Public;
using HTraceSSGI.Scripts.Editor.WindowsAndMenu;
using HTraceSSGI.Scripts.Globals;
using UnityEditor;
using UnityEditor.AnimatedValues;
using UnityEditor.Rendering;
using UnityEngine;
namespace HTraceSSGI.Scripts.Editor
{
[CustomEditor(typeof(HTraceSSGIProfile))]
internal class HTraceSSGIProfileEditor : UnityEditor.Editor
{
HTraceSSGIPreset _preset = HTraceSSGIPreset.Balanced;
bool _globalSettingsTab = true;
bool _qualityTab = true;
bool _denoisingTab = true;
bool _debugTab = true;
private AnimBool AnimBoolGeneralTab;
private AnimBool AnimBoolQualityTab;
private AnimBool AnimBoolDenoisingTab;
private AnimBool AnimBoolDebugTab;
private AnimBool AnimBoolEMPTY;
bool _showPipelineIntegration = true;
bool _showVisualsArea = true;
bool _showTracingArea = true;
bool _showRenderingArea = true;
bool _showRestirValidationArea = true;
bool _showSpatialArea = true;
SerializedProperty GeneralSettings;
SerializedProperty SSGISettings;
SerializedProperty DenoisingSettings;
SerializedProperty DebugSettings;
// Debug Data
SerializedProperty EnableDebug;
SerializedProperty HTraceLayer;
// General Tab
SerializedProperty DebugMode;
SerializedProperty HBuffer;
SerializedProperty MainCamera;
SerializedProperty MetallicIndirectFallback;
SerializedProperty AmbientOverride;
SerializedProperty Multibounce;
SerializedProperty ExcludeReceivingMask;
SerializedProperty ExcludeCastingMask;
SerializedProperty FallbackType;
SerializedProperty SkyIntensity;
//Apv
SerializedProperty ViewBias;
SerializedProperty NormalBias;
SerializedProperty SamplingNoise;
SerializedProperty DenoiseFallback;
// Visuals
SerializedProperty BackfaceLighting;
SerializedProperty MaxRayLength;
SerializedProperty ThicknessMode;
SerializedProperty Thickness;
SerializedProperty Intensity;
SerializedProperty Falloff;
// Quality tab
// Tracing
SerializedProperty RayCount;
SerializedProperty StepCount;
SerializedProperty RefineIntersection;
SerializedProperty FullResolutionDepth;
// Rendering
SerializedProperty Checkerboard;
SerializedProperty RenderScale;
// Denoising tab
SerializedProperty BrightnessClamp;
SerializedProperty MaxValueBrightnessClamp;
SerializedProperty MaxDeviationBrightnessClamp;
// Temporal
SerializedProperty HalfStepValidation;
SerializedProperty SpatialOcclusionValidation;
SerializedProperty TemporalLightingValidation;
SerializedProperty TemporalOcclusionValidation;
// Spatial Filter
SerializedProperty SpatialRadius;
SerializedProperty Adaptivity;
// SerializedProperty SpatialPassCount;
SerializedProperty RecurrentBlur;
SerializedProperty FireflySuppression;
// Debug DEVS
SerializedProperty ShowBowels;
SerializedProperty ShowFullDebugLog;
SerializedProperty TestCheckBox1;
SerializedProperty TestCheckBox2;
SerializedProperty TestCheckBox3;
private void OnEnable()
{
PropertiesRelative();
AnimBoolGeneralTab = new AnimBool(_globalSettingsTab);
AnimBoolGeneralTab.valueChanged.RemoveAllListeners();
AnimBoolGeneralTab.valueChanged.AddListener(Repaint);
AnimBoolQualityTab = new AnimBool(_qualityTab);
AnimBoolQualityTab.valueChanged.RemoveAllListeners();
AnimBoolQualityTab.valueChanged.AddListener(Repaint);
AnimBoolDenoisingTab = new AnimBool(_denoisingTab);
AnimBoolDenoisingTab.valueChanged.RemoveAllListeners();
AnimBoolDenoisingTab.valueChanged.AddListener(Repaint);
AnimBoolDebugTab = new AnimBool(_debugTab);
AnimBoolDebugTab.valueChanged.RemoveAllListeners();
AnimBoolDebugTab.valueChanged.AddListener(Repaint);
AnimBoolEMPTY = new AnimBool(false);
}
protected virtual void OnSceneGUI()
{
HTraceSSGI hTraceSSGI = (HTraceSSGI)target;
}
public override void OnInspectorGUI()
{
serializedObject.Update();
UpdateStandartStyles();
// base.OnInspectorGUI();
//return;
AnimBoolEMPTY = new AnimBool(false);
Color standartBackgroundColor = GUI.backgroundColor;
Color standartColor = GUI.color;
WarningsHandle();
// ------------------------------------- Global settings ----------------------------------------------------------
using (new HEditorUtils.FoldoutScope(AnimBoolGeneralTab, out var shouldDraw, "Global Settings"))
{
_globalSettingsTab = shouldDraw;
if (shouldDraw)
{
EditorGUILayout.Space(3f);
EditorGUILayout.BeginHorizontal();
_preset = (HTraceSSGIPreset)EditorGUILayout.EnumPopup(new GUIContent("Preset"), _preset);
if (GUILayout.Button("Apply", GUILayout.Width(60)))
{
HTraceSSGIProfile profileLocal = HTraceSSGISettings.ActiveProfile;
profileLocal.ApplyPreset(_preset);
EditorUtility.SetDirty(target);
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.Space(3f);
serializedObject.Update();
EditorGUILayout.PropertyField(DebugMode, HEditorStyles.DebugModeContent);
if (DebugMode.enumValueIndex == 1)
EditorGUILayout.PropertyField(HBuffer, HEditorStyles.HBuffer);
EditorGUILayout.Space(5f);
#if UNITY_2023_3_OR_NEWER
EditorGUILayout.PropertyField(ExcludeCastingMask, HEditorStyles.ExcludeCastingMask);
EditorGUILayout.PropertyField(ExcludeReceivingMask, HEditorStyles.ExcludeReceivingMask);
#endif
EditorGUILayout.Space(3f);
EditorGUILayout.PropertyField(FallbackType, HEditorStyles.FallbackType);
if ((Globals.FallbackType)FallbackType.enumValueIndex == Globals.FallbackType.Sky)
EditorGUILayout.Slider(SkyIntensity, 0.0f, 1.0f, HEditorStyles.SkyIntensity);
_showPipelineIntegration = EditorGUILayout.BeginFoldoutHeaderGroup(_showPipelineIntegration, "Pipeline Integration");
if (_showPipelineIntegration)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(MetallicIndirectFallback, new GUIContent("Metallic Indirect Fallback"));
EditorGUILayout.PropertyField(AmbientOverride, new GUIContent("Ambient Override"));
if (RenderSettings.ambientIntensity > 1.0f && AmbientOverride.boolValue == true)
EditorGUILayout.HelpBox("Ambient Override may not work correctly when the Environment Lighting Multiplier is set above 1 !", MessageType.Warning);
EditorGUILayout.PropertyField(Multibounce, new GUIContent("Multibounce"));
EditorGUI.indentLevel--;
EditorGUILayout.Space(3f);
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(3f);
{
_showVisualsArea = EditorGUILayout.BeginFoldoutHeaderGroup(_showVisualsArea, "Visuals");
if (_showVisualsArea)
{
EditorGUI.indentLevel++;
EditorGUILayout.Slider(BackfaceLighting, 0.0f, 1.0f, HEditorStyles.BackfaceLighting);
EditorGUILayout.PropertyField(MaxRayLength, HEditorStyles.MaxRayLength);
if (MaxRayLength.floatValue < 0)
MaxRayLength.floatValue = 0f;
EditorGUILayout.PropertyField(ThicknessMode, HEditorStyles.ThicknessMode);
EditorGUILayout.Slider(Thickness, 0.0f, 1.0f, HEditorStyles.Thickness);
EditorGUILayout.Slider(Intensity, 0.1f, 5.0f, HEditorStyles.Intensity);
EditorGUILayout.Slider(Falloff, 0.0f, 1.0f, HEditorStyles.Falloff);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(3f);
}
}
}
// ------------------------------------- Quality ----------------------------------------------------------
using (new HEditorUtils.FoldoutScope(AnimBoolQualityTab, out var shouldDraw, "Quality"))
{
_qualityTab = shouldDraw;
if (shouldDraw)
{
EditorGUILayout.Space(3f);
_showTracingArea = EditorGUILayout.BeginFoldoutHeaderGroup(_showTracingArea, "Tracing");
if (_showTracingArea)
{
EditorGUI.indentLevel++;
RayCount.intValue = EditorGUILayout.IntSlider(HEditorStyles.RayCount, RayCount.intValue, 2, 16);
StepCount.intValue = EditorGUILayout.IntSlider(HEditorStyles.StepCount, StepCount.intValue, 8, 64);
EditorGUILayout.PropertyField(RefineIntersection, HEditorStyles.RefineIntersection);
EditorGUILayout.PropertyField(FullResolutionDepth, HEditorStyles.FullResolutionDepth);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(5f);
_showRenderingArea = EditorGUILayout.BeginFoldoutHeaderGroup(_showRenderingArea, "Rendering");
if (_showRenderingArea)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(Checkerboard, HEditorStyles.Checkerboard);
EditorGUILayout.Slider(RenderScale, 0.5f, 1.0f, HEditorStyles.RenderScale);
RenderScale.floatValue = RenderScale.floatValue.RoundToCeilTail(2);
if (Mathf.Approximately(RenderScale.floatValue, 1.0f) == false)
{
EditorGUI.indentLevel++;
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(3f);
}
}
// ------------------------------------- Denoising ----------------------------------------------------------
using (new HEditorUtils.FoldoutScope(AnimBoolDenoisingTab, out var shouldDraw, "Denoising"))
{
_denoisingTab = shouldDraw;
if (shouldDraw)
{
EditorGUILayout.Space(3f);
EditorGUILayout.PropertyField(BrightnessClamp, HEditorStyles.BrightnessClamp);
if ((BrightnessClamp)BrightnessClamp.enumValueIndex == Globals.BrightnessClamp.Manual)
EditorGUILayout.Slider(MaxValueBrightnessClamp, 1.0f, 30.0f, HEditorStyles.MaxValueBrightnessClamp);
if ((BrightnessClamp)BrightnessClamp.enumValueIndex == Globals.BrightnessClamp.Automatic)
EditorGUILayout.Slider(MaxDeviationBrightnessClamp, 1.0f, 5.0f, HEditorStyles.MaxDeviationBrightnessClamp);
EditorGUILayout.Space(5f);
_showRestirValidationArea = EditorGUILayout.BeginFoldoutHeaderGroup(_showRestirValidationArea, "ReSTIR Validation");
if (_showRestirValidationArea)
{
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(HalfStepValidation, HEditorStyles.HalfStepValidation);
EditorGUILayout.Space(3f);
EditorGUILayout.LabelField(new GUIContent("Validation Types:"), HEditorStyles.bold);
EditorGUILayout.PropertyField(SpatialOcclusionValidation, HEditorStyles.SpatialOcclusionValidation);
EditorGUILayout.PropertyField(TemporalLightingValidation, HEditorStyles.TemporalLightingValidation);
EditorGUILayout.PropertyField(TemporalOcclusionValidation, HEditorStyles.TemporalOcclusionValidation);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(5f);
_showSpatialArea = EditorGUILayout.BeginFoldoutHeaderGroup(_showSpatialArea, "Spatial Filter");
if (_showSpatialArea)
{
EditorGUI.indentLevel++;
EditorGUILayout.Slider(SpatialRadius, 0.0f, 1.0f, HEditorStyles.SpatialRadius);
EditorGUILayout.Slider(Adaptivity, 0.0f, 1.0f, HEditorStyles.Adaptivity);
// SpatialPassCount.intValue = EditorGUILayout.IntSlider(HEditorStyles.SpatialPassCount, SpatialPassCount.intValue, 0, 4);
EditorGUILayout.PropertyField(RecurrentBlur, HEditorStyles.RecurrentBlur);
EditorGUILayout.PropertyField(FireflySuppression, HEditorStyles.FireflySuppression);
EditorGUI.indentLevel--;
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(3f);
}
}
// ------------------------------------- Debug settings ----------------------------------------------------------
HEditorUtils.HorizontalLine(1f);
EditorGUILayout.Space(3f);
//HEditorUtils.DrawClickableLink($"HTrace AO Version: {HNames.HTRACE_AO_VERSION}", HNames.HTRACE_AO_DOCUMENTATION_LINK, true);
HEditorUtils.DrawLinkRow(
($"Documentation (v." + HNames.HTRACE_SSGI_VERSION + ")", () => Application.OpenURL(HNames.HTRACE_SSGI_DOCUMENTATION_LINK)),
("Discord", () => Application.OpenURL(HNames.HTRACE_DISCORD_LINK)),
("Bug report", () => HBugReporterWindow.ShowWindow())
);
GUI.backgroundColor = standartBackgroundColor;
GUI.color = standartColor;
serializedObject.ApplyModifiedProperties();
}
private void WarningsHandle()
{
}
private void DebugPart()
{
using (new HEditorUtils.FoldoutScope(AnimBoolDebugTab, out var shouldDraw, HEditorStyles.DebugContent.text, toggle: EnableDebug))
{
_debugTab = shouldDraw;
if (shouldDraw)
{
//EditorGUILayout.PropertyField(EnableDebug, HEditorStyles.OcclusionEnable);
//if (EnableDebug.boolValue == true)
{
EditorGUILayout.PropertyField(HTraceLayer, HEditorStyles.hTraceLayerContent);
}
EditorGUILayout.PropertyField(ShowBowels, new GUIContent("Show Bowels"));
ShowFullDebugLog.boolValue = EditorGUILayout.Toggle(new GUIContent("Show Full Debug Log"), ShowFullDebugLog.boolValue);
TestCheckBox1.boolValue = EditorGUILayout.Toggle(new GUIContent("TestCheckBox1"), TestCheckBox1.boolValue);
TestCheckBox2.boolValue = EditorGUILayout.Toggle(new GUIContent("TestCheckBox2"), TestCheckBox2.boolValue);
TestCheckBox3.boolValue = EditorGUILayout.Toggle(new GUIContent("TestCheckBox3"), TestCheckBox3.boolValue);
EditorGUILayout.Space(3);
}
}
}
private void UpdateStandartStyles()
{
HEditorStyles.foldout.fontStyle = FontStyle.Bold;
}
private void PropertiesRelative()
{
GeneralSettings = serializedObject.FindProperty("GeneralSettings");
SSGISettings = serializedObject.FindProperty("SSGISettings");
DenoisingSettings = serializedObject.FindProperty("DenoisingSettings");
DebugSettings = serializedObject.FindProperty("DebugSettings");
// Debug Data
HTraceLayer = DebugSettings.FindPropertyRelative("HTraceLayer");
ShowBowels = DebugSettings.FindPropertyRelative("ShowBowels");
ShowFullDebugLog = DebugSettings.FindPropertyRelative("ShowFullDebugLog");
TestCheckBox1 = DebugSettings.FindPropertyRelative("TestCheckBox1");
TestCheckBox2 = DebugSettings.FindPropertyRelative("TestCheckBox2");
TestCheckBox3 = DebugSettings.FindPropertyRelative("TestCheckBox3");
// Global Tab
DebugMode = GeneralSettings.FindPropertyRelative("DebugMode");
HBuffer = GeneralSettings.FindPropertyRelative("HBuffer");
ExcludeReceivingMask = GeneralSettings.FindPropertyRelative("ExcludeReceivingMask");
ExcludeCastingMask = GeneralSettings.FindPropertyRelative("ExcludeCastingMask");
MetallicIndirectFallback = GeneralSettings.FindPropertyRelative("MetallicIndirectFallback");
AmbientOverride = GeneralSettings.FindPropertyRelative("AmbientOverride");
Multibounce = GeneralSettings.FindPropertyRelative("Multibounce");
FallbackType = GeneralSettings.FindPropertyRelative("FallbackType");
SkyIntensity = GeneralSettings.FindPropertyRelative("_skyIntensity");
ViewBias = GeneralSettings.FindPropertyRelative("_viewBias");
NormalBias = GeneralSettings.FindPropertyRelative("_normalBias");
SamplingNoise = GeneralSettings.FindPropertyRelative("_samplingNoise");
DenoiseFallback = GeneralSettings.FindPropertyRelative("DenoiseFallback");
// Visuals
BackfaceLighting = SSGISettings.FindPropertyRelative("_backfaceLighting");
MaxRayLength = SSGISettings.FindPropertyRelative("_maxRayLength");
ThicknessMode = SSGISettings.FindPropertyRelative("ThicknessMode");
Thickness = SSGISettings.FindPropertyRelative("_thickness");
Intensity = SSGISettings.FindPropertyRelative("_intensity");
Falloff = SSGISettings.FindPropertyRelative("_falloff");
// Quality tab
// Tracing
RayCount = SSGISettings.FindPropertyRelative("_rayCount");
StepCount = SSGISettings.FindPropertyRelative("_stepCount");
RefineIntersection = SSGISettings.FindPropertyRelative("RefineIntersection");
FullResolutionDepth = SSGISettings.FindPropertyRelative("FullResolutionDepth");
// Rendering
Checkerboard = SSGISettings.FindPropertyRelative("Checkerboard");
RenderScale = SSGISettings.FindPropertyRelative("_renderScale");
// Denoising tab
BrightnessClamp = DenoisingSettings.FindPropertyRelative("BrightnessClamp");
MaxValueBrightnessClamp = DenoisingSettings.FindPropertyRelative("_maxValueBrightnessClamp");
MaxDeviationBrightnessClamp = DenoisingSettings.FindPropertyRelative("_maxDeviationBrightnessClamp");
// ReSTIR Validation
HalfStepValidation = DenoisingSettings.FindPropertyRelative("HalfStepValidation");
SpatialOcclusionValidation = DenoisingSettings.FindPropertyRelative("SpatialOcclusionValidation");
TemporalLightingValidation = DenoisingSettings.FindPropertyRelative("TemporalLightingValidation");
TemporalOcclusionValidation = DenoisingSettings.FindPropertyRelative("TemporalOcclusionValidation");
// Spatial
SpatialRadius = DenoisingSettings.FindPropertyRelative("_spatialRadius");
Adaptivity = DenoisingSettings.FindPropertyRelative("_adaptivity");
// SpatialPassCount = DenoisingData.FindPropertyRelative("_spatialPassCount");
RecurrentBlur = DenoisingSettings.FindPropertyRelative("RecurrentBlur");
FireflySuppression = DenoisingSettings.FindPropertyRelative("FireflySuppression");
}
}
}
#endif

View File

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

View File

@@ -0,0 +1,31 @@
//pipelinedefine
#define H_URP
#if UNITY_EDITOR
using HTraceSSGI.Scripts.Infrastructure.URP;
using UnityEditor;
using UnityEditor.Rendering.Universal;
namespace HTraceSSGI.Scripts.Editor
{
[CustomEditor(typeof(HTraceSSGIRendererFeature))]
public class HTraceSSGIRendererFeatureEditor : ScriptableRendererFeatureEditor
{
SerializedProperty useVolumes;
private void OnEnable()
{
useVolumes = serializedObject.FindProperty("UseVolumes");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
EditorGUILayout.PropertyField(useVolumes);
serializedObject.ApplyModifiedProperties();
}
}
}
#endif

View File

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

View File

@@ -0,0 +1,468 @@
//pipelinedefine
#define H_URP
using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
#if UNITY_EDITOR
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Data.Public;
using HTraceSSGI.Scripts.Editor.WindowsAndMenu;
using HTraceSSGI.Scripts.Globals;
using HTraceSSGI.Scripts.Infrastructure.URP;
using UnityEditor;
using UnityEditor.Rendering;
using UnityEditor.AnimatedValues;
namespace HTraceSSGI.Scripts.Editor
{
[CanEditMultipleObjects]
#if UNITY_2022_2_OR_NEWER
[CustomEditor(typeof(HTraceSSGIVolume))]
#else
[VolumeComponentEditor(typeof(HTraceSSGIVolume))]
#endif
internal class HTraceSSGIVolumeEditorURP : VolumeComponentEditor
{
private const string NO_RENDERER_FEATURE_MESSAGE = "HTrace Screen Space Global Illumination feature is missing in the active URP renderer.";
private const string RENDERER_FEATURE_OFF_MESSAGE = "HTrace Screen Space Global Illumination is disabled in the active URP renderer.";
private const string LIGHTING_MULTIPLIER_ABOVE_1_MESSAGE = "Ambient Override may not work correctly when the Environment Lighting Multiplier is set above 1 !";
private const string RENDETIN_LIGHTING_SETTINGS_WINDOW_PATH = "Window/Rendering/Lighting";
private Texture2D m_Icon;
SerializedDataParameter p_Enable;
// General
internal SerializedDataParameter p_DebugMode;
internal SerializedDataParameter p_HBuffer;
internal SerializedDataParameter p_ExcludeCastingMask;
internal SerializedDataParameter p_ExcludeReceivingMask;
internal SerializedDataParameter p_FallbackType;
internal SerializedDataParameter p_SkyIntensity;
internal SerializedDataParameter p_MetallicIndirectFallback;
internal SerializedDataParameter p_AmbientOverride;
internal SerializedDataParameter p_Multibounce;
//Apv
internal SerializedDataParameter p_ViewBias;
internal SerializedDataParameter p_NormalBias;
internal SerializedDataParameter p_SamplingNoise;
internal SerializedDataParameter p_IntensityMultiplier;
internal SerializedDataParameter p_DenoiseFallback;
// Visuals
internal SerializedDataParameter p_BackfaceLighting;
internal SerializedDataParameter p_MaxRayLength;
internal SerializedDataParameter p_ThicknessMode;
internal SerializedDataParameter p_Thickness;
internal SerializedDataParameter p_Intensity;
internal SerializedDataParameter p_Falloff;
// Quality tab
// Tracing
internal SerializedDataParameter p_RayCount;
internal SerializedDataParameter p_StepCount;
internal SerializedDataParameter p_RefineIntersection;
internal SerializedDataParameter p_FullResolutionDepth;
// Rendering
internal SerializedDataParameter p_Checkerboard;
internal SerializedDataParameter p_RenderScale;
// Denoising tab
internal SerializedDataParameter p_BrightnessClamp;
internal SerializedDataParameter p_MaxValueBrightnessClamp;
internal SerializedDataParameter p_MaxDeviationBrightnessClamp;
// Temporal
internal SerializedDataParameter p_HalfStepValidation;
internal SerializedDataParameter p_SpatialOcclusionValidation;
internal SerializedDataParameter p_TemporalLightingValidation;
internal SerializedDataParameter p_TemporalOcclusionValidation;
// Spatial Filter
internal SerializedDataParameter p_SpatialRadius;
internal SerializedDataParameter p_Adaptivity;
internal SerializedDataParameter p_RecurrentBlur;
internal SerializedDataParameter p_FireflySuppression;
//Debug
internal SerializedDataParameter p_ShowBowels;
// Main foldout groups
private AnimBool AnimBoolGeneralTab;
private AnimBool AnimBoolQualityTab;
private AnimBool AnimBoolDenoisingTab;
private AnimBool AnimBoolDebugTab;
private AnimBool AnimBoolEMPTY;
// Menu state
private bool _showPipelineIntegration = true;
private bool _showVisualsArea = true;
private bool _showTracingArea = true;
private bool _showRenderingArea = true;
private bool _showRestirValidationArea = true;
private bool _showSpatialArea = true;
static HTraceSSGIPreset _preset = HTraceSSGIPreset.Balanced;
public override void OnEnable()
{
var o = new PropertyFetcher<HTraceSSGIVolume>(serializedObject);
m_Icon = Resources.Load<Texture2D>("SSGI UI Card");
p_Enable = Unpack(o.Find(x => x.Enable));
// General Settings
p_DebugMode = Unpack(o.Find(x => x.DebugMode));
p_HBuffer = Unpack(o.Find(x => x.HBuffer));
#if UNITY_2023_3_OR_NEWER
p_ExcludeReceivingMask = Unpack(o.Find(x => x.ExcludeReceivingMask));
p_ExcludeCastingMask = Unpack(o.Find(x => x.ExcludeCastingMask));
#endif
p_FallbackType = Unpack(o.Find(x => x.FallbackType));
p_SkyIntensity = Unpack(o.Find(x => x.SkyIntensity));
//Pipeline integration
p_MetallicIndirectFallback = Unpack(o.Find(x => x.MetallicIndirectFallback));
p_AmbientOverride = Unpack(o.Find(x => x.AmbientOverride));
p_Multibounce = Unpack(o.Find(x => x.Multibounce));
//Apv
p_ViewBias = Unpack(o.Find(x => x.ViewBias));
p_NormalBias = Unpack(o.Find(x => x.NormalBias));
p_SamplingNoise = Unpack(o.Find(x => x.SamplingNoise));
p_IntensityMultiplier = Unpack(o.Find(x => x.IntensityMultiplier));
p_DenoiseFallback = Unpack(o.Find(x => x.DenoiseFallback));
// Visuals
p_BackfaceLighting = Unpack(o.Find(x => x.BackfaceLighting));
p_MaxRayLength = Unpack(o.Find(x => x.MaxRayLength));
p_ThicknessMode = Unpack(o.Find(x => x.ThicknessMode));
p_Thickness = Unpack(o.Find(x => x.Thickness));
p_Intensity = Unpack(o.Find(x => x.Intensity));
p_Falloff = Unpack(o.Find(x => x.Falloff));
// Quality tab
// Tracing
p_RayCount = Unpack(o.Find(x => x.RayCount));
p_StepCount = Unpack(o.Find(x => x.StepCount));
p_RefineIntersection = Unpack(o.Find(x => x.RefineIntersection));
p_FullResolutionDepth = Unpack(o.Find(x => x.FullResolutionDepth));
// Rendering
p_Checkerboard = Unpack(o.Find(x => x.Checkerboard));
p_RenderScale = Unpack(o.Find(x => x.RenderScale));
// Denoising tab
p_BrightnessClamp = Unpack(o.Find(x => x.BrightnessClamp));
p_MaxValueBrightnessClamp = Unpack(o.Find(x => x.MaxValueBrightnessClamp));
p_MaxDeviationBrightnessClamp = Unpack(o.Find(x => x.MaxDeviationBrightnessClamp));
// Temporal
p_HalfStepValidation = Unpack(o.Find(x => x.HalfStepValidation));
p_SpatialOcclusionValidation = Unpack(o.Find(x => x.SpatialOcclusionValidation));
p_TemporalLightingValidation = Unpack(o.Find(x => x.TemporalLightingValidation));
p_TemporalOcclusionValidation = Unpack(o.Find(x => x.TemporalOcclusionValidation));
// Spatial Filter
p_SpatialRadius = Unpack(o.Find(x => x.SpatialRadius));
p_Adaptivity = Unpack(o.Find(x => x.Adaptivity));
p_RecurrentBlur = Unpack(o.Find(x => x.RecurrentBlur));
p_FireflySuppression = Unpack(o.Find(x => x.FireflySuppression));
// Debug
p_ShowBowels = Unpack(o.Find(x => x.ShowBowels));
AnimBoolGeneralTab = new AnimBool(true);
AnimBoolGeneralTab.valueChanged.RemoveAllListeners();
AnimBoolGeneralTab.valueChanged.AddListener(Repaint);
AnimBoolQualityTab = new AnimBool(true);
AnimBoolQualityTab.valueChanged.RemoveAllListeners();
AnimBoolQualityTab.valueChanged.AddListener(Repaint);
AnimBoolDenoisingTab = new AnimBool(true);
AnimBoolDenoisingTab.valueChanged.RemoveAllListeners();
AnimBoolDenoisingTab.valueChanged.AddListener(Repaint);
AnimBoolDebugTab = new AnimBool(true); //_debugTab.boolValue
AnimBoolDebugTab.valueChanged.RemoveAllListeners();
AnimBoolDebugTab.valueChanged.AddListener(Repaint);
AnimBoolEMPTY = new AnimBool(false);
}
public override void OnInspectorGUI()
{
var hTraceRendererFeature = HRendererURP.GetRendererFeatureByTypeName(nameof(HTraceSSGIRendererFeature)) as HTraceSSGIRendererFeature;
if (hTraceRendererFeature == null)
{
EditorGUILayout.Space();
CoreEditorUtils.DrawFixMeBox(NO_RENDERER_FEATURE_MESSAGE, MessageType.Error, HEditorStyles.FixButtonName, () =>
{
HRendererURP.AddHTraceRendererFeatureToUniversalRendererData();
GUIUtility.ExitGUI();
});
//EditorGUILayout.HelpBox(NO_RENDERER_FEATURE_MESSAGE, MessageType.Error, wide: true);
return;
}
else if (!hTraceRendererFeature.isActive)
{
EditorGUILayout.Space();
CoreEditorUtils.DrawFixMeBox(RENDERER_FEATURE_OFF_MESSAGE, MessageType.Warning, HEditorStyles.FixButtonName, () =>
{
hTraceRendererFeature.SetActive(true);
GUIUtility.ExitGUI();
});
EditorGUILayout.Space();
}
if (m_Icon != null)
{
//GUILayout.Label(m_Icon, HEditorStyles.icon, GUILayout.ExpandWidth(false));
Rect rect = GUILayoutUtility.GetAspectRect((float)m_Icon.width / m_Icon.height);
rect.xMin += 4;
rect.xMax -= 4;
GUI.DrawTexture(rect, m_Icon, ScaleMode.ScaleToFit);
EditorGUILayout.Space(5f);
}
if (HTraceSSGIRendererFeature.IsUseVolumes == false)
{
CoreEditorUtils.DrawFixMeBox("\"Use Volumes\" checkbox in the HTrace SSGI Renderer feature is disabled, use the HTraceSSGI component in your scenes.", MessageType.Warning, HEditorStyles.ChangeButtonName, () =>
{
hTraceRendererFeature.UseVolumes = true;
GUIUtility.ExitGUI();
});
return;
}
PropertyField(p_Enable);
EditorGUILayout.Space(5f);
// ------------------------------------- Global settings ----------------------------------------------------------
using (new HEditorUtils.FoldoutScope(AnimBoolGeneralTab, out var shouldDraw, HEditorStyles.GlobalSettings.text))
{
if (shouldDraw)
{
using (new IndentLevelScope(10))
{
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel("Preset");
_preset = (HTraceSSGIPreset)EditorGUILayout.EnumPopup(_preset);
if (GUILayout.Button("Apply", GUILayout.Width(60)))
{
HTraceSSGIPresetData.ApplyPresetVolume(this, _preset);
EditorUtility.SetDirty(target);
}
EditorGUILayout.EndHorizontal();
}
EditorGUILayout.Space(5f);
PropertyField(p_DebugMode);
if((DebugMode)p_DebugMode.value.enumValueIndex == DebugMode.MainBuffers)
{
PropertyField(p_HBuffer);
}
EditorGUILayout.Space(5f);
#if UNITY_2023_3_OR_NEWER
PropertyField(p_ExcludeCastingMask);
PropertyField(p_ExcludeReceivingMask);
#endif
EditorGUILayout.Space(3f);
PropertyField(p_FallbackType);
if ((Globals.FallbackType)p_FallbackType.value.enumValueIndex == Globals.FallbackType.Sky)
PropertyField(p_SkyIntensity);
#if UNITY_6000_0_OR_NEWER
if ((FallbackType)p_FallbackType.value.enumValueIndex == Globals.FallbackType.APV)
{
using (new IndentLevelScope())
{
PropertyField(p_ViewBias);
PropertyField(p_NormalBias);
PropertyField(p_SamplingNoise);
PropertyField(p_IntensityMultiplier);
PropertyField(p_DenoiseFallback);
}
}
if ((FallbackType)p_FallbackType.value.enumValueIndex == Globals.FallbackType.Sky)
{
using (new IndentLevelScope())
PropertyField(p_DenoiseFallback);
}
#endif
EditorGUILayout.Space(5f);
{
_showPipelineIntegration = EditorGUILayout.BeginFoldoutHeaderGroup(_showPipelineIntegration, HEditorStyles.PipelineIntegration.text);
if (_showPipelineIntegration)
{
using (new IndentLevelScope())
{
PropertyField(p_MetallicIndirectFallback);
PropertyField(p_AmbientOverride);
if (RenderSettings.ambientIntensity > 1.0f && p_AmbientOverride.value.boolValue == true)
{
CoreEditorUtils.DrawFixMeBox(LIGHTING_MULTIPLIER_ABOVE_1_MESSAGE, MessageType.Warning, HEditorStyles.OpenButtonName, () =>
{
EditorApplication.ExecuteMenuItem(RENDETIN_LIGHTING_SETTINGS_WINDOW_PATH);
GUIUtility.ExitGUI();
});
}
PropertyField(p_Multibounce);
}
EditorGUILayout.Space(3f);
}
EditorGUILayout.EndFoldoutHeaderGroup();
}
EditorGUILayout.Space(3f);
{
_showVisualsArea = EditorGUILayout.BeginFoldoutHeaderGroup(_showVisualsArea, HEditorStyles.Visuals.text);
if (_showVisualsArea)
{
using (new IndentLevelScope())
{
PropertyField(p_BackfaceLighting);
PropertyField(p_MaxRayLength);
if (p_MaxRayLength.value.floatValue < 0)
p_MaxRayLength.value.floatValue = 0f;
PropertyField(p_ThicknessMode);
PropertyField(p_Thickness);
PropertyField(p_Intensity);
PropertyField(p_Falloff);
}
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(3f);
}
}
}
// ------------------------------------- Quality ----------------------------------------------------------
using (new HEditorUtils.FoldoutScope(AnimBoolQualityTab, out var shouldDraw, HEditorStyles.Quality.text))
{
if (shouldDraw)
{
EditorGUILayout.Space(3f);
_showTracingArea = EditorGUILayout.BeginFoldoutHeaderGroup(_showTracingArea, HEditorStyles.Tracing.text);
if (_showTracingArea)
{
using (new IndentLevelScope())
{
PropertyField(p_RayCount);
PropertyField(p_StepCount);
PropertyField(p_RefineIntersection);
PropertyField(p_FullResolutionDepth);
}
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(5f);
_showRenderingArea = EditorGUILayout.BeginFoldoutHeaderGroup(_showRenderingArea, HEditorStyles.Rendering.text);
if (_showRenderingArea)
{
using (new IndentLevelScope())
{
PropertyField(p_Checkerboard);
PropertyField(p_RenderScale);
p_RenderScale.value.floatValue = p_RenderScale.value.floatValue.RoundToCeilTail(2);
}
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(3f);
}
}
// ------------------------------------- Denoising ----------------------------------------------------------
using (new HEditorUtils.FoldoutScope(AnimBoolDenoisingTab, out var shouldDraw, HEditorStyles.Denoising.text))
{
if (shouldDraw)
{
EditorGUILayout.Space(3f);
PropertyField(p_BrightnessClamp);
if ((BrightnessClamp)p_BrightnessClamp.value.enumValueIndex == Globals.BrightnessClamp.Manual)
PropertyField(p_MaxValueBrightnessClamp);
if ((BrightnessClamp)p_BrightnessClamp.value.enumValueIndex == Globals.BrightnessClamp.Automatic)
PropertyField(p_MaxDeviationBrightnessClamp);
EditorGUILayout.Space(5f);
_showRestirValidationArea = EditorGUILayout.BeginFoldoutHeaderGroup(_showRestirValidationArea, HEditorStyles.ReSTIRValidation.text);
if (_showRestirValidationArea)
{
using (new IndentLevelScope())
{
PropertyField(p_HalfStepValidation);
EditorGUILayout.Space(3f);
EditorGUILayout.LabelField(HEditorStyles.ValidationTypes, HEditorStyles.bold);
PropertyField(p_SpatialOcclusionValidation);
PropertyField(p_TemporalLightingValidation);
PropertyField(p_TemporalOcclusionValidation);
}
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(5f);
_showSpatialArea = EditorGUILayout.BeginFoldoutHeaderGroup(_showSpatialArea, HEditorStyles.SpatialFilter.text);
if (_showSpatialArea)
{
using (new IndentLevelScope())
{
PropertyField(p_SpatialRadius);
PropertyField(p_Adaptivity);
PropertyField(p_RecurrentBlur);
PropertyField(p_FireflySuppression);
}
}
EditorGUILayout.EndFoldoutHeaderGroup();
EditorGUILayout.Space(3f);
}
}
HEditorUtils.HorizontalLine(1f);
EditorGUILayout.Space(3f);
//HEditorUtils.DrawClickableLink($"HTrace AO Version: {HNames.HTRACE_AO_VERSION}", HNames.HTRACE_AO_DOCUMENTATION_LINK, true);
HEditorUtils.DrawLinkRow(
($"Documentation (v." + HNames.HTRACE_SSGI_VERSION + ")", () => Application.OpenURL(HNames.HTRACE_SSGI_DOCUMENTATION_LINK)),
("Discord", () => Application.OpenURL(HNames.HTRACE_DISCORD_LINK)),
("Bug report", () => HBugReporterWindow.ShowWindow())
);
}
private void DebugPart()
{
using (new HEditorUtils.FoldoutScope(AnimBoolDebugTab, out var shouldDraw, HEditorStyles.Debug.text))
{
if (shouldDraw)
{
EditorGUILayout.Space(3f);
PropertyField(p_ShowBowels);
EditorGUILayout.Space(3f);
}
}
}
}
}
#endif //UNITY_EDITOR

View File

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

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f30ffee4f8a6491fa30599d846fd00eb
timeCreated: 1757344404

View File

@@ -0,0 +1,41 @@
#if UNITY_EDITOR
using HTraceSSGI.Scripts.Extensions;
using HTraceSSGI.Scripts.Globals;
using UnityEditor;
using UnityEngine;
namespace HTraceSSGI.Scripts.Editor.WindowsAndMenu
{
[InitializeOnLoad]
public static class AssetWelcomeLoader
{
static AssetWelcomeLoader()
{
EditorApplication.delayCall += TryShowWelcome;
}
private static void TryShowWelcome()
{
if (SessionState.GetBool(HNames.HTRACE_WELCOME_SHOW_SESSION, false))
return;
SessionState.SetBool(HNames.HTRACE_WELCOME_SHOW_SESSION, true);
bool dontShowAgain = EditorPrefs.GetBool(HNames.HTRACE_SHOW_KEY, false);
string currentUnityVersion = Application.unityVersion;
string savedUnityVersion = EditorPrefs.GetString(HNames.HTRACE_UNITY_VERSION_KEY, string.Empty);
bool unityVersionChanged = savedUnityVersion != currentUnityVersion;
bool isLts = HExtensions.IsUnityLTS(currentUnityVersion);
bool shouldShowWelcome = !dontShowAgain || (unityVersionChanged && !isLts);
if (shouldShowWelcome)
{
AssetWelcomeWindow.ShowWindow();
}
EditorPrefs.SetString(HNames.HTRACE_UNITY_VERSION_KEY, currentUnityVersion);
}
}
}
#endif

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: b548ee64286c45f48d34d1dc643c5c30
timeCreated: 1766077710
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Editor/WindowsAndMenu/AssetWelcomeLoader.cs
uploadId: 840002

View File

@@ -0,0 +1,139 @@
#if UNITY_EDITOR
using System;
using HTraceSSGI.Scripts.Extensions;
using HTraceSSGI.Scripts.Globals;
using UnityEditor;
using UnityEngine;
namespace HTraceSSGI.Scripts.Editor.WindowsAndMenu
{
public class AssetWelcomeWindow : EditorWindow
{
private static Texture2D _icon;
public static void ShowWindow()
{
_icon = Resources.Load<Texture2D>("SSGI UI Card");
var window = GetWindow<AssetWelcomeWindow>("Welcome");
Vector2 minSize = new Vector2(600, 240);
if (HExtensions.IsUnityLTS(Application.unityVersion))
minSize.y -= 45;
if (_icon != null)
minSize.y += 100;
Vector2 maxSize = minSize - new Vector2(1, 1);
window.minSize = minSize;
window.maxSize = maxSize;
Rect main = EditorGUIUtility.GetMainWindowPosition();
window.position = new Rect(
main.x + (main.width - minSize.x) / 2,
main.y + (main.height - minSize.y) / 2,
minSize.x,
minSize.y
);
}
private void OnGUI()
{
if (_icon != null)
{
GUILayout.Space(5);
Rect rect = GUILayoutUtility.GetAspectRect((float)_icon.width / _icon.height);
rect.xMin += 4;
rect.xMax -= 4;
GUI.DrawTexture(rect, _icon, ScaleMode.ScaleToFit);
EditorGUILayout.Space(5f);
}
GUILayout.Space(5);
GUILayout.Label($"Thank you for purchasing {HNames.ASSET_NAME_FULL_WITH_DOTS}!", EditorStyles.boldLabel);
GUILayout.Space(5);
DrawUnityVersionWarning();
GUILayout.Space(10);
var richLabel = new GUIStyle(EditorStyles.wordWrappedLabel)
{
richText = true
};
GUILayout.Label(
"Please make sure to read the <b>Documentation</b> before using the asset.\n" +
"If you run into any issues, check the <b>Known Issues</b> and <b>FAQ</b> sections before reporting a bug.",
richLabel
);
GUILayout.Space(5);
DrawLinksLine();
GUILayout.Space(10);
GUILayout.Label(
"Shortcuts to the Documentation, Discord support channel, and Bug Report form " +
"can be found at the bottom of the HTrace UI.",
EditorStyles.wordWrappedLabel
);
GUILayout.Space(15);
bool dontShow = GUILayout.Toggle(
EditorPrefs.GetBool(HNames.HTRACE_SHOW_KEY, false),
"Don't show next time"
);
EditorPrefs.SetBool(HNames.HTRACE_SHOW_KEY, dontShow);
GUILayout.Space(10);
if (GUILayout.Button("I understand, close window"))
{
Close();
}
}
private static void DrawUnityVersionWarning()
{
string unityVersion = Application.unityVersion;
if (!HExtensions.IsUnityLTS(unityVersion))
{
EditorGUILayout.HelpBox(
$"The current Unity version ({unityVersion}) is not an LTS release.\n" +
"Bug fixes for non-LTS releases are not guaranteed.",
MessageType.Warning
);
}
}
private static void DrawLinksLine()
{
EditorGUILayout.BeginHorizontal();
DrawLinkButton("Documentation", HNames.HTRACE_SSGI_DOCUMENTATION_LINK);
GUILayout.Label("|", GUILayout.Width(10));
DrawLinkButton("Known Issues", HNames.HTRACE_SSGI_DOCUMENTATION_LINK_KNOWN_ISSUES);
GUILayout.Label("|", GUILayout.Width(10));
DrawLinkButton("FAQ", HNames.HTRACE_SSGI_DOCUMENTATION_LINK_FAQ);
EditorGUILayout.EndHorizontal();
}
private static void DrawLinkButton(string label, string url)
{
var style = new GUIStyle(EditorStyles.linkLabel)
{
wordWrap = false
};
if (GUILayout.Button(label, style, GUILayout.Width(EditorStyles.linkLabel.CalcSize(new GUIContent(label)).x)))
{
Application.OpenURL(url);
}
}
}
}
#endif

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 37241604af0a4e2ea194f52d530a3b97
timeCreated: 1766077786
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Editor/WindowsAndMenu/AssetWelcomeWindow.cs
uploadId: 840002

View File

@@ -0,0 +1,98 @@
using HTraceSSGI.Scripts.Globals;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace HTraceSSGI.Scripts.Editor.WindowsAndMenu
{
#if UNITY_EDITOR
public class HBugReporterWindow : EditorWindow
{
private string _reportData = "";
private GUIStyle _styleLabel;
private Vector2 _scrollPosition = Vector2.zero;
[MenuItem("Window/HTrace/Report a Bug HTrace SSGI", false, priority: 32)]
public static void ShowWindow()
{
var window = GetWindow<HBugReporterWindow>(false, "Report Bug", true);
window.minSize = new Vector2(400, 330);
}
void OnEnable()
{
_reportData = "";
var pipeline = HRenderer.CurrentHRenderPipeline.ToString();
_reportData += $"{HNames.ASSET_NAME_FULL} Version: {HNames.HTRACE_SSGI_VERSION}" + "\n";
_reportData += "\n";
_reportData += "Unity Version: " + Application.unityVersion + "\n";
_reportData += "Pipeline: " + pipeline + "\n";
_reportData += "Platform: " + Application.platform + "\n";
_reportData += "Graphics API: " + SystemInfo.graphicsDeviceType + "\n";
_reportData += "\n";
_reportData += "OS: " + SystemInfo.operatingSystem + "\n";
_reportData += "Graphics: " + SystemInfo.graphicsDeviceName + "\n";
_reportData += "\n";
_reportData += "Additional details:\n";
}
void OnGUI()
{
SetGUIStyles();
GUILayout.Space(-2);
GUILayout.BeginHorizontal();
GUILayout.Space(15);
GUILayout.BeginVertical();
_scrollPosition = GUILayout.BeginScrollView(_scrollPosition, false, false, GUILayout.Width(this.position.width - 28), GUILayout.Height(this.position.height - 80));
GUILayout.Label(_reportData, _styleLabel);
GUILayout.Space(15);
if (GUILayout.Button("Copy Details To Clipboard", GUILayout.Height(24)))
{
var copyData = _reportData;
GUIUtility.systemCopyBuffer = copyData;
}
if (GUILayout.Button("Report Bug on Discord", GUILayout.Height(24)))
{
Application.OpenURL(HNames.HTRACE_DISCORD_BUGS_SSGI_LINK);
}
GUILayout.FlexibleSpace();
GUILayout.Space(20);
GUILayout.EndScrollView();
GUILayout.EndVertical();
GUILayout.Space(13);
GUILayout.EndHorizontal();
}
void SetGUIStyles()
{
_styleLabel = new GUIStyle(EditorStyles.label)
{
richText = true,
};
}
}
#endif
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: dba5cecf144f410fb38b07e1de8c0ca1
timeCreated: 1757344409
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Editor/WindowsAndMenu/HBugReporterWindow.cs
uploadId: 840002

View File

@@ -0,0 +1,52 @@
//pipelinedefine
#define H_URP
#if UNITY_EDITOR
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Extensions;
using HTraceSSGI.Scripts.Globals;
using UnityEditor;
using UnityEditor.ShortcutManagement;
using UnityEngine;
using HTraceSSGI.Scripts.Infrastructure.URP;
namespace HTraceSSGI.Scripts.Editor.WindowsAndMenu
{
#if UNITY_EDITOR
public class HMenuAndFilesManager : EditorWindow
{
[MenuItem("GameObject/Rendering/HTrace Screen Space Global Illumination", false, priority: 30)]
static void CreateHTraceGameObject(MenuCommand menuCommand)
{
HTraceSSGI[] hTraces = FindObjectsOfType(typeof(HTraceSSGI)) as HTraceSSGI[];
if (hTraces != null && hTraces.Length > 0)
{
return;
}
GameObject go = new GameObject(HNames.ASSET_NAME);
GameObjectUtility.SetParentAndAlign(go, menuCommand.context as GameObject);
go.AddComponent<HTraceSSGI>();
Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
Selection.activeObject = go;
}
[MenuItem("Window/HTrace/Add HTrace SSGI Render Feature to active RendererData", false, priority: 32)]
private static void AddRenderFeature()
{
HRendererURP.AddHTraceRendererFeatureToUniversalRendererData();
}
[MenuItem("Window/HTrace/Open HTrace SSGI documentation", false, priority: 32)]
private static void OpenDocumentation()
{
Application.OpenURL(HNames.HTRACE_SSGI_DOCUMENTATION_LINK);
}
}
#endif
}
#endif

View File

@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: 4097973eb33709247ad51c90310a5018
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Editor/WindowsAndMenu/HMenuAndFilesManager.cs
uploadId: 840002

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7c37931430e142a8a8c9147d0094a187
timeCreated: 1756743171

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2ce18ebb0d794317835a43506e011560
timeCreated: 1756743209

View File

@@ -0,0 +1,71 @@
using System;
namespace HTraceSSGI.Scripts.Extensions.CameraHistorySystem
{
public class CameraHistorySystem<T> where T : struct, ICameraHistoryData
{
private const int MaxCameraCount = 4; // minimum 2
private int _cameraHistoryIndex;
private readonly T[] _cameraHistoryData = new T[MaxCameraCount];
public int UpdateCameraHistoryIndex(int currentCameraHash)
{
_cameraHistoryIndex = GetCameraHistoryDataIndex(currentCameraHash);
return _cameraHistoryIndex;
}
private int GetCameraHistoryDataIndex(int cameraHash)
{
// Unroll manually for MAX_CAMERA_COUNT = 4
if (_cameraHistoryData[0].GetHash() == cameraHash) return 0;
if (_cameraHistoryData[1].GetHash() == cameraHash) return 1;
if (_cameraHistoryData[2].GetHash() == cameraHash) return 2;
if (_cameraHistoryData[3].GetHash() == cameraHash) return 3;
return -1; // new camera
}
public void UpdateCameraHistoryData()
{
bool cameraHasChanged = _cameraHistoryIndex == -1;
if (cameraHasChanged)
{
const int lastIndex = MaxCameraCount - 1;
if (_cameraHistoryData[lastIndex] is IDisposable disposable)
disposable.Dispose();
// Shift the camera history data back by one
Array.Copy(_cameraHistoryData, 0, _cameraHistoryData, 1, lastIndex);
_cameraHistoryIndex = 0;
_cameraHistoryData[0] = new T(); //it's critical
}
}
public ref T GetCameraData()
{
return ref _cameraHistoryData[_cameraHistoryIndex];
}
public T[] GetCameraDatas()
{
return _cameraHistoryData;
}
public void SetCameraData(T data)
{
_cameraHistoryData[_cameraHistoryIndex] = data;
}
public void Cleanup()
{
for (int index = 0; index < _cameraHistoryData.Length; index++)
{
_cameraHistoryData[index] = default;
}
}
}
}

View File

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

View File

@@ -0,0 +1,8 @@
namespace HTraceSSGI.Scripts.Extensions.CameraHistorySystem
{
public interface ICameraHistoryData
{
int GetHash();
void SetHash(int hashIn);
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 0c7d445abdf7490a9ce172328c1955e4
timeCreated: 1756743242
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Extensions/CameraHistorySystem/ICameraHistoryData.cs
uploadId: 840002

View File

@@ -0,0 +1,32 @@
//pipelinedefine
#define H_URP
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering.Universal;
#if UNITY_2023_3_OR_NEWER
using UnityEngine.Rendering.RenderGraphModule;
#endif
namespace HTraceSSGI.Scripts.Extensions
{
public class ExtensionsURP
{
#if UNITY_2023_3_OR_NEWER
public static TextureHandle CreateTexture(string name, RenderGraph rg, ref TextureDesc desc, GraphicsFormat format, DepthBits depthBufferBits = DepthBits.None,
bool enableRandomWrite = true, bool useMipMap = false, bool autoGenerateMips = false)
{
desc.name = name;
desc.format = format;
desc.depthBufferBits = depthBufferBits;
desc.enableRandomWrite = enableRandomWrite;
desc.useMipMap = useMipMap;
desc.autoGenerateMips = autoGenerateMips;
desc.msaaSamples = MSAASamples.None;
return rg.CreateTexture(desc);
}
#endif //UNITY_2023_3_OR_NEWER
}
}

View File

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

View File

@@ -0,0 +1,261 @@
//pipelinedefine
#define H_URP
using System;
using System.Reflection;
using HTraceSSGI.Scripts.Globals;
using HTraceSSGI.Scripts.Wrappers;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
#if UNITY_2021 || UNITY_2022
using UnityEngine.Experimental.Rendering;
#endif
namespace HTraceSSGI.Scripts.Extensions
{
public static class HExtensions
{
public static void DebugPrint(DebugType type, string msg)
{
msg = "HTrace log: " + msg;
switch (type)
{
case DebugType.Log:
Debug.Log(msg);
break;
case DebugType.Warning:
Debug.LogWarning(msg);
break;
case DebugType.Error:
Debug.LogError(msg);
break;
}
}
public static ComputeShader LoadComputeShader(string shaderName)
{
var computeShader = (ComputeShader)UnityEngine.Resources.Load($"HTraceSSGI/Computes/{shaderName}");
if (computeShader == null)
{
Debug.LogError($"{shaderName} is missing in HTraceSSGI/Computes folder");
return null;
}
return computeShader;
}
public static RayTracingShader LoadRayTracingShader(string shaderName)
{
var rtShader = (RayTracingShader)UnityEngine.Resources.Load($"HTraceSSGI/Computes/{shaderName}");
if (rtShader == null)
{
Debug.LogError($"{shaderName} is missing in HTraceSSGI/Computes folder");
return null;
}
return rtShader;
}
public static bool ContainsOnOfElement(this string str, string[] elements)
{
foreach (var element in elements)
{
if (str.Contains(element))
return true;
}
return false;
}
public static T NextEnum<T>(this T src) where T : struct
{
if (!typeof(T).IsEnum) throw new ArgumentException(String.Format("Argument {0} is not an Enum", typeof(T).FullName));
T[] Arr = (T[])Enum.GetValues(src.GetType());
int j = Array.IndexOf<T>(Arr, src) + 1;
src = (Arr.Length == j) ? Arr[0] : Arr[j];
return src;
}
public static bool IsUnityLTS(string version)
{
// 2023.1.5f1
if (!Version.TryParse(GetNumericVersion(version), out var current))
return false;
return
current >= new Version(6000, 3, 0) && current < new Version(6000, 3, 100) ||
current >= new Version(6000, 0, 23) && current < new Version(6000, 0, 100) ||
current >= new Version(2022, 3, 0) && current < new Version(2022, 3, 100) ||
current >= new Version(2023, 1, 0) && current < new Version(2023, 1, 100) ||
current >= new Version(2023, 2, 0) && current < new Version(2023, 2, 100);
}
private static string GetNumericVersion(string version)
{
int index = version.IndexOfAny(new[] { 'f', 'a', 'b' });
return index > 0 ? version.Substring(0, index) : version;
}
//custom Attributes
#if UNITY_EDITOR
/// <summary>
/// Read Only attribute.
/// Attribute is use only to mark ReadOnly properties.
/// </summary>
public class ReadOnlyAttribute : PropertyAttribute
{
}
/// <summary>
/// This class contain custom drawer for ReadOnly attribute.
/// </summary>
[CustomPropertyDrawer(typeof(ReadOnlyAttribute))]
public class ReadOnlyDrawer : PropertyDrawer
{
/// <summary>
/// Unity method for drawing GUI in Editor
/// </summary>
/// <param name="position">Position.</param>
/// <param name="property">Property.</param>
/// <param name="label">Label.</param>
public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
{
// Saving previous GUI enabled value
var previousGUIState = GUI.enabled;
// Disabling edit for property
GUI.enabled = false;
// Drawing Property
EditorGUI.PropertyField(position, property, label);
// Setting old GUI enabled value
GUI.enabled = previousGUIState;
}
}
#endif
/// <summary>
/// <para>Attribute used to make a float or int variable in a script be restricted to a specific range.</para>
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class HRangeAttribute : Attribute
{
public readonly bool isFloat;
public readonly float minFloat;
public readonly float maxFloat;
public readonly int minInt;
public readonly int maxInt;
/// <summary>
/// <para>Attribute used to make a float or int variable in a script be restricted to a specific range.</para>
/// </summary>
/// <param name="minFloat">The minimum allowed value.</param>
/// <param name="maxFloat">The maximum allowed value.</param>
public HRangeAttribute(float minFloat, float maxFloat)
{
this.minFloat = minFloat;
this.maxFloat = maxFloat;
isFloat = true;
}
/// <summary>
/// <para>Attribute used to make a float or int variable in a script be restricted to a specific range.</para>
/// </summary>
/// <param name="minFloat">The minimum allowed value.</param>
/// <param name="maxFloat">The maximum allowed value.</param>
public HRangeAttribute(int minInt, int maxInt)
{
this.minInt = minInt;
this.maxInt = maxInt;
isFloat = false;
}
}
public struct HRangeAttributeElement
{
public bool isFloat;
public float minFloat;
public float maxFloat;
public int minInt;
public int maxInt;
}
public static float Clamp(float value, Type type, string nameOfField)
{
HRangeAttribute rangeAttribute = null;
var filed = type.GetField(nameOfField);
if (filed != null)
{
rangeAttribute = filed.GetCustomAttribute<HRangeAttribute>();
}
var property = type.GetProperty(nameOfField);
if (property != null)
{
rangeAttribute = property.GetCustomAttribute<HRangeAttribute>();
}
return Mathf.Clamp(value, rangeAttribute.minFloat, rangeAttribute.maxFloat);
}
public static int Clamp(int value, Type type, string nameOfField)
{
HRangeAttribute rangeAttribute = null;
var filed = type.GetField(nameOfField);
if (filed != null)
{
rangeAttribute = filed.GetCustomAttribute<HRangeAttribute>();
}
var property = type.GetProperty(nameOfField);
if (property != null)
{
rangeAttribute = property.GetCustomAttribute<HRangeAttribute>();
}
return Mathf.Clamp(value, rangeAttribute.minInt, rangeAttribute.maxInt);
}
public static void HRelease(this ComputeBuffer computeBuffer)
{
if (computeBuffer != null)
computeBuffer.Release();
}
public static void HRelease(this CommandBuffer commandBuffer)
{
if (commandBuffer != null)
{
commandBuffer.Clear();
commandBuffer.Release();
}
}
public static void HRelease(this GraphicsBuffer graphicsBuffer)
{
if (graphicsBuffer != null)
{
graphicsBuffer.Release();
}
}
public static void HRelease(this HDynamicBuffer hDynamicBuffer)
{
if (hDynamicBuffer != null)
{
hDynamicBuffer.Release();
}
}
public static void HRelease(this RayTracingAccelerationStructure rayTracingAccelerationStructure)
{
if (rayTracingAccelerationStructure != null)
{
rayTracingAccelerationStructure.Release();
}
}
}
}

View File

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

View File

@@ -0,0 +1,7 @@
namespace HTraceSSGI.Scripts.Extensions
{
public interface IHistoryData
{
void Update();
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 09c7949fa72d433aa944d9be383f2372
timeCreated: 1757489511
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Extensions/IHistoryData.cs
uploadId: 840002

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 03f7f99440026054c98bc8c2d855fe55
timeCreated: 1728989246

View File

@@ -0,0 +1,71 @@
//pipelinedefine
#define H_URP
using UnityEngine.Rendering;
namespace HTraceSSGI.Scripts.Globals
{
public enum ThicknessMode
{
Relative = 0,
Uniform,
}
public enum FallbackType
{
None = 0,
Sky = 1,
#if UNITY_6000_0_OR_NEWER
APV = 2,
#endif
}
public enum BrightnessClamp
{
Manual = 0,
Automatic = 1,
}
public enum ReprojectionFilter
{
Linear4Taps = 0,
Lanczos12Taps = 1,
}
public enum AlphaCutout
{
Evaluate = 0,
DepthTest = 1,
}
public enum DebugMode
{
None = 0,
MainBuffers = 1,
DirectLighting = 2,
GlobalIllumination = 3,
TemporalDisocclusion = 4,
}
public enum HBuffer
{
Multi,
Depth,
Diffuse,
Normal,
MotionMask,
MotionVectors,
}
public enum HInjectionPoint
{
}
public enum DebugType
{
Log,
Warning,
Error,
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 597ae110d1b52354ba4a3f4c6452b96e
timeCreated: 1661865051
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Globals/HEnums.cs
uploadId: 840002

View File

@@ -0,0 +1,183 @@
using UnityEngine;
namespace HTraceSSGI.Scripts.Globals
{
public static class HMath
{
private static Vector2 RemapVoxelsCoeff = new Vector2(64f, 512f); //min - 64 VoxelResolution, max - 512 VoxelResolution
/// <summary>
/// Remap from one range to another
/// </summary>
/// <param name="input"></param>
/// <param name="oldLow"></param>
/// <param name="oldHigh"></param>
/// <param name="newLow"></param>
/// <param name="newHigh"></param>
/// <returns></returns>
public static float Remap(float input, float oldLow, float oldHigh, float newLow, float newHigh)
{
float t = Mathf.InverseLerp(oldLow, oldHigh, input);
return Mathf.Lerp(newLow, newHigh, t);
}
// public static float RemapThickness(float thickness, ThicknessMode thicknessMode)
// {
// float result = 0f;
// switch (thicknessMode)
// {
// case ThicknessMode.Standard:
// result = Remap(thickness, 0f, 1f, 0f, 0.15f);
// break;
// case ThicknessMode.Accurate:
// result = Remap(thickness, 0f, 1f, 0f, 0.05f);
// break;
// default:
// Debug.LogError($"RemapThickness ERROR: thickness: {thickness}, ThicknessMode: {thicknessMode}");
// break;
// }
//
// return result;
// }
/// <summary>
/// Thickness value pre-calculation for GI
/// </summary>
/// <param name="baseThickness"></param>
/// <param name="camera"></param>
/// <returns></returns>
public static Vector2 ThicknessBias(float baseThickness, Camera camera)
{
baseThickness = Remap(baseThickness, 0f, 1f, 0f, 0.5f);
float n = camera.nearClipPlane;
float f = camera.farClipPlane;
float thicknessScale = 1.0f / (1.0f + baseThickness);
float thicknessBias = -n / (f - n) * (baseThickness * thicknessScale);
return new Vector2((float)thicknessScale, (float)thicknessBias);
}
public static Vector4 ComputeViewportScaleAndLimit(Vector2Int viewportSize, Vector2Int bufferSize)
{
return new Vector4(ComputeViewportScale(viewportSize.x, bufferSize.x), // Scale(x)
ComputeViewportScale(viewportSize.y, bufferSize.y), // Scale(y)
ComputeViewportLimit(viewportSize.x, bufferSize.x), // Limit(x)
ComputeViewportLimit(viewportSize.y, bufferSize.y)); // Limit(y)
}
public static float PixelSpreadTangent(float Fov, int Width, int Height)
{
return Mathf.Tan(Fov * Mathf.Deg2Rad * 0.5f) * 2.0f / Mathf.Min(Width, Height);
}
public static float CalculateVoxelSizeInCM_UI(int bounds, float density)
{
float resolution = Mathf.CeilToInt(bounds / (bounds / HMath.Remap(density, 0f, 1f, HMath.RemapVoxelsCoeff.x, HMath.RemapVoxelsCoeff.y)));
return bounds / resolution * 100f; //100 -> cm
}
public static float TexturesSizeInMB_UI(int voxelBounds, float density, bool overrideGroundEnable, int GroundLevel)
{
float resolution = voxelBounds / (voxelBounds / HMath.Remap(density, 0f, 1f, HMath.RemapVoxelsCoeff.x, HMath.RemapVoxelsCoeff.y));
float voxelSize = voxelBounds / resolution;
float textureResolution = resolution * resolution;
textureResolution *= overrideGroundEnable == true ? (GroundLevel / voxelSize) : resolution;
float colorMemorySize = textureResolution * 32 / (1024 * 1024 * 8);
float positionMemorySize = (textureResolution * 32 / (1024 * 1024 * 8)) + (textureResolution * 8 / (1024 * 1024 * 8));
return colorMemorySize + positionMemorySize;
}
public static float TexturesSizeInMB_UI(Vector3Int voxelsRelosution)
{
float textureResolution = voxelsRelosution.x * voxelsRelosution.y * voxelsRelosution.z;
float colorMemorySize = textureResolution * 32 / (1024 * 1024 * 8);
float positionMemorySize = (textureResolution * 32 / (1024 * 1024 * 8)) + (textureResolution * 8 / (1024 * 1024 * 8));
return colorMemorySize + positionMemorySize;
}
public static Vector3Int CalculateVoxelResolution_UI(int voxelBounds, float density, bool overrideGroundEnable, int GroundLevel)
{
Vector3Int resolutionResult = new Vector3Int();
float resolution = HMath.Remap(density, 0f, 1f, HMath.RemapVoxelsCoeff.x, HMath.RemapVoxelsCoeff.y);
resolutionResult.x = Mathf.CeilToInt(resolution);
resolutionResult.y = Mathf.CeilToInt(resolution);
float height = (overrideGroundEnable == false ? voxelBounds : GroundLevel);
resolutionResult.z = Mathf.CeilToInt(height / (voxelBounds / resolution));
resolutionResult.x = HMath.DevisionBy4(resolutionResult.x);
resolutionResult.y = HMath.DevisionBy4(resolutionResult.y);
resolutionResult.z = HMath.DevisionBy4(resolutionResult.z);
return resolutionResult;
}
public static Vector3 Truncate(this Vector3 input, int digits)
{
return new Vector3(input.x.RoundTail(digits), input.y.RoundTail(digits), input.z.RoundTail(digits));
}
public static Vector3 Ceil(this Vector3 input, int digits)
{
return new Vector3(input.x.RoundToCeilTail(digits), input.y.RoundToCeilTail(digits), input.z.RoundToCeilTail(digits));
}
public static float RoundTail(this float value, int digits)
{
float mult = Mathf.Pow(10.0f, digits);
float result = Mathf.Round(mult * value) / mult;
return result;
}
public static float RoundToCeilTail(this float value, int digits)
{
float mult = Mathf.Pow(10.0f, digits);
float result = Mathf.Ceil(mult * value) / mult;
return result;
}
public static Vector2Int CalculateDepthPyramidResolution(Vector2Int screenResolution, int lowestMipLevel)
{
int lowestMipScale = (int)Mathf.Pow(2.0f, lowestMipLevel);
Vector2Int lowestMipResolutiom = new Vector2Int(Mathf.CeilToInt( (float)screenResolution.x / (float)lowestMipScale),
Mathf.CeilToInt( (float)screenResolution.y / (float)lowestMipScale));
Vector2Int paddedDepthPyramidResolution = lowestMipResolutiom * lowestMipScale;
return paddedDepthPyramidResolution;
}
public static int CalculateStepCountSSGI(float giRadius, float giAccuracy)
{
if (giRadius <= 25.0f)
{
//5 -> 16, 10 -> 20, 25 -> 25
return Mathf.FloorToInt((-0.0233f * giRadius * giRadius + 1.15f * giRadius + 10.833f) * giAccuracy);
}
//50 -> 35, 100 -> 50, 150 -> 64
return Mathf.FloorToInt((-0.0002f * giRadius * giRadius + 0.33f * giRadius + 19f) * giAccuracy);
}
private static int DevisionBy4(int value)
{
return value % 4 == 0 ? value : DevisionBy4(value + 1);
}
private static float ComputeViewportScale(int viewportSize, int bufferSize)
{
float rcpBufferSize = 1.0f / bufferSize;
// Scale by (vp_dim / buf_dim).
return viewportSize * rcpBufferSize;
}
private static float ComputeViewportLimit(int viewportSize, int bufferSize)
{
float rcpBufferSize = 1.0f / bufferSize;
// Clamp to (vp_dim - 0.5) / buf_dim.
return (viewportSize - 0.5f) * rcpBufferSize;
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 120dbec02a6a0a4439d6623081e5ed7b
timeCreated: 1661871568
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Globals/HMath.cs
uploadId: 840002

View File

@@ -0,0 +1,32 @@
namespace HTraceSSGI.Scripts.Globals
{
internal static class HNames
{
public const string ASSET_NAME = "HTraceSSGI";
public const string ASSET_NAME_FULL = "HTrace Screen Space Global Illumination";
public const string ASSET_NAME_FULL_WITH_DOTS = "HTrace: Screen Space Global Illumination";
public const string HTRACE_SSGI_DOCUMENTATION_LINK = "https://ipgames.gitbook.io/htrace-ssgi";
public const string HTRACE_SSGI_DOCUMENTATION_LINK_KNOWN_ISSUES = "https://ipgames.gitbook.io/htrace-ssgi/known-issues";
public const string HTRACE_SSGI_DOCUMENTATION_LINK_FAQ = "https://ipgames.gitbook.io/htrace-ssgi/frequently-asked-questions";
public const string HTRACE_DISCORD_LINK = "https://discord.com/invite/Nep56Efu7A";
public const string HTRACE_DISCORD_BUGS_SSGI_LINK = "https://discord.gg/4FN9wsYt5T";
public const string HTRACE_SSGI_VERSION = "1.2.0";
//Prefs
public const string HTRACE_SHOW_KEY = "HTraceSSGI_ShowWelcomeWindow";
public const string HTRACE_WELCOME_SHOW_SESSION = "HTraceSSGI_ShowWelcomeWindowSessions";
public const string HTRACE_UNITY_VERSION_KEY = "HTraceSSGI_UnityVersion";
// ---------------- Profiling ----------------
public const string HTRACE_PRE_PASS_NAME = "HTraceSSGI Pre Pass";
public const string HTRACE_MV_PASS_NAME = "HTraceSSGI Motion Vectors Pass";
public const string HTRACE_OBJECTS_MV_PASS_NAME = "HTraceSSGI Objects Motion Vectors Pass";
public const string HTRACE_CAMERA_MV_PASS_NAME = "HTraceSSGI Camera Motion Vectors Pass";
public const string HTRACE_GBUFFER_PASS_NAME = "HTraceSSGI GBuffer Pass";
public const string HTRACE_SSGI_PASS_NAME = "HTraceSSGI SSGI Pass";
public const string HTRACE_FINAL_PASS_NAME = "HTraceSSGI Final Pass";
public const string KEYWORD_SWITCHER = "HTRACEGI_OVERRIDE";
//public const string INT_SWITCHER = "_HTRACE_INT_OVERRIDE";
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 5a739df963d4e354f8d13ac9e5e6ee44
timeCreated: 1691582446
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Globals/HNames.cs
uploadId: 840002

View File

@@ -0,0 +1,135 @@
//pipelinedefine
#define H_URP
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using HTraceSSGI.Scripts.Infrastructure.URP;
using UnityEngine.Rendering.Universal;
namespace HTraceSSGI.Scripts.Globals
{
public enum HRenderPipeline
{
None,
BIRP,
URP,
HDRP
}
public static class HRenderer
{
static HRenderPipeline s_CurrentHRenderPipeline = HRenderPipeline.None;
public static HRenderPipeline CurrentHRenderPipeline
{
get
{
if (s_CurrentHRenderPipeline == HRenderPipeline.None)
{
s_CurrentHRenderPipeline = GetRenderPipeline();
}
return s_CurrentHRenderPipeline;
}
}
private static HRenderPipeline GetRenderPipeline()
{
if (GraphicsSettings.currentRenderPipeline)
{
if (GraphicsSettings.currentRenderPipeline.GetType().ToString().Contains("HighDefinition"))
return HRenderPipeline.HDRP;
else
return HRenderPipeline.URP;
}
return HRenderPipeline.BIRP;
}
public static bool SupportsInlineRayTracing
{
get
{
#if UNITY_2023_1_OR_NEWER
return SystemInfo.supportsInlineRayTracing;
#else
return false;
#endif
}
}
public static bool SupportsRayTracing
{
get
{
#if UNITY_2023_1_OR_NEWER // TODO: revert this to 2019 when raytracing issue in 2022 is resolved
if (SystemInfo.supportsRayTracing == false)
return false;
return true;
#else
return false;
#endif
}
}
public static int TextureXrSlices
{
get
{
if (Application.isPlaying == false)
return 1;
return 1;
}
}
static RenderTexture emptyTexture;
public static RenderTexture EmptyTexture
{
get
{
if (emptyTexture == null)
{
emptyTexture = new RenderTexture(4, 4, 0);
emptyTexture.enableRandomWrite = true;
emptyTexture.dimension = TextureDimension.Tex2D;
emptyTexture.format = RenderTextureFormat.ARGBFloat;
emptyTexture.Create();
}
return emptyTexture;
}
}
private static Mesh _fullscreenTriangle;
public static Mesh FullscreenTriangle
{
get
{
if (_fullscreenTriangle != null)
return _fullscreenTriangle;
_fullscreenTriangle = new Mesh { name = "Fullscreen Triangle" };
// Because we have to support older platforms (GLES2/3, DX9 etc) we can't do all of
// this directly in the vertex shader using vertex ids :(
_fullscreenTriangle.SetVertices(new List<Vector3>
{
new Vector3(-1f, -1f, 0f),
new Vector3(-1f, 3f, 0f),
new Vector3( 3f, -1f, 0f)
});
_fullscreenTriangle.SetIndices(new[] { 0, 1, 2 }, MeshTopology.Triangles, 0, false);
_fullscreenTriangle.UploadMeshData(false);
return _fullscreenTriangle;
}
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 360412b93660c734f943ed19ba9c2e52
timeCreated: 1727432136
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Globals/HRenderer.cs
uploadId: 840002

View File

@@ -0,0 +1,264 @@
//pipelinedefine
#define H_URP
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Rendering;
using HTraceSSGI.Scripts.Infrastructure.URP;
using UnityEditor;
using UnityEngine.Rendering.Universal;
namespace HTraceSSGI.Scripts.Globals
{
public static class HRendererURP
{
public static bool RenderGraphEnabled
{
get
{
#if UNITY_2023_3_OR_NEWER
return GraphicsSettings.GetRenderPipelineSettings<RenderGraphSettings>().enableRenderCompatibilityMode == false;
#endif
return false;
}
}
public static UniversalRenderPipelineAsset UrpAsset =>
GraphicsSettings.currentRenderPipeline is UniversalRenderPipelineAsset urpAsset ? urpAsset : null;
#if UNITY_EDITOR
private static FieldInfo s_rendererDataListFieldInfo;
private static FieldInfo s_defaultRendererIndexFieldInfo;
private static ScriptableRendererData[] GetRendererDataList()
{
var urpAsset = UrpAsset;
if (urpAsset == null)
return null;
try
{
if (s_rendererDataListFieldInfo == null)
s_rendererDataListFieldInfo = typeof(UniversalRenderPipelineAsset)
.GetField("m_RendererDataList", BindingFlags.Instance | BindingFlags.NonPublic);
if (s_rendererDataListFieldInfo == null)
return null;
return (ScriptableRendererData[])s_rendererDataListFieldInfo.GetValue(urpAsset);
}
catch (Exception e)
{
Debug.LogError($"Failed to get renderer data list: {e.Message}");
return null;
}
}
private static int GetDefaultRendererIndex()
{
var urpAsset = UrpAsset;
if (urpAsset == null)
return -1;
try
{
if (s_defaultRendererIndexFieldInfo == null)
s_defaultRendererIndexFieldInfo = typeof(UniversalRenderPipelineAsset)
.GetField("m_DefaultRendererIndex", BindingFlags.Instance | BindingFlags.NonPublic);
if (s_defaultRendererIndexFieldInfo == null)
return -1;
return (int)s_defaultRendererIndexFieldInfo.GetValue(urpAsset);
}
catch (Exception e)
{
Debug.LogError($"Failed to get default renderer index: {e.Message}");
return -1;
}
}
public static UniversalRendererData UniversalRendererData => GetUniversalRendererData();
/// <summary>
/// Get UniversalRendererData by index or default
/// </summary>
/// <param name="rendererIndex">Renderer index. If -1 - than default</param>
/// <returns></returns>
private static UniversalRendererData GetUniversalRendererData(int rendererIndex = -1)
{
var rendererDataList = GetRendererDataList();
if (rendererDataList == null || rendererDataList.Length == 0)
return null;
if (rendererIndex == -1) rendererIndex = GetDefaultRendererIndex();
// Index validation
if (rendererIndex < 0 || rendererIndex >= rendererDataList.Length)
{
Debug.LogWarning(
$"Invalid renderer index {rendererIndex}. Available renderers: {rendererDataList.Length}");
return null;
}
return rendererDataList[rendererIndex] as UniversalRendererData;
}
public static bool IsSsaoNativeEnabled()
{
return HasRendererFeatureByTypeName("ScreenSpaceAmbientOcclusion");
}
private static bool HasRendererFeatureByTypeName(string typeName, int rendererIndex = -1)
{
return GetRendererFeatureByTypeName(typeName, rendererIndex) != null;
}
public static ScriptableRendererFeature GetRendererFeatureByTypeName(string typeName, int rendererIndex = -1)
{
var rendererDataList = GetRendererDataList();
if (rendererDataList == null || rendererDataList.Length == 0)
return null;
var renderersToSearch = new List<ScriptableRendererData>();
if (rendererIndex >= 0 && rendererIndex < rendererDataList.Length)
renderersToSearch.Add(rendererDataList[rendererIndex]);
else
renderersToSearch.AddRange(rendererDataList);
foreach (var rendererData in renderersToSearch)
{
if (rendererData?.rendererFeatures == null) continue;
foreach (var feature in rendererData.rendererFeatures)
{
if (feature == null) continue;
if (feature.GetType().Name.Contains(typeName, StringComparison.OrdinalIgnoreCase)) return feature;
}
}
return null;
}
public static T GetRendererFeature<T>(int rendererIndex = -1) where T : ScriptableRendererFeature
{
var rendererDataList = GetRendererDataList();
if (rendererDataList == null || rendererDataList.Length == 0)
return null;
var renderersToSearch = new List<ScriptableRendererData>();
if (rendererIndex >= 0 && rendererIndex < rendererDataList.Length)
renderersToSearch.Add(rendererDataList[rendererIndex]);
else
renderersToSearch.AddRange(rendererDataList);
foreach (var rendererData in renderersToSearch)
{
if (rendererData?.rendererFeatures == null) continue;
foreach (var feature in rendererData.rendererFeatures)
if (feature is T typedFeature)
return typedFeature;
}
return null;
}
private static bool ContainsRenderFeature(List<ScriptableRendererFeature> features, string name)
{
if (features == null) return false;
for (var i = 0; i < features.Count; i++)
if (features[i]?.name == name)
return true;
return false;
}
public static void AddHTraceRendererFeatureToUniversalRendererData()
{
var universalRendererData = UniversalRendererData;
if (universalRendererData?.rendererFeatures == null)
{
Debug.LogWarning("Universal Renderer Data not found or has no features list");
return;
}
var features = universalRendererData.rendererFeatures;
CleanupRendererFeatures(features);
if (!ContainsRenderFeature(features, nameof(HTraceSSGIRendererFeature)))
AddHTraceRendererFeature(universalRendererData, features);
universalRendererData.SetDirty();
}
private static void CleanupRendererFeatures(List<ScriptableRendererFeature> features)
{
for (var i = features.Count - 1; i >= 0; i--)
{
var feature = features[i];
// Delete null elements
if (feature == null)
{
features.RemoveAt(i);
continue;
}
if (feature.GetType() == typeof(HTraceSSGIRendererFeature)) features.RemoveAt(i);
}
}
private static void AddHTraceRendererFeature(UniversalRendererData universalRendererData, List<ScriptableRendererFeature> features)
{
try
{
var hTraceFeature = ScriptableObject.CreateInstance<HTraceSSGIRendererFeature>();
AssetDatabase.AddObjectToAsset(hTraceFeature, universalRendererData);
features.Add(hTraceFeature);
Debug.Log($"{HNames.ASSET_NAME} Renderer Feature added successfully");
}
catch (Exception e)
{
Debug.LogError($"Failed to add {HNames.ASSET_NAME} Renderer Feature: {e.Message}");
}
}
/// <summary>
/// Get all renderer features by Type in all RendererDatas
/// </summary>
/// <typeparam name="T">Тип renderer feature</typeparam>
/// <returns></returns>
public static List<T> GetAllRendererFeatures<T>() where T : ScriptableRendererFeature
{
var result = new List<T>();
var rendererDataList = GetRendererDataList();
if (rendererDataList == null) return result;
foreach (var rendererData in rendererDataList)
{
if (rendererData?.rendererFeatures == null) continue;
foreach (var feature in rendererData.rendererFeatures)
if (feature is T typedFeature)
result.Add(typedFeature);
}
return result;
}
public static int GetRenderersCount()
{
return GetRendererDataList()?.Length ?? 0;
}
#endif // UNITY_EDITOR
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 7c6ca928c19f4bff95978f4d91d3733e
timeCreated: 1757343206
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Globals/HRendererURP.cs
uploadId: 840002

View File

@@ -0,0 +1,75 @@
using UnityEngine;
using UnityEngine.Rendering;
namespace HTraceSSGI.Scripts.Globals
{
public static class HShaderParams
{
// ---------------------------------------------- Globals, "g_" prefix ----------------------------------------------
public static readonly int g_HTraceGBuffer0 = Shader.PropertyToID("g_HTraceGBuffer0");
public static readonly int g_HTraceGBuffer1 = Shader.PropertyToID("g_HTraceGBuffer1");
public static readonly int g_HTraceGBuffer2 = Shader.PropertyToID("g_HTraceGBuffer2");
public static readonly int g_HTraceGBuffer3 = Shader.PropertyToID("g_HTraceGBuffer3");
public static readonly int g_HTraceRenderLayerMask = Shader.PropertyToID("g_HTraceRenderLayerMask");
public static readonly int g_HTraceColor = Shader.PropertyToID("g_HTraceColor");
public static readonly int g_HTraceDepth = Shader.PropertyToID("g_HTraceDepth");
public static readonly int g_HTraceNormals = Shader.PropertyToID("g_HTraceNormals");
public static readonly int g_HTraceSSAO = Shader.PropertyToID("g_HTraceSSAO");
public static readonly int g_HTraceDepthPyramidSSGI = Shader.PropertyToID("g_HTraceDepthPyramidSSGI");
public static readonly int g_HTraceStencilBuffer = Shader.PropertyToID("g_HTraceStencilBuffer");
public static readonly int g_HTraceMotionVectors = Shader.PropertyToID("g_HTraceMotionVectors");
public static readonly int g_HTraceMotionMask = Shader.PropertyToID("g_HTraceMotionMask");
public static readonly int g_HTraceBufferAO = Shader.PropertyToID("_HTraceBufferAO");
public static readonly int g_ScreenSpaceOcclusionTexture = Shader.PropertyToID("_ScreenSpaceOcclusionTexture");
public static readonly int g_CameraDepthTexture = Shader.PropertyToID("_CameraDepthTexture");
public static readonly int g_CameraNormalsTexture = Shader.PropertyToID("_CameraNormalsTexture");
// ---------------------------------------------- GBuffer ----------------------------------------------
public static readonly int _GBuffer0 = Shader.PropertyToID("_GBuffer0");
public static readonly int _GBuffer1 = Shader.PropertyToID("_GBuffer1");
public static readonly int _GBuffer2 = Shader.PropertyToID("_GBuffer2");
public static readonly int _GBuffer3 = Shader.PropertyToID("_GBuffer3");
public static readonly int _CameraRenderingLayersTexture = Shader.PropertyToID("_CameraRenderingLayersTexture");
public static readonly int _GBufferTexture0 = Shader.PropertyToID("_GBufferTexture0");
public static readonly int _RenderingLayerMaskTexture = Shader.PropertyToID("_RenderingLayersTexture");
public static readonly int _CameraGBufferTexture0 = Shader.PropertyToID("_CameraGBufferTexture0");
public static readonly int _DepthPyramid_OutputMIP0 = Shader.PropertyToID("_DepthPyramid_OutputMIP0");
public static readonly int _DepthPyramid_OutputMIP1 = Shader.PropertyToID("_DepthPyramid_OutputMIP1");
public static readonly int _DepthPyramid_OutputMIP2 = Shader.PropertyToID("_DepthPyramid_OutputMIP2");
public static readonly int _DepthPyramid_OutputMIP3 = Shader.PropertyToID("_DepthPyramid_OutputMIP3");
public static readonly int _DepthPyramid_OutputMIP4 = Shader.PropertyToID("_DepthPyramid_OutputMIP4");
public static readonly int H_SHAr = Shader.PropertyToID("H_SHAr");
public static readonly int H_SHAg = Shader.PropertyToID("H_SHAg");
public static readonly int H_SHAb = Shader.PropertyToID("H_SHAb");
public static readonly int H_SHBr = Shader.PropertyToID("H_SHBr");
public static readonly int H_SHBg = Shader.PropertyToID("H_SHBg");
public static readonly int H_SHBb = Shader.PropertyToID("H_SHBb");
public static readonly int H_SHC = Shader.PropertyToID("H_SHC");
public static readonly string _GBUFFER_NORMALS_OCT = "_GBUFFER_NORMALS_OCT";
public static readonly string _WRITE_RENDERING_LAYERS = "_WRITE_RENDERING_LAYERS";
public static readonly ShaderTagId UniversalGBufferTag = new ShaderTagId("UniversalGBuffer");
// ---------------------------------------------- Matrix ----------------------------------------------
public static readonly int H_MATRIX_VP = Shader.PropertyToID("_H_MATRIX_VP");
public static readonly int H_MATRIX_I_VP = Shader.PropertyToID("_H_MATRIX_I_VP");
public static readonly int H_MATRIX_PREV_VP = Shader.PropertyToID("_H_MATRIX_PREV_VP");
public static readonly int H_MATRIX_PREV_I_VP = Shader.PropertyToID("_H_MATRIX_PREV_I_VP");
// ---------------------------------------------- Additional ----------------------------------------------
public static int HRenderScale = Shader.PropertyToID("_HRenderScale");
public static int HRenderScalePrevious = Shader.PropertyToID("_HRenderScalePrevious");
public static int FrameCount = Shader.PropertyToID("_FrameCount");
public static int ScreenSize = Shader.PropertyToID("_ScreenSize");
// ---------------------------------------------- Shared Params Other ----------------------------------------------
public static readonly int SliceXR = Shader.PropertyToID("_SliceXR");
public static readonly int IndexXR = Shader.PropertyToID("_IndexXR");
public static readonly int RTAS = Shader.PropertyToID("_RTAS");
}
}

View File

@@ -0,0 +1,9 @@
fileFormatVersion: 2
guid: 4df35d7b3e464734bb736f10640562a2
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Globals/HShaderParams.cs
uploadId: 840002

View File

@@ -0,0 +1,51 @@
//pipelinedefine
#define H_URP
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Data.Public;
using HTraceSSGI.Scripts.Globals;
using HTraceSSGI.Scripts.Infrastructure.URP;
using UnityEngine;
namespace HTraceSSGI.Scripts
{
[ExecuteAlways, ExecuteInEditMode, ImageEffectAllowedInSceneView, DefaultExecutionOrder(100)]
[HelpURL(HNames.HTRACE_SSGI_DOCUMENTATION_LINK)]
public class HTraceSSGI : MonoBehaviour
{
[Tooltip("Currently used HTrace SSGI profile with settings")]
public HTraceSSGIProfile Profile;
private void OnEnable() {
CheckProfile();
}
private void OnDisable()
{
HTraceSSGISettings.SetProfile(null);
}
void OnValidate() {
CheckProfile();
}
private void Reset() {
CheckProfile();
}
void CheckProfile()
{
if (Profile == null)
{
Profile = ScriptableObject.CreateInstance<HTraceSSGIProfile>();
Profile.name = "New HTrace SSGI Profile";
#if UNITY_EDITOR
UnityEditor.EditorUtility.SetDirty(this);
#endif
}
HTraceSSGISettings.SetProfile(this.Profile);
}
}
}

View File

@@ -0,0 +1,18 @@
fileFormatVersion: 2
guid: dc3b78b63e384f78ba4235b7e210bccc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {fileID: 2800000, guid: 72a9ca4a910cb6e478e3b0b89afa0b3c, type: 3}
userData:
assetBundleName:
assetBundleVariant:
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/HTraceSSGI.cs
uploadId: 840002

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f6b3ef9f6a43b53428590848541b0650
timeCreated: 1724837665

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 39d33876f15f45c091746aa50bedf133
timeCreated: 1745943075

View File

@@ -0,0 +1,180 @@
//pipelinedefine
#define H_URP
using System;
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Data.Public;
using HTraceSSGI.Scripts.Globals;
using UnityEngine;
using UnityEngine.Rendering;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace HTraceSSGI.Scripts.Infrastructure.URP
{
[ExecuteAlways]
public class HAmbientOverrideVolume: MonoBehaviour
{
private Volume _volumeComponent;
#if UNITY_6000_0_OR_NEWER
private ProbeVolumesOptions _probeVolumesOptionsOverrideComponent;
#endif
private static HAmbientOverrideVolume s_instance;
public static HAmbientOverrideVolume Instance
{
get
{
if (s_instance == null)
{
s_instance = FindObjectOfType<HAmbientOverrideVolume>();
if (s_instance == null)
{
GameObject singletonObject = new GameObject($"HTrace AmbientOverride");
s_instance = singletonObject.AddComponent<HAmbientOverrideVolume>();
if (Application.isPlaying)
DontDestroyOnLoad(singletonObject);
}
}
return s_instance;
}
}
public void SetActiveVolume(bool isActive)
{
_volumeComponent.enabled = isActive;
#if UNITY_6000_0_OR_NEWER
_probeVolumesOptionsOverrideComponent.active = isActive;
#endif
}
private void Awake()
{
InitializeSingleton();
SetupVolumeURP();
}
private void InitializeSingleton()
{
if (s_instance == null)
{
s_instance = this;
if (Application.isPlaying)
DontDestroyOnLoad(gameObject);
}
else if (s_instance != this)
{
if (Application.isPlaying)
Destroy(gameObject);
else
DestroyImmediate(gameObject);
}
}
#if UNITY_EDITOR
private void OnValidate()
{
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
if (!EditorApplication.isPlayingOrWillChangePlaymode)
SetupVolumeURP();
gameObject.hideFlags = HideFlags.HideAndDontSave;
if (s_instance != null && profile != null && profile.DebugSettings != null)
s_instance.gameObject.hideFlags = profile.DebugSettings.ShowBowels ? HideFlags.None : HideFlags.HideAndDontSave;
}
#endif
private void OnDestroy()
{
if (s_instance == this)
{
s_instance = null;
}
}
private void SetupVolumeURP()
{
#if UNITY_6000_0_OR_NEWER
CreateSSGIOverrideComponent();
ApplySSGIOverrideComponentSettings();
ChangeObjectWithSerialization_ONLYEDITOR();
#endif
}
#if UNITY_6000_0_OR_NEWER
private void CreateSSGIOverrideComponent()
{
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
if (profile != null && profile != null && profile.DebugSettings != null)
gameObject.hideFlags = profile.DebugSettings.ShowBowels ? HideFlags.None : HideFlags.HideAndDontSave;
_volumeComponent = gameObject.GetComponent<Volume>();
if (_volumeComponent == null)
{
_volumeComponent = gameObject.AddComponent<Volume>();
_volumeComponent.enabled = false;
}
if (_volumeComponent.sharedProfile == null)
{
//We can't crate it in runtime, because after build it will break.
//it will call only in editor, but if someone changes it in runtime, we will override.
_volumeComponent.sharedProfile = Resources.Load<VolumeProfile>($"{HNames.ASSET_NAME}/HTraceSSGI Volume Profile URP");
}
if (_probeVolumesOptionsOverrideComponent == null)
_volumeComponent.sharedProfile.TryGet(out _probeVolumesOptionsOverrideComponent);
}
private void ApplySSGIOverrideComponentSettings()
{
_volumeComponent.weight = 1;
_volumeComponent.priority = 100;
#if UNITY_EDITOR
_volumeComponent.runInEditMode = true;
#endif
if (_probeVolumesOptionsOverrideComponent != null)
{
_probeVolumesOptionsOverrideComponent.normalBias.overrideState = true;
_probeVolumesOptionsOverrideComponent.viewBias.overrideState = true;
_probeVolumesOptionsOverrideComponent.samplingNoise.overrideState = true;
}
}
private void ChangeObjectWithSerialization_ONLYEDITOR()
{
#if UNITY_EDITOR
if (_probeVolumesOptionsOverrideComponent == null)
return;
SerializedObject probeVolumesOptionsObject = new SerializedObject(_probeVolumesOptionsOverrideComponent);
var normalBias = probeVolumesOptionsObject.FindProperty("normalBias");
var m_OverrideState_normalBias = normalBias.FindPropertyRelative("m_OverrideState");
var m_Value_normalBias = normalBias.FindPropertyRelative("m_Value");
m_OverrideState_normalBias.boolValue = true;
m_Value_normalBias.floatValue = 0.0f;
var viewBias = probeVolumesOptionsObject.FindProperty("viewBias");
var m_OverrideState_viewBias = viewBias.FindPropertyRelative("m_OverrideState");
var m_Value_viewBias = viewBias.FindPropertyRelative("m_Value");
m_OverrideState_viewBias.boolValue = true;
m_Value_viewBias.floatValue = 0.0f;
var samplingNoise = probeVolumesOptionsObject.FindProperty("samplingNoise");
var m_OverrideState_samplingNoise = samplingNoise.FindPropertyRelative("m_OverrideState");
var m_Value_samplingNoise = samplingNoise.FindPropertyRelative("m_Value");
m_OverrideState_samplingNoise.boolValue = true;
m_Value_samplingNoise.floatValue = 0.0f;
probeVolumesOptionsObject.ApplyModifiedProperties();
#endif
}
#endif
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 665d2080decf49c2b73ac4747dbde1df
timeCreated: 1757588204
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Infrastructure/URP/HAmbientOverrideVolume.cs
uploadId: 840002

View File

@@ -0,0 +1,229 @@
//pipelinedefine
#define H_URP
using System;
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Data.Public;
using HTraceSSGI.Scripts.Editor;
using HTraceSSGI.Scripts.Globals;
using HTraceSSGI.Scripts.Passes.URP;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
#if UNITY_EDITOR
using HTraceSSGI.Scripts.PipelelinesConfigurator;
using UnityEditor;
#endif
namespace HTraceSSGI.Scripts.Infrastructure.URP
{
[DisallowMultipleRendererFeature]
[ExecuteAlways, ExecuteInEditMode]
[HelpURL(HNames.HTRACE_SSGI_DOCUMENTATION_LINK)]
public class HTraceSSGIRendererFeature : ScriptableRendererFeature
{
public bool UseVolumes = true;
internal static bool IsUseVolumes { get; private set; }
private PrePassURP _prePassURP;
private MotionVectorsURP _motionVectors;
private GBufferPassURP _gBufferPass;
private SSGIPassURP _ssgiPassUrp;
private FinalPassURP _finalPassURP;
private bool _initialized = false;
/// <summary>
/// Initializes this feature's resources. This is called every time serialization happens.
/// </summary>
public override void Create()
{
name = HNames.ASSET_NAME_FULL;
// ActiveProfile = Profile;
IsUseVolumes = UseVolumes;
Dispose();
if (UseVolumes)
{
var stack = VolumeManager.instance.stack;
HTraceSSGIVolume hTraceVolume = stack?.GetComponent<HTraceSSGIVolume>();
SettingsBuild(hTraceVolume);
}
_prePassURP = new PrePassURP();
_prePassURP.renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
_motionVectors = new MotionVectorsURP();
_motionVectors.renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
_gBufferPass = new GBufferPassURP();
_gBufferPass.renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
_ssgiPassUrp = new SSGIPassURP();
_ssgiPassUrp.renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
_finalPassURP = new FinalPassURP();
_finalPassURP.renderPassEvent = RenderPassEvent.AfterRenderingPostProcessing;
#if UNITY_EDITOR
HPipelinesConfigurator.AlwaysIncludedShaders();
#endif
_initialized = true;
}
/// <summary>
/// Called when render targets are allocated and ready to be used.
/// </summary>
/// <param name="renderer"></param>
/// <param name="renderingData"></param>
/// <!--https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@13.1/manual/upgrade-guide-2022-1.html-->
public override void SetupRenderPasses(ScriptableRenderer renderer, in RenderingData renderingData)
{
if (_initialized == false)
return;
if (HRendererURP.RenderGraphEnabled == false)
{
_prePassURP.Initialize(renderer);
_motionVectors.Initialize(renderer);
_gBufferPass.Initialize(renderer);
_ssgiPassUrp.Initialize(renderer);
_finalPassURP.Initialize(renderer);
}
}
/// <summary>
/// Injects one or multiple ScriptableRenderPass in the renderer.
/// </summary>
/// <param name="renderer"></param>
/// <param name="renderingData"></param>
public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingData renderingData)
{
if (renderingData.cameraData.cameraType == CameraType.Reflection || renderingData.cameraData.cameraType == CameraType.Preview)
return;
var isActive = HTraceSSGISettings.ActiveProfile != null;
IsUseVolumes = UseVolumes;
if (UseVolumes)
{
var stack = VolumeManager.instance.stack;
var hTraceVolume = stack.GetComponent<HTraceSSGIVolume>();
isActive = hTraceVolume != null && hTraceVolume.IsActive();
SettingsBuild(hTraceVolume);
}
#if UNITY_6000_0_OR_NEWER
HAmbientOverrideVolume.Instance.SetActiveVolume(isActive && HTraceSSGISettings.ActiveProfile != null && HTraceSSGISettings.ActiveProfile.GeneralSettings != null && HTraceSSGISettings.ActiveProfile.GeneralSettings.AmbientOverride);
#endif
if (!isActive)
return;
#if !UNITY_2022_1_OR_NEWER
_prePassURP.Initialize(renderer);
_motionVectors.Initialize(renderer);
_gBufferPass.Initialize(renderer);
_ssgiPassUrp.Initialize(renderer);
_finalPassURP.Initialize(renderer);
#endif
renderer.EnqueuePass(_prePassURP);
renderer.EnqueuePass(_motionVectors);
renderer.EnqueuePass(_gBufferPass);
renderer.EnqueuePass(_ssgiPassUrp);
renderer.EnqueuePass(_finalPassURP);
}
private void SettingsBuild(HTraceSSGIVolume hTraceVolume)
{
if (hTraceVolume == null || UseVolumes == false)
return;
if (HTraceSSGISettings.ActiveProfile == null)
{
HTraceSSGISettings.SetProfile(ScriptableObject.CreateInstance<HTraceSSGIProfile>());
#if UNITY_EDITOR
HTraceSSGISettings.ActiveProfile.ApplyPreset(HTraceSSGIPreset.Balanced);
#endif
HTraceSSGISettings.ActiveProfile.name = "New HTrace SSGI Profile";
}
var activeProfile = HTraceSSGISettings.ActiveProfile;
// Global Settings
activeProfile.GeneralSettings.DebugMode = hTraceVolume.DebugMode.value;
activeProfile.GeneralSettings.HBuffer = hTraceVolume.HBuffer.value;
// Global - Pipeline Integration
activeProfile.GeneralSettings.MetallicIndirectFallback = hTraceVolume.MetallicIndirectFallback.value;
activeProfile.GeneralSettings.AmbientOverride = hTraceVolume.AmbientOverride.value;
activeProfile.GeneralSettings.Multibounce = hTraceVolume.Multibounce.value;
#if UNITY_2023_3_OR_NEWER
activeProfile.GeneralSettings.ExcludeReceivingMask = hTraceVolume.ExcludeReceivingMask.value;
activeProfile.GeneralSettings.ExcludeCastingMask = hTraceVolume.ExcludeCastingMask.value;
#endif
activeProfile.GeneralSettings.FallbackType = hTraceVolume.FallbackType.value;
activeProfile.GeneralSettings.SkyIntensity = hTraceVolume.SkyIntensity.value;
// APV parameters
activeProfile.GeneralSettings.ViewBias = hTraceVolume.ViewBias.value;
activeProfile.GeneralSettings.NormalBias = hTraceVolume.NormalBias.value;
activeProfile.GeneralSettings.SamplingNoise = hTraceVolume.SamplingNoise.value;
activeProfile.GeneralSettings.IntensityMultiplier = hTraceVolume.IntensityMultiplier.value;
activeProfile.GeneralSettings.DenoiseFallback = hTraceVolume.DenoiseFallback.value;
// Global - Visuals
activeProfile.SSGISettings.BackfaceLighting = hTraceVolume.BackfaceLighting.value;
activeProfile.SSGISettings.MaxRayLength = hTraceVolume.MaxRayLength.value;
activeProfile.SSGISettings.ThicknessMode = hTraceVolume.ThicknessMode.value;
activeProfile.SSGISettings.Thickness = hTraceVolume.Thickness.value;
activeProfile.SSGISettings.Intensity = hTraceVolume.Intensity.value;
activeProfile.SSGISettings.Falloff = hTraceVolume.Falloff.value;
// Quality - Tracing
activeProfile.SSGISettings.RayCount = hTraceVolume.RayCount.value;
activeProfile.SSGISettings.StepCount = hTraceVolume.StepCount.value;
activeProfile.SSGISettings.RefineIntersection = hTraceVolume.RefineIntersection.value;
activeProfile.SSGISettings.FullResolutionDepth = hTraceVolume.FullResolutionDepth.value;
// Quality - Rendering
activeProfile.SSGISettings.Checkerboard = hTraceVolume.Checkerboard.value;
activeProfile.SSGISettings.RenderScale = hTraceVolume.RenderScale.value;
// Denoising
activeProfile.DenoisingSettings.BrightnessClamp = hTraceVolume.BrightnessClamp.value;
activeProfile.DenoisingSettings.MaxValueBrightnessClamp = hTraceVolume.MaxValueBrightnessClamp.value;
activeProfile.DenoisingSettings.MaxDeviationBrightnessClamp = hTraceVolume.MaxDeviationBrightnessClamp.value;
// Denoising - ReSTIR Validation
activeProfile.DenoisingSettings.HalfStepValidation = hTraceVolume.HalfStepValidation.value;
activeProfile.DenoisingSettings.SpatialOcclusionValidation = hTraceVolume.SpatialOcclusionValidation.value;
activeProfile.DenoisingSettings.TemporalLightingValidation = hTraceVolume.TemporalLightingValidation.value;
activeProfile.DenoisingSettings.TemporalOcclusionValidation = hTraceVolume.TemporalOcclusionValidation.value;
// Denoising - Spatial Filter
activeProfile.DenoisingSettings.SpatialRadius = hTraceVolume.SpatialRadius.value;
activeProfile.DenoisingSettings.Adaptivity = hTraceVolume.Adaptivity.value;
activeProfile.DenoisingSettings.RecurrentBlur = hTraceVolume.RecurrentBlur.value;
activeProfile.DenoisingSettings.FireflySuppression = hTraceVolume.FireflySuppression.value;
// Debug
activeProfile.DebugSettings.ShowBowels = hTraceVolume.ShowBowels.value;
}
protected override void Dispose(bool disposing)
{
_prePassURP?.Dispose();
_motionVectors?.Dispose();
_gBufferPass?.Dispose();
_ssgiPassUrp?.Dispose();
_finalPassURP?.Dispose();
_prePassURP = null;
_motionVectors = null;
_gBufferPass = null;
_ssgiPassUrp = null;
_finalPassURP = null;
_initialized = false;
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 43a84b065505d8f41b624b74c882ed4b
timeCreated: 1729922427
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Infrastructure/URP/HTraceSSGIRendererFeature.cs
uploadId: 840002

View File

@@ -0,0 +1,231 @@
//pipelinedefine
#define H_URP
using System;
using HTraceSSGI.Scripts.Globals;
using UnityEditor;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace HTraceSSGI.Scripts.Infrastructure.URP
{
#if UNITY_2023_1_OR_NEWER
[VolumeComponentMenu("Lighting/HTrace: Screen Space Global Illumination"), SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
#else
[VolumeComponentMenuForRenderPipeline("Lighting/HTrace: Screen Space Global Illumination", typeof(UniversalRenderPipeline))]
#endif
#if UNITY_2023_3_OR_NEWER
[VolumeRequiresRendererFeatures(typeof(HTraceSSGIRendererFeature))]
#endif
[HelpURL(HNames.HTRACE_SSGI_DOCUMENTATION_LINK)]
public sealed class HTraceSSGIVolume : VolumeComponent, IPostProcessComponent
{
public HTraceSSGIVolume()
{
displayName = HNames.ASSET_NAME_FULL;
}
/// <summary>
/// Enable Screen Space Global Illumination.
/// </summary>
[Tooltip("Enable HTrace Screen Space Global Illumination")]
public BoolParameter Enable = new BoolParameter(false, BoolParameter.DisplayType.EnumPopup);
// --------------------------------------- GLOBAL SETTINGS ---------------------------------------------
[InspectorName("Debug Mode"), Tooltip("")]
public DebugModeParameter DebugMode = new(Globals.DebugMode.None, false);
[InspectorName("Buffer"), Tooltip("Visualizes data from different buffers for debugging")]
public HBufferParameter HBuffer = new(Globals.HBuffer.Multi, false);
#if UNITY_2023_3_OR_NEWER
[InspectorName("Exclude Casting Mask"), Tooltip("Prevents objects on the selected layers from contributing to GI")]
public RenderingLayerMaskEnumParameter ExcludeCastingMask = new(0, false);
[InspectorName("Exclude Receiving Mask"), Tooltip("Prevents objects on the selected layers from receiving GI")]
public RenderingLayerMaskEnumParameter ExcludeReceivingMask = new(0, false);
#endif
[InspectorName("Fallback Type"), Tooltip("Fallback data for rays that failed to find a hit in screen space")]
public FallbackTypeParameter FallbackType = new FallbackTypeParameter(Globals.FallbackType.None, false);
[InspectorName("Sky Intensity"), Tooltip("Brightness of the sky used for fallback")]
public ClampedFloatParameter SkyIntensity = new ClampedFloatParameter(0.5f, 0.0f, 1.0f, false);
[InspectorName("View Bias"), Tooltip("Offsets the APV sample position towards the camera")]
public ClampedFloatParameter ViewBias = new ClampedFloatParameter(0.1f, 0.0f, 2.0f, false);
[InspectorName("Normal Bias"), Tooltip("Offsets the APV sample position along the pixels surface normal")]
public ClampedFloatParameter NormalBias = new ClampedFloatParameter(0.25f, 0.0f, 2.0f, false);
[InspectorName("Sampling Noise"), Tooltip("Amount of jitter noise added to the APV sample position")]
public ClampedFloatParameter SamplingNoise = new ClampedFloatParameter(0.1f, 0.0f, 1.0f, false);
[InspectorName("Intensity Multiplier"), Tooltip("Strength of the light contribution from APV")]
public ClampedFloatParameter IntensityMultiplier = new ClampedFloatParameter(1.0f, 0.0f, 1.0f, false);
[InspectorName("Denoise Fallback"), Tooltip("Includes fallback lighting in denoising")]
public BoolParameter DenoiseFallback = new BoolParameter(true, false);
// ------------------------------------- Pipeline Integration -----------------------------------------
[InspectorName("Metallic Indirect Fallback"), Tooltip("Renders metals as diffuse when no reflections exist, preventing them from going black")]
public BoolParameter MetallicIndirectFallback = new BoolParameter(false, false);
[InspectorName("Ambient Override"), Tooltip("Removes Unitys ambient lighting before HTrace SSGI runs to avoid double GI")]
public BoolParameter AmbientOverride = new BoolParameter(true, false);
[InspectorName("Multibounce"), Tooltip("Uses previous frame GI to approximate additional light bounces")]
public BoolParameter Multibounce = new BoolParameter(true, false);
// -------------------------------------------- Visuals -----------------------------------------------
[InspectorName("Backface Lighting"), Tooltip("Include lighting from back-facing surfaces")]
public ClampedFloatParameter BackfaceLighting = new ClampedFloatParameter(0.25f, 0.0f, 1.0f, false);
[InspectorName("Max Ray Length"), Tooltip("Maximum ray distance in meters")]
public ClampedFloatParameter MaxRayLength = new ClampedFloatParameter(100.0f, 0.0f, float.MaxValue, false);
[InspectorName("Thickness Mode"), Tooltip("Method used for thickness estimation")]
public ThicknessModeParameter ThicknessMode = new(Globals.ThicknessMode.Relative, false);
[InspectorName("Thickness"), Tooltip("Virtual object thickness for ray intersections")]
public ClampedFloatParameter Thickness = new ClampedFloatParameter(0.35f, 0.0f, 1.0f, false);
[InspectorName("Intensity"), Tooltip("Indirect lighting intensity multiplier")]
public ClampedFloatParameter Intensity = new ClampedFloatParameter(1.0f, 0.1f, 5.0f, false);
[InspectorName("Falloff"), Tooltip("Softens indirect lighting over distance")]
public ClampedFloatParameter Falloff = new ClampedFloatParameter(0.0f, 0.0f, 1.0f, false);
// -------------------------------------------- QUALITY -----------------------------------------------
// -------------------------------------------- Tracing -----------------------------------------------
[InspectorName("Ray Count"), Tooltip("Number of rays per pixel")]
public ClampedIntParameter RayCount = new ClampedIntParameter(3, 2, 16, false);
[InspectorName("Step Count"), Tooltip("Number of steps per ray")]
public ClampedIntParameter StepCount = new ClampedIntParameter(24, 8, 64, false);
[InspectorName("Refine Intersection"), Tooltip("Extra check to confirm intersection")]
public BoolParameter RefineIntersection = new BoolParameter(true, false);
[InspectorName("Full Resolution Depth"), Tooltip("Uses full-res depth buffer for tracing")]
public BoolParameter FullResolutionDepth = new BoolParameter(true, false);
// ------------------------------------------- Rendering -----------------------------------------------
[InspectorName("Checkerboard"), Tooltip("Enables checkerboard rendering, processing only half of the pixels per frame")]
public BoolParameter Checkerboard = new BoolParameter(false, false);
[InspectorName("Render Scale"), Tooltip("Local render scale of SSGI pipeline")]
public ClampedFloatParameter RenderScale = new ClampedFloatParameter(1.0f, 0.5f, 1.0f, false);
// ------------------------------------------- DENOISING -----------------------------------------------
[InspectorName("Brightness Clamp"), Tooltip("Defines the maximum brightness at the hit point")]
public BrightnessClampParameter BrightnessClamp = new(Globals.BrightnessClamp.Manual, false);
[InspectorName("Max Value"), Tooltip("Maximum brightness allowed at hit points.")]
public ClampedFloatParameter MaxValueBrightnessClamp = new ClampedFloatParameter(7.0f, 1.0f, 30.0f, false);
[InspectorName("Max Deviation"), Tooltip("Maximum standard deviation for brightness allowed at hit points")]
public ClampedFloatParameter MaxDeviationBrightnessClamp = new ClampedFloatParameter(3.0f, 1.0f, 5.0f, false);
// ---------------------------------------- ReSTIR Validation ------------------------------------------
[InspectorName("Half Step"), Tooltip("Halves validation ray steps")]
public BoolParameter HalfStepValidation = new BoolParameter(false, false);
[InspectorName("Spatial Occlusion"), Tooltip("Protects indirect shadows and details from overblurring")]
public BoolParameter SpatialOcclusionValidation = new BoolParameter(true, false);
[InspectorName("Temporal Lighting"), Tooltip("Faster reaction to changing lighting conditions")]
public BoolParameter TemporalLightingValidation = new BoolParameter(true, false);
[InspectorName("Temporal Occlusion"), Tooltip("Faster reaction to moving indirect shadows")]
public BoolParameter TemporalOcclusionValidation = new BoolParameter(true, false);
// ----------------------------------------- Spatial Filter ---------------------------------------------------
[InspectorName("Spatial"), Tooltip("Width of spatial filter")]
public ClampedFloatParameter SpatialRadius = new ClampedFloatParameter(0.6f, 0.0f, 1.0f, false);
[InspectorName("Adaptivity"), Tooltip("Shrinks the filter radius in geometry corners to preserve details")]
public ClampedFloatParameter Adaptivity = new ClampedFloatParameter(0.9f, 0.0f, 1.0f, false);
[InspectorName("Recurrent Blur"), Tooltip("Makes blur stronger by using the spatial output as temporal history")]
public BoolParameter RecurrentBlur = new BoolParameter(false, false);
[InspectorName("Firefly Suppression"), Tooltip("Removes bright outliers before denoising")]
public BoolParameter FireflySuppression = new BoolParameter(false, false);
// ----------------------------------------------- Debug -----------------------------------------------------
public BoolParameter ShowBowels = new BoolParameter(false, true);
public bool IsActive()
{
return Enable.value;
}
#if !UNITY_2023_2_OR_NEWER
public bool IsTileCompatible() => false;
#endif
[Serializable]
public sealed class HBufferParameter : VolumeParameter<HBuffer>
{
/// <param name="value">The initial value to store in the parameter.</param>
/// <param name="overrideState">The initial override state for the parameter.</param>
public HBufferParameter(HBuffer value, bool overrideState = false) : base(value, overrideState) { }
}
[Serializable]
public sealed class DebugModeParameter : VolumeParameter<DebugMode>
{
/// <param name="value">The initial value to store in the parameter.</param>
/// <param name="overrideState">The initial override state for the parameter.</param>
public DebugModeParameter(DebugMode value, bool overrideState = false) : base(value, overrideState) { }
}
#if UNITY_2023_3_OR_NEWER
[Serializable]
public sealed class RenderingLayerMaskEnumParameter : VolumeParameter<RenderingLayerMask>
{
/// <param name="value">The initial value to store in the parameter.</param>
/// <param name="overrideState">The initial override state for the parameter.</param>
public RenderingLayerMaskEnumParameter(RenderingLayerMask value, bool overrideState = false) : base(value, overrideState) { }
}
#endif
[Serializable]
public sealed class FallbackTypeParameter : VolumeParameter<FallbackType>
{
/// <param name="value">The initial value to store in the parameter.</param>
/// <param name="overrideState">The initial override state for the parameter.</param>
public FallbackTypeParameter(FallbackType value, bool overrideState = false) : base(value, overrideState) { }
}
[Serializable]
public sealed class ThicknessModeParameter : VolumeParameter<ThicknessMode>
{
/// <param name="value">The initial value to store in the parameter.</param>
/// <param name="overrideState">The initial override state for the parameter.</param>
public ThicknessModeParameter(ThicknessMode value, bool overrideState = false) : base(value, overrideState) { }
}
[Serializable]
public sealed class BrightnessClampParameter : VolumeParameter<BrightnessClamp>
{
/// <param name="value">The initial value to store in the parameter.</param>
/// <param name="overrideState">The initial override state for the parameter.</param>
public BrightnessClampParameter(BrightnessClamp value, bool overrideState = false) : base(value, overrideState) { }
}
}
}

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 5f17acff6deb4f089d110375635d4e37
timeCreated: 1756743404
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/Infrastructure/URP/HTraceSSGIVolume.cs
uploadId: 840002

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1da92c815c29dea40bd8c6c3d6f75312
timeCreated: 1674801896

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7a79b752c0a5472889da303294bb41c1
timeCreated: 1756743088

View File

@@ -0,0 +1,63 @@
using UnityEngine;
using UnityEngine.Rendering;
namespace HTraceSSGI.Scripts.Passes.Shared
{
internal static class HBlueNoise
{
internal static readonly int g_OwenScrambledTexture = Shader.PropertyToID("g_OwenScrambledTexture");
internal static readonly int g_ScramblingTileXSPP = Shader.PropertyToID("g_ScramblingTileXSPP");
internal static readonly int g_RankingTileXSPP = Shader.PropertyToID("g_RankingTileXSPP");
internal static readonly int g_ScramblingTexture = Shader.PropertyToID("g_ScramblingTexture");
private static Texture2D _owenScrambledTexture;
public static Texture2D OwenScrambledTexture
{
get
{
if (_owenScrambledTexture == null)
_owenScrambledTexture = UnityEngine.Resources.Load<Texture2D>("HTraceSSGI/BlueNoise/OwenScrambledNoise256");
return _owenScrambledTexture;
}
}
private static Texture2D _scramblingTileXSPP;
public static Texture2D ScramblingTileXSPP
{
get
{
if (_scramblingTileXSPP == null)
_scramblingTileXSPP = UnityEngine.Resources.Load<Texture2D>("HTraceSSGI/BlueNoise/ScramblingTile8SPP");
return _scramblingTileXSPP;
}
}
private static Texture2D _rankingTileXSPP;
public static Texture2D RankingTileXSPP
{
get
{
if (_rankingTileXSPP == null)
_rankingTileXSPP = UnityEngine.Resources.Load<Texture2D>("HTraceSSGI/BlueNoise/RankingTile8SPP");
return _rankingTileXSPP;
}
}
private static Texture2D _scramblingTexture;
public static Texture2D ScramblingTexture
{
get
{
if (_scramblingTexture == null)
_scramblingTexture = UnityEngine.Resources.Load<Texture2D>("HTraceSSGI/BlueNoise/ScrambleNoise");
return _scramblingTexture;
}
}
public static void SetTextures(CommandBuffer cmdList)
{
cmdList.SetGlobalTexture(g_OwenScrambledTexture, OwenScrambledTexture);
cmdList.SetGlobalTexture(g_ScramblingTileXSPP, ScramblingTileXSPP);
cmdList.SetGlobalTexture(g_RankingTileXSPP, RankingTileXSPP);
cmdList.SetGlobalTexture(g_ScramblingTexture, ScramblingTexture);
}
}
}

View File

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

View File

@@ -0,0 +1,667 @@
//pipelinedefine
#define H_URP
using System;
using HTraceSSGI.Scripts.Data.Private;
using HTraceSSGI.Scripts.Data.Public;
using HTraceSSGI.Scripts.Extensions;
using HTraceSSGI.Scripts.Extensions.CameraHistorySystem;
using HTraceSSGI.Scripts.Globals;
using HTraceSSGI.Scripts.Wrappers;
using UnityEngine;
using UnityEngine.Rendering;
using HTraceSSGI.Scripts.Infrastructure.URP;
namespace HTraceSSGI.Scripts.Passes.Shared
{
internal class SSGI
{
// Kernels
internal enum HTemporalReprojectionKernels
{
TemporalReprojection = 0,
ColorReprojection = 1,
CopyHistory = 2,
LuminanceMomentsGeneration = 3,
LuminanceMomentsClear = 4,
}
internal enum HCheckerboardingKernels
{
CheckerboardClassification = 0,
IndirectArguments = 1,
}
internal enum HRenderSSGIKernels
{
TraceSSGI = 0,
MaskExclude = 1,
}
internal enum HReSTIRKernels
{
TemporalResampling = 0,
FireflySuppression = 1,
SpatialResampling = 2,
SpatialValidation = 3,
}
internal enum HDenoiserKernels
{
TemporalAccumulation = 0,
TemporalStabilization = 1,
PointDistributionFill = 2,
SpatialFilter = 3,
SpatialFilter1 = 4,
SpatialFilter2 = 5,
}
internal enum HInterpolationKernels
{
Interpolation = 0,
}
// Textures, except History
public static RTWrapper ColorCopy_URP = new RTWrapper(); // URP only
public static RTWrapper DebugOutput = new RTWrapper();
public static RTWrapper ReservoirLuminance = new RTWrapper();
public static RTWrapper Reservoir = new RTWrapper();
public static RTWrapper ReservoirReprojected = new RTWrapper();
public static RTWrapper ReservoirSpatial = new RTWrapper();
public static RTWrapper SamplecountReprojected = new RTWrapper();
public static RTWrapper TemporalInvalidityFilteredA = new RTWrapper();
public static RTWrapper TemporalInvalidityFilteredB = new RTWrapper();
public static RTWrapper TemporalInvalidityReprojected = new RTWrapper();
public static RTWrapper SpatialOcclusionReprojected = new RTWrapper();
public static RTWrapper AmbientOcclusion = new RTWrapper();
public static RTWrapper AmbientOcclusionGuidance = new RTWrapper();
public static RTWrapper AmbientOcclusionInvalidity = new RTWrapper();
public static RTWrapper AmbientOcclusionReprojected = new RTWrapper();
public static RTWrapper RadianceReprojected = new RTWrapper();
public static RTWrapper RadianceFiltered = new RTWrapper();
public static RTWrapper RadianceInterpolated = new RTWrapper();
public static RTWrapper RadianceStabilized = new RTWrapper();
public static RTWrapper RadianceStabilizedReprojected = new RTWrapper();
public static RTWrapper RadianceNormalDepth = new RTWrapper();
public static RTWrapper ColorReprojected = new RTWrapper();
public static RTWrapper DummyBlackTexture = new RTWrapper();
// History Textures
internal struct HistoryCameraDataSSGI : ICameraHistoryData, IDisposable
{
private int hash;
public RTWrapper ColorPreviousFrame;
public RTWrapper ReservoirTemporal;
public RTWrapper SampleCount;
public RTWrapper NormalDepth;
public RTWrapper NormalDepthFullRes;
public RTWrapper Radiance;
public RTWrapper RadianceAccumulated;
public RTWrapper SpatialOcclusionAccumulated;
public RTWrapper TemporalInvalidityAccumulated;
public RTWrapper AmbientOcclusionAccumulated;
public HistoryCameraDataSSGI(int hash = 0)
{
this.hash = hash;
ColorPreviousFrame = new RTWrapper();
ReservoirTemporal = new RTWrapper();
SampleCount = new RTWrapper();
NormalDepth = new RTWrapper();
NormalDepthFullRes = new RTWrapper();
Radiance = new RTWrapper();
RadianceAccumulated = new RTWrapper();
SpatialOcclusionAccumulated = new RTWrapper();
TemporalInvalidityAccumulated = new RTWrapper();
AmbientOcclusionAccumulated = new RTWrapper();
}
public int GetHash() => hash;
public void SetHash(int hashIn) => this.hash = hashIn;
public void Dispose()
{
ColorPreviousFrame?.HRelease();
ReservoirTemporal?.HRelease();
SampleCount?.HRelease();
NormalDepth?.HRelease();
NormalDepthFullRes?.HRelease();
Radiance?.HRelease();
RadianceAccumulated?.HRelease();
SpatialOcclusionAccumulated?.HRelease();
TemporalInvalidityAccumulated?.HRelease();
AmbientOcclusionAccumulated?.HRelease();
}
}
internal static readonly CameraHistorySystem<HistoryCameraDataSSGI> CameraHistorySystem = new CameraHistorySystem<HistoryCameraDataSSGI>();
// Shader Properties
public static readonly int _RayCounter = Shader.PropertyToID("_RayCounter");
public static readonly int _RayCounter_Output = Shader.PropertyToID("_RayCounter_Output");
public static readonly int _IndirectCoords_Output = Shader.PropertyToID("_IndirectCoords_Output");
public static readonly int _IndirectArguments_Output = Shader.PropertyToID("_IndirectArguments_Output");
public static readonly int _TracingCoords = Shader.PropertyToID("_TracingCoords");
public static readonly int _RayTracedCounter = Shader.PropertyToID("_RayTracedCounter");
public static readonly int _DepthToViewParams = Shader.PropertyToID("_DepthToViewParams");
public static readonly int _HScaleFactorSSGI = Shader.PropertyToID("_HScaleFactorSSGI");
public static readonly int _HPreviousScaleFactorSSGI = Shader.PropertyToID("_HPreviousScaleFactorSSGI");
public static readonly int _ReservoirDiffuseWeight = Shader.PropertyToID("_ReservoirDiffuseWeight");
public static readonly int _ExcludeCastingLayerMaskSSGI = Shader.PropertyToID("_ExcludeCastingLayerMaskSSGI");
public static readonly int _ExcludeReceivingLayerMaskSSGI = Shader.PropertyToID("_ExcludeReceivingLayerMaskSSGI");
public static readonly int _APVParams = Shader.PropertyToID("_APVParams");
public static readonly int _BrightnessClamp = Shader.PropertyToID("_BrightnessClamp");
public static readonly int _MaxDeviation = Shader.PropertyToID("_MaxDeviation");
public static readonly int _RayCount = Shader.PropertyToID("_RayCount");
public static readonly int _StepCount = Shader.PropertyToID("_StepCount");
public static readonly int _RayLength = Shader.PropertyToID("_RayLength");
public static readonly int _SkyFallbackIntensity = Shader.PropertyToID("_SkyFallbackIntensity");
public static readonly int _BackfaceLighting = Shader.PropertyToID("_BackfaceLighting");
public static readonly int _Falloff = Shader.PropertyToID("_Falloff");
public static readonly int _ThicknessParams = Shader.PropertyToID("_ThicknessParams");
public static readonly int _DenoiseFallback = Shader.PropertyToID("_DenoiseFallback");
public static readonly int _FilterAdaptivity = Shader.PropertyToID("_FilterAdaptivity");
public static readonly int _FilterRadius = Shader.PropertyToID("_FilterRadius");
public static readonly int _ColorCopy = Shader.PropertyToID("_ColorCopy");
public static readonly int _Color_History = Shader.PropertyToID("_Color_History");
public static readonly int _LuminanceMoments = Shader.PropertyToID("_LuminanceMoments");
public static readonly int _Radiance_History = Shader.PropertyToID("_Radiance_History");
public static readonly int _RadianceNormalDepth = Shader.PropertyToID("_RadianceNormalDepth");
public static readonly int _Radiance_Output = Shader.PropertyToID("_Radiance_Output");
public static readonly int _NormalDepth_History = Shader.PropertyToID("_NormalDepth_History");
public static readonly int _ReprojectedColor_Output = Shader.PropertyToID("_ReprojectedColor_Output");
public static readonly int _Samplecount_History = Shader.PropertyToID("_Samplecount_History");
public static readonly int _Samplecount_Output = Shader.PropertyToID("_Samplecount_Output");
public static readonly int _SpatialOcclusion_History = Shader.PropertyToID("_SpatialOcclusion_History");
public static readonly int _SpatialOcclusion_Output = Shader.PropertyToID("_SpatialOcclusion_Output");
public static readonly int _PointDistribution_Output = Shader.PropertyToID("_PointDistribution_Output");
public static readonly int _Reservoir = Shader.PropertyToID("_Reservoir");
public static readonly int _Reservoir_Output = Shader.PropertyToID("_Reservoir_Output");
public static readonly int _TemporalInvalidity_History = Shader.PropertyToID("_TemporalInvalidity_History");
public static readonly int _TemporalInvalidity_Output = Shader.PropertyToID("_TemporalInvalidity_Output");
public static readonly int _AmbientOcclusion_History = Shader.PropertyToID("_AmbientOcclusion_History");
public static readonly int _AmbientOcclusion_Output = Shader.PropertyToID("_AmbientOcclusion_Output");
public static readonly int _SampleCount = Shader.PropertyToID("_SampleCount");
public static readonly int _Color = Shader.PropertyToID("_Color");
public static readonly int _AmbientOcclusion = Shader.PropertyToID("_AmbientOcclusion");
public static readonly int _AmbientOcclusionInvalidity = Shader.PropertyToID("_AmbientOcclusionInvalidity");
public static readonly int _AmbientOcclusionReprojected = Shader.PropertyToID("_AmbientOcclusionReprojected");
public static readonly int _SpatialOcclusion = Shader.PropertyToID("_SpatialOcclusion");
public static readonly int _ReservoirReprojected = Shader.PropertyToID("_ReservoirReprojected");
public static readonly int _ReservoirSpatial_Output = Shader.PropertyToID("_ReservoirSpatial_Output");
public static readonly int _ReservoirLuminance = Shader.PropertyToID("_ReservoirLuminance");
public static readonly int _ReservoirTemporal_Output = Shader.PropertyToID("_ReservoirTemporal_Output");
public static readonly int _TemporalInvalidity = Shader.PropertyToID("_TemporalInvalidity");
public static readonly int _NormalDepth_HistoryOutput = Shader.PropertyToID("_NormalDepth_HistoryOutput");
public static readonly int _ReservoirLuminance_Output = Shader.PropertyToID("_ReservoirLuminance_Output");
public static readonly int _SpatialGuidance_Output = Shader.PropertyToID("_SpatialGuidance_Output");
public static readonly int _PointDistribution = Shader.PropertyToID("_PointDistribution");
public static readonly int _NormalDepth = Shader.PropertyToID("_NormalDepth");
public static readonly int _RadianceNormalDepth_Output = Shader.PropertyToID("_RadianceNormalDepth_Output");
public static readonly int _SpatialGuidance = Shader.PropertyToID("_SpatialGuidance");
public static readonly int _SamplecountReprojected = Shader.PropertyToID("_SamplecountReprojected");
public static readonly int _Radiance = Shader.PropertyToID("_Radiance");
public static readonly int _RadianceReprojected = Shader.PropertyToID("_RadianceReprojected");
public static readonly int _Radiance_TemporalOutput = Shader.PropertyToID("_Radiance_TemporalOutput");
public static readonly int _Radiance_SpatialOutput = Shader.PropertyToID("_Radiance_SpatialOutput");
public static readonly int _SampleCountSSGI = Shader.PropertyToID("_SampleCountSSGI");
public static readonly int _HTraceBufferGI = Shader.PropertyToID("_HTraceBufferGI");
public static readonly int _IndirectLightingIntensity = Shader.PropertyToID("_IndirectLightingIntensity");
public static readonly int _MetallicIndirectFallback = Shader.PropertyToID("_MetallicIndirectFallback");
private static readonly int _DebugSwitch = Shader.PropertyToID("_DebugSwitch");
private static readonly int _BuffersSwitch = Shader.PropertyToID("_BuffersSwitch");
private static readonly int _Debug_Output = Shader.PropertyToID("_Debug_Output");
// Keywords
public static readonly string VR_COMPATIBILITY = "VR_COMPATIBILITY";
public static readonly string USE_TEMPORAL_INVALIDITY = "USE_TEMPORAL_INVALIDITY";
public static readonly string USE_RECEIVE_LAYER_MASK = "USE_RECEIVE_LAYER_MASK";
public static readonly string USE_SPATIAL_OCCLUSION = "USE_SPATIAL_OCCLUSION";
public static readonly string INTERPOLATION_OUTPUT = "INTERPOLATION_OUTPUT";
public static readonly string VALIDATE_SPATIAL_OCCLUSION = "VALIDATE_SPATIAL_OCCLUSION";
public static readonly string AUTOMATIC_THICKNESS = "AUTOMATIC_THICKNESS";
public static readonly string LINEAR_THICKNESS = "LINEAR_THICKNESS";
public static readonly string UNIFORM_THICKNESS = "UNIFORM_THICKNESS";
public static readonly string CHECKERBOARDING = "CHECKERBOARDING";
public static readonly string FALLBACK_APV = "FALLBACK_APV";
public static readonly string FALLBACK_SKY = "FALLBACK_SKY";
public static readonly string FULL_RESOLUTION_DEPTH = "FULL_RESOLUTION_DEPTH";
public static readonly string REFINE_INTERSECTION = "REFINE_INTERSECTION";
public static readonly string VALIDATE_TEMPORAL_OCCLUSION = "VALIDATE_TEMPORAL_OCCLUSION";
public static readonly string VALIDATE_TEMPORAL_LIGHTING = "VALIDATE_TEMPORAL_LIGHTING";
public static readonly string HALF_STEP_VALIDATION = "HALF_STEP_VALIDATION";
public static readonly string REPROJECT_TEMPORAL_INVALIDITY = "REPROJECT_TEMPORAL_INVALIDITY";
public static readonly string AUTOMATIC_BRIGHTNESS_CLAMP = "AUTOMATIC_BRIGHTNESS_CLAMP";
public static readonly string REPROJECT_SPATIAL_OCCLUSION = "REPROJECT_SPATIAL_OCCLUSION";
public static readonly string FULL_RESOLUTION_REPROJECTION = "FULL_RESOLUTION_REPROJECTION";
public static readonly string REPROJECT_COLOR = "REPROJECT_COLOR";
// Profiler Samplers
public static ProfilingSampler AmbientLightingOverrideSampler = new ProfilingSampler("Ambient Lighting Override");
public static ProfilingSampler TemporalReprojectionSampler = new ProfilingSampler("Temporal Reprojection");
public static ProfilingSampler CheckerboardingSampler = new ProfilingSampler("Checkerboarding");
public static ProfilingSampler RadianceTracingSampler = new ProfilingSampler("Trace Radiance");
public static ProfilingSampler RestirTemporalSampler = new ProfilingSampler("ReSTIR Temporal");
public static ProfilingSampler RestirFireflySampler = new ProfilingSampler("ReSTIR Firefly");
public static ProfilingSampler RestirSpatialSampler = new ProfilingSampler("ReSTIR Spatial");
public static ProfilingSampler TemporalAccumulationSampler = new ProfilingSampler("Temporal Accumulation");
public static ProfilingSampler SpatialFilterSampler = new ProfilingSampler("Spatial Filter");
public static ProfilingSampler InterpolationSampler = new ProfilingSampler("Interpolation");
public static ProfilingSampler DebugSampler = new ProfilingSampler("Debug");
public static ProfilingSampler IndirectLightingInjectionSampler = new ProfilingSampler("Indirect Lighting Injection");
// Computes
public static ComputeShader HDebug = null;
public static ComputeShader HRenderSSGI = null;
public static ComputeShader HReSTIR = null;
public static ComputeShader HDenoiser = null;
public static ComputeShader HInterpolation = null;
public static ComputeShader HCheckerboarding = null;
public static ComputeShader PyramidGeneration = null;
public static ComputeShader HTemporalReprojection = null;
// Materials
public static Material ColorCompose_BIRP;
public static Material ColorCompose_URP;
// Buffers
public static ComputeBuffer PointDistributionBuffer;
public static ComputeBuffer LuminanceMoments;
public static ComputeBuffer IndirectArguments;
public static ComputeBuffer RayCounter;
public static HDynamicBuffer IndirectCoords;
// Variables
public static RenderTexture finalOutput;
internal struct HistoryData : IHistoryData
{
public bool RecurrentBlur;
public float ScaleFactor;
public void Update()
{
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
RecurrentBlur = profile.DenoisingSettings.RecurrentBlur;
ScaleFactor = Mathf.Round(1.0f / profile.SSGISettings.RenderScale * 100f) / 100f;
}
}
internal static HistoryData History = new HistoryData();
internal static void Execute(CommandBuffer cmd, Camera camera, int cameraWidth, int cameraHeight, RTHandle cameraColorBuffer = null, RTHandle previousColorBuffer = null)
{
HTraceSSGIProfile profile = HTraceSSGISettings.ActiveProfile;
bool UseAPV = false;
bool UseInterpolation = Mathf.Approximately(profile.SSGISettings.RenderScale, 1.0f) ? false : true;
float RenderScaleFactor = (Mathf.Round(1.0f / profile.SSGISettings.RenderScale * 100f) / 100f);
// Depth to PositionVS parameters
float FovRadians = camera.fieldOfView * Mathf.Deg2Rad;
float TanHalfFOVY = Mathf.Tan(FovRadians * 0.5f);
float invHalfTanFov = 1 / TanHalfFOVY;
Vector2 focalLen = new Vector2(invHalfTanFov * ((float)cameraWidth / (float)cameraWidth), invHalfTanFov);
Vector2 invFocalLen = new Vector2(1 / focalLen.x, 1 / focalLen.y);
Vector4 DepthToViewParams = new Vector4(2 * invFocalLen.x, 2 * invFocalLen.y, -1 * invFocalLen.x, -1 * invFocalLen.y);
// Tracing thickness management
float Thickness = Mathf.Clamp(profile.SSGISettings.Thickness, 0.05f, 1.0f);
float n = camera.nearClipPlane;
float f = camera.farClipPlane;
Vector4 ThicknessScaleBias = new Vector4();
ThicknessScaleBias.x = 1.0f / (1.0f + Thickness / 5.0f);
ThicknessScaleBias.y = -n / (f - n) * (Thickness / 5.0f * ThicknessScaleBias.x);
ThicknessScaleBias.z = 1.0f / (1.0f + Thickness / 5.0f * 2.0f);
ThicknessScaleBias.w = -n / (f - n) * (Thickness / 5.0f * 2.0f * ThicknessScaleBias.z);
if ((int)profile.SSGISettings.ThicknessMode == 1)
{
ThicknessScaleBias.x = 1.0f;
ThicknessScaleBias.y = Thickness;
ThicknessScaleBias.z = 1.0f;
ThicknessScaleBias.w = Thickness * 2.0f;
}
// Spatial radius management
float FilterRadiusReSTIR = profile.DenoisingSettings.SpatialRadius - 0.25f; // HData.DenoisingData.SpatialRadius / 2.0f;
float FilterRadiusDenoiser = FilterRadiusReSTIR * 0.7f;
FilterRadiusReSTIR = FilterRadiusReSTIR.RoundToCeilTail(1);
FilterRadiusDenoiser = FilterRadiusDenoiser.RoundToCeilTail(1);
// ---------------------------------------- PARAMETERS SET ---------------------------------------- //
cmd.SetGlobalVector(_DepthToViewParams, DepthToViewParams);
cmd.SetGlobalFloat(_HScaleFactorSSGI, RenderScaleFactor);
cmd.SetGlobalFloat(_HPreviousScaleFactorSSGI, History.ScaleFactor);
cmd.SetGlobalFloat(_ReservoirDiffuseWeight, profile.GeneralSettings.DebugMode == DebugMode.GlobalIllumination ? 0.0f : 1.0f);
#if UNITY_2023_3_OR_NEWER
cmd.SetGlobalInt(_ExcludeCastingLayerMaskSSGI, profile.GeneralSettings.ExcludeCastingMask);
cmd.SetGlobalInt(_ExcludeReceivingLayerMaskSSGI, profile.GeneralSettings.ExcludeReceivingMask);
#endif
cmd.SetGlobalVector(_APVParams, new Vector4(profile.GeneralSettings.NormalBias, profile.GeneralSettings.ViewBias, profile.GeneralSettings.SamplingNoise, profile.GeneralSettings.IntensityMultiplier));
cmd.SetComputeFloatParam(HTemporalReprojection, _BrightnessClamp, profile.DenoisingSettings.MaxValueBrightnessClamp);
cmd.SetComputeFloatParam(HTemporalReprojection, _MaxDeviation, profile.DenoisingSettings.MaxDeviationBrightnessClamp);
cmd.SetComputeIntParam(HRenderSSGI, _RayCount, profile.SSGISettings.RayCount);
cmd.SetComputeIntParam(HRenderSSGI, _StepCount, profile.SSGISettings.StepCount);
cmd.SetComputeFloatParam(HRenderSSGI, _RayLength, Mathf.Max(profile.SSGISettings.MaxRayLength, 0.1f));
cmd.SetComputeFloatParam(HRenderSSGI, _BackfaceLighting, profile.SSGISettings.BackfaceLighting);
cmd.SetComputeFloatParam(HRenderSSGI, _SkyFallbackIntensity, profile.GeneralSettings.SkyIntensity);
cmd.SetComputeFloatParam(HRenderSSGI, _Falloff, profile.SSGISettings.Falloff);
cmd.SetComputeVectorParam(HRenderSSGI, _ThicknessParams, ThicknessScaleBias);
cmd.SetComputeIntParam(HReSTIR, _DenoiseFallback, (profile.GeneralSettings.DenoiseFallback || profile.GeneralSettings.FallbackType == FallbackType.None) ? 1 : 0);
cmd.SetComputeIntParam(HReSTIR, _RayCount, profile.SSGISettings.RayCount);
cmd.SetComputeIntParam(HReSTIR, _StepCount, profile.SSGISettings.StepCount);
cmd.SetComputeFloatParam(HReSTIR, _RayLength, Mathf.Max(profile.SSGISettings.MaxRayLength, 0.1f));
cmd.SetComputeFloatParam(HReSTIR, _BackfaceLighting, profile.SSGISettings.BackfaceLighting);
cmd.SetComputeFloatParam(HReSTIR, _FilterAdaptivity, profile.DenoisingSettings.Adaptivity);
cmd.SetComputeFloatParam(HReSTIR, _Falloff, profile.SSGISettings.Falloff);
cmd.SetComputeFloatParam(HReSTIR, _FilterRadius, FilterRadiusReSTIR);
cmd.SetComputeVectorParam(HReSTIR, _ThicknessParams, ThicknessScaleBias);
cmd.SetComputeFloatParam(HDenoiser, _FilterAdaptivity, profile.DenoisingSettings.Adaptivity);
cmd.SetComputeFloatParam(HDenoiser, _FilterRadius, FilterRadiusDenoiser);
cmd.SetComputeFloatParam(HDenoiser, _StepCount, profile.SSGISettings.StepCount);
RTWrapper ColorPreviousFrame = CameraHistorySystem.GetCameraData().ColorPreviousFrame;
RTWrapper ReservoirTemporal = CameraHistorySystem.GetCameraData().ReservoirTemporal;
RTWrapper SampleCount = CameraHistorySystem.GetCameraData().SampleCount;
RTWrapper NormalDepth = CameraHistorySystem.GetCameraData().NormalDepth;
RTWrapper NormalDepthFullRes = CameraHistorySystem.GetCameraData().NormalDepthFullRes;
RTWrapper Radiance = CameraHistorySystem.GetCameraData().Radiance;
RTWrapper RadianceAccumulated = CameraHistorySystem.GetCameraData().RadianceAccumulated;
RTWrapper SpatialOcclusionAccumulated = CameraHistorySystem.GetCameraData().SpatialOcclusionAccumulated;
RTWrapper TemporalInvalidityAccumulated = CameraHistorySystem.GetCameraData().TemporalInvalidityAccumulated;
RTWrapper AmbientOcclusionAccumulated = CameraHistorySystem.GetCameraData().AmbientOcclusionAccumulated;
// ---------------------------------------- TEMPORAL REPROJECTION ---------------------------------------- //
using (new ProfilingScope(cmd, TemporalReprojectionSampler))
{
var CurrentColorBuffer = ColorPreviousFrame.rt;
var PreviousColorBuffer = ColorPreviousFrame.rt;
CurrentColorBuffer = cameraColorBuffer;
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.LuminanceMomentsGeneration, _Color_History, profile.GeneralSettings.Multibounce ? PreviousColorBuffer : CurrentColorBuffer);
cmd.SetComputeBufferParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.LuminanceMomentsGeneration, _LuminanceMoments, LuminanceMoments);
cmd.DispatchCompute(HTemporalReprojection, (int)HTemporalReprojectionKernels.LuminanceMomentsGeneration, Mathf.CeilToInt(cameraWidth / 8.0f), Mathf.CeilToInt(cameraHeight / 8.0f), 1);
KeywordSwitch(HTemporalReprojection, profile.DenoisingSettings.TemporalLightingValidation | profile.DenoisingSettings.TemporalOcclusionValidation, REPROJECT_TEMPORAL_INVALIDITY);
KeywordSwitch(HTemporalReprojection, profile.DenoisingSettings.BrightnessClamp == BrightnessClamp.Automatic, AUTOMATIC_BRIGHTNESS_CLAMP);
KeywordSwitch(HTemporalReprojection, profile.DenoisingSettings.SpatialOcclusionValidation, REPROJECT_SPATIAL_OCCLUSION);
KeywordSwitch(HTemporalReprojection, UseInterpolation == false, FULL_RESOLUTION_REPROJECTION);
KeywordSwitch(HTemporalReprojection, profile.GeneralSettings.Multibounce, REPROJECT_COLOR);
if (UseInterpolation)
{
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.ColorReprojection, _Color_History, PreviousColorBuffer);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.ColorReprojection, _Radiance_History, RadianceStabilized.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.ColorReprojection, _Radiance_Output, RadianceStabilizedReprojected.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.ColorReprojection, _NormalDepth_History, NormalDepthFullRes.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.ColorReprojection, _ReprojectedColor_Output, ColorReprojected.rt);
cmd.SetComputeBufferParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.ColorReprojection, _LuminanceMoments, LuminanceMoments);
cmd.DispatchCompute(HTemporalReprojection, (int)HTemporalReprojectionKernels.ColorReprojection, Mathf.CeilToInt(cameraWidth / 8.0f), Mathf.CeilToInt(cameraHeight / 8.0f), HRenderer.TextureXrSlices);
}
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _Color_History, PreviousColorBuffer);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _Samplecount_History, SampleCount.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _Samplecount_Output, SamplecountReprojected.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _NormalDepth_History, NormalDepth.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _ReprojectedColor_Output, ColorReprojected.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _Radiance_Output, RadianceReprojected.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _Radiance_History, profile.DenoisingSettings.RecurrentBlur ? Radiance.rt : RadianceAccumulated.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _SpatialOcclusion_History, SpatialOcclusionAccumulated.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _SpatialOcclusion_Output, SpatialOcclusionReprojected.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _Reservoir, ReservoirTemporal.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _Reservoir_Output, ReservoirReprojected.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _TemporalInvalidity_History, TemporalInvalidityAccumulated.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _TemporalInvalidity_Output, TemporalInvalidityReprojected.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _AmbientOcclusion_History, AmbientOcclusionAccumulated.rt);
cmd.SetComputeTextureParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _AmbientOcclusion_Output, AmbientOcclusionReprojected.rt);
cmd.SetComputeBufferParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, _LuminanceMoments, LuminanceMoments);
cmd.DispatchCompute(HTemporalReprojection, (int)HTemporalReprojectionKernels.TemporalReprojection, Mathf.CeilToInt(cameraWidth / RenderScaleFactor / 8.0f), Mathf.CeilToInt(cameraHeight / RenderScaleFactor / 8.0f), HRenderer.TextureXrSlices);
cmd.SetComputeBufferParam(HTemporalReprojection, (int)HTemporalReprojectionKernels.LuminanceMomentsClear, _LuminanceMoments, LuminanceMoments);
cmd.DispatchCompute(HTemporalReprojection, (int)HTemporalReprojectionKernels.LuminanceMomentsClear, 1, 1, 1);
}
// ---------------------------------------- CHECKERBOARDING ---------------------------------------- //
if (profile.SSGISettings.Checkerboard)
{
using (new ProfilingScope(cmd, CheckerboardingSampler))
{
cmd.SetComputeTextureParam(HCheckerboarding, (int)HCheckerboardingKernels.CheckerboardClassification, _SampleCount, SamplecountReprojected.rt);
cmd.SetComputeBufferParam(HCheckerboarding, (int)HCheckerboardingKernels.CheckerboardClassification, _RayCounter_Output, RayCounter);
cmd.SetComputeBufferParam(HCheckerboarding, (int)HCheckerboardingKernels.CheckerboardClassification, _IndirectCoords_Output, IndirectCoords.ComputeBuffer);
cmd.DispatchCompute(HCheckerboarding, (int)HCheckerboardingKernels.CheckerboardClassification, Mathf.CeilToInt(cameraWidth / RenderScaleFactor / 8.0f), Mathf.CeilToInt(cameraHeight / RenderScaleFactor / 8.0f), HRenderer.TextureXrSlices);
cmd.SetComputeIntParam(HCheckerboarding, _RayTracedCounter, 0);
cmd.SetComputeBufferParam(HCheckerboarding, (int)HCheckerboardingKernels.IndirectArguments, _RayCounter, RayCounter);
cmd.SetComputeBufferParam(HCheckerboarding, (int)HCheckerboardingKernels.IndirectArguments, _IndirectArguments_Output, IndirectArguments);
cmd.DispatchCompute(HCheckerboarding, (int)HCheckerboardingKernels.IndirectArguments, 1, 1, HRenderer.TextureXrSlices);
}
}
// ---------------------------------------- GI TRACING ---------------------------------------- //
using (new ProfilingScope(cmd, RadianceTracingSampler))
{
CoreUtils.SetRenderTarget(cmd, RadianceFiltered.rt, ClearFlag.Color, Color.clear, 0, CubemapFace.Unknown, -1);
KeywordSwitch(HRenderSSGI, profile.GeneralSettings.FallbackType == FallbackType.Sky, FALLBACK_SKY);
KeywordSwitch(HRenderSSGI, (int)profile.GeneralSettings.FallbackType == 2 /* Only in HDRP & URP 6000+ */, FALLBACK_APV);
KeywordSwitch(HRenderSSGI, profile.SSGISettings.Checkerboard, CHECKERBOARDING);
KeywordSwitch(HRenderSSGI, profile.SSGISettings.RefineIntersection, REFINE_INTERSECTION);
KeywordSwitch(HRenderSSGI, profile.SSGISettings.FullResolutionDepth, FULL_RESOLUTION_DEPTH);
if ((int)profile.SSGISettings.ThicknessMode == 0) {HRenderSSGI.EnableKeyword(LINEAR_THICKNESS); HRenderSSGI.DisableKeyword(UNIFORM_THICKNESS); HRenderSSGI.DisableKeyword(AUTOMATIC_THICKNESS);}
if ((int)profile.SSGISettings.ThicknessMode == 1) {HRenderSSGI.EnableKeyword(UNIFORM_THICKNESS); HRenderSSGI.DisableKeyword(LINEAR_THICKNESS); HRenderSSGI.DisableKeyword(AUTOMATIC_THICKNESS);}
cmd.SetComputeTextureParam(HRenderSSGI, (int)HRenderSSGIKernels.TraceSSGI, _Color, ColorReprojected.rt);
cmd.SetComputeTextureParam(HRenderSSGI, (int)HRenderSSGIKernels.TraceSSGI, _Radiance_Output, RadianceFiltered.rt);
cmd.SetComputeTextureParam(HRenderSSGI, (int)HRenderSSGIKernels.TraceSSGI, _Reservoir_Output, Reservoir.rt);
cmd.SetComputeTextureParam(HRenderSSGI, (int)HRenderSSGIKernels.TraceSSGI, _AmbientOcclusion_Output, AmbientOcclusion.rt);
cmd.SetComputeTextureParam(HRenderSSGI, (int)HRenderSSGIKernels.TraceSSGI, _SampleCount, SamplecountReprojected.rt);
cmd.SetComputeBufferParam(HRenderSSGI, (int)HRenderSSGIKernels.TraceSSGI, _RayCounter, RayCounter);
cmd.SetComputeBufferParam(HRenderSSGI, (int)HRenderSSGIKernels.TraceSSGI, _TracingCoords, IndirectCoords.ComputeBuffer);
if (profile.SSGISettings.Checkerboard)
{
cmd.SetComputeIntParam(HRenderSSGI, HShaderParams.IndexXR, 0);
cmd.DispatchCompute(HRenderSSGI, (int)HRenderSSGIKernels.TraceSSGI, IndirectArguments, 0);
if (HRenderer.TextureXrSlices > 1)
{
cmd.SetComputeIntParam(HRenderSSGI, HShaderParams.IndexXR, 1);
cmd.DispatchCompute(HRenderSSGI, (int)HRenderSSGIKernels.TraceSSGI, IndirectArguments, sizeof(uint) * 3);
}
}
else cmd.DispatchCompute(HRenderSSGI, (int)HRenderSSGIKernels.TraceSSGI, Mathf.CeilToInt(cameraWidth / RenderScaleFactor / 8.0f), Mathf.CeilToInt(cameraHeight / RenderScaleFactor / 8.0f), HRenderer.TextureXrSlices);
}
// ---------------------------------------- RESTIR TEMPORAL ---------------------------------------- //
using (new ProfilingScope(cmd, RestirTemporalSampler))
{
KeywordSwitch(HReSTIR, profile.DenoisingSettings.TemporalOcclusionValidation, VALIDATE_TEMPORAL_OCCLUSION);
KeywordSwitch(HReSTIR, profile.DenoisingSettings.TemporalLightingValidation, VALIDATE_TEMPORAL_LIGHTING);
KeywordSwitch(HReSTIR, profile.DenoisingSettings.HalfStepValidation, HALF_STEP_VALIDATION);
KeywordSwitch(HReSTIR, profile.SSGISettings.FullResolutionDepth, FULL_RESOLUTION_DEPTH);
KeywordSwitch(HReSTIR, profile.SSGISettings.Checkerboard, CHECKERBOARDING);
if ((int)profile.SSGISettings.ThicknessMode == 0) {HReSTIR.EnableKeyword(LINEAR_THICKNESS); HReSTIR.DisableKeyword(UNIFORM_THICKNESS); HReSTIR.DisableKeyword(AUTOMATIC_THICKNESS);}
if ((int)profile.SSGISettings.ThicknessMode == 1) {HReSTIR.EnableKeyword(UNIFORM_THICKNESS); HReSTIR.DisableKeyword(LINEAR_THICKNESS); HReSTIR.DisableKeyword(AUTOMATIC_THICKNESS);}
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _Radiance_Output, RadianceFiltered.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _SampleCount, SamplecountReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _Color, ColorReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _AmbientOcclusion, AmbientOcclusion.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _AmbientOcclusionInvalidity, AmbientOcclusionInvalidity.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _AmbientOcclusionReprojected, AmbientOcclusionReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _AmbientOcclusion_Output, AmbientOcclusionAccumulated.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _SpatialOcclusion, SpatialOcclusionReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _Reservoir, Reservoir.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _ReservoirReprojected, ReservoirReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _ReservoirSpatial_Output, ReservoirSpatial.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _ReservoirTemporal_Output, ReservoirTemporal.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _TemporalInvalidity, TemporalInvalidityReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _TemporalInvalidity_Output, TemporalInvalidityAccumulated.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _NormalDepth_HistoryOutput, NormalDepth.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _ReservoirLuminance_Output, ReservoirLuminance.rt);
cmd.SetComputeBufferParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _RayCounter, RayCounter);
cmd.SetComputeBufferParam(HReSTIR, (int)HReSTIRKernels.TemporalResampling, _TracingCoords, IndirectCoords.ComputeBuffer);
cmd.DispatchCompute(HReSTIR, (int)HReSTIRKernels.TemporalResampling, Mathf.CeilToInt(cameraWidth / RenderScaleFactor / 8.0f), Mathf.CeilToInt(cameraHeight / RenderScaleFactor / 8.0f), HRenderer.TextureXrSlices);
}
// ---------------------------------------- RESTIR FIREFLY ---------------------------------------- //
using (new ProfilingScope(cmd, RestirFireflySampler))
{
if (profile.DenoisingSettings.FireflySuppression)
{
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.FireflySuppression, _SampleCount, SamplecountReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.FireflySuppression, _ReservoirLuminance, ReservoirLuminance.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.FireflySuppression, _ReservoirSpatial_Output, ReservoirSpatial.rt);
cmd.DispatchCompute(HReSTIR, (int)HReSTIRKernels.FireflySuppression, Mathf.CeilToInt(cameraWidth / RenderScaleFactor / 8.0f), Mathf.CeilToInt(cameraHeight / RenderScaleFactor / 8.0f), HRenderer.TextureXrSlices);
}
}
// ---------------------------------------- RESTIR SPATIAL ---------------------------------------- //
using (new ProfilingScope(cmd, RestirSpatialSampler))
{
KeywordSwitch(HReSTIR, profile.DenoisingSettings.SpatialOcclusionValidation, VALIDATE_SPATIAL_OCCLUSION);
KeywordSwitch(HReSTIR, HRenderer.TextureXrSlices > 1, VR_COMPATIBILITY);
cmd.SetComputeBufferParam(HDenoiser, (int)HDenoiserKernels.PointDistributionFill, _PointDistribution_Output, PointDistributionBuffer);
cmd.DispatchCompute(HDenoiser, (int)HDenoiserKernels.PointDistributionFill, 1, 1, 1);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialResampling, _Reservoir, ReservoirSpatial.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialResampling, _Reservoir_Output, Reservoir.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialResampling, _SampleCount, SamplecountReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialResampling, _TemporalInvalidity, TemporalInvalidityAccumulated.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialResampling, _TemporalInvalidity_Output, TemporalInvalidityFilteredA.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialResampling, _AmbientOcclusion, AmbientOcclusionAccumulated.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialResampling, _SpatialGuidance_Output, AmbientOcclusionGuidance.rt);
cmd.SetComputeBufferParam(HReSTIR, (int)HReSTIRKernels.SpatialResampling, _PointDistribution, PointDistributionBuffer);
cmd.DispatchCompute(HReSTIR, (int)HReSTIRKernels.SpatialResampling, Mathf.CeilToInt(cameraWidth / RenderScaleFactor / 8.0f), Mathf.CeilToInt(cameraHeight / RenderScaleFactor / 8.0f), HRenderer.TextureXrSlices);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _Color, ColorReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _Radiance_Output, Radiance.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _SampleCount, SamplecountReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _AmbientOcclusion, AmbientOcclusionAccumulated.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _Reservoir, Reservoir.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _Reservoir_Output, ReservoirSpatial.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _SpatialOcclusion, SpatialOcclusionReprojected.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _SpatialOcclusion_Output, SpatialOcclusionAccumulated.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _TemporalInvalidity, TemporalInvalidityFilteredA.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _TemporalInvalidity_Output, TemporalInvalidityFilteredB.rt);
cmd.SetComputeTextureParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _SpatialGuidance, AmbientOcclusionGuidance.rt);
cmd.SetComputeBufferParam(HReSTIR, (int)HReSTIRKernels.SpatialValidation, _PointDistribution, PointDistributionBuffer);
cmd.DispatchCompute(HReSTIR, (int)HReSTIRKernels.SpatialValidation, Mathf.CeilToInt(cameraWidth / RenderScaleFactor / 8.0f), Mathf.CeilToInt(cameraHeight / RenderScaleFactor / 8.0f), HRenderer.TextureXrSlices);
}
// ---------------------------------------- DENOISER TEMPORAL ---------------------------------------- //
using (new ProfilingScope(cmd, TemporalAccumulationSampler))
{
KeywordSwitch(HDenoiser, profile.DenoisingSettings.TemporalLightingValidation | profile.DenoisingSettings.TemporalOcclusionValidation, USE_TEMPORAL_INVALIDITY);
KeywordSwitch(HDenoiser, HRenderer.TextureXrSlices > 1, VR_COMPATIBILITY);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalAccumulation, _TemporalInvalidity, TemporalInvalidityFilteredB.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalAccumulation, _SamplecountReprojected, SamplecountReprojected.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalAccumulation, _Samplecount_Output, SampleCount.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalAccumulation, _Radiance, Radiance.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalAccumulation, _RadianceReprojected, RadianceReprojected.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalAccumulation, _Radiance_TemporalOutput, RadianceAccumulated.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalAccumulation, _Radiance_SpatialOutput, RadianceFiltered.rt);
cmd.DispatchCompute(HDenoiser, (int)HDenoiserKernels.TemporalAccumulation, Mathf.CeilToInt(cameraWidth / RenderScaleFactor / 8.0f), Mathf.CeilToInt(cameraHeight / RenderScaleFactor / 8.0f), HRenderer.TextureXrSlices);
}
// ---------------------------------------- DENOISER SPATIAL ---------------------------------------- //
using (new ProfilingScope(cmd, SpatialFilterSampler))
{
KeywordSwitch(HDenoiser, profile.DenoisingSettings.SpatialOcclusionValidation, USE_SPATIAL_OCCLUSION);
KeywordSwitch(HDenoiser, UseInterpolation, INTERPOLATION_OUTPUT);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter1, _NormalDepth, NormalDepth.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter1, _SpatialGuidance, AmbientOcclusionGuidance.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter1, _AmbientOcclusion, AmbientOcclusionAccumulated.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter1, _Radiance, RadianceFiltered.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter1, _Radiance_Output, Radiance.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter1, _SpatialOcclusion, SpatialOcclusionAccumulated.rt);
cmd.SetComputeBufferParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter1, _PointDistribution, PointDistributionBuffer);
cmd.DispatchCompute(HDenoiser, (int)HDenoiserKernels.SpatialFilter1, Mathf.CeilToInt(cameraWidth / RenderScaleFactor / 8.0f), Mathf.CeilToInt(cameraHeight / RenderScaleFactor / 8.0f), HRenderer.TextureXrSlices);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter2, _NormalDepth, NormalDepth.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter2, _SpatialGuidance, AmbientOcclusionGuidance.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter2, _AmbientOcclusion, AmbientOcclusionAccumulated.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter2, _Radiance, Radiance.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter2, _Radiance_Output, RadianceFiltered.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter2, _RadianceNormalDepth_Output, RadianceNormalDepth.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter2, _SpatialOcclusion, SpatialOcclusionAccumulated.rt);
cmd.SetComputeBufferParam(HDenoiser, (int)HDenoiserKernels.SpatialFilter2, _PointDistribution, PointDistributionBuffer);
cmd.DispatchCompute(HDenoiser, (int)HDenoiserKernels.SpatialFilter2, Mathf.CeilToInt(cameraWidth / RenderScaleFactor / 8.0f), Mathf.CeilToInt(cameraHeight / RenderScaleFactor / 8.0f), HRenderer.TextureXrSlices);
}
// ---------------------------------------- INTERPOLATION SPATIAL ---------------------------------------- //
using (new ProfilingScope(cmd, InterpolationSampler))
{
if (UseInterpolation)
{
KeywordSwitch(HInterpolation, HRenderer.TextureXrSlices > 1, VR_COMPATIBILITY);
// Interpolation
cmd.SetComputeTextureParam(HInterpolation, (int)HInterpolationKernels.Interpolation, _RadianceNormalDepth, RadianceNormalDepth.rt);
cmd.SetComputeTextureParam(HInterpolation, (int)HInterpolationKernels.Interpolation, _Radiance_Output, RadianceInterpolated.rt);
cmd.SetComputeTextureParam(HInterpolation, (int)HInterpolationKernels.Interpolation, _NormalDepth_HistoryOutput, NormalDepthFullRes.rt);
cmd.DispatchCompute(HInterpolation, (int)HInterpolationKernels.Interpolation, Mathf.CeilToInt(cameraWidth / 8.0f), Mathf.CeilToInt(cameraHeight / 8.0f), HRenderer.TextureXrSlices);
// Stabilization
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalStabilization, _TemporalInvalidity, TemporalInvalidityFilteredB.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalStabilization, _SamplecountReprojected, SamplecountReprojected.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalStabilization, _Radiance, RadianceInterpolated.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalStabilization, _RadianceReprojected, RadianceStabilizedReprojected.rt);
cmd.SetComputeTextureParam(HDenoiser, (int)HDenoiserKernels.TemporalStabilization, _Radiance_TemporalOutput, RadianceStabilized.rt);
cmd.DispatchCompute(HDenoiser, (int)HDenoiserKernels.TemporalStabilization, Mathf.CeilToInt(cameraWidth / 8.0f), Mathf.CeilToInt(cameraHeight / 8.0f), HRenderer.TextureXrSlices);
}
}
finalOutput = Mathf.Approximately(profile.SSGISettings.RenderScale, 1.0f) ? SSGI.RadianceFiltered.rt : SSGI.RadianceInterpolated.rt;
// --------------------------------------------- DEBUG ----------------------------------------------- //
using (new ProfilingScope(cmd, DebugSampler))
{
if (profile.GeneralSettings.DebugMode != DebugMode.None && profile.GeneralSettings.DebugMode != DebugMode.DirectLighting)
{
cmd.SetComputeIntParams(HDebug, _DebugSwitch, (int)profile.GeneralSettings.DebugMode);
cmd.SetComputeIntParams(HDebug, _BuffersSwitch, (int)profile.GeneralSettings.HBuffer);
cmd.SetComputeTextureParam(HDebug, 0, _Debug_Output, DebugOutput.rt);
cmd.SetComputeTextureParam(HDebug, 0, _SampleCountSSGI, SamplecountReprojected.rt);
cmd.SetComputeTextureParam(HDebug, 0, _HTraceBufferGI, finalOutput);
cmd.DispatchCompute(HDebug, 0, Mathf.CeilToInt(cameraWidth / 8.0f), Mathf.CeilToInt(cameraHeight / 8.0f), HRenderer.TextureXrSlices);
cmd.SetGlobalTexture(_Debug_Output, DebugOutput.rt);
}
}
}
private static void KeywordSwitch(ComputeShader compute, bool state, string keyword)
{
if (state)
compute.EnableKeyword(keyword);
else
compute.DisableKeyword(keyword);
}
}
}

View File

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

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e4b8bb5cb72847444bf29135c1e77513
timeCreated: 1729952262

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

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5c9550853c2ae314088c0f219f0a04f3
timeCreated: 1730454117

View File

@@ -0,0 +1,48 @@
//pipelinedefine
#define H_URP
#if UNITY_EDITOR
using UnityEditor;
namespace HTraceSSGI.Scripts.Patcher
{
//it's Raytracing Patcher for 2022
public class InstalledPackage// : AssetPostprocessor
{
// [InitializeOnLoadMethod]
private static void InitializeOnLoad()
{
// #if UNITY_2022
// string filePath_hRenderRTAO = Path.Combine(ConfiguratorUtils.GetHTraceFolderPath(), "Resources", "HTraceSSGI", "Computes", "HRenderRTAO.compute");
//
// if (File.Exists(filePath_hRenderRTAO) && File.ReadAllLines(filePath_hRenderRTAO).Length > 10)
// {
// string[] hRenderRTAO2022 = new string[]
// {
// "#pragma kernel RenderRTAO",
// "[numthreads(8, 8, 1)]",
// "void RenderRTAO(uint3 pixCoord : SV_DispatchThreadID, uint groupIndex : SV_GroupIndex, uint groupID : SV_GroupID)",
// "{",
// "}",
// };
//
// File.WriteAllLines(filePath_hRenderRTAO, hRenderRTAO2022);
// }
//
// string filePath_hMainHSLS = Path.Combine(ConfiguratorUtils.GetHTraceFolderPath(), "Resources", "HTraceSSGI", "Headers", "HMain.hlsl");
// if (File.Exists(filePath_hMainHSLS))
// {
// string[] allLines_hMainHSLS = File.ReadAllLines(filePath_hMainHSLS);
// if (string.IsNullOrEmpty(allLines_hMainHSLS[3]))
// {
// allLines_hMainHSLS[3] = "#define _RTHandleScale float4(1.0f, 1.0f, 1.0f, 1.0f)";
// File.WriteAllLines(filePath_hMainHSLS, allLines_hMainHSLS);
// }
// }
//
// AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate);
// #endif
}
}
}
#endif

View File

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

View File

@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e00f51d0fe7b9fc4692645cfc5b3c9be
timeCreated: 1729006149

View File

@@ -0,0 +1,84 @@
//pipelinedefine
#define H_URP
#if UNITY_EDITOR
using System;
using System.IO;
using System.Linq;
using UnityEngine;
namespace HTraceSSGI.Scripts.PipelelinesConfigurator
{
public static class ConfiguratorUtils
{
public static string GetFullHdrpPath()
{
string targetPathStandart = Path.Combine(Directory.GetCurrentDirectory(), "Library", "PackageCache");
string hdrpPathStandart = Directory.GetDirectories(targetPathStandart)
.FirstOrDefault(name => name.Contains("high-definition") && !name.Contains("config"));
string targetPathCustom = Path.Combine(Directory.GetCurrentDirectory(), "Packages");
string hdrpPathCustom = Directory.GetDirectories(targetPathCustom)
.FirstOrDefault(name => name.Contains("high-definition") && !name.Contains("config"));
if (string.IsNullOrEmpty(hdrpPathStandart) && string.IsNullOrEmpty(hdrpPathCustom))
{
Debug.LogError($"HDRP path was not found there: {hdrpPathStandart}\n and there:\n{hdrpPathCustom}");
}
return string.IsNullOrEmpty(hdrpPathStandart) ? hdrpPathCustom : hdrpPathStandart;
}
public static string GetHTraceFolderPath()
{
//string filePath = AssetDatabase.GetAssetPath(MonoScript.FromMonoBehaviour(this));
string filePath = new System.Diagnostics.StackTrace(true).GetFrame(0).GetFileName();
string htraceFolder = Directory.GetParent(Directory.GetParent(Path.GetDirectoryName(filePath)).FullName).FullName;
return htraceFolder;
}
public static string GetUnityAndHdrpVersion()
{
return $"Unity {Application.unityVersion}, HDRP version {GetHdrpVersion()}";
}
public static string GetHdrpVersion()
{
string fullHdrpPath = GetFullHdrpPath();
string pathPackageJson = Path.Combine(fullHdrpPath, "package.json");
string[] packageJson = File.ReadAllLines(pathPackageJson);
string hdrpVersion = string.Empty;
foreach (string line in packageJson)
{
if (line.Contains("version"))
{
hdrpVersion = line.Replace("version", "").Replace(" ", "").Replace(":", "").Replace(",", "").Replace("\"", "");
break;
}
}
return hdrpVersion;
}
public static int GetMajorHdrpVersion()
{
string hdrpVersion = GetHdrpVersion();
string[] split = hdrpVersion.Split('.');
return Convert.ToInt32(split[0]);
}
public static int GetMinorHdrpVersion()
{
string hdrpVersion = GetHdrpVersion();
string[] split = hdrpVersion.Split('.');
return Convert.ToInt32(split[1]);
}
public static int GetPatchHdrpVersion()
{
string hdrpVersion = GetHdrpVersion();
string[] split = hdrpVersion.Split('.');
return Convert.ToInt32(split[2]);
}
}
}
#endif

View File

@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 47b546814df5cef4797c41e297dc66d6
timeCreated: 1729006593
AssetOrigin:
serializedVersion: 1
productId: 336896
packageName: 'HTrace: Screen Space Global Illumination URP'
packageVersion: 1.2.0
assetPath: Assets/HTraceSSGI/Scripts/PipelelinesConfigurator/ConfiguratorUtiles.cs
uploadId: 840002

Some files were not shown because too many files have changed in this diff Show More