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: b3fb8b56aca55544ca9b8d53bc19e031
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,11 @@
namespace UnityEditor.Rendering.Universal
{
[CustomEditor(typeof(UnityEngine.Rendering.Universal.CinemachineUniversalPixelPerfect)), CanEditMultipleObjects]
internal class CinemachineUniversalPixelPerfectEditor : Editor
{
public override void OnInspectorGUI()
{
EditorGUILayout.HelpBox("This Cinemachine extension is now deprecated and doesn't function properly. Instead, use the one from Cinemachine v2.4.0 or newer.", MessageType.Error);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3fccaa742ce23c84d99d542d72ccbc74
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,13 @@
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[CustomEditor(typeof(CompositeShadowCaster2D))]
internal class CompositeShadowCaster2DEditor : Editor
{
public override void OnInspectorGUI()
{
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 0bc972c43bf3a8347aee5ba065c03157
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 5361c774211d0234c94d0161651a5407
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,172 @@
using System;
using System.Collections.Generic;
using UnityEditor.Rendering.Converter;
using UnityEngine;
using UnityEngine.Categorization;
using URPPackage = UnityEngine.Rendering.Universal;
#if PIXEL_PERFECT_2D_EXISTS
using U2DPackage = UnityEngine.U2D;
#endif
namespace UnityEditor.Rendering.Universal
{
[Serializable]
internal class PixelPerfectCameraConverterItem : RenderPipelineConverterAssetItem
{
public PixelPerfectCameraConverterItem(string id) : base(id)
{
}
public PixelPerfectCameraConverterItem(GlobalObjectId gid, string assetPath) : base(gid, assetPath)
{
}
public new Texture2D icon => EditorGUIUtility.ObjectContent(null, typeof(UnityEngine.Camera)).image as Texture2D;
}
[Serializable]
[PipelineConverter("Built-in", "Universal Render Pipeline (2D Renderer)")]
[ElementInfo(Name = "Pixel Perfect Camera Converter",
Order = 1000,
Description = "This will upgrade all 2D Pixel Perfect Camera (com.unity.2d.pixelperfect) to the Universal Render Pipeline version.")]
internal class BuiltInPixelPerfectCameraConverter : IRenderPipelineConverter
{
#if PIXEL_PERFECT_2D_EXISTS
public bool isEnabled => true;
public string isDisabledMessage { get; }
public static bool UpgradePixelPerfectCamera(U2DPackage.PixelPerfectCamera cam)
{
if (cam == null)
return false;
// Copy over serialized data
var urpCam = cam.gameObject.AddComponent<URPPackage.PixelPerfectCamera>();
if (urpCam == null)
return false;
urpCam.assetsPPU = cam.assetsPPU;
urpCam.refResolutionX = cam.refResolutionX;
urpCam.refResolutionY = cam.refResolutionY;
if (cam.upscaleRT)
urpCam.gridSnapping = URPPackage.PixelPerfectCamera.GridSnapping.UpscaleRenderTexture;
else if (cam.pixelSnapping)
urpCam.gridSnapping = URPPackage.PixelPerfectCamera.GridSnapping.PixelSnapping;
if (cam.cropFrameX && cam.cropFrameY)
{
if (cam.stretchFill)
urpCam.cropFrame = URPPackage.PixelPerfectCamera.CropFrame.StretchFill;
else
urpCam.cropFrame = URPPackage.PixelPerfectCamera.CropFrame.Windowbox;
}
else if (cam.cropFrameX)
{
urpCam.cropFrame = URPPackage.PixelPerfectCamera.CropFrame.Pillarbox;
}
else if (cam.cropFrameY)
{
urpCam.cropFrame = URPPackage.PixelPerfectCamera.CropFrame.Letterbox;
}
else
{
urpCam.cropFrame = URPPackage.PixelPerfectCamera.CropFrame.None;
}
UnityEngine.Object.DestroyImmediate(cam, true);
EditorUtility.SetDirty(urpCam);
return true;
}
void UpgradeGameObject(GameObject go)
{
var cam = go.GetComponentInChildren<U2DPackage.PixelPerfectCamera>();
if (cam != null)
UpgradePixelPerfectCamera(cam);
}
#else
public bool isEnabled => false;
public string isDisabledMessage => "Pixel Perfect package is not installed. Please install the Pixel Perfect package to enable this converter.";
#endif
public void Scan(Action<List<IRenderPipelineConverterItem>> onScanFinish)
{
#if PIXEL_PERFECT_2D_EXISTS
var returnList = new List<IRenderPipelineConverterItem>();
void OnSearchFinish()
{
onScanFinish?.Invoke(returnList);
}
var processedIds = new HashSet<string>();
SearchServiceUtils.RunQueuedSearch
(
SearchServiceUtils.IndexingOptions.DeepSearch,
new List<(string query, string description)> { ("t:UnityEngine.U2D.PixelPerfectCamera", "Game Objects Referencing a U2D Pixel Perfect Camera") },
(item, description) =>
{
// Direct conversion - works for both assets and scene objects
var unityObject = item.ToObject();
if (unityObject == null)
return;
// Ensure we're always working with GameObjects
GameObject go = null;
if (unityObject is GameObject gameObject)
go = gameObject;
else if (unityObject is Component component)
go = component.gameObject;
else
return; // Not a GameObject or Component
var gid = GlobalObjectId.GetGlobalObjectIdSlow(go);
if (!processedIds.Add(gid.ToString()))
return;
int type = gid.identifierType; // 1=Asset, 2=SceneObject
var go = unityObject as GameObject;
var ppCameraItem = new PixelPerfectCameraConverterItem(gid.ToString())
{
name = $"{unityObject.name} ({(type == 1 ? "Prefab" : "SceneObject")})",
info = type == 1 ? AssetDatabase.GetAssetPath(unityObject) : go.scene.path,
};
returnList.Add(ppCameraItem);
},
OnSearchFinish
);
#else
throw new InvalidOperationException();
#endif
}
public Status Convert(IRenderPipelineConverterItem item, out string message)
{
message = string.Empty;
#if PIXEL_PERFECT_2D_EXISTS
if (item is PixelPerfectCameraConverterItem ppCameraItem)
{
if (ppCameraItem.type == 1) URP2DConverterUtility.UpgradePrefab(ppCameraItem.info, UpgradeGameObject);
else URP2DConverterUtility.UpgradeScene(ppCameraItem.info, UpgradeGameObject);
return Status.Success;
}
#endif
return Status.Error;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 8a5fe95d62765c0459615b3a5e71c3a1
@@ -0,0 +1,45 @@
using System;
using System.Collections.Generic;
using UnityEditor.Rendering.Converter;
using UnityEngine;
using UnityEngine.Categorization;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[Serializable]
[PipelineConverter("Built-in", "Universal Render Pipeline (2D Renderer)")]
[BatchModeConverterClassInfo("BuiltInToURP2D", "ReadonlyMaterial2D")]
[ElementInfo(Name = "Material Reference Converter",
Order = 100,
Description = "Converts references to Built-In readonly materials to URP (2D) readonly materials.")]
internal class BuiltInToURP2DReadonlyMaterialConverter : ReadonlyMaterialConverter
{
public override bool isEnabled
{
get
{
if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset urpAsset)
return false;
return urpAsset.scriptableRenderer is Renderer2D;
}
}
public override string isDisabledMessage => "Converter requires URP with a 2D Renderer. Convert your project to URP to use this converter.";
protected override Dictionary<string, Func<Material>> materialMappings
{
get
{
return new()
{
["Default-Material"] = () => GraphicsSettings.GetRenderPipelineSettings<Renderer2DResources>().defaultMesh2DLitMaterial,
["Sprites-Default"] = () => GraphicsSettings.GetRenderPipelineSettings<Renderer2DResources>().defaultLitMaterial,
["Sprites-Mask"] = () => GraphicsSettings.GetRenderPipelineSettings<Renderer2DResources>().defaultMaskMaterial,
};
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 06094ba9171a2b2449746e516915ac1e
@@ -0,0 +1,89 @@
using System;
using UnityEditor.Rendering.Converter;
using UnityEngine;
using UnityEngine.Categorization;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[Serializable]
[PipelineConverter("Built-in", "Universal Render Pipeline (2D Renderer)")]
[BatchModeConverterClassInfo("BuiltInToURP2D", "RenderSettings2D")]
[ElementInfo(Name = "Rendering Settings",
Order = int.MinValue,
Description = "This converter creates Universal Render Pipeline (URP) assets and corresponding Renderer assets, configuring their settings to match the equivalent settings from the Built-in Render Pipeline.")]
class BuiltInToURP2DRenderSettingsConverter : RenderSettingsConverter
{
public override bool isEnabled => true;
public override string isDisabledMessage => string.Empty;
protected override RenderPipelineAsset CreateAsset(string name)
{
string path = $"Assets/{UniversalProjectSettings.projectSettingsFolderPath}/{name}.asset";
if (AssetDatabase.AssetPathExists(path))
return AssetDatabase.LoadAssetAtPath<UniversalRenderPipelineAsset>(path);
try
{
CoreUtils.EnsureFolderTreeInAssetFilePath(path);
var asset = ScriptableObject.CreateInstance(typeof(UniversalRenderPipelineAsset)) as UniversalRenderPipelineAsset;
AssetDatabase.CreateAsset(asset, path);
AssetDatabase.SaveAssetIfDirty(asset);
return asset;
}
catch (Exception ex)
{
Debug.LogError($"Unable to create asset at path {path} with exception {ex.Message}");
return null;
}
}
Renderer2DData CreateRenderer2DDataAsset()
{
string path = $"Assets/{UniversalProjectSettings.projectSettingsFolderPath}/Default_2D_Renderer.asset";
if (AssetDatabase.AssetPathExists(path))
return AssetDatabase.LoadAssetAtPath<Renderer2DData>(path);
CoreUtils.EnsureFolderTreeInAssetFilePath(path);
var asset = Renderer2DMenus.CreateRendererAsset(path, RendererType._2DRenderer, relativePath: false) as Renderer2DData;
EditorUtility.SetDirty(asset);
AssetDatabase.SaveAssetIfDirty(asset);
return asset;
}
void GetRenderers(out ScriptableRendererData[] renderers, out int defaultIndex)
{
defaultIndex = 0;
using (ListPool<ScriptableRendererData>.Get(out var tmp))
{
tmp.Add(CreateRenderer2DDataAsset());
// In case we need multiple renderers modify the defaultIndex and add more renderers here
// ...
renderers = tmp.ToArray();
}
// Tell the asset database to regenerate the fileId, otherwise when adding the reference to the URP
// asset the fileId might not be computed and the reference might be lost.
AssetDatabase.Refresh();
}
protected override void SetPipelineSettings(RenderPipelineAsset asset)
{
if (asset is not UniversalRenderPipelineAsset urpAsset)
return;
GetRenderers(out var renderers, out var defaultIndex);
urpAsset.m_RendererDataList = renderers;
urpAsset.m_DefaultRendererIndex = defaultIndex;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a56824d790f2d894b87761a6d3c6f176
@@ -0,0 +1,48 @@
using System;
using System.Collections.Generic;
using UnityEditor.Rendering.Converter;
using UnityEngine.Categorization;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[Serializable]
[PipelineConverter("Built-in", "Universal Render Pipeline (2D Renderer)")]
[ElementInfo(Name = "Material Shader Converter",
Order = 100,
Description = "Converts references to Built-In shaders to URP (2D) shaders.")]
internal sealed class BuiltInToURP2DShaderConverter : RenderPipelineConverterMaterialUpgrader
{
public override bool isEnabled
{
get
{
if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset urpAsset)
return false;
return urpAsset.scriptableRenderer is Renderer2D;
}
}
public override string isDisabledMessage => "Converter requires URP with a 2D Renderer. Convert your project to URP to use this converter.";
protected override List<MaterialUpgrader> upgraders
{
get
{
var allURPUpgraders = MaterialUpgrader.FetchAllUpgradersForPipeline(typeof(UniversalRenderPipelineAsset));
var builtInToURPUpgraders = new List<MaterialUpgrader>();
foreach (var upgrader in allURPUpgraders)
{
if (upgrader is IBuiltInToURP2dMaterialUpgrader)
builtInToURPUpgraders.Add(upgrader);
}
return builtInToURPUpgraders;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7c198b1ecf647d44bb399198e12d2bfa
@@ -0,0 +1,82 @@
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
internal interface IBuiltInToURP2dMaterialUpgrader
{
}
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
class BuiltInToURP2DMaterialUpgraderProvider : IMaterialUpgradersProvider
{
public IEnumerable<MaterialUpgrader> GetUpgraders()
{
yield return new SpritesDefaultUpgrader("Sprites-Default");
yield return new SpritesDefaultUpgrader("Sprites-Mask");
yield return new DefaultMaterialUpgrader();
}
}
class DefaultMaterialUpgrader : MaterialUpgrader, IBuiltInToURP2dMaterialUpgrader
{
public DefaultMaterialUpgrader()
{
RenameShader("Standard", "Universal Render Pipeline/2D/Mesh2D-Lit-Default");
}
}
class SpritesDefaultUpgrader : MaterialUpgrader, IBuiltInToURP2dMaterialUpgrader
{
public SpritesDefaultUpgrader(string shaderName)
{
if (shaderName.Equals("Sprites-Default"))
{
Shader newShader = null;
Renderer2DData data = Light2DEditorUtility.GetRenderer2DData();
if (data != null)
newShader = data.GetDefaultMaterial(UnityEngine.Rendering.Universal.DefaultMaterialType.Sprite).shader;
else
newShader = Shader.Find("Universal Render Pipeline/2D/Sprite-Lit-Default");
RenameShader("Sprites/Diffuse", newShader.name);
}
else if (shaderName.Equals("Sprites-Mask"))
{
RenameShader("Sprites/Mask", "Universal Render Pipeline/2D/Sprite-Mask");
}
}
}
internal interface IURP3DToURP2dMaterialUpgrader
{
}
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
class URP3DToURP2DMaterialUpgraderProvider : IMaterialUpgradersProvider
{
public IEnumerable<MaterialUpgrader> GetUpgraders()
{
yield return new LitMaterialUpgrader();
yield return new SimpleLitMaterialUpgrader();
}
}
class LitMaterialUpgrader : MaterialUpgrader, IURP3DToURP2dMaterialUpgrader
{
public LitMaterialUpgrader()
{
RenameShader("Universal Render Pipeline/Lit", "Universal Render Pipeline/2D/Mesh2D-Lit-Default");
}
}
class SimpleLitMaterialUpgrader : MaterialUpgrader, IURP3DToURP2dMaterialUpgrader
{
public SimpleLitMaterialUpgrader()
{
RenameShader("Universal Render Pipeline/Simple Lit", "Universal Render Pipeline/2D/Mesh2D-Lit-Default");
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: eda0e8a03dd031e41974f62cc8cc0608
@@ -0,0 +1,181 @@
using System;
using System.Collections.Generic;
using UnityEditor.Rendering.Converter;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Categorization;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[Serializable]
internal class ParametricToFreeformLightUpgraderItem : RenderPipelineConverterAssetItem
{
public int type { get; set; }
public ParametricToFreeformLightUpgraderItem(string id) : base(id)
{
}
public ParametricToFreeformLightUpgraderItem(GlobalObjectId gid, string assetPath) : base(gid, assetPath)
{
}
public new Texture2D icon => EditorGUIUtility.ObjectContent(null, typeof(UnityEngine.Rendering.Universal.Light2D)).image as Texture2D;
}
[Serializable]
[PipelineTools]
[BatchModeConverterClassInfo("UpgradeURP2DAssets", "ParametricToFreeformLight")]
[ElementInfo(Name = "Parametric to Freeform Light Upgrade",
Order = 100,
Description = "This will upgrade all parametric lights to freeform lights.")]
internal sealed class ParametricToFreeformLightUpgrader : IRenderPipelineConverter
{
public bool isEnabled
{
get
{
var urpAsset = GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset;
if (urpAsset == null)
return false;
var renderer = urpAsset.scriptableRenderer as Renderer2D;
if (renderer == null)
return false;
return true;
}
}
public string isDisabledMessage => "The current Render Pipeline is not URP or the current Renderer is not 2D";
public void Scan(Action<List<IRenderPipelineConverterItem>> onScanFinish)
{
var returnList = new List<IRenderPipelineConverterItem>();
void OnSearchFinish()
{
onScanFinish?.Invoke(returnList);
}
var processedIds = new HashSet<string>();
SearchServiceUtils.RunQueuedSearch
(
SearchServiceUtils.IndexingOptions.DeepSearch,
new List<(string, string)>()
{
("t:UnityEngine.Rendering.Universal.Light2D", "Light 2D"),
},
(item, description) =>
{
// Direct conversion - works for both assets and scene objects
var unityObject = item.ToObject();
if (unityObject == null)
return;
// Ensure we're always working with GameObjects
GameObject go = null;
if (unityObject is GameObject gameObject)
go = gameObject;
else if (unityObject is Component component)
go = component.gameObject;
else
return; // Not a GameObject or Component
var gid = GlobalObjectId.GetGlobalObjectIdSlow(go);
if (!processedIds.Add(gid.ToString()))
return;
int type = gid.identifierType; // 1=Asset, 2=SceneObject
var isPrefab = type == 1;
var lightUpgraderItem = new ParametricToFreeformLightUpgraderItem(gid.ToString())
{
info = isPrefab
? $"Prefab: {AssetDatabase.GetAssetPath(unityObject)}"
: $"Scene: {go.scene.path}",
type = type
};
returnList.Add(lightUpgraderItem);
},
OnSearchFinish
);
}
const float k_EnscribedSquareDiagonalLength = 0.70710678118654752440084436210485f;
public static void UpgradeParametricLight(Light2D light)
{
if (light.lightType == (Light2D.LightType)Light2D.DeprecatedLightType.Parametric)
{
light.lightType = Light2D.LightType.Freeform;
// Parametric radius has to be > 0 in order mesh tessellation to be valid
if (light.shapeLightParametricRadius == 0)
light.shapeLightParametricRadius = 0.01f;
float radius = light.shapeLightParametricRadius;
float angle = light.shapeLightParametricAngleOffset;
int sides = light.shapeLightParametricSides;
var angleOffset = Mathf.PI / 2.0f + Mathf.Deg2Rad * angle;
if (sides < 3)
{
radius = k_EnscribedSquareDiagonalLength * radius;
sides = 4;
}
if (sides == 4)
{
angleOffset = Mathf.PI / 4.0f + Mathf.Deg2Rad * angle;
}
var radiansPerSide = 2 * Mathf.PI / sides;
var min = new Vector3(float.MaxValue, float.MaxValue, 0);
var max = new Vector3(float.MinValue, float.MinValue, 0);
Vector3[] shapePath = new Vector3[sides];
for (var i = 0; i < sides; i++)
{
var endAngle = (i + 1) * radiansPerSide;
var extrudeDir = new Vector3(Mathf.Cos(endAngle + angleOffset), Mathf.Sin(endAngle + angleOffset), 0);
var endPoint = radius * extrudeDir;
shapePath[i] = endPoint;
}
light.shapePath = shapePath;
light.UpdateMesh();
EditorSceneManager.MarkSceneDirty(light.gameObject.scene);
}
}
void UpgradeGameObject(GameObject go)
{
Light2D[] lights = go.GetComponentsInChildren<Light2D>();
foreach (Light2D light in lights)
{
if (light.lightType == Light2D.LightType.Parametric && !PrefabUtility.IsPartOfPrefabInstance(light))
UpgradeParametricLight(light);
}
}
public Status Convert(IRenderPipelineConverterItem item, out string message)
{
if (item is ParametricToFreeformLightUpgraderItem lightItem)
{
if (lightItem.type == 1) URP2DConverterUtility.UpgradePrefab(lightItem.assetPath, UpgradeGameObject);
else URP2DConverterUtility.UpgradeScene(lightItem.assetPath, UpgradeGameObject);
}
message = string.Empty;
return Status.Success;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5f5877a9138882a4095ba0e997d19644
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,80 @@
using System;
using System.Collections.Generic;
using System.Text;
using UnityEditor.Rendering.Converter;
using UnityEngine.Categorization;
using UnityEngine.Rendering.Universal;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering.Universal
{
[Serializable]
[PipelineTools]
[ElementInfo(Name = "Photoshop Assets Upgrader",
Order = 400,
Description = "This converter reimports the assets with extension .psd and .psb.")]
internal sealed class PhotoshopAssetsUpgrader : IRenderPipelineConverter
{
public bool isEnabled
{
get
{
var urpAsset = GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset;
if (urpAsset == null)
return false;
var renderer = urpAsset.scriptableRenderer as Renderer2D;
if (renderer == null)
return false;
return true;
}
}
public string isDisabledMessage => "The current Render Pipeline is not URP or the current Renderer is not 2D";
public void Scan(Action<List<IRenderPipelineConverterItem>> onScanFinish)
{
var returnList = new List<IRenderPipelineConverterItem>();
void OnSearchFinish()
{
onScanFinish?.Invoke(returnList);
}
SearchServiceUtils.RunQueuedSearch
(
SearchServiceUtils.IndexingOptions.DeepSearch,
new List<(string, string)>()
{
("p: ext:psd", "PSD"),
("p: ext:psb", "PSB")
},
(item, description) =>
{
var assetItem = new RenderPipelineConverterAssetItem(item.id)
{
info = description
};
returnList.Add(assetItem);
},
OnSearchFinish
);
}
public Status Convert(IRenderPipelineConverterItem item, out string message)
{
var assetItem = item as RenderPipelineConverterAssetItem;
var obj = assetItem.LoadObject();
if (obj == null)
{
message = $"Failed to load {assetItem.name} Global ID {assetItem.guid} Asset Path {assetItem.assetPath}";
return Status.Error;
}
URP2DConverterUtility.UpgradePSB(assetItem.assetPath);
message = string.Empty;
return Status.Success;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7ff48272166a7b6439b6945d39d51766
@@ -0,0 +1,185 @@
using System;
using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using static UnityEditor.Rendering.AnimationClipUpgrader;
internal static class URP2DConverterUtility
{
private static class Styles
{
public static readonly GUIContent failedToInstallPackageTitle = EditorGUIUtility.TrTextContent("Installation Failed");
public static readonly GUIContent failedToInstallPackageContent = EditorGUIUtility.TrTextContent("Failed to install {0} package.\nErrorCode: {1}\nMessage: {2}");
public static readonly GUIContent okText = EditorGUIUtility.TrTextContent("OK");
}
public static bool InstallPackage(string package)
{
var addRequest = UnityEditor.PackageManager.Client.Add(package);
while (!addRequest.IsCompleted)
System.Threading.Thread.Sleep(10);
if (addRequest.Status == UnityEditor.PackageManager.StatusCode.Failure)
{
var message = System.String.Format(Styles.failedToInstallPackageContent.text, package, addRequest.Error.errorCode, addRequest.Error.message);
EditorUtility.DisplayDialog(Styles.failedToInstallPackageTitle.text, message, Styles.okText.text);
}
UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
return addRequest.Status == UnityEditor.PackageManager.StatusCode.Success;
}
public static bool IsPSB(string path)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(path));
if (path.StartsWith("Packages"))
return false;
return path.EndsWith(".psb") || path.EndsWith(".psd");
}
public static bool IsMaterialPath(string path, string[] ids)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(path));
if (path.StartsWith("Packages"))
return false;
if (path.EndsWith(".mat"))
{
return URP2DConverterUtility.DoesFileContainString(path, ids);
}
return false;
}
public static bool IsPrefabOrScenePath(string path, string[] ids)
{
if (string.IsNullOrEmpty(path))
throw new ArgumentNullException(nameof(path));
if (path.StartsWith("Packages"))
return false;
if (path.EndsWith(".prefab", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".unity", StringComparison.OrdinalIgnoreCase))
return URP2DConverterUtility.DoesFileContainString(path, ids);
return false;
}
public static bool IsPrefabOrScenePath(string path, string id)
{
return IsPrefabOrScenePath(path, new string[] { id });
}
public static bool DoesFileContainString(string path, string[] strs)
{
if (strs != null && strs.Length > 0)
{
using (StreamReader file = File.OpenText(path))
{
string line;
while ((line = file.ReadLine()) != null)
{
for (int i = 0; i < strs.Length; i++)
{
if (line.Contains(strs[i]))
return true;
}
}
}
}
return false;
}
public static string UpgradePSB(string path)
{
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceSynchronousImport | ImportAssetOptions.ForceUpdate);
return string.Empty;
}
public static string UpgradePrefab(string path, Action<GameObject> objectUpgrader)
{
UnityEngine.Object[] objects = AssetDatabase.LoadAllAssetsAtPath(path);
int firstIndex = 0;
for (int i = 0; i < objects.Length; i++)
{
if (objects[i] as GameObject)
{
firstIndex = i;
break;
}
}
// There should be no need to check this as we have already determined that there is something that needs upgrading
if (!PrefabUtility.IsPartOfImmutablePrefab(objects[firstIndex]))
{
for (int objIndex = 0; objIndex < objects.Length; objIndex++)
{
GameObject go = objects[objIndex] as GameObject;
if (go != null)
{
objectUpgrader(go);
}
}
GameObject asset = objects[firstIndex] as GameObject;
PrefabUtility.SavePrefabAsset(asset.transform.root.gameObject);
return string.Empty;
}
return "Unable to modify an immutable prefab";
}
public static void UpgradeScene(string path, Action<GameObject> objectUpgrader)
{
Scene scene = new Scene();
bool openedByUser = false;
for (int i = 0; i < SceneManager.sceneCount && !openedByUser; i++)
{
scene = SceneManager.GetSceneAt(i);
if (path == scene.path)
openedByUser = true;
}
if (!openedByUser)
scene = EditorSceneManager.OpenScene(path, OpenSceneMode.Additive);
GameObject[] gameObjects = scene.GetRootGameObjects();
foreach (GameObject go in gameObjects)
objectUpgrader(go);
EditorSceneManager.SaveScene(scene);
if (!openedByUser)
EditorSceneManager.CloseScene(scene, true);
}
public static void UpgradeMaterial(string path, Action<Material> materialUpgrader)
{
Material material = AssetDatabase.LoadAssetAtPath<Material>(path);
materialUpgrader(material);
GUID guid = AssetDatabase.GUIDFromAssetPath(path);
AssetDatabase.SaveAssetIfDirty(guid);
}
public static string GetObjectIDString(UnityEngine.Object obj)
{
string guid;
long localId;
if (AssetDatabase.TryGetGUIDAndLocalFileIdentifier(obj.GetEntityId(), out guid, out localId))
return "fileID: " + localId + ", guid: " + guid;
return null;
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4d81aa6b4f52f5a46a02e0957a23f550
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using UnityEditor.Rendering.Converter;
using UnityEngine;
using UnityEngine.Categorization;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[Serializable]
[PipelineConverter("Universal Render Pipeline (Universal Renderer)", "Universal Render Pipeline (2D Renderer)")]
[ElementInfo(Name = "Material Reference Converter",
Order = 100,
Description = "Converts references to URP Lit and Simple Lit readonly material to Mesh 2D Lit material.")]
internal class URP3DToURP2DReadonlyMaterialConverter : ReadonlyMaterialConverter
{
private List<(string query, string description)> m_ContextSearchQueriesAndIds;
private Dictionary<string, Func<Material>> m_MaterialMappings;
public override bool isEnabled
{
get
{
if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset urpAsset)
return false;
return urpAsset.scriptableRenderer is Renderer2D;
}
}
public override string isDisabledMessage => "Converter requires URP with a 2D Renderer. Convert your project to URP to use this converter.";
private bool m_Initialized = false;
private void InitializeIfNeeded()
{
if (m_Initialized)
return;
m_Initialized = true;
var urpMaterials = GraphicsSettings.GetRenderPipelineSettings<UniversalRenderPipelineEditorMaterials>();
var lit = urpMaterials.defaultMaterial;
var simpleLit = urpMaterials.simpleLitMaterial;
// -t:RenderPipelineGlobalSettings is to avoid adding the Global Settings as they reference the URP Lit and Simple Lit materials
// We do not want to modify them as part of this conversion, because they must keep referencing the URP 3D materials.
const string formattedId = "p: ref=<$object:{0},UnityEngine.Object$> -t:RenderPipelineGlobalSettings";
m_ContextSearchQueriesAndIds = new List<(string query, string description)>()
{
(string.Format(formattedId, GlobalObjectId.GetGlobalObjectIdSlow(lit)), "URP Lit is being referenced"),
(string.Format(formattedId, GlobalObjectId.GetGlobalObjectIdSlow(simpleLit)), "URP Simple Lit is being referenced")
};
Func<Material> mesh2DLitMaterial = () => GraphicsSettings.GetRenderPipelineSettings<Renderer2DResources>().defaultMesh2DLitMaterial;
m_MaterialMappings = new Dictionary<string, Func<Material>>()
{
["Lit"] = mesh2DLitMaterial,
["SimpleLit"] = mesh2DLitMaterial
};
}
protected override List<(string query, string description)> contextSearchQueriesAndIds
{
get
{
InitializeIfNeeded();
return m_ContextSearchQueriesAndIds;
}
}
protected override Dictionary<string, Func<Material>> materialMappings
{
get
{
InitializeIfNeeded();
return m_MaterialMappings;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 5baecaac191c29b4588b13e6c63bc1b0
@@ -0,0 +1,49 @@
using System;
using System.Collections.Generic;
using UnityEditor.Rendering.Converter;
using UnityEngine;
using UnityEngine.Categorization;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[Serializable]
[PipelineConverter("Universal Render Pipeline (Universal Renderer)", "Universal Render Pipeline (2D Renderer)")]
[ElementInfo(Name = "Material Shader Converter",
Order = 100,
Description = "Converts references to URP Lit and Simple Lit shaders to Mesh 2D Lit shader.")]
internal sealed class URP3DToURP2DShaderConverter : RenderPipelineConverterMaterialUpgrader
{
public override bool isEnabled
{
get
{
if (GraphicsSettings.currentRenderPipeline is not UniversalRenderPipelineAsset urpAsset)
return false;
return urpAsset.scriptableRenderer is Renderer2D;
}
}
public override string isDisabledMessage => "Converter requires URP with a 2D Renderer. Convert your project to URP to use this converter.";
protected override List<MaterialUpgrader> upgraders
{
get
{
var allURPUpgraders = MaterialUpgrader.FetchAllUpgradersForPipeline(typeof(UniversalRenderPipelineAsset));
var builtInToURPUpgraders = new List<MaterialUpgrader>();
foreach (var upgrader in allURPUpgraders)
{
if (upgrader is IURP3DToURP2dMaterialUpgrader)
builtInToURPUpgraders.Add(upgrader);
}
return builtInToURPUpgraders;
}
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: aa2366bbec4f77041b59b590de916a32
@@ -0,0 +1,53 @@
using UnityEngine;
namespace UnityEditor.Rendering.Universal
{
internal static class FreeformPathPresets
{
public static Vector3[] CreateIsometricDiamond()
{
Vector3[] returnPath = new Vector3[4]
{
new Vector3(-0.5f, 0.0f),
new Vector3(0.0f, -0.25f),
new Vector3(0.5f, 0.0f),
new Vector3(0.0f, 0.25f)
};
return returnPath;
}
private static Vector3[] CreateShape(int vertices, float angleOffset)
{
Vector3[] returnPath = new Vector3[vertices];
const float kRadius = 0.5f;
for (int i = 0; i < vertices; i++)
{
float angle = ((float)i * 2 * Mathf.PI / (float)vertices) + angleOffset;
float x = kRadius * Mathf.Cos(angle);
float y = kRadius * Mathf.Sin(angle);
returnPath[i] = new Vector3(x, y);
}
return returnPath;
}
public static Vector3[] CreateCircle()
{
return CreateShape(32, 0);
}
public static Vector3[] CreateHexagonFlatTop()
{
return CreateShape(6, 0);
}
public static Vector3[] CreateHexagonPointedTop()
{
return CreateShape(6, 0.5f * Mathf.PI);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 258887e488db43041a92d45ddb4f2a4d
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,74 @@
using System;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
static class GameObjectCreation
{
const int k_PixelPerfectCameraGameObjectMenuPriority = 5;
[MenuItem("GameObject/2D Object/Pixel Perfect Camera (URP)", priority = k_PixelPerfectCameraGameObjectMenuPriority)]
static void GameObjectCreatePixelPerfectCamera(MenuCommand menuCommand)
{
var go = CreateGameObject("Pixel Perfect Camera", menuCommand, new[] { typeof(PixelPerfectCamera) });
go.GetComponent<PixelPerfectCamera>().gridSnapping = PixelPerfectCamera.GridSnapping.PixelSnapping;
go.GetComponent<Camera>().orthographic = true;
}
static public GameObject CreateGameObject(string name, MenuCommand menuCommand, params Type[] components)
{
var parent = menuCommand.context as GameObject;
var newGO = ObjectFactory.CreateGameObject(name, components);
newGO.name = name;
Selection.activeObject = newGO;
Place(newGO, parent);
if (EditorSettings.defaultBehaviorMode == EditorBehaviorMode.Mode2D)
{
var position = newGO.transform.position;
position.z = 0;
newGO.transform.position = position;
}
Undo.RegisterCreatedObjectUndo(newGO, string.Format("Create {0}", name));
return newGO;
}
internal static void Place(GameObject go, GameObject parentTransform)
{
if (parentTransform != null)
{
var transform = go.transform;
Undo.SetTransformParent(transform, parentTransform.transform, "Reparenting");
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
transform.localScale = Vector3.one;
go.layer = parentTransform.gameObject.layer;
if (parentTransform.GetComponent<RectTransform>())
ObjectFactory.AddComponent<RectTransform>(go);
}
else
{
PlaceGameObjectInFrontOfSceneView(go);
StageUtility.PlaceGameObjectInCurrentStage(go); // may change parent
}
// Only at this point do we know the actual parent of the object and can modify its name accordingly.
GameObjectUtility.EnsureUniqueNameForSibling(go);
Undo.SetCurrentGroupName("Create " + go.name);
Selection.activeGameObject = go;
}
internal static void PlaceGameObjectInFrontOfSceneView(GameObject go)
{
var view = SceneView.lastActiveSceneView;
if (view != null)
{
view.MoveToView(go.transform);
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b080c5c57a34e6e4584e1e2c3e96a0c5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,983 @@
using System.Collections.Generic;
using System.Linq;
using UnityEditor.EditorTools;
using UnityEngine;
using UnityEngine.Rendering.Universal;
#if USING_2DCOMMON
using UnityEditor.U2D.Common.Path;
#endif
namespace UnityEditor.Rendering.Universal
{
[CustomEditor(typeof(Light2D))]
[CanEditMultipleObjects]
internal class Light2DEditor
#if USING_2DCOMMON
: PathComponentEditor<ScriptablePath>
#else
: Editor
#endif
{
#if USING_2DCOMMON
[EditorTool("Edit Freeform Shape", typeof(Light2D))]
class FreeformShapeTool : PathEditorTool<ScriptablePath>
{
const string k_ShapePath = "m_ShapePath";
public override bool IsAvailable()
{
var light = target as Light2D;
if (light == null)
return false;
else
return base.IsAvailable() && light.lightType == Light2D.LightType.Freeform;
}
protected override IShape GetShape(Object target)
{
return (target as Light2D).shapePath.ToPolygon(false);
}
protected override void SetShape(ScriptablePath shapeEditor, SerializedObject serializedObject)
{
serializedObject.Update();
var pointsProperty = serializedObject.FindProperty(k_ShapePath);
pointsProperty.arraySize = shapeEditor.pointCount;
for (var i = 0; i < shapeEditor.pointCount; ++i)
pointsProperty.GetArrayElementAtIndex(i).vector3Value = shapeEditor.GetPoint(i).position;
((Light2D)(serializedObject.targetObject)).UpdateMesh();
// This is untracked right now...
serializedObject.ApplyModifiedProperties();
}
}
#endif
private static class Styles
{
public static readonly GUIContent InnerOuterSpotAngle = EditorGUIUtility.TrTextContent("Inner / Outer Spot Angle", "Adjusts the inner / outer angles of this light to change the angle ranges of this Spot Light’s beam.");
static Texture s_LightCapTopRight;
static Texture s_LightCapTopLeft;
static Texture s_LightCapBottomLeft;
static Texture s_LightCapBottomRight;
static Texture s_LightCapUp;
static Texture s_LightCapDown;
public static Texture lightCapTopRight => s_LightCapTopRight ??= LoadIcon("LightCapTopRight.png");
public static Texture lightCapTopLeft => s_LightCapTopLeft ??= LoadIcon("LightCapTopLeft.png");
public static Texture lightCapBottomLeft => s_LightCapBottomLeft ??= LoadIcon("LightCapBottomLeft.png");
public static Texture lightCapBottomRight => s_LightCapBottomRight ??= LoadIcon("LightCapBottomRight.png");
public static Texture lightCapUp => s_LightCapUp ??= LoadIcon("LightCapUp.png");
public static Texture lightCapDown => s_LightCapDown ??= LoadIcon("LightCapDown.png");
static Texture LoadIcon(string fileName) => AssetDatabase.LoadAssetAtPath<Texture>(Light2DEditorUtility.ResourcePath + fileName);
public static GUIContent blendingSettingsFoldout = EditorGUIUtility.TrTextContent("Blending", "Options used for blending");
public static GUIContent shadowsSettingsFoldout = EditorGUIUtility.TrTextContent("Shadows", "Options used for shadows");
public static GUIContent volumetricSettingsFoldout = EditorGUIUtility.TrTextContent("Volumetric", "Options used for volumetric lighting");
public static GUIContent normalMapsSettingsFoldout = EditorGUIUtility.TrTextContent("Normal Maps", "Options used for normal maps");
public static GUIContent filteringSettingsFoldout = EditorGUIUtility.TrTextContent("Filtering", "Options to filter the light");
public static GUIContent generalLightType = EditorGUIUtility.TrTextContent("Light Type", "Select the light type. \n\nGlobal Light: For ambient light. \nSpot Light: For a spot light / point light. \nFreeform Light: For a custom shape light. \nSprite Light: For a custom light cookie using Sprites.");
public static GUIContent generalFalloffSize = EditorGUIUtility.TrTextContent("Falloff", "Adjusts the falloff area of this light. The higher the falloff value, the larger area the falloff spans.");
public static GUIContent generalFalloffIntensity = EditorGUIUtility.TrTextContent("Falloff Strength", "Adjusts the falloff curve to control the softness of this light’s edges. The higher the falloff strength, the softer the edges of this light.");
public static GUIContent generalLightColor = EditorGUIUtility.TrTextContent("Color", "Adjusts this light’s color.");
public static GUIContent generalLightIntensity = EditorGUIUtility.TrTextContent("Intensity", "Adjusts this light’s color intensity by using multiply to brighten the Sprite beyond its original color.");
public static GUIContent generalVolumeIntensity = EditorGUIUtility.TrTextContent("Intensity", "Adjusts the intensity of this additional light volume that's additively blended on top of this light. To enable the Volumetric Shadow Strength, increase this Intensity to be greater than 0.");
public static GUIContent generalBlendStyle = EditorGUIUtility.TrTextContent("Blend Style", "Adjusts how this light blends with the Sprites on the Target Sorting Layers. Different Blend Styles can be customized in the 2D Renderer Data Asset.");
public static GUIContent generalLightOverlapOperation = EditorGUIUtility.TrTextContent("Overlap Operation", "Determines how this light blends with the other lights either through additive or alpha blending.");
public static GUIContent generalLightOrder = EditorGUIUtility.TrTextContent("Light Order", "Determines the relative order in which lights of the same Blend Style get rendered. Lights with lower values are rendered first.");
public static GUIContent generalShadowIntensity = EditorGUIUtility.TrTextContent("Strength", "Adjusts the amount of light occlusion from the Shadow Caster 2D component(s) when blocking this light.The higher the value, the more opaque the shadow becomes.");
public static GUIContent generalShadowSoftness = EditorGUIUtility.TrTextContent("Softness", "Adjusts the amount of softness at the edge of the shadow.");
public static GUIContent generalShadowSoftnessFalloffIntensity = EditorGUIUtility.TrTextContent("Falloff Strength", "Adjusts the falloff curve to control the softness of the shadow edges. The higher the falloff strength, the softer the edges of this shadow.");
public static GUIContent generalShadowVolumeIntensity = EditorGUIUtility.TrTextContent("Shadow Strength", "Adjusts the amount of volume light occlusion from the Shadow Caster 2D component(s) when blocking this light.");
public static GUIContent generalSortingLayerPrefixLabel = EditorGUIUtility.TrTextContent("Target Sorting Layers", "Determines which layers this light affects. To optimize performance, minimize the number of layers this light affects.");
public static GUIContent generalLightNoLightEnabled = EditorGUIUtility.TrTextContentWithIcon("No valid blend styles are enabled.", MessageType.Error);
public static GUIContent generalNormalMapZDistance = EditorGUIUtility.TrTextContent("Distance", "Adjusts the z-axis distance of this light and the lit Sprite(s). Do note that this distance does not Transform the position of this light in the Scene.");
public static GUIContent generalNormalMapLightQuality = EditorGUIUtility.TrTextContent("Quality", "Determines the accuracy of the lighting calculations when normal map is used. To optimize for performance, select Fast.");
public static GUIContent pointLightRadius = EditorGUIUtility.TrTextContent("Radius", "Adjusts the inner / outer radius of this light to change the size of this light.");
public static GUIContent pointLightInner = EditorGUIUtility.TrTextContent("Inner", "Specify the inner radius of the light");
public static GUIContent pointLightOuter = EditorGUIUtility.TrTextContent("Outer", "Specify the outer radius of the light");
public static GUIContent pointLightSprite = EditorGUIUtility.TrTextContent("Sprite", "Specify the sprite (deprecated)");
public static GUIContent shapeLightSprite = EditorGUIUtility.TrTextContent("Sprite", "Assign a Sprite which acts as a mask to create a light cookie.");
public static GUIContent deprecatedParametricLightWarningSingle = EditorGUIUtility.TrTextContentWithIcon("Parametic Lights have been deprecated. To continue, upgrade your Parametric Light to a Freeform Light to enjoy similar light functionality.", MessageType.Warning);
public static GUIContent deprecatedParametricLightWarningMulti = EditorGUIUtility.TrTextContentWithIcon("Parametic Lights have been deprecated. To continue, upgrade your Parametric Lights to Freeform Lights to enjoy similar light functionality.", MessageType.Warning);
public static GUIContent deprecatedParametricLightInstructions = EditorGUIUtility.TrTextContent("Alternatively, you may choose to upgrade from the menu. Window > Rendering > Render Pipeline Converter > URP 2D Converters");
public static GUIContent deprecatedParametricLightButtonSingle = EditorGUIUtility.TrTextContent("Upgrade Parametric Light");
public static GUIContent deprecatedParametricLightButtonMulti = EditorGUIUtility.TrTextContent("Upgrade Parametric Lights");
public static GUIContent renderPipelineUnassignedWarning = EditorGUIUtility.TrTextContentWithIcon("Universal scriptable renderpipeline asset must be assigned in Graphics Settings or Quality Settings.", MessageType.Warning);
public static GUIContent asset2DUnassignedWarning = EditorGUIUtility.TrTextContentWithIcon("2D renderer data must be assigned to your universal render pipeline asset or camera.", MessageType.Warning);
public static string deprecatedParametricLightDialogTextSingle = "The upgrade will convert the selected parametric light into a freeform light. You can't undo this operation.";
public static string deprecatedParametricLightDialogTextMulti = "The upgrade will convert the selected parametric lights into freeform lights. You can't undo this operation.";
public static string deprecatedParametricLightDialogTitle = "Parametric Light Upgrader";
public static string deprecatedParametricLightDialogProceed = "Proceed";
public static string deprecatedParametricLightDialogCancel = "Cancel";
public static readonly GUIContent buttonText = EditorGUIUtility.TrTextContent("Install 2D Common Package");
public static readonly GUIContent helpBox = EditorGUIUtility.TrTextContent("2D Common Package is required to edit Light 2D Shape. Please install it by clicking button above");
}
const float k_GlobalLightGizmoSize = 1.2f;
const float k_AngleCapSize = 0.16f * k_GlobalLightGizmoSize;
const float k_AngleCapOffset = 0.08f * k_GlobalLightGizmoSize;
const float k_AngleCapOffsetSecondary = -0.05f;
const float k_RangeCapSize = 0.025f * k_GlobalLightGizmoSize;
const float k_InnerRangeCapSize = 0.08f * k_GlobalLightGizmoSize;
SerializedProperty m_LightColor;
SerializedProperty m_LightIntensity;
SerializedProperty m_ShadowsEnabled;
SerializedProperty m_ShadowIntensity;
SerializedProperty m_ShadowSoftness;
SerializedProperty m_ShadowSoftnessFalloffIntensity;
SerializedProperty m_ShadowVolumeIntensity;
SerializedProperty m_ShadowVolumeIntensityEnabled;
SerializedProperty m_VolumetricIntensity;
SerializedProperty m_VolumetricEnabled;
SerializedProperty m_BlendStyleIndex;
SerializedProperty m_FalloffIntensity;
SerializedProperty m_NormalMapZDistance;
SerializedProperty m_NormalMapQuality;
SerializedProperty m_LightOrder;
SerializedProperty m_OverlapOperation;
SerializedProperty m_LightType;
// Point Light Properties
SerializedProperty m_PointInnerAngle;
SerializedProperty m_PointOuterAngle;
SerializedProperty m_PointInnerRadius;
SerializedProperty m_PointOuterRadius;
// Shape Light Properties
SerializedProperty m_ShapeLightFalloffSize;
SerializedProperty m_ShapeLightSprite;
SerializedProperty m_SelectionSources;
SerializedProperty m_RenderingLayersMask;
SavedBool m_BlendingSettingsFoldout;
SavedBool m_ProviderFoldout;
SavedBool m_ShadowsSettingsFoldout;
SavedBool m_VolumetricSettingsFoldout;
SavedBool m_NormalMapsSettingsFoldout;
SavedBool m_FilteringSettingsFoldout;
int[] m_BlendStyleIndices;
GUIContent[] m_BlendStyleNames;
bool m_AnyBlendStyleEnabled = false;
SortingLayerDropDown m_SortingLayerDropDown;
Light2D lightObject => target as Light2D;
Analytics.Renderer2DAnalytics m_Analytics;
HashSet<Light2D> m_ModifiedLights;
private void AnalyticsTrackChanges(SerializedObject serializedObject)
{
if (serializedObject.hasModifiedProperties)
{
foreach (Object targetObj in serializedObject.targetObjects)
{
Light2D light2d = (Light2D)targetObj;
if (!m_ModifiedLights.Contains(light2d))
m_ModifiedLights.Add(light2d);
}
}
}
void OnEnable()
{
m_Analytics = Analytics.Renderer2DAnalytics.instance;
m_ModifiedLights = new HashSet<Light2D>();
m_SortingLayerDropDown = new SortingLayerDropDown();
m_BlendingSettingsFoldout = new SavedBool($"{target.GetType()}.2DURPBlendingSettingsFoldout", false);
m_ShadowsSettingsFoldout = new SavedBool($"{target.GetType()}.2DURPShadowsSettingsFoldout", false);
m_VolumetricSettingsFoldout = new SavedBool($"{target.GetType()}.2DURPVolumetricSettingsFoldout", false);
m_NormalMapsSettingsFoldout = new SavedBool($"{target.GetType()}.2DURPNormalMapsSettingsFoldout", false);
m_FilteringSettingsFoldout = new SavedBool($"{target.GetType()}.2DURPFilteringSettingsFoldout", false);
m_ProviderFoldout = new SavedBool($"{target.GetType()}.2DURPLight2DProviderFoldout", false);
m_LightColor = serializedObject.FindProperty("m_Color");
m_LightIntensity = serializedObject.FindProperty("m_Intensity");
m_ShadowsEnabled = serializedObject.FindProperty("m_ShadowsEnabled");
m_ShadowIntensity = serializedObject.FindProperty("m_ShadowIntensity");
m_ShadowSoftness = serializedObject.FindProperty("m_ShadowSoftness");
m_ShadowSoftnessFalloffIntensity = serializedObject.FindProperty("m_ShadowSoftnessFalloffIntensity");
m_ShadowVolumeIntensity = serializedObject.FindProperty("m_ShadowVolumeIntensity");
m_ShadowVolumeIntensityEnabled = serializedObject.FindProperty("m_ShadowVolumeIntensityEnabled");
m_VolumetricIntensity = serializedObject.FindProperty("m_LightVolumeIntensity");
m_VolumetricEnabled = serializedObject.FindProperty("m_LightVolumeEnabled");
m_BlendStyleIndex = serializedObject.FindProperty("m_BlendStyleIndex");
m_FalloffIntensity = serializedObject.FindProperty("m_FalloffIntensity");
m_NormalMapZDistance = serializedObject.FindProperty("m_NormalMapDistance");
m_NormalMapQuality = serializedObject.FindProperty("m_NormalMapQuality");
m_LightOrder = serializedObject.FindProperty("m_LightOrder");
m_OverlapOperation = serializedObject.FindProperty("m_OverlapOperation");
m_LightType = serializedObject.FindProperty("m_LightType");
// Point Light
m_PointInnerAngle = serializedObject.FindProperty("m_PointLightInnerAngle");
m_PointOuterAngle = serializedObject.FindProperty("m_PointLightOuterAngle");
m_PointInnerRadius = serializedObject.FindProperty("m_PointLightInnerRadius");
m_PointOuterRadius = serializedObject.FindProperty("m_PointLightOuterRadius");
// Shape Light
m_ShapeLightFalloffSize = serializedObject.FindProperty("m_ShapeLightFalloffSize");
m_ShapeLightSprite = serializedObject.FindProperty("m_LightCookieSprite");
m_SelectionSources = serializedObject.FindProperty("m_SelectionSources");
m_RenderingLayersMask = serializedObject.FindProperty("m_RenderingLayersMask");
m_AnyBlendStyleEnabled = false;
var blendStyleIndices = new List<int>();
var blendStyleNames = new List<string>();
var rendererData = Light2DEditorUtility.GetRenderer2DData();
if (rendererData != null)
{
for (int i = 0; i < rendererData.lightBlendStyles.Length; ++i)
{
blendStyleIndices.Add(i);
ref var blendStyle = ref rendererData.lightBlendStyles[i];
if (blendStyle.maskTextureChannel == Light2DBlendStyle.TextureChannel.None)
blendStyleNames.Add(blendStyle.name);
else
{
var name = string.Format("{0} ({1})", blendStyle.name, blendStyle.maskTextureChannel);
blendStyleNames.Add(name);
}
m_AnyBlendStyleEnabled = true;
}
}
else
{
for (int i = 0; i < 4; ++i)
{
blendStyleIndices.Add(i);
blendStyleNames.Add("Operation" + i);
}
}
m_BlendStyleIndices = blendStyleIndices.ToArray();
m_BlendStyleNames = blendStyleNames.Select(x => new GUIContent(x)).ToArray();
m_SortingLayerDropDown.OnEnable(serializedObject, "m_ApplyToSortingLayers");
}
internal void SendModifiedAnalytics(Analytics.Renderer2DAnalytics analytics, Light2D light)
{
Analytics.LightDataAnalytic lightData = new Analytics.LightDataAnalytic(light.GetEntityId(), false, light.lightType);
Analytics.Renderer2DAnalytics.instance.SendData(lightData);
}
void OnDestroy()
{
if (m_ModifiedLights != null && m_ModifiedLights.Count > 0)
{
foreach (Light2D light in m_ModifiedLights)
{
SendModifiedAnalytics(m_Analytics, light);
}
}
}
void DrawFilteringContent()
{
CoreEditorUtils.DrawSplitter(false);
bool foldoutState = CoreEditorUtils.DrawHeaderFoldout(Styles.filteringSettingsFoldout, m_FilteringSettingsFoldout.value);
if (foldoutState != m_FilteringSettingsFoldout.value)
m_FilteringSettingsFoldout.value = foldoutState;
if (m_FilteringSettingsFoldout.value)
{
m_SortingLayerDropDown.OnTargetSortingLayers(serializedObject, targets, Styles.generalSortingLayerPrefixLabel, AnalyticsTrackChanges);
if (m_LightType.intValue != (int)Light2D.LightType.Global)
{
GUI.enabled = UniversalRenderPipeline.asset.useRenderingLayers;
EditorGUILayout.PropertyField(m_RenderingLayersMask, UniversalRenderPipelineLightUI.Styles.RenderingLayers);
GUI.enabled = true;
if (!UniversalRenderPipeline.asset.useRenderingLayers)
{
CoreEditorUtils.DrawFixMeBox(UniversalRenderPipelineLightUI.Styles.RenderingLayersHelpBox, "Enable", () =>
{
UniversalRenderPipeline.asset.useRenderingLayers = true;
EditorUtility.SetDirty(UniversalRenderPipeline.asset);
});
}
}
}
}
void DrawBlendingGroup()
{
CoreEditorUtils.DrawSplitter(false);
bool foldoutState = CoreEditorUtils.DrawHeaderFoldout(Styles.blendingSettingsFoldout, m_BlendingSettingsFoldout.value);
if (foldoutState != m_BlendingSettingsFoldout.value)
m_BlendingSettingsFoldout.value = foldoutState;
if (m_BlendingSettingsFoldout.value)
{
if (!m_AnyBlendStyleEnabled)
EditorGUILayout.HelpBox(Styles.generalLightNoLightEnabled);
else
EditorGUILayout.IntPopup(m_BlendStyleIndex, m_BlendStyleNames, m_BlendStyleIndices, Styles.generalBlendStyle);
EditorGUILayout.PropertyField(m_LightOrder, Styles.generalLightOrder);
EditorGUILayout.PropertyField(m_OverlapOperation, Styles.generalLightOverlapOperation);
}
}
void DrawShadowsGroup()
{
CoreEditorUtils.DrawSplitter(false);
Light2DEditorUtility.DrawHeaderFoldoutWithToggle(Styles.shadowsSettingsFoldout, m_ShadowsSettingsFoldout, m_ShadowsEnabled);
if (m_ShadowsSettingsFoldout.value)
{
EditorGUI.indentLevel++;
EditorGUI.BeginDisabledGroup(!m_ShadowsEnabled.boolValue);
EditorGUILayout.PropertyField(m_ShadowIntensity, Styles.generalShadowIntensity);
EditorGUILayout.PropertyField(m_ShadowSoftness, Styles.generalShadowSoftness);
EditorGUILayout.PropertyField(m_ShadowSoftnessFalloffIntensity, Styles.generalShadowSoftnessFalloffIntensity);
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel--;
}
}
void DrawVolumetricGroup()
{
CoreEditorUtils.DrawSplitter(false);
Light2DEditorUtility.DrawHeaderFoldoutWithToggle(Styles.volumetricSettingsFoldout, m_VolumetricSettingsFoldout, m_VolumetricEnabled);
if (m_VolumetricSettingsFoldout.value)
{
EditorGUI.indentLevel++;
EditorGUI.BeginDisabledGroup(!m_VolumetricEnabled.boolValue);
EditorGUILayout.PropertyField(m_VolumetricIntensity, Styles.generalVolumeIntensity);
if (m_VolumetricIntensity.floatValue < 0)
m_VolumetricIntensity.floatValue = 0;
DrawToggleProperty(Styles.generalShadowVolumeIntensity, m_ShadowVolumeIntensityEnabled, m_ShadowVolumeIntensity);
EditorGUI.EndDisabledGroup();
EditorGUI.indentLevel--;
}
}
void DrawNormalMapGroup()
{
CoreEditorUtils.DrawSplitter(false);
bool foldoutState = CoreEditorUtils.DrawHeaderFoldout(Styles.normalMapsSettingsFoldout, m_NormalMapsSettingsFoldout.value);
if (foldoutState != m_NormalMapsSettingsFoldout.value)
m_NormalMapsSettingsFoldout.value = foldoutState;
if (m_NormalMapsSettingsFoldout.value)
{
EditorGUILayout.PropertyField(m_NormalMapQuality, Styles.generalNormalMapLightQuality);
EditorGUI.BeginDisabledGroup(m_NormalMapQuality.intValue == (int)Light2D.NormalMapQuality.Disabled);
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(m_NormalMapZDistance, Styles.generalNormalMapZDistance);
if (EditorGUI.EndChangeCheck())
m_NormalMapZDistance.floatValue = Mathf.Max(0.0f, m_NormalMapZDistance.floatValue);
EditorGUI.EndDisabledGroup();
}
}
void DrawFoldouts()
{
DrawBlendingGroup();
DrawShadowsGroup();
DrawVolumetricGroup();
DrawNormalMapGroup();
}
void DrawRadiusProperties(GUIContent label, SerializedProperty innerRadius, GUIContent content1, SerializedProperty outerRadius, GUIContent content2)
{
GUIStyle style = GUI.skin.box;
float savedLabelWidth = EditorGUIUtility.labelWidth;
int savedIndentLevel = EditorGUI.indentLevel;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PrefixLabel(label);
EditorGUILayout.BeginHorizontal();
EditorGUI.indentLevel = 0;
EditorGUIUtility.labelWidth = style.CalcSize(content1).x;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(innerRadius, content1);
if (EditorGUI.EndChangeCheck())
{
if (innerRadius.floatValue > outerRadius.floatValue)
innerRadius.floatValue = outerRadius.floatValue;
else if (innerRadius.floatValue < 0)
innerRadius.floatValue = 0;
}
EditorGUIUtility.labelWidth = style.CalcSize(content2).x;
EditorGUI.BeginChangeCheck();
EditorGUILayout.PropertyField(outerRadius, content2);
if (EditorGUI.EndChangeCheck() && outerRadius.floatValue < innerRadius.floatValue)
outerRadius.floatValue = innerRadius.floatValue;
EditorGUILayout.EndHorizontal();
EditorGUILayout.EndHorizontal();
EditorGUIUtility.labelWidth = savedLabelWidth;
EditorGUI.indentLevel = savedIndentLevel;
}
void DrawToggleProperty(GUIContent label, SerializedProperty boolProperty, SerializedProperty property)
{
int savedIndentLevel = EditorGUI.indentLevel;
float savedLabelWidth = EditorGUIUtility.labelWidth;
const int kCheckboxWidth = 20;
EditorGUILayout.BeginHorizontal();
EditorGUILayout.PropertyField(boolProperty, GUIContent.none, GUILayout.MaxWidth(kCheckboxWidth));
EditorGUIUtility.labelWidth = EditorGUIUtility.labelWidth - kCheckboxWidth;
EditorGUI.BeginDisabledGroup(!boolProperty.boolValue);
EditorGUILayout.PropertyField(property, label);
EditorGUI.EndDisabledGroup();
EditorGUILayout.EndHorizontal();
EditorGUI.indentLevel = savedIndentLevel;
EditorGUIUtility.labelWidth = savedLabelWidth;
}
public void DrawInnerAndOuterSpotAngle(SerializedProperty minProperty, SerializedProperty maxProperty, GUIContent label)
{
float textFieldWidth = 45f;
float min = minProperty.floatValue;
float max = maxProperty.floatValue;
var rect = EditorGUILayout.GetControlRect(true, EditorGUIUtility.singleLineHeight);
// This widget is a little bit of a special case.
// The right hand side of the min max slider will control the reset of the max value
// The left hand side of the min max slider will control the reset of the min value
// The label itself will not have a right click and reset value.
rect = EditorGUI.PrefixLabel(rect, label);
EditorGUI.BeginProperty(new Rect(rect) { width = rect.width * 0.5f }, label, minProperty);
EditorGUI.BeginProperty(new Rect(rect) { xMin = rect.x + rect.width * 0.5f }, GUIContent.none, maxProperty);
var minRect = new Rect(rect) { width = textFieldWidth };
var maxRect = new Rect(rect) { xMin = rect.xMax - textFieldWidth };
var sliderRect = new Rect(rect) { xMin = minRect.xMax + 4, xMax = maxRect.xMin - 4 };
EditorGUI.BeginChangeCheck();
EditorGUI.DelayedFloatField(minRect, minProperty, GUIContent.none);
if (EditorGUI.EndChangeCheck())
{
if (minProperty.floatValue > maxProperty.floatValue)
minProperty.floatValue = maxProperty.floatValue;
else if (minProperty.floatValue < 0)
minProperty.floatValue = 0;
}
EditorGUI.BeginChangeCheck();
EditorGUI.MinMaxSlider(sliderRect, ref min, ref max, 0f, 360f);
if (EditorGUI.EndChangeCheck())
{
minProperty.floatValue = min;
maxProperty.floatValue = max;
}
EditorGUI.BeginChangeCheck();
EditorGUI.DelayedFloatField(maxRect, m_PointOuterAngle, GUIContent.none);
if (EditorGUI.EndChangeCheck())
{
if (minProperty.floatValue > maxProperty.floatValue)
maxProperty.floatValue = minProperty.floatValue;
else if (maxProperty.floatValue > 360)
maxProperty.floatValue = 360;
}
EditorGUI.EndProperty();
EditorGUI.EndProperty();
}
void DrawGlobalLight(SerializedObject serializedObject)
{
DrawBlendingGroup();
}
void DrawProviderLight(SerializedObject serializedObject)
{
bool foldoutState = CoreEditorUtils.DrawHeaderFoldout("Provider", m_ProviderFoldout.value);
if (foldoutState != m_ProviderFoldout.value)
m_ProviderFoldout.value = foldoutState;
serializedObject.Update();
if (m_ProviderFoldout.value)
{
// We have to get this because it may have changed in this editor redraw already
SerializedProperty provider = serializedObject.FindProperty("m_Light2DProvider");
Light2DProvider lightProvider = provider.boxedValue as Light2DProvider;
if (lightProvider != null)
{
Light2DProviderSources.DrawSelectedSourceUI(m_SelectionSources);
}
}
serializedObject.ApplyModifiedProperties();
DrawFoldouts();
}
void DrawParametricDeprecated(SerializedObject serializedObject)
{
GUIContent buttonText = targets.Length > 1 ? Styles.deprecatedParametricLightButtonMulti : Styles.deprecatedParametricLightButtonSingle;
GUIContent helpText = targets.Length > 1 ? Styles.deprecatedParametricLightWarningMulti : Styles.deprecatedParametricLightWarningSingle;
string dialogText = targets.Length > 1 ? Styles.deprecatedParametricLightDialogTextMulti : Styles.deprecatedParametricLightDialogTextSingle;
EditorGUILayout.HelpBox(helpText);
EditorGUILayout.Space();
if (GUILayout.Button(buttonText))
{
if (EditorUtility.DisplayDialog(Styles.deprecatedParametricLightDialogTitle, dialogText, Styles.deprecatedParametricLightDialogProceed, Styles.deprecatedParametricLightDialogCancel))
{
for (int i = 0; i < targets.Length; i++)
{
Light2D light = (Light2D)targets[i];
if (light.lightType == (Light2D.LightType)Light2D.DeprecatedLightType.Parametric)
ParametricToFreeformLightUpgrader.UpgradeParametricLight(light);
}
}
}
EditorGUILayout.Space();
EditorGUILayout.HelpBox(Styles.deprecatedParametricLightInstructions);
}
int GetSelectedValue(Light2DProvider light2DProvider)
{
int selectedValue = m_LightType.intValue;
if (selectedValue == (int)Light2D.LightType.Provider)
{
if (light2DProvider != null)
{
selectedValue = light2DProvider.GetType().GetHashCode();
}
}
return selectedValue;
}
bool DrawLightCommon()
{
bool meshChanged = false;
EditorGUI.BeginChangeCheck();
// Use shared utility method for Light Type dropdown
Light2DEditorUtility.DrawLightTypePopup(default(Rect), Styles.generalLightType, serializedObject, layoutMode: true);
serializedObject.Update();
// Color and intensity
EditorGUILayout.PropertyField(m_LightColor, Styles.generalLightColor);
EditorGUILayout.PropertyField(m_LightIntensity, Styles.generalLightIntensity);
DrawFilteringContent();
serializedObject.ApplyModifiedProperties();
// Only check for duplicates when properties change (avoid spam on every repaint)
if (EditorGUI.EndChangeCheck())
{
m_LightIntensity.floatValue = Mathf.Max(m_LightIntensity.floatValue, 0);
Light2D light = (Light2D)target;
LightUtility.CheckForExistingGlobalLight(light.gameObject);
}
return meshChanged;
}
void DrawSpotLight(SerializedObject serializedObject)
{
bool foldoutState = CoreEditorUtils.DrawHeaderFoldout("Spot", m_ProviderFoldout.value);
if (foldoutState != m_ProviderFoldout.value)
m_ProviderFoldout.value = foldoutState;
if (m_ProviderFoldout.value)
{
DrawRadiusProperties(Styles.pointLightRadius, m_PointInnerRadius, Styles.pointLightInner, m_PointOuterRadius, Styles.pointLightOuter);
DrawInnerAndOuterSpotAngle(m_PointInnerAngle, m_PointOuterAngle, Styles.InnerOuterSpotAngle);
EditorGUILayout.Slider(m_FalloffIntensity, 0, 1, Styles.generalFalloffIntensity);
if (m_ShapeLightSprite.objectReferenceValue != null)
EditorGUILayout.PropertyField(m_ShapeLightSprite, Styles.pointLightSprite);
}
DrawFoldouts();
}
void DrawSpriteLight(SerializedObject serializedObject)
{
bool foldoutState = CoreEditorUtils.DrawHeaderFoldout("Sprite", m_ProviderFoldout.value);
if (foldoutState != m_ProviderFoldout.value)
m_ProviderFoldout.value = foldoutState;
if (m_ProviderFoldout.value)
EditorGUILayout.PropertyField(m_ShapeLightSprite, Styles.shapeLightSprite);
DrawFoldouts();
}
void DrawShapeLight(SerializedObject serializedObject)
{
bool foldoutState = CoreEditorUtils.DrawHeaderFoldout("Freeform", m_ProviderFoldout.value);
if (foldoutState != m_ProviderFoldout.value)
m_ProviderFoldout.value = foldoutState;
if (m_ProviderFoldout.value)
{
EditorGUILayout.PropertyField(m_ShapeLightFalloffSize, Styles.generalFalloffSize);
if (m_ShapeLightFalloffSize.floatValue < 0 || m_ShapeLightFalloffSize.floatValue > Light2D.k_MaxFalloffSize)
m_ShapeLightFalloffSize.floatValue = Mathf.Clamp(m_ShapeLightFalloffSize.floatValue, 0, Light2D.k_MaxFalloffSize);
EditorGUILayout.Slider(m_FalloffIntensity, 0, 1, Styles.generalFalloffIntensity);
if (m_LightType.intValue == (int)Light2D.LightType.Freeform)
{
#if USING_2DCOMMON
DoEditButton<FreeformShapeTool>(PathEditorToolContents.icon, "Edit Shape");
DoPathInspector<FreeformShapeTool>();
#else
var clicked = GUILayout.Button(Styles.buttonText);
if (clicked)
URP2DConverterUtility.InstallPackage("com.unity.2d.common");
else
EditorGUILayout.HelpBox(Styles.helpBox.text, MessageType.Info);
#endif
}
}
DrawFoldouts();
}
Vector3 DrawAngleSlider2D(Transform transform, Quaternion rotation, float radius, float offset, Handles.CapFunction capFunc, float capSize, bool leftAngle, bool drawLine, bool useCapOffset, ref float angle)
{
float oldAngle = angle;
float angleBy2 = (angle / 2) * (leftAngle ? -1.0f : 1.0f);
Vector3 trcwPos = Quaternion.AngleAxis(angleBy2, -transform.forward) * (transform.up);
Vector3 cwPos = transform.position + trcwPos * (radius + offset);
float direction = leftAngle ? 1 : -1;
// Offset the handle
float size = .25f * capSize;
Vector3 handleOffset = useCapOffset ? rotation * new Vector3(direction * size, 0, 0) : Vector3.zero;
EditorGUI.BeginChangeCheck();
var id = GUIUtility.GetControlID("AngleSlider".GetHashCode(), FocusType.Passive);
Vector3 cwHandle = Handles.Slider2D(id, cwPos, handleOffset, Vector3.forward, rotation * Vector3.up, rotation * Vector3.right, capSize, capFunc, Vector3.zero);
if (EditorGUI.EndChangeCheck())
{
Vector3 toCwHandle = (transform.position - cwHandle).normalized;
angle = 360 - 2 * Quaternion.Angle(Quaternion.FromToRotation(transform.up, toCwHandle), Quaternion.identity);
angle = Mathf.Round(angle * 100) / 100f;
float side = Vector3.Dot(direction * transform.right, toCwHandle);
if (side < 0)
{
if (oldAngle < 180)
angle = 0;
else
angle = 360;
}
}
if (drawLine)
Handles.DrawLine(transform.position, cwHandle);
return cwHandle;
}
private float DrawAngleHandle(Transform transform, float radius, float offset, Handles.CapFunction capLeft, Handles.CapFunction capRight, ref float angle)
{
float old = angle;
float handleOffset = HandleUtility.GetHandleSize(transform.position) * offset;
float handleSize = HandleUtility.GetHandleSize(transform.position) * k_AngleCapSize;
Quaternion rotLt = Quaternion.AngleAxis(-angle / 2, -transform.forward) * transform.rotation;
DrawAngleSlider2D(transform, rotLt, radius, handleOffset, capLeft, handleSize, true, true, true, ref angle);
Quaternion rotRt = Quaternion.AngleAxis(angle / 2, -transform.forward) * transform.rotation;
DrawAngleSlider2D(transform, rotRt, radius, handleOffset, capRight, handleSize, false, true, true, ref angle);
return angle - old;
}
private void DrawRadiusArc(Transform transform, float radius, float angle, int steps, Handles.CapFunction capFunc, float capSize, bool even)
{
Handles.DrawWireArc(transform.position, transform.forward, Quaternion.AngleAxis(180 - angle / 2, transform.forward) * -transform.up, angle, radius);
}
Handles.CapFunction GetCapFunc(Texture texture, bool isAngleHandle)
{
return (controlID, position, rotation, size, eventType) => Light2DEditorUtility.GUITextureCap(controlID, texture, position, rotation, size, eventType, isAngleHandle);
}
private void DrawAngleHandles(Light2D light)
{
var oldColor = Handles.color;
Handles.color = Color.yellow;
float outerAngle = light.pointLightOuterAngle;
float diff = DrawAngleHandle(light.transform, light.pointLightOuterRadius, k_AngleCapOffset, GetCapFunc(Styles.lightCapTopRight, true), GetCapFunc(Styles.lightCapBottomRight, true), ref outerAngle);
light.pointLightOuterAngle = outerAngle;
if (diff != 0.0f)
light.pointLightInnerAngle = Mathf.Max(0.0f, light.pointLightInnerAngle + diff);
float innerAngle = light.pointLightInnerAngle;
diff = DrawAngleHandle(light.transform, light.pointLightOuterRadius, -k_AngleCapOffset, GetCapFunc(Styles.lightCapTopLeft, true), GetCapFunc(Styles.lightCapBottomLeft, true), ref innerAngle);
light.pointLightInnerAngle = innerAngle;
if (diff != 0.0f)
light.pointLightInnerAngle = light.pointLightInnerAngle < light.pointLightOuterAngle ? light.pointLightInnerAngle : light.pointLightOuterAngle;
light.pointLightInnerAngle = Mathf.Min(light.pointLightInnerAngle, light.pointLightOuterAngle);
Handles.color = oldColor;
}
private void DrawRangeHandles(Light2D light)
{
var dummy = 0.0f;
bool radiusChanged = false;
Vector3 handlePos = Vector3.zero;
Quaternion rotLeft = Quaternion.AngleAxis(0, -light.transform.forward) * light.transform.rotation;
float handleOffset = HandleUtility.GetHandleSize(light.transform.position) * k_AngleCapOffsetSecondary;
float handleSize = HandleUtility.GetHandleSize(light.transform.position) * k_AngleCapSize;
var oldColor = Handles.color;
Handles.color = Color.yellow;
float outerRadius = light.pointLightOuterRadius;
EditorGUI.BeginChangeCheck();
Vector3 returnPos = DrawAngleSlider2D(light.transform, rotLeft, outerRadius, -handleOffset, GetCapFunc(Styles.lightCapUp, false), handleSize, false, false, false, ref dummy);
if (EditorGUI.EndChangeCheck())
{
var vec = (returnPos - light.transform.position).normalized;
light.transform.up = new Vector3(vec.x, vec.y, 0);
outerRadius = (returnPos - light.transform.position).magnitude;
outerRadius = outerRadius + handleOffset;
radiusChanged = true;
}
DrawRadiusArc(light.transform, light.pointLightOuterRadius, light.pointLightOuterAngle, 0, Handles.DotHandleCap, k_RangeCapSize, false);
Handles.color = Color.gray;
float innerRadius = light.pointLightInnerRadius;
EditorGUI.BeginChangeCheck();
returnPos = DrawAngleSlider2D(light.transform, rotLeft, innerRadius, handleOffset, GetCapFunc(Styles.lightCapDown, false), handleSize, true, false, false, ref dummy);
if (EditorGUI.EndChangeCheck())
{
innerRadius = (returnPos - light.transform.position).magnitude;
innerRadius = innerRadius - handleOffset;
radiusChanged = true;
}
DrawRadiusArc(light.transform, light.pointLightInnerRadius, light.pointLightOuterAngle, 0, Handles.SphereHandleCap, k_InnerRangeCapSize, false);
Handles.color = oldColor;
if (radiusChanged)
{
light.pointLightInnerRadius = (outerRadius < innerRadius) ? outerRadius : innerRadius;
light.pointLightOuterRadius = (innerRadius > outerRadius) ? innerRadius : outerRadius;
}
}
void OnSceneGUI()
{
var light = target as Light2D;
if (light == null)
return;
Transform t = light.transform;
switch (light.lightType)
{
case Light2D.LightType.Point:
{
Undo.RecordObject(light.transform, "Edit Point Light Transform");
Undo.RecordObject(light, "Edit Point Light");
DrawRangeHandles(light);
DrawAngleHandles(light);
if (GUI.changed)
EditorUtility.SetDirty(light);
}
break;
case Light2D.LightType.Sprite:
{
var cookieSprite = light.lightCookieSprite;
if (cookieSprite != null)
{
Vector3 min = cookieSprite.bounds.min;
Vector3 max = cookieSprite.bounds.max;
Vector3 v0 = t.TransformPoint(new Vector3(min.x, min.y));
Vector3 v1 = t.TransformPoint(new Vector3(max.x, min.y));
Vector3 v2 = t.TransformPoint(new Vector3(max.x, max.y));
Vector3 v3 = t.TransformPoint(new Vector3(min.x, max.y));
Handles.DrawLine(v0, v1);
Handles.DrawLine(v1, v2);
Handles.DrawLine(v2, v3);
Handles.DrawLine(v3, v0);
}
}
break;
case Light2D.LightType.Freeform:
{
// Draw the falloff shape's outline
List<Vector2> falloffShape = light.GetFalloffShape();
Handles.color = Color.white;
for (int i = 0; i < falloffShape.Count - 1; ++i)
{
Handles.DrawLine(t.TransformPoint(falloffShape[i]), t.TransformPoint(falloffShape[i + 1]));
}
if (falloffShape.Count > 0)
Handles.DrawLine(t.TransformPoint(falloffShape[falloffShape.Count - 1]), t.TransformPoint(falloffShape[0]));
for (int i = 0; i < light.shapePath.Length - 1; ++i)
{
Handles.DrawLine(t.TransformPoint(light.shapePath[i]),
t.TransformPoint(light.shapePath[i + 1]));
}
if (light.shapePath.Length > 0)
Handles.DrawLine(t.TransformPoint(light.shapePath[light.shapePath.Length - 1]), t.TransformPoint(light.shapePath[0]));
}
break;
}
}
public override void OnInspectorGUI()
{
var meshChanged = false;
serializedObject.Update();
UniversalRenderPipelineAsset asset = UniversalRenderPipeline.asset;
if (asset != null)
{
if (!Light2DEditorUtility.IsUsing2DRenderer())
{
EditorGUILayout.HelpBox(Styles.asset2DUnassignedWarning);
}
else
{
if (m_LightType.intValue != (int)Light2D.DeprecatedLightType.Parametric)
meshChanged = DrawLightCommon();
switch (m_LightType.intValue)
{
case (int)Light2D.LightType.Point:
{
DrawSpotLight(serializedObject);
}
break;
case (int)Light2D.LightType.Freeform:
{
DrawShapeLight(serializedObject);
}
break;
case (int)Light2D.LightType.Sprite:
{
DrawSpriteLight(serializedObject);
}
break;
case (int)Light2D.LightType.Global:
{
DrawGlobalLight(serializedObject);
}
break;
case (int)Light2D.DeprecatedLightType.Parametric:
{
DrawParametricDeprecated(serializedObject);
}
break;
case (int)Light2D.LightType.Provider:
{
Light2D light = target as Light2D;
DrawProviderLight(serializedObject);
}
break;
}
AnalyticsTrackChanges(serializedObject);
if (serializedObject.ApplyModifiedProperties())
{
if (meshChanged)
lightObject.UpdateMesh();
}
}
}
else
{
EditorGUILayout.HelpBox(Styles.renderPipelineUnassignedWarning);
if (meshChanged)
lightObject.UpdateMesh();
}
}
}
internal class Light2DPostProcess : AssetPostprocessor
{
void OnPostprocessSprites(Texture2D texture, Sprite[] sprites)
{
var lights = Resources.FindObjectsOfTypeAll<Light2D>().Where(x => x.lightType == Light2D.LightType.Sprite && x.lightCookieSprite == null);
foreach (var light in lights)
light.MarkForUpdate();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c2bef50bb856f744080489123f6b3f84
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,271 @@
using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
internal static class Light2DEditorUtility
{
internal static readonly string ResourcePath = "Packages/com.unity.render-pipelines.universal/Editor/2D/ResourceIcons/";
private static class Styles
{
static GUIContent s_LightTypeFreeform;
static GUIContent s_LightTypeSprite;
static GUIContent s_LightTypePoint;
static GUIContent s_LightTypeGlobal;
public static GUIContent lightTypeFreeform => s_LightTypeFreeform ??= new GUIContent("Freeform", LoadIcon("FreeformLight.png"));
public static GUIContent lightTypeSprite => s_LightTypeSprite ??= new GUIContent("Sprite", LoadIcon("SpriteLight.png"));
public static GUIContent lightTypePoint => s_LightTypePoint ??= new GUIContent("Spot", LoadIcon("PointLight.png"));
public static GUIContent lightTypeGlobal => s_LightTypeGlobal ??= new GUIContent("Global", LoadIcon("GlobalLight.png"));
static Texture LoadIcon(string fileName) => AssetDatabase.LoadAssetAtPath<Texture>(ResourcePath + "InspectorIcons/" + fileName);
}
static Material s_TexCapMaterial = CoreUtils.CreateEngineMaterial(Shader.Find("Hidden/Internal-GUITexture"));
static Mesh k_MeshQuad_Cache;
static Mesh k_MeshQuad => k_MeshQuad_Cache == null || k_MeshQuad_Cache.Equals(null) ? (k_MeshQuad_Cache = Resources.GetBuiltinResource<Mesh>("Quad.fbx")) : k_MeshQuad_Cache;
/// <summary>
/// Draws the Light Type dropdown for a Light2D component using the provider system.
/// </summary>
/// <remarks>
/// This method provides a unified way to render the Light Type dropdown in both the Inspector and Light Explorer windows.
/// It automatically scans for custom Light2DProvider components on the GameObject and includes them in the dropdown
/// alongside built-in light types (Spot, Freeform, Sprite, Global).
///
/// The method handles:
/// - Scanning for custom providers on the GameObject
/// - Synchronizing the dropdown selection with the actual light type value
/// - Detecting and applying user changes only when necessary
/// - Supporting both layout-based (Inspector) and rect-based (Light Explorer) rendering
/// </remarks>
/// <param name="position">The rect to draw the control in. This parameter is ignored when <paramref name="layoutMode"/> is true.</param>
/// <param name="label">The label to display next to the dropdown. Pass <see cref="GUIContent.none"/> for no label.</param>
/// <param name="serializedObject">The SerializedObject containing the Light2D component. Must not be null.</param>
/// <param name="layoutMode">If true, uses EditorGUILayout for automatic layout. If false, uses EditorGUI with the provided <paramref name="position"/> rect.</param>
public static void DrawLightTypePopup(Rect position, GUIContent label, SerializedObject serializedObject, bool layoutMode)
{
serializedObject.Update();
SerializedProperty selectionSources = serializedObject.FindProperty("m_SelectionSources");
SerializedProperty lightType = serializedObject.FindProperty("m_LightType");
if (selectionSources == null || lightType == null)
return;
// Get the Light2D component and its GameObject
Light2D light2D = serializedObject.targetObject as Light2D;
if (light2D == null)
return;
Light2DProviderSources sources = selectionSources.boxedValue as Light2DProviderSources;
if (sources == null)
return;
// Set up the built-in light types
List<SelectionSource> additionalSources = new List<SelectionSource>
{
new Light2DSource_BuiltIn(Styles.lightTypePoint, Light2D.LightType.Point, 0),
new Light2DSource_BuiltIn(Styles.lightTypeFreeform, Light2D.LightType.Freeform, 0),
new Light2DSource_BuiltIn(Styles.lightTypeSprite, Light2D.LightType.Sprite, 0),
new Light2DSource_BuiltIn(Styles.lightTypeGlobal, Light2D.LightType.Global, 0),
};
// Refresh sources to scan for custom providers on the GameObject
int selectedIndex = Provider2DSources<Light2DProvider, Light2DProviderSource>.RefreshSources(sources, light2D.gameObject, 0);
// Add built-in types
var additionalSourcesList = sources.GetAdditionalSources();
if (additionalSourcesList != null)
{
additionalSourcesList.Clear();
foreach (var source in additionalSources)
additionalSourcesList.Add(source);
}
// Refresh again to include the built-in types
selectedIndex = Provider2DSources<Light2DProvider, Light2DProviderSource>.RefreshSources(sources, light2D.gameObject, 0);
// Sync m_SelectionSources with the actual m_LightType value
// This is needed because Light Explorer may have changed m_LightType directly
if (lightType.intValue != (int)Light2D.LightType.Provider && sources.selectedHashCode != lightType.intValue)
{
sources.selectedHashCode = lightType.intValue;
selectedIndex = Provider2DSources<Light2DProvider, Light2DProviderSource>.RefreshSources(sources, light2D.gameObject, 0);
}
// Get all source names for the dropdown
GUIContent[] sourceNames = sources.GetSourceNames();
// Track change
EditorGUI.BeginChangeCheck();
int newSelectedIndex;
// Draw the dropdown using the appropriate mode
if (layoutMode)
{
newSelectedIndex = EditorGUILayout.Popup(label, selectedIndex, sourceNames);
}
else
{
newSelectedIndex = EditorGUI.Popup(position, selectedIndex, sourceNames);
}
// Only apply changes if the user actually changed the value
if (EditorGUI.EndChangeCheck())
{
Provider2DSources<Light2DProvider, Light2DProviderSource>.UpdateSelectionFromIndex(sources, newSelectedIndex);
selectionSources.boxedValue = sources;
Light2DProviderSources.SetSourceType(selectionSources);
}
}
static internal bool ContainsVisibleInspectorProperites(Provider2D provider)
{
Debug.Assert(provider != null);
var type = provider.GetType();
return type.GetFields(BindingFlags.Instance | BindingFlags.Public).Length > 0;
}
static internal void DrawHeaderFoldoutWithToggle(GUIContent title, SavedBool foldoutState, SerializedProperty toggleState, string documentationURL = "")
{
const float height = 17f;
var backgroundRect = GUILayoutUtility.GetRect(0, 0);
float xMin = backgroundRect.xMin;
var labelRect = backgroundRect;
labelRect.yMax += height;
labelRect.xMin += 16f;
labelRect.xMax -= 20f;
bool newToggleState = GUI.Toggle(labelRect, toggleState.boolValue, " "); // Needs a space because the checkbox won't have a proper outline if we don't make a space here
bool newFoldoutState = CoreEditorUtils.DrawHeaderFoldout("", foldoutState.value);
if (newToggleState != toggleState.boolValue)
toggleState.boolValue = newToggleState;
if (newFoldoutState != foldoutState.value)
foldoutState.value = newFoldoutState;
labelRect.xMin += 20;
EditorGUI.LabelField(labelRect, title, EditorStyles.boldLabel);
}
static internal void GUITextureCap(int controlID, Texture texture, Vector3 position, Quaternion rotation, float size, EventType eventType, bool isAngleHandle)
{
switch (eventType)
{
case (EventType.Layout):
{
Vector2 size2 = Vector2.one * size * 0.5f;
if (isAngleHandle)
size2.x = 0.0f;
HandleUtility.AddControl(controlID, DistanceToRectangle(position, rotation, size2));
break;
}
case (EventType.Repaint):
{
s_TexCapMaterial.mainTexture = texture;
s_TexCapMaterial.SetPass(0);
float w = texture.width;
float h = texture.height;
float max = Mathf.Max(w, h);
Vector3 scale = new Vector2(w / max, h / max) * size * 0.5f;
if (Camera.current == null)
scale.y *= -1f;
Matrix4x4 matrix = new Matrix4x4();
matrix.SetTRS(position, rotation, scale);
Graphics.DrawMeshNow(k_MeshQuad, matrix);
}
break;
}
}
static float DistanceToRectangle(Vector3 position, Quaternion rotation, Vector2 size)
{
Vector3[] points = { Vector3.zero, Vector3.zero, Vector3.zero, Vector3.zero, Vector3.zero };
Vector3 sideways = rotation * new Vector3(size.x, 0, 0);
Vector3 up = rotation * new Vector3(0, size.y, 0);
points[0] = HandleUtility.WorldToGUIPoint(position + sideways + up);
points[1] = HandleUtility.WorldToGUIPoint(position + sideways - up);
points[2] = HandleUtility.WorldToGUIPoint(position - sideways - up);
points[3] = HandleUtility.WorldToGUIPoint(position - sideways + up);
points[4] = points[0];
Vector2 pos = Event.current.mousePosition;
bool oddNodes = false;
int j = 4;
for (int i = 0; i < 5; ++i)
{
if ((points[i].y > pos.y) != (points[j].y > pos.y))
{
if (pos.x < (points[j].x - points[i].x) * (pos.y - points[i].y) / (points[j].y - points[i].y) + points[i].x)
oddNodes = !oddNodes;
}
j = i;
}
if (!oddNodes)
{
// Distance to closest edge (not so fast)
float dist, closestDist = -1f;
j = 1;
for (int i = 0; i < 4; ++i)
{
dist = HandleUtility.DistancePointToLineSegment(pos, points[i], points[j++]);
if (dist < closestDist || closestDist < 0)
closestDist = dist;
}
return closestDist;
}
else
return 0;
}
internal static Renderer2DData GetRenderer2DData()
{
UniversalRenderPipelineAsset pipelineAsset = UniversalRenderPipeline.asset;
if (pipelineAsset == null)
return null;
// try get the default
Renderer2DData rendererData = pipelineAsset.scriptableRendererData as Renderer2DData;
if (rendererData == null)
{
foreach (Camera camera in Camera.allCameras)
{
UniversalAdditionalCameraData additionalCameraData = camera.GetComponent<UniversalAdditionalCameraData>();
ScriptableRenderer renderer = additionalCameraData?.scriptableRenderer;
Renderer2D renderer2D = renderer as Renderer2D;
if (renderer2D != null)
return renderer2D.GetRenderer2DData();
}
}
return rendererData;
}
internal static bool IsUsing2DRenderer()
{
return GetRenderer2DData() != null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 62e1d3960d9dba84780a633cbb9f63c2
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,247 @@
using System.Collections.Generic;
using UnityEditor.SceneManagement;
using UnityEngine;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
namespace UnityEditor.Rendering.Universal
{
/// <summary>
/// Scans the project's build scenes for <see cref="Light2D"/> components and records the
/// minimal set of shader keyword combinations the runtime can request from
/// <c>Hidden/Light2D</c>. The result is used by <c>ShaderBuildPreprocessor</c> to populate
/// <see cref="UniversalRenderPipelineAsset.ShaderPrefilteringData.light2DKeptVariantCombos"/>
/// and by <see cref="ShaderScriptableStripper"/> to trim Light2D variants per build.
/// </summary>
static class Light2DPrefilteringAnalysis
{
// Shader keywords (mirror Runtime/2D/Passes/Utility/RendererLighting.cs).
const string kUseNormalMapKeyword = "USE_NORMAL_MAP";
const string kUsePointLightCookiesKeyword = "USE_POINT_LIGHT_COOKIES";
const string kLightQualityFastKeyword = "LIGHT_QUALITY_FAST";
const string kUseShadowMapKeyword = "USE_SHADOW_MAP";
const string kUseAdditiveBlendingKeyword = "USE_ADDITIVE_BLENDING";
const string kUseVolumetricKeyword = "USE_VOLUMETRIC";
// Global multi_compile keywords from Include/ShapeLightShared.hlsl, toggled per draw by
// RendererLighting.EnableBlendStyle. For Hidden/Light2D, runtime usage is bounded:
// - Non-volumetric draws enable exactly one USE_SHAPE_LIGHT_TYPE_<blendStyleIndex>.
// - Volumetric draws enable none (the USE_DEFAULT_LIGHT_TYPE shader fallback handles it).
// - On GLES3 (Renderer2D.supportsMRT == false) the index is forced to 0 regardless.
// The 11 multi-keyword combinations multi_compile generates are unreachable for this shader.
static readonly string[] kShapeLightTypeKeywords =
{
"USE_SHAPE_LIGHT_TYPE_0",
"USE_SHAPE_LIGHT_TYPE_1",
"USE_SHAPE_LIGHT_TYPE_2",
"USE_SHAPE_LIGHT_TYPE_3",
};
/// <summary>
/// Sentinel string used by callers (and the scriptable stripper) to denote the
/// all-keywords-off combination. Matches the encoding produced by <see cref="RecordVariant"/>.
/// </summary>
internal const string kEmptyComboSentinel = "<none>";
internal static List<int> blendStylesIndices = new List<int>();
/// <summary>
/// Walks every enabled build scene and returns the set of comma-joined keyword combos
/// that <see cref="RendererLighting.CreateLightMaterial"/> could legitimately request at
/// runtime. Scenes opened by this method are closed before returning so we don't disturb
/// the user's editor workspace.
/// </summary>
internal static string[] AnalyzeBuildScenes()
{
HashSet<string> combos = new HashSet<string>();
EditorBuildSettingsScene[] scenes = EditorBuildSettings.scenes;
foreach (var sceneSettings in scenes)
{
if (!sceneSettings.enabled)
continue;
Scene scene = EditorSceneManager.GetSceneByPath(sceneSettings.path);
bool weOpenedIt = !scene.isLoaded;
// Open as a preview scene rather than additively: Light2DManager registers preview
// scene lights in a per scene list, so a global light in a build scene can't be
// mistaken for a duplicate of one in a scene the user already has open.
if (weOpenedIt)
scene = EditorSceneManager.OpenPreviewScene(sceneSettings.path);
try
{
AnalyzeSceneForLights(scene, combos);
}
finally
{
// Close before moving on so Light2DManager doesn't accumulate lights across
// scenes (otherwise duplicate-global-light asserts can fire against lights from
// previously opened scenes).
if (weOpenedIt)
EditorSceneManager.ClosePreviewScene(scene);
}
}
string[] result = new string[combos.Count];
combos.CopyTo(result);
return result;
}
static void AnalyzeSceneForLights(Scene scene, HashSet<string> combos)
{
GameObject[] rootObjects = scene.GetRootGameObjects();
List<Light2D> lights = new List<Light2D>();
foreach (var rootObject in rootObjects)
lights.AddRange(rootObject.GetComponentsInChildren<Light2D>(true));
blendStylesIndices.Clear();
// Populate used blend style indices
// Eg. If blend styles 0 and 3 are used, we only need to know indices 0 and 1 will be used for MRT and strip accordingly
foreach (var light in lights)
{
if (!blendStylesIndices.Contains(light.blendStyleIndex))
blendStylesIndices.Add(light.blendStyleIndex);
}
blendStylesIndices.Sort();
foreach (var light in lights)
AnalyzeLight(light, combos);
}
static void AnalyzeLight(Light2D light, HashSet<string> combos)
{
if (light == null)
return;
// The runtime resolves useShadows per draw from layer-batch state, not from
// light.shadowsEnabled directly, so the stripper can't predict which variant any given
// frame will request. Record every variant the runtime could possibly select:
// - Non-volumetric: no-shadow is always reachable; with-shadow only if shadowsEnabled.
// - Volumetric: no-shadow is reachable when volumetricEnabled; with-shadow
// additionally requires renderVolumetricShadows.
RecordVariant(light, isVolume: false, useShadows: false, combos);
if (light.shadowsEnabled)
RecordVariant(light, isVolume: false, useShadows: true, combos);
if (light.volumetricEnabled)
{
RecordVariant(light, isVolume: true, useShadows: false, combos);
if (light.renderVolumetricShadows)
RecordVariant(light, isVolume: true, useShadows: true, combos);
}
}
// Mirrors the keyword logic in RendererLighting.CreateLightMaterial plus the per-draw
// USE_SHAPE_LIGHT_TYPE_N selection in DrawLight2DPass.Execute.
static void RecordVariant(Light2D light, bool isVolume, bool useShadows, HashSet<string> combos)
{
bool isPoint = light.lightType == Light2D.LightType.Point;
List<string> keywords = new List<string>();
if (light.normalMapQuality != Light2D.NormalMapQuality.Disabled)
keywords.Add(kUseNormalMapKeyword);
if (isPoint && light.lightCookieSprite != null && light.lightCookieSprite.texture != null)
keywords.Add(kUsePointLightCookiesKeyword);
if (light.normalMapQuality == Light2D.NormalMapQuality.Fast)
keywords.Add(kLightQualityFastKeyword);
if (useShadows)
keywords.Add(kUseShadowMapKeyword);
// USE_ADDITIVE_BLENDING and USE_VOLUMETRIC are mutually exclusive: CreateLightMaterial
// only sets USE_ADDITIVE_BLENDING on non-volume materials and only sets USE_VOLUMETRIC
// on volume materials.
if (isVolume)
keywords.Add(kUseVolumetricKeyword);
else if (light.overlapOperation == Light2D.OverlapOperation.Additive)
keywords.Add(kUseAdditiveBlendingKeyword);
// Per-draw USE_SHAPE_LIGHT_TYPE_N selection. Volumetric draws don't set any (the shader
// falls back to USE_DEFAULT_LIGHT_TYPE). Non-volumetric draws set exactly one — the
// light's blendStyleIndex, plus USE_SHAPE_LIGHT_TYPE_0 as a GLES3 safety net (where
// Renderer2D.supportsMRT is false and indicesIndex is forced to 0).
if (isVolume)
{
AddCombo(combos, keywords, shapeLightKeyword: null);
}
else
{
int blendStyleIndex = blendStylesIndices.IndexOf(light.blendStyleIndex);
if (blendStyleIndex >= 0 && blendStyleIndex < kShapeLightTypeKeywords.Length)
AddCombo(combos, keywords, kShapeLightTypeKeywords[blendStyleIndex]);
if (blendStyleIndex != 0)
AddCombo(combos, keywords, kShapeLightTypeKeywords[0]);
}
}
static void AddCombo(HashSet<string> combos, List<string> baseKeywords, string shapeLightKeyword)
{
if (shapeLightKeyword == null)
{
string combo = baseKeywords.Count > 0 ? string.Join(",", baseKeywords) : kEmptyComboSentinel;
combos.Add(combo);
return;
}
if (baseKeywords.Count == 0)
{
combos.Add(shapeLightKeyword);
return;
}
// Append shape-light keyword to maintain a stable ordering that matches BuildComboString.
combos.Add(string.Join(",", baseKeywords) + "," + shapeLightKeyword);
}
/// <summary>
/// Builds the comma-joined combo string from a runtime variant's keyword set. Includes the
/// six Light2D shader_feature_local keywords (USE_*, LIGHT_QUALITY_FAST) plus any enabled
/// USE_SHAPE_LIGHT_TYPE_N global keyword. _LIGHT_LAYERS is intentionally ignored — URP's
/// existing prefiltering already gates that one via m_PrefilterWriteRenderingLayers.
///
/// Variants with more than one USE_SHAPE_LIGHT_TYPE_N set will produce a combo string that
/// can't match any recorded combo (which only ever contain zero or one), so they're
/// naturally stripped — those multi-keyword combinations are unreachable from
/// DrawLight2DPass at runtime anyway.
/// </summary>
internal static string BuildComboString(UnityEngine.Rendering.ShaderKeywordSet keywordSet, UnityEngine.Shader shader)
{
List<string> keywords = new List<string>();
AddIfEnabled(keywordSet, shader, kUseNormalMapKeyword, keywords);
AddIfEnabled(keywordSet, shader, kUsePointLightCookiesKeyword, keywords);
AddIfEnabled(keywordSet, shader, kLightQualityFastKeyword, keywords);
AddIfEnabled(keywordSet, shader, kUseShadowMapKeyword, keywords);
AddIfEnabled(keywordSet, shader, kUseAdditiveBlendingKeyword, keywords);
AddIfEnabled(keywordSet, shader, kUseVolumetricKeyword, keywords);
// USE_SHAPE_LIGHT_TYPE_N are global multi_compile keywords from ShapeLightShared.hlsl.
// They live in the shader's keyword space (declared via #pragma multi_compile), so the
// shader-scoped ShaderKeyword lookup finds them without needing them to be registered
// in Unity's global keyword namespace first.
for (int i = 0; i < kShapeLightTypeKeywords.Length; i++)
AddIfEnabled(keywordSet, shader, kShapeLightTypeKeywords[i], keywords);
return keywords.Count > 0 ? string.Join(",", keywords) : kEmptyComboSentinel;
}
// Looks up the keyword in the shader's keyword space (which contains both shader_feature_local
// / multi_compile_local entries AND multi_compile globals declared by the shader). Uses
// ShaderKeyword(Shader, string) rather than LocalKeyword/GlobalKeyword because that
// constructor silently sets IsValid=false for unknown names instead of logging an error;
// safe to call for every variant query even when keywords aren't all registered yet.
static void AddIfEnabled(UnityEngine.Rendering.ShaderKeywordSet keywordSet, UnityEngine.Shader shader, string keywordName, List<string> output)
{
var keyword = new UnityEngine.Rendering.ShaderKeyword(shader, keywordName);
if (keyword.IsValid() && keywordSet.IsEnabled(keyword))
output.Add(keywordName);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 7b3a8c4d2f9e4b66a1d4c7e0f1b9a823
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: bf4452fea996a7a468c7d5443cf2ff2e
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,12 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xmlns:uie="UnityEditor.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance" engine="UnityEngine.UIElements" editor="UnityEditor.UIElements" noNamespaceSchemaLocation="../../UIElementsSchema/UIElements.xsd" editor-extension-mode="False">
<Style src="project://database/Packages/com.unity.render-pipelines.universal/Editor/2D/LightBatchingDebugger/LightBatchingDebugger.uss?fileID=7433441132597879392&amp;guid=fd5cb3dd3de574f1585db92b6689f86a&amp;type=3#LightBatchingDebugger" />
<ui:VisualElement class="BatchList BatchContainer">
<ui:Label name="BatchIndex" class="BatchList IndexColumn Batch" />
<ui:VisualElement name="BatchColor" class="BatchList ColorColumn" />
<ui:VisualElement name="LayerNames" class="BatchList NameColumn Batch" />
</ui:VisualElement>
</ui:UXML>
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 754a67c6d4788447895a4349508b2f37
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0}
@@ -0,0 +1,602 @@
using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Accessibility;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using UnityEngine.UIElements;
namespace UnityEditor.Rendering.Universal
{
internal class LightBatchingDebugger : EditorWindow
{
private const string ResourcePath = "Packages/com.unity.render-pipelines.universal/Editor/2D/LightBatchingDebugger/";
private class LayerBatch
{
public List<string> LayerNames = new List<string>();
public List<UnityEngine.Object> Lights = new List<UnityEngine.Object>();
public List<UnityEngine.Object> Shadows = new List<UnityEngine.Object>();
public int batchId;
}
[MenuItem("Window/2D/Light Batching Debugger")]
public static void ShowExample()
{
// Open Game View
EditorApplication.ExecuteMenuItem("Window/General/Game");
LightBatchingDebugger wnd = GetWindow<LightBatchingDebugger>();
wnd.titleContent = new GUIContent("Light Batching Debugger");
}
VisualElement root => rootVisualElement;
private static Color[] batchColors = new Color[10];
private List<LayerBatch> batchList = new List<LayerBatch>();
private List<int> selectedIndices = new List<int>();
private ListView batchListView;
private int lightCount = 0;
private int shadowCount = 0;
// Variables used for refresh view
static bool doRefresh;
private SceneHandle cachedSceneHandle;
private Vector3 cachedCamPos;
private int totalLightCount;
private int totalShadowCount;
private string[] cachedLightNames;
private string[] cachedShadowCasterNames;
ILight2DCullResult lightCullResult
{
get
{
return renderer2DData?.lightCullResult;
}
}
private static List<ShadowCaster2D> GetAllShadowCasters(HashSet<ShadowCasterGroup2D> shadowGroups)
{
var result = new List<ShadowCaster2D>();
foreach (var group in shadowGroups)
{
foreach (var caster in group.GetShadowCasters())
result.Add(caster);
}
return result;
}
private static List<UnityEngine.Object> GetExcept(List<UnityEngine.Object> source, List<UnityEngine.Object> exclude)
{
var excludeSet = new HashSet<UnityEngine.Object>(exclude);
var result = new List<UnityEngine.Object>();
foreach (var item in source)
{
if (!excludeSet.Contains(item))
result.Add(item);
}
return result;
}
private static void GetFirstAndLast(IEnumerable<int> source, out int first, out int last, out int count)
{
first = -1;
last = -1;
count = 0;
foreach (var item in source)
{
if (count == 0)
first = item;
last = item;
count++;
}
}
private static bool ExistsWithName(List<ShadowCaster2D> list, string name)
{
foreach (var item in list)
{
if (item != null && item.name == name)
return true;
}
return false;
}
Renderer2DData renderer2DData
{
get
{
// Game view main camera
var renderer = Camera.main?.GetUniversalAdditionalCameraData().scriptableRenderer as Renderer2D;
return renderer?.GetRenderer2DData();
}
}
[RuntimeInitializeOnLoadMethod]
static void ResetStaticsOnLoad()
{
doRefresh = true;
}
private bool PopulateData()
{
if (lightCullResult == null)
return false;
batchList.Clear();
var layers = Light2DManager.GetCachedSortingLayer();
var batches = LayerUtility.CalculateBatches(renderer2DData, out var batchCount);
for (var i = 0; i < batchCount; i++)
{
var batchInfo = new LayerBatch
{
batchId = i
};
var batch = batches[i];
// Get the lights
foreach (var light in lightCullResult.visibleLights)
{
// If the lit layers are different, or if they are lit but this is a shadow casting light then don't batch.
if (light.IsLitLayer(batch.startLayerID))
{
batchInfo.Lights.Add(light);
}
}
// Get the shadows
var visibleShadows = GetAllShadowCasters(lightCullResult.visibleShadows);
foreach (var shadowCaster in visibleShadows)
{
if (shadowCaster.IsShadowedLayer(batch.startLayerID))
batchInfo.Shadows.Add(shadowCaster);
}
for (var batchIndex = batch.startIndex; batchIndex <= batch.endIndex; batchIndex++)
{
batchInfo.LayerNames.Add(layers[batchIndex].name);
}
batchList.Add(batchInfo);
}
return true;
}
private VisualElement MakePill(UnityEngine.Object obj)
{
var bubble = new Button();
bubble.AddToClassList("Pill");
bubble.text = obj.name;
bubble.style.maxWidth = 200;
bubble.style.overflow = Overflow.Hidden;
bubble.style.textOverflow = TextOverflow.Ellipsis;
bubble.clicked += () =>
{
Selection.activeObject = obj;
};
return bubble;
}
private VisualElement GetInfoView()
{
// Hide initial prompt
DisplayInitialPrompt(false);
return root.Query<VisualElement>("InfoView").First();
}
private void ViewBatch(int index)
{
if (index >= batchList.Count)
return;
var infoView = GetInfoView();
var batch1 = batchList[index];
var title = root.Query<Label>("InfoTitle").First();
title.text = $"<b>Batch {batch1.batchId}</b>" + " selected. Select any two adjacent batches to compare.";
var title2 = root.Query<Label>("InfoTitle2").First();
title2.text = "";
// Add Light Pill VisualElements
var lightLabel1 = infoView.Query<Label>("LightLabel1").First();
lightLabel1.text = $"Lights in <b>Batch {batch1.batchId}:</b>";
if (batch1.Lights.Count == 0)
lightLabel1.text += "\n\nNo lights found.";
var lightBubble1 = infoView.Query<VisualElement>("LightBubble1").First();
lightBubble1.Clear();
foreach (var obj in batch1.Lights)
{
if (obj != null)
lightBubble1.Add(MakePill(obj));
}
var lightLabel2 = infoView.Query<Label>("LightLabel2").First();
lightLabel2.text = "";
var lightBubble2 = infoView.Query<VisualElement>("LightBubble2").First();
lightBubble2.Clear();
// Add Shadow Caster Pill VisualElements
var shadowLabel1 = infoView.Query<Label>("ShadowLabel1").First();
shadowLabel1.text = $"Shadow Casters in <b>Batch {batch1.batchId}:</b>";
if (batch1.Shadows.Count == 0)
shadowLabel1.text += "\n\nNo shadow casters found.";
var shadowBubble1 = infoView.Query<VisualElement>("ShadowBubble1").First();
shadowBubble1.Clear();
foreach (var obj in batch1.Shadows)
{
if (obj != null)
shadowBubble1.Add(MakePill(obj));
}
var shadowLabel2 = infoView.Query<Label>("ShadowLabel2").First();
shadowLabel2.text = "";
var shadowBubble2 = infoView.Query<VisualElement>("ShadowBubble2").First();
shadowBubble2.Clear();
lightCount = batch1.Lights.Count;
shadowCount = batch1.Shadows.Count;
}
private void CompareBatch(int index1, int index2)
{
// Each editor window contains a root VisualElement object
var infoView = GetInfoView();
LayerBatch batch1;
LayerBatch batch2;
if (batchList[index1].batchId < batchList[index2].batchId)
{
batch1 = batchList[index1];
batch2 = batchList[index2];
}
else
{
batch1 = batchList[index2];
batch2 = batchList[index1];
}
// Do batch comparisons
var lightSet1 = GetExcept(batch1.Lights, batch2.Lights);
var lightSet2 = GetExcept(batch2.Lights, batch1.Lights);
var shadowSet1 = GetExcept(batch1.Shadows, batch2.Shadows);
var shadowSet2 = GetExcept(batch2.Shadows, batch1.Shadows);
// Change InfoTitle description when comparing batches
var title = root.Query<Label>("InfoTitle").First();
title.text = $"Comparing <b>Batch {batch1.batchId}</b> and <b>Batch {batch2.batchId}</b>.";
var title2 = root.Query<Label>("InfoTitle2").First();
title2.text = $"To batch <b>Batch {batch1.batchId}</b> and <b>Batch {batch2.batchId}</b>, ensure that the Sorting Layers in both batches share the same set of Lights and Shadow Casters.";
// Light batch comparison
var lightLabel1 = infoView.Query<Label>("LightLabel1").First();
lightLabel1.text = $"Lights only in <b>Batch {batch1.batchId}:</b>";
if (lightSet1.Count == 0)
lightLabel1.text += "\n\nNo lights found.";
var lightBubble1 = infoView.Query<VisualElement>("LightBubble1").First();
lightBubble1.Clear();
foreach (var obj in lightSet1)
{
if (obj != null)
lightBubble1.Add(MakePill(obj));
}
var lightLabel2 = infoView.Query<Label>("LightLabel2").First();
lightLabel2.text = $"Lights only in <b>Batch {batch2.batchId}:</b>";
if (lightSet2.Count == 0)
lightLabel2.text += "\n\nNo lights found.";
var lightBubble2 = infoView.Query<VisualElement>("LightBubble2").First();
lightBubble2.Clear();
foreach (var obj in lightSet2)
{
if (obj != null)
lightBubble2.Add(MakePill(obj));
}
// Shadow caster batch comparison
var shadowLabel1 = infoView.Query<Label>("ShadowLabel1").First();
shadowLabel1.text = $"Shadow Casters only in <b>Batch {batch1.batchId}:</b>";
if (shadowSet1.Count == 0)
shadowLabel1.text += "\n\nNo shadow casters found.";
var shadowBubble1 = infoView.Query<VisualElement>("ShadowBubble1").First();
shadowBubble1.Clear();
foreach (var obj in shadowSet1)
{
if (obj != null)
shadowBubble1.Add(MakePill(obj));
}
var shadowLabel2 = infoView.Query<Label>("ShadowLabel2").First();
shadowLabel2.text = $"Shadow Casters only in <b>Batch {batch2.batchId}:</b>";
if (shadowSet2.Count == 0)
shadowLabel2.text += "\n\nNo shadow casters found.";
var shadowBubble2 = infoView.Query<VisualElement>("ShadowBubble2").First();
shadowBubble2.Clear();
foreach (var obj in shadowSet2)
{
if (obj != null)
shadowBubble2.Add(MakePill(obj));
}
lightCount = lightSet1.Count + lightSet2.Count;
shadowCount = shadowSet1.Count + shadowSet2.Count;
}
// Create once, initialize
private void CreateGUI()
{
// Generate color-blind friendly colors
VisionUtility.GetColorBlindSafePalette(batchColors, 0.51f, 1.0f);
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(ResourcePath + "LightBatchingDebugger.uxml");
var templateRoot = visualTree.Instantiate();
templateRoot.style.flexGrow = 1;
templateRoot.Q("ParentElement").StretchToParentSize();
root.Add(templateRoot);
var batchElement = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(ResourcePath + "LayerBatch.uxml");
Func<VisualElement> makeItem = () => batchElement.Instantiate();
Action<VisualElement, int> bindItem = (e, i) =>
{
if (i >= batchList.Count)
return;
// This is required to make the child of the ListView vary in heights
e.style.height = StyleKeyword.Auto;
var batch = batchList[i];
var batchIndex = e.Query<Label>("BatchIndex").First();
batchIndex.text = batch.batchId.ToString();
var layers = e.Query<VisualElement>("LayerNames").First();
layers.Clear();
foreach (var layerName in batchList[i].LayerNames)
{
var label = new Label { text = layerName };
label.AddToClassList("LayerNameLabel");
layers.Add(label);
}
var color = e.Query<VisualElement>("BatchColor").First();
color.style.backgroundColor = new StyleColor(batchColors[i % batchColors.Length]);
};
DisplayInitialPrompt(true);
batchListView = root.Query<ListView>("BatchList").First();
batchListView.itemsSource = batchList;
batchListView.makeItem = makeItem;
batchListView.bindItem = bindItem;
batchListView.virtualizationMethod = CollectionVirtualizationMethod.DynamicHeight;
batchListView.showAlternatingRowBackgrounds = AlternatingRowBackground.ContentOnly;
batchListView.selectionType = SelectionType.Multiple;
batchListView.selectionChanged += objects =>
{
OnSelectionChanged();
};
}
private void OnEnable()
{
EditorApplication.playModeStateChanged += OnPlayModeStateChanged;
#if UNITY_EDITOR
SortingLayer.onLayerChanged += QueueRefresh;
#endif
}
private void OnDisable()
{
EditorApplication.playModeStateChanged -= OnPlayModeStateChanged;
#if UNITY_EDITOR
SortingLayer.onLayerChanged -= QueueRefresh;
#endif
}
void OnPlayModeStateChanged(PlayModeStateChange playModeState)
{
if (PlayModeStateChange.EnteredEditMode == playModeState)
QueueRefresh();
}
void DisplayInitialPrompt(bool display)
{
var initialPrompt = root.Query<Label>("InitialPrompt").First();
initialPrompt.style.display = display ? DisplayStyle.Flex : DisplayStyle.None;
var infoView = root.Query<VisualElement>("InfoView").First();
infoView.style.display = display ? DisplayStyle.None : DisplayStyle.Flex;
}
private void OnSelectionChanged()
{
if (batchListView == null)
return;
GetFirstAndLast(batchListView.selectedIndices, out var selFirst, out var selLast, out var selCount);
switch (selCount)
{
case 1:
selectedIndices.Clear();
selectedIndices.Add(batchListView.selectedIndex);
ViewBatch(batchListView.selectedIndex);
break;
case 2:
selectedIndices.Clear();
var firstIndex = selFirst;
var secondIndex = selLast;
if (secondIndex > firstIndex + 1 || secondIndex < firstIndex - 1)
{
// Clamp since we do adjacent batch comparisons
secondIndex = Mathf.Clamp(secondIndex, firstIndex - 1, firstIndex + 1);
selectedIndices.Add(firstIndex);
selectedIndices.Add(secondIndex);
batchListView.SetSelection(selectedIndices);
}
else
{
CompareBatch(firstIndex, secondIndex);
selectedIndices.AddRange(batchListView.selectedIndices);
}
break;
default:
// Account for multiple select either with shift or ctrl keys
if (selCount > 2)
{
if (selectedIndices.Count == 1)
{
firstIndex = secondIndex = selectedIndices[0];
if (selFirst >= firstIndex)
secondIndex = firstIndex + 1;
else if (selFirst < firstIndex)
secondIndex = firstIndex - 1;
selectedIndices.Add(secondIndex);
batchListView.SetSelection(selectedIndices);
}
else if (selectedIndices.Count == 2)
{
batchListView.SetSelection(selectedIndices);
}
}
break;
}
// Update counts
Label lightHeader = root.Query<Label>("LightHeader");
lightHeader.text = $"Lights ({lightCount})";
Label shadowHeader = root.Query<Label>("ShadowHeader");
shadowHeader.text = $"Shadow Casters ({shadowCount})";
}
private void RefreshView()
{
PopulateData();
batchListView?.RefreshItems();
OnSelectionChanged();
ResetDirty();
}
private void Update()
{
if (IsDirty())
QueueRefresh();
if (doRefresh)
RefreshView();
}
private bool IsDirty()
{
if (lightCullResult == null)
return false;
bool isDirty = false;
// Refresh if layers are added or removed
int batchLayerNameCount = 0;
foreach (var batch in batchList)
batchLayerNameCount += batch.LayerNames.Count;
isDirty |= Light2DManager.GetCachedSortingLayer().Length != batchLayerNameCount;
isDirty |= cachedSceneHandle != SceneManager.GetActiveScene().handle;
isDirty |= cachedCamPos != Camera.main?.transform.position;
if (lightCullResult.IsGameView())
{
var visibleShadows = GetAllShadowCasters(lightCullResult.visibleShadows);
isDirty |= totalLightCount != lightCullResult.visibleLights.Count;
isDirty |= totalShadowCount != visibleShadows.Count;
// Account for name changes
if (!isDirty)
{
for (int i = 0; i < totalLightCount; ++i)
isDirty |= !lightCullResult.visibleLights.Exists(x => x != null && x.name == cachedLightNames[i]);
for (int i = 0; i < totalShadowCount; ++i)
isDirty |= !ExistsWithName(visibleShadows, cachedShadowCasterNames[i]);
}
}
return isDirty;
}
private void ResetDirty()
{
cachedSceneHandle = SceneManager.GetActiveScene().handle;
if (Camera.main != null)
cachedCamPos = Camera.main.transform.position;
if (lightCullResult != null)
{
var visibleShadows = GetAllShadowCasters(lightCullResult.visibleShadows);
totalLightCount = lightCullResult.visibleLights.Count;
totalShadowCount = visibleShadows.Count;
cachedLightNames = new string[totalLightCount];
cachedShadowCasterNames = new string[totalShadowCount];
for (int i = 0; i < totalLightCount; ++i)
{
var light = lightCullResult.visibleLights[i];
if (light != null)
cachedLightNames[i] = light.name;
}
for (int i = 0; i < totalShadowCount; ++i)
{
var shadowCaster = visibleShadows[i];
if (shadowCaster != null)
cachedShadowCasterNames[i] = shadowCaster.name;
}
}
doRefresh = false;
}
internal static void QueueRefresh()
{
doRefresh = true;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3f0281a9a104946b4b845f0338560878
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,138 @@
:root {
--border-color-custom: rgb(161, 154, 154);
}
.BatchList {
}
.BatchList.HeaderContainer {
flex-direction: row;
height: auto;
background-color: var(--unity-colors-inspector_titlebar-background);
}
.BatchList.IndexColumn {
margin-left: 5px;
width: 65px;
}
.BatchList.ColorColumn {
width: 3px;
}
.BatchList.NameColumn {
flex-grow: 2;
margin-left: 5px;
}
.BatchList.BatchContainer {
flex-direction: row;
}
.BatchList.ColorColumn.Container {
align-items: center;
}
.BatchList.ColorColumn.Splitter {
margin-top: 5px;
margin-bottom: 5px;
margin-right: 5px;
}
.BatchList.IndexColumn.Header {
margin-top: 5px;
margin-bottom: 5px;
}
.BatchList.NameColumn.Header {
margin-top: 5px;
margin-bottom: 5px;
}
.BatchList.IndexColumn.Batch {
margin-top: 5px;
}
.BatchList.NameColumn.Batch {
margin-top: 5px;
flex-direction: column;
}
.BatchList.List {
flex-grow: 1;
}
.LayerNameLabel {
margin-bottom: 5px;
}
.InfoView {
}
.InfoView.Content {
border-bottom-width: 10px;
white-space: normal;
}
.InfoView.Content.PillContainer {
flex-direction: row;
flex-wrap: wrap;
}
.InfoView.Content.Spacer {
flex-grow: 1;
}
.InfoView.Footer {
padding: 10px;
white-space: normal;
}
.InfoView.Header {
padding: 5px;
align-items: flex-start;
justify-content: space-around;
background-color: var(--unity-colors-window-background);
}
.InfoView.Header.Bottom {
border-bottom-color: var(--unity-colors-default-border);
}
.InfoView.Header.Top {
border-top-color: var(--unity-colors-default-border);
}
.InfoScroller {
flex-grow: 1;
padding: 10px;
}
.MinSize {
min-width: 160px;
min-height: 160px;
}
.InfoContainer{
min-width: 160px;
flex-grow: 1;
background-color: var(--unity-colors-default-background);
justify-content: center;
}
.InitialPrompt {
align-self: center;
}
.Pill {
border-color: var(--border-color-custom);
border-left-width: 1px;
border-right-width: 1px;
border-top-width: 1px;
border-bottom-width: 1px;
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: fd5cb3dd3de574f1585db92b6689f86a
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0}
disableValidation: 0
@@ -0,0 +1,57 @@
<UXML xmlns="UnityEngine.UIElements">
<VisualElement name="ParentElement" style="flex-direction:column">
<Style src="LightBatchingDebugger.uss" />
<Box class="InfoView Header Bottom">
<Label name="InfoTitle"/>
</Box>
<TwoPaneSplitView fixed-pane-initial-dimension="200">
<!--Left Split View Layer Batch Info-->
<VisualElement class="MinSize">
<Box class="BatchList HeaderContainer">
<Label class="BatchList IndexColumn Header" text="Batch ID"/>
<VisualElement class="BatchList ColorColumn Container">
<Label text="|" class="BatchList ColorColumn Splitter"/>
</VisualElement>
<Label class="BatchList NameColumn Header" text="Layer Names"/>
</Box>
<ListView name="BatchList" class="BatchList List"/>
</VisualElement>
<!--Right Split View Lights and Shadows-->
<VisualElement name="InfoContainer" class="InfoContainer">
<Label name="InitialPrompt" text="Open Game View and select a batch to begin." class="InitialPrompt"/>
<TwoPaneSplitView name="InfoView" fixed-pane-initial-dimension="500" orientation="Vertical">
<!--Light Split View Top-->
<VisualElement class="MinSize">
<Box class="BatchList HeaderContainer">
<Label name="LightHeader" class="BatchList IndexColumn Header"/>
</Box>
<ScrollView class="InfoScroller">
<Label name="LightLabel1" class="InfoView Content"/>
<VisualElement name="LightBubble1" class="InfoView Content PillContainer"/>
<Label name="LightLabel2" class="InfoView Content"/>
<VisualElement name="LightBubble2" class="InfoView Content PillContainer"/>
</ScrollView>
</VisualElement>
<!--Shadow Caster Split View Bottom-->
<VisualElement class="MinSize">
<Box class="BatchList HeaderContainer">
<Label name="ShadowHeader" class="BatchList IndexColumn Header"/>
</Box>
<ScrollView class="InfoScroller">
<Label name="ShadowLabel1" class="InfoView Content"/>
<VisualElement name="ShadowBubble1" class="InfoView Content PillContainer"/>
<Label name="ShadowLabel2" class="InfoView Content"/>
<VisualElement name="ShadowBubble2" class="InfoView Content PillContainer"/>
</ScrollView>
</VisualElement>
</TwoPaneSplitView>
</VisualElement>
</TwoPaneSplitView>
<Box class="InfoView Header Top">
<Label name="InfoTitle2"/>
</Box>
</VisualElement>
</UXML>
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 7f54b2764826949c192810bd3944abcc
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: c96a8adc325df8544ae548396468a961
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("DynamicProxyGenAssembly2")] // permit using internal interfaces with Moq
[assembly: InternalsVisibleTo("UniversalGraphicsTests")]
[assembly: InternalsVisibleTo("Unity.RenderPipelines.Universal.Editor.Tests")]
[assembly: InternalsVisibleTo("Unity.Testing.SRP.Universal-Upgrade.Editor")]
[assembly: InternalsVisibleTo("Unity.GraphicTests.Performance.Universal.Editor")]
[assembly: InternalsVisibleTo("Unity.VisualEffectGraph.EditorTests")]
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bcdc8c86abfb40a45aa7ea6f4d34cb13
@@ -0,0 +1,48 @@
using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[CustomEditor(typeof(MeshRenderer))]
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
[CanEditMultipleObjects]
internal class Renderer2DMeshEditor : MeshRendererEditor
{
SerializedProperty m_MaskInteraction;
SavedBool m_2DFoldout;
class Styles
{
public static readonly GUIContent maskInteractionLabel = EditorGUIUtility.TrTextContent("Mask Interaction", "Renderer's interaction with a Sprite Mask");
}
public override void OnEnable()
{
base.OnEnable();
m_MaskInteraction = serializedObject.FindProperty("m_MaskInteraction");
m_2DFoldout = new SavedBool($"{target.GetType()}.MeshEditor2DFoldout", true);
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
var rpAsset = UniversalRenderPipeline.asset;
if (rpAsset != null && (rpAsset.scriptableRenderer is Renderer2D))
{
m_2DFoldout.value = EditorGUILayout.Foldout(m_2DFoldout.value, "2D");
if (m_2DFoldout)
{
EditorGUI.indentLevel++;
m_MaskInteraction.intValue = Convert.ToInt32(EditorGUILayout.EnumPopup(Styles.maskInteractionLabel, (SpriteMaskInteraction)m_MaskInteraction.intValue));
EditorGUI.indentLevel--;
}
}
serializedObject.ApplyModifiedProperties();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: bce6289b8f1e3bf4a82078371dffaebd
@@ -0,0 +1,36 @@
using UnityEngine;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
/// <summary>
/// Custom editor for the ScriptableRendererFeature2D class, allowing for the configuration of renderer features in the Unity Editor.
/// </summary>
[CustomEditor(typeof(ScriptableRendererFeature2D), true)]
public class ScriptableRendererFeature2DEditor : Editor
{
private SerializedProperty m_InjectionPointProperty;
private SerializedProperty m_SortingLayerProperty;
private static readonly GUIContent k_InjectionPointGuiContent = new GUIContent("Injection Point", "Specifies where in the frame this pass will be injected.");
private void OnEnable()
{
m_InjectionPointProperty = serializedObject.FindProperty("injectionPoint2D");
m_SortingLayerProperty = serializedObject.FindProperty("sortingLayerID");
}
/// <summary>
/// Implementation for a ScriptableRendererFeature2D inspector.
/// </summary>
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
EditorGUILayout.PropertyField(m_InjectionPointProperty, k_InjectionPointGuiContent);
if (ScriptableRenderPass2D.IsSortingLayerEvent((RenderPassEvent2D)m_InjectionPointProperty.intValue))
SortingLayerEditorUtility.RenderSortingLayerFields(m_SortingLayerProperty);
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 0f8c4e2f372f94e4dbbdc7ce528a8ba4
@@ -0,0 +1,48 @@
using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[CustomEditor(typeof(SkinnedMeshRenderer))]
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
[CanEditMultipleObjects]
internal class SkinnedMeshEditor2DURP : SkinnedMeshRendererEditor
{
SerializedProperty m_MaskInteraction;
SavedBool m_2DFoldout;
new class Styles
{
public static readonly GUIContent maskInteractionLabel = EditorGUIUtility.TrTextContent("Mask Interaction", "Renderer's interaction with a Sprite Mask");
}
public override void OnEnable()
{
base.OnEnable();
m_MaskInteraction = serializedObject.FindProperty("m_MaskInteraction");
m_2DFoldout = new SavedBool($"{target.GetType()}.SkinnedMeshEditor2DFoldout", true);
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
var rpAsset = UniversalRenderPipeline.asset;
if (rpAsset != null && (rpAsset.scriptableRenderer is Renderer2D))
{
m_2DFoldout.value = EditorGUILayout.Foldout(m_2DFoldout.value, "2D");
if (m_2DFoldout)
{
EditorGUI.indentLevel++;
m_MaskInteraction.intValue = Convert.ToInt32(EditorGUILayout.EnumPopup(Styles.maskInteractionLabel, (SpriteMaskInteraction)m_MaskInteraction.intValue));
EditorGUI.indentLevel--;
}
}
serializedObject.ApplyModifiedProperties();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: d1e4d2637b6c6824e82557977a6727d4
@@ -0,0 +1,120 @@
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor
{
[CustomEditor(typeof(SortingGroup))]
[SupportedOnRenderPipeline(typeof(UniversalRenderPipelineAsset))]
[CanEditMultipleObjects]
internal class SortingGroupEditor2DURP : SortingGroupEditor
{
private enum SortType
{
Default,
SortAtRoot,
Sort3DAs2D
}
private static class GUIStyles
{
public static GUIContent Default = EditorGUIUtility.TrTextContent("Sorting Type",
"Default sorting based on sorting layer and sorting order.");
public static GUIContent sortAtRootStyle = EditorGUIUtility.TrTextContent("Sorting Type",
"Ignores all parent Sorting Groups and sorts at the root level against other Sorting Groups and Renderers");
public static GUIContent sort3DAs2D = EditorGUIUtility.TrTextContent("Sorting Type",
"Clears z values on 3D meshes affected by a Sorting Group allowing them to sort with other 2D objects and Sort 3D as 2D sorting groups. This option also enables Sort At Root");
}
private SerializedProperty m_Sort3DAs2D;
private SortType m_SortType;
public override void OnEnable()
{
base.OnEnable();
m_Sort3DAs2D = serializedObject.FindProperty("m_Sort3DAs2D");
// Initialize m_SortType
m_SortType = m_Sort3DAs2D.boolValue ? SortType.Sort3DAs2D : m_SortAtRoot.boolValue ? SortType.SortAtRoot : SortType.Default;
}
void OnInspectorGUIFor2D()
{
serializedObject.Update();
SortingLayerEditorUtility.RenderSortingLayerFields(m_SortingOrder, m_SortingLayerID);
var prevSortType = m_SortType;
var label = m_Sort3DAs2D.boolValue ? GUIStyles.sort3DAs2D : m_SortAtRoot.boolValue ? GUIStyles.sortAtRootStyle : GUIStyles.Default;
m_SortType = (SortType)EditorGUILayout.EnumPopup(label, m_SortType);
if (prevSortType != m_SortType)
{
switch (m_SortType)
{
case SortType.SortAtRoot:
m_SortAtRoot.boolValue = true;
m_Sort3DAs2D.boolValue = false;
break;
case SortType.Sort3DAs2D:
m_SortAtRoot.boolValue = true;
m_Sort3DAs2D.boolValue = true;
break;
default:
m_SortAtRoot.boolValue = false;
m_Sort3DAs2D.boolValue = false;
break;
}
}
foreach (var target in targets)
{
SortingGroup sortingGroup = (SortingGroup)target;
GameObject go = sortingGroup.gameObject;
go.TryGetComponent(out RenderAs2D renderAs2D);
if (sortingGroup.sort3DAs2D)
{
if (renderAs2D != null && !renderAs2D.IsOwner(sortingGroup))
{
DestroyImmediate(renderAs2D, true);
renderAs2D = null;
}
if (renderAs2D == null)
{
Material mat = AssetDatabase.LoadAssetAtPath<Material>("Packages/com.unity.render-pipelines.universal/Runtime/Materials/RenderAs2D-Flattening.mat");
renderAs2D = go.AddComponent<RenderAs2D>();
renderAs2D.Init(sortingGroup);
renderAs2D.material = mat;
EditorUtility.SetDirty(go);
}
}
else
{
if (renderAs2D != null)
{
DestroyImmediate(renderAs2D, true);
renderAs2D = null;
}
}
}
serializedObject.ApplyModifiedProperties();
}
public override void OnInspectorGUI()
{
var rpAsset = UniversalRenderPipeline.asset;
if (rpAsset != null && (rpAsset.scriptableRenderer is Renderer2D))
OnInspectorGUIFor2D();
else
base.OnInspectorGUI();
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 7dac6048e6e7a4747ad93c64661d3faf
@@ -0,0 +1,60 @@
{
"name": "Unity.RenderPipelines.Universal.2D.Editor.Overrides",
"rootNamespace": "",
"references": [
"GUID:15fc0a57446b3144c949da3e2b9737a9",
"GUID:d60799ab2a985554ea1a39cd38695018",
"GUID:a35efad8797223d499f8c68b1f545dbc",
"GUID:df380645f10b7bc4b97d4f5eb6303d95",
"GUID:69257879134bba646869b21467b3338d",
"GUID:3eae0364be2026648bf74846acb8a731",
"GUID:2a69708d171a17043a9d0ad45f205cfe",
"GUID:be0903cd8e1546f498710afdc59db5eb",
"GUID:b75d3cd3037d383a8d1e2f9a26d73d8a",
"GUID:329b4ccd385744985bf3f83cfd77dfe7",
"GUID:9604b18aafdbc9346bceb5e19ac9c746",
"GUID:f9fe0089ec81f4079af78eb2287a6163",
"GUID:116a4d4dbf5c04973bbf517077a062a1",
"GUID:e40ba710768534012815d3193fa296cb",
"GUID:516a5277b8c3b4f4c8cc86b77b1591ff",
"GUID:4fd6538c1c56b409fb53fdf0183170ec",
"GUID:41524c21c95e5fe4dbc5b48bd21995a4"
],
"includePlatforms": [
"Editor"
],
"excludePlatforms": [],
"allowUnsafeCode": true,
"overrideReferences": false,
"precompiledReferences": [],
"autoReferenced": true,
"defineConstraints": [],
"versionDefines": [
{
"name": "com.unity.adaptiveperformance",
"expression": "2.0.0-preview.7",
"define": "ADAPTIVE_PERFORMANCE_2_0_0_OR_NEWER"
},
{
"name": "com.unity.modules.xr",
"expression": "1.0.0",
"define": "ENABLE_XR_MODULE"
},
{
"name": "com.unity.xr.management",
"expression": "4.0.1",
"define": "XR_MANAGEMENT_4_0_1_OR_NEWER"
},
{
"name": "com.unity.visualeffectgraph",
"expression": "1.0.0",
"define": "HAS_VFX_GRAPH"
},
{
"name": "com.unity.2d.animation",
"expression": "10.0.0-pre.1",
"define": "USING_2DANIMATION"
}
],
"noEngineReferences": false
}
@@ -0,0 +1,7 @@
fileFormatVersion: 2
guid: 71872915d7faaaf47a5587bce19d5214
AssemblyDefinitionImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 2696e9ce38d846088f92fb56b6fbfcf0
timeCreated: 1774326539
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: c26811b239fc485f8e36fa38c71668c7
timeCreated: 1777947979
@@ -0,0 +1,183 @@
fileFormatVersion: 2
guid: f2b86942c8e1d49a4ae3172875621242
TextureImporter:
internalIDToNameTable:
- first:
213: -6875929908116327073
second: 2D_Graphics_0
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 2
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationMethod: 0
spriteTessellationDetail: -1
spriteGeometrySubdivision: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: iOS
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WindowsStoreApps
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites:
- serializedVersion: 2
name: 2D_Graphics_0
rect:
serializedVersion: 2
x: 1
y: 1
width: 14
height: 14
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
customData:
outline: []
physicsShape: []
tessellationDetail: -1
bones: []
spriteID: f55fd36cd2ac390a0800000000000000
internalID: -6875929908116327073
vertices: []
indices:
edges: []
weights: []
outline: []
customData:
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,183 @@
fileFormatVersion: 2
guid: bc2a0e72bee5648db8f50b37d5699a3d
TextureImporter:
internalIDToNameTable:
- first:
213: 6447283584259951572
second: 2D_Graphics@128_0
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 2
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationMethod: 0
spriteTessellationDetail: -1
spriteGeometrySubdivision: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: iOS
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WindowsStoreApps
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites:
- serializedVersion: 2
name: 2D_Graphics@128_0
rect:
serializedVersion: 2
x: 15
y: 15
width: 98
height: 98
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
customData:
outline: []
physicsShape: []
tessellationDetail: -1
bones: []
spriteID: 4db850eb24a597950800000000000000
internalID: 6447283584259951572
vertices: []
indices:
edges: []
weights: []
outline: []
customData:
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,183 @@
fileFormatVersion: 2
guid: 6f61da5d47daa49bdbc8aa90992e7d93
TextureImporter:
internalIDToNameTable:
- first:
213: -8733110783977970003
second: 2D_Graphics@256_0
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 2
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationMethod: 0
spriteTessellationDetail: -1
spriteGeometrySubdivision: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: iOS
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WindowsStoreApps
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites:
- serializedVersion: 2
name: 2D_Graphics@256_0
rect:
serializedVersion: 2
x: 31
y: 31
width: 194
height: 194
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
customData:
outline: []
physicsShape: []
tessellationDetail: -1
bones: []
spriteID: da62cd01302cdc680800000000000000
internalID: -8733110783977970003
vertices: []
indices:
edges: []
weights: []
outline: []
customData:
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,183 @@
fileFormatVersion: 2
guid: 5713bf64396f54c1a8f3bf0924c3454b
TextureImporter:
internalIDToNameTable:
- first:
213: 5722725350267622301
second: 2D_Graphics@32_0
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 2
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationMethod: 0
spriteTessellationDetail: -1
spriteGeometrySubdivision: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: iOS
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WindowsStoreApps
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites:
- serializedVersion: 2
name: 2D_Graphics@32_0
rect:
serializedVersion: 2
x: 3
y: 3
width: 26
height: 26
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
customData:
outline: []
physicsShape: []
tessellationDetail: -1
bones: []
spriteID: d9313d1c2643b6f40800000000000000
internalID: 5722725350267622301
vertices: []
indices:
edges: []
weights: []
outline: []
customData:
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,183 @@
fileFormatVersion: 2
guid: 8ce91386d93f64952b1f8b60832509c2
TextureImporter:
internalIDToNameTable:
- first:
213: -6988430907250545872
second: 2D_Graphics@64_0
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 2
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationMethod: 0
spriteTessellationDetail: -1
spriteGeometrySubdivision: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: iOS
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WindowsStoreApps
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites:
- serializedVersion: 2
name: 2D_Graphics@64_0
rect:
serializedVersion: 2
x: 7
y: 7
width: 50
height: 50
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
customData:
outline: []
physicsShape: []
tessellationDetail: -1
bones: []
spriteID: 03b68fbbd1b140f90800000000000000
internalID: -6988430907250545872
vertices: []
indices:
edges: []
weights: []
outline: []
customData:
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,183 @@
fileFormatVersion: 2
guid: d520d0c73c7a8405fbac8ce2dbe63541
TextureImporter:
internalIDToNameTable:
- first:
213: 5655479116110854875
second: d_2D_Graphics_0
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 2
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationMethod: 0
spriteTessellationDetail: -1
spriteGeometrySubdivision: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: iOS
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WindowsStoreApps
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites:
- serializedVersion: 2
name: d_2D_Graphics_0
rect:
serializedVersion: 2
x: 1
y: 1
width: 14
height: 14
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
customData:
outline: []
physicsShape: []
tessellationDetail: -1
bones: []
spriteID: bda7d66ca4c4c7e40800000000000000
internalID: 5655479116110854875
vertices: []
indices:
edges: []
weights: []
outline: []
customData:
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,183 @@
fileFormatVersion: 2
guid: 61631c3cacd694ef292c329dcb729bef
TextureImporter:
internalIDToNameTable:
- first:
213: 787027614673791679
second: d_2D_Graphics@128_0
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 2
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationMethod: 0
spriteTessellationDetail: -1
spriteGeometrySubdivision: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: iOS
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WindowsStoreApps
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites:
- serializedVersion: 2
name: d_2D_Graphics@128_0
rect:
serializedVersion: 2
x: 15
y: 15
width: 98
height: 98
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
customData:
outline: []
physicsShape: []
tessellationDetail: -1
bones: []
spriteID: fbaed0912751cea00800000000000000
internalID: 787027614673791679
vertices: []
indices:
edges: []
weights: []
outline: []
customData:
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,183 @@
fileFormatVersion: 2
guid: 7d24a5e6aa1594d2cb490a25938487a5
TextureImporter:
internalIDToNameTable:
- first:
213: -7703439571405427093
second: d_2D_Graphics@256_0
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 2
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationMethod: 0
spriteTessellationDetail: -1
spriteGeometrySubdivision: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: iOS
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WindowsStoreApps
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites:
- serializedVersion: 2
name: d_2D_Graphics@256_0
rect:
serializedVersion: 2
x: 31
y: 31
width: 194
height: 194
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
customData:
outline: []
physicsShape: []
tessellationDetail: -1
bones: []
spriteID: b6e21bd3682e71590800000000000000
internalID: -7703439571405427093
vertices: []
indices:
edges: []
weights: []
outline: []
customData:
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,183 @@
fileFormatVersion: 2
guid: 5c293b913d2404a959cc5a69e0b04c95
TextureImporter:
internalIDToNameTable:
- first:
213: 8555540013891001003
second: d_2D_Graphics@32_0
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 2
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationMethod: 0
spriteTessellationDetail: -1
spriteGeometrySubdivision: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: iOS
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WindowsStoreApps
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites:
- serializedVersion: 2
name: d_2D_Graphics@32_0
rect:
serializedVersion: 2
x: 3
y: 3
width: 26
height: 26
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
customData:
outline: []
physicsShape: []
tessellationDetail: -1
bones: []
spriteID: baa1d9d30526bb670800000000000000
internalID: 8555540013891001003
vertices: []
indices:
edges: []
weights: []
outline: []
customData:
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,183 @@
fileFormatVersion: 2
guid: c7148842f397b440b8244314e625264e
TextureImporter:
internalIDToNameTable:
- first:
213: 8318555261245402638
second: d_2D_Graphics@64_0
externalObjects: {}
serializedVersion: 13
mipmaps:
mipMapMode: 0
enableMipMap: 0
sRGBTexture: 1
linearTexture: 0
fadeOut: 0
borderMipMap: 0
mipMapsPreserveCoverage: 0
alphaTestReferenceValue: 0.5
mipMapFadeDistanceStart: 1
mipMapFadeDistanceEnd: 3
bumpmap:
convertToNormalMap: 0
externalNormalMap: 0
heightScale: 0.25
normalMapFilter: 0
flipGreenChannel: 0
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
vTOnly: 0
ignoreMipmapLimit: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: 1
aniso: 2
mipBias: 0
wrapU: 1
wrapV: 1
wrapW: 0
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 1
alignment: 0
spritePivot: {x: 0.5, y: 0.5}
spritePixelsToUnits: 100
spriteBorder: {x: 0, y: 0, z: 0, w: 0}
spriteGenerateFallbackPhysicsShape: 1
alphaUsage: 1
alphaIsTransparency: 1
spriteTessellationMethod: 0
spriteTessellationDetail: -1
spriteGeometrySubdivision: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
flipbookRows: 1
flipbookColumns: 1
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
ignorePngGamma: 0
applyGammaDecoding: 0
swizzle: 50462976
cookieLightType: 0
platformSettings:
- serializedVersion: 4
buildTarget: DefaultTexturePlatform
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Standalone
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: iOS
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: Android
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
- serializedVersion: 4
buildTarget: WindowsStoreApps
maxTextureSize: 8192
resizeAlgorithm: 0
textureFormat: -1
textureCompression: 1
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
ignorePlatformSupport: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 0
spriteSheet:
serializedVersion: 2
sprites:
- serializedVersion: 2
name: d_2D_Graphics@64_0
rect:
serializedVersion: 2
x: 7
y: 7
width: 50
height: 50
alignment: 0
pivot: {x: 0, y: 0}
border: {x: 0, y: 0, z: 0, w: 0}
customData:
outline: []
physicsShape: []
tessellationDetail: -1
bones: []
spriteID: e0e2dfebfe1717370800000000000000
internalID: 8318555261245402638
vertices: []
indices:
edges: []
weights: []
outline: []
customData:
physicsShape: []
bones: []
spriteID: 5e97eb03825dee720800000000000000
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spriteCustomMetadata:
entries: []
nameFileIdTable: {}
mipmapLimitGroupName:
pSDRemoveMatte: 0
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,295 @@
using System;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.Rendering.Universal;
namespace UnityEditor.Rendering.Universal
{
[CustomEditor(typeof(PixelPerfectCamera))]
class PixelPerfectCameraEditor : Editor
{
private class Style
{
public GUIContent x = new GUIContent("X");
public GUIContent y = new GUIContent("Y");
public GUIContent assetsPPU = new GUIContent("Assets Pixels Per Unit", "The amount of pixels that make up one unit of the Scene. Set this value to match the PPU value of Sprites in the Scene.");
public GUIContent refRes = new GUIContent("Reference Resolution", "The original resolution the Assets are designed for.");
public GUIContent gridSnapping = new GUIContent("Grid Snapping", "Sets the snapping behavior for the camera and sprites.");
public GUIContent cropFrame = new GUIContent("Crop Frame", "Crops the viewport to match the Reference Resolution, along the checked axis. Black bars will be added to fit the screen aspect ratio.");
public GUIContent filterMode = new GUIContent("Filter Mode", "Use selected Filter Mode when using Stretch Fill to upscale from Reference Resolution.");
public GUIContent stretchFill = new GUIContent("Stretch Fill", "If enabled, expands the viewport to fit the screen resolution while maintaining the viewport aspect ratio.");
public GUIContent currentPixelRatio = new GUIContent("Current Pixel Ratio", "Ratio of the rendered Sprites compared to their original size.");
public GUIContent runInEditMode = new GUIContent("Run In Edit Mode", "Enable this to preview Camera setting changes in Edit Mode. This will cause constant changes to the Scene while active.");
public const string cameraStackingWarning = "Pixel Perfect Camera won't function properly if stacked with another camera.";
public const string nonRenderer2DWarning = "URP Pixel Perfect Camera requires a camera using a 2D Renderer. Some features, such as Upscale Render Texture, are not supported with other Renderers.";
public const string nonRenderer2DError = "URP Pixel Perfect Camera requires a camera using a 2D Renderer.";
public const string renderScaleWarning = "Render Scale in Quality Settings is {0:F2}. Crop Frame and Upscale Render Texture are not supported when Render Scale is not 1.0.The Render Scale setting will be ignored.";
public GUIStyle centeredLabel;
public Style()
{
centeredLabel = new GUIStyle(EditorStyles.label);
centeredLabel.alignment = TextAnchor.MiddleCenter;
}
}
private static Style m_Style;
private const float k_SingleLetterLabelWidth = 15.0f;
private const float k_DottedLineSpacing = 2.5f;
private SerializedProperty m_AssetsPPU;
private SerializedProperty m_RefResX;
private SerializedProperty m_RefResY;
private SerializedProperty m_CropFrame;
private SerializedProperty m_FilterMode;
private SerializedProperty m_GridSnapping;
private Vector2 m_GameViewSize = Vector2.zero;
private GUIContent m_CurrentPixelRatioValue;
bool m_CameraStacking;
private void LazyInit()
{
if (m_Style == null)
m_Style = new Style();
if (m_CurrentPixelRatioValue == null)
m_CurrentPixelRatioValue = new GUIContent();
}
UniversalAdditionalCameraData GetCameraData()
{
PixelPerfectCamera obj = target as PixelPerfectCamera;
UniversalAdditionalCameraData cameraData = null;
obj?.TryGetComponent(out cameraData);
return cameraData;
}
bool UsingSRP()
{
var cameraData = GetCameraData();
return cameraData?.scriptableRenderer != null;
}
bool UsingRenderer2D()
{
var cameraData = GetCameraData();
if (cameraData != null)
{
Renderer2D renderer2D = cameraData.scriptableRenderer as Renderer2D;
if (renderer2D != null)
return true;
}
return false;
}
void CheckForCameraStacking()
{
m_CameraStacking = false;
var cameraData = GetCameraData();
if (cameraData == null || cameraData.scriptableRenderer == null)
return;
if (cameraData.renderType == CameraRenderType.Base)
{
var cameraStack = cameraData.cameraStack;
m_CameraStacking = cameraStack != null ? cameraStack.Count > 0 : false;
}
else if (cameraData.renderType == CameraRenderType.Overlay)
m_CameraStacking = true;
}
public void OnEnable()
{
m_AssetsPPU = serializedObject.FindProperty("m_AssetsPPU");
m_RefResX = serializedObject.FindProperty("m_RefResolutionX");
m_RefResY = serializedObject.FindProperty("m_RefResolutionY");
m_CropFrame = serializedObject.FindProperty("m_CropFrame");
m_FilterMode = serializedObject.FindProperty("m_FilterMode");
m_GridSnapping = serializedObject.FindProperty("m_GridSnapping");
}
public override bool RequiresConstantRepaint()
{
PixelPerfectCamera obj = target as PixelPerfectCamera;
if (obj == null || !obj.enabled)
return false;
// If game view size changes, we need to force a repaint of the inspector as the pixel ratio value may change accordingly.
Vector2 gameViewSize = Handles.GetMainGameViewSize();
if (gameViewSize != m_GameViewSize)
{
m_GameViewSize = gameViewSize;
return true;
}
else
return false;
}
public override void OnInspectorGUI()
{
LazyInit();
if (!UsingSRP())
{
EditorGUILayout.HelpBox(Style.nonRenderer2DError, MessageType.Error);
return;
}
else if (!UsingRenderer2D())
{
EditorGUILayout.HelpBox(Style.nonRenderer2DWarning, MessageType.Warning);
EditorGUILayout.Space();
}
float originalLabelWidth = EditorGUIUtility.labelWidth;
serializedObject.Update();
if (Event.current.type == EventType.Layout)
CheckForCameraStacking();
if (m_CameraStacking)
EditorGUILayout.HelpBox(Style.cameraStackingWarning, MessageType.Warning);
EditorGUILayout.PropertyField(m_AssetsPPU, m_Style.assetsPPU);
if (m_AssetsPPU.intValue <= 0)
m_AssetsPPU.intValue = 1;
EditorGUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel(m_Style.refRes);
EditorGUIUtility.labelWidth = k_SingleLetterLabelWidth * (EditorGUI.indentLevel + 1);
EditorGUILayout.PropertyField(m_RefResX, m_Style.x);
if (m_RefResX.intValue <= 0)
m_RefResX.intValue = 1;
EditorGUILayout.PropertyField(m_RefResY, m_Style.y);
if (m_RefResY.intValue <= 0)
m_RefResY.intValue = 1;
EditorGUIUtility.labelWidth = originalLabelWidth;
}
EditorGUILayout.EndHorizontal();
EditorGUILayout.PropertyField(m_CropFrame, m_Style.cropFrame);
EditorGUILayout.PropertyField(m_GridSnapping, m_Style.gridSnapping);
if (m_CropFrame.enumValueIndex == (int)PixelPerfectCamera.CropFrame.StretchFill)
{
EditorGUILayout.PropertyField(m_FilterMode, m_Style.filterMode);
}
serializedObject.ApplyModifiedProperties();
PixelPerfectCamera obj = target as PixelPerfectCamera;
if (obj != null)
{
if (obj.isActiveAndEnabled && (EditorApplication.isPlaying || obj.runInEditMode))
{
if (Event.current.type == EventType.Layout)
m_CurrentPixelRatioValue.text = string.Format("{0}:1", obj.pixelRatio);
EditorGUI.BeginDisabledGroup(true);
EditorGUILayout.LabelField(m_Style.currentPixelRatio, m_CurrentPixelRatioValue);
EditorGUI.EndDisabledGroup();
}
}
// Warning for render scale quality setting
var asset = GraphicsSettings.currentRenderPipeline as UniversalRenderPipelineAsset;
if (asset != null && !Mathf.Approximately(asset.renderScale, 1.0f))
{
bool usingCropFrame = m_CropFrame.enumValueIndex != (int)PixelPerfectCamera.CropFrame.None;
bool usingUpscaleRT = m_GridSnapping.enumValueIndex == (int)PixelPerfectCamera.GridSnapping.UpscaleRenderTexture;
if (usingCropFrame || usingUpscaleRT)
{
EditorGUILayout.HelpBox(string.Format(
Style.renderScaleWarning,
asset.renderScale),
MessageType.Warning);
}
}
}
void OnSceneGUI()
{
PixelPerfectCamera obj = target as PixelPerfectCamera;
if (obj == null)
return;
Camera camera = obj.GetComponent<Camera>();
// Show a green rect in scene view that represents the visible area when the pixel perfect correction takes effect in play mode.
Vector2 gameViewSize = Handles.GetMainGameViewSize();
int gameViewWidth = (int)gameViewSize.x;
int gameViewHeight = (int)gameViewSize.y;
int zoom = Math.Max(1, Math.Min(gameViewHeight / obj.refResolutionY, gameViewWidth / obj.refResolutionX));
float verticalOrthoSize;
float horizontalOrthoSize;
if (obj.cropFrame == PixelPerfectCamera.CropFrame.StretchFill || obj.cropFrame == PixelPerfectCamera.CropFrame.Windowbox)
{
verticalOrthoSize = obj.refResolutionY * 0.5f / obj.assetsPPU;
horizontalOrthoSize = verticalOrthoSize * ((float)obj.refResolutionX / obj.refResolutionY);
}
else if (obj.cropFrame == PixelPerfectCamera.CropFrame.Letterbox)
{
verticalOrthoSize = obj.refResolutionY * 0.5f / obj.assetsPPU;
horizontalOrthoSize = verticalOrthoSize * ((float)gameViewWidth / (zoom * obj.refResolutionY));
}
else if (obj.cropFrame == PixelPerfectCamera.CropFrame.Pillarbox)
{
horizontalOrthoSize = obj.refResolutionX * 0.5f / obj.assetsPPU;
verticalOrthoSize = horizontalOrthoSize / (zoom * obj.refResolutionX / (float)gameViewHeight);
}
else
{
verticalOrthoSize = gameViewHeight * 0.5f / (zoom * obj.assetsPPU);
horizontalOrthoSize = verticalOrthoSize * camera.aspect;
}
Handles.color = Color.green;
Vector3 cameraPosition = camera.transform.position;
Vector3 p1 = cameraPosition + new Vector3(-horizontalOrthoSize, verticalOrthoSize, 0.0f);
Vector3 p2 = cameraPosition + new Vector3(horizontalOrthoSize, verticalOrthoSize, 0.0f);
Handles.DrawLine(p1, p2);
p1 = cameraPosition + new Vector3(horizontalOrthoSize, -verticalOrthoSize, 0.0f);
Handles.DrawLine(p2, p1);
p2 = cameraPosition + new Vector3(-horizontalOrthoSize, -verticalOrthoSize, 0.0f);
Handles.DrawLine(p1, p2);
p1 = cameraPosition + new Vector3(-horizontalOrthoSize, verticalOrthoSize, 0.0f);
Handles.DrawLine(p2, p1);
// Show a green dotted rect in scene view that represents the area defined by the reference resolution.
horizontalOrthoSize = obj.refResolutionX * 0.5f / obj.assetsPPU;
verticalOrthoSize = obj.refResolutionY * 0.5f / obj.assetsPPU;
p1 = cameraPosition + new Vector3(-horizontalOrthoSize, verticalOrthoSize, 0.0f);
p2 = cameraPosition + new Vector3(horizontalOrthoSize, verticalOrthoSize, 0.0f);
Handles.DrawDottedLine(p1, p2, k_DottedLineSpacing);
p1 = cameraPosition + new Vector3(horizontalOrthoSize, -verticalOrthoSize, 0.0f);
Handles.DrawDottedLine(p2, p1, k_DottedLineSpacing);
p2 = cameraPosition + new Vector3(-horizontalOrthoSize, -verticalOrthoSize, 0.0f);
Handles.DrawDottedLine(p1, p2, k_DottedLineSpacing);
p1 = cameraPosition + new Vector3(-horizontalOrthoSize, verticalOrthoSize, 0.0f);
Handles.DrawDottedLine(p2, p1, k_DottedLineSpacing);
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 210f441e9bc1d0c4888c4369d2c0859f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 60a2f2c2c1614ff788914122ee32a349
timeCreated: 1773115966
@@ -0,0 +1,33 @@
using System;
using Unity.Profiling;
using Unity.Profiling.Editor;
using UnityEngine;
using UnityEngine.Rendering.Universal.U2D.Profiler;
namespace UnityEditor.U2D.Graphics.Profiler
{
[Serializable]
[ProfilerModuleMetadata("2D Graphics", IconPath = "Packages/com.unity.render-pipelines.universal/Editor/2D/PackageResources/ProfilerIcon/2D_Graphics.png")]
class U2DGraphicProfilerModule : ProfilerModule
{
static readonly ProfilerCounterDescriptor[] k_Counters = new ProfilerCounterDescriptor[]
{
new ProfilerCounterDescriptor(ProfilerMarkers.k_U2DNormalMapProfilerCounterName, ProfilerCategory.U2D),
new ProfilerCounterDescriptor(ProfilerMarkers.k_U2DLightProfilerCounterName, ProfilerCategory.U2D),
new ProfilerCounterDescriptor(ProfilerMarkers.k_U2DShadowProfilerCounterName, ProfilerCategory.U2D),
new ProfilerCounterDescriptor(ProfilerMarkers.k_U2DShadowCasterCounterName, ProfilerCategory.U2D),
new ProfilerCounterDescriptor(ProfilerMarkers.k_U2DShadowVerticesCounterName, ProfilerCategory.U2D),
new ProfilerCounterDescriptor(ProfilerMarkers.k_U2DLightBatchCounterName, ProfilerCategory.U2D),
new ProfilerCounterDescriptor(ProfilerMarkers.k_U2DLightTriangleCounterName, ProfilerCategory.U2D),
};
public U2DGraphicProfilerModule()
: base(k_Counters, ProfilerModuleChartType.Line)
{ }
public override ProfilerModuleViewController CreateDetailsViewController()
{
return new U2DGraphicsProfilerViewController(ProfilerWindow);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 7489d81eef5c4885813460e5c4366eaa
timeCreated: 1773039037
@@ -0,0 +1,243 @@
using System;
using System.Collections.Generic;
using Unity.Profiling.Editor;
using UnityEditor.U2D.Graphics.Profiler.UI;
using UnityEngine;
using UnityEngine.Rendering.Universal.U2D.Profiler;
using UnityEngine.UIElements;
namespace UnityEditor.U2D.Graphics.Profiler
{
class U2DGraphicsProfilerViewController : ProfilerModuleViewController
{
private U2DGraphicsProfilerView m_Root;
public U2DGraphicsProfilerViewController(ProfilerWindow profilerWindow)
: base(profilerWindow)
{
profilerWindow.SelectedFrameIndexChanged += OnProfilerFrameChange;
}
void OnProfilerFrameChange(long obj)
{
#if ENABLE_PROFILER && PROFILER_INSTALLED
if(Event.current != null && Event.current.type == EventType.Layout)
return;
if (obj < 0)
{
m_Root.SetHierarchyData(new[] { new List<U2DGraphicsHierarchyNodeData>(), new List<U2DGraphicsHierarchyNodeData>() });
m_Root.SetStatistic(0,0,0,0,0,0,0,0,0,0,0);
return;
}
CreateRootIfNotExist();
if (UnityEngine.Profiling.Profiler.enabled && !m_Root.IsLiveUpdateEnabled())
return;
var selectedFrameIndexInt32 = Convert.ToInt32(obj);
try
{
using (var frameData =
UnityEditorInternal.ProfilerDriver.GetRawFrameDataView(selectedFrameIndexInt32, 0))
{
// Extract shadow and light hierarchy data
List<U2DGraphicsHierarchyNodeData> shadowNodeList = new List<U2DGraphicsHierarchyNodeData>();
List<U2DGraphicsHierarchyNodeData> lightNodeList = new List<U2DGraphicsHierarchyNodeData>();
// Extract shadow data (tag 0)
var shadowData = frameData.GetFrameMetaData<MeshFrameData>(
ProfilerMarkers.k_2DGraphicProfilerProjectId,
(int)ProfilerMarkers.ProfilerFrameDataTag.ShadowFrameData);
Dictionary<EntityId, U2DGraphicsHierarchyNodeData> nodeDataDict =
new Dictionary<EntityId, U2DGraphicsHierarchyNodeData>();
if (shadowData.IsCreated)
{
for (int i = 0; i < shadowData.Length; i++)
{
var shadowCaster = shadowData[i];
if (shadowCaster.gameObjectEntityId != EntityId.None)
{
if (frameData.GetUnityObjectInfo(shadowCaster.gameObjectEntityId,
out var unityObjectInfo))
{
var node = new U2DGraphicsHierarchyNodeData(
unityObjectInfo.name,
shadowCaster.gameObjectEntityId,
shadowCaster.triangleCount,
shadowCaster.vertexCount,
i,
"") { drawCount = 0 };
shadowNodeList.Add(node);
nodeDataDict.Add(node.entityId, node);
}
}
}
shadowData.Dispose();
}
var shadowRenderCount = frameData.GetFrameMetaData<EntityId>(
ProfilerMarkers.k_2DGraphicProfilerProjectId,
(int)ProfilerMarkers.ProfilerFrameDataTag.ShadowRenderFrameData);
if (shadowRenderCount.IsCreated)
{
for (int i = 0; i < shadowRenderCount.Length; i++)
{
var entityId = shadowRenderCount[i];
if (entityId != EntityId.None)
{
if (nodeDataDict.TryGetValue(entityId, out var node))
{
node.drawCount++;
}
}
}
shadowRenderCount.Dispose();
}
// Extract light data (tag 1)
var lightData = frameData.GetFrameMetaData<MeshFrameData>(
ProfilerMarkers.k_2DGraphicProfilerProjectId,
(int)ProfilerMarkers.ProfilerFrameDataTag.LightFrameData);
nodeDataDict.Clear();
if (lightData.IsCreated)
{
for (int i = 0; i < lightData.Length; i++)
{
var lightMesh = lightData[i];
if (lightMesh.gameObjectEntityId != EntityId.None)
{
if (frameData.GetUnityObjectInfo(lightMesh.gameObjectEntityId, out var unityObjectInfo))
{
var node = new U2DGraphicsHierarchyNodeData(
unityObjectInfo.name,
lightMesh.gameObjectEntityId,
lightMesh.triangleCount,
lightMesh.vertexCount,
i,
"") { drawCount = 0 };
lightNodeList.Add(node);
nodeDataDict.Add(node.entityId, node);
}
}
}
lightData.Dispose();
}
var lightRenderCount = frameData.GetFrameMetaData<EntityId>(
ProfilerMarkers.k_2DGraphicProfilerProjectId,
(int)ProfilerMarkers.ProfilerFrameDataTag.LightRenderFrameData);
if (lightRenderCount.IsCreated)
{
for (int i = 0; i < lightRenderCount.Length; i++)
{
var entityId = lightRenderCount[i];
if (entityId != EntityId.None)
{
if (nodeDataDict.TryGetValue(entityId, out var node))
{
node.drawCount++;
}
}
}
lightRenderCount.Dispose();
}
// Pass categorized data as array: [0] = shadow, [1] = light
m_Root.SetHierarchyData(new[] { shadowNodeList, lightNodeList });
// Extract counter values
var markerId = frameData.GetMarkerId(ProfilerMarkers.k_U2DNormalMapProfilerCounterName);
var normalTextures = frameData.GetCounterValueAsLong(markerId);
markerId = frameData.GetMarkerId(ProfilerMarkers.k_U2DLightProfilerCounterName);
var lightTextures = frameData.GetCounterValueAsLong(markerId);
markerId = frameData.GetMarkerId(ProfilerMarkers.k_U2DLightBatchCounterName);
var lightBatches = frameData.GetCounterValueAsLong(markerId);
markerId = frameData.GetMarkerId(ProfilerMarkers.k_U2DLightTriangleCounterName);
var lightTriangles = frameData.GetCounterValueAsLong(markerId);
markerId = frameData.GetMarkerId(ProfilerMarkers.k_U2DShadowProfilerCounterName);
var shadowTextures = frameData.GetCounterValueAsLong(markerId);
markerId = frameData.GetMarkerId(ProfilerMarkers.k_U2DShadowCasterCounterName);
var shadowCasters = frameData.GetCounterValueAsLong(markerId);
markerId = frameData.GetMarkerId(ProfilerMarkers.k_U2DShadowVerticesCounterName);
var shadowTriangles = frameData.GetCounterValueAsLong(markerId);
var renderPassMarkerID = frameData.GetMarkerId(ProfilerMarkers.s_RenderPass);
float renderPassTime = 0;
var drawShadowMarkerID = frameData.GetMarkerId(ProfilerMarkers.s_ShadowTexture);
float drawShadowTime = 0;
var normalPassMarkerID = frameData.GetMarkerId(ProfilerMarkers.s_MormalPass);
float normalPassTime = 0;
var shadowPasaMarkerID = frameData.GetMarkerId(ProfilerMarkers.s_ShadowPass);
float shadowPasaTime = 0;
int sampleCount = frameData.sampleCount;
for (int i = 0; i < sampleCount; ++i)
{
var sampleMarkerID = frameData.GetSampleMarkerId(i);
if (sampleMarkerID == renderPassMarkerID)
{
renderPassTime += frameData.GetSampleTimeMs(i);
}
else if (sampleMarkerID == drawShadowMarkerID)
{
drawShadowTime += frameData.GetSampleTimeMs(i);
}
else if (sampleMarkerID == normalPassMarkerID)
{
normalPassTime += frameData.GetSampleTimeMs(i);
}
else if (sampleMarkerID == shadowPasaMarkerID)
{
shadowPasaTime += frameData.GetSampleTimeMs(i);
}
}
m_Root.SetStatistic(normalTextures, lightTextures, lightBatches, lightTriangles,
shadowTextures, shadowCasters, shadowTriangles,
renderPassTime, drawShadowTime, normalPassTime, shadowPasaTime);
}
}
catch (Exception)
{
//do nothing if any error happens during data extraction.
}
#endif
}
U2DGraphicsProfilerView CreateRootIfNotExist()
{
if (m_Root == null)
{
m_Root = new U2DGraphicsProfilerView();
}
return m_Root;
}
protected override VisualElement CreateView()
{
CreateRootIfNotExist();
OnProfilerFrameChange(ProfilerWindow.selectedFrameIndex);
return m_Root;
}
protected override void Dispose(bool disposing)
{
if (disposing && m_Root != null)
{
m_Root = null;
}
base.Dispose(disposing);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 1fd63aee254a460f809a4237b8f46479
timeCreated: 1773044863
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: dc8c2562810a74f609591ad0c3ed14f7
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 3e99584e02d054613894dca9f9e68062
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,66 @@
using System;
using UnityEngine;
namespace UnityEditor.U2D.Graphics.Profiler.UI
{
record U2DGraphicsHierarchyNodeData
{
public readonly string name;
public readonly EntityId entityId;
public int triangleCount;
public int vertexCount;
public readonly int id;
public string icon;
[SerializeField]
string m_DrawCountLabel = "";
int m_DrawCount = 0;
public U2DGraphicsHierarchyNodeData(string name, EntityId entityId, int triangleCount, int vertexCount, int id, string icon)
{
this.name = name;
this.entityId = entityId;
this.triangleCount = triangleCount;
this.vertexCount = vertexCount;
this.id = id;
this.icon = icon;
}
public int drawCount
{
get => m_DrawCount;
set
{
m_DrawCount = value;
m_DrawCountLabel = value.ToString();
}
}
public virtual bool Equals(U2DGraphicsHierarchyNodeData other)
{
if (other is null) return false;
if (ReferenceEquals(this, other)) return true;
return entityId == other.entityId;
}
public override int GetHashCode()
{
return entityId.GetHashCode();
}
public static int Compare(U2DGraphicsHierarchyNodeData a, U2DGraphicsHierarchyNodeData b, string propertyToCompare)
{
switch (propertyToCompare)
{
case "name":
case null:
return string.Compare(a.name, b.name, StringComparison.OrdinalIgnoreCase);
case "triangleCount":
return a.triangleCount.CompareTo(b.triangleCount);
case "vertexCount":
return a.vertexCount.CompareTo(b.vertexCount);
default:
return 0;
}
}
}
}
@@ -0,0 +1,261 @@
using System;
using System.Collections.Generic;
using Unity.Properties;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.U2D.Graphics.Profiler.UI
{
[UxmlElement]
[Serializable]
partial class U2DGraphicsHierarchyView : VisualElement
{
const string k_UXML = "Packages/com.unity.render-pipelines.universal/Editor/2D/Profiler/UI/U2DGraphicsHierarchyView/U2DGraphicsHierarchyView.uxml";
MultiColumnTreeView m_Table;
List<TreeViewItemData<U2DGraphicsHierarchyNodeData>> m_Data = new();
Label m_NoDataLabel;
public U2DGraphicsHierarchyView()
{
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(k_UXML);
visualTree.CloneTree(this);
m_Table = this.Q<MultiColumnTreeView>();
m_Table.selectedIndicesChanged += OnSelectionChanged;
m_NoDataLabel = this.Q<Label>("noDataLabel");
SetupTable();
ShowTable();
}
void OnSelectionChanged(IEnumerable<int> obj)
{
var cellData = m_Table.GetItemDataForIndex<U2DGraphicsHierarchyNodeData>(m_Table.selectedIndex);
if (cellData != null)
{
var unityObject = EditorUtility.EntityIdToObject(cellData.entityId);
if (unityObject != null)
Selection.activeObject = unityObject;
}
}
void SetupTable()
{
if(EditorGUIUtility.isProSkin)
m_Table.AddToClassList("dark");
else
m_Table.AddToClassList("light");
m_Table.sortingMode = ColumnSortingMode.Custom;
m_Table.columnSortingChanged += OnColumnSortingChanged;
for(int i = 0; i < m_Table.columns.Count; ++i)
{
var column = m_Table.columns[i];
if (column.name == "Name")
{
column.bindCell = (element, i) =>
{
var label = element.Q<Label>();
var itemData = m_Table.GetItemDataForIndex<U2DGraphicsHierarchyNodeData>(i);
BindLabelToDataSource(label, column.bindingPath, itemData);
SetNameColumnCellIcon(element, itemData);
};
}
else
{
column.bindCell = (element, i) =>
{
var itemData = m_Table.GetItemDataForIndex<U2DGraphicsHierarchyNodeData>(i);
var label = element.Q<Label>();
BindLabelToDataSource(label, column.bindingPath, itemData);
};
}
column.unbindCell = (element, _) =>
{
var label = element.Q<Label>();
label.SetBinding("text", null);
};
column.makeCell = () =>
{
var ve = new VisualElement();
ve.AddToClassList("cell");
var icon = new VisualElement(){name = "Icon"};
icon.AddToClassList("cell-icon");
var label = new Label();
label.AddToClassList("cell-label");
ve.Add(icon);
ve.Add(label);
return ve;
};
column.comparison = (a,b) =>
{
return 0;
};
}
}
void OnColumnSortingChanged()
{
if(m_Table.sortedColumns != null)
{
List<TreeViewItemData<U2DGraphicsHierarchyNodeData>> sortedData = new();
foreach(var child in m_Data)
{
List<TreeViewItemData<U2DGraphicsHierarchyNodeData>> children = new();
foreach(var c in child.children)
{
children.Add(c);
}
children.Sort(SortData);
sortedData.Add(new TreeViewItemData<U2DGraphicsHierarchyNodeData>(child.id, child.data, children));
}
sortedData.Sort(SortData);
m_Data.Clear();
m_Data = sortedData;
m_Table.Clear();
HashSet<int> expandedIds = new();
foreach(var d in m_Data)
{
if(m_Table.IsExpanded(d.id))
expandedIds.Add(d.id);
}
m_Table.SetRootItems(m_Data);
m_Table.Rebuild();
foreach(var id in expandedIds)
{
m_Table.ExpandItem(id);
}
ShowTable();
}
}
int SortData(TreeViewItemData<U2DGraphicsHierarchyNodeData> a, TreeViewItemData<U2DGraphicsHierarchyNodeData> b)
{
using (var enumerator = m_Table.sortedColumns.GetEnumerator())
{
while (enumerator.MoveNext())
{
int result = U2DGraphicsHierarchyNodeData.Compare(a.data, b.data, enumerator.Current.column.bindingPath);
if (result != 0)
return result * (enumerator.Current.direction == SortDirection.Ascending ? 1 : -1);
}
}
return U2DGraphicsHierarchyNodeData.Compare(a.data, b.data, null);
}
void BindLabelToDataSource(Label label, string path, U2DGraphicsHierarchyNodeData cellData)
{
label.SetBinding("text", new DataBinding
{
dataSourcePath = new PropertyPath(path),
bindingMode = BindingMode.ToTarget,
dataSource = cellData
});
}
void SetNameColumnCellIcon(VisualElement ele, U2DGraphicsHierarchyNodeData data)
{
var icon = ele.Q("Icon");
icon.RemoveFromClassList("gameObject-icon");
icon.RemoveFromClassList("shadowCaster-icon");
icon.RemoveFromClassList("light-icon");
icon.RemoveFromClassList("category-icon");
if(data.icon?.Length > 0)
icon.AddToClassList(data.icon);
}
public void SetData(List<U2DGraphicsHierarchyNodeData>[] categorizedData)
{
m_Table.Clear();
HashSet<int> expandedIds = new();
foreach(var item in m_Data)
{
if(m_Table.IsExpanded(item.id))
expandedIds.Add(item.id);
}
m_Data.Clear();
if (categorizedData == null || categorizedData.Length < 2)
{
ShowTable();
return;
}
int rootId = 1;
int childId = 1000;
// Shadow root node (index 0)
var shadowList = categorizedData[0];
if (shadowList != null && shadowList.Count > 0)
{
var shadowRoot = new U2DGraphicsHierarchyNodeData("Shadow", EntityId.None, 0, 0, rootId++, "category-icon");
var shadowChildren = new List<TreeViewItemData<U2DGraphicsHierarchyNodeData>>();
foreach (var node in shadowList)
{
node.icon = "shadowCaster-icon";
shadowChildren.Add(new TreeViewItemData<U2DGraphicsHierarchyNodeData>(childId++, node));
shadowRoot.vertexCount += node.vertexCount;
shadowRoot.triangleCount += node.triangleCount;
}
if (m_Table.sortedColumns != null)
{
shadowChildren.Sort(SortData);
}
m_Data.Add(new TreeViewItemData<U2DGraphicsHierarchyNodeData>(shadowRoot.id, shadowRoot, shadowChildren));
}
// Light root node (index 1)
var lightList = categorizedData[1];
if (lightList != null && lightList.Count > 0)
{
var lightRoot = new U2DGraphicsHierarchyNodeData("Light", EntityId.None, 0, 0, rootId++, "category-icon");
var lightChildren = new List<TreeViewItemData<U2DGraphicsHierarchyNodeData>>();
foreach (var node in lightList)
{
node.icon = "light-icon";
lightChildren.Add(new TreeViewItemData<U2DGraphicsHierarchyNodeData>(childId++, node));
lightRoot.vertexCount += node.vertexCount;
lightRoot.triangleCount += node.triangleCount;
}
if (m_Table.sortedColumns != null)
{
lightChildren.Sort(SortData);
}
m_Data.Add(new TreeViewItemData<U2DGraphicsHierarchyNodeData>(lightRoot.id, lightRoot, lightChildren));
}
if (m_Table.sortedColumns != null)
{
m_Data.Sort(SortData);
}
m_Table.SetRootItems(m_Data);
m_Table.Rebuild();
foreach(var id in expandedIds)
{
m_Table.ExpandItem(id);
}
ShowTable();
}
void ShowTable()
{
if(m_Data.Count == 0)
{
m_Table.style.display = DisplayStyle.None;
m_NoDataLabel.style.display = DisplayStyle.Flex;
}
else
{
m_Table.style.display = DisplayStyle.Flex;
m_NoDataLabel.style.display = DisplayStyle.None;
}
}
}
}
@@ -0,0 +1,67 @@
.container {
flex-grow: 1;
height: 100%;
}
.table {
flex-grow: 1;
height: 100%;
}
.unity-multi-column-header__column--sortable {
flex-direction: row-reverse;
}
#unity-multi-column-header-column-title{
overflow: hidden;
text-overflow: ellipsis;
}
.cell {
flex-direction: row;
align-items: center;
align-content: center;
height: 25px;
}
.cell-icon {
max-width: 16px;
max-height: 16px;
min-width: 16px;
min-height: 16px;
flex: 0 0 0;
flex-direction: row;
background-color: rgba(0, 0, 0, 0);
}
.cell-label {
flex-grow: 1;
}
.shadowCaster-icon {
background-image: resource('GameObject Icon');
}
.dark .shadowCaster-icon {
background-image: resource('d_GameObject Icon');
}
.dark .gameObject-icon {
background-image: resource('d_GameObject Icon');
}
.gameObject-icon {
background-image: resource('GameObject Icon');
}
.light-icon {
background-image: url('../../../../../Editor/2D/ResourceIcons/InspectorIcons/SpriteLight.png');
}
.category-icon {
background-image: resource('Folder Icon');
}
.dark .category-icon {
background-image: resource('d_Folder Icon');
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 97f83210b5a4448cfbc61ec93d00fcaf
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0}
disableValidation: 0
unsupportedSelectorAction: 0
@@ -0,0 +1,18 @@
<ui:UXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:ui="UnityEngine.UIElements"
xmlns:uie="UnityEditor.UIElements"
noNamespaceSchemaLocation="../../../../UIElementsSchema/UIElements.xsd">
<Style src="./U2DGraphicsHierarchyView.uss"/>
<ui:VisualElement class="container">
<ui:Label name = "noDataLabel" text = "No data to show. Select another frame." />
<ui:MultiColumnTreeView name="Table" show-alternating-row-backgrounds="ContentOnly" horizontal-scrolling="true"
sorting-mode="Default" class="table">
<ui:Columns primary-column-name="Name" resize-preview="false">
<ui:Column name="Name" title="Name" binding-path="name" width="200px"/>
<ui:Column name="Triangles" title="Triangles" binding-path="triangleCount" width="150px"/>
<ui:Column name="Vertices" title="Vertices" binding-path="vertexCount" width="150px"/>
<ui:Column name="DrawCount" title="DrawCount" binding-path="m_DrawCountLabel" width="150px"/>
</ui:Columns>
</ui:MultiColumnTreeView>
</ui:VisualElement>
</ui:UXML>
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: 232651f0deb5c4f098846bdb18845f8a
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 86446373f4471422b9f5cb31a4a4577d
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,57 @@
using System;
using System.Collections.Generic;
using UnityEditor.U2D.Graphics.Profiler.UI;
using UnityEngine;
using UnityEngine.UIElements;
namespace UnityEditor.U2D.Graphics.Profiler
{
[Serializable]
class U2DGraphicsProfilerView : VisualElement
{
const string k_UXML = "Packages/com.unity.render-pipelines.universal/Editor/2D/Profiler/UI/U2DGraphicsProfilerView/U2DGraphicsProfilerView.uxml";
U2DGraphicsHierarchyView m_U2DGraphicsHierarchyView;
U2DGraphicsStatisticView m_StatisticView;
public U2DGraphicsProfilerView()
{
var visualTree = AssetDatabase.LoadAssetAtPath<VisualTreeAsset>(k_UXML);
visualTree.CloneTree(this);
var splitView = this.Q<TwoPaneSplitView>();
splitView.fixedPaneInitialDimension = 300;
splitView.fixedPaneIndex = 0;
m_U2DGraphicsHierarchyView = new U2DGraphicsHierarchyView();
m_StatisticView = new U2DGraphicsStatisticView();
var twoPaneSplitView = this.Q<TwoPaneSplitView>();
twoPaneSplitView.Add(m_StatisticView);
twoPaneSplitView.Add(m_U2DGraphicsHierarchyView);
#if ENABLE_PROFILER && PROFILER_INSTALLED
this.Q<Label>("noProfiling").style.display = DisplayStyle.None;
twoPaneSplitView.style.display = DisplayStyle.Flex;
#else
this.Q<Label>("noProfiling").style.display = DisplayStyle.Flex;
twoPaneSplitView.style.display = DisplayStyle.None;
#endif
}
public void SetHierarchyData(List<U2DGraphicsHierarchyNodeData>[] categorizedData)
{
m_U2DGraphicsHierarchyView.SetData(categorizedData);
}
public void SetStatistic(long normalTextures, long lightTextures, long lightBatches, long lightTriangles,
long shadowTextures, long shadowCasters, long shadowTriangles,
float renderPassTime, float drawShadowTime, float normalPassTime, float shadowPassTime)
{
m_StatisticView.SetStatistic(normalTextures, lightTextures, lightBatches, lightTriangles,
shadowTextures, shadowCasters, shadowTriangles,
renderPassTime, drawShadowTime, normalPassTime, shadowPassTime);
}
public bool IsLiveUpdateEnabled()
{
return m_StatisticView.IsLiveUpdateEnabled();
}
}
}

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