This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 126062fea1dcb7f478883bc50375b95f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,386 @@
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using UnityEngine.Rendering;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
namespace UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler
{
// Wrapper struct to allow storing strings in a DynamicArray which requires a type with a parameterless constructor
internal readonly struct Name
{
public readonly string name;
public readonly int utf8ByteCount;
public Name(string name, bool computeUTF8ByteCount = false)
{
this.name = name;
this.utf8ByteCount = ((name?.Length > 0) && computeUTF8ByteCount) ? System.Text.Encoding.UTF8.GetByteCount((ReadOnlySpan<char>)name) : 0;
}
}
// Helper extensions for NativeList
internal static class NativeListExtensions
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static unsafe ReadOnlySpan<T> MakeReadOnlySpan<T>(this ref NativeList<T> list, int first, int numElements) where T : unmanaged
{
#if UNITY_EDITOR
if (first + numElements > list.Length)
throw new IndexOutOfRangeException();
#endif
return new ReadOnlySpan<T>(&list.GetUnsafeReadOnlyPtr()[first], numElements);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static int LastIndex<T>(this ref NativeList<T> list) where T : unmanaged
{
return list.Length - 1;
}
}
// Note pass=node in the graph, both are sometimes mixed up here
// Datastructure that contains passes and dependencies and allow you to iterate and reason on them more like a graph
internal class CompilerContextData : IDisposable
{
public CompilerContextData()
{
fences = new Dictionary<int, GraphicsFence>();
resources = new ResourcesData();
passNames = new DynamicArray<Name>(0, false); // T in NativeList<T> cannot contain managed types, so the names are stored separately
}
void AllocateNativeDataStructuresIfNeeded(int estimatedNumPasses)
{
// Only first init or if Dispose() has been called through RenderGraph.Cleanup()
if (!m_AreNativeListsAllocated)
{
// These are risky heuristics that only work because we purposely estimate a very high number of passes
// We need to fix this with a proper size computation
passData = new NativeList<PassData>(estimatedNumPasses, AllocatorManager.Persistent);
compactedNonCulledRasterPasses = new NativeList<PassData>(0, AllocatorManager.Persistent); // Will be resized during the compilation
inputData = new NativeList<PassInputData>(estimatedNumPasses * 2, AllocatorManager.Persistent);
outputData = new NativeList<PassOutputData>(estimatedNumPasses * 2, AllocatorManager.Persistent);
fragmentData = new NativeList<PassFragmentData>(estimatedNumPasses * 4, AllocatorManager.Persistent);
sampledData = new NativeList<ResourceHandle>(estimatedNumPasses * 2, AllocatorManager.Persistent);
randomAccessResourceData = new NativeList<PassRandomWriteData>(4, AllocatorManager.Persistent); // We assume not a lot of passes use random write
nativePassData = new NativeList<NativePassData>(estimatedNumPasses, AllocatorManager.Persistent);// assume nothing gets merged
nativeSubPassData = new NativeList<SubPassDescriptor>(estimatedNumPasses, AllocatorManager.Persistent);// there should "never" be more subpasses than graph passes
createData = new NativeList<ResourceHandle>(estimatedNumPasses * 2, AllocatorManager.Persistent); // assume every pass creates two resources
destroyData = new NativeList<ResourceHandle>(estimatedNumPasses * 2, AllocatorManager.Persistent); // assume every pass destroys two resources
m_AreNativeListsAllocated = true;
}
}
public void Initialize(RenderGraphResourceRegistry resourceRegistry, int estimatedNumPasses)
{
resources.Initialize(resourceRegistry);
passNames.Reserve(estimatedNumPasses, false);
AllocateNativeDataStructuresIfNeeded(estimatedNumPasses);
}
public void Clear()
{
passNames.Clear();
resources.Clear();
if (m_AreNativeListsAllocated)
{
passData.Clear();
compactedNonCulledRasterPasses.Clear();
fences.Clear();
inputData.Clear();
outputData.Clear();
fragmentData.Clear();
sampledData.Clear();
randomAccessResourceData.Clear();
nativePassData.Clear();
nativeSubPassData.Clear();
createData.Clear();
destroyData.Clear();
}
}
public ResourcesData resources;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref ResourceUnversionedData UnversionedResourceData(in ResourceHandle h)
{
return ref resources.unversionedData[h.iType].ElementAt(h.index);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref ResourceVersionedData VersionedResourceData(in ResourceHandle h)
{
return ref resources[h];
}
// Iterate over all the readers of a particular resource
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<ResourceReaderData> Readers(in ResourceHandle h)
{
int firstReader = resources.IndexReader(h, 0);
int numReaders = resources[h].numReaders;
return resources.readerData[h.iType].MakeReadOnlySpan(firstReader, numReaders);
}
// Get the i'th reader of a resource
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ref ResourceReaderData ResourceReader(in ResourceHandle h, int i)
{
int numReaders = resources[h].numReaders;
#if UNITY_ENABLE_CHECKS
if (i >= numReaders)
{
throw new Exception("Invalid reader id");
}
#endif
return ref resources.readerData[h.iType].ElementAt(resources.IndexReader(h, 0) + i);
}
// Data per graph level renderpass
public NativeList<PassData> passData;
public NativeList<PassData> compactedNonCulledRasterPasses;
public Dictionary<int, GraphicsFence> fences;
public DynamicArray<Name> passNames;
// Tightly packed lists all passes, add to these lists then index in it using offset+count
public NativeList<PassInputData> inputData;
public NativeList<PassOutputData> outputData;
public NativeList<PassFragmentData> fragmentData;
public NativeList<ResourceHandle> sampledData;
public NativeList<ResourceHandle> createData;
public NativeList<ResourceHandle> destroyData;
public NativeList<PassRandomWriteData> randomAccessResourceData;
// Data per native renderpas
public NativeList<NativePassData> nativePassData;
public NativeList<SubPassDescriptor> 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 TryAddToFragmentList(in TextureAccess access, int listFirstIndex, int numItems, out string errorMessage)
{
errorMessage = null;
#if UNITY_ENABLE_CHECKS
if (access.textureHandle.handle.type != RenderGraphResourceType.Texture)
{
errorMessage = RenderGraph.RenderGraphExceptionMessages.k_NonTextureAsAttachmentError;
return false;
}
#endif
for (var i = listFirstIndex; i < listFirstIndex + numItems; ++i)
{
ref var fragment = ref fragmentData.ElementAt(i);
if (fragment.resource.index == access.textureHandle.handle.index)
{
#if UNITY_ENABLE_CHECKS
if (fragment.resource.version != access.textureHandle.handle.version)
{
//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
errorMessage = RenderGraph.RenderGraphExceptionMessages.k_OneResourceTwoVersionsError;
}
#endif
return false;
}
}
// Validate that we're correctly building up the fragment lists, we can only append to the last list
// not in the middle of the other lists
Debug.Assert(listFirstIndex + numItems == fragmentData.Length);
fragmentData.Add(new PassFragmentData(
access.textureHandle.handle,
access.flags,
access.mipLevel,
access.depthSlice
));
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Name GetFullPassName(int passId) => passNames[passId];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string GetPassName(int passId) => passNames[passId].name;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string GetResourceName(in ResourceHandle h) => resources.resourceNames[h.iType][h.index].name;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string GetResourceVersionedName(in 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 TryAddToRandomAccessResourceList(in 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)
{
if (randomAccessResourceData[i].resource.version != h.version)
{
//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
errorMessage = RenderGraph.RenderGraphExceptionMessages.k_UseTextureRandWriteTwoVersionsError;
}
return false;
}
}
// Validate that we're correctly building up the fragment lists we can only append to the last list
// not int the middle of lists
Debug.Assert(listFirstIndex + numItems == randomAccessResourceData.Length);
randomAccessResourceData.Add(new PassRandomWriteData(h, randomWriteSlotIndex, preserveCounterValue));
return true;
}
// Mark all passes as unvisited this is useful for graph algorithms that do something with the tag
public void TagAllPasses(int value)
{
for (int passId = 0; passId < passData.Length; passId++)
{
passData.ElementAt(passId).tag = value;
}
}
public void CullAllPasses(bool isCulled)
{
for (int passId = 0; passId < passData.Length; passId++)
{
passData.ElementAt(passId).culled = isCulled;
}
}
public TextureUVOrigin GetTextureUVOrigin(in TextureHandle targetHandle)
{
if (targetHandle.handle.IsValid())
{
ref readonly ResourceUnversionedData unversionedData = ref UnversionedResourceData(targetHandle.handle);
return unversionedData.textureUVOrigin == TextureUVOriginSelection.TopLeft ? TextureUVOrigin.TopLeft : TextureUVOrigin.BottomLeft;
}
else
{
return TextureUVOrigin.BottomLeft;
}
}
#region Helpers For Testing Only
// Helper to loop over render graph passes
public ref struct PassIterator
{
readonly CompilerContextData m_Ctx;
int m_Index;
public PassIterator(CompilerContextData ctx)
{
m_Ctx = ctx;
m_Index = -1;
}
public ref readonly PassData Current => ref m_Ctx.passData.ElementAt(m_Index);
public bool MoveNext()
{
return ++m_Index < m_Ctx.passData.Length;
}
public PassIterator GetEnumerator()
{
return this;
}
}
public PassIterator Passes => new PassIterator(this);
// Use for testing only
internal List<PassData> GetPasses()
{
var result = new List<PassData>();
foreach (ref readonly var pass in Passes)
{
result.Add(pass);
}
return result;
}
// Helper to loop over native passes
public ref struct NativePassIterator
{
readonly CompilerContextData m_Ctx;
int m_Index;
public NativePassIterator(CompilerContextData ctx)
{
m_Ctx = ctx;
m_Index = -1;
}
public ref readonly NativePassData Current => ref m_Ctx.nativePassData.ElementAt(m_Index);
public bool MoveNext()
{
while (true)
{
m_Index++;
bool inRange = m_Index < m_Ctx.nativePassData.Length;
if (!inRange || m_Ctx.nativePassData.ElementAt(m_Index).IsValid())
return inRange;
}
}
public NativePassIterator GetEnumerator()
{
return this;
}
}
// Iterate only the active native passes
// the list may contain empty dummy entries after merging
public NativePassIterator NativePasses => new NativePassIterator(this);
// Use for testing only
internal List<NativePassData> GetNativePasses()
{
var result = new List<NativePassData>();
foreach (ref readonly var pass in NativePasses)
{
result.Add(pass);
}
return result;
}
#endregion
bool m_AreNativeListsAllocated = false;
public void Dispose()
{
Cleanup();
GC.SuppressFinalize(this);
}
void Cleanup()
{
resources.Dispose();
if (m_AreNativeListsAllocated)
{
passData.Dispose();
compactedNonCulledRasterPasses.Dispose();
inputData.Dispose();
outputData.Dispose();
fragmentData.Dispose();
sampledData.Dispose();
createData.Dispose();
destroyData.Dispose();
randomAccessResourceData.Dispose();
nativePassData.Dispose();
nativeSubPassData.Dispose();
m_AreNativeListsAllocated = false;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9a36f55a31b6ea349b4423fdae1c5e5b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,141 @@
using System;
using System.Runtime.InteropServices;
using Unity.Collections;
namespace UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler
{
/// <summary>
/// A fixed-size array that can contain up to maximum render target attachment amount of items.
/// </summary>
/// <typeparam name="DataType">The type of data to store in the array.</typeparam>
[StructLayout(LayoutKind.Sequential)]
public struct FixedAttachmentArray<DataType> where DataType : unmanaged
{
/// <summary>
/// Returns an empty array.
/// </summary>
public static readonly FixedAttachmentArray<DataType> Empty = new FixedAttachmentArray<DataType>(0);
/// <summary>
/// The maximum number of elements that can be stored in the array.
/// </summary>
public const int MaxAttachments = 8;
/// This is a fixed size struct that emulates itself as an array
/// similar to how Unity.Math emulates fixed size arrays
private DataType a0, a1, a2, a3, a4, a5, a6, a7;
private int activeAttachments;
/// <summary>
/// Created an new array with the specified number of attachments.
/// </summary>
/// <param name="numAttachments">Number of attachments to consider valid.</param>
/// <exception cref="ArgumentException">Thrown if the amount of elements is less than 0 or more than MaxAttachments</exception>
public FixedAttachmentArray(int numAttachments)
{
#if UNITY_ENABLE_CHECKS
if (numAttachments < 0 || numAttachments > MaxAttachments)
{
throw new ArgumentException($"FixedAttachmentArray - numAttachments must be in range of [0, {MaxAttachments}[");
}
#endif
a0 = a1 = a2 = a3 = a4 = a5 = a6 = a7 = new DataType();
activeAttachments = numAttachments;
}
/// <summary>
/// Intialize the FixedAttachmentArray by copying data from the passed in c# array.
/// </summary>
/// <param name="attachments">The C# array from which to copy the elements.</param>
public FixedAttachmentArray(DataType[] attachments) : this(attachments.Length)
{
for (int i = 0; i < activeAttachments; ++i)
{
this[i] = attachments[i];
}
}
/// <summary>
/// Intialize the FixedAttachmentArray by copying data from the passed in native array.
/// </summary>
/// <param name="attachments">The native array from which to copy the elements.</param>
public FixedAttachmentArray(NativeArray<DataType> attachments) : this(attachments.Length)
{
for (int i = 0; i < activeAttachments; ++i)
{
this[i] = attachments[i];
}
}
/// <summary>
/// Number of attachments in the array alway less or equal than MaxAttachments
/// </summary>
public int size
{
get
{
return activeAttachments;
}
}
/// <summary>
/// Clear the array.
/// </summary>
public void Clear()
{
activeAttachments = 0;
}
/// <summary>
/// Add an element tot the array.
/// </summary>
/// <param name="data">Element to add</param>
/// <returns>Returns the index where the item was added.</returns>
/// <exception cref="IndexOutOfRangeException">If the maximum amount of elements (MaxAttachments) is reached.</exception>
public int Add(in DataType data)
{
#if UNITY_ENABLE_CHECKS
if ((uint)activeAttachments >= MaxAttachments)
throw new IndexOutOfRangeException($"A FixedAttachmentArray can only contain {MaxAttachments} items.");
#endif
int index = activeAttachments;
unsafe
{
fixed (FixedAttachmentArray<DataType>* self = &this)
{
DataType* array = (DataType*)self;
array[index] = data;
}
}
activeAttachments++;
return index;
}
/// <summary>
/// Get the element at the specified index in the array.
/// </summary>
/// <param name="index">Index of the element.</param>
/// <value>The value of the element.</value>
/// <exception cref="IndexOutOfRangeException">If the index is outside the valid range.</exception>
public ref DataType this[int index]
{
get
{
#if UNITY_ENABLE_CHECKS
if ((uint)index >= MaxAttachments)
throw new IndexOutOfRangeException($"FixedAttachmentArray - index must be in range of [0, {MaxAttachments}[");
if ((uint)index >= activeAttachments)
throw new IndexOutOfRangeException($"FixedAttachmentArray - index must be in range of [0, {activeAttachments}[");
#endif
unsafe
{
fixed (FixedAttachmentArray<DataType>* self = &this)
{
DataType* array = (DataType*)self;
return ref array[index];
}
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 05e2d0e421581f148a6d7be934c2e7e9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,411 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler
{
internal partial class NativePassCompiler
{
static RenderGraph.DebugData.PassData.NRPInfo.NativeRenderPassInfo.AttachmentInfo MakeAttachmentInfo(
CompilerContextData ctx,
in NativePassData nativePass,
int attachmentIndex)
{
var attachment = nativePass.attachments[attachmentIndex];
var pointTo = ctx.UnversionedResourceData(attachment.handle);
LoadAudit loadAudit = nativePass.loadAudit[attachmentIndex];
string loadReason = LoadAudit.LoadReasonMessages[(int) loadAudit.reason];
if (loadAudit.passId >= 0)
loadReason = loadReason.Replace("{pass}", $"<b>{ctx.passNames[loadAudit.passId].name}</b>");
StoreAudit storeAudit = nativePass.storeAudit[attachmentIndex];
string storeReason = StoreAudit.StoreReasonMessages[(int) storeAudit.reason];
if (storeAudit.passId >= 0)
storeReason = storeReason.Replace("{pass}", $"<b>{ctx.passNames[storeAudit.passId].name}</b>");
string storeMsaaReason = string.Empty;
if (storeAudit.msaaReason != StoreReason.InvalidReason && storeAudit.msaaReason != StoreReason.NoMSAABuffer)
{
storeMsaaReason = StoreAudit.StoreReasonMessages[(int) storeAudit.msaaReason];
if (storeAudit.msaaPassId >= 0)
storeMsaaReason = storeMsaaReason.Replace("{pass}", $"<b>{ctx.passNames[storeAudit.msaaPassId].name}</b>");
}
return new RenderGraph.DebugData.PassData.NRPInfo.NativeRenderPassInfo.AttachmentInfo
{
resourceName = pointTo.GetName(ctx, attachment.handle),
attachmentIndex = attachmentIndex,
loadReason = loadReason,
storeReason = storeReason,
storeMsaaReason = storeMsaaReason,
attachment = new RenderGraph.DebugData.SerializableNativePassAttachment(attachment)
};
}
internal static string MakePassBreakInfoMessage(CompilerContextData ctx, in NativePassData nativePass)
{
string msg = "";
if (nativePass.breakAudit.breakPass >= 0)
{
msg += $"Failed to merge {ctx.passNames[nativePass.breakAudit.breakPass].name} into this native pass.\n";
}
msg += PassBreakAudit.BreakReasonMessages[(int) nativePass.breakAudit.reason];
return msg;
}
internal static string MakePassMergeMessage(CompilerContextData ctx, in PassData pass, in PassData prevPass, in PassBreakAudit mergeResult)
{
string message = mergeResult.reason == PassBreakReason.Merged ?
"The passes are <b>compatible</b> to be merged.\n\n" :
"The passes are <b>incompatible</b> to be merged.\n\n";
string passName = InjectSpaces(pass.GetName(ctx).name);
string prevPassName = InjectSpaces(prevPass.GetName(ctx).name);
switch (mergeResult.reason)
{
case (PassBreakReason.Merged):
if (pass.nativePassIndex == prevPass.nativePassIndex && pass.mergeState != PassMergeState.None)
message += "Passes are merged.";
else
message += "Passes can be merged but are not recorded consecutively.";
break;
case PassBreakReason.TargetSizeMismatch:
message += "The fragment attachments of the passes have different sizes or sample counts.\n" +
$"- {prevPassName}: {prevPass.fragmentInfoWidth}x{prevPass.fragmentInfoHeight}, {prevPass.fragmentInfoSamples} sample(s).\n" +
$"- {passName}: {pass.fragmentInfoWidth}x{pass.fragmentInfoHeight}, {pass.fragmentInfoSamples} sample(s).";
break;
case PassBreakReason.NextPassReadsTexture:
message += $"{prevPassName} output is sampled by {passName} as a regular texture, the pass needs to break.";
break;
case PassBreakReason.NextPassTargetsTexture:
message += $"{prevPassName} reads a texture that {passName} targets to, the pass needs to break.";
break;
case PassBreakReason.NonRasterPass:
message += $"{prevPassName} is type {prevPass.type}. Only Raster passes can be merged.";
break;
case PassBreakReason.DifferentDepthTextures:
message += $"{prevPassName} uses a different depth buffer than {passName}.";
break;
case PassBreakReason.AttachmentLimitReached:
message += $"Merging the passes would use more than {FixedAttachmentArray<PassFragmentData>.MaxAttachments} attachments.";
break;
case PassBreakReason.SubPassLimitReached:
message += $"Merging the passes would use more than {k_MaxSubpass} native subpasses.";
break;
case PassBreakReason.EndOfGraph:
message += "The pass is the last pass in the graph.";
break;
case PassBreakReason.DifferentShadingRateImages:
message += $"{prevPassName} uses a different shading rate image than {passName}.";
break;
case PassBreakReason.DifferentShadingRateStates:
message += $"{prevPassName} uses different shading rate states than {passName}.";
break;
case PassBreakReason.MultisampledShaderResolveMustBeLastPass:
message += $"{prevPassName} uses multisampled shader resolve and so can't have any more passes merged into it.";
break;
case PassBreakReason.PassMergingDisabled:
message += "The pass merging is disabled.";
break;
case PassBreakReason.BackbufferInMultipleRenderTargetsNotSupported:
message += "Mixing backbuffer and custom render textures is not supported on this platform "
+ "(see SystemInfo.supportsBackbufferInMultipleRenderTargets).";
break;
default:
throw new ArgumentOutOfRangeException();
}
return message;
}
static string InjectSpaces(string camelCaseString)
{
var bld = new StringBuilder();
for (var i = 0; i< camelCaseString.Length; i++)
{
if (char.IsUpper(camelCaseString[i])
&& (i!=0 && char.IsLower(camelCaseString[i-1]) ) )
{
bld.Append(" ");
}
bld.Append(camelCaseString[i]);
}
return bld.ToString();
}
internal void GenerateNativeCompilerDebugData(ref RenderGraph.DebugData debugData)
{
ref var ctx = ref contextData;
// Resolve read/write lists per resource
Dictionary<(RenderGraphResourceType, int), List<int>> resourceReadLists = new Dictionary<(RenderGraphResourceType, int), List<int>>();
Dictionary<(RenderGraphResourceType, int), List<int>> resourceWriteLists = new Dictionary<(RenderGraphResourceType, int), List<int>>();
foreach (var renderGraphPass in graph.m_RenderPasses)
{
for (int type = 0; type < (int)RenderGraphResourceType.Count; ++type)
{
int numResources = ctx.resources.unversionedData[type].Length;
for (int resIndex = 0; resIndex < numResources; ++resIndex)
{
foreach (var read in renderGraphPass.resourceReadLists[type])
{
if (renderGraphPass.implicitReadsList.Contains(read))
continue; // Implicit read - do not display them in RG Viewer
if (read.type == (RenderGraphResourceType) type && read.index == resIndex)
{
var pair = ((RenderGraphResourceType) type, resIndex);
if (!resourceReadLists.ContainsKey(pair))
resourceReadLists[pair] = new List<int>();
resourceReadLists[pair].Add(renderGraphPass.index);
}
}
foreach (var read in renderGraphPass.resourceWriteLists[type])
{
if (read.type == (RenderGraphResourceType) type && read.index == resIndex)
{
var pair = ((RenderGraphResourceType) type, resIndex);
if (!resourceWriteLists.ContainsKey(pair))
resourceWriteLists[pair] = new List<int>();
resourceWriteLists[pair].Add(renderGraphPass.index);
}
}
foreach (var read in renderGraphPass.transientResourceList[type])
{
if (read.type == (RenderGraphResourceType)type && read.index == resIndex)
{
// Transient resources are assumed to be read and write
var pair = ((RenderGraphResourceType)type, resIndex);
if (!resourceReadLists.ContainsKey(pair))
resourceReadLists[pair] = new List<int>();
resourceReadLists[pair].Add(renderGraphPass.index);
if (!resourceWriteLists.ContainsKey(pair))
resourceWriteLists[pair] = new List<int>();
resourceWriteLists[pair].Add(renderGraphPass.index);
}
}
}
}
}
// Create resource debug data
for (int t = 0; t < (int)RenderGraphResourceType.Count; ++t)
{
var numResources = ctx.resources.unversionedData[t].Length;
for (int i = 0; i < numResources; ++i)
{
ref var resourceUnversioned = ref ctx.resources.unversionedData[t].ElementAt(i);
RenderGraph.DebugData.ResourceData debugResource = new RenderGraph.DebugData.ResourceData();
RenderGraphResourceType type = (RenderGraphResourceType) t;
bool isNullResource = i == 0;
if (!isNullResource)
{
string resourceName = ctx.resources.resourceNames[t][i].name;
debugResource.name = !string.IsNullOrEmpty(resourceName) ? resourceName : "(unnamed)";
debugResource.imported = resourceUnversioned.isImported;
}
else
{
// The above functions will throw exceptions when used with the null argument so just use a dummy instead
debugResource.name = "<null>";
debugResource.imported = true;
}
var info = new RenderTargetInfo();
if (type == RenderGraphResourceType.Texture && !isNullResource)
{
var handle = new ResourceHandle(i, type, false);
try
{
graph.m_ResourcesForDebugOnly.GetRenderTargetInfo(handle, out info);
}
catch (Exception) { }
}
debugResource.creationPassIndex = resourceUnversioned.firstUsePassID;
debugResource.releasePassIndex = resourceUnversioned.lastUsePassID;
debugResource.textureData = new RenderGraph.DebugData.TextureResourceData();
debugResource.textureData.width = resourceUnversioned.width;
debugResource.textureData.height = resourceUnversioned.height;
debugResource.textureData.depth = resourceUnversioned.volumeDepth;
debugResource.textureData.samples = resourceUnversioned.msaaSamples;
debugResource.textureData.format = info.format;
debugResource.textureData.bindMS = resourceUnversioned.bindMS;
debugResource.textureData.clearBuffer = resourceUnversioned.clear;
debugResource.memoryless = resourceUnversioned.memoryLess;
debugResource.consumerList = new List<int>();
debugResource.producerList = new List<int>();
if (resourceReadLists.ContainsKey(((RenderGraphResourceType) t, i)))
debugResource.consumerList = resourceReadLists[((RenderGraphResourceType) t, i)];
if (resourceWriteLists.ContainsKey(((RenderGraphResourceType) t, i)))
debugResource.producerList = resourceWriteLists[((RenderGraphResourceType) t, i)];
debugData.resourceLists[t].Add(debugResource);
}
}
// Create pass debug data
for (int passId = 0; passId < ctx.passData.Length; passId++)
{
var graphPass = graph.m_RenderPasses[passId];
ref var passData = ref ctx.passData.ElementAt(passId);
string passName = passData.GetName(ctx).name;
string passDisplayName = InjectSpaces(passName);
RenderGraph.DebugData.PassData debugPass = new RenderGraph.DebugData.PassData();
debugPass.name = passDisplayName;
debugPass.type = passData.type;
debugPass.culled = passData.culled;
debugPass.async = passData.asyncCompute;
debugPass.nativeSubPassIndex = passData.nativeSubPassIndex;
debugPass.generateDebugData = graphPass.generateDebugData;
debugPass.resourceReadLists = new RenderGraph.DebugData.PassData.ResourceIdLists();
debugPass.resourceWriteLists = new RenderGraph.DebugData.PassData.ResourceIdLists();
#if UNITY_ENABLE_CHECKS
debugPass.scriptInfo = graphPass.debugScriptInfo;
#endif
debugPass.syncFromPassIndex = passData.awaitingMyGraphicsFencePassId;
debugPass.syncToPassIndex = passData.waitOnGraphicsFencePassId;
debugPass.nrpInfo = new RenderGraph.DebugData.PassData.NRPInfo();
debugPass.nrpInfo.width = passData.fragmentInfoWidth;
debugPass.nrpInfo.height = passData.fragmentInfoHeight;
debugPass.nrpInfo.volumeDepth = passData.fragmentInfoVolumeDepth;
debugPass.nrpInfo.samples = passData.fragmentInfoSamples;
debugPass.nrpInfo.hasDepth = passData.fragmentInfoHasDepth;
foreach (var setGlobal in graphPass.setGlobalsList)
debugPass.nrpInfo.setGlobals.Add(setGlobal.Item1.handle.index);
for (int type = 0; type < (int)RenderGraphResourceType.Count; ++type)
{
debugPass.resourceReadLists[type] = new List<int>();
debugPass.resourceWriteLists[type] = new List<int>();
foreach (var resRead in graphPass.resourceReadLists[type])
{
if (graphPass.implicitReadsList.Contains(resRead))
continue; // Implicit read - do not display them in RG Viewer
debugPass.resourceReadLists[type].Add(resRead.index);
}
foreach (var resWrite in graphPass.resourceWriteLists[type])
debugPass.resourceWriteLists[type].Add(resWrite.index);
}
foreach (var fragmentInput in passData.FragmentInputs(ctx))
{
Debug.Assert(fragmentInput.resource.type == RenderGraphResourceType.Texture);
debugPass.nrpInfo.textureFBFetchList.Add(fragmentInput.resource.index);
}
debugData.passList.Add(debugPass);
}
// Native pass info
foreach (ref readonly var nativePassData in ctx.NativePasses)
{
List<int> mergedPassIds = new List<int>();
for (int graphPassId = nativePassData.firstGraphPass; graphPassId < nativePassData.lastGraphPass + 1; ++graphPassId)
mergedPassIds.Add(graphPassId);
if (nativePassData.numGraphPasses > 0)
{
var nativePassInfo = new RenderGraph.DebugData.PassData.NRPInfo.NativeRenderPassInfo();
nativePassInfo.passBreakReasoning = MakePassBreakInfoMessage(ctx, in nativePassData);
nativePassInfo.attachmentInfos = new ();
for (int a = 0; a < nativePassData.attachments.size; a++)
nativePassInfo.attachmentInfos.Add(MakeAttachmentInfo(ctx, in nativePassData, a));
nativePassInfo.passCompatibility = new ();
nativePassInfo.mergedPassIds = mergedPassIds;
for (int i = 0; i < mergedPassIds.Count; ++i)
{
var mergedPassId = mergedPassIds[i];
var debugPass = debugData.passList[mergedPassId];
debugPass.nrpInfo.nativePassInfo = nativePassInfo;
debugData.passList[mergedPassId] = debugPass;
}
}
}
// Pass compatibility info
for (int passIndex = 0; passIndex < ctx.passData.Length; passIndex++)
{
ref var pass = ref ctx.passData.ElementAt(passIndex);
var nativePassInfo = debugData.passList[pass.passId].nrpInfo.nativePassInfo;
if (nativePassInfo == null)
continue;
// Input dependencies
foreach (ref readonly var input in pass.Inputs(ctx))
{
ref var inputDataVersioned = ref ctx.VersionedResourceData(input.resource);
if (inputDataVersioned.written)
{
var inputDependencyPass = ctx.passData[inputDataVersioned.writePassId];
PassBreakAudit mergeResult = inputDependencyPass.nativePassIndex >= 0
? NativePassData.CanMerge(ctx, inputDependencyPass.nativePassIndex, pass.passId)
: new PassBreakAudit(PassBreakReason.NonRasterPass, pass.passId);
string mergeMessage = "This pass writes to a resource that is read by the currently selected pass.\n\n"
+ MakePassMergeMessage(ctx, pass, inputDependencyPass, mergeResult);
nativePassInfo.passCompatibility.TryAdd(inputDependencyPass.passId,
new RenderGraph.DebugData.PassData.NRPInfo.NativeRenderPassInfo.PassCompatibilityInfo
{
message = mergeMessage,
isCompatible = mergeResult.reason == PassBreakReason.Merged
});
}
}
// Output dependencies (only relevant if current pass is part of a native pass, and therefore candidate for merging)
if (pass.nativePassIndex >= 0)
{
foreach (ref readonly var output in pass.Outputs(ctx))
{
ref var outputDataUnversioned = ref ctx.UnversionedResourceData(output.resource);
if (outputDataUnversioned.lastUsePassID != pass.passId) // Someone else is using this resource
{
ref var outputDataVersioned = ref ctx.VersionedResourceData(output.resource);
var numReaders = outputDataVersioned.numReaders;
for (var i = 0; i < numReaders; ++i)
{
var depIdx = ctx.resources.IndexReader(output.resource, i);
ref var dep = ref ctx.resources.readerData[output.resource.iType].ElementAt(depIdx);
var outputDependencyPass = ctx.passData[dep.passId];
PassBreakAudit mergeResult = NativePassData.CanMerge(ctx, pass.nativePassIndex,
outputDependencyPass.passId);
string mergeMessage = "This pass reads a resource that is written to by the currently selected pass.\n\n"
+ MakePassMergeMessage(ctx, outputDependencyPass, pass, mergeResult);
nativePassInfo.passCompatibility.TryAdd(outputDependencyPass.passId,
new RenderGraph.DebugData.PassData.NRPInfo.NativeRenderPassInfo.PassCompatibilityInfo
{
message = mergeMessage,
isCompatible = mergeResult.reason == PassBreakReason.Merged
});
}
}
}
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 561c70ed7293cf146a66e647cdf30e62
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,101 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Profiling;
namespace UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler
{
internal partial class NativePassCompiler
{
/// <summary>
/// Marks the initialization of per-compilation context data by allocating pass and resource
/// arrays sized to the pass count. Cost scales with pass count and resource count in the
/// render graph.
/// </summary>
internal static readonly ProfilerMarker k_SetupContextData =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_SetupContextData");
/// <summary>
/// Marks construction of the pass dependency graph from the recorded render graph pass
/// list. Iterates every pass to resolve resource read/write relationships. Cost scales
/// with total pass count and the number of resource attachments for each pass.
/// </summary>
internal static readonly ProfilerMarker k_BuildGraph =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_BuildGraph");
/// <summary>
/// Marks dead-code elimination of render passes. Removes passes whose outputs are never
/// consumed and have no side effects. Cost scales with total pass count and the depth of
/// resource dependency chains.
/// </summary>
internal static readonly ProfilerMarker k_CullNodes =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_CullNodes");
/// <summary>
/// Marks the pass-merging phase that combines compatible raster passes into a single
/// native render pass. Reduces load/store operations on tile-based hardware. Cost
/// scales with pass count and render target compatibility checks.
/// </summary>
internal static readonly ProfilerMarker k_TryMergeNativePasses =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_TryMergeNativePasses");
/// <summary>
/// Marks the forward and backward traversal that computes the first and last use of
/// each resource. Results drive resource lifetime, async-compute fence placement, and
/// memoryless eligibility. Cost scales with pass count and total resource reference count.
/// </summary>
internal static readonly ProfilerMarker k_FindResourceUsageRanges =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_FindResourceUsageRanges");
/// <summary>
/// Marks the backward traversal that propagates texture UV origin (top-left or
/// bottom-left) through the native pass graph. Ensures correct blit and resolve
/// operations on platforms with flipped coordinate spaces. Cost scales with native
/// pass count and attachment count.
/// </summary>
internal static readonly ProfilerMarker k_PropagateTextureUVOrigin =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_PropagateTextureUVOrigin");
/// <summary>
/// Marks the scan that identifies transient resources eligible for memoryless
/// (tile-local) allocation. Only runs on hardware that supports memoryless textures.
/// Cost scales with native pass count and the number of transient attachments.
/// </summary>
internal static readonly ProfilerMarker k_DetectMemorylessResources =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_DetectMemorylessResources");
/// <summary>
/// Marks the per-pass resource initialization step that allocates and clears transient
/// render targets before their first use. Cost depends on the number of resources
/// created per pass and whether a clear blit is required.
/// </summary>
internal static readonly ProfilerMarker k_ExecuteInitializeResources =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_ExecuteInitializeResources");
/// <summary>
/// Marks determination of load and store actions for each attachment in a native render
/// pass. Evaluates clear, load, discard, and store policies per attachment. Cost scales
/// with attachment count and the complexity of merged subpass configurations.
/// </summary>
internal static readonly ProfilerMarker k_PrepareNativePass =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_PrepareNativePass");
/// <summary>
/// Marks emission of the BeginRenderPass command into the command buffer. Configures
/// attachment descriptors, MSAA, dimensions, and load/store actions for each attachment.
/// Cost scales with attachment count and MSAA resolve complexity.
/// </summary>
internal static readonly ProfilerMarker k_ExecuteBeginRenderPassCommand =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_ExecuteBeginRenderpassCommand");
/// <summary>
/// Marks per-pass resource destruction after the last pass that uses each transient
/// resource. Releases render targets, temporary allocations, and pooled objects. Cost
/// scales with the number of resources destroyed per pass.
/// </summary>
internal static readonly ProfilerMarker k_ExecuteDestroyResources =
new ProfilerMarker(ProfilerCategory.Render, "Inl_NRPRGComp_ExecuteDestroyResources");
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7f119af5504869344b06b06ee6f1d011
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d9e07f4b3f2788f4aabcef3bf810e3cc
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5349618d155f8ad44a1aa7cc3ade8fcf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,421 @@
using System;
using System.Runtime.CompilerServices;
using Unity.Collections;
using UnityEngine.Rendering;
using UnityEngine.Experimental.Rendering;
namespace UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler
{
// Data per usage of a resource(version)
internal readonly struct ResourceReaderData
{
public readonly int passId; // Pass using this
public readonly int inputSlot; // Nth input of the pass using this resource
public ResourceReaderData(int _passId, int _inputSlot)
{
passId = _passId;
inputSlot = _inputSlot;
}
}
// Part of the data that remains the same for all versions of the resource
// We cache a lot of data here as the compiler accesses this in many places and going through
// RenderGraphResourceRegistry was identified as slow in the profiler
internal struct ResourceUnversionedData
{
public int versionedDataOffset; // Where this resource's versioned data starts in the packed array
public int versionedDataCount; // Number of versions this resource actually has
public int readerDataOffset; // Where this resource's reader data starts in the packed array
public int maxReadersPerVersion; // Max readers across all versions of this resource
public int lastUsePassID; // Index of last used pass. The resource (if not imported) is destroyed after this pass.
public int lastWritePassID; // The last pass writing it. After this other passes may still read the resource
public int firstUsePassID; // First pass using the resource this may be reading or writing. If not imported the resource is allocated just before this pass.
public int latestVersionNumber; // Mostly readonly, can be decremented only if all passes using the last version are culled
public readonly bool isImported; // Imported graph resource
public bool memoryLess; // Never create the texture on GPU if it is allocated/freed within a renderpass
public int lastGraphicsUsePassID; // Last non culled pass using this resource on the graphics queue, -1 if none
public int lastAsyncComputeUsePassID; // Last non culled pass using this resource on the async compute queue, -1 if none
public int tag;
// True when at least one non-culled async compute pass touches this resource, whether or not graphics passes
// use it as well. These are pooled separately from resources only ever used on the graphics queue.
// See RenderGraphResource.CreatePooledGraphicsResource().
public readonly bool usedByAsyncComputePass => lastAsyncComputeUsePassID >= 0;
public readonly int width;
public readonly int height;
public readonly int volumeDepth;
public readonly int msaaSamples;
public readonly GraphicsFormat graphicsFormat;
public readonly bool clear; // graph.m_Resources.GetTextureResourceDesc(fragment.resource).clearBuffer;
public readonly bool discard; // graph.m_Resources.GetTextureResourceDesc(fragment.resource).discardBuffer;
public readonly bool bindMS;
public readonly bool isBackBuffer;
public TextureUVOriginSelection textureUVOrigin;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public string GetName(CompilerContextData ctx, in ResourceHandle h) => ctx.GetResourceName(h);
public ResourceUnversionedData(TextureResource rll, ref RenderTargetInfo info, ref TextureDesc desc, bool isResBackBuffer)
{
isImported = rll.imported;
tag = 0;
firstUsePassID = -1;
lastUsePassID = -1;
lastWritePassID = -1;
memoryLess = false;
lastGraphicsUsePassID = -1;
lastAsyncComputeUsePassID = -1;
width = info.width;
height = info.height;
volumeDepth = info.volumeDepth;
msaaSamples = info.msaaSamples;
latestVersionNumber = (int)rll.writeCount;
clear = desc.clearBuffer;
discard = desc.discardBuffer;
bindMS = info.bindMS;
isBackBuffer = isResBackBuffer;
textureUVOrigin = rll.textureUVOrigin;
graphicsFormat = desc.format;
versionedDataOffset = 0;
versionedDataCount = 0;
readerDataOffset = 0;
maxReadersPerVersion = 0;
}
public ResourceUnversionedData(IRenderGraphResource rll, ref BufferDesc _, bool isResBackBuffer)
{
// We don't do anything with the BufferDesc for now. The compiler doesn't really need the details of the buffer like it does with textures
// since for textures it needs the details to merge passes etc. Which is not relevant for buffers.
isImported = rll.imported;
tag = 0;
firstUsePassID = -1;
lastUsePassID = -1;
lastWritePassID = -1;
memoryLess = false;
lastGraphicsUsePassID = -1;
lastAsyncComputeUsePassID = -1;
width = -1;
height = -1;
volumeDepth = -1;
msaaSamples = -1;
latestVersionNumber = (int)rll.writeCount;
clear = false;
discard = false;
bindMS = false;
isBackBuffer = isResBackBuffer;
textureUVOrigin = TextureUVOriginSelection.Unknown;
graphicsFormat = GraphicsFormat.None;
versionedDataOffset = 0;
versionedDataCount = 0;
readerDataOffset = 0;
maxReadersPerVersion = 0;
}
public ResourceUnversionedData(IRenderGraphResource rll, ref RayTracingAccelerationStructureDesc _, bool isResBackBuffer)
{
// We don't do anything with the RayTracingAccelerationStructureDesc for now. The compiler doesn't really need the details of the acceleration structures like it does with textures
// since for textures it needs the details to merge passes etc. Which is not relevant for acceleration structures.
isImported = rll.imported;
tag = 0;
firstUsePassID = -1;
lastUsePassID = -1;
lastWritePassID = -1;
memoryLess = false;
lastGraphicsUsePassID = -1;
lastAsyncComputeUsePassID = -1;
width = -1;
height = -1;
volumeDepth = -1;
msaaSamples = -1;
latestVersionNumber = (int)rll.writeCount;
clear = false;
discard = false;
bindMS = false;
isBackBuffer = isResBackBuffer;
textureUVOrigin = TextureUVOriginSelection.Unknown;
graphicsFormat = GraphicsFormat.None;
versionedDataOffset = 0;
versionedDataCount = 0;
readerDataOffset = 0;
maxReadersPerVersion = 0;
}
public void InitializeNullResource()
{
firstUsePassID = -1;
lastUsePassID = -1;
lastWritePassID = -1;
lastGraphicsUsePassID = -1;
lastAsyncComputeUsePassID = -1;
textureUVOrigin = TextureUVOriginSelection.Unknown;
}
}
// Data per resource(version)
internal struct ResourceVersionedData
{
public bool written; // This version of the resource is written by a pass (external resources may never be written by the graph for example)
public int writePassId; // Index in the pass array of the pass writing this specific version. If any, there is always a single index as the version differs when a resource is written several times.
public int numReaders; // Number of other passes reading this version
// Register the pass writing this resource version. A version can only be written by a single pass as every write should introduce a new distinct version.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetWritingPass(CompilerContextData ctx, in ResourceHandle h, int passId)
{
#if UNITY_ENABLE_CHECKS
if (written)
{
string passName = ctx.GetPassName(passId);
string resourceName = ctx.GetResourceName(h);
throw new Exception($"Only one pass can write to the same resource. Pass {passName} is trying to write {resourceName} a second time.");
}
#endif
writePassId = passId;
written = true;
}
// Add an extra reader for this resource version. Resource versions can be read many times
// The same pass can even read a resource twice (if it is passed to two separate input slots)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RegisterReadingPass(CompilerContextData ctx, in ResourceHandle h, int passId, int index)
{
#if UNITY_ENABLE_CHECKS
ref var unversioned = ref ctx.resources.unversionedData[h.iType].ElementAt(h.index);
if (numReaders >= unversioned.maxReadersPerVersion)
{
string passName = ctx.GetPassName(passId);
string resourceName = ctx.GetResourceName(h);
throw new Exception($"Maximum '{unversioned.maxReadersPerVersion}' passes can use a single graph output as input. Pass {passName} is trying to read {resourceName}.");
}
#endif
ctx.resources.readerData[h.iType][ctx.resources.IndexReader(h, numReaders)] = new ResourceReaderData(passId, index);
numReaders++;
}
// Remove all the reads for the given pass of this resource version
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void RemoveReadingPass(CompilerContextData ctx, in ResourceHandle h, int passId)
{
for (int r = 0; r < numReaders;)
{
ref var reader = ref ctx.resources.readerData[h.iType].ElementAt(ctx.resources.IndexReader(h, r));
if (reader.passId == passId)
{
// It should be removed, switch with the end of the list if we're not already at the end of it
if (r < numReaders - 1)
{
reader = ctx.resources.readerData[h.iType][ctx.resources.IndexReader(h, numReaders - 1)];
}
numReaders--;
continue; // Do not increment counter so we check the swapped element as well
}
r++;
}
}
}
// This class allows quick lookups from ResourceHandle -> ResourceUnversionedData/ResourceVersionData/ResourceReaderData
// Uses resource-level sparse allocation: each resource allocates only the versions it needs.
// Reader allocation uses total read count as conservative upper bound (not true per-version sparse).
// Allocation metadata is inlined in ResourceUnversionedData for optimal cache performance.
internal class ResourcesData
{
public NativeList<ResourceUnversionedData>[] unversionedData; // Per-resource data (one per resource, includes allocation metadata)
public NativeList<ResourceVersionedData>[] versionedData; // Packed versioned data (sparse)
public NativeList<ResourceReaderData>[] readerData; // Partially packed reader data (semi-sparse)
public DynamicArray<Name>[] resourceNames;
public ResourcesData()
{
unversionedData = new NativeList<ResourceUnversionedData>[(int)RenderGraphResourceType.Count];
versionedData = new NativeList<ResourceVersionedData>[(int)RenderGraphResourceType.Count];
readerData = new NativeList<ResourceReaderData>[(int)RenderGraphResourceType.Count];
resourceNames = new DynamicArray<Name>[(int)RenderGraphResourceType.Count];
for (int t = 0; t < (int)RenderGraphResourceType.Count; t++)
resourceNames[t] = new DynamicArray<Name>(0); // T in NativeList<T> cannot contain managed types, so the names are stored separately
}
public void Clear()
{
for (int t = 0; t < (int)RenderGraphResourceType.Count; t++)
{
if (unversionedData[t].IsCreated)
unversionedData[t].Clear();
if (versionedData[t].IsCreated)
versionedData[t].Clear();
if (readerData[t].IsCreated)
readerData[t].Clear();
resourceNames[t].Clear();
}
}
void AllocateAndResizeNativeListIfNeeded<T>(ref NativeList<T> nativeList, int size, NativeArrayOptions options) where T : unmanaged
{
// Allocate the first time or if Dispose() has been called through RenderGraph.Cleanup()
if (!nativeList.IsCreated)
nativeList = new NativeList<T>(size, AllocatorManager.Persistent);
// Resize the list (it will allocate if necessary)
nativeList.Resize(size, options);
}
public void Initialize(RenderGraphResourceRegistry resources)
{
for (int t = 0; t < (int)RenderGraphResourceType.Count; t++)
{
RenderGraphResourceType resourceType = (RenderGraphResourceType) t;
var numResources = resources.GetResourceCount(resourceType);
// We don't clear the list as we reinitialize it right after
AllocateAndResizeNativeListIfNeeded(ref unversionedData[t], numResources, NativeArrayOptions.UninitializedMemory);
resourceNames[t].Resize(numResources, true);
if (numResources > 0) // Null Resource
{
var nullResource = new ResourceUnversionedData();
nullResource.InitializeNullResource();
unversionedData[t][0] = nullResource;
resourceNames[t][0] = new Name("");
}
// Compute allocation sizes and populate unversionedData in a single pass
int totalVersionedDataCount = 0;
int totalReaderDataCount = 0;
// Null resource at index 0 already initialized to 0 in constructors
// Process all resources in one pass for better cache locality
for (int r = 1; r < numResources; r++)
{
var h = new ResourceHandle(r, resourceType, false);
var rll = resources.GetResourceLowLevel(h);
resourceNames[t][r] = new Name(rll.GetName());
// Initialize unversionedData based on resource type
switch (t)
{
case (int)RenderGraphResourceType.Texture:
{
var tex = rll as TextureResource;
resources.GetRenderTargetInfo(h, out var info);
ref var desc = ref tex.desc;
bool isBackBuffer = resources.IsRenderGraphResourceBackBuffer(h);
unversionedData[t][r] = new ResourceUnversionedData(tex, ref info, ref desc, isBackBuffer);
break;
}
case (int)RenderGraphResourceType.Buffer:
{
ref var desc = ref (rll as BufferResource).desc;
bool isResourceShared = resources.IsRenderGraphResourceShared(h);
bool isBackBuffer = resources.IsRenderGraphResourceBackBuffer(h);
unversionedData[t][r] = new ResourceUnversionedData(rll, ref desc, isBackBuffer);
break;
}
case (int)RenderGraphResourceType.AccelerationStructure:
{
ref var desc = ref (rll as RayTracingAccelerationStructureResource).desc;
bool isResourceShared = resources.IsRenderGraphResourceShared(h);
bool isBackBuffer = resources.IsRenderGraphResourceBackBuffer(h);
unversionedData[t][r] = new ResourceUnversionedData(rll, ref desc, isBackBuffer);
break;
}
default:
throw new Exception("Unsupported resource type: " + t);
}
// Compute allocation metadata for this resource
// +1 for versions: v0 exists even without writes
int numVersions = (int)rll.writeCount + 1;
// +1 for readers: transient resources don't call IncrementReadCount, but BuildGraph adds 1 implicit read
// Note: rll.readCount is total across all versions (not per-version), so this is a conservative upper bound
int numReaders = (int)rll.readCount + 1;
// Populate allocation metadata
ref var unversioned = ref unversionedData[t].ElementAt(r);
unversioned.versionedDataOffset = totalVersionedDataCount;
unversioned.versionedDataCount = numVersions;
unversioned.readerDataOffset = totalReaderDataCount;
unversioned.maxReadersPerVersion = numReaders;
totalVersionedDataCount += numVersions;
totalReaderDataCount += numVersions * numReaders;
}
AllocateAndResizeNativeListIfNeeded(ref versionedData[t], totalVersionedDataCount, NativeArrayOptions.ClearMemory);
AllocateAndResizeNativeListIfNeeded(ref readerData[t], totalReaderDataCount, NativeArrayOptions.ClearMemory);
}
}
// Flatten array index using sparse allocation (uses inlined allocation metadata)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int Index(in ResourceHandle h)
{
ref var unversioned = ref unversionedData[h.iType].ElementAt(h.index);
#if UNITY_EDITOR // Hot path
if (h.version < 0 || h.version >= unversioned.versionedDataCount)
throw new Exception("Invalid version: " + h.version);
#endif
return unversioned.versionedDataOffset + h.version;
}
// Flatten array index for readers using sparse allocation (uses inlined allocation metadata)
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int IndexReader(in ResourceHandle h, int readerID)
{
ref var unversioned = ref unversionedData[h.iType].ElementAt(h.index);
#if UNITY_EDITOR // Hot path
if (h.version < 0 || h.version >= unversioned.versionedDataCount)
throw new Exception("Invalid version");
if (readerID < 0 || readerID >= unversioned.maxReadersPerVersion)
throw new Exception("Invalid reader");
#endif
return unversioned.readerDataOffset + h.version * unversioned.maxReadersPerVersion + readerID;
}
// Lookup data for a given handle
public ref ResourceVersionedData this[ResourceHandle h] => ref versionedData[h.iType].ElementAt(Index(h));
public void Dispose()
{
for (int t = 0; t < (int)RenderGraphResourceType.Count; t++)
{
if (versionedData[t].IsCreated)
versionedData[t].Dispose();
if (unversionedData[t].IsCreated)
unversionedData[t].Dispose();
if (readerData[t].IsCreated)
readerData[t].Dispose();
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 9698efb2816f96349ae46ee06003995b
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0543e23b6a0f25741b67b1bee0292e70
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,81 @@
using System;
using System.Reflection;
using UnityEngine.Rendering.RenderGraphModule;
using NameAndTooltip = UnityEngine.Rendering.DebugUI.Widget.NameAndTooltip;
namespace UnityEngine.Rendering
{
/// <summary>
/// Render Graph-related Rendering Debugger settings.
/// </summary>
[PipelineHelpURL("UniversalRenderPipelineAsset", pageName: "urp/features/rendering-debugger-reference", pageHash: "render-graph")]
[PipelineHelpURL("HDRenderPipelineAsset", pageName: "rendering-debugger-window-reference", pageHash: "render-graph")]
class DebugDisplaySettingsRenderGraph : IDebugDisplaySettingsData
{
public DebugDisplaySettingsRenderGraph()
{
foreach (var graph in RenderGraph.GetRegisteredRenderGraphs())
{
graph.debugParams.Reset();
}
}
[DisplayInfo(name = "Rendering", order = 10)]
private class SettingsPanel : DebugDisplaySettingsPanel
{
public SettingsPanel(DebugDisplaySettingsRenderGraph _)
{
DocumentationUtils.TryGetHelpURL(typeof(DebugDisplaySettingsRenderGraph), out var documentationUrl);
var foldout = new DebugUI.Foldout()
{
displayName = "Render Graph",
documentationUrl = documentationUrl
};
AddWidget(foldout);
bool usingRenderGraph = false;
foreach (var graph in RenderGraph.GetRegisteredRenderGraphs())
{
usingRenderGraph = true;
var list = graph.GetWidgetList();
foreach (var item in list)
foldout.children.Add(item);
}
if (!usingRenderGraph)
{
foldout.children.Add(new DebugUI.MessageBox()
{
displayName =
"Warning: The current render pipeline does not have Render Graphs Registered",
style = DebugUI.MessageBox.Style.Warning
});
}
}
}
#region IDebugDisplaySettingsQuery
/// <inheritdoc/>
IDebugDisplaySettingsPanelDisposable IDebugDisplaySettingsData.CreatePanel()
{
return new SettingsPanel(this);
}
public bool AreAnySettingsActive
{
get
{
foreach (var (graph, _) in RenderGraph.GetRegisteredExecutions())
{
if (graph.areAnySettingsActive)
return true;
}
return false;
}
}
#endregion
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b793a3641e4ad674fa3beb1f2d88751a
@@ -0,0 +1,186 @@
using System;
using System.IO;
using UnityEngine.Networking.PlayerConnection;
#if UNITY_EDITOR
using UnityEditor.Networking.PlayerConnection;
#endif
using static UnityEngine.Rendering.RenderGraphModule.RenderGraph;
namespace UnityEngine.Rendering.RenderGraphModule
{
class DebugMessageHandler : ScriptableObject
{
// Render Graph Viewer Debug message protocol version.
// This number is sent from the player with the MessageType.DebugData message. The editor UI is only compatible
// with an equal version - if the version is not the same, a "not supported" message is displayed in the UI.
// As DebugData is currently serialized as json, it's quite resilient to adding/removing fields, so it's not
// always necessary to bump this version in this case. However, be aware that this leads to a situation where
// players built without this new code will not send these values. If you are unsure, bump the version.
// If you modify the streams in SerializeMessage/DeserializeMessage, you should definitely bump the version.
// ------------------------
// Version history:
// 1 - Initial version
// 2 - Changed executionId from 32bit InstanceID to 64bit EntityId
internal const int k_Version = 2;
// These were generated using GUID.NewGuid and hard-coded
static readonly Guid s_EditorToPlayerGuid = new Guid("df519969-f421-4397-b2a1-1740abc989a0");
static readonly Guid s_PlayerToEditorGuid = new Guid("98d0787d-3917-4c48-8393-e313498046e6");
public enum MessageType : byte
{
Activate = 0,
DebugData = 1,
AnalyticsData = 2
}
public abstract class IPayload
{
public int version;
public bool isCompatible => version == k_Version;
}
public class DebugDataPayload : IPayload
{
public string graphName;
public EntityId executionId;
public DebugData debugData;
}
public class AnalyticsPayload : IPayload
{
public GraphicsDeviceType graphicsDeviceType;
public DeviceType deviceType;
public string deviceModel;
public string gpuVendor;
public string gpuName;
public AnalyticsPayload()
{
deviceModel = SystemInfo.deviceModel;
deviceType = SystemInfo.deviceType;
graphicsDeviceType = SystemInfo.graphicsDeviceType;
gpuVendor = SystemInfo.graphicsDeviceVendor;
gpuName = SystemInfo.graphicsDeviceName;
}
}
Action<MessageType, IPayload> m_UserCallback;
// Note: The callback we register to must be a method of a class inheriting from UnityEngine.Object for the
// persistent callback registration to work.
void InternalCallback(MessageEventArgs msg)
{
var (messageType, payload) = DeserializeMessage(msg.data);
m_UserCallback.Invoke(messageType, payload);
}
public void Register(Action<MessageType, IPayload> callback)
{
m_UserCallback = callback;
#if UNITY_EDITOR
EditorConnection.instance.Register(s_PlayerToEditorGuid, InternalCallback);
#else
PlayerConnection.instance.Register(s_EditorToPlayerGuid, InternalCallback);
#endif
}
public void UnregisterAll()
{
#if UNITY_EDITOR
EditorConnection.instance.Unregister(s_PlayerToEditorGuid, InternalCallback);
#else
PlayerConnection.instance.Unregister(s_EditorToPlayerGuid, InternalCallback);
#endif
}
public void Send(MessageType messageType, IPayload payload = null)
{
#if UNITY_EDITOR
EditorConnection.instance.Send(s_EditorToPlayerGuid, SerializeMessage(messageType, payload));
#else
PlayerConnection.instance.Send(s_PlayerToEditorGuid, SerializeMessage(messageType, payload));
#endif
}
internal static byte[] SerializeMessage(MessageType type, IPayload payload = null)
{
using var memoryStream = new MemoryStream();
using var writer = new BinaryWriter(memoryStream);
writer.Write((byte)type);
if (type == MessageType.DebugData)
{
writer.Write(k_Version);
if (payload is not DebugDataPayload debugDataPayload)
throw new InvalidOperationException("No valid payload provided");
writer.Write(debugDataPayload.graphName);
writer.Write(EntityId.ToULong(debugDataPayload.executionId));
writer.Write(DebugDataSerialization.ToJson(debugDataPayload.debugData));
}
else if (type == MessageType.AnalyticsData)
{
writer.Write(k_Version);
if (payload is not AnalyticsPayload analyticsPayload)
throw new InvalidOperationException("No valid payload provided");
writer.Write((int)analyticsPayload.graphicsDeviceType);
writer.Write((int)analyticsPayload.deviceType);
writer.Write(analyticsPayload.deviceModel);
writer.Write(analyticsPayload.gpuVendor);
writer.Write(analyticsPayload.gpuName);
}
return memoryStream.ToArray();
}
internal static unsafe (MessageType, IPayload) DeserializeMessage(byte[] data)
{
using var memoryStream = new MemoryStream(data);
using var reader = new BinaryReader(memoryStream);
var type = (MessageType)reader.ReadByte();
if (type == MessageType.DebugData)
{
var payload = new DebugDataPayload();
payload.version = reader.ReadInt32();
if (!payload.isCompatible)
{
Debug.LogWarning($"Render Graph Viewer message version mismatch (expected {k_Version}, received {payload.version})");
return (type, payload);
}
payload.graphName = reader.ReadString();
ulong rawEntityId = reader.ReadUInt64();
payload.executionId = *((EntityId*)(&rawEntityId));
payload.debugData = DebugDataSerialization.FromJson(reader.ReadString());
return (type, payload);
}
else if (type == MessageType.AnalyticsData)
{
var payload = new AnalyticsPayload();
payload.version = reader.ReadInt32();
if (!payload.isCompatible)
{
return (type, payload);
}
payload.graphicsDeviceType = (GraphicsDeviceType)reader.ReadInt32();
payload.deviceType = (DeviceType)reader.ReadInt32();
payload.deviceModel = reader.ReadString();
payload.gpuVendor = reader.ReadString();
payload.gpuName = reader.ReadString();
return (type, payload);
}
return (type, null);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2969696e79844f56ac7065ad3ecfd221
timeCreated: 1742299150
@@ -0,0 +1,330 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler;
namespace UnityEngine.Rendering.RenderGraphModule
{
public partial class RenderGraph
{
// Convenience class that wraps execution id and name for display purposes
internal class DebugExecutionItem
{
public EntityId id { get; }
public string name { get; }
public DebugExecutionItem(EntityId id, string name)
{
this.id = id;
this.name = name;
}
}
/// <summary>
/// Debug data interface shared by HDRP RG Compiler and NRP RG Compiler.
/// Some data is optional, depending on the value of isNRPCompiler.
/// </summary>
[Serializable]
internal class DebugData
{
public DebugData(string executionName)
{
this.executionName = executionName;
}
public string executionName;
// Set to true when data has been set
public bool valid = false;
// Capture metadata that is not populated by default
public string captureSourceString;
public string captureTimestamp;
// Compilation hash of the render graph that produced this DebugData.
public int graphHash;
[Serializable]
public class ResourceLists<T>
{
[SerializeField] private List<T> m_Textures = new();
[SerializeField] private List<T> m_Buffers = new();
[SerializeField] private List<T> m_AccelerationStructures = new();
// Indexer to access the lists by index
public List<T> this[int index]
{
get
{
return index switch
{
(int)RenderGraphResourceType.Texture => m_Textures,
(int)RenderGraphResourceType.Buffer => m_Buffers,
(int)RenderGraphResourceType.AccelerationStructure => m_AccelerationStructures,
_ => throw new ArgumentOutOfRangeException(nameof(index))
};
}
set
{
switch (index)
{
case (int)RenderGraphResourceType.Texture:
m_Textures = value ?? new List<T>();
break;
case (int)RenderGraphResourceType.Buffer:
m_Buffers = value ?? new List<T>();
break;
case (int)RenderGraphResourceType.AccelerationStructure:
m_AccelerationStructures = value ?? new List<T>();
break;
default:
throw new ArgumentOutOfRangeException(nameof(index));
}
}
}
public void Clear()
{
for (int i = 0; i < (int)RenderGraphResourceType.Count; ++i)
{
if (this[i] == null)
this[i] = new List<T>();
else
this[i].Clear();
}
}
}
// Debug data for passes.
public List<PassData> passList = new List<PassData>();
// Debug data for resources.
[Serializable]
public class ResourceDataLists : ResourceLists<ResourceData>
{ }
public ResourceDataLists resourceLists = new();
// NOTE: Cannot use NativePassAttachment for DebugData directly because readonly fields are not serialized.
// This class duplicates the relevant contents.
[Serializable]
public class SerializableNativePassAttachment
{
public RenderBufferLoadAction loadAction;
public RenderBufferStoreAction storeAction;
public bool memoryless;
public int mipLevel;
public int depthSlice;
public SerializableNativePassAttachment(NativePassAttachment att)
{
loadAction = att.loadAction;
storeAction = att.storeAction;
memoryless = att.memoryless;
mipLevel = att.mipLevel;
depthSlice = att.depthSlice;
}
}
[Serializable]
[DebuggerDisplay("PassDebug: {name}")]
public struct PassData
{
// Render pass name.
public string name;
// Render graph pass type.
public RenderGraphPassType type;
[Serializable]
public class ResourceIdLists : ResourceLists<int>
{}
// List of ResourceHandle.index's for each resource type read by this pass.
public ResourceIdLists resourceReadLists;
// List of ResourceHandle.index's for each resource type written by this pass.
public ResourceIdLists resourceWriteLists;
// Whether the pass was culled.
public bool culled;
// Whether the pass is an async compute pass.
public bool async;
// Native subpass index.
public int nativeSubPassIndex;
// Index of the pass that needs to be waited for.
public int syncToPassIndex;
// Smaller pass index that waits for this pass.
public int syncFromPassIndex;
// We have this member instead of removing the pass altogether because we need the full list of passes in
// order to be able to remap them correctly when we remove them from display in the viewer.
public bool generateDebugData;
[Serializable]
public class NRPInfo
{
[Serializable]
public class NativeRenderPassInfo
{
[Serializable]
public class AttachmentInfo
{
public string resourceName;
public string loadReason;
public string storeReason;
public string storeMsaaReason;
public int attachmentIndex;
public SerializableNativePassAttachment attachment;
}
[Serializable]
public struct PassCompatibilityInfo
{
public string message;
public bool isCompatible;
}
public string passBreakReasoning;
public List<AttachmentInfo> attachmentInfos;
public SerializedDictionary<int, PassCompatibilityInfo> passCompatibility;
public List<int> mergedPassIds;
}
// If this pass is part of a Native Render Pass, this is available, null otherwise.
[SerializeReference]
public NativeRenderPassInfo nativePassInfo;
// List of ResourceHandle.index's for each texture resource that is accessed using framebuffer fetch.
public List<int> textureFBFetchList = new();
// List of ResourceHandle.index's for each texture resource that this pass called PostSetGlobalTexture() for.
public List<int> setGlobals = new();
// Fragment info
public int width;
public int height;
public int volumeDepth;
public int samples;
public bool hasDepth;
}
// Only available when isNRPCompiler = true, null otherwise.
[SerializeReference]
public NRPInfo nrpInfo;
// File path and line number where the render pass is defined.
public PassScriptInfo scriptInfo;
}
[Serializable]
public class BufferResourceData
{
// Number of elements in buffer.
public int count;
// Size of one element in the buffer.
public int stride;
// Buffer usage type.
public GraphicsBuffer.Target target;
// Buffer usage flags.
public GraphicsBuffer.UsageFlags usage;
}
[Serializable]
public class TextureResourceData
{
// Texture width & height.
public int width;
public int height;
// Texture depth (volume texture).
public int depth;
// Whether the texture is bound with multi sampling.
public bool bindMS;
// Number of texture MSAA samples.
public int samples;
// Render texture graphics format.
public GraphicsFormat format;
// Whether texture is cleared on first use.
public bool clearBuffer;
}
[Serializable]
[DebuggerDisplay("ResourceDebug: {name} [{creationPassIndex}:{releasePassIndex}]")]
public struct ResourceData
{
// Resource name.
public string name;
// Whether the resource is imported outside of render graph.
public bool imported;
// Pass that creates the resource (for imported resources, the first pass that uses the resource).
public int creationPassIndex;
// Pass that releases the resource (for imported resources, the last pass that uses the resource).
public int releasePassIndex;
// List of passes that read the resource.
public List<int> consumerList;
// List of passes that write the resource.
public List<int> producerList;
// Whether the resource is memoryless (i.e resources that are created/destroyed within the same native render pass).
// Available if isNRPCompiler = true.
public bool memoryless;
// Texture-specific resource data.
[SerializeReference]
public TextureResourceData textureData;
// Buffer-specific resource data.
[SerializeReference]
public BufferResourceData bufferData;
}
public void Clear()
{
passList.Clear();
resourceLists.Clear();
valid = false;
}
// Pass script metadata.
[Serializable]
public struct PassScriptInfo
{
public string filePath;
public int line;
}
}
[Conditional("UNITY_ENABLE_CHECKS")]
void AddPassDebugMetadata(RenderGraphPass renderPass, string file, int line)
{
#if UNITY_ENABLE_CHECKS
// Does nothing unless debug session is active.
if (!RenderGraphDebugSession.hasActiveDebugSession)
return;
renderPass.debugScriptInfo = new DebugData.PassScriptInfo { filePath = file, line = line };
#endif
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7cc32b82bcf345c8a7de92821f51dc2d
timeCreated: 1695038102
@@ -0,0 +1,18 @@
namespace UnityEngine.Rendering.RenderGraphModule
{
public partial class RenderGraph
{
internal static class DebugDataSerialization
{
public static string ToJson(DebugData debugData)
{
return debugData != null ? JsonUtility.ToJson(debugData, prettyPrint: false) : string.Empty;
}
public static DebugData FromJson(string json)
{
return !string.IsNullOrEmpty(json) ? JsonUtility.FromJson<DebugData>(json) : null;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2b3b8db61c6ec144a8dd7537477d8404
@@ -0,0 +1,97 @@
using System.Collections.Generic;
using NameAndTooltip = UnityEngine.Rendering.DebugUI.Widget.NameAndTooltip;
namespace UnityEngine.Rendering.RenderGraphModule
{
class RenderGraphDebugParams : IDebugDisplaySettingsQuery
{
DebugUI.Widget[] m_DebugItems;
DebugUI.Panel m_DebugPanel;
public bool clearRenderTargetsAtCreation;
public bool clearRenderTargetsAtRelease;
public bool disablePassCulling;
public bool disablePassMerging;
internal void Reset()
{
clearRenderTargetsAtCreation = false;
clearRenderTargetsAtRelease = false;
disablePassCulling = false;
disablePassMerging = false;
}
private static class Strings
{
public static readonly NameAndTooltip ClearRenderTargetsAtCreation = new() { name = "Clear Render Targets At Creation", tooltip = "Enable to clear all render textures before any rendergraph passes to check if some clears are missing." };
public static readonly NameAndTooltip ClearRenderTargetsAtFree = new() { name = "Clear Render Targets When Freed", tooltip = "Enable to clear all render textures when textures are freed by the graph to detect use after free of textures." };
public static readonly NameAndTooltip DisablePassCulling = new() { name = "Disable Pass Culling", tooltip = "Enable to temporarily disable culling to assess if a pass is culled." };
public static readonly NameAndTooltip DisablePassMerging = new() { name = "Disable Pass Merging", tooltip = "Enable to temporarily disable pass merging to diagnose issues or analyze performance." };
}
internal List<DebugUI.Widget> GetWidgetList()
{
var list = new List<DebugUI.Widget>
{
new DebugUI.BoolField
{
nameAndTooltip = Strings.ClearRenderTargetsAtCreation,
getter = () => clearRenderTargetsAtCreation,
setter = value => clearRenderTargetsAtCreation = value
},
new DebugUI.BoolField
{
nameAndTooltip = Strings.ClearRenderTargetsAtFree,
getter = () => clearRenderTargetsAtRelease,
setter = value => clearRenderTargetsAtRelease = value
},
// We cannot expose this option as it will change the active render target and the debug menu won't know where to render itself anymore.
// list.Add(new DebugUI.BoolField { displayName = "Clear Render Targets at release", getter = () => clearRenderTargetsAtRelease, setter = value => clearRenderTargetsAtRelease = value });
new DebugUI.BoolField
{
nameAndTooltip = Strings.DisablePassCulling,
getter = () => disablePassCulling,
setter = value => disablePassCulling = value
},
new DebugUI.BoolField
{
nameAndTooltip = Strings.DisablePassMerging,
getter = () => disablePassMerging,
setter = value => disablePassMerging = value,
}
};
return list;
}
public void RegisterDebug(string name, DebugUI.Panel debugPanel = null)
{
var list = GetWidgetList();
m_DebugItems = list.ToArray();
m_DebugPanel = debugPanel ?? DebugManager.instance.GetPanel(name.Length == 0 ? "Rendering" : name, true);
var foldout = new DebugUI.Foldout() { displayName = name, };
foldout.children.Add(m_DebugItems);
m_DebugPanel.children.Add(foldout);
}
public void UnRegisterDebug(string name)
{
//DebugManager.instance.RemovePanel(name.Length == 0 ? "Render Graph" : name);
if ( m_DebugPanel != null ) m_DebugPanel.children.Remove(m_DebugItems);
m_DebugPanel = null;
m_DebugItems = null;
}
public bool AreAnySettingsActive
{
get
{
return clearRenderTargetsAtCreation ||
clearRenderTargetsAtRelease ||
disablePassCulling ||
disablePassMerging;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f8fb1e6125f9d0b43a63ce4f782b4219
@@ -0,0 +1,237 @@
using System;
using System.Collections.Generic;
using static UnityEngine.Rendering.RenderGraphModule.RenderGraph;
namespace UnityEngine.Rendering.RenderGraphModule
{
internal abstract class RenderGraphDebugSession : IDisposable
{
protected class DebugDataContainer
{
readonly Dictionary<string, Dictionary<EntityId, DebugData>> m_Container = new();
public bool AddGraph(string graphName)
{
if (m_Container.ContainsKey(graphName))
return false;
m_Container.Add(graphName, new Dictionary<EntityId, DebugData>());
return true;
}
public bool RemoveGraph(string graphName)
{
return m_Container.Remove(graphName);
}
public bool AddExecution(string graphName, EntityId executionId, string executionName)
{
Debug.Assert(m_Container.ContainsKey(graphName));
if (m_Container[graphName].ContainsKey(executionId))
return false;
m_Container[graphName][executionId] = new DebugData(executionName);
return true;
}
public List<string> GetRenderGraphs() => new(m_Container.Keys);
public List<DebugExecutionItem> GetExecutions(string graphName)
{
var executions = new List<DebugExecutionItem>();
if (!string.IsNullOrEmpty(graphName) && m_Container.TryGetValue(graphName, out var executionsDict))
{
foreach (var (executionId, debugData) in executionsDict)
{
var item = new DebugExecutionItem(executionId, debugData.executionName);
executions.Add(item);
}
}
return executions;
}
public DebugData GetDebugData(string renderGraph, EntityId executionId)
{
if (!m_Container.TryGetValue(renderGraph, out var debugDataForGraph))
throw new InvalidOperationException($"RenderGraph '{renderGraph}' was never registered with the debug session.");
return debugDataForGraph[executionId];
}
public void SetDebugData(string renderGraph, EntityId executionId, DebugData data)
{
if (m_Container.TryGetValue(renderGraph, out var debugDataForGraph))
debugDataForGraph[executionId] = data;
}
public void DeleteExecutionIds(string renderGraph, List<EntityId> executionIds)
{
if (m_Container.TryGetValue(renderGraph, out var debugDataForGraph))
{
foreach (var executionId in executionIds)
debugDataForGraph.Remove(executionId);
}
}
public void Clear()
{
m_Container.Clear();
}
public void Invalidate()
{
foreach (var (graph, dict) in m_Container)
{
foreach (var (cam, debugData) in dict)
debugData.Clear();
}
}
}
// Session is considered active when it is collecting debug data
public abstract bool isActive { get; }
public string connectionName { get; set; }
DebugDataContainer debugDataContainer { get; }
protected RenderGraphDebugSession()
{
debugDataContainer = new DebugDataContainer();
onGraphRegistered += RegisterGraph;
onGraphUnregistered += UnregisterGraph;
onExecutionRegistered += RegisterExecution;
}
protected void RegisterGraph(string graphName)
{
if (debugDataContainer.AddGraph(graphName))
onRegisteredGraphsChanged?.Invoke();
}
protected void UnregisterGraph(string graphName)
{
if (debugDataContainer.RemoveGraph(graphName))
onRegisteredGraphsChanged?.Invoke();
}
protected void RegisterExecution(string graphName, EntityId executionId, string executionName)
{
if (debugDataContainer.AddExecution(graphName, executionId, executionName))
onRegisteredGraphsChanged?.Invoke();
}
public virtual void Dispose()
{
onGraphRegistered -= RegisterGraph;
onGraphUnregistered -= UnregisterGraph;
onExecutionRegistered -= RegisterExecution;
debugDataContainer.Clear();
}
protected void InvalidateData()
{
debugDataContainer.Invalidate();
}
public static event Action onRegisteredGraphsChanged;
public static event Action<string, EntityId> onDebugDataUpdated;
static RenderGraphDebugSession s_CurrentDebugSession;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
internal static void ResetStaticsOnLoad()
{
onRegisteredGraphsChanged = null;
onDebugDataUpdated = null;
s_CurrentDebugSession = null;
}
#endif
public static bool hasActiveDebugSession => s_CurrentDebugSession?.isActive ?? false;
public static RenderGraphDebugSession currentDebugSession => s_CurrentDebugSession;
public static void Create<TSession>() where TSession : RenderGraphDebugSession, new()
{
EndSession();
s_CurrentDebugSession = new TSession();
}
// internal: Required in test
internal static void Create(Type sessionType)
{
EndSession();
if (sessionType.IsAssignableFrom(typeof(RenderGraphDebugSession)))
throw new ArgumentException("Incorrect session type. Type should be derived from RenderGraphDebugSession.");
s_CurrentDebugSession = Activator.CreateInstance(sessionType) as RenderGraphDebugSession;
}
public static void EndSession()
{
if (s_CurrentDebugSession != null)
{
s_CurrentDebugSession.Dispose();
s_CurrentDebugSession = null;
}
}
public static readonly List<string> s_EmptyRegisteredGraphs = new();
public static List<string> GetRegisteredGraphs()
{
if (s_CurrentDebugSession == null || s_CurrentDebugSession.debugDataContainer == null)
{
return s_EmptyRegisteredGraphs;
}
return s_CurrentDebugSession.debugDataContainer.GetRenderGraphs();
}
public static readonly List<DebugExecutionItem> s_EmptyExecutions = new();
public static List<DebugExecutionItem> GetExecutions(string graphName)
{
if (s_CurrentDebugSession == null || s_CurrentDebugSession.debugDataContainer == null)
{
return s_EmptyExecutions;
}
return s_CurrentDebugSession.debugDataContainer.GetExecutions(graphName);
}
public static DebugData GetDebugData(string renderGraph, EntityId executionId)
{
return s_CurrentDebugSession.debugDataContainer.GetDebugData(renderGraph, executionId);
}
public static void SetDebugData(string renderGraph, EntityId executionId, DebugData data)
{
data.captureSourceString = s_CurrentDebugSession.connectionName;
data.captureTimestamp = $"{DateTime.Now:HH:mm:ss}";
s_CurrentDebugSession.debugDataContainer.SetDebugData(renderGraph, executionId, data);
onDebugDataUpdated?.Invoke(renderGraph, executionId);
}
public static void DeleteExecutionIds(string renderGraph, List<EntityId> executionIds)
{
s_CurrentDebugSession.debugDataContainer.DeleteExecutionIds(renderGraph, executionIds);
onRegisteredGraphsChanged?.Invoke();
}
protected void RegisterAllLocallyKnownGraphsAndExecutions()
{
var registeredExecutions = GetRegisteredExecutions();
foreach (var (graph, executions) in registeredExecutions)
{
RegisterGraph(graph.name);
foreach (var executionItem in executions)
RegisterExecution(graph.name, executionItem.id, executionItem.name);
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a3aa4608001ca6a4e999f5f24750cae8
@@ -0,0 +1,96 @@
#if !UNITY_EDITOR && UNITY_ENABLE_CHECKS
using UnityEngine.Networking.PlayerConnection;
using static UnityEngine.Rendering.RenderGraphModule.RenderGraph;
namespace UnityEngine.Rendering.RenderGraphModule
{
internal sealed class RenderGraphPlayerRemoteDebugSession : RenderGraphDebugSession
{
bool m_IsActive;
public override bool isActive => m_IsActive;
DebugMessageHandler m_MessageHandler = ScriptableObject.CreateInstance<DebugMessageHandler>();
public RenderGraphPlayerRemoteDebugSession() : base()
{
m_MessageHandler.Register(OnMessageFromEditor);
PlayerConnection.instance.RegisterConnection(OnEditorConnected);
PlayerConnection.instance.RegisterDisconnection(OnEditorDisconnected);
// If the editor is already connected when we get here, we request activation.
// We cannot activate the session immediately because the connection might exist because of the profiler
// or unit test runner, but Render Graph Viewer is not open.
// On the other hand, in the event of disconnection, we can deactivate the session directly.
if (PlayerConnection.instance.isConnected)
RequestActivate();
}
public override void Dispose()
{
base.Dispose();
onDebugDataUpdated -= SendDebugDataToEditor;
PlayerConnection.instance.UnregisterConnection(OnEditorConnected);
PlayerConnection.instance.UnregisterDisconnection(OnEditorDisconnected);
m_MessageHandler.UnregisterAll();
CoreUtils.Destroy(m_MessageHandler);
}
void OnEditorConnected(int playerId) => RequestActivate();
void OnEditorDisconnected(int playerId) => DeactivateSession();
void RequestActivate()
{
m_MessageHandler.Send(DebugMessageHandler.MessageType.Activate);
}
void ActivateSession()
{
InvalidateData(); // Invalidate so that data gets re-sent if the session gets reactivated
if (!m_IsActive)
{
m_IsActive = true;
RegisterAllLocallyKnownGraphsAndExecutions();
onDebugDataUpdated += SendDebugDataToEditor;
SendAnalyticsDataToEditor();
}
}
void DeactivateSession()
{
if (m_IsActive)
{
m_IsActive = false;
onDebugDataUpdated -= SendDebugDataToEditor;
}
}
void OnMessageFromEditor(DebugMessageHandler.MessageType messageType, DebugMessageHandler.IPayload _)
{
if (messageType == DebugMessageHandler.MessageType.Activate)
ActivateSession();
}
void SendDebugDataToEditor(string graph, EntityId executionId)
{
var debugData = GetDebugData(graph, executionId);
DebugMessageHandler.DebugDataPayload payload = new ()
{
graphName = graph,
executionId = executionId,
debugData = debugData
};
m_MessageHandler.Send(DebugMessageHandler.MessageType.DebugData, payload);
}
void SendAnalyticsDataToEditor()
{
var payload = new DebugMessageHandler.AnalyticsPayload();
m_MessageHandler.Send(DebugMessageHandler.MessageType.AnalyticsData, payload);
}
}
}
#endif
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: f531df6a2e5d4a688b7067d894ccc692
timeCreated: 1746447119
@@ -0,0 +1,507 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Scripting.APIUpdating;
// Typedef for the in-engine RendererList API (to avoid conflicts with the experimental version)
using CoreRendererListDesc = UnityEngine.Rendering.RendererUtils.RendererListDesc;
namespace UnityEngine.Rendering.RenderGraphModule
{
/// <summary>
/// This class specifies the context given to every render pass. This context type passes a generic
/// command buffer that can be used to schedule all commands. This will eventually be deprecated
/// in favor of more specific contexts that have more specific command buffer types.
/// </summary>
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
[Obsolete("RenderGraphContext is deprecated, use RasterGraphContext/ComputeGraphContext/UnsafeGraphContext instead.", true)]
public struct RenderGraphContext : IDerivedRendergraphContext
{
private InternalRenderGraphContext wrappedContext;
/// <inheritdoc />
public void FromInternalContext(InternalRenderGraphContext context)
{
wrappedContext = context;
}
/// <inheritdoc />
public readonly TextureUVOrigin GetTextureUVOrigin(in TextureHandle textureHandle) { return TextureUVOrigin.BottomLeft; }
///<summary>Scriptable Render Context used for rendering.</summary>
public ScriptableRenderContext renderContext { get => wrappedContext.renderContext; }
///<summary>Command Buffer used for rendering.</summary>
public CommandBuffer cmd { get => wrappedContext.cmd; }
///<summary>Render Graph pool used for temporary data.</summary>
public RenderGraphObjectPool renderGraphPool { get => wrappedContext.renderGraphPool; }
///<summary>Render Graph default resources.</summary>
public RenderGraphDefaultResources defaultResources { get => wrappedContext.defaultResources; }
}
public partial class RenderGraph
{
/// <summary>
/// Import the final backbuffer to render graph.
/// This function can only be used when nativeRenderPassesEnabled is false.
/// </summary>
/// <remarks>
/// This API cannot be called during the Render Graph execution, please call it outside of SetRenderFunc().
/// </remarks>
/// <param name="rt">Backbuffer render target identifier.</param>
/// <returns>A new TextureHandle that represents the imported texture in the context of this rendergraph.</returns>
[Obsolete("This overload is deprecated, use ImportBackbuffer(RenderTargetIdentifier, RenderTargetInfo, ImportResourceParams) instead.", true)]
public TextureHandle ImportBackbuffer(RenderTargetIdentifier rt)
{
return new TextureHandle();
}
/// <summary>
/// Create a new Render Graph Shared Texture resource.
/// This texture will be persistent across render graph executions.
/// </summary>
/// <remarks>
/// 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().
/// </remarks>
/// <param name="desc">Creation descriptor of the texture.</param>
/// <param name="explicitRelease">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.</param>
/// <returns>A new TextureHandle.</returns>
[Obsolete("CreateSharedTexture() and shared texture workflow are deprecated, use ImportTexture() workflow instead.", true)]
public TextureHandle CreateSharedTexture(in TextureDesc desc, bool explicitRelease = false)
{
return new TextureHandle();
}
/// <summary>
/// Refresh a shared texture with a new descriptor.
/// </summary>
/// <remarks>
/// This API should not be used with URP NRP Render Graph.
/// </remarks>
/// <param name="handle">Shared texture that needs to be updated.</param>
/// <param name="desc">New Descriptor for the texture.</param>
[Obsolete("RefreshSharedTextureDesc() and shared texture workflow are deprecated, use ImportTexture() workflow instead.", true)]
public void RefreshSharedTextureDesc(TextureHandle handle, in TextureDesc desc) {}
/// <summary>
/// Release a Render Graph shared texture resource.
/// </summary>
/// <remarks>
/// 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().
/// </remarks>
/// <param name="texture">The handle to the texture that needs to be release.</param>
[Obsolete("ReleaseSharedTexture() and shared texture workflow are deprecated, use ImportTexture() workflow instead.", true)]
public void ReleaseSharedTexture(TextureHandle texture) {}
/// <summary>
/// Import an external Graphics Buffer to the Render Graph.
/// Any pass writing to an imported graphics buffer will be considered having side effects and can't be automatically culled.
/// </summary>
/// <remarks>
/// This API cannot be called during the Render Graph execution, please call it outside of SetRenderFunc().
/// </remarks>
/// <param name="graphicsBuffer">External Graphics Buffer that needs to be imported.</param>
/// <param name="forceRelease">The imported graphics buffer will be released after usage.</param>
/// <returns>A new GraphicsBufferHandle.</returns>
[Obsolete("ImportBuffer with forceRelease parameter is deprecated. Use ImportBuffer without it instead. #from(6000.3)", true)]
public BufferHandle ImportBuffer(GraphicsBuffer graphicsBuffer, bool forceRelease = false)
{
return new BufferHandle();
}
/// <summary>
/// Add a new Render Pass to the Render Graph.
/// </summary>
/// <typeparam name="PassData">Type of the class to use to provide data to the Render Pass.</typeparam>
/// <param name="passName">Name of the new Render Pass (this is also be used to generate a GPU profiling marker).</param>
/// <param name="passData">Instance of PassData that is passed to the render function and you must fill.</param>
/// <param name="sampler">Profiling sampler used around the pass.</param>
/// <param name="file">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.</param>
/// <param name="line">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.</param>
/// <returns>A new instance of a RenderGraphBuilder used to setup the new Render Pass.</returns>
[Obsolete("AddRenderPass() is deprecated, use AddRasterRenderPass/AddComputePass/AddUnsafePass() instead.", true)]
public RenderGraphBuilder AddRenderPass<PassData>(string passName, out PassData passData, ProfilingSampler sampler
#if !CORE_PACKAGE_DOCTOOLS
,[CallerFilePath] string file = "",
[CallerLineNumber] int line = 0
#endif
) where PassData : class, new()
{
passData = null;
return new RenderGraphBuilder(null, m_Resources, this);
}
/// <summary>
/// Add a new Render Pass to the Render Graph.
/// </summary>
/// <remarks>
/// This API should not be used with URP NRP Render Graph. In addition, it cannot be called when Render Graph records a pass, please call it within SetRenderFunc() or outside of AddUnsafePass()/AddComputePass()/AddRasterRenderPass().
/// </remarks>
/// <typeparam name="PassData">Type of the class to use to provide data to the Render Pass.</typeparam>
/// <param name="passName">Name of the new Render Pass (this is also be used to generate a GPU profiling marker).</param>
/// <param name="passData">Instance of PassData that is passed to the render function and you must fill.</param>
/// <param name="file">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.</param>
/// <param name="line">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.</param>
/// <returns>A new instance of a RenderGraphBuilder used to setup the new Render Pass.</returns>
[Obsolete("AddRenderPass() is deprecated, use AddRasterRenderPass/AddComputePass/AddUnsafePass() instead.", true)]
public RenderGraphBuilder AddRenderPass<PassData>(string passName, out PassData passData
#if !CORE_PACKAGE_DOCTOOLS
,[CallerFilePath] string file = "",
[CallerLineNumber] int line = 0
#endif
) where PassData : class, new()
{
return AddRenderPass(passName, out passData, GetDefaultProfilingSampler(passName), file, line);
}
}
/// <summary>
/// Use this struct to set up a new Render Pass.
/// </summary>
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
[Obsolete("RenderGraphBuilder is deprecated, use IComputeRenderGraphBuilder/IRasterRenderGraphBuilder/IUnsafeRenderGraphBuilder instead.", true)]
public struct RenderGraphBuilder : IDisposable
{
RenderGraphPass m_RenderPass;
RenderGraphResourceRegistry m_Resources;
RenderGraph m_RenderGraph;
bool m_Disposed;
#region Public Interface
/// <summary>
/// Specify that the pass will use a Texture resource as a color render target.
/// This has the same effect as WriteTexture and also automatically sets the Texture to use as a render target.
/// </summary>
/// <param name="input">The Texture resource to use as a color render target.</param>
/// <param name="index">Index for multiple render target usage.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public TextureHandle UseColorBuffer(in TextureHandle input, int index)
{
CheckResource(input.handle, false);
m_Resources.IncrementWriteCount(input.handle);
m_RenderPass.SetColorBuffer(input, index);
return input;
}
/// <summary>
/// Specify that the pass will use a Texture resource as a depth buffer.
/// </summary>
/// <param name="input">The Texture resource to use as a depth buffer during the pass.</param>
/// <param name="flags">Specify the access level for the depth buffer. This allows you to say whether you will read from or write to the depth buffer, or do both.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public TextureHandle UseDepthBuffer(in TextureHandle input, DepthAccess flags)
{
CheckResource(input.handle, false);
if ((flags & DepthAccess.Write) != 0)
m_Resources.IncrementWriteCount(input.handle);
if ((flags & DepthAccess.Read) != 0)
{
if (!m_Resources.IsRenderGraphResourceImported(input.handle) && m_Resources.TextureNeedsFallback(input))
WriteTexture(input);
}
m_RenderPass.SetDepthBuffer(input, flags);
return input;
}
/// <summary>
/// Specify a Texture resource to read from during the pass.
/// </summary>
/// <param name="input">The Texture resource to read from during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public TextureHandle ReadTexture(in TextureHandle input)
{
CheckResource(input.handle);
if (!m_Resources.IsRenderGraphResourceImported(input.handle) && m_Resources.TextureNeedsFallback(input))
{
var textureResource = m_Resources.GetTextureResource(input.handle);
// Ensure we get a fallback to black
textureResource.desc.clearBuffer = true;
textureResource.desc.clearColor = Color.black;
// If texture is read from but never written to, return a fallback black texture to have valid reads
// Return one from the preallocated default textures if possible
if (m_RenderGraph.GetImportedFallback(textureResource.desc, out var fallback))
return fallback;
// If not, simulate a write to the texture so that it gets allocated
WriteTexture(input);
}
m_RenderPass.AddResourceRead(input.handle);
return input;
}
/// <summary>
/// Specify a Texture resource to write to during the pass.
/// </summary>
/// <param name="input">The Texture resource to write to during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public TextureHandle WriteTexture(in TextureHandle input)
{
CheckResource(input.handle);
m_Resources.IncrementWriteCount(input.handle);
m_RenderPass.AddResourceWrite(input.handle);
return input;
}
/// <summary>
/// Specify a Texture resource to read and write to during the pass.
/// </summary>
/// <param name="input">The Texture resource to read and write to during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public TextureHandle ReadWriteTexture(in TextureHandle input)
{
CheckResource(input.handle);
m_Resources.IncrementWriteCount(input.handle);
m_RenderPass.AddResourceWrite(input.handle);
m_RenderPass.AddResourceRead(input.handle);
return input;
}
/// <summary>
/// Create a new Render Graph Texture resource.
/// This texture will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="desc">Texture descriptor.</param>
/// <returns>A new transient TextureHandle.</returns>
public TextureHandle CreateTransientTexture(in TextureDesc desc)
{
var result = m_Resources.CreateTexture(desc, m_RenderPass.index);
m_RenderPass.AddTransientResource(result.handle);
return result;
}
/// <summary>
/// Create a new Render Graph Texture resource using the descriptor from another texture.
/// This texture will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="texture">Texture from which the descriptor should be used.</param>
/// <returns>A new transient TextureHandle.</returns>
public TextureHandle CreateTransientTexture(in TextureHandle texture)
{
ref readonly var desc = ref m_Resources.GetTextureResourceDesc(texture.handle);
var result = m_Resources.CreateTexture(desc, m_RenderPass.index);
m_RenderPass.AddTransientResource(result.handle);
return result;
}
/// <summary>
/// Specify a RayTracingAccelerationStructure resource to build during the pass.
/// </summary>
/// <param name="input">The RayTracingAccelerationStructure resource to build during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public RayTracingAccelerationStructureHandle WriteRayTracingAccelerationStructure(in RayTracingAccelerationStructureHandle input)
{
CheckResource(input.handle);
m_Resources.IncrementWriteCount(input.handle);
m_RenderPass.AddResourceWrite(input.handle);
return input;
}
/// <summary>
/// Specify a RayTracingAccelerationStructure resource to use during the pass.
/// </summary>
/// <param name="input">The RayTracingAccelerationStructure resource to use during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public RayTracingAccelerationStructureHandle ReadRayTracingAccelerationStructure(in RayTracingAccelerationStructureHandle input)
{
CheckResource(input.handle);
m_RenderPass.AddResourceRead(input.handle);
return input;
}
/// <summary>
/// Specify a Renderer List resource to use during the pass.
/// </summary>
/// <param name="input">The Renderer List resource to use during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public RendererListHandle UseRendererList(in RendererListHandle input)
{
if(input.IsValid())
m_RenderPass.UseRendererList(input);
return input;
}
/// <summary>
/// Specify a Graphics Buffer resource to read from during the pass.
/// </summary>
/// <param name="input">The Graphics Buffer resource to read from during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public BufferHandle ReadBuffer(in BufferHandle input)
{
CheckResource(input.handle);
m_RenderPass.AddResourceRead(input.handle);
return input;
}
/// <summary>
/// Specify a Graphics Buffer resource to write to during the pass.
/// </summary>
/// <param name="input">The Graphics Buffer resource to write to during the pass.</param>
/// <returns>An updated resource handle to the input resource.</returns>
public BufferHandle WriteBuffer(in BufferHandle input)
{
CheckResource(input.handle);
m_RenderPass.AddResourceWrite(input.handle);
m_Resources.IncrementWriteCount(input.handle);
return input;
}
/// <summary>
/// Create a new Render Graph Graphics Buffer resource.
/// This Graphics Buffer will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="desc">Graphics Buffer descriptor.</param>
/// <returns>A new transient GraphicsBufferHandle.</returns>
public BufferHandle CreateTransientBuffer(in BufferDesc desc)
{
var result = m_Resources.CreateBuffer(desc, m_RenderPass.index);
m_RenderPass.AddTransientResource(result.handle);
return result;
}
/// <summary>
/// Create a new Render Graph Graphics Buffer resource using the descriptor from another Graphics Buffer.
/// This Graphics Buffer will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="graphicsbuffer">Graphics Buffer from which the descriptor should be used.</param>
/// <returns>A new transient GraphicsBufferHandle.</returns>
public BufferHandle CreateTransientBuffer(in BufferHandle graphicsbuffer)
{
ref readonly var desc = ref m_Resources.GetBufferResourceDesc(graphicsbuffer.handle);
var result = m_Resources.CreateBuffer(desc, m_RenderPass.index);
m_RenderPass.AddTransientResource(result.handle);
return result;
}
/// <summary>
/// Specify the render function to use for this pass.
/// A call to this is mandatory for the pass to be valid.
/// </summary>
/// <typeparam name="PassData">The Type of the class that provides data to the Render Pass.</typeparam>
/// <param name="renderFunc">Render function for the pass.</param>
public void SetRenderFunc<PassData>(BaseRenderFunc<PassData, RenderGraphContext> renderFunc)
where PassData : class, new()
{
((RenderGraphPass<PassData>)m_RenderPass).renderFunc = renderFunc;
}
/// <summary>
/// Enable asynchronous compute for this pass.
/// </summary>
/// <param name="value">Set to true to enable asynchronous compute.</param>
public void EnableAsyncCompute(bool value)
{
m_RenderPass.EnableAsyncCompute(value);
}
/// <summary>
/// Allow or not pass culling
/// By default all passes can be culled out if the render graph detects it's not actually used.
/// In some cases, a pass may not write or read any texture but rather do something with side effects (like setting a global texture parameter for example).
/// This function can be used to tell the system that it should not cull this pass.
/// </summary>
/// <param name="value">True to allow pass culling.</param>
public void AllowPassCulling(bool value)
{
m_RenderPass.AllowPassCulling(value);
}
/// <summary>
/// Enable foveated rendering for this pass.
/// </summary>
/// <param name="value">True to enable foveated rendering.</param>
public void EnableFoveatedRasterization(bool value)
{
m_RenderPass.EnableFoveatedRasterization(value);
}
/// <summary>
/// Dispose the RenderGraphBuilder instance.
/// </summary>
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// Allow or not pass culling based on renderer list results
/// By default all passes can be culled out if the render graph detects they are using a renderer list that is empty (does not draw any geometry)
/// In some cases, a pass may not write or read any texture but rather do something with side effects (like setting a global texture parameter for example).
/// This function can be used to tell the system that it should not cull this pass.
/// </summary>
/// <param name="value">True to allow pass culling.</param>
public void AllowRendererListCulling(bool value)
{
m_RenderPass.AllowRendererListCulling(value);
}
/// <summary>
/// Used to indicate that a pass depends on an external renderer list (that is not directly used in this pass).
/// </summary>
/// <param name="input">The renderer list handle this pass depends on.</param>
/// <returns>A <see cref="RendererListHandle"/></returns>
public RendererListHandle DependsOn(in RendererListHandle input)
{
m_RenderPass.UseRendererList(input);
return input;
}
#endregion
#region Internal Interface
internal RenderGraphBuilder(RenderGraphPass renderPass, RenderGraphResourceRegistry resources, RenderGraph renderGraph)
{
m_RenderPass = renderPass;
m_Resources = resources;
m_RenderGraph = renderGraph;
m_Disposed = false;
}
void Dispose(bool disposing)
{
if (m_Disposed)
return;
m_RenderGraph.RenderGraphState = RenderGraphState.RecordingGraph;
m_Disposed = true;
}
[Conditional("UNITY_ENABLE_CHECKS")]
void CheckResource(in ResourceHandle res, bool checkTransientReadWrite = true)
{
if(RenderGraph.enableValidityChecks)
{
if (res.IsValid())
{
int transientIndex = m_Resources.GetRenderGraphResourceTransientIndex(res);
// 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.");
}
if (transientIndex != -1 && transientIndex != m_RenderPass.index)
{
throw new ArgumentException($"Trying to use a transient texture (pass index {transientIndex}) in a different pass (pass index {m_RenderPass.index}).");
}
}
else
{
throw new ArgumentException($"Trying to use an invalid resource (pass {m_RenderPass.name}).");
}
}
}
internal void GenerateDebugData(bool value)
{
m_RenderPass.GenerateDebugData(value);
}
#endregion
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: b4afee4f5b53ff54eb3e7f4485b61dc4
@@ -0,0 +1,415 @@
using System;
using UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.Rendering.RenderGraphModule
{
/// <summary>
/// Common base interface for the different render graph builders. These functions are supported on all builders.
/// </summary>
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public interface IBaseRenderGraphBuilder : IDisposable
{
/// <summary>
/// Declare that this pass uses the input texture.
/// </summary>
/// <param name="input">The texture resource to use during the pass.</param>
/// <param name="flags">A combination of flags indicating how the resource will be used during the pass. Default value is set to AccessFlag.Read </param>
public void UseTexture(in TextureHandle input, AccessFlags flags = AccessFlags.Read);
/// <summary>
/// Declare that this pass uses the texture assigned to the global texture slot. The actual texture referenced is indirectly specified here it depends
/// on the value previous passes that were added to the graph set for the global texture slot. If no previous pass set a texture to the global slot an
/// exception will be raised.
/// </summary>
/// <param name="propertyId">The global texture slot read by shaders in this pass. Use Shader.PropertyToID to generate these ids.</param>
/// <param name="flags">A combination of flags indicating how the resource will be used during the pass. Default value is set to AccessFlag.Read </param>
public void UseGlobalTexture(int propertyId, AccessFlags flags = AccessFlags.Read);
/// <summary>
/// Indicate that this pass will reference all textures in global texture slots known to the graph. The default setting is false.
/// It is highly recommended if you know which globals you pass will access to use UseTexture(glboalTextureSlotId) with individual texture slots instead of
/// UseAllGlobalTextures(true) to ensure the graph can maximally optimize resource use and lifetimes.
///
/// This function should only be used in cases where it is difficult/impossible to know which globals a pass will access. This is for example true if your pass
/// renders objects in the scene (e.g. using CommandBuffer.DrawRendererList) that might be using arbitrary shaders which in turn may access arbitrary global textures.
/// To avoid having to do a UseAllGlobalTextures(true) in this situation, you will either have to ensure *all* shaders are well behaved and do not access spurious
/// globals our make sure your renderer list filters allow only shaders that are known to be well behaved to pass.
/// </summary>
/// <param name="enable">If true the pass from which this is called will reference all global textures.</param>
public void UseAllGlobalTextures(bool enable);
/// <summary>
/// Make this pass set a global texture slot *at the end* of this pass. During this pass the global texture will still have it's
/// old value. Only after this pass the global texture slot will take on the new value specified.
/// Generally this pass will also do a UseTexture(write) on this texture handle to indicate it is generating this texture, but this is not really a requirement
/// you can have a pass that simply sets up a new value in a global texture slot but doesn't write it.
/// Although counter-intuitive at first, this call doesn't actually have a dependency on the passed in texture handle. It's only when a subsequent pass has
/// a dependency on the global texture slot that subsequent pass will get a dependency on the currently set global texture for that slot. This means
/// globals slots can be set without overhead if you're unsure if a resource will be used or not, the graph will still maintain the correct lifetimes.
///
/// NOTE: When the `RENDER_GRAPH_CLEAR_GLOBALS` define is set, all shader bindings set through this function will be cleared once graph execution completes.
/// </summary>
/// <param name="input">The texture value to set in the global texture slot. This can be an null handle to clear the global texture slot.</param>
/// <param name="propertyId">The global texture slot to set the value for. Use Shader.PropertyToID to generate the id.</param>
public void SetGlobalTextureAfterPass(in TextureHandle input, int propertyId);
/// <summary>
/// Declare that this pass uses the input compute buffer.
/// </summary>
/// <param name="input">The compute buffer resource to use during the pass.</param>
/// <param name="flags">A combination of flags indicating how the resource will be used during the pass. Default value is set to AccessFlag.Read </param>
/// <returns>The value passed to 'input'. You should not use the returned value it will be removed in the future.</returns>
public BufferHandle UseBuffer(in BufferHandle input, AccessFlags flags = AccessFlags.Read);
/// <summary>
/// Create a new Render Graph Texture resource.
/// This texture will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="desc">Texture descriptor.</param>
/// <returns>A new transient TextureHandle.</returns>
public TextureHandle CreateTransientTexture(in TextureDesc desc);
/// <summary>
/// Create a new Render Graph Texture resource using the descriptor from another texture.
/// This texture will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="texture">Texture from which the descriptor should be used.</param>
/// <returns>A new transient TextureHandle.</returns>
public TextureHandle CreateTransientTexture(in TextureHandle texture);
/// <summary>
/// Create a new Render Graph Graphics Buffer resource.
/// This Graphics Buffer will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="desc">Compute Buffer descriptor.</param>
/// <returns>A new transient BufferHandle.</returns>
public BufferHandle CreateTransientBuffer(in BufferDesc desc);
/// <summary>
/// Create a new Render Graph Graphics Buffer resource using the descriptor from another Graphics Buffer.
/// This Graphics Buffer will only be available for the current pass and will be assumed to be both written and read so users don't need to add explicit read/write declarations.
/// </summary>
/// <param name="computebuffer">Graphics Buffer from which the descriptor should be used.</param>
/// <returns>A new transient BufferHandle.</returns>
public BufferHandle CreateTransientBuffer(in BufferHandle computebuffer);
/// <summary>
/// This pass will read from this renderer list. RendererLists are always read-only in the graph so have no access flags.
/// </summary>
/// <param name="input">The Renderer List resource to use during the pass.</param>
public void UseRendererList(in RendererListHandle input);
/// <summary>
/// Enable asynchronous compute for this pass.
/// </summary>
/// <param name="value">Set to true to enable asynchronous compute.</param>
public void EnableAsyncCompute(bool value);
/// <summary>
/// Allow or not pass culling.
/// By default all passes can be culled out if the render graph detects it's not actually used.
/// In some cases, a pass may not write or read any texture but rather do something with side effects (like setting a global texture parameter for example).
/// This function can be used to tell the system that it should not cull this pass.
/// </summary>
/// <param name="value">True to allow pass culling.</param>
public void AllowPassCulling(bool value);
/// <summary>
/// Allow commands in the command buffer to modify global state. This will introduce a render graph sync-point in the frame and cause all passes after this pass to never be
/// reordered before this pass. This may nave negative impact on performance and memory use if not used carefully so it is recommended to only allow this in specific use cases.
/// This will also set AllowPassCulling to false.
/// </summary>
/// <param name="value">True to allow global state modification.</param>
public void AllowGlobalStateModification(bool value);
/// <summary>
/// Enable foveated rendering for this pass.
/// </summary>
/// <param name="value">True to enable foveated rendering.</param>
public void EnableFoveatedRasterization(bool value);
/// <summary>
/// Generates debugging data for this pass, intended for visualization in the RenderGraph Viewer.
/// </summary>
/// <param name="value">True to enable debug data generation for this pass.</param>
public void GenerateDebugData(bool value);
}
/// <summary>
/// An intermediary interface for builders that can set render attachments and random access attachments (UAV).
/// </summary>
public interface IRenderAttachmentRenderGraphBuilder : IBaseRenderGraphBuilder
{
/// <summary>
/// Binds the texture as a color render target (MRT attachment) for this pass.
/// </summary>
/// <param name="tex">The texture to bind as a render target for this pass.</param>
/// <param name="index">The MRT slot the shader writes to. This maps to `SV_Target` in the shader, for example, a value of `1` maps to `SV_Target1`.</param>
/// <param name="flags">The access mode for the texture. The default value is `AccessFlags.Write`.</param>
/// <remarks>
/// Potential access flags:
/// - Write: This pass outputs to the texture using render target rasterization. The render graph binds
/// the texture to the specified MRT slot (index). In HLSL, write to the slot using
/// `float4 outColor : SV_Target{index} = value;`.
/// To use random-access writes, use `SetRandomAccessAttachment` (UAV).
/// Don't write to this target with UAV-style indexed access (`operator[]`).
/// - Read: This pass might read the current contents of the render target implicitly, depending
/// on rasterization state (for example, blending operations that read before writing).
///
/// The render graph can't determine how much of the target you overwrite. By default, it
/// assumes partial updates and preserves existing content. If you fully overwrite the target
/// (for example, in a fullscreen pass), use `AccessFlags.WriteAll` for better performance.
/// </remarks>
void SetRenderAttachment(TextureHandle tex, int index, AccessFlags flags = AccessFlags.Write)
{
SetRenderAttachment(tex, index, flags, 0, -1);
}
/// <summary>
/// Binds the texture as a color render target (MRT attachment) for this pass.
/// </summary>
/// <param name="tex">The texture to bind as a render target for this pass.</param>
/// <param name="index">The MRT slot the shader writes to (corresponds to `SV_Target{index}`).</param>
/// <param name="flags">How this pass accesses the texture. Defaults to `AccessFlags.Write`.</param>
/// <param name="mipLevel">The mip level to bind.</param>
/// <param name="depthSlice">The array slice to bind. Use -1 to bind all slices.</param>
/// <remarks>
/// Potential access flags:
/// - Write: This pass outputs to the texture using render target rasterization. The render graph binds
/// the texture to the specified MRT slot (index). In HLSL, write to the slot using
/// `float4 outColor : SV_Target{index} = value;`.
/// To use random-access writes, use `SetRandomAccessAttachment` (UAV).
/// Don't write to this target with UAV-style indexed access (`operator[]`).
/// - Read: This pass might read the current contents of the render target implicitly, depending
/// on rasterization state (for example, blending operations that read before writing).
///
/// The render graph can't determine how much of the target you overwrite. By default, it
/// assumes partial updates and preserves existing content. If you fully overwrite the target
/// (for example, in a fullscreen pass), use `AccessFlags.WriteAll` for better performance.
///
/// Using the same texture handle with different depth slices at different render target indices is not supported.
/// </remarks>
void SetRenderAttachment(TextureHandle tex, int index, AccessFlags flags, int mipLevel, int depthSlice);
/// <summary>
/// Binds the texture as the depth buffer for this pass.
/// </summary>
/// <param name="tex">The texture to use as the depth buffer for this pass.</param>
/// <param name="flags">Access mode for the texture in this pass. Defaults to `AccessFlag.ReadWrite`.
/// </param>
/// <remarks>
/// Potential access flags:
/// - Write: The pass writes fragment depth to the bound depth buffer (required if `ZWrite` is enabled in shader code).
/// - Read: The pass reads from the bound depth buffer for depth testing (required if `ZTest` is set to an operation other than `Disabled`, `Never`, or `Always` in shader code).
///
/// Only one depth buffer can be tested against or written to in a single pass.
/// To output depth to multiple textures, register the additional texture as a color
/// attachment using `SetRenderAttachment()`, then compute and write the depth value in the shader.
/// If you call `SetRenderAttachmentDepth()` more than once on the same builder, it results in an error.
/// </remarks>
void SetRenderAttachmentDepth(TextureHandle tex, AccessFlags flags = AccessFlags.ReadWrite)
{
SetRenderAttachmentDepth(tex, flags, 0, -1);
}
/// <summary>
/// Binds the texture as the depth buffer for this pass.
/// </summary>
/// <param name="tex">The texture to use as the depth buffer for this pass.</param>
/// <param name="flags">How this pass will access the depth texture (for example, `AccessFlags.Read`, `AccessFlags.Write`, `AccessFlags.ReadWrite`).</param>
/// <param name="mipLevel">The mip level to bind.</param>
/// <param name="depthSlice">The array slice to bind. Use -1 to bind all slices.</param>
/// <remarks>
/// Potential access flags:
/// - Write: The pass writes fragment depth to the bound depth buffer (required if `ZWrite` is enabled in shader code).
/// - Read: The pass reads from the bound depth buffer for depth testing (required if `ZTest` is set to an operation other than `Disabled`, `Never`, or `Always` in shader code).
///
/// Only one depth texture can be read from or written to in a single pass.
/// To output depth to multiple textures, register the additional texture as a color
/// attachment using `SetRenderAttachment()`, then compute and write the depth value in the shader.
/// If you call `SetRenderAttachmentDepth()` more than once on the same builder, it results in an error.
///
/// Using the same texture handle with different depth slices at different render target indices is not supported.
/// </remarks>
void SetRenderAttachmentDepth(TextureHandle tex, AccessFlags flags, int mipLevel, int depthSlice);
/// <summary>
/// Binds the texture as a random-access attachment for this pass
/// (DX12: Unordered Access View, Vulkan: Storage Image).
/// </summary>
/// <param name="tex">The texture to expose as a UAV in this pass.</param>
/// <param name="index">The binding slot the shader uses to access this UAV (HLSL: `register(u[index])`).</param>
/// <param name="flags">Access mode for this texture in the pass. Defaults to `AccessFlags.ReadWrite`.</param>
/// <returns>
/// This declares that shaders in the pass will access the texture via
/// `RWTexture2D`, `RWTexture3D`, etc., enabling read/write operations,
/// atomics, and other UAV-style operations using standard HLSL.
///
/// The value passed to the `tex` parameter. The return value is deprecated.
/// </returns>
/// <remarks>
/// Random-access (UAV) textures share index-based binding slots with
/// render targets and input attachments. Refer to `CommandBuffer.SetRandomWriteTarget`
/// for platform-specific details and constraints.
/// </remarks>
TextureHandle SetRandomAccessAttachment(TextureHandle tex, int index, AccessFlags flags = AccessFlags.ReadWrite);
/// <summary>
/// Binds the buffer as a random-access attachment for this pass
/// (DX12: Unordered Access View, Vulkan: Storage Buffer).
/// </summary>
/// <param name="tex">The buffer to expose as a UAV in this pass.</param>
/// <param name="index">The binding slot the shader uses to access this UAV (HLSL: `register(u[index])`).</param>
/// <param name="flags">Access mode for this buffer in the pass. Defaults to `AccessFlags.Read`.</param>
/// <returns>
/// The value passed to the `buffer` parameter. The return value is deprecated.
/// </returns>
/// <remarks>
/// This declares that shaders in the pass will access the buffer via
/// `RWStructuredBuffer`, `RWByteAddressBuffer`, etc., enabling read/write,
/// atomics, and other UAV-style operations using standard HLSL.
///
/// Random-access (UAV) buffers share index-based binding slots with
/// render targets and input attachments. Refer to `CommandBuffer.SetRandomWriteTarget`
/// for platform-specific details and constraints.
/// </remarks>
BufferHandle UseBufferRandomAccess(BufferHandle tex, int index, AccessFlags flags = AccessFlags.Read);
/// <summary>
/// Binds the buffer as a random-access attachment for this pass
/// (DX12: Unordered Access View, Vulkan: Storage Buffer).
/// </summary>
/// <param name="tex">The buffer to expose as a UAV in this pass.</param>
/// <param name="index">The binding slot the shader uses to access this UAV (HLSL: `register(u[index])`).</param>
/// <param name="preserveCounterValue">Whether to keep the current append/consume counter unchanged for this UAV buffer. Defaults to preserving the existing counter value.</param>
/// <param name="flags">Access mode for this buffer in the pass. Defaults to `AccessFlags.Read`.</param>
/// <returns>
/// The value passed to the `buffer` parameter. The return value is deprecated.
/// </returns>
/// <remarks>
/// This declares that shaders in the pass will access the buffer via
/// `RWStructuredBuffer`, `RWByteAddressBuffer`, etc., enabling read/write,
/// atomics, and other UAV-style operations using standard HLSL.
///
/// Random-access (UAV) buffers share index-based binding slots with
/// render targets and input attachments. Refer to `CommandBuffer.SetRandomWriteTarget`
/// for platform-specific details and constraints.
/// </remarks>
BufferHandle UseBufferRandomAccess(BufferHandle tex, int index, bool preserveCounterValue, AccessFlags flags = AccessFlags.Read);
}
/// <summary>
/// A builder for a compute render pass.
/// <see cref="RenderGraph.AddComputePass"/>
/// </summary>
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public interface IComputeRenderGraphBuilder : IBaseRenderGraphBuilder
{
/// <summary>
/// Specify the render function to use for this pass.
/// A call to this is mandatory for the pass to be valid.
/// </summary>
/// <typeparam name="PassData">The Type of the class that provides data to the Render Pass.</typeparam>
/// <param name="renderFunc">Render function for the pass.</param>
public void SetRenderFunc<PassData>(BaseRenderFunc<PassData, ComputeGraphContext> renderFunc)
where PassData : class, new();
}
/// <summary>
/// A builder for an unsafe render pass.
/// <see cref="RenderGraph.AddUnsafePass"/>
/// </summary>
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public interface IUnsafeRenderGraphBuilder : IRenderAttachmentRenderGraphBuilder
{
/// <summary>
/// Specify the render function to use for this pass.
/// A call to this is mandatory for the pass to be valid.
/// </summary>
/// <typeparam name="PassData">The Type of the class that provides data to the Render Pass.</typeparam>
/// <param name="renderFunc">Render function for the pass.</param>
public void SetRenderFunc<PassData>(BaseRenderFunc<PassData, UnsafeGraphContext> renderFunc)
where PassData : class, new();
}
/// <summary>
/// A builder for a raster render pass.
/// <see cref="RenderGraph.AddRasterRenderPass"/>
/// </summary>
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public interface IRasterRenderGraphBuilder : IRenderAttachmentRenderGraphBuilder
{
/// <summary>
/// Binds the texture as an input attachment for this pass.
///
/// Shaders might read this texture at the current fragment using
/// `LOAD_FRAMEBUFFER_INPUT(idx)` or `LOAD_FRAMEBUFFER_INPUT_MS(idx, sampleIdx)`.
/// The `idx` used in the shader must match the `index` provided to `SetInputAttachment`.
/// </summary>
/// <remarks>
/// Platform support varies. Input attachments, especially with MSAA, might be unsupported on
/// some targets. Use `RenderGraphUtils.IsFramebufferFetchSupportedOnCurrentPlatform` at
/// runtime to check compatibility.
/// </remarks>
/// <param name="tex">The texture to expose as an input attachment.</param>
/// <param name="index">The binding index used by the shader macros (`idx`).</param>
/// <param name="flags">The access mode for this texture. Defaults to `AccessFlags.Read`. Writing is currently not supported on any platform.</param>
void SetInputAttachment(TextureHandle tex, int index, AccessFlags flags = AccessFlags.Read)
{
SetInputAttachment(tex, index, flags, 0, -1);
}
/// <summary>
/// Binds the texture as an input attachment for this pass.
///
/// Shaders might read this texture at the current fragment using
/// `LOAD_FRAMEBUFFER_INPUT(idx)` or `LOAD_FRAMEBUFFER_INPUT_MS(idx, sampleIdx)`.
/// The `idx` used in the shader must match the `index` provided in `SetInputAttachment`.
/// </summary>
/// <remarks>
/// Platform support varies. Input attachments, especially with MSAA, might be unsupported on
/// some targets. Use `RenderGraphUtils.IsFramebufferFetchSupportedOnCurrentPlatform` at
/// runtime to check compatibility.
/// </remarks>
/// <param name="tex">The texture to expose as an input attachment.</param>
/// <param name="index">The binding index used by the shader macros (`idx`).</param>
/// <param name="flags">The access mode for the texture. Defaults to `AccessFlags.Read`. Writing is currently not supported on any platform.</param>
/// <param name="mipLevel">The mip level to bind.</param>
/// <param name="depthSlice">The array slice to bind. Use -1 to bind all slices.</param>
void SetInputAttachment(TextureHandle tex, int index, AccessFlags flags, int mipLevel, int depthSlice);
/// <summary>
/// Enables Variable Rate Shading (VRS) on the current rasterization pass. Rasterization will use the texture to determine the rate of fragment shader invocation.
/// </summary>
/// <param name="tex">Shading rate image (SRI) Texture to use during this pass.</param>
void SetShadingRateImageAttachment(in TextureHandle tex);
/// <summary>
/// Set shading rate fragment size.
/// </summary>
/// <param name="shadingRateFragmentSize">Shading rate fragment size to set.</param>
void SetShadingRateFragmentSize(ShadingRateFragmentSize shadingRateFragmentSize);
/// <summary>
/// Set shading rate combiner.
/// </summary>
/// <param name="stage">Shading rate combiner stage to apply combiner to.</param>
/// <param name="combiner">Shading rate combiner to set.</param>
void SetShadingRateCombiner(ShadingRateCombinerStage stage, ShadingRateCombiner combiner);
/// <summary>
/// Enables the configuration of extended pass properties that may allow platform-specific optimizations.
/// </summary>
/// <param name="extendedFeatureFlags">Specifies additional pass properties that may enable optimizations on certain platforms.</param>
public void SetExtendedFeatureFlags(ExtendedFeatureFlags extendedFeatureFlags);
/// <summary>
/// Specify the render function to use for this pass.
/// A call to this is mandatory for the pass to be valid.
/// </summary>
/// <typeparam name="PassData">The Type of the class that provides data to the Render Pass.</typeparam>
/// <param name="renderFunc">Render function for the pass.</param>
public void SetRenderFunc<PassData>(BaseRenderFunc<PassData, RasterGraphContext> renderFunc)
where PassData : class, new();
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2fcdf4bad9ff6e340a9aaca6de5fe1a3
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
namespace UnityEngine.Rendering.RenderGraphModule
{
/// <summary>
/// Interface to add/manage Render Graph related parameters across different types of RenderPipelineAssets.
/// </summary>
public interface IRenderGraphEnabledRenderPipeline
{
/// <summary>
/// Indicates if this render pipeline instance supports ImmediateMode when debugging the render graph.
/// </summary>
bool isImmediateModeSupported { get; }
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d107e4e863b7b4e579c15e52f775ed03
@@ -0,0 +1,21 @@
using UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.Rendering.RenderGraphModule
{
/// <summary>
/// A base class that can be inherited by render graph implementers. Currently this is only used by URP. In the future this will allow shared SRP rendering features between HDRP and URP through render graph.
/// </summary>
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public interface IRenderGraphRecorder
{
/// <summary>
/// This function is called during render graph recording and allows the implementing class to register the relevant passes and resources to the passed in render graph.
/// To access information about the current execution context (current camera, ...) the ContextContainer can be queried. See the render pipeline documentation
/// for more information on the types that are available in the context container. (The exact types available may differ based on the currently active render pipeline).
/// This is where custom rendering occurs. Specific details are left to the implementation.
/// </summary>
/// <param name="renderGraph">The graph to register resources and passes with.</param>
/// <param name="frameData">A ContextContainer that allows querying information about the current execution context (.e.g. RenderPipeline camera info).</param>
public void RecordRenderGraph(RenderGraph renderGraph, ContextContainer frameData);
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 233f6456f0564543ae9117f9b50bc56a
timeCreated: 1699555576
@@ -0,0 +1,44 @@
using UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler;
namespace UnityEngine.Rendering.RenderGraphModule
{
public partial class RenderGraph
{
//TODO(ddebaets) move old compile func/members over
NativePassCompiler nativeCompiler = null;
internal NativePassCompiler CompileNativeRenderGraph(int graphHash)
{
using (RenderGraphProfilerMarkers.CompileRenderGraph.Auto())
{
if (nativeCompiler == null)
nativeCompiler = new NativePassCompiler(m_CompilationCache);
bool compilationIsCached = nativeCompiler.Initialize(m_Resources, m_RenderPasses, m_DebugParameters, name, m_EnableCompilationCaching, graphHash, m_ExecutionCount, m_renderTextureUVOriginStrategy);
if (!compilationIsCached)
nativeCompiler.Compile(m_Resources);
ref var passData = ref nativeCompiler.contextData.passData;
int numPasses = passData.Length;
for (int i = 0; i < numPasses; ++i)
{
if (!passData.ElementAt(i).culled)
m_RendererLists.AddRange(m_RenderPasses[i].usedRendererListList);
}
m_Resources.CreateRendererLists(m_RendererLists, m_RenderGraphContext.renderContext);
return nativeCompiler;
}
}
void ExecuteNativeRenderGraph()
{
using (new ProfilingScope(m_RenderGraphContext.cmd, RenderGraphProfilerMarkers.ExecuteRenderGraph))
{
nativeCompiler.ExecuteGraph(m_RenderGraphContext, m_Resources, m_RenderPasses);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 250183d182df5b54997e0ec59351e6e4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,238 @@
using System.Collections.Generic;
using System.Diagnostics;
using Unity.Scripting.LifecycleManagement;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler;
namespace UnityEngine.Rendering.RenderGraphModule
{
public partial class RenderGraph
{
internal static class RenderGraphExceptionMessages
{
[NoAutoStaticsCleanup]
internal static bool enableCaller = true; // Only used from tests
internal const string k_RenderGraphExecutionError = "Render Graph Execution error";
static readonly Dictionary<RenderGraphState, string> m_RenderGraphStateMessages = new()
{
{
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.";
internal const string k_GraphPassesCalledBeforeCompactedNonCulledRasterPasses = "Cannot iterate over compactedNonCulledRasterPasses, the data is null. Did you use GraphPasses() before calling CompactNonCulledPassesForRasterPasses?";
// 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.";
internal static string IncompatibleTextureUVOrigin(TextureUVOriginSelection origin, string attachmentType, string attachmentName, RenderGraphResourceType attachmentResourceType, int attachmentResourceIndex, TextureUVOriginSelection attachmentOrigin) =>
$"TextureUVOrigin `{origin}` is not compatible with existing {attachmentType} attachment `{attachmentType}` of type `{attachmentResourceType}` at index `{attachmentResourceIndex}` with TextureUVOrigin `{attachmentOrigin}`";
internal static string IncompatibleTextureUVOriginUseTexture(TextureUVOriginSelection origin) =>
$"UseTexture() of a resource with `{origin}` is not compatible with Unity's standard UV origin for texture reading {TextureUVOrigin.BottomLeft}. Are you trying to UseTexture() on a backbuffer?";
internal static string DepthInputAttachmentNotEnabled(string passName) =>
$"In pass '{passName}' when trying to call SetInputAttachment() with a depth texture - " +
$"This requires calling builder.SetExtendedFeatureFlags(ExtendedFeatureFlags.DepthAttachmentAsInputAttachment) first. " +
$"The extended feature flag was not set before using depth as input attachment.";
internal static string DepthInputAttachmentNotSupported(string passName) =>
$"In pass '{passName}' - " +
$"Read-Only depth attachment as input attachment is not supported on the current platform. " +
$"Platform: {SystemInfo.graphicsDeviceType}. " +
$"Use SystemInfo.supportsDepthAttachmentAsInputAttachment to check support at runtime.";
internal static string DepthInputAttachmentWithWriteAccess(string passName) =>
$"In pass '{passName}' - " +
$"Depth attachment has Write access but ExtendedFeatureFlags.DepthAttachmentAsInputAttachment is set." +
$"Depth input attachment must be read-only. Remove write access from the depth attachment.";
internal static string DepthInputAttachmentWithInvalidIndex(string passName) =>
$"In pass '{passName}' - " +
$"Depth attachment must be set to index 0 when ExtendedFeatureFlags.DepthAttachmentAsInputAttachment is set.";
internal static string DepthInputAttachmentWithColorFormat(string passName) =>
$"In pass '{passName}' - " +
$"Color attachment is set to index 0 but ExtendedFeatureFlags.DepthAttachmentAsInputAttachment is set. " +
$"Index 0 is reserved for the depth when the flag is set. Remove the extended feature flag or set a depth attachment";
// 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_MultisampledShaderResolveInvalidAttachmentSetup =
"Low level rendergraph error: last subpass with shader resolve must have one color attachment.";
internal const string k_MultisampledShaderResolveInputAttachmentNotMemoryless =
"Low level rendergraph error: last subpass with shader resolve must have all input attachments as memoryless attachments.";
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 IncompatibleTextureUVOriginStore(string firstAttachmentName, TextureUVOriginSelection firstAttachmentOrigin, string secondAttachmentName, TextureUVOriginSelection secondAttachmentOrigin) =>
$"Texture attachment {firstAttachmentName} with uv origin {firstAttachmentOrigin} does not match with texture attachment {secondAttachmentName} with uv origin {secondAttachmentOrigin}. Storing both would result in contents being flipped.";
internal static string GetExceptionMessage(RenderGraphState state)
{
string caller = GetHigherCaller();
if (!m_RenderGraphStateMessages.TryGetValue(state, out var messageException))
{
return enableCaller ? $"[{caller}] {k_ErrorDefaultMessage}" : k_ErrorDefaultMessage;
}
return enableCaller ? $"[{caller}] {messageException}" : messageException;
}
static string GetHigherCaller()
{
// k_CurrentStackCaller is used here to skip three levels in the call stack:
// Level 0: GetHigherCaller() itself.
// Level 1: GetExceptionMessage() or any other wrapper method that calls GetHigherCaller().
// Level 2: The function that directly calls GetMessage() (e.g CheckNotUsedWhenExecute).
// Level 3: The actual function we are interested in, our public API.
const int k_CurrentStackCaller = 3;
var stackTrace = new StackTrace(k_CurrentStackCaller, false);
if (stackTrace.FrameCount > 0)
{
var frame = stackTrace.GetFrame(0);
return frame?.GetMethod()?.Name ?? "UnknownCaller";
}
return "UnknownCaller";
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f658c411e0892ba499e17093373f687b
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: cf3029352c65c3e4a9ac9d889fd86f6d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,709 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using UnityEngine.Experimental.Rendering;
using static UnityEngine.Rendering.RenderGraphModule.RenderGraphValidationLayer;
using static UnityEngine.Rendering.RenderGraphModule.RenderGraph;
namespace UnityEngine.Rendering.RenderGraphModule
{
// This is a class making it a struct wouldn't help as we pas it around as an interface which means it would be boxed/unboxed anyway
// Publicly this class has different faces to help the users with different pass types through type safety but internally
// we just have a single implementation for all builders
internal class RenderGraphBuilders : IBaseRenderGraphBuilder, IComputeRenderGraphBuilder, IRasterRenderGraphBuilder, IUnsafeRenderGraphBuilder
{
RenderGraphPass m_RenderPass;
RenderGraphResourceRegistry m_Resources;
RenderGraph m_RenderGraph;
RenderGraphValidationLayer m_AdditionalValidationLayer;
bool m_Disposed;
public RenderGraphBuilders()
{
m_RenderPass = null;
m_Resources = null;
m_RenderGraph = null;
m_AdditionalValidationLayer = null;
m_Disposed = true;
}
internal RenderGraphValidationLayer additionalValidationLayer
{
// By design we don't allow the validation during release. This limits the usage to strictly validation and not actual runtime behavior.
#if UNITY_ENABLE_CHECKS
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return (RenderGraph.enableValidityChecks)? m_AdditionalValidationLayer : null; }
#else
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return null; }
#endif
}
public void Setup(RenderGraphPass renderPass, RenderGraphResourceRegistry resources, RenderGraph renderGraph, RenderGraphValidationLayer validationLayer)
{
#if UNITY_ENABLE_CHECKS
// If the object is not disposed yet this is an error as the pass is not finished (only in the dispose we register it with the rendergraph)
// 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(RenderGraph.RenderGraphExceptionMessages.k_UndisposedBuilderPreviousPass);
}
#endif
m_RenderPass = renderPass;
m_Resources = resources;
m_RenderGraph = renderGraph;
m_AdditionalValidationLayer = validationLayer;
m_Disposed = false;
renderPass.useAllGlobalTextures = false;
if (renderPass.type == RenderGraphPassType.Raster)
{
CommandBuffer.ThrowOnSetRenderTarget = true;
}
#if UNITY_ENABLE_CHECKS
if (additionalValidationLayer != null)
{
RenderPassInfo info = new()
{
type = renderPass.type,
name = renderPass.name
};
additionalValidationLayer.OnPassAddedBegin(in info);
}
#endif
}
[Conditional("UNITY_ENABLE_CHECKS")]
private void CheckInputAttachment(int index, bool isDepth)
{
if (RenderGraph.enableValidityChecks)
{
if (isDepth)
{
// Check ExtendedFeatureFlags
if (!m_RenderPass.extendedFeatureFlags.HasFlag(ExtendedFeatureFlags.DepthAttachmentAsInputAttachment))
{
throw new InvalidOperationException(
RenderGraphExceptionMessages.DepthInputAttachmentNotEnabled(m_RenderPass.name));
}
// Check Systeminfo
if (!SystemInfo.supportsDepthAttachmentAsInputAttachment)
{
throw new InvalidOperationException(
RenderGraphExceptionMessages.DepthInputAttachmentNotSupported(m_RenderPass.name));
}
// Check Index.
if (index != 0)
{
throw new InvalidOperationException(
RenderGraphExceptionMessages.DepthInputAttachmentWithInvalidIndex(m_RenderPass.name));
}
}
else
{
// Check invalid input attachment use case for color
if (m_RenderPass.extendedFeatureFlags.HasFlag(ExtendedFeatureFlags.DepthAttachmentAsInputAttachment) && index == 0)
{
throw new InvalidOperationException(
RenderGraphExceptionMessages.DepthInputAttachmentWithColorFormat(m_RenderPass.name));
}
}
}
}
public void EnableAsyncCompute(bool value)
{
m_RenderPass.EnableAsyncCompute(value);
}
public void AllowPassCulling(bool value)
{
// This pass cannot be culled if it allows global state modifications
if (value && m_RenderPass.allowGlobalState)
return;
m_RenderPass.AllowPassCulling(value);
}
public void AllowGlobalStateModification(bool value)
{
m_RenderPass.AllowGlobalState(value);
// This pass cannot be culled if it allows global state modifications
if (value)
{
AllowPassCulling(false);
}
}
/// <summary>
/// Enable foveated rendering for this pass.
/// </summary>
/// <param name="value">True to enable foveated rendering.</param>
public void EnableFoveatedRasterization(bool value)
{
m_RenderPass.EnableFoveatedRasterization(value);
}
public BufferHandle CreateTransientBuffer(in BufferDesc desc)
{
var result = m_Resources.CreateBuffer(desc, m_RenderPass.index);
UseTransientResource(result.handle);
return result;
}
public BufferHandle CreateTransientBuffer(in BufferHandle computebuffer)
{
ref readonly var desc = ref m_Resources.GetBufferResourceDesc(computebuffer.handle);
return CreateTransientBuffer(desc);
}
public TextureHandle CreateTransientTexture(in TextureDesc desc)
{
var result = m_Resources.CreateTexture(desc, m_RenderPass.index);
UseTransientResource(result.handle);
return result;
}
public TextureHandle CreateTransientTexture(in TextureHandle texture)
{
ref readonly var desc = ref m_Resources.GetTextureResourceDesc(texture.handle);
return CreateTransientTexture(desc);
}
public void GenerateDebugData(bool value)
{
m_RenderPass.GenerateDebugData(value);
}
public void Dispose()
{
Dispose(true);
}
protected virtual void Dispose(bool disposing)
{
if (m_Disposed)
return;
try
{
if (disposing)
{
m_RenderGraph.RenderGraphState = RenderGraphState.RecordingGraph;
#if UNITY_ENABLE_CHECKS
additionalValidationLayer?.OnPassAddedDispose();
#endif
// Use all globals simply means this... we do a UseTexture on all globals so the pass has the correct dependencies.
// This of course goes to show how bad an idea shader-system wide globals really are dependency/lifetime tracking wise :-)
if (m_RenderPass.useAllGlobalTextures)
{
foreach (var texture in m_RenderGraph.AllGlobals())
{
if (texture.IsValid())
this.UseTexture(texture, AccessFlags.Read);
}
}
// Set globals on the graph fronted side so subsequent passes can have pass dependencies on these global texture handles
foreach (var t in m_RenderPass.setGlobalsList)
{
m_RenderGraph.SetGlobal(t.Item1, t.Item2);
}
}
}
finally
{
if (m_RenderPass.type == RenderGraphPassType.Raster)
{
CommandBuffer.ThrowOnSetRenderTarget = false;
}
m_RenderPass = null;
m_Resources = null;
m_RenderGraph = null;
m_AdditionalValidationLayer = null;
m_Disposed = true;
}
}
[Conditional("UNITY_ENABLE_CHECKS")]
private void CheckWriteTo(in ResourceHandle handle)
{
if (RenderGraph.enableValidityChecks)
{
// Write by design generates a new version of the resource. However
// you could in theory write to v2 of the resource while there is already
// a v3 so this write would then introduce a new v4 of the resource.
// This would mean a divergence in the versioning history subsequent versions based on v2 and other subsequent versions based on v3
// this would be very confusing as they are all still refered to by the same texture just different versions
// so we decide to disallow this. It can always be (at zero cost) handled by using a "Move" pass to move the divergent version
// so it's own texture resource which again has it's own single history of versions.
if (handle.IsVersioned)
{
var name = m_Resources.GetRenderGraphResourceName(handle);
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))
{
// We bump the version and write count if you call USeResource with writing flags. So calling this several times
// would lead to the side effect of new versions for every call to UseResource leading to incorrect versions.
// In theory we could detect and ignore the second UseResource but we decided to just disallow is as it might also
// Stem from user confusion.
// It seems the most likely cause of such a situation would be something like:
// TextureHandle b = a;
// ...
// much much code in between, user lost track that a=b
// ...
// builder.WriteTexture(a)
// builder.WriteTexture(b)
// > 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($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type {handle.type} at index {handle.index} - " + RenderGraph.RenderGraphExceptionMessages.k_WriteToResourceTwice);
}
}
}
// Lifetime of a transient resource is one render graph pass
private ResourceHandle UseTransientResource(in ResourceHandle inputHandle)
{
CheckResource(inputHandle);
ResourceHandle versionedHandle = inputHandle.IsVersioned ? inputHandle : m_Resources.GetLatestVersionHandle(inputHandle);
// Transient resources are always considered written and read in the render graph pass where they are used
// Compiler will take it into account later, no need to add them to read and write lists
m_RenderPass.AddTransientResource(versionedHandle);
return versionedHandle;
}
private ResourceHandle UseResource(in ResourceHandle inputHandle, AccessFlags flags)
{
CheckResource(inputHandle);
bool discard = (flags & AccessFlags.Discard) != 0;
bool read = (flags & AccessFlags.Read) != 0;
bool write = (flags & AccessFlags.Write) != 0;
ResourceHandle versionedHandle = inputHandle.IsVersioned ? inputHandle : m_Resources.GetLatestVersionHandle(inputHandle);
// If we are not discarding the current version and its data, add a "read" dependency on it
// this is a bit of a misnomer it really means more like "Preserve existing content or read"
if (!discard)
{
m_Resources.IncrementReadCount(versionedHandle);
m_RenderPass.AddResourceRead(versionedHandle);
// Implicit read - not user-specified
if (!read)
{
m_RenderPass.implicitReadsList.Add(versionedHandle);
}
}
else
{
// We are discarding it but we still read it, so we add a dependency on version "0" of this resource
if (read)
{
var zeroVersionHandle = m_Resources.GetZeroVersionHandle(versionedHandle);
m_Resources.IncrementReadCount(zeroVersionHandle);
m_RenderPass.AddResourceRead(zeroVersionHandle);
}
}
if (write)
{
CheckWriteTo(inputHandle);
// New versioned written by this render graph pass
versionedHandle = m_Resources.IncrementWriteCount(inputHandle);
m_RenderPass.AddResourceWrite(versionedHandle);
}
return versionedHandle;
}
public BufferHandle UseBuffer(in BufferHandle input, AccessFlags flags)
{
#if UNITY_ENABLE_CHECKS
additionalValidationLayer?.UseBuffer(input, flags);
#endif
UseResource(input.handle, flags);
return input;
}
// UseTexture and SetRenderAttachment are currently forced to be mutually exclusive in the same pass
// check this.
// We currently ignore the version. In theory there might be some cases that are actually allowed with versioning
// for ample UseTexture(myTexV1, read) UseFragment(myTexV2, ReadWrite) as they are different versions
// but for now we don't allow any of that.
[Conditional("UNITY_ENABLE_CHECKS")]
private void CheckNotUseFragment(in TextureHandle tex)
{
if (RenderGraph.enableValidityChecks)
{
bool usedAsFragment = (m_RenderPass.depthAccess.textureHandle.IsValid() && m_RenderPass.depthAccess.textureHandle.handle.index == tex.handle.index);
if (!usedAsFragment)
{
for (int i = 0; i <= m_RenderPass.colorBufferMaxIndex; i++)
{
if (m_RenderPass.colorBufferAccess[i].textureHandle.IsValid() && m_RenderPass.colorBufferAccess[i].textureHandle.handle.index == tex.handle.index)
{
usedAsFragment = true;
break;
}
}
}
if (usedAsFragment)
{
var name = m_Resources.GetRenderGraphResourceName(tex.handle);
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);
}
}
}
[Conditional("UNITY_ENABLE_CHECKS")]
private void CheckTextureUVOriginIsValid(in ResourceHandle handle, TextureResource texRes)
{
if (texRes.textureUVOrigin == TextureUVOriginSelection.TopLeft)
{
var name = m_Resources.GetRenderGraphResourceName(handle);
throw new ArgumentException($"In pass '{m_RenderPass.name}' when trying to use resource '{name}' of type `{handle.type}` at index `{handle.index}` - " + RenderGraph.RenderGraphExceptionMessages.IncompatibleTextureUVOriginUseTexture(texRes.textureUVOrigin));
}
}
public void UseTexture(in TextureHandle input, AccessFlags flags)
{
#if UNITY_ENABLE_CHECKS
additionalValidationLayer?.UseTexture(input, flags);
#endif
CheckNotUseFragment(input);
UseResource(input.handle, flags);
if ((flags & AccessFlags.Read) == AccessFlags.Read)
{
if (m_RenderGraph.renderTextureUVOriginStrategy == RenderTextureUVOriginStrategy.PropagateAttachmentOrientation)
{
TextureResource texRes = m_Resources.GetTextureResource(input.handle);
CheckTextureUVOriginIsValid(input.handle, texRes);
texRes.textureUVOrigin = TextureUVOriginSelection.BottomLeft;
}
}
}
public void UseGlobalTexture(int propertyId, AccessFlags flags)
{
#if UNITY_ENABLE_CHECKS
additionalValidationLayer?.UseGlobalTexture(propertyId, flags);
#endif
var h = m_RenderGraph.GetGlobal(propertyId);
if (h.IsValid())
{
UseTexture(h, flags);
}
else
{
// 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));
}
}
public void UseAllGlobalTextures(bool enable)
{
#if UNITY_ENABLE_CHECKS
additionalValidationLayer?.UseAllGlobalTextures(enable);
#endif
m_RenderPass.useAllGlobalTextures = enable;
}
public void SetGlobalTextureAfterPass(in TextureHandle input, int propertyId)
{
#if UNITY_ENABLE_CHECKS
additionalValidationLayer?.SetGlobalTextureAfterPass(input, propertyId);
#endif
m_RenderPass.setGlobalsList.Add(ValueTuple.Create(input, propertyId));
}
// Shared validation between SetRenderAttachment/SetRenderAttachmentDepth
[Conditional("UNITY_ENABLE_CHECKS")]
private void CheckUseFragment(in TextureHandle tex, bool isDepth)
{
if (RenderGraph.enableValidityChecks)
{
// We ignore the version as we don't allow mixing UseTexture/UseFragment between different versions
// even though it should theoretically work (and we might do so in the future) for now we're overly strict.
bool alreadyUsed = false;
//TODO: Check grab textures here and allow if it's grabbed. For now
// SetRenderAttachment()
// UseTexture(grab)
// will work but not the other way around
for (int i = 0; i < m_RenderPass.resourceReadLists[tex.handle.iType].Count; i++)
{
if (m_RenderPass.resourceReadLists[tex.handle.iType][i].index == tex.handle.index)
{
alreadyUsed = true;
break;
}
}
for (int i = 0; i < m_RenderPass.resourceWriteLists[tex.handle.iType].Count; i++)
{
if (m_RenderPass.resourceWriteLists[tex.handle.iType][i].index == tex.handle.index)
{
alreadyUsed = true;
break;
}
}
if (alreadyUsed)
{
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_SetRenderAttachmentTextureAlreadyUsed);
}
m_Resources.GetRenderTargetInfo(tex.handle, out var info);
bool isDepthFormat = GraphicsFormatUtility.IsDepthFormat(info.format);
bool formatMismatch = isDepth != isDepthFormat;
if (formatMismatch)
{
var name = m_Resources.GetRenderGraphResourceName(tex.handle);
var errorMsg = isDepth
? RenderGraph.RenderGraphExceptionMessages.UseDepthWithColorFormat(info.format)
: RenderGraph.RenderGraphExceptionMessages.k_SetRenderAttachmentOnDepthTexture;
throw new InvalidOperationException(
$"In pass '{m_RenderPass.name}' when trying to use resource '{name}' " +
$"of type {tex.handle.type} at index {tex.handle.index} - {errorMsg}");
}
if (m_RenderGraph.renderTextureUVOriginStrategy == RenderTextureUVOriginStrategy.PropagateAttachmentOrientation)
{
var texResource = m_Resources.GetTextureResource(tex.handle);
TextureResource checkTexResource = null;
for (int i = 0; i < m_RenderPass.fragmentInputMaxIndex + 1; ++i)
{
if (m_RenderPass.fragmentInputAccess[i].textureHandle.IsValid())
{
ref readonly TextureHandle texCheck = ref m_RenderPass.fragmentInputAccess[i].textureHandle;
checkTexResource = m_Resources.GetTextureResource(texCheck.handle);
if (texResource.textureUVOrigin != TextureUVOriginSelection.Unknown && checkTexResource.textureUVOrigin != TextureUVOriginSelection.Unknown && texResource.textureUVOrigin != checkTexResource.textureUVOrigin)
{
var name = m_Resources.GetRenderGraphResourceName(tex.handle);
var checkName = m_Resources.GetRenderGraphResourceName(texCheck.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.IncompatibleTextureUVOrigin(texResource.textureUVOrigin, "input", checkName, texCheck.handle.type, texCheck.handle.index, checkTexResource.textureUVOrigin));
}
}
}
for (int i = 0; i < m_RenderPass.colorBufferMaxIndex + 1; ++i)
{
if (m_RenderPass.colorBufferAccess[i].textureHandle.IsValid())
{
ref readonly TextureHandle texCheck = ref m_RenderPass.colorBufferAccess[i].textureHandle;
checkTexResource = m_Resources.GetTextureResource(texCheck.handle);
if (texResource.textureUVOrigin != TextureUVOriginSelection.Unknown && checkTexResource.textureUVOrigin != TextureUVOriginSelection.Unknown && texResource.textureUVOrigin != checkTexResource.textureUVOrigin)
{
var name = m_Resources.GetRenderGraphResourceName(tex.handle);
var checkName = m_Resources.GetRenderGraphResourceName(texCheck.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.IncompatibleTextureUVOrigin(texResource.textureUVOrigin, "render", checkName, texCheck.handle.type, texCheck.handle.index, checkTexResource.textureUVOrigin));
}
}
}
if (!isDepth && m_RenderPass.depthAccess.textureHandle.IsValid())
{
TextureHandle texCheck = m_RenderPass.depthAccess.textureHandle;
checkTexResource = m_Resources.GetTextureResource(texCheck.handle);
if (texResource.textureUVOrigin != TextureUVOriginSelection.Unknown && checkTexResource.textureUVOrigin != TextureUVOriginSelection.Unknown && texResource.textureUVOrigin != checkTexResource.textureUVOrigin)
{
var name = m_Resources.GetRenderGraphResourceName(tex.handle);
var checkName = m_Resources.GetRenderGraphResourceName(texCheck.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.IncompatibleTextureUVOrigin(texResource.textureUVOrigin, "depth", checkName, texCheck.handle.type, texCheck.handle.index, checkTexResource.textureUVOrigin));
}
}
}
foreach (var globalTex in m_RenderPass.setGlobalsList)
{
if (globalTex.Item1.handle.index == tex.handle.index)
{
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);
}
}
}
}
public void SetRenderAttachment(TextureHandle tex, int index, AccessFlags flags, int mipLevel, int depthSlice)
{
#if UNITY_ENABLE_CHECKS
additionalValidationLayer?.SetRenderAttachment(tex, index, flags, mipLevel, depthSlice);
#endif
CheckUseFragment(tex, false);
var versionedTextureHandle = new TextureHandle(UseResource(tex.handle, flags));
m_RenderPass.SetColorBufferRaw(versionedTextureHandle, index, flags, mipLevel, depthSlice);
}
public void SetInputAttachment(TextureHandle tex, int index, AccessFlags flags, int mipLevel, int depthSlice)
{
#if UNITY_ENABLE_CHECKS
additionalValidationLayer?.SetInputAttachment(tex, index, flags, mipLevel, depthSlice);
#endif
CheckFrameBufferFetchEmulationIsSupported(tex);
m_Resources.GetRenderTargetInfo(tex.handle, out var info);
if (GraphicsFormatUtility.IsDepthFormat(info.format))
{
CheckInputAttachment(index, true);
CheckUseFragment(tex, true);
}
else
{
CheckInputAttachment(index, false);
CheckUseFragment(tex, false);
}
var versionedTextureHandle = new TextureHandle(UseResource(tex.handle, flags));
m_RenderPass.SetFragmentInputRaw(versionedTextureHandle, index, flags, mipLevel, depthSlice);
}
public void SetRenderAttachmentDepth(TextureHandle tex, AccessFlags flags, int mipLevel, int depthSlice)
{
#if UNITY_ENABLE_CHECKS
additionalValidationLayer?.SetRenderAttachmentDepth(tex, flags, mipLevel, depthSlice);
#endif
CheckUseFragment(tex, true);
var versionedTextureHandle = new TextureHandle(UseResource(tex.handle, flags));
m_RenderPass.SetDepthBufferRaw(versionedTextureHandle, flags, mipLevel, depthSlice);
}
public TextureHandle SetRandomAccessAttachment(TextureHandle input, int index, AccessFlags flags = AccessFlags.Read)
{
CheckNotUseFragment(input);
ResourceHandle result = UseResource(input.handle, flags);
m_RenderPass.SetRandomWriteResourceRaw(result, index, false, flags);
return input;
}
public void SetShadingRateImageAttachment(in TextureHandle tex)
{
CheckNotUseFragment(tex);
var versionedTextureHandle = new TextureHandle(UseResource(tex.handle, AccessFlags.Read));
m_RenderPass.SetShadingRateImageRaw(versionedTextureHandle);
}
public BufferHandle UseBufferRandomAccess(BufferHandle input, int index, AccessFlags flags = AccessFlags.Read)
{
var h = UseBuffer(input, flags);
m_RenderPass.SetRandomWriteResourceRaw(h.handle, index, true, flags);
return input;
}
public BufferHandle UseBufferRandomAccess(BufferHandle input, int index, bool preserveCounterValue, AccessFlags flags = AccessFlags.Read)
{
var h = UseBuffer(input, flags);
m_RenderPass.SetRandomWriteResourceRaw(h.handle, index, preserveCounterValue, flags);
return input;
}
public void SetRenderFunc<PassData>(BaseRenderFunc<PassData, ComputeGraphContext> renderFunc) where PassData : class, new()
{
((ComputeRenderGraphPass<PassData>)m_RenderPass).renderFunc = renderFunc;
}
public void SetRenderFunc<PassData>(BaseRenderFunc<PassData, RasterGraphContext> renderFunc) where PassData : class, new()
{
((RasterRenderGraphPass<PassData>)m_RenderPass).renderFunc = renderFunc;
}
public void SetRenderFunc<PassData>(BaseRenderFunc<PassData, UnsafeGraphContext> renderFunc) where PassData : class, new()
{
((UnsafeRenderGraphPass<PassData>)m_RenderPass).renderFunc = renderFunc;
}
public void UseRendererList(in RendererListHandle input)
{
m_RenderPass.UseRendererList(input);
}
[Conditional("UNITY_ENABLE_CHECKS")]
void CheckResource(in ResourceHandle res, bool checkTransientReadWrite = false)
{
if (RenderGraph.enableValidityChecks)
{
if (res.IsValid())
{
int transientIndex = m_Resources.GetRenderGraphResourceTransientIndex(res);
// 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)
{
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)
{
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
{
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);
}
}
}
[Conditional("UNITY_ENABLE_CHECKS")]
void CheckFrameBufferFetchEmulationIsSupported(in TextureHandle tex)
{
if (enableValidityChecks)
{
if (!Util.RenderGraphUtils.IsFramebufferFetchEmulationMSAASupportedOnCurrentPlatform())
{
var sourceInfo = m_RenderGraph.GetRenderTargetInfo(tex);
if (sourceInfo.bindMS)
throw new InvalidOperationException($"This API is not supported with MSAA attachments on the current platform: {SystemInfo.graphicsDeviceType}");
}
}
}
public void SetShadingRateFragmentSize(ShadingRateFragmentSize shadingRateFragmentSize)
{
m_RenderPass.SetShadingRateFragmentSize(shadingRateFragmentSize);
}
public void SetShadingRateCombiner(ShadingRateCombinerStage stage, ShadingRateCombiner combiner)
{
m_RenderPass.SetShadingRateCombiner(stage, combiner);
}
public void SetExtendedFeatureFlags(ExtendedFeatureFlags extendedFeatureFlags)
{
m_RenderPass.SetExtendedFeatureFlags(extendedFeatureFlags);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2fe060d1424425e4ebdada331c03d400
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,130 @@
using System.Collections.Generic;
using UnityEngine.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
using UnityEngine.Rendering.RenderGraphModule.NativeRenderPassCompiler;
class RenderGraphCompilationCache
{
struct HashEntry<T>
{
public int hash;
public int lastFrameUsed;
public T compiledGraph;
}
DynamicArray<HashEntry<CompilerContextData>> m_NativeHashEntries = new();
Stack<CompilerContextData> m_NativeCompiledGraphPool = new();
static int HashEntryComparer<T>(HashEntry<T> a, HashEntry<T> b)
{
if (a.lastFrameUsed < b.lastFrameUsed)
return -1;
else if (a.lastFrameUsed > b.lastFrameUsed)
return 1;
else
return 0;
}
static readonly DynamicArray<HashEntry<CompilerContextData>>.SortComparer s_NativeEntryComparer = HashEntryComparer<CompilerContextData>;
const int k_CachedGraphCount = 20;
public RenderGraphCompilationCache()
{
for (int i = 0; i < k_CachedGraphCount; ++i)
{
m_NativeCompiledGraphPool.Push(new CompilerContextData());
}
}
// Looping manually instead of using DynamicArray.FindIndex to avoid GC caused by the lambda capture of the hash
static int FindHashEntryIndex(DynamicArray<HashEntry<CompilerContextData>> hashEntries, int hash)
{
for (int i = 0; i < hashEntries.size; ++i)
{
if (hashEntries[i].hash == hash)
return i;
}
return -1;
}
bool GetCompilationCache(int hash, int frameIndex, out CompilerContextData outGraph, DynamicArray<HashEntry<CompilerContextData>> hashEntries, Stack<CompilerContextData> pool, DynamicArray<HashEntry<CompilerContextData>>.SortComparer comparer)
{
int index = FindHashEntryIndex(hashEntries, hash);
if (index != -1)
{
ref var entry = ref hashEntries[index];
outGraph = entry.compiledGraph;
entry.lastFrameUsed = frameIndex;
return true;
}
else
{
if (pool.Count != 0)
{
var newEntry = new HashEntry<CompilerContextData>()
{
hash = hash,
lastFrameUsed = frameIndex,
compiledGraph = pool.Pop()
};
hashEntries.Add(newEntry);
outGraph = newEntry.compiledGraph;
return false;
}
else
{
// Reuse the oldest one.
hashEntries.QuickSort(comparer);
ref var oldestEntry = ref hashEntries[0];
oldestEntry.hash = hash;
oldestEntry.lastFrameUsed = frameIndex;
oldestEntry.compiledGraph.Clear();
outGraph = oldestEntry.compiledGraph;
return false;
}
}
}
public bool GetCompilationCache(int hash, int frameIndex, out CompilerContextData outGraph)
{
return GetCompilationCache(hash, frameIndex, out outGraph, m_NativeHashEntries, m_NativeCompiledGraphPool, s_NativeEntryComparer);
}
public void Clear()
{
for (int i = 0; i < m_NativeHashEntries.size; ++i)
{
var compiledGraph = m_NativeHashEntries[i].compiledGraph;
compiledGraph.Clear();
m_NativeCompiledGraphPool.Push(compiledGraph);
}
m_NativeHashEntries.Clear();
}
public void Cleanup()
{
// We clear the contents of the pools but not the pool themselves, because they are only
// filled at the beginning of the renderer pipeline and never after. This means when we call
// Cleanup() after an error, if we were clearing the pools, the render graph could not gracefully start
// back up because the cache would have a size of 0 (so no room to cache anything).
// Dispose of CompilerContextData currently in the cache
for (int i = 0; i < m_NativeHashEntries.size; ++i)
{
var compiledGraph = m_NativeHashEntries[i].compiledGraph;
compiledGraph.Dispose();
}
m_NativeHashEntries.Clear();
// Dispose of CompilerContextData that might be left in the pool
var nativeCompiledGraphs = m_NativeCompiledGraphPool.ToArray();
for (int i = 0; i < nativeCompiledGraphs.Length; ++i)
{
nativeCompiledGraphs[i].Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2d61c9446fb9f3c40886545e36cac282
@@ -0,0 +1,95 @@
using UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.Rendering.RenderGraphModule
{
/// <summary>
/// Helper class allowing access to default resources (black or white texture, etc.) during render passes.
/// </summary>
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public class RenderGraphDefaultResources
{
// We need to keep around a RTHandle version of default regular 2D textures since RenderGraph API is all RTHandle.
RTHandle m_BlackTexture2D;
RTHandle m_WhiteTexture2D;
RTHandle m_ShadowTexture2D;
/// <summary>Default black 2D texture.</summary>
public TextureHandle blackTexture { get; private set; }
/// <summary>Default white 2D texture.</summary>
public TextureHandle whiteTexture { get; private set; }
/// <summary>Default clear color XR 2D texture.</summary>
public TextureHandle clearTextureXR { get; private set; }
/// <summary>Default magenta XR 2D texture.</summary>
public TextureHandle magentaTextureXR { get; private set; }
/// <summary>Default black XR 2D texture.</summary>
public TextureHandle blackTextureXR { get; private set; }
/// <summary>Default black XR 2D Array texture.</summary>
public TextureHandle blackTextureArrayXR { get; private set; }
/// <summary>Default black (UInt) XR 2D texture.</summary>
public TextureHandle blackUIntTextureXR { get; private set; }
/// <summary>Default black XR 3D texture.</summary>
public TextureHandle blackTexture3DXR { get; private set; }
/// <summary>Default white XR 2D texture.</summary>
public TextureHandle whiteTextureXR { get; private set; }
/// <summary>Default 1x1 shadow texture.</summary>
public TextureHandle defaultShadowTexture { get; private set; }
internal RenderGraphDefaultResources()
{
InitDefaultResourcesIfNeeded();
}
private void InitDefaultResourcesIfNeeded()
{
if (m_BlackTexture2D == null)
m_BlackTexture2D = RTHandles.Alloc(Texture2D.blackTexture);
if (m_WhiteTexture2D == null)
m_WhiteTexture2D = RTHandles.Alloc(Texture2D.whiteTexture);
if (m_ShadowTexture2D == null)
{
m_ShadowTexture2D = RTHandles.Alloc(1, 1, CoreUtils.GetDefaultDepthOnlyFormat(), isShadowMap: true, name: "DefaultShadowTexture");
// Fill the shadow texture with the default (far-plane) depth value for the current platform.
CommandBuffer cmd = CommandBufferPool.Get();
cmd.SetRenderTarget(m_ShadowTexture2D);
cmd.ClearRenderTarget(RTClearFlags.All, Color.white);
Graphics.ExecuteCommandBuffer(cmd);
CommandBufferPool.Release(cmd);
}
}
internal void Cleanup()
{
m_BlackTexture2D?.Release();
m_BlackTexture2D = null;
m_WhiteTexture2D?.Release();
m_WhiteTexture2D = null;
m_ShadowTexture2D?.Release();
m_ShadowTexture2D = null;
}
internal void InitializeForRendering(RenderGraph renderGraph)
{
InitDefaultResourcesIfNeeded();
blackTexture = renderGraph.ImportTexture(m_BlackTexture2D, true);
whiteTexture = renderGraph.ImportTexture(m_WhiteTexture2D, true);
defaultShadowTexture = renderGraph.ImportTexture(m_ShadowTexture2D, true);
if (!TextureXR.initialized)
return;
clearTextureXR = renderGraph.ImportTexture(TextureXR.GetClearTexture(), true);
magentaTextureXR = renderGraph.ImportTexture(TextureXR.GetMagentaTexture(), true);
blackTextureXR = renderGraph.ImportTexture(TextureXR.GetBlackTexture(), true);
blackTextureArrayXR = renderGraph.ImportTexture(TextureXR.GetBlackTextureArray(), true);
blackUIntTextureXR = renderGraph.ImportTexture(TextureXR.GetBlackUIntTexture(), true);
blackTexture3DXR = renderGraph.ImportTexture(TextureXR.GetBlackTexture3D(), true);
whiteTextureXR = renderGraph.ImportTexture(TextureXR.GetWhiteTexture(), true);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d9929b63696b16c4ca41927306959897
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,72 @@
using System;
namespace UnityEngine.Rendering
{
/// <summary>
/// A graphics settings container for settings related to the Render Graph for all Scriptable Render Pipelines.
/// </summary>
/// <remarks>
/// To change those settings, go to Editor > Project Settings in the Graphics tab.
/// Changing this through the API is only allowed in the Editor. In the Player, this raises an error.
/// </remarks>
/// <seealso cref="IRenderPipelineGraphicsSettings"/>
/// <example>
/// <para> This example demonstrates how to determine if your project uses RenderGraph's compilation caching. </para>
/// <code>
/// using UnityEngine.Rendering;
///
/// public static class RenderGraphHelper
/// {
/// public static bool enableCompilationCaching
/// {
/// get
/// {
/// var gs = GraphicsSettings.GetRenderPipelineSettings&lt;RenderGraphGlobalSettings&gt;();
/// if (gs == null) //not in SRP
/// return false;
/// return gs.enableCompilationCaching;
/// }
/// }
/// }
/// </code>
/// </example>
[Serializable]
[SupportedOnRenderPipeline]
[Categorization.CategoryInfo(Name = "Render Graph", Order = 50)]
[Categorization.ElementInfo(Order = 0)]
public class RenderGraphGlobalSettings : IRenderPipelineGraphicsSettings
{
enum Version
{
Initial,
Count,
Last = Count - 1
}
bool IRenderPipelineGraphicsSettings.isAvailableInPlayerBuild => true;
[SerializeField, HideInInspector]
private Version m_version = Version.Last;
int IRenderPipelineGraphicsSettings.version => (int)m_version;
[RecreatePipelineOnChange , SerializeField, Tooltip("Enable caching of render graph compilation from one frame to another.")]
private bool m_EnableCompilationCaching = true;
/// <summary>Enable Compilation caching for render graph.</summary>
public bool enableCompilationCaching
{
get => m_EnableCompilationCaching;
set => this.SetValueAndNotify(ref m_EnableCompilationCaching, value);
}
[RecreatePipelineOnChange , SerializeField, Tooltip("Enable validity checks of render graph in Editor and Development mode. Always disabled in Release build.")]
private bool m_EnableValidityChecks = true;
/// <summary>Enable validity checks for render graph. Always disabled in Release mode.</summary>
public bool enableValidityChecks
{
get => m_EnableValidityChecks;
set => this.SetValueAndNotify(ref m_EnableValidityChecks, value);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fd759b62892071040858aa540b5340b4
@@ -0,0 +1,153 @@
using System;
using System.Collections.Generic;
namespace UnityEngine.Rendering.RenderGraphModule
{
/// <summary>
/// Helper class provided in the RenderGraphContext to all Render Passes.
/// It allows you to do temporary allocations of various objects during a Render Pass.
/// </summary>
public sealed class RenderGraphObjectPool
{
// Only used to clear all existing pools at once from here when needed
static readonly DynamicArray<SharedObjectPoolBase> s_AllocatedPools = new DynamicArray<SharedObjectPoolBase>();
// Non abstract class instead of an interface to store it in a DynamicArray
class SharedObjectPoolBase
{
public SharedObjectPoolBase() {}
public virtual void Clear() {}
}
class SharedObjectPool<T> : SharedObjectPoolBase where T : class, new()
{
private static readonly Pool.ObjectPool<T> s_Pool = AllocatePool();
private static Pool.ObjectPool<T> AllocatePool()
{
var newPool = new Pool.ObjectPool<T>(() => new T(), null, null);
// Storing instance to clear the static pool of the same type if needed
s_AllocatedPools.Add(new SharedObjectPool<T>());
return newPool;
}
/// <summary>
/// Clear the pool using SharedObjectPool instance.
/// </summary>
/// <returns></returns>
public override void Clear()
{
s_Pool.Clear();
}
/// <summary>
/// Get a new instance from the pool.
/// </summary>
/// <returns></returns>
public static T Get() => s_Pool.Get();
/// <summary>
/// Release an object to the pool.
/// </summary>
/// <param name="toRelease">instance to release.</param>
public static void Release(T toRelease) => s_Pool.Release(toRelease);
}
Dictionary<(Type, int), Stack<object>> m_ArrayPool = new Dictionary<(Type, int), Stack<object>>();
List<(object, (Type, int))> m_AllocatedArrays = new List<(object, (Type, int))>();
List<MaterialPropertyBlock> m_AllocatedMaterialPropertyBlocks = new List<MaterialPropertyBlock>();
internal RenderGraphObjectPool() { }
/// <summary>
/// Allocate a temporary typed array of a specific size.
/// Unity releases the array at the end of the Render Pass.
/// </summary>
/// <typeparam name="T">Type of the array to be allocated.</typeparam>
/// <param name="size">Number of element in the array.</param>
/// <returns>A new array of type T with size number of elements.</returns>
public T[] GetTempArray<T>(int size)
{
if (!m_ArrayPool.TryGetValue((typeof(T), size), out var stack))
{
stack = new Stack<object>();
m_ArrayPool.Add((typeof(T), size), stack);
}
var result = stack.Count > 0 ? (T[])stack.Pop() : new T[size];
m_AllocatedArrays.Add((result, (typeof(T), size)));
return result;
}
/// <summary>
/// Allocate a temporary MaterialPropertyBlock for the Render Pass.
/// </summary>
/// <returns>A new clean MaterialPropertyBlock.</returns>
public MaterialPropertyBlock GetTempMaterialPropertyBlock()
{
var result = SharedObjectPool<MaterialPropertyBlock>.Get();
result.Clear();
m_AllocatedMaterialPropertyBlocks.Add(result);
return result;
}
internal void ReleaseAllTempAlloc()
{
foreach (var arrayDesc in m_AllocatedArrays)
{
bool result = m_ArrayPool.TryGetValue(arrayDesc.Item2, out var stack);
Debug.Assert(result, "Correct stack type should always be allocated.");
stack.Push(arrayDesc.Item1);
}
m_AllocatedArrays.Clear();
foreach (var mpb in m_AllocatedMaterialPropertyBlocks)
{
SharedObjectPool<MaterialPropertyBlock>.Release(mpb);
}
m_AllocatedMaterialPropertyBlocks.Clear();
}
internal bool IsEmpty()
{
return m_AllocatedArrays.Count == 0 && m_AllocatedMaterialPropertyBlocks.Count == 0;
}
// Regular pooling API. Only internal use for now
internal T Get<T>() where T : class, new()
{
return SharedObjectPool<T>.Get();
}
internal void Release<T>(T value) where T : class, new()
{
SharedObjectPool<T>.Release(value);
}
internal void Cleanup()
{
m_AllocatedArrays.Clear();
m_AllocatedMaterialPropertyBlocks.Clear();
m_ArrayPool.Clear();
// Removing all objects in the pools
foreach (var pool in s_AllocatedPools)
pool.Clear();
}
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
foreach (var pool in s_AllocatedPools)
pool.Clear();
// s_AllocatedPools is populated by generic class instantiation of SharedObjectPool<T> when the static
// variable s_Pool is initialized, and won't re-register without domain reload, so it should not be cleared.
}
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: dc968a854959c7d4599914d0b01469c2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,757 @@
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Unity.Scripting.LifecycleManagement;
namespace UnityEngine.Rendering.RenderGraphModule
{
[DebuggerDisplay("RenderPass: {name} (Index:{index} Async:{enableAsyncCompute})")]
abstract class RenderGraphPass
{
public abstract void Execute(InternalRenderGraphContext renderGraphContext);
public abstract void Release(RenderGraphObjectPool pool);
public abstract bool HasRenderFunc();
public abstract int GetRenderFuncHash();
public string name { get; protected set; }
public int index { get; protected set; }
public RenderGraphPassType type { get; internal set; }
public ProfilingSampler customSampler { get; protected set; }
public bool enableAsyncCompute { get; protected set; }
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
public TextureAccess depthAccess { get; protected set; }
public TextureAccess[] colorBufferAccess { get; protected set; } = new TextureAccess[RenderGraph.kMaxMRTCount];
public int colorBufferMaxIndex { get; protected set; } = -1;
public bool hasShadingRateImage { get; protected set; }
public TextureAccess shadingRateAccess { get; protected set; }
public bool hasShadingRateStates { get; protected set; }
public ShadingRateFragmentSize shadingRateFragmentSize { get; protected set; }
public ShadingRateCombiner primitiveShadingRateCombiner { get; protected set; }
public ShadingRateCombiner fragmentShadingRateCombiner { get; protected set; }
// Used by native pass compiler only
public TextureAccess[] fragmentInputAccess { get; protected set; } = new TextureAccess[RenderGraph.kMaxMRTCount];
public int fragmentInputMaxIndex { get; protected set; } = -1;
public struct RandomWriteResourceInfo
{
public ResourceHandle h;
public bool preserveCounterValue;
}
// This list can contain both texture and buffer resources based on their binding index.
public RandomWriteResourceInfo[] randomAccessResource { get; protected set; } = new RandomWriteResourceInfo[RenderGraph.kMaxMRTCount];
public int randomAccessResourceMaxIndex { get; protected set; } = -1;
public bool generateDebugData { get; protected set; }
public bool allowRendererListCulling { get; protected set; }
public List<ResourceHandle>[] resourceReadLists = new List<ResourceHandle>[(int)RenderGraphResourceType.Count];
public List<ResourceHandle>[] resourceWriteLists = new List<ResourceHandle>[(int)RenderGraphResourceType.Count];
public List<ResourceHandle>[] transientResourceList = new List<ResourceHandle>[(int)RenderGraphResourceType.Count];
public List<RendererListHandle> usedRendererListList = new List<RendererListHandle>();
public List<ValueTuple<TextureHandle, int>> setGlobalsList = new List<ValueTuple<TextureHandle, int>>();
public bool useAllGlobalTextures;
public List<ResourceHandle> implicitReadsList = new List<ResourceHandle>();
#if UNITY_ENABLE_CHECKS
public RenderGraph.DebugData.PassScriptInfo debugScriptInfo { get; set; }
#endif
public RenderGraphPass()
{
for (int i = 0; i < (int)RenderGraphResourceType.Count; ++i)
{
resourceReadLists[i] = new List<ResourceHandle>();
resourceWriteLists[i] = new List<ResourceHandle>();
transientResourceList[i] = new List<ResourceHandle>();
}
}
public void Clear()
{
name = "";
index = -1;
customSampler = null;
for (int i = 0; i < (int)RenderGraphResourceType.Count; ++i)
{
resourceReadLists[i].Clear();
resourceWriteLists[i].Clear();
transientResourceList[i].Clear();
}
usedRendererListList.Clear();
setGlobalsList.Clear();
useAllGlobalTextures = false;
implicitReadsList.Clear();
enableAsyncCompute = false;
allowPassCulling = true;
allowRendererListCulling = true;
allowGlobalState = false;
enableFoveatedRasterization = false;
generateDebugData = true;
// Invalidate the buffers without clearing them, as it is too costly
// Use IsValid() to make sure that the data in the colorBuffer/fragmentInput/randomAccessResource buffers are up to date
colorBufferMaxIndex = -1;
fragmentInputMaxIndex = -1;
randomAccessResourceMaxIndex = -1;
// We do not need to clear colorBufferAccess and fragmentInputAccess as we have the colorBufferMaxIndex and fragmentInputMaxIndex
// which are reset above so we only clear depthAccess here.
depthAccess = default(TextureAccess);
hasShadingRateImage = false;
hasShadingRateStates = false;
shadingRateFragmentSize = ShadingRateFragmentSize.FragmentSize1x1;
primitiveShadingRateCombiner = ShadingRateCombiner.Keep;
fragmentShadingRateCombiner = ShadingRateCombiner.Keep;
// Invalidate ExtendedFeatureFlags
extendedFeatureFlags = ExtendedFeatureFlags.None;
}
// Check if the pass has any render targets set-up
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool HasRenderAttachments()
{
return depthAccess.textureHandle.IsValid() || colorBufferAccess[0].textureHandle.IsValid() || colorBufferMaxIndex > 0;
}
// Checks if the resource is involved in this pass
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsTransient(in ResourceHandle res)
{
// Versioning doesn't matter much for transient resources as they are only used within a single pass
for (int i = 0; i < transientResourceList[res.iType].Count; i++)
{
if (transientResourceList[res.iType][i].index == res.index)
{
return true;
}
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsWritten(in ResourceHandle res)
{
// You can only ever write to the latest version so we ignore it when looking in the list
for (int i = 0; i < resourceWriteLists[res.iType].Count; i++)
{
if (resourceWriteLists[res.iType][i].index == res.index)
{
return true;
}
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsRead(in ResourceHandle res)
{
if (res.IsVersioned)
{
return resourceReadLists[res.iType].Contains(res);
}
else
{
// Just look if we are reading any version of this texture.
// Note that in theory this pass could read from several versions of the same texture
// e.g. ColorBuffer,v3 and ColorBuffer,v5 so this check is always conservative
for (int i = 0; i < resourceReadLists[res.iType].Count; i++)
{
if (resourceReadLists[res.iType][i].index == res.index)
{
return true;
}
}
return false;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsAttachment(in TextureHandle res)
{
// We ignore the version when checking, if any version is used it is considered a match
if (depthAccess.textureHandle.IsValid() && depthAccess.textureHandle.handle.index == res.handle.index) return true;
for (int i = 0; i < colorBufferAccess.Length; i++)
{
if (colorBufferAccess[i].textureHandle.IsValid() && colorBufferAccess[i].textureHandle.handle.index == res.handle.index) return true;
}
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AddResourceWrite(in ResourceHandle res)
{
resourceWriteLists[res.iType].Add(res);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AddResourceRead(in ResourceHandle res)
{
resourceReadLists[res.iType].Add(res);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AddTransientResource(in ResourceHandle res)
{
transientResourceList[res.iType].Add(res);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void UseRendererList(in RendererListHandle rendererList)
{
usedRendererListList.Add(rendererList);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EnableAsyncCompute(bool value)
{
enableAsyncCompute = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AllowPassCulling(bool value)
{
allowPassCulling = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EnableFoveatedRasterization(bool value)
{
enableFoveatedRasterization = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AllowRendererListCulling(bool value)
{
allowRendererListCulling = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AllowGlobalState(bool value)
{
allowGlobalState = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void GenerateDebugData(bool value)
{
generateDebugData = value;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetColorBuffer(in TextureHandle resource, int index)
{
Debug.Assert(index < RenderGraph.kMaxMRTCount && index >= 0);
colorBufferMaxIndex = Math.Max(colorBufferMaxIndex, index);
colorBufferAccess[index] = new TextureAccess(colorBufferAccess[index], resource);
AddResourceWrite(resource.handle);
}
// Sets up the color buffer for this pass but not any resource Read/Writes for it
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetColorBufferRaw(in TextureHandle resource, int index, AccessFlags accessFlags, int mipLevel, int depthSlice)
{
Debug.Assert(index < RenderGraph.kMaxMRTCount && index >= 0);
if (colorBufferAccess[index].textureHandle.handle.Equals(resource.handle) || !colorBufferAccess[index].textureHandle.IsValid())
{
colorBufferMaxIndex = Math.Max(colorBufferMaxIndex, index);
colorBufferAccess[index] = new TextureAccess(resource, accessFlags, mipLevel, depthSlice);
}
else
{
#if UNITY_ENABLE_CHECKS
// You tried to do SetRenderAttachment(tex1, 1, ..); SetRenderAttachment(tex2, 1, ..); that is not valid for different textures on the same index
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
}
}
// Sets up the color buffer for this pass but not any resource Read/Writes for it
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetFragmentInputRaw(in TextureHandle resource, int index, AccessFlags accessFlags, int mipLevel, int depthSlice)
{
Debug.Assert(index < RenderGraph.kMaxMRTCount && index >= 0);
if (fragmentInputAccess[index].textureHandle.handle.Equals(resource.handle) || !fragmentInputAccess[index].textureHandle.IsValid())
{
fragmentInputMaxIndex = Math.Max(fragmentInputMaxIndex, index);
fragmentInputAccess[index] = new TextureAccess(resource, accessFlags, mipLevel, depthSlice);
}
else
{
#if UNITY_ENABLE_CHECKS
// You tried to do SetRenderAttachment(tex1, 1, ..); SetRenderAttachment(tex2, 1, ..); that is not valid for different textures on the same index
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
}
}
// Sets up the color buffer for this pass but not any resource Read/Writes for it
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetRandomWriteResourceRaw(in ResourceHandle resource, int index, bool preserveCounterValue, AccessFlags accessFlags)
{
Debug.Assert(index < RenderGraph.kMaxMRTCount && index >= 0);
if (randomAccessResource[index].h.Equals(resource) || !randomAccessResource[index].h.IsValid())
{
randomAccessResourceMaxIndex = Math.Max(randomAccessResourceMaxIndex, index);
ref var info = ref randomAccessResource[index];
info.h = resource;
info.preserveCounterValue = preserveCounterValue;
}
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(
$"In pass '{name}' when trying to call SetRandomAccessAttachment/UseBufferRandomAccess with resource of type {resource.type} at index {index} - " +
RenderGraph.RenderGraphExceptionMessages.k_MoreThanOneTextureRandomWriteInputIndex);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetDepthBuffer(in TextureHandle resource, DepthAccess flags)
{
depthAccess = new TextureAccess(resource, (AccessFlags)flags, 0, 0);
if ((flags & DepthAccess.Read) != 0)
AddResourceRead(resource.handle);
if ((flags & DepthAccess.Write) != 0)
AddResourceWrite(resource.handle);
}
// Sets up the depth buffer for this pass but not any resource Read/Writes for it
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void SetDepthBufferRaw(in TextureHandle resource, AccessFlags accessFlags, int mipLevel, int depthSlice)
{
// If no depth buffer yet or if it is the same one as the previous one, allow the call otherwise log an error.
if (depthAccess.textureHandle.handle.Equals(resource.handle) || !depthAccess.textureHandle.IsValid())
{
depthAccess = new TextureAccess(resource, accessFlags, mipLevel, depthSlice);
}
#if UNITY_ENABLE_CHECKS
else
{
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
}
// Here we want to keep computation to a minimum and only hash what will influence NRP compiler: Pass merging, load/store actions etc.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
void ComputeTextureHash(ref HashFNV1A32 generator, in ResourceHandle handle, RenderGraphResourceRegistry resources)
{
if (handle.index == 0)
return;
if (resources.IsRenderGraphResourceImported(handle))
{
var res = resources.GetTextureResource(handle);
var graphicsResource = res.graphicsResource;
ref readonly var desc = ref res.desc;
var externalTexture = graphicsResource.externalTexture;
if (externalTexture != null) // External texture
{
generator.Append((int) externalTexture.graphicsFormat);
generator.Append((int) externalTexture.dimension);
generator.Append(externalTexture.width);
generator.Append(externalTexture.height);
if (externalTexture is RenderTexture externalRT)
generator.Append(externalRT.antiAliasing);
}
else if (graphicsResource.rt != null) // Regular RTHandle
{
var rt = graphicsResource.rt;
generator.Append((int) rt.graphicsFormat);
generator.Append((int) rt.dimension);
generator.Append(rt.antiAliasing);
if (graphicsResource.useScaling)
if (graphicsResource.scaleFunc != null)
generator.Append(DelegateHashCodeUtils.GetFuncHashCode(graphicsResource.scaleFunc));
else
generator.Append(graphicsResource.scaleFactor);
else
{
generator.Append(rt.width);
generator.Append(rt.height);
}
}
else if (graphicsResource.nameID != default) // External RTI
{
// The only info we have is from the provided desc upon importing.
generator.Append((int) desc.format);
generator.Append((int) desc.dimension);
generator.Append((int) desc.msaaSamples);
generator.Append(desc.width);
generator.Append(desc.height);
}
// Add the clear/discard buffer flags to the hash (used in all the cases above)
generator.Append(desc.clearBuffer);
generator.Append(desc.discardBuffer);
}
else
{
ref readonly var desc = ref resources.GetTextureResourceDesc(handle);
generator.Append((int) desc.format);
generator.Append((int) desc.dimension);
generator.Append((int) desc.msaaSamples);
generator.Append(desc.clearBuffer);
generator.Append(desc.discardBuffer);
switch (desc.sizeMode)
{
case TextureSizeMode.Explicit:
generator.Append(desc.width);
generator.Append(desc.height);
break;
case TextureSizeMode.Scale:
generator.Append(desc.scale);
break;
case TextureSizeMode.Functor:
generator.Append(DelegateHashCodeUtils.GetFuncHashCode(desc.func));
break;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
static void ComputeHashForTextureAccess(ref HashFNV1A32 generator, in ResourceHandle handle, in TextureAccess textureAccess)
{
generator.Append(handle.index);
generator.Append((int) textureAccess.flags);
generator.Append(textureAccess.mipLevel);
generator.Append(textureAccess.depthSlice);
}
// This function is performance sensitive.
// Avoid mass function calls to get the hashCode and compute locally instead.
public void ComputeHash(ref HashFNV1A32 generator, RenderGraphResourceRegistry resources)
{
generator.Append((int) type);
generator.Append(enableAsyncCompute);
generator.Append(allowPassCulling);
generator.Append(allowGlobalState);
generator.Append(enableFoveatedRasterization);
generator.Append(extendedFeatureFlags);
var depthHandle = depthAccess.textureHandle.handle;
if (depthHandle.IsValid())
{
ComputeTextureHash(ref generator, depthHandle, resources);
ComputeHashForTextureAccess(ref generator, depthHandle, depthAccess);
}
for (int i = 0; i < colorBufferMaxIndex + 1; ++i)
{
var colorBufferAccessElement = colorBufferAccess[i];
var handle = colorBufferAccessElement.textureHandle.handle;
if (!handle.IsValid())
continue;
ComputeTextureHash(ref generator, handle, resources);
ComputeHashForTextureAccess(ref generator, handle, colorBufferAccessElement);
}
generator.Append(colorBufferMaxIndex);
generator.Append(hasShadingRateImage);
if (hasShadingRateImage)
{
var handle = shadingRateAccess.textureHandle.handle;
if (handle.IsValid())
{
ComputeTextureHash(ref generator, handle, resources);
ComputeHashForTextureAccess(ref generator, handle, shadingRateAccess);
}
}
generator.Append(hasShadingRateStates);
generator.Append((int)shadingRateFragmentSize);
generator.Append((int)primitiveShadingRateCombiner);
generator.Append((int)fragmentShadingRateCombiner);
for (int i = 0; i < fragmentInputMaxIndex + 1; ++i)
{
var fragmentInputAccessElement = fragmentInputAccess[i];
var handle = fragmentInputAccessElement.textureHandle.handle;
if (!handle.IsValid())
continue;
ComputeTextureHash(ref generator, handle, resources);
ComputeHashForTextureAccess(ref generator, handle, fragmentInputAccessElement);
}
for (int i = 0; i < randomAccessResourceMaxIndex + 1; ++i)
{
var rar = randomAccessResource[i];
if (!rar.h.IsValid())
continue;
generator.Append(rar.h.index);
generator.Append(rar.preserveCounterValue);
}
generator.Append(randomAccessResourceMaxIndex);
generator.Append(fragmentInputMaxIndex);
generator.Append(generateDebugData);
generator.Append(allowRendererListCulling);
for (int resType = 0; resType < (int)RenderGraphResourceType.Count; resType++)
{
var resourceReads = resourceReadLists[resType];
var resourceReadsCount = resourceReads.Count;
for (int i = 0; i < resourceReadsCount; ++i)
generator.Append(resourceReads[i].index);
var resourceWrites = resourceWriteLists[resType];
var resourceWritesCount = resourceWrites.Count;
for (int i = 0; i < resourceWritesCount; ++i)
generator.Append(resourceWrites[i].index);
var resourceTransient = transientResourceList[resType];
var resourceTransientCount = resourceTransient.Count;
for (int i = 0; i < resourceTransientCount; ++i)
generator.Append(resourceTransient[i].index);
}
var usedRendererListListCount = usedRendererListList.Count;
for (int i = 0; i < usedRendererListListCount; ++i)
generator.Append(usedRendererListList[i].handle);
var setGlobalsListCount = setGlobalsList.Count;
for (int i = 0; i < setGlobalsListCount; ++i)
{
var global = setGlobalsList[i];
generator.Append(global.Item1.handle.index);
generator.Append(global.Item2);
}
generator.Append(useAllGlobalTextures);
var implicitReadsListCount = implicitReadsList.Count;
for (int i = 0; i < implicitReadsListCount; ++i)
generator.Append(implicitReadsList[i].index);
generator.Append(GetRenderFuncHash());
}
public void SetShadingRateImageRaw(in TextureHandle shadingRateImage)
{
if (ShadingRateInfo.supportsPerImageTile)
{
hasShadingRateImage = true;
// shading rate image access flag is always read, only 1 mip and 1 slice
shadingRateAccess = new TextureAccess(shadingRateImage, AccessFlags.Read, 0, 0);
}
}
public void SetShadingRateImage(in TextureHandle shadingRateImage, AccessFlags accessFlags, int mipLevel, int depthSlice)
{
if (ShadingRateInfo.supportsPerImageTile)
{
hasShadingRateImage = true;
shadingRateAccess = new TextureAccess(shadingRateImage, accessFlags, mipLevel, depthSlice);
AddResourceRead(shadingRateAccess.textureHandle.handle);
}
}
public void SetShadingRateFragmentSize(ShadingRateFragmentSize shadingRateFragmentSize)
{
if (ShadingRateInfo.supportsPerDrawCall)
{
hasShadingRateStates = true;
this.shadingRateFragmentSize = shadingRateFragmentSize;
}
}
public void SetShadingRateCombiner(ShadingRateCombinerStage stage, ShadingRateCombiner combiner)
{
if (ShadingRateInfo.supportsPerImageTile)
{
switch (stage)
{
case ShadingRateCombinerStage.Primitive:
hasShadingRateStates = true;
primitiveShadingRateCombiner = combiner;
break;
case ShadingRateCombinerStage.Fragment:
hasShadingRateStates = true;
fragmentShadingRateCombiner = combiner;
break;
}
}
}
public void SetExtendedFeatureFlags(ExtendedFeatureFlags value)
{
extendedFeatureFlags |= value;
}
}
// This used to have an extra generic argument 'RenderGraphContext' abstracting the context and avoiding
// the RenderGraphPass/ComputeRenderGraphPass/RasterRenderGraphPass/UnsafeRenderGraphPass classes below
// but this confuses IL2CPP and causes garbage when boxing the context created (even though they are structs)
[DebuggerDisplay("RenderPass: {name} (Index:{index} Async:{enableAsyncCompute})")]
internal abstract class BaseRenderGraphPass<PassData, TRenderGraphContext> : RenderGraphPass
where PassData : class, new()
{
internal PassData data;
internal BaseRenderFunc<PassData, TRenderGraphContext> renderFunc;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Initialize(int passIndex, PassData passData, string passName, RenderGraphPassType passType, ProfilingSampler sampler)
{
Clear();
index = passIndex;
data = passData;
name = passName;
type = passType;
customSampler = sampler;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Release(RenderGraphObjectPool pool)
{
pool.Release(data);
data = null;
renderFunc = null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool HasRenderFunc()
{
return renderFunc != null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override int GetRenderFuncHash()
{
return renderFunc != null ? DelegateHashCodeUtils.GetFuncHashCode(renderFunc) : 0;
}
}
[DebuggerDisplay("RenderPass: {name} (Index:{index} Async:{enableAsyncCompute})")]
[Obsolete("RenderGraphPass is deprecated, use RasterRenderGraphPass/ComputeRenderGraphPass/UnsafeRenderGraphPass instead.")]
internal sealed class RenderGraphPass<PassData> : BaseRenderGraphPass<PassData, RenderGraphContext>
where PassData : class, new()
{
// Variable is reused by overwriting its contents in FromInternalContext() before usage, so no need to reset it when entering play mode.
[NoAutoStaticsCleanup]
internal static RenderGraphContext c = new RenderGraphContext();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Execute(InternalRenderGraphContext renderGraphContext)
{
c.FromInternalContext(renderGraphContext);
renderFunc(data, c);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Release(RenderGraphObjectPool pool)
{
base.Release(pool);
// We need to do the release from here because we need the final type.
pool.Release(this);
}
}
[DebuggerDisplay("RenderPass: {name} (Index:{index} Async:{enableAsyncCompute})")]
internal sealed class ComputeRenderGraphPass<PassData> : BaseRenderGraphPass<PassData, ComputeGraphContext>
where PassData : class, new()
{
// Variable is reused by overwriting its contents in FromInternalContext() before usage, so no need to reset it when entering play mode.
[NoAutoStaticsCleanup]
internal static ComputeGraphContext c = new ComputeGraphContext();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Execute(InternalRenderGraphContext renderGraphContext)
{
c.FromInternalContext(renderGraphContext);
renderFunc(data, c);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Release(RenderGraphObjectPool pool)
{
base.Release(pool);
// We need to do the release from here because we need the final type.
pool.Release(this);
}
}
[DebuggerDisplay("RenderPass: {name} (Index:{index} Async:{enableAsyncCompute})")]
internal sealed class RasterRenderGraphPass<PassData> : BaseRenderGraphPass<PassData, RasterGraphContext>
where PassData : class, new()
{
// Variable is reused by overwriting its contents in FromInternalContext() before usage, so no need to reset it when entering play mode.
[NoAutoStaticsCleanup]
internal static RasterGraphContext c = new RasterGraphContext();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Execute(InternalRenderGraphContext renderGraphContext)
{
c.FromInternalContext(renderGraphContext);
renderFunc(data, c);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Release(RenderGraphObjectPool pool)
{
base.Release(pool);
// We need to do the release from here because we need the final type.
pool.Release(this);
}
}
[DebuggerDisplay("RenderPass: {name} (Index:{index} Async:{enableAsyncCompute})")]
internal sealed class UnsafeRenderGraphPass<PassData> : BaseRenderGraphPass<PassData, UnsafeGraphContext>
where PassData : class, new()
{
// Variable is reused by overwriting its contents in FromInternalContext() before usage, so no need to reset it when entering play mode.
[NoAutoStaticsCleanup]
internal static UnsafeGraphContext c = new UnsafeGraphContext();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Execute(InternalRenderGraphContext renderGraphContext)
{
c.FromInternalContext(renderGraphContext);
renderFunc(data, c);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Release(RenderGraphObjectPool pool)
{
base.Release(pool);
// We need to do the release from here because we need the final type.
pool.Release(this);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 377a2b96156b1344eaf58df67e35de17
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
using UnityEngine.Rendering;
namespace UnityEngine.Rendering.RenderGraphModule
{
internal enum RenderGraphPassType
{
Unsafe,
Raster,
Compute
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a49cc6879c5cd214a835d6a35ea809ce
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
using System;
using UnityEngine.Rendering;
namespace UnityEngine.Rendering.RenderGraphModule
{
[Obsolete("Use RenderGraphProfilerMarkers static fields instead.")]
internal enum RenderGraphProfileId
{
CompileRenderGraph,
ExecuteRenderGraph,
ComputeHashRenderGraph,
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 142844ba90b5f9f489ce89a48bc32e12
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,30 @@
using Unity.Profiling;
using Unity.Profiling.LowLevel;
namespace UnityEngine.Rendering.RenderGraphModule
{
/// <summary>
/// Static profiler marker declarations for the Render Graph system.
/// </summary>
internal static class RenderGraphProfilerMarkers
{
/// <summary>
/// Compiles the native render graph from the recorded pass list, resolving resource
/// lifetimes, merging compatible passes, and allocating transient render targets.
/// </summary>
public static readonly ProfilerMarker CompileRenderGraph = new ProfilerMarker(ProfilerCategory.Render, "Inl_CompileRenderGraph");
/// <summary>
/// Computes an FNV-1a hash of all recorded render graph passes and their resource
/// dependencies, used to detect unchanged graphs and skip recompilation.
/// CPU-only marker — no GPU sampling.
/// </summary>
public static readonly ProfilerMarker ComputeHashRenderGraph = new ProfilerMarker(ProfilerCategory.Render, "Inl_ComputeHashRenderGraph", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Executes the compiled native render graph, dispatching each pass's render commands
/// through the command buffer with automatic resource barriers and load/store actions.
/// </summary>
public static readonly ProfilingSampler ExecuteRenderGraph = ProfilingSampler.Create(nameof(ExecuteRenderGraph), MarkerFlags.Default);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2e7a6390188e38a4c85f34bed59b5c87
@@ -0,0 +1,58 @@
using System.Diagnostics;
using UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.Rendering.RenderGraphModule
{
/// <summary>
/// RayTracingAccelerationStructure resource handle.
/// </summary>
[DebuggerDisplay("RayTracingAccelerationStructure ({handle.index})")]
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public readonly struct RayTracingAccelerationStructureHandle
{
private static readonly RayTracingAccelerationStructureHandle s_NullHandle = new RayTracingAccelerationStructureHandle();
/// <summary>
/// Returns a null ray tracing acceleration structure handle
/// </summary>
/// <value>A null ray tracing acceleration structure handle.</value>
public static RayTracingAccelerationStructureHandle nullHandle { get { return s_NullHandle; } }
internal readonly ResourceHandle handle;
internal RayTracingAccelerationStructureHandle(int handle) { this.handle = new ResourceHandle(handle, RenderGraphResourceType.AccelerationStructure, false); }
/// <summary>
/// Cast to RayTracingAccelerationStructure
/// </summary>
/// <param name="handle">Input RayTracingAccelerationStructureHandle</param>
/// <returns>Resource as a RayTracingAccelerationStructure.</returns>
public static implicit operator RayTracingAccelerationStructure(RayTracingAccelerationStructureHandle handle) => handle.IsValid() ? RenderGraphResourceRegistry.current.GetRayTracingAccelerationStructure(handle) : null;
/// <summary>
/// Return true if the handle is valid.
/// </summary>
/// <returns>True if the handle is valid.</returns>
public bool IsValid() => handle.IsValid();
}
/// <summary>
/// Descriptor used to identify ray tracing acceleration structure resources
/// </summary>
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public struct RayTracingAccelerationStructureDesc
{
/// <summary>RayTracingAccelerationStructure name.</summary>
public string name;
}
[DebuggerDisplay("RayTracingAccelerationStructureResource ({desc.name})")]
class RayTracingAccelerationStructureResource : RenderGraphResource<RayTracingAccelerationStructureDesc, RayTracingAccelerationStructure>
{
public override string GetName()
{
return desc.name;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 83567ec75a578bb47b248b662dd70fe5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,171 @@
using System;
using System.Diagnostics;
using UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.Rendering.RenderGraphModule
{
/// <summary>
/// Graphics Buffer resource handle.
/// </summary>
[DebuggerDisplay("Buffer ({handle.index})")]
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public readonly struct BufferHandle
{
// Minor Warning: This calls the zeroing constructor this means that the embedded ResourceHandle struct will also be zero-ed
// which then means ResourceHandle.type will be set to zero == Texture. As this is an "invalid" bufferhandle I guess setting it
// to type texture just makes it even more properly invalid and not a big issue. But something to keep in mind for tooling/logging.
private static readonly BufferHandle s_NullHandle = new BufferHandle();
/// <summary>
/// Returns a null graphics buffer handle
/// </summary>
/// <value>A null graphics buffer handle.</value>
public static BufferHandle nullHandle { get { return s_NullHandle; } }
internal readonly ResourceHandle handle;
internal BufferHandle(in ResourceHandle h) { handle = h; }
internal BufferHandle(int handle, bool shared = false) { this.handle = new ResourceHandle(handle, RenderGraphResourceType.Buffer, shared); }
/// <summary>
/// Cast to GraphicsBuffer
/// </summary>
/// <param name="buffer">Input BufferHandle</param>
/// <returns>Resource as a Graphics Buffer.</returns>
public static implicit operator GraphicsBuffer(BufferHandle buffer) => buffer.IsValid() ? RenderGraphResourceRegistry.current.GetBuffer(buffer) : null;
/// <summary>
/// Return true if the handle is valid.
/// </summary>
/// <returns>True if the handle is valid.</returns>
public bool IsValid() => handle.IsValid();
}
/// <summary>
/// Descriptor used to create graphics buffer resources
/// </summary>
public struct BufferDesc
{
///<summary>Number of elements in the buffer..</summary>
public int count;
///<summary>Size of one element in the buffer. Has to match size of buffer type in the shader.</summary>
public int stride;
/// <summary>Graphics Buffer name.</summary>
public string name;
/// <summary>The intended usage of a GraphicsBuffer.</summary>
public GraphicsBuffer.Target target;
/// <summary>The intended update mode of a GraphicsBuffer.</summary>
public GraphicsBuffer.UsageFlags usageFlags;
/// <summary>
/// BufferDesc constructor.
/// </summary>
/// <param name="count">Number of elements in the buffer.</param>
/// <param name="stride">Size of one element in the buffer.</param>
public BufferDesc(int count, int stride)
: this()
{
this.count = count;
this.stride = stride;
this.target = GraphicsBuffer.Target.Structured;
this.usageFlags = GraphicsBuffer.UsageFlags.None;
}
/// <summary>
/// BufferDesc constructor.
/// </summary>
/// <param name="count">Number of elements in the buffer.</param>
/// <param name="stride">Size of one element in the buffer.</param>
/// <param name="target">Type of the buffer.</param>
public BufferDesc(int count, int stride, GraphicsBuffer.Target target)
: this()
{
this.count = count;
this.stride = stride;
this.target = target;
this.usageFlags = GraphicsBuffer.UsageFlags.None;
}
/// <summary>
/// Hash function
/// </summary>
/// <returns>The texture descriptor hash.</returns>
public override int GetHashCode() => ComputeDescHash().value;
internal HashFNV1A32 ComputeDescHash()
{
var hashCode = HashFNV1A32.Create();
hashCode.Append(count);
hashCode.Append(stride);
hashCode.Append((int) target);
hashCode.Append((int) usageFlags);
return hashCode;
}
}
[DebuggerDisplay("BufferResource ({desc.name})")]
class BufferResource : RenderGraphResource<BufferDesc, GraphicsBuffer>
{
public override string GetName()
{
if (imported)
return "ImportedGraphicsBuffer"; // No getter for graphics buffer name.
else
return desc.name;
}
public override HashFNV1A32 GetDescHash() { return desc.ComputeDescHash(); }
public override void CreateGraphicsResource()
{
var name = GetName();
graphicsResource = new GraphicsBuffer(desc.target, desc.usageFlags, desc.count, desc.stride);
#if UNITY_ENABLE_CHECKS
graphicsResource.name = name == "" ? $"RenderGraphBuffer_{desc.count}_{desc.stride}_{desc.target}" : name;
#endif
}
public override void UpdateGraphicsResource()
{
if (graphicsResource != null)
graphicsResource.name = GetName();
}
public override void ReleaseGraphicsResource()
{
if (graphicsResource != null)
graphicsResource.Release();
base.ReleaseGraphicsResource();
}
}
class BufferPool : RenderGraphResourcePool<GraphicsBuffer>
{
protected override void ReleaseInternalResource(GraphicsBuffer res)
{
res.Release();
}
protected override string GetResourceName(in GraphicsBuffer res)
{
return "GraphicsBufferNameNotAvailable"; // GraphicsBuffer.name is a setter only :(
}
protected override long GetResourceSize(in GraphicsBuffer res)
{
return res.count * res.stride;
}
override protected string GetResourceTypeName()
{
return "GraphicsBuffer";
}
override protected ulong GetSortIndex(GraphicsBuffer res)
{
return (ulong)res.GetHashCode();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 089429d350f9ca04584448dfa84e2f3d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,229 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace UnityEngine.Rendering.RenderGraphModule
{
abstract class IRenderGraphResourcePool
{
public abstract void PurgeUnusedResources(int currentFrameIndex);
public abstract void Cleanup();
public abstract void CheckFrameAllocation(bool onException, int frameIndex);
// When disabled, resources released in the current execution cannot be reused until the next execution.
// This is useful for Frame Debugger to ensure each pass uses unique resources within an execution.
public bool IntraFrameMemoryAliasing { get; set; } = true;
}
/// <summary>
/// Encapsulates a pooled resource along with its frame and execution tracking metadata.
/// This allows the pool to track when resources were released for proper reuse and purging decisions.
/// </summary>
readonly struct PooledResourceEntry<Type> where Type : class
{
public readonly Type resource;
public readonly int frameIndex;
public readonly int executionCount;
public PooledResourceEntry(Type resource, int frameIndex, int executionCount)
{
this.resource = resource;
this.frameIndex = frameIndex;
this.executionCount = executionCount;
}
}
abstract class RenderGraphResourcePool<Type> : IRenderGraphResourcePool where Type : class
{
// Dictionary tracks resources by hash and stores resources with same hash in a List (list instead of a stack because we need to be able to remove stale allocations, potentially in the middle of the stack).
// The list needs to be sorted otherwise you could get inconsistent resource usage from one frame to another.
protected Dictionary<int, SortedList<ulong, PooledResourceEntry<Type>>> m_ResourcePool = new Dictionary<int, SortedList<ulong, PooledResourceEntry<Type>>>();
// This list allows us to determine if all resources were correctly released in the frame when validity checks are enabled.
// This is useful to warn in case of user error or avoid leaks when a render graph execution error occurs for example.
List<(int, Type)> m_FrameAllocatedResources = new List<(int, Type)>();
const int kStaleResourceLifetime = 10;
// Release the GPU resource itself
protected abstract void ReleaseInternalResource(Type res);
protected abstract string GetResourceName(in Type res);
protected abstract long GetResourceSize(in Type res);
protected abstract string GetResourceTypeName();
protected abstract ulong GetSortIndex(Type res);
public void ReleaseResource(int hash, Type resource, int currentFrameIndex, int currentExecutionCount)
{
if (!m_ResourcePool.TryGetValue(hash, out var list))
{
list = new SortedList<ulong, PooledResourceEntry<Type>>();
m_ResourcePool.Add(hash, list);
}
list.Add(GetSortIndex(resource), new PooledResourceEntry<Type>(resource, currentFrameIndex, currentExecutionCount));
}
public bool TryGetResource(int hashCode, out Type resource, int currentFrameIndex, int currentExecutionCount)
{
if (m_ResourcePool.TryGetValue(hashCode, out SortedList<ulong, PooledResourceEntry<Type>> list) && list.Count > 0)
{
// When "intra frame memory aliasing" mode is disabled, skip resources that were released in the current execution.
// They will only be available for reuse in the next execution.
if (!IntraFrameMemoryAliasing)
{
// Iterate from the end to find a resource not from the current execution.
for (int i = list.Count - 1; i >= 0; i--)
{
var entry = list.Values[i];
// Allow reuse if the resource was released in a previous frame (normal case),
// or in a previous execution within the same frame (Frame Debugger cascade-repaints).
// This handles both standard frame-to-frame reuse and rapid repaints in Frame Debugger.
if (entry.frameIndex < currentFrameIndex || entry.executionCount < currentExecutionCount)
{
resource = entry.resource;
list.RemoveAt(i);
return true;
}
}
// All available resources are from the current execution, so we need to create a new one.
}
else
{
// Normal mode: take the most recent resource.
var index = list.Count - 1;
resource = list.Values[index].resource;
list.RemoveAt(index); // O(1) since it's the last element.
return true;
}
}
resource = null;
return false;
}
public override void Cleanup()
{
// Removing the actual graphics resources
foreach (var kvp in m_ResourcePool)
{
foreach (var res in kvp.Value)
{
ReleaseInternalResource(res.Value.resource);
}
}
// Clearing the lists and the pool itself
m_ResourcePool.Clear();
// Clearing it, if not done already
m_FrameAllocatedResources.Clear();
}
[Conditional("UNITY_ENABLE_CHECKS")]
public void RegisterFrameAllocation(int hash, Type value)
{
if (RenderGraph.enableValidityChecks && hash != -1)
m_FrameAllocatedResources.Add((hash, value));
}
[Conditional("UNITY_ENABLE_CHECKS")]
public void UnregisterFrameAllocation(int hash, Type value)
{
if (RenderGraph.enableValidityChecks && hash != -1)
m_FrameAllocatedResources.Remove((hash, value));
}
public override void CheckFrameAllocation(bool onException, int frameIndex)
{
#if UNITY_ENABLE_CHECKS // conditional not working with override
if (RenderGraph.enableValidityChecks)
{
// In case of exception we need to release all resources to the pool to avoid leaking.
// If it's not an exception then it's a user error so we need to log the problem.
if (m_FrameAllocatedResources.Count != 0)
{
string logMessage = "";
if (!onException)
logMessage = $"RenderGraph: Not all resources of type {GetResourceTypeName()} were released. This can be caused by a resources being allocated but never read by any pass.";
foreach (var value in m_FrameAllocatedResources)
{
if (!onException)
logMessage = $"{logMessage}\n\t{GetResourceName(value.Item2)}";
// When releasing on exception/error, use -1 as executionCount marker.
// This ensures the resource goes back to the pool but won't interfere with normal execution tracking.
ReleaseResource(value.Item1, value.Item2, frameIndex, -1);
}
if (!onException) // If onException is true, logMessage is ""
Debug.LogWarning(logMessage);
}
// If an error occurred during execution, it's expected that textures are not all released so we clear the tracking list.
m_FrameAllocatedResources.Clear();
}
#endif
}
public float GetMemorySizeInMB()
{
float totalSize = 0;
foreach (var kvp in m_ResourcePool)
{
foreach (var res in kvp.Value)
{
totalSize += GetResourceSize(res.Value.resource) / (1024.0f * 1024.0f);
}
}
return totalSize;
}
public int GetNumResourcesAvailable()
{
int totalResources = 0;
foreach (var kvp in m_ResourcePool)
{
totalResources += kvp.Value.Count;
}
return totalResources;
}
static readonly List<ulong> s_ToRemoveList = new List<ulong>(32);
public override void PurgeUnusedResources(int currentFrameIndex)
{
foreach (var kvp in m_ResourcePool)
{
s_ToRemoveList.Clear();
var list = kvp.Value;
var keys = list.Keys;
var values = list.Values;
for (int i = 0; i < list.Count; ++i)
{
var value = values[i];
var key = keys[i];
// When a resource hasn't been used for a few frames, we release it for good to reduce memory footprint.
// We wait a few frames because when having multiple off-screen cameras,
// they are rendered in a separate SRP render call and thus with a different frame index than main camera
// This causes texture to be deallocated/reallocated every frame if the two cameras don't need the same buffers.
if (value.frameIndex + kStaleResourceLifetime < currentFrameIndex)
{
ReleaseInternalResource(value.resource);
// Adding stale resource to the remove list
s_ToRemoveList.Add(key);
}
}
// Removing the stale resource from the pool
for (int j = 0; j < s_ToRemoveList.Count; ++j)
list.Remove(s_ToRemoveList[j]);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4998ae5b70f43844eb7716decb537ba5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 92b6367ea491af341aa7417fbac635ab
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,72 @@
using System.Diagnostics;
using UnityEngine.Scripting.APIUpdating;
// Typedefs for the in-engine RendererList API (to avoid conflicts with the experimental version)
using CoreRendererList = UnityEngine.Rendering.RendererList;
using CoreRendererListDesc = UnityEngine.Rendering.RendererUtils.RendererListDesc;
namespace UnityEngine.Rendering.RenderGraphModule
{
internal enum RendererListHandleType
{
// RendererList and async RendererList
Renderers,
// Other builtin rendererLists representing Gfx works scheduled by Unity core. Such as shadow/skybox/gizmo/etc
Legacy
}
/// <summary>
/// Renderer List resource handle.
/// </summary>
[DebuggerDisplay("RendererList ({handle})")]
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public struct RendererListHandle
{
internal RendererListHandleType type;
bool m_IsValid;
internal int handle { get; private set; }
internal RendererListHandle(int handle, RendererListHandleType type = RendererListHandleType.Renderers) { this.handle = handle; m_IsValid = true; this.type = type; }
/// <summary>
/// Conversion to int.
/// </summary>
/// <param name="handle">Renderer List handle to convert.</param>
/// <returns>The integer representation of the handle.</returns>
public static implicit operator int(RendererListHandle handle) { return handle.handle; }
/// <summary>
/// Cast to RendererList
/// </summary>
/// <param name="rendererList">Input RendererListHandle.</param>
/// <returns>Resource as a RendererList.</returns>
public static implicit operator CoreRendererList(RendererListHandle rendererList) => rendererList.IsValid() ? RenderGraphResourceRegistry.current.GetRendererList(rendererList) : CoreRendererList.nullRendererList;
/// <summary>
/// Return true if the handle is valid.
/// </summary>
/// <returns>True if the handle is valid.</returns>
public bool IsValid() => m_IsValid;
}
internal struct RendererListResource
{
public RendererListParams desc;
public CoreRendererList rendererList;
internal RendererListResource(in RendererListParams desc)
{
this.desc = desc;
this.rendererList = new CoreRendererList(); // Invalid by default
}
}
internal struct RendererListLegacyResource
{
public CoreRendererList rendererList;
public bool isActive;
internal RendererListLegacyResource(in bool active = false)
{
this.rendererList = new CoreRendererList(); // Invalid by default
this.isActive = active;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ec298c53cc0c53d47b753c25f59223ed
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,677 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.Rendering.RenderGraphModule
{
internal readonly struct TextureAccess
{
public readonly TextureHandle textureHandle;
public readonly int mipLevel;
public readonly int depthSlice;
public readonly AccessFlags flags;
public TextureAccess(in TextureHandle handle, AccessFlags flags, int mipLevel, int depthSlice)
{
this.textureHandle = handle;
this.flags = flags;
this.mipLevel = mipLevel;
this.depthSlice = depthSlice;
}
public TextureAccess(in TextureAccess access, in TextureHandle handle)
{
this.textureHandle = handle;
this.flags = access.flags;
this.mipLevel = access.mipLevel;
this.depthSlice = access.depthSlice;
}
}
/// <summary>
/// Represents the origin of UV coordinates for a texture. It represents how Unity stores the content,
/// independent of the active graphics API. The UV coordinate (0,0) in the shader will either sample
/// the bottom left pixel of the image, or the top left pixel (flipped).
/// </summary>
public enum TextureUVOrigin
{
/// <summary>
/// The UV coordinate (0,0) in a shader will sample the BOTTOM left texel of the texture. This matched the OpenGL standard, which is also the Unity standard for textures.
/// To ensure this behavior, Unity will store the content for texture upside down (flipped) on modern graphics APIs.
/// </summary>
BottomLeft,
/// <summary>
/// The UV coordinate (0,0) in a shader will sample the TOP left texel of the texture. This matches the standard of modern graphics APIs (Vulkan, DX, Metal,...).
/// The actual backbuffer will have a TopLeft orientation when a modern graphics API is active.
/// </summary>
TopLeft
}
/// <summary>
/// Represents the origin of UV coordinates for a texture. It represents how Unity stores the content,
/// independent of the active graphics API. The UV coordinate (0,0) in the shader will either sample
/// the bottom left pixel of the image, or the top left pixel (flipped).
/// </summary>
internal enum TextureUVOriginSelection
{
/// <summary>
/// The UV coordinate (0,0) in a shader will sample the BOTTOM left texel of the texture. This matched the OpenGL standard, which is also the Unity standard for textures.
/// To ensure this behavior, Unity will store the content for texture upside down (flipped) on modern graphics APIs.
/// </summary>
BottomLeft,
/// <summary>
/// The UV coordinate (0,0) in a shader will sample the TOP left texel of the texture. This matches the standard of modern graphics APIs (Vulkan, DX, Metal,...).
/// The actual backbuffer will have a TopLeft orientation when a modern graphics API is active.
/// </summary>
TopLeft,
/// <summary>
/// The orientation has not been assigned yet.
/// </summary>
Unknown
}
/// <summary>
/// An abstract handle representing a texture resource as known by one particular record + execute of the render graph.
/// TextureHandles should not be used outside of the context of a render graph execution.
///
/// A render graph needs to do additional state tracking on texture resources (lifetime, how is it used,...) to enable
/// this all textures relevant to the render graph need to be make known to it. A texture handle specifies such a texture as
/// known to the render graph.
///
/// It is important to understand that a render graph texture handle does not necessarily represent an actual texture. For example
/// textures could be created the render graph that are only referenced by passes that are later culled when executing the graph.
/// Such textures would never be allocated as actual RenderTextures.
///
/// Texture handles are only relevant to one particular record+execute phase of the render graph. After execution all texture
/// handles are invalidated. The system will catch texture handles from a different execution of the render graph but still
/// users should be careful to avoid keeping texture handles around from other render graph executions.
///
/// Texture handles do not need to be disposed/freed (they are auto-invalidated at the end of graph execution). The RenderTextures they represent
/// are either freed by the render graph internally (when the handle was acquired through RenderGraph.CreateTexture) or explicitly managed by
/// some external system (when acquired through RenderGraph.ImportTexture).
///
/// </summary>
[DebuggerDisplay("Texture ({handle.index})")]
[MovedFrom(true, "UnityEngine.Experimental.Rendering.RenderGraphModule", "UnityEngine.Rendering.RenderGraphModule")]
public readonly struct TextureHandle : IEquatable<TextureHandle>
{
private static readonly TextureHandle s_NullHandle = new TextureHandle();
/// <summary>
/// Returns a null texture handle
/// </summary>
/// <value>A null texture handle.</value>
public static TextureHandle nullHandle { get { return s_NullHandle; } }
internal readonly ResourceHandle handle;
private readonly bool builtin;
internal TextureHandle(in ResourceHandle h)
{
handle = h;
builtin = false;
}
internal TextureHandle(int handle, bool shared = false, bool builtin = false)
{
this.handle = new ResourceHandle(handle, RenderGraphResourceType.Texture, shared);
this.builtin = builtin;
}
/// <summary>
/// Cast to RenderTargetIdentifier
/// </summary>
/// <param name="texture">Input TextureHandle.</param>
/// <returns>Resource as a RenderTargetIdentifier.</returns>
public static implicit operator RenderTargetIdentifier(TextureHandle texture) => texture.IsValid() ? RenderGraphResourceRegistry.current.GetTexture(texture) : default(RenderTargetIdentifier);
/// <summary>
/// Cast to Texture
/// </summary>
/// <param name="texture">Input TextureHandle.</param>
/// <returns>Resource as a Texture.</returns>
public static implicit operator Texture(TextureHandle texture) => texture.IsValid() ? RenderGraphResourceRegistry.current.GetTexture(texture) : null;
/// <summary>
/// Cast to RenderTexture
/// </summary>
/// <param name="texture">Input TextureHandle.</param>
/// <returns>Resource as a RenderTexture.</returns>
public static implicit operator RenderTexture(TextureHandle texture) => texture.IsValid() ? RenderGraphResourceRegistry.current.GetTexture(texture) : null;
/// <summary>
/// Cast to RTHandle
/// </summary>
/// <param name="texture">Input TextureHandle.</param>
/// <returns>Resource as a RTHandle.</returns>
public static implicit operator RTHandle(TextureHandle texture) => texture.IsValid() ? RenderGraphResourceRegistry.current.GetTexture(texture) : null;
/// <summary>
/// Determines whether this instance and another specified <see cref="TextureHandle"/> object have the same underlying resource handle.
/// </summary>
/// <param name="other">The texture handle to compare with the current instance.</param>
/// <returns>
/// True if both texture handles reference the same underlying resource; otherwise, false.
/// </returns>
public bool Equals(TextureHandle other) => handle.Equals(other.handle);
/// <summary>
/// Determines whether the specified object is equal to the current <see cref="TextureHandle"/>.
/// </summary>
/// <param name="obj">The object to compare with the current instance.</param>
/// <returns>
/// True if the specified object is a <see cref="TextureHandle"/> and references the same underlying resource; otherwise, false.
/// </returns>
public override bool Equals(object obj) => obj is TextureHandle other && Equals(other);
/// <summary>
/// Returns the hash code for this <see cref="TextureHandle"/>.
/// </summary>
/// <returns>
/// The hash code of the current <see cref="TextureHandle"/>.
/// </returns>
public override int GetHashCode() => handle.GetHashCode();
/// <summary>
/// Determines whether two <see cref="TextureHandle"/> instances reference the same underlying resource.
/// </summary>
/// <param name="lhs">The first texture handle to compare.</param>
/// <param name="rhs">The second texture handle to compare.</param>
/// <returns>
/// True if both handles reference the same underlying resource; otherwise, false.
/// </returns>
public static bool operator ==(TextureHandle lhs, TextureHandle rhs) => lhs.handle.Equals(rhs.handle);
/// <summary>
/// Determines whether two <see cref="TextureHandle"/> instances reference different underlying resources.
/// </summary>
/// <param name="lhs">The first texture handle to compare.</param>
/// <param name="rhs">The second texture handle to compare.</param>
/// <returns>
/// True if the handles reference different underlying resources; otherwise, false.
/// </returns>
public static bool operator !=(TextureHandle lhs, TextureHandle rhs) => !lhs.handle.Equals(rhs.handle);
/// <summary>
/// Return true if the handle is valid.
/// </summary>
/// <returns>True if the handle is valid.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsValid() => handle.IsValid();
/// <summary>
/// Return true if the handle is a builtin handle managed by RenderGraph internally.
/// </summary>
/// <returns>True if the handle is a builtin handle.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal bool IsBuiltin() => this.builtin;
/// <summary>
/// Get the Descriptor of the texture. This simply calls RenderGraph.GetTextureDesc but is more easily discoverable through auto complete.
/// </summary>
/// <param name="renderGraph">The rendergraph instance that was used to create the texture on. Texture handles are a lightweight object, all information is stored on the RenderGraph itself.</param>
/// <returns>The texture descriptor for the given texture handle.</returns>
public TextureDesc GetDescriptor(RenderGraph renderGraph) { return renderGraph.GetTextureDesc(this); }
}
/// <summary>
/// The mode that determines the size of a Texture.
/// </summary>
public enum TextureSizeMode
{
///<summary>Explicit size.</summary>
Explicit,
///<summary>Size automatically scaled by a Vector.</summary>
Scale,
///<summary>Size automatically scaled by a Functor.</summary>
Functor
}
/// <summary>
/// Subset of the texture desc containing information for fast memory allocation (when platform supports it)
/// </summary>
public struct FastMemoryDesc
{
///<summary>Whether the texture will be in fast memory.</summary>
public bool inFastMemory;
///<summary>Flag to determine what parts of the render target is spilled if not fully resident in fast memory.</summary>
public FastMemoryFlags flags;
///<summary>How much of the render target is to be switched into fast memory (between 0 and 1).</summary>
public float residencyFraction;
}
/// <summary>
/// Descriptor used to create texture resources
/// </summary>
public struct TextureDesc
{
///<summary>Texture sizing mode.</summary>
public TextureSizeMode sizeMode;
///<summary>Texture width.</summary>
public int width;
///<summary>Texture height.</summary>
public int height;
///<summary>Number of texture slices.</summary>
public int slices;
///<summary>Texture scale.</summary>
public Vector2 scale;
///<summary>Texture scale function.</summary>
public ScaleFunc func;
///<summary>Color or depth stencil format.</summary>
public GraphicsFormat format;
///<summary>Filtering mode.</summary>
public FilterMode filterMode;
///<summary>Addressing mode.</summary>
public TextureWrapMode wrapMode;
///<summary>Texture dimension.</summary>
public TextureDimension dimension;
///<summary>Enable random UAV read/write on the texture.</summary>
public bool enableRandomWrite;
///<summary>Texture needs mip maps.</summary>
public bool useMipMap;
///<summary>Automatically generate mip maps.</summary>
public bool autoGenerateMips;
///<summary>Texture is a shadow map.</summary>
public bool isShadowMap;
///<summary>Anisotropic filtering level.</summary>
public int anisoLevel;
///<summary>Mip map bias.</summary>
public float mipMapBias;
///<summary>Number of MSAA samples.</summary>
public MSAASamples msaaSamples;
///<summary>Bind texture multi sampled.</summary>
public bool bindTextureMS;
///<summary>[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</summary>
public bool useDynamicScale;
///<summary>[See Dynamic Resolution documentation](https://docs.unity3d.com/Manual/DynamicResolution.html)</summary>
public bool useDynamicScaleExplicit;
///<summary>
///[See Memoryless documentation](https://docs.unity3d.com/ScriptReference/RenderTextureMemoryless.html)
///</summary>
///<remarks>
///If this is a Render Graph created resource only used in a single raster render pass, and not sampled (no UseTexture() usage), Render Graph will automatically set this resource as memoryless.
///</remarks>
public RenderTextureMemoryless memoryless;
///<summary>Special treatment of the VR eye texture used in stereoscopic rendering.</summary>
public VRTextureUsage vrUsage;
/// <summary>
/// Set to true if the texture is to be used as a shading rate image.
/// </summary>
/// <remarks>
/// Width and height are usually in pixels but if enableShadingRate is set to true, width and height are in tiles.
/// See also <a href="https://docs.unity3d.com/Manual/variable-rate-shading">Variable Rate Shading</a>.
/// </remarks>
public bool enableShadingRate;
///<summary>Texture name.</summary>
public string name;
///<summary>Descriptor to determine how the texture will be in fast memory on platform that supports it.</summary>
public FastMemoryDesc fastMemoryDesc;
///<summary>Determines whether the texture will fallback to a black texture if it is read without ever writing to it.</summary>
public bool fallBackToBlackTexture;
///<summary>
///If all passes writing to a texture are culled by Dynamic Render Pass Culling, it will automatically fallback to a similar preallocated texture.
///Set this to true to force the allocation.
///</summary>
public bool disableFallBackToImportedTexture;
// Initial state. Those should not be used in the hash
///<summary>Texture needs to be cleared on first use.</summary>
public bool clearBuffer;
///<summary>Clear color.</summary>
public Color clearColor;
///<summary>Texture needs to be discarded on last use.</summary>
public bool discardBuffer;
///<summary>Depth buffer bit depth of the format. The setter convert the bits to valid depth stencil format and sets the format. The getter gets the depth bits of the format.</summary>
public DepthBits depthBufferBits
{
get { return (DepthBits)GraphicsFormatUtility.GetDepthBits(format); }
set
{
if (value == DepthBits.None)
{
if( !GraphicsFormatUtility.IsDepthStencilFormat(format) )
return;
else
format = GraphicsFormat.None;
}
else
{
format = GraphicsFormatUtility.GetDepthStencilFormat((int)value);
}
}
}
///<summary>Color format. Sets the format. The getter checks if format is a color format. Returns the format if a color format, otherwise returns GraphicsFormat.None.</summary>
public GraphicsFormat colorFormat
{
get { return GraphicsFormatUtility.IsDepthStencilFormat(format) ? GraphicsFormat.None : format; }
set { format = value; }
}
void InitDefaultValues(bool dynamicResolution, bool xrReady)
{
useDynamicScale = dynamicResolution;
vrUsage = VRTextureUsage.None;
// XR Ready
if (xrReady)
{
slices = TextureXR.slices;
dimension = TextureXR.dimension;
}
else
{
slices = 1;
dimension = TextureDimension.Tex2D;
}
discardBuffer = false;
}
/// <summary>
/// TextureDesc constructor for a texture using explicit size
/// </summary>
/// <param name="width">Texture width</param>
/// <param name="height">Texture height</param>
/// <param name="dynamicResolution">Use dynamic resolution</param>
/// <param name="xrReady">Set this to true if the Texture is a render texture in an XR setting.</param>
public TextureDesc(int width, int height, bool dynamicResolution = false, bool xrReady = false)
: this()
{
// Size related init
sizeMode = TextureSizeMode.Explicit;
this.width = width;
this.height = height;
// Important default values not handled by zero construction in this()
msaaSamples = MSAASamples.None;
InitDefaultValues(dynamicResolution, xrReady);
}
/// <summary>
/// TextureDesc constructor for a texture using a fixed scaling
/// </summary>
/// <param name="scale">RTHandle scale used for this texture</param>
/// <param name="dynamicResolution">Use dynamic resolution</param>
/// <param name="xrReady">Set this to true if the Texture is a render texture in an XR setting.</param>
public TextureDesc(Vector2 scale, bool dynamicResolution = false, bool xrReady = false)
: this()
{
// Size related init
sizeMode = TextureSizeMode.Scale;
this.scale = scale;
// Important default values not handled by zero construction in this()
msaaSamples = MSAASamples.None;
dimension = TextureDimension.Tex2D;
InitDefaultValues(dynamicResolution, xrReady);
}
/// <summary>
/// TextureDesc constructor for a texture using a functor for scaling
/// </summary>
/// <param name="func">Function used to determine the texture size</param>
/// <param name="dynamicResolution">Use dynamic resolution</param>
/// <param name="xrReady">Set this to true if the Texture is a render texture in an XR setting.</param>
public TextureDesc(ScaleFunc func, bool dynamicResolution = false, bool xrReady = false)
: this()
{
// Size related init
sizeMode = TextureSizeMode.Functor;
this.func = func;
// Important default values not handled by zero construction in this()
msaaSamples = MSAASamples.None;
dimension = TextureDimension.Tex2D;
InitDefaultValues(dynamicResolution, xrReady);
}
/// <summary>
/// Copy constructor
/// </summary>
/// <param name="input">The TextureDesc instance to copy from.</param>
public TextureDesc(TextureDesc input)
{
this = input;
}
/// <summary>
/// Do a best effort conversion from a RenderTextureDescriptor to a TextureDesc. This tries to initialize a descriptor to be as close as possible to the given render texture descriptor but there might be subtle differences when creating
/// render graph textures using this TextureDesc due to the underlying RTHandle system.
/// Some parameters of the TextureDesc (like name and filtering modes) are not present in the RenderTextureDescriptor for these the returned TextureDesc will contain plausible default values.
/// </summary>
/// <param name="input">The texture descriptor to create a TextureDesc from</param>
public TextureDesc(RenderTextureDescriptor input)
{
sizeMode = TextureSizeMode.Explicit;
width = input.width;
height = input.height;
slices = input.volumeDepth;
scale = Vector2.one;
func = null;
format = (input.depthStencilFormat != GraphicsFormat.None) ? input.depthStencilFormat : input.graphicsFormat;
filterMode = FilterMode.Bilinear;
wrapMode = TextureWrapMode.Clamp;
dimension = input.dimension;
enableRandomWrite = input.enableRandomWrite;
useMipMap = input.useMipMap;
autoGenerateMips = input.autoGenerateMips;
isShadowMap = (input.shadowSamplingMode != ShadowSamplingMode.None);
anisoLevel = 1;
mipMapBias = 0;
msaaSamples = (MSAASamples)input.msaaSamples;
bindTextureMS = input.bindMS;
useDynamicScale = input.useDynamicScale;
useDynamicScaleExplicit = false;
memoryless = input.memoryless;
vrUsage = input.vrUsage;
name = "UnNamedFromRenderTextureDescriptor";
fastMemoryDesc = new FastMemoryDesc();
fastMemoryDesc.inFastMemory = false;
fallBackToBlackTexture = false;
disableFallBackToImportedTexture = true;
clearBuffer = true;
clearColor = Color.black;
discardBuffer = false;
enableShadingRate = input.enableShadingRate;
}
/// <summary>
/// Do a best effort conversion from a RenderTexture to a TextureDesc. This tries to initialize a descriptor to be as close as possible to the given render texture but there might be subtle differences when creating
/// render graph textures using this TextureDesc due to the underlying RTHandle system.
/// </summary>
/// <param name="input">The texture to create a TextureDesc from</param>
public TextureDesc(RenderTexture input) : this(input.descriptor)
{
filterMode = input.filterMode;
wrapMode = input.wrapMode;
anisoLevel = input.anisoLevel;
mipMapBias = input.mipMapBias;
name = "UnNamedFromRenderTextureDescriptor";
}
/// <summary>
/// Hash function
/// </summary>
/// <returns>The texture descriptor hash.</returns>
public override int GetHashCode() => ComputeDescHash().value;
internal HashFNV1A32 ComputeDescHash()
{
var hashCode = HashFNV1A32.Create();
switch (sizeMode)
{
case TextureSizeMode.Explicit:
hashCode.Append(width);
hashCode.Append(height);
break;
case TextureSizeMode.Functor:
if (func != null)
hashCode.Append(DelegateHashCodeUtils.GetFuncHashCode(func));
break;
case TextureSizeMode.Scale:
hashCode.Append(scale);
break;
}
hashCode.Append(mipMapBias);
hashCode.Append(slices);
hashCode.Append((int) format);
hashCode.Append((int) filterMode);
hashCode.Append((int) wrapMode);
hashCode.Append((int) dimension);
hashCode.Append((int) memoryless);
hashCode.Append((int) vrUsage);
hashCode.Append(anisoLevel);
hashCode.Append(enableRandomWrite);
hashCode.Append(useMipMap);
hashCode.Append(autoGenerateMips);
hashCode.Append(isShadowMap);
hashCode.Append(bindTextureMS);
hashCode.Append(useDynamicScale);
hashCode.Append((int) msaaSamples);
hashCode.Append(fastMemoryDesc.inFastMemory);
hashCode.Append(enableShadingRate);
return hashCode;
}
/// <summary>
/// Calculate the final size of the texture descriptor in pixels. This takes into account the sizeMode set for this descriptor.
/// For the automatically scaled sizes the size will be relative to the RTHandle reference size <see cref="RTHandles.SetReferenceSize">SetReferenceSize</see>.
/// </summary>
/// <returns>The calculated size.</returns>
/// <exception cref="ArgumentOutOfRangeException">Thrown if the texture descriptor's size mode falls outside the expected range.</exception>
public Vector2Int CalculateFinalDimensions()
{
return sizeMode switch
{
TextureSizeMode.Explicit => new Vector2Int(width, height),
TextureSizeMode.Scale => RTHandles.CalculateDimensions(scale),
TextureSizeMode.Functor => RTHandles.CalculateDimensions(func),
_ => throw new ArgumentOutOfRangeException()
};
}
}
[DebuggerDisplay("TextureResource ({desc.name})")]
class TextureResource : RenderGraphResource<TextureDesc, RTHandle>
{
static int m_TextureCreationIndex;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
m_TextureCreationIndex = 0;
}
#endif
internal TextureUVOriginSelection textureUVOrigin;
public override string GetName()
{
if (imported && !shared)
return graphicsResource != null ? graphicsResource.name : "null resource";
else
return desc.name;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override HashFNV1A32 GetDescHash() { return desc.ComputeDescHash(); }
public override void CreateGraphicsResource()
{
var name = GetName();
// Textures are going to be reused under different aliases along the frame so we can't provide a specific name upon creation.
// The name in the desc is going to be used for debugging purpose and render graph visualization.
if (name == "")
name = $"RenderGraphTexture_{m_TextureCreationIndex++}";
RTHandleAllocInfo rtAllocInfo = new RTHandleAllocInfo(name)
{
slices = desc.slices,
format = desc.format,
filterMode = desc.filterMode,
wrapModeU = desc.wrapMode,
wrapModeV = desc.wrapMode,
wrapModeW = desc.wrapMode,
dimension = desc.dimension,
enableRandomWrite = desc.enableRandomWrite,
useMipMap = desc.useMipMap,
autoGenerateMips = desc.autoGenerateMips,
anisoLevel = desc.anisoLevel,
mipMapBias = desc.mipMapBias,
isShadowMap = desc.isShadowMap,
msaaSamples = (MSAASamples)desc.msaaSamples,
bindTextureMS = desc.bindTextureMS,
useDynamicScale = desc.useDynamicScale,
useDynamicScaleExplicit = desc.useDynamicScaleExplicit,
memoryless = desc.memoryless,
vrUsage = desc.vrUsage,
enableShadingRate = desc.enableShadingRate,
};
switch (desc.sizeMode)
{
case TextureSizeMode.Explicit:
graphicsResource = RTHandles.Alloc(desc.width, desc.height, rtAllocInfo);
break;
case TextureSizeMode.Scale:
graphicsResource = RTHandles.Alloc(desc.scale, rtAllocInfo);
break;
case TextureSizeMode.Functor:
graphicsResource = RTHandles.Alloc(desc.func, rtAllocInfo);
break;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void UpdateGraphicsResource()
{
if (graphicsResource != null)
graphicsResource.m_Name = GetName();
}
public override void ReleaseGraphicsResource()
{
if (graphicsResource != null)
graphicsResource.Release();
base.ReleaseGraphicsResource();
}
}
class TexturePool : RenderGraphResourcePool<RTHandle>
{
protected override void ReleaseInternalResource(RTHandle res)
{
res.Release();
}
protected override string GetResourceName(in RTHandle res)
{
return res.rt.name;
}
protected override long GetResourceSize(in RTHandle res)
{
return Profiling.Profiler.GetRuntimeMemorySizeLong(res.rt);
}
override protected string GetResourceTypeName()
{
return "Texture";
}
override protected ulong GetSortIndex(RTHandle res)
{
return res.GetUniqueID();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: aeec61a3ffba2f347be4a0b1d667c503
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,317 @@
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
namespace UnityEngine.Rendering.RenderGraphModule
{
// RendererList is a different case so not represented here.
internal enum RenderGraphResourceType
{
Texture = 0,
Buffer,
AccelerationStructure,
Count
}
// For performance reasons, ResourceHandle is readonly.
// To update an existing instance with a new version, recreate it using its copy constructor
internal readonly struct ResourceHandle : IEquatable<ResourceHandle>
{
// Note on handles validity.
// PassData classes used during render graph passes are pooled and because of that, when users don't fill them completely,
// they can contain stale handles from a previous render graph execution that could still be considered valid if we only checked the index.
// In order to avoid using those, we incorporate the execution index in a hash to make sure the handle is coming from the current execution.
// If not, it's considered invalid.
// The validity is stored in a separate field, allowing for a full 32-bit validity check. (2^32 =~ 4B (at 60fps it is more than 2 years) 4,294,967,295 unique execution indices before a collision)
// The m_VersionIndex field contains both index and version:
// - Index (lower 16 bits = 65,535 unique indices)
// - Version (upper 16 bits with one for not versioned. 15 bits = 32767 unique versions).
// - Bit 31 is used as a "not versioned" flag for faster checking.
const uint kIndexMask = 0xFFFF;
const uint kVersionMask = 0x7FFF0000;
const int kVersionShift = 16;
const uint kNotVersionedBit = 0x80000000;
private readonly uint m_VersionIndex;
private readonly uint m_Validity;
private readonly RenderGraphResourceType m_Type;
static uint s_CurrentValidBit = 1;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
s_CurrentValidBit = 1;
}
#endif
public int index
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return (int)(m_VersionIndex & kIndexMask); }
}
public int iType
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return (int)type; }
}
public int version
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return (m_VersionIndex & kNotVersionedBit) != 0 ? -1 : (int)((m_VersionIndex & kVersionMask) >> kVersionShift);
}
}
public RenderGraphResourceType type
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get { return m_Type; }
}
internal ResourceHandle(int index, RenderGraphResourceType type, bool shared)
{
Debug.Assert(index > 0 && index <= 0xFFFF, "ResourceHandle: Invalid index, values should be >0 && <65536");
m_VersionIndex = ((uint)index & kIndexMask) | kNotVersionedBit;
m_Validity = s_CurrentValidBit;
m_Type = type;
}
internal ResourceHandle(in ResourceHandle h, int version)
{
Debug.Assert(version >= 0 && version <= 0x7FFF, "ResourceHandle: Invalid version, values should be >=0 && <32768");
uint versionBits = ((uint)version << kVersionShift) & kVersionMask;
m_VersionIndex = (h.m_VersionIndex & kIndexMask) | versionBits;
m_Validity = h.m_Validity;
m_Type = h.type;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsValid()
{
return m_Validity != 0 && (m_Validity == s_CurrentValidBit);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool IsNull()
{
if (index == 0)
{
// Make sure everything is zero
Debug.Assert(m_VersionIndex == 0);
Debug.Assert(m_Validity == 0);
return true;
}
return false;
}
public static void NewFrame(int executionIndex)
{
uint previousValidBit = s_CurrentValidBit;
var hasher = HashFNV1A32.Create();
hasher.Append(executionIndex);
s_CurrentValidBit = (uint)hasher.value;
// In case the current valid bit is 0, even though perfectly valid, 0 represents an invalid handle, hence we'll
// trigger an invalid state incorrectly. To account for this, we actually skip 0 as a viable s_CurrentValidBit and
// start from 1 again.
if (s_CurrentValidBit == 0)
{
// We need to make sure we don't pick the same value twice.
uint value = 1;
while (previousValidBit == value)
value++;
s_CurrentValidBit = value;
}
}
public bool IsVersioned
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get
{
return (m_VersionIndex & kNotVersionedBit) == 0;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool Equals(ResourceHandle hdl)
{
return hdl.m_VersionIndex == this.m_VersionIndex && hdl.m_Validity == this.m_Validity && hdl.type == this.type;
}
public static bool operator ==(ResourceHandle lhs, ResourceHandle rhs) => lhs.Equals(rhs);
public static bool operator !=(ResourceHandle lhs, ResourceHandle rhs) => !lhs.Equals(rhs);
public override bool Equals(object obj) => obj is ResourceHandle other && Equals(other);
public override int GetHashCode()
{
var hashCode = HashFNV1A32.Create();
hashCode.Append(m_VersionIndex);
hashCode.Append(m_Validity);
hashCode.Append(m_Type);
return hashCode.value;
}
}
class IRenderGraphResource
{
public bool imported;
public bool shared;
public bool sharedExplicitRelease;
public bool requestFallBack;
public uint writeCount;
public uint readCount;
public int cachedHash;
public int transientPassIndex;
public int sharedResourceLastFrameUsed;
public bool isBackBuffer;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual void Reset(IRenderGraphResourcePool _ = null)
{
imported = false;
shared = false;
sharedExplicitRelease = false;
cachedHash = -1;
transientPassIndex = -1;
sharedResourceLastFrameUsed = -1;
requestFallBack = false;
writeCount = 0;
readCount = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual string GetName()
{
return "";
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual bool IsCreated()
{
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual uint IncrementWriteCount()
{
writeCount++;
return writeCount;
}
// readCount is currently not used in the HDRP Compiler.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual void IncrementReadCount()
{
readCount++;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public virtual bool NeedsFallBack()
{
return requestFallBack && writeCount == 0;
}
public virtual void CreatePooledGraphicsResource(int frameIndex, int executionCount, bool usedByAsyncComputePass) { }
public virtual void CreateGraphicsResource() { }
public virtual void UpdateGraphicsResource() { }
public virtual void ReleasePooledGraphicsResource(int frameIndex, int executionCount) { }
public virtual void ReleaseGraphicsResource() { }
public virtual int GetSortIndex() { return 0; }
public virtual HashFNV1A32 GetDescHash() { return HashFNV1A32.Create(); }
}
[DebuggerDisplay("Resource ({GetType().Name}:{GetName()})")]
abstract class RenderGraphResource<DescType, ResType>
: IRenderGraphResource
where DescType : struct
where ResType : class
{
public DescType desc;
public bool validDesc; // Does the descriptor contain valid data (this is not always the case for imported resources)
public ResType graphicsResource;
protected RenderGraphResourcePool<ResType> m_Pool;
protected RenderGraphResource()
{
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void Reset(IRenderGraphResourcePool pool = null)
{
base.Reset();
m_Pool = pool as RenderGraphResourcePool<ResType>;
graphicsResource = null;
validDesc = false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override bool IsCreated()
{
return graphicsResource != null;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override void ReleaseGraphicsResource()
{
graphicsResource = null;
}
public override void CreatePooledGraphicsResource(int frameIndex, int executionCount, bool usedByAsyncComputePass)
{
Debug.Assert(m_Pool != null, "RenderGraphResource: CreatePooledGraphicsResource should only be called for regular pooled resources");
var hash = GetDescHash();
// Resource pooling is a problem with async compute because recycling a pooled resource introduces a
// hidden data dependency that is not visible to the compiler, causing data races between graphics and compute
// queues. In the general case this is solved by the "delayed last use" logic in NativePassCompiler.TryGetDelayedLastUsePassId(),
// which delays returning of the resource to the pool to a point where its memory can be safely reused.
//
// By mixing async usage into the pool hash, we split "graphics queue only" and "touched from async queue"
// into two separate pool buckets, across which memory is never shared. This allows graphics-only resources
// to be reused safely with each other within a frame without needing to delay their return to the pool.
// If we were to NOT do this, the delay logic would have to run for every graphics-only resource as well,
// extending their lifetimes in any graph that uses async compute at all and severely reducing the
// effectiveness of the pooling.
hash.Append(usedByAsyncComputePass);
int hashCode = hash.value;
if (graphicsResource != null)
throw new InvalidOperationException($"RenderGraphResource: Trying to create an already created resource ({GetName()}). Resource was probably declared for writing more than once in the same pass.");
// If the pool doesn't have any available resource that we can use, we will create one
// In any case, we will update the graphicsResource name based on the RenderGraph resource name
if (!m_Pool.TryGetResource(hashCode, out graphicsResource, frameIndex, executionCount))
{
CreateGraphicsResource();
}
else
{
UpdateGraphicsResource();
}
cachedHash = hashCode;
m_Pool.RegisterFrameAllocation(cachedHash, graphicsResource);
}
public override void ReleasePooledGraphicsResource(int frameIndex, int executionCount)
{
if (graphicsResource == null)
throw new InvalidOperationException($"RenderGraphResource: Tried to release a resource ({GetName()}) that was never created. Check that there is at least one pass writing to it first.");
// Shared resources don't use the pool
if (m_Pool != null)
{
m_Pool.ReleaseResource(cachedHash, graphicsResource, frameIndex, executionCount);
m_Pool.UnregisterFrameAllocation(cachedHash, graphicsResource);
}
Reset();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4b7ac9a635582ab4998d4179483bacc5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 712023dda7785b54aa46a5d7c812bda3
@@ -0,0 +1,37 @@
using System;
using System.ComponentModel;
namespace UnityEngine.Rendering.RenderGraphModule.Util
{
/// <summary>
/// Core Shader Resources.
/// </summary>
[Serializable]
[HideInInspector]
[Category("Resources/Render Graph Helper Function Resources")]
[SupportedOnRenderPipeline]
class RenderGraphUtilsResources : IRenderPipelineResources
{
public enum Version
{
Initial,
Count,
Latest = Count - 1
}
[SerializeField, HideInInspector] Version m_Version = Version.Latest;
int IRenderPipelineGraphicsSettings.version => (int)m_Version;
[SerializeField, ResourcePath("Shaders/CoreCopy.shader")]
internal Shader m_CoreCopyPS;
/// <summary>
/// Core Copy shader.
/// </summary>
public Shader coreCopyPS
{
get => m_CoreCopyPS;
set => this.SetValueAndNotify(ref m_CoreCopyPS, value, nameof(m_CoreCopyPS));
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e759d295d21a716488424ff0fcbd88aa
@@ -0,0 +1,47 @@
namespace UnityEngine.Rendering.RenderGraphModule
{
// The validation layer is not guaranteed that all of the builder interface methods will be called.
// This will be added adhoc when needed. Adding them is a feature request, not a bug.
internal class RenderGraphValidationLayer : IRasterRenderGraphBuilder, IBaseRenderGraphBuilder
{
public struct RenderPassInfo
{
public RenderGraphPassType type;
public string name;
}
virtual public void OnPassAddedBegin(in RenderPassInfo renderPassInfo) { }
virtual public void OnPassAddedDispose() { }
virtual public void Clear() { }
// Implement IRasterRenderGraphBuilder and IBaseRenderGraphBuilder with stubs so that the implementation is not mandatory in the implementing class.
virtual public void UseTexture(in TextureHandle input, AccessFlags flags) { }
virtual public void UseGlobalTexture(int propertyId, AccessFlags flags) { }
virtual public void UseAllGlobalTextures(bool enable) { }
virtual public void SetGlobalTextureAfterPass(in TextureHandle input, int propertyId) { }
virtual public BufferHandle UseBuffer(in BufferHandle input, AccessFlags flags) { return input; }
virtual public void SetRenderAttachment(TextureHandle tex, int index, AccessFlags flags, int mipLevel, int depthSlice) { }
virtual public void SetRenderAttachmentDepth(TextureHandle tex, AccessFlags flags, int mipLevel, int depthSlice) { }
virtual public void SetInputAttachment(TextureHandle tex, int index, AccessFlags flags, int mipLevel, int depthSlice) { }
// These aren't called and currently not supported for validation
public TextureHandle CreateTransientTexture(in TextureDesc desc) { return TextureHandle.nullHandle; }
public TextureHandle CreateTransientTexture(in TextureHandle texture) { return TextureHandle.nullHandle; }
public BufferHandle CreateTransientBuffer(in BufferDesc desc) { return BufferHandle.nullHandle; }
public BufferHandle CreateTransientBuffer(in BufferHandle computebuffer) { return BufferHandle.nullHandle; }
public void UseRendererList(in RendererListHandle input) { }
public void EnableAsyncCompute(bool value) { }
public void AllowPassCulling(bool value) { }
public void AllowGlobalStateModification(bool value) { }
public void EnableFoveatedRasterization(bool value) { }
public void GenerateDebugData(bool value) { }
public TextureHandle SetRandomAccessAttachment(TextureHandle tex, int index, AccessFlags flags) { return TextureHandle.nullHandle; }
public BufferHandle UseBufferRandomAccess(BufferHandle tex, int index, AccessFlags flags = AccessFlags.Read) { return tex; }
public BufferHandle UseBufferRandomAccess(BufferHandle tex, int index, bool preserveCounterValue, AccessFlags flags) { return tex; }
public void SetShadingRateImageAttachment(in TextureHandle tex) { }
public void SetShadingRateFragmentSize(ShadingRateFragmentSize shadingRateFragmentSize) { }
public void SetShadingRateCombiner(ShadingRateCombinerStage stage, ShadingRateCombiner combiner) { }
public void SetExtendedFeatureFlags(ExtendedFeatureFlags extendedFeatureFlags) { }
public void SetRenderFunc<PassData>(BaseRenderFunc<PassData, RasterGraphContext> renderFunc) where PassData : class, new() { }
virtual public void Dispose() { }
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 912f677447056f04b9e20add2ff2c531