This commit is contained in:
2026-11-24 15:51:02 +01:00
parent cca4d73e41
commit f4aa17114a
22092 changed files with 5042406 additions and 0 deletions
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: f895f2b1dbb2da84e82eedb22e2620f7
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,50 @@
#if UNITY_EDITOR
using UnityEngine.Rendering.RenderGraphModule;
#endif
namespace UnityEngine.Rendering.Universal
{
static class LayerDebug
{
#if UNITY_EDITOR
static internal bool enabled => FrameDebugger.enabled || RenderGraph.isRenderGraphViewerActive;
static internal string GetDebugLayerNames(LayerBatch layerBatch)
{
var debugNames = string.Empty;
var sortingLayers = Light2DManager.GetCachedSortingLayer();
foreach (var layer in sortingLayers)
{
if (layerBatch.IsValueWithinLayerRange(layer.value))
{
if (debugNames == string.Empty)
debugNames = layer.name;
else
debugNames += " | " + layer.name;
}
}
return debugNames;
}
#endif
static internal void FormatPassName(LayerBatch layerBatch, ref string passName)
{
#if UNITY_EDITOR
if (enabled)
passName += " - " + GetDebugLayerNames(layerBatch);
#endif
}
static internal ProfilingSampler GetProfilingSampler(string passName, ProfilingSampler sampler)
{
#if UNITY_EDITOR
if (enabled)
return new ProfilingSampler(passName);
#endif
return sampler;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a2edf664af334144a8ad0aed989753d3
@@ -0,0 +1,219 @@
using Unity.Mathematics;
using System.Collections.Generic;
namespace UnityEngine.Rendering.Universal
{
internal class LayerBatch
{
#if UNITY_EDITOR
internal int startIndex;
internal int endIndex;
#endif
internal int startLayerID;
internal int endLayerValue;
internal SortingLayerRange layerRange;
internal LightStats lightStats;
internal bool useNormals;
internal List<Light2D> lights = new List<Light2D>();
internal List<int> shadowIndices = new List<int>();
internal List<ShadowCasterGroup2D> shadowCasters = new List<ShadowCasterGroup2D>();
internal int[] activeBlendStylesIndices;
// This range check uses SortingLayer.value.
internal bool IsValueWithinLayerRange(int value)
{
return value >= layerRange.lowerBound && value <= layerRange.upperBound;
}
}
internal static class LayerUtility
{
private static LayerBatch[] s_LayerBatches;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod]
static void ResetStaticsOnLoad()
{
s_LayerBatches = null;
}
#endif
private static bool CanBatchLightsInLayer(int layerIndex1, int layerIndex2, SortingLayer[] sortingLayers, ILight2DCullResult lightCullResult)
{
var layerId1 = sortingLayers[layerIndex1].id;
var layerId2 = sortingLayers[layerIndex2].id;
foreach (var light in lightCullResult.visibleLights)
{
// If the lit layers are different don't batch.
if (light.IsLitLayer(layerId1) != light.IsLitLayer(layerId2))
return false;
}
foreach (var group in lightCullResult.visibleShadows)
{
foreach (var shadowCaster in group.GetShadowCasters())
{
// Don't batch when the layer has different shadow casters
if (shadowCaster.IsShadowedLayer(layerId1) != shadowCaster.IsShadowedLayer(layerId2))
return false;
}
}
return true;
}
private static bool CanBatchCameraSortingLayer(int startLayerIndex, SortingLayer[] sortingLayers, Renderer2DData rendererData)
{
if (rendererData.useCameraSortingLayerTexture)
{
var cameraSortingLayerBoundsIndex = rendererData.GetCameraSortingLayerBoundsIndex();
return sortingLayers[startLayerIndex].value == cameraSortingLayerBoundsIndex;
}
return false;
}
private static int FindUpperBoundInBatch(int startLayerIndex, SortingLayer[] sortingLayers, Renderer2DData rendererData)
{
// break layer if camera sorting layer is active
if (CanBatchCameraSortingLayer(startLayerIndex, sortingLayers, rendererData))
return startLayerIndex;
// start checking at the next layer
for (var i = startLayerIndex + 1; i < sortingLayers.Length; i++)
{
if (!CanBatchLightsInLayer(startLayerIndex, i, sortingLayers, rendererData.lightCullResult))
return i - 1;
if (CanBatchCameraSortingLayer(i, sortingLayers, rendererData))
return i;
}
return sortingLayers.Length - 1;
}
private static void InitializeBatchInfos(SortingLayer[] cachedSortingLayers)
{
var count = cachedSortingLayers.Length;
var needInit = s_LayerBatches == null;
if (s_LayerBatches is null)
{
s_LayerBatches = new LayerBatch[count];
}
#if UNITY_EDITOR
// we should fix. Make a non allocating version of this
if (!Application.isPlaying && s_LayerBatches.Length != count)
{
s_LayerBatches = new LayerBatch[count];
needInit = true;
}
#endif
if (needInit)
{
for (var i = 0; i < s_LayerBatches.Length; i++)
s_LayerBatches[i] = new LayerBatch();
}
}
public static LayerBatch[] CalculateBatches(Renderer2DData rendererData, out int batchCount)
{
var cachedSortingLayers = Light2DManager.GetCachedSortingLayer();
InitializeBatchInfos(cachedSortingLayers);
bool anyNormals = false;
batchCount = 0;
for (var i = 0; i < cachedSortingLayers.Length;)
{
var layerToRender = cachedSortingLayers[i].id;
var layerBatch = s_LayerBatches[batchCount++];
var lightStats = rendererData.lightCullResult.GetLightStatsByLayer(layerToRender, ref layerBatch);
// Find the highest layer that share the same set of lights and shadows as this layer.
var upperLayerInBatch = FindUpperBoundInBatch(i, cachedSortingLayers, rendererData);
// Some renderers override their sorting layer value with short.MinValue or short.MaxValue.
// When drawing the first sorting layer, we should include the range from short.MinValue to layerValue.
// Similarly, when drawing the last sorting layer, include the range from layerValue to short.MaxValue.
var startLayerValue = (short)cachedSortingLayers[i].value;
var lowerBound = (i == 0) ? short.MinValue : startLayerValue;
var endLayerValue = (short)cachedSortingLayers[upperLayerInBatch].value;
var upperBound = (upperLayerInBatch == cachedSortingLayers.Length - 1) ? short.MaxValue : endLayerValue;
// Renderer within this range share the same set of lights so they should be rendered together.
var sortingLayerRange = new SortingLayerRange(lowerBound, upperBound);
#if UNITY_EDITOR
layerBatch.startIndex = i;
layerBatch.endIndex = upperLayerInBatch;
#endif
layerBatch.startLayerID = layerToRender;
layerBatch.endLayerValue = endLayerValue;
layerBatch.layerRange = sortingLayerRange;
layerBatch.lightStats = lightStats;
anyNormals |= layerBatch.lightStats.useNormalMap;
i = upperLayerInBatch + 1;
}
// Account for Sprite Mask and normal map usage as there might be masks on a different layer that need to mask out the normals
for (var i = 0; i < batchCount; ++i)
{
var layerBatch = s_LayerBatches[i];
var hasSpriteMask = SpriteMaskUtility.HasSpriteMaskInLayerRange(layerBatch.layerRange);
layerBatch.useNormals = layerBatch.lightStats.useNormalMap || (anyNormals && hasSpriteMask);
}
SetupActiveBlendStyles();
return s_LayerBatches;
}
public static void GetFilterSettings(Renderer2DData rendererData, LayerBatch layerBatch, out FilteringSettings filterSettings)
{
filterSettings = FilteringSettings.defaultValue;
filterSettings.renderQueueRange = RenderQueueRange.all;
filterSettings.layerMask = rendererData.layerMask;
filterSettings.renderingLayerMask = 0xFFFFFFFF;
filterSettings.sortingLayerRange = layerBatch.layerRange;
}
static void SetupActiveBlendStyles()
{
// Calculate active blend styles to save on total light textures allocated
for (int i = 0; i < s_LayerBatches.Length; ++i)
{
ref var layer = ref s_LayerBatches[i];
// Determine number of blend styles used
int size = 0;
for (var blendStyleIndex = 0; blendStyleIndex < RendererLighting.k_ShapeLightTextureIDs.Length; blendStyleIndex++)
{
var blendStyleMask = (uint)(1 << blendStyleIndex);
var blendStyleUsed = (layer.lightStats.blendStylesUsed & blendStyleMask) > 0;
if (blendStyleUsed)
size++;
}
if (layer.activeBlendStylesIndices == null || layer.activeBlendStylesIndices.Length != size)
layer.activeBlendStylesIndices = new int[size];
// Save indices so we don't have to copy the whole Light2DBlendStyle struct
var index = 0;
for (var blendStyleIndex = 0; blendStyleIndex < RendererLighting.k_ShapeLightTextureIDs.Length; blendStyleIndex++)
{
var blendStyleMask = (uint)(1 << blendStyleIndex);
var blendStyleUsed = (layer.lightStats.blendStylesUsed & blendStyleMask) > 0;
if (blendStyleUsed)
layer.activeBlendStylesIndices[index++] = blendStyleIndex;
}
}
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 837cbe89c0a94e149f5b494ae9c69a51
timeCreated: 1599108159
@@ -0,0 +1,166 @@
using UnityEngine.Experimental.Rendering;
namespace UnityEngine.Rendering.Universal
{
internal static class Light2DLookupTexture
{
internal static readonly string k_LightLookupProperty = "_LightLookup";
internal static readonly string k_FalloffLookupProperty = "_FalloffLookup";
internal static readonly int k_LightLookupID = Shader.PropertyToID(k_LightLookupProperty);
internal static readonly int k_FalloffLookupID = Shader.PropertyToID(k_FalloffLookupProperty);
private static RTHandle s_LightLookupRTHandle = null;
private static RTHandle s_FalloffRTHandle = null;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod]
static void ResetStaticsOnLoad()
{
Release();
}
#endif
public static RTHandle GetLightLookupTexture_Rendergraph()
{
if (s_LightLookupRTHandle == null || s_LightLookupRTHandle?.externalTexture == null)
{
var lightLookupTexture = CreatePointLightLookupTexture();
s_LightLookupRTHandle?.Release();
s_LightLookupRTHandle = RTHandles.Alloc(lightLookupTexture);
}
return s_LightLookupRTHandle;
}
public static RTHandle GetFallOffLookupTexture_Rendergraph()
{
if (s_FalloffRTHandle == null || s_FalloffRTHandle?.externalTexture == null)
{
var fallOffLookupTexture = CreateFalloffLookupTexture();
s_FalloffRTHandle?.Release();
s_FalloffRTHandle = RTHandles.Alloc(fallOffLookupTexture);
}
return s_FalloffRTHandle;
}
public static void Release()
{
s_FalloffRTHandle?.Release();
s_LightLookupRTHandle?.Release();
s_FalloffRTHandle = null;
s_LightLookupRTHandle = null;
}
private static Texture2D CreatePointLightLookupTexture()
{
const int WIDTH = 256;
const int HEIGHT = 256;
var textureFormat = GraphicsFormat.R8G8B8A8_UNorm;
if (SystemInfo.IsFormatSupported(GraphicsFormat.R16G16B16A16_SFloat, GraphicsFormatUsage.SetPixels))
textureFormat = GraphicsFormat.R16G16B16A16_SFloat;
else if (SystemInfo.IsFormatSupported(GraphicsFormat.R32G32B32A32_SFloat, GraphicsFormatUsage.SetPixels))
textureFormat = GraphicsFormat.R32G32B32A32_SFloat;
var texture = new Texture2D(WIDTH, HEIGHT, textureFormat, TextureCreationFlags.None);
texture.name = k_LightLookupProperty;
texture.filterMode = FilterMode.Bilinear;
texture.wrapMode = TextureWrapMode.Clamp;
var center = new Vector2(WIDTH / 2.0f, HEIGHT / 2.0f);
for (var y = 0; y < HEIGHT; y++)
{
for (var x = 0; x < WIDTH; x++)
{
var pos = new Vector2(x, y);
var distance = Vector2.Distance(pos, center);
var relPos = pos - center;
var direction = center - pos;
direction.Normalize();
// red = 1-0 distance
// green = 1-0 angle
// blue = direction.x
// alpha = direction.y
float red;
if (x == WIDTH - 1 || y == HEIGHT - 1)
red = 0;
else
red = Mathf.Clamp(1 - (2.0f * distance / WIDTH), 0.0f, 1.0f);
var cosAngle = Vector2.Dot(Vector2.down, relPos.normalized);
var angle = Mathf.Acos(cosAngle) / Mathf.PI; // 0-1
var green = Mathf.Clamp(1 - angle, 0.0f, 1.0f);
var blue = direction.x;
var alpha = direction.y;
var color = new Color(red, green, blue, alpha);
texture.SetPixel(x, y, color);
}
}
texture.Apply();
return texture;
}
private static Texture2D CreateFalloffLookupTexture()
{
const int WIDTH = 2048;
const int HEIGHT = 192;
const GraphicsFormat textureFormat = GraphicsFormat.R8G8B8A8_SRGB;
var texture = new Texture2D(WIDTH, HEIGHT - 64, textureFormat, TextureCreationFlags.None);
texture.name = k_FalloffLookupProperty;
texture.filterMode = FilterMode.Bilinear;
texture.wrapMode = TextureWrapMode.Clamp;
for (var y = 0; y < HEIGHT; y++)
{
var baseValue = (float)(y + 32) / (HEIGHT + 64);
var lineValue = -baseValue + 1;
var exponent = Mathf.Log(lineValue) / Mathf.Log(baseValue);
for (var x = 0; x < WIDTH; x++)
{
var t = (float)x / WIDTH;
var red = Mathf.Pow(t, exponent);
var color = new Color(red, 0, 0, 1);
if (y >= 32 && y < 160)
texture.SetPixel(x, y - 32, color);
}
}
texture.Apply();
return texture;
}
//#if UNITY_EDITOR
// [MenuItem("Light2D Debugging/Write Light Texture")]
// static public void WriteLightTexture()
// {
// var path = EditorUtility.SaveFilePanel("Save texture as PNG", "", "LightLookupTexture.exr", "png");
// CreatePointLightLookupTexture();
// byte[] imgData = s_PointLightLookupTexture.EncodeToEXR(Texture2D.EXRFlags.CompressRLE);
// if (imgData != null)
// File.WriteAllBytes(path, imgData);
// }
// [MenuItem("Light2D Debugging/Write Falloff Texture")]
// static public void WriteCurveTexture()
// {
// var path = EditorUtility.SaveFilePanel("Save texture as PNG", "", "FalloffLookupTexture.png", "png");
// CreateFalloffLookupTexture();
// byte[] imgData = s_FalloffLookupTexture.EncodeToPNG();
// if (imgData != null)
// File.WriteAllBytes(path, imgData);
// }
//#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fed3c64eff8b51649bfa3da654d69182
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,262 @@
using Unity.Collections;
using Unity.Mathematics;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Rendering.Universal.U2D.Profiler;
namespace UnityEngine.Rendering.Universal
{
internal class LightBuffer
{
static readonly internal int kMax = 2048 * 8;
static readonly internal int kCount = 1;
static readonly internal int kLightMod = 64;
static readonly internal int kBatchMax = 256;
private GraphicsBuffer m_GraphicsBuffer;
private NativeArray<int> m_Markers = new NativeArray<int>(kBatchMax, Allocator.Persistent, NativeArrayOptions.ClearMemory);
private NativeArray<PerLight2D> m_NativeBuffer = new NativeArray<PerLight2D>(kMax, Allocator.Persistent, NativeArrayOptions.ClearMemory);
internal GraphicsBuffer graphicsBuffer
{
get
{
if (null == m_GraphicsBuffer)
m_GraphicsBuffer = new GraphicsBuffer(GraphicsBuffer.Target.Structured, kMax, UnsafeUtility.SizeOf<PerLight2D>());
return m_GraphicsBuffer;
}
}
internal NativeArray<int> lightMarkers
{
get
{
return m_Markers;
}
}
internal NativeArray<PerLight2D> nativeBuffer
{
get
{
return m_NativeBuffer;
}
}
internal void Release()
{
m_GraphicsBuffer.Release();
m_GraphicsBuffer = null;
}
internal void Reset()
{
unsafe { UnsafeUtility.MemClear(m_Markers.GetUnsafePtr(), UnsafeUtility.SizeOf<int>() * LightBuffer.kBatchMax); }
unsafe { UnsafeUtility.MemClear(m_NativeBuffer.GetUnsafePtr(), UnsafeUtility.SizeOf<PerLight2D>() * LightBuffer.kMax); }
}
}
// The idea is to avoid CPU cost when rendering meshes with the same shader (Consider this a light-weight SRP batcher). To identify the Mesh instance ID in the Light Buffer we utilize a Slot Index
// identified from the Blue Channel of the Vertex Colors (Solely used for this purpose). This can batch a maximum of kLightMod meshes in best-case scenario. Simple but no optizations have been added yet
internal class LightBatch
{
static readonly int k_BufferOffset = Shader.PropertyToID("_BatchBufferOffset");
static int sBatchIndexCounter = 0; // For LightMesh asset conditioning to facilitate batching.
private static int batchLightMod => LightBuffer.kLightMod;
private static float batchRunningIndex => (sBatchIndexCounter++) % LightBuffer.kLightMod / (float)LightBuffer.kLightMod;
// Should be in Sync with USE_STRUCTURED_BUFFER_FOR_LIGHT2D_DATA
public static bool isBatchingSupported => false;
private int[] subsets = new int[LightBuffer.kMax];
private Mesh[] lightMeshes = new Mesh[LightBuffer.kMax];
private Matrix4x4[] matrices = new Matrix4x4[LightBuffer.kMax];
private LightBuffer[] lightBuffer = new LightBuffer[LightBuffer.kCount];
private Light2D cachedLight;
private Material cachedMaterial;
private int hashCode = 0;
private int lightCount = 0;
private int maxIndex = 0;
private int batchCount = 0;
private int activeCount = 0;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod]
static void ResetStaticsOnLoad()
{
sBatchIndexCounter = 0;
}
#endif
internal NativeArray<PerLight2D> nativeBuffer
{
get
{
if (null == lightBuffer[activeCount])
lightBuffer[activeCount] = new LightBuffer();
return lightBuffer[activeCount].nativeBuffer;
}
}
internal GraphicsBuffer graphicsBuffer
{
get
{
if (null == lightBuffer[activeCount])
lightBuffer[activeCount] = new LightBuffer();
return lightBuffer[activeCount].graphicsBuffer;
}
}
internal NativeArray<int> lightMarker
{
get
{
if (null == lightBuffer[activeCount])
lightBuffer[activeCount] = new LightBuffer();
return lightBuffer[activeCount].lightMarkers;
}
}
internal PerLight2D GetLight(int index) => nativeBuffer[index];
internal static int batchSlotIndex => (int)(batchRunningIndex * LightBuffer.kLightMod);
#if UNITY_EDITOR
static bool kRegisterCallback = false;
#endif
internal void SetLight(int index, PerLight2D light)
{
var buffer = nativeBuffer;
buffer[index] = light;
}
internal static float GetBatchColor()
{
return (float)batchSlotIndex / (float)batchLightMod;
}
internal static int GetBatchSlotIndex(float channelColor)
{
return (int)(channelColor * LightBuffer.kLightMod);
}
static int Hash(Light2D light, Material material)
{
unchecked
{
int _hashCode = (int)2166136261;
_hashCode = _hashCode * 16777619 ^ material.GetHashCode();
_hashCode = _hashCode * 16777619 ^ (light.lightCookieSprite == null ? 0 : light.lightCookieSprite.GetHashCode());
return _hashCode;
}
}
void Validate()
{
#if UNITY_EDITOR
if (!kRegisterCallback)
UnityEditor.AssemblyReloadEvents.beforeAssemblyReload += Release;
kRegisterCallback = true;
#endif
}
internal void Release()
{
for (int i = 0; i < LightBuffer.kCount; ++i)
lightBuffer[i]?.Release();
}
void ResetInternals()
{
for (int i = 0; i < LightBuffer.kCount; ++i)
if (null != lightBuffer[i])
lightBuffer[i].Reset();
}
void SetBuffer()
{
Validate();
graphicsBuffer.SetData(nativeBuffer, lightCount, lightCount, math.min(LightBuffer.kBatchMax, LightBuffer.kMax - lightCount));
}
internal int SlotIndex(int x)
{
return lightCount + x;
}
internal void Reset()
{
if (isBatchingSupported)
{
maxIndex = 0;
hashCode = 0;
batchCount = 0;
lightCount = 0;
activeCount = 0;
Shader.SetGlobalBuffer("_Light2DBuffer", graphicsBuffer);
}
}
internal bool CanBatch(Light2D light, Material material, int index, out int lightHash)
{
if (material == null || light.lightMesh == null)
{
lightHash = 0;
return false;
}
lightHash = Hash(light, material);
hashCode = (hashCode == 0) ? lightHash : hashCode;
if (batchCount == 0)
{
hashCode = lightHash;
}
else if (hashCode != lightHash || SlotIndex(index) >= LightBuffer.kMax || lightMarker[index] == 1)
{
hashCode = lightHash;
return false;
}
return true;
}
internal bool AddBatch(Light2D light, Material material, Matrix4x4 mat, Mesh mesh, int subset, int lightHash, int index)
{
Debug.Assert(lightHash == hashCode);
cachedLight = light;
cachedMaterial = material;
matrices[batchCount] = mat;
lightMeshes[batchCount] = mesh;
subsets[batchCount] = subset;
batchCount++;
maxIndex = math.max(maxIndex, index);
var lightMark = lightMarker;
lightMark[index] = 1;
return true;
}
internal void Flush(RasterCommandBuffer cmd)
{
if (batchCount > 0)
{
using (new ProfilingScope(cmd, ProfilerMarkers.s_ProfilingDrawBatched))
{
SetBuffer();
cmd.SetGlobalInt(k_BufferOffset, lightCount);
cmd.DrawMultipleMeshes(matrices, lightMeshes, subsets, batchCount, cachedMaterial, -1, null);
}
lightCount = lightCount + maxIndex + 1;
}
#if ENABLE_PROFILER && PROFILER_INSTALLED
if (Renderer2D.canProfilerCapture)
ProfilerMarkers.s_U2DLightBatchCounterValue.Value++;
#endif
for (int i = 0; i < batchCount; ++i)
lightMeshes[i] = null;
ResetInternals();
batchCount = 0;
maxIndex = 0;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c67e061ed96500e4ba8ddeabc5f46958
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,364 @@
using UnityEngine.Experimental.Rendering;
using Unity.Mathematics;
namespace UnityEngine.Rendering.Universal
{
internal static class RendererLighting
{
public static readonly Color k_NormalClearColor = new Color(0.5f, 0.5f, 0.5f, 1.0f);
private static readonly string k_UsePointLightCookiesKeyword = "USE_POINT_LIGHT_COOKIES";
private static readonly string k_LightQualityFastKeyword = "LIGHT_QUALITY_FAST";
private static readonly string k_UseNormalMap = "USE_NORMAL_MAP";
private static readonly string k_UseShadowMap = "USE_SHADOW_MAP";
private static readonly string k_UseAdditiveBlendingKeyword = "USE_ADDITIVE_BLENDING";
private static readonly string k_UseVolumetric = "USE_VOLUMETRIC";
private static readonly string[] k_UseBlendStyleKeywords =
{
"USE_SHAPE_LIGHT_TYPE_0", "USE_SHAPE_LIGHT_TYPE_1", "USE_SHAPE_LIGHT_TYPE_2", "USE_SHAPE_LIGHT_TYPE_3"
};
private static readonly int[] k_BlendFactorsPropIDs =
{
Shader.PropertyToID("_ShapeLightBlendFactors0"),
Shader.PropertyToID("_ShapeLightBlendFactors1"),
Shader.PropertyToID("_ShapeLightBlendFactors2"),
Shader.PropertyToID("_ShapeLightBlendFactors3")
};
private static readonly int[] k_MaskFilterPropIDs =
{
Shader.PropertyToID("_ShapeLightMaskFilter0"),
Shader.PropertyToID("_ShapeLightMaskFilter1"),
Shader.PropertyToID("_ShapeLightMaskFilter2"),
Shader.PropertyToID("_ShapeLightMaskFilter3")
};
private static readonly int[] k_InvertedFilterPropIDs =
{
Shader.PropertyToID("_ShapeLightInvertedFilter0"),
Shader.PropertyToID("_ShapeLightInvertedFilter1"),
Shader.PropertyToID("_ShapeLightInvertedFilter2"),
Shader.PropertyToID("_ShapeLightInvertedFilter3")
};
public static readonly string[] k_ShapeLightTextureIDs =
{
"_ShapeLightTexture0",
"_ShapeLightTexture1",
"_ShapeLightTexture2",
"_ShapeLightTexture3"
};
private static GraphicsFormat s_RenderTextureFormatToUse = GraphicsFormat.R8G8B8A8_UNorm;
private static bool s_HasSetupRenderTextureFormatToUse;
private static readonly int k_SrcBlendID = Shader.PropertyToID("_SrcBlend");
private static readonly int k_DstBlendID = Shader.PropertyToID("_DstBlend");
private static readonly int k_CookieTexID = Shader.PropertyToID("_CookieTex");
private static readonly int k_PointLightCookieTexID = Shader.PropertyToID("_PointLightCookieTex");
private static readonly int k_L2DInvMatrix = Shader.PropertyToID("L2DInvMatrix");
private static readonly int k_L2DColor = Shader.PropertyToID("L2DColor");
private static readonly int k_L2DPosition = Shader.PropertyToID("L2DPosition");
private static readonly int k_L2DFalloffIntensity = Shader.PropertyToID("L2DFalloffIntensity");
private static readonly int k_L2DFalloffDistance = Shader.PropertyToID("L2DFalloffDistance");
private static readonly int k_L2DOuterAngle = Shader.PropertyToID("L2DOuterAngle");
private static readonly int k_L2DInnerAngle = Shader.PropertyToID("L2DInnerAngle");
private static readonly int k_L2DInnerRadiusMult = Shader.PropertyToID("L2DInnerRadiusMult");
private static readonly int k_L2DVolumeOpacity = Shader.PropertyToID("L2DVolumeOpacity");
private static readonly int k_L2DShadowIntensity = Shader.PropertyToID("L2DShadowIntensity");
private static readonly int k_L2DLightType = Shader.PropertyToID("L2DLightType");
private static readonly int k_L2DLightRenderingLayer = Shader.PropertyToID("L2DLightRenderingLayer");
// Light Batcher.
internal static LightBatch lightBatch = new LightBatch();
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod]
static void ResetStaticsOnLoad()
{
s_HasSetupRenderTextureFormatToUse = false;
s_RenderTextureFormatToUse = GraphicsFormat.R8G8B8A8_UNorm;
lightBatch.Release();
lightBatch = new LightBatch();
}
#endif
internal static GraphicsFormat GetRenderTextureFormat()
{
if (!s_HasSetupRenderTextureFormatToUse)
{
// UUM-41070: We require `Linear | Render` but with the deprecated FormatUsage this was checking `Blend`
// For now, we keep checking for `Blend` until the performance hit of doing the correct checks is evaluated
if (SystemInfo.IsFormatSupported(GraphicsFormat.B10G11R11_UFloatPack32, GraphicsFormatUsage.Blend))
s_RenderTextureFormatToUse = GraphicsFormat.B10G11R11_UFloatPack32;
else if (SystemInfo.IsFormatSupported(GraphicsFormat.R16G16B16A16_SFloat, GraphicsFormatUsage.Blend))
s_RenderTextureFormatToUse = GraphicsFormat.R16G16B16A16_SFloat;
s_HasSetupRenderTextureFormatToUse = true;
}
return s_RenderTextureFormatToUse;
}
internal static void EnableBlendStyle(IRasterCommandBuffer cmd, int blendStyleIndex, bool enabled)
{
var keyword = k_UseBlendStyleKeywords[blendStyleIndex];
if (enabled)
cmd.EnableShaderKeyword(keyword);
else
cmd.DisableShaderKeyword(keyword);
}
internal static void DisableAllKeywords(IRasterCommandBuffer cmd)
{
foreach (var keyword in k_UseBlendStyleKeywords)
{
cmd.DisableShaderKeyword(keyword);
}
}
internal static void GetTransparencySortingMode(Renderer2DData rendererData, Camera camera, ref SortingSettings sortingSettings)
{
var mode = rendererData.transparencySortMode;
if (mode == TransparencySortMode.Default)
{
mode = camera.orthographic ? TransparencySortMode.Orthographic : TransparencySortMode.Perspective;
}
switch (mode)
{
case TransparencySortMode.Perspective:
sortingSettings.distanceMetric = DistanceMetric.Perspective;
break;
case TransparencySortMode.Orthographic:
sortingSettings.distanceMetric = DistanceMetric.Orthographic;
break;
default:
sortingSettings.distanceMetric = DistanceMetric.CustomAxis;
sortingSettings.customAxis = rendererData.transparencySortAxis;
break;
}
}
internal static bool CanCastShadows(Light2D light, int layerToRender)
{
return light.shadowsEnabled && light.shadowIntensity > 0 && light.IsLitLayer(layerToRender);
}
internal static bool CanCastVolumetricShadows(Light2D light, int endLayerValue)
{
return light.volumeIntensity > 0 && light.volumetricEnabled && light.renderVolumetricShadows && light.GetTopMostLitLayer() == endLayerValue;
}
internal static void SetLightShaderGlobals(IRasterCommandBuffer cmd, Light2DBlendStyle[] lightBlendStyles, int[] blendStyleIndices)
{
for (var i = 0; i < blendStyleIndices.Length; i++)
{
var blendStyleIndex = blendStyleIndices[i];
if (blendStyleIndex >= k_BlendFactorsPropIDs.Length)
break;
var blendStyle = lightBlendStyles[blendStyleIndex];
cmd.SetGlobalVector(k_BlendFactorsPropIDs[blendStyleIndex], blendStyle.blendFactors);
cmd.SetGlobalVector(k_MaskFilterPropIDs[blendStyleIndex], blendStyle.maskTextureChannelFilter.mask);
cmd.SetGlobalVector(k_InvertedFilterPropIDs[blendStyleIndex], blendStyle.maskTextureChannelFilter.inverted);
}
}
private static float GetNormalizedInnerRadius(Light2D light)
{
return light.pointLightInnerRadius / light.pointLightOuterRadius;
}
private static float GetNormalizedAngle(float angle)
{
return (angle / 360.0f);
}
private static void GetScaledLightInvMatrix(Light2D light, out Matrix4x4 retMatrix)
{
var outerRadius = light.pointLightOuterRadius;
var lightScale = Vector3.one;
var outerRadiusScale = new Vector3(lightScale.x * outerRadius, lightScale.y * outerRadius, lightScale.z * outerRadius);
var transform = light.transform;
var scaledLightMat = Matrix4x4.TRS(transform.position, transform.rotation, outerRadiusScale);
retMatrix = Matrix4x4.Inverse(scaledLightMat);
}
internal static void SetPerLightShaderGlobals(IRasterCommandBuffer cmd, Light2D light, int slot, bool isVolumetric, bool hasShadows, bool batchingSupported)
{
float intensity = light.intensity * light.color.a;
Color color = intensity * light.color;
color.a = 1.0f;
float volumeIntensity = light.volumetricEnabled ? light.volumeIntensity : 1.0f;
if (batchingSupported)
{
// Batched Params.
PerLight2D perLight = lightBatch.GetLight(slot);
perLight.Position = new float4(light.transform.position, light.normalMapDistance);
perLight.FalloffIntensity = light.falloffIntensity;
perLight.FalloffDistance = light.shapeLightFalloffSize;
perLight.Color = new float4(color.r, color.g, color.b, color.a);
perLight.VolumeOpacity = volumeIntensity;
perLight.LightType = (int)light.lightType;
perLight.ShadowIntensity = 1.0f;
if (hasShadows)
perLight.ShadowIntensity = isVolumetric ? (1 - light.shadowVolumeIntensity) : (1 - light.shadowIntensity);
lightBatch.SetLight(slot, perLight);
}
else
{
cmd.SetGlobalVector(k_L2DPosition, new float4(light.transform.position, light.normalMapDistance));
cmd.SetGlobalFloat(k_L2DFalloffIntensity, light.falloffIntensity);
cmd.SetGlobalFloat(k_L2DFalloffDistance, light.shapeLightFalloffSize);
cmd.SetGlobalColor(k_L2DColor, color);
cmd.SetGlobalFloat(k_L2DVolumeOpacity, volumeIntensity);
cmd.SetGlobalInt(k_L2DLightType, (int)light.lightType);
cmd.SetGlobalInt(k_L2DLightRenderingLayer, (int)light.renderingLayerMask.value);
cmd.SetGlobalFloat(k_L2DShadowIntensity, hasShadows ? (isVolumetric ? (1 - light.shadowVolumeIntensity) : (1 - light.shadowIntensity)) : 1);
}
if (hasShadows)
ShadowRendering.SetGlobalShadowProp(cmd);
}
internal static void SetPerPointLightShaderGlobals(IRasterCommandBuffer cmd, Light2D light, int slot, bool batchingSupported)
{
// This is used for the lookup texture
GetScaledLightInvMatrix(light, out var lightInverseMatrix);
var innerRadius = GetNormalizedInnerRadius(light);
var innerAngle = GetNormalizedAngle(light.pointLightInnerAngle);
var outerAngle = GetNormalizedAngle(light.pointLightOuterAngle);
var innerRadiusMult = 1 / (1 - innerRadius);
if (batchingSupported)
{
// Batched Params.
PerLight2D perLight = lightBatch.GetLight(slot);
perLight.InvMatrix = new float4x4(lightInverseMatrix.GetColumn(0), lightInverseMatrix.GetColumn(1), lightInverseMatrix.GetColumn(2), lightInverseMatrix.GetColumn(3));
perLight.InnerRadiusMult = innerRadiusMult;
perLight.InnerAngle = innerAngle;
perLight.OuterAngle = outerAngle;
lightBatch.SetLight(slot, perLight);
}
else
{
cmd.SetGlobalMatrix(k_L2DInvMatrix, lightInverseMatrix);
cmd.SetGlobalFloat(k_L2DInnerRadiusMult, innerRadiusMult);
cmd.SetGlobalFloat(k_L2DInnerAngle, innerAngle);
cmd.SetGlobalFloat(k_L2DOuterAngle, outerAngle);
}
}
internal static void SetCookieShaderProperties(Light2D light, MaterialPropertyBlock properties)
{
if (light.useCookieSprite && light.m_CookieSpriteTextureHandle.IsValid())
properties.SetTexture(light.lightType == Light2D.LightType.Sprite ? k_CookieTexID : k_PointLightCookieTexID, light.m_CookieSpriteTextureHandle);
}
private static void SetBlendModes(Material material, BlendMode src, BlendMode dst)
{
material.SetFloat(k_SrcBlendID, (float)src);
material.SetFloat(k_DstBlendID, (float)dst);
}
private static uint GetLightMaterialIndex(Light2D light, bool isVolume, bool useShadows)
{
var isPoint = light.isPointLight;
var bitIndex = 0;
var volumeBit = isVolume ? 1u << bitIndex : 0u;
bitIndex++;
var shapeBit = (isVolume && !isPoint) ? 1u << bitIndex : 0u;
bitIndex++;
var additiveBit = light.overlapOperation == Light2D.OverlapOperation.AlphaBlend ? 0u : 1u << bitIndex;
bitIndex++;
var pointCookieBit = (isPoint && light.lightCookieSprite != null && light.lightCookieSprite.texture != null) ? 1u << bitIndex : 0u;
bitIndex++;
var fastQualityBit = (light.normalMapQuality == Light2D.NormalMapQuality.Fast) ? 1u << bitIndex : 0u;
bitIndex++;
var useNormalMap = light.normalMapQuality != Light2D.NormalMapQuality.Disabled ? 1u << bitIndex : 0u;
bitIndex++;
var useShadowMap = useShadows ? 1u << bitIndex : 0u;
return fastQualityBit | pointCookieBit | additiveBit | shapeBit | volumeBit | useNormalMap | useShadowMap;
}
private static Material CreateLightMaterial(Renderer2DData rendererData, Light2D light, bool isVolume, bool useShadows)
{
if (!GraphicsSettings.TryGetRenderPipelineSettings<Renderer2DResources>(out var resources))
return null;
var isPoint = light.isPointLight;
Material material = CoreUtils.CreateEngineMaterial(resources.lightShader);
if (!isVolume)
{
if (light.overlapOperation == Light2D.OverlapOperation.Additive)
{
SetBlendModes(material, BlendMode.One, BlendMode.One);
material.EnableKeyword(k_UseAdditiveBlendingKeyword);
}
else
SetBlendModes(material, BlendMode.SrcAlpha, BlendMode.OneMinusSrcAlpha);
}
else
{
material.EnableKeyword(k_UseVolumetric);
if (light.lightType == Light2D.LightType.Point)
SetBlendModes(material, BlendMode.One, BlendMode.One);
else
SetBlendModes(material, BlendMode.SrcAlpha, BlendMode.One);
}
if (isPoint && light.lightCookieSprite != null && light.lightCookieSprite.texture != null)
material.EnableKeyword(k_UsePointLightCookiesKeyword);
if (light.normalMapQuality == Light2D.NormalMapQuality.Fast)
material.EnableKeyword(k_LightQualityFastKeyword);
if (light.normalMapQuality != Light2D.NormalMapQuality.Disabled)
material.EnableKeyword(k_UseNormalMap);
if (useShadows)
material.EnableKeyword(k_UseShadowMap);
return material;
}
internal static Material GetLightMaterial(this Renderer2DData rendererData, Light2D light, bool isVolume, bool useShadows)
{
var materialIndex = GetLightMaterialIndex(light, isVolume, useShadows);
if (!rendererData.lightMaterials.TryGetValue(materialIndex, out var material))
{
material = CreateLightMaterial(rendererData, light, isVolume, useShadows);
rendererData.lightMaterials[materialIndex] = material;
}
return material;
}
internal static short GetCameraSortingLayerBoundsIndex(this Renderer2DData rendererData)
{
SortingLayer[] sortingLayers = Light2DManager.GetCachedSortingLayer();
for (short i = 0; i < sortingLayers.Length; i++)
{
if (sortingLayers[i].id == rendererData.cameraSortingLayerTextureBound)
return (short)sortingLayers[i].value;
}
return short.MinValue;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7978073cb0cd25f4f8e29b37e3f55d2a
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant: