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,6 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Core.Editor")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Core.Editor.Tests")]
[assembly: InternalsVisibleTo("UnityEngine.TestTools.Graphics.Contexts")]
[assembly: InternalsVisibleTo("Unity.Entities.Graphics")]
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0eaef5c9e4d984cd295dfacc57398f10
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,36 @@
namespace UnityEngine.Rendering
{
/// <summary>
/// Predefined batch layer values used by the GPU Resident Drawer.
/// </summary>
public class BatchLayer
{
/// <summary>
/// Batch layer for BatchRendererGroup direct draw commands produced by the GPU Resident Drawer.
/// </summary>
public const byte InstanceCullingDirect = 29;
/// <summary>
/// Batch layer for BatchRendererGroup indirect draw commands produced by the GPU Resident Drawer.
/// </summary>
public const byte InstanceCullingIndirect = 28;
/// <summary>
/// A batch layer mask to include BatchRendererGroup direct draw commands produced by the GPU Resident Drawer.
/// Batch layer masks can be used to filter the set of draw calls in a renderer list.
/// </summary>
public const uint InstanceCullingDirectMask = 1u << InstanceCullingDirect;
/// <summary>
/// A batch layer mask to include BatchRendererGroup indirect draw commands produced by the GPU Resident Drawer.
/// Batch layer masks can be used to filter the set of draw calls in a renderer list.
/// </summary>
public const uint InstanceCullingIndirectMask = 1u << InstanceCullingIndirect;
/// <summary>
/// A batch layer mask to include BatchRendererGroup direct and indirect draw commands produced by the GPU Resident Drawer.
/// Batch layer masks can be used to filter the set of draw calls in a renderer list.
/// </summary>
public const uint InstanceCullingMask = InstanceCullingDirectMask | InstanceCullingIndirectMask;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 2885097eeb355a54ea56dc5b842d3469
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 80469c239862e3c48ba6b3917aa31891
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,221 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using UnityEngine.Assertions;
using Unity.Collections;
using Unity.Jobs;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Profiling;
using Unity.Profiling.LowLevel;
namespace UnityEngine.Rendering
{
internal class CPUDrawInstanceData
{
/// <summary>
/// Sorts and removes the destroyed draw instance indices from the CPU draw instance, batch, and
/// range data structures using binary search. Cost scales with total live draw instance count, not just the number removed.
/// </summary>
static readonly ProfilerMarker k_DestroyDrawInstanceIndices =
new ProfilerMarker(ProfilerCategory.Render, "DestroyDrawInstanceIndices.RemoveDrawInstanceIndices", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Removes a batch of GPU instances from all CPU draw data structures. Sorts instance
/// handles, maps them to draw instance indices via a parallel job, then removes those
/// indices. Cost scales with total live draw instance count, not just the number removed.
/// </summary>
static readonly ProfilerMarker k_DestroyDrawInstances =
new ProfilerMarker(ProfilerCategory.Render, "DestroyDrawInstances", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Sorts the destroyed instance handle array in parallel. A prerequisite for the
/// binary-search index-lookup job in DestroyDrawInstances.
/// </summary>
static readonly ProfilerMarker k_DestroyDrawInstancesParallelSort =
new ProfilerMarker(ProfilerCategory.Render, "DestroyDrawInstances.ParallelSort", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Sorts the destroyed batch material ID array in parallel. A prerequisite for the
/// binary-search index-lookup job in DestroyMaterialDrawInstances.
/// </summary>
static readonly ProfilerMarker k_DestroyedBatchMaterialsParallelSort =
new ProfilerMarker(ProfilerCategory.Render, "DestroyedBatchMaterials.ParallelSort", MarkerFlags.VerbosityAdvanced);
public NativeList<DrawInstance> drawInstances => m_DrawInstances;
public NativeParallelHashMap<DrawKey, int> batchHash => m_BatchHash;
public NativeList<DrawBatch> drawBatches => m_DrawBatches;
public NativeParallelHashMap<RangeKey, int> rangeHash => m_RangeHash;
public NativeList<DrawRange> drawRanges => m_DrawRanges;
public NativeArray<int> drawBatchIndices => m_DrawBatchIndices.AsArray();
public NativeArray<int> drawInstanceIndices => m_DrawInstanceIndices.AsArray();
private NativeParallelHashMap<RangeKey, int> m_RangeHash; // index in m_DrawRanges, hashes by range state
private NativeList<DrawRange> m_DrawRanges;
private NativeParallelHashMap<DrawKey, int> m_BatchHash; // index in m_DrawBatches, hashed by draw state
private NativeList<DrawBatch> m_DrawBatches;
private NativeList<DrawInstance> m_DrawInstances;
private NativeList<int> m_DrawInstanceIndices; // DOTS instance index, arranged in contiguous blocks in m_DrawBatches order (see DrawBatch.instanceOffset, DrawBatch.instanceCount)
private NativeList<int> m_DrawBatchIndices; // index in m_DrawBatches, arranged in contiguous blocks in m_DrawRanges order (see DrawRange.drawOffset, DrawRange.drawCount)
private bool m_NeedsRebuild;
public bool valid => m_DrawInstances.IsCreated;
public void Initialize()
{
Assert.IsTrue(!valid);
m_RangeHash = new NativeParallelHashMap<RangeKey, int>(1024, Allocator.Persistent);
m_DrawRanges = new NativeList<DrawRange>(Allocator.Persistent);
m_BatchHash = new NativeParallelHashMap<DrawKey, int>(1024, Allocator.Persistent);
m_DrawBatches = new NativeList<DrawBatch>(Allocator.Persistent);
m_DrawInstances = new NativeList<DrawInstance>(1024, Allocator.Persistent);
m_DrawInstanceIndices = new NativeList<int>(1024, Allocator.Persistent);
m_DrawBatchIndices = new NativeList<int>(1024, Allocator.Persistent);
}
public void Dispose()
{
if (m_DrawBatchIndices.IsCreated)
m_DrawBatchIndices.Dispose();
if (m_DrawInstanceIndices.IsCreated)
m_DrawInstanceIndices.Dispose();
if (m_DrawInstances.IsCreated)
m_DrawInstances.Dispose();
if (m_DrawBatches.IsCreated)
m_DrawBatches.Dispose();
if (m_BatchHash.IsCreated)
m_BatchHash.Dispose();
if (m_DrawRanges.IsCreated)
m_DrawRanges.Dispose();
if (m_RangeHash.IsCreated)
m_RangeHash.Dispose();
}
public void RebuildDrawListsIfNeeded()
{
if (!m_NeedsRebuild)
return;
m_NeedsRebuild = false;
Assert.IsTrue(m_RangeHash.Count() == m_DrawRanges.Length);
Assert.IsTrue(m_BatchHash.Count() == m_DrawBatches.Length);
m_DrawInstanceIndices.ResizeUninitialized(m_DrawInstances.Length);
m_DrawBatchIndices.ResizeUninitialized(m_DrawBatches.Length);
var internalDrawIndex = new NativeArray<int>(drawBatches.Length * BuildDrawListsJob.k_IntsPerCacheLine, Allocator.TempJob, NativeArrayOptions.ClearMemory);
var prefixSumDrawInstancesJob = new PrefixSumDrawInstancesJob()
{
rangeHash = m_RangeHash,
drawRanges = m_DrawRanges,
drawBatches = m_DrawBatches,
drawBatchIndices = m_DrawBatchIndices.AsArray()
};
var prefixSumJobHandle = prefixSumDrawInstancesJob.Schedule();
new BuildDrawListsJob()
{
drawInstances = m_DrawInstances,
batchHash = m_BatchHash,
drawBatches = m_DrawBatches,
internalDrawIndex = internalDrawIndex,
drawInstanceIndices = m_DrawInstanceIndices.AsArray(),
}
.RunParallel(m_DrawInstances.Length, 128, prefixSumJobHandle);
internalDrawIndex.Dispose();
}
public unsafe void DestroyDrawInstanceIndices(NativeArray<int> drawInstanceIndicesToDestroy)
{
using var _ = k_DestroyDrawInstanceIndices.Auto();
drawInstanceIndicesToDestroy.ParallelSort().Complete();
CPUDrawInstanceDataBurst.RemoveDrawInstanceIndices(drawInstanceIndicesToDestroy,
ref m_DrawInstances,
ref m_RangeHash,
ref m_BatchHash,
ref m_DrawRanges,
ref m_DrawBatches);
}
public unsafe void DestroyDrawInstances(NativeArray<InstanceHandle> destroyedInstances)
{
if (m_DrawInstances.IsEmpty || destroyedInstances.Length == 0)
return;
using var _ = k_DestroyDrawInstances.Auto();
NeedsRebuild();
var destroyedInstancesSorted = new NativeArray<InstanceHandle>(destroyedInstances, Allocator.TempJob);
Assert.AreEqual(UnsafeUtility.SizeOf<InstanceHandle>(), UnsafeUtility.SizeOf<int>());
using (k_DestroyDrawInstancesParallelSort.Auto())
{
destroyedInstancesSorted.Reinterpret<int>().ParallelSort().Complete();
}
var drawInstanceIndicesToDestroy = new NativeList<int>(m_DrawInstances.Length, Allocator.TempJob);
new FindDrawInstancesJob()
{
instancesSorted = destroyedInstancesSorted,
drawInstances = m_DrawInstances,
outDrawInstanceIndicesWriter = drawInstanceIndicesToDestroy.AsParallelWriter()
}
.RunBatchParallel(m_DrawInstances.Length, FindDrawInstancesJob.k_MaxBatchSize);
DestroyDrawInstanceIndices(drawInstanceIndicesToDestroy.AsArray());
destroyedInstancesSorted.Dispose();
drawInstanceIndicesToDestroy.Dispose();
}
public unsafe void DestroyMaterialDrawInstances(NativeArray<uint> destroyedBatchMaterials)
{
if (m_DrawInstances.IsEmpty || destroyedBatchMaterials.Length == 0)
return;
NeedsRebuild();
var destroyedBatchMaterialsSorted = new NativeArray<uint>(destroyedBatchMaterials, Allocator.TempJob);
using (k_DestroyedBatchMaterialsParallelSort.Auto())
{
destroyedBatchMaterialsSorted.Reinterpret<int>().ParallelSort().Complete();
}
var drawInstanceIndicesToDestroy = new NativeList<int>(m_DrawInstances.Length, Allocator.TempJob);
new FindMaterialDrawInstancesJob()
{
materialsSorted = destroyedBatchMaterialsSorted,
drawInstances = m_DrawInstances,
outDrawInstanceIndicesWriter = drawInstanceIndicesToDestroy.AsParallelWriter()
}
.RunBatchParallel(m_DrawInstances.Length, FindMaterialDrawInstancesJob.k_MaxBatchSize);
DestroyDrawInstanceIndices(drawInstanceIndicesToDestroy.AsArray());
destroyedBatchMaterialsSorted.Dispose();
drawInstanceIndicesToDestroy.Dispose();
}
public void NeedsRebuild()
{
m_NeedsRebuild = true;
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 8967952de1d564742ae0197935b63bd7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,74 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using Unity.Collections;
using UnityEngine.Rendering;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
[BurstCompile]
internal static class CPUDrawInstanceDataBurst
{
private static void RemoveDrawRange(in RangeKey key, ref NativeParallelHashMap<RangeKey, int> rangeHash, ref NativeList<DrawRange> drawRanges)
{
int drawRangeIndex = rangeHash[key];
ref DrawRange lastDrawRange = ref drawRanges.ElementAt(drawRanges.Length - 1);
rangeHash[lastDrawRange.key] = drawRangeIndex;
rangeHash.Remove(key);
drawRanges.RemoveAtSwapBack(drawRangeIndex);
}
private static void RemoveDrawBatch(in DrawKey key, ref NativeParallelHashMap<RangeKey, int> rangeHash, ref NativeParallelHashMap<DrawKey, int> batchHash,
ref NativeList<DrawRange> drawRanges, ref NativeList<DrawBatch> drawBatches)
{
int drawBatchIndex = batchHash[key];
ref DrawBatch drawBatch = ref drawBatches.ElementAt(drawBatchIndex);
int drawRangeIndex = rangeHash[key.range];
ref DrawRange drawRange = ref drawRanges.ElementAt(drawRangeIndex);
Assert.IsTrue(drawRange.drawCount > 0);
if (--drawRange.drawCount == 0)
RemoveDrawRange(drawRange.key, ref rangeHash, ref drawRanges);
ref DrawBatch lastDrawBatch = ref drawBatches.ElementAt(drawBatches.Length - 1);
batchHash[lastDrawBatch.key] = drawBatchIndex;
batchHash.Remove(key);
drawBatches.RemoveAtSwapBack(drawBatchIndex);
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
public static unsafe void RemoveDrawInstanceIndices(in NativeArray<int> drawInstanceIndicesSorted, ref NativeList<DrawInstance> drawInstances, ref NativeParallelHashMap<RangeKey, int> rangeHash,
ref NativeParallelHashMap<DrawKey, int> batchHash, ref NativeList<DrawRange> drawRanges, ref NativeList<DrawBatch> drawBatches)
{
var drawInstancesPtr = (DrawInstance*)drawInstances.GetUnsafePtr();
var drawInstancesNewBack = drawInstances.Length - 1;
for (int indexRev = drawInstanceIndicesSorted.Length - 1; indexRev >= 0; --indexRev)
{
int indexToRemove = drawInstanceIndicesSorted[indexRev];
DrawInstance* drawInstance = drawInstancesPtr + indexToRemove;
int drawBatchIndex = batchHash[drawInstance->key];
ref DrawBatch drawBatch = ref drawBatches.ElementAt(drawBatchIndex);
Assert.IsTrue(drawBatch.instanceCount > 0);
if (--drawBatch.instanceCount == 0)
RemoveDrawBatch(drawBatch.key, ref rangeHash, ref batchHash, ref drawRanges, ref drawBatches);
UnsafeUtility.MemCpy(drawInstance, drawInstancesPtr + drawInstancesNewBack--, sizeof(DrawInstance));
}
drawInstances.ResizeUninitialized(drawInstancesNewBack + 1);
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: f89188da7ac3dd74e920a8a99c1c0de1
@@ -0,0 +1,237 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using System.Threading;
using UnityEngine.Assertions;
using Unity.Collections;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Burst;
using Unity.Mathematics;
[assembly: RegisterGenericJobType(typeof(UnityEngine.Rendering.FindNonRegisteredInstanceIDsJob<UnityEngine.Rendering.MeshInfo>))]
[assembly: RegisterGenericJobType(typeof(UnityEngine.Rendering.FindNonRegisteredInstanceIDsJob<UnityEngine.Rendering.GPUDrivenMaterial>))]
namespace UnityEngine.Rendering
{
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal struct PrefixSumDrawInstancesJob : IJob
{
[ReadOnly] public NativeParallelHashMap<RangeKey, int> rangeHash;
public NativeList<DrawRange> drawRanges;
public NativeList<DrawBatch> drawBatches;
public NativeArray<int> drawBatchIndices;
public void Execute()
{
Assert.AreEqual(rangeHash.Count(), drawRanges.Length);
Assert.AreEqual(drawBatchIndices.Length, drawBatches.Length);
// Prefix sum to calculate draw offsets for each DrawRange
int drawPrefixSum = 0;
for (int i = 0; i < drawRanges.Length; ++i)
{
ref DrawRange drawRange = ref drawRanges.ElementAt(i);
drawRange.drawOffset = drawPrefixSum;
drawPrefixSum += drawRange.drawCount;
}
// Generate DrawBatch index ranges for each DrawRange
var internalRangeIndex = new NativeArray<int>(drawRanges.Length, Allocator.Temp);
for (int i = 0; i < drawBatches.Length; ++i)
{
ref DrawBatch drawBatch = ref drawBatches.ElementAt(i);
Assert.IsTrue(drawBatch.instanceCount > 0);
if (rangeHash.TryGetValue(drawBatch.key.range, out int drawRangeIndex))
{
ref DrawRange drawRange = ref drawRanges.ElementAt(drawRangeIndex);
drawBatchIndices[drawRange.drawOffset + internalRangeIndex[drawRangeIndex]] = i;
internalRangeIndex[drawRangeIndex]++;
}
}
// Prefix sum to calculate instance offsets for each DrawCommand
int drawInstancesPrefixSum = 0;
for (int i = 0; i < drawBatchIndices.Length; ++i)
{
// DrawIndices remap to get DrawCommands ordered by DrawRange
var drawBatchIndex = drawBatchIndices[i];
ref DrawBatch drawBatch = ref drawBatches.ElementAt(drawBatchIndex);
drawBatch.instanceOffset = drawInstancesPrefixSum;
drawInstancesPrefixSum += drawBatch.instanceCount;
}
internalRangeIndex.Dispose();
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal unsafe struct BuildDrawListsJob : IJobParallelFor
{
public const int k_IntsPerCacheLine = JobsUtility.CacheLineSize / sizeof(int);
[ReadOnly] public NativeParallelHashMap<DrawKey, int> batchHash;
[NativeDisableContainerSafetyRestriction, NoAlias] [ReadOnly] public NativeList<DrawInstance> drawInstances;
[NativeDisableContainerSafetyRestriction, NoAlias] [ReadOnly] public NativeList<DrawBatch> drawBatches;
[NativeDisableContainerSafetyRestriction, NoAlias] [WriteOnly] public NativeArray<int> internalDrawIndex;
[NativeDisableContainerSafetyRestriction, NoAlias] [WriteOnly] public NativeArray<int> drawInstanceIndices;
private unsafe static int IncrementCounter(int* counter)
{
return Interlocked.Increment(ref UnsafeUtility.AsRef<int>(counter)) - 1;
}
public void Execute(int index)
{
// Generate instance index ranges for each DrawCommand
ref DrawInstance drawInstance = ref drawInstances.ElementAt(index);
int drawBatchIndex = batchHash[drawInstance.key];
ref DrawBatch drawBatch = ref drawBatches.ElementAt(drawBatchIndex);
var offset = IncrementCounter((int*)internalDrawIndex.GetUnsafePtr() + drawBatchIndex * k_IntsPerCacheLine);
var writeIndex = drawBatch.instanceOffset + offset;
drawInstanceIndices[writeIndex] = drawInstance.instanceIndex;
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal unsafe struct FindDrawInstancesJob : IJobParallelForBatch
{
public const int k_MaxBatchSize = 128;
[ReadOnly] public NativeArray<InstanceHandle> instancesSorted;
[NativeDisableContainerSafetyRestriction, NoAlias] [ReadOnly] public NativeList<DrawInstance> drawInstances;
[WriteOnly] public NativeList<int>.ParallelWriter outDrawInstanceIndicesWriter;
public void Execute(int startIndex, int count)
{
int* instancesToRemovePtr = stackalloc int[k_MaxBatchSize];
var instancesToRemove = new UnsafeList<int>(instancesToRemovePtr, k_MaxBatchSize);
instancesToRemove.Length = 0;
for (int i = startIndex; i < startIndex + count; ++i)
{
ref DrawInstance drawInstance = ref drawInstances.ElementAt(i);
if (instancesSorted.BinarySearch(InstanceHandle.Create(drawInstance.instanceIndex)) >= 0)
instancesToRemove.AddNoResize(i);
}
outDrawInstanceIndicesWriter.AddRangeNoResize(instancesToRemove);
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal unsafe struct FindMaterialDrawInstancesJob : IJobParallelForBatch
{
public const int k_MaxBatchSize = 128;
[ReadOnly] public NativeArray<uint> materialsSorted;
[NativeDisableContainerSafetyRestriction, NoAlias] [ReadOnly] public NativeList<DrawInstance> drawInstances;
[WriteOnly] public NativeList<int>.ParallelWriter outDrawInstanceIndicesWriter;
public void Execute(int startIndex, int count)
{
int* instancesToRemovePtr = stackalloc int[k_MaxBatchSize];
var instancesToRemove = new UnsafeList<int>(instancesToRemovePtr, k_MaxBatchSize);
instancesToRemove.Length = 0;
for (int i = startIndex; i < startIndex + count; ++i)
{
ref DrawInstance drawInstance = ref drawInstances.ElementAt(i);
if (materialsSorted.BinarySearch(drawInstance.key.materialID.value) >= 0)
instancesToRemove.AddNoResize(i);
}
outDrawInstanceIndicesWriter.AddRangeNoResize(instancesToRemove);
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal struct FindNonRegisteredInstanceIDsJob<T> : IJobParallelFor where T : unmanaged
{
public const int MaxBatchSize = 128;
[ReadOnly] public NativeArray<JaggedJobRange> jobRanges;
[ReadOnly] public JaggedSpan<EntityId> jaggedInstanceIDs;
[ReadOnly] public NativeParallelHashMap<EntityId, T> hashMap;
[WriteOnly] public NativeParallelHashSet<EntityId>.ParallelWriter outInstanceIDWriter;
public unsafe void Execute(int jobIndex)
{
JaggedJobRange jobRange = jobRanges[jobIndex];
NativeArray<EntityId> instanceIDs = jaggedInstanceIDs[jobRange.sectionIndex];
for (int i = jobRange.localStart; i < jobRange.localEnd; ++i)
{
EntityId instanceID = instanceIDs[i];
if (!hashMap.ContainsKey(instanceID))
outInstanceIDWriter.Add(instanceID);
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal struct RegisterNewMaterialsJob : IJobParallelFor
{
[ReadOnly] public NativeArray<EntityId> instanceIDs;
[ReadOnly] public NativeArray<GPUDrivenMaterial> materials;
[WriteOnly] public NativeParallelHashMap<EntityId, GPUDrivenMaterial>.ParallelWriter materialMap;
public unsafe void Execute(int index)
{
bool success = materialMap.TryAdd(instanceIDs[index], materials.ElementAt(index));
Assert.IsTrue(success);
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal struct RegisterNewMeshesJob : IJobParallelFor
{
[ReadOnly] public NativeArray<EntityId> instanceIDs;
[ReadOnly] public NativeArray<BatchMeshID> batchMeshIDs;
[ReadOnly] public NativeArray<GPUDrivenMeshData> meshDatas;
[ReadOnly] public NativeArray<int> subMeshOffsets;
[ReadOnly] public NativeArray<GPUDrivenSubMesh> subMeshBuffer;
[WriteOnly] public NativeParallelHashMap<EntityId, MeshInfo>.ParallelWriter meshMap;
public unsafe void Execute(int index)
{
Assert.IsTrue(instanceIDs.Length == meshDatas.Length);
Assert.IsTrue(instanceIDs.Length == subMeshOffsets.Length);
EntityId instanceID = instanceIDs[index];
int subMeshOffset = subMeshOffsets[index];
GPUDrivenMeshData meshData = meshDatas[index];
BatchMeshID batchMeshID = batchMeshIDs[index];
int totalSubMeshCount = meshData.subMeshCount * math.max(meshData.meshLodCount, 1);
NativeArray<GPUDrivenSubMesh> subMeshes = subMeshBuffer.GetSubArray(subMeshOffset, totalSubMeshCount);
var embeddedSubMeshes = new EmbeddedArray64<GPUDrivenSubMesh>(subMeshes, Allocator.Persistent);
MeshInfo meshInfo = default;
meshInfo.meshID = batchMeshID;
meshInfo.meshLodCount = meshData.meshLodCount;
meshInfo.meshLodSelectionCurve = meshData.meshLodSelectionCurve;
meshInfo.subMeshes = embeddedSubMeshes;
bool success = meshMap.TryAdd(instanceID, meshInfo);
Assert.IsTrue(success);
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 84f2d5310507cd645a110b652fbfd1d7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,540 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using Unity.Collections;
using Unity.Jobs;
using Unity.Profiling;
using Unity.Profiling.LowLevel;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
internal delegate void OnCullingCompleteCallback(JobHandle jobHandle, in BatchCullingContext cullingContext, in BatchCullingOutput cullingOutput);
internal struct MeshInfo
{
public BatchMeshID meshID;
public int meshLodCount;
public Mesh.LodSelectionCurve meshLodSelectionCurve;
public EmbeddedArray64<GPUDrivenSubMesh> subMeshes;
public bool isLodSelectionActive => meshLodCount > 1;
public bool EqualsSourceData(in GPUDrivenMeshData otherData, NativeArray<GPUDrivenSubMesh> otherSubMeshes)
{
if (meshLodCount != otherData.meshLodCount)
return false;
if (meshLodSelectionCurve.lodBias != otherData.meshLodSelectionCurve.lodBias)
return false;
if (meshLodSelectionCurve.lodSlope != otherData.meshLodSelectionCurve.lodSlope)
return false;
if (subMeshes.Length != otherSubMeshes.Length)
return false;
for (int i = 0; i < subMeshes.Length; i++)
{
GPUDrivenSubMesh oldSubMesh = subMeshes[i];
GPUDrivenSubMesh newSubMesh = otherSubMeshes[i];
if (!oldSubMesh.Equals(newSubMesh))
return false;
}
return true;
}
}
internal class InstanceCullingBatcher : IDisposable
{
/// <summary>
/// Filters the incoming mesh IDs to find previously unseen ones, registers them with the
/// BatchRendererGroup, then fetches and stores their sub-mesh data. Cost scales with the
/// number of unique new meshes and their sub-mesh counts.
/// </summary>
static readonly ProfilerMarker k_RegisterMeshes =
new ProfilerMarker(ProfilerCategory.Render, "RegisterMeshes", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Filters the incoming material IDs to find previously unseen ones, then registers them
/// with the BatchRendererGroup. Cost scales with the number of unique new materials.
/// </summary>
static readonly ProfilerMarker k_RegisterMaterials =
new ProfilerMarker(ProfilerCategory.Render, "RegisterMaterials", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Unregisters each destroyed material from the BatchRendererGroup, removes it from the
/// material map, and removes all associated draw instances from CPU draw data structures.
/// </summary>
static readonly ProfilerMarker k_DestroyMaterials =
new ProfilerMarker(ProfilerCategory.Render, "DestroyMaterials", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Unregisters each destroyed mesh from the BatchRendererGroup, disposes its sub-mesh
/// data, and removes it from the mesh map.
/// </summary>
static readonly ProfilerMarker k_DestroyMeshes =
new ProfilerMarker(ProfilerCategory.Render, "DestroyMeshes", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Removes stale draw instances for the given instances, then creates new draw batches
/// by grouping instances by mesh, material, and render state. Marks the draw lists dirty
/// for rebuild on next cull.
/// </summary>
internal static readonly ProfilerMarker k_BuildBatches =
new ProfilerMarker(ProfilerCategory.Render, "BuildBatches", MarkerFlags.VerbosityAdvanced);
/// <summary>
/// Registers any new meshes and materials in the update batch, then rebuilds draw batches
/// for the affected instances. Combines RegisterMeshes, RegisterMaterials,
/// and BuildBatches in a single scope.
/// </summary>
static readonly ProfilerMarker k_RegisterAndBuildBatches =
new ProfilerMarker(ProfilerCategory.Render, "RegisterAndBuildBatches");
/// <summary>
/// Registers any newly-encountered materials and meshes with the BatchRendererGroup
/// for an update batch, before draw batches that reference them are built. The
/// surrounding BuildBatches step is intentionally excluded so the recorder doesn't
/// double-count with <c>k_BuildBatches</c>.
/// </summary>
internal static readonly ProfilerMarker k_RegisterMaterialsAndMeshes =
new ProfilerMarker(ProfilerCategory.Render, "GRD.RegisterMaterialsAndMeshes");
/// <summary>
/// Schedules the per-frame culling job tree (frustum, LOD, occlusion). Covers the
/// CPU-side dispatch and scheduling cost only; the actual worker-thread job execution
/// is not included.
/// </summary>
internal static readonly ProfilerMarker k_CreateCullJobTree =
new ProfilerMarker(ProfilerCategory.Render, "GRD.CreateCullJobTree");
private GPUResidentContext m_GRDContext;
private InstanceDataSystem m_InstanceDataSystem;
private LODGroupDataSystem m_LODGroupDataSystem;
private CPUDrawInstanceData m_DrawInstanceData;
private BatchRendererGroup m_BRG;
private OnCullingCompleteCallback m_OnCompleteCallback;
private NativeParallelHashMap<GPUArchetypeHandle, BatchID> m_BatchIDs;
private NativeParallelHashMap<EntityId, GPUDrivenMaterial> m_MaterialMap;
private NativeParallelHashMap<EntityId, MeshInfo> m_MeshMap;
private int m_CachedInstanceDataBufferLayoutVersion;
private NativeArray<BatchMeshID> m_TempBatchMeshIDs;
private NativeHashSet<EntityId> m_TempChangedMeshIDs;
public NativeParallelHashMap<EntityId, GPUDrivenMaterial> materialMap => m_MaterialMap;
public NativeParallelHashMap<EntityId, MeshInfo> meshMap => m_MeshMap;
public void Initialize(GPUResidentContext grdContext,
in GPUResidentDrawerSettings settings,
BatchRendererGroup.OnFinishedCulling onFinishedCulling,
OnCullingCompleteCallback onCompleteCallback = null)
{
m_GRDContext = grdContext;
m_InstanceDataSystem = grdContext.instanceDataSystem;
m_LODGroupDataSystem = grdContext.lodGroupDataSystem;
m_DrawInstanceData = new CPUDrawInstanceData();
m_DrawInstanceData.Initialize();
m_BRG = new BatchRendererGroup(new BatchRendererGroupCreateInfo
{
cullingCallback = OnPerformCulling,
finishedCullingCallback = onFinishedCulling,
userContext = IntPtr.Zero
});
#if UNITY_EDITOR
if (settings.pickingShader != null)
{
var mat = new Material(settings.pickingShader);
mat.hideFlags = HideFlags.HideAndDontSave;
m_BRG.SetPickingMaterial(mat);
}
if (settings.loadingShader != null)
{
var mat = new Material(settings.loadingShader);
mat.hideFlags = HideFlags.HideAndDontSave;
m_BRG.SetLoadingMaterial(mat);
}
if (settings.errorShader != null)
{
var mat = new Material(settings.errorShader);
mat.hideFlags = HideFlags.HideAndDontSave;
m_BRG.SetErrorMaterial(mat);
}
m_BRG.SetEnabledViewTypes(new BatchCullingViewType[]
{
BatchCullingViewType.Light,
BatchCullingViewType.Camera,
BatchCullingViewType.Picking,
BatchCullingViewType.SelectionOutline,
BatchCullingViewType.Filtering
});
#endif
m_CachedInstanceDataBufferLayoutVersion = -1;
m_OnCompleteCallback = onCompleteCallback;
m_MaterialMap = new NativeParallelHashMap<EntityId, GPUDrivenMaterial>(64, Allocator.Persistent);
m_MeshMap = new NativeParallelHashMap<EntityId, MeshInfo>(64, Allocator.Persistent);
m_BatchIDs = new NativeParallelHashMap<GPUArchetypeHandle, BatchID>(8, Allocator.Persistent);
m_InstanceDataSystem.onGPUBufferLayoutChanged += UpdateInstanceDataBufferLayoutVersion;
}
public void Dispose()
{
m_OnCompleteCallback = null;
m_InstanceDataSystem.onGPUBufferLayoutChanged -= UpdateInstanceDataBufferLayoutVersion;
foreach (var batchID in m_BatchIDs)
{
m_BRG.RemoveBatch(batchID.Value);
}
m_BatchIDs.Dispose();
if (m_BRG != null)
m_BRG.Dispose();
m_DrawInstanceData.Dispose();
m_DrawInstanceData = null;
m_MaterialMap.Dispose();
foreach (var kv in m_MeshMap)
kv.Value.subMeshes.Dispose();
m_MeshMap.Dispose();
}
private BatchID AddBatch(GPUArchetypeHandle archetype)
{
if (m_CachedInstanceDataBufferLayoutVersion != m_InstanceDataSystem.gpuBufferLayoutVersion)
return BatchID.Null;
var instanceDataBuffer = m_InstanceDataSystem.gpuBuffer;
var archetypeDesc = m_InstanceDataSystem.archetypeManager.GetRef().GetArchetypeDesc(archetype);
var components = archetypeDesc.components;
var metadatas = new NativeArray<MetadataValue>(components.Length, Allocator.Temp);
for (int i = 0; i < metadatas.Length; ++i)
{
var componentHandle = components[i];
var compIndex = instanceDataBuffer.GetComponentIndex(componentHandle).index;
var metadata = m_InstanceDataSystem.gpuBuffer.componentsMetadata[compIndex];
metadatas[i] = metadata;
}
return m_BRG.AddBatch(metadatas, m_InstanceDataSystem.gpuBufferHandle);
}
private void UpdateInstanceDataBufferLayoutVersion()
{
if (m_CachedInstanceDataBufferLayoutVersion != m_InstanceDataSystem.gpuBufferLayoutVersion)
{
m_CachedInstanceDataBufferLayoutVersion = m_InstanceDataSystem.gpuBufferLayoutVersion;
foreach (var kv in m_BatchIDs)
{
var batchID = kv.Value;
m_BRG.RemoveBatch(batchID);
}
m_BatchIDs.Clear();
var archetypeManager = m_InstanceDataSystem.archetypeManager;
var archetypeCount = archetypeManager.GetRef().GetArchetypesCount();
for (int i = 0; i < archetypeCount; i++)
{
var archetype = GPUArchetypeHandle.Create((short)i);
var batchID = AddBatch(archetype);
m_BatchIDs.Add(archetype, batchID);
}
}
}
private void OnFetchMeshesDataForRegistration(NativeArray<EntityId> meshIDs,
NativeArray<GPUDrivenMeshData> meshDatas,
NativeArray<int> subMeshOffsets,
NativeArray<GPUDrivenSubMesh> subMeshes)
{
Assert.IsTrue(meshIDs.Length == meshDatas.Length);
Assert.IsTrue(m_TempBatchMeshIDs.Length == meshIDs.Length);
new RegisterNewMeshesJob
{
meshMap = m_MeshMap.AsParallelWriter(),
instanceIDs = meshIDs,
batchMeshIDs = m_TempBatchMeshIDs,
meshDatas = meshDatas,
subMeshOffsets = subMeshOffsets,
subMeshBuffer = subMeshes,
}
.RunParallel(meshIDs.Length, 128);
}
private void RegisterMeshes(JaggedSpan<EntityId> meshIDs)
{
using var _ = k_RegisterMeshes.Auto();
var jobRanges = JaggedJobRange.FromSpanWithMaxBatchSize(meshIDs, FindNonRegisteredInstanceIDsJob<MeshInfo>.MaxBatchSize, Allocator.TempJob);
var newMeshSet = new NativeParallelHashSet<EntityId>(meshIDs.totalLength, Allocator.TempJob);
new FindNonRegisteredInstanceIDsJob<MeshInfo>
{
jobRanges = jobRanges.AsArray(),
jaggedInstanceIDs = meshIDs,
hashMap = m_MeshMap,
outInstanceIDWriter = newMeshSet.AsParallelWriter()
}
.RunParallel(jobRanges);
if (!newMeshSet.IsEmpty)
{
NativeArray<EntityId> newMeshIDs = newMeshSet.ToNativeArray(Allocator.TempJob);
var batchMeshIDs = new NativeArray<BatchMeshID>(newMeshIDs.Length, Allocator.TempJob);
GPUDrivenProcessor.RegisterMeshes(m_BRG, newMeshIDs, batchMeshIDs);
int totalMeshesNum = m_MeshMap.Count() + newMeshIDs.Length;
m_MeshMap.Capacity = Math.Max(m_MeshMap.Capacity, Mathf.CeilToInt(totalMeshesNum / 1023.0f) * 1024);
m_TempBatchMeshIDs = batchMeshIDs;
GPUDrivenProcessor.FetchMeshDatas(newMeshIDs, OnFetchMeshesDataForRegistration);
m_TempBatchMeshIDs = default;
newMeshIDs.Dispose();
batchMeshIDs.Dispose();
}
jobRanges.Dispose();
newMeshSet.Dispose();
}
private void RegisterMaterials(JaggedSpan<EntityId> materials)
{
using var _ = k_RegisterMaterials.Auto();
var jobRanges = JaggedJobRange.FromSpanWithMaxBatchSize(materials, FindNonRegisteredInstanceIDsJob<GPUDrivenMaterial>.MaxBatchSize, Allocator.TempJob);
var newMaterialIDSet = new NativeParallelHashSet<EntityId>(materials.totalLength, Allocator.TempJob);
new FindNonRegisteredInstanceIDsJob<GPUDrivenMaterial>
{
jobRanges = jobRanges.AsArray(),
jaggedInstanceIDs = materials,
hashMap = m_MaterialMap,
outInstanceIDWriter = newMaterialIDSet.AsParallelWriter()
}
.RunParallel(jobRanges);
if (!newMaterialIDSet.IsEmpty)
{
NativeArray<EntityId> newMaterialIDs = newMaterialIDSet.ToNativeArray(Allocator.TempJob);
var newMaterials = new NativeArray<GPUDrivenMaterial>(newMaterialIDs.Length, Allocator.TempJob);
GPUDrivenProcessor.RegisterMaterials(m_BRG, newMaterialIDs, newMaterials);
int totalMaterialsNum = m_MaterialMap.Count() + newMaterialIDs.Length;
m_MaterialMap.Capacity = Math.Max(m_MaterialMap.Capacity, Mathf.CeilToInt(totalMaterialsNum / 1023.0f) * 1024);
new RegisterNewMaterialsJob
{
instanceIDs = newMaterialIDs,
materials = newMaterials,
materialMap = m_MaterialMap.AsParallelWriter()
}
.RunParallel(newMaterialIDs.Length, 128);
newMaterialIDs.Dispose();
newMaterials.Dispose();
}
jobRanges.Dispose();
newMaterialIDSet.Dispose();
}
private void OnFetchMeshesDataForUpdate(NativeArray<EntityId> meshIDs,
NativeArray<GPUDrivenMeshData> meshDatas,
NativeArray<int> subMeshOffsets,
NativeArray<GPUDrivenSubMesh> subMeshBuffer)
{
Assert.IsTrue(meshIDs.Length == meshDatas.Length);
Assert.IsTrue(m_TempChangedMeshIDs.IsCreated);
InstanceCullingBatcherBurst.UpdateMeshData(meshIDs, meshDatas, subMeshOffsets, subMeshBuffer, ref m_MeshMap, ref m_TempChangedMeshIDs);
}
public NativeHashSet<EntityId> UpdateMeshData(NativeArray<EntityId> meshIDs, Allocator allocator)
{
NativeHashSet<EntityId> changeMeshIDs = new NativeHashSet<EntityId>(meshIDs.Length, allocator);
m_TempChangedMeshIDs = changeMeshIDs;
GPUDrivenProcessor.FetchMeshDatas(meshIDs, OnFetchMeshesDataForUpdate);
m_TempChangedMeshIDs = default;
return changeMeshIDs;
}
public NativeHashSet<EntityId> UpdateMaterialData(NativeArray<EntityId> materials, NativeArray<GPUDrivenMaterialData> materialDatas, Allocator allocator)
{
NativeHashSet<EntityId> changeMaterialIDs = new NativeHashSet<EntityId>(materials.Length, allocator);
InstanceCullingBatcherBurst.UpdateMaterialData(materials, materialDatas, ref m_MaterialMap, ref changeMaterialIDs);
return changeMaterialIDs;
}
public CPUDrawInstanceData GetDrawInstanceData()
{
return m_DrawInstanceData;
}
public unsafe JobHandle OnPerformCulling(BatchRendererGroup rendererGroup, BatchCullingContext context, BatchCullingOutput cullingOutput, IntPtr userContext)
{
foreach (var batchID in m_BatchIDs)
{
if (batchID.Value == BatchID.Null)
return new JobHandle();
}
m_DrawInstanceData.RebuildDrawListsIfNeeded();
if (m_DrawInstanceData.drawRanges.Length == 0)
return default;
if (m_DrawInstanceData.drawBatches.Length == 0)
return default;
IncludeExcludeListFilter includeExcludeListFilter = default;
#if UNITY_EDITOR
includeExcludeListFilter = IncludeExcludeListFilter.GetFilterForCurrentCullingCallback(context, Allocator.TempJob);
// If inclusive filtering is enabled and we know there are no included entities,
// we can skip all the work because we know that the result will be nothing.
if (includeExcludeListFilter.IsIncludeEnabled && includeExcludeListFilter.IsIncludeEmpty)
{
includeExcludeListFilter.Dispose();
return default;
}
#else
includeExcludeListFilter = IncludeExcludeListFilter.GetEmptyFilter(Allocator.TempJob);
#endif
bool allowOcclusionCulling = m_InstanceDataSystem.hasBoundingSpheres;
JobHandle jobHandle;
using (k_CreateCullJobTree.Auto())
{
jobHandle = m_GRDContext.culler.CreateCullJobTree(
context,
cullingOutput,
m_InstanceDataSystem.renderWorld,
m_GRDContext.batcher.meshMap,
m_InstanceDataSystem.gpuBuffer.AsReadOnly(),
m_LODGroupDataSystem.lodGroupCullingData,
m_DrawInstanceData,
m_BatchIDs,
m_GRDContext.smallMeshScreenPercentage,
m_GRDContext.shadowSmallMeshScreenPercentages,
allowOcclusionCulling ? m_GRDContext.occlusionCullingCommon : null,
includeExcludeListFilter);
}
if (m_OnCompleteCallback != null)
m_OnCompleteCallback(jobHandle, context, cullingOutput);
return includeExcludeListFilter.Dispose(jobHandle);
}
public void DestroyDrawInstances(NativeArray<InstanceHandle> instances)
{
m_DrawInstanceData.DestroyDrawInstances(instances);
}
public void DestroyMaterials(NativeArray<EntityId> destroyedInstanceIDs)
{
if (destroyedInstanceIDs.Length == 0)
return;
using var _ = k_DestroyMaterials.Auto();
var destroyedBatchMaterials = new NativeList<uint>(destroyedInstanceIDs.Length, Allocator.TempJob);
foreach (EntityId instanceID in destroyedInstanceIDs)
{
if (m_MaterialMap.TryGetValue(instanceID, out GPUDrivenMaterial materialData))
{
BatchMaterialID batchMaterialID = materialData.materialID;
destroyedBatchMaterials.Add(batchMaterialID.value);
m_MaterialMap.Remove(instanceID);
m_BRG.UnregisterMaterial(batchMaterialID);
}
}
m_DrawInstanceData.DestroyMaterialDrawInstances(destroyedBatchMaterials.AsArray());
destroyedBatchMaterials.Dispose();
}
public void DestroyMeshes(NativeArray<EntityId> destroyedInstanceIDs)
{
if (destroyedInstanceIDs.Length == 0)
return;
using var _ = k_DestroyMeshes.Auto();
foreach (EntityId instanceID in destroyedInstanceIDs)
{
if (m_MeshMap.TryGetValue(instanceID, out var meshData))
{
meshData.subMeshes.Dispose();
m_MeshMap.Remove(instanceID);
m_BRG.UnregisterMesh(meshData.meshID);
}
}
}
public void BuildBatches(NativeArray<InstanceHandle> instances)
{
using var _ = k_BuildBatches.Auto();
DestroyDrawInstances(instances);
var rangeHash = m_DrawInstanceData.rangeHash;
var drawRanges = m_DrawInstanceData.drawRanges;
var batchHash = m_DrawInstanceData.batchHash;
var drawBatches = m_DrawInstanceData.drawBatches;
var drawInstances = m_DrawInstanceData.drawInstances;
InstanceCullingBatcherBurst.CreateDrawBatches(instances,
ref m_InstanceDataSystem.renderWorld,
m_MeshMap,
m_MaterialMap,
ref rangeHash,
ref drawRanges,
ref batchHash,
ref drawBatches,
ref drawInstances);
m_DrawInstanceData.NeedsRebuild();
}
public void RegisterAndBuildBatches(NativeArray<InstanceHandle> instances, in MeshRendererUpdateBatch updateBatch)
{
using var _ = k_RegisterAndBuildBatches.Auto();
// Wrap only the register portion so the recorder doesn't double-count BuildBatches.
using (k_RegisterMaterialsAndMeshes.Auto())
{
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.Material))
RegisterMaterials(updateBatch.materialIDs);
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.Mesh))
RegisterMeshes(updateBatch.meshIDs);
}
BuildBatches(instances);
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: bc861765f685b66449a8c8966e008804
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,270 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using Unity.Collections;
using Unity.Burst;
using UnityEngine.Assertions;
using Unity.Mathematics;
namespace UnityEngine.Rendering
{
[BurstCompile]
internal static class InstanceCullingBatcherBurst
{
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
public static void UpdateMaterialData(in NativeArray<EntityId> materialIDs,
in NativeArray<GPUDrivenMaterialData> materialDatas,
ref NativeParallelHashMap<EntityId, GPUDrivenMaterial> materialMap,
ref NativeHashSet<EntityId> changedMaterialIDs)
{
for (int index = 0; index < materialIDs.Length; index++)
{
EntityId materialID = materialIDs[index];
GPUDrivenMaterialData newMaterialData = materialDatas[index];
if (!materialMap.TryGetValue(materialID, out var material) || material.data.Equals(newMaterialData))
continue;
// Update the material data
material.data = newMaterialData;
materialMap[materialID] = material;
changedMaterialIDs.Add(materialID);
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
public static void UpdateMeshData(in NativeArray<EntityId> meshIDs,
in NativeArray<GPUDrivenMeshData> meshDatas,
in NativeArray<int> subMeshOffsets,
in NativeArray<GPUDrivenSubMesh> subMeshBuffer,
ref NativeParallelHashMap<EntityId, MeshInfo> meshMap,
ref NativeHashSet<EntityId> changedMeshIDs)
{
for (int index = 0; index < meshIDs.Length; index++)
{
EntityId meshID = meshIDs[index];
GPUDrivenMeshData newMeshData = meshDatas[index];
int subMeshOffset = subMeshOffsets[index];
int totalSubMeshCount = newMeshData.subMeshCount * math.max(newMeshData.meshLodCount, 1);
NativeArray<GPUDrivenSubMesh> newSubMeshes = subMeshBuffer.GetSubArray(subMeshOffset, totalSubMeshCount);
if (!meshMap.TryGetValue(meshID, out var meshInfo) || meshInfo.EqualsSourceData(newMeshData, newSubMeshes))
continue;
MeshInfo newMeshInfo = meshInfo;
newMeshInfo.meshLodCount = newMeshData.meshLodCount;
newMeshInfo.meshLodSelectionCurve = newMeshData.meshLodSelectionCurve;
newMeshInfo.subMeshes = new EmbeddedArray64<GPUDrivenSubMesh>(newSubMeshes, Allocator.Persistent);
// Update the mesh data
meshMap[meshID] = newMeshInfo;
changedMeshIDs.Add(meshID);
meshInfo.subMeshes.Dispose();
}
}
private static ref DrawRange EditDrawRange(in RangeKey key, ref NativeParallelHashMap<RangeKey, int> rangeHash, ref NativeList<DrawRange> drawRanges)
{
int drawRangeIndex;
if (!rangeHash.TryGetValue(key, out drawRangeIndex))
{
var drawRange = new DrawRange { key = key, drawCount = 0, drawOffset = 0 };
drawRangeIndex = drawRanges.Length;
rangeHash.Add(key, drawRangeIndex);
drawRanges.Add(drawRange);
}
ref DrawRange data = ref drawRanges.ElementAt(drawRangeIndex);
Assert.IsTrue(data.key.Equals(key));
return ref data;
}
private static ref DrawBatch EditDrawBatch(in DrawKey key,
in GPUDrivenSubMesh subMesh,
ref NativeParallelHashMap<DrawKey, int> batchHash,
ref NativeList<DrawBatch> drawBatches)
{
int drawBatchIndex;
if (!batchHash.TryGetValue(key, out drawBatchIndex))
{
var drawBatch = new DrawBatch
{
key = key,
instanceCount = 0,
instanceOffset = 0,
baseVertex = subMesh.baseVertex,
firstIndex = subMesh.indexStart,
indexCount = subMesh.indexCount,
topology = subMesh.topology,
};
drawBatchIndex = drawBatches.Length;
batchHash.Add(key, drawBatchIndex);
drawBatches.Add(drawBatch);
}
ref DrawBatch data = ref drawBatches.ElementAt(drawBatchIndex);
Assert.IsTrue(data.key.Equals(key));
return ref data;
}
private static void ProcessRenderer(InstanceHandle instance,
ref RenderWorld renderWorld,
in NativeParallelHashMap<EntityId, MeshInfo> meshMap,
in NativeParallelHashMap<EntityId, GPUDrivenMaterial> materialMap,
ref NativeParallelHashMap<RangeKey, int> rangeHash,
ref NativeList<DrawRange> drawRanges,
ref NativeParallelHashMap<DrawKey, int> batchHash,
ref NativeList<DrawBatch> drawBatches,
ref NativeList<DrawInstance> drawInstances)
{
Assert.IsTrue(instance.isValid, "Invalid Instance");
if (!instance.isValid)
return;
int instanceIndex = renderWorld.HandleToIndex(instance);
GPUArchetypeHandle archetype = renderWorld.gpuHandles[instanceIndex].archetype;
EntityId meshID = renderWorld.meshIDs[instanceIndex];
EntityId rendererID = renderWorld.instanceIDs[instanceIndex];
short lightmapIndex = renderWorld.lightmapIndices[instanceIndex];
InternalMeshRendererSettings rendererSettings = renderWorld.rendererSettings[instanceIndex];
int rendererPriority = renderWorld.rendererPriorities[instanceIndex];
ushort subMeshStartIndex = renderWorld.subMeshStartIndices[instanceIndex];
ushort staticBatchSubMeshCount = renderWorld.staticBatchSubMeshCounts[instanceIndex];
EmbeddedArray32<EntityId> subMaterialIDs = renderWorld.materialIDArrays[instanceIndex];
if (!meshMap.TryGetValue(meshID, out MeshInfo mesh))
return;
int lodLoopCount = math.max(mesh.meshLodCount, 1);
int availableSubMeshCount = mesh.subMeshes.Length / lodLoopCount - subMeshStartIndex;
int subMeshCount = rendererSettings.IsPartOfStaticBatch
? math.min(staticBatchSubMeshCount, availableSubMeshCount)
: availableSubMeshCount;
if (subMeshCount <= 0)
return;
int GetSubMeshIndexForMaterial(int materialIndex) => subMeshStartIndex + math.min(materialIndex, subMeshCount - 1);
// Scan all materials once to retrieve whether this renderer is indirect-compatible or not (and store it in the RangeKey).
// Also cache hash map lookups since we need them right after.
bool supportsIndirect = true;
bool isMetal = SystemInfo.graphicsDeviceType == GraphicsDeviceType.Metal;
var subMaterials = new NativeArray<GPUDrivenMaterial>(subMaterialIDs.Length, Allocator.Temp);
for (int i = 0; i < subMaterialIDs.Length; i++)
{
EntityId subMaterialID = subMaterialIDs[i];
if (!materialMap.TryGetValue(subMaterialID, out GPUDrivenMaterial subMaterial))
continue;
subMaterials[i] = subMaterial;
int subMeshIndex = GetSubMeshIndexForMaterial(i);
var subMesh = mesh.subMeshes[subMeshIndex * lodLoopCount];
// The indirect path does not support topology adjustment; use the direct path when this is required.
// Concretely, for quads, only use the indirect path if we allow quads natively (e.g. tessellation shaders).
supportsIndirect &= subMesh.topology != MeshTopology.Quads || subMaterial.hasTessellation;
supportsIndirect &= !isMetal || !subMaterial.hasTessellation;
}
var rangeKey = new RangeKey
{
layer = rendererSettings.ObjectLayer,
renderingLayerMask = rendererSettings.RenderingLayerMask,
motionMode = rendererSettings.MotionVectorGenerationMode,
shadowCastingMode = rendererSettings.ShadowCastingMode,
staticShadowCaster = rendererSettings.StaticShadowCaster,
rendererPriority = rendererPriority,
supportsIndirect = supportsIndirect
};
ref DrawRange drawRange = ref EditDrawRange(rangeKey, ref rangeHash, ref drawRanges);
for (int i = 0; i < subMaterials.Length; i++)
{
GPUDrivenMaterial subMaterial = subMaterials[i];
if (subMaterial.materialID == BatchMaterialID.Null)
continue;
// We always provide crossfade value packed in instance index. We don't use None even if there is no LOD to not split the batch.
var flags = BatchDrawCommandFlags.LODCrossFadeValuePacked;
if (LightmapUtils.UsesLightmaps(lightmapIndex))
flags |= BatchDrawCommandFlags.UseLegacyLightmapsKeyword;
// assume that a custom motion vectors pass contains deformation motion, so should always output motion vectors
// (otherwise this flag is set dynamically during culling only when the transform is changing)
if (subMaterial.isMotionVectorsPassEnabled)
flags |= BatchDrawCommandFlags.HasMotion;
if (subMaterial.isTransparent)
flags |= BatchDrawCommandFlags.HasSortingPosition;
if (subMaterial.supportsCrossFade)
flags |= BatchDrawCommandFlags.LODCrossFadeKeyword;
// Static batching uses per MeshRenderer sub-mesh offset
int subMeshIndex = GetSubMeshIndexForMaterial(i);
for (int lodLoopIndex = 0; lodLoopIndex < lodLoopCount; lodLoopIndex++)
{
GPUDrivenSubMesh subMesh = mesh.subMeshes[subMeshIndex * lodLoopCount + lodLoopIndex];
var drawKey = new DrawKey
{
materialID = subMaterial.materialID,
meshID = mesh.meshID,
submeshIndex = subMeshIndex,
activeMeshLod = mesh.isLodSelectionActive ? lodLoopIndex : -1,
flags = flags,
transparentInstanceID = subMaterial.isTransparent ? rendererID : EntityId.None,
range = rangeKey,
archetype = archetype,
// When we've opted out of lightmap texture arrays, we
// need to pass in a valid lightmap index. The engine
// uses this index for sorting and for breaking the
// batch when lightmaps change across draw calls, and
// for binding the correct light map.
lightmapIndex = lightmapIndex
};
ref DrawBatch drawBatch = ref EditDrawBatch(drawKey, subMesh, ref batchHash, ref drawBatches);
if (drawBatch.instanceCount == 0)
drawRange.drawCount += 1;
drawBatch.instanceCount += 1;
drawInstances.Add(new DrawInstance
{
key = drawKey,
instanceIndex = instance.index
});
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
public static void CreateDrawBatches(in NativeArray<InstanceHandle> instances,
ref RenderWorld renderWorld,
in NativeParallelHashMap<EntityId, MeshInfo> meshMap,
in NativeParallelHashMap<EntityId, GPUDrivenMaterial> materialMap,
ref NativeParallelHashMap<RangeKey, int> rangeHash,
ref NativeList<DrawRange> drawRanges,
ref NativeParallelHashMap<DrawKey, int> batchHash,
ref NativeList<DrawBatch> drawBatches,
ref NativeList<DrawInstance> drawInstances)
{
for (int i = 0; i < instances.Length; i++)
ProcessRenderer(instances[i], ref renderWorld, meshMap, materialMap, ref rangeHash, ref drawRanges, ref batchHash, ref drawBatches, ref drawInstances);
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a27d8a9d1dff4734cb0e88406d333941
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: efa82a5fd775b99479c361771fb9e6d1
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,72 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using UnityEngine.Serialization;
namespace UnityEngine.Rendering
{
[ExecuteInEditMode]
internal class DisallowGPUDrivenRendering : MonoBehaviour
{
private bool m_AppliedRecursively;
[FormerlySerializedAs("applyToChildrenRecursively")]
public bool m_applyToChildrenRecursively;
public bool applyToChildrenRecursively
{
get => m_applyToChildrenRecursively;
set
{
m_applyToChildrenRecursively = value;
OnDisable();
OnEnable();
}
}
private void OnEnable()
{
m_AppliedRecursively = applyToChildrenRecursively;
if (applyToChildrenRecursively)
AllowGPUDrivenRenderingRecursively(transform, false);
else
AllowGPUDrivenRendering(transform, false);
}
private void OnDisable()
{
if (m_AppliedRecursively)
AllowGPUDrivenRenderingRecursively(transform, true);
else
AllowGPUDrivenRendering(transform, true);
}
private static void AllowGPUDrivenRendering(Transform transform, bool allow)
{
var renderer = transform.GetComponent<MeshRenderer>();
if (renderer)
renderer.allowGPUDrivenRendering = allow;
}
private static void AllowGPUDrivenRenderingRecursively(Transform transform, bool allow)
{
AllowGPUDrivenRendering(transform, allow);
foreach (Transform child in transform)
{
if (!child.GetComponent<DisallowGPUDrivenRendering>())
AllowGPUDrivenRenderingRecursively(child, allow);
}
}
private void OnValidate()
{
OnDisable();
if (enabled)
OnEnable();
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 644debc0b7d33d043af3caab53baa000
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,68 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
namespace UnityEngine.Rendering
{
[ExecuteInEditMode]
internal class DisallowSmallMeshCulling : MonoBehaviour
{
private bool m_AppliedRecursively;
public bool m_applyToChildrenRecursively;
public bool applyToChildrenRecursively
{
get => m_applyToChildrenRecursively;
set
{
m_applyToChildrenRecursively = value;
OnDisable();
OnEnable();
}
}
private void OnEnable()
{
m_AppliedRecursively = applyToChildrenRecursively;
if (applyToChildrenRecursively)
AllowSmallMeshCullingRecursively(transform, false);
else
AllowSmallMeshCulling(transform, false);
}
private void OnDisable()
{
if (m_AppliedRecursively)
AllowSmallMeshCullingRecursively(transform, true);
else
AllowSmallMeshCulling(transform, true);
}
private static void AllowSmallMeshCulling(Transform transform, bool allow)
{
var renderer = transform.GetComponent<MeshRenderer>();
if (renderer)
renderer.smallMeshCulling = allow;
}
private static void AllowSmallMeshCullingRecursively(Transform transform, bool allow)
{
AllowSmallMeshCulling(transform, allow);
foreach (Transform child in transform)
{
if (!child.GetComponent<DisallowGPUDrivenRendering>())
AllowSmallMeshCullingRecursively(child, allow);
}
}
private void OnValidate()
{
OnDisable();
OnEnable();
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a55bb9f7efce64f3ab3a138447cb46c0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 88615a6f33ae421468a6a44c5ec2a601
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,118 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using Unity.Collections;
namespace UnityEngine.Rendering
{
// Move all propertyID static fields to a separate struct.
// Burst does not support external calls like PropertyToID from static constructors.
static internal class DefaultShaderPropertyID
{
public static readonly int unity_SHCoefficients = Shader.PropertyToID("unity_SHCoefficients");
public static readonly int unity_LightmapST = Shader.PropertyToID("unity_LightmapST");
public static readonly int unity_ObjectToWorld = Shader.PropertyToID("unity_ObjectToWorld");
public static readonly int unity_WorldToObject = Shader.PropertyToID("unity_WorldToObject");
public static readonly int unity_MatrixPreviousM = Shader.PropertyToID("unity_MatrixPreviousM");
public static readonly int unity_MatrixPreviousMI = Shader.PropertyToID("unity_MatrixPreviousMI");
public static readonly int unity_WorldBoundingSphere = Shader.PropertyToID("unity_WorldBoundingSphere");
public static readonly int unity_RendererUserValuesPropertyEntry = Shader.PropertyToID("unity_RendererUserValuesPropertyEntry");
public static readonly int[] DOTS_ST_WindParams = new int[InstanceDataSystem.k_STMaxWindParamsCount];
public static readonly int[] DOTS_ST_WindHistoryParams = new int[InstanceDataSystem.k_STMaxWindParamsCount];
static DefaultShaderPropertyID()
{
for (int i = 0; i < InstanceDataSystem.k_STMaxWindParamsCount; ++i)
{
DOTS_ST_WindParams[i] = Shader.PropertyToID($"DOTS_ST_WindParam{i}");
DOTS_ST_WindHistoryParams[i] = Shader.PropertyToID($"DOTS_ST_WindHistoryParam{i}");
}
}
}
internal struct DefaultGPUComponents
{
public readonly GPUComponentHandle shCoefficients;
public readonly GPUComponentHandle lightmapScaleOffset;
public readonly GPUComponentHandle objectToWorld;
public readonly GPUComponentHandle worldToObject;
public readonly GPUComponentHandle matrixPreviousM;
public readonly GPUComponentHandle matrixPreviousMI;
public readonly GPUComponentHandle rendererUserValues;
public readonly GPUComponentHandle boundingSphere;
public readonly NativeArray<GPUComponentHandle> speedTreeWind;
public readonly NativeArray<GPUComponentHandle> speedTreeWindHistory;
public readonly GPUComponentSet requiredComponentSet;
public readonly GPUComponentSet lightProbesComponentSet;
public readonly GPUComponentSet speedTreeComponentSet;
public readonly GPUComponentSet defaultGOComponentSet;
public readonly GPUComponentSet defaultSpeedTreeComponentSet;
public readonly GPUArchetypeHandle defaultGOArchetype;
public DefaultGPUComponents(ref GPUArchetypeManager archetypeManager, bool enableBoundingSpheresInstanceData)
{
shCoefficients = archetypeManager.CreateComponent<SHCoefficients>(DefaultShaderPropertyID.unity_SHCoefficients, true);
lightmapScaleOffset = archetypeManager.CreateComponent<Vector4>(DefaultShaderPropertyID.unity_LightmapST, true);
objectToWorld = archetypeManager.CreateComponent<PackedMatrix>(DefaultShaderPropertyID.unity_ObjectToWorld, true);
worldToObject = archetypeManager.CreateComponent<PackedMatrix>(DefaultShaderPropertyID.unity_WorldToObject, true);
matrixPreviousM = archetypeManager.CreateComponent<PackedMatrix>(DefaultShaderPropertyID.unity_MatrixPreviousM, true);
matrixPreviousMI = archetypeManager.CreateComponent<PackedMatrix>(DefaultShaderPropertyID.unity_MatrixPreviousMI, true);
rendererUserValues = archetypeManager.CreateComponent<uint>(DefaultShaderPropertyID.unity_RendererUserValuesPropertyEntry, true);
boundingSphere = enableBoundingSpheresInstanceData
? archetypeManager.CreateComponent<Vector4>(DefaultShaderPropertyID.unity_WorldBoundingSphere, true)
: default;
speedTreeWind = new NativeArray<GPUComponentHandle>(InstanceDataSystem.k_STMaxWindParamsCount, Allocator.Persistent);
speedTreeWindHistory = new NativeArray<GPUComponentHandle>(InstanceDataSystem.k_STMaxWindParamsCount, Allocator.Persistent);
for (int i = 0; i < InstanceDataSystem.k_STMaxWindParamsCount; ++i)
speedTreeWind[i] = archetypeManager.CreateComponent<Vector4>(DefaultShaderPropertyID.DOTS_ST_WindParams[i], true);
for (int i = 0; i < InstanceDataSystem.k_STMaxWindParamsCount; ++i)
speedTreeWindHistory[i] = archetypeManager.CreateComponent<Vector4>(DefaultShaderPropertyID.DOTS_ST_WindHistoryParams[i], true);
//@ Investigate how to avoid uploading the previous matrices for everything.
// It should only be needed when using object motion vectors.
requiredComponentSet = new GPUComponentSet()
{
objectToWorld,
worldToObject,
matrixPreviousM,
matrixPreviousMI,
rendererUserValues,
};
if (enableBoundingSpheresInstanceData)
requiredComponentSet.Add(boundingSphere);
lightProbesComponentSet = new GPUComponentSet()
{
shCoefficients,
};
speedTreeComponentSet = new GPUComponentSet();
for (int i = 0; i < speedTreeWind.Length; ++i)
speedTreeComponentSet.Add(speedTreeWind[i]);
for (int i = 0; i < speedTreeWindHistory.Length; ++i)
speedTreeComponentSet.Add(speedTreeWindHistory[i]);
defaultGOComponentSet = requiredComponentSet;
defaultSpeedTreeComponentSet = defaultGOComponentSet;
defaultSpeedTreeComponentSet.Add(lightmapScaleOffset);
defaultSpeedTreeComponentSet.AddSet(speedTreeComponentSet);
defaultGOArchetype = archetypeManager.GetOrCreateArchetype(defaultGOComponentSet);
}
public void Dispose()
{
speedTreeWind.Dispose();
speedTreeWindHistory.Dispose();
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 22f804ff14ea3354fb0ae80ecfba8616
@@ -0,0 +1,303 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
internal struct GPUArchetypeManager : IDisposable
{
// We can make this larger if needed. If we need 128 the we just need to have 2 ulong componentMask in GPUComponentSet.
public const int kMaxComponentsCount = 64;
public const int kGPUArchetypeBits = 6;
public const int kMaxGPUArchetypesCount = 1 << kGPUArchetypeBits;
public const int kGPUArchetypeBitsMask = kMaxGPUArchetypesCount - 1;
private NativeHandleAllocator m_ComponentHandleAllocator;
private NativeHandleAllocator m_ArchetypeHandleAllocator;
private NativeList<GPUComponentDesc> m_Components;
private NativeList<GPUArchetypeDesc> m_Archetypes;
private NativeParallelHashMap<int, GPUComponentHandle> m_ComponentHash;
private NativeParallelHashMap<GPUComponentSet, GPUArchetypeHandle> m_ArchetypeHash;
private NativeParallelHashMap<GPUArchetypeHandle, GPUComponentSet> m_ComponentSetHash;
private GraphicsDeviceType m_GraphicsDeviceType;
public void Initialize()
{
m_ComponentHandleAllocator = new NativeHandleAllocator();
m_ComponentHandleAllocator.Initialize();
m_ArchetypeHandleAllocator = new NativeHandleAllocator();
m_ArchetypeHandleAllocator.Initialize();
m_Components = new NativeList<GPUComponentDesc>(Allocator.Persistent);
m_Archetypes = new NativeList<GPUArchetypeDesc>(Allocator.Persistent);
m_ComponentHash = new NativeParallelHashMap<int, GPUComponentHandle>(16, Allocator.Persistent);
m_ArchetypeHash = new NativeParallelHashMap<GPUComponentSet, GPUArchetypeHandle>(16, Allocator.Persistent);
m_ComponentSetHash = new NativeParallelHashMap<GPUArchetypeHandle, GPUComponentSet>(16, Allocator.Persistent);
m_GraphicsDeviceType = SystemInfo.graphicsDeviceType;
}
public void Dispose()
{
m_ComponentHandleAllocator.Dispose();
m_ArchetypeHandleAllocator.Dispose();
foreach (var component in m_Components)
component.archetypes.Dispose();
foreach (var archetype in m_Archetypes)
archetype.components.Dispose();
m_Components.Dispose();
m_Archetypes.Dispose();
m_ComponentHash.Dispose();
m_ArchetypeHash.Dispose();
m_ComponentSetHash.Dispose();
}
public GPUComponentHandle FindComponent(int propertyID)
{
if (m_ComponentHash.TryGetValue(propertyID, out var componentHandle))
return componentHandle;
return GPUComponentHandle.Invalid;
}
public GPUArchetypeHandle FindArchetype(GPUComponentSet componentSet)
{
if (m_ArchetypeHash.TryGetValue(componentSet, out var archetype))
return archetype;
return GPUArchetypeHandle.Invalid;
}
public GPUComponentSet FindComponentSet(GPUArchetypeHandle archetype)
{
Assert.IsTrue(archetype.valid);
Assert.IsTrue(m_ComponentSetHash.ContainsKey(archetype));
return m_ComponentSetHash[archetype];
}
public ref readonly GPUComponentDesc GetComponentDesc(GPUComponentHandle componentHandle)
{
Assert.IsTrue(componentHandle.valid);
return ref m_Components.ElementAt(componentHandle.index);
}
public ref readonly GPUArchetypeDesc GetArchetypeDesc(GPUArchetypeHandle archetypeHandle)
{
Assert.IsTrue(archetypeHandle.valid);
return ref m_Archetypes.ElementAt(archetypeHandle.index);
}
public int GetComponentsCount() => m_Components.Length;
public int GetArchetypesCount() => m_Archetypes.Length;
public GPUComponentHandle CreateComponent(int propertyID, int byteSize, bool isPerInstance)
{
//@ Should we extend this assert to all devices to address slowdowns caused by unaligned access on GPU?
if (m_GraphicsDeviceType == GraphicsDeviceType.OpenGLES3)
Assert.IsTrue(byteSize % UnsafeUtility.SizeOf<Vector4>() == 0, "On OpenGLES3 component size must be aligned by float4.");
Assert.IsTrue(m_Components.Length < kMaxComponentsCount, "Maximum GPU components count reached.");
Assert.IsTrue(byteSize > 0, "Component size is zero.");
Assert.IsTrue(!m_ComponentHash.ContainsKey(propertyID), $"Component with propertyID {propertyID} already exists.");
var componentDesc = new GPUComponentDesc
{
propertyID = propertyID,
byteSize = byteSize,
isPerInstance = isPerInstance,
archetypes = new UnsafeList<GPUArchetypeHandle>(4, Allocator.Persistent)
};
var componentHandle = GPUComponentHandle.Create((short)m_ComponentHandleAllocator.Allocate());
if (m_Components.Length <= componentHandle.index)
m_Components.Resize(componentHandle.index + 1, NativeArrayOptions.ClearMemory);
m_Components[componentHandle.index] = componentDesc;
m_ComponentHash.Add(propertyID, componentHandle);
return componentHandle;
}
public GPUComponentHandle CreateComponent<T>(int propertyID, bool isPerInstance) where T : unmanaged
{
return CreateComponent(propertyID, UnsafeUtility.SizeOf<T>(), isPerInstance);
}
public unsafe GPUArchetypeHandle CreateArchetype(GPUComponentSet componentSet)
{
Assert.IsTrue(m_Archetypes.Length < kMaxGPUArchetypesCount, "Maximum GPU archetypes count reached.");
Assert.IsFalse(m_ArchetypeHash.ContainsKey(componentSet), "Archetype with the same component set already exists.");
var archetypeHandle = GPUArchetypeHandle.Create((short)m_ArchetypeHandleAllocator.Allocate());
var components = componentSet.GetComponents(Allocator.Persistent);
var archetypeDesc = new GPUArchetypeDesc { components = components };
for (int i = 0; i < components.Length; ++i)
{
Assert.IsTrue(components[i].valid);
ref GPUComponentDesc componentDesc = ref m_Components.ElementAt(components[i].index);
Assert.IsFalse(componentDesc.archetypes.Contains(archetypeHandle), "Archetype already contains component.");
componentDesc.archetypes.Add(archetypeHandle);
}
if (m_Archetypes.Length <= archetypeHandle.index)
m_Archetypes.Resize(archetypeHandle.index + 1, NativeArrayOptions.ClearMemory);
m_Archetypes[archetypeHandle.index] = archetypeDesc;
m_ArchetypeHash.Add(componentSet, archetypeHandle);
m_ComponentSetHash.Add(archetypeHandle, componentSet);
return archetypeHandle;
}
public GPUArchetypeHandle GetOrCreateArchetype(GPUComponentSet componentSet)
{
if (m_ArchetypeHash.TryGetValue(componentSet, out var archetype))
return archetype;
return CreateArchetype(componentSet);
}
public GPUComponentHandle GetOrCreateComponent(int propertyID, int byteSize, bool perInstance)
{
var componentHandle = FindComponent(propertyID);
if (!componentHandle.Equals(GPUComponentHandle.Invalid))
return componentHandle;
return CreateComponent(propertyID, byteSize, perInstance);
}
}
internal struct GPUComponentDesc
{
public int propertyID;
public int byteSize;
public bool isPerInstance;
public UnsafeList<GPUArchetypeHandle> archetypes;
}
internal struct GPUArchetypeDesc
{
public NativeList<GPUComponentHandle> components;
}
internal struct GPUComponentHandle : IEquatable<GPUComponentHandle>, IComparable<GPUComponentHandle>
{
public short index { get; private set; }
public bool valid => index >= 0;
public static GPUComponentHandle Create(short index) { return new GPUComponentHandle { index = index }; }
public static readonly GPUComponentHandle Invalid = new GPUComponentHandle { index = -1 };
public bool Equals(GPUComponentHandle other) => index == other.index;
public int CompareTo(GPUComponentHandle other) { return index.CompareTo(other.index); }
public override int GetHashCode() { return index; }
}
internal struct GPUArchetypeHandle : IEquatable<GPUArchetypeHandle>, IComparable<GPUArchetypeHandle>
{
public short index { get; private set; }
public bool valid => index >= 0;
public static GPUArchetypeHandle Create(short index) { return new GPUArchetypeHandle { index = index }; }
public static readonly GPUArchetypeHandle Invalid = new GPUArchetypeHandle { index = -1 };
public bool Equals(GPUArchetypeHandle other) => index == other.index;
public int CompareTo(GPUArchetypeHandle other) { return index.CompareTo(other.index); }
public override int GetHashCode() { return index; }
}
//@ We could separate shader parameters from GPUComponents and alias different shader parameters to the same GPUComponent if they have the same size.
//@ Basically that would allow to have multiple GPUComponentSets ([default + float4 ParamName1], [default + float4 ParamName2], etc...) with the same component sizes but different propertyIDs but mapped to the same archetype.
//@ This will not be very hard to do but it will require some additional bookkeeping. But in the end it will decrease the number of archetypes that we have to handle on GPU.
internal struct GPUComponentSet : IEquatable<GPUComponentSet>, IComparable<GPUComponentSet>, IEnumerable
{
public ulong componentsMask { get; private set; }
public bool isEmpty => componentsMask == 0;
public bool Equals(GPUComponentSet other) => componentsMask == other.componentsMask;
public int CompareTo(GPUComponentSet other) { return componentsMask.CompareTo(other.componentsMask); }
public override int GetHashCode() { return componentsMask.GetHashCode(); }
static GPUComponentSet()
{
Assert.AreEqual(GPUArchetypeManager.kMaxComponentsCount, UnsafeUtility.SizeOf<ulong>() * 8, "Adjust componentsMask type to correspond to kMaxComponentsCount.");
}
public GPUComponentSet(NativeArray<GPUComponentHandle> components)
{
componentsMask = 0;
AddRange(components);
}
public void Add(GPUComponentHandle componentHandle)
{
Assert.IsTrue(componentHandle.valid);
componentsMask |= 1ul << componentHandle.index;
}
public void AddSet(GPUComponentSet componentSet)
{
componentsMask |= componentSet.componentsMask;
}
public void AddRange(NativeArray<GPUComponentHandle> components)
{
for (int i = 0; i < components.Length; ++i)
Add(components[i]);
}
public int GetComponentsCount()
{
return math.countbits(componentsMask);
}
public IEnumerator GetEnumerator()
{
int count = GetComponentsCount();
for (int i = 0; i < count; i++)
yield return GetComponentByIndex(i);
}
public GPUComponentHandle GetComponentByIndex(int index)
{
Assert.IsTrue(index >= 0 && index < GetComponentsCount(), "Index out of range.");
ulong mask = componentsMask;
int compIndex = 0;
while (mask != 0)
{
var component = GPUComponentHandle.Create((short)math.tzcnt(mask));
mask &= ~(1ul << component.index);
if (compIndex++ == index)
return component;
}
throw new InvalidOperationException("Index out of range.");
}
public NativeList<GPUComponentHandle> GetComponents(Allocator allocator)
{
var components = new NativeList<GPUComponentHandle>(GetComponentsCount(), allocator);
for (int i = 0; i < GPUArchetypeManager.kMaxComponentsCount; ++i)
{
if ((componentsMask & (1ul << i)) != 0)
components.AddNoResize(GPUComponentHandle.Create((short)i));
}
return components;
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 18fb68347df974242bdf9a3f2efe05bd
@@ -0,0 +1,16 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef GPUINSTANCEDATABUFFER_CS_HLSL
#define GPUINSTANCEDATABUFFER_CS_HLSL
//
// UnityEngine.Rendering.GPUInstanceDataBufferConstants: static fields
//
#define GPUINSTANCEDATABUFFERCONSTANTS_THREAD_GROUP_SIZE (128)
#define GPUINSTANCEDATABUFFERCONSTANTS_UINT_PER_THREAD (16)
#define GPUINSTANCEDATABUFFERCONSTANTS_UINT_PER_THREAD_GROUP (2048)
#define GPUINSTANCEDATABUFFERCONSTANTS_MAX_THREAD_GROUPS_PER_DISPATCH (65535)
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: c624d8646a289a747b3dfb97cf7aebdd
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7e2ab3702e1f0d2408e45282d1cb4e9f
@@ -0,0 +1,111 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
//@ Add instance version or generation to detect dangling instance handles.
// This is used to uniquely reference an instance on the CPU side.
internal struct InstanceHandle : IEquatable<InstanceHandle>, IComparable<InstanceHandle>
{
public int index { get; private set; }
public bool isValid => index >= 0;
public static InstanceHandle Create(int index) { return new InstanceHandle { index = index }; }
public static readonly InstanceHandle Invalid = new InstanceHandle { index = -1 };
public bool Equals(InstanceHandle other) => index == other.index;
public int CompareTo(InstanceHandle other) { return index.CompareTo(other.index); }
public override int GetHashCode() { return index; }
}
// This is used to uniquely define an instance within its archetype on the GPU side. (Instance data is sorted by archetype on the GPU).
internal struct InstanceGPUHandle : IEquatable<InstanceGPUHandle>, IComparable<InstanceGPUHandle>
{
private int m_Data;
public bool isValid => m_Data >= 0;
public GPUArchetypeHandle archetype => GPUArchetypeHandle.Create((short)(m_Data & GPUArchetypeManager.kGPUArchetypeBitsMask));
public int archetypeInstanceIndex => m_Data >> GPUArchetypeManager.kGPUArchetypeBits;
public static InstanceGPUHandle Create(GPUArchetypeHandle gpuArchetype, int gpuPerArchetypeIndex)
{
Assert.IsTrue(gpuArchetype.index < GPUArchetypeManager.kMaxGPUArchetypesCount);
return new InstanceGPUHandle
{
m_Data = ((gpuPerArchetypeIndex << GPUArchetypeManager.kGPUArchetypeBits) | (int)gpuArchetype.index)
};
}
public static readonly InstanceGPUHandle Invalid = new InstanceGPUHandle { m_Data = -1 };
public bool Equals(InstanceGPUHandle other) => m_Data == other.m_Data;
public int CompareTo(InstanceGPUHandle other) { return m_Data.CompareTo(other.m_Data); }
public override int GetHashCode() { return m_Data; }
}
internal unsafe struct InstanceAllocators
{
private NativeHandleAllocator m_InstanceCPUHandleAllocator;
private NativeArray<NativeHandleAllocator> m_InstanceGPUHandleAllocators;
public void Initialize()
{
m_InstanceCPUHandleAllocator = new NativeHandleAllocator();
m_InstanceCPUHandleAllocator.Initialize();
m_InstanceGPUHandleAllocators = new NativeArray<NativeHandleAllocator>(GPUArchetypeManager.kMaxGPUArchetypesCount, Allocator.Persistent);
for(int i = 0; i < m_InstanceGPUHandleAllocators.Length; ++i)
UnsafeUtility.ArrayElementAsRef<NativeHandleAllocator>(m_InstanceGPUHandleAllocators.GetUnsafePtr(), i).Initialize();
}
public unsafe void Dispose()
{
m_InstanceCPUHandleAllocator.Dispose();
for (int i = 0; i < m_InstanceGPUHandleAllocators.Length; ++i)
UnsafeUtility.ArrayElementAsRef<NativeHandleAllocator>(m_InstanceGPUHandleAllocators.GetUnsafePtr(), i).Dispose();
m_InstanceGPUHandleAllocators.Dispose();
}
private ref NativeHandleAllocator GetInstanceGPUHandleAllocator(GPUArchetypeHandle archetype)
{
Assert.IsTrue(archetype.valid);
return ref UnsafeUtility.ArrayElementAsRef<NativeHandleAllocator>(m_InstanceGPUHandleAllocators.GetUnsafePtr(), archetype.index);
}
public int TrimGPUAllocatorLength(GPUArchetypeHandle archetype)
{
ref var allocator = ref GetInstanceGPUHandleAllocator(archetype);
allocator.TrimLength();
return allocator.length;
}
public int GetInstanceGPUHandlesAllocatedCount(GPUArchetypeHandle archetype)
{
return GetInstanceGPUHandleAllocator(archetype).allocatedCount;
}
public InstanceHandle AllocateInstance()
{
return InstanceHandle.Create(m_InstanceCPUHandleAllocator.Allocate());
}
public InstanceGPUHandle AllocateInstanceGPUHandle(GPUArchetypeHandle archetype)
{
return InstanceGPUHandle.Create(archetype, GetInstanceGPUHandleAllocator(archetype).Allocate());
}
public void FreeInstance(InstanceHandle instance)
{
Assert.IsTrue(instance.isValid);
m_InstanceCPUHandleAllocator.Free(instance.index);
}
public void FreeInstanceGPUHandle(InstanceGPUHandle gpuHandle)
{
Assert.IsTrue(gpuHandle.isValid);
GetInstanceGPUHandleAllocator(gpuHandle.archetype).Free(gpuHandle.archetypeInstanceIndex);
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c82098f48a6ef0540a1073dd15a52c80
@@ -0,0 +1,661 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using System.Runtime.CompilerServices;
using System.Threading;
using Unity.Burst;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
internal partial class InstanceDataSystem : IDisposable
{
static float3 AABBRotateExtents(float3 extents, float3 m0, float3 m1, float3 m2)
{
return math.abs(m0 * extents.x) + math.abs(m1 * extents.y) + math.abs(m2 * extents.z);
}
public static AABB AABBTransform(float4x4 transform, AABB localBounds)
{
AABB transformed;
transformed.extents = AABBRotateExtents(localBounds.extents, transform.c0.xyz, transform.c1.xyz, transform.c2.xyz);
transformed.center = math.transform(transform, localBounds.center);
return transformed;
}
private unsafe static int AtomicAddLengthNoResize<T>(in NativeList<T> list, int count) where T : unmanaged
{
UnsafeList<T>* unsafeList = list.GetUnsafeList();
var newLength = Interlocked.Add(ref unsafeList->m_length, count);
Assert.IsTrue(unsafeList->Capacity >= newLength);
return newLength - count;
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private unsafe struct QueryRendererInstancesJob : IJobParallelFor
{
[ReadOnly] public NativeArray<JaggedJobRange> jobRanges;
[ReadOnly] public NativeParallelHashMap<EntityId, InstanceHandle> rendererToInstanceMap;
[NativeDisableContainerSafetyRestriction, NoAlias][ReadOnly] public JaggedSpan<EntityId> jaggedRenderers;
[NativeDisableContainerSafetyRestriction, NoAlias][WriteOnly] public NativeArray<InstanceHandle> instances;
[NativeDisableUnsafePtrRestriction] public UnsafeAtomicCounter32 atomicNonFoundInstancesCount;
public void Execute(int jobIndex)
{
JaggedJobRange jobRange = jobRanges[jobIndex];
NativeArray<EntityId> renderers = jaggedRenderers[jobRange.sectionIndex];
int newInstancesCountJob = 0;
for (int i = 0; i < jobRange.length; ++i)
{
int localIndex = jobRange.localStart + i;
int absoluteIndex = jobRange.absoluteStart + i;
if (rendererToInstanceMap.TryGetValue(renderers[localIndex], out var instance))
{
instances[absoluteIndex] = instance;
}
else
{
newInstancesCountJob += 1;
instances[absoluteIndex] = InstanceHandle.Invalid;
}
}
if (atomicNonFoundInstancesCount.Counter != null && newInstancesCountJob > 0)
atomicNonFoundInstancesCount.Add(newInstancesCountJob);
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private struct QuerySortedMeshInstancesJob : IJobParallelForBatch
{
public const int MaxBatchSize = 64;
[ReadOnly] public RenderWorld renderWorld;
[ReadOnly] public NativeArray<EntityId> sortedMeshes;
[NativeDisableParallelForRestriction][WriteOnly] public NativeList<InstanceHandle> instances;
public void Execute(int startIndex, int count)
{
Assert.IsTrue(MaxBatchSize <= 64 && count <= 64);
ulong validBits = 0;
// Do a first pass to count the number of valid instances so we can do only one atomic add for the whole range.
for (int i = 0; i < count; ++i)
{
int instanceIndex = startIndex + i;
InstanceHandle instance = renderWorld.IndexToHanle(instanceIndex);
EntityId mesh = renderWorld.meshIDs[instanceIndex];
if (sortedMeshes.BinarySearch(mesh) >= 0)
validBits |= 1ul << i;
}
int validBitCount = math.countbits(validBits);
if (validBitCount > 0)
{
int writeIndex = AtomicAddLengthNoResize(instances, validBitCount);
int validBitIndex = math.tzcnt(validBits);
while (validBits != 0)
{
int instanceIndex = startIndex + validBitIndex;
instances[writeIndex] = renderWorld.indexToHandle[instanceIndex];
writeIndex += 1;
validBits &= ~(1ul << validBitIndex);
validBitIndex = math.tzcnt(validBits);
}
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private struct CalculateInterpolatedLightAndOcclusionProbesBatchJob : IJobParallelFor
{
public const int k_CalculatedProbesPerBatch = 8;
[ReadOnly] public int probesCount;
[ReadOnly] public LightProbesQuery lightProbesQuery;
[NativeDisableParallelForRestriction][ReadOnly] public NativeArray<Vector3> queryPostitions;
[NativeDisableParallelForRestriction] public NativeArray<int> compactTetrahedronCache;
[NativeDisableParallelForRestriction][WriteOnly] public NativeArray<SphericalHarmonicsL2> probesSphericalHarmonics;
[NativeDisableParallelForRestriction][WriteOnly] public NativeArray<Vector4> probesOcclusion;
public void Execute(int index)
{
var startIndex = index * k_CalculatedProbesPerBatch;
var endIndex = math.min(probesCount, startIndex + k_CalculatedProbesPerBatch);
var count = endIndex - startIndex;
var compactTetrahedronCacheSubArray = compactTetrahedronCache.GetSubArray(startIndex, count);
var queryPostitionsSubArray = queryPostitions.GetSubArray(startIndex, count);
var probesSphericalHarmonicsSubArray = probesSphericalHarmonics.GetSubArray(startIndex, count);
var probesOcclusionSubArray = probesOcclusion.GetSubArray(startIndex, count);
lightProbesQuery.CalculateInterpolatedLightAndOcclusionProbes(queryPostitionsSubArray, compactTetrahedronCacheSubArray, probesSphericalHarmonicsSubArray, probesOcclusionSubArray);
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private struct ScatterTetrahedronCacheIndicesJob : IJobParallelFor
{
[ReadOnly] public NativeArray<InstanceHandle> probeInstances;
[ReadOnly] public NativeArray<int> compactTetrahedronCache;
[NativeDisableContainerSafetyRestriction, NoAlias][NativeDisableParallelForRestriction] public RenderWorld renderWorld;
public void Execute(int index)
{
InstanceHandle instance = probeInstances[index];
int instanceIndex = renderWorld.HandleToIndex(instance);
renderWorld.tetrahedronCacheIndices.ElementAtRW(instanceIndex) = compactTetrahedronCache[index];
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private unsafe struct TransformUpdateJob : IJobParallelFor
{
public const int MaxBatchSize = 64;
[ReadOnly] public NativeArray<JaggedJobRange> jobRanges;
[ReadOnly] public NativeArray<InstanceHandle> instances;
[ReadOnly] public JaggedSpan<float4x4> jaggedLocalToWorldMatrices;
[ReadOnly] public JaggedSpan<float4x4> jaggedPrevLocalToWorldMatrices;
[ReadOnly] public bool initialize;
[ReadOnly] public bool enableBoundingSpheres;
[NativeDisableUnsafePtrRestriction] public UnsafeAtomicCounter32 atomicTransformQueueCount;
[NativeDisableParallelForRestriction] public RenderWorld renderWorld;
[NativeDisableParallelForRestriction] public NativeArray<InstanceHandle> transformUpdateInstanceQueue;
[NativeDisableParallelForRestriction] public NativeArray<TransformUpdatePacket> transformUpdateDataQueue;
[NativeDisableParallelForRestriction] public NativeArray<float4> boundingSpheresDataQueue;
public void Execute(int jobIndex)
{
var jobRange = jobRanges[jobIndex];
var localToWorldMatrices = jaggedLocalToWorldMatrices[jobRange.sectionIndex];
var prevLocalToWorldMatrices = jaggedPrevLocalToWorldMatrices[jobRange.sectionIndex];
// The bitfield can only contain up to 64 instances
Assert.IsTrue(MaxBatchSize <= 64 && jobRange.length <= 64);
ulong validBits = 0;
for (int i = 0; i < jobRange.length; ++i)
{
InstanceHandle instance = instances[jobRange.absoluteStart + i];
if (!instance.isValid)
continue;
if (!initialize)
{
int instanceIndex = renderWorld.HandleToIndex(instance);
bool movedCurrentFrame = renderWorld.movedInCurrentFrameBits.Get(instanceIndex);
bool isStaticObject = renderWorld.rendererSettings[instanceIndex].IsPartOfStaticBatch;
if (isStaticObject || movedCurrentFrame)
continue;
}
validBits |= 1ul << i;
}
int validBitCount = math.countbits(validBits);
if (validBitCount > 0)
{
int writeIndex = atomicTransformQueueCount.Add(validBitCount);
int validBitIndex = math.tzcnt(validBits);
while (validBits != 0)
{
int absoluteIndex = jobRange.absoluteStart + validBitIndex;
int localIndex = jobRange.localStart + validBitIndex;
InstanceHandle instance = instances[absoluteIndex];
int instanceIndex = renderWorld.HandleToIndex(instance);
bool isStaticObject = renderWorld.rendererSettings[instanceIndex].IsPartOfStaticBatch;
renderWorld.movedInCurrentFrameBits.Set(instanceIndex, !isStaticObject);
transformUpdateInstanceQueue[writeIndex] = instance;
ref readonly float4x4 l2w = ref localToWorldMatrices.ElementAt(localIndex);
ref readonly AABB localAABB = ref renderWorld.localAABBs.ElementAt(instanceIndex);
AABB worldAABB = AABBTransform(l2w, localAABB);
float det = math.determinant((float3x3)l2w);
renderWorld.worldAABBs.ElementAtRW(instanceIndex) = worldAABB;
renderWorld.localToWorldIsFlippedBits.Set(instanceIndex, det < 0.0f);
if (initialize)
{
PackedMatrix l2wPacked = PackedMatrix.FromFloat4x4(l2w);
PackedMatrix l2wPrevPacked = PackedMatrix.FromFloat4x4(prevLocalToWorldMatrices.ElementAt(localIndex));
transformUpdateDataQueue[writeIndex * 2] = new TransformUpdatePacket()
{
localToWorld0 = l2wPacked.packed0,
localToWorld1 = l2wPacked.packed1,
localToWorld2 = l2wPacked.packed2,
};
transformUpdateDataQueue[writeIndex * 2 + 1] = new TransformUpdatePacket()
{
localToWorld0 = l2wPrevPacked.packed0,
localToWorld1 = l2wPrevPacked.packed1,
localToWorld2 = l2wPrevPacked.packed2,
};
}
else
{
PackedMatrix l2wPacked = PackedMatrix.FromFloat4x4(l2w);
transformUpdateDataQueue[writeIndex] = new TransformUpdatePacket()
{
localToWorld0 = l2wPacked.packed0,
localToWorld1 = l2wPacked.packed1,
localToWorld2 = l2wPacked.packed2,
};
}
if (enableBoundingSpheres)
boundingSpheresDataQueue[writeIndex] = new float4(worldAABB.center.x, worldAABB.center.y, worldAABB.center.z, math.distance(worldAABB.max, worldAABB.min) * 0.5f);
writeIndex += 1;
validBits &= ~(1ul << validBitIndex);
validBitIndex = math.tzcnt(validBits);
}
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private unsafe struct ProbesUpdateJob : IJobParallelForBatch
{
public const int MaxBatchSize = 64;
[ReadOnly] [NativeDisableContainerSafetyRestriction, NoAlias] public NativeArray<InstanceHandle> instances;
[ReadOnly] [NativeDisableContainerSafetyRestriction, NoAlias] public RenderWorld renderWorld;
[NativeDisableUnsafePtrRestriction] public UnsafeAtomicCounter32 atomicProbesQueueCount;
[NativeDisableParallelForRestriction] public NativeArray<InstanceHandle> probeInstanceQueue;
[NativeDisableParallelForRestriction] public NativeArray<int> compactTetrahedronCache;
[NativeDisableParallelForRestriction] public NativeArray<Vector3> probeQueryPosition;
public void Execute(int startIndex, int count)
{
Assert.IsTrue(MaxBatchSize <= 64 && count <= 64);
ulong validBits = 0;
for (int i = 0; i < count; ++i)
{
InstanceHandle instance = instances[startIndex + i];
if (!instance.isValid)
continue;
int instanceIndex = renderWorld.HandleToIndex(instance);
InternalMeshRendererSettings rendererSettings = renderWorld.rendererSettings[instanceIndex];
int lightmapIndex = renderWorld.lightmapIndices[instanceIndex];
bool hasLightProbes = !LightmapUtils.UsesLightmaps(lightmapIndex)
&& rendererSettings.LightProbeUsage == LightProbeUsage.BlendProbes;
if (!hasLightProbes)
continue;
validBits |= 1ul << i;
}
int validBitCount = math.countbits(validBits);
if (validBitCount > 0)
{
int writeIndex = atomicProbesQueueCount.Add(validBitCount);
int validBitIndex = math.tzcnt(validBits);
while (validBits != 0)
{
InstanceHandle instance = instances[startIndex + validBitIndex];
int instanceIndex = renderWorld.HandleToIndex(instance);
ref readonly AABB worldAABB = ref renderWorld.worldAABBs.ElementAt(instanceIndex);
probeInstanceQueue[writeIndex] = instance;
probeQueryPosition[writeIndex] = worldAABB.center;
compactTetrahedronCache[writeIndex] = renderWorld.tetrahedronCacheIndices[instanceIndex];
writeIndex += 1;
validBits &= ~(1ul << validBitIndex);
validBitIndex = math.tzcnt(validBits);
}
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private struct MotionUpdateJob : IJobParallelFor
{
[ReadOnly] public int queueWriteBase;
[NativeDisableParallelForRestriction] public RenderWorld renderWorld;
[NativeDisableUnsafePtrRestriction] public UnsafeAtomicCounter32 atomicUpdateQueueCount;
[NativeDisableParallelForRestriction][WriteOnly] public NativeArray<InstanceHandle> transformUpdateInstanceQueue;
public void Execute(int chunk_index)
{
int maxChunkBitCount = math.min(renderWorld.instanceCount - 64 * chunk_index, 64);
ulong chunkBitMask = ~0ul >> (64 - maxChunkBitCount);
ulong currentChunkBits = renderWorld.movedInCurrentFrameBits.GetChunk(chunk_index) & chunkBitMask;
ulong prevChunkBits = renderWorld.movedInPreviousFrameBits.GetChunk(chunk_index) & chunkBitMask;
// update state in memory for the next frame
renderWorld.movedInCurrentFrameBits.SetChunk(chunk_index, 0);
renderWorld.movedInPreviousFrameBits.SetChunk(chunk_index, currentChunkBits);
// ensure that objects that were moved last frame update their previous world matrix, if not already fully updated
ulong remainingChunkBits = prevChunkBits & ~currentChunkBits;
// allocate space for all the writes from this chunk
int chunkBitCount = math.countbits(remainingChunkBits);
int writeIndex = queueWriteBase;
if (chunkBitCount > 0)
writeIndex += atomicUpdateQueueCount.Add(chunkBitCount);
// loop over set bits to do the writes
int indexInChunk = math.tzcnt(remainingChunkBits);
while (indexInChunk < 64)
{
int instanceIndex = 64 * chunk_index + indexInChunk;
transformUpdateInstanceQueue[writeIndex] = renderWorld.IndexToHanle(instanceIndex);
writeIndex += 1;
remainingChunkBits &= ~(1ul << indexInChunk);
indexInChunk = math.tzcnt(remainingChunkBits);
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private unsafe struct UpdateRendererInstancesJob : IJobParallelFor
{
[ReadOnly] public NativeArray<JaggedJobRange> jobRanges;
[ReadOnly] public MeshRendererUpdateBatch updateBatch;
[ReadOnly] public NativeArray<InstanceHandle> instances;
[ReadOnly] public NativeParallelHashMap<EntityId, GPUInstanceIndex> lodGroupDataMap;
[NativeDisableParallelForRestriction][NativeDisableContainerSafetyRestriction] public RenderWorld renderWorld;
public void Execute(int jobIndex)
{
JaggedJobRange jobRange = jobRanges[jobIndex];
NativeArray<EntityId> rendererSection = updateBatch.instanceIDs[jobRange.sectionIndex];
NativeArray<EntityId> meshSection = updateBatch.GetMeshSectionOrDefault(jobRange.sectionIndex);
NativeArray<ushort> subMeshStartIndexSection = updateBatch.GetSubMeshStartIndexSectionOrDefault(jobRange.sectionIndex);
NativeArray<ushort> staticBatchSubMeshCountSection = updateBatch.GetStaticBatchSubMeshCountSectionOrDefault(jobRange.sectionIndex);
NativeArray<EntityId> materialSection = updateBatch.GetMaterialSectionOrDefault(jobRange.sectionIndex);
NativeArray<RangeInt> subMaterialRangeSection = updateBatch.GetSubMaterialRangeSectionOrDefault(jobRange.sectionIndex);
NativeArray<float4x4> localToWorldSection = updateBatch.GetLocalToWorldSectionOrDefault(jobRange.sectionIndex);
NativeArray<AABB> localBoundsSection = updateBatch.GetLocalBoundsSectionOrDefault(jobRange.sectionIndex);
NativeArray<InternalMeshRendererSettings> rendererSettingsSection = updateBatch.GetRendererSettingsSectionOrDefault(jobRange.sectionIndex);
NativeArray<int> rendererPrioritySection = updateBatch.GetRendererPrioritySectionOrDefault(jobRange.sectionIndex);
NativeArray<short> lightmapIndexSection = updateBatch.GetLightmapIndexSectionOrDefault(jobRange.sectionIndex);
NativeArray<EntityId> parentLODGroupSection = updateBatch.GetParentLODGroupIDSectionOrDefault(jobRange.sectionIndex);
NativeArray<byte> lodMaskSection = updateBatch.GetLODMaskSectionOrDefault(jobRange.sectionIndex);
NativeArray<InternalMeshLodRendererSettings> meshLodSettingsSection = updateBatch.GetMeshLodSettingsSectionOrDefault(jobRange.sectionIndex);
UnsafeBitArray renderingEnabledSection = updateBatch.GetRenderingEnabledSectionOrDefault(jobRange.sectionIndex);
NativeArray<ulong> sceneCullingMaskSection = default;
ulong sharedSceneCullingMask = 0;
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.SceneCullingMask))
{
if (updateBatch.useSharedSceneCullingMask)
{
sharedSceneCullingMask = updateBatch.sharedSceneCullingMasks[jobRange.sectionIndex];
}
else
{
sceneCullingMaskSection = updateBatch.sceneCullingMasks[jobRange.sectionIndex];
}
}
MeshRendererUpdateType updateType = updateBatch.updateType;
bool hasOnlyKnowInstances = updateType == MeshRendererUpdateType.NoStructuralChanges
|| updateType == MeshRendererUpdateType.RecreateOnlyKnownInstances;
int treeCountDelta = 0;
for (int i = 0; i < jobRange.length; i++)
{
int localIndex = jobRange.localStart + i;
int absoluteIndex = jobRange.absoluteStart + i;
EntityId renderer = rendererSection[localIndex];
InstanceHandle instance = instances[absoluteIndex];
Assert.IsTrue(instance.isValid, "Invalid Instance");
if (!instance.isValid)
continue;
int instanceIndex = renderWorld.HandleToIndex(instance);
bool oldInstanceHasTree = renderWorld.rendererSettings[instanceIndex].HasTree;
// Rebuild instance from scratch in all cases except when we know there is no structural changes.
if (updateType != MeshRendererUpdateType.NoStructuralChanges)
renderWorld.ResetInstance(instanceIndex);
if (hasOnlyKnowInstances)
{
Assert.IsTrue(renderWorld.instanceIDs[instanceIndex] == renderer);
}
else
{
renderWorld.instanceIDs.ElementAtRW(instanceIndex) = renderer;
}
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.Material))
{
var subMaterialRange = subMaterialRangeSection[localIndex];
var subMaterialIDs = new EmbeddedArray32<EntityId>(materialSection.GetSubArray(subMaterialRange.start, subMaterialRange.length),
Allocator.Persistent);
renderWorld.materialIDArrays.ElementAtRW(instanceIndex).Dispose();
renderWorld.materialIDArrays.ElementAtRW(instanceIndex) = subMaterialIDs;
}
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.LocalBounds))
{
Assert.AreEqual(localToWorldSection.Length, rendererSection.Length);
ref readonly float4x4 l2w = ref localToWorldSection.ElementAt(localIndex);
AABB localBounds = localBoundsSection[localIndex];
AABB worldBounds = AABBTransform(l2w, localBounds);
// Note that world bounds are updated here only when local bounds change, but not when transforms change.
// Transform changes are handled in other dedicated jobs.
renderWorld.localAABBs.ElementAtRW(instanceIndex) = localBounds;
renderWorld.worldAABBs.ElementAtRW(instanceIndex) = worldBounds;
}
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.ParentLODGroup))
{
EntityId parentLODGroup = parentLODGroupSection[localIndex];
// Renderer's LODGroup could be disabled which means that the renderer is not managed by it.
GPUInstanceIndex parentLODGroupHandle = GPUInstanceIndex.Invalid;
if (lodGroupDataMap.TryGetValue(parentLODGroup, out var handle))
parentLODGroupHandle = handle;
renderWorld.lodGroupIndices.ElementAtRW(instanceIndex) = parentLODGroupHandle;
}
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.LODMask))
renderWorld.lodMasks.ElementAtRW(instanceIndex) = lodMaskSection[localIndex];
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.MeshLodSettings))
renderWorld.meshLodRendererSettings.ElementAtRW(instanceIndex) = meshLodSettingsSection[localIndex];
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.Mesh))
renderWorld.meshIDs.ElementAtRW(instanceIndex) = meshSection[localIndex];
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.SubMeshStartIndex))
renderWorld.subMeshStartIndices.ElementAtRW(instanceIndex) = subMeshStartIndexSection[localIndex];
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.StaticBatchSubMeshCount))
renderWorld.staticBatchSubMeshCounts.ElementAtRW(instanceIndex) = staticBatchSubMeshCountSection[localIndex];
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.RendererSettings))
{
InternalMeshRendererSettings newSettings = rendererSettingsSection[localIndex];
if (oldInstanceHasTree)
{
if (!newSettings.HasTree)
--treeCountDelta;
}
else
{
if (newSettings.HasTree)
++treeCountDelta;
}
renderWorld.rendererSettings.ElementAtRW(instanceIndex) = newSettings;
}
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.Lightmap))
renderWorld.lightmapIndices.ElementAtRW(instanceIndex) = lightmapIndexSection[localIndex];
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.RendererPriority))
renderWorld.rendererPriorities.ElementAtRW(instanceIndex) = rendererPrioritySection[localIndex];
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.RenderingEnabled))
renderWorld.renderingEnabled.Set(instanceIndex, renderingEnabledSection.IsSet(localIndex));
#if UNITY_EDITOR
if (updateBatch.HasAnyComponent(MeshRendererComponentMask.SceneCullingMask))
renderWorld.sceneCullingMasks.ElementAtRW(instanceIndex) = updateBatch.useSharedSceneCullingMask ?
sharedSceneCullingMask :
sceneCullingMaskSection[localIndex];
#endif
}
int oldTotalTreeCount = renderWorld.atomicTotalTreeCount.Add(treeCountDelta);
Assert.IsTrue(oldTotalTreeCount + treeCountDelta >= 0);
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private struct GetVisibleNonProcessedTreeInstancesJob : IJobParallelForBatch
{
public const int MaxBatchSize = 64;
[ReadOnly] public RenderWorld renderWorld;
[ReadOnly][NativeDisableContainerSafetyRestriction, NoAlias] public ParallelBitArray compactedVisibilityMasks;
[ReadOnly] public bool becomeVisible;
[NativeDisableParallelForRestriction] public ParallelBitArray processedBits;
[NativeDisableParallelForRestriction][WriteOnly] public NativeArray<EntityId> renderers;
[NativeDisableParallelForRestriction][WriteOnly] public NativeArray<InstanceHandle> instances;
[NativeDisableUnsafePtrRestriction] public UnsafeAtomicCounter32 atomicTreeInstancesCount;
public void Execute(int startIndex, int count)
{
Assert.IsTrue(MaxBatchSize == 64 && count <= 64);
ulong validBits = 0;
var chunkIndex = startIndex / 64;
var visibleInPrevFrameChunk = renderWorld.visibleInPreviousFrameBits.GetChunk(chunkIndex);
var processedChunk = processedBits.GetChunk(chunkIndex);
for (int i = 0; i < count; ++i)
{
int instanceIndex = startIndex + i;
InstanceHandle instance = renderWorld.IndexToHanle(instanceIndex);
bool hasTree = renderWorld.rendererSettings[instanceIndex].HasTree;
if (hasTree && compactedVisibilityMasks.Get(instance.index))
{
var bitMask = 1ul << i;
var processedInCurrentFrame = (processedChunk & bitMask) != 0;
if (!processedInCurrentFrame)
{
bool visibleInPrevFrame = (visibleInPrevFrameChunk & bitMask) != 0;
if (becomeVisible)
{
if (!visibleInPrevFrame)
validBits |= bitMask;
}
else
{
if (visibleInPrevFrame)
validBits |= bitMask;
}
}
}
}
int validBitsCount = math.countbits(validBits);
if (validBitsCount > 0)
{
processedBits.SetChunk(chunkIndex, processedChunk | validBits);
int writeIndex = atomicTreeInstancesCount.Add(validBitsCount);
int validBitIndex = math.tzcnt(validBits);
while (validBits != 0)
{
int instanceIndex = startIndex + validBitIndex;
EntityId renderer = renderWorld.instanceIDs[instanceIndex];
InstanceHandle instance = renderWorld.IndexToHanle(instanceIndex);
renderers[writeIndex] = renderer;
instances[writeIndex] = instance;
writeIndex += 1;
validBits &= ~(1ul << validBitIndex);
validBitIndex = math.tzcnt(validBits);
}
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
private struct UpdateCompactedInstanceVisibilityJob : IJobParallelForBatch
{
public const int MaxBatchSize = 64;
[ReadOnly] public ParallelBitArray compactedVisibilityMasks;
[NativeDisableContainerSafetyRestriction, NoAlias][NativeDisableParallelForRestriction] public RenderWorld renderWorld;
public void Execute(int startIndex, int count)
{
Assert.IsTrue(MaxBatchSize == 64 && count <= 64);
ulong visibleBits = 0;
for (int i = 0; i < count; ++i)
{
int instanceIndex = startIndex + i;
InstanceHandle instance = renderWorld.IndexToHanle(instanceIndex);
bool visible = compactedVisibilityMasks.Get(instance.index);
if (visible)
visibleBits |= 1ul << i;
}
renderWorld.visibleInPreviousFrameBits.SetChunk(startIndex / 64, visibleBits);
}
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4fde0d9aabe2aee46b306a42532dafc7
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1b8bad1fc5971e549920c6b3e6c4b309
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,200 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System.Runtime.CompilerServices;
using Unity.Collections;
using Unity.Burst;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
internal enum InstanceAllocatorVariant
{
Null,
AllocOnly,
GPUReallocOnly,
AllocOrGPURealloc
}
[BurstCompile]
internal static class InstanceDataSystemBurst
{
// Length == 1 means the archetype is shared over all the instances
private static GPUArchetypeHandle FetchArchetype(in NativeArray<GPUArchetypeHandle> archetypes, int index) => archetypes.Length == 1 ? archetypes[0] : archetypes[index];
private static unsafe void AllocOnlyIteration(NativeArray<EntityId> instanceIDSection,
int absoluteIndex,
int localIndex,
in NativeArray<GPUArchetypeHandle> archetypes,
InstanceAllocators* instanceAllocators,
ref RenderWorld renderWorld,
ref NativeArray<InstanceHandle> instances,
ref NativeParallelHashMap<EntityId, InstanceHandle> rendererToInstanceMap)
{
EntityId instanceID = instanceIDSection[localIndex];
GPUArchetypeHandle archetype = FetchArchetype(archetypes, absoluteIndex);
InstanceHandle newInstance = instanceAllocators->AllocateInstance();
InstanceGPUHandle newGPUHandle = instanceAllocators->AllocateInstanceGPUHandle(archetype);
int instanceIndex = renderWorld.AddInstanceNoGrow(newInstance);
renderWorld.gpuHandles.ElementAtRW(instanceIndex) = newGPUHandle;
rendererToInstanceMap.Add(instanceID, newInstance);
instances[absoluteIndex] = newInstance;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void AllocOnly(in JaggedSpan<EntityId> jaggedInstanceIDs,
in NativeArray<GPUArchetypeHandle> archetypes,
InstanceAllocators* instanceAllocators,
ref RenderWorld renderWorld,
ref NativeArray<InstanceHandle> instances,
ref NativeParallelHashMap<EntityId, InstanceHandle> rendererToInstanceMap)
{
int absoluteIndex = 0;
for (int sectionIndex = 0; sectionIndex < jaggedInstanceIDs.sectionCount; sectionIndex++)
{
NativeArray<EntityId> instanceIDs = jaggedInstanceIDs[sectionIndex];
for (int localIndex = 0; localIndex < instanceIDs.Length; localIndex++, absoluteIndex++)
{
AllocOnlyIteration(instanceIDs, absoluteIndex, localIndex, archetypes, instanceAllocators, ref renderWorld, ref instances, ref rendererToInstanceMap);
}
}
}
private static unsafe void GPUReallocOnlyIteration(InstanceHandle instance,
GPUArchetypeHandle archetype,
InstanceAllocators* instanceAllocators,
ref RenderWorld renderWorld)
{
int instanceIndex = renderWorld.HandleToIndex(instance);
InstanceGPUHandle gpuHandle = renderWorld.gpuHandles[instanceIndex];
Assert.IsTrue(gpuHandle.isValid);
if (archetype.Equals(gpuHandle.archetype))
return;
instanceAllocators->FreeInstanceGPUHandle(gpuHandle);
renderWorld.gpuHandles.ElementAtRW(instanceIndex) = instanceAllocators->AllocateInstanceGPUHandle(archetype);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void GPUReallocOnly(in NativeArray<GPUArchetypeHandle> archetypes,
InstanceAllocators* instanceAllocators,
ref RenderWorld renderWorld,
ref NativeArray<InstanceHandle> instances)
{
for (int i = 0; i < instances.Length; i++)
{
InstanceHandle instance = instances[i];
Assert.IsTrue(instance.isValid, "Invalid Instance");
if (!instance.isValid)
continue;
GPUArchetypeHandle archetype = FetchArchetype(archetypes, i);
GPUReallocOnlyIteration(instance, archetype, instanceAllocators, ref renderWorld);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static unsafe void AllocOrGPURealloc(in JaggedSpan<EntityId> jaggedInstanceIDs,
in NativeArray<GPUArchetypeHandle> archetypes,
InstanceAllocators* instanceAllocators,
ref RenderWorld renderWorld,
ref NativeArray<InstanceHandle> instances,
ref NativeParallelHashMap<EntityId, InstanceHandle> rendererToInstanceMap)
{
int absoluteIndex = 0;
for (int sectionIndex = 0; sectionIndex < jaggedInstanceIDs.sectionCount; sectionIndex++)
{
NativeArray<EntityId> instanceIDs = jaggedInstanceIDs[sectionIndex];
for (int localIndex = 0; localIndex < instanceIDs.Length; localIndex++, absoluteIndex++)
{
GPUArchetypeHandle archetype = FetchArchetype(archetypes, absoluteIndex);
InstanceHandle instance = instances[absoluteIndex];
if (instance.isValid)
{
GPUReallocOnlyIteration(instance, archetype, instanceAllocators, ref renderWorld);
}
else
{
AllocOnlyIteration(instanceIDs, absoluteIndex, localIndex, archetypes, instanceAllocators, ref renderWorld, ref instances, ref rendererToInstanceMap);
}
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
// Without using InstanceAllocators as a pointer there is a crash inside native containers allocator. Same everywhere.
public static unsafe void AllocateInstances(InstanceAllocatorVariant allocVariant,
in JaggedSpan<EntityId> jaggedInstanceIDs,
in NativeArray<GPUArchetypeHandle> archetypes,
InstanceAllocators* instanceAllocators,
ref RenderWorld renderWorld,
ref NativeArray<InstanceHandle> instances,
ref NativeParallelHashMap<EntityId, InstanceHandle> rendererToInstanceMap)
{
switch (allocVariant)
{
case InstanceAllocatorVariant.AllocOnly:
AllocOnly(jaggedInstanceIDs, archetypes, instanceAllocators, ref renderWorld, ref instances, ref rendererToInstanceMap);
break;
case InstanceAllocatorVariant.GPUReallocOnly:
GPUReallocOnly(archetypes, instanceAllocators, ref renderWorld, ref instances);
break;
case InstanceAllocatorVariant.AllocOrGPURealloc:
AllocOrGPURealloc(jaggedInstanceIDs, archetypes, instanceAllocators, ref renderWorld, ref instances, ref rendererToInstanceMap);
break;
default:
Assert.IsTrue(false, "Invalid InstanceAllocatorVariant");
break;
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
public static unsafe void FreeInstances(in NativeArray<InstanceHandle> instances,
InstanceAllocators* instanceAllocators,
ref RenderWorld renderWorld,
ref NativeParallelHashMap<EntityId, InstanceHandle> rendererToInstanceMap)
{
foreach (var instance in instances)
{
if (!renderWorld.IsValidInstance(instance))
continue;
int instanceIndex = renderWorld.HandleToIndex(instance);
EntityId renderer = renderWorld.instanceIDs[instanceIndex];
InstanceGPUHandle gpuHandle = renderWorld.gpuHandles[instanceIndex];
Assert.IsTrue(rendererToInstanceMap[renderer].Equals(instance));
rendererToInstanceMap.Remove(renderer);
renderWorld.RemoveInstance(instance);
instanceAllocators->FreeInstance(instance);
instanceAllocators->FreeInstanceGPUHandle(gpuHandle);
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
public static int ComputeTotalTreeCount(in NativeArray<InternalMeshRendererSettings> rendererSettings)
{
int totalTreeCount = 0;
foreach (var settings in rendererSettings)
{
totalTreeCount += settings.HasTree ? 1 : 0;
}
return totalTreeCount;
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c449e4f867e4b2b49bf7ff68b4ea66dd
@@ -0,0 +1,26 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using Unity.Mathematics;
using System.Runtime.InteropServices;
namespace UnityEngine.Rendering
{
[GenerateHLSL]
internal struct TransformUpdatePacket
{
public float4 localToWorld0;
public float4 localToWorld1;
public float4 localToWorld2;
}
//Must be a copy of SphericalHarmonicsL2
[GenerateHLSL]
[StructLayout(LayoutKind.Sequential)]
internal struct SHUpdatePacket
{
public float shr0, shr1, shr2, shr3, shr4, shr5, shr6, shr7, shr8;
public float shg0, shg1, shg2, shg3, shg4, shg5, shg6, shg7, shg8;
public float shb0, shb1, shb2, shb3, shb4, shb5, shb6, shb7, shb8;
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,176 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef INSTANCETRANSFORMUPDATEDEFS_CS_HLSL
#define INSTANCETRANSFORMUPDATEDEFS_CS_HLSL
// Generated from UnityEngine.Rendering.SHUpdatePacket
// PackingRules = Exact
struct SHUpdatePacket
{
float shr0;
float shr1;
float shr2;
float shr3;
float shr4;
float shr5;
float shr6;
float shr7;
float shr8;
float shg0;
float shg1;
float shg2;
float shg3;
float shg4;
float shg5;
float shg6;
float shg7;
float shg8;
float shb0;
float shb1;
float shb2;
float shb3;
float shb4;
float shb5;
float shb6;
float shb7;
float shb8;
};
// Generated from UnityEngine.Rendering.TransformUpdatePacket
// PackingRules = Exact
struct TransformUpdatePacket
{
float4 localToWorld0;
float4 localToWorld1;
float4 localToWorld2;
};
//
// Accessors for UnityEngine.Rendering.SHUpdatePacket
//
float GetShr0(SHUpdatePacket value)
{
return value.shr0;
}
float GetShr1(SHUpdatePacket value)
{
return value.shr1;
}
float GetShr2(SHUpdatePacket value)
{
return value.shr2;
}
float GetShr3(SHUpdatePacket value)
{
return value.shr3;
}
float GetShr4(SHUpdatePacket value)
{
return value.shr4;
}
float GetShr5(SHUpdatePacket value)
{
return value.shr5;
}
float GetShr6(SHUpdatePacket value)
{
return value.shr6;
}
float GetShr7(SHUpdatePacket value)
{
return value.shr7;
}
float GetShr8(SHUpdatePacket value)
{
return value.shr8;
}
float GetShg0(SHUpdatePacket value)
{
return value.shg0;
}
float GetShg1(SHUpdatePacket value)
{
return value.shg1;
}
float GetShg2(SHUpdatePacket value)
{
return value.shg2;
}
float GetShg3(SHUpdatePacket value)
{
return value.shg3;
}
float GetShg4(SHUpdatePacket value)
{
return value.shg4;
}
float GetShg5(SHUpdatePacket value)
{
return value.shg5;
}
float GetShg6(SHUpdatePacket value)
{
return value.shg6;
}
float GetShg7(SHUpdatePacket value)
{
return value.shg7;
}
float GetShg8(SHUpdatePacket value)
{
return value.shg8;
}
float GetShb0(SHUpdatePacket value)
{
return value.shb0;
}
float GetShb1(SHUpdatePacket value)
{
return value.shb1;
}
float GetShb2(SHUpdatePacket value)
{
return value.shb2;
}
float GetShb3(SHUpdatePacket value)
{
return value.shb3;
}
float GetShb4(SHUpdatePacket value)
{
return value.shb4;
}
float GetShb5(SHUpdatePacket value)
{
return value.shb5;
}
float GetShb6(SHUpdatePacket value)
{
return value.shb6;
}
float GetShb7(SHUpdatePacket value)
{
return value.shb7;
}
float GetShb8(SHUpdatePacket value)
{
return value.shb8;
}
//
// Accessors for UnityEngine.Rendering.TransformUpdatePacket
//
float4 GetLocalToWorld0(TransformUpdatePacket value)
{
return value.localToWorld0;
}
float4 GetLocalToWorld1(TransformUpdatePacket value)
{
return value.localToWorld1;
}
float4 GetLocalToWorld2(TransformUpdatePacket value)
{
return value.localToWorld2;
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: d73035ddef2bea3469c6784cf7f2e865
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 39c61558833551e4baa6edfa795338be
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
namespace UnityEngine.Rendering
{
[GenerateHLSL]
internal static class SpeedTreeWindShaderDef
{
public const int kMaxWindParamsCount = InstanceDataSystem.k_STMaxWindParamsCount;
};
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,13 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef INSTANCEWINDDATAUPDATEDEFS_CS_HLSL
#define INSTANCEWINDDATAUPDATEDEFS_CS_HLSL
//
// UnityEngine.Rendering.SpeedTreeWindShaderDef: static fields
//
#define MAX_WIND_PARAMS_COUNT (16)
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f267e53cd6dfdee4c820be8c35548ffe
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e2393c2c53c02d24b9313fde572f87af
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,182 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using UnityEngine.Assertions;
using Unity.Collections;
using Unity.Jobs;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Burst;
using Unity.Mathematics;
namespace UnityEngine.Rendering
{
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal struct UpdateLODGroupTransformJob : IJobParallelFor
{
[ReadOnly] public NativeArray<JaggedJobRange> jobRanges;
[ReadOnly] public NativeParallelHashMap<EntityId, GPUInstanceIndex> lodGroupDataHash;
[ReadOnly] public JaggedSpan<EntityId> jaggedLODGroups;
[ReadOnly] public JaggedSpan<float> jaggedWorldSpaceSizes;
[ReadOnly] public JaggedSpan<float3> jaggedWorldSpaceReferencePoints;
[ReadOnly] public bool requiresGPUUpload;
[ReadOnly] public bool supportDitheringCrossFade;
[NativeDisableContainerSafetyRestriction, NoAlias, ReadOnly] public NativeList<LODGroupData> lodGroupDatas;
[NativeDisableContainerSafetyRestriction, NoAlias, WriteOnly] public NativeList<LODGroupCullingData> lodGroupCullingDatas;
public unsafe void Execute(int jobIndex)
{
var jobRange = jobRanges[jobIndex];
NativeArray<EntityId> lodGroupSection = jaggedLODGroups[jobRange.sectionIndex];
NativeArray<float> worldSpaceSizesSection = jaggedWorldSpaceSizes[jobRange.sectionIndex];
NativeArray<float3> worldSpaceReferencePointSection = jaggedWorldSpaceReferencePoints[jobRange.sectionIndex];
for (int indexInRange = 0; indexInRange < jobRange.length; indexInRange++)
{
int localIndex = jobRange.localStart + indexInRange;
EntityId lodGroup = lodGroupSection[localIndex];
if (lodGroupDataHash.TryGetValue(lodGroup, out var lodGroupInstance))
{
float worldSpaceSize = worldSpaceSizesSection[localIndex];
ref LODGroupData lodGroupData = ref lodGroupDatas.ElementAt(lodGroupInstance.index);
ref LODGroupCullingData lodGroupTransformResult = ref lodGroupCullingDatas.ElementAt(lodGroupInstance.index);
lodGroupTransformResult.worldSpaceSize = worldSpaceSize;
lodGroupTransformResult.worldSpaceReferencePoint = worldSpaceReferencePointSection[localIndex];
for (int i = 0; i < lodGroupData.lodCount; ++i)
{
float lodHeight = lodGroupData.screenRelativeTransitionHeights[i];
float lodDist = LODRenderingUtils.CalculateLODDistance(lodHeight, worldSpaceSize);
lodGroupTransformResult.sqrDistances[i] = lodDist * lodDist;
if (supportDitheringCrossFade && !lodGroupTransformResult.percentageFlags[i])
{
float prevLODHeight = i != 0 ? lodGroupData.screenRelativeTransitionHeights[i - 1] : 1.0f;
float transitionHeight = lodHeight + lodGroupData.fadeTransitionWidth[i] * (prevLODHeight - lodHeight);
float transitionDistance = lodDist - LODRenderingUtils.CalculateLODDistance(transitionHeight, worldSpaceSize);
transitionDistance = Mathf.Max(0.0f, transitionDistance);
lodGroupTransformResult.transitionDistances[i] = transitionDistance;
}
else
{
lodGroupTransformResult.transitionDistances[i] = 0f;
}
}
}
}
}
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
internal unsafe struct UpdateLODGroupDataJob : IJobParallelFor
{
[ReadOnly] public NativeArray<JaggedJobRange> jobRanges;
[ReadOnly] public NativeArray<GPUInstanceIndex> lodGroupInstances;
[ReadOnly] public LODGroupUpdateBatch updateBatch;
[ReadOnly] public bool supportDitheringCrossFade;
public NativeArray<LODGroupData> lodGroupsData;
public NativeArray<LODGroupCullingData> lodGroupsCullingData;
[NativeDisableUnsafePtrRestriction] public UnsafeAtomicCounter32 rendererCount;
public void Execute(int jobIndex)
{
JaggedJobRange jobRange = jobRanges[jobIndex];
NativeArray<float3> worldReferencePointSection = updateBatch.worldSpaceReferencePoints[jobRange.sectionIndex];
NativeArray<float> worldSpaceSizeSection = updateBatch.worldSpaceSizes[jobRange.sectionIndex];
NativeArray<InternalLODGroupSettings> lodGroupSettingsSection = updateBatch.lodGroupSettings[jobRange.sectionIndex];
var hasForceLOD = updateBatch.HasAnyComponent(LODGroupComponentMask.ForceLOD);
NativeArray<byte> forceLODMaskSection = hasForceLOD ? updateBatch.forceLODMask[jobRange.sectionIndex] : default;
NativeArray<EmbeddedLODBuffer> lodBufferSection = updateBatch.lodBuffers[jobRange.sectionIndex];
for (int indexInRange = 0; indexInRange < jobRange.length; indexInRange++)
{
int localIndex = jobRange.localStart + indexInRange;
int absoluteIndex = jobRange.absoluteStart + indexInRange;
GPUInstanceIndex lodGroupInstance = lodGroupInstances[absoluteIndex];
float3 worldReferencePoint = worldReferencePointSection[localIndex];
float worldSpaceSize = worldSpaceSizeSection[localIndex];
InternalLODGroupSettings lodGroupSettings = lodGroupSettingsSection[localIndex];
byte forceLODMask = hasForceLOD ? forceLODMaskSection[localIndex] : (byte)0;
ref readonly EmbeddedLODBuffer lodBuffer = ref lodBufferSection.ElementAt(localIndex);
int lodCount = lodBuffer.Length;
LODFadeMode fadeMode = lodGroupSettings.fadeMode;
bool useDitheringCrossFade = fadeMode != LODFadeMode.None && supportDitheringCrossFade;
bool useSpeedTreeCrossFade = fadeMode == LODFadeMode.SpeedTree;
int totalRendererCount = 0;
for (int i = 0; i < lodCount; i++)
{
int lodRendererCount = lodBuffer.GetRendererCount(i);
totalRendererCount += lodRendererCount;
}
ref LODGroupData lodGroupData = ref lodGroupsData.ElementAtRW(lodGroupInstance.index);
ref LODGroupCullingData lodGroupCullingData = ref lodGroupsCullingData.ElementAtRW(lodGroupInstance.index);
lodGroupData.valid = true;
lodGroupData.lodCount = lodCount;
lodGroupData.rendererCount = useDitheringCrossFade ? totalRendererCount : 0;
lodGroupCullingData.worldSpaceSize = worldSpaceSize;
lodGroupCullingData.worldSpaceReferencePoint = worldReferencePoint;
lodGroupCullingData.forceLODMask = forceLODMask;
lodGroupCullingData.lodCount = lodCount;
rendererCount.Add(lodGroupData.rendererCount);
int crossFadeLODBegin = 0;
if (useSpeedTreeCrossFade)
{
int lastLODIndex = lodCount - 1;
bool hasBillboardLOD = lodCount > 0 && lodBuffer.GetRendererCount(lastLODIndex) == 1 && lodGroupSettings.lastLODIsBillboard;
if (lodCount == 0)
crossFadeLODBegin = 0;
else if (hasBillboardLOD)
crossFadeLODBegin = math.max(lodCount, 2) - 2;
else
crossFadeLODBegin = lodCount - 1;
}
for (int i = 0; i < lodCount; ++i)
{
float lodHeight = lodBuffer.GetScreenRelativeTransitionHeight(i);
float lodDist = LODRenderingUtils.CalculateLODDistance(lodHeight, worldSpaceSize);
lodGroupData.screenRelativeTransitionHeights[i] = lodHeight;
lodGroupData.fadeTransitionWidth[i] = 0.0f;
lodGroupCullingData.sqrDistances[i] = lodDist * lodDist;
lodGroupCullingData.percentageFlags[i] = false;
lodGroupCullingData.transitionDistances[i] = 0.0f;
if (useSpeedTreeCrossFade && i < crossFadeLODBegin)
{
lodGroupCullingData.percentageFlags[i] = true;
}
else if (useDitheringCrossFade && i >= crossFadeLODBegin)
{
float fadeTransitionWidth = lodBuffer.GetFadeTransitionWidth(i);
float prevLODHeight = i != 0 ? lodBuffer.GetScreenRelativeTransitionHeight(i - 1) : 1.0f;
float transitionHeight = lodHeight + fadeTransitionWidth * (prevLODHeight - lodHeight);
float transitionDistance = lodDist - LODRenderingUtils.CalculateLODDistance(transitionHeight, worldSpaceSize);
transitionDistance = Mathf.Max(0.0f, transitionDistance);
lodGroupData.fadeTransitionWidth[i] = fadeTransitionWidth;
lodGroupCullingData.transitionDistances[i] = transitionDistance;
}
}
}
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f3545fc7afc41164dbfc733522d08386
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,142 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using UnityEngine.Assertions;
using Unity.Collections;
using Unity.Jobs;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
namespace UnityEngine.Rendering
{
internal unsafe struct LODGroupData
{
public const int k_MaxLODLevelsCount = 8;
public bool valid;
public int lodCount;
public int rendererCount;
public fixed float screenRelativeTransitionHeights[k_MaxLODLevelsCount];
public fixed float fadeTransitionWidth[k_MaxLODLevelsCount];
}
internal unsafe struct LODGroupCullingData
{
public float3 worldSpaceReferencePoint;
public int lodCount;
public fixed float sqrDistances[LODGroupData.k_MaxLODLevelsCount]; // we use square distance to get rid of a sqrt in gpu culling..
public fixed float transitionDistances[LODGroupData.k_MaxLODLevelsCount]; // todo - make this a separate data struct (CPUOnly, as we do not support dithering on GPU..)
public float worldSpaceSize;// SpeedTree crossfade.
public fixed bool percentageFlags[LODGroupData.k_MaxLODLevelsCount];// SpeedTree crossfade.
public byte forceLODMask;
}
//@ Merge this class into InstanceDataSystem there is no need to have two separate classes for this.
internal class LODGroupDataSystem : IDisposable
{
private NativeList<LODGroupData> m_LODGroupData;
private NativeParallelHashMap<EntityId, GPUInstanceIndex> m_LODGroupDataHash;
private NativeList<LODGroupCullingData> m_LODGroupCullingData;
private NativeList<GPUInstanceIndex> m_FreeLODGroupDataHandles;
private int m_CrossfadedRendererCount;
private bool m_SupportDitheringCrossFade;
public NativeParallelHashMap<EntityId, GPUInstanceIndex> lodGroupDataHash => m_LODGroupDataHash;
public NativeList<LODGroupCullingData> lodGroupCullingData => m_LODGroupCullingData;
public int crossfadedRendererCount => m_CrossfadedRendererCount;
public int activeLodGroupCount => m_LODGroupData.Length;
public LODGroupDataSystem(bool supportDitheringCrossFade)
{
m_LODGroupData = new NativeList<LODGroupData>(Allocator.Persistent);
m_LODGroupDataHash = new NativeParallelHashMap<EntityId, GPUInstanceIndex>(64, Allocator.Persistent);
m_LODGroupCullingData = new NativeList<LODGroupCullingData>(Allocator.Persistent);
m_FreeLODGroupDataHandles = new NativeList<GPUInstanceIndex>(Allocator.Persistent);
m_SupportDitheringCrossFade = supportDitheringCrossFade;
}
public void Dispose()
{
m_LODGroupData.Dispose();
m_LODGroupDataHash.Dispose();
m_LODGroupCullingData.Dispose();
m_FreeLODGroupDataHandles.Dispose();
}
public NativeArray<GPUInstanceIndex> GetOrAllocateInstances(in LODGroupUpdateBatch updateBatch, Allocator allocator)
{
var instances = new NativeArray<GPUInstanceIndex>(updateBatch.TotalLength, allocator, NativeArrayOptions.UninitializedMemory);
int previousRendererCount = LODGroupDataSystemBurst.GetOrAllocateLODGroupDataInstances(updateBatch.instanceIDs,
ref m_LODGroupData,
ref m_LODGroupCullingData,
ref m_LODGroupDataHash,
ref m_FreeLODGroupDataHandles,
ref instances);
m_CrossfadedRendererCount -= previousRendererCount;
Assert.IsTrue(m_CrossfadedRendererCount >= 0);
return instances;
}
public unsafe void UpdateLODGroupData(in LODGroupUpdateBatch updateBatch, NativeArray<GPUInstanceIndex> instances)
{
var jobRanges = JaggedJobRange.FromSpanWithRelaxedBatchSize(updateBatch.instanceIDs, 256, Allocator.TempJob);
int rendererCount = 0;
new UpdateLODGroupDataJob
{
jobRanges = jobRanges.AsArray(),
lodGroupInstances = instances,
updateBatch = updateBatch,
supportDitheringCrossFade = m_SupportDitheringCrossFade,
lodGroupsData = m_LODGroupData.AsArray(),
lodGroupsCullingData = m_LODGroupCullingData.AsArray(),
rendererCount = new UnsafeAtomicCounter32(&rendererCount),
}
.RunParallel(jobRanges);
m_CrossfadedRendererCount += rendererCount;
jobRanges.Dispose();
}
public unsafe void UpdateLODGroupTransforms(in LODGroupUpdateBatch updateBatch)
{
var jobRanges = JaggedJobRange.FromSpanWithRelaxedBatchSize(updateBatch.instanceIDs, 256, Allocator.TempJob);
new UpdateLODGroupTransformJob()
{
jobRanges = jobRanges.AsArray(),
lodGroupDataHash = m_LODGroupDataHash,
jaggedLODGroups = updateBatch.instanceIDs,
jaggedWorldSpaceReferencePoints = updateBatch.worldSpaceReferencePoints,
jaggedWorldSpaceSizes = updateBatch.worldSpaceSizes,
lodGroupDatas = m_LODGroupData,
lodGroupCullingDatas = m_LODGroupCullingData,
supportDitheringCrossFade = m_SupportDitheringCrossFade,
}
.RunParallel(jobRanges);
jobRanges.Dispose();
}
public void FreeLODGroups(NativeArray<EntityId> destroyedLODGroupsID)
{
if (destroyedLODGroupsID.Length == 0)
return;
int removedRendererCount = LODGroupDataSystemBurst.FreeLODGroupData(destroyedLODGroupsID, ref m_LODGroupData, ref m_LODGroupDataHash, ref m_FreeLODGroupDataHandles);
m_CrossfadedRendererCount -= removedRendererCount;
Assert.IsTrue(m_CrossfadedRendererCount >= 0);
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e4efe0c149e2f2b429a927ed9df0d8b1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,90 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System.Runtime.CompilerServices;
using Unity.Collections;
using Unity.Burst;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
[BurstCompile]
internal static class LODGroupDataSystemBurst
{
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
public static int GetOrAllocateLODGroupDataInstances(in JaggedSpan<EntityId> jaggedLODGroups,
ref NativeList<LODGroupData> lodGroupsData,
ref NativeList<LODGroupCullingData> lodGroupCullingData,
ref NativeParallelHashMap<EntityId, GPUInstanceIndex> lodGroupDataHash,
ref NativeList<GPUInstanceIndex> freeLODGroupDataHandles,
ref NativeArray<GPUInstanceIndex> lodGroupInstances)
{
int freeHandlesCount = freeLODGroupDataHandles.Length;
int lodDataLength = lodGroupsData.Length;
int absoluteIndex = 0;
int previousRendererCount = 0;
for (int sectionIndex = 0; sectionIndex < jaggedLODGroups.sectionCount; ++sectionIndex)
{
NativeArray<EntityId> lodGroups = jaggedLODGroups[sectionIndex];
for (int localIndex = 0; localIndex < lodGroups.Length; localIndex++, ++absoluteIndex)
{
EntityId lodGroup = lodGroups[localIndex];
if (!lodGroupDataHash.TryGetValue(lodGroup, out var lodGroupInstance))
{
if (freeHandlesCount == 0)
lodGroupInstance = GPUInstanceIndex.Create(lodDataLength++);
else
lodGroupInstance = freeLODGroupDataHandles[--freeHandlesCount];
lodGroupDataHash.TryAdd(lodGroup, lodGroupInstance);
}
else
{
previousRendererCount += lodGroupsData.ElementAt(lodGroupInstance.index).rendererCount;
}
lodGroupInstances[absoluteIndex] = lodGroupInstance;
}
}
freeLODGroupDataHandles.ResizeUninitialized(freeHandlesCount);
lodGroupsData.ResizeUninitialized(lodDataLength);
lodGroupCullingData.ResizeUninitialized(lodDataLength);
return previousRendererCount;
}
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
public static int FreeLODGroupData(in NativeArray<EntityId> destroyedLODGroups,
ref NativeList<LODGroupData> lodGroupsData,
ref NativeParallelHashMap<EntityId, GPUInstanceIndex> lodGroupDataHash,
ref NativeList<GPUInstanceIndex> freeLODGroupDataHandles)
{
int removedRendererCount = 0;
foreach (EntityId lodGroup in destroyedLODGroups)
{
if (lodGroupDataHash.TryGetValue(lodGroup, out var lodGroupInstance))
{
Assert.IsTrue(lodGroupInstance.valid);
lodGroupDataHash.Remove(lodGroup);
freeLODGroupDataHandles.Add(lodGroupInstance);
ref LODGroupData lodGroupData = ref lodGroupsData.ElementAt(lodGroupInstance.index);
Assert.IsTrue(lodGroupData.valid);
removedRendererCount += lodGroupData.rendererCount;
lodGroupData.valid = false;
}
}
return removedRendererCount;
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a44ea003ea382364d9e18b103d0503cf
@@ -0,0 +1,563 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Mathematics;
using UnityEngine.Assertions;
#if UNITY_EDITOR
using UnityEditor.SceneManagement;
#endif
namespace UnityEngine.Rendering
{
internal struct RenderWorld : IDisposable
{
public static readonly EntityId DefaultMesh = EntityId.None;
public static readonly ushort DefaultSubMeshStartIndex = 0;
public static readonly ushort DefaultStaticBatchSubMeshCount = 0;
public static readonly AABB DefaultLocalBounds = default;
public static readonly InternalMeshRendererSettings DefaultRendererSettings = InternalMeshRendererSettings.Default;
public static readonly InternalMeshLodRendererSettings DefaultMeshLodRendererSettings = InternalMeshLodRendererSettings.Default;
public static readonly int DefaultParentLODGroupID = 0;
public static readonly byte DefaultLODMask = 0;
public static readonly short DefaultLightmapIndex = LightmapUtils.LightmapIndexNull;
public static readonly int DefaultRendererPriority = 0;
#if UNITY_EDITOR
public static readonly ulong DefaultSceneCullingMask = SceneCullingMasks.DefaultSceneCullingMask;
#endif
private const int InvalidIndex = -1;
// Keep these as NativeReference so that they can be modified from Burst jobs operating on the RenderWorld.
// Also keep the length separately because the component NativeArrays length is atually the capacity.
// Arrays growth/realloc doesn't follow a double on realloc policy, it is manually controlled.
private NativeReference<int> m_InstancesCount;
private NativeReference<int> m_TotalTreeCount;
private NativeList<int> m_HandleToIndex;
private NativeArray<InstanceHandle> m_IndexToHandle;
private NativeArray<EntityId> m_InstanceIDs;
private NativeArray<EmbeddedArray32<EntityId>> m_MaterialIDArrays;
private NativeArray<EntityId> m_MeshIDs;
private NativeArray<InternalMeshLodRendererSettings> m_MeshLodRendererSettings;
private NativeArray<ushort> m_SubMeshStartIndices;
private NativeArray<ushort> m_StaticBatchSubMeshCounts;
private NativeArray<AABB> m_LocalAABBs;
private NativeArray<InternalMeshRendererSettings> m_RendererSettings;
private NativeArray<short> m_LightmapIndices;
private NativeArray<GPUInstanceIndex> m_LODGroupIndices;
private NativeArray<byte> m_LODMasks;
private NativeArray<int> m_RendererPriorities;
private NativeArray<InstanceGPUHandle> m_GPUHandles;
private ParallelBitArray m_LocalToWorldIsFlippedBits;
private NativeArray<AABB> m_WorldAABBs;
private NativeArray<int> m_TetrahedronCacheIndices;
private ParallelBitArray m_MovedInCurrentFrameBits;
private ParallelBitArray m_MovedInPreviousFrameBits;
private ParallelBitArray m_VisibleInPreviousFrameBits;
private ParallelBitArray m_RenderingEnabled;
private EditorOnly m_EditorOnly;
private NativeParallelHashMap<EntityId, UnsafePerCameraInstanceData> m_PerCameraInstanceDataMap;
public NativeArray<InstanceHandle> indexToHandle => m_IndexToHandle.GetSubArray(0, instanceCount);
public NativeArray<EntityId> instanceIDs => m_InstanceIDs.GetSubArray(0, instanceCount);
public NativeArray<EmbeddedArray32<EntityId>> materialIDArrays => m_MaterialIDArrays.GetSubArray(0, instanceCount);
public NativeArray<EntityId> meshIDs => m_MeshIDs.GetSubArray(0, instanceCount);
public NativeArray<InternalMeshLodRendererSettings> meshLodRendererSettings => m_MeshLodRendererSettings.GetSubArray(0, instanceCount);
public NativeArray<ushort> subMeshStartIndices => m_SubMeshStartIndices.GetSubArray(0, instanceCount);
public NativeArray<ushort> staticBatchSubMeshCounts => m_StaticBatchSubMeshCounts.GetSubArray(0, instanceCount);
public NativeArray<AABB> localAABBs => m_LocalAABBs.GetSubArray(0, instanceCount);
public NativeArray<InternalMeshRendererSettings> rendererSettings => m_RendererSettings.GetSubArray(0, instanceCount);
public NativeArray<short> lightmapIndices => m_LightmapIndices.GetSubArray(0, instanceCount);
public NativeArray<GPUInstanceIndex> lodGroupIndices => m_LODGroupIndices.GetSubArray(0, instanceCount);
public NativeArray<byte> lodMasks => m_LODMasks.GetSubArray(0, instanceCount);
public NativeArray<int> rendererPriorities => m_RendererPriorities.GetSubArray(0, instanceCount);
public NativeArray<InstanceGPUHandle> gpuHandles => m_GPUHandles.GetSubArray(0, instanceCount);
public ParallelBitArray localToWorldIsFlippedBits => m_LocalToWorldIsFlippedBits.GetSubArray(instanceCount);
public NativeArray<AABB> worldAABBs => m_WorldAABBs.GetSubArray(0, instanceCount);
public NativeArray<int> tetrahedronCacheIndices => m_TetrahedronCacheIndices.GetSubArray(0, instanceCount);
public ParallelBitArray movedInCurrentFrameBits => m_MovedInCurrentFrameBits.GetSubArray(instanceCount);
public ParallelBitArray movedInPreviousFrameBits => m_MovedInPreviousFrameBits.GetSubArray(instanceCount);
public ParallelBitArray visibleInPreviousFrameBits => m_VisibleInPreviousFrameBits.GetSubArray(instanceCount);
public ParallelBitArray renderingEnabled => m_RenderingEnabled.GetSubArray(instanceCount);
#if UNITY_EDITOR
public NativeArray<ulong> sceneCullingMasks => m_EditorOnly.sceneCullingMasks.GetSubArray(0, instanceCount);
#endif
public int instanceCount { get => m_InstancesCount.Value; private set => m_InstancesCount.Value = value; }
public int handleCount => m_HandleToIndex.Length;
public int totalTreeCount => m_TotalTreeCount.Value;
public int cameraCount => m_PerCameraInstanceDataMap.Count();
public unsafe UnsafeAtomicCounter32 atomicTotalTreeCount => new UnsafeAtomicCounter32(m_TotalTreeCount.GetUnsafePtr());
public void Initialize(int initCapacity)
{
m_InstancesCount = new NativeReference<int>(0, Allocator.Persistent);
m_TotalTreeCount = new NativeReference<int>(0, Allocator.Persistent);
m_HandleToIndex = new NativeList<int>(Allocator.Persistent);
m_IndexToHandle = new NativeArray<InstanceHandle>(initCapacity, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
m_IndexToHandle.FillArray(InstanceHandle.Invalid);
m_InstanceIDs = new NativeArray<EntityId>(initCapacity, Allocator.Persistent);
m_MaterialIDArrays = new NativeArray<EmbeddedArray32<EntityId>>(initCapacity, Allocator.Persistent);
m_MeshIDs = new NativeArray<EntityId>(initCapacity, Allocator.Persistent);
m_MeshLodRendererSettings = new NativeArray<InternalMeshLodRendererSettings>(initCapacity, Allocator.Persistent);
m_SubMeshStartIndices = new NativeArray<ushort>(initCapacity, Allocator.Persistent);
m_StaticBatchSubMeshCounts = new NativeArray<ushort>(initCapacity, Allocator.Persistent);
m_LocalAABBs = new NativeArray<AABB>(initCapacity, Allocator.Persistent);
m_RendererSettings = new NativeArray<InternalMeshRendererSettings>(initCapacity, Allocator.Persistent);
m_LightmapIndices = new NativeArray<short>(initCapacity, Allocator.Persistent);
m_LODGroupIndices = new NativeArray<GPUInstanceIndex>(initCapacity, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
m_LODGroupIndices.FillArray(GPUInstanceIndex.Invalid);
m_LODMasks = new NativeArray<byte>(initCapacity, Allocator.Persistent);
m_RendererPriorities = new NativeArray<int>(initCapacity, Allocator.Persistent);
m_GPUHandles = new NativeArray<InstanceGPUHandle>(initCapacity, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
m_GPUHandles.FillArray(InstanceGPUHandle.Invalid);
m_LocalToWorldIsFlippedBits = new ParallelBitArray(initCapacity, Allocator.Persistent);
m_WorldAABBs = new NativeArray<AABB>(initCapacity, Allocator.Persistent);
m_TetrahedronCacheIndices = new NativeArray<int>(initCapacity, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
m_TetrahedronCacheIndices.FillArray(InvalidIndex);
m_MovedInCurrentFrameBits = new ParallelBitArray(initCapacity, Allocator.Persistent);
m_MovedInPreviousFrameBits = new ParallelBitArray(initCapacity, Allocator.Persistent);
m_VisibleInPreviousFrameBits = new ParallelBitArray(initCapacity, Allocator.Persistent);
m_RenderingEnabled = new ParallelBitArray(initCapacity, Allocator.Persistent);
m_EditorOnly.Initialize(initCapacity);
m_PerCameraInstanceDataMap = new NativeParallelHashMap<EntityId, UnsafePerCameraInstanceData>(1, Allocator.Persistent);
}
public void Dispose()
{
int aliveInstanceCount = m_InstancesCount.Value;
m_InstancesCount.Dispose();
m_TotalTreeCount.Dispose();
m_HandleToIndex.Dispose();
m_IndexToHandle.Dispose();
m_InstanceIDs.Dispose();
for (int i = 0; i < aliveInstanceCount; i++)
m_MaterialIDArrays[i].Dispose();
m_MaterialIDArrays.Dispose();
m_MeshIDs.Dispose();
m_MeshLodRendererSettings.Dispose();
m_SubMeshStartIndices.Dispose();
m_StaticBatchSubMeshCounts.Dispose();
m_LocalAABBs.Dispose();
m_RendererSettings.Dispose();
m_LightmapIndices.Dispose();
m_LODGroupIndices.Dispose();
m_LODMasks.Dispose();
m_RendererPriorities.Dispose();
m_GPUHandles.Dispose();
m_LocalToWorldIsFlippedBits.Dispose();
m_WorldAABBs.Dispose();
m_TetrahedronCacheIndices.Dispose();
m_MovedInCurrentFrameBits.Dispose();
m_MovedInPreviousFrameBits.Dispose();
m_VisibleInPreviousFrameBits.Dispose();
m_RenderingEnabled.Dispose();
m_EditorOnly.Dispose();
foreach (var kv in m_PerCameraInstanceDataMap)
kv.Value.Dispose();
m_PerCameraInstanceDataMap.Dispose();
}
private void Grow(int newCapacity)
{
int instancesCapacity = GetInstanceCapacity();
Assert.IsTrue(newCapacity > instancesCapacity);
m_IndexToHandle.ResizeArray(newCapacity);
m_IndexToHandle.FillArray(InstanceHandle.Invalid, instancesCapacity);
m_InstanceIDs.ResizeArray(newCapacity);
m_MaterialIDArrays.ResizeArray(newCapacity);
m_MaterialIDArrays.FillArray(default, instancesCapacity);
m_MeshIDs.ResizeArray(newCapacity);
m_MeshLodRendererSettings.ResizeArray(newCapacity);
m_SubMeshStartIndices.ResizeArray(newCapacity);
m_StaticBatchSubMeshCounts.ResizeArray(newCapacity);
m_LocalAABBs.ResizeArray(newCapacity);
m_RendererSettings.ResizeArray(newCapacity);
m_LightmapIndices.ResizeArray(newCapacity);
m_LODGroupIndices.ResizeArray(newCapacity);
m_LODGroupIndices.FillArray(GPUInstanceIndex.Invalid, instancesCapacity);
m_LODMasks.ResizeArray(newCapacity);
m_LODMasks.FillArray(DefaultLODMask, instancesCapacity);
m_RendererPriorities.ResizeArray(newCapacity);
m_GPUHandles.ResizeArray(newCapacity);
m_GPUHandles.FillArray(InstanceGPUHandle.Invalid, instancesCapacity);
m_LocalToWorldIsFlippedBits.Resize(newCapacity);
m_WorldAABBs.ResizeArray(newCapacity);
m_TetrahedronCacheIndices.ResizeArray(newCapacity);
m_TetrahedronCacheIndices.FillArray(InvalidIndex, instancesCapacity);
m_MovedInCurrentFrameBits.Resize(newCapacity);
m_MovedInPreviousFrameBits.Resize(newCapacity);
m_VisibleInPreviousFrameBits.Resize(newCapacity);
m_RenderingEnabled.Resize(newCapacity);
m_EditorOnly.Grow(newCapacity);
foreach (var kv in m_PerCameraInstanceDataMap)
kv.Value.Resize(newCapacity);
}
private int AddUninitialized(InstanceHandle instance)
{
if (instance.index >= m_HandleToIndex.Length)
{
int prevLength = m_HandleToIndex.Length;
m_HandleToIndex.ResizeUninitialized(instance.index + 1);
for (int i = prevLength; i < m_HandleToIndex.Length - 1; ++i)
m_HandleToIndex[i] = InvalidIndex;
}
m_HandleToIndex[instance.index] = instanceCount;
m_IndexToHandle[instanceCount] = instance;
return instanceCount++;
}
public int HandleToIndex(InstanceHandle instance)
{
Assert.IsTrue(IsValidInstance(instance));
return m_HandleToIndex[instance.index];
}
public InstanceHandle IndexToHanle(int index)
{
Assert.IsTrue(IsValidIndex(index));
return m_IndexToHandle[index];
}
public bool IsValidInstance(InstanceHandle instance)
{
if (instance.isValid && instance.index < m_HandleToIndex.Length)
{
int index = m_HandleToIndex[instance.index];
return index >= 0 && index < instanceCount && m_IndexToHandle[index].Equals(instance);
}
return false;
}
public bool IsValidIndex(int index)
{
if (index >= 0 && index < instanceCount)
{
InstanceHandle instance = m_IndexToHandle[index];
return index == m_HandleToIndex[instance.index];
}
return false;
}
public bool IsFreeInstanceHandle(InstanceHandle instance)
{
return instance.isValid && (instance.index >= m_HandleToIndex.Length || m_HandleToIndex[instance.index] == InvalidIndex);
}
public int GetInstanceCapacity()
{
return m_IndexToHandle.Length;
}
public int GetFreeCapacity()
{
return GetInstanceCapacity() - instanceCount;
}
public void EnsureFreeCapacity(int instancesCount)
{
if (instancesCount == 0)
return;
int freeInstancesCount = GetFreeCapacity();
int needInstances = instancesCount - freeInstancesCount;
if (needInstances > 0)
Grow(GetInstanceCapacity() + needInstances + 256);
}
public int AddInstanceNoGrow(InstanceHandle instance)
{
Assert.IsTrue(instance.isValid);
Assert.IsTrue(IsFreeInstanceHandle(instance));
Assert.IsTrue(GetFreeCapacity() > 0);
int instanceIndex = AddUninitialized(instance);
InitializeInstance(instanceIndex);
return instanceIndex;
}
public void RemoveInstance(InstanceHandle instance)
{
Assert.IsTrue(IsValidInstance(instance));
int index = HandleToIndex(instance);
int lastIndex = instanceCount - 1;
if (m_RendererSettings[index].HasTree)
{
Assert.IsTrue(m_TotalTreeCount.Value > 0);
--m_TotalTreeCount.Value;
}
m_IndexToHandle[index] = m_IndexToHandle[lastIndex];
m_InstanceIDs[index] = m_InstanceIDs[lastIndex];
m_MaterialIDArrays[index].Dispose();
m_MaterialIDArrays[index] = m_MaterialIDArrays[lastIndex];
m_MaterialIDArrays[lastIndex] = default;
m_MeshIDs[index] = m_MeshIDs[lastIndex];
m_MeshLodRendererSettings[index] = m_MeshLodRendererSettings[lastIndex];
m_SubMeshStartIndices[index] = m_SubMeshStartIndices[lastIndex];
m_StaticBatchSubMeshCounts[index] = m_StaticBatchSubMeshCounts[lastIndex];
m_LocalAABBs[index] = m_LocalAABBs[lastIndex];
m_RendererSettings[index] = m_RendererSettings[lastIndex];
m_LightmapIndices[index] = m_LightmapIndices[lastIndex];
m_LODGroupIndices[index] = m_LODGroupIndices[lastIndex];
m_LODMasks[index] = m_LODMasks[lastIndex];
m_RendererPriorities[index] = m_RendererPriorities[lastIndex];
m_GPUHandles[index] = m_GPUHandles[lastIndex];
m_LocalToWorldIsFlippedBits.Set(index, m_LocalToWorldIsFlippedBits.Get(lastIndex));
m_WorldAABBs[index] = m_WorldAABBs[lastIndex];
m_TetrahedronCacheIndices[index] = m_TetrahedronCacheIndices[lastIndex];
m_MovedInCurrentFrameBits.Set(index, m_MovedInCurrentFrameBits.Get(lastIndex));
m_MovedInPreviousFrameBits.Set(index, m_MovedInPreviousFrameBits.Get(lastIndex));
m_VisibleInPreviousFrameBits.Set(index, m_VisibleInPreviousFrameBits.Get(lastIndex));
m_RenderingEnabled.Set(index, m_RenderingEnabled.Get(lastIndex));
m_EditorOnly.Remove(index, lastIndex);
foreach (var kv in m_PerCameraInstanceDataMap)
kv.Value.Remove(index, lastIndex);
m_HandleToIndex[m_IndexToHandle[lastIndex].index] = index;
m_HandleToIndex[instance.index] = InvalidIndex;
instanceCount -= 1;
}
public void ResetInstance(int instanceIndex)
{
m_MaterialIDArrays[instanceIndex].Dispose();
m_MaterialIDArrays[instanceIndex] = default;
m_MeshIDs[instanceIndex] = DefaultMesh;
m_MeshLodRendererSettings[instanceIndex] = DefaultMeshLodRendererSettings;
m_SubMeshStartIndices[instanceIndex] = DefaultSubMeshStartIndex;
m_StaticBatchSubMeshCounts[instanceIndex] = DefaultStaticBatchSubMeshCount;
m_LocalAABBs[instanceIndex] = DefaultLocalBounds;
m_RendererSettings[instanceIndex] = DefaultRendererSettings;
m_LightmapIndices[instanceIndex] = DefaultLightmapIndex;
m_LODGroupIndices[instanceIndex] = GPUInstanceIndex.Invalid;
m_LODMasks[instanceIndex] = DefaultLODMask;
m_RendererPriorities[instanceIndex] = DefaultRendererPriority;
m_LocalToWorldIsFlippedBits.Set(instanceIndex, false);
m_WorldAABBs[instanceIndex] = default;
m_TetrahedronCacheIndices[instanceIndex] = InvalidIndex;
m_RenderingEnabled.Set(instanceIndex, true);
m_EditorOnly.SetDefault(instanceIndex);
foreach (var kv in m_PerCameraInstanceDataMap)
{
kv.Value.meshLods[instanceIndex] = PerCameraInstanceData.InvalidByteData;
kv.Value.crossFades[instanceIndex] = PerCameraInstanceData.InvalidByteData;
}
}
private void InitializeInstance(int instanceIndex)
{
ResetInstance(instanceIndex);
m_InstanceIDs[instanceIndex] = EntityId.None;
m_GPUHandles[instanceIndex] = InstanceGPUHandle.Invalid;
m_MovedInCurrentFrameBits.Set(instanceIndex, false);
m_MovedInPreviousFrameBits.Set(instanceIndex, false);
m_VisibleInPreviousFrameBits.Set(instanceIndex, false);
}
public void AddCameras(NativeArray<EntityId> cameraIDs)
{
foreach (var cameraID in cameraIDs)
{
if (m_PerCameraInstanceDataMap.ContainsKey(cameraID))
continue;
m_PerCameraInstanceDataMap.Add(cameraID, new UnsafePerCameraInstanceData(GetInstanceCapacity(), Allocator.Persistent));
}
}
public void RemoveCameras(NativeArray<EntityId> cameraIDs)
{
foreach (var cameraID in cameraIDs)
{
if (!m_PerCameraInstanceDataMap.ContainsKey(cameraID))
continue;
m_PerCameraInstanceDataMap[cameraID].Dispose();
m_PerCameraInstanceDataMap.Remove(cameraID);
}
}
public bool TryGetPerCameraInstanceData(EntityId cameraID, out PerCameraInstanceData perCameraInstanceData)
{
perCameraInstanceData = default;
if (!m_PerCameraInstanceDataMap.TryGetValue(cameraID, out UnsafePerCameraInstanceData unsafePerCameraData))
return false;
perCameraInstanceData = unsafePerCameraData.ToPerCameraInstanceData(instanceCount);
return true;
}
public PerCameraInstanceData GetPerCameraInstanceData(EntityId cameraID)
{
return m_PerCameraInstanceDataMap[cameraID].ToPerCameraInstanceData(instanceCount);
}
public struct PerCameraInstanceData
{
public const int InvalidByteData = 0xff;
public NativeArray<byte> meshLods;
public NativeArray<byte> crossFades;
public bool IsCreated => meshLods.IsCreated && crossFades.IsCreated;
public PerCameraInstanceData(int length, Allocator allocator)
{
meshLods = new NativeArray<byte>(length, allocator);
crossFades = new NativeArray<byte>(length, allocator);
}
public JobHandle Dispose(JobHandle jobHandle)
{
return JobHandle.CombineDependencies(meshLods.Dispose(jobHandle), crossFades.Dispose(jobHandle));
}
}
struct UnsafePerCameraInstanceData : IDisposable
{
public UnsafeList<byte> meshLods;
public UnsafeList<byte> crossFades;
public UnsafePerCameraInstanceData(int initCapacity, Allocator allocator)
{
meshLods = new UnsafeList<byte>(initCapacity, allocator, NativeArrayOptions.UninitializedMemory);
meshLods.AddReplicate(PerCameraInstanceData.InvalidByteData, initCapacity);
crossFades = new UnsafeList<byte>(initCapacity, allocator, NativeArrayOptions.UninitializedMemory);
crossFades.AddReplicate(PerCameraInstanceData.InvalidByteData, initCapacity);
}
public void Dispose()
{
meshLods.Dispose();
crossFades.Dispose();
}
public void Remove(int index, int lastIndex)
{
meshLods[index] = meshLods[lastIndex];
crossFades[index] = crossFades[lastIndex];
}
public void Resize(int newCapacity)
{
meshLods.Resize(newCapacity);
crossFades.Resize(newCapacity);
}
public PerCameraInstanceData ToPerCameraInstanceData(int instanceCount)
{
return new PerCameraInstanceData
{
meshLods = meshLods.AsNativeArray().GetSubArray(0, instanceCount),
crossFades = crossFades.AsNativeArray().GetSubArray(0, instanceCount)
};
}
}
struct EditorOnly
{
#if UNITY_EDITOR
public NativeArray<ulong> sceneCullingMasks;
public void Initialize(int initCapacity)
{
sceneCullingMasks = new NativeArray<ulong>(initCapacity, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
sceneCullingMasks.FillArray(ulong.MaxValue);
}
public void Dispose()
{
sceneCullingMasks.Dispose();
}
public void Grow(int newCapacity)
{
sceneCullingMasks.ResizeArray(newCapacity);
}
public void Remove(int index, int lastIndex)
{
sceneCullingMasks[index] = sceneCullingMasks[lastIndex];
}
public void SetDefault(int index)
{
sceneCullingMasks[index] = DefaultSceneCullingMask;
}
#else
public void Initialize(int initCapacity) { }
public void Dispose() { }
public void Grow(int newCapacity) { }
public void Remove(int index, int lastIndex) { }
public void SetDefault(int index) { }
#endif
}
}
internal struct PackedMatrix
{
/* mat4x3 packed like this:
p1.x, p1.w, p2.z, p3.y,
p1.y, p2.x, p2.w, p3.z,
p1.z, p2.y, p3.x, p3.w,
0.0, 0.0, 0.0, 1.0
*/
public float4 packed0;
public float4 packed1;
public float4 packed2;
public static PackedMatrix FromMatrix4x4(in Matrix4x4 m)
{
return new PackedMatrix
{
packed0 = new float4(m.m00, m.m10, m.m20, m.m01),
packed1 = new float4(m.m11, m.m21, m.m02, m.m12),
packed2 = new float4(m.m22, m.m03, m.m13, m.m23)
};
}
public static PackedMatrix FromFloat4x4(in float4x4 m)
{
return new PackedMatrix
{
packed0 = new float4(m.c0.x, m.c0.y, m.c0.z, m.c1.x),
packed1 = new float4(m.c1.y, m.c1.z, m.c2.x, m.c2.y),
packed2 = new float4(m.c2.z, m.c3.x, m.c3.y, m.c3.z)
};
}
public override string ToString()
{
return $"[{packed0}, {packed1}, {packed2}]";
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3d4a5f192498160488916c4e31a73a29
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 99ecf45f0f3a0df48a6c4e7128c4e5cb
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: df6b79ad3423a5745916fceb76fdefbf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,30 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using Unity.Collections;
using Unity.Burst;
namespace UnityEngine.Rendering
{
[BurstCompile]
internal static class InstanceCullerBurst
{
[BurstCompile(DisableSafetyChecks = true, OptimizeFor = OptimizeFor.Performance)]
public static unsafe void SetupCullingJobInput(float lodBias,
float meshLodThreshold,
BatchCullingContext* context,
ReceiverPlanes* receiverPlanes,
ReceiverSphereCuller* receiverSphereCuller,
FrustumPlaneCuller* frustumPlaneCuller,
float* screenRelativeMetric,
float* meshLodConstant)
{
*receiverPlanes = ReceiverPlanes.Create(*context, Allocator.TempJob);
*receiverSphereCuller = ReceiverSphereCuller.Create(*context, Allocator.TempJob);
*frustumPlaneCuller = FrustumPlaneCuller.Create(*context, receiverPlanes->planes.AsArray(), *receiverSphereCuller, Allocator.TempJob);
*screenRelativeMetric = LODRenderingUtils.CalculateScreenRelativeMetricNoBias(context->lodParameters);
*meshLodConstant = LODRenderingUtils.CalculateMeshLodConstant(context->lodParameters, *screenRelativeMetric, meshLodThreshold);
*screenRelativeMetric /= lodBias;
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 86dce443230a0694d8fedef47e43b707
@@ -0,0 +1,827 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using UnityEngine.Assertions;
using Unity.Burst;
using Unity.Burst.CompilerServices;
using Unity.Mathematics;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Jobs;
using Unity.Jobs.LowLevel.Unsafe;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering.RenderGraphModule;
namespace UnityEngine.Rendering
{
internal struct OccluderDerivedData
{
/// <summary></summary>
public Matrix4x4 viewProjMatrix; // from view-centered world space
/// <summary></summary>
public Vector4 viewOriginWorldSpace;
/// <summary></summary>
public Vector4 radialDirWorldSpace;
/// <summary></summary>
public Vector4 facingDirWorldSpace;
public static OccluderDerivedData FromParameters(in OccluderSubviewUpdate occluderSubviewUpdate)
{
var origin = occluderSubviewUpdate.viewOffsetWorldSpace + (Vector3)occluderSubviewUpdate.invViewMatrix.GetColumn(3); // view origin in world space
var xViewVec = (Vector3)occluderSubviewUpdate.invViewMatrix.GetColumn(0); // positive x axis in world space
var yViewVec = (Vector3)occluderSubviewUpdate.invViewMatrix.GetColumn(1); // positive y axis in world space
var towardsVec = (Vector3)occluderSubviewUpdate.invViewMatrix.GetColumn(2); // positive z axis in world space
var viewMatrixNoTranslation = occluderSubviewUpdate.viewMatrix;
viewMatrixNoTranslation.SetColumn(3, new Vector4(0.0f, 0.0f, 0.0f, 1.0f));
return new OccluderDerivedData
{
viewOriginWorldSpace = origin,
facingDirWorldSpace = towardsVec.normalized,
radialDirWorldSpace = (xViewVec + yViewVec).normalized,
viewProjMatrix = occluderSubviewUpdate.gpuProjMatrix * viewMatrixNoTranslation,
};
}
}
internal struct OccluderHandles
{
public TextureHandle occluderDepthPyramid;
public BufferHandle occlusionDebugOverlay;
public bool IsValid()
{
return occluderDepthPyramid.IsValid();
}
public void UseForOcclusionTest(IBaseRenderGraphBuilder builder)
{
builder.UseTexture(occluderDepthPyramid, AccessFlags.Read);
if (occlusionDebugOverlay.IsValid())
builder.UseBuffer(occlusionDebugOverlay, AccessFlags.ReadWrite);
}
public void UseForOccluderUpdate(IBaseRenderGraphBuilder builder)
{
builder.UseTexture(occluderDepthPyramid, AccessFlags.ReadWrite);
if (occlusionDebugOverlay.IsValid())
builder.UseBuffer(occlusionDebugOverlay, AccessFlags.ReadWrite);
}
}
[GenerateHLSL(needAccessors = false)]
internal enum InstanceOcclusionTestDebugCounter
{
InstancesOccluded,
InstancesNotOccluded,
PrimitivesOccluded,
PrimitivesNotOccluded,
Count,
}
[GenerateHLSL(needAccessors = false)]
internal struct IndirectInstanceInfo
{
public int drawOffsetAndSplitMask; // [31:8]=draw_offset, [7:0]=split_mask
public int instanceIndexAndCrossFade; // DOTS instance index
}
[GenerateHLSL(needAccessors = false)]
internal struct IndirectDrawInfo
{
public uint indexCount;
public uint firstIndex;
public uint baseVertex;
public uint firstInstanceGlobalIndex;
public uint maxInstanceCountAndTopology; // [31:3]=max_instance_count, [2:0]=topology
}
internal struct IndirectBufferAllocInfo
{
public int drawAllocIndex;
public int drawCount;
public int instanceAllocIndex;
public int instanceCount;
public bool IsEmpty()
{
return drawCount == 0;
}
public bool IsWithinLimits(in IndirectBufferLimits limits)
{
return drawAllocIndex + drawCount <= limits.maxDrawCount
&& instanceAllocIndex + instanceCount <= limits.maxInstanceCount;
}
public int GetExtraDrawInfoSlotIndex()
{
return drawAllocIndex + drawCount;
}
}
internal struct IndirectBufferContext
{
public JobHandle cullingJobHandle;
public enum BufferState
{
Pending, // Not synced with culling output yet
Zeroed, // All draws have zero instances
NoOcclusionTest, // Copy the results of CPU frustum/LOD culling
AllInstancesOcclusionTested, // Occlusion test the results of CPU frustum/LOD culling
OccludedInstancesReTested, // Re-test previously occluded instances (against updated occluders)
}
public BufferState bufferState;
public int occluderVersion;
public int subviewMask;
public IndirectBufferContext(JobHandle cullingJobHandle)
{
this.cullingJobHandle = cullingJobHandle;
this.bufferState = BufferState.Pending;
this.occluderVersion = 0;
this.subviewMask = 0;
}
public bool Matches(BufferState bufferState, int occluderVersion, int subviewMask)
{
return this.bufferState == bufferState
&& this.occluderVersion == occluderVersion
&& this.subviewMask == subviewMask;
}
}
internal struct OccluderMipBounds
{
public Vector2Int offset;
public Vector2Int size;
}
internal struct OccluderContext : IDisposable
{
private static class ShaderIDs
{
public static readonly int _SrcDepth = Shader.PropertyToID("_SrcDepth");
public static readonly int _DstDepth = Shader.PropertyToID("_DstDepth");
public static readonly int OccluderDepthPyramidConstants = Shader.PropertyToID("OccluderDepthPyramidConstants");
}
public const int k_FirstDepthMipIndex = 3; // 8x8 tiles
public const int k_MaxOccluderMips = (int)OcclusionCullingCommonConfig.MaxOccluderMips;
public const int k_MaxSilhouettePlanes = (int)OcclusionCullingCommonConfig.MaxOccluderSilhouettePlanes;
public const int k_MaxSubviewsPerView = (int)OcclusionCullingCommonConfig.MaxSubviewsPerView;
public int version;
public Vector2Int depthBufferSize;
public NativeArray<OccluderDerivedData> subviewData;
public int subviewCount { get { return subviewData.Length; } }
public int subviewValidMask;
public bool IsSubviewValid(int subviewIndex)
{
return subviewIndex < subviewCount && (subviewValidMask & (1 << subviewIndex)) != 0;
}
public NativeArray<OccluderMipBounds> occluderMipBounds;
public Vector2Int occluderMipLayoutSize; // total size of 2D layout specified by occluderMipBounds
public Vector2Int occluderDepthPyramidSize; // at least the size of N mip layouts tiled vertically (one per subview)
public RTHandle occluderDepthPyramid;
public int occlusionDebugOverlaySize;
public GraphicsBuffer occlusionDebugOverlay;
public bool debugNeedsClear;
public ComputeBuffer constantBuffer;
public NativeArray<OccluderDepthPyramidConstants> constantBufferData;
public Vector2 depthBufferSizeInOccluderPixels {
get
{
int occluderPixelSize = 1 << k_FirstDepthMipIndex;
return new Vector2(
(float)depthBufferSize.x / (float)occluderPixelSize,
(float)depthBufferSize.y / (float)occluderPixelSize);
}
}
public void Dispose()
{
if (subviewData.IsCreated)
subviewData.Dispose();
if (occluderMipBounds.IsCreated)
occluderMipBounds.Dispose();
if (occluderDepthPyramid != null)
{
occluderDepthPyramid.Release();
occluderDepthPyramid = null;
}
if (occlusionDebugOverlay != null)
{
occlusionDebugOverlay.Release();
occlusionDebugOverlay = null;
}
if (constantBuffer != null)
{
constantBuffer.Release();
constantBuffer = null;
}
if (constantBufferData.IsCreated)
constantBufferData.Dispose();
}
private void UpdateMipBounds()
{
int occluderPixelSize = 1 << k_FirstDepthMipIndex;
Vector2Int topMipSize = (depthBufferSize + (occluderPixelSize - 1) * Vector2Int.one) / occluderPixelSize;
Vector2Int totalSize = Vector2Int.zero;
Vector2Int mipOffset = Vector2Int.zero;
Vector2Int mipSize = topMipSize;
if (!occluderMipBounds.IsCreated)
occluderMipBounds = new NativeArray<OccluderMipBounds>(k_MaxOccluderMips, Allocator.Persistent);
for (int mipIndex = 0; mipIndex < k_MaxOccluderMips; ++mipIndex)
{
occluderMipBounds[mipIndex] = new OccluderMipBounds { offset = mipOffset, size = mipSize };
totalSize.x = Mathf.Max(totalSize.x, mipOffset.x + mipSize.x);
totalSize.y = Mathf.Max(totalSize.y, mipOffset.y + mipSize.y);
if (mipIndex == 0)
{
mipOffset.x = 0;
mipOffset.y += mipSize.y;
}
else
{
mipOffset.x += mipSize.x;
}
mipSize.x = (mipSize.x + 1) / 2;
mipSize.y = (mipSize.y + 1) / 2;
}
occluderMipLayoutSize = totalSize;
}
private void AllocateTexturesIfNecessary(bool debugOverlayEnabled)
{
Vector2Int minDepthPyramidSize = new Vector2Int(occluderMipLayoutSize.x, occluderMipLayoutSize.y * subviewCount);
if (occluderDepthPyramidSize.x < minDepthPyramidSize.x || occluderDepthPyramidSize.y < minDepthPyramidSize.y)
{
if (occluderDepthPyramid != null)
occluderDepthPyramid.Release();
occluderDepthPyramidSize = minDepthPyramidSize;
occluderDepthPyramid = RTHandles.Alloc(
occluderDepthPyramidSize.x, occluderDepthPyramidSize.y,
dimension: TextureDimension.Tex2D,
format: GraphicsFormat.R32_SFloat,
filterMode: FilterMode.Point,
wrapMode: TextureWrapMode.Clamp,
enableRandomWrite: true,
name: "Occluder Depths");
}
int newDebugOverlaySize = debugOverlayEnabled ? (minDepthPyramidSize.x * minDepthPyramidSize.y) : 0;
if (occlusionDebugOverlaySize < newDebugOverlaySize)
{
if (occlusionDebugOverlay != null)
occlusionDebugOverlay.Release();
occlusionDebugOverlaySize = newDebugOverlaySize;
debugNeedsClear = true;
// We use buffer instead of texture, because some platforms don't support atmoic operations for Texture2D<uint>
occlusionDebugOverlay = new GraphicsBuffer(GraphicsBuffer.Target.Structured, GraphicsBuffer.UsageFlags.None,
occlusionDebugOverlaySize + (int)OcclusionCullingCommonConfig.DebugPyramidOffset, sizeof(uint));
}
if (newDebugOverlaySize == 0)
{
if (occlusionDebugOverlay != null)
{
occlusionDebugOverlay.Release();
occlusionDebugOverlay = null;
}
occlusionDebugOverlaySize = newDebugOverlaySize;
}
if (constantBuffer == null)
constantBuffer = new ComputeBuffer(1, UnsafeUtility.SizeOf<OccluderDepthPyramidConstants>(), ComputeBufferType.Constant);
if (!constantBufferData.IsCreated)
constantBufferData = new NativeArray<OccluderDepthPyramidConstants>(1, Allocator.Persistent);
}
internal static void SetKeyword(ComputeCommandBuffer cmd, ComputeShader cs, in LocalKeyword keyword, bool value)
{
if (value)
cmd.EnableKeyword(cs, keyword);
else
cmd.DisableKeyword(cs, keyword);
}
private OccluderDepthPyramidConstants SetupFarDepthPyramidConstants(ReadOnlySpan<OccluderSubviewUpdate> occluderSubviewUpdates, NativeArray<Plane> silhouettePlanes)
{
OccluderDepthPyramidConstants cb = new OccluderDepthPyramidConstants();
// write globals
cb._OccluderMipLayoutSizeX = (uint)occluderMipLayoutSize.x;
cb._OccluderMipLayoutSizeY = (uint)occluderMipLayoutSize.y;
// write per-subview data
int updateCount = occluderSubviewUpdates.Length;
for (int updateIndex = 0; updateIndex < updateCount; ++updateIndex)
{
ref readonly OccluderSubviewUpdate update = ref occluderSubviewUpdates[updateIndex];
int subviewIndex = update.subviewIndex;
subviewData[subviewIndex] = OccluderDerivedData.FromParameters(update);
subviewValidMask |= 1 << update.subviewIndex;
Matrix4x4 viewProjMatrix
= update.gpuProjMatrix
* update.viewMatrix
* Matrix4x4.Translate(-update.viewOffsetWorldSpace);
Matrix4x4 invViewProjMatrix = viewProjMatrix.inverse;
unsafe
{
for (int j = 0; j < 16; ++j)
cb._InvViewProjMatrix[16 * updateIndex + j] = invViewProjMatrix[j];
cb._SrcOffset[4 * updateIndex + 0] = (uint)update.depthOffset.x;
cb._SrcOffset[4 * updateIndex + 1] = (uint)update.depthOffset.y;
cb._SrcOffset[4 * updateIndex + 2] = 0;
cb._SrcOffset[4 * updateIndex + 3] = 0;
}
cb._SrcSliceIndices |= (((uint)update.depthSliceIndex & 0xf) << (4 * updateIndex));
cb._DstSubviewIndices |= ((uint)subviewIndex << (4 * updateIndex));
}
// TODO: transform these planes from world space into NDC space planes
for (int i = 0; i < k_MaxSilhouettePlanes; ++i)
{
Plane plane = new Plane(Vector3.zero, 0.0f);
if (i < silhouettePlanes.Length)
plane = silhouettePlanes[i];
unsafe
{
cb._SilhouettePlanes[4 * i + 0] = plane.normal.x;
cb._SilhouettePlanes[4 * i + 1] = plane.normal.y;
cb._SilhouettePlanes[4 * i + 2] = plane.normal.z;
cb._SilhouettePlanes[4 * i + 3] = plane.distance;
}
}
cb._SilhouettePlaneCount = (uint)silhouettePlanes.Length;
return cb;
}
public void CreateFarDepthPyramid(ComputeCommandBuffer cmd, in OccluderParameters occluderParams, ReadOnlySpan<OccluderSubviewUpdate> occluderSubviewUpdates, in OccluderHandles occluderHandles, NativeArray<Plane> silhouettePlanes, ComputeShader occluderDepthPyramidCS, int occluderDepthDownscaleKernel)
{
OccluderDepthPyramidConstants cb = SetupFarDepthPyramidConstants(occluderSubviewUpdates, silhouettePlanes);
var cs = occluderDepthPyramidCS;
int kernel = occluderDepthDownscaleKernel;
var srcKeyword = new LocalKeyword(cs, "USE_SRC");
var srcIsArrayKeyword = new LocalKeyword(cs, "SRC_IS_ARRAY");
var srcIsMsaaKeyword = new LocalKeyword(cs, "SRC_IS_MSAA");
bool srcIsArray = occluderParams.depthIsArray;
RTHandle depthTexture = (RTHandle)occluderParams.depthTexture;
bool srcIsMsaa = depthTexture?.isMSAAEnabled ?? false;
int mipCount = k_FirstDepthMipIndex + k_MaxOccluderMips;
for (int mipIndexBase = 0; mipIndexBase < mipCount - 1; mipIndexBase += 4)
{
cmd.SetComputeTextureParam(cs, kernel, ShaderIDs._DstDepth, occluderHandles.occluderDepthPyramid);
bool useSrc = (mipIndexBase == 0);
SetKeyword(cmd, cs, srcKeyword, useSrc);
SetKeyword(cmd, cs, srcIsArrayKeyword, useSrc && srcIsArray);
SetKeyword(cmd, cs, srcIsMsaaKeyword, useSrc && srcIsMsaa);
if (useSrc)
cmd.SetComputeTextureParam(cs, kernel, ShaderIDs._SrcDepth, occluderParams.depthTexture);
cb._MipCount = (uint)Math.Min(mipCount - 1 - mipIndexBase, 4);
Vector2Int srcSize = Vector2Int.zero;
for (int i = 0; i < 5; ++i)
{
Vector2Int offset = Vector2Int.zero;
Vector2Int size = Vector2Int.zero;
int mipIndex = mipIndexBase + i;
if (mipIndex == 0)
{
size = occluderParams.depthSize;
}
else
{
int occMipIndex = mipIndex - k_FirstDepthMipIndex;
if (0 <= occMipIndex && occMipIndex < k_MaxOccluderMips)
{
offset = occluderMipBounds[occMipIndex].offset;
size = occluderMipBounds[occMipIndex].size;
}
}
if (i == 0)
srcSize = size;
unsafe
{
cb._MipOffsetAndSize[4 * i + 0] = (uint)offset.x;
cb._MipOffsetAndSize[4 * i + 1] = (uint)offset.y;
cb._MipOffsetAndSize[4 * i + 2] = (uint)size.x;
cb._MipOffsetAndSize[4 * i + 3] = (uint)size.y;
}
}
constantBufferData[0] = cb;
cmd.SetBufferData(constantBuffer, constantBufferData);
cmd.SetComputeConstantBufferParam(cs, ShaderIDs.OccluderDepthPyramidConstants, constantBuffer, 0, constantBuffer.stride);
cmd.DispatchCompute(cs, kernel, (srcSize.x + 15) / 16, (srcSize.y + 15) / 16, occluderSubviewUpdates.Length);
}
}
public OccluderHandles Import(RenderGraph renderGraph)
{
RenderTargetInfo rtInfo = new RenderTargetInfo
{
width = occluderDepthPyramidSize.x,
height = occluderDepthPyramidSize.y,
volumeDepth = 1,
msaaSamples = 1,
format = GraphicsFormat.R32_SFloat,
bindMS = false,
};
OccluderHandles occluderHandles = new OccluderHandles()
{
occluderDepthPyramid = renderGraph.ImportTexture(occluderDepthPyramid, rtInfo)
};
if (occlusionDebugOverlay != null)
occluderHandles.occlusionDebugOverlay = renderGraph.ImportBuffer(occlusionDebugOverlay);
return occluderHandles;
}
public void PrepareOccluders(in OccluderParameters occluderParams)
{
if (subviewCount != occluderParams.subviewCount)
{
if (subviewData.IsCreated)
subviewData.Dispose();
subviewData = new NativeArray<OccluderDerivedData>(occluderParams.subviewCount, Allocator.Persistent);
subviewValidMask = 0;
}
depthBufferSize = occluderParams.depthSize;
// enable debug counters for cameras when the overlay is enabled
bool debugOverlayEnabled = GPUResidentDrawer.debugDisplaySettings?.occlusionTestOverlayEnabled ?? false;
UpdateMipBounds();
AllocateTexturesIfNecessary(debugOverlayEnabled);
}
internal OcclusionCullingDebugOutput GetDebugOutput()
{
var debugOutput = new OcclusionCullingDebugOutput
{
occluderDepthPyramid = occluderDepthPyramid,
occlusionDebugOverlay = occlusionDebugOverlay,
};
debugOutput.cb._DepthSizeInOccluderPixels = depthBufferSizeInOccluderPixels;
debugOutput.cb._OccluderMipLayoutSizeX = (uint)occluderMipLayoutSize.x;
debugOutput.cb._OccluderMipLayoutSizeY = (uint)occluderMipLayoutSize.y;
for (int i = 0; i < occluderMipBounds.Length; ++i)
{
var mipBounds = occluderMipBounds[i];
unsafe
{
debugOutput.cb._OccluderMipBounds[4 * i + 0] = (uint)mipBounds.offset.x;
debugOutput.cb._OccluderMipBounds[4 * i + 1] = (uint)mipBounds.offset.y;
debugOutput.cb._OccluderMipBounds[4 * i + 2] = (uint)mipBounds.size.x;
debugOutput.cb._OccluderMipBounds[4 * i + 3] = (uint)mipBounds.size.y;
}
}
return debugOutput;
}
}
internal enum IndirectAllocator
{
NextInstanceIndex,
NextDrawIndex,
Count // keep last
}
internal struct IndirectBufferLimits
{
public int maxInstanceCount;
public int maxDrawCount;
}
internal struct InstanceOcclusionTestSubviewSettings
{
public int testCount;
public int occluderSubviewIndices;
public int occluderSubviewMask;
public int cullingSplitIndices;
public int cullingSplitMask;
public static InstanceOcclusionTestSubviewSettings FromSpan(ReadOnlySpan<SubviewOcclusionTest> subviewOcclusionTests)
{
InstanceOcclusionTestSubviewSettings settings = new InstanceOcclusionTestSubviewSettings();
for (int testIndex = 0; testIndex < subviewOcclusionTests.Length; ++testIndex)
{
SubviewOcclusionTest subviewTest = subviewOcclusionTests[testIndex];
settings.occluderSubviewIndices |= subviewTest.occluderSubviewIndex << (4 * testIndex);
settings.occluderSubviewMask |= 1 << subviewTest.occluderSubviewIndex;
settings.cullingSplitIndices |= subviewTest.cullingSplitIndex << (4 * testIndex);
settings.cullingSplitMask |= 1 << subviewTest.cullingSplitIndex;
}
settings.testCount = subviewOcclusionTests.Length;
return settings;
}
}
internal struct IndirectBufferContextHandles
{
public BufferHandle instanceBuffer;
public BufferHandle instanceInfoBuffer;
public BufferHandle dispatchArgsBuffer;
public BufferHandle drawArgsBuffer;
public BufferHandle drawInfoBuffer;
public void UseForOcclusionTest(IBaseRenderGraphBuilder builder)
{
instanceBuffer = builder.UseBuffer(instanceBuffer, AccessFlags.ReadWrite);
instanceInfoBuffer = builder.UseBuffer(instanceInfoBuffer, AccessFlags.Read);
dispatchArgsBuffer = builder.UseBuffer(dispatchArgsBuffer, AccessFlags.ReadWrite);
drawArgsBuffer = builder.UseBuffer(drawArgsBuffer, AccessFlags.ReadWrite);
drawInfoBuffer = builder.UseBuffer(drawInfoBuffer, AccessFlags.Read);
}
}
internal struct IndirectBufferContextStorage : IDisposable
{
private const int kAllocatorCount = (int)IndirectAllocator.Count;
internal const int kInstanceInfoGpuOffsetMultiplier = 2; // GPU side allocates storage for extra copy of instance list
private IndirectBufferLimits m_BufferLimits;
private GraphicsBuffer m_InstanceBuffer;
private GraphicsBuffer m_InstanceInfoBuffer;
private NativeArray<IndirectInstanceInfo> m_InstanceInfoStaging;
private GraphicsBuffer m_DispatchArgsBuffer;
private GraphicsBuffer m_DrawArgsBuffer;
private GraphicsBuffer m_DrawInfoBuffer;
private NativeArray<IndirectDrawInfo> m_DrawInfoStaging;
private int m_ContextAllocCounter;
private NativeHashMap<EntityId, int> m_ContextIndexFromViewID;
private NativeList<IndirectBufferContext> m_Contexts;
private NativeArray<IndirectBufferAllocInfo> m_ContextAllocInfo;
private NativeArray<int> m_AllocationCounters;
public GraphicsBuffer instanceBuffer { get { return m_InstanceBuffer; } }
public GraphicsBuffer instanceInfoBuffer { get { return m_InstanceInfoBuffer; } }
public GraphicsBuffer dispatchArgsBuffer { get { return m_DispatchArgsBuffer; } }
public GraphicsBuffer drawArgsBuffer { get { return m_DrawArgsBuffer; } }
public GraphicsBuffer drawInfoBuffer { get { return m_DrawInfoBuffer; } }
public GraphicsBufferHandle visibleInstanceBufferHandle { get { return m_InstanceBuffer.bufferHandle; } }
public GraphicsBufferHandle indirectDrawArgsBufferHandle { get { return m_DrawArgsBuffer.bufferHandle; } }
public IndirectBufferContextHandles ImportBuffers(RenderGraph renderGraph)
{
return new IndirectBufferContextHandles()
{
instanceBuffer = renderGraph.ImportBuffer(m_InstanceBuffer),
instanceInfoBuffer = renderGraph.ImportBuffer(m_InstanceInfoBuffer),
dispatchArgsBuffer = renderGraph.ImportBuffer(m_DispatchArgsBuffer),
drawArgsBuffer = renderGraph.ImportBuffer(m_DrawArgsBuffer),
drawInfoBuffer = renderGraph.ImportBuffer(m_DrawInfoBuffer),
};
}
public NativeArray<IndirectInstanceInfo> instanceInfoGlobalArray { get { return m_InstanceInfoStaging; } }
public NativeArray<IndirectDrawInfo> drawInfoGlobalArray { get { return m_DrawInfoStaging; } }
public NativeArray<int> allocationCounters { get { return m_AllocationCounters; } }
public void Init()
{
int initialDrawCount = 256;
int initialInstanceCount = 64 * initialDrawCount;
int initialContextCount = 8;
AllocateInstanceBuffers(initialInstanceCount);
AllocateDrawBuffers(initialDrawCount);
m_ContextIndexFromViewID = new NativeHashMap<EntityId, int>(initialContextCount, Allocator.Persistent);
m_Contexts = new NativeList<IndirectBufferContext>(initialContextCount, Allocator.Persistent);
m_ContextAllocInfo = new NativeArray<IndirectBufferAllocInfo>(initialContextCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
m_AllocationCounters = new NativeArray<int>(kAllocatorCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
ResetAllocators();
}
void AllocateInstanceBuffers(int maxInstanceCount)
{
m_InstanceBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Raw, maxInstanceCount, sizeof(int));
m_InstanceInfoBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, kInstanceInfoGpuOffsetMultiplier * maxInstanceCount, System.Runtime.InteropServices.Marshal.SizeOf<IndirectInstanceInfo>());
m_InstanceInfoStaging = new NativeArray<IndirectInstanceInfo>(maxInstanceCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
m_BufferLimits.maxInstanceCount = maxInstanceCount;
}
void FreeInstanceBuffers()
{
m_InstanceBuffer.Release();
m_InstanceInfoBuffer.Release();
m_InstanceInfoStaging.Dispose();
m_BufferLimits.maxInstanceCount = 0;
}
void AllocateDrawBuffers(int maxDrawCount)
{
// Compute dispatch arguments are number of thread groups in X,Y and Z dimensions, hence 3 integers for the size.
m_DispatchArgsBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.IndirectArguments, 3, sizeof(int));
m_DrawArgsBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.IndirectArguments, maxDrawCount * (GraphicsBuffer.IndirectDrawIndexedArgs.size / sizeof(int)), sizeof(int));
m_DrawInfoBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, maxDrawCount, System.Runtime.InteropServices.Marshal.SizeOf<IndirectDrawInfo>());
m_DrawInfoStaging = new NativeArray<IndirectDrawInfo>(maxDrawCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
m_BufferLimits.maxDrawCount = maxDrawCount;
}
void FreeDrawBuffers()
{
m_DispatchArgsBuffer.Release();
m_DrawArgsBuffer.Release();
m_DrawInfoBuffer.Release();
m_DrawInfoStaging.Dispose();
m_BufferLimits.maxDrawCount = 0;
}
public void Dispose()
{
SyncContexts();
FreeInstanceBuffers();
FreeDrawBuffers();
m_ContextIndexFromViewID.Dispose();
m_Contexts.Dispose();
m_ContextAllocInfo.Dispose();
m_AllocationCounters.Dispose();
}
private void SyncContexts()
{
for (int contextIndex = 0; contextIndex < m_Contexts.Length; ++contextIndex)
m_Contexts[contextIndex].cullingJobHandle.Complete();
}
private void ResetAllocators()
{
m_ContextAllocCounter = 0;
m_ContextIndexFromViewID.Clear();
m_Contexts.Clear();
m_AllocationCounters.FillArray(0);
}
private void GrowBuffers()
{
if (m_ContextAllocCounter > m_ContextAllocInfo.Length)
{
// allocate 20% more than the high water mark
int newContextCount = (m_ContextAllocCounter * 6) / 5;
m_Contexts.Clear();
m_Contexts.SetCapacity(newContextCount);
m_ContextAllocInfo.Dispose();
m_ContextAllocInfo = new NativeArray<IndirectBufferAllocInfo>(newContextCount, Allocator.Persistent, NativeArrayOptions.UninitializedMemory);
//Debug.Log("Raised indirect context count to " + newContextCount);
}
int instanceAllocCounter = m_AllocationCounters[(int)IndirectAllocator.NextInstanceIndex];
if (instanceAllocCounter > m_BufferLimits.maxInstanceCount)
{
// allocate 20% more than the high water mark
int newInstanceCount = (instanceAllocCounter * 6) / 5;
FreeInstanceBuffers();
AllocateInstanceBuffers(newInstanceCount);
//Debug.Log("Raised indirect instance count to " + newInstanceCount);
}
int drawAllocCounter = m_AllocationCounters[(int)IndirectAllocator.NextDrawIndex];
if (drawAllocCounter > m_BufferLimits.maxDrawCount)
{
// allocate 20% more than the high water mark
int newDrawCount = (drawAllocCounter * 6) / 5;
FreeDrawBuffers();
AllocateDrawBuffers(newDrawCount);
//Debug.Log("Raised indirect draw count to " + newDrawCount);
}
}
public void ClearContextsAndGrowBuffers()
{
SyncContexts();
GrowBuffers();
ResetAllocators();
}
public int TryAllocateContext(EntityId viewID)
{
// Disallow using the same viewID multiple times for a frame, since it is used as a UID to update indirect args
// This will prevent multiple context being created for example if a custom pass is being used
if (m_ContextIndexFromViewID.ContainsKey(viewID))
return -1;
int contextIndex = -1;
m_ContextAllocCounter += 1;
if (m_Contexts.Length < m_ContextAllocInfo.Length)
{
contextIndex = m_Contexts.Length;
m_Contexts.Add(new IndirectBufferContext());
m_ContextIndexFromViewID.Add(viewID, contextIndex);
}
return contextIndex;
}
public int TryGetContextIndex(EntityId viewID)
{
if (!m_ContextIndexFromViewID.TryGetValue(viewID, out var contextIndex))
contextIndex = -1;
return contextIndex;
}
public NativeArray<IndirectBufferAllocInfo> GetAllocInfoSubArray(int contextIndex)
{
int safeIndex = Mathf.Max(contextIndex, 0);
return m_ContextAllocInfo.GetSubArray(safeIndex, 1);
}
public IndirectBufferAllocInfo GetAllocInfo(int contextIndex)
{
IndirectBufferAllocInfo allocInfo = new IndirectBufferAllocInfo();
if (0 <= contextIndex && contextIndex < m_Contexts.Length)
allocInfo = m_ContextAllocInfo[contextIndex];
return allocInfo;
}
public void CopyFromStaging(CommandBuffer cmd, in IndirectBufferAllocInfo allocInfo)
{
if (!allocInfo.IsEmpty())
{
cmd.SetBufferData(
m_DrawInfoBuffer,
m_DrawInfoStaging,
allocInfo.drawAllocIndex,
allocInfo.drawAllocIndex,
allocInfo.drawCount);
cmd.SetBufferData(
m_InstanceInfoBuffer,
m_InstanceInfoStaging,
allocInfo.instanceAllocIndex,
kInstanceInfoGpuOffsetMultiplier * allocInfo.instanceAllocIndex,
allocInfo.instanceCount);
}
}
public IndirectBufferLimits GetLimits(int contextIndex)
{
IndirectBufferLimits limits = new IndirectBufferLimits();
if (contextIndex >= 0)
limits = m_BufferLimits;
return limits;
}
public IndirectBufferContext GetBufferContext(int contextIndex)
{
IndirectBufferContext ctx = new IndirectBufferContext();
if (0 <= contextIndex && contextIndex < m_Contexts.Length)
ctx = m_Contexts[contextIndex];
return ctx;
}
public void SetBufferContext(int contextIndex, IndirectBufferContext ctx)
{
if (0 <= contextIndex && contextIndex < m_Contexts.Length)
m_Contexts[contextIndex] = ctx;
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,36 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef INSTANCEOCCLUSIONCULLER_CS_HLSL
#define INSTANCEOCCLUSIONCULLER_CS_HLSL
//
// UnityEngine.Rendering.InstanceOcclusionTestDebugCounter: static fields
//
#define INSTANCEOCCLUSIONTESTDEBUGCOUNTER_INSTANCES_OCCLUDED (0)
#define INSTANCEOCCLUSIONTESTDEBUGCOUNTER_INSTANCES_NOT_OCCLUDED (1)
#define INSTANCEOCCLUSIONTESTDEBUGCOUNTER_PRIMITIVES_OCCLUDED (2)
#define INSTANCEOCCLUSIONTESTDEBUGCOUNTER_PRIMITIVES_NOT_OCCLUDED (3)
#define INSTANCEOCCLUSIONTESTDEBUGCOUNTER_COUNT (4)
// Generated from UnityEngine.Rendering.IndirectDrawInfo
// PackingRules = Exact
struct IndirectDrawInfo
{
uint indexCount;
uint firstIndex;
uint baseVertex;
uint firstInstanceGlobalIndex;
uint maxInstanceCountAndTopology;
};
// Generated from UnityEngine.Rendering.IndirectInstanceInfo
// PackingRules = Exact
struct IndirectInstanceInfo
{
int drawOffsetAndSplitMask;
int instanceIndexAndCrossFade;
};
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a71fe447aa3034341b4a16245852e2f5
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: acfffa7be0fa59d409bb1d0a89b9b13b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,20 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
namespace UnityEngine.Rendering
{
[GenerateHLSL(needAccessors = false, generateCBuffer = true)]
internal unsafe struct InstanceOcclusionCullerShaderVariables
{
public uint _DrawInfoAllocIndex;
public uint _DrawInfoCount;
public uint _InstanceInfoAllocIndex;
public uint _InstanceInfoCount;
public int _BoundingSphereInstanceDataAddress;
public int _DebugCounterIndex;
public int _InstanceMultiplierShift;
public int _InstanceOcclusionCullerPad0;
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,21 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef INSTANCEOCCLUSIONCULLERSHADERVARIABLES_CS_HLSL
#define INSTANCEOCCLUSIONCULLERSHADERVARIABLES_CS_HLSL
// Generated from UnityEngine.Rendering.InstanceOcclusionCullerShaderVariables
// PackingRules = Exact
CBUFFER_START(InstanceOcclusionCullerShaderVariables)
uint _DrawInfoAllocIndex;
uint _DrawInfoCount;
uint _InstanceInfoAllocIndex;
uint _InstanceInfoCount;
int _BoundingSphereInstanceDataAddress;
int _DebugCounterIndex;
int _InstanceMultiplierShift;
int _InstanceOcclusionCullerPad0;
CBUFFER_END
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 60581e86aa47d834785ca132fc385273
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1895ea87beb6a2944b488685a325ccc9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,31 @@
#if !UNITY_WEBGL_RENDERER_ONLY
namespace UnityEngine.Rendering
{
[GenerateHLSL(needAccessors = false, generateCBuffer = true)]
internal unsafe struct OccluderDepthPyramidConstants
{
[HLSLArray(OccluderContext.k_MaxSubviewsPerView, typeof(Matrix4x4))]
public fixed float _InvViewProjMatrix[OccluderContext.k_MaxSubviewsPerView * 16];
[HLSLArray(OccluderContext.k_MaxSilhouettePlanes, typeof(Vector4))]
public fixed float _SilhouettePlanes[OccluderContext.k_MaxSilhouettePlanes * 4];
[HLSLArray(OccluderContext.k_MaxSubviewsPerView, typeof(ShaderGenUInt4))]
public fixed uint _SrcOffset[OccluderContext.k_MaxSubviewsPerView * 4];
[HLSLArray(5, typeof(ShaderGenUInt4))]
public fixed uint _MipOffsetAndSize[5 * 4];
public uint _OccluderMipLayoutSizeX;
public uint _OccluderMipLayoutSizeY;
public uint _OccluderDepthPyramidPad0;
public uint _OccluderDepthPyramidPad1;
public uint _SrcSliceIndices; // packed 4 bits each
public uint _DstSubviewIndices; // packed 4 bits each
public uint _MipCount;
public uint _SilhouettePlaneCount;
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,25 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef OCCLUDERDEPTHPYRAMIDCONSTANTS_CS_HLSL
#define OCCLUDERDEPTHPYRAMIDCONSTANTS_CS_HLSL
// Generated from UnityEngine.Rendering.OccluderDepthPyramidConstants
// PackingRules = Exact
CBUFFER_START(OccluderDepthPyramidConstants)
float4x4 _InvViewProjMatrix[6];
float4 _SilhouettePlanes[6];
uint4 _SrcOffset[6];
uint4 _MipOffsetAndSize[5];
uint _OccluderMipLayoutSizeX;
uint _OccluderMipLayoutSizeY;
uint _OccluderDepthPyramidPad0;
uint _OccluderDepthPyramidPad1;
uint _SrcSliceIndices;
uint _DstSubviewIndices;
uint _MipCount;
uint _SilhouettePlaneCount;
CBUFFER_END
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5cbc804d3cb252947a62ba74b9e72d08
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c681068da611a114aa6b31c7214140f7
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,623 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Rendering.RenderGraphModule;
namespace UnityEngine.Rendering
{
[GenerateHLSL]
internal enum OcclusionCullingCommonConfig
{
MaxOccluderMips = 8,
MaxOccluderSilhouettePlanes = 6,
MaxSubviewsPerView = 6,
DebugPyramidOffset = 4, // TODO: rename
}
[GenerateHLSL(needAccessors = false)]
internal enum OcclusionTestDebugFlag
{
AlwaysPass = (1 << 0),
CountVisible = (1 << 1),
}
internal struct OcclusionTestComputeShader
{
public ComputeShader cs;
public LocalKeyword occlusionDebugKeyword;
public void Init(ComputeShader cs)
{
this.cs = cs;
this.occlusionDebugKeyword = new LocalKeyword(cs, "OCCLUSION_DEBUG");
}
}
internal struct SilhouettePlaneCache : IDisposable
{
private struct Slot
{
public bool isActive;
public EntityId viewID;
public int planeCount; // planeIndex = slotIndex * kMaxSilhouettePlanes
public int lastUsedFrameIndex;
public Slot(EntityId viewID, int planeCount, int frameIndex)
{
this.isActive = true;
this.viewID = viewID;
this.planeCount = planeCount;
this.lastUsedFrameIndex = frameIndex;
}
}
private const int kMaxSilhouettePlanes = (int)OcclusionCullingCommonConfig.MaxOccluderSilhouettePlanes;
private NativeParallelHashMap<EntityId, int> m_SubViewIDToIndexMap;
private NativeList<int> m_SlotFreeList;
private NativeList<Slot> m_Slots;
private NativeList<Plane> m_PlaneStorage;
public void Init()
{
m_SubViewIDToIndexMap = new NativeParallelHashMap<EntityId, int>(16, Allocator.Persistent);
m_SlotFreeList = new NativeList<int>(16, Allocator.Persistent);
m_Slots = new NativeList<Slot>(16, Allocator.Persistent);
m_PlaneStorage = new NativeList<Plane>(16 * kMaxSilhouettePlanes, Allocator.Persistent);
}
public void Dispose()
{
m_SubViewIDToIndexMap.Dispose();
m_SlotFreeList.Dispose();
m_Slots.Dispose();
m_PlaneStorage.Dispose();
}
public void Update(EntityId viewID, NativeArray<Plane> planes, int frameIndex)
{
int planeCount = Math.Min(planes.Length, kMaxSilhouettePlanes);
if (!m_SubViewIDToIndexMap.TryGetValue(viewID, out int slotIndex))
{
if (m_SlotFreeList.Length > 0)
{
// take a free slot from the free list
slotIndex = m_SlotFreeList[m_SlotFreeList.Length - 1];
m_SlotFreeList.Length = m_SlotFreeList.Length - 1;
}
else
{
// ensure we have capacity for a few more
if (m_Slots.Length == m_Slots.Capacity)
{
int newCapacity = m_Slots.Length + 8;
m_Slots.SetCapacity(newCapacity);
m_PlaneStorage.SetCapacity(newCapacity * kMaxSilhouettePlanes);
}
// use the next slot in storage
slotIndex = m_Slots.Length;
int newSlotCount = slotIndex + 1;
m_Slots.ResizeUninitialized(newSlotCount);
m_PlaneStorage.ResizeUninitialized(newSlotCount * kMaxSilhouettePlanes);
}
// associate with this view ID
m_SubViewIDToIndexMap.Add(viewID, slotIndex);
}
m_Slots[slotIndex] = new Slot(viewID, planeCount, frameIndex);
m_PlaneStorage.AsArray().GetSubArray(slotIndex * kMaxSilhouettePlanes, planeCount).CopyFrom(planes);
}
public void FreeUnusedSlots(int frameIndex, int maximumAge)
{
for (int slotIndex = 0; slotIndex < m_Slots.Length; ++slotIndex)
{
var slot = m_Slots[slotIndex];
if (!slot.isActive)
continue;
if ((frameIndex - slot.lastUsedFrameIndex) > maximumAge)
{
slot.isActive = false;
m_Slots[slotIndex] = slot;
m_SubViewIDToIndexMap.Remove(slot.viewID);
m_SlotFreeList.Add(slotIndex);
}
}
}
public NativeArray<Plane> GetSubArray(EntityId viewID)
{
int planeOffset = 0;
int planeCount = 0;
if (m_SubViewIDToIndexMap.TryGetValue(viewID, out int slotIndex))
{
planeOffset = slotIndex * kMaxSilhouettePlanes;
planeCount = m_Slots[slotIndex].planeCount;
}
return m_PlaneStorage.AsArray().GetSubArray(planeOffset, planeCount);
}
}
internal class OcclusionCullingCommon : IDisposable
{
private struct OccluderContextSlot
{
public bool valid;
public int lastUsedFrameIndex;
public EntityId viewID;
}
private static readonly int s_MaxContextGCFrame = 8; // Allow a few frames for alternate frame shadow updates before cleanup
private Material m_DebugOcclusionTestMaterial;
private Material m_OccluderDebugViewMaterial;
private ComputeShader m_OcclusionDebugCS;
private int m_ClearOcclusionDebugKernel;
private ComputeShader m_OccluderDepthPyramidCS;
private int m_OccluderDepthDownscaleKernel;
private int m_FrameIndex = 0;
private SilhouettePlaneCache m_SilhouettePlaneCache;
private NativeParallelHashMap<EntityId, int> m_ViewIDToIndexMap;
private List<OccluderContext> m_OccluderContextData;
private NativeList<OccluderContextSlot> m_OccluderContextSlots;
private NativeList<int> m_FreeOccluderContexts;
private NativeArray<OcclusionCullingCommonShaderVariables> m_CommonShaderVariables;
private ComputeBuffer m_CommonConstantBuffer;
private NativeArray<OcclusionCullingDebugShaderVariables> m_DebugShaderVariables;
private ComputeBuffer m_DebugConstantBuffer;
private ProfilingSampler m_ProfilingSamplerUpdateOccluders;
private ProfilingSampler m_ProfilingSamplerOcclusionTestOverlay;
private ProfilingSampler m_ProfilingSamplerOccluderOverlay;
private BaseRenderFunc<OcclusionTestOverlaySetupPassData, ComputeGraphContext> m_ComputePassRenderFunc;
private BaseRenderFunc<OcclusionTestOverlayPassData, RasterGraphContext> m_RasterPassRenderFunc;
internal void Initialize(GPUResidentDrawerResources resources)
{
m_DebugOcclusionTestMaterial = CoreUtils.CreateEngineMaterial(resources.debugOcclusionTestPS);
m_OccluderDebugViewMaterial = CoreUtils.CreateEngineMaterial(resources.debugOccluderPS);
m_OcclusionDebugCS = resources.occlusionCullingDebugKernels;
m_ClearOcclusionDebugKernel = m_OcclusionDebugCS.FindKernel("ClearOcclusionDebug");
m_OccluderDepthPyramidCS = resources.occluderDepthPyramidKernels;
m_OccluderDepthDownscaleKernel = m_OccluderDepthPyramidCS.FindKernel("OccluderDepthDownscale");
m_SilhouettePlaneCache.Init();
m_ViewIDToIndexMap = new NativeParallelHashMap<EntityId, int>(64, Allocator.Persistent);
m_OccluderContextData = new List<OccluderContext>();
m_OccluderContextSlots = new NativeList<OccluderContextSlot>(64, Allocator.Persistent);
m_FreeOccluderContexts = new NativeList<int>(64, Allocator.Persistent);
m_ProfilingSamplerUpdateOccluders = new ProfilingSampler("UpdateOccluders");
m_ProfilingSamplerOcclusionTestOverlay = new ProfilingSampler("OcclusionTestOverlay");
m_ProfilingSamplerOccluderOverlay = new ProfilingSampler("OccluderOverlay");
m_CommonShaderVariables = new NativeArray<OcclusionCullingCommonShaderVariables>(1, Allocator.Persistent);
m_CommonConstantBuffer = new ComputeBuffer(1, UnsafeUtility.SizeOf<OcclusionCullingCommonShaderVariables>(), ComputeBufferType.Constant);
m_DebugShaderVariables = new NativeArray<OcclusionCullingDebugShaderVariables>(1, Allocator.Persistent);
m_DebugConstantBuffer = new ComputeBuffer(1, UnsafeUtility.SizeOf<OcclusionCullingDebugShaderVariables>(), ComputeBufferType.Constant);
m_ComputePassRenderFunc = (OcclusionTestOverlaySetupPassData data, ComputeGraphContext ctx) =>
{
m_DebugShaderVariables[0] = data.cb;
ctx.cmd.SetBufferData(m_DebugConstantBuffer, m_DebugShaderVariables);
m_DebugOcclusionTestMaterial.SetConstantBuffer(
ShaderIDs.OcclusionCullingDebugShaderVariables,
m_DebugConstantBuffer,
0,
m_DebugConstantBuffer.stride);
};
m_RasterPassRenderFunc = (OcclusionTestOverlayPassData data, RasterGraphContext ctx) =>
{
ctx.cmd.SetGlobalBuffer(ShaderIDs._OcclusionDebugOverlay, data.debugPyramid);
CoreUtils.DrawFullScreen(ctx.cmd, m_DebugOcclusionTestMaterial);
};
}
private static class ShaderIDs
{
public static readonly int OcclusionCullingCommonShaderVariables = Shader.PropertyToID("OcclusionCullingCommonShaderVariables");
public static readonly int _OccluderDepthPyramid = Shader.PropertyToID("_OccluderDepthPyramid");
public static readonly int _OcclusionDebugOverlay = Shader.PropertyToID("_OcclusionDebugOverlay");
public static readonly int OcclusionCullingDebugShaderVariables = Shader.PropertyToID("OcclusionCullingDebugShaderVariables");
}
internal static bool UseOcclusionDebug(in OccluderContext occluderCtx)
{
return occluderCtx.occlusionDebugOverlaySize != 0;
}
internal void PrepareCulling(ComputeCommandBuffer cmd, in OccluderContext occluderCtx, in OcclusionCullingSettings settings, in InstanceOcclusionTestSubviewSettings subviewSettings, in OcclusionTestComputeShader shader, bool useOcclusionDebug)
{
OccluderContext.SetKeyword(cmd, shader.cs, shader.occlusionDebugKeyword, useOcclusionDebug);
var debugDisplaySettings = GPUResidentDrawer.debugDisplaySettings;
m_CommonShaderVariables[0] = new OcclusionCullingCommonShaderVariables(
in occluderCtx,
subviewSettings,
debugDisplaySettings?.occlusionTestOverlayCountVisible ?? false,
debugDisplaySettings?.overrideOcclusionTestToAlwaysPass ?? false);
cmd.SetBufferData(m_CommonConstantBuffer, m_CommonShaderVariables);
cmd.SetComputeConstantBufferParam(shader.cs, ShaderIDs.OcclusionCullingCommonShaderVariables, m_CommonConstantBuffer, 0, m_CommonConstantBuffer.stride);
DispatchDebugClear(cmd, settings.viewInstanceID);
}
internal static void SetDepthPyramid(ComputeCommandBuffer cmd, in OcclusionTestComputeShader shader, int kernel, in OccluderHandles occluderHandles)
{
cmd.SetComputeTextureParam(shader.cs, kernel, ShaderIDs._OccluderDepthPyramid, occluderHandles.occluderDepthPyramid);
}
internal static void SetDebugPyramid(ComputeCommandBuffer cmd, in OcclusionTestComputeShader shader, int kernel, in OccluderHandles occluderHandles)
{
cmd.SetComputeBufferParam(shader.cs, kernel, ShaderIDs._OcclusionDebugOverlay, occluderHandles.occlusionDebugOverlay);
}
private class OcclusionTestOverlaySetupPassData
{
public OcclusionCullingDebugShaderVariables cb;
}
private class OcclusionTestOverlayPassData
{
public BufferHandle debugPyramid;
}
public void RenderDebugOcclusionTestOverlay(RenderGraph renderGraph, DebugDisplayGPUResidentDrawer debugSettings, EntityId viewID, TextureHandle colorBuffer)
{
if (debugSettings == null)
return;
if (!debugSettings.occlusionTestOverlayEnabled)
return;
OcclusionCullingDebugOutput debugOutput = GetOcclusionTestDebugOutput(viewID);
if (debugOutput.occlusionDebugOverlay == null)
return;
using (var builder = renderGraph.AddComputePass<OcclusionTestOverlaySetupPassData>("OcclusionTestOverlay", out var passData, m_ProfilingSamplerOcclusionTestOverlay))
{
builder.AllowPassCulling(false);
passData.cb = debugOutput.cb;
builder.SetRenderFunc(m_ComputePassRenderFunc);
}
using (var builder = renderGraph.AddRasterRenderPass<OcclusionTestOverlayPassData>("OcclusionTestOverlay", out var passData, m_ProfilingSamplerOcclusionTestOverlay))
{
builder.AllowGlobalStateModification(true);
passData.debugPyramid = renderGraph.ImportBuffer(debugOutput.occlusionDebugOverlay);
builder.SetRenderAttachment(colorBuffer, 0);
builder.UseBuffer(passData.debugPyramid);
builder.SetRenderFunc(m_RasterPassRenderFunc);
}
}
private struct DebugOccluderViewData
{
public int passIndex;
public Rect viewport;
public bool valid;
}
class OccluderOverlayPassData
{
public Material debugMaterial;
public RTHandle occluderTexture;
public Rect viewport;
public int passIndex;
public Vector2 validRange;
}
public void RenderDebugOccluderOverlay(RenderGraph renderGraph, DebugDisplayGPUResidentDrawer debugSettings, Vector2 screenPos, float maxHeight, TextureHandle colorBuffer)
{
if (debugSettings == null)
return;
if (!debugSettings.occluderDebugViewEnable)
return;
if (!debugSettings.GetOccluderViewID(out var camera))
return;
var occluderTexture = GetOcclusionTestDebugOutput(camera).occluderDepthPyramid;
if (occluderTexture == null)
return;
Material debugMaterial = m_OccluderDebugViewMaterial;
int passIndex = debugMaterial.FindPass("DebugOccluder");
Vector2 outputSize = occluderTexture.referenceSize;
float scaleFactor = maxHeight / outputSize.y;
outputSize *= scaleFactor;
Rect viewport = new Rect(screenPos.x, screenPos.y, outputSize.x, outputSize.y);
using (var builder = renderGraph.AddRasterRenderPass<OccluderOverlayPassData>("OccluderOverlay", out var passData, m_ProfilingSamplerOccluderOverlay))
{
builder.AllowGlobalStateModification(true);
builder.SetRenderAttachment(colorBuffer, 0);
passData.debugMaterial = debugMaterial;
passData.occluderTexture = occluderTexture;
passData.viewport = viewport;
passData.passIndex = passIndex;
passData.validRange = debugSettings.occluderDebugViewRange;
builder.SetRenderFunc(
static (OccluderOverlayPassData data, RasterGraphContext ctx) =>
{
var mpb = ctx.renderGraphPool.GetTempMaterialPropertyBlock();
mpb.SetTexture("_OccluderTexture", data.occluderTexture);
mpb.SetVector("_ValidRange", data.validRange);
ctx.cmd.SetViewport(data.viewport);
ctx.cmd.DrawProcedural(Matrix4x4.identity, data.debugMaterial, data.passIndex, MeshTopology.Triangles, 3, 1, mpb);
});
}
}
private void DispatchDebugClear(ComputeCommandBuffer cmd, EntityId viewID)
{
if (!m_ViewIDToIndexMap.TryGetValue(viewID, out var contextIndex))
return;
OccluderContext occluderCtx = m_OccluderContextData[contextIndex];
if (UseOcclusionDebug(in occluderCtx) && occluderCtx.debugNeedsClear)
{
var cs = m_OcclusionDebugCS;
int kernel = m_ClearOcclusionDebugKernel;
cmd.SetComputeConstantBufferParam(cs, ShaderIDs.OcclusionCullingCommonShaderVariables, m_CommonConstantBuffer, 0, m_CommonConstantBuffer.stride);
cmd.SetComputeBufferParam(cs, kernel, ShaderIDs._OcclusionDebugOverlay, occluderCtx.occlusionDebugOverlay);
Vector2Int mip0Size = occluderCtx.occluderMipBounds[0].size;
cmd.DispatchCompute(cs, kernel, (mip0Size.x + 7) / 8, (mip0Size.y + 7) / 8, occluderCtx.subviewCount);
// mark as cleared in the dictionary
occluderCtx.debugNeedsClear = false;
m_OccluderContextData[contextIndex] = occluderCtx;
}
}
private OccluderHandles PrepareOccluders(RenderGraph renderGraph, in OccluderParameters occluderParams)
{
OccluderHandles occluderHandles = new OccluderHandles();
if (occluderParams.depthTexture.IsValid())
{
if (!m_ViewIDToIndexMap.TryGetValue(occluderParams.viewInstanceID, out var contextIndex))
contextIndex = NewContext(occluderParams.viewInstanceID);
OccluderContext ctx = m_OccluderContextData[contextIndex];
ctx.PrepareOccluders(occluderParams);
occluderHandles = ctx.Import(renderGraph);
m_OccluderContextData[contextIndex] = ctx;
}
else
{
DeleteContext(occluderParams.viewInstanceID);
}
return occluderHandles;
}
private void CreateFarDepthPyramid(ComputeCommandBuffer cmd, in OccluderParameters occluderParams, ReadOnlySpan<OccluderSubviewUpdate> occluderSubviewUpdates, in OccluderHandles occluderHandles)
{
if (!m_ViewIDToIndexMap.TryGetValue(occluderParams.viewInstanceID, out var contextIndex))
return;
var silhouettePlanes = m_SilhouettePlaneCache.GetSubArray(occluderParams.viewInstanceID);
OccluderContext ctx = m_OccluderContextData[contextIndex];
ctx.CreateFarDepthPyramid(cmd, occluderParams, occluderSubviewUpdates, occluderHandles, silhouettePlanes, m_OccluderDepthPyramidCS, m_OccluderDepthDownscaleKernel);
ctx.version++;
m_OccluderContextData[contextIndex] = ctx;
var slot = m_OccluderContextSlots[contextIndex];
slot.lastUsedFrameIndex = m_FrameIndex;
m_OccluderContextSlots[contextIndex] = slot;
}
private class UpdateOccludersPassData
{
public OccluderParameters occluderParams;
public List<OccluderSubviewUpdate> occluderSubviewUpdates;
public OccluderHandles occluderHandles;
public GPUResidentContext grdContext;
}
public bool UpdateInstanceOccluders(RenderGraph renderGraph, GPUResidentContext grdContext, in OccluderParameters occluderParams, ReadOnlySpan<OccluderSubviewUpdate> occluderSubviewUpdates)
{
var occluderHandles = PrepareOccluders(renderGraph, occluderParams);
if (!occluderHandles.occluderDepthPyramid.IsValid())
return false;
using (var builder = renderGraph.AddComputePass<UpdateOccludersPassData>("Update Occluders", out var passData, m_ProfilingSamplerUpdateOccluders))
{
builder.AllowGlobalStateModification(true);
passData.grdContext = grdContext;
passData.occluderParams = occluderParams;
if (passData.occluderSubviewUpdates is null)
passData.occluderSubviewUpdates = new List<OccluderSubviewUpdate>();
else
passData.occluderSubviewUpdates.Clear();
for (int i = 0; i < occluderSubviewUpdates.Length; ++i)
passData.occluderSubviewUpdates.Add(occluderSubviewUpdates[i]);
passData.occluderHandles = occluderHandles;
builder.UseTexture(passData.occluderParams.depthTexture);
passData.occluderHandles.UseForOccluderUpdate(builder);
builder.SetRenderFunc(
static (UpdateOccludersPassData data, ComputeGraphContext context) =>
{
Span<OccluderSubviewUpdate> occluderSubviewUpdates = stackalloc OccluderSubviewUpdate[data.occluderSubviewUpdates.Count];
int subviewMask = 0;
for (int i = 0; i < data.occluderSubviewUpdates.Count; ++i)
{
occluderSubviewUpdates[i] = data.occluderSubviewUpdates[i];
subviewMask |= 1 << data.occluderSubviewUpdates[i].subviewIndex;
}
OcclusionCullingCommon occlusionCullingCommon = data.grdContext.occlusionCullingCommon;
occlusionCullingCommon.CreateFarDepthPyramid(context.cmd, in data.occluderParams, occluderSubviewUpdates, in data.occluderHandles);
data.grdContext.culler.InstanceOccludersUpdated(data.occluderParams.viewInstanceID, subviewMask, occlusionCullingCommon);
});
}
return true;
}
internal void UpdateSilhouettePlanes(EntityId viewID, NativeArray<Plane> planes)
{
m_SilhouettePlaneCache.Update(viewID, planes, m_FrameIndex);
}
internal OcclusionCullingDebugOutput GetOcclusionTestDebugOutput(EntityId viewID)
{
if (m_ViewIDToIndexMap.TryGetValue(viewID, out var contextIndex) && m_OccluderContextSlots[contextIndex].valid)
return m_OccluderContextData[contextIndex].GetDebugOutput();
return new OcclusionCullingDebugOutput();
}
public void UpdateOccluderStats(DebugRendererBatcherStats debugStats)
{
debugStats.occluderStats.Clear();
foreach (var pair in m_ViewIDToIndexMap)
{
if (pair.Value < m_OccluderContextSlots.Length && m_OccluderContextSlots[pair.Value].valid)
{
debugStats.occluderStats.Add(new DebugOccluderStats
{
viewID = pair.Key,
subviewCount = m_OccluderContextData[pair.Value].subviewCount,
occluderMipLayoutSize = m_OccluderContextData[pair.Value].occluderMipLayoutSize,
});
}
}
}
internal bool HasOccluderContext(EntityId viewID)
{
return m_ViewIDToIndexMap.ContainsKey(viewID);
}
internal bool GetOccluderContext(EntityId viewID, out OccluderContext occluderContext)
{
if (m_ViewIDToIndexMap.TryGetValue(viewID, out var contextIndex) && m_OccluderContextSlots[contextIndex].valid)
{
occluderContext = m_OccluderContextData[contextIndex];
return true;
}
occluderContext = new OccluderContext();
return false;
}
internal void UpdateFrame()
{
for (int i = 0; i < m_OccluderContextData.Count; ++i)
{
if (!m_OccluderContextSlots[i].valid)
continue;
OccluderContext occluderCtx = m_OccluderContextData[i];
var slot = m_OccluderContextSlots[i];
//Garbage collect unused contexts for a long time:
if ((m_FrameIndex - slot.lastUsedFrameIndex) >= s_MaxContextGCFrame)
{
DeleteContext(slot.viewID);
continue;
}
occluderCtx.debugNeedsClear = true;
m_OccluderContextData[i] = occluderCtx;
}
m_SilhouettePlaneCache.FreeUnusedSlots(m_FrameIndex, s_MaxContextGCFrame);
++m_FrameIndex;
}
private int NewContext(EntityId viewID)
{
int newSlot = -1;
var newCtxSlot = new OccluderContextSlot { valid = true, viewID = viewID, lastUsedFrameIndex = m_FrameIndex };
var newCtx = new OccluderContext() {};
if (m_FreeOccluderContexts.Length > 0)
{
newSlot = m_FreeOccluderContexts[m_FreeOccluderContexts.Length - 1];
m_FreeOccluderContexts.RemoveAt(m_FreeOccluderContexts.Length - 1);
m_OccluderContextData[newSlot] = newCtx;
m_OccluderContextSlots[newSlot] = newCtxSlot;
}
else
{
newSlot = m_OccluderContextData.Count;
m_OccluderContextData.Add(newCtx);
m_OccluderContextSlots.Add(newCtxSlot);
}
m_ViewIDToIndexMap.Add(viewID, newSlot);
return newSlot;
}
private void DeleteContext(EntityId viewID)
{
if (!m_ViewIDToIndexMap.TryGetValue(viewID, out var contextIndex) || !m_OccluderContextSlots[contextIndex].valid)
return;
m_OccluderContextData[contextIndex].Dispose();
m_OccluderContextSlots[contextIndex] = new OccluderContextSlot { valid = false };
m_FreeOccluderContexts.Add(contextIndex);
m_ViewIDToIndexMap.Remove(viewID);
}
public void Dispose()
{
CoreUtils.Destroy(m_DebugOcclusionTestMaterial);
CoreUtils.Destroy(m_OccluderDebugViewMaterial);
for (int i = 0; i < m_OccluderContextData.Count; ++i)
{
if (m_OccluderContextSlots[i].valid)
m_OccluderContextData[i].Dispose();
}
m_SilhouettePlaneCache.Dispose();
m_ViewIDToIndexMap.Dispose();
m_FreeOccluderContexts.Dispose();
m_OccluderContextData.Clear();
m_OccluderContextSlots.Dispose();
m_CommonShaderVariables.Dispose();
m_CommonConstantBuffer.Release();
m_DebugShaderVariables.Dispose();
m_DebugConstantBuffer.Release();
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,22 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef OCCLUSIONCULLINGCOMMON_CS_HLSL
#define OCCLUSIONCULLINGCOMMON_CS_HLSL
//
// UnityEngine.Rendering.OcclusionCullingCommonConfig: static fields
//
#define OCCLUSIONCULLINGCOMMONCONFIG_MAX_OCCLUDER_MIPS (8)
#define OCCLUSIONCULLINGCOMMONCONFIG_MAX_OCCLUDER_SILHOUETTE_PLANES (6)
#define OCCLUSIONCULLINGCOMMONCONFIG_MAX_SUBVIEWS_PER_VIEW (6)
#define OCCLUSIONCULLINGCOMMONCONFIG_DEBUG_PYRAMID_OFFSET (4)
//
// UnityEngine.Rendering.OcclusionTestDebugFlag: static fields
//
#define OCCLUSIONTESTDEBUGFLAG_ALWAYS_PASS (1)
#define OCCLUSIONTESTDEBUGFLAG_COUNT_VISIBLE (2)
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 1ed97a1fe4775544caa75b92f1d8e9ae
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: ec1ae020bebf201478636c2123e2dde8
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,106 @@
#ifndef _OCCLUSION_CULLING_COMMON_H
#define _OCCLUSION_CULLING_COMMON_H
// If using this the shader should add
// #pragma multi_compile _ OCCLUSION_DEBUG
// before including this file
#include "Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/Culling/OcclusionCullingCommon.cs.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/Culling/OcclusionCullingCommonShaderVariables.cs.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/Culling/OcclusionTestCommon.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/GPUDriven/Utilities/GeometryUtilities.hlsl"
#define OCCLUSION_ENABLE_GATHER_TRIM 1
TEXTURE2D(_OccluderDepthPyramid);
SAMPLER(s_linear_clamp_sampler);
#ifdef OCCLUSION_DEBUG
RWStructuredBuffer<uint> _OcclusionDebugOverlay;
uint OcclusionDebugOverlayOffset(uint2 coord)
{
return OCCLUSIONCULLINGCOMMONCONFIG_DEBUG_PYRAMID_OFFSET + coord.x + _OccluderMipLayoutSizeX * coord.y;
}
#endif
bool IsOcclusionVisible(float3 frontCenterPosRWS, float2 centerPosNDC, float2 radialPosNDC, int subviewIndex)
{
bool isVisible = true;
float queryClosestDepth = ComputeNormalizedDeviceCoordinatesWithZ(frontCenterPosRWS, _ViewProjMatrix[subviewIndex]).z;
bool isBehindCamera = dot(frontCenterPosRWS, _FacingDirWorldSpace[subviewIndex].xyz) >= 0.f;
float2 centerCoordInTopMip = centerPosNDC * _DepthSizeInOccluderPixels.xy;
float radiusInPixels = length((radialPosNDC - centerPosNDC) * _DepthSizeInOccluderPixels.xy);
// log2 of the radius in pixels for the gather4 mip level
int mipLevel = 0;
float mipPartUnused = frexp(radiusInPixels, mipLevel);
mipLevel = max(mipLevel + 1, 0);
if (mipLevel < OCCLUSIONCULLINGCOMMONCONFIG_MAX_OCCLUDER_MIPS && !isBehindCamera)
{
// scale our coordinate to this mip
float2 centerCoordInChosenMip = ldexp(centerCoordInTopMip, -mipLevel);
int4 mipBounds = _OccluderMipBounds[mipLevel];
mipBounds.y += subviewIndex * _OccluderMipLayoutSizeY;
if ((_OcclusionTestDebugFlags & OCCLUSIONTESTDEBUGFLAG_ALWAYS_PASS) == 0)
{
// gather4 occluder depths to cover this radius
float2 gatherUv = (float2(mipBounds.xy) + clamp(centerCoordInChosenMip, .5f, float2(mipBounds.zw) - .5f)) * _OccluderDepthPyramidSize.zw;
float4 gatherDepths = GATHER_TEXTURE2D(_OccluderDepthPyramid, s_linear_clamp_sampler, gatherUv);
float occluderDepth = FarthestDepth(gatherDepths);
isVisible = IsVisibleAfterOcclusion(occluderDepth, queryClosestDepth);
}
#ifdef OCCLUSION_DEBUG
// show footprint of gather4 in debug output
bool countForOverlay = ((_OcclusionTestDebugFlags & OCCLUSIONTESTDEBUGFLAG_COUNT_VISIBLE) != 0);
if (!isVisible)
countForOverlay = !countForOverlay;
if (countForOverlay)
{
uint2 debugCoord = mipBounds.xy + uint2(clamp(int2(centerCoordInChosenMip - .5f), 0, mipBounds.zw - 2));
InterlockedAdd(_OcclusionDebugOverlay[OcclusionDebugOverlayOffset(debugCoord + uint2(0, 0))], 1);
InterlockedAdd(_OcclusionDebugOverlay[OcclusionDebugOverlayOffset(debugCoord + uint2(1, 0))], 1);
InterlockedAdd(_OcclusionDebugOverlay[OcclusionDebugOverlayOffset(debugCoord + uint2(0, 1))], 1);
InterlockedAdd(_OcclusionDebugOverlay[OcclusionDebugOverlayOffset(debugCoord + uint2(1, 1))], 1);
// accumulate the total in the first slot
InterlockedAdd(_OcclusionDebugOverlay[0], 1);
}
#endif
}
return isVisible;
}
bool IsOcclusionVisible(BoundingObjectData data, int subviewIndex)
{
return IsOcclusionVisible(data.frontCenterPosRWS, data.centerPosNDC, data.radialPosNDC, subviewIndex);
}
bool IsOcclusionVisible(SphereBound boundingSphere, int subviewIndex)
{
BoundingObjectData data = CalculateBoundingObjectData(
boundingSphere,
_ViewProjMatrix[subviewIndex],
_ViewOriginWorldSpace[subviewIndex],
_RadialDirWorldSpace[subviewIndex],
_FacingDirWorldSpace[subviewIndex]);
return IsOcclusionVisible(data, subviewIndex);
}
bool IsOcclusionVisible(CylinderBound cylinderBound, int subviewIndex)
{
BoundingObjectData data = CalculateBoundingObjectData(
cylinderBound,
_ViewProjMatrix[subviewIndex],
_ViewOriginWorldSpace[subviewIndex],
_RadialDirWorldSpace[subviewIndex],
_FacingDirWorldSpace[subviewIndex]);
return IsOcclusionVisible(data, subviewIndex);
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 13f1cda4ab8412041ac157181fa6e421
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,92 @@
#if !UNITY_WEBGL_RENDERER_ONLY
namespace UnityEngine.Rendering
{
// TODO make consistent with InstanceOcclusionCullerShaderVariables
[GenerateHLSL(needAccessors = false, generateCBuffer = true)]
internal unsafe struct OcclusionCullingCommonShaderVariables
{
[HLSLArray(OccluderContext.k_MaxOccluderMips, typeof(ShaderGenUInt4))]
public fixed uint _OccluderMipBounds[OccluderContext.k_MaxOccluderMips * 4];
[HLSLArray(OccluderContext.k_MaxSubviewsPerView, typeof(Matrix4x4))]
public fixed float _ViewProjMatrix[OccluderContext.k_MaxSubviewsPerView * 16]; // from view-centered world space
[HLSLArray(OccluderContext.k_MaxSubviewsPerView, typeof(Vector4))]
public fixed float _ViewOriginWorldSpace[OccluderContext.k_MaxSubviewsPerView * 4];
[HLSLArray(OccluderContext.k_MaxSubviewsPerView, typeof(Vector4))]
public fixed float _FacingDirWorldSpace[OccluderContext.k_MaxSubviewsPerView * 4];
[HLSLArray(OccluderContext.k_MaxSubviewsPerView, typeof(Vector4))]
public fixed float _RadialDirWorldSpace[OccluderContext.k_MaxSubviewsPerView * 4];
public Vector4 _DepthSizeInOccluderPixels;
public Vector4 _OccluderDepthPyramidSize;
public uint _OccluderMipLayoutSizeX;
public uint _OccluderMipLayoutSizeY;
public uint _OcclusionTestDebugFlags;
public uint _OcclusionCullingCommonPad0;
public int _OcclusionTestCount;
public int _OccluderSubviewIndices; // packed 4 bits each
public int _CullingSplitIndices; // packed 4 bits each
public int _CullingSplitMask; // only used for early out
internal OcclusionCullingCommonShaderVariables(
in OccluderContext occluderCtx,
in InstanceOcclusionTestSubviewSettings subviewSettings,
bool occlusionOverlayCountVisible,
bool overrideOcclusionTestToAlwaysPass)
{
for (int i = 0; i < occluderCtx.subviewCount; ++i)
{
if (occluderCtx.IsSubviewValid(i))
{
unsafe
{
for (int j = 0; j < 16; ++j)
_ViewProjMatrix[16 * i + j] = occluderCtx.subviewData[i].viewProjMatrix[j];
for (int j = 0; j < 4; ++j)
{
_ViewOriginWorldSpace[4 * i + j] = occluderCtx.subviewData[i].viewOriginWorldSpace[j];
_FacingDirWorldSpace[4 * i + j] = occluderCtx.subviewData[i].facingDirWorldSpace[j];
_RadialDirWorldSpace[4 * i + j] = occluderCtx.subviewData[i].radialDirWorldSpace[j];
}
}
}
}
_OccluderMipLayoutSizeX = (uint)occluderCtx.occluderMipLayoutSize.x;
_OccluderMipLayoutSizeY = (uint)occluderCtx.occluderMipLayoutSize.y;
_OcclusionTestDebugFlags
= (overrideOcclusionTestToAlwaysPass ? (uint)OcclusionTestDebugFlag.AlwaysPass : 0)
| (occlusionOverlayCountVisible ? (uint)OcclusionTestDebugFlag.CountVisible : 0);
_OcclusionCullingCommonPad0 = 0;
_OcclusionTestCount = subviewSettings.testCount;
_OccluderSubviewIndices = subviewSettings.occluderSubviewIndices;
_CullingSplitIndices = subviewSettings.cullingSplitIndices;
_CullingSplitMask = subviewSettings.cullingSplitMask;
_DepthSizeInOccluderPixels = occluderCtx.depthBufferSizeInOccluderPixels;
Vector2Int textureSize = occluderCtx.occluderDepthPyramidSize;
_OccluderDepthPyramidSize = new Vector4(textureSize.x, textureSize.y, 1.0f / textureSize.x, 1.0f / textureSize.y);
for (int i = 0; i < occluderCtx.occluderMipBounds.Length; ++i)
{
var mipBounds = occluderCtx.occluderMipBounds[i];
unsafe
{
_OccluderMipBounds[4*i + 0] = (uint)mipBounds.offset.x;
_OccluderMipBounds[4*i + 1] = (uint)mipBounds.offset.y;
_OccluderMipBounds[4*i + 2] = (uint)mipBounds.size.x;
_OccluderMipBounds[4*i + 3] = (uint)mipBounds.size.y;
}
}
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,28 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef OCCLUSIONCULLINGCOMMONSHADERVARIABLES_CS_HLSL
#define OCCLUSIONCULLINGCOMMONSHADERVARIABLES_CS_HLSL
// Generated from UnityEngine.Rendering.OcclusionCullingCommonShaderVariables
// PackingRules = Exact
CBUFFER_START(OcclusionCullingCommonShaderVariables)
uint4 _OccluderMipBounds[8];
float4x4 _ViewProjMatrix[6];
float4 _ViewOriginWorldSpace[6];
float4 _FacingDirWorldSpace[6];
float4 _RadialDirWorldSpace[6];
float4 _DepthSizeInOccluderPixels;
float4 _OccluderDepthPyramidSize;
uint _OccluderMipLayoutSizeX;
uint _OccluderMipLayoutSizeY;
uint _OcclusionTestDebugFlags;
uint _OcclusionCullingCommonPad0;
int _OcclusionTestCount;
int _OccluderSubviewIndices;
int _CullingSplitIndices;
int _CullingSplitMask;
CBUFFER_END
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: a5ea6c3e82289ce4d8ea0b60a96b1ee2
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e30628ae9a1faa34fb2853ed6354bc90
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,21 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
namespace UnityEngine.Rendering
{
[GenerateHLSL(needAccessors = false, generateCBuffer = true)]
internal unsafe struct OcclusionCullingDebugShaderVariables
{
public Vector4 _DepthSizeInOccluderPixels;
[HLSLArray(OccluderContext.k_MaxOccluderMips, typeof(ShaderGenUInt4))]
public fixed uint _OccluderMipBounds[OccluderContext.k_MaxOccluderMips * 4];
public uint _OccluderMipLayoutSizeX;
public uint _OccluderMipLayoutSizeY;
public uint _OcclusionCullingDebugPad0;
public uint _OcclusionCullingDebugPad1;
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,19 @@
//
// This file was automatically generated. Please don't edit by hand. Execute Editor command [ Edit > Rendering > Generate Shader Includes ] instead
//
#ifndef OCCLUSIONCULLINGDEBUGSHADERVARIABLES_CS_HLSL
#define OCCLUSIONCULLINGDEBUGSHADERVARIABLES_CS_HLSL
// Generated from UnityEngine.Rendering.OcclusionCullingDebugShaderVariables
// PackingRules = Exact
CBUFFER_START(OcclusionCullingDebugShaderVariables)
float4 _DepthSizeInOccluderPixels;
uint4 _OccluderMipBounds[8];
uint _OccluderMipLayoutSizeX;
uint _OccluderMipLayoutSizeY;
uint _OcclusionCullingDebugPad0;
uint _OcclusionCullingDebugPad1;
CBUFFER_END
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 00f96d87bb315084d89b58bd90c5304a
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5c8137fcac12c3743bd060b069e1962b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,33 @@
#ifndef _OCCLUSION_TEST_COMMON_H
#define _OCCLUSION_TEST_COMMON_H
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
float FarthestDepth(float depthA, float depthB)
{
#if UNITY_REVERSED_Z
return min(depthA, depthB);
#else
return max(depthA, depthB);
#endif
}
float FarthestDepth(float4 depths)
{
#if UNITY_REVERSED_Z
return Min3(depths.x, depths.y, min(depths.z, depths.w));
#else
return Max3(depths.x, depths.y, max(depths.z, depths.w));
#endif
}
bool IsVisibleAfterOcclusion(float occluderDepth, float queryClosestDepth)
{
#if UNITY_REVERSED_Z
return queryClosestDepth > occluderDepth;
#else
return queryClosestDepth < occluderDepth;
#endif
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 1024f2cfcd9723443be47989a040394e
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: e06600b8901fc6741a0d7f96ca9d7f0f
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,561 @@
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
using static UnityEngine.Rendering.DebugUI;
using static UnityEngine.Rendering.DebugUI.Widget;
namespace UnityEngine.Rendering
{
/// <summary>
/// GPU Resident Drawer Rendering Debugger settings.
/// </summary>
[PipelineHelpURL("UniversalRenderPipelineAsset", "urp/gpu-resident-drawer")]
[PipelineHelpURL("HDRenderPipelineAsset", "gpu-resident-drawer")]
[Serializable]
public class DebugDisplayGPUResidentDrawer : IDebugDisplaySettingsData, ISerializedDebugDisplaySettings
{
#if !UNITY_WEBGL_RENDERER_ONLY
const string k_FormatString = "{0}";
const float k_RefreshRate = 1f / 5f;
const int k_MaxViewCount = 32;
const int k_MaxOcclusionPassCount = 32;
const int k_MaxContextCount = 16;
internal bool displayBatcherStats { get; set; }
/// <summary>Returns the view EntityId for the selected occluder debug view index, or EntityId.Null if not valid.</summary>
internal bool GetOccluderViewID(out EntityId viewID)
{
DebugRendererBatcherStats debugStats = GPUResidentDrawer.GetDebugStats();
if (debugStats != null)
{
if (occluderDebugViewIndex >= 0 && occluderDebugViewIndex < debugStats.occluderStats.Length)
{
viewID = debugStats.occluderStats[occluderDebugViewIndex].viewID;
return true;
}
}
viewID = EntityId.None;
return false;
}
/// <summary>Returns if the occlusion test heatmap debug overlay is enabled.</summary>
internal bool occlusionTestOverlayEnabled { get; set; }
internal bool occlusionTestOverlayCountVisible { get; set; }
internal bool overrideOcclusionTestToAlwaysPass { get; set; }
/// <summary>Returns true if the occluder debug overlay is enabled.</summary>
public bool occluderDebugViewEnable = false;
internal bool occluderContextStats = false;
internal Vector2 occluderDebugViewRange = new Vector2(0.0f, 1.0f);
internal int occluderDebugViewIndex = 0;
private static InstanceCullerViewStats GetInstanceCullerViewStats(int viewIndex)
{
DebugRendererBatcherStats debugStats = GPUResidentDrawer.GetDebugStats();
if (debugStats != null && viewIndex < debugStats.instanceCullerStats.Length)
return debugStats.instanceCullerStats[viewIndex];
else
return new InstanceCullerViewStats();
}
private static InstanceOcclusionEventStats GetInstanceOcclusionEventStats(int passIndex)
{
DebugRendererBatcherStats debugStats = GPUResidentDrawer.GetDebugStats();
if (debugStats != null && passIndex < debugStats.instanceOcclusionEventStats.Length)
return debugStats.instanceOcclusionEventStats[passIndex];
else
return new InstanceOcclusionEventStats();
}
static class Strings
{
public const string drawerSettingsContainerName = "GPU Resident Drawer Settings";
public static readonly NameAndTooltip displayBatcherStats = new() { name = "Display Culling Stats", tooltip = "Enable the checkbox to display stats for instance culling." };
public const string occlusionCullingTitle = "Occlusion Culling";
public static readonly NameAndTooltip occlusionTestOverlayEnable = new() { name = "Occlusion Test Overlay", tooltip = "Occlusion test visualisation." };
public static readonly NameAndTooltip occlusionTestOverlayCountVisible = new() { name = "Occlusion Test Overlay Count Visible", tooltip = "Occlusion test visualisation should count visible instances instead of occluded instances." };
public static readonly NameAndTooltip overrideOcclusionTestToAlwaysPass = new() { name = "Override Occlusion Test To Always Pass", tooltip = "Occlusion test always passes." };
public static readonly NameAndTooltip occluderContextStats = new() { name = "Occluder Context Stats", tooltip = "Show all the active occluder context textures." };
public static readonly NameAndTooltip occluderDebugViewEnable = new() { name = "Occluder Debug View", tooltip = "Debug view of occluder texture." };
public static readonly NameAndTooltip occluderDebugViewIndex = new() { name = "Occluder Debug View Index", tooltip = "Index of the view for which the occluder texture is displayed. Use the Occlusion Test Context Stats for a list of the views." };
public static readonly NameAndTooltip occluderDebugViewRangeMin = new() { name = "Occluder Debug View Range Min", tooltip = "Range in which the occluder debug texture are displayed." };
public static readonly NameAndTooltip occluderDebugViewRangeMax = new() { name = "Occluder Debug View Range Max", tooltip = "Range in which the occluder debug texture are displayed." };
}
private static DebugOccluderStats GetOccluderStats(int occluderIndex)
{
DebugRendererBatcherStats debugStats = GPUResidentDrawer.GetDebugStats();
if (debugStats != null && occluderIndex < debugStats.occluderStats.Length)
return debugStats.occluderStats[occluderIndex];
else
return new DebugOccluderStats();
}
private static int GetOcclusionContextsCounts()
{
return GPUResidentDrawer.GetDebugStats()?.occluderStats.Length ?? 0;
}
private static int GetInstanceCullerViewCount()
{
return GPUResidentDrawer.GetDebugStats()?.instanceCullerStats.Length ?? 0;
}
private static int GetInstanceOcclusionEventCount()
{
return GPUResidentDrawer.GetDebugStats()?.instanceOcclusionEventStats.Length ?? 0;
}
private static DebugUI.Table.Row AddInstanceCullerViewDataRow(int viewIndex)
{
return new DebugUI.Table.Row
{
displayName = "",
isHiddenCallback = () => { return viewIndex >= GetInstanceCullerViewCount(); },
children =
{
new DebugUI.Value { displayName = "View Type", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => GetInstanceCullerViewStats(viewIndex).viewType },
new DebugUI.Value { displayName = "View Instance ID", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () =>
{
var viewStats = GetInstanceCullerViewStats(viewIndex);
#if UNITY_EDITOR
Object view = EditorUtility.EntityIdToObject(viewStats.viewID);
if (view)
{
return $"{viewStats.viewID} ({view.name})";
}
#endif
return viewStats.viewID;
}
},
new DebugUI.Value { displayName = "Split Index", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => GetInstanceCullerViewStats(viewIndex).splitIndex },
new DebugUI.Value { displayName = "Visible Instances CPU | GPU", tooltip = "Visible instances after CPU culling and after GPU culling.", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () =>
{
var viewStats = GetInstanceCullerViewStats(viewIndex);
return $"{viewStats.visibleInstancesOnCPU} | {viewStats.visibleInstancesOnGPU}";
}
},
new DebugUI.Value { displayName = "Visible Primitives CPU | GPU", tooltip = "Visible primitives after CPU culling and after GPU culling.", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () =>
{
var viewStats = GetInstanceCullerViewStats(viewIndex);
return $"{viewStats.visiblePrimitivesOnCPU} | {viewStats.visiblePrimitivesOnGPU}";
}
},
new DebugUI.Value { displayName = "Draw Commands", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => GetInstanceCullerViewStats(viewIndex).drawCommands },
}
};
}
private static object OccluderVersionString(in InstanceOcclusionEventStats stats)
{
return (stats.eventType == InstanceOcclusionEventType.OccluderUpdate || stats.occlusionTest != OcclusionTest.None) ? stats.occluderVersion : "-";
}
private static object OcclusionTestString(in InstanceOcclusionEventStats stats)
{
return (stats.eventType == InstanceOcclusionEventType.OcclusionTest) ? stats.occlusionTest : "-";
}
private static object VisibleInstancesString(in InstanceOcclusionEventStats stats)
{
return (stats.eventType == InstanceOcclusionEventType.OcclusionTest) ? stats.visibleInstances : "-";
}
private static object CulledInstancesString(in InstanceOcclusionEventStats stats)
{
return (stats.eventType == InstanceOcclusionEventType.OcclusionTest) ? stats.culledInstances : "-";
}
private static object VisiblePrimitivesString(in InstanceOcclusionEventStats stats)
{
return (stats.eventType == InstanceOcclusionEventType.OcclusionTest) ? stats.visiblePrimitives : "-";
}
private static object CulledPrimitivesString(in InstanceOcclusionEventStats stats)
{
return (stats.eventType == InstanceOcclusionEventType.OcclusionTest) ? stats.culledPrimitives : "-";
}
private static DebugUI.Table.Row AddInstanceOcclusionPassDataRow(int eventIndex)
{
return new DebugUI.Table.Row
{
displayName = "",
isHiddenCallback = () => { return eventIndex >= GetInstanceOcclusionEventCount(); },
children =
{
new DebugUI.Value { displayName = "View Instance ID", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () =>
{
var eventStats = GetInstanceOcclusionEventStats(eventIndex);
#if UNITY_EDITOR
Object view = EditorUtility.EntityIdToObject(eventStats.viewID);
if (view)
{
return $"{eventStats.viewID} ({view.name})";
}
#endif
return eventStats.viewID;
}
},
new DebugUI.Value { displayName = "Event Type", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => $"{GetInstanceOcclusionEventStats(eventIndex).eventType}" },
new DebugUI.Value { displayName = "Occluder Version", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => OccluderVersionString(GetInstanceOcclusionEventStats(eventIndex)) },
new DebugUI.Value { displayName = "Subview Mask", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => $"0x{GetInstanceOcclusionEventStats(eventIndex).subviewMask:X}" },
new DebugUI.Value { displayName = "Occlusion Test", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => $"{OcclusionTestString(GetInstanceOcclusionEventStats(eventIndex))}" },
new DebugUI.Value { displayName = "Visible Instances", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => VisibleInstancesString(GetInstanceOcclusionEventStats(eventIndex)) },
new DebugUI.Value { displayName = "Culled Instances", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => CulledInstancesString(GetInstanceOcclusionEventStats(eventIndex)) },
new DebugUI.Value { displayName = "Visible Primitives", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => VisiblePrimitivesString(GetInstanceOcclusionEventStats(eventIndex)) },
new DebugUI.Value { displayName = "Culled Primitives", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => CulledPrimitivesString(GetInstanceOcclusionEventStats(eventIndex)) },
}
};
}
private static DebugUI.Table.Row AddOcclusionContextDataRow(int index)
{
return new DebugUI.Table.Row
{
displayName = "",
isHiddenCallback = () => index >= GetOcclusionContextsCounts(),
children =
{
new DebugUI.Value { displayName = "View Instance ID", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => GetOccluderStats(index).viewID },
new DebugUI.Value { displayName = "Subview Count", refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => GetOccluderStats(index).subviewCount },
new DebugUI.Value { displayName = "Size Per Subview", refreshRate = k_RefreshRate, formatString = k_FormatString, getter =
() =>
{
Vector2Int size = GetOccluderStats(index).occluderMipLayoutSize;
return $"{size.x}x{size.y}";
}},
}
};
}
[DisplayInfo(name = "Rendering", order = 5)]
private class SettingsPanel : DebugDisplaySettingsPanel
{
public SettingsPanel(DebugDisplayGPUResidentDrawer data)
{
DocumentationUtils.TryGetHelpURL(typeof(DebugDisplayGPUResidentDrawer), out var documentationUrl);
var foldout = new DebugUI.Foldout()
{
displayName = Strings.drawerSettingsContainerName,
documentationUrl = documentationUrl
};
AddWidget(foldout);
var helpBox = new DebugUI.MessageBox()
{
displayName = "Not Supported",
style = MessageBox.Style.Warning,
messageCallback = () =>
{
var settings = GPUResidentDrawer.GetGlobalSettingsFromRPAsset();
return GPUResidentDrawer.IsGPUResidentDrawerSupportedBySRP(settings, out var msg, out var _) ? string.Empty : msg;
},
isHiddenCallback = () => GPUResidentDrawer.IsInitialized()
};
foldout.children.Add(helpBox);
GPUResidentDrawer.initializedChanged += OnGPUResidentDrawerInitializedChanged;
// Avoid creating GRD debug modes when it's not enabled.
// This debug UI currently creates ~650 DebugUI Widgets (over 80% of all debug widgets in URP).
// To avoid the overhead, we don't create them if GRD is not enabled. If GRD gets enabled while window is open,
// we refresh the window. It would probably be a good idea to rethink how the stats tables are implemented.
if (!GPUResidentDrawer.IsInitialized())
return;
foldout.children.Add(new Container()
{
displayName = Strings.occlusionCullingTitle,
isHiddenCallback = () => !GPUResidentDrawer.IsInitialized(),
children =
{
new DebugUI.BoolField { nameAndTooltip = Strings.occlusionTestOverlayEnable, getter = () => data.occlusionTestOverlayEnabled, setter = value => data.occlusionTestOverlayEnabled = value},
new DebugUI.BoolField { nameAndTooltip = Strings.occlusionTestOverlayCountVisible, getter = () => data.occlusionTestOverlayCountVisible, setter = value => data.occlusionTestOverlayCountVisible = value},
new DebugUI.BoolField { nameAndTooltip = Strings.overrideOcclusionTestToAlwaysPass, getter = () => data.overrideOcclusionTestToAlwaysPass, setter = value => data.overrideOcclusionTestToAlwaysPass = value},
new DebugUI.BoolField { nameAndTooltip = Strings.occluderContextStats, getter = () => data.occluderContextStats, setter = value => data.occluderContextStats = value},
new DebugUI.BoolField { nameAndTooltip = Strings.occluderDebugViewEnable, getter = () => data.occluderDebugViewEnable, setter = value => data.occluderDebugViewEnable = value},
new DebugUI.IntField { nameAndTooltip = Strings.occluderDebugViewIndex, getter = () => data.occluderDebugViewIndex, setter = value => data.occluderDebugViewIndex = value, isHiddenCallback = () => !data.occluderDebugViewEnable, min = () => 0, max = () => Math.Max(GetOcclusionContextsCounts() - 1, 0) },
new DebugUI.FloatField {nameAndTooltip = Strings.occluderDebugViewRangeMin, getter = () => data.occluderDebugViewRange.x, setter = value => data.occluderDebugViewRange.x = value, isHiddenCallback = () => !data.occluderDebugViewEnable},
new DebugUI.FloatField {nameAndTooltip = Strings.occluderDebugViewRangeMax, getter = () => data.occluderDebugViewRange.y, setter = value => data.occluderDebugViewRange.y = value, isHiddenCallback = () => !data.occluderDebugViewEnable}
}
});
AddOcclusionContextStatsWidget(data);
foldout.children.Add(new DebugUI.BoolField
{
nameAndTooltip = Strings.displayBatcherStats,
getter = () => data.displayBatcherStats,
setter = value => data.displayBatcherStats = value,
isHiddenCallback = () => !GPUResidentDrawer.IsInitialized()
});
AddInstanceCullingStatsWidget(data);
}
private void OnGPUResidentDrawerInitializedChanged(bool previousValue, bool currentValue)
{
DebugManager.instance.RecreateDebugUI();
}
public override void Dispose()
{
base.Dispose();
GPUResidentDrawer.initializedChanged -= OnGPUResidentDrawerInitializedChanged;
}
private void AddInstanceCullingStatsWidget(DebugDisplayGPUResidentDrawer data)
{
var instanceCullerStats = new DebugUI.Foldout
{
displayName = "Instance Culler Stats",
isHeader = true,
opened = true,
isHiddenCallback = () => !data.displayBatcherStats
};
instanceCullerStats.children.Add(new DebugUI.ValueTuple()
{
displayName = "View Count",
values = new[]
{
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => GetInstanceCullerViewCount() }
}
});
instanceCullerStats.children.Add(new DebugUI.ValueTuple()
{
displayName = "Total Visible Instances (Cameras | Lights | Both)",
values = new[]
{
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () =>
{
int totalGRDInstances = 0;
for (int viewIndex = 0; viewIndex < GetInstanceCullerViewCount(); viewIndex++)
{
var viewStats = GetInstanceCullerViewStats(viewIndex);
if (viewStats.viewType == BatchCullingViewType.Camera)
totalGRDInstances += viewStats.visibleInstancesOnGPU;
}
return totalGRDInstances;
}
},
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () =>
{
int totalGRDInstances = 0;
for (int viewIndex = 0; viewIndex < GetInstanceCullerViewCount(); viewIndex++)
{
var viewStats = GetInstanceCullerViewStats(viewIndex);
if (viewStats.viewType == BatchCullingViewType.Light)
totalGRDInstances += viewStats.visibleInstancesOnGPU;
}
return totalGRDInstances;
}
},
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () =>
{
int totalGRDInstances = 0;
for (int viewIndex = 0; viewIndex < GetInstanceCullerViewCount(); viewIndex++)
{
var viewStats = GetInstanceCullerViewStats(viewIndex);
if (viewStats.viewType != BatchCullingViewType.Filtering
&& viewStats.viewType != BatchCullingViewType.Picking
&& viewStats.viewType != BatchCullingViewType.SelectionOutline)
totalGRDInstances += viewStats.visibleInstancesOnGPU;
}
return totalGRDInstances;
}
},
}
});
instanceCullerStats.children.Add(new DebugUI.ValueTuple()
{
displayName = "Total Visible Primitives (Cameras | Lights | Both)",
values = new[]
{
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () =>
{
int totalGRDPrimitives = 0;
for (int viewIndex = 0; viewIndex < GetInstanceCullerViewCount(); viewIndex++)
{
var viewStats = GetInstanceCullerViewStats(viewIndex);
if (viewStats.viewType == BatchCullingViewType.Camera)
totalGRDPrimitives += viewStats.visiblePrimitivesOnGPU;
}
return totalGRDPrimitives;
}
},
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () =>
{
int totalGRDPrimitives = 0;
for (int viewIndex = 0; viewIndex < GetInstanceCullerViewCount(); viewIndex++)
{
var viewStats = GetInstanceCullerViewStats(viewIndex);
if (viewStats.viewType == BatchCullingViewType.Light)
totalGRDPrimitives += viewStats.visiblePrimitivesOnGPU;
}
return totalGRDPrimitives;
}
},
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () =>
{
int totalGRDPrimitives = 0;
for (int viewIndex = 0; viewIndex < GetInstanceCullerViewCount(); viewIndex++)
{
var viewStats = GetInstanceCullerViewStats(viewIndex);
if (viewStats.viewType != BatchCullingViewType.Filtering
&& viewStats.viewType != BatchCullingViewType.Picking
&& viewStats.viewType != BatchCullingViewType.SelectionOutline)
totalGRDPrimitives += viewStats.visiblePrimitivesOnGPU;
}
return totalGRDPrimitives;
}
},
}
});
DebugUI.Table viewTable = new DebugUI.Table
{
displayName = "",
displayRowNames = false,
isReadOnly = true
};
// Always add all possible rows, they are dynamically hidden based on actual data
for (int i = 0; i < k_MaxViewCount; i++)
viewTable.children.Add(AddInstanceCullerViewDataRow(i));
var perViewStats = new DebugUI.Foldout
{
displayName = "Per View Stats",
isHeader = true,
opened = false,
isHiddenCallback = () => !data.displayBatcherStats
};
perViewStats.children.Add(viewTable);
instanceCullerStats.children.Add(perViewStats);
DebugUI.Table eventTable = new DebugUI.Table
{
displayName = "", // First column is empty because its content needs to change dynamically
displayRowNames = false,
isReadOnly = true
};
// Always add all possible rows, they are dynamically hidden based on actual data
for (int i = 0; i < k_MaxOcclusionPassCount; i++)
eventTable.children.Add(AddInstanceOcclusionPassDataRow(i));
var perEventStats = new DebugUI.Foldout
{
displayName = "Occlusion Culling Events",
isHeader = true,
opened = false,
isHiddenCallback = () => !data.displayBatcherStats
};
perEventStats.children.Add(eventTable);
instanceCullerStats.children.Add(perEventStats);
AddWidget(instanceCullerStats);
}
private void AddOcclusionContextStatsWidget(DebugDisplayGPUResidentDrawer data)
{
var visibilityStats = new DebugUI.Foldout
{
displayName = "Occlusion Context Stats",
isHeader = true,
opened = true,
isHiddenCallback = () => !data.occluderContextStats
};
visibilityStats.children.Add(new DebugUI.ValueTuple()
{
displayName = "Active Occlusion Contexts",
values = new[]
{
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FormatString, getter = () => GetOcclusionContextsCounts() }
}
});
DebugUI.Table viewTable = new DebugUI.Table
{
displayName = "", // First column is empty because its content needs to change dynamically
isReadOnly = true
};
// Always add all possible rows, they are dynamically hidden based on actual data
for (int i = 0; i < k_MaxContextCount; i++)
viewTable.children.Add(AddOcclusionContextDataRow(i));
visibilityStats.children.Add(viewTable);
AddWidget(visibilityStats);
}
}
#region IDebugDisplaySettingsQuery
/// <inheritdoc/>
public bool AreAnySettingsActive => displayBatcherStats;
/// <inheritdoc/>
public bool IsPostProcessingAllowed => true;
/// <inheritdoc/>
public bool IsLightingActive => true;
/// <inheritdoc/>
public bool TryGetScreenClearColor(ref Color color)
{
return false;
}
/// <inheritdoc/>
IDebugDisplaySettingsPanelDisposable IDebugDisplaySettingsData.CreatePanel()
{
return new SettingsPanel(this);
}
#endregion
#else
public bool occluderDebugViewEnable = false;
public bool AreAnySettingsActive => false;
public bool IsPostProcessingAllowed => true;
public bool IsLightingActive => true;
public bool TryGetScreenClearColor(ref Color color) => false;
IDebugDisplaySettingsPanelDisposable IDebugDisplaySettingsData.CreatePanel()
{
return new EmptySettingsPanel();
}
private class EmptySettingsPanel : IDebugDisplaySettingsPanelDisposable
{
public string PanelName => string.Empty;
public DebugUI.Widget[] Widgets => Array.Empty<DebugUI.Widget>();
public DebugUI.Flags Flags => DebugUI.Flags.None;
public void Dispose() {}
}
#endif
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 99341524cef9ec347a5aa046d0215e59
@@ -0,0 +1,469 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using System.Collections.Generic;
using Unity.Collections;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
#if ENABLE_PROFILER
#region GRD Debug Suite Types
/// <summary>
/// Reason a renderer was excluded from the GRD path.
/// Keep in sync with GRDExclusionReason in GPUDrivenProcessor.h.
/// </summary>
/// <remarks>
/// WIRE FORMAT: values are received as raw bytes from native via
/// <c>invalidRendererReason</c> in <see cref="GPUDrivenMeshRendererData"/>. Do not reorder
/// existing values or change the underlying type — append new values before <see cref="Count"/>,
/// and mirror the change in the C++ enum.
/// </remarks>
internal enum GRDExclusionReason : byte
{
None = 0,
// Actionable — user can fix these
LODAnimateCrossFading,
CustomMaterialPropertyBlock,
RenderCallback,
NonStandardSortKey,
ProxyVolumeProbe,
BlendProbesWithAnchor,
EnlightenVertexStream,
MissingDOTSInstancing,
NullMaterial, // material slot or shader is null/missing
TooManySubmeshes,
MissingMesh, // no mesh assigned to the renderer
GPUDrivenDisabled, // AllowGPUDrivenRendering explicitly set to false
// Not actionable — renderer type or system-level constraint
AnimationVisibility,
TextMeshComponent,
InactiveOrDisabled, // inactive GameObject, disabled renderer, or ForceRenderingOff
Count
}
/// <summary>
/// High-level grouping of <see cref="GRDExclusionReason"/> values for Coverage reporting.
/// Determines whether a renderer counts toward the Coverage % denominator.
/// </summary>
internal enum GRDExclusionCategory : byte
{
/// <summary>Renderer is on the GRD path. Numerator of Coverage %.</summary>
OnPath,
/// <summary>Renders via the standard SRP path. Counted in the Coverage % denominator
/// because it represents a real GRD-vs-SRP decision the user can act on.</summary>
Excluded,
/// <summary>Asset is broken (missing mesh, null material) — not rendered by any path.
/// Surfaced as an issue but excluded from Coverage % math.</summary>
NonRendering,
/// <summary>GameObject/Renderer is intentionally disabled. Not rendering, not a
/// GRD-vs-SRP decision. Excluded from Coverage % math.</summary>
Inactive,
Count
}
internal static class GRDExclusionReasonExtensions
{
/// <summary>Maps each exclusion reason to its Coverage category.</summary>
public static GRDExclusionCategory GetCategory(this GRDExclusionReason reason) => reason switch
{
GRDExclusionReason.None => GRDExclusionCategory.OnPath,
GRDExclusionReason.NullMaterial => GRDExclusionCategory.NonRendering,
GRDExclusionReason.MissingMesh => GRDExclusionCategory.NonRendering,
GRDExclusionReason.InactiveOrDisabled => GRDExclusionCategory.Inactive,
_ => GRDExclusionCategory.Excluded,
};
}
/// <summary>
/// Breakdown of GPU upload timings by dispatch type.
/// </summary>
internal struct GRDUploadTimingDetail
{
/// <summary>Time in ms for LocalToWorld, WorldToObject, bounding sphere dispatches.</summary>
public float transformDispatchTime;
/// <summary>Time in ms for PrevLocalToWorld motion update dispatches.</summary>
public float motionDispatchTime;
/// <summary>Time in ms for SH coefficient and occlusion probe dispatches.</summary>
public float probeDispatchTime;
/// <summary>Time in ms for GPU component override uploads (lightmap, SpeedTree wind, etc).</summary>
public float componentOverrideTime;
}
/// <summary>
/// Timings for each stage of the GRD pipeline.
/// </summary>
internal struct GRDPipelineStats
{
/// <summary>Time in ms for detecting scene object changes.</summary>
public float dataCollectionTime;
/// <summary>Time in ms for building draw command batches.</summary>
public float batchBuildingTime;
/// <summary>Time in ms for uploading instance data to the GPU.</summary>
public float cpuToGpuUploadTime;
/// <summary>Main-thread CPU time in ms spent dispatching the per-camera cull job tree
/// (CreateCullJobTree). Does NOT include the actual job execution on worker threads.
/// </summary>
public float cullingScheduleTime;
/// <summary>Per-dispatch-type upload timing breakdown.</summary>
public GRDUploadTimingDetail uploadDetail;
}
/// <summary>
/// Culling statistics aggregated by reason. All counts are per-frame for the camera view.
/// totalInstances == sum of every other field below; this invariant is what the UI relies on
/// to render correct percentages.
/// </summary>
internal struct GRDCullingStats
{
/// <summary>Total instances processed (sum of every other count below).</summary>
public int totalInstances;
/// <summary>Instances that passed all culling tests.</summary>
public int visibleInstances;
/// <summary>Instances rejected because the renderer is disabled at runtime
/// (MeshRenderer.enabled=false or GameObject inactive).</summary>
public int renderingDisabledCount;
/// <summary>Instances culled by layer mask.</summary>
public int layerCulledCount;
/// <summary>Instances culled by frustum / receiver-sphere tests.</summary>
public int frustumCulledCount;
/// <summary>Instances culled by LODGroup selection.</summary>
public int lodGroupCulledCount;
/// <summary>Instances culled by small mesh threshold.</summary>
public int smallMeshCulledCount;
/// <summary>Instances culled by CPU occlusion buffer.</summary>
public int occlusionCulledCount;
/// <summary>Instances culled by GPU occlusion (post-CullingJob).</summary>
public int gpuOcclusionCulledCount;
/// <summary>Editor scene-mask / selection-outline / shadow-mode mismatch / lightmapped-shadow-caster cuts.</summary>
public int otherCulledCount;
/// <summary>Clear all statistics.</summary>
public void Clear()
{
totalInstances = 0;
visibleInstances = 0;
renderingDisabledCount = 0;
layerCulledCount = 0;
frustumCulledCount = 0;
lodGroupCulledCount = 0;
smallMeshCulledCount = 0;
occlusionCulledCount = 0;
gpuOcclusionCulledCount = 0;
otherCulledCount = 0;
}
}
/// <summary>
/// LOD level distribution statistics. Counts are CPU-side: an instance is bucketed when
/// it passes CullingJob's visibility + LOD selection, before GPU occlusion runs. So
/// (lod0 + lod1 + lod2 + lod3Plus) does not exactly equal
/// <see cref="GRDCullingStats.visibleInstances"/> (which has GPU-occluded subtracted) —
/// difference is typically small (sub-percent on most scenes).
/// </summary>
internal struct GRDLODStats
{
/// <summary>Instances at LOD level 0 (highest detail).</summary>
public int lod0Count;
/// <summary>Instances at LOD level 1.</summary>
public int lod1Count;
/// <summary>Instances at LOD level 2.</summary>
public int lod2Count;
/// <summary>Instances at LOD level 3 or higher.</summary>
public int lod3PlusCount;
/// <summary>Clear all statistics.</summary>
public void Clear()
{
lod0Count = 0;
lod1Count = 0;
lod2Count = 0;
lod3PlusCount = 0;
}
}
/// <summary>
/// Combined debug statistics for GRD.
/// </summary>
internal class GRDDebugStats : IDisposable
{
/// <summary>Culling statistics by reason.</summary>
public GRDCullingStats cullingStats;
/// <summary>LOD distribution statistics.</summary>
public GRDLODStats lodStats;
// Coverage tracking — source of truth.
// Mutate only through RegisterGRDRenderers / UnregisterRenderers / RegisterExcludedRenderers.
private readonly HashSet<EntityId> m_GRDRendererSet = new HashSet<EntityId>();
private readonly Dictionary<EntityId, GRDExclusionReason> m_ExcludedRendererDict = new Dictionary<EntityId, GRDExclusionReason>();
private readonly int[] m_PerReasonCount = new int[(int)GRDExclusionReason.Count];
private readonly int[] m_PerCategoryCount = new int[(int)GRDExclusionCategory.Count]; // indexed by GRDExclusionCategory; OnPath slot unused
/// <summary>Per-frame count of GRD-path renderers whose <c>renderingEnabled</c> bit is
/// false (toggled disabled at runtime after registration). Updated by
/// <see cref="GPUResidentDrawer"/> once per frame before counter emit.</summary>
internal int liveDisabledGRDCount;
/// <summary>Number of renderers on the GRD path (registered, regardless of runtime
/// disable state).</summary>
public int grdRendererCount => m_GRDRendererSet.Count;
/// <summary>Number of renderers in the <see cref="GRDExclusionCategory.Excluded"/>
/// category — render via SRP path, count toward Coverage % denominator.</summary>
public int excludedRendererCount => m_PerCategoryCount[(int)GRDExclusionCategory.Excluded];
/// <summary>Number of renderers in the <see cref="GRDExclusionCategory.NonRendering"/>
/// category — broken assets, not rendered by any path.</summary>
public int nonRenderingRendererCount => m_PerCategoryCount[(int)GRDExclusionCategory.NonRendering];
/// <summary>Number of renderers that were inactive at registration time. Combine with
/// <see cref="liveDisabledGRDCount"/> for the total currently-inactive count.</summary>
public int inactiveAtRegistrationCount => m_PerCategoryCount[(int)GRDExclusionCategory.Inactive];
/// <summary>Total currently-inactive renderers (snapshot + live-toggled). What the UI
/// surfaces as "inactive" to the user.</summary>
public int inactiveRendererCount => inactiveAtRegistrationCount + liveDisabledGRDCount;
/// <summary>Percentage of GRD-vs-SRP candidates that took the GRD path. Excludes
/// non-rendering and inactive renderers from the denominator — they aren't competing.</summary>
public float coveragePercent
{
get
{
int denom = grdRendererCount + excludedRendererCount;
return denom > 0 ? (float)grdRendererCount / denom * 100f : 0f;
}
}
/// <summary>Returns the number of excluded renderers for a given reason.</summary>
public int GetExcludedCountForReason(GRDExclusionReason reason) => m_PerReasonCount[(int)reason];
public GRDDebugStats()
{
cullingStats = new GRDCullingStats();
lodStats = new GRDLODStats();
}
/// <summary>Clear all statistics.</summary>
public void Clear()
{
cullingStats.Clear();
lodStats.Clear();
m_GRDRendererSet.Clear();
m_ExcludedRendererDict.Clear();
System.Array.Clear(m_PerReasonCount, 0, m_PerReasonCount.Length);
System.Array.Clear(m_PerCategoryCount, 0, m_PerCategoryCount.Length);
liveDisabledGRDCount = 0;
}
public void Dispose() => Clear();
internal void UnregisterRenderers(NativeArray<EntityId> ids)
{
foreach (var id in ids)
{
if (!m_GRDRendererSet.Remove(id) &&
m_ExcludedRendererDict.Remove(id, out var reason))
{
m_PerReasonCount[(int)reason]--;
m_PerCategoryCount[(int)reason.GetCategory()]--;
}
}
}
private void RegisterGRDRenderers(NativeArray<EntityId> ids)
{
foreach (var id in ids)
{
if (m_ExcludedRendererDict.Remove(id, out var oldReason))
{
m_PerReasonCount[(int)oldReason]--;
m_PerCategoryCount[(int)oldReason.GetCategory()]--;
}
m_GRDRendererSet.Add(id); // HashSet.Add is idempotent — re-registering an already-tracked renderer is a no-op.
}
}
private void RegisterExcludedRenderers(NativeArray<EntityId> ids, NativeArray<byte> reasons)
{
for (int i = 0; i < ids.Length; i++)
{
var id = ids[i];
var reason = (GRDExclusionReason)reasons[i];
if (m_ExcludedRendererDict.TryGetValue(id, out var oldReason))
{
m_PerReasonCount[(int)oldReason]--;
m_PerCategoryCount[(int)oldReason.GetCategory()]--;
}
m_PerReasonCount[(int)reason]++;
m_PerCategoryCount[(int)reason.GetCategory()]++;
m_ExcludedRendererDict[id] = reason;
}
}
/// <summary>
/// Records renderers as excluded from GRD, all with the same reason.
/// Assumes renderers have already been removed from the GRD set (via UnregisterRenderers).
/// </summary>
internal void RegisterExcludedRenderers(NativeArray<EntityId> ids, GRDExclusionReason reason)
{
int newCategoryIndex = (int)reason.GetCategory();
foreach (var id in ids)
{
if (m_ExcludedRendererDict.TryGetValue(id, out var oldReason))
{
m_PerReasonCount[(int)oldReason]--;
m_PerCategoryCount[(int)oldReason.GetCategory()]--;
}
m_PerReasonCount[(int)reason]++;
m_PerCategoryCount[newCategoryIndex]++;
m_ExcludedRendererDict[id] = reason;
}
}
/// <summary>
/// Records the GRD-classification verdict (accepted + excluded with reasons) for a batch
/// of renderers. Every GRD entry path must call this so counters reflect all considered
/// renderers regardless of entry.
/// </summary>
internal void RecordRenderers(
NativeArray<EntityId> accepted,
NativeArray<EntityId> excluded,
NativeArray<byte> excludedReasons)
{
if (excluded.Length > 0)
{
Assert.AreEqual(excluded.Length, excludedReasons.Length,
"excluded and excludedReasons arrays must have equal length.");
UnregisterRenderers(excluded);
RegisterExcludedRenderers(excluded, excludedReasons);
}
if (accepted.Length > 0)
RegisterGRDRenderers(accepted);
}
}
#endregion
#endif // ENABLE_PROFILER
internal struct InstanceCullerViewStats
{
public BatchCullingViewType viewType;
public EntityId viewID;
public int splitIndex;
public int visibleInstancesOnCPU;
public int visibleInstancesOnGPU;
public int visiblePrimitivesOnCPU;
public int visiblePrimitivesOnGPU;
public int drawCommands;
}
internal enum InstanceOcclusionEventType
{
OcclusionTest,
OccluderUpdate,
}
internal struct InstanceOcclusionEventStats
{
public EntityId viewID;
public InstanceOcclusionEventType eventType;
public int occluderVersion;
public int subviewMask;
public OcclusionTest occlusionTest;
public int visibleInstances;
public int culledInstances;
public int visiblePrimitives;
public int culledPrimitives;
}
internal struct DebugOccluderStats
{
public EntityId viewID;
public int subviewCount;
public Vector2Int occluderMipLayoutSize;
}
internal class DebugRendererBatcherStats : IDisposable
{
public NativeList<InstanceCullerViewStats> instanceCullerStats;
public NativeList<InstanceOcclusionEventStats> instanceOcclusionEventStats;
public NativeList<DebugOccluderStats> occluderStats;
// Camera-view only. Shadow / light / SelectionOutline views are excluded so this aligns
// with visibleInstances (also camera-only) when the consumer subtracts one from the other.
// Mixing views would push the diff negative on multi-camera scenes.
public int cameraGPUOcclusionCulled;
public DebugRendererBatcherStats()
{
instanceCullerStats = new NativeList<InstanceCullerViewStats>(Allocator.Persistent);
instanceOcclusionEventStats = new NativeList<InstanceOcclusionEventStats>(Allocator.Persistent);
occluderStats = new NativeList<DebugOccluderStats>(Allocator.Persistent);
}
public void FinalizeInstanceCullerViewStats()
{
cameraGPUOcclusionCulled = 0;
// For each view, update the on GPU instance and primitive counts. The final rendered primitive and
// instance count can be found at the last pass of all the occlusion passes.
for (int viewIndex = 0; viewIndex < instanceCullerStats.Length; viewIndex++)
{
InstanceCullerViewStats cullerStats = instanceCullerStats[viewIndex];
InstanceOcclusionEventStats lastOcclusionEventStats = GetLastInstanceOcclusionEventStatsForView(viewIndex);
if (lastOcclusionEventStats.viewID == cullerStats.viewID)
{
// The Min test is because the SelectionOutline view (and probably picking as well) share the same viewInstanceID with
// the scene camera for instance, so we pick up the camera's occlusion event. And we can't have more instances on GPU than we had on CPU.
cullerStats.visibleInstancesOnGPU = Math.Min(lastOcclusionEventStats.visibleInstances, cullerStats.visibleInstancesOnCPU);
cullerStats.visiblePrimitivesOnGPU = Math.Min(lastOcclusionEventStats.visiblePrimitives, cullerStats.visiblePrimitivesOnCPU);
if (cullerStats.viewType == BatchCullingViewType.Camera)
cameraGPUOcclusionCulled += lastOcclusionEventStats.culledInstances;
}
else
{
// There was no occlusion culling for this view, so reuse the same counts as on the CPU.
cullerStats.visibleInstancesOnGPU = cullerStats.visibleInstancesOnCPU;
cullerStats.visiblePrimitivesOnGPU = cullerStats.visiblePrimitivesOnCPU;
}
instanceCullerStats[viewIndex] = cullerStats;
}
}
private InstanceOcclusionEventStats GetLastInstanceOcclusionEventStatsForView(int viewIndex)
{
if (viewIndex < instanceCullerStats.Length)
{
EntityId viewID = instanceCullerStats[viewIndex].viewID;
for (int passIndex = instanceOcclusionEventStats.Length - 1; passIndex >= 0; passIndex--)
{
if (instanceOcclusionEventStats[passIndex].viewID == viewID)
return instanceOcclusionEventStats[passIndex];
}
}
return new InstanceOcclusionEventStats();
}
public void Dispose()
{
if (instanceCullerStats.IsCreated)
instanceCullerStats.Dispose();
if (instanceOcclusionEventStats.IsCreated)
instanceOcclusionEventStats.Dispose();
if (occluderStats.IsCreated)
occluderStats.Dispose();
}
}
internal struct OcclusionCullingDebugOutput
{
public RTHandle occluderDepthPyramid;
public GraphicsBuffer occlusionDebugOverlay;
public OcclusionCullingDebugShaderVariables cb;
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0fd0ea96637f6954bad526ba9c76b16b
@@ -0,0 +1,274 @@
#if !UNITY_WEBGL_RENDERER_ONLY && ENABLE_PROFILER
using Unity.Profiling;
namespace UnityEngine.Rendering
{
/// <summary>
/// ProfilerCounter declarations for GPU Resident Drawer.
/// Emitted every frame in PostPostLateUpdate; read by the GRD Profiler module in the Editor.
/// </summary>
/// <remarks>
/// Counters land under "User &gt; GPU Resident Drawer" in the Profiler Module Editor. Same
/// grouping convention other Unity-shipped C# packages use (Entities, NetCode, …). Unity's
/// builtin "Render" group is reserved for counters registered from native (C++); see
/// <c>ProfilerUnsafeUtility.bindings.cpp</c> — managed CreateCounterValue auto-applies
/// <c>Marker::kScriptUser</c>, forcing user classification regardless of the marker flags
/// passed from C#.
/// </remarks>
static class GRDProfilerCounters
{
internal const string k_CategoryName = "GPU Resident Drawer";
internal static readonly ProfilerCategory k_Category = new(k_CategoryName);
// --- Pipeline Timing (top-level stages) ---
// All four stages are main-thread CPU time. The Culling Schedule stage measures only
// the main-thread time spent building the per-camera cull job graph (CreateCullJobTree);
// actual job execution is not included — see GRDPipelineStats.cullingScheduleTime.
internal const string k_DataCollection = "Data Collection";
internal const string k_BatchBuilding = "Batch Building";
internal const string k_CpuToGpuUpload = "CPU to GPU Upload";
internal const string k_CullingSchedule = "Culling Schedule";
// --- Pipeline Timing (upload sub-breakdown) ---
internal const string k_TransformDispatch = "Transform Dispatch";
internal const string k_MotionDispatch = "Motion Dispatch";
internal const string k_ProbeDispatch = "Probe Dispatch";
internal const string k_ComponentOverride = "Component Override";
// --- Coverage ---
// GRD vs Excluded are the two segments competing for the GRD path; CoveragePercent is
// GRD / (GRD + Excluded). NonRendering and Inactive are tracked but kept out of the
// ratio because they don't represent a GRD-vs-SRP decision (broken assets / disabled
// GameObjects respectively).
internal const string k_GRDRenderers = "GRD Renderers";
internal const string k_ExcludedRenderers = "Excluded Renderers";
internal const string k_NonRenderingRenderers = "Non-Rendering Renderers";
internal const string k_InactiveRenderers = "Inactive Renderers";
internal const string k_CoveragePercent = "Coverage %";
// --- Culling --- (sum of the 9 sub-counters below == k_TotalInstances by construction;
// k_TotalInstances is emitted explicitly so consumers can use it as a denominator
// without having to know — and stay in sync with — the full sub-counter set.)
internal const string k_TotalInstances = "Total Instances";
internal const string k_VisibleInstances = "Visible Instances";
internal const string k_DisabledRendererCulled = "Disabled Renderer Culled";
internal const string k_LayerCulled = "Layer Culled";
internal const string k_FrustumCulled = "Frustum Culled";
internal const string k_OcclusionCulled = "Occlusion Culled";
internal const string k_GpuOcclusionCulled = "GPU Occlusion Culled";
internal const string k_LODGroupCulled = "LOD Group Culled";
internal const string k_SmallMeshCulled = "Small Mesh Culled";
internal const string k_OtherCulled = "Other Culled";
// --- LOD Distribution ---
internal const string k_LOD0 = "LOD 0";
internal const string k_LOD1 = "LOD 1";
internal const string k_LOD2 = "LOD 2";
internal const string k_LOD3Plus = "LOD 3+";
// --- Exclusion Reasons (per-reason breakdown) ---
internal const string k_ExclLODAnimateCrossFading = "Excl: LOD Animate CrossFading";
internal const string k_ExclCustomMaterialPropertyBlock = "Excl: Custom MaterialPropertyBlock";
internal const string k_ExclRenderCallback = "Excl: Render Callback";
internal const string k_ExclNonStandardSortKey = "Excl: Non-Standard Sort Key";
internal const string k_ExclProxyVolumeProbe = "Excl: Proxy Volume Probe";
internal const string k_ExclBlendProbesWithAnchor = "Excl: Blend Probes With Anchor";
internal const string k_ExclEnlightenVertexStream = "Excl: Enlighten Vertex Stream";
internal const string k_ExclMissingDOTSInstancing = "Excl: Missing DOTS Instancing";
internal const string k_ExclNullMaterial = "Excl: Null Material";
internal const string k_ExclTooManySubmeshes = "Excl: Too Many Submeshes";
internal const string k_ExclMissingMesh = "Excl: Missing Mesh";
internal const string k_ExclGPUDrivenDisabled = "Excl: GPU Driven Disabled";
internal const string k_ExclAnimationVisibility = "Excl: Animation Visibility";
internal const string k_ExclTextMeshComponent = "Excl: TextMesh Component";
internal const string k_ExclInactiveOrDisabled = "Excl: Inactive Or Disabled";
/// <summary>
/// Maps GRDExclusionReason enum to counter name. Index = (int)reason.
/// None (0) maps to null.
/// </summary>
internal static readonly string[] k_ExclusionReasonCounterNames = new string[(int)GRDExclusionReason.Count]
{
null, // None
k_ExclLODAnimateCrossFading,
k_ExclCustomMaterialPropertyBlock,
k_ExclRenderCallback,
k_ExclNonStandardSortKey,
k_ExclProxyVolumeProbe,
k_ExclBlendProbesWithAnchor,
k_ExclEnlightenVertexStream,
k_ExclMissingDOTSInstancing,
k_ExclNullMaterial,
k_ExclTooManySubmeshes,
k_ExclMissingMesh,
k_ExclGPUDrivenDisabled,
k_ExclAnimationVisibility,
k_ExclTextMeshComponent,
k_ExclInactiveOrDisabled,
};
// ===== Counter instances =====
// Pipeline Timing (TimeNanoseconds for StackedTimeArea chart compatibility)
static readonly ProfilerCounterValue<long> s_DataCollection = NewTimingCounter(k_DataCollection);
static readonly ProfilerCounterValue<long> s_BatchBuilding = NewTimingCounter(k_BatchBuilding);
static readonly ProfilerCounterValue<long> s_CpuToGpuUpload = NewTimingCounter(k_CpuToGpuUpload);
static readonly ProfilerCounterValue<long> s_CullingSchedule = NewTimingCounter(k_CullingSchedule);
// Upload sub-breakdown
static readonly ProfilerCounterValue<long> s_TransformDispatch = NewTimingCounter(k_TransformDispatch);
static readonly ProfilerCounterValue<long> s_MotionDispatch = NewTimingCounter(k_MotionDispatch);
static readonly ProfilerCounterValue<long> s_ProbeDispatch = NewTimingCounter(k_ProbeDispatch);
static readonly ProfilerCounterValue<long> s_ComponentOverride = NewTimingCounter(k_ComponentOverride);
// Coverage — % is exposed as float so the chart legend reads "94.32%" not "94%".
static readonly ProfilerCounterValue<int> s_GRDRenderers = NewCumulativeCounter(k_GRDRenderers);
static readonly ProfilerCounterValue<int> s_ExcludedRenderers = NewCumulativeCounter(k_ExcludedRenderers);
static readonly ProfilerCounterValue<int> s_NonRenderingRenderers = NewCumulativeCounter(k_NonRenderingRenderers);
static readonly ProfilerCounterValue<int> s_InactiveRenderers = NewCumulativeCounter(k_InactiveRenderers);
static readonly ProfilerCounterValue<float> s_CoveragePercent = NewPercentCounter(k_CoveragePercent);
// Culling
static readonly ProfilerCounterValue<int> s_TotalInstances = NewPerFrameCounter(k_TotalInstances);
static readonly ProfilerCounterValue<int> s_VisibleInstances = NewPerFrameCounter(k_VisibleInstances);
static readonly ProfilerCounterValue<int> s_RenderingDisabledCulled = NewPerFrameCounter(k_DisabledRendererCulled);
static readonly ProfilerCounterValue<int> s_LayerCulled = NewPerFrameCounter(k_LayerCulled);
static readonly ProfilerCounterValue<int> s_FrustumCulled = NewPerFrameCounter(k_FrustumCulled);
static readonly ProfilerCounterValue<int> s_OcclusionCulled = NewPerFrameCounter(k_OcclusionCulled);
static readonly ProfilerCounterValue<int> s_GpuOcclusionCulled = NewPerFrameCounter(k_GpuOcclusionCulled);
static readonly ProfilerCounterValue<int> s_LODGroupCulled = NewPerFrameCounter(k_LODGroupCulled);
static readonly ProfilerCounterValue<int> s_SmallMeshCulled = NewPerFrameCounter(k_SmallMeshCulled);
static readonly ProfilerCounterValue<int> s_OtherCulled = NewPerFrameCounter(k_OtherCulled);
// LOD Distribution
static readonly ProfilerCounterValue<int> s_LOD0 = NewPerFrameCounter(k_LOD0);
static readonly ProfilerCounterValue<int> s_LOD1 = NewPerFrameCounter(k_LOD1);
static readonly ProfilerCounterValue<int> s_LOD2 = NewPerFrameCounter(k_LOD2);
static readonly ProfilerCounterValue<int> s_LOD3Plus = NewPerFrameCounter(k_LOD3Plus);
// Exclusion Reasons (per-reason)
static readonly ProfilerCounterValue<int>[] s_ExclusionReasonCounters = CreateExclusionReasonCounters();
static ProfilerCounterValue<int>[] CreateExclusionReasonCounters()
{
// Index 0 (None) is intentionally left as default(ProfilerCounterValue<int>) — "not
// excluded" has no associated counter. EmitAll iterates from i=1 so the empty slot
// is never written.
var counters = new ProfilerCounterValue<int>[(int)GRDExclusionReason.Count];
for (int i = 1; i < (int)GRDExclusionReason.Count; i++)
{
var name = k_ExclusionReasonCounterNames[i];
if (name != null)
counters[i] = NewCumulativeCounter(name);
}
return counters;
}
// ===== Registration =====
// Touching the type forces all static field initializers to run, which is how
// ProfilerCounterValue<T> instances get registered with the Profiler. Without this,
// counters only appear in the Profiler's Module Editor after the first frame where
// Profiler.enabled is true (i.e. after recording starts) — confusing because GRD is
// running but its counters are missing from the "Add Counter" dropdown.
internal static void EnsureRegistered() { }
// ===== Emit =====
internal static void EmitAll(GRDDebugStats stats, GRDPipelineStats pipelineStats)
{
if (stats == null)
return;
// Pipeline timing (ms → nanoseconds for StackedTimeArea)
s_DataCollection.Value = MsToNs(pipelineStats.dataCollectionTime);
s_BatchBuilding.Value = MsToNs(pipelineStats.batchBuildingTime);
s_CpuToGpuUpload.Value = MsToNs(pipelineStats.cpuToGpuUploadTime);
s_CullingSchedule.Value = MsToNs(pipelineStats.cullingScheduleTime);
// Upload sub-breakdown
s_TransformDispatch.Value = MsToNs(pipelineStats.uploadDetail.transformDispatchTime);
s_MotionDispatch.Value = MsToNs(pipelineStats.uploadDetail.motionDispatchTime);
s_ProbeDispatch.Value = MsToNs(pipelineStats.uploadDetail.probeDispatchTime);
s_ComponentOverride.Value = MsToNs(pipelineStats.uploadDetail.componentOverrideTime);
// Coverage
s_GRDRenderers.Value = stats.grdRendererCount;
s_ExcludedRenderers.Value = stats.excludedRendererCount;
s_NonRenderingRenderers.Value = stats.nonRenderingRendererCount;
s_InactiveRenderers.Value = stats.inactiveRendererCount;
s_CoveragePercent.Value = stats.coveragePercent;
// Culling
s_TotalInstances.Value = stats.cullingStats.totalInstances;
s_VisibleInstances.Value = stats.cullingStats.visibleInstances;
s_RenderingDisabledCulled.Value = stats.cullingStats.renderingDisabledCount;
s_LayerCulled.Value = stats.cullingStats.layerCulledCount;
s_FrustumCulled.Value = stats.cullingStats.frustumCulledCount;
s_OcclusionCulled.Value = stats.cullingStats.occlusionCulledCount;
s_GpuOcclusionCulled.Value = stats.cullingStats.gpuOcclusionCulledCount;
s_LODGroupCulled.Value = stats.cullingStats.lodGroupCulledCount;
s_SmallMeshCulled.Value = stats.cullingStats.smallMeshCulledCount;
s_OtherCulled.Value = stats.cullingStats.otherCulledCount;
// LOD distribution
s_LOD0.Value = stats.lodStats.lod0Count;
s_LOD1.Value = stats.lodStats.lod1Count;
s_LOD2.Value = stats.lodStats.lod2Count;
s_LOD3Plus.Value = stats.lodStats.lod3PlusCount;
// Exclusion reasons
for (int i = 1; i < (int)GRDExclusionReason.Count; i++)
s_ExclusionReasonCounters[i].Value = stats.GetExcludedCountForReason((GRDExclusionReason)i);
}
// ===== Test hooks =====
// Returns every counter name this class registers, in stable enumeration order.
// Used by GRDProfilerCounterNamesTests to verify the editor-side mirror in
// Modules/ProfilerEditor/.../GRDCounterNames.cs has not drifted.
internal static string[] GetCounterNamesForValidation()
{
var names = new System.Collections.Generic.List<string>(48)
{
k_DataCollection, k_BatchBuilding, k_CpuToGpuUpload, k_CullingSchedule,
k_TransformDispatch, k_MotionDispatch, k_ProbeDispatch, k_ComponentOverride,
k_GRDRenderers, k_ExcludedRenderers, k_NonRenderingRenderers, k_InactiveRenderers, k_CoveragePercent,
k_TotalInstances,
k_VisibleInstances, k_DisabledRendererCulled, k_LayerCulled, k_FrustumCulled,
k_OcclusionCulled, k_GpuOcclusionCulled, k_LODGroupCulled, k_SmallMeshCulled, k_OtherCulled,
k_LOD0, k_LOD1, k_LOD2, k_LOD3Plus,
};
for (int i = 1; i < (int)GRDExclusionReason.Count; i++)
{
if (k_ExclusionReasonCounterNames[i] != null)
names.Add(k_ExclusionReasonCounterNames[i]);
}
return names.ToArray();
}
internal static string CategoryNameForValidation => k_CategoryName;
// ===== Helpers =====
static long MsToNs(float ms) => (long)(ms * 1_000_000f);
static ProfilerCounterValue<long> NewTimingCounter(string name) => new(
k_Category, name, ProfilerMarkerDataUnit.TimeNanoseconds,
ProfilerCounterOptions.FlushOnEndOfFrame | ProfilerCounterOptions.ResetToZeroOnFlush);
static ProfilerCounterValue<int> NewPerFrameCounter(string name) => new(
k_Category, name, ProfilerMarkerDataUnit.Count,
ProfilerCounterOptions.FlushOnEndOfFrame | ProfilerCounterOptions.ResetToZeroOnFlush);
static ProfilerCounterValue<int> NewCumulativeCounter(string name) => new(
k_Category, name, ProfilerMarkerDataUnit.Count,
ProfilerCounterOptions.FlushOnEndOfFrame);
static ProfilerCounterValue<float> NewPercentCounter(string name) => new(
k_Category, name, ProfilerMarkerDataUnit.Percent,
ProfilerCounterOptions.FlushOnEndOfFrame);
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0c5bdfbdbc7214538873141d7507bbab
@@ -0,0 +1,71 @@
#if !UNITY_WEBGL_RENDERER_ONLY
using System;
using Unity.Mathematics;
using Unity.Collections;
namespace UnityEngine.Rendering
{
internal class GPUResidentContext : IDisposable
{
private InstanceDataSystem m_InstanceDataSystem;
private LODGroupDataSystem m_LODGroupDataSystem;
private InstanceCuller m_Culler;
private OcclusionCullingCommon m_OcclusionCullingCommon;
private InstanceCullingBatcher m_InstanceCullingBatcher;
private GPUResidentDrawerResources m_Resources;
private DebugRendererBatcherStats m_DebugStats;
#if ENABLE_PROFILER
private GRDDebugStats m_AdvancedDebugStats;
#endif
public InstanceDataSystem instanceDataSystem => m_InstanceDataSystem;
public LODGroupDataSystem lodGroupDataSystem => m_LODGroupDataSystem;
public InstanceCuller culler => m_Culler;
internal OcclusionCullingCommon occlusionCullingCommon => m_OcclusionCullingCommon;
public InstanceCullingBatcher batcher => m_InstanceCullingBatcher;
public GPUResidentDrawerResources resources => m_Resources;
internal DebugRendererBatcherStats debugStats => m_DebugStats;
#if ENABLE_PROFILER
internal GRDDebugStats advancedDebugStats => m_AdvancedDebugStats;
#endif
public SphericalHarmonicsL2 cachedAmbientProbe;
public readonly float smallMeshScreenPercentage;
public readonly float4 shadowSmallMeshScreenPercentages;
public GPUResidentContext(in GPUResidentDrawerSettings settings,
InstanceDataSystem instanceDataSystem,
LODGroupDataSystem lodGroupDataSystem,
InstanceCuller culler,
OcclusionCullingCommon occlusionCullingCommon,
InstanceCullingBatcher instanceCullingBatcher,
GPUResidentDrawerResources resources)
{
m_InstanceDataSystem = instanceDataSystem;
m_LODGroupDataSystem = lodGroupDataSystem;
m_Culler = culler;
m_OcclusionCullingCommon = occlusionCullingCommon;
m_InstanceCullingBatcher = instanceCullingBatcher;
m_Resources = resources;
m_DebugStats = new DebugRendererBatcherStats(); // for now, always allow the possibility of reading counter stats from the cullers.
#if ENABLE_PROFILER
m_AdvancedDebugStats = new GRDDebugStats();
#endif
cachedAmbientProbe = RenderSettings.ambientProbe;
smallMeshScreenPercentage = settings.smallMeshScreenPercentage;
shadowSmallMeshScreenPercentages = settings.shadowSmallMeshScreenPercentages;
}
public void Dispose()
{
m_DebugStats?.Dispose();
m_DebugStats = null;
#if ENABLE_PROFILER
m_AdvancedDebugStats?.Dispose();
m_AdvancedDebugStats = null;
#endif
}
}
}
#endif // !UNITY_WEBGL_RENDERER_ONLY
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7fea6addcc5a75b4a946e867d13833cf
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,149 @@
#if UNITY_EDITOR
using System;
using UnityEditor;
using UnityEditor.Rendering;
#endif
namespace UnityEngine.Rendering
{
public partial class GPUResidentDrawer
{
#if !UNITY_WEBGL_RENDERER_ONLY
static class Strings
{
public static readonly string drawerModeDisabled = "The GPU Resident Drawer is disabled. Enable it on your current Render Pipeline Asset.";
public static readonly string allowInEditModeDisabled = "The current mode does not allow the GPU Resident Drawer. Check the Allow In Edit Mode setting.";
public static readonly string notGPUResidentRenderPipeline = "The GPU Resident Drawer is disabled because the current render pipeline does not support it.";
public static readonly string rawBufferNotSupportedByPlatform = "The current platform does not support the raw buffer path that the GPU Resident Drawer requires.";
public static readonly string kernelNotPresent = "The GPU Resident Drawer kernel is not present. Ensure the player settings include a supported graphics API.";
public static readonly string batchRendererGroupShaderStrippingModeInvalid = "The GPU Resident Drawer requires the \"BatchRendererGroup Variants\" setting to be \"Keep All\"." +
" The current setting will cause errors when building a player because all DOTS instancing shaders will be stripped." +
" To fix, modify Graphics settings and set \"BatchRendererGroup Variants\" to \"Keep All\".";
public static readonly string visionOSNotSupported = "The GPU Resident Drawer is disabled on VisionOS as it is not applicable. This platform uses a custom rendering path and doesn't go through the resident drawer.";
}
internal static bool IsProjectSupported()
{
return IsProjectSupported(out string _, out LogType __);
}
internal static bool IsProjectSupported(out string message, out LogType severity)
{
message = string.Empty;
severity = LogType.Log;
if (Application.platform == RuntimePlatform.VisionOS)
{
message = Strings.visionOSNotSupported;
severity = LogType.Log;
return false;
}
// The GPUResidentDrawer only has support when the RawBuffer path of providing data
// ConstantBuffer path and any other unsupported platforms early out here
if (BatchRendererGroup.BufferTarget != BatchBufferTarget.RawBuffer)
{
severity = LogType.Warning;
message = Strings.rawBufferNotSupportedByPlatform;
return false;
}
#if UNITY_EDITOR
// Check the build target is supported by checking the depth downscale kernel (which has an only_renderers pragma) is present
var resources = GraphicsSettings.GetRenderPipelineSettings<GPUResidentDrawerResources>();
if (!(resources.occluderDepthPyramidKernels && resources.occluderDepthPyramidKernels.HasKernel("OccluderDepthDownscale")))
{
severity = LogType.Warning;
message = Strings.kernelNotPresent;
return false;
}
if (EditorGraphicsSettings.batchRendererGroupShaderStrippingMode != BatchRendererGroupStrippingMode.KeepAll)
{
severity = LogType.Warning;
message = Strings.batchRendererGroupShaderStrippingModeInvalid;
return false;
}
#endif
return true;
}
internal static bool IsGPUResidentDrawerSupportedBySRP(GPUResidentDrawerSettings settings, out string message, out LogType severity)
{
message = string.Empty;
severity = LogType.Log;
// nothing to create
if (settings.mode == GPUResidentDrawerMode.Disabled)
{
message = Strings.drawerModeDisabled;
return false;
}
#if UNITY_EDITOR
// In play mode, the GPU Resident Drawer is always allowed.
// In edit mode, the GPU Resident Drawer is only allowed if the user explicitly requests it with a setting.
bool isAllowedInCurrentMode = EditorApplication.isPlayingOrWillChangePlaymode || settings.allowInEditMode;
if (!isAllowedInCurrentMode)
{
message = Strings.allowInEditModeDisabled;
return false;
}
// Disable GRD in any external AssetImporter child process. GRD isn't made for AssetImporter workflow/lifetime
// Avoid memory leak warning messages and also some future issues (UUM-90039)
if (AssetDatabase.IsAssetImportWorkerProcess())
return false;
#endif
// If we are forcing the system, no need to perform further checks
if (IsForcedOnViaCommandLine() || MaintainContext)
return true;
if (GraphicsSettings.currentRenderPipeline is not IGPUResidentRenderPipeline asset)
{
message = Strings.notGPUResidentRenderPipeline;
severity = LogType.Warning;
return false;
}
return asset.IsGPUResidentDrawerSupportedBySRP(out message, out severity) && IsProjectSupported(out message, out severity);
}
internal static void LogMessage(string message, LogType severity)
{
switch (severity)
{
case LogType.Error:
case LogType.Exception:
Debug.LogError(message);
break;
case LogType.Warning:
Debug.LogWarning(message);
break;
}
}
#else
internal static bool IsProjectSupported()
{
return false;
}
internal static bool IsProjectSupported(out string message, out LogType severity)
{
message = string.Empty;
severity = LogType.Log;
return false;
}
internal static bool IsGPUResidentDrawerSupportedBySRP(GPUResidentDrawerSettings settings, out string message, out LogType severity)
{
message = string.Empty;
severity = LogType.Log;
return false;
}
internal static void LogMessage(string message, LogType severity) {}
#endif
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c0081f3ec5034f9e989cab19a96d6096
timeCreated: 1710836492
@@ -0,0 +1,895 @@
#define GPU_RESIDENT_DRAWER_ALLOW_FORCE_ON
#if UNITY_EDITOR
#define GPU_RESIDENT_DRAWER_ENABLE_VALIDATION
#endif
//#define GPU_RESIDENT_DRAWER_ENABLE_DEEP_VALIDATION
using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Profiling;
using UnityEngine.Assertions;
using UnityEngine.LowLevel;
using UnityEngine.PlayerLoop;
using UnityEngine.SceneManagement;
using UnityEngine.Rendering.RenderGraphModule;
using Unity.Burst;
using Unity.Scripting.LifecycleManagement;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Rendering
{
#if !UNITY_WEBGL_RENDERER_ONLY
internal struct InternalGPUResidentDrawerSettings
{
public RenderPipelineAsset renderPipelineAsset;
public GPUResidentDrawerResources resources;
public OnCullingCompleteCallback onCompleteCallback;
public bool isManagedByUnitTest;
public static readonly InternalGPUResidentDrawerSettings Default = new InternalGPUResidentDrawerSettings
{
renderPipelineAsset = null,
resources = null,
onCompleteCallback = null,
isManagedByUnitTest = false,
};
}
#endif
/// <summary>
/// Static utility class for updating data post cull in begin camera rendering
/// </summary>
[BurstCompile]
public partial class GPUResidentDrawer
{
#if !UNITY_WEBGL_RENDERER_ONLY
#if GPU_RESIDENT_DRAWER_ENABLE_VALIDATION || GPU_RESIDENT_DRAWER_ENABLE_DEEP_VALIDATION
internal const bool EnableValidation = true;
#else
internal const bool EnableValidation = false;
#endif
#if GPU_RESIDENT_DRAWER_ENABLE_DEEP_VALIDATION
internal const bool EnableDeepValidation = true;
#else
internal const bool EnableDeepValidation = false;
#endif
[AutoStaticsCleanup]
internal static bool MaintainContext { get; set; } = false;
[AutoStaticsCleanup]
internal static bool ForceOcclusion { get; set; } = false;
[AutoStaticsCleanup]
private static uint s_InstanceVersion = 0;
[AutoStaticsCleanup]
internal static Action<bool, bool> initializedChanged; // previousValue, currentValue
[NoAutoStaticsCleanup] // Manually cleaned up with [OnCodeUnloading] Cleanup()
private static GPUResidentDrawer s_Instance = null;
////////////////////////////////////////
// Public API for rendering pipelines //
////////////////////////////////////////
#region Public API
/// <summary>
/// Utility function to test if instance occlusion culling is enabled
/// </summary>
/// <returns>True if instance occlusion culling is enabled</returns>
public static bool IsInstanceOcclusionCullingEnabled()
{
if (s_Instance == null)
return false;
if (s_Instance.settings.mode != GPUResidentDrawerMode.InstancedDrawing)
return false;
if (s_Instance.settings.enableOcclusionCulling)
return true;
return false;
}
/// <summary>
/// Utility function for updating data post cull in begin camera rendering
/// </summary>
/// <param name="context">
/// Context containing the data to be set
/// </param>
public static void PostCullBeginCameraRendering(RenderRequestBatcherContext context)
{
s_Instance?.OnPostCullBeginCameraRendering(context);
}
/// <summary>
/// Utility function for updating probe data after global ambient probe is set up
/// </summary>
public static void OnSetupAmbientProbe()
{
s_Instance?.UpdateAmbientProbeAndGPUBuffer(forceUpdate: false);
}
/// <summary>
/// Utility function to run an occlusion test in compute to update indirect draws.
/// This function will dispatch compute shaders to run the given occlusion test and
/// update all indirect draws in the culling output for the given view.
/// The next time a renderer list that uses this culling output is drawn, these
/// indirect draw commands will contain only the instances that passed the given
/// occlusion test.
/// </summary>
/// <param name="renderGraph">Render graph that will have a compute pass added.</param>
/// <param name="settings">The view to update and occlusion test to use.</param>
/// <param name="subviewOcclusionTests">Specifies the occluder subviews to use with each culling split index.</param>
public static void InstanceOcclusionTest(RenderGraph renderGraph, in OcclusionCullingSettings settings, ReadOnlySpan<SubviewOcclusionTest> subviewOcclusionTests)
{
if (s_Instance == null || !s_Instance.m_InstanceDataSystem.hasBoundingSpheres)
return;
s_Instance.m_Culler.InstanceOcclusionTest(renderGraph, settings, subviewOcclusionTests, s_Instance.m_GRDContext);
}
/// <summary>
/// Utility function used to update occluders using a depth buffer.
/// This function will dispatch compute shaders to read the given depth buffer
/// and build a mip pyramid of closest depths for use during occlusion culling.
/// The next time an occlusion test is issed for this view, instances will be
/// tested against the updated occluders.
/// </summary>
/// <param name="renderGraph">Render graph that will have a compute pass added.</param>
/// <param name="occluderParameters">Parameter to specify the view and depth buffer to read.</param>
/// <param name="occluderSubviewUpdates">Specifies which occluder subviews to update from slices of the input depth buffer.</param>
public static void UpdateInstanceOccluders(RenderGraph renderGraph, in OccluderParameters occluderParameters, ReadOnlySpan<OccluderSubviewUpdate> occluderSubviewUpdates)
{
if (s_Instance == null || !s_Instance.m_InstanceDataSystem.hasBoundingSpheres)
return;
s_Instance.m_OcclusionCullingCommon.UpdateInstanceOccluders(renderGraph, s_Instance.m_GRDContext, occluderParameters, occluderSubviewUpdates);
}
/// <summary>
/// Enable or disable GPUResidentDrawer based on the project settings.
/// We call this every frame because GPUResidentDrawer can be enabled/disabled by the settings outside the render pipeline asset.
/// </summary>
public static void ReinitializeIfNeeded()
{
#if UNITY_EDITOR
if (!IsForcedOnViaCommandLine() && !MaintainContext && (IsProjectSupported() != IsInitialized()))
{
Reinitialize();
}
#endif
}
#endregion
#region Public Debug API
/// <summary>
/// Utility function to render an occlusion test heatmap debug overlay.
/// </summary>
/// <param name="renderGraph">Render graph that will have a compute pass added.</param>
/// <param name="debugSettings">The rendering debugger debug settings to read parameters from.</param>
/// <param name="viewID">The EntityId of the camera using a GPU occlusion test.</param>
/// <param name="colorBuffer">The color buffer to render the overlay on.</param>
public static void RenderDebugOcclusionTestOverlay(RenderGraph renderGraph, DebugDisplayGPUResidentDrawer debugSettings, EntityId viewID, TextureHandle colorBuffer)
{
s_Instance?.m_OcclusionCullingCommon.RenderDebugOcclusionTestOverlay(renderGraph, debugSettings, viewID, colorBuffer);
}
/// <summary>
/// Utility function visualise the occluder pyramid in a debug overlay.
/// </summary>
/// <param name="renderGraph">Render graph that will have a compute pass added.</param>
/// <param name="debugSettings">The rendering debugger debug settings to read parameters from.</param>
/// <param name="screenPos">The screen position to render the overlay at.</param>
/// <param name="maxHeight">The maximum screen height of the overlay.</param>
/// <param name="colorBuffer">The color buffer to render the overlay on.</param>
public static void RenderDebugOccluderOverlay(RenderGraph renderGraph, DebugDisplayGPUResidentDrawer debugSettings, Vector2 screenPos, float maxHeight, TextureHandle colorBuffer)
{
s_Instance?.m_OcclusionCullingCommon.RenderDebugOccluderOverlay(renderGraph, debugSettings, screenPos, maxHeight, colorBuffer);
}
#endregion
internal static bool IsEnabledFromSettings() => GetGlobalSettingsFromRPAsset().mode != GPUResidentDrawerMode.Disabled;
internal static bool IsInitialized() => s_Instance != null;
internal static uint GetInstanceVersion() => s_InstanceVersion;
internal static NativeReference<GPUArchetypeManager> GetGPUArchetypeManager() => s_Instance != null ? s_Instance.m_InstanceDataSystem.archetypeManager : default;
internal static ref DefaultGPUComponents GetDefaultGPUComponents() => ref s_Instance.m_InstanceDataSystem.defaultGPUComponents;
internal static GPUInstanceDataBuffer.ReadOnly GetInstanceDataBuffer() => s_Instance != null ? s_Instance.m_InstanceDataSystem.gpuBuffer.AsReadOnly() : default;
internal static GPUInstanceDataBufferReadback<T> ReadbackInstanceDataBuffer<T>() where T : unmanaged => s_Instance != null ? s_Instance.m_InstanceDataSystem.ReadbackInstanceDataBuffer<T>() : default;
internal static DebugRendererBatcherStats GetDebugStats() => s_Instance?.m_GRDContext.debugStats;
internal static void PushMeshRendererUpdateBatches(NativeArray<MeshRendererUpdateBatch> batches) => s_Instance.m_WorldProcessor.PushMeshRendererUpdateBatches(batches);
internal static void PushLODGroupUpdateBatches(NativeArray<LODGroupUpdateBatch> batches) => s_Instance.m_WorldProcessor.PushLODGroupUpdateBatches(batches);
internal static void PushMeshRendererDeletionBatches(NativeArray<NativeArray<EntityId>> batches) => s_Instance.m_WorldProcessor.PushMeshRendererDeletionBatch(batches);
internal static void PushLODGroupDeletionBatches(NativeArray<NativeArray<EntityId>> batches) => s_Instance.m_WorldProcessor.PushLODGroupDeletionBatch(batches);
#if ENABLE_PROFILER
internal static void RecordRenderers(NativeArray<EntityId> accepted, NativeArray<EntityId> excluded, NativeArray<byte> excludedReasons)
=> s_Instance?.m_GRDContext.advancedDebugStats?.RecordRenderers(accepted, excluded, excludedReasons);
#endif
internal static DebugDisplayGPUResidentDrawer debugDisplaySettings => s_Instance?.m_DebugDisplaySettings;
private void InsertIntoPlayerLoop()
{
var rootLoop = LowLevel.PlayerLoop.GetCurrentPlayerLoop();
bool isAdded = false;
for (var i = 0; i < rootLoop.subSystemList.Length; i++)
{
var subSystem = rootLoop.subSystemList[i];
// We have to update inside the PostLateUpdate systems, because we have to be able to get previous matrices from renderers.
// Previous matrices are updated by renderer managers on UpdateAllRenderers which is part of PostLateUpdate.
if (!isAdded && subSystem.type == typeof(PostLateUpdate))
{
var subSubSystems = new List<PlayerLoopSystem>();
foreach (var subSubSystem in subSystem.subSystemList)
{
if (subSubSystem.type == typeof(PostLateUpdate.FinishFrameRendering))
{
PlayerLoopSystem s = default;
s.updateDelegate += PostPostLateUpdateStatic;
s.type = GetType();
subSubSystems.Add(s);
isAdded = true;
}
subSubSystems.Add(subSubSystem);
}
subSystem.subSystemList = subSubSystems.ToArray();
rootLoop.subSystemList[i] = subSystem;
}
}
LowLevel.PlayerLoop.SetPlayerLoop(rootLoop);
}
private void RemoveFromPlayerLoop()
{
var rootLoop = LowLevel.PlayerLoop.GetCurrentPlayerLoop();
for (int i = 0; i < rootLoop.subSystemList.Length; i++)
{
var subsystem = rootLoop.subSystemList[i];
if (subsystem.type != typeof(PostLateUpdate))
continue;
var newList = new List<PlayerLoopSystem>();
foreach (var subSubSystem in subsystem.subSystemList)
{
if (subSubSystem.type != GetType())
newList.Add(subSubSystem);
}
subsystem.subSystemList = newList.ToArray();
rootLoop.subSystemList[i] = subsystem;
}
LowLevel.PlayerLoop.SetPlayerLoop(rootLoop);
}
internal static GPUResidentDrawerSettings GetGlobalSettingsFromRPAsset()
{
var renderPipelineAsset = GraphicsSettings.currentRenderPipeline;
if (renderPipelineAsset is not IGPUResidentRenderPipeline mbAsset)
return new GPUResidentDrawerSettings();
var settings = mbAsset.gpuResidentDrawerSettings;
if (IsForcedOnViaCommandLine())
settings.mode = GPUResidentDrawerMode.InstancedDrawing;
if (IsOcclusionForcedOnViaCommandLine() || ForceOcclusion)
settings.enableOcclusionCulling = true;
return settings;
}
/// <summary>
/// Is GRD forced on via the command line via -force-gpuresidentdrawer. Editor only.
/// </summary>
/// <returns>true if forced on</returns>
internal static bool IsForcedOnViaCommandLine()
{
#if UNITY_EDITOR
return s_IsForcedOnViaCommandLine;
#else
return false;
#endif
}
/// <summary>
/// Is occlusion culling forced on via the command line via -force-gpuocclusion. Editor only.
/// </summary>
/// <returns>true if forced on</returns>
internal static bool IsOcclusionForcedOnViaCommandLine()
{
#if UNITY_EDITOR
return s_IsOcclusionForcedOnViaCommandLine;
#else
return false;
#endif
}
internal static void Reinitialize()
{
var settings = GetGlobalSettingsFromRPAsset();
// When compiling in the editor, we include a try catch block around our initialization logic to avoid leaving the editor window in a broken state if something goes wrong.
// We can probably remove this in the future once the edit mode functionality stabilizes, but for now it's safest to have a fallback.
#if UNITY_EDITOR
try
#endif
{
Recreate(settings);
}
#if UNITY_EDITOR
catch (Exception exception)
{
Debug.LogError($"The GPU Resident Drawer encountered an error during initialization. The standard SRP path will be used instead. [Error: {exception.Message}]");
Debug.LogError($"GPU Resident drawer stack trace: {exception.StackTrace}");
Cleanup();
}
#endif
}
#if UNITY_EDITOR
[InitializeOnEnterPlayMode]
private static void OnEnteringPlaymode(EnterPlayModeOptions options)
{
if (options.HasFlag(EnterPlayModeOptions.DisableDomainReload))
Cleanup();
}
[OnCodeUnloading]
private static void OnCodeUnloading()
{
Cleanup();
}
#endif
private static void Cleanup()
{
RenderPipelineManager.activeRenderPipelineDisposed -= Cleanup;
if (s_Instance == null)
return;
s_Instance.Dispose();
s_Instance = null;
++s_InstanceVersion;
}
private static void Recreate(GPUResidentDrawerSettings settings)
{
bool wasInitialized = IsInitialized();
Cleanup();
if (IsGPUResidentDrawerSupportedBySRP(settings, out var message, out var severity))
{
s_Instance = new GPUResidentDrawer(settings);
RenderPipelineManager.activeRenderPipelineDisposed += Cleanup;
++s_InstanceVersion;
}
else
{
LogMessage(message, severity);
}
bool isInitialized = IsInitialized();
if (wasInitialized != isInitialized)
initializedChanged?.Invoke(wasInitialized, isInitialized);
}
private IntPtr m_ContextIntPtr = IntPtr.Zero;
private GPUResidentDrawerSettings m_Settings;
private InternalGPUResidentDrawerSettings m_InternalSettings;
// Core Systems
internal GPUDrivenProcessor m_GPUDrivenProcessor;
internal ObjectDispatcher m_ObjectDispatcher;
internal InstanceDataSystem m_InstanceDataSystem;
internal LODGroupDataSystem m_LODGroupDataSystem;
internal InstanceCuller m_Culler;
internal OcclusionCullingCommon m_OcclusionCullingCommon;
internal InstanceCullingBatcher m_Batcher;
internal GPUResidentContext m_GRDContext;
#if ENABLE_TERRAIN_MODULE
internal SpeedTreeWindGPUDataUpdater m_SpeedTreeWindGPUDataUpdater;
#endif
internal WorldProcessor m_WorldProcessor;
internal GPUResidentDrawerSettings settings => m_Settings;
private DebugDisplayGPUResidentDrawer m_DebugDisplaySettings = null;
#if UNITY_EDITOR
private static readonly bool s_IsForcedOnViaCommandLine;
private static readonly bool s_IsOcclusionForcedOnViaCommandLine;
private NativeList<EntityId> m_FrameCameraIDs;
private bool m_FrameUpdateNeeded = false;
static GPUResidentDrawer()
{
Lightmapping.bakeCompleted += Reinitialize;
#if GPU_RESIDENT_DRAWER_ALLOW_FORCE_ON
foreach (var arg in Environment.GetCommandLineArgs())
{
if (arg.Equals("-force-gpuresidentdrawer", StringComparison.InvariantCultureIgnoreCase))
{
Debug.Log("GPU Resident Drawer forced on via commandline");
s_IsForcedOnViaCommandLine = true;
}
if (arg.Equals("-force-gpuocclusion", StringComparison.InvariantCultureIgnoreCase))
{
Debug.Log("GPU occlusion culling forced on via commandline");
s_IsOcclusionForcedOnViaCommandLine = true;
}
}
#endif
}
#endif
internal GPUResidentDrawer(in GPUResidentDrawerSettings settings) : this(settings, InternalGPUResidentDrawerSettings.Default) {}
internal GPUResidentDrawer(in GPUResidentDrawerSettings settings, in InternalGPUResidentDrawerSettings internalSettings)
{
Assert.IsTrue(settings.mode != GPUResidentDrawerMode.Disabled);
var resources = internalSettings.resources != null ? internalSettings.resources : GraphicsSettings.GetRenderPipelineSettings<GPUResidentDrawerResources>();
var renderPipelineAsset = internalSettings.renderPipelineAsset != null ? internalSettings.renderPipelineAsset : GraphicsSettings.currentRenderPipeline;
if (renderPipelineAsset is not IGPUResidentRenderPipeline)
Assert.IsTrue(internalSettings.isManagedByUnitTest, "No compatible Render Pipeline found");
m_Settings = settings;
m_InternalSettings = internalSettings;
m_GPUDrivenProcessor = new GPUDrivenProcessor();
//@ Disable partial rendering for now as it hasn't been widely tested in the main branch.
//@ This feature was initially developed alongside deferred materials and was controlled by deferred materials settings.
//@ It enables rendering only the materials and sub-meshes within the same object that are supported by the BRG, while SRP handles the rest.
m_GPUDrivenProcessor.enablePartialRendering = false;
m_ObjectDispatcher = new ObjectDispatcher();
m_InstanceDataSystem = new InstanceDataSystem(1024, settings.enableOcclusionCulling, resources);
m_LODGroupDataSystem = new LODGroupDataSystem(settings.supportDitheringCrossFade);
m_Culler = new InstanceCuller();
m_OcclusionCullingCommon = new OcclusionCullingCommon();
m_Batcher = new InstanceCullingBatcher();
m_GRDContext = new GPUResidentContext(settings,
m_InstanceDataSystem,
m_LODGroupDataSystem,
m_Culler,
m_OcclusionCullingCommon,
m_Batcher,
resources);
m_WorldProcessor = new WorldProcessor();
#if ENABLE_PROFILER
// Register Profiler counters eagerly so they show up in the Profiler's Module
// Editor regardless of whether recording is active. Pipeline recorders are
// lazily allocated on first observation (see EnsurePipelineRecordersRunning).
GRDProfilerCounters.EnsureRegistered();
#endif
m_ObjectDispatcher.EnableTypeTracking<Mesh>();
m_ObjectDispatcher.EnableTypeTracking<Material>();
m_ObjectDispatcher.EnableTypeTracking<MeshRenderer>(ObjectDispatcher.TypeTrackingFlags.SceneObjects);
m_ObjectDispatcher.EnableTypeTracking<LODGroup>(ObjectDispatcher.TypeTrackingFlags.SceneObjects);
m_ObjectDispatcher.EnableTypeTracking<Camera>(ObjectDispatcher.TypeTrackingFlags.SceneObjects | ObjectDispatcher.TypeTrackingFlags.EditorOnlyObjects);
m_ObjectDispatcher.EnableTransformTracking<MeshRenderer>(ObjectDispatcher.TransformTrackingType.GlobalTRS);
m_ObjectDispatcher.EnableTransformTracking<LODGroup>(ObjectDispatcher.TransformTrackingType.GlobalTRS);
m_Culler.Initialize(resources, m_GRDContext.debugStats);
#if ENABLE_PROFILER
m_Culler.InitializeAdvancedDebugStats(m_GRDContext.advancedDebugStats);
#endif
m_OcclusionCullingCommon.Initialize(resources);
m_Batcher.Initialize(m_GRDContext, settings, OnFinishedCulling, internalSettings.onCompleteCallback);
#if ENABLE_TERRAIN_MODULE
m_SpeedTreeWindGPUDataUpdater = new SpeedTreeWindGPUDataUpdater();
m_SpeedTreeWindGPUDataUpdater.Initialize(m_InstanceDataSystem, m_Culler);
#endif
m_WorldProcessor.Initialize(m_GPUDrivenProcessor, m_ObjectDispatcher, m_GRDContext);
#if UNITY_EDITOR
m_FrameCameraIDs = new NativeList<EntityId>(1, Allocator.Persistent);
#endif
SceneManager.sceneLoaded += OnSceneLoaded;
RenderPipelineManager.beginContextRendering += OnBeginContextRendering;
RenderPipelineManager.endContextRendering += OnEndContextRendering;
RenderPipelineManager.beginCameraRendering += OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering += OnEndCameraRendering;
const string useLegacyLightmapsKeyword = "USE_LEGACY_LIGHTMAPS";
Shader.EnableKeyword(useLegacyLightmapsKeyword);
if (!internalSettings.isManagedByUnitTest)
InsertIntoPlayerLoop();
string extraText = IsForcedOnViaCommandLine() ? " (forced on via commandline)" : "";
extraText = MaintainContext ? " (forced on via MaintainContext)" : extraText;
if (settings.enableOcclusionCulling)
{
string occlusionText = IsOcclusionForcedOnViaCommandLine() ? " (forced on via commandline)" : "";
occlusionText = ForceOcclusion ? " (forced on via ForceOcclusion)" : occlusionText;
extraText = $"{extraText} with GPU Occlusion Culling{occlusionText}";
}
Console.WriteLine($"GPU Resident Drawer created{extraText}.");
}
internal void Dispose()
{
NativeArray<EntityId> rendererIDs = m_InstanceDataSystem.renderWorld.instanceIDs;
if (rendererIDs.Length > 0)
m_GPUDrivenProcessor.DisableGPUDrivenRendering(rendererIDs);
#if UNITY_EDITOR
if (m_FrameCameraIDs.IsCreated)
m_FrameCameraIDs.Dispose();
#endif
SceneManager.sceneLoaded -= OnSceneLoaded;
// Note: Those RenderPipelineManager callbacks do not run when using built-in editor debug views such as lightmap, shadowmask etc
RenderPipelineManager.beginContextRendering -= OnBeginContextRendering;
RenderPipelineManager.endContextRendering -= OnEndContextRendering;
RenderPipelineManager.beginCameraRendering -= OnBeginCameraRendering;
RenderPipelineManager.endCameraRendering -= OnEndCameraRendering;
if (!m_InternalSettings.isManagedByUnitTest)
RemoveFromPlayerLoop();
const string useLegacyLightmapsKeyword = "USE_LEGACY_LIGHTMAPS";
Shader.DisableKeyword(useLegacyLightmapsKeyword);
m_WorldProcessor.Dispose();
m_WorldProcessor = null;
#if ENABLE_PROFILER
DisposePipelineRecorders();
#endif
#if ENABLE_TERRAIN_MODULE
m_SpeedTreeWindGPUDataUpdater.Dispose();
m_SpeedTreeWindGPUDataUpdater = null;
#endif
m_Batcher.Dispose();
m_Batcher = null;
m_OcclusionCullingCommon?.Dispose();
m_OcclusionCullingCommon = null;
m_Culler.Dispose();
m_Culler = null;
m_InstanceDataSystem.Dispose();
m_InstanceDataSystem = null;
m_LODGroupDataSystem.Dispose();
m_LODGroupDataSystem = null;
m_GRDContext.Dispose();
m_GRDContext = null;
m_ObjectDispatcher.Dispose();
m_ObjectDispatcher = null;
m_GPUDrivenProcessor.Dispose();
m_GPUDrivenProcessor = null;
m_ContextIntPtr = IntPtr.Zero;
Console.WriteLine($"GPU Resident Drawer disposed.");
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
// Loaded scene might contain light probes that would affect existing objects. Hence we have to update all probes data.
if (mode == LoadSceneMode.Additive)
UpdateAmbientProbeAndGPUBuffer(forceUpdate: true);
}
private static void PostPostLateUpdateStatic()
{
s_Instance?.PostPostLateUpdate();
}
#if UNITY_EDITOR
// If running in the editor the player loop might not run
// In order to still have a single frame update we keep track of the camera ids
// A frame update happens in case the first camera is rendered again
// Note: This doesn't run when using built-in debug views such as lightmaps, shadowmask and etc
private void EditorFrameUpdate(List<Camera> cameras)
{
bool newFrame = false;
foreach (Camera camera in cameras)
{
EntityId instanceID = camera.GetEntityId();
if (m_FrameCameraIDs.Length == 0 || m_FrameCameraIDs.Contains(instanceID))
{
newFrame = true;
m_FrameCameraIDs.Clear();
}
m_FrameCameraIDs.Add(instanceID);
}
if (newFrame)
{
if (m_FrameUpdateNeeded)
{
CullerUpdateFrame();
}
else
{
m_FrameUpdateNeeded = true;
}
}
}
#endif
private void OnBeginContextRendering(ScriptableRenderContext context, List<Camera> cameras)
{
// This logic ensures that EditorFrameUpdate is not called more than once after calling BeginContextRendering, unless EndContextRendering has also been called.
if (m_ContextIntPtr == IntPtr.Zero)
{
m_ContextIntPtr = context.Internal_GetPtr();
#if UNITY_EDITOR
EditorFrameUpdate(cameras);
#endif
#if ENABLE_TERRAIN_MODULE
m_SpeedTreeWindGPUDataUpdater.OnBeginContextRendering();
#endif
}
if (m_DebugDisplaySettings == null)
m_DebugDisplaySettings = DebugDisplaySerializer.Get<DebugDisplayGPUResidentDrawer>();
}
private void OnEndContextRendering(ScriptableRenderContext context, List<Camera> cameras)
{
ParallelBitArray compactedVisibilityMasks = m_Culler.GetCompactedVisibilityMasks(syncCullingJobs: true);
if (m_ContextIntPtr == context.Internal_GetPtr())
{
m_ContextIntPtr = IntPtr.Zero;
if (compactedVisibilityMasks.IsCreated)
m_InstanceDataSystem.UpdatePerFrameInstanceVisibility(compactedVisibilityMasks);
}
}
private void OnBeginCameraRendering(ScriptableRenderContext context, Camera camera)
{
m_Culler.OnBeginCameraRendering(camera);
}
private void OnEndCameraRendering(ScriptableRenderContext context, Camera camera)
{
m_Culler.OnEndCameraRendering(camera);
}
private void OnFinishedCulling(IntPtr customCullingResult)
{
m_Culler.EnsureValidOcclusionTestResults(viewID : EntityId.FromULong((ulong)customCullingResult));
#if ENABLE_TERRAIN_MODULE
m_SpeedTreeWindGPUDataUpdater.UpdateGPUData();
#endif
}
private void OnPostCullBeginCameraRendering(RenderRequestBatcherContext context) {}
private void UpdateAmbientProbeAndGPUBuffer(bool forceUpdate)
{
if (forceUpdate || m_GRDContext.cachedAmbientProbe != RenderSettings.ambientProbe)
{
m_GRDContext.cachedAmbientProbe = RenderSettings.ambientProbe;
m_InstanceDataSystem.UpdateAllInstanceProbes();
}
}
private void CullerUpdateFrame()
{
m_Culler.UpdateFrame(m_InstanceDataSystem.renderWorld.cameraCount);
m_OcclusionCullingCommon.UpdateFrame();
if (m_GRDContext.debugStats != null)
m_OcclusionCullingCommon.UpdateOccluderStats(m_GRDContext.debugStats);
}
#if ENABLE_PROFILER
// Count GRD-path renderers whose renderingEnabled bit is currently false (toggled
// disabled at runtime, after registration). Combined with the registration-snapshot
// inactive count for the Coverage card's footer. Cheap: popcnt over a packed bit array.
private void UpdateLiveDisabledGRDCount()
{
var advStats = m_GRDContext?.advancedDebugStats;
if (advStats == null)
return;
ref var renderWorld = ref m_InstanceDataSystem.renderWorld;
int instanceCount = renderWorld.instanceCount;
if (instanceCount <= 0)
{
advStats.liveDisabledGRDCount = 0;
return;
}
var bits = renderWorld.renderingEnabled;
int chunkCount = bits.ChunkCount();
int activeBits = 0;
int fullChunks = instanceCount / 64;
for (int i = 0; i < fullChunks; i++)
activeBits += Unity.Mathematics.math.countbits((long)bits.GetChunk(i));
int tailBits = instanceCount & 63;
if (tailBits > 0 && fullChunks < chunkCount)
{
ulong tailMask = (1ul << tailBits) - 1ul;
activeBits += Unity.Mathematics.math.countbits((long)(bits.GetChunk(fullChunks) & tailMask));
}
advStats.liveDisabledGRDCount = Math.Max(0, instanceCount - activeBits);
}
#endif
private void PostPostLateUpdate()
{
UpdateAmbientProbeAndGPUBuffer(forceUpdate: false);
m_WorldProcessor.Update();
CullerUpdateFrame();
#if ENABLE_PROFILER
// Skip the per-frame counter flush when nothing observes it. ProfilerCounterValue setters
// are cheap individually but we have ~30+ of them; this matters for shipping/development
// builds where Profiler is rarely live. The category gate avoids emitting when the GRD
// Profiler module is hidden even though Profiler.enabled is true. Pipeline recorders
// follow the same gate — allocated and started lazily on first observation, stopped (but
// kept allocated) when observation ceases, fully disposed only on shutdown.
if (UnityEngine.Profiling.Profiler.enabled
&& UnityEngine.Profiling.Profiler.IsCategoryEnabled(GRDProfilerCounters.k_Category))
{
EnsurePipelineRecordersRunning();
UpdateLiveDisabledGRDCount();
GRDPipelineStats pipelineStats = ReadPipelineStatsFromRecorders();
GRDProfilerCounters.EmitAll(m_GRDContext.advancedDebugStats, pipelineStats);
}
else
{
StopPipelineRecordersIfRunning();
}
#endif
#if UNITY_EDITOR
m_FrameUpdateNeeded = false;
#endif
}
#if ENABLE_PROFILER
// Pipeline timing reads existing ProfilerMarkers around the dispatch helpers — single
// source of truth with the Profiler trace.
//
// Culling Schedule covers only the CreateCullJobTree dispatch call; worker-thread job
// execution is not included.
ProfilerRecorder m_RecProbeDispatch;
ProfilerRecorder m_RecMotionDispatch;
ProfilerRecorder m_RecTransformDispatch;
ProfilerRecorder m_RecComponentOverride;
ProfilerRecorder m_RecBuildBatches;
ProfilerRecorder m_RecRegisterMaterialsAndMeshes;
ProfilerRecorder m_RecCreateCullJobTree;
ProfilerRecorder m_RecWorldProcessorUpdate;
bool m_PipelineRecordersRunning;
// Pattern mirrors ProfilingSampler.enableRecording: allocate the recorder lazily on first
// start, then Stop/Start for subsequent toggles to keep the native sampling slot reserved
// without re-allocating. Avoids holding sampling capacity when nobody is observing.
static void StartOrResume(ref ProfilerRecorder rec, ProfilerMarker marker)
{
if (!rec.Valid)
rec = ProfilerRecorder.StartNew(marker, 1, ProfilerRecorderOptions.Default);
else
rec.Start();
}
void EnsurePipelineRecordersRunning()
{
if (m_PipelineRecordersRunning)
return;
StartOrResume(ref m_RecProbeDispatch, InstanceDataSystem.k_DispatchProbeUpdateCommand);
StartOrResume(ref m_RecMotionDispatch, InstanceDataSystem.k_DispatchMotionUpdateCommand);
StartOrResume(ref m_RecTransformDispatch, InstanceDataSystem.k_DispatchTransformUpdateCommand);
StartOrResume(ref m_RecComponentOverride, MeshRendererProcessor.k_UploadGPUComponentOverrides);
StartOrResume(ref m_RecBuildBatches, InstanceCullingBatcher.k_BuildBatches);
StartOrResume(ref m_RecRegisterMaterialsAndMeshes, InstanceCullingBatcher.k_RegisterMaterialsAndMeshes);
StartOrResume(ref m_RecCreateCullJobTree, InstanceCullingBatcher.k_CreateCullJobTree);
StartOrResume(ref m_RecWorldProcessorUpdate, WorldProcessor.k_Update);
m_PipelineRecordersRunning = true;
}
void StopPipelineRecordersIfRunning()
{
if (!m_PipelineRecordersRunning)
return;
if (m_RecProbeDispatch.Valid) m_RecProbeDispatch.Stop();
if (m_RecMotionDispatch.Valid) m_RecMotionDispatch.Stop();
if (m_RecTransformDispatch.Valid) m_RecTransformDispatch.Stop();
if (m_RecComponentOverride.Valid) m_RecComponentOverride.Stop();
if (m_RecBuildBatches.Valid) m_RecBuildBatches.Stop();
if (m_RecRegisterMaterialsAndMeshes.Valid) m_RecRegisterMaterialsAndMeshes.Stop();
if (m_RecCreateCullJobTree.Valid) m_RecCreateCullJobTree.Stop();
if (m_RecWorldProcessorUpdate.Valid) m_RecWorldProcessorUpdate.Stop();
m_PipelineRecordersRunning = false;
}
void DisposePipelineRecorders()
{
m_RecProbeDispatch.Dispose();
m_RecMotionDispatch.Dispose();
m_RecTransformDispatch.Dispose();
m_RecComponentOverride.Dispose();
m_RecBuildBatches.Dispose();
m_RecRegisterMaterialsAndMeshes.Dispose();
m_RecCreateCullJobTree.Dispose();
m_RecWorldProcessorUpdate.Dispose();
m_PipelineRecordersRunning = false;
}
GRDPipelineStats ReadPipelineStatsFromRecorders()
{
long probe = m_RecProbeDispatch.LastValue;
long motion = m_RecMotionDispatch.LastValue;
long transform = m_RecTransformDispatch.LastValue;
long compOverride = m_RecComponentOverride.LastValue;
long batchBuild = m_RecBuildBatches.LastValue + m_RecRegisterMaterialsAndMeshes.LastValue;
long worldProcessor = m_RecWorldProcessorUpdate.LastValue;
long upload = probe + motion + transform + compOverride;
var stats = new GRDPipelineStats();
stats.uploadDetail.probeDispatchTime = NsToMs(probe);
stats.uploadDetail.motionDispatchTime = NsToMs(motion);
stats.uploadDetail.transformDispatchTime = NsToMs(transform);
stats.uploadDetail.componentOverrideTime = NsToMs(compOverride);
stats.batchBuildingTime = NsToMs(batchBuild);
stats.cullingScheduleTime = NsToMs(m_RecCreateCullJobTree.LastValue);
stats.cpuToGpuUploadTime = NsToMs(upload);
// Residual: WorldProcessor.Update minus the sub-stages that run inside it.
// Clamp at zero — sample boundaries between nested markers can drive the diff slightly
// negative on cheap frames.
stats.dataCollectionTime = NsToMs(Math.Max(0L, worldProcessor - batchBuild - upload));
return stats;
}
static float NsToMs(long ns) => ns * 1e-6f;
#endif // ENABLE_PROFILER
#else
// Public API stubs
public static bool IsInstanceOcclusionCullingEnabled() => false;
public static void PostCullBeginCameraRendering(RenderRequestBatcherContext context) {}
public static void OnSetupAmbientProbe() {}
public static void InstanceOcclusionTest(RenderGraph renderGraph, in OcclusionCullingSettings settings, ReadOnlySpan<SubviewOcclusionTest> subviewOcclusionTests) {}
public static void UpdateInstanceOccluders(RenderGraph renderGraph, in OccluderParameters occluderParameters, ReadOnlySpan<OccluderSubviewUpdate> occluderSubviewUpdates) {}
public static void ReinitializeIfNeeded() {}
public static void RenderDebugOcclusionTestOverlay(RenderGraph renderGraph, DebugDisplayGPUResidentDrawer debugSettings, EntityId viewID, TextureHandle colorBuffer) {}
public static void RenderDebugOccluderOverlay(RenderGraph renderGraph, DebugDisplayGPUResidentDrawer debugSettings, Vector2 screenPos, float maxHeight, TextureHandle colorBuffer) {}
// Internal stubs (for e.g. IGPUResidentRenderPipeline)
internal static bool IsInitialized() => false;
internal static void Reinitialize() {}
// Internal stubs (for tests)
internal static bool IsForcedOnViaCommandLine() => false;
internal static bool IsOcclusionForcedOnViaCommandLine() => false;
internal static bool MaintainContext { get; set; }
internal static bool ForceOcclusion { get; set; }
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 723b7447e23e2b5429e727c3b3a76834
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,123 @@
using System;
namespace UnityEngine.Rendering
{
/// <summary> Class for tracking resources used by the GPUResidentDrawer </summary>
[Serializable]
[SupportedOnRenderPipeline]
[Categorization.CategoryInfo(Name = "R: GPU Resident Drawers", Order = 1000), HideInInspector]
class GPUResidentDrawerResources : IRenderPipelineResources
{
public enum Version
{
Initial,
Count,
Latest = Count - 1
}
[SerializeField, HideInInspector] Version m_Version = Version.Latest;
int IRenderPipelineGraphicsSettings.version => (int)m_Version;
[SerializeField, ResourcePath("Runtime/RenderPipelineResources/GPUDriven/InstanceDataBufferCopyKernels.compute")]
ComputeShader m_InstanceDataBufferCopyKernels;
/// <summary> InstanceDataBufferCopyKernels compute shader reference </summary>
public ComputeShader instanceDataBufferCopyKernels
{
get => m_InstanceDataBufferCopyKernels;
set => this.SetValueAndNotify(ref m_InstanceDataBufferCopyKernels, value, nameof(m_InstanceDataBufferCopyKernels));
}
[SerializeField, ResourcePath("Runtime/RenderPipelineResources/GPUDriven/InstanceDataBufferUploadKernels.compute")]
ComputeShader m_InstanceDataBufferUploadKernels;
/// <summary> InstanceDataBufferUploadKernels compute shader reference </summary>
public ComputeShader instanceDataBufferUploadKernels
{
get => m_InstanceDataBufferUploadKernels;
set => this.SetValueAndNotify(ref m_InstanceDataBufferUploadKernels, value, nameof(m_InstanceDataBufferUploadKernels));
}
[SerializeField, ResourcePath("Runtime/RenderPipelineResources/GPUDriven/InstanceTransformUpdateKernels.compute")]
ComputeShader m_TransformUpdaterKernels;
/// <summary> TransformUpdaterKernels compute shader reference </summary>
public ComputeShader transformUpdaterKernels
{
get => m_TransformUpdaterKernels;
set => this.SetValueAndNotify(ref m_TransformUpdaterKernels, value, nameof(m_TransformUpdaterKernels));
}
[SerializeField, ResourcePath("Runtime/RenderPipelineResources/GPUDriven/InstanceWindDataUpdateKernels.compute")]
public ComputeShader m_WindDataUpdaterKernels;
/// <summary>
/// InstanceWindDataUpdateKernels compute shader reference
/// </summary>
public ComputeShader windDataUpdaterKernels
{
get => m_WindDataUpdaterKernels;
set => this.SetValueAndNotify(ref m_WindDataUpdaterKernels, value, nameof(m_WindDataUpdaterKernels));
}
[SerializeField, ResourcePath("Runtime/RenderPipelineResources/GPUDriven/OccluderDepthPyramidKernels.compute")]
ComputeShader m_OccluderDepthPyramidKernels;
/// <summary>
/// OccluderDepthPyramidKernels compute shader reference
/// </summary>
public ComputeShader occluderDepthPyramidKernels
{
get => m_OccluderDepthPyramidKernels;
set => this.SetValueAndNotify(ref m_OccluderDepthPyramidKernels, value, nameof(m_OccluderDepthPyramidKernels));
}
[SerializeField, ResourcePath("Runtime/RenderPipelineResources/GPUDriven/InstanceOcclusionCullingKernels.compute")]
ComputeShader m_InstanceOcclusionCullingKernels;
/// <summary>
/// InstanceOcclusionCullingKernels compute shader reference
/// </summary>
public ComputeShader instanceOcclusionCullingKernels
{
get => m_InstanceOcclusionCullingKernels;
set => this.SetValueAndNotify(ref m_InstanceOcclusionCullingKernels, value, nameof(m_InstanceOcclusionCullingKernels));
}
[SerializeField, ResourcePath("Runtime/RenderPipelineResources/GPUDriven/OcclusionCullingDebug.compute")]
ComputeShader m_OcclusionCullingDebugKernels;
/// <summary>
/// OcclusionCullingDebugKernels compute shader reference
/// </summary>
public ComputeShader occlusionCullingDebugKernels
{
get => m_OcclusionCullingDebugKernels;
set => this.SetValueAndNotify(ref m_OcclusionCullingDebugKernels, value, nameof(m_OcclusionCullingDebugKernels));
}
[SerializeField, ResourcePath("Runtime/RenderPipelineResources/GPUDriven/DebugOcclusionTest.shader")]
Shader m_DebugOcclusionTestPS;
/// <summary>
/// DebugOcclusionTestPS pixel shader reference
/// </summary>
public Shader debugOcclusionTestPS
{
get => m_DebugOcclusionTestPS;
set => this.SetValueAndNotify(ref m_DebugOcclusionTestPS, value, nameof(m_DebugOcclusionTestPS));
}
[SerializeField, ResourcePath("Runtime/RenderPipelineResources/GPUDriven/DebugOccluder.shader")]
Shader m_DebugOccluderPS;
/// <summary>
/// DebugOccluderPS pixel shader reference
/// </summary>
public Shader debugOccluderPS
{
get => m_DebugOccluderPS;
set => this.SetValueAndNotify(ref m_DebugOccluderPS, value, nameof(m_DebugOccluderPS));
}
}
}

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