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,17 @@
using System;
using UnityEngine.Rendering;
namespace UnityEngine.PathTracing.Lightmapping
{
internal static class AdaptiveSamplingHelpers
{
internal const float AdaptiveThreshold_00 = 0.0f; // Accept no error
internal const float AdaptiveThreshold_01 = 0.01f / 2.58f; // Accept 1% error using 99% confidence interval
internal const float AdaptiveThreshold_05 = 0.05f / 1.96f; // Accept 5% error using 95% confidence interval
internal const float AdaptiveThreshold_10 = 0.10f / 1.645f; // Accept 10% error using 90% confidence interval
internal const float AdaptiveThreshold_20 = 0.20f / 1.285f; // Accept 20% error using 80% confidence interval
internal const float AdaptiveThreshold_30 = 0.30f / 1.035f; // Accept 30% error using 70% confidence interval
internal const float AdaptiveThreshold_40 = 0.40f / 0.845f; // Accept 40% error using 60% confidence interval
internal const float AdaptiveThreshold_50 = 0.50f / 0.675f; // Accept 50% error using 50% confidence interval
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2555d7f783a93094cb7bd2e7f54feca1
@@ -0,0 +1,15 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("Unity.Rendering.GIPreview.Editor.Tests")]
[assembly: InternalsVisibleTo("Unity.PathTracing.Editor.Tests")]
[assembly: InternalsVisibleTo("Unity.PathTracing.Runtime.Tests")]
[assembly: InternalsVisibleTo("Assembly-CSharp-Editor-testable")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Runtime")]
[assembly: InternalsVisibleTo("Unity.PathTracing.Editor")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Core.Editor")]
[assembly: InternalsVisibleTo("Unity.SurfaceCache.Runtime")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Core.Editor.Tests")]
[assembly: InternalsVisibleTo("Unity.SurfaceCache.Tests")]
[assembly: InternalsVisibleTo("Assembly-CSharp-testable")]
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: d2dd2e13c500b9944a6ad6cf50cbbe8d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,306 @@
using System;
using Unity.Mathematics;
using UnityEngine.Experimental.Rendering;
using UnityEngine.PathTracing.Integration;
using UnityEngine.PathTracing.Core;
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
using UnityEngine.Rendering.Sampling;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.PathTracing.Lightmapping
{
using InstanceHandle = Handle<World.InstanceKey>;
using MaterialHandle = Handle<MaterialPool.MaterialDescriptor>;
internal struct LodInstanceBuildData
{
public int LodMask;
public Mesh Mesh;
public MaterialHandle[] Materials;
public uint[] Masks;
public Matrix4x4 LocalToWorldMatrix;
public Bounds Bounds;
public bool IsStatic;
public RenderedGameObjectsFilter Filter;
}
internal struct LodIdentifier
{
public LodIdentifier(Int32 lodGroup, byte lodMask, Int32 lodContributorLevel)
{
this.LodGroup = lodGroup;
this.LodMask = lodMask;
this.LodContributorLevel = lodContributorLevel;
}
public Int32 LodGroup;
public byte LodMask;
Int32 LodContributorLevel;
public override int GetHashCode() => HashCode.Combine(LodGroup, LodMask);
public override bool Equals(object obj) => obj is LodIdentifier other && other.LodGroup == LodGroup && other.LodMask == LodMask;
public static readonly LodIdentifier Invalid = new LodIdentifier(-1, 0, -1);
public bool IsValid() => LodGroup != -1;
public bool IsContributor()
{
if (LodContributorLevel == -1) return false;
return (LodMask & (1 << LodContributorLevel)) != 0;
}
public byte MinLodLevelMask() { return (byte)(LodMask & -LodMask); }
}
internal struct ContributorLodInfo
{
public InstanceHandle InstanceHandle;
public uint[] Masks;
public int LodMask;
}
internal struct FatInstance
{
public BoundingSphere BoundingSphere;
public Mesh Mesh;
public Vector2 UVBoundsSize;
public Vector2 UVBoundsOffset;
public MaterialHandle[] Materials;
public uint[] SubMeshMasks;
public Matrix4x4 LocalToWorldMatrix;
public Bounds Bounds;
public bool IsStatic;
public LodIdentifier LodIdentifier;
public bool ReceiveShadows;
public RenderedGameObjectsFilter Filter;
public uint RenderingObjectLayer;
public bool EnableEmissiveSampling;
public bool IsProceduralTerrain;
public int TerrainIndex;
}
internal struct BakeInstance
{
public Mesh Mesh;
public Vector4 NormalizedOccupiedST; // Transforms coordinates in [0; 1] range into the occupied rectangle in the lightmap atlas, also in [0; 1] range.
public Vector4 SourceLightmapST;
public Vector2Int TexelSize; // Instance size in the lightmap atlas, in pixels.
public Vector2Int TexelOffset; // Instance offset in the lightmap atlas, in pixels.
public Matrix4x4 LocalToWorldMatrix;
public Matrix4x4 LocalToWorldMatrixNormals;
public bool ReceiveShadows;
public LodIdentifier LodIdentifier;
public uint InstanceIndex; // Index of the instance in BakeInput
public bool IsProceduralTerrain;
public int TerrainIndex;
private static float4x4 NormalMatrix(float4x4 m)
{
float3x3 t = new float3x3(m);
return new float4x4(math.inverse(math.transpose(t)), new float3(0.0));
}
public BoundingSphere GetBoundingSphere()
{
var boundingSphere = new BoundingSphere();
boundingSphere.position = LocalToWorldMatrix.MultiplyPoint(Mesh.bounds.center);
boundingSphere.radius = (LocalToWorldMatrix.MultiplyPoint(Mesh.bounds.extents) - boundingSphere.position).magnitude;
return boundingSphere;
}
public void Build(Mesh mesh, Vector4 normalizedOccupiedST, Vector4 sourceLightmapST, Vector2Int texelSize, Vector2Int texelOffset, Matrix4x4 localToWorldMatrix, bool receiveShadows, LodIdentifier lodIdentifier, uint instanceIndex, bool isProceduralTerrain, int terrainIndex)
{
Mesh = mesh;
NormalizedOccupiedST = normalizedOccupiedST;
SourceLightmapST = sourceLightmapST;
TexelSize = texelSize;
TexelOffset = texelOffset;
LocalToWorldMatrix = localToWorldMatrix;
ReceiveShadows = receiveShadows;
LocalToWorldMatrixNormals = NormalMatrix(this.LocalToWorldMatrix);
LodIdentifier = lodIdentifier;
InstanceIndex = instanceIndex;
IsProceduralTerrain = isProceduralTerrain;
TerrainIndex = terrainIndex;
}
}
internal class LightmapDesc
{
public uint Resolution;
public float PushOff;
public BakeInstance[] BakeInstances;
}
internal enum IntegratedOutputType
{
Direct,
DirectBRDF,
Indirect,
AO,
Validity,
DirectionalityDirect,
DirectionalityDirectBRDF,
DirectionalityIndirect,
ShadowMask
}
internal class LightmapIntegratorContext : IDisposable
{
internal UVFallbackBufferBuilder UVFallbackBufferBuilder;
internal LightmapDirectIntegrator LightmapDirectIntegrator;
internal LightmapDirectBRDFIntegrator LightmapDirectBRDFIntegrator;
internal LightmapIndirectIntegrator LightmapIndirectIntegrator;
internal LightmapAOIntegrator LightmapAOIntegrator;
internal LightmapValidityIntegrator LightmapValidityIntegrator;
internal LightmapOccupancyIntegrator LightmapOccupancyIntegrator;
internal LightmapShadowMaskIntegrator LightmapShadowMaskIntegrator;
internal GBufferDebug GBufferDebugShader;
internal IRayTracingShader GBufferShader;
internal ComputeShader ExpansionShaders;
internal SamplingResources SamplingResources;
private RTHandle _emptyExposureTexture;
internal GraphicsBuffer ClearDispatchBuffer;
internal GraphicsBuffer CopyDispatchBuffer;
internal GraphicsBuffer ReduceDispatchBuffer;
internal GraphicsBuffer CompactedGBufferLength;
internal int CompactGBufferKernel;
internal int PopulateAccumulationDispatchKernel;
internal int PopulateClearDispatchKernel;
internal int PopulateCopyDispatchKernel;
internal int PopulateReduceDispatchKernel;
internal int ClearBufferKernel;
internal int ReductionKernel;
internal int CopyToLightmapKernel;
public void Dispose()
{
UVFallbackBufferBuilder?.Dispose();
UVFallbackBufferBuilder = null;
LightmapDirectIntegrator?.Dispose();
LightmapDirectIntegrator = null;
LightmapDirectBRDFIntegrator?.Dispose();
LightmapDirectBRDFIntegrator = null;
LightmapIndirectIntegrator?.Dispose();
LightmapIndirectIntegrator = null;
LightmapAOIntegrator?.Dispose();
LightmapAOIntegrator = null;
LightmapValidityIntegrator?.Dispose();
LightmapValidityIntegrator = null;
LightmapOccupancyIntegrator = null;
LightmapShadowMaskIntegrator?.Dispose();
LightmapShadowMaskIntegrator = null;
GBufferDebugShader?.Dispose();
GBufferDebugShader = null;
_emptyExposureTexture?.Release();
_emptyExposureTexture = null;
ClearDispatchBuffer?.Dispose();
CopyDispatchBuffer?.Dispose();
ReduceDispatchBuffer?.Dispose();
CompactedGBufferLength?.Dispose();
}
internal void Initialize(SamplingResources samplingResources, LightmapResourceLibrary lightmapResourceLib)
{
SamplingResources = samplingResources;
_emptyExposureTexture = RTHandles.Alloc(1, 1, enableRandomWrite: true, name: "Empty EV100 Exposure", colorFormat: GraphicsFormat.R8G8B8A8_UNorm);
UVFallbackBufferBuilder = new UVFallbackBufferBuilder();
UVFallbackBufferBuilder.Prepare(lightmapResourceLib.UVFallbackBufferGenerationMaterial);
LightmapDirectIntegrator = new LightmapDirectIntegrator();
LightmapDirectIntegrator.Prepare(lightmapResourceLib.DirectStochasticLightShader, lightmapResourceLib.DirectDirectionalAndEnvironmentShader, lightmapResourceLib.NormalizationShader, lightmapResourceLib.ExpansionHelpers, SamplingResources, _emptyExposureTexture);
LightmapDirectBRDFIntegrator = new LightmapDirectBRDFIntegrator();
LightmapDirectBRDFIntegrator.Prepare(lightmapResourceLib.DirectBRDFAccumulationShader, lightmapResourceLib.NormalizationShader, lightmapResourceLib.ExpansionHelpers, SamplingResources, _emptyExposureTexture);
LightmapIndirectIntegrator = new LightmapIndirectIntegrator();
LightmapIndirectIntegrator.Prepare(lightmapResourceLib.IndirectAccumulationShader, lightmapResourceLib.NormalizationShader, lightmapResourceLib.ExpansionHelpers, SamplingResources, _emptyExposureTexture);
LightmapAOIntegrator = new LightmapAOIntegrator();
LightmapAOIntegrator.Prepare(lightmapResourceLib.AOAccumulationShader, lightmapResourceLib.NormalizationShader, lightmapResourceLib.ExpansionHelpers, SamplingResources, _emptyExposureTexture);
LightmapValidityIntegrator = new LightmapValidityIntegrator();
LightmapValidityIntegrator.Prepare(lightmapResourceLib.ValidityAccumulationShader, lightmapResourceLib.NormalizationShader, lightmapResourceLib.ExpansionHelpers, SamplingResources, _emptyExposureTexture);
LightmapOccupancyIntegrator = new LightmapOccupancyIntegrator();
LightmapOccupancyIntegrator.Prepare(lightmapResourceLib.OccupancyShader);
LightmapShadowMaskIntegrator = new LightmapShadowMaskIntegrator();
LightmapShadowMaskIntegrator.Prepare(lightmapResourceLib.ShadowMaskAccumulationShader, lightmapResourceLib.NormalizationShader, lightmapResourceLib.ExpansionHelpers, SamplingResources, _emptyExposureTexture);
GBufferDebugShader = new GBufferDebug();
GBufferDebugShader.Prepare(lightmapResourceLib.GBufferDebugShader, lightmapResourceLib.ExpansionHelpers);
GBufferShader = lightmapResourceLib.GBufferShader;
ExpansionShaders = lightmapResourceLib.ExpansionHelpers;
CompactGBufferKernel = ExpansionShaders.FindKernel("CompactGBuffer");
PopulateAccumulationDispatchKernel = ExpansionShaders.FindKernel("PopulateAccumulationDispatch");
PopulateClearDispatchKernel = ExpansionShaders.FindKernel("PopulateClearDispatch");
PopulateCopyDispatchKernel = ExpansionShaders.FindKernel("PopulateCopyDispatch");
PopulateReduceDispatchKernel = ExpansionShaders.FindKernel("PopulateReduceDispatch");
ClearBufferKernel = ExpansionShaders.FindKernel("ClearFloat4Buffer");
ReductionKernel = ExpansionShaders.FindKernel("BinaryGroupSumLeft");
CopyToLightmapKernel = ExpansionShaders.FindKernel("AdditivelyCopyCompactedTo2D");
ClearDispatchBuffer = new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments | GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource | GraphicsBuffer.Target.CopyDestination, 3, sizeof(uint));
CopyDispatchBuffer = new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments | GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource | GraphicsBuffer.Target.CopyDestination, 3, sizeof(uint));
ReduceDispatchBuffer = new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments | GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource | GraphicsBuffer.Target.CopyDestination, 3, sizeof(uint));
CompactedGBufferLength = new GraphicsBuffer(GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource, 1, sizeof(uint));
}
}
internal class LightmapResourceLibrary
{
internal IRayTracingShader GBufferShader;
internal ComputeShader NormalizationShader;
internal IRayTracingShader DirectStochasticLightShader;
internal IRayTracingShader DirectBRDFAccumulationShader;
internal IRayTracingShader DirectDirectionalAndEnvironmentShader;
internal IRayTracingShader AOAccumulationShader;
internal IRayTracingShader ValidityAccumulationShader;
internal IRayTracingShader IndirectAccumulationShader;
internal IRayTracingShader ShadowMaskAccumulationShader;
internal IRayTracingShader NormalAccumulationShader;
internal IRayTracingShader GBufferDebugShader;
internal Material UVFallbackBufferGenerationMaterial;
internal ComputeShader OccupancyShader;
internal LightmapIntegrationHelpers.ComputeHelpers ComputeHelpers;
internal ComputeShader BoxFilterShader;
internal ComputeShader SelectGraphicsBufferShader;
internal ComputeShader CopyTextureAdditiveShader;
internal ComputeShader ExpansionHelpers;
internal Shader SoftwareChartRasterizationShader;
internal Shader HardwareChartRasterizationShader;
#if UNITY_EDITOR
public void Load(RayTracingContext context)
{
const string packageFolder = "Packages/com.unity.render-pipelines.core/Runtime/PathTracing/";
GBufferShader = context.LoadRayTracingShader(packageFolder + "Shaders/LightmapGBufferIntegration.urtshader");
NormalizationShader = AssetDatabase.LoadAssetAtPath<ComputeShader>(packageFolder + "Shaders/ResolveAccumulation.compute");
DirectStochasticLightShader = context.LoadRayTracingShader(packageFolder + "Shaders/LightmapDirectStochasticLightIntegration.urtshader");
DirectBRDFAccumulationShader = context.LoadRayTracingShader(packageFolder + "Shaders/LightmapDirectBRDFIntegration.urtshader");
DirectDirectionalAndEnvironmentShader = context.LoadRayTracingShader(packageFolder + "Shaders/LightmapDirectDirectionalAndEnvironmentIntegration.urtshader");
AOAccumulationShader = context.LoadRayTracingShader(packageFolder + "Shaders/LightmapAOIntegration.urtshader");
ValidityAccumulationShader = context.LoadRayTracingShader(packageFolder + "Shaders/LightmapValidityIntegration.urtshader");
IndirectAccumulationShader = context.LoadRayTracingShader(packageFolder + "Shaders/LightmapIndirectIntegration.urtshader");
ShadowMaskAccumulationShader = context.LoadRayTracingShader(packageFolder + "Shaders/LightmapShadowMaskIntegration.urtshader");
GBufferDebugShader = context.LoadRayTracingShader(packageFolder + "Shaders/LightmapGBufferDebug.urtshader");
NormalAccumulationShader = context.LoadRayTracingShader(packageFolder + "Shaders/LightmapNormalIntegration.urtshader");
UVFallbackBufferGenerationMaterial = new Material(AssetDatabase.LoadAssetAtPath<Shader>(packageFolder + "Shaders/Lightmapping/UVFallbackBufferGeneration.shader"));
OccupancyShader = AssetDatabase.LoadAssetAtPath<ComputeShader>(packageFolder + "Shaders/LightmapOccupancy.compute");
ExpansionHelpers = AssetDatabase.LoadAssetAtPath<ComputeShader>(packageFolder + "Shaders/ExpansionHelpers.compute");
ComputeHelpers = new LightmapIntegrationHelpers.ComputeHelpers();
ComputeHelpers.Load();
ChartRasterizer.LoadShaders(out SoftwareChartRasterizationShader, out HardwareChartRasterizationShader);
BoxFilterShader = ComputeHelpers.ComputeHelperShader;
SelectGraphicsBufferShader = ComputeHelpers.ComputeHelperShader;
CopyTextureAdditiveShader = ComputeHelpers.ComputeHelperShader;
}
#endif
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e53fede703e0349479a0fba60658fa50
@@ -0,0 +1,489 @@
using System;
using Unity.Mathematics;
using Unity.Profiling;
using Unity.Profiling.LowLevel;
using UnityEngine.PathTracing.Core;
using UnityEngine.PathTracing.Integration;
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
namespace UnityEngine.PathTracing.Lightmapping
{
internal static class BakeLightmapDriver
{
/// <summary>
/// Profiles a single per-instance lightmap accumulation step, spanning GBuffer sampling,
/// path-tracing dispatch, and all output integrators (direct, indirect, AO, validity, shadow mask).
/// </summary>
static readonly ProfilerMarker k_AccumulateLightmapInstance =
new ProfilerMarker(ProfilerCategory.Render, "AccumulateLightmapInstance",
MarkerFlags.Default | MarkerFlags.SampleGPU);
public class LightmapBakeState
{
public uint SampleIndex;
public UInt64 TexelIndex;
public void Init()
{
SampleIndex = 0;
TexelIndex = 0;
}
public void Tick(uint passSampleCount, uint totalSampleCount, UInt64 chunkTexelCount, UInt64 totalTexelCount, out bool instanceIsDone, out bool chunkIsDone)
{
instanceIsDone = false;
chunkIsDone = false;
SampleIndex += passSampleCount;
Debug.Assert(SampleIndex <= totalSampleCount);
if (SampleIndex == totalSampleCount)
{
// a chunk is done since we have reached `totalSampleCount`
chunkIsDone = true;
TexelIndex += chunkTexelCount;
SampleIndex = 0;
}
Debug.Assert(TexelIndex <= totalTexelCount);
if (TexelIndex == totalTexelCount)
{
// an instance is done since we have reached `totalTexelCount`
instanceIsDone = true;
}
}
}
public struct IntegrationSettings
{
public RayTracingBackend Backend;
public uint MaxDispatchesPerFlush; // how many dispatches to do before flushing the GPU
public bool DebugDispatches;
public static readonly IntegrationSettings Default = new IntegrationSettings
{
Backend = RayTracingBackend.Compute,
MaxDispatchesPerFlush = 1,
DebugDispatches = false
};
}
public class LightmapBakeSettings
{
public uint AOSampleCount = 32;
public uint DirectSampleCount = 32;
public uint DirectBRDFSampleCount = 32;
public uint IndirectSampleCount = 512;
public uint ValiditySampleCount = 512;
public AntiAliasingType AOAntiAliasingType = AntiAliasingType.Stochastic;
public AntiAliasingType DirectAntiAliasingType = AntiAliasingType.SuperSampling;
public AntiAliasingType IndirectAntiAliasingType = AntiAliasingType.Stochastic;
public AntiAliasingType ValidityAntiAliasingType = AntiAliasingType.Stochastic;
public uint BounceCount = 4;
public float AOMaxDistance = 1.0f;
public float PushOff = 0.00001f;
public UInt64 ExpandedBufferSize = 524288;
public LightSamplingMode DirectLightSamplingMode;
public uint DirectRISCandidateCount;
public LightSamplingMode IndirectLightSamplingMode;
public uint IndirectRISCandidateCount;
public EmissiveSamplingMode DirectEmissiveSamplingMode;
public EmissiveSamplingMode IndirectEmissiveSamplingMode;
public uint GetSampleCount(IntegratedOutputType integratedOutputType)
{
switch (integratedOutputType)
{
case IntegratedOutputType.AO: return AOSampleCount;
case IntegratedOutputType.Direct: return DirectSampleCount;
case IntegratedOutputType.DirectBRDF: return DirectBRDFSampleCount;
case IntegratedOutputType.DirectionalityDirect: return DirectSampleCount;
case IntegratedOutputType.DirectionalityDirectBRDF: return DirectBRDFSampleCount;
case IntegratedOutputType.Indirect: return IndirectSampleCount;
case IntegratedOutputType.DirectionalityIndirect: return IndirectSampleCount;
case IntegratedOutputType.Validity: return ValiditySampleCount;
case IntegratedOutputType.ShadowMask: return DirectSampleCount;
default:
Debug.Assert(false, "Unexpected case.");
return 0;
}
}
public AntiAliasingType GetAntiAliasingType(IntegratedOutputType integratedOutputType)
{
switch (integratedOutputType)
{
case IntegratedOutputType.AO: return AOAntiAliasingType;
case IntegratedOutputType.Direct: return DirectAntiAliasingType;
case IntegratedOutputType.DirectBRDF: return DirectAntiAliasingType;
case IntegratedOutputType.DirectionalityDirect: return DirectAntiAliasingType;
case IntegratedOutputType.DirectionalityDirectBRDF: return DirectAntiAliasingType;
case IntegratedOutputType.Indirect: return IndirectAntiAliasingType;
case IntegratedOutputType.DirectionalityIndirect: return IndirectAntiAliasingType;
case IntegratedOutputType.Validity: return ValidityAntiAliasingType;
case IntegratedOutputType.ShadowMask: return DirectAntiAliasingType;
default:
Debug.Assert(false, "Unexpected case.");
return 0;
}
}
}
static bool IsNewChunkStarted(
uint maxChunkSize,
uint instanceWidth,
uint instanceHeight,
uint currentChunkTexelOffset, // current starting texel index for the chunk, linear offset into instanceWidth*instanceHeight
uint currentSampleIndex, // current sample index for the chunk
uint maxSamplesPerTexel, // total sample count per texel
out uint chunkSize, // number of texels to process in a single pass
out uint expandedSampleWidth, // number of expanded samples per texel, power of two, this might exceed the required sample count
out uint passSampleCount, // the actual number of samples to take, this might be smaller than the expanded sample width
out uint2 chunkOffset // the chunk offset in 2D
)
{
// this function should only be called when there is work to do
Debug.Assert(currentSampleIndex < maxSamplesPerTexel);
Debug.Assert(maxChunkSize > 0);
Debug.Assert(instanceWidth > 0);
Debug.Assert(instanceHeight > 0);
Debug.Assert(currentChunkTexelOffset < instanceWidth * instanceHeight);
chunkOffset = new uint2((uint)(currentChunkTexelOffset % (UInt64)instanceWidth), (uint)(currentChunkTexelOffset / (UInt64)instanceWidth));
Debug.Assert(chunkOffset.x < instanceWidth);
Debug.Assert(chunkOffset.y < instanceHeight);
uint remainingTexels = (uint)instanceWidth - chunkOffset.x + ((uint)(instanceHeight - 1) - chunkOffset.y) * (uint)instanceWidth;
Debug.Assert(remainingTexels > 0);
uint remainingSampleCount = math.max(0, maxSamplesPerTexel - currentSampleIndex);
Debug.Assert(remainingSampleCount > 0);
// Choose the size of chunk to take
chunkSize = math.min(remainingTexels, maxChunkSize); // Take as many *texels* as possible in a single pass - this is done to reduce the number of dispatches for compaction, reduction and `copy to lightmap`
Debug.Assert(chunkSize <= maxChunkSize);
// Calculate the maximum number of samples that can be taken in a single pass
uint maxSamplesPerChunk = math.min(maxChunkSize / chunkSize, maxSamplesPerTexel); // The maximum number of samples we can take for the current chunk
Debug.Assert(chunkSize * maxSamplesPerChunk <= maxChunkSize);
// Sample count expansion needs to be a power of 2 - calculate the expansion width
expandedSampleWidth = math.ceilpow2(maxSamplesPerChunk);
if (expandedSampleWidth > maxSamplesPerChunk) expandedSampleWidth /= 2;
Debug.Assert(expandedSampleWidth >= 1);
Debug.Assert(expandedSampleWidth * chunkSize <= maxChunkSize);
// Calculate how many samples we can take in this pass
passSampleCount = math.min(maxSamplesPerChunk, math.min(remainingSampleCount, expandedSampleWidth));
Debug.Assert(passSampleCount > 0);
Debug.Assert(passSampleCount <= expandedSampleWidth);
Debug.Assert(passSampleCount + currentSampleIndex <= maxSamplesPerTexel);
return currentSampleIndex == 0; // When the sample count has rolled back to zero a new chunk has started
}
internal static uint AccumulateLightmapInstance(
LightmapBakeState bakeState,
BakeInstance instance,
LightmapBakeSettings lightmapBakeSettings,
IntegratedOutputType integratedOutputType,
LightmappingContext lightmappingContext,
UVAccelerationStructure uvAS,
UVFallbackBuffer uvFallbackBuffer,
bool doDirectionality,
out uint chunkSize,
out bool instanceIsDone)
{
CommandBuffer cmd = lightmappingContext.GetCommandBuffer();
GraphicsBuffer traceScratchBuffer = lightmappingContext.TraceScratchBuffer;
var ctx = lightmappingContext.IntegratorContext;
var expansionShaders = ctx.ExpansionShaders;
bool doDirectional = doDirectionality || integratedOutputType == IntegratedOutputType.ShadowMask; // Shadowmask uses the directional buffer to store the sample count - so also process that
Vector2Int instanceTexelOffset = instance.TexelOffset;
{
var maxSampleCountPerTexel = lightmapBakeSettings.GetSampleCount(integratedOutputType);
var instanceWidth = instance.TexelSize.x;
var instanceHeight = instance.TexelSize.y;
var instanceTexelCount = (UInt64)instanceWidth * (UInt64)instanceHeight;
var sampleOffset = bakeState.SampleIndex;
var maxChunkSize = (uint)lightmappingContext.ExpandedOutput.count;
bool newChunkStarted = IsNewChunkStarted(
maxChunkSize,
(uint)instanceWidth,
(uint)instanceHeight,
(uint)bakeState.TexelIndex,
sampleOffset,
maxSampleCountPerTexel,
out chunkSize,
out uint expandedSampleWidth,
out uint passSampleCount,
out uint2 chunkOffset);
if (newChunkStarted)
{
// compact the texels
ExpansionHelpers.CompactGBuffer(cmd, expansionShaders, ctx.CompactGBufferKernel, (uint)instanceWidth, chunkSize, chunkOffset, uvFallbackBuffer, ctx.CompactedGBufferLength, lightmappingContext.CompactedTexelIndices);
// clear the expanded output buffer
// Populate the expanded clear indirect dispatch buffer - using the compacted size.
expansionShaders.GetKernelThreadGroupSizes(ctx.ClearBufferKernel, out uint clearThreadGroupSizeX, out uint clearThreadGroupSizeY, out uint clearThreadGroupSizeZ);
Debug.Assert(clearThreadGroupSizeY == 1 && clearThreadGroupSizeZ == 1);
ExpansionHelpers.PopulateClearExpandedOutputIndirectDispatch(cmd, expansionShaders, ctx.PopulateClearDispatchKernel, clearThreadGroupSizeX, expandedSampleWidth, ctx.CompactedGBufferLength, ctx.ClearDispatchBuffer);
// Clear the output buffers.
ExpansionHelpers.ClearExpandedOutput(cmd, expansionShaders, ctx.ClearBufferKernel, lightmappingContext.ExpandedOutput, ctx.ClearDispatchBuffer);
if (doDirectional)
ExpansionHelpers.ClearExpandedOutput(cmd, expansionShaders, ctx.ClearBufferKernel, lightmappingContext.ExpandedOutputDirectional, ctx.ClearDispatchBuffer);
}
// Work out the super sampling resolution. It's the width of the N x N supersampling kernel. Find the largest perfect square that is less than or equal to the max sample count per texel.
uint superSampleWidth = Math.Max(1, (uint)Math.Sqrt(maxSampleCountPerTexel));
// generate the GBuffer
ExpansionHelpers.GenerateGBuffer(
cmd,
lightmappingContext.IntegratorContext.GBufferShader,
lightmappingContext.GBuffer,
traceScratchBuffer,
lightmappingContext.IntegratorContext.SamplingResources,
uvAS,
uvFallbackBuffer,
ctx.CompactedGBufferLength,
lightmappingContext.CompactedTexelIndices,
instanceTexelOffset,
chunkOffset,
chunkSize,
expandedSampleWidth,
passSampleCount,
sampleOffset,
lightmapBakeSettings.GetAntiAliasingType(integratedOutputType),
superSampleWidth
);
GraphicsBuffer expandedDirectional = lightmappingContext.ExpandedOutputDirectional;
var instanceGeometryIndex = instance.IsProceduralTerrain
? -1
: lightmappingContext.World.PathTracingWorld.GetAccelerationStructure().GeometryPool.GetInstanceGeometryIndex(instance.Mesh);
var terrainIndex = instance.TerrainIndex;
bool debugGBuffer = false;
if (debugGBuffer)
{
Debug.Log($"Lightmap resolution: {lightmappingContext.Width} x {lightmappingContext.Height}");
Debug.Log($"Instance resolution: {instanceWidth} x {instanceHeight}");
Debug.Log($"Instance offset: {instanceTexelOffset}");
Debug.Log($"Sample count: {maxSampleCountPerTexel}");
var occupancy = (double)(passSampleCount * chunkSize) / (double)maxChunkSize * 100.0;
Debug.Log(string.Format(System.Globalization.CultureInfo.InvariantCulture, "Occupancy: {0:F2}%", occupancy));
// write out the lightmap UV samples
var uvSampleData = ExpansionHelpers.DebugGBuffer(cmd, instance, lightmappingContext, expandedSampleWidth, passSampleCount);
string sampleOutput = new("");
foreach (var sample in uvSampleData)
sampleOutput += string.Format(System.Globalization.CultureInfo.InvariantCulture, "float2({0}, {1})\n", sample.x, sample.y);
System.Console.WriteLine(sampleOutput);
}
// accumulate the lightmap texel
cmd.BeginSample(k_AccumulateLightmapInstance);
switch (integratedOutputType)
{
case IntegratedOutputType.AO:
{
lightmappingContext.IntegratorContext.LightmapAOIntegrator.Accumulate(
cmd,
passSampleCount,
bakeState.SampleIndex,
instance.LocalToWorldMatrix,
instance.LocalToWorldMatrixNormals,
instanceGeometryIndex,
terrainIndex,
instance.TexelSize,
chunkOffset,
lightmappingContext.World.PathTracingWorld,
traceScratchBuffer,
lightmappingContext.GBuffer,
expandedSampleWidth,
lightmappingContext.ExpandedOutput,
lightmappingContext.CompactedTexelIndices,
lightmappingContext.IntegratorContext.CompactedGBufferLength,
lightmapBakeSettings.PushOff,
lightmapBakeSettings.AOMaxDistance,
newChunkStarted
);
break;
}
case IntegratedOutputType.Validity:
{
lightmappingContext.IntegratorContext.LightmapValidityIntegrator.Accumulate(
cmd,
passSampleCount,
bakeState.SampleIndex,
instance.LocalToWorldMatrix,
instance.LocalToWorldMatrixNormals,
instanceGeometryIndex,
terrainIndex,
instance.TexelSize,
chunkOffset,
lightmappingContext.World.PathTracingWorld,
traceScratchBuffer,
lightmappingContext.GBuffer,
expandedSampleWidth,
lightmappingContext.ExpandedOutput,
lightmappingContext.CompactedTexelIndices,
lightmappingContext.IntegratorContext.CompactedGBufferLength,
lightmapBakeSettings.PushOff,
newChunkStarted
);
break;
}
case IntegratedOutputType.Direct:
case IntegratedOutputType.DirectionalityDirect:
{
lightmappingContext.IntegratorContext.LightmapDirectIntegrator.Accumulate(
cmd,
passSampleCount,
bakeState.SampleIndex,
instance.LocalToWorldMatrix,
instance.LocalToWorldMatrixNormals,
instanceGeometryIndex,
terrainIndex,
instance.TexelSize,
chunkOffset,
lightmappingContext.World.PathTracingWorld,
traceScratchBuffer,
lightmappingContext.GBuffer,
expandedSampleWidth,
lightmappingContext.ExpandedOutput,
expandedDirectional,
lightmappingContext.CompactedTexelIndices,
lightmappingContext.IntegratorContext.CompactedGBufferLength,
instance.ReceiveShadows,
lightmapBakeSettings.PushOff,
lightmapBakeSettings.DirectRISCandidateCount,
lightmapBakeSettings.DirectLightSamplingMode,
(uint)lightmappingContext.World.PathTracingWorld.MaxLightsInAnyCell,
newChunkStarted
);
break;
}
case IntegratedOutputType.DirectBRDF:
case IntegratedOutputType.DirectionalityDirectBRDF:
{
lightmappingContext.IntegratorContext.LightmapDirectBRDFIntegrator.Accumulate(
cmd,
passSampleCount,
bakeState.SampleIndex,
instance.LocalToWorldMatrix,
instance.LocalToWorldMatrixNormals,
instanceGeometryIndex,
terrainIndex,
instance.TexelSize,
chunkOffset,
lightmappingContext.World.PathTracingWorld,
traceScratchBuffer,
lightmappingContext.GBuffer,
expandedSampleWidth,
lightmappingContext.ExpandedOutput,
expandedDirectional,
lightmappingContext.CompactedTexelIndices,
lightmappingContext.IntegratorContext.CompactedGBufferLength,
instance.ReceiveShadows,
lightmapBakeSettings.PushOff,
lightmapBakeSettings.DirectRISCandidateCount,
newChunkStarted
);
break;
}
case IntegratedOutputType.Indirect:
case IntegratedOutputType.DirectionalityIndirect:
{
lightmappingContext.IntegratorContext.LightmapIndirectIntegrator.Accumulate(
cmd,
passSampleCount,
bakeState.SampleIndex,
lightmapBakeSettings.BounceCount,
instance.LocalToWorldMatrix,
instance.LocalToWorldMatrixNormals,
instanceGeometryIndex,
terrainIndex,
instance.TexelSize,
chunkOffset,
lightmappingContext.World.PathTracingWorld,
traceScratchBuffer,
lightmappingContext.GBuffer,
expandedSampleWidth,
lightmappingContext.ExpandedOutput,
expandedDirectional,
lightmappingContext.CompactedTexelIndices,
lightmappingContext.IntegratorContext.CompactedGBufferLength,
lightmapBakeSettings.PushOff,
lightmapBakeSettings.IndirectRISCandidateCount,
newChunkStarted
);
break;
}
case IntegratedOutputType.ShadowMask:
{
lightmappingContext.IntegratorContext.LightmapShadowMaskIntegrator.Accumulate(
cmd,
passSampleCount,
bakeState.SampleIndex,
instance.LocalToWorldMatrix,
instance.LocalToWorldMatrixNormals,
instanceGeometryIndex,
terrainIndex,
instance.TexelSize,
chunkOffset,
lightmappingContext.World.PathTracingWorld,
traceScratchBuffer,
lightmappingContext.GBuffer,
expandedSampleWidth,
lightmappingContext.ExpandedOutput,
expandedDirectional,
lightmappingContext.CompactedTexelIndices,
lightmappingContext.IntegratorContext.CompactedGBufferLength,
instance.ReceiveShadows,
lightmapBakeSettings.PushOff,
newChunkStarted
);
break;
}
}
cmd.EndSample(k_AccumulateLightmapInstance);
//LightmapIntegrationHelpers.LogGraphicsBuffer(cmd, lightmappingContext.ExpandedOutput, "expandedOutput", LightmapIntegrationHelpers.LogBufferType.Float4);
// Update the baking state
bakeState.Tick(
passSampleCount,
maxSampleCountPerTexel,
chunkSize,
instanceTexelCount,
out instanceIsDone,
out bool chunkIsDone);
if (chunkIsDone)
{
int maxExpandedDispatchSize = instanceWidth * instanceHeight * (int)expandedSampleWidth;
// Gather to lightmap -> first reduce to output resolution
// Populate the reduce indirect dispatch buffer - using the compacted size.
expansionShaders.GetKernelThreadGroupSizes(ctx.ReductionKernel, out uint reduceThreadGroupSizeX, out uint reduceThreadGroupSizeY, out uint reduceThreadGroupSizeZ);
Debug.Assert(reduceThreadGroupSizeY == 1 && reduceThreadGroupSizeZ == 1);
ExpansionHelpers.PopulateReduceExpandedOutputIndirectDispatch(cmd, expansionShaders, ctx.PopulateReduceDispatchKernel, reduceThreadGroupSizeX, expandedSampleWidth, ctx.CompactedGBufferLength, ctx.ReduceDispatchBuffer);
ExpansionHelpers.ReduceExpandedOutput(cmd, expansionShaders, ctx.ReductionKernel, lightmappingContext.ExpandedOutput, maxExpandedDispatchSize, expandedSampleWidth, ctx.ReduceDispatchBuffer);
if (doDirectional)
ExpansionHelpers.ReduceExpandedOutput(cmd, expansionShaders, ctx.ReductionKernel, lightmappingContext.ExpandedOutputDirectional, maxExpandedDispatchSize, expandedSampleWidth, ctx.ReduceDispatchBuffer);
// Populate the copy indirect dispatch buffer - using the compacted size.
expansionShaders.GetKernelThreadGroupSizes(ctx.CopyToLightmapKernel, out uint copyThreadGroupSizeX, out uint copyThreadGroupSizeY, out uint copyThreadGroupSizeZ);
Debug.Assert(copyThreadGroupSizeY == 1 && copyThreadGroupSizeZ == 1);
ExpansionHelpers.PopulateCopyToLightmapIndirectDispatch(cmd, expansionShaders, ctx.PopulateCopyDispatchKernel, copyThreadGroupSizeX, ctx.CompactedGBufferLength, ctx.CopyDispatchBuffer);
ExpansionHelpers.CopyToLightmap(cmd, expansionShaders, ctx.CopyToLightmapKernel, expandedSampleWidth, instanceWidth, instanceTexelOffset, chunkOffset, ctx.CompactedGBufferLength, lightmappingContext.CompactedTexelIndices, lightmappingContext.ExpandedOutput, ctx.CopyDispatchBuffer, lightmappingContext.AccumulatedOutput);
if (doDirectional)
ExpansionHelpers.CopyToLightmap(cmd, expansionShaders, ctx.CopyToLightmapKernel, expandedSampleWidth, instanceWidth, instanceTexelOffset, chunkOffset, ctx.CompactedGBufferLength, lightmappingContext.CompactedTexelIndices, lightmappingContext.ExpandedOutputDirectional, ctx.CopyDispatchBuffer, lightmappingContext.AccumulatedDirectionalOutput);
}
return passSampleCount;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4d348a097ea36d6418bdf3e858a808d0
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 2fb8d6a4d744c6343a2307687e61e916
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,18 @@
namespace UnityEngine.PathTracing.Core
{
// Must be kept in-sync with the equivalent type in Unity Core assembly.
internal enum LightSamplingMode
{
RIS = 0,
Uniform = 1,
RoundRobin = 2,
};
// Must be kept in-sync with the equivalent type in Unity Core assembly.
internal enum EmissiveSamplingMode
{
LightSampling = 0,
BRDFSampling = 1,
MIS = 2,
};
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 388805dc784049d2a487708b8e7df266
timeCreated: 1777042235
@@ -0,0 +1,155 @@
using System;
using System.Collections.Generic;
namespace UnityEngine.PathTracing.Core
{
internal class TextureQuadTree
{
public class TextureNode
{
public TextureNode TopLeft;
public TextureNode TopRight;
public TextureNode BottomLeft;
public TextureNode BottomRight;
public TextureNode Parent;
public int PosX;
public int PosY;
public int Size;
}
private readonly int _size;
private readonly List<TextureNode> _leaves;
public TextureQuadTree(int size)
{
_size = size;
var root = new TextureNode() { PosX = 0, PosY = 0, Size = _size };
_leaves = new List<TextureNode>() { root };
}
private void SubdivideNode(TextureNode node)
{
node.TopLeft = new TextureNode()
{
PosX = node.PosX,
PosY = node.PosY,
Size = node.Size / 2,
Parent = node
};
node.BottomLeft = new TextureNode()
{
PosX = node.PosX,
PosY = node.PosY + node.Size / 2,
Size = node.Size / 2,
Parent = node
};
node.TopRight = new TextureNode()
{
PosX = node.PosX + node.Size / 2,
PosY = node.PosY,
Size = node.Size / 2,
Parent = node
};
node.BottomRight = new TextureNode()
{
PosX = node.PosX + node.Size / 2,
PosY = node.PosY + node.Size / 2,
Size = node.Size / 2,
Parent = node
};
}
public bool AddTexture(int size, out TextureNode node)
{
int targetSize = Mathf.Min(Mathf.NextPowerOfTwo(size), _size);
// Search for a node with the right size
int bestSize = int.MaxValue;
TextureNode candidate = null;
for (int i = _leaves.Count - 1; i >= 0; i--)
{
// If we have a match, return it
int leafSize = _leaves[i].Size;
if (targetSize == leafSize)
{
node = _leaves[i];
_leaves.RemoveAt(i);
return true;
}
// Keep track of the best candidate we find
if (targetSize < leafSize && leafSize < bestSize)
{
candidate = _leaves[i];
bestSize = leafSize;
}
}
// If we have a candidate, subdivide one child until we are at the right size
if (candidate != null)
{
while (candidate.Size != targetSize)
{
SubdivideNode(candidate);
_leaves.Remove(candidate);
_leaves.Add(candidate.BottomRight);
_leaves.Add(candidate.BottomLeft);
_leaves.Add(candidate.TopRight);
candidate = candidate.TopLeft;
}
node = candidate;
return true;
}
node = null;
return false;
}
public void RemoveTexture(TextureNode node)
{
bool ShouldCollapse(TextureNode node)
{
return
(node.TopLeft == null || _leaves.Contains(node.TopLeft)) &&
(node.TopRight == null || _leaves.Contains(node.TopRight)) &&
(node.BottomLeft == null || _leaves.Contains(node.BottomLeft)) &&
(node.BottomRight == null || _leaves.Contains(node.BottomRight));
}
// Add the node to the list of leaves
_leaves.Add(node);
// Recursively collapse the quad tree if the parent node is empty, to avoid fragmentation
TextureNode parent = node.Parent;
while (parent != null && ShouldCollapse(parent))
{
// Remove the children from the leaves list
if (_leaves.Contains(parent.TopLeft)) _leaves.Remove(parent.TopLeft);
if (_leaves.Contains(parent.TopRight)) _leaves.Remove(parent.TopRight);
if (_leaves.Contains(parent.BottomLeft)) _leaves.Remove(parent.BottomLeft);
if (_leaves.Contains(parent.BottomRight)) _leaves.Remove(parent.BottomRight);
// Collapse the parent node
parent.TopLeft = null;
parent.TopRight = null;
parent.BottomLeft = null;
parent.BottomRight = null;
// Add the parent to the leaves list, and check the next parent
_leaves.Add(parent);
parent = parent.Parent;
}
}
public bool HasSpaceForTexture(int textureSize)
{
return _leaves.Exists(leaf => leaf.Size >= textureSize);
}
public bool IsFull => _leaves.Count == 0;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4b4536f3e86fa534d9779cfdf6d8f12e
@@ -0,0 +1,212 @@
using System;
using System.Collections.Generic;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
namespace UnityEngine.PathTracing.Core
{
// Container type that stores a set of arbitrarily sized textures in a 2D texture array,
// where each slice is a quadtree. Supports add/update/remove operations.
internal class TextureSlotAllocator : IDisposable
{
public readonly struct TextureLocation
{
public readonly int AtlasIndex; // Which atlas is the texture in
public readonly TextureQuadTree.TextureNode TextureNode; // Which position in the atlas is the texture
public TextureLocation(int atlasIndex, TextureQuadTree.TextureNode textureNode)
{
AtlasIndex = atlasIndex;
TextureNode = textureNode;
}
public static readonly TextureLocation Invalid = new(-1, null);
public bool IsValid => AtlasIndex >= 0 && TextureNode != null;
}
private readonly int _size;
private readonly GraphicsFormat _format;
private readonly FilterMode _filterMode;
private readonly CommandBuffer _cmd;
private RenderTexture _atlases;
private readonly HashSet<int> _freeAtlases = new();
private TextureQuadTree[] _textureQuadTrees = Array.Empty<TextureQuadTree>();
// Texture sizes stored in each quadtree node don't necessarily match the size of the quadtree node.
// We keep track of the real texture size here, so we can write to the atlas without stretching.
private readonly Dictionary<TextureLocation, Vector2Int> _textureSizes = new();
private readonly int _tempTextureID = Shader.PropertyToID("_TempSlotRT");
public RenderTexture Texture => _atlases;
public TextureSlotAllocator(int size, GraphicsFormat format, FilterMode filterMode)
{
_size = size;
_format = format;
_filterMode = filterMode;
_cmd = new CommandBuffer();
_cmd.name = $"Texture Slot Allocator ({size}, {format})";
// Initial allocation, in order to have a texture atlas in place even if we don't add anything to it.
// Note: This is required when binding the textures to ray tracing shaders (compute shaders seem to be OK with null textures)
ResizeAtlas(1);
}
public TextureLocation AddTexture(Texture texture, Vector2 scale, Vector2 offset)
{
// Find the max dimension
int size = Mathf.Max(texture.width, texture.height);
// Try to find an appropriately sized atlas in the free list
int atlasIndex = -1;
TextureQuadTree atlas = null;
foreach (int freeIndex in _freeAtlases)
{
if (_textureQuadTrees[freeIndex].HasSpaceForTexture(size))
{
atlasIndex = freeIndex;
atlas = _textureQuadTrees[atlasIndex];
break;
}
}
// If we couldn't find one, create a new atlas
if (atlasIndex == -1 || atlas == null)
{
// Create a new atlas
atlasIndex = _textureQuadTrees.Length;
Array.Resize(ref _textureQuadTrees, atlasIndex + 1);
atlas = new TextureQuadTree(_size);
_textureQuadTrees[atlasIndex] = atlas;
ResizeAtlas(atlasIndex + 1);
// Add it to the free list
_freeAtlases.Add(atlasIndex);
}
// Place in atlas
if (!atlas.AddTexture(size, out var textureNode))
{
return TextureLocation.Invalid;
}
// We might have filled up the atlas. If so, we remove it from the free list, if it is there.
if (atlas.IsFull)
{
_freeAtlases.Remove(atlasIndex);
}
// Blit the texture into the atlas
TextureLocation location = new TextureLocation(atlasIndex, textureNode);
UpdateTexture(in location, texture, scale, offset);
return location;
}
public void UpdateTexture(in TextureLocation location, Texture texture, Vector2 scale, Vector2 offset)
{
TextureQuadTree.TextureNode node = location.TextureNode;
int atlasIndex = location.AtlasIndex;
Debug.Assert(atlasIndex < _atlases.volumeDepth, "The texture atlas is too small.");
Vector2 textureScale = new Vector2(
node.Size / (float)Mathf.Min(texture.width, node.Size),
node.Size / (float)Mathf.Min(texture.height, node.Size));
_cmd.GetTemporaryRT(_tempTextureID, new RenderTextureDescriptor(node.Size, node.Size, _format, 0));
_cmd.Blit(texture, _tempTextureID, textureScale * scale, offset);
_cmd.CopyTexture(_tempTextureID, 0, 0, 0, 0, node.Size, node.Size, _atlases, atlasIndex, 0, node.PosX, node.PosY);
_cmd.ReleaseTemporaryRT(_tempTextureID);
Graphics.ExecuteCommandBuffer(_cmd);
_cmd.Clear();
// Keep track of texture size
_textureSizes[location] = new Vector2Int(texture.width, texture.height);
}
public void RemoveTexture(in TextureLocation location)
{
Debug.Assert(location.AtlasIndex < _textureQuadTrees.Length);
var atlas = _textureQuadTrees[location.AtlasIndex];
atlas.RemoveTexture(location.TextureNode);
// After removal, the atlas can't be full, so make sure it's in the free list
_freeAtlases.Add(location.AtlasIndex);
// No need to hold on to texture size anymore
_textureSizes.Remove(location);
// We could choose to shrink the atlas here to save memory,
// but don't do so currently due to the overhead of resizing the atlas.
}
public Vector2Int GetTextureSize(in TextureLocation location)
{
return new Vector2Int(
Mathf.Min(_textureSizes[location].x, location.TextureNode.Size),
Mathf.Min(_textureSizes[location].y, location.TextureNode.Size));
}
public void GetScaleAndOffset(in TextureLocation location, out Vector2 scale, out Vector2 offset)
{
Debug.Assert(location.AtlasIndex < _textureQuadTrees.Length);
Vector2Int textureSize = GetTextureSize(location);
scale = new Vector2(textureSize.x / (float)_size, textureSize.y / (float)_size);
offset = new Vector2(location.TextureNode.PosX / (float)_size, location.TextureNode.PosY / (float)_size);
}
private void ResizeAtlas(int sliceCount)
{
// Create new atlas array
var texture = new RenderTexture(new RenderTextureDescriptor(_size, _size)
{
dimension = TextureDimension.Tex2DArray,
depthBufferBits = 0,
volumeDepth = sliceCount,
msaaSamples = 1,
vrUsage = VRTextureUsage.OneEye,
graphicsFormat = _format,
enableRandomWrite = true,
})
{
name = $"Texture Atlas (Format = {_format})",
hideFlags = HideFlags.DontSaveInEditor,
wrapMode = TextureWrapMode.Clamp,
wrapModeU = TextureWrapMode.Clamp,
wrapModeV = TextureWrapMode.Clamp,
filterMode = _filterMode,
};
texture.Create();
if (_atlases != null)
{
var previousRT = RenderTexture.active;
// Blit old atlases into new one
for (int i = 0; i < Mathf.Min(sliceCount, _atlases.volumeDepth); i++)
{
Graphics.Blit(_atlases, texture, i, i);
}
RenderTexture.active = previousRT;
// Release old atlases
_atlases.Release();
CoreUtils.Destroy(_atlases);
}
_atlases = texture;
}
public void Dispose()
{
_cmd?.Dispose();
if (_atlases != null)
{
_atlases.Release();
CoreUtils.Destroy(_atlases);
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5f1e2bdf0b363ad42b67c77917a4efc9
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fef47f3c37586ba45b0c35e831041767
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,273 @@
using System;
using Unity.Mathematics;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.PathTracing.Core
{
internal class CubemapRender : IDisposable
{
internal enum Mode
{
Material,
Color
}
private Material _material;
private Shader _lastUsedShader;
private LocalKeyword? _noSunKeyword;
private Color[] _faceColors = new Color[6]
{
Color.black,
Color.black,
Color.black,
Color.black,
Color.black,
Color.black
};
private readonly Mesh _skyboxMesh;
private readonly Mesh _sixFaceSkyboxMesh;
private readonly Shader _solidColorShader;
private Material _colorMaterial;
private MaterialPropertyBlock _colorProperties;
private RenderTexture _cubemap;
private int _hash;
private Mode _mode = Mode.Color;
private static readonly int[] _cubeFaceToSkyboxPass = { 2, 3, 4, 5, 0, 1 };
private static readonly Matrix4x4[] _cubemapFaceBases = new Matrix4x4[6]
{
new(new float4(0, 0, -1, 0), new float4(0, 1, 0, 0), new float4(-1, 0, 0, 0), new float4(0, 0, 0, 1)),
new(new float4(0, 0, 1, 0), new float4(0, 1, 0, 0), new float4(1, 0, 0, 0), new float4(0, 0, 0, 1)),
new(new float4(1, 0, 0, 0), new float4(0, 0, -1, 0), new float4(0, -1, 0, 0), new float4(0, 0, 0, 1)),
new(new float4(1, 0, 0, 0), new float4(0, 0, 1, 0), new float4(0, 1, 0, 0), new float4(0, 0, 0, 1)),
new(new float4(1, 0, 0, 0), new float4(0, 1, 0, 0), new float4(0, 0, -1, 0), new float4(0, 0, 0, 1)),
new(new float4(-1, 0, 0, 0), new float4(0, 1, 0, 0), new float4(0, 0, 1, 0), new float4(0, 0, 0, 1)),
};
private static readonly int s_ColorID = Shader.PropertyToID("_Color");
public int Hash => _hash;
public CubemapRender(Mesh skyboxMesh, Mesh sixFaceSkyboxMesh, Shader solidColorShader)
{
_skyboxMesh = skyboxMesh;
_sixFaceSkyboxMesh = sixFaceSkyboxMesh;
_solidColorShader = solidColorShader;
_hash = 0;
}
public void Dispose()
{
ReleaseCubemapIfExists();
if (_colorMaterial != null)
{
CoreUtils.Destroy(_colorMaterial);
_colorMaterial = null;
}
}
public void SetMaterial(Material mat)
{
_material = mat;
}
public void SetColor(Color color)
{
for (int faceIndex = 0; faceIndex < 6; faceIndex++)
{
_faceColors[faceIndex] = color;
}
}
public void SetFaceColor(CubemapFace face, Color color)
{
_faceColors[(int)face] = color;
}
public void SetMode(Mode mode)
{
_mode = mode;
}
public Material GetMaterial() => _material;
Color LightColorInRenderingSpace(Light light)
{
Color cct = light.useColorTemperature ? Mathf.CorrelatedColorTemperatureToRGB(light.colorTemperature) : new Color(1, 1, 1, 1);
Color filter = light.color.linear;
return cct * filter * light.intensity;
}
public void Update(CommandBuffer cmd, Light sun, int resolution, out bool viewAndProjectionMatricesChanged)
{
viewAndProjectionMatricesChanged = false;
int newHash = ((int)_mode) + 1;
if (_mode == Mode.Color)
{
for (int faceIndex = 0; faceIndex < 6; faceIndex++)
{
newHash = HashCode.Combine(newHash, _faceColors[faceIndex].r, _faceColors[faceIndex].g, _faceColors[faceIndex].b);
}
if (newHash != _hash)
RenderWithColor(cmd);
}
else if (_mode == Mode.Material)
{
if (_material)
{
newHash = HashCode.Combine(newHash, _material.ComputeCRC());
if (sun != null)
{
var color = LightColorInRenderingSpace(sun);
var dir = -sun.GetComponent<Transform>().forward;
newHash = HashCode.Combine(newHash, color.r, color.g, color.b);
newHash = HashCode.Combine(newHash, dir.x, dir.y, dir.z);
}
if (newHash != _hash)
RenderWithMaterial(cmd, sun, resolution, out viewAndProjectionMatricesChanged);
}
else
{
newHash = 42;
ReleaseCubemapIfExists();
}
}
_hash = newHash;
}
void ReleaseCubemapIfExists()
{
if (_cubemap != null)
{
_cubemap.Release();
CoreUtils.Destroy(_cubemap);
_cubemap = null;
}
}
public Texture GetCubemap()
{
return _cubemap != null ? _cubemap : CoreUtils.blackCubeTexture;
}
private void RenderWithColor(CommandBuffer cmd)
{
EnsureCubemapExistsWithParticularResolution(1);
// Draw the color rather than ClearRenderTarget it: on some platforms a fast clear
// collapses a non-{0,1} HDR clear color to ~white, while a fullscreen draw is exact.
_colorMaterial ??= CoreUtils.CreateEngineMaterial(_solidColorShader);
_colorProperties ??= new MaterialPropertyBlock();
for (int faceIndex = 0; faceIndex < 6; ++faceIndex)
{
cmd.SetRenderTarget(new RenderTargetIdentifier(_cubemap, 0, (CubemapFace) faceIndex));
cmd.SetViewport(new Rect(0, 0, 1, 1));
_colorProperties.SetVector(s_ColorID, _faceColors[faceIndex]);
CoreUtils.DrawFullScreen(cmd, _colorMaterial, _colorProperties);
}
}
private void RenderWithMaterial(CommandBuffer cmd, Light sun, int cubemapResolution, out bool viewAndProjectionMatricesChanged)
{
EnsureCubemapExistsWithParticularResolution(cubemapResolution);
var properties = new MaterialPropertyBlock();
if (sun != null)
{
properties.SetVector(Shader.PropertyToID("_LightColor0"), LightColorInRenderingSpace(sun));
properties.SetVector(Shader.PropertyToID("_WorldSpaceLightPos0"), -sun.GetComponent<Transform>().forward);
}
else
{
properties.SetVector(Shader.PropertyToID("_LightColor0"), Color.black);
properties.SetVector(Shader.PropertyToID("_WorldSpaceLightPos0"), new Vector4(0, 0, -1, 0));
}
if (_lastUsedShader != _material.shader)
{
var keyword = _material.shader.keywordSpace.FindKeyword("_SUNDISK_NONE");
_noSunKeyword = keyword.isValid ? keyword : null;
_lastUsedShader = _material.shader;
}
if (_noSunKeyword.HasValue)
cmd.EnableKeyword(_material, _noSunKeyword.Value);
for (int faceIndex = 0; faceIndex < 6; ++faceIndex)
{
var viewMatrix = _cubemapFaceBases[faceIndex];
var proj = Matrix4x4.Perspective(90.0f, 1.0f, 0.1f, 10.0f);
if (IsOpenGLGfxDevice())
proj.SetColumn(1, -proj.GetColumn(1)); // flip Y axis
cmd.SetViewProjectionMatrices(viewMatrix, proj);
cmd.SetRenderTarget(new RenderTargetIdentifier(_cubemap, 0, (CubemapFace) faceIndex));
cmd.SetViewport(new Rect(0, 0, _cubemap.width, _cubemap.height));
cmd.ClearRenderTarget(false, true, new Color(0, 0, 0, 1));
#if UNITY_EDITOR
ShaderUtil.SetAsyncCompilation(cmd, false);
#endif
if (_material.passCount == 6)
{
int passIndex = _cubeFaceToSkyboxPass[faceIndex];
cmd.DrawMesh(_sixFaceSkyboxMesh, Matrix4x4.identity, _material, passIndex, passIndex, properties);
}
else
{
cmd.DrawMesh(_skyboxMesh, Matrix4x4.identity, _material, 0, 0, properties);
}
#if UNITY_EDITOR
ShaderUtil.RestoreAsyncCompilation(cmd);
#endif
}
viewAndProjectionMatricesChanged = true;
if (_noSunKeyword.HasValue)
cmd.DisableKeyword(_material, _noSunKeyword.Value);
}
private void EnsureCubemapExistsWithParticularResolution(int resolution)
{
if (_cubemap == null || _cubemap.width != resolution)
{
ReleaseCubemapIfExists();
CreateCubemap(resolution);
}
}
private void CreateCubemap(int width)
{
var texture = new RenderTexture(new RenderTextureDescriptor(){
dimension = TextureDimension.Cube,
width = width,
height = width,
depthBufferBits = 0,
volumeDepth = 1,
msaaSamples = 1,
vrUsage = VRTextureUsage.OneEye,
graphicsFormat = GraphicsFormat.R16G16B16A16_SFloat,
enableRandomWrite = true
});
texture.Create();
texture.name = "EnvironmentCubemap";
_cubemap = texture;
}
private static bool IsOpenGLGfxDevice()
{
return SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLES3 ||
SystemInfo.graphicsDeviceType == GraphicsDeviceType.OpenGLCore;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4bde7a8c0f6757b48a734d0a21766a01
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,62 @@
using System;
using UnityEngine.Rendering;
namespace UnityEngine.PathTracing.Core
{
internal struct EnvironmentCDF
{
public GraphicsBuffer ConditionalBuffer;
public GraphicsBuffer MarginalBuffer;
public int ConditionalResolution;
public int MarginalResolution;
}
internal class EnvironmentImportanceSampling : IDisposable
{
public EnvironmentImportanceSampling(ComputeShader shader)
{
_environmentCDF.MarginalResolution = 64;
_environmentCDF.ConditionalResolution = _environmentCDF.MarginalResolution * 2;
_environmentCDF.ConditionalBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, _environmentCDF.ConditionalResolution * _environmentCDF.MarginalResolution, sizeof(float));
_environmentCDF.MarginalBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, _environmentCDF.MarginalResolution, sizeof(float));
_shader = shader;
if (_shader)
{
_computeConditionalKernel = _shader.FindKernel("ComputeConditional");
_computeMarginalKernel = _shader.FindKernel("ComputeMarginal");
}
}
public void ComputeCDFBuffers(CommandBuffer cmd, Texture cubemap)
{
cmd.SetComputeIntParam(_shader, "_ConditionalResolution", _environmentCDF.ConditionalResolution);
cmd.SetComputeIntParam(_shader, "_MarginalResolution", _environmentCDF.MarginalResolution);
cmd.SetComputeTextureParam(_shader, _computeConditionalKernel, "_EnvCubemap", cubemap);
cmd.SetComputeBufferParam(_shader, _computeConditionalKernel, "_ConditionalBuffer", _environmentCDF.ConditionalBuffer);
cmd.SetComputeBufferParam(_shader, _computeConditionalKernel, "_MarginalBuffer", _environmentCDF.MarginalBuffer);
cmd.DispatchCompute(_shader, _computeConditionalKernel, 1, _environmentCDF.MarginalResolution, 1);
cmd.SetComputeBufferParam(_shader, _computeMarginalKernel, "_MarginalBuffer", _environmentCDF.MarginalBuffer);
cmd.DispatchCompute(_shader, _computeMarginalKernel, 1, 1, 1);
}
internal EnvironmentCDF GetSkyboxCDF()
{
return _environmentCDF;
}
public void Dispose()
{
_environmentCDF.ConditionalBuffer.Dispose();
_environmentCDF.MarginalBuffer.Dispose();
}
private readonly ComputeShader _shader;
private readonly int _computeConditionalKernel;
private readonly int _computeMarginalKernel;
private readonly EnvironmentCDF _environmentCDF;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1c1174c4c735e6b45bb06384a3c08e2d
@@ -0,0 +1,71 @@
#ifndef _ENVIRONMENT_IMPORTANCE_SAMPLING_HLSL_
#define _ENVIRONMENT_IMPORTANCE_SAMPLING_HLSL_
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Sampling/Sampling.hlsl"
// Equiareal mapping
float2 MapSkyDirectionToUV(float3 dir)
{
float cosTheta = dir.y;
float phi = atan2(-dir.z, -dir.x);
return float2(0.5 - phi * INV_TWO_PI, (cosTheta + 1.0) * 0.5);
}
// Equiareal mapping
float3 MapUVToSkyDirection(float2 uv)
{
float phi = TWO_PI * (1.0 - uv.x);
float cosTheta = 2.0 * uv.y - 1.0;
return TransformGLtoDX(SphericalToCartesian((real)phi, (real)cosTheta));
}
// Dichotomic search
float SampleSkyCDF(StructuredBuffer<float> cdf, uint size, uint bufferOffset, float smp)
{
uint i = 0;
for (uint halfsize = size >> 1, offset = halfsize; offset > 0; offset >>= 1)
{
if (smp < cdf[bufferOffset + halfsize])
{
// i is already in the right half (lower one)
halfsize -= offset >> 1;
}
else
{
// i has to move to the other half (upper one)
i += offset;
halfsize += offset >> 1;
}
}
// MarginalTexture[0] stores the PDF normalization factor, so we need a test on i == 0
float cdfInf = i == 0 ? 0.0 : cdf[bufferOffset + i];
float cdfSup = i + 1 == size ? 1.0f : cdf[bufferOffset + i + 1];
return (i + (smp - cdfInf) / (cdfSup - cdfInf)) / size;
}
float GetSkyPDFNormalizationFactor(StructuredBuffer<float> marginalBuffer)
{
return marginalBuffer[0];
}
// This PDF approximation is valid only if PDF/CDF tables are computed with equiareal mapping
float GetSkyPDFFromValue(float3 value, float pdfNormalization)
{
return Luminance(value) * pdfNormalization;
}
float GetSkyPDFFromValue(float3 value, StructuredBuffer<float> marginalBuffer)
{
return GetSkyPDFFromValue(value, GetSkyPDFNormalizationFactor(marginalBuffer));
}
float2 SampleSky(float2 rand, uint marginalResolution, StructuredBuffer<float> marginalBuffer, uint conditionalResolution, StructuredBuffer<float> conditionalBuffer)
{
float v = SampleSkyCDF(marginalBuffer, marginalResolution, 0, rand.x);
float u = SampleSkyCDF(conditionalBuffer, conditionalResolution, conditionalResolution * uint(v * marginalResolution), rand.y);
return float2(u, v);
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: cd8fa354645948a46bc538729ae1b169
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,151 @@
// This implementation is adapted from BuildProbabilityTables.compute
#pragma only_renderers d3d11 vulkan metal glcore
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Color.hlsl"
#include "EnvironmentImportanceSampling.hlsl"
#define KERNEL_WIDTH 64
uint _ConditionalResolution;
uint _MarginalResolution;
RWStructuredBuffer<float> _ConditionalBuffer;
RWStructuredBuffer<float> _MarginalBuffer;
TextureCube<float4> _EnvCubemap;
SamplerState sampler_EnvCubemap;
float3 SampleSkyTexture(float3 dir, float lod, int sliceIndex)
{
return _EnvCubemap.SampleLevel(sampler_EnvCubemap, dir, lod).xyz;
}
// Performs a block-level parallel scan.
// Ref: GPU Gems 3, Chapter 39: "Parallel Prefix Sum (Scan) with CUDA".
void ParallelScan(uint i, uint w, uint iterCount, RWStructuredBuffer<float> buf, uint bufferOffset, out float sum)
{
uint offset;
// Execute the up-sweep phase.
for (offset = 1; offset <= w / 2; offset *= 2)
{
AllMemoryBarrierWithGroupSync();
for (uint iter = 0; iter < iterCount; iter++)
{
uint idx = i + iter * KERNEL_WIDTH;
// a1 = (2 * i + 1) * offset - 1
uint a1 = Mad24(Mad24(2u, idx, 1u), offset, -1);
uint a2 = a1 + offset;
if (a2 < w)
{
buf[bufferOffset + a2] += buf[bufferOffset + a1];
}
}
}
AllMemoryBarrierWithGroupSync();
// Prevent NaNs arising from the division of 0 by 0.
sum = max(buf[bufferOffset + w - 1], FLT_MIN);
AllMemoryBarrierWithGroupSync();
// The exclusive scan requires the last element to be 0.
if (i == 0)
{
buf[bufferOffset + w - 1] = 0.0;
}
// Execute the down-sweep phase.
for (offset = w / 2; offset > 0; offset /= 2)
{
AllMemoryBarrierWithGroupSync();
for (uint iter = 0; iter < iterCount; iter++)
{
uint idx = i + iter * KERNEL_WIDTH;
// a1 = (2 * i + 1) * offset - 1
uint a1 = Mad24(Mad24(2u, idx, 1u), offset, -1);
uint a2 = a1 + offset;
if (a2 < w)
{
float t1 = buf[bufferOffset + a1];
buf[bufferOffset + a1] = buf[bufferOffset + a2];
buf[bufferOffset + a2] += t1;
}
}
}
AllMemoryBarrierWithGroupSync();
}
#pragma kernel ComputeConditional
[numthreads(KERNEL_WIDTH, 1, 1)]
void ComputeConditional(uint3 dispatchThreadId : SV_DispatchThreadID)
{
const uint i = dispatchThreadId.x;
const uint j = dispatchThreadId.y;
const uint iterCount = _ConditionalResolution / KERNEL_WIDTH;
const uint conditionalBufferOffset = j * _ConditionalResolution;
uint iter;
float v = (j + 0.5) / _MarginalResolution;
//float sinTheta = sin(v * PI);
for (iter = 0; iter < iterCount; iter++)
{
uint idx = i + iter * KERNEL_WIDTH;
float u = (idx + 0.5) / _ConditionalResolution;
// No need for a sinTheta term in the PDF when using equiareal mapping
float3 dir = MapUVToSkyDirection(float2(u, v));
_ConditionalBuffer[conditionalBufferOffset + idx] = Luminance(SampleSkyTexture(dir, 0.0, 0).rgb); // * sinTheta;
}
float rowValSum = 0.0f;
ParallelScan(i, _ConditionalResolution, iterCount, _ConditionalBuffer, conditionalBufferOffset, rowValSum);
for (iter = 0; iter < iterCount; iter++)
{
uint idx = i + iter * KERNEL_WIDTH;
_ConditionalBuffer[conditionalBufferOffset + idx] /= rowValSum;
}
if (i == 0)
{
float rowIntegralValue = rowValSum / _ConditionalResolution;
_MarginalBuffer[j] = rowIntegralValue;
}
}
#pragma kernel ComputeMarginal
[numthreads(KERNEL_WIDTH, 1, 1)]
void ComputeMarginal(uint3 dispatchThreadId : SV_DispatchThreadID)
{
const uint i = dispatchThreadId.x;
const uint iterCount = _MarginalResolution / KERNEL_WIDTH;
float rowValSum = 0.0f;
ParallelScan(i, _MarginalResolution, iterCount, _MarginalBuffer, 0, rowValSum);
for (uint iter = 0; iter < iterCount; iter++)
{
uint idx = i + iter * KERNEL_WIDTH;
_MarginalBuffer[idx] /= rowValSum;
}
if (i == 0)
{
float imgIntegralValue = rowValSum / _MarginalResolution;
float pdfNormalization = imgIntegralValue > 0.0 ? rcp(imgIntegralValue) * 0.25 * INV_PI : 0.0;
_MarginalBuffer[0] = pdfNormalization;
}
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5bb2534d2411d344cbc54f880232640f
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,30 @@
Shader "Hidden/PathTracing/SolidColor"
{
Properties { _Color ("Color", Vector) = (0,0,0,0) }
SubShader
{
Pass
{
ZTest Always Cull Off ZWrite Off
HLSLPROGRAM
#pragma vertex Vert
#pragma fragment Frag
float4 _Color;
float4 Vert(uint vertexID : SV_VertexID) : SV_POSITION
{
// Fullscreen triangle from the vertex id (DrawProcedural with 3 verts).
float2 uv = float2((vertexID << 1) & 2, vertexID & 2);
return float4(uv * 2.0 - 1.0, 0.0, 1.0);
}
float4 Frag() : SV_Target
{
return _Color;
}
ENDHLSL
}
}
Fallback Off
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 3765a7ac691541038de4d587b94ae768
ShaderImporter:
externalObjects: {}
defaultTextures: []
nonModifiableTextures: []
preprocessorOverride: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,63 @@
using System;
using System.Collections.Generic;
using Unity.Collections.LowLevel.Unsafe;
namespace UnityEngine.PathTracing.Core
{
// The type parameter T is only used as a tag, preventing different kinds of handles from being mixed together.
internal readonly struct Handle<T>
{
public readonly UInt64 Value;
public Handle(UInt64 value)
{
Value = value;
}
public static readonly Handle<T> Invalid = new(0xFFFFFFFFFFFFFFFF);
public bool IsValid() => Value >= 0;
internal int ToInt()
{
Debug.Assert(UnsafeUtility.SizeOf<EntityId>() == sizeof(int),
"If this assert is firing, the size of EntityId has changed. This function should no longer be used.");
return (int)Value;
}
// Value type semantics
public override int GetHashCode() => Value.GetHashCode();
public override bool Equals(object obj) => obj is Handle<T> other && other.Value == Value;
public override string ToString() => $"Handle<{typeof(T).Name}>({Value})";
public static bool operator ==(Handle<T> a, Handle<T> b) => a.Value == b.Value;
public static bool operator !=(Handle<T> a, Handle<T> b) => a.Value != b.Value;
}
// Keeps track of allocated instance handles. Reuses freed handles.
internal class HandleSet<T>
{
private readonly Stack<Handle<T>> _freeHandles = new();
private UInt64 _nextHandleIndex;
public Handle<T> Add()
{
if (_freeHandles.Count > 0)
return _freeHandles.Pop();
return new Handle<T>(_nextHandleIndex++);
}
public void Remove(Handle<T> handle)
{
Debug.Assert(!_freeHandles.Contains(handle));
_freeHandles.Push(handle);
}
public void Clear()
{
_freeHandles.Clear();
_nextHandleIndex = 0;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 79550f93c7dc21e41b0af2097cf46b53
@@ -0,0 +1,136 @@
using System;
using System.Collections.Generic;
using Unity.Mathematics;
namespace UnityEngine.PathTracing.Core
{
internal struct LightFalloffDesc
{
public float LUTRange;
public Experimental.GlobalIllumination.FalloffType FalloffType;
public readonly override int GetHashCode()
{
return HashCode.Combine(LUTRange, FalloffType);
}
}
internal class LightFalloffLUT
{
// Inverse squared falloff: minimum distance to light to avoid division by zero
public const float DistThresholdSqr = 0.0001f; // 1cm (in Unity 1 is 1m) so this is 0.01^2
// Legacy Unity falloff: where the falloff down to zero should start
private const float ToZeroFadeStart = 0.8f * 0.8f;
// Legacy Unity falloff: constants for OpenGL attenuation
private const float ConstantFac = 1.000f;
private const float QuadraticFac = 25.0f;
// Calculate the quadratic attenuation factor for a light with a specified range
private static float CalculateLightQuadFac(float range)
{
return QuadraticFac / (range * range);
}
private static float LightAttenuateNormalized(float distSqr)
{
// match the vertex lighting falloff
float atten = 1 / (ConstantFac + CalculateLightQuadFac(1.0f) * distSqr);
// ...but vertex one does not falloff to zero at light's range;
// So force it to falloff to zero at the edges.
if (distSqr >= ToZeroFadeStart)
{
if (distSqr > 1)
atten = 0;
else
atten *= 1 - (distSqr - ToZeroFadeStart) / (1 - ToZeroFadeStart);
}
return atten;
}
public static float LegacyUnityFalloff(float normalizedDistance)
{
float clampedDist = math.clamp(normalizedDistance, 0.0f, 1.0f);
return LightAttenuateNormalized(clampedDist * clampedDist);
}
public static float SmoothDistanceAttenuation(float squaredDistance, float invSqrAttenuationRadius)
{
float factor = squaredDistance * invSqrAttenuationRadius;
float smoothFactor = math.saturate(1.0f - factor * factor);
return smoothFactor * smoothFactor;
}
public static float InverseSquaredFalloffSmooth(float squaredDistance, float invSqrAttenuationRadius)
{
float attenuation = 1.0f / (math.max(DistThresholdSqr, squaredDistance));
// Non physically based hack to limit light influence to attenuationRadius. As we approach the range we fade out the light.
return attenuation * SmoothDistanceAttenuation(squaredDistance, invSqrAttenuationRadius);
}
public static float InverseSquaredFalloff(float squaredDistance)
{
return 1.0f / (math.max(DistThresholdSqr, squaredDistance));
}
public static float[] BuildLightFalloffLUTs(LightFalloffDesc[] lightFalloffDescs, uint lightFalloffLUTLength = 1024)
{
List<float> lightFalloffData = new();
foreach (var lightFalloffDesc in lightFalloffDescs)
{
float range = lightFalloffDesc.LUTRange;
switch (lightFalloffDesc.FalloffType)
{
case Experimental.GlobalIllumination.FalloffType.InverseSquaredNoRangeAttenuation:
{
for (uint k = 0; k < lightFalloffLUTLength; ++k)
{
float normalizedTableDistance = (float)k / (float)(lightFalloffLUTLength - 1);
float distance = range * normalizedTableDistance;
float value = InverseSquaredFalloff(distance * distance);
lightFalloffData.Add(value);
}
}
break;
case Experimental.GlobalIllumination.FalloffType.InverseSquared:
{
float invSqrAttenuationRadius = 1.0f / math.max(DistThresholdSqr, range * range);
for (uint k = 0; k < lightFalloffLUTLength; ++k)
{
float normalizedTableDistance = (float)k / (float)(lightFalloffLUTLength - 1);
float distance = range * normalizedTableDistance;
float value = InverseSquaredFalloffSmooth(distance * distance, invSqrAttenuationRadius);
lightFalloffData.Add(value);
}
}
break;
case Experimental.GlobalIllumination.FalloffType.Linear:
{
for (uint k = 0; k < lightFalloffLUTLength; ++k)
{
float linear = 1.0f - ((float)k / (float)(lightFalloffLUTLength - 1));
lightFalloffData.Add(linear);
}
}
break;
case Experimental.GlobalIllumination.FalloffType.Legacy:
default:
{
for (uint k = 0; k < lightFalloffLUTLength; ++k)
{
float normalizedTableDistance = (float)k / (float)(lightFalloffLUTLength - 1);
float value = LegacyUnityFalloff(normalizedTableDistance);
lightFalloffData.Add(value);
}
}
break;
}
// Change the last value to 0 to limit the light influence to the range
lightFalloffData[^1] = 0.0f;
}
return lightFalloffData.ToArray();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 4d731376742bf4a49a65a6083a9b9b32
@@ -0,0 +1,304 @@
using Unity.Mathematics;
using Unity.Profiling;
using Unity.Profiling.LowLevel;
using UnityEngine.PathTracing.Core;
using UnityEngine.PathTracing.Integration;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Sampling;
using UnityEngine.Rendering.UnifiedRayTracing;
using static UnityEngine.PathTracing.Lightmapping.LightmapIntegrationHelpers;
namespace UnityEngine.PathTracing.Lightmapping
{
internal static class ExpansionShaderIDs
{
public static readonly int GBuffer = Shader.PropertyToID("g_GBuffer");
public static readonly int DestinationTexture = Shader.PropertyToID("g_DestinationTexture");
public static readonly int DestinationX = Shader.PropertyToID("g_DestinationX");
public static readonly int DestinationY = Shader.PropertyToID("g_DestinationY");
public static readonly int ExpandedTexelSampleWidth = Shader.PropertyToID("g_ExpandedTexelSampleWidth");
public static readonly int Float4Buffer = Shader.PropertyToID("g_Float4Buffer");
public static readonly int Float4BufferLength = Shader.PropertyToID("g_Float4BufferLength");
public static readonly int BinaryBufferSize = Shader.PropertyToID("g_BinaryBufferSize");
public static readonly int BinaryGroupSize = Shader.PropertyToID("g_BinaryGroupSize");
public static readonly int SourceBuffer = Shader.PropertyToID("g_SourceBuffer");
public static readonly int SourceStride = Shader.PropertyToID("g_SourceStride");
public static readonly int GBufferLength = Shader.PropertyToID("g_GBufferLength");
public static readonly int CompactedGBuffer = Shader.PropertyToID("g_CompactedGBuffer");
public static readonly int CompactedGBufferLength = Shader.PropertyToID("g_CompactedGBufferLength");
public static readonly int InstanceWidth = Shader.PropertyToID("g_InstanceWidth");
public static readonly int ThreadGroupSizeX = Shader.PropertyToID("g_ThreadGroupSizeX");
public static readonly int AccumulationDispatchBuffer = Shader.PropertyToID("g_AccumulationDispatchBuffer");
public static readonly int ClearDispatchBuffer = Shader.PropertyToID("g_ClearDispatchBuffer");
public static readonly int CopyDispatchBuffer = Shader.PropertyToID("g_CopyDispatchBuffer");
public static readonly int ReduceDispatchBuffer = Shader.PropertyToID("g_ReduceDispatchBuffer");
public static readonly int ChunkSize = Shader.PropertyToID("g_ChunkSize");
public static readonly int ChunkOffsetX = Shader.PropertyToID("g_ChunkOffsetX");
public static readonly int ChunkOffsetY = Shader.PropertyToID("g_ChunkOffsetY");
public static readonly int PassSampleCount = Shader.PropertyToID("g_PassSampleCount");
public static readonly int SampleOffset = Shader.PropertyToID("g_SampleOffset");
}
internal static class ExpansionHelpers
{
/// <summary>
/// Clears the expanded output buffer to zero before the accumulation loop begins.
/// </summary>
static readonly ProfilerMarker k_ClearExpanded =
new ProfilerMarker(ProfilerCategory.Render, "Clear (Expanded)",
MarkerFlags.Default | MarkerFlags.SampleGPU);
/// <summary>
/// Traces rays from each lightmap texel into the scene to populate the GBuffer with
/// world-space hit data. This ray-tracing dispatch is a prerequisite for all
/// subsequent accumulation passes.
/// </summary>
static readonly ProfilerMarker k_UVSampling =
new ProfilerMarker(ProfilerCategory.Render, "UV Sampling",
MarkerFlags.Default | MarkerFlags.SampleGPU);
/// <summary>
/// Compacts the GBuffer by stream-compacting out invalid (missed-ray) texels so the
/// accumulation dispatch only processes valid hits.
/// </summary>
static readonly ProfilerMarker k_CompactGBuffer =
new ProfilerMarker(ProfilerCategory.Render, "Compact GBuffer",
MarkerFlags.Default | MarkerFlags.SampleGPU);
/// <summary>
/// Performs one stage of the parallel-reduction sum over expanded sample groups.
/// Called repeatedly in a loop where each invocation halves the remaining group count
/// until all samples within each texel are summed.
/// </summary>
static readonly ProfilerMarker k_BinarySum =
new ProfilerMarker(ProfilerCategory.Render, "Binary Sum",
MarkerFlags.Default | MarkerFlags.SampleGPU);
/// <summary>
/// Copies the accumulated, reduced texel values from the expanded buffer into the
/// final lightmap texture at the correct instance offset and chunk bounds.
/// </summary>
static readonly ProfilerMarker k_CopyToLightmap =
new ProfilerMarker(ProfilerCategory.Render, "Copy to Lightmap",
MarkerFlags.Default | MarkerFlags.SampleGPU);
static internal int PopulateAccumulationIndirectDispatch(CommandBuffer cmd, ComputeShader populateShader, int populateKernel, uint expandedSampleWidth, GraphicsBuffer compactedGbufferLength, GraphicsBuffer accumulationDispatchBuffer)
{
cmd.SetComputeIntParam(populateShader, ExpansionShaderIDs.ExpandedTexelSampleWidth, (int)expandedSampleWidth);
cmd.SetComputeBufferParam(populateShader, populateKernel, ExpansionShaderIDs.CompactedGBufferLength, compactedGbufferLength);
cmd.SetComputeBufferParam(populateShader, populateKernel, ExpansionShaderIDs.AccumulationDispatchBuffer, accumulationDispatchBuffer);
cmd.DispatchCompute(populateShader, populateKernel, 1, 1, 1);
//LightmapIntegrationHelpers.LogGraphicsBuffer(cmd, accumulationDispatchBuffer, "accumulationDispatchBuffer", LogBufferType.UInt);
return 1;
}
static internal int PopulateClearExpandedOutputIndirectDispatch(CommandBuffer cmd, ComputeShader populateClearDispatch, int populateClearDispatchKernel, uint clearThreadGroupSizeX, uint expandedSampleWidth, GraphicsBuffer compactedGBufferLength, GraphicsBuffer clearDispatchBuffer)
{
// Populate the expanded clear indirect dispatch buffer - using the compacted size.
cmd.SetComputeIntParam(populateClearDispatch, ExpansionShaderIDs.ExpandedTexelSampleWidth, (int)expandedSampleWidth);
cmd.SetComputeIntParam(populateClearDispatch, ExpansionShaderIDs.ThreadGroupSizeX, (int)clearThreadGroupSizeX);
cmd.SetComputeBufferParam(populateClearDispatch, populateClearDispatchKernel, ExpansionShaderIDs.CompactedGBufferLength, compactedGBufferLength);
cmd.SetComputeBufferParam(populateClearDispatch, populateClearDispatchKernel, ExpansionShaderIDs.ClearDispatchBuffer, clearDispatchBuffer);
cmd.DispatchCompute(populateClearDispatch, populateClearDispatchKernel, 1, 1, 1);
//LightmapIntegrationHelpers.LogGraphicsBuffer(cmd, clearDispatchBuffer, "clearDispatchBuffer", LogBufferType.UInt);
return 1;
}
static internal int ClearExpandedOutput(CommandBuffer cmd, ComputeShader clearExpandedOutput, int clearExpandedOutputKernel, GraphicsBuffer expandedOutput, GraphicsBuffer clearDispatchBuffer)
{
Debug.Assert(expandedOutput.stride == 16);
// Clear the output buffers.
cmd.SetComputeIntParam(clearExpandedOutput, ExpansionShaderIDs.Float4BufferLength, expandedOutput.count);
cmd.SetComputeBufferParam(clearExpandedOutput, clearExpandedOutputKernel, ExpansionShaderIDs.Float4Buffer, expandedOutput);
cmd.BeginSample(k_ClearExpanded);
cmd.DispatchCompute(clearExpandedOutput, clearExpandedOutputKernel, clearDispatchBuffer, 0);
cmd.EndSample(k_ClearExpanded);
//LightmapIntegrationHelpers.LogGraphicsBuffer(cmd, expandedOutput, "expandedOutput", LogBufferType.Float4);
return 1;
}
static internal void GenerateGBuffer(
CommandBuffer cmd,
IRayTracingShader gBufferShader,
GraphicsBuffer gBuffer,
GraphicsBuffer traceScratchBuffer,
SamplingResources samplingResources,
UVAccelerationStructure uvAS,
UVFallbackBuffer uvFallbackBuffer,
GraphicsBuffer compactedGBufferLength,
GraphicsBuffer compactedTexelIndices,
Vector2Int instanceTexelOffset,
uint2 chunkOffset,
uint chunkSize,
uint expandedSampleWidth,
uint passSampleCount,
uint sampleOffset,
AntiAliasingType aaType,
uint superSampleWidth // the width of the superSampleWidth x superSampleWidth grid used when not using stochastic anti-aliasing
)
{
var stochasticAntiAliasing = aaType == AntiAliasingType.Stochastic;
// bind buffers
gBufferShader.SetAccelerationStructure(cmd, "g_UVAccelStruct", uvAS._uvAS);
gBufferShader.SetBufferParam(cmd, LightmapIntegratorShaderIDs.GBuffer, gBuffer);
SamplingResources.Bind(cmd, samplingResources);
uvFallbackBuffer.BindChunked(cmd, gBufferShader, instanceTexelOffset, chunkOffset, chunkSize);
gBufferShader.SetBufferParam(cmd, ExpansionShaderIDs.CompactedGBuffer, compactedTexelIndices);
gBufferShader.SetBufferParam(cmd, ExpansionShaderIDs.CompactedGBufferLength, compactedGBufferLength);
gBufferShader.SetIntParam(cmd, ExpansionShaderIDs.ExpandedTexelSampleWidth, (int)expandedSampleWidth);
gBufferShader.SetIntParam(cmd, ExpansionShaderIDs.PassSampleCount, (int)passSampleCount);
gBufferShader.SetIntParam(cmd, ExpansionShaderIDs.SampleOffset, (int)sampleOffset);
// set antialiasing parameters
gBufferShader.SetIntParam(cmd, LightmapIntegratorShaderIDs.StochasticAntialiasing, stochasticAntiAliasing ? 1 : 0);
gBufferShader.SetIntParam(cmd, LightmapIntegratorShaderIDs.SuperSampleWidth, (int)superSampleWidth);
// dispatch the shader
Debug.Assert(gBufferShader is HardwareRayTracingShader || GraphicsHelpers.DivUp((int)chunkSize, gBufferShader.GetThreadGroupSizes().x) < 65536, "Chunk size is too large for the shader to handle.");
cmd.BeginSample(k_UVSampling);
gBufferShader.Dispatch(cmd, traceScratchBuffer, chunkSize * expandedSampleWidth, 1, 1);
cmd.EndSample(k_UVSampling);
//LightmapIntegrationHelpers.LogGraphicsBuffer(cmd, gBuffer, "gBuffer", LogBufferType.HitEntry);
}
static internal float2[] DebugGBuffer(CommandBuffer cmd, BakeInstance instance, LightmappingContext lightmappingContext, uint expandedSampleWidth, uint passSampleCount)
{
// Get the length of the compacted GBuffer length to know how many samples there are.
uint[] compactedLength = new uint[1];
GraphicsHelpers.Flush(cmd);
lightmappingContext.IntegratorContext.CompactedGBufferLength.GetData(compactedLength);
uint sampleCount = compactedLength[0] * expandedSampleWidth;
// Run the debug shader to retrieve the samples.
var lightmapSamplesExpanded = new GraphicsBuffer(GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource, (int)(sampleCount), sizeof(float) * 2);
var instanceGeometryIndex = instance.IsProceduralTerrain
? -1
: lightmappingContext.World.PathTracingWorld.GetAccelerationStructure().GeometryPool.GetInstanceGeometryIndex(instance.Mesh);
var terrainIndex = instance.TerrainIndex;
lightmappingContext.IntegratorContext.GBufferDebugShader.Accumulate(
cmd,
instance.LocalToWorldMatrix,
instance.LocalToWorldMatrixNormals,
instanceGeometryIndex,
terrainIndex,
lightmappingContext.World.PathTracingWorld,
lightmappingContext.GBuffer,
expandedSampleWidth,
lightmapSamplesExpanded,
lightmappingContext.IntegratorContext.CompactedGBufferLength
);
GraphicsHelpers.Flush(cmd);
// Retrieve the samples from the GPU.
float2[] uvSampleData = new float2[sampleCount];
lightmapSamplesExpanded.GetData(uvSampleData, 0, 0, (int)sampleCount);
lightmapSamplesExpanded.Dispose();
// Filter the samples
float4 scaleAndOffset = instance.SourceLightmapST;
System.Collections.Generic.List<float2> filteredSamples = new System.Collections.Generic.List<float2>();
for (int i = 0; i < uvSampleData.Length; ++i)
{
// For some passes the expanded buffer is not filled completely and we need to account for that.
var localSampleIndex = i % expandedSampleWidth;
if (localSampleIndex < passSampleCount)
{
// this is a valid sample - apply lightmap ST to map into lightmap space
var sample = uvSampleData[i];
var transformedUV = sample * scaleAndOffset.xy + scaleAndOffset.zw;
filteredSamples.Add(transformedUV);
}
}
return filteredSamples.ToArray();
}
static internal int CompactGBuffer(CommandBuffer cmd, ComputeShader compactGBuffer, int compactGBufferKernel, uint instanceWidth, uint chunkSize, uint2 chunkOffset, UVFallbackBuffer uvFallbackBuffer, GraphicsBuffer compactedGBufferLength, GraphicsBuffer compactedTexelIndices)
{
compactGBuffer.GetKernelThreadGroupSizes(compactGBufferKernel, out uint gbuf_x, out _, out _);
cmd.SetBufferData(compactedGBufferLength, new uint[] { 0 });
cmd.SetComputeIntParam(compactGBuffer, ExpansionShaderIDs.ChunkSize, (int)chunkSize);
cmd.SetComputeIntParam(compactGBuffer, ExpansionShaderIDs.InstanceWidth, (int)instanceWidth);
cmd.SetComputeIntParam(compactGBuffer, ExpansionShaderIDs.ChunkOffsetX, (int)chunkOffset.x);
cmd.SetComputeIntParam(compactGBuffer, ExpansionShaderIDs.ChunkOffsetY, (int)chunkOffset.y);
cmd.SetComputeTextureParam(compactGBuffer, compactGBufferKernel, UVFallbackBufferBuilderShaderIDs.UvFallback, uvFallbackBuffer.UVFallbackRT);
cmd.SetComputeBufferParam(compactGBuffer, compactGBufferKernel, ExpansionShaderIDs.CompactedGBuffer, compactedTexelIndices);
cmd.SetComputeBufferParam(compactGBuffer, compactGBufferKernel, ExpansionShaderIDs.CompactedGBufferLength, compactedGBufferLength);
cmd.BeginSample(k_CompactGBuffer);
cmd.DispatchCompute(compactGBuffer, compactGBufferKernel, GraphicsHelpers.DivUp((int)chunkSize, gbuf_x), 1, 1);
cmd.EndSample(k_CompactGBuffer);
//System.Console.WriteLine($"compactGBufferThreadGroupSizeX: {gbuf_x}");
//LightmapIntegrationHelpers.LogGraphicsBuffer(cmd, compactedGBufferLength, "compactedGBufferLength", LogBufferType.UInt);
//LightmapIntegrationHelpers.LogGraphicsBuffer(cmd, compactedTexelIndices, "compactedTexelIndices", LogBufferType.UInt);
return 1;
}
static internal int PopulateReduceExpandedOutputIndirectDispatch(CommandBuffer cmd, ComputeShader populateReduceExpandedOutput, int populateReduceExpandedOutputKernel, uint reduceThreadGroupSizeX, uint expandedSampleWidth, GraphicsBuffer compactedGBufferLength, GraphicsBuffer reduceDispatchBuffer)
{
// Populate the reduce copy indirect dispatch buffer - using the compacted size.
cmd.SetComputeIntParam(populateReduceExpandedOutput, ExpansionShaderIDs.ExpandedTexelSampleWidth, (int)expandedSampleWidth);
cmd.SetComputeIntParam(populateReduceExpandedOutput, ExpansionShaderIDs.ThreadGroupSizeX, (int)reduceThreadGroupSizeX);
cmd.SetComputeBufferParam(populateReduceExpandedOutput, populateReduceExpandedOutputKernel, ExpansionShaderIDs.CompactedGBufferLength, compactedGBufferLength);
cmd.SetComputeBufferParam(populateReduceExpandedOutput, populateReduceExpandedOutputKernel, ExpansionShaderIDs.ReduceDispatchBuffer, reduceDispatchBuffer);
cmd.DispatchCompute(populateReduceExpandedOutput, populateReduceExpandedOutputKernel, 1, 1, 1);
//LightmapIntegrationHelpers.LogGraphicsBuffer(cmd, reduceDispatchBuffer, "reduceDispatchBuffer");
return 1;
}
static internal int ReduceExpandedOutput(CommandBuffer cmd, ComputeShader binaryGroupSumLeftShader, int binaryGroupSumLeftKernel, GraphicsBuffer expandedOutput, int expandedDispatchSize, uint expandedSampleWidth, GraphicsBuffer reduceDispatch)
{
Debug.Assert(math.ispow2(expandedSampleWidth));
// the expandedOutput buffer contains groups of expandedSampleWidth samples
// do binary summation within the sample groups ending up with summed samples in the leftmost sample for each texel
cmd.SetComputeBufferParam(binaryGroupSumLeftShader, binaryGroupSumLeftKernel, ExpansionShaderIDs.Float4Buffer, expandedOutput);
cmd.SetComputeIntParam(binaryGroupSumLeftShader, ExpansionShaderIDs.BinaryBufferSize, expandedDispatchSize);
int groupSize = 1;
int dispatches = 0;
while (groupSize < expandedSampleWidth)
{
cmd.SetComputeIntParam(binaryGroupSumLeftShader, ExpansionShaderIDs.BinaryGroupSize, groupSize);
cmd.BeginSample(k_BinarySum);
cmd.DispatchCompute(binaryGroupSumLeftShader, binaryGroupSumLeftKernel, reduceDispatch, 0);
cmd.EndSample(k_BinarySum);
groupSize *= 2;
dispatches++;
}
return dispatches;
}
static internal int PopulateCopyToLightmapIndirectDispatch(CommandBuffer cmd, ComputeShader populateCopyToLightmap, int populateCopyToLightmapKernel, uint copyThreadGroupSizeX, GraphicsBuffer compactedGBufferLength, GraphicsBuffer copyDispatch)
{
// Populate the expanded copy indirect dispatch buffer - using the compacted size.
cmd.SetComputeIntParam(populateCopyToLightmap, ExpansionShaderIDs.ThreadGroupSizeX, (int)copyThreadGroupSizeX);
cmd.SetComputeBufferParam(populateCopyToLightmap, populateCopyToLightmapKernel, ExpansionShaderIDs.CompactedGBufferLength, compactedGBufferLength);
cmd.SetComputeBufferParam(populateCopyToLightmap, populateCopyToLightmapKernel, ExpansionShaderIDs.CopyDispatchBuffer, copyDispatch);
cmd.DispatchCompute(populateCopyToLightmap, populateCopyToLightmapKernel, 1, 1, 1);
//LightmapIntegrationHelpers.LogGraphicsBuffer(cmd, copyDispatch, "copyDispatch");
return 1;
}
static internal int CopyToLightmap(CommandBuffer cmd, ComputeShader copyToLightmap, int copyToLightmapKernel, uint expandedSampleWidth, int instanceWidth, Vector2Int instanceTexelOffset, uint2 chunkOffset, GraphicsBuffer compactedGBufferLength, GraphicsBuffer compactedTexelIndices, GraphicsBuffer expandedOutput, GraphicsBuffer copyDispatch, RenderTexture output)
{
cmd.SetComputeBufferParam(copyToLightmap, copyToLightmapKernel, ExpansionShaderIDs.SourceBuffer, expandedOutput);
cmd.SetComputeIntParam(copyToLightmap, ExpansionShaderIDs.SourceStride, (int)expandedSampleWidth);
cmd.SetComputeTextureParam(copyToLightmap, copyToLightmapKernel, ExpansionShaderIDs.DestinationTexture, output);
cmd.SetComputeBufferParam(copyToLightmap, copyToLightmapKernel, ExpansionShaderIDs.CompactedGBuffer, compactedTexelIndices);
cmd.SetComputeBufferParam(copyToLightmap, copyToLightmapKernel, ExpansionShaderIDs.CompactedGBufferLength, compactedGBufferLength);
cmd.SetComputeIntParam(copyToLightmap, ExpansionShaderIDs.InstanceWidth, instanceWidth);
cmd.SetComputeIntParam(copyToLightmap, ExpansionShaderIDs.DestinationX, instanceTexelOffset.x);
cmd.SetComputeIntParam(copyToLightmap, ExpansionShaderIDs.DestinationY, instanceTexelOffset.y);
cmd.SetComputeIntParam(copyToLightmap, ExpansionShaderIDs.ChunkOffsetX, (int)chunkOffset.x);
cmd.SetComputeIntParam(copyToLightmap, ExpansionShaderIDs.ChunkOffsetY, (int)chunkOffset.y);
copyToLightmap.GetKernelThreadGroupSizes(copyToLightmapKernel, out uint copyx, out uint _, out _);
cmd.BeginSample(k_CopyToLightmap);
cmd.DispatchCompute(copyToLightmap, copyToLightmapKernel, copyDispatch, 0);
cmd.EndSample(k_CopyToLightmap);
return 1;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 96b2515d277249b4586313e2b9578b83
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1b7f24ec37ad098488d9130f9203f68a
@@ -0,0 +1,681 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using Unity.Mathematics;
using Unity.Profiling;
using Unity.Profiling.LowLevel;
using UnityEngine.Assertions;
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
namespace UnityEngine.PathTracing.Lightmapping
{
internal static class LightmapIntegrationHelpers
{
/// <summary>
/// Profiles the box filtering pass applied to the blue channel of the lightmap output,
/// used to smooth validity values through an indirect compute dispatch.
/// </summary>
static readonly ProfilerMarker k_BoxFiltering =
new ProfilerMarker(ProfilerCategory.Render, "BoxFiltering",
MarkerFlags.Default | MarkerFlags.SampleGPU);
internal class ComputeHelpers
{
internal ComputeShader ComputeHelperShader = null;
internal static class ShaderIDs
{
public static readonly int TextureInOut = Shader.PropertyToID("g_TextureInOut");
public static readonly int SampleCountInW = Shader.PropertyToID("g_SampleCountInW");
public static readonly int VarianceInR = Shader.PropertyToID("g_VarianceInR");
public static readonly int StandardErrorInR = Shader.PropertyToID("g_StandardErrorInR");
public static readonly int MeanInR = Shader.PropertyToID("g_MeanInR");
public static readonly int SourceTexture = Shader.PropertyToID("g_SourceTexture");
public static readonly int OutputBuffer = Shader.PropertyToID("g_OutputBuffer");
public static readonly int X = Shader.PropertyToID("g_X");
public static readonly int Y = Shader.PropertyToID("g_Y");
public static readonly int TextureOut = Shader.PropertyToID("g_TextureOut");
public static readonly int TextureWidth = Shader.PropertyToID("g_TextureWidth");
public static readonly int TextureHeight = Shader.PropertyToID("g_TextureHeight");
public static readonly int MultiplicationFactor = Shader.PropertyToID("g_MultiplicationFactor");
public static readonly int BoxFilterRadius = Shader.PropertyToID("g_BoxFilterRadius");
public static readonly int StandardErrorThreshold = Shader.PropertyToID("g_StandardErrorThreshold");
public static readonly int ChannelIndex = Shader.PropertyToID("g_ChannelIndex");
public static readonly int ChannelValue = Shader.PropertyToID("g_ChannelValue");
public static readonly int TemporaryRenderTarget = Shader.PropertyToID("g_TemporaryRenderTarget");
public static readonly int SecondTemporaryRenderTarget = Shader.PropertyToID("g_SecondTemporaryRenderTarget");
public static readonly int MultiplyTemporaryRenderTarget = Shader.PropertyToID("g_MultiplyTemporaryRenderTarget");
public static readonly int DestinationTexture = Shader.PropertyToID("g_DestinationTexture");
public static readonly int SourceX = Shader.PropertyToID("g_SourceX");
public static readonly int SourceY = Shader.PropertyToID("g_SourceY");
public static readonly int SourceWidth = Shader.PropertyToID("g_SourceWidth");
public static readonly int SourceHeight = Shader.PropertyToID("g_SourceHeight");
public static readonly int DestinationX = Shader.PropertyToID("g_DestinationX");
public static readonly int DestinationY = Shader.PropertyToID("g_DestinationY");
}
internal static int MultiplyKernel;
internal static int BroadcastChannelKernel;
internal static int SetChannelKernel;
internal static int ReferenceBoxFilterKernel;
internal static int ReferenceBoxFilterBlueChannelKernel;
internal static int StandardErrorKernel;
internal static int StandardErrorThresholdKernel;
internal static int GetValueKernel;
internal static int NormalizeByAlphaKernel;
internal static int CopyTextureAdditiveKernel;
internal static int MaskAlphaChannelKernel;
/// <summary>
/// Profiles the additive texture copy compute dispatch that blends a source region
/// into a destination region of a lightmap during accumulation.
/// </summary>
static readonly ProfilerMarker k_CopyTextureAdditive =
new ProfilerMarker(ProfilerCategory.Render, "CopyTextureAdditive",
MarkerFlags.Default | MarkerFlags.SampleGPU);
/// <summary>
/// Profiles the alpha channel mask compute dispatch that clears or fills the alpha
/// channel of a lightmap texture to mark valid texel coverage.
/// </summary>
static readonly ProfilerMarker k_MaskAlphaChannel =
new ProfilerMarker(ProfilerCategory.Render, "MaskAlphaChannel",
MarkerFlags.Default | MarkerFlags.SampleGPU);
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
MultiplyKernel = -1;
BroadcastChannelKernel = -1;
SetChannelKernel = -1;
ReferenceBoxFilterKernel = -1;
ReferenceBoxFilterBlueChannelKernel = -1;
StandardErrorKernel = -1;
StandardErrorThresholdKernel = -1;
GetValueKernel = -1;
NormalizeByAlphaKernel = -1;
}
#endif
public void Load()
{
#if UNITY_EDITOR
const string packageFolder = "Packages/com.unity.render-pipelines.core/Runtime/PathTracing/";
ComputeHelperShader = UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(packageFolder + "Shaders/ComputeHelpers.compute");
#endif
if (ComputeHelperShader != null)
{
MultiplyKernel = ComputeHelperShader.FindKernel("Multiply");
BroadcastChannelKernel = ComputeHelperShader.FindKernel("BroadcastChannel");
SetChannelKernel = ComputeHelperShader.FindKernel("SetChannel");
ReferenceBoxFilterKernel = ComputeHelperShader.FindKernel("ReferenceBoxFilter");
ReferenceBoxFilterBlueChannelKernel = ComputeHelperShader.FindKernel("ReferenceBoxFilterBlueChannel");
StandardErrorKernel = ComputeHelperShader.FindKernel("StandardError");
StandardErrorThresholdKernel = ComputeHelperShader.FindKernel("StandardErrorThreshold");
GetValueKernel = ComputeHelperShader.FindKernel("GetValue");
NormalizeByAlphaKernel = ComputeHelperShader.FindKernel("NormalizeByAlpha");
CopyTextureAdditiveKernel = ComputeHelperShader.FindKernel("CopyTextureAdditive");
MaskAlphaChannelKernel = ComputeHelperShader.FindKernel("MaskAlphaChannel");
}
}
public void CopyTextureAdditive(CommandBuffer cmd, RenderTargetIdentifier source, RenderTargetIdentifier destination,
int width, int height, int sourceX = 0, int sourceY = 0, int destinationX = 0, int destinationY = 0)
{
cmd.BeginSample(k_CopyTextureAdditive);
cmd.SetComputeTextureParam(ComputeHelperShader, CopyTextureAdditiveKernel, ShaderIDs.SourceTexture, source);
cmd.SetComputeTextureParam(ComputeHelperShader, CopyTextureAdditiveKernel, ShaderIDs.DestinationTexture, destination);
cmd.SetComputeIntParam(ComputeHelperShader, ShaderIDs.SourceWidth, width);
cmd.SetComputeIntParam(ComputeHelperShader, ShaderIDs.SourceHeight, height);
cmd.SetComputeIntParam(ComputeHelperShader, ShaderIDs.SourceX, sourceX);
cmd.SetComputeIntParam(ComputeHelperShader, ShaderIDs.SourceY, sourceY);
cmd.SetComputeIntParam(ComputeHelperShader, ShaderIDs.DestinationX, destinationX);
cmd.SetComputeIntParam(ComputeHelperShader, ShaderIDs.DestinationY, destinationY);
ComputeHelperShader.GetKernelThreadGroupSizes(CopyTextureAdditiveKernel, out uint groupX, out uint groupY, out _);
cmd.DispatchCompute(ComputeHelperShader, CopyTextureAdditiveKernel, GraphicsHelpers.DivUp(width, groupX), GraphicsHelpers.DivUp(height, groupY), 1);
cmd.EndSample(k_CopyTextureAdditive);
}
public void MaskAlphaChannel(CommandBuffer cmd, RenderTargetIdentifier texture, int width, int height)
{
cmd.BeginSample(k_MaskAlphaChannel);
cmd.SetComputeTextureParam(ComputeHelperShader, MaskAlphaChannelKernel, ShaderIDs.TextureInOut, texture);
cmd.SetComputeIntParam(ComputeHelperShader, ShaderIDs.TextureWidth, width);
cmd.SetComputeIntParam(ComputeHelperShader, ShaderIDs.TextureHeight, height);
ComputeHelperShader.GetKernelThreadGroupSizes(MaskAlphaChannelKernel, out uint groupX, out uint groupY, out _);
cmd.DispatchCompute(ComputeHelperShader, MaskAlphaChannelKernel, GraphicsHelpers.DivUp(width, groupX), GraphicsHelpers.DivUp(height, groupY), 1);
cmd.EndSample(k_MaskAlphaChannel);
}
}
public class GPUSync : IDisposable
{
private RenderTexture _syncTexture;
private Texture2D _readableTex;
public void Create()
{
Debug.Assert(_syncTexture == null);
_syncTexture = new RenderTexture(1, 1, 0, RenderTextureFormat.ARGB32)
{
name = "_syncTexture",
enableRandomWrite = true,
hideFlags = HideFlags.HideAndDontSave
};
_syncTexture.Create();
_readableTex = new Texture2D(_syncTexture.width, _syncTexture.height, TextureFormat.ARGB32, false, true)
{
name = "_readableTex",
hideFlags = HideFlags.HideAndDontSave
};
}
public void Sync(CommandBuffer cmd)
{
Debug.Assert(_syncTexture != null, "Create must be called before Sync.");
Debug.Assert(_readableTex != null, "Create must be called before Sync.");
cmd.SetRenderTarget(_syncTexture);
cmd.ClearRenderTarget(false, true, new Color32(1, 2, 3, 4));
cmd.RequestAsyncReadback(_syncTexture, delegate { });
cmd.WaitAllAsyncReadbackRequests();
GraphicsHelpers.Flush(cmd);
}
public void RequestAsyncReadback(CommandBuffer cmd, Action<AsyncGPUReadbackRequest> callback) =>
cmd.RequestAsyncReadback(_syncTexture, callback);
public void Dispose()
{
if (_syncTexture != null)
{
_syncTexture.Release();
CoreUtils.Destroy(_syncTexture);
_syncTexture = null;
}
if (_readableTex == null)
return;
CoreUtils.Destroy(_readableTex);
_readableTex = null;
}
}
private static string IntegratedOutputTypeToComponentName(IntegratedOutputType integratedOutputType)
{
switch (integratedOutputType)
{
case IntegratedOutputType.Direct: return "irradianceDirect";
case IntegratedOutputType.DirectBRDF: return "irradianceDirectBRDF";
case IntegratedOutputType.Indirect: return "irradianceIndirect";
case IntegratedOutputType.AO: return "ambientOcclusion";
case IntegratedOutputType.Validity: return "validity";
case IntegratedOutputType.DirectionalityDirect: return "directionalityDirect";
case IntegratedOutputType.DirectionalityDirectBRDF: return "directionalityDirectBRDF";
case IntegratedOutputType.DirectionalityIndirect: return "directionalityIndirect";
case IntegratedOutputType.ShadowMask: return "shadowmask";
default:
{
Debug.Assert(false, "Missing lightmap type in LightmapTypeToComponentName");
return "Missing lightmap type in LightmapTypeToComponentName";
}
}
}
static string BuildLightmapComponentPath(string outputType, int lightmapIndex, string path)
{
// Naming convention is path/componentName+LightmapIndex.r2d
return $"{path}/{outputType}{lightmapIndex}.r2d";
}
public static bool WriteLightmap(CommandBuffer cmd, RenderTexture renderTex, string outputType, int lightmapIndex, string path)
{
try
{
DirectoryInfo directoryInfo = Directory.CreateDirectory(path);
if (directoryInfo.Exists == false)
return false;
string fullPath = BuildLightmapComponentPath(outputType, lightmapIndex, path);
SerializationHelpers.WriteRenderTexture(cmd, fullPath, renderTex);
return true;
}
catch (Exception e)
{
Debug.Assert(false, e.Message);
return false;
}
}
public static bool WriteLightmap(CommandBuffer cmd, RenderTexture renderTex, IntegratedOutputType integratedOutputType, int lightmapIndex, string path)
{
return WriteLightmap(cmd, renderTex, IntegratedOutputTypeToComponentName(integratedOutputType),
lightmapIndex, path);
}
public static Texture2D ReadLightmap(IntegratedOutputType integratedOutputType, int lightmapIndex, string path)
{
#if ENABLE_IMAGECONVERSION_MODULE
Texture2D tex = new(2, 2);
byte[] bytes = File.ReadAllBytes(BuildLightmapComponentPath(IntegratedOutputTypeToComponentName(integratedOutputType), lightmapIndex, path));
bool ret = ImageConversion.LoadImage(tex, bytes);
if (!ret)
return null;
return tex;
#else
Debug.Assert(false, "The Image Conversion Module is not available.");
return null;
#endif
}
private static void OutputUIntRequestData(string prefix, AsyncGPUReadbackRequest request)
{
string output = new("");
Debug.Assert(!request.hasError);
if (!request.hasError)
{
var src = request.GetData<uint>();
output = $"{prefix}:\n";
for (int i = 0; i < src.Length; ++i)
{
output += src[i];
if (i < src.Length - 1)
output += "\n";
}
}
else
output = "AsyncReadBack failed";
System.Console.WriteLine(output);
}
private static void OutputFloat2RequestData(string prefix, AsyncGPUReadbackRequest request)
{
string output = new("");
Debug.Assert(!request.hasError);
if (!request.hasError)
{
var src = request.GetData<float>();
Debug.Assert(src.Length % 2 == 0);
output = $"{prefix}:\n";
for (int i = 0; i < src.Length; i += 2)
{
output += string.Format(System.Globalization.CultureInfo.InvariantCulture, "float2({0}, {1})", src[i], src[i + 1]);
if (i < src.Length - 1)
output += "\n";
}
}
else
output = "AsyncReadBack failed";
System.Console.WriteLine(output);
}
private static void OutputFloat4RequestData(string prefix, AsyncGPUReadbackRequest request)
{
string output = new("");
Debug.Assert(!request.hasError);
if (!request.hasError)
{
var src = request.GetData<float>();
Debug.Assert(src.Length % 4 == 0);
output = $"{prefix}:\n";
for (int i = 0; i < src.Length; i+=4)
{
output += string.Format(System.Globalization.CultureInfo.InvariantCulture, "float4({0}, {1}, {2}, {3})", src[i], src[i + 1], src[i + 2], src[i + 3]);
if (i < src.Length - 1)
output += "\n";
}
}
else
output = "AsyncReadBack failed";
System.Console.WriteLine(output);
}
public struct HitEntry
{
public uint instanceID;
public uint primitiveIndex;
public Unity.Mathematics.float2 barycentrics;
};
private static void OutputHitEntryRequestData(string prefix, AsyncGPUReadbackRequest request)
{
string output = new("");
Debug.Assert(!request.hasError);
if (!request.hasError)
{
var src = request.GetData<HitEntry>();
output = $"{prefix}:\n";
for (int i = 0; i < src.Length; i++)
{
output += $"hitEntry({src[i].instanceID}, {src[i].primitiveIndex}, bary: [{src[i].barycentrics.x}, {src[i].barycentrics.y}])";
if (i < src.Length - 1)
output += "\n";
}
}
else
output = "AsyncReadBack failed";
System.Console.WriteLine(output);
}
public enum LogBufferType
{
UInt,
Float2,
Float4,
HitEntry
}
public static void LogGraphicsBuffer(CommandBuffer cmd, GraphicsBuffer graphicsBuffer, string prefix, LogBufferType type)
{
using GraphicsBuffer stagingBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopyDestination, graphicsBuffer.count, graphicsBuffer.stride);
cmd.CopyBuffer(graphicsBuffer, stagingBuffer);
switch (type)
{
case LogBufferType.UInt:
Debug.Assert(graphicsBuffer.stride == 4);
cmd.RequestAsyncReadback(stagingBuffer, (AsyncGPUReadbackRequest request) => { OutputUIntRequestData(prefix, request); });
break;
case LogBufferType.Float2:
Debug.Assert(graphicsBuffer.stride == 8);
cmd.RequestAsyncReadback(stagingBuffer, (AsyncGPUReadbackRequest request) => { OutputFloat2RequestData(prefix, request); });
break;
case LogBufferType.Float4:
Debug.Assert(graphicsBuffer.stride == 16);
cmd.RequestAsyncReadback(stagingBuffer, (AsyncGPUReadbackRequest request) => { OutputFloat4RequestData(prefix, request); });
break;
case LogBufferType.HitEntry:
Debug.Assert(graphicsBuffer.stride == 16);
cmd.RequestAsyncReadback(stagingBuffer, (AsyncGPUReadbackRequest request) => { OutputHitEntryRequestData(prefix, request); });
break;
default:
Debug.LogWarning($"LogGraphicsBuffer: GraphicsBuffer type {type} is not implemented.");
break;
}
cmd.WaitAllAsyncReadbackRequests();
Graphics.ExecuteCommandBuffer(cmd);
cmd.Clear();
}
public static bool IsPow2(int value) => (value & (value - 1)) == 0 && value > 0;
internal static GraphicsBuffer CreateDispatchDimensionBuffer()
{
return new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments | GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource, 3, sizeof(uint));
}
public static double4 GetSum(int width, int height, RenderTexture renderTex)
{
RenderTexture previous = RenderTexture.active;
RenderTexture.active = renderTex;
Texture2D readableTex = new Texture2D(width, height, TextureFormat.RGBAFloat, false, true) { name = "GetSum.readableTex", hideFlags = HideFlags.HideAndDontSave };
Assert.IsTrue(readableTex.isReadable);
readableTex.ReadPixels(new Rect(0, 0, width, height), 0, 0);
RenderTexture.active = previous;
Color[] colors = readableTex.GetPixels();
double4 colorSum = new double4(0.0, 0.0, 0.0, 0.0);
foreach (var color in colors)
colorSum += new double4(color.r, color.g, color.b, color.a);
CoreUtils.Destroy(readableTex);
return colorSum;
}
public static float Luminance(Color color)
{
return color.r * 0.2126f + color.g * 0.7152f + color.b * 0.0722f;
}
public static Color GetValue(CommandBuffer cmd, ComputeShader computeShader, int getValueKernel, int sampleX, int sampleY, int width, int height, RenderTargetIdentifier renderTargetIdentifier)
{
using ComputeBuffer colorBuffer = new(4, sizeof(float));
cmd.SetComputeBufferParam(computeShader, getValueKernel, ComputeHelpers.ShaderIDs.OutputBuffer, colorBuffer);
cmd.SetComputeTextureParam(computeShader, getValueKernel, ComputeHelpers.ShaderIDs.SourceTexture, renderTargetIdentifier);
cmd.SetComputeIntParam(computeShader, ComputeHelpers.ShaderIDs.TextureWidth, width);
cmd.SetComputeIntParam(computeShader, ComputeHelpers.ShaderIDs.TextureHeight, height);
cmd.SetComputeIntParam(computeShader, ComputeHelpers.ShaderIDs.X, sampleX);
cmd.SetComputeIntParam(computeShader, ComputeHelpers.ShaderIDs.Y, sampleY);
computeShader.GetKernelThreadGroupSizes(getValueKernel, out uint x, out uint y, out _);
cmd.DispatchCompute(computeShader, getValueKernel, GraphicsHelpers.DivUp(width, x), GraphicsHelpers.DivUp(height, y), 1);
Graphics.ExecuteCommandBuffer(cmd);
cmd.Clear();
float[] tempColorArray = new float[4];
colorBuffer.GetData(tempColorArray);
colorBuffer.Release();
return new Color(tempColorArray[0], tempColorArray[1], tempColorArray[2], tempColorArray[3]);
}
public static void NormalizeByAlpha(CommandBuffer cmd, ComputeShader computeShader, int normalizeByAlphaKernel, int width, int height, RenderTargetIdentifier inOut)
{
cmd.SetComputeTextureParam(computeShader, normalizeByAlphaKernel, ComputeHelpers.ShaderIDs.TextureInOut, inOut);
cmd.SetComputeIntParam(computeShader, ComputeHelpers.ShaderIDs.TextureWidth, width);
cmd.SetComputeIntParam(computeShader, ComputeHelpers.ShaderIDs.TextureHeight, height);
computeShader.GetKernelThreadGroupSizes(normalizeByAlphaKernel, out uint x, out uint y, out _);
cmd.DispatchCompute(computeShader, normalizeByAlphaKernel, GraphicsHelpers.DivUp(width, x), GraphicsHelpers.DivUp(height, y), 1);
}
public static void MultiplyRenderTexture(CommandBuffer cmd, ComputeShader multiplyShader, int multiplyKernel, RenderTargetIdentifier inOut, int width, int height, Vector4 multiplicationFactor)
{
cmd.SetComputeTextureParam(multiplyShader, multiplyKernel, ComputeHelpers.ShaderIDs.TextureInOut, inOut);
cmd.SetComputeIntParam(multiplyShader, ComputeHelpers.ShaderIDs.TextureWidth, width);
cmd.SetComputeIntParam(multiplyShader, ComputeHelpers.ShaderIDs.TextureHeight, height);
cmd.SetComputeVectorParam(multiplyShader, ComputeHelpers.ShaderIDs.MultiplicationFactor, multiplicationFactor);
multiplyShader.GetKernelThreadGroupSizes(multiplyKernel, out uint x, out uint y, out _);
cmd.DispatchCompute(multiplyShader, multiplyKernel, GraphicsHelpers.DivUp(width, x), GraphicsHelpers.DivUp(height, y), 1);
}
public static void MultiplyTexture(CommandBuffer cmd, ComputeShader multiplyShader, int multiplyKernel, Texture2D texture, Vector4 multiplicationFactor)
{
int renderTargetID = ComputeHelpers.ShaderIDs.MultiplyTemporaryRenderTarget;
cmd.GetTemporaryRT(renderTargetID, texture.width, texture.height, 0, FilterMode.Point, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear, 1, true);
cmd.CopyTexture(texture, renderTargetID);
LightmapIntegrationHelpers.MultiplyRenderTexture(cmd, multiplyShader, multiplyKernel, renderTargetID, texture.width, texture.height, multiplicationFactor);
cmd.CopyTexture(renderTargetID, texture);
cmd.ReleaseTemporaryRT(renderTargetID);
}
public static void StandardErrorRenderTexture(CommandBuffer cmd, ComputeShader standardError, int standardErrorKernel, RenderTargetIdentifier varianceInR, RenderTargetIdentifier sampleCountInW, RenderTargetIdentifier output, int width, int height)
{
cmd.SetComputeTextureParam(standardError, standardErrorKernel, ComputeHelpers.ShaderIDs.VarianceInR, varianceInR);
cmd.SetComputeTextureParam(standardError, standardErrorKernel, ComputeHelpers.ShaderIDs.SampleCountInW, sampleCountInW);
cmd.SetComputeTextureParam(standardError, standardErrorKernel, ComputeHelpers.ShaderIDs.TextureOut, output);
cmd.SetComputeIntParam(standardError, ComputeHelpers.ShaderIDs.TextureWidth, width);
cmd.SetComputeIntParam(standardError, ComputeHelpers.ShaderIDs.TextureHeight, height);
standardError.GetKernelThreadGroupSizes(standardErrorKernel, out uint x, out uint y, out _);
cmd.DispatchCompute(standardError, standardErrorKernel, GraphicsHelpers.DivUp(width, x), GraphicsHelpers.DivUp(height, y), 1);
}
public static void StandardErrorThresholdRenderTexture(CommandBuffer cmd, ComputeShader standardErrorThreshold, int StandardErrorThresholdKernel, RenderTargetIdentifier standardErrorInR, RenderTargetIdentifier meanInR, float standardErrorThresholdValue, RenderTargetIdentifier output, int width, int height)
{
cmd.SetComputeTextureParam(standardErrorThreshold, StandardErrorThresholdKernel, ComputeHelpers.ShaderIDs.StandardErrorInR, standardErrorInR);
cmd.SetComputeTextureParam(standardErrorThreshold, StandardErrorThresholdKernel, ComputeHelpers.ShaderIDs.MeanInR, meanInR);
cmd.SetComputeTextureParam(standardErrorThreshold, StandardErrorThresholdKernel, ComputeHelpers.ShaderIDs.TextureOut, output);
cmd.SetComputeFloatParam(standardErrorThreshold, ComputeHelpers.ShaderIDs.StandardErrorThreshold, standardErrorThresholdValue);
cmd.SetComputeIntParam(standardErrorThreshold, ComputeHelpers.ShaderIDs.TextureWidth, width);
cmd.SetComputeIntParam(standardErrorThreshold, ComputeHelpers.ShaderIDs.TextureHeight, height);
standardErrorThreshold.GetKernelThreadGroupSizes(StandardErrorThresholdKernel, out uint x, out uint y, out _);
cmd.DispatchCompute(standardErrorThreshold, StandardErrorThresholdKernel, GraphicsHelpers.DivUp(width, x), GraphicsHelpers.DivUp(height, y), 1);
}
public static void BroadcastChannelRenderTexture(CommandBuffer cmd, ComputeShader broadcastChannelShader, int broadcastChannelKernel, RenderTargetIdentifier inOut, int width, int height, int channelIndex)
{
cmd.SetComputeTextureParam(broadcastChannelShader, broadcastChannelKernel, ComputeHelpers.ShaderIDs.TextureInOut, inOut);
cmd.SetComputeIntParam(broadcastChannelShader, ComputeHelpers.ShaderIDs.TextureWidth, width);
cmd.SetComputeIntParam(broadcastChannelShader, ComputeHelpers.ShaderIDs.TextureHeight, height);
cmd.SetComputeIntParam(broadcastChannelShader, ComputeHelpers.ShaderIDs.ChannelIndex, channelIndex);
broadcastChannelShader.GetKernelThreadGroupSizes(broadcastChannelKernel, out uint x, out uint y, out _);
cmd.DispatchCompute(broadcastChannelShader, broadcastChannelKernel, GraphicsHelpers.DivUp(width, x), GraphicsHelpers.DivUp(height, y), 1);
}
public static void SetChannelRenderTexture(CommandBuffer cmd, ComputeShader setChannelShader, int setChannelKernel, RenderTargetIdentifier inOut, int width, int height, int channelIndex, float channelValue)
{
cmd.SetComputeTextureParam(setChannelShader, setChannelKernel, ComputeHelpers.ShaderIDs.TextureInOut, inOut);
cmd.SetComputeIntParam(setChannelShader, ComputeHelpers.ShaderIDs.TextureWidth, width);
cmd.SetComputeIntParam(setChannelShader, ComputeHelpers.ShaderIDs.TextureHeight, height);
cmd.SetComputeIntParam(setChannelShader, ComputeHelpers.ShaderIDs.ChannelIndex, channelIndex);
cmd.SetComputeFloatParam(setChannelShader, ComputeHelpers.ShaderIDs.ChannelValue, channelValue);
setChannelShader.GetKernelThreadGroupSizes(setChannelKernel, out uint x, out uint y, out _);
cmd.DispatchCompute(setChannelShader, setChannelKernel, GraphicsHelpers.DivUp(width, x), GraphicsHelpers.DivUp(height, y), 1);
}
public static void ReferenceBoxFilterRenderTexture(CommandBuffer cmd, ComputeShader referenceBoxFilterShader, int referenceBoxFilterKernel, RenderTargetIdentifier inOut, int width, int height, int radius)
{
cmd.GetTemporaryRT(ComputeHelpers.ShaderIDs.TextureOut, width, height, 0, FilterMode.Point, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear, 1, true);
cmd.SetComputeTextureParam(referenceBoxFilterShader, referenceBoxFilterKernel, ComputeHelpers.ShaderIDs.SourceTexture, inOut);
cmd.SetComputeTextureParam(referenceBoxFilterShader, referenceBoxFilterKernel, ComputeHelpers.ShaderIDs.TextureOut, ComputeHelpers.ShaderIDs.TextureOut);
cmd.SetComputeIntParam(referenceBoxFilterShader, ComputeHelpers.ShaderIDs.TextureWidth, width);
cmd.SetComputeIntParam(referenceBoxFilterShader, ComputeHelpers.ShaderIDs.TextureHeight, height);
cmd.SetComputeIntParam(referenceBoxFilterShader, ComputeHelpers.ShaderIDs.BoxFilterRadius, radius);
referenceBoxFilterShader.GetKernelThreadGroupSizes(referenceBoxFilterKernel, out uint x, out uint y, out _);
cmd.DispatchCompute(referenceBoxFilterShader, referenceBoxFilterKernel, GraphicsHelpers.DivUp(width, x), GraphicsHelpers.DivUp(height, y), 1);
cmd.CopyTexture(ComputeHelpers.ShaderIDs.TextureOut, inOut);
cmd.ReleaseTemporaryRT(ComputeHelpers.ShaderIDs.TextureOut);
}
public static void ReferenceBoxFilterBlueChannelRenderTexture(CommandBuffer cmd, ComputeShader referenceBoxFilterBlueChannelShader, int referenceBoxFilterBlueChannelKernel, RenderTargetIdentifier inOut, int width, int height, int radius, GraphicsBuffer indirectDispatchBuffer)
{
cmd.BeginSample(k_BoxFiltering);
cmd.GetTemporaryRT(ComputeHelpers.ShaderIDs.TextureOut, width, height, 0, FilterMode.Point, RenderTextureFormat.ARGBFloat, RenderTextureReadWrite.Linear, 1, true);
cmd.SetComputeTextureParam(referenceBoxFilterBlueChannelShader, referenceBoxFilterBlueChannelKernel, ComputeHelpers.ShaderIDs.SourceTexture, inOut);
cmd.SetComputeTextureParam(referenceBoxFilterBlueChannelShader, referenceBoxFilterBlueChannelKernel, ComputeHelpers.ShaderIDs.TextureOut, ComputeHelpers.ShaderIDs.TextureOut);
cmd.SetComputeIntParam(referenceBoxFilterBlueChannelShader, ComputeHelpers.ShaderIDs.TextureWidth, width);
cmd.SetComputeIntParam(referenceBoxFilterBlueChannelShader, ComputeHelpers.ShaderIDs.TextureHeight, height);
cmd.SetComputeIntParam(referenceBoxFilterBlueChannelShader, ComputeHelpers.ShaderIDs.BoxFilterRadius, radius);
cmd.DispatchCompute(referenceBoxFilterBlueChannelShader, referenceBoxFilterBlueChannelKernel, indirectDispatchBuffer, 0);
cmd.CopyTexture(ComputeHelpers.ShaderIDs.TextureOut, inOut); // TODO(jesper): dont do copy
cmd.ReleaseTemporaryRT(ComputeHelpers.ShaderIDs.TextureOut);
cmd.EndSample(k_BoxFiltering);
}
// Computes the region of a lightmap that is occupied by the pixels of a specific instance,
// given the lightmap size, the instance's scale and offset within the lightmap (lightmap ST),
// and the bounding box of the instance's UVs.
//
// NOTE: Only considering the region defined by the instance's lightmap ST causes issues, because
// these regions can overlap for multiple instances, when the instance's UV layout doesn't fully
// cover the [0; 1] range. We pack based on tight bounding boxes of the instance's UVs,
// but lightmap STs are with respect to the instance's entire UV layout.
// It is assumed that the lightmap offset is aligned to either half or full texel.
internal static void ComputeOccupiedTexelRegionForInstance(
uint lightmapWidth,
uint lightmapHeight,
Vector4 instanceLightmapST,
Vector2 uvBoundsSize,
Vector2 uvBoundsOffset,
out Vector4 normalizedOccupiedST,
out Vector2Int occupiedTexelSize,
out Vector2Int occupiedTexelOffset)
{
// Transform the "instance stamp" bounds to contain only the occupied region.
float normalizedOccupiedWidth = instanceLightmapST.x * uvBoundsSize.x;
float normalizedOccupiedHeight = instanceLightmapST.y * uvBoundsSize.y;
float normalizedOccupiedOffsetX = instanceLightmapST.z + uvBoundsOffset.x * instanceLightmapST.x;
float normalizedOccupiedOffsetY = instanceLightmapST.w + uvBoundsOffset.y * instanceLightmapST.y;
normalizedOccupiedST = new Vector4(normalizedOccupiedWidth, normalizedOccupiedHeight, normalizedOccupiedOffsetX, normalizedOccupiedOffsetY);
// Transform the occupied region to lightmap pixel coordinate space.
float occupiedWidth = lightmapWidth * normalizedOccupiedWidth;
float occupiedHeight = lightmapHeight * normalizedOccupiedHeight;
float occupiedOffsetX = lightmapWidth * normalizedOccupiedOffsetX;
float occupiedOffsetY = lightmapHeight * normalizedOccupiedOffsetY;
// Round up to the nearest integer to ensure we cover all texels that the instance's UVs touch.
occupiedTexelSize = new(Mathf.CeilToInt(occupiedWidth), Mathf.CeilToInt(occupiedHeight));
// Clamp the occupied region to the lightmap bounds.
float occupiedTexelOffsetXFloat = Mathf.Max(occupiedOffsetX, 0f);
float occupiedTexelOffsetYFloat = Mathf.Max(occupiedOffsetY, 0f);
// Get the fractional value
float offsetFracX = Mathf.Abs(occupiedTexelOffsetXFloat - Mathf.Floor(occupiedTexelOffsetXFloat));
float offsetFracY = Mathf.Abs(occupiedTexelOffsetYFloat - Mathf.Floor(occupiedTexelOffsetYFloat));
// Check that we are either aligned to half or full texel
float distanceToHalfX = Mathf.Abs(offsetFracX - 0.5f);
float distanceToHalfY = Mathf.Abs(offsetFracY - 0.5f);
float distanceToWholeX = Mathf.Abs(Mathf.Round(offsetFracX) - offsetFracX);
float distanceToWholeY = Mathf.Abs(Mathf.Round(offsetFracY) - offsetFracY);
Debug.Assert(Mathf.Min(distanceToHalfX, distanceToWholeX) < 0.001f, $"Expected offset (X) to align with an offset of 0.5 (half texel) or 0.0 (whole texel). Was {occupiedTexelOffsetXFloat}. Was the scene baked with the same resolution as it was atlassed for?");
Debug.Assert(Mathf.Min(distanceToHalfY, distanceToWholeY) < 0.001f, $"Expected offset (Y) to align with an offset of 0.5 (half texel) or 0.0 (whole texel). Was {occupiedTexelOffsetYFloat}. Was the scene baked with the same resolution as it was atlassed for?");
Debug.Assert((distanceToHalfX < distanceToWholeX && distanceToHalfY < distanceToWholeY) || (distanceToHalfX > distanceToWholeX && distanceToHalfY > distanceToWholeY), "Texel alignment with an offset of 0.5 (half texel) or 0.0 (whole texel) must be the same for X and Y");
int occupiedTexelOffsetX = 0;
int occupiedTexelOffsetY = 0;
if (distanceToHalfX < distanceToWholeX)
occupiedTexelOffsetX = (int)Mathf.Floor(occupiedTexelOffsetXFloat);
else
occupiedTexelOffsetX = (int)Mathf.Round(occupiedTexelOffsetXFloat);
if (distanceToHalfY < distanceToWholeY)
occupiedTexelOffsetY = (int)Mathf.Floor(occupiedTexelOffsetYFloat);
else
occupiedTexelOffsetY = (int)Mathf.Round(occupiedTexelOffsetYFloat);
occupiedTexelOffset = new(occupiedTexelOffsetX, occupiedTexelOffsetY);
}
// Computes the bounding box of a set of UV coordinates.
internal static void ComputeUVBounds(IEnumerable<Vector2> uvs, out Vector2 size, out Vector2 offset)
{
Vector2 minUV = new Vector2(float.MaxValue, float.MaxValue);
Vector2 maxUV = new Vector2(float.MinValue, float.MinValue);
foreach (var uv in uvs)
{
minUV = Vector2.Min(minUV, uv);
maxUV = Vector2.Max(maxUV, uv);
}
size = new Vector2(maxUV.x - minUV.x, maxUV.y - minUV.y);
offset = minUV;
}
public class AdaptiveSample
{
public uint sampleCount;
public float accumulatedLuminance;
public float mean;
public float meanSqr;
public float variance;
public float varianceFiltered;
public float standardError;
public bool active;
override public string ToString()
{
string samplesString = new("");
samplesString += sampleCount.ToString() + "\t";
samplesString += accumulatedLuminance.ToString("F99").TrimEnd('0') + "\t";
samplesString += mean.ToString("F99").TrimEnd('0') + "\t";
samplesString += meanSqr.ToString("F99").TrimEnd('0') + "\t";
samplesString += variance.ToString("F99").TrimEnd('0') + "\t";
samplesString += varianceFiltered.ToString("F99").TrimEnd('0') + "\t";
samplesString += standardError.ToString("F99").TrimEnd('0') + "\t";
samplesString += active.ToString() + "\n";
return samplesString;
}
public static string HeaderString()
{
string headerString = new("");
headerString += "sampleCount\taccumulatedLuminance\tmean\tmeanSqr\tvariance\tvarianceFiltered\tstandardError\tactive\n";
return headerString;
}
static public string SamplesToString(AdaptiveSample[] samples, int x, int y, float adaptiveThreshold)
{
if (samples.Length == 0)
return "";
string samplesString = new($"data for pixel [{x}, {y}], threshold:\t{adaptiveThreshold}\n");
samplesString += AdaptiveSample.HeaderString();
foreach (AdaptiveSample sample in samples)
{
samplesString += sample.ToString();
}
return samplesString;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2e9dd43ea62c0dd43be9269bb4e53a11
@@ -0,0 +1,226 @@
using System;
using System.Collections.Generic;
using Unity.Profiling;
using Unity.Profiling.LowLevel;
using UnityEngine.PathTracing.Core;
using UnityEngine.PathTracing.Integration;
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
namespace UnityEngine.PathTracing.Lightmapping
{
internal class LightmapIntegrationResourceCache : IDisposable
{
/// <summary>
/// Profiles the build of the UV acceleration structure (BVH) over UV-space triangles,
/// used to resolve lightmap texels to world-space positions in ray tracing.
/// </summary>
static readonly ProfilerMarker k_BuildUVAccelerationStructure =
new ProfilerMarker(ProfilerCategory.Render, "Build UVAccelerationStructure",
MarkerFlags.Default | MarkerFlags.SampleGPU);
private Dictionary<ulong, UVMesh> _meshToUVMesh = new();
private Dictionary<ulong, UVAccelerationStructure> _meshToUVAccelerationStructure = new();
private Dictionary<UVFallbackBufferKey, UVFallbackBuffer> _meshToUVFallbackBuffer = new();
private struct UVFallbackBufferKey : IEquatable<UVFallbackBufferKey>
{
int width;
int height;
ulong meshInstanceID;
public UVFallbackBufferKey(int width, int height, EntityId meshInstanceID)
{
this.width = width;
this.height = height;
this.meshInstanceID = Util.EntityIDToUlong(meshInstanceID);
}
public bool Equals(UVFallbackBufferKey other) =>
width == other.width && height == other.height && meshInstanceID == other.meshInstanceID;
public override bool Equals(object obj) => obj is UVFallbackBufferKey other && Equals(other);
public override int GetHashCode() => HashCode.Combine(width, height, meshInstanceID);
public static bool operator ==(UVFallbackBufferKey left, UVFallbackBufferKey right) => left.Equals(right);
public static bool operator !=(UVFallbackBufferKey left, UVFallbackBufferKey right) => !left.Equals(right);
}
public int UVMeshCount()
{
return _meshToUVMesh.Count;
}
public int UVAccelerationStructureCount()
{
return _meshToUVAccelerationStructure.Count;
}
public int UVFallbackBufferCount()
{
return _meshToUVFallbackBuffer.Count;
}
internal bool CacheIsHot(BakeInstance[] instances)
{
foreach (BakeInstance instance in instances)
{
// UVMesh
ulong uvMeshHash = Util.EntityIDToUlong(instance.Mesh.GetEntityId());
if (!_meshToUVMesh.TryGetValue(uvMeshHash, out UVMesh uvMesh))
return false;
// UVAccelerationStructure
ulong uvASHash = uvMeshHash;
if (!_meshToUVAccelerationStructure.TryGetValue(uvASHash, out UVAccelerationStructure uvAS))
return false;
// UVFallbackBuffer
var uvFBKey = new UVFallbackBufferKey(instance.TexelSize.x, instance.TexelSize.y, uvMesh.Mesh.GetEntityId());
if (!_meshToUVFallbackBuffer.TryGetValue(uvFBKey, out UVFallbackBuffer uvFB))
return false;
}
return true;
}
internal bool AddResources(
BakeInstance[] instances,
RayTracingContext context,
CommandBuffer cmd,
UVFallbackBufferBuilder uvFallbackBufferBuilder)
{
foreach (BakeInstance instance in instances)
{
// UVMesh
ulong uvMeshHash = Util.EntityIDToUlong(instance.Mesh.GetEntityId());
if (!_meshToUVMesh.TryGetValue(uvMeshHash, out UVMesh uvMesh))
{
UVMesh newUVMesh = new();
if (!newUVMesh.Build(instance.Mesh))
{
newUVMesh?.Dispose();
return false;
}
_meshToUVMesh.Add(uvMeshHash, newUVMesh);
uvMesh = newUVMesh;
}
// UVAccelerationStructure
ulong uvASHash = Util.EntityIDToUlong(uvMesh.Mesh.GetEntityId());
if (!_meshToUVAccelerationStructure.TryGetValue(uvASHash, out UVAccelerationStructure uvAS))
{
cmd.BeginSample(k_BuildUVAccelerationStructure);
UVAccelerationStructure newUVAS = new();
newUVAS.Build(cmd, context, uvMesh, BuildFlags.None);
_meshToUVAccelerationStructure.Add(uvASHash, newUVAS);
uvAS = newUVAS;
cmd.EndSample(k_BuildUVAccelerationStructure);
}
// UVFallbackBuffer
var uvFBKey = new UVFallbackBufferKey(instance.TexelSize.x, instance.TexelSize.y, uvMesh.Mesh.GetEntityId());
if (!_meshToUVFallbackBuffer.TryGetValue(uvFBKey, out UVFallbackBuffer uvFB))
{
UVFallbackBuffer newUVFB = new();
if (!newUVFB.Build(
cmd,
uvFallbackBufferBuilder,
instance.TexelSize.x,
instance.TexelSize.y,
uvMesh))
{
newUVFB?.Dispose();
return false;
}
_meshToUVFallbackBuffer.Add(uvFBKey, newUVFB);
uvFB = newUVFB;
}
}
return true;
}
internal void FreeResources(BakeInstance[] instancesToKeep)
{
// Build dictionary over resources to keep
Dictionary<ulong, UVMesh> uvMeshesToKeep = new();
Dictionary<ulong, UVAccelerationStructure> uvASToKeep = new();
Dictionary<UVFallbackBufferKey, UVFallbackBuffer> uvFBToKeep = new();
foreach (var instance in instancesToKeep)
{
ulong uvMeshHash = Util.EntityIDToUlong(instance.Mesh.GetEntityId());
if (_meshToUVMesh.TryGetValue(uvMeshHash, out UVMesh uvMesh))
{
uvMeshesToKeep.Add(uvMeshHash, uvMesh);
_meshToUVMesh.Remove(uvMeshHash);
ulong uvASHash = Util.EntityIDToUlong(uvMesh.Mesh.GetEntityId());
if (_meshToUVAccelerationStructure.TryGetValue(uvASHash, out UVAccelerationStructure uvAS))
{
uvASToKeep.Add(uvASHash, uvAS);
_meshToUVAccelerationStructure.Remove(uvASHash);
var uvFBKey = new UVFallbackBufferKey(instance.TexelSize.x, instance.TexelSize.y, uvMesh.Mesh.GetEntityId());
if (_meshToUVFallbackBuffer.TryGetValue(uvFBKey, out UVFallbackBuffer uvFB))
{
uvFBToKeep.Add(uvFBKey, uvFB);
_meshToUVFallbackBuffer.Remove(uvFBKey);
}
}
}
}
// Dispose remaining resources
Clear();
// Restore resources to keep
_meshToUVMesh = uvMeshesToKeep;
_meshToUVAccelerationStructure = uvASToKeep;
_meshToUVFallbackBuffer = uvFBToKeep;
}
internal bool GetResources(
BakeInstance[] instances,
out UVMesh[] uvMeshes,
out UVAccelerationStructure[] uvAccelerationStructures,
out UVFallbackBuffer[] uvFallbackBuffers)
{
List<UVMesh> uvMeshList = new();
List<UVAccelerationStructure> uvAccelerationStructureList = new();
List<UVFallbackBuffer> uvFallbackBufferList = new();
uvMeshes = null;
uvAccelerationStructures = null;
uvFallbackBuffers = null;
foreach (var instance in instances)
{
ulong uvMeshHash = Util.EntityIDToUlong(instance.Mesh.GetEntityId());
if (!_meshToUVMesh.TryGetValue(uvMeshHash, out UVMesh uvMesh))
return false;
uvMeshList.Add(uvMesh);
ulong uvASHash = Util.EntityIDToUlong(uvMesh.Mesh.GetEntityId());
if (!_meshToUVAccelerationStructure.TryGetValue(uvASHash, out UVAccelerationStructure uvAS))
return false;
uvAccelerationStructureList.Add(uvAS);
var uvFBKey = new UVFallbackBufferKey(instance.TexelSize.x, instance.TexelSize.y, uvMesh.Mesh.GetEntityId());
if (!_meshToUVFallbackBuffer.TryGetValue(uvFBKey, out UVFallbackBuffer uvFB))
return false;
uvFallbackBufferList.Add(uvFB);
}
uvMeshes = uvMeshList.ToArray();
uvAccelerationStructures = uvAccelerationStructureList.ToArray();
uvFallbackBuffers = uvFallbackBufferList.ToArray();
return true;
}
private void Clear()
{
foreach (var uvMesh in _meshToUVMesh)
uvMesh.Value.Dispose();
foreach (var uvAccelerationStructure in _meshToUVAccelerationStructure)
uvAccelerationStructure.Value.Dispose();
foreach (var uvFallbackBuffer in _meshToUVFallbackBuffer)
uvFallbackBuffer.Value.Dispose();
_meshToUVMesh.Clear();
_meshToUVAccelerationStructure.Clear();
_meshToUVFallbackBuffer.Clear();
}
public void Dispose()
{
Clear();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 54b4c219a2fd01e439bdc9ef8bc2faf8
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 1b049d4faa1758345969290b189e9c0b
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,261 @@
using System;
using System.Collections.Generic;
using Unity.Jobs;
using Unity.Collections;
using Unity.Mathematics;
namespace UnityEngine.PathTracing.Lightmapping
{
internal static class ChartIdentification
{
private static UInt32 FindRepWithPathCompression(Span<UInt32> reps, UInt32 vertexIdx)
{
UInt32 rep = reps[(int)vertexIdx];
if (rep == vertexIdx)
return vertexIdx;
rep = FindRepWithPathCompression(reps, rep);
reps[(int)vertexIdx] = rep;
return rep;
}
private static UInt32 FindRepresentative(Span<UInt32> reps, UInt32 vertexIdx)
{
UInt32 rep = reps[(int)vertexIdx];
return (rep == vertexIdx ? vertexIdx : FindRepresentative(reps, rep));
}
private static void Union(Span<UInt32> reps, UInt32 vertexIdx0, UInt32 vertexIdx1)
{
var rep0 = FindRepWithPathCompression(reps, vertexIdx0);
var rep1 = FindRepWithPathCompression(reps, vertexIdx1);
reps[(int)rep1] = rep0;
}
public static void UnionTriangleEdges(ReadOnlySpan<UInt32> triangleIndices, Span<UInt32> vertexChartIds)
{
Span<UInt32> reps = vertexChartIds;
Debug.Assert(triangleIndices.Length % 3 == 0);
int triangleCount = triangleIndices.Length / 3;
for (int triIdx = 0; triIdx < triangleCount; ++triIdx)
{
int offset = triIdx * 3;
UInt32 vertexIdx0 = triangleIndices[offset];
UInt32 vertexIdx1 = triangleIndices[offset + 1];
UInt32 vertexIdx2 = triangleIndices[offset + 2];
Union(reps, vertexIdx0, vertexIdx1);
Union(reps, vertexIdx1, vertexIdx2);
}
}
public static void UnionDuplicateVertices(ReadOnlySpan<float2> vertexUvs, ReadOnlySpan<float3> vertexPositions, ReadOnlySpan<float3> vertexNormals, Span<UInt32> vertexChartIds, bool respectNormals)
{
var map = new Dictionary<(float2, float3, float3), uint>();
for (uint i = 0; i < vertexChartIds.Length; ++i)
{
var tuple = (
vertexUvs[(int)i],
vertexPositions[(int)i],
respectNormals ? vertexNormals[(int)i] : float3.zero);
if (map.TryGetValue(tuple, out uint deduplicatedIndex))
{
Union(vertexChartIds, i, deduplicatedIndex);
}
else
{
map.Add(tuple, i);
}
}
}
public static void FindRepresentatives(Span<UInt32> vertexChartIds)
{
for (uint i = 0; i < vertexChartIds.Length; ++i)
{
vertexChartIds[(int)i] = FindRepresentative(vertexChartIds, i);
}
}
public static void InitializeRepresentatives(Span<UInt32> vertexChartIds)
{
for (UInt32 i = 0; i < vertexChartIds.Length; ++i)
vertexChartIds[(int)i] = i;
}
public static void Compact(Span<UInt32> vertexChartIds, out uint chartCount)
{
var map = new Dictionary<UInt32, UInt32>();
for (int vertexIdx = 0; vertexIdx < vertexChartIds.Length; ++vertexIdx)
{
var chartId = vertexChartIds[vertexIdx];
UInt32 newChartId;
if (map.TryGetValue(chartId, out UInt32 compactedId))
{
newChartId = compactedId;
}
else
{
newChartId = (UInt32)map.Count;
map.Add(chartId, newChartId);
}
vertexChartIds[vertexIdx] = newChartId;
}
chartCount = (uint)map.Count;
}
}
internal class ParallelChartIdentification : IDisposable
{
private readonly MeshChartIdentificationJob[] _jobs;
private readonly JobHandle[] _jobHandles;
private readonly NativeArray<UInt32>[] _outputVertexChartIndices;
private readonly NativeArray<UInt32>[] _outputVertexChartIndicesIgnoringNormals;
private readonly NativeArray<UInt32>[] _outputChartCounts;
private readonly Dictionary<Mesh, uint> _meshToJobIdx;
public struct MeshResult
{
// Vertex -> Chart index mapping taking normals into account.
// Triangles are considered belonging to different charts if
// only connected by overlapping vertices which have different normals.
// Used for the 'baked UV charts' output, which is used to
// prevent filtering over hard edges during postprocessing.
public NativeArray<UInt32> VertexChartIndices;
public uint ChartCount;
// Vertex -> Chart index mapping NOT taking normals into account.
// Triangles are considered belonging to the SAME chart if
// only connected by overlapping vertices which have different normals.
// Used for the 'baked UV overlap', since bilinear bleeding across hard edges
// within a single UV island is considered acceptable.
public NativeArray<UInt32> VertexChartIndicesIgnoringNormals;
public uint ChartCountIgnoringNormals;
};
private struct MeshChartIdentificationJob : IJob
{
[ReadOnly, DeallocateOnJobCompletion]
public NativeArray<UInt32> InputVertexIndexBuffer;
[ReadOnly, DeallocateOnJobCompletion]
public NativeArray<float2> InputVertexUvBuffer;
[ReadOnly, DeallocateOnJobCompletion]
public NativeArray<float3> InputVertexPositionBuffer;
[ReadOnly, DeallocateOnJobCompletion]
public NativeArray<float3> InputVertexNormalBuffer;
public NativeArray<UInt32> OutputVertexChartIndicesBuffer;
public NativeArray<UInt32> OutputVertexChartIndicesIgnoringNormalsBuffer;
// Always 2 elements. Job system doesn't support scalar outputs.
public NativeArray<UInt32> OutputChartCount;
public void Execute()
{
ChartIdentification.InitializeRepresentatives(OutputVertexChartIndicesBuffer);
ChartIdentification.UnionTriangleEdges(InputVertexIndexBuffer, OutputVertexChartIndicesBuffer);
// Union duplicate verts taking normal into account
ChartIdentification.UnionDuplicateVertices(InputVertexUvBuffer, InputVertexPositionBuffer, InputVertexNormalBuffer, OutputVertexChartIndicesBuffer, respectNormals: true);
ChartIdentification.FindRepresentatives(OutputVertexChartIndicesBuffer);
// Union duplicate verts NOT taking normal into account
OutputVertexChartIndicesBuffer.CopyTo(OutputVertexChartIndicesIgnoringNormalsBuffer);
ChartIdentification.UnionDuplicateVertices(InputVertexUvBuffer, InputVertexPositionBuffer, InputVertexNormalBuffer, OutputVertexChartIndicesIgnoringNormalsBuffer, respectNormals: false);
ChartIdentification.FindRepresentatives(OutputVertexChartIndicesIgnoringNormalsBuffer);
// Compact and output both mappings
ChartIdentification.Compact(OutputVertexChartIndicesBuffer, out uint outputChartCount);
ChartIdentification.Compact(OutputVertexChartIndicesIgnoringNormalsBuffer, out uint outputChartIgnoringNormalsCount);
OutputChartCount[0] = outputChartCount;
OutputChartCount[1] = outputChartIgnoringNormalsCount;
}
}
public ParallelChartIdentification(IList<Mesh> meshes)
{
_outputVertexChartIndices = new NativeArray<UInt32>[meshes.Count];
_outputVertexChartIndicesIgnoringNormals = new NativeArray<UInt32>[meshes.Count];
_outputChartCounts = new NativeArray<UInt32>[meshes.Count];
_jobs = new MeshChartIdentificationJob[meshes.Count];
_jobHandles = new JobHandle[meshes.Count];
_meshToJobIdx = new Dictionary<Mesh, uint>();
for (uint meshIdx = 0; meshIdx < meshes.Count; ++meshIdx)
{
var mesh = meshes[(int)meshIdx];
// Select uv buffer, prefer uv2
var uvBuffer = mesh.uv2;
if (uvBuffer == null || uvBuffer.Length == 0)
uvBuffer = mesh.uv;
var inputVertexIndices = new NativeArray<Int32>(mesh.triangles, Allocator.TempJob).Reinterpret<UInt32>(sizeof(Int32));
var inputVertexUvs = new NativeArray<Vector2>(uvBuffer, Allocator.TempJob).Reinterpret<float2>(sizeof(float) * 2);
var inputVertexPositions = new NativeArray<Vector3>(mesh.vertices, Allocator.TempJob).Reinterpret<float3>(sizeof(float) * 3);
var inputVertexNormals = new NativeArray<Vector3>(mesh.normals, Allocator.TempJob).Reinterpret<float3>(sizeof(float) * 3);
var outputChartIndices = new NativeArray<UInt32>(mesh.vertexCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
var outputChartIndicesIgnoringNormals = new NativeArray<UInt32>(mesh.vertexCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory);
var outputChartCount = new NativeArray<UInt32>(2, Allocator.TempJob);
var job = new MeshChartIdentificationJob
{
InputVertexIndexBuffer = inputVertexIndices,
InputVertexUvBuffer = inputVertexUvs,
InputVertexPositionBuffer = inputVertexPositions,
InputVertexNormalBuffer = inputVertexNormals,
OutputVertexChartIndicesBuffer = outputChartIndices,
OutputVertexChartIndicesIgnoringNormalsBuffer = outputChartIndicesIgnoringNormals,
OutputChartCount = outputChartCount,
};
_outputVertexChartIndices[meshIdx] = outputChartIndices;
_outputVertexChartIndicesIgnoringNormals[meshIdx] = outputChartIndicesIgnoringNormals;
_outputChartCounts[meshIdx] = outputChartCount;
_jobs[meshIdx] = job;
_meshToJobIdx[mesh] = meshIdx;
}
}
public void Start()
{
for (uint meshIdx = 0; meshIdx < _jobs.Length; ++meshIdx)
{
_jobHandles[meshIdx] = _jobs[meshIdx].ScheduleByRef();
}
}
public MeshResult CompleteAndGetResult(Mesh mesh)
{
uint meshIdx = _meshToJobIdx[mesh];
_jobHandles[meshIdx].Complete();
var meshResult = new MeshResult
{
VertexChartIndices = _outputVertexChartIndices[meshIdx],
ChartCount = _outputChartCounts[meshIdx][0],
VertexChartIndicesIgnoringNormals = _outputVertexChartIndicesIgnoringNormals[meshIdx],
ChartCountIgnoringNormals = _outputChartCounts[meshIdx][1],
};
return meshResult;
}
public void Dispose()
{
for (uint meshIdx = 0; meshIdx < _jobs.Length; ++meshIdx)
_jobHandles[meshIdx].Complete();
foreach (var chartIndexList in _outputVertexChartIndices)
chartIndexList.Dispose();
foreach (var chartIndexList in _outputVertexChartIndicesIgnoringNormals)
chartIndexList.Dispose();
foreach (var chartCountList in _outputChartCounts)
chartCountList.Dispose();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7a907a631dd46324681dd9b152a939c5
@@ -0,0 +1,110 @@
using System;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Rendering;
namespace UnityEngine.PathTracing.Lightmapping
{
internal class ChartRasterizer : IDisposable
{
// Buffers required to execute chart rasterization
public struct Buffers
{
public GraphicsBuffer vertex; // Only used in software path
public GraphicsBuffer vertexToOriginalVertex; // Only used in software path
public GraphicsBuffer vertexToChartID;
}
private readonly Material _softwareRasterizationMaterial;
private readonly Material _hardwareRasterizationMaterial;
private static class ShaderProperties
{
public static readonly int VertexBuffer = Shader.PropertyToID("g_VertexBuffer");
public static readonly int VertexToOriginalVertex = Shader.PropertyToID("g_VertexToOriginalVertex");
public static readonly int VertexToChartID = Shader.PropertyToID("g_VertexToChartID");
public static readonly int ScaleAndOffset = Shader.PropertyToID("g_ScaleAndOffset");
public static readonly int ChartIndexOffset = Shader.PropertyToID("g_ChartIndexOffset");
public static readonly int Width = Shader.PropertyToID("g_Width");
public static readonly int Height = Shader.PropertyToID("g_Height");
}
public ChartRasterizer(Shader softwareRasterizationShader, Shader hardwareRasterizationShader)
{
_softwareRasterizationMaterial = new Material(softwareRasterizationShader);
_hardwareRasterizationMaterial = new Material(hardwareRasterizationShader);
}
public void Dispose()
{
CoreUtils.Destroy(_softwareRasterizationMaterial);
CoreUtils.Destroy(_hardwareRasterizationMaterial);
}
#if UNITY_EDITOR
public static void LoadShaders(out Shader softwareRasterizationShader, out Shader hardwareRasterizationShader)
{
softwareRasterizationShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(
"Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/Lightmapping/ChartRasterizerSoftware.shader");
hardwareRasterizationShader = UnityEditor.AssetDatabase.LoadAssetAtPath<Shader>(
"Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/Lightmapping/ChartRasterizerHardware.shader");
}
#endif
private static Vector2[] SelectUVBuffer(Mesh from)
{
var uv2 = from.uv2;
if (uv2 != null && uv2.Length > 0)
return uv2;
else
return from.uv;
}
public static void PrepareRasterizeSoftware(CommandBuffer cmd, Mesh from, GraphicsBuffer vertexBuffer, GraphicsBuffer vertexToOriginalVertexBuffer)
{
var originalUVs = from.vertices;
var originalIndices = from.triangles;
var uvs = new Vector2[originalIndices.Length];
var vertexIds = new uint[originalIndices.Length];
for (int i = 0; i < originalIndices.Length; i++)
{
uint originalVertexIdx = (uint)originalIndices[i];
uvs[i] = originalUVs[originalVertexIdx];
vertexIds[i] = originalVertexIdx;
}
cmd.SetBufferData(vertexBuffer, uvs);
cmd.SetBufferData(vertexToOriginalVertexBuffer, vertexIds);
}
public void RasterizeSoftware(CommandBuffer cmd, GraphicsBuffer vertexBuffer, GraphicsBuffer vertexToOriginalVertexBuffer, GraphicsBuffer vertexToChartIdBuffer, uint indexCount, Vector4 scaleAndOffset, uint chartIndexOffset, RenderTexture destination)
{
cmd.SetGlobalBuffer(ShaderProperties.VertexBuffer, vertexBuffer);
cmd.SetGlobalBuffer(ShaderProperties.VertexToOriginalVertex, vertexToOriginalVertexBuffer);
cmd.SetGlobalBuffer(ShaderProperties.VertexToChartID, vertexToChartIdBuffer);
cmd.SetGlobalVector(ShaderProperties.ScaleAndOffset, scaleAndOffset);
cmd.SetGlobalInt(ShaderProperties.ChartIndexOffset, (int)chartIndexOffset);
cmd.SetGlobalInteger(ShaderProperties.Width, destination.width);
cmd.SetGlobalInteger(ShaderProperties.Height, destination.height);
cmd.SetRenderTarget(destination);
cmd.DrawProcedural(Matrix4x4.identity, _softwareRasterizationMaterial, 0, MeshTopology.Triangles, (int)indexCount);
}
public void RasterizeHardware(CommandBuffer cmd, Mesh mesh, GraphicsBuffer vertexToChartIdBuffer, Vector4 scaleAndOffset, uint chartIndexOffset, RenderTexture destination)
{
Debug.Assert(SystemInfo.supportsConservativeRaster, "Conservative rasterization is not supported on the current platform.");
cmd.SetGlobalBuffer(ShaderProperties.VertexToChartID, vertexToChartIdBuffer);
cmd.SetGlobalVector(ShaderProperties.ScaleAndOffset, scaleAndOffset);
cmd.SetGlobalInt(ShaderProperties.ChartIndexOffset, (int)chartIndexOffset);
cmd.SetRenderTarget(destination);
for (int i = 0; i < mesh.subMeshCount; i++)
{
cmd.DrawMesh(mesh, Matrix4x4.identity, _hardwareRasterizationMaterial, i, 0);
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 54a5cb4c515d9304ba7e7c9cab9ed90e
@@ -0,0 +1,194 @@
using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using Unity.Mathematics;
using UnityEngine;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
namespace UnityEngine.PathTracing.Lightmapping
{
// Detects pixels where multiple UV charts have overlapping bilinear neighborhoods.
internal class UVOverlapDetection : IDisposable
{
private static class ShaderProperties
{
public static readonly int TextureSize = Shader.PropertyToID("_TextureSize");
public static readonly int PerPixelChart = Shader.PropertyToID("_PerPixelChart");
public static readonly int InstanceIndex = Shader.PropertyToID("_InstanceIndex");
public static readonly int EdgeCount = Shader.PropertyToID("_EdgeCount");
public static readonly int TriangleEdges = Shader.PropertyToID("_TriangleEdges");
public static readonly int ChartIndices = Shader.PropertyToID("_ChartIndices");
public static readonly int OverlapPixels = Shader.PropertyToID("_OverlapPixels");
public static readonly int OverlapInstances = Shader.PropertyToID("_OverlapInstances");
public static readonly int TileX = Shader.PropertyToID("_TileX");
public static readonly int TileY = Shader.PropertyToID("_TileY");
public static readonly int TileSize = Shader.PropertyToID("_TileSize");
}
private int _lightmapResolution;
private ComputeShader _shader;
private NativeArray<float4> _triangleEdges;
private NativeArray<uint> _chartIndices;
private GraphicsBuffer _triangleEdgesBuffer;
private GraphicsBuffer _chartIndicesBuffer;
private GraphicsBuffer _perPixelChart;
private GraphicsBuffer _overlapPixelsBuffer;
private GraphicsBuffer _overlapInstancesBuffer;
private int _overlapKernel;
private uint _overlapKernelSize;
public void Initialize(ComputeShader shader, uint lightmapResolution, uint maxEdgeCount, uint instanceCount)
{
_lightmapResolution = (int)lightmapResolution;
_shader = shader;
_triangleEdges = new NativeArray<float4>((int)maxEdgeCount,Allocator.Persistent);
_chartIndices = new NativeArray<uint>((int)maxEdgeCount, Allocator.Persistent);
_triangleEdgesBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, _triangleEdges.Length, UnsafeUtility.SizeOf<float4>());
_chartIndicesBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, _chartIndices.Length, sizeof(uint));
_perPixelChart = new GraphicsBuffer(GraphicsBuffer.Target.Structured, _lightmapResolution*_lightmapResolution, sizeof(uint));
_overlapPixelsBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, _lightmapResolution*_lightmapResolution, sizeof(uint));
_overlapInstancesBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, (int)instanceCount, sizeof(uint));
_overlapKernel = shader.FindKernel("MarkBilinearOverlaps");
shader.GetKernelThreadGroupSizes(_overlapKernel, out _overlapKernelSize, out _, out _);
// Initialize buffers
_overlapPixelsBuffer.SetData(new uint[_lightmapResolution*_lightmapResolution]);
_overlapInstancesBuffer.SetData(new uint[instanceCount]);
var initPerPixelChart = new uint[_lightmapResolution * _lightmapResolution];
Array.Fill(initPerPixelChart, uint.MaxValue);
_perPixelChart.SetData(initPerPixelChart);
}
public void MarkOverlapsInInstance(
CommandBuffer cmd,
Mesh uvMesh,
NativeArray<UInt32> vertexToChartIndex,
float4 occupiedST,
uint instanceIndex,
uint chartIndexOffset)
{
// Get the start and end pos of every edge, and the chart index for each edge.
var indices = uvMesh.triangles;
var vertices = uvMesh.vertices;
for (uint triangleIdx = 0; triangleIdx < indices.Length / 3; triangleIdx++)
{
for (uint edgeOffset = 0; edgeOffset < 3; edgeOffset++)
{
uint baseTriangleIdx = triangleIdx * 3;
int startVertexIdx = indices[baseTriangleIdx + edgeOffset];
int endVertexIdx = indices[baseTriangleIdx + ((edgeOffset + 1) % 3)];
float3 start = vertices[startVertexIdx];
float3 end = vertices[endVertexIdx];
start.xy = (start.xy * occupiedST.xy + occupiedST.zw) * _lightmapResolution;
end.xy = (end.xy * occupiedST.xy + occupiedST.zw) * _lightmapResolution;
_triangleEdges[(int)(baseTriangleIdx + edgeOffset)] = new float4(start.x, start.y, end.x, end.y);
uint chartIdx = chartIndexOffset + vertexToChartIndex[startVertexIdx];
_chartIndices[(int)(baseTriangleIdx + edgeOffset)] = chartIdx;
}
}
cmd.SetBufferData(_triangleEdgesBuffer, _triangleEdges);
cmd.SetBufferData(_chartIndicesBuffer, _chartIndices);
// If the lightmap resolution is over this constant, we split the dispatch into multiple
// smaller dispatches over tiles, to prevent dispatches that are too large. Otherwise in
// the worst case, every lightmap texel can be checked in one dispatch.
const uint tileSize = 1024;
// Mark overlaps
int edgeCount = indices.Length;
cmd.SetComputeIntParam(_shader, ShaderProperties.InstanceIndex, (int)instanceIndex);
cmd.SetComputeIntParam(_shader, ShaderProperties.EdgeCount, edgeCount);
cmd.SetComputeIntParam(_shader, ShaderProperties.TextureSize, _lightmapResolution);
cmd.SetComputeIntParam(_shader, ShaderProperties.TileSize, (int)tileSize);
cmd.SetComputeBufferParam(_shader, _overlapKernel, ShaderProperties.TriangleEdges, _triangleEdgesBuffer);
cmd.SetComputeBufferParam(_shader, _overlapKernel, ShaderProperties.ChartIndices, _chartIndicesBuffer);
cmd.SetComputeBufferParam(_shader, _overlapKernel, ShaderProperties.PerPixelChart, _perPixelChart);
cmd.SetComputeBufferParam(_shader, _overlapKernel, ShaderProperties.OverlapPixels, _overlapPixelsBuffer);
cmd.SetComputeBufferParam(_shader, _overlapKernel, ShaderProperties.OverlapInstances, _overlapInstancesBuffer);
int dispatchSize = GraphicsHelpers.DivUp(edgeCount, _overlapKernelSize);
uint tileCountOnEachDim = GraphicsHelpers.DivUp((uint)_lightmapResolution, tileSize);
for (uint tileY = 0; tileY < tileCountOnEachDim; tileY++)
{
for (uint tileX = 0; tileX < tileCountOnEachDim; tileX++)
{
cmd.SetComputeIntParam(_shader, ShaderProperties.TileX, (int)tileX);
cmd.SetComputeIntParam(_shader, ShaderProperties.TileY, (int)tileY);
cmd.DispatchCompute(_shader, _overlapKernel, dispatchSize, 1, 1);
}
}
}
public void CompactAndReadbackOverlaps(
CommandBuffer cmd,
out uint[] uniqueOverlapPixelIndices,
out ulong[] uniqueOverlapInstanceIndices)
{
// Make sure all kernels are finished
GraphicsHelpers.Flush(cmd);
// Readback overlap buffers
uint[] overlapPixels = new uint[_overlapPixelsBuffer.count];
_overlapPixelsBuffer.GetData(overlapPixels);
uint[] overlapInstances = new uint[_overlapInstancesBuffer.count];
_overlapInstancesBuffer.GetData(overlapInstances);
// Deduplicate overlaps
List<uint> uniqueOverlapPixelIndicesSet = new List<uint>();
List<ulong> uniqueOverlapInstanceIndicesSet = new List<ulong>();
for (uint pixelIndex = 0; pixelIndex < _overlapPixelsBuffer.count; pixelIndex++)
{
if (overlapPixels[pixelIndex] != 0)
uniqueOverlapPixelIndicesSet.Add(pixelIndex);
}
for (uint instanceIndex = 0; instanceIndex < _overlapInstancesBuffer.count; instanceIndex++)
{
if (overlapInstances[instanceIndex] != 0)
uniqueOverlapInstanceIndicesSet.Add(instanceIndex);
}
uniqueOverlapPixelIndices = new uint[uniqueOverlapPixelIndicesSet.Count];
uniqueOverlapPixelIndicesSet.CopyTo(uniqueOverlapPixelIndices);
uniqueOverlapInstanceIndices = new ulong[uniqueOverlapInstanceIndicesSet.Count];
uniqueOverlapInstanceIndicesSet.CopyTo(uniqueOverlapInstanceIndices);
// Sort to keep the order deterministic
Array.Sort(uniqueOverlapPixelIndices);
Array.Sort(uniqueOverlapInstanceIndices);
}
public void Dispose()
{
if (_triangleEdges.IsCreated)
_triangleEdges.Dispose();
if (_chartIndices.IsCreated)
_chartIndices.Dispose();
if (_triangleEdgesBuffer != null && _triangleEdgesBuffer.IsValid())
_triangleEdgesBuffer.Dispose();
if (_chartIndicesBuffer != null && _chartIndicesBuffer.IsValid())
_chartIndicesBuffer.Dispose();
if (_perPixelChart != null && _perPixelChart.IsValid())
_perPixelChart.Dispose();
if (_overlapPixelsBuffer != null && _overlapPixelsBuffer.IsValid())
_overlapPixelsBuffer.Dispose();
if (_overlapInstancesBuffer != null && _overlapInstancesBuffer.IsValid())
_overlapInstancesBuffer.Dispose();
}
#if UNITY_EDITOR
public static ComputeShader LoadShader()
{
return UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>(
"Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/Lightmapping/BilinearOverlaps.compute");
}
#endif
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e4ea9631f1f5a904d97ac50debf8006b
@@ -0,0 +1,247 @@
using System;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.PathTracing.Core;
using UnityEngine.PathTracing.Integration;
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
namespace UnityEngine.PathTracing.Lightmapping
{
internal class LightmappingContext: IDisposable
{
UnityComputeDeviceContext _deviceContext;
public UnityComputeWorld World;
public GraphicsBuffer TraceScratchBuffer;
public LightmapIntegratorContext IntegratorContext;
public LightmapIntegrationResourceCache ResourceCache;
public RenderTexture AccumulatedOutput;
public RenderTexture AccumulatedDirectionalOutput;
public GraphicsBuffer ExpandedOutput;
public GraphicsBuffer ExpandedOutputDirectional;
public GraphicsBuffer GBuffer;
public GraphicsBuffer CompactedTexelIndices;
public GraphicsBuffer CompactedGBufferLength;
public GraphicsBuffer IndirectDispatchBuffer;
public GraphicsBuffer IndirectDispatchRayTracingBuffer;
public ChartRasterizer ChartRasterizer;
// Temporary buffers required for chart rasterization
public ChartRasterizer.Buffers ChartRasterizerBuffers;
private int _width;
private int _height;
public int Width => _width;
public int Height => _height;
public void ClearOutputs()
{
CommandBuffer cmd = GetCommandBuffer();
if (AccumulatedOutput is not null)
{
cmd.SetRenderTarget(AccumulatedOutput);
cmd.ClearRenderTarget(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f));
}
if (AccumulatedDirectionalOutput is not null)
{
cmd.SetRenderTarget(AccumulatedDirectionalOutput);
cmd.ClearRenderTarget(false, true, new Color(0.0f, 0.0f, 0.0f, 0.0f));
}
}
static public RenderTexture MakeRenderTexture(int width, int height, string name)
{
RenderTextureDescriptor rtDesc = new RenderTextureDescriptor(width, height, RenderTextureFormat.ARGBFloat, 0)
{
sRGB = false,
useMipMap = false,
autoGenerateMips = false,
enableRandomWrite = true,
dimension = TextureDimension.Tex2D,
volumeDepth = 1,
msaaSamples = 1,
vrUsage = VRTextureUsage.None,
memoryless = RenderTextureMemoryless.None,
useDynamicScale = false,
depthBufferBits = 0
};
RenderTexture renderTexture = new RenderTexture(rtDesc)
{
name = name,
enableRandomWrite = true,
hideFlags = HideFlags.HideAndDontSave
};
return renderTexture;
}
internal bool ExpandedBufferNeedsUpdating(UInt64 expandedSize)
{
if (ExpandedOutput is not null &&
ExpandedOutputDirectional is not null &&
CompactedTexelIndices is not null &&
GBuffer is not null &&
expandedSize == (UInt64)ExpandedOutput.count &&
expandedSize == (UInt64)ExpandedOutputDirectional.count &&
expandedSize == (UInt64)CompactedTexelIndices.count &&
expandedSize == (UInt64)CompactedTexelIndices.count)
{
return false;
}
return true;
}
internal bool InitializeExpandedBuffer(UInt64 expandedSize)
{
if (!ExpandedBufferNeedsUpdating(expandedSize))
return true;
ExpandedOutput?.Dispose();
ExpandedOutput = new GraphicsBuffer(GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource, (int)(expandedSize), sizeof(float) * 4);
if (ExpandedOutput is null)
{
Dispose();
return false;
}
ExpandedOutputDirectional?.Dispose();
ExpandedOutputDirectional = new GraphicsBuffer(GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource, (int)(expandedSize), sizeof(float) * 4);
if (ExpandedOutputDirectional is null)
{
Dispose();
return false;
}
CompactedTexelIndices?.Dispose();
CompactedTexelIndices = new GraphicsBuffer(GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource, (int)(expandedSize), sizeof(uint));
if (CompactedTexelIndices is null)
{
Dispose();
return false;
}
GBuffer?.Dispose();
GBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource, (int)(expandedSize), 16); // the GBuffer is used to store the UV samples as HitEntry (StochasticLightmapSampling.hlsl) hence the stride
if (GBuffer is null)
{
Dispose();
return false;
}
return true;
}
internal bool Initialize(UnityComputeDeviceContext deviceContext, int width, int height, UnityComputeWorld world, uint maxIndexCount, uint maxVertexCount, LightmapResourceLibrary resources)
{
_deviceContext = deviceContext;
World = world;
IntegratorContext = new LightmapIntegratorContext();
ResourceCache = new LightmapIntegrationResourceCache();
ChartRasterizer = new ChartRasterizer(resources.SoftwareChartRasterizationShader, resources.HardwareChartRasterizationShader);
InitializeChartRasterizationBuffers(maxIndexCount, maxVertexCount);
return SetOutputResolution(width, height);
}
internal bool SetOutputResolution(int width, int height) // In case of failure, the context is disposed and is thus not usable anymore
{
_width = width;
_height = height;
ReleaseAndDestroy(ref AccumulatedOutput);
AccumulatedOutput = MakeRenderTexture(width, height, "AccumulatedOutput");
if (AccumulatedOutput == null || !AccumulatedOutput.Create())
{
Dispose();
return false;
}
ReleaseAndDestroy(ref AccumulatedDirectionalOutput);
AccumulatedDirectionalOutput = MakeRenderTexture(width, height, "AccumulatedDirectionalOutput");
if (AccumulatedDirectionalOutput == null || !AccumulatedDirectionalOutput.Create())
{
Dispose();
return false;
}
CompactedGBufferLength?.Dispose();
IndirectDispatchBuffer?.Dispose();
IndirectDispatchRayTracingBuffer?.Dispose();
CompactedGBufferLength = new GraphicsBuffer(GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource, 1, sizeof(uint));
IndirectDispatchBuffer = new GraphicsBuffer(GraphicsBuffer.Target.IndirectArguments | GraphicsBuffer.Target.Structured | GraphicsBuffer.Target.CopySource | GraphicsBuffer.Target.CopyDestination, 3, sizeof(uint));
IndirectDispatchRayTracingBuffer = RayTracingHelper.CreateDispatchIndirectBuffer();
return true;
}
public void InitializeTraceScratchBuffer(uint width, uint height, uint expandedSampleWidth)
{
TraceScratchBuffer?.Dispose();
TraceScratchBuffer = null;
Debug.Assert(World is not null);
ulong scratchSize = World.RayTracingContext.GetRequiredTraceScratchBufferSizeInBytes(width, height, expandedSampleWidth);
uint scratchStride = RayTracingContext.GetScratchBufferStrideInBytes();
if (scratchSize > 0)
{
TraceScratchBuffer = new GraphicsBuffer(RayTracingHelper.ScratchBufferTarget, (int)(scratchSize / scratchStride), 4);
Debug.Assert(TraceScratchBuffer == null || TraceScratchBuffer.target == RayTracingHelper.ScratchBufferTarget);
}
}
private void InitializeChartRasterizationBuffers(uint maxIndexCount, uint maxVertexCount)
{
ChartRasterizerBuffers.vertex?.Dispose();
ChartRasterizerBuffers.vertex = null;
ChartRasterizerBuffers.vertexToOriginalVertex?.Dispose();
ChartRasterizerBuffers.vertexToOriginalVertex = null;
ChartRasterizerBuffers.vertexToChartID?.Dispose();
ChartRasterizerBuffers.vertexToChartID = null;
// We base the size of the temporary buffers on the vertex count or index count of the mesh with the most vertices / indices, to avoid constant reallocations.
uint maxCount = Math.Max(maxIndexCount, maxVertexCount);
ChartRasterizerBuffers.vertex = new GraphicsBuffer(GraphicsBuffer.Target.Structured, (int)maxCount, UnsafeUtility.SizeOf<Vector2>());
ChartRasterizerBuffers.vertexToOriginalVertex = new GraphicsBuffer(GraphicsBuffer.Target.Structured, (int)maxCount, sizeof(uint));
ChartRasterizerBuffers.vertexToChartID = new GraphicsBuffer(GraphicsBuffer.Target.Structured, (int)maxCount, sizeof(uint));
}
public CommandBuffer GetCommandBuffer()
{
Debug.Assert(_deviceContext != null);
return _deviceContext.GetCommandBuffer();
}
public void Dispose()
{
TraceScratchBuffer?.Dispose();
ResourceCache?.Dispose();
IntegratorContext?.Dispose();
ReleaseAndDestroy(ref AccumulatedOutput);
ReleaseAndDestroy(ref AccumulatedDirectionalOutput);
ExpandedOutput?.Dispose();
ExpandedOutputDirectional?.Dispose();
CompactedTexelIndices?.Dispose();
GBuffer?.Dispose();
CompactedGBufferLength?.Dispose();
IndirectDispatchBuffer?.Dispose();
IndirectDispatchRayTracingBuffer?.Dispose();
ChartRasterizerBuffers.vertex?.Dispose();
ChartRasterizerBuffers.vertexToOriginalVertex?.Dispose();
ChartRasterizerBuffers.vertexToChartID?.Dispose();
ChartRasterizer?.Dispose();
ChartRasterizer = null;
}
private static void ReleaseAndDestroy(ref RenderTexture tex)
{
if (tex == null)
return;
tex.Release();
CoreUtils.Destroy(tex);
tex = null;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: db5319227b76429d9c98f680dfe63490
timeCreated: 1720172589
@@ -0,0 +1,383 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Unity.Mathematics;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Sampling;
using UnityEngine.Rendering.UnifiedRayTracing;
using static UnityEngine.PathTracing.Core.World;
namespace UnityEngine.PathTracing.Core
{
// Interface for many light sampling
internal interface IManyLightSampling : IDisposable
{
void Build(CommandBuffer cmd, World.LightState lightState, Bounds sceneBounds, SamplingResources samplingResources);
void Bind(CommandBuffer cmd, IRayTracingShader shader);
}
internal enum GridMemLayout { Sparse, Dense };
internal enum GridSizingStrategy { Uniform, FitToSceneBounds };
internal static class LightGridUtils
{
public static Vector3Int ComputeLightGridDims(Vector3 sceneBounds, int maxLightGridCellCount, GridSizingStrategy lightGridSizingStrategy)
{
if (lightGridSizingStrategy == GridSizingStrategy.Uniform)
{
int volumeSide = (int)Math.Pow((double)maxLightGridCellCount, 1.0 / 3.0);
if ((volumeSide + 1) * (volumeSide + 1) * (volumeSide + 1) <= maxLightGridCellCount)
volumeSide++;
return new Vector3Int(volumeSide, volumeSide, volumeSide);
}
// Fix scene bounds if the ratio between 2 dims is too important
float maxSceneDim = math.max(sceneBounds.x, math.max(sceneBounds.y, sceneBounds.z));
if (sceneBounds.x * Mathf.Sqrt(maxLightGridCellCount) < maxSceneDim)
sceneBounds.x = maxSceneDim / Mathf.Sqrt(maxLightGridCellCount);
if (sceneBounds.y * Mathf.Sqrt(maxLightGridCellCount) < maxSceneDim)
sceneBounds.y = maxSceneDim / Mathf.Sqrt(maxLightGridCellCount);
if (sceneBounds.z * Mathf.Sqrt(maxLightGridCellCount) < maxSceneDim)
sceneBounds.z = maxSceneDim / Mathf.Sqrt(maxLightGridCellCount);
// Compute ideal cell width (we aim for for cells having the same width along all 3 axes)
float idealCellWidth = Mathf.Pow(sceneBounds.x * sceneBounds.y * sceneBounds.z / ((float)maxLightGridCellCount), 1.0f / 3.0f);
// Use ideal cell width to compute grid dims
Vector3Int gridDims = new Vector3Int(
Math.Max((int)(sceneBounds.x / idealCellWidth), 1),
Math.Max((int)(sceneBounds.y / idealCellWidth), 1),
Math.Max((int)(sceneBounds.z / idealCellWidth), 1));
Debug.Assert(gridDims.x * gridDims.y * gridDims.z <= maxLightGridCellCount);
return gridDims;
}
public static int ComputeMaxLightsInAnyCell(int2[] grid, Vector3Int gridDims)
{
int maxLightsInAnyCell = 0;
for (int i = 0; i < gridDims.x * gridDims.y * gridDims.z; i++)
{
int lightCount = grid[i].y;
maxLightsInAnyCell = Math.Max(maxLightsInAnyCell, lightCount);
}
return maxLightsInAnyCell;
}
}
internal class ConservativeLightGrid : IManyLightSampling
{
// Light grid parameters
public int LightGridCellCount = 64 * 64 * 64;
public int MaxLightsPerCell = 64; // Only used with GridMemLayout.Dense
public GridSizingStrategy LightGridSizingStrategy = GridSizingStrategy.FitToSceneBounds;
public GridMemLayout GridMemLayout = GridMemLayout.Sparse;
public int MaxLightsInAnyCell => _maxLightsInAnyCell;
public ConservativeLightGrid(ComputeShader shader)
{
_shader = shader;
_buildLightGridlKernel = _shader.FindKernel("BuildConservativeLightGrid");
}
public void Init()
{
if (GridMemLayout == GridMemLayout.Dense && (_lightGridCellsDataBuffer == null || _lightGridCellsDataBuffer.count <= 1))
{
int count = LightGridCellCount * MaxLightsPerCell;
int stride = Marshal.SizeOf<World.ThinReservoir>();
_lightGridCellsDataBuffer?.Dispose();
_lightGridCellsDataBuffer = new ComputeBuffer(count, stride);
}
if (_lightGridBuffer == null || _lightGridBuffer.count <= 1)
{
int count = LightGridCellCount;
int stride = Marshal.SizeOf<int2>();
_lightGridBuffer?.Dispose();
_lightGridBuffer = new ComputeBuffer(count, stride);
}
if (_totalLightsInGridCountBuffer == null)
{
_totalLightsInGridCountBuffer = new ComputeBuffer(1, sizeof(int));
}
}
protected void BindComputeResources(CommandBuffer cmd, World.LightState lightState, Bounds sceneBounds, SamplingResources samplingResources)
{
SamplingResources.Bind(cmd, samplingResources);
// Set the input lighting state.Note that this is a subset, as we evaluate without light cookies
cmd.SetComputeIntParam(_shader, ShaderProperties.NumLights, lightState.LightCount);
cmd.SetComputeIntParam(_shader, ShaderProperties.MaxLightsPerCell, MaxLightsPerCell);
cmd.SetComputeIntParam(_shader, ShaderProperties.NumEmissiveMeshes, lightState.MeshLightCount);
cmd.SetComputeIntParam(_shader, ShaderProperties.GridDimX, _lightGridDims.x);
cmd.SetComputeIntParam(_shader, ShaderProperties.GridDimY, _lightGridDims.y);
cmd.SetComputeIntParam(_shader, ShaderProperties.GridDimZ, _lightGridDims.z);
cmd.SetComputeVectorParam(_shader, ShaderProperties.GridMin, sceneBounds.min);
cmd.SetComputeVectorParam(_shader, ShaderProperties.GridSize, sceneBounds.size);
cmd.SetComputeVectorParam(_shader, ShaderProperties.CellSize, _cellSize);
cmd.SetComputeVectorParam(_shader, ShaderProperties.InvCellSize, _invCellSize);
cmd.SetComputeBufferParam(_shader, _buildLightGridlKernel, ShaderProperties.LightList, lightState.LightListBuffer);
// Set the output buffer
cmd.SetComputeBufferParam(_shader, _buildLightGridlKernel, ShaderProperties.LightGrid, _lightGridBuffer);
cmd.SetComputeBufferParam(_shader, _buildLightGridlKernel, ShaderProperties.TotalReservoirCount, _totalLightsInGridCountBuffer);
}
public void Build(CommandBuffer cmd, World.LightState lightState, Bounds sceneBounds, SamplingResources samplingResources)
{
if (lightState.LightListBuffer == null)
return;
Init();
_sceneBounds = sceneBounds;
_lightGridDims = LightGridUtils.ComputeLightGridDims(sceneBounds.size, LightGridCellCount, LightGridSizingStrategy);
Vector3 div = new Vector3(1.0f / _lightGridDims.x, 1.0f / _lightGridDims.y, 1.0f / _lightGridDims.z);
Vector3 cellSize = Vector3.Scale(sceneBounds.size, div);
_cellSize = cellSize;
// The length of the diagonal
_cellSize.w = Mathf.Sqrt(cellSize.x * cellSize.x + cellSize.y * cellSize.y + cellSize.z * cellSize.z);
_invCellSize = new Vector4(1.0f / _cellSize.x, 1.0f / _cellSize.y, 1.0f / _cellSize.z, 1.0f / _cellSize.w);
BindComputeResources(cmd, lightState, sceneBounds, samplingResources);
// If the grid is sparse, do a first dispatch to determine the total light count for all cells
// And allocate the _lightGridBuffer based on that number
if (GridMemLayout == GridMemLayout.Sparse)
{
_shader.EnableKeyword("SPARSE_GRID");
cmd.SetComputeBufferParam(_shader, _buildLightGridlKernel, ShaderProperties.LightGridCellsData, _lightGridBuffer); // dummy bind
DispatchBuild(cmd, 0);
GraphicsHelpers.Flush(cmd);
var requiredLightCount = new int[1];
_totalLightsInGridCountBuffer.GetData(requiredLightCount);
if (_lightGridCellsDataBuffer == null || _lightGridCellsDataBuffer.count < requiredLightCount[0])
{
_lightGridCellsDataBuffer?.Dispose();
_lightGridCellsDataBuffer = new ComputeBuffer(math.max(requiredLightCount[0], 1), Marshal.SizeOf<World.ThinReservoir>());
}
// Need to re-bind everything after flush
BindComputeResources(cmd, lightState, sceneBounds, samplingResources);
}
else
{
_shader.DisableKeyword("SPARSE_GRID");
}
// Build the grid
cmd.SetComputeBufferParam(_shader, _buildLightGridlKernel, ShaderProperties.LightGridCellsData, _lightGridCellsDataBuffer);
DispatchBuild(cmd, 1);
GraphicsHelpers.Flush(cmd);
int2[] grid = new int2[_lightGridBuffer.count];
_lightGridBuffer.GetData(grid);
_maxLightsInAnyCell = LightGridUtils.ComputeMaxLightsInAnyCell(grid, _lightGridDims);
}
public void Bind(CommandBuffer cmd, IRayTracingShader shader)
{
if (_lightGridCellsDataBuffer == null)
{
// dummy buffer, when the feature is disabled
int stride = Marshal.SizeOf<World.ThinReservoir>();
_lightGridCellsDataBuffer = new ComputeBuffer(1, stride);
}
if (_lightGridBuffer == null)
{
// dummy buffer, when the feature is disabled
_lightGridBuffer = new ComputeBuffer(1, Marshal.SizeOf<int2>());
}
shader.SetIntParam(cmd, ShaderProperties.GridDimX, _lightGridDims.x);
shader.SetIntParam(cmd, ShaderProperties.GridDimY, _lightGridDims.y);
shader.SetIntParam(cmd, ShaderProperties.GridDimZ, _lightGridDims.z);
shader.SetIntParam(cmd, ShaderProperties.NumReservoirs, MaxLightsPerCell);
shader.SetVectorParam(cmd, ShaderProperties.GridMin, _sceneBounds.min);
shader.SetVectorParam(cmd, ShaderProperties.GridSize, _sceneBounds.size);
shader.SetVectorParam(cmd, ShaderProperties.CellSize, _cellSize);
shader.SetVectorParam(cmd, ShaderProperties.InvCellSize, _invCellSize);
shader.SetBufferParam(cmd, ShaderProperties.LightGridCellsData, _lightGridCellsDataBuffer);
shader.SetBufferParam(cmd, ShaderProperties.LightGrid, _lightGridBuffer);
}
public void Dispose()
{
_lightGridCellsDataBuffer?.Dispose();
_lightGridBuffer?.Dispose();
_totalLightsInGridCountBuffer?.Dispose();
}
void DispatchBuild(CommandBuffer cmd, int buildPass)
{
const int groupDim = 4;
cmd.SetComputeIntParam(_shader, ShaderProperties.BuildPass, buildPass);
cmd.SetBufferData(_totalLightsInGridCountBuffer, new uint[] { 0 });
cmd.DispatchCompute(_shader, _buildLightGridlKernel,
GraphicsHelpers.DivUp(_lightGridDims.x, groupDim),
GraphicsHelpers.DivUp(_lightGridDims.y, groupDim),
GraphicsHelpers.DivUp(_lightGridDims.z, groupDim));
}
readonly ComputeShader _shader;
readonly int _buildLightGridlKernel;
ComputeBuffer _lightGridCellsDataBuffer;
ComputeBuffer _lightGridBuffer;
ComputeBuffer _totalLightsInGridCountBuffer;
Bounds _sceneBounds;
Vector4 _cellSize;
Vector4 _invCellSize;
Vector3Int _lightGridDims;
int _maxLightsInAnyCell;
}
internal class RegirLightGrid : IManyLightSampling
{
// Light grid parameters
public int LightGridCellCount = 64 * 64 * 64;
public int MaxLightsPerCell = 64;
public int NumCandidates = -1; // -1 means we iterate over all the lights
public GridSizingStrategy LightGridSizingStrategy = GridSizingStrategy.Uniform;
public int MaxLightsInAnyCell => _maxLightsInAnyCell;
public RegirLightGrid(ComputeShader shader)
{
_shader = shader;
_buildRegirLightGridlKernel = _shader.FindKernel("BuildRegirLightGrid");
}
public void Init()
{
if (_lightGridCellsDataBuffer == null || _lightGridCellsDataBuffer.count <= 1)
{
int count = LightGridCellCount * MaxLightsPerCell;
int stride = Marshal.SizeOf<World.ThinReservoir>();
_lightGridCellsDataBuffer?.Dispose();
_lightGridCellsDataBuffer = new ComputeBuffer(count, stride);
}
if (_lightGridBuffer == null || _lightGridBuffer.count <= 1)
{
int count = LightGridCellCount;
int stride = Marshal.SizeOf<int2>();
_lightGridBuffer?.Dispose();
_lightGridBuffer = new ComputeBuffer(count, stride);
}
}
public void Build(CommandBuffer cmd, World.LightState lightState, Bounds sceneBounds, SamplingResources samplingResources)
{
if (lightState.LightListBuffer == null)
return;
Init();
_sceneBounds = sceneBounds;
// The number of RIS candidates cannot exceed the number of light sources
int activeCandidates = NumCandidates == -1 ? lightState.LightCount : Mathf.Min(NumCandidates, lightState.LightCount);
_lightGridDims = LightGridUtils.ComputeLightGridDims(sceneBounds.size, LightGridCellCount, LightGridSizingStrategy);
Vector3 div = new Vector3(1.0f / _lightGridDims.x, 1.0f / _lightGridDims.y, 1.0f / _lightGridDims.z);
Vector3 cellSize = Vector3.Scale(sceneBounds.size, div);
_cellSize = cellSize;
// The length of the diagonal
_cellSize.w = Mathf.Sqrt(cellSize.x * cellSize.x + cellSize.y * cellSize.y + cellSize.z * cellSize.z);
_invCellSize = new Vector4(1.0f / _cellSize.x, 1.0f / _cellSize.y, 1.0f / _cellSize.z, 1.0f / _cellSize.w);
SamplingResources.Bind(cmd, samplingResources);
// Set the input lighting state.Note that this is a subset, as we evaluate without light cookies
cmd.SetComputeIntParam(_shader, ShaderProperties.NumLights, lightState.LightCount);
cmd.SetComputeIntParam(_shader, ShaderProperties.NumCandidates, activeCandidates);
cmd.SetComputeIntParam(_shader, ShaderProperties.NumReservoirs, MaxLightsPerCell);
cmd.SetComputeIntParam(_shader, ShaderProperties.NumEmissiveMeshes, lightState.MeshLightCount);
cmd.SetComputeIntParam(_shader, ShaderProperties.GridDimX, _lightGridDims.x);
cmd.SetComputeIntParam(_shader, ShaderProperties.GridDimY, _lightGridDims.y);
cmd.SetComputeIntParam(_shader, ShaderProperties.GridDimZ, _lightGridDims.z);
cmd.SetComputeVectorParam(_shader, ShaderProperties.GridMin, sceneBounds.min);
cmd.SetComputeVectorParam(_shader, ShaderProperties.GridSize, sceneBounds.size);
cmd.SetComputeVectorParam(_shader, ShaderProperties.CellSize, _cellSize);
cmd.SetComputeVectorParam(_shader, ShaderProperties.InvCellSize, _invCellSize);
cmd.SetComputeBufferParam(_shader, _buildRegirLightGridlKernel, ShaderProperties.LightList, lightState.LightListBuffer);
// Set the output buffer
cmd.SetComputeBufferParam(_shader, _buildRegirLightGridlKernel, ShaderProperties.LightGrid, _lightGridBuffer);
cmd.SetComputeBufferParam(_shader, _buildRegirLightGridlKernel, ShaderProperties.LightGridCellsData, _lightGridCellsDataBuffer);
// Build the grid
const int groupDim = 4;
cmd.DispatchCompute(_shader, _buildRegirLightGridlKernel,
GraphicsHelpers.DivUp(_lightGridDims.x, groupDim),
GraphicsHelpers.DivUp(_lightGridDims.y, groupDim),
GraphicsHelpers.DivUp(_lightGridDims.z, groupDim));
GraphicsHelpers.Flush(cmd);
int2[] grid = new int2[_lightGridBuffer.count];
_lightGridBuffer.GetData(grid);
_maxLightsInAnyCell = LightGridUtils.ComputeMaxLightsInAnyCell(grid, _lightGridDims);
}
public void Bind(CommandBuffer cmd, IRayTracingShader shader)
{
if (_lightGridCellsDataBuffer == null)
{
// dummy buffer, when the feature is disabled
int stride = Marshal.SizeOf<World.ThinReservoir>();
_lightGridCellsDataBuffer = new ComputeBuffer(1, stride);
}
if (_lightGridBuffer == null)
{
// dummy buffer, when the feature is disabled
_lightGridBuffer = new ComputeBuffer(1, Marshal.SizeOf<int2>());
}
shader.SetIntParam(cmd, ShaderProperties.GridDimX, _lightGridDims.x);
shader.SetIntParam(cmd, ShaderProperties.GridDimY, _lightGridDims.y);
shader.SetIntParam(cmd, ShaderProperties.GridDimZ, _lightGridDims.z);
shader.SetIntParam(cmd, ShaderProperties.NumReservoirs, MaxLightsPerCell);
shader.SetVectorParam(cmd, ShaderProperties.GridMin, _sceneBounds.min);
shader.SetVectorParam(cmd, ShaderProperties.GridSize, _sceneBounds.size);
shader.SetVectorParam(cmd, ShaderProperties.CellSize, _cellSize);
shader.SetVectorParam(cmd, ShaderProperties.InvCellSize, _invCellSize);
shader.SetBufferParam(cmd, ShaderProperties.LightGridCellsData, _lightGridCellsDataBuffer);
shader.SetBufferParam(cmd, ShaderProperties.LightGrid, _lightGridBuffer);
}
public void Dispose()
{
_lightGridCellsDataBuffer?.Dispose();
_lightGridBuffer?.Dispose();
}
readonly ComputeShader _shader;
readonly int _buildRegirLightGridlKernel;
ComputeBuffer _lightGridCellsDataBuffer;
ComputeBuffer _lightGridBuffer;
Bounds _sceneBounds;
Vector4 _cellSize;
Vector4 _invCellSize;
Vector3Int _lightGridDims;
int _maxLightsInAnyCell;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 79729a586fa84f249a56f19de16c118e
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 372699641323414393473220cead670a
timeCreated: 1758191411
@@ -0,0 +1,237 @@
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine.Rendering;
namespace UnityEngine.PathTracing.Core
{
internal enum MaterialPropertyType { None = 0, Color, Texture }
internal struct MaterialPropertyDesc
{
public MaterialPropertyType Type;
public float3 Color; // Unused if type == Textured
}
internal enum EmissionMode
{
Baked,
Realtime
}
internal enum TransmissionChannels { None = 0, RGB, Alpha }
internal struct TransmissionDesc
{
public Texture SourceTexture;
public TransmissionChannels Channels;
public Vector2 Scale;
public Vector2 Offset;
}
internal static class MaterialAspectOracle
{
// See gi::HasBakedEmissive in Materials.cpp
public static MaterialPropertyDesc GetEmission(Material mat, EmissionMode emissionMode)
{
var emissiveFlags = mat.globalIlluminationFlags;
// If the material is explicitly marked as black, there is no emission
bool isBlack = emissiveFlags.HasFlag(MaterialGlobalIlluminationFlags.EmissiveIsBlack);
if (isBlack)
{
return new MaterialPropertyDesc { Type = MaterialPropertyType.None, Color = float3.zero };
}
bool isBaked = emissiveFlags.HasFlag(MaterialGlobalIlluminationFlags.BakedEmissive);
bool isRealtime = emissiveFlags.HasFlag(MaterialGlobalIlluminationFlags.RealtimeEmissive);
bool emissionEnabled = false;
switch (emissionMode)
{
case EmissionMode.Baked:
emissionEnabled = isBaked;
break;
case EmissionMode.Realtime:
emissionEnabled = isRealtime;
break;
default:
Debug.LogError($"Unexpected emission mode: {emissionMode}");
break;
}
if (!emissionEnabled)
{
return new MaterialPropertyDesc { Type = MaterialPropertyType.None, Color = float3.zero };
}
// If the material has an emission keyword, but it is disabled, there is no emission
if (IsMaterialWithEmissionKeyword(mat) && !EnumerableArrayContains(mat.shaderKeywords, "_EMISSION"))
{
return new MaterialPropertyDesc { Type = MaterialPropertyType.None, Color = float3.zero };
}
// If we have reached this point, the material should be emissive.
// First we check for an emissive texture, and use that if it exists
if (HasEmissionMap(mat))
{
return new MaterialPropertyDesc { Type = MaterialPropertyType.Texture, Color = float3.zero };
}
// Otherwise, if the material only has an emissive color, we use that
if (mat.HasProperty(SID.EmissionColor))
{
return new MaterialPropertyDesc { Type = MaterialPropertyType.Color, Color = ToFloat3(mat.GetColor(SID.EmissionColor)) };
}
// If we found neither property, we assume that the material has an unusual meta pass implementation,
// which will render the emission - thus we use texture mode
return new MaterialPropertyDesc { Type = MaterialPropertyType.Texture, Color = float3.zero };
}
private static bool EnumerableArrayContains(IEnumerable<string> array, string value)
{
foreach (string element in array)
if (EqualityComparer<string>.Default.Equals(element, value))
return true;
return false;
}
// Check if a material has a property with a specific Shaderlab property flag
private static bool MaterialHasPropertyWithFlag(Material mat, ShaderPropertyFlags flag)
{
if (mat.shader == null)
return false;
int numProperties = mat.shader.GetPropertyCount();
for (int i = 0; i < numProperties; ++i)
{
var flags = mat.shader.GetPropertyFlags(i);
if (flags.HasFlag(flag))
{
return true;
}
}
return false;
}
// See CreateBakeMaterial in ExtractBakeMaterials.cpp
public static TransmissionDesc GetTransmission(Material mat)
{
// Full RGB transmission
bool hasRGBTransparencyTexture = mat.HasProperty(SID.TransparencyLm) && mat.GetTexture(SID.TransparencyLm) != null;
if (hasRGBTransparencyTexture)
{
return new TransmissionDesc
{
Channels = TransmissionChannels.RGB,
SourceTexture = mat.GetTexture(SID.TransparencyLm),
Scale = mat.GetTextureScale(SID.TransparencyLm),
Offset = mat.GetTextureOffset(SID.TransparencyLm)
};
}
// Alpha-only transmission, alpha from main texture (if exists)
bool isOnTransparentQueue = mat.renderQueue >= (int)RenderQueue.AlphaTestRenderQueue && mat.renderQueue < (int)RenderQueue.OverlayRenderQueue;
bool hasMainTexture = MaterialHasPropertyWithFlag(mat, ShaderPropertyFlags.MainTexture) || mat.HasProperty(SID.MainTex);
if (isOnTransparentQueue && hasMainTexture)
{
return new TransmissionDesc
{
Channels = TransmissionChannels.Alpha,
SourceTexture = mat.mainTexture,
Scale = mat.mainTextureScale,
Offset = mat.mainTextureOffset
};
}
// No transmission
return new TransmissionDesc { Channels = TransmissionChannels.None };
}
private static bool HasEmissionMap(Material mat)
{
return (mat.HasProperty(SID.EmissionMap) && mat.GetTexture(SID.EmissionMap) != null)
&& (!mat.HasProperty(SID.UseEmissiveMap) || mat.GetInt(SID.UseEmissiveMap) == 1);
}
private static bool IsMaterialWithEmissionKeyword(Material mat)
{
return EnumerableArrayContains(mat.shader.keywordSpace.keywordNames, "_EMISSION");
}
public static float GetAlpha(Material mat)
{
if (mat.HasProperty(SID.BaseColor))
{
return mat.GetColor(SID.BaseColor).a;
}
else if (mat.HasProperty(SID.Color))
{
return mat.GetColor(SID.Color).a;
}
else
{
for (int i = 0; i < mat.shader.GetPropertyCount(); i++)
{
if (mat.shader.GetPropertyFlags(i).HasFlag(ShaderPropertyFlags.MainColor))
{
return mat.GetColor(mat.shader.GetPropertyNameId(i)).a;
}
}
return 1.0f;
}
}
public static bool UsesAlphaCutoff(Material mat)
{
bool alphaTestQueue = mat.renderQueue >= (int)RenderQueue.AlphaTestRenderQueue && mat.renderQueue < (int)RenderQueue.TransparentRenderQueue;
if (!alphaTestQueue)
return false;
return mat.HasProperty(SID.Cutoff) || mat.HasProperty(SID.AlphaTestRef);
}
public static float GetAlphaCutoff(Material mat)
{
if (mat.HasProperty(SID.Cutoff))
{
return mat.GetFloat(SID.Cutoff);
}
else if (mat.HasProperty(SID.AlphaTestRef))
{
return mat.GetFloat(SID.AlphaTestRef);
}
return 0.0f;
}
private static float3 ToFloat3(Color col)
{
return new float3(col.r, col.g, col.b);
}
private enum RenderQueue
{
GeometryRenderQueue = 2000,
AlphaTestRenderQueue = 2450,
TransparentRenderQueue = 3000,
OverlayRenderQueue = 4000,
}
private static class SID
{
public static readonly int EmissionColor = Shader.PropertyToID("_EmissionColor");
public static readonly int EmissionMap = Shader.PropertyToID("_EmissionMap");
public static readonly int UseEmissiveMap = Shader.PropertyToID("_UseEmissiveMap");
public static readonly int TransparencyLm = Shader.PropertyToID("_TransparencyLM");
public static readonly int Color = Shader.PropertyToID("_Color");
public static readonly int BaseColor = Shader.PropertyToID("_BaseColor");
public static readonly int Cutoff = Shader.PropertyToID("_Cutoff");
public static readonly int AlphaTestRef = Shader.PropertyToID("_AlphaTestRef");
public static readonly int MainTex = Shader.PropertyToID("_MainTex");
}
// TODO(Yvain) Bump, roughness, metalness ?
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 57a4583d3447a474ab6db0deedbaeb0b
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,821 @@
using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using Unity.Collections;
using Unity.Mathematics;
using UnityEngine.Assertions;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
namespace UnityEngine.PathTracing.Core
{
internal enum UVChannel : uint { UV0 = 0, UV1 = 1 };
internal class MaterialPool : IDisposable
{
internal struct MaterialDescriptor
{
public Texture Albedo;
public Vector2 AlbedoScale;
public Vector2 AlbedoOffset;
public Texture Emission;
public Vector2 EmissionScale;
public Vector2 EmissionOffset;
public Vector3 EmissionColor;
public MaterialPropertyType EmissionType;
public Texture Transmission;
public Vector2 TransmissionScale;
public Vector2 TransmissionOffset;
public TransmissionChannels TransmissionChannels;
public float Alpha;
public float AlphaCutoff;
public bool UseAlphaCutoff;
public bool DoubleSidedGI;
public bool PointSampleTransmission;
public bool PointSampleAlbedo;
public bool PointSampleEmission;
}
[Flags]
private enum MaterialFlags : uint
{
None = 0,
IsTransmissive = 1 << 0,
DoubleSidedGI = 1 << 1,
PointSampleTransmission = 1 << 2,
PointSampleAlbedo = 1 << 3,
PointSampleEmission = 1 << 4,
}
private struct GpuMaterialEntry
{
public int AlbedoTextureIndex;
public int EmissionTextureIndex;
public int TransmissionTextureIndex;
public MaterialFlags Flags;
public float2 AlbedoScale;
public float2 AlbedoOffset;
public float2 EmissionScale;
public float2 EmissionOffset;
public float2 TransmissionScale;
public float2 TransmissionOffset;
public float3 EmissionColor;
public UVChannel AlbedoAndEmissionUVChannel;
};
private enum TextureType { Albedo, Emission, Transmission, LightCookie, LightCubemap };
private class MaterialEntry
{
public MaterialEntry(BlockAllocator.Allocation indexInBufferAlloc)
{
IndexInBuffer = indexInBufferAlloc;
}
public readonly BlockAllocator.Allocation IndexInBuffer;
public TextureSlotAllocator.TextureLocation AlbedoTextureLocation = TextureSlotAllocator.TextureLocation.Invalid;
public TextureSlotAllocator.TextureLocation EmissionTextureLocation = TextureSlotAllocator.TextureLocation.Invalid;
public TextureSlotAllocator.TextureLocation TransmissionTextureLocation = TextureSlotAllocator.TextureLocation.Invalid;
public float3 EmissionColor = new(0, 0, 0);
public UVChannel AlbedoAndEmissionUVChannel = 0;
public bool DoubleSidedGI;
public bool IsTransmissive;
public bool PointSampleTransmission;
public bool PointSampleAlbedo;
public bool PointSampleEmission;
};
private readonly Dictionary<UInt64, MaterialEntry> _materialMap = new();
private readonly Dictionary<ulong, BlockAllocator.Allocation> _lightCookies = new(); // this dictionary is used to keep track of which textures are inserted in the atlas and avoid duplication (important for LiveGI)
private readonly Dictionary<int, ulong> _cookieHandleToID = new(); // this dictionary is used when deleting lights with cookies attached, so we can free-up the atlas slots
public int MaterialCount => _materialMap.Count;
private BlockAllocator _materialSlotAllocator;
public ComputeBuffer MaterialBuffer;
private NativeArray<GpuMaterialEntry> _gpuMaterialList;
private bool _materialArrayDirty = true;
private readonly TextureSlotAllocator _albedoTextureAllocator;
private readonly TextureSlotAllocator _emissionTextureAllocator;
private readonly TextureSlotAllocator _transmissionTextureAllocator;
// Avoid overflowing the graphics ring buffer when adding textures to the atlases.
private const int k_TextureFlushThreshold = 128;
private int _textureBlitsSinceLastFlush;
public RenderTexture AlbedoTextures => _albedoTextureAllocator.Texture;
public RenderTexture EmissionTextures => _emissionTextureAllocator.Texture;
public RenderTexture TransmissionTextures => _transmissionTextureAllocator.Texture;
private static Mesh _planeMesh;
public RenderTexture LightCookieTextures;
private BlockAllocator _lightCookieTexturesSlotAllocator;
public RenderTexture LightCubemapTextures;
private BlockAllocator _lightCubemapTexturesSlotAllocator;
private readonly ComputeShader _setAlphaChannelShader;
private readonly int _setAlphaChannelKernel;
private readonly uint3 _alphaShaderThreadGroupSizes;
private readonly ComputeShader _blitCubemapShader;
private readonly int _blitCubemapKernel;
private readonly ComputeShader _blitGrayscaleCookieShader;
private readonly int _blitGrayscaleCookieKernel;
private const int AtlasSize = 256;
public MaterialPool(ComputeShader setAlphaChannelShader, ComputeShader blitCubemapShader, ComputeShader blitGrayscaleCookieShader)
{
_setAlphaChannelShader = setAlphaChannelShader;
_setAlphaChannelKernel = _setAlphaChannelShader.FindKernel("SetAlphaChannel");
_setAlphaChannelShader.GetKernelThreadGroupSizes(_setAlphaChannelKernel,
out _alphaShaderThreadGroupSizes.x, out _alphaShaderThreadGroupSizes.y, out _alphaShaderThreadGroupSizes.z);
_blitCubemapShader = blitCubemapShader;
_blitCubemapKernel = _blitCubemapShader.FindKernel("BlitCubemap");
_blitGrayscaleCookieShader = blitGrayscaleCookieShader;
_blitGrayscaleCookieKernel = _blitGrayscaleCookieShader.FindKernel("BlitGrayScaleCookie");
const int initialMaxLightCookieTextureCount = 30;
const int initialMaxLightCubemapTextureCount = 3;
const int initialMaxMaterialCount = 100;
_albedoTextureAllocator = new TextureSlotAllocator(AtlasSize, GetTextureFormat(TextureType.Albedo), FilterMode.Bilinear);
_emissionTextureAllocator = new TextureSlotAllocator(AtlasSize, GetTextureFormat(TextureType.Emission), FilterMode.Bilinear);
_transmissionTextureAllocator = new TextureSlotAllocator(AtlasSize, GetTextureFormat(TextureType.Transmission), FilterMode.Bilinear);
_materialSlotAllocator.Initialize(initialMaxMaterialCount);
MaterialBuffer = new ComputeBuffer(initialMaxMaterialCount, Marshal.SizeOf<GpuMaterialEntry>());
_gpuMaterialList = new NativeArray<GpuMaterialEntry>(initialMaxMaterialCount, Allocator.Persistent);
LightCookieTextures = CreateTextureArray(initialMaxLightCookieTextureCount, TextureType.LightCookie);
_lightCookieTexturesSlotAllocator.Initialize(initialMaxLightCookieTextureCount);
LightCubemapTextures = CreateTextureArray(initialMaxLightCubemapTextureCount, TextureType.LightCubemap);
_lightCubemapTexturesSlotAllocator.Initialize(initialMaxLightCubemapTextureCount);
}
public void Dispose()
{
_materialSlotAllocator.Dispose();
MaterialBuffer?.Dispose();
if (_gpuMaterialList.IsCreated)
_gpuMaterialList.Dispose();
_albedoTextureAllocator.Dispose();
_emissionTextureAllocator.Dispose();
_transmissionTextureAllocator.Dispose();
_lightCookieTexturesSlotAllocator.Dispose();
if (LightCookieTextures != null)
{
LightCookieTextures.Release();
CoreUtils.Destroy(LightCookieTextures);
}
_lightCubemapTexturesSlotAllocator.Dispose();
if (LightCubemapTextures != null)
{
LightCubemapTextures.Release();
CoreUtils.Destroy(LightCubemapTextures);
}
}
public void AddMaterial(UInt64 materialHandle, in MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel)
{
MaterialEntry materialEntry;
Debug.Assert(!_materialMap.ContainsKey(materialHandle), "Material was already added to the pool.");
var slotAllocation = _materialSlotAllocator.Allocate(1);
if (!slotAllocation.valid)
{
_materialSlotAllocator.Grow(_materialSlotAllocator.capacity+1);
RecreateGpuMaterialList();
slotAllocation = _materialSlotAllocator.Allocate(1);
Assert.IsTrue(slotAllocation.valid);
}
materialEntry = new MaterialEntry(slotAllocation);
UpdateMaterial(in material, albedoAndEmissionUVChannel, materialEntry);
_materialMap.Add(materialHandle, materialEntry);
UpdateMaterialList(materialEntry);
}
public void UpdateMaterial(UInt64 materialHandle, in MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel)
{
MaterialEntry materialEntry = _materialMap[materialHandle];
UpdateMaterial(in material, albedoAndEmissionUVChannel, materialEntry);
}
public void RemoveMaterial(UInt64 materialInstanceID)
{
if (!_materialMap.TryGetValue(materialInstanceID, out var materialEntry))
{
Debug.Assert(false, "Material was not added to the pool.");
return;
}
_materialSlotAllocator.FreeAllocation(in materialEntry.IndexInBuffer);
RemoveTextureIfPresent(TextureType.Albedo, ref materialEntry.AlbedoTextureLocation);
RemoveTextureIfPresent(TextureType.Emission, ref materialEntry.EmissionTextureLocation);
RemoveTextureIfPresent(TextureType.Transmission, ref materialEntry.TransmissionTextureLocation);
_materialMap.Remove(materialInstanceID);
}
public void GetMaterialInfo(UInt64 materialHandle, out uint materialIndex, out bool isTransmissive)
{
MaterialEntry entry;
if (_materialMap.TryGetValue(materialHandle, out entry))
{
materialIndex = (uint)entry.IndexInBuffer.block.offset;
isTransmissive = entry.IsTransmissive;
}
else
throw new InvalidOperationException("Material not in pool");
}
public bool IsEmissive(UInt64 materialHandle, out float3 emissionColor)
{
float3 zero = new(0, 0, 0);
emissionColor = zero;
if (_materialMap.TryGetValue(materialHandle, out var entry))
{
if (entry.EmissionTextureLocation.IsValid || math.any(entry.EmissionColor != zero))
{
emissionColor = entry.EmissionColor;
return true;
}
return false;
}
else
return false;
}
public void Build(CommandBuffer cmd)
{
if (cmd is null)
throw new InvalidOperationException("Invalid CommandBuffer, did you forget to call Initialize()?");
if (_materialArrayDirty)
{
cmd.SetBufferData(MaterialBuffer, _gpuMaterialList);
_materialArrayDirty = false;
}
}
private void UpdateMaterial(in MaterialDescriptor material, UVChannel albedoAndEmissionUVChannel, MaterialEntry materialEntry)
{
AddOrUpdateTexture(in material, TextureType.Albedo, ref materialEntry.AlbedoTextureLocation);
if (material.TransmissionChannels == TransmissionChannels.Alpha)
FillAlbedoTextureAlphaWithOpacity(in material, materialEntry.AlbedoTextureLocation);
materialEntry.AlbedoAndEmissionUVChannel = albedoAndEmissionUVChannel;
materialEntry.DoubleSidedGI = material.DoubleSidedGI;
materialEntry.IsTransmissive = material.TransmissionChannels != TransmissionChannels.None;
materialEntry.PointSampleTransmission = material.PointSampleTransmission;
materialEntry.PointSampleAlbedo = material.PointSampleAlbedo;
materialEntry.PointSampleEmission = material.PointSampleEmission;
var emissionType = material.EmissionType;
if (emissionType == MaterialPropertyType.Texture)
{
AddOrUpdateTexture(in material, TextureType.Emission, ref materialEntry.EmissionTextureLocation);
materialEntry.EmissionColor = 0;
}
else if (emissionType == MaterialPropertyType.Color)
{
RemoveTextureIfPresent(TextureType.Emission, ref materialEntry.EmissionTextureLocation);
materialEntry.EmissionColor = material.EmissionColor;
}
else if (emissionType == MaterialPropertyType.None)
{
RemoveTextureIfPresent(TextureType.Emission, ref materialEntry.EmissionTextureLocation);
materialEntry.EmissionColor = 0;
}
if (material.TransmissionChannels == TransmissionChannels.RGB && material.Transmission != null)
{
AddOrUpdateTexture(in material, TextureType.Transmission, ref materialEntry.TransmissionTextureLocation);
}
else
{
RemoveTextureIfPresent(TextureType.Transmission, ref materialEntry.TransmissionTextureLocation);
}
UpdateMaterialList(materialEntry);
}
private void UpdateMaterialList(MaterialEntry entry)
{
// Default values, filled in below
var gpuMat = new GpuMaterialEntry()
{
// Default values, filled in below
AlbedoTextureIndex = -1,
EmissionTextureIndex = -1,
TransmissionTextureIndex = -1,
AlbedoScale = Vector2.one,
AlbedoOffset = Vector2.zero,
EmissionScale = Vector2.one,
EmissionOffset = Vector2.zero,
TransmissionScale = Vector2.one,
TransmissionOffset = Vector2.zero,
// Values to be filled in immediately
EmissionColor = entry.EmissionColor,
AlbedoAndEmissionUVChannel = entry.AlbedoAndEmissionUVChannel,
Flags = (entry.IsTransmissive ? MaterialFlags.IsTransmissive : MaterialFlags.None) |
(entry.DoubleSidedGI ? MaterialFlags.DoubleSidedGI : MaterialFlags.None) |
(entry.PointSampleTransmission ? MaterialFlags.PointSampleTransmission : MaterialFlags.None) |
(entry.PointSampleAlbedo ? MaterialFlags.PointSampleAlbedo : MaterialFlags.None) |
(entry.PointSampleEmission ? MaterialFlags.PointSampleEmission : MaterialFlags.None),
};
if (entry.AlbedoTextureLocation.IsValid)
{
gpuMat.AlbedoTextureIndex = entry.AlbedoTextureLocation.AtlasIndex;
_albedoTextureAllocator.GetScaleAndOffset(in entry.AlbedoTextureLocation, out var albedoScale, out var albedoOffset);
gpuMat.AlbedoScale = albedoScale;
gpuMat.AlbedoOffset = albedoOffset;
}
if (entry.EmissionTextureLocation.IsValid)
{
gpuMat.EmissionTextureIndex = entry.EmissionTextureLocation.AtlasIndex;
_emissionTextureAllocator.GetScaleAndOffset(in entry.EmissionTextureLocation, out var emissionScale, out var emissionOffset);
gpuMat.EmissionScale = emissionScale;
gpuMat.EmissionOffset = emissionOffset;
}
if (entry.TransmissionTextureLocation.IsValid)
{
gpuMat.TransmissionTextureIndex = entry.TransmissionTextureLocation.AtlasIndex;
_transmissionTextureAllocator.GetScaleAndOffset(in entry.TransmissionTextureLocation, out var transmissionScale, out var transmissionOffset);
gpuMat.TransmissionScale = transmissionScale;
gpuMat.TransmissionOffset = transmissionOffset;
}
_gpuMaterialList[entry.IndexInBuffer.block.offset] = gpuMat;
_materialArrayDirty = true;
}
#region Cookie support
private static int GetCookieFaces(Texture tex)
{
return (tex.dimension == TextureDimension.Cube) ? 6 : 1;
}
private static int GetCookieHandle(int slices, int handle)
{
int offset = (slices > 1) ? 1 : 0;
// use the first bit to indicate the array type
return 2 * handle + offset;
}
public int AddCookieTexture(Texture cookie)
{
if (cookie != null)
{
var cookieID = Util.EntityIDToUlong(cookie.GetEntityId());
if (_lightCookies.TryGetValue(cookieID, out var allocator))
{
// This cookie was already copied in the atlas in a previous frame
// Baking will never hit this path, as the lights are not updated during a bake, but it's important for LiveGI
return allocator.handle;
}
int slices = GetCookieFaces(cookie);
BlockAllocator.Allocation slotAllocation;
if (slices > 1)
{
slotAllocation = _lightCubemapTexturesSlotAllocator.Allocate(1);
ExpandCookieTextureArray(true, ref _lightCubemapTexturesSlotAllocator, ref LightCubemapTextures, ref slotAllocation);
RenderTexture prevRT = RenderTexture.active;
BlitCubemapCookie(cookie, LightCubemapTextures, slotAllocation.block.offset);
RenderTexture.active = prevRT;
}
else
{
slotAllocation = _lightCookieTexturesSlotAllocator.Allocate(1);
ExpandCookieTextureArray(false, ref _lightCookieTexturesSlotAllocator, ref LightCookieTextures, ref slotAllocation);
RenderTexture prevRT = RenderTexture.active;
Blit2DCookie(cookie, LightCookieTextures, slotAllocation.block.offset);
RenderTexture.active = prevRT;
}
int handle = GetCookieHandle(slices, slotAllocation.handle);
_lightCookies.Add(cookieID, slotAllocation);
_cookieHandleToID.Add(handle, cookieID);
return slotAllocation.handle;
}
return -1;
}
public void RemoveCookieTexture(int cookieFaces, int cookieIndex)
{
if (cookieIndex == -1)
return;
int cookieHandle = GetCookieHandle(cookieFaces, cookieIndex);
if (!_cookieHandleToID.TryGetValue(cookieHandle, out var cookieID))
{
if (!_lightCookies.TryGetValue(cookieID, out var cookieAllocation))
{
Debug.Assert(false, "Light cookie was not found in the pool.");
return;
}
if (cookieFaces > 1)
_lightCubemapTexturesSlotAllocator.FreeAllocation(in cookieAllocation);
else
_lightCookieTexturesSlotAllocator.FreeAllocation(in cookieAllocation);
_lightCookies.Remove(cookieID);
_cookieHandleToID.Remove(cookieHandle);
}
}
private void ExpandCookieTextureArray(bool isCubemapCookie, ref BlockAllocator allocator, ref RenderTexture texture, ref BlockAllocator.Allocation textureAlloc)
{
if (!textureAlloc.valid)
{
textureAlloc = allocator.Allocate(1);
if (!textureAlloc.valid)
{
var oldCapacity = allocator.capacity;
allocator.Grow(allocator.capacity + 1);
var newTexture = CreateTextureArray(allocator.capacity, isCubemapCookie ? TextureType.LightCubemap : TextureType.LightCookie);
using var cmd = new CommandBuffer();
for (int i = 0; i < oldCapacity; ++i)
cmd.CopyTexture(texture, i, newTexture, i);
Graphics.ExecuteCommandBuffer(cmd);
texture.Release();
texture = newTexture;
textureAlloc = allocator.Allocate(1);
Assert.IsTrue(textureAlloc.valid);
}
}
}
// Blits all faces of a cubemap to a slice of a cubemap array, performing any format conversions that are necessary
private void BlitCubemapCookie(Texture source, RenderTexture dest, int destIndex)
{
using var cmd = new CommandBuffer();
RenderTexture tempRT = new RenderTexture(AtlasSize, AtlasSize, 0, dest.format, 0);
tempRT.enableRandomWrite = true;
tempRT.Create();
if (GraphicsFormatUtility.IsAlphaOnlyFormat(source.graphicsFormat))
_blitCubemapShader.EnableKeyword("GRAYSCALE_BLIT");
else
_blitCubemapShader.DisableKeyword("GRAYSCALE_BLIT");
for (int i = 0; i < 6; ++i)
{
cmd.SetComputeIntParam(_blitCubemapShader, Shader.PropertyToID("g_TextureSize"), dest.width);
cmd.SetComputeIntParam(_blitCubemapShader, Shader.PropertyToID("g_Face"), i);
cmd.SetComputeTextureParam(_blitCubemapShader, _blitCubemapKernel, Shader.PropertyToID("g_Source"), source);
cmd.SetComputeTextureParam(_blitCubemapShader, _blitCubemapKernel, Shader.PropertyToID("g_Destination"), tempRT);
int dispatchSize = GraphicsHelpers.DivUp(dest.width, 8);
cmd.DispatchCompute(_blitCubemapShader, _blitCubemapKernel, dispatchSize, dispatchSize, 1);
cmd.CopyTexture(tempRT, 0, dest, 6 * destIndex + i);
}
Graphics.ExecuteCommandBuffer(cmd);
tempRT.Release();
CoreUtils.Destroy(tempRT);
}
private void Blit2DCookie(Texture source, RenderTexture dest, int destIndex)
{
if (!GraphicsFormatUtility.IsAlphaOnlyFormat(source.graphicsFormat))
{
Graphics.Blit(source, dest, 0, destIndex);
}
else
{
// Handle grayscale 2d cookie to RGB conversion
RenderTexture tempRT = new RenderTexture(AtlasSize, AtlasSize, 0, dest.format, 0);
tempRT.enableRandomWrite = true;
tempRT.Create();
using var cmd = new CommandBuffer();
cmd.SetComputeIntParam(_blitGrayscaleCookieShader, Shader.PropertyToID("g_TextureWidth"), dest.width);
cmd.SetComputeIntParam(_blitGrayscaleCookieShader, Shader.PropertyToID("g_TextureHeight"), dest.height);
cmd.SetComputeTextureParam(_blitGrayscaleCookieShader, _blitGrayscaleCookieKernel, Shader.PropertyToID("g_Source"), source);
cmd.SetComputeTextureParam(_blitGrayscaleCookieShader, _blitGrayscaleCookieKernel, Shader.PropertyToID("g_Destination"), tempRT);
cmd.DispatchCompute(_blitGrayscaleCookieShader, _blitGrayscaleCookieKernel, GraphicsHelpers.DivUp(dest.width, 8), GraphicsHelpers.DivUp(dest.height, 8), 1);
cmd.CopyTexture(tempRT, 0, dest, destIndex);
Graphics.ExecuteCommandBuffer(cmd);
tempRT.Release();
CoreUtils.Destroy(tempRT);
}
}
#endregion
private void AddOrUpdateTexture(in MaterialDescriptor material, TextureType textureType, ref TextureSlotAllocator.TextureLocation location)
{
// Find appropriate allocator, scale, offset and texture
var allocator = _transmissionTextureAllocator;
Vector2 scale = material.TransmissionScale;
Vector2 offset = material.TransmissionOffset;
offset.y = -offset.y; // TODO: During extraction this value is negated. This should be fixed. Tracked here: https://jira.unity3d.com/browse/GFXFEAT-802
Texture texture = material.Transmission;
if (textureType == TextureType.Albedo)
{
allocator = _albedoTextureAllocator;
texture = material.Albedo;
scale = material.AlbedoScale;
offset = material.AlbedoOffset;
}
else if (textureType == TextureType.Emission)
{
allocator = _emissionTextureAllocator;
texture = material.Emission;
scale = material.EmissionScale;
offset = material.EmissionOffset;
}
// Invalid texture - bail
if (texture == null)
return;
// Update path
if (location.IsValid)
{
allocator.UpdateTexture(in location, texture, scale, offset);
}
// Add path
else
{
location = allocator.AddTexture(texture, scale, offset);
}
if (++_textureBlitsSinceLastFlush >= k_TextureFlushThreshold)
{
GL.Flush();
_textureBlitsSinceLastFlush = 0;
}
}
private void RemoveTextureIfPresent(TextureType textureType, ref TextureSlotAllocator.TextureLocation location)
{
if (!location.IsValid)
return;
if (textureType == TextureType.Albedo)
_albedoTextureAllocator.RemoveTexture(in location);
else if (textureType == TextureType.Emission)
_emissionTextureAllocator.RemoveTexture(in location);
else
_transmissionTextureAllocator.RemoveTexture(in location);
location = TextureSlotAllocator.TextureLocation.Invalid;
}
private void FillAlbedoTextureAlphaWithOpacity(in MaterialDescriptor material, TextureSlotAllocator.TextureLocation location)
{
if (material.Transmission == null)
return;
Vector2Int targetSize = _albedoTextureAllocator.GetTextureSize(location);
int targetOffsetX = location.TextureNode.PosX;
int targetOffsetY = location.TextureNode.PosY;
using var cmd = new CommandBuffer();
cmd.SetComputeIntParam(_setAlphaChannelShader, Shader.PropertyToID("g_TextureWidth"), targetSize.x);
cmd.SetComputeIntParam(_setAlphaChannelShader, Shader.PropertyToID("g_TextureHeight"), targetSize.y);
cmd.SetComputeIntParam(_setAlphaChannelShader, Shader.PropertyToID("g_TargetSlice"), location.AtlasIndex);
cmd.SetComputeIntParam(_setAlphaChannelShader, Shader.PropertyToID("g_TargetOffsetX"), targetOffsetX);
cmd.SetComputeIntParam(_setAlphaChannelShader, Shader.PropertyToID("g_TargetOffsetY"), targetOffsetY);
cmd.SetComputeFloatParam(_setAlphaChannelShader, Shader.PropertyToID("g_Alpha"), material.Alpha);
cmd.SetComputeFloatParam(_setAlphaChannelShader, Shader.PropertyToID("g_AlphaCutoff"), material.AlphaCutoff);
cmd.SetComputeIntParam(_setAlphaChannelShader, Shader.PropertyToID("g_UseAlphaCutoff"), material.UseAlphaCutoff ? 1 : 0);
cmd.SetComputeTextureParam(_setAlphaChannelShader, _setAlphaChannelKernel, Shader.PropertyToID("g_AlbedoTextures"), AlbedoTextures);
cmd.SetComputeTextureParam(_setAlphaChannelShader, _setAlphaChannelKernel, Shader.PropertyToID("g_OpacityTexture"), material.Transmission);
cmd.SetComputeVectorParam(_setAlphaChannelShader, Shader.PropertyToID("g_OpacityTextureUVTransform"), new float4(material.TransmissionScale, material.TransmissionOffset));
cmd.DispatchCompute(_setAlphaChannelShader, _setAlphaChannelKernel, GraphicsHelpers.DivUp(targetSize.x, _alphaShaderThreadGroupSizes.x), GraphicsHelpers.DivUp(targetSize.y, _alphaShaderThreadGroupSizes.y), 1);
Graphics.ExecuteCommandBuffer(cmd);
}
// Render out an albedo/emission texture using the meta pass
private static Texture EvaluateMetaPass(Material material, TextureType textureType)
{
if (textureType == TextureType.Transmission)
{
Debug.Assert(false, "Transmission textures should be handled outside of this function.");
return null;
}
var targetTexture = CreateTexture(textureType);
int metaPassIndex = material.FindPass("Meta");
var fragmentControl = Vector4.zero;
fragmentControl.x = textureType == TextureType.Albedo ? 1 : 0;
fragmentControl.y = textureType == TextureType.Emission ? 1 : 0;
var properties = new MaterialPropertyBlock();
properties.SetVector(Shader.PropertyToID("unity_MetaVertexControl"), new Vector4(0, 0, 0, 0));
properties.SetVector(Shader.PropertyToID("unity_MetaFragmentControl"), fragmentControl);
properties.SetFloat(Shader.PropertyToID("unity_OneOverOutputBoost"), 1.0f);
properties.SetFloat(Shader.PropertyToID("unity_MaxOutputValue"), 0.97f); // only used by albedo pass
properties.SetInt(Shader.PropertyToID("unity_UseLinearSpace"), QualitySettings.activeColorSpace == ColorSpace.Linear ? 1 : 0);
material.DisableKeyword("EDITOR_VISUALIZATION");
using var cmd = new CommandBuffer();
cmd.SetRenderTarget(targetTexture);
cmd.SetViewProjectionMatrices(Matrix4x4.identity, GL.GetGPUProjectionMatrix(Matrix4x4.Ortho(-1, 1, -1, 1, -50, 50), true));
cmd.SetViewport(new Rect(0, 0, targetTexture.width, targetTexture.height));
cmd.ClearRenderTarget(false, true, new Color(0, 0, 0, 1));
if (_planeMesh == null)
_planeMesh = CreateQuadMesh();
Debug.Assert(metaPassIndex != -1, $"Users of MaterialPool are expected to only pass in materials which have a metapass. Material: '{material.name}'.", material);
#if UNITY_EDITOR
Debug.Assert(UnityEditor.ShaderUtil.IsPassCompiled(material, metaPassIndex) || !UnityEditor.ShaderUtil.allowAsyncCompilation, "Users of MaterialPool are expected to ensure that the metapass shader is ready to be used.");
#endif
cmd.DrawMesh(_planeMesh, Matrix4x4.identity, material, 0, metaPassIndex, properties);
Graphics.ExecuteCommandBuffer(cmd);
return targetTexture;
}
// The textures referenced by the material descriptor are owned by the material descriptor.
public static MaterialPool.MaterialDescriptor ConvertUnityMaterialToMaterialDescriptor(Material material, EmissionMode emissionMode)
{
MaterialPool.MaterialDescriptor descriptor = new();
// Emission
var emission = MaterialAspectOracle.GetEmission(material, emissionMode);
descriptor.EmissionType = emission.Type;
descriptor.EmissionColor = emission.Color;
if (emission.Type == MaterialPropertyType.Texture)
{
descriptor.Emission = EvaluateMetaPass(material, TextureType.Emission);
descriptor.EmissionScale = Vector2.one; // Scale and offset handled by meta pass
descriptor.EmissionOffset = Vector2.zero;
}
// Albedo
descriptor.Albedo = EvaluateMetaPass(material, TextureType.Albedo);
descriptor.AlbedoScale = Vector2.one; // Scale and offset handled by meta pass
descriptor.AlbedoOffset = Vector2.zero;
// Transmission
var transmission = MaterialAspectOracle.GetTransmission(material);
descriptor.TransmissionChannels = transmission.Channels;
descriptor.TransmissionScale = Vector2.one; // Scale and offset handled in the Blit below, so we don't have to apply it later
descriptor.TransmissionOffset = Vector2.zero;
if (transmission.Channels != TransmissionChannels.None)
{
RenderTexture prevRT = RenderTexture.active;
var transmissionTexture = CreateTexture(TextureType.Transmission);
Graphics.Blit(transmission.SourceTexture, transmissionTexture, transmission.Scale, transmission.Offset);
descriptor.Transmission = transmissionTexture;
RenderTexture.active = prevRT;
}
descriptor.Alpha = MaterialAspectOracle.GetAlpha(material);
descriptor.UseAlphaCutoff = MaterialAspectOracle.UsesAlphaCutoff(material);
descriptor.AlphaCutoff = MaterialAspectOracle.GetAlphaCutoff(material);
// Other properties
descriptor.DoubleSidedGI = material.doubleSidedGI;
return descriptor;
}
static private GraphicsFormat GetTextureFormat(TextureType textureType)
{
switch (textureType)
{
case TextureType.Albedo: return GraphicsFormat.R8G8B8A8_UNorm;
case TextureType.Emission: return GraphicsFormat.R16G16B16A16_SFloat; // TODO(Yvain) might want to use B10G11R11_UFloatPack32 for emissionthere
case TextureType.Transmission: return GraphicsFormat.R8G8B8A8_UNorm;
case TextureType.LightCookie: return GraphicsFormat.R16G16B16A16_SFloat; // same as emission
case TextureType.LightCubemap: return GraphicsFormat.R16G16B16A16_SFloat; // same as emission
}
return 0;
}
private static RenderTexture CreateTextureArray(int sliceCount, TextureType textureType)
{
TextureDimension dimension = (textureType == TextureType.LightCubemap) ? TextureDimension.CubeArray: TextureDimension.Tex2DArray;
return CreateTexture(textureType, dimension, textureType == TextureType.LightCubemap ? sliceCount * 6 : sliceCount);
}
private static RenderTexture CreateTexture(TextureType textureType, TextureDimension dimension = TextureDimension.Tex2D, int sliceCount = 1)
{
var format = GetTextureFormat(textureType);
var texture = new RenderTexture(new RenderTextureDescriptor(AtlasSize, AtlasSize)
{
dimension = dimension,
depthBufferBits = 0,
volumeDepth = sliceCount,
msaaSamples = 1,
vrUsage = VRTextureUsage.OneEye,
graphicsFormat = format,
enableRandomWrite = true,
})
{
name = "CreateTexture (MaterialPool)",
hideFlags = HideFlags.DontSaveInEditor,
wrapMode = TextureWrapMode.Repeat,
wrapModeU = TextureWrapMode.Repeat,
wrapModeV = TextureWrapMode.Repeat
};
texture.Create();
return texture;
}
private void RecreateGpuMaterialList()
{
MaterialBuffer?.Dispose();
MaterialBuffer = new ComputeBuffer(_materialSlotAllocator.capacity, Marshal.SizeOf<GpuMaterialEntry>());
var oldMaterialList = _gpuMaterialList;
_gpuMaterialList = new NativeArray<GpuMaterialEntry>(_materialSlotAllocator.capacity, Allocator.Persistent);
NativeArray<GpuMaterialEntry>.Copy(oldMaterialList, _gpuMaterialList, oldMaterialList.Length);
oldMaterialList.Dispose();
}
private static Mesh CreateQuadMesh()
{
Mesh mesh = new Mesh();
Vector3[] vertices = {
new(-1.0f, -1.0f, 0),
new(1.0f, -1.0f, 0),
new(-1.0f, 1.0f, 0),
new(1.0f, 1.0f, 0)
};
mesh.vertices = vertices;
Vector3[] normals = {
-Vector3.forward,
-Vector3.forward,
-Vector3.forward,
-Vector3.forward
};
mesh.normals = normals;
Vector2[] uv = {
new(0, 1),
new(1, 1),
new(0, 0),
new(1, 0)
};
mesh.uv = uv;
mesh.uv2 = uv;
int[] tris = {
0, 2, 1, // lower left triangle
2, 3, 1 // upper right triangle
};
mesh.triangles = tris;
mesh.hideFlags = HideFlags.DontSaveInEditor;
return mesh;
}
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetStaticsOnLoad()
{
if (_planeMesh)
{
Object.Destroy(_planeMesh);
_planeMesh = null;
}
}
#endif
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: e1da6470aa67d413da04758e62ce5af9
@@ -0,0 +1,172 @@
#ifndef _MATERIAL_POOL_HLSL_
#define _MATERIAL_POOL_HLSL_
namespace MaterialPool
{
struct MaterialEntry
{
int albedoTextureIndex;
int emissionTextureIndex;
int transmissionTextureIndex;
uint flags;
float2 albedoScale;
float2 albedoOffset;
float2 emissionScale;
float2 emissionOffset;
float2 transmissionScale;
float2 transmissionOffset;
float3 emissionColor;
uint albedoAndEmissionUVChannel;
};
struct MaterialProperties
{
float3 baseColor;
float metalness;
float3 emission;
float roughness;
float3 transmission;
uint isTransmissive;
uint doubleSidedGI;
};
float4 SampleAtlas(Texture2DArray<float4> atlas, SamplerState atlasSampler, float atlasTexelSize, uint index, float2 uv, float2 scale, float2 offset, bool pointFilterMode)
{
// Apply the scale and offset to access to desired atlas entry
float2 localUV = uv * scale + offset;
// To prevent sampling part of the neighbor due to bilinear filtering, we need to clamp the sample
// position to an 'inner rectangle' of the atlas entry, which is shrunk by half a texel on each side.
float2 innerRectMin = offset + (atlasTexelSize * 0.5f);
// Calculating the rectangle extent is a bit tricky, because the size of the entry (scale)
// is not necessarily a multiple of the atlas texel size. We need to round it up to the next texel first,
// then subtract the half texel.
float2 innerRectMax = ceil((offset + scale) / atlasTexelSize) * atlasTexelSize - (atlasTexelSize * 0.5f);
float2 clampedUV = clamp(localUV, innerRectMin, innerRectMax);
[branch] if (pointFilterMode)
return atlas.Load(int4(clampedUV * rcp(atlasTexelSize), index, 0));
else
return atlas.SampleLevel(atlasSampler, float3(clampedUV, index), 0);
}
float4 LoadAlbedo(
MaterialEntry matEntry,
Texture2DArray<float4> albedoTextures,
SamplerState albedoSamplerState,
float atlasTexelSize,
float2 uv0,
float2 uv1)
{
float4 albedo = float4(0.75, 0.75, 0.75, 0);
if (matEntry.albedoTextureIndex != -1)
{
float2 textureUV = matEntry.albedoAndEmissionUVChannel == 1 ? uv1 : uv0;
bool pointSampleAlbedo = (matEntry.flags & 8) != 0;
albedo = SampleAtlas(albedoTextures, albedoSamplerState, atlasTexelSize, matEntry.albedoTextureIndex, textureUV, matEntry.albedoScale, matEntry.albedoOffset, pointSampleAlbedo);
}
return albedo;
}
float3 BoostAlbedo(float3 albedo, float albedoBoost)
{
// Apply albedo boost, but still keep the reflectance at maximum 100%
return min(albedoBoost * albedo, float3(1.0, 1.0, 1.0));
}
float3 LoadAlbedoWithBoost(
MaterialEntry matEntry,
Texture2DArray<float4> albedoTextures,
SamplerState albedoSamplerState,
float atlasTexelSize,
float albedoBoost,
float2 uv0,
float2 uv1)
{
float4 albedo = LoadAlbedo(matEntry, albedoTextures, albedoSamplerState, atlasTexelSize, uv0, uv1);
return BoostAlbedo(albedo.rgb, albedoBoost);
}
float3 LoadEmission(
MaterialEntry matEntry,
Texture2DArray<float4> emissionTextures,
SamplerState emissionSamplerState,
float atlasTexelSize,
float2 uv0,
float2 uv1)
{
float3 emission;
if (matEntry.emissionTextureIndex != -1)
{
float2 textureUV = matEntry.albedoAndEmissionUVChannel == 1 ? uv1 : uv0;
bool pointSampleEmission = (matEntry.flags & 16) != 0;
emission = SampleAtlas(emissionTextures, emissionSamplerState, atlasTexelSize, matEntry.emissionTextureIndex, textureUV, matEntry.emissionScale, matEntry.emissionOffset, pointSampleEmission).rgb;
}
else
{
emission = matEntry.emissionColor;
}
return emission;
}
float3 LoadTransmission(
MaterialEntry matEntry,
float4 albedo,
Texture2DArray<float4> transmissionTextures,
SamplerState transmissionSamplerState,
float atlasTexelSize,
float2 uv0)
{
float3 transmission = 1.0f - float3(albedo.a, albedo.a, albedo.a);
if (matEntry.transmissionTextureIndex != -1)
{
bool pointSampleTransmission = (matEntry.flags & 4) != 0;
transmission = saturate(SampleAtlas(transmissionTextures, transmissionSamplerState, atlasTexelSize, matEntry.transmissionTextureIndex, uv0, matEntry.transmissionScale, matEntry.transmissionOffset, pointSampleTransmission).rgb);
}
return transmission;
}
MaterialProperties LoadMaterialProperties(
StructuredBuffer<MaterialEntry> materialList,
Texture2DArray<float4> albedoTextures,
SamplerState albedoSamplerState,
Texture2DArray<float4> transmissionTextures,
SamplerState transmissionSamplerState,
Texture2DArray<float4> emissionTextures,
SamplerState emissionSamplerState,
float albedoBoost,
float atlasTexelSize,
uint materialIndex,
float2 uv0,
float2 uv1)
{
const MaterialEntry matEntry = materialList[materialIndex];
MaterialProperties material;
float4 albedo = LoadAlbedo(matEntry, albedoTextures, albedoSamplerState, atlasTexelSize, uv0, uv1);
material.baseColor = BoostAlbedo(albedo.rgb, albedoBoost);
material.transmission = LoadTransmission(matEntry, albedo, transmissionTextures, transmissionSamplerState, atlasTexelSize, uv0);
material.emission = LoadEmission(matEntry, emissionTextures, emissionSamplerState, atlasTexelSize, uv0, uv1);
material.isTransmissive = matEntry.flags & 1;
material.doubleSidedGI = matEntry.flags & 2;
// unused for now, we need these for specular support
material.roughness = 1.0;
material.metalness = 0;
return material;
}
}
#endif
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 974851aba193482e9b796e8883db5c98
timeCreated: 1758099355
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c46962a92697fa0448dfe0c7bb1d6cbb
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,217 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!43 &4300000
Mesh:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_Name: 6FaceSkyboxMesh
serializedVersion: 11
m_SubMeshes:
- serializedVersion: 2
firstByte: 0
indexCount: 6
topology: 0
baseVertex: 0
firstVertex: 0
vertexCount: 6
localAABB:
m_Center: {x: 0, y: 0, z: 1}
m_Extent: {x: 1, y: 1, z: 0}
- serializedVersion: 2
firstByte: 12
indexCount: 6
topology: 0
baseVertex: 0
firstVertex: 6
vertexCount: 6
localAABB:
m_Center: {x: 0, y: 0, z: -1}
m_Extent: {x: 1, y: 1, z: 0}
- serializedVersion: 2
firstByte: 24
indexCount: 6
topology: 0
baseVertex: 0
firstVertex: 12
vertexCount: 6
localAABB:
m_Center: {x: 1, y: 0, z: 0}
m_Extent: {x: 0, y: 1, z: 1}
- serializedVersion: 2
firstByte: 36
indexCount: 6
topology: 0
baseVertex: 0
firstVertex: 18
vertexCount: 6
localAABB:
m_Center: {x: -1, y: 0, z: 0}
m_Extent: {x: 0, y: 1, z: 1}
- serializedVersion: 2
firstByte: 48
indexCount: 6
topology: 0
baseVertex: 0
firstVertex: 24
vertexCount: 6
localAABB:
m_Center: {x: 0, y: 1, z: 0}
m_Extent: {x: 1, y: 0, z: 1}
- serializedVersion: 2
firstByte: 60
indexCount: 6
topology: 0
baseVertex: 0
firstVertex: 30
vertexCount: 6
localAABB:
m_Center: {x: 0, y: -1, z: 0}
m_Extent: {x: 1, y: 0, z: 1}
m_Shapes:
vertices: []
shapes: []
channels: []
fullWeights: []
m_BindPose: []
m_BoneNameHashes:
m_RootBoneNameHash: 0
m_BonesAABB: []
m_VariableBoneCountWeights:
m_Data:
m_MeshCompression: 0
m_IsReadable: 1
m_KeepVertices: 1
m_KeepIndices: 1
m_IndexFormat: 0
m_IndexBuffer: 00000100020003000400050006000700080009000a000b000c000d000e000f0010001100120013001400150016001700180019001a001b001c001d001e001f002000210022002300
m_VertexData:
serializedVersion: 3
m_VertexCount: 36
m_Channels:
- stream: 0
offset: 0
format: 0
dimension: 3
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 12
format: 0
dimension: 2
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 0
format: 0
dimension: 0
- stream: 0
offset: 0
format: 0
dimension: 0
m_DataSize: 720
_typelessdata: 000080bf0000803f0000803f000000000000803f0000803f0000803f0000803f0000803f0000803f0000803f000080bf0000803f0000803f00000000000080bf0000803f0000803f000000000000803f0000803f000080bf0000803f0000803f00000000000080bf000080bf0000803f00000000000000000000803f0000803f000080bf000000000000803f000080bf0000803f000080bf0000803f0000803f000080bf000080bf000080bf0000803f000000000000803f0000803f000080bf000000000000803f000080bf000080bf000080bf0000803f000000000000803f000080bf000080bf00000000000000000000803f0000803f0000803f000000000000803f0000803f0000803f000080bf0000803f0000803f0000803f000080bf000080bf0000803f000000000000803f0000803f0000803f000000000000803f0000803f000080bf000080bf0000803f000000000000803f000080bf0000803f0000000000000000000080bf0000803f000080bf000000000000803f000080bf0000803f0000803f0000803f0000803f000080bf000080bf0000803f0000803f00000000000080bf0000803f000080bf000000000000803f000080bf000080bf0000803f0000803f00000000000080bf000080bf000080bf0000000000000000000080bf0000803f000080bf000000000000803f0000803f0000803f000080bf0000803f0000803f0000803f0000803f0000803f0000803f00000000000080bf0000803f000080bf000000000000803f0000803f0000803f0000803f0000803f00000000000080bf0000803f0000803f0000000000000000000080bf000080bf0000803f000000000000803f0000803f000080bf0000803f0000803f0000803f0000803f000080bf000080bf0000803f00000000000080bf000080bf0000803f000000000000803f0000803f000080bf000080bf0000803f00000000000080bf000080bf000080bf0000000000000000
m_CompressedMesh:
m_Vertices:
m_NumItems: 0
m_Range: 0
m_Start: 0
m_Data:
m_BitSize: 0
m_UV:
m_NumItems: 0
m_Range: 0
m_Start: 0
m_Data:
m_BitSize: 0
m_Normals:
m_NumItems: 0
m_Range: 0
m_Start: 0
m_Data:
m_BitSize: 0
m_Tangents:
m_NumItems: 0
m_Range: 0
m_Start: 0
m_Data:
m_BitSize: 0
m_Weights:
m_NumItems: 0
m_Data:
m_BitSize: 0
m_NormalSigns:
m_NumItems: 0
m_Data:
m_BitSize: 0
m_TangentSigns:
m_NumItems: 0
m_Data:
m_BitSize: 0
m_FloatColors:
m_NumItems: 0
m_Range: 0
m_Start: 0
m_Data:
m_BitSize: 0
m_BoneIndices:
m_NumItems: 0
m_Data:
m_BitSize: 0
m_Triangles:
m_NumItems: 0
m_Data:
m_BitSize: 0
m_UVInfo: 0
m_LocalAABB:
m_Center: {x: 0, y: 0, z: 0}
m_Extent: {x: 1, y: 1, z: 1}
m_MeshUsageFlags: 0
m_CookingOptions: 30
m_BakedConvexCollisionMesh:
m_BakedTriangleCollisionMesh:
m_MeshMetrics[0]: 1
m_MeshMetrics[1]: 1
m_MeshOptimizationFlags: 1
m_StreamData:
serializedVersion: 2
offset: 0
size: 0
path:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: a80925ceebd011741b42509226cefc74
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 4300000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0529e6c5f6dea8c4a8c2835ed7de57cb
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 4300000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,297 @@
using System;
using Unity.Collections.LowLevel.Unsafe;
using UnityEditor;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Sampling;
using UnityEngine.Rendering.UnifiedRayTracing;
using static UnityEngine.PathTracing.Core.World;
namespace UnityEngine.PathTracing.Core
{
internal class Util
{
internal static class ShaderProperties
{
public static readonly int ScramblingTileXSPP = Shader.PropertyToID("_ScramblingTileXSPP");
public static readonly int RankingTileXSPP = Shader.PropertyToID("_RankingTileXSPP");
public static readonly int ScramblingTexture = Shader.PropertyToID("_ScramblingTexture");
public static readonly int OwenScrambledTexture = Shader.PropertyToID("_OwenScrambledTexture");
public static readonly int NumLights = Shader.PropertyToID("g_NumLights");
public static readonly int NumEmissiveMeshes = Shader.PropertyToID("g_NumEmissiveMeshes");
public static readonly int LightList = Shader.PropertyToID("g_LightList");
public static readonly int MainDirectionalLight = Shader.PropertyToID("g_MainDirectionalLight");
public static readonly int HasMainDirectionalLight = Shader.PropertyToID("g_HasMainDirectionalLight");
public static readonly int HasEnvironmentLight = Shader.PropertyToID("g_HasEnvironmentLight");
public static readonly int LightFalloff = Shader.PropertyToID("g_LightFalloff");
public static readonly int LightFalloffLUTRange = Shader.PropertyToID("g_LightFalloffLUTRange");
public static readonly int LightFalloffLUTLength = Shader.PropertyToID("g_LightFalloffLUTLength");
public static readonly int MaterialList = Shader.PropertyToID("g_MaterialList");
public static readonly int AlbedoTextures = Shader.PropertyToID("g_AlbedoTextures");
public static readonly int EmissionTextures = Shader.PropertyToID("g_EmissionTextures");
public static readonly int TransmissionTextures = Shader.PropertyToID("g_TransmissionTextures");
public static readonly int AtlasTexelSize = Shader.PropertyToID("g_AtlasTexelSize");
public static readonly int EnvironmentCdfConditionalResolution = Shader.PropertyToID("_EnvironmentCdfConditionalResolution");
public static readonly int EnvironmentCdfMarginalResolution = Shader.PropertyToID("_EnvironmentCdfMarginalResolution");
public static readonly int EnvironmentCdfConditionalBuffer = Shader.PropertyToID("_EnvironmentCdfConditionalBuffer");
public static readonly int EnvironmentCdfMarginalBuffer = Shader.PropertyToID("_EnvironmentCdfMarginalBuffer");
public static readonly int SceneAccelStruct = Shader.PropertyToID("g_SceneAccelStruct");
public static readonly int EnvTex = Shader.PropertyToID("g_EnvTex");
public static readonly int LightEvaluations = Shader.PropertyToID("g_LightEvaluations");
public static readonly int PathtracerAsGiPreviewMode = Shader.PropertyToID("g_PathtracerAsGiPreviewMode");
public static readonly int RenderedInstances = Shader.PropertyToID("g_RenderedInstances");
public static readonly int PreExpose = Shader.PropertyToID("g_PreExpose");
public static readonly int BounceCount = Shader.PropertyToID("g_BounceCount");
public static readonly int MaxIntensity = Shader.PropertyToID("g_MaxIntensity");
public static readonly int ExposureScale = Shader.PropertyToID("g_ExposureScale");
public static readonly int LightPickingMethod = Shader.PropertyToID("g_LightPickingMethod");
public static readonly int IndirectScale = Shader.PropertyToID("g_IndirectScale");
public static readonly int FrameIndex = Shader.PropertyToID("g_FrameIndex");
public static readonly int EnableSubPixelJittering = Shader.PropertyToID("g_EnableSubPixelJittering");
public static readonly int AlbedoBoost = Shader.PropertyToID("g_AlbedoBoost");
public static readonly int EnvIntensityMultiplier = Shader.PropertyToID("g_EnvIntensityMultiplier");
public static readonly int ExposureTexture = Shader.PropertyToID("_ExposureTexture");
public static readonly int CookieAtlas = Shader.PropertyToID("g_CookieAtlas");
public static readonly int CubemapAtlas = Shader.PropertyToID("g_CubemapAtlas");
}
public static void BindLightBuffers(CommandBuffer cmd, IRayTracingShader shader, World world)
{
Debug.Assert(world.LightListBuffer != null);
shader.SetIntParam(cmd, ShaderProperties.LightPickingMethod, (int)world.lightPickingMethod);
shader.SetIntParam(cmd, ShaderProperties.NumLights, world.LightCount);
shader.SetIntParam(cmd, ShaderProperties.NumEmissiveMeshes, world.MeshLightCount);
shader.SetBufferParam(cmd, ShaderProperties.LightList, world.LightListBuffer);
shader.SetBufferParam(cmd, ShaderProperties.MainDirectionalLight, world.MainDirectionalLightBuffer);
shader.SetIntParam(cmd, ShaderProperties.HasMainDirectionalLight, world.HasMainDirectionalLight ? 1 : 0);
shader.SetIntParam(cmd, ShaderProperties.HasEnvironmentLight, world.HasEnvironmentLight ? 1 : 0);
shader.SetBufferParam(cmd, ShaderProperties.LightFalloff, world.LightFalloffBuffer);
shader.SetBufferParam(cmd, ShaderProperties.LightFalloffLUTRange, world.LightFalloffLUTRangeBuffer);
shader.SetIntParam(cmd, ShaderProperties.LightFalloffLUTLength, (int)world.LightFalloffLUTLength);
shader.SetTextureParam(cmd, ShaderProperties.CookieAtlas, world.GetLightCookieTextures());
shader.SetTextureParam(cmd, ShaderProperties.CubemapAtlas, world.GetLightCubemapTextures());
world.BindLightAccelerationStructure(cmd, shader);
}
internal static void BindMaterials(CommandBuffer cmd, IRayTracingShader shader, World world)
{
shader.SetBufferParam(cmd, ShaderProperties.MaterialList, world.GetMaterialListBuffer());
}
internal static void BindTextures(CommandBuffer cmd, IRayTracingShader shader, World world)
{
var albedoAtlas = world.GetMaterialAlbedoTextures();
var emissionAtlas = world.GetMaterialEmissionTextures();
var transmissionAtlas = world.GetMaterialTransmissionTextures();
shader.SetTextureParam(cmd, ShaderProperties.AlbedoTextures, albedoAtlas);
shader.SetTextureParam(cmd, ShaderProperties.EmissionTextures, emissionAtlas);
shader.SetTextureParam(cmd, ShaderProperties.TransmissionTextures, transmissionAtlas);
if (albedoAtlas != null)
Debug.Assert(albedoAtlas.width == albedoAtlas.height, "Atlas expected to be square");
if (emissionAtlas != null)
Debug.Assert(emissionAtlas.width == albedoAtlas.width && emissionAtlas.height == albedoAtlas.height, "Atlases expected to have same size");
if (transmissionAtlas != null)
Debug.Assert(transmissionAtlas.width == albedoAtlas.width && transmissionAtlas.height == albedoAtlas.height, "Atlases expected to have same size");
int atlasSize = albedoAtlas?.width ?? 1;
float atlasTexelSize = 1.0f / atlasSize;
shader.SetFloatParam(cmd, ShaderProperties.AtlasTexelSize, atlasTexelSize);
}
internal static void BindMaterialsAndTextures(CommandBuffer cmd, IRayTracingShader shader, World world)
{
BindMaterials(cmd, shader, world);
BindTextures(cmd, shader, world);
}
// Helper function to set the skybox CDF resources
internal static void SetEnvSamplingShaderParams(CommandBuffer cmd, IRayTracingShader shader, EnvironmentCDF envCDF)
{
shader.SetIntParam(cmd, ShaderProperties.EnvironmentCdfConditionalResolution, envCDF.ConditionalResolution);
shader.SetIntParam(cmd, ShaderProperties.EnvironmentCdfMarginalResolution, envCDF.MarginalResolution);
shader.SetBufferParam(cmd, ShaderProperties.EnvironmentCdfConditionalBuffer, envCDF.ConditionalBuffer);
shader.SetBufferParam(cmd, ShaderProperties.EnvironmentCdfMarginalBuffer, envCDF.MarginalBuffer);
}
internal static void BindAccelerationStructure(CommandBuffer cmd, IRayTracingShader shader, AccelStructAdapter accel)
{
accel.Bind(cmd, "g_SceneAccelStruct", shader);
}
internal static void BindWorld(CommandBuffer cmd, IRayTracingShader shader, World world)
{
BindAccelerationStructure(cmd, shader, world.GetAccelerationStructure());
BindLightBuffers(cmd, shader, world);
BindMaterialsAndTextures(cmd, shader, world);
var envTex = world.GetEnvironmentTexture(cmd, out EnvironmentCDF envCDF);
shader.SetTextureParam(cmd, Shader.PropertyToID("g_EnvTex"), envTex);
SetEnvSamplingShaderParams(cmd, shader, envCDF);
world.GetAccelerationStructure().BindTerrainResources(cmd, shader);
}
static internal void BindPathTracingInputs(
CommandBuffer cmd,
IRayTracingShader shader,
uint risCandidateCount,
bool preExpose,
int bounces,
float environmentIntensityMultiplier,
RenderedGameObjectsFilter renderedGameObjectsFilter,
SamplingResources samplingResources,
RTHandle emptyTexture)
{
shader.SetIntParam(cmd, ShaderProperties.LightEvaluations, (int)risCandidateCount);
shader.SetIntParam(cmd, ShaderProperties.PathtracerAsGiPreviewMode, 0);
shader.SetIntParam(cmd, ShaderProperties.RenderedInstances, (int)renderedGameObjectsFilter);
shader.SetIntParam(cmd, ShaderProperties.PreExpose, preExpose ? 1 : 0);
shader.SetIntParam(cmd, ShaderProperties.BounceCount, bounces);
shader.SetIntParam(cmd, ShaderProperties.MaxIntensity, int.MaxValue);
shader.SetFloatParam(cmd, ShaderProperties.ExposureScale, 1.0f);
shader.SetFloatParam(cmd, ShaderProperties.IndirectScale, 1.0f);
shader.SetIntParam(cmd, ShaderProperties.FrameIndex, 0);
shader.SetIntParam(cmd, ShaderProperties.EnableSubPixelJittering, 0);
shader.SetFloatParam(cmd, ShaderProperties.AlbedoBoost, 1.0f);
shader.SetFloatParam(cmd, ShaderProperties.EnvIntensityMultiplier, environmentIntensityMultiplier);
SamplingResources.Bind(cmd, samplingResources);
// To avoid shader permutations, we always need to set an exposure texture, even if we don't read it
if (!preExpose)
{
shader.SetTextureParam(cmd, ShaderProperties.ExposureTexture, emptyTexture);
}
}
internal static void SetLightSamplingKeyword(CommandBuffer cmd, IRayTracingShader shader, LightSamplingMode lightSamplingMode)
{
shader.SetKeyword(cmd, shader.CreateLocalKeyword("LIGHT_SAMPLING_UNIFORM"), lightSamplingMode == LightSamplingMode.Uniform);
shader.SetKeyword(cmd, shader.CreateLocalKeyword("LIGHT_SAMPLING_RIS"), lightSamplingMode == LightSamplingMode.RIS);
shader.SetKeyword(cmd, shader.CreateLocalKeyword("LIGHT_SAMPLING_ROUND_ROBIN"), lightSamplingMode == LightSamplingMode.RoundRobin);
}
internal static void SetEmissiveSamplingKeyword(CommandBuffer cmd, IRayTracingShader shader, EmissiveSamplingMode lightSamplingMode)
{
shader.SetKeyword(cmd, shader.CreateLocalKeyword("EMISSIVE_SAMPLING_LIGHT"), lightSamplingMode == EmissiveSamplingMode.LightSampling);
shader.SetKeyword(cmd, shader.CreateLocalKeyword("EMISSIVE_SAMPLING_BRDF"), lightSamplingMode == EmissiveSamplingMode.BRDFSampling);
shader.SetKeyword(cmd, shader.CreateLocalKeyword("EMISSIVE_SAMPLING_MIS"), lightSamplingMode == EmissiveSamplingMode.MIS);
}
internal static void SetTerrainRayMarchingKeyword(CommandBuffer cmd, IRayTracingShader shader, bool enableTerrain)
{
shader.SetKeyword(cmd, shader.CreateLocalKeyword("TERRAIN_RAY_MARCHING_ENABLED"), enableTerrain);
}
internal static RayTracingResources LoadOrCreateRayTracingResources()
{
RayTracingResources resources = new RayTracingResources();
#if UNITY_EDITOR
resources.Load();
#endif
return resources;
}
internal static bool IsStatic(GameObject obj)
{
#if UNITY_EDITOR
// If we are in the editor, access the StaticEditorFlags
int flags = (int)GameObjectUtility.GetStaticEditorFlags(obj);
return (flags & (int)StaticEditorFlags.ContributeGI) != 0;
#else
return obj.isStatic;
#endif
}
internal static bool IsCookieValid(uint cookieTextureIndex)
{
return cookieTextureIndex != UInt32.MaxValue;
}
internal static bool IsPunctualLightType(LightType lightType)
{
return lightType == LightType.Directional || lightType == LightType.Spot || lightType == LightType.Point || lightType == LightType.Box || lightType == LightType.Pyramid;
}
// Our old baker, LightBaker, multiplied intensities of punctual lights by PI. This isn't quite correct, but it was never changed as it would be breaking.
// The 'multiplyPunctualLightIntensityByPI' can be used to mimic that old behavior.
internal static LightDescriptor[] ConvertUnityLightsToLightDescriptors(Light[] lights, bool multiplyPunctualLightIntensityByPI)
{
LightDescriptor[] lightDescriptors = new LightDescriptor[lights.Length];
for (int i = 0; i < lights.Length; i++)
{
Light light = lights[i];
ref LightDescriptor ld = ref lightDescriptors[i];
ld.Type = light.type;
ld.LinearLightColor = GetLinearLightColor(light);
if (multiplyPunctualLightIntensityByPI && IsPunctualLightType(light.type))
ld.LinearLightColor *= Mathf.PI;
ld.Shadows = light.shadows;
ld.Transform = light.transform.localToWorldMatrix;
ld.ColorTemperature = light.colorTemperature;
#if UNITY_EDITOR
ld.LightmapBakeType = light.lightmapBakeType;
#else
ld.LightmapBakeType = LightmapBakeType.Baked;
#endif
ld.AreaSize = light.areaSize;
ld.SpotAngle = light.spotAngle;
ld.InnerSpotAngle = light.innerSpotAngle;
ld.CullingMask = (uint)light.cullingMask;
ld.BounceIntensity = light.bounceIntensity;
ld.Range = light.range;
ld.ShadowMaskChannel = -1;
ld.UseColorTemperature = light.useColorTemperature;
ld.FalloffType = Experimental.GlobalIllumination.FalloffType.InverseSquared; // When we extract lights for the path tracer, we assume inverse squared falloff.
ld.ShadowRadius = Util.IsPunctualLightType(light.type) ? light.shapeRadius : 0.0f;
ld.CookieTexture = light.cookie;
ld.CookieSize = Math.Max(light.cookieSize2D.x, light.cookieSize2D.y);
}
return lightDescriptors;
}
// Copy of internal API from Color.cs
private static Color RGBMultiplied(Color color, float multiplier)
{
return new Color(color.r * multiplier, color.g * multiplier, color.b * multiplier, color.a);
}
internal static Vector3 GetLinearLightColor(Light light)
{
return GetLinearLightColor(light, 1.0f);
}
internal static Vector3 GetLinearLightColor(Light light, float intensityMultiplier)
{
float effectiveIntensity = light.intensity * intensityMultiplier;
Color lightColor = (GraphicsSettings.lightsUseLinearIntensity) ? RGBMultiplied(light.color.linear, effectiveIntensity) : RGBMultiplied(light.color, effectiveIntensity).linear;
lightColor *= light.useColorTemperature ? Mathf.CorrelatedColorTemperatureToRGB(light.colorTemperature) : Color.white;
return new Vector3(lightColor.r, lightColor.g, lightColor.b) * lightColor.a;
}
internal static Material[] GetMaterials(MeshRenderer renderer)
{
int submeshCount = 1;
var meshFilter = renderer.GetComponent<MeshFilter>();
if (meshFilter)
submeshCount = renderer.GetComponent<MeshFilter>().sharedMesh.subMeshCount;
Material[] mats = new Material[submeshCount];
for (int i = 0; i < mats.Length; ++i)
{
if (i < renderer.sharedMaterials.Length && renderer.sharedMaterials[i] != null)
mats[i] = renderer.sharedMaterials[i];
else
mats[i] = null;
}
return mats;
}
internal static ulong EntityIDToUlong(EntityId id)
{
Debug.Assert(UnsafeUtility.SizeOf<EntityId>() == sizeof(ulong), "EntityId should be 8 bytes");
return EntityId.ToULong(id);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 197834254760f5f458d4f0d320728587
@@ -0,0 +1,333 @@
using System;
using UnityEngine.LightTransport;
using UnityEngine.PathTracing.Core;
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
using UnityEngine.Rendering.Sampling;
using UnityEngine.PathTracing.Lightmapping;
namespace UnityEngine.PathTracing.Integration
{
internal class ProbeIntegratorResources
{
internal IRayTracingShader IndirectShader;
internal IRayTracingShader DirectStochasticLightShader;
internal IRayTracingShader DirectDirectionalAndEnviromentShader;
internal IRayTracingShader ValidityShader;
internal IRayTracingShader OcclusionShader;
internal SegmentedReduction GatherKernel;
#if UNITY_EDITOR
public void Load(RayTracingContext context)
{
const string packageFolder = "Packages/com.unity.render-pipelines.core/Runtime/PathTracing/";
IndirectShader = context.LoadRayTracingShader(packageFolder + "Shaders/ProbeIntegrationIndirect.urtshader");
DirectStochasticLightShader = context.LoadRayTracingShader(packageFolder + "Shaders/ProbeIntegrationDirectStochasticLight.urtshader");
DirectDirectionalAndEnviromentShader = context.LoadRayTracingShader(packageFolder + "Shaders/ProbeIntegrationDirectDirectionalAndEnvironment.urtshader");
ValidityShader = context.LoadRayTracingShader(packageFolder + "Shaders/ProbeIntegrationValidity.urtshader");
OcclusionShader = context.LoadRayTracingShader(packageFolder + "Shaders/ProbeIntegrationOcclusion.urtshader");
GatherKernel = new(SegmentedReduction.LoadShader());
}
#endif
}
internal class ProbeIntegrator : IDisposable
{
GraphicsBuffer _positionsBuffer;
SamplingResources _samplingResources;
ProbeIntegratorResources _resourceLibrary;
GraphicsBuffer _traceScratchBuffer;
RTHandle _emptyExposureTexture;
private BakeProgressState _progressState;
// This is a magic number, chosen to be a decent balance between performance and memory usage.
// This will use at maximum (1024 * 1024) * 27 * 4 bytes = 108 MB of VRAM for the expansion buffer when using SH.
const uint maxTotalSamplesPerDispatch = 1024 * 1024;
private static class ShaderProperties
{
public static readonly int Positions = Shader.PropertyToID("g_Positions");
public static readonly int ExpansionOffset = Shader.PropertyToID("g_ExpansionOffset");
public static readonly int PositionsOffset = Shader.PropertyToID("g_PositionsOffset");
public static readonly int RadianceShl2 = Shader.PropertyToID("g_RadianceShl2");
public static readonly int RadianceShl2Offset = Shader.PropertyToID("g_RadianceShl2Offset");
public static readonly int Validity = Shader.PropertyToID("g_Validity");
public static readonly int ValidityOffset = Shader.PropertyToID("g_ValidityOffset");
public static readonly int SampleOffset = Shader.PropertyToID("g_SampleOffset");
public static readonly int SampleCount = Shader.PropertyToID("g_SampleCount");
public static readonly int Occlusion = Shader.PropertyToID("g_Occlusion");
public static readonly int OcclusionOffset = Shader.PropertyToID("g_OcclusionOffset");
public static readonly int PerProbeLightIndices = Shader.PropertyToID("g_PerProbeLightIndices");
public static readonly int PerProbeLightIndicesOffset = Shader.PropertyToID("g_PerProbeLightIndicesOffset");
public static readonly int MaxLightsPerProbe = Shader.PropertyToID("g_MaxLightsPerProbe");
public static readonly int LightIndexInCell = Shader.PropertyToID("g_LightIndexInCell");
}
internal void Prepare(GraphicsBuffer positionsBuffer, ProbeIntegratorResources integrationResources, SamplingResources samplingResources)
{
// First release any previously allocated resources, prepare may be called multiple times
ReleaseExistingAllocations();
_positionsBuffer = positionsBuffer;
_resourceLibrary = integrationResources;
_samplingResources = samplingResources;
_emptyExposureTexture = RTHandles.Alloc(1, 1, enableRandomWrite: true, name: "Empty EV100 Exposure");
}
// We need 2 buffers for expansion and gathering: 1 buffer to store expanded samples, and 1 buffer to use as scratch space for the segmented reduction.
public static void GetScratchBufferSizesInDwords(uint outputStride, uint positionCount, uint sampleCount, out uint expansionBufferSize, out uint reductionBufferSize)
{
uint maxProbesPerDispatch = maxTotalSamplesPerDispatch / sampleCount;
expansionBufferSize = Math.Min(maxTotalSamplesPerDispatch, positionCount * sampleCount) * outputStride;
reductionBufferSize = SegmentedReduction.GetScratchBufferSizeInDwords(sampleCount, outputStride, Math.Min(maxProbesPerDispatch, positionCount));
}
public static void GetRadianceScratchBufferSizesInDwords(uint positionCount, uint sampleCount, out uint expansionBufferSize, out uint reductionBufferSize)
=> GetScratchBufferSizesInDwords(27, positionCount, sampleCount, out expansionBufferSize, out reductionBufferSize);
public static void GetValidityScratchBufferSizesInDwords(uint positionCount, uint sampleCount, out uint expansionBufferSize, out uint reductionBufferSize)
=> GetScratchBufferSizesInDwords(1, positionCount, sampleCount, out expansionBufferSize, out reductionBufferSize);
public static void GetOcclusionScratchBufferSizesInDwords(uint maxLightsPerProbe, uint positionCount, uint sampleCount, out uint expansionBufferSize, out uint reductionBufferSize)
=> GetScratchBufferSizesInDwords(maxLightsPerProbe, positionCount, sampleCount, out expansionBufferSize, out reductionBufferSize);
private void DispatchRadianceEstimationKernel(
CommandBuffer cmd,
IRayTracingShader shader,
World world,
uint positionOffset,
uint positionCount,
uint bounceCount,
uint sampleOffset,
uint sampleCount,
LightSamplingMode lightSamplingMode,
uint risCandidateCount,
uint maxLightsInAnyCell,
float environmentIntensityMultiplier,
GraphicsBuffer radianceShl2,
uint radianceOffset,
GraphicsBuffer expansionBuffer,
GraphicsBuffer reductionBuffer)
{
Debug.Assert(world.GetAccelerationStructure() != null);
// General path tracing parameters
Util.SetLightSamplingKeyword(cmd, shader, lightSamplingMode);
bool preExpose = false;
Util.BindPathTracingInputs(cmd, shader, risCandidateCount, preExpose, (int)bounceCount, environmentIntensityMultiplier, RenderedGameObjectsFilter.OnlyStatic, _samplingResources, _emptyExposureTexture);
Util.BindWorld(cmd, shader, world);
const uint floatsPerSH = 27;
DispatchProbeKernel(cmd, shader, positionOffset, positionCount, sampleOffset, sampleCount, floatsPerSH, ShaderProperties.RadianceShl2, radianceShl2, radianceOffset, expansionBuffer, reductionBuffer,
bounceCount, lightSamplingMode == LightSamplingMode.RoundRobin, maxLightsInAnyCell);
}
private void DispatchProbeKernel(
CommandBuffer cmd,
IRayTracingShader shader,
uint positionOffset,
uint positionCount,
uint sampleOffset,
uint sampleCount,
uint outputStride,
int outputBufferPropertyID,
GraphicsBuffer outputBuffer,
uint outputOffset,
GraphicsBuffer expansionBuffer,
GraphicsBuffer reductionBuffer,
uint bounceCount,
bool roundRobin,
uint maxLightsInAnyCell)
{
// Set constant kernel parameters
shader.SetBufferParam(cmd, ShaderProperties.Positions, _positionsBuffer);
shader.SetIntParam(cmd, ShaderProperties.SampleCount, (int)sampleCount);
shader.SetBufferParam(cmd, outputBufferPropertyID, expansionBuffer);
uint totalSamples = positionCount * sampleCount;
RayTracingHelper.ResizeScratchBufferForTrace(shader, Math.Min(maxTotalSamplesPerDispatch, totalSamples), 1, 1, ref _traceScratchBuffer);
uint maxProbesPerDispatch = Math.Max(maxTotalSamplesPerDispatch / sampleCount, 1);
// This outer loop is only here to handle the case where sampleCount > maxTotalSamplesPerDispatch,
// which is possible, but extremely unlikely. In this case, we just run the entire integation loop multiple times.
for (uint sampleWindow = 0; sampleWindow < sampleCount; sampleWindow += maxTotalSamplesPerDispatch)
{
shader.SetIntParam(cmd, ShaderProperties.SampleOffset, (int)sampleOffset + (int)sampleWindow);
// Loop over chunks of probes, calculate all samples for each chunk.
for (uint probeOffset = 0; probeOffset < positionCount; probeOffset += maxProbesPerDispatch)
{
shader.SetIntParam(cmd, ShaderProperties.ExpansionOffset, (int)probeOffset);
shader.SetIntParam(cmd, ShaderProperties.PositionsOffset, (int)positionOffset + (int)probeOffset);
// Calculate as many samples as possible given the budget
uint probesToDispatch = Math.Min(maxProbesPerDispatch, positionCount - probeOffset);
uint samplesToDispatch = probesToDispatch * sampleCount;
uint loopCount = roundRobin ? maxLightsInAnyCell : 1;
for (int lightIndexInCell = 0; lightIndexInCell < loopCount; ++lightIndexInCell)
{
shader.SetIntParam(cmd, ShaderProperties.LightIndexInCell, lightIndexInCell);
shader.Dispatch(cmd, _traceScratchBuffer, samplesToDispatch, 1, 1);
}
// Perform reduction of each probes samples
_resourceLibrary.GatherKernel.TwoPassSegmentedReduction(
cmd,
sampleCount,
outputStride,
probesToDispatch,
0,
outputOffset + probeOffset,
expansionBuffer,
reductionBuffer,
outputBuffer,
false);
// Chip-off work steps based on the current request
ulong workStepsForThisRequest = CalculateWorkSteps(probesToDispatch, sampleCount, bounceCount);
// We need some resource in order to be able to get an async readback, outputBuffer is as good a candidate as any other
cmd.RequestAsyncReadback(outputBuffer, 1, 0, _ => { _progressState.IncrementCompletedWorkSteps(workStepsForThisRequest); });
GraphicsHelpers.Flush(cmd);
}
}
}
internal static ulong CalculateWorkSteps(ulong probesCount, ulong sampleCount, ulong bounceCount, ulong multiplier = 1) =>
probesCount * sampleCount * (0 == bounceCount ? 1 : bounceCount) * multiplier;
internal static ulong CalculateWorkStepsIndirectRadiance(ulong probesCount, ulong sampleCount, ulong bounceCount) => CalculateWorkSteps(probesCount, sampleCount, bounceCount, 1);
internal static ulong CalculateWorkStepsDirectRadiance(ulong probesCount, ulong sampleCount) => CalculateWorkSteps(probesCount, sampleCount, 0, 2);
internal static ulong CalculateWorkStepsOcclusion(ulong probesCount, ulong sampleCount) => CalculateWorkSteps(probesCount, sampleCount, 0, 1);
internal static ulong CalculateWorkStepsValidity(ulong probesCount, ulong sampleCount) => CalculateWorkSteps(probesCount, sampleCount, 0, 1);
internal void EstimateIndirectRadianceShl2(
CommandBuffer cmd,
World world,
uint positionOffset,
uint positionCount,
uint bounceCount,
uint sampleOffset,
uint sampleCount,
LightSamplingMode lightSamplingMode,
uint risCandidateCount,
uint maxLightsInAnyCell,
EmissiveSamplingMode emissiveSamplingMode,
bool ignoreEnvironment,
GraphicsBuffer radianceShl2,
uint radianceOffset,
GraphicsBuffer expansionBuffer,
GraphicsBuffer reductionBuffer,
bool hasTerrains)
{
// Zero initialize output buffer
const uint floatsPerSH = 27;
cmd.SetBufferData(radianceShl2, new float[positionCount * floatsPerSH]);
float environmentIntensityMultiplier = ignoreEnvironment ? 0.0f : 1.0f;
Util.SetEmissiveSamplingKeyword(cmd, _resourceLibrary.IndirectShader, emissiveSamplingMode);
Util.SetTerrainRayMarchingKeyword(cmd, _resourceLibrary.IndirectShader, hasTerrains);
DispatchRadianceEstimationKernel(cmd, _resourceLibrary.IndirectShader, world, positionOffset, positionCount, bounceCount, sampleOffset, sampleCount, lightSamplingMode, risCandidateCount, maxLightsInAnyCell, environmentIntensityMultiplier, radianceShl2, radianceOffset, expansionBuffer, reductionBuffer);
}
internal void EstimateDirectRadianceShl2(
CommandBuffer cmd,
World world,
uint positionOffset,
uint positionCount,
uint sampleOffset,
uint sampleCount,
LightSamplingMode lightSamplingMode,
uint risCandidateCount,
uint maxLightsInAnyCell,
bool ignoreEnvironment,
GraphicsBuffer radianceShl2,
uint radianceOffset,
GraphicsBuffer expansionBuffer,
GraphicsBuffer reductionBuffer,
bool hasTerrains)
{
// Zero initialize output buffer
const uint floatsPerSH = 27;
cmd.SetBufferData(radianceShl2, new float[positionCount * floatsPerSH]);
float environmentIntensityMultiplier = ignoreEnvironment ? 0.0f : 1.0f;
Util.SetTerrainRayMarchingKeyword(cmd, _resourceLibrary.DirectStochasticLightShader, hasTerrains);
DispatchRadianceEstimationKernel(cmd, _resourceLibrary.DirectStochasticLightShader, world, positionOffset, positionCount, 0, sampleOffset, sampleCount, lightSamplingMode, risCandidateCount, maxLightsInAnyCell, environmentIntensityMultiplier, radianceShl2, radianceOffset, expansionBuffer, reductionBuffer);
Util.SetTerrainRayMarchingKeyword(cmd, _resourceLibrary.DirectDirectionalAndEnviromentShader, hasTerrains);
DispatchRadianceEstimationKernel(cmd, _resourceLibrary.DirectDirectionalAndEnviromentShader, world, positionOffset, positionCount, 0, sampleOffset, sampleCount, LightSamplingMode.Uniform, risCandidateCount, maxLightsInAnyCell, environmentIntensityMultiplier, radianceShl2, radianceOffset, expansionBuffer, reductionBuffer);
}
internal void EstimateValidity(
CommandBuffer cmd,
World world,
uint positionOffset,
uint positionCount,
uint sampleOffset,
uint sampleCount,
GraphicsBuffer validity,
uint validityOffset,
GraphicsBuffer expansionBuffer,
GraphicsBuffer reductionBuffer,
bool hasTerrains)
{
var validityShader = _resourceLibrary.ValidityShader;
// General path tracing parameters
Util.BindAccelerationStructure(cmd, validityShader, world.GetAccelerationStructure());
Util.BindMaterialsAndTextures(cmd, validityShader, world);
SamplingResources.Bind(cmd, _samplingResources);
Util.SetTerrainRayMarchingKeyword(cmd, validityShader, hasTerrains);
DispatchProbeKernel(cmd, validityShader, positionOffset, positionCount, sampleOffset, sampleCount, 1, ShaderProperties.Validity, validity, validityOffset, expansionBuffer, reductionBuffer,
0, false, 0);
}
internal void EstimateLightOcclusion(
CommandBuffer cmd,
World world,
uint positionOffset,
uint positionCount,
uint sampleOffset,
uint sampleCount,
uint maxLightsPerProbe,
GraphicsBuffer perProbeLightIndices,
uint perProbeLightIndicesOffset,
GraphicsBuffer occlusion,
uint occlusionOffset,
GraphicsBuffer expansionBuffer,
GraphicsBuffer reductionBuffer,
bool hasTerrains)
{
var occlusionShader = _resourceLibrary.OcclusionShader;
// General path tracing parameters
Util.BindWorld(cmd, occlusionShader, world);
SamplingResources.Bind(cmd, _samplingResources);
occlusionShader.SetBufferParam(cmd, ShaderProperties.PerProbeLightIndices, perProbeLightIndices);
occlusionShader.SetIntParam(cmd, ShaderProperties.PerProbeLightIndicesOffset, (int)perProbeLightIndicesOffset);
occlusionShader.SetIntParam(cmd, ShaderProperties.MaxLightsPerProbe, (int)maxLightsPerProbe);
Util.SetTerrainRayMarchingKeyword(cmd, occlusionShader, hasTerrains);
DispatchProbeKernel(cmd, occlusionShader, positionOffset, positionCount, sampleOffset, sampleCount, maxLightsPerProbe, ShaderProperties.Occlusion, occlusion, occlusionOffset, expansionBuffer, reductionBuffer,
0, false, 0);
}
private void ReleaseExistingAllocations()
{
_emptyExposureTexture?.Release();
_traceScratchBuffer?.Dispose();
_traceScratchBuffer = null;
_samplingResources = null;
}
public void Dispose()
{
ReleaseExistingAllocations();
}
public void SetProgressReporter(BakeProgressState progressState) => _progressState = progressState;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fb60b03cc4272524e90a04de8c72b9e1
@@ -0,0 +1,117 @@
using UnityEngine.Rendering;
namespace UnityEngine.PathTracing.PostProcessing
{
internal class ProbePostProcessor
{
private ComputeShader _computeShader;
private int _convolveRadianceToIrradianceKernel;
private int _convertToUnityFormatKernel;
private int _addSphericalHarmonicsL2Kernel;
private int _scaleSphericalHarmonicsL2Kernel;
private int _windowSphericalHarmonicsL2Kernel;
/// <summary>
/// Prepares the probe post processor for use.
/// Expects to be given the "ProbePostProcessing.compute" shader.
/// </summary>
/// <param name="computeShader">The compute shader containing post processing kernels. Should be the "ProbePostProcessing.compute" shader.</param>
public void Prepare(ComputeShader computeShader)
{
_computeShader = computeShader;
Debug.Assert(_computeShader != null);
_convolveRadianceToIrradianceKernel = _computeShader.FindKernel("ConvolveRadianceToIrradiance");
Debug.Assert(_convolveRadianceToIrradianceKernel != -1);
_convertToUnityFormatKernel = _computeShader.FindKernel("ConvertToUnityFormat");
Debug.Assert(_convertToUnityFormatKernel != -1);
_addSphericalHarmonicsL2Kernel = _computeShader.FindKernel("AddSphericalHarmonicsL2");
Debug.Assert(_addSphericalHarmonicsL2Kernel != -1);
_scaleSphericalHarmonicsL2Kernel = _computeShader.FindKernel("ScaleSphericalHarmonicsL2");
Debug.Assert(_scaleSphericalHarmonicsL2Kernel != -1);
_windowSphericalHarmonicsL2Kernel = _computeShader.FindKernel("WindowSphericalHarmonicsL2");
Debug.Assert(_windowSphericalHarmonicsL2Kernel != -1);
}
public void ConvolveRadianceToIrradiance(CommandBuffer cmd, GraphicsBuffer inRadianceBuffer, GraphicsBuffer outIrradianceBuffer, uint inputOffset, uint outputOffset, uint probeCount)
{
Debug.Assert(_computeShader != null);
Debug.Assert(inRadianceBuffer.count == outIrradianceBuffer.count);
Debug.Assert(inRadianceBuffer.stride == sizeof(float));
cmd.SetComputeBufferParam(_computeShader, _convolveRadianceToIrradianceKernel, Shader.PropertyToID("g_PrimaryInputShl2"), inRadianceBuffer);
cmd.SetComputeBufferParam(_computeShader, _convolveRadianceToIrradianceKernel, Shader.PropertyToID("g_OutputShl2"), outIrradianceBuffer);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_PrimaryInputOffset"), (int)inputOffset);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_OutputOffset"), (int)outputOffset);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_ProbeCount"), (int)probeCount);
_computeShader.GetKernelThreadGroupSizes(_convolveRadianceToIrradianceKernel, out uint threadGroupsX, out uint _, out uint _);
cmd.DispatchCompute(_computeShader, _convolveRadianceToIrradianceKernel, Mathf.CeilToInt(probeCount / (float)threadGroupsX), 1, 1);
}
public void ConvertToUnityFormat(CommandBuffer cmd, GraphicsBuffer inIrradianceBuffer, GraphicsBuffer outIrradianceBuffer, uint inputOffset, uint outputOffset, uint probeCount)
{
Debug.Assert(_computeShader != null);
Debug.Assert(inIrradianceBuffer.count == outIrradianceBuffer.count);
Debug.Assert(inIrradianceBuffer.stride == sizeof(float));
cmd.SetComputeBufferParam(_computeShader, _convertToUnityFormatKernel, Shader.PropertyToID("g_PrimaryInputShl2"), inIrradianceBuffer);
cmd.SetComputeBufferParam(_computeShader, _convertToUnityFormatKernel, Shader.PropertyToID("g_OutputShl2"), outIrradianceBuffer);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_PrimaryInputOffset"), (int)inputOffset);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_OutputOffset"), (int)outputOffset);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_ProbeCount"), (int)probeCount);
_computeShader.GetKernelThreadGroupSizes(_convertToUnityFormatKernel, out uint threadGroupsX, out _, out _);
cmd.DispatchCompute(_computeShader, _convertToUnityFormatKernel, Mathf.CeilToInt(probeCount / (float)threadGroupsX), 1, 1);
}
internal void AddSphericalHarmonicsL2(CommandBuffer cmd, GraphicsBuffer inA, GraphicsBuffer inB, GraphicsBuffer outSum, uint inputOffsetA, uint inputOffsetB, uint outputOffset, uint probeCount)
{
Debug.Assert(_computeShader != null);
Debug.Assert(inA.count == inB.count);
Debug.Assert(inA.count == outSum.count);
Debug.Assert(inA.stride == sizeof(float));
cmd.SetComputeBufferParam(_computeShader, _addSphericalHarmonicsL2Kernel, Shader.PropertyToID("g_PrimaryInputShl2"), inA);
cmd.SetComputeBufferParam(_computeShader, _addSphericalHarmonicsL2Kernel, Shader.PropertyToID("g_SecondaryInputShl2"), inB);
cmd.SetComputeBufferParam(_computeShader, _addSphericalHarmonicsL2Kernel, Shader.PropertyToID("g_OutputShl2"), outSum);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_PrimaryInputOffset"), (int)inputOffsetA);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_SecondaryInputOffset"), (int)inputOffsetB);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_OutputOffset"), (int)outputOffset);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_ProbeCount"), (int)probeCount);
_computeShader.GetKernelThreadGroupSizes(_addSphericalHarmonicsL2Kernel, out uint threadGroupsX, out _, out _);
cmd.DispatchCompute(_computeShader, _addSphericalHarmonicsL2Kernel, Mathf.CeilToInt(probeCount / (float)threadGroupsX), 1, 1);
}
internal void ScaleSphericalHarmonicsL2(CommandBuffer cmd, GraphicsBuffer input, GraphicsBuffer outScaled, uint inputOffset, uint outputOffset, uint probeCount, float scale)
{
Debug.Assert(_computeShader != null);
Debug.Assert(input.stride == sizeof(float));
cmd.SetComputeBufferParam(_computeShader, _scaleSphericalHarmonicsL2Kernel, Shader.PropertyToID("g_PrimaryInputShl2"), input);
cmd.SetComputeBufferParam(_computeShader, _scaleSphericalHarmonicsL2Kernel, Shader.PropertyToID("g_OutputShl2"), outScaled);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_PrimaryInputOffset"), (int)inputOffset);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_OutputOffset"), (int)outputOffset);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_ProbeCount"), (int)probeCount);
cmd.SetComputeFloatParam(_computeShader, Shader.PropertyToID("g_Scale"), scale);
_computeShader.GetKernelThreadGroupSizes(_scaleSphericalHarmonicsL2Kernel, out uint threadGroupsX, out _, out _);
cmd.DispatchCompute(_computeShader, _scaleSphericalHarmonicsL2Kernel, Mathf.CeilToInt(probeCount / (float)threadGroupsX), 1, 1);
}
internal void WindowSphericalHarmonicsL2(CommandBuffer cmd, GraphicsBuffer input, GraphicsBuffer outWindowed, uint inputOffset, uint outputOffset, uint probeCount)
{
Debug.Assert(_computeShader != null);
Debug.Assert(input.stride == sizeof(float));
cmd.SetComputeBufferParam(_computeShader, _windowSphericalHarmonicsL2Kernel, Shader.PropertyToID("g_PrimaryInputShl2"), input);
cmd.SetComputeBufferParam(_computeShader, _windowSphericalHarmonicsL2Kernel, Shader.PropertyToID("g_OutputShl2"), outWindowed);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_PrimaryInputOffset"), (int)inputOffset);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_OutputOffset"), (int)outputOffset);
cmd.SetComputeIntParam(_computeShader, Shader.PropertyToID("g_ProbeCount"), (int)probeCount);
_computeShader.GetKernelThreadGroupSizes(_windowSphericalHarmonicsL2Kernel, out uint threadGroupsX, out _, out _);
cmd.DispatchCompute(_computeShader, _windowSphericalHarmonicsL2Kernel, Mathf.CeilToInt(probeCount / (float)threadGroupsX), 1, 1);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2f16318919ba4cf4686265a429896fd9
@@ -0,0 +1,145 @@
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.UnifiedRayTracing;
namespace UnityEngine.PathTracing.Core
{
internal class SegmentedReduction
{
private readonly ComputeShader _segmentedReductionShader;
private readonly int _reductionKernel;
private readonly uint _threadGroupSize;
private static class ShaderProperties
{
public static readonly int SegmentWidth = Shader.PropertyToID("g_SegmentWidth");
public static readonly int SegmentStride = Shader.PropertyToID("g_SegmentStride");
public static readonly int SegmentCount = Shader.PropertyToID("g_SegmentCount");
public static readonly int InputOffset = Shader.PropertyToID("g_InputOffset");
public static readonly int OutputOffset = Shader.PropertyToID("g_OutputOffset");
public static readonly int OverwriteOutput = Shader.PropertyToID("g_OverwriteOutput");
public static readonly int TruncateInterval = Shader.PropertyToID("g_TruncateInterval");
public static readonly int TruncatedSegmentWidth = Shader.PropertyToID("g_TruncatedSegmentWidth");
public static readonly int InputFloatBuffer = Shader.PropertyToID("g_InputFloatBuffer");
public static readonly int OutputFloatBuffer = Shader.PropertyToID("g_OutputFloatBuffer");
}
public SegmentedReduction(ComputeShader segmentedReductionShader)
{
_segmentedReductionShader = segmentedReductionShader;
_reductionKernel = _segmentedReductionShader.FindKernel("SegmentedReductionFloat");
_segmentedReductionShader.GetKernelThreadGroupSizes(_reductionKernel, out _threadGroupSize, out _, out _);
}
#if UNITY_EDITOR
public static ComputeShader LoadShader()
{
return UnityEditor.AssetDatabase.LoadAssetAtPath<ComputeShader>("Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/SegmentedReduction.compute");
}
#endif
private static void CalculateParametersForTwoPassReduction(
uint segmentWidth,
uint segmentCount,
out uint firstPassSegmentCount,
out uint firstPassSegmentWidth,
out uint truncateInterval,
out uint truncatedSegmentWidth,
out uint secondPassSegmentCount,
out uint secondPassSegmentWidth)
{
// Split each segments into a number of segments with size close to sqrt(segmentWidth).
firstPassSegmentWidth = (uint)Mathf.Floor(Mathf.Sqrt(segmentWidth));
// Splitting may result in a truncated segment at the end of each original segment.
// Calculate how often this happen, how wide the truncated segment will be.
truncateInterval = GraphicsHelpers.DivUp(segmentWidth, firstPassSegmentWidth);
truncatedSegmentWidth = segmentWidth % firstPassSegmentWidth;
// Calculate total number of segments after splitting.
firstPassSegmentCount = truncateInterval * segmentCount;
// The second pass reduces the output of the first pass.
// The first pass will produce segmentCount segments of width truncateInterval.
secondPassSegmentCount = segmentCount;
secondPassSegmentWidth = truncateInterval;
}
public static uint GetScratchBufferSizeInDwords(uint segmentWidth, uint segmentStride, uint segmentCount)
{
CalculateParametersForTwoPassReduction(segmentWidth, segmentCount, out uint firstPassSegmentCount, out _, out _, out _, out _, out _);
return firstPassSegmentCount * segmentStride;
}
// Performs segmented reduction in 2 passes, each doing roughly sqrt(N) reductions.
// This is almost always faster than single pass reduction, and should be preferred over it.
public void TwoPassSegmentedReduction(
CommandBuffer cmd,
uint segmentWidth,
uint segmentStride,
uint segmentCount,
uint inputOffset,
uint outputOffset,
GraphicsBuffer inputBuffer,
GraphicsBuffer scratchBuffer,
GraphicsBuffer outputBuffer,
bool overwriteOutput)
{
CalculateParametersForTwoPassReduction(
segmentWidth,
segmentCount,
out uint firstPassSegmentCount,
out uint firstPassSegmentWidth,
out uint truncateInterval,
out uint truncatedSegmentWidth,
out uint secondPassSegmentCount,
out uint secondPassSegmentWidth);
DispatchReductionKernel(cmd, firstPassSegmentWidth, segmentStride, firstPassSegmentCount, inputOffset, 0, inputBuffer, scratchBuffer, true, truncateInterval, truncatedSegmentWidth);
DispatchReductionKernel(cmd, secondPassSegmentWidth, segmentStride, secondPassSegmentCount, inputOffset, outputOffset, scratchBuffer, outputBuffer, overwriteOutput, 0, 0);
}
// Performs segmented reduction in a single pass. This is slower than the 2 pass
// variant in most cases, except for the case where each individual reduction is very small.
// This function is mostly intended for small problem sizes and for debugging.
public void SinglePassSegmentedReduction(
CommandBuffer cmd,
uint segmentWidth,
uint segmentStride,
uint segmentCount,
uint inputOffset,
uint outputOffset,
GraphicsBuffer inputBuffer,
GraphicsBuffer outputBuffer,
bool overwriteOutput)
{
DispatchReductionKernel(cmd, segmentWidth, segmentStride, segmentCount, inputOffset, outputOffset, inputBuffer, outputBuffer, overwriteOutput, 0, 0);
}
private void DispatchReductionKernel(
CommandBuffer cmd,
uint segmentWidth,
uint segmentStride,
uint segmentCount,
uint inputOffset,
uint outputOffset,
GraphicsBuffer inputBuffer,
GraphicsBuffer outputBuffer,
bool overwriteOutput,
uint truncateInterval,
uint truncatedSegmentWidth)
{
cmd.SetComputeIntParam(_segmentedReductionShader, ShaderProperties.SegmentWidth, (int)segmentWidth);
cmd.SetComputeIntParam(_segmentedReductionShader, ShaderProperties.SegmentStride, (int)segmentStride);
cmd.SetComputeIntParam(_segmentedReductionShader, ShaderProperties.SegmentCount, (int)segmentCount);
cmd.SetComputeIntParam(_segmentedReductionShader, ShaderProperties.InputOffset, (int)inputOffset);
cmd.SetComputeIntParam(_segmentedReductionShader, ShaderProperties.OutputOffset, (int)outputOffset);
cmd.SetComputeIntParam(_segmentedReductionShader, ShaderProperties.OverwriteOutput, overwriteOutput ? 1 : 0);
cmd.SetComputeIntParam(_segmentedReductionShader, ShaderProperties.TruncateInterval, (int)truncateInterval);
cmd.SetComputeIntParam(_segmentedReductionShader, ShaderProperties.TruncatedSegmentWidth, (int)truncatedSegmentWidth);
cmd.SetComputeBufferParam(_segmentedReductionShader, _reductionKernel, ShaderProperties.InputFloatBuffer, inputBuffer);
cmd.SetComputeBufferParam(_segmentedReductionShader, _reductionKernel, ShaderProperties.OutputFloatBuffer, outputBuffer);
cmd.DispatchCompute(_segmentedReductionShader, _reductionKernel, (int)GraphicsHelpers.DivUp(segmentCount, _threadGroupSize), 1, 1);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2502941332b91fa4a8a2804e7ecb19ac
@@ -0,0 +1,24 @@
namespace UnityEngine.PathTracing.Core
{
internal static class ShaderProperties
{
public static readonly int LightGrid = Shader.PropertyToID("g_LightGrid");
public static readonly int LightGridCellsData = Shader.PropertyToID("g_LightGridCellsData");
public static readonly int GridDimX = Shader.PropertyToID("g_GridDimX");
public static readonly int GridDimY = Shader.PropertyToID("g_GridDimY");
public static readonly int GridDimZ = Shader.PropertyToID("g_GridDimZ");
public static readonly int NumLights = Shader.PropertyToID("g_NumLights");
public static readonly int GridMin = Shader.PropertyToID("g_GridMin");
public static readonly int GridSize = Shader.PropertyToID("g_GridSize");
public static readonly int CellSize = Shader.PropertyToID("g_CellSize");
public static readonly int InvCellSize = Shader.PropertyToID("g_InvCellSize");
public static readonly int TotalReservoirCount = Shader.PropertyToID("g_TotalLightsInGridCount");
public static readonly int BuildPass = Shader.PropertyToID("g_BuildPass");
public static readonly int NumCandidates = Shader.PropertyToID("g_NumCandidates");
public static readonly int NumReservoirs = Shader.PropertyToID("g_NumReservoirs");
public static readonly int MaxLightsPerCell = Shader.PropertyToID("g_MaxLightsPerCell");
public static readonly int LightList = Shader.PropertyToID("g_LightList");
public static readonly int NumEmissiveMeshes = Shader.PropertyToID("g_NumEmissiveMeshes");
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: da922357540ba0d44ba6435efbaa8da4
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 7cd12a213ac4f5f4d917aa18d3a538ce
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,27 @@
#pragma only_renderers d3d11 vulkan metal glcore ps5 switch2
#define GROUP_SIZE_X 8
#define GROUP_SIZE_Y 8
Texture2D<float4> g_Source;
RWTexture2D<float4> g_Destination;
SamplerState sampler_g_Source;
uint g_TextureWidth;
uint g_TextureHeight;
// Projects (blits) a face of a cubemap on a 2D texture
#pragma kernel BlitGrayScaleCookie
[numthreads(GROUP_SIZE_X, GROUP_SIZE_Y, 1)]
void BlitGrayScaleCookie(in uint2 gidx : SV_DispatchThreadID)
{
if (gidx.x >= g_TextureWidth || gidx.y >= g_TextureHeight)
return;
float2 texCoord = float2((gidx.x + 0.5f) / g_TextureWidth, (gidx.y + 0.5f) / g_TextureHeight);
float c = g_Source.SampleLevel(sampler_g_Source, texCoord, 0).w;
g_Destination[gidx] = float4(c, c, c, 1);
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 557fa399e33bf7647bda5697c5c158df
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,67 @@
#pragma only_renderers d3d11 vulkan metal glcore ps5 switch2
#define GROUP_SIZE_X 8
#define GROUP_SIZE_Y 8
#pragma multi_compile _ GRAYSCALE_BLIT
TextureCube<float4> g_Source;
RWTexture2D<float4> g_Destination;
SamplerState sampler_g_Source;
int g_TextureSize;
int g_Face;
#define PositiveX 0
#define NegativeX 1
#define PositiveY 2
#define NegativeY 3
#define PositiveZ 4
#define NegativeZ 5
// Projects (blits) a face of a cubemap on a 2D texture
#pragma kernel BlitCubemap
[numthreads(GROUP_SIZE_X, GROUP_SIZE_Y, 1)]
void BlitCubemap(in uint2 gidx: SV_DispatchThreadID)
{
if (gidx.x >= uint(g_TextureSize) || gidx.y >= uint(g_TextureSize))
return;
float u = (gidx.x + 0.5f) / g_TextureSize;
float v = (gidx.y + 0.5f) / g_TextureSize;
u = 2 * u - 1.0f;
v = 1.0f - 2 * v;
float3 texCoord = 0;
switch (g_Face)
{
case PositiveX:
texCoord = float3(1, v, -u);
break;
case NegativeX:
texCoord = float3(-1, v, u);
break;
case PositiveY:
texCoord = float3(u, 1, -v);
break;
case NegativeY:
texCoord = float3(u, -1, v);
break;
case PositiveZ:
texCoord = float3(u, v, 1);
break;
case NegativeZ:
texCoord = float3(-u, v, -1);
break;
}
float4 c = g_Source.SampleLevel(sampler_g_Source, texCoord, 0);
#if defined(GRAYSCALE_BLIT)
g_Destination[gidx] = float4(c.w, c.w, c.w, 1);
#else
g_Destination[gidx] = float4(c.r, c.g, c.b, 1);
#endif
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 5a992812cb320d146a66cc600200cce7
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,296 @@
#pragma only_renderers d3d11 vulkan metal glcore
#pragma multi_compile _ SPARSE_GRID
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/Common.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/GeometricTools.hlsl"
#include "Packages/com.unity.render-pipelines.core/ShaderLibrary/CommonLighting.hlsl"
#include "PathTracingCommon.hlsl"
#include "PathTracingRandom.hlsl"
#include "PathTracingLightGrid.hlsl"
#if defined(SHADER_API_MOBILE) && defined(SHADER_API_METAL)
// On pre A9 (iPhone 6S and earlier) devices, the max groupshared size is 16352. So to avoid exceeding that limit, we reduce the group size.
#define GROUP_SIZE_X 4
#define GROUP_SIZE_Y 4
#define GROUP_SIZE_Z 2
#else
#define GROUP_SIZE_X 4
#define GROUP_SIZE_Y 4
#define GROUP_SIZE_Z 4
#endif
#define MAX_RESERVOIRS_PER_VOXEL 64
groupshared float s_SampleCount[GROUP_SIZE_X * GROUP_SIZE_Y * GROUP_SIZE_Z * MAX_RESERVOIRS_PER_VOXEL];
#ifndef PI
#define PI 3.14159265358979323846f
#endif
// Input parameters and lighting state
StructuredBuffer<PTLight> g_LightList;
uint g_NumLights;
uint g_MaxLightsPerCell;
uint g_NumCandidates;
uint g_BuildPass;
// Output indices and grid
RWStructuredBuffer<ThinReservoir> g_LightGridCellsData;
RWStructuredBuffer<uint2> g_LightGrid;
RWStructuredBuffer<uint> g_TotalLightsInGridCount;
float4 PlaneFromNormalAndPosition(float3 normal, float3 pos)
{
return float4(normal, -dot(normal, pos));
}
void GetBoxLightFrustumPlanes(float3 lightOrigin, float3 lightBasisX, float3 lightBasisY, float3 lightBasisZ, float halfSizeX, float halfSizeY, float range, out float4 frustumPlanes[6])
{
// sides along X
frustumPlanes[0] = PlaneFromNormalAndPosition(-lightBasisX, lightOrigin + lightBasisX * halfSizeX);
frustumPlanes[1] = PlaneFromNormalAndPosition(lightBasisX, lightOrigin - lightBasisX * halfSizeX);
// sides along Y
frustumPlanes[2] = PlaneFromNormalAndPosition(-lightBasisY, lightOrigin + lightBasisY * halfSizeY);
frustumPlanes[3] = PlaneFromNormalAndPosition(lightBasisY, lightOrigin - lightBasisY * halfSizeY);
// sides along Z
frustumPlanes[4] = PlaneFromNormalAndPosition(lightBasisZ, lightOrigin);
frustumPlanes[5] = PlaneFromNormalAndPosition(-lightBasisZ, lightOrigin + lightBasisZ * range);
}
void GetPyramidLightFrustumPlanes(float3 lightOrigin, float3 lightBasisX, float3 lightBasisY, float3 lightBasisZ, float halfSizeX, float halfSizeY, float range, out float4 frustumPlanes[6])
{
float2 nX = normalize(float2(1.0, halfSizeX));
float2 nY = normalize(float2(1.0, halfSizeY));
// the plane's normals point towards the interior of the frustum
// Pyramid sides along X
frustumPlanes[0] = PlaneFromNormalAndPosition(nX.y * lightBasisZ + nX.x * lightBasisX, lightOrigin);
frustumPlanes[1] = PlaneFromNormalAndPosition(nX.y * lightBasisZ - nX.x * lightBasisX, lightOrigin);
// Pyramid sides along Y
frustumPlanes[2] = PlaneFromNormalAndPosition(nY.y * lightBasisZ + nY.x * lightBasisY, lightOrigin);
frustumPlanes[3] = PlaneFromNormalAndPosition(nY.y * lightBasisZ - nY.x * lightBasisY, lightOrigin);
// Pyramid near and far planes
frustumPlanes[4] = PlaneFromNormalAndPosition(lightBasisZ, lightOrigin);
frustumPlanes[5] = PlaneFromNormalAndPosition(-lightBasisZ, lightOrigin + lightBasisZ * range);
}
// Estimate the maximum emission in a voxel / Target function for RIS
float3 EstimateEmission(PTLight light, float3 worldPosition)
{
// Evaluate the light's distance attenuation
float distAttenuation = 1.0;
if (light.type != DIRECTIONAL_LIGHT && light.type != ENVIRONMENT_LIGHT && light.type != BOX_LIGHT && light.type != EMISSIVE_MESH)
{
// First compute the point light attenuation
float d = length(light.position - worldPosition);
// To be conservative on the attenuation, we substruct the cell radius of the grid.
// We also substract the radius (of the bounding sphere) of the light
float r = 0.0f;
if (light.type == DISC_LIGHT)
r = light.width;
if (light.type == RECTANGULAR_LIGHT)
r = 0.5f * sqrt(light.width * light.width + light.height * light.height);
// To be conservative on the attenuation, we substruct the cell radius of the grid
d = max(0.01f, d - GetCellSize() - r);
distAttenuation = SmoothWindowedDistanceAttenuation(d * d, rcp(d), light.attenuation.x, light.attenuation.y);
}
// Evaluate the lights's emission + culling by light's bounding shape
const float Deg2Rad = PI * 2.0f / 360.0f;
float3 emission = float3(1.0f, 1.0f, 1.0f);
if (light.type == DIRECTIONAL_LIGHT || light.type == POINT_LIGHT)
{
emission = light.intensity;
}
else if (light.type == ENVIRONMENT_LIGHT || light.type == EMISSIVE_MESH)
{
emission = float3(1.0f, 1.0f, 1.0f);
}
else if (light.type == BOX_LIGHT) // Frustum vs cell AABB culling
{
float4 frustumPlanes[6];
GetBoxLightFrustumPlanes(light.position, light.right, light.up, light.forward, 0.5 * light.width, 0.5 * light.height, light.range, frustumPlanes);
float3 aabbCenter = worldPosition;
float3 aabbExtent = 0.5 * GetCellSize();
bool intersection = IntersectFrustumPlanesAABB(frustumPlanes, aabbCenter, aabbExtent);
emission = intersection ? light.intensity : 0.0f;
}
else if (light.type == PYRAMID_LIGHT) // Frustum vs cell AABB culling
{
float4 frustumPlanes[6];
GetPyramidLightFrustumPlanes(light.position, light.right, light.up, light.forward, 0.5 * light.width, 0.5 * light.height, light.range, frustumPlanes);
float3 aabbCenter = worldPosition;
float3 aabbExtent = 0.5 * GetCellSize();
bool intersection = IntersectFrustumPlanesAABB(frustumPlanes, aabbCenter, aabbExtent);
emission = intersection ? light.intensity : 0.0f;
}
else // SPOT_LIGHT || RECTANGULAR_LIGHT || DISC_LIGHT (cone vs cell's bounding sphere culling)
{
float coneAngle = (light.type == SPOT_LIGHT) ? 0.5 * light.spotAngle.x * Deg2Rad : 0.5f * 180.0f * Deg2Rad;
float4 bSphere = float4(worldPosition, 0.5 * GetCellSize());
bool intersection = IntersectSphericalConeWithSphere(light.position, light.forward, light.range, cos(coneAngle), sin(coneAngle), bSphere);
emission = intersection ? light.intensity : 0.0f;
}
return distAttenuation * emission;
}
float GetLightTargetFunction(float3 pos, uint lightIndex)
{
PTLight light = g_LightList[lightIndex];
float3 emission = EstimateEmission(light, pos);
return Luminance(emission);
}
#pragma kernel BuildConservativeLightGrid
[numthreads(GROUP_SIZE_X, GROUP_SIZE_Y, GROUP_SIZE_Z)]
void BuildConservativeLightGrid(in uint3 gidx : SV_DispatchThreadID, in uint threadIndex : SV_GroupIndex)
{
if (gidx.x >= g_GridDimX || gidx.y >= g_GridDimY || gidx.z >= g_GridDimZ)
return;
uint cellIndex = GetCellIndex(gidx);
PathTracingSampler rngState;
rngState.Init(gidx.xy, gidx.z);
float3 pos = GetCellPosition(gidx);
if (g_BuildPass == 0) // compute number of lights overlapping current cell
{
uint lightCount = 0;
for (uint lightIndex = 0; lightIndex < g_NumLights; ++lightIndex)
{
if (GetLightTargetFunction(pos, lightIndex) > 0)
lightCount++;
}
uint unusedOldValue;
InterlockedAdd(g_TotalLightsInGridCount[0], lightCount, unusedOldValue);
g_LightGrid[cellIndex] = uint2(0, lightCount);
}
else // write lights overlapping current cell to g_LightGridCellsData
{
#if SPARSE_GRID
uint lightCount = g_LightGrid[cellIndex].y;
uint firstCellLightDataIndex;
InterlockedAdd(g_TotalLightsInGridCount[0], lightCount, firstCellLightDataIndex);
g_LightGrid[cellIndex].x = firstCellLightDataIndex;
uint cellDataStart = firstCellLightDataIndex;
#else
uint cellDataStart = cellIndex * g_MaxLightsPerCell;
#endif
uint lightDataIndex = 0;
for (uint lightIndex = 0; lightIndex < g_NumLights; ++lightIndex)
{
// Conservative culling mode: if there is a contribution, save the light index / reservoir
// This should be used when the number of candidates equals the number of ligths
if (GetLightTargetFunction(pos, lightIndex) > 0)
{
ThinReservoir reservoir = { lightIndex, 1.0f};
g_LightGridCellsData[cellDataStart + lightDataIndex] = reservoir;
lightDataIndex++;
}
#if !(SPARSE_GRID)
if (lightDataIndex >= g_MaxLightsPerCell)
break;
#endif
}
#if !(SPARSE_GRID)
uint lightCount = lightDataIndex;
g_LightGrid[cellIndex] = uint2(cellDataStart, lightCount);
#endif
}
}
void UpdateReservoir(int reservoirIndex, int lightIndex, float targetFunction, float r)
{
float candidateRISWeight = targetFunction;
ThinReservoir reservoir = g_LightGridCellsData[reservoirIndex];
float totalWeights = reservoir.weight + candidateRISWeight;
if (r * totalWeights < candidateRISWeight)
{
reservoir.lightIndex = lightIndex;
reservoir.weight = totalWeights;
}
g_LightGridCellsData[reservoirIndex] = reservoir;
}
void NormalizeReservoirWeights(uint offset, float3 pos, uint numReservoirs, uint threadIndex)
{
for (uint i = 0; i < numReservoirs; ++i)
{
ThinReservoir reservoir = g_LightGridCellsData[offset + i];
float numSamples = s_SampleCount[threadIndex * MAX_RESERVOIRS_PER_VOXEL + i];
float sampleTargetDensity = GetLightTargetFunction(pos, reservoir.lightIndex);
float risSampleWeight = (reservoir.weight / numSamples) / sampleTargetDensity;
reservoir.weight = risSampleWeight;
g_LightGridCellsData[offset + i] = reservoir;
}
}
#pragma kernel BuildRegirLightGrid
[numthreads(GROUP_SIZE_X, GROUP_SIZE_Y, GROUP_SIZE_Z)]
void BuildRegirLightGrid(in uint3 gidx : SV_DispatchThreadID, in uint threadIndex : SV_GroupIndex)
{
if (gidx.x >= g_GridDimX || gidx.y >= g_GridDimY || gidx.z >= g_GridDimZ)
return;
uint cellIndex = GetCellIndex(gidx);
PathTracingSampler rngState;
rngState.Init(gidx.xy, gidx.z);
float3 pos = GetCellPosition(gidx);
uint reservoirIndex = 0;
for (uint lightIndex = 0; lightIndex < g_NumCandidates; ++lightIndex)
{
float targetFunction = GetLightTargetFunction(pos, lightIndex);
// Conservative culling mode: if there is a contribution, save the light index / reservoir
// This should be used when the number of candidates equals the number of ligths
if (targetFunction > 0)
{
ThinReservoir reservoir = { lightIndex, targetFunction };
if (reservoirIndex < g_NumReservoirs)
{
g_LightGridCellsData[cellIndex * g_NumReservoirs + reservoirIndex] = reservoir;
s_SampleCount[threadIndex * MAX_RESERVOIRS_PER_VOXEL + reservoirIndex] = 1.0f;
reservoirIndex++;
}
else
{
// When we run out of free reservoirs, we rely on reservoir sampling to update an existing one
// The reservoirs are stratified based on the lightIndex % g_NumReservoirs
uint reservoirLocalIndex = lightIndex % max(g_NumReservoirs, 1);
uint reservoirGlobalIndex = cellIndex * g_NumReservoirs + reservoirLocalIndex;
float rnd = rngState.GetSample1D(lightIndex);
UpdateReservoir(reservoirGlobalIndex, lightIndex, targetFunction, rnd);
s_SampleCount[threadIndex * MAX_RESERVOIRS_PER_VOXEL + reservoirLocalIndex] += 1;
}
}
}
NormalizeReservoirWeights(cellIndex * g_NumReservoirs, pos, reservoirIndex, threadIndex);
g_LightGrid[cellIndex] = uint2(cellIndex * g_NumReservoirs, reservoirIndex);
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 16e47c1641bd0104e92b624601457bb0
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,195 @@
#pragma only_renderers d3d11 vulkan metal glcore
RWTexture2D<float4> g_TextureInOut;
int g_TextureWidth;
int g_TextureHeight;
float4 g_MultiplicationFactor;
#pragma kernel Multiply
[numthreads(8,8,1)]
void Multiply(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_TextureWidth) || id.y >= uint(g_TextureHeight))
return;
g_TextureInOut[id.xy] = g_TextureInOut[id.xy] * g_MultiplicationFactor;
}
int g_ChannelIndex;
#pragma kernel BroadcastChannel
[numthreads(8,8,1)]
void BroadcastChannel(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_TextureWidth) || id.y >= uint(g_TextureHeight))
return;
if (g_ChannelIndex < 0 || g_ChannelIndex > 3)
return;
g_TextureInOut[id.xy] = g_TextureInOut[id.xy][g_ChannelIndex];
}
float g_ChannelValue;
#pragma kernel SetChannel
[numthreads(8,8,1)]
void SetChannel(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_TextureWidth) || id.y >= uint(g_TextureHeight))
return;
if (g_ChannelIndex < 0 || g_ChannelIndex > 3)
return;
switch (g_ChannelIndex)
{
case 0:
g_TextureInOut[id.xy] = float4(g_ChannelValue, g_TextureInOut[id.xy].g, g_TextureInOut[id.xy].b, g_TextureInOut[id.xy].a);
break;
case 1:
g_TextureInOut[id.xy] = float4(g_TextureInOut[id.xy].r, g_ChannelValue, g_TextureInOut[id.xy].b, g_TextureInOut[id.xy].a);
break;
case 2:
g_TextureInOut[id.xy] = float4(g_TextureInOut[id.xy].r, g_TextureInOut[id.xy].g, g_ChannelValue, g_TextureInOut[id.xy].a);
break;
case 3:
g_TextureInOut[id.xy] = float4(g_TextureInOut[id.xy].r, g_TextureInOut[id.xy].g, g_TextureInOut[id.xy].b, g_ChannelValue);
break;
}
}
Texture2D<float4> g_SourceTexture;
SamplerState g_LinearClampSampler;
RWTexture2D<float4> g_TextureOut;
int g_BoxFilterRadius;
#pragma kernel ReferenceBoxFilter
[numthreads(8,8,1)]
void ReferenceBoxFilter(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_TextureWidth) || id.y >= uint(g_TextureHeight))
return;
float4 sum = float4(0, 0, 0, 0);
for (int y = -g_BoxFilterRadius; y <= g_BoxFilterRadius; ++y)
{
for (int x = -g_BoxFilterRadius; x <= g_BoxFilterRadius; ++x)
{
float2 uv = (float2(id.xy) + float2(x, y)) / float2(g_TextureWidth, g_TextureHeight);
sum += g_SourceTexture.SampleLevel(g_LinearClampSampler, uv, 0);
}
}
g_TextureOut[id.xy] = sum / float((g_BoxFilterRadius * 2 + 1) * (g_BoxFilterRadius * 2 + 1));
}
#pragma kernel ReferenceBoxFilterBlueChannel
[numthreads(16,8,1)]
void ReferenceBoxFilterBlueChannel(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_TextureWidth) || id.y >= uint(g_TextureHeight))
return;
float4 color = g_SourceTexture[id.xy];
float sum = 0;
for (int y = -g_BoxFilterRadius; y <= g_BoxFilterRadius; ++y)
{
for (int x = -g_BoxFilterRadius; x <= g_BoxFilterRadius; ++x)
{
float2 uv = (float2(id.xy) + float2(x, y)) / float2(g_TextureWidth, g_TextureHeight);
sum += g_SourceTexture.SampleLevel(g_LinearClampSampler, uv, 0).b;
}
}
float average = sum / float((g_BoxFilterRadius * 2 + 1) * (g_BoxFilterRadius * 2 + 1));
g_TextureOut[id.xy] = float4(color.rg, average, color.a);
}
Texture2D<float4> g_SampleCountInW;
Texture2D<float4> g_VarianceInR;
#pragma kernel StandardError
[numthreads(8,8,1)]
void StandardError(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_TextureWidth) || id.y >= uint(g_TextureHeight))
return;
float variance = g_VarianceInR[id.xy].r;
float error = sqrt(variance / g_SampleCountInW[id.xy].w);
g_TextureOut[id.xy] = float4(error, error, error, 1.f);
}
Texture2D<float4> g_StandardErrorInR;
Texture2D<float4> g_MeanInR;
float g_StandardErrorThreshold;
#pragma kernel StandardErrorThreshold
[numthreads(8,8,1)]
void StandardErrorThreshold(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_TextureWidth) || id.y >= uint(g_TextureHeight))
return;
float mean = g_MeanInR[id.xy].r;
float standardError = g_StandardErrorInR[id.xy].r;
bool shouldStop = standardError < mean * g_StandardErrorThreshold || mean < 0.000001f;
g_TextureOut[id.xy] = shouldStop ? float4(0.0f, 0.0f, 0.0f, 1.f) : float4(1.0f, 1.0f, 1.0f, 1.f);
}
RWStructuredBuffer<float> g_OutputBuffer;
int g_X;
int g_Y;
#pragma kernel GetValue
[numthreads(8,8,1)]
void GetValue(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_TextureWidth) || id.y >= uint(g_TextureHeight))
return;
if (id.x == uint(g_X) && id.y == uint(g_Y))
{
float4 color = g_SourceTexture[id.xy];
g_OutputBuffer[0] = color.r;
g_OutputBuffer[1] = color.g;
g_OutputBuffer[2] = color.b;
g_OutputBuffer[3] = color.a;
}
}
#pragma kernel NormalizeByAlpha
[numthreads(8,8,1)]
void NormalizeByAlpha(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_TextureWidth) || id.y >= uint(g_TextureHeight))
return;
const float4 color = g_TextureInOut[id.xy];
const float sampleCount = max(color.w, 1.0f);
g_TextureInOut[id.xy] = float4(color.xyzw * (1.f / sampleCount));
}
StructuredBuffer<uint> g_InputBufferSelector; // 0 or 1
int g_InputBufferLength;
StructuredBuffer<uint> g_InputBuffer0;
StructuredBuffer<uint> g_InputBuffer1;
RWStructuredBuffer<uint> g_SelectionOutput;
#pragma kernel SelectGraphicsBuffer
[numthreads(16,1,1)]
void SelectGraphicsBuffer(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_InputBufferLength) || id.y >= 1u || id.z >= 1u)
return;
g_SelectionOutput[id.x] = g_InputBufferSelector[0] == 0u ? g_InputBuffer0[id.x] : g_InputBuffer1[id.x];
}
RWTexture2D<float4> g_DestinationTexture;
int g_SourceX;
int g_SourceY;
int g_SourceWidth;
int g_SourceHeight;
int g_DestinationX;
int g_DestinationY;
#pragma kernel CopyTextureAdditive
[numthreads(8,8,1)]
void CopyTextureAdditive(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_SourceWidth) || id.y >= uint(g_SourceHeight))
return;
uint2 src = id.xy + uint2(uint(g_SourceX), uint(g_SourceY));
uint2 dst = id.xy + uint2(uint(g_DestinationX), uint(g_DestinationY));
g_DestinationTexture[dst] = g_DestinationTexture[dst] + g_SourceTexture[src];
}
#pragma kernel MaskAlphaChannel
[numthreads(8,8,1)]
void MaskAlphaChannel(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_TextureWidth) || id.y >= uint(g_TextureHeight))
return;
float4 val = g_TextureInOut[id.xy];
val.a = val.a > 0;
g_TextureInOut[id.xy] = val;
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 2ba9c897a5bfc8c4e8faefab864e2a59
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,119 @@
#pragma only_renderers d3d11 vulkan metal glcore
#define UNIFIED_RT_BACKEND_COMPUTE
#define UNIFIED_RT_GROUP_SIZE_X 16
#define UNIFIED_RT_GROUP_SIZE_Y 8
#include "ExpansionHelpers.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/CommonStructs.hlsl"
// Compact an instance GBuffer to a buffer of non-empty texel indices.
// The output buffer has non-empty texels indices written into it. The number of texels written is stored in g_CompactedBufferLength.
// g_CompactedBufferLength must be initialized to 0 before calling this kernel.
#pragma kernel CompactGBuffer
[numthreads(64,1,1)]
void CompactGBuffer(uint3 id : SV_DispatchThreadID)
{
CompactGBufferInternal(id.x);
}
uint DivUp(uint x, uint y)
{
return uint((x + (int)y - 1) / (int)y);
}
// Populate the indirect dispatch buffer for the accumulation shader. Dimensions are in threads.
int g_ExpandedTexelSampleWidth;
int g_ThreadGroupSizeX;
RWStructuredBuffer<uint> g_AccumulationDispatchBuffer;
#pragma kernel PopulateAccumulationDispatch
[numthreads(8,1,1)]
void PopulateAccumulationDispatch(uint3 id : SV_DispatchThreadID)
{
if (id.x >= 1)
return;
const uint dimX = uint(g_ExpandedTexelSampleWidth) * g_CompactedGBufferLength[0];
g_AccumulationDispatchBuffer[0] = dimX;
g_AccumulationDispatchBuffer[1] = 1;
g_AccumulationDispatchBuffer[2] = 1;
}
// Populate the indirect dispatch buffer for the clear shader.
RWStructuredBuffer<uint> g_ClearDispatchBuffer;
#pragma kernel PopulateClearDispatch
[numthreads(8,1,1)]
void PopulateClearDispatch(uint3 id : SV_DispatchThreadID)
{
if (id.x >= 1)
return;
const uint dimX = uint(g_ExpandedTexelSampleWidth) * g_CompactedGBufferLength[0];
g_ClearDispatchBuffer[0] = DivUp(dimX, uint(g_ThreadGroupSizeX));
g_ClearDispatchBuffer[1] = 1;
g_ClearDispatchBuffer[2] = 1;
}
// Populate the indirect dispatch buffer for the copy shader.
RWStructuredBuffer<uint> g_CopyDispatchBuffer;
#pragma kernel PopulateCopyDispatch
[numthreads(8,1,1)]
void PopulateCopyDispatch(uint3 id : SV_DispatchThreadID)
{
if (id.x >= 1)
return;
const uint dimX = g_CompactedGBufferLength[0];
g_CopyDispatchBuffer[0] = DivUp(dimX, uint(g_ThreadGroupSizeX));
g_CopyDispatchBuffer[1] = 1;
g_CopyDispatchBuffer[2] = 1;
}
// Populate the indirect dispatch buffer for the reduce shader.
RWStructuredBuffer<uint> g_ReduceDispatchBuffer;
#pragma kernel PopulateReduceDispatch
[numthreads(8,1,1)]
void PopulateReduceDispatch(uint3 id : SV_DispatchThreadID)
{
if (id.x >= 1)
return;
const uint dimX = uint(g_ExpandedTexelSampleWidth) * g_CompactedGBufferLength[0];
g_ReduceDispatchBuffer[0] = DivUp(dimX, uint(g_ThreadGroupSizeX));
g_ReduceDispatchBuffer[1] = 1;
g_ReduceDispatchBuffer[2] = 1;
}
StructuredBuffer<float4> g_SourceBuffer;
RWTexture2D<float4> g_DestinationTexture;
int g_SourceStride;
int g_DestinationX;
int g_DestinationY;
#pragma kernel AdditivelyCopyCompactedTo2D
[numthreads(64,1,1)]
void AdditivelyCopyCompactedTo2D(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_CompactedGBufferLength[0]))
return;
uint linearChunkOffset = g_ChunkOffsetX + g_ChunkOffsetY * uint(g_InstanceWidth);
uint linearTexelIndex = g_CompactedGBuffer[id.x] + linearChunkOffset;
uint2 texelIndex = uint2(linearTexelIndex % uint(g_InstanceWidth), linearTexelIndex / uint(g_InstanceWidth)) + uint2(uint(g_DestinationX), uint(g_DestinationY));
g_DestinationTexture[texelIndex] += g_SourceBuffer[id.x*uint(g_SourceStride)];
}
// Sums the leftmost value of each group to the left
// The input buffer must be a multiple of g_BinaryGroupSize
RWStructuredBuffer<float4> g_Float4Buffer;
#pragma kernel BinaryGroupSumLeft
int g_BinaryBufferSize;
int g_BinaryGroupSize;
[numthreads(64,1,1)]
void BinaryGroupSumLeft(uint3 id : SV_DispatchThreadID)
{
if (id.x % (2 * uint(g_BinaryGroupSize)) != 0 || id.x + uint(g_BinaryGroupSize) >= uint(g_BinaryBufferSize))
return;
g_Float4Buffer[id.x] += g_Float4Buffer[id.x + g_BinaryGroupSize];
}
int g_Float4BufferLength;
#pragma kernel ClearFloat4Buffer
[numthreads(64,1,1)]
void ClearFloat4Buffer(uint3 id : SV_DispatchThreadID)
{
if (id.x >= uint(g_Float4BufferLength))
return;
g_Float4Buffer[id.x] = 0.0f;
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 200e63f12ebe79f4aa306481ce8ce4a4
ComputeShaderImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,32 @@
#ifndef _PATHTRACING_EXPANSIONHELPERS_HLSL_
#define _PATHTRACING_EXPANSIONHELPERS_HLSL_
#include "PathTracingCommon.hlsl"
RWStructuredBuffer<uint> g_CompactedGBuffer;
RWStructuredBuffer<uint> g_CompactedGBufferLength; // This will contain the number of texels written.
int g_ChunkOffsetX;
int g_ChunkOffsetY;
int g_ChunkSize;
int g_InstanceWidth;
Texture2D<half2> g_UvFallback;
void CompactGBufferInternal(uint index)
{
// The dispatch domain is [0; g_ChunkSize-1] in X
if (index >= (uint)g_ChunkSize)
return;
const uint linearChunkOffset = g_ChunkOffsetX + g_ChunkOffsetY * g_InstanceWidth;
const uint linearDispatch = linearChunkOffset + index;
const uint2 instanceTexelPos = uint2(linearDispatch % g_InstanceWidth, linearDispatch / g_InstanceWidth);
if (g_UvFallback[instanceTexelPos].x < 0)
return;
uint destinationIndex = 0;
InterlockedAdd(g_CompactedGBufferLength[0], 1, destinationIndex);
g_CompactedGBuffer[destinationIndex] = index;
}
#endif
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: e287e19aac082a84e9ede659dfde55ee
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,26 @@
#ifndef _PATHTRACING_FETCHTERRAINGEOMETRY_HLSL_
#define _PATHTRACING_FETCHTERRAINGEOMETRY_HLSL_
#include "Packages/com.unity.render-pipelines.core/Runtime/PathTracing/Shaders/TerrainRayMarching.hlsl"
UnifiedRT::HitGeomAttributes FetchTerrainHitGeomAttributes(UnifiedRT::Hit hit, int terrainIndex)
{
UnifiedRT::TerrainData terrainData = g_TerrainList[terrainIndex];
float numCells = 1.0 / terrainData.invHeightmapWidthInTexels - 1.0;
float2 heightmapUV = hit.uvBarycentrics * numCells;
float3 localPos, localNormal;
ComputeTerrainLocalPosAndNormal(terrainData, terrainIndex, heightmapUV, localPos, localNormal);
UnifiedRT::HitGeomAttributes result = (UnifiedRT::HitGeomAttributes) 0;
result.position = localPos;
result.normal = localNormal;
result.faceNormal = localNormal;
result.uv0 = hit.uvBarycentrics;
result.uv1 = hit.uvBarycentrics;
return result;
}
#endif // _PATHTRACING_FETCHTERRAINGEOMETRY_HLSL_
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 7d54f9694e06a3f42b78d1b025fb4aab
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: f4d1137d7b0a472438ff16f81047ba11
ShaderIncludeImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,75 @@
#pragma only_renderers d3d11 vulkan metal glcore
#pragma multi_compile _ TERRAIN_RAY_MARCHING_ENABLED
#define UNIFIED_RT_GROUP_SIZE_X 64
#define UNIFIED_RT_GROUP_SIZE_Y 1
#define UNIFIED_RT_RAYGEN_FUNC AccumulateInternal
#include "PathTracing.hlsl"
#include "LightmapIntegrationHelpers.hlsl"
int g_SampleOffset;
float g_PushOff;
RWStructuredBuffer<float4> g_ExpandedOutput;
float g_AOMaxDistance;
void AccumulateInternal(UnifiedRT::DispatchInfo dispatchInfo)
{
float3 worldPosition = 0.f;
float3 worldNormal = 0.f;
float3 worldFaceNormal = 0.f;
uint localSampleOffset = 0;
uint2 instanceTexelPos = 0;
const bool gotSample = GetExpandedSample(dispatchInfo.dispatchThreadID.x, localSampleOffset, instanceTexelPos, worldPosition, worldNormal, worldFaceNormal);
if (!gotSample)
return;
UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(g_SceneAccelStruct);
// setup rng
const uint sampleOffset = g_SampleOffset + localSampleOffset;
PathTracingSampler rngState;
rngState.Init(instanceTexelPos, sampleOffset);
// now sample occlusion with the gBuffer data
UnifiedRT::Ray ray;
float3 origin = OffsetRayOrigin(worldPosition, worldFaceNormal, g_PushOff);
float3 direction = CosineSample(rngState.GetSample2D(RAND_DIM_SURF_SCATTER), worldNormal);
ray.origin = origin;
ray.direction = direction;
ray.tMin = 0;
ray.tMax = g_AOMaxDistance;
rngState.NextBounce();
float3 occlusion = 0.f;
// trace through potentially several layers of transmissive materials, determining at each hit whether or not to kill the ray
for (uint i = 0; i < MAX_TRANSMISSION_BOUNCES; i++)
{
UnifiedRT::Hit hitResult = TraceRayClosestHit(dispatchInfo, accelStruct, RayMask(true), ray, 0);
if (hitResult.IsValid())
{
UnifiedRT::InstanceData instance = UnifiedRT::GetInstance(hitResult.instanceID);
PTHitGeom geometry = GetHitGeomInfo(instance, hitResult);
geometry.FixNormals(direction);
MaterialProperties material = LoadMaterialProperties(instance, geometry.uv0, geometry.uv1);
// Transmissive material, continue with a probability
if (ShouldTransmitRay(rngState, material))
{
ray.origin = geometry.NextTransmissionRayOrigin();
ray.tMax = g_AOMaxDistance - distance(origin, ray.origin);
rngState.NextBounce();
}
// No transmission, so the ray is occluded
else
{
occlusion = 1.f;
break;
}
}
// Hit nothing, so the ray is not occluded
else
break;
}
g_ExpandedOutput[dispatchInfo.dispatchThreadID.x] += float4(occlusion, 1.0f);
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 1c410815c01ce1d4d82c645c0cd45747
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 42d537a8a4089e448a99fc57a06d74a9, type: 3}
@@ -0,0 +1,132 @@
#pragma only_renderers d3d11 vulkan metal glcore
#pragma exclude_renderers switch switch2
#pragma multi_compile _ EMISSIVE_SAMPLING_LIGHT EMISSIVE_SAMPLING_BRDF EMISSIVE_SAMPLING_MIS
#pragma multi_compile _ TERRAIN_RAY_MARCHING_ENABLED
#define UNIFIED_RT_GROUP_SIZE_X 64
#define UNIFIED_RT_GROUP_SIZE_Y 1
#define UNIFIED_RT_RAYGEN_FUNC AccumulateInternal
#include "PathTracing.hlsl"
#include "LightmapIntegrationHelpers.hlsl"
int g_AccumulateDirectional;
int g_SampleOffset;
uint g_ReceiveShadows;
float g_PushOff;
RWStructuredBuffer<float4> g_ExpandedOutput;
RWStructuredBuffer<float4> g_ExpandedOutputDirectional;
// Sample a random cosine weighted direction, weight with MIS. Only counts contribution from emissive meshes.
// Assumes 2 sampling strategies, the other being direct sampling of lights (which may or may not be emissive meshes).
void EstimateMISWeightedIrradianceUsingCosineSampling(
UnifiedRT::DispatchInfo dispatchInfo,
UnifiedRT::RayTracingAccelStruct accelStruct,
StructuredBuffer<UnifiedRT::InstanceData> instanceList,
float3 origin,
float3 normal,
inout PathTracingSampler rngState,
inout float4 irradiance,
inout float4 directional)
{
UnifiedRT::Ray ray;
ray.origin = origin;
ray.direction = CosineSample(rngState.GetSample2D(RAND_DIM_SURF_SCATTER), normal);
ray.tMin = 0;
ray.tMax = FLT_MAX;
float sampleDensity = dot(normal, ray.direction) / PI;
float lightDensity = 0.f;
float3 emission = 0.f;
float3 attenuation = 1.0f;
for (uint i = 0; i < MAX_TRANSMISSION_BOUNCES; i++)
{
UnifiedRT::Hit hitResult = TraceRayClosestHit(dispatchInfo, accelStruct, RayMask(true), ray, 0);
if (hitResult.IsValid()) // Hit something, possibly emissive
{
UnifiedRT::InstanceData instance = UnifiedRT::GetInstance(hitResult.instanceID);
PTHitGeom geometry = GetHitGeomInfo(instance, hitResult);
geometry.FixNormals(ray.direction);
MaterialProperties material = LoadMaterialProperties(instance, geometry.uv0, geometry.uv1);
// Transmissive material, either continue or terminate ray, then apply attenuation.
if (ShouldTransmitRay(rngState, material))
{
attenuation *= saturate(material.transmission);
ray.origin = geometry.NextTransmissionRayOrigin();
rngState.NextBounce();
continue;
}
// Hit emissive frontface
else if (!ShouldTreatAsBackface(hitResult, material) && any(material.emission))
{
// The density used to calculate MIS weights should include both the probability of sampling the specific
// point on the emissive mesh, as well as the probability of picking the emissive mesh.
lightDensity = ComputeEmissiveTriangleDensity(instanceList, geometry, hitResult.instanceID, ray.origin);
lightDensity /= GetNumLights(ray.origin);
emission = material.emission;
}
break;
}
else // Hit skybox, so stop
{
GetEnvironmentLightEmissionAndDensity(ray.direction, emission, lightDensity);
break;
}
}
// Tint the emissiom by the transmissive attenuation before accumulating
emission *= attenuation;
// MIS - Cosine weighted sampling
float sampleMISWeight = EmissiveMISWeightForBrdfRay(lightDensity, sampleDensity);
// f(x)/p(x) = (Li * cos(theta)) / (cos(theta) / PI) = Li * PI
float3 e = emission * PI * sampleMISWeight;
irradiance.rgb += e;
directional += float4(ray.direction, 1.f) * Luminance(e);
}
void AccumulateInternal(UnifiedRT::DispatchInfo dispatchInfo)
{
float3 worldPosition = 0.f;
float3 worldNormal = 0.f;
float3 worldFaceNormal = 0.f;
uint localSampleOffset = 0;
uint2 instanceTexelPos = 0;
const bool gotSample = GetExpandedSample(dispatchInfo.dispatchThreadID.x, localSampleOffset, instanceTexelPos, worldPosition, worldNormal, worldFaceNormal);
if (!gotSample)
return;
UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(g_SceneAccelStruct);
const uint sampleOffset = g_SampleOffset + localSampleOffset;
float3 origin = OffsetRayOrigin(worldPosition, worldFaceNormal, g_PushOff);
float4 irradiance = 0.f;
float4 directional = 0.f;
PathTracingSampler rngState;
rngState.Init(instanceTexelPos, sampleOffset);
SampleLightsOptions options;
options.isDirect = true;
options.receiveShadows = g_ReceiveShadows;
options.shadowRayMask = ShadowRayMask();
options.lightsRenderingLayerMask = 0xFFFFFFFF;
options.numLightCandidates = min(g_LightEvaluations, MAX_LIGHT_EVALUATIONS);
uint numLightsInCell = GetNumLights(origin);
EstimateMISWeightedIrradianceUsingCosineSampling(dispatchInfo, accelStruct, g_AccelStructInstanceList, origin, worldNormal, rngState, irradiance, directional);
// Store new accumulated irradiance
g_ExpandedOutput[dispatchInfo.dispatchThreadID.x] += float4(irradiance.rgb, 1.0);
if (g_AccumulateDirectional > 0)
g_ExpandedOutputDirectional[dispatchInfo.dispatchThreadID.x] += directional;
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 5951703b3d165764c95c653e98350884
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 42d537a8a4089e448a99fc57a06d74a9, type: 3}
@@ -0,0 +1,86 @@
#pragma only_renderers d3d11 vulkan metal glcore
#pragma exclude_renderers switch switch2
#pragma multi_compile _ LIGHT_SAMPLING_UNIFORM LIGHT_SAMPLING_RIS LIGHT_SAMPLING_ROUND_ROBIN
#pragma multi_compile _ EMISSIVE_SAMPLING_LIGHT EMISSIVE_SAMPLING_BRDF EMISSIVE_SAMPLING_MIS
#pragma multi_compile _ TERRAIN_RAY_MARCHING_ENABLED
#define UNIFIED_RT_GROUP_SIZE_X 64
#define UNIFIED_RT_GROUP_SIZE_Y 1
#define UNIFIED_RT_RAYGEN_FUNC AccumulateInternal
#include "PathTracing.hlsl"
#include "LightmapIntegrationHelpers.hlsl"
int g_AccumulateDirectional;
int g_SampleOffset;
uint g_ReceiveShadows;
float g_PushOff;
RWStructuredBuffer<float4> g_ExpandedOutput;
RWStructuredBuffer<float4> g_ExpandedOutputDirectional;
void AccumulateInternal(UnifiedRT::DispatchInfo dispatchInfo)
{
float3 worldPosition = 0.f;
float3 worldNormal = 0.f;
float3 worldFaceNormal = 0.f;
uint localSampleOffset = 0;
uint2 instanceTexelPos = 0;
const bool gotSample = GetExpandedSample(dispatchInfo.dispatchThreadID.x, localSampleOffset, instanceTexelPos, worldPosition, worldNormal, worldFaceNormal);
if (!gotSample)
return;
UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(g_SceneAccelStruct);
const uint sampleOffset = g_SampleOffset + localSampleOffset;
float3 origin = OffsetRayOrigin(worldPosition, worldFaceNormal, g_PushOff);
float4 irradiance = 0.0f;
float4 directional = 0.0f;
PathTracingSampler rngState;
rngState.Init(instanceTexelPos, sampleOffset);
SampleLightsOptions options;
options.isDirect = true;
options.receiveShadows = g_ReceiveShadows;
options.shadowRayMask = ShadowRayMask();
options.lightsRenderingLayerMask = 0xFFFFFFFF;
options.numLightCandidates = 1;
// TODO: Specialize sampling codepaths for different light types: https://jira.unity3d.com/browse/GFXLIGHT-2260
// Sample the main directional light
if (g_HasMainDirectionalLight)
{
PTLight directionalLight = g_MainDirectionalLight[0];
LightSample directionalLightSample;
SampleLightRadiance(dispatchInfo, accelStruct, g_AccelStructInstanceList, origin, worldNormal, options, directionalLight, rngState, directionalLightSample);
float3 eval = ClampedCosine(worldNormal, directionalLightSample.direction) * directionalLightSample.radiance;
irradiance.rgb += eval;
directional += float4(directionalLightSample.direction, 1.f) * Luminance(eval);
}
// Sample the environment
if (g_HasEnvironmentLight)
{
PTLight environmentLight = (PTLight)0;
environmentLight.type = ENVIRONMENT_LIGHT;
environmentLight.castsShadows = 1;
environmentLight.contributesToDirectLighting = 1;
environmentLight.layerMask = UINT_MAX;
LightSample environmentLightSample;
SampleLightRadiance(dispatchInfo, accelStruct, g_AccelStructInstanceList, origin, worldNormal, options, environmentLight, rngState, environmentLightSample);
float misWeight = EmissiveMISWeightForLightRay(environmentLightSample.lightType, environmentLightSample.direction, environmentLightSample.risSourcePdf, worldNormal);
float3 eval = misWeight * ClampedCosine(worldNormal, environmentLightSample.direction) * environmentLightSample.radiance;
irradiance.rgb += eval;
directional += float4(environmentLightSample.direction, 1.f) * Luminance(eval);
}
// Store new accumulated irradiance
g_ExpandedOutput[dispatchInfo.dispatchThreadID.x] += float4(irradiance.rgb, 0.0f);
if (g_AccumulateDirectional > 0)
g_ExpandedOutputDirectional[dispatchInfo.dispatchThreadID.x] += directional;
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: f5ba4d424d4566249b3d94cf81a3e916
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 42d537a8a4089e448a99fc57a06d74a9, type: 3}
@@ -0,0 +1,141 @@
#pragma only_renderers d3d11 vulkan metal glcore
#pragma exclude_renderers switch switch2
#pragma multi_compile _ LIGHT_SAMPLING_UNIFORM LIGHT_SAMPLING_RIS LIGHT_SAMPLING_ROUND_ROBIN
#pragma multi_compile _ EMISSIVE_SAMPLING_LIGHT EMISSIVE_SAMPLING_BRDF EMISSIVE_SAMPLING_MIS
#pragma multi_compile _ TERRAIN_RAY_MARCHING_ENABLED
#define UNIFIED_RT_GROUP_SIZE_X 64
#define UNIFIED_RT_GROUP_SIZE_Y 1
#define UNIFIED_RT_RAYGEN_FUNC AccumulateInternal
#include "PathTracing.hlsl"
#include "LightmapIntegrationHelpers.hlsl"
uint g_LightIndexInCell;
int g_AccumulateDirectional;
int g_SampleOffset;
uint g_ReceiveShadows;
float g_PushOff;
RWStructuredBuffer<float4> g_ExpandedOutput;
RWStructuredBuffer<float4> g_ExpandedOutputDirectional;
// Sample a specific light directly, weight with MIS.
// Assumes 2 sampling strategies, the other being cosine weighted hemisphere sampling.
void EstimateMISWeightedIrradianceForSpecificLightUsingDirectSampling(
UnifiedRT::DispatchInfo dispatchInfo,
UnifiedRT::RayTracingAccelStruct accelStruct,
StructuredBuffer<UnifiedRT::InstanceData> instanceList,
float3 origin,
float3 normal,
SampleLightsOptions options,
uint lightIndexInCell,
inout PathTracingSampler rngState,
inout float4 irradiance,
inout float4 directional,
out LightSample lightSample)
{
float3 sampleRadiance = 0.f;
float3 sampleDirection = 0.f;
float sampleDensity = 0.f;
uint lightIndex = LocalToGlobalLightIndex(origin, lightIndexInCell);
if (SampleLightRadianceRoundRobin(dispatchInfo, accelStruct, g_AccelStructInstanceList, origin, normal, options, lightIndex, rngState, lightSample))
{
float sampleMISWeight = EmissiveMISWeightForLightRay(lightSample.lightType, lightSample.direction, lightSample.risSourcePdf, normal);
float3 e = sampleMISWeight * ClampedCosine(normal, lightSample.direction) * lightSample.radiance;
irradiance.rgb += e;
directional += float4(lightSample.direction, 1.f) * Luminance(e);
}
}
// Sample every light directly, weight with MIS.
// Assumes 2 sampling strategies, the other being cosine weighted hemisphere sampling.
void EstimateMISWeightedIrradianceUsingDirectSampling(
UnifiedRT::DispatchInfo dispatchInfo,
UnifiedRT::RayTracingAccelStruct accelStruct,
StructuredBuffer<UnifiedRT::InstanceData> instanceList,
float3 origin,
float3 normal,
SampleLightsOptions options,
inout PathTracingSampler rngState,
inout float4 irradiance,
inout float4 directional,
out LightSample lightSample)
{
float3 sampleRadiance = 0.f;
float3 sampleDirection = 0.f;
float sampleDensity = 0.f;
if (SampleRadianceFromLightGrid(dispatchInfo, accelStruct, instanceList, origin, normal, options, rngState, lightSample))
{
float sampleMISWeight = EmissiveMISWeightForLightRay(lightSample.lightType, lightSample.direction, lightSample.risSourcePdf, normal);
float3 e = sampleMISWeight * ClampedCosine(normal, lightSample.direction) * lightSample.radiance;
irradiance.rgb += e;
directional += float4(lightSample.direction, 1.f) * Luminance(e);
}
}
void AccumulateInternal(UnifiedRT::DispatchInfo dispatchInfo)
{
float3 worldPosition = 0.f;
float3 worldNormal = 0.f;
float3 worldFaceNormal = 0.f;
uint localSampleOffset = 0;
uint2 instanceTexelPos = 0;
const bool gotSample = GetExpandedSample(dispatchInfo.dispatchThreadID.x, localSampleOffset, instanceTexelPos, worldPosition, worldNormal, worldFaceNormal);
if (!gotSample)
return;
UnifiedRT::RayTracingAccelStruct accelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(g_SceneAccelStruct);
const uint sampleOffset = g_SampleOffset + localSampleOffset;
float3 origin = OffsetRayOrigin(worldPosition, worldFaceNormal, g_PushOff);
float4 irradiance = 0.f;
float4 directional = 0.f;
PathTracingSampler rngState;
rngState.Init(instanceTexelPos, sampleOffset);
SampleLightsOptions options;
options.isDirect = true;
options.receiveShadows = g_ReceiveShadows;
options.shadowRayMask = ShadowRayMask();
options.lightsRenderingLayerMask = 0xFFFFFFFF;
options.numLightCandidates = min(g_LightEvaluations, MAX_LIGHT_EVALUATIONS);
uint numLightsInCell = GetNumLights(origin);
// Sample a light using direct sampling, weight with MIS.
#ifdef LIGHT_SAMPLING_ROUND_ROBIN
// If we have already sampled every light in the cell, skip this sample to avoid needing to normalize per-light.
[branch] if (g_LightIndexInCell >= numLightsInCell)
{
g_ExpandedOutput[dispatchInfo.dispatchThreadID.x] += float4(0,0,0,g_LightIndexInCell==0);
return;
}
LightSample lightSample;
EstimateMISWeightedIrradianceForSpecificLightUsingDirectSampling(dispatchInfo, accelStruct, g_AccelStructInstanceList, origin, worldNormal, options, g_LightIndexInCell, rngState, irradiance, directional, lightSample);
#else
LightSample lightSample;
EstimateMISWeightedIrradianceUsingDirectSampling(dispatchInfo, accelStruct, g_AccelStructInstanceList, origin, worldNormal, options, rngState, irradiance, directional, lightSample);
#endif
// With round-robin, we take (numLights*sampleCount) samples instead of just (sampleCount).
// To keep normalization consistent with the other strategies, we keep the same effective
// sample count in the alpha channel of the output, but divide each sample by (numLights).
#ifdef LIGHT_SAMPLING_ROUND_ROBIN
irradiance /= numLightsInCell;
directional /= numLightsInCell;
#endif
// Store new accumulated irradiance
g_ExpandedOutput[dispatchInfo.dispatchThreadID.x] += float4(irradiance.rgb,g_LightIndexInCell==0);
if (g_AccumulateDirectional > 0)
g_ExpandedOutputDirectional[dispatchInfo.dispatchThreadID.x] += directional;
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 5bbebdef5916845478fcef13fa10d89f
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 42d537a8a4089e448a99fc57a06d74a9, type: 3}
@@ -0,0 +1,23 @@
#pragma only_renderers d3d11 vulkan metal glcore
#pragma multi_compile _ TERRAIN_RAY_MARCHING_ENABLED
#define UNIFIED_RT_GROUP_SIZE_X 64
#define UNIFIED_RT_GROUP_SIZE_Y 1
#define UNIFIED_RT_RAYGEN_FUNC AccumulateInternal
#include "PathTracing.hlsl"
#include "LightmapIntegrationHelpers.hlsl"
RWStructuredBuffer<float2> g_LightmapSamplesExpanded;
void AccumulateInternal(UnifiedRT::DispatchInfo dispatchInfo)
{
float3 worldPosition = 0.f;
float3 worldNormal = 0.f;
float3 worldFaceNormal = 0.f;
float2 uv1 = 0.f;
const bool gotSample = GetExpandedSample(dispatchInfo.dispatchThreadID.x, worldPosition, worldNormal, worldFaceNormal, uv1);
if (!gotSample)
return;
g_LightmapSamplesExpanded[dispatchInfo.dispatchThreadID.x] = uv1;
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 737a1597422c12547a8714d76a9406ec
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 42d537a8a4089e448a99fc57a06d74a9, type: 3}
@@ -0,0 +1,99 @@
#pragma only_renderers d3d11 vulkan metal glcore
#pragma multi_compile _ TERRAIN_RAY_MARCHING_ENABLED
#define UNIFIED_RT_GROUP_SIZE_X 64
#define UNIFIED_RT_GROUP_SIZE_Y 1
#define UNIFIED_RT_RAYGEN_FUNC AccumulateInternal
#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/FetchGeometry.hlsl"
#include "Packages/com.unity.render-pipelines.core/Runtime/UnifiedRayTracing/TraceRayAndQueryHit.hlsl"
#include "PathTracingRandom.hlsl"
#include "StochasticLightmapSampling.hlsl"
UNIFIED_RT_DECLARE_ACCEL_STRUCT(g_UVAccelStruct);
int g_StochasticAntialiasing;
int g_SuperSampleWidth; // width of the super sampling grid - defines as g_SuperSampleWidth x g_SuperSampleWidth grid of samples
int g_InstanceOffsetX;
int g_InstanceOffsetY;
int g_InstanceWidth;
int g_InstanceHeight;
float g_InstanceWidthScale;
float g_InstanceHeightScale;
int g_ChunkOffsetX;
int g_ChunkOffsetY;
int g_ChunkSize;
int g_ExpandedTexelSampleWidth;
int g_PassSampleCount;
int g_SampleOffset;
Texture2D<half2> g_UvFallback;
RWStructuredBuffer<HitEntry> g_GBuffer;
StructuredBuffer<uint> g_CompactedGBuffer;
StructuredBuffer<uint> g_CompactedGBufferLength;
float2 JitterSample(float2 sample, float2 random01, float jitterAmount)
{
const float2 jitteredSample = sample + jitterAmount * (random01 - 0.5f);
return saturate(jitteredSample);
}
float2 GetSuperSamplingOffset(uint currentSuperSampleIndex, uint superSampleWidth)
{
currentSuperSampleIndex = currentSuperSampleIndex % (superSampleWidth * superSampleWidth);
uint ssX = currentSuperSampleIndex % superSampleWidth;
uint ssY = currentSuperSampleIndex / superSampleWidth;
return (float2(ssX, ssY) + 0.5f) / (float)superSampleWidth;
}
void AccumulateInternal(UnifiedRT::DispatchInfo dispatchInfo)
{
// The dispatch domain is [0; (g_ChunkSize * g_ExpandedTexelSampleWidth) - 1] in X
const uint sampleIndex = dispatchInfo.dispatchThreadID.x;
g_GBuffer[sampleIndex].instanceID = -1;
g_GBuffer[sampleIndex].primitiveIndex = -1;
g_GBuffer[sampleIndex].barycentrics = uint2(0,0);
const uint compactedRange = g_CompactedGBufferLength[0] * (uint)g_ExpandedTexelSampleWidth;
if (sampleIndex >= compactedRange)
return;
// check that the sample is needed, g_ExpandedTexelSampleWidth might have more samples than needed as it is power of two
// .. and the last sampling pass might have few remaining samples
uint localSampleIndex = (uint)sampleIndex % (uint)g_ExpandedTexelSampleWidth;
if (localSampleIndex >= (uint)g_PassSampleCount)
return;
uint compactedTexelIndex = sampleIndex / (uint)g_ExpandedTexelSampleWidth;
uint chunkLinearTexelIndex = g_CompactedGBuffer[compactedTexelIndex];
if (chunkLinearTexelIndex >= (uint)g_ChunkSize)
return;
const uint linearChunkOffset = g_ChunkOffsetX + g_ChunkOffsetY * g_InstanceWidth;
const uint linearInstancePos = linearChunkOffset + chunkLinearTexelIndex;
if (linearInstancePos >= (uint)g_InstanceWidth * (uint)g_InstanceHeight)
return;
const uint2 instanceTexelPos = uint2(linearInstancePos % g_InstanceWidth, linearInstancePos / g_InstanceWidth);
const uint2 lightmapTexelPos = uint2(g_InstanceOffsetX, g_InstanceOffsetY) + instanceTexelPos;
const float2 instanceSize = float2(g_InstanceWidth, g_InstanceHeight);
UnifiedRT::RayTracingAccelStruct uvAccelStruct = UNIFIED_RT_GET_ACCEL_STRUCT(g_UVAccelStruct);
PathTracingSampler rngState;
rngState.Init(lightmapTexelPos, g_SampleOffset + localSampleIndex);
// select a random point in the texel
const float2 random01 = rngState.GetSample2D(RAND_DIM_AA);
const float2 texelSample = g_StochasticAntialiasing == 1 ? random01 : JitterSample(GetSuperSamplingOffset(g_SampleOffset + localSampleIndex, g_SuperSampleWidth), random01, 0.001f); // the jitter is to avoid issues with raytracing watertightness
const float2 instanceScale = float2(g_InstanceWidthScale, g_InstanceHeightScale);
const UnifiedRT::Hit hit = LightmapSampleTexelOffset(instanceTexelPos, texelSample, instanceSize, instanceScale, dispatchInfo, uvAccelStruct, g_UvFallback[instanceTexelPos]);
if (!hit.IsValid())
{
// no intersection found
return;
}
g_GBuffer[sampleIndex].instanceID = hit.instanceID;
g_GBuffer[sampleIndex].primitiveIndex = hit.primitiveIndex;
g_GBuffer[sampleIndex].barycentrics = hit.uvBarycentrics;
}
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: e9f4de6d1e07fb94f9a60d35b618f724
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 11500000, guid: 42d537a8a4089e448a99fc57a06d74a9, type: 3}

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