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,806 @@
using System;
using UnityEngine.Serialization;
using UnityEngine.Scripting.APIUpdating;
using UnityEngine.U2D;
using UnityEngine.Rendering.RenderGraphModule;
using System.Collections.Generic;
namespace UnityEngine.Rendering.Universal
{
/// <summary>
/// Class <c>Light2D</c> is a 2D light which can be used with the 2D Renderer.
/// </summary>
///
[ExecuteAlways, DisallowMultipleComponent]
[Icon("UnityEngine/Light Icon")]
[MovedFrom(true, "UnityEngine.Experimental.Rendering.Universal", "Unity.RenderPipelines.Universal.Runtime")]
[AddComponentMenu("Rendering/2D/Light 2D")]
[HelpURL("https://docs.unity3d.com/Packages/com.unity.render-pipelines.universal@latest/index.html?subfolder=/manual/2DLightProperties.html")]
public sealed partial class Light2D : Light2DBase, ISerializationCallbackReceiver
{
/// <summary>
/// Deprecated Light types that are no supported. Please migrate to either Freeform or Point lights.
/// </summary>
public enum DeprecatedLightType
{
/// <summary>
/// N-gon shaped lights.
/// </summary>
Parametric = 0,
}
/// <summary>
/// An enumeration of the types of light
/// </summary>
public enum LightType
{
/// <summary>
/// N-gon shaped lights. Deprecated.
/// </summary>
Parametric = 0,
/// <summary>
/// The shape of the light is based on a user defined closed shape with multiple points.
/// </summary>
Freeform = 1,
/// <summary>
/// The shape of the light is based on a Sprite.
/// </summary>
Sprite = 2,
/// <summary>
/// The shape of light is circular and can also be configured into a pizza shape.
/// </summary>
Point = 3,
/// <summary>
/// Shapeless light that affects the entire screen.
/// </summary>
Global = 4,
/// <summary>
/// Light completely supplied by a provider
/// </summary>
Provider = 5,
}
/// <summary>
/// The accuracy of how the normal map calculation.
/// </summary>
public enum NormalMapQuality
{
/// <summary>
/// Normal map not used.
/// </summary>
Disabled = 2,
/// <summary>
/// Faster calculation with less accuracy suited for small shapes on screen.
/// </summary>
Fast = 0,
/// <summary>
/// Accurate calculation useful for better output on bigger shapes on screen.
/// </summary>
Accurate = 1
}
/// <summary>
/// Determines how the final color is calculated when multiple lights overlap each other
/// </summary>
public enum OverlapOperation
{
/// <summary>
/// Colors are added together
/// </summary>
Additive,
/// <summary>
/// Colors are blended using standard blending (alpha, 1-alpha)
/// </summary>
AlphaBlend
}
private enum ComponentVersions
{
Version_Unserialized = 0,
Version_1 = 1,
Version_2 = 2,
Version_3 = 3,
Version_4 = 4
}
const ComponentVersions k_CurrentComponentVersion = ComponentVersions.Version_4;
[SerializeField] ComponentVersions m_ComponentVersion = ComponentVersions.Version_Unserialized;
static Bounds kEmptyBounds = new Bounds(Vector3.zero, Vector3.zero);
#if USING_ANIMATION_MODULE
[UnityEngine.Animations.NotKeyable]
#endif
[SerializeField] LightType m_LightType = LightType.Point;
[SerializeField, FormerlySerializedAs("m_LightOperationIndex")]
int m_BlendStyleIndex = 0;
[SerializeReference] Light2DProvider m_Light2DProvider;
#if UNITY_EDITOR
[SerializeReference] Light2DProviderSources m_SelectionSources = new Light2DProviderSources();
#endif
[SerializeField] float m_FalloffIntensity = 0.5f;
[ColorUsage(true)]
[SerializeField] Color m_Color = Color.white;
[SerializeField] float m_Intensity = 1;
[FormerlySerializedAs("m_LightVolumeOpacity")]
[SerializeField] float m_LightVolumeIntensity = 1.0f;
[FormerlySerializedAs("m_LightVolumeIntensityEnabled")]
[SerializeField] bool m_LightVolumeEnabled = false;
[SerializeField] int[] m_ApplyToSortingLayers; // These are sorting layer IDs. If we need to update this at runtime make sure we add code to update global lights
[Reload("Textures/2D/Sparkle.png")]
[SerializeField] Sprite m_LightCookieSprite;
[Obsolete("Use m_LightCookieSprite instead")]
[SerializeField] Sprite m_DeprecatedPointLightCookieSprite;
[SerializeField] int m_LightOrder = 0;
[SerializeField] bool m_AlphaBlendOnOverlap = false; // This is now deprecated. Keep it here for backwards compatibility.
[SerializeField] OverlapOperation m_OverlapOperation = OverlapOperation.Additive;
[FormerlySerializedAs("m_PointLightDistance")]
[SerializeField] float m_NormalMapDistance = 3.0f;
#if USING_ANIMATION_MODULE
[UnityEngine.Animations.NotKeyable]
#endif
[FormerlySerializedAs("m_PointLightQuality")]
[SerializeField] NormalMapQuality m_NormalMapQuality = NormalMapQuality.Disabled;
[SerializeField] bool m_UseNormalMap = false; // This is now deprecated. Keep it here for backwards compatibility.
[FormerlySerializedAs("m_ShadowIntensityEnabled")]
[SerializeField] bool m_ShadowsEnabled = true;
[Range(0, 1)]
[SerializeField] float m_ShadowIntensity = 0.75f;
[Range(0, 1)]
[SerializeField] float m_ShadowSoftness = 0.3f;
[Range(0, 1)]
[SerializeField] float m_ShadowSoftnessFalloffIntensity = 0.5f;
[SerializeField] bool m_ShadowVolumeIntensityEnabled = false;
[Range(0, 1)]
[SerializeField] float m_ShadowVolumeIntensity = 0.75f;
[SerializeField] RenderingLayerMask m_RenderingLayersMask = RenderingLayerMask.defaultRenderingLayerMask;
Mesh m_Mesh;
// m_Mesh either points at a Mesh this component allocated through lightMesh, or at one handed over by
// Light2DProvider.GetMesh(). That contract only returns a mesh to render and does not transfer ownership,
// so provider meshes may be shared between lights and must never be destroyed from here.
bool m_OwnsMesh;
[NonSerialized]
private LightUtility.LightMeshVertex[] m_Vertices = new LightUtility.LightMeshVertex[1];
[NonSerialized]
private ushort[] m_Triangles = new ushort[1];
internal LightUtility.LightMeshVertex[] vertices { get { return m_Vertices; } set { m_Vertices = value; } }
internal ushort[] indices { get { return m_Triangles; } set { m_Triangles = value; } }
// Transients
EntityId m_PreviousLightCookieSprite;
internal Vector3 m_CachedPosition;
// We use Blue Channel of LightMesh's vertex color to indicate Slot Index.
int m_BatchSlotIndex = 0;
internal int batchSlotIndex { get { return m_BatchSlotIndex; } set { m_BatchSlotIndex = value; } }
private EntityId lightCookieSpriteEntityId => lightCookieSprite?.GetEntityId() ?? EntityId.None;
internal bool useCookieSprite => (lightType == LightType.Point || lightType == LightType.Sprite) && (lightCookieSprite != null && lightCookieSprite.texture != null);
internal RTHandle m_CookieSpriteTexture = null;
internal TextureHandle m_CookieSpriteTextureHandle;
[SerializeField]
Bounds m_LocalBounds;
internal BoundingSphere boundingSphere { get; private set; }
internal Mesh lightMesh
{
get
{
if (null == m_Mesh)
{
m_Mesh = new Mesh();
m_OwnsMesh = true;
}
return m_Mesh;
}
}
// Takes the mesh a Light2DProvider handed us, releasing any mesh we allocated ourselves first so replacing
// it does not leak.
void SetProviderMesh(Mesh providerMesh)
{
// A provider is free to hand back the mesh we already hold, in which case ownership is unchanged.
if (m_Mesh == providerMesh)
return;
if (m_OwnsMesh)
CoreUtils.Destroy(m_Mesh);
m_Mesh = providerMesh;
m_OwnsMesh = false;
}
internal bool hasCachedMesh => (vertices.Length > 1 && indices.Length > 1);
internal bool forceUpdate = false;
/// <summary>
/// The light's current type
/// </summary>
public LightType lightType
{
get { return (LightType)m_LightType; }
set
{
m_LightType = value;
#if UNITY_EDITOR
if((int)m_LightType != (int)LightType.Provider)
m_SelectionSources.selectedHashCode = (int)m_LightType;
#endif
}
}
/// <summary>
/// Gets or sets the current light2DProvider
/// </summary>
public Light2DProvider light2DProvider
{
get { return m_Light2DProvider; }
set { m_Light2DProvider = value; }
}
/// <summary>
/// The lights current operation index
/// </summary>
public int blendStyleIndex { get => m_BlendStyleIndex; set => m_BlendStyleIndex = value; }
/// <summary>
/// Specifies the darkness of the shadow
/// </summary>
public float shadowIntensity { get => m_ShadowIntensity; set => m_ShadowIntensity = Mathf.Clamp01(value); }
/// <summary>
/// Specifies the softness of the soft shadow
/// </summary>
public float shadowSoftness { get => m_ShadowSoftness; set => m_ShadowSoftness = value; }
/// <summary>
/// Specifies that the shadows are enabled
/// </summary>
public bool shadowsEnabled { get => m_ShadowsEnabled; set => m_ShadowsEnabled = value; }
/// <summary>
/// Specifies the darkness of the shadow
/// </summary>
public float shadowVolumeIntensity { get => m_ShadowVolumeIntensity; set => m_ShadowVolumeIntensity = Mathf.Clamp01(value); }
/// <summary>
/// Specifies that the volumetric shadows are enabled
/// </summary>
public bool volumetricShadowsEnabled { get => m_ShadowVolumeIntensityEnabled; set => m_ShadowVolumeIntensityEnabled = value; }
/// <summary>
/// The lights current color
/// </summary>
public Color color { get => m_Color; set => m_Color = value; }
/// <summary>
/// The lights current intensity
/// </summary>
public float intensity { get => m_Intensity; set => m_Intensity = value; }
/// <summary>
/// The lights current intensity
/// </summary>
///
[Obsolete("#from(2021.1)")]
public float volumeOpacity => m_LightVolumeIntensity;
/// <summary>
/// Controls the visibility of the light's volume
/// </summary>
public float volumeIntensity { get => m_LightVolumeIntensity; set => m_LightVolumeIntensity = value; }
/// <summary>
/// Enables or disables the light's volume
/// </summary>
///
[Obsolete("#from(2023.1)")]
public bool volumeIntensityEnabled { get => m_LightVolumeEnabled; set => m_LightVolumeEnabled = value; }
/// <summary>
/// Enables or disables the light's volume
/// </summary>
///
public bool volumetricEnabled { get => m_LightVolumeEnabled; set => m_LightVolumeEnabled = value; }
/// <summary>
/// The Sprite that's used by the Sprite Light type to control the shape light
/// </summary>
public Sprite lightCookieSprite { get { return m_LightCookieSprite; } set => m_LightCookieSprite = value; }
/// <summary>
/// Controls the brightness and distance of the fall off (edge) of the light
/// </summary>
public float falloffIntensity { get => m_FalloffIntensity; set => m_FalloffIntensity = Mathf.Clamp(value, 0, 1); }
/// <summary>
/// Controls the falloff for soft shadows
/// </summary>
public float shadowSoftnessFalloffIntensity { get => m_ShadowSoftnessFalloffIntensity; set => m_ShadowSoftnessFalloffIntensity = Mathf.Clamp(value, 0, 1); }
/// <summary>
/// Checks if the alpha overlap operation is alpha blend.
/// This is obsolete.
/// </summary>
[Obsolete("#from(2021.1)")]
public bool alphaBlendOnOverlap { get { return m_OverlapOperation == OverlapOperation.AlphaBlend; } }
/// <summary>
/// Controls the overlap operation mode.
/// </summary>
public OverlapOperation overlapOperation { get => m_OverlapOperation; set => m_OverlapOperation = value; }
/// <summary>
/// Gets or sets the light order. The lightOrder determines the order in which the lights are rendered onto the light textures.
/// </summary>
public int lightOrder { get => m_LightOrder; set => m_LightOrder = value; }
/// <summary>
/// The simulated z distance of the light from the surface used in normal map calculation.
/// </summary>
public float normalMapDistance => m_NormalMapDistance;
/// <summary>
/// Returns the calculation quality for the normal map rendering. Please refer to NormalMapQuality.
/// </summary>
public NormalMapQuality normalMapQuality => m_NormalMapQuality;
/// <summary>
/// Returns if volumetric shadows should be rendered.
/// </summary>
public bool renderVolumetricShadows => volumetricShadowsEnabled && shadowVolumeIntensity > 0;
/// <summary>
/// Gets or sets the target sorting layers for the light. Contains an array of sorting layer IDs.
/// </summary>
public int[] targetSortingLayers
{
get => m_ApplyToSortingLayers;
set
{
var layers = new List<int>();
foreach (var layerID in value)
{
if (SortingLayer.IsValid(layerID))
layers.Add(layerID);
}
m_ApplyToSortingLayers = layers.ToArray();
}
}
/// <summary>
/// Gets or sets the rendering layer mask for the light.
/// </summary>
public RenderingLayerMask renderingLayerMask
{
get { return m_RenderingLayersMask; }
set
{
m_RenderingLayersMask = value;
}
}
bool IsValidLayer(string name)
{
// Have this check as SortingLayer.NameToID returns 0 (default layer) if layer is not found
foreach (var layer in Light2DManager.GetCachedSortingLayer())
{
if (layer.name == name)
return true;
}
return false;
}
/// <summary>
/// Adds a target sorting layer to the light.
/// </summary>
/// <param name="layerName">The sorting layer name to be added.</param>
/// <returns>Returns true if the sorting layer is added. Returns false if the layer name is invalid or has already been added.</returns>
public bool AddTargetSortingLayer(string layerName)
{
var layers = new List<int>(m_ApplyToSortingLayers);
var id = SortingLayer.NameToID(layerName);
// Invalid or duplicate layerID
if (!IsValidLayer(layerName) || layers.Contains(id))
return false;
layers.Add(id);
m_ApplyToSortingLayers = layers.ToArray();
return true;
}
/// <summary>
/// Adds a target sorting layer to the light.
/// </summary>
/// <param name="layerID">The sorting layer ID to be added.</param>
/// <returns>Returns true if the sorting layer is added. Returns false if the layer ID is invalid or has already been added.</returns>
public bool AddTargetSortingLayer(int layerID)
{
return AddTargetSortingLayer(SortingLayer.IDToName(layerID));
}
/// <summary>
/// Removes a target sorting layer from the light.
/// </summary>
/// <param name="layerName">The sorting layer name to be removed.</param>
/// <returns>Returns true if the sorting layer is removed. Returns false if the layer name is invalid or doesn't exist.</returns>
public bool RemoveTargetSortingLayer(string layerName)
{
var layers = new List<int>(m_ApplyToSortingLayers);
var id = SortingLayer.NameToID(layerName);
// Invalid or layerID does not exist
if (!IsValidLayer(layerName) || !layers.Contains(id))
return false;
layers.Remove(id);
m_ApplyToSortingLayers = layers.ToArray();
return true;
}
/// <summary>
/// Removes a target sorting layer from the light.
/// </summary>
/// <param name="layerID">The sorting layer ID to be removed.</param>
/// <returns>Returns true if the sorting layer is removed. Returns false if the layer ID is invalid or doesn't exist.</returns>
public bool RemoveTargetSortingLayer(int layerID)
{
return RemoveTargetSortingLayer(SortingLayer.IDToName(layerID));
}
internal void MarkForUpdate()
{
forceUpdate = true;
}
internal void CacheValues()
{
m_CachedPosition = transform.position;
}
internal int GetTopMostLitLayer()
{
var largestIndex = Int32.MinValue;
var largestLayer = 0;
var layers = Light2DManager.GetCachedSortingLayer();
for (var i = 0; i < m_ApplyToSortingLayers.Length; ++i)
{
for (var layer = layers.Length - 1; layer >= largestLayer; --layer)
{
if (layers[layer].id == m_ApplyToSortingLayers[i])
{
largestIndex = layers[layer].value;
largestLayer = layer;
}
}
}
return largestIndex;
}
internal Bounds UpdateSpriteMesh()
{
if (m_LightCookieSprite == null && (m_Vertices.Length != 1 || m_Triangles.Length != 1))
{
m_Vertices = new LightUtility.LightMeshVertex[1];
m_Triangles = new ushort[1];
}
return LightUtility.GenerateSpriteMesh(this, m_LightCookieSprite, LightBatch.GetBatchColor());
}
internal void UpdateBatchSlotIndex()
{
if (lightMesh && lightMesh.colors != null && lightMesh.colors.Length != 0)
m_BatchSlotIndex = LightBatch.GetBatchSlotIndex(lightMesh.colors[0].b);
}
internal bool NeedsColorIndexBaking()
{
if (lightMesh && LightBatch.isBatchingSupported)
{
if (lightMesh.colors.Length != 0)
return lightMesh.colors[0].b == 0;
}
return false;
}
internal Bounds UpdateProviderMesh()
{
SetProviderMesh(light2DProvider.GetMesh());
if (m_Mesh != null)
return m_Mesh.bounds;
else
return kEmptyBounds;
}
internal void UpdateCookieSpriteTexture()
{
m_CookieSpriteTexture?.Release();
if (useCookieSprite)
m_CookieSpriteTexture = RTHandles.Alloc(lightCookieSprite.texture);
}
internal void UpdateMesh(bool forceUpdate = false)
{
var lightTypeChanged = LightUtility.CheckForChange(lightType, ref m_PreviousLightType);
if (lightType != LightType.Provider)
{
var shapePathHash = LightUtility.GetShapePathHash(shapePath);
var fallOffSizeChanged = LightUtility.CheckForChange(m_ShapeLightFalloffSize, ref m_PreviousShapeLightFalloffSize);
var parametricRadiusChanged = LightUtility.CheckForChange(m_ShapeLightParametricRadius, ref m_PreviousShapeLightParametricRadius);
var parametricSidesChanged = LightUtility.CheckForChange(m_ShapeLightParametricSides, ref m_PreviousShapeLightParametricSides);
var parametricAngleOffsetChanged = LightUtility.CheckForChange(m_ShapeLightParametricAngleOffset, ref m_PreviousShapeLightParametricAngleOffset);
var spriteInstanceChanged = LightUtility.CheckForChange(lightCookieSpriteEntityId, ref m_PreviousLightCookieSprite);
var shapePathHashChanged = LightUtility.CheckForChange(shapePathHash, ref m_PreviousShapePathHash);
var hashChanged = fallOffSizeChanged || parametricRadiusChanged || parametricSidesChanged ||
parametricAngleOffsetChanged || spriteInstanceChanged || shapePathHashChanged || lightTypeChanged || NeedsColorIndexBaking();
// Mesh Rebuilding
if (hashChanged || forceUpdate)
{
var batchChannelColor = LightBatch.GetBatchColor();
switch (lightType)
{
case LightType.Freeform:
m_LocalBounds = LightUtility.GenerateShapeMesh(this, m_ShapePath, m_ShapeLightFalloffSize, batchChannelColor);
break;
case LightType.Parametric:
m_LocalBounds = LightUtility.GenerateParametricMesh(this, m_ShapeLightParametricRadius, m_ShapeLightFalloffSize, m_ShapeLightParametricAngleOffset, m_ShapeLightParametricSides, batchChannelColor);
break;
case LightType.Sprite:
m_LocalBounds = UpdateSpriteMesh();
break;
case LightType.Point:
m_LocalBounds = LightUtility.GenerateParametricMesh(this, 1.412135f, 0, 0, 4, batchChannelColor);
break;
}
UpdateCookieSpriteTexture();
UpdateBatchSlotIndex();
}
}
else
{
if (light2DProvider != null)
{
if (m_Mesh != null)
{
SetProviderMesh(light2DProvider.GetMesh());
m_LocalBounds = m_Mesh.bounds;
}
}
else
{
m_Mesh.Clear();
m_LocalBounds = kEmptyBounds;
}
}
}
internal void UpdateBoundingSphere()
{
if (isPointLight)
{
boundingSphere = new BoundingSphere(transform.position, m_PointLightOuterRadius);
return;
}
var maxBound = transform.TransformPoint(Vector3.Max(m_LocalBounds.max, m_LocalBounds.max + (Vector3)m_ShapeLightFalloffOffset));
var minBound = transform.TransformPoint(Vector3.Min(m_LocalBounds.min, m_LocalBounds.min + (Vector3)m_ShapeLightFalloffOffset));
var center = 0.5f * (maxBound + minBound);
var radius = Vector3.Magnitude(maxBound - center);
boundingSphere = new BoundingSphere(center, radius);
}
internal bool IsLitLayer(int layer)
{
if (m_ApplyToSortingLayers == null)
return false;
for (var i = 0; i < m_ApplyToSortingLayers.Length; i++)
if (m_ApplyToSortingLayers[i] == layer)
return true;
return false;
}
internal Matrix4x4 GetMatrix()
{
var matrix = transform.localToWorldMatrix;
if (lightType == Light2D.LightType.Point)
{
var scale = new Vector3(pointLightOuterRadius, pointLightOuterRadius, pointLightOuterRadius);
matrix = Matrix4x4.TRS(transform.position, transform.rotation, scale);
}
return matrix;
}
private void Awake()
{
// Default target sorting layers to "All"
if (m_ApplyToSortingLayers == null)
{
m_ApplyToSortingLayers = new int[SortingLayer.layers.Length];
for (int i = 0; i < m_ApplyToSortingLayers.Length; ++i)
m_ApplyToSortingLayers[i] = SortingLayer.layers[i].id;
}
}
void OnEnable()
{
m_PreviousLightCookieSprite = lightCookieSpriteEntityId;
Light2DManager.RegisterLight(this);
UpdateCookieSpriteTexture();
#if UNITY_EDITOR
SortingLayer.onLayerAdded += OnSortingLayerAdded;
SortingLayer.onLayerRemoved += OnSortingLayerRemoved;
#endif
}
private void OnDestroy()
{
// Only the mesh we allocated ourselves is ours to destroy; a provider owns the one it returned.
if (m_OwnsMesh)
CoreUtils.Destroy(m_Mesh);
m_Mesh = null;
m_OwnsMesh = false;
}
private void OnDisable()
{
Light2DManager.DeregisterLight(this);
m_CookieSpriteTexture?.Release();
#if UNITY_EDITOR
SortingLayer.onLayerAdded -= OnSortingLayerAdded;
SortingLayer.onLayerRemoved -= OnSortingLayerRemoved;
#endif
}
private void LateUpdate()
{
if (lightType == LightType.Global)
return;
UpdateMesh(forceUpdate);
UpdateBoundingSphere();
forceUpdate = false;
}
#if UNITY_EDITOR
private void OnSortingLayerAdded(SortingLayer layer)
{
var newArray = new int[m_ApplyToSortingLayers.Length + 1];
for (int i = 0; i < m_ApplyToSortingLayers.Length; i++)
{
newArray[i] = m_ApplyToSortingLayers[i];
}
newArray[m_ApplyToSortingLayers.Length] = layer.id;
m_ApplyToSortingLayers = newArray;
}
private void OnSortingLayerRemoved(SortingLayer layer)
{
var tempList = new List<int>();
foreach (var x in m_ApplyToSortingLayers)
{
if (x != layer.id && SortingLayer.IsValid(x))
tempList.Add(x);
}
m_ApplyToSortingLayers = tempList.ToArray();
}
#endif
/// <summary>
/// OnBeforeSerialize implementation.
/// </summary>
public void OnBeforeSerialize()
{
m_ComponentVersion = k_CurrentComponentVersion;
}
// OnAfterDeserialize can run off the main thread, where the Unity null check throws.
// The Editor reads an unassigned reference as a fake null object, which has no entity ID.
static bool IsAssigned(UnityEngine.Object reference)
{
if ((object)reference == null)
return false;
#if UNITY_EDITOR
return reference.GetEntityIdForSerializationUnchecked() != EntityId.None;
#else
return true;
#endif
}
/// <summary>
/// OnAfterSerialize implementation.
/// </summary>
public void OnAfterDeserialize()
{
// Upgrade from no serialized version
if (m_ComponentVersion == ComponentVersions.Version_Unserialized)
{
m_ShadowVolumeIntensityEnabled = m_ShadowVolumeIntensity > 0;
m_ShadowsEnabled = m_ShadowIntensity > 0;
m_LightVolumeEnabled = m_LightVolumeIntensity > 0;
m_NormalMapQuality = !m_UseNormalMap ? NormalMapQuality.Disabled : m_NormalMapQuality;
m_OverlapOperation = m_AlphaBlendOnOverlap ? OverlapOperation.AlphaBlend : m_OverlapOperation;
m_ComponentVersion = ComponentVersions.Version_1;
}
if (m_ComponentVersion < ComponentVersions.Version_2)
{
m_ShadowSoftness = 0;
}
if (m_ComponentVersion < ComponentVersions.Version_3)
{
#if UNITY_EDITOR
m_SelectionSources.selectedHashCode = (int)m_LightType;
#endif
}
if (m_ComponentVersion < ComponentVersions.Version_4)
{
#pragma warning disable CS0618
// Version_3 data from the 6000.0 and 6000.3 ports is already migrated, so only a set deprecated cookie is applied (UUM-156931)
if (m_LightType == LightType.Point &&
(m_ComponentVersion < ComponentVersions.Version_3 || IsAssigned(m_DeprecatedPointLightCookieSprite)))
{
m_LightCookieSprite = m_DeprecatedPointLightCookieSprite;
}
m_DeprecatedPointLightCookieSprite = null;
#pragma warning restore CS0618
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 073797afb82c5a1438f328866b10b3f0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,38 @@
using System.Collections.Generic;
namespace UnityEngine.Rendering.Universal
{
public sealed partial class Light2D
{
#if UNITY_EDITOR
private const string s_IconsPath = "Packages/com.unity.render-pipelines.universal/Editor/2D/ResourceIcons/SceneViewIcons/";
private static readonly string[] s_LightIconFileNames = new[]
{
"ParametricLight.png",
"FreeformLight.png",
"SpriteLight.png",
"PointLight.png",
"GlobalLight.png"
};
private void OnDrawGizmos()
{
if (lightType != LightType.Provider)
{
Gizmos.color = Color.blue;
Gizmos.DrawIcon(transform.position, s_IconsPath + s_LightIconFileNames[(int)lightType], true);
}
else
{
light2DProvider.OnDrawGizmos(transform);
}
}
internal List<Vector2> GetFalloffShape()
{
return LightUtility.GetOutlinePath(m_ShapePath, m_ShapeLightFalloffSize);
}
#endif
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 14716551160f4757bf2332c27a53ec34
timeCreated: 1595907042
@@ -0,0 +1,122 @@
using System;
using UnityEngine.Scripting.APIUpdating;
namespace UnityEngine.Rendering.Universal
{
/// <summary>
/// Controls how the light texture is used when rendering Sprites and other 2D renderers.
/// </summary>
[Serializable]
[MovedFrom(true, "UnityEngine.Experimental.Rendering.Universal", "Unity.RenderPipelines.Universal.Runtime")]
public struct Light2DBlendStyle
{
internal enum TextureChannel
{
None = 0,
R = 1,
G = 2,
B = 3,
A = 4,
OneMinusR = 5,
OneMinusG = 6,
OneMinusB = 7,
OneMinusA = 8
}
internal struct MaskChannelFilter
{
public Vector4 mask { get; private set; }
public Vector4 inverted { get; private set; }
public MaskChannelFilter(Vector4 m, Vector4 i)
{
mask = m;
inverted = i;
}
}
internal enum BlendMode
{
Additive = 0,
Multiply = 1,
Subtractive = 2
}
[Serializable]
internal struct BlendFactors
{
public float multiplicative;
public float additive;
}
/// <summary>
/// Returns the name of the blend style
/// </summary>
public string name;
[SerializeField]
internal TextureChannel maskTextureChannel;
[SerializeField]
internal BlendMode blendMode;
internal Vector2 blendFactors
{
get
{
var result = new Vector2();
switch (blendMode)
{
case BlendMode.Additive:
result.x = 0.0f;
result.y = 1.0f;
break;
case BlendMode.Multiply:
result.x = 1.0f;
result.y = 0.0f;
break;
case BlendMode.Subtractive:
result.x = 0.0f;
result.y = -1.0f;
break;
default:
result.x = 1.0f;
result.y = 0.0f;
break;
}
return result;
}
}
internal MaskChannelFilter maskTextureChannelFilter
{
get
{
switch (maskTextureChannel)
{
case TextureChannel.R:
return new MaskChannelFilter(new Vector4(1, 0, 0, 0), new Vector4(0, 0, 0, 0));
case TextureChannel.OneMinusR:
return new MaskChannelFilter(new Vector4(1, 0, 0, 0), new Vector4(1, 0, 0, 0));
case TextureChannel.G:
return new MaskChannelFilter(new Vector4(0, 1, 0, 0), new Vector4(0, 0, 0, 0));
case TextureChannel.OneMinusG:
return new MaskChannelFilter(new Vector4(0, 1, 0, 0), new Vector4(0, 1, 0, 0));
case TextureChannel.B:
return new MaskChannelFilter(new Vector4(0, 0, 1, 0), new Vector4(0, 0, 0, 0));
case TextureChannel.OneMinusB:
return new MaskChannelFilter(new Vector4(0, 0, 1, 0), new Vector4(0, 0, 1, 0));
case TextureChannel.A:
return new MaskChannelFilter(new Vector4(0, 0, 0, 1), new Vector4(0, 0, 0, 0));
case TextureChannel.OneMinusA:
return new MaskChannelFilter(new Vector4(0, 0, 0, 1), new Vector4(0, 0, 0, 1));
case TextureChannel.None:
default:
return new MaskChannelFilter(Vector4.zero, Vector4.zero);
}
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: f4caf3da21d83644ea1c04986c6cea14
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,208 @@
using System.Collections.Generic;
using Unity.Mathematics;
using UnityEngine.Profiling;
namespace UnityEngine.Rendering.Universal
{
internal struct LightStats
{
public int totalLights;
public int totalShadowLights;
public int totalShadows;
public int totalNormalMapUsage;
public int totalVolumetricUsage;
public int totalVolumetricShadowUsage;
public uint blendStylesUsed;
public uint blendStylesWithLights;
public bool useLights { get { return totalLights > 0; } }
public bool useShadows { get { return totalShadows > 0; } }
public bool useVolumetricLights { get { return totalVolumetricUsage > 0; } }
public bool useVolumetricShadowLights { get { return totalVolumetricShadowUsage > 0; } }
public bool useNormalMap { get { return totalNormalMapUsage > 0; } }
}
internal interface ILight2DCullResult
{
List<Light2D> visibleLights { get; }
HashSet<ShadowCasterGroup2D> visibleShadows { get; }
LightStats GetLightStatsByLayer(int layerID, ref LayerBatch layer);
bool IsSceneLit();
#if UNITY_EDITOR
// Determine if culling result is based of game camera
bool IsGameView();
#endif
}
internal class Light2DCullResult : ILight2DCullResult
{
private List<Light2D> m_VisibleLights = new List<Light2D>();
public List<Light2D> visibleLights => m_VisibleLights;
private HashSet<ShadowCasterGroup2D> m_VisibleShadows = new HashSet<ShadowCasterGroup2D>();
public HashSet<ShadowCasterGroup2D> visibleShadows => m_VisibleShadows;
bool m_IsSceneLit;
#if UNITY_EDITOR
bool m_IsGameView;
#endif
// Checks if the scene has any lights, even if they are culled
public bool IsSceneLit()
{
return m_IsSceneLit;
}
#if UNITY_EDITOR
public bool IsGameView()
{
return m_IsGameView;
}
#endif
public LightStats GetLightStatsByLayer(int layerID, ref LayerBatch layer)
{
layer.lights.Clear();
layer.shadowIndices.Clear();
layer.shadowCasters.Clear();
var returnStats = new LightStats();
foreach (var light in visibleLights)
{
if (!light.IsLitLayer(layerID))
continue;
if (light.normalMapQuality != Light2D.NormalMapQuality.Disabled)
returnStats.totalNormalMapUsage++;
if (light.volumeIntensity > 0 && light.volumetricEnabled)
returnStats.totalVolumetricUsage++;
if (RendererLighting.CanCastVolumetricShadows(light, layer.endLayerValue))
returnStats.totalVolumetricShadowUsage++;
returnStats.blendStylesUsed |= (uint)(1 << light.blendStyleIndex);
if (light.lightType != Light2D.LightType.Global)
returnStats.blendStylesWithLights |= (uint)(1 << light.blendStyleIndex);
// Check if layer has shadows
bool isShadowed = false;
if (RendererLighting.CanCastShadows(light, layerID))
{
foreach (var group in visibleShadows)
{
var shadowCasters = group.GetShadowCasters();
if (shadowCasters != null)
{
foreach (var shadowCaster in shadowCasters)
{
if (shadowCaster.IsLit(light) && shadowCaster.IsShadowedLayer(layerID))
{
isShadowed = true;
returnStats.totalShadows++;
if (!layer.shadowCasters.Contains(group))
layer.shadowCasters.Add(group);
}
}
}
}
}
if (isShadowed)
{
returnStats.totalShadowLights++;
layer.shadowIndices.Add(layer.lights.Count);
}
returnStats.totalLights++;
layer.lights.Add(light);
}
return returnStats;
}
public void SetupCulling(ref ScriptableCullingParameters cullingParameters, Camera camera)
{
#if UNITY_EDITOR
m_IsGameView = UniversalRenderPipeline.IsGameCamera(camera);
#endif
Profiler.BeginSample("Cull 2D Lights and Shadow Casters");
m_VisibleLights.Clear();
m_IsSceneLit = false;
if (Light2DManager.TryGetLights(camera.gameObject, out var lights))
{
m_IsSceneLit = lights.Count > 0;
foreach (var light in lights)
{
if ((camera.cullingMask & (1 << light.gameObject.layer)) == 0)
continue;
#if UNITY_EDITOR
if (!UnityEditor.SceneManagement.StageUtility.IsGameObjectRenderedByCamera(light.gameObject, camera))
continue;
#endif
if (light.lightType == Light2D.LightType.Global)
{
m_VisibleLights.Add(light);
continue;
}
Profiler.BeginSample("Test Planes");
var position = light.boundingSphere.position;
var culled = false;
for (var i = 0; i < cullingParameters.cullingPlaneCount; ++i)
{
var plane = cullingParameters.GetCullingPlane(i);
// most of the time is spent getting world position
var distance = math.dot(position, plane.normal) + plane.distance;
if (distance < -light.boundingSphere.radius)
{
culled = true;
break;
}
}
Profiler.EndSample();
if (culled)
continue;
m_VisibleLights.Add(light);
}
}
// must be sorted here because light order could change
m_VisibleLights.Sort((l1, l2) => l1.lightOrder - l2.lightOrder);
m_VisibleShadows.Clear();
if (ShadowCasterGroup2DManager.shadowCasterGroups != null)
{
foreach (var group in ShadowCasterGroup2DManager.shadowCasterGroups)
{
var shadowCasters = group.GetShadowCasters();
if (shadowCasters != null)
{
foreach (var shadowCaster in shadowCasters)
{
// Cull against visible lights in the scene
foreach (var light in m_VisibleLights)
{
if (shadowCaster.IsLit(light) && !m_VisibleShadows.Contains(group))
{
m_VisibleShadows.Add(group);
break;
}
}
if (m_VisibleShadows.Contains(group))
break;
}
}
}
}
Profiler.EndSample();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 704a37a0ce184459805c0b7719a25a60
timeCreated: 1596067202
@@ -0,0 +1,227 @@
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
#endif
namespace UnityEngine.Rendering.Universal
{
internal static class Light2DManager
{
private static SortingLayer[] s_SortingLayers;
static List<Light2D> s_Lights = new List<Light2D>(); // Scene/Game/Prefab view
#if UNITY_EDITOR
static Dictionary<SceneHandle, List<Light2D>> s_LightsEditorOnly = new Dictionary<SceneHandle, List<Light2D>>(); // Preview view
#endif
// GetLights return different list depending on the context of the GameObject requesting (Camera or Light2D)
// We determine if the GameObject is part of the preview scene through IsPreviewSceneObject
// Scene, Game, Prefab view uses s_Lights
// Preview view uses s_LightsEditorOnly
static List<Light2D> GetOrCreateLights(GameObject obj)
{
#if UNITY_EDITOR
if (IsPreview(obj, out var key))
{
if (!s_LightsEditorOnly.TryGetValue(key, out var list))
{
list = new List<Light2D>();
s_LightsEditorOnly.Add(key, list);
}
return s_LightsEditorOnly[key];
}
#endif
return s_Lights;
}
internal static bool TryGetLights(GameObject obj, out List<Light2D> lights)
{
#if UNITY_EDITOR
if (IsPreview(obj, out var key))
return s_LightsEditorOnly.TryGetValue(key, out lights);
#endif
lights = s_Lights;
return true;
}
internal static void RemoveLight(Light2D light)
{
#if UNITY_EDITOR
if (IsPreview(light.gameObject, out var key))
{
if (s_LightsEditorOnly.TryGetValue(key, out var list))
{
Debug.Assert(list.Contains(light));
list.Remove(light);
if (list.Count == 0)
s_LightsEditorOnly.Remove(key);
return;
}
}
#endif
Debug.Assert(s_Lights.Contains(light));
s_Lights.Remove(light);
}
#if UNITY_EDITOR
static bool IsPreview(GameObject obj, out SceneHandle handle)
{
handle = obj.scene.handle;
var isPreview = EditorSceneManager.IsPreviewSceneObject(obj);
// Prefab scene
var prefabStage = PrefabStageUtility.GetPrefabStage(obj);
if (prefabStage != null && isPreview)
{
if (obj.TryGetComponent<Camera>(out var cam))
isPreview = cam.cameraType == CameraType.Preview;
else
isPreview = false;
}
return isPreview;
}
#endif
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.SubsystemRegistration)]
static void ResetStaticsOnLoad()
{
s_SortingLayers = null;
s_Lights.Clear();
s_LightsEditorOnly.Clear();
}
#endif
internal static void Initialize()
{
#if UNITY_EDITOR
SortingLayer.onLayerChanged += OnSortingLayerChanged;
#endif
}
internal static void Dispose()
{
#if UNITY_EDITOR
SortingLayer.onLayerChanged -= OnSortingLayerChanged;
#endif
}
// Called during OnEnable
public static void RegisterLight(Light2D light)
{
var lights = GetOrCreateLights(light.gameObject);
Debug.Assert(!lights.Contains(light));
lights.Add(light);
ErrorIfDuplicateGlobalLight(light);
}
// Called during OnEnable
public static void DeregisterLight(Light2D light)
{
RemoveLight(light);
}
public static void ErrorIfDuplicateGlobalLight(Light2D light)
{
if (light.lightType != Light2D.LightType.Global)
return;
foreach (var sortingLayer in light.targetSortingLayers)
{
// should this really trigger at runtime?
if (ContainsDuplicateGlobalLight(sortingLayer, light))
Debug.LogError("More than one global light on layer " + SortingLayer.IDToName(sortingLayer) + " for light blend style index " + light.blendStyleIndex);
}
}
internal static bool GetGlobalColor(int sortingLayerIndex, int blendStyleIndex, Camera cam, out Color color)
{
var foundGlobalColor = false;
color = Color.black;
// This should be rewritten to search only global lights
foreach (var light in GetOrCreateLights(cam.gameObject))
{
if (light.lightType != Light2D.LightType.Global ||
light.blendStyleIndex != blendStyleIndex ||
!light.IsLitLayer(sortingLayerIndex))
continue;
var inCurrentPrefabStage = true;
#if UNITY_EDITOR
// If we found the first global light in our prefab stage
inCurrentPrefabStage = PrefabStageUtility.GetCurrentPrefabStage()?.IsPartOfPrefabContents(light.gameObject) ?? true;
#endif
if (inCurrentPrefabStage)
{
color = light.color * light.intensity;
return true;
}
else
{
if (!foundGlobalColor)
{
color = light.color * light.intensity;
foundGlobalColor = true;
}
}
}
return foundGlobalColor;
}
private static bool ContainsDuplicateGlobalLight(int sortingLayerIndex, Light2D inLight)
{
var globalLightCount = 0;
// This should be rewritten to search only global lights
foreach (var light in GetOrCreateLights(inLight.gameObject))
{
if (light.lightType == Light2D.LightType.Global &&
light.blendStyleIndex == inLight.blendStyleIndex &&
light.IsLitLayer(sortingLayerIndex))
{
#if UNITY_EDITOR
// If we found the first global light in our prefab stage
if (PrefabStageUtility.GetPrefabStage(light.gameObject) == PrefabStageUtility.GetCurrentPrefabStage())
#endif
{
if (globalLightCount > 0)
return true;
globalLightCount++;
}
}
}
return false;
}
public static SortingLayer[] GetCachedSortingLayer()
{
if (s_SortingLayers is null)
s_SortingLayers = SortingLayer.layers;
return s_SortingLayers;
}
#if UNITY_EDITOR
internal static void OnSortingLayerChanged()
{
// Update sorting layers that were added or removed or changed order
s_SortingLayers = SortingLayer.layers;
}
#endif
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d8151411c155429aa167611d958fbb8c
timeCreated: 1595907591
@@ -0,0 +1,68 @@
using System;
namespace UnityEngine.Rendering.Universal
{
public sealed partial class Light2D
{
[SerializeField] float m_PointLightInnerAngle = 360.0f;
[SerializeField] float m_PointLightOuterAngle = 360.0f;
[SerializeField] float m_PointLightInnerRadius = 0.0f;
[SerializeField] float m_PointLightOuterRadius = 1.0f;
/// <summary>
/// The inner angle of the point light shape. The bigger the angle, the wider the gap.
/// The gap between the innner and outer angle will determine the size of the light's penumbra.
/// </summary>
public float pointLightInnerAngle
{
get => m_PointLightInnerAngle;
set => m_PointLightInnerAngle = value;
}
/// <summary>
/// The angle that determins the shape of the inner light area.
/// The gap between the innner and outer angle will determine the size of the light's penumbra.
/// </summary>
public float pointLightOuterAngle
{
get => m_PointLightOuterAngle;
set => m_PointLightOuterAngle = value;
}
/// <summary>
/// The radius of the inner light area that has full brightness.
/// The gap between the inner and outer radius will determine the size of the light's penumbra.
/// </summary>
public float pointLightInnerRadius
{
get => m_PointLightInnerRadius;
set => m_PointLightInnerRadius = value;
}
/// <summary>
/// The outer radius that determines the size of the light.
/// The gap between the inner and outer radius will determine the size of the light's penumbra.
/// </summary>
public float pointLightOuterRadius
{
get => m_PointLightOuterRadius;
set => m_PointLightOuterRadius = value;
}
/// <summary>
/// The point light distance.
/// This is obsolete and has been changed to normalMapDistance.
/// </summary>
[Obsolete("pointLightDistance has been changed to normalMapDistance #from(2021.1) #breakingFrom(2021.1)", true)]
public float pointLightDistance => m_NormalMapDistance;
/// <summary>
/// The quality of the point light.
/// This is obsolete and has been changed to normalMapQuality.
/// </summary>
[Obsolete("pointLightQuality has been changed to normalMapQuality #from(2021.1) #breakingFrom(2021.1)", true)]
public NormalMapQuality pointLightQuality => m_NormalMapQuality;
internal bool isPointLight => lightType == LightType.Point;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 1202285d83908604784202e4a57aa93c
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,68 @@
namespace UnityEngine.Rendering.Universal
{
public sealed partial class Light2D
{
[SerializeField] int m_ShapeLightParametricSides = 5;
[SerializeField] float m_ShapeLightParametricAngleOffset = 0.0f;
[SerializeField] float m_ShapeLightParametricRadius = 1.0f;
[SerializeField] float m_ShapeLightFalloffSize = 0.50f;
[SerializeField] Vector2 m_ShapeLightFalloffOffset = Vector2.zero;
[SerializeField] Vector3[] m_ShapePath = { new Vector3(-0.5f, -0.5f), new Vector3(0.5f, -0.5f), new Vector3(0.5f, 0.5f), new Vector3(-0.5f, 0.5f) };
float m_PreviousShapeLightFalloffSize = -1;
int m_PreviousShapeLightParametricSides = -1;
float m_PreviousShapeLightParametricAngleOffset = -1;
float m_PreviousShapeLightParametricRadius = -1;
int m_PreviousShapePathHash = -1;
LightType m_PreviousLightType = LightType.Parametric;
internal const float k_MaxFalloffSize = 1000000f;
/// <summary>
/// The number of sides in the parametric shape.
/// </summary>
public int shapeLightParametricSides => m_ShapeLightParametricSides;
/// <summary>
/// The offset of the shape from the light's origin.
/// </summary>
public float shapeLightParametricAngleOffset => m_ShapeLightParametricAngleOffset;
/// <summary>
/// The size of the shape.
/// </summary>
public float shapeLightParametricRadius
{
get { return m_ShapeLightParametricRadius; }
internal set { m_ShapeLightParametricRadius = value; }
}
/// <summary>
/// The size of the fall-off area. Bigger value corresponds to bigger fall off size.
/// Possible values between 0 and 1000000.
/// </summary>
public float shapeLightFalloffSize
{
get { return m_ShapeLightFalloffSize; }
set { m_ShapeLightFalloffSize = Mathf.Clamp(value, 0, k_MaxFalloffSize); }
}
/// <summary>
/// Returns the path that represents the shape light. Values are in object space.
/// </summary>
public Vector3[] shapePath
{
get { return m_ShapePath; }
internal set { m_ShapePath = value; }
}
/// <summary>
/// Set the shape that represents the freeform light. Values are in object space.
/// </summary>
/// <param name="path">Array of Vector3 defining the shape.</param>
public void SetShapePath(Vector3[] path)
{
m_ShapePath = path;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 074e9a8a8d8919e469b8dd79c7dc69a9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,622 @@
using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Mathematics;
using UnityEngine.U2D;
#if USING_2DCOMMON
using UnityEngine.U2D.Common;
#endif
namespace UnityEngine.Rendering.Universal
{
// Per Light parameters to batch.
struct PerLight2D
{
internal float4x4 InvMatrix;
internal float4 Color;
internal float4 Position;
internal float FalloffIntensity;
internal float FalloffDistance;
internal float OuterAngle;
internal float InnerAngle;
internal float InnerRadiusMult;
internal float VolumeOpacity;
internal float ShadowIntensity;
internal int LightType;
};
internal static class LightUtility
{
public static int ProviderToHash(Provider2D provider, Component component)
{
if (provider != null && component != null)
return StringToHash(provider.GetType().Name + component.GetType().Name);
else
return 0;
}
public static int StringToHash(string str)
{
return (int)URP2D_Crc32.Compute(str);
}
public static bool CheckForChange(Light2D.LightType a, ref Light2D.LightType b)
{
var changed = a != b;
b = a;
return changed;
}
public static bool CheckForChange(Component a, ref Component b)
{
var changed = a != b;
b = a;
return changed;
}
public static bool CheckForChange(int a, ref int b)
{
var changed = a != b;
b = a;
return changed;
}
public static bool CheckForChange(EntityId a, ref EntityId b)
{
var changed = a != b;
b = a;
return changed;
}
public static bool CheckForChange(float a, ref float b)
{
var changed = a != b;
b = a;
return changed;
}
public static bool CheckForChange(bool a, ref bool b)
{
var changed = a != b;
b = a;
return changed;
}
private enum PivotType
{
PivotBase,
PivotCurve,
PivotIntersect,
PivotSkip,
PivotClip
};
[Serializable]
internal struct LightMeshVertex
{
public Vector3 position;
public Color color;
public Vector2 uv;
public static readonly VertexAttributeDescriptor[] VertexLayout = new[]
{
new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 3),
new VertexAttributeDescriptor(VertexAttribute.Color, VertexAttributeFormat.Float32, 4),
new VertexAttributeDescriptor(VertexAttribute.TexCoord0, VertexAttributeFormat.Float32, 2),
};
}
static bool TestPivot(List<IntPoint> path, int activePoint, long lastPoint)
{
for (int i = activePoint; i < path.Count; ++i)
{
if (path[i].N > lastPoint)
return true;
}
return (path[activePoint].N == -1);
}
// Degenerate Pivots at the End Points.
static List<IntPoint> DegeneratePivots(List<IntPoint> path, List<IntPoint> inPath, ref int interiorStart)
{
List<IntPoint> degenerate = new List<IntPoint>();
var minN = path[0].N;
var maxN = path[0].N;
for (int i = 1; i < path.Count; ++i)
{
if (path[i].N != -1)
{
minN = Math.Min(minN, path[i].N);
maxN = Math.Max(maxN, path[i].N);
}
}
for (long i = 0; i < minN; ++i)
{
IntPoint ins = path[(int)minN];
ins.N = i;
degenerate.Add(ins);
}
degenerate.AddRange(path.GetRange(0, path.Count));
interiorStart = degenerate.Count;
for (long i = maxN + 1; i < inPath.Count; ++i)
{
IntPoint ins = inPath[(int)i];
ins.N = i;
degenerate.Add(ins);
}
return degenerate;
}
// Ensure that we get a valid path from 0.
static List<IntPoint> SortPivots(List<IntPoint> outPath, List<IntPoint> inPath)
{
List<IntPoint> sorted = new List<IntPoint>();
var min = outPath[0].N;
var max = outPath[0].N;
var minIndex = 0;
bool newMin = true;
for (int i = 1; i < outPath.Count; ++i)
{
if (max > outPath[i].N && newMin && outPath[i].N != -1)
{
min = max = outPath[i].N;
minIndex = i;
newMin = false;
}
else if (outPath[i].N >= max)
{
max = outPath[i].N;
newMin = true;
}
}
sorted.AddRange(outPath.GetRange(minIndex, (outPath.Count - minIndex)));
sorted.AddRange(outPath.GetRange(0, minIndex));
return sorted;
}
// Ensure that all points eliminated due to overlaps and intersections are accounted for Tessellation.
static List<IntPoint> FixPivots(List<IntPoint> outPath, List<IntPoint> inPath, ref int interiorStart)
{
var path = SortPivots(outPath, inPath);
long pivotPoint = path[0].N;
// Connect Points for Overlaps.
for (int i = 1; i < path.Count; ++i)
{
var j = (i == path.Count - 1) ? 0 : (i + 1);
var prev = path[i - 1];
var curr = path[i];
var next = path[j];
if (prev.N > curr.N)
{
var incr = TestPivot(path, i, pivotPoint);
if (incr)
{
if (prev.N == next.N)
curr.N = prev.N;
else
curr.N = (pivotPoint + 1) < inPath.Count ? (pivotPoint + 1) : 0;
curr.D = 3;
path[i] = curr;
}
}
pivotPoint = path[i].N;
}
// Insert Skipped Points.
for (int i = 1; i < path.Count - 1;)
{
var prev = path[i - 1];
var curr = path[i];
var next = path[i + 1];
if (curr.N - prev.N > 1)
{
if (curr.N == next.N)
{
IntPoint ins = curr;
ins.N = (ins.N - 1);
path[i] = ins;
}
else
{
IntPoint ins = curr;
ins.N = (ins.N - 1);
path.Insert(i, ins);
}
}
else
{
i++;
}
}
path = DegeneratePivots(path, inPath, ref interiorStart);
return path;
}
// Rough shape only used in Inspector for quick preview.
internal static List<Vector2> GetOutlinePath(Vector3[] shapePath, float offsetDistance)
{
const float kClipperScale = 10000.0f;
List<IntPoint> path = new List<IntPoint>();
List<Vector2> output = new List<Vector2>();
for (var i = 0; i < shapePath.Length; ++i)
{
var newPoint = new Vector2(shapePath[i].x, shapePath[i].y) * kClipperScale;
path.Add(new IntPoint((System.Int64)(newPoint.x), (System.Int64)(newPoint.y)));
}
List<List<IntPoint>> solution = new List<List<IntPoint>>();
ClipperOffset clipOffset = new ClipperOffset(24.0f);
clipOffset.AddPath(path, JoinTypes.jtRound, EndTypes.etClosedPolygon);
clipOffset.Execute(ref solution, kClipperScale * offsetDistance, path.Count);
if (solution.Count > 0)
{
int interiorStart = 0;
var outPath = solution[0];
outPath = FixPivots(outPath, path, ref interiorStart);
for (int i = 0; i < outPath.Count; ++i)
output.Add(new Vector2(outPath[i].X / kClipperScale, outPath[i].Y / kClipperScale));
}
return output;
}
static void TransferToMesh(NativeArray<LightMeshVertex> vertices, int vertexCount, NativeArray<ushort> indices,
int indexCount, Light2D light)
{
var mesh = light.lightMesh;
mesh.SetVertexBufferParams(vertexCount, LightMeshVertex.VertexLayout);
mesh.SetVertexBufferData(vertices, 0, 0, vertexCount);
mesh.SetIndices(indices, 0, indexCount, MeshTopology.Triangles, 0, true);
light.vertices = new LightMeshVertex[vertexCount];
NativeArray<LightMeshVertex>.Copy(vertices, light.vertices, vertexCount);
light.indices = new ushort[indexCount];
NativeArray<ushort>.Copy(indices, light.indices, indexCount);
}
public static Bounds GenerateShapeMesh(Light2D light, Vector3[] shapePath, float falloffDistance, float batchColor)
{
const float kClipperScale = 10000.0f;
var restoreState = Random.state;
Random.InitState(123456); // for deterministic output
// todo Revisit this while we do Batching.
var meshInteriorColor = new Color(0, 0, batchColor, 1.0f);
var meshExteriorColor = new Color(0, 0, batchColor, 0.0f);
// Create shape geometry based on edges
int inEdgeCount = shapePath.Length;
NativeArray<int2> tessInEdges = new NativeArray<int2>(inEdgeCount, Allocator.Temp);
NativeArray<float2> tessInVertices = new NativeArray<float2>(inEdgeCount, Allocator.Temp);
for (int i = 0; i < inEdgeCount; ++i)
{
int edgeEnd = i + 1;
if (edgeEnd == inEdgeCount)
edgeEnd = 0;
int2 edge = new int2(i, edgeEnd);
tessInEdges[i] = edge;
int index = edge.x;
tessInVertices[index] = new float2(shapePath[index].x, shapePath[index].y);
}
// Do tessellation
NativeArray<int> tessOutIndices = new NativeArray<int>(tessInEdges.Length * 8, Allocator.Temp);
NativeArray<float2> tessOutVertices = new NativeArray<float2>(tessInEdges.Length * 8, Allocator.Temp);
NativeArray<int2> tessOutEdges = new NativeArray<int2>(tessInEdges.Length * 8, Allocator.Temp);
int tessOutVertexCount = 0;
int tessOutIndexCount = 0;
#if USING_2DCOMMON
int tessOutEdgeCount = 0;
// runPlanarGraph must stay true: the user can drag a Freeform shape until its edges cross,
// and the tessellator overruns its edge buffer unless crossing edges are split first.
UnityEngine.U2D.Common.UTess.ModuleHandle.Tessellate(Allocator.Temp, tessInVertices, tessInEdges, ref tessOutVertices, out tessOutVertexCount, ref tessOutIndices, out tessOutIndexCount, ref tessOutEdges, out tessOutEdgeCount, true);
#endif
// Create falloff geometry with random noise to account for collinear points
var inputPointCount = shapePath.Length;
List<IntPoint> path = new List<IntPoint>();
for (var i = 0; i < inputPointCount; ++i)
{
var nx = (System.Int64)((double)shapePath[i].x * (double)kClipperScale);
var ny = (System.Int64)((double)shapePath[i].y * (double)kClipperScale);
var addPoint = new IntPoint(nx + Random.Range(-10, 10), ny + Random.Range(-10, 10));
addPoint.N = i; addPoint.D = -1;
path.Add(addPoint);
}
var lastPointIndex = inputPointCount - 1;
var interiorStartPoint = 0;
// Generate Bevels.
List<List<IntPoint>> solution = new List<List<IntPoint>>();
ClipperOffset clipOffset = new ClipperOffset(24.0f);
clipOffset.AddPath(path, JoinTypes.jtRound, EndTypes.etClosedPolygon);
clipOffset.Execute(ref solution, kClipperScale * falloffDistance, path.Count);
if (solution.Count > 0)
{
// Fix path for Pivots.
var outPath = solution[0];
var minPath = (long)inputPointCount;
for (int i = 0; i < outPath.Count; ++i)
minPath = (outPath[i].N != -1) ? Math.Min(minPath, outPath[i].N) : minPath;
var containsStart = minPath == 0;
outPath = FixPivots(outPath, path, ref interiorStartPoint);
// Size accounts for light mesh + falloff geometry(outer + inner)
int totalOutVertices = tessOutVertexCount + outPath.Count + inputPointCount;
int totalOutIndices = tessOutIndexCount + (outPath.Count * 6) + 6;
var outVertices = new NativeArray<LightMeshVertex>(totalOutVertices, Allocator.Temp);
var outIndices = new NativeArray<ushort>(totalOutIndices, Allocator.Temp);
for (int i = 0; i < tessOutIndexCount; ++i)
outIndices[i] = (ushort)tessOutIndices[i];
for (int i = 0; i < tessOutVertexCount; ++i)
{
outVertices[i] = new LightMeshVertex()
{
position = new float3(tessOutVertices[i].x, tessOutVertices[i].y, 0),
color = meshInteriorColor
};
}
var vcount = tessOutVertexCount;
var icount = tessOutIndexCount;
var innerIndices = new ushort[inputPointCount];
// Inner Vertices. (These may or may not be part of the created path. Beware!!)
for (int i = 0; i < inputPointCount; ++i)
{
outVertices[vcount++] = new LightMeshVertex()
{
position = new float3(shapePath[i].x, shapePath[i].y, 0),
color = meshInteriorColor
};
innerIndices[i] = (ushort)(vcount - 1);
}
var saveIndex = (ushort)vcount;
var pathStart = saveIndex;
var prevIndex = outPath[0].N == -1 ? 0 : outPath[0].N;
// Outer Vertices
for (int i = 0; i < outPath.Count; ++i)
{
var curr = outPath[i];
var currPoint = new float2(curr.X / kClipperScale, curr.Y / kClipperScale);
var currIndex = curr.N == -1 ? 0 : curr.N;
outVertices[vcount++] = new LightMeshVertex()
{
position = new float3(currPoint.x, currPoint.y, 0),
color = (interiorStartPoint > i) ? meshExteriorColor : meshInteriorColor
};
if (prevIndex != currIndex)
{
outIndices[icount++] = innerIndices[prevIndex];
outIndices[icount++] = innerIndices[currIndex];
outIndices[icount++] = (ushort)(vcount - 1);
}
outIndices[icount++] = innerIndices[prevIndex];
outIndices[icount++] = saveIndex;
outIndices[icount++] = saveIndex = (ushort)(vcount - 1);
prevIndex = currIndex;
}
// Close the Loop.
{
outIndices[icount++] = pathStart;
outIndices[icount++] = innerIndices[minPath];
outIndices[icount++] = containsStart ? innerIndices[lastPointIndex] : saveIndex;
outIndices[icount++] = containsStart ? pathStart : saveIndex;
outIndices[icount++] = containsStart ? saveIndex : innerIndices[minPath];
// Last Triangle. todo: Remove Clipper Usage and use SpriteShape Geometry Generator for falloff potentially.
if (containsStart)
{
var kTolerance = 0.001f;
var connectingPoint = innerIndices[lastPointIndex];
// End point detection is tricky and depends on convexity of shape. Simple test is to just check the vertices and detect.
var testA = MathF.Abs(outVertices[connectingPoint].position.x - outVertices[outIndices[icount - 1]].position.x) > kTolerance || MathF.Abs(outVertices[connectingPoint].position.y - outVertices[outIndices[icount - 1]].position.y) > kTolerance;
var testB = MathF.Abs(outVertices[connectingPoint].position.x - outVertices[outIndices[icount - 2]].position.x) > kTolerance || MathF.Abs(outVertices[connectingPoint].position.y - outVertices[outIndices[icount - 2]].position.y) > kTolerance;
if (!testA || !testB)
connectingPoint = (ushort)(interiorStartPoint + inputPointCount + tessOutVertexCount - 1);
outIndices[icount++] = connectingPoint;
}
else
outIndices[icount++] = innerIndices[minPath - 1];
}
TransferToMesh(outVertices, vcount, outIndices, icount, light);
}
Random.state = restoreState;
return light.lightMesh.GetSubMesh(0).bounds;
}
public static Bounds GenerateParametricMesh(Light2D light, float radius, float falloffDistance, float angle, int sides, float batchColor)
{
var angleOffset = Mathf.PI / 2.0f + Mathf.Deg2Rad * angle;
if (sides < 3)
{
radius = 0.70710678118654752440084436210485f * radius;
sides = 4;
}
if (sides == 4)
{
angleOffset = Mathf.PI / 4.0f + Mathf.Deg2Rad * angle;
}
var vertexCount = 1 + 2 * sides;
var indexCount = 3 * 3 * sides;
var vertices = new NativeArray<LightMeshVertex>(vertexCount, Allocator.Temp);
var triangles = new NativeArray<ushort>(indexCount, Allocator.Temp);
var centerIndex = (ushort)(2 * sides);
var mesh = light.lightMesh;
// Only Alpha value in Color channel is ever used. May remove it or keep it for batching params in the future.
var color = new Color(0, 0, batchColor, 1.0f);
vertices[centerIndex] = new LightMeshVertex
{
position = float3.zero,
color = color
};
var radiansPerSide = 2 * Mathf.PI / sides;
var min = new float3(float.MaxValue, float.MaxValue, 0);
var max = new float3(float.MinValue, float.MinValue, 0);
for (var i = 0; i < sides; i++)
{
var endAngle = (i + 1) * radiansPerSide;
var extrudeDir = new float3(math.cos(endAngle + angleOffset), math.sin(endAngle + angleOffset), 0);
var endPoint = radius * extrudeDir;
var vertexIndex = (2 * i + 2) % (2 * sides);
vertices[vertexIndex] = new LightMeshVertex
{
position = endPoint,
color = new Color(extrudeDir.x, extrudeDir.y, batchColor, 0)
};
vertices[vertexIndex + 1] = new LightMeshVertex
{
position = endPoint,
color = color
};
// Triangle 1 (Tip)
var triangleIndex = 9 * i;
triangles[triangleIndex] = (ushort)(vertexIndex + 1);
triangles[triangleIndex + 1] = (ushort)(2 * i + 1);
triangles[triangleIndex + 2] = centerIndex;
// Triangle 2 (Upper Top Left)
triangles[triangleIndex + 3] = (ushort)(vertexIndex);
triangles[triangleIndex + 4] = (ushort)(2 * i);
triangles[triangleIndex + 5] = (ushort)(2 * i + 1);
// Triangle 2 (Bottom Top Left)
triangles[triangleIndex + 6] = (ushort)(vertexIndex + 1);
triangles[triangleIndex + 7] = (ushort)(vertexIndex);
triangles[triangleIndex + 8] = (ushort)(2 * i + 1);
min = math.min(min, endPoint + extrudeDir * falloffDistance);
max = math.max(max, endPoint + extrudeDir * falloffDistance);
}
mesh.SetVertexBufferParams(vertexCount, LightMeshVertex.VertexLayout);
mesh.SetVertexBufferData(vertices, 0, 0, vertexCount);
mesh.SetIndices(triangles, MeshTopology.Triangles, 0, false);
light.vertices = new LightMeshVertex[vertexCount];
NativeArray<LightMeshVertex>.Copy(vertices, light.vertices, vertexCount);
light.indices = new ushort[indexCount];
NativeArray<ushort>.Copy(triangles, light.indices, indexCount);
return new Bounds
{
min = min,
max = max
};
}
public static Bounds GenerateSpriteMesh(Light2D light, Sprite sprite, float batchColor)
{
var mesh = light.lightMesh;
if (sprite == null)
{
mesh.Clear();
return new Bounds(Vector3.zero, Vector3.zero);
}
// this needs to be called before getting UV at the line below.
// Venky fixed it, enroute to trunk
var uvs = sprite.uv;
var srcVertices = sprite.GetVertexAttribute<Vector3>(VertexAttribute.Position);
var srcUVs = sprite.GetVertexAttribute<Vector2>(VertexAttribute.TexCoord0);
var srcIndices = sprite.GetIndices();
var center = 0.5f * (sprite.bounds.min + sprite.bounds.max);
var vertices = new NativeArray<LightMeshVertex>(srcIndices.Length, Allocator.Temp);
var color = new Color(0, 0, batchColor, 1);
for (var i = 0; i < srcVertices.Length; i++)
{
vertices[i] = new LightMeshVertex
{
position = new Vector3(srcVertices[i].x, srcVertices[i].y, 0),
color = color,
uv = srcUVs[i]
};
}
mesh.SetVertexBufferParams(vertices.Length, LightMeshVertex.VertexLayout);
mesh.SetVertexBufferData(vertices, 0, 0, vertices.Length);
mesh.SetIndices(srcIndices, MeshTopology.Triangles, 0, true);
light.vertices = new LightMeshVertex[vertices.Length];
NativeArray<LightMeshVertex>.Copy(vertices, light.vertices, vertices.Length);
light.indices = new ushort[srcIndices.Length];
NativeArray<ushort>.Copy(srcIndices, light.indices, srcIndices.Length);
return mesh.GetSubMesh(0).bounds;
}
public static int GetShapePathHash(Vector3[] path)
{
unchecked
{
int hashCode = (int)2166136261;
if (path != null)
{
foreach (var point in path)
hashCode = hashCode * 16777619 ^ point.GetHashCode();
}
else
{
hashCode = 0;
}
return hashCode;
}
}
/// <summary>
/// Checks if another enabled Global light already exists in the scene
/// </summary>
internal static void CheckForExistingGlobalLight(GameObject obj)
{
#if UNITY_EDITOR
if (Light2DManager.TryGetLights(obj, out var lights))
{
foreach (var light in lights)
{
if (light.lightType == Light2D.LightType.Global && light.enabled)
{
Light2DManager.ErrorIfDuplicateGlobalLight(light);
}
}
}
#endif
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fd90885134624894ba845bbc692698a0
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: d9f6628807013a2458d91f3c291f75aa
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,31 @@
using System;
using System.Collections.Generic;
using Unity.Collections;
using UnityEngine;
namespace UnityEngine.Rendering.Universal
{
/// <summary>
/// Class <c>Light2DProvider</c> has methods called in URP 2D which can be used to create custom lights.
/// </summary>
[Serializable]
public class Light2DProvider : Provider2D
{
/// <summary>
/// Returns the display name shown in the Light Type dropdown of the Light2D component.
/// </summary>
/// <returns>The GUIContent used in the Light2D Light Type dropdown.</returns>
public virtual GUIContent ProviderName() { return new GUIContent("Custom Light Provider", "Implemented by " + this.GetType().Name); }
/// <summary>
/// Returns the mesh used to render the Light2D.
/// </summary>
/// <returns>The mesh used for rendering.</returns>
public virtual Mesh GetMesh() { return null; }
/// <summary>
/// Internal entry point used by the rendering pipeline to retrieve the provider name.
/// </summary>
internal override GUIContent Internal_ProviderName(string componentName) { return ProviderName(); }
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: fbffb490ff4824544a472e97ee0a6679