diff --git a/.gitattributes b/.gitattributes
index 05481a1b526..fcc798703c2 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -378,3 +378,7 @@ Editor/Resources/unity[[:space:]]editor[[:space:]]resources filter=lfs diff=lfs
# buginfo tools
/Tools/Unity.BugInfo.Coverage/bin/* filter=lfs diff=lfs merge=lfs -text
+
+# search test cases
+/Modules/QuickSearch/Tests/QuickSearch/Assets/Cases/UUM-113048/uum-113048.index filter=lfs diff=lfs merge=lfs -text
+
diff --git a/Packages/com.unity.render-pipelines.core/Documentation~/Examples/BlitColorAndDepth.shader b/Packages/com.unity.render-pipelines.core/Documentation~/Examples/BlitColorAndDepth.shader
index cc99e427ec6..94762042f5d 100644
--- a/Packages/com.unity.render-pipelines.core/Documentation~/Examples/BlitColorAndDepth.shader
+++ b/Packages/com.unity.render-pipelines.core/Documentation~/Examples/BlitColorAndDepth.shader
@@ -5,7 +5,7 @@ Shader "Hidden/Universal/CoreBlitColorAndDepth"
#pragma editor_sync_compilation
// Core.hlsl for XR dependencies
#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
- #include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/BlitColorAndDepth.hlsl"
+ #include_with_pragmas "Packages/com.unity.render-pipelines.core/Runtime/Utilities/BlitColorAndDepth.hlsl"
ENDHLSL
SubShader
diff --git a/Packages/com.unity.render-pipelines.core/Documentation~/Images/videos/light-anchor-animation.mp4 b/Packages/com.unity.render-pipelines.core/Documentation~/Images/videos/light-anchor-animation.mp4
index 1b7784f1e57..053921f77c8 100644
Binary files a/Packages/com.unity.render-pipelines.core/Documentation~/Images/videos/light-anchor-animation.mp4 and b/Packages/com.unity.render-pipelines.core/Documentation~/Images/videos/light-anchor-animation.mp4 differ
diff --git a/Packages/com.unity.render-pipelines.core/Documentation~/whats-new-17.md b/Packages/com.unity.render-pipelines.core/Documentation~/whats-new-17.md
index 0aee2ac7f4f..eb305f87c54 100644
--- a/Packages/com.unity.render-pipelines.core/Documentation~/whats-new-17.md
+++ b/Packages/com.unity.render-pipelines.core/Documentation~/whats-new-17.md
@@ -1,4 +1,8 @@
-# What's new in SRP Core 17.1 / Unity 6.1
+# What's new in SRP Core 17 / Unity 6
+
+**Note:** Starting with 17.2 (Unity 6.2), refer to [What’s new in Unity](xref:um-whats-new) for the latest updates and improvements.
+
+## What's new in SRP Core 17.1 / Unity 6.1
The following are the new features and improvements added to the SRP Core package 17.1, embedded Unity 6.1.
## Added
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Upgraders.meta b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/AssetCallbacks.meta
similarity index 77%
rename from Packages/com.unity.render-pipelines.high-definition/Editor/Upgraders.meta
rename to Packages/com.unity.render-pipelines.core/Editor-PrivateShared/AssetCallbacks.meta
index acbc18ff7f6..6c70f0aa22c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Upgraders.meta
+++ b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/AssetCallbacks.meta
@@ -1,5 +1,5 @@
fileFormatVersion: 2
-guid: 8f178178961a5b244b01761fddf5a5aa
+guid: d2b6d2a66db8e07418eae9d75a2ebb55
folderAsset: yes
DefaultImporter:
externalObjects: {}
diff --git a/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/AssetCallbacks/AssetCreationUtil.cs b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/AssetCallbacks/AssetCreationUtil.cs
new file mode 100644
index 00000000000..664137243cc
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/AssetCallbacks/AssetCreationUtil.cs
@@ -0,0 +1,110 @@
+using System;
+using System.IO;
+using UnityEngine;
+
+namespace UnityEditor.RenderPipelines.Core
+{
+ internal static class AssetCreationUtil
+ {
+ ///
+ /// Prompts the user to save a new asset created from the shader template, and creates and with it.
+ ///
+ /// Default material name.
+ /// A delegate (callback) that will be invoked with the .
+ /// Path of the Shader Template file.
+ internal static void CreateShaderAndMaterial(string name, Action callback, string shaderTemplateAssetPath)
+ {
+ CreateShader(
+ name,
+ (shader) =>
+ {
+ Material material = new Material(shader);
+ var path = AssetDatabase.GetAssetPath(shader);
+ AssetDatabase.CreateAsset(material, Path.Combine(Path.GetDirectoryName(path), Path.GetFileNameWithoutExtension(path) + ".mat"));
+ AssetDatabase.SaveAssetIfDirty(material);
+ AssetDatabase.Refresh(ImportAssetOptions.Default);
+ callback?.Invoke(material);
+ },
+ shaderTemplateAssetPath);
+ }
+
+ ///
+ /// Prompts the user to save a new asset created using the .
+ ///
+ /// Default material name.
+ /// A delegate (callback) that will be invoked with the .
+ /// to create the new with.
+ internal static void CreateMaterial(string name, Action callback, Shader shader)
+ {
+ if (shader == null)
+ {
+ Debug.LogError($"Null Shader reference. Cannot create Material {name}.");
+ return;
+ }
+
+ CreateAsset(
+ name,
+ (materialPath) =>
+ {
+ Material material = new Material(shader);
+ AssetDatabase.CreateAsset(material, materialPath);
+ AssetDatabase.SaveAssetIfDirty(material);
+ AssetDatabase.Refresh(ImportAssetOptions.Default);
+ callback?.Invoke(material);
+ },
+ "mat",
+ typeof(Material)
+ );
+ }
+
+ internal static void CreateShader(string name, Action callback, string shaderTemplateAssetPath)
+ {
+ if (!AssetDatabase.AssetPathExists(shaderTemplateAssetPath))
+ {
+ Debug.LogError($"Shader Template File missing at path: {shaderTemplateAssetPath}.");
+ return;
+ }
+
+ CreateAsset(
+ name,
+ (shaderPath) =>
+ {
+ string fileName = Path.GetFileNameWithoutExtension(shaderPath);
+ string templateCode = File.ReadAllText(shaderTemplateAssetPath);
+ templateCode = templateCode.Replace("#SCRIPTNAME#", fileName);
+ File.WriteAllText(shaderPath, templateCode);
+
+ AssetDatabase.Refresh();
+ AssetDatabase.ImportAsset(shaderPath);
+ Shader shader = AssetDatabase.LoadAssetAtPath(shaderPath);
+
+ callback?.Invoke(shader);
+ },
+ "shader",
+ typeof(Shader)
+ );
+ }
+
+ static void CreateAsset(string name, Action callback = null, string extension = "asset", Type type = null)
+ {
+ AssetCreationCallback assetCreationCallback = ScriptableObject.CreateInstance();
+ assetCreationCallback.callback = callback;
+ assetCreationCallback.extension = extension;
+
+ var icon = AssetPreview.GetMiniTypeThumbnail(type);
+ ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, assetCreationCallback, name, icon, null, false);
+ }
+
+ class AssetCreationCallback : ProjectWindowCallback.EndNameEditAction
+ {
+ public Action callback;
+ public string extension;
+
+ public override void Action(int instanceId, string pathName, string resourceFile)
+ {
+ string path = AssetDatabase.GenerateUniqueAssetPath(pathName + $".{extension}");
+ callback?.Invoke(path);
+ }
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/AssetCallbacks/AssetCreationUtil.cs.meta b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/AssetCallbacks/AssetCreationUtil.cs.meta
new file mode 100644
index 00000000000..1ed34fe995a
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor-PrivateShared/AssetCallbacks/AssetCreationUtil.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 7401208cb37292748ba71a2a214f9c01
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Editor/AssemblyInfo.cs b/Packages/com.unity.render-pipelines.core/Editor/AssemblyInfo.cs
index da38b033da5..8b43a084d74 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/AssemblyInfo.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/AssemblyInfo.cs
@@ -3,6 +3,6 @@
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Core.Editor.Shared")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Core.Editor.Tests")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition.Editor.Tests")]
-[assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition.Editor.Tests")]
+[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor.Tests")]
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")]
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Icons/.buginfo b/Packages/com.unity.render-pipelines.core/Editor/Icons/.buginfo
index 232e4ce2766..dab9babb33b 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Icons/.buginfo
+++ b/Packages/com.unity.render-pipelines.core/Editor/Icons/.buginfo
@@ -1,4 +1,5 @@
-area: SRP Settings
+default:
+ area: SRP Settings
graphic-tools:
when:
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/AdaptiveProbeVolumes.BakePipelineDriver.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/AdaptiveProbeVolumes.BakePipelineDriver.cs
new file mode 100644
index 00000000000..3880a1392be
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/AdaptiveProbeVolumes.BakePipelineDriver.cs
@@ -0,0 +1,89 @@
+using System;
+using System.Reflection;
+using System.Runtime.CompilerServices;
+using UnityEditor.LightBaking;
+
+namespace UnityEngine.Rendering
+{
+ partial class AdaptiveProbeVolumes
+ {
+ // This class is used to (1) access the internal class UnityEditor.LightBaking.BakePipelineDriver and (2) provide a slightly higher level API.
+ private sealed class BakePipelineDriver : IDisposable
+ {
+ // Keep in sync with the enum BakePipeline::Run::StageName
+ public enum StageName : int
+ {
+ Initialized,
+ Preprocess,
+ Bake,
+ PostProcess,
+ AdditionalBake,
+ Done
+ }
+
+ private readonly object _bakePipelineDriver;
+ private readonly Type _bakePipelineDriverType;
+
+ internal BakePipelineDriver()
+ {
+ _bakePipelineDriverType = Type.GetType("UnityEditor.LightBaking.BakePipelineDriver, UnityEditor");
+ bool newed = _bakePipelineDriverType != null;
+ Debug.Assert(newed, "Unexpected, could not find the type UnityEditor.LightBaking.BakePipelineDriver");
+ _bakePipelineDriver = newed ? Activator.CreateInstance(_bakePipelineDriverType) : null;
+ Debug.Assert(_bakePipelineDriver != null, "Unexpected, could not new up a BakePipelineDriver");
+ }
+
+ internal void StartBake(bool enablePatching, ref float progress, ref StageName stage)
+ {
+ SetEnableBakedLightmaps(false); // Additional only
+ SetEnablePatching(enablePatching);
+ Update(false, true, true, out progress, out stage);
+ }
+
+ internal bool RunInProgress()
+ {
+ if (!InvokeMethod(new object[] { }, out object result))
+ return false;
+
+ return result is true;
+ }
+
+ internal void Step(ref float progress, ref StageName stage) =>
+ Update(true, true, true, out progress, out stage);
+
+ private void SetEnableBakedLightmaps(bool enable) =>
+ InvokeMethod(new object[] { enable }, out _);
+
+ private void SetEnablePatching(bool enable) =>
+ InvokeMethod(new object[] { enable }, out _);
+
+ private void Update(bool isOnDemandBakeInProgress, bool isOnDemandBakeAsync, bool shouldBeRunning,
+ out float progress, out StageName stage)
+ {
+ object[] parameters = { isOnDemandBakeInProgress, isOnDemandBakeAsync, shouldBeRunning, -1.0f, -1 };
+ InvokeMethod(parameters, out _);
+ progress = (float)parameters[3];
+ stage = (StageName)parameters[4];
+ }
+
+ public void Dispose() =>
+ InvokeMethod(new object[] { }, out _);
+
+ private bool InvokeMethod(object[] parameters, out object result, [CallerMemberName] string methodName = "")
+ {
+ MethodInfo methodInfo = _bakePipelineDriverType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
+ bool gotMethod = methodInfo != null;
+ Debug.Assert(gotMethod, $"Unexpected, could not find {methodName} on BakePipelineDriver");
+ if (!gotMethod)
+ {
+ result = null;
+ return false;
+ }
+
+ result = methodInfo.Invoke(_bakePipelineDriver, parameters);
+
+ return true;
+ }
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/AdaptiveProbeVolumes.BakePipelineDriver.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/AdaptiveProbeVolumes.BakePipelineDriver.cs.meta
new file mode 100644
index 00000000000..7f81a30826f
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/AdaptiveProbeVolumes.BakePipelineDriver.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 779328fa1a16dcd44965cc2e65be77ed
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeAdjustmentVolumeEditor.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeAdjustmentVolumeEditor.cs
index a923793ec90..117a4fcfeb7 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeAdjustmentVolumeEditor.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeAdjustmentVolumeEditor.cs
@@ -258,10 +258,18 @@ public static void DrawAdjustmentContent(SerializedProbeAdjustmentVolume seriali
options[i] = "Mask " + (i + 1);
}
- EditorGUI.BeginChangeCheck();
- int newMask = EditorGUILayout.MaskField(Styles.renderingLayerMask, serialized.renderingLayerMask.intValue, options);
- if (EditorGUI.EndChangeCheck())
- serialized.renderingLayerMask.uintValue = (uint)newMask;
+ if (options.Length == 0)
+ {
+ using (new EditorGUI.DisabledScope(true))
+ EditorGUILayout.MaskField(Styles.renderingLayerMask, 0, new[] { "Nothing" });
+ }
+ else
+ {
+ EditorGUI.BeginChangeCheck();
+ int newMask = EditorGUILayout.MaskField(Styles.renderingLayerMask, serialized.renderingLayerMask.intValue, options);
+ if (EditorGUI.EndChangeCheck())
+ serialized.renderingLayerMask.uintValue = (uint)newMask;
+ }
}
}
}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeCellDilation.compute b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeCellDilation.compute
index 04dd0fa3d1f..c4a4e85c677 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeCellDilation.compute
+++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeCellDilation.compute
@@ -1,6 +1,6 @@
#pragma kernel DilateCell
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch webgpu
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2 webgpu
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl"
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs
index dffbc3e31da..93fe0f073d5 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeEditor.cs
@@ -148,7 +148,7 @@ public override void OnInspectorGUI()
if (ProbeVolumeLightingTab.GetLightingSettings().realtimeGI)
{
- EditorGUILayout.HelpBox("Adaptive Probe Volumes are not supported when using Enlighten.", MessageType.Warning, wide: true);
+ EditorGUILayout.HelpBox("Adaptive Probe Volumes are not supported when using Realtime Global Illumination(Enlighten).", MessageType.Warning, wide: true);
drawInspector = false;
}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeLightingTab.cs b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeLightingTab.cs
index 4e087fe443d..b7d5271ddef 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeLightingTab.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeLightingTab.cs
@@ -964,6 +964,9 @@ internal bool PrepareAPVBake(ProbeReferenceVolume prv)
if (!prv.isInitialized || !prv.enabledBySRP)
return false;
+ // Always baking with a fresh activeSet
+ activeSet = null;
+
// In case UI was never opened we have to setup some stuff
FindActiveSet();
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeSubdivide.compute b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeSubdivide.compute
index 2b7fb853aee..d6e74780aea 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeSubdivide.compute
+++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/ProbeVolumeSubdivide.compute
@@ -6,7 +6,7 @@
#pragma kernel VoxelizeProbeVolumeData
#pragma kernel Subdivide
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch webgpu
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2 webgpu
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/VirtualOffset/TraceVirtualOffset.urtshader b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/VirtualOffset/TraceVirtualOffset.urtshader
index 0eff6ea7854..f528bf94f5f 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/VirtualOffset/TraceVirtualOffset.urtshader
+++ b/Packages/com.unity.render-pipelines.core/Editor/Lighting/ProbeVolume/VirtualOffset/TraceVirtualOffset.urtshader
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal webgpu switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal webgpu switch switch2
#define UNIFIED_RT_GROUP_SIZE_X 64
#define UNIFIED_RT_GROUP_SIZE_Y 1
diff --git a/Packages/com.unity.render-pipelines.core/Editor/MaterialUpgrader.cs b/Packages/com.unity.render-pipelines.core/Editor/MaterialUpgrader.cs
deleted file mode 100644
index de1841763cd..00000000000
--- a/Packages/com.unity.render-pipelines.core/Editor/MaterialUpgrader.cs
+++ /dev/null
@@ -1,640 +0,0 @@
-using System.Collections.Generic;
-using UnityEngine;
-using System;
-using UnityEngine.Rendering;
-using System.Text;
-
-namespace UnityEditor.Rendering
-{
- ///
- /// Material Upgrader dialog text.
- ///
- public static class DialogText
- {
- /// Material Upgrader title.
- public static readonly string title = "Material Upgrader";
- /// Material Upgrader proceed.
- public static readonly string proceed = "Proceed";
- /// Material Upgrader Ok.
- public static readonly string ok = "OK";
- /// Material Upgrader cancel.
- public static readonly string cancel = "Cancel";
- /// Material Upgrader no selection message.
- public static readonly string noSelectionMessage = "You must select at least one material.";
- /// Material Upgrader project backup message.
- public static readonly string projectBackMessage = "Make sure to have a project backup before proceeding.";
- }
-
- ///
- /// Material Upgrader class.
- ///
- public class MaterialUpgrader
- {
- ///
- /// Material Upgrader finalizer delegate.
- ///
- /// Material
- public delegate void MaterialFinalizer(Material mat);
-
- string m_OldShader;
- string m_NewShader;
-
- private static string[] s_PathsWhiteList = new[]
- {
- "Hidden/",
- "HDRP/",
- "Shader Graphs/"
- };
-
- ///
- /// Retrieves path to new shader.
- ///
- public string NewShaderPath
- {
- get => m_NewShader;
- }
-
- MaterialFinalizer m_Finalizer;
-
- Dictionary m_TextureRename = new Dictionary();
- Dictionary m_FloatRename = new Dictionary();
- Dictionary m_ColorRename = new Dictionary();
-
- Dictionary m_FloatPropertiesToSet = new Dictionary();
- Dictionary m_ColorPropertiesToSet = new Dictionary();
- List m_TexturesToRemove = new List();
- Dictionary m_TexturesToSet = new Dictionary();
-
- class KeywordFloatRename
- {
- public string keyword;
- public string property;
- public float setVal, unsetVal;
- }
- List m_KeywordFloatRename = new List();
-
- ///
- /// Type of property to rename.
- ///
- public enum MaterialPropertyType
- {
- /// Texture reference property.
- Texture,
- /// Float property.
- Float,
- /// Color property.
- Color
- }
-
- ///
- /// Retrieves a collection of renamed parameters of a specific MaterialPropertyType.
- ///
- /// Material Property Type
- /// Dictionary of property names to their renamed values.
- /// type is not valid.
- public IReadOnlyDictionary GetPropertyRenameMap(MaterialPropertyType type)
- {
- switch (type)
- {
- case MaterialPropertyType.Texture: return m_TextureRename;
- case MaterialPropertyType.Float: return m_FloatRename;
- case MaterialPropertyType.Color: return m_ColorRename;
- default: throw new ArgumentException(nameof(type));
- }
- }
-
- ///
- /// Upgrade Flags
- ///
- [Flags]
- public enum UpgradeFlags
- {
- /// None.
- None = 0,
- /// LogErrorOnNonExistingProperty.
- LogErrorOnNonExistingProperty = 1,
- /// CleanupNonUpgradedProperties.
- CleanupNonUpgradedProperties = 2,
- /// LogMessageWhenNoUpgraderFound.
- LogMessageWhenNoUpgraderFound = 4
- }
-
- ///
- /// Upgrade method.
- ///
- /// Material to upgrade.
- /// Upgrade flag
- public void Upgrade(Material material, UpgradeFlags flags)
- {
- Material newMaterial;
- if ((flags & UpgradeFlags.CleanupNonUpgradedProperties) != 0)
- {
- newMaterial = new Material(Shader.Find(m_NewShader));
- }
- else
- {
- newMaterial = UnityEngine.Object.Instantiate(material) as Material;
- newMaterial.shader = Shader.Find(m_NewShader);
- }
-
- Convert(material, newMaterial);
-
- material.shader = Shader.Find(m_NewShader);
- material.CopyPropertiesFromMaterial(newMaterial);
- UnityEngine.Object.DestroyImmediate(newMaterial);
-
- if (m_Finalizer != null)
- m_Finalizer(material);
- }
-
- // Overridable function to implement custom material upgrading functionality
- ///
- /// Custom material conversion method.
- ///
- /// Source material.
- /// Destination material.
- public virtual void Convert(Material srcMaterial, Material dstMaterial)
- {
- foreach (var t in m_TextureRename)
- {
- if (!srcMaterial.HasProperty(t.Key) || !dstMaterial.HasProperty(t.Value))
- continue;
-
- dstMaterial.SetTextureScale(t.Value, srcMaterial.GetTextureScale(t.Key));
- dstMaterial.SetTextureOffset(t.Value, srcMaterial.GetTextureOffset(t.Key));
- dstMaterial.SetTexture(t.Value, srcMaterial.GetTexture(t.Key));
- }
-
- foreach (var t in m_FloatRename)
- {
- if (!srcMaterial.HasProperty(t.Key) || !dstMaterial.HasProperty(t.Value))
- continue;
-
- dstMaterial.SetFloat(t.Value, srcMaterial.GetFloat(t.Key));
- }
-
- foreach (var t in m_ColorRename)
- {
- if (!srcMaterial.HasProperty(t.Key) || !dstMaterial.HasProperty(t.Value))
- continue;
-
- dstMaterial.SetColor(t.Value, srcMaterial.GetColor(t.Key));
- }
-
- foreach (var prop in m_TexturesToRemove)
- {
- if (!dstMaterial.HasProperty(prop))
- continue;
-
- dstMaterial.SetTexture(prop, null);
- }
-
- foreach (var prop in m_TexturesToSet)
- {
- if (!dstMaterial.HasProperty(prop.Key))
- continue;
-
- dstMaterial.SetTexture(prop.Key, prop.Value);
- }
-
- foreach (var prop in m_FloatPropertiesToSet)
- {
- if (!dstMaterial.HasProperty(prop.Key))
- continue;
-
- dstMaterial.SetFloat(prop.Key, prop.Value);
- }
-
- foreach (var prop in m_ColorPropertiesToSet)
- {
- if (!dstMaterial.HasProperty(prop.Key))
- continue;
-
- dstMaterial.SetColor(prop.Key, prop.Value);
- }
-
- foreach (var t in m_KeywordFloatRename)
- {
- if (!dstMaterial.HasProperty(t.property))
- continue;
-
- dstMaterial.SetFloat(t.property, srcMaterial.IsKeywordEnabled(t.keyword) ? t.setVal : t.unsetVal);
- }
- }
-
- ///
- /// Rename shader.
- ///
- /// Old name.
- /// New name.
- /// Finalizer delegate.
- public void RenameShader(string oldName, string newName, MaterialFinalizer finalizer = null)
- {
- m_OldShader = oldName;
- m_NewShader = newName;
- m_Finalizer = finalizer;
- }
-
- ///
- /// Rename Texture Parameter.
- ///
- /// Old name.
- /// New name.
- public void RenameTexture(string oldName, string newName)
- {
- m_TextureRename[oldName] = newName;
- }
-
- ///
- /// Rename Float Parameter.
- ///
- /// Old name.
- /// New name.
- public void RenameFloat(string oldName, string newName)
- {
- m_FloatRename[oldName] = newName;
- }
-
- ///
- /// Rename Color Parameter.
- ///
- /// Old name.
- /// New name.
- public void RenameColor(string oldName, string newName)
- {
- m_ColorRename[oldName] = newName;
- }
-
- ///
- /// Remove Texture Parameter.
- ///
- /// Parameter name.
- public void RemoveTexture(string name)
- {
- m_TexturesToRemove.Add(name);
- }
-
- ///
- /// Set float property.
- ///
- /// Property name.
- /// Property value.
- public void SetFloat(string propertyName, float value)
- {
- m_FloatPropertiesToSet[propertyName] = value;
- }
-
- ///
- /// Set color property.
- ///
- /// Property name.
- /// Property value.
- public void SetColor(string propertyName, Color value)
- {
- m_ColorPropertiesToSet[propertyName] = value;
- }
-
- ///
- /// Set texture property.
- ///
- /// Property name.
- /// Property value.
- public void SetTexture(string propertyName, Texture value)
- {
- m_TexturesToSet[propertyName] = value;
- }
-
- ///
- /// Rename a keyword to float.
- ///
- /// Old name.
- /// New name.
- /// Value when set.
- /// Value when unset.
- public void RenameKeywordToFloat(string oldName, string newName, float setVal, float unsetVal)
- {
- m_KeywordFloatRename.Add(new KeywordFloatRename { keyword = oldName, property = newName, setVal = setVal, unsetVal = unsetVal });
- }
-
- static MaterialUpgrader GetUpgrader(List upgraders, Material material)
- {
- if (material == null || material.shader == null)
- return null;
-
- string shaderName = material.shader.name;
- for (int i = 0; i != upgraders.Count; i++)
- {
- if (upgraders[i].m_OldShader == shaderName)
- return upgraders[i];
- }
-
- return null;
- }
-
- //@TODO: Only do this when it exceeds memory consumption...
- static void SaveAssetsAndFreeMemory()
- {
- AssetDatabase.SaveAssets();
- GC.Collect();
- EditorUtility.UnloadUnusedAssetsImmediate();
- AssetDatabase.Refresh();
- }
-
- ///
- /// Checking if the passed in value is a path to a Material.
- ///
- /// Material to check.
- /// HashSet of strings to ignore.
- /// Returns true if the passed in material's shader is not in the passed in ignore list.
- static bool ShouldUpgradeShader(Material material, HashSet shaderNamesToIgnore)
- {
- if (material == null)
- return false;
-
- if (material.shader == null)
- return false;
-
- return !shaderNamesToIgnore.Contains(material.shader.name);
- }
-
- ///
- /// Check if the materials in the list are variants of upgradable materials, and logs a infomative message to the user..
- ///
- /// Array of materials GUIDs.
- /// List or available upgraders.
- static void LogMaterialVariantMessage(string[] materialGUIDs, List upgraders)
- {
- List materials = new List();
- foreach (var guid in materialGUIDs)
- materials.Add(AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid)));
-
- LogMaterialVariantMessage(materials, upgraders);
- }
-
- ///
- /// Check if the materials in the list are variants of upgradable materials, and logs a infomative message to the user..
- ///
- /// Array of objects.
- /// List or available upgraders.
- static void LogMaterialVariantMessage(UnityEngine.Object[] objects, List upgraders)
- {
- Material mat;
- List materials = new List();
- for (int i = 0; i
- /// Check if the materials in the list are variants of upgradable materials, and logs a infomative message to the user..
- ///
- /// List of materials.
- /// List or available upgraders.
- static void LogMaterialVariantMessage(List materials, List upgraders)
- {
- StringBuilder sb = new StringBuilder();
- sb.AppendLine("Can not upgrade Material Variants, the following assets were skipped:");
- bool needsLogging = false;
-
- Material rootMaterial;
-
- foreach (Material material in materials)
- {
- if (material.isVariant)
- {
- rootMaterial = material;
- while (rootMaterial.isVariant)
- rootMaterial = rootMaterial.parent;
-
- if (GetUpgrader(upgraders, rootMaterial) != null)
- {
- needsLogging = true;
- sb.AppendLine($"- {material.name}, variant of {material.parent.name} with shader {rootMaterial.shader.name}.");
- }
- }
- }
-
- if (needsLogging)
- Debug.Log(sb.ToString(), null);
- }
-
-
- private static bool IsNotAutomaticallyUpgradable(List upgraders, Material material)
- {
- return GetUpgrader(upgraders, material) == null && !material.shader.name.ContainsAny(s_PathsWhiteList);
- }
-
-
- ///
- /// Checking if project folder contains any materials that are not using built-in shaders.
- ///
- /// List if MaterialUpgraders
- /// Returns true if at least one material uses a non-built-in shader (ignores Hidden, HDRP and Shader Graph Shaders)
- public static bool ProjectFolderContainsNonBuiltinMaterials(List upgraders)
- {
- foreach (var material in AssetDatabaseHelper.FindAssets(".mat"))
- {
- if(IsNotAutomaticallyUpgradable(upgraders, material))
- return true;
- }
-
- return false;
- }
-
- ///
- /// Upgrade the project folder.
- ///
- /// List of upgraders.
- /// Name of the progress bar.
- /// Material Upgrader flags.
- public static void UpgradeProjectFolder(List upgraders, string progressBarName, UpgradeFlags flags = UpgradeFlags.None)
- {
- HashSet shaderNamesToIgnore = new HashSet();
- UpgradeProjectFolder(upgraders, shaderNamesToIgnore, progressBarName, flags);
- }
-
- ///
- /// Upgrade the project folder.
- ///
- /// List of upgraders.
- /// Set of shader names to ignore.
- /// Name of the progress bar.
- /// Material Upgrader flags.
- public static void UpgradeProjectFolder(List upgraders, HashSet shaderNamesToIgnore, string progressBarName, UpgradeFlags flags = UpgradeFlags.None)
- {
- if ((!Application.isBatchMode) && (!EditorUtility.DisplayDialog(DialogText.title, "The upgrade will overwrite materials in your project. " + DialogText.projectBackMessage, DialogText.proceed, DialogText.cancel)))
- return;
-
- var materialAssets = AssetDatabase.FindAssets($"t:{nameof(Material)} glob:\"**/*.mat\"");
- int materialIndex = 0;
-
- LogMaterialVariantMessage(materialAssets, upgraders);
-
- foreach (var guid in materialAssets)
- {
- Material material = AssetDatabase.LoadAssetAtPath(AssetDatabase.GUIDToAssetPath(guid));
- materialIndex++;
- if (UnityEditor.EditorUtility.DisplayCancelableProgressBar(progressBarName, string.Format("({0} of {1}) {2}", materialIndex, materialAssets.Length, material), (float)materialIndex / (float)materialAssets.Length))
- break;
-
- if (!ShouldUpgradeShader(material, shaderNamesToIgnore))
- continue;
-
- if (material.isVariant)
- continue;
-
- Upgrade(material, upgraders, flags);
-
- }
-
- // Upgrade terrain specifically since it is a builtin material
- if (Terrain.activeTerrains.Length > 0)
- {
- Material terrainMat = Terrain.activeTerrain.materialTemplate;
- Upgrade(terrainMat, upgraders, flags);
- }
-
- UnityEditor.EditorUtility.ClearProgressBar();
- }
-
- ///
- /// Upgrade a material.
- ///
- /// Material to upgrade.
- /// Material upgrader.
- /// Material Upgrader flags.
- public static void Upgrade(Material material, MaterialUpgrader upgrader, UpgradeFlags flags)
- {
- using (ListPool.Get(out List upgraders))
- {
- upgraders.Add(upgrader);
- Upgrade(material, upgraders, flags);
- }
- }
-
- ///
- /// Upgrade a material.
- ///
- /// Material to upgrade.
- /// List of Material upgraders.
- /// Material Upgrader flags.
- public static void Upgrade(Material material, List upgraders, UpgradeFlags flags)
- {
- string message = string.Empty;
- if (Upgrade(material, upgraders, flags, ref message))
- return;
-
- if (!string.IsNullOrEmpty(message))
- {
- Debug.Log(message);
- }
- }
-
- ///
- /// Upgrade a material.
- ///
- /// Material to upgrade.
- /// List of Material upgraders.
- /// Material upgrader flags.
- /// Error message to be outputted when no material upgraders are suitable for given material if the flags is used.
- /// Returns true if the upgrader was found for the passed in material.
- public static bool Upgrade(Material material, List upgraders, UpgradeFlags flags, ref string message)
- {
- if (material == null)
- return false;
-
- var upgrader = GetUpgrader(upgraders, material);
-
- if (upgrader != null)
- {
- upgrader.Upgrade(material, flags);
- return true;
- }
- if ((flags & UpgradeFlags.LogMessageWhenNoUpgraderFound) == UpgradeFlags.LogMessageWhenNoUpgraderFound)
- {
- message =
- $"{material.name} material was not upgraded. There's no upgrader to convert {material.shader.name} shader to selected pipeline";
- return false;
- }
-
- return true;
- }
-
- ///
- /// Upgrade the selection.
- ///
- /// List of upgraders.
- /// Name of the progress bar.
- /// Material Upgrader flags.
- public static void UpgradeSelection(List upgraders, string progressBarName, UpgradeFlags flags = UpgradeFlags.None)
- {
- HashSet shaderNamesToIgnore = new HashSet();
- UpgradeSelection(upgraders, shaderNamesToIgnore, progressBarName, flags);
- }
-
- ///
- /// Upgrade the selection.
- ///
- /// List of upgraders.
- /// Set of shader names to ignore.
- /// Name of the progress bar.
- /// Material Upgrader flags.
- public static void UpgradeSelection(List upgraders, HashSet shaderNamesToIgnore, string progressBarName, UpgradeFlags flags = UpgradeFlags.None)
- {
- var selection = Selection.objects;
-
- if (selection == null)
- {
- EditorUtility.DisplayDialog(DialogText.title, DialogText.noSelectionMessage, DialogText.ok);
- return;
- }
-
- List selectedMaterials = new List(selection.Length);
-
- LogMaterialVariantMessage(selection, upgraders);
-
- for (int i = 0; i < selection.Length; ++i)
- {
- Material mat = selection[i] as Material;
- if (mat != null && !mat.isVariant)
- selectedMaterials.Add(mat);
- }
-
- int selectedMaterialsCount = selectedMaterials.Count;
- if (selectedMaterialsCount == 0)
- {
- EditorUtility.DisplayDialog(DialogText.title, DialogText.noSelectionMessage, DialogText.ok);
- return;
- }
-
- if (!EditorUtility.DisplayDialog(DialogText.title, string.Format("The upgrade will overwrite {0} selected material{1}. ", selectedMaterialsCount, selectedMaterialsCount > 1 ? "s" : "") +
- DialogText.projectBackMessage, DialogText.proceed, DialogText.cancel))
- return;
-
- string lastMaterialName = "";
- for (int i = 0; i < selectedMaterialsCount; i++)
- {
- if (UnityEditor.EditorUtility.DisplayCancelableProgressBar(progressBarName, string.Format("({0} of {1}) {2}", i, selectedMaterialsCount, lastMaterialName), (float)i / (float)selectedMaterialsCount))
- break;
-
- var material = selectedMaterials[i];
-
- if (!ShouldUpgradeShader(material, shaderNamesToIgnore))
- continue;
-
- Upgrade(material, upgraders, flags);
- if (material != null)
- lastMaterialName = material.name;
- }
-
- AssetDatabase.SaveAssets();
-
- UnityEditor.EditorUtility.ClearProgressBar();
- }
- }
-}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/PostProcessing/LensFlareDataSRPEditor.cs b/Packages/com.unity.render-pipelines.core/Editor/PostProcessing/LensFlareDataSRPEditor.cs
index a9daa6859cd..cb15cf824b3 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/PostProcessing/LensFlareDataSRPEditor.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/PostProcessing/LensFlareDataSRPEditor.cs
@@ -443,10 +443,8 @@ void ComputeThumbnail(ref Texture2D computedTexture, SerializedProperty element,
CommandBuffer cmd = CommandBufferPool.Get();
cmd.DisableShaderKeyword("FLARE_HAS_OCCLUSION");
- Vector4 flareData1 = new Vector4(0.0f, 0.0f, 0.0f, ((float)Styles.thumbnailSizeHeight) / ((float)Styles.thumbnailSizeWidth));
Vector2 screenSize = new Vector2(Styles.thumbnailSizeWidth, Styles.thumbnailSizeHeight);
- float screenRatio = screenSize.y / screenSize.x;
- Vector2 vScreenRatio = new Vector2(screenRatio, 1.0f);
+ float aspect = screenSize.y / screenSize.x;
Shader local = Shader.Find("Hidden/Core/LensFlareDataDrivenPreview2");
Material localMat = new Material(local);
@@ -474,6 +472,8 @@ void ComputeThumbnail(ref Texture2D computedTexture, SerializedProperty element,
scale = 10.0f / uniformScaleProp.floatValue / Mathf.Max(sizeXYProp.vector2Value.x, sizeXYProp.vector2Value.y);
}
cmd.SetGlobalVector(k_FlarePreviewData, new Vector4(Styles.thumbnailSizeWidth, Styles.thumbnailSizeHeight, 1f, 0f));
+ cmd.SetGlobalVector(LensFlareCommonSRP._FlareData1, new Vector4(0.0f, 0.0f, 0.0f, ((float)Styles.thumbnailSizeHeight) / ((float)Styles.thumbnailSizeWidth)));
+ Vector3 unused = new();
LensFlareCommonSRP.ProcessLensFlareSRPElementsSingle(
elementLocal,
cmd,
@@ -482,8 +482,8 @@ void ComputeThumbnail(ref Texture2D computedTexture, SerializedProperty element,
1.0f, scale,
localMat, center,
false,
- vScreenRatio,
- flareData1, false, 0);
+ new Vector2(aspect, 1),
+ unused, false, 0);
Graphics.ExecuteCommandBuffer(cmd);
cmd.CopyTexture(m_PreviewTexture.rt, computedTexture);
diff --git a/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphTestsCore.cs b/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphTestsCore.cs
new file mode 100644
index 00000000000..3a6bcde82f7
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphTestsCore.cs
@@ -0,0 +1,183 @@
+using NUnit.Framework;
+using System;
+using System.Collections.Generic;
+using UnityEngine.Rendering.RenderGraphModule;
+
+#if UNITY_EDITOR
+using UnityEditor.Rendering;
+#endif
+
+namespace UnityEngine.Rendering.Tests
+{
+ // TODO: Move this class to the Tests/Editor folder once the "IsolatedPackagesVerified" CI test correctly resolves all dependencies.
+ // Currently, the URP package fails to locate the RenderGraphTestsCore class when it's placed under Tests/Editor,
+ // unless the Core package is explicitly added to the "testables" list in the project manifest — which is not a sustainable solution.
+ internal class RenderGraphTestsCore
+ {
+ // For RG Record/Hash/Compile testing, use m_RenderGraph
+ protected RenderGraph m_RenderGraph;
+
+ protected RenderPipelineAsset m_OldDefaultRenderPipeline;
+ protected RenderPipelineAsset m_OldQualityRenderPipeline;
+
+ // For RG Execute/Submit testing with rendering, use m_RenderGraphTestPipeline and m_RenderGraph in its recordRenderGraphBody
+ protected RenderGraphTestPipelineAsset m_RenderGraphTestPipeline;
+ protected RenderGraphTestGlobalSettings m_RenderGraphTestGlobalSettings;
+
+ protected GameObject m_GameObject;
+
+ // We need a camera to execute the render graph and a game object to attach a camera
+ protected Camera m_Camera;
+
+ // For the testing of the following RG steps: Execute and Submit (native) with camera rendering, use this custom RenderGraph render pipeline
+ // through a camera render call to test the RG with a real ScriptableRenderContext
+ internal class RenderGraphTestPipelineAsset : RenderPipelineAsset
+ {
+ public Action recordRenderGraphBody;
+
+ public RenderGraph renderGraph;
+
+ protected override RenderPipeline CreatePipeline()
+ {
+ return new RenderGraphTestPipelineInstance(this);
+ }
+
+ // Called only once per UTR
+ void OnEnable()
+ {
+ renderGraph = new();
+ }
+ }
+
+ internal class RenderGraphTestPipelineInstance : RenderPipeline
+ {
+ RenderGraphTestPipelineAsset asset;
+
+ // Having the RG at this level allows us to handle RG framework within Render() for easier testing
+ RenderGraph m_RenderGraph;
+
+ public RenderGraphTestPipelineInstance(RenderGraphTestPipelineAsset asset)
+ {
+ this.asset = asset;
+ this.m_RenderGraph = asset.renderGraph;
+ }
+
+ protected override void Render(ScriptableRenderContext renderContext, List cameras)
+ {
+ foreach (var camera in cameras)
+ {
+ if (!camera.enabled)
+ continue;
+
+ var cmd = CommandBufferPool.Get();
+
+ RenderGraphParameters rgParams = new()
+ {
+ commandBuffer = cmd,
+ scriptableRenderContext = renderContext,
+ currentFrameIndex = Time.frameCount,
+ invalidContextForTesting = false
+ };
+
+ try
+ {
+ // Necessary to reinitialize the state, since we have many tests which do not use this system but directly adding
+ // passes to the graph (to test the compilation) and destroying them without executing them with camera.Render()
+ // (e.g GraphicsPassWriteWaitOnAsyncPipe). So the state becomes RecordGraph because of the Builder.Destroy logic.
+ m_RenderGraph.RenderGraphState = RenderGraphState.Idle;
+
+ m_RenderGraph.BeginRecording(rgParams);
+
+ asset.recordRenderGraphBody?.Invoke(renderContext, camera, cmd);
+
+ m_RenderGraph.EndRecordingAndExecute();
+ }
+ catch (Exception e)
+ {
+ if (m_RenderGraph.ResetGraphAndLogException(e))
+ throw;
+ return;
+ }
+
+ renderContext.ExecuteCommandBuffer(cmd);
+
+ CommandBufferPool.Release(cmd);
+ }
+ renderContext.Submit();
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(RenderGraphTestPipelineAsset))]
+ [System.ComponentModel.DisplayName("RenderGraphTest")]
+ internal class RenderGraphTestGlobalSettings : RenderPipelineGlobalSettings
+ {
+ [SerializeField] RenderPipelineGraphicsSettingsContainer m_Settings = new();
+
+ protected override List settingsList => m_Settings.settingsList;
+ }
+
+ [OneTimeSetUp]
+ public void Setup()
+ {
+ // Setting default global settings to the custom RG render pipeline type, no quality settings so we can rely on the default RP
+ m_RenderGraphTestGlobalSettings = ScriptableObject.CreateInstance();
+#if UNITY_EDITOR
+ EditorGraphicsSettings.SetRenderPipelineGlobalSettingsAsset(m_RenderGraphTestGlobalSettings);
+#endif
+ // Saving old render pipelines to set them back after testing
+ m_OldDefaultRenderPipeline = GraphicsSettings.defaultRenderPipeline;
+ m_OldQualityRenderPipeline = QualitySettings.renderPipeline;
+
+ // Setting the custom RG render pipeline
+ m_RenderGraphTestPipeline = ScriptableObject.CreateInstance();
+ GraphicsSettings.defaultRenderPipeline = m_RenderGraphTestPipeline;
+ QualitySettings.renderPipeline = m_RenderGraphTestPipeline;
+
+ // Getting the RG from the custom asset pipeline
+ m_RenderGraph = m_RenderGraphTestPipeline.renderGraph;
+ m_RenderGraph.nativeRenderPassesEnabled = true;
+
+ // Necessary to disable it for the Unit Tests, as the caller is not the same.
+ RenderGraph.RenderGraphExceptionMessages.enableCaller = false;
+
+ // We need a real ScriptableRenderContext and a camera to execute the Render Graph
+ m_GameObject = new GameObject("testGameObject")
+ {
+ hideFlags = HideFlags.HideAndDontSave
+ };
+ m_GameObject.tag = "MainCamera";
+ m_Camera = m_GameObject.AddComponent();
+ }
+
+ [OneTimeTearDown]
+ public void Cleanup()
+ {
+ GraphicsSettings.defaultRenderPipeline = m_OldDefaultRenderPipeline;
+ m_OldDefaultRenderPipeline = null;
+
+ QualitySettings.renderPipeline = m_OldQualityRenderPipeline;
+ m_OldQualityRenderPipeline = null;
+
+ m_RenderGraph.Cleanup();
+
+ Object.DestroyImmediate(m_RenderGraphTestPipeline);
+
+#if UNITY_EDITOR
+ EditorGraphicsSettings.SetRenderPipelineGlobalSettingsAsset(null);
+#endif
+ Object.DestroyImmediate(m_RenderGraphTestGlobalSettings);
+
+ GameObject.DestroyImmediate(m_GameObject);
+ m_GameObject = null;
+ m_Camera = null;
+ }
+
+ [TearDown]
+ public void CleanupRenderGraph()
+ {
+ // Cleaning all Render Graph resources and data structures
+ // Nothing remains, Render Graph in next test will start from scratch
+ m_RenderGraph.ForceCleanup();
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphTestsCore.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphTestsCore.cs.meta
new file mode 100644
index 00000000000..b294c8f7a20
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/RenderGraph/RenderGraphTestsCore.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: adee57cb848200543880b66dfd96f208
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Editor/SampleDependencyImportSystem/SampleDependencyImporter.cs b/Packages/com.unity.render-pipelines.core/Editor/SampleDependencyImportSystem/SampleDependencyImporter.cs
index 64f375968ff..734e122df1e 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/SampleDependencyImportSystem/SampleDependencyImporter.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/SampleDependencyImportSystem/SampleDependencyImporter.cs
@@ -8,7 +8,7 @@
using PackageInfo = UnityEditor.PackageManager.PackageInfo;
///
-/// To implement this, the package needs to starts with k_srpPrefixPackage
+/// To implement this, the package needs to be in the allowedPackageList
/// Then, in the package.json, an array can be added after the path variable of the sample. The path should start from the Packages/ folder, as such:
/// "samples": [
/// {
@@ -128,13 +128,11 @@ static bool TryLoadSampleConfiguration(PackageInfo packageInfo, out SampleList c
///
void LoadAssetDependencies(string assetPath)
{
-
- ImportTextMeshProEssentialResources();
-
if (m_SampleList != null)
{
var assetsImported = false;
-
+ bool atLeastOneIsSampleDirectory = false;
+
for (int i = 0; i < m_Samples.Count; ++i)
{
string pathPrefix = $"Assets/Samples/{m_PackageInfo.displayName}/{m_PackageInfo.version}/";
@@ -143,18 +141,23 @@ void LoadAssetDependencies(string assetPath)
var isSampleDirectory = assetPath.EndsWith(m_Samples[i].displayName) && assetPath.StartsWith(pathPrefix);
if (isSampleDirectory)
{
+ atLeastOneIsSampleDirectory = true;
+
// Retrieving the dependencies of the sample that is currently being imported.
SampleInformation currentSampleInformation = GetSampleInformation(m_Samples[i].displayName);
if (currentSampleInformation != null)
{
// Import the common asset dependencies
- assetsImported = ImportDependencies(m_PackageInfo, currentSampleInformation.dependencies);
+ assetsImported = ImportDependencies(m_PackageInfo, currentSampleInformation.dependencies);
}
}
}
-
-
+
+ // Only import TMPro resources if a sample is currently imported.
+ // This is done outside the loop to save cost.
+ if (atLeastOneIsSampleDirectory)
+ ImportTextMeshProEssentialResources();
if (assetsImported)
AssetDatabase.Refresh();
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools.meta b/Packages/com.unity.render-pipelines.core/Editor/Tools.meta
new file mode 100644
index 00000000000..ea8868521df
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 983c27c4e607ff143aea413ddb18548f
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Upgraders/.buginfo b/Packages/com.unity.render-pipelines.core/Editor/Tools/.buginfo
similarity index 100%
rename from Packages/com.unity.render-pipelines.high-definition/Editor/Upgraders/.buginfo
rename to Packages/com.unity.render-pipelines.core/Editor/Tools/.buginfo
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools/Deprecated.cs b/Packages/com.unity.render-pipelines.core/Editor/Tools/Deprecated.cs
new file mode 100644
index 00000000000..c535e8009d9
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/Deprecated.cs
@@ -0,0 +1,56 @@
+using System.Collections.Generic;
+using System;
+using UnityEngine;
+
+namespace UnityEditor.Rendering
+{
+ public partial class MaterialUpgrader
+ {
+ ///
+ /// Material Upgrader dialog text.
+ ///
+ [Obsolete("DialogText has been deprecated. #from(6000.3)")]
+ public static class DialogText
+ {
+ /// Material Upgrader title.
+ public static readonly string title = "Material Upgrader";
+ /// Material Upgrader proceed.
+ public static readonly string proceed = "Proceed";
+ /// Material Upgrader Ok.
+ public static readonly string ok = "OK";
+ /// Material Upgrader cancel.
+ public static readonly string cancel = "Cancel";
+ /// Material Upgrader no selection message.
+ public static readonly string noSelectionMessage = "You must select at least one material.";
+ /// Material Upgrader project backup message.
+ public static readonly string projectBackMessage = "Make sure to have a project backup before proceeding.";
+ }
+
+ ///
+ /// Checking if project folder contains any materials that are not using built-in shaders.
+ ///
+ /// List if MaterialUpgraders
+ /// Returns true if at least one material uses a non-built-in shader (ignores Hidden, HDRP and Shader Graph Shaders)
+ [Obsolete("Please directly use ProjectContainsNonAutomaticUpgradePath now. #from(6000.3)")]
+ public static bool ProjectFolderContainsNonBuiltinMaterials(List upgraders)
+ {
+ string[] pathsWhiteList = new[]
+ {
+ "Hidden/",
+ "HDRP/",
+ "Shader Graphs/"
+ };
+
+ foreach (var material in AssetDatabaseHelper.FindAssets(".mat"))
+ {
+ if (material.shader.name.ContainsAny(pathsWhiteList))
+ continue;
+
+ if (!IsMaterialUpgradable(upgraders, material))
+ return true;
+ }
+
+ return false;
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools/Deprecated.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/Tools/Deprecated.cs.meta
new file mode 100644
index 00000000000..c6e9e3cf7e6
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/Deprecated.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: f561b489519a3334bbc61fdb29229240
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader.meta b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader.meta
new file mode 100644
index 00000000000..84e1aa67255
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 50a860756cfb850468867cc0b3e55a5a
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/IMaterialUpgradersProvider.cs b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/IMaterialUpgradersProvider.cs
new file mode 100644
index 00000000000..bb3e4fb132a
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/IMaterialUpgradersProvider.cs
@@ -0,0 +1,16 @@
+using System.Collections.Generic;
+
+namespace UnityEditor.Rendering
+{
+ ///
+ /// Provider for a set of Materials Upgraders
+ ///
+ public interface IMaterialUpgradersProvider
+ {
+ ///
+ /// Returns a list of custom MaterialUpgrader instances.
+ ///
+ /// A list of upgraders
+ IEnumerable GetUpgraders();
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/IMaterialUpgradersProvider.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/IMaterialUpgradersProvider.cs.meta
new file mode 100644
index 00000000000..ddbada6e753
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/IMaterialUpgradersProvider.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 245f99d8bedd61c4780fbe93fdee0cb8
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.Utils.cs b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.Utils.cs
new file mode 100644
index 00000000000..2673c9d8651
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.Utils.cs
@@ -0,0 +1,563 @@
+using System;
+using System.Collections.Generic;
+using System.Text;
+using JetBrains.Annotations;
+using UnityEngine;
+using UnityEngine.Rendering;
+
+namespace UnityEditor.Rendering
+{
+ ///
+ /// Material Upgrader class.
+ ///
+ public partial class MaterialUpgrader
+ {
+ #region Internal API
+ ///
+ /// Represents an entry describing material properties
+ ///
+ internal class MaterialInfo
+ {
+ ///
+ /// The material name
+ ///
+ public string Name { get; set; }
+
+ ///
+ /// The material being evaluated.
+ ///
+ [CanBeNull]
+ public Material Material { get; set; }
+
+ ///
+ /// The current shader of the material.
+ ///
+ public string ShaderName { get; set; }
+
+ ///
+ /// If the material is a variant
+ ///
+ public bool IsVariant { get; set; }
+
+ ///
+ /// The base material name
+ ///
+ public string BaseMaterialName { get; set; }
+
+ ///
+ /// The base material is is true
+ ///
+ [CanBeNull]
+ public Material BaseMaterial { get; set; }
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ /// The object to compare with the current object.
+ /// true if the specified object is equal to the current object; otherwise, false.
+ public override bool Equals(object obj)
+ {
+ if (obj is not MaterialInfo other)
+ return false;
+
+ return string.Equals(ShaderName, other.ShaderName, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Serves as the default hash function.
+ ///
+ /// A hash code for the current object.
+ public override int GetHashCode()
+ {
+ return ShaderName?.GetHashCode() ?? 0;
+ }
+ }
+
+ ///
+ /// Represents an entry describing whether a material is available for upgrade,
+ /// along with the reason if it's not.
+ ///
+ internal class MaterialUpgradeEntry
+ {
+ ///
+ /// The material being evaluated.
+ ///
+ public MaterialInfo MaterialInfo { get; set; }
+
+ ///
+ /// Indicates whether the material is available for upgrade.
+ ///
+ public bool AvailableForUpgrade { get; set; }
+
+ ///
+ /// If the material is not available for upgrade, this provides the reason why.
+ /// Empty if is true.
+ ///
+ public string NotAvailableForUpgradeReason { get; set; }
+
+ ///
+ /// Determines whether the specified object is equal to the current .
+ ///
+ /// The object to compare with the current object.
+ /// true if the specified object is equal to the current object; otherwise, false.
+ public override bool Equals(object obj)
+ {
+ if (obj is not MaterialUpgradeEntry other)
+ return false;
+
+ return Equals(MaterialInfo, other.MaterialInfo) &&
+ AvailableForUpgrade == other.AvailableForUpgrade &&
+ string.Equals(NotAvailableForUpgradeReason, other.NotAvailableForUpgradeReason, StringComparison.OrdinalIgnoreCase);
+ }
+
+ ///
+ /// Serves as the default hash function.
+ ///
+ /// A hash code for the current object.
+ public override int GetHashCode()
+ {
+ return HashCode.Combine(MaterialInfo, AvailableForUpgrade, NotAvailableForUpgradeReason);
+ }
+ }
+
+ static MaterialUpgrader GetUpgrader(List upgraders, Material material)
+ {
+ if (material == null || material.shader == null)
+ return null;
+
+ string shaderName = material.shader.name;
+ for (int i = 0; i != upgraders.Count; i++)
+ {
+ if (upgraders[i].OldShaderPath == shaderName)
+ return upgraders[i];
+ }
+
+ return null;
+ }
+
+ //@TODO: Only do this when it exceeds memory consumption...
+ static void SaveAssetsAndFreeMemory()
+ {
+ AssetDatabase.SaveAssets();
+ GC.Collect();
+ EditorUtility.UnloadUnusedAssetsImmediate();
+ AssetDatabase.Refresh();
+ }
+
+ ///
+ /// Returns if the material has a mapping upgrader
+ ///
+ /// The available upgrader list
+ /// The material to check
+ ///
+ static bool IsMaterialUpgradable(List upgraders, Material material)
+ {
+ if (material == null || upgraders == null)
+ throw new ArgumentException("Invalid input: upgraders or material is null.");
+
+ return GetUpgrader(upgraders, material) != null;
+ }
+ /// Extracts shader paths from a list of upgraders into two sets:
+ /// one for shaders to upgrade (old) and one for shaders already upgraded (new).
+ internal static void GetUpgraderShaderPaths(List upgraders, out HashSet oldShaders, out HashSet newShaders)
+ {
+ oldShaders = new HashSet();
+ newShaders = new HashSet();
+
+ if (upgraders == null)
+ return;
+
+ foreach (var upgrader in upgraders)
+ {
+ if (!string.IsNullOrEmpty(upgrader.OldShaderPath))
+ oldShaders.Add(upgrader.OldShaderPath);
+
+ if (!string.IsNullOrEmpty(upgrader.NewShaderPath))
+ newShaders.Add(upgrader.NewShaderPath);
+ }
+ }
+
+ internal static MaterialInfo ToMaterialInfo(Material material)
+ {
+ Material baseMaterial = material;
+
+ if (material.isVariant)
+ {
+ // Traverse up to the root material
+ while (baseMaterial.isVariant && baseMaterial.parent != null)
+ {
+ baseMaterial = baseMaterial.parent;
+ }
+ }
+
+ return new MaterialInfo
+ {
+ Name = material.name,
+ Material = material,
+ ShaderName = material.shader.name,
+ IsVariant = material.isVariant,
+ BaseMaterialName = baseMaterial.name,
+ BaseMaterial = baseMaterial
+ };
+ }
+
+ internal static List GatherInfo(IEnumerable materials)
+ {
+ var materialsInfo = new List();
+ foreach (var material in materials)
+ {
+ if (material == null || material.shader == null)
+ continue;
+
+ materialsInfo.Add(ToMaterialInfo(material));
+ }
+
+ return materialsInfo;
+ }
+
+ internal static IEnumerable FetchUpgradeOptions(HashSet upgradersAvailable, HashSet shaderNamesToIgnore, List materialInfo)
+ {
+ foreach (var material in materialInfo)
+ {
+ var shaderName = material.ShaderName;
+ bool isShaderIgnored = shaderNamesToIgnore.Contains(shaderName);
+ if (isShaderIgnored)
+ continue;
+
+ bool isUpgradable = !material.IsVariant && upgradersAvailable.Contains(shaderName);
+ string reason = isUpgradable ? string.Empty : GenerateReason(material);
+
+ yield return new MaterialUpgradeEntry
+ {
+ MaterialInfo = material,
+ AvailableForUpgrade = isUpgradable,
+ NotAvailableForUpgradeReason = reason
+ };
+ }
+ }
+
+ internal static List FetchAllMaterialsInProject()
+ {
+ List materials = new(AssetDatabaseHelper.FindAssets(".mat"));
+ // Add the build in material of terrain ( must be always available )
+ if (Terrain.activeTerrains.Length > 0)
+ {
+ materials.Add(Terrain.activeTerrain.materialTemplate);
+ }
+
+ return materials;
+ }
+
+ ///
+ /// Given a set of material assets in the project and determines whether they are eligible for upgrade.
+ ///
+ /// A list of instances to use for determining upgradability.
+ /// A list of materials to check for upgrade options, if null Unity asumes that you want all project materials.
+ ///
+ /// An enumerable of representing each material and whether it can be upgraded.
+ ///
+ /// Thrown if is null.
+ internal static IEnumerable FetchUpgradeOptions(List upgraders, List materials = null)
+ {
+ if (upgraders == null)
+ throw new ArgumentNullException(nameof(upgraders));
+
+ // If no materials are provided, gather all materials in the project.
+ if (materials == null)
+ {
+ materials = FetchAllMaterialsInProject();
+ }
+
+ var materialInfo = GatherInfo(materials);
+ GetUpgraderShaderPaths(upgraders, out var upgradersAvailable, out var shaderNamesToIgnore);
+
+ return FetchUpgradeOptions(upgradersAvailable, shaderNamesToIgnore, materialInfo);
+ }
+
+ internal static string GenerateReason(MaterialInfo material)
+ {
+ string reason = $"No upgrader available to convert material '{material.Name}'";
+ if (material.IsVariant)
+ {
+ reason += $", a variant of '{material.BaseMaterialName}',";
+ }
+ reason += $" using shader '{material.BaseMaterialName}'.";
+ return reason;
+ }
+
+ static StringBuilder s_UpgradeLog = new StringBuilder();
+
+ internal static string PerformUpgradeInternal(
+ List materialUpgrades,
+ List upgraders,
+ HashSet shaderNamesToIgnore,
+ string progressBarName,
+ bool showProgressBar = true,
+ UpgradeFlags flags = UpgradeFlags.None)
+ {
+ s_UpgradeLog.Clear();
+
+ if (materialUpgrades.Count > 0)
+ {
+ s_UpgradeLog.AppendLine($"{progressBarName}");
+
+ for (int materialIndex = 0; materialIndex < materialUpgrades.Count; ++materialIndex)
+ {
+ var entry = materialUpgrades[materialIndex];
+
+ if (showProgressBar)
+ {
+ if (EditorUtility.DisplayCancelableProgressBar(progressBarName, $"({materialIndex} of {materialUpgrades.Count}) {entry.MaterialInfo.Name}", (float)materialIndex / (float)materialUpgrades.Count))
+ {
+ s_UpgradeLog.AppendLine("Process cancelled by user.");
+ break;
+ }
+ }
+
+ if (!entry.AvailableForUpgrade || shaderNamesToIgnore.Contains(entry.MaterialInfo.ShaderName))
+ {
+ s_UpgradeLog.AppendLine($"Skipping material: {entry.MaterialInfo.Name} - {entry.NotAvailableForUpgradeReason}");
+ }
+ else
+ {
+ s_UpgradeLog.AppendLine($"Upgrading material: {entry.MaterialInfo.Name} using shader: {entry.MaterialInfo.ShaderName}");
+ Upgrade(entry.MaterialInfo.Material, upgraders, flags);
+ }
+ }
+
+ AssetDatabase.SaveAssets();
+
+ if (showProgressBar)
+ EditorUtility.ClearProgressBar();
+ }
+
+ return s_UpgradeLog.ToString();
+ }
+
+ static void PerformUpgrade(List materialUpgrades, List upgraders, HashSet shaderNamesToIgnore, string progressBarName, UpgradeFlags flags = UpgradeFlags.None)
+ {
+ if (materialUpgrades == null || materialUpgrades.Count == 0)
+ {
+ Debug.LogWarning("No materials found for upgrade.");
+ return;
+ }
+
+ bool CanPerformUpgrade()
+ {
+ const string title = "Material Upgrader";
+ const string message = "This operation will overwrite existing materials in your project.\n\nPlease ensure you have a backup before proceeding.";
+ const string proceed = "Proceed";
+ const string cancel = "Cancel";
+
+ if (Application.isBatchMode)
+ return true;
+
+ return EditorUtility.DisplayDialog(title, message, proceed, cancel);
+ }
+
+ if (CanPerformUpgrade())
+ {
+ string upgradeLog = PerformUpgradeInternal(materialUpgrades, upgraders, shaderNamesToIgnore, progressBarName, true, flags);
+ Debug.Log(upgradeLog);
+ }
+ }
+
+ #endregion
+
+ #region Public API
+ ///
+ /// Checking if project folder contains any materials that can not be automatic upgraded.
+ ///
+ /// List if
+ /// Returns true if at least one material uses a non-built-in shader
+ public static bool ProjectContainsNonAutomaticUpgradePath(List upgraders)
+ {
+ foreach (var material in AssetDatabaseHelper.FindAssets(".mat"))
+ {
+ if (!IsMaterialUpgradable(upgraders, material))
+ return true;
+ }
+
+ return false;
+ }
+
+ ///
+ /// Upgrade the project folder.
+ ///
+ /// List of upgraders.
+ /// Name of the progress bar.
+ /// Material Upgrader flags.
+ public static void UpgradeProjectFolder(List upgraders, string progressBarName, UpgradeFlags flags = UpgradeFlags.None)
+ {
+ HashSet shaderNamesToIgnore = new HashSet();
+ UpgradeProjectFolder(upgraders, shaderNamesToIgnore, progressBarName, flags);
+ }
+
+ ///
+ /// Fetches all upgraders that support the given render pipeline asset type
+ ///
+ /// The RP asset type
+ /// A list with all the upgraders in for the given pipeline
+ public static List FetchAllUpgradersForPipeline(Type renderPipelineAssetType)
+ {
+ if (!typeof(RenderPipelineAsset).IsAssignableFrom(renderPipelineAssetType))
+ throw new ArgumentException($"Type '{renderPipelineAssetType.FullName}' must inherit from RenderPipelineAsset.", nameof(renderPipelineAssetType));
+
+ return MaterialUpgraderRegistry.instance.GetMaterialUpgradersForPipeline(renderPipelineAssetType);
+ }
+
+ ///
+ /// Fetches all materials in the project that are upgradable to the given render pipeline asset type
+ ///
+ /// The RP asset type
+ /// A list with all the materials in the project
+ public static List FetchAllUpgradableMaterialsForPipeline(Type renderPipelineAssetType)
+ {
+ var upgraders = FetchAllUpgradersForPipeline(renderPipelineAssetType);
+
+ if (upgraders == null || upgraders.Count == 0)
+ {
+ Debug.LogWarning($"No material upgraders found for pipeline: {renderPipelineAssetType.Name}");
+ return new List();
+ }
+
+ var allMaterials = FetchAllMaterialsInProject();
+
+ var materialsAvailableForUpgrade = new List();
+ foreach (var option in FetchUpgradeOptions(upgraders, allMaterials))
+ {
+ if (!option.AvailableForUpgrade)
+ continue;
+
+ materialsAvailableForUpgrade.Add(option.MaterialInfo.Material);
+ }
+
+ return materialsAvailableForUpgrade;
+ }
+
+ ///
+ /// Upgrade a material.
+ ///
+ /// Material to upgrade.
+ /// Material upgrader.
+ /// Material Upgrader flags.
+ public static void Upgrade(Material material, MaterialUpgrader upgrader, UpgradeFlags flags)
+ {
+ using (ListPool.Get(out List upgraders))
+ {
+ upgraders.Add(upgrader);
+ Upgrade(material, upgraders, flags);
+ }
+ }
+
+ ///
+ /// Upgrade a material.
+ ///
+ /// Material to upgrade.
+ /// List of Material upgraders.
+ /// Material Upgrader flags.
+ public static void Upgrade(Material material, List upgraders, UpgradeFlags flags)
+ {
+ if (material == null || upgraders == null || upgraders.Count == 0)
+ return;
+
+ string message = string.Empty;
+ if (Upgrade(material, upgraders, flags, ref message))
+ return;
+
+ if (!string.IsNullOrEmpty(message))
+ {
+ Debug.Log(message);
+ }
+ }
+
+ ///
+ /// Upgrade a material.
+ ///
+ /// Material to upgrade.
+ /// List of Material upgraders.
+ /// Material upgrader flags.
+ /// Error message to be outputted when no material upgraders are suitable for given material if the flags is used.
+ /// Returns true if the upgrader was found for the passed in material.
+ public static bool Upgrade(Material material, List upgraders, UpgradeFlags flags, ref string message)
+ {
+ if (material == null)
+ return false;
+
+ var upgrader = GetUpgrader(upgraders, material);
+
+ if (upgrader != null)
+ {
+ upgrader.Upgrade(material, flags);
+ return true;
+ }
+ if ((flags & UpgradeFlags.LogMessageWhenNoUpgraderFound) == UpgradeFlags.LogMessageWhenNoUpgraderFound)
+ {
+ message =
+ $"{material.name} material was not upgraded. There's no upgrader to convert {material.shader.name} shader to selected pipeline";
+ return false;
+ }
+
+ return true;
+ }
+
+ ///
+ /// Upgrade the project folder.
+ ///
+ /// List of upgraders.
+ /// Set of shader names to ignore.
+ /// Name of the progress bar.
+ /// Material Upgrader flags.
+ public static void UpgradeProjectFolder(List upgraders, HashSet shaderNamesToIgnore, string progressBarName, UpgradeFlags flags = UpgradeFlags.None)
+ {
+ using (ListPool.Get(out var tmp))
+ {
+ tmp.AddRange(FetchUpgradeOptions(upgraders));
+ PerformUpgrade(tmp, upgraders, shaderNamesToIgnore, progressBarName, flags);
+ }
+ }
+
+ ///
+ /// Upgrade the selection.
+ ///
+ /// List of upgraders.
+ /// Name of the progress bar.
+ /// Material Upgrader flags.
+ public static void UpgradeSelection(List upgraders, string progressBarName, UpgradeFlags flags = UpgradeFlags.None)
+ {
+ HashSet shaderNamesToIgnore = new HashSet();
+ UpgradeSelection(upgraders, shaderNamesToIgnore, progressBarName, flags);
+ }
+
+ ///
+ /// Upgrade the selection.
+ ///
+ /// List of upgraders.
+ /// Set of shader names to ignore.
+ /// Name of the progress bar.
+ /// Material Upgrader flags.
+ public static void UpgradeSelection(List upgraders, HashSet shaderNamesToIgnore, string progressBarName, UpgradeFlags flags = UpgradeFlags.None)
+ {
+ using (ListPool.Get(out var tmp))
+ {
+ using (ListPool.Get(out var selectedMaterials))
+ {
+ var selection = Selection.objects;
+ if (selection != null)
+ {
+ for (int i = 0; i < selection.Length; ++i)
+ {
+ if (selection[i] is Material m)
+ selectedMaterials.Add(m);
+ }
+ }
+
+ tmp.AddRange(FetchUpgradeOptions(upgraders, selectedMaterials));
+ }
+
+ PerformUpgrade(tmp, upgraders, shaderNamesToIgnore, progressBarName, flags);
+ }
+ }
+ #endregion
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.Utils.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.Utils.cs.meta
new file mode 100644
index 00000000000..7b198a986b7
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.Utils.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 91bd3583117bf334eb9150fbfd3b22b3
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.cs b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.cs
new file mode 100644
index 00000000000..f25401b58aa
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.cs
@@ -0,0 +1,321 @@
+using System;
+using System.Collections.Generic;
+using UnityEngine;
+
+namespace UnityEditor.Rendering
+{
+ public partial class MaterialUpgrader
+ {
+ ///
+ /// The priority of the upgrader.
+ ///
+ public virtual int priority => 0;
+
+ ///
+ /// Material Upgrader finalizer delegate.
+ ///
+ /// Material
+ public delegate void MaterialFinalizer(Material mat);
+
+ string m_OldShader;
+ string m_NewShader;
+
+ ///
+ /// Retrieves path to new shader.
+ ///
+ public string NewShaderPath => m_NewShader;
+
+ ///
+ /// Retrieves path to old shader.
+ ///
+ public string OldShaderPath => m_OldShader;
+
+ MaterialFinalizer m_Finalizer;
+
+ Dictionary m_TextureRename = new Dictionary();
+ Dictionary m_FloatRename = new Dictionary();
+ Dictionary m_ColorRename = new Dictionary();
+
+ Dictionary m_FloatPropertiesToSet = new Dictionary();
+ Dictionary m_ColorPropertiesToSet = new Dictionary();
+ List m_TexturesToRemove = new List();
+ Dictionary m_TexturesToSet = new Dictionary();
+
+ class KeywordFloatRename
+ {
+ public string keyword;
+ public string property;
+ public float setVal, unsetVal;
+ }
+ List m_KeywordFloatRename = new List();
+ Dictionary)> m_ConditionalFloatRename;
+
+ ///
+ /// Type of property to rename.
+ ///
+ public enum MaterialPropertyType
+ {
+ /// Texture reference property.
+ Texture,
+ /// Float property.
+ Float,
+ /// Color property.
+ Color
+ }
+
+ ///
+ /// Retrieves a collection of renamed parameters of a specific MaterialPropertyType.
+ ///
+ /// Material Property Type
+ /// Dictionary of property names to their renamed values.
+ /// type is not valid.
+ public IReadOnlyDictionary GetPropertyRenameMap(MaterialPropertyType type)
+ {
+ switch (type)
+ {
+ case MaterialPropertyType.Texture: return m_TextureRename;
+ case MaterialPropertyType.Float: return m_FloatRename;
+ case MaterialPropertyType.Color: return m_ColorRename;
+ default: throw new ArgumentException(nameof(type));
+ }
+ }
+
+ ///
+ /// Upgrade Flags
+ ///
+ [Flags]
+ public enum UpgradeFlags
+ {
+ /// None.
+ None = 0,
+ /// LogErrorOnNonExistingProperty.
+ LogErrorOnNonExistingProperty = 1,
+ /// CleanupNonUpgradedProperties.
+ CleanupNonUpgradedProperties = 2,
+ /// LogMessageWhenNoUpgraderFound.
+ LogMessageWhenNoUpgraderFound = 4
+ }
+
+ ///
+ /// Upgrade method.
+ ///
+ /// Material to upgrade.
+ /// Upgrade flag
+ public void Upgrade(Material material, UpgradeFlags flags)
+ {
+ Material newMaterial;
+ if ((flags & UpgradeFlags.CleanupNonUpgradedProperties) != 0)
+ {
+ newMaterial = new Material(Shader.Find(m_NewShader));
+ }
+ else
+ {
+ newMaterial = UnityEngine.Object.Instantiate(material) as Material;
+ newMaterial.shader = Shader.Find(m_NewShader);
+ }
+
+ Convert(material, newMaterial);
+
+ material.shader = Shader.Find(m_NewShader);
+ material.CopyPropertiesFromMaterial(newMaterial);
+ UnityEngine.Object.DestroyImmediate(newMaterial);
+
+ if (m_Finalizer != null)
+ m_Finalizer(material);
+ }
+
+ // Overridable function to implement custom material upgrading functionality
+ ///
+ /// Custom material conversion method.
+ ///
+ /// Source material.
+ /// Destination material.
+ public virtual void Convert(Material srcMaterial, Material dstMaterial)
+ {
+ foreach (var t in m_TextureRename)
+ {
+ if (!srcMaterial.HasProperty(t.Key) || !dstMaterial.HasProperty(t.Value))
+ continue;
+
+ dstMaterial.SetTextureScale(t.Value, srcMaterial.GetTextureScale(t.Key));
+ dstMaterial.SetTextureOffset(t.Value, srcMaterial.GetTextureOffset(t.Key));
+ dstMaterial.SetTexture(t.Value, srcMaterial.GetTexture(t.Key));
+ }
+
+ foreach (var t in m_FloatRename)
+ {
+ if (!srcMaterial.HasProperty(t.Key) || !dstMaterial.HasProperty(t.Value))
+ continue;
+
+ dstMaterial.SetFloat(t.Value, srcMaterial.GetFloat(t.Key));
+ }
+
+ foreach (var t in m_ColorRename)
+ {
+ if (!srcMaterial.HasProperty(t.Key) || !dstMaterial.HasProperty(t.Value))
+ continue;
+
+ dstMaterial.SetColor(t.Value, srcMaterial.GetColor(t.Key));
+ }
+
+ foreach (var prop in m_TexturesToRemove)
+ {
+ if (!dstMaterial.HasProperty(prop))
+ continue;
+
+ dstMaterial.SetTexture(prop, null);
+ }
+
+ foreach (var prop in m_TexturesToSet)
+ {
+ if (!dstMaterial.HasProperty(prop.Key))
+ continue;
+
+ dstMaterial.SetTexture(prop.Key, prop.Value);
+ }
+
+ foreach (var prop in m_FloatPropertiesToSet)
+ {
+ if (!dstMaterial.HasProperty(prop.Key))
+ continue;
+
+ dstMaterial.SetFloat(prop.Key, prop.Value);
+ }
+
+ foreach (var prop in m_ColorPropertiesToSet)
+ {
+ if (!dstMaterial.HasProperty(prop.Key))
+ continue;
+
+ dstMaterial.SetColor(prop.Key, prop.Value);
+ }
+
+ foreach (var t in m_KeywordFloatRename)
+ {
+ if (!dstMaterial.HasProperty(t.property))
+ continue;
+
+ dstMaterial.SetFloat(t.property, srcMaterial.IsKeywordEnabled(t.keyword) ? t.setVal : t.unsetVal);
+ }
+
+ // Handle conditional float renaming
+ if (m_ConditionalFloatRename != null)
+ {
+ foreach (var (oldName, (newName, condition)) in m_ConditionalFloatRename)
+ {
+ if (srcMaterial.HasProperty(oldName) &&
+ condition(srcMaterial.GetFloat(oldName)) &&
+ dstMaterial.HasProperty(newName))
+ {
+ dstMaterial.SetFloat(newName, 1.0f);
+ }
+ }
+ }
+ }
+
+ ///
+ /// Rename shader.
+ ///
+ /// Old name.
+ /// New name.
+ /// Finalizer delegate.
+ public void RenameShader(string oldName, string newName, MaterialFinalizer finalizer = null)
+ {
+ m_OldShader = oldName;
+ m_NewShader = newName;
+ m_Finalizer = finalizer;
+ }
+
+ ///
+ /// Rename Texture Parameter.
+ ///
+ /// Old name.
+ /// New name.
+ public void RenameTexture(string oldName, string newName)
+ {
+ m_TextureRename[oldName] = newName;
+ }
+
+ ///
+ /// Rename Float Parameter.
+ ///
+ /// Old name.
+ /// New name.
+ public void RenameFloat(string oldName, string newName)
+ {
+ m_FloatRename[oldName] = newName;
+ }
+
+ ///
+ /// Rename Color Parameter.
+ ///
+ /// Old name.
+ /// New name.
+ public void RenameColor(string oldName, string newName)
+ {
+ m_ColorRename[oldName] = newName;
+ }
+
+ ///
+ /// Remove Texture Parameter.
+ ///
+ /// Parameter name.
+ public void RemoveTexture(string name)
+ {
+ m_TexturesToRemove.Add(name);
+ }
+
+ ///
+ /// Set float property.
+ ///
+ /// Property name.
+ /// Property value.
+ public void SetFloat(string propertyName, float value)
+ {
+ m_FloatPropertiesToSet[propertyName] = value;
+ }
+
+ ///
+ /// Set color property.
+ ///
+ /// Property name.
+ /// Property value.
+ public void SetColor(string propertyName, Color value)
+ {
+ m_ColorPropertiesToSet[propertyName] = value;
+ }
+
+ ///
+ /// Set texture property.
+ ///
+ /// Property name.
+ /// Property value.
+ public void SetTexture(string propertyName, Texture value)
+ {
+ m_TexturesToSet[propertyName] = value;
+ }
+
+ ///
+ /// Rename a keyword to float.
+ ///
+ /// Old name.
+ /// New name.
+ /// Value when set.
+ /// Value when unset.
+ public void RenameKeywordToFloat(string oldName, string newName, float setVal, float unsetVal)
+ {
+ m_KeywordFloatRename.Add(new KeywordFloatRename { keyword = oldName, property = newName, setVal = setVal, unsetVal = unsetVal });
+ }
+
+ ///
+ /// Rename a float property conditionally based on its value
+ ///
+ /// Old property name
+ /// New property name
+ /// Condition function that takes the float value and returns true if renaming should occur
+ protected void RenameFloat(string oldName, string newName, System.Func condition)
+ {
+ (m_ConditionalFloatRename ??= new Dictionary)>())[oldName] = (newName, condition);
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/MaterialUpgrader.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.cs.meta
similarity index 100%
rename from Packages/com.unity.render-pipelines.core/Editor/MaterialUpgrader.cs.meta
rename to Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgrader.cs.meta
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistry.cs b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistry.cs
new file mode 100644
index 00000000000..798d3e7f70f
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistry.cs
@@ -0,0 +1,102 @@
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using UnityEngine.Rendering;
+
+namespace UnityEditor.Rendering
+{
+ ///
+ /// Class to handle the Material Upgraders and fetching of them
+ ///
+ internal class MaterialUpgraderRegistry
+ {
+ private static Lazy m_Instance = new(() => new MaterialUpgraderRegistry());
+
+ ///
+ /// Singleton instance of the registry.
+ ///
+ public static MaterialUpgraderRegistry instance => m_Instance.Value;
+
+ Dictionary> m_UpgradersSupportedByPipeline = new();
+
+ ///
+ /// Returns a list of with a given asset type
+ ///
+ /// A valid RP asset type
+ /// Returns a list of
+ public List GetMaterialUpgradersForPipeline(Type renderPipelineAssetType)
+ {
+ List materialUpgraders = GetOrCreateMaterialUpgradersForPipeline(renderPipelineAssetType);
+ materialUpgraders.AddRange(GetOrCreateMaterialUpgradersForPipeline(typeof(RenderPipelineAsset)));
+ materialUpgraders.Sort(CompareUpgradersByOldShaderAndPriority);
+ return materialUpgraders;
+ }
+
+ private int CompareUpgradersByOldShaderAndPriority(MaterialUpgrader a, MaterialUpgrader b)
+ {
+ string nameA = a?.OldShaderPath ?? string.Empty;
+ string nameB = b?.OldShaderPath ?? string.Empty;
+ int nameComparison = string.Compare(nameA, nameB, StringComparison.Ordinal);
+ if (nameComparison != 0)
+ return nameComparison;
+
+ // If names are the same, compare by priority
+ return b.priority.CompareTo(a.priority);
+ }
+
+ MaterialUpgraderRegistry()
+ {
+ var providerTypes = TypeCache.GetTypesDerivedFrom();
+
+ foreach (var providerType in providerTypes)
+ {
+ if (providerType.IsAbstract)
+ continue;
+
+ var provider = Activator.CreateInstance(providerType) as IMaterialUpgradersProvider;
+
+ var upgraders = provider.GetUpgraders();
+ if (upgraders == null)
+ continue;
+
+ var pipelineTypes = GetSupportedPipelines(providerType);
+
+ if (pipelineTypes.Length == 0)
+ pipelineTypes = new Type[] { typeof(RenderPipelineAsset) }; // Default to all pipelines if none specified
+
+ foreach (var pipelineType in pipelineTypes)
+ {
+ var upgradersForPipeline = GetOrCreateMaterialUpgradersForPipeline(pipelineType);
+ foreach(var upgrader in upgraders)
+ {
+ upgradersForPipeline.Add(upgrader);
+ }
+ }
+ }
+ }
+
+ private static Type[] GetSupportedPipelines(Type upgraderType)
+ {
+ var attr = upgraderType.GetCustomAttribute();
+ if (attr == null)
+ throw new InvalidOperationException($"Missing {nameof(SupportedOnRenderPipelineAttribute)} on {upgraderType}");
+
+ return attr.renderPipelineTypes;
+ }
+
+
+ private List GetOrCreateMaterialUpgradersForPipeline(Type renderPipelineAssetType)
+ {
+ if (!typeof(RenderPipelineAsset).IsAssignableFrom(renderPipelineAssetType))
+ throw new ArgumentException($"Type '{renderPipelineAssetType.FullName}' must inherit from RenderPipelineAsset.", nameof(renderPipelineAssetType));
+
+ if (!m_UpgradersSupportedByPipeline.TryGetValue(renderPipelineAssetType, out var upgradersForPipeline))
+ {
+ upgradersForPipeline = new List();
+ m_UpgradersSupportedByPipeline[renderPipelineAssetType] = upgradersForPipeline;
+ }
+
+ return upgradersForPipeline;
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistry.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistry.cs.meta
new file mode 100644
index 00000000000..50dddff57cf
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistry.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: f118938a043d65c4cbecc1878576e305
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Editor/SpeedTree8MaterialUpgrader.cs b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/SpeedTree8MaterialUpgrader.cs
similarity index 99%
rename from Packages/com.unity.render-pipelines.core/Editor/SpeedTree8MaterialUpgrader.cs
rename to Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/SpeedTree8MaterialUpgrader.cs
index 3cb18a77aad..456344041eb 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/SpeedTree8MaterialUpgrader.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/SpeedTree8MaterialUpgrader.cs
@@ -1,7 +1,4 @@
-using System.Collections.Generic;
using UnityEngine;
-using System;
-using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Rendering
{
diff --git a/Packages/com.unity.render-pipelines.core/Editor/SpeedTree8MaterialUpgrader.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/SpeedTree8MaterialUpgrader.cs.meta
similarity index 100%
rename from Packages/com.unity.render-pipelines.core/Editor/SpeedTree8MaterialUpgrader.cs.meta
rename to Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/SpeedTree8MaterialUpgrader.cs.meta
diff --git a/Packages/com.unity.render-pipelines.core/Editor/SpeedTree9MaterialUpgrader.cs b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/SpeedTree9MaterialUpgrader.cs
similarity index 93%
rename from Packages/com.unity.render-pipelines.core/Editor/SpeedTree9MaterialUpgrader.cs
rename to Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/SpeedTree9MaterialUpgrader.cs
index ffe4c8a24bb..ef531f282b7 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/SpeedTree9MaterialUpgrader.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/SpeedTree9MaterialUpgrader.cs
@@ -1,7 +1,4 @@
-using System.Collections.Generic;
using UnityEngine;
-using System;
-using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Rendering
{
diff --git a/Packages/com.unity.render-pipelines.core/Editor/SpeedTree9MaterialUpgrader.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/SpeedTree9MaterialUpgrader.cs.meta
similarity index 100%
rename from Packages/com.unity.render-pipelines.core/Editor/SpeedTree9MaterialUpgrader.cs.meta
rename to Packages/com.unity.render-pipelines.core/Editor/Tools/MaterialUpgrader/SpeedTree9MaterialUpgrader.cs.meta
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Utilities/GenericEditorTool.cs b/Packages/com.unity.render-pipelines.core/Editor/Utilities/GenericEditorTool.cs
new file mode 100644
index 00000000000..276f8346483
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Utilities/GenericEditorTool.cs
@@ -0,0 +1,65 @@
+
+using System.Collections.Generic;
+
+using UnityEditorInternal;
+
+using UnityEditor.EditorTools;
+
+using UnityEngine;
+
+using Object = UnityEngine.Object;
+using System.Runtime.CompilerServices;
+
+using UnityEditor;
+
+[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor")]
+[assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition.Editor")]
+
+namespace UnityEditor.Rendering.Utilities
+{
+ class GenericEditorTool : EditorTool where T : Component
+ {
+ readonly string m_Description;
+ readonly EditMode.SceneViewEditMode m_Mode;
+ readonly string m_IconName;
+ GUIContent m_IconContent;
+
+ protected GenericEditorTool(string description, EditMode.SceneViewEditMode mode, string iconName)
+ {
+ m_Description = description;
+ m_Mode = mode;
+ m_IconName = iconName;
+ }
+
+ public override GUIContent toolbarIcon => m_IconContent;
+ public override void OnWillBeDeactivated() => EditMode.SetEditModeToNone();
+ public override void OnToolGUI(EditorWindow window)
+ {
+ if (EditMode.editMode == m_Mode)
+ return;
+
+ List usefulTargets = new();
+ foreach (Object thisTarget in targets)
+ if (thisTarget is T usefulTarget)
+ usefulTargets.Add(usefulTarget);
+
+ if (usefulTargets.Count == 0)
+ return;
+
+ Bounds bounds = GetBoundsOfTargets(usefulTargets);
+ EditMode.ChangeEditMode(m_Mode, bounds);
+ ToolManager.SetActiveTool(this);
+ }
+
+ private static Bounds GetBoundsOfTargets(IEnumerable targets)
+ {
+ var bounds = new Bounds { min = Vector3.positiveInfinity, max = Vector3.negativeInfinity };
+ foreach (T t in targets)
+ bounds.Encapsulate(t.transform.position);
+
+ return bounds;
+ }
+
+ private void OnEnable() => m_IconContent = EditorGUIUtility.TrIconContent(m_IconName, m_Description);
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Utilities/GenericEditorTool.cs.meta b/Packages/com.unity.render-pipelines.core/Editor/Utilities/GenericEditorTool.cs.meta
new file mode 100644
index 00000000000..59ddc2b0b94
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Editor/Utilities/GenericEditorTool.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 78d06e068976749e285dd70a52d49c80
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentEditor.cs b/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentEditor.cs
index b61b9fa322b..13367b7e2ac 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentEditor.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentEditor.cs
@@ -447,8 +447,17 @@ public override void OnInspectorGUI()
/// A label to display in the component header.
public virtual GUIContent GetDisplayTitle()
{
- var title = string.IsNullOrEmpty(volumeComponent.displayName) ? ObjectNames.NicifyVariableName(volumeComponent.GetType().Name) : volumeComponent.displayName;
- return EditorGUIUtility.TrTextContent(title, string.Empty);
+ var volumeComponentType = volumeComponent.GetType();
+ var displayInfo = volumeComponentType.GetCustomAttribute();
+ if (displayInfo != null && !string.IsNullOrWhiteSpace(displayInfo.name))
+ return EditorGUIUtility.TrTextContent(displayInfo.name, string.Empty);
+
+ #pragma warning disable CS0618
+ if (!string.IsNullOrWhiteSpace(volumeComponent.displayName))
+ return EditorGUIUtility.TrTextContent(volumeComponent.displayName, string.Empty);
+ #pragma warning restore CS0618
+
+ return EditorGUIUtility.TrTextContent(ObjectNames.NicifyVariableName(volumeComponentType.Name) , string.Empty);
}
void AddToggleState(GUIContent content, bool state)
diff --git a/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentListEditor.cs b/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentListEditor.cs
index 36eebd1b566..69af1c4dcdc 100644
--- a/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentListEditor.cs
+++ b/Packages/com.unity.render-pipelines.core/Editor/Volume/VolumeComponentListEditor.cs
@@ -236,11 +236,14 @@ public void OnGUI()
// Even if the asset is not dirty, the list of component may have been changed by another inspector.
// In this case, only the hash will tell us that we need to refresh.
- if (asset.isDirty || asset.GetComponentListHashCode() != m_CurrentHashCode)
+ if (asset.dirtyState != VolumeProfile.DirtyState.None || asset.GetComponentListHashCode() != m_CurrentHashCode)
{
RefreshEditors();
VolumeManager.instance.OnVolumeProfileChanged(asset);
- asset.isDirty = false;
+
+ if ((asset.dirtyState & VolumeProfile.DirtyState.DirtyByProfileReset) != 0)
+ UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
+ asset.dirtyState = VolumeProfile.DirtyState.None;
}
if (m_IsDefaultVolumeProfile && VolumeManager.instance.isInitialized && m_EditorsByCategory.Count == 0)
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Common/GlobalDynamicResolutionSettings.cs b/Packages/com.unity.render-pipelines.core/Runtime/Common/GlobalDynamicResolutionSettings.cs
index 7cda3fe1976..dcc9fbac97d 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Common/GlobalDynamicResolutionSettings.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Common/GlobalDynamicResolutionSettings.cs
@@ -68,7 +68,11 @@ public enum AdvancedUpscalers : byte
/// Spatial-Temporal Post-Processing
///
[InspectorName("Spatial-Temporal Post-Processing (STP)")]
- STP = 2
+ STP = 2,
+
+#if ENABLE_UPSCALER_FRAMEWORK
+ IUpscaler = 3
+#endif
}
/// User-facing settings for dynamic resolution.
@@ -90,6 +94,10 @@ public struct GlobalDynamicResolutionSettings
lowResVolumetricCloudsMinimumThreshold = 50.0f,
rayTracingHalfResThreshold = 50.0f,
+#if ENABLE_UPSCALER_FRAMEWORK
+ IUpscalerOptions = new List(),
+#endif
+
DLSSUseOptimalSettings = true,
DLSSPerfQualitySetting = 0,
DLSSSharpness = 0.5f,
@@ -102,7 +110,7 @@ public struct GlobalDynamicResolutionSettings
FSR2InjectionPoint = DynamicResolutionHandler.UpsamplerScheduleType.BeforePost,
TAAUInjectionPoint = DynamicResolutionHandler.UpsamplerScheduleType.BeforePost,
defaultInjectionPoint = DynamicResolutionHandler.UpsamplerScheduleType.AfterPost,
- advancedUpscalersByPriority = new List() { AdvancedUpscalers.STP },
+ advancedUpscalerNames = new List() { AdvancedUpscalers.STP.ToString() },
fsrOverrideSharpness = false,
fsrSharpness = FSRUtils.kDefaultSharpnessLinear
@@ -114,8 +122,12 @@ public struct GlobalDynamicResolutionSettings
public bool useMipBias;
/// Enables upsamplers available for certain platforms by priority.
+ [Obsolete("Obsolete, use advancedUpscalerNames list instead.")]
public List advancedUpscalersByPriority;
+ /// List of upsamplers available for certain platforms by priority.
+ public List advancedUpscalerNames;
+
/// Opaque quality setting of NVIDIA Deep Learning Super Sampling (DLSS). Use the system enum UnityEngine.NVIDIA.DLSSQuality to set the quality.
public uint DLSSPerfQualitySetting;
@@ -180,6 +192,11 @@ public struct GlobalDynamicResolutionSettings
[Range(0, 1)]
public float fsrSharpness;
+#if ENABLE_UPSCALER_FRAMEWORK
+ [SerializeReference]
+ public List IUpscalerOptions;
+#endif
+
/// The maximum resolution percentage that dynamic resolution can reach.
public float maxPercentage;
/// The minimum resolution percentage that dynamic resolution can reach.
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebug.shader b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebug.shader
index 7fce64773b0..a6a1ee4d5c5 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebug.shader
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeDebug.shader
@@ -7,7 +7,7 @@ Shader "Hidden/Core/ProbeVolumeDebug"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_fragment _ PROBE_VOLUMES_L1 PROBE_VOLUMES_L2
// Central render pipeline specific includes
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeFragmentationDebug.shader b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeFragmentationDebug.shader
index 48fd203bd3e..a845ec3ed05 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeFragmentationDebug.shader
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeFragmentationDebug.shader
@@ -13,7 +13,7 @@ Shader "Hidden/Core/ProbeVolumeFragmentationDebug"
HLSLPROGRAM
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
#pragma vertex Vert
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeOffsetDebug.shader b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeOffsetDebug.shader
index f345c3857db..4d5f20a52f8 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeOffsetDebug.shader
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeOffsetDebug.shader
@@ -8,7 +8,7 @@ Shader "Hidden/Core/ProbeVolumeOffsetDebug"
HLSLINCLUDE
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_fragment _ PROBE_VOLUMES_L1 PROBE_VOLUMES_L2
// Central render pipeline specific includes
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeSamplingDebug.shader b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeSamplingDebug.shader
index e03f043b9dd..dc1395e9a07 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeSamplingDebug.shader
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Debug/ProbeVolumeSamplingDebug.shader
@@ -9,7 +9,7 @@ Shader "Hidden/Core/ProbeVolumeSamplingDebug"
HLSLINCLUDE
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_fragment _ PROBE_VOLUMES_L1 PROBE_VOLUMES_L2
//#pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.UIState.cs b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.UIState.cs
index f80b0058759..edcdd3623b4 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.UIState.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Debugging/DebugManager.UIState.cs
@@ -6,7 +6,7 @@
using UnityEditor;
#endif
-#if UNITY_ANDROID || UNITY_IPHONE || UNITY_TVOS || UNITY_SWITCH
+#if UNITY_ANDROID || UNITY_IPHONE || UNITY_TVOS || UNITY_SWITCH || UNITY_SWITCH2
using UnityEngine.UI;
#endif
@@ -104,7 +104,7 @@ public bool displayRuntimeUI
m_Root.transform.localPosition = Vector3.zero;
m_RootUICanvas = m_Root.GetComponent();
-#if UNITY_ANDROID || UNITY_IPHONE || UNITY_TVOS || UNITY_SWITCH
+#if UNITY_ANDROID || UNITY_IPHONE || UNITY_TVOS || UNITY_SWITCH || UNITY_SWITCH2
var canvasScaler = m_Root.GetComponent();
canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
#endif
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/GPUResidentBatcher.cs b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/GPUResidentBatcher.cs
index f868a00d477..a7f39e7a5ff 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/GPUResidentBatcher.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/GPUResidentBatcher.cs
@@ -173,9 +173,15 @@ private void UpdateRendererInstancesAndBatches(in GPUDrivenRendererGroupData ren
GPUInstanceDataBufferUploader uploader = m_BatchersContext.CreateDataBufferUploader(instances.Length, InstanceType.MeshRenderer);
uploader.AllocateUploadHandles(instances.Length);
- JobHandle writeJobHandle = default;
- writeJobHandle = uploader.WriteInstanceDataJob(m_BatchersContext.renderersParameters.lightmapScale.index, rendererData.lightmapScaleOffset, rendererData.rendererGroupIndex);
- writeJobHandle.Complete();
+ JobHandle lightmapSTWriteJobHandle = uploader.WriteInstanceDataJob(m_BatchersContext.renderersParameters.lightmapScale.index,
+ rendererData.lightmapScaleOffset,
+ rendererData.rendererGroupIndex);
+
+ JobHandle rendererUserValuesWriteJobHandle = uploader.WriteInstanceDataJob(m_BatchersContext.renderersParameters.rendererUserValues.index,
+ rendererData.rendererUserValues,
+ rendererData.rendererGroupIndex);
+
+ JobHandle.CombineDependencies(lightmapSTWriteJobHandle, rendererUserValuesWriteJobHandle).Complete();
m_BatchersContext.SubmitToGpu(instances, ref uploader, submitOnlyWrittenParams: true);
m_BatchersContext.ChangeInstanceBufferVersion();
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCuller.cs b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCuller.cs
index 6a1ecf711f7..d4909830936 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCuller.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/InstanceCuller.cs
@@ -403,11 +403,11 @@ private unsafe uint CalculateVisibilityMask(int instanceIndex, int sharedInstanc
private uint ComputeMeshLODLevel(int instanceIndex, int sharedInstanceIndex)
{
ref readonly GPUDrivenRendererMeshLodData meshLodData = ref instanceData.meshLodData.UnsafeElementAt(instanceIndex);
+ var meshLodInfo = sharedInstanceData.meshLodInfos[sharedInstanceIndex];
if (meshLodData.forceLod >= 0)
- return (uint)meshLodData.forceLod;
+ return (uint)math.clamp(meshLodData.forceLod, 0, meshLodInfo.levelCount - 1);
- var levelInfo = sharedInstanceData.meshLodInfos[sharedInstanceIndex];
ref readonly AABB worldAABB = ref instanceData.worldAABBs.UnsafeElementAt(instanceIndex);
var radiusSqr = math.max(math.lengthsq(worldAABB.extents), 1e-5f);
@@ -417,13 +417,13 @@ private uint ComputeMeshLODLevel(int instanceIndex, int sharedInstanceIndex)
var boundsDesiredPercentage = Math.Sqrt(cameraSqrHeightAtDistance / diameterSqr);
- var levelIndexFlt = math.log2(boundsDesiredPercentage) * levelInfo.lodSlope + levelInfo.lodBias;
+ var levelIndexFlt = math.log2(boundsDesiredPercentage) * meshLodInfo.lodSlope + meshLodInfo.lodBias;
// We apply Bias after max to enforce that a positive bias of +N we would select lodN instead of Lod0
levelIndexFlt = math.max(levelIndexFlt, 0);
levelIndexFlt += meshLodData.lodSelectionBias;
- levelIndexFlt = math.clamp(levelIndexFlt,0, levelInfo.levelCount - 1);
+ levelIndexFlt = math.clamp(levelIndexFlt, 0, meshLodInfo.levelCount - 1);
return (uint)math.floor(levelIndexFlt);
}
@@ -1323,7 +1323,7 @@ public void Execute()
output.drawCommandCount = output.visibleInstanceCount; // for picking/filtering, 1 draw command per instance!
output.drawCommands = MemoryUtilities.Malloc(output.drawCommandCount, Allocator.TempJob);
- output.drawCommandPickingInstanceIDs = MemoryUtilities.Malloc(output.drawCommandCount, Allocator.TempJob);
+ output.drawCommandPickingEntityIds = MemoryUtilities.Malloc(output.drawCommandCount, Allocator.TempJob);
int outRangeIndex = 0;
int outCommandIndex = 0;
@@ -1372,7 +1372,7 @@ public void Execute()
throw new Exception("Draw command created with an invalid BatchID");
#endif
output.visibleInstances[outVisibleInstanceIndex] = instanceDataBuffer.CPUInstanceToGPUInstance(instance).index;
- output.drawCommandPickingInstanceIDs[outCommandIndex] = rendererID;
+ output.drawCommandPickingEntityIds[outCommandIndex] = rendererID;
output.drawCommands[outCommandIndex] = new BatchDrawCommand
{
flags = BatchDrawCommandFlags.None,
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/RenderersParameters.cs b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/RenderersParameters.cs
index 3b8293dd827..c66a6ba531d 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/RenderersParameters.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/RenderersParameters.cs
@@ -4,6 +4,7 @@
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
+using Unity.Mathematics;
namespace UnityEngine.Rendering
{
@@ -44,6 +45,7 @@ public static class ParamNames
public static readonly int unity_MatrixPreviousM = Shader.PropertyToID("unity_MatrixPreviousM");
public static readonly int unity_MatrixPreviousMI = Shader.PropertyToID("unity_MatrixPreviousMI");
public static readonly int unity_WorldBoundingSphere = Shader.PropertyToID("unity_WorldBoundingSphere");
+ public static readonly int unity_RendererUserValuesPropertyEntry = Shader.PropertyToID("unity_RendererUserValuesPropertyEntry");
public static readonly int[] DOTS_ST_WindParams = new int[(int)SpeedTreeWindParamIndex.MaxWindParamsCount];
public static readonly int[] DOTS_ST_WindHistoryParams = new int[(int)SpeedTreeWindParamIndex.MaxWindParamsCount];
@@ -70,6 +72,7 @@ public static GPUInstanceDataBuffer CreateInstanceDataBuffer(Flags flags, in Ins
builder.AddComponent(ParamNames.unity_WorldToObject, isOverriden: true, isPerInstance: true, InstanceType.MeshRenderer);
builder.AddComponent(ParamNames.unity_MatrixPreviousM, isOverriden: true, isPerInstance: true, InstanceType.MeshRenderer);
builder.AddComponent(ParamNames.unity_MatrixPreviousMI, isOverriden: true, isPerInstance: true, InstanceType.MeshRenderer);
+ builder.AddComponent(ParamNames.unity_RendererUserValuesPropertyEntry, isOverriden: true, isPerInstance: true, InstanceType.MeshRenderer);
if ((flags & Flags.UseBoundingSphereParameter) != 0)
{
builder.AddComponent(ParamNames.unity_WorldBoundingSphere, isOverriden: true, isPerInstance: true, InstanceType.MeshRenderer);
@@ -99,6 +102,7 @@ public struct ParamInfo
public ParamInfo matrixPreviousM;
public ParamInfo matrixPreviousMI;
public ParamInfo shCoefficients;
+ public ParamInfo rendererUserValues;
public ParamInfo boundingSphere;
public ParamInfo[] windParams;
@@ -124,6 +128,7 @@ ParamInfo GetParamInfo(in GPUInstanceDataBuffer instanceDataBuffer, int paramNam
matrixPreviousM = GetParamInfo(instanceDataBuffer, ParamNames.unity_MatrixPreviousM);
matrixPreviousMI = GetParamInfo(instanceDataBuffer, ParamNames.unity_MatrixPreviousMI);
shCoefficients = GetParamInfo(instanceDataBuffer, ParamNames.unity_SHCoefficients);
+ rendererUserValues = GetParamInfo(instanceDataBuffer, ParamNames.unity_RendererUserValuesPropertyEntry);
boundingSphere = GetParamInfo(instanceDataBuffer, ParamNames.unity_WorldBoundingSphere, assertOnFail: false);
windParams = new ParamInfo[(int)SpeedTreeWindParamIndex.MaxWindParamsCount];
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl
index 73e63fd81e9..b7ae5454872 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolume.hlsl
@@ -1,9 +1,9 @@
#ifndef __PROBEVOLUME_HLSL__
#define __PROBEVOLUME_HLSL__
-#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH)
+#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
//#define USE_APV_TEXTURE_HALF
-#endif // SHADER_API_MOBILE || SHADER_API_SWITCH
+#endif // SHADER_API_MOBILE || SHADER_API_SWITCH || SHADER_API_SWITCH2
#include "Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ShaderVariablesProbeVolumes.cs.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/SphericalHarmonics.hlsl"
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumesOptions.cs b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumesOptions.cs
index 2ddb14a8ef4..ebbbd638cfc 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumesOptions.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Lighting/ProbeVolume/ProbeVolumesOptions.cs
@@ -23,13 +23,9 @@ public APVLeakReductionModeParameter(APVLeakReductionMode value, bool overrideSt
///
[Serializable, VolumeComponentMenu("Lighting/Adaptive Probe Volumes Options"), SupportedOnRenderPipeline]
[CurrentPipelineHelpURL("probevolumes")]
+ [DisplayInfo(name = "Adaptive Probe Volumes Options")]
public sealed class ProbeVolumesOptions : VolumeComponent
{
- ProbeVolumesOptions()
- {
- displayName = "Adaptive Probe Volumes Options";
- }
-
///
/// The overridden normal bias to be applied to the world position when sampling the Adaptive Probe Volumes data structure. Unit is meters.
///
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PostProcessing/LensFlareCommonSRP.cs b/Packages/com.unity.render-pipelines.core/Runtime/PostProcessing/LensFlareCommonSRP.cs
index a77e76c7b1c..346b28985b8 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/PostProcessing/LensFlareCommonSRP.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/PostProcessing/LensFlareCommonSRP.cs
@@ -1,6 +1,5 @@
using System;
using System.Collections.Generic;
-using System.Xml.Linq;
using UnityEngine.Experimental.Rendering;
namespace UnityEngine.Rendering
@@ -92,6 +91,7 @@ internal LensFlareCompInfo(int idx, LensFlareComponentSRP cmp)
internal static readonly int _FlareData3 = Shader.PropertyToID("_FlareData3");
internal static readonly int _FlareData4 = Shader.PropertyToID("_FlareData4");
internal static readonly int _FlareData5 = Shader.PropertyToID("_FlareData5");
+ internal static readonly int _FlareData6 = Shader.PropertyToID("_FlareData6");
internal static readonly int _FlareRadialTint = Shader.PropertyToID("_FlareRadialTint");
internal static readonly int _ViewId = Shader.PropertyToID("_ViewId");
@@ -759,20 +759,17 @@ static bool IsLensFlareSRPHidden(Camera cam, LensFlareComponentSRP comp, LensFla
return false;
}
- ///
- /// Computes the internal parameters needed to render a single flare.
- ///
- /// The screen position of the flare.
- /// The scale of translation applied to the flare.
- /// The base offset for the flare ray.
- /// The ratio of the flare's local screen size.
- /// The base angle of rotation for the flare.
- /// The position along the flare's radial line, relative to the source, where 1.0 represents the edge of the screen.
- /// Angular offset applied to the flare's position.
- /// The offset from the flare's calculated position.
- /// Flag to enable automatic rotation based on flare's position.
- /// A Vector4 object representing the shader parameters _FlareData0.
- static public Vector4 GetFlareData0(Vector2 screenPos, Vector2 translationScale, Vector2 rayOff0, Vector2 vLocalScreenRatio, float angleDeg, float position, float angularOffset, Vector2 positionOffset, bool autoRotate)
+ static Vector4 InternalGetFlareData0(
+ Vector2 screenPos,
+ Vector2 translationScale,
+ Vector2 rayOff0,
+ Vector2 vLocalScreenRatio,
+ float angleDeg,
+ float position,
+ float angularOffset,
+ Vector2 positionOffset,
+ bool autoRotate
+ )
{
if (!SystemInfo.graphicsUVStartsAtTop)
{
@@ -803,7 +800,26 @@ static public Vector4 GetFlareData0(Vector2 screenPos, Vector2 translationScale,
return new Vector4(localCos0, localSin0, positionOffset.x + rayOff0.x * translationScale.x, -positionOffset.y + rayOff0.y * translationScale.y);
}
- static Vector2 GetLensFlareRayOffset(Vector2 screenPos, float position, float globalCos0, float globalSin0, Vector2 vAspectRatio)
+ ///
+ /// Computes the internal parameters needed to render a single flare.
+ ///
+ /// The screen position of the flare.
+ /// The scale of translation applied to the flare.
+ /// The base offset for the flare ray.
+ /// The ratio of the flare's local screen size.
+ /// The base angle of rotation for the flare.
+ /// The position along the flare's radial line, relative to the source, where 1.0 represents the edge of the screen.
+ /// Angular offset applied to the flare's position.
+ /// The offset from the flare's calculated position.
+ /// Flag to enable automatic rotation based on flare's position.
+ /// A Vector4 object representing the shader parameters _FlareData0.
+ [Obsolete("This is now deprecated as a public API. Call ComputeOcclusion() or DoLensFlareDataDrivenCommon() instead. #from(6000.3)")]
+ static public Vector4 GetFlareData0(Vector2 screenPos, Vector2 translationScale, Vector2 rayOff0, Vector2 vLocalScreenRatio, float angleDeg, float position, float angularOffset, Vector2 positionOffset, bool autoRotate)
+ {
+ return InternalGetFlareData0(screenPos, translationScale, rayOff0, vLocalScreenRatio, angleDeg, position, angularOffset, positionOffset, autoRotate);
+ }
+
+ static Vector2 GetLensFlareRayOffset(Vector2 screenPos, float position, float globalCos0, float globalSin0)
{
Vector2 rayOff = -(screenPos + screenPos * (position - 1.0f));
return new Vector2(globalCos0 * rayOff.x - globalSin0 * rayOff.y,
@@ -899,20 +915,6 @@ static public bool IsCloudLayerOpacityNeeded(Camera cam)
return false;
}
- static void SetOcclusionPermutation(CommandBuffer cmd, bool useFogOpacityOcclusion, int _FlareSunOcclusionTex, Texture sunOcclusionTexture)
- {
- uint occlusionPermutation = (uint)(LensFlareOcclusionPermutation.Depth);
-
- if (useFogOpacityOcclusion && sunOcclusionTexture != null)
- {
- occlusionPermutation |= (uint)(LensFlareOcclusionPermutation.FogOpacity);
- cmd.SetGlobalTexture(_FlareSunOcclusionTex, sunOcclusionTexture);
- }
-
- int convInt = unchecked((int)occlusionPermutation);
- cmd.SetGlobalInt(_FlareOcclusionPermutation, convInt);
- }
-
#if UNITY_EDITOR
static bool IsPrefabStageEnabled()
{
@@ -936,58 +938,6 @@ static bool IsCurrentPrefabLensFlareComponent(GameObject go, LensFlareComponentS
}
#endif
- ///
- /// Renders the set of lens flare registered.
- ///
- /// lens flare material (HDRP or URP shader)
- /// Camera
- /// XR Infos
- /// Index of the SinglePass XR
- /// Width actually used for rendering after dynamic resolution and XR is applied.
- /// Height actually used for rendering after dynamic resolution and XR is applied.
- /// Set if use Panani Projection
- /// Distance used for Panini projection
- /// CropToFit parameter used for Panini projection
- /// Set if camera is relative
- /// Camera World Space position
- /// View Projection Matrix of the current camera
- /// Command Buffer
- /// Set if TAA is enabled
- /// Unused
- /// Unused
- /// Sun Occlusion Texture from VolumetricCloud on HDRP or null
- /// ShaderID for the FlareOcclusionTex
- /// ShaderID for the FlareCloudOpacity
- /// ShaderID for the FlareOcclusionIndex
- /// ShaderID for the FlareTex
- /// ShaderID for the FlareColor
- /// ShaderID for the _FlareSunOcclusionTex
- /// ShaderID for the FlareData0
- /// ShaderID for the FlareData1
- /// ShaderID for the FlareData2
- /// ShaderID for the FlareData3
- /// ShaderID for the FlareData4
- [Obsolete("Use ComputeOcclusion without _FlareOcclusionTex.._FlareData4 parameters. #from(2023.3)")]
- static public void ComputeOcclusion(Material lensFlareShader, Camera cam, XRPass xr, int xrIndex,
- float actualWidth, float actualHeight,
- bool usePanini, float paniniDistance, float paniniCropToFit, bool isCameraRelative,
- Vector3 cameraPositionWS,
- Matrix4x4 viewProjMatrix,
- UnsafeCommandBuffer cmd,
- bool taaEnabled, bool hasCloudLayer, Texture cloudOpacityTexture, Texture sunOcclusionTexture,
- int _FlareOcclusionTex, int _FlareCloudOpacity, int _FlareOcclusionIndex, int _FlareTex, int _FlareColorValue, int _FlareSunOcclusionTex, int _FlareData0, int _FlareData1, int _FlareData2, int _FlareData3, int _FlareData4)
- {
- ComputeOcclusion(
- lensFlareShader, cam, xr, xrIndex,
- actualWidth, actualHeight,
- usePanini, paniniDistance, paniniCropToFit, isCameraRelative,
- cameraPositionWS,
- viewProjMatrix,
- cmd.m_WrappedCommandBuffer,
- taaEnabled, hasCloudLayer, cloudOpacityTexture, sunOcclusionTexture,
- _FlareOcclusionTex, _FlareCloudOpacity, _FlareOcclusionIndex, _FlareTex, _FlareColorValue, _FlareSunOcclusionTex, _FlareData0, _FlareData1, _FlareData2, _FlareData3, _FlareData4);
- }
-
///
/// Renders the set of lens flare registered.
///
@@ -1026,56 +976,6 @@ static public void ComputeOcclusion(Material lensFlareShader, Camera cam, XRPass
taaEnabled, hasCloudLayer, cloudOpacityTexture, sunOcclusionTexture);
}
- ///
- /// Renders the set of lens flare registered.
- ///
- /// lens flare material (HDRP or URP shader)
- /// Camera
- /// XRPass data.
- /// XR multipass ID.
- /// Width actually used for rendering after dynamic resolution and XR is applied.
- /// Height actually used for rendering after dynamic resolution and XR is applied.
- /// Set if use Panani Projection
- /// Distance used for Panini projection
- /// CropToFit parameter used for Panini projection
- /// Set if camera is relative
- /// Camera World Space position
- /// View Projection Matrix of the current camera
- /// Command Buffer
- /// Set if TAA is enabled
- /// Unused
- /// Unused
- /// Sun Occlusion Texture from VolumetricCloud on HDRP or null
- /// ShaderID for the FlareOcclusionTex
- /// ShaderID for the FlareCloudOpacity
- /// ShaderID for the FlareOcclusionIndex
- /// ShaderID for the FlareTex
- /// ShaderID for the FlareColor
- /// ShaderID for the _FlareSunOcclusionTex
- /// ShaderID for the FlareData0
- /// ShaderID for the FlareData1
- /// ShaderID for the FlareData2
- /// ShaderID for the FlareData3
- /// ShaderID for the FlareData4
- [Obsolete("Use ComputeOcclusion without _FlareOcclusionTex.._FlareData4 parameters. #from(2023.3)")]
- static public void ComputeOcclusion(Material lensFlareShader, Camera cam, XRPass xr, int xrIndex,
- float actualWidth, float actualHeight,
- bool usePanini, float paniniDistance, float paniniCropToFit, bool isCameraRelative,
- Vector3 cameraPositionWS,
- Matrix4x4 viewProjMatrix,
- Rendering.CommandBuffer cmd,
- bool taaEnabled, bool hasCloudLayer, Texture cloudOpacityTexture, Texture sunOcclusionTexture,
- int _FlareOcclusionTex, int _FlareCloudOpacity, int _FlareOcclusionIndex, int _FlareTex, int _FlareColorValue, int _FlareSunOcclusionTex, int _FlareData0, int _FlareData1, int _FlareData2, int _FlareData3, int _FlareData4)
- {
- ComputeOcclusion(lensFlareShader, cam, xr, xrIndex,
- actualWidth, actualHeight,
- usePanini, paniniDistance, paniniCropToFit, isCameraRelative,
- cameraPositionWS,
- viewProjMatrix,
- cmd,
- taaEnabled, hasCloudLayer, cloudOpacityTexture, sunOcclusionTexture);
- }
-
static bool ForceSingleElement(LensFlareDataElementSRP element)
{
return !element.allowMultipleElement
@@ -1083,238 +983,392 @@ static bool ForceSingleElement(LensFlareDataElementSRP element)
|| element.flareType == SRPLensFlareType.Ring;
}
- ///
- /// Computes the occlusion of lens flare using the depth buffer and additional occlusion textures if not null.
- ///
- /// Lens flare material (HDRP or URP shader)
- /// Camera
- /// XRPass data.
- /// XR multipass ID.
- /// Width actually used for rendering after dynamic resolution and XR is applied.
- /// Height actually used for rendering after dynamic resolution and XR is applied.
- /// Set if use Panani Projection
- /// Distance used for Panini projection
- /// CropToFit parameter used for Panini projection
- /// Set if camera is relative
- /// Camera World Space position
- /// View Projection Matrix of the current camera
- /// Command Buffer
- /// Set if TAA is enabled
- /// Unused
- /// Unused
- /// Sun Occlusion Texture from VolumetricCloud on HDRP or null
- static public void ComputeOcclusion(Material lensFlareShader, Camera cam, XRPass xr, int xrIndex,
- float actualWidth, float actualHeight,
- bool usePanini, float paniniDistance, float paniniCropToFit, bool isCameraRelative,
- Vector3 cameraPositionWS,
- Matrix4x4 viewProjMatrix,
- Rendering.CommandBuffer cmd,
- bool taaEnabled, bool hasCloudLayer, Texture cloudOpacityTexture, Texture sunOcclusionTexture)
+ // Do the once-per-frame setup before we loop over the lens flare
+ // components to render them. This involves querying whether we're
+ // editing a prefab, checking if lens flares are disabled in scene view,
+ // setting the render target, and potentially clearing it.
+ // If this returns false, we can early out before rendering anything.
+ static bool PreDrawSetup(
+ bool occlusionOnly,
+ bool clearRenderTarget,
+ RenderTargetIdentifier rt,
+ Camera cam,
+ XRPass xr,
+ int xrIndex,
+ Rendering.CommandBuffer cmd
+#if UNITY_EDITOR
+ , out bool inPrefabStage,
+ out GameObject prefabGameObject,
+ out LensFlareComponentSRP[] prefabStageLensFlares
+#endif
+ )
{
- if (!IsOcclusionRTCompatible())
- return;
-
- xr.StopSinglePass(cmd);
-
+ // Get prefab information if we're in prefab staging mode
#if UNITY_EDITOR
- bool inPrefabStage = IsPrefabStageEnabled();
- UnityEditor.SceneManagement.PrefabStage prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
- GameObject prefabGameObject = null;
- LensFlareComponentSRP[] prefabStageLensFlares = null;
+ inPrefabStage = IsPrefabStageEnabled();
+ UnityEditor.SceneManagement.PrefabStage prefabStage =UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
+ prefabGameObject = null;
+ prefabStageLensFlares = null;
if (prefabStage != null)
{
+ if (prefabStage.prefabContentsRoot == null)
+ return false;
+
prefabGameObject = prefabStage.prefabContentsRoot;
- if (prefabGameObject == null)
- return;
prefabStageLensFlares = GetLensFlareComponents(prefabGameObject);
if (prefabStageLensFlares.Length == 0)
{
- return;
+ return false;
}
}
#endif
+ xr.StopSinglePass(cmd);
+
if (Instance.IsEmpty())
- return;
+ return false;
+ // Early out if we're in the scene view and if flares are disabled
+ // there.
#if UNITY_EDITOR
if (cam.cameraType == CameraType.SceneView)
{
- // Determine whether the "Animated Materials" checkbox is checked for the current view.
- for (int i = 0; i < UnityEditor.SceneView.sceneViews.Count; i++) // Using a foreach on an ArrayList generates garbage ...
+ // Determine whether the "Animated Materials" checkbox is
+ // checked for the current view.
+ for (int i = 0; i < UnityEditor.SceneView.sceneViews.Count; i++)
{
var sv = UnityEditor.SceneView.sceneViews[i] as UnityEditor.SceneView;
if (sv.camera == cam && !sv.sceneViewState.flaresEnabled)
{
- return;
+ return false;
}
}
}
#endif
- Vector2 screenSize = new Vector2(actualWidth, actualHeight);
- float screenRatio = screenSize.x / screenSize.y;
- Vector2 vScreenRatio = new Vector2(screenRatio, 1.0f);
-
-#if ENABLE_VR && ENABLE_XR_MODULE
- if (xr.enabled && xr.singlePassEnabled)
- {
- CoreUtils.SetRenderTarget(cmd, occlusionRT, depthSlice: xrIndex);
- cmd.SetGlobalInt(_ViewId, xrIndex);
- }
- else
-#endif
+ // Set the render target and the view ID
{
- CoreUtils.SetRenderTarget(cmd, occlusionRT);
- if (xr.enabled) // multipass
- cmd.SetGlobalInt(_ViewId, xr.multipassId);
+ int viewId = occlusionOnly? -1 : 0;
+#if ENABLE_VR && ENABLE_XR_MODULE
+ if (xr.enabled && xr.singlePassEnabled)
+ {
+ CoreUtils.SetRenderTarget(cmd, rt, depthSlice: xrIndex);
+ cmd.SetGlobalInt(_ViewId, xrIndex);
+ }
else
- cmd.SetGlobalInt(_ViewId, -1);
+#endif
+ {
+ CoreUtils.SetRenderTarget(cmd, rt);
+ if (xr.enabled) // multipass
+ cmd.SetGlobalInt(_ViewId, xr.multipassId);
+ else
+ cmd.SetGlobalInt(_ViewId, viewId);
+ }
}
- if (!taaEnabled)
- {
+ // TODO: Maybe we need to do this?
+ /* if (!occlusionOnly) {
+ cmd.SetViewport(viewport);
+ } */
+
+ if (clearRenderTarget) {
cmd.ClearRenderTarget(false, true, Color.black);
}
- float dx = 1.0f / ((float)maxLensFlareWithOcclusion);
- float dy = 1.0f / ((float)(maxLensFlareWithOcclusionTemporalSample + mergeNeeded));
- float halfx = 0.5f / ((float)maxLensFlareWithOcclusion);
- float halfy = 0.5f / ((float)(maxLensFlareWithOcclusionTemporalSample + mergeNeeded));
+ return true;
+ }
- foreach (LensFlareCompInfo info in m_Data)
- {
- if (info == null || info.comp == null)
- continue;
+ static bool DoComponent(
+ bool occlusionOnly,
+ LensFlareCompInfo info,
+ Camera cam,
+ Vector3 cameraPositionWS,
+ float actualWidth,
+ float actualHeight,
+ bool usePanini,
+ float paniniDistance,
+ float paniniCropToFit,
+ bool isCameraRelative,
+ Matrix4x4 viewProjMatrix,
+ Rendering.CommandBuffer cmd,
+#if UNITY_EDITOR
+ bool inPrefabStage,
+ GameObject prefabGameObject,
+ LensFlareComponentSRP[] prefabStageLensFlares,
+#endif
+ out Vector3 flarePosWS,
+ out Vector3 flarePosViewport,
+ out Vector2 flarePosScreen,
+ out Vector3 camToFlare,
+ out Light light,
+ out bool isDirLight,
+ out float flareIntensity,
+ out float distanceAttenuation
+ )
+ {
+ // Init out values in case we early out
+ flarePosWS = Vector3.zero;
+ flarePosViewport = Vector3.zero;
+ flarePosScreen = Vector2.zero;
+ camToFlare = Vector3.zero;
+ isDirLight = false;
+ light = null;
+ flareIntensity = 0f;
+ distanceAttenuation = 1f;
+
+ if (info == null || info.comp == null)
+ return false;
- LensFlareComponentSRP comp = info.comp;
- LensFlareDataSRP data = comp.lensFlareData;
+ LensFlareComponentSRP comp = info.comp;
+ LensFlareDataSRP data = comp.lensFlareData;
- if (IsLensFlareSRPHidden(cam, comp, data) ||
- !comp.useOcclusion ||
- (comp.useOcclusion && comp.sampleCount == 0))
- continue;
+ if (IsLensFlareSRPHidden(cam, comp, data))
+ return false;
+
+ // If we're in occlusion-only mode, and occlusion isn't used, we can
+ // early out. If we're in color mode, this component
+ // will be drawn, so we do not early out.
+ if (occlusionOnly && !comp.useOcclusion)
+ return false;
#if UNITY_EDITOR
- if (inPrefabStage && !IsCurrentPrefabLensFlareComponent(prefabGameObject, prefabStageLensFlares, comp))
- {
- continue;
- }
+ // If we're editing a prefab, but we're not editing this component,
+ // we don't want to render it. Early out.
+ if (inPrefabStage && !IsCurrentPrefabLensFlareComponent(prefabGameObject, prefabStageLensFlares, comp))
+ {
+ return false;
+ }
#endif
- Light light = null;
+ // Get the light and some related variables
+ {
if (!comp.TryGetComponent(out light))
light = null;
- Vector3 positionWS;
- Vector3 viewportPos;
- bool isDirLight = false;
if (light != null && light.type == LightType.Directional)
{
- positionWS = -light.transform.forward * cam.farClipPlane;
+ flarePosWS = -light.transform.forward * cam.farClipPlane;
isDirLight = true;
}
else
{
- positionWS = comp.transform.position;
- }
-
- viewportPos = WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS);
-
- if (usePanini && cam == Camera.main)
- {
- viewportPos = DoPaniniProjection(viewportPos, actualWidth, actualHeight, cam.fieldOfView, paniniCropToFit, paniniDistance);
- }
-
- if (viewportPos.z < 0.0f)
- continue;
-
- if (!comp.allowOffScreen)
- {
- if (viewportPos.x < 0.0f || viewportPos.x > 1.0f ||
- viewportPos.y < 0.0f || viewportPos.y > 1.0f)
- continue;
- }
-
- Vector3 diffToObject = positionWS - cameraPositionWS;
- // Check if the light is forward, can be an issue with,
- // the math associated to Panini projection
- if (Vector3.Dot(cam.transform.forward, diffToObject) < 0.0f)
- {
- continue;
+ flarePosWS = comp.transform.position;
}
- float distToObject = diffToObject.magnitude;
- float coefDistSample = distToObject / comp.maxAttenuationDistance;
- float coefScaleSample = distToObject / comp.maxAttenuationScale;
- float distanceAttenuation = !isDirLight && comp.distanceAttenuationCurve.length > 0 ? comp.distanceAttenuationCurve.Evaluate(coefDistSample) : 1.0f;
- float scaleByDistance = !isDirLight && comp.scaleByDistanceCurve.length >= 1 ? comp.scaleByDistanceCurve.Evaluate(coefScaleSample) : 1.0f;
-
- Vector3 dir;
- if (isDirLight)
- dir = comp.transform.forward;
- else
- dir = (cam.transform.position - comp.transform.position).normalized;
- Vector3 screenPosZ = WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS + dir * comp.occlusionOffset);
-
- float adjustedOcclusionRadius = isDirLight ? comp.celestialProjectedOcclusionRadius(cam) : comp.occlusionRadius;
- Vector2 occlusionRadiusEdgeScreenPos0 = (Vector2)viewportPos;
- Vector2 occlusionRadiusEdgeScreenPos1 = (Vector2)WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS + cam.transform.up * adjustedOcclusionRadius);
- float occlusionRadius = (occlusionRadiusEdgeScreenPos1 - occlusionRadiusEdgeScreenPos0).magnitude;
-
- cmd.SetGlobalVector(_FlareData1, new Vector4(occlusionRadius, comp.sampleCount, screenPosZ.z, actualHeight / actualWidth));
+ }
- SetOcclusionPermutation(cmd, comp.environmentOcclusion, _FlareSunOcclusionTex, sunOcclusionTexture);
- cmd.EnableShaderKeyword("FLARE_COMPUTE_OCCLUSION");
+ // Users can specify a light override. If set, it specifices the light
+ // component where color and shape values are fetched from for this
+ // component. This only matters in the color pass, and not in the
+ // occlusion-only pass.
+ if (!occlusionOnly && comp.lightOverride != null)
+ {
+ light = comp.lightOverride;
+ }
- Vector2 screenPos = new Vector2(2.0f * viewportPos.x - 1.0f, -(2.0f * viewportPos.y - 1.0f));
- if (!SystemInfo.graphicsUVStartsAtTop && isDirLight)
- screenPos.y = -screenPos.y;
+ flarePosViewport = WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, flarePosWS);
- Vector2 radPos = new Vector2(Mathf.Abs(screenPos.x), Mathf.Abs(screenPos.y));
- float radius = Mathf.Max(radPos.x, radPos.y); // l1 norm (instead of l2 norm)
- float radialsScaleRadius = comp.radialScreenAttenuationCurve.length > 0 ? comp.radialScreenAttenuationCurve.Evaluate(radius) : 1.0f;
+ if (usePanini && cam == Camera.main)
+ {
+ flarePosViewport = DoPaniniProjection(flarePosViewport, actualWidth, actualHeight, cam.fieldOfView, paniniCropToFit, paniniDistance);
+ }
- float compIntensity = comp.intensity * radialsScaleRadius * distanceAttenuation;
+ if (flarePosViewport.z < 0.0f)
+ return false;
- if (compIntensity <= 0.0f)
- continue;
+ if (!comp.allowOffScreen)
+ {
+ // Early out if the component is outside the screen
+ if (flarePosViewport.x < 0.0f || flarePosViewport.x > 1.0f ||
+ flarePosViewport.y < 0.0f || flarePosViewport.y > 1.0f)
+ return false;
+ }
- float globalCos0 = Mathf.Cos(0.0f);
- float globalSin0 = Mathf.Sin(0.0f);
+ // Early out if the light is behind the camera. If we don't do this,
+ // it can cause issues with Panini projection.
+ camToFlare = flarePosWS - cameraPositionWS;
+ if (Vector3.Dot(cam.transform.forward, camToFlare) < 0.0f)
+ return false;
- float position = 0.0f;
+ float distToObject = camToFlare.magnitude; // TOD: return;
+ float coefDistSample = distToObject / comp.maxAttenuationDistance;
+ distanceAttenuation = !isDirLight && comp.distanceAttenuationCurve.length > 0 ? comp.distanceAttenuationCurve.Evaluate(coefDistSample) : 1.0f;
- float usedGradientPosition = Mathf.Clamp01(1.0f - 1e-6f);
+ // Calculate the screen-space position
+ flarePosScreen = new Vector2(2.0f * flarePosViewport.x - 1.0f, -(2.0f * flarePosViewport.y - 1.0f));
+ if (!SystemInfo.graphicsUVStartsAtTop && isDirLight)
+ // Y-flip for OpenGL
+ flarePosScreen.y = -flarePosScreen.y;
- cmd.SetGlobalVector(_FlareData3, new Vector4(comp.allowOffScreen ? 1.0f : -1.0f, usedGradientPosition, Mathf.Exp(Mathf.Lerp(0.0f, 4.0f, 1.0f)), 1.0f / 3.0f));
+ Vector2 radPos = new Vector2(Mathf.Abs(flarePosScreen.x), Mathf.Abs(flarePosScreen.y));
+ float radius = Mathf.Max(radPos.x, radPos.y); // L1 norm (instead of L2 norm)
+ float radialsScaleRadius = comp.radialScreenAttenuationCurve.length > 0 ?
+ comp.radialScreenAttenuationCurve.Evaluate(radius) : 1.0f;
- Vector2 rayOff = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0, vScreenRatio);
- Vector4 flareData0 = GetFlareData0(screenPos, Vector2.one, rayOff, vScreenRatio, 0.0f, position, 0.0f, Vector2.zero, false);
- cmd.SetGlobalVector(_FlareData0, flareData0);
- cmd.SetGlobalVector(_FlareData2, new Vector4(screenPos.x, screenPos.y, 0.0f, 0.0f));
+ // Early out if the component's intensity is zero or negative
+ flareIntensity = comp.intensity * radialsScaleRadius * distanceAttenuation;
+ if (flareIntensity <= 0.0f)
+ return false;
- Rect rect;
- if (taaEnabled)
- rect = new Rect() { x = info.index, y = frameIdx + mergeNeeded, width = 1, height = 1 };
- else
- rect = new Rect() { x = info.index, y = 0, width = 1, height = 1 };
- cmd.SetViewport(rect);
+ // Set _FlareData1
+ {
+ float adjustedOcclusionRadius =
+ isDirLight ? comp.celestialProjectedOcclusionRadius(cam) : comp.occlusionRadius;
+ Vector2 occlusionRadiusEdgeScreenPos0 = (Vector2)flarePosViewport;
+ Vector2 occlusionRadiusEdgeScreenPos1 = (Vector2)WorldToViewport(cam, !isDirLight, isCameraRelative,
+ viewProjMatrix, flarePosWS + cam.transform.up * adjustedOcclusionRadius);
+ float occlusionRadius = (occlusionRadiusEdgeScreenPos1 - occlusionRadiusEdgeScreenPos0).magnitude;
- Blitter.DrawQuad(cmd, lensFlareShader, lensFlareShader.FindPass("LensFlareOcclusion"));
- }
+ Vector3 dir = (cam.transform.position - comp.transform.position).normalized;
+ Vector3 screenPosZ = WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix,
+ flarePosWS + dir * comp.occlusionOffset);
- // Clear the remaining buffer if not TAA the whole OcclusionRT is already cleared
- if (taaEnabled)
- {
- CoreUtils.SetRenderTarget(cmd, occlusionRT, depthSlice: xrIndex);
- cmd.SetViewport(new Rect() { x = m_Data.Count, y = 0, width = (maxLensFlareWithOcclusion - m_Data.Count), height = (maxLensFlareWithOcclusionTemporalSample + mergeNeeded) });
- cmd.ClearRenderTarget(false, true, Color.black);
+ cmd.SetGlobalVector(_FlareData1,
+ new Vector4(occlusionRadius, comp.sampleCount, screenPosZ.z, actualHeight / actualWidth));
}
- ++frameIdx;
- frameIdx %= maxLensFlareWithOcclusionTemporalSample;
+ return true;
+ }
+
+ ///
+ /// Computes the occlusion of lens flare using the depth buffer and additional occlusion textures if not null.
+ ///
+ /// Lens flare material (HDRP or URP shader)
+ /// Camera
+ /// XRPass data.
+ /// XR multipass ID.
+ /// Width actually used for rendering after dynamic resolution and XR is applied.
+ /// Height actually used for rendering after dynamic resolution and XR is applied.
+ /// Set if use Panani Projection
+ /// Distance used for Panini projection
+ /// CropToFit parameter used for Panini projection
+ /// Set if camera is relative
+ /// Camera World Space position
+ /// View Projection Matrix of the current camera
+ /// Command Buffer
+ /// Set if TAA is enabled
+ /// Unused
+ /// Unused
+ /// Sun Occlusion Texture from VolumetricCloud on HDRP or null
+ static public void ComputeOcclusion(Material lensFlareShader, Camera cam, XRPass xr, int xrIndex,
+ float actualWidth, float actualHeight,
+ bool usePanini, float paniniDistance, float paniniCropToFit, bool isCameraRelative,
+ Vector3 cameraPositionWS,
+ Matrix4x4 viewProjMatrix,
+ Rendering.CommandBuffer cmd,
+ bool taaEnabled, bool hasCloudLayer, Texture cloudOpacityTexture, Texture sunOcclusionTexture)
+ {
+ if (!IsOcclusionRTCompatible())
+ return;
+
+ // Once-per frame setup
+ bool clearRenderTarget = !taaEnabled;
+ bool ok = PreDrawSetup(
+ true,
+ clearRenderTarget,
+ occlusionRT,
+ cam,
+ xr,
+ xrIndex,
+ cmd
+#if UNITY_EDITOR
+ , out bool inPrefabStage,
+ out GameObject prefabGameObject,
+ out LensFlareComponentSRP[] prefabStageLensFlares
+#endif
+ );
+
+ if (!ok)
+ return;
+
+ float aspect = actualWidth / actualHeight;
+
+ foreach (LensFlareCompInfo info in m_Data)
+ {
+ bool okComp = DoComponent(
+ true,
+ info,
+ cam,
+ cameraPositionWS,
+ actualWidth,
+ actualHeight,
+ usePanini,
+ paniniDistance,
+ paniniCropToFit,
+ isCameraRelative,
+ viewProjMatrix,
+ cmd,
+#if UNITY_EDITOR
+ inPrefabStage,
+ prefabGameObject,
+ prefabStageLensFlares,
+#endif
+ out Vector3 flarePosWS,
+ out Vector3 flarePosViewport,
+ out Vector2 flarePosScreen,
+ out Vector3 camToFlare,
+ out Light light,
+ out bool isDirLight,
+ out float flareIntensity,
+ out float distanceAttenuation
+ );
+ if (!okComp)
+ continue;
+
+ LensFlareComponentSRP comp = info.comp;
+
+ // Set the occlusion keyword and bind occlusion shader constants
+ {
+ cmd.EnableShaderKeyword("FLARE_COMPUTE_OCCLUSION");
+ uint occlusionPermutation = (uint)(LensFlareOcclusionPermutation.Depth);
+
+ if (comp.environmentOcclusion && sunOcclusionTexture != null)
+ {
+ occlusionPermutation |= (uint)(LensFlareOcclusionPermutation.FogOpacity);
+ cmd.SetGlobalTexture(_FlareSunOcclusionTex, sunOcclusionTexture);
+ }
+
+ int convInt = unchecked((int)occlusionPermutation);
+ cmd.SetGlobalInt(_FlareOcclusionPermutation, convInt);
+ }
+
+ float globalCos0 = Mathf.Cos(0.0f);
+ float globalSin0 = Mathf.Sin(0.0f);
+
+ float position = 0.0f;
+
+ float usedGradientPosition = Mathf.Clamp01(1.0f - 1e-6f);
+
+ cmd.SetGlobalVector(_FlareData3, new Vector4(comp.allowOffScreen ? 1.0f : -1.0f, usedGradientPosition, Mathf.Exp(Mathf.Lerp(0.0f, 4.0f, 1.0f)), 1.0f / 3.0f));
+
+ Vector2 rayOff = GetLensFlareRayOffset(flarePosScreen, position, globalCos0, globalSin0);
+ Vector2 vScreenRatio = new Vector2(aspect, 1f);
+ Vector4 flareData0 = InternalGetFlareData0(flarePosScreen, Vector2.one, rayOff, vScreenRatio, 0.0f, position, 0.0f, Vector2.zero, false);
+
+ cmd.SetGlobalVector(_FlareData0, flareData0);
+ cmd.SetGlobalVector(_FlareData2, new Vector4(flarePosScreen.x, flarePosScreen.y, 0.0f, 0.0f));
+
+ Rect rect;
+ if (taaEnabled)
+ rect = new Rect() { x = info.index, y = frameIdx + mergeNeeded, width = 1, height = 1 };
+ else
+ rect = new Rect() { x = info.index, y = 0, width = 1, height = 1 };
+ cmd.SetViewport(rect);
+
+ Blitter.DrawQuad(cmd, lensFlareShader, lensFlareShader.FindPass("LensFlareOcclusion"));
+ }
+
+ // Clear the remaining buffer if not TAA the whole OcclusionRT is already cleared
+ if (taaEnabled)
+ {
+ CoreUtils.SetRenderTarget(cmd, occlusionRT, depthSlice: xrIndex);
+ cmd.SetViewport(new Rect() { x = m_Data.Count, y = 0, width = (maxLensFlareWithOcclusion - m_Data.Count), height = (maxLensFlareWithOcclusionTemporalSample + mergeNeeded) });
+ cmd.ClearRenderTarget(false, true, Color.black);
+ }
+
+ ++frameIdx;
+ frameIdx %= maxLensFlareWithOcclusionTemporalSample;
xr.StartSinglePass(cmd);
}
@@ -1339,7 +1393,7 @@ static public void ComputeOcclusion(Material lensFlareShader, Camera cam, XRPass
/// true if we are on preview on the inspector
/// Depth counter for recursive call of 'ProcessLensFlareSRPElementsSingle'.
public static void ProcessLensFlareSRPElementsSingle(LensFlareDataElementSRP element, Rendering.CommandBuffer cmd, Color globalColorModulation, Light light,
- float compIntensity, float scale, Material lensFlareShader, Vector2 screenPos, bool compAllowOffScreen, Vector2 vScreenRatio, Vector4 flareData1, bool preview, int depth)
+ float compIntensity, float scale, Material lensFlareShader, Vector2 screenPos, bool compAllowOffScreen, Vector2 vScreenRatio, Vector3 flareData1, bool preview, int depth)
{
if (element == null ||
element.visible == false ||
@@ -1351,7 +1405,8 @@ public static void ProcessLensFlareSRPElementsSingle(LensFlareDataElementSRP ele
if (element.flareType == SRPLensFlareType.LensFlareDataSRP && element.lensFlareDataSRP != null)
{
- ProcessLensFlareSRPElements(ref element.lensFlareDataSRP.elements, cmd, globalColorModulation, light, compIntensity, scale, lensFlareShader, screenPos, compAllowOffScreen, vScreenRatio, flareData1, preview, depth + 1);
+ Vector3 unused = new();
+ ProcessLensFlareSRPElements(ref element.lensFlareDataSRP.elements, cmd, globalColorModulation, light, compIntensity, scale, lensFlareShader, screenPos, compAllowOffScreen, vScreenRatio.x, unused, preview, depth + 1);
return;
}
@@ -1436,9 +1491,9 @@ public static void ProcessLensFlareSRPElementsSingle(LensFlareDataElementSRP ele
}
#endif
- flareData1.x = (float)element.flareType;
+ var flareData6 = new Vector4((float)element.flareType, 0, 0, 0);
if (ForceSingleElement(element))
- cmd.SetGlobalVector(_FlareData1, flareData1);
+ cmd.SetGlobalVector(_FlareData6, flareData6);
if (element.flareType == SRPLensFlareType.Circle ||
element.flareType == SRPLensFlareType.Polygon ||
@@ -1470,7 +1525,7 @@ public static void ProcessLensFlareSRPElementsSingle(LensFlareDataElementSRP ele
Vector2 ComputeLocalSize(Vector2 rayOff, Vector2 rayOff0, Vector2 curSize, AnimationCurve distortionCurve)
{
- Vector2 rayOffZ = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0, vScreenRatio);
+ Vector2 rayOffZ = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0);
Vector2 localRadPos;
float localRadius;
if (!element.distortionRelativeToCenter)
@@ -1520,13 +1575,13 @@ Vector2 ComputeLocalSize(Vector2 rayOff, Vector2 rayOff0, Vector2 curSize, Anima
if (ForceSingleElement(element))
{
Vector2 localSize = size;
- Vector2 rayOff = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0, vScreenRatio);
+ Vector2 rayOff = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0);
if (element.enableRadialDistortion)
{
- Vector2 rayOff0 = GetLensFlareRayOffset(screenPos, 0.0f, globalCos0, globalSin0, vScreenRatio);
+ Vector2 rayOff0 = GetLensFlareRayOffset(screenPos, 0.0f, globalCos0, globalSin0);
localSize = ComputeLocalSize(rayOff, rayOff0, localSize, element.distortionCurve);
}
- Vector4 flareData0 = GetFlareData0(screenPos, element.translationScale, rayOff, vScreenRatio, rotation, position, angularOffset, element.positionOffset, element.autoRotate);
+ Vector4 flareData0 = InternalGetFlareData0(screenPos, element.translationScale, rayOff, vScreenRatio, rotation, position, angularOffset, element.positionOffset, element.autoRotate);
cmd.SetGlobalVector(_FlareData0, flareData0);
cmd.SetGlobalVector(_FlareData2, new Vector4(screenPos.x, screenPos.y, localSize.x, localSize.y));
@@ -1544,10 +1599,10 @@ Vector2 ComputeLocalSize(Vector2 rayOff, Vector2 rayOff0, Vector2 curSize, Anima
for (int elemIdx = 0; elemIdx < element.count; ++elemIdx)
{
Vector2 localSize = size;
- Vector2 rayOff = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0, vScreenRatio);
+ Vector2 rayOff = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0);
if (element.enableRadialDistortion)
{
- Vector2 rayOff0 = GetLensFlareRayOffset(screenPos, 0.0f, globalCos0, globalSin0, vScreenRatio);
+ Vector2 rayOff0 = GetLensFlareRayOffset(screenPos, 0.0f, globalCos0, globalSin0);
localSize = ComputeLocalSize(rayOff, rayOff0, localSize, element.distortionCurve);
}
@@ -1555,11 +1610,11 @@ Vector2 ComputeLocalSize(Vector2 rayOff, Vector2 rayOff0, Vector2 curSize, Anima
Color col = element.colorGradient.Evaluate(timeScale);
- Vector4 flareData0 = GetFlareData0(screenPos, element.translationScale, rayOff, vScreenRatio, rotation + uniformAngle, position, angularOffset, element.positionOffset, element.autoRotate);
+ Vector4 flareData0 = InternalGetFlareData0(screenPos, element.translationScale, rayOff, vScreenRatio, rotation + uniformAngle, position, angularOffset, element.positionOffset, element.autoRotate);
cmd.SetGlobalVector(_FlareData0, flareData0);
- flareData1.y = (float)elemIdx;
- cmd.SetGlobalVector(_FlareData1, flareData1);
+ flareData6.y = (float)elemIdx;
+ cmd.SetGlobalVector(_FlareData6, flareData6);
cmd.SetGlobalVector(_FlareData2, new Vector4(screenPos.x, screenPos.y, localSize.x, localSize.y));
cmd.SetGlobalVector(_FlareColorValue, curColor * col);
@@ -1583,11 +1638,11 @@ float RandomRange(float min, float max)
{
float localIntensity = RandomRange(-1.0f, 1.0f) * element.intensityVariation + 1.0f;
- Vector2 rayOff = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0, vScreenRatio);
+ Vector2 rayOff = GetLensFlareRayOffset(screenPos, position, globalCos0, globalSin0);
Vector2 localSize = size;
if (element.enableRadialDistortion)
{
- Vector2 rayOff0 = GetLensFlareRayOffset(screenPos, 0.0f, globalCos0, globalSin0, vScreenRatio);
+ Vector2 rayOff0 = GetLensFlareRayOffset(screenPos, 0.0f, globalCos0, globalSin0);
localSize = ComputeLocalSize(rayOff, rayOff0, localSize, element.distortionCurve);
}
@@ -1601,10 +1656,10 @@ float RandomRange(float min, float max)
if (localIntensity > 0.0f)
{
- Vector4 flareData0 = GetFlareData0(screenPos, element.translationScale, rayOff, vScreenRatio, localRotation, position, angularOffset, localPositionOffset, element.autoRotate);
+ Vector4 flareData0 = InternalGetFlareData0(screenPos, element.translationScale, rayOff, vScreenRatio, localRotation, position, angularOffset, localPositionOffset, element.autoRotate);
cmd.SetGlobalVector(_FlareData0, flareData0);
- flareData1.y = (float)elemIdx;
- cmd.SetGlobalVector(_FlareData1, flareData1);
+ flareData6.y = (float)elemIdx;
+ cmd.SetGlobalVector(_FlareData6, flareData6);
cmd.SetGlobalVector(_FlareData2, new Vector4(screenPos.x, screenPos.y, localSize.x, localSize.y));
cmd.SetGlobalVector(_FlareColorValue, curColor * randCol * localIntensity);
@@ -1627,11 +1682,11 @@ float RandomRange(float min, float max)
float positionSpacing = element.positionCurve.length > 0 ? element.positionCurve.Evaluate(timeScale) : 1.0f;
float localPos = position + 2.0f * element.lengthSpread * positionSpacing;
- Vector2 rayOff = GetLensFlareRayOffset(screenPos, localPos, globalCos0, globalSin0, vScreenRatio);
+ Vector2 rayOff = GetLensFlareRayOffset(screenPos, localPos, globalCos0, globalSin0);
Vector2 localSize = size;
if (element.enableRadialDistortion)
{
- Vector2 rayOff0 = GetLensFlareRayOffset(screenPos, 0.0f, globalCos0, globalSin0, vScreenRatio);
+ Vector2 rayOff0 = GetLensFlareRayOffset(screenPos, 0.0f, globalCos0, globalSin0);
localSize = ComputeLocalSize(rayOff, rayOff0, localSize, element.distortionCurve);
}
float sizeCurveValue = element.scaleCurve.length > 0 ? element.scaleCurve.Evaluate(timeScale) : 1.0f;
@@ -1639,10 +1694,10 @@ float RandomRange(float min, float max)
float angleFromCurve = element.uniformAngleCurve.Evaluate(timeScale) * (180.0f - (180.0f / (float)element.count));
- Vector4 flareData0 = GetFlareData0(screenPos, element.translationScale, rayOff, vScreenRatio, rotation + angleFromCurve, localPos, angularOffset, element.positionOffset, element.autoRotate);
+ Vector4 flareData0 = InternalGetFlareData0(screenPos, element.translationScale, rayOff, vScreenRatio, rotation + angleFromCurve, localPos, angularOffset, element.positionOffset, element.autoRotate);
cmd.SetGlobalVector(_FlareData0, flareData0);
- flareData1.y = (float)elemIdx;
- cmd.SetGlobalVector(_FlareData1, flareData1);
+ flareData6.y = (float)elemIdx;
+ cmd.SetGlobalVector(_FlareData6, flareData6);
cmd.SetGlobalVector(_FlareData2, new Vector4(screenPos.x, screenPos.y, localSize.x, localSize.y));
cmd.SetGlobalVector(_FlareColorValue, curColor * col);
@@ -1653,7 +1708,7 @@ float RandomRange(float min, float max)
}
static void ProcessLensFlareSRPElements(ref LensFlareDataElementSRP[] elements, Rendering.CommandBuffer cmd, Color globalColorModulation, Light light,
- float compIntensity, float scale, Material lensFlareShader, Vector2 screenPos, bool compAllowOffScreen, Vector2 vScreenRatio, Vector4 flareData1, bool preview, int depth)
+ float compIntensity, float scale, Material lensFlareShader, Vector2 screenPos, bool compAllowOffScreen, float aspect, Vector4 flareData6, bool preview, int depth)
{
if (depth > 16)
{
@@ -1663,75 +1718,11 @@ static void ProcessLensFlareSRPElements(ref LensFlareDataElementSRP[] elements,
foreach (LensFlareDataElementSRP element in elements)
{
- ProcessLensFlareSRPElementsSingle(element, cmd, globalColorModulation, light, compIntensity, scale, lensFlareShader, screenPos, compAllowOffScreen, vScreenRatio, flareData1, preview, depth);
+ Vector3 unused = new();
+ ProcessLensFlareSRPElementsSingle(element, cmd, globalColorModulation, light, compIntensity, scale, lensFlareShader, screenPos, compAllowOffScreen, new Vector2(aspect, 1), unused, preview, depth);
}
}
- ///
- /// Renders the set of lens flare registered.
- ///
- /// Lens flare material (HDRP or URP shader)
- /// Camera
- /// Viewport used for rendering and XR applied.
- /// XRPass data.
- /// XR multipass ID.
- /// Width actually used for rendering after dynamic resolution and XR is applied.
- /// Height actually used for rendering after dynamic resolution and XR is applied.
- /// Set if use Panani Projection
- /// Distance used for Panini projection
- /// CropToFit parameter used for Panini projection
- /// Set if camera is relative
- /// Camera World Space position
- /// View Projection Matrix of the current camera
- /// Command Buffer
- /// Set if TAA is enabled
- /// Unused
- /// Unused
- /// Sun Occlusion Texture from VolumetricCloud on HDRP or null
- /// Source Render Target which contains the Color Buffer
- /// Delegate to which return return the Attenuation of the light based on their shape which uses the functions ShapeAttenuation...(...), must reimplemented per SRP
- /// ShaderID for the FlareOcclusionTex
- /// ShaderID for the FlareOcclusionIndex
- /// ShaderID for the OcclusionRemap
- /// ShaderID for the FlareCloudOpacity
- /// ShaderID for the _FlareSunOcclusionTex
- /// ShaderID for the FlareTex
- /// ShaderID for the FlareColor
- /// ShaderID for the FlareData0
- /// ShaderID for the FlareData1
- /// ShaderID for the FlareData2
- /// ShaderID for the FlareData3
- /// ShaderID for the FlareData4
- /// Debug View which setup black background to see only lens flare
- [Obsolete("Use DoLensFlareDataDrivenCommon without _FlareOcclusionRemapTex.._FlareData4 parameters. #from(2023.3)")]
- static public void DoLensFlareDataDrivenCommon(Material lensFlareShader, Camera cam, Rect viewport, XRPass xr, int xrIndex,
- float actualWidth, float actualHeight,
- bool usePanini, float paniniDistance, float paniniCropToFit,
- bool isCameraRelative,
- Vector3 cameraPositionWS,
- Matrix4x4 viewProjMatrix,
- UnsafeCommandBuffer cmd,
- bool taaEnabled, bool hasCloudLayer, Texture cloudOpacityTexture, Texture sunOcclusionTexture,
- Rendering.RenderTargetIdentifier colorBuffer,
- System.Func GetLensFlareLightAttenuation,
- int _FlareOcclusionRemapTex, int _FlareOcclusionTex, int _FlareOcclusionIndex,
- int _FlareCloudOpacity, int _FlareSunOcclusionTex,
- int _FlareTex, int _FlareColorValue, int _FlareData0, int _FlareData1, int _FlareData2, int _FlareData3, int _FlareData4,
- bool debugView)
- {
- DoLensFlareDataDrivenCommon(lensFlareShader, cam, viewport, xr, xrIndex,
- actualWidth, actualHeight,
- usePanini, paniniDistance, paniniCropToFit,
- isCameraRelative,
- cameraPositionWS,
- viewProjMatrix,
- cmd,
- taaEnabled, hasCloudLayer, cloudOpacityTexture, sunOcclusionTexture,
- colorBuffer,
- GetLensFlareLightAttenuation,
- debugView);
- }
-
///
/// Renders all visible lens flares.
///
@@ -1784,71 +1775,6 @@ static public void DoLensFlareDataDrivenCommon(Material lensFlareShader, Camera
debugView);
}
- ///
- /// Renders the set of lens flare registered.
- ///
- /// Lens flare material (HDRP or URP shader)
- /// Camera
- /// Viewport used for rendering and XR applied.
- /// XRPass data.
- /// XR multipass ID.
- /// Width actually used for rendering after dynamic resolution and XR is applied.
- /// Height actually used for rendering after dynamic resolution and XR is applied.
- /// Set if use Panani Projection
- /// Distance used for Panini projection
- /// CropToFit parameter used for Panini projection
- /// Set if camera is relative
- /// Camera World Space position
- /// View Projection Matrix of the current camera
- /// Command Buffer
- /// Set if TAA is enabled
- /// Unused
- /// Unused
- /// Sun Occlusion Texture from VolumetricCloud on HDRP or null
- /// Source Render Target which contains the Color Buffer
- /// Delegate to which return return the Attenuation of the light based on their shape which uses the functions ShapeAttenuation...(...), must reimplemented per SRP
- /// ShaderID for the FlareOcclusionTex
- /// ShaderID for the FlareOcclusionIndex
- /// ShaderID for the OcclusionRemap
- /// ShaderID for the FlareCloudOpacity
- /// ShaderID for the _FlareSunOcclusionTex
- /// ShaderID for the FlareTex
- /// ShaderID for the FlareColor
- /// ShaderID for the FlareData0
- /// ShaderID for the FlareData1
- /// ShaderID for the FlareData2
- /// ShaderID for the FlareData3
- /// ShaderID for the FlareData4
- /// Debug View which setup black background to see only lens flare
- [Obsolete("Use DoLensFlareDataDrivenCommon without _FlareOcclusionRemapTex.._FlareData4 parameters. #from(2023.3)")]
- static public void DoLensFlareDataDrivenCommon(Material lensFlareShader, Camera cam, Rect viewport, XRPass xr, int xrIndex,
- float actualWidth, float actualHeight,
- bool usePanini, float paniniDistance, float paniniCropToFit,
- bool isCameraRelative,
- Vector3 cameraPositionWS,
- Matrix4x4 viewProjMatrix,
- Rendering.CommandBuffer cmd,
- bool taaEnabled, bool hasCloudLayer, Texture cloudOpacityTexture, Texture sunOcclusionTexture,
- Rendering.RenderTargetIdentifier colorBuffer,
- System.Func GetLensFlareLightAttenuation,
- int _FlareOcclusionRemapTex, int _FlareOcclusionTex, int _FlareOcclusionIndex,
- int _FlareCloudOpacity, int _FlareSunOcclusionTex,
- int _FlareTex, int _FlareColorValue, int _FlareData0, int _FlareData1, int _FlareData2, int _FlareData3, int _FlareData4,
- bool debugView)
- {
- DoLensFlareDataDrivenCommon(lensFlareShader, cam, viewport, xr, xrIndex,
- actualWidth, actualHeight,
- usePanini, paniniDistance, paniniCropToFit,
- isCameraRelative,
- cameraPositionWS,
- viewProjMatrix,
- cmd,
- taaEnabled, hasCloudLayer, cloudOpacityTexture, sunOcclusionTexture,
- colorBuffer,
- GetLensFlareLightAttenuation,
- debugView);
- }
-
///
/// Renders all visible lens flares.
///
@@ -1888,180 +1814,77 @@ static public void DoLensFlareDataDrivenCommon(Material lensFlareShader, Camera
System.Func GetLensFlareLightAttenuation,
bool debugView)
{
+ // Once-per frame setup
+ bool clearRenderTarget = debugView;
+ bool ok = PreDrawSetup(
+ false,
+ clearRenderTarget,
+ colorBuffer,
+ cam,
+ xr,
+ xrIndex,
+ cmd
#if UNITY_EDITOR
- bool inPrefabStage = IsPrefabStageEnabled();
- UnityEditor.SceneManagement.PrefabStage prefabStage = UnityEditor.SceneManagement.PrefabStageUtility.GetCurrentPrefabStage();
- GameObject prefabGameObject = null;
- LensFlareComponentSRP[] prefabStageLensFlares = null;
- if (prefabStage != null)
- {
- prefabGameObject = prefabStage.prefabContentsRoot;
- if (prefabGameObject == null)
- return;
- prefabStageLensFlares = GetLensFlareComponents(prefabGameObject);
- if (prefabStageLensFlares.Length == 0)
- {
- return;
- }
- }
+ , out bool inPrefabStage,
+ out GameObject prefabGameObject,
+ out LensFlareComponentSRP[] prefabStageLensFlares
#endif
+ );
- xr.StopSinglePass(cmd);
-
- Vector2 vScreenRatio;
-
- if (Instance.IsEmpty())
+ if (!ok)
return;
-#if UNITY_EDITOR
- if (cam.cameraType == CameraType.SceneView)
- {
- // Determine whether the "Animated Materials" checkbox is checked for the current view.
- for (int i = 0; i < UnityEditor.SceneView.sceneViews.Count; i++) // Using a foreach on an ArrayList generates garbage ...
- {
- var sv = UnityEditor.SceneView.sceneViews[i] as UnityEditor.SceneView;
- if (sv.camera == cam && !sv.sceneViewState.flaresEnabled)
- {
- return;
- }
- }
- }
-#endif
-
- Vector2 screenSize = new Vector2(actualWidth, actualHeight);
- float screenRatio = screenSize.x / screenSize.y;
- vScreenRatio = new Vector2(screenRatio, 1.0f);
-
-#if ENABLE_VR && ENABLE_XR_MODULE
- if (xr.enabled && xr.singlePassEnabled)
- {
- CoreUtils.SetRenderTarget(cmd, colorBuffer, depthSlice: xrIndex);
- cmd.SetGlobalInt(_ViewId, xrIndex);
- }
- else
-#endif
- {
- CoreUtils.SetRenderTarget(cmd, colorBuffer);
- if (xr.enabled) // multipass
- cmd.SetGlobalInt(_ViewId, xr.multipassId);
- else
- cmd.SetGlobalInt(_ViewId, 0);
- }
-
cmd.SetViewport(viewport);
- if (debugView)
- {
- // Background pitch black to see only the Flares
- cmd.ClearRenderTarget(false, true, Color.black);
- }
+ float aspect = actualWidth / actualHeight;
foreach (LensFlareCompInfo info in m_Data)
{
- if (info == null || info.comp == null)
- continue;
-
- LensFlareComponentSRP comp = info.comp;
- LensFlareDataSRP data = comp.lensFlareData;
-
- if (IsLensFlareSRPHidden(cam, comp, data))
- continue;
-
+ bool okComp = DoComponent(
+ false,
+ info,
+ cam,
+ cameraPositionWS,
+ actualWidth,
+ actualHeight,
+ usePanini,
+ paniniDistance,
+ paniniCropToFit,
+ isCameraRelative,
+ viewProjMatrix,
+ cmd,
#if UNITY_EDITOR
- if (inPrefabStage && !IsCurrentPrefabLensFlareComponent(prefabGameObject, prefabStageLensFlares, comp))
- {
- continue;
- }
+ inPrefabStage,
+ prefabGameObject,
+ prefabStageLensFlares,
#endif
-
- Light light = null;
- if (!comp.TryGetComponent(out light))
- light = null;
-
- Vector3 positionWS;
- Vector3 viewportPos;
-
- bool isDirLight = false;
- if (light != null && light.type == LightType.Directional)
- {
- positionWS = -light.transform.forward * cam.farClipPlane;
- isDirLight = true;
- }
- else
- {
- positionWS = comp.transform.position;
- }
-
- // After positionWS computation, lightOverride do not change the position
- if (comp.lightOverride != null)
- {
- light = comp.lightOverride;
- }
-
- viewportPos = WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS);
-
- if (usePanini && cam == Camera.main)
- {
- viewportPos = DoPaniniProjection(viewportPos, actualWidth, actualHeight, cam.fieldOfView, paniniCropToFit, paniniDistance);
- }
-
- if (viewportPos.z < 0.0f)
+ out Vector3 flarePosWS,
+ out Vector3 flarePosViewport,
+ out Vector2 flarePosScreen,
+ out Vector3 camToFlare,
+ out Light light,
+ out bool isDirLight,
+ out float flareIntensity,
+ out float distanceAttenuation
+ );
+ if (!okComp)
continue;
- if (!comp.allowOffScreen)
- {
- if (viewportPos.x < 0.0f || viewportPos.x > 1.0f ||
- viewportPos.y < 0.0f || viewportPos.y > 1.0f)
- continue;
- }
-
- Vector3 diffToObject = positionWS - cameraPositionWS;
- // Check if the light is forward, can be an issue with,
- // the math associated to Panini projection
- if (Vector3.Dot(cam.transform.forward, diffToObject) < 0.0f)
- {
- continue;
- }
- float distToObject = diffToObject.magnitude;
- float coefDistSample = distToObject / comp.maxAttenuationDistance;
- float coefScaleSample = distToObject / comp.maxAttenuationScale;
- float distanceAttenuation = !isDirLight && comp.distanceAttenuationCurve.length > 0 ? comp.distanceAttenuationCurve.Evaluate(coefDistSample) : 1.0f;
- float scaleByDistance = !isDirLight && comp.scaleByDistanceCurve.length >= 1 ? comp.scaleByDistanceCurve.Evaluate(coefScaleSample) : 1.0f;
+ LensFlareComponentSRP comp = info.comp;
- Color globalColorModulation = Color.white;
- if (light != null)
+ // Set the occlusion-related keywords
+ if (comp.useOcclusion && IsOcclusionRTCompatible())
{
- if (comp.attenuationByLightShape)
- globalColorModulation *= GetLensFlareLightAttenuation(light, cam, -diffToObject.normalized);
+ // We want occlusion for our lens flare and our API supports an occlusion render target.
+ Debug.Assert(occlusionRT != null);
+ cmd.SetGlobalTexture(_FlareOcclusionTex, occlusionRT);
+ cmd.EnableShaderKeyword("FLARE_HAS_OCCLUSION");
}
-
- Vector2 screenPos = new Vector2(2.0f * viewportPos.x - 1.0f, -(2.0f * viewportPos.y - 1.0f));
-
- if(!SystemInfo.graphicsUVStartsAtTop && isDirLight) // Y-flip for OpenGL & directional light
- screenPos.y = -screenPos.y;
-
- Vector2 radPos = new Vector2(Mathf.Abs(screenPos.x), Mathf.Abs(screenPos.y));
- float radius = Mathf.Max(radPos.x, radPos.y); // l1 norm (instead of l2 norm)
- float radialsScaleRadius = comp.radialScreenAttenuationCurve.length > 0 ? comp.radialScreenAttenuationCurve.Evaluate(radius) : 1.0f;
-
- float compIntensity = comp.intensity * radialsScaleRadius * distanceAttenuation;
-
- if (compIntensity <= 0.0f)
- continue;
-
- globalColorModulation *= distanceAttenuation;
-
- Vector3 dir = (cam.transform.position - comp.transform.position).normalized;
- Vector3 screenPosZ = WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS + dir * comp.occlusionOffset);
-
- float adjustedOcclusionRadius = isDirLight ? comp.celestialProjectedOcclusionRadius(cam) : comp.occlusionRadius;
- Vector2 occlusionRadiusEdgeScreenPos0 = (Vector2)viewportPos;
- Vector2 occlusionRadiusEdgeScreenPos1 = (Vector2)WorldToViewport(cam, !isDirLight, isCameraRelative, viewProjMatrix, positionWS + cam.transform.up * adjustedOcclusionRadius);
- float occlusionRadius = (occlusionRadiusEdgeScreenPos1 - occlusionRadiusEdgeScreenPos0).magnitude;
-
- if (comp.useOcclusion && occlusionRT != null)
+ else if (comp.useOcclusion && !IsOcclusionRTCompatible())
{
- cmd.SetGlobalTexture(_FlareOcclusionTex, occlusionRT);
+ // We want occlusion for our lens flare, but our API doesn't support an occlusion render target.
+ // In this case, we won't have an _FlareOcclusionTex, but we can get the depth info from
+ // _CameraDepthTexture instead.
cmd.EnableShaderKeyword("FLARE_HAS_OCCLUSION");
}
else
@@ -2070,21 +1893,28 @@ static public void DoLensFlareDataDrivenCommon(Material lensFlareShader, Camera
}
if (IsOcclusionRTCompatible())
- {
cmd.DisableShaderKeyword("FLARE_OPENGL3_OR_OPENGLCORE");
- }
else
- {
cmd.EnableShaderKeyword("FLARE_OPENGL3_OR_OPENGLCORE");
- }
cmd.SetGlobalVector(_FlareOcclusionIndex, new Vector4((float)info.index, 0.0f, 0.0f, 0.0f));
cmd.SetGlobalTexture(_FlareOcclusionRemapTex, comp.occlusionRemapCurve.GetTexture());
- Vector4 flareData1 = new Vector4(0.0f, comp.sampleCount, screenPosZ.z, actualHeight / actualWidth);
- ProcessLensFlareSRPElements(ref data.elements, cmd, globalColorModulation, light,
- compIntensity, scaleByDistance * comp.scale, lensFlareShader,
- screenPos, comp.allowOffScreen, vScreenRatio, flareData1, false, 0);
+ Vector4 flareData6 = new Vector4();
+ float coefScaleSample = camToFlare.magnitude / comp.maxAttenuationScale;
+ float scaleByDistance = !isDirLight && comp.scaleByDistanceCurve.length >= 1 ? comp.scaleByDistanceCurve.Evaluate(coefScaleSample) : 1.0f;
+
+ Color globalColorModulation = Color.white;
+ if (light != null)
+ {
+ if (comp.attenuationByLightShape)
+ globalColorModulation *= GetLensFlareLightAttenuation(light, cam, -camToFlare.normalized);
+ }
+
+ globalColorModulation *= distanceAttenuation;
+ ProcessLensFlareSRPElements(ref comp.lensFlareData.elements, cmd, globalColorModulation, light,
+ flareIntensity, scaleByDistance * comp.scale, lensFlareShader,
+ flarePosScreen, comp.allowOffScreen, aspect, flareData6, false, 0);
}
xr.StartSinglePass(cmd);
@@ -2155,94 +1985,6 @@ static public void DoLensFlareScreenSpaceCommon(
debugView);
}
- ///
- /// Renders the screen space lens flare effect.
- ///
- ///
- /// Call this function during the post processing of the render pipeline after the bloom.
- ///
- /// Lens flare material (HDRP or URP shader)
- /// Camera
- /// Width actually used for rendering after dynamic resolution and XR is applied.
- /// Height actually used for rendering after dynamic resolution and XR is applied.
- /// tintColor to multiply all the flare by
- /// original Bloom texture used to write on at the end of compositing
- /// Bloom mip texture used as data for the effect
- /// spectralLut used for chromatic aberration effect
- /// Texture used for the multiple pass streaks effect
- /// Texture used for the multiple pass streaks effect
- /// globalIntensity, regularIntensity, reverseIntensity, warpedIntensity
- /// vignetteEffect, startingPosition, scale, freeSlot
- /// samples, sampleDimmer, chromaticAbberationIntensity, chromaticAbberationSamples
- /// streaksIntensity, streaksLength, streaksOrientation, streaksThreshold
- /// downsampleStreak, warpedFlareScaleX, warpedFlareScaleY, freeSlot
- /// Command Buffer
- /// Result RT for the lens flare Screen Space
- /// ShaderID for the original bloom texture
- /// ShaderID for the LensFlareScreenSpaceResultTexture texture
- /// ShaderID for the LensFlareScreenSpaceSpectralLut texture
- /// ShaderID for the LensFlareScreenSpaceStreakTex streak temp texture
- /// ShaderID for the LensFlareScreenSpaceMipLevel parameter
- /// ShaderID for the LensFlareScreenSpaceTintColor color
- /// ShaderID for the LensFlareScreenSpaceParams1
- /// ShaderID for the LensFlareScreenSpaceParams2
- /// ShaderID for the LensFlareScreenSpaceParams3
- /// ShaderID for the LensFlareScreenSpaceParams4
- /// ShaderID for the LensFlareScreenSpaceParams5
- /// Information if we are in debug mode or not
- [Obsolete("Use DoLensFlareScreenSpaceCommon without _Shader IDs parameters. #from(2023.3)")]
- static public void DoLensFlareScreenSpaceCommon(
- Material lensFlareShader,
- Camera cam,
- float actualWidth,
- float actualHeight,
- Color tintColor,
- Texture originalBloomTexture,
- Texture bloomMipTexture,
- Texture spectralLut,
- Texture streakTextureTmp,
- Texture streakTextureTmp2,
- Vector4 parameters1,
- Vector4 parameters2,
- Vector4 parameters3,
- Vector4 parameters4,
- Vector4 parameters5,
- Rendering.CommandBuffer cmd,
- RTHandle result,
- int _LensFlareScreenSpaceBloomMipTexture,
- int _LensFlareScreenSpaceResultTexture,
- int _LensFlareScreenSpaceSpectralLut,
- int _LensFlareScreenSpaceStreakTex,
- int _LensFlareScreenSpaceMipLevel,
- int _LensFlareScreenSpaceTintColor,
- int _LensFlareScreenSpaceParams1,
- int _LensFlareScreenSpaceParams2,
- int _LensFlareScreenSpaceParams3,
- int _LensFlareScreenSpaceParams4,
- int _LensFlareScreenSpaceParams5,
- bool debugView)
- {
- DoLensFlareScreenSpaceCommon(
- lensFlareShader,
- cam,
- actualWidth,
- actualHeight,
- tintColor,
- originalBloomTexture,
- bloomMipTexture,
- spectralLut,
- streakTextureTmp,
- streakTextureTmp2,
- parameters1,
- parameters2,
- parameters3,
- parameters4,
- parameters5,
- cmd,
- result,
- debugView);
- }
-
///
/// Renders the screen space lens flare effect.
///
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/PostProcessing/Shaders/LensFlareCommon.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/PostProcessing/Shaders/LensFlareCommon.hlsl
index 1116c6d15d1..c620775e788 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/PostProcessing/Shaders/LensFlareCommon.hlsl
+++ b/Packages/com.unity.render-pipelines.core/Runtime/PostProcessing/Shaders/LensFlareCommon.hlsl
@@ -49,8 +49,6 @@ SAMPLER(sampler_FlareSunOcclusionTex);
float4 _FlareColorValue;
float4 _FlareData0; // x: localCos0, y: localSin0, zw: PositionOffsetXY
float4 _FlareData1; // x: OcclusionRadius, y: OcclusionSampleCount, z: ScreenPosZ, w: ScreenRatio
- // Fragment Shader:
- // x: LensFlareType, y: ElementIndex
float4 _FlareData2; // xy: ScreenPos, zw: FlareSize
float4 _FlareData3; // x: Allow Offscreen, y: Edge Offset, z: Falloff, w: invSideCount
// For Ring:
@@ -59,6 +57,7 @@ float4 _FlareData4; // x: SDF Roundness, y: Poly Radius, z: PolyParam0, w: PolyP
// For Ring:
// x: noiseAmplitude, y: noiseFrequency, z: noiseSparsity, w: noiseSpeed
float4 _FlareData5; // x: ConstantColor, y: Intensity, z: shapeCutOffSpeed, w: cutoffRadius
+float4 _FlareData6; // x: LensFlareType, y: ElementIndex
TEXTURE2D(_FlareRadialTint);
SAMPLER(sampler_FlareRadialTint);
@@ -86,9 +85,8 @@ float4 _FlareOcclusionIndex;
#endif
// Fragment _FlareData1
-#define _FlareType ((int)_FlareData1.x)
-#define _FlareElementIndex ((int)_FlareData1.y)
-#define _FlareHoopFactor _FlareData1.z
+#define _FlareType ((int)_FlareData6.x)
+#define _FlareElementIndex ((int)_FlareData6.y)
#define _ScreenPos _FlareData2.xy
#define _FlareSize _FlareData2.zw
@@ -184,11 +182,7 @@ float GetOcclusion(float ratio)
{
float depth0 = GetLinearDepthValue(pos);
-#if UNITY_REVERSED_Z
if (depth0 > _ScreenPosZ)
-#else
- if (depth0 < _ScreenPosZ)
-#endif
{
float occlusionValue = 1.0f;
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/CompilerContextData.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/CompilerContextData.cs
index 578cf80a25a..3829ae79dbe 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/CompilerContextData.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/CompilerContextData.cs
@@ -153,10 +153,15 @@ public ref ResourceReaderData ResourceReader(ResourceHandle h, int i)
public NativeList nativeSubPassData; //Tighty packed list of per nrp subpasses
// resources can be added as fragment both as input and output so make sure not to add them twice (return true upon new addition)
- public bool AddToFragmentList(TextureAccess access, int listFirstIndex, int numItems)
+ public bool TryAddToFragmentList(TextureAccess access, int listFirstIndex, int numItems, out string errorMessage)
{
+ errorMessage = null;
#if DEVELOPMENT_BUILD || UNITY_EDITOR
- if (access.textureHandle.handle.type != RenderGraphResourceType.Texture) new Exception("Only textures can be used as a fragment attachment.");
+ if (access.textureHandle.handle.type != RenderGraphResourceType.Texture)
+ {
+ errorMessage = RenderGraph.RenderGraphExceptionMessages.k_NonTextureAsAttachmentError;
+ return false;
+ }
#endif
for (var i = listFirstIndex; i < listFirstIndex + numItems; ++i)
{
@@ -168,7 +173,7 @@ public bool AddToFragmentList(TextureAccess access, int listFirstIndex, int numI
{
//this would mean you're trying to attach say both v1 and v2 of a resource to the same pass as an attachment
//this is not allowed
- throw new Exception("Trying to UseFragment two versions of the same resource");
+ errorMessage = RenderGraph.RenderGraphExceptionMessages.k_OneResourceTwoVersionsError;
}
#endif
return false;
@@ -201,8 +206,9 @@ public bool AddToFragmentList(TextureAccess access, int listFirstIndex, int numI
public string GetResourceVersionedName(ResourceHandle h) => GetResourceName(h) + " V" + h.version;
// resources can be added as fragment both as input and output so make sure not to add them twice (return true upon new addition)
- public bool AddToRandomAccessResourceList(ResourceHandle h, int randomWriteSlotIndex, bool preserveCounterValue, int listFirstIndex, int numItems)
+ public bool TryAddToRandomAccessResourceList(ResourceHandle h, int randomWriteSlotIndex, bool preserveCounterValue, int listFirstIndex, int numItems, out string errorMessage)
{
+ errorMessage = null;
for (var i = listFirstIndex; i < listFirstIndex + numItems; ++i)
{
if (randomAccessResourceData[i].resource.index == h.index && randomAccessResourceData[i].resource.type == h.type)
@@ -211,7 +217,7 @@ public bool AddToRandomAccessResourceList(ResourceHandle h, int randomWriteSlotI
{
//this would mean you're trying to attach say both v1 and v2 of a resource to the same pass as an attachment
//this is not allowed
- throw new Exception("Trying to UseTextureRandomWrite two versions of the same resource");
+ errorMessage = RenderGraph.RenderGraphExceptionMessages.k_UseTextureRandWriteTwoVersionsError;
}
return false;
}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/NativePassCompiler.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/NativePassCompiler.cs
index 12d21e179eb..a56bcef23da 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/NativePassCompiler.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/NativePassCompiler.cs
@@ -88,8 +88,44 @@ public bool Initialize(RenderGraphResourceRegistry resources, List= 0)
+ {
+ int firstGraphPass = contextData.nativePassData[nativePassIndex].firstGraphPass;
+ int graphPassIndex = 0;
+ for (int nativeSubPassIndex = 0; nativeSubPassIndex < contextData.nativePassData[nativePassIndex].numNativeSubPasses; nativeSubPassIndex++)
+ {
+ // Start with the MVPVV compatible flag set so that it can be used for the & operation later
+ SubPassFlags extendedSubPassFlags = SubPassFlags.MultiviewRenderRegionsCompatible;
+ // Iterate over all graph passes that got merged into this sub pass
+ while ((graphPassIndex < contextData.nativePassData[nativePassIndex].numGraphPasses) && (contextData.passData[graphPassIndex + firstGraphPass].nativeSubPassIndex == nativeSubPassIndex))
+ {
+ if (contextData.passData[graphPassIndex + firstGraphPass].extendedFeatureFlags.HasFlag(ExtendedFeatureFlags.TileProperties))
+ {
+ extendedSubPassFlags |= SubPassFlags.TileProperties;
+ }
+ // A native sub pass is MultiviewRenderRegionsCompatible only if all of its graph passes are compatible
+ if (!contextData.passData[graphPassIndex + firstGraphPass].extendedFeatureFlags.HasFlag(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible))
+ {
+ extendedSubPassFlags &= ~SubPassFlags.MultiviewRenderRegionsCompatible;
+ }
+ graphPassIndex++;
+ }
+ contextData.nativeSubPassData.ElementAt(firstNativeSubPass + nativeSubPassIndex).flags |= extendedSubPassFlags;
+ }
+ }
+ }
+ }
+
public void Compile(RenderGraphResourceRegistry resources)
{
+ ValidatePasses();
+
SetupContextData(resources);
BuildGraph();
@@ -98,6 +134,8 @@ public void Compile(RenderGraphResourceRegistry resources)
TryMergeNativePasses();
+ HandleExtendedFeatureFlags();
+
FindResourceUsageRanges();
DetectMemoryLessResources();
@@ -131,6 +169,26 @@ internal enum NativeCompilerProfileId
NRPRGComp_ExecuteDestroyResources,
}
+ [Conditional("DEVELOPMENT_BUILD"), Conditional("UNITY_EDITOR")]
+ void ValidatePasses()
+ {
+ if (RenderGraph.enableValidityChecks)
+ {
+ int tilePropertiesPassIndex = -1;
+ for (int passId = 0; passId < graph.m_RenderPasses.Count; passId++)
+ {
+ if (graph.m_RenderPasses[passId].extendedFeatureFlags.HasFlag(ExtendedFeatureFlags.TileProperties))
+ {
+ if (tilePropertiesPassIndex > -1)
+ {
+ throw new Exception($"ExtendedFeatureFlags.TileProperties can only be set once per render graph (render graph {graph.debugName}, pass {graph.m_RenderPasses[passId].name}), previously set at (pass {graph.m_RenderPasses[tilePropertiesPassIndex].name}).");
+ }
+ tilePropertiesPassIndex = passId;
+ }
+ }
+ }
+ }
+
void SetupContextData(RenderGraphResourceRegistry resources)
{
using (new ProfilingScope(ProfilingSampler.Get(NativeCompilerProfileId.NRPRGComp_SetupContextData)))
@@ -139,6 +197,121 @@ void SetupContextData(RenderGraphResourceRegistry resources)
}
}
+ // Returns true if the RasterFragmentList is successfully set up
+ bool TrySetupRasterFragmentList(ref PassData ctxPass, ref RenderGraphPass inputPass, out string errorMessage)
+ {
+ errorMessage = null;
+ var ctx = contextData;
+ // Grab offset in context fragment list to begin building the fragment list
+ ctxPass.firstFragment = ctx.fragmentData.Length;
+
+ // Depth attachment is always at index 0
+ if (inputPass.depthAccess.textureHandle.handle.IsValid())
+ {
+ ctxPass.fragmentInfoHasDepth = true;
+
+ if (ctx.TryAddToFragmentList(inputPass.depthAccess, ctxPass.firstFragment, ctxPass.numFragments, out errorMessage))
+ {
+ ctxPass.TryAddFragment(inputPass.depthAccess.textureHandle.handle, ctx, out errorMessage);
+ }
+
+ if (errorMessage != null)
+ {
+ errorMessage =
+ $"when trying to add depth attachment of type {inputPass.depthAccess.textureHandle.handle.type} at index {inputPass.depthAccess.textureHandle.handle.index} - {errorMessage}";
+ return false;
+ }
+ }
+
+ for (var ci = 0; ci < inputPass.colorBufferMaxIndex + 1; ++ci)
+ {
+ // Skip unused color slots
+ if (!inputPass.colorBufferAccess[ci].textureHandle.handle.IsValid()) continue;
+
+ if (ctx.TryAddToFragmentList(inputPass.colorBufferAccess[ci], ctxPass.firstFragment, ctxPass.numFragments, out errorMessage))
+ {
+ ctxPass.TryAddFragment(inputPass.colorBufferAccess[ci].textureHandle.handle, ctx, out errorMessage);
+ }
+
+ if (errorMessage != null)
+ {
+ errorMessage =
+ $"when trying to add render attachment of type {inputPass.colorBufferAccess[ci].textureHandle.handle.type} at index {inputPass.colorBufferAccess[ci].textureHandle.handle.index} - {errorMessage}";
+ return false;
+ }
+ }
+
+ // shading rate
+ if (inputPass.hasShadingRateImage &&
+ inputPass.shadingRateAccess.textureHandle.handle.IsValid())
+ {
+ ctxPass.shadingRateImageIndex = ctx.fragmentData.Length;
+ ctx.TryAddToFragmentList(inputPass.shadingRateAccess, ctxPass.shadingRateImageIndex, 0, out errorMessage);
+
+ if (errorMessage != null)
+ {
+ errorMessage = $"when trying to add VRS attachment of type {inputPass.shadingRateAccess.textureHandle.handle.type} at index {inputPass.shadingRateAccess.textureHandle.handle.index} - {errorMessage}";
+ return false;
+ }
+ }
+
+ // Grab offset in context fragment list to begin building the fragment input list
+ ctxPass.firstFragmentInput = ctx.fragmentData.Length;
+
+ for (var ci = 0; ci < inputPass.fragmentInputMaxIndex + 1; ++ci)
+ {
+ // Skip unused fragment input slots
+ if (!inputPass.fragmentInputAccess[ci].textureHandle.IsValid()) continue;
+
+ var resource = inputPass.fragmentInputAccess[ci].textureHandle;
+ if (ctx.TryAddToFragmentList(inputPass.fragmentInputAccess[ci], ctxPass.firstFragmentInput,
+ ctxPass.numFragmentInputs, out errorMessage))
+ {
+ ctxPass.TryAddFragmentInput(inputPass.fragmentInputAccess[ci].textureHandle.handle, ctx, out errorMessage);
+ }
+
+ if (errorMessage != null)
+ {
+ errorMessage =
+ $"when trying to add input attachment of type {inputPass.fragmentInputAccess[ci].textureHandle.handle.type} at index {inputPass.fragmentInputAccess[ci].textureHandle.handle.index} - {errorMessage}";
+ return false;
+ }
+ }
+
+ // Grab offset in context random write list to begin building the per pass random write lists
+ ctxPass.firstRandomAccessResource = ctx.randomAccessResourceData.Length;
+
+ for (var ci = 0; ci < inputPass.randomAccessResourceMaxIndex + 1; ++ci)
+ {
+ ref var uav = ref inputPass.randomAccessResource[ci];
+
+ // Skip unused random write slots
+ if (!uav.h.IsValid()) continue;
+
+ if (ctx.TryAddToRandomAccessResourceList(uav.h, ci, uav.preserveCounterValue,
+ ctxPass.firstRandomAccessResource, ctxPass.numRandomAccessResources, out errorMessage))
+ {
+ ctxPass.AddRandomAccessResource();
+ }
+
+ if (errorMessage != null)
+ {
+ errorMessage = $"when trying to add random access attachment of type {uav.h.type} at index {uav.h.index} - {errorMessage}";
+ return false;
+ }
+ }
+
+ // This is suspicious, there are frame buffer fetch inputs but nothing is output. We don't allow this for now.
+ // In theory you could fb-fetch inputs and write something to a uav and output nothing? This needs to be investigated
+ // so don't allow it for now.
+ if (ctxPass.numFragments == 0)
+ {
+ Debug.Assert(ctxPass.numFragmentInputs == 0);
+ }
+
+ return true;
+ }
+
void BuildGraph()
{
var ctx = contextData;
@@ -158,9 +331,7 @@ void BuildGraph()
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (inputPass.type == RenderGraphPassType.Legacy)
{
- throw new Exception("Pass '" + inputPass.name + "' is using the legacy rendergraph API." +
- " You cannot use legacy passes with the Native Render Pass Compiler." +
- " The APIs that are compatible with the Native Render Pass Compiler are AddUnsafePass, AddComputePass and AddRasterRenderPass.");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.UsingLegacyRenderGraph(inputPass.name));
}
#endif
@@ -181,76 +352,9 @@ void BuildGraph()
// will also be in the pass read/write lists accordingly
if (ctxPass.type == RenderGraphPassType.Raster)
{
- // Grab offset in context fragment list to begin building the fragment list
- ctxPass.firstFragment = ctx.fragmentData.Length;
-
- // Depth attachment is always at index 0
- if (inputPass.depthAccess.textureHandle.handle.IsValid())
- {
- ctxPass.fragmentInfoHasDepth = true;
-
- if (ctx.AddToFragmentList(inputPass.depthAccess, ctxPass.firstFragment, ctxPass.numFragments))
- {
- ctxPass.AddFragment(inputPass.depthAccess.textureHandle.handle, ctx);
- }
- }
-
- for (var ci = 0; ci < inputPass.colorBufferMaxIndex + 1; ++ci)
- {
- // Skip unused color slots
- if (!inputPass.colorBufferAccess[ci].textureHandle.handle.IsValid()) continue;
-
- if (ctx.AddToFragmentList(inputPass.colorBufferAccess[ci], ctxPass.firstFragment, ctxPass.numFragments))
- {
- ctxPass.AddFragment(inputPass.colorBufferAccess[ci].textureHandle.handle, ctx);
- }
- }
-
- // shading rate
- if (inputPass.hasShadingRateImage &&
- inputPass.shadingRateAccess.textureHandle.handle.IsValid())
- {
- ctxPass.shadingRateImageIndex = ctx.fragmentData.Length;
- ctx.AddToFragmentList(inputPass.shadingRateAccess, ctxPass.shadingRateImageIndex, 0);
- }
-
- // Grab offset in context fragment list to begin building the fragment input list
- ctxPass.firstFragmentInput = ctx.fragmentData.Length;
-
- for (var ci = 0; ci < inputPass.fragmentInputMaxIndex + 1; ++ci)
- {
- // Skip unused fragment input slots
- if (!inputPass.fragmentInputAccess[ci].textureHandle.IsValid()) continue;
-
- var resource = inputPass.fragmentInputAccess[ci].textureHandle;
- if (ctx.AddToFragmentList(inputPass.fragmentInputAccess[ci], ctxPass.firstFragmentInput, ctxPass.numFragmentInputs))
- {
- ctxPass.AddFragmentInput(inputPass.fragmentInputAccess[ci].textureHandle.handle, ctx);
- }
- }
-
- // Grab offset in context random write list to begin building the per pass random write lists
- ctxPass.firstRandomAccessResource = ctx.randomAccessResourceData.Length;
-
- for (var ci = 0; ci < passes[passId].randomAccessResourceMaxIndex + 1; ++ci)
- {
- ref var uav = ref passes[passId].randomAccessResource[ci];
-
- // Skip unused random write slots
- if (!uav.h.IsValid()) continue;
-
- if (ctx.AddToRandomAccessResourceList(uav.h, ci, uav.preserveCounterValue, ctxPass.firstRandomAccessResource, ctxPass.numRandomAccessResources))
- {
- ctxPass.AddRandomAccessResource();
- }
- }
-
- // This is suspicious, there are frame buffer fetch inputs but nothing is output. We don't allow this for now.
- // In theory you could fb-fetch inputs and write something to a uav and output nothing? This needs to be investigated
- // so don't allow it for now.
- if (ctxPass.numFragments == 0)
+ if (!TrySetupRasterFragmentList(ref ctxPass, ref inputPass, out var errorMessage))
{
- Debug.Assert(ctxPass.numFragmentInputs == 0);
+ throw new Exception($"In pass '{inputPass.name}', {errorMessage}");
}
}
@@ -269,7 +373,7 @@ void BuildGraph()
ref var resData = ref ctx.UnversionedResourceData(resource);
if (resData.isImported)
{
- if (ctxPass.hasSideEffects == false)
+ if (!ctxPass.hasSideEffects)
{
ctxPass.hasSideEffects = true;
toVisitPassIds.Push(passId);
@@ -722,7 +826,11 @@ void DetectMemoryLessResources()
internal static bool IsSameNativeSubPass(ref SubPassDescriptor a, ref SubPassDescriptor b)
{
- if (a.flags != b.flags
+ const SubPassFlags k_SubPassMergeIgnoreMask = ~(SubPassFlags.TileProperties | SubPassFlags.MultiviewRenderRegionsCompatible);
+ // Mask out the flags we can ignore.
+ SubPassFlags aflags = a.flags & k_SubPassMergeIgnoreMask;
+ SubPassFlags bflags = b.flags & k_SubPassMergeIgnoreMask;
+ if (aflags != bflags
|| a.colorOutputs.Length != b.colorOutputs.Length
|| a.inputs.Length != b.inputs.Length)
{
@@ -1166,9 +1274,9 @@ void DetermineLoadStoreActions(ref NativePassData nativePass)
#if UNITY_EDITOR || DEVELOPMENT_BUILD
// Ensure load/store actions are actually valid for memory less
if (loadAction == RenderBufferLoadAction.Load)
- throw new Exception("Resource was marked as memoryless but is trying to load.");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_LoadingMemorylessResource);
if (storeAction != RenderBufferStoreAction.DontCare)
- throw new Exception("Resource was marked as memoryless but is trying to store or resolve.");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_ResolvignMemorylessResource);
#endif
}
@@ -1192,10 +1300,10 @@ private void ValidateNativePass(in NativePassData nativePass, int width, int hei
if (RenderGraph.enableValidityChecks)
{
if (nativePass.attachments.size == 0 || nativePass.numNativeSubPasses == 0)
- throw new Exception("Empty render pass");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_RenderPassIsEmpty);
if (width == 0 || height == 0 || depth == 0 || samples == 0 || nativePass.numNativeSubPasses == 0 || attachmentCount == 0)
- throw new Exception("Invalid render pass properties. One or more properties are zero.");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_RenderPassHasInvalidProperties);
}
}
@@ -1211,13 +1319,13 @@ private void ValidateAttachment(in RenderTargetInfo attRenderTargetInfo, RenderG
if (attRenderTargetInfo.width != tileSize.x || attRenderTargetInfo.height != tileSize.y || attRenderTargetInfo.msaaSamples != 1)
{
- throw new Exception("Low level rendergraph error: Shading rate image attachment in renderpass does not match!");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_ShadingRateImageAttachmentDoesNotMatch);
}
}
else
{
if (attRenderTargetInfo.width != nativePassWidth || attRenderTargetInfo.height != nativePassHeight || attRenderTargetInfo.msaaSamples != nativePassMSAASamples)
- throw new Exception("Low level rendergraph error: Attachments in renderpass do not match!");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_AttachmentsDoNotMatch);
}
}
}
@@ -1428,7 +1536,7 @@ private void ExecuteSetRenderTargets(RenderGraphPass pass, InternalRenderGraphCo
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (!colorBufferAccess[i].textureHandle.IsValid())
- throw new InvalidOperationException("MRT setup is invalid. Some indices are not used.");
+ throw new InvalidOperationException($"In pass {pass.name}, when trying to use {colorBufferAccess[i].textureHandle.handle.type} attachment at index {colorBufferAccess[i].textureHandle.handle.index} - " + RenderGraph.RenderGraphExceptionMessages.k_InvalidMRTSetup);
#endif
mrtArray[i] = resources.GetTexture(colorBufferAccess[i].textureHandle);
}
@@ -1439,7 +1547,7 @@ private void ExecuteSetRenderTargets(RenderGraphPass pass, InternalRenderGraphCo
}
else
{
- throw new InvalidOperationException("Setting MRTs without a depth buffer is not supported.");
+ throw new InvalidOperationException($"In pass {pass.name} - " + RenderGraph.RenderGraphExceptionMessages.k_NoDepthBufferMRT);
}
}
else
@@ -1463,7 +1571,7 @@ private void ExecuteSetRenderTargets(RenderGraphPass pass, InternalRenderGraphCo
CoreUtils.SetRenderTarget(rgContext.cmd, resources.GetTexture(pass.colorBufferAccess[0].textureHandle));
}
else
- throw new InvalidOperationException("Neither Depth nor color render targets are correctly setup at pass " + pass.name + ".");
+ throw new InvalidOperationException($"In pass {pass.name} - " + RenderGraph.RenderGraphExceptionMessages.k_InvalidDepthAndColorTargets);
}
}
}
@@ -1491,7 +1599,8 @@ internal unsafe void ExecuteSetRandomWriteTarget(in CommandBuffer cmd, RenderGra
}
else
{
- throw new Exception($"Invalid resource type {resource.type}, expected texture or buffer");
+ var name = resources.GetRenderGraphResourceName(resource);
+ throw new Exception($"When trying to use resource '{name}' of type {resource.type} - " + RenderGraph.RenderGraphExceptionMessages.k_InvalidResourceType);
}
}
@@ -1502,8 +1611,8 @@ internal void ExecuteRenderGraphPass(ref InternalRenderGraphContext rgContext, R
if (!pass.HasRenderFunc())
{
- throw new InvalidOperationException(
- string.Format("RenderPass {0} was not provided with an execute function.", pass.name));
+ throw new InvalidOperationException($"In pass {pass.name} - " +
+ RenderGraph.RenderGraphExceptionMessages.k_NoRenderFunction);
}
using (new ProfilingScope(rgContext.cmd, pass.customSampler))
@@ -1577,8 +1686,7 @@ public void ExecuteGraph(InternalRenderGraphContext rgContext, RenderGraphResour
{
if (!inRenderPass)
{
- throw new Exception(
- "Compiler error: Pass is marked as beginning a native sub pass but no pass is currently active.");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_BeginNoActivePass);
}
rgContext.cmd.NextSubPass();
@@ -1630,8 +1738,7 @@ void EndRenderGraphPass(ref InternalRenderGraphContext rgContext, ref PassData p
{
if (!inRenderPass)
{
- throw new Exception(
- "Compiler error: Generated a subpass pass but no pass is currently active.");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_NoActivePassForSubpass);
}
if (nativePass.hasFoveatedRasterization)
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/PassesData.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/PassesData.cs
index e278ec334a1..84232e905aa 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/PassesData.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/Compiler/PassesData.cs
@@ -110,6 +110,7 @@ internal struct PassData
public int passId; // Index of self in the passData list, can we calculate this somehow in c#? would use offsetof in c++
public RenderGraphPassType type;
public bool hasFoveatedRasterization;
+ public ExtendedFeatureFlags extendedFeatureFlags;
public int tag; // Arbitrary per node int used by various graph analysis tools
public ShadingRateFragmentSize shadingRateFragmentSize;
@@ -163,6 +164,7 @@ public PassData(in RenderGraphPass pass, int passIndex)
asyncCompute = pass.enableAsyncCompute;
hasSideEffects = !pass.allowPassCulling;
hasFoveatedRasterization = pass.enableFoveatedRasterization;
+ extendedFeatureFlags = pass.extendedFeatureFlags;
mergeState = PassMergeState.None;
nativePassIndex = -1;
nativeSubPassIndex = -1;
@@ -211,7 +213,7 @@ public void ResetAndInitialize(in RenderGraphPass pass, int passIndex)
asyncCompute = pass.enableAsyncCompute;
hasSideEffects = !pass.allowPassCulling;
hasFoveatedRasterization = pass.enableFoveatedRasterization;
-
+ extendedFeatureFlags = pass.extendedFeatureFlags;
mergeState = PassMergeState.None;
nativePassIndex = -1;
nativeSubPassIndex = -1;
@@ -284,25 +286,51 @@ public ReadOnlySpan RandomWriteTextures(CompilerContextData
public readonly ReadOnlySpan LastUsedResources(CompilerContextData ctx)
=> ctx.destroyData.MakeReadOnlySpan(firstDestroy, numDestroyed);
- private void SetupAndValidateFragmentInfo(ResourceHandle h, CompilerContextData ctx)
+ private bool TrySetupAndValidateFragmentInfo(ResourceHandle h, CompilerContextData ctx, out string errorMessage)
{
+ errorMessage = null;
+
#if DEVELOPMENT_BUILD || UNITY_EDITOR
- if (h.type != RenderGraphResourceType.Texture) new Exception("Only textures can be used as a fragment attachment.");
+ if (h.type != RenderGraphResourceType.Texture)
+ {
+ errorMessage = RenderGraph.RenderGraphExceptionMessages.k_NonTextureAsAttachmentError;
+ return false;
+ }
#endif
ref readonly var resInfo = ref ctx.UnversionedResourceData(h);
#if DEVELOPMENT_BUILD || UNITY_EDITOR
- if (resInfo.width == 0 || resInfo.height == 0 || resInfo.msaaSamples == 0) throw new Exception("GetRenderTargetInfo returned invalid results.");
+ if (resInfo.width == 0 || resInfo.height == 0 || resInfo.msaaSamples == 0)
+ {
+ errorMessage = RenderGraph.RenderGraphExceptionMessages.k_InvalidGetRenderTargetInfoResultsError;
+ return false;
+ }
#endif
- if (fragmentInfoValid)
+ if (RenderGraph.enableValidityChecks && fragmentInfoValid)
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (fragmentInfoWidth != resInfo.width ||
fragmentInfoHeight != resInfo.height ||
- fragmentInfoVolumeDepth != resInfo.volumeDepth ||
- fragmentInfoSamples != resInfo.msaaSamples)
- throw new Exception("Mismatch in Fragment dimensions");
+ fragmentInfoVolumeDepth != resInfo.volumeDepth)
+ {
+ var name = resInfo.GetName(ctx, h);
+ if (string.IsNullOrEmpty(name))
+ name = "unnamed fragment";
+
+ errorMessage = RenderGraph.RenderGraphExceptionMessages.MismatchInDimensions(name, fragmentInfoWidth, fragmentInfoHeight, fragmentInfoVolumeDepth, resInfo);
+ return false;
+ }
+
+ if (fragmentInfoSamples != resInfo.msaaSamples)
+ {
+ var name = resInfo.GetName(ctx, h);
+ if (string.IsNullOrEmpty(name))
+ name = "unnamed fragment";
+
+ errorMessage = RenderGraph.RenderGraphExceptionMessages.MismatchInMSAASamlpes(name, fragmentInfoSamples, resInfo.msaaSamples);
+ return false;
+ }
#endif
}
else
@@ -313,20 +341,21 @@ private void SetupAndValidateFragmentInfo(ResourceHandle h, CompilerContextData
fragmentInfoVolumeDepth = resInfo.volumeDepth;
fragmentInfoValid = true;
}
+ return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void AddFragment(ResourceHandle h, CompilerContextData ctx)
+ internal void TryAddFragment(ResourceHandle h, CompilerContextData ctx, out string errorMessage)
{
- SetupAndValidateFragmentInfo(h, ctx);
- numFragments++;
+ if (TrySetupAndValidateFragmentInfo(h, ctx, out errorMessage))
+ numFragments++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
- internal void AddFragmentInput(ResourceHandle h, CompilerContextData ctx)
+ internal void TryAddFragmentInput(ResourceHandle h, CompilerContextData ctx, out string errorMessage)
{
- SetupAndValidateFragmentInfo(h, ctx);
- numFragmentInputs++;
+ if (TrySetupAndValidateFragmentInfo(h, ctx, out errorMessage))
+ numFragmentInputs++;
}
internal void AddRandomAccessResource()
@@ -355,7 +384,7 @@ internal void AddFirstUse(ResourceHandle h, CompilerContextData ctx)
firstCreate = addedIndex;
}
- Debug.Assert(addedIndex == firstCreate + numCreated, "you can only incrementally set-up the Creation lists for all passes, AddCreation is called in an arbitrary non-incremental way");
+ Debug.Assert(addedIndex == firstCreate + numCreated, RenderGraph.RenderGraphExceptionMessages.k_NonIncrementalCreationCall);
numCreated++;
}
@@ -379,7 +408,7 @@ internal void AddLastUse(ResourceHandle h, CompilerContextData ctx)
firstDestroy = addedIndex;
}
- Debug.Assert(addedIndex == firstDestroy + numDestroyed, "you can only incrementally set-up the Destruction lists for all passes, AddCreation is called in an arbitrary non-incremental way");
+ Debug.Assert(addedIndex == firstDestroy + numDestroyed, RenderGraph.RenderGraphExceptionMessages.k_NonIncrementalDestructionCall);
numDestroyed++;
}
@@ -534,6 +563,7 @@ internal enum PassBreakReason
FRStateMismatch, // One pass is using foveated rendering and the other not
DifferentShadingRateImages, // The next pass uses a different shading rate image (and we only allow one in a whole NRP)
DifferentShadingRateStates, // The next pass uses different shading rate states (and we only allow one set in a whole NRP)
+ ExtendedFeatureFlagsIncompatible, // Handles the case where flags added via SetExtendedFeatureFlags are not compatible
PassMergingDisabled, // Wasn't merged because pass merging is disabled
Merged, // I actually got merged
@@ -569,6 +599,7 @@ public PassBreakAudit(PassBreakReason reason, int breakPass)
"The next pass uses a different foveated rendering state",
"The next pass uses a different shading rate image",
"The next pass uses a different shading rate rendering state",
+ "Extended feature flags are incompatible",
"Pass merging is disabled so this pass was not merged",
"The next pass got merged into this pass.",
};
@@ -601,6 +632,7 @@ internal struct NativePassData
public bool hasFoveatedRasterization;
public bool hasShadingRateImage => shadingRateImageIndex >= 0;
public bool hasShadingRateStates;
+ public ExtendedFeatureFlags extendedFeatureFlags;
public ShadingRateFragmentSize shadingRateFragmentSize;
public ShadingRateCombiner primitiveShadingRateCombiner;
@@ -623,6 +655,7 @@ public NativePassData(ref PassData pass, CompilerContextData ctx)
samples = pass.fragmentInfoSamples;
hasDepth = pass.fragmentInfoHasDepth;
hasFoveatedRasterization = pass.hasFoveatedRasterization;
+ extendedFeatureFlags = pass.extendedFeatureFlags;
loadAudit = new FixedAttachmentArray();
storeAudit = new FixedAttachmentArray();
@@ -663,7 +696,7 @@ public SubPassFlags GetSubPassFlagForMerging()
// We should not be calling this method if native pass doesn't have depth.
if (hasDepth == false)
{
- throw new Exception("SubPassFlag for merging can not be determined if native pass doesn't have a depth attachment");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_CannotDetermineSubPassFlagNoDepth);
}
// Only do this for mobile using Vulkan.
@@ -733,6 +766,12 @@ public readonly void GetGraphPassNames(CompilerContextData ctx, DynamicArray newAttach.resource.version)
- throw new Exception("Adding an older version while a higher version is already registered with the pass.");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_AddingOlderAttachmentVersion);
#endif
existingAttach = new PassFragmentData(
new ResourceHandle(existingAttach.resource, newAttach.resource.version),
@@ -1291,7 +1335,7 @@ public static PassBreakAudit TryMerge(CompilerContextData contextData, int activ
#if DEVELOPMENT_BUILD || UNITY_EDITOR
if (existingAttach.resource.version > newAttach.resource.version)
- throw new Exception("Adding an older version while a higher version is already registered with the pass.");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_AddingOlderAttachmentVersion);
#endif
existingAttach = new PassFragmentData(
@@ -1330,7 +1374,7 @@ public static void SetPassStatesForNativePass(CompilerContextData contextData, i
{
var indexPass = nativePass.firstGraphPass + i;
- // This pass was culled and should not be considere
+ // This pass was culled and should not be considered
if (contextData.passData.ElementAt(indexPass).culled)
{
contextData.passData.ElementAt(indexPass).mergeState = PassMergeState.None;
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/IRenderGraphBuilder.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/IRenderGraphBuilder.cs
index 20c694adfac..5b53db80e89 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/IRenderGraphBuilder.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/IRenderGraphBuilder.cs
@@ -374,6 +374,12 @@ void SetInputAttachment(TextureHandle tex, int index, AccessFlags flags = Access
/// Shading rate combiner to set.
void SetShadingRateCombiner(ShadingRateCombinerStage stage, ShadingRateCombiner combiner);
+ ///
+ /// Enables the configuration of extended pass properties that may allow platform-specific optimizations.
+ ///
+ /// Specifies additional pass properties that may enable optimizations on certain platforms.
+ public void SetExtendedFeatureFlags(ExtendedFeatureFlags extendedFeatureFlags);
+
///
/// Specify the render function to use for this pass.
/// A call to this is mandatory for the pass to be valid.
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.ExceptionMessages.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.ExceptionMessages.cs
index ee5273810c5..dc8e798608e 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.ExceptionMessages.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.ExceptionMessages.cs
@@ -1,5 +1,7 @@
using System.Collections.Generic;
using System.Diagnostics;
+using UnityEngine.Experimental.Rendering;
+using UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler;
namespace UnityEngine.Rendering.RenderGraphModule
{
@@ -13,15 +15,153 @@ internal static class RenderGraphExceptionMessages
static readonly Dictionary m_RenderGraphStateMessages = new()
{
- { RenderGraphState.RecordingPass, "This API cannot be called when Render Graph records a pass, please call it within SetRenderFunc() or outside of AddUnsafePass()/AddComputePass()/AddRasterRenderPass()." },
- { RenderGraphState.RecordingGraph, "This API cannot be called during the Render Graph high-level recording step, please call it within AddUnsafePass()/AddComputePass()/AddRasterRenderPass() or outside of RecordRenderGraph()." },
- { RenderGraphState.RecordingPass | RenderGraphState.Executing, "This API cannot be called when Render Graph records a pass or executes it, please call it outside of AddUnsafePass()/AddComputePass()/AddRasterRenderPass()." },
- { RenderGraphState.Executing, "This API cannot be called during the Render Graph execution, please call it outside of SetRenderFunc()." },
- { RenderGraphState.Active, "This API cannot be called when Render Graph is active, please call it outside of RecordRenderGraph()." }
+ {
+ RenderGraphState.RecordingPass,
+ "This API cannot be called when Render Graph records a pass. Call the API within SetRenderFunc() or outside of AddUnsafePass()/AddComputePass()/AddRasterRenderPass()."
+ },
+ {
+ RenderGraphState.RecordingGraph,
+ "This API cannot be called during the Render Graph high-level recording step. Call the API within AddUnsafePass()/AddComputePass()/AddRasterRenderPass() or outside of RecordRenderGraph()."
+ },
+ {
+ RenderGraphState.RecordingPass | RenderGraphState.Executing,
+ "This API cannot be called when Render Graph records a pass or executes it. Call the API outside of AddUnsafePass()/AddComputePass()/AddRasterRenderPass()."
+ },
+ {
+ RenderGraphState.Executing,
+ "This API cannot be called during the Render Graph execution. Call the API outside of SetRenderFunc()."
+ },
+ {
+ RenderGraphState.Active,
+ "This API cannot be called when Render Graph is active. Call the API outside of RecordRenderGraph()."
+ }
};
+ // General Errors
const string k_ErrorDefaultMessage = "Invalid render graph state, impossible to log the exception.";
+ internal const string k_NonTextureAsAttachmentError = "Only textures can be used as a fragment attachment.";
+
+ // Compiler Context Data
+ internal const string k_OneResourceTwoVersionsError =
+ "A pass is using SetAttachment or UseTexture on two versions of the same resource. Make sure you only access the latest version.";
+
+ internal const string k_UseTextureRandWriteTwoVersionsError =
+ "A pass is using UseTextureRandomWrite on two versions of the same resource. Make sure you only access the latest version.";
+
+ // Passes Data
+ internal const string k_InvalidGetRenderTargetInfoResultsError =
+ "GetRenderTargetInfo returned invalid results. Check that the width, height, and number of MSAA samples is not 0.";
+
+ internal const string k_CannotDetermineSubPassFlagNoDepth =
+ "SubPassFlag for merging cannot be determined if native pass doesn't have a depth attachment. Make sure your pass has a depth attachment.";
+
+ internal const string k_AddingOlderAttachmentVersion = "The pass adds an older version while a higher version is already registered with the pass. Make sure you only access the latest version.";
+
+ // Users shouldn't be seeing these, they are a sort of catch for internal RG mistakes.
+ internal const string k_NonIncrementalCreationCall =
+ "Something went wrong when compiling the graph. The Creation lists must be set-up incrementally for all passes, but AddFirstUse is called in an arbitrary non-incremental way.";
+
+ internal const string k_NonIncrementalDestructionCall =
+ "Something went wrong when compiling the graph. The Destruction lists must be set-up incrementally for all passes, AddLastUse is called in an arbitrary non-incremental way.";
+
+ internal static string MismatchInDimensions(string name, int fragWidth, int fragHeight, int fragVolumeDepth,
+ ResourceUnversionedData resInfo)
+ =>
+ $"Mismatch in fragment dimensions when using resource '{name}'. Expected {fragWidth} x {fragHeight} x {fragVolumeDepth} " +
+ $"but got {resInfo.width} x {resInfo.height} x {resInfo.volumeDepth} instead.";
+
+ internal static string MismatchInMSAASamlpes(string name, int expectedSamples, int actualSamples)
+ {
+ var expectedSamplesString = expectedSamples == 1 ? "None" : expectedSamples.ToString();
+ var actualSamplesString = actualSamples == 1 ? "None" : actualSamples.ToString();
+ return $"Mismatch in number of MSAA samples when using resource '{name}'. Expected {expectedSamplesString} but got {actualSamplesString} instead.";
+ }
+
+ // RenderGraphBuilders
+ internal const string k_UndisposedBuilderPreviousPass =
+ "Finish building the previous pass first by disposing of the pass builder object before adding a new pass. You can manually dispose of the builder with 'builder.Dispose()'.";
+
+ internal const string k_WriteToVersionedResource =
+ "The pass writes to a versioned resource handle. You can only write to unversioned resource handles to avoid branches in the resource history.";
+
+ internal const string k_WriteToResourceTwice = "The pass writes to a resource twice. You can only write the same resource once within a pass.";
+
+ internal const string k_TextureAlreadyBeingUsedThroughSetAttachment =
+ "UseTexture is called on a texture that is already used through SetRenderAttachment. Check your code and make sure the texture is only used once.";
+
+ internal const string k_SetRenderAttachmentTextureAlreadyUsed =
+ "SetRenderAttachment is called on a texture that is already used through UseTexture/SetRenderAttachment. Check your code and make sure the texture is only used once.";
+
+ internal const string k_SetRenderAttachmentOnDepthTexture =
+ "SetRenderAttachment is called on a texture that has a depth format. Use a texture with a color format instead, or call SetRenderDepthAttachment.";
+
+ internal const string k_SetRenderAttachmentOnGlobalTexture =
+ "SetRenderAttachment is called on a texture that is currently bound to a global texture slot. Shaders might be using the texture using samplers. Make sure textures are not set as globals when using them as fragment attachments.";
+
+ internal const string k_InvalidResource = "Using an invalid resource. Invalid resources can be resources leftover from a previous execution.";
+
+ internal const string k_ReadWriteTransient =
+ "This pass is reading or writing a transient resource. Transient resources are always assumed to be both read and written using 'AccessFlags.ReadWrite'.";
+
+ internal static string NoGlobalTextureAtPropertyID(int propertyId) =>
+ $"This pass is trying to read the global texture property {propertyId} but no previous pass in the graph bound a value to this global.";
+
+ internal static string UseDepthWithColorFormat(GraphicsFormat colorFormat) =>
+ $"SetRenderAttachmentDepth is called on a texture that has a color format {colorFormat}. Use a texture with a depth format instead, or call SetRenderAttachment.";
+
+ internal static string UseTransientTextureInWrongPass(int transientIndex) =>
+ $"This pass is using a transient resource from a different pass (pass index {transientIndex}). A transient resource should only be used in a single pass.";
+
+ // RenderGraphPass
+ internal const string k_MoreThanOneResourceForMRTIndex =
+ "You can only bind a single texture to a single index in a multiple render texture (MRT). Verify your indexes are correct.";
+
+ internal const string k_MoreThanOneTextureForFragInputIndex =
+ "You can only bind a single texture to a fragment input index. Verify your indexes are correct.";
+
+ internal const string k_MoreThanOneTextureRandomWriteInputIndex =
+ "You can only bind a single texture to a random write input index. Verify your indexes are correct.";
+
+ internal const string k_MultipleDepthTextures = "You can only set a single depth texture per pass.";
+
+ //NativePassCompiler
+ internal const string k_LoadingMemorylessResource = "This pass is loading a resource marked as memoryless.";
+
+ internal const string k_ResolvignMemorylessResource =
+ "This pass is storing or resolving a resource marked as memoryless";
+
+ internal const string k_RenderPassIsEmpty = "Empty render pass";
+
+ internal const string k_RenderPassHasInvalidProperties =
+ "Invalid render pass properties. One or more properties are zero.";
+
+ internal const string k_ShadingRateImageAttachmentDoesNotMatch =
+ "Low level rendergraph error: Shading rate image attachment in renderpass does not match.";
+
+ internal const string k_AttachmentsDoNotMatch =
+ "Low level rendergraph error: Attachments in renderpass do not match.";
+
+ internal const string k_InvalidMRTSetup = "Multiple render texture (MRT) setup is invalid. Some indices are not used.";
+
+ internal const string k_NoDepthBufferMRT = "Setting multiple render textures (MRTs) without a depth buffer is not supported.";
+
+ internal const string k_InvalidDepthAndColorTargets = "Neither depth nor color render targets are correctly set up.";
+
+ internal const string k_InvalidResourceType = "Invalid resource type, expected texture or buffer";
+
+ internal const string k_NoRenderFunction = "RenderPass was not provided with an execute function.";
+
+ internal const string k_BeginNoActivePass =
+ "Compiler error: Pass is marked as beginning a native sub pass but no pass is currently active.";
+
+ internal const string k_NoActivePassForSubpass =
+ "Compiler error: Generated a subpass pass but no pass is currently active.";
+ internal static string UsingLegacyRenderGraph(string passName) =>
+ "Pass '" + passName + "' is using the legacy rendergraph API." +
+ " You cannot use legacy passes with the Native Render Pass Compiler." +
+ " The APIs that are compatible with the Native Render Pass Compiler are AddUnsafePass, AddComputePass and AddRasterRenderPass.";
+
internal static string GetExceptionMessage(RenderGraphState state)
{
string caller = GetHigherCaller();
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs
index 18ae21bbe9e..e5dda05452b 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraph.cs
@@ -48,6 +48,20 @@ public enum AccessFlags
ReadWrite = Read | Write
}
+ ///
+ /// Expresses additional pass properties that can be used to perform optimizations on some platforms.
+ ///
+ [Flags]
+ public enum ExtendedFeatureFlags
+ {
+ ///Default state with no extended features enabled.
+ None = 0,
+ ///On Meta XR, this flag can be set for the pass that performs the most 3D rendering to achieve better performance.
+ TileProperties = 1 << 0,
+ ///On XR, this flag can be set for passes that are compatible with Multiview Render Regions
+ MultiviewRenderRegionsCompatible = 1 << 1
+ }
+
[Flags]
internal enum RenderGraphState
{
@@ -115,6 +129,7 @@ internal interface IDerivedRendergraphContext
/// in favor of more specific contexts that have more specific command buffer types.
///
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
+ [Obsolete("RenderGraphContext is deprecated, use RasterGraphContext/ComputeGraphContext/UnsafeGraphContext instead.")]
public struct RenderGraphContext : IDerivedRendergraphContext
{
private InternalRenderGraphContext wrappedContext;
@@ -318,6 +333,7 @@ internal struct CompiledPassInfo
public bool culledByRendererList;
public bool hasSideEffect;
public bool enableFoveatedRasterization;
+ public ExtendedFeatureFlags extendedFeatureFlags;
public bool hasShadingRateImage;
public bool hasShadingRateStates;
@@ -329,6 +345,7 @@ public void Reset(RenderGraphPass pass, int index)
enableAsyncCompute = pass.enableAsyncCompute;
allowPassCulling = pass.allowPassCulling;
enableFoveatedRasterization = pass.enableFoveatedRasterization;
+ extendedFeatureFlags = ExtendedFeatureFlags.None;
hasShadingRateImage = pass.hasShadingRateImage && !pass.enableFoveatedRasterization;
hasShadingRateStates = pass.hasShadingRateStates && !pass.enableFoveatedRasterization;
@@ -378,9 +395,9 @@ public void Reset(RenderGraphPass pass, int index)
}
///
- /// Enable the use of the render pass API by the graph instead of traditional SetRenderTarget. This is an advanced
- /// feature and users have to be aware of the specific impact it has on rendergraph/graphics APIs below.
- ///
+ /// Enable the use of the render pass API instead of the traditional SetRenderTarget workflow for AddRasterRenderPass() API. Enabled by default since 6000.3.
+ ///
+ ///
/// When enabled, the render graph try to use render passes and supasses instead of relying on SetRendertarget. It
/// will try to aggressively optimize the number of BeginRenderPass+EndRenderPass calls as well as calls to NextSubPass.
/// This with the aim to maximize the time spent "on chip" on tile based renderers.
@@ -400,11 +417,8 @@ public void Reset(RenderGraphPass pass, int index)
///
/// Note: that CommandBuffer.BeginRenderPass/EndRenderPass calls are different by design from SetRenderTarget so this could also have
/// effects outside of render graph (e.g. for code relying on the currently active render target as this will not be updated when using render passes).
- ///
- public bool nativeRenderPassesEnabled
- {
- get; set;
- }
+ ///
+ public bool nativeRenderPassesEnabled { get; set; } = true;
internal static bool hasAnyRenderGraphWithNativeRenderPassesEnabled
{
@@ -531,7 +545,7 @@ public RenderGraphDefaultResources defaultResources
///
/// Render Graph constructor.
///
- /// Optional name used to identify the render graph instnace.
+ /// Optional name used to identify the render graph instance.
public RenderGraph(string name = "RenderGraph")
{
this.name = name;
@@ -827,6 +841,7 @@ public TextureHandle CreateTexture(in TextureDesc desc)
/// Creation descriptor of the texture.
/// Set to true if you want to manage the lifetime of the resource yourself. Otherwise the resource will be released automatically if unused for a time.
/// A new TextureHandle.
+ [Obsolete("CreateSharedTexture() and shared texture workflow are deprecated, use ImportTexture() workflow instead.")]
public TextureHandle CreateSharedTexture(in TextureDesc desc, bool explicitRelease = false)
{
CheckNotUsingNativeRenderPassCompiler();
@@ -843,6 +858,7 @@ public TextureHandle CreateSharedTexture(in TextureDesc desc, bool explicitRelea
///
/// Shared texture that needs to be updated.
/// New Descriptor for the texture.
+ [Obsolete("RefreshSharedTextureDesc() and shared texture workflow are deprecated, use ImportTexture() workflow instead.")]
public void RefreshSharedTextureDesc(TextureHandle handle, in TextureDesc desc)
{
CheckNotUsingNativeRenderPassCompiler();
@@ -857,6 +873,7 @@ public void RefreshSharedTextureDesc(TextureHandle handle, in TextureDesc desc)
/// This API should not be used with URP NRP Render Graph. This API cannot be called when Render Graph is active, please call it outside of RecordRenderGraph().
///
/// The handle to the texture that needs to be release.
+ [Obsolete("ReleaseSharedTexture() and shared texture workflow are deprecated, use ImportTexture() workflow instead.")]
public void ReleaseSharedTexture(TextureHandle texture)
{
CheckNotUsingNativeRenderPassCompiler();
@@ -1415,6 +1432,7 @@ public IUnsafeRenderGraphBuilder AddUnsafePass(string passName, out Pa
/// File name of the source file this function is called from. Used for debugging. This parameter is automatically generated by the compiler. Users do not need to pass it.
/// File line of the source file this function is called from. Used for debugging. This parameter is automatically generated by the compiler. Users do not need to pass it.
/// A new instance of a RenderGraphBuilder used to setup the new Render Pass.
+ [Obsolete("AddRenderPass() is deprecated, use AddRasterRenderPass/AddComputePass/AddUnsafePass() instead.")]
public RenderGraphBuilder AddRenderPass(string passName, out PassData passData, ProfilingSampler sampler
#if !CORE_PACKAGE_DOCTOOLS
,[CallerFilePath] string file = "",
@@ -1451,6 +1469,7 @@ public RenderGraphBuilder AddRenderPass(string passName, out PassData
/// File name of the source file this function is called from. Used for debugging. This parameter is automatically generated by the compiler. Users do not need to pass it.
/// File line of the source file this function is called from. Used for debugging. This parameter is automatically generated by the compiler. Users do not need to pass it.
/// A new instance of a RenderGraphBuilder used to setup the new Render Pass.
+ [Obsolete("AddRenderPass() is deprecated, use AddRasterRenderPass/AddComputePass/AddUnsafePass() instead.")]
public RenderGraphBuilder AddRenderPass(string passName, out PassData passData
#if !CORE_PACKAGE_DOCTOOLS
,[CallerFilePath] string file = "",
@@ -1570,7 +1589,10 @@ public bool ResetGraphAndLogException(Exception e)
// TODO: Do we really want to swallow exceptions here? Not a very c# thing to do.
Debug.LogError(RenderGraphExceptionMessages.k_RenderGraphExecutionError);
if (!m_ExecutionExceptionWasRaised) // Already logged. TODO: There is probably a better way in C# to handle that.
+ {
Debug.LogException(e);
+ }
+
m_ExecutionExceptionWasRaised = true;
}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs
index 68106a2bab0..8bdf1bfd889 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilder.cs
@@ -8,6 +8,7 @@ namespace UnityEngine.Rendering.RenderGraphModule
/// Use this struct to set up a new Render Pass.
///
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
+ [Obsolete("RenderGraphBuilder is deprecated, use IComputeRenderGraphBuilder/IRasterRenderGraphBuilder/IUnsafeRenderGraphBuilder instead.")]
public struct RenderGraphBuilder : IDisposable
{
RenderGraphPass m_RenderPass;
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilders.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilders.cs
index 1d37fafe61b..7ea606fdc74 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilders.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphBuilders.cs
@@ -15,7 +15,6 @@ internal class RenderGraphBuilders : IBaseRenderGraphBuilder, IComputeRenderGrap
RenderGraph m_RenderGraph;
bool m_Disposed;
-
public RenderGraphBuilders()
{
m_RenderPass = null;
@@ -31,7 +30,7 @@ public void Setup(RenderGraphPass renderPass, RenderGraphResourceRegistry resour
// This is likely cause by a user not doing a clean using and then forgetting to manually dispose the object.
if (m_Disposed != true)
{
- throw new Exception("Please finish building the previous pass first by disposing the pass builder object before adding a new pass.");
+ throw new Exception(RenderGraph.RenderGraphExceptionMessages.k_UndisposedBuilderPreviousPass);
}
#endif
m_RenderPass = renderPass;
@@ -112,7 +111,7 @@ public void GenerateDebugData(bool value)
{
m_RenderPass.GenerateDebugData(value);
}
-
+
public void Dispose()
{
Dispose(true);
@@ -178,7 +177,7 @@ private void ValidateWriteTo(in ResourceHandle handle)
if (handle.IsVersioned)
{
var name = m_Resources.GetRenderGraphResourceName(handle);
- throw new InvalidOperationException($"Trying to write to a versioned resource handle. You can only write to unversioned resource handles to avoid branches in the resource history. (pass {m_RenderPass.name} resource{name}).");
+ throw new InvalidOperationException($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {handle.type} at index {handle.index} - " + RenderGraph.RenderGraphExceptionMessages.k_WriteToVersionedResource);
}
if (m_RenderPass.IsWritten(handle))
@@ -197,7 +196,7 @@ private void ValidateWriteTo(in ResourceHandle handle)
// > Get this error they were probably thinking they were writing two separate outputs... but they are just two versions of resource 'a'
// where they can only differ between by careful management of versioned resources.
var name = m_Resources.GetRenderGraphResourceName(handle);
- throw new InvalidOperationException($"Trying to write a resource twice in a pass. You can only write the same resource once within a pass (pass {m_RenderPass.name} resource{name}).");
+ throw new InvalidOperationException($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {handle.type} at index {handle.index} - " + RenderGraph.RenderGraphExceptionMessages.k_WriteToResourceTwice);
}
}
}
@@ -288,7 +287,7 @@ private void CheckNotUseFragment(TextureHandle tex)
if (usedAsFragment)
{
var name = m_Resources.GetRenderGraphResourceName(tex.handle);
- throw new ArgumentException($"Trying to UseTexture on a texture that is already used through SetRenderAttachment. Consider updating your code. (pass {m_RenderPass.name} resource{name}).");
+ throw new ArgumentException($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {tex.handle.type} at index {tex.handle.index} - " + RenderGraph.RenderGraphExceptionMessages.k_TextureAlreadyBeingUsedThroughSetAttachment);
}
}
}
@@ -308,7 +307,9 @@ public void UseGlobalTexture(int propertyId, AccessFlags flags)
}
else
{
- throw new ArgumentException($"Trying to read global texture property {propertyId} but no previous pass in the graph assigned a value to this global.");
+ // rose test this path
+ var name = m_Resources.GetRenderGraphResourceName(h.handle);
+ throw new ArgumentException($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {h.handle.type} at index {h.handle.index} - " + RenderGraph.RenderGraphExceptionMessages.NoGlobalTextureAtPropertyID(propertyId));
}
}
@@ -357,12 +358,12 @@ private void CheckUseFragment(TextureHandle tex, bool isDepth)
if (alreadyUsed)
{
var name = m_Resources.GetRenderGraphResourceName(tex.handle);
- throw new InvalidOperationException($"Trying to SetRenderAttachment on a texture that is already used through UseTexture/SetRenderAttachment. Consider updating your code. (pass '{m_RenderPass.name}' resource '{name}').");
+ throw new InvalidOperationException($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {tex.handle.type} at index {tex.handle.index} - " + RenderGraph.RenderGraphExceptionMessages.k_SetRenderAttachmentTextureAlreadyUsed);
}
m_Resources.GetRenderTargetInfo(tex.handle, out var info);
- // The old path is full of invalid uses that somehow work (or seemt to work) so we skip the tests if not using actual native renderpass
+ // The old path is full of invalid uses that somehow work (or seem to work) so we skip validation if not using actual native renderpass
if (m_RenderGraph.nativeRenderPassesEnabled)
{
if (isDepth)
@@ -370,7 +371,7 @@ private void CheckUseFragment(TextureHandle tex, bool isDepth)
if (!GraphicsFormatUtility.IsDepthFormat(info.format))
{
var name = m_Resources.GetRenderGraphResourceName(tex.handle);
- throw new InvalidOperationException($"Trying to SetRenderAttachmentDepth on a texture that has a color format {info.format}. Use a texture with a depth format instead. (pass '{m_RenderPass.name}' resource '{name}').");
+ throw new InvalidOperationException($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {tex.handle.type} at index {tex.handle.index} - " + RenderGraph.RenderGraphExceptionMessages.UseDepthWithColorFormat(info.format));
}
}
else
@@ -378,7 +379,7 @@ private void CheckUseFragment(TextureHandle tex, bool isDepth)
if (GraphicsFormatUtility.IsDepthFormat(info.format))
{
var name = m_Resources.GetRenderGraphResourceName(tex.handle);
- throw new InvalidOperationException($"Trying to SetRenderAttachment on a texture that has a depth format. Use a texture with a color format instead. (pass '{m_RenderPass.name}' resource '{name}').");
+ throw new InvalidOperationException($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {tex.handle.type} at index {tex.handle.index} - " + RenderGraph.RenderGraphExceptionMessages.k_SetRenderAttachmentOnDepthTexture);
}
}
}
@@ -387,7 +388,8 @@ private void CheckUseFragment(TextureHandle tex, bool isDepth)
{
if (globalTex.Item1.handle.index == tex.handle.index)
{
- throw new InvalidOperationException("Trying to SetRenderAttachment on a texture that is currently set on a global texture slot. Shaders might be using the texture using samplers. You should ensure textures are not set as globals when using them as fragment attachments.");
+ var name = m_Resources.GetRenderGraphResourceName(tex.handle);
+ throw new InvalidOperationException($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {tex.handle.type} at index {tex.handle.index} - " + RenderGraph.RenderGraphExceptionMessages.k_SetRenderAttachmentOnGlobalTexture);
}
}
}
@@ -480,17 +482,22 @@ void CheckResource(in ResourceHandle res, bool checkTransientReadWrite = false)
// We have dontCheckTransientReadWrite here because users may want to use UseColorBuffer/UseDepthBuffer API to benefit from render target auto binding. In this case we don't want to raise the error.
if (transientIndex == m_RenderPass.index && checkTransientReadWrite)
{
- Debug.LogError($"Trying to read or write a transient resource at pass {m_RenderPass.name}.Transient resource are always assumed to be both read and written.");
+ var name = m_Resources.GetRenderGraphResourceName(res);
+ Debug.LogError($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {res.type} at index {res.index} - " + RenderGraph.RenderGraphExceptionMessages.k_ReadWriteTransient);
}
if (transientIndex != -1 && transientIndex != m_RenderPass.index)
{
- throw new ArgumentException($"Trying to use a transient {res.type} (pass index {transientIndex}) in a different pass (pass index {m_RenderPass.index}).");
+ var name = m_Resources.GetRenderGraphResourceName(res);
+ throw new ArgumentException(
+ $"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {res.type} at index {res.index} - " +
+ RenderGraph.RenderGraphExceptionMessages.UseTransientTextureInWrongPass(transientIndex));
}
}
else
{
- throw new Exception($"Trying to use an invalid resource (pass {m_RenderPass.name}).");
+ var name = m_Resources.GetRenderGraphResourceName(res);
+ throw new Exception($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {res.type} at index {res.index} - " + RenderGraph.RenderGraphExceptionMessages.k_InvalidResource);
}
}
}
@@ -534,5 +541,10 @@ public void SetShadingRateCombiner(ShadingRateCombinerStage stage, ShadingRateCo
{
m_RenderPass.SetShadingRateCombiner(stage, combiner);
}
+
+ public void SetExtendedFeatureFlags(ExtendedFeatureFlags extendedFeatureFlags)
+ {
+ m_RenderPass.SetExtendedFeatureFlags(extendedFeatureFlags);
+ }
}
}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphPass.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphPass.cs
index bd5ef25e2ea..8643987c676 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphPass.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphPass.cs
@@ -21,6 +21,7 @@ abstract class RenderGraphPass
public bool allowPassCulling { get; protected set; }
public bool allowGlobalState { get; protected set; }
public bool enableFoveatedRasterization { get; protected set; }
+ public ExtendedFeatureFlags extendedFeatureFlags { get; protected set; }
// Before using the AccessFlags use resourceHandle.isValid()
// to make sure that the data in the colorBuffer/fragmentInput/randomAccessResource buffers are up to date
@@ -277,7 +278,9 @@ public void SetColorBufferRaw(in TextureHandle resource, int index, AccessFlags
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
// You tried to do SetRenderAttachment(tex1, 1, ..); SetRenderAttachment(tex2, 1, ..); that is not valid for different textures on the same index
- throw new InvalidOperationException("You can only bind a single texture to an MRT index. Verify your indexes are correct.");
+ throw new InvalidOperationException(
+ $"In pass '{name}' when trying to call SetRenderAttachment with resource of type {resource.handle.type} at index {index} - " +
+ RenderGraph.RenderGraphExceptionMessages.k_MoreThanOneResourceForMRTIndex);
#endif
}
}
@@ -296,7 +299,9 @@ public void SetFragmentInputRaw(in TextureHandle resource, int index, AccessFlag
{
#if DEVELOPMENT_BUILD || UNITY_EDITOR
// You tried to do SetRenderAttachment(tex1, 1, ..); SetRenderAttachment(tex2, 1, ..); that is not valid for different textures on the same index
- throw new InvalidOperationException("You can only bind a single texture to an fragment input index. Verify your indexes are correct.");
+ throw new InvalidOperationException(
+ $"In pass '{name}' when trying to call SetInputAttachment with resource of type {resource.handle.type} at index {index} - " +
+ RenderGraph.RenderGraphExceptionMessages.k_MoreThanOneTextureForFragInputIndex);
#endif
}
}
@@ -316,7 +321,9 @@ public void SetRandomWriteResourceRaw(in ResourceHandle resource, int index, boo
else
{
// You tried to do SetRenderAttachment(tex1, 1, ..); SetRenderAttachment(tex2, 1, ..); that is not valid for different textures on the same index
- throw new InvalidOperationException("You can only bind a single texture to an random write input index. Verify your indexes are correct.");
+ throw new InvalidOperationException(
+ $"In pass '{name}' when trying to call SetRandomAccessAttachment/UseBufferRandomAccess with resource of type {resource.type} at index {index} - " +
+ RenderGraph.RenderGraphExceptionMessages.k_MoreThanOneTextureRandomWriteInputIndex);
}
}
@@ -343,7 +350,9 @@ public void SetDepthBufferRaw(in TextureHandle resource, AccessFlags accessFlags
#if DEVELOPMENT_BUILD || UNITY_EDITOR
else
{
- throw new InvalidOperationException("You can only set a single depth texture per pass.");
+ throw new InvalidOperationException(
+ $"In pass '{name}' when trying to call SetRenderAttachmentDepth with resource of type {resource.handle.type} at index {index} - " +
+ RenderGraph.RenderGraphExceptionMessages.k_MultipleDepthTextures);
}
#endif
}
@@ -581,6 +590,11 @@ public void SetShadingRateCombiner(ShadingRateCombinerStage stage, ShadingRateCo
}
}
}
+
+ public void SetExtendedFeatureFlags(ExtendedFeatureFlags value)
+ {
+ extendedFeatureFlags |= value;
+ }
}
// This used to have an extra generic argument 'RenderGraphContext' abstracting the context and avoiding
@@ -626,6 +640,7 @@ public override int GetRenderFuncHash()
}
[DebuggerDisplay("RenderPass: {name} (Index:{index} Async:{enableAsyncCompute})")]
+ [Obsolete("RenderGraphPass is deprecated, use RasterRenderGraphPass/ComputeRenderGraphPass/UnsafeRenderGraphPass instead.")]
internal sealed class RenderGraphPass : BaseRenderGraphPass
where PassData : class, new()
{
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsBlit.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsBlit.cs
index 6cc9d72aeb5..76620b94986 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsBlit.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsBlit.cs
@@ -1,6 +1,7 @@
using System;
using System.Runtime.CompilerServices;
using Unity.Mathematics;
+using UnityEngine.Experimental.Rendering;
namespace UnityEngine.Rendering.RenderGraphModule.Util
{
@@ -121,6 +122,9 @@ public static bool CanAddCopyPass(this RenderGraph graph, TextureHandle source,
if (sourceInfo.volumeDepth != destinationInfo.volumeDepth)
return false;
+ if (GraphicsFormatUtility.IsDepthFormat(sourceInfo.format) || GraphicsFormatUtility.IsDepthFormat(destinationInfo.format))
+ return false;
+
// Note: Needs shader model ps_4.1 to support SV_SampleIndex which means the copy pass isn't supported for MSAA on some platforms.
// We can check this by checking the amout of shader passes the copy shader has.
// It would have 1 if the MSAA pass is not able to be used for target and 2 otherwise.
@@ -185,6 +189,9 @@ public static IBaseRenderGraphBuilder AddCopyPass(
if (sourceInfo.volumeDepth != destinationInfo.volumeDepth)
throw new ArgumentException("Slice count for source and destination texture doesn't match.");
+ if (GraphicsFormatUtility.IsDepthFormat(sourceInfo.format) || GraphicsFormatUtility.IsDepthFormat(destinationInfo.format))
+ throw new ArgumentException("Depth format for source or destination texture is not supported. Use AddBlitPass instead.");
+
var isMSAA = (int)sourceInfo.msaaSamples > 1;
// Note: Needs shader model ps_4.1 to support SV_SampleIndex which means the copy pass isn't supported for MSAA on some platforms.
@@ -238,7 +245,7 @@ public static IBaseRenderGraphBuilder AddCopyPass(
/// is here for backwards compatibility with existing code.
///
/// When XR is active, array textures containing both eyes will be automatically copied.
- ///
+ ///
///
/// The RenderGraph adding this pass to.
/// The texture the data is copied from.
@@ -325,17 +332,20 @@ class BlitPassData
public int numMips;
public BlitFilterMode filterMode;
public bool isXR;
-
+ public bool isDepth;
}
///
/// Add a render graph pass to blit an area of the source texture into the destination texture. Blitting is a high-level way to transfer texture data from a source to a destination texture.
/// It may scale and texture-filter the transferred data as well as doing data transformations on it (e.g. R8Unorm to float).
///
- /// This function does not have special handling for MSAA textures. This means that when the source is sampled this will be a resolved value (standard Unity behavior when sampling an MSAA render texture)
+ /// This function does not have special handling for MSAA color textures. This means that when the source color is sampled this will be a resolved value (standard Unity behavior when sampling an MSAA render texture)
/// and when the destination is MSAA all written samples will contain the same values (e.g. as you would expect when rendering a full screen quad to an msaa buffer). If you need special MSAA
/// handling or custom resolving please use the overload that takes a Material and implement the appropriate behavior in the shader.
///
+ /// For depth textures, MSAA handling is different. If the bindTextureMS flag of the source texture is set to true, then the MSAA values will be resolved by the blit shader and write a single value to a non-MSAA output texture.
+ /// It is not supported to set the source texture bindTextureMS flag to false or to bind an MSAA texture as destination when using a depth texture as source texture.
+ ///
/// This function works transparently with regular textures and XR textures (which may depending on the situation be 2D array textures). In the case of an XR array texture
/// the operation will be repeated for each slice in the texture if numSlices is set to -1.
///
@@ -407,10 +417,18 @@ public static IBaseRenderGraphBuilder AddBlitPass(this RenderGraph graph,
throw new ArgumentException($"BlitPass: {passName} attempts to blit too many mips. The pass will be skipped.");
}
+ bool sourceIsDepth = GraphicsFormatUtility.IsDepthFormat(sourceDesc.format);
+ bool destinationIsDepth = GraphicsFormatUtility.IsDepthFormat(destinationDesc.format);
+ if (!sourceIsDepth && destinationIsDepth)
+ throw new ArgumentException($"BlitPass: {passName} attempts to blit from a color texture to a depth texture. This is not allowed.");
+
+ if (sourceIsDepth && !sourceDesc.bindTextureMS && sourceDesc.msaaSamples != MSAASamples.None)
+ throw new ArgumentException($"BlitPass: {passName} source depth render texture is MSAA but doesn't have the bindTextureMS flag set to true, this is not supported. This is not allowed.");
+
var canUseCopyPass = CanAddCopyPass(graph, source, destination)
&& scale == Vector2.one && offset == Vector2.zero && numSlices == 1 && numMips == 1;
- if (canUseCopyPass)
+ if (canUseCopyPass && !destinationIsDepth)
{
return AddCopyPass(graph, source, destination, passName, returnBuilder, file, line);
}
@@ -430,6 +448,7 @@ public static IBaseRenderGraphBuilder AddBlitPass(this RenderGraph graph,
passData.destinationMip = destinationMip;
passData.numMips = numMips;
passData.filterMode = filterMode;
+ passData.isDepth = destinationIsDepth;
builder.UseTexture(source, AccessFlags.Read);
builder.UseTexture(destination, AccessFlags.Write);
builder.SetRenderFunc((BlitPassData data, UnsafeGraphContext context) => BlitRenderFunc(data, context));
@@ -456,9 +475,15 @@ static void BlitRenderFunc(BlitPassData data, UnsafeGraphContext context)
s_BlitScaleBias.w = data.offset.y;
CommandBuffer unsafeCmd = CommandBufferHelpers.GetNativeCommandBuffer(context.cmd);
- if (data.isXR)
+
+ if (data.isDepth)
+ {
+ context.cmd.SetRenderTarget(data.destination, 0, CubemapFace.Unknown, -1);
+ Blitter.BlitDepth(unsafeCmd, data.source, s_BlitScaleBias, 0);
+ }
+ else if (data.isXR)
{
- // This is the magic that makes XR work for blit. We set the rendertargets passing -1 for the slices. This means it will bind all (both eyes) slices.
+ // This is the magic that makes XR work for blit. We set the rendertargets passing -1 for the slices. This means it will bind all (both eyes) slices.
// The engine will then also automatically duplicate our draws and the vertex and pixel shader (through macros) will ensure those draws end up in the right eye.
context.cmd.SetRenderTarget(data.destination, 0, CubemapFace.Unknown, -1);
Blitter.BlitTexture(unsafeCmd, data.source, s_BlitScaleBias, data.sourceMip, data.filterMode == BlitFilterMode.ClampBilinear);
@@ -506,7 +531,7 @@ public enum FullScreenGeometryType
/// Use one of the constructor overloads for common use cases.
///
/// By default most constructors will copy all array texture slices. This ensures XR textures are handled "automatically" without additional consideration.
- ///
+ ///
/// The shader properties defined in the struct or constructors is used for most common usecases but they are not required to be used in the shader.
/// By using the MaterialPropertyBlock can you add your shader properties with custom values.
///
@@ -519,7 +544,7 @@ public struct BlitMaterialParameters
///
/// Simple constructor that sets only the most common parameters to blit. The other parameters will be set to sensible default values.
- ///
+ ///
///
/// The texture the data is copied from.
/// The texture the data is copied to.
@@ -901,7 +926,7 @@ class BlitMaterialPassData
/// Notes on using this function:
/// - If you need special handling of MSAA buffers this can be implemented using the bindMS flag on the source texture and per-sample pixel shader invocation on the destination texture (e.g. using SV_SampleIndex).
/// - MaterialPropertyBlocks used for this function should not contain any textures added by MaterialPropertyBlock.SetTexture(...) as it will cause untracked textures when using RenderGraph causing uninstended behaviour.
- ///
+ ///
///
/// The RenderGraph adding this pass to.
/// Parameters used for rendering.
@@ -1036,7 +1061,7 @@ static void BlitMaterialRenderFunc(BlitMaterialPassData data, UnsafeGraphContext
if (data.isXR)
{
- // This is the magic that makes XR work for blit. We set the rendertargets passing -1 for the slices. This means it will bind all (both eyes) slices.
+ // This is the magic that makes XR work for blit. We set the rendertargets passing -1 for the slices. This means it will bind all (both eyes) slices.
// The engine will then also automatically duplicate our draws and the vertex and pixel shader (through macros) will ensure those draws end up in the right eye.
if (data.sourceSlice != -1)
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsResources.cs b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsResources.cs
index 0f927331ed5..253ae578066 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsResources.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderGraph/RenderGraphUtilsResources.cs
@@ -3,6 +3,9 @@
namespace UnityEngine.Rendering.RenderGraphModule.Util
{
+ ///
+ /// Core Shader Resources.
+ ///
[Serializable]
[HideInInspector]
[Category("Resources/Render Graph Helper Function Resources")]
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOccluder.shader b/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOccluder.shader
index c5a6d602d51..24149a67fb8 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOccluder.shader
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOccluder.shader
@@ -2,7 +2,7 @@ Shader "Hidden/Core/DebugOccluder"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch webgpu
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2 webgpu
//#pragma enable_d3d11_debug_symbols
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOcclusionTest.shader b/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOcclusionTest.shader
index 2513172f098..ac340d0bd4e 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOcclusionTest.shader
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/DebugOcclusionTest.shader
@@ -12,7 +12,7 @@ Shader "Hidden/Core/DebugOcclusionTest"
HLSLPROGRAM
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch webgpu
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2 webgpu
#pragma vertex Vert
#pragma fragment Frag
@@ -90,7 +90,7 @@ Shader "Hidden/Core/DebugOcclusionTest"
if(total == 0)
return float4(0, 0, 0, 0);
-
+
float cost = log2((float)total);
uint screenTotal = _OcclusionDebugOverlay[0]; // This should be always >= 1, because total >= 1 at this point.
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/OccluderDepthPyramidKernels.compute b/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/OccluderDepthPyramidKernels.compute
index f01cb36f907..4a2c3dce7a8 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/OccluderDepthPyramidKernels.compute
+++ b/Packages/com.unity.render-pipelines.core/Runtime/RenderPipelineResources/GPUDriven/OccluderDepthPyramidKernels.compute
@@ -1,6 +1,6 @@
#pragma kernel OccluderDepthDownscale
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch webgpu
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2 webgpu
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/OccluderDepthPyramidConstants.cs.hlsl"
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/STP/STPIUpscaler.cs b/Packages/com.unity.render-pipelines.core/Runtime/STP/STPIUpscaler.cs
new file mode 100644
index 00000000000..aa946b9ff0f
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/STP/STPIUpscaler.cs
@@ -0,0 +1,164 @@
+#if ENABLE_UPSCALER_FRAMEWORK
+using UnityEngine;
+using UnityEngine.Experimental.Rendering;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.RenderGraphModule;
+
+#if UNITY_EDITOR
+using UnityEditor;
+#endif
+
+
+#if UNITY_EDITOR
+[InitializeOnLoad]
+#endif
+static class RegisterSTP
+{
+ static RegisterSTP() => UpscalerRegistry.Register(STPIUpscaler.UPSCALER_NAME);
+
+ [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
+ static void InitRuntime() => UpscalerRegistry.Register(STPIUpscaler.UPSCALER_NAME);
+}
+
+public class STPIUpscaler : AbstractUpscaler
+{
+ public static readonly string UPSCALER_NAME = "STP (IUpscaler)";
+
+ STPOptions options; // contains injection point (for HDRP at this time)
+ private const string _UpscaledColorTargetName = "_UpscaledCameraColor";
+ private STP.HistoryContext[] histories; // One history per eye
+
+ public STPIUpscaler(STPOptions optionsIn)
+ {
+ options = optionsIn;
+
+ histories = new STP.HistoryContext[2];
+ for (int i = 0; i < histories.Length; i++)
+ {
+ histories[i] = new STP.HistoryContext();
+ }
+ }
+
+ public override UpscalerOptions GetOptions()
+ {
+ return options;
+ }
+
+ public override string GetName()
+ {
+ return UPSCALER_NAME;
+ }
+
+ public override bool IsTemporalUpscaler() { return true; }
+
+ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
+ {
+ UpscalingIO io = frameData.Get();
+
+ // Create an output texture
+ TextureHandle outputColor;
+ {
+ TextureDesc inputDesc = io.cameraColor.GetDescriptor(renderGraph);
+ TextureDesc outputDesc = inputDesc;
+ outputDesc.width = io.postUpscaleResolution.x;
+ outputDesc.height = io.postUpscaleResolution.y;
+ // Avoid enabling sRGB because STP works with compute shaders which can't output sRGB automatically.
+ outputDesc.format = GraphicsFormatUtility.GetLinearFormat(inputDesc.format);
+ outputDesc.msaaSamples = MSAASamples.None;
+ outputDesc.useMipMap = false;
+ outputDesc.autoGenerateMips = false;
+ outputDesc.useDynamicScale = false;
+ outputDesc.anisoLevel = 0;
+ outputDesc.discardBuffer = false;
+ // STP uses compute shaders so all render textures must enable random writes
+ outputDesc.enableRandomWrite = true;
+
+ outputDesc.name = _UpscaledColorTargetName;
+ outputDesc.clearBuffer = false;
+ outputDesc.filterMode = FilterMode.Bilinear;
+ outputColor = renderGraph.CreateTexture(outputDesc);
+ }
+
+ // Populate the STP config
+ STP.Config config = new();
+ {
+ // TODO (Apoorva): Set this using UpscalingInputs when we add HDRP support
+ config.enableTexArray = io.enableTexArray;
+ config.enableMotionScaling = io.enableMotionScaling;
+ config.noiseTexture = io.blueNoiseTextureSet[io.frameIndex & (io.blueNoiseTextureSet.Length - 1)];
+ config.inputColor = io.cameraColor;
+ config.inputDepth = io.cameraDepth;
+ config.inputMotion = io.motionVectorColor;
+ config.currentImageSize = io.preUpscaleResolution;
+ config.priorImageSize = io.previousPreUpscaleResolution;
+ config.outputImageSize = io.postUpscaleResolution;
+ config.deltaTime = io.deltaTime;
+ config.lastDeltaTime = io.previousDeltaTime;
+ config.frameIndex = io.frameIndex;
+ config.nearPlane = io.nearClipPlane;
+ config.farPlane = io.farClipPlane;
+
+ // TODO (Apoorva): Support stencil masking. URP doesn't support this, HDRP does. We should add support for
+ // both.
+ config.inputStencil = TextureHandle.nullHandle;
+ config.stencilMask = 0;
+
+ // TODO (Apoorva): Add support for debug views.
+ config.debugView = TextureHandle.nullHandle;
+ config.debugViewIndex = 0;
+
+ config.destination = outputColor;
+
+ Debug.Assert(io.eyeIndex < histories.Length);
+ bool hasValidHistory;
+ {
+ STP.HistoryUpdateInfo info;
+ info.preUpscaleSize = io.preUpscaleResolution;
+ info.postUpscaleSize = io.postUpscaleResolution;
+ info.useHwDrs = io.enableHwDrs;
+ info.useTexArray = io.enableTexArray;
+ hasValidHistory = histories[io.eyeIndex].Update(ref info);
+ }
+ config.historyContext = histories[io.eyeIndex];
+ config.enableHwDrs = io.enableHwDrs;
+ config.hasValidHistory = !io.resetHistory && hasValidHistory;
+
+
+ config.numActiveViews = io.numActiveViews;
+ config.perViewConfigs = STP.perViewConfigs;
+ Debug.Assert(io.numActiveViews <= STP.perViewConfigs.Length);
+ for (int viewIndex = 0; viewIndex < io.numActiveViews; ++viewIndex)
+ {
+ int targetIndex = viewIndex + io.eyeIndex;
+
+ STP.PerViewConfig perViewConfig;
+
+ // STP requires non-jittered versions of the current, previous, and "previous previous" projection
+ // matrix.
+ perViewConfig.currentProj = io.projectionMatrices[targetIndex];
+ perViewConfig.lastProj = io.previousProjectionMatrices[targetIndex];
+ perViewConfig.lastLastProj = io.previousPreviousProjectionMatrices[targetIndex];
+
+ perViewConfig.currentView = io.viewMatrices[targetIndex];
+ perViewConfig.lastView = io.previousViewMatrices[targetIndex];
+ perViewConfig.lastLastView = io.previousPreviousViewMatrices[targetIndex];
+
+ // NOTE: STP assumes the view matrices also contain the world space camera position so we inject the
+ // camera position directly here.
+ Vector3 currentPosition = io.worldSpaceCameraPositions[viewIndex];
+ Vector3 lastPosition = io.previousWorldSpaceCameraPositions[viewIndex];
+ Vector3 lastLastPosition = io.previousPreviousWorldSpaceCameraPositions[viewIndex];
+
+ perViewConfig.currentView.SetColumn(3, new Vector4(-currentPosition.x, -currentPosition.y, -currentPosition.z, 1.0f));
+ perViewConfig.lastView.SetColumn(3, new Vector4(-lastPosition.x, -lastPosition.y, -lastPosition.z, 1.0f));
+ perViewConfig.lastLastView.SetColumn(3, new Vector4(-lastLastPosition.x, -lastLastPosition.y, -lastLastPosition.z, 1.0f));
+
+ STP.perViewConfigs[viewIndex] = perViewConfig;
+ }
+ }
+
+ STP.Execute(renderGraph, ref config);
+ io.cameraColor = outputColor;
+ }
+}
+#endif
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/STP/STPIUpscaler.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/STP/STPIUpscaler.cs.meta
new file mode 100644
index 00000000000..7b19f191dff
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/STP/STPIUpscaler.cs.meta
@@ -0,0 +1,3 @@
+fileFormatVersion: 2
+guid: 085e6b7f79d14ea1a804921025e9c646
+timeCreated: 1743498958
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/STP/STPOptions.cs b/Packages/com.unity.render-pipelines.core/Runtime/STP/STPOptions.cs
new file mode 100644
index 00000000000..ea854bc3b09
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/STP/STPOptions.cs
@@ -0,0 +1,24 @@
+#if ENABLE_UPSCALER_FRAMEWORK
+using UnityEngine;
+using UnityEngine.Experimental.Rendering;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.RenderGraphModule;
+using System;
+
+#if UNITY_EDITOR
+using UnityEditor;
+#endif
+
+[Serializable]
+public class STPOptions : UpscalerOptions
+{
+ // UpscalerOptions contains the injection point option with default value BeforePostProcess.
+ //
+ // An empty options class like this must be defined & registered if we want to
+ // provide the option to change the injection point of the IUpscaler.
+ //
+ // If no options are defined & registered for an IUpscaler, there won't be a dropdown
+ // in the Render Pipeline settings to change the injection point.
+}
+
+#endif
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/STP/STPOptions.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/STP/STPOptions.cs.meta
new file mode 100644
index 00000000000..40dfe306801
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/STP/STPOptions.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 03be459180a06974d8583254adb17471
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/STP/StpCommon.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/STP/StpCommon.hlsl
index 423d5bed3e8..4e21a5a2324 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/STP/StpCommon.hlsl
+++ b/Packages/com.unity.render-pipelines.core/Runtime/STP/StpCommon.hlsl
@@ -38,11 +38,11 @@
#endif
// Mobile platforms use a simplified version of STP to reduce runtime overhead.
-#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH)
+#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
#define STP_TAA_Q 0
#endif
-#if defined(SHADER_API_SWITCH)
+#if defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
#define STP_BUG_SAT_INF 1
#endif
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/STP/StpPreTaa.compute b/Packages/com.unity.render-pipelines.core/Runtime/STP/StpPreTaa.compute
index 5c89ff78bfc..5e5286ffffd 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/STP/StpPreTaa.compute
+++ b/Packages/com.unity.render-pipelines.core/Runtime/STP/StpPreTaa.compute
@@ -7,7 +7,7 @@
#pragma multi_compile _ DISABLE_TEXTURE2D_X_ARRAY
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch glcore
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2 glcore
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/STP/StpSetup.compute b/Packages/com.unity.render-pipelines.core/Runtime/STP/StpSetup.compute
index 4d98f8bb130..c0614aabcc7 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/STP/StpSetup.compute
+++ b/Packages/com.unity.render-pipelines.core/Runtime/STP/StpSetup.compute
@@ -14,7 +14,7 @@
#pragma multi_compile _ DISABLE_TEXTURE2D_X_ARRAY
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch glcore
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2 glcore
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
@@ -59,7 +59,7 @@ TEXTURE2D_X(_StpPriorFeedback);
#define STP_SETUP_PER_VIEW_CONSTANTS_STEREO_OFFSET (SLICE_ARRAY_INDEX * STPSETUPPERVIEWCONSTANTS_COUNT)
-#if defined(SHADER_API_PSSL) || defined(SHADER_API_SWITCH) || (defined(SHADER_API_METAL) && !defined(SHADER_API_MOBILE))
+#if defined(SHADER_API_PSSL) || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2) || (defined(SHADER_API_METAL) && !defined(SHADER_API_MOBILE))
// Force usage of the 32-bit reduction path even in 16-bit environments
#define STP_FORCE_32BIT_REDUCTION
#endif
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/STP/StpTaa.compute b/Packages/com.unity.render-pipelines.core/Runtime/STP/StpTaa.compute
index c9904044acc..7e26bd633de 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/STP/StpTaa.compute
+++ b/Packages/com.unity.render-pipelines.core/Runtime/STP/StpTaa.compute
@@ -7,7 +7,7 @@
#pragma multi_compile _ DISABLE_TEXTURE2D_X_ARRAY
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch glcore
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2 glcore
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Sampling/Common.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Sampling/Common.hlsl
index 63f8da86c6b..94635eefb7f 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Sampling/Common.hlsl
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Sampling/Common.hlsl
@@ -105,6 +105,16 @@ float3 CosineSample(float2 u, float3 normal)
return mul(basis, localDir);
}
+float3 UniformHemisphereSample(float2 u, float3 normal)
+{
+ float z = u[0];
+ float r = sqrt(max(0.0f, 1.0f - z * z));
+ float phi = 2.0f * PI * u[1];
+ float3 localDir = float3(r * cos(phi), r * sin(phi), z);
+ float3x3 basis = OrthoBasisFromVector(normal);
+ return mul(basis, localDir);
+}
+
float PowerHeuristic(float f, float b)
{
float q = (f * f) + (b * b);
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Settings/RenderingDebuggerRuntimeResources.cs b/Packages/com.unity.render-pipelines.core/Runtime/Settings/RenderingDebuggerRuntimeResources.cs
new file mode 100644
index 00000000000..cc7c00f2020
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Settings/RenderingDebuggerRuntimeResources.cs
@@ -0,0 +1,24 @@
+using System;
+
+namespace UnityEngine.Rendering
+{
+ [Serializable, HideInInspector]
+ [SupportedOnRenderPipeline]
+ [Categorization.CategoryInfo(Name = "R : Rendering Debugger Resources", Order = 100)]
+ [Categorization.ElementInfo(Order = 0)]
+ class RenderingDebuggerRuntimeResources : IRenderPipelineResources
+ {
+ enum Version
+ {
+ Initial,
+
+ Count,
+ Last = Count - 1
+ }
+ [SerializeField, HideInInspector]
+ private Version m_version = Version.Last;
+ int IRenderPipelineGraphicsSettings.version => (int)m_version;
+
+ // TODO Add Rendering Debugger Resources here
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Settings/RenderingDebuggerRuntimeResources.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Settings/RenderingDebuggerRuntimeResources.cs.meta
new file mode 100644
index 00000000000..c346610f7a3
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Settings/RenderingDebuggerRuntimeResources.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: c8ecfef0ec5856a4fa9b1c416f2d51e3
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructAdapter.cs b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructAdapter.cs
index a14bccf7ed8..4b9bb1e8e8e 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructAdapter.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common/AccelStructAdapter.cs
@@ -132,7 +132,7 @@ void AddTrees(TerrainDesc terrainDesc, ref List instanceHandles)
{
TerrainData terrainData = terrainDesc.terrain.terrainData;
float4x4 terrainLocalToWorld = terrainDesc.localToWorldMatrix;
- float3 positionScale = new float3((float)terrainData.heightmapResolution, 1.0f, (float)terrainData.heightmapResolution) * terrainData.heightmapScale;
+ float3 positionScale = new float3((float)terrainData.heightmapResolution, 1.0f, (float)terrainData.heightmapResolution) * (float3)(terrainData.heightmapScale);
float3 positionOffset = new float3(terrainLocalToWorld[3].x, terrainLocalToWorld[3].y, terrainLocalToWorld[3].z);
foreach (var treeInstance in terrainData.treeInstances)
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Unity.RenderPipelines.Core.Runtime.asmdef b/Packages/com.unity.render-pipelines.core/Runtime/Unity.RenderPipelines.Core.Runtime.asmdef
index 78acc72040d..3052597a3f0 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Unity.RenderPipelines.Core.Runtime.asmdef
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Unity.RenderPipelines.Core.Runtime.asmdef
@@ -44,7 +44,12 @@
"name": "com.unity.modules.nvidia",
"expression": "1.0.0",
"define": "ENABLE_NVIDIA_MODULE"
+ },
+ {
+ "name": "com.unity.modules.amd",
+ "expression": "1.0.0",
+ "define": "ENABLE_AMD_MODULE"
}
],
"noEngineReferences": false
-}
\ No newline at end of file
+}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling.meta
new file mode 100644
index 00000000000..53f7f332732
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: eaa9f70ff0dbb864181af13946980fad
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSIUpscaler.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSIUpscaler.cs
new file mode 100644
index 00000000000..19a5cc1aa04
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSIUpscaler.cs
@@ -0,0 +1,357 @@
+using UnityEngine;
+using UnityEngine.Experimental.Rendering;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.RenderGraphModule;
+#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
+using UnityEngine.NVIDIA;
+#endif
+using System;
+
+#if UNITY_EDITOR
+using UnityEditor;
+#endif
+
+#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
+
+#if UNITY_EDITOR
+[InitializeOnLoad]
+#endif
+static class RegisterDLSS
+{
+ static RegisterDLSS() => UpscalerRegistry.Register(DLSSIUpscaler.UPSCALER_NAME);
+
+ [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
+ static void InitRuntime() => UpscalerRegistry.Register(DLSSIUpscaler.UPSCALER_NAME);
+}
+
+public class DLSSIUpscaler : AbstractUpscaler
+{
+ public static readonly string UPSCALER_NAME = "DLSS (IUpscaler)";
+
+#region DLSS_UTILITIES
+ static bool CheckDLSSFeatureAvailable()
+ {
+ // check plugin availability
+ if (!UnityEngine.NVIDIA.NVUnityPlugin.IsLoaded())
+ {
+ Debug.LogWarning("NVUnityPlugin not loaded.");
+ return false;
+ }
+
+ // check GPU vendor
+ if (!SystemInfo.graphicsDeviceVendor.ToLowerInvariant().Contains("nvidia"))
+ {
+ Debug.LogWarning("DLSS not available on non-NVIDIA graphics cards.");
+ return false;
+ }
+
+ // check device
+ UnityEngine.NVIDIA.GraphicsDevice device = UnityEngine.NVIDIA.GraphicsDevice.CreateGraphicsDevice();
+ if (device == null)
+ {
+ Debug.LogWarning("NVUnityPlugin failed to create device.");
+ return false;
+ }
+
+ // check DLSS feature
+ if(!device.IsFeatureAvailable(UnityEngine.NVIDIA.GraphicsDeviceFeature.DLSS))
+ {
+ Debug.LogWarning("DLSS not available on the current NVIDIA graphics card.");
+ return false;
+ }
+
+ return true;
+ }
+ static void DestroyContext(ref DLSSContext ctx, CommandBuffer cmd)
+ {
+ GraphicsDevice.device.DestroyFeature(cmd, ctx);
+ ctx = null;
+ }
+ static void CreateContext(ref DLSSContext ctx, CommandBuffer cmd, ref DLSSGraphData data, ref DLSSOptions options)
+ {
+ /* Motion vectors are typically calculated at the
+ same resolution as the input color frame (i.e. at the render resolution). If the rendering engine
+ supports calculating motion vectors at the display/output resolution and dilating the motion
+ vectors, DLSS can accept those by setting the flag to “0”. This is preferred, though uncommon,
+ and can result in higher quality antialiasing of moving objects and less blurring of small objects
+ and thin details.
+ */
+ bool MVLowResolution = data.motionVectorSizeX <= data.colorInputSizeX || data.motionVectorSizeY <= data.colorInputSizeY;
+
+ DLSSCommandInitializationData settings = new();
+ settings.SetFlag(DLSSFeatureFlags.IsHDR, data.inputIsHDR);
+ settings.SetFlag(DLSSFeatureFlags.MVLowRes, MVLowResolution);
+ settings.SetFlag(DLSSFeatureFlags.DepthInverted, data.invertedDepthBuffer);
+ settings.SetFlag(DLSSFeatureFlags.MVJittered, data.motionVectorsAreJittered);
+ settings.inputRTWidth = data.colorInputSizeX;
+ settings.inputRTHeight = data.colorInputSizeY;
+ settings.outputRTWidth = data.colorOutputSizeX;
+ settings.outputRTHeight = data.colorOutputSizeY;
+ settings.quality = (DLSSQuality)options.DLSSQualityMode;
+ settings.presetQualityMode = (DLSSPreset)options.DLSSRenderPresetQuality;
+ settings.presetBalancedMode = (DLSSPreset)options.DLSSRenderPresetBalanced;
+ settings.presetPerformanceMode = (DLSSPreset)options.DLSSRenderPresetPerformance;
+ settings.presetUltraPerformanceMode = (DLSSPreset)options.DLSSRenderPresetUltraPerformance;
+ settings.presetDlaaMode = (DLSSPreset)options.DLSSRenderPresetDLAA;
+ ctx = GraphicsDevice.device.CreateFeature(cmd, settings);
+ }
+#endregion // DLSS_UTILITIES
+
+
+#region RENDERGRAPH_INTERFACE_DATA
+ class DLSSGraphData
+ {
+ public bool shouldReinitializeContext;
+
+ public uint colorInputSizeX;
+ public uint colorInputSizeY;
+ public uint colorOutputSizeX;
+ public uint colorOutputSizeY;
+ public uint motionVectorSizeX;
+ public uint motionVectorSizeY;
+ public bool invertedDepthBuffer;
+ public bool inputIsHDR;
+ public bool motionVectorsAreJittered;
+
+ public DLSSCommandExecutionData execData;
+ public TextureHandle colorInput;
+ public TextureHandle depth;
+ public TextureHandle motionVectors;
+ public TextureHandle colorOutput;
+ };
+#endregion
+
+#region IUPSCALER_INTERFACE
+ public DLSSIUpscaler(DLSSOptions o)
+ {
+ if(!CheckDLSSFeatureAvailable())
+ {
+ m_DLSSReady = false;
+ return;
+ }
+
+ m_Options = o;
+ if(m_Options == null)
+ {
+ Debug.LogWarning("null options given to DLSSIUpscaler()");
+ m_Options = (DLSSOptions)ScriptableObject.CreateInstance(typeof(DLSSOptions));
+ m_Options.UpscalerName = GetName();
+ }
+ if (string.IsNullOrEmpty(m_Options.UpscalerName))
+ {
+ Debug.LogWarning("options given with empty ID");
+ m_Options.UpscalerName = GetName();
+ }
+ m_QualityModeHistory = (DLSSQuality)m_Options.DLSSQualityMode;
+
+ m_OutputResolutionPrevious = new Vector2Int(0, 0);
+ m_InputResolution = new Vector2Int(1, 1);
+ m_OutputResolution = new Vector2Int(1, 1);
+ m_Jitter = new Vector2(0, 0);
+
+ m_DLSSReady = true;
+ }
+
+ public override string GetName()
+ {
+ return UPSCALER_NAME;
+ }
+ public override bool IsTemporalUpscaler() { return true; }
+ public override void CalculateJitter(int frameIndex, out Vector2 jitter, out bool allowScaling)
+ {
+ float upscaleRatio = (float)(m_OutputResolution.x) / m_InputResolution.x;
+ int numPhases = CalculateJitterPhaseCount(upscaleRatio);
+
+ int haltonIndex = (frameIndex % numPhases) + 1;
+ float x = HaltonSequence.Get(haltonIndex, 2) - 0.5f;
+ float y = HaltonSequence.Get(haltonIndex, 3) - 0.5f;
+
+ //Debug.LogFormat("haltonIndex: {0}\nframeIndex: {1}\njitter=({2}, {3})\nphases: {4}\nupscaleRatio: {5}", haltonIndex, frameIndex, x, y, numPhases, upscaleRatio);
+
+ jitter = new Vector2(x, y);
+ allowScaling = false;
+
+ m_Jitter = jitter;
+ }
+
+ public override void NegotiatePreUpscaleResolution(ref Vector2Int preUpscaleResolution, Vector2Int postUpscaleResolution)
+ {
+ if(m_Options.FixedResolutionMode)
+ {
+ Debug.Assert(GraphicsDevice.device != null);
+
+ DLSSQuality qualityMode = (DLSSQuality)m_Options.DLSSQualityMode;
+ GraphicsDevice.device.GetOptimalSettings(
+ (uint)postUpscaleResolution.x,
+ (uint)postUpscaleResolution.y,
+ qualityMode,
+ out OptimalDLSSSettingsData dlssOptimalData
+ );
+ preUpscaleResolution.x = (int)dlssOptimalData.outRenderWidth;
+ preUpscaleResolution.y = (int)dlssOptimalData.outRenderHeight;
+ }
+ }
+
+ static int CalculateJitterPhaseCount(float upscaleRatio)
+ {
+ const float basePhaseCount = 8.0f;
+ return (int)(basePhaseCount * upscaleRatio * upscaleRatio);
+ }
+
+ private bool ShouldResetDLSSContext(UpscalingIO io)
+ {
+ bool qualityChanged = m_QualityModeHistory != (DLSSQuality)m_Options.DLSSQualityMode;
+
+ bool presetChanged = m_PresetQualityHistory != (DLSSPreset)m_Options.DLSSRenderPresetQuality
+ || m_PresetBalancedHistory != (DLSSPreset)m_Options.DLSSRenderPresetBalanced
+ || m_PresetPerfHistory != (DLSSPreset)m_Options.DLSSRenderPresetPerformance
+ || m_PresetUltraPerfHistory != (DLSSPreset)m_Options.DLSSRenderPresetUltraPerformance
+ || m_PresetDLAAHistory != (DLSSPreset)m_Options.DLSSRenderPresetDLAA;
+
+ bool outputResolutionChanged = m_OutputResolutionPrevious != io.postUpscaleResolution;
+
+ bool nullContext = m_DLSSContext == null;
+
+ return nullContext || qualityChanged || presetChanged || outputResolutionChanged;
+ }
+
+ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
+ {
+ if(!m_DLSSReady)
+ return;
+
+ Debug.Assert(GraphicsDevice.device != null);
+
+ UpscalingIO io = frameData.Get();
+
+ m_InputResolution = io.preUpscaleResolution;
+ m_OutputResolution = io.postUpscaleResolution;
+
+ // describe output texture
+ TextureHandle outputColor;
+ {
+ TextureDesc inputDesc = io.cameraColor.GetDescriptor(renderGraph);
+ TextureDesc outputDesc = inputDesc;
+ outputDesc.width = io.postUpscaleResolution.x;
+ outputDesc.height = io.postUpscaleResolution.y;
+
+ outputDesc.format = GraphicsFormatUtility.GetLinearFormat(inputDesc.format);
+ outputDesc.msaaSamples = MSAASamples.None;
+ outputDesc.useMipMap = false;
+ outputDesc.autoGenerateMips = false;
+ outputDesc.useDynamicScale = false;
+ outputDesc.anisoLevel = 0;
+ outputDesc.discardBuffer = false;
+ outputDesc.enableRandomWrite = true; // compute shader resource
+ outputDesc.name = "_DLSSOutputTarget";
+ outputDesc.clearBuffer = false;
+ outputDesc.filterMode = FilterMode.Bilinear;
+ outputColor = renderGraph.CreateTexture(outputDesc);
+ }
+
+ using (var builder = renderGraph.AddUnsafePass("Deep Learning Super Sampling", out DLSSGraphData passData, new ProfilingSampler("DLSS")))
+ {
+ float motionVectorSign = io.motionVectorDirection == UpscalingIO.MotionVectorDirection.PreviousFrameToCurrentFrame ? -1.0f : 1.0f;
+ float motionVectorScaleX = io.motionVectorDomain == UpscalingIO.MotionVectorDomain.NDC ? io.motionVectorTextureSize.x : 1.0f;
+ float motionVectorScaleY = io.motionVectorDomain == UpscalingIO.MotionVectorDomain.NDC ? io.motionVectorTextureSize.y : 1.0f;
+
+ // setup pass data (UpscalingIO --> DLSSGraphData)
+ passData.shouldReinitializeContext = ShouldResetDLSSContext(io);
+
+ passData.execData.mvScaleX = motionVectorSign * motionVectorScaleX;
+ passData.execData.mvScaleY = motionVectorSign * motionVectorScaleY;
+ passData.execData.subrectOffsetX = 0;
+ passData.execData.subrectOffsetY = 0;
+ passData.execData.subrectWidth = (uint)io.preUpscaleResolution.x;
+ passData.execData.subrectHeight = (uint)io.preUpscaleResolution.y;
+ passData.execData.jitterOffsetX = m_Jitter.x;
+ passData.execData.jitterOffsetY = m_Jitter.y;
+ passData.execData.preExposure = Mathf.Clamp(io.preExposureValue, 0.20f, 2.0f); // clamp to a reasonable value to prevent ghosting
+ passData.execData.invertYAxis = io.flippedY ? 1u : 0u;
+ passData.execData.invertXAxis = io.flippedX ? 1u : 0u;
+ passData.execData.reset = io.resetHistory ? 1 : 0;
+
+ builder.UseTexture(io.cameraColor);
+ builder.UseTexture(io.cameraDepth);
+ builder.UseTexture(io.motionVectorColor);
+ builder.UseTexture(outputColor, AccessFlags.Write);
+ passData.colorInput = io.cameraColor;
+ passData.depth = io.cameraDepth;
+ passData.motionVectors = io.motionVectorColor;
+ passData.colorOutput = outputColor;
+
+ passData.colorInputSizeX = (uint)io.preUpscaleResolution.x;
+ passData.colorInputSizeY = (uint)io.preUpscaleResolution.y;
+ passData.colorOutputSizeX = (uint)io.postUpscaleResolution.x;
+ passData.colorOutputSizeY = (uint)io.postUpscaleResolution.y;
+ passData.motionVectorSizeX = (uint)io.motionVectorTextureSize.x;
+ passData.motionVectorSizeY = (uint)io.motionVectorTextureSize.y;
+ passData.invertedDepthBuffer = io.invertedDepth;
+ passData.inputIsHDR = io.hdrInput;
+ passData.motionVectorsAreJittered = io.jitteredMotionVectors;
+
+ // set render function
+ builder.SetRenderFunc((DLSSGraphData data, UnsafeGraphContext ctx) =>
+ {
+ CommandBuffer cmd = CommandBufferHelpers.GetNativeCommandBuffer(ctx.cmd);
+ if (data.shouldReinitializeContext)
+ {
+ if (m_DLSSContext != null)
+ {
+ DestroyContext(ref m_DLSSContext, cmd);
+ }
+ CreateContext(ref m_DLSSContext, cmd, ref data, ref m_Options);
+ }
+
+ Debug.Assert(m_DLSSContext != null);
+
+ m_DLSSContext.executeData = data.execData;
+ DLSSTextureTable textureTable = new()
+ {
+ colorInput = data.colorInput,
+ depth = data.depth,
+ motionVectors = data.motionVectors,
+ colorOutput = data.colorOutput,
+ };
+
+ GraphicsDevice.device.ExecuteDLSS(cmd, m_DLSSContext, textureTable);
+ });
+ }
+
+ io.cameraColor = outputColor;
+
+ // record history
+ m_OutputResolutionPrevious = io.postUpscaleResolution;
+ m_QualityModeHistory = (DLSSQuality)m_Options.DLSSQualityMode;
+ m_PresetQualityHistory = (DLSSPreset)m_Options.DLSSRenderPresetQuality;
+ m_PresetBalancedHistory = (DLSSPreset)m_Options.DLSSRenderPresetBalanced;
+ m_PresetPerfHistory = (DLSSPreset)m_Options.DLSSRenderPresetPerformance;
+ m_PresetUltraPerfHistory = (DLSSPreset)m_Options.DLSSRenderPresetUltraPerformance;
+ m_PresetDLAAHistory = (DLSSPreset)m_Options.DLSSRenderPresetDLAA;
+ }
+#endregion
+
+
+#region DATA
+ // static data
+ private bool m_DLSSReady = false;
+
+ DLSSOptions m_Options = null;
+ DLSSQuality m_QualityModeHistory = DLSSQuality.DLAA;
+ DLSSPreset m_PresetQualityHistory = DLSSPreset.Preset_Default;
+ DLSSPreset m_PresetBalancedHistory = DLSSPreset.Preset_Default;
+ DLSSPreset m_PresetPerfHistory = DLSSPreset.Preset_Default;
+ DLSSPreset m_PresetUltraPerfHistory = DLSSPreset.Preset_Default;
+ DLSSPreset m_PresetDLAAHistory = DLSSPreset.Preset_Default;
+
+ // per-view DLSS data (per camera / per use)
+ private DLSSContext m_DLSSContext = null;
+
+ private Vector2Int m_OutputResolutionPrevious;
+ private Vector2Int m_InputResolution;
+ private Vector2Int m_OutputResolution;
+ private Vector2 m_Jitter;
+ #endregion
+}
+
+#endif // ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSIUpscaler.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSIUpscaler.cs.meta
new file mode 100644
index 00000000000..b3ff6f41294
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSIUpscaler.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: ac8be94ed6c6df548a43cbac716f5147
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSOptions.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSOptions.cs
new file mode 100644
index 00000000000..41258437521
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSOptions.cs
@@ -0,0 +1,41 @@
+using UnityEngine;
+using UnityEngine.Experimental.Rendering;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.RenderGraphModule;
+#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
+using UnityEngine.NVIDIA;
+#endif
+using System;
+
+#if UNITY_EDITOR
+using UnityEditor;
+using UnityEditorInternal;
+#endif
+
+#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
+
+[Serializable]
+public class DLSSOptions : UpscalerOptions
+{
+ [EnumOption(typeof(DLSSQuality), "DLSS Quality Mode")]
+ public int DLSSQualityMode = (int)DLSSQuality.MaximumQuality;
+
+ [BoolOption("Force Quality Mode")]
+ public bool FixedResolutionMode = false;
+
+ // TODO: fix available preset values, currently all values are displayed.
+ // every preset have their own list of available presets, that may differ from each other.
+ // need a way to represent the available subset of enum values for each preset to enforce the value requirements.
+ [EnumOption(typeof(DLSSPreset), "DLSS Preset for Quality")]
+ public int DLSSRenderPresetQuality;
+ [EnumOption(typeof(DLSSPreset), "DLSS Preset for Balanced")]
+ public int DLSSRenderPresetBalanced;
+ [EnumOption(typeof(DLSSPreset), "DLSS Preset for Performance")]
+ public int DLSSRenderPresetPerformance;
+ [EnumOption(typeof(DLSSPreset), "DLSS Preset for Ultra Performance")]
+ public int DLSSRenderPresetUltraPerformance;
+ [EnumOption(typeof(DLSSPreset), "DLSS Preset for DLAA")]
+ public int DLSSRenderPresetDLAA;
+}
+
+#endif // ENABLE_UPSCALER_FRAMEWORK && ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSOptions.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSOptions.cs.meta
new file mode 100644
index 00000000000..65493bc006d
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/DLSSOptions.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: dffd75c6cf5e26843be8893fada27a36
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2IUpscaler.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2IUpscaler.cs
new file mode 100644
index 00000000000..e7023ea894a
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2IUpscaler.cs
@@ -0,0 +1,304 @@
+using UnityEngine;
+using UnityEngine.Experimental.Rendering;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.RenderGraphModule;
+#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
+using UnityEngine.AMD;
+#endif
+using System;
+
+
+#if UNITY_EDITOR
+using UnityEditor;
+#endif
+
+#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
+
+#if UNITY_EDITOR
+[InitializeOnLoad]
+#endif
+static class RegisterFSR2
+{
+ static RegisterFSR2() => UpscalerRegistry.Register(FSR2IUpscaler.UPSCALER_NAME);
+
+ [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
+ static void InitRuntime() => UpscalerRegistry.Register(FSR2IUpscaler.UPSCALER_NAME);
+}
+
+public class FSR2IUpscaler : AbstractUpscaler
+{
+ public static readonly string UPSCALER_NAME = "FSR2 (IUpscaler)";
+
+#region FSR2_UTILITIES
+ static bool CheckFSR2FeatureAvailable()
+ {
+ // check plugin availability
+ if (!UnityEngine.AMD.AMDUnityPlugin.IsLoaded())
+ {
+ Debug.LogWarning("AMDUnityPlugin not loaded.");
+ return false;
+ }
+
+ // check plugin version
+ // if (s_ExpectedDeviceVersion != UnityEngine.AMD.GraphicsDevice.version)
+ // {
+ // Debug.LogWarning("Cannot instantiate AMD device because the version HDRP expects does not match the backend version.");
+ // return false;
+ // }
+
+ // check device
+ UnityEngine.AMD.GraphicsDevice device = UnityEngine.AMD.GraphicsDevice.CreateGraphicsDevice();
+ if (device == null)
+ {
+ Debug.LogWarning("AMDUnityPlugin failed to create device.");
+ return false;
+ }
+
+ return true;
+ }
+ static void DestroyContext(ref FSR2Context ctx, CommandBuffer cmd)
+ {
+ GraphicsDevice.device.DestroyFeature(cmd, ctx);
+ ctx = null;
+ }
+ static void CreateContext(ref FSR2Context ctx, CommandBuffer cmd, ref FSR2GraphData data)
+ {
+ bool displayResolutionMotionVectors = data.motionVectorSizeX == data.colorOutputSizeX && data.motionVectorSizeY == data.colorOutputSizeY;
+
+ FSR2CommandInitializationData settings = new();
+ settings.SetFlag(FfxFsr2InitializationFlags.EnableHighDynamicRange, data.inputIsHDR);
+ settings.SetFlag(FfxFsr2InitializationFlags.EnableDisplayResolutionMotionVectors, displayResolutionMotionVectors);
+ settings.SetFlag(FfxFsr2InitializationFlags.DepthInverted, data.invertedDepthBuffer);
+ settings.SetFlag(FfxFsr2InitializationFlags.EnableMotionVectorsJitterCancellation, data.motionVectorsAreJittered);
+ settings.maxRenderSizeWidth = data.colorInputSizeX;
+ settings.maxRenderSizeHeight = data.colorInputSizeY;
+ settings.displaySizeWidth = data.colorOutputSizeX;
+ settings.displaySizeHeight = data.colorOutputSizeY;
+ ctx = GraphicsDevice.device.CreateFeature(cmd, settings);
+ }
+#endregion // FSR2_UTILITIES
+
+
+#region RENDERGRAPH_INTERFACE_DATA
+ class FSR2GraphData
+ {
+ public bool shouldReinitializeContext;
+
+ public uint colorInputSizeX;
+ public uint colorInputSizeY;
+ public uint colorOutputSizeX;
+ public uint colorOutputSizeY;
+ public uint motionVectorSizeX;
+ public uint motionVectorSizeY;
+ public bool invertedDepthBuffer;
+ public bool inputIsHDR;
+ public bool motionVectorsAreJittered;
+
+ public FSR2CommandExecutionData execData;
+ public TextureHandle colorInput;
+ public TextureHandle depth;
+ public TextureHandle motionVectors;
+ public TextureHandle colorOutput;
+ };
+#endregion
+
+#region IUPSCALER_INTERFACE
+ public FSR2IUpscaler(FSR2Options o)
+ {
+ if(!CheckFSR2FeatureAvailable())
+ {
+ m_FSR2Ready = false;
+ return;
+ }
+
+ m_Options = o;
+
+ m_OutputResolutionPrevious = new Vector2Int(0, 0);
+ m_InputResolution = new Vector2Int(1, 1);
+ m_OutputResolution = new Vector2Int(1, 1);
+ m_Jitter = new Vector2(0, 0);
+
+ m_FSR2Ready = true;
+ }
+
+ public override string GetName()
+ {
+ return UPSCALER_NAME;
+ }
+ public override bool IsTemporalUpscaler() { return true; }
+
+ public override void CalculateJitter(int frameIndex, out Vector2 jitter, out bool allowScaling)
+ {
+ float upscaleRatio = (float)(m_OutputResolution.x) / m_InputResolution.x;
+ int numPhases = CalculateJitterPhaseCount(upscaleRatio);
+
+ int haltonIndex = (frameIndex % numPhases) + 1;
+ float x = HaltonSequence.Get(haltonIndex, 2) - 0.5f;
+ float y = HaltonSequence.Get(haltonIndex, 3) - 0.5f;
+
+ jitter = new Vector2(x, y);
+ allowScaling = false;
+
+ m_Jitter = jitter;
+ }
+
+ static int CalculateJitterPhaseCount(float upscaleRatio)
+ {
+ const float basePhaseCount = 8.0f;
+ return (int)(basePhaseCount * upscaleRatio * upscaleRatio);
+ }
+
+ private bool ShouldResetFSR2Context(UpscalingIO io)
+ {
+ bool nullContext = m_FSR2Context == null;
+ bool outputResolutionChanged = m_OutputResolutionPrevious != io.postUpscaleResolution;
+
+ return nullContext || outputResolutionChanged;
+ }
+
+ public override void NegotiatePreUpscaleResolution(ref Vector2Int preUpscaleResolution, Vector2Int postUpscaleResolution)
+ {
+ if (m_Options.FixedResolutionMode)
+ {
+ Debug.Assert(GraphicsDevice.device != null);
+
+ FSR2Quality qualityMode = (FSR2Quality)m_Options.FSR2QualityMode;
+ GraphicsDevice.device.GetRenderResolutionFromQualityMode(qualityMode,
+ (uint)postUpscaleResolution.x,
+ (uint)postUpscaleResolution.y,
+ out uint renderResoolutionX,
+ out uint renderResoolutionY
+ );
+ preUpscaleResolution.x = (int)renderResoolutionX;
+ preUpscaleResolution.y = (int)renderResoolutionY;
+ }
+ }
+
+ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData)
+ {
+ if(!m_FSR2Ready)
+ return;
+
+ Debug.Assert(GraphicsDevice.device != null);
+
+ UpscalingIO io = frameData.Get();
+
+ m_InputResolution = io.preUpscaleResolution;
+ m_OutputResolution = io.postUpscaleResolution;
+
+ // describe output texture
+ TextureHandle outputColor;
+ {
+ TextureDesc inputDesc = io.cameraColor.GetDescriptor(renderGraph);
+ TextureDesc outputDesc = inputDesc;
+ outputDesc.width = io.postUpscaleResolution.x;
+ outputDesc.height = io.postUpscaleResolution.y;
+
+ outputDesc.format = GraphicsFormatUtility.GetLinearFormat(inputDesc.format);
+ outputDesc.msaaSamples = MSAASamples.None;
+ outputDesc.useMipMap = false;
+ outputDesc.autoGenerateMips = false;
+ outputDesc.useDynamicScale = false;
+ outputDesc.anisoLevel = 0;
+ outputDesc.discardBuffer = false;
+ outputDesc.enableRandomWrite = true; // compute shader resource
+ outputDesc.name = "_FSR2OutputTarget";
+ outputDesc.clearBuffer = false;
+ outputDesc.filterMode = FilterMode.Bilinear;
+ outputColor = renderGraph.CreateTexture(outputDesc);
+ }
+
+ using (var builder = renderGraph.AddUnsafePass("FidelityFX Super Resolution 2", out FSR2GraphData passData, new ProfilingSampler("FSR2")))
+ {
+ float motionVectorSign = io.motionVectorDirection == UpscalingIO.MotionVectorDirection.PreviousFrameToCurrentFrame ? -1.0f : 1.0f;
+ float motionVectorScaleX = io.motionVectorDomain == UpscalingIO.MotionVectorDomain.NDC ? io.motionVectorTextureSize.x : 1.0f;
+ float motionVectorScaleY = io.motionVectorDomain == UpscalingIO.MotionVectorDomain.NDC ? io.motionVectorTextureSize.y : 1.0f;
+
+ // setup pass data (UpscalingIO --> FSR2GraphData)
+ passData.shouldReinitializeContext = ShouldResetFSR2Context(io);
+
+ passData.execData.enableSharpening = m_Options.EnableSharpening ? 1 : 0;
+ passData.execData.sharpness = m_Options.Sharpness;
+ passData.execData.MVScaleX = motionVectorSign * motionVectorScaleX;
+ passData.execData.MVScaleY = motionVectorSign * motionVectorScaleY;
+ passData.execData.renderSizeWidth = (uint)io.preUpscaleResolution.x;
+ passData.execData.renderSizeHeight = (uint)io.preUpscaleResolution.y;
+ passData.execData.jitterOffsetX = m_Jitter.x;
+ passData.execData.jitterOffsetY = m_Jitter.y;
+ passData.execData.cameraNear = io.nearClipPlane;
+ passData.execData.cameraFar = io.farClipPlane;
+ passData.execData.cameraFovAngleVertical = 2.0f * (float)Math.PI * (1 / 360.0f) * io.fieldOfViewDegrees; // radians
+ passData.execData.preExposure = 1.0f; // Mathf.Clamp(io.preExposureValue, 0.20f, 2.0f); // clamp to a reasonable value to prevent ghosting
+ passData.execData.frameTimeDelta = io.deltaTime * 1000.0f; // in milliseconds
+ passData.execData.reset = io.resetHistory ? 1 : 0;
+
+ builder.UseTexture(io.cameraColor);
+ builder.UseTexture(io.cameraDepth);
+ builder.UseTexture(io.motionVectorColor);
+ builder.UseTexture(outputColor, AccessFlags.Write);
+ passData.colorInput = io.cameraColor;
+ passData.depth = io.cameraDepth;
+ passData.motionVectors = io.motionVectorColor;
+ passData.colorOutput = outputColor;
+
+ passData.colorInputSizeX = (uint)io.preUpscaleResolution.x;
+ passData.colorInputSizeY = (uint)io.preUpscaleResolution.y;
+ passData.colorOutputSizeX = (uint)io.postUpscaleResolution.x;
+ passData.colorOutputSizeY = (uint)io.postUpscaleResolution.y;
+ passData.motionVectorSizeX = (uint)io.motionVectorTextureSize.x;
+ passData.motionVectorSizeY = (uint)io.motionVectorTextureSize.y;
+ passData.invertedDepthBuffer = io.invertedDepth;
+ passData.inputIsHDR = io.hdrInput;
+ passData.motionVectorsAreJittered = io.jitteredMotionVectors;
+
+ // set render function
+ builder.SetRenderFunc((FSR2GraphData data, UnsafeGraphContext ctx) =>
+ {
+ CommandBuffer cmd = CommandBufferHelpers.GetNativeCommandBuffer(ctx.cmd);
+ if (data.shouldReinitializeContext)
+ {
+ if (m_FSR2Context != null)
+ {
+ DestroyContext(ref m_FSR2Context, cmd);
+ }
+ CreateContext(ref m_FSR2Context, cmd, ref data);
+ }
+
+ Debug.Assert(m_FSR2Context != null);
+
+ m_FSR2Context.executeData = data.execData;
+ FSR2TextureTable textureTable = new()
+ {
+ colorInput = data.colorInput,
+ depth = data.depth,
+ motionVectors = data.motionVectors,
+ colorOutput = data.colorOutput,
+ };
+
+ GraphicsDevice.device.ExecuteFSR2(cmd, m_FSR2Context, textureTable);
+ });
+ }
+
+ io.cameraColor = outputColor;
+
+ m_OutputResolutionPrevious = io.postUpscaleResolution;
+ }
+#endregion
+
+
+#region DATA
+ // static data
+ private bool m_FSR2Ready = false;
+
+ // per-view FSR2 data (per camera / per use)
+ private FSR2Context m_FSR2Context = null;
+ private FSR2Options m_Options = null;
+
+ private Vector2Int m_OutputResolutionPrevious;
+ private Vector2Int m_InputResolution;
+ private Vector2Int m_OutputResolution;
+ private Vector2 m_Jitter;
+ #endregion
+}
+
+#endif // ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2IUpscaler.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2IUpscaler.cs.meta
new file mode 100644
index 00000000000..e71ad324a91
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2IUpscaler.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: be41240ee7c09d949b3575ef8d2ad8c9
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2Options.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2Options.cs
new file mode 100644
index 00000000000..e3f4bb4d95b
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2Options.cs
@@ -0,0 +1,34 @@
+using UnityEngine;
+using UnityEngine.Experimental.Rendering;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.RenderGraphModule;
+#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
+using UnityEngine.AMD;
+#endif
+using System;
+
+
+#if UNITY_EDITOR
+using UnityEditor;
+#endif
+
+#if ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
+
+[Serializable]
+public class FSR2Options : UpscalerOptions
+{
+ [EnumOption(typeof(FSR2Quality), "FSR2 Quality Mode")]
+ public int FSR2QualityMode = (int)FSR2Quality.Quality;
+
+ [BoolOption("Fixed Resolution")]
+ public bool FixedResolutionMode = false;
+
+ [BoolOption("Enable Sharpening")]
+ public bool EnableSharpening = false;
+
+ [FloatOption(0.0f, 1.0f, "Sharpness")]
+ public float Sharpness = 0.92f;
+};
+
+
+#endif // ENABLE_UPSCALER_FRAMEWORK && ENABLE_AMD && ENABLE_AMD_MODULE
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2Options.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2Options.cs.meta
new file mode 100644
index 00000000000..f27c71cb498
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/FSR2Options.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1b516656c1bb6634192a33e967e54491
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscaler.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscaler.cs
new file mode 100644
index 00000000000..c4fc99474f9
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscaler.cs
@@ -0,0 +1,195 @@
+#if ENABLE_UPSCALER_FRAMEWORK
+using System;
+using UnityEditor;
+using UnityEngine.Rendering.RenderGraphModule;
+
+namespace UnityEngine.Rendering
+{
+ ///
+ /// Defines the essential contract for any upscaling technology.
+ ///
+ public interface IUpscaler : IRenderGraphRecorder
+ {
+ ///
+ /// Gets the display name of the upscaler (e.g., "FSR2").
+ ///
+ string GetName();
+
+ ///
+ /// Gets the options for this particular upscaler.
+ ///
+ UpscalerOptions GetOptions();
+
+ ///
+ /// Returns true if the upscaler uses temporal information from previous frames.
+ ///
+ bool IsTemporalUpscaler();
+
+ ///
+ /// Returns true if the upscaler supports XR rendering.
+ ///
+ bool IsSupportedXR();
+
+
+ ///
+ /// Calculates the pixel jitter for the current frame.
+ ///
+ void CalculateJitter(int frameIndex, out Vector2 jitter, out bool allowScaling);
+
+ ///
+ /// Determines the render resolution based on display resolution and optional internal state or options.
+ ///
+ void NegotiatePreUpscaleResolution(ref Vector2Int preUpscaleResolution, Vector2Int postUpscaleResolution);
+ }
+
+ public abstract class AbstractUpscaler : IUpscaler
+ {
+ public abstract string GetName();
+ public abstract bool IsTemporalUpscaler();
+
+ public virtual UpscalerOptions GetOptions() { return null; }
+ public virtual bool IsSupportedXR() { return false; }
+ public virtual void NegotiatePreUpscaleResolution(ref Vector2Int preUpscaleResolution, Vector2Int postUpscaleResolution) {}
+ public virtual void CalculateJitter(int frameIndex, out Vector2 jitter, out bool allowScaling)
+ {
+ jitter = -STP.Jit16(frameIndex);
+ allowScaling = false;
+ }
+
+ public virtual void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData) { }
+ }
+
+ public class UpscalingIO : ContextItem
+ {
+ // Upscalers like DLSS & FSR expect screen space values representing motion
+ // from _current frame to previous frame_. SRPs can have different configurations
+ // for motion vectors than the requirements, so we need to specify to the upscaler
+ // inputs on how to treat the values in the MV textures. They usually include a scaling
+ // factor which can be derived from the enums below.
+ public enum MotionVectorDomain
+ {
+ NDC, // [-1, 1] for X & Y
+ ScreenSpace, // [-W, W] for X, [-H, H] for Y
+ };
+ public enum MotionVectorDirection
+ {
+ PreviousFrameToCurrentFrame,
+ CurrentFrameToPreviousFrame
+ };
+
+ // -------------------------------------------------------
+ // TEXTURE I/O
+ // -------------------------------------------------------
+ public TextureHandle cameraColor;
+ public TextureHandle cameraDepth;
+ public TextureHandle motionVectorColor;
+ public TextureHandle exposureTexture;
+ public Vector2Int preUpscaleResolution;
+ public Vector2Int previousPreUpscaleResolution;
+ public Vector2Int postUpscaleResolution;
+ public bool enableTexArray;
+ public bool invertedDepth; // near plane: 1.0f, far plane: 0.0f
+ public bool flippedY; // upside down
+ public bool flippedX; // right to left
+ public bool hdrInput;
+ public Vector2Int motionVectorTextureSize;
+ public MotionVectorDomain motionVectorDomain;
+ public MotionVectorDirection motionVectorDirection;
+ public bool jitteredMotionVectors;
+ public Texture2D[] blueNoiseTextureSet;
+
+ // -------------------------------------------------------
+ // CAMERA
+ // -------------------------------------------------------
+ public int cameraInstanceID;
+ public float nearClipPlane;
+ public float farClipPlane;
+ public float fieldOfViewDegrees;
+ public int numActiveViews;
+ public int eyeIndex;
+ public Vector3[] worldSpaceCameraPositions;
+ public Vector3[] previousWorldSpaceCameraPositions;
+ public Vector3[] previousPreviousWorldSpaceCameraPositions;
+ public Matrix4x4[] projectionMatrices;
+ public Matrix4x4[] previousProjectionMatrices;
+ public Matrix4x4[] previousPreviousProjectionMatrices;
+ public Matrix4x4[] viewMatrices;
+ public Matrix4x4[] previousViewMatrices;
+ public Matrix4x4[] previousPreviousViewMatrices;
+
+ // Some implementations (HDRP) has the exposure value pre-applied
+ // to the lighting accumulation buffer as opposed to doing exposure
+ // in tonemapper. Some upscalers (DLSS/FSR) need to know about this
+ // exposure value used in the (previous) color input so that it can properly
+ // construct the current frame without ghosting artifacts while ignoring
+ // the exposure texture input listed above. This value is usually obtained
+ // by a CPU readback on the 1x1 exposure texture.
+ public float preExposureValue;
+
+ // Some upscalers can't support HDR color gamuts.
+ // Therefore, use HDRDisplayInformation to temporarily convert to SDR.
+ public HDROutputUtils.HDRDisplayInformation hdrDisplayInformation;
+
+ // -------------------------------------------------------
+ // TIME
+ // -------------------------------------------------------
+ public bool resetHistory;
+ public int frameIndex;
+ public float deltaTime;
+ public float previousDeltaTime;
+
+ // -------------------------------------------------------
+ // MISC
+ // -------------------------------------------------------
+ public bool enableMotionScaling;
+ public bool enableHwDrs;
+
+ public override void Reset()
+ {
+ cameraColor = TextureHandle.nullHandle;
+ cameraDepth = TextureHandle.nullHandle;
+ motionVectorColor = TextureHandle.nullHandle;
+ exposureTexture = TextureHandle.nullHandle;
+ preUpscaleResolution = new();
+ previousPreUpscaleResolution = new();
+ postUpscaleResolution = new();
+ enableTexArray = false;
+ invertedDepth = false;
+ flippedX = false;
+ flippedY = false;
+ hdrInput = false;
+ motionVectorTextureSize = new();
+ motionVectorDomain = MotionVectorDomain.NDC;
+ motionVectorDirection = MotionVectorDirection.PreviousFrameToCurrentFrame;
+ jitteredMotionVectors = false;
+ blueNoiseTextureSet = null;
+
+ cameraInstanceID = -1;
+ nearClipPlane = 0f;
+ farClipPlane = 0f;
+ fieldOfViewDegrees = 0f;
+ numActiveViews = 0;
+ eyeIndex = 0;
+ worldSpaceCameraPositions = Array.Empty();
+ previousWorldSpaceCameraPositions = Array.Empty();
+ previousPreviousWorldSpaceCameraPositions = Array.Empty();
+ projectionMatrices = Array.Empty();
+ previousProjectionMatrices = Array.Empty();
+ previousPreviousProjectionMatrices = Array.Empty();
+ viewMatrices = Array.Empty();
+ previousViewMatrices = Array.Empty();
+ previousPreviousViewMatrices = Array.Empty();
+ preExposureValue = 1.0f;
+ hdrDisplayInformation = new HDROutputUtils.HDRDisplayInformation();
+
+ resetHistory = true;
+ frameIndex = 0;
+ deltaTime = 0f;
+ previousDeltaTime = 0f;
+
+ enableMotionScaling = false;
+ enableHwDrs = false;
+ }
+ }
+}
+#endif
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscaler.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscaler.cs.meta
new file mode 100644
index 00000000000..536ba8d6f8e
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscaler.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 80c8d7b6f99b7a34eba11304141760a1
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscalerOptions.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscalerOptions.cs
new file mode 100644
index 00000000000..1553d21d07e
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscalerOptions.cs
@@ -0,0 +1,546 @@
+#if ENABLE_UPSCALER_FRAMEWORK
+using System;
+using System.Collections.Generic;
+using System.Reflection;
+using UnityEditor;
+using UnityEngine.Scripting;
+using static UnityEngine.Rendering.DynamicResolutionHandler;
+
+namespace UnityEngine.Rendering
+{
+#nullable enable
+ #region Attributes
+
+ ///
+ /// Base class for all custom option attributes.
+ /// UpscalerOptions attributes facilitate GUI rendering for a given option by sepcifying its type, range of values and display label.
+ ///
+ public abstract class BaseOptionAttribute : PropertyAttribute // Using PropertyAttribute for Unity Editor integration
+ {
+ public string? DisplayName { get; protected set; }
+
+ protected BaseOptionAttribute(string? displayName = null)
+ {
+ DisplayName = displayName;
+ }
+ }
+
+
+ ///
+ /// Marks an int field as representing an enum value.
+ ///
+ [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
+ public class EnumOptionAttribute : BaseOptionAttribute
+ {
+ public Type EnumType { get; private set; }
+
+ public EnumOptionAttribute(Type enumType, string? displayName = null) : base(displayName)
+ {
+ if (enumType == null || !enumType.IsEnum)
+ {
+ throw new ArgumentException("EnumType must be a valid Enum type.", nameof(enumType));
+ }
+ EnumType = enumType;
+ }
+ }
+
+ ///
+ /// Marks a float field as an option.
+ ///
+ [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
+ public class FloatOptionAttribute : BaseOptionAttribute
+ {
+ public float Min { get; private set; }
+ public float Max { get; private set; }
+ public bool HasRange { get; private set; } // Indicates if min/max were explicitly set
+ public FloatOptionAttribute(string? displayName = null) : base(displayName)
+ {
+ HasRange = false;
+ Min = 0f; // Default, will be ignored if HasRange is false
+ Max = 0f;
+ }
+ public FloatOptionAttribute(float min, float max, string? displayName = null) : base(displayName)
+ {
+ HasRange = true;
+ Min = min;
+ Max = max;
+ }
+ }
+
+ ///
+ /// Marks an int field as an option.
+ ///
+ [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
+ public class IntOptionAttribute : BaseOptionAttribute
+ {
+ public int Min { get; private set; }
+ public int Max { get; private set; }
+ public bool HasRange { get; private set; } // Indicates if min/max were explicitly set
+
+ // Constructor for int without range
+ public IntOptionAttribute(string? displayName = null) : base(displayName)
+ {
+ HasRange = false;
+ Min = 0; // Default
+ Max = 0;
+ }
+
+ // Constructor for int with range
+ public IntOptionAttribute(int min, int max, string? displayName = null) : base(displayName)
+ {
+ HasRange = true;
+ Min = min;
+ Max = max;
+ }
+ }
+
+ ///
+ /// Marks a boolean field as an option.
+ ///
+ [AttributeUsage(AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
+ public class BoolOptionAttribute : BaseOptionAttribute
+ {
+ public BoolOptionAttribute(string? displayName = null) : base(displayName) { }
+ }
+ #endregion
+
+ #region OptionsBase
+ ///
+ /// Represents a single configurable option that can be read from and written to.
+ ///
+ public interface IOption
+ {
+ string Id { get; } // A unique identifier for the option (e.g., field name)
+ string DisplayName { get; } // A user-friendly name for the option
+ Type ValueType { get; } // The actual C# type of the option's value (e.g., typeof(float), typeof(DLSSQuality))
+
+ abstract object? GetValue(object targetInstance);
+ abstract void SetValue(object targetInstance, object? newValue);
+ }
+
+ ///
+ /// Represents an option whose value is an enum.
+ ///
+ public interface IEnumOption : IOption
+ {
+ Type EnumType { get; } // The specific enum Type (e.g., typeof(DLSSQuality))
+ Array GetEnumValues(); // Returns an array of the actual enum values
+ string[] GetEnumNames(); // Returns an array of the enum names (for display)
+ }
+
+ ///
+ /// Represents a numeric option that has a defined minimum and maximum value.
+ ///
+ public interface IRangeOption : IOption
+ {
+ float MinValue { get; } // Using float for generics, int ranges will cast
+ float MaxValue { get; } // Using float for generics, int ranges will cast
+ bool HasRange { get; } // True if a min/max was explicitly set
+ }
+
+
+ ///
+ /// Abstract base class for option implementations, handles common properties.
+ ///
+ internal abstract class OptionBase : IOption
+ {
+ protected readonly FieldInfo _fieldInfo;
+
+ public string Id { get; private set; }
+ public string DisplayName { get; private set; }
+ public abstract Type ValueType { get; }
+
+ protected OptionBase(FieldInfo fieldInfo, string displayName)
+ {
+ _fieldInfo = fieldInfo ?? throw new ArgumentNullException(nameof(fieldInfo));
+ Id = fieldInfo.Name;
+ DisplayName = displayName;
+ }
+
+ public virtual object? GetValue(object targetInstance)
+ {
+ if (targetInstance == null || !_fieldInfo.DeclaringType!.IsAssignableFrom(targetInstance.GetType()))
+ {
+ throw new ArgumentException($"Target instance is not compatible with option's field type. Expected {_fieldInfo.DeclaringType.Name}, got {targetInstance?.GetType().Name}.", nameof(targetInstance));
+ }
+ return _fieldInfo.GetValue(targetInstance);
+ }
+
+ public virtual void SetValue(object targetInstance, object? newValue)
+ {
+ if (targetInstance == null || !_fieldInfo.DeclaringType!.IsAssignableFrom(targetInstance.GetType()))
+ {
+ throw new ArgumentException($"Target instance is not compatible with option's field type. Expected {_fieldInfo.DeclaringType.Name}, got {targetInstance?.GetType().Name}.", nameof(targetInstance));
+ }
+ _fieldInfo.SetValue(targetInstance, newValue);
+ }
+ }
+ #endregion
+
+
+ #region TypedOptions
+ ///
+ /// Represents an integer option backed by an enum.
+ ///
+ internal class EnumIntOption : OptionBase, IEnumOption
+ {
+ public Type EnumType { get; private set; }
+
+ public override Type ValueType => EnumType;
+
+ public EnumIntOption(FieldInfo fieldInfo, string displayName, Type enumType)
+ : base(fieldInfo, displayName)
+ {
+ if (!enumType.IsEnum)
+ {
+ throw new ArgumentException($"Provided type '{enumType.Name}' is not an enum.", nameof(enumType));
+ }
+ if (fieldInfo.FieldType != typeof(int))
+ {
+ throw new ArgumentException($"EnumIntOption can only wrap int fields. Field '{fieldInfo.Name}' is of type '{fieldInfo.FieldType.Name}'.", nameof(fieldInfo));
+ }
+ EnumType = enumType;
+ }
+
+ public override object? GetValue(object targetInstance)
+ {
+ int intValue = (int)(base.GetValue(targetInstance) ?? 0); // Handle potential null for value types
+ return Enum.ToObject(EnumType, intValue);
+ }
+
+ public override void SetValue(object targetInstance, object? newValue)
+ {
+ if (newValue != null && newValue.GetType() != EnumType)
+ {
+ throw new ArgumentException($"Cannot set EnumIntOption '{DisplayName}': value type mismatch. Expected '{EnumType.Name}', got '{newValue?.GetType().Name}'.", nameof(newValue));
+ }
+ base.SetValue(targetInstance, Convert.ToInt32(newValue));
+ }
+
+ public Array GetEnumValues() => Enum.GetValues(EnumType);
+ public string[] GetEnumNames() => Enum.GetNames(EnumType);
+ }
+
+ ///
+ /// Represents a boolean option.
+ ///
+ internal class BoolOption : OptionBase
+ {
+ public override Type ValueType => typeof(bool);
+
+ public BoolOption(FieldInfo fieldInfo, string displayName)
+ : base(fieldInfo, displayName)
+ {
+ if (fieldInfo.FieldType != typeof(bool))
+ {
+ throw new ArgumentException($"BoolOption can only wrap bool fields. Field '{fieldInfo.Name}' is of type '{fieldInfo.FieldType.Name}'.", nameof(fieldInfo));
+ }
+ }
+ }
+
+ ///
+ /// Represents a float option, with an optional min/max range.
+ ///
+ internal class FloatOption : OptionBase, IRangeOption
+ {
+ public override Type ValueType => typeof(float);
+ public float MinValue { get; private set; }
+ public float MaxValue { get; private set; }
+ public bool HasRange { get; private set; }
+
+ public FloatOption(FieldInfo fieldInfo, string displayName, float min, float max, bool hasRange)
+ : base(fieldInfo, displayName)
+ {
+ if (fieldInfo.FieldType != typeof(float))
+ {
+ throw new ArgumentException($"FloatOption can only wrap float fields. Field '{fieldInfo.Name}' is of type '{fieldInfo.FieldType.Name}'.", nameof(fieldInfo));
+ }
+ MinValue = min;
+ MaxValue = max;
+ HasRange = hasRange;
+ }
+ }
+
+ ///
+ /// Represents an int option, with an optional min/max range.
+ ///
+ internal class IntOption : OptionBase, IRangeOption
+ {
+ public override Type ValueType => typeof(int);
+ public float MinValue { get; private set; } // Storing as float, will cast to int when used
+ public float MaxValue { get; private set; } // Storing as float, will cast to int when used
+ public bool HasRange { get; private set; }
+
+ public IntOption(FieldInfo fieldInfo, string displayName, int min, int max, bool hasRange)
+ : base(fieldInfo, displayName)
+ {
+ if (fieldInfo.FieldType != typeof(int))
+ {
+ throw new ArgumentException($"IntOption can only wrap int fields. Field '{fieldInfo.Name}' is of type '{fieldInfo.FieldType.Name}'.", nameof(fieldInfo));
+ }
+ MinValue = min;
+ MaxValue = max;
+ HasRange = hasRange;
+ }
+ }
+
+ #endregion
+
+ #region OptionsRegistry
+ ///
+ /// Provides methods to generically inspect UpscalerOptions instances
+ /// and retrieve their configurable options.
+ ///
+ public static class UpscalerOptionsRegistry
+ {
+ // Cached reflection results
+ private static readonly Dictionary> s_CachedOptions = new();
+
+#if UNITY_EDITOR
+ ///
+ /// Discovers and returns all configurable options for a given UpscalerOptions instance.
+ /// This method uses reflection and caches results for performance.
+ ///
+ /// The UpscalerOptions instance to inspect.
+ /// A list of IOption objects representing the configurable options.
+ [Preserve] // Prevent IL2CPP stripping if attributes/reflection are only used by this.
+ public static IReadOnlyList GetConfigurableOptions(UpscalerOptions optionsInstance)
+ {
+ if (optionsInstance == null)
+ {
+ Debug.LogWarning("GetConfigurableOptions called with a null options instance.");
+ return new List();
+ }
+
+ Type optionsType = optionsInstance.GetType();
+
+ // Use cached metadata if available
+ if (s_CachedOptions.TryGetValue(optionsType, out var optionsList))
+ {
+ return optionsList;
+ }
+
+ // Otherwise, perform reflection and build the metadata
+ List discoveredOptions = new List();
+
+ // Get all instance fields, both public and non-public (for [SerializeField] private fields)
+ FieldInfo[] fields = optionsType.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
+
+ foreach (FieldInfo field in fields)
+ {
+ // Check for our custom option attributes
+ BaseOptionAttribute? attr = field.GetCustomAttribute(true);
+
+ if (attr == null) continue; // Not an option we care about
+
+ // Determine the display name, prioritizing the one from the attribute
+ string displayName = attr.DisplayName ?? ObjectNames.NicifyVariableName(field.Name);
+
+ // Create the appropriate IOption wrapper based on the attribute type
+ if (attr is EnumOptionAttribute enumAttr)
+ {
+ discoveredOptions.Add(new EnumIntOption(field, displayName, enumAttr.EnumType));
+ }
+ else if (attr is FloatOptionAttribute floatAttr)
+ {
+ discoveredOptions.Add(new FloatOption(field, displayName, floatAttr.Min, floatAttr.Max, floatAttr.HasRange));
+ }
+ else if (attr is IntOptionAttribute intAttr)
+ {
+ discoveredOptions.Add(new IntOption(field, displayName, intAttr.Min, intAttr.Max, intAttr.HasRange));
+ }
+ else if (attr is BoolOptionAttribute)
+ {
+ discoveredOptions.Add(new BoolOption(field, displayName));
+ }
+ else
+ {
+ Debug.LogWarning($"Unhandled BaseOptionAttribute type for field '{field.Name}' in '{optionsType.Name}': {attr.GetType().Name}.");
+ }
+ }
+
+ // Cache and return
+ s_CachedOptions[optionsType] = discoveredOptions;
+ return discoveredOptions;
+ }
+
+ ///
+ /// Finds a specific option by its ID (field name).
+ ///
+ /// The UpscalerOptions instance.
+ /// The ID (field name) of the option to find.
+ /// The IOption object if found, otherwise null.
+ public static IOption? GetOptionById(UpscalerOptions optionsInstance, string optionId)
+ {
+ foreach(IOption opt in GetConfigurableOptions(optionsInstance))
+ {
+ if (opt.Id == optionId)
+ return opt;
+ }
+ return null;
+ }
+#endif
+ };
+ #endregion
+
+
+ [Serializable]
+ public class UpscalerOptions : ScriptableObject
+ {
+ public string UpscalerName
+ {
+ get => m_UpscalerName;
+ set => m_UpscalerName = value;
+ }
+
+ public UpsamplerScheduleType InjectionPoint
+ {
+ get => m_InjectionPoint;
+ set => m_InjectionPoint = value;
+ }
+
+ [SerializeField] private string m_UpscalerName = "";
+ [SerializeField] private UpsamplerScheduleType m_InjectionPoint = UpsamplerScheduleType.BeforePost;
+
+
+#if UNITY_EDITOR
+ public bool DrawOptionsEditorGUI()
+ {
+ bool optionUpdated = false;
+ IReadOnlyList options = UpscalerOptionsRegistry.GetConfigurableOptions(this);
+ foreach (IOption opt in options)
+ {
+ object? currentValue = opt.GetValue(this);
+ object? newValue = null; // store the value returned by the GUI control
+
+ // ranged int/float options
+ if (opt is IRangeOption rangeOption && rangeOption.HasRange)
+ {
+ if (opt.ValueType == typeof(float))
+ {
+ float currentFloatValue = (float)currentValue!;
+ newValue = EditorGUILayout.Slider(opt.DisplayName, currentFloatValue, rangeOption.MinValue, rangeOption.MaxValue);
+ }
+ else if (opt.ValueType == typeof(int))
+ {
+ int currentIntValue = (int)currentValue!;
+ newValue = EditorGUILayout.IntSlider(opt.DisplayName, currentIntValue, (int)rangeOption.MinValue, (int)rangeOption.MaxValue);
+ }
+ else
+ {
+ // Fallback for unexpected IRangeOption types (shouldn't happen if attributes are correct)
+ EditorGUILayout.LabelField(opt.DisplayName, $"Range Type (Unhandled): {opt.ValueType.Name}, Value: {currentValue?.ToString() ?? "N/A"}");
+ }
+ }
+ // regular options
+ else
+ {
+ if (opt is IEnumOption enumOption)
+ {
+ Enum currentEnumValue = (Enum)currentValue!;
+ newValue = EditorGUILayout.EnumPopup(enumOption.DisplayName, currentEnumValue);
+ }
+ else if (opt.ValueType == typeof(float))
+ {
+ float currentFloatValue = (float)currentValue!;
+ newValue = EditorGUILayout.FloatField(opt.DisplayName, currentFloatValue);
+ }
+ else if (opt.ValueType == typeof(int))
+ {
+ int currentIntValue = (int)currentValue!;
+ newValue = EditorGUILayout.IntField(opt.DisplayName, currentIntValue);
+ }
+ else if (opt.ValueType == typeof(bool))
+ {
+ bool currentBoolValue = (bool)currentValue!;
+ newValue = EditorGUILayout.Toggle(opt.DisplayName, currentBoolValue);
+ }
+ }
+
+ bool valueChanged = newValue != null && !newValue.Equals(currentValue);
+ if (valueChanged)
+ {
+ opt.SetValue(this, newValue);
+ optionUpdated = true;
+ }
+ }
+
+ return optionUpdated;
+ }
+
+ // The core method to ensure options exist and are linked.
+ // It operates on a SerializedProperty representing the list.
+ public static bool ValidateSerializedUpscalerOptionReferencesWithinRPAsset(ScriptableObject parentRPAsset, SerializedProperty optionsListProp)
+ {
+ if (parentRPAsset == null)
+ {
+ Debug.LogError("[Auto-Populate] Parent asset is null.");
+ return false;
+ }
+ if (optionsListProp == null || !optionsListProp.isArray)
+ {
+ Debug.LogError($"[Auto-Populate] Provided SerializedProperty '{optionsListProp?.name ?? "null"}' is not a valid list for upscaler options.");
+ return false;
+ }
+
+ bool propertyModified = false;
+
+ // remove null entries
+ for (int i = optionsListProp.arraySize - 1; i >= 0; i--)
+ {
+ SerializedProperty elementProp = optionsListProp.GetArrayElementAtIndex(i);
+ if (elementProp.objectReferenceValue == null)
+ {
+ optionsListProp.DeleteArrayElementAtIndex(i);
+ propertyModified = true;
+ Debug.LogWarning($"[RP Asset] Removed null upscaler option from asset '{parentRPAsset.name}'.");
+ }
+ }
+
+ // default-initialize registered upscaler options if they're not found within serialized asset
+ foreach (var kvp in UpscalerRegistry.s_RegisteredUpscalers)
+ {
+ Type upscalerType = kvp.Key;
+ Type? optionsType = kvp.Value.OptionsType;
+
+ if (optionsType == null)
+ continue;
+
+ string upscalerName = kvp.Value.ID;
+
+ bool foundExisting = false;
+ for (int i = 0; i < optionsListProp.arraySize; i++)
+ {
+ SerializedProperty elementProp = optionsListProp.GetArrayElementAtIndex(i);
+ UpscalerOptions? existingOption = elementProp.objectReferenceValue as UpscalerOptions;
+
+ if (existingOption != null && existingOption.GetType() == optionsType /*&& existingOption.UpscalerName == upscalerName*/)
+ {
+ foundExisting = true;
+ break;
+ }
+ }
+
+ if (!foundExisting)
+ {
+ UpscalerOptions newOption = (UpscalerOptions)ScriptableObject.CreateInstance(optionsType);
+ newOption.hideFlags = HideFlags.HideInHierarchy;
+ newOption.UpscalerName = upscalerName;
+
+ AssetDatabase.AddObjectToAsset(newOption, parentRPAsset);
+
+ optionsListProp.arraySize++;
+ optionsListProp.GetArrayElementAtIndex(optionsListProp.arraySize - 1).objectReferenceValue = newOption;
+
+ propertyModified = true;
+ Debug.Log($"[RP Asset] Auto-populated missing upscaler option on asset '{parentRPAsset.name}': {optionsType.Name} for ID: {upscalerName}");
+ }
+ }
+ return propertyModified;
+ }
+#endif
+ }
+
+#nullable disable
+}
+#endif // ENABLE_UPSCALER_FRAMEWORK
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscalerOptions.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscalerOptions.cs.meta
new file mode 100644
index 00000000000..e6d8064b477
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/IUpscalerOptions.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 588cd674e5de5f94c8cb1337010456a3
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/Upscaling.cs b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/Upscaling.cs
new file mode 100644
index 00000000000..f2297a81988
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/Upscaling.cs
@@ -0,0 +1,148 @@
+#if ENABLE_UPSCALER_FRAMEWORK
+#nullable enable
+using System;
+using System.Collections.Generic;
+
+namespace UnityEngine.Rendering
+{
+ public static class UpscalerRegistry
+ {
+ public static readonly Dictionary s_RegisteredUpscalers = new();
+
+ ///
+ /// Registers an IUpscaler type without any custom options type.
+ ///
+ public static void Register(string id) where TUpscaler : IUpscaler, new()
+ {
+ s_RegisteredUpscalers[typeof(TUpscaler)] = (null, id);
+ }
+
+ ///
+ /// Registers an IUpscaler type with its custom options type.
+ ///
+ public static void Register(string id)
+ where TUpscaler : IUpscaler
+ where TOptions : UpscalerOptions
+ {
+ s_RegisteredUpscalers[typeof(TUpscaler)] = (typeof(TOptions), id);
+ }
+ }
+
+ public class Upscaling
+ {
+ public List upscalers = new();
+ public string[] upscalerNames { get; }
+
+ private int activeUpscalerIndex = -1;
+
+ ///
+ /// Initializes the Upscaling system with the given list of upscaler options per upscaler type.
+ ///
+ public Upscaling(List RPAssetUpscalerOptionsList)
+ {
+ foreach (var kvp in UpscalerRegistry.s_RegisteredUpscalers)
+ {
+ Type upscalerType = kvp.Key;
+ Type? optionsType = kvp.Value.OptionsType;
+
+ // find any serialized options, if any provided by the package implementor
+ int optionsIndex = RPAssetUpscalerOptionsList.FindIndex(o => o != null && o.GetType() == optionsType);
+ bool optionsNotFound = optionsIndex == -1;
+ UpscalerOptions? options = optionsNotFound ? null: RPAssetUpscalerOptionsList[optionsIndex];
+
+ // construct upscaler
+ IUpscaler upscaler = optionsType != null
+ ? (IUpscaler)Activator.CreateInstance(upscalerType, new object[] { options! })
+ : (IUpscaler)Activator.CreateInstance(upscalerType);
+
+ if(options != null && string.IsNullOrEmpty(options.UpscalerName))
+ {
+ string upscalerName = upscaler.GetName();
+ Debug.LogWarningFormat("[Upscaling] UpscalerOptions with empty UpscalerName for {0}", upscalerName);
+ options.UpscalerName = upscalerName;
+ }
+ upscalers.Add(upscaler);
+ }
+
+ // Get upscaler names
+ upscalerNames = new string[upscalers.Count];
+ for (int i = 0; i < upscalers.Count; i++)
+ {
+ upscalerNames[i] = upscalers[i].GetName();
+ }
+ }
+
+ ///
+ /// Returns the IUpscaler at the given index.
+ ///
+ public IUpscaler GetUpscalerAtIndex(int index)
+ {
+ Debug.Assert(index >= 0 && index < upscalers.Count);
+ return upscalers[index];
+ }
+
+ ///
+ /// Returns whether an upscaler with the given name was found.
+ ///
+ public bool SetActiveUpscaler(string name)
+ {
+ // TODO (Apoorva): We need to allow the IUpscaler itself to decide whether it can run. E.g.
+ // DLSS might need a certain version of Windows, and a compatible GPU. We should add an
+ // overrideable function to IUpscaler so that the active IUpscaler can return a bool
+ // indicating support.
+
+ bool found = false;
+ for (int i = 0; i < upscalerNames.Length; i++)
+ {
+ if (upscalerNames[i] == name)
+ {
+ activeUpscalerIndex = i;
+ found = true;
+ break;
+ }
+ }
+
+ return found;
+ }
+
+ ///
+ /// Returns null if no IUpscaler is active
+ ///
+ public IUpscaler? GetActiveUpscaler()
+ {
+ if (activeUpscalerIndex == -1)
+ return null;
+
+ return GetUpscalerAtIndex(activeUpscalerIndex);
+ }
+
+ ///
+ /// Returns null if no IUpscaler exists for given type
+ ///
+ public IUpscaler? GetIUpscalerOfType() where T : IUpscaler
+ {
+ if(!UpscalerRegistry.s_RegisteredUpscalers.ContainsKey(typeof(T)))
+ return null;
+ foreach (IUpscaler upscaler in upscalers)
+ if (upscaler.GetType() == typeof(T))
+ return upscaler;
+ Debug.LogErrorFormat($"Upscaler type {typeof(T)} not found");
+ return null;
+ }
+
+ ///
+ /// Returns null if no IUpscaler exists for given type
+ ///
+ public IUpscaler? GetIUpscalerOfType(Type T)
+ {
+ if (!UpscalerRegistry.s_RegisteredUpscalers.ContainsKey(T))
+ return null;
+ foreach (IUpscaler upscaler in upscalers)
+ if (upscaler.GetType() == T)
+ return upscaler;
+ Debug.LogErrorFormat($"Upscaler type {T} not found");
+ return null;
+ }
+ }
+}
+#endif
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/Upscaling.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/Upscaling.cs.meta
new file mode 100644
index 00000000000..9ee2fb34c5f
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Upscaling/Upscaling.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 89581a153029901419c003d693ca36a6
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/BlitColorAndDepth.hlsl b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/BlitColorAndDepth.hlsl
index 9be77bd527b..060b2acf1c7 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/BlitColorAndDepth.hlsl
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/BlitColorAndDepth.hlsl
@@ -2,14 +2,39 @@
#define UNITY_CORE_BLIT_COLOR_AND_DEPTH_INCLUDED
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/TextureXR.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/DynamicScaling.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/GlobalSamplers.hlsl"
-TEXTURE2D (_BlitTexture);
-TEXTURE2D (_InputDepthTexture);
+#pragma multi_compile _ _MSAA_2X _MSAA_4X _MSAA_8X
+
+#if defined(_MSAA_2X)
+# define SAMPLE_COUNT 2
+#elif defined (_MSAA_4X)
+# define SAMPLE_COUNT 4
+#elif defined(_MSAA_8X)
+# define SAMPLE_COUNT 8
+#else
+# define SAMPLE_COUNT 1
+#endif
+
+#if UNITY_REVERSED_Z
+ #define DEPTH_DEFAULT_VALUE 1.0
+ #define DEPTH_OP min
+#else
+ #define DEPTH_DEFAULT_VALUE 0.0
+ #define DEPTH_OP max
+#endif
+
+TEXTURE2D_X(_BlitTexture);
+TEXTURE2D(_InputDepthTexture);
+TEXTURE2D_X(_InputDepthTextureXR);
+TEXTURE2D_X_MSAA(float4, _InputDepthTextureXR_MS);
+
uniform float4 _BlitScaleBias;
uniform float _BlitMipLevel;
+uniform float2 _SourceResolution;
struct Attributes
{
@@ -43,7 +68,7 @@ float4 FragColorOnly(Varyings input) : SV_Target
{
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
- return SAMPLE_TEXTURE2D_LOD(_BlitTexture, sampler_LinearClamp, input.texcoord.xy, _BlitMipLevel);
+ return SAMPLE_TEXTURE2D_X_LOD(_BlitTexture, sampler_LinearClamp, input.texcoord.xy, _BlitMipLevel);
}
struct PixelData
@@ -57,9 +82,31 @@ PixelData FragColorAndDepth(Varyings input)
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
PixelData pd;
- pd.color = SAMPLE_TEXTURE2D_LOD(_BlitTexture, sampler_LinearClamp, input.texcoord.xy, _BlitMipLevel);
+ pd.color = SAMPLE_TEXTURE2D_X_LOD(_BlitTexture, sampler_LinearClamp, input.texcoord.xy, _BlitMipLevel);
pd.depth = SAMPLE_TEXTURE2D_LOD(_InputDepthTexture, sampler_PointClamp, input.texcoord.xy, _BlitMipLevel).x;
return pd;
}
+float SampleDepth(float2 uv)
+{
+ uint2 pixelCoords = uint2(uv * _SourceResolution);
+#if SAMPLE_COUNT == 1
+ return LOAD_TEXTURE2D_X_LOD(_InputDepthTextureXR, pixelCoords, _BlitMipLevel).x;
+#else
+ float outDepth = DEPTH_DEFAULT_VALUE;
+
+ UNITY_UNROLL
+ for (int i = 0; i < SAMPLE_COUNT; ++i)
+ outDepth = DEPTH_OP(LOAD_TEXTURE2D_X_MSAA(_InputDepthTextureXR_MS, pixelCoords, i), outDepth).x;
+ return outDepth;
+#endif
+}
+
+float FragDepthOnly(Varyings input) : SV_Depth
+{
+ UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
+
+ return SampleDepth(input.texcoord.xy);
+}
+
#endif // UNITY_CORE_BLIT_COLOR_AND_DEPTH_INCLUDED
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blitter.cs b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blitter.cs
index 87ff26c99f4..a4f968a48dd 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blitter.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/Blitter.cs
@@ -43,18 +43,25 @@ public static class Blitter
static LocalKeyword s_DecodeHdrKeyword;
+ static LocalKeyword s_ResolveDepthMSAA2X;
+ static LocalKeyword s_ResolveDepthMSAA4X;
+ static LocalKeyword s_ResolveDepthMSAA8X;
+
static class BlitShaderIDs
{
public static readonly int _BlitTexture = Shader.PropertyToID("_BlitTexture");
public static readonly int _BlitCubeTexture = Shader.PropertyToID("_BlitCubeTexture");
public static readonly int _BlitScaleBias = Shader.PropertyToID("_BlitScaleBias");
public static readonly int _BlitScaleBiasRt = Shader.PropertyToID("_BlitScaleBiasRt");
+ public static readonly int _SourceResolution = Shader.PropertyToID("_SourceResolution");
public static readonly int _BlitMipLevel = Shader.PropertyToID("_BlitMipLevel");
public static readonly int _BlitTexArraySlice = Shader.PropertyToID("_BlitTexArraySlice");
public static readonly int _BlitTextureSize = Shader.PropertyToID("_BlitTextureSize");
public static readonly int _BlitPaddingSize = Shader.PropertyToID("_BlitPaddingSize");
public static readonly int _BlitDecodeInstructions = Shader.PropertyToID("_BlitDecodeInstructions");
public static readonly int _InputDepth = Shader.PropertyToID("_InputDepthTexture");
+ public static readonly int _InputDepthXR = Shader.PropertyToID("_InputDepthTextureXR");
+ public static readonly int _InputDepthXRMS = Shader.PropertyToID("_InputDepthTextureXR_MS");
}
// This enum needs to be in sync with the shader pass names and indices of the Blit.shader in every pipeline.
@@ -90,6 +97,7 @@ enum BlitColorAndDepthPassNames
{
ColorOnly = 0,
ColorAndDepth = 1,
+ DepthOnly = 2,
}
// This maps the requested shader indices to actual existing shader indices. When running in a build, it's possible
@@ -161,10 +169,15 @@ public static void Initialize(Shader blitPS, Shader blitColorAndDepthPS)
s_DecodeHdrKeyword = new LocalKeyword(blitPS, "BLIT_DECODE_HDR");
+ s_ResolveDepthMSAA2X = new(s_BlitColorAndDepth.shader, "_MSAA_2X");
+ s_ResolveDepthMSAA4X = new(s_BlitColorAndDepth.shader, "_MSAA_4X");
+ s_ResolveDepthMSAA8X = new(s_BlitColorAndDepth.shader, "_MSAA_8X");
+
// With texture array enabled, we still need the normal blit version for other systems like atlas
if (TextureXR.useTexArray)
{
s_Blit.EnableKeyword("DISABLE_TEXTURE2D_X_ARRAY");
+ s_BlitColorAndDepth.EnableKeyword("DISABLE_TEXTURE2D_X_ARRAY");
s_BlitTexArray = CoreUtils.CreateEngineMaterial(blitPS);
s_BlitTexArraySingleSlice = CoreUtils.CreateEngineMaterial(blitPS);
s_BlitTexArraySingleSlice.EnableKeyword("BLIT_SINGLE_SLICE");
@@ -676,6 +689,43 @@ public static void BlitColorAndDepth(CommandBuffer cmd, Texture sourceColor, Ren
DrawTriangle(cmd, s_BlitColorAndDepth, s_BlitColorAndDepthShaderPassIndicesMap[blitDepth ? 1 : 0]);
}
+ ///
+ /// Adds in a a command to blit an XR compatible depth texture into
+ /// the currently bound depth render target.
+ ///
+ ///
+ /// This function is meant for textures and render targets which depend on XR output modes by proper handling, when
+ /// necessary, of left / right eye data copying. This generally corresponds to textures which represent full screen
+ /// data that may differ between eyes.
+ ///
+ /// The scaleBias parameter controls the rectangle of pixels in the source texture to copy by manipulating
+ /// the source texture coordinates. The X and Y coordinates store the scaling factor to apply to these texture
+ /// coordinates, while the Z and W coordinates store the texture coordinate offsets. The operation will always
+ /// write to the full destination render target rectangle.
+ ///
+ /// Command Buffer used for recording the action.
+ /// Source depth render texture to copy from.
+ /// Scale and bias for sampling the source texture.
+ /// Mip level of the source texture to copy from.
+ public static void BlitDepth(CommandBuffer cmd, RenderTexture sourceDepth, Vector4 scaleBias, float mipLevel)
+ {
+ s_PropertyBlock.SetFloat(BlitShaderIDs._BlitMipLevel, mipLevel);
+ s_PropertyBlock.SetVector(BlitShaderIDs._BlitScaleBias, scaleBias);
+ s_PropertyBlock.SetVector(BlitShaderIDs._SourceResolution, new Vector2(sourceDepth.width, sourceDepth.height));
+
+ // Setup MSAA keywords
+ cmd.SetKeyword(s_BlitColorAndDepth, s_ResolveDepthMSAA2X, sourceDepth.antiAliasing == 2);
+ cmd.SetKeyword(s_BlitColorAndDepth, s_ResolveDepthMSAA4X, sourceDepth.antiAliasing == 4);
+ cmd.SetKeyword(s_BlitColorAndDepth, s_ResolveDepthMSAA8X, sourceDepth.antiAliasing == 8);
+
+ if (sourceDepth.antiAliasing > 1)
+ s_PropertyBlock.SetTexture(BlitShaderIDs._InputDepthXRMS, sourceDepth, RenderTextureSubElement.Depth);
+ else
+ s_PropertyBlock.SetTexture(BlitShaderIDs._InputDepthXR, sourceDepth, RenderTextureSubElement.Depth);
+
+ DrawTriangle(cmd, s_BlitColorAndDepth, s_BlitColorAndDepthShaderPassIndicesMap[2]);
+ }
+
///
/// Adds in a a command to copy a texture identified by its into
/// the currently bound render target's color buffer, using a user material and specific shader pass.
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs
index e355d2b8069..69841980810 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/CoreUtils.cs
@@ -1,7 +1,6 @@
using System;
using System.Collections;
using System.IO;
-using System.Linq;
using System.Collections.Generic;
using UnityEngine.Experimental.Rendering;
using System.Runtime.CompilerServices;
@@ -1332,7 +1331,7 @@ public static void Destroy(UnityObject obj)
}
}
- static IEnumerable m_AssemblyTypes;
+ static IEnumerable s_AssemblyTypes;
///
/// Returns all assembly types.
@@ -1340,23 +1339,21 @@ public static void Destroy(UnityObject obj)
/// The list of all assembly types of the current domain.
public static IEnumerable GetAllAssemblyTypes()
{
- if (m_AssemblyTypes == null)
+ if (s_AssemblyTypes != null)
+ return s_AssemblyTypes;
+
+ var typeList = new List();
+ foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
{
- m_AssemblyTypes = AppDomain.CurrentDomain.GetAssemblies()
- .SelectMany(t =>
- {
- // Ugly hack to handle mis-versioned dlls
- var innerTypes = new Type[0];
- try
- {
- innerTypes = t.GetTypes();
- }
- catch { }
- return innerTypes;
- });
+ try
+ {
+ typeList.AddRange(assembly.GetTypes());
+ }
+ catch (Exception)
+ { }
}
-
- return m_AssemblyTypes;
+ s_AssemblyTypes = typeList;
+ return s_AssemblyTypes;
}
///
@@ -1369,7 +1366,14 @@ public static IEnumerable GetAllTypesDerivedFrom()
#if UNITY_EDITOR && UNITY_2019_2_OR_NEWER
return UnityEditor.TypeCache.GetTypesDerivedFrom();
#else
- return GetAllAssemblyTypes().Where(t => t.IsSubclassOf(typeof(T)));
+ var derivedTypes = new List();
+ var baseType = typeof(T);
+ foreach (var type in GetAllAssemblyTypes())
+ {
+ if (type.IsSubclassOf(baseType))
+ derivedTypes.Add(type);
+ }
+ return derivedTypes;
#endif
}
@@ -1787,7 +1791,10 @@ public static int DivRoundUp(int value, int divisor)
/// Type of the enum
/// Last value of the enum
public static T GetLastEnumValue() where T : Enum
- => typeof(T).GetEnumValues().Cast().Last();
+ {
+ var values = Enum.GetValues(typeof(T));
+ return (T)values.GetValue(values.Length - 1);
+ }
internal static string GetCorePath()
=> "Packages/com.unity.render-pipelines.core/";
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/GPUPrefixSum/GPUPrefixSum.Data.cs b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/GPUPrefixSum/GPUPrefixSum.Data.cs
index f48b41fc9d0..e01b90f7f67 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Utilities/GPUPrefixSum/GPUPrefixSum.Data.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Utilities/GPUPrefixSum/GPUPrefixSum.Data.cs
@@ -89,6 +89,7 @@ public static RenderGraphResources Create(int newMaxElementCount, RenderGraph re
return resources;
}
+#pragma warning disable CS0618 // Type or member is obsolete
void Initialize(int newMaxElementCount, RenderGraph renderGraph, RenderGraphBuilder builder, bool outputIsTemp = false)
{
newMaxElementCount = Math.Max(newMaxElementCount, 1);
@@ -104,6 +105,7 @@ void Initialize(int newMaxElementCount, RenderGraph renderGraph, RenderGraphBuil
maxBufferCount = totalSize;
maxLevelCount = levelCounts;
}
+#pragma warning restore CS0618 // Type or member is obsolete
///
/// Creates the render graph buffer resources from an input count.
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs b/Packages/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs
index ebb8a8e1a41..88c36382a08 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs
@@ -11,6 +11,7 @@ namespace UnityEngine.Rendering
[PipelineHelpURL("UniversalRenderPipelineAsset", "Volumes")]
[ExecuteAlways]
[AddComponentMenu("Miscellaneous/Volume")]
+ [Icon("Packages/com.unity.render-pipelines.core/Editor/Icons/Processed/Volume Icon.asset")]
public class Volume : MonoBehaviour, IVolume
{
[SerializeField, FormerlySerializedAs("isGlobal")]
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs.meta b/Packages/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs.meta
index e59941be5a4..e3aa1d2d2ec 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs.meta
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Volume/Volume.cs.meta
@@ -5,7 +5,7 @@ MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
- icon: {fileID: 2800000, guid: 32b23d5d74f3aee4f9364e34e2f59379, type: 3}
+ icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeComponent.cs b/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeComponent.cs
index 155f50b88af..1773e492c4f 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeComponent.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeComponent.cs
@@ -157,7 +157,8 @@ public Indent(int relativeAmount = 1)
/// The name displayed in the component header. If you do not set a name, Unity generates one from
/// the class name automatically.
///
- public string displayName { get; protected set; } = "";
+ [Obsolete("Use DisplayInfo attribute to define a display name instead. #from(6000.3)", false)]
+ public string displayName { get; protected set; }
///
/// The backing storage of . Use this for performance-critical work.
@@ -165,6 +166,7 @@ public Indent(int relativeAmount = 1)
internal VolumeParameter[] parameterList;
ReadOnlyCollection m_ParameterReadOnlyCollection;
+
///
/// A read-only collection of all the s defined in this class.
///
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeProfile.cs b/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeProfile.cs
index 6b15949c1ab..53d2a302c32 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeProfile.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Volume/VolumeProfile.cs
@@ -23,8 +23,28 @@ public sealed class VolumeProfile : ScriptableObject
/// A dirty check used to redraw the profile inspector when something has changed. This is
/// currently only used in the editor.
///
- [NonSerialized]
- public bool isDirty = true; // Editor only, doesn't have any use outside of it
+ [Obsolete("This field was only public for editor access. #from(6000.0)")]
+ public bool isDirty
+ {
+ get => dirtyState != DirtyState.None;
+ set
+ {
+ if (value)
+ dirtyState |= DirtyState.Other;
+ else
+ dirtyState &= ~DirtyState.Other;
+ }
+ }
+
+ [Flags] internal enum DirtyState
+ {
+ None = 0,
+ DirtyByComponentChange = 1,
+ DirtyByProfileReset = 2,
+ Other = 4
+ }
+
+ internal DirtyState dirtyState;
void OnEnable()
{
@@ -56,9 +76,7 @@ internal void OnDisable()
/// Volume Profile editor when you modify the Asset via script instead of the Inspector.
///
public void Reset()
- {
- isDirty = true;
- }
+ => dirtyState |= DirtyState.DirtyByProfileReset;
///
/// Adds a to this Volume Profile.
@@ -100,7 +118,7 @@ public VolumeComponent Add(Type type, bool overrides = false)
#endif
component.SetAllOverridesTo(overrides);
components.Add(component);
- isDirty = true;
+ dirtyState |= DirtyState.DirtyByComponentChange;
return component;
}
@@ -142,7 +160,7 @@ public void Remove(Type type)
if (toRemove >= 0)
{
components.RemoveAt(toRemove);
- isDirty = true;
+ dirtyState |= DirtyState.DirtyByComponentChange;
}
}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Vrs/VrsLut.cs b/Packages/com.unity.render-pipelines.core/Runtime/Vrs/VrsLut.cs
index 7f53faf674e..33a6a49baaa 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Vrs/VrsLut.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Vrs/VrsLut.cs
@@ -17,15 +17,15 @@ public static VrsLut CreateDefault()
{
return new VrsLut()
{
- [ShadingRateFragmentSize.FragmentSize1x1] = Color.red,
- [ShadingRateFragmentSize.FragmentSize1x2] = Color.yellow,
- [ShadingRateFragmentSize.FragmentSize2x1] = Color.white,
- [ShadingRateFragmentSize.FragmentSize2x2] = Color.green,
- [ShadingRateFragmentSize.FragmentSize1x4] = new Color(0.75f, 0.75f, 0.00f, 1),
- [ShadingRateFragmentSize.FragmentSize4x1] = new Color(0.00f, 0.75f, 0.55f, 1),
- [ShadingRateFragmentSize.FragmentSize2x4] = new Color(0.50f, 0.00f, 0.50f, 1),
- [ShadingRateFragmentSize.FragmentSize4x2] = Color.grey,
- [ShadingRateFragmentSize.FragmentSize4x4] = Color.blue,
+ [ShadingRateFragmentSize.FragmentSize1x1] = new Color(0.785f, 0.23f, 0.20f, 1), // Red
+ [ShadingRateFragmentSize.FragmentSize1x2] = new Color(1.00f, 0.80f, 0.80f, 1), // Light Red
+ [ShadingRateFragmentSize.FragmentSize2x1] = new Color(0.40f, 0.20f, 0.20f, 1), // Dark Red
+ [ShadingRateFragmentSize.FragmentSize2x2] = new Color(0.51f, 0.80f, 0.60f, 1), // Green
+ [ShadingRateFragmentSize.FragmentSize1x4] = new Color(0.60f, 0.80f, 1.00f, 1), // Light Blue
+ [ShadingRateFragmentSize.FragmentSize4x1] = new Color(0.20f, 0.40f, 0.60f, 1), // Medium Blue
+ [ShadingRateFragmentSize.FragmentSize2x4] = new Color(0.80f, 1.00f, 0.80f, 1), // Light Green
+ [ShadingRateFragmentSize.FragmentSize4x2] = new Color(0.20f, 0.40f, 0.20f, 1), // Dark Green
+ [ShadingRateFragmentSize.FragmentSize4x4] = new Color(0.125f, 0.22f, 0.36f, 1), // Dark Blue
};
}
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/Vrs/VrsRenderPipelineRuntimeResources.cs b/Packages/com.unity.render-pipelines.core/Runtime/Vrs/VrsRenderPipelineRuntimeResources.cs
index 95b724b6094..f1f02491c40 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/Vrs/VrsRenderPipelineRuntimeResources.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/Vrs/VrsRenderPipelineRuntimeResources.cs
@@ -7,7 +7,7 @@ namespace UnityEngine.Rendering
///
[Serializable]
[SupportedOnRenderPipeline]
- [Categorization.CategoryInfo(Name = "R: VRS - Runtime Resources", Order = 1000), HideInInspector]
+ [Categorization.CategoryInfo(Name = "R: VRS - Runtime Resources", Order = 1000)]
public sealed class VrsRenderPipelineRuntimeResources : IRenderPipelineResources
{
///
diff --git a/Packages/com.unity.render-pipelines.core/Runtime/XR/XRSystem.cs b/Packages/com.unity.render-pipelines.core/Runtime/XR/XRSystem.cs
index 582999e9efb..4e0d8aa3e39 100644
--- a/Packages/com.unity.render-pipelines.core/Runtime/XR/XRSystem.cs
+++ b/Packages/com.unity.render-pipelines.core/Runtime/XR/XRSystem.cs
@@ -254,15 +254,15 @@ public static void SetRenderScale(float renderScale)
///
- /// Used by the render pipeline to retrieve the renderViewportScale value from the XR display.
+ /// Used by the render pipeline to retrieve the applied renderViewportScale value from the XR display.
/// One use case for retriving this value is that render pipeline can properly sync some SRP owned textures to scale accordingly
///
- /// Returns current scaleOfAllViewports value from the XRDisplaySubsystem.
+ /// Returns current appliedViewportScale value from the XRDisplaySubsystem.
public static float GetRenderViewportScale()
{
#if ENABLE_VR && ENABLE_XR_MODULE
- return s_Display.scaleOfAllViewports;
+ return s_Display.appliedViewportScale;
#else
return 1.0f;
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/ACES.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/ACES.hlsl
index 64a6ae1ec17..56044f41362 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/ACES.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/ACES.hlsl
@@ -1,7 +1,7 @@
#ifndef __ACES__
#define __ACES__
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -347,7 +347,7 @@ half rgb_2_yc(half3 rgb)
half b = rgb.z;
half k = b * (b - g) + g * (g - r) + r * (r - b);
k = max(k, 0.0); // Clamp to avoid precision issue causing k < 0, making sqrt(k) undefined
-#if defined(SHADER_API_SWITCH)
+#if defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
half chroma = k == 0.0 ? 0.0 : sqrt(k); // Avoid Nan
#else
half chroma = sqrt(k);
@@ -1514,7 +1514,7 @@ half3 ODT_4000nits_ToAP1(half3 oces)
return rgbPost;
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Switch2.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Switch2.hlsl
new file mode 100644
index 00000000000..fa7c10ba347
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Switch2.hlsl
@@ -0,0 +1,155 @@
+// This file assume SHADER_API_SWITCH2 is defined
+// TODO: This is a straight copy from D3D11.hlsl. Go through all this stuff and adjust where needed.
+
+#define UNITY_UV_STARTS_AT_TOP 1
+#define UNITY_REVERSED_Z 1
+#define UNITY_NEAR_CLIP_VALUE (1.0)
+// This value will not go through any matrix projection conversion
+#define UNITY_RAW_FAR_CLIP_VALUE (0.0)
+#define VERTEXID_SEMANTIC SV_VertexID
+#define INSTANCEID_SEMANTIC SV_InstanceID
+#define FRONT_FACE_SEMANTIC SV_IsFrontFace
+#define FRONT_FACE_TYPE bool
+#define IS_FRONT_VFACE(VAL, FRONT, BACK) ((VAL) ? (FRONT) : (BACK))
+
+#define CBUFFER_START(name) cbuffer name {
+#define CBUFFER_END };
+
+#define PLATFORM_SUPPORTS_EXPLICIT_BINDING
+#define PLATFORM_NEEDS_UNORM_UAV_SPECIFIER
+#define PLATFORM_LANE_COUNT 32
+
+// flow control attributes
+#define UNITY_BRANCH [branch]
+#define UNITY_FLATTEN [flatten]
+#define UNITY_UNROLL [unroll]
+#define UNITY_UNROLLX(_x) [unroll(_x)]
+#define UNITY_LOOP [loop]
+
+// Initialize arbitrary structure with zero values.
+// Do not exist on some platform, in this case we need to have a standard name that call a function that will initialize all parameters to 0
+#define ZERO_INITIALIZE(type, name) name = (type)0;
+#define ZERO_INITIALIZE_ARRAY(type, name, arraySize) { for (int arrayIndex = 0; arrayIndex < arraySize; arrayIndex++) { name[arrayIndex] = (type)0; } }
+
+// Texture util abstraction
+
+#define CALCULATE_TEXTURE2D_LOD(textureName, samplerName, coord2) textureName.CalculateLevelOfDetail(samplerName, coord2)
+
+// Texture abstraction
+
+#define TEXTURE2D(textureName) Texture2D textureName
+#define TEXTURE2D_ARRAY(textureName) Texture2DArray textureName
+#define TEXTURECUBE(textureName) TextureCube textureName
+#define TEXTURECUBE_ARRAY(textureName) TextureCubeArray textureName
+#define TEXTURE3D(textureName) Texture3D textureName
+
+#define TEXTURE2D_FLOAT(textureName) Texture2D textureName
+#define TEXTURE2D_ARRAY_FLOAT(textureName) Texture2DArray textureName
+#define TEXTURECUBE_FLOAT(textureName) TextureCube textureName
+#define TEXTURECUBE_ARRAY_FLOAT(textureName) TextureCubeArray textureName
+#define TEXTURE3D_FLOAT(textureName) Texture3D textureName
+
+#define TEXTURE2D_HALF(textureName) Texture2D textureName
+#define TEXTURE2D_ARRAY_HALF(textureName) Texture2DArray textureName
+#define TEXTURECUBE_HALF(textureName) TextureCube textureName
+#define TEXTURECUBE_ARRAY_HALF(textureName) TextureCubeArray textureName
+#define TEXTURE3D_HALF(textureName) Texture3D textureName
+
+#define TEXTURE2D_SHADOW(textureName) TEXTURE2D(textureName)
+#define TEXTURE2D_ARRAY_SHADOW(textureName) TEXTURE2D_ARRAY(textureName)
+#define TEXTURECUBE_SHADOW(textureName) TEXTURECUBE(textureName)
+#define TEXTURECUBE_ARRAY_SHADOW(textureName) TEXTURECUBE_ARRAY(textureName)
+
+#define TYPED_TEXTURE2D(type, textureName) Texture2D textureName
+#define TYPED_TEXTURE2D_ARRAY(type, textureName) Texture2DArray textureName
+#define TYPED_TEXTURE3D(type, textureName) Texture3D textureName
+#define RW_TEXTURE2D(type, textureName) RWTexture2D textureName
+#define RW_TEXTURE2D_ARRAY(type, textureName) RWTexture2DArray textureName
+#define RW_TEXTURE3D(type, textureName) RWTexture3D textureName
+
+#define SAMPLER(samplerName) SamplerState samplerName
+#define SAMPLER_CMP(samplerName) SamplerComparisonState samplerName
+#define ASSIGN_SAMPLER(samplerName, samplerValue) samplerName = samplerValue
+
+#define TEXTURE2D_PARAM(textureName, samplerName) TEXTURE2D(textureName), SAMPLER(samplerName)
+#define TEXTURE2D_ARRAY_PARAM(textureName, samplerName) TEXTURE2D_ARRAY(textureName), SAMPLER(samplerName)
+#define TEXTURECUBE_PARAM(textureName, samplerName) TEXTURECUBE(textureName), SAMPLER(samplerName)
+#define TEXTURECUBE_ARRAY_PARAM(textureName, samplerName) TEXTURECUBE_ARRAY(textureName), SAMPLER(samplerName)
+#define TEXTURE3D_PARAM(textureName, samplerName) TEXTURE3D(textureName), SAMPLER(samplerName)
+
+#define TEXTURE2D_SHADOW_PARAM(textureName, samplerName) TEXTURE2D(textureName), SAMPLER_CMP(samplerName)
+#define TEXTURE2D_ARRAY_SHADOW_PARAM(textureName, samplerName) TEXTURE2D_ARRAY(textureName), SAMPLER_CMP(samplerName)
+#define TEXTURECUBE_SHADOW_PARAM(textureName, samplerName) TEXTURECUBE(textureName), SAMPLER_CMP(samplerName)
+#define TEXTURECUBE_ARRAY_SHADOW_PARAM(textureName, samplerName) TEXTURECUBE_ARRAY(textureName), SAMPLER_CMP(samplerName)
+
+#define TEXTURE2D_ARGS(textureName, samplerName) textureName, samplerName
+#define TEXTURE2D_ARRAY_ARGS(textureName, samplerName) textureName, samplerName
+#define TEXTURECUBE_ARGS(textureName, samplerName) textureName, samplerName
+#define TEXTURECUBE_ARRAY_ARGS(textureName, samplerName) textureName, samplerName
+#define TEXTURE3D_ARGS(textureName, samplerName) textureName, samplerName
+
+#define TEXTURE2D_SHADOW_ARGS(textureName, samplerName) textureName, samplerName
+#define TEXTURE2D_ARRAY_SHADOW_ARGS(textureName, samplerName) textureName, samplerName
+#define TEXTURECUBE_SHADOW_ARGS(textureName, samplerName) textureName, samplerName
+#define TEXTURECUBE_ARRAY_SHADOW_ARGS(textureName, samplerName) textureName, samplerName
+
+#define PLATFORM_SAMPLE_TEXTURE2D(textureName, samplerName, coord2) textureName.Sample(samplerName, coord2)
+#define PLATFORM_SAMPLE_TEXTURE2D_LOD(textureName, samplerName, coord2, lod) textureName.SampleLevel(samplerName, coord2, lod)
+#define PLATFORM_SAMPLE_TEXTURE2D_BIAS(textureName, samplerName, coord2, bias) textureName.SampleBias(samplerName, coord2, bias)
+#define PLATFORM_SAMPLE_TEXTURE2D_GRAD(textureName, samplerName, coord2, dpdx, dpdy) textureName.SampleGrad(samplerName, coord2, dpdx, dpdy)
+#define PLATFORM_SAMPLE_TEXTURE2D_ARRAY(textureName, samplerName, coord2, index) textureName.Sample(samplerName, float3(coord2, index))
+#define PLATFORM_SAMPLE_TEXTURE2D_ARRAY_LOD(textureName, samplerName, coord2, index, lod) textureName.SampleLevel(samplerName, float3(coord2, index), lod)
+#define PLATFORM_SAMPLE_TEXTURE2D_ARRAY_BIAS(textureName, samplerName, coord2, index, bias) textureName.SampleBias(samplerName, float3(coord2, index), bias)
+#define PLATFORM_SAMPLE_TEXTURE2D_ARRAY_GRAD(textureName, samplerName, coord2, index, dpdx, dpdy) textureName.SampleGrad(samplerName, float3(coord2, index), dpdx, dpdy)
+#define PLATFORM_SAMPLE_TEXTURECUBE(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
+#define PLATFORM_SAMPLE_TEXTURECUBE_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
+#define PLATFORM_SAMPLE_TEXTURECUBE_BIAS(textureName, samplerName, coord3, bias) textureName.SampleBias(samplerName, coord3, bias)
+#define PLATFORM_SAMPLE_TEXTURECUBE_ARRAY(textureName, samplerName, coord3, index) textureName.Sample(samplerName, float4(coord3, index))
+#define PLATFORM_SAMPLE_TEXTURECUBE_ARRAY_LOD(textureName, samplerName, coord3, index, lod) textureName.SampleLevel(samplerName, float4(coord3, index), lod)
+#define PLATFORM_SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias) textureName.SampleBias(samplerName, float4(coord3, index), bias)
+#define PLATFORM_SAMPLE_TEXTURE3D(textureName, samplerName, coord3) textureName.Sample(samplerName, coord3)
+#define PLATFORM_SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) textureName.SampleLevel(samplerName, coord3, lod)
+
+#define SAMPLE_TEXTURE2D(textureName, samplerName, coord2) PLATFORM_SAMPLE_TEXTURE2D(textureName, samplerName, coord2)
+#define SAMPLE_TEXTURE2D_LOD(textureName, samplerName, coord2, lod) PLATFORM_SAMPLE_TEXTURE2D_LOD(textureName, samplerName, coord2, lod)
+#define SAMPLE_TEXTURE2D_BIAS(textureName, samplerName, coord2, bias) PLATFORM_SAMPLE_TEXTURE2D_BIAS(textureName, samplerName, coord2, bias)
+#define SAMPLE_TEXTURE2D_GRAD(textureName, samplerName, coord2, dpdx, dpdy) PLATFORM_SAMPLE_TEXTURE2D_GRAD(textureName, samplerName, coord2, dpdx, dpdy)
+#define SAMPLE_TEXTURE2D_ARRAY(textureName, samplerName, coord2, index) PLATFORM_SAMPLE_TEXTURE2D_ARRAY(textureName, samplerName, coord2, index)
+#define SAMPLE_TEXTURE2D_ARRAY_LOD(textureName, samplerName, coord2, index, lod) PLATFORM_SAMPLE_TEXTURE2D_ARRAY_LOD(textureName, samplerName, coord2, index, lod)
+#define SAMPLE_TEXTURE2D_ARRAY_BIAS(textureName, samplerName, coord2, index, bias) PLATFORM_SAMPLE_TEXTURE2D_ARRAY_BIAS(textureName, samplerName, coord2, index, bias)
+#define SAMPLE_TEXTURE2D_ARRAY_GRAD(textureName, samplerName, coord2, index, dpdx, dpdy) PLATFORM_SAMPLE_TEXTURE2D_ARRAY_GRAD(textureName, samplerName, coord2, index, dpdx, dpdy)
+#define SAMPLE_TEXTURECUBE(textureName, samplerName, coord3) PLATFORM_SAMPLE_TEXTURECUBE(textureName, samplerName, coord3)
+#define SAMPLE_TEXTURECUBE_LOD(textureName, samplerName, coord3, lod) PLATFORM_SAMPLE_TEXTURECUBE_LOD(textureName, samplerName, coord3, lod)
+#define SAMPLE_TEXTURECUBE_BIAS(textureName, samplerName, coord3, bias) PLATFORM_SAMPLE_TEXTURECUBE_BIAS(textureName, samplerName, coord3, bias)
+#define SAMPLE_TEXTURECUBE_ARRAY(textureName, samplerName, coord3, index) PLATFORM_SAMPLE_TEXTURECUBE_ARRAY(textureName, samplerName, coord3, index)
+#define SAMPLE_TEXTURECUBE_ARRAY_LOD(textureName, samplerName, coord3, index, lod) PLATFORM_SAMPLE_TEXTURECUBE_ARRAY_LOD(textureName, samplerName, coord3, index, lod)
+#define SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias) PLATFORM_SAMPLE_TEXTURECUBE_ARRAY_BIAS(textureName, samplerName, coord3, index, bias)
+#define SAMPLE_TEXTURE3D(textureName, samplerName, coord3) PLATFORM_SAMPLE_TEXTURE3D(textureName, samplerName, coord3)
+#define SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod) PLATFORM_SAMPLE_TEXTURE3D_LOD(textureName, samplerName, coord3, lod)
+
+#define SAMPLE_TEXTURE2D_SHADOW(textureName, samplerName, coord3) textureName.SampleCmpLevelZero(samplerName, (coord3).xy, (coord3).z)
+#define SAMPLE_TEXTURE2D_ARRAY_SHADOW(textureName, samplerName, coord3, index) textureName.SampleCmpLevelZero(samplerName, float3((coord3).xy, index), (coord3).z)
+#define SAMPLE_TEXTURECUBE_SHADOW(textureName, samplerName, coord4) textureName.SampleCmpLevelZero(samplerName, (coord4).xyz, (coord4).w)
+#define SAMPLE_TEXTURECUBE_ARRAY_SHADOW(textureName, samplerName, coord4, index) textureName.SampleCmpLevelZero(samplerName, float4((coord4).xyz, index), (coord4).w)
+
+#define SAMPLE_DEPTH_TEXTURE(textureName, samplerName, coord2) SAMPLE_TEXTURE2D(textureName, samplerName, coord2).r
+#define SAMPLE_DEPTH_TEXTURE_LOD(textureName, samplerName, coord2, lod) SAMPLE_TEXTURE2D_LOD(textureName, samplerName, coord2, lod).r
+
+#define LOAD_TEXTURE2D(textureName, unCoord2) textureName.Load(int3(unCoord2, 0))
+#define LOAD_TEXTURE2D_LOD(textureName, unCoord2, lod) textureName.Load(int3(unCoord2, lod))
+#define LOAD_TEXTURE2D_MSAA(textureName, unCoord2, sampleIndex) textureName.Load(unCoord2, sampleIndex)
+#define LOAD_TEXTURE2D_ARRAY(textureName, unCoord2, index) textureName.Load(int4(unCoord2, index, 0))
+#define LOAD_TEXTURE2D_ARRAY_MSAA(textureName, unCoord2, index, sampleIndex) textureName.Load(int3(unCoord2, index), sampleIndex)
+#define LOAD_TEXTURE2D_ARRAY_LOD(textureName, unCoord2, index, lod) textureName.Load(int4(unCoord2, index, lod))
+#define LOAD_TEXTURE3D(textureName, unCoord3) textureName.Load(int4(unCoord3, 0))
+#define LOAD_TEXTURE3D_LOD(textureName, unCoord3, lod) textureName.Load(int4(unCoord3, lod))
+
+#define PLATFORM_SUPPORT_GATHER
+#define GATHER_TEXTURE2D(textureName, samplerName, coord2) textureName.Gather(samplerName, coord2)
+#define GATHER_TEXTURE2D_ARRAY(textureName, samplerName, coord2, index) textureName.Gather(samplerName, float3(coord2, index))
+#define GATHER_TEXTURECUBE(textureName, samplerName, coord3) textureName.Gather(samplerName, coord3)
+#define GATHER_TEXTURECUBE_ARRAY(textureName, samplerName, coord3, index) textureName.Gather(samplerName, float4(coord3, index))
+#define GATHER_RED_TEXTURE2D(textureName, samplerName, coord2) textureName.GatherRed(samplerName, coord2)
+#define GATHER_GREEN_TEXTURE2D(textureName, samplerName, coord2) textureName.GatherGreen(samplerName, coord2)
+#define GATHER_BLUE_TEXTURE2D(textureName, samplerName, coord2) textureName.GatherBlue(samplerName, coord2)
+#define GATHER_ALPHA_TEXTURE2D(textureName, samplerName, coord2) textureName.GatherAlpha(samplerName, coord2)
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Switch2.hlsl.meta b/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Switch2.hlsl.meta
new file mode 100644
index 00000000000..9e90741feda
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Switch2.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 27b804a87c546b2429017809b12cd1c9
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/BSDF.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/BSDF.hlsl
index 9f4a72f19a0..979202c5b0c 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/BSDF.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/BSDF.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_BSDF_INCLUDED
#define UNITY_BSDF_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -658,7 +658,7 @@ real3 D_KajiyaKay(real3 T, real3 H, real specularExponent)
return dirAttn * norm * PositivePow(sinTHSq, 0.5 * n);
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH2 || SHADER_API_SWITCH
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl
index a67c8ae337e..bf20910ed5f 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_COLOR_INCLUDED
#define UNITY_COLOR_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -676,7 +676,7 @@ float3 AcesTonemap(float3 aces)
const float d = 0.4329510f;
const float e = 0.238081f;
-#if defined(SHADER_API_SWITCH)
+#if defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
// To reduce the likelyhood of extremely large values, we avoid using the x^2 term and therefore
// divide numerator and denominator by it. This will lead to the constant factors of the
// quadratic in the numerator and denominator to be divided by x; we add a tiny epsilon to avoid divide by 0.
@@ -729,7 +729,7 @@ half3 DecodeRGBM(half4 rgbm)
return rgbm.xyz * rgbm.w * kRGBMRange;
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl
index 4b01974196d..cd2a7d8d12b 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_COMMON_INCLUDED
#define UNITY_COMMON_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -118,6 +118,9 @@
// The including shader should define whether half
// precision is suitable for its needs. The shader
// API (for now) can indicate whether half is possible.
+//
+// We do not define this on Switch2 currently, this would cause function DV_SmithJointGGX (that refers to value REAL_MIN)
+// to return incorrect values, which then would cause specular highlights to look extremely bright and incorrect.
#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH) || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#define HAS_HALF 1
#else
@@ -228,6 +231,8 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Vulkan.hlsl"
#elif defined(SHADER_API_SWITCH)
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Switch.hlsl"
+#elif defined(SHADER_API_SWITCH2)
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/API/Switch2.hlsl"
#elif defined(SHADER_API_GLCORE)
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/API/GLCore.hlsl"
#elif defined(SHADER_API_GLES3)
@@ -1027,7 +1032,7 @@ float ComputeTextureLOD(float3 duvw_dx, float3 duvw_dy, float3 duvw_dz, float sc
#define MIP_COUNT_SUPPORTED 1
#endif
// TODO: Bug workaround, switch defines GLCORE when it shouldn't
-#if ((defined(SHADER_API_GLCORE) && !defined(SHADER_API_SWITCH)) || defined(SHADER_API_VULKAN)) && !defined(SHADER_STAGE_COMPUTE)
+#if ((defined(SHADER_API_GLCORE) && !defined(SHADER_API_SWITCH) && !defined(SHADER_API_SWITCH2)) || defined(SHADER_API_VULKAN)) && !defined(SHADER_STAGE_COMPUTE)
// OpenGL only supports textureSize for width, height, depth
// textureQueryLevels (GL_ARB_texture_query_levels) needs OpenGL 4.3 or above and doesn't compile in compute shaders
// tex.GetDimensions converted to textureQueryLevels
@@ -1057,7 +1062,7 @@ uint GetMipCount(TEXTURE2D_PARAM(tex, smp))
#define DXC_SAMPLER_COMPATIBILITY 1
// On DXC platforms which don't care about explicit sampler precison we want the emulated types to work directly e.g without needing to redefine 'sampler2D' to 'sampler2D_f'
-#if !defined(SHADER_API_GLES3) && !defined(SHADER_API_VULKAN) && !defined(SHADER_API_METAL) && !defined(SHADER_API_SWITCH) && !defined(SHADER_API_WEBGPU)
+#if !defined(SHADER_API_GLES3) && !defined(SHADER_API_VULKAN) && !defined(SHADER_API_METAL) && !defined(SHADER_API_SWITCH) && !defined(SHADER_API_SWITCH2) && !defined(SHADER_API_WEBGPU)
#define sampler1D_f sampler1D
#define sampler2D_f sampler2D
#define sampler3D_f sampler3D
@@ -1694,7 +1699,7 @@ float SharpenAlpha(float alpha, float alphaClipTreshold)
// These clamping function to max of floating point 16 bit are use to prevent INF in code in case of extreme value
TEMPLATE_1_FLT(ClampToFloat16Max, value, return min(value, HALF_MAX))
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl
index 8344c4fc420..ccb2ab7e75d 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_COMMON_LIGHTING_INCLUDED
#define UNITY_COMMON_LIGHTING_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -552,7 +552,7 @@ bool IsMatchingLightLayer(uint lightLayers, uint renderingLayers)
return (lightLayers & renderingLayers) != 0;
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl
index 71ea6299b45..1ecccb074c7 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonMaterial.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_COMMON_MATERIAL_INCLUDED
#define UNITY_COMMON_MATERIAL_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -363,7 +363,7 @@ real3 LerpWhiteTo(real3 b, real t)
}
#endif
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/EntityLighting.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/EntityLighting.hlsl
index 1191d588d0a..fee97a62604 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/EntityLighting.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/EntityLighting.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_ENTITY_LIGHTING_INCLUDED
#define UNITY_ENTITY_LIGHTING_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2|| defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -341,7 +341,7 @@ real3 SampleDirectionalLightmap(TEXTURE2D_LIGHTMAP_PARAM(lightmapTex, lightmapSa
return SampleDirectionalLightmap(TEXTURE2D_LIGHTMAP_ARGS(lightmapTex, lightmapSampler), TEXTURE2D_LIGHTMAP_ARGS(lightmapDirTex, lightmapDirSampler), LIGHTMAP_EXTRA_ARGS_USE, transform, normalWS, isStaticLightmap);
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl
index 8cdf6028a5b..515878e8254 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_IMAGE_BASED_LIGHTING_HLSL_INCLUDED
#define UNITY_IMAGE_BASED_LIGHTING_HLSL_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -399,7 +399,7 @@ uint GetIBLRuntimeFilterSampleCount(uint mipLevel)
{
case 1: sampleCount = 21; break;
case 2: sampleCount = 34; break;
-#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH)
+#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
case 3: sampleCount = 34; break;
case 4: sampleCount = 34; break;
case 5: sampleCount = 34; break;
@@ -696,7 +696,7 @@ float InfluenceFadeNormalWeight(float3 normal, float3 centerToPos)
return saturate((-1.0f / 0.4f) * dot(normal, centerToPos) + (0.6f / 0.4f));
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl
index 1815093115a..0f9c96c91a9 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_PACKING_INCLUDED
#define UNITY_PACKING_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -621,7 +621,7 @@ float3 UnpackFromR7G7B6(uint rgb)
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Fibonacci.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Fibonacci.hlsl
index 64c792125e3..69bb653deec 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Fibonacci.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Fibonacci.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_FIBONACCI_INCLUDED
#define UNITY_FIBONACCI_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -299,7 +299,7 @@ real2 SampleSphereFibonacci(uint i, uint sampleCount)
return real2(1 - 2 * f.x, TWO_PI * f.y);
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Hammersley.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Hammersley.hlsl
index f74372049ea..06d99ed5abf 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Hammersley.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Hammersley.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_HAMMERSLEY_INCLUDED
#define UNITY_HAMMERSLEY_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -437,7 +437,7 @@ real2 Hammersley2d(uint i, uint sampleCount)
}
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Sampling.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Sampling.hlsl
index ba16bd5acd0..4c97e8e030d 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Sampling.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Sampling.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_SAMPLING_INCLUDED
#define UNITY_SAMPLING_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -136,9 +136,9 @@ real2 SampleDiskCubic(real u1, real u2)
return r * real2(cosPhi, sinPhi);
}
-real3 SampleConeUniform(real u1, real u2, real cos_theta)
+real3 SampleConeUniform(real u1, real u2, real cosTheta)
{
- float r0 = cos_theta + u1 * (1.0f - cos_theta);
+ float r0 = cosTheta + u1 * (1.0f - cosTheta);
float r = sqrt(max(0.0, 1.0 - r0 * r0));
float phi = TWO_PI * u2;
return float3(r * cos(phi), r * sin(phi), r0);
@@ -148,7 +148,6 @@ real3 SampleSphereUniform(real u1, real u2)
{
real phi = TWO_PI * u2;
real cosTheta = 1.0 - 2.0 * u1;
-
return SphericalToCartesian(phi, cosTheta);
}
@@ -322,7 +321,7 @@ real3 SampleConeStrata(uint sampleIdx, real rcpSampleCount, real cosHalfApexAngl
return real3(r * cphi, r * sphi, z);
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl
index 38e138a6200..86b259e577b 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/SpaceTransforms.hlsl
@@ -1,7 +1,7 @@
#ifndef UNITY_SPACE_TRANSFORMS_INCLUDED
#define UNITY_SPACE_TRANSFORMS_INCLUDED
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2 || defined(UNITY_UNIFIED_SHADER_PRECISION_MODEL)
#pragma warning (disable : 3205) // conversion of larger type to smaller
#endif
@@ -340,7 +340,7 @@ real3 TransformObjectToTangent(real3 dirOS, real3x3 tangentToWorld)
return TransformWorldToTangent(normalWS, tangentToWorld);
}
-#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH
+#if SHADER_API_MOBILE || SHADER_API_GLES3 || SHADER_API_SWITCH || SHADER_API_SWITCH2
#pragma warning (enable : 3205) // conversion of larger type to smaller
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Threading.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Threading.hlsl
index 7f3e7514284..58e10098a6a 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/Threading.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/Threading.hlsl
@@ -28,6 +28,8 @@
/// - If defined, forces usage of the fallback groupshared memory implementation
///
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
+
#ifndef THREADING_BLOCK_SIZE
#error THREADING_BLOCK_SIZE must be defined as the flattened thread group size.
#endif
diff --git a/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl b/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl
index 05b865f2bb7..c3265083e7d 100644
--- a/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl
+++ b/Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl
@@ -5,7 +5,7 @@
#define UNITY_SUPPORT_INSTANCING
#endif
-#if defined(SHADER_API_SWITCH)
+#if defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
#define UNITY_SUPPORT_INSTANCING
#endif
@@ -14,7 +14,7 @@
#endif
// These platforms support dynamically adjusting the instancing CB size according to the current batch.
-#if defined(SHADER_API_D3D11) || defined(SHADER_API_GLCORE) || defined(SHADER_API_GLES3) || defined(SHADER_API_METAL) || defined(SHADER_API_PSSL) || defined(SHADER_API_VULKAN) || defined(SHADER_API_SWITCH) || defined(SHADER_API_WEBGPU)
+#if defined(SHADER_API_D3D11) || defined(SHADER_API_GLCORE) || defined(SHADER_API_GLES3) || defined(SHADER_API_METAL) || defined(SHADER_API_PSSL) || defined(SHADER_API_VULKAN) || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2) || defined(SHADER_API_WEBGPU)
#define UNITY_INSTANCING_SUPPORT_FLEXIBLE_ARRAY_SIZE
#endif
@@ -38,7 +38,7 @@
#define UNITY_DOTS_INSTANCING_ENABLED
// On GL & GLES, use UBO path, on every other platform use SSBO path (including Switch, even if it defines SHADER_API_GLCORE)
- #if (defined(SHADER_API_GLCORE) || defined(SHADER_API_GLES3)) && (!defined(SHADER_API_SWITCH))
+ #if (defined(SHADER_API_GLCORE) || defined(SHADER_API_GLES3)) && (!defined(SHADER_API_SWITCH)) && (!defined(SHADER_API_SWITCH2))
#define UNITY_DOTS_INSTANCING_UNIFORM_BUFFER
#endif
@@ -262,7 +262,7 @@
#elif defined(UNITY_MAX_INSTANCE_COUNT)
#define UNITY_INSTANCED_ARRAY_SIZE UNITY_MAX_INSTANCE_COUNT
#else
- #if (defined(SHADER_API_VULKAN) && defined(SHADER_API_MOBILE)) || defined(SHADER_API_SWITCH) || defined(SHADER_API_WEBGPU)
+ #if (defined(SHADER_API_VULKAN) && defined(SHADER_API_MOBILE)) || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2) || defined(SHADER_API_WEBGPU)
#define UNITY_INSTANCED_ARRAY_SIZE 250
#else
#define UNITY_INSTANCED_ARRAY_SIZE 500
@@ -366,6 +366,8 @@
#if defined(UNITY_USE_RENDERINGLAYER_ARRAY) && defined(UNITY_INSTANCING_SUPPORT_FLEXIBLE_ARRAY_SIZE)
UNITY_DEFINE_INSTANCED_PROP(float, unity_RenderingLayerArray)
#define unity_RenderingLayer UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, unity_RenderingLayerArray).xxxx
+ UNITY_DEFINE_INSTANCED_PROP(float, unity_RendererUserValueArray)
+ #define unity_RendererUserValue asuint(UNITY_ACCESS_INSTANCED_PROP(unity_Builtins0, unity_RendererUserValueArray).x)
#endif
UNITY_INSTANCING_BUFFER_END(unity_Builtins0)
@@ -380,7 +382,9 @@
#if defined(UNITY_USE_RENDERINGLAYER_ARRAY) && !defined(UNITY_INSTANCING_SUPPORT_FLEXIBLE_ARRAY_SIZE)
UNITY_DEFINE_INSTANCED_PROP(float, unity_RenderingLayerArray)
#define unity_RenderingLayer UNITY_ACCESS_INSTANCED_PROP(unity_Builtins1, unity_RenderingLayerArray).xxxx
- #endif
+ UNITY_DEFINE_INSTANCED_PROP(float, unity_RendererUserValueArray)
+ #define unity_RendererUserValue asuint(UNITY_ACCESS_INSTANCED_PROP(unity_Builtins1, unity_RendererUserValueArray).x)
+ #endif
#if defined(UNITY_USE_RENDERER_BOUNDS)
UNITY_DEFINE_INSTANCED_PROP(float4, unity_RendererBounds_MinArray)
UNITY_DEFINE_INSTANCED_PROP(float4, unity_RendererBounds_MaxArray)
diff --git a/Packages/com.unity.render-pipelines.core/Shaders/CoreCopy.shader b/Packages/com.unity.render-pipelines.core/Shaders/CoreCopy.shader
index dc6870af200..bb86957a949 100644
--- a/Packages/com.unity.render-pipelines.core/Shaders/CoreCopy.shader
+++ b/Packages/com.unity.render-pipelines.core/Shaders/CoreCopy.shader
@@ -2,80 +2,77 @@ Shader "Hidden/CoreSRP/CoreCopy"
{
SubShader
{
- Tags { "RenderType" = "Opaque" }
- ZClip Off
- ZTest Off
- ZWrite Off Cull Off
+ HLSLINCLUDE
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl"
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/TextureXR.hlsl"
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl"
+
+ #pragma vertex Vert
+
+ struct Attributes
+ {
+ uint vertexID : SV_VertexID;
+ UNITY_VERTEX_INPUT_INSTANCE_ID
+ };
+
+ struct Varyings
+ {
+ float4 positionCS : SV_POSITION;
+ UNITY_VERTEX_OUTPUT_STEREO
+ };
+
+ Varyings Vert(Attributes input)
+ {
+ Varyings output;
+ UNITY_SETUP_INSTANCE_ID(input);
+ UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
+
+ output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
+ return output;
+ }
+
+ ENDHLSL
+
Pass
{
Name "Copy"
-
- HLSLPROGRAM
- #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
- #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl"
- #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/TextureXR.hlsl"
- #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl"
+ ZClip Off
+ ZTest Off
+ ZWrite Off
+ Cull Off
+ HLSLPROGRAM
#pragma multi_compile_fragment _ DISABLE_TEXTURE2D_X_ARRAY
- #pragma vertex Vert
#pragma fragment CopyFrag
-
// Declares the framebuffer input as a texture 2d containing half.
FRAMEBUFFER_INPUT_X_FLOAT(0);
- struct Attributes
- {
- uint vertexID : SV_VertexID;
- UNITY_VERTEX_INPUT_INSTANCE_ID
- };
-
- struct Varyings
- {
- float4 positionCS : SV_POSITION;
- UNITY_VERTEX_OUTPUT_STEREO
- };
-
- Varyings Vert(Attributes input)
- {
- Varyings output;
- UNITY_SETUP_INSTANCE_ID(input);
- UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
-
- output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
- return output;
- }
-
- // Out frag function takes as input a struct that contains the screen space coordinate we are going to use to sample our texture. It also writes to SV_Target0, this has to match the index set in the UseTextureFragment(sourceTexture, 0, …) we defined in our render pass script.
+ // Out frag function takes as input a struct that contains the screen space coordinate we are going to use to sample our texture. It also writes to SV_Target0, this has to match the index set in the UseTextureFragment(sourceTexture, 0, …) we defined in our render pass script.
float4 CopyFrag(Varyings input) : SV_Target0
{
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
// read previous subpasses directly from the framebuffer.
half4 color = LOAD_FRAMEBUFFER_INPUT_X(0, input.positionCS.xy);
-
+
// Modify the sampled color
return color;
}
ENDHLSL
}
- Tags { "RenderType" = "Opaque" }
- ZClip Off
- ZTest Off
- ZWrite Off Cull Off
Pass
{
Name "CopyMS"
+ ZClip Off
+ ZTest Off
+ ZWrite Off
+ Cull Off
HLSLPROGRAM
- #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
- #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Packing.hlsl"
- #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/TextureXR.hlsl"
- #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/UnityInstancing.hlsl"
-
#pragma multi_compile_fragment _ DISABLE_TEXTURE2D_X_ARRAY
- #pragma vertex Vert
#pragma fragment CopyFragMS
#pragma target 4.5
#pragma require msaatex
@@ -83,29 +80,7 @@ Shader "Hidden/CoreSRP/CoreCopy"
// Declares the framebuffer input as a texture 2d containing half.
FRAMEBUFFER_INPUT_X_FLOAT_MS(0);
- struct Attributes
- {
- uint vertexID : SV_VertexID;
- UNITY_VERTEX_INPUT_INSTANCE_ID
- };
-
- struct Varyings
- {
- float4 positionCS : SV_POSITION;
- UNITY_VERTEX_OUTPUT_STEREO
- };
-
- Varyings Vert(Attributes input)
- {
- Varyings output;
- UNITY_SETUP_INSTANCE_ID(input);
- UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
-
- output.positionCS = GetFullScreenTriangleVertexPosition(input.vertexID);
- return output;
- }
-
- // Out frag function takes as input a struct that contains the screen space coordinate we are going to use to sample our texture. It also writes to SV_Target0, this has to match the index set in the UseTextureFragment(sourceTexture, 0, …) we defined in our render pass script.
+ // Out frag function takes as input a struct that contains the screen space coordinate we are going to use to sample our texture. It also writes to SV_Target0, this has to match the index set in the UseTextureFragment(sourceTexture, 0, …) we defined in our render pass script.
float4 CopyFragMS(Varyings input, uint sampleID : SV_SampleIndex) : SV_Target0
{
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(input);
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/NativePassCompilerRenderGraphTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/NativePassCompilerRenderGraphTests.cs
index 882c0edd34e..20d922628a0 100644
--- a/Packages/com.unity.render-pipelines.core/Tests/Editor/NativePassCompilerRenderGraphTests.cs
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/NativePassCompilerRenderGraphTests.cs
@@ -83,7 +83,6 @@ public void OneTimeTearDown()
RenderGraph AllocateRenderGraph()
{
RenderGraph g = new RenderGraph();
- g.nativeRenderPassesEnabled = true;
return g;
}
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraph.ComputeGraphHash.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraph.ComputeGraphHash.cs
index adc3d8d66df..662eb57bd41 100644
--- a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraph.ComputeGraphHash.cs
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraph.ComputeGraphHash.cs
@@ -178,7 +178,7 @@ public void ComputeGraphHash_WhenManyDifferentPassesUsed_HashcodeIsDifferent()
Assert.AreNotEqual(hash0, hash1);
}
- static TestCaseData[] s_TextureParametersCases =
+ public static TestCaseData[] s_TextureParametersCases =
{
new TestCaseData(new TextureDesc(Vector2.zero) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm },
new TextureDesc(Vector2.zero) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm },
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs
index a395d9e26e5..927ab1d41c6 100644
--- a/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/RenderGraphTests.cs
@@ -30,174 +30,12 @@ static RenderGraphTestsOnLoad()
}
}
- partial class RenderGraphTests
+ partial class RenderGraphTests : RenderGraphTestsCore
{
const string k_InvalidOperationMessage = "InvalidOperationException: ";
- // For RG Record/Hash/Compile testing, use m_RenderGraph
- RenderGraph m_RenderGraph;
-
- RenderPipelineAsset m_OldDefaultRenderPipeline;
- RenderPipelineAsset m_OldQualityRenderPipeline;
-
- // For RG Execute/Submit testing with rendering, use m_RenderGraphTestPipeline and m_RenderGraph in its recordRenderGraphBody
- RenderGraphTestPipelineAsset m_RenderGraphTestPipeline;
- RenderGraphTestGlobalSettings m_RenderGraphTestGlobalSettings;
-
Dictionary> m_GraphStateActions = new Dictionary>();
- // We need a camera to execute the render graph and a game object to attach a camera
- GameObject m_GameObject;
- Camera m_Camera;
-
- // For the testing of the following RG steps: Execute and Submit (native) with camera rendering, use this custom RenderGraph render pipeline
- // through a camera render call to test the RG with a real ScriptableRenderContext
- class RenderGraphTestPipelineAsset : RenderPipelineAsset
- {
- public Action recordRenderGraphBody;
- public RenderGraph renderGraph;
- protected override RenderPipeline CreatePipeline()
- {
- return new RenderGraphTestPipelineInstance(this);
- }
-
- // Called only once per UTR
- void OnEnable()
- {
- renderGraph = new();
- }
- }
-
- class RenderGraphTestPipelineInstance : RenderPipeline
- {
- RenderGraphTestPipelineAsset asset;
-
- // Having the RG at this level allows us to handle RG framework within Render() for easier testing
- RenderGraph m_RenderGraph;
-
- public RenderGraphTestPipelineInstance(RenderGraphTestPipelineAsset asset)
- {
- this.asset = asset;
- this.m_RenderGraph = asset.renderGraph;
- }
-
- protected override void Render(ScriptableRenderContext renderContext, List cameras)
- {
- foreach (var camera in cameras)
- {
- if (!camera.enabled)
- continue;
-
- var cmd = CommandBufferPool.Get();
-
- RenderGraphParameters rgParams = new()
- {
- commandBuffer = cmd,
- scriptableRenderContext = renderContext,
- currentFrameIndex = Time.frameCount,
- invalidContextForTesting = false
- };
-
- try
- {
- // Necessary to reinitialize the state, since we have many tests which do not use this system but directly adding
- // passes to the graph (to test the compilation) and destroying them without executing them with camera.Render()
- // (e.g GraphicsPassWriteWaitOnAsyncPipe). So the state becomes RecordGraph because of the Builder.Destroy logic.
- m_RenderGraph.RenderGraphState = RenderGraphState.Idle;
-
- m_RenderGraph.BeginRecording(rgParams);
-
- asset.recordRenderGraphBody?.Invoke(renderContext, camera, cmd);
-
- m_RenderGraph.EndRecordingAndExecute();
- }
- catch (Exception e)
- {
- if (m_RenderGraph.ResetGraphAndLogException(e))
- throw;
- return;
- }
-
- renderContext.ExecuteCommandBuffer(cmd);
-
- CommandBufferPool.Release(cmd);
- }
- renderContext.Submit();
- }
- }
-
- [SupportedOnRenderPipeline(typeof(RenderGraphTestPipelineAsset))]
- [System.ComponentModel.DisplayName("RenderGraphTest")]
- class RenderGraphTestGlobalSettings : RenderPipelineGlobalSettings
- {
- [SerializeField] RenderPipelineGraphicsSettingsContainer m_Settings = new();
- protected override List settingsList => m_Settings.settingsList;
- }
-
- [OneTimeSetUp]
- public void Setup()
- {
- // Setting default global settings to the custom RG render pipeline type, no quality settings so we can rely on the default RP
- m_RenderGraphTestGlobalSettings = ScriptableObject.CreateInstance();
-#if UNITY_EDITOR
- EditorGraphicsSettings.SetRenderPipelineGlobalSettingsAsset(m_RenderGraphTestGlobalSettings);
-#endif
- // Saving old render pipelines to set them back after testing
- m_OldDefaultRenderPipeline = GraphicsSettings.defaultRenderPipeline;
- m_OldQualityRenderPipeline = QualitySettings.renderPipeline;
-
- // Setting the custom RG render pipeline
- m_RenderGraphTestPipeline = ScriptableObject.CreateInstance();
- GraphicsSettings.defaultRenderPipeline = m_RenderGraphTestPipeline;
- QualitySettings.renderPipeline = m_RenderGraphTestPipeline;
-
- // Getting the RG from the custom asset pipeline
- m_RenderGraph = m_RenderGraphTestPipeline.renderGraph;
- m_RenderGraph.nativeRenderPassesEnabled = true;
-
- // Necessary to disable it for the Unit Tests, as the caller is not the same.
- RenderGraph.RenderGraphExceptionMessages.enableCaller = false;
-
- // We need a real ScriptableRenderContext and a camera to execute the Render Graph
- m_GameObject = new GameObject("testGameObject")
- {
- hideFlags = HideFlags.HideAndDontSave
- };
- m_GameObject.tag = "MainCamera";
- m_Camera = m_GameObject.AddComponent();
- }
-
- [OneTimeTearDown]
- public void Cleanup()
- {
- GraphicsSettings.defaultRenderPipeline = m_OldDefaultRenderPipeline;
- m_OldDefaultRenderPipeline = null;
-
- QualitySettings.renderPipeline = m_OldQualityRenderPipeline;
- m_OldQualityRenderPipeline = null;
-
- m_RenderGraph.Cleanup();
-
- Object.DestroyImmediate(m_RenderGraphTestPipeline);
-
-#if UNITY_EDITOR
- EditorGraphicsSettings.SetRenderPipelineGlobalSettingsAsset(null);
-#endif
- Object.DestroyImmediate(m_RenderGraphTestGlobalSettings);
-
- GameObject.DestroyImmediate(m_GameObject);
- m_GameObject = null;
- m_Camera = null;
- }
-
- [TearDown]
- public void CleanupRenderGraph()
- {
- // Cleaning all Render Graph resources and data structures
- // Nothing remains, Render Graph in next test will start from scratch
- m_RenderGraph.ForceCleanup();
- }
-
class RenderGraphTestPassData
{
public TextureHandle[] textures = new TextureHandle[8];
@@ -933,7 +771,7 @@ public void RenderPassWithNoRenderFuncThrows()
}
};
LogAssert.Expect(LogType.Error, "Render Graph Execution error");
- LogAssert.Expect(LogType.Exception, "InvalidOperationException: RenderPass TestPassWithNoRenderFunc was not provided with an execute function.");
+ LogAssert.Expect(LogType.Exception, "InvalidOperationException: In pass TestPassWithNoRenderFunc - " + RenderGraph.RenderGraphExceptionMessages.k_NoRenderFunction);
m_Camera.Render();
}
@@ -974,11 +812,13 @@ public void ExceptionsOnExecuteAreHandledAsExpected()
[Test]
public void UsingAddRenderPassWithNRPThrows()
{
- // m_RenderGraph.nativeRenderPassesEnabled is set to true in the setup
+ // m_RenderGraph.nativeRenderPassesEnabled is true by default
// record and execute render graph calls
m_RenderGraphTestPipeline.recordRenderGraphBody = (context, camera, cmd) =>
{
+#pragma warning disable CS0618 // Type or member is obsolete
using var builder = m_RenderGraph.AddRenderPass("HDRP Render Pass", out var passData);
+#pragma warning restore CS0618 // Type or member is obsolete
};
LogAssert.Expect(LogType.Error, "Render Graph Execution error");
@@ -1103,6 +943,137 @@ public void RenderGraphClearDepthTextureWithDepthReadOnlyFlag()
}
}
+ [Test]
+ public void RenderGraphTilePropertiesWorksWithDepthOnlyReadFlag()
+ {
+ const int kWidth = 4;
+ const int kHeight = 4;
+
+ TextureHandle texture0 = m_RenderGraph.CreateTexture(new TextureDesc(kWidth, kHeight) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm });
+ TextureHandle depthTexture = m_RenderGraph.CreateTexture(new TextureDesc(kWidth, kHeight) { colorFormat = GraphicsFormat.D16_UNorm });
+ // no depth with Tile Properties
+ using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass0", out var passData))
+ {
+ builder.SetRenderAttachment(texture0, 0, AccessFlags.Write);
+ builder.AllowPassCulling(false);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.TileProperties);
+ builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { });
+ }
+
+ // with depth
+ using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass1", out var passData))
+ {
+ builder.SetRenderAttachment(texture0, 0, AccessFlags.Write);
+ builder.SetRenderAttachmentDepth(depthTexture, AccessFlags.Write);
+ builder.AllowPassCulling(false);
+ builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { });
+ }
+
+ var result = m_RenderGraph.CompileNativeRenderGraph(m_RenderGraph.ComputeGraphHash());
+ var passes = result.contextData.GetNativePasses();
+ // EXpected result is that ReadOnlyDepth is added to subpass 0 to be able to merge subpass 0 and 1 into the same render pass.
+ // TileProperties flag should be added to subpass 0 and not interfere with merging.
+ Assert.AreEqual(1, passes.Count); // 1 native Pass
+ Assert.AreEqual(2, passes[0].numNativeSubPasses);
+ Assert.True(result.contextData.nativeSubPassData[0].flags.HasFlag(SubPassFlags.ReadOnlyDepth));
+ Assert.True(result.contextData.nativeSubPassData[0].flags.HasFlag(SubPassFlags.TileProperties));
+ }
+
+ [Test]
+ public void RenderGraphTilePropertiesWorksWhenItsLast()
+ {
+ const int kWidth = 4;
+ const int kHeight = 4;
+
+ TextureHandle texture0 = m_RenderGraph.CreateTexture(new TextureDesc(kWidth, kHeight) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm });
+ TextureHandle depthTexture = m_RenderGraph.CreateTexture(new TextureDesc(kWidth, kHeight) { colorFormat = GraphicsFormat.D16_UNorm });
+
+ // no Tile Properties
+ using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass0", out var passData))
+ {
+ builder.SetRenderAttachment(texture0, 0, AccessFlags.Write);
+ builder.AllowPassCulling(false);
+ builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { });
+ }
+
+ // with Tile Properties
+ using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass1", out var passData))
+ {
+ builder.SetRenderAttachment(texture0, 0, AccessFlags.Write);
+ builder.AllowPassCulling(false);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.TileProperties);
+ builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { });
+ }
+
+ var result = m_RenderGraph.CompileNativeRenderGraph(m_RenderGraph.ComputeGraphHash());
+ var passes = result.contextData.GetNativePasses();
+ // TilePrperties flag should be added to subpass 0 and not interfere with merging.
+ Assert.AreEqual(1, passes.Count); // 1 native Pass
+ Assert.True(result.contextData.nativeSubPassData[0].flags.HasFlag(SubPassFlags.TileProperties));
+ }
+
+ [Test]
+ public void RenderGraphTilePropertiesWorksWhenItsMiddle()
+ {
+ const int kWidth = 4;
+ const int kHeight = 4;
+
+ TextureHandle texture0 = m_RenderGraph.CreateTexture(new TextureDesc(kWidth, kHeight) { colorFormat = GraphicsFormat.R8G8B8A8_UNorm });
+ TextureHandle depthTexture = m_RenderGraph.CreateTexture(new TextureDesc(kWidth, kHeight) { colorFormat = GraphicsFormat.D16_UNorm });
+
+ // no tile properties
+ using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass0", out var passData))
+ {
+ builder.SetRenderAttachment(texture0, 0, AccessFlags.Write);
+ builder.AllowPassCulling(false);
+ builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { });
+ }
+
+ // with Tile Properties
+ using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass1", out var passData))
+ {
+ builder.SetRenderAttachment(texture0, 0, AccessFlags.Write);
+ builder.AllowPassCulling(false);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.TileProperties);
+ builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { });
+ }
+
+ // no tile properties
+ using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass2", out var passData))
+ {
+ builder.SetRenderAttachment(texture0, 0, AccessFlags.Write);
+ builder.AllowPassCulling(false);
+ builder.SetRenderFunc((RenderGraphTestPassData data, RasterGraphContext context) => { });
+ }
+
+ var result = m_RenderGraph.CompileNativeRenderGraph(m_RenderGraph.ComputeGraphHash());
+ var passes = result.contextData.GetNativePasses();
+ // TilePrperties flag should be added to subpass 0 and not interfere with merging.
+ Assert.AreEqual(1, passes.Count); // 1 native Pass
+ Assert.True(result.contextData.nativeSubPassData[0].flags.HasFlag(SubPassFlags.TileProperties));
+ }
+
+ [Test]
+ public void RenderGraphTilePropertiesCanOnlyBeSetForOnePass()
+ {
+ m_RenderGraphTestPipeline.recordRenderGraphBody = (context, camera, cmd) =>
+ {
+ using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass0", out var passData))
+ {
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.TileProperties);
+ }
+
+ using (var builder = m_RenderGraph.AddRasterRenderPass("TestPass1", out var passData))
+ {
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.TileProperties);
+ }
+ LogAssert.Expect(LogType.Error, "Render Graph Execution error");
+ LogAssert.Expect(LogType.Exception, "Exception: ExtendedFeatureFlags.TileProperties can only be set once per render graph (render graph RenderGraph, pass TestPass1), previously set at (pass TestPass0).");
+ var result = m_RenderGraph.CompileNativeRenderGraph(m_RenderGraph.ComputeGraphHash());
+ };
+ m_Camera.Render();
+ }
+
/*
// Disabled for now as version management is not exposed to user code
[Test]
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools.meta
new file mode 100644
index 00000000000..e16ce82813c
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 167414eb9b5aac148a050554ea60a5cc
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/.buginfo b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/.buginfo
new file mode 100644
index 00000000000..a8e3ae67ae4
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/.buginfo
@@ -0,0 +1 @@
+area: Graphics Tools
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader.meta
new file mode 100644
index 00000000000..60c77487071
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: aa8ba3d47aaac7e4b830b55e85d7d679
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistryTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistryTests.cs
new file mode 100644
index 00000000000..e985f0fdb43
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistryTests.cs
@@ -0,0 +1,144 @@
+using System;
+using System.Collections.Generic;
+using NUnit.Framework;
+using UnityEngine.Rendering;
+
+namespace UnityEditor.Rendering.Tools.Tests
+{
+ class MaterialUpgraderRegistryTests
+ {
+ class TestPipeline : RenderPipelineAsset
+ {
+ protected override RenderPipeline CreatePipeline()
+ {
+ throw new System.NotImplementedException();
+ }
+ }
+
+ public class MaterialUpgraderTest1000 : MaterialUpgrader
+ {
+ public override int priority => 1000;
+
+ public MaterialUpgraderTest1000(string oldShaderName, string newShaderName)
+ {
+ if (oldShaderName == null)
+ throw new ArgumentNullException("oldShaderName");
+
+ RenameShader(oldShaderName, newShaderName, null);
+ }
+ }
+
+ public class MaterialUpgraderTest2000 : MaterialUpgrader
+ {
+ public override int priority => 2000;
+
+ public MaterialUpgraderTest2000(string oldShaderName, string newShaderName)
+ {
+ if (oldShaderName == null)
+ throw new ArgumentNullException("oldShaderName");
+
+ RenameShader(oldShaderName, newShaderName, null);
+ }
+ }
+
+ public class MaterialUpgraderTest0000 : MaterialUpgrader
+ {
+ public MaterialUpgraderTest0000(string oldShaderName, string newShaderName)
+ {
+ if (oldShaderName == null)
+ throw new ArgumentNullException("oldShaderName");
+
+ RenameShader(oldShaderName, newShaderName, null);
+ }
+ }
+
+ public class MaterialUpgraderTest5000 : MaterialUpgrader
+ {
+ public override int priority => 5000;
+
+ public MaterialUpgraderTest5000(string oldShaderName, string newShaderName)
+ {
+ if (oldShaderName == null)
+ throw new ArgumentNullException("oldShaderName");
+
+ RenameShader(oldShaderName, newShaderName, null);
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(TestPipeline))]
+ private class MaterialUpgraderProvider1000 : IMaterialUpgradersProvider
+ {
+ public int priority => 1000;
+
+ public IEnumerable GetUpgraders()
+ {
+ yield return new MaterialUpgraderTest1000("SomePath", "1000");
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(TestPipeline))]
+ private class MaterialUpgraderProvider5000 : IMaterialUpgradersProvider
+ {
+ public int priority => 5000;
+
+ public IEnumerable GetUpgraders()
+ {
+ yield return new MaterialUpgraderTest5000("SomePath1", "5000");
+ yield return new MaterialUpgraderTest5000("A", "5000");
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(TestPipeline))]
+ private class MaterialUpgraderProvider0000 : IMaterialUpgradersProvider
+ {
+ public IEnumerable GetUpgraders()
+ {
+ yield return new MaterialUpgraderTest2000("SomePath", "2000");
+ yield return new MaterialUpgraderTest1000("SomePath1", "1000");
+ yield return new MaterialUpgraderTest0000("Z", "0000");
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(TestPipeline))]
+ private class MaterialUpgraderProvider2000 : IMaterialUpgradersProvider
+ {
+ public IEnumerable GetUpgraders()
+ {
+ yield return new MaterialUpgraderTest5000("SomePath", "5000");
+ yield return new MaterialUpgraderTest2000("SomePath1", "2000");
+ }
+ }
+
+ [Test]
+ public void MaterialUpgraders_AreSortedCorrectly()
+ {
+ var expected = new List<(Type type, string oldShader, string newShader, int priority)>
+ {
+ (typeof(MaterialUpgraderTest5000), "A", "5000", 5000),
+ (typeof(MaterialUpgraderTest5000), "SomePath", "5000", 5000),
+ (typeof(MaterialUpgraderTest2000), "SomePath", "2000", 2000),
+ (typeof(MaterialUpgraderTest1000), "SomePath", "1000", 1000),
+ (typeof(MaterialUpgraderTest5000), "SomePath1", "5000", 5000),
+ (typeof(MaterialUpgraderTest2000), "SomePath1", "2000", 2000),
+ (typeof(MaterialUpgraderTest1000), "SomePath1", "1000", 1000),
+ (typeof(MaterialUpgraderTest0000), "Z", "0000", 0),
+ };
+
+ var actual = MaterialUpgraderRegistry.instance.GetMaterialUpgradersForPipeline(typeof(TestPipeline));
+
+ Assert.AreEqual(expected.Count, actual.Count, "Mismatch in number of upgraders returned");
+
+ for (int i = 0; i < expected.Count; i++)
+ {
+ var expectedItem = expected[i];
+ var actualItem = actual[i];
+
+ Assert.AreEqual(expectedItem.type, actualItem.GetType(), $"Type mismatch at index {i}");
+ Assert.AreEqual(expectedItem.oldShader, actualItem.OldShaderPath, $"Old shader mismatch at index {i}");
+ Assert.AreEqual(expectedItem.newShader, actualItem.NewShaderPath, $"New shader mismatch at index {i}");
+ Assert.AreEqual(expectedItem.priority, actualItem.priority, $"Priority mismatch at index {i}");
+ }
+ }
+ }
+
+}
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistryTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistryTests.cs.meta
new file mode 100644
index 00000000000..457201d0cdf
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderRegistryTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: be1c44158e9907547b5966f847328df5
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderTests.cs b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderTests.cs
new file mode 100644
index 00000000000..edf579da95b
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderTests.cs
@@ -0,0 +1,127 @@
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Linq;
+using NUnit.Framework;
+using static UnityEditor.Rendering.MaterialUpgrader;
+
+namespace UnityEditor.Rendering.Tools.Tests
+{
+ class MaterialUpgraderTests
+ {
+ public class MaterialUpgradeTestCase
+ {
+ public List Materials { get; set; }
+ public HashSet Upgraders { get; set; }
+ public HashSet IgnoredShaders { get; set; }
+ public List ExpectedUpgradeEntries { get; set; }
+ public string ExpectedLog { get; set; }
+ public override string ToString() => ExpectedLog?.Split('\n').FirstOrDefault() ?? "Case";
+ }
+
+ public static IEnumerable TestCases
+ {
+ get
+ {
+ // Case 1: Upgradable
+ var info1 = new MaterialInfo { ShaderName = "Standard" };
+ yield return new TestCaseData(new MaterialUpgradeTestCase
+ {
+ Materials = new() { info1 },
+ Upgraders = new() { "Standard" },
+ IgnoredShaders = new(),
+ ExpectedUpgradeEntries = new()
+ {
+ new MaterialUpgradeEntry
+ {
+ MaterialInfo = info1,
+ AvailableForUpgrade = true,
+ NotAvailableForUpgradeReason = ""
+ }
+ },
+ ExpectedLog = "Testing" + Environment.NewLine + "Upgrading material: using shader: Standard" + Environment.NewLine
+ }).SetName("Material is upgradable");
+
+ // Case 2: Not upgradable
+ var info2 = new MaterialInfo { ShaderName = "Legacy/Diffuse" };
+ yield return new TestCaseData(new MaterialUpgradeTestCase
+ {
+ Materials = new() { info2 },
+ Upgraders = new(),
+ IgnoredShaders = new(),
+ ExpectedUpgradeEntries = new()
+ {
+ new()
+ {
+ MaterialInfo = info2,
+ AvailableForUpgrade = false,
+ NotAvailableForUpgradeReason = MaterialUpgrader.GenerateReason(info2)
+ }
+ },
+ ExpectedLog = "Testing" + Environment.NewLine + $"Skipping material: - {MaterialUpgrader.GenerateReason(info2)}" + Environment.NewLine
+ }).SetName("Material is not upgradable");
+
+ // Case 3: Ignored
+ var info3 = new MaterialInfo { ShaderName = "Unlit/Color" };
+ yield return new TestCaseData(new MaterialUpgradeTestCase
+ {
+ Materials = new() { info3 },
+ Upgraders = new() { "Unlit/Color" },
+ IgnoredShaders = new() { "Unlit/Color" },
+ ExpectedUpgradeEntries = new(),
+ ExpectedLog = string.Empty
+ }).SetName("Material is ignored");
+
+ // Case 4: Variant
+ var info4 = new MaterialInfo
+ {
+ Name = "Standard Variant",
+ BaseMaterialName = "Standard Base",
+ ShaderName = "Standard",
+ IsVariant = true
+ };
+ yield return new TestCaseData(new MaterialUpgradeTestCase
+ {
+ Materials = new() { info4 },
+ Upgraders = new() { "Standard" },
+ IgnoredShaders = new(),
+ ExpectedUpgradeEntries = new()
+ {
+ new MaterialUpgradeEntry
+ {
+ MaterialInfo = info4,
+ AvailableForUpgrade = false,
+ NotAvailableForUpgradeReason = MaterialUpgrader.GenerateReason(info4)
+ }
+ },
+ ExpectedLog = $"Testing\r\nSkipping material: Standard Variant - {MaterialUpgrader.GenerateReason(info4)}\r\n"
+ }).SetName("Material is a variant and skipped");
+ }
+ }
+
+ [TestCaseSource(nameof(TestCases))]
+ public void FetchUpgradeOptionsTest(MaterialUpgradeTestCase testCase)
+ {
+ var result = MaterialUpgrader.FetchUpgradeOptions(
+ testCase.Upgraders,
+ testCase.IgnoredShaders,
+ testCase.Materials).ToList();
+
+ Assert.That(result, Is.EqualTo(testCase.ExpectedUpgradeEntries));
+ }
+
+ [TestCaseSource(nameof(TestCases))]
+ public void PerformUpgradeTest(MaterialUpgradeTestCase testCase)
+ {
+ var entries = MaterialUpgrader.FetchUpgradeOptions(
+ testCase.Upgraders,
+ testCase.IgnoredShaders,
+ testCase.Materials).ToList();
+
+ var log = MaterialUpgrader.PerformUpgradeInternal(
+ entries, null, testCase.IgnoredShaders, "Testing", false, UpgradeFlags.None);
+
+ Assert.That(log, Is.EqualTo(testCase.ExpectedLog));
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderTests.cs.meta b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderTests.cs.meta
new file mode 100644
index 00000000000..3b7d83ab730
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.core/Tests/Editor/Tools/MaterialUpgrader/MaterialUpgraderTests.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 81ee3cf225778834abb6a30cf1007ea1
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.core/Tests/Runtime/Threading/FunctionTestsWave.compute b/Packages/com.unity.render-pipelines.core/Tests/Runtime/Threading/FunctionTestsWave.compute
index 9105fdf348a..f6a1ca315f4 100644
--- a/Packages/com.unity.render-pipelines.core/Tests/Runtime/Threading/FunctionTestsWave.compute
+++ b/Packages/com.unity.render-pipelines.core/Tests/Runtime/Threading/FunctionTestsWave.compute
@@ -46,7 +46,9 @@
// 1. The BitXor, Product, and PrefixProduct SM6 intrinsics fail to compile on Xbox One because they aren't supported.
// We could potentially emulate these if necessary, but they aren't particularly useful.
// For now, we just skip the native path tests on Xbox One.
-#define ENABLE_SM6_WORKAROUND (defined(SHADER_API_GAMECORE_XBOXONE) || defined(SHADER_API_XBOXONE))
+//
+// 2. On some platforms, we probably cannot access SM6 instrinsics when using the HLSLcc pipeline
+#define ENABLE_SM6_WORKAROUND (defined(SHADER_API_GAMECORE_XBOXONE) || defined(SHADER_API_XBOXONE) || defined(SHADER_API_SWITCH2))
// Force emulation on whenever a specific wave size is provided
#if defined(THREADING_WAVE_SIZE) || ENABLE_SM6_WORKAROUND
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ambient-Occlusion.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ambient-Occlusion.md
index c6b4f3172e9..55dca7373d0 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ambient-Occlusion.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ambient-Occlusion.md
@@ -1,24 +1,24 @@
-# Ambient occlusion
+# Assign an ambient occlusion texture
-The High Definition Render Pipeline (HDRP) uses ambient occlusion to approximate ambient light on a GameObject’s surface that has been cast by details present in the Material but not the surface geometry. Since these details don't exist on the model, you must provide an ambient occlusion Texture for HDRP to occlude indirect lighting (lighting from Lightmaps, [Light Probes](https://docs.unity3d.com/Manual/LightProbes.html) or Ambient Light Probes). HDRP also uses the ambient occlusion Texture to calculate specular occlusion. It calculates specular occlusion from the Camera's view vector and the ambient occlusion Texture to dim reflections in cavities.
+To assign an [ambient occlusion texture](ambient-occlusion-introduction.md) to a GameObject, follow these steps:
-To generate an ambient occlusion Texture, you can use external software like:
+1. Use an external software package to create a single-channel ambient occlusion texture that maps the corners and crevices where light is occluded. Use values closer to `0` to indicate more occlusion, and values closer to `1` to indicate less occlusion.
-* xNormal
-* Substance Designer or Painter
-* Knald
+1. Create a [mask map](Mask-Map-and-Detail-Map.md#MaskMap) texture, and use the ambient occlusion texture as the green channel.
-When authoring ambient occlusion Textures, be aware that a value of 0 specifies an area that's fully occluded and a value of 1 specifies an area that's fully visible.
+1. Import the mask map texture into Unity.
-When you create the Texture, you must apply it to a Material. To do this, you must use the green channel of a [mask map](Mask-Map-and-Detail-Map.md#MaskMap).
+1. Select a material in the **Project** window, then drag the mask map texture into the **Occlusion** (⊙) property of the **Inspector** window.
+
+HDRP also uses the ambient occlusion texture to calculate specular occlusion, by reducing the intensity of reflections in corners.
**Note**: Ambient occlusion in a Lit Shader using [deferred rendering](Forward-And-Deferred-Rendering.md) affects emission due to a technical constraint. Lit Shaders that use [forward rendering](Forward-And-Deferred-Rendering.md) don't have this constraint and don't affect emission.
-## Properties
+For more information about ambient occlusion texture properties in an HDRP material, refer to the material in [Materials and surfaces](materials-and-surfaces.md).
-The ambient occlusion properties are located in the **Mask Map** section of the **Surface Inputs** foldout of your material's **Inspector** window.
+## Additional resources
-| Property | Description |
-| ------------------------------- | ------------------------------------------------------------ |
-| **Mask Map - Green channel** | Assign the ambient occlusion map in the green channel of the **Mask Map** Texture. HDRP uses the green channel of this map to calculate ambient occlusion. |
-| **Ambient Occlusion Remapping** | Remaps the ambient occlusion map in the green channel of the **Mask Map** between the minimum and maximum values you define on the slider. These values are between 0 and 1.
• Drag the left handle to the right to make the ambient occlusion more subtle. • Drag the right handle to the left to apply ambient occlusion to the whole Material. This is useful when the GameObject this Material is on is occluded by a dynamic GameObject.
This property only appears when you assign a Texture to the **Mask Map**. |
+- [Screen space ambient occlusion (SSAO)](Override-Ambient-Occlusion.md)
+- [Ray-traced ambient occlusion (RTAO)](Ray-Traced-Ambient-Occlusion.md)
+- [Mask and detail maps](Mask-Map-and-Detail-Map.md#MaskMap)
+- [Textures](https://docs.unity3d.com/Manual/Textures-landing.html)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Custom-Pass-Injection-Points.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Custom-Pass-Injection-Points.md
index 3e20c3bc9c3..48cbda3cd3a 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Custom-Pass-Injection-Points.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Custom-Pass-Injection-Points.md
@@ -14,13 +14,14 @@ To learn when injection points happen in the render pipeline refer to [Execution
Unity triggers the following injection points in a frame, in order from top to bottom:
-| **Injection point** | **Available buffers** | **Description** |
-|---------------------------| ------------------------------------------------------------ |---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
-| BeforeRendering | Depth (Write) | Unity clears the depth buffer immediately before this injection point.
In this injection point you can write to the depth buffer so that Unity doesn’t render depth-tested, opaque objects.
You can also clear the buffer you allocated or the `Custom Buffer`.
When you select this Injection point for a [FullscreenCustom Pass](custom-pass-create-gameobject.md#full-screen-custom-pass), Unity assigns the camera color buffer as the target by default. |
-| AfterOpaqueDepthAndNormal | Depth (Read \| Write), Normal and roughness (Read \| Write), Motion Vectors (Write) | The available buffers for this injection point contain all opaque objects.
In this injection point you can modify the normal, roughness, depth, and motion vectors buffers. HDRP takes this into account in the lighting and the depth pyramid.
Normals and roughness are in the same buffer. You can use `DecodeFromNormalBuffer` and `EncodeIntoNormalBuffer` methods to read/write normal and roughness data.
The Motion Vectors buffer only includes object motion vector data when you use [forward rendering](Forward-And-Deferred-Rendering.md). To include object motion vector data in the Motion Vectors buffer when using deferred rendering, go to [Frame Settings](Frame-Settings.md) and enable **Depth Prepass within Deferred**. |
-| AfterOpaqueAndSky | Color (no pyramid \| Read \| Write), Depth (Read \| Write), Normal and roughness (Read), Motion Vectors (Read \| Write) | The available buffers for this injection point contain all opaque objects and the sky. Note that the Fog is rendered just after this pass, so if you modify the color buffer, fog will be added on top of your effect. |
-| BeforePreRefraction | Color (no pyramid \| Read \| Write), Depth (Read \| Write), Normal and roughness (Read), Motion Vectors (Read \| Write) | The available buffers for this injection point contain all opaque objects, the camera and object motion vectors, and the sky.
From this point, the motion vectors buffer is complete.
In this injection point you can render any transparent objects that require refraction. These objects are then included in the color pyramid that Unity uses for refraction when it renders transparent objects. |
-| BeforeTransparent | Color (Pyramid \| Read \| Write), Depth (Read \| Write), Normal and roughness (Read), Motion Vectors (Read) | The available buffers for this injection point contain: - All opaque objects. - Transparent PreRefraction objects. - Transparent objects with depth-prepass and screen space reflections (SSR) enabled.
In this Injection Point you can sample the color pyramid that Unity uses for transparent refraction. You can use this to create a blur effect. All objects Unity renders in this injection point will not be in the color pyramid.
You can also use this injection point to draw some transparent objects that refract the whole scene, like water. |
-| BeforePostProcess | Color (Pyramid \| Read \| Write), Depth (Read \| Write), Normal and roughness (Read), Motion Vectors (Read) | The available buffers for this injection point contain all geometry in the frame that uses High Dynamic Range (HDR). |
-| AfterPostProcess | Color (Read \| Write), Depth (Read) | The available buffers for this injection point contain the final render of the scene, including post-process effects.
This injection point executes the available buffers after Unity applies any post-processing effects.
If you select this injection point, objects that use the depth buffer display jittering artifacts.
When you select this injection point for a [FullscreenCustom Pass](custom-pass-create-gameobject.md#full-screen-custom-pass), Unity assigns the camera color buffer as the target by default.**Note:** When sampling scene color using HDSceneColor node in a FullScreenShaderGraph at this injection point, consider using a temporary buffer to handle concurrent read/write operations. See [Scene Color Sampling in AfterPostProcess](Custom-Pass-Scene-Color-Read.md) for implementation details. |
+| **Injection point** | **Available buffers** | **Description** |
+|-|-|-|
+| BeforeRendering | Depth (write) | Unity clears the depth buffer immediately before this injection point.
In this injection point you can write to the depth buffer so that Unity doesn’t render depth-tested, opaque objects.
You can also clear the buffer you allocated or the `Custom Buffer`.
When you select this Injection point for a [FullscreenCustom Pass](custom-pass-create-gameobject.md#full-screen-custom-pass), Unity assigns the camera color buffer as the target by default. |
+| AfterOpaqueDepthAndNormal | Depth (read, write), Normal and roughness (read, write), Motion vectors (write) | The available buffers for this injection point contain all opaque objects.
In this injection point you can modify the normal, roughness, depth, and motion vectors buffers. HDRP takes this into account in the lighting and the depth pyramid.
Normals and roughness are in the same buffer. You can use `DecodeFromNormalBuffer` and `EncodeIntoNormalBuffer` methods to read/write normal and roughness data.
The Motion vectors buffer only includes object motion vector data when you use [forward rendering](Forward-And-Deferred-Rendering.md). To include object motion vector data in the Motion vectors buffer when using deferred rendering, go to [Frame Settings](Frame-Settings.md) and enable **Depth Prepass within Deferred**. |
+| AfterOpaqueColor | Color (no pyramid; read, write), Depth (read, write), Normal and roughness (read), Motion vectors (read, write) | The color buffer contains all the opaque objects in your view. HDRP hasn't rendered the sky or fog yet, so if you change the color buffer in this injection point, HDRP applies fog on top of your effect. |
+| AfterOpaqueAndSky | Color (no pyramid; read, write), Depth (read, write), Normal and roughness (read), Motion vectors (read, write) | The available buffers for this injection point contain all opaque objects and the sky. Note that the Fog is rendered just after this pass, so if you modify the color buffer, fog will be added on top of your effect. |
+| BeforePreRefraction | Color (no pyramid; read, write), Depth (read, write), Normal and roughness (read), Motion vectors (read, write) | The available buffers for this injection point contain all opaque objects, the camera and object motion vectors, and the sky.
From this point, the motion vectors buffer is complete.
In this injection point you can render any transparent objects that require refraction. These objects are then included in the color pyramid that Unity uses for refraction when it renders transparent objects. |
+| BeforeTransparent | Color (Pyramid \| read, write), Depth (read, write), Normal and roughness (read), Motion vectors (read) | The available buffers for this injection point contain:
All opaque objects.
Transparent PreRefraction objects.
Transparent objects with depth-prepass and screen space reflections (SSR) enabled.
In this Injection Point you can sample the color pyramid that Unity uses for transparent refraction. You can use this to create a blur effect. All objects Unity renders in this injection point will not be in the color pyramid.
You can also use this injection point to draw some transparent objects that refract the whole scene, like water. |
+| BeforePostProcess | Color (Pyramid \| read, write), Depth (read, write), Normal and roughness (read), Motion vectors (read) | The available buffers for this injection point contain all geometry in the frame that uses High Dynamic Range (HDR). |
+| AfterPostProcess | Color (read, write), Depth (read) | The available buffers for this injection point contain the final render of the scene, including post-process effects.
This injection point executes the available buffers after Unity applies any post-processing effects.
If you select this injection point, objects that use the depth buffer display jittering artifacts.
When you select this injection point for a [FullscreenCustom Pass](custom-pass-create-gameobject.md#full-screen-custom-pass), Unity assigns the camera color buffer as the target by default.**Note:** When sampling scene color using HDSceneColor node in a FullScreenShaderGraph at this injection point, consider using a temporary buffer to handle concurrent read/write operations. See [Scene Color Sampling in AfterPostProcess](Custom-Pass-Scene-Color-Read.md) for implementation details. |
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Dynamic-Resolution.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Dynamic-Resolution.md
index 4d4f9a99557..d3372b051ce 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Dynamic-Resolution.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Dynamic-Resolution.md
@@ -111,10 +111,10 @@ HDRP provides the following upscale filter methods:
| **Catmull-Rom** | Catmull-Rom uses four bilinear samples. This uses the least resources, but it can cause blurry images after HDRP performs the upscaling step.
Catmull-Rom has no dependencies and runs at the end of the post-processing pipeline. |
| **Contrast Adaptive Sharpen (CAS)** | Contrast Adaptive Sharpen (CAS) uses **FidelityFX (CAS) AMD™**. This method produces a sharp image with an aggressive sharpening step. Do not use this option when the dynamic resolution screen percentage is less than 50%. For information about FidelityFX and Contrast Adaptive Sharpening, refer to [AMD FidelityFX](https://www.amd.com/en/technologies/radeon-software-fidelityfx).
Contrast Adaptive Sharpen (CAS) has no dependencies and runs at the end of the post-processing pipeline. |
| **AMD FidelityFX Super Resolution 1.0 (FSR1)** | FidelityFX Super Resolution 1.0 uses a spatial super-resolution method that balances quality and performance. For more information, refer to [AMD FidelityFX](https://www.amd.com/en/technologies/radeon-software-fidelityfx).
FSR1 has no dependencies and runs at the end of the post-processing pipeline.
FSR1 also runs when at 100% resolution as it can have beneficial sharpening effects.
For more information, refer to the section [Notes on FidelityFX Super Resolution 1.0](Dynamic-Resolution.md#notes-on-fidelityfx-super-resolution-10-fsr)|
-| **AMD FidelityFX Super Resolution 2 (FSR2)** | For more information, refer to [AMD FidelityFX Super Resolution 2](https://gpuopen.com/fidelityfx-superresolution-2/). |
+| **AMD FidelityFX Super Resolution 2 (FSR2)** | Version 2.2.1. For more information, refer to [AMD FidelityFX Super Resolution 2](https://gpuopen.com/fidelityfx-superresolution-2/). |
| **Temporal Anti-Aliasing (TAA) Upscale** | Temporal Anti-Aliasing (TAA) Upscale uses temporal integration to produce a sharp image. Unity performs this method alongside the normal anti-aliasing.
HDRP executes this upscale filter before post processing and at the same time as the TAA step. This means you can only use the TAA anti-aliasing method. This filter is not compatible with other anti-aliasing methods.
Temporal Anti-Aliasing (TAA) Upscale performs antialiasing on each frame. This means that it also runs when you enable Dynamic Resolution, even when the screen percentage is at 100% resolution.
For more information, see the section [Notes on TAA Upscale](Dynamic-Resolution.md#notes-on-temporal-anti-aliasing-taa-upscale). |
| **Spatial-Temporal Post-Processing (STP)** | Spatial-Temporal Post-Processing (STP) uses spatial and temporal upsampling techniques to produce a high quality, anti-aliased image.
Similar to the TAA Upscale filter, you can only use STP with the TAA anti-aliasing method. It is not compatible with other anti-aliasing methods. STP remains active when **Render Scale** is set to **1.0** as it applies temporal anti-aliasing (TAA) affects to the final rendered output.
A limitation of using STP is that it does not support dynamic resolution without hardware support. You can still use STP for fixed resolution scaling in cases where hardware dynamic resolution support is unavailable. However, **Render Scale** must be set to a fixed value.
For more information on STP, refer to [Spatial-Temporal Post-processing](stp/stp-upscaler.md) |
-| **NVIDIA Deep Learning Super Sampling (DLSS)** | HDRP supports DLSS only on the following platforms:
DirectX 11 on Windows 64-bit
DirectX 12 on Windows 64-bit
Vulkan on Windows 64-bit
Refer to [DLSS in HDRP](deep-learning-super-sampling-in-hdrp.md). |
+| **NVIDIA Deep Learning Super Sampling 4 (DLSS 4)** | HDRP supports DLSS only on the following platforms:
DirectX 11 on Windows 64-bit
DirectX 12 on Windows 64-bit
Vulkan on Windows 64-bit
Refer to [DLSS in HDRP](deep-learning-super-sampling-in-hdrp.md). |
## Override upscale options in a script
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Environment-Lighting.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Environment-Lighting.md
index 4fc7276e640..c81788ce915 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Environment-Lighting.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Environment-Lighting.md
@@ -1,52 +1,26 @@
-# Create environment lighting
+# Environment lighting
-Environment lighting allows you to simulate lighting coming from the surroundings of your Scene. It is common to use environment lighting to simulate sky lighting, but you can also use it to simulate a colored ambient light, or a lighting studio.
-In the High Definition Render Pipeline (HDRP), there are two parts to environment lighting:
+Simulate light from the surroundings of your scene, for example the sky or a lighting studio, in the High Definition Render Pipeline (HDRP).
-* The visual environment, controlled by the [Visual Environment Volume override](visual-environment-volume-override-reference.md). This controls the skybox that you can see through the Camera and represents the visual side of the environment lighting. With the[ built-in render pipeline](https://docs.unity3d.com/Manual/SL-RenderPipeline.html), you customize visual environment lighting settings on a per-Scene basis. In contrast, HDRP's Visual Environment uses the [Volume](understand-volumes.md) framework to smoothly interpolate between different sets of environment lighting settings for your sky (and fog) within the same Scene.
-* The lighting environment, controlled by the **Environment (HDRP)** section of the Lighting window. HDRP uses the lighting environment to calculate indirect ambient lighting for your Scene. It does not use the Volume framework as HDRP's indirect ambient lighting currently only supports one source of environment lighting.
+HDRP does the following to create environment lighting:
-Essentially, you use the visual environment to control how the sky looks in your Scene and use the lighting environment to control how the sky contributes to indirect ambient lighting.
+1. Renders a background, for example an HDRI sky texture or a gradient. For more information, refer to [Sky](sky.md).
-For information about the [Lighting window](https://docs.unity3d.com/Manual/lighting-window.html) **Environment (HDRP)** properties, refer to
+2. Uses the sky to calculate how the GameObjects in your scene receive [indirect ambient light](https://docs.unity3d.com/Manual/lighting-ambient-light.html). To control the light, use the [**Environment (HDRP)** tab of the Lighting window](reference-lighting-environment.md).
-## Visual Environment
-The Visual Environment is a Volume override that tells HDRP what type of [sky](HDRP-Features.md#sky) you want to see through Cameras that the Volume affects. For information on how to customize Visual Environments, see the [Visual Environment](visual-environment-volume-override-reference.md) documentation.
+## How HDRP calculates ambient light
-Your Unity Project’s [HDRP Asset](HDRP-Asset.md) has the following properties that also affect all Visual Environments:
+Depending on your settings and baked lighting, HDRP fetches the sky color for a GameObject from one of the following:
-* **Reflection Size**: Controls the resolution of the sky cube map. Unity uses this cube map as a fallback Reflection Probe for areas that local Reflection Probes do not affect. It has no effect on the quality of the sky directly seen through the camera.
-* **Lighting Override Mask**: A LayerMask that allows you to decouple the sky seen through the Camera from the one that affects the ambient lighting. For example, you might want a dark sky at night time, but to have brighter lighting so that you can still see clearly. See [Decoupling the visual environment from the lighting environment](#DecoupleVisualEnvironment).
+- The default [ambient light probe](https://docs.unity3d.com/6000.2/Documentation/ScriptReference/RenderSettings-ambientProbe.html), which captures either the static sky in the **Environment (HDRP)** tab of the Lighting window, or the dynamic sky at runtime from the **Visual Environment** volume override.
+- Baked lightmap textures from [lightmapping](https://docs.unity3d.com/Manual/Lightmapping-baking-before-runtime.html).
+- Realtime lightmap textures from [Enlighten Realtime Global Illumination](https://docs.unity3d.com/Manual/realtime-gi-using-enlighten-landing.html).
+- [Adaptive Probe Volumes](probevolumes.md).
+- [Screen space global illumination](Override-Screen-Space-GI.md) or [ray-traced global illumination](ray-traced-global-illumination.md).
-### HDRP built-in sky types
+**Note:** HDRP calculates the ambient Light Probe on the GPU, then uses asynchronous readback on the CPU, so the lighting is one frame late.
-HDRP has three built-in [sky types](HDRP-Features.md#sky):
+## Additional resources
-* [HDRI Sky](create-an-hdri-sky.md)
-* [Gradient Sky](create-a-gradient-sky.md)
-* [Physically Based Sky](create-a-physically-based-sky.md)
-
-HDRP also allows you to implement your own sky types that display a background and handle environment lighting. See the [Customizing HDRP](create-a-custom-sky.md) documentation for instructions on how to implement your own sky.
-
-**Note**: The **Procedural Sky** is deprecated and no longer built into HDRP. For information on how to add Procedural Sky to your HDRP Project, see the [Upgrading from 2019.2 to 2019.3 guide](Upgrading-From-2019.2-to-2019.3.md#ProceduralSky).
-
-
-
-## Decouple the visual environment from the lighting environment
-
-You can use the sky **Lighting Override Mask** in your Unity Project’s HDRP Asset to separate the Visual Environment from the environment lighting. If you set the **Lighting Override Mask** to **Nothing**, or to a group of Layers that have no Volumes on them, then no Layer acts as an override. This means that environment lighting comes from all Volumes that affect a Camera. If you set the **Lighting Override Mask** to include Layers that have Volumes on them, HDRP only uses Volumes on these Layers to calculate environment lighting.
-
-An example of where you would want to decouple the sky lighting from the visual sky, and use a different Volume Profile for each, is when you have an [HDRI Sky](create-an-hdri-sky.md) that includes sunlight. To make the sun visible at runtime in your application, your sky background must show an HDRI sky that features the sun. To achieve real-time lighting from the sun, you must use a Directional [Light](Light-Component.md) in your Scene and, for the baking process, use an HDRI sky that is identical to the first one but does not include the sun. If you were to use an HDRI sky that includes the sun to bake the lighting, the sun would contribute to the lighting twice (once from the Directional Light, and once from the baking process) and make the lighting look unrealistic.
-
-## Ambient light probe
-
-HDRP uses the ambient Light Probe as the final fallback for indirect diffuse lighting. For more information, refer to [Ambient light probe](ambient-light-probe.md).
-
-## Ambient Reflection Probe
-
-HDRP uses the ambient Reflection Probe as a fallback for indirect specular lighting. This means that it only affects areas that local Reflection Probes, Screen Space Reflection, and raytraced reflections do not affect.
-
-
-## Reflection
-
-Reflection Probes work like Cameras; they use the Volume system, and therefore use environment lighting from the sky, which you set in the Visual Environment of the Volume that affects them. For more information, refer to [Reflection](Reflection-in-HDRP.md).
+- [Configure environment lighting](ambient-lighting-configure.md)
+- [Ambient light](https://docs.unity3d.com/Manual/lighting-ambient-light.html)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/HDRP-Asset.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/HDRP-Asset.md
index 2942590aa11..2b2b8750692 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/HDRP-Asset.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/HDRP-Asset.md
@@ -6,28 +6,29 @@ Unity only allocates memory and builds shader variants for features you enable i
## Rendering
-| **Property** | **Subproperty** | **Description** |
-|-|-|-|
-| **Color Buffer Format** | N/A | The format of the color buffer that HDRP uses for rendering. Using R16G16B16A16 instead of R11G11B10 doubles the memory usage, but helps avoid banding. R16G16B16A16 is also required for [Alpha-Output](Alpha-Output.md). |
+| **Property** | **Subproperty** | **Description** |
+|------------------------------------------|-|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| **Color Buffer Format** | N/A | The format of the color buffer that HDRP uses for rendering. Using R16G16B16A16 instead of R11G11B10 doubles the memory usage, but helps avoid banding. R16G16B16A16 is also required for [Alpha-Output](Alpha-Output.md). |
+| **Depth Buffer Format** | N/A | The format of the depth buffer that HDRP uses for rendering. Using Auto is the default behavior and lets HDRP choose between 32 bits and 24 bits depth buffer depending on the platform. Forcing 16 bits depth buffer improves performances on low-end devices but can lead to Z-fighting artifacts depending on the maximum view distance of the camera. |
| **Lit Shader Mode** | N/A | Use the drop-down to choose which mode HDRP uses for the [Lit Shader](lit-material.md). • **Forward Only**: forces HDRP to only use forward rendering for Lit Shaders. • **Deferred Only**: forces HDRP to use deferred rendering for Lit Shaders (HDRP still renders advanced Materials using forward rendering). • **Both**: allows the Camera to use deferred and forward rendering.
Select **Both** to allow you to switch between forward and deferred rendering for Lit Shaders at runtime per Camera. Selecting a specific mode reduces build time and Shader memory because HDRP requires less Shader variants, but it's not possible to switch from one mode to the other at runtime. |
-| N/A | **Multisample Anti-aliasing Quality** | Use the drop-down to set the number of samples HDRP uses for multisample anti-aliasing (MSAA). The larger the sample count, the better the quality. Select **None** to disable MSAA. This property is only visible when **Lit Shader Mode** is set to **Forward Only** or **Both**. |
-| **Motion Vectors** | N/A | Enable the checkbox to enable motion vector support in HDRP. HDRP uses motion vectors for effects like screen space reflection (SSR) and motion blur. When disabled, motion blur has no effect and HDRP calculates SSR with lower quality. |
-| **Runtime Debug Display** | N/A | Enable the checkbox to enable HDRP to use debug modes from the [Rendering Debugger](use-the-rendering-debugger.md) at runtime. Disable the checkbox to reduce build time and shader memory. This disables all property override options, all lighting debug modes, and all material property debug modes except GBuffer debug. |
-| **Runtime AOV API** | N/A | Enable the checkbox to enable HDRP able to use the AOV API (rendering of material properties and lighting modes) at runtime. Disable this checkbox to reduce build time and shader memory. This disables all material properties and lighting modes. |
-| **Terrain Hole** | N/A | Enable the checkbox to enable support for [Terrain Holes](https://docs.unity3d.com/2019.3/Documentation/Manual/terrain-PaintHoles.html) in HDRP. If you don't enable this, Terrain Holes aren't visible in your Scene. |
-| **Transparent Backface** | N/A | Enable the checkbox to enable support for transparent back-face render passes in HDRP. If your Unity Project doesn't need to make a transparent back-face pass, disable this checkbox to reduce build time. |
-| **Transparent Depth Prepass** | N/A | Enable the checkbox to enable support for transparent depth render prepasses in HDRP. If your Unity Project doesn't need to make a transparent depth prepass, disable this checkbox to reduce build time. |
-| **Transparent Depth Postpass** | N/A | Enable the checkbox to enable support for transparent depth render postpasses in HDRP. If your Unity Project doesn't make use of a transparent depth postpass, disable this checkbox to reduce build time. |
-| **Custom Pass** | N/A | Enable the checkbox to enable support for [custom passes](Custom-Pass.md) in HDRP. If your Unity Project doesn't use custom passes, disable this checkbox to save memory. |
-| - **Custom Buffer Format** | N/A | Specify the texture format for the custom buffer. If you experience banding issues due to your custom passes, you can change it to either `R11G11B10` if you don't need alpha, or `R16G16B16A16` if you do need alpha. |
-| **Realtime Raytracing (Preview)** | N/A | Enable the checkbox to enable HDRP realtime ray tracing (Preview). It requires ray tracing-compatible hardware. For more information, refer to [Ray Tracing Getting Started](Ray-Tracing-Getting-Started.md). |
-| **Visual Effects Ray Tracing (Preview)** | N/A | Enable the checkbox to enable support for ray tracing with Visual Effects in HDRP. **Realtime Raytracing (Preview)** must be enabled. |
-| **Supported Ray Tracing Mode (Preview)** | N/A | Select the supported modes for ray tracing effects (**Performance**, **Quality**, or **Both**). For more information, refer to [Ray Tracing Getting Started](Ray-Tracing-Getting-Started.md). |
-| - **LOD Bias** | N/A | Set the value that Cameras use to calculate their LOD bias. The Camera uses this value differently depending on the **LOD Bias Mode** you select. |
-| - **Maximum LOD Level** | N/A | Set the value that Cameras use to calculate their maximum level of detail. The Camera uses this value differently depending on the **Maximum LOD Level Mode** you select. |
-| **GPU Resident Drawer** | N/A | The GPU Resident Drawer automatically uses the [`BatchRendererGroup`](https://docs.unity3d.com/Manual/batch-renderer-group.html) API to draw GameObjects with GPU instancing. Refer to [Use the GPU Resident Drawer](gpu-resident-drawer.md) for more information.
**Disabled**: Unity doesn't automatically draw GameObjects with GPU instancing.
**Instanced Drawing**: Unity automatically draws GameObjects with GPU instancing.
|
-| N/A | **Small-Mesh Screen-Percentage** | Set the screen percentage Unity uses to cull small GameObjects, to speed up rendering. Unity culls GameObjects that fill less of the screen than this value. This setting might not work if you use your own [Level of Detail (LOD) meshes](https://docs.unity3d.com/Manual/LevelOfDetail.html). Set the value to 0 to stop Unity culling small GameObjects.
To prevent Unity culling an individual GameObject that covers less screen space than this value, go to the **Inspector** window for the GameObject and add a **Disallow Small Mesh Culling** component. |
-| N/A | **GPU Occlusion Culling** | Enable Unity using the GPU instead of the CPU to exclude GameObjects from rendering when they're hidden behind other GameObjects. Refer to [Use GPU occlusion culling](gpu-culling.md) for more information. |
+| N/A | **Multisample Anti-aliasing Quality** | Use the drop-down to set the number of samples HDRP uses for multisample anti-aliasing (MSAA). The larger the sample count, the better the quality. Select **None** to disable MSAA. This property is only visible when **Lit Shader Mode** is set to **Forward Only** or **Both**. |
+| **Motion Vectors** | N/A | Enable the checkbox to enable motion vector support in HDRP. HDRP uses motion vectors for effects like screen space reflection (SSR) and motion blur. When disabled, motion blur has no effect and HDRP calculates SSR with lower quality. |
+| **Runtime Debug Display** | N/A | Enable the checkbox to enable HDRP to use debug modes from the [Rendering Debugger](use-the-rendering-debugger.md) at runtime. Disable the checkbox to reduce build time and shader memory. This disables all property override options, all lighting debug modes, and all material property debug modes except GBuffer debug. |
+| **Runtime AOV API** | N/A | Enable the checkbox to enable HDRP able to use the AOV API (rendering of material properties and lighting modes) at runtime. Disable this checkbox to reduce build time and shader memory. This disables all material properties and lighting modes. |
+| **Terrain Hole** | N/A | Enable the checkbox to enable support for [Terrain Holes](https://docs.unity3d.com/2019.3/Documentation/Manual/terrain-PaintHoles.html) in HDRP. If you don't enable this, Terrain Holes aren't visible in your Scene. |
+| **Transparent Backface** | N/A | Enable the checkbox to enable support for transparent back-face render passes in HDRP. If your Unity Project doesn't need to make a transparent back-face pass, disable this checkbox to reduce build time. |
+| **Transparent Depth Prepass** | N/A | Enable the checkbox to enable support for transparent depth render prepasses in HDRP. If your Unity Project doesn't need to make a transparent depth prepass, disable this checkbox to reduce build time. |
+| **Transparent Depth Postpass** | N/A | Enable the checkbox to enable support for transparent depth render postpasses in HDRP. If your Unity Project doesn't make use of a transparent depth postpass, disable this checkbox to reduce build time. |
+| **Custom Pass** | N/A | Enable the checkbox to enable support for [custom passes](Custom-Pass.md) in HDRP. If your Unity Project doesn't use custom passes, disable this checkbox to save memory. |
+| - **Custom Buffer Format** | N/A | Specify the texture format for the custom buffer. If you experience banding issues due to your custom passes, you can change it to either `R11G11B10` if you don't need alpha, or `R16G16B16A16` if you do need alpha. |
+| **Realtime Raytracing (Preview)** | N/A | Enable the checkbox to enable HDRP realtime ray tracing (Preview). It requires ray tracing-compatible hardware. For more information, refer to [Ray Tracing Getting Started](Ray-Tracing-Getting-Started.md). |
+| **Visual Effects Ray Tracing (Preview)** | N/A | Enable the checkbox to enable support for ray tracing with Visual Effects in HDRP. **Realtime Raytracing (Preview)** must be enabled. |
+| **Supported Ray Tracing Mode (Preview)** | N/A | Select the supported modes for ray tracing effects (**Performance**, **Quality**, or **Both**). For more information, refer to [Ray Tracing Getting Started](Ray-Tracing-Getting-Started.md). |
+| - **LOD Bias** | N/A | Set the value that Cameras use to calculate their LOD bias. The Camera uses this value differently depending on the **LOD Bias Mode** you select. |
+| - **Maximum LOD Level** | N/A | Set the value that Cameras use to calculate their maximum level of detail. The Camera uses this value differently depending on the **Maximum LOD Level Mode** you select. |
+| **GPU Resident Drawer** | N/A | The GPU Resident Drawer automatically uses the [`BatchRendererGroup`](https://docs.unity3d.com/Manual/batch-renderer-group.html) API to draw GameObjects with GPU instancing. Refer to [Use the GPU Resident Drawer](gpu-resident-drawer.md) for more information.
**Disabled**: Unity doesn't automatically draw GameObjects with GPU instancing.
**Instanced Drawing**: Unity automatically draws GameObjects with GPU instancing.
|
+| N/A | **Small-Mesh Screen-Percentage** | Set the screen percentage Unity uses to cull small GameObjects, to speed up rendering. Unity culls GameObjects that fill less of the screen than this value. This setting might not work if you use your own [Level of Detail (LOD) meshes](https://docs.unity3d.com/Manual/LevelOfDetail.html). Set the value to 0 to stop Unity culling small GameObjects.
To prevent Unity culling an individual GameObject that covers less screen space than this value, go to the **Inspector** window for the GameObject and add a **Disallow Small Mesh Culling** component. |
+| N/A | **GPU Occlusion Culling** | Enable Unity using the GPU instead of the CPU to exclude GameObjects from rendering when they're hidden behind other GameObjects. Refer to [Use GPU occlusion culling](gpu-culling.md) for more information. |
@@ -315,8 +316,7 @@ Use these settings to enable or disable settings relating to lighting in HDRP.
| **Grading LUT Format** | Use the drop-down to select the format to encode the color grading LUTs with. Lower precision formats are faster and use less memory at the expense of color precision. These formats directly map to their equivalent in the built-in [GraphicsFormat](https://docs.unity3d.com/ScriptReference/Experimental.Rendering.GraphicsFormat.html) enum value. |
| **Buffer Format** | Use the drop-down to select the format of the color buffers that are used in the post-processing passes. Lower precision formats are faster and use less memory at the expense of color precision. These formats directly map to their equivalent in the built-in [GraphicsFormat](https://docs.unity3d.com/ScriptReference/Experimental.Rendering.GraphicsFormat.html) enum value.
-## Post-processing Quality Settings
-These settings define the quality levels (low, medium, high) related to post processing effects in HDRP. For a detailed description of each setting, see the [Post-processing in HDRP](Post-Processing-Main.md) section of the documentation.
+These settings also define the quality levels (low, medium, high) related to post processing effects in HDRP. For a detailed description of each setting, see the [Post-processing in HDRP](Post-Processing-Main.md) section of the documentation.
## Virtual Texturing
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Images/aocomparison.png b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Images/aocomparison.png
new file mode 100644
index 00000000000..f12006d0bb2
Binary files /dev/null and b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Images/aocomparison.png differ
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Images/shared/lens-flare/screenspacelensflares-threshold.mp4 b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Images/shared/lens-flare/screenspacelensflares-threshold.mp4
index c7fc8aa8af4..fa7b840a86e 100644
Binary files a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Images/shared/lens-flare/screenspacelensflares-threshold.mp4 and b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Images/shared/lens-flare/screenspacelensflares-threshold.mp4 differ
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Images/ssao-rtao-comparison.jpg b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Images/ssao-rtao-comparison.jpg
new file mode 100644
index 00000000000..946d0d65092
Binary files /dev/null and b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Images/ssao-rtao-comparison.jpg differ
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Override-Ambient-Occlusion.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Override-Ambient-Occlusion.md
index c05a1f3ec90..04bf97b10f5 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Override-Ambient-Occlusion.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Override-Ambient-Occlusion.md
@@ -1,37 +1,36 @@
-# Screen Space Ambient Occlusion (SSAO)
+# Screen space ambient occlusion (SSAO)
-The **Screen Space Ambient Occlusion** override is a real-time, full-screen lighting effect available in the High Definition Render Pipeline (HDRP). This effect approximates [ambient occlusion](https://en.wikipedia.org/wiki/Ambient_occlusion) in the current field of view. It approximates the intensity and position of ambient light on a GameObject’s surface, based on the light in the Scene and the environment around the GameObject. To achieve this, it darkens creases, holes, intersections, and surfaces that are close to one another. In real life, these areas tend to block out, or occlude, ambient light, and so appear darker.
+The Screen Space Ambient Occlusion (SSAO) volume override simulates [ambient occlusion](ambient-occlusion-introduction.md) in real-time.
-For information on how to use a Texture to specify ambient occlusion caused by details present in a GameObject's Material but not on it's surface geometry, see [Ambient Occlusion](Ambient-Occlusion.md).
+
+A single-channel screen space ambient occlusion texture of a gothic corridor. The scene is white with shades of grey representing corners and crevices.
-HDRP implements [ray-traced ambient occlusion](Ray-Traced-Ambient-Occlusion.md) on top of this override. This means that the properties visible in the Inspector change depending on whether you enable ray tracing.
+For each frame, SSAO creates a texture containing occluded areas in the camera view, which HDRP uses to reduce indirect lighting in those areas.
-
+SSAO doesn't affect direct lighting, or the indirect light from Reflection Probes.
-## Enable Screen Space Ambient Occlusion
+A screen-space effect only processes what's on-screen, so objects outside the camera view don't occlude objects in the camera view. You can sometimes see this at the edges of the screen. To include off-screen objects for better results, enable [Ray-traced ambient occlusion](Ray-Traced-Ambient-Occlusion.md) instead.
-[!include[](snippets/Volume-Override-Enable-Override.md)]
+## Enable screen space ambient occlusion
-* To enable SSAO in your HDRP Asset go to **Lighting** > **Screen Space Ambient Occlusion**.
-* To enable SSAO in your Frame Settings go to **Edit** > **Project Settings** > **Graphics** > **Pipeline Specific Settings** > **HDRP** > **Frame Settings (Default Values)** > **Camera** > **Lighting** > **Screen Space Ambient Occlusion**.
+Follow these steps:
-
+1. Enable screen space ambient occlusion in your project.
-## Use Screen Space Ambient Occlusion
+ [!include[](snippets/Volume-Override-Enable-Override.md)]
-**Screen Space Ambient Occlusion** uses the [Volume](understand-volumes.md) framework, so to enable and modify **Screen Space Ambient Occlusion** properties, you must add an **Screen Space Ambient Occlusion** override to a [Volume](understand-volumes.md) in your Scene. To add **Ambient Occlusion** to a Volume:
+ * To enable SSAO in your HDRP Asset, go to **Lighting** > **Screen Space Ambient Occlusion**.
+ * To enable SSAO in your Frame Settings, go to **Edit** > **Project Settings** > **Graphics** > **Pipeline Specific Settings** > **HDRP** > **Frame Settings (Default Values)** > **Camera** > **Lighting** > **Screen Space Ambient Occlusion**.
-1. In the Scene or Hierarchy view, select a GameObject that contains a Volume component to view it in the Inspector.
-2. In the Inspector, navigate to **Add Override** > **Lighting** and click on **Ambient Occlusion**.
- HDRP now applies **Ambient Occlusion** to any Camera this Volume affects.
+2. [Add a volume component](set-up-a-volume.md#add-a-volume) to any GameObject in your scene.
-[!include[](snippets/volume-override-api.md)]
+3. Select the GameObject, then in the **Inspector** window select **Add Override** > **Lighting** > **Ambient Occlusion**.
+ HDRP now applies screen space ambient occlusion to any camera this volume affects.
-## Limitations
+To access and control the volume override at runtime, refer to [Volume scripting API](Volumes-API.md#changing-volume-profile-properties).
-### Screen-space ambient occlusion
-
-A screen-space effect only processes what's on the screen at a given point. This means that objects outside of the field of view can't visually occlude objects in the view. You can sometimes see this on the edges of the screen.
-When rendering [Reflection Probes](Reflection-Probe.md) screen space ambient occlusion isn't supported.
+## Additional resources
+- [Assign an ambient occlusion texture](Ambient-Occlusion.md)
+- [Ray-traced ambient occlusion](Ray-Traced-Ambient-Occlusion.md)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Override-Contact-Shadows.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Override-Contact-Shadows.md
index 8db8ebcbf42..53b0dc5afc9 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Override-Contact-Shadows.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Override-Contact-Shadows.md
@@ -1,7 +1,7 @@
# Use contact shadows
-Contact Shadows are shadows that HDRP [ray marches](Glossary.md#RayMarching) in screen space, inside the depth buffer, at a close range. They provide small, detailed, shadows for details in geometry that shadow maps can't usually capture.
+Contact Shadows are shadows that HDRP [ray marches](Glossary.md#RayMarching) in screen space, inside the depth buffer, at a close range. Use Contact Shadows to provide shadows for geometry details that regular shadow mapping algorithms usually fail to capture.
+
-The Contact Shadows [Volume Override](volume-component.md) specifies properties which control the behavior of Contact Shadows. Contact Shadows are shadows that The High Definition Render Pipeline (HDRP) [ray marches](Glossary.md#RayMarching) in screen space inside the depth buffer. The goal of using Contact Shadows is to capture small details that regular shadow mapping algorithms fail to capture.
24 Lights (Direction, Point or Spot) can cast Contact Shadows at a time.
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ray-Traced-Ambient-Occlusion.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ray-Traced-Ambient-Occlusion.md
index 26229ec3049..53779d05e60 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ray-Traced-Ambient-Occlusion.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/Ray-Traced-Ambient-Occlusion.md
@@ -1,26 +1,25 @@
# Ray-traced ambient occlusion
-Ray-Traced Ambient Occlusion is a ray tracing feature in the High Definition Render Pipeline (HDRP). It is an alternative to HDRP's s [screen space ambient occlusion](Override-Ambient-Occlusion.md), with a more accurate ray-traced solution that can use off-screen data.
+Ray-traced ambient occlusion (RTAO) is an alternative to [screen space ambient occlusion](Override-Ambient-Occlusion.md) that's more accurate because it uses off-screen data.
-
+
+A single-channel occlusion texture of a gothic corridor. The screen space ambient occlusion texture on the left has fewer details and lighter shadows than the ray-traced ambient occlusion texture on the right.
-**Screen space ambient occlusion**
+Follow these steps:
-
+1. [Enable screen space ambient occlusion](Override-Ambient-Occlusion.md#enable-screen-space-ambient-occlusion).
-**Ray-traced ambient occlusion**
+1. [Set up ray tracing](Ray-Tracing-Getting-Started.md) in your HDRP project.
-For information about ray tracing in HDRP, and how to set up your HDRP Project to support ray tracing, see [Getting started with ray tracing](Ray-Tracing-Getting-Started.md).
+1. Select the GameObject with the volume override you created in step 1.
-To troubleshoot this effect, HDRP provides an Ambient Occlusion [Debug Mode](Ray-Tracing-Debug.md) and a Ray Tracing Acceleration Structure [Debug Mode](Ray-Tracing-Debug.md) in Lighting Full Screen Debug Mode.
+1. In the Inspector window of the **Screen Space Ambient Occlusion** override, enable **Ray Tracing**.
-## Use ray-traced ambient occlusion
+To control the effect, refer to the **Ray-traced** properties on the [Ambient occlusion reference](reference-ambient-occlusion.md) page.
-Because this feature is an alternative to the [Ambient Occlusion](Override-Ambient-Occlusion.md) Volume Override, the initial setup is very similar. To setup ray traced ambient occlusion, first follow the [Enabling Ambient Occlusion](Override-Ambient-Occlusion.md#enable-screen-space-ambient-occlusion) and [Using Ambient Occlusion](Override-Ambient-Occlusion.md#use-screen-space-ambient-occlusion) steps. After you setup the Ambient Occlusion override, to make it use ray tracing:
+To troubleshoot ray-traced ambient occlusion, HDRP provides an Ambient Occlusion [Debug Mode](Ray-Tracing-Debug.md) and a Ray Tracing Acceleration Structure [Debug Mode](Ray-Tracing-Debug.md) in Lighting Full Screen Debug Mode.
-1. In the Frame Settings for your Cameras, enable **Ray Tracing**.
-2. Select the [Ambient Occlusion](Override-Ambient-Occlusion.md) override and, in the Inspector, enable **Ray Tracing**. If you do not see a **Ray Tracing** option, make sure your HDRP Project supports ray tracing. For information on setting up ray tracing in HDRP, see [Getting started with ray tracing](Ray-Tracing-Getting-Started.md).
+## Additional resources
-## Properties
-
-HDRP implements ray-traced ambient occlusion on top of the Ambient Occlusion override. For information on the properties that control this effect, see [Ambient occlusion reference](reference-ambient-occlusion.md).
+- [Assign an ambient occlusion texture](Ambient-Occlusion.md) for each GameObject.
+- [Screen space ambient occlusion (SSAO)](Override-Ambient-Occlusion.md), which uses information from the whole screen.
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/TableOfContents.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/TableOfContents.md
index a2df3a5bec2..2c165159c9d 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/TableOfContents.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/TableOfContents.md
@@ -60,9 +60,10 @@
* [View and control a light from its perspective](lights-placement-tool.md)
* [Use light rendering layers](Rendering-Layers.md)
* [Ambient lighting](ambient-lighting.md)
- * [Create environment lighting](Environment-Lighting.md)
- * [Ambient occlusion](Ambient-Occlusion.md)
- * [Ambient light probe](ambient-light-probe.md)
+ * [Environment lighting](Environment-Lighting.md)
+ * [Configure environment lighting](ambient-lighting-configure.md)
+ * [Ambient occlusion](ambient-occlusion-introduction.md)
+ * [Assign an ambient occlusion texture](Ambient-Occlusion.md)
* [Screen Space Ambient Occlusion (SSAO)](Override-Ambient-Occlusion.md)
* [Control exposure](Override-Exposure.md)
* [Shadows](shadows.md)
@@ -382,7 +383,7 @@
* [Shader materials reference](shader-materials-reference.md)
* [HDRP material reference](reference-hdrp-materials.md)
* [Alpha Clipping reference](Alpha-Clipping.md)
- * [Ambient Occlusion reference](Ambient-Occlusion.md)
+ * [Ambient Occlusion reference](reference-ambient-occlusion.md)
* [Displacement Mode reference](Displacement-Mode.md)
* [Double Sided reference](Double-Sided.md)
* [Geometric Specular Anti-aliasing reference](Geometric-Specular-Anti-Aliasing.md)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-light-probe.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-light-probe.md
deleted file mode 100644
index 2d68a78aa6c..00000000000
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-light-probe.md
+++ /dev/null
@@ -1,17 +0,0 @@
-## Understand the ambient light probe
-
-HDRP uses the ambient Light Probe as the final fallback for indirect diffuse lighting. It affects:
-
-- All Mesh Renderers if there is no indirect ambient light computed for the Scene (this applies when Unity has not computed any lightmaps or Light Probes for the Scene)
-- Mesh Renderers that have their **Light Probe Mode** set to **Off**
-- Volumetric fog if the Global Light Probe dimmer is set to a value above 0
-
-The ambient Light Probe can be static (generated only once from the static lighting sky set in the HDRP **Environment (HDRP)**panel) or dynamic (updated at runtime from the sky currently in use).
-
-***\*Note\****: If there is a ***\*Light Probe group\**** in your Scene and you have computed indirect ambient lighting, then the Ambient Light Probe only affects Mesh Renderers that have their ***\*Light Probe Mode\**** set to ***\*Off\****, and that have ***\*Volumetric fog\**** (if it’s enabled in the Scene).
-
-### Limitations of dynamic ambient mode
-
-The Ambient Light Probe always affects your scene one frame late after HDRP calculates it. This is because HDRP calculates Ambient Light Probes on the GPU and then uses asynchronous readback on the CPU.
-
-As a result, the ambient lighting might not match the actual lighting and cause visual artifacts. This can happen when you use the dynamic ambient mode and use reflection probes that update on demand.
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-lighting-configure.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-lighting-configure.md
new file mode 100644
index 00000000000..8eea9aafb54
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-lighting-configure.md
@@ -0,0 +1,38 @@
+# Configure environment lighting
+
+Control how your scene receives light from the environment.
+
+## Make scene elements use the ambient light probe
+
+If you have lightmap textures or Light Probes in your scene, HDRP doesn't use the ambient light probe by default.
+
+To set objects and fog to use the ambient light probe, follow these steps:
+
+1. Select a GameObject, then in the **Mesh Renderer** component disable the GameObject from receiving light from global illumination.
+1. In the **Fog** volume override, in the **Volumetric Fog** section, set **GI Dimmer** to 0.
+
+
+
+## Decouple lighting from the sky
+
+To decouple lighting from the sky, use a lighting override mask. For example, you can do the following:
+
+- Render a dark sky, but calculate brighter lighting on GameObjects so they display clearly.
+- Use a directional light for a moving sun, but a sky background that excludes the sun to avoid double lighting.
+
+First, create a volume with the sky you want to use for lighting:
+
+1. Create a new sky and fog global volume. From the main menu, select **GameObject** > **Volume** > **Sky and Fog Global Volume**.
+1. Select the volume, then use the **Visual Environment** volume override to set the type of sky you want HDRP to use for lighting.
+1. At the top of the **Inspector** window, open the **Layers** dropdown and set the volume to a different layer.
+
+You can now set HDRP to use the layer for lighting, without affecting the sky background:
+
+1. From the main menu, select **Edit** > **Project Settings**.
+1. Go to **Quality** > **HDRP**.
+1. In the **Lighting** > **Sky** section, set **Lighting Override Mask** to the layer.
+
+## Additional resources
+
+- [Environment lighting](Environment-lighting.md)
+- [Ambient light](https://docs.unity3d.com/Manual/lighting-ambient-light.html)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-lighting.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-lighting.md
index 13fc88c7c6e..35aa2e91f66 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-lighting.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-lighting.md
@@ -1,18 +1,17 @@
# Ambient lighting
-Create and control indirect diffuse lighting.
+Create and control light from the environment in your scene in the High Definition Render Pipeline (HDRP), to create more realistic lighting.
-|Page|Description|
+|**Topic**|**Description**|
|-|-|
-|[Create environment lighting](Environment-lighting.md)|Simulate light that comes from the surroundings of a scene.|
-|[Ambient occlusion](Ambient-Occlusion.md)| Apply ambient occlusion to a material. |
-|[Screen Space Ambient Occlusion (SSAO)](Override-Ambient-Occlusion.md)|Enable and use the Screen Space Ambient Occlusion (SSAO) volume override. |
-|[Ambient light probe](ambient-light-probe.md)| Learn about the method that HDRP uses as the fallback for indirect diffuse lighting. |
-|[Adaptive Probe Volumes](probevolumes.md)| Learn about the method that HDRP proposes for baked indirect diffuse lighting. |
-
+|[Environment lighting](Environment-lighting.md)| Learn about how HDRP calculates ambient light in your scene. |
+|[Configure environment lighting](ambient-lighting-configure.md)| Make scene elements use the ambient probe, or decouple lighting from the sky. |
+|[Ambient occlusion](ambient-occlusion-introduction.md)| Learn about darkening corners in areas where it's difficult for indirect light to reach.|
+|[Assign an ambient occlusion texture](Ambient-Occlusion.md)| Use a texture to create ambient occlusion for a GameObject. |
+|[Screen space ambient occlusion (SSAO)](Override-Ambient-Occlusion.md)| Use a volume override to create ambient occlusion across the screen. |
## Additional resources
+
+- [Ray-traced ambient occlusion (RTAO)](Ray-Traced-Ambient-Occlusion.md)
+- [Adaptive Probe Volumes](probevolumes.md)
- [Volumetric Lighting](Volumetric-Lighting.md)
-- [Ambient Occlusion](Override-Ambient-Occlusion.md)
-- [Visual Environment volume override reference](visual-environment-volume-override-reference.md)
-- [Fog Volume Override reference](fog-volume-override-reference.md)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-occlusion-introduction.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-occlusion-introduction.md
new file mode 100644
index 00000000000..8a376d8f8f2
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/ambient-occlusion-introduction.md
@@ -0,0 +1,23 @@
+# Ambient occlusion
+
+Ambient occlusion (AO) darkens corners in areas where surfaces are close to each other and difficult for indirect light to reach.
+
+The High Definition Render Pipeline (HDRP) can create ambient occlusion by reducing how much light a surface gets from indirect ambient light sources. For more information about indirect ambient light, refer to [Environment lighting](environment-lighting.md).
+
+**Note:** Ambient occlusion doesn't affect direct lighting.
+
+To enable ambient occlusion, use one of the following methods:
+
+- [Assign an ambient occlusion texture](Ambient-Occlusion.md) for each GameObject.
+- [Screen space ambient occlusion (SSAO)](Override-Ambient-Occlusion.md), which uses information from the whole screen. SSAO is enabled by default.
+- [Ray-traced ambient occlusion (RTAO)](Ray-Traced-Ambient-Occlusion.md), which uses information from beyond the screen.
+
+If you create an ambient occlusion texture, HDRP also uses it to calculate specular occlusion, by reducing the intensity of reflections in corners.
+
+
+Four versions of a scene with dragon statues in a brick dungeon, lit brightly from above. With no ambient occlusion, there are no shadows in corners and crevices. Ambient occlusion, SSAO with ambient occlusion, and RTAO with ambient occlusion give progressively better results.
+
+## Additional resources
+
+- [Ambient light](https://docs.unity3d.com/Manual/lighting-ambient-light.html)
+- [Reflection and refraction](Reflection-in-HDRP.md)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/configure-a-project-using-the-hdrp-config-package.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/configure-a-project-using-the-hdrp-config-package.md
index 4c9d66c59e3..09abbad57b1 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/configure-a-project-using-the-hdrp-config-package.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/configure-a-project-using-the-hdrp-config-package.md
@@ -12,17 +12,14 @@ For example, you can use it to:
## Using the HDRP Config package
-To use the HDRP Config package in your HDRP Project, you need to create a local copy of it and make your Project's package manifest reference it. You can either do this manually or use the [HDRP Wizard](Render-Pipeline-Wizard.md).
+* To check or customize the Config Package:
-* **Manual**: In your Project's directory, move and rename the folder "**/Library/PackageCache/com.unity.render-pipelines.high-definition-config@[versionnumber]**" to "**/Packages/com.unity.render-pipelines.high-definition-config**".
-* **HDRP Wizard**: Open the HDRP Wizard (**Windows > Rendering > HDRP Wizard**) and click the **Embed Configuration Editable Package**. This creates a **LocalPackage** folder at the root of your Project and populates it with a compatible HDRP config package.
-
-**Note**: Using the Package Manager to upgrade your HDRP package does not automatically upgrade the local config package. To manually upgrade the local config package:
-
-1. Make a copy of your current config package.
-2. Use the HDRP Wizard to create a new, compatible config package.
-3. Apply the settings from the old config package to the new config package.
+1. Go to **Edit > Preferences > Graphics > High Definition Render Pipeline**.
+2. Under **Config Package**, click **View in Package Manager**.
+3. In the Package Manager, select `com.unity.render-pipelines.high-definition-config`.
+4. Click the **Manage** dropdown and choose **Customize** to embed and edit the package.
+Alternatively you can manually embed the package by copying it to your Project's **Packages** folder. In your Project's directory, move and rename the folder "**/Library/PackageCache/com.unity.render-pipelines.high-definition-config@[versionnumber]**" to "**/Packages/com.unity.render-pipelines.high-definition-config**".
## Configuring HDRP using the config package
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/create-a-custom-sky.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/create-a-custom-sky.md
index a9e26f8ad35..21094a019d0 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/create-a-custom-sky.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/create-a-custom-sky.md
@@ -205,7 +205,7 @@ Shader "Hidden/HDRP/Sky/NewSky"
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/create-custom-cloud-effects.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/create-custom-cloud-effects.md
index 62181aea561..5932b32d1e9 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/create-custom-cloud-effects.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/create-custom-cloud-effects.md
@@ -144,7 +144,7 @@ Shader "Hidden/HDRP/Sky/NewCloud"
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/deep-learning-super-sampling-in-hdrp.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/deep-learning-super-sampling-in-hdrp.md
index eab74e186dc..0b4b54c3c2c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/deep-learning-super-sampling-in-hdrp.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/deep-learning-super-sampling-in-hdrp.md
@@ -1,6 +1,6 @@
# Deep learning super sampling (DLSS)
-[NVIDIA Deep Learning Super Sampling (DLSS)](https://www.nvidia.com/en-us/geforce/technologies/dlss/) is a rendering technology that uses artificial intelligence to increase graphics performance. The High Definition Render Pipeline (HDRP) natively supports DLSS.
+[NVIDIA Deep Learning Super Sampling (DLSS)](https://www.nvidia.com/en-us/geforce/technologies/dlss/) is a rendering technology that uses artificial intelligence to increase graphics performance. The High Definition Render Pipeline (HDRP) natively supports DLSS 4 Super Resolution.
## Requirements and compatibility
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-ambient-occlusion.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-ambient-occlusion.md
index d9f60296378..4b00cfb514c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-ambient-occlusion.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-ambient-occlusion.md
@@ -1,4 +1,4 @@
-# Ambient Occlusion reference
+# Screen Space Ambient Occlusion (SSAO) volume override reference
## Properties
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-lighting-environment.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-lighting-environment.md
index c0ae1669000..0816b33c9d9 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-lighting-environment.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/reference-lighting-environment.md
@@ -1,4 +1,4 @@
-# Lighting environment reference
+# Lighting window Environment (HDRP) tab reference
The **Environment (HDRP)** is a section in the [Lighting window](https://docs.unity3d.com/Manual/lighting-window.html) that allows you to specify which sky to use for indirect ambient light in HDRP. To open the window, select **Window > Rendering > Lighting > Environment**.
diff --git a/Packages/com.unity.render-pipelines.high-definition/Documentation~/sky.md b/Packages/com.unity.render-pipelines.high-definition/Documentation~/sky.md
index 30ae0cfd283..d0a1fb35cbc 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Documentation~/sky.md
+++ b/Packages/com.unity.render-pipelines.high-definition/Documentation~/sky.md
@@ -2,6 +2,8 @@
Create different types of sky in the High Definition Render Pipeline (HDRP).
+**Note**: Procedural sky is deprecated and no longer built into HDRP. For information on how to add Procedural Sky to your HDRP Project, see the [Upgrading from 2019.2 to 2019.3 guide](Upgrading-From-2019.2-to-2019.3.md#ProceduralSky).
+
| Page | Description |
|-|-|
| [Understand sky](understand-sky.md) | Understand the different ways you can create sky in HDRP. |
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Core/HDRenderPipelinePreferencesProvider.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Core/HDRenderPipelinePreferencesProvider.cs
index 965bbf77980..d63c09cdc4d 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Core/HDRenderPipelinePreferencesProvider.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Core/HDRenderPipelinePreferencesProvider.cs
@@ -1,10 +1,32 @@
using System.Collections.Generic;
+using System.Reflection;
+using UnityEditor.PackageManager;
+using UnityEditor.PackageManager.Requests;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
namespace UnityEditor.Rendering.HighDefinition.Core
{
+ static class PackageManagerHelper
+ {
+ public static void OpenPackageManagerToPackage(string packageName)
+ {
+ var packageManagerUI = typeof(Editor).Assembly
+ .GetType("UnityEditor.PackageManager.UI.Window");
+
+ if (packageManagerUI != null)
+ {
+ var openMethod = packageManagerUI.GetMethod("Open", BindingFlags.Public | BindingFlags.Static);
+ openMethod?.Invoke(null, new object[] { packageName });
+ }
+ else
+ {
+ Debug.LogWarning("Could not find PackageManager UI type. Package Manager may have changed.");
+ }
+ }
+ }
+
///
/// Editor Preferences for HDRP
///
@@ -13,12 +35,24 @@ public class HDRenderPipelinePreferencesProvider : ICoreRenderPipelinePreference
{
class Styles
{
+ public static readonly GUIContent configPackageLabel = new("Config Package", "Choose whether to embed or sync with registry version.");
+
+ public static readonly GUIContent viewInPackageManagerLabel = new("View in Package Manager", "");
+
+ public static readonly GUIContent hdrpProjectSettingsPathLabel = EditorGUIUtility.TrTextContent("Resources Folder Name", "Resources Folder will be the one where to get project elements related to HDRP as default scene and default settings.");
+
public static readonly GUIContent matcapLabel = EditorGUIUtility.TrTextContent("MatCap Mode Default Values");
public static readonly GUIContent matcapViewMixAlbedoLabel = EditorGUIUtility.TrTextContent("Mix Albedo", "Enable to make HDRP mix the albedo of the Material with its material capture.");
public static readonly GUIContent matcapViewScaleLabel = EditorGUIUtility.TrTextContent("Intensity Scale", "Set the intensity of the material capture. This increases the brightness of the Scene. This is useful if the albedo darkens the Scene considerably.");
}
- static List s_SearchKeywords = new() { "MatCap Mode", "Intensity scale", "Mix Albedo" };
+ static List s_SearchKeywords = new() {
+ "MatCap Mode",
+ "Intensity scale",
+ "Mix Albedo",
+ "Default Resources Folder",
+ "Config Package"
+ };
///
/// Keyworks for the preferences
@@ -29,6 +63,13 @@ class Styles
/// UI for the preferences.
///
public void PreferenceGUI()
+ {
+ HDProjectSettings.projectSettingsFolderPath = EditorGUILayout.TextField(Styles.hdrpProjectSettingsPathLabel, HDProjectSettings.projectSettingsFolderPath);
+ DrawConfigPackageDropdown();
+ DrawMatCapDefaults();
+ }
+
+ void DrawMatCapDefaults()
{
EditorGUILayout.LabelField(Styles.matcapLabel, EditorStyles.boldLabel);
EditorGUI.indentLevel++;
@@ -38,5 +79,18 @@ public void PreferenceGUI()
matCapMode.viewScale.value = EditorGUILayout.FloatField(Styles.matcapViewScaleLabel, matCapMode.viewScale.value);
EditorGUI.indentLevel--;
}
+
+ private const string k_PackageName = "com.unity.render-pipelines.high-definition-config";
+
+ void DrawConfigPackageDropdown()
+ {
+ GUILayout.BeginHorizontal();
+ EditorGUILayout.LabelField(Styles.configPackageLabel, GUILayout.Width(EditorGUIUtility.labelWidth));
+ if (GUILayout.Button(Styles.viewInPackageManagerLabel, GUILayout.Width(200)))
+ {
+ PackageManagerHelper.OpenPackageManagerToPackage(k_PackageName);
+ }
+ GUILayout.EndHorizontal();
+ }
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Drawers.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Drawers.cs
index 50832ecd001..7db6891b9d3 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Drawers.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/HDProbeUI.Drawers.cs
@@ -10,6 +10,8 @@
using UnityEngine.Rendering;
using Object = UnityEngine.Object;
+using UnityEditor.Rendering.Utilities;
+
namespace UnityEditor.Rendering.HighDefinition
{
static partial class HDProbeUI
@@ -515,49 +517,5 @@ internal class ReflectionProbeModifyCapturePositionTool : GenericEditorTool : EditorTool where T : Component
- {
- private readonly string _description;
- private readonly EditMode.SceneViewEditMode _mode;
- private readonly string _iconName;
- private GUIContent _iconContent;
-
- protected GenericEditorTool(string description, EditMode.SceneViewEditMode mode, string iconName)
- {
- _description = description;
- _mode = mode;
- _iconName = iconName;
- }
-
- public override GUIContent toolbarIcon => _iconContent;
- public override void OnWillBeDeactivated() => EditMode.SetEditModeToNone();
- public override void OnToolGUI(EditorWindow window)
- {
- if (EditMode.editMode == _mode)
- return;
-
- List usefulTargets = new();
- foreach (Object thisTarget in targets)
- if (thisTarget is T usefulTarget)
- usefulTargets.Add(usefulTarget);
-
- if (usefulTargets.Count == 0)
- return;
-
- Bounds bounds = GetBoundsOfTargets(usefulTargets);
- EditMode.ChangeEditMode(_mode, bounds);
- ToolManager.SetActiveTool(this);
- }
-
- private static Bounds GetBoundsOfTargets(IEnumerable targets)
- {
- var bounds = new Bounds { min = Vector3.positiveInfinity, max = Vector3.negativeInfinity };
- foreach (T t in targets)
- bounds.Encapsulate(t.transform.position);
-
- return bounds;
- }
-
- private void OnEnable() => _iconContent = EditorGUIUtility.TrIconContent(_iconName, _description);
- }
+
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/PlanarReflectionProbesPreview.shader b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/PlanarReflectionProbesPreview.shader
index f289e86dc25..81609a31409 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/PlanarReflectionProbesPreview.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/PlanarReflectionProbesPreview.shader
@@ -23,7 +23,7 @@ Shader "Hidden/Debug/PlanarReflectionProbePreview"
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma vertex vert
#pragma fragment frag
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/ReflectionProbesPreview.shader b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/ReflectionProbesPreview.shader
index 7f44d1a6fb2..30d2b65d979 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/ReflectionProbesPreview.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/Reflection/ReflectionProbesPreview.shader
@@ -22,7 +22,7 @@ Shader "Hidden/Debug/ReflectionProbePreview"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma editor_sync_compilation
#pragma vertex vert
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricClouds/WorleyEvaluator.compute b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricClouds/WorleyEvaluator.compute
index ccac46616c3..724a6a1c1bd 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricClouds/WorleyEvaluator.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricClouds/WorleyEvaluator.compute
@@ -2,7 +2,7 @@
#pragma kernel WorleyNoiseEvaluator
#pragma kernel PerlinNoiseEvaluator
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/LocalVolumetricFogEditor.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/LocalVolumetricFogEditor.cs
index 698f569f57d..2d28707102a 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/LocalVolumetricFogEditor.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Lighting/VolumetricLighting/LocalVolumetricFogEditor.cs
@@ -4,6 +4,8 @@
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
+using UnityEditor.Rendering.Utilities;
+
namespace UnityEditor.Rendering.HighDefinition
{
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/BRGPicking.shader b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/BRGPicking.shader
index fe81f4b78bc..f166edf3b29 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/BRGPicking.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/BRGPicking.shader
@@ -5,7 +5,7 @@ Shader "Hidden/HDRP/BRGPicking"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma editor_sync_compilation
#pragma multi_compile DOTS_INSTANCING_ON
//#pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.cs
index f4745d524ce..3d4ef28d2dc 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/Decal/DecalProjectorEditor.cs
@@ -11,6 +11,8 @@
using UnityEngine.Rendering.HighDefinition;
using static UnityEditorInternal.EditMode;
using RenderingLayerMask = UnityEngine.RenderingLayerMask;
+using UnityEditor.RenderPipelines.Core;
+using UnityEditor.Rendering.Utilities;
namespace UnityEditor.Rendering.HighDefinition
{
@@ -21,16 +23,11 @@ partial class DecalProjectorEditor : Editor
const float k_Limit = 100000;
const float k_LimitInv = 1 / k_Limit;
+ static readonly GUIContent k_NewDecalMaterialButtonText = EditorGUIUtility.TrTextContent("New", "Creates a new Decal material.");
+ static readonly string k_NewDecalText = "HDRP Decal";
+ static readonly string k_NewSGDecalText = "ShaderGraph Decal";
+ static readonly string k_DefaultDecalShaderGraphTemplatePath = "Packages/com.unity.shadergraph/GraphTemplates/Cross Pipeline/0_Decal Simple.shadergraph";
- static public readonly GUIContent k_NewDecalMaterialButtonText = EditorGUIUtility.TrTextContent("New", "Creates a new Decal material.");
- static public readonly string k_NewDecalText = "HDRP Decal";
- static public readonly string k_NewSGDecalText = "ShaderGraph Decal";
-
- internal enum DefaultDecal
- {
- HDRPDecal,
- SGDecal
- }
static Color fullColor
{
get
@@ -869,35 +866,51 @@ internal void DecalMaterialFieldWithButton(SerializedProperty prop)
return;
GenericMenu menu = new GenericMenu();
- menu.AddItem(new GUIContent(k_NewDecalText), false, () => CreateDefaultDecalMaterial(target as MonoBehaviour, DefaultDecal.HDRPDecal));
- menu.AddItem(new GUIContent(k_NewSGDecalText), false, () => CreateDefaultDecalMaterial(target as MonoBehaviour, DefaultDecal.SGDecal));
+ menu.AddItem(new GUIContent(k_NewDecalText), false, () => CreateDefaultDecalMaterial(targets));
+ menu.AddItem(new GUIContent(k_NewSGDecalText), false, () => CreateDecalMaterialFromTemplate(targets, k_DefaultDecalShaderGraphTemplatePath));
+
+ // For later introduction of SG Filtered Template Browser
+ //menu.AddItem(new GUIContent(k_NewSGDecalFromTemplateText), false, () => CreateDecalMaterialFromTemplate(targets));
+
menu.DropDown(newFieldRect);
}
- public static void CreateDefaultDecalMaterial(MonoBehaviour obj, DefaultDecal defaultDecal)
+ static void CreateDecalMaterialFromTemplate(UnityEngine.Object[] decalProjectors, string templatePath = null)
+ {
+ CreateShaderGraph.CreateGraphAndMaterialFromTemplate((material) =>
+ {
+ SetDecalMaterial(decalProjectors, material);
+ },
+ templatePath,
+ $"New {k_NewSGDecalText}");
+ }
+
+ static void CreateDefaultDecalMaterial(UnityEngine.Object[] decalProjectors)
{
- string materialName = "";
- var materialIcon = AssetPreview.GetMiniTypeThumbnail(typeof(Material));
+ string materialName = "New " + k_NewDecalText;
- var action = ScriptableObject.CreateInstance();
- action.decalProjector = obj as DecalProjector;
+ Shader shader = Shader.Find("HDRP/Decal");
- switch (defaultDecal)
+ AssetCreationUtil.CreateMaterial(
+ materialName,
+ (material) =>
+ {
+ SetDecalMaterial(decalProjectors, material);
+ },
+ shader
+ );
+ }
+
+ static void SetDecalMaterial(UnityEngine.Object[] decalProjectors, Material material)
+ {
+ var selection = new List();
+ foreach (DecalProjector decalProjector in decalProjectors)
{
- case DefaultDecal.HDRPDecal:
- materialName = "New " + k_NewDecalText;
- action.isShaderGraph = false;
- break;
- case DefaultDecal.SGDecal:
- materialName = "New " + k_NewSGDecalText;
- action.isShaderGraph = true;
- break;
- default:
- Debug.LogError("Decal creation failed.");
- break;
+ decalProjector.material = material;
+ EditorUtility.SetDirty(decalProjector);
+ selection.Add(decalProjector.gameObject);
}
-
- ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, action, materialName, materialIcon, null);
+ Selection.objects = selection.ToArray();
}
[Shortcut("HDRP/Decal: Handle changing size stretching UV", typeof(SceneView), KeyCode.Keypad1, ShortcutModifiers.Action)]
@@ -968,41 +981,12 @@ static void ExitEditMode(ShortcutArguments args)
}
}
- class DoCreateDecalDefaultMaterial : ProjectWindowCallback.EndNameEditAction
- {
- public DecalProjector decalProjector;
- public bool isShaderGraph = false;
- public override void Action(int instanceId, string pathName, string resourceFile)
- {
- string shaderGraphName = AssetDatabase.GenerateUniqueAssetPath(pathName + ".shadergraph");
- string materialName = AssetDatabase.GenerateUniqueAssetPath(pathName + ".mat");
- Shader shader = null;
-
- if (isShaderGraph)
- {
- shader = DecalSubTarget.CreateDecalGraphAtPath(shaderGraphName);
- }
- else
- {
- shader = Shader.Find("HDRP/Decal");
- }
-
- if (shader != null)
- {
- var material = new Material(shader);
- AssetDatabase.CreateAsset(material, materialName);
- ProjectWindowUtil.ShowCreatedAsset(material);
- decalProjector.material = material;
- }
- }
- }
-
[EditorTool(Description, typeof(DecalProjector), toolPriority = (int)Mode)]
internal class DecalProjectorModifyScaleTool : GenericEditorTool
{
private const string Description = DecalProjectorEditor.k_EditShapeWithoutPreservingUVTooltip;
private const EditMode.SceneViewEditMode Mode = DecalProjectorEditor.k_EditShapeWithoutPreservingUV;
- private const string IconName = "d_ScaleTool";
+ private const string IconName = "ScaleTool";
protected DecalProjectorModifyScaleTool() : base(Description, Mode, IconName) { }
}
@@ -1012,7 +996,7 @@ internal class DecalProjectorEditShapeTool : GenericEditorTool
{
private const string Description = DecalProjectorEditor.k_EditShapePreservingUVTooltip;
private const EditMode.SceneViewEditMode Mode = DecalProjectorEditor.k_EditShapePreservingUV;
- private const string IconName = "d_RectTool";
+ private const string IconName = "RectTool";
protected DecalProjectorEditShapeTool() : base(Description, Mode, IconName) { }
}
@@ -1022,7 +1006,7 @@ internal class DecalProjectorEditTool : GenericEditorTool
{
private const string Description = DecalProjectorEditor.k_EditUVTooltip;
private const EditMode.SceneViewEditMode Mode = DecalProjectorEditor.k_EditUVAndPivot;
- private const string IconName = "d_MoveTool";
+ private const string IconName = "MoveTool";
protected DecalProjectorEditTool() : base(Description, Mode, IconName) { }
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DrawDiffusionProfile.shader b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DrawDiffusionProfile.shader
index c6e060daa34..857e8cb7883 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DrawDiffusionProfile.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DrawDiffusionProfile.shader
@@ -13,7 +13,7 @@ Shader "Hidden/HDRP/DrawDiffusionProfile"
HLSLPROGRAM
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma vertex Vert
#pragma fragment Frag
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DrawTransmittanceGraph.shader b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DrawTransmittanceGraph.shader
index e1de7a86bcd..d91562b2687 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DrawTransmittanceGraph.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/DiffusionProfile/DrawTransmittanceGraph.shader
@@ -13,7 +13,7 @@ Shader "Hidden/HDRP/DrawTransmittanceGraph"
HLSLPROGRAM
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma vertex Vert
#pragma fragment Frag
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDTarget.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDTarget.cs
index f3b7cfc386b..98aa76faeb8 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDTarget.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/ShaderGraph/HDTarget.cs
@@ -91,6 +91,7 @@ public bool supportLineRendering
{
// Currently there is not support for VFX decals via HDRP master node.
typeof(DecalSubTarget),
+ typeof(TerrainLitSubTarget),
typeof(HDCanvasSubTarget),
typeof(HDFullscreenSubTarget),
typeof(WaterSubTarget),
@@ -119,7 +120,17 @@ public override bool IsNodeAllowedByTarget(Type nodeType)
bool worksWithThisSrp = srpFilter == null || srpFilter.srpTypes.Contains(typeof(HDRenderPipeline));
SubTargetFilterAttribute subTargetFilter = NodeClassCache.GetAttributeOnNodeType(nodeType);
- bool worksWithThisSubTarget = subTargetFilter == null || subTargetFilter.subTargetTypes.Contains(activeSubTarget.GetType());
+ var activeSubTargetType = activeSubTarget.GetType();
+ var worksWithThisSubTarget = subTargetFilter == null;
+ if (subTargetFilter != null)
+ {
+ foreach (var type in subTargetFilter.subTargetTypes)
+ {
+ if (!type.IsAssignableFrom(activeSubTargetType)) continue;
+ worksWithThisSubTarget = true;
+ break;
+ }
+ }
if (activeSubTarget.IsActive())
worksWithThisSubTarget &= activeSubTarget.IsNodeAllowedBySubTarget(nodeType);
@@ -1238,6 +1249,8 @@ static class CoreIncludes
public const string kStackLitPathtracing = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLitPathTracing.hlsl";
public const string kHairRaytracing = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/HairRaytracing.hlsl";
public const string kHairPathtracing = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/HairPathTracing.hlsl";
+ public const string kTerrainRaytracing = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitRaytracing.hlsl";
+ public const string kTerrainPathtracing = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitPathtracing.hlsl";
public const string kRaytracingLightLoop = "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightLoop.hlsl";
public const string kRaytracingCommon = "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingCommon.hlsl";
public const string kNormalBuffer = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/NormalBuffer.hlsl";
@@ -1269,6 +1282,7 @@ static class CoreIncludes
public const string kFabric = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/Fabric.hlsl";
public const string kHair = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/Hair.hlsl";
public const string kStackLit = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/StackLit/StackLit.hlsl";
+ public const string kTerrainLit = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.hlsl";
public const string kSixWayLit = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SixWayLit/SixWaySmokeLit.hlsl";
// Public Pregraph Misc
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph.meta
new file mode 100644
index 00000000000..07357e3bf70
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 3429a133263f8654885a005a3176ea42
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template
new file mode 100644
index 00000000000..7dcc828236c
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template
@@ -0,0 +1,156 @@
+Pass
+{
+ Tags
+ {
+ $splice(BaseGenName)
+ $splice(BaseGenTexFormat)
+ $splice(BaseGenTexSize)
+ }
+
+ // Render State
+ $splice(RenderState)
+
+ // --------------------------------------------------
+ // Pass
+
+ HLSLPROGRAM
+
+ // Pragmas
+ $splice(PassPragmas)
+
+ // Keywords
+ $splice(PassKeywords)
+ $splice(GraphKeywords)
+
+ // For custom interpolators to inject a substruct definition before FragInputs definition,
+ // allowing for FragInputs to capture CI's intended for ShaderGraph's SDI.
+ $splice(CustomInterpolatorPreInclude)
+
+ #define SURFACE_GRADIENT
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Texture.hlsl"
+ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
+ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl"
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/NormalSurfaceGradient.hlsl"
+ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderGraphHeader.hlsl" // Need to be here for Gradient struct definition
+ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap_Includes.hlsl" // Required by terrain
+
+ // --------------------------------------------------
+ // Defines
+
+ // Attribute
+ $AttributesMesh.normalOS: #define ATTRIBUTES_NEED_NORMAL
+ $AttributesMesh.tangentOS: #define ATTRIBUTES_NEED_TANGENT
+ $AttributesMesh.uv0: #define ATTRIBUTES_NEED_TEXCOORD0
+ $AttributesMesh.uv1: #define ATTRIBUTES_NEED_TEXCOORD1
+ $AttributesMesh.uv2: #define ATTRIBUTES_NEED_TEXCOORD2
+ $AttributesMesh.uv3: #define ATTRIBUTES_NEED_TEXCOORD3
+ $AttributesMesh.color: #define ATTRIBUTES_NEED_COLOR
+ $AttributesMesh.vertexID: #define ATTRIBUTES_NEED_VERTEXID
+ $VaryingsMeshToPS.positionRWS: #define VARYINGS_NEED_POSITION_WS
+ $VaryingsMeshToPS.positionPredisplacementRWS: #define VARYINGS_NEED_POSITIONPREDISPLACEMENT_WS
+ $VaryingsMeshToPS.normalWS: #define VARYINGS_NEED_TANGENT_TO_WORLD
+ $VaryingsMeshToPS.texCoord0: #define VARYINGS_NEED_TEXCOORD0
+ $VaryingsMeshToPS.texCoord1: #define VARYINGS_NEED_TEXCOORD1
+ $VaryingsMeshToPS.texCoord2: #define VARYINGS_NEED_TEXCOORD2
+ $VaryingsMeshToPS.texCoord3: #define VARYINGS_NEED_TEXCOORD3
+ $VaryingsMeshToPS.color: #define VARYINGS_NEED_COLOR
+ $VaryingsMeshToPS.elementToWorld0: #define VARYINGS_NEED_ELEMENT_TO_WORLD
+ $VaryingsMeshToPS.worldToElement0: #define VARYINGS_NEED_WORLD_TO_ELEMENT
+
+ $features.graphVertex: #define HAVE_MESH_MODIFICATION
+
+ $SurfaceDescriptionInputs.FaceSign: // Define when IsFontFaceNode is included in ShaderGraph
+ $SurfaceDescriptionInputs.FaceSign: #define VARYINGS_NEED_CULLFACE
+
+ $VertexDescription.CustomVelocity: #define _ADD_CUSTOM_VELOCITY
+
+ $splice(GraphDefines)
+
+ $features.graphTessellation: #ifdef TESSELLATION_ON
+ $features.graphTessellation: // World and normal are always available
+ $features.graphTessellation: $VaryingsMeshToDS.positionPredisplacementRWS: #define VARYINGS_DS_NEED_POSITIONPREDISPLACEMENT
+ $features.graphTessellation: $VaryingsMeshToDS.tangentWS: #define VARYINGS_DS_NEED_TANGENT
+ $features.graphTessellation: $VaryingsMeshToDS.texCoord0: #define VARYINGS_DS_NEED_TEXCOORD0
+ $features.graphTessellation: $VaryingsMeshToDS.texCoord1: #define VARYINGS_DS_NEED_TEXCOORD1
+ $features.graphTessellation: $VaryingsMeshToDS.texCoord2: #define VARYINGS_DS_NEED_TEXCOORD2
+ $features.graphTessellation: $VaryingsMeshToDS.texCoord3: #define VARYINGS_DS_NEED_TEXCOORD3
+ $features.graphTessellation: $VaryingsMeshToDS.color: #define VARYINGS_DS_NEED_COLOR
+ $features.graphTessellation: #endif
+
+ // Following two define are a workaround introduce in 10.1.x for RaytracingQualityNode
+ // The ShaderGraph don't support correctly migration of this node as it serialize all the node data
+ // in the json file making it impossible to uprgrade. Until we get a fix, we do a workaround here
+ // to still allow us to rename the field and keyword of this node without breaking existing code.
+ #ifdef RAYTRACING_SHADER_GRAPH_DEFAULT
+ #define RAYTRACING_SHADER_GRAPH_HIGH
+ #endif
+
+ #ifdef RAYTRACING_SHADER_GRAPH_RAYTRACED
+ #define RAYTRACING_SHADER_GRAPH_LOW
+ #endif
+ // end
+
+ #ifndef SHADER_UNLIT
+ // We need isFrontFace when using double sided - it is not required for unlit as in case of unlit double sided only drive the cullmode
+ // VARYINGS_NEED_CULLFACE can be define by VaryingsMeshToPS.FaceSign input if a IsFrontFace Node is included in the shader graph.
+ #if defined(_DOUBLESIDED_ON) && !defined(VARYINGS_NEED_CULLFACE)
+ #define VARYINGS_NEED_CULLFACE
+ #endif
+ #endif
+
+ #ifndef HD_TERRAIN_ENABLED
+ #ifndef UNITY_TERRAIN_CB_VARS
+ #define UNITY_TERRAIN_CB_VARS
+ #endif
+ #ifndef UNITY_TERRAIN_CB_DEBUG_VARS
+ #define UNITY_TERRAIN_CB_DEBUG_VARS
+ #endif
+ #endif
+
+ // Caution: we can use the define SHADER_UNLIT onlit after the above Material include as it is the Unlit template who define it
+
+ // -- Graph Properties
+ $splice(GraphProperties)
+
+ // -- Properties used by TerrainPass
+ #if HD_TERRAIN_ENABLED
+ CBUFFER_START(UnityTerrain)
+ UNITY_TERRAIN_CB_VARS
+ float4 _Control0_ST;
+ CBUFFER_END
+ #endif // HD_TERRAIN_ENABLED
+
+ // Includes
+ $splice(PreGraphIncludes)
+ $splice(GraphIncludes)
+
+ // Specific Material Define
+ $include("ShaderPassDefine.template.hlsl")
+
+ // --------------------------------------------------
+ // Structs and Packing
+
+ $splice(PassStructs)
+
+ $splice(InterpolatorPack)
+
+ // --------------------------------------------------
+ // Graph
+
+ // Graph Functions
+ $splice(GraphFunctions)
+
+ // Graph Vertex
+ $splice(GraphVertex)
+
+ // Graph Pixel
+ $splice(GraphPixel)
+
+ // --------------------------------------------------
+ // Main
+
+ $include("BaseMapGenPass.template.hlsl")
+
+ ENDHLSL
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template.hlsl b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template.hlsl
new file mode 100644
index 00000000000..df8ac29380f
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template.hlsl
@@ -0,0 +1,42 @@
+
+struct Varyings
+{
+ float4 positionCS : SV_POSITION;
+ float4 texcoord : TEXCOORD0;
+};
+
+float2 ComputeControlUV(float2 uv)
+{
+ // adjust splatUVs so the edges of the terrain tile lie on pixel centers
+ return (uv * (_Control0_TexelSize.zw - 1.0f) + 0.5f) * _Control0_TexelSize.xy;
+}
+
+Varyings Vert(uint vertexID : SV_VertexID)
+{
+ Varyings output;
+ output.positionCS = GetFullScreenTriangleVertexPosition(vertexID);
+ output.texcoord.xy = TRANSFORM_TEX(GetFullScreenTriangleTexCoord(vertexID), _Control0);
+ output.texcoord.zw = ComputeControlUV(output.texcoord.xy);
+ return output;
+}
+
+#if SHADERPASS == SHADERPASS_MAINTEX
+float4 Frag(Varyings input) : SV_Target
+#elif SHADERPASS == SHADERPASS_METALLICTEX
+float2 Frag(Varyings input) : SV_Target
+#endif
+{
+ SurfaceDescriptionInputs surfaceDescriptionInputs;
+ ZERO_INITIALIZE(SurfaceDescriptionInputs, surfaceDescriptionInputs);
+
+ $SurfaceDescriptionInputs.TangentSpaceNormal: surfaceDescriptionInputs.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
+ $SurfaceDescriptionInputs.uv0: surfaceDescriptionInputs.uv0 = input.texcoord;
+
+ SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
+
+#if SHADERPASS == SHADERPASS_MAINTEX
+ return float4(surfaceDescription.BaseColor, surfaceDescription.Smoothness);
+#elif SHADERPASS == SHADERPASS_METALLICTEX
+ return float2(surfaceDescription.Metallic, surfaceDescription.Occlusion);
+#endif
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template.hlsl.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template.hlsl.meta
new file mode 100644
index 00000000000..da7d0447877
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 08df62abac843704ebac409bef3ca70a
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template.meta
new file mode 100644
index 00000000000..ac261a34904
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 197aa062b1da19c4ab751e473602b6d1
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/CreateTerrainLitShaderGraph.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/CreateTerrainLitShaderGraph.cs
new file mode 100644
index 00000000000..3e0e2059e00
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/CreateTerrainLitShaderGraph.cs
@@ -0,0 +1,29 @@
+using System;
+using UnityEditor.ShaderGraph;
+using UnityEngine.Rendering;
+
+namespace UnityEditor.Rendering.HighDefinition.ShaderGraph
+{
+ static class CreateTerrainLitShaderGraph
+ {
+ [MenuItem("Assets/Create/Shader Graph/HDRP/TerrainLit Shader Graph", priority = CoreUtils.Priorities.assetsCreateShaderMenuPriority + 9)]
+ public static void CreateTerrainLitGraph()
+ {
+ var target = (HDTarget)Activator.CreateInstance(typeof(HDTarget));
+ target.TrySetActiveSubTarget(typeof(TerrainLitSubTarget));
+
+ var blockDescriptors = new[]
+ {
+ BlockFields.VertexDescription.Position,
+ BlockFields.SurfaceDescription.BaseColor,
+ BlockFields.SurfaceDescription.NormalTS,
+ BlockFields.SurfaceDescription.Metallic,
+ BlockFields.SurfaceDescription.Emission,
+ BlockFields.SurfaceDescription.Smoothness,
+ BlockFields.SurfaceDescription.Occlusion,
+ };
+
+ GraphUtil.CreateNewGraphWithOutputs(new[] { target }, blockDescriptors);
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/CreateTerrainLitShaderGraph.cs.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/CreateTerrainLitShaderGraph.cs.meta
new file mode 100644
index 00000000000..f97c059b0b1
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/CreateTerrainLitShaderGraph.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: cd75a312c9771134fba5bb24d4c44d35
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template
new file mode 100644
index 00000000000..51dd09c60af
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template
@@ -0,0 +1,263 @@
+Pass
+{
+ $splice(PassName)
+ Tags
+ {
+ $splice(LightMode)
+ }
+
+ // Render State
+ $splice(RenderState)
+
+ // Debug
+ $splice(Debug)
+
+ // --------------------------------------------------
+ // Pass
+
+ HLSLPROGRAM
+
+ // Pragmas
+ $splice(PassPragmas)
+
+ // Keywords
+ $splice(PassKeywords)
+ $splice(GraphKeywords)
+
+ // For custom interpolators to inject a substruct definition before FragInputs definition,
+ // allowing for FragInputs to capture CI's intended for ShaderGraph's SDI.
+ $splice(CustomInterpolatorPreInclude)
+
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/GeometricTools.hlsl" // Required by Tessellation.hlsl
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Tessellation.hlsl"
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Texture.hlsl"
+ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
+ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/FragInputs.hlsl"
+ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPass.cs.hlsl"
+ #include "Packages/com.unity.render-pipelines.core/ShaderLibrary/TextureStack.hlsl" // Required to be include before we include properties as it define DECLARE_STACK_CB
+ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderGraphHeader.hlsl" // Need to be here for Gradient struct definition
+ #include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap_Includes.hlsl" // Required by terrain
+
+ // --------------------------------------------------
+ // Defines
+
+ // Attribute
+ $AttributesMesh.normalOS: #define ATTRIBUTES_NEED_NORMAL
+ $AttributesMesh.uv0: #define ATTRIBUTES_NEED_TEXCOORD0
+ $AttributesMesh.color: #define ATTRIBUTES_NEED_COLOR
+ $AttributesMesh.vertexID: #define ATTRIBUTES_NEED_VERTEXID
+ $VaryingsMeshToPS.positionRWS: #define VARYINGS_NEED_POSITION_WS
+ $VaryingsMeshToPS.positionPredisplacementRWS: #define VARYINGS_NEED_POSITIONPREDISPLACEMENT_WS
+ $VaryingsMeshToPS.normalWS: #define VARYINGS_NEED_TANGENT_TO_WORLD
+ $VaryingsMeshToPS.texCoord0: #define VARYINGS_NEED_TEXCOORD0
+ $VaryingsMeshToPS.color: #define VARYINGS_NEED_COLOR
+ $VaryingsMeshToPS.elementToWorld0: #define VARYINGS_NEED_ELEMENT_TO_WORLD
+ $VaryingsMeshToPS.worldToElement0: #define VARYINGS_NEED_WORLD_TO_ELEMENT
+
+ $features.graphVertex: #define HAVE_MESH_MODIFICATION
+
+ $SurfaceDescriptionInputs.FaceSign: // Define when IsFontFaceNode is included in ShaderGraph
+ $SurfaceDescriptionInputs.FaceSign: #define VARYINGS_NEED_CULLFACE
+
+ $VertexDescription.CustomVelocity: #define _ADD_CUSTOM_VELOCITY
+
+ $splice(GraphDefines)
+
+ $features.graphTessellation: #ifdef TESSELLATION_ON
+ $features.graphTessellation: // World and normal are always available
+ $features.graphTessellation: $VaryingsMeshToDS.positionPredisplacementRWS: #define VARYINGS_DS_NEED_POSITIONPREDISPLACEMENT
+ $features.graphTessellation: $VaryingsMeshToDS.tangentWS: #define VARYINGS_DS_NEED_TANGENT
+ $features.graphTessellation: $VaryingsMeshToDS.texCoord0: #define VARYINGS_DS_NEED_TEXCOORD0
+ $features.graphTessellation: $VaryingsMeshToDS.texCoord1: #define VARYINGS_DS_NEED_TEXCOORD1
+ $features.graphTessellation: $VaryingsMeshToDS.texCoord2: #define VARYINGS_DS_NEED_TEXCOORD2
+ $features.graphTessellation: $VaryingsMeshToDS.texCoord3: #define VARYINGS_DS_NEED_TEXCOORD3
+ $features.graphTessellation: $VaryingsMeshToDS.color: #define VARYINGS_DS_NEED_COLOR
+ $features.graphTessellation: #endif
+
+ // Following two define are a workaround introduce in 10.1.x for RaytracingQualityNode
+ // The ShaderGraph don't support correctly migration of this node as it serialize all the node data
+ // in the json file making it impossible to uprgrade. Until we get a fix, we do a workaround here
+ // to still allow us to rename the field and keyword of this node without breaking existing code.
+ #ifdef RAYTRACING_SHADER_GRAPH_DEFAULT
+ #define RAYTRACING_SHADER_GRAPH_HIGH
+ #endif
+
+ #ifdef RAYTRACING_SHADER_GRAPH_RAYTRACED
+ #define RAYTRACING_SHADER_GRAPH_LOW
+ #endif
+ // end
+
+ #ifndef SHADER_UNLIT
+ // We need isFrontFace when using double sided - it is not required for unlit as in case of unlit double sided only drive the cullmode
+ // VARYINGS_NEED_CULLFACE can be define by VaryingsMeshToPS.FaceSign input if a IsFrontFace Node is included in the shader graph.
+ #if defined(_DOUBLESIDED_ON) && !defined(VARYINGS_NEED_CULLFACE)
+ #define VARYINGS_NEED_CULLFACE
+ #endif
+ #endif
+
+ #ifndef HD_TERRAIN_ENABLED
+ #ifndef UNITY_TERRAIN_CB_VARS
+ #define UNITY_TERRAIN_CB_VARS
+ #endif
+ #ifndef UNITY_TERRAIN_CB_DEBUG_VARS
+ #define UNITY_TERRAIN_CB_DEBUG_VARS
+ #endif
+ #endif
+
+ // Caution: we can use the define SHADER_UNLIT onlit after the above Material include as it is the Unlit template who define it
+
+ #ifndef DEBUG_DISPLAY
+ // In case of opaque we don't want to perform the alpha test, it is done in depth prepass and we use depth equal for ztest (setup from UI)
+ // Don't do it with debug display mode as it is possible there is no depth prepass in this case
+ #if !defined(_SURFACE_TYPE_TRANSPARENT)
+ #if SHADERPASS == SHADERPASS_FORWARD
+ #define SHADERPASS_FORWARD_BYPASS_ALPHA_TEST
+ #elif SHADERPASS == SHADERPASS_GBUFFER
+ #define SHADERPASS_GBUFFER_BYPASS_ALPHA_TEST
+ #endif
+ #endif
+ #endif
+
+ // Define _DEFERRED_CAPABLE_MATERIAL for shader capable to run in deferred pass
+ #if defined(SHADER_LIT) && !defined(_SURFACE_TYPE_TRANSPARENT)
+ #define _DEFERRED_CAPABLE_MATERIAL
+ #endif
+
+ // -- Graph Properties
+ $splice(GraphProperties)
+
+ // -- Property used by ScenePickingPass
+ #ifdef SCENEPICKINGPASS
+ float4 _SelectionID;
+ #endif
+
+ // -- Properties used by SceneSelectionPass
+ #ifdef SCENESELECTIONPASS
+ int _ObjectId;
+ int _PassValue;
+ #endif
+
+ // -- Properties used by TerrainPass
+ #if HD_TERRAIN_ENABLED
+ CBUFFER_START(UnityTerrain)
+ UNITY_TERRAIN_CB_VARS
+ #ifdef UNITY_INSTANCING_ENABLED
+ float4 _TerrainHeightmapRecipSize; // float4(1.0f/width, 1.0f/height, 1.0f/(width-1), 1.0f/(height-1))
+ float4 _TerrainHeightmapScale; // float4(hmScale.x, hmScale.y / (float)(kMaxHeight), hmScale.z, 0.0f)
+ TEXTURE2D(_TerrainHeightmapTexture);
+ TEXTURE2D(_TerrainNormalmapTexture);
+ SAMPLER(sampler_TerrainNormalmapTexture);
+ #endif // UNITY_INSTANCING_ENABLED
+
+ #ifdef DEBUG_DISPLAY
+ UNITY_TERRAIN_CB_DEBUG_VARS
+ #endif
+ CBUFFER_END
+ #endif // HD_TERRAIN_ENABLED
+
+ // Includes
+ $splice(PreGraphIncludes)
+ $splice(GraphIncludes)
+
+ // Specific Material Define
+ $include("ShaderPassDefine.template.hlsl")
+
+ // --------------------------------------------------
+ // Structs and Packing
+
+ $splice(PassStructs)
+
+ $splice(InterpolatorPack)
+
+ // --------------------------------------------------
+ // Graph
+
+ // Graph Functions
+ $splice(GraphFunctions)
+
+ // Graph Vertex
+ $splice(GraphVertex)
+
+ // Graph Pixel
+ $splice(GraphPixel)
+
+ // --------------------------------------------------
+ // Build Graph Inputs
+ $features.graphVertex: $include("Vertex.template.hlsl")
+ $features.graphTessellation: $include("Tessellation.template.hlsl")
+ $features.graphPixel: $include("Pixel.template.hlsl")
+
+ // --------------------------------------------------
+ // Build Surface Data (Specific Material)
+
+ $include("ShaderPass.template.hlsl")
+
+ // --------------------------------------------------
+ // Get Surface And BuiltinData
+
+ void GetSurfaceAndBuiltinData(FragInputs fragInputs, float3 V, inout PositionInputs posInput, out SurfaceData surfaceData, out BuiltinData builtinData RAY_TRACING_OPTIONAL_PARAMETERS)
+ {
+#ifdef ENABLE_TERRAIN_PERPIXEL_NORMAL
+ float2 terrainNormalMapUV = (fragInputs.texCoord0.xy + 0.5f) * _TerrainHeightmapRecipSize.xy;
+ float3 normalOS = SAMPLE_TEXTURE2D(_TerrainNormalmapTexture, sampler_TerrainNormalmapTexture, terrainNormalMapUV).rgb * 2.0 - 1.0;
+ float3 normalWS = TransformObjectToWorldNormal(normalOS);
+ float4 tangentOS = ConstructTerrainTangent(normalOS, float3(0.0, 0.0, 1.0));
+ float4 tangentWS = float4(TransformObjectToWorldNormal(tangentOS.xyz), 0.0);
+
+ fragInputs.tangentToWorld = BuildTangentToWorld(tangentWS, normalWS);
+ fragInputs.texCoord0.xy *= _TerrainHeightmapRecipSize.zw;
+#endif
+
+ // terrain lightmap uvs are always taken from uv0
+ fragInputs.texCoord1 = fragInputs.texCoord2 = fragInputs.texCoord0;
+
+ SurfaceDescriptionInputs surfaceDescriptionInputs = FragInputsToSurfaceDescriptionInputs(fragInputs, V);
+ SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
+
+#ifdef _TERRAIN_SG_ALPHA_CLIP
+ half alpha = surfaceDescription.Alpha;
+ clip(alpha - surfaceDescription.AlphaClipThreshold);
+#endif
+
+ #if !defined(SHADER_STAGE_RAY_TRACING) && _DEPTHOFFSET_ON
+ ApplyDepthOffsetPositionInput(V, surfaceDescription.DepthOffset, GetViewForwardDir(), GetWorldToHClipMatrix(), posInput);
+ #endif
+
+ float3 bentNormalWS;
+ BuildSurfaceData(fragInputs, surfaceDescription, V, posInput, surfaceData, bentNormalWS);
+
+ // Builtin Data
+ // For back lighting we use the oposite vertex normal
+ InitBuiltinData(posInput, 1.0, bentNormalWS, -fragInputs.tangentToWorld[2], fragInputs.texCoord1, fragInputs.texCoord2, builtinData);
+
+ // override sampleBakedGI - not used by Unlit
+ $LightingGI: builtinData.bakeDiffuseLighting = surfaceDescription.BakedGI;
+ $BackLightingGI: builtinData.backBakeDiffuseLighting = surfaceDescription.BakedBackGI;
+
+ $SurfaceDescription.Emission: builtinData.emissiveColor = surfaceDescription.Emission;
+
+ // Note this will not fully work on transparent surfaces (can check with _SURFACE_TYPE_TRANSPARENT define)
+ // We will always overwrite vt feeback with the nearest. So behind transparent surfaces vt will not be resolved
+ // This is a limitation of the current MRT approach.
+ #ifdef UNITY_VIRTUAL_TEXTURING
+ $SurfaceDescription.VTPackedFeedback: builtinData.vtPackedFeedback = surfaceDescription.VTPackedFeedback;
+ #endif
+
+ #if _DEPTHOFFSET_ON
+ builtinData.depthOffset = surfaceDescription.DepthOffset;
+ #endif
+
+ // PostInitBuiltinData call ApplyDebugToBuiltinData
+ PostInitBuiltinData(V, posInput, surfaceData, builtinData);
+
+ RAY_TRACING_OPTIONAL_ALPHA_TEST_PASS
+ }
+
+ // --------------------------------------------------
+ // Main
+
+ $splice(PostGraphIncludes)
+
+ ENDHLSL
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template.hlsl b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template.hlsl
new file mode 100644
index 00000000000..458575e6744
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template.hlsl
@@ -0,0 +1,137 @@
+float3 ConvertToNormalTS(float3 normalData, float3 tangentWS, float3 bitangentWS)
+{
+#ifdef _NORMALMAP
+ #ifdef SURFACE_GRADIENT
+ return SurfaceGradientFromTBN(normalData.xy, tangentWS, bitangentWS);
+ #else
+ return normalData;
+ #endif
+#else
+ #ifdef SURFACE_GRADIENT
+ return float3(0.0, 0.0, 0.0); // No gradient
+ #else
+ return float3(0.0, 0.0, 1.0);
+ #endif
+#endif
+}
+
+void BuildSurfaceData(inout FragInputs fragInputs, inout SurfaceDescription surfaceDescription, float3 V, PositionInputs posInput, out SurfaceData surfaceData, out float3 bentNormalWS)
+{
+ ZERO_INITIALIZE(SurfaceData, surfaceData);
+
+#ifdef ENABLE_TERRAIN_PERPIXEL_NORMAL
+ #ifdef TERRAIN_PERPIXEL_NORMAL_OVERRIDE
+ float3 normalWS = surfaceDescription.normalWS;
+ #else
+ float2 texCoord0 = fragInputs.texCoord0.xy / _TerrainHeightmapRecipSize.zw;
+ float2 terrainNormalMapUV = (texCoord0 + 0.5f) * _TerrainHeightmapRecipSize.xy;
+ float3 normalOS = SAMPLE_TEXTURE2D(_TerrainNormalmapTexture, sampler_TerrainNormalmapTexture, terrainNormalMapUV).rgb * 2.0 - 1.0;
+ float3 normalWS = mul((float3x3)GetObjectToWorldMatrix(), normalOS);
+ #endif
+ float4 tangentWS = ConstructTerrainTangent(normalWS, GetObjectToWorldMatrix()._13_23_33);
+ fragInputs.tangentToWorld = BuildTangentToWorld(tangentWS, normalWS);
+ surfaceData.normalWS = normalWS;
+#endif
+
+ // The tangent is not normalize in tangentToWorld for mikkt. Tag: SURFACE_GRADIENT
+ surfaceData.tangentWS = normalize(fragInputs.tangentToWorld[0].xyz);
+
+ surfaceData.geomNormalWS = fragInputs.tangentToWorld[2];
+
+ $SurfaceDescription.BaseColor: surfaceData.baseColor = surfaceDescription.BaseColor;
+ $SurfaceDescription.Smoothness: surfaceData.perceptualSmoothness = surfaceDescription.Smoothness;
+ $SurfaceDescription.Occlusion: surfaceData.ambientOcclusion = surfaceDescription.Occlusion;
+ $SurfaceDescription.SpecularOcclusion: surfaceData.specularOcclusion = surfaceDescription.SpecularOcclusion;
+ $SurfaceDescription.Metallic: surfaceData.metallic = surfaceDescription.Metallic;
+
+ // Transparency parameters
+ // Use thickness from SSS
+ surfaceData.ior = 1.0;
+ surfaceData.transmittanceColor = float3(1.0, 1.0, 1.0);
+ surfaceData.atDistance = 1000000.0;
+ surfaceData.transmittanceMask = 0.0;
+
+ // specularOcclusion need to be init ahead of decal to quiet the compiler that modify the SurfaceData struct
+ // however specularOcclusion can come from the graph, so need to be init here so it can be override.
+ surfaceData.specularOcclusion = 1.0;
+
+ // These static material feature allow compile time optimization
+ surfaceData.materialFeatures = MATERIALFEATUREFLAGS_LIT_STANDARD;
+
+#if defined(DECAL_SURFACE_GRADIENT) && defined(SURFACE_GRADIENT)
+ #if !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL) || !defined(TERRAIN_PERPIXEL_NORMAL_OVERRIDE)
+ float3 normalTS = float3(0.0, 0.0, 1.0);
+ $SurfaceDescription.NormalOS: normalTS = TransformObjectToTangent(surfaceDescription.NormalOS, fragInputs.tangentToWorld);
+ $SurfaceDescription.NormalTS: normalTS = surfaceDescription.NormalTS;
+ $SurfaceDescription.NormalWS: normalTS = TransformWorldToTangent(surfaceDescription.NormalWS, fragInputs.tangentToWorld);
+ normalTS = ConvertToNormalTS(normalTS, fragInputs.tangentToWorld[0], fragInputs.tangentToWorld[1]);
+ #if HAVE_DECALS
+ if (_EnableDecals)
+ {
+ float alpha = 1.0; // unused
+
+ DecalSurfaceData decalSurfaceData = GetDecalSurfaceData(posInput, fragInputs, alpha);
+ ApplyDecalToSurfaceData(decalSurfaceData, fragInputs.tangentToWorld[2], surfaceData, normalTS);
+ }
+ #endif // HAVE_DECALS
+ GetNormalWS(fragInputs, normalTS, surfaceData.normalWS, float3(1.0, 1.0, 1.0));
+ #elif HAVE_DECALS
+ if (_EnableDecals)
+ {
+ float3 normalTS = SurfaceGradientFromPerturbedNormal(input.tangentToWorld[2], surfaceData.normalWS);
+
+ float alpha = 1.0; // unused
+
+ DecalSurfaceData decalSurfaceData = GetDecalSurfaceData(posInput, fragInputs, alpha);
+ ApplyDecalToSurfaceData(decalSurfaceData, fragInputs.tangentToWorld[2], surfaceData, normalTS);
+
+ GetNormalWS(fragInputs, normalTS, surfaceData.normalWS, float3(1.0, 1.0, 1.0));
+ }
+ #endif // HAVE_DECALS
+#else // DECAL_SURFACE_GRADIENT && SURFACE_GRADIENT
+ #if !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL) || !defined(TERRAIN_PERPIXEL_NORMAL_OVERRIDE)
+ float3 normalTS = float3(0.0, 0.0, 1.0);
+ $SurfaceDescription.NormalOS: normalTS = TransformObjectToTangent(surfaceDescription.NormalOS, fragInputs.tangentToWorld);
+ $SurfaceDescription.NormalTS: normalTS = surfaceDescription.NormalTS;
+ $SurfaceDescription.NormalWS: normalTS = TransformWorldToTangent(surfaceDescription.NormalWS, fragInputs.tangentToWorld);
+ normalTS = ConvertToNormalTS(normalTS, fragInputs.tangentToWorld[0], fragInputs.tangentToWorld[1]);
+ GetNormalWS(fragInputs, normalTS, surfaceData.normalWS, float3(1.0, 1.0, 1.0));
+ #endif
+
+ #if HAVE_DECALS
+ if (_EnableDecals)
+ {
+ float alpha = 1.0; // unused
+
+ // Both uses and modifies 'surfaceData.normalWS'.
+ DecalSurfaceData decalSurfaceData = GetDecalSurfaceData(posInput, fragInputs, alpha);
+ ApplyDecalToSurfaceData(decalSurfaceData, fragInputs.tangentToWorld[2], surfaceData);
+ }
+ #endif // HAVE_DECALS
+#endif // DECAL_SURFACE_GRADIENT && SURFACE_GRADIENT
+
+ bentNormalWS = surfaceData.normalWS;
+
+#ifdef DEBUG_DISPLAY
+ if (_DebugMipMapMode != DEBUGMIPMAPMODE_NONE)
+ {
+ // TODO: need to update mip info
+ TerrainLitDebug(fragInputs.texCoord0.xy, posInput.positionSS, surfaceData.baseColor);
+ surfaceData.metallic = 0;
+ }
+
+ // We need to call ApplyDebugToSurfaceData after filling the surfarcedata and before filling builtinData
+ // as it can modify attribute use for static lighting
+ ApplyDebugToSurfaceData(fragInputs.tangentToWorld, surfaceData);
+#endif
+
+// By default we use the ambient occlusion with Tri-ace trick (apply outside) for specular occlusion.
+// If user provide bent normal then we process a better term
+#if defined(_MASKMAP) && !defined(_SPECULAR_OCCLUSION_NONE)
+ surfaceData.specularOcclusion = GetSpecularOcclusionFromAmbientOcclusion(ClampNdotV(dot(surfaceData.normalWS, V)), surfaceData.ambientOcclusion, PerceptualSmoothnessToRoughness(surfaceData.perceptualSmoothness));
+#endif
+
+#if defined(_ENABLE_GEOMETRIC_SPECULAR_AA) && !defined(SHADER_STAGE_RAY_TRACING)
+ surfaceData.perceptualSmoothness = GeometricNormalFiltering(surfaceData.perceptualSmoothness, fragInputs.tangentToWorld[2], surfaceDescription.SpecularAAScreenSpaceVariance, surfaceDescription.SpecularAAThreshold);
+#endif
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template.hlsl.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template.hlsl.meta
new file mode 100644
index 00000000000..dd9b5bf2bb5
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template.hlsl.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 9a03d0d46bf247744afd9c654824e1f4
+ShaderImporter:
+ externalObjects: {}
+ defaultTextures: []
+ nonModifiableTextures: []
+ preprocessorOverride: 0
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template.meta
new file mode 100644
index 00000000000..6861a10e3ac
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: e308631955a56a44b819ab9acedd344c
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPassDefine.template.hlsl b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPassDefine.template.hlsl
new file mode 100644
index 00000000000..de12049f2f5
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPassDefine.template.hlsl
@@ -0,0 +1,278 @@
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Texture.hlsl"
+
+$Material.SubsurfaceScattering: #define _MATERIAL_FEATURE_SUBSURFACE_SCATTERING 1
+$Material.Transmission: #define _MATERIAL_FEATURE_TRANSMISSION 1
+$Material.Anisotropy: #define _MATERIAL_FEATURE_ANISOTROPY 1
+$Material.Iridescence: #define _MATERIAL_FEATURE_IRIDESCENCE 1
+$Material.SpecularColor: #define _MATERIAL_FEATURE_SPECULAR_COLOR 1
+$Material.ClearCoat: #define _MATERIAL_FEATURE_CLEAR_COAT
+$AmbientOcclusion: #define _AMBIENT_OCCLUSION 1
+$SpecularOcclusionFromAO: #define _SPECULAR_OCCLUSION_FROM_AO 1
+$SpecularOcclusionFromAOBentNormal: #define _SPECULAR_OCCLUSION_FROM_AO_BENT_NORMAL 1
+$SpecularOcclusionCustom: #define _SPECULAR_OCCLUSION_CUSTOM 1
+$Specular.EnergyConserving: #define _ENERGY_CONSERVING_SPECULAR 1
+$Specular.AA: #define _ENABLE_GEOMETRIC_SPECULAR_AA 1
+$RefractionBox: #define _REFRACTION_PLANE 1
+$RefractionSphere: #define _REFRACTION_SPHERE 1
+$RefractionThin: #define _REFRACTION_THIN 1
+
+// This shader support recursive rendering for raytracing
+//#define HAVE_RECURSIVE_RENDERING
+
+#define SHADERPASS_MAINTEX (27)
+#define SHADERPASS_METALLICTEX (28)
+
+#if defined(UNITY_INSTANCING_ENABLED) && defined(_TERRAIN_INSTANCED_PERPIXEL_NORMAL)
+#define ENABLE_TERRAIN_PERPIXEL_NORMAL
+#endif
+
+#define TERRAIN_DEFAULT_TEXTURE
+TEXTURE2D(_BlackTex); SAMPLER(sampler_BlackTex);
+TEXTURE2D(_NormalBlank); SAMPLER(sampler_NormalBlank);
+TEXTURE2D(_DefaultWhiteTex); SAMPLER(sampler_BilinearClamp);
+SAMPLER(sampler_BilinearRepeat);
+SAMPLER(sampler_Control1);
+
+float4 _BlackTex_TexelSize = float4(1,1,1,1);
+half4 _BlackTex_ST = half4(1,1,0,0);
+
+
+
+#if defined(_ALPHATEST_ON) && !defined(_HOLES_TEXTURE_DEF)
+#define _HOLES_TEXTURE_DEF
+TEXTURE2D(_TerrainHolesTexture);
+SAMPLER(sampler_TerrainHolesTexture);
+#endif
+
+UnityTexture2D TerrainBuildUnityTexture2DStructInternal(Texture2D tex, SamplerState samplerstate, float4 texelSize, float4 scaleTranslate)
+{
+ UnityTexture2D result;
+ result.tex = tex;
+ result.samplerstate = samplerstate;
+ result.texelSize = texelSize;
+ result.scaleTranslate = scaleTranslate;
+ return result;
+}
+
+
+#ifndef _TERRAIN_8_LAYERS
+#define DEF_TERRAIN_TEXTURE_LOAD(name, defaultName) UnityTexture2D TerrainBuildUnityTexture2DStructInternal##name(int index) \
+{ \
+ switch(index) \
+ { \
+ case 0: \
+ return TerrainBuildUnityTexture2DStructInternal(name##0, sampler_BilinearRepeat, _Splat0_TexelSize, _Splat0_ST); \
+ case 1: \
+ return TerrainBuildUnityTexture2DStructInternal(name##1, sampler_BilinearRepeat, _Splat1_TexelSize, _Splat1_ST); \
+ case 2: \
+ return TerrainBuildUnityTexture2DStructInternal(name##2, sampler_BilinearRepeat, _Splat2_TexelSize, _Splat2_ST); \
+ case 3: \
+ return TerrainBuildUnityTexture2DStructInternal(name##3, sampler_BilinearRepeat, _Splat3_TexelSize, _Splat3_ST); \
+ default: \
+ return TerrainBuildUnityTexture2DStructInternal(defaultName, sampler_BilinearRepeat, _BlackTex_TexelSize, _BlackTex_ST); \
+ } \
+}
+
+#define DEF_TERRAIN_TEXTURE_AVAILABLE(name) float TerrainTextureAvailableInternal##name(int index) \
+{ \
+ switch(index) \
+ { \
+ case 0: \
+ case 1: \
+ case 2: \
+ case 3: \
+ return 1; \
+ default: \
+ return 0; \
+ } \
+}
+
+#define DEF_TERRAIN_VALUE_LOAD(name, returnType, defaultVal) returnType Unity_Terrain##name(int index) \
+{ \
+ switch(index) \
+ { \
+ case 0: \
+ return name##0; \
+ case 1: \
+ return name##1; \
+ case 2: \
+ return name##2; \
+ case 3: \
+ return name##3; \
+ } \
+ return defaultVal; \
+}
+
+float TerrainTextureAvailableInternal_Mask(int index)
+{
+ switch(index)
+ {
+ case 0:
+ return _LayerHasMask0;
+ case 1:
+ return _LayerHasMask1;
+ case 2:
+ return _LayerHasMask2;
+ case 3:
+ return _LayerHasMask3;
+ default:
+ return 0;
+ }
+}
+
+#else
+
+#define DEF_TERRAIN_TEXTURE_LOAD(name, defaultName) UnityTexture2D TerrainBuildUnityTexture2DStructInternal##name(int index) \
+{ \
+ switch(index) \
+ { \
+ case 0: \
+ return TerrainBuildUnityTexture2DStructInternal(name##0, sampler_BilinearRepeat, _Splat0_TexelSize, _Splat0_ST); \
+ case 1: \
+ return TerrainBuildUnityTexture2DStructInternal(name##1, sampler_BilinearRepeat, _Splat1_TexelSize, _Splat1_ST); \
+ case 2: \
+ return TerrainBuildUnityTexture2DStructInternal(name##2, sampler_BilinearRepeat, _Splat2_TexelSize, _Splat2_ST); \
+ case 3: \
+ return TerrainBuildUnityTexture2DStructInternal(name##3, sampler_BilinearRepeat, _Splat3_TexelSize, _Splat3_ST); \
+ case 4: \
+ return TerrainBuildUnityTexture2DStructInternal(name##4, sampler_BilinearRepeat, _Splat4_TexelSize, _Splat4_ST); \
+ case 5: \
+ return TerrainBuildUnityTexture2DStructInternal(name##5, sampler_BilinearRepeat, _Splat5_TexelSize, _Splat5_ST); \
+ case 6: \
+ return TerrainBuildUnityTexture2DStructInternal(name##6, sampler_BilinearRepeat, _Splat6_TexelSize, _Splat6_ST); \
+ case 7: \
+ return TerrainBuildUnityTexture2DStructInternal(name##7, sampler_BilinearRepeat, _Splat7_TexelSize, _Splat7_ST); \
+ default: \
+ return TerrainBuildUnityTexture2DStructInternal(defaultName, sampler_BilinearRepeat, _BlackTex_TexelSize, _BlackTex_ST); \
+ } \
+}
+
+#define DEF_TERRAIN_TEXTURE_AVAILABLE(name) float TerrainTextureAvailableInternal##name(int index) \
+{ \
+ switch(index) \
+ { \
+ case 0: \
+ case 1: \
+ case 2: \
+ case 3: \
+ case 4: \
+ case 5: \
+ case 6: \
+ case 7: \
+ return 1; \
+ default: \
+ return 0; \
+ } \
+}
+
+float TerrainTextureAvailableInternal_Mask(int index)
+{
+ switch(index)
+ {
+ case 0:
+ return _LayerHasMask0;
+ case 1:
+ return _LayerHasMask1;
+ case 2:
+ return _LayerHasMask2;
+ case 3:
+ return _LayerHasMask3;
+ case 4:
+ return _LayerHasMask4;
+ case 5:
+ return _LayerHasMask5;
+ case 6:
+ return _LayerHasMask6;
+ case 7:
+ return _LayerHasMask7;
+ default:
+ return 0;
+ }
+}
+
+#define DEF_TERRAIN_VALUE_LOAD(name, returnType, defaultVal) returnType Unity_Terrain##name(int index) \
+{ \
+ switch(index) \
+ { \
+ case 0: \
+ return name##0; \
+ case 1: \
+ return name##1; \
+ case 2: \
+ return name##2; \
+ case 3: \
+ return name##3; \
+ case 4: \
+ return name##4; \
+ case 5: \
+ return name##5; \
+ case 6: \
+ return name##6; \
+ case 7: \
+ return name##7; \
+ } \
+ return defaultVal; \
+}
+
+#endif
+
+DEF_TERRAIN_TEXTURE_LOAD(_Splat, _BlackTex)
+DEF_TERRAIN_TEXTURE_AVAILABLE(_Splat)
+DEF_TERRAIN_TEXTURE_LOAD(_Normal, _NormalBlank)
+DEF_TERRAIN_TEXTURE_AVAILABLE(_Normal)
+DEF_TERRAIN_TEXTURE_LOAD(_Mask, _BlackTex)
+
+DEF_TERRAIN_VALUE_LOAD(_NormalScale, float, float(1))
+DEF_TERRAIN_VALUE_LOAD(_Metallic, float, float(0))
+DEF_TERRAIN_VALUE_LOAD(_Smoothness, float, float(0.5))
+DEF_TERRAIN_VALUE_LOAD(_DiffuseRemapScale, float4, float4(1,1,1,1))
+DEF_TERRAIN_VALUE_LOAD(_MaskMapRemapOffset, float4, float4(0,0,0,0))
+DEF_TERRAIN_VALUE_LOAD(_MaskMapRemapScale, float4, float4(1,1,1,1))
+
+#ifndef _TERRAIN_8_LAYERS
+float TerrainTextureAvailableInternal_Control(int index)
+{
+ return index==0;
+}
+UnityTexture2D TerrainBuildUnityTextureControl(int index)
+{
+ switch(index)
+ {
+ case 0:
+ return TerrainBuildUnityTexture2DStructInternal(_Control0, sampler_Control0, _Control0_TexelSize, float4(1,1,0,0));
+ default:
+ return TerrainBuildUnityTexture2DStructInternal(_BlackTex, sampler_BlackTex, _BlackTex_TexelSize, _BlackTex_ST);
+ }
+}
+#else
+float TerrainTextureAvailableInternal_Control(int index)
+{
+ return index==0||index==1;
+}
+UnityTexture2D TerrainBuildUnityTextureControl(int index)
+{
+ switch(index)
+ {
+ case 0:
+ return TerrainBuildUnityTexture2DStructInternal(_Control0, sampler_Control0, _Control0_TexelSize, float4(1,1,0,0));
+ case 1:
+ return TerrainBuildUnityTexture2DStructInternal(_Control1, sampler_Control1, _Control0_TexelSize, float4(1,1,0,0));
+ default:
+ return TerrainBuildUnityTexture2DStructInternal(_BlackTex, sampler_BlackTex, _BlackTex_TexelSize, _BlackTex_ST);
+ }
+}
+#endif
+#define Unity_TerrainTextureAvailable(t, n) TerrainTextureAvailableInternal##t(n)
+
+UnityTexture2D TerrainBuildUnityTextureHoles(int index)
+{
+ #if defined(_ALPHATEST_ON)
+ return TerrainBuildUnityTexture2DStructInternal(_TerrainHolesTexture, sampler_TerrainHolesTexture, _Control0_TexelSize, float4(1,1,0,0));
+ #else
+ return TerrainBuildUnityTexture2DStructInternal(_DefaultWhiteTex, sampler_BilinearClamp, _BlackTex_TexelSize, _BlackTex_ST);
+ #endif
+}
+
+#define TerrainBuildUnityTexture2DStruct(name, index) TerrainBuildUnityTexture2DStructInternal##name(index)
+#define TerrainBuildUnityTexture2DStructNoIndex(name) TerrainBuildUnityTexture2DStructInternal(name, sampler##name, name##_TexelSize, name##_ST)
+
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPassDefine.template.hlsl.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPassDefine.template.hlsl.meta
new file mode 100644
index 00000000000..0e76c9e075b
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/ShaderPassDefine.template.hlsl.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: f9d1b55e3551258479b60f736e947138
+ShaderImporter:
+ externalObjects: {}
+ defaultTextures: []
+ nonModifiableTextures: []
+ preprocessorOverride: 0
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitData.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitData.cs
new file mode 100644
index 00000000000..886bbdf9a69
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitData.cs
@@ -0,0 +1,32 @@
+using UnityEngine;
+
+namespace UnityEditor.Rendering.HighDefinition.ShaderGraph
+{
+ class TerrainLitData : HDTargetData
+ {
+ [SerializeField]
+ private bool m_EnableHeightBlened;
+ public bool enableHeightBlend
+ {
+ get => m_EnableHeightBlened;
+ set => m_EnableHeightBlened = value;
+ }
+
+ [SerializeField]
+ private float m_HeightTransition;
+ public float heightTransition
+ {
+ get => m_HeightTransition;
+ set => m_HeightTransition = value;
+ }
+
+ [SerializeField]
+ private bool m_EnableInstancedPerPixelNormal = true;
+ public bool enableInstancedPerPixelNormal
+ {
+ get => m_EnableInstancedPerPixelNormal;
+ set => m_EnableInstancedPerPixelNormal = value;
+ }
+
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitData.cs.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitData.cs.meta
new file mode 100644
index 00000000000..77d625345d7
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitData.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: dac99753de6d2fa49be5a291db03011c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.Dependencies.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.Dependencies.cs
new file mode 100644
index 00000000000..9c7118b8daa
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.Dependencies.cs
@@ -0,0 +1,138 @@
+using System.Collections.Generic;
+using UnityEditor.ShaderGraph;
+using UnityEngine.Rendering.HighDefinition;
+
+namespace UnityEditor.Rendering.HighDefinition.ShaderGraph
+{
+ sealed partial class TerrainLitSubTarget
+ {
+ #region Template
+ static class TerrainBaseMapGenTemplate
+ {
+ public static readonly string kPassTemplate = $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/TerrainLit/ShaderGraph/BaseMapGenPass.template";
+ }
+ #endregion
+
+ private SubShaderDescriptor GetBaseMapGenSubShaderDescriptor()
+ {
+ return new SubShaderDescriptor()
+ {
+ hideTags = true,
+ generatesPreview = false,
+ customTags = "\"SplatCount\" = \"8\"",
+ passes = GetPasses(),
+ additionalShaderID = "Hidden/{Name}_BaseMapGen",
+ shaderCustomEditors = new List(),
+ shaderCustomEditor = "",
+ shaderFallback = "",
+ };
+
+ PassCollection GetPasses()
+ {
+ var passes = new PassCollection()
+ {
+ GenerateMainTex(systemData.tessellation),
+ GenerateMetallicTex(systemData.tessellation),
+ };
+
+ return passes;
+ }
+ }
+
+ #region Passes
+ static public PassDescriptor GenerateMainTex(bool useTessellation)
+ {
+ var result = new PassDescriptor()
+ {
+ // Definition
+ referenceName = "SHADERPASS_MAINTEX",
+ displayName = "MainTex",
+ lightMode = "MainTex",
+ useInPreview = false,
+ passTemplatePath = TerrainBaseMapGenTemplate.kPassTemplate,
+
+ // Collections
+ structs = HDShaderPasses.GenerateStructs(null, false, useTessellation),
+ requiredFields = CoreRequiredFields.BasicLighting,
+ renderStates = TerrainBaseGen.BaseMapGenRenderState,
+ pragmas = TerrainBaseGen.BaseMapPragmas,
+ defines = HDShaderPasses.GenerateDefines(CoreDefines.ForwardLit, false, useTessellation),
+ includes = TerrainBaseGen.Includes,
+ additionalCommands = TerrainBaseGen.BaseMapMainTex,
+ virtualTextureFeedback = false,
+ };
+
+ return result;
+ }
+
+ static public PassDescriptor GenerateMetallicTex(bool useTessellation)
+ {
+ return new PassDescriptor()
+ {
+ // Definition
+ referenceName = "SHADERPASS_METALLICTEX",
+ displayName = "MetallicTex",
+ lightMode = "MetallicTex",
+ useInPreview = false,
+ passTemplatePath = TerrainBaseMapGenTemplate.kPassTemplate,
+
+ // Collections
+ structs = HDShaderPasses.GenerateStructs(null, false, useTessellation),
+ requiredFields = CoreRequiredFields.BasicLighting,
+ renderStates = TerrainBaseGen.BaseMapGenRenderState,
+ pragmas = TerrainBaseGen.BaseMapPragmas,
+ defines = HDShaderPasses.GenerateDefines(CoreDefines.ForwardLit, false, useTessellation),
+ includes = TerrainBaseGen.Includes,
+ additionalCommands = TerrainBaseGen.BaseMapMetallicTex,
+ virtualTextureFeedback = false,
+ };
+ }
+
+ static class TerrainBaseGen
+ {
+ private static string kMainTexName = "\"Name\" = \"_MainTex\"";
+ private static string kMainTexFormat = "\"Format\" = \"ARGB32\"";
+ private static string kMainTexSize = "\"Size\" = \"1\"";
+
+ private static string kMetallicTexName = "\"Name\" = \"_MetallicTex\"";
+ private static string kMetallicTexFormat = "\"Format\" = \"RG16\"";
+ private static string kMetallicTexSize = "\"Size\" = \"1/4\"";
+
+ public static RenderStateCollection BaseMapGenRenderState = new RenderStateCollection()
+ {
+ { RenderState.ZTest(ZTest.Always) },
+ { RenderState.Cull(Cull.Off) },
+ { RenderState.ZWrite(ZWrite.Off) },
+ { RenderState.Blend("One", "[_DstBlend]") },
+ };
+
+ public static readonly PragmaCollection BaseMapPragmas = new PragmaCollection()
+ {
+ { Pragma.Target(ShaderModel.Target45) },
+ { Pragma.Vertex("Vert") },
+ { Pragma.Fragment("Frag") },
+ };
+
+ public static IncludeCollection Includes = new IncludeCollection
+ {
+ { TerrainIncludes.kTerrainLitSurfaceData, IncludeLocation.Pregraph },
+ { TerrainIncludes.kSplatmap, IncludeLocation.Pregraph },
+ };
+
+ public static readonly AdditionalCommandCollection BaseMapMainTex = new AdditionalCommandCollection()
+ {
+ new AdditionalCommandDescriptor("BaseGenName", kMainTexName),
+ new AdditionalCommandDescriptor("BaseGenTexFormat", kMainTexFormat),
+ new AdditionalCommandDescriptor("BaseGenTexSize", kMainTexSize),
+ };
+
+ public static readonly AdditionalCommandCollection BaseMapMetallicTex = new AdditionalCommandCollection()
+ {
+ new AdditionalCommandDescriptor("BaseGenName", kMetallicTexName),
+ new AdditionalCommandDescriptor("BaseGenTexFormat", kMetallicTexFormat),
+ new AdditionalCommandDescriptor("BaseGenTexSize", kMetallicTexSize),
+ };
+ }
+ #endregion
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.Dependencies.cs.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.Dependencies.cs.meta
new file mode 100644
index 00000000000..8f1aab39e57
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.Dependencies.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d38af0e5f7d74df45aca3b38c4561f33
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.cs
new file mode 100644
index 00000000000..bef6e6918eb
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.cs
@@ -0,0 +1,1102 @@
+using System;
+using System.Collections.Generic;
+using UnityEditor.ShaderGraph;
+using UnityEditor.ShaderGraph.Internal;
+using UnityEditor.ShaderGraph.Legacy;
+using UnityEngine;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.HighDefinition;
+
+using static UnityEngine.Rendering.HighDefinition.HDMaterial;
+using static UnityEngine.Rendering.HighDefinition.HDMaterialProperties;
+using static UnityEditor.Rendering.HighDefinition.HDFields;
+
+namespace UnityEditor.Rendering.HighDefinition.ShaderGraph
+{
+ sealed partial class TerrainLitSubTarget : LightingSubTarget, IRequiresData, ITerrainSubTarget
+ {
+ public TerrainLitSubTarget() => displayName = "TerrainLit";
+
+ private static readonly GUID kSubTargetSourceCodeGuid = new GUID("7771b949c95f4ed9ac018e9db21849e5");
+ private static string[] passTemplateMaterialDirectories => new [] {$"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/TerrainLit/ShaderGraph/"};
+
+ protected override string templatePath => $"{HDUtils.GetHDRenderPipelinePath()}Editor/Material/TerrainLit/ShaderGraph/ShaderPass.template";
+ protected override string[] templateMaterialDirectories => passTemplateMaterialDirectories;
+ protected override ShaderID shaderID => ShaderID.SG_TerrainLit;
+ protected override string customInspector => "Rendering.HighDefinition.TerrainLitShaderGraphGUI";
+ protected override string renderType => HDRenderTypeTags.Opaque.ToString();
+ protected override GUID subTargetAssetGuid => kSubTargetSourceCodeGuid;
+ internal override MaterialResetter setupMaterialKeywordsAndPassFunc => ShaderGraphAPI.ValidateTerrain;
+ protected override FieldDescriptor subShaderField => new FieldDescriptor(kSubShader, "TerrainLit SubShader", "");
+ protected override string subShaderInclude => CoreIncludes.kTerrainLit;
+ protected override string postDecalsInclude => "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitDecalData.hlsl";
+ protected override string raytracingInclude => CoreIncludes.kTerrainRaytracing;
+
+ protected override bool requireSplitLighting => false;
+ protected override bool supportForward => false;
+ protected override bool supportLighting => true;
+ protected override bool supportDistortion => false;
+ protected override bool supportRaytracing => false;
+ protected override bool supportPathtracing => false;
+
+ static readonly GUID kSourceCodeGuid = new GUID("be136c27a7154cd99820c558d8feedb2"); // TerrainLitSubTarget.cs
+
+ private TerrainLitData m_TerrainLitData;
+
+ TerrainLitData IRequiresData.data
+ {
+ get => m_TerrainLitData;
+ set => m_TerrainLitData = value;
+ }
+
+ public TerrainLitData terrainLitData
+ {
+ get => m_TerrainLitData;
+ set => m_TerrainLitData = value;
+ }
+
+ public override void Setup(ref TargetSetupContext context)
+ {
+ context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
+ base.Setup(ref context);
+ }
+
+ protected override IEnumerable EnumerateSubShaders()
+ {
+ yield return PostProcessSubShader(GetSubShaderDescriptor());
+ yield return PostProcessSubShader(GetBaseMapGenSubShaderDescriptor());
+ }
+
+ protected override SubShaderDescriptor GetSubShaderDescriptor()
+ {
+ return new SubShaderDescriptor
+ {
+ generatesPreview = true,
+ customTags = "\"SplatCount\" = \"8\" \"TerrainCompatible\" = \"True\"",
+ passes = GetPasses(),
+ shaderDependencies = GetDependencies(),
+ };
+
+ PassCollection GetPasses()
+ {
+ var passes = new PassCollection()
+ {
+ HDTerrainPasses.GenerateShadowCaster(supportLighting, systemData.tessellation),
+ HDTerrainPasses.GenerateMETA(supportLighting),
+ HDTerrainPasses.GenerateScenePicking(systemData.tessellation),
+ HDTerrainPasses.GenerateSceneSelection(supportLighting, systemData.tessellation),
+ };
+
+ if (supportForward)
+ {
+ passes.Add(HDTerrainPasses.GenerateDepthForwardOnlyPass(supportLighting, systemData.tessellation));
+ passes.Add(HDTerrainPasses.GenerateForwardOnlyPass(supportLighting, systemData.tessellation));
+ }
+
+ passes.Add(HDTerrainPasses.GenerateLitDepthOnly(systemData.tessellation));
+ passes.Add(HDTerrainPasses.GenerateGBuffer(systemData.tessellation));
+ passes.Add(HDTerrainPasses.GenerateLitForward(systemData.tessellation));
+
+ return passes;
+ }
+
+ List GetDependencies()
+ {
+ var dependencyList = new List();
+ dependencyList.Add(TerrainDependencies.BaseMapShader());
+ dependencyList.Add(TerrainDependencies.BaseMapGenShader());
+
+ return dependencyList;
+ }
+ }
+
+ protected override void CollectPassKeywords(ref PassDescriptor pass)
+ {
+ pass.defines.Add(TerrainKeywordDescriptors.TerrainEnabled, 1);
+ pass.keywords.Add(TerrainKeywordDescriptors.TerrainNormalmap);
+ pass.keywords.Add(TerrainKeywordDescriptors.TerrainMaskmap);
+ pass.keywords.Add(TerrainKeywordDescriptors.Terrain8Layers);
+ pass.keywords.Add(TerrainKeywordDescriptors.TerrainSpecularOcclusionNone);
+ pass.keywords.Add(TerrainKeywordDescriptors.TerrainBlendHeight);
+ pass.keywords.Add(CoreKeywordDescriptors.DepthOffset, new FieldCondition(HDFields.DepthOffset, true));
+ pass.keywords.Add(CoreKeywordDescriptors.ConservativeDepthOffset, new FieldCondition(HDFields.ConservativeDepthOffset, true));
+
+ if (pass.displayName == "MainTex" || pass.displayName == "MetallicTex")
+ pass.defines.Add(TerrainKeywordDescriptors.TerrainBaseMapGen, 1);
+ else
+ pass.keywords.Add(TerrainKeywordDescriptors.TerrainInstancedPerPixelNormal);
+
+ pass.defines.Add(TerrainKeywordDescriptors.TerrainAlphaClipEnable, systemData.alphaTest?1:0);
+
+ pass.keywords.Add(CoreKeywordDescriptors.DisableDecals);
+ pass.keywords.Add(CoreKeywordDescriptors.DisableSSR);
+
+ if (pass.lightMode == HDShaderPassNames.s_MotionVectorsStr)
+ pass.keywords.Add(CoreKeywordDescriptors.WriteDecalBufferMotionVector);
+ else if (pass.IsDepthOrMV())
+ pass.keywords.Add(CoreKeywordDescriptors.WriteDecalBufferDepthOnly);
+
+ if (pass.IsLightingOrMaterial())
+ {
+ pass.keywords.Add(CoreKeywordDescriptors.Lightmap);
+ pass.keywords.Add(CoreKeywordDescriptors.DirectionalLightmapCombined);
+ pass.keywords.Add(CoreKeywordDescriptors.ProbeVolumes);
+ pass.keywords.Add(CoreKeywordDescriptors.DynamicLightmap);
+
+ if (!pass.IsRelatedToRaytracing())
+ {
+ pass.keywords.Add(CoreKeywordDescriptors.ShadowsShadowmask);
+ pass.keywords.Add(CoreKeywordDescriptors.Decals);
+ pass.keywords.Add(CoreKeywordDescriptors.DecalSurfaceGradient);
+ }
+ }
+
+ if (pass.IsForward())
+ {
+ pass.keywords.Add(CoreKeywordDescriptors.PunctualShadow);
+ pass.keywords.Add(CoreKeywordDescriptors.DirectionalShadow);
+ pass.keywords.Add(CoreKeywordDescriptors.AreaShadow);
+ pass.keywords.Add(CoreKeywordDescriptors.ScreenSpaceShadow);
+ pass.keywords.Add(CoreKeywordDescriptors.LightList);
+ }
+
+ if (pass.NeedsDebugDisplay())
+ pass.keywords.Add(CoreKeywordDescriptors.DebugDisplay);
+
+ if (pass.lightMode == HDShaderPassNames.s_MotionVectorsStr)
+ {
+ if (supportForward)
+ pass.defines.Add(CoreKeywordDescriptors.WriteNormalBuffer, 1, new FieldCondition(HDFields.Unlit, false));
+ else
+ pass.keywords.Add(CoreKeywordDescriptors.WriteNormalBuffer, new FieldCondition(HDFields.Unlit, false));
+ }
+
+ }
+
+ public override void GetFields(ref TargetFieldContext context)
+ {
+ // Common properties to all Lit master nodes
+ var descs = new HashSet();
+ foreach (var block in context.blocks)
+ {
+ descs.Add(block.descriptor);
+ }
+
+ var pixelBlocks = new HashSet();
+ foreach (var block in context.pass.validPixelBlocks)
+ {
+ pixelBlocks.Add(block);
+ }
+ // Lit specific properties
+ context.AddField(DotsProperties, context.hasDotsProperties);
+
+ // Misc
+ context.AddField(LightingGI, descs.Contains(HDBlockFields.SurfaceDescription.BakedGI) && pixelBlocks.Contains(HDBlockFields.SurfaceDescription.BakedGI));
+ context.AddField(BackLightingGI, descs.Contains(HDBlockFields.SurfaceDescription.BakedBackGI) && pixelBlocks.Contains(HDBlockFields.SurfaceDescription.BakedBackGI));
+ context.AddField(HDFields.AmbientOcclusion, context.blocks.Contains((BlockFields.SurfaceDescription.Occlusion, false)) && pixelBlocks.Contains(BlockFields.SurfaceDescription.Occlusion));
+ context.AddField(HDFields.DepthOffset, builtinData.depthOffset && pixelBlocks.Contains(HDBlockFields.SurfaceDescription.DepthOffset));
+ context.AddField(HDFields.ConservativeDepthOffset, builtinData.conservativeDepthOffset && builtinData.depthOffset && pixelBlocks.Contains(HDBlockFields.SurfaceDescription.DepthOffset));
+ // Depth offset needs positionRWS and is now a multi_compile
+ if (builtinData.depthOffset)
+ context.AddField(HDStructFields.FragInputs.positionRWS);
+
+ // Specular Occlusion Fields
+ context.AddField(SpecularOcclusionFromAO, lightingData.specularOcclusionMode == SpecularOcclusionMode.FromAO);
+ context.AddField(SpecularOcclusionFromAOBentNormal, lightingData.specularOcclusionMode == SpecularOcclusionMode.FromAOAndBentNormal);
+ context.AddField(SpecularOcclusionCustom, lightingData.specularOcclusionMode == SpecularOcclusionMode.Custom);
+ }
+
+ public override void GetActiveBlocks(ref TargetActiveBlockContext context)
+ {
+ // Common block between all "surface" master nodes
+ // Vertex
+ context.AddBlock(BlockFields.VertexDescription.Position);
+
+ // Surface
+ context.AddBlock(BlockFields.SurfaceDescription.BaseColor);
+ context.AddBlock(BlockFields.SurfaceDescription.Emission);
+
+ // Misc
+ context.AddBlock(HDBlockFields.SurfaceDescription.DepthOffset, builtinData.depthOffset);
+
+ context.AddBlock(BlockFields.SurfaceDescription.Metallic);
+
+ context.AddBlock(BlockFields.SurfaceDescription.Smoothness);
+ context.AddBlock(BlockFields.SurfaceDescription.Occlusion);
+
+ context.AddBlock(HDBlockFields.SurfaceDescription.SpecularOcclusion, lightingData.specularOcclusionMode == SpecularOcclusionMode.Custom);
+
+ context.AddBlock(BlockFields.SurfaceDescription.NormalOS, lightingData.normalDropOffSpace == NormalDropOffSpace.Object);
+ context.AddBlock(BlockFields.SurfaceDescription.NormalTS, lightingData.normalDropOffSpace == NormalDropOffSpace.Tangent);
+ context.AddBlock(BlockFields.SurfaceDescription.NormalWS, lightingData.normalDropOffSpace == NormalDropOffSpace.World);
+
+ context.AddBlock(BlockFields.SurfaceDescription.Alpha, systemData.alphaTest);
+ context.AddBlock(BlockFields.SurfaceDescription.AlphaClipThreshold, systemData.alphaTest);
+ }
+
+ public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
+ {
+ collector.AddShaderProperty(new BooleanShaderProperty
+ {
+ value = terrainLitData.enableHeightBlend,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_EnableHeightBlend",
+ displayName = "Enable Height Blend",
+ });
+
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ floatType = FloatType.Slider,
+ value = terrainLitData.heightTransition,
+ hidden = false,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_HeightTransition",
+ displayName = "Height Transition",
+ });
+
+ collector.AddShaderProperty(new BooleanShaderProperty
+ {
+ value = terrainLitData.enableInstancedPerPixelNormal,
+ hidden = false,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_EnableInstancedPerPixelNormal",
+ displayName = "Enable Instanced per Pixel Normal",
+ });
+
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.White,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_TerrainHolesTexture",
+ displayName = "Holes Map (RGB)",
+ });
+
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.White,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_MainTex",
+ displayName = "Albedo",
+ });
+
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.White,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_DefaultWhiteTex",
+ displayName = "DefaultWhiteTex",
+ });
+
+ collector.AddShaderProperty(new ColorShaderProperty()
+ {
+ value = new Color(1.0f, 1.0f, 1.0f, 1.0f),
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.UnityPerMaterial,
+ overrideReferenceName = "_Color",
+ displayName = "Color,"
+ });
+
+ collector.AddShaderProperty(new ColorShaderProperty()
+ {
+ value = new Color(1.0f, 1.0f, 1.0f, 1.0f),
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.UnityPerMaterial,
+ overrideReferenceName = "_EmissionColor",
+ displayName = "Color,"
+ });
+
+ // ShaderGraph only property used to send the RenderQueueType to the material
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ value = (int)systemData.renderQueueType,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_RenderQueueType",
+ });
+
+ //See SG-ADDITIONALVELOCITY-NOTE
+ collector.AddShaderProperty(new BooleanShaderProperty
+ {
+ value = builtinData.addPrecomputedVelocity,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = kAddPrecomputedVelocity,
+ });
+
+ collector.AddShaderProperty(new BooleanShaderProperty
+ {
+ value = builtinData.depthOffset,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = kDepthOffsetEnable
+ });
+
+ collector.AddShaderProperty(new BooleanShaderProperty
+ {
+ value = builtinData.conservativeDepthOffset,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = kConservativeDepthOffsetEnable
+ });
+
+ collector.AddShaderProperty(new BooleanShaderProperty
+ {
+ value = builtinData.transparentWritesMotionVec,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = kTransparentWritingMotionVec
+ });
+
+ collector.AddShaderProperty(new BooleanShaderProperty
+ {
+ value = true,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = kZWrite,
+ });
+
+ collector.AddShaderProperty(new BooleanShaderProperty
+ {
+ value = systemData.transparentZWrite,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = kTransparentZWrite,
+ });
+
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ value = (int)CullMode.Back,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_CullMode",
+ });
+
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ floatType = FloatType.Integer,
+ value = (int)CompareFunction.LessEqual,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_ZTestDepthEqualForOpaque",
+ });
+
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ floatType = FloatType.Default,
+ value = 0.0f,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.Global,
+ overrideReferenceName = "_DstBlend",
+ displayName = "DstBlend",
+ });
+
+ HDSubShaderUtilities.AddStencilShaderProperties(collector, systemData, lightingData, requireSplitLighting, true, supportForward);
+ }
+
+ public override void ProcessPreviewMaterial(Material material)
+ {
+ base.ProcessPreviewMaterial(material);
+
+ material.SetFloat(kReceivesSSR, lightingData.receiveSSR ? 1 : 0);
+ }
+
+ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo)
+ {
+ var gui = new SubTargetPropertiesGUI(context, onChange, registerUndo, systemData, builtinData, lightingData);
+ AddInspectorPropertyBlocks(gui);
+ context.Add(gui);
+ }
+
+ protected override void AddInspectorPropertyBlocks(SubTargetPropertiesGUI blockList)
+ {
+ blockList.AddPropertyBlock(new TerrainLitSurfaceOptionPropertyBlock(SurfaceOptionPropertyBlock.Features.Lit));
+ blockList.AddPropertyBlock(new AdvancedOptionsPropertyBlock());
+ }
+
+
+ #region Structs
+ static class HDTerrainStructs
+ {
+ public static StructDescriptor AttributesMesh = new StructDescriptor()
+ {
+ name = "AttributesMesh",
+ packFields = false,
+ fields = new FieldDescriptor[]
+ {
+ HDStructFields.AttributesMesh.positionOS,
+ HDStructFields.AttributesMesh.normalOS,
+ HDStructFields.AttributesMesh.uv0,
+ HDStructFields.AttributesMesh.color,
+ HDStructFields.AttributesMesh.instanceID,
+ HDStructFields.AttributesMesh.vertexID,
+ }
+ };
+
+ public static StructDescriptor VaryingsMeshToPS = new StructDescriptor()
+ {
+ name = "VaryingsMeshToPS",
+ packFields = true,
+ populateWithCustomInterpolators = true,
+ fields = new FieldDescriptor[]
+ {
+ HDStructFields.VaryingsMeshToPS.positionCS,
+ HDStructFields.VaryingsMeshToPS.positionRWS,
+ HDStructFields.VaryingsMeshToPS.positionPredisplacementRWS,
+ HDStructFields.VaryingsMeshToPS.normalWS,
+ HDStructFields.VaryingsMeshToPS.tangentWS,
+ HDStructFields.VaryingsMeshToPS.texCoord0,
+ HDStructFields.VaryingsMeshToPS.color,
+ HDStructFields.VaryingsMeshToPS.instanceID,
+ }
+ };
+ }
+ #endregion
+
+ #region StructCollections
+ static class TerrainStructCollections
+ {
+ public static StructCollection Basic = new StructCollection
+ {
+ { HDTerrainStructs.AttributesMesh },
+ { HDTerrainStructs.VaryingsMeshToPS },
+ { Structs.VertexDescriptionInputs },
+ { Structs.SurfaceDescriptionInputs },
+ };
+ }
+ #endregion
+
+ #region RequiredFields
+ static class TerrainRequiredFields
+ {
+ public static FieldCollection BasicLighting = new FieldCollection()
+ {
+ HDStructFields.AttributesMesh.positionOS,
+ HDStructFields.AttributesMesh.normalOS,
+ HDStructFields.AttributesMesh.uv0,
+ HDStructFields.FragInputs.positionRWS,
+ HDStructFields.FragInputs.tangentToWorld,
+ HDStructFields.FragInputs.texCoord0,
+ HDStructFields.FragInputs.texCoord1,
+ HDStructFields.FragInputs.texCoord2,
+ };
+ }
+ #endregion
+
+ #region KeywordDescriptors
+ static class TerrainKeywordDescriptors
+ {
+ public static KeywordDescriptor TerrainEnabled = new KeywordDescriptor()
+ {
+ displayName = "HD Terrain",
+ referenceName = "HD_TERRAIN_ENABLED",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ };
+
+ public static KeywordDescriptor TerrainNormalmap = new KeywordDescriptor()
+ {
+ displayName = "Terrain Normal Map",
+ referenceName = "_NORMALMAP",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ };
+
+ public static KeywordDescriptor TerrainMaskmap = new KeywordDescriptor()
+ {
+ displayName = "Terrain Mask Map",
+ referenceName = "_MASKMAP",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ };
+
+ public static KeywordDescriptor Terrain8Layers = new KeywordDescriptor()
+ {
+ displayName = "Terrain 8 Layers",
+ referenceName = "_TERRAIN_8_LAYERS",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ };
+
+ public static KeywordDescriptor TerrainSpecularOcclusionNone = new KeywordDescriptor()
+ {
+ displayName = "Terrain Non Specular Occlusion",
+ referenceName = "_SPECULAR_OCCLUSION_NONE",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ };
+
+ public static KeywordDescriptor TerrainBlendHeight = new KeywordDescriptor()
+ {
+ displayName = "Terrain Blend Height",
+ referenceName = "_TERRAIN_BLEND_HEIGHT",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ };
+
+ public static KeywordDescriptor TerrainBaseMapGen = new KeywordDescriptor()
+ {
+ displayName = "Terrain Base Map Generation",
+ referenceName = "_TERRAIN_BASEMAP_GEN",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ };
+
+ public static readonly KeywordDescriptor TerrainAlphaClipEnable = new KeywordDescriptor()
+ {
+ displayName = "Terrain Alpha Clip Enable",
+ referenceName = "_TERRAIN_SG_ALPHA_CLIP",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ stages = KeywordShaderStage.Fragment,
+ };
+
+ public static KeywordDescriptor TerrainInstancedPerPixelNormal = new KeywordDescriptor()
+ {
+ displayName = "Instanced PerPixel Normal",
+ referenceName = "_TERRAIN_INSTANCED_PERPIXEL_NORMAL",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ };
+ }
+ #endregion
+
+ #region Includes
+ static class TerrainIncludes
+ {
+ public const string kTerrainLitSurfaceData = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitSurfaceData.hlsl";
+ public const string kSplatmap = "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap.hlsl";
+ }
+
+ public static IncludeCollection DepthOnlyIncludes = new IncludeCollection
+ {
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph },
+ { CoreIncludes.kPassPlaceholder, IncludeLocation.Pregraph },
+ { CoreIncludes.CoreUtility },
+ { CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph },
+ { CoreIncludes.kPostDecalsPlaceholder, IncludeLocation.Pregraph },
+ { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph },
+ { TerrainIncludes.kTerrainLitSurfaceData, IncludeLocation.Pregraph },
+ { TerrainIncludes.kSplatmap, IncludeLocation.Pregraph },
+ { CoreIncludes.kPassDepthOnly, IncludeLocation.Postgraph },
+ };
+
+ public static IncludeCollection GBufferIncludes = new IncludeCollection
+ {
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph },
+ { CoreIncludes.kPassPlaceholder, IncludeLocation.Pregraph },
+ { CoreIncludes.CoreUtility },
+ { CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph },
+ { CoreIncludes.kPostDecalsPlaceholder, IncludeLocation.Pregraph },
+ { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph },
+ { TerrainIncludes.kTerrainLitSurfaceData, IncludeLocation.Pregraph },
+ { TerrainIncludes.kSplatmap, IncludeLocation.Pregraph },
+ { CoreIncludes.kPassGBuffer, IncludeLocation.Postgraph },
+ };
+
+ public static IncludeCollection ForwardIncludes = new IncludeCollection
+ {
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph },
+ { CoreIncludes.kLighting, IncludeLocation.Pregraph },
+ { CoreIncludes.kLightLoopDef, IncludeLocation.Pregraph },
+ { CoreIncludes.kPassPlaceholder, IncludeLocation.Pregraph },
+ { CoreIncludes.kLightLoop, IncludeLocation.Pregraph },
+ { CoreIncludes.CoreUtility },
+ { CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph },
+ { CoreIncludes.kPostDecalsPlaceholder, IncludeLocation.Pregraph },
+ { CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph },
+ { TerrainIncludes.kTerrainLitSurfaceData, IncludeLocation.Pregraph },
+ { TerrainIncludes.kSplatmap, IncludeLocation.Pregraph },
+ { CoreIncludes.kPassForward, IncludeLocation.Postgraph },
+ };
+ #endregion
+
+ #region Pragmas
+ static class TerrainPragmas
+ {
+ public static PragmaCollection DotsInstanced = new PragmaCollection
+ {
+ { Pragma.DOTSInstancing },
+ { Pragma.InstancingOptions(new []
+ {
+ InstancingOptions.AssumeUniformScaling,
+ InstancingOptions.NoMatrices,
+ InstancingOptions.NoLightProbe,
+ InstancingOptions.NoLightmap,
+ }) },
+ };
+
+ public static PragmaCollection DotsInstancedEditorSync = new PragmaCollection
+ {
+ { Pragma.DOTSInstancing },
+ { Pragma.EditorSyncCompilation },
+ { Pragma.InstancingOptions(new []
+ {
+ InstancingOptions.AssumeUniformScaling,
+ InstancingOptions.NoMatrices,
+ InstancingOptions.NoLightProbe,
+ InstancingOptions.NoLightmap,
+ }) },
+ };
+ }
+ #endregion
+
+ #region Passes
+ static class HDTerrainPasses
+ {
+ public static readonly KeywordDescriptor AlphaTestOn = new KeywordDescriptor()
+ {
+ displayName = "_ALPHATEST_ON",
+ referenceName = "_ALPHATEST_ON",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.MultiCompile,
+ scope = KeywordScope.Global,
+ };
+
+ private static StructCollection GenerateStructs()
+ {
+ return new StructCollection { TerrainStructCollections.Basic };
+ }
+
+ public static PassDescriptor GenerateShadowCaster(bool supportLighting, bool useTessellation)
+ {
+ return new PassDescriptor()
+ {
+ // Definition
+ displayName = "ShadowCaster",
+ referenceName = "SHADERPASS_SHADOWS",
+ lightMode = "ShadowCaster",
+ useInPreview = false,
+ validPixelBlocks = new BlockFieldDescriptor[]
+ {
+ BlockFields.SurfaceDescription.Alpha, BlockFields.SurfaceDescription.AlphaClipThreshold,
+ HDBlockFields.SurfaceDescription.AlphaClipThresholdShadow,
+ HDBlockFields.SurfaceDescription.DepthOffset,
+ HDBlockFields.SurfaceDescription
+ .DiffusionProfileHash // not used, but keeps the UnityPerMaterial cbuffer identical
+ },
+
+ // Collections
+ structs = GenerateStructs(),
+ requiredFields = CoreRequiredFields.Basic,
+ renderStates = CoreRenderStates.ShadowCaster,
+ pragmas = HDShaderPasses.GeneratePragmas(TerrainPragmas.DotsInstanced, false, useTessellation),
+ defines = HDShaderPasses.GenerateDefines(null, false, useTessellation),
+ keywords = new KeywordCollection() { HDTerrainPasses.AlphaTestOn, },
+ includes = GenerateIncludes(),
+ customInterpolators = CoreCustomInterpolators.Common,
+ };
+
+ IncludeCollection GenerateIncludes()
+ {
+ var includes = new IncludeCollection();
+
+ includes.Add(CoreIncludes.CorePregraph);
+ if (supportLighting)
+ includes.Add(CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPassPlaceholder, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.CoreUtility);
+ if (supportLighting)
+ {
+ includes.Add(CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPostDecalsPlaceholder, IncludeLocation.Pregraph);
+ }
+
+ includes.Add(CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kTerrainLitSurfaceData, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kSplatmap, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPassDepthOnly, IncludeLocation.Postgraph);
+
+ return includes;
+ }
+ }
+
+ public static PassDescriptor GenerateMETA(bool supportLighting)
+ {
+ return new PassDescriptor
+ {
+ // Definition
+ displayName = "META",
+ referenceName = "SHADERPASS_LIGHT_TRANSPORT",
+ lightMode = "META",
+ useInPreview = false,
+
+ // We don't need any vertex inputs on meta pass:
+ validVertexBlocks = new BlockFieldDescriptor[0],
+
+ // Collections
+ structs = GenerateStructs(),
+ requiredFields = CoreRequiredFields.Meta,
+ renderStates = CoreRenderStates.Meta,
+ // Note: no tessellation for meta pass
+ pragmas = HDShaderPasses.GeneratePragmas(TerrainPragmas.DotsInstanced, false, false),
+ defines = HDShaderPasses.GenerateDefines(CoreDefines.ShaderGraphRaytracingDefault, false, false),
+ keywords = new KeywordCollection() { CoreKeywordDescriptors.EditorVisualization, HDTerrainPasses.AlphaTestOn, },
+ includes = GenerateIncludes(),
+ };
+
+ IncludeCollection GenerateIncludes()
+ {
+ var includes = new IncludeCollection();
+
+ includes.Add(CoreIncludes.CorePregraph);
+ if (supportLighting)
+ includes.Add(CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPassPlaceholder, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.CoreUtility);
+ if (supportLighting)
+ {
+ includes.Add(CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPostDecalsPlaceholder, IncludeLocation.Pregraph);
+ }
+ includes.Add(CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kTerrainLitSurfaceData, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kSplatmap, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPassLightTransport, IncludeLocation.Postgraph);
+
+ return includes;
+ }
+ }
+
+ public static PassDescriptor GenerateScenePicking(bool useTessellation)
+ {
+ return new PassDescriptor
+ {
+ // Definition
+ displayName = "ScenePickingPass",
+ referenceName = "SHADERPASS_DEPTH_ONLY",
+ lightMode = "Picking",
+ useInPreview = false,
+
+ // Collections
+ structs = GenerateStructs(),
+ requiredFields = GenerateRequiredFields(),
+ renderStates = CoreRenderStates.ScenePicking,
+ pragmas = HDShaderPasses.GeneratePragmas(TerrainPragmas.DotsInstancedEditorSync, false, useTessellation),
+ defines = HDShaderPasses.GenerateDefines(CoreDefines.ScenePicking, false, useTessellation),
+ keywords = new KeywordCollection() { HDTerrainPasses.AlphaTestOn, },
+ includes = GenerateIncludes(),
+ customInterpolators = CoreCustomInterpolators.Common,
+ };
+
+ FieldCollection GenerateRequiredFields()
+ {
+ var fieldCollection = new FieldCollection();
+
+ fieldCollection.Add(CoreRequiredFields.Basic);
+ fieldCollection.Add(CoreRequiredFields.AddWriteNormalBuffer);
+
+ return fieldCollection;
+ }
+
+ IncludeCollection GenerateIncludes()
+ {
+ var includes = new IncludeCollection();
+
+ includes.Add(CoreIncludes.kPickingSpaceTransforms, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.CorePregraph);
+ includes.Add(CoreIncludes.kPassPlaceholder, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.CoreUtility);
+ includes.Add(CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kTerrainLitSurfaceData, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kSplatmap, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPassDepthOnly, IncludeLocation.Postgraph);
+
+ return includes;
+ }
+ }
+
+ public static PassDescriptor GenerateSceneSelection(bool supportLighting, bool useTessellation)
+ {
+ return new PassDescriptor
+ {
+ // Definition
+ displayName = "SceneSelectionPass",
+ referenceName = "SHADERPASS_DEPTH_ONLY",
+ lightMode = "SceneSelectionPass",
+ useInPreview = false,
+
+ // Collections
+ structs = GenerateStructs(),
+ requiredFields = CoreRequiredFields.Basic,
+ renderStates = CoreRenderStates.SceneSelection,
+ pragmas = HDShaderPasses.GeneratePragmas(TerrainPragmas.DotsInstancedEditorSync, false, useTessellation),
+ defines = HDShaderPasses.GenerateDefines(CoreDefines.SceneSelection, false, useTessellation),
+ keywords = new KeywordCollection() { AlphaTestOn, },
+ includes = GenerateIncludes(),
+ customInterpolators = CoreCustomInterpolators.Common,
+ };
+
+ IncludeCollection GenerateIncludes()
+ {
+ var includes = new IncludeCollection();
+
+ includes.Add(CoreIncludes.kPickingSpaceTransforms, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.CorePregraph);
+ if (supportLighting)
+ includes.Add(CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPassPlaceholder, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.CoreUtility);
+ if (supportLighting)
+ {
+ includes.Add(CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPostDecalsPlaceholder, IncludeLocation.Pregraph);
+ }
+ includes.Add(CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kTerrainLitSurfaceData, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kSplatmap, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPassDepthOnly, IncludeLocation.Postgraph);
+
+ return includes;
+ }
+ }
+
+ public static PassDescriptor GenerateDepthForwardOnlyPass(bool supportLighting, bool useTessellation)
+ {
+ return new PassDescriptor
+ {
+ // Definition
+ displayName = "DepthForwardOnly",
+ referenceName = "SHADERPASS_DEPTH_ONLY",
+ lightMode = "DepthForwardOnly",
+ useInPreview = true,
+
+ // Collections
+ structs = GenerateStructs(),
+ requiredFields = GenerateRequiredFields(),
+ renderStates = GenerateRenderState(),
+ pragmas = HDShaderPasses.GeneratePragmas(TerrainPragmas.DotsInstanced, false, useTessellation),
+ defines = HDShaderPasses.GenerateDefines(supportLighting ? CoreDefines.DepthForwardOnly : CoreDefines.DepthForwardOnlyUnlit, false, useTessellation),
+ keywords = new KeywordCollection() { AlphaTestOn },
+ includes = GenerateIncludes(),
+ customInterpolators = CoreCustomInterpolators.Common,
+ };
+
+ FieldCollection GenerateRequiredFields()
+ {
+ var fieldCollection = new FieldCollection();
+
+ fieldCollection.Add(supportLighting ? TerrainRequiredFields.BasicLighting : CoreRequiredFields.Basic);
+ fieldCollection.Add(CoreRequiredFields.AddWriteNormalBuffer);
+
+ return fieldCollection;
+ }
+
+ RenderStateCollection GenerateRenderState()
+ {
+ var renderState = new RenderStateCollection { CoreRenderStates.DepthOnly };
+ return renderState;
+ }
+
+ IncludeCollection GenerateIncludes()
+ {
+ var includes = new IncludeCollection();
+
+ includes.Add(CoreIncludes.CorePregraph);
+ if (supportLighting)
+ includes.Add(CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPassPlaceholder, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.CoreUtility);
+ if (supportLighting)
+ includes.Add(CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kTerrainLitSurfaceData, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kSplatmap, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPassDepthOnly, IncludeLocation.Postgraph);
+
+ return includes;
+ }
+ }
+
+ public static PassDescriptor GenerateForwardOnlyPass(bool supportLighting, bool useTessellation)
+ {
+ return new PassDescriptor
+ {
+ // Definition
+ displayName = "ForwardOnly",
+ referenceName = supportLighting ? "SHADERPASS_FORWARD" : "SHADERPASS_FORWARD_UNLIT",
+ lightMode = "ForwardOnly",
+ useInPreview = true,
+
+ // Collections
+ structs = GenerateStructs(),
+ // We need motion vector version as Forward pass support transparent motion vector and we can't use ifdef for it
+ requiredFields = supportLighting ? TerrainRequiredFields.BasicLighting : CoreRequiredFields.BasicSurfaceData,
+ renderStates = CoreRenderStates.Forward,
+ pragmas = HDShaderPasses.GeneratePragmas(TerrainPragmas.DotsInstanced, false, useTessellation),
+ defines = HDShaderPasses.GenerateDefines(supportLighting ? CoreDefines.Forward : CoreDefines.ForwardUnlit, false, useTessellation),
+ keywords = new KeywordCollection() { HDTerrainPasses.AlphaTestOn, },
+ includes = GenerateIncludes(),
+
+ virtualTextureFeedback = true,
+ customInterpolators = CoreCustomInterpolators.Common
+ };
+
+ IncludeCollection GenerateIncludes()
+ {
+ var includes = new IncludeCollection();
+
+ includes.Add(CoreIncludes.CorePregraph);
+ if (supportLighting)
+ {
+ includes.Add(CoreIncludes.kNormalSurfaceGradient, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kLighting, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kLightLoopDef, IncludeLocation.Pregraph);
+ }
+ includes.Add(CoreIncludes.kPassPlaceholder, IncludeLocation.Pregraph);
+ if (supportLighting)
+ includes.Add(CoreIncludes.kLightLoop, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.CoreUtility);
+ if (supportLighting)
+ {
+ includes.Add(CoreIncludes.kDecalUtilities, IncludeLocation.Pregraph);
+ includes.Add(CoreIncludes.kPostDecalsPlaceholder, IncludeLocation.Pregraph);
+ }
+ includes.Add(CoreIncludes.kShaderGraphFunctions, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kTerrainLitSurfaceData, IncludeLocation.Pregraph);
+ includes.Add(TerrainIncludes.kSplatmap, IncludeLocation.Pregraph);
+ if (supportLighting)
+ includes.Add(CoreIncludes.kPassForward, IncludeLocation.Postgraph);
+ else
+ includes.Add(CoreIncludes.kPassForwardUnlit, IncludeLocation.Postgraph);
+
+ return includes;
+ }
+ }
+
+ public static PassDescriptor GenerateLitDepthOnly(bool useTessellation)
+ {
+ return new PassDescriptor
+ {
+ displayName = "DepthOnly",
+ referenceName = "SHADERPASS_DEPTH_ONLY",
+ lightMode = "DepthOnly",
+ useInPreview = true,
+
+ // Collections
+ structs = GenerateStructs(),
+ requiredFields = GenerateRequiredFields(),
+ renderStates = CoreRenderStates.DepthOnly,
+ pragmas = HDShaderPasses.GeneratePragmas(TerrainPragmas.DotsInstanced, false, useTessellation),
+ defines = HDShaderPasses.GenerateDefines(CoreDefines.ShaderGraphRaytracingDefault, false, useTessellation),
+ keywords = new KeywordCollection() { CoreKeywordDescriptors.WriteNormalBuffer, HDTerrainPasses.AlphaTestOn, },
+ includes = DepthOnlyIncludes,
+ customInterpolators = CoreCustomInterpolators.Common,
+ };
+
+ FieldCollection GenerateRequiredFields()
+ {
+ var fieldCollection = new FieldCollection();
+
+ fieldCollection.Add(CoreRequiredFields.Basic);
+ fieldCollection.Add(CoreRequiredFields.AddWriteNormalBuffer);
+
+ return fieldCollection;
+ }
+ }
+
+ public static PassDescriptor GenerateGBuffer(bool useTessellation)
+ {
+ return new PassDescriptor
+ {
+ // Definition
+ displayName = "GBuffer",
+ referenceName = "SHADERPASS_GBUFFER",
+ lightMode = "GBuffer",
+ useInPreview = true,
+
+ // Collections
+ structs = GenerateStructs(),
+ requiredFields = TerrainRequiredFields.BasicLighting,
+ renderStates = HDShaderPasses.GBufferRenderState,
+ pragmas = HDShaderPasses.GeneratePragmas(TerrainPragmas.DotsInstanced, false, useTessellation),
+ defines = HDShaderPasses.GenerateDefines(CoreDefines.ShaderGraphRaytracingDefault, false, useTessellation),
+ keywords = new KeywordCollection() { CoreKeywordDescriptors.RenderingLayers, HDTerrainPasses.AlphaTestOn, },
+ includes = GBufferIncludes,
+ virtualTextureFeedback = true,
+ customInterpolators = CoreCustomInterpolators.Common,
+ };
+ }
+
+ public static PassDescriptor GenerateLitForward(bool useTessellation)
+ {
+ return new PassDescriptor
+ {
+ // Definition
+ displayName = "Forward",
+ referenceName = "SHADERPASS_FORWARD",
+ lightMode = "Forward",
+ useInPreview = true,
+
+ // Collections
+ structs = GenerateStructs(),
+ // We need motion vector version as Forward pass support transparent motion vector and we can't use ifdef for it
+ requiredFields = TerrainRequiredFields.BasicLighting,
+ renderStates = CoreRenderStates.Forward,
+ pragmas = HDShaderPasses.GeneratePragmas(TerrainPragmas.DotsInstanced, false, useTessellation),
+ defines = HDShaderPasses.GenerateDefines(CoreDefines.ForwardLit, false, useTessellation),
+ keywords = new KeywordCollection() { HDTerrainPasses.AlphaTestOn, },
+ includes = ForwardIncludes,
+ virtualTextureFeedback = true,
+ customInterpolators = CoreCustomInterpolators.Common,
+ };
+ }
+ }
+ #endregion
+
+ #region Dependencies
+ static class TerrainDependencies
+ {
+ public static ShaderDependency BaseMapShader()
+ {
+ return new ShaderDependency()
+ {
+ dependencyName = "BaseMapShader",
+ shaderName = "Hidden/HDRP/TerrainLit_Basemap",
+ };
+ }
+ public static ShaderDependency BaseMapGenShader()
+ {
+ return new ShaderDependency()
+ {
+ dependencyName = "BaseMapGenShader",
+ shaderName = "Hidden/{Name}_BaseMapGen",
+ };
+ }
+ }
+ #endregion
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.cs.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.cs.meta
new file mode 100644
index 00000000000..bc6d9ed8927
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSubTarget.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 1dc05784b2f63c746a6e1c967f1359b0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSurfaceOptionPropertyBlock.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSurfaceOptionPropertyBlock.cs
new file mode 100644
index 00000000000..4b563d65c10
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSurfaceOptionPropertyBlock.cs
@@ -0,0 +1,56 @@
+using UnityEngine.Rendering.HighDefinition;
+using UnityEngine;
+using UnityEngine.UIElements;
+
+// We share the name of the properties in the UI to avoid duplication
+using static UnityEditor.Rendering.HighDefinition.SurfaceOptionUIBlock.Styles;
+using static UnityEditor.Rendering.HighDefinition.LitSurfaceInputsUIBlock.Styles;
+
+namespace UnityEditor.Rendering.HighDefinition.ShaderGraph
+{
+ class TerrainLitSurfaceOptionPropertyBlock : SurfaceOptionPropertyBlock
+ {
+ class Styles
+ {
+ public static GUIContent fragmentNormalSpace = new GUIContent("Fragment Normal Space", "Select the space use for normal map in Fragment shader in this shader graph.");
+ }
+
+ public TerrainLitSurfaceOptionPropertyBlock(Features features) : base(features)
+ {
+
+ }
+
+ protected override void CreatePropertyGUI()
+ {
+ // properties of opaque type
+ context.globalIndentLevel++;
+ var renderingPassList = HDSubShaderUtilities.GetRenderingPassList(systemData.surfaceType == SurfaceType.Opaque, false); // Show after post process for unlit shaders
+ var renderingPassValue = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.GetOpaqueEquivalent(systemData.renderQueueType) : HDRenderQueue.GetTransparentEquivalent(systemData.renderQueueType);
+ var renderQueueType = systemData.surfaceType == SurfaceType.Opaque ? HDRenderQueue.RenderQueueType.Opaque : HDRenderQueue.RenderQueueType.Transparent;
+ context.AddProperty(renderingPassText, new PopupField(renderingPassList, renderQueueType, HDSubShaderUtilities.RenderQueueName, HDSubShaderUtilities.RenderQueueName) { value = renderingPassValue }, (evt) =>
+ {
+ registerUndo(renderingPassText);
+ if (systemData.TryChangeRenderingPass(evt.newValue))
+ onChange();
+ });
+ context.globalIndentLevel--;
+
+ // Misc
+ AddProperty(Styles.fragmentNormalSpace, () => lightingData.normalDropOffSpace, (newValue) => lightingData.normalDropOffSpace = newValue);
+
+ AddProperty(alphaCutoffEnableText, () => systemData.alphaTest, (newValue) => systemData.alphaTest = newValue);
+
+ AddProperty(depthOffsetEnableText, () => builtinData.depthOffset, (newValue) => builtinData.depthOffset = newValue);
+ if (builtinData.depthOffset)
+ {
+ context.globalIndentLevel++;
+ AddProperty(conservativeDepthOffsetEnableText, () => builtinData.conservativeDepthOffset, (newValue) => builtinData.conservativeDepthOffset = newValue);
+ context.globalIndentLevel--;
+ }
+
+ // Misc Cont.
+ AddProperty(supportDecalsText, () => lightingData.receiveDecals, (newValue) => lightingData.receiveDecals = newValue);
+ AddProperty(receivesSSRText, () => lightingData.receiveSSR, (newValue) => lightingData.receiveSSR = newValue);
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSurfaceOptionPropertyBlock.cs.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSurfaceOptionPropertyBlock.cs.meta
new file mode 100644
index 00000000000..d55ad57714e
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/TerrainLitSurfaceOptionPropertyBlock.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 85639c071465e44419eaba2b6c25b51c
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/Vertex.template.hlsl b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/Vertex.template.hlsl
new file mode 100644
index 00000000000..a284446edbd
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/Vertex.template.hlsl
@@ -0,0 +1,164 @@
+
+VertexDescriptionInputs AttributesMeshToVertexDescriptionInputs(AttributesMesh input)
+{
+ VertexDescriptionInputs output;
+ ZERO_INITIALIZE(VertexDescriptionInputs, output);
+
+ $VertexDescriptionInputs.ObjectSpaceNormal: output.ObjectSpaceNormal = input.normalOS;
+ $VertexDescriptionInputs.WorldSpaceNormal: output.WorldSpaceNormal = TransformObjectToWorldNormal(input.normalOS);
+ $VertexDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = TransformWorldToViewDir(output.WorldSpaceNormal);
+ $VertexDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
+ $VertexDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = input.tangentOS.xyz;
+ $VertexDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = TransformObjectToWorldDir(input.tangentOS.xyz);
+ $VertexDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = TransformWorldToViewDir(output.WorldSpaceTangent);
+ $VertexDescriptionInputs.TangentSpaceTangent: output.TangentSpaceTangent = float3(1.0f, 0.0f, 0.0f);
+ $VertexDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = normalize(cross(input.normalOS.xyz, input.tangentOS.xyz) * (input.tangentOS.w > 0.0f ? 1.0f : -1.0f) * GetOddNegativeScale());
+ $VertexDescriptionInputs.WorldSpaceBiTangent: output.WorldSpaceBiTangent = TransformObjectToWorldDir(output.ObjectSpaceBiTangent);
+ $VertexDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = TransformWorldToViewDir(output.WorldSpaceBiTangent);
+ $VertexDescriptionInputs.TangentSpaceBiTangent: output.TangentSpaceBiTangent = float3(0.0f, 1.0f, 0.0f);
+ $VertexDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = input.positionOS;
+ $VertexDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = TransformObjectToWorld(input.positionOS);
+ $VertexDescriptionInputs.ViewSpacePosition: output.ViewSpacePosition = TransformWorldToView(output.WorldSpacePosition);
+ $VertexDescriptionInputs.TangentSpacePosition: output.TangentSpacePosition = float3(0.0f, 0.0f, 0.0f);
+ $VertexDescriptionInputs.AbsoluteWorldSpacePosition: output.AbsoluteWorldSpacePosition = GetAbsolutePositionWS(TransformObjectToWorld(input.positionOS).xyz);
+ $VertexDescriptionInputs.ObjectSpacePositionPredisplacement: output.ObjectSpacePositionPredisplacement = input.positionOS;
+ $VertexDescriptionInputs.WorldSpacePositionPredisplacement: output.WorldSpacePositionPredisplacement = TransformObjectToWorld(input.positionOS);
+ $VertexDescriptionInputs.ViewSpacePositionPredisplacement: output.ViewSpacePositionPredisplacement = TransformWorldToView(output.WorldSpacePosition);
+ $VertexDescriptionInputs.TangentSpacePositionPredisplacement: output.TangentSpacePositionPredisplacement = float3(0.0f, 0.0f, 0.0f);
+ $VertexDescriptionInputs.AbsoluteWorldSpacePositionPredisplacement: output.AbsoluteWorldSpacePositionPredisplacement = GetAbsolutePositionWS(TransformObjectToWorld(input.positionOS).xyz);
+ $VertexDescriptionInputs.WorldSpaceViewDirection: output.WorldSpaceViewDirection = GetWorldSpaceNormalizeViewDir(output.WorldSpacePosition);
+ $VertexDescriptionInputs.ObjectSpaceViewDirection: output.ObjectSpaceViewDirection = TransformWorldToObjectDir(output.WorldSpaceViewDirection);
+ $VertexDescriptionInputs.ViewSpaceViewDirection: output.ViewSpaceViewDirection = TransformWorldToViewDir(output.WorldSpaceViewDirection);
+ $VertexDescriptionInputs.TangentSpaceViewDirection: float3x3 tangentSpaceTransform = float3x3(output.WorldSpaceTangent,output.WorldSpaceBiTangent,output.WorldSpaceNormal);
+ $VertexDescriptionInputs.TangentSpaceViewDirection: output.TangentSpaceViewDirection = TransformWorldToTangent(output.WorldSpaceViewDirection, tangentSpaceTransform);
+ $VertexDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(output.WorldSpacePosition), _ProjectionParams.x);
+ $VertexDescriptionInputs.NDCPosition: output.NDCPosition = output.ScreenPosition.xy / output.ScreenPosition.w;
+ $VertexDescriptionInputs.PixelPosition: output.PixelPosition = float2(output.NDCPosition.x, 1.0f - output.NDCPosition.y) * _ScreenParams.xy;
+ $VertexDescriptionInputs.uv0: output.uv0 = input.uv0;
+ $VertexDescriptionInputs.uv1: output.uv1 = input.uv1;
+ $VertexDescriptionInputs.uv2: output.uv2 = input.uv2;
+ $VertexDescriptionInputs.uv3: output.uv3 = input.uv3;
+ $VertexDescriptionInputs.VertexColor: output.VertexColor = input.color;
+ $VertexDescriptionInputs.TimeParameters: output.TimeParameters = _TimeParameters.xyz; // Note: in case of animation this will be overwrite (allow to handle motion vector)
+ $VertexDescriptionInputs.BoneWeights: output.BoneWeights = input.weights;
+ $VertexDescriptionInputs.BoneIndices: output.BoneIndices = input.indices;
+ $VertexDescriptionInputs.VertexID: output.VertexID = input.vertexID;
+
+ return output;
+}
+
+VertexDescription GetVertexDescription(AttributesMesh input, float3 timeParameters)
+{
+ // build graph inputs
+ VertexDescriptionInputs vertexDescriptionInputs = AttributesMeshToVertexDescriptionInputs(input);
+ // Override time parameters with used one (This is required to correctly handle motion vector for vertex animation based on time)
+ $VertexDescriptionInputs.TimeParameters: vertexDescriptionInputs.TimeParameters = timeParameters;
+
+ VertexDescription vertexDescription = VertexDescriptionFunction(vertexDescriptionInputs);
+
+ return vertexDescription;
+
+}
+
+// Vertex height displacement
+#ifdef HAVE_MESH_MODIFICATION
+
+UNITY_INSTANCING_BUFFER_START(Terrain)
+UNITY_DEFINE_INSTANCED_PROP(float4, _TerrainPatchInstanceData) // float4(xBase, yBase, skipScale, ~)
+UNITY_INSTANCING_BUFFER_END(Terrain)
+
+float4 ConstructTerrainTangent(float3 normal, float3 positiveZ)
+{
+ // Consider a flat terrain. It should have tangent be (1, 0, 0) and bitangent be (0, 0, 1) as the UV of the terrain grid mesh is a scale of the world XZ position.
+ // In CreateTangentToWorld function (in SpaceTransform.hlsl), it is cross(normal, tangent) * sgn for the bitangent vector.
+ // It is not true in a left-handed coordinate system for the terrain bitangent, if we provide 1 as the tangent.w. It would produce (0, 0, -1) instead of (0, 0, 1).
+ // Also terrain's tangent calculation was wrong in a left handed system because cross((0,0,1), terrainNormalOS) points to the wrong direction as negative X.
+ // Therefore all the 4 xyzw components of the tangent needs to be flipped to correct the tangent frame.
+ // (See TerrainLitData.hlsl - GetSurfaceAndBuiltinData)
+ float3 tangent = cross(normal, positiveZ);
+ return float4(tangent, -1);
+}
+
+AttributesMesh ApplyMeshModification(AttributesMesh input, float3 timeParameters
+#ifdef USE_CUSTOMINTERP_SUBSTRUCT
+ , inout VaryingsMeshToPS varyings
+#endif
+ )
+{
+#ifdef UNITY_INSTANCING_ENABLED
+ float2 patchVertex = input.positionOS.xy;
+ float4 instanceData = UNITY_ACCESS_INSTANCED_PROP(Terrain, _TerrainPatchInstanceData);
+
+ float2 sampleCoords = (patchVertex.xy + instanceData.xy) * instanceData.z; // (xy + float2(xBase,yBase)) * skipScale
+ float height = UnpackHeightmap(_TerrainHeightmapTexture.Load(int3(sampleCoords, 0)));
+
+ input.positionOS.xz = sampleCoords * _TerrainHeightmapScale.xz;
+ input.positionOS.y = height * _TerrainHeightmapScale.y;
+
+ #if defined(ATTRIBUTES_NEED_NORMAL) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)
+ input.normalOS = _TerrainNormalmapTexture.Load(int3(sampleCoords.xy, 0)).rgb * 2.0 - 1.0;
+ #endif
+
+ #ifdef ATTRIBUTES_NEED_TEXCOORD0
+ #ifdef ENABLE_TERRAIN_PERPIXEL_NORMAL
+ input.uv0.xy = sampleCoords;
+ #else
+ input.uv0.xy = sampleCoords * _TerrainHeightmapRecipSize.zw;
+ #endif
+ #endif
+#endif
+
+ VertexDescription vertexDescription = GetVertexDescription(input, timeParameters);
+
+ // copy graph output to the results
+ $VertexDescription.Position: input.positionOS = vertexDescription.Position;
+ $VertexDescription.Normal: input.normalOS = vertexDescription.Normal;
+ $VertexDescription.uv0: input.uv0 = vertexDescription.uv0;
+
+ return input;
+}
+
+#endif // HAVE_MESH_MODIFICATION
+
+FragInputs BuildFragInputs(VaryingsMeshToPS input)
+{
+ FragInputs output;
+ ZERO_INITIALIZE(FragInputs, output);
+
+ // Init to some default value to make the computer quiet (else it output 'divide by zero' warning even if value is not used).
+ // TODO: this is a really poor workaround, but the variable is used in a bunch of places
+ // to compute normals which are then passed on elsewhere to compute other values...
+ output.tangentToWorld = k_identity3x3;
+ output.positionSS = input.positionCS; // input.positionCS is SV_Position
+
+#ifdef ENABLE_TERRAIN_PERPIXEL_NORMAL
+ // it will be reconstructed in fragment stage
+ $FragInputs.tangentToWorld: float3x3 tangentToWorld = k_identity3x3;
+#else
+ $FragInputs.tangentToWorld: float3 normalWS = input.normalWS;
+ $FragInputs.tangentToWorld: float3 normalOS = TransformWorldToObjectNormal(normalWS);
+ $FragInputs.tangentToWorld: float4 tangentOS = ConstructTerrainTangent(normalOS, float3(0.0, 0.0, 1.0));
+ $FragInputs.tangentToWorld: float4 tangentWS = float4(TransformObjectToWorldNormal(tangentOS.xyz), 0.0);
+ $FragInputs.tangentToWorld: float3x3 tangentToWorld = BuildTangentToWorld(tangentWS, normalWS);
+#endif
+
+ $FragInputs.positionRWS: output.positionRWS = input.positionRWS;
+ $FragInputs.positionPixel: output.positionPixel = input.positionCS.xy; // NOTE: this is not actually in clip space, it is the VPOS pixel coordinate value
+ $FragInputs.positionPredisplacementRWS: output.positionPredisplacementRWS = input.positionPredisplacementRWS;
+ $FragInputs.tangentToWorld: output.tangentToWorld = tangentToWorld;
+ $FragInputs.texCoord0: output.texCoord0 = input.texCoord0;
+ $FragInputs.color: output.color = input.color;
+
+ // splice point to copy custom interpolator fields from varyings to frag inputs
+ $splice(CustomInterpolatorVaryingsToFragInputs)
+
+ return output;
+}
+
+// existing HDRP code uses the combined function to go directly from packed to frag inputs
+FragInputs UnpackVaryingsMeshToFragInputs(PackedVaryingsMeshToPS input)
+{
+ UNITY_SETUP_INSTANCE_ID(input);
+ VaryingsMeshToPS unpacked = UnpackVaryingsMeshToPS(input);
+ return BuildFragInputs(unpacked);
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/Vertex.template.hlsl.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/Vertex.template.hlsl.meta
new file mode 100644
index 00000000000..f8c7f5d988c
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/ShaderGraph/Vertex.template.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 9c4aebecece9d9b46b4035f7ea38e219
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/TerrainLitGUI.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/TerrainLitGUI.cs
index 4d47228f8ab..c7032292bbb 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/TerrainLitGUI.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/TerrainLit/TerrainLitGUI.cs
@@ -15,7 +15,7 @@ namespace UnityEditor.Rendering.HighDefinition
///
class TerrainLitGUI : HDShaderGUI, ITerrainLayerCustomUI
{
- const SurfaceOptionUIBlock.Features surfaceOptionFeatures = SurfaceOptionUIBlock.Features.Unlit | SurfaceOptionUIBlock.Features.ReceiveDecal;
+ const SurfaceOptionUIBlock.Features surfaceOptionFeatures = SurfaceOptionUIBlock.Features.Unlit | SurfaceOptionUIBlock.Features.ReceiveDecal | SurfaceOptionUIBlock.Features.AlphaCutoff;
const AdvancedOptionsUIBlock.Features advancedOptionsFeatures = AdvancedOptionsUIBlock.Features.Instancing | AdvancedOptionsUIBlock.Features.SpecularOcclusion;
[Flags]
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainLitShaderGraphGUI.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainLitShaderGraphGUI.cs
new file mode 100644
index 00000000000..b0b7ddb2246
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainLitShaderGraphGUI.cs
@@ -0,0 +1,38 @@
+using UnityEngine;
+using UnityEngine.Rendering.HighDefinition;
+
+namespace UnityEditor.Rendering.HighDefinition
+{
+ ///
+ /// Material GUI for TerrainLit ShaderGraph
+ ///
+ internal class TerrainLitShaderGraphGUI : HDShaderGUI, ITerrainLayerCustomUI
+ {
+ const SurfaceOptionUIBlock.Features surfaceOptionFeatures = SurfaceOptionUIBlock.Features.Unlit | SurfaceOptionUIBlock.Features.ReceiveDecal | SurfaceOptionUIBlock.Features.AlphaCutoff;
+ const AdvancedOptionsUIBlock.Features advancedOptionsFeatures = AdvancedOptionsUIBlock.Features.Instancing;
+
+ protected MaterialUIBlockList uiBlocks = new MaterialUIBlockList
+ {
+ new SurfaceOptionUIBlock(MaterialUIBlock.ExpandableBit.Base, features: surfaceOptionFeatures),
+ new TerrainSurfaceOptionsUIBlock(MaterialUIBlock.ExpandableBit.Other),
+ new ShaderGraphUIBlock(MaterialUIBlock.ExpandableBit.ShaderGraph),
+ new AdvancedOptionsUIBlock(MaterialUIBlock.ExpandableBit.Advance, features: advancedOptionsFeatures),
+ };
+
+ protected override void OnMaterialGUI(MaterialEditor materialEditor, MaterialProperty[] props)
+ {
+ uiBlocks.OnGUI(materialEditor, props);
+ }
+
+ bool ITerrainLayerCustomUI.OnTerrainLayerGUI(TerrainLayer terrainLayer, Terrain terrain)
+ {
+ var terrainSurfaceOptions = uiBlocks.FetchUIBlock();
+ if (terrainSurfaceOptions == null)
+ return false;
+
+ return terrainSurfaceOptions.OnTerrainLayerGUI(terrainLayer, terrain);
+ }
+
+ public override void ValidateMaterial(Material material) => TerrainLitAPI.ValidateMaterial(material);
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainLitShaderGraphGUI.cs.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainLitShaderGraphGUI.cs.meta
new file mode 100644
index 00000000000..bcbf3af9f89
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainLitShaderGraphGUI.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 4e823842cc0481e478a071f23ae555ab
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainSurfaceOptionsUIBlock.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainSurfaceOptionsUIBlock.cs
new file mode 100644
index 00000000000..0c11f91ad27
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainSurfaceOptionsUIBlock.cs
@@ -0,0 +1,310 @@
+using System;
+using System.Collections.Generic;
+using UnityEngine;
+using UnityEngine.Experimental.Rendering;
+using UnityEngine.Rendering.HighDefinition;
+
+namespace UnityEditor.Rendering.HighDefinition
+{
+ ///
+ /// The UI block that represents the sorting inputs for terrain lit materials.
+ ///
+ public class TerrainSurfaceOptionsUIBlock : MaterialUIBlock
+ {
+ [Flags]
+ internal enum Expandable
+ {
+ Terrain = 1 << 1,
+ }
+
+ internal enum HeightParametrization
+ {
+ Amplitude,
+ MinMax
+ };
+
+ internal class Styles
+ {
+ public static GUIContent optionText { get; } = EditorGUIUtility.TrTextContent("Terrain Options");
+ public static readonly GUIContent enableHeightBlend = new GUIContent("Enable Height-based Blend", "Blend terrain layers based on height values.");
+ public static readonly GUIContent heightTransition = new GUIContent("Height Transition", "Size in world units of the smooth transition between layers.");
+ public static readonly GUIContent enableInstancedPerPixelNormal = new GUIContent("Enable Per-pixel Normal", "Enable per-pixel normal when the terrain uses instanced rendering.");
+
+ public static readonly GUIContent diffuseTexture = new GUIContent("Diffuse");
+ public static readonly GUIContent colorTint = new GUIContent("Color Tint");
+ public static readonly GUIContent opacityAsDensity = new GUIContent("Opacity as Density", "Enable Density Blend");
+ public static readonly GUIContent normalMapTexture = new GUIContent("Normal Map");
+ public static readonly GUIContent normalScale = new GUIContent("Normal Scale");
+ public static readonly GUIContent maskMapTexture = new GUIContent("Mask", "R: Metallic\nG: Ambient Occlusion\nB: Height\nA: Smoothness.");
+ public static readonly GUIContent maskMapTextureWithoutHeight = new GUIContent("Mask Map", "R: Metallic\nG: Ambient Occlusion\nA: Smoothness.");
+ public static readonly GUIContent channelRemapping = new GUIContent("Channel Remapping");
+ public static readonly GUIContent defaultValues = new GUIContent("Channel Default Values");
+ public static readonly GUIContent metallic = new GUIContent("R: Metallic");
+ public static readonly GUIContent ao = new GUIContent("G: AO");
+ public static readonly GUIContent height = new GUIContent("B: Height", "Specifies the Height Map for this Material.");
+ public static readonly GUIContent heightParametrization = new GUIContent("Parametrization", "Specifies the parametrization method for the Height Map.");
+ public static readonly GUIContent heightAmplitude = new GUIContent("Amplitude", "Sets the amplitude of the Height Map (in centimeters).");
+ public static readonly GUIContent heightBase = new GUIContent("Base", "Controls the base of the Height Map (between 0 and 1).");
+ public static readonly GUIContent heightMin = new GUIContent("Min", "Sets the minimum value in the Height Map (in centimeters).");
+ public static readonly GUIContent heightMax = new GUIContent("Max", "Sets the maximum value in the Height Map (in centimeters).");
+ public static readonly GUIContent heightCm = new GUIContent("B: Height (cm)");
+ public static readonly GUIContent smoothness = new GUIContent("A: Smoothness");
+ }
+
+ private MaterialProperty enableHeightBlend = null;
+ private MaterialProperty heightTransition = null;
+ private MaterialProperty enableInstancedPerPixelNormal = null;
+
+ private bool m_ShowChannelRemapping = false;
+ private HeightParametrization m_HeightParametrization = HeightParametrization.Amplitude;
+
+ ///
+ /// Constructs the TerrainSurfaceOptionsUIBlock based on the parameters.
+ ///
+ /// Bit index used to store the foldout state.
+ public TerrainSurfaceOptionsUIBlock(ExpandableBit expandableBit) : base(expandableBit, Styles.optionText)
+ {
+
+ }
+
+ ///
+ /// Loads the material properties for the block.
+ ///
+ public override void LoadMaterialProperties()
+ {
+ FindTerrainLitProperties(properties);
+ }
+
+ ///
+ /// Renders the properties in the block.
+ ///
+ protected override void OnGUIOpen()
+ {
+ if (enableHeightBlend != null)
+ {
+ materialEditor.ShaderProperty(enableHeightBlend, Styles.enableHeightBlend);
+ if (enableHeightBlend.floatValue > 0)
+ {
+ EditorGUI.indentLevel++;
+ materialEditor.ShaderProperty(heightTransition, Styles.heightTransition);
+ EditorGUI.indentLevel--;
+ }
+ }
+
+ if (enableInstancedPerPixelNormal != null)
+ {
+ EditorGUI.BeginDisabledGroup(!materialEditor.IsInstancingEnabled());
+ materialEditor.ShaderProperty(enableInstancedPerPixelNormal, Styles.enableInstancedPerPixelNormal);
+ EditorGUI.EndDisabledGroup();
+ }
+ }
+
+ ///
+ /// Renders the properties for terrain layers in the block.
+ ///
+ /// Terray Layer.
+ /// Terrain.
+ /// True if it has any masks and processed the inspector to show properties.
+ public bool OnTerrainLayerGUI(TerrainLayer terrainLayer, Terrain terrain)
+ {
+ var terrainLayers = terrain.terrainData.terrainLayers;
+ if (!DoesTerrainUseMaskMaps(terrainLayers))
+ return false;
+
+ // Don't use the member field enableHeightBlend as ShaderGUI.OnGUI might not be called if the material UI is folded.
+ bool heightBlend =
+ terrain.materialTemplate.HasProperty(HDMaterialProperties.kEnableHeightBlend) &&
+ terrain.materialTemplate.GetFloat(HDMaterialProperties.kEnableHeightBlend) > 0;
+
+ terrainLayer.diffuseTexture = EditorGUILayout.ObjectField(Styles.diffuseTexture, terrainLayer.diffuseTexture, typeof(Texture2D), false) as Texture2D;
+ TerrainLayerUtility.ValidateDiffuseTextureUI(terrainLayer.diffuseTexture);
+
+ var diffuseRemapMin = terrainLayer.diffuseRemapMin;
+ var diffuseRemapMax = terrainLayer.diffuseRemapMax;
+ EditorGUI.BeginChangeCheck();
+
+ bool enableDensity = false;
+ if (terrainLayer.diffuseTexture != null)
+ {
+ var rect = GUILayoutUtility.GetLastRect();
+ rect.y += 16 + 4;
+ rect.width = EditorGUIUtility.labelWidth + 64;
+ rect.height = 16;
+
+ ++EditorGUI.indentLevel;
+
+ var diffuseTint = new Color(diffuseRemapMax.x, diffuseRemapMax.y, diffuseRemapMax.z);
+ diffuseTint = EditorGUI.ColorField(rect, Styles.colorTint, diffuseTint, true, false, false);
+ diffuseRemapMax.x = diffuseTint.r;
+ diffuseRemapMax.y = diffuseTint.g;
+ diffuseRemapMax.z = diffuseTint.b;
+ diffuseRemapMin.x = diffuseRemapMin.y = diffuseRemapMin.z = 0;
+
+ if (!heightBlend)
+ {
+ rect.y = rect.yMax + 2;
+ enableDensity = EditorGUI.Toggle(rect, Styles.opacityAsDensity, diffuseRemapMin.w > 0);
+ }
+
+ --EditorGUI.indentLevel;
+ }
+ diffuseRemapMax.w = 1;
+ diffuseRemapMin.w = enableDensity ? 1 : 0;
+
+ if (EditorGUI.EndChangeCheck())
+ {
+ terrainLayer.diffuseRemapMin = diffuseRemapMin;
+ terrainLayer.diffuseRemapMax = diffuseRemapMax;
+ }
+
+ terrainLayer.normalMapTexture = EditorGUILayout.ObjectField(Styles.normalMapTexture, terrainLayer.normalMapTexture, typeof(Texture2D), false) as Texture2D;
+ TerrainLayerUtility.ValidateNormalMapTextureUI(terrainLayer.normalMapTexture, TerrainLayerUtility.CheckNormalMapTextureType(terrainLayer.normalMapTexture));
+
+ if (terrainLayer.normalMapTexture != null)
+ {
+ var rect = GUILayoutUtility.GetLastRect();
+ rect.y += 16 + 4;
+ rect.width = EditorGUIUtility.labelWidth + 64;
+ rect.height = 16;
+
+ ++EditorGUI.indentLevel;
+ terrainLayer.normalScale = EditorGUI.FloatField(rect, Styles.normalScale, terrainLayer.normalScale);
+ --EditorGUI.indentLevel;
+ }
+
+ terrainLayer.maskMapTexture = EditorGUILayout.ObjectField(heightBlend ? Styles.maskMapTexture : Styles.maskMapTextureWithoutHeight, terrainLayer.maskMapTexture, typeof(Texture2D), false) as Texture2D;
+ TerrainLayerUtility.ValidateMaskMapTextureUI(terrainLayer.maskMapTexture);
+
+ var maskMapRemapMin = terrainLayer.maskMapRemapMin;
+ var maskMapRemapMax = terrainLayer.maskMapRemapMax;
+ var smoothness = terrainLayer.smoothness;
+ var metallic = terrainLayer.metallic;
+
+ ++EditorGUI.indentLevel;
+ EditorGUI.BeginChangeCheck();
+
+ m_ShowChannelRemapping = EditorGUILayout.Foldout(m_ShowChannelRemapping, terrainLayer.maskMapTexture != null ? Styles.channelRemapping : Styles.defaultValues);
+ if (m_ShowChannelRemapping)
+ {
+ if (terrainLayer.maskMapTexture != null)
+ {
+ float min, max;
+ min = maskMapRemapMin.x; max = maskMapRemapMax.x;
+ EditorGUILayout.MinMaxSlider(Styles.metallic, ref min, ref max, 0, 1);
+ maskMapRemapMin.x = min; maskMapRemapMax.x = max;
+
+ min = maskMapRemapMin.y; max = maskMapRemapMax.y;
+ EditorGUILayout.MinMaxSlider(Styles.ao, ref min, ref max, 0, 1);
+ maskMapRemapMin.y = min; maskMapRemapMax.y = max;
+
+ if (heightBlend)
+ {
+ EditorGUILayout.LabelField(Styles.height);
+ ++EditorGUI.indentLevel;
+ m_HeightParametrization = (HeightParametrization)EditorGUILayout.EnumPopup(Styles.heightParametrization, m_HeightParametrization);
+ if (m_HeightParametrization == HeightParametrization.Amplitude)
+ {
+ // (height - heightBase) * amplitude
+ float amplitude = Mathf.Max(maskMapRemapMax.z - maskMapRemapMin.z, Mathf.Epsilon); // to avoid divide by zero
+ float heightBase = -maskMapRemapMin.z / amplitude;
+ amplitude = EditorGUILayout.FloatField(Styles.heightAmplitude, amplitude * 100) / 100;
+ heightBase = EditorGUILayout.Slider(Styles.heightBase, heightBase, 0.0f, 1.0f);
+ maskMapRemapMin.z = -heightBase * amplitude;
+ maskMapRemapMax.z = (1 - heightBase) * amplitude;
+ }
+ else
+ {
+ maskMapRemapMin.z = EditorGUILayout.FloatField(Styles.heightMin, maskMapRemapMin.z * 100) / 100;
+ maskMapRemapMax.z = EditorGUILayout.FloatField(Styles.heightMax, maskMapRemapMax.z * 100) / 100;
+ }
+ --EditorGUI.indentLevel;
+ }
+
+ min = maskMapRemapMin.w; max = maskMapRemapMax.w;
+ EditorGUILayout.MinMaxSlider(Styles.smoothness, ref min, ref max, 0, 1);
+ maskMapRemapMin.w = min; maskMapRemapMax.w = max;
+ }
+ else
+ {
+ metallic = EditorGUILayout.Slider(Styles.metallic, metallic, 0, 1);
+ // AO and Height are still exclusively controlled via the maskRemap controls
+ // metallic and smoothness have their own values as fields within the LayerData.
+ maskMapRemapMax.y = EditorGUILayout.Slider(Styles.ao, maskMapRemapMax.y, 0, 1);
+
+ if (heightBlend)
+ {
+ maskMapRemapMax.z = EditorGUILayout.FloatField(Styles.heightCm, maskMapRemapMax.z * 100) / 100;
+ }
+ // There's a possibility that someone could slide max below the existing min value
+ // so we'll just protect against that by locking the min value down a little bit.
+ // In the case of height (Z), we are trying to set min to no lower than zero value unless
+ // max goes negative. Zero is a good sensible value for the minimum. For AO (Y), we
+ // don't need this extra protection step because the UI blocks us from going negative
+ // anyway. In both cases, pushing the slider below the min value will lock them together,
+ // but min will be "left behind" if you go back up.
+ maskMapRemapMin.y = Mathf.Min(maskMapRemapMin.y, maskMapRemapMax.y);
+ maskMapRemapMin.z = Mathf.Min(Mathf.Max(0, maskMapRemapMin.z), maskMapRemapMax.z);
+
+ if (TextureHasAlpha(terrainLayer.diffuseTexture))
+ {
+ GUIStyle warnStyle = new GUIStyle(GUI.skin.label);
+ warnStyle.wordWrap = true;
+ GUILayout.Label("Smoothness is controlled by diffuse alpha channel", warnStyle);
+ }
+ else
+ smoothness = EditorGUILayout.Slider(Styles.smoothness, smoothness, 0, 1);
+ }
+ }
+
+ if (EditorGUI.EndChangeCheck())
+ {
+ terrainLayer.maskMapRemapMin = maskMapRemapMin;
+ terrainLayer.maskMapRemapMax = maskMapRemapMax;
+ terrainLayer.smoothness = smoothness;
+ terrainLayer.metallic = metallic;
+ }
+ --EditorGUI.indentLevel;
+
+ EditorGUILayout.Space();
+ TerrainLayerUtility.TilingSettingsUI(terrainLayer);
+
+ return true;
+ }
+
+ private static bool DoesTerrainUseMaskMaps(TerrainLayer[] terrainLayers)
+ {
+ for (int i = 0; i < terrainLayers.Length; ++i)
+ {
+ if (terrainLayers[i].maskMapTexture != null)
+ return true;
+ }
+
+ return false;
+ }
+
+ private static bool TextureHasAlpha(Texture2D inTex)
+ {
+ if (inTex == null)
+ return false;
+
+ return GraphicsFormatUtility.HasAlphaChannel(GraphicsFormatUtility.GetGraphicsFormat(inTex.format, true));
+ }
+
+ ///
+ /// Find the properties of terrain in the block.
+ ///
+ /// The list of properties in the inspected material(s).
+ protected void FindTerrainLitProperties(MaterialProperty[] props)
+ {
+ foreach (var prop in props)
+ {
+ if (prop.name == HDMaterialProperties.kEnableHeightBlend)
+ enableHeightBlend = prop;
+ else if (prop.name == HDMaterialProperties.kHeightTransition)
+ heightTransition = prop;
+ else if (prop.name == HDMaterialProperties.kEnableInstancedPerPixelNormal)
+ enableInstancedPerPixelNormal = prop;
+ }
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainSurfaceOptionsUIBlock.cs.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainSurfaceOptionsUIBlock.cs.meta
new file mode 100644
index 00000000000..296d1033eb5
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Material/UIBlocks/TerrainSurfaceOptionsUIBlock.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: d6ff0ab5d9aba734390e2d665cc03ab2
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ScreenSpaceLensFlareEditor.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ScreenSpaceLensFlareEditor.cs
index e7b9023d6ed..e153e49ac45 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ScreenSpaceLensFlareEditor.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/PostProcessing/ScreenSpaceLensFlareEditor.cs
@@ -79,7 +79,7 @@ public override void OnEnable()
public override void OnInspectorGUI()
{
// We loop through each camera and displaying a message if there's any bloom intensity = 0 preventing lens flare to render.
- HDEditorUtils.EnsureVolume((Bloom bloom) => !bloom.IsActive() ? "One or more Bloom override has an intensity set to 0. This prevents Screen Space Lens Flare to render." : null);
+ HDEditorUtils.EnsureVolume((Bloom bloom) => !bloom.IsActive() ? "Screen Space Lens Flare cannot render properly because Bloom override intensity property in the Volume System is either set to zero or the current camera is currently not rendering." : null);
HDEditorUtils.EnsureFrameSetting(FrameSettingsField.LensFlareScreenSpace);
if (!HDRenderPipeline.currentAsset?.currentPlatformRenderPipelineSettings.supportScreenSpaceLensFlare ?? false)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/PostProcessing/Templates/CustomPostProcessingShader.template b/Packages/com.unity.render-pipelines.high-definition/Editor/PostProcessing/Templates/CustomPostProcessingShader.template
index 0a339966683..9d18cfde76d 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/PostProcessing/Templates/CustomPostProcessingShader.template
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/PostProcessing/Templates/CustomPostProcessingShader.template
@@ -9,7 +9,7 @@ Shader "Hidden/Shader/#SCRIPTNAME#"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Rendering.Drawers.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Rendering.Drawers.cs
index 2c90c94b564..12dfbfd4568 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Rendering.Drawers.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Camera/HDCameraUI.Rendering.Drawers.cs
@@ -122,7 +122,7 @@ static void Drawer_Rendering_AllowDynamicResolution(SerializedHDCamera p, Editor
static void Drawer_Draw_DLSS_Section(SerializedHDCamera p, Editor owner)
{
EditorGUI.indentLevel++;
- bool isDLSSEnabledInQualityAsset = HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.Contains(UnityEngine.Rendering.AdvancedUpscalers.DLSS);
+ bool isDLSSEnabledInQualityAsset = HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.Contains("DLSS");
EditorGUILayout.PropertyField(p.allowDeepLearningSuperSampling, Styles.DLSSAllow);
if (!isDLSSEnabledInQualityAsset && p.allowDeepLearningSuperSampling.boolValue)
@@ -170,7 +170,7 @@ static void Drawer_Draw_DLSS_Section(SerializedHDCamera p, Editor owner)
static void Drawer_Draw_FSR2_Section(SerializedHDCamera p, Editor owner)
{
EditorGUI.indentLevel++;
- bool isFSR2EnabledInQualityAsset = HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.Contains(UnityEngine.Rendering.AdvancedUpscalers.FSR2);
+ bool isFSR2EnabledInQualityAsset = HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.Contains("FSR2");
EditorGUILayout.PropertyField(p.allowFidelityFX2SuperResolution, Styles.FSR2Allow);
@@ -250,7 +250,7 @@ static void Drawer_Rendering_Antialiasing(SerializedHDCamera p, Editor owner)
bool showAntialiasContentAsFallback = false;
#if ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
- bool isDLSSEnabled = HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.Contains(UnityEngine.Rendering.AdvancedUpscalers.DLSS)
+ bool isDLSSEnabled = HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.Contains("DLSS")
&& p.allowDeepLearningSuperSampling.boolValue;
showAntialiasContentAsFallback = isDLSSEnabled;
#endif
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassFullScreenShader.shadergraph.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassFullScreenShader.shadergraph.meta
index 096513879e9..f90b62c0e26 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassFullScreenShader.shadergraph.meta
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassFullScreenShader.shadergraph.meta
@@ -8,3 +8,17 @@ ScriptedImporter:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 625f186215c104763be7675aa2d941aa, type: 3}
+ useAsTemplate: 1
+ exposeTemplateAsShader: 1
+ template:
+ name: Fullscreen (Empty) - HDRP
+ category: Image Processing
+ description: "An HDRP Shader Graph template that does nothing, ready for editing.\r\n\r\nFullscreen
+ shaders are intended to be used to apply image adjustments for applications
+ like post-process filters. They are not intended to be applied to individual
+ meshes.\r\n\r\nTo apply a fullscreen shader as a post-process filter, create
+ a Custom Pass Volume, add a Fullscreen Custom Pass and assign a material created
+ from your fullscreen shader.\r\n\nSupported Pipeline(s): HDRP\r\nActive
+ Target: Fullscreen\r\nVFX Graph Support: disabled\r"
+ icon: {instanceID: 0}
+ thumbnail: {fileID: 2800000, guid: 735f538caff1db74f943ce9ea87633e9, type: 3}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassFullScreenShader.template b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassFullScreenShader.template
index a8247cd31bf..66e2f62ba26 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassFullScreenShader.template
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassFullScreenShader.template
@@ -5,7 +5,7 @@ Shader "FullScreen/#SCRIPTNAME#"
#pragma vertex Vert
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassCommon.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassRenderersShader.template b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassRenderersShader.template
index d06752bddf3..aedd36d7d7b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassRenderersShader.template
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/CustomPassRenderersShader.template
@@ -13,7 +13,7 @@ Shader "Renderers/#SCRIPTNAME#"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/FullScreenCustomPassDrawer.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/FullScreenCustomPassDrawer.cs
index d73c6c1c89f..dd98fddee89 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/FullScreenCustomPassDrawer.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/CustomPass/FullScreenCustomPassDrawer.cs
@@ -9,6 +9,7 @@
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor.ShaderGraph;
+using UnityEditor.RenderPipelines.Core;
namespace UnityEditor.Rendering.HighDefinition
{
@@ -34,44 +35,12 @@ private class Styles
public readonly static string stencilHelpInfo = $"Stencil is enabled on the material. To help you configure the stencil operations, use these values for the bits available in HDRP: User Bit 0: {(int)UserStencilUsage.UserBit0} User Bit 1: {(int)UserStencilUsage.UserBit1}";
}
- class CreateFullscreenMaterialAction : ProjectWindowCallback.EndNameEditAction
- {
- public bool createShaderGraphShader; // TODO
- public FullScreenCustomPass customPass;
-
- static Regex s_ShaderNameRegex = new(@"(Material$|Mat$)", RegexOptions.IgnoreCase);
+ static readonly string k_NewShaderText = "HDRP Fullscreen Shader";
+ static readonly string k_NewShaderGraphText = "Fullscreen ShaderGraph";
- public override void Action(int instanceId, string pathName, string resourceFile)
- {
- string fileName = Path.GetFileNameWithoutExtension(pathName);
- string directoryName = Path.GetDirectoryName(pathName);
- // Clean up name to create shader file:
- var shaderName = s_ShaderNameRegex.Replace(fileName, "") + "Shader";
- shaderName += createShaderGraphShader ? "." + ShaderGraphImporter.Extension : ".shader";
- string shaderPath = Path.Combine(directoryName, shaderName);
- shaderPath = AssetDatabase.GenerateUniqueAssetPath(shaderPath);
- pathName = AssetDatabase.GenerateUniqueAssetPath(pathName);
-
- string templateFolder = $"{HDUtils.GetHDRenderPipelinePath()}/Editor/RenderPipeline/CustomPass";
- string templatePath = createShaderGraphShader ? $"{templateFolder}/CustomPassFullScreenShader.shadergraph" : $"{templateFolder}/CustomPassFullScreenShader.template";
-
- // Load template code and replace shader name with current file name
- string templateCode = File.ReadAllText(templatePath);
- templateCode = templateCode.Replace("#SCRIPTNAME#", fileName);
- File.WriteAllText(shaderPath, templateCode);
-
- AssetDatabase.Refresh();
- AssetDatabase.ImportAsset(shaderPath);
- var shader = AssetDatabase.LoadAssetAtPath(shaderPath);
- shader.name = Path.GetFileName(pathName);
- var material = new Material(shader);
-
- customPass.fullscreenPassMaterial = material;
-
- AssetDatabase.CreateAsset(material, pathName);
- ProjectWindowUtil.ShowCreatedAsset(material);
- }
- }
+ static readonly string k_TemplateFolder = $"{HDUtils.GetHDRenderPipelinePath()}/Editor/RenderPipeline/CustomPass";
+ static readonly string k_ShaderGraphTemplatePath = $"{k_TemplateFolder}/CustomPassFullScreenShader.shadergraph";
+ static readonly string k_shaderTemplatePath = $"{k_TemplateFolder}/CustomPassFullScreenShader.template";
// Fullscreen pass
SerializedProperty m_FullScreenPassMaterial;
@@ -84,7 +53,7 @@ public override void Action(int instanceId, string pathName, string resourceFile
bool m_ShowStencilInfoBox = false;
static readonly float k_NewMaterialButtonWidth = 60;
- static readonly string k_DefaultMaterialName = "New FullScreen Material.mat";
+ static readonly string k_DefaultMaterialName = "New FullScreen Material";
CustomPass.TargetBuffer targetColorBuffer => (CustomPass.TargetBuffer)m_TargetColorBuffer.intValue;
CustomPass.TargetBuffer targetDepthBuffer => (CustomPass.TargetBuffer)m_TargetDepthBuffer.intValue;
@@ -114,8 +83,7 @@ protected override void DoPassGUI(SerializedProperty customPass, Rect rect)
Rect materialField = rect;
Rect newMaterialField = rect;
- if (m_FullScreenPassMaterial.objectReferenceValue == null)
- materialField.xMax -= k_NewMaterialButtonWidth;
+ materialField.xMax -= k_NewMaterialButtonWidth;
newMaterialField.xMin += materialField.width;
EditorGUI.PropertyField(materialField, m_FullScreenPassMaterial, Styles.fullScreenPassMaterial);
rect.y += Styles.defaultLineSpace;
@@ -177,35 +145,52 @@ protected override void DoPassGUI(SerializedProperty customPass, Rect rect)
}
}
}
- else if (m_FullScreenPassMaterial.objectReferenceValue == null)
- {
- // null material, show the button to create a new material & associated shaders
- ShowNewMaterialButton(newMaterialField);
- }
+ ShowNewMaterialButton(newMaterialField, customPass.serializedObject);
}
- void ShowNewMaterialButton(Rect buttonRect)
+ void ShowNewMaterialButton(Rect buttonRect, SerializedObject serializedObject)
{
// Small padding to separate both fields:
buttonRect.xMin += 2;
if (!EditorGUI.DropdownButton(buttonRect, Styles.newMaterialButton, FocusType.Keyboard))
return;
- void CreateMaterial(bool shaderGraph)
- {
- var materialIcon = AssetPreview.GetMiniTypeThumbnail(typeof(Material));
- var action = ScriptableObject.CreateInstance();
- action.createShaderGraphShader = shaderGraph;
- action.customPass = target as FullScreenCustomPass;
- ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, action, k_DefaultMaterialName, materialIcon, null);
- }
-
GenericMenu menu = new GenericMenu();
- menu.AddItem(new GUIContent("ShaderGraph"), false, () => CreateMaterial(true));
- menu.AddItem(new GUIContent("Handwritten Shader"), false, () => CreateMaterial(false));
+ menu.AddItem(new GUIContent(k_NewShaderGraphText), false, () => CreateFullscreenMaterialFromTemplate(target as FullScreenCustomPass, serializedObject.targetObject as CustomPassVolume, k_ShaderGraphTemplatePath));
+
+ // For later introduction of SG Filtered Template Browser
+ //menu.AddItem(new GUIContent(k_NewShaderGraphFromTemplateText), false, () => CreateFullscreenMaterialFromTemplate(target as FullScreenCustomPass, serializedObject.targetObject as CustomPassVolume));
+
+ menu.AddItem(new GUIContent(k_NewShaderText), false, () => CreateFullscreenShaderFromTemplate(target as FullScreenCustomPass, serializedObject.targetObject as CustomPassVolume));
menu.DropDown(buttonRect);
}
+ static void CreateFullscreenShaderFromTemplate(FullScreenCustomPass obj, CustomPassVolume targetObject)
+ {
+ AssetCreationUtil.CreateShaderAndMaterial(
+ k_DefaultMaterialName,
+ (material) =>
+ {
+ obj.fullscreenPassMaterial = material;
+ EditorUtility.SetDirty(targetObject);
+ Selection.activeGameObject = targetObject.gameObject; // restoring selection
+ },
+ k_shaderTemplatePath
+ );
+ }
+
+ static void CreateFullscreenMaterialFromTemplate(FullScreenCustomPass obj, CustomPassVolume targetObject, string templatePath = null)
+ {
+ CreateShaderGraph.CreateGraphAndMaterialFromTemplate((material) =>
+ {
+ obj.fullscreenPassMaterial = material;
+ EditorUtility.SetDirty(targetObject);
+ Selection.activeGameObject = targetObject.gameObject; // restoring selection
+ },
+ templatePath,
+ $"{k_DefaultMaterialName}");
+ }
+
bool DoesWriteMaskContainsReservedBits(int writeMask)
{
if (targetDepthBuffer == CustomPass.TargetBuffer.Custom)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.Skin.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.Skin.cs
index bf8b7d51ae9..54cc0482719 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.Skin.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.Skin.cs
@@ -163,6 +163,7 @@ public class Styles
public static readonly GUIContent volumetricResolutionContent = EditorGUIUtility.TrTextContent("High Quality ", "When enabled, HDRP increases the resolution of volumetric lighting buffers. Warning: There is a high performance cost, do not enable on consoles.");
public static readonly GUIContent supportLightLayerContent = EditorGUIUtility.TrTextContent("Light Layers", "When enabled, HDRP allocates memory for processing Light Layers. This allows you to use Light Layers in your Unity Project. For deferred rendering, this allocation includes an extra render target in memory and extra cost.");
public static readonly GUIContent colorBufferFormatContent = EditorGUIUtility.TrTextContent("Color Buffer Format", "Specifies the format used by the scene color render target. R11G11B10 is a faster option and should have sufficient precision.");
+ public static readonly GUIContent depthBufferFormatContent = EditorGUIUtility.TrTextContent("Depth Buffer Format", "Specifies the format used by the scene depth render target.");
public static readonly GUIContent supportCustomPassContent = EditorGUIUtility.TrTextContent("Custom Pass", "When enabled, HDRP allocates a custom pass buffer. It also enable custom passes inside Custom Pass Volume components.");
public static readonly GUIContent supportVariableRateShadingContent = EditorGUIUtility.TrTextContent("Variable Rate Shading", "When enabled, HDRP enables the usage of variable rate shading in custom passes.");
public static readonly GUIContent customBufferFormatContent = EditorGUIUtility.TrTextContent("Custom Buffer Format", "Specifies the format used by the custom pass render target.");
@@ -275,6 +276,9 @@ public class Styles
public static readonly GUIContent defaultInjectionPoint = EditorGUIUtility.TrTextContent("Injection Point", "The injection point at which to apply the upscaling.");
public static readonly GUIContent TAAUInjectionPoint = EditorGUIUtility.TrTextContent("TAA Upscale Injection Point", "The injection point at which to apply the upscaling.");
public static readonly GUIContent STPInjectionPoint = EditorGUIUtility.TrTextContent("STP Injection Point", "The injection point at which to apply the upscaling.");
+#if ENABLE_UPSCALER_FRAMEWORK
+ public static readonly GUIContent IUpscalerInjectionPoint = EditorGUIUtility.TrTextContent("Injection Point", "The injection point at which to apply the upscaling.");
+#endif
public static readonly GUIContent DLSSUseOptimalSettingsContent = EditorGUIUtility.TrTextContent("DLSS Use Optimal Settings", "Sets the scale automatically for NVIDIA Deep Learning Super Sampling, depending on the values of quality settings. When DLSS Optimal Settings is on, the percentage settings for Dynamic Resolution Scaling are ignored.");
public static readonly GUIContent DLSSRenderPresetsContent = EditorGUIUtility.TrTextContent("DLSS Render Presets", "DLSS will use the specified render preset for each quality value.");
#if ENABLE_NVIDIA && ENABLE_NVIDIA_MODULE
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.cs
index 3fc4ff1106c..a6bace5bf55 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/HDRenderPipelineUI.cs
@@ -587,16 +587,45 @@ static void Drawer_SectionDynamicResolutionSettings(SerializedHDRenderPipelineAs
advancedUpscalersDetectedMask |= (1 << (int)AdvancedUpscalers.STP);
advancedUpscalersAvailable |= (1 << (int)AdvancedUpscalers.STP);
- for (int i = 0; i < serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.arraySize; ++i)
+#if ENABLE_UPSCALER_FRAMEWORK
+ if (HDRenderPipeline.currentPipeline != null && HDRenderPipeline.currentPipeline.upscaling != null && HDRenderPipeline.currentPipeline.upscaling.upscalerNames.Length > 0)
{
- int upscalerMaskValue = 1 << serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.GetArrayElementAtIndex(i).intValue;
- advancedUpscalersEnabledMask |= upscalerMaskValue;
+ advancedUpscalersDetectedMask |= (1 << (int)AdvancedUpscalers.IUpscaler);
+ }
+#endif
+
+#if ENABLE_UPSCALER_FRAMEWORK
+ const int builtinUpscalerCount = (int)AdvancedUpscalers.IUpscaler;
+#else
+ const int builtinUpscalerCount = (int)AdvancedUpscalers.STP + 1;
+#endif
+ // calculate advancedUpscalersEnabledMask value
+ for (int i = 0; i < serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.arraySize; ++i)
+ {
+ string name = serialized.renderPipelineSettings.dynamicResolutionSettings
+ .advancedUpscalerNames.GetArrayElementAtIndex(i).stringValue;
+ int nameIndex = -1;
+ for (int j = 0; j < builtinUpscalerCount; j++)
+ {
+ if (name == ((AdvancedUpscalers)j).ToString())
+ {
+ nameIndex = j;
+ break;
+ }
+ }
+
+ if (nameIndex >= 0)
+ {
+ int upscalerMaskValue = 1 << nameIndex;
+ advancedUpscalersEnabledMask |= upscalerMaskValue;
+ }
}
++EditorGUI.indentLevel;
using (new EditorGUI.DisabledScope(!serialized.renderPipelineSettings.dynamicResolutionSettings.enabled.boolValue))
{
+ #region UPSCALER_PRIORITY_ORDERING
if (advancedUpscalersDetectedMask != 0)
{
ReorderableList reorderableList = null;
@@ -605,7 +634,7 @@ static void Drawer_SectionDynamicResolutionSettings(SerializedHDRenderPipelineAs
HDRenderPipelineEditor editor = owner as HDRenderPipelineEditor;
reorderableList = editor.reusableReorderableList;
- reorderableList ??= new ReorderableList(serialized.serializedObject, serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority, true, true, true, true)
+ reorderableList ??= new ReorderableList(serialized.serializedObject, serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames, true, true, true, true)
{
drawHeaderCallback = (Rect rect) =>
{
@@ -613,15 +642,23 @@ static void Drawer_SectionDynamicResolutionSettings(SerializedHDRenderPipelineAs
},
drawElementCallback = (Rect rect, int index, bool isActive, bool isFocused) =>
{
- var element = serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.GetArrayElementAtIndex(index);
+ string name = serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.GetArrayElementAtIndex(index).stringValue;
rect.y += 2;
- EditorGUI.LabelField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), element.enumDisplayNames[element.enumValueIndex], EditorStyles.label);
+ EditorGUI.LabelField(new Rect(rect.x, rect.y, rect.width, EditorGUIUtility.singleLineHeight), name, EditorStyles.label);
},
onAddDropdownCallback = (rect,list) => {
- int availableScalers = math.countbits(advancedUpscalersAvailable);
- AdvancedUpscalers[] possible = new AdvancedUpscalers[availableScalers];
- var names = new GUIContent[availableScalers];
- var enabled = new bool[availableScalers];
+ int numIUpscalers = 0;
+#if ENABLE_UPSCALER_FRAMEWORK
+ if (HDRenderPipeline.currentPipeline != null && HDRenderPipeline.currentPipeline.upscaling != null)
+ {
+ numIUpscalers = HDRenderPipeline.currentPipeline.upscaling.upscalerNames.Length;
+ }
+#endif
+ int numBuiltinUpscalers = math.countbits(advancedUpscalersAvailable);
+ AdvancedUpscalers[] possible = new AdvancedUpscalers[numBuiltinUpscalers + numIUpscalers];
+ var names = new GUIContent[numBuiltinUpscalers + numIUpscalers];
+ var enabled = new bool[numBuiltinUpscalers + numIUpscalers];
+ // Populate builtin upscalers
for (int upscalerRemainingMask = advancedUpscalersAvailable, nextItem = 0; upscalerRemainingMask != 0;)
{
AdvancedUpscalers upscalerIndex = (AdvancedUpscalers)math.tzcnt(upscalerRemainingMask);
@@ -631,14 +668,24 @@ static void Drawer_SectionDynamicResolutionSettings(SerializedHDRenderPipelineAs
upscalerRemainingMask ^= (1 << (int)upscalerIndex);//turn off the bit
nextItem++;
}
+#if ENABLE_UPSCALER_FRAMEWORK
+ // Populate IUpscalers
+ for (int i = numBuiltinUpscalers; i < numBuiltinUpscalers + numIUpscalers; i++)
+ {
+ possible[i] = AdvancedUpscalers.IUpscaler;
+ names[i] = new GUIContent(HDRenderPipeline.currentPipeline.upscaling.upscalerNames[i - numBuiltinUpscalers]);
+ enabled[i] = false;
+ }
+#endif
EditorUtility.SelectMenuItemFunction value = (userData, options, selected) =>
{
//Check if upscalerPriority already contains this selected upscalertype
bool containsSelection = false;
- for(int i = 0; i < serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.arraySize; ++i)
+ for(int i = 0; i < serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.arraySize; ++i)
{
- if(serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.GetArrayElementAtIndex(i).intValue == (int)possible[selected])
+ string name = serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.GetArrayElementAtIndex(i).stringValue;
+ if(name == names[selected].text)
{
containsSelection = true;
break;
@@ -649,9 +696,9 @@ static void Drawer_SectionDynamicResolutionSettings(SerializedHDRenderPipelineAs
if(!containsSelection)
{
int index = list.count > 0 ? list.index : 0;
- serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.InsertArrayElementAtIndex(index);
- var newElement = serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.GetArrayElementAtIndex(index);
- newElement.enumValueIndex = (int)possible[selected];
+ serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.InsertArrayElementAtIndex(index);
+ SerializedProperty nameProp = serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.GetArrayElementAtIndex(index);
+ nameProp.stringValue = names[selected].text;
serialized.serializedObject.ApplyModifiedProperties();
}
};
@@ -666,9 +713,10 @@ static void Drawer_SectionDynamicResolutionSettings(SerializedHDRenderPipelineAs
EditorGUILayout.BeginVertical(new GUIStyle() { margin = new RectOffset((EditorGUI.indentLevel + 1) * 15, 0, 0, 0) });
reorderableList.DoLayoutList();
EditorGUILayout.EndVertical();
-
}
+ #endregion
+ #region DLSS_GUI
bool containsDLSS = ((1 << (int)AdvancedUpscalers.DLSS) & advancedUpscalersEnabledMask) != 0;
bool dlssDetected = ((1 << (int)AdvancedUpscalers.DLSS) & advancedUpscalersDetectedMask) != 0;
if (containsDLSS)
@@ -749,7 +797,7 @@ uint GUIIndexToPresetValue(uint presetBitmask, uint index)
DrawPresetDropdown(ref drsSettings.DLSSRenderPresetForDLAA , UnityEngine.NVIDIA.DLSSQuality.DLAA );
--EditorGUI.indentLevel;
-
+
#endif
--EditorGUI.indentLevel;
@@ -775,7 +823,9 @@ uint GUIIndexToPresetValue(uint presetBitmask, uint index)
EditorGUILayout.EndHorizontal();
++EditorGUI.indentLevel;
}
+ #endregion
+ #region FSR2_GUI
bool containsFSR2 = ((1 << (int)AdvancedUpscalers.FSR2) & advancedUpscalersEnabledMask) != 0;
bool fsr2Detected = ((1 << (int)AdvancedUpscalers.FSR2) & advancedUpscalersDetectedMask) != 0;
if (containsFSR2)
@@ -820,7 +870,9 @@ uint GUIIndexToPresetValue(uint presetBitmask, uint index)
EditorGUILayout.EndHorizontal();
++EditorGUI.indentLevel;
}
+ #endregion
+ #region STP_GUI
bool containsSTP = ((1 << (int)AdvancedUpscalers.STP) & advancedUpscalersEnabledMask) != 0;
if (containsSTP)
{
@@ -831,7 +883,58 @@ uint GUIIndexToPresetValue(uint presetBitmask, uint index)
serialized.renderPipelineSettings.dynamicResolutionSettings.STPInjectionPoint.intValue = value;
}
}
+ #endregion
+
+ #region IUPSCALER_GUI
+#if ENABLE_UPSCALER_FRAMEWORK
+ bool detectedIUpscaler = ((1 << (int)AdvancedUpscalers.IUpscaler) & advancedUpscalersDetectedMask) != 0;
+ if(detectedIUpscaler)
+ {
+ ++EditorGUI.indentLevel;
+
+ bool optionsChanged = false;
+
+ // O(N^2) IUpscaler name comparison but typical use case is <6 entries w/ each entry around 20B of char data
+ for(int i=0; i< serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.arraySize; ++i)
+ {
+ string advancedUpscalerName = serialized.renderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.GetArrayElementAtIndex(i).stringValue;
+
+ List upscalerOptionsList = HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.IUpscalerOptions;
+ foreach (UpscalerOptions upscalerOptions in upscalerOptionsList)
+ {
+ if (upscalerOptions.UpscalerName != advancedUpscalerName)
+ {
+ continue;
+ }
+
+ EditorGUILayout.LabelField(upscalerOptions.UpscalerName, EditorStyles.boldLabel);
+ ++EditorGUI.indentLevel;
+
+ // injection point selection (common to all IUpscalers)
+ int injectionPointBefore = (int)upscalerOptions.InjectionPoint;
+ int injectionPointSelection = EditorGUILayout.IntPopup(Styles.IUpscalerInjectionPoint, (int)upscalerOptions.InjectionPoint, Styles.UpscalerInjectionPointNames, Styles.UpscalerInjectionPointValues);
+ bool injectionPointChanged = injectionPointBefore != injectionPointSelection;
+ if (injectionPointChanged)
+ upscalerOptions.InjectionPoint = (DynamicResolutionHandler.UpsamplerScheduleType)injectionPointSelection;
+ // draw rest of the options
+ bool optionsChangedOnThisUpscaler = upscalerOptions.DrawOptionsEditorGUI();
+
+ optionsChanged = optionsChanged || injectionPointChanged || optionsChangedOnThisUpscaler;
+
+ --EditorGUI.indentLevel;
+ }
+ }
+
+ --EditorGUI.indentLevel;
+
+ if(optionsChanged)
+ {
+ EditorUtility.SetDirty(HDRenderPipeline.currentAsset);
+ }
+ }
+#endif
+ #endregion
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.dynamicResolutionSettings.dynamicResType, Styles.dynResType);
bool isHwDrs = (serialized.renderPipelineSettings.dynamicResolutionSettings.dynamicResType.intValue == (int)DynamicResolutionType.Hardware);
bool gfxDeviceSupportsHwDrs = HDUtils.IsHardwareDynamicResolutionSupportedByDevice(SystemInfo.graphicsDeviceType);
@@ -1297,6 +1400,7 @@ internal static void DisplayRayTracingSupportBox()
static void Drawer_SectionRenderingUnsorted(SerializedHDRenderPipelineAsset serialized, Editor owner)
{
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.colorBufferFormat, Styles.colorBufferFormatContent);
+ EditorGUILayout.PropertyField(serialized.renderPipelineSettings.depthBufferFormat, Styles.depthBufferFormatContent);
EditorGUILayout.PropertyField(serialized.renderPipelineSettings.supportedLitShaderMode, Styles.supportLitShaderModeContent);
// MSAA is an option that is only available in full forward but Camera can be set in Full Forward only. Thus MSAA have no dependency currently
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedDynamicResolutionSettings.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedDynamicResolutionSettings.cs
index 66bb13a20e9..6fb3e9c466b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedDynamicResolutionSettings.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedDynamicResolutionSettings.cs
@@ -1,4 +1,3 @@
-using UnityEditor.Rendering;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.HighDefinition
@@ -35,22 +34,26 @@ class SerializedDynamicResolutionSettings
public SerializedProperty rayTracingHalfResThreshold;
public SerializedProperty lowResSSGIMinimumThreshold;
public SerializedProperty lowResVolumetricCloudsMinimumThreshold;
- public SerializedProperty advancedUpscalersByPriority;
+ public SerializedProperty advancedUpscalerNames;
public SerializedProperty TAAUInjectionPoint;
public SerializedProperty STPInjectionPoint;
public SerializedProperty defaultInjectionPoint;
-
+#if ENABLE_UPSCALER_FRAMEWORK
+ public SerializedProperty IUpscalerOptions;
+#endif
public SerializedDynamicResolutionSettings(SerializedProperty root)
{
this.root = root;
enabled = root.Find((GlobalDynamicResolutionSettings s) => s.enabled);
useMipBias = root.Find((GlobalDynamicResolutionSettings s) => s.useMipBias);
- DLSSPerfQualitySetting = root.Find((GlobalDynamicResolutionSettings s) => s.DLSSPerfQualitySetting);
- DLSSInjectionPoint = root.Find((GlobalDynamicResolutionSettings s) => s.DLSSInjectionPoint);
TAAUInjectionPoint = root.Find((GlobalDynamicResolutionSettings s) => s.TAAUInjectionPoint);
STPInjectionPoint = root.Find((GlobalDynamicResolutionSettings s) => s.STPInjectionPoint);
defaultInjectionPoint = root.Find((GlobalDynamicResolutionSettings s) => s.defaultInjectionPoint);
+ advancedUpscalerNames = root.Find((GlobalDynamicResolutionSettings s) => s.advancedUpscalerNames);
+
+ DLSSInjectionPoint = root.Find((GlobalDynamicResolutionSettings s) => s.DLSSInjectionPoint);
+ DLSSPerfQualitySetting = root.Find((GlobalDynamicResolutionSettings s) => s.DLSSPerfQualitySetting);
DLSSUseOptimalSettings = root.Find((GlobalDynamicResolutionSettings s) => s.DLSSUseOptimalSettings);
DLSSSharpness = root.Find((GlobalDynamicResolutionSettings s) => s.DLSSSharpness);
DLSSRenderPresetForQuality = root.Find((GlobalDynamicResolutionSettings s) => s.DLSSRenderPresetForQuality);
@@ -58,14 +61,20 @@ public SerializedDynamicResolutionSettings(SerializedProperty root)
DLSSRenderPresetForPerformance = root.Find((GlobalDynamicResolutionSettings s) => s.DLSSRenderPresetForPerformance);
DLSSRenderPresetForUltraPerformance = root.Find((GlobalDynamicResolutionSettings s) => s.DLSSRenderPresetForUltraPerformance);
DLSSRenderPresetForDLAA = root.Find((GlobalDynamicResolutionSettings s) => s.DLSSRenderPresetForDLAA);
- advancedUpscalersByPriority = root.Find((GlobalDynamicResolutionSettings s) => s.advancedUpscalersByPriority);
+
FSR2EnableSharpness = root.Find((GlobalDynamicResolutionSettings s) => s.FSR2EnableSharpness);
FSR2Sharpness = root.Find((GlobalDynamicResolutionSettings s) => s.FSR2Sharpness);
FSR2UseOptimalSettings = root.Find((GlobalDynamicResolutionSettings s) => s.FSR2UseOptimalSettings);
FSR2QualitySetting = root.Find((GlobalDynamicResolutionSettings s) => s.FSR2QualitySetting);
FSR2InjectionPoint = root.Find((GlobalDynamicResolutionSettings s) => s.FSR2InjectionPoint);
+
fsrOverrideSharpness = root.Find((GlobalDynamicResolutionSettings s) => s.fsrOverrideSharpness);
fsrSharpness = root.Find((GlobalDynamicResolutionSettings s) => s.fsrSharpness);
+
+#if ENABLE_UPSCALER_FRAMEWORK
+ IUpscalerOptions = root.Find((GlobalDynamicResolutionSettings s) => s.IUpscalerOptions);
+#endif
+
maxPercentage = root.Find((GlobalDynamicResolutionSettings s) => s.maxPercentage);
minPercentage = root.Find((GlobalDynamicResolutionSettings s) => s.minPercentage);
dynamicResType = root.Find((GlobalDynamicResolutionSettings s) => s.dynResType);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedHDRenderPipelineAsset.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedHDRenderPipelineAsset.cs
index 675334824c8..373c7bdab93 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedHDRenderPipelineAsset.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedHDRenderPipelineAsset.cs
@@ -1,4 +1,4 @@
-using UnityEditor.Rendering;
+using UnityEngine.Rendering;
using UnityEngine.Rendering.HighDefinition;
namespace UnityEditor.Rendering.HighDefinition
@@ -19,6 +19,7 @@ class SerializedHDRenderPipelineAsset
public SerializedHDRenderPipelineAsset(SerializedObject serializedObject)
{
this.serializedObject = serializedObject;
+ HDRenderPipelineAsset asset = serializedObject.targetObject as HDRenderPipelineAsset;
defaultMaterialQualityLevel = serializedObject.FindProperty("m_DefaultMaterialQualityLevel");
volumeProfile = serializedObject.FindProperty("m_VolumeProfile");
@@ -29,6 +30,32 @@ public SerializedHDRenderPipelineAsset(SerializedObject serializedObject)
renderPipelineSettings = new SerializedRenderPipelineSettings(serializedObject.FindProperty("m_RenderPipelineSettings"));
virtualTexturingSettings = new SerializedVirtualTexturingSettings(serializedObject.FindProperty("virtualTexturingSettings"));
+
+#if ENABLE_UPSCALER_FRAMEWORK
+ // HDRenderPipelineAsset/RenderPipelineSettings/GlobalDynamicResolutionScaling struct contains the
+ // UpscalerOptions collection (polymorphic data) tagged with [SerializeReference].
+ // Here we ensure the ScriptableObject references (concrete UpscalerOptions) are in a valid state,
+ // and initialize with defaults if they're not within the serialized asset.
+ SerializedProperty dynamicResolutionSettingsProp = renderPipelineSettings.root.FindPropertyRelative("dynamicResolutionSettings");
+ if (dynamicResolutionSettingsProp == null)
+ {
+ UnityEngine.Debug.LogError($"[HDRP Serialized Asset] Could not find 'dynamicResolutionSettings' property in m_RenderPipelineSettings for {asset.name}.");
+ return;
+ }
+ SerializedProperty UpscalerOptionBaseProp = dynamicResolutionSettingsProp.FindPropertyRelative("IUpscalerOptions");
+ if (UpscalerOptionBaseProp == null)
+ {
+ UnityEngine.Debug.LogError($"[HDRP Serialized Asset] Could not find 'UpscalerOptions' property in DynamicResolutionSettings for {asset.name}.");
+ return;
+ }
+ if (UpscalerOptions.ValidateSerializedUpscalerOptionReferencesWithinRPAsset(asset, UpscalerOptionBaseProp))
+ {
+ serializedObject.ApplyModifiedProperties();
+ EditorUtility.SetDirty(asset);
+
+ UnityEngine.Debug.Log($"[URP Serialized Asset] UniversalRenderPipelineAsset '{asset.name}' auto-populated and saved on SerializedObject creation.");
+ }
+#endif
}
public void Update()
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedRenderPipelineSettings.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedRenderPipelineSettings.cs
index f52f914e130..39ea34382bf 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedRenderPipelineSettings.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipeline/Settings/SerializedRenderPipelineSettings.cs
@@ -49,6 +49,7 @@ class SerializedRenderPipelineSettings
public SerializedProperty supportLightLayers;
public SerializedProperty supportedLitShaderMode;
public SerializedProperty colorBufferFormat;
+ public SerializedProperty depthBufferFormat;
public SerializedProperty supportCustomPass;
public SerializedProperty supportVariableRateShading;
public SerializedProperty customBufferFormat;
@@ -141,6 +142,7 @@ public SerializedRenderPipelineSettings(SerializedProperty root)
supportLightLayers = root.Find((RenderPipelineSettings s) => s.supportLightLayers);
colorBufferFormat = root.Find((RenderPipelineSettings s) => s.colorBufferFormat);
+ depthBufferFormat = root.Find((RenderPipelineSettings s) => s.depthBufferFormat);
customBufferFormat = root.Find((RenderPipelineSettings s) => s.customBufferFormat);
renderingLayerMaskBuffer = root.Find((RenderPipelineSettings s) => s.renderingLayerMaskBuffer);
supportCustomPass = root.Find((RenderPipelineSettings s) => s.supportCustomPass);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Shaders/GUITextureBlit2SRGB.shader b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Shaders/GUITextureBlit2SRGB.shader
index c94622ae56a..34ef15d0f37 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Shaders/GUITextureBlit2SRGB.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Shaders/GUITextureBlit2SRGB.shader
@@ -15,7 +15,7 @@ Shader "Hidden/GUITextureBlit2SRGB" {
HLSLPROGRAM
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma vertex vert
#pragma fragment frag
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Texture/LocalVolumetricFog.png b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Texture/LocalVolumetricFog.png
new file mode 100644
index 00000000000..3eadb0952f1
Binary files /dev/null and b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Texture/LocalVolumetricFog.png differ
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Texture/LocalVolumetricFog.png.meta b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Texture/LocalVolumetricFog.png.meta
new file mode 100644
index 00000000000..faeb5597b72
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Texture/LocalVolumetricFog.png.meta
@@ -0,0 +1,260 @@
+fileFormatVersion: 2
+guid: f1a8309765f875a468f713b57896df1c
+TextureImporter:
+ internalIDToNameTable: []
+ externalObjects: {}
+ serializedVersion: 13
+ mipmaps:
+ mipMapMode: 0
+ enableMipMap: 1
+ sRGBTexture: 1
+ linearTexture: 0
+ fadeOut: 0
+ borderMipMap: 0
+ mipMapsPreserveCoverage: 0
+ alphaTestReferenceValue: 0.5
+ mipMapFadeDistanceStart: 1
+ mipMapFadeDistanceEnd: 3
+ bumpmap:
+ convertToNormalMap: 0
+ externalNormalMap: 0
+ heightScale: 0.25
+ normalMapFilter: 0
+ flipGreenChannel: 0
+ isReadable: 0
+ streamingMipmaps: 0
+ streamingMipmapsPriority: 0
+ vTOnly: 0
+ ignoreMipmapLimit: 0
+ grayScaleToAlpha: 0
+ generateCubemap: 6
+ cubemapConvolution: 0
+ seamlessCubemap: 0
+ textureFormat: 1
+ maxTextureSize: 2048
+ textureSettings:
+ serializedVersion: 2
+ filterMode: 1
+ aniso: 1
+ mipBias: 0
+ wrapU: 0
+ wrapV: 0
+ wrapW: 0
+ nPOTScale: 1
+ lightmap: 0
+ compressionQuality: 50
+ spriteMode: 0
+ spriteExtrude: 1
+ spriteMeshType: 1
+ alignment: 0
+ spritePivot: {x: 0.5, y: 0.5}
+ spritePixelsToUnits: 100
+ spriteBorder: {x: 0, y: 0, z: 0, w: 0}
+ spriteGenerateFallbackPhysicsShape: 1
+ alphaUsage: 1
+ alphaIsTransparency: 0
+ spriteTessellationDetail: -1
+ textureType: 0
+ textureShape: 1
+ singleChannelComponent: 0
+ flipbookRows: 1
+ flipbookColumns: 1
+ maxTextureSizeSet: 0
+ compressionQualitySet: 0
+ textureFormatSet: 0
+ ignorePngGamma: 0
+ applyGammaDecoding: 0
+ swizzle: 50462976
+ cookieLightType: 0
+ platformSettings:
+ - serializedVersion: 4
+ buildTarget: DefaultTexturePlatform
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: CloudRendering
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: Switch
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: WebGL
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: QNX
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: Android
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: Standalone
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: EmbeddedLinux
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: Kepler
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: WindowsStoreApps
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: iOS
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: VisionOS
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: tvOS
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ spriteSheet:
+ serializedVersion: 2
+ sprites: []
+ outline: []
+ customData:
+ physicsShape: []
+ bones: []
+ spriteID:
+ internalID: 0
+ vertices: []
+ indices:
+ edges: []
+ weights: []
+ secondaryTextures: []
+ spriteCustomMetadata:
+ entries: []
+ nameFileIdTable: {}
+ mipmapLimitGroupName:
+ pSDRemoveMatte: 0
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Texture/PlanarReflection.png b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Texture/PlanarReflection.png
index d853d0bc679..e03ea7a3d80 100644
Binary files a/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Texture/PlanarReflection.png and b/Packages/com.unity.render-pipelines.high-definition/Editor/RenderPipelineResources/Texture/PlanarReflection.png differ
diff --git a/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/ColorCheckerToolEditor.cs b/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/ColorCheckerToolEditor.cs
index 14e4a5a8efc..befc21fada5 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/ColorCheckerToolEditor.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Editor/Tools/ColorCheckerToolEditor.cs
@@ -72,7 +72,8 @@ public override VisualElement CreateInspectorGUI()
//Prepare metallic toggles for material mode
for(int i=0; i<12;i++)
{
- Toggle metallicToggle = new Toggle() { name ="metallic" + i, label = "is Metallic", tabIndex = i};
+ Toggle metallicToggle = new Toggle() { name ="metallic" + i, label = "Metallic", tabIndex = i};
+ metallicToggle.Q
[Tooltip("Controls the thickness of the depth buffer used for ray marching.")]
public ClampedFloatParameter depthBufferThickness = new ClampedFloatParameter(0.1f, 0.0f, 0.5f);
-
- GlobalIllumination()
- {
- displayName = "Screen Space Global Illumination";
- }
-
+
///
/// Defines if the screen space global illumination should be evaluated at full resolution.
///
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClearLightLists.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClearLightLists.compute
index e897a278473..2f76292140f 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClearLightLists.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/ClearLightLists.compute
@@ -1,5 +1,5 @@
#pragma kernel ClearList
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
RWStructuredBuffer _LightListToClear;
int2 _LightListEntriesAndOffset;
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute
index ea7dac2a6e3..7b8b9b47199 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/Deferred.compute
@@ -92,7 +92,7 @@ CBUFFER_END
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDStencilUsage.cs.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//-------------------------------------------------------------------------------------
// variable declaration
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs
index 125a3b981d3..7a665519702 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoop.cs
@@ -300,7 +300,7 @@ public partial class HDRenderPipeline
internal const int k_MaxLightsPerClusterCell = ShaderConfig.LightClusterMaxCellElementCount;
internal static readonly Vector3 k_BoxCullingExtentThreshold = Vector3.one * 0.01f;
-#if !UNITY_EDITOR && UNITY_SWITCH
+#if !UNITY_EDITOR && (UNITY_SWITCH || UNITY_SWITCH2)
const int k_ThreadGroupOptimalSize = 32;
#else
const int k_ThreadGroupOptimalSize = 64;
@@ -558,7 +558,7 @@ enum ClusterDepthSource : int
const bool k_UseDepthBuffer = true; // only has an impact when EnableClustered is true (requires a depth-prepass)
-#if !UNITY_EDITOR && UNITY_SWITCH
+#if !UNITY_EDITOR && (UNITY_SWITCH || UNITY_SWITCH2)
const int k_Log2NumClusters = 5; // accepted range is from 0 to 5 (NR_THREADS is set to 32). NumClusters is 1< g_DispatchIndirectBuffer : register( u0 ); // Indirect arguments have to be in a _buffer_, not a structured buffer
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute
index 3b0c7cdb9f8..dc3d9f0a982 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-bigtile.compute
@@ -8,7 +8,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightingConvexHullUtils.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/SortingComputeUtils.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ GENERATE_VOLUMETRIC_BIGTILE
@@ -159,7 +159,11 @@ void BigTileLightListGen(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_Gro
}
}
-#if NR_THREADS > PLATFORM_LANE_COUNT || defined(SHADER_API_XBOXONE) || defined(SHADER_API_GAMECORE) || defined(SHADER_API_SWITCH) // not sure why XB1 and Switch need the barrier (it will not be correct without)
+ // For some platforms we always need GroupMemoryBarrierWithGroupSync() otherwise results are incorrect.
+ // Reason is under investigation, related discussions:
+ // https://unity.slack.com/archives/C02C8FWPNHE/p1704321597295329
+ // https://unity.slack.com/archives/G3JUQKYV8/p1705081617447289
+#if NR_THREADS > PLATFORM_LANE_COUNT || defined(SHADER_API_XBOXONE) || defined(SHADER_API_GAMECORE) || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
GroupMemoryBarrierWithGroupSync();
#endif
@@ -189,19 +193,17 @@ void BigTileLightListGen(uint threadID : SV_GroupIndex, uint3 u3GroupID : SV_Gro
for(i = t; i * 2 < iNrCoarseLights + 1; i += NR_THREADS / 2)
{
uint id = i * 2;
-
uint lightIndexOrCount0 = iNrCoarseLights; // Count
if (id > 0) // cannot use ternary operator here (it would evaluate both sides and fetch invalid indices, causing crash on some GPUs)
{
lightIndexOrCount0 = lightsListLDS[id - 1]; // Index0
}
-
+
uint lightIndex1 = 0; // Index1
if (id < iNrCoarseLights) // cannot use ternary operator here (it would evaluate both sides and fetch invalid indices, causing crash on some GPUs)
{
lightIndex1 = lightsListLDS[id];
}
-
// Pack 2 light indices into a single bigtile value
g_vLightList[MAX_NR_BIG_TILE_LIGHTS_PLUS_ONE * offs / 2 + i] = (lightIndexOrCount0 & 0xFFFF) | (lightIndex1 << 16);
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clearatomic.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clearatomic.compute
index 7b52e1acea1..4894091b422 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clearatomic.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clearatomic.compute
@@ -4,7 +4,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
RWStructuredBuffer g_LayeredSingleIdxBuffer : register(u2); // don't support RWBuffer yet in unity
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute
index aca9d4f1cbf..c40fb059194 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild-clustered.compute
@@ -23,11 +23,11 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightingConvexHullUtils.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl"
-#if !defined(SHADER_API_XBOXONE) && !defined(SHADER_API_PSSL) && !defined(SHADER_API_SWITCH) && !defined(SHADER_API_GAMECORE)
+#if !defined(SHADER_API_XBOXONE) && !defined(SHADER_API_PSSL) && !defined(SHADER_API_SWITCH) && !defined(SHADER_API_GAMECORE) && !defined(SHADER_API_SWITCH2)
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/SortingComputeUtils.hlsl"
#endif
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#define EXACT_EDGE_TESTS
#define PERFORM_SPHERICAL_INTERSECTION_TESTS
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild.compute
index de71120111c..05d638cef68 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/lightlistbuild.compute
@@ -18,11 +18,11 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightingConvexHullUtils.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightCullUtils.hlsl"
-#if !defined(SHADER_API_XBOXONE) && !defined(SHADER_API_PSSL) && !defined(SHADER_API_SWITCH) && !defined(SHADER_API_GAMECORE)
+#if !defined(SHADER_API_XBOXONE) && !defined(SHADER_API_PSSL) && !defined(SHADER_API_SWITCH) && !defined(SHADER_API_GAMECORE) && !defined(SHADER_API_SWITCH2)
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/SortingComputeUtils.hlsl"
#endif
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define FINE_PRUNING_ENABLED
#define PERFORM_SPHERICAL_INTERSECTION_TESTS
@@ -204,7 +204,11 @@ void TileLightListGen(uint3 dispatchThreadId : SV_DispatchThreadID, uint threadI
InterlockedMax(ldsZMax, asuint(dpt_ma));
InterlockedMin(ldsZMin, asuint(dpt_mi));
-#if NR_THREADS > PLATFORM_LANE_COUNT || defined(SHADER_API_SWITCH) // not sure why Switch needs the barrier (it will not be correct without)
+ // For some platforms we always need GroupMemoryBarrierWithGroupSync() otherwise results are incorrect.
+ // Reason is under investigation, related discussions:
+ // https://unity.slack.com/archives/C02C8FWPNHE/p1704321597295329
+ // https://unity.slack.com/archives/G3JUQKYV8/p1705081617447289
+#if NR_THREADS > PLATFORM_LANE_COUNT || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
GroupMemoryBarrierWithGroupSync();
#endif
}
@@ -260,6 +264,7 @@ void TileLightListGen(uint3 dispatchThreadId : SV_DispatchThreadID, uint threadI
#ifndef FINE_PRUNING_ENABLED
{
+ UNITY_UNROLL
for(i=t; i PLATFORM_LANE_COUNT || defined(SHADER_API_SWITCH) // not sure why Switch needs the barrier (it will not be correct without)
+ // For some platforms we always need GroupMemoryBarrierWithGroupSync() otherwise results are incorrect.
+ // Reason is under investigation, related discussions:
+ // https://unity.slack.com/archives/C02C8FWPNHE/p1704321597295329
+ // https://unity.slack.com/archives/G3JUQKYV8/p1705081617447289
+#if NR_THREADS > PLATFORM_LANE_COUNT || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
GroupMemoryBarrierWithGroupSync();
#endif
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute
index 53305f85789..fb7cd6f0327 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/materialflags.compute
@@ -14,7 +14,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define USE_MATERIAL_FEATURE_FLAGS
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute
index 708826c9ceb..cd15f9858bd 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/scrbound.compute
@@ -1,5 +1,5 @@
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel main
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/PlanarReflectionFiltering.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/PlanarReflectionFiltering.compute
index 64d4e37a547..9fa9877be8e 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/PlanarReflectionFiltering.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/PlanarReflectionFiltering.compute
@@ -2,7 +2,7 @@
#pragma kernel DownScale
#pragma kernel DepthConversion
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
// The process is done in 3 steps. We start by converting the depth from oblique to regular frustum depth.
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/PlanarReflectionProbe.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/PlanarReflectionProbe.cs
index a1bd838f7ea..4dde02a7f8c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/PlanarReflectionProbe.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Reflection/PlanarReflectionProbe.cs
@@ -10,6 +10,7 @@ namespace UnityEngine.Rendering.HighDefinition
[HDRPHelpURLAttribute("Planar-Reflection-Probe")]
[ExecuteAlways]
[AddComponentMenu("Rendering/Planar Reflection Probe")]
+ [Icon("PlanarReflections")]
public sealed partial class PlanarReflectionProbe : HDProbe
{
// Serialized data
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/BilateralUpsample.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/BilateralUpsample.compute
index f869782e3a9..56928b2272a 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/BilateralUpsample.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/BilateralUpsample.compute
@@ -3,7 +3,7 @@
//#pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define BILATERAL_UPSAMPLE_TILE_SIZE 8
@@ -139,7 +139,7 @@ void BilateralUpSampleColor(uint3 currentCoord : SV_DispatchThreadID)
float closestDepth = max(depthNeighborhood.x, max(depthNeighborhood.y, max(depthNeighborhood.z, depthNeighborhood.w)));
float2 uvAtLowRes = min((currentCoord.xy) * _RayMarchingLowResPercentage + 0.5, _HalfScreenSize.xy - 1) * _ScreenSize.zw;
- float2 sampleUV = ClampAndScaleUVForBilinear(uvAtLowRes);
+ float2 sampleUV = ClampAndScaleUVForBilinear(uvAtLowRes);
float2 samplePixel = sampleUV * _ScreenSize.xy;
float2 bottomRight = frac(samplePixel + 0.5);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAO.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAO.compute
index 0f85c896e8a..4b5cddca7c8 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAO.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAO.compute
@@ -1,7 +1,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCommon.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/NormalBuffer.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#pragma enable_d3d11_debug_symbols
#pragma kernel GTAOMain
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOBlurAndUpsample.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOBlurAndUpsample.compute
index f4371200c85..6410a3a2803 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOBlurAndUpsample.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOBlurAndUpsample.compute
@@ -21,7 +21,7 @@
#pragma kernel Blur BLUR_KERNEL_NAME=Blur BLUR
#pragma kernel Blur_FullRes BLUR_KERNEL_NAME=Blur_FullRes BLUR FULL_RES
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
TEXTURE2D_X(_AOPackedData);
RW_TEXTURE2D_X(float, _OcclusionTexture);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCopyHistory.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCopyHistory.compute
index 0fc542a21c2..758b60dc135 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCopyHistory.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCopyHistory.compute
@@ -1,6 +1,6 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel GTAODenoise_CopyHistory
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOSpatialDenoise.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOSpatialDenoise.compute
index 7d0914373a6..721ade2a869 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOSpatialDenoise.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOSpatialDenoise.compute
@@ -3,7 +3,7 @@
// TODO: This pass really could really use some quality improvement.
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel SpatialDenoise
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOTemporalDenoise.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOTemporalDenoise.compute
index f909b9725c1..9a2f82bae19 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOTemporalDenoise.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOTemporalDenoise.compute
@@ -1,7 +1,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/GTAOCommon.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/NormalBuffer.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel TemporalDenoise
#pragma multi_compile HALF_RES FULL_RES
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute
index 540578b661e..516f3d5fe4e 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceGlobalIllumination.compute
@@ -21,7 +21,7 @@
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel TraceGlobalIllumination TRACE_GLOBAL_ILLUMINATION=TraceGlobalIllumination GI_TRACE
#pragma kernel TraceGlobalIlluminationHalf TRACE_GLOBAL_ILLUMINATION=TraceGlobalIlluminationHalf GI_TRACE HALF_RES
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflections.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflections.compute
index 5aa08154573..b27e6135463 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflections.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/ScreenSpaceLighting/ScreenSpaceReflections.compute
@@ -3,7 +3,7 @@
//--------------------------------------------------------------------------------------------------
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel ScreenSpaceReflectionsTracing SSR_TRACE
#pragma kernel ScreenSpaceReflectionsReprojection SSR_REPROJECT
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.compute
index 57cb489b39f..87722e13043 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.compute
@@ -10,7 +10,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/LightLoop/LightLoopDef.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#ifdef SHADER_API_PSSL
#include SHADER_COMPILER_GLOBAL_OPTIMIZE_REGISTER_USAGE
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.cs
index 83dd1eb497f..2a952962dd2 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ContactShadows.cs
@@ -9,6 +9,7 @@ namespace UnityEngine.Rendering.HighDefinition
[Serializable, VolumeComponentMenu("Shadowing/Contact Shadows")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("Override-Contact-Shadows")]
+ [DisplayInfo(name = "Contact Shadows")]
public class ContactShadows : VolumeComponentWithQuality
{
///
@@ -76,10 +77,5 @@ public int sampleCount
[SerializeField, FormerlySerializedAs("sampleCount")]
private NoInterpClampedIntParameter m_SampleCount = new NoInterpClampedIntParameter(10, 4, 64);
-
- ContactShadows()
- {
- displayName = "Contact Shadows";
- }
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/DebugDisplayHDShadowMap.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/DebugDisplayHDShadowMap.shader
index fbdef7797e9..875b39e5bf7 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/DebugDisplayHDShadowMap.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/DebugDisplayHDShadowMap.shader
@@ -2,7 +2,7 @@ Shader "Hidden/ScriptableRenderPipeline/DebugDisplayHDShadowMap"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/EVSMBlur.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/EVSMBlur.compute
index c5fb2ef6aa6..5ec4d3ef12c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/EVSMBlur.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/EVSMBlur.compute
@@ -10,7 +10,7 @@
#pragma kernel CopyMoments
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
Texture2D _DepthTexture;
RW_TEXTURE2D(float2, _InputTexture);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowSettings.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowSettings.cs
index 6b3f25aab14..b0a34848b43 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowSettings.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/HDShadowSettings.cs
@@ -8,6 +8,7 @@ namespace UnityEngine.Rendering.HighDefinition
[Serializable, VolumeComponentMenu("Shadowing/Shadows")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("Override-Shadows")]
+ [DisplayInfo(name = "Shadows")]
public class HDShadowSettings : VolumeComponent, ISerializationCallbackReceiver
{
float[] m_CascadeShadowSplits = new float[3];
@@ -125,12 +126,12 @@ public void OnAfterDeserialize()
/// Border size at the end of the last cascade split.
[Tooltip("Sets the border size at the end of the last cascade split.")]
public CascadeEndBorderParameter cascadeShadowBorder3 = new CascadeEndBorderParameter(0.0f);
-
-
- HDShadowSettings()
+
+ ///
+ protected override void OnEnable()
{
- displayName = "Shadows";
-
+ base.OnEnable();
+
cascadeShadowSplit0.Init(cascadeShadowSplitCount, 2, maxShadowDistance, null, cascadeShadowSplit1);
cascadeShadowSplit1.Init(cascadeShadowSplitCount, 3, maxShadowDistance, cascadeShadowSplit0, cascadeShadowSplit2);
cascadeShadowSplit2.Init(cascadeShadowSplitCount, 4, maxShadowDistance, cascadeShadowSplit1, null);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MicroShadowing.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MicroShadowing.cs
index dcce85eddd2..9e246876833 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MicroShadowing.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MicroShadowing.cs
@@ -8,6 +8,7 @@ namespace UnityEngine.Rendering.HighDefinition
[Serializable, VolumeComponentMenu("Shadowing/Micro Shadows")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURLAttribute("Override-Micro-Shadows")]
+ [DisplayInfo(name = "Micro Shadows")]
public class MicroShadowing : VolumeComponent
{
///
@@ -22,10 +23,5 @@ public class MicroShadowing : VolumeComponent
///
[Tooltip("Controls the opacity of the micro shadows.")]
public ClampedFloatParameter opacity = new ClampedFloatParameter(1.0f, 0.0f, 1.0f);
-
- MicroShadowing()
- {
- displayName = "Micro Shadows";
- }
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MomentShadows.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MomentShadows.compute
index 1a4339bd28a..38839a802e9 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MomentShadows.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/MomentShadows.compute
@@ -11,7 +11,7 @@
//#pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadows.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadows.shader
index 3b9d8598bda..2864ea0e19c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadows.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ScreenSpaceShadows.shader
@@ -3,7 +3,7 @@ Shader "Hidden/HDRP/ScreenSpaceShadows"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_fragment PUNCTUAL_SHADOW_LOW PUNCTUAL_SHADOW_MEDIUM PUNCTUAL_SHADOW_HIGH
#pragma multi_compile_fragment DIRECTIONAL_SHADOW_LOW DIRECTIONAL_SHADOW_MEDIUM DIRECTIONAL_SHADOW_HIGH
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowBlit.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowBlit.shader
index 109fa303b7a..1491360b3be 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowBlit.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowBlit.shader
@@ -2,7 +2,7 @@ Shader "Hidden/ScriptableRenderPipeline/ShadowBlit"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/DynamicScaling.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowClear.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowClear.shader
index 4bde629c733..18a1be96dac 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowClear.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/Shadow/ShadowClear.shader
@@ -2,7 +2,7 @@ Shader "Hidden/ScriptableRenderPipeline/ShadowClear"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
ENDHLSL
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricClouds.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricClouds.compute
index 5fb00d2a89f..80b8c9e3e49 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricClouds.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricClouds.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// Trace to intermediate
#pragma kernel ReprojectClouds REPROJECT_CLOUDS=ReprojectClouds
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricClouds.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricClouds.cs
index 0a68cb7205a..73577389642 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricClouds.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricClouds.cs
@@ -9,6 +9,7 @@ namespace UnityEngine.Rendering.HighDefinition
[Serializable, VolumeComponentMenu("Sky/Volumetric Clouds")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("create-realistic-clouds-volumetric-clouds")]
+ [DisplayInfo(name = "Volumetric Clouds")]
public sealed partial class VolumetricClouds : VolumeComponent
{
///
@@ -631,10 +632,5 @@ void ApplyCurrentCloudPreset()
break;
}
}
-
- VolumetricClouds()
- {
- displayName = "Volumetric Clouds";
- }
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsCombine.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsCombine.shader
index 0fcdc0ec9ff..32954c82e6b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsCombine.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsCombine.shader
@@ -6,7 +6,7 @@ Shader "Hidden/HDRP/VolumetricCloudsCombine"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#pragma enable_d3d11_debug_symbols
#pragma vertex Vert
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsShadowFilter.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsShadowFilter.compute
index 2ecfd009339..ace80ef864c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsShadowFilter.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsShadowFilter.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel FilterVolumetricCloudsShadow
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsTrace.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsTrace.compute
index f82c83cf341..9f748c72bf1 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsTrace.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsTrace.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// Render clouds
#pragma kernel RenderClouds
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsTraceShadows.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsTraceShadows.compute
index 009135f2e3b..785115fdf20 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsTraceShadows.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricClouds/VolumetricCloudsTraceShadows.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// Shadows
#pragma kernel TraceVolumetricCloudsShadows
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DebugLocalVolumetricFogAtlas.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DebugLocalVolumetricFogAtlas.shader
index 653dcf364c2..e8785dad79c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DebugLocalVolumetricFogAtlas.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/DebugLocalVolumetricFogAtlas.shader
@@ -6,7 +6,7 @@ Shader "Hidden/HDRP/DebugLocalVolumetricFogAtlas"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma vertex Vert
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/HDRenderPipeline.VolumetricLighting.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/HDRenderPipeline.VolumetricLighting.cs
index 46d4ed3e989..9fc1b7e08ec 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/HDRenderPipeline.VolumetricLighting.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/HDRenderPipeline.VolumetricLighting.cs
@@ -576,11 +576,11 @@ TextureHandle GenerateMaxZPass(RenderGraph renderGraph, HDCamera hdCamera, Textu
passData.depthTexture = depthTexture;
builder.UseTexture(passData.depthTexture, AccessFlags.Read);
passData.maxZ8xBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one * 0.125f, true, true)
- { format = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "MaxZ mask 8x" });
+ { format = GetDepthBufferFormat(true), enableRandomWrite = true, name = "MaxZ mask 8x" });
passData.maxZBuffer = builder.CreateTransientTexture(new TextureDesc(Vector2.one * 0.125f, true, true)
- { format = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "MaxZ mask" });
+ { format = GetDepthBufferFormat(true), enableRandomWrite = true, name = "MaxZ mask" });
passData.dilatedMaxZBuffer = renderGraph.CreateTexture(new TextureDesc(Vector2.one / 16.0f, true, true)
- { format = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "Dilated MaxZ mask" });
+ { format = GetDepthBufferFormat(true), enableRandomWrite = true, name = "Dilated MaxZ mask" });
builder.UseTexture(passData.dilatedMaxZBuffer, AccessFlags.ReadWrite);
builder.SetRenderFunc(
@@ -896,7 +896,7 @@ void PrepareVisibleLocalVolumetricFogList(HDCamera hdCamera, CommandBuffer cmd)
// Handle camera-relative rendering.
center -= camOffset;
-
+
var bounds = GeometryUtils.OBBToAABB(transform.right, transform.up, transform.forward, scaleSize, center);
// Frustum cull on the CPU for now. TODO: do it on the GPU.
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/LocalVolumetricFog.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/LocalVolumetricFog.cs
index f1f3c018159..7d1ad3a31b0 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/LocalVolumetricFog.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/LocalVolumetricFog.cs
@@ -197,6 +197,7 @@ internal LocalVolumetricFogEngineData ConvertToEngineData()
[HDRPHelpURLAttribute("create-a-local-fog-effect")]
[ExecuteAlways]
[AddComponentMenu("Rendering/Local Volumetric Fog")]
+ [Icon("Fog")]
public partial class LocalVolumetricFog : MonoBehaviour
{
/// Local Volumetric Fog parameters.
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/LocalVolumetricFog.cs.meta b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/LocalVolumetricFog.cs.meta
index b4a68f1959b..63fb2860484 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/LocalVolumetricFog.cs.meta
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/LocalVolumetricFog.cs.meta
@@ -5,7 +5,7 @@ MonoImporter:
serializedVersion: 2
defaultReferences: []
executionOrder: 0
- icon: {fileID: 2800000, guid: 16796ce96bc102d4d963f22a60a69125, type: 3}
+ icon: {fileID: 2800000, guid: f1a8309765f875a468f713b57896df1c, type: 3}
userData:
assetBundleName:
assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute
index aa8a5aa0169..1dd388140c1 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumeVoxelization.compute
@@ -3,7 +3,7 @@
//--------------------------------------------------------------------------------------------------
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel VolumeVoxelization
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute
index 6507bf51797..f3a3cb75887 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLighting.compute
@@ -3,7 +3,7 @@
//--------------------------------------------------------------------------------------------------
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel VolumetricLighting
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingController.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingController.cs
index f9f09d7b3b7..d07f0a0b46d 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingController.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingController.cs
@@ -5,6 +5,7 @@ namespace UnityEngine.Rendering.HighDefinition
{
[Obsolete("#from(2021.2)")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
+ [DisplayInfo(name = "Volumetric Fog Quality (Deprecated)")]
class VolumetricLightingController : VolumeComponent
{
[Tooltip("Sets the distance (in meters) from the Camera's Near Clipping Plane to the back of the Camera's volumetric lighting buffer.")]
@@ -12,10 +13,5 @@ class VolumetricLightingController : VolumeComponent
[Tooltip("Controls the distribution of slices along the Camera's focal axis. 0 is exponential distribution and 1 is linear distribution.")]
[FormerlySerializedAs("depthDistributionUniformity")]
public ClampedFloatParameter sliceDistributionUniformity = new ClampedFloatParameter(0.75f, 0, 1);
-
- VolumetricLightingController()
- {
- displayName = "Volumetric Fog Quality (Deprecated)";
- }
}
} // UnityEngine.Rendering.HighDefinition
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingFiltering.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingFiltering.compute
index 9d805deabab..468e2e781a3 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingFiltering.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Lighting/VolumetricLighting/VolumetricLightingFiltering.compute
@@ -3,7 +3,7 @@
//--------------------------------------------------------------------------------------------------
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel FilterVolumetricLighting
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.shader
index 4406553f41f..f73538de569 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/AxF.shader
@@ -244,7 +244,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// Note: Require _SelectionID variable
@@ -275,7 +275,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
@@ -314,7 +314,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -359,7 +359,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -400,7 +400,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -446,7 +446,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -502,7 +502,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -578,7 +578,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
@@ -607,7 +607,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -639,7 +639,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -689,7 +689,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -736,7 +736,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -777,7 +777,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#define SHADERPASS SHADERPASS_RAYTRACING_VISIBILITY
@@ -806,7 +806,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#define SHADERPASS SHADERPASS_RAYTRACING_DEBUG
@@ -830,7 +830,7 @@ Shader "HDRP/AxF"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_CookTorrance.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_CookTorrance.shader
index 2f7eb877508..7fdcc682eb9 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_CookTorrance.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_CookTorrance.shader
@@ -14,7 +14,7 @@ Shader "Hidden/HDRP/PreIntegratedFGD_CookTorrance"
#pragma vertex Vert
#pragma fragment Frag
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define PREFER_HALF 0
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_Ward.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_Ward.shader
index ccca50fccef..b33efdd458a 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_Ward.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/AxF/PreIntegratedFGD_Ward.shader
@@ -14,7 +14,7 @@ Shader "Hidden/HDRP/PreIntegratedFGD_Ward"
#pragma vertex Vert
#pragma fragment Frag
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define PREFER_HALF 0
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.shader
index 9b82c7f04dc..1987b545629 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/Decal.shader
@@ -65,7 +65,7 @@ Shader "HDRP/Decal"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#pragma enable_d3d11_debug_symbols
//-------------------------------------------------------------------------------------
@@ -282,7 +282,7 @@ Shader "HDRP/Decal"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma instancing_options renderinglayer
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalNormalBuffer.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalNormalBuffer.shader
index 90a7db8a473..98d34a539d0 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalNormalBuffer.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalNormalBuffer.shader
@@ -11,7 +11,7 @@ Shader "Hidden/HDRP/Material/Decal/DecalNormalBuffer"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_fragment _ DECAL_SURFACE_GRADIENT
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalProjector.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalProjector.cs
index 1b0a8722195..a734f17e9ad 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalProjector.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalProjector.cs
@@ -27,6 +27,7 @@ public enum DecalScaleMode
[CanEditMultipleObjects]
#endif
[AddComponentMenu("Rendering/HDRP Decal Projector")]
+ [Icon("DecalProjector")]
public partial class DecalProjector : MonoBehaviour
{
[SerializeField]
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs
index 6e7bff2d27b..daa780fb05f 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Decal/DecalSystem.cs
@@ -284,7 +284,7 @@ public Camera CurrentCamera
// to work on Vulkan Mobile?
// Core\CoreRP\ShaderLibrary\UnityInstancing.hlsl
- // #if (defined(SHADER_API_VULKAN) && defined(SHADER_API_MOBILE)) || defined(SHADER_API_SWITCH)
+ // #if (defined(SHADER_API_VULKAN) && defined(SHADER_API_MOBILE)) || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
// #define UNITY_INSTANCED_ARRAY_SIZE 250
private const int kDrawIndexedBatchSize = 250;
@@ -318,10 +318,10 @@ public enum DecalCullingMode
static public Vector4[] m_BaseColor = new Vector4[kDecalBlockSize];
// Clustered decal world space info -- useful when m_CullingMode is set to WorldspaceBasedCulling
- // This data is cached and can be queried for algorithms doing their own clustering (e.g. path tracing).
+ // This data is cached and can be queried for algorithms doing their own clustering (e.g. path tracing).
static public Vector3[] m_DecalDatasWSPositions = new Vector3[kDecalBlockSize];
static public Vector3[] m_DecalDatasWSRanges = new Vector3[kDecalBlockSize];
-
+
static public int m_DecalDatasCount = 0;
static public float[] m_BoundingDistances = new float[1];
@@ -638,7 +638,7 @@ public void InitializeMaterialValues()
float normalBlendSrc = 0.0f;
float maskBlendSrc = 1.0f;
m_BlendParams = new Vector3(normalBlendSrc, maskBlendSrc, (float)affectFlags);
-
+
m_SampleNormalAlpha = 1.0f;
// Metallic, AO and Smoothness remapping can be done directly in the shader graph
// By hard coding those values we do an additional lerp within EvalDecalMask which could be avoided
@@ -648,7 +648,7 @@ public void InitializeMaterialValues()
m_ScalingBlueMaskMap = 1.0f;
m_RemappingMetallic = new Vector2(remapMin, remapMax);
m_RemappingAOS = new Vector4(remapMin, remapMax, remapMin, remapMax);
-
+
// With ShaderGraph it is possible that the pass isn't generated. But if it is, it can be disabled.
m_cachedProjectorPassValue = m_Material.FindPass(s_MaterialDecalPassNames[(int)MaterialDecalPass.DBufferProjector]);
if (m_cachedProjectorPassValue != -1 && m_Material.GetShaderPassEnabled(s_MaterialDecalPassNames[(int)MaterialDecalPass.DBufferProjector]) == false)
@@ -938,7 +938,7 @@ public void CreateDrawData(IntScalableSetting transparentTextureResolution)
var camera = instance.CurrentCamera;
Matrix4x4 worldToView = HDRenderPipeline.WorldToCamera(camera);
- /* Prepare data for the DBuffer drawing */
+ /* Prepare data for the DBuffer drawing */
if ((DecalSystem.m_CullingMode & DecalCullingMode.ViewspaceBasedCulling) != 0)
{
int cullingMask = camera.cullingMask;
@@ -960,7 +960,7 @@ public void CreateDrawData(IntScalableSetting transparentTextureResolution)
int decalMask = 1 << m_CachedLayerMask[decalIndex];
ulong decalSceneCullingMask = m_CachedSceneLayerMask[decalIndex];
bool sceneViewCullingMaskTest = true;
-#if UNITY_EDITOR
+#if UNITY_EDITOR
// In the player, both masks will be zero. Besides we don't want to pay the cost in this case.
sceneViewCullingMaskTest = (sceneCullingMask & decalSceneCullingMask) != 0;
#endif
@@ -1611,7 +1611,7 @@ public void UpdateTextureAtlas(CommandBuffer cmd)
public void CreateDrawData()
{
- // Reset number of clustered decals
+ // Reset number of clustered decals
m_DecalDatasCount = 0;
// Count the current maximum number of decals to cluster, to allow reallocation if needed
int maxDecalsToCluster = m_DecalsVisibleThisFrame;
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeCausticLUTGen.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeCausticLUTGen.compute
index 0bbda47c8a8..db6459fe330 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeCausticLUTGen.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Eye/EyeCausticLUTGen.compute
@@ -1,7 +1,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel SampleCaustic
#pragma kernel CopyToLUT
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/CharlieConvolve.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/CharlieConvolve.shader
index 2abe11988b7..e38d6d340f2 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/CharlieConvolve.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Fabric/CharlieConvolve.shader
@@ -12,7 +12,7 @@ Shader "Hidden/HDRP/CharlieConvolve"
HLSLPROGRAM
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma vertex Vert
#pragma fragment Frag
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/FallbackError.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/FallbackError.shader
index 57481aab0fa..614be368887 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/FallbackError.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/FallbackError.shader
@@ -8,7 +8,7 @@ Shader "Hidden/HDRP/FallbackError"
{
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma vertex vert
#pragma fragment frag
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/BuildProbabilityTables.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/BuildProbabilityTables.compute
index 14b989165d3..a328d3710df 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/BuildProbabilityTables.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/BuildProbabilityTables.compute
@@ -8,7 +8,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
/* --- Input --- */
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/ComputeGgxIblSampleData.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/ComputeGgxIblSampleData.compute
index c065c16b398..6d08815b90b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/ComputeGgxIblSampleData.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/ComputeGgxIblSampleData.compute
@@ -3,9 +3,9 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
-#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH)
+#if defined(SHADER_API_MOBILE) || defined(SHADER_API_SWITCH) || defined(SHADER_API_SWITCH2)
#define MAX_IBL_SAMPLE_CNT 34
#else
#define MAX_IBL_SAMPLE_CNT 89
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/GGXConvolve.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/GGXConvolve.shader
index 440a45fd72b..ab1f14b8ffe 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/GGXConvolve.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/GGXConvolution/GGXConvolve.shader
@@ -13,7 +13,7 @@ Shader "Hidden/HDRP/GGXConvolve"
HLSLPROGRAM
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_local_fragment _ USE_MIS
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/MultipleScattering/HairMultipleScatteringPreIntegration.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/MultipleScattering/HairMultipleScatteringPreIntegration.compute
index ffe89bafa46..f30d4c97a44 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/MultipleScattering/HairMultipleScatteringPreIntegration.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Hair/MultipleScattering/HairMultipleScatteringPreIntegration.compute
@@ -3,7 +3,7 @@
#pragma kernel ComputeAzimuthalScattering
#pragma kernel ComputeLongitudinalScattering
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// This define is required for invoking BSDF.
#define HAS_LIGHTLOOP
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LTCAreaLight/FilterAreaLightCookies.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LTCAreaLight/FilterAreaLightCookies.shader
index 6dd280039d3..403b7bdaa21 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LTCAreaLight/FilterAreaLightCookies.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LTCAreaLight/FilterAreaLightCookies.shader
@@ -2,7 +2,7 @@ Shader "Hidden/CoreResources/FilterAreaLightCookies"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma editor_sync_compilation
#pragma vertex Vert
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader
index 1195e8f0bee..68fbf401ff6 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLit.shader
@@ -586,7 +586,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -624,7 +624,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -671,7 +671,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -769,7 +769,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -866,7 +866,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -934,7 +934,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -977,7 +977,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -1055,7 +1055,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -1186,7 +1186,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define SHADERPASS SHADERPASS_CONSTANT
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl"
@@ -1213,7 +1213,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -1245,7 +1245,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -1300,7 +1300,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -1352,7 +1352,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -1398,7 +1398,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#define SHADERPASS SHADERPASS_RAYTRACING_VISIBILITY
@@ -1429,7 +1429,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -1470,7 +1470,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma shader_feature_local_raytracing _DISABLE_DECALS
@@ -1499,7 +1499,7 @@ Shader "HDRP/LayeredLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader
index 2517df4c3ee..b3594cdf389 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/LayeredLit/LayeredLitTessellation.shader
@@ -619,7 +619,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -663,7 +663,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -712,7 +712,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -813,7 +813,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -912,7 +912,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -983,7 +983,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -1028,7 +1028,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -1108,7 +1108,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -1242,7 +1242,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define SHADERPASS SHADERPASS_CONSTANT
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Material.hlsl"
@@ -1271,7 +1271,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
@@ -1304,7 +1304,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
@@ -1362,7 +1362,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
@@ -1417,7 +1417,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
@@ -1466,7 +1466,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
@@ -1500,7 +1500,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
@@ -1543,7 +1543,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#define SHADERPASS SHADERPASS_RAYTRACING_DEBUG
@@ -1572,7 +1572,7 @@ Shader "HDRP/LayeredLitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.shader
index 77386cd71ea..00107110805 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.shader
@@ -358,7 +358,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
@@ -398,7 +398,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
@@ -448,7 +448,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -535,7 +535,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -612,7 +612,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -656,7 +656,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -721,7 +721,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -789,7 +789,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -851,7 +851,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -979,7 +979,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -1097,7 +1097,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -1134,7 +1134,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
@@ -1163,7 +1163,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -1195,7 +1195,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -1258,7 +1258,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -1317,7 +1317,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -1366,7 +1366,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#define SHADERPASS SHADERPASS_RAYTRACING_VISIBILITY
@@ -1401,7 +1401,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -1442,7 +1442,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma shader_feature_local_raytracing _DISABLE_DECALS
@@ -1472,7 +1472,7 @@ Shader "HDRP/Lit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitTessellation.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitTessellation.shader
index 64bb9e09131..7386093ebf9 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitTessellation.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/LitTessellation.shader
@@ -235,7 +235,7 @@ Shader "HDRP/LitTessellation"
HLSLINCLUDE
#pragma target 5.0
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//-------------------------------------------------------------------------------------
// Variant
@@ -376,7 +376,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
@@ -418,7 +418,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
@@ -470,7 +470,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -554,7 +554,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -632,7 +632,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -678,7 +678,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -745,7 +745,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -816,7 +816,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -879,7 +879,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -1007,7 +1007,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -1123,7 +1123,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -1161,7 +1161,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// enable dithering LOD crossfade
#pragma multi_compile _ LOD_FADE_CROSSFADE
@@ -1192,7 +1192,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma instancing_options renderinglayer
@@ -1226,7 +1226,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#undef TESSELLATION_ON
@@ -1286,7 +1286,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#undef TESSELLATION_ON
@@ -1342,7 +1342,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#undef TESSELLATION_ON
@@ -1393,7 +1393,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#undef TESSELLATION_ON
@@ -1430,7 +1430,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#undef TESSELLATION_ON
@@ -1473,7 +1473,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma shader_feature_local_raytracing _DISABLE_DECALS
@@ -1503,7 +1503,7 @@ Shader "HDRP/LitTessellation"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#undef TESSELLATION_ON
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/MaterialExtension.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/MaterialExtension.cs
index 8e79cfb7169..e4bcfb9cb32 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/MaterialExtension.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/MaterialExtension.cs
@@ -275,6 +275,7 @@ internal enum ShaderID
SG_Decal,
SG_Eye,
SG_Water,
+ SG_TerrainLit,
SG_WaterDecal,
SG_FogVolume,
SG_SixWay,
@@ -333,6 +334,7 @@ internal enum ShaderID
{ ShaderID.SG_StackLit, ShaderGraphAPI.ValidateLightingMaterial },
{ ShaderID.SG_Decal, ShaderGraphAPI.ValidateDecalMaterial },
{ ShaderID.SG_Eye, ShaderGraphAPI.ValidateLightingMaterial },
+ { ShaderID.SG_TerrainLit, ShaderGraphAPI.ValidateTerrain },
{ ShaderID.SG_FogVolume, ShaderGraphAPI.ValidateFogVolumeMaterial },
{ ShaderID.SG_SixWay, ShaderGraphAPI.ValidateSixWayMaterial },
{ ShaderID.SG_WaterDecal, ShaderGraphAPI.ValidateWaterDecalMaterial },
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD_Marschner.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD_Marschner.shader
index 1b9c823b8d2..2b0b30f412f 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD_Marschner.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/PreIntegratedFGD_Marschner.shader
@@ -14,7 +14,7 @@ Shader "Hidden/HDRP/PreIntegratedFGD_Marschner"
#pragma vertex Vert
#pragma fragment Frag
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define PREFER_HALF 0
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_CharlieFabricLambert.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_CharlieFabricLambert.shader
index 7007bac0a86..68f6c9018ed 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_CharlieFabricLambert.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_CharlieFabricLambert.shader
@@ -14,7 +14,7 @@ Shader "Hidden/HDRP/preIntegratedFGD_CharlieFabricLambert"
#pragma vertex Vert
#pragma fragment Frag
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define PREFER_HALF 0
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_GGXDisneyDiffuse.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_GGXDisneyDiffuse.shader
index 433970d02f9..db0dda96b1b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_GGXDisneyDiffuse.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/PreIntegratedFGD/preIntegratedFGD_GGXDisneyDiffuse.shader
@@ -14,7 +14,7 @@ Shader "Hidden/HDRP/preIntegratedFGD_GGXDisneyDiffuse"
#pragma vertex Vert
#pragma fragment Frag
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define PREFER_HALF 0
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/ShaderGraphAPI.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/ShaderGraphAPI.cs
index a703d8e293e..93ac0673cb6 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/ShaderGraphAPI.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/ShaderGraphAPI.cs
@@ -89,6 +89,11 @@ public static void ValidateDecalMaterial(Material material)
DecalAPI.SetupCommonDecalMaterialKeywordsAndPass(material);
}
+ public static void ValidateTerrain(Material material)
+ {
+ TerrainLitAPI.ValidateMaterial(material);
+ }
+
public static void ValidateFogVolumeMaterial(Material material)
{
FogVolumeAPI.SetupFogVolumeKeywordsAndProperties(material);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/CombineLighting.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/CombineLighting.shader
index b2ae0f27954..459d6859f23 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/CombineLighting.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/CombineLighting.shader
@@ -10,7 +10,7 @@ Shader "Hidden/HDRP/CombineLighting"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
#pragma vertex Vert
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/RandomDownsample.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/RandomDownsample.compute
index 787228ea0e5..2e4ebce9f1c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/RandomDownsample.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/RandomDownsample.compute
@@ -3,7 +3,7 @@
//--------------------------------------------------------------------------------------------------
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel Downsample
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubSurfaceScattering.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubSurfaceScattering.cs
index 63a89f7365b..4d04a62d646 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubSurfaceScattering.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubSurfaceScattering.cs
@@ -9,6 +9,7 @@ namespace UnityEngine.Rendering.HighDefinition
[Serializable, VolumeComponentMenu("Ray Tracing/SubSurface Scattering")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("Ray-Traced-Subsurface-Scattering")]
+ [DisplayInfo(name = "SubSurface Scattering")]
public sealed class SubSurfaceScattering : VolumeComponent
{
///
@@ -22,12 +23,5 @@ public sealed class SubSurfaceScattering : VolumeComponent
///
[Tooltip("Number of samples for sub-surface scattering.")]
public ClampedIntParameter sampleCount = new ClampedIntParameter(1, 1, 32);
- ///
- /// Default constructor for the subsurface scattering volume component.
- ///
- public SubSurfaceScattering()
- {
- displayName = "SubSurface Scattering";
- }
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.compute
index c275b1cc40a..70223e8a7ac 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/SubsurfaceScattering/SubsurfaceScattering.compute
@@ -5,7 +5,7 @@
//--------------------------------------------------------------------------------------------------
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel SubsurfaceScattering
#pragma kernel PackDiffusionProfile PACK_DIFFUSION_PROFILE
@@ -37,7 +37,7 @@
// Check for support of typed UAV loads from FORMAT_R16G16B16A16_FLOAT.
// TODO: query the format support more precisely.
-#if !(defined(SHADER_API_PSSL) || defined(SHADER_API_XBOXONE) || defined(SHADER_API_GAMECORE)) || defined(ENABLE_MSAA)
+#if !(defined(SHADER_API_PSSL) || defined(SHADER_API_XBOXONE) || defined(SHADER_API_GAMECORE) || defined(SHADER_API_SWITCH2)) || defined(ENABLE_MSAA)
#define USE_INTERMEDIATE_BUFFER
#endif
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.hlsl b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.hlsl
new file mode 100644
index 00000000000..c7ed157b6f8
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.hlsl
@@ -0,0 +1,12 @@
+
+#if SHADERPASS == SHADERPASS_DEPTH_ONLY
+ #ifdef WRITE_NORMAL_BUFFER
+ #if defined(_NORMALMAP)
+ #define OVERRIDE_SPLAT_SAMPLER_NAME sampler_Normal0
+ #elif defined(_MASKMAP)
+ #define OVERRIDE_SPLAT_SAMPLER_NAME sampler_Mask0
+ #endif
+ #endif
+#endif
+
+#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Lit/Lit.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.hlsl.meta b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.hlsl.meta
new file mode 100644
index 00000000000..fd7e9b99ca1
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.hlsl.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 935e239fbabf4124d9476c92c47c8fa7
+ShaderImporter:
+ externalObjects: {}
+ defaultTextures: []
+ nonModifiableTextures: []
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader
index b774c332c80..bdb2892316f 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit.shader
@@ -122,7 +122,7 @@ Shader "HDRP/TerrainLit"
}
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// All our shaders use same name for entry point
#pragma vertex Vert
#pragma fragment Frag
@@ -160,7 +160,7 @@ Shader "HDRP/TerrainLit"
Cull Off
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// All our shaders use same name for entry point
#pragma vertex Vert
#pragma fragment Frag
@@ -195,7 +195,7 @@ Shader "HDRP/TerrainLit"
ColorMask 0
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// All our shaders use same name for entry point
#pragma vertex Vert
#pragma fragment Frag
@@ -230,7 +230,7 @@ Shader "HDRP/TerrainLit"
ZWrite On
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// All our shaders use same name for entry point
#pragma vertex Vert
#pragma fragment Frag
@@ -278,7 +278,7 @@ Shader "HDRP/TerrainLit"
Cull [_CullMode]
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// All our shaders use same name for entry point
#pragma vertex Vert
#pragma fragment Frag
@@ -321,7 +321,7 @@ Shader "HDRP/TerrainLit"
Cull Off
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// All our shaders use same name for entry point
#pragma vertex Vert
#pragma fragment Frag
@@ -366,7 +366,7 @@ Shader "HDRP/TerrainLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -401,7 +401,7 @@ Shader "HDRP/TerrainLit"
Tags{ "LightMode" = "ForwardDXR" }
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -437,7 +437,7 @@ Shader "HDRP/TerrainLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -470,7 +470,7 @@ Shader "HDRP/TerrainLit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
@@ -491,7 +491,7 @@ Shader "HDRP/TerrainLit"
Tags{ "LightMode" = "DebugDXR" }
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
@@ -517,7 +517,7 @@ Shader "HDRP/TerrainLit"
Tags{ "LightMode" = "PathTracingDXR" }
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitAPI.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitAPI.cs
index f82c908395e..e8c9e64e7a6 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitAPI.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitAPI.cs
@@ -29,8 +29,29 @@ public static void ValidateMaterial(Material material)
bool enableInstancedPerPixelNormal = material.HasProperty(kEnableInstancedPerPixelNormal) && material.GetFloat(kEnableInstancedPerPixelNormal) > 0.0f;
CoreUtils.SetKeyword(material, "_TERRAIN_INSTANCED_PERPIXEL_NORMAL", enableInstancedPerPixelNormal);
- int specOcclusionMode = material.GetInt(kSpecularOcclusionMode);
- CoreUtils.SetKeyword(material, "_SPECULAR_OCCLUSION_NONE", specOcclusionMode == 0);
+ // check if it has 'kSpecularOcclusionMode', because a shadergraph of terrain doesn't have it.
+ // the terrain-shadergraph's specular occlusion option is handled on shadergraph's way
+ if (material.HasInt(kSpecularOcclusionMode))
+ {
+ int specOcclusionMode = material.GetInt(kSpecularOcclusionMode);
+ CoreUtils.SetKeyword(material, "_SPECULAR_OCCLUSION_NONE", specOcclusionMode == 0);
+ }
+ }
+
+ public static void SetupLayersMappingKeywords(Material material)
+ {
+ const string kLayerMappingPlanar = "_LAYER_MAPPING_PLANAR";
+ const string kLayerMappingTriplanar = "_LAYER_MAPPING_TRIPLANAR";
+
+ for (int i = 0; i < kMaxLayerCount; ++i)
+ {
+ string layerUVBaseParam = string.Format("{0}{1}", kUVBase, i);
+ UVBaseMapping layerUVBaseMapping = (UVBaseMapping)material.GetFloat(layerUVBaseParam);
+ string currentLayerMappingPlanar = string.Format("{0}{1}", kLayerMappingPlanar, i);
+ CoreUtils.SetKeyword(material, currentLayerMappingPlanar, layerUVBaseMapping == UVBaseMapping.Planar);
+ string currentLayerMappingTriplanar = string.Format("{0}{1}", kLayerMappingTriplanar, i);
+ CoreUtils.SetKeyword(material, currentLayerMappingTriplanar, layerUVBaseMapping == UVBaseMapping.Triplanar);
+ }
}
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitTemplate.hlsl.meta b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitTemplate.hlsl.meta
index fd7e9b99ca1..4330668937e 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitTemplate.hlsl.meta
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLitTemplate.hlsl.meta
@@ -1,9 +1,7 @@
fileFormatVersion: 2
-guid: 935e239fbabf4124d9476c92c47c8fa7
-ShaderImporter:
+guid: 5fb31de5873235a4592bd395dcb73a6d
+ShaderIncludeImporter:
externalObjects: {}
- defaultTextures: []
- nonModifiableTextures: []
userData:
assetBundleName:
assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader
index 95b1f98874c..04e6633db21 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Basemap.shader
@@ -42,7 +42,7 @@ Shader "Hidden/HDRP/TerrainLit_Basemap"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma shader_feature_local _DISABLE_DECALS
#pragma shader_feature_local _TERRAIN_INSTANCED_PERPIXEL_NORMAL
@@ -266,7 +266,7 @@ Shader "Hidden/HDRP/TerrainLit_Basemap"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -301,7 +301,7 @@ Shader "Hidden/HDRP/TerrainLit_Basemap"
Tags{ "LightMode" = "ForwardDXR" }
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -337,7 +337,7 @@ Shader "Hidden/HDRP/TerrainLit_Basemap"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -370,7 +370,7 @@ Shader "Hidden/HDRP/TerrainLit_Basemap"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
@@ -391,7 +391,7 @@ Shader "Hidden/HDRP/TerrainLit_Basemap"
Tags{ "LightMode" = "DebugDXR" }
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
@@ -417,7 +417,7 @@ Shader "Hidden/HDRP/TerrainLit_Basemap"
Tags{ "LightMode" = "PathTracingDXR" }
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_BasemapGen.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_BasemapGen.shader
index b4c3d0f6014..19d4050295c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_BasemapGen.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_BasemapGen.shader
@@ -12,7 +12,7 @@ Shader "Hidden/HDRP/TerrainLit_BasemapGen"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define SURFACE_GRADIENT // Must use Surface Gradient as the normal map texture format is now RG floating point
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap_Includes.hlsl b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap_Includes.hlsl
index 80bf02afbe8..5524c1e89c1 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap_Includes.hlsl
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/TerrainLit/TerrainLit_Splatmap_Includes.hlsl
@@ -10,6 +10,7 @@
#define DECLARE_TERRAIN_LAYER_PROPS(n) \
float4 _Splat##n##_ST; \
+ float4 _Splat##n##_TexelSize; \
float _Metallic##n; \
float _Smoothness##n; \
float _NormalScale##n; \
@@ -43,19 +44,11 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/DebugMipmapStreamingMacros.hlsl"
#define UNITY_TERRAIN_CB_DEBUG_VARS \
UNITY_TEXTURE_STREAMING_DEBUG_VARS_FOR_TEX(_Control0); \
- float4 _Splat0_TexelSize; \
UNITY_TEXTURE_STREAMING_DEBUG_VARS_FOR_TEX(_Splat0); \
- float4 _Splat1_TexelSize; \
UNITY_TEXTURE_STREAMING_DEBUG_VARS_FOR_TEX(_Splat1); \
- float4 _Splat2_TexelSize; \
UNITY_TEXTURE_STREAMING_DEBUG_VARS_FOR_TEX(_Splat2); \
- float4 _Splat3_TexelSize; \
UNITY_TEXTURE_STREAMING_DEBUG_VARS_FOR_TEX(_Splat3); \
- float4 _Splat4_TexelSize; \
UNITY_TEXTURE_STREAMING_DEBUG_VARS_FOR_TEX(_Splat4); \
- float4 _Splat5_TexelSize; \
UNITY_TEXTURE_STREAMING_DEBUG_VARS_FOR_TEX(_Splat5); \
- float4 _Splat6_TexelSize; \
UNITY_TEXTURE_STREAMING_DEBUG_VARS_FOR_TEX(_Splat6); \
- float4 _Splat7_TexelSize; \
UNITY_TEXTURE_STREAMING_DEBUG_VARS_FOR_TEX(_Splat7);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.shader
index ae8e7970867..59fcfa7761e 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Unlit/Unlit.shader
@@ -96,7 +96,7 @@ Shader "HDRP/Unlit"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//-------------------------------------------------------------------------------------
// Variant
@@ -149,7 +149,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -193,7 +193,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -239,7 +239,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -288,7 +288,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -328,7 +328,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -375,7 +375,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -414,7 +414,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -449,7 +449,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
#pragma multi_compile _ DOTS_INSTANCING_ON
@@ -484,7 +484,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -519,7 +519,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ DEBUG_DISPLAY
@@ -553,7 +553,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
// Keyword for transparent
@@ -588,7 +588,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#define SHADOW_LOW
@@ -624,7 +624,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
// Keyword for transparent
@@ -652,7 +652,7 @@ Shader "HDRP/Unlit"
HLSLPROGRAM
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma raytracing surface_shader
#pragma multi_compile _ SENSORSDK_OVERRIDE_REFLECTANCE
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/VolumetricMaterial/VolumetricMaterial.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/VolumetricMaterial/VolumetricMaterial.compute
index c7e59a0e8c8..c72bfc60746 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/VolumetricMaterial/VolumetricMaterial.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Material/VolumetricMaterial/VolumetricMaterial.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel ComputeVolumetricMaterialRenderingParameters
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/LiftGammaGain.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/LiftGammaGain.cs
index 4f9fcfc87f9..6ed1394732b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/LiftGammaGain.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/LiftGammaGain.cs
@@ -8,6 +8,7 @@ namespace UnityEngine.Rendering.HighDefinition
[Serializable, VolumeComponentMenu("Post-processing/Lift, Gamma, Gain")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("Post-Processing-Lift-Gamma-Gain")]
+ [DisplayInfo(name = "Lift, Gamma, Gain")]
public sealed class LiftGammaGain : VolumeComponent, IPostProcessComponent
{
///
@@ -36,7 +37,5 @@ public bool IsActive()
|| gamma != defaultState
|| gain != defaultState;
}
-
- LiftGammaGain() => displayName = "Lift, Gamma, Gain";
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/ScreenSpaceLensFlare.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/ScreenSpaceLensFlare.cs
index b468979ec8d..4ae29ce7cfc 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/ScreenSpaceLensFlare.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/ScreenSpaceLensFlare.cs
@@ -29,6 +29,7 @@ public enum ScreenSpaceLensFlareResolution : int
[Serializable, VolumeComponentMenu("Post-processing/Screen Space Lens Flare")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("shared/lens-flare/Override-Screen-Space-Lens-Flare")]
+ [DisplayInfo(name = "Screen Space Lens Flare")]
public class ScreenSpaceLensFlare : VolumeComponent, IPostProcessComponent
{
///
@@ -119,13 +120,6 @@ public class ScreenSpaceLensFlare : VolumeComponent, IPostProcessComponent
/// Controls the number of samples HDRP uses to render the Chromatic Aberration effect. A lower sample number results in better performance.
///
public ClampedIntParameter chromaticAbberationSampleCount = new ClampedIntParameter(3, 3, 8);
- ///
- /// Default constructor for the lens flare volume component.
- ///
- public ScreenSpaceLensFlare()
- {
- displayName = "Screen Space Lens Flare";
- }
///
/// Mandatory function, cannot have an Override without it
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/ShadowsMidtonesHighlights.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/ShadowsMidtonesHighlights.cs
index 16ff59e44aa..91a133bedba 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/ShadowsMidtonesHighlights.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Components/ShadowsMidtonesHighlights.cs
@@ -8,6 +8,7 @@ namespace UnityEngine.Rendering.HighDefinition
[Serializable, VolumeComponentMenu("Post-processing/Shadows, Midtones, Highlights")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("Post-Processing-Shadows-Midtones-Highlights")]
+ [DisplayInfo(name = "Shadows, Midtones, Highlights")]
public sealed class ShadowsMidtonesHighlights : VolumeComponent, IPostProcessComponent
{
///
@@ -62,7 +63,5 @@ public bool IsActive()
|| midtones != defaultState
|| highlights != defaultState;
}
-
- ShadowsMidtonesHighlights() => displayName = "Shadows, Midtones, Highlights";
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/AlphaCopy.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/AlphaCopy.compute
index 58115afca88..940a970539a 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/AlphaCopy.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/AlphaCopy.compute
@@ -1,6 +1,6 @@
#pragma kernel KMain
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ApplyExposure.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ApplyExposure.compute
index 28d11250d68..528ab4d55ac 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ApplyExposure.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ApplyExposure.compute
@@ -1,7 +1,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain
#pragma multi_compile _ ENABLE_ALPHA
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomBlur.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomBlur.compute
index 19e8bac5db7..e2ef0ab3aac 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomBlur.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomBlur.compute
@@ -4,7 +4,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/DynamicScalingClamping.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain MAIN=KMain
#pragma kernel KDownsample MAIN=KDownsample DOWNSAMPLE
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute
index 9681b96b00e..4bd25f60f64 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomPrefilter.compute
@@ -5,7 +5,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomCommon.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostProcessDefines.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomUpsample.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomUpsample.compute
index 5c55ec25e34..e7785787142 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomUpsample.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomUpsample.compute
@@ -3,7 +3,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/DynamicScalingClamping.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ClearBlack.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ClearBlack.shader
index 7393964fa13..083269a5f2f 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ClearBlack.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ClearBlack.shader
@@ -3,7 +3,7 @@ Shader "Hidden/HDRP/ClearBlack"
HLSLINCLUDE
#pragma target 4.5
#pragma editor_sync_compilation
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/CompositeWithUIAndOETF.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/CompositeWithUIAndOETF.shader
index 557bc105ea8..3cafebfa39d 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/CompositeWithUIAndOETF.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/CompositeWithUIAndOETF.shader
@@ -3,7 +3,7 @@ Shader "Hidden/HDRP/CompositeUI"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma editor_sync_compilation
#pragma multi_compile_local_fragment _ APPLY_AFTER_POST
#pragma multi_compile_local _ DISABLE_TEXTURE2D_X_ARRAY
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ContrastAdaptiveSharpen.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ContrastAdaptiveSharpen.compute
index 68b4a216083..a5c24818fbf 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ContrastAdaptiveSharpen.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ContrastAdaptiveSharpen.compute
@@ -2,7 +2,7 @@
#pragma kernel KInitialize
#pragma multi_compile _ HDR_INPUT
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DLSSBiasColorMask.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DLSSBiasColorMask.shader
index ad816c57649..33d2e99267b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DLSSBiasColorMask.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DLSSBiasColorMask.shader
@@ -8,7 +8,7 @@ Shader "Hidden/HDRP/DLSSBiasColorMask"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DebugHDRxyMapping.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DebugHDRxyMapping.compute
index fd9c3cb7c10..b60de61bfdb 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DebugHDRxyMapping.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DebugHDRxyMapping.compute
@@ -4,7 +4,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ACES.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/HDROutput.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KCIExyGen
#define GROUP_SIZE_X 8
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DebugHistogramImage.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DebugHistogramImage.compute
index 5ba9618bb2c..eabd1c9b60c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DebugHistogramImage.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DebugHistogramImage.compute
@@ -3,7 +3,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/PhysicalCamera.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KHistogramGen
#define GROUP_SIZE_X 16
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldClearIndirectArgs.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldClearIndirectArgs.compute
index 3e330cf3267..68a94fc8928 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldClearIndirectArgs.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldClearIndirectArgs.compute
@@ -1,6 +1,6 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KClear
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoC.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoC.compute
index cb9cb8fcb64..2bffa97cf12 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoC.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoC.compute
@@ -2,7 +2,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ USE_MIN_DEPTH // Active when using MSAA
#pragma multi_compile _ FIX_NEAR_BLEND
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCDilate.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCDilate.compute
index 80a4d33f648..51cf76c35ad 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCDilate.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCDilate.compute
@@ -1,7 +1,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCReproject.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCReproject.compute
index bbc5aa95134..7c01a99eb70 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCReproject.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCoCReproject.compute
@@ -2,7 +2,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ ENABLE_MAX_BLENDING
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCombine.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCombine.compute
index fdae7afe892..97537010fea 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCombine.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCombine.compute
@@ -2,7 +2,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Filtering.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute
index 6e83bd8fd69..b831418ba14 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldGather.compute
@@ -2,7 +2,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMainNear MAIN=KMainNear NEAR
#pragma kernel KMainFar MAIN=KMainFar FAR
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldKernel.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldKernel.compute
index 3420365d746..9ea3c7a5f0a 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldKernel.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldKernel.compute
@@ -1,7 +1,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KParametricBlurKernel MAIN=KParametricBlurKernel GROUP_SIZE=64
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMip.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMip.compute
index 7bd488c2f63..7c714608179 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMip.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMip.compute
@@ -1,7 +1,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMainColor MAIN=KMainColor CTYPE=float3
#pragma kernel KMainColorAlpha MAIN=KMainColorAlpha CTYPE=float4
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMipSafe.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMipSafe.compute
index 722eff37a67..b186aa0436b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMipSafe.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldMipSafe.compute
@@ -1,7 +1,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPreCombineFar.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPreCombineFar.compute
index e9ddd43bb69..1a2f77d9eaa 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPreCombineFar.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPreCombineFar.compute
@@ -2,7 +2,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Filtering.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMainPreCombineFar
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPrefilter.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPrefilter.compute
index f2d33556541..ecff97fa3af 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPrefilter.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldPrefilter.compute
@@ -1,7 +1,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ NEAR
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldTileMax.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldTileMax.compute
index 9261be7594d..ea75e9d68ba 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldTileMax.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldTileMax.compute
@@ -2,7 +2,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain
#pragma multi_compile _ NEAR
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFApertureShape.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFApertureShape.compute
index 76df386427d..b69f13b711b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFApertureShape.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFApertureShape.compute
@@ -3,7 +3,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostProcessDefines.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel ComputeShapeBuffer
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCircleOfConfusion.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCircleOfConfusion.compute
index 5c08e05c297..53fc250cb05 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCircleOfConfusion.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCircleOfConfusion.compute
@@ -3,7 +3,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostProcessDefines.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ USE_MIN_DEPTH // Active when using MSAA
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCoCMinMax.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCoCMinMax.compute
index 730835d6b66..f107bf3f480 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCoCMinMax.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCoCMinMax.compute
@@ -3,7 +3,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostProcessDefines.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMainCoCMinMax
TEXTURE2D_X(_InputTexture);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCombine.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCombine.compute
index 9b2552ec649..4738f7df8cf 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCombine.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFCombine.compute
@@ -4,7 +4,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingSampling.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel UpsampleFastTiles
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFComputeSlowTiles.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFComputeSlowTiles.compute
index 99d826e780e..6e9900c3e9c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFComputeSlowTiles.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFComputeSlowTiles.compute
@@ -4,7 +4,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingSampling.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel ComputeSlowTiles
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute
index 508ea385b73..2d42dcc683d 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFGather.compute
@@ -4,7 +4,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingSampling.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFMinMaxDilate.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFMinMaxDilate.compute
index edc10ead1ad..9d0a83487f6 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFMinMaxDilate.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DoFMinMaxDilate.compute
@@ -3,7 +3,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostProcessDefines.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/DepthOfFieldCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain
TEXTURE2D_X(_InputTexture);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/EdgeAdaptiveSpatialUpsampling.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/EdgeAdaptiveSpatialUpsampling.compute
index 6d372ddd86a..8e1aeb4dc67 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/EdgeAdaptiveSpatialUpsampling.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/EdgeAdaptiveSpatialUpsampling.compute
@@ -2,7 +2,7 @@
#pragma multi_compile _ ENABLE_ALPHA
#pragma multi_compile _ HDR_INPUT
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/Exposure.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/Exposure.compute
index bb3837ddc6e..4d68a417dd3 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/Exposure.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/Exposure.compute
@@ -1,6 +1,6 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/ExposureCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KFixedExposure
#pragma kernel KManualCameraExposure
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FXAA.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FXAA.compute
index 4f167835eb0..f1eebe72fa2 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FXAA.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FXAA.compute
@@ -3,7 +3,7 @@
#pragma multi_compile _ ENABLE_ALPHA
#pragma multi_compile _ HDR_INPUT
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FinalPass.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FinalPass.shader
index d8d118481db..bfa71b43af9 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FinalPass.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/FinalPass.shader
@@ -4,7 +4,7 @@ Shader "Hidden/HDRP/FinalPass"
#pragma target 4.5
#pragma editor_sync_compilation
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_fragment _ SCREEN_COORD_OVERRIDE
#pragma multi_compile_local_fragment _ FXAA
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/HistogramExposure.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/HistogramExposure.compute
index dd37def8d17..35e3b2777cb 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/HistogramExposure.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/HistogramExposure.compute
@@ -14,7 +14,7 @@
#pragma multi_compile _ OUTPUT_DEBUG_DATA
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#ifdef GEN_PASS
// Because atomics are only on uint and we need a weighted value, we need to convert.
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareDataDriven.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareDataDriven.shader
index fe8b18e0db1..2095f98fdc2 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareDataDriven.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareDataDriven.shader
@@ -17,7 +17,7 @@ Shader "Hidden/HDRP/LensFlareDataDriven"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma target 5.0
#pragma vertex vert
@@ -49,7 +49,7 @@ Shader "Hidden/HDRP/LensFlareDataDriven"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma target 5.0
#pragma vertex vert
@@ -81,7 +81,7 @@ Shader "Hidden/HDRP/LensFlareDataDriven"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma target 5.0
#pragma vertex vert
@@ -113,7 +113,7 @@ Shader "Hidden/HDRP/LensFlareDataDriven"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma target 5.0
#pragma vertex vert
@@ -143,7 +143,7 @@ Shader "Hidden/HDRP/LensFlareDataDriven"
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma target 5.0
#pragma vertex vertOcclusion
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareMergeOcclusionDataDriven.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareMergeOcclusionDataDriven.compute
index 746cf5e4ffa..5b9fbdba16a 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareMergeOcclusionDataDriven.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareMergeOcclusionDataDriven.compute
@@ -2,7 +2,7 @@
//--------------------------------------------------------------------------------------------------
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel MainCS
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareScreenSpace.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareScreenSpace.shader
index 25b6832d172..47afa59591b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareScreenSpace.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LensFlareScreenSpace.shader
@@ -14,7 +14,7 @@ Shader "Hidden/HDRP/LensFlareScreenSpace"
ZTest Always
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma target 5.0
#pragma vertex vert
@@ -39,7 +39,7 @@ Shader "Hidden/HDRP/LensFlareScreenSpace"
ZTest Always
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma target 5.0
#pragma vertex vert
@@ -64,7 +64,7 @@ Shader "Hidden/HDRP/LensFlareScreenSpace"
ZTest Always
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma target 5.0
#pragma vertex vert
@@ -89,7 +89,7 @@ Shader "Hidden/HDRP/LensFlareScreenSpace"
ZTest Always
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma target 5.0
#pragma vertex vert
@@ -116,7 +116,7 @@ Shader "Hidden/HDRP/LensFlareScreenSpace"
ZTest Always
HLSLPROGRAM
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma target 5.0
#pragma vertex vert
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LutBuilder3D.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LutBuilder3D.compute
index 984540ebd15..3c239ad63fa 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LutBuilder3D.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/LutBuilder3D.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile TONEMAPPING_NONE TONEMAPPING_NEUTRAL TONEMAPPING_ACES_APPROX TONEMAPPING_ACES_FULL TONEMAPPING_CUSTOM TONEMAPPING_EXTERNAL
#pragma multi_compile_local _ HDR_COLORSPACE_CONVERSION
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlur.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlur.compute
index f8c2a1d2962..bd1f2a9b954 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlur.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlur.compute
@@ -1,7 +1,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurCommon.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostProcessDefines.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel MotionBlurCS
@@ -182,7 +182,7 @@ float3 BlendMotionBlurLayers(float3 centralColor, float4 accumulation, float sca
// accumulation - rgb hold the unormalized weighted sum of the blur kernel. So Sum(c * w[i]). The w component holds the sum of all the weights Sum(w[i])
// scatterNeighborhoodIntensity - Within the tile (neighborhood) how blurry this pixel will look like. High value means this pixels motion vector has a high intensity relative to neighborhood, and viceversa
// invSampleCount - reciprocal of number of samples added in accumulation (1.0 / N)
- //
+ //
// Explanation of blur algorithm:
// We split this blend into a top layer, and a back layer.
// Top layer -
@@ -192,7 +192,7 @@ float3 BlendMotionBlurLayers(float3 centralColor, float4 accumulation, float sca
// is the unormalized / low intensity color bleeding into background pixels. This looks good when a foreground object is moving fast, and the background is static. It however adds a ringing artifact when the background is fast moving and the foreground is static.
// To get the best of both results, we blend them depending on how much the current pixel has to scatter. If the current pixel scatters a lot (high motion vector intensity relative to tile) we opt for a top layer.
// on the other hand, if the current pixel doesn't scatter as much (has a low intensity motion vector) we are ok showing more of the bottom layer.
-
+
float3 topLayerColor = accumulation.w < 1e-4 ? centralColor.rgb : accumulation.rgb/accumulation.w;
float topLayerAlpha = accumulation.w * invSampleCount;
float3 backLayerColor = lerp(centralColor.rgb, topLayerColor, topLayerAlpha);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurGenTilePass.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurGenTilePass.compute
index 51c072f7736..4e608d9d170 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurGenTilePass.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurGenTilePass.compute
@@ -1,6 +1,6 @@
#pragma kernel TileGenPass GEN_PASS
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ SCATTERING
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurTileCommon.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMergeTilePass.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMergeTilePass.compute
index 703c3c86adb..bf92d87e716 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMergeTilePass.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMergeTilePass.compute
@@ -1,5 +1,5 @@
#pragma kernel TileMerge MERGE_PASS SCATTERING
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurTileCommon.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMotionVecPrep.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMotionVecPrep.compute
index 5323ccad0b1..1b9ba8bf071 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMotionVecPrep.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurMotionVecPrep.compute
@@ -2,7 +2,7 @@
#pragma kernel MotionVecPreppingCS MOTION_VEC_PREPPING
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define SKIP_PREPPING_IF_NOT_NEEDED defined(PLATFORM_SUPPORTS_WAVE_INTRINSICS)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurNeighborhoodTilePass.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurNeighborhoodTilePass.compute
index c718e275c73..c8589974b9e 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurNeighborhoodTilePass.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurNeighborhoodTilePass.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel TileNeighbourhood NEIGHBOURHOOD_PASS
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/MotionBlurTileCommon.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/NaNKiller.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/NaNKiller.compute
index d1a35847d0a..3fdc0088933 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/NaNKiller.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/NaNKiller.compute
@@ -1,6 +1,6 @@
#pragma kernel KMain
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute
index 99d6c27797a..0a7da205660 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PaniniProjection.compute
@@ -2,7 +2,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostProcessDefines.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KMain
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostSharpenPass.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostSharpenPass.compute
index 5838f12e9dd..65fed312b99 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostSharpenPass.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/PostSharpenPass.compute
@@ -6,7 +6,7 @@
#pragma kernel SharpenCS
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
TEXTURE2D_X(_InputTexture);
RW_TEXTURE2D_X(CTYPE, _OutputTexture);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.shader
index 2a337f6ba69..1d34f6f6415 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/SubpixelMorphologicalAntialiasing.shader
@@ -8,7 +8,7 @@ Shader "Hidden/PostProcessing/SubpixelMorphologicalAntialiasing"
HLSLINCLUDE
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_fragment SMAA_PRESET_LOW SMAA_PRESET_MEDIUM SMAA_PRESET_HIGH
#pragma editor_sync_compilation
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntiAliasing.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntiAliasing.shader
index b973fbf5ee5..4f74a5785cb 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntiAliasing.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/TemporalAntiAliasing.shader
@@ -20,7 +20,7 @@ Shader "Hidden/HDRP/TemporalAA"
#pragma editor_sync_compilation
// #pragma enable_d3d11_debug_symbols
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute
index 03d051a8794..8ada7553cd7 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPost.compute
@@ -7,7 +7,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ScreenCoordOverride.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/UberPostFeatures.cs.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/PostProcessing/Shaders/BloomCommon.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel Uber
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/Shaders/Accumulation.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/Shaders/Accumulation.compute
index fab2c80d88a..2e44dfd5042 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/Shaders/Accumulation.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/Shaders/Accumulation.compute
@@ -4,7 +4,7 @@
#pragma kernel KMain
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ INPUT_FROM_FRAME_TEXTURE
#pragma multi_compile _ WRITE_TO_OUTPUT_TEXTURE
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/Shaders/BlitAndExpose.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/Shaders/BlitAndExpose.compute
index 4a3f524854d..a1ea3d73b33 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/Shaders/BlitAndExpose.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Accumulation/Shaders/BlitAndExpose.compute
@@ -6,7 +6,7 @@
#pragma kernel KAddMain
#pragma kernel KAccumMain
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// Input
TEXTURE2D_X(_InputTexture);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.cs
index 43333cb629d..261764a7a59 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDAdditionalCameraData.cs
@@ -393,6 +393,7 @@ public enum TAASharpenMode
/// Transform used when Screen Coordinates Override is active.
public Vector4 screenCoordScaleBias;
+ #region DLSS_OVERRIDES
/// Allow NVIDIA Deep Learning Super Sampling (DLSS) on this camera.
[Tooltip("Allow NVIDIA Deep Learning Super Sampling (DLSS) on this camera")]
public bool allowDeepLearningSuperSampling = true;
@@ -417,7 +418,9 @@ public enum TAASharpenMode
[Tooltip("Sets the Sharpening value for NVIDIA Deep Learning Super Sampling (DLSS) for this camera.")]
[Range(0, 1)]
public float deepLearningSuperSamplingSharpening = 0;
+ #endregion
+ #region FSR2_OVERRIDES
/// Allow FidelityFX Super Resolution (FSR2) on this camera.
[Tooltip("Allow FidelityFX Super Resolution (FSR2) on this camera.")]
public bool allowFidelityFX2SuperResolution = true;
@@ -446,6 +449,7 @@ public enum TAASharpenMode
[Tooltip("Sets the Sharpening value for AMD FidelityFX 2.0 Super Resolution (FSR2) for this camera.")]
[Range(0, 1)]
public float fidelityFX2SuperResolutionSharpening = 0;
+ #endregion
/// internal state set by the runtime wether DLSS is enabled or not on this camera, depending on the results of all other settings.
[ExcludeCopy]
@@ -459,6 +463,17 @@ public enum TAASharpenMode
[ExcludeCopy]
internal bool cameraCanRenderSTP = false;
+#if ENABLE_UPSCALER_FRAMEWORK
+ /// internal state set by the runtime whether the upscaler framework is enabled or not on this camera, depending on the results of all other settings.
+ [ExcludeCopy]
+ internal bool cameraCanRenderIUpscaler = false;
+
+ // internal state set by the runtime whether the upscaler using the framework is a temporal upscaler or not.
+ [ExcludeCopy]
+ internal bool cameraIUpscalerIsTemporalUpscaler = false;
+#endif
+
+ #region FSR1_OVERRIDES
/// If set to true, AMD FidelityFX Super Resolution (FSR) will utilize the sharpness setting set on this camera instead of the one specified in the quality asset.
[Tooltip("If set to true, AMD FidelityFX Super Resolution (FSR) will utilize the sharpness setting set on this camera instead of the one specified in the quality asset.")]
public bool fsrOverrideSharpness = false;
@@ -467,6 +482,7 @@ public enum TAASharpenMode
[Tooltip("Sets this camera's sharpness value for AMD FidelityFX Super Resolution 1.0 (FSR).")]
[Range(0, 1)]
public float fsrSharpness = FSRUtils.kDefaultSharpnessLinear;
+ #endregion
/// Event used to override HDRP rendering for this particular camera.
public event Action customRender;
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs
index f9ea495e583..ce271d1c004 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Camera/HDCamera.cs
@@ -440,6 +440,7 @@ internal void Set(Vector3 cameraPos, VisualEnvironment visualEnv)
internal Action prepareDispatchRays = null;
#endif
+ internal ContextContainer contextContainer;
internal Vector4[] frustumPlaneEquations;
internal int taaFrameIndex;
internal float taaSharpenStrength;
@@ -850,14 +851,14 @@ internal void RequestStpHistory(out bool useHwDrs, out bool hasValidHistory, out
if (isDynResEnabled && !DynResRequest.hardwareEnabled)
Debug.Assert(DynResRequest.forcingResolution);
- Vector2Int preUpscaleSize = new Vector2Int(actualWidth, actualHeight);
- Vector2Int postUpscaleSize = new Vector2Int((int)finalViewport.width, (int)finalViewport.height);
+ Vector2Int preUpscaleResolution = new Vector2Int(actualWidth, actualHeight);
+ Vector2Int postUpscaleResolution = new Vector2Int((int)finalViewport.width, (int)finalViewport.height);
useHwDrs = isDynResEnabled && DynResRequest.hardwareEnabled;
STP.HistoryUpdateInfo info;
- info.preUpscaleSize = preUpscaleSize;
- info.postUpscaleSize = postUpscaleSize;
+ info.preUpscaleSize = preUpscaleResolution;
+ info.postUpscaleSize = postUpscaleResolution;
info.useHwDrs = useHwDrs;
info.useTexArray = TextureXR.useTexArray;
@@ -991,6 +992,10 @@ internal HDCamera(Camera cam)
// Initially, we don't want to clear any history buffer
m_ClearHistoryRequest = false;
+ contextContainer = new ContextContainer();
+#if ENABLE_UPSCALER_FRAMEWORK
+ contextContainer.Create();
+#endif
Reset();
}
@@ -1018,6 +1023,17 @@ internal bool IsSTPEnabled()
return m_AdditionalCameraData == null ? false : m_AdditionalCameraData.cameraCanRenderSTP;
}
+#if ENABLE_UPSCALER_FRAMEWORK
+ internal bool IsIUpscalerEnabled()
+ {
+ return m_AdditionalCameraData == null ? false : m_AdditionalCameraData.cameraCanRenderIUpscaler;
+ }
+ internal bool IsIUpscalerTemporalUpscaler()
+ {
+ return m_AdditionalCameraData == null ? false : m_AdditionalCameraData.cameraIUpscalerIsTemporalUpscaler;
+ }
+#endif
+
internal bool IsPathTracingEnabled()
{
HDRenderPipelineAsset currentAsset = HDRenderPipeline.currentAsset;
@@ -1065,6 +1081,31 @@ internal DynamicResolutionHandler.UpsamplerScheduleType UpsampleSyncPoint()
{
return HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.STPInjectionPoint;
}
+#if ENABLE_UPSCALER_FRAMEWORK
+ else if (IsIUpscalerEnabled())
+ {
+ // get activeUpscalerName
+ // do we need to read this from currentAsset dynamicResolutionSettings upscalerNames (and find the first IUpscaler?)
+ Debug.Assert(HDRenderPipeline.currentPipeline != null);
+ IUpscaler upscaler = HDRenderPipeline.currentPipeline.upscaling.GetActiveUpscaler();
+ Debug.Assert(upscaler != null);
+ string activeUpscalerName = upscaler.GetName();
+
+ // return the injection point of matching options
+ foreach (UpscalerOptions options in HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.IUpscalerOptions)
+ {
+ if (options.UpscalerName == activeUpscalerName)
+ {
+ return options.InjectionPoint;
+ }
+ }
+
+ // options not found, return a default value
+ return IsIUpscalerTemporalUpscaler()
+ ? DynamicResolutionHandler.UpsamplerScheduleType.BeforePost // temporal upscaler
+ : DynamicResolutionHandler.UpsamplerScheduleType.AfterPost; // spatial upscaler
+ }
+#endif
else if (IsTAAUEnabled())
{
return HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.TAAUInjectionPoint;
@@ -1104,7 +1145,12 @@ internal DynamicResolutionHandler.UpsamplerScheduleType UpsampleSyncPoint()
internal bool RequiresCameraJitter()
{
- return (antialiasing == AntialiasingMode.TemporalAntialiasing || IsFSR2Enabled() || IsDLSSEnabled() || IsTAAUEnabled()) && !IsPathTracingEnabled();
+ bool isTemporalUpscaler = IsFSR2Enabled() || IsDLSSEnabled() || IsTAAUEnabled();
+#if ENABLE_UPSCALER_FRAMEWORK
+ isTemporalUpscaler = isTemporalUpscaler || IsIUpscalerTemporalUpscaler();
+#endif
+
+ return (antialiasing == AntialiasingMode.TemporalAntialiasing || isTemporalUpscaler) && !IsPathTracingEnabled();
}
internal bool IsSSREnabled(bool transparent = false)
@@ -1407,6 +1453,21 @@ internal void Update(FrameSettings currentFrameSettings, HDRenderPipeline hdrp,
/// Set the RTHandle scale to the actual camera size (can be scaled)
internal void SetReferenceSize()
{
+#if ENABLE_UPSCALER_FRAMEWORK
+ if (IsIUpscalerEnabled())
+ {
+ // An IUpscaler is active. It might want to change the pre-upscale resolution. Negotiate with it.
+ Debug.Assert(HDRenderPipeline.currentPipeline != null);
+ IUpscaler activeUpscaler = HDRenderPipeline.currentPipeline.upscaling.GetActiveUpscaler();
+ Debug.Assert(activeUpscaler != null);
+ Vector2Int res = new Vector2Int(actualWidth, actualHeight);
+ activeUpscaler.NegotiatePreUpscaleResolution(ref res,
+ new Vector2Int(camera.pixelWidth, camera.pixelHeight));
+ actualWidth = res.x;
+ actualHeight = res.y;
+ }
+#endif
+
RTHandles.SetReferenceSize(actualWidth, actualHeight);
m_HistoryRTSystem.SwapAndSetReferenceSize(actualWidth, actualHeight);
SetPostProcessScreenSize(actualWidth, actualHeight);
@@ -2274,7 +2335,13 @@ internal Matrix4x4 GetJitteredProjectionMatrix(Matrix4x4 origProj)
{
// Do not add extra jitter in VR unless requested (micro-variations from head tracking are usually enough)
// Note: We make an exception for STP since it cannot produce correct results without a specific jitter pattern.
- if (xr.enabled && !HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.xrSettings.cameraJitter && !IsSTPEnabled())
+ if (xr.enabled
+ && !HDRenderPipeline.currentAsset.currentPlatformRenderPipelineSettings.xrSettings.cameraJitter
+ && !IsSTPEnabled()
+#if ENABLE_UPSCALER_FRAMEWORK
+ && !IsIUpscalerEnabled()
+#endif
+ )
{
taaJitter = Vector4.zero;
return origProj;
@@ -2295,6 +2362,21 @@ internal Matrix4x4 GetJitteredProjectionMatrix(Matrix4x4 origProj)
jitterX = stpJit.x;
jitterY = stpJit.y;
}
+#if ENABLE_UPSCALER_FRAMEWORK
+ else if (IsIUpscalerEnabled())
+ {
+ Debug.Assert(HDRenderPipeline.currentPipeline != null);
+ IUpscaler upscaler = HDRenderPipeline.currentPipeline.upscaling.GetActiveUpscaler();
+ Debug.Assert(upscaler != null); // If we're in this condition, upscaler should be non-null.
+ upscaler.CalculateJitter(taaFrameIndex, out Vector2 jitter, out bool allowScaling);
+ // TODO (Apoorva): Re-examine if this negative sign is needed. It's currently there because URP and HDRP
+ // seem to be different in this regard. In URP, the jitter offset is -STP.Jit16(), while in HDRP, it
+ // seems to be STP.Jit16(). Maybe the usage of the jitter vector cancels this sign out, making the math
+ // equivalent. Needs more investigation. Until then, we add a negative sign in HDRP.
+ jitterX = -jitter.x;
+ jitterY = -jitter.y;
+ }
+#endif
else
{
// The variance between 0 and the actual halton sequence values reveals noticeable
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs
index 1116721b2bf..0d1531d0149 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Debug.cs
@@ -848,6 +848,8 @@ class RenderTileClusterDebugOverlayPassData
public BufferHandle tileList;
public BufferHandle lightList;
public BufferHandle perVoxelLightList;
+ public BufferHandle perTileLogBaseTweak;
+ public BufferHandle perVoxelOffset;
public BufferHandle dispatchIndirect;
public Material debugViewTilesMaterial;
public LightingDebugSettings lightingDebugSettings;
@@ -860,7 +862,12 @@ void RenderTileClusterDebugOverlay(RenderGraph renderGraph, TextureHandle colorB
if (!lightLists.tileList.IsValid())
return;
- if (m_CurrentDebugDisplaySettings.data.lightingDebugSettings.tileClusterDebug == TileClusterDebug.None)
+ TileClusterDebug tileClusterDebug = m_CurrentDebugDisplaySettings.data.lightingDebugSettings.tileClusterDebug;
+
+ if (tileClusterDebug == TileClusterDebug.None)
+ return;
+
+ if (tileClusterDebug == TileClusterDebug.MaterialFeatureVariants && !GetFeatureVariantsEnabled(hdCamera.frameSettings))
return;
using (var builder = renderGraph.AddUnsafePass("RenderTileAndClusterDebugOverlay", out var passData, ProfilingSampler.Get(HDProfileId.TileClusterLightingDebug)))
@@ -871,14 +878,27 @@ void RenderTileClusterDebugOverlay(RenderGraph renderGraph, TextureHandle colorB
builder.SetRenderAttachment(colorBuffer, 0);
passData.depthPyramidTexture = depthPyramidTexture;
builder.UseTexture(passData.depthPyramidTexture, AccessFlags.Read);
- passData.tileList = lightLists.tileList;
- builder.UseBuffer(passData.tileList, AccessFlags.Read);
- passData.lightList = lightLists.lightList;
- builder.UseBuffer(passData.lightList, AccessFlags.Read);
- passData.perVoxelLightList = lightLists.perVoxelLightLists;
- builder.UseBuffer(passData.perVoxelLightList, AccessFlags.Read);
- passData.dispatchIndirect = lightLists.dispatchIndirectBuffer;
- builder.UseBuffer(passData.dispatchIndirect, AccessFlags.Read);
+ if (tileClusterDebug == TileClusterDebug.MaterialFeatureVariants)
+ {
+ passData.tileList = lightLists.tileList;
+ builder.UseBuffer(passData.tileList, AccessFlags.Read);
+ passData.dispatchIndirect = lightLists.dispatchIndirectBuffer;
+ builder.UseBuffer(passData.dispatchIndirect, AccessFlags.Read);
+ }
+ else if (tileClusterDebug == TileClusterDebug.Cluster)
+ {
+ passData.perVoxelLightList = lightLists.perVoxelLightLists;
+ builder.UseBuffer(passData.perVoxelLightList, AccessFlags.Read);
+ passData.perTileLogBaseTweak = lightLists.perTileLogBaseTweak;
+ builder.UseBuffer(passData.perTileLogBaseTweak, AccessFlags.Read);
+ passData.perVoxelOffset = lightLists.perVoxelOffset;
+ builder.UseBuffer(passData.perVoxelOffset, AccessFlags.Read);
+ }
+ else
+ {
+ passData.lightList = lightLists.lightList;
+ builder.UseBuffer(passData.lightList, AccessFlags.Read);
+ }
passData.debugViewTilesMaterial = m_DebugViewTilesMaterial;
passData.lightingDebugSettings = m_CurrentDebugDisplaySettings.data.lightingDebugSettings;
passData.lightingViewportSize = new Vector4(hdCamera.actualWidth, hdCamera.actualHeight, 1.0f / (float)hdCamera.actualWidth, 1.0f / (float)hdCamera.actualHeight);
@@ -887,34 +907,32 @@ void RenderTileClusterDebugOverlay(RenderGraph renderGraph, TextureHandle colorB
(RenderTileClusterDebugOverlayPassData data, UnsafeGraphContext ctx) =>
{
var natCmd = CommandBufferHelpers.GetNativeCommandBuffer(ctx.cmd);
- int w = data.hdCamera.actualWidth;
- int h = data.hdCamera.actualHeight;
- int numTilesX = (w + 15) / 16;
- int numTilesY = (h + 15) / 16;
- int numTiles = numTilesX * numTilesY;
var lightingDebug = data.lightingDebugSettings;
// Debug tiles
if (lightingDebug.tileClusterDebug == TileClusterDebug.MaterialFeatureVariants)
{
- if (GetFeatureVariantsEnabled(data.hdCamera.frameSettings))
- {
- // featureVariants
- data.debugViewTilesMaterial.SetInt(HDShaderIDs._NumTiles, numTiles);
- data.debugViewTilesMaterial.SetInt(HDShaderIDs._ViewTilesFlags, (int)lightingDebug.tileClusterDebugByCategory);
- data.debugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(data.hdCamera));
- data.debugViewTilesMaterial.SetVector(HDShaderIDs._MouseClickPixelCoord, HDUtils.GetMouseClickCoordinates(data.hdCamera));
- data.debugViewTilesMaterial.SetVector(HDShaderIDs._ClusterDebugLightViewportSize, data.lightingViewportSize);
- data.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_TileList, data.tileList);
- data.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_DispatchIndirectBuffer, data.dispatchIndirect);
- CoreUtils.SetKeyword(ctx.cmd, "USE_FPTL_LIGHTLIST", true);
- CoreUtils.SetKeyword(ctx.cmd, "USE_CLUSTERED_LIGHTLIST", false);
-
- data.debugViewTilesMaterial.DisableKeyword("SHOW_LIGHT_CATEGORIES");
- data.debugViewTilesMaterial.EnableKeyword("SHOW_FEATURE_VARIANTS");
- natCmd.DrawProcedural(Matrix4x4.identity, data.debugViewTilesMaterial, 0, MeshTopology.Triangles, numTiles * 6);
- }
+ int w = data.hdCamera.actualWidth;
+ int h = data.hdCamera.actualHeight;
+ int numTilesX = (w + 15) / 16;
+ int numTilesY = (h + 15) / 16;
+ int numTiles = numTilesX * numTilesY;
+
+ // featureVariants
+ data.debugViewTilesMaterial.SetInt(HDShaderIDs._NumTiles, numTiles);
+ data.debugViewTilesMaterial.SetInt(HDShaderIDs._ViewTilesFlags, (int)lightingDebug.tileClusterDebugByCategory);
+ data.debugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(data.hdCamera));
+ data.debugViewTilesMaterial.SetVector(HDShaderIDs._MouseClickPixelCoord, HDUtils.GetMouseClickCoordinates(data.hdCamera));
+ data.debugViewTilesMaterial.SetVector(HDShaderIDs._ClusterDebugLightViewportSize, data.lightingViewportSize);
+ data.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_TileList, data.tileList);
+ data.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_DispatchIndirectBuffer, data.dispatchIndirect);
+ CoreUtils.SetKeyword(ctx.cmd, "USE_FPTL_LIGHTLIST", true);
+ CoreUtils.SetKeyword(ctx.cmd, "USE_CLUSTERED_LIGHTLIST", false);
+
+ data.debugViewTilesMaterial.DisableKeyword("SHOW_LIGHT_CATEGORIES");
+ data.debugViewTilesMaterial.EnableKeyword("SHOW_FEATURE_VARIANTS");
+ natCmd.DrawProcedural(Matrix4x4.identity, data.debugViewTilesMaterial, 0, MeshTopology.Triangles, numTiles * 6);
}
else // tile or cluster
{
@@ -927,8 +945,14 @@ void RenderTileClusterDebugOverlay(RenderGraph renderGraph, TextureHandle colorB
data.debugViewTilesMaterial.SetVector(HDShaderIDs._ClusterDebugLightViewportSize, data.lightingViewportSize);
data.debugViewTilesMaterial.SetVector(HDShaderIDs._MousePixelCoord, HDUtils.GetMouseCoordinates(data.hdCamera));
data.debugViewTilesMaterial.SetVector(HDShaderIDs._MouseClickPixelCoord, HDUtils.GetMouseClickCoordinates(data.hdCamera));
- data.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_vLightListTile, data.lightList);
- data.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_vLightListCluster, data.perVoxelLightList);
+ if (bUseClustered)
+ {
+ data.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_vLightListCluster, data.perVoxelLightList);
+ data.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_logBaseBuffer, data.perTileLogBaseTweak);
+ data.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_vLayeredOffsetsBuffer, data.perVoxelOffset);
+ }
+ else
+ data.debugViewTilesMaterial.SetBuffer(HDShaderIDs.g_vLightListTile, data.lightList);
data.debugViewTilesMaterial.SetTexture(HDShaderIDs._CameraDepthTexture, data.depthPyramidTexture);
CoreUtils.SetKeyword(natCmd, "USE_FPTL_LIGHTLIST", !bUseClustered);
@@ -1540,6 +1564,8 @@ class DebugViewMaterialData
public bool decalsEnabled;
public BufferHandle perVoxelOffset;
public BufferHandle lightList;
+ public BufferHandle perVoxelLightLists;
+ public BufferHandle perTileLogBaseTweak;
public DBufferOutput dbuffer;
public GBufferOutput gbuffer;
public TextureHandle depthBuffer;
@@ -1624,10 +1650,21 @@ TextureHandle RenderDebugViewMaterial(RenderGraph renderGraph, CullingResults cu
builder.UseRendererList(passData.transparentRendererList);
passData.decalsEnabled = (hdCamera.frameSettings.IsEnabled(FrameSettingsField.Decals)) && (DecalSystem.m_DecalDatasCount > 0);
- passData.perVoxelOffset = lightLists.perVoxelOffset;
- builder.UseBuffer(passData.perVoxelOffset, AccessFlags.Read);
- passData.lightList = lightLists.lightList;
- builder.UseBuffer(passData.lightList, AccessFlags.Read);
+
+ if (m_CurrentDebugDisplaySettings.data.lightingDebugSettings.tileClusterDebug == TileClusterDebug.Cluster)
+ {
+ passData.perVoxelLightLists = lightLists.perVoxelLightLists;
+ builder.UseBuffer(passData.perVoxelLightLists, AccessFlags.Read);
+ passData.perTileLogBaseTweak = lightLists.perTileLogBaseTweak;
+ builder.UseBuffer(passData.perTileLogBaseTweak, AccessFlags.Read);
+ passData.perVoxelOffset = lightLists.perVoxelOffset;
+ builder.UseBuffer(passData.perVoxelOffset, AccessFlags.Read);
+ }
+ else
+ {
+ passData.lightList = lightLists.lightList;
+ builder.UseBuffer(passData.lightList, AccessFlags.Read);
+ }
passData.dbuffer = ReadDBuffer(dbuffer, builder);
passData.clearColorTexture = Compositor.CompositionManager.GetClearTextureForStackedCamera(hdCamera); // returns null if is not a stacked camera
@@ -1648,7 +1685,17 @@ TextureHandle RenderDebugViewMaterial(RenderGraph renderGraph, CullingResults cu
BindDefaultTexturesLightingBuffers(ctx.defaultResources, natCmd);
- if (data.lightList.IsValid())
+ bool bUseClustered = data.perVoxelLightLists.IsValid();
+ CoreUtils.SetKeyword(natCmd, "USE_FPTL_LIGHTLIST", !bUseClustered);
+ CoreUtils.SetKeyword(natCmd, "USE_CLUSTERED_LIGHTLIST", bUseClustered);
+
+ if (bUseClustered)
+ {
+ natCmd.SetGlobalBuffer(HDShaderIDs.g_vLightListCluster, data.perVoxelLightLists);
+ natCmd.SetGlobalBuffer(HDShaderIDs.g_logBaseBuffer, data.perTileLogBaseTweak);
+ natCmd.SetGlobalBuffer(HDShaderIDs.g_vLayeredOffsetsBuffer, data.perVoxelOffset);
+ }
+ else
natCmd.SetGlobalBuffer(HDShaderIDs.g_vLightListTile, data.lightList);
BindDBufferGlobalData(data.dbuffer, ctx);
@@ -1656,8 +1703,7 @@ TextureHandle RenderDebugViewMaterial(RenderGraph renderGraph, CullingResults cu
if (data.decalsEnabled)
DecalSystem.instance.SetAtlas(natCmd); // for clustered decals
- if (data.perVoxelOffset.IsValid())
- natCmd.SetGlobalBuffer(HDShaderIDs.g_vLayeredOffsetsBuffer, data.perVoxelOffset);
+
DrawTransparentRendererList(ctx, data.frameSettings, data.transparentRendererList);
});
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs
index dd290abf7ca..8dcfc7ef7e4 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.PostProcess.cs
@@ -215,6 +215,8 @@ void InitializePostProcess()
m_MotionBlurSupportsScattering = SystemInfo.IsFormatSupported(GraphicsFormat.R32_UInt, GraphicsFormatUsage.LoadStore) && SystemInfo.IsFormatSupported(GraphicsFormat.R16_UInt, GraphicsFormatUsage.LoadStore);
// TODO: Remove this line when atomic bug in HLSLcc is fixed.
m_MotionBlurSupportsScattering = m_MotionBlurSupportsScattering && (SystemInfo.graphicsDeviceType != GraphicsDeviceType.Vulkan);
+ // TODO: Remove this line when atomic bug in HLSLcc is fixed.
+ m_MotionBlurSupportsScattering = m_MotionBlurSupportsScattering && (SystemInfo.graphicsDeviceType != GraphicsDeviceType.Switch2);
// TODO: Write a version that uses structured buffer instead of texture to do atomic as Metal doesn't support atomics on textures.
m_MotionBlurSupportsScattering = m_MotionBlurSupportsScattering && (SystemInfo.graphicsDeviceType != GraphicsDeviceType.Metal);
@@ -390,6 +392,9 @@ void BeginPostProcessFrame(CommandBuffer cmd, HDCamera camera, HDRenderPipeline
m_EnabledAdvancedUpscalerPassMask |= m_DLSSPass != null && camera.IsDLSSEnabled() ? (1 << (int)AdvancedUpscalers.DLSS): 0;
m_EnabledAdvancedUpscalerPassMask |= m_FSR2Pass != null && camera.IsFSR2Enabled() ? (1 << (int)AdvancedUpscalers.FSR2): 0;
m_EnabledAdvancedUpscalerPassMask |= camera.IsSTPEnabled() ? (1 << (int)AdvancedUpscalers.STP): 0;
+#if ENABLE_UPSCALER_FRAMEWORK
+ m_EnabledAdvancedUpscalerPassMask |= camera.IsIUpscalerEnabled() ? (1 << (int)AdvancedUpscalers.IUpscaler): 0;
+#endif
m_DebugExposureCompensation = m_CurrentDebugDisplaySettings.data.lightingDebugSettings.debugExposure;
@@ -577,6 +582,18 @@ public bool PerformsAntiAliasing()
}
}
+#if ENABLE_UPSCALER_FRAMEWORK
+ if (hdCamera.IsIUpscalerEnabled())
+ {
+ return new CurrentUpsamplerData
+ {
+ isAdvancedUpsampler = true,
+ advancedUpsampler = AdvancedUpscalers.IUpscaler,
+ schedule = DynamicResolutionHandler.instance.upsamplerSchedule,
+ };
+ }
+#endif
+
if (hdCamera.DynResRequest.enabled)
{
if (hdCamera.DynResRequest.filter == DynamicResUpscaleFilter.ContrastAdaptiveSharpen)
@@ -612,6 +629,10 @@ TextureHandle DoUpscalingAndAntiAliasing(RenderGraph renderGraph, HDCamera hdCam
{
{ isAdvancedUpsampler: true, advancedUpsampler: AdvancedUpscalers.STP }
=> DoStpPasses(renderGraph, hdCamera, source, depthBuffer, motionVectors, stencilBuffer),
+#if ENABLE_UPSCALER_FRAMEWORK
+ { isAdvancedUpsampler: true, advancedUpsampler: AdvancedUpscalers.IUpscaler }
+ => DoIUpscalerPasses(renderGraph, hdCamera, source, depthBuffer, motionVectors, stencilBuffer),
+#endif
{ isAdvancedUpsampler: true, advancedUpsampler: AdvancedUpscalers.DLSS}
=> DoDLSSPasses(renderGraph, hdCamera, upsamplerDataData.schedule, source, depthBuffer, motionVectors),
{ isAdvancedUpsampler: true, advancedUpsampler: AdvancedUpscalers.FSR2}
@@ -1030,6 +1051,112 @@ TextureHandle DoFSR2Pass(
#endregion
+ #region IUpscaler
+#if ENABLE_UPSCALER_FRAMEWORK
+ TextureHandle DoIUpscalerPasses(
+ RenderGraph renderGraph,
+ HDCamera hdCamera,
+ TextureHandle inputColor,
+ TextureHandle inputDepth,
+ TextureHandle inputMotion,
+ TextureHandle inputStencil
+ )
+ {
+ // Create a context item containing upscaling inputs
+ UpscalingIO io = hdCamera.contextContainer.Get();
+ io.cameraColor = inputColor;
+ io.cameraDepth = inputDepth;
+ io.motionVectorColor = inputMotion;
+ io.exposureTexture = renderGraph.ImportTexture(GetExposureTexture(hdCamera));
+ io.motionVectorDomain = UpscalingIO.MotionVectorDomain.NDC;
+ io.motionVectorDirection = UpscalingIO.MotionVectorDirection.PreviousFrameToCurrentFrame;
+ io.motionVectorTextureSize = hdCamera.historyRTHandleProperties.currentViewportSize; // is there ever a scenario where MVs are smaller than input color? if not, remove this.
+ io.jitteredMotionVectors = false; // HDRP has no jittering in MVs
+ io.preUpscaleResolution = hdCamera.historyRTHandleProperties.currentViewportSize;
+ io.previousPreUpscaleResolution = hdCamera.historyRTHandleProperties.previousViewportSize;
+ io.postUpscaleResolution = new Vector2Int((int)hdCamera.finalViewport.width, (int)hdCamera.finalViewport.height);
+ io.enableTexArray = TextureXR.useTexArray;
+ io.cameraInstanceID = hdCamera.camera.GetInstanceID();
+ io.nearClipPlane = hdCamera.camera.nearClipPlane;
+ io.farClipPlane = hdCamera.camera.farClipPlane;
+ io.fieldOfViewDegrees = hdCamera.camera.fieldOfView;
+ io.invertedDepth = SystemInfo.usesReversedZBuffer;
+ io.flippedY = SystemInfo.graphicsUVStartsAtTop;
+ io.flippedX = false;
+ io.hdrInput = GraphicsFormatUtility.IsHDRFormat(inputColor.GetDescriptor(renderGraph).format);
+ io.blueNoiseTextureSet = m_BlueNoise.textures16L;
+
+ // The number of active views may vary over time, but it must never be more than we expected during initialization.
+ int numActiveViews = hdCamera.m_XRViewConstants.Length;
+ Debug.Assert(numActiveViews <= STP.perViewConfigs.Length);
+
+ io.numActiveViews = numActiveViews;
+ io.eyeIndex = 0; // Maybe we should rename this to viewIndexBias or maybe even find a way to remove this entirely.
+ io.worldSpaceCameraPositions = new Vector3[numActiveViews];
+ io.previousWorldSpaceCameraPositions = new Vector3[numActiveViews];
+ io.previousPreviousWorldSpaceCameraPositions = new Vector3[numActiveViews];
+ io.projectionMatrices = new Matrix4x4[numActiveViews];
+ io.previousProjectionMatrices = new Matrix4x4[numActiveViews];
+ io.previousPreviousProjectionMatrices = new Matrix4x4[numActiveViews];
+ io.viewMatrices = new Matrix4x4[numActiveViews];
+ io.previousViewMatrices = new Matrix4x4[numActiveViews];
+ io.previousPreviousViewMatrices = new Matrix4x4[numActiveViews];
+ for (int i = 0; i < numActiveViews; i++)
+ {
+ // NOTE: STP assumes the view matrices also contain the camera position. However, HDRP may be configured to perform camera relative rendering which
+ // removes the camera translation from the view matrices. We inject the camera position directly into the view matrix here to make sure we don't
+ // run into issues when camera relative rendering is enabled.
+ //
+ // Also, the previous world space camera position variable is specified as a value relative to the current world space camera position.
+ // We must add both values together in order to produce the last camera position as an absolute world space value.
+ io.worldSpaceCameraPositions[i] = hdCamera.m_XRViewConstants[i].worldSpaceCameraPos;
+ io.previousWorldSpaceCameraPositions[i] =
+ hdCamera.m_XRViewConstants[i].prevWorldSpaceCameraPos + hdCamera.m_XRViewConstants[i].worldSpaceCameraPos;
+ io.previousPreviousWorldSpaceCameraPositions[i] =
+ hdCamera.m_XRViewConstants[i].prevPrevWorldSpaceCameraPos + io.previousWorldSpaceCameraPositions[i];
+
+ io.projectionMatrices[i] = hdCamera.m_XRViewConstants[i].nonJitteredProjMatrix;
+ io.previousProjectionMatrices[i] = hdCamera.m_XRViewConstants[i].prevProjMatrix;
+ io.previousPreviousProjectionMatrices[i] = hdCamera.m_XRViewConstants[i].prevPrevProjMatrix;
+ io.viewMatrices[i] = hdCamera.m_XRViewConstants[i].viewMatrix;
+ io.previousViewMatrices[i] = hdCamera.m_XRViewConstants[i].prevViewMatrix;
+ io.previousPreviousViewMatrices[i] = hdCamera.m_XRViewConstants[i].prevPrevViewMatrix;
+ }
+ io.preExposureValue = hdCamera.GpuExposureValue();
+
+ io.resetHistory = hdCamera.resetPostProcessingHistory;
+ io.frameIndex = hdCamera.taaFrameIndex;
+ io.deltaTime = hdCamera.currentRenderDeltaTime;
+ io.previousDeltaTime = hdCamera.lastRenderDeltaTime;
+ io.hdrDisplayInformation = HDROutputIsActive(hdCamera) ? HDRDisplayInformationForCamera(hdCamera) : new HDROutputUtils.HDRDisplayInformation(-1, -1, -1, 160.0f);
+
+ // The motion scaling feature is only active outside of test environments. If we allowed it to run
+ // during automated graphics tests, the results of each test run would be dependent on system
+ // performance.
+#if HDRP_DEBUG_STATIC_POSTFX
+ io.enableMotionScaling = false;
+#else
+ io.enableMotionScaling = true;
+#endif
+ // Hardware Dynamic Resolution Scaling
+ {
+ // When HW DRS is not enabled, STP is only functional when the dynamic resolution is forced to a fixed value
+ if (hdCamera.DynResRequest.enabled && !hdCamera.DynResRequest.hardwareEnabled)
+ Debug.Assert(hdCamera.DynResRequest.forcingResolution);
+
+ io.enableHwDrs = hdCamera.DynResRequest.enabled && hdCamera.DynResRequest.hardwareEnabled;
+ }
+
+ // Insert the active upscaler's render graph passes
+ IUpscaler upscaler = upscaling.GetActiveUpscaler();
+ Debug.Assert(upscaler != null);
+ upscaler.RecordRenderGraph(renderGraph, hdCamera.contextContainer);
+
+ return io.cameraColor;
+ }
+#endif
+ #endregion
+
#region Copy Alpha
class AlphaCopyPassData
{
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs
index 9daa44b5a19..de466c82090 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.Prepass.cs
@@ -132,7 +132,7 @@ TextureHandle CreateDepthBuffer(RenderGraph renderGraph, bool clear, MSAASamples
TextureDesc depthDesc = new TextureDesc(Vector2.one, true, true)
{
- format = CoreUtils.GetDefaultDepthStencilFormat(),
+ format = GetDepthBufferFormat(false),
bindTextureMS = msaa,
msaaSamples = msaaSamples,
clearBuffer = clear,
@@ -187,7 +187,7 @@ TextureHandle CreateRenderingLayersBuffer(RenderGraph renderGraph, MSAASamples m
TextureHandle CreateDepthAsColorBuffer(RenderGraph renderGraph, MSAASamples msaaSamples)
{
return renderGraph.CreateTexture(new TextureDesc(Vector2.one, true, true)
- { format = GraphicsFormat.R32_SFloat, clearBuffer = true, clearColor = Color.black, bindTextureMS = true, msaaSamples = msaaSamples, name = "DepthAsColorMSAA" });
+ { format = GetDepthBufferFormat(true), clearBuffer = true, clearColor = Color.black, bindTextureMS = true, msaaSamples = msaaSamples, name = "DepthAsColorMSAA" });
}
TextureHandle CreateMotionVectorBuffer(RenderGraph renderGraph, bool clear, MSAASamples msaaSamples)
@@ -1206,7 +1206,7 @@ void CopyDepthBufferIfNeeded(RenderGraph renderGraph, HDCamera hdCamera, ref Pre
builder.UseTexture(passData.inputDepth, AccessFlags.ReadWrite);
passData.outputDepth = renderGraph.CreateTexture(new TextureDesc(depthMipchainSize.x, depthMipchainSize.y, true, true)
- { format = GraphicsFormat.R32_SFloat, enableRandomWrite = true, name = "CameraDepthBufferMipChain" });
+ { format = GetDepthBufferFormat(true), enableRandomWrite = true, name = "CameraDepthBufferMipChain" });
builder.UseTexture(passData.outputDepth, AccessFlags.Write);
passData.GPUCopy = m_GPUCopy;
@@ -1390,7 +1390,8 @@ void RenderDBuffer(RenderGraph renderGraph, HDCamera hdCamera, ref PrepassOutput
SystemInfo.graphicsDeviceType == GraphicsDeviceType.Switch ||
SystemInfo.graphicsDeviceType == GraphicsDeviceType.XboxOneD3D12 ||
SystemInfo.graphicsDeviceType == GraphicsDeviceType.GameCoreXboxOne ||
- SystemInfo.graphicsDeviceType == GraphicsDeviceType.GameCoreXboxSeries;
+ SystemInfo.graphicsDeviceType == GraphicsDeviceType.GameCoreXboxSeries ||
+ SystemInfo.graphicsDeviceType == GraphicsDeviceType.Switch2;
if (!canReadBoundDepthBuffer)
{
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs
index 11bc093edb7..85a78cfe49a 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.RenderGraph.cs
@@ -461,8 +461,6 @@ void ExecuteWithRenderGraph(RenderRequest renderRequest,
commandBuffer = commandBuffer
};
- m_RenderGraph.nativeRenderPassesEnabled = true;
-
try
{
m_RenderGraph.BeginRecording(parameters);
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.STP.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.STP.cs
index 9ee6be70df0..c8d4892b287 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.STP.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.STP.cs
@@ -10,7 +10,7 @@ public partial class HDRenderPipeline
void PopulateStpConfig(HDCamera hdCamera, TextureHandle inputColor, TextureHandle inputDepth, TextureHandle inputMotion, TextureHandle inputStencil, int debugViewIndex, TextureHandle debugView, TextureHandle destination, out STP.Config config)
{
hdCamera.RequestStpHistory(out var useHwDrs, out var hasValidHistory, out var history);
-
+
config.historyContext = history;
config.enableHwDrs = useHwDrs;
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs
index 08dd11fd5d0..e1ccfb3d4d5 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.SubsurfaceScattering.cs
@@ -165,7 +165,8 @@ static bool NeedTemporarySubsurfaceBuffer()
SystemInfo.graphicsDeviceType != GraphicsDeviceType.XboxOne &&
SystemInfo.graphicsDeviceType != GraphicsDeviceType.XboxOneD3D12 &&
SystemInfo.graphicsDeviceType != GraphicsDeviceType.GameCoreXboxOne &&
- SystemInfo.graphicsDeviceType != GraphicsDeviceType.GameCoreXboxSeries);
+ SystemInfo.graphicsDeviceType != GraphicsDeviceType.GameCoreXboxSeries &&
+ SystemInfo.graphicsDeviceType != GraphicsDeviceType.Switch2);
}
// Albedo + SSS Profile and mask / Specular occlusion (when no SSS)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs
index 87e60dafdbb..2653a86dd85 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipeline.cs
@@ -81,6 +81,9 @@ internal static HDRenderPipeline currentPipeline
readonly List m_MaterialList = new List();
+#if ENABLE_UPSCALER_FRAMEWORK
+ internal Upscaling upscaling;
+#endif
// Keep track of previous Graphic and QualitySettings value to reset when switching to another pipeline
bool m_PreviousLightsUseLinearIntensity;
@@ -225,6 +228,34 @@ internal GraphicsFormat GetColorBufferFormat()
return m_ShouldOverrideColorBufferFormat ? m_AOVGraphicsFormat : (GraphicsFormat)m_Asset.currentPlatformRenderPipelineSettings.colorBufferFormat;
}
+ ///
+ /// Returns the current depth buffer format based on the HDRP asset config
+ ///
+ /// Set to true to return a color format capable of storing a depth with enought precision instead of a depth format.
+ /// Returns either the color or depth format using the configured precision in the HDRP asset.
+ internal GraphicsFormat GetDepthBufferFormat(bool depthAsColor)
+ {
+ var depthFormat = m_Asset.currentPlatformRenderPipelineSettings.depthBufferFormat;
+ if (depthAsColor)
+ {
+ switch (depthFormat)
+ {
+ case RenderPipelineSettings.DepthBufferFormat.Auto:
+ // Auto mode can choose between 32 or 24 bit modes but there is no 24 bit texture format, so we fall back on 32
+ case RenderPipelineSettings.DepthBufferFormat.ForceD32:
+ case RenderPipelineSettings.DepthBufferFormat.ForceD24:
+ return GraphicsFormat.R32_SFloat;
+ case RenderPipelineSettings.DepthBufferFormat.ForceD16:
+ return GraphicsFormat.R16_SFloat;
+ }
+ }
+
+ if (depthFormat == RenderPipelineSettings.DepthBufferFormat.Auto)
+ return CoreUtils.GetDefaultDepthStencilFormat();
+ else
+ return (GraphicsFormat)depthFormat;
+ }
+
GraphicsFormat GetCustomBufferFormat()
=> (GraphicsFormat)m_Asset.currentPlatformRenderPipelineSettings.customBufferFormat;
@@ -358,8 +389,10 @@ void SetHDRState(HDCamera camera)
#else
bool hdrInPlayerSettings = true;
#endif
+ bool supportsSwitchingHDR = SystemInfo.hdrDisplaySupportFlags.HasFlag(HDRDisplaySupportFlags.RuntimeSwitchable);
+ bool hdrOutputActive = HDROutputSettings.main.available && HDROutputSettings.main.active;
- if (hdrInPlayerSettings && HDROutputSettings.main.available)
+ if (hdrInPlayerSettings && supportsSwitchingHDR && hdrOutputActive)
{
if (camera.camera.cameraType != CameraType.Game)
{
@@ -712,6 +745,9 @@ public HDRenderPipeline(HDRenderPipelineAsset asset)
LocalVolumetricFogManager.manager.InitializeGraphicsBuffers(asset.currentPlatformRenderPipelineSettings.lightLoopSettings.maxLocalVolumetricFogOnScreen);
VrsInitializeResources();
+#if ENABLE_UPSCALER_FRAMEWORK
+ upscaling = new Upscaling(asset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.IUpscalerOptions);
+#endif
#if UNITY_EDITOR
GPUInlineDebugDrawer.Initialize();
@@ -1354,23 +1390,32 @@ void SetupPartnerUpscalers(
hdCam.cameraCanRenderDLSS = false;
hdCam.cameraCanRenderFSR2 = false;
hdCam.cameraCanRenderSTP = false;
+#if ENABLE_UPSCALER_FRAMEWORK
+ hdCam.cameraCanRenderIUpscaler = false;
+ hdCam.cameraIUpscalerIsTemporalUpscaler = false;
+#endif
if (!cameraRequestedDynamicRes || !m_Asset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.enabled)
return;
- var upscalerList = m_Asset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority;
- if (upscalerList == null || upscalerList.Count == 0)
+ var upscalerNames = m_Asset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames;
+ if (upscalerNames == null || upscalerNames.Count == 0)
return;
+ // STP cannot support dynamic resolution when hardware support is not available.
+ // However, we make an exception for cases where the dynamic resolution is known to be forced to a fixed value.
+ bool isHwDrsSupported = HDUtils.IsHardwareDynamicResolutionSupportedByDevice(SystemInfo.graphicsDeviceType);
+ var drsSettings = m_Asset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings;
+ bool isStpSupported = ((drsSettings.dynResType == DynamicResolutionType.Hardware) && isHwDrsSupported) || drsSettings.forceResolution;
+
// External upscaler priority system: we pick the first upscaler in the pre sorted priority list to activate for the frame.
bool found = false;
- for (int i = 0; i < upscalerList.Count && !found; ++i)
+ for (int i = 0; i < upscalerNames.Count && !found; ++i)
{
- var scaler = upscalerList[i];
- switch (scaler)
+ var name = upscalerNames[i];
+ switch(name)
{
- case AdvancedUpscalers.DLSS:
- {
+ case "DLSS":
hdCam.cameraCanRenderDLSS = HDDynamicResolutionPlatformCapabilities.DLSSDetected && hdCam.allowDeepLearningSuperSampling;
found = hdCam.cameraCanRenderDLSS;
if (m_DLSSPass != null && hdCam.cameraCanRenderDLSS)
@@ -1380,10 +1425,9 @@ void SetupPartnerUpscalers(
: m_Asset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.DLSSUseOptimalSettings;
m_DLSSPass.SetupDRSScaling(useOptimalSettings, camera, hdCam, xrPass, ref outDrsSettings);
}
- }
- break;
- case AdvancedUpscalers.FSR2:
- {
+ break;
+
+ case "FSR2":
hdCam.cameraCanRenderFSR2 = HDDynamicResolutionPlatformCapabilities.FSR2Detected && hdCam.allowFidelityFX2SuperResolution;
found = hdCam.cameraCanRenderFSR2;
if (m_FSR2Pass != null && hdCam.cameraCanRenderFSR2)
@@ -1393,23 +1437,54 @@ void SetupPartnerUpscalers(
: m_Asset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings.FSR2UseOptimalSettings;
m_FSR2Pass.SetupDRSScaling(useOptimalSettings, camera, hdCam, xrPass, ref outDrsSettings);
}
- }
- break;
- case AdvancedUpscalers.STP:
+ break;
+
+ case "STP":
+ hdCam.cameraCanRenderSTP = isStpSupported;
+ found = hdCam.cameraCanRenderSTP;
+ break;
+
+#if ENABLE_UPSCALER_FRAMEWORK
+ default:
{
- bool isHwDrsSupported = HDUtils.IsHardwareDynamicResolutionSupportedByDevice(SystemInfo.graphicsDeviceType);
+ // The upscaler name should be an IUpscaler
+ IUpscaler optActiveIUpscaler = this.upscaling.GetActiveUpscaler();
- var drsSettings = m_Asset.currentPlatformRenderPipelineSettings.dynamicResolutionSettings;
- // STP cannot support dynamic resolution when hardware support is not available.
- // However, we make an exception for cases where the dynamic resolution is known to be forced to a fixed value.
- bool isStpSupported = ((drsSettings.dynResType == DynamicResolutionType.Hardware) && isHwDrsSupported) || drsSettings.forceResolution;
+ // TODO (Apoorva): Make this condition dynamic from the IUpscaler interface, so that an
+ // individual upscaling package can decide whether it is supported in the current config.
+ bool isSupported = ((drsSettings.dynResType == DynamicResolutionType.Hardware) && isHwDrsSupported) || drsSettings.forceResolution;
+ if (isSupported)
+ {
+ if (optActiveIUpscaler == null || name != optActiveIUpscaler.GetName())
+ {
+ // The active upscaler should be an IUpscaler, but it isn't currently set active in the
+ // upscaling manager.
+ bool ok = this.upscaling.SetActiveUpscaler(name);
+ if (!ok)
+ {
+ Debug.LogWarning(
+ $"Upscaler with name '{name}' is listed in the HDRP asset, but not found at run-time. Maybe an upscaling package is missing. Skipping over this upscaler.");
+ }
+ else
+ {
+ // The upscaler was successfully set. Get a handle to it.
+ optActiveIUpscaler = this.upscaling.GetActiveUpscaler();
+ Debug.Assert(optActiveIUpscaler != null);
+ }
+ }
- hdCam.cameraCanRenderSTP = isStpSupported;
- found = hdCam.cameraCanRenderSTP;
+ if (optActiveIUpscaler != null)
+ {
+ hdCam.cameraCanRenderIUpscaler = true;
+ hdCam.cameraIUpscalerIsTemporalUpscaler = optActiveIUpscaler.IsTemporalUpscaler();
+ found = true;
+ }
+ }
}
break;
- }
+#endif // ENABLE_UPSCALER_FRAMEWORK
+ } // switch(upscalerNames[i])
}
}
@@ -1746,7 +1821,7 @@ ScriptableRenderContext renderContext
visibleProbe.AllocTexture(probeFormat);
visibleProbe.SetCameraAnchor(cameraSettings, viewerTransform);
var isPlanarReflectionProbe = visibleProbe.type == ProbeSettings.ProbeType.PlanarProbe;
-
+
ProbeRenderSteps skippedRenderSteps = ProbeRenderSteps.None;
for (int j = 0; j < cameraSettings.Count; ++j)
{
@@ -1759,7 +1834,7 @@ ScriptableRenderContext renderContext
DynamicResolutionHandler.UpdateAndUseCamera(camera, settingsCopy);
foreach (var terrain in m_ActiveTerrains)
- terrain.SetKeepUnusedCameraRenderingResources(camera.GetInstanceID(), true);
+ terrain.SetKeepUnusedCameraRenderingResources(camera.GetEntityId(), true);
if (!camera.TryGetComponent(out var additionalCameraData))
{
@@ -2259,7 +2334,16 @@ protected override void Render(ScriptableRenderContext renderContext, List
{
- data.m_RenderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.Clear();
#pragma warning disable 618 // Type or member is obsolete
+ data.m_RenderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.Clear();
if(!data.m_RenderPipelineSettings.dynamicResolutionSettings.enableDLSS)
return;
data.m_RenderPipelineSettings.dynamicResolutionSettings.enableDLSS = false;
-#pragma warning restore 618
data.m_RenderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.Add(AdvancedUpscalers.DLSS);
+#pragma warning restore 618
+ }),
+ MigrationStep.New(Version.AddNamesToUpscalers, (HDRenderPipelineAsset data) =>
+ {
+ data.m_RenderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames = new List();
+#pragma warning disable 618 // Type or member is obsolete
+ foreach (var u in data.m_RenderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority)
+#pragma warning restore 618
+ {
+ data.m_RenderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.Add(u.ToString());
+ }
})
);
#endregion
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.cs
index e24dcb29a48..af921d813a8 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/HDRenderPipelineAsset.cs
@@ -209,7 +209,7 @@ internal bool useRenderGraph
}
///
- public bool isImmediateModeSupported => true;
+ public bool isImmediateModeSupported => false;
[SerializeField] private CustomPostProcessVolumeComponentList m_CompositorCustomVolumeComponentsList = new(CustomPostProcessInjectionPoint.BeforePostProcess);
@@ -290,7 +290,11 @@ public bool isStpUsed
{
get
{
- return m_RenderPipelineSettings.dynamicResolutionSettings.advancedUpscalersByPriority.Contains(AdvancedUpscalers.STP);
+ return m_RenderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.Contains("STP")
+ #if ENABLE_UPSCALER_FRAMEWORK
+ || m_RenderPipelineSettings.dynamicResolutionSettings.advancedUpscalerNames.Contains("STP (IUpscaler)")
+ #endif
+ ;
}
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/CompositeLines.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/CompositeLines.shader
index 70a85057f86..a450b2f8ea3 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/CompositeLines.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/CompositeLines.shader
@@ -3,7 +3,7 @@ Shader "Hidden/HDRP/CompositeLines"
HLSLINCLUDE
#pragma target 4.5
#pragma editor_sync_compilation
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/HDRenderPipeline.LineRendering.VolumeComponent.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/HDRenderPipeline.LineRendering.VolumeComponent.cs
index 26d472868f1..00f1ba5a66d 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/HDRenderPipeline.LineRendering.VolumeComponent.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/HDRenderPipeline.LineRendering.VolumeComponent.cs
@@ -7,6 +7,7 @@ namespace UnityEngine.Rendering.HighDefinition
///
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[Serializable, VolumeComponentMenu("Rendering/High Quality Lines")]
+ [DisplayInfo(name = "High Quality Line Rendering")]
public class HighQualityLineRenderingVolumeComponent : VolumeComponent
{
///
@@ -71,10 +72,5 @@ public LinesSortingQualityParameter(LineRendering.SortingQuality value, bool ove
///
[Tooltip("Threshold for determining when to write depth to output.")]
public ClampedFloatParameter writeDepthAlphaThreshold = new ClampedFloatParameter(0.0f, 0.0f, 1.0f);
-
- HighQualityLineRenderingVolumeComponent()
- {
- displayName = "High Quality Line Rendering";
- }
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StagePrepare.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StagePrepare.compute
index 80b55b35e4a..67c0270ec7f 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StagePrepare.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StagePrepare.compute
@@ -49,7 +49,7 @@ void ClearClusters(uint3 dispatchThreadID : SV_DispatchThreadID)
_ClusterCountersBuffer.Store(dispatchThreadID.x << 2, 0);
}
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
groupshared float2 gs_ViewSpaceDepthRanges;
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageRasterBin.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageRasterBin.compute
index e25cb635245..9820af44684 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageRasterBin.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageRasterBin.compute
@@ -1,7 +1,7 @@
#pragma kernel Main
#pragma kernel MainArgs
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Core/LineRenderingCommon.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageRasterFine.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageRasterFine.compute
index cd80333beb3..6ef4c11e1eb 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageRasterFine.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageRasterFine.compute
@@ -5,7 +5,7 @@
#pragma kernel Main SEGMENTS_PER_CLUSTER=2048 LDS_STRIDE=5 DEBUG
#pragma kernel Main SEGMENTS_PER_CLUSTER=256 LDS_STRIDE=2 COMPILING_SHADER
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
int _HairDebugMode;
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageSetupSegment.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageSetupSegment.compute
index 613037d8b1c..80451d7d9cc 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageSetupSegment.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageSetupSegment.compute
@@ -2,7 +2,7 @@
#pragma multi_compile INDEX_FORMAT_UINT_16 INDEX_FORMAT_UINT_32
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Core/LineRenderingCommon.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageShadingSetup.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageShadingSetup.compute
index 30714a7dead..6847d89c1d0 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageShadingSetup.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageShadingSetup.compute
@@ -9,7 +9,7 @@
#pragma kernel CalculateHighestVisibleHistogramID
#pragma kernel DiscardSamplesBasedOnHistogram
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Core/LineRenderingCommon.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageWorkQueue.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageWorkQueue.compute
index 5110a4f105e..c87b5c025c5 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageWorkQueue.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Kernels/StageWorkQueue.compute
@@ -4,7 +4,7 @@
#pragma kernel WorkQueueActiveClusters
#pragma kernel BuildFineRasterArgs
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/LineRendering/Core/LineRenderingCommon.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs
index 8190d838ee6..77f8bb24ec9 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/PathTracing.cs
@@ -132,6 +132,7 @@ public SeedModeParameter(SeedMode value, bool overrideState = false) : base(valu
[Serializable, VolumeComponentMenu("Ray Tracing/Path Tracing")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("Ray-Tracing-Path-Tracing")]
+ [DisplayInfo(name = "Path Tracing")]
public sealed class PathTracing : VolumeComponent
{
///
@@ -227,17 +228,6 @@ public sealed class PathTracing : VolumeComponent
///
[HideInInspector]
public IntParameter customSeed = new IntParameter(0);
-
- ///
- /// Default constructor for the path tracing volume component.
- ///
- ///
- /// Use the constructor with no arguments to create a new path tracing volume component with default values.
- ///
- public PathTracing()
- {
- displayName = "Path Tracing";
- }
}
public partial class HDRenderPipeline
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingSkySamplingData.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingSkySamplingData.compute
index 66004b6695d..03cf3297775 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingSkySamplingData.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/PathTracing/Shaders/PathTracingSkySamplingData.compute
@@ -2,7 +2,7 @@
#define COMPUTE_PATH_TRACING_SKY_SAMPLING_DATA
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/ImageBasedLighting.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/LightCluster.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/LightCluster.cs
index 2ff01443ce5..29f2e799f69 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/LightCluster.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/LightCluster.cs
@@ -8,6 +8,7 @@ namespace UnityEngine.Rendering.HighDefinition
[Serializable, VolumeComponentMenu("Ray Tracing/Light Cluster")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("Ray-Tracing-Light-Cluster")]
+ [DisplayInfo(name = "Light Cluster")]
public sealed class LightCluster : VolumeComponent
{
///
@@ -15,12 +16,5 @@ public sealed class LightCluster : VolumeComponent
///
[Tooltip("Controls the range of the cluster around the camera in meters.")]
public MinFloatParameter cameraClusterRange = new MinFloatParameter(10.0f, 0.001f);
- ///
- /// Default constructor for the light cluster volume component.
- ///
- public LightCluster()
- {
- displayName = "Light Cluster";
- }
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingSettings.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingSettings.cs
index a781dc90c92..f0beb817e12 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingSettings.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RayTracingSettings.cs
@@ -63,6 +63,7 @@ public RTASCullingModeParameter(RTASCullingMode value, bool overrideState = fals
[Serializable, VolumeComponentMenu("Ray Tracing/Ray Tracing Settings")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("Ray-Tracing-Settings")]
+ [DisplayInfo(name = "Ray Tracing Settings")]
public sealed class RayTracingSettings : VolumeComponent
{
///
@@ -127,13 +128,5 @@ public sealed class RayTracingSettings : VolumeComponent
///
[Tooltip("Specifies the minimum object solid angle in degrees relative to the camera position to accept objects to the ray tracing acceleration structure when the culling mode is set to Solid Angle.")]
public ClampedFloatParameter minSolidAngle = new ClampedFloatParameter(4.0f, 0.01f, 180f);
-
- ///
- /// Default constructor for the ray tracing settings volume component.
- ///
- public RayTracingSettings()
- {
- displayName = "Ray Tracing Settings";
- }
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RecursiveRendering.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RecursiveRendering.cs
index 8ba925e7461..804bc400071 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RecursiveRendering.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/RecursiveRendering.cs
@@ -9,6 +9,7 @@ namespace UnityEngine.Rendering.HighDefinition
[Serializable, VolumeComponentMenu("Ray Tracing/Recursive Rendering")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("Ray-Tracing-Recursive-Rendering")]
+ [DisplayInfo(name = "Recursive Rendering")]
public sealed class RecursiveRendering : VolumeComponent
{
///
@@ -60,13 +61,5 @@ public sealed class RecursiveRendering : VolumeComponent
[Tooltip("Controls the dimmer applied to the ambient and legacy light probes.")]
[AdditionalProperty]
public ClampedFloatParameter ambientProbeDimmer = new ClampedFloatParameter(1.0f, 0.0f, 1.0f);
-
- ///
- /// Default constructor for the recursive rendering volume component.
- ///
- public RecursiveRendering()
- {
- displayName = "Recursive Rendering";
- }
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Common/RayBinning.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Common/RayBinning.compute
index f4e55b16a78..d47d8ae518e 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Common/RayBinning.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Common/RayBinning.compute
@@ -1,7 +1,7 @@
#pragma kernel RayBinning RAY_BINNING=RayBinning
#pragma kernel RayBinningHalf RAY_BINNING=RayBinningHalf HALF_RESOLUTION
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/CountTracedRays.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/CountTracedRays.compute
index 102707e040e..958bd7d1728 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/CountTracedRays.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/CountTracedRays.compute
@@ -3,7 +3,7 @@
#pragma kernel BufferReduction
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.compute
index bec68dc2812..e361403f215 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.compute
@@ -1,6 +1,6 @@
#pragma kernel DebugLightCluster
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#define DEBUG_LIGHT_CLUSTER_TILE_SIZE 8
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.shader
index 099c9d345a5..5fda7761058 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/DebugLightCluster.shader
@@ -6,7 +6,7 @@ Shader "Hidden/HDRP/DebugLightCluster"
HLSLINCLUDE
- #pragma only_renderers d3d11 xboxseries ps5
+ #pragma only_renderers d3d11 xboxseries ps5 switch2
static const float3 cubeVertices[24] =
{
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingDeferred.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingDeferred.compute
index e84a01555fc..2b07f9f8bdd 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingDeferred.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Deferred/RaytracingDeferred.compute
@@ -17,7 +17,7 @@
// In addition to that, we intentionally disabled dithering for the ray tracing case as it requires the screen space position.
#define SHADOW_LOW
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// Needed for the ray miss and the last bounce indirect diffuse lighting
#pragma multi_compile _ PROBE_VOLUMES_L1 PROBE_VOLUMES_L2
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseDenoiser.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseDenoiser.compute
index 8c74f6d5a5c..b248aad9e27 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseDenoiser.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseDenoiser.compute
@@ -6,7 +6,7 @@
#pragma kernel GatherSingle GATHER_FILTER=GatherSingle SINGLE_CHANNEL
#pragma kernel GatherColor GATHER_FILTER=GatherColor
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// We need the stencil flag of this.
#define BILATERLAL_UNLIT
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseShadowDenoiser.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseShadowDenoiser.compute
index 1f10ab6fd9e..3ce7be3ea28 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseShadowDenoiser.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/DiffuseShadowDenoiser.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#pragma kernel BilateralFilterHSingleDirectional BILATERAL_FILTER=BilateralFilterHSingleDirectional SINGLE_CHANNEL DIRECTIONAL_LIGHT
#pragma kernel BilateralFilterVSingleDirectional BILATERAL_FILTER=BilateralFilterVSingleDirectional FINAL_PASS SINGLE_CHANNEL DIRECTIONAL_LIGHT
@@ -31,7 +31,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/BilateralFilter.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RayTracingShadowUtilities.hlsl"
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_Blur.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_Blur.compute
index 526bda3d111..9bee8a57e7c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_Blur.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_Blur.compute
@@ -1,6 +1,6 @@
#pragma kernel Blur
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_CopyHistory.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_CopyHistory.compute
index f419f570e87..6498ee92736 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_CopyHistory.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_CopyHistory.compute
@@ -1,7 +1,7 @@
#pragma kernel CopyHistoryAccumulation COPY_HISTORY=CopyHistoryAccumulation ACCUMULATION
#pragma kernel CopyHistory COPY_HISTORY=CopyHistory
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_HistoryFix.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_HistoryFix.compute
index e9f21be4974..8e6ea939be8 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_HistoryFix.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_HistoryFix.compute
@@ -1,6 +1,6 @@
#pragma kernel HistoryFix
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_MipGeneration.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_MipGeneration.compute
index daffe389200..b9024137ed5 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_MipGeneration.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_MipGeneration.compute
@@ -1,7 +1,7 @@
#pragma kernel MipGeneration
#pragma kernel CopyMip
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_PostBlur.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_PostBlur.compute
index cbed1a0703c..96281620f7a 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_PostBlur.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_PostBlur.compute
@@ -1,6 +1,6 @@
#pragma kernel PostBlur
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_PreBlur.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_PreBlur.compute
index 2a048be6c3a..22f6dfe6a91 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_PreBlur.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_PreBlur.compute
@@ -1,6 +1,6 @@
#pragma kernel PreBlur
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_TemporalAccumulation.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_TemporalAccumulation.compute
index 0b7554bb2ca..4150db65190 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_TemporalAccumulation.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_TemporalAccumulation.compute
@@ -1,6 +1,6 @@
#pragma kernel TemporalAccumulation
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/Material/Builtin/BuiltinData.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_TemporalStabilization.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_TemporalStabilization.compute
index 319721ab4f1..a1701a975b0 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_TemporalStabilization.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReBlur/ReBlur_TemporalStabilization.compute
@@ -1,6 +1,6 @@
#pragma kernel TemporalStabilization
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReflectionDenoiser.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReflectionDenoiser.compute
index b9808f2686e..cc3bd289287 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReflectionDenoiser.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/ReflectionDenoiser.compute
@@ -6,7 +6,7 @@
#pragma kernel BilateralFilterH_HR BILATERAL_FILTER=BilateralFilterH_HR HALF_RESOLUTION
#pragma kernel BilateralFilterV_HR BILATERAL_FILTER=BilateralFilterV_HR FINAL_PASS HALF_RESOLUTION
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/SimpleDenoiser.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/SimpleDenoiser.compute
index 5edde8cacc4..a0e0bd7f8aa 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/SimpleDenoiser.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/SimpleDenoiser.compute
@@ -1,5 +1,5 @@
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// Temporal Filtering kernels
#pragma kernel BilateralFilterHSingle BILATERAL_FILTER=BilateralFilterHSingle SINGLE_CHANNEL
@@ -9,7 +9,7 @@
#pragma kernel BilateralFilterVColor BILATERAL_FILTER=BilateralFilterVColor FINAL_PASS
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute
index 6eecfcd151c..43b53428452 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Denoising/TemporalFilter.compute
@@ -13,7 +13,7 @@
#pragma kernel OutputHistoryArray OUTPUT_IS_ARRAY
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// Common includes
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/IndirectDiffuse/RaytracingIndirectDiffuse.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/IndirectDiffuse/RaytracingIndirectDiffuse.compute
index 4acd845cd52..db2839f382b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/IndirectDiffuse/RaytracingIndirectDiffuse.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/IndirectDiffuse/RaytracingIndirectDiffuse.compute
@@ -3,7 +3,7 @@
#pragma kernel IndirectDiffuseIntegrationUpscaleHalfRes
#pragma kernel IndirectDiffuseIntegrationUpscaleFullRes
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// Include and define the shader pass
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPass.cs.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayMarching.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayMarching.compute
index 7e04b3664fa..94a4c621691 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayMarching.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayMarching.compute
@@ -1,7 +1,7 @@
#pragma kernel RayMarchKernel RAY_MARCH_KERNEL=RayMarchKernel
#pragma kernel RayMarchHalfKernel RAY_MARCH_KERNEL=RayMarchHalfKernel HALF_RESOLUTION
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// Include and define the shader pass
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPass.cs.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingAmbientOcclusion.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingAmbientOcclusion.compute
index 76ddadd9857..0c9b33b4333 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingAmbientOcclusion.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RayTracingAmbientOcclusion.compute
@@ -1,13 +1,13 @@
#pragma kernel RTAOApplyIntensity
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// HDRP generic includes
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// #pragma enable_d3d11_debug_symbols
// Tile size of this compute
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute
index ba545fc783b..9bc57f224e0 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingLightCluster.compute
@@ -1,7 +1,7 @@
#pragma kernel RaytracingLightCluster
#pragma kernel RaytracingLightCull
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// SRP & HDRP includes
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingReflectionFilter.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingReflectionFilter.compute
index a426d991d54..e58704c7b06 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingReflectionFilter.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/RaytracingReflectionFilter.compute
@@ -1,7 +1,7 @@
#pragma kernel ReflectionAdjustWeight
#pragma kernel ReflectionUpscale
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Reflections/RaytracingReflections.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Reflections/RaytracingReflections.compute
index 12aa9dd3997..49e5d857035 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Reflections/RaytracingReflections.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Reflections/RaytracingReflections.compute
@@ -8,7 +8,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ShaderPass.cs.hlsl"
#define SHADERPASS SHADERPASS_RAYTRACING
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute
index def31ddbec5..e0078e463e3 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadow.compute
@@ -46,7 +46,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingMIS.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RayTracingShadowUtilities.hlsl"
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadowFilter.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadowFilter.compute
index 3e0d45f7535..64c8d151067 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadowFilter.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/Shadows/RaytracingShadowFilter.compute
@@ -19,7 +19,7 @@
// Debug
#pragma kernel WriteShadowTextureDebug
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/SubSurface/RayTracingSubSurface.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/SubSurface/RayTracingSubSurface.compute
index b638fa1a57f..ccc16e04c34 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/SubSurface/RayTracingSubSurface.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Raytracing/Shaders/SubSurface/RayTracingSubSurface.compute
@@ -2,7 +2,7 @@
#pragma kernel BlendSubSurfaceData
#pragma kernel BlendSubSurfaceDataWithGI
-#pragma only_renderers d3d11 xboxseries ps5
+#pragma only_renderers d3d11 xboxseries ps5 switch2
// Given that this pass does not use the shadow algorithm multi-compile, we need to define SHADOW_LOW to quite the shadow algorithm error
#define SHADOW_LOW
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/ColorPyramid.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/ColorPyramid.compute
index a0a7083cf6f..9101956b46c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/ColorPyramid.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/ColorPyramid.compute
@@ -19,7 +19,7 @@
// Author: Bob Brown
//
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel KColorGaussian KERNEL_SIZE=8 MAIN_GAUSSIAN=KColorGaussian
#pragma kernel KColorDownsample KERNEL_SIZE=8 MAIN_DOWNSAMPLE=KColorDownsample
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/ColorPyramidPS.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/ColorPyramidPS.shader
index d568a012215..9f4ed8d25a1 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/ColorPyramidPS.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/ColorPyramidPS.shader
@@ -13,7 +13,7 @@ Shader "Hidden/ColorPyramidPS"
HLSLPROGRAM
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma vertex Vert
#pragma fragment Frag
#define DISABLE_TEXTURE2D_X_ARRAY 1
@@ -30,7 +30,7 @@ Shader "Hidden/ColorPyramidPS"
HLSLPROGRAM
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma vertex Vert
#pragma fragment Frag
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/ColorPyramidPS.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderersUtils.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderersUtils.shader
index 290f5e6735e..22b83db62bc 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderersUtils.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassRenderersUtils.shader
@@ -7,7 +7,7 @@ Shader "Hidden/HDRP/CustomPassRenderersUtils"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassUtils.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassUtils.shader
index 207a0214dea..046e335b826 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassUtils.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassUtils.shader
@@ -5,7 +5,7 @@ Shader "Hidden/HDRP/CustomPassUtils"
#pragma vertex Vert
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/CustomPass/CustomPassCommon.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/DepthPyramid.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/DepthPyramid.compute
index 57e79ae6baf..f0ed38f0482 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/DepthPyramid.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/DepthPyramid.compute
@@ -2,7 +2,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/TextureXR.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/DepthPyramidConstants.cs.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_local _ ENABLE_CHECKERBOARD
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader
index e9826d586b1..dddcfa68550 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/Distortion/ApplyDistortion.shader
@@ -9,7 +9,7 @@ Shader "Hidden/HDRP/ApplyDistortion"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma editor_sync_compilation
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FSR2Pass.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FSR2Pass.cs
index 0f5e04a7740..532946b11e1 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FSR2Pass.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/FSR2Pass.cs
@@ -25,9 +25,15 @@ public static bool SetupFeature()
Debug.LogWarning("Cannot instantiate AMD device because the version HDRP expects does not match the backend version.");
return false;
}
+
+ bool deviceReady = AMD.GraphicsDevice.device != null;
+ if (!deviceReady)
+ {
+ AMD.GraphicsDevice.CreateGraphicsDevice();
+ deviceReady = AMD.GraphicsDevice.device != null;
+ }
- AMD.GraphicsDevice device = AMD.GraphicsDevice.CreateGraphicsDevice();
- return device != null;
+ return deviceReady;
#else
return false;
#endif
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/GenerateMaxZ.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/GenerateMaxZ.compute
index 2875aeac759..bfca96d7ed0 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/GenerateMaxZ.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/GenerateMaxZ.compute
@@ -2,7 +2,7 @@
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/TextureXR.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel ComputeMaxZ MAX_Z_DOWNSAMPLE=1
#pragma kernel ComputeFinalMask FINAL_MASK=1
@@ -120,7 +120,7 @@ void ComputeMaxZ(uint3 dispatchThreadId : SV_DispatchThreadID, uint gid : SV_Gro
#elif FINAL_MASK
-TEXTURE2D_X(_InputTexture);
+TEXTURE2D_X_FLOAT(_InputTexture);
RW_TEXTURE2D_X(OUT_MASK_FORMAT, _OutputTexture);
void DownsampleDepth(float s0, float s1, float s2, float s3, out float maxDepth)
@@ -171,7 +171,7 @@ void ComputeFinalMask(uint3 dispatchThreadId : SV_DispatchThreadID, uint gid : S
#elif DILATE_MASK
-TEXTURE2D_X(_InputTexture);
+TEXTURE2D_X_FLOAT(_InputTexture);
RW_TEXTURE2D_X(OUT_MASK_FORMAT, _OutputTexture);
OUT_MASK_FORMAT DilateValue(OUT_MASK_FORMAT currMax, OUT_MASK_FORMAT currSample)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/AmbientOcclusionResolve.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/AmbientOcclusionResolve.shader
index cd9465280ff..ea6218b3e2f 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/AmbientOcclusionResolve.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/AmbientOcclusionResolve.shader
@@ -2,7 +2,7 @@ Shader "Hidden/HDRP/AOResolve"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
//#pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/ColorResolve.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/ColorResolve.shader
index 7a923ac38dc..f7cf351414b 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/ColorResolve.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/ColorResolve.shader
@@ -2,7 +2,7 @@ Shader "Hidden/HDRP/ColorResolve"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/DepthValues.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/DepthValues.shader
index e35257553a0..34239d2a2c4 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/DepthValues.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/DepthValues.shader
@@ -2,7 +2,7 @@ Shader "Hidden/HDRP/DepthValues"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_fragment _ _HAS_MOTION_VECTORS _DEPTH_ONLY
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/MotionVecResolve.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/MotionVecResolve.shader
index 079cd75ecf3..3a20ae10dc7 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/MotionVecResolve.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MSAA/MotionVecResolve.shader
@@ -2,7 +2,7 @@ Shader "Hidden/HDRP/MotionVecResolve"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MotionVectors/CameraMotionVectors.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MotionVectors/CameraMotionVectors.shader
index 3cbedae2d56..80066d232ed 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MotionVectors/CameraMotionVectors.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/RenderPass/MotionVectors/CameraMotionVectors.shader
@@ -10,7 +10,7 @@ Shader "Hidden/HDRP/CameraMotionVectors"
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/RenderPipelineSettings.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/RenderPipelineSettings.cs
index d502899e358..7c2ae3f6bc3 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/RenderPipelineSettings.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Settings/RenderPipelineSettings.cs
@@ -67,6 +67,21 @@ public enum ColorBufferFormat
R16G16B16A16 = GraphicsFormat.R16G16B16A16_SFloat
}
+ ///
+ /// Depth Buffer format.
+ ///
+ public enum DepthBufferFormat
+ {
+ /// Automatically switch between 32 and 24 bit depth depending on the platform.
+ Auto = 0,
+ /// Forces HDRP to use 32 bit depth + 8 bit stencil buffer
+ ForceD32 = GraphicsFormat.D32_SFloat_S8_UInt,
+ /// Forces HDRP to use 24 bit depth + 8 bit stencil buffer
+ ForceD24 = GraphicsFormat.D24_UNorm_S8_UInt,
+ /// Forces HDRP to use 16 bit depth + 8 bit stencil buffer. Improves performances of depth related effects but can cause Z-Fighting due to the low precision.
+ ForceD16 = GraphicsFormat.D16_UNorm_S8_UInt,
+ }
+
///
/// Custom Buffers format.
///
@@ -116,6 +131,7 @@ internal static RenderPipelineSettings NewDefault()
supportTransparentDepthPrepass = true,
supportTransparentDepthPostpass = true,
colorBufferFormat = ColorBufferFormat.R11G11B10,
+ depthBufferFormat = DepthBufferFormat.Auto,
supportCustomPass = true,
supportVariableRateShading = true,
customBufferFormat = CustomBufferFormat.R8G8B8A8,
@@ -315,6 +331,8 @@ public string[] renderingLayerNames
public bool supportTransparentDepthPostpass;
/// Color buffer format.
public ColorBufferFormat colorBufferFormat;
+ /// Depth buffer format.
+ public DepthBufferFormat depthBufferFormat;
/// Support custom passes.
public bool supportCustomPass;
/// Support variable rate shading.
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ComputeThickness.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ComputeThickness.shader
index c86878e4efd..9289dbfd9c6 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ComputeThickness.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/ComputeThickness.shader
@@ -3,7 +3,7 @@ Shader "Renderers/Thickness"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//enable GPU instancing support
#pragma multi_compile_instancing
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/VertMesh.hlsl b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/VertMesh.hlsl
index 8ab1776161f..d262e944a3d 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/VertMesh.hlsl
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/ShaderPass/VertMesh.hlsl
@@ -187,6 +187,8 @@ VaryingsMeshType VertMesh(AttributesMesh input, float3 worldSpaceOffset
#ifdef ATTRIBUTES_NEED_TANGENT
float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
+#else
+ float4 tangentWS = float4(1.0, 0.0, 0.0, 0.0);
#endif
// Do vertex modification in camera relative space (if enable)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs
index 9cc312463ba..e18bf714c65 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/HDUtils.cs
@@ -810,6 +810,9 @@ internal static bool IsSupportedGraphicDevice(GraphicsDeviceType graphicDevice)
if (graphicDevice == GraphicsDeviceType.Switch) // Switch support only enabled when forced by env variable for CI
return Environment.GetEnvironmentVariable("ENABLE_HDRP_SWITCH_SUPPORT") != null || Application.platform == RuntimePlatform.Switch;
+ if (graphicDevice == GraphicsDeviceType.Switch2) // Switch2 support only enabled when forced by env variable for CI
+ return Environment.GetEnvironmentVariable("ENABLE_HDRP_SWITCH2_SUPPORT") != null || Application.platform == RuntimePlatform.Switch2;
+
return (graphicDevice == GraphicsDeviceType.Direct3D11 ||
graphicDevice == GraphicsDeviceType.Direct3D12 ||
graphicDevice == GraphicsDeviceType.PlayStation4 ||
@@ -820,7 +823,9 @@ internal static bool IsSupportedGraphicDevice(GraphicsDeviceType graphicDevice)
graphicDevice == GraphicsDeviceType.GameCoreXboxOne ||
graphicDevice == GraphicsDeviceType.GameCoreXboxSeries ||
graphicDevice == GraphicsDeviceType.Metal ||
- graphicDevice == GraphicsDeviceType.Vulkan);
+ graphicDevice == GraphicsDeviceType.Vulkan
+ // || graphicDevice == GraphicsDeviceType.Switch2
+ );
}
internal static bool IsHardwareDynamicResolutionSupportedByDevice(GraphicsDeviceType deviceType)
@@ -838,6 +843,8 @@ internal static bool IsSupportedBuildTarget(UnityEditor.BuildTarget buildTarget)
{
if (buildTarget == UnityEditor.BuildTarget.Switch) // Switch support only enabled when forced by env variable for CI
return Environment.GetEnvironmentVariable("ENABLE_HDRP_SWITCH_SUPPORT") != null;
+ if (buildTarget == UnityEditor.BuildTarget.Switch2) // Switch2 support only enabled when forced by env variable for CI
+ return Environment.GetEnvironmentVariable("ENABLE_HDRP_SWITCH2_SUPPORT") != null;
return (buildTarget == UnityEditor.BuildTarget.StandaloneWindows ||
buildTarget == UnityEditor.BuildTarget.StandaloneWindows64 ||
buildTarget == UnityEditor.BuildTarget.StandaloneLinux64 ||
@@ -846,6 +853,7 @@ internal static bool IsSupportedBuildTarget(UnityEditor.BuildTarget buildTarget)
buildTarget == UnityEditor.BuildTarget.XboxOne ||
buildTarget == UnityEditor.BuildTarget.GameCoreXboxOne ||
buildTarget == UnityEditor.BuildTarget.GameCoreXboxSeries ||
+ buildTarget == UnityEditor.BuildTarget.Switch2 ||
buildTarget == UnityEditor.BuildTarget.PS4 ||
buildTarget == UnityEditor.BuildTarget.PS5 ||
// buildTarget == UnityEditor.BuildTarget.iOS || // IOS isn't supported
@@ -1271,8 +1279,22 @@ internal static string GetUnsupportedAPIMessage(string graphicAPI)
if (isSupportedBuildTarget)
msg = "Platform " + currentPlatform + " with graphics API " + graphicAPI + " is not supported with HDRP";
else
+ {
msg = "Platform " + currentPlatform + " is not supported with HDRP";
+#if UNITY_EDITOR
+ if (buildTarget == UnityEditor.BuildTarget.Switch2)
+ {
+ msg += ". (For testing purpose only, un-hide by defining environment variable ENABLE_HDRP_SWITCH2_SUPPORT)";
+ }
+#else
+ if (currentPlatform == "Switch2 OS")
+ {
+ msg += ". (For testing purpose only, un-hide by defining environment variable ENABLE_HDRP_SWITCH2_SUPPORT)";
+ }
+#endif
+ }
+
// Display more information to the users when it should have use Metal instead of OpenGL
if (graphicAPI.StartsWith("OpenGL"))
{
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture3DAtlas.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture3DAtlas.compute
index b0ce842cf82..c6592812ee6 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture3DAtlas.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipeline/Utility/Texture3DAtlas.compute
@@ -1,6 +1,6 @@
#pragma kernel Copy
#pragma kernel GenerateMipMap
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/ShaderGraph/Fullscreen Basic HDRP.shadergraph.meta b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/ShaderGraph/Fullscreen Basic HDRP.shadergraph.meta
index a586bfe41bb..de5da3b58c7 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/ShaderGraph/Fullscreen Basic HDRP.shadergraph.meta
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/RenderPipelineResources/ShaderGraph/Fullscreen Basic HDRP.shadergraph.meta
@@ -9,31 +9,17 @@ ScriptedImporter:
assetBundleVariant:
script: {fileID: 11500000, guid: 625f186215c104763be7675aa2d941aa, type: 3}
useAsTemplate: 1
+ exposeTemplateAsShader: 0
template:
name: Fullscreen Basic - HDRP
category: Image Processing
- description: 'An HDRP Shader Graph template that does simple fullscreen image
- adjustments including tinting, saturation, and contrast.
-
-
- Fullscreen
+ description: "An HDRP Shader Graph template that does simple fullscreen image
+ adjustments including tinting, saturation, and contrast.\r\n\r\nFullscreen
shaders are intended to be used to apply image adjustments for applications
like post-process filters. They are not intended to be applied to individual
- meshes.
-
-
- To apply a fullscreen shader as a post-process filter, select
- HDRP''s renderer data asset and click the Add Renderer Feature button at the
- bottom of the Inspector. Choose Full Screen Pass Renderer Feature. Then create
- a material from your fullscreen shader and apply it to the Pass Material slot
- of the Full Screen Pass Renderer Feature.
-
-
- Supported Pipeline(s):
- HDRP
-
- Active Target: Fullscreen
-
- VFX Graph Support: disabled'
+ meshes.\r\n\r\nTo apply a fullscreen shader as a post-process filter, create
+ a Custom Pass Volume, add a Fullscreen Custom Pass and assign a material created
+ from your fullscreen shader.\r\n\r\nSupported Pipeline(s): HDRP\r\nActive
+ Target: Fullscreen\r\nVFX Graph Support: disabled\r"
icon: {instanceID: 0}
thumbnail: {fileID: 2800000, guid: d62e6a58a6263764faa13fa5481cbf1e, type: 3}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Settings/HDRenderPipelineRuntimeShaders.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Settings/HDRenderPipelineRuntimeShaders.cs
index eeb04ca2a2f..20641bafddc 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Settings/HDRenderPipelineRuntimeShaders.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Settings/HDRenderPipelineRuntimeShaders.cs
@@ -120,7 +120,7 @@ public Shader copyDepthBufferPS
get => m_CopyDepthBufferPS;
set => this.SetValueAndNotify(ref m_CopyDepthBufferPS, value);
}
-
+
[SerializeField, ResourcePath("Runtime/ShaderLibrary/Blit.shader")]
private Shader m_BlitPS;
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/Blit.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/Blit.shader
index 63fcc2ead04..364073bf243 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/Blit.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/Blit.shader
@@ -4,7 +4,7 @@ Shader "Hidden/HDRP/Blit"
#pragma target 4.5
#pragma editor_sync_compilation
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ DISABLE_TEXTURE2D_X_ARRAY
#pragma multi_compile _ BLIT_SINGLE_SLICE
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/BlitColorAndDepth.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/BlitColorAndDepth.shader
index 8d7351af6e9..06f403a4a3c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/BlitColorAndDepth.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/BlitColorAndDepth.shader
@@ -4,12 +4,12 @@ Shader "Hidden/HDRP/BlitColorAndDepth"
#pragma target 4.5
#pragma editor_sync_compilation
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ DISABLE_TEXTURE2D_X_ARRAY
#pragma multi_compile _ BLIT_SINGLE_SLICE
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
- #include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/BlitColorAndDepth.hlsl"
+ #include_with_pragmas "Packages/com.unity.render-pipelines.core/Runtime/Utilities/BlitColorAndDepth.hlsl"
ENDHLSL
SubShader
@@ -39,7 +39,18 @@ Shader "Hidden/HDRP/BlitColorAndDepth"
#pragma fragment FragColorAndDepth
ENDHLSL
}
+
+ // 2: Depth Only
+ Pass
+ {
+ ZWrite On ZTest Always Blend Off Cull Off ColorMask 0
+ Name "DepthOnly"
+ HLSLPROGRAM
+ #pragma vertex Vert
+ #pragma fragment FragDepthOnly
+ ENDHLSL
+ }
}
Fallback Off
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ClearStencilBuffer.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ClearStencilBuffer.shader
index b56481778b1..edf57c301ff 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ClearStencilBuffer.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ClearStencilBuffer.shader
@@ -8,7 +8,7 @@ Shader "Hidden/HDRP/ClearStencilBuffer"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyDepthBuffer.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyDepthBuffer.shader
index 69e24c42df4..6450e147eeb 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyDepthBuffer.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyDepthBuffer.shader
@@ -27,7 +27,7 @@ Shader "Hidden/HDRP/CopyDepthBuffer"
HLSLPROGRAM
#pragma target 4.5
#pragma editor_sync_compilation
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma fragment Frag
#pragma vertex Vert
//#pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyStencilBuffer.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyStencilBuffer.shader
index 22d9c8535c6..38e4322f74c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyStencilBuffer.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/CopyStencilBuffer.shader
@@ -9,7 +9,7 @@ Shader "Hidden/HDRP/CopyStencilBuffer"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/DownsampleDepth.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/DownsampleDepth.shader
index 1a7c500bb24..1f1acff1716 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/DownsampleDepth.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/DownsampleDepth.shader
@@ -5,7 +5,7 @@ Shader "Hidden/HDRP/DownsampleDepth"
#pragma target 4.5
#pragma editor_sync_compilation
#pragma multi_compile_local_fragment _ GATHER_DOWNSAMPLE
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ResolveStencilBuffer.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ResolveStencilBuffer.compute
index 03ae1f2ef86..567ec1e6a81 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ResolveStencilBuffer.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ResolveStencilBuffer.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel Main
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl
index 8be2d26bdfc..f099f5e35a4 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl
@@ -104,8 +104,13 @@ CBUFFER_START(UnityPerDraw)
CBUFFER_END
+static const uint unity_RendererUserValue = asuint(unity_RenderingLayer.y);
+
#endif // DOTS_INSTANCING_ON
+// The renderer user values are packed in unity_RenderingLayer. So we need a dummy property to be able to use Shader.PropertyToID.
+uint unity_RendererUserValuesPropertyEntry;
+
CBUFFER_START(UnityPerDrawRare)
float4x4 glstate_matrix_transpose_modelview0;
CBUFFER_END
@@ -619,12 +624,14 @@ UNITY_DOTS_INSTANCING_START(BuiltinPropertyMetadata)
UNITY_DOTS_INSTANCED_PROP_OVERRIDE_SUPPORTED(float3x4, unity_MatrixPreviousMI)
UNITY_DOTS_INSTANCED_PROP_OVERRIDE_SUPPORTED(SH, unity_SHCoefficients)
UNITY_DOTS_INSTANCED_PROP_OVERRIDE_SUPPORTED(uint2, unity_EntityId)
+ UNITY_DOTS_INSTANCED_PROP_OVERRIDE_SUPPORTED(uint, unity_RendererUserValuesPropertyEntry)
UNITY_DOTS_INSTANCING_END(BuiltinPropertyMetadata)
#define unity_LODFade LoadDOTSInstancedData_LODFade()
#define unity_LightmapST UNITY_ACCESS_DOTS_INSTANCED_PROP(float4, unity_LightmapST)
#define unity_LightmapIndex UNITY_ACCESS_DOTS_INSTANCED_PROP(float4, unity_LightmapIndex)
#define unity_DynamicLightmapST UNITY_ACCESS_DOTS_INSTANCED_PROP(float4, unity_DynamicLightmapST)
+#define unity_RendererUserValue (UNITY_ACCESS_DOTS_INSTANCED_PROP(uint, unity_RendererUserValuesPropertyEntry))
#define unity_SHAr LoadDOTSInstancedData_SHAr()
#define unity_SHAg LoadDOTSInstancedData_SHAg()
#define unity_SHAb LoadDOTSInstancedData_SHAb()
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/UpsampleTransparent.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/UpsampleTransparent.shader
index 18726abbc46..9b3118599ec 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/UpsampleTransparent.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/UpsampleTransparent.shader
@@ -4,7 +4,7 @@ Shader "Hidden/HDRP/UpsampleTransparent"
#pragma target 4.5
#pragma editor_sync_compilation
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XRMirrorView.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XRMirrorView.shader
index 57b413d3769..93f0e0b2d09 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XRMirrorView.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XRMirrorView.shader
@@ -6,7 +6,7 @@ Shader "Hidden/HDRP/XRMirrorView"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_local_fragment _ HDR_COLORSPACE_CONVERSION_AND_ENCODING
#pragma multi_compile_fragment _ DISABLE_TEXTURE2D_X_ARRAY
ENDHLSL
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XROcclusionMesh.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XROcclusionMesh.shader
index 38bdad7bc2b..86dff9b829d 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XROcclusionMesh.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/XROcclusionMesh.shader
@@ -2,7 +2,7 @@ Shader "Hidden/HDRP/XROcclusionMesh"
{
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ XR_OCCLUSION_MESH_COMBINED
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/AmbientProbeConvolution.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/AmbientProbeConvolution.compute
index adad297c575..7cc158819c4 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/AmbientProbeConvolution.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/AmbientProbeConvolution.compute
@@ -7,7 +7,7 @@
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Hammersley.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Sampling.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// Regular ambient probe convolution
// Always use mips and output separate diffuse buffer.
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/BlitCubemap.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/BlitCubemap.shader
index f4248c78e77..36c24f1a875 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/BlitCubemap.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/BlitCubemap.shader
@@ -12,7 +12,7 @@ Shader "Hidden/BlitCubemap" {
#pragma vertex vert
#pragma fragment frag
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/BakeCloudShadows.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/BakeCloudShadows.compute
index 35bdbbfd014..fb1bb1ee1e5 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/BakeCloudShadows.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/BakeCloudShadows.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#pragma enable_d3d11_debug_symbols
#pragma multi_compile_local LAYER1_OFF LAYER1_STATIC LAYER1_PROCEDURAL LAYER1_FLOWMAP
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/BakeCloudTexture.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/BakeCloudTexture.compute
index 2d74e82c7d6..0d7177a3494 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/BakeCloudTexture.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/BakeCloudTexture.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_local _ USE_SECOND_CLOUD_LAYER
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/CloudLayer.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/CloudLayer.shader
index 9134ff4fa96..4e98777c971 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/CloudLayer.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/CloudSystem/CloudLayer/CloudLayer.shader
@@ -6,7 +6,7 @@ Shader "Hidden/HDRP/Sky/CloudLayer"
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#pragma enable_d3d11_debug_symbols
#pragma multi_compile_local LAYER1_STATIC LAYER1_PROCEDURAL LAYER1_FLOWMAP
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/GradientSky/GradientSky.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/GradientSky/GradientSky.shader
index ffa0d53747d..e2f3ade6604 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/GradientSky/GradientSky.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/GradientSky/GradientSky.shader
@@ -6,7 +6,7 @@ Shader "Hidden/HDRP/Sky/GradientSky"
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader
index 6685de59727..3b44e190e15 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/HDRISky.shader
@@ -6,7 +6,7 @@ Shader "Hidden/HDRP/Sky/HDRISky"
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#define LIGHTLOOP_DISABLE_TILE_AND_CLUSTER
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/IntegrateHDRISky.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/IntegrateHDRISky.shader
index f9760c745c8..973ac31a118 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/IntegrateHDRISky.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/HDRISky/IntegrateHDRISky.shader
@@ -18,7 +18,7 @@ Shader "Hidden/HDRP/IntegrateHDRI"
#pragma vertex Vert
#pragma fragment Frag
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/GroundIrradiancePrecomputation.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/GroundIrradiancePrecomputation.compute
index cc54b81ca45..7c415274cd6 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/GroundIrradiancePrecomputation.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/GroundIrradiancePrecomputation.compute
@@ -1,5 +1,5 @@
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel main
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/InScatteredRadiancePrecomputation.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/InScatteredRadiancePrecomputation.compute
index 069b802ba19..3b8e6dc2623 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/InScatteredRadiancePrecomputation.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/InScatteredRadiancePrecomputation.compute
@@ -1,5 +1,5 @@
// #pragma enable_d3d11_debug_symbols
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma kernel main
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.cs
index 7a402f74de2..652581df332 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.cs
@@ -23,6 +23,7 @@ public enum PhysicallyBasedSkyModel
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[SkyUniqueID((int)SkyType.PhysicallyBased)]
[HDRPHelpURL("create-a-physically-based-sky")]
+ [DisplayInfo(name = "Physically Based Sky")]
public partial class PhysicallyBasedSky : SkySettings
{
///
@@ -320,12 +321,6 @@ internal float GetOzoneLayerMinimumAltitude()
return k_DefaultOzoneMinimumAltitude;
}
- PhysicallyBasedSky()
- {
- displayName = "Physically Based Sky";
- }
-
-
internal int GetPrecomputationHashCode(HDCamera hdCamera)
{
int hash = GetPrecomputationHashCode();
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.shader
index 463ccd430af..7d2d9d756aa 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/PhysicallyBasedSky.shader
@@ -7,7 +7,7 @@ Shader "Hidden/HDRP/Sky/PbrSky"
// #pragma enable_d3d11_debug_symbols
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile_fragment _ LOCAL_SKY
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/SkyLUTGenerator.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/SkyLUTGenerator.compute
index b50f8dba4c6..7c8f925fccb 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/SkyLUTGenerator.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Sky/PhysicallyBasedSky/SkyLUTGenerator.compute
@@ -1,7 +1,7 @@
// Ref: A Scalable and Production Ready Sky and Atmosphere Rendering Technique - Hillaire, ESGR 2020
// https://sebh.github.io/publications/egsr2020.pdf
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#pragma enable_d3d11_debug_symbols
#pragma kernel MultiScatteringLUT OUTPUT_MULTISCATTERING
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/GPUPrefixSum/GPUPrefixSum.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/GPUPrefixSum/GPUPrefixSum.compute
index d80989f603c..042c8e9dae2 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/GPUPrefixSum/GPUPrefixSum.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/GPUPrefixSum/GPUPrefixSum.compute
@@ -9,7 +9,7 @@
#include "Packages/com.unity.render-pipelines.core/Runtime/Utilities/GPUPrefixSum/GPUPrefixSum.Data.cs.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
@@ -139,7 +139,11 @@ void MainPrefixSumOnGroupCommon(int3 dispatchThreadID, int groupThreadIndex, boo
//Hillis Steele Scan
for (int i = 1; i < GROUP_SIZE; i <<= 1)
{
- uint val = groupThreadIndex >= i ? gs_prefixCache[groupThreadIndex - i] : 0u;
+ //Avoiding ternary operator (it would evaluate both sides and fetch invalid indices, causing crash on some GPUs)
+ uint val = 0u;
+ if (groupThreadIndex >= i)
+ val = gs_prefixCache[groupThreadIndex - i];
+
GroupMemoryBarrierWithGroupSync();
gs_prefixCache[groupThreadIndex] += val;
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/GPUSort/GPUSort.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/GPUSort/GPUSort.compute
index 886b288be37..f8cdd1a4600 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/GPUSort/GPUSort.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Utilities/GPUSort/GPUSort.compute
@@ -4,7 +4,7 @@
// Ref: https://poniesandlight.co.uk/reflect/bitonic_merge_sort/
#pragma multi_compile _ STAGE_BMS STAGE_LOCAL_DISPERSE STAGE_BIG_FLIP STAGE_BIG_DISPERSE
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// Disable warning for auto unrolling of single iteration loop.
#pragma warning(disable : 3557)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/VirtualTexturing/Shaders/DownsampleVTFeedback.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/VirtualTexturing/Shaders/DownsampleVTFeedback.compute
index 1cdff7dc6ee..1b88c3bd314 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/VirtualTexturing/Shaders/DownsampleVTFeedback.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/VirtualTexturing/Shaders/DownsampleVTFeedback.compute
@@ -2,7 +2,7 @@
#pragma kernel KMain
#pragma kernel KMainMSAA
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.high-definition/Runtime/ShaderLibrary/ShaderVariables.hlsl"
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/FourierTransform.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/FourierTransform.compute
index 55e1a2f3c60..8c385b89c0e 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/FourierTransform.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/FourierTransform.compute
@@ -18,7 +18,7 @@
// Generic Graphics includes
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// The set of possible kernels
#pragma kernel RowPassTi_256 FFT_PASS_TI=RowPassTi_256 FFT_RESOLUTION=256 BUTTERFLY_COUNT=8 COMPENSATION_FACTOR=1.0
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/SampleWaterSurface.hlsl b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/SampleWaterSurface.hlsl
index 082ba04846b..fb09f49872e 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/SampleWaterSurface.hlsl
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/SampleWaterSurface.hlsl
@@ -302,7 +302,7 @@ void EvaluateDisplacement(float3 positionOS, float3 verticalDisplacements, out f
#if defined(SUPPORT_WATER_DEFORMATION)
// Apply the deformation data
- float4 deformation = EvaluateWaterDeformation(positionAWS + verticalDisplacements);
+ float4 deformation = EvaluateWaterDeformation(positionAWS);
horizontalDisplacement = deformation.yz;
verticalDisplacement += deformation.x;
lowFrequencyHeight += deformation.x;
@@ -317,18 +317,20 @@ struct WaterDisplacementData
void EvaluateWaterDisplacement(float3 positionOS, out WaterDisplacementData displacementData)
{
- float2 simulationHorizontalDisplacement;
- float2 deformationHorizontalDisplacement;
- float3 verticalDisplacements;
- EvaluateSimulationDisplacement(positionOS, simulationHorizontalDisplacement, verticalDisplacements);
-
+ // This is a float 3 because there's one displacement per frequency band.
+ float3 simulationVerticalDisplacements;
+ float2 simulationHorizontalDisplacement;
+
+ EvaluateSimulationDisplacement(positionOS, simulationHorizontalDisplacement, simulationVerticalDisplacements);
+
+ // Out parameters to evaluate deformation displacement.
+ float deformationVerticalDisplacement;
+ float2 deformationHorizontalDisplacement;
float lowFrequencyHeight;
- float3 displacement = float3(simulationHorizontalDisplacement.x, 0, simulationHorizontalDisplacement.y);
- EvaluateDisplacement(positionOS + displacement, verticalDisplacements, displacement.y, deformationHorizontalDisplacement, lowFrequencyHeight);
+ EvaluateDisplacement(positionOS, simulationVerticalDisplacements, deformationVerticalDisplacement, deformationHorizontalDisplacement, lowFrequencyHeight);
- displacement.xz += deformationHorizontalDisplacement.xy;
-
- displacementData.displacement = displacement;
+ // Simulation displacement is not included in the displacement to avoid having water decal effects move with the waves if the distand wind is high.
+ displacementData.displacement = float3(deformationHorizontalDisplacement.x, deformationVerticalDisplacement, deformationHorizontalDisplacement.y);
displacementData.lowFrequencyHeight = lowFrequencyHeight;
#if defined(SHADER_STAGE_VERTEX) && !defined(WATER_DISPLACEMENT)
@@ -435,22 +437,17 @@ void SampleSimulation_PS(WaterSimCoord waterCoord, float3 waterMask, float dista
}
}
-void EvaluateWaterAdditionalData(float3 positionOS, float3 transformedPosition, float3 meshNormalOS, float2 horizontalDisplacement, out WaterAdditionalData waterAdditionalData)
+void EvaluateWaterAdditionalData(float3 positionOS, float3 positionRWS, float3 meshNormalOS, float2 horizontalDisplacement, out WaterAdditionalData waterAdditionalData)
{
ZERO_INITIALIZE(WaterAdditionalData, waterAdditionalData);
if (_GridSize.x < 0)
return;
- // Evaluate the pre-displaced absolute position
-#if defined(WATER_DISPLACEMENT)
- float3 positionRWS = positionOS;
-#else
- float3 positionRWS = TransformObjectToWorld_Water(positionOS);
-#endif
- // Evaluate the distance to the camera
+ // Evaluate the distance to the camera. used only if WATER_DISPLACEMENT is defined.
float distanceToCamera = length(positionRWS);
+
// Get the world space transformed postion
- float3 transformedAWS = GetAbsolutePositionWS(transformedPosition);
+ float3 transformedAWS = GetAbsolutePositionWS(positionRWS);
float2 decalUV = EvaluateDecalUV(transformedAWS - float3(horizontalDisplacement.x, 0.0f, horizontalDisplacement.y));
// Compute the texture size param for the filtering
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/UnderWaterUtilities.hlsl b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/UnderWaterUtilities.hlsl
index 4061c46854f..af77c05be04 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/UnderWaterUtilities.hlsl
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/UnderWaterUtilities.hlsl
@@ -62,7 +62,7 @@ bool IsUnderWater(uint2 coord)
TEXTURE2D_X(_WaterGBufferTexture0);
TEXTURE2D_X(_WaterGBufferTexture1);
TEXTURE2D_X(_WaterGBufferTexture2);
-TEXTURE2D_X(_WaterGBufferTexture3);
+TEXTURE2D_X_FLOAT(_WaterGBufferTexture3); // force high-precision else UnpackSurfaceIndex gives incorrect values on builds defaulting to mediump
StructuredBuffer _WaterSurfaceProfiles;
uint UnpackSurfaceIndex(uint2 positionSS)
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterCaustics.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterCaustics.shader
index 73f28a2ac84..68178cc1c35 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterCaustics.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterCaustics.shader
@@ -4,7 +4,7 @@ Shader "Hidden/HDRP/WaterCaustics"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterDecal.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterDecal.shader
index 685fe085416..9ce151d6cb4 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterDecal.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterDecal.shader
@@ -4,7 +4,7 @@ Shader "Hidden/HDRP/WaterDecal"
HLSLINCLUDE
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterDeformation.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterDeformation.compute
index 50aef467e8f..c4915885b8a 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterDeformation.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterDeformation.compute
@@ -1,7 +1,7 @@
#pragma kernel FilterDeformation
#pragma kernel EvaluateDeformationSurfaceGradient
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ HORIZONTAL_DEFORMATION
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterEvaluation.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterEvaluation.compute
index 5c82455b59c..ec60888304c 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterEvaluation.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterEvaluation.compute
@@ -1,6 +1,6 @@
#pragma kernel FindVerticalDisplacements
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterExclusion.shader b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterExclusion.shader
index 1e72406e005..15a1952199e 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterExclusion.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterExclusion.shader
@@ -25,7 +25,7 @@ Shader "Hidden/HDRP/WaterExclusion"
HLSLPROGRAM
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ DOTS_INSTANCING_ON
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterFoam.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterFoam.compute
index 5b7ec0a1fc4..920bdc29330 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterFoam.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterFoam.compute
@@ -1,7 +1,7 @@
#pragma kernel ReprojectFoam
#pragma kernel AttenuateFoam
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterLighting.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterLighting.compute
index 733d772c722..372738e7b81 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterLighting.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterLighting.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#pragma enable_d3d11_debug_symbols
#pragma kernel WaterClearIndirect
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterLine.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterLine.compute
index 0557f3ddc4e..8cbaa51323f 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterLine.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterLine.compute
@@ -1,4 +1,4 @@
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
//#pragma enable_d3d11_debug_symbols
#pragma kernel ClearWaterLine
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterSimulation.compute b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterSimulation.compute
index 2ccf4f83c16..ac853ec57e7 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterSimulation.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/Shaders/WaterSimulation.compute
@@ -6,7 +6,7 @@
#pragma kernel EvaluateInstanceData EVALUATE_INSTANCE_DATA=EvaluateInstanceData
#pragma kernel EvaluateInstanceDataInfinite EVALUATE_INSTANCE_DATA=EvaluateInstanceDataInfinite INFINITE_WATER
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/WaterRendering.cs b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/WaterRendering.cs
index f8dcdae4772..d3a631443af 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/WaterRendering.cs
+++ b/Packages/com.unity.render-pipelines.high-definition/Runtime/Water/WaterRendering.cs
@@ -8,6 +8,7 @@ namespace UnityEngine.Rendering.HighDefinition
[Serializable, VolumeComponentMenu("Rendering/Water Rendering")]
[SupportedOnRenderPipeline(typeof(HDRenderPipelineAsset))]
[HDRPHelpURL("water-use-the-water-system-in-your-project")]
+ [DisplayInfo(name = "Water Rendering")]
public sealed partial class WaterRendering : VolumeComponent
{
///
@@ -27,10 +28,5 @@ public sealed partial class WaterRendering : VolumeComponent
///
[Tooltip("Controls the influence of the ambient light probe on the water surfaces.")]
public ClampedFloatParameter ambientProbeDimmer = new ClampedFloatParameter(0.5f, 0.0f, 1.0f);
-
- WaterRendering()
- {
- displayName = "Water Rendering";
- }
}
}
diff --git a/Packages/com.unity.render-pipelines.high-definition/Samples~/ProceduralSky/Runtime/ProceduralSky/Resources/ProceduralSky.shader b/Packages/com.unity.render-pipelines.high-definition/Samples~/ProceduralSky/Runtime/ProceduralSky/Resources/ProceduralSky.shader
index c3716367065..4079c363deb 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Samples~/ProceduralSky/Runtime/ProceduralSky/Resources/ProceduralSky.shader
+++ b/Packages/com.unity.render-pipelines.high-definition/Samples~/ProceduralSky/Runtime/ProceduralSky/Resources/ProceduralSky.shader
@@ -11,7 +11,7 @@ Shader "Hidden/HDRP/Sky/ProceduralSky"
#pragma editor_sync_compilation
#pragma target 4.5
- #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+ #pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
#pragma multi_compile _ _ENABLE_SUN_DISK
diff --git a/Packages/com.unity.render-pipelines.high-definition/Tests/Editor/HDAnalyticsTests_Defaults.txt b/Packages/com.unity.render-pipelines.high-definition/Tests/Editor/HDAnalyticsTests_Defaults.txt
index 77f3426560d..ba7c26be958 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Tests/Editor/HDAnalyticsTests_Defaults.txt
+++ b/Packages/com.unity.render-pipelines.high-definition/Tests/Editor/HDAnalyticsTests_Defaults.txt
@@ -29,6 +29,7 @@
{"supportTransparentDepthPrepass":"True"},
{"supportTransparentDepthPostpass":"True"},
{"colorBufferFormat":"R11G11B10"},
+{"depthBufferFormat":"Auto"},
{"supportCustomPass":"True"},
{"supportVariableRateShading":"True"},
{"customBufferFormat":"R8G8B8A8"},
diff --git a/Packages/com.unity.render-pipelines.high-definition/Tests/Editor/Utilities/FurnaceTests.compute b/Packages/com.unity.render-pipelines.high-definition/Tests/Editor/Utilities/FurnaceTests.compute
index d8b47cad886..ef81fffa009 100644
--- a/Packages/com.unity.render-pipelines.high-definition/Tests/Editor/Utilities/FurnaceTests.compute
+++ b/Packages/com.unity.render-pipelines.high-definition/Tests/Editor/Utilities/FurnaceTests.compute
@@ -1,7 +1,7 @@
#pragma kernel FurnaceTest
#pragma kernel FurnaceTestSampled
-#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch
+#pragma only_renderers d3d11 playstation xboxone xboxseries vulkan metal switch switch2
// #pragma enable_d3d11_debug_symbols
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/Base2DMaterialUpgrader.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/Base2DMaterialUpgrader.cs
new file mode 100644
index 00000000000..0db8d4e6003
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/Base2DMaterialUpgrader.cs
@@ -0,0 +1,183 @@
+using System;
+using System.IO;
+using System.Collections.Generic;
+using UnityEditor.Rendering.Universal;
+using UnityEngine;
+using UnityEngine.Rendering.Universal;
+using static UnityEditor.AssetDatabase;
+using System.Collections;
+using System.Runtime.Remoting.Messaging;
+
+namespace UnityEditor.Rendering.Universal
+{
+ internal abstract class Base2DMaterialUpgrader : RenderPipelineConverter
+ {
+ public const string k_PackageMaterialsPath = "Packages/com.unity.render-pipelines.universal/Runtime/Materials/";
+
+ public struct MaterialConversionInfo
+ {
+ private Material m_OldMaterial;
+ private Material m_NewMaterial;
+ private string m_OldMaterialId;
+
+ public Material oldMaterial => m_OldMaterial;
+ public Material newMaterial => m_NewMaterial;
+ public string oldMaterialId => m_OldMaterialId;
+
+ public MaterialConversionInfo(Material oldMaterial, Material newMaterial)
+ {
+ m_OldMaterial = oldMaterial;
+ m_NewMaterial = newMaterial;
+ m_OldMaterialId = URP2DConverterUtility.GetObjectIDString(oldMaterial);
+ }
+ }
+
+ public struct ShaderConversionInfo
+ {
+ public Shader oldShader;
+ public Shader newShader;
+ }
+ List m_AssetsToConvert = new List();
+
+ MaterialConversionInfo[] m_MaterialConversionInfo;
+
+ public Material GetSpriteDefaultMaterial()
+ {
+ // Note: functions here are shortened versions using static AssetDatabase
+ Renderer2DData data = Light2DEditorUtility.GetRenderer2DData();
+ if (data != null)
+ return data.GetDefaultMaterial(DefaultMaterialType.Sprite);
+ else
+ return LoadAssetAtPath(k_PackageMaterialsPath + "Sprite-Lit-Default.mat");
+ }
+
+ public abstract MaterialConversionInfo[] InitializeMaterialConversionInfo();
+
+
+ Material ReplaceMaterial(Material currentMaterial)
+ {
+ foreach(MaterialConversionInfo info in m_MaterialConversionInfo)
+ {
+ if (currentMaterial == info.oldMaterial)
+ return info.newMaterial;
+ }
+
+ return currentMaterial;
+ }
+
+ void UpgradeGameObject(GameObject go)
+ {
+ Renderer[] renderers = go.GetComponentsInChildren();
+ foreach (Renderer renderer in renderers)
+ {
+ if (!PrefabUtility.IsPartOfPrefabInstance(renderer))
+ {
+ int materialCount = renderer.sharedMaterials.Length;
+ Material[] newMaterials = new Material[materialCount];
+ bool updateMaterials = false;
+
+ for (int matIndex = 0; matIndex < materialCount; matIndex++)
+ {
+ newMaterials[matIndex] = ReplaceMaterial(renderer.sharedMaterials[matIndex]);
+ updateMaterials |= newMaterials[matIndex] != renderer.sharedMaterials[matIndex];
+ }
+
+ if (updateMaterials)
+ renderer.sharedMaterials = newMaterials;
+ }
+ }
+ }
+
+ void UpgradeMaterial(Material material)
+ {
+ for (int i = 0; i < m_MaterialConversionInfo.Length; i++)
+ {
+ if (material.shader == m_MaterialConversionInfo[i].oldMaterial.shader)
+ {
+ material.shader = m_MaterialConversionInfo[i].newMaterial.shader;
+ break;
+ }
+ }
+ }
+
+ string[] GetAllMaterialConversionIds()
+ {
+ string[] materialIds = new string[m_MaterialConversionInfo.Length];
+ for (int i = 0; i < m_MaterialConversionInfo.Length; i++)
+ materialIds[i] = m_MaterialConversionInfo[i].oldMaterialId;
+
+ return materialIds;
+ }
+
+ string[] GetAllShaderConversionIds()
+ {
+ string[] shaderIds = new string[m_MaterialConversionInfo.Length];
+ for (int i = 0; i < m_MaterialConversionInfo.Length; i++)
+ shaderIds[i] = URP2DConverterUtility.GetObjectIDString(m_MaterialConversionInfo[i].oldMaterial.shader);
+ return shaderIds;
+ }
+
+ public override void OnInitialize(InitializeConverterContext context, Action callback)
+ {
+ m_MaterialConversionInfo = InitializeMaterialConversionInfo();
+
+ string[] allAssetPaths = AssetDatabase.GetAllAssetPaths();
+ string[] allMaterialConversionIds = GetAllMaterialConversionIds();
+ string[] allShaderConversionIds = GetAllShaderConversionIds();
+
+ foreach (string path in allAssetPaths)
+ {
+ if (URP2DConverterUtility.IsPSB(path) || URP2DConverterUtility.IsMaterialPath(path, allShaderConversionIds) || URP2DConverterUtility.IsPrefabOrScenePath(path, allMaterialConversionIds))
+ {
+ ConverterItemDescriptor desc = new ConverterItemDescriptor()
+ {
+ name = Path.GetFileNameWithoutExtension(path),
+ info = path,
+ warningMessage = String.Empty,
+ helpLink = String.Empty
+ };
+
+ // Each converter needs to add this info using this API.
+ m_AssetsToConvert.Add(path);
+ context.AddAssetToConvert(desc);
+ }
+ }
+
+ callback.Invoke();
+ }
+
+ public override void OnRun(ref RunItemContext context)
+ {
+ string result = string.Empty;
+ string ext = Path.GetExtension(context.item.descriptor.info);
+ if (ext == ".prefab")
+ result = URP2DConverterUtility.UpgradePrefab(context.item.descriptor.info, UpgradeGameObject);
+ else if (ext == ".unity")
+ URP2DConverterUtility.UpgradeScene(context.item.descriptor.info, UpgradeGameObject);
+ else if (ext == ".mat")
+ URP2DConverterUtility.UpgradeMaterial(context.item.descriptor.info, UpgradeMaterial);
+ else if (ext == ".psb" || ext == ".psd")
+ result = URP2DConverterUtility.UpgradePSB(context.item.descriptor.info);
+
+ if (result != string.Empty)
+ {
+ context.didFail = true;
+ context.info = result;
+ }
+ else
+ {
+ context.hasConverted = true;
+ }
+ }
+
+ public override void OnClicked(int index)
+ {
+ EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath(m_AssetsToConvert[index]));
+ }
+
+ public override void OnPostRun()
+ {
+ Resources.UnloadUnusedAssets();
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/Base2DMaterialUpgrader.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/Base2DMaterialUpgrader.cs.meta
new file mode 100644
index 00000000000..cbf1b6e3675
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/Base2DMaterialUpgrader.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 9899a41038dc3954a9a5d802ef6ee182
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DConverterContainer.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DConverterContainer.cs
new file mode 100644
index 00000000000..191b3eccb35
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DConverterContainer.cs
@@ -0,0 +1,8 @@
+namespace UnityEditor.Rendering.Universal
+{
+ internal sealed class BuiltInAndURP3DTo2DConverterContainer : RenderPipelineConverterContainer
+ {
+ public override string name => "2D Converters/Convert 3D Materials for 2D URP";
+ public override string info => "Converter performs the following tasks:\n* Converts 3D project elements from the Built-in/URP Render Pipeline for use in 2D URP.";
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DConverterContainer.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DConverterContainer.cs.meta
new file mode 100644
index 00000000000..0c4cbe4d542
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DConverterContainer.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 57eb02d33c8513341a2dc6be5c3d38e4
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DMaterialUpgrader.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DMaterialUpgrader.cs
new file mode 100644
index 00000000000..41ef4d33500
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DMaterialUpgrader.cs
@@ -0,0 +1,47 @@
+using System;
+using System.IO;
+using System.Collections.Generic;
+using UnityEditor.Rendering.Universal;
+using UnityEngine;
+using UnityEngine.Rendering.Universal;
+using static UnityEditor.AssetDatabase;
+using System.Collections;
+
+namespace UnityEditor.Rendering.Universal
+{
+ internal sealed class BuiltInAndURP3DTo2DMaterialUpgrader : Base2DMaterialUpgrader
+ {
+ public override string name => "Material and Material Reference Upgrade";
+ public override string info => "This will upgrade/crossgrade all 3D materials and 3D material references for URP 2D.";
+ public override int priority => -1000;
+ public override Type container => typeof(BuiltInAndURP3DTo2DConverterContainer);
+
+ public override MaterialConversionInfo[] InitializeMaterialConversionInfo()
+ {
+ // Note: functions here are shortened versions using static AssetDatabase
+ Material meshLit = LoadAssetAtPath(k_PackageMaterialsPath + "Mesh2D-Lit-Default.mat");
+ Material spriteDefaultMat = GetSpriteDefaultMaterial();
+
+ MaterialConversionInfo[] materialConversionInfo = new MaterialConversionInfo[]
+ {
+ // Conversion from built-in to URP 2D
+ new MaterialConversionInfo(
+ GetBuiltinExtraResource("Default-Material.mat"),
+ meshLit
+ ),
+
+ // Cross conversion from URP 3D to URP 2D. Just supports simple conversion for now
+ new MaterialConversionInfo(
+ LoadAssetAtPath(k_PackageMaterialsPath + "Lit.mat"),
+ meshLit
+ ),
+ new MaterialConversionInfo(
+ LoadAssetAtPath(k_PackageMaterialsPath + "SimpleLit.mat"),
+ meshLit
+ ),
+ };
+
+ return materialConversionInfo;
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DMaterialUpgrader.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DMaterialUpgrader.cs.meta
new file mode 100644
index 00000000000..6bbb108ff03
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInAndURP3DTo2DMaterialUpgrader.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: fed0ca29658777447b2eedcce144000b
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DConverterContainer.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DConverterContainer.cs
index c839d08a3d6..321d7223e75 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DConverterContainer.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DConverterContainer.cs
@@ -2,7 +2,7 @@ namespace UnityEditor.Rendering.Universal
{
internal sealed class BuiltInToURP2DConverterContainer : RenderPipelineConverterContainer
{
- public override string name => "Built-in to 2D (URP)";
+ public override string name => "2D Converters/Built-in to 2D URP Material Upgrader";
public override string info => "Converter performs the following tasks:\n* Converts project elements from the Built-in Render Pipeline to 2D URP.";
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DMaterialUpgrader.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DMaterialUpgrader.cs
index 88fb87d7996..0726d91f522 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DMaterialUpgrader.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/BuiltInToURP2DMaterialUpgrader.cs
@@ -4,135 +4,38 @@
using UnityEditor.Rendering.Universal;
using UnityEngine;
using UnityEngine.Rendering.Universal;
-
+using static UnityEditor.AssetDatabase;
+using System.Collections;
namespace UnityEditor.Rendering.Universal
{
- internal sealed class BuiltInToURP2DMaterialUpgrader : RenderPipelineConverter
+ internal sealed class BuiltInToURP2DMaterialUpgrader : Base2DMaterialUpgrader
{
public override string name => "Material and Material Reference Upgrade";
public override string info => "This will upgrade all materials and material references.";
public override int priority => -1000;
public override Type container => typeof(BuiltInToURP2DConverterContainer);
- List m_AssetsToConvert = new List();
-
- Material m_SpriteLitDefaultMat;
- Material m_SpritesDefaultMat;
- Material m_SpritesMaskMat;
- Material m_SpriteMaskDefaultMat;
- Shader m_SpriteLitDefaultShader;
- Shader m_SpritesDefaultShader;
-
- string m_SpritesDefaultShaderId;
- string m_SpritesDefaultMatId;
- string m_SpritesMaskMatId;
-
- void UpgradeGameObject(GameObject go)
+ public override MaterialConversionInfo[] InitializeMaterialConversionInfo()
{
- Renderer[] renderers = go.GetComponentsInChildren();
- foreach (Renderer renderer in renderers)
- {
- if (!PrefabUtility.IsPartOfPrefabInstance(renderer))
- {
- int materialCount = renderer.sharedMaterials.Length;
- Material[] newMaterials = new Material[materialCount];
- bool updateMaterials = false;
-
- for (int matIndex = 0; matIndex < materialCount; matIndex++)
- {
- if (renderer.sharedMaterials[matIndex] == m_SpritesDefaultMat)
- {
- newMaterials[matIndex] = m_SpriteLitDefaultMat;
- updateMaterials = true;
- }
- else if (renderer.sharedMaterials[matIndex] == m_SpritesMaskMat)
- {
- newMaterials[matIndex] = m_SpriteMaskDefaultMat;
- updateMaterials = true;
- }
- else
- newMaterials[matIndex] = renderer.sharedMaterials[matIndex];
- }
+ // Note: functions here are shortened versions using static AssetDatabase
+ Material spriteDefaultMat = GetSpriteDefaultMaterial();
- if (updateMaterials)
- renderer.sharedMaterials = newMaterials;
- }
- }
- }
-
- public override void OnInitialize(InitializeConverterContext context, Action callback)
- {
- Renderer2DData data = Light2DEditorUtility.GetRenderer2DData();
- if (data != null)
- m_SpriteLitDefaultMat = data.GetDefaultMaterial(DefaultMaterialType.Sprite);
- else
- m_SpriteLitDefaultMat = AssetDatabase.LoadAssetAtPath("Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Lit-Default.mat");
-
- m_SpritesDefaultMat = AssetDatabase.GetBuiltinExtraResource("Sprites-Default.mat");
- m_SpriteMaskDefaultMat = AssetDatabase.LoadAssetAtPath("Packages/com.unity.render-pipelines.universal/Runtime/Materials/SpriteMask-Default.mat");
- m_SpritesMaskMat = AssetDatabase.GetBuiltinExtraResource("Sprites-Mask.mat");
- m_SpriteLitDefaultShader = m_SpriteLitDefaultMat.shader;
- m_SpritesDefaultShader = m_SpritesDefaultMat.shader;
- m_SpritesDefaultShaderId = URP2DConverterUtility.GetObjectIDString(m_SpritesDefaultShader);
- m_SpritesDefaultMatId = URP2DConverterUtility.GetObjectIDString(m_SpritesDefaultMat);
- m_SpritesMaskMatId = URP2DConverterUtility.GetObjectIDString(m_SpritesMaskMat);
-
- string[] allAssetPaths = AssetDatabase.GetAllAssetPaths();
-
- foreach (string path in allAssetPaths)
+ MaterialConversionInfo[] materialConversionInfo = new MaterialConversionInfo[]
{
- if (URP2DConverterUtility.IsPSB(path) || URP2DConverterUtility.IsMaterialPath(path, m_SpritesDefaultShaderId) || URP2DConverterUtility.IsPrefabOrScenePath(path, new string[] { m_SpritesDefaultMatId, m_SpritesMaskMatId }))
- {
- ConverterItemDescriptor desc = new ConverterItemDescriptor()
- {
- name = Path.GetFileNameWithoutExtension(path),
- info = path,
- warningMessage = String.Empty,
- helpLink = String.Empty
- };
-
- // Each converter needs to add this info using this API.
- m_AssetsToConvert.Add(path);
- context.AddAssetToConvert(desc);
- }
- }
-
- callback.Invoke();
- }
-
- public override void OnRun(ref RunItemContext context)
- {
- string result = string.Empty;
- string ext = Path.GetExtension(context.item.descriptor.info);
- if (ext == ".prefab")
- result = URP2DConverterUtility.UpgradePrefab(context.item.descriptor.info, UpgradeGameObject);
- else if (ext == ".unity")
- URP2DConverterUtility.UpgradeScene(context.item.descriptor.info, UpgradeGameObject);
- else if (ext == ".mat")
- URP2DConverterUtility.UpgradeMaterial(context.item.descriptor.info, m_SpritesDefaultShader, m_SpriteLitDefaultShader);
- else if (ext == ".psb" || ext == ".psd")
- result = URP2DConverterUtility.UpgradePSB(context.item.descriptor.info);
-
- if (result != string.Empty)
- {
- context.didFail = true;
- context.info = result;
- }
- else
- {
- context.hasConverted = true;
- }
- }
-
- public override void OnClicked(int index)
- {
- EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath(m_AssetsToConvert[index]));
+ // Conversion from built-in to URP 2D
+ new MaterialConversionInfo(
+ GetBuiltinExtraResource("Sprites-Default.mat"),
+ spriteDefaultMat
+ ),
+ new MaterialConversionInfo(
+ GetBuiltinExtraResource("Sprites-Mask.mat"),
+ LoadAssetAtPath(k_PackageMaterialsPath + "SpriteMask-Default.mat")
+ ),
+ };
+
+ return materialConversionInfo;
}
- public override void OnPostRun()
- {
- Resources.UnloadUnusedAssets();
- }
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/URP2DConverterUtility.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/URP2DConverterUtility.cs
index c66fc0f190f..0d9a56e75ee 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/URP2DConverterUtility.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/URP2DConverterUtility.cs
@@ -20,7 +20,7 @@ public static bool IsPSB(string path)
}
- public static bool IsMaterialPath(string path, string id)
+ public static bool IsMaterialPath(string path, string[] ids)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(path));
@@ -29,7 +29,10 @@ public static bool IsMaterialPath(string path, string id)
return false;
if (path.EndsWith(".mat"))
- return URP2DConverterUtility.DoesFileContainString(path, new string[] { id });
+ {
+ return URP2DConverterUtility.DoesFileContainString(path, ids);
+ }
+
return false;
}
@@ -138,11 +141,10 @@ public static void UpgradeScene(string path, Action objectUpgrader)
EditorSceneManager.CloseScene(scene, true);
}
- public static void UpgradeMaterial(string path, Shader oldShader, Shader newShader)
+ public static void UpgradeMaterial(string path, Action materialUpgrader)
{
Material material = AssetDatabase.LoadAssetAtPath(path);
- if (material.shader == oldShader)
- material.shader = newShader;
+ materialUpgrader(material);
GUID guid = AssetDatabase.GUIDFromAssetPath(path);
AssetDatabase.SaveAssetIfDirty(guid);
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/UpgradeURP2DAssetsContainer.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/UpgradeURP2DAssetsContainer.cs
index 06873aded6f..71ff7e198a6 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/UpgradeURP2DAssetsContainer.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Converter/UpgradeURP2DAssetsContainer.cs
@@ -2,7 +2,7 @@ namespace UnityEditor.Rendering.Universal
{
internal sealed class UpgradeURP2DAssetsContainer : RenderPipelineConverterContainer
{
- public override string name => "Upgrade 2D (URP) Assets";
+ public override string name => "2D Converters/Upgrade Deprecated 2D Features";
public override string info => "Converter performs the following tasks:\n* Upgrades assets from earlier 2D URP versions to the current 2D URP version.";
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides.meta
new file mode 100644
index 00000000000..b6ec7a95faa
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: c96a8adc325df8544ae548396468a961
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/AssemblyInfo.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/AssemblyInfo.cs
new file mode 100644
index 00000000000..ac7dfdecd5a
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/AssemblyInfo.cs
@@ -0,0 +1,8 @@
+using System.Runtime.CompilerServices;
+
+[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // permit using internal interfaces with Moq
+[assembly: InternalsVisibleTo("UniversalGraphicsTests")]
+[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor.Tests")]
+[assembly: InternalsVisibleTo("Unity.Testing.SRP.Universal-Upgrade.Editor")]
+[assembly: InternalsVisibleTo("Unity.GraphicTests.Performance.Universal.Editor")]
+[assembly: InternalsVisibleTo("Unity.VisualEffectGraph.EditorTests")]
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/AssemblyInfo.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/AssemblyInfo.cs.meta
new file mode 100644
index 00000000000..0f54b476eeb
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/AssemblyInfo.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: bcdc8c86abfb40a45aa7ea6f4d34cb13
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/MeshEditor2DURP.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/MeshEditor2DURP.cs
new file mode 100644
index 00000000000..400b101d8a9
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/MeshEditor2DURP.cs
@@ -0,0 +1,48 @@
+using System;
+using UnityEngine;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.Universal;
+
+
+namespace UnityEditor.Rendering.Universal
+{
+ [CustomEditor(typeof(MeshRenderer))]
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ [CanEditMultipleObjects]
+ internal class Renderer2DMeshEditor : MeshRendererEditor
+ {
+ SerializedProperty m_MaskInteraction;
+ SavedBool m_2DFoldout;
+ class Styles
+ {
+ public static readonly GUIContent maskInteractionLabel = EditorGUIUtility.TrTextContent("Mask Interaction", "Renderer's interaction with a Sprite Mask");
+ }
+
+
+ public override void OnEnable()
+ {
+ base.OnEnable();
+ m_MaskInteraction = serializedObject.FindProperty("m_MaskInteraction");
+ m_2DFoldout = new SavedBool($"{target.GetType()}.MeshEditor2DFoldout", true);
+ }
+
+ public override void OnInspectorGUI()
+ {
+ base.OnInspectorGUI();
+
+ serializedObject.Update();
+ var rpAsset = UniversalRenderPipeline.asset;
+ if (rpAsset != null && (rpAsset.scriptableRenderer is Renderer2D))
+ {
+ m_2DFoldout.value = EditorGUILayout.Foldout(m_2DFoldout.value, "2D");
+ if (m_2DFoldout)
+ {
+ EditorGUI.indentLevel++;
+ m_MaskInteraction.intValue = Convert.ToInt32(EditorGUILayout.EnumPopup(Styles.maskInteractionLabel, (SpriteMaskInteraction)m_MaskInteraction.intValue));
+ EditorGUI.indentLevel--;
+ }
+ }
+ serializedObject.ApplyModifiedProperties();
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/MeshEditor2DURP.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/MeshEditor2DURP.cs.meta
new file mode 100644
index 00000000000..1d914e57a87
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/MeshEditor2DURP.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: bce6289b8f1e3bf4a82078371dffaebd
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SkinnedMeshEditor2DURP.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SkinnedMeshEditor2DURP.cs
new file mode 100644
index 00000000000..d69eb3ceef8
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SkinnedMeshEditor2DURP.cs
@@ -0,0 +1,48 @@
+using System;
+using UnityEngine;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.Universal;
+
+
+namespace UnityEditor.Rendering.Universal
+{
+ [CustomEditor(typeof(SkinnedMeshRenderer))]
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ [CanEditMultipleObjects]
+ internal class SkinnedMeshEditor2DURP : SkinnedMeshRendererEditor
+ {
+ SerializedProperty m_MaskInteraction;
+ SavedBool m_2DFoldout;
+ new class Styles
+ {
+ public static readonly GUIContent maskInteractionLabel = EditorGUIUtility.TrTextContent("Mask Interaction", "Renderer's interaction with a Sprite Mask");
+ }
+
+
+ public override void OnEnable()
+ {
+ base.OnEnable();
+ m_MaskInteraction = serializedObject.FindProperty("m_MaskInteraction");
+ m_2DFoldout = new SavedBool($"{target.GetType()}.SkinnedMeshEditor2DFoldout", true);
+ }
+
+ public override void OnInspectorGUI()
+ {
+ base.OnInspectorGUI();
+
+ serializedObject.Update();
+ var rpAsset = UniversalRenderPipeline.asset;
+ if (rpAsset != null && (rpAsset.scriptableRenderer is Renderer2D))
+ {
+ m_2DFoldout.value = EditorGUILayout.Foldout(m_2DFoldout.value, "2D");
+ if (m_2DFoldout)
+ {
+ EditorGUI.indentLevel++;
+ m_MaskInteraction.intValue = Convert.ToInt32(EditorGUILayout.EnumPopup(Styles.maskInteractionLabel, (SpriteMaskInteraction)m_MaskInteraction.intValue));
+ EditorGUI.indentLevel--;
+ }
+ }
+ serializedObject.ApplyModifiedProperties();
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SkinnedMeshEditor2DURP.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SkinnedMeshEditor2DURP.cs.meta
new file mode 100644
index 00000000000..ee9c5c928b8
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SkinnedMeshEditor2DURP.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: d1e4d2637b6c6824e82557977a6727d4
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SortingGroupEditor2DURP.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SortingGroupEditor2DURP.cs
new file mode 100644
index 00000000000..db2b3838630
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SortingGroupEditor2DURP.cs
@@ -0,0 +1,104 @@
+using UnityEditorInternal;
+using UnityEngine;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.Universal;
+
+namespace UnityEditor
+{
+ [CustomEditor(typeof(UnityEngine.Rendering.SortingGroup))]
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ [CanEditMultipleObjects]
+ internal class SortingGroupEditor2DURP : Editor
+ {
+ private static class Styles
+ {
+ public static GUIContent flattenGroup = EditorGUIUtility.TrTextContent("Sort 3D as 2D", "Clears z values on 3D meshes affected by a Sorting Group allowing them to sort with other 2D objects and Sort 3D as 2D sorting groups.");
+ }
+
+ private SerializedProperty m_SortingOrder;
+ private SerializedProperty m_SortingLayerID;
+
+ public virtual void OnEnable()
+ {
+ alwaysAllowExpansion = true;
+ m_SortingOrder = serializedObject.FindProperty("m_SortingOrder");
+ m_SortingLayerID = serializedObject.FindProperty("m_SortingLayerID");
+ }
+
+ public RenderAs2D TryToFindCreatedRenderAs2D(SortingGroup sortingGroup)
+ {
+ RenderAs2D[] renderAs2Ds = sortingGroup.GetComponents();
+ foreach(RenderAs2D renderAs2D in renderAs2Ds)
+ {
+ if (renderAs2D.IsOwner(sortingGroup))
+ return renderAs2D;
+ }
+
+ return null;
+ }
+
+ bool DrawToggleWithLayout(bool flatten, GUIContent content)
+ {
+ Rect rect = EditorGUILayout.GetControlRect();
+ var boolValue = EditorGUI.Toggle(rect, content, flatten);
+ return boolValue;
+ }
+
+ void DirtyScene()
+ {
+ UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEngine.SceneManagement.SceneManager.GetActiveScene());
+ }
+
+ void RenderFlattening()
+ {
+
+ bool tryToFlatten = TryToFindCreatedRenderAs2D(serializedObject.targetObject as SortingGroup) != null;
+ bool result = DrawToggleWithLayout(tryToFlatten, Styles.flattenGroup);
+
+ if (tryToFlatten != result)
+ {
+ tryToFlatten = result;
+ foreach (Object targetObject in serializedObject.targetObjects)
+ {
+ SortingGroup sortingGroup = targetObject as SortingGroup;
+ RenderAs2D renderAs2D = TryToFindCreatedRenderAs2D(sortingGroup);
+
+ if (tryToFlatten)
+ {
+ if (!renderAs2D)
+ {
+ RenderAs2D newRenderAs2D = sortingGroup.gameObject.AddComponent();
+ newRenderAs2D.Init(sortingGroup);
+ newRenderAs2D.hideFlags = HideFlags.HideInInspector | HideFlags.HideInHierarchy;
+ DirtyScene();
+ }
+ }
+ else
+ {
+ if (renderAs2D)
+ {
+ Component.DestroyImmediate(renderAs2D);
+ DirtyScene();
+ }
+ }
+ }
+ }
+ }
+
+ public override void OnInspectorGUI()
+ {
+ serializedObject.Update();
+
+ var rpAsset = UniversalRenderPipeline.asset;
+ if (rpAsset != null && (rpAsset.scriptableRenderer is Renderer2D))
+ {
+ SortingLayerEditorUtility.RenderSortingLayerFields(m_SortingOrder, m_SortingLayerID);
+ RenderFlattening();
+ }
+ else
+ base.OnInspectorGUI();
+
+ serializedObject.ApplyModifiedProperties();
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SortingGroupEditor2DURP.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SortingGroupEditor2DURP.cs.meta
new file mode 100644
index 00000000000..0de279afeaf
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/SortingGroupEditor2DURP.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 7dac6048e6e7a4747ad93c64661d3faf
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/Unity.RenderPipelines.Universal.2D.Editor.Overrides.asmdef b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/Unity.RenderPipelines.Universal.2D.Editor.Overrides.asmdef
new file mode 100644
index 00000000000..40745ec8b32
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/Unity.RenderPipelines.Universal.2D.Editor.Overrides.asmdef
@@ -0,0 +1,60 @@
+{
+ "name": "Unity.RenderPipelines.Universal.2D.Editor.Overrides",
+ "rootNamespace": "",
+ "references": [
+ "GUID:15fc0a57446b3144c949da3e2b9737a9",
+ "GUID:d60799ab2a985554ea1a39cd38695018",
+ "GUID:a35efad8797223d499f8c68b1f545dbc",
+ "GUID:df380645f10b7bc4b97d4f5eb6303d95",
+ "GUID:69257879134bba646869b21467b3338d",
+ "GUID:3eae0364be2026648bf74846acb8a731",
+ "GUID:2a69708d171a17043a9d0ad45f205cfe",
+ "GUID:be0903cd8e1546f498710afdc59db5eb",
+ "GUID:b75d3cd3037d383a8d1e2f9a26d73d8a",
+ "GUID:329b4ccd385744985bf3f83cfd77dfe7",
+ "GUID:9604b18aafdbc9346bceb5e19ac9c746",
+ "GUID:f9fe0089ec81f4079af78eb2287a6163",
+ "GUID:116a4d4dbf5c04973bbf517077a062a1",
+ "GUID:e40ba710768534012815d3193fa296cb",
+ "GUID:516a5277b8c3b4f4c8cc86b77b1591ff",
+ "GUID:4fd6538c1c56b409fb53fdf0183170ec",
+ "GUID:41524c21c95e5fe4dbc5b48bd21995a4"
+ ],
+ "includePlatforms": [
+ "Editor"
+ ],
+ "excludePlatforms": [],
+ "allowUnsafeCode": true,
+ "overrideReferences": false,
+ "precompiledReferences": [],
+ "autoReferenced": true,
+ "defineConstraints": [],
+ "versionDefines": [
+ {
+ "name": "com.unity.adaptiveperformance",
+ "expression": "2.0.0-preview.7",
+ "define": "ADAPTIVE_PERFORMANCE_2_0_0_OR_NEWER"
+ },
+ {
+ "name": "com.unity.modules.xr",
+ "expression": "1.0.0",
+ "define": "ENABLE_XR_MODULE"
+ },
+ {
+ "name": "com.unity.xr.management",
+ "expression": "4.0.1",
+ "define": "XR_MANAGEMENT_4_0_1_OR_NEWER"
+ },
+ {
+ "name": "com.unity.visualeffectgraph",
+ "expression": "1.0.0",
+ "define": "HAS_VFX_GRAPH"
+ },
+ {
+ "name": "com.unity.2d.animation",
+ "expression": "10.0.0-pre.1",
+ "define": "USING_2DANIMATION"
+ }
+ ],
+ "noEngineReferences": false
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/Unity.RenderPipelines.Universal.2D.Editor.Overrides.asmdef.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/Unity.RenderPipelines.Universal.2D.Editor.Overrides.asmdef.meta
new file mode 100644
index 00000000000..bc7a38f57a6
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Overrides/Unity.RenderPipelines.Universal.2D.Editor.Overrides.asmdef.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 71872915d7faaaf47a5587bce19d5214
+AssemblyDefinitionImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Resources/InspectorIcons/PointLight.png b/Packages/com.unity.render-pipelines.universal/Editor/2D/Resources/InspectorIcons/PointLight.png
index 9e8bbecb6a8..d9f1be528d3 100644
Binary files a/Packages/com.unity.render-pipelines.universal/Editor/2D/Resources/InspectorIcons/PointLight.png and b/Packages/com.unity.render-pipelines.universal/Editor/2D/Resources/InspectorIcons/PointLight.png differ
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/Resources/InspectorIcons/PointLight.png.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/Resources/InspectorIcons/PointLight.png.meta
index 449aeab9206..0f2f9e1acf9 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/2D/Resources/InspectorIcons/PointLight.png.meta
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/Resources/InspectorIcons/PointLight.png.meta
@@ -1,9 +1,12 @@
fileFormatVersion: 2
-guid: b3ab972b21db85d48ade9657efdd4771
+guid: 6eaa9958d83ec43499e946a21edba283
TextureImporter:
- internalIDToNameTable: []
+ internalIDToNameTable:
+ - first:
+ 213: 1287649992867056945
+ second: PointLight@64_0
externalObjects: {}
- serializedVersion: 10
+ serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
@@ -20,9 +23,12 @@ TextureImporter:
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
+ flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
+ vTOnly: 0
+ ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
@@ -31,16 +37,16 @@ TextureImporter:
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
- filterMode: -1
+ filterMode: 1
aniso: 1
- mipBias: -100
+ mipBias: 0
wrapU: 1
wrapV: 1
- wrapW: -1
+ wrapW: 1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
- spriteMode: 0
+ spriteMode: 2
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
@@ -51,42 +57,150 @@ TextureImporter:
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationDetail: -1
- textureType: 2
+ textureType: 8
textureShape: 1
singleChannelComponent: 0
+ flipbookRows: 1
+ flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
+ applyGammaDecoding: 0
+ swizzle: 50462976
+ cookieLightType: 0
platformSettings:
- - serializedVersion: 3
+ - serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
- textureCompression: 2
+ textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
+ ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- - serializedVersion: 3
+ - serializedVersion: 4
+ buildTarget: CloudRendering
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: Switch
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: WebGL
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 2048
resizeAlgorithm: 0
textureFormat: -1
- textureCompression: 2
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: Android
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: GameCoreXboxOne
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
+ compressionQuality: 50
+ crunchedCompression: 0
+ allowsAlphaSplitting: 0
+ overridden: 0
+ ignorePlatformSupport: 0
+ androidETC2FallbackOverride: 0
+ forceMaximumCompressionQuality_BC6H_BC7: 0
+ - serializedVersion: 4
+ buildTarget: GameCoreScarlett
+ maxTextureSize: 2048
+ resizeAlgorithm: 0
+ textureFormat: -1
+ textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
+ ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
- sprites: []
+ sprites:
+ - serializedVersion: 2
+ name: PointLight@64_0
+ rect:
+ serializedVersion: 2
+ x: 11
+ y: 2
+ width: 42
+ height: 62
+ alignment: 0
+ pivot: {x: 0, y: 0}
+ border: {x: 0, y: 0, z: 0, w: 0}
+ customData:
+ outline: []
+ physicsShape: []
+ tessellationDetail: -1
+ bones: []
+ spriteID: 13d00e3a8d6aed110800000000000000
+ internalID: 1287649992867056945
+ vertices: []
+ indices:
+ edges: []
+ weights: []
outline: []
+ customData:
physicsShape: []
bones: []
spriteID:
@@ -96,9 +210,12 @@ TextureImporter:
edges: []
weights: []
secondaryTextures: []
- spritePackingTag:
+ spriteCustomMetadata:
+ entries: []
+ nameFileIdTable:
+ PointLight@64_0: 1287649992867056945
+ mipmapLimitGroupName:
pSDRemoveMatte: 0
- pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Mesh2DLitPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Mesh2DLitPass.hlsl
new file mode 100644
index 00000000000..3cba5c63538
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Mesh2DLitPass.hlsl
@@ -0,0 +1,52 @@
+#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/Core2D.hlsl"
+#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/SurfaceData2D.hlsl"
+#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging2D.hlsl"
+
+#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/CombinedShapeLightShared.hlsl"
+
+half4 White;
+
+PackedVaryings vert(Attributes input)
+{
+ Varyings output = (Varyings)0;
+ input.positionOS = input.positionOS;
+ output = BuildVaryings(input);
+ PackedVaryings packedOutput = PackVaryings(output);
+ return packedOutput;
+}
+
+half4 frag(PackedVaryings packedInput) : SV_TARGET
+{
+ Varyings unpacked = UnpackVaryings(packedInput);
+ UNITY_SETUP_INSTANCE_ID(unpacked);
+ UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
+
+ SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
+
+#ifdef UNIVERSAL_USELEGACYSPRITEBLOCKS
+ half4 color = surfaceDescription.SpriteColor;
+#else
+ half4 color = half4(surfaceDescription.BaseColor, surfaceDescription.Alpha);
+#endif
+
+#if ALPHA_CLIP_THRESHOLD
+ clip(color.a - surfaceDescription.AlphaClipThreshold);
+#endif
+
+ // Disable vertex color multiplication. Users can get the color from VertexColor node
+#if !defined(HAVE_VFX_MODIFICATION) && !defined(_DISABLE_COLOR_TINT)
+ color *= unpacked.color;
+#endif
+
+ SurfaceData2D surfaceData;
+ InitializeSurfaceData(color.rgb, color.a, surfaceDescription.SpriteMask, surfaceData);
+ InputData2D inputData;
+ InitializeInputData(unpacked.texCoord0.xy, half2(unpacked.screenPosition.xy / unpacked.screenPosition.w), inputData);
+ SETUP_DEBUG_DATA_2D(inputData, unpacked.positionWS, unpacked.positionCS);
+
+#if defined(SHADERGRAPH_PREVIEW_MAIN) || defined(SHADERGRAPH_PREVIEW)
+ return CombinedShapeLightShared(surfaceData, inputData);
+#else
+ return White * CombinedShapeLightShared(surfaceData, inputData);
+#endif
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Mesh2DLitPass.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Mesh2DLitPass.hlsl.meta
new file mode 100644
index 00000000000..96196126a62
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Mesh2DLitPass.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 19a7eabf161c29846b42f73a2965d39b
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshNormalPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshNormalPass.hlsl
new file mode 100644
index 00000000000..e7e373d02c0
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshNormalPass.hlsl
@@ -0,0 +1,40 @@
+#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/Core2D.hlsl"
+
+half4 White;
+
+PackedVaryings vert(Attributes input)
+{
+ Varyings output = (Varyings)0;
+ output = BuildVaryings(input);
+ output.normalWS = TransformObjectToWorldDir(input.normalOS);
+ PackedVaryings packedOutput = PackVaryings(output);
+ return packedOutput;
+}
+
+half4 frag(PackedVaryings packedInput) : SV_TARGET
+{
+ Varyings unpacked = UnpackVaryings(packedInput);
+ UNITY_SETUP_INSTANCE_ID(unpacked);
+ UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
+
+ SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
+
+#ifdef UNIVERSAL_USELEGACYSPRITEBLOCKS
+ half4 color = surfaceDescription.SpriteColor;
+#else
+ half4 color = half4(1.0,1.0,1.0, surfaceDescription.Alpha);
+#endif
+
+#if ALPHA_CLIP_THRESHOLD
+ clip(color.a - surfaceDescription.AlphaClipThreshold);
+#endif
+
+ half crossSign = (unpacked.tangentWS.w > 0.0 ? 1.0 : -1.0) * GetOddNegativeScale();
+ half3 bitangent = crossSign * cross(unpacked.normalWS.xyz, unpacked.tangentWS.xyz);
+
+ #if defined(SHADERGRAPH_PREVIEW_MAIN) || defined(SHADERGRAPH_PREVIEW)
+ return NormalsRenderingShared(color, surfaceDescription.NormalTS, unpacked.tangentWS.xyz, bitangent, unpacked.normalWS);
+ #else
+ return White * NormalsRenderingShared(color, surfaceDescription.NormalTS, unpacked.tangentWS.xyz, bitangent, unpacked.normalWS);
+ #endif
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshNormalPass.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshNormalPass.hlsl.meta
new file mode 100644
index 00000000000..6b0cbf02f97
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshNormalPass.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 523042f52a938dd469d367936b00da21
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshUnlitPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshUnlitPass.hlsl
new file mode 100644
index 00000000000..efc279ec30a
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshUnlitPass.hlsl
@@ -0,0 +1,62 @@
+#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/Core2D.hlsl"
+#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/SurfaceData2D.hlsl"
+#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging2D.hlsl"
+
+half4 White;
+
+PackedVaryings vert(Attributes input)
+{
+ Varyings output = (Varyings)0;
+ input.positionOS = input.positionOS;
+ output = BuildVaryings(input);
+ PackedVaryings packedOutput = PackVaryings(output);
+ return packedOutput;
+}
+
+half4 frag(PackedVaryings packedInput) : SV_TARGET
+{
+ Varyings unpacked = UnpackVaryings(packedInput);
+ UNITY_SETUP_INSTANCE_ID(unpacked);
+ UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
+
+ SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
+
+#ifdef UNIVERSAL_USELEGACYSPRITEBLOCKS
+ half4 color = surfaceDescription.SpriteColor;
+#else
+ half4 color = half4(surfaceDescription.BaseColor, surfaceDescription.Alpha);
+#endif
+
+ if (color.a == 0.0)
+ discard;
+
+#if ALPHA_CLIP_THRESHOLD
+ clip(color.a - surfaceDescription.AlphaClipThreshold);
+#endif
+
+ #if defined(DEBUG_DISPLAY)
+ SurfaceData2D surfaceData;
+ InitializeSurfaceData(color.rgb, color.a, surfaceData);
+ InputData2D inputData;
+ InitializeInputData(unpacked.positionWS.xy, half2(unpacked.texCoord0.xy), inputData);
+ half4 debugColor = 0;
+
+ SETUP_DEBUG_DATA_2D(inputData, unpacked.positionWS, unpacked.positionCS);
+
+ if (CanDebugOverrideOutputColor(surfaceData, inputData, debugColor))
+ {
+ return debugColor;
+ }
+ #endif
+
+ // Disable vertex color multiplication. Users can get the color from VertexColor node
+#if !defined(HAVE_VFX_MODIFICATION) && !defined(_DISABLE_COLOR_TINT)
+ color *= unpacked.color;
+#endif
+
+#if defined(SHADERGRAPH_PREVIEW_MAIN) || defined(SHADERGRAPH_PREVIEW)
+ return color;
+#else
+ return White * color;
+#endif
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshUnlitPass.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshUnlitPass.hlsl.meta
new file mode 100644
index 00000000000..57d11832a22
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshUnlitPass.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: bce3f62f3aca0994599f5113432c9136
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteLitPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteLitPass.hlsl
index 43bc2140bae..bb22c30e4a1 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteLitPass.hlsl
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteLitPass.hlsl
@@ -1,23 +1,4 @@
#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/Core2D.hlsl"
-#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/SurfaceData2D.hlsl"
-#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Debug/Debugging2D.hlsl"
-
-#if USE_SHAPE_LIGHT_TYPE_0
-SHAPE_LIGHT(0)
-#endif
-
-#if USE_SHAPE_LIGHT_TYPE_1
-SHAPE_LIGHT(1)
-#endif
-
-#if USE_SHAPE_LIGHT_TYPE_2
-SHAPE_LIGHT(2)
-#endif
-
-#if USE_SHAPE_LIGHT_TYPE_3
-SHAPE_LIGHT(3)
-#endif
-
#include "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/CombinedShapeLightShared.hlsl"
half4 _RendererColor;
@@ -62,7 +43,9 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET
InitializeSurfaceData(color.rgb, color.a, surfaceDescription.SpriteMask, surfaceData);
InputData2D inputData;
InitializeInputData(unpacked.texCoord0.xy, half2(unpacked.screenPosition.xy / unpacked.screenPosition.w), inputData);
+#if defined(DEBUG_DISPLAY)
SETUP_DEBUG_DATA_2D(inputData, unpacked.positionWS, unpacked.positionCS);
+#endif
return CombinedShapeLightShared(surfaceData, inputData);
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/SpriteSubTargetUtility.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/SpriteSubTargetUtility.cs
index df4238e297b..fdcb4fef2eb 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/SpriteSubTargetUtility.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/SpriteSubTargetUtility.cs
@@ -1,7 +1,9 @@
using System;
using System.Linq;
+using UnityEngine;
using UnityEditor.ShaderGraph;
using UnityEngine.UIElements;
+using UnityEditor.ShaderGraph.Internal;
using static UnityEditor.Rendering.Universal.ShaderGraph.UniversalTarget;
namespace UnityEditor.Rendering.Universal.ShaderGraph
@@ -117,6 +119,16 @@ public static void AddDefaultPropertiesGUI(ref TargetPropertyGUIContext context,
target.disableTint = evt.newValue;
onChange();
});
+
+ context.AddProperty("Sort 3D as 2D Compatible", new Toggle() { value = target.sort3Das2DCompatible }, (evt) =>
+ {
+ if (Equals(target.sort3Das2DCompatible, evt.newValue))
+ return;
+
+ registerUndo("Change Sort 3D as 2D Compatible");
+ target.sort3Das2DCompatible = evt.newValue;
+ onChange();
+ });
}
public static void AddAlphaClipControlToPass(ref PassDescriptor pass, UniversalTarget target)
@@ -124,5 +136,21 @@ public static void AddAlphaClipControlToPass(ref PassDescriptor pass, UniversalT
if (target.alphaClip)
pass.defines.Add(CoreKeywordDescriptors.AlphaClipThreshold, 1);
}
+
+ public static void AddSRPIncompatibility(PropertyCollector collector)
+ {
+ var property = new ColorShaderProperty()
+ {
+ overrideReferenceName = "White",
+ value = new Color(1, 1, 1, 1),
+ hidden = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideHLSLDeclaration = true,
+ generatePropertyBlock = true,
+
+ };
+
+ collector.AddShaderProperty(property);
+ }
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/Universal2DSubTargetDescriptors.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/Universal2DSubTargetDescriptors.cs
new file mode 100644
index 00000000000..c55089a04dc
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/Universal2DSubTargetDescriptors.cs
@@ -0,0 +1,36 @@
+using UnityEditor.ShaderGraph;
+
+namespace UnityEditor.Rendering.Universal.ShaderGraph
+{
+ internal static class Universal2DSubTargetDescriptors
+ {
+ internal static class Keywords
+ {
+ public static readonly KeywordDescriptor Sort3DAs2DCompatible = new KeywordDescriptor()
+ {
+ displayName = "Sort 3D As 2D Compatible",
+ referenceName = "_ENABLE_SORT_3D_AS_2D_COMPATIBLE",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ stages = KeywordShaderStage.All,
+ };
+ }
+
+ internal static class RenderStateCollections
+ {
+ public static readonly RenderStateCollection Sort3Das2DCompatible = new RenderStateCollection()
+ {
+ { RenderState.Blend(Blend.SrcAlpha, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha), new FieldCondition(Fields.BlendAlpha, true)},
+ { RenderState.ZWrite(ZWrite.On) },
+ { RenderState.ZTest(ZTest.LEqual) },
+ { RenderState.Cull(Cull.Back) },
+ { RenderState.Stencil(new StencilDescriptor() {
+ Ref = "128",
+ Comp = "Always",
+ Pass = "Replace",
+ })},
+ };
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/Universal2DSubTargetDescriptors.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/Universal2DSubTargetDescriptors.cs.meta
new file mode 100644
index 00000000000..580749fbc97
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/Universal2DSubTargetDescriptors.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 8813ce52b5a413e40b14da5290946105
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshLitInfo.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshLitInfo.cs
new file mode 100644
index 00000000000..0ee88a67da4
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshLitInfo.cs
@@ -0,0 +1,49 @@
+using UnityEditor.ShaderGraph;
+
+namespace UnityEditor.Rendering.Universal.ShaderGraph
+{
+ internal static class UniversalMeshLitInfo
+ {
+ public static class Includes
+ {
+ const string k2DNormal = "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/NormalsRenderingShared.hlsl";
+ const string kMeshLitPass = "Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/Mesh2DLitPass.hlsl";
+ const string kMeshNormalPass = "Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshNormalPass.hlsl";
+ const string kMeshForwardPass = "Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteForwardPass.hlsl";
+
+ public static IncludeCollection Lit = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+
+ // Post-graph
+ { CoreIncludes.CorePostgraph },
+ { kMeshLitPass, IncludeLocation.Postgraph },
+ };
+
+ public static IncludeCollection Normal = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { k2DNormal, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { CoreIncludes.CorePostgraph },
+ { kMeshNormalPass, IncludeLocation.Postgraph },
+ };
+
+ public static IncludeCollection Forward = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+
+ // Post-graph
+ { CoreIncludes.CorePostgraph },
+ { kMeshForwardPass, IncludeLocation.Postgraph },
+ };
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshLitInfo.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshLitInfo.cs.meta
new file mode 100644
index 00000000000..8e19b4e8a0f
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshLitInfo.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 1d05733e1c6394a479c53e1428a543dd
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshUnlitInfo.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshUnlitInfo.cs
new file mode 100644
index 00000000000..43b60d1c0e5
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshUnlitInfo.cs
@@ -0,0 +1,20 @@
+using UnityEditor.ShaderGraph;
+
+namespace UnityEditor.Rendering.Universal.ShaderGraph
+{
+ internal static class MeshUnlitIncludes
+ {
+ const string kMeshUnlitPass = "Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/MeshUnlitPass.hlsl";
+
+ public static IncludeCollection Unlit = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+
+ // Post-graph
+ { CoreIncludes.CorePostgraph },
+ { kMeshUnlitPass, IncludeLocation.Postgraph },
+ };
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshUnlitInfo.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshUnlitInfo.cs.meta
new file mode 100644
index 00000000000..d3eb4f00261
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalMeshUnlitInfo.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: de06e51a002915c43a237aa558ee66e7
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs
index 80800e8501d..cd1f259cc1f 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteCustomLitSubTarget.cs
@@ -52,6 +52,12 @@ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Acti
SpriteSubTargetUtility.AddDefaultPropertiesGUI(ref context, onChange, registerUndo, target);
}
+ public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
+ {
+ base.CollectShaderProperties(collector, generationMode);
+ SpriteSubTargetUtility.AddSRPIncompatibility(collector);
+ }
+
#region SubShader
static class SubShaders
{
@@ -66,13 +72,13 @@ public static SubShaderDescriptor SpriteLit(UniversalTarget target)
generatesPreview = true,
passes = new PassCollection
{
- { SpriteLitPasses.Lit(target) },
- { SpriteLitPasses.Normal(target) },
+ { SpriteCustomLitPasses.CustomLit(target) },
+ { SpriteCustomLitPasses.Normal(target) },
// Currently neither of these passes (selection/picking) can be last for the game view for
// UI shaders to render correctly. Verify [1352225] before changing this order.
{ CorePasses._2DSceneSelection(target) },
{ CorePasses._2DScenePicking(target) },
- { SpriteLitPasses.Forward(target) },
+ { SpriteCustomLitPasses.Forward(target) },
},
};
return result;
@@ -81,9 +87,9 @@ public static SubShaderDescriptor SpriteLit(UniversalTarget target)
#endregion
#region Passes
- static class SpriteLitPasses
+ static class SpriteCustomLitPasses
{
- public static PassDescriptor Lit(UniversalTarget target)
+ public static PassDescriptor CustomLit(UniversalTarget target)
{
var result = new PassDescriptor()
{
@@ -107,11 +113,11 @@ public static PassDescriptor Lit(UniversalTarget target)
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
- renderStates = SpriteSubTargetUtility.GetDefaultRenderState(target),
+ renderStates = target.sort3Das2DCompatible ? Universal2DSubTargetDescriptors.RenderStateCollections.Sort3Das2DCompatible : CoreRenderStates.Default,
pragmas = CorePragmas._2DDefault,
defines = new DefineCollection(),
- keywords = SpriteLitKeywords.Lit,
- includes = SpriteLitIncludes.Lit,
+ keywords = SpriteCustomLitKeywords.Lit,
+ includes = target.sort3Das2DCompatible ? MeshUnlitIncludes.Unlit : SpriteCustomLitIncludes.Unlit,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
@@ -149,13 +155,15 @@ public static PassDescriptor Normal(UniversalTarget target)
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
- renderStates = CoreRenderStates.Default,
+
+ renderStates = target.sort3Das2DCompatible ? Universal2DSubTargetDescriptors.RenderStateCollections.Sort3Das2DCompatible : CoreRenderStates.Default,
pragmas = CorePragmas._2DDefault,
defines = new DefineCollection(),
- includes = SpriteLitIncludes.Normal,
+ includes = target.sort3Das2DCompatible ? UniversalMeshLitInfo.Includes.Normal : SpriteCustomLitIncludes.Normal,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
+
};
if (target.disableTint)
@@ -187,14 +195,14 @@ public static PassDescriptor Forward(UniversalTarget target)
// Fields
structs = CoreStructCollections.Default,
requiredFields = SpriteLitRequiredFields.Forward,
- keywords = SpriteLitKeywords.Forward,
+ keywords = SpriteCustomLitKeywords.Forward,
fieldDependencies = CoreFieldDependencies.Default,
// Conditional State
renderStates = CoreRenderStates.Default,
pragmas = CorePragmas._2DDefault,
defines = new DefineCollection(),
- includes = SpriteLitIncludes.Forward,
+ includes = SpriteCustomLitIncludes.Forward,
// Custom Interpolator Support
customInterpolators = CoreCustomInterpDescriptors.Common
@@ -266,7 +274,7 @@ static class SpriteLitRequiredFields
#endregion
#region Keywords
- static class SpriteLitKeywords
+ static class SpriteCustomLitKeywords
{
public static KeywordCollection Lit = new KeywordCollection
{
@@ -283,7 +291,7 @@ static class SpriteLitKeywords
#endregion
#region Includes
- static class SpriteLitIncludes
+ static class SpriteCustomLitIncludes
{
const string kSpriteCore2D = "Packages/com.unity.render-pipelines.universal/Shaders/2D/Include/Core2D.hlsl";
const string kSpriteUnlitPass = "Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteUnlitPass.hlsl";
@@ -291,7 +299,7 @@ static class SpriteLitIncludes
const string kSpriteNormalPass = "Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteNormalPass.hlsl";
const string kSpriteForwardPass = "Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Includes/SpriteForwardPass.hlsl";
- public static IncludeCollection Lit = new IncludeCollection
+ public static IncludeCollection Unlit = new IncludeCollection
{
// Pre-graph
{ CoreIncludes.FogPregraph },
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs
index 9a501535081..21c1b0cb4d1 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/2D/ShaderGraph/Targets/UniversalSpriteLitSubTarget.cs
@@ -75,6 +75,12 @@ public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary urpAssets)
+ {
+ foreach (var urpAssetForBuild in urpAssets)
+ {
+ foreach (var rendererData in urpAssetForBuild.m_RendererDataList)
+ {
+ if(rendererData is not UniversalRendererData)
+ continue;
+
+ foreach (var rendererFeature in rendererData.rendererFeatures)
+ {
+ if (rendererFeature is SurfaceCacheGlobalIlluminationRendererFeature { isActive: true })
+ return false;
+ }
+ }
+ }
+ return false;
+ }
+
+ internal static bool CanRemoveSurfaceCacheSettings(List urpAssets)
+ {
+ if (GraphicsSettings.TryGetRenderPipelineSettings(out var urpShaderStrippingSettings) && !urpShaderStrippingSettings.stripUnusedVariants)
+ return false;
+
+ if (IsSurfaceCacheEnabled(urpAssets))
+ return false;
+
+ return true;
+ }
+ }
+
+ class UniversalSurfaceCacheIntegrationStripper : IRenderPipelineGraphicsSettingsStripper
+ {
+ public bool active => URPBuildData.instance.buildingPlayerForUniversalRenderPipeline;
+
+ public bool CanRemoveSettings(UnityEngine.Rendering.Universal.SurfaceCacheRenderPipelineResourceSet settings)
+ {
+ return SurfaceCacheStripperUtility.CanRemoveSurfaceCacheSettings(URPBuildData.instance.renderPipelineAssets);
+ }
+ }
+
+ class UniversalSurfaceCacheCoreStripper : IRenderPipelineGraphicsSettingsStripper
+ {
+ public bool active => URPBuildData.instance.buildingPlayerForUniversalRenderPipeline;
+
+ public bool CanRemoveSettings(UnityEngine.Rendering.SurfaceCacheRenderPipelineResourceSet settings)
+ {
+ return SurfaceCacheStripperUtility.CanRemoveSurfaceCacheSettings(URPBuildData.instance.renderPipelineAssets);
+ }
+
+ }
+}
+#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/BuildProcessors/GraphicsSettingsStrippers/SurfaceCacheGlobalIlluminationStripper.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/BuildProcessors/GraphicsSettingsStrippers/SurfaceCacheGlobalIlluminationStripper.cs.meta
new file mode 100644
index 00000000000..53ccde453c3
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/BuildProcessors/GraphicsSettingsStrippers/SurfaceCacheGlobalIlluminationStripper.cs.meta
@@ -0,0 +1,3 @@
+fileFormatVersion: 2
+guid: c094860479f147488030fb1820fb1264
+timeCreated: 1753885315
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Converter/AnimationClipConverter.cs b/Packages/com.unity.render-pipelines.universal/Editor/Converter/AnimationClipConverter.cs
index c97448cb7e2..d4c0c6ada93 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/Converter/AnimationClipConverter.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Converter/AnimationClipConverter.cs
@@ -3,6 +3,7 @@
using System.Linq;
using System.Text;
using UnityEditor.Rendering.Universal;
+using UnityEngine.Rendering.Universal;
using ClipPath = UnityEditor.Rendering.AnimationClipUpgrader.ClipPath;
using ClipProxy = UnityEditor.Rendering.AnimationClipUpgrader.AnimationClipProxy;
using UnityObject = UnityEngine.Object;
@@ -68,8 +69,8 @@ public override void OnPreRun()
.ToArray();
// create table mapping all upgrade paths to new shaders
- var upgraders = new UniversalRenderPipelineMaterialUpgrader().upgraders;
- var allUpgradePathsToNewShaders = UpgradeUtility.GetAllUpgradePathsToShaders(upgraders);
+ var allUpgradePathsToNewShaders = UpgradeUtility.GetAllUpgradePathsToShaders(
+ MaterialUpgrader.FetchAllUpgradersForPipeline(typeof(UniversalRenderPipelineAsset)));
// TODO: could pass in upgrade paths used by materials in the future
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Converter/RenderPipelineConvertersEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/Converter/RenderPipelineConvertersEditor.cs
index d083527cfad..445ad816ef6 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/Converter/RenderPipelineConvertersEditor.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Converter/RenderPipelineConvertersEditor.cs
@@ -254,8 +254,11 @@ void GetConverters()
for (int i = 0; i < converterList.Count; ++i)
{
// Iterate over the converters that are used by the current container
- RenderPipelineConverter conv = (RenderPipelineConverter)Activator.CreateInstance(converterList[i]);
- m_CoreConvertersList.Add(conv);
+ if (!converterList[i].IsAbstract)
+ {
+ RenderPipelineConverter conv = (RenderPipelineConverter)Activator.CreateInstance(converterList[i]);
+ m_CoreConvertersList.Add(conv);
+ }
}
// this need to be sorted by Priority property
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Decal/DecalProjectorEditor.Skin.cs b/Packages/com.unity.render-pipelines.universal/Editor/Decal/DecalProjectorEditor.Skin.cs
index 2294730d57b..b75b74678c7 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/Decal/DecalProjectorEditor.Skin.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Decal/DecalProjectorEditor.Skin.cs
@@ -23,7 +23,6 @@ partial class DecalProjectorEditor
static readonly GUIContent k_Offset = EditorGUIUtility.TrTextContent("Pivot", "Controls the position of the pivot point of the decal.");
static readonly GUIContent k_NewMaterialButtonText = EditorGUIUtility.TrTextContent("New", "Creates a new decal Material asset template.");
- static readonly string k_NewDecalMaterialText = "New Decal";
static readonly string k_BaseSceneEditingToolText = "Decal Scene Editing Mode: ";
static readonly string k_EditShapeWithoutPreservingUVName = k_BaseSceneEditingToolText + "Scale";
static readonly string k_EditShapePreservingUVName = k_BaseSceneEditingToolText + "Crop";
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Decal/DecalProjectorEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/Decal/DecalProjectorEditor.cs
index 29b3ee2ccb6..e9881f0764d 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/Decal/DecalProjectorEditor.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Decal/DecalProjectorEditor.cs
@@ -1,10 +1,14 @@
using System;
using System.Collections.Generic;
using UnityEditor.IMGUI.Controls;
+using UnityEditor.ShaderGraph;
using UnityEditor.ShortcutManagement;
using UnityEditorInternal;
+using UnityEditor.EditorTools;
+using UnityEditor.Rendering.Utilities;
using UnityEngine;
using UnityEngine.Rendering;
+using UnityEditor.RenderPipelines.Core;
using UnityEngine.Rendering.Universal;
using static UnityEditorInternal.EditMode;
@@ -17,6 +21,11 @@ partial class DecalProjectorEditor : Editor
const float k_Limit = 100000f;
const float k_LimitInv = 1f / k_Limit;
+ static readonly GUIContent k_NewDecalMaterialButtonText = EditorGUIUtility.TrTextContent("New", "Creates a new Decal material.");
+ static readonly string k_NewDecalText = "URP Decal";
+ static readonly string k_NewSGDecalText = "ShaderGraph Decal";
+ static readonly string k_DefaultDecalShaderGraphTemplatePath = "Packages/com.unity.render-pipelines.universal/Shaders/Decal.shadergraph";
+
static Color fullColor
{
get
@@ -117,14 +126,6 @@ static DisplacableRectHandles uvHandles
static Func s_DrawPivotHandle;
- static GUIContent[] k_EditVolumeLabels = null;
- static GUIContent[] editVolumeLabels => k_EditVolumeLabels ?? (k_EditVolumeLabels = new GUIContent[]
- {
- EditorGUIUtility.TrIconContent("d_ScaleTool", k_EditShapeWithoutPreservingUVTooltip),
- EditorGUIUtility.TrIconContent("d_RectTool", k_EditShapePreservingUVTooltip),
- EditorGUIUtility.TrIconContent("d_MoveTool", k_EditUVTooltip),
- });
-
static List s_Instances = new List();
static DecalProjectorEditor FindEditorFromSelection()
@@ -557,29 +558,6 @@ public override void OnInspectorGUI()
EditorGUI.BeginChangeCheck();
{
- EditorGUILayout.BeginHorizontal();
- GUILayout.FlexibleSpace();
- DoInspectorToolbar(k_EditVolumeModes, editVolumeLabels, GetBoundsGetter(target as DecalProjector), this);
- GUILayout.FlexibleSpace();
- EditorGUILayout.EndHorizontal();
-
- EditorGUILayout.Space();
-
- // Info box for tools
- GUIStyle style = new GUIStyle(EditorStyles.miniLabel);
- style.richText = true;
- GUILayout.BeginVertical(EditorStyles.helpBox);
- string helpText = k_BaseSceneEditingToolText;
- if (EditMode.editMode == k_EditShapeWithoutPreservingUV && EditMode.IsOwner(this))
- helpText = k_EditShapeWithoutPreservingUVName;
- if (EditMode.editMode == k_EditShapePreservingUV && EditMode.IsOwner(this))
- helpText = k_EditShapePreservingUVName;
- if (EditMode.editMode == k_EditUVAndPivot && EditMode.IsOwner(this))
- helpText = k_EditUVAndPivotName;
- GUILayout.Label(helpText, style);
- GUILayout.EndVertical();
- EditorGUILayout.Space();
-
EditorGUILayout.PropertyField(m_ScaleMode, k_ScaleMode);
bool negativeScale = false;
@@ -743,15 +721,54 @@ internal void MaterialFieldWithButton(SerializedProperty prop, GUIContent label)
newFieldRect.x = rect.xMax + 2;
newFieldRect.width = k_NewFieldWidth;
- if (GUI.Button(newFieldRect, k_NewMaterialButtonText))
+ if (!EditorGUI.DropdownButton(newFieldRect, k_NewDecalMaterialButtonText, FocusType.Keyboard))
+ return;
+
+ GenericMenu menu = new GenericMenu();
+
+ menu.AddItem(new GUIContent(k_NewDecalText), false, () => CreateDefaultDecalMaterial(targets));
+ menu.AddItem(new GUIContent(k_NewSGDecalText), false, () => CreateDecalMaterialFromTemplate(targets, k_DefaultDecalShaderGraphTemplatePath));
+
+ // For later introduction of SG Filtered Template Browser
+ //menu.AddItem(new GUIContent(k_NewSGDecalFromTemplateText), false, () => CreateDecalMaterialFromTemplate(targets));
+
+ menu.DropDown(newFieldRect);
+ }
+
+ static void CreateDecalMaterialFromTemplate(UnityEngine.Object[] decalProjectors, string templatePath = null)
+ {
+ CreateShaderGraph.CreateGraphAndMaterialFromTemplate((material) =>
{
- string materialName = k_NewDecalMaterialText + ".mat";
- var materialIcon = AssetPreview.GetMiniTypeThumbnail(typeof(Material));
- var action = ScriptableObject.CreateInstance();
- action.decalProjector = target as DecalProjector;
- ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, action, materialName, materialIcon, null);
+ SetDecalMaterial(decalProjectors, material);
+ },
+ templatePath,
+ $"New {k_NewSGDecalText}");
+ }
+
+ static void CreateDefaultDecalMaterial(UnityEngine.Object[] decalProjectors)
+ {
+ string materialName = "New " + k_NewDecalText;
+
+ AssetCreationUtil.CreateMaterial(
+ materialName,
+ (material) =>
+ {
+ SetDecalMaterial(decalProjectors, material);
+ },
+ DecalProjector.defaultMaterial.shader
+ );
+ }
+
+ static void SetDecalMaterial(UnityEngine.Object[] decalProjectors, Material material)
+ {
+ var selection = new List();
+ foreach (DecalProjector decalProjector in decalProjectors)
+ {
+ decalProjector.material = material;
+ EditorUtility.SetDirty(decalProjector);
+ selection.Add(decalProjector.gameObject);
}
-
+ Selection.objects = selection.ToArray();
}
[Shortcut("URP/Decal: Handle changing size stretching UV", typeof(SceneView), KeyCode.Keypad1, ShortcutModifiers.Action)]
@@ -820,18 +837,35 @@ static void ExitEditMode(ShortcutArguments args)
QuitEditMode();
}
- }
- class DoCreateDecalDefaultMaterial : ProjectWindowCallback.EndNameEditAction
- {
- public DecalProjector decalProjector;
- public override void Action(int instanceId, string pathName, string resourceFile)
- {
- var shader = DecalProjector.defaultMaterial.shader;
- var material = new Material(shader);
- AssetDatabase.CreateAsset(material, pathName);
- ProjectWindowUtil.ShowCreatedAsset(material);
- decalProjector.material = material;
+ [EditorTool(Description, typeof(DecalProjector), toolPriority = (int)Mode)]
+ internal class DecalProjectorModifyScaleTool : GenericEditorTool
+ {
+ private const string Description = DecalProjectorEditor.k_EditShapeWithoutPreservingUVTooltip;
+ private const EditMode.SceneViewEditMode Mode = DecalProjectorEditor.k_EditShapeWithoutPreservingUV;
+ private const string IconName = "ScaleTool";
+
+ protected DecalProjectorModifyScaleTool() : base(Description, Mode, IconName) { }
+ }
+
+ [EditorTool(Description, typeof(DecalProjector), toolPriority = (int)Mode)]
+ internal class DecalProjectorEditShapeTool : GenericEditorTool
+ {
+ private const string Description = DecalProjectorEditor.k_EditShapePreservingUVTooltip;
+ private const EditMode.SceneViewEditMode Mode = DecalProjectorEditor.k_EditShapePreservingUV;
+ private const string IconName = "RectTool";
+
+ protected DecalProjectorEditShapeTool() : base(Description, Mode, IconName) { }
+ }
+
+ [EditorTool(Description, typeof(DecalProjector), toolPriority = (int)Mode)]
+ internal class DecalProjectorEditTool : GenericEditorTool
+ {
+ private const string Description = DecalProjectorEditor.k_EditUVTooltip;
+ private const EditMode.SceneViewEditMode Mode = DecalProjectorEditor.k_EditUVAndPivot;
+ private const string IconName = "MoveTool";
+
+ protected DecalProjectorEditTool() : base(Description, Mode, IconName) { }
}
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/DecalRendererFeatureEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/DecalRendererFeatureEditor.cs
index 620f5be2d3a..ba16ae93864 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/DecalRendererFeatureEditor.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/DecalRendererFeatureEditor.cs
@@ -45,12 +45,20 @@ public override void OnInspectorGUI()
{
Init();
+ var isGLDevice = SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3 || SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLCore;
+
EditorGUILayout.PropertyField(m_Technique, Styles.Technique);
DecalTechniqueOption technique = (DecalTechniqueOption)m_Technique.intValue;
if (technique == DecalTechniqueOption.DBuffer)
{
+ if (isGLDevice)
+ {
+ EditorGUILayout.HelpBox("DBuffer technique is not supported on OpenGL. Decals will not be rendered.", MessageType.Error);
+ EditorGUILayout.Space();
+ }
+
EditorGUI.indentLevel++;
EditorGUILayout.PropertyField(m_DBufferSurfaceData, Styles.SurfaceData);
EditorGUI.indentLevel--;
@@ -64,7 +72,25 @@ public override void OnInspectorGUI()
}
EditorGUILayout.PropertyField(m_MaxDrawDistance, Styles.MaxDrawDistance);
+
+ if (isGLDevice)
+ {
+ if (m_DecalLayers.boolValue)
+ {
+ m_DecalLayers.boolValue = false;
+ serializedObject.ApplyModifiedProperties();
+ }
+
+ GUI.enabled = false;
+ }
+
EditorGUILayout.PropertyField(m_DecalLayers, Styles.UseRenderingLayers);
+
+ if (isGLDevice)
+ {
+ GUI.enabled = true;
+ EditorGUILayout.HelpBox("Rendering Layers are not supported on OpenGL.", MessageType.Warning);
+ }
}
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/FullScreenPassRendererFeatureEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/FullScreenPassRendererFeatureEditor.cs
index 92691710b72..261a729c086 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/FullScreenPassRendererFeatureEditor.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/FullScreenPassRendererFeatureEditor.cs
@@ -1,6 +1,9 @@
using System.Collections.Generic;
+using UnityEditor.RenderPipelines.Core;
+using UnityEditor.ShaderGraph;
using UnityEngine;
using UnityEngine.Rendering.Universal;
+using static UnityEditor.Rendering.InspectorCurveEditor;
namespace UnityEditor.Rendering.Universal
{
@@ -26,6 +29,12 @@ public class FullScreenPassRendererFeatureEditor : Editor
private static readonly GUIContent k_PassMaterialGuiContent = new GUIContent("Pass Material", "The material used to render the full screen pass.");
private static readonly GUIContent k_PassGuiContent = new GUIContent("Pass", "The name of the shader pass to use from the assigned material.");
+ static readonly GUIContent k_NewFullscreenMaterialButtonText = EditorGUIUtility.TrTextContent("New", "Creates a new Fullscreen material.");
+ static readonly string k_NewBlitShaderText = "SRP Blit Shader";
+ static readonly string k_NewSGFullscreenText = "ShaderGraph Fullscreen";
+ static readonly string k_BlitShaderTemplatePath = "Packages/com.unity.render-pipelines.core/Editor/ScriptTemplates/BlitSRP.txt";
+ static readonly string k_DefaultFullscreenShaderGraphTemplatePath = "Packages/com.unity.render-pipelines.universal/Shaders/FullscreenInvertColors.shadergraph";
+
private void OnEnable()
{
m_InjectionPointProperty = serializedObject.FindProperty("injectionPoint");
@@ -50,7 +59,11 @@ public override void OnInspectorGUI()
EditorGUILayout.PropertyField(m_RequirementsProperty, k_RequirementsGuiContent);
EditorGUILayout.PropertyField(m_FetchColorBufferProperty, k_FetchColorBufferGuiContent);
EditorGUILayout.PropertyField(m_BindDepthStencilAttachmentProperty, k_BindDepthStencilAttachmentGuiContent);
- EditorGUILayout.PropertyField(m_PassMaterialProperty, k_PassMaterialGuiContent);
+
+ MaterialFieldWithButton(m_PassMaterialProperty, k_PassMaterialGuiContent);
+
+ if (m_PassMaterialProperty.objectReferenceValue == null)
+ EditorGUILayout.HelpBox("The full screen feature will not execute - no material is assigned. Please make sure a material is assigned for this feature on the renderer asset.", MessageType.Warning, true);
if (AdvancedProperties.BeginGroup())
{
@@ -61,6 +74,62 @@ public override void OnInspectorGUI()
serializedObject.ApplyModifiedProperties();
}
+ internal void MaterialFieldWithButton(SerializedProperty prop, GUIContent label)
+ {
+ const int k_NewFieldWidth = 70;
+
+ var rect = EditorGUILayout.GetControlRect();
+ rect.xMax -= k_NewFieldWidth + 2;
+
+ EditorGUI.PropertyField(rect, prop, label);
+
+ var newFieldRect = rect;
+ newFieldRect.x = rect.xMax + 2;
+ newFieldRect.width = k_NewFieldWidth;
+
+ if (!EditorGUI.DropdownButton(newFieldRect, k_NewFullscreenMaterialButtonText, FocusType.Keyboard))
+ return;
+
+ GenericMenu menu = new GenericMenu();
+ menu.AddItem(new GUIContent(k_NewSGFullscreenText), false, () => CreateFullscreenMaterialFromTemplate(target as FullScreenPassRendererFeature, k_DefaultFullscreenShaderGraphTemplatePath));
+
+ // For later introduction of SG Filtered Template Browser
+ //menu.AddItem(new GUIContent(k_NewSGFullscreenFromTemplateText), false, () => CreateFullscreenMaterialFromTemplate(target as FullScreenPassRendererFeature));
+
+ menu.AddItem(new GUIContent(k_NewBlitShaderText), false, () => CreateDefaultFullscreenMaterial(target as FullScreenPassRendererFeature));
+ menu.DropDown(newFieldRect);
+ }
+
+ internal static void CreateFullscreenMaterialFromTemplate(FullScreenPassRendererFeature obj, string templatePath = null)
+ {
+ var selection = Selection.activeObject; // holding selection
+ CreateShaderGraph.CreateGraphAndMaterialFromTemplate((material) =>
+ {
+ obj.passMaterial = material;
+ EditorUtility.SetDirty(obj);
+ Selection.activeObject = selection; //restoring selection
+ },
+ templatePath,
+ $"New {k_NewSGFullscreenText}");
+ }
+
+ internal static void CreateDefaultFullscreenMaterial(FullScreenPassRendererFeature obj)
+ {
+ string materialName = "New " + k_NewBlitShaderText;
+
+ var selection = Selection.activeObject; // holding selection
+ AssetCreationUtil.CreateShaderAndMaterial(
+ materialName,
+ (material) =>
+ {
+ obj.passMaterial = material;
+ EditorUtility.SetDirty(obj);
+ Selection.activeObject = selection; //restoring selection
+ },
+ k_BlitShaderTemplatePath
+ );
+ }
+
private void DrawMaterialPassProperty(FullScreenPassRendererFeature feature)
{
List selectablePasses;
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/ScreenSpaceShadowsEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/ScreenSpaceShadowsEditor.cs
index ba30993c0cb..fd5a65920ca 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/ScreenSpaceShadowsEditor.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/ScreenSpaceShadowsEditor.cs
@@ -12,9 +12,9 @@ internal class ScreenSpaceShadowsEditor : Editor
private bool m_IsInitialized = false;
- private struct Styles
+ static class Styles
{
- public static GUIContent Description = EditorGUIUtility.TrTextContent("Description", "This feature resolves the cascaded shadows in screen space, so there is no options now. It might have additional settings later.");
+ public static readonly string k_NoSettingsHelpBox = L10n.Tr("This feature resolves the cascaded shadows in screen space, so there is no options now. It might have additional settings later.");
}
private void Init()
@@ -30,7 +30,7 @@ public override void OnInspectorGUI()
Init();
}
- EditorGUILayout.PropertyField(m_SettingsProp, Styles.Description);
+ EditorGUILayout.HelpBox(Styles.k_NoSettingsHelpBox, MessageType.Info);
}
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/SurfaceCacheGlobalIlluminationEditor.cs b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/SurfaceCacheGlobalIlluminationEditor.cs
new file mode 100644
index 00000000000..bf09baa7edd
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/SurfaceCacheGlobalIlluminationEditor.cs
@@ -0,0 +1,179 @@
+#if SURFACE_CACHE
+
+using UnityEngine;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.Universal;
+
+namespace UnityEditor.Rendering.Universal
+{
+ [CustomEditor(typeof(SurfaceCacheGlobalIlluminationRendererFeature))]
+ internal class SurfaceCacheGlobalIlluminationEditor : Editor
+ {
+ private bool m_IsInitialized;
+
+ private SerializedProperty _uniformEstimationSampleCount;
+ private SerializedProperty _restirEstimationConfidenceCap;
+ private SerializedProperty _restirEstimationSpatialSampleCount;
+ private SerializedProperty _restirEstimationSpatialFilterSize;
+ private SerializedProperty _restirEstimationValidationFrameInterval;
+ private SerializedProperty _risEstimationCandidateCount;
+ private SerializedProperty _risEstimationTargetFunctionUpdateWeight;
+ private SerializedProperty _multiBounce;
+ private SerializedProperty _estimationMethod;
+ private SerializedProperty _temporalSmoothing;
+ private SerializedProperty _spatialFilterEnabled;
+ private SerializedProperty _spatialFilterSampleCount;
+ private SerializedProperty _spatialFilterRadius;
+ private SerializedProperty _temporalPostFilterEnabled;
+ private SerializedProperty _lookupSampleCount;
+ private SerializedProperty _upsamplingKernelSize;
+ private SerializedProperty _upsamplingSampleCount;
+ private SerializedProperty _gridSize;
+ private SerializedProperty _voxelMinSize;
+ private SerializedProperty _cascadeCount;
+ private SerializedProperty _cascadeMovement;
+ private SerializedProperty _debugEnabled;
+ private SerializedProperty _debugViewMode;
+ private SerializedProperty _debugShowSamplePosition;
+
+ private struct TextContent
+ {
+ public static GUIContent UniformEstimationSampleCount = EditorGUIUtility.TrTextContent("Sample Count", "");
+ public static GUIContent RestirEstimationConfidenceCap = EditorGUIUtility.TrTextContent("Confidence Cap", "");
+ public static GUIContent RestirEstimationSpatialSampleCount = EditorGUIUtility.TrTextContent("Spatial Sample Count", "");
+ public static GUIContent RestirEstimationSpatialFilterSize = EditorGUIUtility.TrTextContent("Spatial Filter Size", "");
+ public static GUIContent RestirEstimationValidationFrameInterval = EditorGUIUtility.TrTextContent("Validation Frame Interval", "");
+ public static GUIContent RisEstimationCandidateCount = EditorGUIUtility.TrTextContent("Candidate Count", "");
+ public static GUIContent RisEstimationTargetFunctionUpdateWeight = EditorGUIUtility.TrTextContent("Target Function Update Weight", "");
+ public static GUIContent MultiBounce = EditorGUIUtility.TrTextContent("Multi Bounce", "");
+ public static GUIContent EstimationMethod = EditorGUIUtility.TrTextContent("Estimation Method", "");
+
+ public static GUIContent TemporalSmoothing = EditorGUIUtility.TrTextContent("Temporal Smoothing", "");
+ public static GUIContent SpatialFilterEnabled = EditorGUIUtility.TrTextContent("Spatial Filter Enabled", "");
+ public static GUIContent SpatialFilterSampleCount = EditorGUIUtility.TrTextContent("Spatial Sample Count", "");
+ public static GUIContent SpatialFilterRadius = EditorGUIUtility.TrTextContent("Spatial Radius", "");
+ public static GUIContent TemporalPostFilterEnabled = EditorGUIUtility.TrTextContent("Temporal Post Filter Enabled", "");
+
+ public static GUIContent LookupSampleCount = EditorGUIUtility.TrTextContent("Lookup Sample Count", "");
+ public static GUIContent UpsamplingKernelSize = EditorGUIUtility.TrTextContent("Upsampling Kernel Size", "");
+ public static GUIContent UpsamplingSampleCount = EditorGUIUtility.TrTextContent("Upsampling Sample Count", "");
+
+ public static GUIContent GridSize = EditorGUIUtility.TrTextContent("Grid Size", "");
+ public static GUIContent VoxelMinSize = EditorGUIUtility.TrTextContent("Voxel Min Size", "");
+ public static GUIContent CascadeCount = EditorGUIUtility.TrTextContent("Cascade Count", "");
+ public static GUIContent CascadeMovement = EditorGUIUtility.TrTextContent("Cascade Movement", "");
+
+ public static GUIContent DebugEnabled = EditorGUIUtility.TrTextContent("Debug Enabled", "");
+ public static GUIContent DebugViewMode = EditorGUIUtility.TrTextContent("Debug View Mode", "");
+ public static GUIContent DebugShowSamplePosition = EditorGUIUtility.TrTextContent("Debug Show Sample Position", "");
+ }
+
+ private void Init()
+ {
+ SerializedProperty paramSet = serializedObject.FindProperty("_parameterSet");
+
+ SerializedProperty uniformParamSet = paramSet.FindPropertyRelative("UniformEstimationParams");
+ SerializedProperty restirParamSet = paramSet.FindPropertyRelative("RestirEstimationParams");
+ SerializedProperty risParamSet = paramSet.FindPropertyRelative("RisEstimationParams");
+ SerializedProperty patchFilteringParamSet = paramSet.FindPropertyRelative("PatchFilteringParams");
+ SerializedProperty screenFilteringParamSet = paramSet.FindPropertyRelative("ScreenFilteringParams");
+ SerializedProperty gridParamSet = paramSet.FindPropertyRelative("GridParams");
+
+ _multiBounce = paramSet.FindPropertyRelative("MultiBounce");
+ _estimationMethod = paramSet.FindPropertyRelative("EstimationMethod");
+
+ _uniformEstimationSampleCount = uniformParamSet.FindPropertyRelative("SampleCount");
+ _restirEstimationConfidenceCap = restirParamSet.FindPropertyRelative("ConfidenceCap");
+ _restirEstimationSpatialSampleCount = restirParamSet.FindPropertyRelative("SpatialSampleCount");
+ _restirEstimationSpatialFilterSize = restirParamSet.FindPropertyRelative("SpatialFilterSize");
+ _restirEstimationValidationFrameInterval = restirParamSet.FindPropertyRelative("ValidationFrameInterval");
+ _risEstimationCandidateCount = risParamSet.FindPropertyRelative("CandidateCount");
+ _risEstimationTargetFunctionUpdateWeight = risParamSet.FindPropertyRelative("TargetFunctionUpdateWeight");
+
+ _temporalSmoothing = patchFilteringParamSet.FindPropertyRelative("TemporalSmoothing");
+ _spatialFilterEnabled = patchFilteringParamSet.FindPropertyRelative("SpatialFilterEnabled");
+ _spatialFilterSampleCount = patchFilteringParamSet.FindPropertyRelative("SpatialFilterSampleCount");
+ _spatialFilterRadius = patchFilteringParamSet.FindPropertyRelative("SpatialFilterRadius");
+ _temporalPostFilterEnabled = patchFilteringParamSet.FindPropertyRelative("TemporalPostFilterEnabled");
+
+ _lookupSampleCount = screenFilteringParamSet.FindPropertyRelative("LookupSampleCount");
+ _upsamplingKernelSize = screenFilteringParamSet.FindPropertyRelative("UpsamplingKernelSize");
+ _upsamplingSampleCount = screenFilteringParamSet.FindPropertyRelative("UpsamplingSampleCount");
+
+ _gridSize = gridParamSet.FindPropertyRelative("GridSize");
+ _voxelMinSize = gridParamSet.FindPropertyRelative("VoxelMinSize");
+ _cascadeCount = gridParamSet.FindPropertyRelative("CascadeCount");
+ _cascadeMovement = gridParamSet.FindPropertyRelative("CascadeMovement");
+
+ _debugEnabled = paramSet.FindPropertyRelative("DebugEnabled");
+ _debugViewMode = paramSet.FindPropertyRelative("DebugViewMode");
+ _debugShowSamplePosition = paramSet.FindPropertyRelative("DebugShowSamplePosition");
+ }
+
+ public override void OnInspectorGUI()
+ {
+ if (!m_IsInitialized)
+ Init();
+
+ if (SceneView.lastActiveSceneView && !SceneView.lastActiveSceneView.sceneViewState.alwaysRefreshEnabled)
+ {
+ EditorGUILayout.HelpBox("Enable \"Always Refresh\" in the Scene View to see realtime updates in the Scene View.", MessageType.Info);
+ }
+
+ EditorGUILayout.LabelField("Light Transport", EditorStyles.boldLabel);
+ EditorGUILayout.PropertyField(_multiBounce, TextContent.MultiBounce);
+ EditorGUILayout.PropertyField(_estimationMethod, TextContent.EstimationMethod);
+ if (_estimationMethod.intValue == (int)SurfaceCacheEstimationMethod.Uniform)
+ {
+ EditorGUILayout.Space();
+ EditorGUILayout.LabelField("Uniform Estimation", EditorStyles.boldLabel);
+ EditorGUILayout.IntSlider(_uniformEstimationSampleCount, 1, 32, TextContent.UniformEstimationSampleCount);
+ }
+ else if (_estimationMethod.intValue == (int)SurfaceCacheEstimationMethod.Restir)
+ {
+ EditorGUILayout.Space();
+ EditorGUILayout.LabelField("Restir Estimation", EditorStyles.boldLabel);
+ EditorGUILayout.IntSlider(_restirEstimationConfidenceCap, 1, 64, TextContent.RestirEstimationConfidenceCap);
+ EditorGUILayout.IntSlider(_restirEstimationSpatialSampleCount, 0, 8, TextContent.RestirEstimationSpatialSampleCount);
+ EditorGUILayout.Slider(_restirEstimationSpatialFilterSize, 0.0f, 4.0f, TextContent.RestirEstimationSpatialFilterSize);
+ EditorGUILayout.IntSlider(_restirEstimationValidationFrameInterval, 2, 8, TextContent.RestirEstimationValidationFrameInterval);
+ }
+ else if (_estimationMethod.intValue == (int)SurfaceCacheEstimationMethod.Ris)
+ {
+ EditorGUILayout.Space();
+ EditorGUILayout.LabelField("SH-Guided Ris Estimation", EditorStyles.boldLabel);
+ EditorGUILayout.IntSlider(_risEstimationCandidateCount, 2, 64, TextContent.RisEstimationCandidateCount);
+ EditorGUILayout.Slider(_risEstimationTargetFunctionUpdateWeight, 0.0f, 1.0f, TextContent.RisEstimationTargetFunctionUpdateWeight);
+ }
+
+ EditorGUILayout.Space();
+ EditorGUILayout.LabelField("Patch Filtering", EditorStyles.boldLabel);
+ EditorGUILayout.Slider(_temporalSmoothing, 0.0f, 1.0f, TextContent.TemporalSmoothing);
+ EditorGUILayout.PropertyField(_spatialFilterEnabled, TextContent.SpatialFilterEnabled);
+ EditorGUILayout.IntSlider(_spatialFilterSampleCount, 1, 8, TextContent.SpatialFilterSampleCount);
+ EditorGUILayout.Slider(_spatialFilterRadius, 0.1f, 4.0f, TextContent.SpatialFilterRadius);
+ EditorGUILayout.PropertyField(_temporalPostFilterEnabled, TextContent.TemporalPostFilterEnabled);
+
+ EditorGUILayout.Space();
+ EditorGUILayout.LabelField("Screen Filtering", EditorStyles.boldLabel);
+ EditorGUILayout.IntSlider(_lookupSampleCount, 0, 8, TextContent.LookupSampleCount);
+ EditorGUILayout.Slider(_upsamplingKernelSize, 0.0f, 8.0f, TextContent.UpsamplingKernelSize);
+ EditorGUILayout.IntSlider(_upsamplingSampleCount, 1, 16, TextContent.UpsamplingSampleCount);
+
+ EditorGUILayout.Space();
+ EditorGUILayout.LabelField("Grid", EditorStyles.boldLabel);
+ EditorGUILayout.IntSlider(_gridSize, 16, 64, TextContent.GridSize);
+ EditorGUILayout.Slider(_voxelMinSize, 0.1f, 2.0f, TextContent.VoxelMinSize);
+ EditorGUILayout.IntSlider(_cascadeCount, 1, (int)SurfaceCache.CascadeMax, TextContent.CascadeCount);
+ EditorGUILayout.PropertyField(_cascadeMovement, TextContent.CascadeMovement);
+
+ EditorGUILayout.Space();
+ EditorGUILayout.LabelField("Debugging", EditorStyles.boldLabel);
+ EditorGUILayout.PropertyField(_debugEnabled, TextContent.DebugEnabled);
+ EditorGUILayout.PropertyField(_debugViewMode, TextContent.DebugViewMode);
+ EditorGUILayout.PropertyField(_debugShowSamplePosition, TextContent.DebugShowSamplePosition);
+ }
+ }
+}
+
+#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/SurfaceCacheGlobalIlluminationEditor.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/SurfaceCacheGlobalIlluminationEditor.cs.meta
new file mode 100644
index 00000000000..55e252005d5
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/RendererFeatures/SurfaceCacheGlobalIlluminationEditor.cs.meta
@@ -0,0 +1,3 @@
+fileFormatVersion: 2
+guid: d5f6a7ce5f9e41eb8f3b1910acaacd49
+timeCreated: 1733488061
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs
index cff29c71ba4..b69643de379 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderBuildPreprocessor.cs
@@ -73,6 +73,9 @@ enum ShaderFeatures : long
StencilLODCrossFade = (1L << 50),
DeferredPlus = (1L << 51),
ReflectionProbeAtlas = (1L << 52),
+#if SURFACE_CACHE
+ SurfaceCache = (1L << 53),
+#endif
All = ~0
}
@@ -169,11 +172,13 @@ internal sealed class PlatformBuildTimeDetect
internal bool isHololens { get; private set; }
internal bool isQuest { get; private set; }
internal bool isSwitch { get; private set; }
+ internal bool isSwitch2 { get; private set; }
private PlatformBuildTimeDetect()
{
BuildTargetGroup buildTargetGroup = BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget);
isSwitch = buildTargetGroup == BuildTargetGroup.Switch;
+ isSwitch2 = buildTargetGroup == BuildTargetGroup.Switch2;
#if XR_MANAGEMENT_4_0_1_OR_NEWER
var buildTargetSettings = XRGeneralSettingsPerBuildTarget.XRGeneralSettingsForBuildTarget(buildTargetGroup);
@@ -296,7 +301,7 @@ private static void GetGlobalAndPlatformSettings(bool isDevelopmentBuild)
PlatformBuildTimeDetect platformBuildTimeDetect = PlatformBuildTimeDetect.GetInstance();
bool isShaderAPIMobileDefined = GraphicsSettings.HasShaderDefine(BuiltinShaderDefine.SHADER_API_MOBILE);
- if (platformBuildTimeDetect.isSwitch || isShaderAPIMobileDefined)
+ if (platformBuildTimeDetect.isSwitch || platformBuildTimeDetect.isSwitch2 || isShaderAPIMobileDefined)
s_UseSHPerVertexForSHAuto = true;
// XR Stripping
@@ -457,9 +462,17 @@ private static void GetSupportedShaderFeaturesFromAssets(ref List ssaoRendererFeatures,
bool stripUnusedVariants,
out bool containsForwardRenderer,
+#if SURFACE_CACHE
+ out bool containsSurfaceCache,
+#endif
out bool everyRendererHasSSAO)
{
ShaderFeatures urpAssetShaderFeatures = ShaderFeatures.MainLight;
@@ -578,6 +597,9 @@ internal static ShaderFeatures GetSupportedShaderFeaturesFromAsset(
ref ssaoRendererFeatures,
stripUnusedVariants,
out containsForwardRenderer,
+#if SURFACE_CACHE
+ out containsSurfaceCache,
+#endif
out everyRendererHasSSAO);
return urpAssetShaderFeatures;
@@ -591,6 +613,9 @@ internal static ShaderFeatures GetSupportedShaderFeaturesFromRenderers(
ref List ssaoRendererFeatures,
bool stripUnusedVariants,
out bool containsForwardRenderer,
+#if SURFACE_CACHE
+ out bool containsSurfaceCache,
+#endif
out bool everyRendererHasSSAO)
{
// Sanity check
@@ -603,6 +628,9 @@ internal static ShaderFeatures GetSupportedShaderFeaturesFromRenderers(
ShaderFeatures combinedURPAssetShaderFeatures = ShaderFeatures.None;
containsForwardRenderer = false;
+#if SURFACE_CACHE
+ containsSurfaceCache = false;
+#endif
everyRendererHasSSAO = true;
ScriptableRendererData[] rendererDataArray = urpAsset.m_RendererDataList;
for (int rendererIndex = 0; rendererIndex < rendererDataArray.Length; ++rendererIndex)
@@ -618,6 +646,11 @@ internal static ShaderFeatures GetSupportedShaderFeaturesFromRenderers(
ShaderFeatures rendererShaderFeatures = GetSupportedShaderFeaturesFromRenderer(ref rendererRequirements, ref rendererData, ref ssaoRendererFeatures, ref containsForwardRenderer, urpAssetShaderFeatures);
rendererFeaturesList.Add(rendererShaderFeatures);
+#if SURFACE_CACHE
+ // Check to see if the Surface Cache feature is enabled
+ containsSurfaceCache |= IsFeatureEnabled(rendererShaderFeatures, ShaderFeatures.SurfaceCache);
+#endif
+
// Check to see if it's possible to remove the OFF variant for SSAO
everyRendererHasSSAO &= IsFeatureEnabled(rendererShaderFeatures, ShaderFeatures.ScreenSpaceOcclusion);
@@ -659,9 +692,9 @@ internal static RendererRequirements GetRendererRequirements(ref UniversalRender
rsd.needsGBufferRenderingLayers = (rsd.isUniversalRenderer && rsd.needsDeferredLighting && urpAsset.useRenderingLayers);
rsd.needsGBufferAccurateNormals = (rsd.isUniversalRenderer && rsd.needsDeferredLighting && (universalRendererData.renderingMode == RenderingMode.Deferred || universalRendererData.renderingMode == RenderingMode.DeferredPlus) && universalRendererData.accurateGbufferNormals);
rsd.needsRenderPass = (rsd.isUniversalRenderer && rsd.needsDeferredLighting);
- rsd.needsReflectionProbeBlending = urpAsset.reflectionProbeBlending;
+ rsd.needsReflectionProbeBlending = urpAsset.ShouldUseReflectionProbeBlending();
rsd.needsReflectionProbeBoxProjection = urpAsset.reflectionProbeBoxProjection;
- rsd.needsReflectionProbeAtlas = urpAsset.reflectionProbeBlending && (rsd.renderingMode == RenderingMode.DeferredPlus || urpAsset.reflectionProbeAtlas || urpAsset.gpuResidentDrawerMode != GPUResidentDrawerMode.Disabled) && rsd.needsClusterLightLoop;
+ rsd.needsReflectionProbeAtlas = urpAsset.ShouldUseReflectionProbeAtlasBlending(rsd.renderingMode) && rsd.needsClusterLightLoop;
rsd.needsProcedural = NeedsProceduralKeyword(ref rsd);
rsd.needsSHVertexForSHAuto = s_UseSHPerVertexForSHAuto;
@@ -832,6 +865,16 @@ internal static ShaderFeatures GetSupportedShaderFeaturesFromRendererFeatures(re
continue;
}
+#if SURFACE_CACHE
+ // Surface Cache GI...
+ SurfaceCacheGlobalIlluminationRendererFeature surfaceCacheFeature = rendererFeature as SurfaceCacheGlobalIlluminationRendererFeature;
+ if(surfaceCacheFeature != null)
+ {
+ shaderFeatures |= ShaderFeatures.SurfaceCache;
+ continue;
+ }
+#endif
+
// Decals...
DecalRendererFeature decal = rendererFeature as DecalRendererFeature;
if (decal != null && rendererRequirements.isUniversalRenderer)
@@ -939,6 +982,9 @@ internal static ShaderPrefilteringData CreatePrefilteringSettings(
bool stripScreenCoord,
bool stripBicubicLightmap,
bool stripReflectionProbeRotation,
+#if SURFACE_CACHE
+ bool stripScreenSpaceIrradiance,
+#endif
bool stripUnusedVariants,
ref List ssaoRendererFeatures
)
@@ -958,7 +1004,14 @@ ref List ssaoRendererFeatures
spd.stripScreenCoordOverride = stripScreenCoord;
spd.stripBicubicLightmapSampling = stripBicubicLightmap;
spd.stripReflectionProbeRotation = stripReflectionProbeRotation;
- spd.stripScreenSpaceIrradiance = true; // This is currently not exposed to the user nor used by anything internal.
+ spd.stripReflectionProbeBlending = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.ReflectionProbeBlending);
+ spd.stripReflectionProbeBoxProjection = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.ReflectionProbeBoxProjection);
+ spd.stripReflectionProbeAtlas = !IsFeatureEnabled(shaderFeatures, ShaderFeatures.ReflectionProbeAtlas);
+#if SURFACE_CACHE
+ spd.stripScreenSpaceIrradiance = stripScreenSpaceIrradiance;
+#else
+ spd.stripScreenSpaceIrradiance = true;
+#endif
// Rendering Modes
// Check if only Deferred is being used
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShaderGraphTerrainLitGUI.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShaderGraphTerrainLitGUI.cs
new file mode 100644
index 00000000000..b4d119861d8
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShaderGraphTerrainLitGUI.cs
@@ -0,0 +1,27 @@
+using UnityEngine;
+
+namespace UnityEditor.Rendering.Universal
+{
+ internal class ShaderGraphTerrainLitGUI : TerrainLitShaderGUI
+ {
+ protected override uint materialFilter => (uint)(Expandable.SurfaceOptions | Expandable.SurfaceInputs);
+ private MaterialProperty[] properties;
+
+ public override void FindProperties(MaterialProperty[] properties)
+ {
+ this.properties = properties;
+
+ var material = materialEditor?.target as Material;
+ if (material == null)
+ return;
+
+ base.FindProperties(properties);
+ FindMaterialProperties(properties);
+ }
+
+ public override void DrawSurfaceInputs(Material material)
+ {
+ DrawShaderGraphProperties(material, properties);
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShaderGraphTerrainLitGUI.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShaderGraphTerrainLitGUI.cs.meta
new file mode 100644
index 00000000000..9f1b92d72a7
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/ShaderGraphTerrainLitGUI.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: a48458ea708872f44bf79d4c9e33ff07
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/TerrainLitShaderGUI.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/TerrainLitShaderGUI.cs
index 4b670041501..b23d377b996 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/TerrainLitShaderGUI.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGUI/TerrainLitShaderGUI.cs
@@ -1,12 +1,11 @@
using System;
using UnityEngine;
using UnityEngine.Rendering;
-using UnityEditor;
using UnityEngine.Experimental.Rendering;
namespace UnityEditor.Rendering.Universal
{
- internal class TerrainLitShaderGUI : UnityEditor.ShaderGUI, ITerrainLayerCustomUI
+ internal class TerrainLitShaderGUI : BaseShaderGUI, ITerrainLayerCustomUI
{
private class StylesLayer
{
@@ -40,8 +39,11 @@ private class StylesLayer
static StylesLayer s_Styles = null;
private static StylesLayer styles { get { if (s_Styles == null) s_Styles = new StylesLayer(); return s_Styles; } }
+ protected override uint materialFilter => (uint)Expandable.SurfaceOptions;
+
public TerrainLitShaderGUI()
{
+
}
// Height blend params
@@ -98,12 +100,16 @@ static public bool TextureHasAlpha(Texture2D inTex)
return false;
}
- public override void OnGUI(MaterialEditor materialEditorIn, MaterialProperty[] properties)
+ public override void FindProperties(MaterialProperty[] properties)
{
- if (materialEditorIn == null)
- throw new ArgumentNullException("materialEditorIn");
-
+ base.FindProperties(properties);
FindMaterialProperties(properties);
+ }
+
+ public override void DrawSurfaceOptions(Material material)
+ {
+ if (materialEditor == null)
+ throw new ArgumentNullException("materialEditor");
bool optionsChanged = false;
EditorGUI.BeginChangeCheck();
@@ -111,18 +117,16 @@ public override void OnGUI(MaterialEditor materialEditorIn, MaterialProperty[] p
if (enableHeightBlend != null)
{
EditorGUI.indentLevel++;
- materialEditorIn.ShaderProperty(enableHeightBlend, styles.enableHeightBlend);
+ materialEditor.ShaderProperty(enableHeightBlend, styles.enableHeightBlend);
if (enableHeightBlend.floatValue > 0)
{
EditorGUI.indentLevel++;
EditorGUILayout.HelpBox(styles.warningHeightBasedBlending.text, MessageType.Info);
- materialEditorIn.ShaderProperty(heightTransition, styles.heightTransition);
+ materialEditor.ShaderProperty(heightTransition, styles.heightTransition);
EditorGUI.indentLevel--;
}
EditorGUI.indentLevel--;
}
-
- EditorGUILayout.Space();
}
if (EditorGUI.EndChangeCheck())
{
@@ -137,21 +141,21 @@ public override void OnGUI(MaterialEditor materialEditorIn, MaterialProperty[] p
{
EditorGUI.indentLevel++;
EditorGUI.BeginChangeCheck();
- materialEditorIn.ShaderProperty(enableInstancedPerPixelNormal, styles.enableInstancedPerPixelNormal);
+ materialEditor.ShaderProperty(enableInstancedPerPixelNormal, styles.enableInstancedPerPixelNormal);
enablePerPixelNormalChanged = EditorGUI.EndChangeCheck();
EditorGUI.indentLevel--;
}
if (optionsChanged || enablePerPixelNormalChanged)
{
- foreach (var obj in materialEditorIn.targets)
+ foreach (var obj in materialEditor.targets)
{
SetupMaterialKeywords((Material)obj);
}
}
// We should always do this call at the end
- materialEditorIn.serializedObject.ApplyModifiedProperties();
+ materialEditor.serializedObject.ApplyModifiedProperties();
}
bool ITerrainLayerCustomUI.OnTerrainLayerGUI(TerrainLayer terrainLayer, Terrain terrain)
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateTerrainShaderGraph.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateTerrainShaderGraph.cs
new file mode 100644
index 00000000000..0051a761d32
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateTerrainShaderGraph.cs
@@ -0,0 +1,29 @@
+using System;
+using UnityEditor.ShaderGraph;
+using UnityEngine.Rendering;
+
+namespace UnityEditor.Rendering.Universal.ShaderGraph
+{
+ internal static class CreateTerrainShaderGraph
+ {
+ [MenuItem("Assets/Create/Shader Graph/URP/Terrain Lit Shader Graph", priority = CoreUtils.Sections.section4 + CoreUtils.Priorities.assetsCreateShaderMenuPriority + 2)]
+ public static void CreateTerrainGraph()
+ {
+ var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget));
+ target.TrySetActiveSubTarget(typeof(UniversalTerrainLitSubTarget));
+
+ var blockDescriptors = new[]
+ {
+ BlockFields.VertexDescription.Position,
+ BlockFields.SurfaceDescription.BaseColor,
+ BlockFields.SurfaceDescription.NormalTS,
+ BlockFields.SurfaceDescription.Metallic,
+ BlockFields.SurfaceDescription.Emission,
+ BlockFields.SurfaceDescription.Smoothness,
+ BlockFields.SurfaceDescription.Occlusion,
+ };
+
+ GraphUtil.CreateNewGraphWithOutputs(new[] {target}, blockDescriptors);
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateTerrainShaderGraph.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateTerrainShaderGraph.cs.meta
new file mode 100644
index 00000000000..c81df0f4948
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateTerrainShaderGraph.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: fb4cc07de95d2c14bbd0d0a735e84eb0
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUITKShaderGraph.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUITKShaderGraph.cs
new file mode 100644
index 00000000000..98069cc3ba9
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUITKShaderGraph.cs
@@ -0,0 +1,25 @@
+using System;
+using UnityEditor.ShaderGraph;
+using UnityEngine.Rendering;
+using UnityEditor.Rendering.Fullscreen.ShaderGraph;
+
+namespace UnityEditor.Rendering.Universal.ShaderGraph
+{
+ static class CreateUITKShaderGraph
+ {
+ [MenuItem("Assets/Create/Shader Graph/URP/UI Shader Graph", priority = CoreUtils.Sections.section5 + CoreUtils.Priorities.assetsCreateShaderMenuPriority)]
+ public static void CreateUITKGraph()
+ {
+ var target = (UniversalTarget)Activator.CreateInstance(typeof(UniversalTarget));
+ target.TrySetActiveSubTarget(typeof(UniversalUISubTarget));
+
+ var blockDescriptors = new[]
+ {
+ BlockFields.SurfaceDescription.BaseColor,
+ BlockFields.SurfaceDescription.Alpha,
+ };
+
+ GraphUtil.CreateNewGraphWithOutputs(new[] { target }, blockDescriptors);
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUITKShaderGraph.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUITKShaderGraph.cs.meta
new file mode 100644
index 00000000000..ac1b3934d9f
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/AssetCallbacks/CreateUITKShaderGraph.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 6869d97760ee37741bce9a471f54c720
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/GraphTemplates/2D/0_2D Sprite Lit.shadergraph b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/GraphTemplates/2D/0_2D Sprite Lit.shadergraph
index 467144b8b30..d90f3b5bb66 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/GraphTemplates/2D/0_2D Sprite Lit.shadergraph
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/GraphTemplates/2D/0_2D Sprite Lit.shadergraph
@@ -46,9 +46,6 @@
{
"m_Id": "28e02ff88fbb4ffa899ba50e51a556da"
},
- {
- "m_Id": "ec7034ed2e654c1a9c69351f2427ec1b"
- },
{
"m_Id": "f4b179e9fe7a4ed0a70351e482563166"
},
@@ -343,9 +340,6 @@
{
"m_Id": "2437c384dfcf4078bc8e52d64b24b85b"
},
- {
- "m_Id": "ec7034ed2e654c1a9c69351f2427ec1b"
- },
{
"m_Id": "2f05b7d671124aa5b380d30ab309dbf9"
},
@@ -943,6 +937,9 @@
"m_Guid": {
"m_GuidSerialized": "f5a728a4-369c-45ed-a11d-be58ca753d7a"
},
+ "promotedFromAssetID": "",
+ "promotedFromCategoryName": "",
+ "promotedOrdering": -1,
"m_Name": "Normal Map",
"m_DefaultRefNameVersion": 1,
"m_RefNameGeneratedByDisplayName": "Normal Map",
@@ -956,6 +953,8 @@
"overrideHLSLDeclaration": false,
"hlslDeclarationOverride": 0,
"m_Hidden": false,
+ "m_PerRendererData": false,
+ "m_customAttributes": [],
"m_Value": {
"m_SerializedTexture": "",
"m_Guid": ""
@@ -1020,6 +1019,9 @@
"m_Guid": {
"m_GuidSerialized": "ed78179f-21ae-469b-b0ad-98973dd70676"
},
+ "promotedFromAssetID": "",
+ "promotedFromCategoryName": "",
+ "promotedOrdering": -1,
"m_Name": "Mask Map",
"m_DefaultRefNameVersion": 1,
"m_RefNameGeneratedByDisplayName": "Mask Map",
@@ -1033,6 +1035,8 @@
"overrideHLSLDeclaration": false,
"hlslDeclarationOverride": 0,
"m_Hidden": false,
+ "m_PerRendererData": false,
+ "m_customAttributes": [],
"m_Value": {
"m_SerializedTexture": "",
"m_Guid": ""
@@ -1291,6 +1295,9 @@
"m_Guid": {
"m_GuidSerialized": "b5705445-c2f9-4869-9449-ab518dcbfd7e"
},
+ "promotedFromAssetID": "",
+ "promotedFromCategoryName": "",
+ "promotedOrdering": -1,
"m_Name": "Use Color",
"m_DefaultRefNameVersion": 1,
"m_RefNameGeneratedByDisplayName": "Use Color",
@@ -2012,21 +2019,6 @@
"m_Space": 0
}
-{
- "m_SGVersion": 0,
- "m_Type": "UnityEditor.ShaderGraph.Vector1MaterialSlot",
- "m_ObjectId": "e02d79117d4540c39fa0b51b9507eb61",
- "m_Id": 0,
- "m_DisplayName": "Alpha Clip Threshold",
- "m_SlotType": 0,
- "m_Hidden": false,
- "m_ShaderOutputName": "AlphaClipThreshold",
- "m_StageCapability": 2,
- "m_Value": 0.00800000037997961,
- "m_DefaultValue": 0.5,
- "m_Labels": []
-}
-
{
"m_SGVersion": 0,
"m_Type": "UnityEditor.ShaderGraph.Texture2DInputMaterialSlot",
@@ -2128,40 +2120,6 @@
"m_Labels": []
}
-{
- "m_SGVersion": 0,
- "m_Type": "UnityEditor.ShaderGraph.BlockNode",
- "m_ObjectId": "ec7034ed2e654c1a9c69351f2427ec1b",
- "m_Group": {
- "m_Id": ""
- },
- "m_Name": "SurfaceDescription.AlphaClipThreshold",
- "m_DrawState": {
- "m_Expanded": true,
- "m_Position": {
- "serializedVersion": "2",
- "x": 0.0,
- "y": 0.0,
- "width": 0.0,
- "height": 0.0
- }
- },
- "m_Slots": [
- {
- "m_Id": "e02d79117d4540c39fa0b51b9507eb61"
- }
- ],
- "synonyms": [],
- "m_Precision": 0,
- "m_PreviewExpanded": true,
- "m_DismissedVersion": 0,
- "m_PreviewMode": 0,
- "m_CustomColors": {
- "m_SerializableColors": []
- },
- "m_SerializedDescriptor": "SurfaceDescription.AlphaClipThreshold"
-}
-
{
"m_SGVersion": 0,
"m_Type": "UnityEditor.ShaderGraph.Vector4MaterialSlot",
@@ -2343,6 +2301,9 @@
"m_Guid": {
"m_GuidSerialized": "4747fe67-4822-4c0c-893c-67cf72333a1f"
},
+ "promotedFromAssetID": "",
+ "promotedFromCategoryName": "",
+ "promotedOrdering": -1,
"m_Name": "Color Map",
"m_DefaultRefNameVersion": 1,
"m_RefNameGeneratedByDisplayName": "Color Map",
@@ -2356,6 +2317,8 @@
"overrideHLSLDeclaration": false,
"hlslDeclarationOverride": 0,
"m_Hidden": false,
+ "m_PerRendererData": false,
+ "m_customAttributes": [],
"m_Value": {
"m_SerializedTexture": "",
"m_Guid": ""
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/GraphTemplates/2D/1_2D Sprite Unlit.shadergraph b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/GraphTemplates/2D/1_2D Sprite Unlit.shadergraph
index 637f3111bf4..7dc941b3ebd 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/GraphTemplates/2D/1_2D Sprite Unlit.shadergraph
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/GraphTemplates/2D/1_2D Sprite Unlit.shadergraph
@@ -40,9 +40,6 @@
{
"m_Id": "28e02ff88fbb4ffa899ba50e51a556da"
},
- {
- "m_Id": "ec7034ed2e654c1a9c69351f2427ec1b"
- },
{
"m_Id": "f4b179e9fe7a4ed0a70351e482563166"
},
@@ -234,9 +231,6 @@
},
{
"m_Id": "2437c384dfcf4078bc8e52d64b24b85b"
- },
- {
- "m_Id": "ec7034ed2e654c1a9c69351f2427ec1b"
}
]
},
@@ -856,6 +850,9 @@
"m_Guid": {
"m_GuidSerialized": "b5705445-c2f9-4869-9449-ab518dcbfd7e"
},
+ "promotedFromAssetID": "",
+ "promotedFromCategoryName": "",
+ "promotedOrdering": -1,
"m_Name": "Use Color",
"m_DefaultRefNameVersion": 1,
"m_RefNameGeneratedByDisplayName": "Use Color",
@@ -1299,21 +1296,6 @@
"m_Space": 0
}
-{
- "m_SGVersion": 0,
- "m_Type": "UnityEditor.ShaderGraph.Vector1MaterialSlot",
- "m_ObjectId": "e02d79117d4540c39fa0b51b9507eb61",
- "m_Id": 0,
- "m_DisplayName": "Alpha Clip Threshold",
- "m_SlotType": 0,
- "m_Hidden": false,
- "m_ShaderOutputName": "AlphaClipThreshold",
- "m_StageCapability": 2,
- "m_Value": 0.00800000037997961,
- "m_DefaultValue": 0.5,
- "m_Labels": []
-}
-
{
"m_SGVersion": 0,
"m_Type": "UnityEditor.ShaderGraph.DynamicVectorMaterialSlot",
@@ -1372,40 +1354,6 @@
"m_SerializedDescriptor": "VertexDescription.Tangent"
}
-{
- "m_SGVersion": 0,
- "m_Type": "UnityEditor.ShaderGraph.BlockNode",
- "m_ObjectId": "ec7034ed2e654c1a9c69351f2427ec1b",
- "m_Group": {
- "m_Id": ""
- },
- "m_Name": "SurfaceDescription.AlphaClipThreshold",
- "m_DrawState": {
- "m_Expanded": true,
- "m_Position": {
- "serializedVersion": "2",
- "x": 0.0,
- "y": 0.0,
- "width": 0.0,
- "height": 0.0
- }
- },
- "m_Slots": [
- {
- "m_Id": "e02d79117d4540c39fa0b51b9507eb61"
- }
- ],
- "synonyms": [],
- "m_Precision": 0,
- "m_PreviewExpanded": true,
- "m_DismissedVersion": 0,
- "m_PreviewMode": 0,
- "m_CustomColors": {
- "m_SerializableColors": []
- },
- "m_SerializedDescriptor": "SurfaceDescription.AlphaClipThreshold"
-}
-
{
"m_SGVersion": 0,
"m_Type": "UnityEditor.ShaderGraph.CategoryData",
@@ -1550,6 +1498,9 @@
"m_Guid": {
"m_GuidSerialized": "4747fe67-4822-4c0c-893c-67cf72333a1f"
},
+ "promotedFromAssetID": "",
+ "promotedFromCategoryName": "",
+ "promotedOrdering": -1,
"m_Name": "Sprite Texture",
"m_DefaultRefNameVersion": 1,
"m_RefNameGeneratedByDisplayName": "Sprite Texture",
@@ -1563,6 +1514,8 @@
"overrideHLSLDeclaration": false,
"hlslDeclarationOverride": 0,
"m_Hidden": false,
+ "m_PerRendererData": false,
+ "m_customAttributes": [],
"m_Value": {
"m_SerializedTexture": "",
"m_Guid": ""
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl
index cc1a37cc641..aa5581d95b5 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl
@@ -16,7 +16,7 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET
UNITY_SETUP_INSTANCE_ID(unpacked);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
- #if _ALPHATEST_ON
+ #if defined(_ALPHATEST_ON)
clip(surfaceDescription.Alpha - surfaceDescription.AlphaClipThreshold);
#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SelectionPickingPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SelectionPickingPass.hlsl
index ec77f0b98d6..1d2fc0c0a37 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SelectionPickingPass.hlsl
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SelectionPickingPass.hlsl
@@ -17,7 +17,7 @@ half4 frag(PackedVaryings packedInput) : SV_TARGET
UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
- #if _ALPHATEST_ON
+ #if (!defined(UNIVERSAL_TERRAIN_ENABLED) && defined(_ALPHATEST_ON)) || defined(_TERRAIN_SG_ALPHA_CLIP)
// This isn't defined in the sprite passes. It looks like the built-in legacy shader will use this as it's default constant
float alphaClipThreshold = 0.01f;
#if ALPHA_CLIP_THRESHOLD
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain.meta
new file mode 100644
index 00000000000..a69dbed34be
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: f4e1f16cd720fd149b53725287d528da
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/DepthNormalsOnlyPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/DepthNormalsOnlyPass.hlsl
new file mode 100644
index 00000000000..222e3d2fb19
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/DepthNormalsOnlyPass.hlsl
@@ -0,0 +1,37 @@
+#ifndef SG_TERRAIN_DEPTH_NORMALS_PASS_INCLUDED
+#define SG_TERRAIN_DEPTH_NORMALS_PASS_INCLUDED
+
+#include "TerrainVert.hlsl"
+
+void frag(PackedVaryings packedInput,
+ out half4 color : SV_Target0
+#ifdef _WRITE_RENDERING_LAYERS
+ , out uint outRenderingLayers : SV_Target1
+#endif
+)
+{
+ Varyings unpacked = UnpackVaryings(packedInput);
+ UNITY_SETUP_INSTANCE_ID(unpacked);
+ UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
+
+#ifdef ENABLE_TERRAIN_PERPIXEL_NORMAL
+ float2 sampleCoords = (unpacked.texCoord0.xy / _TerrainHeightmapRecipSize.zw + 0.5f) * _TerrainHeightmapRecipSize.xy;
+ float3 normalOS = SAMPLE_TEXTURE2D(_TerrainNormalmapTexture, sampler_TerrainNormalmapTexture, sampleCoords).rgb;
+ normalOS = normalize(normalOS * 2.0 - 1.0);
+ unpacked.normalWS = TransformObjectToWorldNormal(normalOS);
+#endif
+
+ SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
+
+#ifdef _TERRAIN_SG_ALPHA_CLIP
+ half alpha = AlphaDiscard(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
+#endif
+
+ half3 normalWS = GetTerrainNormalWS(unpacked, surfaceDescription);
+#ifdef _WRITE_RENDERING_LAYERS
+ outRenderingLayers = EncodeMeshRenderingLayer();
+#endif
+ color = half4(NormalizeNormalPerPixel(normalWS), 0.0);
+}
+
+#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/DepthNormalsOnlyPass.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/DepthNormalsOnlyPass.hlsl.meta
new file mode 100644
index 00000000000..9efa43adfe5
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/DepthNormalsOnlyPass.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 78121747aa974234f94f7fda667dbbe1
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl
new file mode 100644
index 00000000000..a0297185349
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl
@@ -0,0 +1,113 @@
+#ifndef SG_TERRAIN_PBRFORWARDPASS_INC
+#define SG_TERRAIN_PBRFORWARDPASS_INC
+
+#include "TerrainVert.hlsl"
+
+void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData)
+{
+ inputData = (InputData)0;
+
+ inputData.positionWS = input.positionWS;
+
+ half3 SH = 0.0h;
+ CalculateTerrainNormalWS(input, surfaceDescription, inputData);
+
+ #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
+ inputData.shadowCoord = input.shadowCoord;
+ #elif defined(MAIN_LIGHT_CALCULATE_SHADOWS)
+ inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS);
+ #else
+ inputData.shadowCoord = float4(0, 0, 0, 0);
+ #endif
+
+ inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x);
+ inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
+
+#if defined(DYNAMICLIGHTMAP_ON)
+ inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV.xy, SH, inputData.normalWS);
+#else
+ inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, SH, inputData.normalWS);
+#endif
+ inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
+ inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
+
+ #if defined(DEBUG_DISPLAY)
+ #if defined(DYNAMICLIGHTMAP_ON)
+ inputData.dynamicLightmapUV = input.dynamicLightmapUV.xy;
+ #endif
+ #if defined(LIGHTMAP_ON)
+ inputData.staticLightmapUV = input.staticLightmapUV;
+ #else
+ inputData.vertexSH = input.sh;
+ #endif
+ #endif
+}
+
+void frag(PackedVaryings packedInput,
+ out half4 color : SV_Target0
+#ifdef _WRITE_RENDERING_LAYERS
+ , out uint outRenderingLayers : SV_Target1
+#endif
+ )
+{
+ Varyings unpacked = UnpackVaryings(packedInput);
+ UNITY_SETUP_INSTANCE_ID(unpacked);
+ UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
+#ifdef ENABLE_TERRAIN_PERPIXEL_NORMAL
+ float2 sampleCoords = (unpacked.texCoord0.xy / _TerrainHeightmapRecipSize.zw + 0.5f) * _TerrainHeightmapRecipSize.xy;
+ float3 normalOS = SAMPLE_TEXTURE2D(_TerrainNormalmapTexture, sampler_TerrainNormalmapTexture, sampleCoords).rgb;
+ normalOS = normalize(normalOS * 2.0 - 1.0);
+
+ unpacked.normalWS = TransformObjectToWorldNormal(normalOS);
+
+ #ifdef VARYINGS_NEED_TANGENT_WS
+ float4 tangentOS = ConstructTerrainTangent(normalOS, float3(0.0, 0.0, 1.0));
+ unpacked.tangentWS = float4(TransformObjectToWorldNormal(normalize(tangentOS.xyz)), tangentOS.w);
+ #endif
+#endif
+
+ SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
+ #ifdef _TERRAIN_SG_ALPHA_CLIP
+ AlphaDiscard(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
+ #endif
+
+ InputData inputData;
+ InitializeInputData(unpacked, surfaceDescription, inputData);
+ SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0.xy);
+
+ float3 specular = 0;
+ float metallic = surfaceDescription.Metallic;
+
+ half3 normalTS = half3(0, 0, 0);
+ #if defined(_NORMALMAP) && defined(_NORMAL_DROPOFF_TS)
+ normalTS = surfaceDescription.NormalTS;
+ #endif
+
+ SurfaceData surface;
+ surface.albedo = surfaceDescription.BaseColor;
+ surface.metallic = saturate(metallic);
+ surface.specular = specular;
+ surface.smoothness = saturate(surfaceDescription.Smoothness);
+ surface.occlusion = surfaceDescription.Occlusion;
+ surface.emission = surfaceDescription.Emission;
+ surface.alpha = 1.0;
+ surface.normalTS = normalTS;
+ surface.clearCoatMask = 0;
+ surface.clearCoatSmoothness = 1;
+
+ surface.albedo = AlphaModulate(surface.albedo, surface.alpha);
+
+#ifdef _DBUFFER
+ ApplyDecalToSurfaceData(unpacked.positionCS, surface, inputData);
+#endif
+
+ color = UniversalFragmentPBR(inputData, surface);
+ SplatmapFinalColor(color, inputData.fogCoord);
+
+#ifdef _WRITE_RENDERING_LAYERS
+ outRenderingLayers = EncodeMeshRenderingLayer();
+#endif
+ color = half4(color.rgb, 1.0h);
+}
+
+#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl.meta
new file mode 100644
index 00000000000..d63f2b13c3c
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 713d6952dfc661f44b856f1bfc9a4880
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl
new file mode 100644
index 00000000000..8d6f188373b
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl
@@ -0,0 +1,127 @@
+#ifndef SG_TERRAIN_PBRGBUFFERPASS_INC
+#define SG_TERRAIN_PBRGBUFFERPASS_INC
+
+#include "TerrainVert.hlsl"
+
+void InitializeInputData(Varyings input, SurfaceDescription surfaceDescription, out InputData inputData)
+{
+ inputData = (InputData)0;
+
+ inputData.positionWS = input.positionWS;
+
+ half3 SH = 0.0h;
+ CalculateTerrainNormalWS(input, surfaceDescription, inputData);
+
+ #if defined(REQUIRES_VERTEX_SHADOW_COORD_INTERPOLATOR)
+ inputData.shadowCoord = input.shadowCoord;
+ #elif defined(MAIN_LIGHT_CALCULATE_SHADOWS)
+ inputData.shadowCoord = TransformWorldToShadowCoord(inputData.positionWS);
+ #else
+ inputData.shadowCoord = float4(0, 0, 0, 0);
+ #endif
+
+ inputData.fogCoord = InitializeInputDataFog(float4(input.positionWS, 1.0), input.fogFactorAndVertexLight.x);
+ inputData.vertexLighting = input.fogFactorAndVertexLight.yzw;
+
+#if defined(DYNAMICLIGHTMAP_ON)
+ inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, input.dynamicLightmapUV.xy, SH, inputData.normalWS);
+#else
+ inputData.bakedGI = SAMPLE_GI(input.staticLightmapUV, SH, inputData.normalWS);
+#endif
+ inputData.normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(input.positionCS);
+ inputData.shadowMask = SAMPLE_SHADOWMASK(input.staticLightmapUV);
+
+ #if defined(DEBUG_DISPLAY)
+ #if defined(DYNAMICLIGHTMAP_ON)
+ inputData.dynamicLightmapUV = input.dynamicLightmapUV.xy;
+ #endif
+ #if defined(LIGHTMAP_ON)
+ inputData.staticLightmapUV = input.staticLightmapUV;
+ #else
+ inputData.vertexSH = input.sh;
+ #endif
+ #endif
+}
+
+GBufferFragOutput frag(PackedVaryings packedInput)
+{
+ Varyings unpacked = UnpackVaryings(packedInput);
+ UNITY_SETUP_INSTANCE_ID(unpacked);
+ UNITY_SETUP_STEREO_EYE_INDEX_POST_VERTEX(unpacked);
+
+
+#ifdef ENABLE_TERRAIN_PERPIXEL_NORMAL
+ float2 sampleCoords = (unpacked.texCoord0.xy / _TerrainHeightmapRecipSize.zw + 0.5f) * _TerrainHeightmapRecipSize.xy;
+ float3 normalOS = SAMPLE_TEXTURE2D(_TerrainNormalmapTexture, sampler_TerrainNormalmapTexture, sampleCoords).rgb;
+ normalOS = normalize(normalOS * 2.0 - 1.0);
+
+ unpacked.normalWS = TransformObjectToWorldNormal(normalOS);
+
+ #ifdef VARYINGS_NEED_TANGENT_WS
+ float4 tangentOS = ConstructTerrainTangent(normalOS, float3(0.0, 0.0, 1.0));
+ unpacked.tangentWS = float4(TransformObjectToWorldNormal(normalize(tangentOS.xyz)), tangentOS.w);
+ #endif
+#endif
+
+ SurfaceDescription surfaceDescription = BuildSurfaceDescription(unpacked);
+#ifdef _TERRAIN_SG_ALPHA_CLIP
+ half alpha = AlphaDiscard(surfaceDescription.Alpha, surfaceDescription.AlphaClipThreshold);
+#else
+ half alpha = 1.0;
+#endif
+
+ InputData inputData;
+ InitializeInputData(unpacked, surfaceDescription, inputData);
+ SETUP_DEBUG_TEXTURE_DATA(inputData, unpacked.texCoord0);
+
+ float3 specular = 0;
+ float metallic = surfaceDescription.Metallic;
+
+ half3 normalTS = half3(0, 0, 0);
+ #if defined(_NORMALMAP) && defined(_NORMAL_DROPOFF_TS)
+ normalTS = surfaceDescription.NormalTS;
+ #endif
+
+ SurfaceData surface;
+ surface.albedo = surfaceDescription.BaseColor;
+ surface.metallic = saturate(metallic);
+ surface.specular = specular;
+ surface.smoothness = saturate(surfaceDescription.Smoothness),
+ surface.occlusion = surfaceDescription.Occlusion,
+ surface.emission = surfaceDescription.Emission,
+ surface.alpha = 1.0;
+ surface.normalTS = normalTS;
+ surface.clearCoatMask = 0;
+ surface.clearCoatSmoothness = 1;
+
+ surface.albedo = AlphaModulate(surface.albedo, surface.alpha);
+
+#ifdef _DBUFFER
+ ApplyDecalToSurfaceData(unpacked.positionCS, surface, inputData);
+#endif
+
+ BRDFData brdfData;
+ InitializeBRDFData(surfaceDescription.BaseColor, metallic, specular, surfaceDescription.Smoothness, alpha, brdfData);
+
+ // Baked lighting.
+ half4 color;
+ Light mainLight = GetMainLight(inputData.shadowCoord, inputData.positionWS, inputData.shadowMask);
+ MixRealtimeAndBakedGI(mainLight, inputData.normalWS, inputData.bakedGI, inputData.shadowMask);
+ color.rgb = GlobalIllumination(brdfData, inputData.bakedGI, surfaceDescription.Occlusion, inputData.positionWS, inputData.normalWS, inputData.viewDirectionWS);
+ color.a = alpha;
+ SplatmapFinalColor(color, inputData.fogCoord);
+
+ // Dynamic lighting: emulate SplatmapFinalColor() by scaling gbuffer material properties. This will not give the same results
+ // as forward renderer because we apply blending pre-lighting instead of post-lighting.
+ // Blending of smoothness and normals is also not correct but close enough?
+ brdfData.albedo.rgb *= alpha;
+ brdfData.diffuse.rgb *= alpha;
+ brdfData.specular.rgb *= alpha;
+ brdfData.reflectivity *= alpha;
+ inputData.normalWS = inputData.normalWS * alpha;
+ surfaceDescription.Smoothness *= alpha;
+
+ return PackGBuffersBRDFData(brdfData, inputData, surfaceDescription.Smoothness, color.rgb, surfaceDescription.Occlusion);
+}
+
+#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl.meta
new file mode 100644
index 00000000000..e389e329d74
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 6970aba7f3c314f4fa5d5b93188b6de3
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/TerrainVert.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/TerrainVert.hlsl
new file mode 100644
index 00000000000..de41824134b
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/TerrainVert.hlsl
@@ -0,0 +1,13 @@
+#ifndef SG_TERRAIN_VERTEX_INC
+#define SG_TERRAIN_VERTEX_INC
+
+PackedVaryings vert(Attributes input)
+{
+ Varyings output = (Varyings)0;
+ output = BuildVaryings(input);
+ PackedVaryings packedOutput = (PackedVaryings)0;
+ packedOutput = PackVaryings(output);
+ return packedOutput;
+}
+
+#endif
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/TerrainVert.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/TerrainVert.hlsl.meta
new file mode 100644
index 00000000000..cdd26af8688
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/TerrainVert.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 3a737aafdc720423fac5e90590a0f05f
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UITKPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UITKPass.hlsl
new file mode 100644
index 00000000000..46bd4b9038f
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UITKPass.hlsl
@@ -0,0 +1,61 @@
+#if SHADERPASS != SHADERPASS_CUSTOM_UI
+#error SHADERPASS_CUSTOM_UI_is_not_correctly_defined
+#endif
+
+
+#define UIE_NOINTERPOLATION nointerpolation
+
+PackedVaryings uie_custom_vert(Attributes input)
+{
+ appdata_t uieInput = (appdata_t)0;
+ uieInput.vertex = float4(input.positionOS, 1.0f);
+ uieInput.color = input.color;
+ uieInput.uv = input.uv0;
+ uieInput.xformClipPages = input.uv1;
+ uieInput.ids = input.uv2;
+ uieInput.flags = input.uv3;
+ uieInput.opacityColorPages = input.uv4;
+ uieInput.settingIndex = input.uv5;
+ uieInput.circle = input.uv6;
+ uieInput.textureId = input.uv7.x;
+
+
+ v2f uieOutput = uie_std_vert(uieInput);
+
+ Varyings varyings = (Varyings)0;
+ varyings.positionCS = uieOutput.pos;
+ varyings.color = uieOutput.color;
+ varyings.texCoord0 = uieOutput.uvClip;
+ varyings.texCoord1 = uieOutput.typeTexSettings;
+ varyings.texCoord3 = float4(uieOutput.textCoreLoc.x, uieOutput.textCoreLoc.y, input.uv0.z, input.uv0.w); // Layout uv in z, w
+ varyings.texCoord4 = uieOutput.circle;
+
+ PackedVaryings packedOutput = PackVaryings(varyings);
+ return packedOutput;
+}
+
+UIE_FRAG_T uie_custom_frag(PackedVaryings packedInput) : SV_Target
+{
+ Varyings varyings = UnpackVaryings(packedInput);
+ SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(varyings);
+
+ SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
+
+ // TODO: In the future, we should try to use surfaceDescription.coverage instead of computing coverage outside
+ // of the branches like we do here.
+ half renderType = round(surfaceDescriptionInputs.typeTexSettings.x);
+ half isArc = surfaceDescriptionInputs.typeTexSettings.w;
+ float2 outer = surfaceDescriptionInputs.circle.xy;
+ float2 inner = surfaceDescriptionInputs.circle.zw;
+ float coverage = uie_sg_compute_aa_coverage(renderType, isArc, outer, inner);
+
+ coverage *= uie_fragment_clip(surfaceDescriptionInputs.uvClip.zw);
+
+ // Clip fragments when coverage is close to 0 (< 1/256 here).
+ // This will write proper masks values in the stencil buffer.
+ clip(coverage - 0.003f);
+
+ surfaceDescription.Alpha *= coverage;
+
+ return float4(surfaceDescription.BaseColor, surfaceDescription.Alpha);
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UITKPass.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UITKPass.hlsl.meta
new file mode 100644
index 00000000000..43280db9d38
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UITKPass.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 4f183ca0bce4b844b8b2b26d1a18159c
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl
index 8b684185df8..83f4bd5c0c9 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl
@@ -66,7 +66,7 @@ void frag(
surfaceDescription.BaseColor = AlphaModulate(surfaceDescription.BaseColor, alpha);
#endif
-#if defined(_DBUFFER)
+#if defined(_DBUFFER) && defined(UNLIT_DEFAULT_DECAL_BLENDING)
ApplyDecalToBaseColor(unpacked.positionCS, surfaceDescription.BaseColor);
#endif
@@ -81,7 +81,7 @@ void frag(
half4 finalColor = UniversalFragmentUnlit(inputData, surfaceDescription.BaseColor, alpha);
finalColor.a = OutputAlpha(finalColor.a, isTransparent);
- #if defined(_SCREEN_SPACE_OCCLUSION) && !defined(_SURFACE_TYPE_TRANSPARENT)
+ #if defined(_SCREEN_SPACE_OCCLUSION) && !defined(_SURFACE_TYPE_TRANSPARENT) && defined(UNLIT_DEFAULT_SSAO)
float2 normalizedScreenSpaceUV = GetNormalizedScreenSpaceUV(unpacked.positionCS);
AmbientOcclusionFactor aoFactor = GetScreenSpaceAmbientOcclusion(normalizedScreenSpaceUV);
finalColor.rgb *= aoFactor.directAmbientOcclusion;
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl
index c6b58cd352c..488fab541d0 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl
@@ -109,6 +109,10 @@ Varyings BuildVaryings(Attributes input
{
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(output);
+ #ifdef UNIVERSAL_TERRAIN_ENABLED
+ TerrainVaryingGeneration(input, output);
+ #endif
+
#if defined(FEATURES_GRAPH_VERTEX)
#if defined(HAVE_VFX_MODIFICATION)
GraphProperties properties;
@@ -135,7 +139,7 @@ Varyings BuildVaryings(Attributes input
VertexPositionInputs vertexInput = GetVertexPositionInputs(input.positionOS.xyz);
// Returns the camera relative position (if enabled)
- float3 positionWS = TransformObjectToWorld(input.positionOS);
+ float3 positionWS = vertexInput.positionWS;
#if (SHADERPASS == SHADERPASS_MOTION_VECTORS)
motionVectorOutput.positionOS = input.positionOS;
@@ -155,11 +159,25 @@ Varyings BuildVaryings(Attributes input
// Required to compile ApplyVertexModification that doesn't use normal.
float3 normalWS = float3(0.0, 0.0, 0.0);
#endif
+ #ifdef UNIVERSAL_TERRAIN_ENABLED
+ #if defined(_NORMALMAP) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)
+ half3 viewDirWS = GetWorldSpaceNormalizeViewDir(positionWS);
+ float4 vertexTangent = float4(cross(float3(0.0, 0.0, 1.0), input.normalOS), 1.0);
+ VertexNormalInputs normalInput = GetVertexNormalInputs(input.normalOS, vertexTangent);
- #ifdef ATTRIBUTES_NEED_TANGENT
- float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
- #endif
+ output.normalViewDir = float4(normalInput.normalWS, viewDirWS.x);
+ output.tangentViewDir = float4(normalInput.tangentWS, viewDirWS.y);
+ output.bitangentViewDir = float4(normalInput.bitangentWS, viewDirWS.z);
+ float4 tangentWS = float4(normalInput.tangentWS, 1.0);
+ #else
+ float4 tangentWS = float4(1.0, 0.0, 0.0, 0.0);
+ #endif
+ #else
+ #ifdef ATTRIBUTES_NEED_TANGENT
+ float4 tangentWS = float4(TransformObjectToWorldDir(input.tangentOS.xyz), input.tangentOS.w);
+ #endif
+ #endif
// TODO: Change to inline ifdef
// Do vertex modification in camera relative space (if enabled)
#if defined(HAVE_VERTEX_MODIFICATION)
@@ -246,15 +264,23 @@ Varyings BuildVaryings(Attributes input
#ifdef VARYINGS_NEED_SCREENPOSITION
output.screenPosition = vertexInput.positionNDC;
#endif
-
- #if (SHADERPASS == SHADERPASS_FORWARD) || (SHADERPASS == SHADERPASS_GBUFFER)
- OUTPUT_LIGHTMAP_UV(input.uv1, unity_LightmapST, output.staticLightmapUV);
- #if defined(DYNAMICLIGHTMAP_ON)
- output.dynamicLightmapUV.xy = input.uv2.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
- #endif
- OUTPUT_SH4(vertexInput.positionWS, normalWS.xyz, GetWorldSpaceNormalizeViewDir(vertexInput.positionWS), output.sh, output.probeOcclusion);
+ #ifdef UNIVERSAL_TERRAIN_ENABLED
+ #if (SHADERPASS == SHADERPASS_FORWARD) || (SHADERPASS == SHADERPASS_GBUFFER)
+ OUTPUT_LIGHTMAP_UV(input.uv0, unity_LightmapST, output.staticLightmapUV);
+ #if defined(DYNAMICLIGHTMAP_ON)
+ output.dynamicLightmapUV.xy = input.uv0.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
+ #endif
+ OUTPUT_SH4(vertexInput.positionWS, normalWS.xyz, GetWorldSpaceNormalizeViewDir(vertexInput.positionWS), output.sh, output.probeOcclusion);
+ #endif
+ #else
+ #if (SHADERPASS == SHADERPASS_FORWARD) || (SHADERPASS == SHADERPASS_GBUFFER)
+ OUTPUT_LIGHTMAP_UV(input.uv1, unity_LightmapST, output.staticLightmapUV);
+ #if defined(DYNAMICLIGHTMAP_ON)
+ output.dynamicLightmapUV.xy = input.uv2.xy * unity_DynamicLightmapST.xy + unity_DynamicLightmapST.zw;
+ #endif
+ OUTPUT_SH4(vertexInput.positionWS, normalWS.xyz, GetWorldSpaceNormalizeViewDir(vertexInput.positionWS), output.sh, output.probeOcclusion);
+ #endif
#endif
-
#ifdef VARYINGS_NEED_FOG_AND_VERTEX_LIGHT
half fogFactor = 0;
#if !defined(_FOG_FRAGMENT)
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs
index db82831f0d6..63247006be5 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalLitSubTarget.cs
@@ -183,6 +183,8 @@ public override void CollectShaderProperties(PropertyCollector collector, Genera
collector.AddFloatProperty(Property.BlendModePreserveSpecular, blendModePreserveSpecular ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.SrcBlend, 1.0f); // always set by material inspector, ok to have incorrect values here
collector.AddFloatProperty(Property.DstBlend, 0.0f); // always set by material inspector, ok to have incorrect values here
+ collector.AddFloatProperty(Property.SrcBlendAlpha, 1.0f); // always set by material inspector, ok to have incorrect values here
+ collector.AddFloatProperty(Property.DstBlendAlpha, 0.0f); // always set by material inspector, ok to have incorrect values here
collector.AddToggleProperty(Property.ZWrite, (target.surfaceType == SurfaceType.Opaque));
collector.AddFloatProperty(Property.ZWriteControl, (float)target.zWriteControl);
collector.AddFloatProperty(Property.ZTest, (float)target.zTestMode); // ztest mode is designed to directly pass as ztest
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSixWaySubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSixWaySubTarget.cs
index ccf5c730eda..9f63cb7e2ca 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSixWaySubTarget.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSixWaySubTarget.cs
@@ -1,4 +1,4 @@
-using System;
+using System;
using UnityEngine;
using UnityEditor.ShaderGraph;
using UnityEngine.UIElements;
@@ -151,6 +151,8 @@ public override void CollectShaderProperties(PropertyCollector collector, Genera
collector.AddFloatProperty(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.SrcBlend, 1.0f); // always set by material inspector, ok to have incorrect values here
collector.AddFloatProperty(Property.DstBlend, 0.0f); // always set by material inspector, ok to have incorrect values here
+ collector.AddFloatProperty(Property.SrcBlendAlpha, 1.0f); // always set by material inspector, ok to have incorrect values here
+ collector.AddFloatProperty(Property.DstBlendAlpha, 0.0f); // always set by material inspector, ok to have incorrect values here
collector.AddToggleProperty(Property.ZWrite, (target.surfaceType == SurfaceType.Opaque));
collector.AddFloatProperty(Property.ZWriteControl, (float)target.zWriteControl);
collector.AddFloatProperty(Property.ZTest, (float)target.zTestMode); // ztest mode is designed to directly pass as ztest
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSubTarget.cs
index 3511f5a7c97..0f99214f30a 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSubTarget.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalSubTarget.cs
@@ -33,7 +33,6 @@ public void ConfigureContextData(VFXContext context, VFXTaskCompiledData data)
m_ContextVFX = context;
m_TaskDataVFX = data;
}
-
#endif
protected SubShaderDescriptor PostProcessSubShader(SubShaderDescriptor subShaderDescriptor)
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs
index a51042c73ec..09ec19c7a55 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTarget.cs
@@ -1,15 +1,17 @@
using System;
using System.Linq;
using System.Collections.Generic;
+using UnityEditor.Rendering.UITK.ShaderGraph;
+using UnityEditor.ShaderGraph;
+using UnityEditor.ShaderGraph.Internal;
+using UnityEditor.ShaderGraph.Legacy;
+using UnityEditor.ShaderGraph.Serialization;
+using UnityEditor.UIElements;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
+using UnityEngine.Rendering.VirtualTexturing;
using UnityEngine.UIElements;
-using UnityEditor.ShaderGraph;
-using UnityEditor.ShaderGraph.Internal;
-using UnityEditor.UIElements;
-using UnityEditor.ShaderGraph.Serialization;
-using UnityEditor.ShaderGraph.Legacy;
#if HAS_VFX_GRAPH
using UnityEditor.VFX;
#endif
@@ -112,6 +114,7 @@ sealed class UniversalTarget : Target, IHasMetadata, ILegacyTarget, IMaySupportV
#endif
{
public override int latestVersion => 1;
+ internal override bool prefersUITKPreview => m_ActiveSubTarget.value is IUISubTarget;
// Constants
static readonly GUID kSourceCodeGuid = new GUID("8c72f47fdde33b14a9340e325ce56f4d"); // UniversalTarget.cs
@@ -119,6 +122,7 @@ sealed class UniversalTarget : Target, IHasMetadata, ILegacyTarget, IMaySupportV
public const string kComplexLitMaterialTypeTag = "\"UniversalMaterialType\" = \"ComplexLit\"";
public const string kLitMaterialTypeTag = "\"UniversalMaterialType\" = \"Lit\"";
public const string kUnlitMaterialTypeTag = "\"UniversalMaterialType\" = \"Unlit\"";
+ public const string kTerrainMaterialTypeTag = "\"TerrainCompatible\" = \"True\"";
public const string kAlwaysRenderMotionVectorsTag = "\"AlwaysRenderMotionVectors\" = \"true\"";
public static readonly string[] kSharedTemplateDirectories = GenerationUtils.GetDefaultSharedTemplateDirectories().Union(new string[]
{
@@ -179,6 +183,9 @@ sealed class UniversalTarget : Target, IHasMetadata, ILegacyTarget, IMaySupportV
[SerializeField]
bool m_DisableTint = false;
+ [SerializeField]
+ bool m_Sort3Das2DCompatible = false;
+
[SerializeField]
AdditionalMotionVectorMode m_AdditionalMotionVectorMode = AdditionalMotionVectorMode.None;
@@ -299,6 +306,12 @@ public bool disableTint
set => m_DisableTint = value;
}
+ public bool sort3Das2DCompatible
+ {
+ get => m_Sort3Das2DCompatible;
+ set => m_Sort3Das2DCompatible = value;
+ }
+
public bool castShadows
{
get => m_CastShadows;
@@ -377,7 +390,17 @@ public override bool IsNodeAllowedByTarget(Type nodeType)
bool worksWithThisSrp = srpFilter == null || srpFilter.srpTypes.Contains(typeof(UniversalRenderPipeline));
SubTargetFilterAttribute subTargetFilter = NodeClassCache.GetAttributeOnNodeType(nodeType);
- bool worksWithThisSubTarget = subTargetFilter == null || subTargetFilter.subTargetTypes.Contains(activeSubTarget.GetType());
+ var activeSubTargetType = activeSubTarget.GetType();
+ var worksWithThisSubTarget = subTargetFilter == null;
+ if (subTargetFilter != null)
+ {
+ foreach (var type in subTargetFilter.subTargetTypes)
+ {
+ if (!type.IsAssignableFrom(activeSubTargetType)) continue;
+ worksWithThisSubTarget = true;
+ break;
+ }
+ }
if (activeSubTarget.IsActive())
worksWithThisSubTarget &= activeSubTarget.IsNodeAllowedBySubTarget(nodeType);
@@ -428,17 +451,20 @@ public override void GetFields(ref TargetFieldContext context)
public override void GetActiveBlocks(ref TargetActiveBlockContext context)
{
// Core blocks
- bool useCoreBlocks = !(m_ActiveSubTarget.value is UnityEditor.Rendering.Fullscreen.ShaderGraph.FullscreenSubTarget | m_ActiveSubTarget.value is UnityEditor.Rendering.Canvas.ShaderGraph.CanvasSubTarget);
+ bool useCoreBlocks = !(m_ActiveSubTarget.value is UnityEditor.Rendering.Fullscreen.ShaderGraph.FullscreenSubTarget
+ | m_ActiveSubTarget.value is UnityEditor.Rendering.Canvas.ShaderGraph.CanvasSubTarget
+ | m_ActiveSubTarget.value is UnityEditor.Rendering.UITK.ShaderGraph.UISubTarget);
// Core blocks
if (useCoreBlocks)
{
context.AddBlock(BlockFields.VertexDescription.Position);
- context.AddBlock(BlockFields.VertexDescription.Normal);
- context.AddBlock(BlockFields.VertexDescription.Tangent);
+ if (m_ActiveSubTarget.value is not UniversalTerrainLitSubTarget){
+ context.AddBlock(BlockFields.VertexDescription.Normal);
+ context.AddBlock(BlockFields.VertexDescription.Tangent);
+ }
context.AddBlock(BlockFields.SurfaceDescription.BaseColor);
}
-
// SubTarget blocks
m_ActiveSubTarget.value.GetActiveBlocks(ref context);
}
@@ -469,6 +495,7 @@ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Acti
{
// Core properties
m_SubTargetField = new PopupField(m_SubTargetNames, activeSubTargetIndex);
+ var validationAction = context.graphValidation;
context.AddProperty("Material", m_SubTargetField, (evt) =>
{
if (Equals(activeSubTargetIndex, m_SubTargetField.index))
@@ -478,6 +505,7 @@ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Acti
m_ActiveSubTarget = m_SubTargets[m_SubTargetField.index];
ProcessSubTargetDatas(m_ActiveSubTarget.value);
onChange();
+ validationAction();
});
// SubTarget properties
@@ -1448,6 +1476,8 @@ public static class Uniforms
{
public static readonly string srcBlend = "[" + Property.SrcBlend + "]";
public static readonly string dstBlend = "[" + Property.DstBlend + "]";
+ public static readonly string srcBlendAlpha = "[" + Property.SrcBlendAlpha + "]";
+ public static readonly string dstBlendAlpha = "[" + Property.DstBlendAlpha + "]";
public static readonly string cullMode = "[" + Property.CullMode + "]";
public static readonly string zWrite = "[" + Property.ZWrite + "]";
public static readonly string zTest = "[" + Property.ZTest + "]";
@@ -1489,7 +1519,7 @@ public static RenderStateCollection UberSwitchedRenderState(UniversalTarget targ
RenderState.ZTest(Uniforms.zTest),
RenderState.ZWrite(Uniforms.zWrite),
RenderState.Cull(Uniforms.cullMode),
- RenderState.Blend(Uniforms.srcBlend, Uniforms.dstBlend),
+ RenderState.Blend(Uniforms.srcBlend, Uniforms.dstBlend, Uniforms.srcBlendAlpha, Uniforms.dstBlendAlpha),
};
}
else
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.Dependencies.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.Dependencies.cs
new file mode 100644
index 00000000000..23b34b54d24
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.Dependencies.cs
@@ -0,0 +1,286 @@
+using System;
+using System.Collections.Generic;
+using UnityEditor.ShaderGraph;
+using UnityEditor.ShaderGraph.Legacy;
+
+namespace UnityEditor.Rendering.Universal.ShaderGraph
+{
+ partial class UniversalTerrainLitSubTarget
+ {
+ #region Template
+ static class TerrainBaseMapGenTemplate
+ {
+ public static readonly string kPassTemplate = "Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.template";
+ public static readonly string[] kSharedTemplateDirectories;
+ static TerrainBaseMapGenTemplate()
+ {
+ kSharedTemplateDirectories = new string[UniversalTarget.kSharedTemplateDirectories.Length + 1];
+ Array.Copy(UniversalTarget.kSharedTemplateDirectories, kSharedTemplateDirectories, UniversalTarget.kSharedTemplateDirectories.Length);
+ kSharedTemplateDirectories[^1] = "Packages/com.unity.render-pipelines.universal/Editor/Terrain/";
+ }
+ }
+ #endregion
+
+ #region SubShaders
+ static class TerrainLitAddSubShaders
+ {
+ public static SubShaderDescriptor LitComputeDotsSubShader(UniversalTarget target, string renderType, string renderQueue, bool blendModePreserveSpecular)
+ {
+ SubShaderDescriptor result = new SubShaderDescriptor()
+ {
+ pipelineTag = UniversalTarget.kPipelineTag,
+ customTags = UniversalTarget.kLitMaterialTypeTag,
+ renderType = renderType,
+ renderQueue = renderQueue,
+ generatesPreview = false,
+ passes = new PassCollection(),
+ additionalShaderID = "Hidden/{Name}_AddPass",
+ shaderCustomEditors = new List(),
+ shaderCustomEditor = "",
+ shaderFallback = "",
+ };
+
+ result.passes.Add(TerrainLitAddPasses.Forward(target, blendModePreserveSpecular, TerrainCorePragmas.DOTSForward));
+ result.passes.Add(TerrainLitAddPasses.GBuffer(target, blendModePreserveSpecular));
+
+ return result;
+ }
+
+ public static SubShaderDescriptor LitGLESSubShader(UniversalTarget target, string renderType, string renderQueue, bool blendModePreserveSpecular)
+ {
+ SubShaderDescriptor result = new SubShaderDescriptor()
+ {
+ pipelineTag = UniversalTarget.kPipelineTag,
+ customTags = UniversalTarget.kLitMaterialTypeTag,
+ renderType = renderType,
+ renderQueue = renderQueue,
+ generatesPreview = false,
+ passes = new PassCollection(),
+ additionalShaderID = "Hidden/{Name}_AddPass",
+ shaderCustomEditors = new List(),
+ shaderCustomEditor = "",
+ shaderFallback = "",
+ };
+
+ result.passes.Add(TerrainLitAddPasses.Forward(target, blendModePreserveSpecular));
+
+ return result;
+ }
+ }
+
+ static class TerrainLitBaseMapGenSubShaders
+ {
+ public static SubShaderDescriptor GenerateBaseMap(UniversalTarget target, string renderType, string renderQueue, bool blendModePreserveSpecular)
+ {
+ SubShaderDescriptor result = new SubShaderDescriptor()
+ {
+ hideTags = true,
+ generatesPreview = false,
+ passes = new PassCollection(),
+ additionalShaderID = "Hidden/{Name}_BaseMapGen",
+ shaderCustomEditors = new List(),
+ shaderCustomEditor = "",
+ shaderFallback = "",
+ };
+
+ result.passes.Add(TerrainBaseGenPasses.MainTex(target));
+ result.passes.Add(TerrainBaseGenPasses.MetallicTex(target));
+
+ return result;
+ }
+ }
+ #endregion
+
+ #region Passes
+ static class TerrainLitAddPasses
+ {
+ public static PassDescriptor Forward(UniversalTarget target, bool blendModePreserveSpecular, PragmaCollection pragmas = null)
+ {
+ var result = TerrainLitPasses.Forward(target, blendModePreserveSpecular, pragmas);
+ result.renderStates = AdditionalLayersRenderState();
+ result.defines.Add(TerrainDefines.TerrainAddPass, 1);
+
+ return result;
+ }
+
+ // Deferred only in SM4.5, MRT not supported in GLES2
+ public static PassDescriptor GBuffer(UniversalTarget target, bool blendModePreserveSpecular)
+ {
+ var result = TerrainLitPasses.GBuffer(target, blendModePreserveSpecular);
+ result.renderStates = AdditionalLayersRenderState();
+ result.defines.Add(TerrainDefines.TerrainAddPass, 1);
+
+ return result;
+ }
+
+ // used by lit/unlit subtargets
+ public static RenderStateCollection AdditionalLayersRenderState()
+ {
+ var result = new RenderStateCollection();
+
+ result.Add(RenderState.Blend(Blend.One, Blend.One));
+
+ return result;
+ }
+ }
+
+ static class TerrainBaseGenPasses
+ {
+ private static string kMainTexName = "\"Name\" = \"_MainTex\"";
+ private static string kMainTexFormat = "\"Format\" = \"ARGB32\"";
+ private static string kMainTexSize = "\"Size\" = \"1\"";
+ private static string kMainEmptyColor = "\"EmptyColor\" = \"\"";
+
+ private static string kMetallicTexName = "\"Name\" = \"_MetallicTex\"";
+ private static string kMetallicTexFormat = "\"Format\" = \"R8\"";
+ private static string kMetallicTexSize = "\"Size\" = \"1/4\"";
+ private static string kMetallicEmptyColor = "\"EmptyColor\" = \"FF000000\"";
+
+ public static PassDescriptor MainTex(UniversalTarget target)
+ {
+ var result = new PassDescriptor
+ {
+ referenceName = "SHADERPASS_MAINTEX",
+
+ // Template
+ passTemplatePath = TerrainBaseMapGenTemplate.kPassTemplate,
+ sharedTemplateDirectories = TerrainBaseMapGenTemplate.kSharedTemplateDirectories,
+
+ // Port Mask
+ validVertexBlocks = TerrainBlockMasks.Vertex,
+ validPixelBlocks = TerrainBlockMasks.FragmentLit,
+
+ // Fields
+ structs = TerrainStructCollections.Default,
+ requiredFields = TerrainRequiredFields.Forward,
+ fieldDependencies = CoreFieldDependencies.Default,
+
+ // Conditional State
+ renderStates = BaseMapGenRenderState,
+ pragmas = BaseMapPragmas,
+ defines = new DefineCollection(),
+ keywords = new KeywordCollection(),
+ includes = BaseGenMainTexIncludes,
+ additionalCommands = BaseMapMainTex,
+
+ // Custom Interpolator Support
+ customInterpolators = CoreCustomInterpDescriptors.Common,
+ };
+
+ result.defines.Add(TerrainDefines.TerrainEnabled, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat01, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat23, 1);
+ result.defines.Add(TerrainDefines.MetallicSpecGlossMap, 1);
+ result.defines.Add(TerrainDefines.SmoothnessTextureAlbedoChannelA, 1);
+ result.defines.Add(TerrainDefines.TerrainBaseMapGen, 1);
+ result.keywords.Add(TerrainDefines.TerrainMaskmap);
+ result.keywords.Add(TerrainDefines.TerrainBlendHeight);
+
+ return result;
+ }
+
+ public static PassDescriptor MetallicTex(UniversalTarget target)
+ {
+ var result = new PassDescriptor
+ {
+ referenceName = "SHADERPASS_METALLICTEX",
+
+ // Template
+ passTemplatePath = TerrainBaseMapGenTemplate.kPassTemplate,
+ sharedTemplateDirectories = TerrainBaseMapGenTemplate.kSharedTemplateDirectories,
+
+ // Port Mask
+ validVertexBlocks = TerrainBlockMasks.Vertex,
+ validPixelBlocks = TerrainBlockMasks.FragmentLit,
+
+ // Fields
+ structs = TerrainStructCollections.Default,
+ requiredFields = TerrainRequiredFields.Forward,
+ fieldDependencies = CoreFieldDependencies.Default,
+
+ // Conditional State
+ renderStates = BaseMapGenRenderState,
+ pragmas = BaseMapPragmas,
+ defines = new DefineCollection(),
+ keywords = new KeywordCollection(),
+ includes = BaseGenMetallicTexIncludes,
+ additionalCommands = BaseMapMetallicTex,
+
+ // Custom Interpolator Support
+ customInterpolators = CoreCustomInterpDescriptors.Common,
+ };
+
+ result.defines.Add(TerrainDefines.TerrainEnabled, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat01, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat23, 1);
+ result.defines.Add(TerrainDefines.MetallicSpecGlossMap, 1);
+ result.defines.Add(TerrainDefines.SmoothnessTextureAlbedoChannelA, 1);
+ result.defines.Add(TerrainDefines.TerrainBaseMapGen, 1);
+ result.keywords.Add(TerrainDefines.TerrainMaskmap);
+ result.keywords.Add(TerrainDefines.TerrainBlendHeight);
+
+ return result;
+ }
+
+ public static RenderStateCollection BaseMapGenRenderState = new RenderStateCollection()
+ {
+ { RenderState.ZTest(ZTest.Always) },
+ { RenderState.Cull(Cull.Off) },
+ { RenderState.ZWrite(ZWrite.Off) },
+ { RenderState.Blend("One", "[_DstBlend]") },
+ };
+
+ public static readonly PragmaCollection BaseMapPragmas = new PragmaCollection()
+ {
+ { Pragma.Target(ShaderModel.Target30) },
+ { Pragma.Vertex("vert") },
+ { Pragma.Fragment("frag") },
+ };
+
+ public static readonly string kBaseMapPass = "Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.hlsl";
+
+ public static readonly IncludeCollection BaseGenMainTexIncludes = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { TerrainCoreIncludes.kTerrainLitInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainPassUtils, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { TerrainCoreIncludes.CorePostgraph },
+ { TerrainBaseGenPasses.kBaseMapPass, IncludeLocation.Postgraph },
+ };
+
+ public static readonly IncludeCollection BaseGenMetallicTexIncludes = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { TerrainCoreIncludes.kTerrainLitInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainPassUtils, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { TerrainCoreIncludes.CorePostgraph },
+ { TerrainBaseGenPasses.kBaseMapPass, IncludeLocation.Postgraph },
+ };
+
+ public static readonly AdditionalCommandCollection BaseMapMainTex = new AdditionalCommandCollection()
+ {
+ new AdditionalCommandDescriptor("BaseGenName", kMainTexName),
+ new AdditionalCommandDescriptor("BaseGenTexFormat", kMainTexFormat),
+ new AdditionalCommandDescriptor("BaseGenTexSize", kMainTexSize),
+ new AdditionalCommandDescriptor("BaseGenEmptyColor", kMainEmptyColor),
+ };
+
+ public static readonly AdditionalCommandCollection BaseMapMetallicTex = new AdditionalCommandCollection()
+ {
+ new AdditionalCommandDescriptor("BaseGenName", kMetallicTexName),
+ new AdditionalCommandDescriptor("BaseGenTexFormat", kMetallicTexFormat),
+ new AdditionalCommandDescriptor("BaseGenTexSize", kMetallicTexSize),
+ new AdditionalCommandDescriptor("BaseGenEmptyColor", kMetallicEmptyColor),
+ };
+ }
+ #endregion
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.Dependencies.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.Dependencies.cs.meta
new file mode 100644
index 00000000000..81d0c62dbef
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.Dependencies.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 45705132c6bcacc459c763f7cd71b9fa
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.cs
new file mode 100644
index 00000000000..12f9b70e905
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.cs
@@ -0,0 +1,1732 @@
+using System;
+using System.Collections.Generic;
+using UnityEngine;
+using UnityEditor.ShaderGraph;
+using UnityEditor.ShaderGraph.Internal;
+using UnityEngine.UIElements;
+using UnityEditor.ShaderGraph.Legacy;
+using UnityEngine.Assertions;
+using static UnityEditor.Rendering.Universal.ShaderGraph.SubShaderUtils;
+using UnityEngine.Rendering.Universal;
+using static Unity.Rendering.Universal.ShaderUtils;
+
+namespace UnityEditor.Rendering.Universal.ShaderGraph
+{
+ partial class UniversalTerrainLitSubTarget : UniversalSubTarget, ITerrainSubTarget
+ {
+ private static readonly GUID kSourceCodeGuid = new GUID("ea07e558bc2741a5ba7f1d5470eb242b"); // UniversalTerrainLitSubTarget.cs
+
+ public override int latestVersion => 1;
+
+ [SerializeField]
+ private bool m_EnableHeightBlend;
+
+ [SerializeField]
+ float m_HeightTransition;
+
+ [SerializeField]
+ bool m_EnableInstancedPerPixelNormal = true;
+
+ [SerializeField]
+ NormalDropOffSpace m_NormalDropOffSpace = NormalDropOffSpace.Tangent;
+
+ [SerializeField]
+ bool m_BlendModePreserveSpecular = true;
+
+ protected override ShaderID shaderID => ShaderID.SG_TerrainLit;
+
+ public bool enableHeightBlend
+ {
+ get => m_EnableHeightBlend;
+ set => m_EnableHeightBlend = value;
+ }
+
+ public float heightTransition
+ {
+ get => m_HeightTransition;
+ set => m_HeightTransition = value;
+ }
+
+ public bool enableInstancedPerPixelNormal
+ {
+ get => m_EnableInstancedPerPixelNormal;
+ set => m_EnableInstancedPerPixelNormal = value;
+ }
+
+ public NormalDropOffSpace normalDropOffSpace
+ {
+ get => m_NormalDropOffSpace;
+ set => m_NormalDropOffSpace = value;
+ }
+
+ public bool blendModePreserveSpecular
+ {
+ get => m_BlendModePreserveSpecular;
+ set => m_BlendModePreserveSpecular = value;
+ }
+
+ public UniversalTerrainLitSubTarget()
+ {
+ displayName = "TerrainLit";
+ }
+
+ public override bool IsActive() => true;
+
+ public override void Setup(ref TargetSetupContext context)
+ {
+ context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
+ base.Setup(ref context);
+
+ var universalRPType = typeof(UniversalRenderPipelineAsset);
+ if (!context.HasCustomEditorForRenderPipeline(universalRPType))
+ context.AddCustomEditorForRenderPipeline(typeof(ShaderGraphTerrainLitGUI).FullName, universalRPType);
+
+ context.AddSubShader(PostProcessSubShader(TerrainSubShaders.LitComputeDotsSubShader(target, target.renderType, target.renderQueue, blendModePreserveSpecular)));
+ context.AddSubShader(PostProcessSubShader(TerrainSubShaders.LitGLESSubShader(target, target.renderType, target.renderQueue, blendModePreserveSpecular)));
+
+ context.AddSubShader(PostProcessSubShader(TerrainLitAddSubShaders.LitComputeDotsSubShader(target, target.renderType, target.renderQueue, blendModePreserveSpecular)));
+ context.AddSubShader(PostProcessSubShader(TerrainLitAddSubShaders.LitGLESSubShader(target, target.renderType, target.renderQueue, blendModePreserveSpecular)));
+
+ context.AddSubShader(PostProcessSubShader(TerrainLitBaseMapGenSubShaders.GenerateBaseMap(target, target.renderType, target.renderQueue, blendModePreserveSpecular)));
+ }
+
+ public override void ProcessPreviewMaterial(Material material)
+ {
+ if (target.allowMaterialOverride)
+ {
+ // copy our target's default settings into the material
+ // (technically not necessary since we are always recreating the material from the shader each time,
+ // which will pull over the defaults from the shader definition)
+ // but if that ever changes, this will ensure the defaults are set
+ material.SetFloat(Property.SpecularWorkflowMode, 1.0f);
+ material.SetFloat(Property.CastShadows, target.castShadows ? 1.0f : 0.0f);
+ material.SetFloat(Property.ReceiveShadows, target.receiveShadows ? 1.0f : 0.0f);
+ material.SetFloat(Property.SurfaceType, 0.0f);
+ material.SetFloat(Property.BlendMode, (float)target.alphaMode);
+ material.SetFloat(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f);
+ material.SetFloat(Property.CullMode, 2.0f);
+ material.SetFloat(Property.ZWriteControl, (float)target.zWriteControl);
+ material.SetFloat(Property.ZTest, (float)target.zTestMode);
+ }
+
+ // We always need these properties regardless of whether the material is allowed to override
+ // Queue control & offset enable correct automatic render queue behavior
+ // Control == 0 is automatic, 1 is user-specified render queue
+ material.SetFloat(Property.QueueOffset, 0.0f);
+ material.SetFloat(Property.QueueControl, (float)BaseShaderGUI.QueueControl.Auto);
+
+ // call the full unlit material setup function
+ ShaderGraphLitGUI.UpdateMaterial(material, MaterialUpdateType.CreatedNewMaterial);
+ }
+
+ public override void GetFields(ref TargetFieldContext context)
+ {
+ base.GetFields(ref context);
+
+ // TerrainLit -- always controlled by subtarget
+ context.AddField(UniversalFields.NormalDropOffOS, normalDropOffSpace == NormalDropOffSpace.Object);
+ context.AddField(UniversalFields.NormalDropOffTS, normalDropOffSpace == NormalDropOffSpace.Tangent);
+ context.AddField(UniversalFields.NormalDropOffWS, normalDropOffSpace == NormalDropOffSpace.World);
+ }
+
+ public override void GetActiveBlocks(ref TargetActiveBlockContext context)
+ {
+ context.AddBlock(BlockFields.SurfaceDescription.Smoothness);
+ context.AddBlock(BlockFields.SurfaceDescription.NormalOS, normalDropOffSpace == NormalDropOffSpace.Object);
+ context.AddBlock(BlockFields.SurfaceDescription.NormalTS, normalDropOffSpace == NormalDropOffSpace.Tangent);
+ context.AddBlock(BlockFields.SurfaceDescription.NormalWS, normalDropOffSpace == NormalDropOffSpace.World);
+ context.AddBlock(BlockFields.SurfaceDescription.Emission);
+ context.AddBlock(BlockFields.SurfaceDescription.Occlusion);
+
+ // when the surface options are material controlled, we must show all of these blocks
+ // when target controlled, we can cull the unnecessary blocks
+ context.AddBlock(BlockFields.SurfaceDescription.Specular, target.allowMaterialOverride);
+ context.AddBlock(BlockFields.SurfaceDescription.Metallic);
+ context.AddBlock(BlockFields.SurfaceDescription.Alpha, target.alphaClip);
+ context.AddBlock(BlockFields.SurfaceDescription.AlphaClipThreshold, target.alphaClip);
+ }
+
+ public override void CollectShaderProperties(PropertyCollector collector, GenerationMode generationMode)
+ {
+ collector.AddShaderProperty(new BooleanShaderProperty
+ {
+ value = enableHeightBlend,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_EnableHeightBlend",
+ displayName = "Enable Height Blend",
+ });
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ floatType = FloatType.Slider,
+ value = heightTransition,
+ hidden = false,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_HeightTransition",
+ displayName = "Height Transition",
+ });
+ collector.AddShaderProperty(new BooleanShaderProperty
+ {
+ value = enableInstancedPerPixelNormal,
+ hidden = false,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_EnableInstancedPerPixelNormal",
+ displayName = "Enable Instanced per Pixel Normal",
+ });
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.White,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_TerrainHolesTexture",
+ displayName = "Holes Map (RGB)",
+ });
+
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.White,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_DefaultWhiteTex",
+ displayName = "DefaultWhiteTex",
+ });
+
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.NormalMap,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_NormalBlank",
+ displayName = "Empty Normal Map",
+ });
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.Black,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_BlackTex",
+ displayName = "Empty Texture",
+ });
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.White,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Splat0",
+ displayName = "Layer 0 (R)",
+ useTilingAndOffset = true,
+ });
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.White,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Splat1",
+ displayName = "Layer 1 (G)",
+ useTilingAndOffset = true,
+ });
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.White,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Splat2",
+ displayName = "Layer 2 (B)",
+ useTilingAndOffset = true,
+ });
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.White,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Splat3",
+ displayName = "Layer 3 (A)",
+ useTilingAndOffset = true,
+ });
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.Grey,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Mask3",
+ displayName = "Layer 3 (A)",
+ useTilingAndOffset = true,
+ });
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.Grey,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Mask2",
+ displayName = "Layer 2 (B)",
+ useTilingAndOffset = true,
+ });
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.Grey,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Mask1",
+ displayName = "Layer 1 (G)",
+ useTilingAndOffset = true,
+ });
+ collector.AddShaderProperty(new Texture2DShaderProperty
+ {
+ defaultType = Texture2DShaderProperty.DefaultType.Grey,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Mask0",
+ displayName = "Layer 0 (R)",
+ useTilingAndOffset = true,
+ });
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ floatType = FloatType.Slider,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Metallic0",
+ displayName = "Metallic 0",
+ });
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ floatType = FloatType.Slider,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Metallic1",
+ displayName = "Metallic 1",
+ });
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ floatType = FloatType.Slider,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Metallic2",
+ displayName = "Metallic 2",
+ });
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ floatType = FloatType.Slider,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Metallic3",
+ displayName = "Metallic 3",
+ });
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ value = 1.0f,
+ floatType = FloatType.Slider,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Smoothness0",
+ displayName = "Smoothness 0",
+ });
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ value = 1.0f,
+ floatType = FloatType.Slider,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Smoothness1",
+ displayName = "Smoothness 1",
+ });
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ value = 1.0f,
+ floatType = FloatType.Slider,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Smoothness2",
+ displayName = "Smoothness 2",
+ });
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ value = 1.0f,
+ floatType = FloatType.Slider,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.DoNotDeclare,
+ overrideReferenceName = "_Smoothness3",
+ displayName = "Smoothness 3",
+ });
+
+ collector.AddShaderProperty(new Vector1ShaderProperty
+ {
+ floatType = FloatType.Default,
+ value = 0.0f,
+ hidden = true,
+ overrideHLSLDeclaration = true,
+ hlslDeclarationOverride = HLSLDeclaration.Global,
+ overrideReferenceName = "_DstBlend",
+ displayName = "DstBlend",
+ });
+ }
+
+ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo)
+ {
+ var universalTarget = (target as UniversalTarget);
+ universalTarget.AddDefaultMaterialOverrideGUI(ref context, onChange, registerUndo);
+
+ context.AddProperty("Blending Mode", new EnumField(AlphaMode.Alpha) { value = target.alphaMode }, target.surfaceType == SurfaceType.Transparent, (evt) =>
+ {
+ if (Equals(target.alphaMode, evt.newValue))
+ return;
+
+ registerUndo("Change Blend");
+ target.alphaMode = (AlphaMode)evt.newValue;
+ onChange();
+ });
+
+ context.AddProperty("Depth Write", new EnumField(ZWriteControl.Auto) { value = target.zWriteControl }, (evt) =>
+ {
+ if (Equals(target.zWriteControl, evt.newValue))
+ return;
+
+ registerUndo("Change Depth Write Control");
+ target.zWriteControl = (ZWriteControl)evt.newValue;
+ onChange();
+ });
+
+ context.AddProperty("Depth Test", new EnumField(ZTestModeForUI.LEqual) { value = (ZTestModeForUI)target.zTestMode }, (evt) =>
+ {
+ if (Equals(target.zTestMode, evt.newValue))
+ return;
+
+ registerUndo("Change Depth Test");
+ target.zTestMode = (ZTestMode)evt.newValue;
+ onChange();
+ });
+
+ context.AddProperty("Alpha Clipping", new Toggle() { value = target.alphaClip }, (evt) =>
+ {
+ if (Equals(target.alphaClip, evt.newValue))
+ return;
+
+ registerUndo("Change Alpha Clip");
+ target.alphaClip = evt.newValue;
+ onChange();
+ });
+
+ context.AddProperty("Cast Shadows", new Toggle() { value = target.castShadows }, (evt) =>
+ {
+ if (Equals(target.castShadows, evt.newValue))
+ return;
+
+ registerUndo("Change Cast Shadows");
+ target.castShadows = evt.newValue;
+ onChange();
+ });
+
+ context.AddProperty("Receive Shadows", new Toggle() {value = target.receiveShadows}, (evt) =>
+ {
+ if (Equals(target.receiveShadows, evt.newValue))
+ return;
+
+ registerUndo("Change Receive Shadows");
+ target.receiveShadows = evt.newValue;
+ onChange();
+ });
+
+ context.AddProperty("Fragment Normal Space", new EnumField(NormalDropOffSpace.Tangent) { value = normalDropOffSpace }, (evt) =>
+ {
+ if (Equals(normalDropOffSpace, evt.newValue))
+ return;
+
+ registerUndo("Change Fragment Normal Space");
+ normalDropOffSpace = (NormalDropOffSpace)evt.newValue;
+ onChange();
+ });
+ }
+
+ protected override int ComputeMaterialNeedsUpdateHash()
+ {
+ int hash = base.ComputeMaterialNeedsUpdateHash();
+ hash = hash * 23 + target.allowMaterialOverride.GetHashCode();
+ return hash;
+ }
+
+ // this is a copy of ZTestMode, but hides the "Disabled" option, which is invalid
+ enum ZTestModeForUI
+ {
+ Never = 1,
+ Less = 2,
+ Equal = 3,
+ LEqual = 4, // default for most rendering
+ Greater = 5,
+ NotEqual = 6,
+ GEqual = 7,
+ Always = 8,
+ };
+
+ internal override void OnAfterParentTargetDeserialized()
+ {
+ Assert.IsNotNull(target);
+
+ if (this.sgVersion < latestVersion)
+ {
+ // Upgrade old incorrect Premultiplied blend into
+ // equivalent Alpha + Preserve Specular blend mode.
+ if (this.sgVersion < 1)
+ {
+ if (target.alphaMode == AlphaMode.Premultiply)
+ {
+ target.alphaMode = AlphaMode.Alpha;
+ blendModePreserveSpecular = true;
+ }
+ else
+ blendModePreserveSpecular = false;
+ }
+ ChangeVersion(latestVersion);
+ }
+ }
+
+ #region Template
+ static class TerrainLitTemplate
+ {
+ public static readonly string kPassTemplate = "Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPass.template";
+ public static readonly string[] kSharedTemplateDirectories;
+
+ static TerrainLitTemplate()
+ {
+ kSharedTemplateDirectories = new string[UniversalTarget.kSharedTemplateDirectories.Length + 1];
+ Array.Copy(UniversalTarget.kSharedTemplateDirectories, kSharedTemplateDirectories, UniversalTarget.kSharedTemplateDirectories.Length);
+ kSharedTemplateDirectories[^1] = "Packages/com.unity.render-pipelines.universal/Editor/Terrain/";
+ }
+ }
+ #endregion
+
+ #region StructCollections
+ static class TerrainStructFields
+ {
+ public struct Varyings
+ {
+ public static FieldDescriptor uvSplat01 = new FieldDescriptor(
+ StructFields.Varyings.name, "uvSplat01", "", ShaderValueType.Float4, "TEXCOORD1", preprocessor: "defined(UNIVERSAL_TERRAIN_SPLAT01)", subscriptOptions: StructFieldOptions.Optional);
+ public static FieldDescriptor uvSplat23 = new FieldDescriptor(
+ StructFields.Varyings.name, "uvSplat23", "", ShaderValueType.Float4, "TEXCOORD2", preprocessor: "defined(UNIVERSAL_TERRAIN_SPLAT23)", subscriptOptions: StructFieldOptions.Optional);
+ public static FieldDescriptor normalViewDir = new FieldDescriptor(
+ StructFields.Varyings.name, "normalViewDir", "", ShaderValueType.Float4, "TEXCOORD3", "defined(_NORMALMAP) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)", StructFieldOptions.Optional);
+ public static FieldDescriptor tangentViewDir = new FieldDescriptor(
+ StructFields.Varyings.name, "tangentViewDir", "", ShaderValueType.Float4, "TEXCOORD4", "defined(_NORMALMAP) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)", StructFieldOptions.Optional);
+ public static FieldDescriptor bitangentViewDir = new FieldDescriptor(
+ StructFields.Varyings.name, "bitangentViewDir", "", ShaderValueType.Float4, "TEXCOORD5", "defined(_NORMALMAP) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)", StructFieldOptions.Optional);
+ }
+
+ public struct SurfaceDescriptionInputs
+ {
+ public static FieldDescriptor uvSplat01 = new FieldDescriptor(
+ StructFields.SurfaceDescriptionInputs.name, "uvSplat01", "", ShaderValueType.Float4, "TEXCOORD1", "defined(UNIVERSAL_TERRAIN_SPLAT01)");
+ public static FieldDescriptor uvSplat23 = new FieldDescriptor(
+ StructFields.SurfaceDescriptionInputs.name, "uvSplat23", "", ShaderValueType.Float4, "TEXCOORD2", "defined(UNIVERSAL_TERRAIN_SPLAT23)");
+ }
+ }
+
+ internal static class TerrainStructs
+ {
+ public static StructDescriptor Attributes = new StructDescriptor()
+ {
+ name = "Attributes",
+ packFields = false,
+ fields = new FieldDescriptor[]
+ {
+ StructFields.Attributes.positionOS,
+ StructFields.Attributes.normalOS,
+ StructFields.Attributes.uv0,
+ StructFields.Attributes.uv1,
+ StructFields.Attributes.uv2,
+ StructFields.Attributes.uv3,
+ StructFields.Attributes.color,
+ StructFields.Attributes.instanceID,
+ StructFields.Attributes.vertexID,
+ }
+ };
+
+ public static StructDescriptor MetaAttributes = new StructDescriptor()
+ {
+ name = "Attributes",
+ packFields = false,
+ fields = new FieldDescriptor[]
+ {
+ StructFields.Attributes.positionOS,
+ StructFields.Attributes.normalOS,
+ StructFields.Attributes.uv0,
+ StructFields.Attributes.uv1,
+ StructFields.Attributes.uv2,
+ StructFields.Attributes.uv3,
+ StructFields.Attributes.color,
+ StructFields.Attributes.instanceID,
+ StructFields.Attributes.vertexID,
+ }
+ };
+
+ public static StructDescriptor Varyings = new StructDescriptor()
+ {
+ name = "Varyings",
+ packFields = true,
+ populateWithCustomInterpolators = true,
+ fields = new FieldDescriptor[]
+ {
+ StructFields.Varyings.positionCS,
+ StructFields.Varyings.positionWS,
+ StructFields.Varyings.normalWS,
+ StructFields.Varyings.tangentWS,
+ StructFields.Varyings.texCoord0,
+ StructFields.Varyings.texCoord1,
+ StructFields.Varyings.texCoord2,
+ StructFields.Varyings.texCoord3,
+ StructFields.Varyings.color,
+ StructFields.Varyings.screenPosition,
+ TerrainStructFields.Varyings.uvSplat01,
+ TerrainStructFields.Varyings.uvSplat23,
+ TerrainStructFields.Varyings.normalViewDir,
+ TerrainStructFields.Varyings.tangentViewDir,
+ TerrainStructFields.Varyings.bitangentViewDir,
+ UniversalStructFields.Varyings.staticLightmapUV,
+ UniversalStructFields.Varyings.dynamicLightmapUV,
+ UniversalStructFields.Varyings.sh,
+ UniversalStructFields.Varyings.fogFactorAndVertexLight,
+ UniversalStructFields.Varyings.shadowCoord,
+ StructFields.Varyings.instanceID,
+ UniversalStructFields.Varyings.stereoTargetEyeIndexAsBlendIdx0,
+ UniversalStructFields.Varyings.stereoTargetEyeIndexAsRTArrayIdx,
+ StructFields.Varyings.cullFace,
+ }
+ };
+
+ public static StructDescriptor MetaVaryings = new StructDescriptor()
+ {
+ name = "Varyings",
+ packFields = true,
+ populateWithCustomInterpolators = true,
+ fields = new FieldDescriptor[]
+ {
+ StructFields.Varyings.positionCS,
+ StructFields.Varyings.positionWS,
+ StructFields.Varyings.normalWS,
+ StructFields.Varyings.tangentWS,
+ StructFields.Varyings.texCoord0,
+ StructFields.Varyings.texCoord1,
+ StructFields.Varyings.texCoord2,
+ StructFields.Varyings.texCoord3,
+ StructFields.Varyings.color,
+ StructFields.Varyings.screenPosition,
+ TerrainStructFields.Varyings.uvSplat01,
+ TerrainStructFields.Varyings.uvSplat23,
+ TerrainStructFields.Varyings.normalViewDir,
+ TerrainStructFields.Varyings.tangentViewDir,
+ TerrainStructFields.Varyings.bitangentViewDir,
+ UniversalStructFields.Varyings.staticLightmapUV,
+ UniversalStructFields.Varyings.dynamicLightmapUV,
+ UniversalStructFields.Varyings.sh,
+ UniversalStructFields.Varyings.fogFactorAndVertexLight,
+ UniversalStructFields.Varyings.shadowCoord,
+ StructFields.Varyings.instanceID,
+ UniversalStructFields.Varyings.stereoTargetEyeIndexAsBlendIdx0,
+ UniversalStructFields.Varyings.stereoTargetEyeIndexAsRTArrayIdx,
+ StructFields.Varyings.cullFace,
+ }
+ };
+
+ private static StructDescriptor SurfaceDescriptionInputsImpl()
+ {
+ var surfaceDescriptionInputs = Structs.SurfaceDescriptionInputs;
+ var terrainFieldList = new List();
+
+ for (int i = 0; i < surfaceDescriptionInputs.fields.Length; ++i)
+ terrainFieldList.Add(surfaceDescriptionInputs.fields[i]);
+
+ terrainFieldList.Add(TerrainStructFields.SurfaceDescriptionInputs.uvSplat01);
+ terrainFieldList.Add(TerrainStructFields.SurfaceDescriptionInputs.uvSplat23);
+
+ return new StructDescriptor()
+ {
+ name = "SurfaceDescriptionInputs",
+ packFields = false,
+ populateWithCustomInterpolators = true,
+ fields = terrainFieldList.ToArray(),
+ };
+ }
+
+ public static StructDescriptor SurfaceDescriptionInputs => SurfaceDescriptionInputsImpl();
+ }
+
+ static class TerrainStructCollections
+ {
+ public static readonly StructCollection Default = new StructCollection
+ {
+ { TerrainStructs.Attributes },
+ { TerrainStructs.Varyings },
+ { Structs.VertexDescriptionInputs },
+ { TerrainStructs.SurfaceDescriptionInputs },
+ };
+
+ public static readonly StructCollection Meta = new StructCollection()
+ {
+ { TerrainStructs.MetaAttributes },
+ { TerrainStructs.MetaVaryings },
+ { Structs.VertexDescriptionInputs },
+ { TerrainStructs.SurfaceDescriptionInputs },
+ };
+ }
+ #endregion
+
+ #region SubShader
+ static class TerrainSubShaders
+ {
+ public static readonly KeywordDescriptor AlphaTestOn = new KeywordDescriptor()
+ {
+ displayName = ShaderKeywordStrings._ALPHATEST_ON,
+ referenceName = ShaderKeywordStrings._ALPHATEST_ON,
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.MultiCompile,
+ scope = KeywordScope.Global,
+ };
+
+ // SM 4.5, compute with dots instancing
+ public static SubShaderDescriptor LitComputeDotsSubShader(UniversalTarget target, string renderType, string renderQueue, bool blendModePreserveSpecular)
+ {
+ SubShaderDescriptor result = new SubShaderDescriptor()
+ {
+ pipelineTag = UniversalTarget.kPipelineTag,
+ customTags = string.Concat(UniversalTarget.kLitMaterialTypeTag, UniversalTarget.kTerrainMaterialTypeTag),
+ renderType = renderType,
+ renderQueue = renderQueue,
+ generatesPreview = true,
+ passes = new PassCollection(),
+ shaderDependencies = new List(),
+ };
+
+ result.passes.Add(TerrainLitPasses.Forward(target, blendModePreserveSpecular, TerrainCorePragmas.DOTSForward));
+ result.passes.Add(TerrainLitPasses.GBuffer(target, blendModePreserveSpecular));
+
+ // cull the shadowcaster pass if we know it will never be used
+ if (target.castShadows || target.allowMaterialOverride)
+ result.passes.Add(PassVariant(TerrainLitPasses.ShadowCaster(target), TerrainCorePragmas.DOTSInstanced));
+
+ if (target.mayWriteDepth)
+ result.passes.Add(PassVariant(TerrainLitPasses.DepthOnly(target), TerrainCorePragmas.DOTSInstanced));
+
+ result.passes.Add(PassVariant(TerrainLitPasses.DepthNormal(target), TerrainCorePragmas.DOTSInstanced));
+ result.passes.Add(PassVariant(TerrainLitPasses.Meta(target), TerrainCorePragmas.DOTSInstanced));
+
+ // Currently neither of these passes (selection/picking) can be last for the game view for
+ // UI shaders to render correctly. Verify [1352225] before changing this order.
+ result.passes.Add(PassVariant(TerrainLitPasses.SceneSelection(target), TerrainCorePragmas.DOTSDefault));
+ result.passes.Add(PassVariant(TerrainLitPasses.ScenePicking(target), TerrainCorePragmas.DOTSDefault));
+
+ result.shaderDependencies.Add(TerrainDependencies.AddPassShader());
+ result.shaderDependencies.Add(TerrainDependencies.BaseMapShader());
+ result.shaderDependencies.Add(TerrainDependencies.BaseMapGenShader());
+
+ return result;
+ }
+
+ public static SubShaderDescriptor LitGLESSubShader(UniversalTarget target, string renderType, string renderQueue, bool blendModePreserveSpecular)
+ {
+ // SM 2.0, GLES
+
+ // ForwardOnly pass is used as complex Lit SM 2.0 fallback for GLES.
+ // Drops advanced features and renders materials as Lit.
+
+ SubShaderDescriptor result = new SubShaderDescriptor()
+ {
+ pipelineTag = UniversalTarget.kPipelineTag,
+ customTags = string.Concat(UniversalTarget.kLitMaterialTypeTag, UniversalTarget.kTerrainMaterialTypeTag),
+ renderType = renderType,
+ renderQueue = renderQueue,
+ generatesPreview = true,
+ passes = new PassCollection(),
+ shaderDependencies = new List(),
+ };
+
+ result.passes.Add(TerrainLitPasses.Forward(target, blendModePreserveSpecular));
+
+ // cull the shadowcaster pass if we know it will never be used
+ if (target.castShadows || target.allowMaterialOverride)
+ result.passes.Add(TerrainLitPasses.ShadowCaster(target));
+
+ if (target.mayWriteDepth)
+ result.passes.Add(TerrainLitPasses.DepthOnly(target));
+
+ result.passes.Add(TerrainLitPasses.DepthNormal(target));
+ result.passes.Add(TerrainLitPasses.Meta(target));
+
+ // Currently neither of these passes (selection/picking) can be last for the game view for
+ // UI shaders to render correctly. Verify [1352225] before changing this order.
+ result.passes.Add(TerrainLitPasses.SceneSelection(target));
+ result.passes.Add(TerrainLitPasses.ScenePicking(target));
+
+ result.shaderDependencies.Add(TerrainDependencies.AddPassShader());
+ result.shaderDependencies.Add(TerrainDependencies.BaseMapShader());
+ result.shaderDependencies.Add(TerrainDependencies.BaseMapGenShader());
+
+ return result;
+ }
+ }
+ #endregion
+
+ #region Pragmas
+ static class TerrainCorePragmas
+ {
+ private static InstancingOptions[] InstancingOptionList()
+ {
+ return new []
+ {
+ InstancingOptions.AssumeUniformScaling,
+ InstancingOptions.NoMatrices,
+ InstancingOptions.NoLightProbe,
+ InstancingOptions.NoLightmap,
+ };
+ }
+
+ public static readonly PragmaCollection Default = new PragmaCollection
+ {
+ { Pragma.Target(ShaderModel.Target20) },
+ { Pragma.OnlyRenderers(new[] { Platform.GLES3, Platform.GLCore, Platform.D3D11 }) },
+ { Pragma.MultiCompileInstancing },
+ { Pragma.InstancingOptions(InstancingOptionList()) },
+ { Pragma.Vertex("vert") },
+ { Pragma.Fragment("frag") },
+ };
+
+ public static readonly PragmaCollection Instanced = new PragmaCollection
+ {
+ { Pragma.Target(ShaderModel.Target20) },
+ { Pragma.OnlyRenderers(new[] { Platform.GLES3, Platform.GLCore, Platform.D3D11 }) },
+ { Pragma.MultiCompileInstancing },
+ { Pragma.InstancingOptions(InstancingOptionList()) },
+ { Pragma.Vertex("vert") },
+ { Pragma.Fragment("frag") },
+ };
+
+ public static readonly PragmaCollection Forward = new PragmaCollection
+ {
+ { Pragma.Target(ShaderModel.Target20) },
+ { Pragma.OnlyRenderers(new[] { Platform.GLES3, Platform.GLCore, Platform.D3D11 }) },
+ { Pragma.MultiCompileInstancing },
+ { Pragma.MultiCompileFog },
+ { Pragma.InstancingOptions(InstancingOptionList()) },
+ { Pragma.Vertex("vert") },
+ { Pragma.Fragment("frag") },
+ };
+
+ public static readonly PragmaCollection DOTSDefault = new PragmaCollection
+ {
+ { Pragma.Target(ShaderModel.Target45) },
+ { Pragma.ExcludeRenderers(new[] { Platform.GLES3, Platform.GLCore }) },
+ { Pragma.MultiCompileInstancing },
+ { Pragma.InstancingOptions(InstancingOptionList()) },
+ { Pragma.Vertex("vert") },
+ { Pragma.Fragment("frag") },
+ };
+
+ public static readonly PragmaCollection DOTSInstanced = new PragmaCollection
+ {
+ { Pragma.Target(ShaderModel.Target45) },
+ { Pragma.ExcludeRenderers(new[] { Platform.GLES3, Platform.GLCore }) },
+ { Pragma.MultiCompileInstancing },
+ { Pragma.InstancingOptions(InstancingOptionList()) },
+ { Pragma.DOTSInstancing },
+ { Pragma.Vertex("vert") },
+ { Pragma.Fragment("frag") },
+ };
+
+ public static readonly PragmaCollection DOTSForward = new PragmaCollection
+ {
+ { Pragma.Target(ShaderModel.Target45) },
+ { Pragma.ExcludeRenderers(new[] {Platform.GLES3, Platform.GLCore}) },
+ { Pragma.MultiCompileInstancing },
+ { Pragma.MultiCompileFog },
+ { Pragma.InstancingOptions(InstancingOptionList()) },
+ { Pragma.DOTSInstancing },
+ { Pragma.Vertex("vert") },
+ { Pragma.Fragment("frag") },
+ };
+
+ public static readonly PragmaCollection DOTSGBuffer = new PragmaCollection
+ {
+ { Pragma.Target(ShaderModel.Target45) },
+ { Pragma.ExcludeRenderers(new[] { Platform.GLES3, Platform.GLCore }) },
+ { Pragma.MultiCompileInstancing },
+ { Pragma.MultiCompileFog },
+ { Pragma.InstancingOptions(InstancingOptionList()) },
+ { Pragma.DOTSInstancing },
+ { Pragma.Vertex("vert") },
+ { Pragma.Fragment("frag") },
+ };
+ }
+ #endregion
+
+ #region Passes
+ internal static class TerrainLitPasses
+ {
+ public static void AddReceiveShadowsControlToPass(ref PassDescriptor pass, UniversalTarget target, bool receiveShadows)
+ {
+ if (target.allowMaterialOverride)
+ pass.keywords.Add(TerrainLitKeywords.ReceiveShadowsOff);
+ else if (!receiveShadows)
+ pass.defines.Add(TerrainLitKeywords.ReceiveShadowsOff, 1);
+ }
+
+ public static PassDescriptor Forward(UniversalTarget target, bool blendModePreserveSpecular, PragmaCollection pragmas = null)
+ {
+ var result = new PassDescriptor()
+ {
+ // Definition
+ displayName = "Universal Forward",
+ referenceName = "SHADERPASS_FORWARD",
+ lightMode = "UniversalForward",
+ useInPreview = true,
+
+ // Template
+ passTemplatePath = TerrainLitTemplate.kPassTemplate,
+ sharedTemplateDirectories = TerrainLitTemplate.kSharedTemplateDirectories,
+
+ // Port Mask
+ validVertexBlocks = TerrainBlockMasks.Vertex,
+ validPixelBlocks = TerrainBlockMasks.FragmentLit,
+
+ // Fields
+ structs = TerrainStructCollections.Default,
+ requiredFields = TerrainRequiredFields.Forward,
+ fieldDependencies = CoreFieldDependencies.Default,
+
+ // Conditional State
+ renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular),
+ pragmas = pragmas ?? TerrainCorePragmas.Forward,
+ defines = new DefineCollection() { CoreDefines.UseFragmentFog, },
+ keywords = new KeywordCollection() { TerrainLitKeywords.Forward },
+ includes = TerrainCoreIncludes.Forward,
+
+ // Custom Interpolator Support
+ customInterpolators = CoreCustomInterpDescriptors.Common
+ };
+ result.defines.Add(TerrainDefines.TerrainEnabled, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat01, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat23, 1);
+ result.keywords.Add(TerrainDefines.TerrainNormalmap);
+ result.keywords.Add(TerrainDefines.TerrainMaskmap);
+ result.keywords.Add(TerrainDefines.TerrainBlendHeight);
+ result.keywords.Add(TerrainDefines.TerrainInstancedPerPixelNormal);
+ result.defines.Add(TerrainDefines.MetallicSpecGlossMap, 1);
+ result.defines.Add(TerrainDefines.SmoothnessTextureAlbedoChannelA, 1);
+ result.defines.Add(TerrainDefines.TerrainAlphaClipEnable, target.alphaClip?1:0);
+
+ CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular);
+ AddReceiveShadowsControlToPass(ref result, target, target.receiveShadows);
+
+ return result;
+ }
+
+ // Deferred only in SM4.5, MRT not supported in GLES2
+ public static PassDescriptor GBuffer(UniversalTarget target, bool blendModePreserveSpecular)
+ {
+ var result = new PassDescriptor
+ {
+ // Definition
+ displayName = "GBuffer",
+ referenceName = "SHADERPASS_GBUFFER",
+ lightMode = "UniversalGBuffer",
+
+ // Template
+ passTemplatePath = TerrainLitTemplate.kPassTemplate,
+ sharedTemplateDirectories = TerrainLitTemplate.kSharedTemplateDirectories,
+
+ // Port Mask
+ validVertexBlocks = TerrainBlockMasks.Vertex,
+ validPixelBlocks = TerrainBlockMasks.FragmentLit,
+
+ // Fields
+ structs = TerrainStructCollections.Default,
+ requiredFields = TerrainRequiredFields.GBuffer,
+ fieldDependencies = CoreFieldDependencies.Default,
+
+ // Conditional State
+ renderStates = CoreRenderStates.UberSwitchedRenderState(target, blendModePreserveSpecular),
+ pragmas = TerrainCorePragmas.DOTSGBuffer,
+ defines = new DefineCollection() { CoreDefines.UseFragmentFog },
+ keywords = new KeywordCollection() { TerrainLitKeywords.GBuffer },
+ includes = TerrainCoreIncludes.GBuffer,
+
+ // Custom Interpolator Support
+ customInterpolators = CoreCustomInterpDescriptors.Common
+ };
+
+ result.defines.Add(TerrainDefines.TerrainEnabled, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat01, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat23, 1);
+ result.keywords.Add(TerrainDefines.TerrainNormalmap);
+ result.keywords.Add(TerrainDefines.TerrainMaskmap);
+ result.keywords.Add(TerrainDefines.TerrainBlendHeight);
+ result.keywords.Add(TerrainDefines.TerrainInstancedPerPixelNormal);
+ result.defines.Add(TerrainDefines.MetallicSpecGlossMap, 1);
+ result.defines.Add(TerrainDefines.SmoothnessTextureAlbedoChannelA, 1);
+ result.defines.Add(TerrainDefines.TerrainAlphaClipEnable, target.alphaClip?1:0);
+
+ CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular);
+ AddReceiveShadowsControlToPass(ref result, target, target.receiveShadows);
+
+ return result;
+ }
+
+ public static PassDescriptor ShadowCaster(UniversalTarget target)
+ {
+ var result = new PassDescriptor()
+ {
+ // Definition
+ displayName = "ShadowCaster",
+ referenceName = "SHADERPASS_SHADOWCASTER",
+ lightMode = "ShadowCaster",
+
+ // Template
+ passTemplatePath = TerrainLitTemplate.kPassTemplate,
+ sharedTemplateDirectories = TerrainLitTemplate.kSharedTemplateDirectories,
+
+ // Port Mask
+ validVertexBlocks = TerrainBlockMasks.Vertex,
+ validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly,
+
+ // Fields
+ structs = TerrainStructCollections.Default,
+ requiredFields = TerrainRequiredFields.ShadowCaster,
+ fieldDependencies = CoreFieldDependencies.Default,
+
+ // Conditional State
+ renderStates = CoreRenderStates.ShadowCaster(target),
+ pragmas = TerrainCorePragmas.Instanced,
+ defines = new DefineCollection(),
+ keywords = new KeywordCollection() { CoreKeywords.ShadowCaster, },
+ includes = TerrainCoreIncludes.ShadowCaster,
+
+ // Custom Interpolator Support
+ customInterpolators = CoreCustomInterpDescriptors.Common
+ };
+
+ result.defines.Add(TerrainDefines.TerrainEnabled, 1);
+ result.defines.Add(TerrainDefines.TerrainAlphaClipEnable, target.alphaClip?1:0);
+
+ // CorePasses.AddTargetSurfaceControlsToPass(ref result, target, blendModePreserveSpecular);
+ CorePasses.AddAlphaClipControlToPass(ref result, target);
+
+ return result;
+ }
+
+ public static PassDescriptor DepthOnly(UniversalTarget target)
+ {
+ var result = new PassDescriptor()
+ {
+ // Definition
+ displayName = "DepthOnly",
+ referenceName = "SHADERPASS_DEPTHONLY",
+ lightMode = "DepthOnly",
+ useInPreview = true,
+
+ // Template
+ passTemplatePath = TerrainLitTemplate.kPassTemplate,
+ sharedTemplateDirectories = TerrainLitTemplate.kSharedTemplateDirectories,
+
+ // Port Mask
+ validVertexBlocks = TerrainBlockMasks.Vertex,
+ validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly,
+
+ // Fields
+ structs = TerrainStructCollections.Default,
+ requiredFields = TerrainRequiredFields.DepthOnly,
+ fieldDependencies = CoreFieldDependencies.Default,
+
+ // Conditional State
+ renderStates = CoreRenderStates.DepthOnly(target),
+ pragmas = TerrainCorePragmas.Instanced,
+ defines = new DefineCollection(),
+ keywords = new KeywordCollection() { },
+ includes = TerrainCoreIncludes.DepthOnly,
+
+ // Custom Interpolator Support
+ customInterpolators = CoreCustomInterpDescriptors.Common
+ };
+
+ result.defines.Add(TerrainDefines.TerrainEnabled, 1);
+ result.defines.Add(TerrainDefines.TerrainAlphaClipEnable, target.alphaClip?1:0);
+
+ CorePasses.AddAlphaClipControlToPass(ref result, target);
+
+ return result;
+ }
+
+ public static PassDescriptor DepthNormal(UniversalTarget target)
+ {
+ var result = new PassDescriptor()
+ {
+ // Definition
+ displayName = "DepthNormals",
+ referenceName = "SHADERPASS_DEPTHNORMALS",
+ lightMode = "DepthNormals",
+ useInPreview = false,
+
+ // Template
+ passTemplatePath = TerrainLitTemplate.kPassTemplate,
+ sharedTemplateDirectories = TerrainLitTemplate.kSharedTemplateDirectories,
+
+ // Port Mask
+ validVertexBlocks = TerrainBlockMasks.Vertex,
+ validPixelBlocks = CoreBlockMasks.FragmentDepthNormals,
+
+ // Fields
+ structs = TerrainStructCollections.Default,
+ requiredFields = TerrainRequiredFields.DepthNormals,
+ fieldDependencies = CoreFieldDependencies.Default,
+
+ // Conditional State
+ renderStates = CoreRenderStates.DepthNormalsOnly(target),
+ pragmas = TerrainCorePragmas.Instanced,
+ defines = new DefineCollection(),
+ keywords = new KeywordCollection() { TerrainSubShaders.AlphaTestOn, },
+ includes = TerrainCoreIncludes.DepthNormalsOnly,
+
+ // Custom Interpolator Support
+ customInterpolators = CoreCustomInterpDescriptors.Common
+ };
+
+ result.defines.Add(TerrainDefines.TerrainEnabled, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat01, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat23, 1);
+ result.defines.Add(TerrainDefines.TerrainAlphaClipEnable, target.alphaClip?1:0);
+ result.keywords.Add(TerrainDefines.TerrainNormalmap);
+ result.keywords.Add(TerrainDefines.TerrainBlendHeight);
+ result.keywords.Add(TerrainDefines.TerrainInstancedPerPixelNormal);
+
+ CorePasses.AddAlphaClipControlToPass(ref result, target);
+
+ return result;
+ }
+
+ public static PassDescriptor Meta(UniversalTarget target)
+ {
+ var result = new PassDescriptor()
+ {
+ // Definition
+ displayName = "Meta",
+ referenceName = "SHADERPASS_META",
+ lightMode = "Meta",
+
+ // Template
+ passTemplatePath = TerrainLitTemplate.kPassTemplate,
+ sharedTemplateDirectories = TerrainLitTemplate.kSharedTemplateDirectories,
+
+ // Port Mask
+ validVertexBlocks = TerrainBlockMasks.Vertex,
+ validPixelBlocks = TerrainBlockMasks.FragmentMeta,
+
+ // Fields
+ structs = TerrainStructCollections.Meta,
+ requiredFields = TerrainRequiredFields.Meta,
+ fieldDependencies = CoreFieldDependencies.Default,
+
+ // Conditional State
+ renderStates = CoreRenderStates.Meta,
+ pragmas = TerrainCorePragmas.Default,
+ defines = new DefineCollection() { CoreDefines.UseFragmentFog },
+ keywords = new KeywordCollection() { CoreKeywordDescriptors.EditorVisualization, TerrainSubShaders.AlphaTestOn, },
+ includes = TerrainCoreIncludes.Meta,
+
+ // Custom Interpolator Support
+ customInterpolators = CoreCustomInterpDescriptors.Common
+ };
+
+ result.defines.Add(TerrainDefines.TerrainEnabled, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat01, 1);
+ result.defines.Add(TerrainDefines.TerrainSplat23, 1);
+ result.defines.Add(TerrainDefines.MetallicSpecGlossMap, 1);
+ result.defines.Add(TerrainDefines.SmoothnessTextureAlbedoChannelA, 1);
+ result.defines.Add(TerrainDefines.TerrainAlphaClipEnable, target.alphaClip?1:0);
+
+ CorePasses.AddAlphaClipControlToPass(ref result, target);
+
+ return result;
+ }
+
+ public static PassDescriptor SceneSelection(UniversalTarget target)
+ {
+ var result = new PassDescriptor()
+ {
+ // Definition
+ displayName = "SceneSelectionPass",
+ referenceName = "SHADERPASS_DEPTHONLY",
+ lightMode = "SceneSelectionPass",
+ useInPreview = false,
+
+ // Template
+ passTemplatePath = TerrainLitTemplate.kPassTemplate,
+ sharedTemplateDirectories = TerrainLitTemplate.kSharedTemplateDirectories,
+
+ // Port Mask
+ validVertexBlocks = TerrainBlockMasks.Vertex,
+ validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly,
+
+ // Fields
+ structs = TerrainStructCollections.Default,
+ requiredFields = TerrainRequiredFields.DepthOnly,
+ fieldDependencies = CoreFieldDependencies.Default,
+
+ // Conditional State
+ renderStates = CoreRenderStates.SceneSelection(target),
+ pragmas = TerrainCorePragmas.Default,
+ defines = new DefineCollection { CoreDefines.SceneSelection, },
+ keywords = new KeywordCollection() { TerrainSubShaders.AlphaTestOn, },
+ includes = TerrainCoreIncludes.SceneSelection,
+
+ // Custom Interpolator Support
+ customInterpolators = CoreCustomInterpDescriptors.Common
+ };
+
+ result.defines.Add(TerrainDefines.TerrainEnabled, 1);
+ result.defines.Add(TerrainDefines.TerrainAlphaClipEnable, target.alphaClip?1:0);
+
+ CorePasses.AddAlphaClipControlToPass(ref result, target);
+
+ return result;
+ }
+
+ public static PassDescriptor ScenePicking(UniversalTarget target)
+ {
+ var result = new PassDescriptor()
+ {
+ // Definition
+ displayName = "ScenePickingPass",
+ referenceName = "SHADERPASS_DEPTHONLY",
+ lightMode = "Picking",
+ useInPreview = false,
+
+ // Template
+ passTemplatePath = TerrainLitTemplate.kPassTemplate,
+ sharedTemplateDirectories = TerrainLitTemplate.kSharedTemplateDirectories,
+
+ // Port Mask
+ validVertexBlocks = TerrainBlockMasks.Vertex,
+ validPixelBlocks = CoreBlockMasks.FragmentAlphaOnly,
+
+ // Fields
+ structs = TerrainStructCollections.Default,
+ requiredFields = TerrainRequiredFields.DepthOnly,
+ fieldDependencies = CoreFieldDependencies.Default,
+
+ // Conditional State
+ renderStates = CoreRenderStates.ScenePicking(target),
+ pragmas = TerrainCorePragmas.Default,
+ defines = new DefineCollection { CoreDefines.ScenePicking, },
+ keywords = new KeywordCollection() { TerrainSubShaders.AlphaTestOn, },
+ includes = TerrainCoreIncludes.ScenePicking,
+
+ // Custom Interpolator Support
+ customInterpolators = CoreCustomInterpDescriptors.Common
+ };
+
+ result.defines.Add(TerrainDefines.TerrainEnabled, 1);
+ result.defines.Add(TerrainDefines.TerrainAlphaClipEnable, target.alphaClip?1:0);
+
+ CorePasses.AddAlphaClipControlToPass(ref result, target);
+
+ return result;
+ }
+ }
+ #endregion
+
+ #region Dependencies
+ static class TerrainDependencies
+ {
+ public static ShaderDependency AddPassShader()
+ {
+ return new ShaderDependency()
+ {
+ dependencyName = "AddPassShader",
+ shaderName = "Hidden/{Name}_AddPass",
+ };
+ }
+ public static ShaderDependency BaseMapShader()
+ {
+ return new ShaderDependency()
+ {
+ dependencyName = "BaseMapShader",
+ shaderName = "Hidden/Universal Render Pipeline/Terrain/Lit (Base Pass)",
+ };
+ }
+ public static ShaderDependency BaseMapGenShader()
+ {
+ return new ShaderDependency()
+ {
+ dependencyName = "BaseMapGenShader",
+ shaderName = "Hidden/{Name}_BaseMapGen",
+ };
+ }
+ }
+ #endregion
+
+ #region PortMasks
+ static class TerrainBlockMasks
+ {
+ public static readonly BlockFieldDescriptor[] Vertex = new BlockFieldDescriptor[]
+ {
+ BlockFields.VertexDescription.Position,
+ };
+
+ public static readonly BlockFieldDescriptor[] FragmentLit = new BlockFieldDescriptor[]
+ {
+ BlockFields.SurfaceDescription.BaseColor,
+ BlockFields.SurfaceDescription.NormalOS,
+ BlockFields.SurfaceDescription.NormalTS,
+ BlockFields.SurfaceDescription.NormalWS,
+ BlockFields.SurfaceDescription.Emission,
+ BlockFields.SurfaceDescription.Metallic,
+ BlockFields.SurfaceDescription.Smoothness,
+ BlockFields.SurfaceDescription.Occlusion,
+ BlockFields.SurfaceDescription.Alpha,
+ BlockFields.SurfaceDescription.AlphaClipThreshold,
+ };
+
+ public static readonly BlockFieldDescriptor[] FragmentMeta = new BlockFieldDescriptor[]
+ {
+ BlockFields.SurfaceDescription.BaseColor,
+ BlockFields.SurfaceDescription.Emission,
+ BlockFields.SurfaceDescription.Alpha,
+ BlockFields.SurfaceDescription.AlphaClipThreshold,
+ };
+ }
+ #endregion
+
+ #region RequiredField
+ static class TerrainRequiredFields
+ {
+ public static readonly FieldCollection Forward = new FieldCollection()
+ {
+ StructFields.Attributes.uv0,
+ StructFields.Attributes.instanceID,
+ StructFields.Varyings.positionWS,
+ StructFields.Varyings.normalWS,
+ StructFields.Varyings.texCoord0,
+ StructFields.Varyings.instanceID,
+ TerrainStructFields.Varyings.uvSplat01,
+ TerrainStructFields.Varyings.uvSplat23,
+ TerrainStructFields.Varyings.normalViewDir,
+ TerrainStructFields.Varyings.tangentViewDir,
+ TerrainStructFields.Varyings.bitangentViewDir,
+ UniversalStructFields.Varyings.staticLightmapUV,
+ UniversalStructFields.Varyings.dynamicLightmapUV,
+ UniversalStructFields.Varyings.sh,
+ UniversalStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency
+ UniversalStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency
+ TerrainStructFields.SurfaceDescriptionInputs.uvSplat01,
+ TerrainStructFields.SurfaceDescriptionInputs.uvSplat23,
+ };
+
+ public static readonly FieldCollection GBuffer = new FieldCollection()
+ {
+ StructFields.Attributes.uv0,
+ StructFields.Attributes.instanceID,
+ StructFields.Varyings.positionWS,
+ StructFields.Varyings.normalWS,
+ StructFields.Varyings.texCoord0,
+ StructFields.Varyings.instanceID,
+ TerrainStructFields.Varyings.uvSplat01,
+ TerrainStructFields.Varyings.uvSplat23,
+ TerrainStructFields.Varyings.normalViewDir,
+ TerrainStructFields.Varyings.tangentViewDir,
+ TerrainStructFields.Varyings.bitangentViewDir,
+ UniversalStructFields.Varyings.staticLightmapUV,
+ UniversalStructFields.Varyings.dynamicLightmapUV,
+ UniversalStructFields.Varyings.sh,
+ UniversalStructFields.Varyings.fogFactorAndVertexLight, // fog and vertex lighting, vert input is dependency
+ UniversalStructFields.Varyings.shadowCoord, // shadow coord, vert input is dependency
+ TerrainStructFields.SurfaceDescriptionInputs.uvSplat01,
+ TerrainStructFields.SurfaceDescriptionInputs.uvSplat23,
+ };
+
+ public static readonly FieldCollection ShadowCaster = new FieldCollection()
+ {
+ StructFields.Attributes.uv0,
+ StructFields.Attributes.instanceID,
+ StructFields.Varyings.texCoord0,
+ StructFields.Varyings.instanceID,
+ };
+
+ public static readonly FieldCollection DepthOnly = new FieldCollection()
+ {
+ StructFields.Attributes.uv0,
+ StructFields.Attributes.instanceID,
+ StructFields.Varyings.texCoord0,
+ StructFields.Varyings.instanceID,
+ };
+
+ public static readonly FieldCollection DepthNormals = new FieldCollection()
+ {
+ StructFields.Attributes.uv0,
+ StructFields.Attributes.instanceID,
+ StructFields.Varyings.normalWS,
+ StructFields.Varyings.texCoord0,
+ StructFields.Varyings.instanceID,
+ TerrainStructFields.Varyings.uvSplat01,
+ TerrainStructFields.Varyings.uvSplat23,
+ TerrainStructFields.Varyings.normalViewDir,
+ TerrainStructFields.Varyings.tangentViewDir,
+ TerrainStructFields.Varyings.bitangentViewDir,
+ TerrainStructFields.SurfaceDescriptionInputs.uvSplat01,
+ TerrainStructFields.SurfaceDescriptionInputs.uvSplat23,
+ };
+
+ public static readonly FieldCollection Meta = new FieldCollection()
+ {
+ StructFields.Attributes.positionOS,
+ StructFields.Attributes.normalOS,
+ StructFields.Attributes.uv0, //
+ StructFields.Attributes.uv1, // needed for meta vertex position
+ StructFields.Attributes.uv2, // needed for meta UVs
+ StructFields.Attributes.instanceID, // needed for rendering instanced terrain
+ TerrainStructFields.Varyings.uvSplat01,
+ TerrainStructFields.Varyings.uvSplat23,
+ StructFields.Varyings.positionCS,
+ StructFields.Varyings.texCoord0, // needed for meta UVs
+ StructFields.Varyings.texCoord1, // VizUV
+ StructFields.Varyings.texCoord2, // LightCoord
+ StructFields.Varyings.instanceID,
+ TerrainStructFields.SurfaceDescriptionInputs.uvSplat01,
+ TerrainStructFields.SurfaceDescriptionInputs.uvSplat23,
+ };
+ }
+ #endregion
+
+ #region Defines
+ static class TerrainDefines
+ {
+ public static readonly KeywordDescriptor TerrainEnabled = new KeywordDescriptor()
+ {
+ displayName = "Universal Terrain",
+ referenceName = "UNIVERSAL_TERRAIN_ENABLED",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ };
+
+ public static readonly KeywordDescriptor TerrainSplat01 = new KeywordDescriptor()
+ {
+ displayName = "Universal Terrain Splat01",
+ referenceName = "UNIVERSAL_TERRAIN_SPLAT01",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ };
+
+ public static readonly KeywordDescriptor TerrainSplat23 = new KeywordDescriptor()
+ {
+ displayName = "Universal Terrain Splat23",
+ referenceName = "UNIVERSAL_TERRAIN_SPLAT23",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ };
+
+ public static readonly KeywordDescriptor TerrainAddPass = new KeywordDescriptor()
+ {
+ displayName = "Universal Terrain AddPass",
+ referenceName = "TERRAIN_SPLAT_ADDPASS",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ };
+
+ public static KeywordDescriptor TerrainNormalmap = new KeywordDescriptor()
+ {
+ displayName = "Terrain Normal Map",
+ referenceName = "_NORMALMAP",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ };
+
+ public static KeywordDescriptor TerrainMaskmap = new KeywordDescriptor()
+ {
+ displayName = "Terrain Mask Map",
+ referenceName = "_MASKMAP",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ stages = KeywordShaderStage.Fragment,
+ };
+
+ public static KeywordDescriptor TerrainBlendHeight = new KeywordDescriptor()
+ {
+ displayName = "Terrain Blend Height",
+ referenceName = "_TERRAIN_BLEND_HEIGHT",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ stages = KeywordShaderStage.Fragment,
+ };
+
+ public static KeywordDescriptor TerrainInstancedPerPixelNormal = new KeywordDescriptor()
+ {
+ displayName = "Instanced PerPixel Normal",
+ referenceName = "_TERRAIN_INSTANCED_PERPIXEL_NORMAL",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ };
+
+ public static readonly KeywordDescriptor MetallicSpecGlossMap = new KeywordDescriptor()
+ {
+ displayName = "Metallic SpecGloss Map",
+ referenceName = "_METALLICSPECGLOSSMAP",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ };
+
+ public static readonly KeywordDescriptor SmoothnessTextureAlbedoChannelA = new KeywordDescriptor()
+ {
+ displayName = "Smoothness Texture Albedo Channel A",
+ referenceName = "_SMOOTHNESS_TEXTURE_ALBEDO_CHANNEL_A",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ };
+
+ public static readonly KeywordDescriptor TerrainBaseMapGen = new KeywordDescriptor()
+ {
+ displayName = "Terrain Base Map Generation",
+ referenceName = "_TERRAIN_BASEMAP_GEN",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ };
+
+ public static readonly KeywordDescriptor TerrainAlphaClipEnable = new KeywordDescriptor()
+ {
+ displayName = "Terrain Alpha Clip Enable",
+ referenceName = "_TERRAIN_SG_ALPHA_CLIP",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ stages = KeywordShaderStage.Fragment,
+ };
+ }
+ #endregion
+
+ #region Keywords
+ static class TerrainLitKeywords
+ {
+ public static readonly KeywordDescriptor ReceiveShadowsOff = new KeywordDescriptor()
+ {
+ displayName = "Receive Shadows Off",
+ referenceName = ShaderKeywordStrings._RECEIVE_SHADOWS_OFF,
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.ShaderFeature,
+ scope = KeywordScope.Local,
+ };
+
+ public static readonly KeywordDescriptor ScreenSpaceAmbientOcclusion = new KeywordDescriptor()
+ {
+ displayName = "Screen Space Ambient Occlusion",
+ referenceName = "_SCREEN_SPACE_OCCLUSION",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.MultiCompile,
+ scope = KeywordScope.Global,
+ };
+
+ public static readonly KeywordCollection Forward = new KeywordCollection
+ {
+ { ScreenSpaceAmbientOcclusion },
+ { CoreKeywordDescriptors.StaticLightmap },
+ { CoreKeywordDescriptors.DynamicLightmap },
+ { CoreKeywordDescriptors.DirectionalLightmapCombined },
+ { CoreKeywordDescriptors.MainLightShadows },
+ { CoreKeywordDescriptors.AdditionalLights },
+ { CoreKeywordDescriptors.AdditionalLightShadows },
+ { CoreKeywordDescriptors.ReflectionProbeBlending },
+ { CoreKeywordDescriptors.ReflectionProbeBoxProjection },
+ { CoreKeywordDescriptors.ShadowsSoft },
+ { CoreKeywordDescriptors.LightmapShadowMixing },
+ { CoreKeywordDescriptors.ShadowsShadowmask },
+ { CoreKeywordDescriptors.ClusterLightLoop },
+ { CoreKeywordDescriptors.DBuffer },
+ { CoreKeywordDescriptors.LightLayers },
+ { CoreKeywordDescriptors.DebugDisplay },
+ { CoreKeywordDescriptors.LightCookies },
+ };
+
+ public static readonly KeywordCollection GBuffer = new KeywordCollection
+ {
+ { CoreKeywordDescriptors.StaticLightmap },
+ { CoreKeywordDescriptors.DynamicLightmap },
+ { CoreKeywordDescriptors.DirectionalLightmapCombined },
+ { CoreKeywordDescriptors.MainLightShadows },
+ { CoreKeywordDescriptors.ShadowsSoft },
+ { CoreKeywordDescriptors.LightmapShadowMixing },
+ { CoreKeywordDescriptors.MixedLightingSubtractive },
+ { CoreKeywordDescriptors.DBuffer },
+ { CoreKeywordDescriptors.GBufferNormalsOct },
+ { CoreKeywordDescriptors.LightLayers },
+ { CoreKeywordDescriptors.RenderPassEnabled },
+ { CoreKeywordDescriptors.DebugDisplay },
+ };
+ }
+ #endregion
+
+ #region Includes
+ static class TerrainCoreIncludes
+ {
+ public static readonly string kVaryings = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Varyings.hlsl";
+ public static readonly string kShaderPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShaderPass.hlsl";
+ public static readonly string kShadows = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Shadows.hlsl";
+ public static readonly string kMetaInput = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/MetaInput.hlsl";
+ public static readonly string kDepthOnlyPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/DepthOnlyPass.hlsl";
+ public static readonly string kDepthNormalsOnlyPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/DepthNormalsOnlyPass.hlsl";
+ public static readonly string kShadowCasterPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/ShadowCasterPass.hlsl";
+ public static readonly string kForwardPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRForwardPass.hlsl";
+ public static readonly string kGBuffer = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/GBufferOutput.hlsl";
+ public static readonly string kPBRGBufferPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/Terrain/PBRGBufferPass.hlsl";
+ public static readonly string kLightingMetaPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/LightingMetaPass.hlsl";
+ public static readonly string kSelectionPickingPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/SelectionPickingPass.hlsl";
+
+ public static readonly string kTerrainLitInput = "Packages/com.unity.render-pipelines.universal/Shaders/Terrain/TerrainLitInput.hlsl";
+ public static readonly string kTerrainPassUtils = "Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassUtils.hlsl";
+ public static readonly string kRenderingLayers = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/RenderingLayers.hlsl";
+
+ public static readonly IncludeCollection CorePostgraph = new IncludeCollection
+ {
+ { kShaderPass, IncludeLocation.Pregraph },
+ { kRenderingLayers, IncludeLocation.Pregraph, true },
+ { kVaryings, IncludeLocation.Postgraph },
+ };
+
+ public static readonly IncludeCollection Forward = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { TerrainCoreIncludes.kShadows, IncludeLocation.Pregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { CoreIncludes.DBufferPregraph },
+ { TerrainCoreIncludes.kTerrainLitInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainPassUtils, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { TerrainCoreIncludes.CorePostgraph },
+ { TerrainCoreIncludes.kForwardPass, IncludeLocation.Postgraph },
+ };
+
+ public static readonly IncludeCollection DepthOnly = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { TerrainCoreIncludes.kTerrainLitInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainPassUtils, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { TerrainCoreIncludes.CorePostgraph },
+ { TerrainCoreIncludes.kDepthOnlyPass, IncludeLocation.Postgraph },
+ };
+
+ public static readonly IncludeCollection DepthNormalsOnly = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { TerrainCoreIncludes.kTerrainLitInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainPassUtils, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { TerrainCoreIncludes.CorePostgraph },
+ { TerrainCoreIncludes.kDepthNormalsOnlyPass, IncludeLocation.Postgraph },
+ };
+
+ public static readonly IncludeCollection ShadowCaster = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { TerrainCoreIncludes.kTerrainLitInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainPassUtils, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { TerrainCoreIncludes.CorePostgraph },
+ { TerrainCoreIncludes.kShadowCasterPass, IncludeLocation.Postgraph },
+ };
+
+ public static readonly IncludeCollection GBuffer = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { TerrainCoreIncludes.kShadows, IncludeLocation.Pregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { CoreIncludes.DBufferPregraph },
+ { TerrainCoreIncludes.kTerrainLitInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainPassUtils, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { TerrainCoreIncludes.CorePostgraph },
+ { TerrainCoreIncludes.kGBuffer, IncludeLocation.Postgraph },
+ { TerrainCoreIncludes.kPBRGBufferPass, IncludeLocation.Postgraph },
+ };
+
+ public static readonly IncludeCollection Meta = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { TerrainCoreIncludes.kMetaInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainLitInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainPassUtils, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { TerrainCoreIncludes.CorePostgraph },
+ { TerrainCoreIncludes.kLightingMetaPass, IncludeLocation.Postgraph },
+ };
+
+ public static readonly IncludeCollection SceneSelection = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { TerrainCoreIncludes.kTerrainLitInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainPassUtils, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { TerrainCoreIncludes.CorePostgraph },
+ { TerrainCoreIncludes.kSelectionPickingPass, IncludeLocation.Postgraph },
+ };
+
+ public static readonly IncludeCollection ScenePicking = new IncludeCollection
+ {
+ // Pre-graph
+ { CoreIncludes.CorePregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { TerrainCoreIncludes.kTerrainLitInput, IncludeLocation.Pregraph },
+ { TerrainCoreIncludes.kTerrainPassUtils, IncludeLocation.Pregraph },
+
+ // Post-graph
+ { TerrainCoreIncludes.CorePostgraph },
+ { TerrainCoreIncludes.kSelectionPickingPass, IncludeLocation.Postgraph },
+ };
+ }
+ #endregion
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.cs.meta
new file mode 100644
index 00000000000..a4366fc2762
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalTerrainLitSubTarget.cs.meta
@@ -0,0 +1,11 @@
+fileFormatVersion: 2
+guid: 928853c33a90408408408d3b4bfb96e8
+MonoImporter:
+ externalObjects: {}
+ serializedVersion: 2
+ defaultReferences: []
+ executionOrder: 0
+ icon: {instanceID: 0}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUISubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUISubTarget.cs
new file mode 100644
index 00000000000..fe6a61cbae9
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUISubTarget.cs
@@ -0,0 +1,113 @@
+using UnityEditor.ShaderGraph;
+using System;
+using System.Collections.Generic;
+using UnityEditor.Rendering.UITK.ShaderGraph;
+
+namespace UnityEditor.Rendering.Universal.ShaderGraph
+{
+ class UniversalUISubTarget: UISubTarget
+ {
+ static readonly GUID kSourceCodeGuid = new GUID("b1197b10aa62577498d67cffe1d3bd43"); // UniversalUISubTarget.cs
+
+ static readonly string kUITKPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UITKPass.hlsl";
+ public override void Setup(ref TargetSetupContext context)
+ {
+ base.Setup(ref context);
+ context.AddAssetDependency(kSourceCodeGuid, AssetCollection.Flags.SourceDependency);
+ }
+ public override bool IsActive() => true;
+
+ // We don't need the save context / update materials for now
+ public override object saveContext => null;
+
+ protected override string pipelineTag => UniversalTarget.kPipelineTag;
+
+ protected override IncludeCollection pregraphIncludes => new IncludeCollection
+ {
+ { CoreIncludes.CorePregraph },
+ { kInstancing, IncludeLocation.Pregraph },
+ { CoreIncludes.ShaderGraphPregraph },
+ { kUIShim, IncludeLocation.Pregraph }
+ };
+ protected override IncludeCollection postgraphIncludes => new IncludeCollection
+ {
+ {kUITKPass, IncludeLocation.Postgraph},
+ };
+
+ public UniversalUISubTarget()
+ {
+ displayName = "UI";
+ }
+
+ HashSet m_UnsupportedNodes;
+
+ public override void GetFields(ref TargetFieldContext context)
+ {
+ context.AddField(Fields.GraphVertex);
+ context.AddField(Fields.GraphPixel);
+
+ base.GetFields(ref context);
+
+ switch (target.alphaMode)
+ {
+ case AlphaMode.Premultiply:
+ context.AddField(UniversalFields.BlendPremultiply);
+ break;
+ case AlphaMode.Additive:
+ context.AddField(UniversalFields.BlendAdd);
+ break;
+ case AlphaMode.Multiply:
+ context.AddField(UniversalFields.BlendMultiply);
+ break;
+ default:
+ context.AddField(Fields.BlendAlpha);
+ break;
+ }
+
+ }
+
+ public override PassDescriptor GenerateUIPassDescriptor(bool isSRP)
+ {
+ PassDescriptor passDescriptor = base.GenerateUIPassDescriptor(isSRP);
+
+ var result = new RenderStateCollection();
+
+ result.Add(RenderState.Cull(Cull.Off));
+ result.Add(RenderState.ZWrite(ZWrite.Off));
+
+ switch (target.alphaMode)
+ {
+ case AlphaMode.Alpha:
+ result.Add(RenderState.Blend(Blend.SrcAlpha, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha));
+ break;
+ case AlphaMode.Premultiply:
+ result.Add(RenderState.Blend(Blend.One, Blend.OneMinusSrcAlpha, Blend.One, Blend.OneMinusSrcAlpha));
+ break;
+ case AlphaMode.Additive:
+ result.Add(RenderState.Blend(Blend.SrcAlpha, Blend.One, Blend.One, Blend.One));
+ break;
+ case AlphaMode.Multiply:
+ result.Add(RenderState.Blend(Blend.DstColor, Blend.OneMinusSrcAlpha, Blend.Zero, Blend.One));
+ break;
+ }
+
+ passDescriptor.renderStates = result;
+
+ return passDescriptor;
+ }
+
+ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Action onChange, Action registerUndo)
+ {
+ context.AddHelpBox(MessageType.Info, "This shader is intended for use with Unity's UI Toolkit. It has special requirements.\n\nStart with the UI > Render Type Branch node and connect its outputs to the Fragment node.");
+ context.AddProperty("Blending Mode", new UnityEngine.UIElements.EnumField(AlphaMode.Alpha) { value = target.alphaMode }, (evt) =>
+ {
+ if (Equals(target.alphaMode, evt.newValue))
+ return;
+
+ registerUndo("Change Blend");
+ target.alphaMode = (AlphaMode)evt.newValue;
+ onChange();
+ });
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUISubTarget.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUISubTarget.cs.meta
new file mode 100644
index 00000000000..358ee2d3270
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUISubTarget.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: b1197b10aa62577498d67cffe1d3bd43
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs
index 06368956d3f..b5c6dfbe9d4 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Targets/UniversalUnlitSubTarget.cs
@@ -4,6 +4,7 @@
using UnityEngine.Assertions;
using UnityEditor.ShaderGraph;
using UnityEditor.ShaderGraph.Legacy;
+using UnityEngine.UIElements;
using static UnityEditor.Rendering.Universal.ShaderGraph.SubShaderUtils;
using static Unity.Rendering.Universal.ShaderUtils;
@@ -15,6 +16,33 @@ sealed class UniversalUnlitSubTarget : UniversalSubTarget, ILegacyTarget
public override int latestVersion => 2;
+ [SerializeField]
+ bool m_KeepLightingVariants = false;
+
+ [SerializeField]
+ bool m_DefaultDecalBlending = true;
+
+ [SerializeField]
+ bool m_DefaultSSAO = true;
+
+ public bool keepLightingVariants
+ {
+ get => m_KeepLightingVariants;
+ set => m_KeepLightingVariants = value;
+ }
+
+ public bool defaultDecalBlending
+ {
+ get => m_DefaultDecalBlending;
+ set => m_DefaultDecalBlending = value;
+ }
+
+ public bool defaultSSAO
+ {
+ get => m_DefaultSSAO;
+ set => m_DefaultSSAO = value;
+ }
+
public UniversalUnlitSubTarget()
{
displayName = "Unlit";
@@ -96,6 +124,8 @@ public override void CollectShaderProperties(PropertyCollector collector, Genera
collector.AddFloatProperty(Property.AlphaClip, target.alphaClip ? 1.0f : 0.0f);
collector.AddFloatProperty(Property.SrcBlend, 1.0f); // always set by material inspector
collector.AddFloatProperty(Property.DstBlend, 0.0f); // always set by material inspector
+ collector.AddFloatProperty(Property.SrcBlendAlpha, 1.0f); // always set by material inspector, ok to have incorrect values here
+ collector.AddFloatProperty(Property.DstBlendAlpha, 0.0f); // always set by material inspector, ok to have incorrect values here
collector.AddToggleProperty(Property.ZWrite, (target.surfaceType == SurfaceType.Opaque));
collector.AddFloatProperty(Property.ZWriteControl, (float)target.zWriteControl);
collector.AddFloatProperty(Property.ZTest, (float)target.zTestMode); // ztest mode is designed to directly pass as ztest
@@ -120,6 +150,39 @@ public override void GetPropertiesGUI(ref TargetPropertyGUIContext context, Acti
var universalTarget = (target as UniversalTarget);
universalTarget.AddDefaultMaterialOverrideGUI(ref context, onChange, registerUndo);
universalTarget.AddDefaultSurfacePropertiesGUI(ref context, onChange, registerUndo, showReceiveShadows: false);
+
+ // Unlit option to add additional realtime lighting variants. Useful for custom lighting.
+ context.AddProperty("Keep Lighting Variants", new Toggle() { value = keepLightingVariants }, (evt) =>
+ {
+ if (Equals(keepLightingVariants, evt.newValue))
+ return;
+
+ registerUndo("Change Keep Lighting Variants");
+ keepLightingVariants = evt.newValue;
+ onChange();
+ });
+
+ // Unlit option to disable default decal blending behaviour.
+ context.AddProperty("Default Decal Blending", new Toggle() { value = defaultDecalBlending }, (evt) =>
+ {
+ if (Equals(defaultDecalBlending, evt.newValue))
+ return;
+
+ registerUndo("Change Default Decal Blending");
+ defaultDecalBlending = evt.newValue;
+ onChange();
+ });
+
+ // Unlit option to disable default SSAO behaviour.
+ context.AddProperty("Default SSAO", new Toggle() { value = defaultSSAO }, (evt) =>
+ {
+ if (Equals(defaultSSAO, evt.newValue))
+ return;
+
+ registerUndo("Change Default SSAO");
+ defaultSSAO = evt.newValue;
+ onChange();
+ });
}
public bool TryUpgradeFromMasterNode(IMasterNode1 masterNode, out Dictionary blockMap)
@@ -207,9 +270,35 @@ public static SubShaderDescriptor Unlit(UniversalTarget target, string renderTyp
}
#endregion
- #region Pass
+ #region Passes
static class UnlitPasses
{
+ internal static void AddLightingVariantsControlToPass(ref PassDescriptor pass, UniversalUnlitSubTarget unlitSubTarget)
+ {
+ if (unlitSubTarget.keepLightingVariants)
+ {
+ pass.includes.Add(UnlitIncludes.LightingIncludes);
+ pass.keywords.Add(UnlitKeywords.LightingVariants);
+ pass.defines.Add(UnlitDefines.LightingDefine, 1);
+ }
+ }
+
+ internal static void AddDefaultDecalBlendingControlToPass(ref PassDescriptor pass, UniversalUnlitSubTarget unlitSubTarget)
+ {
+ if (unlitSubTarget.defaultDecalBlending)
+ {
+ pass.defines.Add(UnlitDefines.DefaultDecalBlendingDefine, 1);
+ }
+ }
+
+ internal static void AddDefaultSSAOControlToPass(ref PassDescriptor pass, UniversalUnlitSubTarget unlitSubTarget)
+ {
+ if (unlitSubTarget.defaultSSAO)
+ {
+ pass.defines.Add(UnlitDefines.DefaultSSAODefine, 1);
+ }
+ }
+
public static PassDescriptor Forward(UniversalTarget target, KeywordCollection keywords)
{
var result = new PassDescriptor
@@ -247,6 +336,13 @@ public static PassDescriptor Forward(UniversalTarget target, KeywordCollection k
CorePasses.AddAlphaToMaskControlToPass(ref result, target);
CorePasses.AddLODCrossFadeControlToPass(ref result, target);
+ if (target.activeSubTarget is UniversalUnlitSubTarget unlitSubTarget)
+ {
+ UnlitPasses.AddLightingVariantsControlToPass(ref result, unlitSubTarget);
+ UnlitPasses.AddDefaultDecalBlendingControlToPass(ref result, unlitSubTarget);
+ UnlitPasses.AddDefaultSSAOControlToPass(ref result, unlitSubTarget);
+ }
+
return result;
}
@@ -370,6 +466,41 @@ static class UnlitRequiredFields
}
#endregion
+ #region Defines
+ static class UnlitDefines
+ {
+ public static readonly KeywordDescriptor LightingDefine = new KeywordDescriptor()
+ {
+ displayName = "Keep Lighting Variants",
+ referenceName = "UNLIT_REALTIME_LIGHTING",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ stages = KeywordShaderStage.Vertex | KeywordShaderStage.Fragment
+ };
+
+ public static readonly KeywordDescriptor DefaultDecalBlendingDefine = new KeywordDescriptor()
+ {
+ displayName = "Default Decal Blending",
+ referenceName = "UNLIT_DEFAULT_DECAL_BLENDING",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ stages = KeywordShaderStage.Fragment
+ };
+
+ public static readonly KeywordDescriptor DefaultSSAODefine = new KeywordDescriptor()
+ {
+ displayName = "Default SSAO",
+ referenceName = "UNLIT_DEFAULT_SSAO",
+ type = KeywordType.Boolean,
+ definition = KeywordDefinition.Predefined,
+ scope = KeywordScope.Local,
+ stages = KeywordShaderStage.Fragment
+ };
+ }
+ #endregion
+
#region Keywords
static class UnlitKeywords
{
@@ -382,8 +513,6 @@ static class UnlitKeywords
CoreKeywordDescriptors.DirectionalLightmapCombined,
CoreKeywordDescriptors.UseLegacyLightmaps,
CoreKeywordDescriptors.LightmapBicubicSampling,
- CoreKeywordDescriptors.ReflectionProbeRotation,
- CoreKeywordDescriptors.SampleGI,
CoreKeywordDescriptors.DBuffer,
CoreKeywordDescriptors.DebugDisplay,
CoreKeywordDescriptors.ScreenSpaceAmbientOcclusion,
@@ -397,6 +526,23 @@ static class UnlitKeywords
CoreKeywordDescriptors.GBufferNormalsOct,
CoreKeywordDescriptors.ShadowsShadowmask
};
+
+ public static readonly KeywordCollection LightingVariants = new KeywordCollection()
+ {
+ { CoreKeywordDescriptors.MainLightShadows },
+ { CoreKeywordDescriptors.AdditionalLights },
+ { CoreKeywordDescriptors.AdditionalLightShadows },
+ { CoreKeywordDescriptors.ReflectionProbeBlending },
+ { CoreKeywordDescriptors.ReflectionProbeBoxProjection },
+ { CoreKeywordDescriptors.ReflectionProbeAtlas },
+ { CoreKeywordDescriptors.ReflectionProbeRotation },
+ { CoreKeywordDescriptors.ShadowsSoft },
+ { CoreKeywordDescriptors.LightmapShadowMixing },
+ { CoreKeywordDescriptors.ShadowsShadowmask },
+ { CoreKeywordDescriptors.LightLayers },
+ { CoreKeywordDescriptors.LightCookies },
+ { CoreKeywordDescriptors.ClusterLightLoop },
+ };
}
#endregion
@@ -405,6 +551,7 @@ static class UnlitIncludes
{
const string kUnlitPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitPass.hlsl";
const string kUnlitGBufferPass = "Packages/com.unity.render-pipelines.universal/Editor/ShaderGraph/Includes/UnlitGBufferPass.hlsl";
+ const string kLighting = "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Lighting.hlsl";
public static IncludeCollection Forward = new IncludeCollection
{
@@ -435,6 +582,12 @@ static class UnlitIncludes
{ CoreIncludes.CorePostgraph },
{ kUnlitGBufferPass, IncludeLocation.Postgraph },
};
+
+ public static IncludeCollection LightingIncludes = new IncludeCollection
+ {
+ // Pre-graph
+ { kLighting, IncludeLocation.Pregraph },
+ };
}
#endregion
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs
index 0cfad880d21..0c69260274c 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderScriptableStripper.cs
@@ -402,7 +402,16 @@ internal bool StripUnusedFeatures_ScreenCoordOverride(ref IShaderScriptableStrip
internal bool StripUnusedFeatures_ScreenSpaceIrradiance(ref IShaderScriptableStrippingData strippingData)
{
- return strippingData.IsKeywordEnabled(m_ScreenSpaceIrradiance); // Screen space irradiance is currently not exposed to the user nor used by anything internal.
+#if SURFACE_CACHE
+ if (strippingData.PassHasKeyword(m_ScreenSpaceIrradiance))
+ {
+ bool useScreenSpaceIrradiance = strippingData.IsShaderFeatureEnabled(ShaderFeatures.SurfaceCache);
+ return !strippingData.IsShaderFeatureEnabled(ShaderFeatures.SurfaceCache) && strippingData.IsKeywordEnabled(m_ScreenSpaceIrradiance);
+ }
+ return false;
+#else
+ return strippingData.IsKeywordEnabled(m_ScreenSpaceIrradiance);
+#endif
}
internal bool StripUnusedFeatures_BicubicLightmapSampling(ref IShaderScriptableStrippingData strippingData)
@@ -1057,7 +1066,11 @@ internal bool StripUnusedPass_Meta(ref IShaderScriptableStrippingData strippingD
if (strippingData.passType == PassType.Meta)
{
if (SupportedRenderingFeatures.active.enlighten == false
- || ((int)SupportedRenderingFeatures.active.lightmapBakeTypes | (int)LightmapBakeType.Realtime) == 0)
+ || ((int)SupportedRenderingFeatures.active.lightmapBakeTypes | (int)LightmapBakeType.Realtime) == 0
+#if SURFACE_CACHE
+ || !strippingData.IsShaderFeatureEnabled(ShaderFeatures.SurfaceCache)
+#endif
+ )
return true;
}
return false;
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/ShaderUtils.cs b/Packages/com.unity.render-pipelines.universal/Editor/ShaderUtils.cs
index b02e1b835ff..2fe8cc06f1e 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/ShaderUtils.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/ShaderUtils.cs
@@ -1,6 +1,7 @@
using System;
using UnityEngine;
using UnityEditor;
+using UnityEditor.Rendering.Universal;
using ShaderPathID = UnityEngine.Rendering.Universal.ShaderPathID;
using UnityEditor.ShaderGraph;
using UnityEditor.Rendering.Universal.ShaderGraph;
@@ -39,6 +40,7 @@ internal enum ShaderID
SG_Decal, // UniversalDecalSubTarget
SG_SpriteUnlit, // UniversalSpriteUnlitSubTarget
SG_SpriteLit, // UniversalSpriteLitSubTarget
+ SG_TerrainLit, // UniversalTerrainLitSubTarget
SG_SpriteCustomLit, // UniversalSpriteCustomLitSubTarget
SG_SixWaySmokeLit // UniversalSixWaySubTarget
}
@@ -190,6 +192,9 @@ internal static void UpdateMaterial(Material material, MaterialUpdateType update
break;
case ShaderID.SG_Decal:
break;
+ case ShaderID.SG_TerrainLit:
+ TerrainLitShaderGUI.SetupMaterialKeywords(material);
+ break;
case ShaderID.SG_SpriteUnlit:
break;
case ShaderID.SG_SpriteLit:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain.meta b/Packages/com.unity.render-pipelines.universal/Editor/Terrain.meta
new file mode 100644
index 00000000000..3df1dbbb061
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: fc44513cb116d68479a07038666952cc
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainSurfaceDescriptionInputs.template.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainSurfaceDescriptionInputs.template.hlsl
new file mode 100644
index 00000000000..8b1e92177a7
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainSurfaceDescriptionInputs.template.hlsl
@@ -0,0 +1,137 @@
+SurfaceDescriptionInputs BuildSurfaceDescriptionInputs(Varyings input)
+{
+ SurfaceDescriptionInputs output;
+ ZERO_INITIALIZE(SurfaceDescriptionInputs, output);
+
+ $splice(CustomInterpolatorCopyToSDI)
+
+ $SurfaceDescriptionInputs.WorldSpaceNormal: // must use interpolated tangent, bitangent and normal before they are normalized in the pixel shader.
+ $SurfaceDescriptionInputs.WorldSpaceNormal: float3 unnormalizedNormalWS = input.normalWS;
+ $SurfaceDescriptionInputs.WorldSpaceNormal: const float renormFactor = 1.0 / length(unnormalizedNormalWS);
+
+ $SurfaceDescriptionInputs.WorldSpaceBiTangent: // use bitangent on the fly like in hdrp
+ $SurfaceDescriptionInputs.WorldSpaceBiTangent: // IMPORTANT! If we ever support Flip on double sided materials ensure bitangent and tangent are NOT flipped.
+ $SurfaceDescriptionInputs.WorldSpaceBiTangent: float crossSign = (input.tangentWS.w > 0.0 ? 1.0 : -1.0)* GetOddNegativeScale();
+ $SurfaceDescriptionInputs.WorldSpaceBiTangent: float3 bitang = crossSign * cross(input.normalWS.xyz, input.tangentWS.xyz);
+
+ $SurfaceDescriptionInputs.WorldSpaceNormal: output.WorldSpaceNormal = renormFactor * input.normalWS.xyz; // we want a unit length Normal Vector node in shader graph
+ $SurfaceDescriptionInputs.ObjectSpaceNormal: output.ObjectSpaceNormal = normalize(mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_M)); // transposed multiplication by inverse matrix to handle normal scale
+ $SurfaceDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = mul(output.WorldSpaceNormal, (float3x3) UNITY_MATRIX_I_V); // transposed multiplication by inverse matrix to handle normal scale
+ $SurfaceDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
+
+ $SurfaceDescriptionInputs.WorldSpaceTangent: // to preserve mikktspace compliance we use same scale renormFactor as was used on the normal.
+ $SurfaceDescriptionInputs.WorldSpaceTangent: // This is explained in section 2.2 in "surface gradient based bump mapping framework"
+ $SurfaceDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = renormFactor * input.tangentWS.xyz;
+ $SurfaceDescriptionInputs.WorldSpaceBiTangent: output.WorldSpaceBiTangent = renormFactor * bitang;
+
+ $SurfaceDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = TransformWorldToObjectDir(output.WorldSpaceTangent);
+ $SurfaceDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = TransformWorldToViewDir(output.WorldSpaceTangent);
+ $SurfaceDescriptionInputs.TangentSpaceTangent: output.TangentSpaceTangent = float3(1.0f, 0.0f, 0.0f);
+ $SurfaceDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = TransformWorldToObjectDir(output.WorldSpaceBiTangent);
+ $SurfaceDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = TransformWorldToViewDir(output.WorldSpaceBiTangent);
+ $SurfaceDescriptionInputs.TangentSpaceBiTangent: output.TangentSpaceBiTangent = float3(0.0f, 1.0f, 0.0f);
+ $SurfaceDescriptionInputs.WorldSpaceViewDirection: output.WorldSpaceViewDirection = GetWorldSpaceNormalizeViewDir(input.positionWS);
+ $SurfaceDescriptionInputs.ObjectSpaceViewDirection: output.ObjectSpaceViewDirection = TransformWorldToObjectDir(output.WorldSpaceViewDirection);
+ $SurfaceDescriptionInputs.ViewSpaceViewDirection: output.ViewSpaceViewDirection = TransformWorldToViewDir(output.WorldSpaceViewDirection);
+ $SurfaceDescriptionInputs.TangentSpaceViewDirection: float3x3 tangentSpaceTransform = float3x3(output.WorldSpaceTangent, output.WorldSpaceBiTangent, output.WorldSpaceNormal);
+ $SurfaceDescriptionInputs.TangentSpaceViewDirection: output.TangentSpaceViewDirection = mul(tangentSpaceTransform, output.WorldSpaceViewDirection);
+ $SurfaceDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = input.positionWS;
+ $SurfaceDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = TransformWorldToObject(input.positionWS);
+ $SurfaceDescriptionInputs.ViewSpacePosition: output.ViewSpacePosition = TransformWorldToView(input.positionWS);
+ $SurfaceDescriptionInputs.TangentSpacePosition: output.TangentSpacePosition = float3(0.0f, 0.0f, 0.0f);
+ $SurfaceDescriptionInputs.AbsoluteWorldSpacePosition: output.AbsoluteWorldSpacePosition = GetAbsolutePositionWS(input.positionWS);
+ $SurfaceDescriptionInputs.WorldSpacePositionPredisplacement: output.WorldSpacePositionPredisplacement = input.positionWS;
+ $SurfaceDescriptionInputs.ObjectSpacePositionPredisplacement: output.ObjectSpacePositionPredisplacement = TransformWorldToObject(input.positionWS);
+ $SurfaceDescriptionInputs.ViewSpacePositionPredisplacement: output.ViewSpacePositionPredisplacement = TransformWorldToView(input.positionWS);
+ $SurfaceDescriptionInputs.TangentSpacePositionPredisplacement: output.TangentSpacePositionPredisplacement = float3(0.0f, 0.0f, 0.0f);
+ $SurfaceDescriptionInputs.AbsoluteWorldSpacePositionPredisplacement:output.AbsoluteWorldSpacePositionPredisplacement = GetAbsolutePositionWS(input.positionWS);
+ $SurfaceDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(input.positionWS), _ProjectionParams.x);
+
+#if UNITY_UV_STARTS_AT_TOP
+ $SurfaceDescriptionInputs.PixelPosition: output.PixelPosition = float2(input.positionCS.x, (_ProjectionParams.x < 0) ? (_ScreenParams.y - input.positionCS.y) : input.positionCS.y);
+#else
+ $SurfaceDescriptionInputs.PixelPosition: output.PixelPosition = float2(input.positionCS.x, (_ProjectionParams.x > 0) ? (_ScreenParams.y - input.positionCS.y) : input.positionCS.y);
+#endif
+
+ $SurfaceDescriptionInputs.NDCPosition: output.NDCPosition = output.PixelPosition.xy / _ScreenParams.xy;
+ $SurfaceDescriptionInputs.NDCPosition: output.NDCPosition.y = 1.0f - output.NDCPosition.y;
+
+ $SurfaceDescriptionInputs.uv0: output.uv0 = input.texCoord0;
+ $SurfaceDescriptionInputs.uv1: output.uv1 = input.texCoord1;
+ $SurfaceDescriptionInputs.uv2: output.uv2 = input.texCoord2;
+ $SurfaceDescriptionInputs.uv3: output.uv3 = input.texCoord3;
+ $SurfaceDescriptionInputs.VertexColor: output.VertexColor = input.color;
+ $SurfaceDescriptionInputs.TimeParameters: output.TimeParameters = _TimeParameters.xyz; // This is mainly for LW as HD overwrite this value
+#ifdef UNIVERSAL_TERRAIN_SPLAT01
+ $SurfaceDescriptionInputs.uvSplat01: output.uvSplat01 = input.uvSplat01;
+#endif
+#ifdef UNIVERSAL_TERRAIN_SPLAT23
+ $SurfaceDescriptionInputs.uvSplat23: output.uvSplat23 = input.uvSplat23;
+#endif
+#if defined(SHADER_STAGE_FRAGMENT) && defined(VARYINGS_NEED_CULLFACE)
+#define BUILD_SURFACE_DESCRIPTION_INPUTS_OUTPUT_FACESIGN output.FaceSign = IS_FRONT_VFACE(input.cullFace, true, false);
+#else
+#define BUILD_SURFACE_DESCRIPTION_INPUTS_OUTPUT_FACESIGN
+#endif
+ $SurfaceDescriptionInputs.FaceSign: BUILD_SURFACE_DESCRIPTION_INPUTS_OUTPUT_FACESIGN
+#undef BUILD_SURFACE_DESCRIPTION_INPUTS_OUTPUT_FACESIGN
+
+ return output;
+}
+
+#if SHADERPASS == SHADERPASS_FORWARD || SHADERPASS == SHADERPASS_GBUFFER
+
+void CalculateTerrainNormalWS(Varyings input, inout SurfaceDescription surfaceDescription, inout InputData inputData)
+{
+ $SurfaceDescription.NormalTS: half3 normalTS = surfaceDescription.NormalTS;
+ $SurfaceDescription.NormalOS: half3 NormalOS = surfaceDescription.NormalOS;
+ $SurfaceDescription.NormalWS: half3 normalWS = surfaceDescription.NormalWS;
+
+#if defined(_NORMALMAP) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)
+ half3 viewDirWS = half3(input.normalViewDir.w, input.tangentViewDir.w, input.bitangentViewDir.w);
+
+ $SurfaceDescription.NormalTS: inputData.tangentToWorld = half3x3(-input.tangentViewDir.xyz, input.bitangentViewDir.xyz, input.normalViewDir.xyz);
+ $SurfaceDescription.NormalTS: half3 normalWS = TransformTangentToWorld(normalTS, inputData.tangentToWorld);
+ $SurfaceDescription.NormalOS: half3 normalWS = TransformObjectToWorldNormal(NormalOS);
+#elif defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)
+ half3 viewDirWS = GetWorldSpaceNormalizeViewDir(input.positionWS);
+
+ $SurfaceDescription.NormalTS: half3 tangentWS = cross(GetObjectToWorldMatrix()._13_23_33, input.normalWS);
+ $SurfaceDescription.NormalTS: half3 normalWS = TransformTangentToWorld(normalTS, half3x3(-tangentWS, cross(input.normalWS, tangentWS), input.normalWS));
+ $SurfaceDescription.NormalOS: half3 normalWS = TransformObjectToWorldNormal(NormalOS);
+#else
+ half3 viewDirWS = GetWorldSpaceNormalizeViewDir(input.positionWS);
+
+ $SurfaceDescription.NormalTS: half3 normalWS = input.normalWS;
+ $SurfaceDescription.NormalOS: half3 normalWS = TransformObjectToWorldNormal(NormalOS);
+#endif
+
+ inputData.normalWS = NormalizeNormalPerPixel(normalWS);
+ inputData.viewDirectionWS = viewDirWS;
+}
+
+#elif SHADERPASS == SHADERPASS_DEPTHNORMALS
+
+half3 GetTerrainNormalWS(Varyings input, SurfaceDescription surfaceDescription)
+{
+ $SurfaceDescription.NormalTS: half3 normalTS = surfaceDescription.NormalTS;
+ $SurfaceDescription.NormalOS: half3 NormalOS = surfaceDescription.NormalOS;
+ $SurfaceDescription.NormalWS: half3 normalWS = surfaceDescription.NormalWS;
+
+#if defined(_NORMALMAP) && !defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)
+ $SurfaceDescription.NormalTS: half3x3 tangentToWorld = half3x3(-input.tangentViewDir.xyz, input.bitangentViewDir.xyz, input.normalViewDir.xyz);
+ $SurfaceDescription.NormalTS: half3 normalWS = TransformTangentToWorld(normalTS, tangentToWorld);
+ $SurfaceDescription.NormalOS: half3 normalWS = TransformObjectToWorldNormal(NormalOS);
+#elif defined(ENABLE_TERRAIN_PERPIXEL_NORMAL)
+ $SurfaceDescription.NormalTS: half3 tangentWS = cross(GetObjectToWorldMatrix()._13_23_33, input.normalWS);
+ $SurfaceDescription.NormalTS: half3 normalWS = TransformTangentToWorld(normalTS, half3x3(-tangentWS, cross(input.normalWS, tangentWS), input.normalWS));
+ $SurfaceDescription.NormalOS: half3 normalWS = TransformObjectToWorldNormal(NormalOS);
+#else
+ $SurfaceDescription.NormalTS: half3 normalWS = input.normalWS;
+ $SurfaceDescription.NormalOS: half3 normalWS = TransformObjectToWorldNormal(NormalOS);
+#endif
+
+ return normalWS;
+}
+
+#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainSurfaceDescriptionInputs.template.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainSurfaceDescriptionInputs.template.hlsl.meta
new file mode 100644
index 00000000000..19a546974f0
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainSurfaceDescriptionInputs.template.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: ef136de7def056a4d8aa337fa0bcd989
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainVertexDescriptionInputs.template.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainVertexDescriptionInputs.template.hlsl
new file mode 100644
index 00000000000..f98a82c136d
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainVertexDescriptionInputs.template.hlsl
@@ -0,0 +1,84 @@
+VertexDescriptionInputs BuildVertexDescriptionInputs(Attributes input)
+{
+ VertexDescriptionInputs output;
+ ZERO_INITIALIZE(VertexDescriptionInputs, output);
+
+ $VertexDescriptionInputs.ObjectSpaceNormal: output.ObjectSpaceNormal = input.normalOS;
+ $VertexDescriptionInputs.WorldSpaceNormal: output.WorldSpaceNormal = TransformObjectToWorldNormal(input.normalOS);
+ $VertexDescriptionInputs.ViewSpaceNormal: output.ViewSpaceNormal = TransformWorldToViewDir(output.WorldSpaceNormal);
+ $VertexDescriptionInputs.TangentSpaceNormal: output.TangentSpaceNormal = float3(0.0f, 0.0f, 1.0f);
+ $VertexDescriptionInputs.ObjectSpaceTangent: output.ObjectSpaceTangent = input.tangentOS.xyz;
+ $VertexDescriptionInputs.WorldSpaceTangent: output.WorldSpaceTangent = TransformObjectToWorldDir(input.tangentOS.xyz);
+ $VertexDescriptionInputs.ViewSpaceTangent: output.ViewSpaceTangent = TransformWorldToViewDir(output.WorldSpaceTangent);
+ $VertexDescriptionInputs.TangentSpaceTangent: output.TangentSpaceTangent = float3(1.0f, 0.0f, 0.0f);
+ $VertexDescriptionInputs.ObjectSpaceBiTangent: output.ObjectSpaceBiTangent = normalize(cross(input.normalOS, input.tangentOS.xyz) * (input.tangentOS.w > 0.0f ? 1.0f : -1.0f) * GetOddNegativeScale());
+ $VertexDescriptionInputs.WorldSpaceBiTangent: output.WorldSpaceBiTangent = TransformObjectToWorldDir(output.ObjectSpaceBiTangent);
+ $VertexDescriptionInputs.ViewSpaceBiTangent: output.ViewSpaceBiTangent = TransformWorldToViewDir(output.WorldSpaceBiTangent);
+ $VertexDescriptionInputs.TangentSpaceBiTangent: output.TangentSpaceBiTangent = float3(0.0f, 1.0f, 0.0f);
+ $VertexDescriptionInputs.ObjectSpacePosition: output.ObjectSpacePosition = input.positionOS;
+ $VertexDescriptionInputs.WorldSpacePosition: output.WorldSpacePosition = TransformObjectToWorld(input.positionOS);
+ $VertexDescriptionInputs.ViewSpacePosition: output.ViewSpacePosition = TransformWorldToView(output.WorldSpacePosition);
+ $VertexDescriptionInputs.TangentSpacePosition: output.TangentSpacePosition = float3(0.0f, 0.0f, 0.0f);
+ $VertexDescriptionInputs.AbsoluteWorldSpacePosition: output.AbsoluteWorldSpacePosition = GetAbsolutePositionWS(TransformObjectToWorld(input.positionOS));
+ $VertexDescriptionInputs.ObjectSpacePositionPredisplacement: output.ObjectSpacePositionPredisplacement = input.positionOS;
+ $VertexDescriptionInputs.WorldSpacePositionPredisplacement: output.WorldSpacePositionPredisplacement = TransformObjectToWorld(input.positionOS);
+ $VertexDescriptionInputs.ViewSpacePositionPredisplacement: output.ViewSpacePositionPredisplacement = TransformWorldToView(output.WorldSpacePosition);
+ $VertexDescriptionInputs.TangentSpacePositionPredisplacement: output.TangentSpacePositionPredisplacement = float3(0.0f, 0.0f, 0.0f);
+ $VertexDescriptionInputs.AbsoluteWorldSpacePositionPredisplacement: output.AbsoluteWorldSpacePositionPredisplacement = GetAbsolutePositionWS(TransformObjectToWorld(input.positionOS));
+ $VertexDescriptionInputs.WorldSpaceViewDirection: output.WorldSpaceViewDirection = GetWorldSpaceNormalizeViewDir(output.WorldSpacePosition);
+ $VertexDescriptionInputs.ObjectSpaceViewDirection: output.ObjectSpaceViewDirection = TransformWorldToObjectDir(output.WorldSpaceViewDirection);
+ $VertexDescriptionInputs.ViewSpaceViewDirection: output.ViewSpaceViewDirection = TransformWorldToViewDir(output.WorldSpaceViewDirection);
+ $VertexDescriptionInputs.TangentSpaceViewDirection: float3x3 tangentSpaceTransform = float3x3(output.WorldSpaceTangent,output.WorldSpaceBiTangent,output.WorldSpaceNormal);
+ $VertexDescriptionInputs.TangentSpaceViewDirection: output.TangentSpaceViewDirection = TransformWorldToTangent(output.WorldSpaceViewDirection, tangentSpaceTransform);
+ $VertexDescriptionInputs.ScreenPosition: output.ScreenPosition = ComputeScreenPos(TransformWorldToHClip(output.WorldSpacePosition), _ProjectionParams.x);
+ $VertexDescriptionInputs.NDCPosition: output.NDCPosition = output.ScreenPosition.xy / output.ScreenPosition.w;
+ $VertexDescriptionInputs.PixelPosition: output.PixelPosition = float2(output.NDCPosition.x, 1.0f - output.NDCPosition.y) * _ScreenParams.xy;
+ $VertexDescriptionInputs.uv0: output.uv0 = input.uv0;
+ $VertexDescriptionInputs.uv1: output.uv1 = input.uv1;
+ $VertexDescriptionInputs.uv2: output.uv2 = input.uv2;
+ $VertexDescriptionInputs.uv3: output.uv3 = input.uv3;
+ $VertexDescriptionInputs.VertexColor: output.VertexColor = input.color;
+ $VertexDescriptionInputs.TimeParameters: output.TimeParameters = _TimeParameters.xyz;
+ $VertexDescriptionInputs.BoneWeights: output.BoneWeights = input.weights;
+ $VertexDescriptionInputs.BoneIndices: output.BoneIndices = input.indices;
+ $VertexDescriptionInputs.VertexID: output.VertexID = input.vertexID;
+
+ return output;
+}
+
+void TerrainVaryingGeneration(inout Attributes input, inout Varyings output)
+{
+ float4 positionOS = float4(input.positionOS, 1.0);
+ #if defined(VARYINGS_NEED_TEXCOORD0) && defined(ATTRIBUTES_NEED_NORMAL)
+ TerrainInstancing(positionOS, input.normalOS, input.uv0.xy);
+ #elif defined(VARYINGS_NEED_TEXCOORD0)
+ float3 normal = float3(0, 0, 0);
+ TerrainInstancing(positionOS, normal, input.uv0.xy);
+ #elif defined(ATTRIBUTES_NEED_NORMAL)
+ TerrainInstancing(positionOS, input.normalOS);
+ #else
+ TerrainInstancing(positionOS);
+ #endif
+ input.positionOS = positionOS.xyz;
+
+#if defined(VARYINGS_NEED_TEXCOORD0) && defined(UNIVERSAL_TERRAIN_SPLAT01)
+ output.uvSplat01.xy = TRANSFORM_TEX(input.uv0, _Splat0);
+ output.uvSplat01.zw = TRANSFORM_TEX(input.uv0, _Splat1);
+#endif
+#if defined(VARYINGS_NEED_TEXCOORD0) && defined(UNIVERSAL_TERRAIN_SPLAT23)
+ output.uvSplat23.xy = TRANSFORM_TEX(input.uv0, _Splat2);
+ output.uvSplat23.zw = TRANSFORM_TEX(input.uv0, _Splat3);
+#endif
+}
+
+float4 ConstructTerrainTangent(float3 normal, float3 positiveZ)
+{
+ // Consider a flat terrain. It should have tangent be (1, 0, 0) and bitangent be (0, 0, 1) as the UV of the terrain grid mesh is a scale of the world XZ position.
+ // In CreateTangentToWorld function (in SpaceTransform.hlsl), it is cross(normal, tangent) * sgn for the bitangent vector.
+ // It is not true in a left-handed coordinate system for the terrain bitangent, if we provide 1 as the tangent.w. It would produce (0, 0, -1) instead of (0, 0, 1).
+ // Also terrain's tangent calculation was wrong in a left handed system because cross((0,0,1), terrainNormalOS) points to the wrong direction as negative X.
+ // Therefore all the 4 xyzw components of the tangent needs to be flipped to correct the tangent frame.
+ // (See TerrainLitData.hlsl - GetSurfaceAndBuiltinData)
+ float3 tangent = cross(normal, positiveZ);
+ return float4(tangent, -1);
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainVertexDescriptionInputs.template.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainVertexDescriptionInputs.template.hlsl.meta
new file mode 100644
index 00000000000..2d9d4609a88
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/BuildTerrainVertexDescriptionInputs.template.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 93d037989b854c24d8f2a8284a46acf3
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.hlsl
new file mode 100644
index 00000000000..9c6f6b024e2
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.hlsl
@@ -0,0 +1,44 @@
+Varyings Vert(Attributes IN)
+{
+ Varyings output = (Varyings) 0;
+
+ output.positionCS = TransformWorldToHClip(IN.positionOS.xyz);
+
+ // NOTE : This is basically coming from the vertex shader in TerrainLitPasses
+ // There are other plenty of other values that the original version computes, but for this
+ // pass, we are only interested in a few, so I'm just skipping the rest.
+ output.texCoord0.xy = IN.uv0; // uvMainAndLM
+ #if defined(UNIVERSAL_TERRAIN_SPLAT01)
+ output.uvSplat01.xy = TRANSFORM_TEX(IN.uv0, _Splat0);
+ output.uvSplat01.zw = TRANSFORM_TEX(IN.uv0, _Splat1);
+ #endif
+ #if defined(UNIVERSAL_TERRAIN_SPLAT02)
+ output.uvSplat23.xy = TRANSFORM_TEX(IN.uv0, _Splat2);
+ output.uvSplat23.zw = TRANSFORM_TEX(IN.uv0, _Splat3);
+ #endif
+
+ return output;
+}
+
+PackedVaryings vert(Attributes input)
+{
+ Varyings output = (Varyings)0;
+ output = Vert(input);
+ PackedVaryings packedOutput = (PackedVaryings)0;
+ packedOutput = PackVaryings(output);
+ return packedOutput;
+}
+
+half4 frag(PackedVaryings packedInput) : SV_TARGET
+{
+ Varyings unpacked = UnpackVaryings(packedInput);
+
+ SurfaceDescriptionInputs surfaceDescriptionInputs = BuildSurfaceDescriptionInputs(unpacked);
+ SurfaceDescription surfaceDescription = SurfaceDescriptionFunction(surfaceDescriptionInputs);
+
+#if SHADERPASS == SHADERPASS_MAINTEX
+ return half4(surfaceDescription.BaseColor, surfaceDescription.Smoothness);
+#elif SHADERPASS == SHADERPASS_METALLICTEX
+ return surfaceDescription.Metallic;
+#endif
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.hlsl.meta
new file mode 100644
index 00000000000..25a6335bb80
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 038de1c4d210733429acda9d6f95d183
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.template b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.template
new file mode 100644
index 00000000000..6b0a8e67d9e
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.template
@@ -0,0 +1,102 @@
+Pass
+{
+ Tags
+ {
+ $splice(BaseGenName)
+ $splice(BaseGenTexFormat)
+ $splice(BaseGenTexSize)
+ $splice(BaseGenEmptyColor)
+ }
+
+ // Render State
+ $splice(RenderState)
+
+ // --------------------------------------------------
+ // Pass
+
+ HLSLPROGRAM
+
+ // Pragmas
+ $splice(PassPragmas)
+
+ // Keywords
+ $splice(PassKeywords)
+ $splice(GraphKeywords)
+
+ $NormalDropOffTS: #define _NORMAL_DROPOFF_TS 1
+ $NormalDropOffOS: #define _NORMAL_DROPOFF_OS 1
+ $NormalDropOffWS: #define _NORMAL_DROPOFF_WS 1
+ $Attributes.normalOS: #define ATTRIBUTES_NEED_NORMAL
+ $Attributes.uv0: #define ATTRIBUTES_NEED_TEXCOORD0
+ $Attributes.uv1: #define ATTRIBUTES_NEED_TEXCOORD1
+ $Attributes.uv2: #define ATTRIBUTES_NEED_TEXCOORD2
+ $Attributes.uv3: #define ATTRIBUTES_NEED_TEXCOORD3
+ $Attributes.color: #define ATTRIBUTES_NEED_COLOR
+ $Attributes.vertexID: #define ATTRIBUTES_NEED_VERTEXID
+ $Varyings.positionWS: #define VARYINGS_NEED_POSITION_WS
+ $Varyings.normalWS: #define VARYINGS_NEED_NORMAL_WS
+ $Varyings.tangentWS: #define VARYINGS_NEED_TANGENT_WS
+ $Varyings.texCoord0: #define VARYINGS_NEED_TEXCOORD0
+ $Varyings.texCoord1: #define VARYINGS_NEED_TEXCOORD1
+ $Varyings.texCoord2: #define VARYINGS_NEED_TEXCOORD2
+ $Varyings.texCoord3: #define VARYINGS_NEED_TEXCOORD3
+ $Varyings.color: #define VARYINGS_NEED_COLOR
+ $Varyings.elementToWorld0: #define VARYINGS_NEED_ELEMENT_TO_WORLD
+ $Varyings.worldToElement0: #define VARYINGS_NEED_WORLD_TO_ELEMENT
+ $Varyings.bitangentWS: #define VARYINGS_NEED_BITANGENT_WS
+ $Varyings.screenPosition: #define VARYINGS_NEED_SCREENPOSITION
+ $Varyings.fogFactorAndVertexLight: #define VARYINGS_NEED_FOG_AND_VERTEX_LIGHT
+ $Varyings.shadowCoord: #define VARYINGS_NEED_SHADOW_COORD
+ $Varyings.cullFace: #define VARYINGS_NEED_CULLFACE
+ $features.graphVertex: #define FEATURES_GRAPH_VERTEX
+ $Universal.UseLegacySpriteBlocks: #define UNIVERSAL_USELEGACYSPRITEBLOCKS
+ $splice(PassInstancing)
+ $splice(GraphDefines)
+ $splice(DotsInstancingVars)
+
+ // Includes
+ $splice(PreGraphIncludes)
+
+ // Specific Terrain Define
+ $include("TerrainPassDefine.template.hlsl")
+
+ // --------------------------------------------------
+ // Structs and Packing
+
+ // custom interpolators pre packing
+ $splice(CustomInterpolatorPrePacking)
+
+ $splice(PassStructs)
+
+ $splice(InterpolatorPack)
+
+ // --------------------------------------------------
+ // Graph
+
+ // Graph Properties
+ $splice(GraphProperties)
+
+ // Graph Includes
+ $splice(GraphIncludes)
+
+ // Graph Functions
+ $splice(GraphFunctions)
+
+ // Graph Vertex
+ $splice(GraphVertex)
+
+ // Graph Pixel
+ $splice(GraphPixel)
+
+ // --------------------------------------------------
+ // Build Graph Inputs
+ $features.graphVertex: $include("BuildTerrainVertexDescriptionInputs.template.hlsl")
+ $features.graphPixel: $include("BuildTerrainSurfaceDescriptionInputs.template.hlsl")
+
+ // --------------------------------------------------
+ // Main
+
+ $include("TerrainBaseMapGenPass.hlsl")
+
+ ENDHLSL
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.template.meta b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.template.meta
new file mode 100644
index 00000000000..8bc43246860
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainBaseMapGenPass.template.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 4288d0244223deb429fef72cf614023d
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPass.template b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPass.template
new file mode 100644
index 00000000000..de84e8b3d2a
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPass.template
@@ -0,0 +1,117 @@
+Pass
+{
+ $splice(PassName)
+ Tags
+ {
+ $splice(LightMode)
+ }
+
+ // Render State
+ $splice(RenderState)
+
+ // Debug
+ $splice(Debug)
+
+ // --------------------------------------------------
+ // Pass
+
+ HLSLPROGRAM
+
+ // Pragmas
+ $splice(PassPragmas)
+
+ // Keywords
+ $splice(PassKeywords)
+ $splice(GraphKeywords)
+
+ $NormalDropOffTS: #define _NORMAL_DROPOFF_TS 1
+ $NormalDropOffOS: #define _NORMAL_DROPOFF_OS 1
+ $NormalDropOffWS: #define _NORMAL_DROPOFF_WS 1
+ $Attributes.normalOS: #define ATTRIBUTES_NEED_NORMAL
+ $Attributes.uv0: #define ATTRIBUTES_NEED_TEXCOORD0
+ $Attributes.uv1: #define ATTRIBUTES_NEED_TEXCOORD1
+ $Attributes.uv2: #define ATTRIBUTES_NEED_TEXCOORD2
+ $Attributes.uv3: #define ATTRIBUTES_NEED_TEXCOORD3
+ $Attributes.color: #define ATTRIBUTES_NEED_COLOR
+ $Attributes.vertexID: #define ATTRIBUTES_NEED_VERTEXID
+ $Varyings.positionWS: #define VARYINGS_NEED_POSITION_WS
+ $Varyings.normalWS: #define VARYINGS_NEED_NORMAL_WS
+ $Varyings.tangentWS: #define VARYINGS_NEED_TANGENT_WS
+ $Varyings.texCoord0: #define VARYINGS_NEED_TEXCOORD0
+ $Varyings.texCoord1: #define VARYINGS_NEED_TEXCOORD1
+ $Varyings.texCoord2: #define VARYINGS_NEED_TEXCOORD2
+ $Varyings.texCoord3: #define VARYINGS_NEED_TEXCOORD3
+ $Varyings.color: #define VARYINGS_NEED_COLOR
+ $Varyings.elementToWorld0: #define VARYINGS_NEED_ELEMENT_TO_WORLD
+ $Varyings.worldToElement0: #define VARYINGS_NEED_WORLD_TO_ELEMENT
+ $Varyings.bitangentWS: #define VARYINGS_NEED_BITANGENT_WS
+ $Varyings.screenPosition: #define VARYINGS_NEED_SCREENPOSITION
+ $Varyings.fogFactorAndVertexLight: #define VARYINGS_NEED_FOG_AND_VERTEX_LIGHT
+ $Varyings.shadowCoord: #define VARYINGS_NEED_SHADOW_COORD
+ $Varyings.cullFace: #define VARYINGS_NEED_CULLFACE
+ $features.graphVertex: #define FEATURES_GRAPH_VERTEX
+ $Universal.UseLegacySpriteBlocks: #define UNIVERSAL_USELEGACYSPRITEBLOCKS
+ $splice(PassInstancing)
+ $splice(GraphDefines)
+ $splice(DotsInstancingVars)
+
+ // custom interpolator pre-include
+ $splice(sgci_CustomInterpolatorPreInclude)
+
+ // Includes
+ $splice(PreGraphIncludes)
+
+ // Specific Terrain Define
+ $include("TerrainPassDefine.template.hlsl")
+
+ // --------------------------------------------------
+ // Structs and Packing
+
+ // custom interpolators pre packing
+ $splice(CustomInterpolatorPrePacking)
+
+ $splice(PassStructs)
+
+ $splice(InterpolatorPack)
+
+ // --------------------------------------------------
+ // Graph
+
+ // Graph Properties
+ $splice(GraphProperties)
+
+ // Graph Includes
+ $splice(GraphIncludes)
+
+ // -- Property used by ScenePickingPass
+ #ifdef SCENEPICKINGPASS
+ float4 _SelectionID;
+ #endif
+
+ // Graph Functions
+ $splice(GraphFunctions)
+
+ // Custom interpolators pre vertex
+ $splice(CustomInterpolatorPreVertex)
+
+ // Graph Vertex
+ $splice(GraphVertex)
+
+ // Custom interpolators, pre surface
+ $splice(CustomInterpolatorPreSurface)
+
+ // Graph Pixel
+ $splice(GraphPixel)
+
+ // --------------------------------------------------
+ // Build Graph Inputs
+ $features.graphVertex: $include("BuildTerrainVertexDescriptionInputs.template.hlsl")
+ $features.graphPixel: $include("BuildTerrainSurfaceDescriptionInputs.template.hlsl")
+
+ // --------------------------------------------------
+ // Main
+
+ $splice(PostGraphIncludes)
+
+ ENDHLSL
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPass.template.meta b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPass.template.meta
new file mode 100644
index 00000000000..0a52abaec91
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPass.template.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: bf34598b1ba253f4ab82fc5cffbed1ba
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassDefine.template.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassDefine.template.hlsl
new file mode 100644
index 00000000000..7aa0b768754
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassDefine.template.hlsl
@@ -0,0 +1,171 @@
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Texture.hlsl"
+#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
+
+#define SHADERPASS_MAINTEX (27)
+#define SHADERPASS_METALLICTEX (28)
+
+#define TERRAIN_DEFAULT_TEXTURE
+TEXTURE2D(_BlackTex); SAMPLER(sampler_BlackTex);
+TEXTURE2D(_NormalBlank); SAMPLER(sampler_NormalBlank);
+TEXTURE2D(_DefaultWhiteTex); SAMPLER(sampler_BilinearClamp);
+SAMPLER(sampler_BilinearRepeat);
+
+float4 _BlackTex_TexelSize = float4(1,1,1,1);
+half4 _BlackTex_ST = half4(1,1,0,0);
+
+#define _Control0 _Control
+#define _Control1 _BlackTex
+
+#define _Splat4 _BlackTex
+#define _Splat5 _BlackTex
+#define _Splat6 _BlackTex
+#define _Splat7 _BlackTex
+#define sampler_Splat4 sampler_BlackTex
+#define sampler_Splat5 sampler_BlackTex
+#define sampler_Splat6 sampler_BlackTex
+#define sampler_Splat7 sampler_BlackTex
+
+#define _Normal4 _NormalBlank
+#define _Normal5 _NormalBlank
+#define _Normal6 _NormalBlank
+#define _Normal7 _NormalBlank
+#define sampler_Normal4 sampler_NormalBlank
+#define sampler_Normal5 sampler_NormalBlank
+#define sampler_Normal6 sampler_NormalBlank
+#define sampler_Normal7 sampler_NormalBlank
+
+#define _Mask4 _BlackTex
+#define _Mask5 _BlackTex
+#define _Mask6 _BlackTex
+#define _Mask7 _BlackTex
+#define sampler_Mask4 sampler_BlackTex
+#define sampler_Mask5 sampler_BlackTex
+#define sampler_Mask6 sampler_BlackTex
+#define sampler_Mask7 sampler_BlackTex
+
+#define _Control1 _BlackTex
+#define sampler_Control1 sampler_BlackTex
+
+UnityTexture2D TerrainBuildUnityTexture2DStructInternal(Texture2D tex, SamplerState samplerstate, float4 texelSize, float4 scaleTranslate)
+{
+ UnityTexture2D result;
+ result.tex = tex;
+ result.samplerstate = samplerstate;
+ result.texelSize = texelSize;
+ result.scaleTranslate = scaleTranslate;
+ return result;
+}
+
+#define DEF_TERRAIN_TEXTURE_LOAD(name, defaultName) UnityTexture2D TerrainBuildUnityTexture2DStructInternal##name(int index) \
+{ \
+ switch(index) \
+ { \
+ case 0: \
+ return TerrainBuildUnityTexture2DStructInternal(name##0, sampler_BilinearRepeat, _Splat0_TexelSize, _Splat0_ST); \
+ case 1: \
+ return TerrainBuildUnityTexture2DStructInternal(name##1, sampler_BilinearRepeat, _Splat1_TexelSize, _Splat1_ST); \
+ case 2: \
+ return TerrainBuildUnityTexture2DStructInternal(name##2, sampler_BilinearRepeat, _Splat2_TexelSize, _Splat2_ST); \
+ case 3: \
+ return TerrainBuildUnityTexture2DStructInternal(name##3, sampler_BilinearRepeat, _Splat3_TexelSize, _Splat3_ST); \
+ default: \
+ return TerrainBuildUnityTexture2DStructInternal(defaultName, sampler_BilinearRepeat, _BlackTex_TexelSize, _BlackTex_ST); \
+ } \
+}
+
+#define DEF_TERRAIN_TEXTURE_AVAILABLE(name) float TerrainTextureAvailableInternal##name(int index) \
+{ \
+ switch(index) \
+ { \
+ case 0: \
+ case 1: \
+ case 2: \
+ case 3: \
+ return 1; \
+ default: \
+ return 0; \
+ } \
+}
+
+DEF_TERRAIN_TEXTURE_LOAD(_Splat, _BlackTex)
+DEF_TERRAIN_TEXTURE_AVAILABLE(_Splat)
+DEF_TERRAIN_TEXTURE_LOAD(_Normal, _NormalBlank)
+DEF_TERRAIN_TEXTURE_AVAILABLE(_Normal)
+DEF_TERRAIN_TEXTURE_LOAD(_Mask, _BlackTex)
+
+float TerrainTextureAvailableInternal_Mask(int index)
+{
+ switch(index)
+ {
+ case 0:
+ return _LayerHasMask0;
+ case 1:
+ return _LayerHasMask1;
+ case 2:
+ return _LayerHasMask2;
+ case 3:
+ return _LayerHasMask3;
+ default:
+ return 0;
+ }
+}
+
+float TerrainTextureAvailableInternal_Control(int index)
+{
+ switch(index)
+ {
+ case 0:
+ case 1:
+ return 1;
+ default:
+ return 0;
+ }
+}
+
+#define Unity_TerrainTextureAvailable(t, n) TerrainTextureAvailableInternal##t(n)
+
+UnityTexture2D TerrainBuildUnityTextureControl(int index)
+{
+ switch(index)
+ {
+ case 0:
+ return TerrainBuildUnityTexture2DStructInternal(_Control, sampler_Control, _Control_TexelSize, _Control_ST);
+ default:
+ return TerrainBuildUnityTexture2DStructInternal(_BlackTex, sampler_BlackTex, _BlackTex_TexelSize, _BlackTex_ST);
+ }
+}
+
+UnityTexture2D TerrainBuildUnityTextureHoles(int index)
+{
+ #if defined(_ALPHATEST_ON)
+ return TerrainBuildUnityTexture2DStructInternal(_TerrainHolesTexture, sampler_TerrainHolesTexture, _Control_TexelSize, _Control_ST);
+ #else
+ return TerrainBuildUnityTexture2DStructInternal(_DefaultWhiteTex, sampler_BilinearClamp, _BlackTex_TexelSize, _BlackTex_ST);
+ #endif
+}
+
+#define DEF_TERRAIN_VALUE_LOAD(name, returnType, defaultVal) returnType Unity_Terrain##name(int index) \
+{ \
+ switch(index) \
+ { \
+ case 0: \
+ return name##0; \
+ case 1: \
+ return name##1; \
+ case 2: \
+ return name##2; \
+ case 3: \
+ return name##3; \
+ } \
+ return defaultVal; \
+}
+
+DEF_TERRAIN_VALUE_LOAD(_NormalScale, float, float(1))
+DEF_TERRAIN_VALUE_LOAD(_Metallic, float, float(0))
+DEF_TERRAIN_VALUE_LOAD(_Smoothness, float, float(0.5))
+DEF_TERRAIN_VALUE_LOAD(_DiffuseRemapScale, float4, float4(1,1,1,1))
+DEF_TERRAIN_VALUE_LOAD(_MaskMapRemapOffset, float4, float4(0,0,0,0))
+DEF_TERRAIN_VALUE_LOAD(_MaskMapRemapScale, float4, float4(1,1,1,1))
+
+#define TerrainBuildUnityTexture2DStruct(name, index) TerrainBuildUnityTexture2DStructInternal##name(index)
+#define TerrainBuildUnityTexture2DStructNoIndex(name) TerrainBuildUnityTexture2DStructInternal(name, sampler##name, name##_TexelSize, name##_ST)
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassDefine.template.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassDefine.template.hlsl.meta
new file mode 100644
index 00000000000..d18f9692ab3
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassDefine.template.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 3b77405e9fadb4c408bbf830f615ce99
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassUtils.hlsl b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassUtils.hlsl
new file mode 100644
index 00000000000..5f43eb66787
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassUtils.hlsl
@@ -0,0 +1,13 @@
+
+void SplatmapFinalColor(inout half4 color, half fogCoord)
+{
+ color.rgb *= color.a;
+
+#ifndef TERRAIN_GBUFFER // Technically we don't need fogCoord, but it is still passed from the vertex shader.
+ #ifdef TERRAIN_SPLAT_ADDPASS
+ color.rgb = MixFogColor(color.rgb, half3(0,0,0), fogCoord);
+ #else
+ color.rgb = MixFog(color.rgb, fogCoord);
+ #endif
+#endif
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassUtils.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassUtils.hlsl.meta
new file mode 100644
index 00000000000..ce64614acb6
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Terrain/TerrainPassUtils.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 08f4bc71ad275bc4b90168fda29f36b5
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools.meta b/Packages/com.unity.render-pipelines.universal/Editor/Tools.meta
new file mode 100644
index 00000000000..b25ad0f0dc3
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 715d10cee9082354a92701de6d5f6527
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/.buginfo b/Packages/com.unity.render-pipelines.universal/Editor/Tools/.buginfo
new file mode 100644
index 00000000000..a8e3ae67ae4
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/.buginfo
@@ -0,0 +1 @@
+area: Graphics Tools
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader.meta b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader.meta
new file mode 100644
index 00000000000..f416f5b78de
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: d5fa30f043d2e274f9024230be655650
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderProviders.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderProviders.cs
new file mode 100644
index 00000000000..538bd849b21
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderProviders.cs
@@ -0,0 +1,145 @@
+using System.Collections.Generic;
+using UnityEngine.Rendering;
+using UnityEngine.Rendering.Universal;
+
+namespace UnityEditor.Rendering.Universal
+{
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ class StandardMaterialUpgraderProvider : IMaterialUpgradersProvider
+ {
+ public IEnumerable GetUpgraders()
+ {
+ yield return new StandardUpgrader("Standard");
+ yield return new StandardUpgrader("Standard (Specular setup)");
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ class StandardSimpleLightingUpgraderProvider : IMaterialUpgradersProvider
+ {
+ public IEnumerable GetUpgraders()
+ {
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse Detail", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse Fast", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Specular", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Bumped Specular", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Parallax Diffuse", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Parallax Specular", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/VertexLit", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/VertexLit", SupportedUpgradeParams.specularAlphaCutout);
+
+ // Reflective
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Diffuse", SupportedUpgradeParams.diffuseCubemap);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Specular", SupportedUpgradeParams.specularCubemap);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Unlit", SupportedUpgradeParams.diffuseCubemap);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped VertexLit", SupportedUpgradeParams.diffuseCubemap);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Diffuse", SupportedUpgradeParams.diffuseCubemap);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Specular", SupportedUpgradeParams.specularCubemap);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/VertexLit", SupportedUpgradeParams.diffuseCubemap);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Parallax Diffuse", SupportedUpgradeParams.diffuseCubemap);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Parallax Specular", SupportedUpgradeParams.specularCubemap);
+
+ // Self-Illum
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Diffuse", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Parallax Diffuse", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Specular", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Bumped Specular", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Parallax Specular", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/VertexLit", SupportedUpgradeParams.specularOpaque);
+
+ // Alpha Blended
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Diffuse", SupportedUpgradeParams.diffuseAlpha);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Specular", SupportedUpgradeParams.specularAlpha);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Bumped Diffuse", SupportedUpgradeParams.diffuseAlpha);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Bumped Specular", SupportedUpgradeParams.specularAlpha);
+
+ // Cutout
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Diffuse", SupportedUpgradeParams.diffuseAlphaCutout);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Specular", SupportedUpgradeParams.specularAlphaCutout);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Bumped Diffuse", SupportedUpgradeParams.diffuseAlphaCutout);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Bumped Specular", SupportedUpgradeParams.specularAlphaCutout);
+
+ // Lightmapped
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Diffuse", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Specular", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/VertexLit", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Bumped Specular", SupportedUpgradeParams.specularOpaque);
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ class SpriteMaterialUpgraderProviders : IMaterialUpgradersProvider
+ {
+ public IEnumerable GetUpgraders()
+ {
+ yield return new StandardSimpleLightingUpgrader("Sprites/Diffuse", SupportedUpgradeParams.diffuseAlpha);
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ class UIMaterialUpgraderProviders : IMaterialUpgradersProvider
+ {
+ public IEnumerable GetUpgraders()
+ {
+ yield return new StandardSimpleLightingUpgrader("UI/Lit/Bumped", SupportedUpgradeParams.diffuseAlphaCutout);
+ yield return new StandardSimpleLightingUpgrader("UI/Lit/Detail", SupportedUpgradeParams.diffuseAlphaCutout);
+ yield return new StandardSimpleLightingUpgrader("UI/Lit/Refraction", SupportedUpgradeParams.diffuseAlphaCutout);
+ yield return new StandardSimpleLightingUpgrader("UI/Lit/Refraction Detail", SupportedUpgradeParams.diffuseAlphaCutout);
+ yield return new StandardSimpleLightingUpgrader("UI/Lit/Transparent", SupportedUpgradeParams.diffuseAlpha);
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ class MobileMaterialUpgraderProviders : IMaterialUpgradersProvider
+ {
+ public IEnumerable GetUpgraders()
+ {
+ yield return new StandardSimpleLightingUpgrader("Mobile/Diffuse", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Mobile/Bumped Specular", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Mobile/Bumped Specular (1 Directional Light)", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Mobile/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Mobile/Unlit (Supports Lightmap)", SupportedUpgradeParams.diffuseOpaque);
+ yield return new StandardSimpleLightingUpgrader("Mobile/VertexLit", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Mobile/VertexLit (Only Directional Lights)", SupportedUpgradeParams.specularOpaque);
+ yield return new StandardSimpleLightingUpgrader("Mobile/Particles/VertexLit Blended", SupportedUpgradeParams.specularOpaque);
+
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ class TerrainMaterialUpgraderProvider : IMaterialUpgradersProvider
+ {
+ public IEnumerable GetUpgraders()
+ {
+ yield return new TerrainUpgrader("Nature/Terrain/Standard");
+ yield return new SpeedTreeUpgrader("Nature/SpeedTree");
+ yield return new SpeedTreeBillboardUpgrader("Nature/SpeedTree Billboard");
+ yield return new UniversalSpeedTree8Upgrader("Nature/SpeedTree8");
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ class ParticleMaterialUpgraderProvider : IMaterialUpgradersProvider
+ {
+ public IEnumerable GetUpgraders()
+ {
+ // Standard particle shaders
+ yield return new ParticleUpgrader("Particles/Standard Surface");
+ yield return new ParticleUpgrader("Particles/Standard Unlit");
+ yield return new ParticleUpgrader("Particles/VertexLit Blended");
+ }
+ }
+
+ [SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
+ class AutodeskMaterialUpgraderProvider : IMaterialUpgradersProvider
+ {
+ public IEnumerable GetUpgraders()
+ {
+ yield return new AutodeskInteractiveUpgrader("Autodesk Interactive");
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderProviders.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderProviders.cs.meta
new file mode 100644
index 00000000000..f0836679d47
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/MaterialUpgraderProviders.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 2f37f38354ae11b4ba31a324dbabef7d
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineMaterialUpgrader.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalRenderPipelineMaterialUpgrader.cs
similarity index 60%
rename from Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineMaterialUpgrader.cs
rename to Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalRenderPipelineMaterialUpgrader.cs
index 287c1658e2e..c6935e6076c 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineMaterialUpgrader.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalRenderPipelineMaterialUpgrader.cs
@@ -1,11 +1,9 @@
using System;
using System.Collections.Generic;
-using UnityEditor.Rendering.Universal;
+using System.Runtime.CompilerServices;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
-using System.Runtime.CompilerServices;
-using System.Linq;
[assembly: InternalsVisibleTo("MaterialPostprocessor")]
namespace UnityEditor.Rendering.Universal
@@ -13,256 +11,45 @@ namespace UnityEditor.Rendering.Universal
internal sealed class UniversalRenderPipelineMaterialUpgrader : RenderPipelineConverter
{
public override string name => "Material Upgrade";
- public override string info => "This converter converts Materials from the Built-in Render Pipeline to URP. This converter works best on default pre-built Materials that are supplied by Unity. Custom Materials are not supported.";
+ public override string info => $@"This converter upgrades Materials from the Built-in Render Pipeline to URP.
+It uses {typeof(MaterialUpgrader).Name}instances that implement {typeof(IMaterialUpgradersProvider).Name}.";
+
public override int priority => -1000;
public override Type container => typeof(BuiltInToURPConverterContainer);
List m_AssetsToConvert = new List();
static List m_Upgraders;
- private static HashSet m_ShaderNamesToIgnore;
-
- public IReadOnlyList upgraders => m_Upgraders;
- static UniversalRenderPipelineMaterialUpgrader()
- {
- m_Upgraders = new List();
- GetUpgraders(ref m_Upgraders);
-
- m_ShaderNamesToIgnore = new HashSet();
- GetShaderNamesToIgnore(ref m_ShaderNamesToIgnore);
- }
-
- private static void UpgradeProjectMaterials()
- {
- m_Upgraders = new List();
- GetUpgraders(ref m_Upgraders);
-
- m_ShaderNamesToIgnore = new HashSet();
- GetShaderNamesToIgnore(ref m_ShaderNamesToIgnore);
-
- MaterialUpgrader.UpgradeProjectFolder(m_Upgraders, m_ShaderNamesToIgnore, "Upgrade to URP Materials", MaterialUpgrader.UpgradeFlags.LogMessageWhenNoUpgraderFound);
- // TODO: return upgrade paths and pass to AnimationClipUpgrader
- AnimationClipUpgrader.DoUpgradeAllClipsMenuItem(m_Upgraders, "Upgrade Animation Clips to URP Materials");
- }
-
- [MenuItem("Edit/Rendering/Materials/Convert Selected Built-in Materials to URP", true)]
- static bool MaterialValidate(MenuCommand command)
- {
- foreach (var obj in Selection.objects)
- {
- if (obj is not Material) return false;
- }
-
- return true;
- }
-
- [MenuItem("Edit/Rendering/Materials/Convert Selected Built-in Materials to URP", priority = CoreUtils.Sections.section1 + CoreUtils.Priorities.editMenuPriority + 1)]
- private static void UpgradeSelectedMaterialsMenuItem()
- {
- UpgradeSelectedMaterials(false);
- }
-
- // Added bool variable in case this method was used by anyone.
- // Doing this, since the menuitem should behave as it did before,
- // and then we didn't have the Animation clips upgrader
- private static void UpgradeSelectedMaterials(bool UpgradeAnimationClips = true)
- {
- List upgraders = new List();
- GetUpgraders(ref upgraders);
-
- HashSet shaderNamesToIgnore = new HashSet();
- GetShaderNamesToIgnore(ref shaderNamesToIgnore);
-
- MaterialUpgrader.UpgradeSelection(upgraders, shaderNamesToIgnore, "Upgrade to URP Materials", MaterialUpgrader.UpgradeFlags.LogMessageWhenNoUpgraderFound);
- if (UpgradeAnimationClips)
- {
- // TODO: return upgrade paths and pass to AnimationClipUpgrader
- AnimationClipUpgrader.DoUpgradeAllClipsMenuItem(upgraders, "Upgrade Animation Clips to URP Materials");
- }
- }
-
- private static void GetShaderNamesToIgnore(ref HashSet shadersToIgnore)
- {
- shadersToIgnore.Add("Universal Render Pipeline/Baked Lit");
- shadersToIgnore.Add("Universal Render Pipeline/Lit");
- shadersToIgnore.Add("Universal Render Pipeline/Particles/Lit");
- shadersToIgnore.Add("Universal Render Pipeline/Particles/Simple Lit");
- shadersToIgnore.Add("Universal Render Pipeline/Particles/Unlit");
- shadersToIgnore.Add("Universal Render Pipeline/Simple Lit");
- shadersToIgnore.Add("Universal Render Pipeline/Nature/SpeedTree7");
- shadersToIgnore.Add("Universal Render Pipeline/Nature/SpeedTree7 Billboard");
- shadersToIgnore.Add("Universal Render Pipeline/Nature/SpeedTree8");
- shadersToIgnore.Add("Universal Render Pipeline/Nature/SpeedTree8_PBRLit");
- shadersToIgnore.Add("Universal Render Pipeline/2D/Sprite-Lit-Default");
- shadersToIgnore.Add("Universal Render Pipeline/Terrain/Lit");
- shadersToIgnore.Add("Universal Render Pipeline/Unlit");
- shadersToIgnore.Add("Sprites/Default");
- }
- private static void GetUpgraders(ref List upgraders)
- {
- /////////////////////////////////////
- // Unity Standard Upgraders //
- /////////////////////////////////////
- upgraders.Add(new StandardUpgrader("Standard"));
- upgraders.Add(new StandardUpgrader("Standard (Specular setup)"));
-
- /////////////////////////////////////
- // Legacy Shaders upgraders /
- /////////////////////////////////////
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse Detail", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Diffuse Fast", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Specular", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Bumped Specular", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Parallax Diffuse", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Parallax Specular", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/VertexLit", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/VertexLit", SupportedUpgradeParams.specularAlphaCutout));
-
- // Reflective
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Diffuse", SupportedUpgradeParams.diffuseCubemap));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Specular", SupportedUpgradeParams.specularCubemap));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped Unlit", SupportedUpgradeParams.diffuseCubemap));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Bumped VertexLit", SupportedUpgradeParams.diffuseCubemap));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Diffuse", SupportedUpgradeParams.diffuseCubemap));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Specular", SupportedUpgradeParams.specularCubemap));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/VertexLit", SupportedUpgradeParams.diffuseCubemap));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Parallax Diffuse", SupportedUpgradeParams.diffuseCubemap));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Reflective/Parallax Specular", SupportedUpgradeParams.specularCubemap));
-
- // Self-Illum upgrader
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Diffuse", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Parallax Diffuse", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Specular", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Bumped Specular", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/Parallax Specular", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Self-Illumin/VertexLit", SupportedUpgradeParams.specularOpaque));
-
- // Alpha Blended
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Diffuse", SupportedUpgradeParams.diffuseAlpha));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Specular", SupportedUpgradeParams.specularAlpha));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Bumped Diffuse", SupportedUpgradeParams.diffuseAlpha));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Bumped Specular", SupportedUpgradeParams.specularAlpha));
-
- // Cutout
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Diffuse", SupportedUpgradeParams.diffuseAlphaCutout));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Specular", SupportedUpgradeParams.specularAlphaCutout));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Bumped Diffuse", SupportedUpgradeParams.diffuseAlphaCutout));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Transparent/Cutout/Bumped Specular", SupportedUpgradeParams.specularAlphaCutout));
-
- // Lightmapped
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Diffuse", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Specular", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/VertexLit", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Legacy Shaders/Lightmapped/Bumped Specular", SupportedUpgradeParams.specularOpaque));
-
- /////////////////////////////////////
- // Sprites Upgraders
- /////////////////////////////////////
- upgraders.Add(new StandardSimpleLightingUpgrader("Sprites/Diffuse", SupportedUpgradeParams.diffuseAlpha));
-
- /////////////////////////////////////
- // UI Upgraders
- /////////////////////////////////////
- upgraders.Add(new StandardSimpleLightingUpgrader("UI/Lit/Bumped", SupportedUpgradeParams.diffuseAlphaCutout));
- upgraders.Add(new StandardSimpleLightingUpgrader("UI/Lit/Detail", SupportedUpgradeParams.diffuseAlphaCutout));
- upgraders.Add(new StandardSimpleLightingUpgrader("UI/Lit/Refraction", SupportedUpgradeParams.diffuseAlphaCutout));
- upgraders.Add(new StandardSimpleLightingUpgrader("UI/Lit/Refraction Detail", SupportedUpgradeParams.diffuseAlphaCutout));
- upgraders.Add(new StandardSimpleLightingUpgrader("UI/Lit/Transparent", SupportedUpgradeParams.diffuseAlpha));
-
-
- /////////////////////////////////////
- // Mobile Upgraders /
- /////////////////////////////////////
- upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/Diffuse", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/Bumped Specular", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/Bumped Specular (1 Directional Light)", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/Bumped Diffuse", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/Unlit (Supports Lightmap)", SupportedUpgradeParams.diffuseOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/VertexLit", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/VertexLit (Only Directional Lights)", SupportedUpgradeParams.specularOpaque));
- upgraders.Add(new StandardSimpleLightingUpgrader("Mobile/Particles/VertexLit Blended", SupportedUpgradeParams.specularOpaque));
-
- ////////////////////////////////////
- // Terrain Upgraders //
- ////////////////////////////////////
- upgraders.Add(new TerrainUpgrader("Nature/Terrain/Standard"));
- upgraders.Add(new SpeedTreeUpgrader("Nature/SpeedTree"));
- upgraders.Add(new SpeedTreeBillboardUpgrader("Nature/SpeedTree Billboard"));
- upgraders.Add(new UniversalSpeedTree8Upgrader("Nature/SpeedTree8"));
-
- ////////////////////////////////////
- // Particle Upgraders //
- ////////////////////////////////////
- upgraders.Add(new ParticleUpgrader("Particles/Standard Surface"));
- upgraders.Add(new ParticleUpgrader("Particles/Standard Unlit"));
- upgraders.Add(new ParticleUpgrader("Particles/VertexLit Blended"));
-
- ////////////////////////////////////
- // Autodesk Interactive //
- ////////////////////////////////////
- upgraders.Add(new AutodeskInteractiveUpgrader("Autodesk Interactive"));
- }
-
- bool IsMaterialPath(string path)
+ public UniversalRenderPipelineMaterialUpgrader()
{
- if (string.IsNullOrEmpty(path))
- {
- throw new ArgumentNullException(nameof(path));
- }
- // Making sure it is a .mat file and it is not from a package.
- return path.EndsWith(".mat", StringComparison.OrdinalIgnoreCase) && !(path.StartsWith("Packages/", StringComparison.OrdinalIgnoreCase));
- }
-
- bool ShouldUpgradeShader(Material material, HashSet shaderNamesToIgnore)
- {
- if (material == null)
- return false;
-
- if (material.shader == null)
- return false;
-
- // Checking if the Shader Graph tag exists, if it does it is a Shader Graph and shouldnt be Upgraded here
- var result = material.GetTag("ShaderGraphShader", false, "sg");
- if (result != "sg")
- {
- return false;
- }
- return !shaderNamesToIgnore.Contains(material.shader.name);
+ m_Upgraders = MaterialUpgrader.FetchAllUpgradersForPipeline(typeof(UniversalRenderPipelineAsset));
}
///
public override void OnInitialize(InitializeConverterContext context, Action callback)
{
List descriptors = new List();
- foreach (string path in AssetDatabase.GetAllAssetPaths())
+
+ var entries = MaterialUpgrader.FetchAllUpgradableMaterialsForPipeline(typeof(UniversalRenderPipelineAsset));
+ foreach (var material in entries)
{
- if (IsMaterialPath(path))
+ ConverterItemDescriptor desc = new ConverterItemDescriptor()
{
- Material m = AssetDatabase.LoadMainAssetAtPath(path) as Material;
-
- // We should also check if the material is already URP
- if (!ShouldUpgradeShader(m, m_ShaderNamesToIgnore))
- continue;
-
- ConverterItemDescriptor desc = new ConverterItemDescriptor()
- {
- name = m.name,
- info = path,
- warningMessage = String.Empty,
- helpLink = String.Empty,
- };
-
- descriptors.Add(desc);
- }
+ name = material.name,
+ info = AssetDatabase.GetAssetPath(material),
+ warningMessage = string.Empty,
+ helpLink = string.Empty,
+ };
+
+ descriptors.Add(desc);
}
- // This need to be sorted by name property
- descriptors = descriptors.OrderBy(o => o.name).ToList();
+ descriptors.Sort(delegate (ConverterItemDescriptor a, ConverterItemDescriptor b)
+ {
+ return string.Compare(a.name, b.name, StringComparison.Ordinal);
+ });
+
foreach (var desc in descriptors)
{
context.AddAssetToConvert(desc);
@@ -551,6 +338,7 @@ public StandardUpgrader(string oldShaderName)
}
RenameFloat("_Mode", "_Surface");
+ RenameFloat("_Mode", "_AlphaClip", renderingMode => renderingMode == 1.0f);
RenameTexture("_MainTex", "_BaseMap");
RenameColor("_Color", "_BaseColor");
RenameFloat("_GlossyReflections", "_EnvironmentReflections");
@@ -755,6 +543,14 @@ public static void UpdateSurfaceBlendModes(Material material)
///
public class AutodeskInteractiveUpgrader : MaterialUpgrader
{
+ enum LegacyRenderingMode
+ {
+ Opaque,
+ Cutout,
+ Fade, // Old school alpha-blending mode, fresnel does not affect amount of transparency
+ Transparent // Physically plausible transparency mode, implemented as alpha pre-multiply
+ }
+
///
/// Constructor for the autodesk interactive upgrader.
///
@@ -776,6 +572,25 @@ public override void Convert(Material srcMaterial, Material dstMaterial)
dstMaterial.SetFloat("_UseAoMap", srcMaterial.GetTexture("_OcclusionMap") ? 1.0f : .0f);
dstMaterial.SetVector("_UvOffset", srcMaterial.GetTextureOffset("_MainTex"));
dstMaterial.SetVector("_UvTiling", srcMaterial.GetTextureScale("_MainTex"));
+
+ var legacyRenderingMode = (LegacyRenderingMode)srcMaterial.GetFloat("_Mode");
+ switch (legacyRenderingMode)
+ {
+ case LegacyRenderingMode.Opaque:
+ RenameShader(OldShaderPath, GraphicsSettings.GetRenderPipelineSettings().autodeskInteractiveShader.name, UniversalRenderPipelineMaterialUpgrader.DisableKeywords);
+ break;
+ case LegacyRenderingMode.Cutout:
+ RenameShader(OldShaderPath, GraphicsSettings.GetRenderPipelineSettings().autodeskInteractiveMaskedShader.name, UniversalRenderPipelineMaterialUpgrader.DisableKeywords);
+ dstMaterial.SetFloat("_UseOpacityMap", .0f);
+ dstMaterial.SetFloat("_OpacityThreshold", srcMaterial.GetFloat("_Cutoff"));
+ break;
+ case LegacyRenderingMode.Fade:
+ case LegacyRenderingMode.Transparent:
+ RenameShader(OldShaderPath, GraphicsSettings.GetRenderPipelineSettings().autodeskInteractiveTransparentShader.name, UniversalRenderPipelineMaterialUpgrader.DisableKeywords);
+ dstMaterial.SetFloat("_UseOpacityMap", .0f);
+ dstMaterial.SetFloat("_Opacity", srcMaterial.GetColor("_Color").a);
+ break;
+ }
}
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineMaterialUpgrader.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalRenderPipelineMaterialUpgrader.cs.meta
similarity index 100%
rename from Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineMaterialUpgrader.cs.meta
rename to Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalRenderPipelineMaterialUpgrader.cs.meta
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalSpeedTree8MaterialUpgrader.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalSpeedTree8MaterialUpgrader.cs
similarity index 99%
rename from Packages/com.unity.render-pipelines.universal/Editor/UniversalSpeedTree8MaterialUpgrader.cs
rename to Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalSpeedTree8MaterialUpgrader.cs
index 21e00edd06c..d26163f006b 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/UniversalSpeedTree8MaterialUpgrader.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalSpeedTree8MaterialUpgrader.cs
@@ -1,7 +1,6 @@
-using System;
-using UnityEngine.Rendering.Universal;
using UnityEngine;
using UnityEngine.Rendering;
+using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalSpeedTree8MaterialUpgrader.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalSpeedTree8MaterialUpgrader.cs.meta
similarity index 100%
rename from Packages/com.unity.render-pipelines.universal/Editor/UniversalSpeedTree8MaterialUpgrader.cs.meta
rename to Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalSpeedTree8MaterialUpgrader.cs.meta
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalSpeedTree9MaterialUpgrader.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalSpeedTree9MaterialUpgrader.cs
similarity index 100%
rename from Packages/com.unity.render-pipelines.universal/Editor/UniversalSpeedTree9MaterialUpgrader.cs
rename to Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalSpeedTree9MaterialUpgrader.cs
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalSpeedTree9MaterialUpgrader.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalSpeedTree9MaterialUpgrader.cs.meta
similarity index 100%
rename from Packages/com.unity.render-pipelines.universal/Editor/UniversalSpeedTree9MaterialUpgrader.cs.meta
rename to Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UniversalSpeedTree9MaterialUpgrader.cs.meta
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UpgradeCommon.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UpgradeCommon.cs
similarity index 98%
rename from Packages/com.unity.render-pipelines.universal/Editor/UpgradeCommon.cs
rename to Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UpgradeCommon.cs
index ef150bcb04c..1347326895a 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/UpgradeCommon.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UpgradeCommon.cs
@@ -1,5 +1,3 @@
-using UnityEngine.Scripting.APIUpdating;
-
namespace UnityEditor.Rendering.Universal
{
///
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UpgradeCommon.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UpgradeCommon.cs.meta
similarity index 100%
rename from Packages/com.unity.render-pipelines.universal/Editor/UpgradeCommon.cs.meta
rename to Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UpgradeCommon.cs.meta
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UpgradeUtility.cs b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UpgradeUtility.cs
similarity index 100%
rename from Packages/com.unity.render-pipelines.universal/Editor/UpgradeUtility.cs
rename to Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UpgradeUtility.cs
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UpgradeUtility.cs.meta b/Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UpgradeUtility.cs.meta
similarity index 100%
rename from Packages/com.unity.render-pipelines.universal/Editor/UpgradeUtility.cs.meta
rename to Packages/com.unity.render-pipelines.universal/Editor/Tools/MaterialUpgrader/UpgradeUtility.cs.meta
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/Unity.RenderPipelines.Universal.Editor.asmdef b/Packages/com.unity.render-pipelines.universal/Editor/Unity.RenderPipelines.Universal.Editor.asmdef
index 714be72c6fe..da5458a3447 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/Unity.RenderPipelines.Universal.Editor.asmdef
+++ b/Packages/com.unity.render-pipelines.universal/Editor/Unity.RenderPipelines.Universal.Editor.asmdef
@@ -31,9 +31,9 @@
"defineConstraints": [],
"versionDefines": [
{
- "name": "com.unity.adaptiveperformance",
- "expression": "2.0.0-preview.7",
- "define": "ADAPTIVE_PERFORMANCE_2_0_0_OR_NEWER"
+ "name": "com.unity.modules.adaptiveperformance",
+ "expression": "1.0.0",
+ "define": "ENABLE_ADAPTIVE_PERFORMANCE"
},
{
"name": "com.unity.modules.xr",
@@ -57,4 +57,4 @@
}
],
"noEngineReferences": false
-}
+}
\ No newline at end of file
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/SerializedUniversalRenderPipelineAsset.cs b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/SerializedUniversalRenderPipelineAsset.cs
index 132deefd387..79d38947f35 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/SerializedUniversalRenderPipelineAsset.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/SerializedUniversalRenderPipelineAsset.cs
@@ -1,4 +1,4 @@
-using UnityEditorInternal;
+using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
@@ -21,6 +21,11 @@ internal class SerializedUniversalRenderPipelineAsset
public SerializedProperty msaa { get; }
public SerializedProperty renderScale { get; }
public SerializedProperty upscalingFilter { get; }
+#if ENABLE_UPSCALER_FRAMEWORK
+ public SerializedProperty iUpscalerName { get; }
+
+ public SerializedProperty upscalerOptions { get; }
+#endif
public SerializedProperty fsrOverrideSharpness { get; }
public SerializedProperty fsrSharpness { get; }
@@ -88,7 +93,7 @@ internal class SerializedUniversalRenderPipelineAsset
public SerializedProperty smallMeshScreenPercentage { get; }
public SerializedProperty gpuResidentDrawerEnableOcclusionCullingInCameras { get; }
-#if ADAPTIVE_PERFORMANCE_2_0_0_OR_NEWER
+#if ENABLE_ADAPTIVE_PERFORMANCE
public SerializedProperty useAdaptivePerformance { get; }
#endif
public UniversalRenderPipelineAsset asset { get; }
@@ -113,6 +118,10 @@ public SerializedUniversalRenderPipelineAsset(SerializedObject serializedObject)
msaa = serializedObject.FindProperty("m_MSAA");
renderScale = serializedObject.FindProperty("m_RenderScale");
upscalingFilter = serializedObject.FindProperty("m_UpscalingFilter");
+#if ENABLE_UPSCALER_FRAMEWORK
+ iUpscalerName = serializedObject.FindProperty("m_IUpscalerName");
+ upscalerOptions = serializedObject.FindProperty("m_UpscalerOptions");
+#endif
fsrOverrideSharpness = serializedObject.FindProperty("m_FsrOverrideSharpness");
fsrSharpness = serializedObject.FindProperty("m_FsrSharpness");
@@ -184,9 +193,18 @@ public SerializedUniversalRenderPipelineAsset(SerializedObject serializedObject)
smallMeshScreenPercentage = serializedObject.FindProperty("m_SmallMeshScreenPercentage");
gpuResidentDrawerEnableOcclusionCullingInCameras = serializedObject.FindProperty("m_GPUResidentDrawerEnableOcclusionCullingInCameras");
-#if ADAPTIVE_PERFORMANCE_2_0_0_OR_NEWER
+#if ENABLE_ADAPTIVE_PERFORMANCE
useAdaptivePerformance = serializedObject.FindProperty("m_UseAdaptivePerformance");
#endif
+#if ENABLE_UPSCALER_FRAMEWORK
+ bool referenceModified = UpscalerOptions.ValidateSerializedUpscalerOptionReferencesWithinRPAsset(asset, upscalerOptions);
+ if (referenceModified)
+ {
+ serializedObject.ApplyModifiedProperties();
+ EditorUtility.SetDirty(asset);
+ }
+#endif
+
string Key = "Universal_Shadow_Setting_Unit:UI_State";
state = new EditorPrefBoolFlags(Key);
}
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Drawers.cs b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Drawers.cs
index d461504de59..4d9b60731b2 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Drawers.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Drawers.cs
@@ -1,4 +1,5 @@
using System;
+using System.Reflection;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
@@ -16,7 +17,7 @@ internal enum Expandable
Lighting = 1 << 3,
Shadows = 1 << 4,
PostProcessing = 1 << 5,
-#if ADAPTIVE_PERFORMANCE_2_0_0_OR_NEWER
+#if ENABLE_ADAPTIVE_PERFORMANCE
AdaptivePerformance = 1 << 6,
#endif
Volumes = 1 << 7,
@@ -106,7 +107,7 @@ internal static void Expand(Expandable expandable, bool state)
CED.AdditionalPropertiesFoldoutGroup(Styles.shadowSettingsText, Expandable.Shadows, k_ExpandedState, ExpandableAdditional.Shadows, k_AdditionalPropertiesState, DrawShadows, DrawShadowsAdditional),
CED.FoldoutGroup(Styles.postProcessingSettingsText, Expandable.PostProcessing, k_ExpandedState, DrawPostProcessing),
CED.FoldoutGroup(Styles.volumeSettingsText, Expandable.Volumes, k_ExpandedState, DrawVolumes)
-#if ADAPTIVE_PERFORMANCE_2_0_0_OR_NEWER
+#if ENABLE_ADAPTIVE_PERFORMANCE
, CED.FoldoutGroup(Styles.adaptivePerformanceText, Expandable.AdaptivePerformance, k_ExpandedState, CED.Group(DrawAdaptivePerformance))
#endif
);
@@ -189,51 +190,169 @@ static void DrawQuality(SerializedUniversalRenderPipelineAsset serialized, Edito
EditorGUILayout.PropertyField(serialized.msaa, Styles.msaaText);
serialized.renderScale.floatValue = EditorGUILayout.Slider(Styles.renderScaleText, serialized.renderScale.floatValue, UniversalRenderPipeline.minRenderScale, UniversalRenderPipeline.maxRenderScale);
- EditorGUILayout.PropertyField(serialized.upscalingFilter, Styles.upscalingFilterText);
- if (serialized.asset.upscalingFilter == UpscalingFilterSelection.FSR)
- {
- ++EditorGUI.indentLevel;
- EditorGUILayout.PropertyField(serialized.fsrOverrideSharpness, Styles.fsrOverrideSharpness);
+ DrawUpscalingFilterDropdownAndOptions(serialized);
- // We put the FSR sharpness override value behind an override checkbox so we can tell when the user intends to use a custom value rather than the default.
- if (serialized.fsrOverrideSharpness.boolValue)
+ EditorGUILayout.PropertyField(serialized.enableLODCrossFadeProp, Styles.enableLODCrossFadeText);
+ EditorGUI.BeginDisabledGroup(!serialized.enableLODCrossFadeProp.boolValue);
+ EditorGUILayout.PropertyField(serialized.lodCrossFadeDitheringTypeProp, Styles.lodCrossFadeDitheringTypeText);
+ if (serialized.asset.enableLODCrossFade && serialized.asset.lodCrossFadeDitheringType == LODCrossFadeDitheringType.Stencil)
+ {
+ var rendererData = serialized.asset.m_RendererDataList[serialized.asset.m_DefaultRendererIndex];
+ if (rendererData is UniversalRendererData && ((UniversalRendererData)rendererData).defaultStencilState.overrideStencilState)
{
- serialized.fsrSharpness.floatValue = EditorGUILayout.Slider(Styles.fsrSharpnessText, serialized.fsrSharpness.floatValue, 0.0f, 1.0f);
+ EditorGUILayout.HelpBox(Styles.stencilLodCrossFadeWarningMessage.text, MessageType.Warning, true);
}
+ }
- --EditorGUI.indentLevel;
+ EditorGUI.EndDisabledGroup();
+ }
+
+ static void DrawUpscalingFilterDropdownAndOptions(SerializedUniversalRenderPipelineAsset serialized)
+ {
+ // Get the names of IUpscalers currently present
+ string[] iUpscalerNames = { };
+#if ENABLE_UPSCALER_FRAMEWORK
+ if (UniversalRenderPipeline.upscaling != null)
+ {
+ iUpscalerNames = UniversalRenderPipeline.upscaling.upscalerNames;
}
- else if (serialized.asset.upscalingFilter == UpscalingFilterSelection.STP)
+#endif
+
+ // Count builtin and IUpscalers
+#if ENABLE_UPSCALER_FRAMEWORK
+ int numBuiltInUpscalers = (int)UpscalingFilterSelection.IUpscaler;
+#else
+ int numBuiltInUpscalers = (int)UpscalingFilterSelection.STP + 1;
+#endif
+ int numIUpscalers = iUpscalerNames.Length;
+ int numTotalUpscalers = numBuiltInUpscalers + numIUpscalers;
+
+ // Create arrays for options and enum values
+ string[] names = new string[numTotalUpscalers];
+
+ // Get names and values for builtin upscalers
{
-#if URP_COMPATIBILITY_MODE
- // Warn users if they attempt to enable STP without render graph
- if (GraphicsSettings.GetRenderPipelineSettings().enableRenderCompatibilityMode)
+ var bnames = Enum.GetNames(typeof(UpscalingFilterSelection));
+
+ for (int i = 0; i < numBuiltInUpscalers; i++)
{
- EditorGUILayout.HelpBox(Styles.stpRequiresRenderGraph, MessageType.Warning, true);
+ // Get the display name from the InspectorName attribute if it exists
+ var field = typeof(UpscalingFilterSelection).GetField(bnames[i]);
+ var inspectorNameAttribute = field.GetCustomAttribute();
+ names[i] = inspectorNameAttribute != null ? inspectorNameAttribute.displayName : bnames[i];
}
+ }
+
+ // Get names and values for IUpscalers
+ for (int i = 0; i < numIUpscalers; i++)
+ {
+ var dst = numBuiltInUpscalers + i;
+ names[dst] = iUpscalerNames[i];
+ }
+
+ // Get the current enum value
+ UpscalingFilterSelection curUpscaler =
+ (UpscalingFilterSelection)serialized.upscalingFilter.enumValueIndex;
+
+ // Find the current selected index
+ int selectedIndex = 0; // [0, iUpscalerCount + BuiltinUpscalerCount)
+#if ENABLE_UPSCALER_FRAMEWORK
+ int selectedIUpscalerIndex = -1; // [0, iUpscalerCount)
+ if (curUpscaler == UpscalingFilterSelection.IUpscaler) // An IUpscaler is selected.
+ {
+ // Find the package by name in our options
+ selectedIUpscalerIndex = Array.IndexOf(iUpscalerNames, serialized.iUpscalerName.stringValue);
+
+ selectedIndex = selectedIUpscalerIndex == -1
+ ? 0 // The IUpscaler that was serialized in the asset wasn't found. This can happen if an upscaling package was removed.
+ : numBuiltInUpscalers + selectedIUpscalerIndex;
+ }
+ else // A built-in upscaler is selected.
+#else
+ // A built-in upscaler is selected (IUpscaler not available).
#endif
+ {
+ selectedIndex = serialized.upscalingFilter.enumValueIndex;
+ }
- // Warn users about performance expectations if they attempt to enable STP on a mobile platform
- if (PlatformAutoDetect.isShaderAPIMobileDefined)
- {
- EditorGUILayout.HelpBox(Styles.stpMobilePlatformWarning, MessageType.Warning, true);
- }
+ // --------------------------------------------------- GUI ---------------------------------------------------
+
+ // Show the dropdown
+ EditorGUI.BeginChangeCheck();
+ selectedIndex = EditorGUILayout.Popup(Styles.upscalingFilterText, selectedIndex, names);
+ if (EditorGUI.EndChangeCheck())
+ {
+ serialized.upscalingFilter.enumValueIndex = Math.Min(selectedIndex,
+#if ENABLE_UPSCALER_FRAMEWORK
+ (int)UpscalingFilterSelection.IUpscaler
+#else
+ (int)UpscalingFilterSelection.STP
+#endif
+ );
+
+#if ENABLE_UPSCALER_FRAMEWORK
+ serialized.iUpscalerName.stringValue = selectedIndex < numBuiltInUpscalers ?
+ string.Empty : // A built-in upscaler is selected
+ names[selectedIndex]; // An IUpscaler is selected.
+#endif
}
- EditorGUILayout.PropertyField(serialized.enableLODCrossFadeProp, Styles.enableLODCrossFadeText);
- EditorGUI.BeginDisabledGroup(!serialized.enableLODCrossFadeProp.boolValue);
- EditorGUILayout.PropertyField(serialized.lodCrossFadeDitheringTypeProp, Styles.lodCrossFadeDitheringTypeText);
- if (serialized.asset.enableLODCrossFade && serialized.asset.lodCrossFadeDitheringType == LODCrossFadeDitheringType.Stencil)
+ // draw upscaler options, if any
+ switch (serialized.asset.upscalingFilter)
{
- var rendererData = serialized.asset.m_RendererDataList[serialized.asset.m_DefaultRendererIndex];
- if (rendererData is UniversalRendererData && ((UniversalRendererData)rendererData).defaultStencilState.overrideStencilState)
+ case UpscalingFilterSelection.FSR:
{
- EditorGUILayout.HelpBox(Styles.stencilLodCrossFadeWarningMessage.text, MessageType.Warning, true);
- }
+ ++EditorGUI.indentLevel;
+
+ EditorGUILayout.PropertyField(serialized.fsrOverrideSharpness, Styles.fsrOverrideSharpness);
+
+ // We put the FSR sharpness override value behind an override checkbox so we can tell when the user intends to use a custom value rather than the default.
+ if (serialized.fsrOverrideSharpness.boolValue)
+ {
+ serialized.fsrSharpness.floatValue = EditorGUILayout.Slider(Styles.fsrSharpnessText, serialized.fsrSharpness.floatValue, 0.0f, 1.0f);
+ }
+
+ --EditorGUI.indentLevel;
+ } break;
+
+ case UpscalingFilterSelection.STP:
+ {
+#if URP_COMPATIBILITY_MODE
+ // Warn users if they attempt to enable STP without render graph
+ if (GraphicsSettings.GetRenderPipelineSettings().enableRenderCompatibilityMode)
+ {
+ EditorGUILayout.HelpBox(Styles.stpRequiresRenderGraph, MessageType.Warning, true);
+ }
+#endif
+ // Warn users about performance expectations if they attempt to enable STP on a mobile platform
+ if (PlatformAutoDetect.isShaderAPIMobileDefined)
+ {
+ EditorGUILayout.HelpBox(Styles.stpMobilePlatformWarning, MessageType.Warning, true);
+ }
+ } break;
+
+#if ENABLE_UPSCALER_FRAMEWORK
+ case UpscalingFilterSelection.IUpscaler:
+ {
+ if (RenderPipelineManager.currentPipeline is UniversalRenderPipeline && selectedIUpscalerIndex != -1)
+ {
+ UpscalerOptions options = serialized.asset.GetIUpscalerOptions(serialized.iUpscalerName.stringValue);
+ if (options != null)
+ {
+ ++EditorGUI.indentLevel;
+ bool optionChanged = options.DrawOptionsEditorGUI();
+ if (optionChanged)
+ {
+ EditorUtility.SetDirty(serialized.asset);
+ }
+ --EditorGUI.indentLevel;
+ }
+ }
+ } break;
+#endif
}
- EditorGUI.EndDisabledGroup();
}
static void DrawHDR(SerializedUniversalRenderPipelineAsset serialized, Editor ownerEditor)
@@ -359,11 +478,16 @@ static void DrawLighting(SerializedUniversalRenderPipelineAsset serialized, Edit
EditorGUI.BeginDisabledGroup(!serialized.reflectionProbeBlendingProp.boolValue);
EditorGUILayout.PropertyField(serialized.reflectionProbeAtlasProp, Styles.reflectionProbeAtlasText);
EditorGUI.EndDisabledGroup();
+
// Disable probeAtlas when probeBlending is off.
if (!serialized.reflectionProbeBlendingProp.boolValue)
serialized.reflectionProbeAtlasProp.boolValue = false;
- else if ((GPUResidentDrawerMode)serialized.gpuResidentDrawerMode.intValue != GPUResidentDrawerMode.Disabled && !serialized.reflectionProbeAtlasProp.boolValue)
- EditorGUILayout.HelpBox(Styles.reflectionProbeAtlasGpuResidentDrawerWarningText.text, MessageType.Warning, true);
+
+ if ((GPUResidentDrawerMode)serialized.gpuResidentDrawerMode.intValue != GPUResidentDrawerMode.Disabled)
+ {
+ if (!serialized.reflectionProbeBlendingProp.boolValue || !serialized.reflectionProbeAtlasProp.boolValue)
+ EditorGUILayout.HelpBox(Styles.reflectionProbeBlendingGpuResidentDrawerWarningText.text, MessageType.Warning, true);
+ }
EditorGUI.indentLevel--;
@@ -707,7 +831,7 @@ static void DrawVolumes(SerializedUniversalRenderPipelineAsset serialized, Edito
}
}
-#if ADAPTIVE_PERFORMANCE_2_0_0_OR_NEWER
+#if ENABLE_ADAPTIVE_PERFORMANCE
static void DrawAdaptivePerformance(SerializedUniversalRenderPipelineAsset serialized, Editor ownerEditor)
{
EditorGUILayout.PropertyField(serialized.useAdaptivePerformance, Styles.useAdaptivePerformance);
diff --git a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Skin.cs b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Skin.cs
index c05952d1c1e..e0f6934023f 100644
--- a/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Skin.cs
+++ b/Packages/com.unity.render-pipelines.universal/Editor/UniversalRenderPipelineAsset/UniversalRenderPipelineAssetUI.Skin.cs
@@ -82,7 +82,7 @@ internal static class Styles
public static GUIContent reflectionProbeBlendingText = EditorGUIUtility.TrTextContent("Probe Blending", "If enabled smooth transitions will be created between reflection probes.");
public static GUIContent reflectionProbeAtlasText = EditorGUIUtility.TrTextContent("Probe Atlas Blending", "If enabled, reflection probes will be added to the Forward Plus data grid and combined into a single atlas texture. The atlas is used by default when both Forward Plus and the GPU Resident Drawer are used.");
public static GUIContent reflectionProbeBoxProjectionText = EditorGUIUtility.TrTextContent("Box Projection", "If enabled reflections appear based on the object’s position within the probe’s box, while still using a single probe as the source of the reflection.");
- public static GUIContent reflectionProbeAtlasGpuResidentDrawerWarningText = EditorGUIUtility.TrTextContent("The Probe Atlas Blending is used by default when both Forward Plus and the GPU Resident Drawer are used.");
+ public static GUIContent reflectionProbeBlendingGpuResidentDrawerWarningText = EditorGUIUtility.TrTextContent("Probe Atlas Blending is currently force enabled because GPUResidentDrawer is in use. GPUResidentDrawer currently only supports Reflection Probes via Probe Atlas Blending.");
// Additional lighting settings
public static GUIContent mixedLightingSupportLabel = EditorGUIUtility.TrTextContent("Mixed Lighting", "Makes the render pipeline include mixed-lighting Shader Variants in the build.");
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/AssemblyInfo.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/AssemblyInfo.cs
index 1d6e1912e8f..81cf4ab425f 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/AssemblyInfo.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/AssemblyInfo.cs
@@ -3,7 +3,7 @@
[assembly: InternalsVisibleTo("Universal2DGraphicsTests")]
[assembly: InternalsVisibleTo("Universal2DEditorTests")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor")]
-[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor")]
+[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.2D.Editor.Overrides")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor.Tests")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Runtime.Tests")]
[assembly: InternalsVisibleTo("Unity.GraphicTests.Performance.Universal.Runtime")]
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs
index d3f3cc32947..1120772c3f9 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Passes/Utility/RendererLighting.cs
@@ -714,9 +714,7 @@ private static Material CreateLightMaterial(Renderer2DData rendererData, Light2D
if (light.lightType == Light2D.LightType.Point)
SetBlendModes(material, BlendMode.One, BlendMode.One);
else
- {
SetBlendModes(material, BlendMode.SrcAlpha, BlendMode.One);
- }
}
if (isPoint && light.lightCookieSprite != null && light.lightCookieSprite.texture != null)
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DData.cs
index 91a8871d107..1530a003689 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DData.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DData.cs
@@ -97,12 +97,14 @@ protected override ScriptableRenderer Create()
ReloadAllNullProperties();
}
#endif
-
+ UnityEngine.RenderAs2DUtil.InitializeCanRenderAs2D();
return new Renderer2D(this);
}
internal void Dispose()
{
+ UnityEngine.RenderAs2DUtil.DisposeCanRenderAs2D();
+
#if URP_COMPATIBILITY_MODE
for (var i = 0; i < m_LightBlendStyles.Length; ++i)
m_LightBlendStyles[i].renderTargetHandle?.Release();
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DDataAuthoring.cs b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DDataAuthoring.cs
index 5428dd2d24f..06d39f1fa2b 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DDataAuthoring.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Renderer2DDataAuthoring.cs
@@ -26,6 +26,15 @@ internal override Material GetDefaultMaterial(DefaultMaterialType materialType)
switch (materialType)
{
+ case DefaultMaterialType.Default:
+ {
+ return m_DefaultMaterialType switch
+ {
+ Renderer2DDefaultMaterialType.Lit => resources.defaultMesh2DLitMaterial,
+ Renderer2DDefaultMaterialType.Unlit => resources.defaultMesh2DLitMaterial,
+ _ => m_DefaultCustomMaterial
+ };
+ }
case DefaultMaterialType.Sprite:
case DefaultMaterialType.Particle:
{
@@ -38,6 +47,9 @@ internal override Material GetDefaultMaterial(DefaultMaterialType materialType)
}
case DefaultMaterialType.SpriteMask:
return resources.defaultMaskMaterial;
+
+ case DefaultMaterialType.RenderAs2D:
+ return resources.defaultRenderAs2D;
default:
return null;
}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Unity.RenderPipelines.Universal.2D.Runtime.asmdef b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Unity.RenderPipelines.Universal.2D.Runtime.asmdef
index cdb5d66544f..400f14963cf 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/2D/Unity.RenderPipelines.Universal.2D.Runtime.asmdef
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/2D/Unity.RenderPipelines.Universal.2D.Runtime.asmdef
@@ -8,7 +8,8 @@
"GUID:ab67fb10353d84448ac887a7367cbda8",
"GUID:41524c21c95e5fe4dbc5b48bd21995a4",
"GUID:caccfbdb442cdc64fa722b4c5585521f",
- "GUID:2665a8d13d1b3f18800f46e256720795"
+ "GUID:2665a8d13d1b3f18800f46e256720795",
+ "RenderAs2DModule"
],
"includePlatforms": [],
"excludePlatforms": [],
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Data/PostProcessData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Data/PostProcessData.cs
index c2346d4949f..4456b29df56 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Data/PostProcessData.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Data/PostProcessData.cs
@@ -56,7 +56,7 @@ void LoadResources(bool reset)
{
if (GraphicsSettings.TryGetRenderPipelineSettings(out var defaultShaderResources))
{
- if (shaders == null || reset)
+ if (shaders == null || reset)
shaders = new ShaderResources();
shaders.Populate(defaultShaderResources);
@@ -64,7 +64,7 @@ void LoadResources(bool reset)
if (GraphicsSettings.TryGetRenderPipelineSettings(out var defaultTextureResources))
{
- if (textures == null || reset)
+ if (textures == null || reset)
textures = new TextureResources();
textures.Populate(defaultTextureResources);
@@ -177,7 +177,7 @@ public sealed class ShaderResources : IRenderPipelineResources
///
[ResourcePath("Shaders/PostProcessing/FinalPost.shader")]
public Shader finalPostPassPS;
-
+
#if UNITY_EDITOR
///
/// Copies all fields and resources from a source object into this object.
@@ -232,7 +232,7 @@ public sealed class TextureResources : IRenderPipelineResources
///
/// Pre-baked Blue noise textures.
///
- [ResourceFormattedPaths("Textures/BlueNoise16/L/LDR_LLL1_{0}.png", 0, 32)]
+ // [ResourceFormattedPaths("Textures/BlueNoise16/L/LDR_LLL1_{0}.png", 0, 32)]
public Texture2D[] blueNoise16LTex;
///
@@ -263,7 +263,7 @@ public sealed class TextureResources : IRenderPipelineResources
///
[ResourcePath("Textures/SMAA/SearchTex.tga")]
public Texture2D smaaSearchTex;
-
+
#if UNITY_EDITOR
///
/// Copies all fields and resources from a source object into this object.
@@ -316,4 +316,4 @@ internal void Populate(TextureResources source)
///
public TextureResources textures;
}
-}
\ No newline at end of file
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.DefaultResources.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.DefaultResources.cs
index 68af2ba6540..f5b992bbc3e 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.DefaultResources.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.DefaultResources.cs
@@ -10,7 +10,8 @@ internal enum DefaultMaterialType
Terrain,
Sprite,
SpriteMask,
- Decal
+ Decal,
+ RenderAs2D
}
public partial class UniversalRenderPipelineAsset
@@ -83,6 +84,12 @@ Material GetMaterial(DefaultMaterialType materialType)
/// Returns the material containing the default shader pass for sprite mask in the 2D renderer.
public override Material default2DMaskMaterial => GetMaterial(DefaultMaterialType.SpriteMask);
+ ///
+ /// Returns the default renderAs2D material for the 2D renderer.
+ ///
+ /// Returns the material containing the default RenderAs2D shader passes for meshes in the 2D renderer.
+ public override Material defaultRenderAs2DMaterial => GetMaterial(DefaultMaterialType.RenderAs2D);
+
///
/// Returns the Material that Unity uses to render decals.
///
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs
index b21e83e7b8f..f8d06f0435f 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAsset.cs
@@ -9,6 +9,8 @@
using UnityEngine.Serialization;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
+using UnityEngine.Assertions;
+using System.Collections.Generic;
namespace UnityEngine.Rendering.Universal
{
@@ -367,7 +369,11 @@ public enum UpscalingFilterSelection
/// Unity uses the Spatial-Temporal Post-Processing technique to perform upscaling.
///
[InspectorName("Spatial-Temporal Post-Processing"), Tooltip("If the target device does not support compute shaders or is running GLES, Unity falls back to the Automatic option.")]
- STP
+ STP,
+
+#if ENABLE_UPSCALER_FRAMEWORK
+ IUpscaler // Should always be last
+#endif
}
///
@@ -480,6 +486,15 @@ public partial class UniversalRenderPipelineAsset : RenderPipelineAsset m_UpscalerOptions = new List();
+#endif
[SerializeField] bool m_FsrOverrideSharpness = false;
[SerializeField] float m_FsrSharpness = FSRUtils.kDefaultSharpnessLinear;
@@ -532,17 +547,8 @@ public partial class UniversalRenderPipelineAsset : RenderPipelineAsset m_UpscalingFilter = value;
}
+
+ ///
+ /// Returns the name of the selected upscaling filter.
+ ///
+ public string upscalerName
+ {
+#if ENABLE_UPSCALER_FRAMEWORK
+ get => m_IUpscalerName;
+#else
+ get => string.Empty;
+#endif
+ }
+
+#if ENABLE_UPSCALER_FRAMEWORK
+
+ public List iUpscalerOptions
+ {
+ get => m_UpscalerOptions;
+ }
+
+ public UpscalerOptions GetIUpscalerOptions(string UpscalerName)
+ {
+ foreach(UpscalerOptions option in m_UpscalerOptions)
+ {
+ if (option == null)
+ continue;
+ if (option.UpscalerName == UpscalerName)
+ return option;
+ }
+ return null;
+ }
+#endif
+
///
/// If this property is set to true, the value from the fsrSharpness property will control the intensity of the
/// sharpening filter associated with FidelityFX Super Resolution.
@@ -1363,6 +1402,15 @@ public bool reflectionProbeBlending
internal set => m_ReflectionProbeBlending = value;
}
+ internal bool ShouldUseReflectionProbeBlending()
+ {
+ // The probe blending with atlas code path is always force enabled with GPUResidentDrawer since that is the only path supported here.
+ if (gpuResidentDrawerMode != GPUResidentDrawerMode.Disabled)
+ return true;
+
+ return reflectionProbeBlending;
+ }
+
///
/// Specifies if this UniversalRenderPipelineAsset should allow box projection for the reflection probes in the scene.
///
@@ -1381,6 +1429,20 @@ public bool reflectionProbeAtlas
internal set => m_ReflectionProbeAtlas = value;
}
+ internal bool ShouldUseReflectionProbeAtlasBlending(RenderingMode renderingMode)
+ {
+ var useProbeBlending = ShouldUseReflectionProbeBlending();
+
+ // The probe blending with atlas code path is always force enabled with GPUResidentDrawer since that is the only path supported here.
+ if (gpuResidentDrawerMode != GPUResidentDrawerMode.Disabled)
+ {
+ Assert.IsTrue(useProbeBlending);
+ return true;
+ }
+
+ return useProbeBlending && (reflectionProbeAtlas || renderingMode == RenderingMode.DeferredPlus);
+ }
+
///
/// Controls the maximum distance at which shadows are visible.
///
@@ -1986,7 +2048,14 @@ public ProbeVolumeSHBands maxSHBands
///
public bool isStpUsed
{
- get { return m_UpscalingFilter == UpscalingFilterSelection.STP; }
+ get
+ {
+ return m_UpscalingFilter == UpscalingFilterSelection.STP
+#if ENABLE_UPSCALER_FRAMEWORK
+ || m_UpscalingFilter == UpscalingFilterSelection.IUpscaler
+#endif
+ ;
+ }
}
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAssetPrefiltering.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAssetPrefiltering.cs
index 6b20f04ce24..814e25d750b 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAssetPrefiltering.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Data/UniversalRenderPipelineAssetPrefiltering.cs
@@ -197,6 +197,18 @@ internal enum PrefilteringModeAdditionalLights
[ShaderKeywordFilter.SelectIf(false, keywordNames: ShaderKeywordStrings.ReflectionProbeRotation)]
[SerializeField] private bool m_PrefilterReflectionProbeRotation = false;
+ // Reflection probe blending (_REFLECTION_PROBE_BLENDING)
+ [ShaderKeywordFilter.SelectOrRemove(false, keywordNames: ShaderKeywordStrings.ReflectionProbeBlending)]
+ [SerializeField] private bool m_PrefilterReflectionProbeBlending = false;
+
+ // Reflection probe box projection (_REFLECTION_PROBE_BOX_PROJECTION)
+ [ShaderKeywordFilter.SelectOrRemove(false, keywordNames: ShaderKeywordStrings.ReflectionProbeBoxProjection)]
+ [SerializeField] private bool m_PrefilterReflectionProbeBoxProjection = false;
+
+ // Reflection probe atlas (_REFLECTION_PROBE_ATLAS)
+ [ShaderKeywordFilter.RemoveIf(true, keywordNames: ShaderKeywordStrings.ReflectionProbeAtlas)]
+ [SerializeField] private bool m_PrefilterReflectionProbeAtlas = false;
+
///
/// Data used for Shader Prefiltering. Gathered after going through the URP Assets,
/// Renderers and Renderer Features in OnPreprocessBuild() inside ShaderPreprocessor.cs.
@@ -237,6 +249,9 @@ internal struct ShaderPrefilteringData
public bool stripBicubicLightmapSampling;
public bool stripReflectionProbeRotation;
+ public bool stripReflectionProbeBlending;
+ public bool stripReflectionProbeBoxProjection;
+ public bool stripReflectionProbeAtlas;
public bool stripScreenSpaceIrradiance;
@@ -296,6 +311,9 @@ internal void UpdateShaderKeywordPrefiltering(ref ShaderPrefilteringData prefilt
m_PrefilterBicubicLightmapSampling = prefilteringData.stripBicubicLightmapSampling;
m_PrefilterReflectionProbeRotation = prefilteringData.stripReflectionProbeRotation;
+ m_PrefilterReflectionProbeBlending = prefilteringData.stripReflectionProbeBlending;
+ m_PrefilterReflectionProbeBoxProjection = prefilteringData.stripReflectionProbeBoxProjection;
+ m_PrefilterReflectionProbeAtlas = prefilteringData.stripReflectionProbeAtlas;
m_PrefilterScreenSpaceIrradiance = prefilteringData.stripScreenSpaceIrradiance;
}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Decal/ScreenSpace/DecalScreenSpaceRenderPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Decal/ScreenSpace/DecalScreenSpaceRenderPass.cs
index bbd3f766f09..a7ed88b6dfa 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Decal/ScreenSpace/DecalScreenSpaceRenderPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Decal/ScreenSpace/DecalScreenSpaceRenderPass.cs
@@ -128,6 +128,10 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
builder.SetRenderAttachment(resourceData.activeColorTexture, 0, AccessFlags.Write);
builder.SetRenderAttachmentDepth(resourceData.activeDepthTexture, AccessFlags.Read);
+ if (cameraData.xr.enabled)
+ {
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
+ }
var param = CreateRenderListParams(renderingData, passData.cameraData, lightData);
passData.rendererList = renderGraph.CreateRendererList(param);
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs
index 30cc2b1a7f4..2980025cd09 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalCameraData.cs
@@ -160,7 +160,7 @@ public Matrix4x4 GetGPUProjectionMatrixNoJitter(int viewIndex = 0)
internal Matrix4x4 GetGPUProjectionMatrix(bool renderIntoTexture, int viewIndex = 0)
{
- return m_JitterMatrix * GL.GetGPUProjectionMatrix(GetProjectionMatrix(viewIndex), renderIntoTexture);
+ return GL.GetGPUProjectionMatrix(GetProjectionMatrix(viewIndex), renderIntoTexture);
}
///
@@ -173,15 +173,14 @@ internal Matrix4x4 GetGPUProjectionMatrix(bool renderIntoTexture, int viewIndex
/// By obtaining the pixelWidth of the camera and taking into account the render scale
/// The min dimension is 1.
///
- public int scaledWidth => Mathf.Max(1, (int)(camera.pixelWidth * renderScale));
+ public int scaledWidth;
///
/// Returns the scaled height of the Camera
/// By obtaining the pixelHeight of the camera and taking into account the render scale
/// The min dimension is 1.
///
- public int scaledHeight => Mathf.Max(1, (int)(camera.pixelHeight * renderScale));
-
+ public int scaledHeight;
// NOTE: This is internal instead of private to allow ref return in the old CameraData compatibility property.
// We can make this private when it is removed.
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalPostProcessingData.cs b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalPostProcessingData.cs
index 7c0be86476c..e1319e8e7b5 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalPostProcessingData.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/FrameData/UniversalPostProcessingData.cs
@@ -38,6 +38,13 @@ public class UniversalPostProcessingData : ContextItem
///
public bool supportDataDrivenLensFlare;
+ ///
+ /// Returns null if there isn't an active upscaler
+ ///
+#if ENABLE_UPSCALER_FRAMEWORK
+ public IUpscaler activeUpscaler;
+#endif
+
///
/// Empty function added for the IDisposable interface.
///
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Lit-Default.mat b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Lit-Default.mat
new file mode 100644
index 00000000000..faeb7122638
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Lit-Default.mat
@@ -0,0 +1,50 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: Mesh2D-Lit-Default
+ m_Shader: {fileID: 4800000, guid: 4e90a8289da1f3943885176e4f83e35c, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords: []
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: -1
+ stringTagMap: {}
+ disabledShaderPasses: []
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _AlphaTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MaskTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _NormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _EnableExternalAlpha: 0
+ m_Colors:
+ - _Color: {r: 1, g: 1, b: 1, a: 1}
+ - _Flip: {r: 1, g: 1, b: 1, a: 1}
+ - _RendererColor: {r: 1, g: 1, b: 1, a: 1}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Lit-Default.mat.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Lit-Default.mat.meta
new file mode 100644
index 00000000000..9d9488d75f0
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Lit-Default.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 9452ae1262a74094f8a68013fbcd1834
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Unlit-Default.mat b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Unlit-Default.mat
new file mode 100644
index 00000000000..c6fa8644a67
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Unlit-Default.mat
@@ -0,0 +1,100 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: Mesh2D-Unlit-Default
+ m_Shader: {fileID: 4800000, guid: 8c3bb6de0c0e7c047b65c077249507e5, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords: []
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: -1
+ stringTagMap: {}
+ disabledShaderPasses: []
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _AlphaTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BumpMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailAlbedoMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailMask:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailNormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _EmissionMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MaskTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MetallicGlossMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _NormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _OcclusionMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _ParallaxMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - PixelSnap: 0
+ - _BumpScale: 1
+ - _Cutoff: 0.5
+ - _DetailNormalMapScale: 1
+ - _DstBlend: 0
+ - _EnableExternalAlpha: 0
+ - _GlossMapScale: 1
+ - _Glossiness: 0.5
+ - _GlossyReflections: 1
+ - _Metallic: 0
+ - _Mode: 0
+ - _OcclusionStrength: 1
+ - _Parallax: 0.02
+ - _SmoothnessTextureChannel: 0
+ - _SpecularHighlights: 1
+ - _SrcBlend: 1
+ - _UVSec: 0
+ - _ZWrite: 1
+ m_Colors:
+ - _Color: {r: 1, g: 1, b: 1, a: 1}
+ - _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
+ - _Flip: {r: 1, g: 1, b: 1, a: 1}
+ - _RendererColor: {r: 1, g: 1, b: 1, a: 1}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Unlit-Default.mat.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Unlit-Default.mat.meta
new file mode 100644
index 00000000000..18c5cccf57c
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Mesh2D-Unlit-Default.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 71942363c5608a64bb62421349d39c9c
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Default.mat b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Default.mat
new file mode 100644
index 00000000000..c63aedbb0e0
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Default.mat
@@ -0,0 +1,50 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: RenderAs2D-Default
+ m_Shader: {fileID: 4800000, guid: 74659692f6350ba46b88180d9c826630, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords: []
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: -1
+ stringTagMap: {}
+ disabledShaderPasses: []
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _AlphaTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MaskTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _NormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _EnableExternalAlpha: 0
+ m_Colors:
+ - _Color: {r: 1, g: 1, b: 1, a: 1}
+ - _Flip: {r: 1, g: 1, b: 1, a: 1}
+ - _RendererColor: {r: 1, g: 1, b: 1, a: 1}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Default.mat.meta b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Default.mat.meta
new file mode 100644
index 00000000000..e0f020adc92
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Default.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: b697f6a938056384e968ccf6527dac83
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 2100000
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Lit-Default.mat b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Lit-Default.mat
index 2abe899aa8c..2d0d49b678f 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Lit-Default.mat
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Materials/Sprite-Lit-Default.mat
@@ -2,20 +2,25 @@
%TAG !u! tag:unity3d.com,2011:
--- !u!21 &2100000
Material:
- serializedVersion: 6
+ serializedVersion: 8
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: Sprite-Lit-Default
m_Shader: {fileID: 4800000, guid: e260cfa7296ee7642b167f1eb5be5023, type: 3}
- m_ShaderKeywords: ETC1_EXTERNAL_ALPHA
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords:
+ - ETC1_EXTERNAL_ALPHA
+ m_InvalidKeywords: []
m_LightmapFlags: 4
m_EnableInstancingVariants: 0
m_DoubleSidedGI: 0
m_CustomRenderQueue: -1
stringTagMap: {}
disabledShaderPasses: []
+ m_LockedProperties:
m_SavedProperties:
serializedVersion: 3
m_TexEnvs:
@@ -44,3 +49,4 @@ Material:
- _Flip: {r: 1, g: 1, b: 1, a: 1}
- _RendererColor: {r: 1, g: 1, b: 1, a: 1}
m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ScreenSpaceLensFlare.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ScreenSpaceLensFlare.cs
index 567fa6a087a..04d0b2f89bf 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ScreenSpaceLensFlare.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Overrides/ScreenSpaceLensFlare.cs
@@ -163,6 +163,7 @@ public enum ScreenSpaceLensFlareResolution : int
[Serializable, VolumeComponentMenu("Post-processing/Screen Space Lens Flare")]
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
[URPHelpURL("shared/lens-flare/lens-flare-component")]
+ [DisplayInfo(name = "Screen Space Lens Flare")]
public class ScreenSpaceLensFlare : VolumeComponent, IPostProcessComponent
{
///
@@ -245,14 +246,7 @@ public class ScreenSpaceLensFlare : VolumeComponent, IPostProcessComponent
///
[Header("Chromatic Abberation")]
public ClampedFloatParameter chromaticAbberationIntensity = new ClampedFloatParameter(0.5f, 0f, 1f);
- ///
- /// Default constructor for the lens flare volume component.
- ///
- public ScreenSpaceLensFlare()
- {
- displayName = "Screen Space Lens Flare";
- }
-
+
///
/// Tells if the post process needs to be rendered or not.
///
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/CopyDepthPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/CopyDepthPass.cs
index 342cbcccf74..3a789a6b712 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/CopyDepthPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/CopyDepthPass.cs
@@ -99,6 +99,14 @@ public void Dispose()
[Obsolete(DeprecationMessage.CompatibilityScriptingAPIObsoleteFrom2023_3)]
public override void OnCameraSetup(CommandBuffer cmd, ref RenderingData renderingData)
{
+#if UNITY_ANDROID
+ // Mali Valhall + SSAO compatibility: Override timing when accessing depth data
+ if (PlatformAutoDetect.isRunningOnMaliValhallGPU && renderingData.cameraData.postProcessEnabled)
+ {
+ renderPassEvent = RenderPassEvent.AfterRenderingOpaques;
+ }
+#endif
+
// Disable obsolete warning for internal usage
#pragma warning disable CS0618
#if UNITY_EDITOR
@@ -286,6 +294,11 @@ public void Render(RenderGraph renderGraph, TextureHandle destination, TextureHa
passData.copyToDepth = CopyToDepth || CopyToDepthXR;
passData.isDstBackbuffer = CopyToBackbuffer || CopyToDepthXR;
+ if (cameraData.xr.enabled)
+ {
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
+ }
+
if (CopyToDepth)
{
// Writes depth using custom depth output
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs
index 249e0585055..d2f247f3af4 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthNormalOnlyPass.cs
@@ -226,7 +226,10 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, Textur
passData.rendererList = renderGraph.CreateRendererList(param);
builder.UseRendererList(passData.rendererList);
if (cameraData.xr.enabled)
+ {
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && cameraData.xrUniversal.canFoveateIntermediatePasses);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
+ }
if (setGlobalTextures)
{
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs
index bc31b07a33a..83b7fe14507 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DepthOnlyPass.cs
@@ -154,7 +154,10 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, ref Te
builder.AllowGlobalStateModification(true);
if (cameraData.xr.enabled)
+ {
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && cameraData.xrUniversal.canFoveateIntermediatePasses);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
+ }
builder.SetRenderFunc((PassData data, RasterGraphContext context) =>
{
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs
index 9babe8e418e..7a47a4ca134 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawObjectsPass.cs
@@ -274,7 +274,7 @@ internal void InitRendererLists(UniversalRenderingData renderingData, UniversalC
}
}
- internal void Render(RenderGraph renderGraph, ContextContainer frameData, TextureHandle colorTarget, TextureHandle depthTarget, TextureHandle mainShadowsTexture, TextureHandle additionalShadowsTexture, uint batchLayerMask = uint.MaxValue)
+ internal void Render(RenderGraph renderGraph, ContextContainer frameData, TextureHandle colorTarget, TextureHandle depthTarget, TextureHandle mainShadowsTexture, TextureHandle additionalShadowsTexture, uint batchLayerMask = uint.MaxValue, bool isMainOpaquePass = false)
{
UniversalResourceData resourceData = frameData.Get();
UniversalRenderingData renderingData = frameData.Get();
@@ -330,11 +330,17 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, Textur
}
builder.AllowGlobalStateModification(true);
-
if (cameraData.xr.enabled)
{
bool passSupportsFoveation = cameraData.xrUniversal.canFoveateIntermediatePasses || resourceData.isActiveTargetBackBuffer;
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && passSupportsFoveation);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
+#if ENABLE_VR && ENABLE_XR_MODULE && PLATFORM_ANDROID
+ if (isMainOpaquePass)
+ {
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.TileProperties);
+ }
+#endif
}
builder.SetRenderFunc((PassData data, RasterGraphContext context) =>
@@ -499,6 +505,7 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, Textur
{
bool passSupportsFoveation = cameraData.xrUniversal.canFoveateIntermediatePasses || resourceData.isActiveTargetBackBuffer;
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && passSupportsFoveation);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
}
builder.SetRenderFunc((RenderingLayersPassData data, RasterGraphContext context) =>
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawSkyboxPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawSkyboxPass.cs
index 8bb0e01ad6f..b6892bb91af 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawSkyboxPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/DrawSkyboxPass.cs
@@ -158,6 +158,7 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, Script
{
bool passSupportsFoveation = cameraData.xrUniversal.canFoveateIntermediatePasses || resourceData.isActiveTargetBackBuffer;
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && passSupportsFoveation);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
}
builder.SetRenderFunc((PassData data, RasterGraphContext context) =>
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs
index d403bd6de3c..33b6140cb0d 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/FinalBlitPass.cs
@@ -299,6 +299,7 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, Univer
// This is a screen-space pass, make sure foveated rendering is disabled for non-uniform renders
bool passSupportsFoveation = !XRSystem.foveatedRenderingCaps.HasFlag(FoveatedRenderingCaps.NonUniformRaster);
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && passSupportsFoveation);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
// Optimization: In XR, we don't have split screen use case.
// The access flag can be set to WriteAll if there is a full screen blit and no alpha blending,
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MotionVectorRenderPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MotionVectorRenderPass.cs
index 72a1463859a..180fc93f6ac 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MotionVectorRenderPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/MotionVectorRenderPass.cs
@@ -220,7 +220,10 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, Textur
builder.AllowGlobalStateModification(true);
if (cameraData.xr.enabled)
+ {
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && cameraData.xrUniversal.canFoveateIntermediatePasses);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
+ }
builder.SetRenderAttachment(motionVectorColor, 0, AccessFlags.Write);
builder.SetRenderAttachmentDepth(motionVectorDepth, AccessFlags.Write);
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPassRenderGraph.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPassRenderGraph.cs
index cc8ea85503b..b74c9118eed 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPassRenderGraph.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/PostProcessPassRenderGraph.cs
@@ -2195,6 +2195,7 @@ public void RenderFinalBlit(RenderGraph renderGraph, UniversalCameraData cameraD
// This is a screen-space pass, make sure foveated rendering is disabled for non-uniform renders
bool passSupportsFoveation = !XRSystem.foveatedRenderingCaps.HasFlag(FoveatedRenderingCaps.NonUniformRaster);
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && passSupportsFoveation);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
}
#endif
@@ -2351,7 +2352,13 @@ public void RenderFinalPassRenderGraph(RenderGraph renderGraph, ContextContainer
// This avoids the cost of EASU and is available for other upscaling options.
// If FSR is enabled then FSR settings override the TAA settings and we perform RCAS only once.
// If STP is enabled, then TAA sharpening has already been performed inside STP.
- settings.isTaaSharpeningEnabled = (cameraData.IsTemporalAAEnabled() && cameraData.taaSettings.contrastAdaptiveSharpening > 0.0f) && !settings.isFsrEnabled && !cameraData.IsSTPEnabled();
+ settings.isTaaSharpeningEnabled = (cameraData.IsTemporalAAEnabled() && cameraData.taaSettings.contrastAdaptiveSharpening > 0.0f) && !settings.isFsrEnabled && !cameraData.IsSTPEnabled() &&
+#if ENABLE_UPSCALER_FRAMEWORK
+ cameraData.upscalingFilter != ImageUpscalingFilter.IUpscaler
+#else
+ true
+#endif
+ ;
var tempRtDesc = srcDesc;
@@ -2505,6 +2512,7 @@ public void RenderUberPost(RenderGraph renderGraph, ContextContainer frameData,
// This is a screen-space pass, make sure foveated rendering is disabled for non-uniform renders
passSupportsFoveation &= !XRSystem.foveatedRenderingCaps.HasFlag(FoveatedRenderingCaps.NonUniformRaster);
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && passSupportsFoveation);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
}
#endif
@@ -2694,7 +2702,92 @@ public void RenderPostProcessingRenderGraph(RenderGraph renderGraph, ContextCont
currentSource = DoFTarget;
}
- // Temporal Anti Aliasing
+ // Temporal Anti Aliasing / Upscaling
+#if ENABLE_UPSCALER_FRAMEWORK
+ if (useTemporalAA && postProcessingData.activeUpscaler != null)
+ {
+ // Create a context item containing upscaling inputs
+ UpscalingIO io = frameData.Create();
+ io.cameraColor = currentSource;
+ io.cameraDepth = resourceData.cameraDepth;
+ io.motionVectorColor = resourceData.motionVectorColor;
+ io.motionVectorDomain = UpscalingIO.MotionVectorDomain.NDC;
+ io.motionVectorDirection = UpscalingIO.MotionVectorDirection.PreviousFrameToCurrentFrame;
+ io.jitteredMotionVectors = false; // URP has no jittering in MVs
+ // io.exposureTexture; // TODO: set exposure texture when available
+ io.preExposureValue = 1.0f; // TODO: set if exposure value is pre-multiplied
+ io.hdrDisplayInformation = cameraData.isHDROutputActive ? cameraData.hdrDisplayInformation : new HDROutputUtils.HDRDisplayInformation(-1, -1, -1, 160.0f);
+ io.preUpscaleResolution = new Vector2Int(
+ cameraData.cameraTargetDescriptor.width,
+ cameraData.cameraTargetDescriptor.height
+ );
+ io.previousPreUpscaleResolution = io.preUpscaleResolution; // URP doesn't support Dynamic Resolution Scaling (DRS).
+ io.postUpscaleResolution = new Vector2Int(cameraData.pixelWidth, cameraData.pixelHeight);
+ io.motionVectorTextureSize = io.preUpscaleResolution;
+ io.enableTexArray = cameraData.xr.enabled && cameraData.xr.singlePassEnabled;
+
+ MotionVectorsPersistentData motionData = null;
+ {
+ cameraData.camera.TryGetComponent(out var additionalCameraData);
+ Debug.Assert(additionalCameraData != null);
+ motionData = additionalCameraData.motionVectorsPersistentData;
+ Debug.Assert(motionData != null);
+ }
+ io.cameraInstanceID = cameraData.camera.GetInstanceID();
+ io.nearClipPlane = cameraData.camera.nearClipPlane;
+ io.farClipPlane = cameraData.camera.farClipPlane;
+ io.fieldOfViewDegrees = cameraData.camera.fieldOfView;
+ io.invertedDepth = SystemInfo.usesReversedZBuffer;
+ io.flippedY = SystemInfo.graphicsUVStartsAtTop;
+ io.flippedX = false;
+ io.hdrInput = GraphicsFormatUtility.IsHDRFormat(currentSource.GetDescriptor(renderGraph).format);
+ io.numActiveViews = cameraData.xr.enabled ? cameraData.xr.viewCount : 1;
+ io.eyeIndex = (cameraData.xr.enabled && !cameraData.xr.singlePassEnabled) ? cameraData.xr.multipassId : 0;
+ io.worldSpaceCameraPositions = new Vector3[io.numActiveViews];
+ io.previousWorldSpaceCameraPositions = new Vector3[io.numActiveViews];
+ io.previousPreviousWorldSpaceCameraPositions = new Vector3[io.numActiveViews];
+ for (int i = 0; i < io.numActiveViews; i++)
+ {
+ io.worldSpaceCameraPositions[i] = motionData.worldSpaceCameraPos;
+ io.previousWorldSpaceCameraPositions[i] = motionData.previousWorldSpaceCameraPos;
+ io.previousPreviousWorldSpaceCameraPositions[i] = motionData.previousPreviousWorldSpaceCameraPos;
+ }
+ io.projectionMatrices = motionData.projectionStereo;
+ io.previousProjectionMatrices = motionData.previousProjectionStereo;
+ io.previousPreviousProjectionMatrices = motionData.previousPreviousProjectionStereo;
+ io.viewMatrices = motionData.viewStereo;
+ io.previousViewMatrices = motionData.previousViewStereo;
+ io.previousPreviousViewMatrices = motionData.previousPreviousViewStereo;
+ io.resetHistory = cameraData.resetHistory;
+ // TODO (Apoorva): Maybe we want to support this?
+ // URP supports adding an offset value to the TAA frame index for testing determinism as follows:
+ // io.frameIndex = Time.frameCount + settings.jitterFrameCountOffset;
+ io.frameIndex = Time.frameCount;
+ io.deltaTime = motionData.deltaTime;
+ io.previousDeltaTime = motionData.lastDeltaTime;
+ io.blueNoiseTextureSet = m_Materials.resources.textures.blueNoise16LTex;
+
+ // The motion scaling feature is only active outside of test environments. If we allowed it to run
+ // during automated graphics tests, the results of each test run would be dependent on system
+ // performance.
+#if LWRP_DEBUG_STATIC_POSTFX
+ io.enableMotionScaling = false;
+#else
+ io.enableMotionScaling = true;
+#endif
+ io.enableHwDrs = false; // URP doesn't support hardware dynamic resolution scaling
+ // Insert the active upscaler's render graph passes
+ postProcessingData.activeUpscaler.RecordRenderGraph(renderGraph, frameData);
+
+ // Update the camera resolution to reflect the upscaled size
+ var desc = io.cameraColor.GetDescriptor(renderGraph);
+ UpdateCameraResolution(renderGraph, cameraData, new Vector2Int(desc.width, desc.height));
+
+ // Use the output texture of upscaling
+ currentSource = io.cameraColor;
+ }
+ else
+#endif
if (useTemporalAA)
{
if (useSTP)
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs
index 466f516ec8d..339d52b6de6 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/RenderObjectsPass.cs
@@ -316,7 +316,10 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
builder.AllowGlobalStateModification(true);
if (cameraData.xr.enabled)
+ {
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && cameraData.xrUniversal.canFoveateIntermediatePasses);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
+ }
builder.SetRenderFunc((PassData data, RasterGraphContext rgContext) =>
{
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusionPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusionPass.cs
index 34ff69fbf8b..4423f63fe99 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusionPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/ScreenSpaceAmbientOcclusionPass.cs
@@ -412,8 +412,7 @@ public override void RecordRenderGraph(RenderGraph renderGraph, ContextContainer
RenderBufferLoadAction finalLoadAction = data.afterOpaque ? RenderBufferLoadAction.Load : RenderBufferLoadAction.DontCare;
// Setup
- if (data.cameraColor.IsValid())
- PostProcessUtils.SetSourceSize(cmd, data.cameraColor);
+ PostProcessUtils.SetSourceSize(cmd, data.cameraData.cameraTargetDescriptor.width, data.cameraData.cameraTargetDescriptor.height, data.cameraColor);
if (data.cameraNormalsTexture.IsValid())
data.material.SetTexture(s_CameraNormalsTextureID, data.cameraNormalsTexture);
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XRDepthMotionPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XRDepthMotionPass.cs
index 877b0fa4260..3556fa6f8d3 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XRDepthMotionPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XRDepthMotionPass.cs
@@ -194,6 +194,7 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData)
using (var builder = renderGraph.AddRasterRenderPass("XR Motion Pass", out var passData, base.profilingSampler))
{
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
// Setup Color and Depth attachments
builder.SetRenderAttachment(xrMotionVectorColor, 0, AccessFlags.Write);
builder.SetRenderAttachmentDepth(xrMotionVectorDepth, AccessFlags.Write);
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XROcclusionMeshPass.cs b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XROcclusionMeshPass.cs
index 41fa05bfe19..aa28082ec00 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XROcclusionMeshPass.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/Passes/XROcclusionMeshPass.cs
@@ -79,6 +79,7 @@ internal void Render(RenderGraph renderGraph, ContextContainer frameData, in Tex
{
bool passSupportsFoveation = cameraData.xrUniversal.canFoveateIntermediatePasses || resourceData.isActiveTargetBackBuffer;
builder.EnableFoveatedRasterization(cameraData.xr.supportsFoveatedRendering && passSupportsFoveation);
+ builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.MultiviewRenderRegionsCompatible);
}
builder.SetRenderFunc((PassData data, RasterGraphContext context) =>
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs b/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs
index 56e5ed6efcd..4f5fafee5e3 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/PostProcessUtils.cs
@@ -115,17 +115,15 @@ public static void ConfigureFilmGrain(PostProcessData data, FilmGrain settings,
material.SetVector(ShaderConstants._Grain_TilingParams, tilingParams);
}
- internal static void SetSourceSize(RasterCommandBuffer cmd, RTHandle source)
+ internal static void SetSourceSize(RasterCommandBuffer cmd, float width, float height, RenderTexture rt)
{
- float width = source.rt.width;
- float height = source.rt.height;
- if (source.rt.useDynamicScale)
+ if (rt != null && rt.useDynamicScale)
{
#if ENABLE_VR && ENABLE_XR_MODULE
- if (source.rt.vrUsage != VRTextureUsage.None)
+ if (rt.vrUsage != VRTextureUsage.None)
{
- width = XRSystem.ScaleTextureWidthForXR(source.rt);
- height = XRSystem.ScaleTextureHeightForXR(source.rt);
+ width = XRSystem.ScaleTextureWidthForXR(rt);
+ height = XRSystem.ScaleTextureHeightForXR(rt);
}
else
#endif
@@ -137,6 +135,16 @@ internal static void SetSourceSize(RasterCommandBuffer cmd, RTHandle source)
cmd.SetGlobalVector(ShaderConstants._SourceSize, new Vector4(width, height, 1.0f / width, 1.0f / height));
}
+ internal static void SetSourceSize(CommandBuffer cmd, float width, float height, RenderTexture rt)
+ {
+ SetSourceSize(CommandBufferHelpers.GetRasterCommandBuffer(cmd), width, height, rt);
+ }
+
+ internal static void SetSourceSize(RasterCommandBuffer cmd, RTHandle source)
+ {
+ SetSourceSize(cmd, source.rt.width, source.rt.height, source.rt);
+ }
+
internal static void SetSourceSize(CommandBuffer cmd, RTHandle source)
{
SetSourceSize(CommandBufferHelpers.GetRasterCommandBuffer(cmd), source);
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RenderPipelineResources/Renderer2DResources.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RenderPipelineResources/Renderer2DResources.cs
index 0affe578a3b..a908112c30a 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/RenderPipelineResources/Renderer2DResources.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RenderPipelineResources/Renderer2DResources.cs
@@ -113,6 +113,27 @@ internal Material defaultMaskMaterial
get => m_DefaultMaskMaterial;
set => this.SetValueAndNotify(ref m_DefaultMaskMaterial, value, nameof(m_DefaultMaskMaterial));
}
+
+
+
+ [SerializeField, ResourcePath("Runtime/Materials/Mesh2D-Lit-Default.mat")]
+ Material m_DefaultMesh2DLitMaterial = null;
+ internal Material defaultMesh2DLitMaterial
+ {
+ get => m_DefaultMesh2DLitMaterial;
+ set => this.SetValueAndNotify(ref m_DefaultMesh2DLitMaterial, value, nameof(m_DefaultMesh2DLitMaterial));
+ }
+
+ [SerializeField, ResourcePath("Runtime/Materials/RenderAs2D-Default.mat")]
+ Material m_DefaultRenderAs2DMaterial = null;
+ internal Material defaultRenderAs2D
+ {
+ get => m_DefaultRenderAs2DMaterial;
+ set => this.SetValueAndNotify(ref m_DefaultRenderAs2DMaterial, value, nameof(m_DefaultRenderAs2DMaterial));
+ }
#endif
+
+ [SerializeField, ResourcePath("Shaders/2D/RenderAs2D-Flattening.shader")]
+ Shader m_RenderAs2DFlatteningShader;
}
}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DecalRendererFeature.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DecalRendererFeature.cs
index 086264ff518..acaca5a0b12 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DecalRendererFeature.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/DecalRendererFeature.cs
@@ -302,7 +302,9 @@ internal DecalTechnique GetTechnique(bool isDeferred, bool needsGBufferAccurateN
switch (m_Settings.technique)
{
case DecalTechniqueOption.Automatic:
- if (IsAutomaticDBuffer() || isDeferred && needsGBufferAccurateNormals)
+ if (isGLDevice)
+ technique = isDeferred ? DecalTechnique.GBuffer : DecalTechnique.ScreenSpace;
+ else if (IsAutomaticDBuffer() || isDeferred && needsGBufferAccurateNormals)
technique = DecalTechnique.DBuffer;
else if (isDeferred)
technique = DecalTechnique.GBuffer;
@@ -602,11 +604,11 @@ protected override void Dispose(bool disposing)
}
}
- [Conditional("ADAPTIVE_PERFORMANCE_4_0_0_OR_NEWER")]
+ [Conditional("ENABLE_ADAPTIVE_PERFORMANCE")]
private void ChangeAdaptivePerformanceDrawDistances()
{
-#if ADAPTIVE_PERFORMANCE_4_0_0_OR_NEWER
- if (UniversalRenderPipeline.asset.useAdaptivePerformance)
+#if ENABLE_ADAPTIVE_PERFORMANCE
+ if (UniversalRenderPipeline.asset?.useAdaptivePerformance == true)
{
if (m_DecalCreateDrawCallSystem != null)
{
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/FullScreenPassRendererFeature.cs b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/FullScreenPassRendererFeature.cs
index be0bd220a97..5599d00bd14 100644
--- a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/FullScreenPassRendererFeature.cs
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/FullScreenPassRendererFeature.cs
@@ -91,10 +91,7 @@ public override void AddRenderPasses(ScriptableRenderer renderer, ref RenderingD
return;
if (passMaterial == null)
- {
- Debug.LogWarningFormat("The full screen feature \"{0}\" will not execute - no material is assigned. Please make sure a material is assigned for this feature on the renderer asset.", name);
return;
- }
if (passIndex < 0 || passIndex >= passMaterial.passCount)
{
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature.meta
new file mode 100644
index 00000000000..093b98c3cf1
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: d71af0079d49214429c1d2e98f012e07
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/Debug.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/Debug.compute
new file mode 100644
index 00000000000..12ea3f7cedb
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/Debug.compute
@@ -0,0 +1,181 @@
+// These shaders do not currently work on Switch due to its limited binding range
+// https://jira.unity3d.com/browse/GFXLIGHT-1730
+#pragma exclude_renderers switch switch2
+#pragma kernel Visualize
+
+#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
+#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/GBufferCommon.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/Sampling/Common.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/Sampling/Hashes.hlsl"
+#include "SurfaceCacheCore/PatchUtil.hlsl"
+#include "SurfaceCacheCore/RingBuffer.hlsl"
+
+StructuredBuffer _RingConfigBuffer;
+StructuredBuffer _PatchIrradiances;
+StructuredBuffer _PatchCellIndices;
+StructuredBuffer _PatchGeometries;
+StructuredBuffer _PatchStatistics;
+StructuredBuffer _CellPatchIndices;
+StructuredBuffer _CascadeOffsets;
+RWStructuredBuffer _PatchCounterSets;
+
+RWTexture2D _Result;
+Texture2D _ScreenDepths;
+Texture2D _ScreenShadedNormals;
+Texture2D _ScreenFlatNormals;
+
+uint _RingConfigOffset;
+uint _GridSize;
+uint _CascadeCount;
+float _VoxelMinSize;
+uint _ViewMode;
+uint _ShowSamplePosition;
+float4x4 _ClipToWorldTransform;
+uint _FrameIdx;
+float3 _GridTargetPos;
+
+uint _DummyBlackbox; // By using a uniform we force the compiler to not make any assumptions.
+float3 IsActuallyNan(float3 val) {
+ return isnan(asfloat(_DummyBlackbox ^ asuint(val)));
+}
+
+float3 IsActuallyInf(float3 val) {
+ return isinf(asfloat(_DummyBlackbox ^ asuint(val)));
+}
+
+[numthreads(8,8,1)]
+void Visualize(uint2 threadIdx : SV_DispatchThreadID)
+{
+ uint2 screenSize;
+ _ScreenDepths.GetDimensions(screenSize.x, screenSize.y);
+
+ float3 output;
+
+ const float statusBarHeight = 0.05f;
+ if (float(threadIdx.y) / screenSize.y < statusBarHeight)
+ {
+ const RingBuffer::Config ringConfig = RingBuffer::LoadConfig(_RingConfigBuffer, _RingConfigOffset);
+ const uint patchIdx = float(threadIdx.x) / screenSize.x * patchCapacity;
+ if (RingBuffer::IsPositionUnused(ringConfig, patchIdx))
+ {
+ output = float3(1.0f, 1.0f, 1.0f);
+ }
+ else
+ {
+ if (_PatchCellIndices[patchIdx] == PatchUtil::invalidCellIndex)
+ output = float3(1.0f, 0.0f, 0.0f);
+ else
+ output = float3(0.0f, 1.0f, 0.0f);
+ }
+ }
+ else
+ {
+ const float ndcDepth = LoadNdcDepth(_ScreenDepths, threadIdx);
+ if (ndcDepth == invalidNdcDepth)
+ return;
+
+ const float2 uv = (float2(threadIdx.xy) + 0.5f) / float2(screenSize);
+ const float3 worldPos = ComputeWorldSpacePosition(uv, ndcDepth, _ClipToWorldTransform);
+ const float3 worldShadedNormal = UnpackGBufferNormal(_ScreenShadedNormals[threadIdx.xy]);
+ const float3 worldFlatNormal = _ScreenFlatNormals[threadIdx.xy];
+
+ PatchUtil::VolumePositionResolution posResolution = PatchUtil::ResolveVolumePosition(worldPos, _GridTargetPos, _GridSize, _CascadeOffsets, _CascadeCount, _VoxelMinSize);
+ output = float3(1.0f, 0.0f, 1.0f);
+ if (posResolution.isValid())
+ {
+ const uint directionIdx = PatchUtil::GetDirectionIndex(worldFlatNormal, PatchUtil::gridCellAngularResolution);
+ const uint3 positionStorageSpace = PatchUtil::ConvertGridSpaceToStorageSpace(posResolution.positionGridSpace, _GridSize, _CascadeOffsets[posResolution.cascadeIdx]);
+ const uint cellIdx = PatchUtil::GetCellIndex(posResolution.cascadeIdx, positionStorageSpace, directionIdx, _GridSize, PatchUtil::gridCellAngularResolution);
+ const uint patchIdx = _CellPatchIndices[cellIdx];
+ const bool hasPatch = (patchIdx != PatchUtil::invalidPatchIndex);
+
+ SphericalHarmonics::RGBL1 patchIrradiance = (SphericalHarmonics::RGBL1)0;
+ float3 patchPos = 0; // initializing value only to silence shader warning
+ if (hasPatch)
+ {
+ patchIrradiance = _PatchIrradiances[patchIdx];
+ patchPos = _PatchGeometries[patchIdx].position;
+ PatchUtil::WriteLastFrameAccess(_PatchCounterSets, patchIdx, _FrameIdx);
+ }
+
+ if (_ShowSamplePosition == 1 && hasPatch && length(worldPos - patchPos) < 0.12f)
+ {
+ output = 30.0f;
+ }
+ else if (_ViewMode == 0)
+ {
+ const float arbitraryBoost = 5.0f;
+ output = arbitraryBoost * float3(
+ UintToFloat01(LowBiasHash32(cellIdx, 0)),
+ UintToFloat01(LowBiasHash32(cellIdx, 1)),
+ UintToFloat01(LowBiasHash32(cellIdx, 2)));
+ }
+ else if (_ViewMode == 1)
+ {
+ if (hasPatch)
+ {
+ const float3 shEval = SphericalHarmonics::Eval(patchIrradiance, worldShadedNormal);
+ if (any(IsActuallyNan(shEval)))
+ output = float3(1, 0, 0);
+ else if (any(IsActuallyInf(shEval)))
+ output = float3(0, 1, 0);
+ else
+ output = max(0, shEval);
+ }
+ }
+ else if (_ViewMode == 2) // fast irradiance
+ {
+ if (hasPatch)
+ {
+ output = _PatchStatistics[patchIdx].mean * SphericalHarmonics::y0;
+ }
+ }
+ else if (_ViewMode == 3) // coefficient of variation
+ {
+ if (hasPatch)
+ {
+ const PatchUtil::PatchStatisticsSet stats = _PatchStatistics[patchIdx];
+ output = sqrt(stats.variance) / max(0.01f, stats.mean) / 20.0f;
+ }
+ }
+ else if (_ViewMode == 4)
+ {
+ if (hasPatch)
+ {
+ const PatchUtil::PatchStatisticsSet stats = _PatchStatistics[patchIdx];
+ float3 longIrradiance = _PatchIrradiances[patchIdx].l0;
+ float3 shortStdDev = sqrt(stats.variance);
+ float3 drift = abs(longIrradiance - stats.mean) / max(0.001f, shortStdDev);
+ output = drift * 0.25f;
+ }
+ }
+ else if (_ViewMode == 5)
+ {
+ if (hasPatch)
+ {
+ output = sqrt(_PatchStatistics[patchIdx].variance) * 0.1f;
+ }
+ }
+ else if (_ViewMode == 6)
+ {
+ if (hasPatch)
+ {
+ const float3 green = float3(0, 1, 0);
+ const float3 red = float3(1, 0, 0);
+ const PatchUtil::PatchCounterSet counterSet = _PatchCounterSets[patchIdx];
+ const uint updateCount = PatchUtil::GetUpdateCount(counterSet);
+ const float s = float(updateCount) / PatchUtil::updateMax;
+ const float3 redGreenMix = lerp(red, green, s);
+ const float3 checker = UintToFloat01(LowBiasHash32(cellIdx, 0)); // To make cells visible.
+ output = lerp(redGreenMix, checker, 0.25f);
+ }
+ }
+ else if (_ViewMode == 7)
+ {
+ output = worldFlatNormal * 0.5f + 0.5f;
+ }
+ }
+ }
+
+ _Result[threadIdx.xy] = float4(output, 1.0f);
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/Debug.compute.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/Debug.compute.meta
new file mode 100644
index 00000000000..5c4c660a3f1
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/Debug.compute.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 4d40202dfa5473d44bcdc97e00d74703
+ComputeShaderImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.mat b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.mat
new file mode 100644
index 00000000000..bcaaa252e8b
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.mat
@@ -0,0 +1,137 @@
+%YAML 1.1
+%TAG !u! tag:unity3d.com,2011:
+--- !u!114 &-3080243762180101051
+MonoBehaviour:
+ m_ObjectHideFlags: 11
+ 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: d0353a89b1f911e48b9e16bdc9f2e058, type: 3}
+ m_Name:
+ m_EditorClassIdentifier:
+ version: 9
+--- !u!21 &2100000
+Material:
+ serializedVersion: 8
+ m_ObjectHideFlags: 0
+ m_CorrespondingSourceObject: {fileID: 0}
+ m_PrefabInstance: {fileID: 0}
+ m_PrefabAsset: {fileID: 0}
+ m_Name: FallbackMaterial
+ m_Shader: {fileID: 4800000, guid: 421501d8e4bd2014dbd1dbe80ec2bb5a, type: 3}
+ m_Parent: {fileID: 0}
+ m_ModifiedSerializedProperties: 0
+ m_ValidKeywords: []
+ m_InvalidKeywords: []
+ m_LightmapFlags: 4
+ m_EnableInstancingVariants: 0
+ m_DoubleSidedGI: 0
+ m_CustomRenderQueue: -1
+ stringTagMap:
+ RenderType: Opaque
+ disabledShaderPasses:
+ - MOTIONVECTORS
+ m_LockedProperties:
+ m_SavedProperties:
+ serializedVersion: 3
+ m_TexEnvs:
+ - _BaseMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _BumpMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailAlbedoMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailMask:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _DetailNormalMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _EmissionMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MainTex:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _MetallicGlossMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _OcclusionMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _ParallaxMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - _SpecGlossMap:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_Lightmaps:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_LightmapsInd:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ - unity_ShadowMasks:
+ m_Texture: {fileID: 0}
+ m_Scale: {x: 1, y: 1}
+ m_Offset: {x: 0, y: 0}
+ m_Ints: []
+ m_Floats:
+ - _AddPrecomputedVelocity: 0
+ - _AlphaClip: 0
+ - _AlphaToMask: 0
+ - _Blend: 0
+ - _BlendModePreserveSpecular: 1
+ - _BumpScale: 1
+ - _ClearCoatMask: 0
+ - _ClearCoatSmoothness: 0
+ - _Cull: 2
+ - _Cutoff: 0.5
+ - _DetailAlbedoMapScale: 1
+ - _DetailNormalMapScale: 1
+ - _DstBlend: 0
+ - _DstBlendAlpha: 0
+ - _EnvironmentReflections: 1
+ - _GlossMapScale: 0
+ - _Glossiness: 0
+ - _GlossyReflections: 0
+ - _Metallic: 0
+ - _OcclusionStrength: 1
+ - _Parallax: 0.005
+ - _QueueOffset: 0
+ - _ReceiveShadows: 1
+ - _Smoothness: 0.5
+ - _SmoothnessTextureChannel: 0
+ - _SpecularHighlights: 1
+ - _SrcBlend: 1
+ - _SrcBlendAlpha: 1
+ - _Surface: 0
+ - _WorkflowMode: 1
+ - _XRMotionVectorsPass: 1
+ - _ZWrite: 1
+ m_Colors:
+ - _BaseColor: {r: 1, g: 1, b: 1, a: 1}
+ - _Color: {r: 1, g: 1, b: 1, a: 1}
+ - _EmissionColor: {r: 0, g: 0, b: 0, a: 1}
+ - _SpecColor: {r: 0.19999996, g: 0.19999996, b: 0.19999996, a: 1}
+ m_BuildTextureStacks: []
+ m_AllowLocking: 1
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.mat.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.mat.meta
new file mode 100644
index 00000000000..4a4702a560b
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.mat.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: 8a239b3da89050c4e89ac06b168fc684
+NativeFormatImporter:
+ externalObjects: {}
+ mainObjectFileID: 0
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.shader b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.shader
new file mode 100644
index 00000000000..1e200c23ade
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.shader
@@ -0,0 +1,34 @@
+Shader "Hidden/SurfaceCache/Fallback"
+{
+ Properties
+ {
+ }
+ SubShader
+ {
+ Tags { "RenderType"="Opaque" }
+ LOD 100
+
+ Pass
+ {
+ Name "META"
+ Tags {"LightMode"="Meta"}
+ Cull Off
+ CGPROGRAM
+
+ #include"UnityStandardMeta.cginc"
+
+ float4 frag_meta2(v2f_meta i): SV_Target
+ {
+ UnityMetaInput o;
+ UNITY_INITIALIZE_OUTPUT(UnityMetaInput, o);
+ o.Albedo = float3(0.5, 0.5, 0.5);
+ o.Emission = 0;
+ return UnityMetaFragment(o);
+ }
+
+ #pragma vertex vert_meta
+ #pragma fragment frag_meta2
+ ENDCG
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.shader.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.shader.meta
new file mode 100644
index 00000000000..5bc03edfcd4
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FallbackMaterial.shader.meta
@@ -0,0 +1,9 @@
+fileFormatVersion: 2
+guid: 421501d8e4bd2014dbd1dbe80ec2bb5a
+ShaderImporter:
+ externalObjects: {}
+ defaultTextures: []
+ nonModifiableTextures: []
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FlatNormalResolution.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FlatNormalResolution.compute
new file mode 100644
index 00000000000..d12133df52b
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FlatNormalResolution.compute
@@ -0,0 +1,93 @@
+// These shaders do not currently work on Switch due to its limited binding range
+// https://jira.unity3d.com/browse/GFXLIGHT-1730
+#pragma exclude_renderers switch switch2
+#pragma kernel ResolveFlatNormals
+
+#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
+#include "SurfaceCacheCore/Common.hlsl"
+
+Texture2D _ScreenDepths;
+RWTexture2D _ScreenFlatNormals;
+
+float4x4 _ClipToWorldTransform;
+
+[numthreads(8, 8, 1)]
+void ResolveFlatNormals(uint2 centerPixelPos : SV_DispatchThreadID)
+{
+ // This is inspired by https://wickedengine.net/2019/09/improved-normal-reconstruction-from-depth/.
+ // In addition to the center sample, we take 4 depth samples in a cross around the center.
+ // Of these 4, we pick the best in the horizontal direction and the best in the vertical direction
+ // and use these to approximate the triangle surface orientation.
+
+ uint2 screenSize;
+ _ScreenDepths.GetDimensions(screenSize.x, screenSize.y);
+
+ if (any(screenSize <= centerPixelPos))
+ return;
+
+ const float centerNdcDepth = LoadNdcDepth(_ScreenDepths, centerPixelPos);
+ if (centerNdcDepth == invalidNdcDepth)
+ return;
+
+ const float2 reciprocalScreenSize = rcp(float2(screenSize));
+ const float2 centerUvPos = PixelPosToUvPos(centerPixelPos, reciprocalScreenSize);
+ const float3 centerWorldPos = ComputeWorldSpacePosition(centerUvPos, centerNdcDepth, _ClipToWorldTransform);
+
+ bool handednessFlip = false; // Account for handedness and winding order.
+
+ float3 ddxPos;
+ {
+ const uint2 rightPixelPos = centerPixelPos + int2(1, 0);
+ const float rightNdcDepth = LoadNdcDepth(_ScreenDepths, rightPixelPos);
+ const uint2 leftPixelPos = centerPixelPos + int2(-1, 0);
+ const float leftNdcDepth = LoadNdcDepth(_ScreenDepths, leftPixelPos);
+
+ uint2 horizontalPixelPos;
+ float horizontalNdcDepth;
+ if (abs(centerNdcDepth - leftNdcDepth) < abs(centerNdcDepth - rightNdcDepth))
+ {
+ horizontalPixelPos = leftPixelPos;
+ horizontalNdcDepth = leftNdcDepth;
+ handednessFlip = !handednessFlip;
+ }
+ else
+ {
+ horizontalPixelPos = rightPixelPos;
+ horizontalNdcDepth = rightNdcDepth;
+ }
+ const float2 horizontalUvPos = PixelPosToUvPos(horizontalPixelPos, reciprocalScreenSize);
+ const float3 horizontalWorldPos = ComputeWorldSpacePosition(horizontalUvPos, horizontalNdcDepth, _ClipToWorldTransform);
+ ddxPos = horizontalWorldPos - centerWorldPos;
+ }
+
+ float3 ddyPos;
+ {
+ const uint2 upPixelPos = centerPixelPos + int2(0, 1);
+ const float upNdcDepth = LoadNdcDepth(_ScreenDepths, upPixelPos);
+ const uint2 downPixelPos = centerPixelPos + int2(0, -1);
+ const float downNdcDepth = LoadNdcDepth(_ScreenDepths, downPixelPos);
+
+ uint2 verticalPixelPos;
+ float verticalNdcDepth;
+ if (abs(centerNdcDepth - downNdcDepth) < abs(centerNdcDepth - upNdcDepth))
+ {
+ verticalPixelPos = downPixelPos;
+ verticalNdcDepth = downNdcDepth;
+ }
+ else
+ {
+ verticalPixelPos = upPixelPos;
+ verticalNdcDepth = upNdcDepth;
+ handednessFlip = !handednessFlip;
+ }
+ const float2 verticalUvPos = PixelPosToUvPos(verticalPixelPos, reciprocalScreenSize);
+ const float3 verticalWorldPos = ComputeWorldSpacePosition(verticalUvPos, verticalNdcDepth, _ClipToWorldTransform);
+ ddyPos = verticalWorldPos - centerWorldPos;
+ }
+
+ float3 flatNormal = normalize(cross(ddxPos, ddyPos));
+ if (handednessFlip)
+ flatNormal = -flatNormal;
+
+ _ScreenFlatNormals[centerPixelPos] = flatNormal;
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FlatNormalResolution.compute.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FlatNormalResolution.compute.meta
new file mode 100644
index 00000000000..de1fafbab6d
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/FlatNormalResolution.compute.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 134e9451a58aaba43ba713adbd103d92
+ComputeShaderImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/PatchAllocation.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/PatchAllocation.compute
new file mode 100644
index 00000000000..ebb531fecda
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/PatchAllocation.compute
@@ -0,0 +1,227 @@
+// These shaders do not currently work on Switch due to its limited binding range
+// https://jira.unity3d.com/browse/GFXLIGHT-1730
+#pragma exclude_renderers switch switch2
+#pragma kernel Allocate
+
+#define PATCH_UTIL_USE_RW_IRRADIANCE_BUFFER
+#define PATCH_UTIL_USE_RW_CELL_INDEX_BUFFER
+#define PATCH_UTIL_USE_RW_CELL_ALLOCATION_MARK_BUFFER
+
+#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/Sampling/Hashes.hlsl"
+#include "SurfaceCacheCore/IrradianceCompression.hlsl"
+#include "SurfaceCacheCore/PatchUtil.hlsl"
+
+RWStructuredBuffer _RingConfigBuffer;
+RWStructuredBuffer _PatchGeometries;
+RWStructuredBuffer _PatchCellIndices;
+RWStructuredBuffer _PatchCounterSets;
+RWStructuredBuffer _PatchIrradiances0;
+RWStructuredBuffer _PatchIrradiances1;
+RWStructuredBuffer _CellAllocationMarks;
+RWStructuredBuffer _CellPatchIndices;
+
+StructuredBuffer _CascadeOffsets;
+
+Texture2D _CurrentFullResScreenDepths;
+Texture2D _CurrentFullResScreenFlatNormals;
+Texture2D _CurrentFullResScreenMotionVectors;
+Texture2D _PreviousLowResScreenIrradiancesL0;
+Texture2D _PreviousLowResScreenIrradiancesL10;
+Texture2D _PreviousLowResScreenIrradiancesL11;
+Texture2D _PreviousLowResScreenIrradiancesL12;
+Texture2D _PreviousLowResScreenNdcDepths;
+
+uint _FrameIdx;
+uint _GridSize;
+float _VoxelMinSize;
+uint _CascadeCount;
+uint _RingConfigOffset;
+float4x4 _CurrentClipToWorldTransform;
+float4x4 _PreviousClipToWorldTransform;
+float3 _GridTargetPos;
+uint2 _LowResScreenSize;
+uint2 _FullResPixelOffset;
+int _UseMotionVectorSeeding;
+
+uint CountLeadingZeroes(uint x)
+{
+ // Note that this assumes firstbithigh(0) = -1.
+ return 31 - firstbithigh(x);
+}
+
+// https://andrew-helmer.github.io/permute/
+// https://graphics.pixar.com/library/MultiJitteredSampling/
+uint RandomPermute(uint idx, uint len, uint seed)
+{
+ const uint mask = 0xFFFFFFFF >> CountLeadingZeroes(len - 1);
+
+ // This max guard is required and it is not clear why.
+ // https://jira.unity3d.com/browse/GFXLIGHT-1616
+ const uint iterMax = 16;
+
+ uint iterCount = 0;
+ do {
+ idx ^= seed;
+ idx *= 0xe170893d;
+ idx ^= seed >> 16;
+ idx ^= (idx & mask) >> 4;
+ idx ^= seed >> 8;
+ idx *= 0x0929eb3f;
+ idx ^= seed >> 23;
+ idx ^= (idx & mask) >> 1;
+ idx *= 1 | seed >> 27;
+ idx *= 0x6935fa69;
+ idx ^= (idx & mask) >> 11;
+ idx *= 0x74dcb303;
+ idx ^= (idx & mask) >> 2;
+ idx *= 0x9e501cc3;
+ idx ^= (idx & mask) >> 2;
+ idx *= 0xc860a3df;
+ idx &= mask;
+ idx ^= idx >> 5;
+
+ iterCount++;
+ } while (idx >= len && iterCount < iterMax);
+
+ return idx;
+}
+
+#define GROUP_SIZE 8
+
+[numthreads(GROUP_SIZE, GROUP_SIZE, 1)]
+void Allocate(uint2 lowResPixelPos : SV_DispatchThreadID)
+{
+ if (any(lowResPixelPos >= _LowResScreenSize))
+ return;
+
+ const uint lowResThreadPosIndex = lowResPixelPos.y * _LowResScreenSize.x + lowResPixelPos.x;
+ const uint shuffleHash = LowBiasHash32(_FrameIdx, 1); // We pass a seed of 1 to avoid the degenerate zero case.
+ const uint shuffledLowResThreadPosIndex = RandomPermute(lowResThreadPosIndex, _LowResScreenSize.x * _LowResScreenSize.y, shuffleHash);
+ lowResPixelPos = uint2(shuffledLowResThreadPosIndex % _LowResScreenSize.x, shuffledLowResThreadPosIndex / _LowResScreenSize.x);
+
+ const uint2 fullResPixelPos = lowResPixelPos * lowResScreenScaling + _FullResPixelOffset;
+ uint2 fullResScreenSize;
+ _CurrentFullResScreenDepths.GetDimensions(fullResScreenSize.x, fullResScreenSize.y);
+
+ if (any(fullResPixelPos >= fullResScreenSize))
+ return;
+
+ const float ndcDepth = LoadNdcDepth(_CurrentFullResScreenDepths, fullResPixelPos);
+ if (ndcDepth == invalidNdcDepth)
+ return;
+
+ const float2 rcpFullResScreenSize = rcp(float2(fullResScreenSize));
+
+ const float2 sourceUvPos = PixelPosToUvPos(fullResPixelPos, rcpFullResScreenSize);
+ const float3 sourceWorldPosition = ComputeWorldSpacePosition(sourceUvPos, ndcDepth, _CurrentClipToWorldTransform);
+ const float3 sourceWorldFlatNormal = _CurrentFullResScreenFlatNormals[fullResPixelPos];
+
+ PatchUtil::VolumePositionResolution patchPosResolution = PatchUtil::ResolveVolumePosition(sourceWorldPosition, _GridTargetPos, _GridSize, _CascadeOffsets, _CascadeCount, _VoxelMinSize);
+
+ if (patchPosResolution.isValid())
+ {
+ const uint directionIdx = PatchUtil::GetDirectionIndex(sourceWorldFlatNormal, PatchUtil::gridCellAngularResolution);
+ const uint3 positionStorageSpace = PatchUtil::ConvertGridSpaceToStorageSpace(patchPosResolution.positionGridSpace, _GridSize, _CascadeOffsets[patchPosResolution.cascadeIdx]);
+ const uint cellIdx = PatchUtil::GetCellIndex(patchPosResolution.cascadeIdx, positionStorageSpace, directionIdx, _GridSize, PatchUtil::gridCellAngularResolution);
+
+ PatchUtil::PatchIndexResolutionResult resolutionResult = PatchUtil::ResolvePatchIndex(
+ _RingConfigBuffer,
+ _RingConfigOffset,
+ _CellPatchIndices,
+ _CellAllocationMarks,
+ cellIdx);
+
+ if (resolutionResult.code != PatchUtil::patchIndexResolutionCodeAllocationFailure)
+ {
+ PatchUtil::PatchGeometry geo;
+ geo.position = sourceWorldPosition;
+ geo.normal = sourceWorldFlatNormal;
+ _PatchGeometries[resolutionResult.patchIdx] = geo;
+ }
+
+ if (resolutionResult.code == PatchUtil::patchIndexResolutionCodeAllocationSuccess)
+ {
+ _PatchCellIndices[resolutionResult.patchIdx] = cellIdx;
+
+ PatchUtil::PatchCounterSet counterSet;
+ PatchUtil::Reset(counterSet);
+ PatchUtil::SetLastAccessFrame(counterSet, _FrameIdx);
+
+ SphericalHarmonics::RGBL1 irradianceSeed = (SphericalHarmonics::RGBL1)0;
+ if (_FrameIdx != 0)
+ {
+ if (_UseMotionVectorSeeding)
+ {
+ const float2 threadUvPos = PixelPosToUvPos(fullResPixelPos, rcpFullResScreenSize);
+ float2 reprojectedThreadUvPos = threadUvPos - _CurrentFullResScreenMotionVectors[fullResPixelPos];
+ if (all((0.0f < reprojectedThreadUvPos) * (reprojectedThreadUvPos < 1.0f)))
+ {
+ const uint2 reprojectedThreadPixelPos = reprojectedThreadUvPos * fullResScreenSize;
+ const uint2 seedLowResPixelPos = reprojectedThreadPixelPos / lowResScreenScaling;
+ const float seedNdcDepth = _PreviousLowResScreenNdcDepths[seedLowResPixelPos];
+
+ if (seedNdcDepth != invalidNdcDepth)
+ {
+ const float2 seedFullResUvPos = PixelPosToUvPos(seedLowResPixelPos * lowResScreenScaling, rcpFullResScreenSize);
+ const float3 seedWorldPosition = ComputeWorldSpacePosition(seedFullResUvPos, seedNdcDepth, _PreviousClipToWorldTransform);
+ const float voxelSize = PatchUtil::GetVoxelSize(_VoxelMinSize, patchPosResolution.cascadeIdx);
+ const float patchPlaneToSeedPositionDistance = dot(sourceWorldFlatNormal, seedWorldPosition - sourceWorldPosition);
+ if (patchPlaneToSeedPositionDistance < voxelSize)
+ {
+ irradianceSeed = IrradianceCompression::LoadAndDecompress(
+ _PreviousLowResScreenIrradiancesL0,
+ _PreviousLowResScreenIrradiancesL10,
+ _PreviousLowResScreenIrradiancesL11,
+ _PreviousLowResScreenIrradiancesL12,
+ seedLowResPixelPos);
+
+ if (PatchUtil::IsValid(irradianceSeed))
+ PatchUtil::SetUpdateCount(counterSet, PatchUtil::updateMax / 2);
+ #ifdef SEED_DEBUGGING
+ else
+ {
+ irradianceSeed = (SphericalHarmonics::RGBL1)0;
+ PatchUtil::SetUpdateCount(counterSet, PatchUtil::updateMax);
+ irradianceSeed.l0 = float3(10, 0, 0);
+ }
+ #endif
+ }
+ #ifdef SEED_DEBUGGING
+ else
+ {
+ PatchUtil::SetUpdateCount(counterSet, PatchUtil::updateMax);
+ irradianceSeed.l0 = float3(0, 0, 10);
+ }
+ #endif
+ }
+ }
+ }
+ else
+ {
+ irradianceSeed = IrradianceCompression::LoadAndDecompress(
+ _PreviousLowResScreenIrradiancesL0,
+ _PreviousLowResScreenIrradiancesL10,
+ _PreviousLowResScreenIrradiancesL11,
+ _PreviousLowResScreenIrradiancesL12,
+ lowResPixelPos);
+
+ if (PatchUtil::IsValid(irradianceSeed))
+ PatchUtil::SetUpdateCount(counterSet, PatchUtil::updateMax / 2);
+ }
+ #ifdef SEED_DEBUGGING
+ // For debugging: Add color to unseeded patches.
+ if (PatchUtil::GetUpdateCount(counterSet) == 0)
+ {
+ PatchUtil::SetUpdateCount(counterSet, PatchUtil::updateMax);
+ irradianceSeed.l0 = float3(0, 10, 0);
+ }
+ #endif
+ }
+
+ _PatchIrradiances0[resolutionResult.patchIdx] = irradianceSeed;
+ _PatchIrradiances1[resolutionResult.patchIdx] = irradianceSeed;
+ _PatchCounterSets[resolutionResult.patchIdx] = counterSet;
+ }
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/PatchAllocation.compute.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/PatchAllocation.compute.meta
new file mode 100644
index 00000000000..73e1fa97c19
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/PatchAllocation.compute.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 3d9fc4c0ae8e22f49a8ebefad82718d9
+ComputeShaderImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveLookup.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveLookup.compute
new file mode 100644
index 00000000000..81a59f05a7c
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveLookup.compute
@@ -0,0 +1,105 @@
+// These shaders do not currently work on Switch due to its limited binding range
+// https://jira.unity3d.com/browse/GFXLIGHT-1730
+#pragma exclude_renderers switch switch2
+#pragma kernel Lookup
+
+#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Sampling.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/Sampling/QuasiRandom.hlsl"
+#include "SurfaceCacheCore/Common.hlsl"
+#include "SurfaceCacheCore/PatchUtil.hlsl"
+#include "SurfaceCacheCore/IrradianceCompression.hlsl"
+
+Texture2D _ScreenDepths;
+Texture2D _ScreenFlatNormals;
+RWTexture2D _ResultL0;
+RWTexture2D _ResultL10;
+RWTexture2D _ResultL11;
+RWTexture2D _ResultL12;
+RWTexture2D _ResultNdcDepths;
+RWStructuredBuffer _PatchCounterSets;
+
+StructuredBuffer _PatchIrradiances;
+StructuredBuffer _CellPatchIndices;
+StructuredBuffer _CascadeOffsets;
+
+uint _GridSize;
+uint _CascadeCount;
+uint _SampleCount;
+float _VoxelMinSize;
+float4x4 _ClipToWorldTransform;
+uint _FrameIdx;
+float3 _GridTargetPos;
+
+#define GROUP_SIZE 8
+
+[numthreads(GROUP_SIZE, GROUP_SIZE, 1)]
+void Lookup(uint2 lowResPixelPos : SV_DispatchThreadID)
+{
+ uint2 lowResSize;
+ _ResultL0.GetDimensions(lowResSize.x, lowResSize.y);
+
+ if (any(lowResPixelPos >= lowResSize))
+ return;
+
+ const uint2 fullResPixelPos = lowResPixelPos * lowResScreenScaling;
+
+ uint2 fullResSize;
+ _ScreenDepths.GetDimensions(fullResSize.x, fullResSize.y);
+
+ const float ndcDepth = LoadNdcDepth(_ScreenDepths, fullResPixelPos);
+ _ResultNdcDepths[lowResPixelPos] = ndcDepth;
+ if (ndcDepth == invalidNdcDepth)
+ return;
+
+ const float2 uv = PixelPosToUvPos(fullResPixelPos, rcp(float2(fullResSize)));
+ const float3 worldPos = ComputeWorldSpacePosition(uv, ndcDepth, _ClipToWorldTransform);
+ const float3 worldNormal = _ScreenFlatNormals[fullResPixelPos];
+
+ QrngKronecker rng;
+ rng.Init(lowResPixelPos, 0);
+
+ const int cascadeResolution = PatchUtil::ResolveCascadeIndex(_GridTargetPos, worldPos, _GridSize, _CascadeCount, _VoxelMinSize);
+ const uint cascadeIdx = cascadeResolution == -1 ? _CascadeCount - 1 : cascadeResolution;
+ const float voxelSize = PatchUtil::GetVoxelSize(_VoxelMinSize, cascadeIdx);
+
+ SphericalHarmonics::RGBL1 irradianceSum = (SphericalHarmonics::RGBL1)0;
+ float weightSum = 0.0f;
+ {
+ uint patchIdx = PatchUtil::FindPatchIndexAndUpdateLastAccess(_GridTargetPos, _CellPatchIndices, _GridSize, _CascadeOffsets, _PatchCounterSets, _CascadeCount, _VoxelMinSize, worldPos, worldNormal, _FrameIdx);
+ if (patchIdx != PatchUtil::invalidPatchIndex)
+ {
+ const float weight = 0.01f;
+ irradianceSum = SphericalHarmonics::MulPure(_PatchIrradiances[patchIdx], weight);
+ weightSum = weight;
+ }
+ }
+
+ const float3x3 orthoBasis = OrthoBasisFromVector(worldNormal);
+ for (uint sampleIdx = 0; sampleIdx < _SampleCount; ++sampleIdx)
+ {
+ float2 jitter = float2(rng.GetFloat(0), rng.GetFloat(1)) * 2.0f - 1.0f;
+ const float3 jitteredWorldPos = worldPos + (orthoBasis[0] * jitter.x + orthoBasis[1] * jitter.y) * voxelSize;
+
+ jitter = float2(rng.GetFloat(2), rng.GetFloat(3));
+ const float cosSpread = 0.9f; // This constant was empirically determined.
+ const float3 localJitteredDirection = SampleConeUniform(jitter.x, jitter.y, cosSpread);
+ const float3 jitteredWorldDir = mul(orthoBasis, localJitteredDirection);
+
+ uint patchIdx = PatchUtil::FindPatchIndexAndUpdateLastAccess(_GridTargetPos, _CellPatchIndices, _GridSize, _CascadeOffsets, _PatchCounterSets, _CascadeCount, _VoxelMinSize, jitteredWorldPos, jitteredWorldDir, _FrameIdx);
+ if (patchIdx != PatchUtil::invalidPatchIndex)
+ {
+ SphericalHarmonics::AddMut(irradianceSum, _PatchIrradiances[patchIdx]);
+ weightSum += 1.0f;
+ }
+
+ rng.NextSample();
+ }
+
+ SphericalHarmonics::RGBL1 output = (SphericalHarmonics::RGBL1)0; // Initialization is theoretically not required. Only done to silence shader compiler warning.
+ PatchUtil::MarkInvalid(output);
+ if (weightSum != 0.0f)
+ output = SphericalHarmonics::MulPure(irradianceSum, rcp(weightSum));
+
+ IrradianceCompression::CompressAndStore(output, _ResultL0, _ResultL10, _ResultL11, _ResultL12, lowResPixelPos);
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveLookup.compute.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveLookup.compute.meta
new file mode 100644
index 00000000000..47c756ba8cc
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveLookup.compute.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 4d271c06564c6784392d81f949558e5c
+ComputeShaderImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveUpsampling.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveUpsampling.compute
new file mode 100644
index 00000000000..7345b83a7a6
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveUpsampling.compute
@@ -0,0 +1,102 @@
+// These shaders do not currently work on Switch due to its limited binding range
+// https://jira.unity3d.com/browse/GFXLIGHT-1730
+#pragma exclude_renderers switch switch2
+#pragma kernel Upsample
+
+#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/Core.hlsl"
+#include "Packages/com.unity.render-pipelines.universal/ShaderLibrary/GBufferCommon.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/Sampling/QuasiRandom.hlsl"
+#include "SurfaceCacheCore/IrradianceCompression.hlsl"
+#include "SurfaceCacheCore/PatchUtil.hlsl"
+#include "SurfaceCacheCore/Common.hlsl"
+
+Texture2D _FullResDepths;
+Texture2D _FullResFlatNormals;
+Texture2D _FullResShadedNormals;
+Texture2D _LowResIrradiancesL0;
+Texture2D _LowResIrradiancesL10;
+Texture2D _LowResIrradiancesL11;
+Texture2D _LowResIrradiancesL12;
+RWTexture2D _FullResIrradiances;
+
+float _FilterRadius;
+uint _SampleCount;
+float4x4 _ClipToWorldTransform;
+
+[numthreads(16, 16, 1)]
+void Upsample(uint2 targetPixelPos : SV_DispatchThreadID)
+{
+ uint2 fullRes;
+ _FullResDepths.GetDimensions(fullRes.x, fullRes.y);
+
+ if (any(targetPixelPos >= fullRes))
+ return;
+
+ QrngKronecker rng;
+ rng.Init(targetPixelPos, 0);
+
+ const float ndcDepth = LoadNdcDepth(_FullResDepths, targetPixelPos);
+ if (ndcDepth == invalidNdcDepth)
+ return;
+
+ const float2 targetPixelUv = PixelPosToUvPos(targetPixelPos, rcp(float2(fullRes)));
+ const float3 targetWorldPos = ComputeWorldSpacePosition(targetPixelUv, ndcDepth, _ClipToWorldTransform);
+ const float3 targetWorldFlatNormal = _FullResFlatNormals[targetPixelPos];
+ const int2 targetPixelPosLowRes = int2(targetPixelPos / lowResScreenScaling);
+ const float reciprocalSampleCount = rcp(_SampleCount);
+
+ float weightSum = 0.0f;
+ SphericalHarmonics::RGBL1 irradianceSum = (SphericalHarmonics::RGBL1)0;
+
+ for (uint sampleIdx = 0; sampleIdx < _SampleCount; ++sampleIdx)
+ {
+ const float goldenAngle = 2.39996323f;
+ const float kernelExponent = 0.5f;
+ const float angle = rng.GetFloat(0) + goldenAngle * sampleIdx;
+ const float radius = pow(float(sampleIdx + 1) * reciprocalSampleCount, kernelExponent) * _FilterRadius;
+
+ float2 sinCos;
+ sincos(angle, sinCos.x, sinCos.y);
+ const int2 samplePixelPosLowRes = targetPixelPosLowRes + int2(sinCos * radius);
+
+ if(any((samplePixelPosLowRes < 0) + (int2(fullRes) <= samplePixelPosLowRes)))
+ continue;
+
+ const uint2 samplePixelPosFullRes = samplePixelPosLowRes * lowResScreenScaling;
+ const float sampleDepth = _FullResDepths[samplePixelPosFullRes];
+
+ if (sampleDepth == 0.0f)
+ continue;
+
+ const float2 sampleUvPosFullRes = (float2(samplePixelPosFullRes) + 0.5f) / float2(fullRes);
+ const float3 sampleWorldPos = ComputeWorldSpacePosition(sampleUvPosFullRes, sampleDepth, _ClipToWorldTransform);
+ const float3 sampleWorldFlatNormal = _FullResFlatNormals[samplePixelPosFullRes].xyz;
+
+ const SphericalHarmonics::RGBL1 contribution = IrradianceCompression::LoadAndDecompress(_LowResIrradiancesL0, _LowResIrradiancesL10, _LowResIrradiancesL11, _LowResIrradiancesL12, samplePixelPosLowRes);
+
+ float weight = 1.0f;
+ weight *= max(0.0f, dot(targetWorldFlatNormal, sampleWorldFlatNormal));
+ const float planeDistance = abs(dot(targetWorldFlatNormal, sampleWorldPos - targetWorldPos));
+
+ const float maxWeight = 32.0f;
+ weight *= min(1.0f / planeDistance, maxWeight);
+
+ // This effectively acts as a fallback in cases where a pixel finds no good samples.
+ weight += 0.01f;
+
+ if (all(contribution.l0 == PatchUtil::invalidIrradiance))
+ weight = 0.0f;
+
+ weightSum += weight;
+ SphericalHarmonics::MulAddMut(irradianceSum, weight, contribution);
+ }
+
+ float3 output = 0.0f;
+ if (weightSum != 0.0f)
+ {
+ SphericalHarmonics::RGBL1 irradiance = SphericalHarmonics::MulPure(irradianceSum, rcp(weightSum));
+ output = SphericalHarmonics::Eval(irradiance, UnpackGBufferNormal(_FullResShadedNormals[targetPixelPos]));
+ }
+
+ _FullResIrradiances[targetPixelPos] = float4(output, 1);
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveUpsampling.compute.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveUpsampling.compute.meta
new file mode 100644
index 00000000000..f0a387065ed
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/ScreenResolveUpsampling.compute.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 7c302ee1d7410a6458981a5f329520b4
+ComputeShaderImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore.meta
new file mode 100644
index 00000000000..e7053e80486
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore.meta
@@ -0,0 +1,8 @@
+fileFormatVersion: 2
+guid: a2edb5f961ad3b341b5045c3e6ffd4b5
+folderAsset: yes
+DefaultImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Common.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Common.hlsl
new file mode 100644
index 00000000000..04db9ad9624
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Common.hlsl
@@ -0,0 +1,158 @@
+#ifndef SURFACE_CACHE_COMMON
+#define SURFACE_CACHE_COMMON
+
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl"
+
+static const uint patchCapacity = 65536; // Must match C# side.
+static const uint cascadeMax = 8; // Must match C# side.
+#if UNITY_REVERSED_Z
+static const float invalidNdcDepth = 0.0f;
+#else
+static const float invalidNdcDepth = 1.0f;
+#endif
+
+static const uint lowResScreenScaling = 4; // must match cpu side.
+
+float LoadNdcDepth(Texture2D depthBuffer, uint2 pos)
+{
+ const float depthBufferDepth = depthBuffer[pos];
+ #if UNITY_REVERSED_Z
+ return depthBufferDepth;
+ #else
+ if(depthBufferDepth == 1.0f)
+ return invalidNdcDepth;
+ else
+ return depthBufferDepth * 2.0f - 1.0f;
+ #endif
+}
+
+float2 PixelPosToUvPos(uint2 pixelPos, float2 reciprocalScreenSize)
+{
+ return (float2(pixelPos) + 0.5f) * reciprocalScreenSize;
+}
+
+namespace SphericalHarmonics
+{
+ static const float y0 = sqrt(1.0f / PI) * 0.5f;
+ static const float y1Constant = sqrt(3.0f / PI) * 0.5f;
+ static const float y20Constant = sqrt(15.0f / PI) * 0.5f;
+ static const float y21Constant = y20Constant;
+ static const float y22Constant = sqrt(5.0f / PI) * 0.25f;
+ static const float y23Constant = y20Constant;
+ static const float y24Constant = sqrt(15.0f / PI) * 0.25f;
+
+ struct RGBL1
+ {
+ float3 l0;
+ float3 l1s[3];
+ };
+
+ float3 Eval(in RGBL1 f, float3 direction)
+ {
+ return f.l0 * y0 + y1Constant * (f.l1s[0] * direction.x + f.l1s[1] * direction.z + f.l1s[2] * direction.y);
+ }
+
+ RGBL1 MulPure(RGBL1 f, float multiplier)
+ {
+ RGBL1 result;
+ result.l0 = f.l0 * multiplier;
+ result.l1s[0] = f.l1s[0] * multiplier;
+ result.l1s[1] = f.l1s[1] * multiplier;
+ result.l1s[2] = f.l1s[2] * multiplier;
+ return result;
+ }
+
+ RGBL1 AddPure(RGBL1 a, RGBL1 b)
+ {
+ RGBL1 result;
+ result.l0 = a.l0 + b.l0;
+ result.l1s[0] = a.l1s[0] + b.l1s[0];
+ result.l1s[1] = a.l1s[1] + b.l1s[1];
+ result.l1s[2] = a.l1s[2] + b.l1s[2];
+ return result;
+ }
+
+ // Multiply-add: a = a + b * c.
+ void AddMut(inout RGBL1 a, RGBL1 b)
+ {
+ a.l0 += b.l0;
+ a.l1s[0] += b.l1s[0];
+ a.l1s[1] += b.l1s[1];
+ a.l1s[2] += b.l1s[2];
+ }
+
+ // Multiply-add: a = a + b * c.
+ void MulAddMut(inout RGBL1 a, float b, RGBL1 c)
+ {
+ a.l0 += b * c.l0;
+ a.l1s[0] += b * c.l1s[0];
+ a.l1s[1] += b * c.l1s[1];
+ a.l1s[2] += b * c.l1s[2];
+ }
+
+ void MulMut(inout RGBL1 f, float multiplier)
+ {
+ f.l0 *= multiplier;
+ f.l1s[0] *= multiplier;
+ f.l1s[1] *= multiplier;
+ f.l1s[2] *= multiplier;
+ }
+
+ RGBL1 Lerp(in RGBL1 a, in RGBL1 b, float3 s)
+ {
+ RGBL1 output;
+ output.l0 = lerp(a.l0, b.l0, s);
+ output.l1s[0] = lerp(a.l1s[0], b.l1s[0], s);
+ output.l1s[1] = lerp(a.l1s[1], b.l1s[1], s);
+ output.l1s[2] = lerp(a.l1s[2], b.l1s[2], s);
+ return output;
+ }
+
+ // Convolve with cos(theta). https://cseweb.ucsd.edu/~ravir/papers/envmap/envmap.pdf
+ void CosineConvolve(inout RGBL1 f)
+ {
+ const float aHat0 = PI;
+ const float aHat1 = (2.0f * PI) / 3.0f;
+ f.l0 *= aHat0;
+ f.l1s[0] *= aHat1;
+ f.l1s[1] *= aHat1;
+ f.l1s[2] *= aHat1;
+ }
+
+ struct ScalarL2
+ {
+ float l0;
+ float l1s[3];
+ float l2s[5];
+ };
+
+ float Eval(in ScalarL2 f, float3 direction)
+ {
+ return f.l0 * y0 +
+ f.l1s[0] * y1Constant * direction.x +
+ f.l1s[1] * y1Constant * direction.z +
+ f.l1s[2] * y1Constant * direction.y +
+ f.l2s[0] * y20Constant * direction.x * direction.y +
+ f.l2s[1] * y21Constant * direction.y * direction.z +
+ f.l2s[2] * y22Constant * (3.0f * direction.z * direction.z - 1.0f) +
+ f.l2s[3] * y23Constant * direction.x * direction.z +
+ f.l2s[4] * y24Constant * (direction.x * direction.x - direction.y * direction.y);
+ }
+
+ ScalarL2 Lerp(ScalarL2 a, ScalarL2 b, float s)
+ {
+ SphericalHarmonics::ScalarL2 output;
+ output.l0 = lerp(a.l0, b.l0, s);
+ output.l1s[0] = lerp(a.l1s[0], b.l1s[0], s);
+ output.l1s[1] = lerp(a.l1s[1], b.l1s[1], s);
+ output.l1s[2] = lerp(a.l1s[2], b.l1s[2], s);
+ output.l2s[0] = lerp(a.l2s[0], b.l2s[0], s);
+ output.l2s[1] = lerp(a.l2s[1], b.l2s[1], s);
+ output.l2s[2] = lerp(a.l2s[2], b.l2s[2], s);
+ output.l2s[3] = lerp(a.l2s[3], b.l2s[3], s);
+ output.l2s[4] = lerp(a.l2s[4], b.l2s[4], s);
+ return output;
+ }
+}
+
+#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Common.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Common.hlsl.meta
new file mode 100644
index 00000000000..7c0fe89a58c
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Common.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 9bdf70d328f46724a8d2a29eacb6e8d7
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Defrag.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Defrag.compute
new file mode 100644
index 00000000000..9bd0eb68bbe
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Defrag.compute
@@ -0,0 +1,92 @@
+// Surface Cache shaders do not currently work on Switch due to its limited binding range
+// https://jira.unity3d.com/browse/GFXLIGHT-1730
+#pragma exclude_renderers switch switch2
+#pragma multi_compile_local SUB_GROUP_SIZE_8 SUB_GROUP_SIZE_16 SUB_GROUP_SIZE_32 SUB_GROUP_SIZE_48 SUB_GROUP_SIZE_64
+
+#ifdef SUB_GROUP_SIZE_8
+#define SUB_GROUP_SIZE 8
+#endif
+#ifdef SUB_GROUP_SIZE_16
+#define SUB_GROUP_SIZE 16
+#endif
+#ifdef SUB_GROUP_SIZE_32
+#define SUB_GROUP_SIZE 32
+#endif
+#ifdef SUB_GROUP_SIZE_48
+#define SUB_GROUP_SIZE 48
+#endif
+#ifdef SUB_GROUP_SIZE_64
+#define SUB_GROUP_SIZE 64
+#endif
+
+#pragma kernel Defrag
+
+#define RING_BUFFER_USE_RW_RING_CONFIG_BUFFER
+#define GROUP_SIZE 512
+
+#include "RingBuffer.hlsl"
+#include "PatchUtil.hlsl"
+
+#define THREADING_BLOCK_SIZE GROUP_SIZE
+#define THREADING_WAVE_SIZE SUB_GROUP_SIZE
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Threading.hlsl"
+
+RWStructuredBuffer _RingConfigBuffer;
+RWStructuredBuffer _CellPatchIndices;
+RWStructuredBuffer _PatchCellIndices;
+RWStructuredBuffer _PatchCounterSets;
+RWStructuredBuffer _PatchIrradiances0;
+RWStructuredBuffer _PatchIrradiances1;
+RWStructuredBuffer _PatchGeometries;
+RWStructuredBuffer _PatchStatistics;
+
+uint _RingConfigReadOffset;
+uint _RingConfigWriteOffset;
+uint _PatchOffset;
+
+[numthreads(GROUP_SIZE, 1, 1)]
+void Defrag(Threading::Group group)
+{
+ const uint patchIdx = (group.dispatchID.x + _PatchOffset) % patchCapacity;
+ Threading::Wave wave = group.GetWave();
+
+ const RingBuffer::Config config = RingBuffer::LoadConfig(_RingConfigBuffer, _RingConfigReadOffset);
+ const bool isInRingContentRange = !RingBuffer::IsPositionUnused(config, patchIdx);
+
+ const uint firstLaneIndexOutsideContentRange = wave.Min(!isInRingContentRange ? wave.GetLaneIndex() : UINT_MAX);
+ const bool isLaneIndexAfterFirstLaneIndexThatIsOutsideContentRange = firstLaneIndexOutsideContentRange == UINT_MAX || firstLaneIndexOutsideContentRange < wave.GetLaneIndex();
+ const bool startEndHazardCheck = config.start != config.end || RingBuffer::IsPositionOutsideRangeAssumingStartNotEqualEnd((config.start - SUB_GROUP_SIZE) % patchCapacity, config.start, patchIdx);
+
+ const uint patchCellIdx = _PatchCellIndices[patchIdx];
+ const uint isReclaimable =
+ patchCellIdx == PatchUtil::invalidCellIndex &&
+ isInRingContentRange &&
+ isLaneIndexAfterFirstLaneIndexThatIsOutsideContentRange && // Ensures we only defrag elements that are inside the "content range" of the ring buffer.
+ startEndHazardCheck; // Ensures we avoid defragging "across" the start/end boundary in the special case when start == end.
+
+ const uint leftReclaimableCount = wave.PrefixSum(isReclaimable);
+ const uint reclaimableCount = wave.Sum(isReclaimable);
+ const uint rightReclaimableCount = reclaimableCount - leftReclaimableCount;
+
+ if(patchIdx == config.start)
+ {
+ _RingConfigBuffer[_RingConfigWriteOffset + RingBuffer::countConfigIndex] = config.count - reclaimableCount;
+ _RingConfigBuffer[_RingConfigWriteOffset + RingBuffer::startConfigIndex] = _RingConfigBuffer[_RingConfigReadOffset + RingBuffer::startConfigIndex] + reclaimableCount;
+ _RingConfigBuffer[_RingConfigWriteOffset + RingBuffer::endConfigIndex] = _RingConfigBuffer[_RingConfigReadOffset + RingBuffer::endConfigIndex];
+ }
+
+ if(reclaimableCount != 0 && !isReclaimable && isInRingContentRange && isLaneIndexAfterFirstLaneIndexThatIsOutsideContentRange && startEndHazardCheck) {
+ uint oldPatchCellIndex = _PatchCellIndices[patchIdx];
+ _PatchCellIndices[patchIdx] = PatchUtil::invalidCellIndex;
+
+ const uint newPatchIdx = (patchIdx + rightReclaimableCount) % patchCapacity;
+ _PatchCellIndices[newPatchIdx] = oldPatchCellIndex;
+ _PatchCounterSets[newPatchIdx] = _PatchCounterSets[patchIdx];
+ _PatchIrradiances0[newPatchIdx] = _PatchIrradiances0[patchIdx];
+ _PatchIrradiances1[newPatchIdx] = _PatchIrradiances1[patchIdx];
+ _PatchGeometries[newPatchIdx] = _PatchGeometries[patchIdx];
+ _PatchStatistics[newPatchIdx] = _PatchStatistics[patchIdx];
+
+ _CellPatchIndices[patchCellIdx] = newPatchIdx;
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Defrag.compute.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Defrag.compute.meta
new file mode 100644
index 00000000000..9dec69ddb81
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Defrag.compute.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: a183a2d0b1da4904fb3bd71c6111ebb1
+ComputeShaderImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Estimation.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Estimation.hlsl
new file mode 100644
index 00000000000..c2464297292
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Estimation.hlsl
@@ -0,0 +1,33 @@
+#include "Common.hlsl"
+#include "PatchUtil.hlsl"
+#include "TemporalFiltering.hlsl"
+
+void ProcessAndStoreRadianceSample(RWStructuredBuffer patchIrradiances, RWStructuredBuffer patchStatistics, RWStructuredBuffer patchCounterSets, uint patchIdx, SphericalHarmonics::RGBL1 radianceSample, float shortHysteresis)
+{
+ SphericalHarmonics::CosineConvolve(radianceSample);
+
+ PatchUtil::PatchStatisticsSet oldStats = patchStatistics[patchIdx];
+
+ const SphericalHarmonics::RGBL1 oldIrradiance = patchIrradiances[patchIdx];
+ const float3 newL0ShortIrradiance = lerp(radianceSample.l0, oldStats.mean, shortHysteresis);
+ const float3 varianceSample = (radianceSample.l0 - newL0ShortIrradiance) * (radianceSample.l0 - oldStats.mean);
+ const float3 newVariance = lerp(varianceSample, oldStats.variance, shortHysteresis);
+
+ const PatchUtil::PatchCounterSet oldCounterSet = patchCounterSets[patchIdx];
+ const uint oldUpdateCount = PatchUtil::GetUpdateCount(patchCounterSets[patchIdx]);
+ const uint newUpdateCount = min(oldUpdateCount + 1, PatchUtil::updateMax);
+
+ PatchUtil::PatchCounterSet newCounterSet = oldCounterSet;
+ PatchUtil::SetUpdateCount(newCounterSet, newUpdateCount);
+
+ SphericalHarmonics::RGBL1 output = FilterTemporallyVarianceGuided(shortHysteresis, newUpdateCount, newVariance, newL0ShortIrradiance, radianceSample, oldIrradiance);
+
+ patchIrradiances[patchIdx] = output;
+ if (!PatchUtil::IsEqual(oldCounterSet, newCounterSet))
+ patchCounterSets[patchIdx] = newCounterSet;
+
+ PatchUtil::PatchStatisticsSet newStats;
+ newStats.mean = newL0ShortIrradiance;
+ newStats.variance = newVariance;
+ patchStatistics[patchIdx] = newStats;
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Estimation.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Estimation.hlsl.meta
new file mode 100644
index 00000000000..4e3a0e94c90
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Estimation.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 6d141c681d76ebf4a954f3cbee57173c
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Eviction.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Eviction.compute
new file mode 100644
index 00000000000..a8cd0763955
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Eviction.compute
@@ -0,0 +1,51 @@
+// Surface Cache shaders do not currently work on Switch due to its limited binding range
+// https://jira.unity3d.com/browse/GFXLIGHT-1730
+#pragma exclude_renderers switch switch2
+#pragma kernel Evict
+
+#include "PatchUtil.hlsl"
+
+StructuredBuffer _RingConfigBuffer;
+StructuredBuffer _PatchCounterSets;
+RWStructuredBuffer _CellAllocationMarks;
+RWStructuredBuffer _CellPatchIndices;
+RWStructuredBuffer _PatchCellIndices;
+
+uint _RingConfigOffset;
+uint _FrameIdx;
+
+uint ModuloDistance(uint a, uint b, uint modulo)
+{
+ int dif = abs(int(a) - int(b));
+ return min(dif, modulo - dif);
+}
+
+[numthreads(256, 1, 1)]
+void Evict(uint patchIdx : SV_DispatchThreadID)
+{
+ if (patchCapacity <= patchIdx)
+ return;
+
+ if (RingBuffer::IsPositionUnused(_RingConfigBuffer, _RingConfigOffset, patchIdx))
+ return;
+
+ const uint cellIdx = _PatchCellIndices[patchIdx];
+ if (cellIdx == PatchUtil::invalidCellIndex)
+ return;
+
+ const PatchUtil::PatchCounterSet counterSet = _PatchCounterSets[patchIdx];
+ const uint lastAccessFrameIdx = PatchUtil::GetLastAccessFrame(counterSet);
+
+ // Here we take into account that last frame access index is in [0, 2^16-1].
+ // We use that the last frame index can never be later than current frame index.
+ const uint modulo = 65536; // 2^16
+ const uint frameSinceLastUse = ModuloDistance(_FrameIdx % modulo, lastAccessFrameIdx, modulo);
+
+ const uint evictionThreshold = 60 * 4;
+ if (evictionThreshold < frameSinceLastUse)
+ {
+ _PatchCellIndices[patchIdx] = PatchUtil::invalidCellIndex;
+ _CellAllocationMarks[cellIdx] = 0;
+ _CellPatchIndices[cellIdx] = PatchUtil::invalidPatchIndex;
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Eviction.compute.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Eviction.compute.meta
new file mode 100644
index 00000000000..64309a98be1
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/Eviction.compute.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: c9f2aeed6ef396f4d9134e4da1edfe19
+ComputeShaderImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/IrradianceCompression.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/IrradianceCompression.hlsl
new file mode 100644
index 00000000000..a774c376d7a
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/IrradianceCompression.hlsl
@@ -0,0 +1,67 @@
+#include "Common.hlsl"
+
+// This compression assumes a few things:
+// 1) The coefs must be with respect to the standard orthonormal SH basis. For example,
+// the first basis function must be 1/sqrt(4pi).
+// 2) Irradiance is calculated by projecting radiance into SH, then converting to
+// irradiance using Ramamoorthi's method, https://cseweb.ucsd.edu/~ravir/papers/envmap/envmap.pdf.
+// 3) The coefs are exact (as opposed to noisy approximations).
+// If these assumptions are met then L1 is guaranteed to be in [0,1] after compression. L0 terms
+// are unaffected. If (2) and (3) are not met, then the L1 terms should still be _approximately_ in
+// [0,1].
+namespace IrradianceCompression
+{
+ void Compress(inout SphericalHarmonics::RGBL1 irradiance)
+ {
+ const float3 multiplier = float3(
+ irradiance.l0.x == 0.0f ? 0.0f : sqrt(3.0f) / 4.0f * rcp(irradiance.l0.x),
+ irradiance.l0.y == 0.0f ? 0.0f : sqrt(3.0f) / 4.0f * rcp(irradiance.l0.y),
+ irradiance.l0.z == 0.0f ? 0.0f : sqrt(3.0f) / 4.0f * rcp(irradiance.l0.z)
+ );
+
+ const float3 addend = float3(
+ irradiance.l0.x == 0.0f ? 0.0f : 0.5f,
+ irradiance.l0.y == 0.0f ? 0.0f : 0.5f,
+ irradiance.l0.z == 0.0f ? 0.0f : 0.5f
+ );
+
+ [unroll]
+ for (uint i = 0; i < 3; ++i)
+ irradiance.l1s[i] = irradiance.l1s[i] * multiplier + addend;
+ }
+
+ void Decompress(inout SphericalHarmonics::RGBL1 irradiance)
+ {
+ const float3 multiplier = 4.0f / sqrt(3.0f) * irradiance.l0;
+
+ const float3 addend = float3(
+ irradiance.l0.x == 0.0f ? 0.0f : -0.5f,
+ irradiance.l0.y == 0.0f ? 0.0f : -0.5f,
+ irradiance.l0.z == 0.0f ? 0.0f : -0.5f
+ );
+
+ [unroll]
+ for (uint i = 0; i < 3; ++i)
+ irradiance.l1s[i] = (irradiance.l1s[i] + addend) * multiplier;
+ }
+
+ SphericalHarmonics::RGBL1 LoadAndDecompress(Texture2D l0, Texture2D l10, Texture2D l11, Texture2D l12, uint2 pos)
+ {
+ SphericalHarmonics::RGBL1 result;
+ result.l0 = l0[pos];
+ result.l1s[0] = l10[pos];
+ result.l1s[1] = l11[pos];
+ result.l1s[2] = l12[pos];
+ IrradianceCompression::Decompress(result);
+ return result;
+ }
+
+ void CompressAndStore(SphericalHarmonics::RGBL1 irradiance, RWTexture2D l0, RWTexture2D l10, RWTexture2D l11, RWTexture2D l12, uint2 pos)
+ {
+ IrradianceCompression::Compress(irradiance);
+ l0[pos] = irradiance.l0;
+ l10[pos] = irradiance.l1s[0];
+ l11[pos] = irradiance.l1s[1];
+ l12[pos] = irradiance.l1s[2];
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/IrradianceCompression.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/IrradianceCompression.hlsl.meta
new file mode 100644
index 00000000000..3cd6b11a510
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/IrradianceCompression.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 7be701552a7670148a7c948d2b363156
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PatchUtil.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PatchUtil.hlsl
new file mode 100644
index 00000000000..7760bbfe625
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PatchUtil.hlsl
@@ -0,0 +1,391 @@
+#ifndef SURFACE_CACHE_PATCH_UTIL
+#define SURFACE_CACHE_PATCH_UTIL
+
+#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Macros.hlsl"
+#include "Common.hlsl"
+#include "RingBuffer.hlsl"
+
+#if defined(PATCH_UTIL_USE_RW_IRRADIANCE_BUFFER)
+#define IrradianceBufferType RWStructuredBuffer
+#else
+#define IrradianceBufferType StructuredBuffer
+#endif
+
+#if defined(PATCH_UTIL_USE_RW_CELL_INDEX_BUFFER)
+#define CellPatchIndexBufferType RWStructuredBuffer
+#else
+#define CellPatchIndexBufferType StructuredBuffer
+#endif
+
+#if defined(PATCH_UTIL_USE_RW_CELL_ALLOCATION_MARK_BUFFER)
+#define CellAllocationMarkBufferType RWStructuredBuffer
+#else
+#define CellAllocationMarkBufferType StructuredBuffer
+#endif
+
+namespace PatchUtil
+{
+ static const uint invalidPatchIndex = UINT_MAX; // Must match C# side.
+ static const uint invalidCellIndex = UINT_MAX; // Must match C# side.
+ static const uint gridCellAngularResolution = 4; // Must match C# side.
+ static const float3 invalidIrradiance = float3(-1, -1, -1);
+ static const uint updateMax = 32;
+
+ struct PatchGeometry
+ {
+ float3 position;
+ float3 normal;
+ };
+
+ struct PatchStatisticsSet
+ {
+ float3 mean;
+ float3 variance;
+ };
+
+ struct PatchCounterSet
+ {
+ uint data;
+ };
+
+ void Reset(inout PatchCounterSet set)
+ {
+ set.data = 0;
+ }
+
+ uint GetUpdateCount(PatchCounterSet set)
+ {
+ return set.data & 0xFFFF;
+ }
+
+ uint GetLastAccessFrame(PatchCounterSet set)
+ {
+ return set.data >> 16;
+ }
+
+ void SetUpdateCount(inout PatchCounterSet set, uint updateCount)
+ {
+ set.data = updateCount | (set.data & 0xFFFF0000);
+ }
+
+ void SetLastAccessFrame(inout PatchCounterSet set, uint lastAccessFrame)
+ {
+ set.data = (lastAccessFrame << 16) | (set.data & 0xFFFF);
+ }
+
+ bool IsEqual(PatchCounterSet a, PatchCounterSet b)
+ {
+ return a.data == b.data;
+ }
+
+ void WriteLastFrameAccess(RWStructuredBuffer counterSets, uint patchIdx, uint frameIdx)
+ {
+ PatchCounterSet counterSet = counterSets[patchIdx];
+ SetLastAccessFrame(counterSet, frameIdx);
+ counterSets[patchIdx] = counterSet;
+ }
+
+ float GetVoxelSize(float voxelMinSize, uint cascadeIdx)
+ {
+ return voxelMinSize * (1u << cascadeIdx);
+ }
+
+ float2 OctWrap(float2 v)
+ {
+ return (1.0 - abs(v.yx)) * (step(0.0, v.xy) * 2.0 - 1.0);
+ }
+
+ float2 SphereToSquare(float3 n)
+ {
+ n /= (abs(n.x) + abs(n.y) + abs(n.z));
+ n.xy = n.z >= 0.0 ? n.xy : OctWrap(n.xy);
+ n.xy = n.xy * 0.5 + 0.5;
+ return n.xy;
+ }
+
+ struct VolumePositionResolution
+ {
+ uint cascadeIdx;
+ uint3 positionGridSpace;
+
+ void markInvalid()
+ {
+ positionGridSpace = UINT_MAX;
+ }
+
+ bool isValid()
+ {
+ return all(positionGridSpace != UINT_MAX);
+ }
+ };
+
+ uint GetCellIndex(uint cascadeIdx, uint3 positionStorageSpace, uint directionIndex, uint gridSize, uint angularResolution)
+ {
+ const uint angularResolutionSquared = angularResolution * angularResolution;
+ const uint gridSizeSquared = gridSize * gridSize;
+
+ const uint cellsPerCascade = gridSizeSquared * gridSize * angularResolutionSquared;
+ const uint withinCascadeIdx = angularResolutionSquared * (positionStorageSpace.x * gridSizeSquared + positionStorageSpace.y * gridSize + positionStorageSpace.z) + directionIndex;
+ return cellsPerCascade * cascadeIdx + withinCascadeIdx;
+ }
+
+ uint GetDirectionIndex(float3 direction, uint angularResolution)
+ {
+ // To avoid discontinuities near the cardinal axis directions, we apply an arbitrary rotation.
+ // This is based on the assumption that surfaces oriented along the cardinal axis directions
+ // are most likely in a scene compared to other directions.
+ const float3x3 arbitraryRotation = float3x3(
+ float3(0.34034f, -0.30925f, 0.888f),
+ float3(-0.30925f, 0.85502f, 0.41629f),
+ float3(-0.888f, -0.41629f, 0.19536f));
+ const float3 rotatedDirection = mul(arbitraryRotation, direction);
+
+ const uint2 angularSquarePos = min(uint2(3, 3), SphereToSquare(rotatedDirection) * angularResolution);
+ return angularSquarePos.y * angularResolution + angularSquarePos.x;
+ }
+
+ // Unlike the regular HLSL % operator, this function supports the case where the first
+ // argument is negative and the second argument is positive.
+ uint3 SignedIntegerModulo(int3 x, uint modulus)
+ {
+ #pragma warning (disable : 3556)
+ const int modulusInt = int(modulus);
+ const int3 result = x - x / modulusInt * modulusInt;
+ return int3(result.x < 0 ? result.x + modulusInt : result.x,
+ result.y < 0 ? result.y + modulusInt : result.y,
+ result.z < 0 ? result.z + modulusInt : result.z);
+ }
+
+ uint3 ConvertGridSpaceToStorageSpace(uint3 posGridSpace, uint gridSize, int3 cascadeOffset)
+ {
+ return SignedIntegerModulo(int3(posGridSpace) + cascadeOffset, gridSize);
+ }
+
+ uint3 ConvertStorageSpaceToGridSpace(uint3 posStorageSpace, uint gridSize, int3 cascadeOffset)
+ {
+ return SignedIntegerModulo(int3(posStorageSpace) - cascadeOffset, gridSize);
+ }
+
+ bool IsInsideCascade(float3 gridTargetPos, float3 queryPos, float cascadeVoxelSize, uint gridSize)
+ {
+ const float3 dif = gridTargetPos - queryPos;
+ const float difSquaredLength = dot(dif, dif);
+ // We subtract 0.5 here to account for the fact that the Grid Target Pos can move up to
+ // 0.499... voxel sizes away from the cascade center in any dimension without causing the
+ // cascade to move.
+ const float threshold = cascadeVoxelSize * (float(gridSize) * 0.5f - 0.5f);
+ const float squaredThreshold = threshold * threshold;
+ return difSquaredLength < squaredThreshold;
+ }
+
+ VolumePositionResolution ResolveVolumePosition(float3 queryPos, float3 gridTargetPos, uint gridSize, StructuredBuffer cascadeOffsets, uint cascadeCount, float voxelMinSize, uint startCascadeIdx = 0)
+ {
+ VolumePositionResolution resolution = (VolumePositionResolution)0; // Zero initialization is strictly not required but this silences a shader compiler warning.
+
+ resolution.markInvalid();
+ const float halfGridSize = float(gridSize) * 0.5f;
+ [unroll(cascadeMax)]
+ for (uint cascadeIdx = startCascadeIdx; cascadeIdx < cascadeCount; ++cascadeIdx)
+ {
+ const float cascadeVoxelSize = GetVoxelSize(voxelMinSize, cascadeIdx);
+ if (IsInsideCascade(gridTargetPos, queryPos, cascadeVoxelSize, gridSize))
+ {
+ const int3 cascadeOffset = cascadeOffsets[cascadeIdx];
+ const float3 centerRelativePositionSpatialGridSpace = queryPos / cascadeVoxelSize - cascadeOffset;
+ resolution.positionGridSpace = centerRelativePositionSpatialGridSpace + halfGridSize;
+ resolution.cascadeIdx = cascadeIdx;
+ break;
+ }
+ }
+
+ return resolution;
+ }
+
+ int ResolveCascadeIndex(float3 gridTargetPos, float3 queryPos, uint gridSize, uint cascadeCount, float voxelMinSize)
+ {
+ int result = -1;
+ [unroll(cascadeMax)]
+ for (uint cascadeIdx = 0; cascadeIdx < cascadeCount; ++cascadeIdx)
+ {
+ const float cascadeVoxelSize = GetVoxelSize(voxelMinSize, cascadeIdx);
+ if (IsInsideCascade(gridTargetPos, queryPos, cascadeVoxelSize, gridSize))
+ {
+ result = cascadeIdx;
+ break;
+ }
+ }
+ return result;
+ }
+
+ static const uint patchIndexResolutionCodeLookup = 0;
+ static const uint patchIndexResolutionCodeAllocationSuccess = 1;
+ static const uint patchIndexResolutionCodeAllocationFailure = 2;
+
+ struct PatchIndexResolutionResult
+ {
+ uint code;
+ uint patchIdx;
+ };
+
+ PatchIndexResolutionResult ResolvePatchIndex(RWStructuredBuffer ringConfigBuffer, uint ringConfigOffset, RWStructuredBuffer cellPatchIndices, RWStructuredBuffer cellAllocationMarks, uint cellIdx)
+ {
+ PatchIndexResolutionResult result;
+ result.patchIdx = invalidPatchIndex;
+
+ uint existingPatchIndex = cellPatchIndices[cellIdx];
+ if (existingPatchIndex != invalidPatchIndex)
+ {
+ result.patchIdx = existingPatchIndex;
+ result.code = patchIndexResolutionCodeLookup;
+ }
+ else
+ {
+ result.code = patchIndexResolutionCodeAllocationFailure;
+
+ uint existingAllocationMark;
+ InterlockedExchange(cellAllocationMarks[cellIdx], 1, existingAllocationMark);
+ if (existingAllocationMark == 0)
+ {
+ uint countBeforeAllocation;
+ InterlockedAdd(ringConfigBuffer[ringConfigOffset + RingBuffer::countConfigIndex], 1, countBeforeAllocation);
+ if (countBeforeAllocation < patchCapacity)
+ {
+ uint newPatchIdx;
+ InterlockedAdd(ringConfigBuffer[ringConfigOffset + RingBuffer::endConfigIndex], 1, newPatchIdx);
+ newPatchIdx %= patchCapacity; // Here we exploit the requirement that UINT_MAX is a multiple of patchCapacity.
+
+ result.code = patchIndexResolutionCodeAllocationSuccess;
+ result.patchIdx = newPatchIdx;
+ cellPatchIndices[cellIdx] = newPatchIdx;
+ }
+ else
+ {
+ // Allocation failed, no room. Backing out.
+ ringConfigBuffer[ringConfigOffset + RingBuffer::countConfigIndex] = patchCapacity;
+ cellAllocationMarks[cellIdx] = 0;
+ }
+ }
+ }
+
+ return result;
+ }
+
+ bool ReadHemisphericalIrradiance(IrradianceBufferType patchIrradiances, CellPatchIndexBufferType cellPatchIndices, uint gridSize, uint cascadeIdx, uint3 gridSpacePosition, float3 worldNormal, out SphericalHarmonics::RGBL1 resultIrradiance)
+ {
+ const uint directionIdx = GetDirectionIndex(worldNormal, gridCellAngularResolution);
+ const uint cellIdx = GetCellIndex(cascadeIdx, gridSpacePosition, directionIdx, gridSize, gridCellAngularResolution);
+
+ bool resultBool = false;
+ const uint patchIdx = cellPatchIndices[cellIdx];
+ resultIrradiance = (SphericalHarmonics::RGBL1)0; // Setting value only to silence shader compilation warning.
+ if (patchIdx != invalidPatchIndex)
+ {
+ resultIrradiance = patchIrradiances[patchIdx];
+ resultBool = true;
+ }
+ return resultBool;
+ }
+
+ uint FindPatchIndex(float3 gridTargetPos, StructuredBuffer cellPatchIndices, uint gridSize, StructuredBuffer cascadeOffsets, uint cascadeCount, float voxelMinSize, float3 worldPosition, float3 worldNormal)
+ {
+ VolumePositionResolution posResolution = ResolveVolumePosition(worldPosition, gridTargetPos, gridSize, cascadeOffsets, cascadeCount, voxelMinSize);
+ if (posResolution.isValid())
+ {
+ const uint directionIdx = GetDirectionIndex(worldNormal, gridCellAngularResolution);
+ const uint3 positionStorageSpace = ConvertGridSpaceToStorageSpace(posResolution.positionGridSpace, gridSize, cascadeOffsets[posResolution.cascadeIdx]);
+ const uint cellIdx = GetCellIndex(posResolution.cascadeIdx, positionStorageSpace, directionIdx, gridSize, gridCellAngularResolution);
+ const uint patchIdx = cellPatchIndices[cellIdx];
+ if (patchIdx != invalidPatchIndex)
+ {
+ return patchIdx;
+ }
+ else
+ {
+ return invalidPatchIndex;
+ }
+ }
+ else
+ {
+ return invalidPatchIndex;
+ }
+ }
+
+ uint FindPatchIndexAndUpdateLastAccess(float3 gridTargetPos, StructuredBuffer cellPatchIndices, uint gridSize, StructuredBuffer cascadeOffsets, RWStructuredBuffer patchCounterSets, uint cascadeCount, float voxelMinSize, float3 worldPosition, float3 worldNormal, uint frameIdx)
+ {
+ const uint patchIdx = FindPatchIndex(gridTargetPos, cellPatchIndices, gridSize, cascadeOffsets, cascadeCount, voxelMinSize,worldPosition, worldNormal);
+ if (patchIdx != invalidPatchIndex)
+ {
+ WriteLastFrameAccess(patchCounterSets, patchIdx, frameIdx);
+ }
+ return patchIdx;
+ }
+
+ bool ReadHemisphericalIrradiance(IrradianceBufferType patchIrradiances, CellPatchIndexBufferType cellPatchIndices, uint gridSize, StructuredBuffer cascadeOffsets, float3 cascadeFocusPos, uint cascadeCount, float voxelMinSize, float3 worldPosition, float3 worldNormal, uint startCascadeIdx, out SphericalHarmonics::RGBL1 resultIrradiance)
+ {
+ VolumePositionResolution posResolution = ResolveVolumePosition(worldPosition, cascadeFocusPos, gridSize, cascadeOffsets, cascadeCount, voxelMinSize, startCascadeIdx);
+ bool resultBool = false;
+
+ resultIrradiance = (SphericalHarmonics::RGBL1)0; // Theoretically not required but added to silence a shader compilation warning.
+
+ if (posResolution.isValid())
+ {
+ const uint3 positionStorageSpace = ConvertGridSpaceToStorageSpace(posResolution.positionGridSpace, gridSize, cascadeOffsets[posResolution.cascadeIdx]);
+ resultBool = ReadHemisphericalIrradiance(patchIrradiances, cellPatchIndices, gridSize, posResolution.cascadeIdx, positionStorageSpace, worldNormal, resultIrradiance);
+ }
+
+ return resultBool;
+ }
+
+ bool ReadHemisphericalIrradiance(IrradianceBufferType patchIrradiances, CellPatchIndexBufferType cellPatchIndices, uint gridSize, StructuredBuffer cascadeOffsets, float3 cascadeFocusPos, uint cascadeCount, float voxelMinSize, float3 worldPosition, float3 worldNormal, out SphericalHarmonics::RGBL1 resultIrradiance)
+ {
+ const uint conservativeStartCascadeIdx = 0;
+ return ReadHemisphericalIrradiance(
+ patchIrradiances,
+ cellPatchIndices,
+ gridSize,
+ cascadeOffsets,
+ cascadeFocusPos,
+ cascadeCount,
+ voxelMinSize,
+ worldPosition,
+ worldNormal,
+ conservativeStartCascadeIdx,
+ resultIrradiance);
+ }
+
+ float3 ReadPlanarIrradiance(IrradianceBufferType patchIrradiances, CellPatchIndexBufferType cellPatchIndices, uint gridSize, uint cascadeIdx, uint3 gridSpacePosition, float3 worldNormal)
+ {
+ SphericalHarmonics::RGBL1 resultIrradiance;
+ bool resultBool = ReadHemisphericalIrradiance(patchIrradiances, cellPatchIndices, gridSize, cascadeIdx, gridSpacePosition, worldNormal, resultIrradiance);
+ if (resultBool)
+ return max(0, SphericalHarmonics::Eval(resultIrradiance, worldNormal));
+ else
+ return invalidIrradiance;
+ }
+
+ float3 ReadPlanarIrradiance(float3 gridTargetPos, IrradianceBufferType patchIrradiances, CellPatchIndexBufferType cellPatchIndices, uint gridSize, StructuredBuffer cascadeOffsets, uint cascadeCount, float voxelMinSize, float3 worldPosition, float3 worldNormal)
+ {
+ VolumePositionResolution posResolution = ResolveVolumePosition(worldPosition, gridTargetPos, gridSize, cascadeOffsets, cascadeCount, voxelMinSize);
+ if (posResolution.isValid())
+ {
+ const uint3 positionStorageSpace = ConvertGridSpaceToStorageSpace(posResolution.positionGridSpace, gridSize, cascadeOffsets[posResolution.cascadeIdx]);
+ return ReadPlanarIrradiance(patchIrradiances, cellPatchIndices, gridSize, posResolution.cascadeIdx, positionStorageSpace, worldNormal);
+ }
+ else
+ {
+ return invalidIrradiance;
+ }
+ }
+
+ void MarkInvalid(inout SphericalHarmonics::RGBL1 irradiance)
+ {
+ irradiance.l0 = -1.0f;
+ }
+
+ bool IsValid(inout SphericalHarmonics::RGBL1 irradiance)
+ {
+ return all(irradiance.l0 != -1.0f);
+ }
+}
+
+#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PatchUtil.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PatchUtil.hlsl.meta
new file mode 100644
index 00000000000..d4dc1c58234
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PatchUtil.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 804415e4b1bf68147a30546faefeeb0b
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracing.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracing.hlsl
new file mode 100644
index 00000000000..7f903392734
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracing.hlsl
@@ -0,0 +1,115 @@
+#include "Common.hlsl"
+#include "PatchUtil.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/FetchGeometry.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/TraceRayAndQueryHit.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common.hlsl"
+#include "PathTracingCommon.hlsl"
+#include "PathTracingMaterials.hlsl"
+
+static const float3 invalidRadianceSample = float3(-1.0f, -1.0f, -1.0f);
+
+float3 SampleOutgoingRadianceAssumingLambertianBrdf(
+ float3 position,
+ float3 normal,
+ UnifiedRT::DispatchInfo dispatchInfo,
+ UnifiedRT::RayTracingAccelStruct accelStruct,
+ StructuredBuffer lightList,
+ bool multiBounce,
+ IrradianceBufferType patchIrradiances,
+ StructuredBuffer cellPatchIndices,
+ uint gridSize,
+ StructuredBuffer cascadeOffsets,
+ float3 gridTargetPos,
+ uint cascadeCount,
+ float voxelMinSize,
+ float3 albedo,
+ float3 emission)
+{
+ float3 radianceSample = 0.0f;
+
+ // For now we assume only a single directional light has been added.
+ // Support for more lights will be added.
+ PTLight sun = lightList[0];
+
+ const float worldHitNormalDotSunDir = dot(sun.forward, normal);
+ if (worldHitNormalDotSunDir < 0.0f)
+ {
+ UnifiedRT::Ray ray2;
+ ray2.origin = OffsetRayOrigin(position, normal);
+ ray2.direction = -sun.forward;
+ ray2.tMin = 0;
+ ray2.tMax = FLT_MAX;
+
+ UnifiedRT::Hit hitResult2 = UnifiedRT::TraceRayClosestHit(dispatchInfo, accelStruct, 0xFFFFFFFF, ray2, UnifiedRT::kRayFlagNone);
+ if (!hitResult2.IsValid())
+ {
+ radianceSample += sun.intensity * dot(-sun.forward, normal);
+ }
+ }
+
+ if (multiBounce)
+ {
+ float3 cacheRead = PatchUtil::ReadPlanarIrradiance(gridTargetPos, patchIrradiances, cellPatchIndices, gridSize, cascadeOffsets, cascadeCount, voxelMinSize, position, normal);
+ if (all(cacheRead != PatchUtil::invalidIrradiance))
+ radianceSample += cacheRead;
+ }
+
+ radianceSample *= albedo / PI;
+ radianceSample += emission;
+ return radianceSample;
+}
+
+float3 SampleIncomingRadianceAssumingLambertianBrdf(
+ UnifiedRT::DispatchInfo dispatchInfo,
+ UnifiedRT::RayTracingAccelStruct accelStruct,
+ UnifiedRT::Ray ray,
+ StructuredBuffer lightList,
+ bool multiBounce,
+ TextureCube envTex,
+ SamplerState envSampler,
+ IrradianceBufferType patchIrradiances,
+ StructuredBuffer cellPatchIndices,
+ uint gridSize,
+ StructuredBuffer cascadeOffsets,
+ float3 gridTargetPos,
+ uint cascadeCount,
+ float voxelMinSize)
+{
+ UnifiedRT::Hit hitResult = UnifiedRT::TraceRayClosestHit(dispatchInfo, accelStruct, 0xFFFFFFFF, ray, UnifiedRT::kRayFlagNone);
+ float3 radianceSample;
+ if (hitResult.IsValid())
+ {
+ if (!hitResult.isFrontFace)
+ {
+ radianceSample = invalidRadianceSample;
+ }
+ else
+ {
+ const UnifiedRT::InstanceData hitInstance = UnifiedRT::GetInstance(hitResult.instanceID);
+ const PTHitGeom hitGeo = GetHitGeomInfo(hitInstance, hitResult);
+ const MaterialProperties hitMat = LoadMaterialProperties(hitInstance, false, hitGeo);
+
+ radianceSample = SampleOutgoingRadianceAssumingLambertianBrdf(
+ hitGeo.worldPosition,
+ hitGeo.worldFaceNormal,
+ dispatchInfo,
+ accelStruct,
+ lightList,
+ multiBounce,
+ patchIrradiances,
+ cellPatchIndices,
+ gridSize,
+ cascadeOffsets,
+ gridTargetPos,
+ cascadeCount,
+ voxelMinSize,
+ hitMat.baseColor,
+ hitMat.emissive);
+ }
+ }
+ else
+ {
+ radianceSample = envTex.SampleLevel(envSampler, ray.direction, 0);
+ }
+ return radianceSample;
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracing.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracing.hlsl.meta
new file mode 100644
index 00000000000..987d3bb00e0
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracing.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: a30369464edbd71488d5d8fdb678695f
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingCommon.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingCommon.hlsl
new file mode 100644
index 00000000000..a817bd18258
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingCommon.hlsl
@@ -0,0 +1,177 @@
+#ifndef _PATHTRACING_PATHTRACINGCOMMON_HLSL_
+#define _PATHTRACING_PATHTRACINGCOMMON_HLSL_
+
+#pragma warning(error: 3206) // Implicit truncation of vector type
+
+#include "Packages/com.unity.render-pipelines.core/Runtime/Sampling/Common.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/FetchGeometry.hlsl"
+
+#define LIGHT_SAMPLING 0
+#define BRDF_SAMPLING 1
+#define MIS 2
+
+// Force uniform sampling of the skybox for debugging / ground truth generation
+//#define UNIFORM_ENVSAMPLING
+
+// Emissive mesh sampling: we combine explicit light and brdf sampling using MIS.
+// We can disable MIS and use exclusively one of the two sampling techniques with the EMISSIVE_SAMPLING define.
+#define EMISSIVE_SAMPLING BRDF_SAMPLING
+
+#define SPOT_LIGHT 0
+#define DIRECTIONAL_LIGHT 1
+#define POINT_LIGHT 2
+#define RECTANGULAR_LIGHT 3
+#define DISC_LIGHT 4
+#define PYRAMID_LIGHT 5
+#define BOX_LIGHT 6
+#define EMISSIVE_MESH 8 // Must match the variable in UnityEngine.PathTracing.Core.World
+#define ENVIRONMENT_LIGHT 9 // Must match the variable in UnityEngine.PathTracing.Core.World
+
+#define LIGHT_PICKING_METHOD_UNIFORM 0
+#define LIGHT_PICKING_METHOD_POWER 1
+
+#define DIRECT_RAY_VIS_MASK 1u
+#define INDIRECT_RAY_VIS_MASK 2u
+#define SHADOW_RAY_VIS_MASK 4u
+// warning: bits 8u and 16u are used for lightmap LODs
+
+#define MAX_TRANSMISSION_BOUNCES 6
+
+
+struct HitEntry
+{
+ uint instanceID;
+ uint primitiveIndex;
+ float2 barycentrics;
+ bool IsValid()
+ {
+ return instanceID != -1;
+ }
+};
+
+struct PixelState
+{
+ float3 radiance;
+ float3 avgLightingDir;
+ float2 coord;
+ float2 motionVector;
+ float3 normal;
+ uint2 launchIndex;
+ uint2 launchDim;
+ float depth;
+};
+
+struct PTLight
+{
+ float3 position;
+ int type;
+ float3 intensity;
+ int castsShadows;
+ float3 forward;
+ int contributesToDirectLighting;
+ float4 attenuation;
+ float3 up;
+ float width;
+ float3 right;
+ float height;
+ uint layerMask;
+ float indirectScale;
+ float2 unused;
+ float range;
+ int shadowMaskChannel;
+ int falloffIndex;
+ float shadowRadius;
+ int cookieIndex;
+};
+
+int GetMeshLightInstanceID(PTLight light)
+{
+ return light.height;
+}
+
+struct LightSample
+{
+ float3 lightVector;
+ float3 L;
+ float weight;
+ float distanceToLight;
+ float2 uv;
+ int materialIndex;
+};
+
+float4 GetColumn(float4x4 mat, int colIndex)
+{
+ return float4(mat[0][3], mat[1][3], mat[2][3], mat[3][3]);
+}
+
+// Photometric RGB -> (Perceived) Luminance / digital ITU BT.709 (https://www.itu.int/rec/R-REC-BT.709)
+float Luminance(float3 color)
+{
+ const float3 weights = float3(0.2126f, 0.7152f, 0.0722f);
+ return dot(color, weights);
+}
+
+float3 EvalDiffuseBrdf(float3 albedo)
+{
+ return albedo / PI;
+}
+
+float ClampedCosine(float3 normal, float3 direction)
+{
+ return saturate(dot(normal, direction));
+}
+
+struct PTHitGeom
+{
+ float3 worldPosition;
+ float3 lastWorldPosition;
+ float3 worldNormal;
+ float3 worldFaceNormal;
+ float2 uv0;
+ float2 uv1;
+ float triangleArea;
+ uint renderingLayerMask;
+
+ void FixNormals(float3 rayDirection)
+ {
+ worldFaceNormal = dot(rayDirection, worldFaceNormal) >= 0 ? -worldFaceNormal : worldFaceNormal;
+ worldNormal = dot(worldNormal, worldFaceNormal) < 0 ? -worldNormal : worldNormal;
+ }
+
+ float3 NextRayOrigin()
+ {
+ return OffsetRayOrigin(worldPosition, worldFaceNormal);
+ }
+
+ float3 NextTransmissionRayOrigin()
+ {
+ return OffsetRayOrigin(worldPosition, -worldFaceNormal);
+ }
+};
+
+PTHitGeom GetHitGeomInfo(UnifiedRT::InstanceData instanceInfo, UnifiedRT::Hit hit)
+{
+ UnifiedRT::HitGeomAttributes attributes = UnifiedRT::FetchHitGeomAttributes(hit);
+
+ PTHitGeom res;
+ res.worldPosition = mul(instanceInfo.localToWorld, float4(attributes.position, 1)).xyz;
+ res.lastWorldPosition = mul(instanceInfo.previousLocalToWorld, float4(attributes.position, 1)).xyz;
+ res.worldNormal = normalize(mul((float3x3)instanceInfo.localToWorldNormals, attributes.normal));
+ res.worldFaceNormal = mul((float3x3)instanceInfo.localToWorldNormals, attributes.faceNormal);
+ res.uv0 = attributes.uv0.xy;
+ res.uv1 = attributes.uv1.xy;
+ res.renderingLayerMask = instanceInfo.renderingLayerMask;
+
+ // compute the area of the hit point (used for MIS)
+ float l = length(res.worldFaceNormal);
+ res.triangleArea = 0.5 * determinant(instanceInfo.localToWorld) * l;
+
+ // normalize the face normal
+ if (l > 0)
+ res.worldFaceNormal /= l;
+
+ return res;
+}
+
+#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingCommon.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingCommon.hlsl.meta
new file mode 100644
index 00000000000..5897c421830
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingCommon.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 26c202ba0499aad4387888eff3a31187
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingMaterials.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingMaterials.hlsl
new file mode 100644
index 00000000000..7798f215896
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingMaterials.hlsl
@@ -0,0 +1,123 @@
+#ifndef _PATHTRACING_PATHTRACINGMATERIALS_HLSL_
+#define _PATHTRACING_PATHTRACINGMATERIALS_HLSL_
+
+struct PTMaterial
+{
+ int albedoTextureIndex;
+ int emissionTextureIndex;
+ int transmissionTextureIndex;
+ uint flags;
+ float2 albedoScale;
+ float2 albedoOffset;
+ float2 emissionScale;
+ float2 emissionOffset;
+ float2 transmissionScale;
+ float2 transmissionOffset;
+ float3 emissionColor;
+ uint albedoAndEmissionUVChannel;
+};
+
+struct MaterialProperties
+{
+ float3 baseColor;
+ float metalness;
+
+ float3 emissive;
+ float roughness;
+
+ float3 transmission;
+ uint isTransmissive;
+
+ uint doubleSidedGI;
+};
+
+StructuredBuffer g_MaterialList;
+
+// Textures
+Texture2DArray g_AlbedoTextures;
+Texture2DArray g_TransmissionTextures;
+Texture2DArray g_EmissionTextures;
+float g_AtlasTexelSize; // The size of 1 texel in the atlases above
+
+// Samplers
+SamplerState sampler_g_EmissionTextures;
+SamplerState sampler_g_AlbedoTextures;
+SamplerState sampler_g_TransmissionTextures;
+
+float g_AlbedoBoost;
+
+float4 SampleAtlas(Texture2DArray atlas, SamplerState atlasSampler, uint index, float2 uv, float2 scale, float2 offset, bool pointFilterMode)
+{
+ // Apply the scale and offset to access to desired atlas entry
+ float2 localUV = uv * scale + offset;
+
+ // To prevent sampling part of the neighbor due to bilinear filtering, we need to clamp the sample
+ // position to an 'inner rectangle' of the atlas entry, which is shrunk by half a texel on each side.
+ float2 innerRectMin = offset + (g_AtlasTexelSize * 0.5f);
+ // Calculating the rectangle extent is a bit tricky, because the size of the entry (scale)
+ // is not necessarily a multiple of the atlas texel size. We need to round it up to the next texel first,
+ // then subtract the half texel.
+ float2 innerRectMax = ceil((offset + scale) / g_AtlasTexelSize) * g_AtlasTexelSize - (g_AtlasTexelSize * 0.5f);
+ float2 clampedUV = clamp(localUV, innerRectMin, innerRectMax);
+
+ [branch] if (pointFilterMode)
+ return atlas.Load(int4(clampedUV * rcp(g_AtlasTexelSize), index, 0));
+ else
+ return atlas.SampleLevel(atlasSampler, float3(clampedUV, index), 0);
+}
+
+MaterialProperties LoadMaterialProperties(UnifiedRT::InstanceData instanceInfo, bool useWhiteAsBaseColor, PTHitGeom hitGeom)
+{
+ int materialIndex = instanceInfo.userMaterialID;
+ PTMaterial matInfo = g_MaterialList[materialIndex];
+
+ MaterialProperties material = (MaterialProperties)0;
+
+ material.baseColor = float3(0.75, 0.75, 0.75);
+ material.emissive = float3(0.0, 0.0, 0.0);
+ material.transmission = float3(1.0, 1.0, 1.0);
+ material.isTransmissive = matInfo.flags & 1;
+
+ if (matInfo.albedoTextureIndex != -1)
+ {
+ float2 textureUV = matInfo.albedoAndEmissionUVChannel == 1 ? hitGeom.uv1 : hitGeom.uv0;
+ float4 texColor = SampleAtlas(g_AlbedoTextures, sampler_g_AlbedoTextures, matInfo.albedoTextureIndex, textureUV, matInfo.albedoScale, matInfo.albedoOffset, false);
+ material.baseColor = texColor.rgb;
+ // apply albedo boost, but still keep the reflectance at maximum 100%
+ material.baseColor = min(g_AlbedoBoost * material.baseColor, float3(1.0, 1.0, 1.0));
+ material.transmission = 1.0f - float3(texColor.a, texColor.a, texColor.a);
+ }
+
+ if (matInfo.emissionTextureIndex != -1)
+ {
+ float2 textureUV = matInfo.albedoAndEmissionUVChannel == 1 ? hitGeom.uv1 : hitGeom.uv0;
+ material.emissive = SampleAtlas(g_EmissionTextures, sampler_g_EmissionTextures, matInfo.emissionTextureIndex, textureUV, matInfo.emissionScale, matInfo.emissionOffset, false).rgb;
+ }
+ else
+ {
+ material.emissive = matInfo.emissionColor;
+ }
+
+ if (matInfo.transmissionTextureIndex != -1)
+ {
+ float2 uv = hitGeom.uv0;
+ bool pointSampleTransmission = (matInfo.flags & 4) != 0;
+ material.transmission = saturate(SampleAtlas(g_TransmissionTextures, sampler_g_TransmissionTextures, matInfo.transmissionTextureIndex, uv, matInfo.transmissionScale, matInfo.transmissionOffset, pointSampleTransmission).rgb);
+ }
+
+ // unused for now, we need these for specular support
+ material.roughness = 1.0;
+ material.metalness = 0;
+
+ if (useWhiteAsBaseColor)
+ {
+ // override to white albedo, because albedo is multiplied with lightmap color at runtime
+ material.baseColor = float3(1, 1, 1);
+ }
+
+ material.doubleSidedGI = matInfo.flags & 2;
+
+ return material;
+}
+
+#endif
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingMaterials.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingMaterials.hlsl.meta
new file mode 100644
index 00000000000..ff555638ec9
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/PathTracingMaterials.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 8441f2d912ff46d418f324f16d4540c1
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.hlsl
new file mode 100644
index 00000000000..6db59b70755
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.hlsl
@@ -0,0 +1,161 @@
+#include "Common.hlsl"
+#include "RingBuffer.hlsl"
+#include "PathTracing.hlsl"
+#include "RestirEstimation.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/Sampling/PseudoRandom.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/Common.hlsl"
+
+StructuredBuffer _RingConfigBuffer;
+StructuredBuffer _PatchIrradiances;
+StructuredBuffer _PatchGeometries;
+StructuredBuffer _CellPatchIndices;
+StructuredBuffer _CascadeOffsets;
+RWStructuredBuffer _PatchRealizations;
+
+UNIFIED_RT_DECLARE_ACCEL_STRUCT(g_SceneAccelStruct);
+
+StructuredBuffer g_LightList;
+
+uint _FrameIdx;
+uint _GridSize;
+uint _CascadeCount;
+float _VoxelMinSize;
+uint _MultiBounce;
+float _ConfidenceCap;
+uint _ValidationFrameInterval;
+uint _RingConfigOffset;
+float3 _GridTargetPos;
+
+TextureCube g_EnvTex;
+SamplerState sampler_g_EnvTex;
+
+void GenerateCandidateAndResampleTemporally(UnifiedRT::DispatchInfo dispatchInfo)
+{
+ uint patchIdx = dispatchInfo.dispatchThreadID.x;
+
+ if (RingBuffer::IsPositionUnused(_RingConfigBuffer, _RingConfigOffset, patchIdx))
+ return;
+
+ UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(g_SceneAccelStruct);
+ const Realization oldRealization = _PatchRealizations[patchIdx];
+ Realization newRealization = (Realization)0; // Initializing only to silence shader warning.
+
+ const bool isCandidateFrame = _FrameIdx % _ValidationFrameInterval != _ValidationFrameInterval - 1;
+
+ // We expect this branch to have relatively low divergence because almost all realizations either
+ // have a non-zero weight or they have been allocated this frame. Therefore, realizations that are
+ // nearby in the buffer should almost always agree on whether their weight is zero or not.
+ if (isCandidateFrame || oldRealization.weight == 0.0f)
+ {
+ Reservoir reservoir;
+ reservoir.Init();
+
+ QrngPcg4D rng;
+ const uint candidateFrameIdx = _FrameIdx - _FrameIdx / _ValidationFrameInterval;
+ rng.Init(uint2(patchIdx, 0), candidateFrameIdx);
+
+ {
+ const PatchUtil::PatchGeometry patchGeo = _PatchGeometries[patchIdx];
+
+ UnifiedRT::Ray ray;
+ ray.origin = OffsetRayOrigin(patchGeo.position, patchGeo.normal);
+ ray.direction = UniformHemisphereSample(float2(rng.GetFloat(0), rng.GetFloat(1)), patchGeo.normal);
+ ray.tMin = 0;
+ ray.tMax = FLT_MAX;
+
+ UnifiedRT::Hit hitResult = UnifiedRT::TraceRayClosestHit(dispatchInfo, accelStruct, 0xFFFFFFFF, ray, UnifiedRT::kRayFlagNone);
+ Sample sample = (Sample)0; // Initializing value only to silence shader compilation warning.
+ sample.rayOrigin = ray.origin;
+ sample.rayDirection = ray.direction;
+ if (hitResult.IsValid())
+ {
+ UnifiedRT::InstanceData hitInstance = UnifiedRT::GetInstance(hitResult.instanceID);
+ PTHitGeom hitGeo = GetHitGeomInfo(hitInstance, hitResult);
+ MaterialProperties mat = LoadMaterialProperties(hitInstance, false, hitGeo);
+
+ sample.sampleType = SAMPLE_TYPE_HIT;
+ sample.hitPointOrDirection = hitGeo.worldPosition;
+
+ if (!hitResult.isFrontFace)
+ {
+ // If we hit the backface of a water-tight piece of geometry we do nothing. This is to prevent accumulating "false" darkness
+ // which can give artifacts if a patch reappears after temporarily being inside moving geometry.
+ // If we hit the backface of geometry which is not water tight, then this most likely a user authoring problem.
+ return;
+ }
+ else
+ {
+ sample.radiance = SampleOutgoingRadianceAssumingLambertianBrdf(
+ hitGeo.worldPosition,
+ hitGeo.worldFaceNormal,
+ dispatchInfo,
+ accelStruct,
+ g_LightList,
+ _MultiBounce,
+ _PatchIrradiances,
+ _CellPatchIndices,
+ _GridSize,
+ _CascadeOffsets,
+ _GridTargetPos,
+ _CascadeCount,
+ _VoxelMinSize,
+ mat.baseColor,
+ mat.emissive);
+ }
+ }
+ else
+ {
+ sample.sampleType = SAMPLE_TYPE_ENV;
+ sample.radiance = g_EnvTex.SampleLevel(sampler_g_EnvTex, ray.direction, 0);
+ sample.hitPointOrDirection = ray.direction;
+ }
+
+ float invCandidateWeight = 2.0f * PI;
+ float candidateWeight = TargetFunction(sample) * invCandidateWeight;
+ reservoir.Update(sample, 1.0f, candidateWeight, 0.5f);
+ }
+
+ {
+ float cappedConfidence = min(oldRealization.confidence, _ConfidenceCap);
+ float candidateWeight = TargetFunction(oldRealization.sample) * oldRealization.weight * cappedConfidence;
+ reservoir.Update(oldRealization.sample, cappedConfidence, candidateWeight, rng.GetFloat(3));
+ }
+
+ newRealization = CreateRealizationFromReservoir(reservoir);
+ }
+ else
+ {
+ UnifiedRT::Ray ray;
+ ray.origin = oldRealization.sample.rayOrigin;
+ ray.direction = oldRealization.sample.rayDirection;
+ ray.tMin = 0;
+ ray.tMax = FLT_MAX;
+
+ const float3 radianceSample = SampleIncomingRadianceAssumingLambertianBrdf(
+ dispatchInfo,
+ accelStruct,
+ ray,
+ g_LightList,
+ _MultiBounce,
+ g_EnvTex,
+ sampler_g_EnvTex,
+ _PatchIrradiances,
+ _CellPatchIndices,
+ _GridSize,
+ _CascadeOffsets,
+ _GridTargetPos,
+ _CascadeCount,
+ _VoxelMinSize);
+
+ if (all(radianceSample != invalidRadianceSample))
+ {
+ newRealization = oldRealization;
+ if (all(radianceSample + oldRealization.sample.radiance != 0.0f))
+ {
+ newRealization.confidence *= max(0, 1.0f - length(abs(radianceSample - oldRealization.sample.radiance) / (radianceSample + oldRealization.sample.radiance)) / length(float3(1,1,1)));
+ }
+ }
+ }
+
+ _PatchRealizations[patchIdx] = newRealization;
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.hlsl.meta
new file mode 100644
index 00000000000..ed1343525db
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: e78ab4c515da1e442a19a4905ed03844
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.urtshader b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.urtshader
new file mode 100644
index 00000000000..602c8f9aa8e
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.urtshader
@@ -0,0 +1,10 @@
+// Surface Cache shaders do not currently work on Switch due to its limited binding range
+// https://jira.unity3d.com/browse/GFXLIGHT-1730
+#pragma exclude_renderers switch
+
+#define UNIFIED_RT_GROUP_SIZE_X 64
+#define UNIFIED_RT_GROUP_SIZE_Y 1
+#define UNIFIED_RT_GROUP_SIZE_Z 1
+#define UNIFIED_RT_RAYGEN_FUNC GenerateCandidateAndResampleTemporally
+
+#include "RestirCandidateTemporal.hlsl"
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.urtshader.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.urtshader.meta
new file mode 100644
index 00000000000..cee35362d9c
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirCandidateTemporal.urtshader.meta
@@ -0,0 +1,10 @@
+fileFormatVersion: 2
+guid: 905bb0d291c283e4aaaea1a6e4aa8e58
+ScriptedImporter:
+ internalIDToNameTable: []
+ externalObjects: {}
+ serializedVersion: 2
+ userData:
+ assetBundleName:
+ assetBundleVariant:
+ script: {fileID: 11500000, guid: 42d537a8a4089e448a99fc57a06d74a9, type: 3}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.compute
new file mode 100644
index 00000000000..84120914ab9
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.compute
@@ -0,0 +1,49 @@
+// Surface Cache shaders do not currently work on Switch due to its limited binding range
+// https://jira.unity3d.com/browse/GFXLIGHT-1730
+#pragma exclude_renderers switch switch2
+#pragma kernel Estimate
+
+#include "Common.hlsl"
+#include "Estimation.hlsl"
+#include "RingBuffer.hlsl"
+#include "RestirEstimation.hlsl"
+
+StructuredBuffer _RingConfigBuffer;
+StructuredBuffer _PatchRealizations;
+StructuredBuffer _PatchGeometries;
+RWStructuredBuffer _PatchIrradiances;
+RWStructuredBuffer _PatchStatistics;
+RWStructuredBuffer _PatchCounterSets;
+
+uint _RingConfigOffset;
+float _ShortHysteresis;
+
+[numthreads(64, 1, 1)]
+void Estimate(uint patchIdx : SV_DispatchThreadID)
+{
+ if (RingBuffer::IsPositionUnused(_RingConfigBuffer, _RingConfigOffset, patchIdx))
+ return;
+
+ const Realization realization = _PatchRealizations[patchIdx];
+
+ float3 rayDirection;
+ if (realization.sample.sampleType == SAMPLE_TYPE_ENV)
+ {
+ rayDirection = realization.sample.hitPointOrDirection;
+ }
+ else
+ {
+ const float3 patchPosition = _PatchGeometries[patchIdx].position;
+ rayDirection = normalize(realization.sample.hitPointOrDirection - patchPosition);
+ }
+
+ if (realization.weight != 0.0f)
+ {
+ SphericalHarmonics::RGBL1 estimate;
+ estimate.l0 = realization.sample.radiance * SphericalHarmonics::y0 * realization.weight;
+ estimate.l1s[0] = realization.sample.radiance * SphericalHarmonics::y1Constant * rayDirection.x * realization.weight;
+ estimate.l1s[1] = realization.sample.radiance * SphericalHarmonics::y1Constant * rayDirection.z * realization.weight;
+ estimate.l1s[2] = realization.sample.radiance * SphericalHarmonics::y1Constant * rayDirection.y * realization.weight;
+ ProcessAndStoreRadianceSample(_PatchIrradiances, _PatchStatistics, _PatchCounterSets, patchIdx, estimate, _ShortHysteresis);
+ }
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.compute.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.compute.meta
new file mode 100644
index 00000000000..b72136bd2c3
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.compute.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: b5dbdcea251f42c4a9b8721877f436bf
+ComputeShaderImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.hlsl b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.hlsl
new file mode 100644
index 00000000000..7987d475228
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.hlsl
@@ -0,0 +1,57 @@
+#define SAMPLE_TYPE_HIT 0
+#define SAMPLE_TYPE_ENV 1
+
+struct Sample
+{
+ float3 radiance;
+ float3 hitPointOrDirection;
+ float3 rayOrigin;
+ float3 rayDirection;
+ uint sampleType; // SAMPLE_TYPE_HIT is hit, SAMPLE_TYPE_ENV is env.
+};
+
+struct Realization
+{
+ Sample sample;
+ float weight;
+ float confidence;
+};
+
+float TargetFunction(Sample sample)
+{
+ return sample.radiance.r + sample.radiance.g + sample.radiance.b;
+}
+
+struct Reservoir
+{
+ Sample sample;
+ float weightSum;
+ float confidenceSum;
+
+ void Init()
+ {
+ sample = (Sample)0;
+ weightSum = 0.0f;
+ confidenceSum = 0;
+ }
+
+ void Update(in Sample newSample, float confidence, float weight, float u)
+ {
+ confidenceSum += confidence;
+ weightSum += weight;
+ if (u * weightSum < weight)
+ sample = newSample;
+ }
+};
+
+Realization CreateRealizationFromReservoir(in Reservoir reservoir)
+{
+ Realization realization;
+ realization.sample = reservoir.sample;
+ realization.confidence = reservoir.confidenceSum;
+ if (reservoir.weightSum == 0.0f)
+ realization.weight = 0.0f;
+ else
+ realization.weight = reservoir.weightSum / (TargetFunction(reservoir.sample) * reservoir.confidenceSum);
+ return realization;
+}
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.hlsl.meta b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.hlsl.meta
new file mode 100644
index 00000000000..118f9bfe784
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirEstimation.hlsl.meta
@@ -0,0 +1,7 @@
+fileFormatVersion: 2
+guid: 66f41beb195ccdf408b955566b037e9d
+ShaderIncludeImporter:
+ externalObjects: {}
+ userData:
+ assetBundleName:
+ assetBundleVariant:
diff --git a/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirSpatial.compute b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirSpatial.compute
new file mode 100644
index 00000000000..33c8feabcbc
--- /dev/null
+++ b/Packages/com.unity.render-pipelines.universal/Runtime/RendererFeatures/SurfaceCacheGlobalIlluminationRendererFeature/SurfaceCacheCore/RestirSpatial.compute
@@ -0,0 +1,71 @@
+// Surface Cache shaders do not currently work on Switch due to its limited binding range
+// https://jira.unity3d.com/browse/GFXLIGHT-1730
+#pragma exclude_renderers switch switch2
+#pragma kernel ResampleSpatially
+
+#include "PatchUtil.hlsl"
+#include "RingBuffer.hlsl"
+#include "Packages/com.unity.render-pipelines.core/Runtime/Sampling/QuasiRandom.hlsl"
+#include "RestirEstimation.hlsl"
+
+StructuredBuffer _RingConfigBuffer;
+StructuredBuffer _InputPatchRealizations;
+StructuredBuffer