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,121 @@
using System;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Rendering
{
/// <summary>
/// Helper class that serializes Rendering Debugger state across domain reloads.
/// If you want the state of your debug variables to persist across domain reloads, the setting class should
/// be marked [Serializable] and implement the <see cref="ISerializedDebugDisplaySettings"/> interface.
/// Then you can access the serialized instance through <see cref="GetOrCreate{T}"/>.
/// </summary>
public sealed class DebugDisplaySerializer
#if UNITY_EDITOR
: ScriptableSingleton<DebugDisplaySerializer>
#endif
{
// For player builds, implement the singleton pattern internally
#if !UNITY_EDITOR
static Lazy<DebugDisplaySerializer> s_Instance = new (() => new ());
/// <summary>Gets the instance of the singleton.</summary>
public static DebugDisplaySerializer instance => s_Instance.Value;
#endif
[SerializeReference]
List<ISerializedDebugDisplaySettings> m_Settings = new();
[SerializeField]
SerializedDictionary<string, bool> m_FoldoutStates = new();
ISerializedDebugDisplaySettings GetOrCreate(Type type)
{
var setting = Get(type);
if (setting != null)
return setting;
if (!type.IsAbstract && !type.IsInterface)
{
setting = Activator.CreateInstance(type, nonPublic: true) as ISerializedDebugDisplaySettings;
m_Settings.Add(setting);
return setting;
}
return null;
}
ISerializedDebugDisplaySettings Get(Type type)
{
int numSettings = m_Settings.Count;
for (int i = 0; i < numSettings; ++i)
{
if (m_Settings[i].GetType() == type)
return m_Settings[i];
}
return null;
}
/// <summary>
/// Returns the serialized instance for the given debug display settings type.
/// If the instance does not exist yet, it will be created. The next time this method is called with
/// the same type, the same instance will be returned.
/// </summary>
/// <typeparam name="T">The debug display settings type to retrieve.</typeparam>
/// <returns>The serialized instance for the given debug display settings type.</returns>
public static T GetOrCreate<T>() where T : class, ISerializedDebugDisplaySettings
{
return instance.GetOrCreate(typeof(T)) as T;
}
/// <summary>
/// Returns the serialized instance for the given debug display settings type.
/// If the instance does not exist, null is returned.
/// </summary>
/// <typeparam name="T">The debug display settings type to retrieve.</typeparam>
/// <returns>The serialized instance for the given debug display settings type if it exists, or null otherwise.</returns>
public static T Get<T>() where T : class, ISerializedDebugDisplaySettings
{
return instance.Get(typeof(T)) as T;
}
/// <summary>
/// Remove all instances of serialized debug display settings that have been created.
/// </summary>
public static void Clear()
{
instance.m_Settings.Clear();
}
/// <summary>
/// Restore foldout open/closed states from serialized data.
/// </summary>
public static void LoadFoldoutStates()
{
DebugManager.instance.ForEachWidget(widget =>
{
if (widget is DebugUI.Foldout foldout)
if (instance.m_FoldoutStates.TryGetValue(widget.queryPath, out bool opened))
foldout.opened = opened;
});
}
/// <summary>
/// Save foldout open/closed states to serialized data.
/// </summary>
public static void SaveFoldoutStates()
{
instance.m_FoldoutStates.Clear();
DebugManager.instance.ForEachWidget(widget =>
{
if (widget is DebugUI.Foldout foldout)
instance.m_FoldoutStates.TryAdd(widget.queryPath, foldout.opened);
});
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5656576c8c834caeac23f9db698f265f
timeCreated: 1756467515
@@ -0,0 +1,165 @@
using System;
using System.Collections.Generic;
namespace UnityEngine.Rendering
{
/// <summary>
/// Templated class for <see cref="IDebugDisplaySettings"/>
/// </summary>
/// <typeparam name="T">The specific type of Debug Display Settings that is inheriting from the IDebugDisplaySettings interface.</typeparam>
public abstract class DebugDisplaySettings<T> : IDebugDisplaySettings
where T : IDebugDisplaySettings, new()
{
class IDebugDisplaySettingsDataComparer : IEqualityComparer<IDebugDisplaySettingsData>
{
public bool Equals(IDebugDisplaySettingsData x, IDebugDisplaySettingsData y)
{
if (ReferenceEquals(x, y))
return true;
if (x == null || y == null)
return false;
return x.GetType() == y.GetType();
}
public int GetHashCode(IDebugDisplaySettingsData obj)
{
// Define your custom hashing logic based on the properties you want to include.
unchecked
{
int hash = 17;
hash = hash * 23 + obj.GetType().GetHashCode();
return hash;
}
}
}
/// <summary>
/// The set of <see cref="IDebugDisplaySettingsData"/> containing the settings for this debug display
/// </summary>
protected readonly HashSet<IDebugDisplaySettingsData> m_Settings = new HashSet<IDebugDisplaySettingsData>(new IDebugDisplaySettingsDataComparer());
private static readonly Lazy<T> s_Instance = new Lazy<T>(() =>
{
var instance = new T();
instance.Reset();
return instance;
});
/// <summary>
/// The singleton instance that contains the current settings of Rendering Debugger.
/// </summary>
public static T Instance => s_Instance.Value;
#region IDebugDisplaySettingsQuery
/// <summary>
/// Returns true if any of the debug settings are currently active.
/// </summary>
public virtual bool AreAnySettingsActive
{
get
{
foreach (IDebugDisplaySettingsData setting in m_Settings)
{
if (setting.AreAnySettingsActive)
return true;
}
return false;
}
}
/// <summary>
/// Checks whether the current state of these settings allows post-processing.
/// </summary>
public virtual bool IsPostProcessingAllowed
{
get
{
// Only enable post-processing if we aren't using certain debug-views.
bool postProcessingAllowed = true;
foreach (IDebugDisplaySettingsData setting in m_Settings)
postProcessingAllowed &= setting.IsPostProcessingAllowed;
return postProcessingAllowed;
}
}
/// <summary>
/// Returns true if lighting is active for current state of debug settings.
/// </summary>
public virtual bool IsLightingActive
{
get
{
bool lightingActive = true;
foreach (IDebugDisplaySettingsData setting in m_Settings)
lightingActive &= setting.IsLightingActive;
return lightingActive;
}
}
#endregion
/// <summary>
/// Adds a new <see cref="TData"/> to this settings
/// </summary>
/// <typeparam name="TData">The type of <see cref="TData"/> to be added</typeparam>
/// <param name="newData">The <see cref="TData"/> to be added</param>
/// <returns>The type of <see cref="TData"/> that has been added</returns>
protected TData Add<TData>(TData newData)
where TData : IDebugDisplaySettingsData
{
m_Settings.Add(newData);
return newData;
}
/// <inheritdoc/>
IDebugDisplaySettingsData IDebugDisplaySettings.Add(IDebugDisplaySettingsData newData)
{
m_Settings.Add(newData);
return newData;
}
/// <summary>
/// Executes an action for each element
/// </summary>
/// <param name="onExecute">The action to be executed on each element in the Debug Display Settings data.</param>
public void ForEach(Action<IDebugDisplaySettingsData> onExecute)
{
foreach (IDebugDisplaySettingsData setting in m_Settings)
{
onExecute(setting);
}
}
/// <summary>
/// Reset the stored debug settings
/// </summary>
public virtual void Reset()
{
foreach (IDebugDisplaySettingsData setting in m_Settings)
{
setting.Reset();
}
m_Settings.Clear();
}
/// <summary>
/// Attempts to get the color that should be used to clear the screen according to current debug settings.
/// </summary>
/// <param name="color">A reference to the screen clear color to use.</param>
/// <returns>True if the color reference was updated, and false otherwise.</returns>
public virtual bool TryGetScreenClearColor(ref Color color)
{
foreach (IDebugDisplaySettingsData setting in m_Settings)
{
if (setting.TryGetScreenClearColor(ref color))
return true;
}
return false;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: c4e8d2f4fab62224f8d693e15696410e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,235 @@
namespace UnityEngine.Rendering
{
/// <summary>
/// Debug Display Settings HDR Output
/// </summary>
public class DebugDisplaySettingsHDROutput
{
static class Strings
{
public static readonly string hdrOutputAPI = "HDROutputSettings";
public static readonly string displayName = "Display ";
public static readonly string displayMain = " (main)";
public static readonly string hdrActive = "HDR Output Active";
public static readonly string hdrAvailable = "HDR Output Available";
public static readonly string gamut = "Display Color Gamut";
public static readonly string format = "Display Buffer Graphics Format";
public static readonly string autoHdrTonemapping = "Automatic HDR Tonemapping";
public static readonly string paperWhite = "Paper White Nits";
public static readonly string minLuminance = "Min Tone Map Luminance";
public static readonly string maxLuminance = "Max Tone Map Luminance";
public static readonly string maxFullFrameLuminance = "Max Full Frame Tone Map Luminance";
public static readonly string modeChangeRequested = "HDR Mode Change Requested";
public static readonly string notAvailable = "N/A";
}
/// <summary>
/// Creates a table of values from the HDROutputSettings API.
/// </summary>
/// <returns>A table containing the values from the HDROutputSettings API.</returns>
public static DebugUI.Table CreateHDROuputDisplayTable()
{
//Create table and rows
var table = new DebugUI.Table()
{
displayName = Strings.hdrOutputAPI,
alternateRowColors = true,
isReadOnly = true
};
var row_hdrActive = new DebugUI.Table.Row { displayName = Strings.hdrActive };
var row_hdrAvailable = new DebugUI.Table.Row { displayName = Strings.hdrAvailable };
var row_gamut = new DebugUI.Table.Row { displayName = Strings.gamut };
var row_format = new DebugUI.Table.Row { displayName = Strings.format };
var row_autoHdrTonemapping = new DebugUI.Table.Row { displayName = Strings.autoHdrTonemapping };
var row_paperWhite = new DebugUI.Table.Row { displayName = Strings.paperWhite };
var row_minLuminance = new DebugUI.Table.Row { displayName = Strings.minLuminance };
var row_maxLuminance = new DebugUI.Table.Row { displayName = Strings.maxLuminance };
var row_maxFullFrameLuminance = new DebugUI.Table.Row { displayName = Strings.maxFullFrameLuminance};
var row_modeChangeRequested = new DebugUI.Table.Row { displayName = Strings.modeChangeRequested };
//Iterate through all displays
HDROutputSettings[] displays = HDROutputSettings.displays;
for(int i=0; i<displays.Length; i++)
{
var d = displays[i];
//Check if main display
int idName = i + 1;
var name = Strings.displayName + idName;
if(HDROutputSettings.main == d)
{
name += Strings.displayMain;
}
//Fill rows
row_hdrActive.children.Add
(
new DebugUI.Value()
{
displayName = name,
getter = () =>
{
return d.active;
}
}
);
row_hdrAvailable.children.Add
(
new DebugUI.Value()
{
displayName = name,
getter = () =>
{
return d.available;
}
}
);
row_gamut.children.Add
(
new DebugUI.Value()
{
displayName = name,
getter = () =>
{
if(d.available)
{
return d.displayColorGamut;
}
return Strings.notAvailable;
}
}
);
row_format.children.Add
(
new DebugUI.Value()
{
displayName = name,
getter = () =>
{
if(d.available)
{
return d.graphicsFormat;
}
return Strings.notAvailable;
}
}
);
row_autoHdrTonemapping.children.Add
(
new DebugUI.Value()
{
displayName = name,
getter = () =>
{
if(d.available)
{
return d.automaticHDRTonemapping;
}
return Strings.notAvailable;
}
}
);
row_paperWhite.children.Add
(
new DebugUI.Value()
{
displayName = name,
getter = () =>
{
if(d.available)
{
return d.paperWhiteNits;
}
return Strings.notAvailable;
}
}
);
row_minLuminance.children.Add
(
new DebugUI.Value()
{
displayName = name,
getter = () =>
{
if(d.available)
{
return d.minToneMapLuminance;
}
return Strings.notAvailable;
}
}
);
row_maxLuminance.children.Add
(
new DebugUI.Value()
{
displayName = name,
getter = () =>
{
if(d.available)
{
return d.maxToneMapLuminance;
}
return Strings.notAvailable;
}
}
);
row_maxFullFrameLuminance.children.Add
(
new DebugUI.Value()
{
displayName = name,
getter = () =>
{
if(d.available)
{
return d.maxFullFrameToneMapLuminance;
}
return Strings.notAvailable;
}
}
);
row_modeChangeRequested.children.Add
(
new DebugUI.Value()
{
displayName = name,
getter = () =>
{
if(d.available)
{
return d.HDRModeChangeRequested;
}
return Strings.notAvailable;
}
}
);
}
//Add rows to table
table.children.Add(row_hdrActive);
table.children.Add(row_hdrAvailable);
table.children.Add(row_gamut);
table.children.Add(row_format);
table.children.Add(row_autoHdrTonemapping);
table.children.Add(row_paperWhite);
table.children.Add(row_minLuminance);
table.children.Add(row_maxLuminance);
table.children.Add(row_maxFullFrameLuminance);
table.children.Add(row_modeChangeRequested);
return table;
}
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: daa3eec2dfce59046ae258efe3ff1419
@@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.Reflection;
namespace UnityEngine.Rendering
{
/// <summary>
/// The abstract common implementation of the <see cref="IDebugDisplaySettingsPanelDisposable"/>
/// </summary>
public abstract class DebugDisplaySettingsPanel : IDebugDisplaySettingsPanelDisposable
{
private readonly List<DebugUI.Widget> m_Widgets = new List<DebugUI.Widget>();
private readonly DisplayInfoAttribute m_DisplayInfo;
/// <summary>
/// The Panel name
/// </summary>
public virtual string PanelName => m_DisplayInfo?.name ?? string.Empty;
/// <summary>
/// The order where this panel should be shown
/// </summary>
public virtual int Order => m_DisplayInfo?.order ?? 0;
/// <summary>
/// The collection of widgets that are in this panel
/// </summary>
public DebugUI.Widget[] Widgets => m_Widgets.ToArray();
/// <summary>
/// The <see cref="DebugUI.Flags"/> for this panel
/// </summary>
public virtual DebugUI.Flags Flags => DebugUI.Flags.None;
/// <summary>
/// Adds a widget to the panel
/// </summary>
/// <param name="widget">The <see cref="DebugUI.Widget"/> to be added.</param>
protected void AddWidget(DebugUI.Widget widget)
{
if (widget == null)
throw new ArgumentNullException(nameof(widget));
m_Widgets.Add(widget);
}
/// <summary>
/// Clears the widgets list
/// </summary>
protected void Clear()
{
m_Widgets.Clear();
}
/// <summary>
/// Disposes the panel
/// </summary>
public virtual void Dispose()
{
Clear();
}
/// <summary>
/// Default constructor
/// </summary>
protected DebugDisplaySettingsPanel()
{
m_DisplayInfo = GetType().GetCustomAttribute<DisplayInfoAttribute>();
if (m_DisplayInfo == null)
Debug.Log($"Type {GetType()} should specify the attribute {nameof(DisplayInfoAttribute)}");
}
}
/// <summary>
/// Class to help declare rendering debugger panels
/// </summary>
/// <typeparam name="T">The type of Debug Display Settings Data that a Rendering Debugger Panel is using.</typeparam>
public abstract class DebugDisplaySettingsPanel<T> : DebugDisplaySettingsPanel
where T : IDebugDisplaySettingsData
{
internal T m_Data;
/// <summary>
/// Access to the data stored
/// </summary>
public T data
{
get => m_Data;
internal set => m_Data = value;
}
/// <summary>
/// Default constructor
/// </summary>
/// <param name="data">The data that the panel holds</param>
protected DebugDisplaySettingsPanel(T data)
: base()
{
m_Data = data;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: e5ee786a2f4e04b5bbc5c7b2e645272e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,116 @@
using System;
using System.Collections.Generic;
namespace UnityEngine.Rendering
{
/// <summary>
/// Display stats panel.
/// </summary>
public class DebugDisplaySettingsStats : IDebugDisplaySettingsData
{
/// <summary>Current display stats.</summary>
public DebugDisplayStats debugDisplayStats { get; }
/// <summary>
/// Display stats panel constructor with settings.
/// </summary>
/// <param name="debugDisplayStats">The debug display stats object that is used for configuring settings in the stats panel.</param>
public DebugDisplaySettingsStats(DebugDisplayStats debugDisplayStats)
{
this.debugDisplayStats = debugDisplayStats;
}
[DisplayInfo(name = "Display Stats", order = int.MinValue)]
private class StatsPanel : DebugDisplaySettingsPanel
{
readonly DebugDisplaySettingsStats m_Data;
public override DebugUI.Flags Flags => DebugUI.Flags.RuntimeOnly;
public StatsPanel(DebugDisplaySettingsStats displaySettingsStats)
{
m_Data = displaySettingsStats;
m_Data.debugDisplayStats.EnableProfilingRecorders();
var list = new List<DebugUI.Widget>();
m_Data.debugDisplayStats.RegisterDebugUI(list);
foreach (var w in list)
AddWidget(w);
}
public override void Dispose()
{
m_Data.debugDisplayStats.DisableProfilingRecorders();
base.Dispose();
}
}
/// <inheritdoc/>
public bool AreAnySettingsActive => false;
/// <inheritdoc/>
public IDebugDisplaySettingsPanelDisposable CreatePanel()
{
return new StatsPanel(this);
}
}
/// <summary>
/// Display stats panel.
/// </summary>
/// <typeparam name="TProfileId">Type of ProfileId the pipeline uses</typeparam>
[Obsolete("Use the non-generic DebugDisplaySettingsStats class. #from(6000.6)")]
public class DebugDisplaySettingsStats<TProfileId> : IDebugDisplaySettingsData
where TProfileId : Enum
{
/// <summary>Current display stats</summary>
public DebugDisplayStats<TProfileId> debugDisplayStats { get; }
/// <summary>
/// Display stats panel constructor with settings
/// </summary>
/// <param name="debugDisplayStats">The debug display stats object that is used for configuring settings in the stats panel.</param>
public DebugDisplaySettingsStats(DebugDisplayStats<TProfileId> debugDisplayStats)
{
this.debugDisplayStats = debugDisplayStats;
}
[DisplayInfo(name = "Display Stats", order = int.MinValue)]
private class StatsPanel : DebugDisplaySettingsPanel
{
readonly DebugDisplaySettingsStats<TProfileId> m_Data;
public override DebugUI.Flags Flags => DebugUI.Flags.RuntimeOnly;
public StatsPanel(DebugDisplaySettingsStats<TProfileId> displaySettingsStats)
{
m_Data = displaySettingsStats;
m_Data.debugDisplayStats.EnableProfilingRecorders();
var list = new List<DebugUI.Widget>();
m_Data.debugDisplayStats.RegisterDebugUI(list);
foreach (var w in list)
AddWidget(w);
}
public override void Dispose()
{
m_Data.debugDisplayStats.DisableProfilingRecorders();
base.Dispose();
}
}
/// <inheritdoc/>
public bool AreAnySettingsActive => false;
/// <inheritdoc/>
public IDebugDisplaySettingsPanelDisposable CreatePanel()
{
return new StatsPanel(this);
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6d72467fc287492393584eb6647d416d
timeCreated: 1661338407
@@ -0,0 +1,141 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEngine.Rendering.RenderGraphModule;
namespace UnityEngine.Rendering
{
/// <summary>
/// The UI implementation for a debug settings panel
/// </summary>
public class DebugDisplaySettingsUI : IDebugData
{
private IEnumerable<IDebugDisplaySettingsPanelDisposable> m_DisposablePanels;
private IDebugDisplaySettings m_Settings;
private void Reset()
{
if (m_Settings != null)
{
m_Settings.Reset();
ReregisterDebugPanels();
}
}
/// <summary>
/// Unregisters and re-registers all DebugUI panels associated with the current <see cref="ISerializedDebugDisplaySettings"/>.
/// This effectively rebuilds the debug panel hierarchy without touching the Rendering Debugger window state itself.
/// </summary>
void ReregisterDebugPanels()
{
// TODO: Tear the UI down and re-create it for now - this is horrible, so reset it instead.
UnregisterDebug();
RegisterDebug(m_Settings);
}
/// <summary>
/// Register a display for the UI
/// </summary>
/// <param name="settings"><see cref="IDebugDisplaySettings"/> to be registered</param>
public void RegisterDebug(IDebugDisplaySettings settings)
{
DebugManager.instance.RegisterData(this);
DebugManager.instance.onRecreateDebugUI += ReregisterDebugPanels;
m_Settings = settings;
m_Settings.Add(new DebugDisplaySettingsRenderGraph());
// Don't initialize the UI immediately to avoid unnecessary work at pipeline init time. Instaed,
// initialize UI when any debug UI is opened (or if the editor window is already open)
DebugManager.windowStateChanged += DebugUIOpened;
if (DebugManager.instance.isAnyDebugUIActive)
InitializeDebugUI();
}
void DebugUIOpened(DebugManager.UIMode uiMode, bool isOpen)
{
InitializeDebugUI();
}
internal void InitializeDebugUI()
{
if (m_DisposablePanels == null)
{
var panels = new List<IDebugDisplaySettingsPanelDisposable>();
Action<IDebugDisplaySettingsData> onExecute = (data) =>
{
IDebugDisplaySettingsPanelDisposable disposableSettingsPanel = data.CreatePanel();
DebugUI.Widget[] panelWidgets = disposableSettingsPanel.Widgets;
DebugUI.Panel panel = DebugManager.instance.GetPanel(
displayName: disposableSettingsPanel.PanelName,
createIfNull: true,
groupIndex: (disposableSettingsPanel is DebugDisplaySettingsPanel debugDisplaySettingsPanel) ? debugDisplaySettingsPanel.Order : 0);
#if UNITY_EDITOR
if (DocumentationUtils.TryGetHelpURL(disposableSettingsPanel.GetType(), out var documentationUrl))
panel.documentationUrl = documentationUrl;
#endif
ObservableList<DebugUI.Widget> panelChildren = panel.children;
panel.flags = disposableSettingsPanel.Flags;
panels.Add(disposableSettingsPanel);
panelChildren.Add(panelWidgets);
};
m_Settings.ForEach(onExecute);
m_DisposablePanels = panels;
DebugDisplaySerializer.LoadFoldoutStates();
}
}
/// <summary>
/// Unregister the debug panels
/// </summary>
public void UnregisterDebug()
{
DebugDisplaySerializer.SaveFoldoutStates();
DebugManager debugManager = DebugManager.instance;
if (m_DisposablePanels != null)
{
foreach (IDebugDisplaySettingsPanelDisposable disposableSettingsPanel in m_DisposablePanels)
{
DebugUI.Widget[] panelWidgets = disposableSettingsPanel.Widgets;
string panelId = disposableSettingsPanel.PanelName;
DebugUI.Panel panel = debugManager.GetPanel(panelId, true);
ObservableList<DebugUI.Widget> panelChildren = panel.children;
disposableSettingsPanel.Dispose();
panelChildren.Remove(panelWidgets);
}
m_DisposablePanels = null;
}
debugManager.UnregisterData(this);
debugManager.onRecreateDebugUI -= ReregisterDebugPanels;
DebugManager.windowStateChanged -= DebugUIOpened;
}
#region IDebugData
/// <summary>
/// The reset action to be executed when a Reset of the rendering debugger is need
/// </summary>
/// <returns>A <see cref="Action"/> with the restet callback</returns>
public Action GetReset()
{
return Reset;
}
#endregion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 267b889b8e81a45d2a5f5bc4121bc7b9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,755 @@
using System;
using System.Collections.Generic;
using System.Reflection;
#if UNITY_EDITOR
using UnityEditor;
#endif
namespace UnityEngine.Rendering
{
/// <summary>
/// Debug Display Settings Volume
/// </summary>
[Serializable]
public class DebugDisplaySettingsVolume : IDebugDisplaySettingsData, ISerializedDebugDisplaySettings
{
/// <summary>Current volume debug settings.</summary>
[Obsolete("This property has been obsoleted and will be removed in a future version. #from(6000.2)")]
public IVolumeDebugSettings volumeDebugSettings { get; }
private int m_SelectedComponentIndex = -1;
/// <summary>Current volume component to debug.</summary>
public int selectedComponent
{
get => m_SelectedComponentIndex;
set
{
if (value != m_SelectedComponentIndex)
{
m_SelectedComponentIndex = value;
OnSelectionChanged();
}
}
}
private void DestroyVolumeInterpolatedResults()
{
if (m_VolumeInterpolatedResults != null)
ScriptableObject.DestroyImmediate(m_VolumeInterpolatedResults);
}
/// <summary>Type of the current component to debug.</summary>
public Type selectedComponentType
{
get => selectedComponent > 0 ? volumeComponentsPathAndType[selectedComponent - 1].Item2 : null;
set
{
var index = volumeComponentsPathAndType.FindIndex(t => t.Item2 == value);
if (index != -1)
selectedComponent = index + 1;
}
}
/// <summary>List of Volume component types.</summary>
public List<(string, Type)> volumeComponentsPathAndType => VolumeManager.instance.GetVolumeComponentsForDisplay(GraphicsSettings.currentRenderPipelineAssetType);
private Camera m_SelectedCamera;
/// <summary>Current camera to debug.</summary>
public Camera selectedCamera
{
get => m_SelectedCamera;
set
{
if (value != m_SelectedCamera)
{
m_SelectedCamera = value;
OnSelectionChanged();
}
}
}
private void OnSelectionChanged()
{
ClearInterpolationData();
DestroyVolumeInterpolatedResults();
}
VolumeComponent m_VolumeInterpolatedResults;
private bool m_StoreStackInterpolatedValues;
private ObservableList<Volume> m_InfluenceVolumes = new ();
private List<(Volume volume, float weight)> m_VolumesWeights = new ();
private void ClearInterpolationData()
{
m_VolumesWeights.Clear();
}
static bool AreVolumesChanged(ObservableList<Volume> influenceVolumes, List<(Volume volume, float weight)> volumesWeights)
{
// First, check if the lists have the same number of elements
if (influenceVolumes.Count != volumesWeights.Count)
return true;
// Sequence Equals
for (int i = 0; i < influenceVolumes.Count; i++)
{
if (influenceVolumes[i] != volumesWeights[i].volume)
return true;
}
// If all checks pass, the lists are the same (in terms of both content and order)
return false;
}
private void OnBeginVolumeStackUpdate(VolumeStack stack, Camera camera)
{
if (camera == selectedCamera)
{
ClearInterpolationData();
m_StoreStackInterpolatedValues = selectedCamera != null && selectedComponentType != null;
}
}
private void OnEndVolumeStackUpdate(VolumeStack stack, Camera camera)
{
if (m_StoreStackInterpolatedValues)
{
if (AreVolumesChanged(m_InfluenceVolumes, m_VolumesWeights))
{
m_InfluenceVolumes.Clear();
foreach (var pair in m_VolumesWeights)
m_InfluenceVolumes.Add(pair.volume);
}
// Copy the results of the interpolation into our resulVolumeComponent
var componentInStack = stack.GetComponent(selectedComponentType);
for (int i = 0; i < componentInStack.parameters.Count; ++i)
{
resultVolumeComponent.parameters[i].SetValue(componentInStack.parameters[i]);
}
m_StoreStackInterpolatedValues = false;
}
}
private void OnVolumeStackInterpolated(VolumeStack stack, Volume volume, float interpolationFactor)
{
if (m_StoreStackInterpolatedValues)
{
m_VolumesWeights.Add((volume, interpolationFactor));
}
}
/// <summary>
/// Obtains the volume weight
/// </summary>
/// <param name="volume"><see cref="Volume"/></param>
/// <returns>The weight of the volume</returns>
public float GetVolumeWeight(Volume volume)
{
// Try to get the weight associated with the volume
// If the volume is not found, return a default value (e.g., 0.0f)
if (m_VolumesWeights.Count == 0)
return 0.0f;
foreach (var pair in m_VolumesWeights)
{
if (volume == pair.volume)
return pair.weight;
}
return 0.0f;
}
/// <summary>
/// Gets the Volumes List for the current camera and selected volume component
/// </summary>
/// <returns>The list of influenced volumes</returns>
public ObservableList<Volume> GetVolumesList()
{
return m_InfluenceVolumes;
}
void IDebugDisplaySettingsData.Reset()
{
#if UNITY_ENABLE_CHECKS
VolumeManager.instance.overrideVolumeStackData -= OnVolumeStackInterpolated;
VolumeManager.instance.beginVolumeStackUpdate -= OnBeginVolumeStackUpdate;
VolumeManager.instance.endVolumeStackUpdate -= OnEndVolumeStackUpdate;
VolumeManager.instance.renderingDebuggerAttached = false;
#endif
ClearInterpolationData();
DestroyVolumeInterpolatedResults();
}
/// <summary>
/// Constructor with the settings
/// </summary>
/// <param name="volumeDebugSettings">The volume debug settings object used for configuration.</param>
[Obsolete("This constructor has been obsoleted and will be removed in a future version. #from(6000.2)")]
public DebugDisplaySettingsVolume(IVolumeDebugSettings volumeDebugSettings)
: this()
{
this.volumeDebugSettings = volumeDebugSettings;
}
/// <summary>
/// Constructor with the settings
/// </summary>
public DebugDisplaySettingsVolume()
{
#if UNITY_ENABLE_CHECKS
VolumeManager.instance.overrideVolumeStackData += OnVolumeStackInterpolated;
VolumeManager.instance.beginVolumeStackUpdate += OnBeginVolumeStackUpdate;
VolumeManager.instance.endVolumeStackUpdate += OnEndVolumeStackUpdate;
#endif
}
internal int volumeComponentEnumIndex;
internal VolumeComponent resultVolumeComponent
{
get
{
if (m_VolumeInterpolatedResults == null)
m_VolumeInterpolatedResults = ScriptableObject.CreateInstance(selectedComponentType) as VolumeComponent;
return m_VolumeInterpolatedResults;
}
}
internal static string ExtractResult(VolumeParameter param)
{
if (param == null)
return Strings.parameterNotCalculated;
var paramType = param.GetType();
var property = paramType.GetProperty("value");
if (property == null)
return "-";
var value = property.GetValue(param);
var propertyType = property.PropertyType;
if (value == null || value.Equals(null))
return Strings.none + $" ({propertyType.Name})";
var toString = propertyType.GetMethod("ToString", Type.EmptyTypes);
if ((toString == null) || (toString.DeclaringType == typeof(object)) || (toString.DeclaringType == typeof(Object)))
{
// Check if the parameter has a name
var nameProp = property.PropertyType.GetProperty("name");
if (nameProp == null)
return Strings.debugViewNotSupported;
var valueString = $"{nameProp.GetValue(value)}";
return valueString ?? Strings.none;
}
return value.ToString();
}
static class Styles
{
public static readonly GUIContent none = new GUIContent("None");
}
static class Strings
{
public static readonly string cameraNeedsRendering = "Values might not be fully updated if the camera you are inspecting is not rendered.";
public static readonly string none = "None";
public static readonly string parameter = "Parameter";
public static readonly string component = "Component";
public static readonly string debugViewNotSupported = "N/A";
public static readonly string volumeInfo = "Volume Info";
public static readonly string gameObject = "GameObject";
public static readonly string priority = "Priority";
public static readonly string resultValue = "Result";
public static readonly string resultValueTooltip = "The interpolated result value of the parameter. This value is used to render the camera.";
public static readonly string globalDefaultValue = "Graphics Settings";
public static readonly string globalDefaultValueTooltip = "Default value for this parameter, defined by the Default Volume Profile in Global Settings.";
public static readonly string qualityLevelValue = "Quality Settings";
public static readonly string qualityLevelValueTooltip = "Override value for this parameter, defined by the Volume Profile in the current SRP Asset.";
public static readonly string global = "Global";
public static readonly string local = "Local";
public static readonly string volumeProfile = "Volume Profile";
public static readonly string parameterNotCalculated = "N/A";
}
const string k_PanelTitle = "Volume";
#if UNITY_EDITOR
internal static void OpenInRenderingDebugger(VolumeComponent volumeComponent = null)
{
EditorApplication.ExecuteMenuItem("Window/Analysis/Rendering Debugger");
var panel = DebugManager.instance.GetPanel(k_PanelTitle);
if (panel == null)
return;
DebugManager.instance.RequestPanelSelection(k_PanelTitle);
// Try to select the given volume component in the component selector drop down
if (volumeComponent != null &&
VolumeManager.instance.TryGetVolumePathAndType(volumeComponent.GetType(), out var result) &&
panel.TryFindChild<DebugUI.EnumField>(Strings.component, out var componentSelector))
{
int selectedIndex = -1;
for (int i = 0; i < componentSelector.enumNames.Length; ++i)
{
var current = componentSelector.enumNames[i];
if (current.text.Equals(result.path))
{
selectedIndex = i;
break;
}
}
if (selectedIndex > -1)
EditorApplication.delayCall = () =>
{
componentSelector.SetValue(selectedIndex);
};
}
}
#endif
internal static class WidgetFactory
{
public static DebugUI.EnumField CreateComponentSelector(SettingsPanel panel, Action<DebugUI.Field<int>, int> refresh)
{
int componentIndex = 0;
var componentNames = new List<GUIContent>() { Styles.none };
var componentValues = new List<int>() { componentIndex++ };
var volumesAndTypes = panel.data.volumeComponentsPathAndType;
foreach (var type in volumesAndTypes)
{
componentNames.Add(new GUIContent() { text = type.Item1 });
componentValues.Add(componentIndex++);
}
return new DebugUI.EnumField
{
displayName = Strings.component,
getter = () => panel.data.selectedComponent,
setter = value => panel.data.selectedComponent = value,
enumNames = componentNames.ToArray(),
enumValues = componentValues.ToArray(),
getIndex = () => panel.data.volumeComponentEnumIndex,
setIndex = value => { panel.data.volumeComponentEnumIndex = value; },
onValueChanged = refresh
};
}
public static DebugUI.CameraSelector CreateCameraSelector(SettingsPanel panel, Action<DebugUI.Field<Object>, Object> refresh)
{
return new DebugUI.CameraSelector()
{
getter = () => panel.data.selectedCamera,
setter = value => panel.data.selectedCamera = value as Camera,
onValueChanged = refresh
};
}
internal static DebugUI.Widget CreateVolumeParameterWidget(string name, bool isResultParameter, VolumeParameter param)
{
#if UNITY_ENABLE_CHECKS
if (param != null)
{
Func<bool> isHiddenCallback = isResultParameter ?
() => false :
() => !param.overrideState;
var parameterType = param.GetType();
if (parameterType == typeof(ColorParameter))
{
var p = (ColorParameter)param;
return new DebugUI.ColorField()
{
displayName = "",
hdr = p.hdr,
showAlpha = p.showAlpha,
showPicker = false,
getter = () => p.value,
setter = value => p.value = value,
isHiddenCallback = isHiddenCallback
};
}
else if (parameterType.BaseType.IsGenericType && parameterType.BaseType.GetGenericArguments().Length > 0)
{
// Get the generic type argument, e.g., <Texture> in VolumeParameter<Texture>
var genericArgument = parameterType.BaseType.GetGenericArguments()[0];
// Check if the argument is a UnityEngine.Object or derived type
if (typeof(Object).IsAssignableFrom(genericArgument))
{
return new DebugUI.ObjectField()
{
displayName = "",
getter = () =>
{
var property = parameterType.GetProperty("value");
if (property == null)
return null;
var value = property.GetValue(param);
return value as Object;
},
isHiddenCallback = isHiddenCallback
};
}
}
var typeInfo = parameterType.GetTypeInfo();
var genericArguments = typeInfo.BaseType.GenericTypeArguments;
if (genericArguments.Length > 0 && genericArguments[0].IsArray)
{
return new DebugUI.ObjectListField()
{
displayName = name,
getter = () => (Object[])parameterType.GetProperty("value").GetValue(param, null),
type = parameterType,
// Result column reads a pool-rented buffer whose tail is null-padded; hide it.
trimTrailingNulls = isResultParameter,
isHiddenCallback = isHiddenCallback
};
}
return new DebugUI.Value()
{
displayName = name,
getter = () => ExtractResult(param),
isHiddenCallback = isHiddenCallback
};
}
#endif
return new DebugUI.Value() { displayName = name, getter = () => Strings.parameterNotCalculated, };
}
static readonly DebugUI.Value s_EmptyDebugUIValue = new DebugUI.Value { getter = () => string.Empty };
struct VolumeParameterChain
{
public DebugUI.Widget.NameAndTooltip nameAndTooltip;
public VolumeProfile volumeProfile;
public VolumeComponent volumeComponent;
public Volume volume;
}
static VolumeComponent GetSelectedVolumeComponent(VolumeProfile profile, Type selectedType)
{
if (profile != null)
{
foreach (var component in profile.components)
if (component.GetType() == selectedType)
return component;
}
return null;
}
static List<VolumeParameterChain> GetResolutionChain(DebugDisplaySettingsVolume data)
{
List<VolumeParameterChain> chain = new List<VolumeParameterChain>();
Type selectedType = data.selectedComponentType;
if (data.selectedCamera == null || selectedType == null)
return chain;
if (data.resultVolumeComponent == null)
return chain;
var result = new VolumeParameterChain()
{
nameAndTooltip = new DebugUI.Widget.NameAndTooltip()
{
name = Strings.resultValue,
tooltip = Strings.resultValueTooltip,
},
volumeComponent = data.resultVolumeComponent
};
chain.Add(result);
// Add volume components that override the default values.
// Iterate in reverse order to display the last interpolated Volume (most relevant) next to the result in the table view.
var volumes = data.GetVolumesList();
for (int i = volumes.Count - 1; i >= 0; i--)
{
var volume = volumes[i];
var profile = volume.HasInstantiatedProfile() ? volume.profile : volume.sharedProfile;
var overrideComponent = GetSelectedVolumeComponent(profile, selectedType);
if (overrideComponent != null)
{
var overrideVolume = new VolumeParameterChain()
{
nameAndTooltip = new DebugUI.Widget.NameAndTooltip()
{
name = profile.name,
tooltip = profile.name,
},
volumeProfile = profile,
volumeComponent = overrideComponent,
volume = volume
};
chain.Add(overrideVolume);
}
}
// Add custom default profiles
if (VolumeManager.instance.customDefaultProfiles != null)
{
foreach (var customProfile in VolumeManager.instance.customDefaultProfiles)
{
var customProfileComponent = GetSelectedVolumeComponent(customProfile, selectedType);
if (customProfileComponent != null)
{
var overrideVolume = new VolumeParameterChain()
{
nameAndTooltip = new DebugUI.Widget.NameAndTooltip()
{
name = customProfile.name,
tooltip = customProfile.name,
},
volumeProfile = customProfile,
volumeComponent = customProfileComponent,
};
chain.Add(overrideVolume);
}
}
}
// Add Quality Settings
if (VolumeManager.instance.qualityDefaultProfile != null)
{
var qualitySettingsComponent = GetSelectedVolumeComponent(VolumeManager.instance.qualityDefaultProfile, selectedType);
if (qualitySettingsComponent != null)
{
var overrideVolume = new VolumeParameterChain()
{
nameAndTooltip = new DebugUI.Widget.NameAndTooltip()
{
name = Strings.qualityLevelValue,
tooltip = Strings.qualityLevelValueTooltip,
},
volumeProfile = VolumeManager.instance.qualityDefaultProfile,
volumeComponent = qualitySettingsComponent,
};
chain.Add(overrideVolume);
}
}
// Add Graphics Settings
if (VolumeManager.instance.globalDefaultProfile != null)
{
var graphicsSettingsComponent = GetSelectedVolumeComponent(VolumeManager.instance.globalDefaultProfile, selectedType);
if (graphicsSettingsComponent != null)
{
var overrideVolume = new VolumeParameterChain()
{
nameAndTooltip = new DebugUI.Widget.NameAndTooltip()
{
name = Strings.globalDefaultValue,
tooltip = Strings.globalDefaultValueTooltip,
},
volumeProfile = VolumeManager.instance.globalDefaultProfile,
volumeComponent = graphicsSettingsComponent,
};
chain.Add(overrideVolume);
}
}
return chain;
}
public static DebugUI.Table CreateVolumeTable(DebugDisplaySettingsVolume data)
{
// Function for updating the attach state and also checking if the table should be visible
Func<bool> hiddenCallback = () =>
{
#if UNITY_ENABLE_CHECKS
VolumeManager.instance.renderingDebuggerAttached = data.selectedComponent > 0 && data.selectedCamera != null;
return !VolumeManager.instance.renderingDebuggerAttached;
#else
return true;
#endif
};
var table = new DebugUI.Table()
{
displayName = Strings.parameter,
isReadOnly = true,
alternateRowColors = true,
isHiddenCallback = hiddenCallback,
};
var resolutionChain = GetResolutionChain(data);
if (resolutionChain.Count == 0)
return table;
GenerateTableRows(table, resolutionChain);
GenerateTableColumns(table, data, resolutionChain);
return table;
}
private static void GenerateTableColumns(DebugUI.Table table, DebugDisplaySettingsVolume data, List<VolumeParameterChain> resolutionChain)
{
for (int i = 0; i < resolutionChain.Count; ++i)
{
var chain = resolutionChain[i];
int iRowIndex = -1;
if (chain.volume != null)
{
((DebugUI.Table.Row)table.children[++iRowIndex]).children.Add(new DebugUI.Value()
{
nameAndTooltip = chain.nameAndTooltip,
getter = () =>
{
var scope = chain.volume.isGlobal ? Strings.global : Strings.local;
var weight = data.GetVolumeWeight(chain.volume);
if (chain.volumeComponent.active)
return $"{scope} ({(weight * 100f):F2}%)";
else
return $"{scope} (disabled)";
},
refreshRate = 0.2f
});
((DebugUI.Table.Row)table.children[++iRowIndex]).children.Add(new DebugUI.ObjectField() { displayName = string.Empty, getter = () => chain.volume });
((DebugUI.Table.Row)table.children[++iRowIndex]).children.Add(new DebugUI.Value()
{
nameAndTooltip = chain.nameAndTooltip,
getter = () => chain.volume.priority
});
}
else
{
((DebugUI.Table.Row)table.children[++iRowIndex]).children.Add(new DebugUI.Value()
{
nameAndTooltip = chain.nameAndTooltip,
getter = () => string.Empty
});
((DebugUI.Table.Row)table.children[++iRowIndex]).children.Add(s_EmptyDebugUIValue);
((DebugUI.Table.Row)table.children[++iRowIndex]).children.Add(s_EmptyDebugUIValue);
}
((DebugUI.Table.Row)table.children[++iRowIndex]).children.Add(chain.volumeProfile != null ?
new DebugUI.ObjectField() { displayName = string.Empty, getter = () => chain.volumeProfile } :
s_EmptyDebugUIValue);
((DebugUI.Table.Row)table.children[++iRowIndex]).children.Add(s_EmptyDebugUIValue);
bool isResultParameter = i == 0;
for (int j = 0; j < chain.volumeComponent.parameterList.Length; ++j)
{
var parameter = chain.volumeComponent.parameterList[j];
((DebugUI.Table.Row)table.children[++iRowIndex]).children.Add(
CreateVolumeParameterWidget(chain.nameAndTooltip.name, isResultParameter, parameter));
}
}
}
private static void GenerateTableRows(DebugUI.Table table, List<VolumeParameterChain> resolutionChain)
{
table.children.Add(new DebugUI.Table.Row { displayName = Strings.volumeInfo });
table.children.Add(new DebugUI.Table.Row { displayName = Strings.gameObject });
table.children.Add(new DebugUI.Table.Row { displayName = Strings.priority });
table.children.Add(new DebugUI.Table.Row { displayName = Strings.volumeProfile });
table.children.Add(new DebugUI.Table.Row { displayName = string.Empty }); // Empty separator row
var results = resolutionChain[0].volumeComponent;
for (int i = 0; i < results.parameterList.Length; ++i)
{
var parameter = results.parameterList[i];
#if UNITY_ENABLE_CHECKS
string displayName = VolumeDebugData.GetVolumeParameterDebugId(parameter); // In the Editor or in the Debug or Checked managed code variant, just the debug id
#else
string displayName = i.ToString(); // Everywhere else, just a dummy id ( TODO: The Volume panel code should be stripped completely in the Instrumented and Release managed code variants )
#endif
table.children.Add(new DebugUI.Table.Row { displayName = displayName });
}
}
}
[DisplayInfo(name = k_PanelTitle, order = int.MaxValue)]
internal class SettingsPanel : DebugDisplaySettingsPanel<DebugDisplaySettingsVolume>
{
public override void Dispose()
{
base.Dispose();
data.GetVolumesList().ItemAdded -= OnVolumeInfluenceChanged;
data.GetVolumesList().ItemRemoved -= OnVolumeInfluenceChanged;
}
public SettingsPanel(DebugDisplaySettingsVolume data)
: base(data)
{
var cameraSelector = WidgetFactory.CreateCameraSelector(this, (_, __) => Refresh());
// Select first camera if none is selected
var availableCameras = cameraSelector.getObjects() as List<Camera>;
if (data.selectedCamera == null && availableCameras is { Count: > 0 })
data.selectedCamera = availableCameras[0];
AddWidget(cameraSelector);
var componentSelector = WidgetFactory.CreateComponentSelector(this, (_, __) => Refresh());
componentSelector.isHiddenCallback = () => data.selectedCamera == null;
AddWidget(componentSelector);
Func<bool> hiddenCallback = () => data.selectedCamera == null || data.selectedComponent <= 0;
AddWidget(new DebugUI.MessageBox()
{
displayName = Strings.cameraNeedsRendering,
style = DebugUI.MessageBox.Style.Warning,
isHiddenCallback = hiddenCallback,
});
m_VolumeTable = WidgetFactory.CreateVolumeTable(data);
AddWidget(m_VolumeTable);
data.GetVolumesList().ItemAdded += OnVolumeInfluenceChanged;
data.GetVolumesList().ItemRemoved += OnVolumeInfluenceChanged;
}
private void OnVolumeInfluenceChanged(ObservableList<Volume> sender, ListChangedEventArgs<Volume> e)
{
Refresh();
}
DebugUI.Table m_VolumeTable = null;
void Refresh()
{
var panel = DebugManager.instance.GetPanel(PanelName);
if (panel == null)
return;
if (m_Data.selectedComponent > 0 && m_Data.selectedCamera != null)
{
var volumeTable = WidgetFactory.CreateVolumeTable(m_Data);
m_VolumeTable.children.Clear();
foreach (var row in volumeTable.children)
{
m_VolumeTable.children.Add(row);
}
}
}
}
#region IDebugDisplaySettingsData
/// <summary>
/// Checks whether ANY of the debug settings are currently active.
/// </summary>
public bool AreAnySettingsActive => false; // Volume Debug Panel doesn't need to modify the renderer data, therefore this property returns false
/// <inheritdoc/>
public IDebugDisplaySettingsPanelDisposable CreatePanel()
{
return new SettingsPanel(this);
}
#endregion
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 987617381d0b4ad4fafa9f3ab3ae5fb4
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,353 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace UnityEngine.Rendering
{
/// <summary>
/// Base class for Rendering Debugger Display Stats.
/// Subclasses provide pipeline-specific lists of <see cref="ProfilingSampler"/> instances
/// and register the corresponding debug UI widgets.
/// </summary>
public abstract class DebugDisplayStats
{
List<ProfilingSampler> m_CoreProfilingSamplers = GetProfilingSamplersToDisplay(typeof(CoreProfilingSamplers));
// Accumulate values to avg over one second.
private class AccumulatedTiming
{
public float accumulatedValue = 0;
public float lastAverage = 0;
internal void UpdateLastAverage(int frameCount)
{
lastAverage = accumulatedValue / frameCount;
accumulatedValue = 0.0f;
}
}
private enum DebugProfilingType
{
CPU,
InlineCPU,
GPU
}
/// <summary>
/// Enable profiling recorders.
/// </summary>
public virtual void EnableProfilingRecorders()
{
AddAndEnableProfilingSamplers(m_CoreProfilingSamplers);
}
/// <summary>
/// Add Profiling Samplers to recorded list and enable them.
/// </summary>
/// <param name="samplers">List of profiling samplers.</param>
protected void AddAndEnableProfilingSamplers(List<ProfilingSampler> samplers)
{
foreach (var sampler in samplers)
{
if (sampler == null) continue;
m_RecordedSamplers.Add(sampler);
sampler.enableRecording = true;
}
}
/// <summary>
/// Disable all active profiling recorders.
/// </summary>
public virtual void DisableProfilingRecorders()
{
foreach (var sampler in m_RecordedSamplers)
sampler.enableRecording = false;
m_RecordedSamplers.Clear();
}
/// <summary>
/// Add display stats widgets to the list provided.
/// </summary>
/// <param name="list">List to add the widgets to.</param>
public virtual void RegisterDebugUI(List<DebugUI.Widget> list)
{
m_DebugFrameTiming.RegisterDebugUI(list);
var detailedStatsFoldout = new DebugUI.Foldout
{
displayName = "Detailed Stats",
opened = false,
children =
{
new DebugUI.BoolField
{
displayName = "Update every second with average",
getter = () => averageProfilerTimingsOverASecond,
setter = value => averageProfilerTimingsOverASecond = value
},
new DebugUI.BoolField
{
displayName = "Hide empty scopes",
tooltip = "Hide profiling scopes where elapsed time in each category is zero",
getter = () => hideEmptyScopes,
setter = value => hideEmptyScopes = value
}
}
};
detailedStatsFoldout.children.Add(BuildDetailedStatsList("Profiling Scopes", m_CoreProfilingSamplers));
list.Add(detailedStatsFoldout);
}
/// <summary>
/// Update the timing data displayed in Display Stats panel.
/// </summary>
public virtual void Update()
{
m_DebugFrameTiming.UpdateFrameTiming();
UpdateDetailedStats(m_RecordedSamplers);
}
/// <summary>
/// Collects all <c>public static readonly ProfilingSampler</c> fields from
/// <paramref name="markersType"/>, skipping any decorated with
/// <see cref="HideInDebugUIAttribute"/>.
/// </summary>
/// <param name="markersType">A static class containing ProfilingSampler fields
/// (e.g. <c>typeof(CoreProfilingSamplers)</c>).</param>
/// <returns>List of ProfilingSampler instances to display.</returns>
protected static List<ProfilingSampler> GetProfilingSamplersToDisplay(Type markersType)
{
var result = new List<ProfilingSampler>();
foreach (var field in markersType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (field.FieldType != typeof(ProfilingSampler))
continue;
if (field.GetCustomAttribute<HideInDebugUIAttribute>() != null)
continue;
if (field.GetValue(null) is ProfilingSampler sampler)
result.Add(sampler);
}
return result;
}
/// <summary>
/// Update the detailed stats.
/// </summary>
/// <param name="samplers">List of samplers to update.</param>
protected void UpdateDetailedStats(List<ProfilingSampler> samplers)
{
m_HiddenSamplers.Clear();
m_TimeSinceLastAvgValue += Time.unscaledDeltaTime;
m_AccumulatedFrames++;
bool needUpdatingAverages = m_TimeSinceLastAvgValue >= k_AccumulationTimeInSeconds;
UpdateListOfAveragedProfilerTimings(needUpdatingAverages, samplers);
if (needUpdatingAverages)
{
m_TimeSinceLastAvgValue = 0.0f;
m_AccumulatedFrames = 0;
}
}
private static readonly string[] k_DetailedStatsColumnLabels = {"CPU", "CPUInline", "GPU"};
private Dictionary<ProfilingSampler, AccumulatedTiming>[] m_AccumulatedTiming = { new(), new(), new() };
private float m_TimeSinceLastAvgValue = 0.0f;
private int m_AccumulatedFrames = 0;
private HashSet<ProfilingSampler> m_HiddenSamplers = new();
private const float k_AccumulationTimeInSeconds = 1.0f;
/// <summary> Whether to display timings averaged over a second instead of updating every frame. </summary>
protected bool averageProfilerTimingsOverASecond = false;
/// <summary> Whether to hide empty scopes from UI. </summary>
protected bool hideEmptyScopes = true;
/// <summary>
/// Frame Times measurements used for Display Stats.
/// </summary>
readonly DebugFrameTiming m_DebugFrameTiming = new();
/// <summary>
/// List of markers for Detailed stats.
/// </summary>
readonly List<ProfilingSampler> m_RecordedSamplers = new();
/// <summary>
/// Helper function to build a list of sampler widgets for display stats.
/// </summary>
/// <param name="title">Title for the stats list foldout.</param>
/// <param name="samplers">List of samplers to display.</param>
/// <returns>Foldout containing the list of sampler widgets.</returns>
protected DebugUI.Widget BuildDetailedStatsList(string title, List<ProfilingSampler> samplers)
{
var foldout = new DebugUI.Foldout(title, BuildProfilingSamplerWidgetList(samplers), k_DetailedStatsColumnLabels);
foldout.opened = true;
foldout.alternateRowColors = true;
return foldout;
}
private void UpdateListOfAveragedProfilerTimings(bool needUpdatingAverages, List<ProfilingSampler> samplers)
{
foreach (var sampler in samplers)
{
// Accumulate.
bool allValuesZero = true;
if (m_AccumulatedTiming[(int)DebugProfilingType.CPU].TryGetValue(sampler, out var accCPUTiming))
{
accCPUTiming.accumulatedValue += sampler.cpuElapsedTime;
allValuesZero &= accCPUTiming.accumulatedValue == 0;
}
if (m_AccumulatedTiming[(int)DebugProfilingType.InlineCPU].TryGetValue(sampler, out var accInlineCPUTiming))
{
accInlineCPUTiming.accumulatedValue += sampler.inlineCpuElapsedTime;
allValuesZero &= accInlineCPUTiming.accumulatedValue == 0;
}
if (m_AccumulatedTiming[(int)DebugProfilingType.GPU].TryGetValue(sampler, out var accGPUTiming))
{
accGPUTiming.accumulatedValue += sampler.gpuElapsedTime;
allValuesZero &= accGPUTiming.accumulatedValue == 0;
}
if (needUpdatingAverages)
{
accCPUTiming?.UpdateLastAverage(m_AccumulatedFrames);
accInlineCPUTiming?.UpdateLastAverage(m_AccumulatedFrames);
accGPUTiming?.UpdateLastAverage(m_AccumulatedFrames);
}
// Update visibility status based on whether each accumulated value of this scope is zero
if (allValuesZero)
m_HiddenSamplers.Add(sampler);
}
}
private float GetSamplerTiming(ProfilingSampler sampler, DebugProfilingType type)
{
if (averageProfilerTimingsOverASecond)
{
// Find the right accumulated dictionary
if (m_AccumulatedTiming[(int)type].TryGetValue(sampler, out AccumulatedTiming accTiming))
return accTiming.lastAverage;
}
return (type == DebugProfilingType.CPU)
? sampler.cpuElapsedTime
: ((type == DebugProfilingType.GPU) ? sampler.gpuElapsedTime : sampler.inlineCpuElapsedTime);
}
/// <summary>
/// Create an observable list of widgets from Profiling Samplers
/// </summary>
/// <param name="samplers">Profiling Sampler collection.</param>
/// <returns>An observable list of widgets.</returns>
protected ObservableList<DebugUI.Widget> BuildProfilingSamplerWidgetList(IEnumerable<ProfilingSampler> samplers)
{
var result = new ObservableList<DebugUI.Widget>();
DebugUI.Value CreateWidgetForSampler(ProfilingSampler sampler, DebugProfilingType type)
{
// Find the right accumulated dictionary and add it there if not existing yet.
var accumulatedDictionary = m_AccumulatedTiming[(int)type];
if (!accumulatedDictionary.ContainsKey(sampler))
{
accumulatedDictionary.Add(sampler, new AccumulatedTiming());
}
return new()
{
formatString = "{0:F2}ms",
refreshRate = 1.0f / 5.0f,
getter = () => GetSamplerTiming(sampler, type)
};
}
foreach (var sampler in samplers)
{
if (sampler == null) continue;
result.Add(new DebugUI.ValueTuple
{
displayName = sampler.name,
isHiddenCallback = () => hideEmptyScopes && m_HiddenSamplers.Contains(sampler),
values = Enum.GetValues(typeof(DebugProfilingType)).Cast<DebugProfilingType>()
.Select(e => CreateWidgetForSampler(sampler, e)).ToArray()
});
}
return result;
}
}
/// <summary>
/// Base class for Rendering Debugger Display Stats.
/// </summary>
/// <typeparam name="TProfileId">Type of ProfileId the pipeline uses</typeparam>
[Obsolete("Use the non-generic DebugDisplayStats base class with ProfilingSampler lists. #from(6000.6)")]
public abstract class DebugDisplayStats<TProfileId> : DebugDisplayStats where TProfileId : Enum
{
/// <summary>
/// Helper function to get all TProfilerId values of a given type to show in Detailed Stats section.
/// </summary>
/// <returns>List of TProfileId values excluding ones marked with [HideInDebugUI]</returns>
[Obsolete("Use GetProfilingSamplersToDisplay(Type) with a static marker class. #from(6000.6)")]
protected List<TProfileId> GetProfilerIdsToDisplay()
{
List<TProfileId> ids = new();
var type = typeof(TProfileId);
var enumValues = Enum.GetValues(type);
foreach (var enumValue in enumValues)
{
var memberInfos = type.GetMember(enumValue.ToString());
var enumValueMemberInfo = memberInfos.First(m => m.DeclaringType == type);
var hiddenAttribute = Attribute.GetCustomAttribute(enumValueMemberInfo, typeof(HideInDebugUIAttribute));
if (hiddenAttribute == null)
ids.Add((TProfileId)enumValue);
}
return ids;
}
/// <summary>
/// Update the detailed stats.
/// </summary>
/// <param name="samplers">List of enum profile IDs to update.</param>
[Obsolete("Use UpdateDetailedStats(List<ProfilingSampler>) instead. #from(6000.6)")]
protected void UpdateDetailedStats(List<TProfileId> samplers)
{
UpdateDetailedStats(ConvertToSamplers(samplers));
}
/// <summary>
/// Helper function to build a list of sampler widgets for display stats.
/// </summary>
/// <param name="title">Title for the stats list foldout.</param>
/// <param name="samplers">List of enum profile IDs to display.</param>
/// <returns>Foldout containing the list of sampler widgets.</returns>
[Obsolete("Use BuildDetailedStatsList(string, List<ProfilingSampler>) instead. #from(6000.6)")]
protected DebugUI.Widget BuildDetailedStatsList(string title, List<TProfileId> samplers)
{
return BuildDetailedStatsList(title, ConvertToSamplers(samplers));
}
static List<ProfilingSampler> ConvertToSamplers(List<TProfileId> ids)
{
var samplers = new List<ProfilingSampler>(ids.Count);
foreach (var id in ids)
{
var sampler = ProfilingSampler.Get(id);
if (sampler != null)
samplers.Add(sampler);
}
return samplers;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: e817ef0dd5474269a43c074c595854d6
timeCreated: 1661411588
@@ -0,0 +1,214 @@
//#define RTPROFILER_DEBUG
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UnityEngine.Rendering
{
/// <summary>
/// Debug frame timings class
/// </summary>
public class DebugFrameTiming
{
const string k_FpsFormatString = "{0:F1}";
const string k_MsFormatString = "{0:F2}ms";
const float k_RefreshRate = 1f / 5f;
internal FrameTimeSampleHistory m_FrameHistory;
internal BottleneckHistory m_BottleneckHistory;
/// <summary>
/// Size of the Bottleneck History Window in number of samples.
/// </summary>
public int bottleneckHistorySize { get; set; } = 60;
/// <summary>
/// Size of the Sample History Window in number of samples.
/// </summary>
public int sampleHistorySize { get; set; } = 30;
FrameTiming[] m_Timing = new FrameTiming[1];
FrameTimeSample m_Sample = new FrameTimeSample();
/// <summary>
/// Constructs the debug frame timing
/// </summary>
public DebugFrameTiming()
{
m_FrameHistory = new FrameTimeSampleHistory(sampleHistorySize);
m_BottleneckHistory = new BottleneckHistory(bottleneckHistorySize);
}
/// <summary>
/// Update timing data from profiling counters.
/// </summary>
public void UpdateFrameTiming()
{
m_Timing[0] = default;
m_Sample = default;
FrameTimingManager.CaptureFrameTimings();
FrameTimingManager.GetLatestTimings(1, m_Timing);
if (m_Timing.Length > 0)
{
m_Sample.FullFrameTime = (float)m_Timing.First().cpuFrameTime;
m_Sample.FramesPerSecond = m_Sample.FullFrameTime > 0f ? 1000f / m_Sample.FullFrameTime : 0f;
m_Sample.MainThreadCPUFrameTime = (float)m_Timing.First().cpuMainThreadFrameTime;
m_Sample.MainThreadCPUPresentWaitTime = (float)m_Timing.First().cpuMainThreadPresentWaitTime;
m_Sample.RenderThreadCPUFrameTime = (float)m_Timing.First().cpuRenderThreadFrameTime;
m_Sample.GPUFrameTime = (float)m_Timing.First().gpuFrameTime;
}
m_FrameHistory.DiscardOldSamples(sampleHistorySize);
m_FrameHistory.Add(m_Sample);
m_FrameHistory.ComputeAggregateValues();
m_BottleneckHistory.DiscardOldSamples(bottleneckHistorySize);
m_BottleneckHistory.AddBottleneckFromAveragedSample(m_FrameHistory.SampleAverage);
m_BottleneckHistory.ComputeHistogram();
}
/// <summary>
/// Add frame timing data widgets to debug UI.
/// </summary>
/// <param name="list">List of widgets to add the stats.</param>
public void RegisterDebugUI(List<DebugUI.Widget> list)
{
list.Add(new DebugUI.Foldout()
{
displayName = "Frame Stats",
opened = true,
columnLabels = new string[] { "Avg", "Min", "Max" },
alternateRowColors = true,
children =
{
new DebugUI.ValueTuple
{
displayName = "Frame Rate (FPS)",
values = new[]
{
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FpsFormatString, getter = () => m_FrameHistory.SampleAverage.FramesPerSecond },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FpsFormatString, getter = () => m_FrameHistory.SampleMin.FramesPerSecond },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_FpsFormatString, getter = () => m_FrameHistory.SampleMax.FramesPerSecond },
}
},
new DebugUI.ValueTuple
{
displayName = "Frame Time",
values = new[]
{
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleAverage.FullFrameTime },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleMin.FullFrameTime },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleMax.FullFrameTime },
}
},
new DebugUI.ValueTuple
{
displayName = "CPU Main Thread Frame",
values = new[]
{
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleAverage.MainThreadCPUFrameTime },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleMin.MainThreadCPUFrameTime },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleMax.MainThreadCPUFrameTime },
}
},
new DebugUI.ValueTuple
{
displayName = "CPU Render Thread Frame",
values = new[]
{
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleAverage.RenderThreadCPUFrameTime },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleMin.RenderThreadCPUFrameTime },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleMax.RenderThreadCPUFrameTime },
}
},
new DebugUI.ValueTuple
{
displayName = "CPU Present Wait",
values = new[]
{
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleAverage.MainThreadCPUPresentWaitTime },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleMin.MainThreadCPUPresentWaitTime },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleMax.MainThreadCPUPresentWaitTime },
}
},
new DebugUI.ValueTuple
{
displayName = "GPU Frame",
values = new[]
{
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleAverage.GPUFrameTime },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleMin.GPUFrameTime },
new DebugUI.Value { refreshRate = k_RefreshRate, formatString = k_MsFormatString, getter = () => m_FrameHistory.SampleMax.GPUFrameTime },
}
}
}
});
list.Add(new DebugUI.Foldout
{
displayName = "Bottlenecks",
children =
{
#if UNITY_EDITOR
new DebugUI.Container { displayName = "Not supported in Editor" }
#else
new DebugUI.ProgressBarValue { displayName = "CPU", getter = () => m_BottleneckHistory.Histogram.CPU },
new DebugUI.ProgressBarValue { displayName = "GPU", getter = () => m_BottleneckHistory.Histogram.GPU },
new DebugUI.ProgressBarValue { displayName = "Present limited", getter = () => m_BottleneckHistory.Histogram.PresentLimited },
new DebugUI.ProgressBarValue { displayName = "Balanced", getter = () => m_BottleneckHistory.Histogram.Balanced },
#endif
}
});
#if RTPROFILER_DEBUG
list.Add(new DebugUI.Foldout
{
displayName = "Realtime Profiler Debug",
children =
{
new DebugUI.IntField
{
displayName = "Frame Time Sample History Size",
getter = () => sampleHistorySize,
setter = (value) => { sampleHistorySize = value; },
min = () => 1,
max = () => 100
},
new DebugUI.IntField
{
displayName = "Bottleneck History Size",
getter = () => bottleneckHistorySize,
setter = (value) => { bottleneckHistorySize = value; },
min = () => 1,
max = () => 100
},
new DebugUI.IntField
{
displayName = "Force VSyncCount",
min = () => - 1,
max = () => 4,
getter = () => QualitySettings.vSyncCount,
setter = (value) => { QualitySettings.vSyncCount = value; }
},
new DebugUI.IntField
{
displayName = "Force TargetFrameRate",
min = () => - 1,
max = () => 1000,
getter = () => Application.targetFrameRate,
setter = (value) => { Application.targetFrameRate = value; }
},
}
});
#endif
}
internal void Reset()
{
m_BottleneckHistory.Clear();
m_FrameHistory.Clear();
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 5b966c0b6fb41a743ad89f19c17430eb
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,117 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
#if ENABLE_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM_PACKAGE
#define USE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif
// Input support for Rendering Debugger using Input System Package
namespace UnityEngine.Rendering
{
public sealed partial class DebugManager
{
const string k_EnableDebug = "Enable Debug";
const string k_ResetBtn = "Debug Reset";
const string k_DebugPreviousBtn = "Debug Previous";
const string k_DebugNextBtn = "Debug Next";
const string k_PersistentBtn = "Debug Persistent";
const string k_DPadHorizontal = "Debug Horizontal";
const string k_MultiplierBtn = "Debug Multiplier";
#if USE_INPUT_SYSTEM
const string k_AnyTouch = "Any Touch";
readonly InputActionMap m_DebugMenuEnableActions = new InputActionMap("Debug Menu Enable Actions");
readonly InputActionMap m_DebugMenuActions = new InputActionMap("Debug Menu Actions");
InputAction m_MultiplierAction;
internal void EnableInputCallbacks()
{
m_DebugMenuEnableActions.Enable();
}
internal void DisableInputCallbacks()
{
m_DebugMenuEnableActions.Disable();
}
void ToggleRuntimeUI() => displayRuntimeUI = !displayRuntimeUI;
void RegisterDebugInputs()
{
var enableAction = m_DebugMenuEnableActions.AddAction(k_EnableDebug, type: InputActionType.Button);
enableAction.AddCompositeBinding("ButtonWithOneModifier")
.With("Modifier", "<Gamepad>/rightStickPress")
.With("Button", "<Gamepad>/leftStickPress")
.With("Modifier", "<Keyboard>/leftCtrl")
.With("Button", "<Keyboard>/backspace");
enableAction.performed += _ => ToggleRuntimeUI();
var anyTouchAction = m_DebugMenuEnableActions.AddAction(k_AnyTouch, type: InputActionType.Button);
anyTouchAction.AddBinding("<Touchscreen>/touch2/tap"); // touch2 means "third finger"
anyTouchAction.performed += ctx =>
{
// We want a three-finger double-tap to toggle the debug UI. However, it's a bit tricky to perform a
// three-finger tap consistently. Therefore, to be slightly error-tolerant, we actually check for a
// "double-tap action on the third tracked finger".
var pressControl = ctx.control as InputSystem.Controls.ButtonControl;
var touchControl = pressControl?.parent as InputSystem.Controls.TouchControl;
int tapCount = touchControl?.tapCount?.ReadValue() ?? 0;
if (tapCount == 2)
ToggleRuntimeUI();
};
#if ENABLE_RENDERING_DEBUGGER_UI
var resetAction = m_DebugMenuActions.AddAction(k_ResetBtn, type: InputActionType.Button);
resetAction.AddCompositeBinding("ButtonWithOneModifier")
.With("Modifier", "<Gamepad>/rightStickPress")
.With("Button", "<Gamepad>/b")
.With("Modifier", "<Keyboard>/leftAlt")
.With("Button", "<Keyboard>/backspace");
resetAction.performed += _ => { Reset(); };
var next = m_DebugMenuActions.AddAction(k_DebugNextBtn, type: InputActionType.Button);
next.AddBinding("<Keyboard>/pageDown");
next.AddBinding("<Gamepad>/rightShoulder");
next.performed += _ => { m_RuntimeDebugWindow.SelectNextPanel(); };
var previous = m_DebugMenuActions.AddAction(k_DebugPreviousBtn, type: InputActionType.Button);
previous.AddBinding("<Keyboard>/pageUp");
previous.AddBinding("<Gamepad>/leftShoulder");
previous.performed += _ => { m_RuntimeDebugWindow.SelectPreviousPanel(); };
var persistentAction = m_DebugMenuActions.AddAction(k_PersistentBtn, type: InputActionType.Button);
persistentAction.AddBinding("<Keyboard>/rightShift");
persistentAction.AddBinding("<Gamepad>/x");
persistentAction.performed += _ => { TogglePersistent(); };
m_MultiplierAction = m_DebugMenuActions.AddAction(k_MultiplierBtn, type: InputActionType.Value);
m_MultiplierAction.AddBinding("<Keyboard>/leftShift");
m_MultiplierAction.AddBinding("<Gamepad>/y");
var moveHorizontalAction = m_DebugMenuActions.AddAction(k_DPadHorizontal);
moveHorizontalAction.AddCompositeBinding("1DAxis")
.With("Positive", "<Gamepad>/dpad/right")
.With("Negative", "<Gamepad>/dpad/left")
.With("Positive", "<Keyboard>/rightArrow")
.With("Negative", "<Keyboard>/leftArrow");
moveHorizontalAction.performed += ctx =>
{
bool multiplierPressed = m_MultiplierAction.IsPressed();
bool increment = ctx.ReadValue<float>() > 0.0f;
if (increment)
{
selectedWidget?.OnIncrement(multiplierPressed);
}
else
{
selectedWidget?.OnDecrement(multiplierPressed);
}
};
#endif
}
#endif
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d2aa9a8abb8f4355a8a8d4cae3e1f907
timeCreated: 1765195846
@@ -0,0 +1,339 @@
#if ENABLE_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM_PACKAGE
#define USE_INPUT_SYSTEM
#endif
// Input support for Rendering Debugger using legacy InputManager
#if !USE_INPUT_SYSTEM
using System;
using System.Collections.Generic;
namespace UnityEngine.Rendering
{
internal enum DebugAction
{
EnableDebugMenu,
PreviousDebugPanel,
NextDebugPanel,
MakePersistent,
MoveHorizontal,
Multiplier,
ResetAll,
DebugActionCount
}
enum DebugActionRepeatMode
{
Never,
Delay
}
public sealed partial class DebugManager
{
const string k_EnableDebugBtn1 = "Enable Debug Button 1";
const string k_EnableDebugBtn2 = "Enable Debug Button 2";
DebugActionDesc[] m_DebugActions;
DebugActionState[] m_DebugActionStates;
void RegisterActions()
{
m_DebugActions = new DebugActionDesc[(int)DebugAction.DebugActionCount];
m_DebugActionStates = new DebugActionState[(int)DebugAction.DebugActionCount];
var enableDebugMenu = new DebugActionDesc();
enableDebugMenu.buttonTriggerList.Add(new[] { k_EnableDebugBtn1, k_EnableDebugBtn2 });
enableDebugMenu.keyTriggerList.Add(new[] { KeyCode.LeftControl, KeyCode.Backspace });
enableDebugMenu.repeatMode = DebugActionRepeatMode.Never;
AddAction(DebugAction.EnableDebugMenu, enableDebugMenu);
var resetDebugMenu = new DebugActionDesc();
resetDebugMenu.keyTriggerList.Add(new[] { KeyCode.LeftAlt, KeyCode.Backspace });
resetDebugMenu.buttonTriggerList.Add(new[] { k_ResetBtn, k_EnableDebugBtn2 });
resetDebugMenu.repeatMode = DebugActionRepeatMode.Never;
AddAction(DebugAction.ResetAll, resetDebugMenu);
var nextDebugPanel = new DebugActionDesc();
nextDebugPanel.buttonTriggerList.Add(new[] { k_DebugNextBtn });
nextDebugPanel.repeatMode = DebugActionRepeatMode.Never;
AddAction(DebugAction.NextDebugPanel, nextDebugPanel);
var previousDebugPanel = new DebugActionDesc();
previousDebugPanel.buttonTriggerList.Add(new[] { k_DebugPreviousBtn });
previousDebugPanel.repeatMode = DebugActionRepeatMode.Never;
AddAction(DebugAction.PreviousDebugPanel, previousDebugPanel);
var persistent = new DebugActionDesc();
persistent.buttonTriggerList.Add(new[] { k_PersistentBtn });
persistent.repeatMode = DebugActionRepeatMode.Never;
AddAction(DebugAction.MakePersistent, persistent);
var multiplier = new DebugActionDesc();
multiplier.buttonTriggerList.Add(new[] { k_MultiplierBtn });
multiplier.repeatMode = DebugActionRepeatMode.Delay;
multiplier.repeatDelay = 0f;
AddAction(DebugAction.Multiplier, multiplier);
var moveHorizontal = new DebugActionDesc();
moveHorizontal.axisTrigger = k_DPadHorizontal;
moveHorizontal.repeatMode = DebugActionRepeatMode.Delay;
moveHorizontal.repeatDelay = 0.16f;
AddAction(DebugAction.MoveHorizontal, moveHorizontal);
}
void AddAction(DebugAction action, DebugActionDesc desc)
{
int index = (int)action;
m_DebugActions[index] = desc;
m_DebugActionStates[index] = new DebugActionState();
}
void SampleAction(int actionIndex)
{
var desc = m_DebugActions[actionIndex];
var state = m_DebugActionStates[actionIndex];
#if ENABLE_LEGACY_INPUT_MANAGER
if (state.runningAction == false)
{
// Check button triggers
for (int buttonListIndex = 0; buttonListIndex < desc.buttonTriggerList.Count; ++buttonListIndex)
{
var buttons = desc.buttonTriggerList[buttonListIndex];
bool allButtonPressed = true;
try
{
foreach (var button in buttons)
{
allButtonPressed = Input.GetButton(button);
if (!allButtonPressed)
break;
}
}
catch (ArgumentException)
{
// Exception thrown if the input mapping gets removed while in play mode (UUM-37148)
allButtonPressed = false;
}
if (allButtonPressed)
{
state.TriggerWithButton(buttons, 1f);
break;
}
}
// Check axis triggers
if (desc.axisTrigger != "")
{
try
{
float axisValue = Input.GetAxis(desc.axisTrigger);
if (axisValue != 0f)
state.TriggerWithAxis(desc.axisTrigger, axisValue);
}
catch (ArgumentException)
{
// Exception thrown if the input mapping gets removed while in play mode (UUM-37148)
}
}
// Check key triggers
for (int keyListIndex = 0; keyListIndex < desc.keyTriggerList.Count; ++keyListIndex)
{
bool allKeyPressed = true;
var keys = desc.keyTriggerList[keyListIndex];
try
{
foreach (var key in keys)
{
allKeyPressed = Input.GetKey(key);
if (!allKeyPressed)
break;
}
}
catch (ArgumentException)
{
// Exception thrown if the input mapping gets removed while in play mode (UUM-37148)
allKeyPressed = false;
}
if (allKeyPressed)
{
state.TriggerWithKey(keys, 1f);
break;
}
}
}
#endif
}
void UpdateAction(int actionIndex)
{
var desc = m_DebugActions[actionIndex];
var state = m_DebugActionStates[actionIndex];
if (state.runningAction)
state.Update(desc);
}
internal void UpdateActions()
{
for (int actionIndex = 0; actionIndex < m_DebugActions.Length; ++actionIndex)
{
UpdateAction(actionIndex);
SampleAction(actionIndex);
}
}
internal float GetAction(DebugAction action)
{
return m_DebugActionStates[(int)action].actionState;
}
internal bool GetActionToggleDebugMenuWithTouch()
{
var touchCount = Input.touchCount;
TouchPhase expectedTouchPhase = TouchPhase.Began;
if (touchCount == 3)
{
var touches = Input.touches; // Note: Causes an allocation
foreach (var touch in touches)
{
// Gesture: 3-finger double-tap
if (touch.phase == expectedTouchPhase && touch.tapCount == 2)
return true;
}
}
return false;
}
void RegisterDebugInputs()
{
#if UNITY_EDITOR
#pragma warning disable CS0618 // Type or member is obsolete
var inputEntries = new List<InputManagerEntry>
{
new InputManagerEntry { name = k_EnableDebugBtn1, kind = InputManagerEntry.Kind.KeyOrButton, btnPositive = "left ctrl", altBtnPositive = "joystick button 8" },
new InputManagerEntry { name = k_EnableDebugBtn2, kind = InputManagerEntry.Kind.KeyOrButton, btnPositive = "backspace", altBtnPositive = "joystick button 9" },
new InputManagerEntry { name = k_ResetBtn, kind = InputManagerEntry.Kind.KeyOrButton, btnPositive = "left alt", altBtnPositive = "joystick button 1" },
new InputManagerEntry { name = k_DebugNextBtn, kind = InputManagerEntry.Kind.KeyOrButton, btnPositive = "page down", altBtnPositive = "joystick button 5" },
new InputManagerEntry { name = k_DebugPreviousBtn, kind = InputManagerEntry.Kind.KeyOrButton, btnPositive = "page up", altBtnPositive = "joystick button 4" },
new InputManagerEntry { name = k_PersistentBtn, kind = InputManagerEntry.Kind.KeyOrButton, btnPositive = "right shift", altBtnPositive = "joystick button 2" },
new InputManagerEntry { name = k_MultiplierBtn, kind = InputManagerEntry.Kind.KeyOrButton, btnPositive = "left shift", altBtnPositive = "joystick button 3" },
new InputManagerEntry { name = k_DPadHorizontal, kind = InputManagerEntry.Kind.KeyOrButton, btnPositive = "right", btnNegative = "left", gravity = 1000f, deadZone = 0.001f, sensitivity = 1000f },
new InputManagerEntry { name = k_DPadHorizontal, kind = InputManagerEntry.Kind.Axis, axis = InputManagerEntry.Axis.Sixth, btnPositive = "right", btnNegative = "left", gravity = 1000f, deadZone = 0.001f, sensitivity = 1000f },
};
InputRegistering.RegisterInputs(inputEntries);
#pragma warning restore CS0618 // Type or member is obsolete
#endif
RegisterActions();
}
}
class DebugActionDesc
{
public string axisTrigger = "";
public List<string[]> buttonTriggerList = new List<string[]>();
public List<KeyCode[]> keyTriggerList = new List<KeyCode[]>();
public DebugActionRepeatMode repeatMode = DebugActionRepeatMode.Never;
public float repeatDelay;
}
class DebugActionState
{
enum DebugActionKeyType
{
Button,
Axis,
Key
}
DebugActionKeyType m_Type;
string[] m_PressedButtons;
string m_PressedAxis = "";
KeyCode[] m_PressedKeys;
bool[] m_TriggerPressedUp;
float m_Timer;
internal bool runningAction { get; private set; }
internal float actionState { get; private set; }
void Trigger(int triggerCount, float state)
{
actionState = state;
runningAction = true;
m_Timer = 0f;
m_TriggerPressedUp = new bool[triggerCount];
for (int i = 0; i < m_TriggerPressedUp.Length; ++i)
m_TriggerPressedUp[i] = false;
}
public void TriggerWithButton(string[] buttons, float state)
{
m_Type = DebugActionKeyType.Button;
m_PressedButtons = buttons;
m_PressedAxis = "";
Trigger(buttons.Length, state);
}
public void TriggerWithAxis(string axis, float state)
{
m_Type = DebugActionKeyType.Axis;
m_PressedAxis = axis;
Trigger(1, state);
}
public void TriggerWithKey(KeyCode[] keys, float state)
{
m_Type = DebugActionKeyType.Key;
m_PressedKeys = keys;
m_PressedAxis = "";
Trigger(keys.Length, state);
}
void Reset()
{
runningAction = false;
m_Timer = 0f;
m_TriggerPressedUp = null;
}
public void Update(DebugActionDesc desc)
{
// Always reset this so that the action can only be caught once until repeat/reset
actionState = 0f;
if (m_TriggerPressedUp != null)
{
m_Timer += Time.deltaTime;
for (int i = 0; i < m_TriggerPressedUp.Length; ++i)
{
if (m_Type == DebugActionKeyType.Button)
m_TriggerPressedUp[i] |= Input.GetButtonUp(m_PressedButtons[i]);
else if (m_Type == DebugActionKeyType.Axis)
m_TriggerPressedUp[i] |= Mathf.Approximately(Input.GetAxis(m_PressedAxis), 0f);
else
m_TriggerPressedUp[i] |= Input.GetKeyUp(m_PressedKeys[i]);
}
bool allTriggerUp = true;
foreach (bool value in m_TriggerPressedUp)
allTriggerUp &= value;
if (allTriggerUp || (m_Timer > desc.repeatDelay && desc.repeatMode == DebugActionRepeatMode.Delay))
Reset();
}
}
}
}
#endif
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b9ea0a15a47dead4ebc52bd3f7a926c1
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,121 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
#if ENABLE_RENDERING_DEBUGGER_UI
using System.Collections.Generic;
using UnityEngine.UIElements;
namespace UnityEngine.Rendering
{
using ScheduledItemsDictionary = Dictionary<DebugUI.Widget, List<IVisualElementScheduledItem>>;
public sealed partial class DebugManager
{
// This class keeps track of all VisualElementScheduledItems created by DebugUI widgets so they can be paused when the content is not visible,
// and resumed when it becomes visible again. This greatly speeds up the UI because we don't process schedulers in inactive panels and closed foldouts.
internal class SchedulerTracker
{
readonly ScheduledItemsDictionary[] m_ScheduledItems;
public SchedulerTracker()
{
int numDictionaries = (int)DebugUI.Context.Count;
m_ScheduledItems = new ScheduledItemsDictionary[numDictionaries];
for (int i = 0; i < numDictionaries; i++)
m_ScheduledItems[i] = new ScheduledItemsDictionary();
}
internal ScheduledItemsDictionary GetScheduledItemsDictionary(DebugUI.Context context) => m_ScheduledItems[(int)context];
public void SetEnabled(DebugUI.Context context, DebugUI.Widget widget, bool enabled)
{
var dict = GetScheduledItemsDictionary(context);
if (dict.TryGetValue(widget, out var scheduledItems))
{
foreach (var scheduledItem in scheduledItems)
{
if (enabled)
scheduledItem.Resume();
else
scheduledItem.Pause();
}
}
}
// Any time a widget constructs internal widgets (like containers, tuples, history fields), those widgets need to be handled
// here to ensure their schedulers are enabled/disabled when needed.
void UpdateSchedulersRecursive(DebugUI.Context context, DebugUI.IContainer container, bool enabled)
{
foreach (var child in container.children)
{
SetEnabled(context, child, enabled);
if (child is DebugUI.IContainer childContainer)
{
bool childContainerEnabled = enabled;
if (child is DebugUI.Foldout childFoldout)
childContainerEnabled = enabled && childFoldout.opened;
UpdateSchedulersRecursive(context, childContainer, childContainerEnabled);
}
if (child is DebugUI.ValueTuple childTuple)
{
foreach (var value in childTuple.values)
SetEnabled(context, value, enabled);
}
if (child is DebugUI.HistoryBoolField childHistoryBoolField)
{
foreach (var value in childHistoryBoolField.childWidgets)
SetEnabled(context, value, enabled);
}
if (child is DebugUI.HistoryEnumField childHistoryEnumField)
{
foreach (var value in childHistoryEnumField.childWidgets)
SetEnabled(context, value, enabled);
}
}
}
public void SetHierarchyEnabled(DebugUI.Context context, DebugUI.IContainer container, bool enabled)
{
UpdateSchedulersRecursive(context, container, enabled);
}
public void Add(DebugUI.Context context, DebugUI.Widget widget, IVisualElementScheduledItem scheduledItem)
{
var dict = GetScheduledItemsDictionary(context);
if (!dict.TryGetValue(widget, out var widgetScheduledItemList))
{
widgetScheduledItemList = new List<IVisualElementScheduledItem>();
dict.Add(widget, widgetScheduledItemList);
}
widgetScheduledItemList.Add(scheduledItem);
}
public void Remove(DebugUI.Context context, DebugUI.Widget widget, VisualElement removedVisualElement)
{
var dict = GetScheduledItemsDictionary(context);
if (dict.TryGetValue(widget, out var widgetScheduledItemList))
{
for (int i = widgetScheduledItemList.Count - 1; i >= 0; i--)
{
var scheduledItem = widgetScheduledItemList[i];
if (scheduledItem.element == removedVisualElement)
{
scheduledItem.Pause();
widgetScheduledItemList.RemoveAt(i);
}
}
if (widgetScheduledItemList.Count == 0)
dict.Remove(widget);
}
}
}
}
}
#endif
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 3a99bcf1786a473e87ec8fb420401e52
timeCreated: 1758007291
@@ -0,0 +1,170 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
#if ENABLE_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM_PACKAGE
#define USE_INPUT_SYSTEM
#endif
using System;
namespace UnityEngine.Rendering
{
public sealed partial class DebugManager
{
/// <summary>
/// The modes of the UI of the Rendering Debugger
/// </summary>
public enum UIMode : int
{
/// <summary>
/// Editor Window
/// </summary>
EditorMode,
/// <summary>
/// In Game view
/// </summary>
RuntimeMode
}
/// <summary>
/// Event that is raised when a window state is changed
/// </summary>
public static event Action<UIMode, bool> windowStateChanged;
class UIState
{
public UIMode mode;
bool m_Open;
public bool open
{
get => m_Open;
set
{
if (m_Open == value)
return;
m_Open = value;
windowStateChanged?.Invoke(mode, m_Open);
}
}
}
readonly UIState m_EditorUIState = new UIState() { mode = UIMode.EditorMode };
/// <summary>
/// Is the debug editor window open.
/// </summary>
public bool displayEditorUI
{
get => m_EditorUIState.open;
set => m_EditorUIState.open = value;
}
bool m_EnableRuntimeUI = true;
/// <summary>
/// Controls whether runtime UI can be enabled. When this is set to false, there will be no overhead
/// from debug GameObjects or runtime initialization.
/// </summary>
public bool enableRuntimeUI
{
get => m_EnableRuntimeUI;
set
{
if (value != m_EnableRuntimeUI)
{
m_EnableRuntimeUI = value;
DebugUpdater.SetEnabled(value);
}
}
}
readonly UIState m_RuntimeUIState = new UIState() { mode = UIMode.RuntimeMode };
/// <summary>
/// Displays the runtime version of the debug window.
/// </summary>
public bool displayRuntimeUI
{
#if ENABLE_RENDERING_DEBUGGER_UI
get => m_RuntimeDebugWindow != null && m_RuntimeDebugWindow.gameObject.activeInHierarchy;
set
{
if (value)
{
if (m_RuntimeDebugWindow == null && GraphicsSettings.TryGetRenderPipelineSettings<RenderingDebuggerRuntimeResources>(out _))
{
var go = new GameObject("[Debug UI]");
m_RuntimeDebugWindow = go.AddComponent<RuntimeDebugWindow>();
go.SetActive(true);
}
#if USE_INPUT_SYSTEM
m_DebugMenuActions.Enable();
#endif
}
else
{
if (m_RuntimeDebugWindow != null)
{
CoreUtils.Destroy(m_RuntimeDebugWindow.gameObject);
m_RuntimeDebugWindow = null;
}
#if USE_INPUT_SYSTEM
m_DebugMenuActions.Disable();
#endif
}
onDisplayRuntimeUIChanged(value);
m_RuntimeUIState.open = m_RuntimeDebugWindow != null && m_RuntimeDebugWindow.gameObject.activeInHierarchy;
}
#else
get => false;
set
{
if (value)
throw new NotSupportedException("Rendering Debugger Runtime UI requires the UIElements module.");
}
#endif
}
/// <summary>
/// Displays the persistent runtime debug window.
/// </summary>
public bool displayPersistentRuntimeUI
{
#if ENABLE_RENDERING_DEBUGGER_UI
get => m_RuntimePersistentDebugUI != null && m_RuntimePersistentDebugUI.gameObject.activeInHierarchy;
set
{
if (value)
{
if (m_RuntimePersistentDebugUI == null && GraphicsSettings.TryGetRenderPipelineSettings<RenderingDebuggerRuntimeResources>(out _))
{
var go = new GameObject("[Persistent Debug UI]");
m_RuntimePersistentDebugUI = go.AddComponent<RuntimePersistentDebugUI>();
go.SetActive(true);
}
}
else
{
CoreUtils.Destroy(m_RuntimePersistentDebugUI?.gameObject);
m_RuntimePersistentDebugUI = null;
}
}
#else
get => false;
set
{
if (value)
throw new NotSupportedException("Rendering Debugger Runtime UI requires the UIElements module.");
}
#endif
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 77aa0fe63e0ce9b428385908d4cd2663
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,491 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics.CodeAnalysis;
namespace UnityEngine.Rendering
{
/// <summary>
/// Implementing this interface enables integration with Unity's Rendering debugger, providing a way to manage and control the state of debug data.
/// </summary>
///
/// <remarks>
/// Use the `IDebugData` interface to register custom debug data. You can reset the data when necessary, which makes it suitable for debugging scenarios
/// where you need to clear or reset specific data. For example, when the application state changes or during gameplay session resets,
/// or when the **Reset** button is selected in the **Rendering Debugger** window in the Editor or at runtime.
/// </remarks>
///
/// <example>
/// <code>
/// public class MyDebugData : IDebugData
/// {
/// private int _value;
///
/// /// Constructor of the debug data that will receive the reset callback
/// public MyDebugData()
/// {
/// _value = 0;
/// }
///
/// public Action GetReset()
/// {
/// /// Specify the callback when the reset operation is being called.
/// return () => _value = 0; // Resets the value to 0
/// }
/// }
/// </code>
/// </example>
public interface IDebugData
{
/// <summary>Provides the reset callback for resetting the debug data.</summary>
/// <returns>The reset callback</returns>
Action GetReset();
}
/// <summary>
/// The <see cref="DebugManager"/> class provides a centralized manager for handling Unity's Rendering debugger.
/// </summary>
/// <remarks>
/// The DebugManager allows you to register, unregister, and manipulate debug data, panels, and widgets for runtime or editor debugging.
/// - Register and manage debug panels and widgets.
/// - Refresh and reset the debug UI based on runtime changes.
/// - Provides a global instance for easy access from anywhere in the codebase.
/// </remarks>
///
/// <example>
/// <code>
/// {
/// /// Create a list to store the new DebugUI widgets
/// /// by creating different DebugUI.Values that display a label with a value.
/// var list = new System.Collections.Generic.List&lt;DebugUI.Widget&gt;
/// {
/// new DebugUI.Value { displayName = "Lighting Intensity", getter = () => 1.0f, setter = value => Debug.Log($"Lighting Intensity set to {value}") },
/// new DebugUI.Value { displayName = "Light Color", getter = () => Color.white, setter = value => Debug.Log($"Light Color set to {value}") }
/// };
/// var items = list.ToArray();
///
/// /// Obtain the panel from the DebugManager instance, and add the Widgets that we want to display there.
/// var panel = DebugManager.instance.GetPanel("Lighting", true);
/// panel.children.AddRange(items);
/// }
/// </code>
/// </example>
public sealed partial class DebugManager
{
static readonly Lazy<DebugManager> s_Instance = new Lazy<DebugManager>(() => new DebugManager());
/// <summary>
/// Global instance of the DebugManager.
/// </summary>
public static DebugManager instance => s_Instance.Value;
ReadOnlyCollection<DebugUI.Panel> m_ReadOnlyPanels;
readonly List<DebugUI.Panel> m_Panels = new List<DebugUI.Panel>();
void UpdateReadOnlyCollection()
{
m_Panels.Sort();
m_ReadOnlyPanels = m_Panels.AsReadOnly();
}
/// <summary>
/// List of currently registered debug panels.
/// </summary>
public ReadOnlyCollection<DebugUI.Panel> panels
{
get
{
if (m_ReadOnlyPanels == null)
UpdateReadOnlyCollection();
return m_ReadOnlyPanels;
}
}
void ForEachWidgetInContainer(DebugUI.Widget widget, Action<DebugUI.Widget> action)
{
action(widget);
if (widget is DebugUI.IContainer container)
{
foreach (var child in container.children)
ForEachWidgetInContainer(child, action);
}
}
/// <summary>
/// Iterate over all widgets in all panels and invoke the provided action on each widget.
/// </summary>
/// <param name="action">Action to invoke.</param>
internal void ForEachWidget(Action<DebugUI.Widget> action)
{
foreach (var panel in m_Panels)
foreach (var widget in panel.children)
ForEachWidgetInContainer(widget, action);
}
/// <summary>
/// Callback called when the runtime UI changed.
/// </summary>
public event Action<bool> onDisplayRuntimeUIChanged = delegate { };
/// <summary>
/// Callback called when the debug window is dirty.
/// </summary>
public event Action onSetDirty = delegate { };
event Action resetData;
/// <summary>
/// Event invoked when debug UI needs to be recreated (panels torn down and rebuilt).
/// </summary>
internal event Action onRecreateDebugUI;
/// <summary>
/// Event invoked when a panel selection is requested.
/// </summary>
internal event Action<string> onPanelSelectionRequested;
string m_RequestedPanel;
#if ENABLE_RENDERING_DEBUGGER_UI
internal RuntimeDebugWindow m_RuntimeDebugWindow;
RuntimePersistentDebugUI m_RuntimePersistentDebugUI;
internal SchedulerTracker schedulerTracker { get; } = new();
#endif
internal DebugUI.Widget selectedWidget { get; set; }
/// <summary>
/// Is any debug window or UI currently active.
/// </summary>
public bool isAnyDebugUIActive
{
get
{
return
displayRuntimeUI || displayPersistentRuntimeUI
#if UNITY_EDITOR
|| displayEditorUI
#endif
;
}
}
DebugManager()
{
#if UNITY_ENABLE_CHECKS
RegisterDebugInputs();
#endif
}
/// <summary>
/// Recreates the debug UI for all panels. Use this when the panel structure needs to be rebuilt
/// (e.g., when widgets need to be added/removed dynamically based on feature availability).
/// For simple value refreshes, the UI automatically updates through widget getters.
/// </summary>
public void RecreateDebugUI()
{
onRecreateDebugUI?.Invoke();
}
/// <summary>
/// Reset the debug window.
/// </summary>
public void Reset()
{
DebugDisplaySerializer.SaveFoldoutStates();
DebugDisplaySerializer.Clear();
resetData?.Invoke();
#if ENABLE_RENDERING_DEBUGGER_UI
displayPersistentRuntimeUI = false;
ForEachWidget(w => { if (w is DebugUI.ValueTuple vt) vt.pinnedElementIndex = -1; });
#endif
}
/// <summary>
/// Register debug data.
/// </summary>
/// <param name="data">Data to be registered.</param>
public void RegisterData(IDebugData data) => resetData += data.GetReset();
/// <summary>
/// Register debug data.
/// </summary>
/// <param name="data">Data to be registered.</param>
public void UnregisterData(IDebugData data) => resetData -= data.GetReset();
int GetMaxPinnedIndex(DebugUI.Container container)
{
int pinnedIndex = -1;
foreach (var child in container.children)
{
if (child is DebugUI.ValueTuple valueTuple && valueTuple.pinnedElementIndex > pinnedIndex)
{
pinnedIndex = valueTuple.pinnedElementIndex;
}
}
return pinnedIndex;
}
internal void TogglePersistent()
{
if (selectedWidget != null)
TogglePersistent(selectedWidget);
}
void TogglePersistent(DebugUI.Widget widget, int? forceTupleIndex = null)
{
#if ENABLE_RENDERING_DEBUGGER_UI
if (widget == null)
return;
displayPersistentRuntimeUI = true;
switch (widget)
{
case DebugUI.Value value:
m_RuntimePersistentDebugUI.Toggle(value);
break;
case DebugUI.ValueTuple valueTuple:
m_RuntimePersistentDebugUI.Toggle(valueTuple, forceTupleIndex);
break;
case DebugUI.Container container:
// When container is toggled, we make sure that if there are ValueTuples, they all get the same element index.
int pinnedIndex = GetMaxPinnedIndex(container);
foreach (var child in container.children)
{
if (child is DebugUI.Value || child is DebugUI.ValueTuple)
TogglePersistent(child, pinnedIndex);
}
break;
default:
Debug.Log("Only readonly items can be made persistent.");
break;
}
if (m_RuntimePersistentDebugUI != null && m_RuntimePersistentDebugUI.IsEmpty())
displayPersistentRuntimeUI = false;
#endif
}
void OnPanelDirty(DebugUI.Panel panel)
{
onSetDirty();
}
/// <summary>
/// Returns the panel index
/// </summary>
/// <param name="displayName">The displayname for the panel</param>
/// <returns>The index for the panel or -1 if not found.</returns>
public int PanelIndex([DisallowNull] string displayName)
{
displayName ??= string.Empty;
for (int i = 0; i < m_Panels.Count; ++i)
{
if (displayName.Equals(m_Panels[i].displayName, StringComparison.InvariantCultureIgnoreCase))
return i;
}
return -1;
}
/// <summary>
/// Returns the panel display name
/// </summary>
/// <param name="panelIndex">The panelIndex for the panel to get the name</param>
/// <returns>The display name of the panel, or empty string otherwise</returns>
public string PanelDisplayName(int panelIndex)
{
if (panelIndex < 0 || panelIndex > m_Panels.Count - 1)
return string.Empty;
return m_Panels[panelIndex].displayName;
}
/// <summary>
/// Request DebugWindow to open the specified panel.
/// </summary>
/// <param name="panelName">Name of window panel to activate.</param>
public void RequestPanelSelection(string panelName)
{
int panelIndex = FindPanelIndex(panelName);
if (panelIndex != -1)
{
onPanelSelectionRequested?.Invoke(panelName);
}
else
{
Debug.LogWarning($"No panel with name {panelName} has been registered.");
}
}
// TODO: Optimally we should use a query path here instead of a display name
/// <summary>
/// Returns a debug panel.
/// </summary>
/// <param name="displayName">Name of the debug panel.</param>
/// <param name="createIfNull">Create the panel if it does not exists.</param>
/// <param name="groupIndex">Group index.</param>
/// <param name="overrideIfExist">Replace an existing panel.</param>
/// <returns>The requested debug panel or null if it does not exist and createIfNull is set to false</returns>
public DebugUI.Panel GetPanel(string displayName, bool createIfNull = false, int groupIndex = 0, bool overrideIfExist = false)
{
int panelIndex = PanelIndex(displayName);
DebugUI.Panel p = panelIndex >= 0 ? m_Panels[panelIndex] : null;
if (p != null)
{
if (overrideIfExist)
{
p.onSetDirty -= OnPanelDirty;
RemovePanel(p);
p = null;
}
else
return p;
}
if (createIfNull)
{
p = new DebugUI.Panel { displayName = displayName, groupIndex = groupIndex };
p.onSetDirty += OnPanelDirty;
m_Panels.Add(p);
UpdateReadOnlyCollection();
}
return p;
}
/// <summary>
/// Find the index of the panel from it's display name.
/// </summary>
/// <param name="displayName">The display name of the panel to find.</param>
/// <returns>The index of the panel in the list. -1 if not found.</returns>
public int FindPanelIndex(string displayName)
=> m_Panels.FindIndex(p => p.displayName == displayName);
// TODO: Use a query path here as well instead of a display name
/// <summary>
/// Remove a debug panel.
/// </summary>
/// <param name="displayName">Name of the debug panel to remove.</param>
public void RemovePanel(string displayName)
{
DebugUI.Panel panel = null;
foreach (var p in m_Panels)
{
if (p.displayName == displayName)
{
p.onSetDirty -= OnPanelDirty;
panel = p;
break;
}
}
RemovePanel(panel);
}
/// <summary>
/// Remove a debug panel.
/// </summary>
/// <param name="panel">Reference to the debug panel to remove.</param>
public void RemovePanel(DebugUI.Panel panel)
{
if (panel == null)
return;
m_Panels.Remove(panel);
UpdateReadOnlyCollection();
}
/// <summary>
/// Gets an <see cref="DebugUI.Widget[]"/> matching the given <see cref="DebugUI.Flags"/>
/// </summary>
/// <param name="flags">The flags of the widget</param>
/// <returns>Reference to the requested debug item.</returns>
public DebugUI.Widget[] GetItems(DebugUI.Flags flags)
{
using (ListPool<DebugUI.Widget>.Get(out var temp))
{
foreach (var panel in m_Panels)
{
var widgets = GetItemsFromContainer(flags, panel);
temp.AddRange(widgets);
}
return temp.ToArray();
}
}
internal DebugUI.Widget[] GetItemsFromContainer(DebugUI.Flags flags, DebugUI.IContainer container)
{
using (ListPool<DebugUI.Widget>.Get(out var temp))
{
foreach (var child in container.children)
{
if (child.flags.HasFlag(flags))
{
temp.Add(child);
continue;
}
if (child is DebugUI.IContainer containerChild)
{
temp.AddRange(GetItemsFromContainer(flags, containerChild));
}
}
return temp.ToArray();
}
}
/// <summary>
/// Get a Debug Item.
/// </summary>
/// <param name="queryPath">Path of the debug item.</param>
/// <returns>Reference to the requested debug item.</returns>
public DebugUI.Widget GetItem(string queryPath)
{
foreach (var panel in m_Panels)
{
var w = GetItem(queryPath, panel);
if (w != null)
return w;
}
return null;
}
/// <summary>
/// Get a debug item from a specific container.
/// </summary>
/// <param name="queryPath">Path of the debug item.</param>
/// <param name="container">Container to query.</param>
/// <returns>Reference to the requested debug item.</returns>
DebugUI.Widget GetItem(string queryPath, DebugUI.IContainer container)
{
foreach (var child in container.children)
{
if (child.queryPath == queryPath)
return child;
if (child is DebugUI.IContainer containerChild)
{
var w = GetItem(queryPath, containerChild);
if (w != null)
return w;
}
}
return null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a09c907f481d4894a96697283a87c352
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,66 @@
namespace UnityEngine.Rendering
{
/// <summary>
/// Utility class for debug overlay coordinates.
/// </summary>
public class DebugOverlay
{
/// <summary>Current x coordinate.</summary>
public int x { get; private set; }
/// <summary>Current y coordinate.</summary>
public int y { get; private set; }
/// <summary>Current overlay size.</summary>
public int overlaySize { get; private set; }
int m_InitialPositionX;
int m_ScreenWidth;
/// <summary>
/// Start rendering overlay.
/// </summary>
/// <param name="initialX">Initial x position.</param>
/// <param name="initialY">Initial y position.</param>
/// <param name="overlaySize">Size of overlays between 0 and 1.</param>
/// <param name="screenWidth">Width of the screen.</param>
public void StartOverlay(int initialX, int initialY, int overlaySize, int screenWidth)
{
x = initialX;
y = initialY;
this.overlaySize = overlaySize;
m_InitialPositionX = initialX;
m_ScreenWidth = screenWidth;
}
/// <summary>
/// Increment coordinates to the next overlay and return the current overlay rect.
/// </summary>
/// <param name="aspect">Aspect of the current overlay.</param>
/// <returns>Returns a rect of the current overlay.</returns>
public Rect Next(float aspect = 1.0f)
{
int overlayWidth = (int)(overlaySize * aspect);
if ((x + overlayWidth) > m_ScreenWidth && x > m_InitialPositionX)
{
x = m_InitialPositionX;
y -= overlaySize;
}
Rect rect = new Rect(x, y, overlayWidth, overlaySize);
x += overlayWidth;
return rect;
}
/// <summary>
/// Setup the viewport for the current overlay.
/// </summary>
/// <param name="cmd">Command buffer used to setup viewport.</param>
public void SetViewport(CommandBuffer cmd)
{
cmd.SetViewport(new Rect(x, y, overlaySize, overlaySize));
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 01796373c956d2c40b09d1e150c2a2bd
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,543 @@
namespace UnityEngine.Rendering
{
/// <summary>Debug class containing several debug shapes for debugging</summary>
public partial class DebugShapes
{
// Singleton
static DebugShapes s_Instance = null;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
s_Instance = null;
}
#endif
/// <summary>Singleton instance</summary>
static public DebugShapes instance
{
get
{
if (s_Instance == null)
{
s_Instance = new DebugShapes();
}
return s_Instance;
}
}
Mesh m_sphereMesh = null;
Mesh m_boxMesh = null;
Mesh m_coneMesh = null;
Mesh m_pyramidMesh = null;
// This code has been grabbed from http://wiki.unity3d.com/index.php/ProceduralPrimitives
void BuildSphere(ref Mesh outputMesh, float radius, uint longSubdiv, uint latSubdiv)
{
// Make sure it is empty before pushing anything to it
outputMesh.Clear();
// Build the vertices array
Vector3[] vertices = new Vector3[(longSubdiv + 1) * latSubdiv + 2];
float _pi = Mathf.PI;
float _2pi = _pi * 2f;
vertices[0] = Vector3.up * radius;
for (int lat = 0; lat < latSubdiv; lat++)
{
float a1 = _pi * (float)(lat + 1) / (latSubdiv + 1);
float sin1 = Mathf.Sin(a1);
float cos1 = Mathf.Cos(a1);
for (int lon = 0; lon <= longSubdiv; lon++)
{
float a2 = _2pi * (float)(lon == longSubdiv ? 0 : lon) / longSubdiv;
float sin2 = Mathf.Sin(a2);
float cos2 = Mathf.Cos(a2);
vertices[lon + lat * (longSubdiv + 1) + 1] = new Vector3(sin1 * cos2, cos1, sin1 * sin2) * radius;
}
}
vertices[vertices.Length - 1] = Vector3.up * -radius;
// Build the normals array
Vector3[] normals = new Vector3[vertices.Length];
for (int n = 0; n < vertices.Length; n++)
{
normals[n] = vertices[n].normalized;
}
// Build the UV array
Vector2[] uvs = new Vector2[vertices.Length];
uvs[0] = Vector2.up;
uvs[uvs.Length - 1] = Vector2.zero;
for (int lat = 0; lat < latSubdiv; lat++)
{
for (int lon = 0; lon <= longSubdiv; lon++)
{
uvs[lon + lat * (longSubdiv + 1) + 1] = new Vector2((float)lon / longSubdiv, 1f - (float)(lat + 1) / (latSubdiv + 1));
}
}
// Build the index array
uint nbTriangles = longSubdiv * 2 + // Top and bottom cap
(latSubdiv - 1) * longSubdiv * 2; // Middle part
uint nbIndexes = nbTriangles * 3;
int[] triangles = new int[nbIndexes];
// Top Cap
int i = 0;
for (int lon = 0; lon < longSubdiv; lon++)
{
triangles[i++] = lon + 2;
triangles[i++] = lon + 1;
triangles[i++] = 0;
}
//Middle
for (uint lat = 0; lat < latSubdiv - 1; lat++)
{
for (uint lon = 0; lon < longSubdiv; lon++)
{
uint current = lon + lat * (longSubdiv + 1) + 1;
uint next = current + longSubdiv + 1;
triangles[i++] = (int)current;
triangles[i++] = (int)current + 1;
triangles[i++] = (int)next + 1;
triangles[i++] = (int)current;
triangles[i++] = (int)next + 1;
triangles[i++] = (int)next;
}
}
// Bottom Cap
for (int lon = 0; lon < longSubdiv; lon++)
{
triangles[i++] = vertices.Length - 1;
triangles[i++] = vertices.Length - (lon + 2) - 1;
triangles[i++] = vertices.Length - (lon + 1) - 1;
}
// Assign them to
outputMesh.vertices = vertices;
outputMesh.normals = normals;
outputMesh.uv = uvs;
outputMesh.triangles = triangles;
outputMesh.RecalculateBounds();
}
void BuildBox(ref Mesh outputMesh, float length, float width, float height)
{
outputMesh.Clear();
Vector3 p0 = new Vector3(-length * .5f, -width * .5f, height * .5f);
Vector3 p1 = new Vector3(length * .5f, -width * .5f, height * .5f);
Vector3 p2 = new Vector3(length * .5f, -width * .5f, -height * .5f);
Vector3 p3 = new Vector3(-length * .5f, -width * .5f, -height * .5f);
Vector3 p4 = new Vector3(-length * .5f, width * .5f, height * .5f);
Vector3 p5 = new Vector3(length * .5f, width * .5f, height * .5f);
Vector3 p6 = new Vector3(length * .5f, width * .5f, -height * .5f);
Vector3 p7 = new Vector3(-length * .5f, width * .5f, -height * .5f);
Vector3[] vertices = new Vector3[]
{
// Bottom
p0, p1, p2, p3,
// Left
p7, p4, p0, p3,
// Front
p4, p5, p1, p0,
// Back
p6, p7, p3, p2,
// Right
p5, p6, p2, p1,
// Top
p7, p6, p5, p4
};
Vector3 up = Vector3.up;
Vector3 down = Vector3.down;
Vector3 front = Vector3.forward;
Vector3 back = Vector3.back;
Vector3 left = Vector3.left;
Vector3 right = Vector3.right;
Vector3[] normales = new Vector3[]
{
// Bottom
down, down, down, down,
// Left
left, left, left, left,
// Front
front, front, front, front,
// Back
back, back, back, back,
// Right
right, right, right, right,
// Top
up, up, up, up
};
Vector2 _00 = new Vector2(0f, 0f);
Vector2 _10 = new Vector2(1f, 0f);
Vector2 _01 = new Vector2(0f, 1f);
Vector2 _11 = new Vector2(1f, 1f);
Vector2[] uvs = new Vector2[]
{
// Bottom
_11, _01, _00, _10,
// Left
_11, _01, _00, _10,
// Front
_11, _01, _00, _10,
// Back
_11, _01, _00, _10,
// Right
_11, _01, _00, _10,
// Top
_11, _01, _00, _10,
};
int[] triangles = new int[]
{
// Bottom
3, 1, 0,
3, 2, 1,
// Left
3 + 4 * 1, 1 + 4 * 1, 0 + 4 * 1,
3 + 4 * 1, 2 + 4 * 1, 1 + 4 * 1,
// Front
3 + 4 * 2, 1 + 4 * 2, 0 + 4 * 2,
3 + 4 * 2, 2 + 4 * 2, 1 + 4 * 2,
// Back
3 + 4 * 3, 1 + 4 * 3, 0 + 4 * 3,
3 + 4 * 3, 2 + 4 * 3, 1 + 4 * 3,
// Right
3 + 4 * 4, 1 + 4 * 4, 0 + 4 * 4,
3 + 4 * 4, 2 + 4 * 4, 1 + 4 * 4,
// Top
3 + 4 * 5, 1 + 4 * 5, 0 + 4 * 5,
3 + 4 * 5, 2 + 4 * 5, 1 + 4 * 5,
};
outputMesh.vertices = vertices;
outputMesh.normals = normales;
outputMesh.uv = uvs;
outputMesh.triangles = triangles;
outputMesh.RecalculateBounds();
}
void BuildCone(ref Mesh outputMesh, float height, float topRadius, float bottomRadius, int nbSides)
{
outputMesh.Clear();
int nbVerticesCap = nbSides + 1;
// bottom + top + sides
Vector3[] vertices = new Vector3[nbVerticesCap + nbVerticesCap + nbSides * 2 + 2];
int vert = 0;
float _2pi = Mathf.PI * 2f;
// Bottom cap
vertices[vert++] = new Vector3(0f, 0f, 0f);
while (vert <= nbSides)
{
float rad = (float)vert / nbSides * _2pi;
vertices[vert] = new Vector3(Mathf.Sin(rad) * bottomRadius, Mathf.Cos(rad) * bottomRadius, 0f);
vert++;
}
// Top cap
vertices[vert++] = new Vector3(0f, 0f, height);
while (vert <= nbSides * 2 + 1)
{
float rad = (float)(vert - nbSides - 1) / nbSides * _2pi;
vertices[vert] = new Vector3(Mathf.Sin(rad) * topRadius, Mathf.Cos(rad) * topRadius, height);
vert++;
}
// Sides
int v = 0;
while (vert <= vertices.Length - 4)
{
float rad = (float)v / nbSides * _2pi;
vertices[vert] = new Vector3(Mathf.Sin(rad) * topRadius, Mathf.Cos(rad) * topRadius, height);
vertices[vert + 1] = new Vector3(Mathf.Sin(rad) * bottomRadius, Mathf.Cos(rad) * bottomRadius, 0);
vert += 2;
v++;
}
vertices[vert] = vertices[nbSides * 2 + 2];
vertices[vert + 1] = vertices[nbSides * 2 + 3];
// bottom + top + sides
Vector3[] normales = new Vector3[vertices.Length];
vert = 0;
// Bottom cap
while (vert <= nbSides)
{
normales[vert++] = new Vector3(0, 0, -1);
}
// Top cap
while (vert <= nbSides * 2 + 1)
{
normales[vert++] = new Vector3(0, 0, 1);
}
// Sides
v = 0;
while (vert <= vertices.Length - 4)
{
float rad = (float)v / nbSides * _2pi;
float cos = Mathf.Cos(rad);
float sin = Mathf.Sin(rad);
normales[vert] = new Vector3(sin, cos, 0f);
normales[vert + 1] = normales[vert];
vert += 2;
v++;
}
normales[vert] = normales[nbSides * 2 + 2];
normales[vert + 1] = normales[nbSides * 2 + 3];
Vector2[] uvs = new Vector2[vertices.Length];
// Bottom cap
int u = 0;
uvs[u++] = new Vector2(0.5f, 0.5f);
while (u <= nbSides)
{
float rad = (float)u / nbSides * _2pi;
uvs[u] = new Vector2(Mathf.Cos(rad) * .5f + .5f, Mathf.Sin(rad) * .5f + .5f);
u++;
}
// Top cap
uvs[u++] = new Vector2(0.5f, 0.5f);
while (u <= nbSides * 2 + 1)
{
float rad = (float)u / nbSides * _2pi;
uvs[u] = new Vector2(Mathf.Cos(rad) * .5f + .5f, Mathf.Sin(rad) * .5f + .5f);
u++;
}
// Sides
int u_sides = 0;
while (u <= uvs.Length - 4)
{
float t = (float)u_sides / nbSides;
uvs[u] = new Vector3(t, 1f);
uvs[u + 1] = new Vector3(t, 0f);
u += 2;
u_sides++;
}
uvs[u] = new Vector2(1f, 1f);
uvs[u + 1] = new Vector2(1f, 0f);
int nbTriangles = nbSides + nbSides + nbSides * 2;
int[] triangles = new int[nbTriangles * 3 + 3];
// Bottom cap
int tri = 0;
int i = 0;
while (tri < nbSides - 1)
{
triangles[i] = 0;
triangles[i + 1] = tri + 1;
triangles[i + 2] = tri + 2;
tri++;
i += 3;
}
triangles[i] = 0;
triangles[i + 1] = tri + 1;
triangles[i + 2] = 1;
tri++;
i += 3;
// Top cap
//tri++;
while (tri < nbSides * 2)
{
triangles[i] = tri + 2;
triangles[i + 1] = tri + 1;
triangles[i + 2] = nbVerticesCap;
tri++;
i += 3;
}
triangles[i] = nbVerticesCap + 1;
triangles[i + 1] = tri + 1;
triangles[i + 2] = nbVerticesCap;
tri++;
i += 3;
tri++;
// Sides
while (tri <= nbTriangles)
{
triangles[i] = tri + 2;
triangles[i + 1] = tri + 1;
triangles[i + 2] = tri + 0;
tri++;
i += 3;
triangles[i] = tri + 1;
triangles[i + 1] = tri + 2;
triangles[i + 2] = tri + 0;
tri++;
i += 3;
}
outputMesh.vertices = vertices;
outputMesh.normals = normales;
outputMesh.uv = uvs;
outputMesh.triangles = triangles;
outputMesh.RecalculateBounds();
}
void BuildPyramid(ref Mesh outputMesh, float width, float height, float depth)
{
outputMesh.Clear();
// Allocate the buffer
Vector3[] vertices = new Vector3[16];
// Top Face
vertices[0] = new Vector3(0f, 0f, 0f);
vertices[1] = new Vector3(-width / 2.0f, height / 2.0f, depth);
vertices[2] = new Vector3(width / 2.0f, height / 2.0f, depth);
// Left Face
vertices[3] = new Vector3(0f, 0f, 0f);
vertices[4] = new Vector3(width / 2.0f, height / 2.0f, depth);
vertices[5] = new Vector3(width / 2.0f, -height / 2.0f, depth);
// Bottom Face
vertices[6] = new Vector3(0f, 0f, 0f);
vertices[7] = new Vector3(width / 2.0f, -height / 2.0f, depth);
vertices[8] = new Vector3(-width / 2.0f, -height / 2.0f, depth);
// Right Face
vertices[9] = new Vector3(0f, 0f, 0f);
vertices[10] = new Vector3(-width / 2.0f, -height / 2.0f, depth);
vertices[11] = new Vector3(-width / 2.0f, height / 2.0f, depth);
// Cap
vertices[12] = new Vector3(-width / 2.0f, height / 2.0f, depth);
vertices[13] = new Vector3(-width / 2.0f, -height / 2.0f, depth);
vertices[14] = new Vector3(width / 2.0f, -height / 2.0f, depth);
vertices[15] = new Vector3(width / 2.0f, height / 2.0f, depth);
// TODO: support the uv/normals
Vector3[] normals = new Vector3[vertices.Length];
Vector2[] uvs = new Vector2[vertices.Length];
// The indexes for the side part is simple
int[] triangles = new int[18];
for (int idx = 0; idx < 12; ++idx)
{
triangles[idx] = idx;
}
// Cap indexes
triangles[12] = 12;
triangles[13] = 13;
triangles[14] = 14;
triangles[15] = 12;
triangles[16] = 14;
triangles[17] = 15;
outputMesh.vertices = vertices;
outputMesh.normals = normals;
outputMesh.uv = uvs;
outputMesh.triangles = triangles;
outputMesh.RecalculateBounds();
}
void BuildShapes()
{
m_sphereMesh = new Mesh();
BuildSphere(ref m_sphereMesh, 1.0f, 24, 16);
m_boxMesh = new Mesh();
BuildBox(ref m_boxMesh, 1.0f, 1.0f, 1.0f);
m_coneMesh = new Mesh();
BuildCone(ref m_coneMesh, 1.0f, 1.0f, 0.0f, 16);
m_pyramidMesh = new Mesh();
BuildPyramid(ref m_pyramidMesh, 1.0f, 1.0f, 1.0f);
}
void RebuildResources()
{
if (m_sphereMesh == null || m_boxMesh == null || m_coneMesh == null || m_pyramidMesh == null)
{
BuildShapes();
}
}
/// <summary>Get a Sphere Mesh</summary>
/// <returns>A Sphere Mesh</returns>
public Mesh RequestSphereMesh()
{
RebuildResources();
return m_sphereMesh;
}
/// <summary>Builds a custom Sphere Mesh</summary>
/// <param name="radius">The radius of the generated sphere.</param>
/// <param name="longSubdiv">The number of subdivisions along the equator of the sphere. Must be at least 3 to give a relevant shape.</param>
/// <param name="latSubdiv">The number of subdivisions from north to south. Must be at least 1 to give a relevant shape.</param>
/// <returns>A Sphere Mesh</returns>
/// <example>
/// <code>
/// <![CDATA[
/// Mesh lowPolyDebugMesh = DebugShapes.instance.BuildCustomSphereMesh(0.5f, 9, 8); // Generates a 82 vert sphere
/// ]]>
///</code>
/// </example>
public Mesh BuildCustomSphereMesh(float radius, uint longSubdiv, uint latSubdiv)
{
Mesh sphereMesh = new Mesh();
BuildSphere(ref sphereMesh, radius, longSubdiv, latSubdiv);
return sphereMesh;
}
/// <summary>Get a Box Mesh</summary>
/// <returns>A Box Mesh</returns>
public Mesh RequestBoxMesh()
{
RebuildResources();
return m_boxMesh;
}
/// <summary>Get a Cone Mesh</summary>
/// <returns>A Cone Mesh</returns>
public Mesh RequestConeMesh()
{
RebuildResources();
return m_coneMesh;
}
/// <summary>Get a Pyramid Mesh</summary>
/// <returns>A Pyramid Mesh</returns>
public Mesh RequestPyramidMesh()
{
RebuildResources();
return m_pyramidMesh;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: a164ae4d75dc0074b966a2efdf0a5700
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,862 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
using System;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
#if ENABLE_RENDERING_DEBUGGER_UI
using UnityEngine.UIElements;
#endif
namespace UnityEngine.Rendering
{
public partial class DebugUI
{
/// <summary>
/// Base class for "container" type widgets, although it can be used on its own (if a display name is set then it'll behave as a group with a header)
/// </summary>
public class Container : Widget, IContainer
{
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
VisualElement container = new UIElements.VisualElement();
container.AddToClassList("debug-window-container");
if (!hideDisplayName)
{
var label = new Label(displayName);
label.AddToClassList("debug-window-container-displayname");
label.AddToClassList("debug-window-search-filter-target");
container.Add(label);
}
var content = new VisualElement();
content.AddToClassList("debug-window-container-content");
AddChildren(content, m_Context);
container.Add(content);
return container;
}
/// <summary>
/// Adds all the children to the given container
/// </summary>
/// <param name="container">The container to insert elements</param>
/// <param name="context">The context where the widget is being added</param>
protected void AddChildren(VisualElement container, DebugUI.Context context)
{
for (int i = 0; i < children.Count; ++i)
{
var child = children[i];
if (context == Context.Editor && child.isRuntimeOnly)
continue;
if (context.IsAnyRuntimeContext() && child.isEditorOnly)
continue;
var childUIElement = child.ToVisualElement(context);
if (childUIElement != null)
container.Add(childUIElement);
}
// As the elements might change visibility, we need to update alternating background colors
if (alternateRowColors)
{
this.ScheduleTracked(container, () => container.schedule.Execute(() =>
{
int i = 0;
foreach (var child in container.Children())
{
if (child.style.display == DisplayStyle.Flex)
{
if (i % 2 != 0)
child.AddToClassList(k_AlternateRowColorClassName);
else
child.RemoveFromClassList(k_AlternateRowColorClassName);
++i;
}
}
}).Every(100));
}
}
#endif
const string k_IDToken = "#";
internal bool hideDisplayName => string.IsNullOrEmpty(displayName) || displayName.StartsWith(k_IDToken);
/// <summary>
/// List of children.
/// </summary>
public ObservableList<Widget> children { get; private set; }
const string k_AlternateRowColorClassName = "debug-window-row-alternate";
/// <summary>
/// Set to true to alternate background colors of the rows inside the container.
/// </summary>
public bool alternateRowColors { get; set; }
/// <summary>
/// Panel the container is attached to.
/// </summary>
public override Panel panel
{
get { return m_Panel; }
internal set
{
m_Panel = value;
// Bubble down
int numChildren = children.Count;
for (int i = 0; i < numChildren; i++)
children[i].panel = value;
}
}
/// <summary>
/// Constructor
/// </summary>
public Container()
: this(string.Empty, new ObservableList<Widget>())
{
}
/// <summary>
/// Constructor for a container without header
/// </summary>
/// <param name="id">The id of the container</param>
public Container(string id)
: this($"{k_IDToken}{id}", new ObservableList<Widget>())
{
}
/// <summary>
/// Constructor.
/// </summary>
/// <param name="displayName">Display name of the container.</param>
/// <param name="children">List of attached children.</param>
public Container(string displayName, ObservableList<Widget> children)
{
this.displayName = displayName;
this.children = children;
children.ItemAdded += OnItemAdded;
children.ItemRemoved += OnItemRemoved;
// Call OnAdded callback for already existing items to ensure their panel & parent are set
for (int i = 0; i < this.children.Count; i++)
OnItemAdded(this.children, new ListChangedEventArgs<Widget>(i, this.children[i]));
}
internal override void GenerateQueryPath()
{
base.GenerateQueryPath();
int numChildren = children.Count;
for (int i = 0; i < numChildren; i++)
children[i].GenerateQueryPath();
}
/// <summary>
/// Method called when a children is added.
/// </summary>
/// <param name="sender">Sender widget.</param>
/// <param name="e">List of added children.</param>
protected virtual void OnItemAdded(ObservableList<Widget> sender, ListChangedEventArgs<Widget> e)
{
if (e.item != null)
{
e.item.panel = m_Panel;
e.item.parent = this;
}
if (m_Panel != null)
m_Panel.SetDirty();
}
/// <summary>
/// Method called when a children is removed.
/// </summary>
/// <param name="sender">Sender widget.</param>
/// <param name="e">List of removed children.</param>
protected virtual void OnItemRemoved(ObservableList<Widget> sender, ListChangedEventArgs<Widget> e)
{
if (e.item != null)
{
e.item.panel = null;
e.item.parent = null;
}
if (m_Panel != null)
m_Panel.SetDirty();
}
}
/// <summary>
/// Unity-like foldout that can be collapsed.
/// </summary>
public class Foldout : Container
#pragma warning disable CS0618 // Type or member is obsolete
, IValueField
#pragma warning restore CS0618 // Type or member is obsolete
{
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var container = new UIElements.Foldout { text = displayName };
if (m_Context == Context.Editor && (contextMenuItems != null || !string.IsNullOrEmpty(documentationUrl)))
{
#if UNITY_EDITOR
// Get Toggle element of the Foldout to be able to attach the help and menu buttons
var toggleHeader = container.Q<Toggle>().ElementAt(0);
if (!string.IsNullOrEmpty(documentationUrl))
{
var infoButton = new UIElements.Button((Background.FromTexture2D((Texture2D)EditorGUIUtility.TrIconContent("_Help").image )),() => Help.BrowseURL(documentationUrl));
infoButton.AddToClassList("info-button");
infoButton.tooltip = $"Open Reference for {displayName}.";
toggleHeader.Add(infoButton);
}
if (contextMenuItems != null)
{
var button = new UIElements.Button();
button.AddToClassList("more-options-button");
var contextualMenu = new GenericDropdownMenu();
foreach(var item in contextMenuItems)
{
contextualMenu.AddItem(item.displayName, false, item.action );
}
button.clicked += () =>
{
contextualMenu.DropDown(button.worldBound, button, DropdownMenuSizeMode.Auto);
};
toggleHeader.Add(button);
}
#endif
}
// Add special classes for styles
// Use header style for top-level foldouts (not inside a Container), regular style for nested ones
bool isHeaderFoldout = parent is DebugUI.Panel;
container.AddToClassList(isHeaderFoldout ? "debug-window-foldout-header" : "debug-window-foldout");
container.Q(className: "unity-foldout__text").AddToClassList("debug-window-search-filter-target");
// Update UI to match object's initial state
container.SetValueWithoutNotify(GetValue());
// Sync value to object when changed in UI
container.RegisterCallback<ChangeEvent<bool>>(evt =>
{
SetValue(container.value);
});
// Sync value to object based on navigation events separately, because they don't trigger a ChangeEvent
container.RegisterCallback<NavigationMoveEvent>(evt =>
{
if (DebugManager.instance.selectedWidget == this)
{
if (evt.direction == NavigationMoveEvent.Direction.Right)
SetValue(true);
else if (evt.direction == NavigationMoveEvent.Direction.Left)
SetValue(false);
}
}, TrickleDown.TrickleDown); // Foldout internally stops propagation so must use TrickleDown to see it
// Sync opened state from object to UI
this.ScheduleTracked(container, () => container.schedule.Execute(() =>
{
container.SetValueWithoutNotify(GetValue());
}).Every(100));
if (columnLabels is { Length: > 0 })
{
var columnLabelsValues = new DebugUI.Value[columnLabels.Length];
for (int i = 0; i < columnLabels.Length; i++)
{
string value = columnLabels[i];
object Getter() => value;
columnLabelsValues[i] = new DebugUI.Value()
{
displayName = string.Empty,
getter = Getter
};
}
var header = new DebugUI.ValueTuple()
{
displayName = string.Empty,
isHeader = true,
values = columnLabelsValues
};
container.Add(header.ToVisualElement(m_Context));
container.RegisterCallback<GeometryChangedEvent>(evt =>
{
var numColumns = columnLabels.Length;
foreach (var visualElement in container.Children())
{
var width = (evt.newRect.width - ValueTuple.GetLabelWidth(m_Context)) / numColumns;
int i = 0;
foreach (var child in visualElement.Children())
{
if (i != 0)
child.style.width = width;
++i;
}
}
});
}
AddChildren(container, m_Context);
return container;
}
#endif
/// <summary>
/// Context menu item.
/// </summary>
public struct ContextMenuItem
{
/// <summary>
/// Name of the item displayed in context menu dropdown.
/// </summary>
public string displayName;
/// <summary>
/// Callback when context menu item is selected.
/// </summary>
public Action action;
}
/// <summary>
/// Always false.
/// </summary>
public bool isReadOnly { get { return false; } }
bool m_Opened;
/// <summary>
/// Opened state of the foldout.
/// </summary>
public bool opened
{
get => m_Opened;
set
{
if (opened != value)
{
#if ENABLE_RENDERING_DEBUGGER_UI
if (m_VisualElement != null)
DebugManager.instance.schedulerTracker.SetHierarchyEnabled(m_Context, this, value);
#endif
m_Opened = value;
}
}
}
/// <summary>
/// Draw the foldout in full width using a header style.
/// </summary>
public bool isHeader;
/// <summary>
/// Optional list of context menu items. If the list is not provided, no context menu button will be displayed.
/// </summary>
public List<ContextMenuItem> contextMenuItems = null;
/// <summary>
/// Optional help URL for the editor UI
/// </summary>
public string documentationUrl { get; set; }
private bool m_Dirty;
private string[] m_ColumnLabels;
private string[] m_ColumnTooltips;
/// <summary>
/// List of columns labels.
/// </summary>
public string[] columnLabels
{
get => m_ColumnLabels;
set
{
m_ColumnLabels = value;
m_Dirty = true;
}
}
/// <summary>
/// List of columns label tooltips.
/// </summary>
public string[] columnTooltips
{
get => m_ColumnTooltips;
set
{
m_ColumnTooltips = value;
m_Dirty = true;
}
}
private List<GUIContent> m_RowContents = new();
internal List<GUIContent> rowContents
{
get
{
if (m_Dirty)
{
if (m_ColumnTooltips == null)
{
m_ColumnTooltips = new string[m_ColumnLabels.Length];
Array.Fill(columnTooltips, string.Empty);
}
else
{
if (m_ColumnTooltips.Length != m_ColumnLabels.Length)
throw new Exception(
$"Dimension for labels and tooltips on {nameof(DebugUI.Foldout)} - {displayName}, do not match");
}
m_RowContents.Clear();
for (int i = 0; i < m_ColumnLabels.Length; ++i)
{
string label = columnLabels[i] ?? string.Empty;
string tooltip = m_ColumnTooltips[i] ?? string.Empty;
m_RowContents.Add(
#if UNITY_EDITOR
EditorGUIUtility.TrTextContent(label, tooltip)
#else
new GUIContent(label, tooltip)
#endif
);
}
m_Dirty = false;
}
return m_RowContents;
}
}
/// <summary>
/// Constructor.
/// </summary>
public Foldout() : base() { }
/// <summary>
/// Constructor.
/// </summary>
/// <param name="displayName">Display name of the foldout.</param>
/// <param name="children">List of attached children.</param>
/// <param name="columnLabels">Optional list of column names.</param>
/// <param name="columnTooltips">Optional list of tooltips for column name labels.</param>
public Foldout(string displayName, ObservableList<Widget> children, string[] columnLabels = null, string[] columnTooltips = null)
: base(displayName, children)
{
this.columnLabels = columnLabels;
this.columnTooltips = columnTooltips;
}
/// <summary>
/// Get the opened state of the foldout.
/// </summary>
/// <returns>True if the foldout is opened.</returns>
public bool GetValue() => opened;
/// <summary>
/// Get the opened state of the foldout.
/// </summary>
/// <returns>True if the foldout is opened.</returns>
object IValueField.GetValue() => GetValue();
/// <summary>
/// Set the opened state of the foldout.
/// </summary>
/// <param name="value">True to open the foldout, false to close it.</param>
[Obsolete("This method is no longer used. #from(6000.5)")]
public void SetValue(object value) => SetValue((bool)value);
/// <summary>
/// Validates the value of the widget before setting it.
/// </summary>
/// <param name="value">Input value.</param>
/// <returns>The validated value.</returns>
[Obsolete("This method is no longer used. #from(6000.5)")]
public object ValidateValue(object value) => value;
/// <summary>
/// Set the value of the widget.
/// </summary>
/// <param name="value">Input value.</param>
public void SetValue(bool value) => opened = value;
}
/// <summary>
/// Horizontal Layout Container.
/// </summary>
public class HBox : Container
{
/// <summary>
/// Constructor.
/// </summary>
public HBox()
{
displayName = "HBox";
}
}
/// <summary>
/// Vertical Layout Container.
/// </summary>
public class VBox : Container
{
/// <summary>
/// Constructor.
/// </summary>
public VBox()
{
displayName = "VBox";
}
}
/// <summary>
/// Array Container.
/// </summary>
public class Table : Container
{
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var container = new UIElements.VisualElement();
container.AddToClassList("debug-window-table");
using (ListPool<string>.Get(out var tmp))
{
if (children.Count != 0 && children[0] is Row row)
{
foreach (var child in row.children)
tmp.Add(child.displayName);
}
var columnLabelsValues = new DebugUI.Value[tmp.Count];
for (int i = 0; i < columnLabelsValues.Length; i++)
{
string value = tmp[i];
object Getter() => value;
columnLabelsValues[i] = new DebugUI.Value()
{
displayName = string.Empty,
getter = Getter
};
}
var header = new DebugUI.ValueTuple()
{
displayName = string.Empty,
isHeader = true,
values = columnLabelsValues
};
var headerVisualElement = header.ToVisualElement(m_Context);
headerVisualElement.AddToClassList("debug-window-table-header-row");
foreach (var headerElement in headerVisualElement.Children())
headerElement.AddToClassList("debug-window-table-header-cell");
container.Add(headerVisualElement);
// NOTE: Current implementation constructs the table cells from individual elements, so cell width needs to be
// set manually like this. This is necessary because of the DebugUI.Table/Row structure, which is why we can't use
// a proper table.
container.RegisterCallback<GeometryChangedEvent>(evt =>
{
var numColumns = columnLabelsValues.Length;
var availableWidth = evt.newRect.width;
if (displayRowNames)
availableWidth -= ValueTuple.GetLabelWidth(m_Context);
var width = availableWidth / numColumns;
foreach (var visualElement in container.Children())
{
int i = 0;
foreach (var child in visualElement.Children())
{
if (i == 0)
child.style.display = displayRowNames ? DisplayStyle.Flex : DisplayStyle.None;
else
{
child.style.width = width;
child.style.display = DisplayStyle.Flex;
}
++i;
}
}
});
}
AddChildren(container, m_Context);
container.enabledSelf = !isReadOnly;
return container;
}
#endif
/// <summary>Row Container.</summary>
public class Row : Container
{
/// <summary>Constructor.</summary>
public Row() { displayName = "Row"; }
/// <summary>Opened state of the row. No longer used.</summary>
[Obsolete("This class no longer inherits from Foldout, but from Container. This field is kept for compatibility but it no longer does anything. #from(6000.5)")]
public bool opened { get; set; }
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var rowContainer = new UIElements.VisualElement();
rowContainer.AddToClassList("debug-window-table-row");
var label = new Label(displayName) { style = { width = ValueTuple.GetLabelWidth(m_Context) }, };
label.AddToClassList("debug-window-table-row-displayname");
label.AddToClassList("debug-window-search-filter-target");
rowContainer.Add(label);
foreach (var c in children)
{
c.keepLayoutWhenHidden = true;
var rowElement = c.ToVisualElement(m_Context);
rowElement.AddToClassList("debug-window-table-cell");
// In Table layout we don't want to show the labels of DebugUI.Values
var valueLabel = rowElement.Q<Label>(className: "debug-window-value-name");
if (valueLabel != null)
valueLabel.style.display = DisplayStyle.None;
rowContainer.Add(rowElement);
}
return rowContainer;
}
#endif
}
/// <summary>
/// True if the table is read only.
/// </summary>
public bool isReadOnly = false;
/// <summary>
/// Set to false to hide the first column containing the row names
/// </summary>
public bool displayRowNames = true;
/// <summary>Constructor.</summary>
public Table() { displayName = "Array"; }
/// <summary>
/// Set column visibility.
/// </summary>
/// <param name="index">Index of the column.</param>
/// <param name="visible">True if the column should be visible.</param>
[Obsolete("This method is no longer used. #from(6000.5)")]
public void SetColumnVisibility(int index, bool visible)
{
#if UNITY_EDITOR
var header = Header;
if (index < 0 || index >= m_ColumnCount)
return;
index++;
if (header.IsColumnVisible(index) != visible)
{
var newVisibleColumns = new System.Collections.Generic.List<int>(header.state.visibleColumns);
if (newVisibleColumns.Contains(index))
{
newVisibleColumns.Remove(index);
}
else
{
newVisibleColumns.Add(index);
newVisibleColumns.Sort();
}
header.state.visibleColumns = newVisibleColumns.ToArray();
var cols = header.state.columns;
for (int i = 0; i < cols.Length; i++)
cols[i].width = 50f;
header.ResizeToFit();
}
#else
var columns = VisibleColumns;
if (index < 0 || index > columns.Length)
return;
columns[index] = visible;
#endif
}
/// <summary>
/// Get column visibility.
/// </summary>
/// <param name="index">Index of the column.</param>
/// <returns>True if the column is visible.</returns>
[Obsolete("This method is no longer used. #from(6000.5)")]
public bool GetColumnVisibility(int index)
{
#if UNITY_EDITOR
var header = Header;
if (index < 0 || index >= m_ColumnCount)
return false;
return header.IsColumnVisible(index + 1);
#else
var columns = VisibleColumns;
if (index < 0 || index > columns.Length)
return false;
return columns[index];
#endif
}
#if UNITY_EDITOR
/// <summary>
/// The scroll position of the table.
/// </summary>
[Obsolete("This property is no longer used. #from(6000.5)")]
public Vector2 scroll = Vector2.zero;
int m_ColumnCount;
UnityEditor.IMGUI.Controls.MultiColumnHeader m_Header = null;
/// <summary>
/// The table header for drawing
/// </summary>
[Obsolete("This property is no longer used. #from(6000.5)")]
public UnityEditor.IMGUI.Controls.MultiColumnHeader Header
{
get
{
if (m_Header != null)
return m_Header;
if (children.Count != 0)
{
m_ColumnCount = ((Container)children[0]).children.Count;
for (int i = 1; i < children.Count; i++)
{
if (((Container)children[i]).children.Count != m_ColumnCount)
{
Debug.LogError("All rows must have the same number of children.");
return null;
}
}
}
UnityEditor.IMGUI.Controls.MultiColumnHeaderState.Column CreateColumn(string name, string tooltip)
{
var col = new UnityEditor.IMGUI.Controls.MultiColumnHeaderState.Column()
{
canSort = false,
headerTextAlignment = TextAlignment.Center,
headerContent = new GUIContent(name, tooltip ?? string.Empty)
};
//columnHeaderStyle.CalcMinMaxWidth(col.headerContent, out col.width, out float _);
col.width = Mathf.Min(col.width, 50f);
return col;
}
var cols = new UnityEditor.IMGUI.Controls.MultiColumnHeaderState.Column[m_ColumnCount + 1];
cols[0] = CreateColumn(displayName, tooltip);
cols[0].allowToggleVisibility = false;
for (int i = 0; i < m_ColumnCount; i++)
{
var elem = ((Container) children[0]).children[i];
cols[i + 1] = CreateColumn(elem.displayName, elem.tooltip);
}
var state = new UnityEditor.IMGUI.Controls.MultiColumnHeaderState(cols);
m_Header = new UnityEditor.IMGUI.Controls.MultiColumnHeader(state) { height = 23 };
m_Header.ResizeToFit();
return m_Header;
}
}
#else
bool[] m_Header = null;
/// <summary>
/// The visible columns
/// </summary>
[Obsolete("This property is no longer used. #from(6000.5)")]
public bool[] VisibleColumns
{
get
{
if (m_Header != null)
return m_Header;
int columnCount = 0;
if (children.Count != 0)
{
columnCount = ((Container)children[0]).children.Count;
for (int i = 1; i < children.Count; i++)
{
if (((Container)children[i]).children.Count != columnCount)
{
Debug.LogError("All rows must have the same number of children.");
return null;
}
}
}
m_Header = new bool[columnCount];
for (int i = 0; i < columnCount; i++)
m_Header[i] = true;
return m_Header;
}
}
#endif
/// <summary>
/// Method called when a children is added.
/// </summary>
/// <param name="sender">Sender widget.</param>
/// <param name="e">List of added children.</param>
protected override void OnItemAdded(ObservableList<Widget> sender, ListChangedEventArgs<Widget> e)
{
base.OnItemAdded(sender, e);
m_Header = null;
}
/// <summary>
/// Method called when a children is removed.
/// </summary>
/// <param name="sender">Sender widget.</param>
/// <param name="e">List of removed children.</param>
protected override void OnItemRemoved(ObservableList<Widget> sender, ListChangedEventArgs<Widget> e)
{
base.OnItemRemoved(sender, e);
m_Header = null;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 02feae31429679949ab4a4a40c8ad34e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,164 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
using System;
#if ENABLE_RENDERING_DEBUGGER_UI
using UnityEngine.UIElements;
namespace UnityEngine.Rendering
{
public partial class DebugUI
{
// Helper for configuring Field<T> that is implemented using a UIElements.BaseField<T>
internal static class BaseFieldHelper
{
internal static void ConfigureBaseField<T>(Field<T> widget, UIElements.BaseField<T> field)
{
field.label = widget.displayName;
field.style.flexGrow = 0f;
field.AddToClassList($"debug-window-basefield_{typeof(T).Name.ToLower()}");
field.labelElement.AddToClassList("debug-window-search-filter-target");
field.RegisterCallback<ChangeEvent<T>>(evt => widget.SetValue(evt.newValue));
widget.ScheduleTracked(field, () => field.schedule.Execute(() =>
{
field.SetValueWithoutNotify((T)Convert.ChangeType(widget.GetValue(), typeof(T)));
}).Every(100));
field.AddToClassList(UIElements.BaseField<T>.alignedFieldUssClassName);
}
}
// Helper for adding numeric fields increment/decrement buttons for Runtime UI
internal static class DebugUIStepperHelper
{
public static void AddStepper<T>(
UIElements.TextInputBaseField<T> field,
Action<T> onValueChanged,
Func<T> getValue,
Action<bool> onDecrement = null,
Action<bool> onIncrement = null)
where T : struct
{
// Create stepper buttons
var btnDecLarge = new UIElements.Button { text = "<<", focusable = false };
var btnDecSmall = new UIElements.Button { text = "<", focusable = false };
var btnIncSmall = new UIElements.Button { text = ">", focusable = false };
// Need to remove marginRight of latest button to perfectly align with the other fields
var btnIncLarge = new UIElements.Button { text = ">>", focusable = false, style = { marginRight = 0 } };
// Add button event handlers
btnDecLarge.clicked += () =>
{
if (onDecrement == null)
return;
T validatedValue;
onDecrement(true);
validatedValue = getValue();
field.SetValueWithoutNotify(validatedValue);
};
btnDecSmall.clicked += () =>
{
if (onDecrement == null)
return;
T validatedValue;
onDecrement(false);
validatedValue = getValue();
field.SetValueWithoutNotify(validatedValue);
};
btnIncSmall.clicked += () =>
{
if (onIncrement == null)
return;
T validatedValue;
onIncrement(false);
validatedValue = getValue();
field.SetValueWithoutNotify(validatedValue);
};
btnIncLarge.clicked += () =>
{
if (onIncrement == null)
return;
T validatedValue;
onIncrement(true);
validatedValue = getValue();
field.SetValueWithoutNotify(validatedValue);
};
// Make field read-only for stepper control, disable select text
field.isReadOnly = true;
// Disable test selection to better readability
field.selectAllOnFocus = false;
field.doubleClickSelectsWord = false;
field.tripleClickSelectsLine = false;
// Insert buttons into field
field.Insert(0, btnDecLarge);
field.Insert(1, btnDecSmall);
field.Add(btnIncSmall);
field.Add(btnIncLarge);
field.AddToClassList("debug-window-stepper-field");
// Style the buttons
foreach (var btn in new[] { btnDecLarge, btnDecSmall, btnIncSmall, btnIncLarge })
{
btn.AddToClassList("debug-window-stepper-button");
}
}
static int CountDecimalPlaces(float value)
{
value = Mathf.Abs(value);
if (value == 0f || float.IsNaN(value) || float.IsInfinity(value))
return 0;
int decimals = 0;
const int kMaxDecimalPlaces = 7;
const float kEpsilon = 1e-4f;
// Multiply the original value by 10 until we reach an integer value
float multipliedValue = value;
while (decimals < kMaxDecimalPlaces)
{
float nearestInteger = Mathf.Round(multipliedValue);
if (Mathf.Abs(multipliedValue - nearestInteger) <= kEpsilon)
break;
multipliedValue *= 10f;
decimals++;
}
return decimals;
}
// Rounds 'value' to the maximum decimal precision found in 'referenceValues'
internal static float RoundToPrecision(float value, params float[] referenceValues)
{
int decimalPlaces = 0;
foreach (float refValue in referenceValues)
{
decimalPlaces = Math.Max(decimalPlaces, CountDecimalPlaces(refValue));
}
double rounded = Math.Round(value, decimalPlaces, MidpointRounding.AwayFromZero);
return (float)rounded;
}
}
}
}
#endif
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 5484b35e7a724b13a637afdb13e824b0
timeCreated: 1763549507
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 332920c028664644e9e4e1bf5a1631d5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,221 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
using System;
#if UNITY_EDITOR
using UnityEditor;
#endif
#if ENABLE_RENDERING_DEBUGGER_UI
using UnityEngine.UIElements;
#endif
namespace UnityEngine.Rendering
{
public partial class DebugUI
{
// Root panel class - we don't want to extend Container here because we need a clear
// separation between debug panels and actual widgets
/// <summary>
/// Root panel class.
/// </summary>
public class Panel : IContainer, IComparable<Panel>
{
#if ENABLE_RENDERING_DEBUGGER_UI
private VisualElement m_HelpButton;
/// <inheritdoc/>
public VisualElement Create(DebugUI.Context context)
{
VisualElement container = new GroupBox()
{
text = displayName,
name = displayName + "_Content"
};
var label = container.Q<Label>(className: "unity-group-box__label");
label.AddToClassList("debug-window-header-title");
label.AddToClassList("debug-window-search-filter-target");
label.AddToClassList("debug-window-header-row");
#if UNITY_EDITOR
if (EditorGUIUtility.isProSkin)
{
container.AddToClassList("dark");
}
m_HelpButton = new UIElements.Button(() => Help.BrowseURL(documentationUrl));
m_HelpButton.tooltip = $"Open Reference for {displayName} debugger panel.";
m_HelpButton.SetEnabled(!string.IsNullOrEmpty(documentationUrl));
m_HelpButton.AddToClassList("debug-window-help-button");
label.Add(m_HelpButton);
#endif
container.AddToClassList("debug-window-tab-content");
container.AddToClassList("unity-inspector-element");
var content = new VisualElement();
foreach (var child in children)
{
if (context == Context.Editor && child.isRuntimeOnly)
continue;
if (context.IsAnyRuntimeContext() && child.isEditorOnly)
continue;
var childUIElement = child.ToVisualElement(context);
if (childUIElement != null)
content.Add(childUIElement);
}
container.Add(content);
return container;
}
#endif
/// <summary>
/// Widget flags for this panel.
/// </summary>
public Flags flags { get; set; }
/// <summary>
/// Display name of the panel.
/// </summary>
public string displayName { get; set; }
/// <summary>
/// Group index of the panel.
/// </summary>
public int groupIndex { get; set; }
/// <summary>
/// Path of the panel.
/// </summary>
public string queryPath { get { return displayName; } }
/// <summary>
/// Specify if the panel is editor only.
/// </summary>
public bool isEditorOnly { get { return (flags & Flags.EditorOnly) != 0; } }
/// <summary>
/// Specify if the panel is runtime only.
/// </summary>
public bool isRuntimeOnly { get { return (flags & Flags.RuntimeOnly) != 0; } }
/// <summary>
/// Returns true if the panel is inactive in the editor.
/// </summary>
public bool isInactiveInEditor { get { return (isRuntimeOnly && !Application.isPlaying); } }
/// <summary>
/// Returns true if the panel should always be updated.
/// </summary>
[Obsolete("This is no longer used. #from(6000.5)")]
public bool editorForceUpdate => false;
/// <summary>
/// List of children.
/// </summary>
public ObservableList<Widget> children { get; private set; }
/// <summary>
/// Callback used when the panel is set dirty.
/// </summary>
public event Action<Panel> onSetDirty = delegate { };
#if UNITY_EDITOR
private string m_DocumentationURL;
public string documentationUrl {
get => m_DocumentationURL;
set
{
if (m_DocumentationURL == value)
return;
m_DocumentationURL = value;
#if ENABLE_RENDERING_DEBUGGER_UI
m_HelpButton?.SetEnabled(!string.IsNullOrEmpty(m_DocumentationURL));
#endif
}
}
#endif
/// <summary>
/// Constructor.
/// </summary>
public Panel()
{
children = new ObservableList<Widget>(0, (widget, widget1) => widget.order.CompareTo(widget1.order));
children.ItemAdded += OnItemAdded;
children.ItemRemoved += OnItemRemoved;
}
/// <summary>
/// Callback used when a child is added.
/// </summary>
/// <param name="sender">Sender widget.</param>
/// <param name="e">List of added children.</param>
protected virtual void OnItemAdded(ObservableList<Widget> sender, ListChangedEventArgs<Widget> e)
{
if (e.item != null)
{
e.item.panel = this;
e.item.parent = this;
}
SetDirty();
}
/// <summary>
/// Callback used when a child is removed.
/// </summary>
/// <param name="sender">Sender widget.</param>
/// <param name="e">List of removed children.</param>
protected virtual void OnItemRemoved(ObservableList<Widget> sender, ListChangedEventArgs<Widget> e)
{
if (e.item != null)
{
e.item.panel = null;
e.item.parent = null;
}
SetDirty();
}
/// <summary>
/// Set the panel dirty.
/// </summary>
public void SetDirty()
{
int numChildren = children.Count;
for (int i = 0; i < numChildren; i++)
children[i].GenerateQueryPath();
onSetDirty(this);
}
/// <summary>
/// Comparison function.
/// </summary>
/// <param name="other">Panel to compare to.</param>
/// <returns>True if the panels share the same group index.</returns>
int IComparable<Panel>.CompareTo(Panel other) => other == null ? 1 : groupIndex.CompareTo(other.groupIndex);
internal bool TryFindChild<T>(string childDisplayName, out T foundChild)
where T : DebugUI.Widget
{
foundChild = null;
if (!string.IsNullOrEmpty(childDisplayName))
{
foreach (var child in children)
{
if (child.displayName.Equals(childDisplayName) && child is T castedChild)
{
foundChild = castedChild;
break;
}
}
}
return foundChild != null;
}
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9a33c6b643214f847b2e0cf1721a64db
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,821 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
using System;
using System.Collections.Generic;
using UnityEngine.Assertions;
#if ENABLE_RENDERING_DEBUGGER_UI
using UnityEngine.UIElements;
#endif
namespace UnityEngine.Rendering
{
#if ENABLE_RENDERING_DEBUGGER_UI
internal static class DebugUIExtensions
{
public static List<(Label, VisualElement)> CreatePanels(List<DebugUI.Panel> panels, DebugUI.Context context)
{
List<(Label, VisualElement)> returnList = new();
foreach (var p in panels)
{
var tab = new Label(p.displayName)
{
name = p.displayName + "_Tab",
focusable = true
};
tab.AddToClassList("debug-window-tab-item");
var panel = p.Create(context);
returnList.Add((tab, panel));
}
return returnList;
}
/// <summary>
/// Utility to add a scheduled item to the panel's tracker so it can be disabled when the widget is not visible.
/// </summary>
/// <param name="widget">Widget that contains the scheduler</param>
/// <param name="element">VisualElement whose scheduler is used to create the ScheduledItem</param>
/// <param name="scheduledItemCreator">Callback that creates the ScheduledItem.</param>
internal static void ScheduleTracked(this DebugUI.Widget widget, VisualElement element, Func<IVisualElementScheduledItem> scheduledItemCreator)
{
ScheduleTracked(widget, element, widget.m_Context, scheduledItemCreator);
}
/// <summary>
/// Utility to add a scheduled item to the panel's tracker, using an explicit context for Add/Remove
/// rather than reading widget.m_Context lazily. Use this when the same widget instance may be
/// rendered into multiple panels (which mutates m_Context), and you want this scheduled item
/// tracked under a specific context.
/// </summary>
internal static void ScheduleTracked(this DebugUI.Widget widget, VisualElement element, DebugUI.Context context, Func<IVisualElementScheduledItem> scheduledItemCreator)
{
element.RegisterCallback<AttachToPanelEvent>(_ =>
{
var scheduledItem = scheduledItemCreator.Invoke();
DebugManager.instance.schedulerTracker.Add(context, widget, scheduledItem);
scheduledItem.Pause(); // All schedulers start paused, and are enabled/disabled by DebugManager based on widget visibility.
});
element.RegisterCallback<DetachFromPanelEvent>(_ =>
{
DebugManager.instance.schedulerTracker.Remove(context, widget, element);
});
}
public static bool IsAnyRuntimeContext(this DebugUI.Context context)
{
return (context == DebugUI.Context.Runtime) ||
(context == DebugUI.Context.RuntimePersistent);
}
}
#endif
/// <summary>
/// The `DebugUI` class defines a collection of debug UI components that are useful for debugging and profiling Rendering features
/// </summary>
/// <remarks>
/// Widgets can be added to the UI, customized, and manipulated at runtime or during editor sessions. The class supports various
/// widget types, including buttons, read-only value fields, and progress bars. It also provides mechanisms for organizing these
/// widgets into containers. Each widget has a set of flags to control its visibility and behavior depending on whether it is
/// used in the editor or at runtime. The widgets can also contain callbacks for conditional visibility at runtime.
/// Important Notes:
/// - Widgets can be nested inside containers, allowing for organized groupings of debug UI elements.
/// - Widgets may be runtime-only, editor-only, or both, allowing them to behave differently depending on the application's
/// state (e.g., whether it is in the editor or playing at runtime).
/// - `DebugUI` also includes helper methods for widget initialization, such as compact initialization using the `NameAndTooltip` struct.
///
/// This API lets you do the following:
/// - Specify widget behavior such as "EditorOnly" and "RuntimeOnly".
/// - Show dynamic data with optional formatting.
/// - Specify delegate functions to show or hide widgets
///
/// <b>Related Resources:</b>
/// - [Debug UI Overview](https://docs.unity3d.com/6000.0/Documentation/Manual/urp/features/rendering-debugger.html)
/// - [Rendering Debugger Controls](https://docs.unity3d.com/6000.0/Documentation/Manual/urp/features/rendering-debugger-add-controls.html).
/// - [Using Rendering Debugger](https://docs.unity.cn/Packages/com.unity.render-pipelines.high-definition@16.0/manual/use-the-rendering-debugger.html).
/// </remarks>
/// <example>
/// <code>
/// using UnityEngine;
/// using UnityEngine.Rendering;
///
/// [ExecuteInEditMode]
/// public class DebugUIExample : MonoBehaviour
/// {
/// void OnEnable()
/// {
/// // Create a button widget that logs a message when you select it
/// DebugUI.Button button = new DebugUI.Button
/// {
/// displayName = "Log Message Button",
/// action = () => Debug.Log("Button selected")
/// };
///
/// // Create a value widget that displays the current time
/// DebugUI.Value timeValue = new DebugUI.Value
/// {
/// // Set the display label
/// displayName = "Current Time",
///
/// // Set the format for the time
/// getter = () => System.DateTime.Now.ToString("HH:mm:ss"),
///
/// // Set the value to refresh every second
/// refreshRate = 1f
/// };
///
/// // Add widgets a new Rendering Debugger panel
/// var panel = DebugManager.instance.GetPanel("My Custom Panel", createIfNull: true);
///
/// // Add the widgets to the panel
/// panel.children.Add(button);
/// panel.children.Add(timeValue);
/// }
/// }
/// </code>
/// </example>
public partial class DebugUI
{
/// <summary>
/// A column of checkboxes for enabling and disabling flags.
/// </summary>
[Flags]
public enum Flags
{
/// <summary>
/// None.
/// </summary>
None = 0,
/// <summary>
/// This widget is Editor only.
/// </summary>
EditorOnly = 1 << 1,
/// <summary>
/// This widget is Runtime only.
/// </summary>
RuntimeOnly = 1 << 2,
/// <summary>
/// This widget will force the Debug Editor Window refresh.
/// </summary>
[Obsolete("This is no longer used. #from(6000.5)")]
EditorForceUpdate = 1 << 3,
/// <summary>
/// This widget will appear in the section "Frequently Used"
/// </summary>
[Obsolete("This is no longer used. #from(6000.5)")]
FrequentlyUsed = 1 << 4
}
/// <summary>
/// Context in which the widget is used.
/// </summary>
public enum Context
{
/// <summary>Invalid context</summary>
Invalid = -1,
/// <summary>Editor context</summary>
Editor = 0,
/// <summary>Runtime context</summary>
Runtime = 1,
/// <summary>Runtime persistent context</summary>
RuntimePersistent = 2,
/// <summary>Count</summary>
Count
}
/// <summary>
/// Base class for all debug UI widgets.
/// </summary>
public abstract class Widget
{
/// <summary>
/// The order of the widget
/// </summary>
public int order { get; set; } = 0;
// Set to null until it's added to a panel, be careful
/// <summary>
/// Panels containing the widget.
/// </summary>
protected Panel m_Panel;
/// <summary>
/// Panels containing the widget.
/// </summary>
public virtual Panel panel
{
get { return m_Panel; }
internal set { m_Panel = value; }
}
#if ENABLE_RENDERING_DEBUGGER_UI
/// <summary>
/// Creates the VisualElement for the widget that will be added to the panel UI.
/// </summary>
/// <returns>The widget's VisualElement</returns>
protected abstract VisualElement Create();
/// <summary>
/// Controls the way the widget is hidden.
/// When set to false (default), the widget is removed from the layout (DisplayStyle.None).
/// When set to true, the widget is not rendered but takes space in the layout (Visibility.Hidden).
/// </summary>
internal bool keepLayoutWhenHidden { private get; set; }
internal bool m_IsHiddenBySearchFilter;
internal string m_AdditionalSearchText = string.Empty;
protected internal bool m_RequiresLegacyStateHandling = false;
void UpdateElementVisibility()
{
if (m_IsHiddenBySearchFilter)
{
m_VisualElement.style.display = DisplayStyle.None;
return;
}
if (keepLayoutWhenHidden)
{
m_VisualElement.style.display = DisplayStyle.Flex;
m_VisualElement.style.visibility = isHidden ? Visibility.Hidden : Visibility.Visible;
}
else
{
m_VisualElement.style.display = isHidden ? DisplayStyle.None : DisplayStyle.Flex;
}
}
int ComputeIndentationLevel()
{
int indentLevel = 0;
Container currentParent = parent as Container;
while (currentParent != null)
{
indentLevel++;
currentParent = currentParent.parent as Container;
}
return indentLevel;
}
// Once the element is attached to the panel, recalculate the base field label width
// whenever the window is resized, or the tab/panel divider is moved.
internal void CustomAlignBaseFieldLabelWhenResized(VisualElement label)
{
if (m_Context == Context.Editor)
{
label.RegisterCallbackOnce<AttachToPanelEvent>(panelEvt =>
{
// Use the tab container element (we want to exclude tabs)
var contentPanel = panelEvt.destinationPanel.visualTree.Q<VisualElement>("debug-window-tab-container");
contentPanel.RegisterCallback<GeometryChangedEvent>(geometryEvt =>
{
CustomAlignBaseFieldLabel(label, geometryEvt.newRect.width);
});
});
}
}
// We need to do base field label alignment manually in two cases:
// 1. In runtime context, where UIE.BaseField<T> alignment logic is disabled
// 2. In any context, for elements that do not inherit from UIE.BaseField<T>, but we still want
// to align them, such as DebugUI.Value and DebugUI.ProgressBar.
internal void CustomAlignBaseFieldLabel(VisualElement label, float width = 0f)
{
if (label != null)
{
int indentationLevel = ComputeIndentationLevel();
if (m_Context == Context.Runtime)
{
// NOTE: In the runtime we don't care about the window width, just use a fixed label width.
const float kLabelBaseWidth = 330f;
const float kIndentSize = 8f; // Should match .debug-window-container-content margin-left
float totalPadding = indentationLevel*kIndentSize;
label.style.minWidth = kLabelBaseWidth - totalPadding;
}
else
{
// This is trying to match the BaseField field alignment logic as closely as possible.
// For the magic numbers & full logic see UIElements/Core/Controls/InputField/BaseField.cs
const float kLabelWidthRatio = 0.45f; // Should match UIElements.BaseField m_LabelWidthRatio
const float kLabelExtraPadding = 37.0f; // Should match UIElements.BaseField m_LabelExtraPadding
const float kIndentSize = 8f;
float totalPadding = indentationLevel*kIndentSize + kLabelExtraPadding;
label.style.minWidth = Mathf.Ceil(width * kLabelWidthRatio) - totalPadding;
}
}
}
internal VisualElement ToVisualElement(Context context)
{
m_Context = context;
m_VisualElement = Create();
if (m_VisualElement == null)
{
Debug.LogWarning($"Unable to create a Visual Element for type {GetType()}");
return null;
}
m_VisualElement.AddToClassList("unity-inspector-element");
m_VisualElement.name = displayName;
m_VisualElement.tooltip = tooltip;
#if UNITY_EDITOR
// Support for legacy state handling
if (this is ISupportsLegacyStateHandling legacyStateWidget)
{
m_RequiresLegacyStateHandling = legacyStateWidget.RequiresLegacyStateHandling();
}
#endif
UpdateElementVisibility();
this.ScheduleTracked(m_VisualElement, () => m_VisualElement.schedule.Execute(UpdateElementVisibility).Every(100));
// In runtime window, figure out indentation level to ensure field alignment
if (context == Context.Runtime)
{
m_VisualElement.RegisterCallbackOnce<AttachToPanelEvent>(_ =>
{
CustomAlignBaseFieldLabel(m_VisualElement.Q<Label>(classes: "unity-base-field__label"));
});
}
// In runtime UI, attach focus handler for keyboard navigation & pinning
if (context.IsAnyRuntimeContext())
{
VisualElement focusTarget = m_VisualElement;
if (this is Foldout)
{
focusTarget = m_VisualElement.Q<Toggle>();
}
focusTarget?.RegisterCallback<FocusInEvent>(evt =>
{
var targetElement = evt.target as VisualElement;
if (DebugManager.instance.m_RuntimeDebugWindow?.IsPopupOpen() ?? false)
{
if (targetElement != null)
{
var elementThatGetFocus = evt.target as VisualElement;
var focusController = targetElement.panel?.focusController;
if (focusController != null)
{
// Blur the entering focus to restore it to the previous one.
elementThatGetFocus.Blur();
}
}
evt.StopImmediatePropagation();
}
else if (targetElement != null)
{
// Ensure focused element is visible in the scroll view
var scrollView = targetElement.GetFirstAncestorOfType<ScrollView>();
scrollView.ScrollTo(targetElement);
}
}, TrickleDown.TrickleDown);
focusTarget?.RegisterCallback<FocusEvent>(_ =>
{
DebugManager.instance.selectedWidget = this;
});
}
return m_VisualElement;
}
// Root visual element of the widget, valid after it has been initialized by calling ToVisualElement.
internal VisualElement m_VisualElement = null;
// Context of the widget, valid after it has been initialized by calling ToVisualElement.
internal Context m_Context = Context.Invalid;
#endif
/// <summary>
/// Increment button implementation for numeric fields
/// </summary>
/// <param name="fast">Whether to use fast increment</param>
internal virtual void OnIncrement(bool fast) { }
/// <summary>
/// Decrement button implementation for numeric fields
/// </summary>
/// <param name="fast">Whether to use fast decrement</param>
internal virtual void OnDecrement(bool fast) { }
/// <summary>
/// Parent container.
/// </summary>
protected IContainer m_Parent;
/// <summary>
/// Parent container.
/// </summary>
public virtual IContainer parent
{
get { return m_Parent; }
internal set { m_Parent = value; }
}
/// <summary>
/// Flags for the widget.
/// </summary>
public Flags flags { get; set; }
/// <summary>
/// Display name.
/// </summary>
public string displayName { get; set; }
/// <summary>
/// Tooltip.
/// </summary>
public string tooltip { get; set; }
/// <summary>
/// Path of the widget.
/// </summary>
public string queryPath { get; private set; }
/// <summary>
/// True if the widget is Editor only.
/// </summary>
public bool isEditorOnly => flags.HasFlag(Flags.EditorOnly);
/// <summary>
/// True if the widget is Runtime only.
/// </summary>
public bool isRuntimeOnly => flags.HasFlag(Flags.RuntimeOnly);
/// <summary>
/// True if the widget is inactive in the editor (i.e. widget is runtime only and the application is not 'Playing').
/// </summary>
public bool isInactiveInEditor => (isRuntimeOnly && !Application.isPlaying);
/// <summary>
/// Optional delegate that can be used to conditionally hide widgets at runtime (e.g. due to state of other widgets).
/// </summary>
public Func<bool> isHiddenCallback;
/// <summary>
/// If <see cref="isHiddenCallback">shouldHideDelegate</see> has been set and returns true, the widget is hidden from the UI.
/// </summary>
public bool isHidden => isHiddenCallback?.Invoke() ?? false;
internal virtual void GenerateQueryPath()
{
queryPath = displayName.Trim();
if (m_Parent != null)
queryPath = m_Parent.queryPath + " -> " + queryPath;
}
/// <summary>
/// Helper struct to allow more compact initialization of widgets.
/// </summary>
public struct NameAndTooltip
{
/// <summary>
/// The name
/// </summary>
public string name;
/// <summary>
/// The tooltip
/// </summary>
public string tooltip;
}
/// <summary>
/// Helper setter to allow more compact initialization of widgets.
/// </summary>
public NameAndTooltip nameAndTooltip
{
set
{
displayName = value.name;
tooltip = value.tooltip;
}
}
}
/// <summary>
/// Interface for widgets that can contain other widgets.
/// </summary>
public interface IContainer
{
/// <summary>
/// List of children of the container.
/// </summary>
ObservableList<Widget> children { get; }
/// <summary>
/// Display name of the container.
/// </summary>
string displayName { get; set; }
/// <summary>
/// Path of the container.
/// </summary>
string queryPath { get; }
}
/// <summary>
/// Any widget that implements this will be considered for serialization (only if the setter is set and thus is not read-only)
/// </summary>
[Obsolete("This interface is no longer used. #from(6000.5)")]
public interface IValueField
{
/// <summary>
/// Return the value of the field.
/// </summary>
/// <returns>Value of the field.</returns>
[Obsolete("This method is no longer used. #from(6000.5)")]
object GetValue();
/// <summary>
/// Set the value of the field.
/// </summary>
/// <param name="value">Input value.</param>
[Obsolete("This method is no longer used. #from(6000.5)")]
void SetValue(object value);
/// <summary>
/// Function used to validate the value when setting it.
/// </summary>
/// <param name="value">Input value.</param>
/// <returns>Validated value.</returns>
[Obsolete("This method is no longer used. #from(6000.5)")]
object ValidateValue(object value);
}
// Miscellaneous
/// <summary>
/// Button widget.
/// </summary>
public class Button : Widget
{
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var button = new UIElements.Button
{
text = displayName
};
button.AddToClassList("debug-window-button");
button.AddToClassList("debug-window-search-filter-target");
button.clicked += () => action();
return button;
}
#endif
/// <summary>
/// Action performed by the button.
/// </summary>
public Action action { get; set; }
}
/// <summary>
/// A field that displays a read-only value.
/// </summary>
public class Value : Widget
{
/// <summary>
/// If is a header, and it should be displayed with bold font
/// </summary>
public bool isHeader { get; set; }
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var container = new VisualElement();
container.AddToClassList("debug-window-value-container");
var nameLabel = new Label() { text = displayName };
nameLabel.AddToClassList("debug-window-value-name");
nameLabel.AddToClassList("debug-window-search-filter-target");
var valueLabel = new Label() { text = FormatString(GetValue()) };
valueLabel.AddToClassList("debug-window-value-value");
valueLabel.focusable = true;
if (isHeader)
{
valueLabel.style.unityFontStyleAndWeight = FontStyle.Bold;
}
this.ScheduleTracked(valueLabel, () => valueLabel.schedule.Execute(() =>
{
valueLabel.text = FormatString(GetValue());
}).Every((long)(refreshRate * 1000.0f)));
CustomAlignBaseFieldLabelWhenResized(nameLabel);
container.Add(nameLabel);
container.Add(valueLabel);
return container;
}
#endif
/// <summary>
/// Getter for the Value.
/// </summary>
public Func<object> getter { get; set; }
/// <summary>
/// Refresh rate for the read-only value (runtime only)
/// </summary>
public float refreshRate = 0.1f;
/// <summary>
/// Optional C# numeric format string, using following syntax: "{0[:numericFormatString]}"
/// See https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings
/// and https://docs.microsoft.com/en-us/dotnet/standard/base-types/composite-formatting
/// Example: 123.45678 with formatString "{0:F2} ms" --> "123.45 ms".
/// </summary>
public string formatString = null;
/// <summary>
/// Constructor.
/// </summary>
public Value()
{
displayName = "";
}
/// <summary>
/// Returns the value of the widget.
/// </summary>
/// <returns>The value of the widget.</returns>
public virtual object GetValue()
{
Assert.IsNotNull(getter);
return getter();
}
/// <summary>
/// Returns the formatted value string for display purposes.
/// </summary>
/// <param name="value">Value to be formatted.</param>
/// <returns>The formatted value string.</returns>
public virtual string FormatString(object value)
{
return string.IsNullOrEmpty(formatString) ? $"{value}" : string.Format(formatString, value);
}
}
/// <summary>
/// A progress bar that displays values between 0% and 100%.
/// </summary>
public class ProgressBarValue : Value
{
/// <summary>
/// Minimum value.
/// </summary>
public float min = 0f;
/// <summary>
/// Maximum value.
/// </summary>
public float max = 1f;
/// <summary>
/// Get the current progress string, remapped to [0, 1] range, representing the progress between min and max.
/// </summary>
/// <param name="value">Value to be formatted.</param>
/// <returns>Formatted progress percentage string between 0% and 100%.</returns>
public override string FormatString(object value)
{
static float Remap01(float v, float x0, float y0) => (v - x0) / (y0 - x0);
float clamped = Mathf.Clamp((float)value, min, max);
float percentage = Remap01(clamped, min, max);
return $"{percentage:P1}";
}
#if ENABLE_RENDERING_DEBUGGER_UI
protected override VisualElement Create()
{
var container = new VisualElement();
container.AddToClassList(UIElements.BaseField<float>.ussClassName);
container.style.flexDirection = FlexDirection.Row;
var label = new Label();
label.AddToClassList(UIElements.BaseField<float>.labelUssClassName);
label.text = displayName;
container.Add(label);
var progressBar = new UIElements.ProgressBar()
{
lowValue = min,
highValue = max
};
progressBar.style.flexGrow = 1;
progressBar.schedule.Execute(() =>
{
progressBar.title = FormatString(GetValue());
progressBar.value = (float)GetValue();
}).Every((long)(refreshRate * 1000.0f));
CustomAlignBaseFieldLabelWhenResized(label);
container.AddToClassList(UIElements.BaseField<float>.alignedFieldUssClassName);
container.Add(progressBar);
return container;
}
#endif
}
/// <summary>
/// An array of read-only values that Unity displays in a horizontal row.
/// </summary>
public class ValueTuple : Widget
{
internal const int k_LabelWidthEditor = 280;
internal const int k_LabelWidthRuntime = 340;
internal static int GetLabelWidth(Context ctx) => ctx == Context.Editor ? k_LabelWidthEditor : k_LabelWidthRuntime;
/// <summary>
/// If is a header, and it should be displayed with bold font
/// </summary>
public bool isHeader { get; set; }
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var valueContainer = new UIElements.VisualElement();
valueContainer.AddToClassList("debug-window-valuetuple");
var label = new Label(displayName) { style = { minWidth = ValueTuple.GetLabelWidth(m_Context) }, };
label.AddToClassList("debug-window-search-filter-target");
if (isHeader)
label.style.unityFontStyleAndWeight = FontStyle.Bold;
valueContainer.Add(label);
if (!isHeader)
valueContainer.focusable = true;
foreach (var value in values)
{
value.isHeader = isHeader;
var valueVisualElement = value.ToVisualElement(m_Context);
var valueLabel = valueVisualElement.Q<Label>(className: "debug-window-value-name");
if (valueLabel != null)
valueLabel.style.display = DisplayStyle.None; // With ValueTuples we don't want to show individual value names
valueContainer.Add(valueVisualElement);
}
return valueContainer;
}
#endif
/// <summary>
/// Number of elements in the tuple.
/// </summary>
public int numElements
{
get
{
Assert.IsTrue(values.Length > 0);
return values.Length;
}
}
/// <summary>
/// Value widgets.
/// </summary>
public Value[] values;
/// <summary>
/// Refresh rate for the read-only values (runtime only)
/// </summary>
public float refreshRate
{
get
{
if (values != null && values.Length > 0 && values[0] != null)
{
return values[0].refreshRate;
}
return 0.1f;
}
}
/// <summary>
/// The currently pinned element index, or -1 if none are pinned.
/// </summary>
public int pinnedElementIndex = -1;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4cce618ad8a6d934dbdc631f979b3aa6
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,126 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
#if ENABLE_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM_PACKAGE
#define USE_INPUT_SYSTEM
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.EnhancedTouch;
#endif
using System;
using System.Collections;
using System.Diagnostics;
namespace UnityEngine.Rendering
{
[CoreRPHelpURL("Rendering-Debugger")]
[AddComponentMenu("")] // Hide from Add Component menu
class DebugUpdater : MonoBehaviour
{
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterSceneLoad)]
static void RuntimeInit()
{
#if UNITY_ENABLE_CHECKS
if (DebugManager.instance.enableRuntimeUI)
EnableRuntime();
#endif
}
internal static void SetEnabled(bool enabled)
{
if (enabled)
EnableRuntime();
else
DisableRuntime();
}
static void EnableRuntime()
{
#if USE_INPUT_SYSTEM
// With Input System, we don't need the DebugUpdater GameObject as we can just use input callbacks.
DebugManager.instance.EnableInputCallbacks();
#else
// With old InputManager, we need the DebugUpdater GameObject to poll for input in Update().
if (s_Instance != null)
return;
var go = new GameObject { name = "[Debug Updater]" };
s_Instance = go.AddComponent<DebugUpdater>();
DontDestroyOnLoad(go);
#endif
}
static void DisableRuntime()
{
#if USE_INPUT_SYSTEM
DebugManager.instance.DisableInputCallbacks();
#else
DebugManager debugManager = DebugManager.instance;
debugManager.displayRuntimeUI = false;
debugManager.displayPersistentRuntimeUI = false;
if (s_Instance != null)
{
CoreUtils.Destroy(s_Instance.gameObject);
s_Instance = null;
}
#endif
}
#if !USE_INPUT_SYSTEM
static DebugUpdater s_Instance = null;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
s_Instance = null;
}
#endif
void Update()
{
DebugManager debugManager = DebugManager.instance;
debugManager.UpdateActions();
if (debugManager.GetAction(DebugAction.EnableDebugMenu) != 0.0f ||
debugManager.GetActionToggleDebugMenuWithTouch())
{
debugManager.displayRuntimeUI = !debugManager.displayRuntimeUI;
}
#if ENABLE_RENDERING_DEBUGGER_UI
if (debugManager.displayRuntimeUI)
{
if (debugManager.m_RuntimeDebugWindow.IsPopupOpen())
return;
if (debugManager.GetAction(DebugAction.ResetAll) != 0.0f)
debugManager.Reset();
if (debugManager.GetAction(DebugAction.MakePersistent) != 0.0f)
debugManager.TogglePersistent();
if (debugManager.GetAction(DebugAction.NextDebugPanel) != 0.0f)
debugManager.m_RuntimeDebugWindow.SelectNextPanel();
if (debugManager.GetAction(DebugAction.PreviousDebugPanel) != 0.0f)
debugManager.m_RuntimeDebugWindow.SelectPreviousPanel();
float moveHorizontal = debugManager.GetAction(DebugAction.MoveHorizontal);
if (moveHorizontal != 0.0f)
{
bool fast = DebugManager.instance.GetAction(DebugAction.Multiplier) != 0f;
if (moveHorizontal < 0f)
DebugManager.instance.selectedWidget.OnDecrement(fast);
else
DebugManager.instance.selectedWidget.OnIncrement(fast);
}
}
#endif
}
#endif
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 6fa749f6d8ed4b441af9aa005fe0f895
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 0f240cc177d08124a9694021c19c0dc4
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,131 @@
using System;
using System.Collections.Generic;
namespace UnityEngine.Rendering
{
/// <summary>
/// Represents a system bottleneck, meaning the factor that is most dominant in determining
/// the total frame time.
/// </summary>
internal enum PerformanceBottleneck
{
Indeterminate, // Cannot be determined
PresentLimited, // Limited by presentation (vsync or framerate cap)
CPU, // Limited by CPU (main and/or render thread)
GPU, // Limited by GPU
Balanced, // Limited by both CPU and GPU, i.e. well balanced
}
/// <summary>
/// BottleneckHistogram represents the distribution of bottlenecks over the Bottleneck History Window,
/// the size of which is determined by <see cref="DebugFrameTiming.bottleneckHistorySize"/>.
/// </summary>
internal struct BottleneckHistogram
{
internal float PresentLimited;
internal float CPU;
internal float GPU;
internal float Balanced;
};
/// <summary>
/// Container class for bottleneck history with helper to calculate histogram.
/// </summary>
internal class BottleneckHistory
{
public BottleneckHistory(int initialCapacity)
{
m_Bottlenecks.Capacity = initialCapacity;
}
List<PerformanceBottleneck> m_Bottlenecks = new();
internal BottleneckHistogram Histogram;
internal void DiscardOldSamples(int historySize)
{
Debug.Assert(historySize > 0, "Invalid sampleHistorySize");
while (m_Bottlenecks.Count >= historySize)
m_Bottlenecks.RemoveAt(0);
m_Bottlenecks.Capacity = historySize;
}
internal void AddBottleneckFromAveragedSample(FrameTimeSample frameHistorySampleAverage)
{
var bottleneck = DetermineBottleneck(frameHistorySampleAverage);
m_Bottlenecks.Add(bottleneck);
}
internal void ComputeHistogram()
{
var stats = new BottleneckHistogram();
for (int i = 0; i < m_Bottlenecks.Count; i++)
{
switch (m_Bottlenecks[i])
{
case PerformanceBottleneck.Balanced:
stats.Balanced++;
break;
case PerformanceBottleneck.CPU:
stats.CPU++;
break;
case PerformanceBottleneck.GPU:
stats.GPU++;
break;
case PerformanceBottleneck.PresentLimited:
stats.PresentLimited++;
break;
}
}
stats.Balanced /= m_Bottlenecks.Count;
stats.CPU /= m_Bottlenecks.Count;
stats.GPU /= m_Bottlenecks.Count;
stats.PresentLimited /= m_Bottlenecks.Count;
Histogram = stats;
}
static PerformanceBottleneck DetermineBottleneck(FrameTimeSample s)
{
const float kNearFullFrameTimeThresholdPercent = 0.2f;
const float kNonZeroPresentWaitTimeMs = 0.5f;
if (s.GPUFrameTime == 0 || s.MainThreadCPUFrameTime == 0) // In direct mode, render thread doesn't exist
return PerformanceBottleneck.Indeterminate; // Missing data
float fullFrameTimeWithMargin = (1f - kNearFullFrameTimeThresholdPercent) * s.FullFrameTime;
// GPU time is close to frame time, CPU times are not
if (s.GPUFrameTime > fullFrameTimeWithMargin &&
s.MainThreadCPUFrameTime < fullFrameTimeWithMargin &&
s.RenderThreadCPUFrameTime < fullFrameTimeWithMargin)
return PerformanceBottleneck.GPU;
// One of the CPU times is close to frame time, GPU is not
if (s.GPUFrameTime < fullFrameTimeWithMargin &&
(s.MainThreadCPUFrameTime > fullFrameTimeWithMargin ||
s.RenderThreadCPUFrameTime > fullFrameTimeWithMargin))
return PerformanceBottleneck.CPU;
// Main thread waited due to Vsync or target frame rate
if (s.MainThreadCPUPresentWaitTime > kNonZeroPresentWaitTimeMs)
{
// None of the times are close to frame time
if (s.GPUFrameTime < fullFrameTimeWithMargin &&
s.MainThreadCPUFrameTime < fullFrameTimeWithMargin &&
s.RenderThreadCPUFrameTime < fullFrameTimeWithMargin)
return PerformanceBottleneck.PresentLimited;
}
return PerformanceBottleneck.Balanced;
}
internal void Clear()
{
m_Bottlenecks.Clear();
Histogram = new BottleneckHistogram();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 331aa10d229f4c2fb9a9240812fb45d6
timeCreated: 1629185832
@@ -0,0 +1,133 @@
using System;
using System.Collections.Generic;
namespace UnityEngine.Rendering
{
/// <summary>
/// Represents timing data captured from a single frame.
/// </summary>
internal struct FrameTimeSample
{
internal float FramesPerSecond;
internal float FullFrameTime;
internal float MainThreadCPUFrameTime;
internal float MainThreadCPUPresentWaitTime;
internal float RenderThreadCPUFrameTime;
internal float GPUFrameTime;
internal FrameTimeSample(float initValue)
{
FramesPerSecond = initValue;
FullFrameTime = initValue;
MainThreadCPUFrameTime = initValue;
MainThreadCPUPresentWaitTime = initValue;
RenderThreadCPUFrameTime = initValue;
GPUFrameTime = initValue;
}
};
/// <summary>
/// Container class for sample history with helpers to calculate min, max and average in one pass.
/// </summary>
class FrameTimeSampleHistory
{
public FrameTimeSampleHistory(int initialCapacity)
{
m_Samples.Capacity = initialCapacity;
}
List<FrameTimeSample> m_Samples = new();
internal FrameTimeSample SampleAverage;
internal FrameTimeSample SampleMin;
internal FrameTimeSample SampleMax;
internal void Add(FrameTimeSample sample)
{
m_Samples.Add(sample);
}
// Helper functions
static readonly Func<float, float, float> s_SampleValueAdd = (float value, float other) =>
{
return value + other;
};
static readonly Func<float, float, float> s_SampleValueMin = (float value, float other) =>
{
return other > 0 ? Mathf.Min(value, other) : value;
};
static readonly Func<float, float, float> s_SampleValueMax = (float value, float other) =>
{
return Mathf.Max(value, other);
};
static readonly Func<float, float, float> s_SampleValueCountValid = (float value, float other) =>
{
return other > 0 ? value + 1 : value;
};
static readonly Func<float, float, float> s_SampleValueEnsureValid = (float value, float other) =>
{
return other > 0 ? value : 0;
};
static readonly Func<float, float, float> s_SampleValueDivide = (float value, float other) =>
{
return other > 0 ? value / other : 0;
};
internal void ComputeAggregateValues()
{
void ForEachSampleMember(ref FrameTimeSample aggregate, FrameTimeSample sample, Func<float, float, float> func)
{
aggregate.FramesPerSecond = func(aggregate.FramesPerSecond, sample.FramesPerSecond);
aggregate.FullFrameTime = func(aggregate.FullFrameTime, sample.FullFrameTime);
aggregate.MainThreadCPUFrameTime = func(aggregate.MainThreadCPUFrameTime, sample.MainThreadCPUFrameTime);
aggregate.MainThreadCPUPresentWaitTime = func(aggregate.MainThreadCPUPresentWaitTime, sample.MainThreadCPUPresentWaitTime);
aggregate.RenderThreadCPUFrameTime = func(aggregate.RenderThreadCPUFrameTime, sample.RenderThreadCPUFrameTime);
aggregate.GPUFrameTime = func(aggregate.GPUFrameTime, sample.GPUFrameTime);
};
FrameTimeSample average = new();
FrameTimeSample min = new(float.MaxValue);
FrameTimeSample max = new(float.MinValue);
FrameTimeSample numValidSamples = new(); // Using the struct to record how many valid samples each field has
for (int i = 0; i < m_Samples.Count; i++)
{
var s = m_Samples[i];
ForEachSampleMember(ref min, s, s_SampleValueMin);
ForEachSampleMember(ref max, s, s_SampleValueMax);
ForEachSampleMember(ref average, s, s_SampleValueAdd);
ForEachSampleMember(ref numValidSamples, s, s_SampleValueCountValid);
}
ForEachSampleMember(ref min, numValidSamples, s_SampleValueEnsureValid);
ForEachSampleMember(ref max, numValidSamples, s_SampleValueEnsureValid);
ForEachSampleMember(ref average, numValidSamples, s_SampleValueDivide);
SampleAverage = average;
SampleMin = min;
SampleMax = max;
}
internal void DiscardOldSamples(int sampleHistorySize)
{
Debug.Assert(sampleHistorySize > 0, "Invalid sampleHistorySize");
while (m_Samples.Count >= sampleHistorySize)
m_Samples.RemoveAt(0);
m_Samples.Capacity = sampleHistorySize;
}
internal void Clear()
{
m_Samples.Clear();
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d7cc2267acce47fdae2ece838f34df48
timeCreated: 1629185717
@@ -0,0 +1,32 @@
using System;
using UnityEngine;
namespace UnityEngine.Rendering
{
/// <summary>
/// Interface for storing the debug settings
/// </summary>
public interface IDebugDisplaySettings
{
/// <summary>
/// Reset the stored debug settings
/// </summary>
void Reset();
/// <summary>
/// Executes an action for each element
/// </summary>
/// <param name="onExecute">The action to execute for each element, accepting an IDebugDisplaySettingsData object as a parameter.</param>
void ForEach(Action<IDebugDisplaySettingsData> onExecute);
/// <summary>
/// Adds a <see cref="IDebugDisplaySettingsData"/> to this instance of <see cref="IDebugDisplaySettings"/>
/// </summary>
/// <param name="newData">The <see cref="IDebugDisplaySettingsData"/> to be added to this settings</param>
/// <returns><see cref="IDebugDisplaySettingsData"/></returns>
IDebugDisplaySettingsData Add(IDebugDisplaySettingsData newData)
{
return null;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3be1aff9418ca6840a765320b0c2a2db
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,19 @@
namespace UnityEngine.Rendering
{
/// <summary>
/// Debug UI panel interface
/// </summary>
public interface IDebugDisplaySettingsData : IDebugDisplaySettingsQuery
{
/// <summary>
/// Creates the debug UI panel needed for these debug settings.
/// </summary>
/// <returns>The debug UI panel created.</returns>
IDebugDisplaySettingsPanelDisposable CreatePanel();
/// <summary>
/// Resets the values of the settings data
/// </summary>
void Reset() { }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 78ae6e132563244b58b0aeaf4f96453e
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,32 @@
using System;
namespace UnityEngine.Rendering
{
/// <summary>
/// Debug UI panel
/// </summary>
public interface IDebugDisplaySettingsPanel
{
/// <summary>
/// The name used when displaying this panel.
/// </summary>
string PanelName { get; }
/// <summary>
/// Widgets used by this panel.
/// </summary>
DebugUI.Widget[] Widgets { get; }
/// <summary>
/// Flags to be applied to the top-level panel.
/// </summary>
DebugUI.Flags Flags { get; }
}
/// <summary>
/// Debug UI panel disposable
/// </summary>
public interface IDebugDisplaySettingsPanelDisposable : IDebugDisplaySettingsPanel, IDisposable
{
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: b2dd686478607420fa4600df5d27143f
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,32 @@
using UnityEngine;
namespace UnityEngine.Rendering
{
/// <summary>
/// Interface for determining what kind of debug settings are currently active.
/// </summary>
public interface IDebugDisplaySettingsQuery
{
/// <summary>
/// Checks whether ANY of the debug settings are currently active.
/// </summary>
bool AreAnySettingsActive { get; }
/// <summary>
/// Checks whether the current state of these settings allows post-processing.
/// </summary>
bool IsPostProcessingAllowed => true;
/// <summary>
/// Checks whether lighting is active for these settings.
/// </summary>
bool IsLightingActive => true;
/// <summary>
/// Attempts to get the color used to clear the screen for this debug setting.
/// </summary>
/// <param name="color">A reference to the screen clear color to use.</param>
/// <returns>"true" if we updated the color, "false" if we didn't change anything.</returns>
bool TryGetScreenClearColor(ref Color color) => false;
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 52acb35497424fdcb9cc2535113a9c15
timeCreated: 1613054809
@@ -0,0 +1,9 @@
namespace UnityEngine.Rendering
{
/// <summary>
/// Interface used to mark debug display settings types that can be serialized using DebugDisplaySerializer.
/// </summary>
public interface ISerializedDebugDisplaySettings
{
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 6333654841b048a68ca51b3b64fd0fbb
timeCreated: 1756463997
@@ -0,0 +1,84 @@
using System;
using System.Collections.Generic;
namespace UnityEngine.Rendering
{
/// <summary>
/// Volume debug settings.
/// This variant is obsolete and kept only for not breaking user code. Use <see cref="IVolumeDebugSettings2"/> for all new usage.
/// </summary>
[Obsolete("This is not longer supported Please use DebugDisplaySettingsVolume. #from(6000.2)")]
public interface IVolumeDebugSettings
{
/// <summary>Selected component.</summary>
int selectedComponent { get; set; }
/// <summary>Current camera to debug.</summary>
Camera selectedCamera { get; }
/// <summary>Returns the collection of registered cameras.</summary>
IEnumerable<Camera> cameras { get; }
/// <summary>Selected camera index.</summary>
int selectedCameraIndex { get; set; }
/// <summary>Selected camera volume stack.</summary>
VolumeStack selectedCameraVolumeStack { get; }
/// <summary>Selected camera volume layer mask.</summary>
LayerMask selectedCameraLayerMask { get; }
/// <summary>Selected camera volume position.</summary>
Vector3 selectedCameraPosition { get; }
/// <summary>Type of the current component to debug.</summary>
Type selectedComponentType { get; set; }
/// <summary>
/// Obtains the Volumes
/// </summary>
/// <returns>The list of <see cref="Volume"/></returns>
Volume[] GetVolumes();
/// <summary>
/// Return if the <see cref="Volume"/> has influence
/// </summary>
/// <param name="volume"><see cref="Volume"/> to check the influence</param>
/// <returns>If the volume has influence</returns>
bool VolumeHasInfluence(Volume volume);
/// <summary>
/// Refreshes the volumes, fetches the stored volumes on the panel
/// </summary>
/// <param name="newVolumes">The list of <see cref="Volume"/> to refresh</param>
/// <returns>If the volumes have been refreshed</returns>
bool RefreshVolumes(Volume[] newVolumes);
/// <summary>
/// Obtains the volume weight
/// </summary>
/// <param name="volume"><see cref="Volume"/></param>
/// <returns>The weight of the volume</returns>
float GetVolumeWeight(Volume volume);
}
/// <summary>
/// Volume debug settings.
/// </summary>
#pragma warning disable CS0618 // Type or member is obsolete
[Obsolete("This is not longer supported Please use DebugDisplaySettingsVolume. #from(6000.2)")]
public interface IVolumeDebugSettings2 : IVolumeDebugSettings
#pragma warning restore CS0618 // Type or member is obsolete
{
/// <summary>
/// Specifies the render pipeline
/// </summary>
[Obsolete("This property is obsolete and kept only for not breaking user code. VolumeDebugSettings will use current pipeline when it needs to gather volume component types and paths. #from(2023.2)")]
Type targetRenderPipeline { get; }
/// <summary>List of Volume component types and their path</summary>
[Obsolete("This property is obsolete and kept only for not breaking user code. VolumeDebugSettings will use current pipeline when it needs to gather volume component types and paths. #from(2023.2)")]
List<(string, Type)> volumeComponentsPathAndType { get; }
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 9771abc6c607d7244b4ddbe608ab86fa
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,213 @@
#if ENABLE_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM_PACKAGE
#define USE_INPUT_SYSTEM
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
#endif
using UnityEditor;
namespace UnityEngine.Rendering
{
/// <summary>
/// Provides mouse position for debugging purpose.
/// </summary>
public class MousePositionDebug
{
// Singleton
private static MousePositionDebug s_Instance = null;
#if UNITY_EDITOR
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
static void ResetStaticsOnLoad()
{
s_Instance = null;
}
#endif
/// <summary>
/// Singleton instance.
/// </summary>
static public MousePositionDebug instance
{
get
{
if (s_Instance == null)
{
s_Instance = new MousePositionDebug();
}
return s_Instance;
}
}
#if UNITY_EDITOR
[ExecuteAlways]
class GameViewEventCatcher : MonoBehaviour
{
public static GameViewEventCatcher s_Instance = null;
public static void Cleanup()
{
if (s_Instance != null)
{
// Either we call DestroyImmediate or Destroy we get an error :(
// GameViewEventCatcher is only use for SSR debugging currently so comment this code and uncomment it if you want to debug SSR
//DestroyImmediate(s_Instance.gameObject);
//Destroy(s_Instance.gameObject);
}
}
public static void Build()
{
Cleanup();
var go = new GameObject("__GameViewEventCatcher");
go.hideFlags = HideFlags.HideAndDontSave;
s_Instance = go.AddComponent<GameViewEventCatcher>();
}
void Update()
{
Vector2 mousePosition;
bool rightClickPressed = false;
bool endKeyPressed = false;
#if USE_INPUT_SYSTEM
mousePosition = Pointer.current != null ? Pointer.current.position.ReadValue() : new Vector2(-1, -1);
if (Mouse.current != null)
rightClickPressed = Mouse.current.rightButton.isPressed;
if (Keyboard.current != null)
endKeyPressed = Keyboard.current.endKey.isPressed;
#else
mousePosition = Input.mousePosition;
rightClickPressed = Input.GetMouseButton(1);
endKeyPressed = Input.GetKey(KeyCode.End);
#endif
if (mousePosition.x < 0
|| mousePosition.y < 0
|| mousePosition.x > Screen.width
|| mousePosition.y > Screen.height)
return;
instance.m_mousePosition = mousePosition;
instance.m_mousePosition.y = Screen.height - instance.m_mousePosition.y;
if (rightClickPressed)
instance.m_MouseClickPosition = instance.m_mousePosition;
if (endKeyPressed)
instance.m_MouseClickPosition = instance.m_mousePosition;
}
}
private Vector2 m_mousePosition = Vector2.zero;
Vector2 m_MouseClickPosition = Vector2.zero;
private void OnSceneGUI(UnityEditor.SceneView sceneview)
{
m_mousePosition = Event.current.mousePosition;
switch (Event.current.type)
{
case EventType.MouseDown:
m_MouseClickPosition = m_mousePosition;
break;
case EventType.KeyDown:
switch (Event.current.keyCode)
{
case KeyCode.End:
// Usefull we you don't want to change the scene viewport but still update the mouse click position
m_MouseClickPosition = m_mousePosition;
sceneview.Repaint();
break;
}
break;
}
}
#endif
/// <summary>
/// Initialize the MousePositionDebug class.
/// </summary>
public void Build()
{
#if UNITY_EDITOR
UnityEditor.SceneView.duringSceneGui -= OnSceneGUI;
UnityEditor.SceneView.duringSceneGui += OnSceneGUI;
// Disabled as it cause error: GameViewEventCatcher is only use for SSR debugging currently so comment this code and uncomment it if you want to debug SSR
//GameViewEventCatcher.Build();
#endif
}
/// <summary>
/// Cleanup the MousePositionDebug class.
/// </summary>
public void Cleanup()
{
#if UNITY_EDITOR
UnityEditor.SceneView.duringSceneGui -= OnSceneGUI;
// Disabled as it cause error: GameViewEventCatcher is only use for SSR debugging currently so comment this code and uncomment it if you want to debug SSR
//GameViewEventCatcher.Cleanup();
#endif
}
/// <summary>
/// Get the mouse position in the scene or game view.
/// </summary>
/// <param name="ScreenHeight">Window height.</param>
/// <param name="sceneView">Get position in the scene view?</param>
/// <returns>Coordinates of the mouse in the specified window.</returns>
public Vector2 GetMousePosition(float ScreenHeight, bool sceneView)
{
#if UNITY_EDITOR
if (sceneView)
{
// In play mode, m_mousePosition the one in the scene view
Vector2 mousePixelCoord = EditorGUIUtility.PointsToPixels(m_mousePosition);
mousePixelCoord.y = (ScreenHeight - 1.0f) - mousePixelCoord.y;
return mousePixelCoord;
}
else
{
// In play mode, Input.mousecoords matches the position in the game view
if (EditorApplication.isPlayingOrWillChangePlaymode)
{
return GetInputMousePosition();
}
else
{
// In non-play mode, only m_mousePosition is valid.
// We force -1, -1 as a game view pixel pos to avoid
// rendering un-wanted effects
return new Vector2(-1.0f, -1.0f);
}
}
#else
// In app mode, we only use the Input.mousecoords
return GetInputMousePosition();
#endif
}
Vector2 GetInputMousePosition()
{
#if USE_INPUT_SYSTEM
return Pointer.current != null ? Pointer.current.position.ReadValue() : new Vector2(-1, -1);
#else
return Input.mousePosition;
#endif
}
/// <summary>
/// Returns the position of the mouse click.
/// </summary>
/// <param name="ScreenHeight">Window height.</param>
/// <returns>The coordinates of the mouse click.</returns>
public Vector2 GetMouseClickPosition(float ScreenHeight)
{
#if UNITY_EDITOR
Vector2 mousePixelCoord = EditorGUIUtility.PointsToPixels(m_MouseClickPosition);
mousePixelCoord.y = (ScreenHeight - 1.0f) - mousePixelCoord.y;
return mousePixelCoord;
#else
return Vector2.zero;
#endif
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 16870bb28557a8f4182d1c8191e951a5
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,495 @@
// When defined, ProfilingSampler creates ProfilerRecorder instances to expose per-frame CPU/GPU
// timing and sample-count properties (cpuElapsedTime, gpuElapsedTime, inlineCpuElapsedTime, …).
// Undefine to strip all recorder allocations from builds where profiling overhead is unacceptable.
#define UNITY_USE_RECORDER
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using Unity.Profiling;
using Unity.Profiling.LowLevel;
namespace UnityEngine.Rendering
{
class TProfilingSampler<TEnum> : ProfilingSampler where TEnum : Enum
{
internal static readonly Dictionary<TEnum, TProfilingSampler<TEnum>> samples = new Dictionary<TEnum, TProfilingSampler<TEnum>>();
static TProfilingSampler()
{
var names = Enum.GetNames(typeof(TEnum));
var values = Enum.GetValues(typeof(TEnum));
for (int i = 0; i < names.Length; i++)
{
var sample = new TProfilingSampler<TEnum>(names[i]);
samples.Add((TEnum)values.GetValue(i), sample);
}
}
public TProfilingSampler(string name)
: base(name)
{
}
}
/// <summary>
/// Wraps a ProfilerMarker and its associated ProfilerRecorder instances
/// to provide per-frame CPU and GPU timing for a named profiling scope.
/// Use together with <see cref="ProfilingScope"/> to bracket code you want to measure.
/// </summary>
/// <remarks>
/// Timing properties (<see cref="cpuElapsedTime"/>, <see cref="gpuElapsedTime"/>,
/// <see cref="inlineCpuElapsedTime"/>, and their sample-count counterparts) are only
/// populated after <see cref="enableRecording"/> is set to <c>true</c> and at least one
/// frame has elapsed.
/// ProfilerRecorder instances are allocated lazily on the first <see cref="enableRecording"/> = <c>true</c> call;
/// samplers that never enable recording hold no native resources.
/// Recording support requires the <c>UNITY_USE_RECORDER</c> define (enabled by default);
/// without it all timing properties return zero and no ProfilerRecorder is ever allocated.
/// </remarks>
[IgnoredByDeepProfiler]
public class ProfilingSampler : IDisposable
{
/// <summary>
/// Get the sampler for the corresponding enumeration value.
/// </summary>
/// <typeparam name="TEnum">Type of the enumeration.</typeparam>
/// <param name="marker">Enumeration value.</param>
/// <returns>The <see cref="ProfilingSampler"/> for the given enumeration value,
/// or <c>null</c> in non-development Player builds.</returns>
public static ProfilingSampler Get<TEnum>(TEnum marker)
where TEnum : Enum
{
#if ENABLE_PROFILER
TProfilingSampler<TEnum>.samples.TryGetValue(marker, out var sampler);
return sampler;
#else
return null;
#endif
}
/// <summary>
/// Creates a new <see cref="ProfilingSampler"/> under ProfilerCategory.Render
/// with the specified MarkerFlags.
/// </summary>
/// <remarks>
/// Registers the following ProfilerMarkers:
/// <list type="bullet">
/// <item><description>
/// <b><paramref name="name"/></b> — The primary marker. Appears in the Profiler under
/// ProfilerCategory.Render. Drives <see cref="cpuElapsedTime"/>, <see cref="cpuSampleCount"/>,
/// and (when GPU sampling is active) <see cref="gpuElapsedTime"/> and <see cref="gpuSampleCount"/>.
/// Use the primary marker name to measure CommandBuffer execution timings on the render thread.
/// </description></item>
/// <item><description>
/// <b>"Inl_<paramref name="name"/>"</b> — The inline marker. Also under ProfilerCategory.Render,
/// but without SampleGPU. Sampled directly by <see cref="Begin"/> and <see cref="End"/> on the
/// calling thread. Drives <see cref="inlineCpuElapsedTime"/> and <see cref="inlineCpuSampleCount"/>.
/// </description></item>
/// </list>
/// When no verbosity bits (bits 10–12) are set in <paramref name="flags"/>,
/// MarkerFlags.SampleGPU is added to the primary marker automatically so that GPU timing is
/// captured by default for user-visible markers.
/// Pass any <c>Verbosity*</c> flag (e.g. MarkerFlags.VerbosityAdvanced) to suppress GPU recording.
/// ProfilerRecorder instances (which hold native handles) are not allocated in the constructor;
/// they are created lazily the first time <see cref="enableRecording"/> is set to <c>true</c>.
/// Samplers that never enable recording add no native-resource overhead.
/// </remarks>
/// <param name="name">Name of the profiling sampler.</param>
/// <param name="flags">Verbosity flags (e.g. MarkerFlags.Default,
/// MarkerFlags.VerbosityAdvanced).</param>
/// <returns>A new <see cref="ProfilingSampler"/>, or <c>null</c> in non-development Player builds.</returns>
public static ProfilingSampler Create(string name, MarkerFlags flags)
{
#if ENABLE_PROFILER
return new ProfilingSampler(name, flags);
#else
return null;
#endif
}
/// <summary>
/// Creates a <see cref="ProfilingSampler"/> with <see cref="MarkerFlags.Default"/> under
/// ProfilerCategory.Render. MarkerFlags.SampleGPU is added
/// automatically because no verbosity level is set.
/// </summary>
/// <param name="name">Name shown in the Unity Profiler for this marker.</param>
public ProfilingSampler(string name)
: this(name, MarkerFlags.Default)
{
}
/// <summary>
/// Creates a <see cref="ProfilingSampler"/> with the specified name and flags under ProfilerCategory.Render.
/// Private to ensure we only create ProfilingSamplers with the Create() method,
/// which handles the ENABLE_PROFILER conditional and ensures no overhead in non-development Players.
/// </summary>
/// <param name="name">Name shown in the Unity Profiler for this marker.</param>
/// <param name="flags">Marker flags controlling verbosity and GPU sampling.</param>
private ProfilingSampler(string name, MarkerFlags flags)
{
#if ENABLE_PROFILER
#if UNITY_USE_RECORDER
const MarkerFlags k_VerbosityMask = (MarkerFlags)0x1C00;
var renderFlags = (flags & k_VerbosityMask) == 0 ? flags | MarkerFlags.SampleGPU : flags;
m_SampleGpu = (renderFlags & MarkerFlags.SampleGPU) != 0;
#else
var renderFlags = flags;
#endif
m_Marker = new ProfilerMarker(ProfilerCategory.Render, name, renderFlags);
m_InlineMarker = new ProfilerMarker(ProfilerCategory.Render, $"Inl_{name}", flags);
#endif
this.name = name;
// ProfilerRecorder allocation deferred to first enableRecording = true.
}
/// <summary>
/// Begins the profiling block. Records both a command-buffer marker (if
/// <paramref name="cmd"/> is non-null) and an inline CPU marker.
/// </summary>
/// <param name="cmd">Command buffer to receive the GPU-visible marker.
/// Pass <c>null</c> for CPU-only inline profiling.</param>
[Conditional("ENABLE_PROFILER")]
[MethodImpl(MethodImplOptions.AggressiveInlining | (MethodImplOptions)512)]
public void Begin(CommandBuffer cmd)
{
#if ENABLE_PROFILER
cmd?.BeginSample(m_Marker);
m_InlineMarker.Begin();
#endif
}
/// <summary>
/// Begins the profiling block with a Unity Object context associated with the sample.
/// Records both a command-buffer marker (if <paramref name="cmd"/> is non-null) and an
/// inline CPU marker.
/// </summary>
/// <param name="cmd">Command buffer to receive the GPU-visible marker.
/// Pass <c>null</c> for CPU-only inline profiling.</param>
/// <param name="contextObject">Unity Object (e.g. Texture, Mesh, Material) to associate
/// with this sample. The Profiler displays it in the sample hierarchy.</param>
[Conditional("ENABLE_PROFILER")]
[MethodImpl(MethodImplOptions.AggressiveInlining | (MethodImplOptions)512)]
public void Begin(CommandBuffer cmd, Object contextObject)
{
#if ENABLE_PROFILER
cmd?.BeginSample(m_Marker, contextObject);
m_InlineMarker.Begin(contextObject);
#endif
}
/// <summary>
/// Ends the profiling block started by <see cref="Begin"/> call.
/// </summary>
/// <param name="cmd">The same command buffer passed to <see cref="Begin"/> call,
/// or <c>null</c> if no command buffer was used.</param>
[Conditional("ENABLE_PROFILER")]
[MethodImpl(MethodImplOptions.AggressiveInlining | (MethodImplOptions)512)]
public void End(CommandBuffer cmd)
{
#if ENABLE_PROFILER
cmd?.EndSample(m_Marker);
m_InlineMarker.End();
#endif
}
internal bool IsValid()
{
#if ENABLE_PROFILER
return m_Marker.Handle != IntPtr.Zero;
#else
return false;
#endif
}
#if ENABLE_PROFILER
internal ProfilerMarker m_Marker;
internal ProfilerMarker m_InlineMarker;
#if UNITY_USE_RECORDER
internal ProfilerRecorder m_Recorder;
internal ProfilerRecorder m_GpuRecorder;
internal ProfilerRecorder m_InlineRecorder;
readonly bool m_SampleGpu;
#endif
#endif
/// <summary>
/// Name of this sampler as it appears in the Unity Profiler.
/// </summary>
public string name { get; private set; }
/// <summary>
/// Enables or disables ProfilerRecorder data collection for this sampler.
/// </summary>
/// <remarks>
/// Setting to <c>true</c> for the first time allocates the underlying ProfilerRecorder instances
/// and starts collection; timing properties reflect the <em>previous</em> frame's data after
/// at least one frame has elapsed.
/// Setting back to <c>false</c> stops collection but keeps the recorders allocated for reuse.
/// Has no effect when <c>UNITY_USE_RECORDER</c> is not defined.
/// </remarks>
public bool enableRecording
{
set
{
#if UNITY_USE_RECORDER && ENABLE_PROFILER
if (value)
{
const ProfilerRecorderOptions recorderDefaultOptions =
ProfilerRecorderOptions.WrapAroundWhenCapacityReached |
ProfilerRecorderOptions.SumAllSamplesInFrame |
// TODO: Shared recorder flag. Remove once we transition fully from Enums to static ProfilerSamplers.
// Allows to reuse the same underlying recorder for multiple ProfilingSampler instances with the same marker,
// which is important to avoid disruptions in Graphics Performance Tests during transition.
(ProfilerRecorderOptions)(1 << 7);
if (!m_Recorder.Valid)
{
m_Recorder = new ProfilerRecorder(m_Marker, 1, recorderDefaultOptions);
if (m_SampleGpu)
m_GpuRecorder = new ProfilerRecorder(m_Marker, 1, recorderDefaultOptions | ProfilerRecorderOptions.GpuRecorder);
m_InlineRecorder = new ProfilerRecorder(m_InlineMarker, 1, recorderDefaultOptions);
}
m_Recorder.Start();
if (m_GpuRecorder.Valid)
m_GpuRecorder.Start();
m_InlineRecorder.Start();
}
else
{
if (m_Recorder.Valid)
m_Recorder.Stop();
if (m_GpuRecorder.Valid)
m_GpuRecorder.Stop();
if (m_InlineRecorder.Valid)
m_InlineRecorder.Stop();
}
#endif
}
}
/// <summary>
/// Releases the native ProfilerRecorder resources held by this sampler.
/// This is a no-op if <see cref="enableRecording"/> was never set to <c>true</c>.
/// </summary>
public void Dispose()
{
#if ENABLE_PROFILER
Dispose(true);
GC.SuppressFinalize(this);
#endif
}
#if ENABLE_PROFILER
/// <summary>Finalizer — releases recorders when no explicit <see cref="Dispose"/> call was made.</summary>
~ProfilingSampler() => Dispose(false);
#endif
void Dispose(bool disposing)
{
#if UNITY_USE_RECORDER && ENABLE_PROFILER
if (m_Recorder.Valid)
m_Recorder.Dispose();
if (m_GpuRecorder.Valid)
m_GpuRecorder.Dispose();
if (m_InlineRecorder.Valid)
m_InlineRecorder.Dispose();
#endif
}
#if UNITY_USE_RECORDER && ENABLE_PROFILER
const float k_NanosecondsToMilliseconds = 1.0f / 1000000.0f;
/// <summary>
/// GPU elapsed time in milliseconds for the previous frame.
/// </summary>
/// <remarks>
/// Only non-zero for user-visible markers (those created without verbosity flags), because
/// MarkerFlags.SampleGPU is only added automatically in that case.
/// Always returns <c>0</c> for markers created with a <c>Verbosity*</c> flag.
/// </remarks>
public float gpuElapsedTime => (m_GpuRecorder.Valid && m_GpuRecorder.IsRunning) ? m_GpuRecorder.LastValue * k_NanosecondsToMilliseconds : 0.0f;
/// <summary>
/// Number of times this sampler was hit on the GPU in the previous frame.
/// </summary>
/// <remarks>Subject to the same MarkerFlags.SampleGPU condition as <see cref="gpuElapsedTime"/>.</remarks>
public int gpuSampleCount => (m_GpuRecorder.Valid && m_GpuRecorder.IsRunning) ? (int)m_GpuRecorder.GetSample(0).Count : 0;
/// <summary>
/// CPU elapsed time in milliseconds for command-buffer execution in the previous frame.
/// </summary>
/// <remarks>
/// Measures time spent replaying the command buffer on the CPU render thread.
/// For inline (non-command-buffer) CPU time use <see cref="inlineCpuElapsedTime"/>.
/// </remarks>
public float cpuElapsedTime => (m_Recorder.Valid && m_Recorder.IsRunning) ? m_Recorder.LastValue * k_NanosecondsToMilliseconds : 0.0f;
/// <summary>
/// Number of times this sampler was hit via a command buffer on the CPU in the previous frame.
/// </summary>
public int cpuSampleCount => (m_Recorder.Valid && m_Recorder.IsRunning) ? (int)m_Recorder.GetSample(0).Count : 0;
/// <summary>
/// CPU elapsed time in milliseconds for direct (inline) <see cref="Begin"/>/<see cref="End"/>
/// calls in the previous frame.
/// </summary>
/// <remarks>
/// Reflects time recorded by <see cref="Begin"/> and <see cref="End"/> called directly on the
/// calling thread, not via a command buffer. For command-buffer time use <see cref="cpuElapsedTime"/>.
/// </remarks>
public float inlineCpuElapsedTime => (m_InlineRecorder.Valid && m_InlineRecorder.IsRunning) ? m_InlineRecorder.LastValue * k_NanosecondsToMilliseconds : 0.0f;
/// <summary>
/// Number of times this sampler was hit via direct inline calls in the previous frame.
/// </summary>
public int inlineCpuSampleCount => (m_InlineRecorder.Valid && m_InlineRecorder.IsRunning) ? (int)m_InlineRecorder.GetSample(0).Count : 0;
#else
/// <summary>GPU Elapsed time in milliseconds.</summary>
public float gpuElapsedTime => 0.0f;
/// <summary>Number of times the Profiling Sampler has hit on the GPU</summary>
public int gpuSampleCount => 0;
/// <summary>CPU Elapsed time in milliseconds (Command Buffer execution).</summary>
public float cpuElapsedTime => 0.0f;
/// <summary>Number of times the Profiling Sampler has hit on the CPU in the command buffer.</summary>
public int cpuSampleCount => 0;
/// <summary>CPU Elapsed time in milliseconds (Direct execution).</summary>
public float inlineCpuElapsedTime => 0.0f;
/// <summary>Number of times the Profiling Sampler has hit on the CPU.</summary>
public int inlineCpuSampleCount => 0;
#endif
// Keep the constructor private
ProfilingSampler() { }
}
/// <summary>
/// RAII scope that calls <see cref="ProfilingSampler.Begin"/> on construction and
/// <see cref="ProfilingSampler.End"/> on disposal, ensuring markers are always balanced.
/// Use in a <c>using</c> statement to guarantee <see cref="Dispose"/> is called.
/// </summary>
/// <remarks>This struct is a no-op in non-development Players.</remarks>
[IgnoredByDeepProfiler]
public struct ProfilingScope : IDisposable
{
#if ENABLE_PROFILER
ProfilingSampler m_Sampler;
CommandBuffer m_Cmd;
#endif
/// <summary>
/// Creates a profiling scope without a command buffer (inline CPU profiling only).
/// </summary>
/// <param name="sampler">The sampler that provides the underlying marker.
/// May be <c>null</c>; the scope is a no-op in that case.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining | (MethodImplOptions)512)]
public ProfilingScope(ProfilingSampler sampler)
: this((CommandBuffer)null, sampler)
{
}
/// <summary>
/// Creates an inline CPU-only profiling scope with a Unity Object context associated
/// with the sample. No command buffer is involved; the marker is emitted directly
/// on the CPU timeline.
/// </summary>
/// <param name="sampler">The sampler that provides the underlying marker.
/// May be <c>null</c>; the scope is a no-op in that case.</param>
/// <param name="contextObject">Unity Object (e.g. Texture, Mesh, Material) to associate
/// with this sample. The Profiler displays it in the sample hierarchy.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining | (MethodImplOptions)512)]
public ProfilingScope(ProfilingSampler sampler, Object contextObject)
: this((CommandBuffer)null, sampler, contextObject)
{
}
/// <summary>
/// Creates a profiling scope that records markers into <paramref name="cmd"/> as well as inline on the CPU.
/// </summary>
/// <remarks>
/// Do not use with a named <see cref="CommandBuffer"/>. A named command buffer inserts its own
/// scope marker on execution, which orphans the markers added here: the begin and end appear
/// inside different named-buffer execution brackets and will be mismatched in the Profiler timeline.
/// </remarks>
/// <param name="cmd">Command buffer to receive the GPU-visible begin/end markers.</param>
/// <param name="sampler">The sampler that provides the underlying marker.
/// May be <c>null</c>; the scope is a no-op in that case.</param>
public ProfilingScope(CommandBuffer cmd, ProfilingSampler sampler)
{
#if ENABLE_PROFILER
sampler?.Begin(cmd);
m_Sampler = sampler;
m_Cmd = cmd;
#endif
}
/// <summary>
/// Creates a profiling scope that records markers into <paramref name="cmd"/> with a
/// Unity Object context associated with the sample.
/// </summary>
/// <remarks>
/// Do not use with a named <see cref="CommandBuffer"/>. A named command buffer inserts
/// its own scope marker on execution, which orphans the markers added here.
/// </remarks>
/// <param name="cmd">Command buffer to receive the GPU-visible begin/end markers.</param>
/// <param name="sampler">The sampler that provides the underlying marker.
/// May be <c>null</c>; the scope is a no-op in that case.</param>
/// <param name="contextObject">Unity Object (e.g. Texture, Mesh, Material) to associate
/// with this sample. The Profiler displays it in the sample hierarchy.</param>
public ProfilingScope(CommandBuffer cmd, ProfilingSampler sampler, Object contextObject)
{
#if ENABLE_PROFILER
sampler?.Begin(cmd, contextObject);
m_Sampler = sampler;
m_Cmd = cmd;
#endif
}
/// <summary>
/// Creates a profiling scope that records markers into <paramref name="cmd"/> as well as inline on the CPU.
/// </summary>
/// <remarks>
/// Do not use with a named <see cref="CommandBuffer"/>. A named command buffer inserts its own
/// scope marker on execution, which orphans the markers added here: the begin and end appear
/// inside different named-buffer execution brackets and will be mismatched in the Profiler timeline.
/// </remarks>
/// <param name="cmd">Command buffer to receive the GPU-visible begin/end markers.</param>
/// <param name="sampler">The sampler that provides the underlying marker.
/// May be <c>null</c>; the scope is a no-op in that case.</param>
public ProfilingScope(BaseCommandBuffer cmd, ProfilingSampler sampler)
{
#if ENABLE_PROFILER
sampler?.Begin(cmd.m_WrappedCommandBuffer);
m_Sampler = sampler;
m_Cmd = cmd.m_WrappedCommandBuffer;
#endif
}
/// <summary>
/// Creates a profiling scope that records markers into <paramref name="cmd"/> as well as inline on the CPU,
/// and associates a Unity Object with the sample for identification in the Profiler.
/// </summary>
/// <remarks>
/// Do not use with a named <see cref="CommandBuffer"/>. A named command buffer inserts its own
/// scope marker on execution, which orphans the markers added here: the begin and end appear
/// inside different named-buffer execution brackets and will be mismatched in the Profiler timeline.
/// </remarks>
/// <param name="cmd">BaseCommandBuffer (e.g. RasterCommandBuffer, UnsafeCommandBuffer) to receive the GPU-visible begin/end markers.</param>
/// <param name="sampler">The sampler that provides the underlying marker.
/// May be <c>null</c>; the scope is a no-op in that case.</param>
/// <param name="contextObject">Unity Object (e.g. Texture, Mesh, Material) to associate
/// with this sample. The Profiler displays it in the sample hierarchy.</param>
[MethodImpl(MethodImplOptions.AggressiveInlining | (MethodImplOptions)512)]
public ProfilingScope(BaseCommandBuffer cmd, ProfilingSampler sampler, Object contextObject)
: this(cmd.m_WrappedCommandBuffer, sampler, contextObject)
{
}
/// <summary>
/// Ends the profiling scope by calling <see cref="ProfilingSampler.End"/>. Safe to call multiple times.
/// </summary>
public void Dispose()
{
#if ENABLE_PROFILER
if (m_Sampler == null)
return;
m_Sampler.End(m_Cmd);
m_Sampler = null;
#endif
}
}
}
@@ -0,0 +1,13 @@
fileFormatVersion: 2
guid: a9115e9ffa8b6df4ba69fe5eb9b541db
timeCreated: 1507043252
licenseType: Pro
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: 81b0bfa724056e24e95404168aca40dd
folderAsset: yes
DefaultImporter:
externalObjects: {}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,145 @@
:root {
}
/* Common */
.debug-window-header-row {
flex-direction: row;
align-items: center;
justify-content: flex-end;
min-height: 30px;
width: 100%;
}
.debug-window-header-title {
font-size: 24px;
-unity-font-style: bold;
}
.unity-base-field > Label {
padding-left: 0; /* Remove internal label indentation from the field widgets */
}
/* Widgets */
.debug-window-valuetuple {
flex-direction: row;
}
.debug-window-value-container {
flex-direction: row;
}
.debug-window-historyenum {
flex-direction: row;
}
.debug-window-historyenum .debug-window-enumfield {
margin-top: 2px;
padding-right: 10px;
margin-bottom: 2px;
}
.debug-window-historyboolfield {
flex-direction: row;
}
.debug-window-objectfield,
.debug-window-objectpopupfield,
.debug-window-enumfield {
flex-grow: 0;
}
/* Remove -12px for toggle for align it when used in fields */
.debug-window-renderinglayerfield__content > .unity-foldout > .unity-foldout__toggle{
margin-left: 0px !important;
}
.debug-window-objectlistfield.unity-foldout > .unity-foldout__toggle{
margin-left: 0px !important;
}
/* Containers */
.debug-window-container-content {
margin-left: 8px; /*If modified, modify it in Debug.ToVisualElement. Compensate indentation margin */
}
.debug-window-container-displayname {
-unity-font-style: bold;
margin-bottom: 4px;
margin-top: 6px;
margin-left: 3px;
}
.debug-window-foldout {
margin-left: 8px;
margin-right: -3px;
}
.debug-window-row-alternate {
background-color: var(--unity-colors-alternated_rows-background);
}
.debug-window-table {
}
.debug-window-table-header-row {
-unity-font-style: bold;
border-bottom-color: var(--unity-colors-app_toolbar_button-border);
border-bottom-width: 1px;
}
.debug-window-table-header-cell {
overflow: hidden;
text-overflow: ellipsis;
}
.debug-window-table-row {
flex-direction: row;
min-height: 16px;
}
.debug-window-table-cell {
overflow: hidden;
text-overflow: ellipsis;
padding: 2px 2px 4px 2px;
border-right-color: var(--unity-colors-app_toolbar_button-border);
border-right-width: 0px;
min-height: 10px;
margin-left: 0px;
margin-right: 0px;
}
.debug-window-colorfield.debug-window-table-cell>.unity-base-field__input {
flex-grow: 0;
}
.debug-window-help-button {
width: 30px;
height: 30px;
padding: 0;
margin-top: 0;
margin-bottom: 0;
border-width: 0;
border-radius: 3px;
background-color: transparent;
background-size: 16px 16px;
background-image: resource("Icons/_Help.png");
align-self: flex-end;
}
.debug-window-help-button:hover {
background-color: var(--unity-colors-button-background-hover);
}
.dark .debug-window-help-button {
background-image: resource("Icons/d__Help.png");
}
.debug-window-help-button:disabled
{
display: none;
}
@@ -0,0 +1,12 @@
fileFormatVersion: 2
guid: 0ff99fd36f66f1a41bcc1d3c90e0922a
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0}
disableValidation: 0
unsupportedSelectorAction: 0
@@ -0,0 +1,3 @@
@import url("unity-theme://default");
@import url("RuntimeDebugWindow.uss");
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 76404632120e0ae4885fc7be8197097c
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 12388, guid: 0000000000000000e000000000000000, type: 0}
disableValidation: 0
@@ -0,0 +1,312 @@
:root {
--widget-focus-color: #81B4FF;
--active-tab-underline-color: #46607C;
--window-background-color: #000000EA;
--persistent-widget-background-color: #000000EA;
--tab-background-color: #00000088;
--text-color: #BBBBBB;
--text-color-inactive: #888888;
--widget-background-color: #515151;
--widget-background-color-hover: #666666;
--widget-border-color: #303030;
--toolbar-height: 60px;
--checkmark-tint: #888888;
--checkmark-background: #00000000;
--helpbox-background: #00000000;
--scrollbar-tracker-color: #00000000;
}
VisualElement {
font-size: 18px; /* Global font size */
}
#debug-window {
background-color: var(--window-background-color);
margin-left: 16px;
margin-top: 16px;
margin-bottom: 16px;
color: var(--text-color);
}
#debug-window.landscape-orientation {
width: 50%;
height: 95%;
}
#debug-window.portrait-orientation {
width: 95%;
height: 50%;
}
/* Dropdown popup overrides */
PanelRootElement > .unity-base-dropdown {
color: var(--text-color);
}
/* Tab bar */
#debug-window-tabview {
}
#debug-window-tabview .unity-tab-view__content-viewport {
max-width: 90%; /* Leave room for reset button */
background-color: var(--tab-background-color);
}
#debug-window-tabview .unity-tab__header:checked > .unity-tab__header-underline {
background-color: var(--active-tab-underline-color);
}
#debug-window-tabview .unity-tab__header {
color: var(--text-color-inactive);
}
#debug-window-tabview .unity-tab__header:checked {
color: var(--text-color);
}
#debug-window-tabview .unity-tab__header:hover {
color: var(--text-color);
}
#debug-window-tabview .unity-tab__header {
background-color: #00000000;
height: var(--toolbar-height);
}
#debug-window-tabview RepeatButton {
background-color: var(--tab-background-color);
-unity-background-image-tint-color: var(--checkmark-tint);
}
#debug-window-tabview RepeatButton:hover {
background-color: var(--widget-background-color-hover);
}
.debug-window-header-title {
display: none;
}
/* Toolbar */
#toolbar {
position: absolute;
width: 10%; /* Note: should match remaining width from #debug-window-tabview .unity-tab-view__content-viewport */
height: var(--toolbar-height);
background-color: var(--tab-background-color);
flex-direction: row;
justify-content: flex-end;
right: 0;
}
#btn-reset {
position: relative;
padding: 6px;
padding-left: 10px;
padding-right: 10px;
margin: 8px;
align-content: center;
align-self: center;
-unity-text-align: middle-center;
background-color: var(--widget-background-color);
border-color: var(--widget-border-color);
border-radius: 4px;
}
#btn-reset:hover {
background-color: var(--widget-background-color-hover);
}
.debug-window-objectfield {
margin-left: 8px;
}
.debug-window-messagebox {
background-color: var(--helpbox-background);
}
.debug-window-basefield_boolean .unity-base-field__input {
margin-left: 4px;
}
.debug-window-button {
-unity-text-align: middle-center;
background-color: var(--widget-background-color);
border-color: var(--widget-border-color);
border-radius: 4px;
}
.debug-window-stepper-button {
margin-top: 0px;
margin-bottom: 0px;
}
.debug-window-stepper-field > .unity-base-field__input {
margin-left: 4px;
margin-right: 4px;
}
/* Align content of the foldouts with the text */
.debug-window-foldout > .unity-foldout__content {
margin: 0px 4px 8px 12px;
}
/* TODO: Need to have highly specific selectors to override default focus styles - figure out how to do this better */
.debug-window-button:enabled:hover {
background-color: var(--widget-background-color-hover);
}
.unity-inspector-element:focus > .unity-label {
color: var(--widget-focus-color);
}
.unity-inspector-element:focus:enabled > .unity-base-field__label {
color: var(--widget-focus-color);
}
.unity-foldout__toggle .unity-toggle__input:focus:enabled > .unity-label {
color: var(--widget-focus-color);
}
/* Persistent widgets */
.debug-window-persistent-root {
background-color: var(--persistent-widget-background-color);
margin: 8px;
flex-direction: column;
flex-grow: 0;
flex-shrink: 0;
align-self: flex-end;
color: var(--text-color);
}
.debug-window-persistent-value-container {
flex-direction: row;
justify-content: space-between;
padding-right: 10px;
}
.debug-window-persistent-value-name {
min-width: 200px;
}
.debug-window-persistent-value-value {
min-width: 100px;
-unity-text-align: middle-right;
}
/* Global overrides for widget styles */
#unity-checkmark {
-unity-background-image-tint-color: var(--checkmark-tint);
background-color: var(--checkmark-background);
}
.debug-window-basefield_boolean:hover #unity-checkmark{
border-color: var(--checkmark-tint);
}
.unity-base-popup-field__input {
background-color: var(--widget-background-color);
border-color: var(--widget-border-color);
}
.unity-base-popup-field__input:hover {
background-color: var(--widget-background-color-hover);
}
/* Sometimes popupfield stays in "active" pseudostate after the popup is closed. */
/* Fix this weird behavior by overriding the active style to be same as the non-active one. */
.unity-base-popup-field:active:enabled > .unity-base-popup-field__input {
background-color: var(--widget-background-color);
}
.unity-base-popup-field__input .unity-base-popup-field__arrow {
-unity-background-image-tint-color: var(--checkmark-tint);
background-color: var(--checkmark-background);
}
.unity-base-dropdown__container-inner {
background-color: var(--widget-background-color);
border-color: var(--widget-border-color);
}
.unity-base-field .unity-button {
background-color: var(--widget-background-color);
border-color: var(--widget-border-color);
}
.unity-base-field:hover .unity-button {
background-color: var(--widget-background-color-hover);
}
.unity-base-field .unity-button:hover {
background-color: var(--widget-background-color-hover);
}
.unity-base-text-field__input {
background-color: var(--widget-background-color);
border-color: var(--widget-border-color);
}
Scroller #unity-tracker {
background-color: var(--scrollbar-tracker-color);
border-width: 0;
}
Scroller #unity-dragger {
background-color: var(--widget-background-color);
}
Scroller #unity-dragger:hover {
background-color: var(--widget-background-color-hover);
}
Scroller #unity-low-button {
border-width: 0;
}
Scroller #unity-high-button {
border-width: 0;
}
/* Style for Vector fields */
.debug-window-vector2field-runtime,
.debug-window-vector3field-runtime,
.debug-window-vector4field-runtime
{
color: var(--text-color);
}
.debug-window-stepper-field:focus
{
color: var(--widget-focus-color);
}
.debug-window-stepper-field > .unity-base-field__label
{
min-width:24px;
}
/* Progress Bar */
.unity-progress-bar
{
margin: 0px;
color: var(--text-color);
}
.unity-progress-bar__background
{
background-color: var(--widget-border-color);
border-width: 0px;
border-radius: 4px;
}
.unity-progress-bar__progress
{
margin: 0px;
background-color: var(--widget-focus-color);
border-radius: 4px;
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 3a8aa4d508da46d4dace18b280f064aa
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 12385, guid: 0000000000000000e000000000000000, type: 0}
disableValidation: 0
@@ -0,0 +1,12 @@
<ui:UXML xmlns:ui="UnityEngine.UIElements" xsi="http://www.w3.org/2001/XMLSchema-instance"
engine="UnityEngine.UIElements" noNamespaceSchemaLocation="../../../../../UIElementsSchema/UIElements.xsd">
<ui:VisualElement name="debug-window">
<ui:HelpBox text="No debug items found." name="no-debug-items-message" />
<ui:VisualElement name="content-container">
<ui:TabView name="debug-window-tabview"/>
<ui:VisualElement name="toolbar">
<ui:Button text="Reset" name="btn-reset" focusable="false" />
</ui:VisualElement>
</ui:VisualElement>
</ui:VisualElement>
</ui:UXML>
@@ -0,0 +1,10 @@
fileFormatVersion: 2
guid: b647ceb1e15264943b9b439971e71110
ScriptedImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 2
userData:
assetBundleName:
assetBundleVariant:
script: {fileID: 13804, guid: 0000000000000000e000000000000000, type: 0}
@@ -0,0 +1,54 @@
%YAML 1.1
%TAG !u! tag:unity3d.com,2011:
--- !u!114 &11400000
MonoBehaviour:
m_ObjectHideFlags: 0
m_CorrespondingSourceObject: {fileID: 0}
m_PrefabInstance: {fileID: 0}
m_PrefabAsset: {fileID: 0}
m_GameObject: {fileID: 0}
m_Enabled: 1
m_EditorHideFlags: 0
m_Script: {fileID: 19101, guid: 0000000000000000e000000000000000, type: 0}
m_Name: RuntimeDebugWindow_PanelSettings
m_EditorClassIdentifier:
themeUss: {fileID: -4733365628477956816, guid: 76404632120e0ae4885fc7be8197097c, type: 3}
m_DisableNoThemeWarning: 0
m_TargetTexture: {fileID: 0}
m_RenderMode: 0
m_ColliderUpdateMode: 0
m_ColliderIsTrigger: 1
m_ScaleMode: 2
m_ReferenceSpritePixelsPerUnit: 100
m_PixelsPerUnit: 100
m_Scale: 1
m_ReferenceDpi: 96
m_FallbackDpi: 96
m_ReferenceResolution: {x: 1536, y: 864}
m_ScreenMatchMode: 0
m_Match: 0.3
m_SortingOrder: 0
m_TargetDisplay: 0
m_BindingLogLevel: 0
m_ClearDepthStencil: 1
m_ClearColor: 0
m_ColorClearValue: {r: 0, g: 0, b: 0, a: 0}
m_VertexBudget: 0
m_ExtraVertexChannels: 0
m_TextureSlotCount: 8
m_DynamicAtlasSettings:
m_MinAtlasSize: 64
m_MaxAtlasSize: 4096
m_MaxSubTextureSize: 64
m_ActiveFilters: -1
m_AtlasBlitShader: {fileID: 9101, guid: 0000000000000000f000000000000000, type: 0}
m_DefaultShader: {fileID: 9100, guid: 0000000000000000f000000000000000, type: 0}
m_RuntimeGaussianBlurShader: {fileID: 20300, guid: 0000000000000000f000000000000000, type: 0}
m_RuntimeColorEffectShader: {fileID: 20301, guid: 0000000000000000f000000000000000, type: 0}
m_RuntimeDropShadowComposite: {fileID: 20302, guid: 0000000000000000f000000000000000, type: 0}
m_SDFShader: {fileID: 19011, guid: 0000000000000000f000000000000000, type: 0}
m_BitmapShader: {fileID: 9001, guid: 0000000000000000f000000000000000, type: 0}
m_SpriteShader: {fileID: 19012, guid: 0000000000000000f000000000000000, type: 0}
m_ICUDataAsset: {fileID: 20204, guid: 0000000000000000f000000000000000, type: 0}
forceGammaRendering: 1
textSettings: {fileID: 0}
@@ -0,0 +1,8 @@
fileFormatVersion: 2
guid: fa69697be3070b04a893666f5947f18c
NativeFormatImporter:
externalObjects: {}
mainObjectFileID: 11400000
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,335 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
#if ENABLE_RENDERING_DEBUGGER_UI
using System.Collections.Generic;
using UnityEngine.UIElements;
namespace UnityEngine.Rendering
{
[AddComponentMenu("")] // Hide from Add Component menu
class RuntimeDebugWindow : MonoBehaviour
{
PanelRenderer m_PanelRenderer;
VisualElement m_RootVisualElement;
VisualElement m_PanelRootElement;
TabView m_TabViewElement;
DebugUI.Panel m_SelectedPanel;
bool m_PortraitOrientation;
bool m_NeedsRebuild;
int m_UIVersion = 0;
Dictionary<string, Vector2> m_ScrollPositions = new Dictionary<string, Vector2>();
void Awake()
{
DebugManager.instance.onSetDirty += RequestRebuild;
DebugManager.instance.onRecreateDebugUI += RequestRebuild;
if (m_PanelRenderer == null)
{
m_PanelRenderer = gameObject.AddComponent<PanelRenderer>();
if (GraphicsSettings.TryGetRenderPipelineSettings<RenderingDebuggerRuntimeResources>(out var resources))
{
m_PanelRenderer.panelSettings = resources.panelSettings;
m_PanelRenderer.visualTreeAsset = resources.visualTreeAsset;
}
}
m_PanelRenderer.RegisterUIReloadCallback(OnUIReload);
}
internal void OnUIReload(PanelRenderer renderer, VisualElement rootElement, int version)
{
// Called on initial load AND on any asset change
if (rootElement == null || rootElement.childCount == 0)
return;
if (version == m_UIVersion)
return;
m_UIVersion = version;
m_PanelRootElement = rootElement;
m_RootVisualElement = rootElement[0];
var resources = GraphicsSettings.GetRenderPipelineSettings<RenderingDebuggerRuntimeResources>();
var styleSheets = resources.styleSheets;
foreach (var uss in styleSheets)
m_PanelRootElement.styleSheets.Add(uss);
BuildDebugUI();
}
void BuildDebugUI()
{
if (m_RootVisualElement == null)
return;
UpdateOrientation(forceUpdate: true);
// Save scroll positions before clearing
if (m_TabViewElement != null)
{
m_ScrollPositions.Clear();
foreach (var tab in m_TabViewElement.Query<Tab>().ToList())
{
var scrollView = tab.Q<ScrollView>();
if (scrollView != null)
{
m_ScrollPositions[tab.label] = scrollView.scrollOffset;
}
}
}
m_TabViewElement = m_RootVisualElement.Q<TabView>(name: "debug-window-tabview");
m_TabViewElement.Clear();
var resetButton = m_RootVisualElement.Q<Button>(name: "btn-reset");
resetButton.clicked -= ResetClicked;
resetButton.clicked += ResetClicked;
var panels = DebugManager.instance.panels;
var activePanels = new List<DebugUI.Panel>();
// Filter out editor only panels and panels with no active children
foreach (var panel in panels)
{
bool isEditorOnlyPanel = panel.isEditorOnly;
bool hasVisibleChildren = false;
foreach (var w in panel.children)
{
if (!w.isEditorOnly && !w.isHidden)
{
hasVisibleChildren = true;
break;
}
}
if (!isEditorOnlyPanel && hasVisibleChildren)
{
activePanels.Add(panel);
}
}
bool hasDebugItems = activePanels.Count > 0;
m_RootVisualElement.Q<HelpBox>(name: "no-debug-items-message").style.display = hasDebugItems ? DisplayStyle.None : DisplayStyle.Flex;
m_RootVisualElement.Q<VisualElement>(name: "content-container").style.display = hasDebugItems ? DisplayStyle.Flex : DisplayStyle.None;
if (!hasDebugItems)
return;
var uiPanels = DebugUIExtensions.CreatePanels(activePanels, DebugUI.Context.Runtime);
foreach (var (tabLabel, panel) in uiPanels)
{
ScrollView scrollView = new ScrollView();
scrollView.horizontalScrollerVisibility = ScrollerVisibility.Hidden;
scrollView.verticalScroller.slider.focusable = false;
scrollView.Add(panel);
// Restore scroll position if saved
if (m_ScrollPositions.TryGetValue(tabLabel.text, out var savedScrollOffset))
{
scrollView.schedule.Execute(() => scrollView.scrollOffset = savedScrollOffset).StartingIn(0);
}
Tab tab = new Tab(tabLabel.text);
tab.name = tabLabel.name;
tab.selected += t => SetSelectedPanel(t.label);
tab.Add(scrollView);
m_TabViewElement.Add(tab);
}
// We want to treat Up/Down NavigationMoveEvents as Next/Previous instead to get correct focus ring behavior, i.e. make
// up/down arrows behave as tab/shift+tab. To do this we intercept the Up/Down events and send Next/Previous instead.
m_PanelRootElement.UnregisterCallback<NavigationMoveEvent>(ConvertNavigationMoveEvents, TrickleDown.TrickleDown);
m_PanelRootElement.RegisterCallback<NavigationMoveEvent>(ConvertNavigationMoveEvents, TrickleDown.TrickleDown);
string selectedPanelName;
if (m_SelectedPanel == null || !activePanels.Contains(m_SelectedPanel))
selectedPanelName = DebugManager.instance.panels.Count > 0 ? DebugManager.instance.panels[0].displayName : null;
else
selectedPanelName = m_SelectedPanel.displayName;
// Defer until after layout so all AttachToPanelEvent callbacks from ScheduleTracked
// have fired and registered their schedulers before SetHierarchyEnabled is called.
m_TabViewElement.schedule.Execute(_ => SetSelectedPanel(selectedPanelName)).StartingIn(100);
m_NeedsRebuild = false;
}
void OnDestroy()
{
DebugManager.instance.onSetDirty -= RequestRebuild;
DebugManager.instance.onRecreateDebugUI -= RequestRebuild;
if (m_PanelRenderer != null)
{
// Unregister the UI reload callback
m_PanelRenderer.UnregisterUIReloadCallback(OnUIReload);
// Need to unregister here as well because when the UI is closed and reopened, it is a different object so the member
// function will be a different object and the Unregister call in RecreateGUI does nothing.
m_PanelRootElement?.UnregisterCallback<NavigationMoveEvent>(ConvertNavigationMoveEvents, TrickleDown.TrickleDown);
}
DebugManager.instance.displayRuntimeUI = false;
}
void ConvertNavigationMoveEvents(NavigationMoveEvent evt)
{
if (m_PanelRootElement == null)
return;
if (IsPopupOpen())
return; // Popup navigation uses up/down normally
if (evt.direction != NavigationMoveEvent.Direction.Up &&
evt.direction != NavigationMoveEvent.Direction.Down)
return;
evt.StopPropagation();
m_PanelRootElement.focusController.IgnoreEvent(evt);
var newDirection = evt.direction == NavigationMoveEvent.Direction.Down
? NavigationMoveEvent.Direction.Next
: NavigationMoveEvent.Direction.Previous;
using (var newEvt = NavigationMoveEvent.GetPooled(newDirection))
{
newEvt.target = evt.target;
m_PanelRootElement.panel.visualTree.SendEvent(newEvt);
}
}
internal void RequestRebuild()
{
m_NeedsRebuild = true;
}
void Update()
{
UpdateOrientation();
if (m_NeedsRebuild)
BuildDebugUI();
}
void UpdateOrientation(bool forceUpdate = false)
{
// We use screen dimensions instead of Screen.orientation to handle desktop platforms where it's better
// to treat typical screen resolutions as "Landscape", but Screen.orientation reports it as "Portrait".
bool portraitOrientation = Screen.width < Screen.height;
if (forceUpdate || m_PortraitOrientation != portraitOrientation)
{
m_PortraitOrientation = portraitOrientation;
const string portraitClassName = "portrait-orientation";
const string landscapeClassName = "landscape-orientation";
var debugWindowElement = m_PanelRootElement?.Q("debug-window");
if (debugWindowElement == null)
return;
debugWindowElement.RemoveFromClassList(portraitClassName);
debugWindowElement.RemoveFromClassList(landscapeClassName);
if (m_PortraitOrientation)
{
debugWindowElement.AddToClassList(portraitClassName);
}
else
{
debugWindowElement.AddToClassList(landscapeClassName);
}
}
}
void ResetClicked()
{
DebugDisplaySerializer.SaveFoldoutStates();
DebugDisplaySerializer.Clear();
DebugManager.instance.Reset();
DebugDisplaySerializer.LoadFoldoutStates();
}
void SetSelectedPanel(string panelName)
{
if (string.IsNullOrEmpty(panelName))
return;
if (m_SelectedPanel != null)
{
var previousPanel = DebugManager.instance.GetPanel(m_SelectedPanel.displayName);
if (previousPanel != null)
DebugManager.instance.schedulerTracker.SetHierarchyEnabled(DebugUI.Context.Runtime, previousPanel, false);
}
m_SelectedPanel = DebugManager.instance.GetPanel(panelName);
if (m_SelectedPanel != null)
{
var newSelectedTab = m_TabViewElement.Q<Tab>(name: $"{m_SelectedPanel.displayName}_Tab");
if (newSelectedTab != null)
m_TabViewElement.activeTab = newSelectedTab;
DebugManager.instance.schedulerTracker.SetHierarchyEnabled(DebugUI.Context.Runtime, m_SelectedPanel, true);
// Focus first focusable child in the panel
foreach (var widget in m_SelectedPanel.children)
{
if (widget.m_VisualElement is { focusable: true })
{
widget.m_VisualElement.Focus();
break;
}
}
}
}
internal bool IsPopupOpen()
{
if (m_PanelRootElement == null)
return false;
const string popupClassName = "unity-base-dropdown";
var numPanelChildren = m_PanelRootElement.childCount;
// reverse loop because the popup will appear at the end
for (int i = numPanelChildren - 1; i >= 0; i--)
{
var child = m_PanelRootElement[i];
if (child != null && child.ClassListContains(popupClassName))
return true;
}
return false;
}
internal void SelectNextPanel() => SelectPanelWithOffset(+1);
internal void SelectPreviousPanel() => SelectPanelWithOffset(-1);
void SelectPanelWithOffset(int offset)
{
if (m_SelectedPanel == null)
return;
var panels = DebugManager.instance.panels;
int index = DebugManager.instance.FindPanelIndex(m_SelectedPanel.displayName);
int Mod(int x, int m)
{
return (x % m + m) % m; // Handle negative offset correctly
}
int nextIndex = Mod(index + offset, panels.Count);
SetSelectedPanel(panels[nextIndex].displayName);
}
}
}
#endif
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 2fb81ce9d2193c743903de96dcf799d7
@@ -0,0 +1,124 @@
#if ENABLE_UIELEMENTS_MODULE && UNITY_ENABLE_CHECKS
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
#if ENABLE_RENDERING_DEBUGGER_UI
using System.Collections.Generic;
using UnityEngine.UIElements;
namespace UnityEngine.Rendering
{
[AddComponentMenu("")] // Hide from Add Component menu
class RuntimePersistentDebugUI : MonoBehaviour
{
UIDocument m_Document;
VisualElement m_PersistentRoot;
readonly Dictionary<DebugUI.Value, VisualElement> m_Values = new();
readonly HashSet<DebugUI.ValueTuple> m_ValueTuples = new();
void Awake()
{
RecreateGUI();
}
void RecreateGUI()
{
var resources = GraphicsSettings.GetRenderPipelineSettings<RenderingDebuggerRuntimeResources>();
if (m_Document == null)
m_Document = gameObject.AddComponent<UIDocument>();
m_Document.panelSettings = resources.panelSettings;
var rootVisualElement = m_Document.rootVisualElement;
var styleSheets = resources.styleSheets;
foreach (var uss in styleSheets)
rootVisualElement.styleSheets.Add(uss);
// Prevent input
rootVisualElement.pickingMode = PickingMode.Ignore;
rootVisualElement.focusable = false;
rootVisualElement.tabIndex = -1;
var persistentRoot = new VisualElement();
persistentRoot.AddToClassList("debug-window-persistent-root");
rootVisualElement.Add(persistentRoot);
m_PersistentRoot = persistentRoot;
}
// Toggles persistent value widget on/off.
internal void Toggle(DebugUI.Value valueWidget, string displayName = null)
{
// Remove & return
if (m_Values.TryGetValue(valueWidget, out var existingVisualElement))
{
DebugManager.instance.schedulerTracker.SetEnabled(DebugUI.Context.RuntimePersistent, valueWidget, false);
m_Values.Remove(valueWidget);
m_PersistentRoot.Remove(existingVisualElement);
return;
}
// Add
var valueContainer = new VisualElement();
valueContainer.AddToClassList("debug-window-persistent-value-container");
var label = new Label(displayName);
label.AddToClassList("debug-window-persistent-value-name");
valueContainer.Add(label);
var value = valueWidget.ToVisualElement(DebugUI.Context.RuntimePersistent);
value.AddToClassList("debug-window-persistent-value-value");
valueContainer.Add(value);
m_PersistentRoot.Add(valueContainer);
m_Values.Add(valueWidget, valueContainer);
DebugManager.instance.schedulerTracker.SetEnabled(DebugUI.Context.RuntimePersistent, valueWidget, true);
}
// For ValueTuples (multiple values on one row), we cycle through the columns, and turn the widget
// off after the last column.
internal void Toggle(DebugUI.ValueTuple valueTupleWidget, int? forceTupleIndex = null)
{
int tupleIndex = valueTupleWidget.pinnedElementIndex;
// Clear old widget
if (m_ValueTuples.Contains(valueTupleWidget))
{
m_ValueTuples.Remove(valueTupleWidget);
Toggle(valueTupleWidget.values[tupleIndex]);
}
if (forceTupleIndex != null)
tupleIndex = forceTupleIndex.Value;
// Enable next widget (unless at the last index)
if (tupleIndex + 1 < valueTupleWidget.numElements)
{
valueTupleWidget.pinnedElementIndex = tupleIndex + 1;
// Add column to name
string displayName = valueTupleWidget.displayName;
if (valueTupleWidget.parent is DebugUI.Foldout foldout)
{
var columnLabels = foldout.columnLabels;
if (columnLabels != null && valueTupleWidget.pinnedElementIndex < columnLabels.Length)
{
displayName += $" ({columnLabels[valueTupleWidget.pinnedElementIndex]})";
}
}
Toggle(valueTupleWidget.values[valueTupleWidget.pinnedElementIndex], displayName);
m_ValueTuples.Add(valueTupleWidget);
}
else
{
valueTupleWidget.pinnedElementIndex = -1;
}
}
internal bool IsEmpty()
{
return m_Values.Count == 0;
}
}
}
#endif
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: d3743b694e3b469a866192d7dc9bf453
timeCreated: 1757415482
@@ -0,0 +1,430 @@
using System;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Assertions;
namespace UnityEngine.Rendering
{
/// <summary>
/// Internal development tool.
/// Manages gpu-buffers for shader debug printing.
/// </summary>
public sealed class ShaderDebugPrintManager
{
private static readonly ShaderDebugPrintManager s_Instance = new ShaderDebugPrintManager();
private const int k_FramesInFlight = 4;
private const int k_MaxBufferElements = 1024 * 16; // Must match the shader size definition
private List<GraphicsBuffer> m_OutputBuffers = new List<GraphicsBuffer>();
private List<Rendering.AsyncGPUReadbackRequest> m_ReadbackRequests =
new List<Rendering.AsyncGPUReadbackRequest>();
// Cache Action to avoid delegate allocation
private Action<AsyncGPUReadbackRequest> m_BufferReadCompleteAction;
private int m_FrameCounter = 0;
private bool m_FrameCleared = false;
private string m_OutputLine = "";
private Action<string> m_OutputAction;
private static readonly int m_ShaderPropertyIDInputMouse = Shader.PropertyToID("_ShaderDebugPrintInputMouse");
private static readonly int m_ShaderPropertyIDInputFrame = Shader.PropertyToID("_ShaderDebugPrintInputFrame");
private static readonly int m_shaderDebugOutputData = Shader.PropertyToID("shaderDebugOutputData");
// A static "container" for all profiler markers.
private static class Profiling
{
// Uses nameof to avoid aliasing
public static readonly ProfilingSampler BufferReadComplete = new ProfilingSampler($"{nameof(ShaderDebugPrintManager)}.{nameof(BufferReadComplete)}");
}
// Should match: com.unity.render-pipelines.core/ShaderLibrary/ShaderDebugPrint.hlsl
enum DebugValueType
{
TypeUint = 1,
TypeInt = 2,
TypeFloat = 3,
TypeUint2 = 4,
TypeInt2 = 5,
TypeFloat2 = 6,
TypeUint3 = 7,
TypeInt3 = 8,
TypeFloat3 = 9,
TypeUint4 = 10,
TypeInt4 = 11,
TypeFloat4 = 12,
TypeBool = 13,
};
private const uint k_TypeHasTag = 128;
private int DebugValueTypeToElemSize(DebugValueType type)
{
switch (type)
{
case DebugValueType.TypeUint:
case DebugValueType.TypeInt:
case DebugValueType.TypeFloat:
case DebugValueType.TypeBool:
return 1;
case DebugValueType.TypeUint2:
case DebugValueType.TypeInt2:
case DebugValueType.TypeFloat2:
return 2;
case DebugValueType.TypeUint3:
case DebugValueType.TypeInt3:
case DebugValueType.TypeFloat3:
return 3;
case DebugValueType.TypeUint4:
case DebugValueType.TypeInt4:
case DebugValueType.TypeFloat4:
return 4;
default:
return 0;
}
}
private ShaderDebugPrintManager()
{
for (int i = 0; i < k_FramesInFlight; i++)
{
m_OutputBuffers.Add(new GraphicsBuffer(GraphicsBuffer.Target.Structured, k_MaxBufferElements, 4));
m_ReadbackRequests.Add(new Rendering.AsyncGPUReadbackRequest());
}
m_BufferReadCompleteAction = BufferReadComplete;
m_OutputAction = DefaultOutput;
}
/// <summary>
/// Get the current instance.
/// </summary>
public static ShaderDebugPrintManager instance => s_Instance;
/// <summary>
/// Set shader input constants.
/// </summary>
/// <param name="cmd">CommandBuffer to store the commands.</param>
/// <param name="input">Input parameters for the constants.</param>
public void SetShaderDebugPrintInputConstants(CommandBuffer cmd, ShaderDebugPrintInput input)
{
var mouse = new Vector4(input.pos.x, input.pos.y, input.leftDown ? 1 : 0, input.rightDown ? 1 : 0);
cmd.SetGlobalVector(m_ShaderPropertyIDInputMouse, mouse);
cmd.SetGlobalInt(m_ShaderPropertyIDInputFrame, m_FrameCounter);
}
/// <summary>
/// Binds the gpu-buffers for current frame.
/// </summary>
/// <param name="cmd">CommandBuffer to store the commands.</param>
public void SetShaderDebugPrintBindings(CommandBuffer cmd)
{
int index = m_FrameCounter % k_FramesInFlight;
if (!m_ReadbackRequests[index].done)
{
// We shouldn't end up here too often
m_ReadbackRequests[index].WaitForCompletion();
}
cmd.SetGlobalBuffer(m_shaderDebugOutputData, m_OutputBuffers[index]);
ClearShaderDebugPrintBuffer();
}
private void ClearShaderDebugPrintBuffer()
{
// Only clear the buffer the first time this is called in each frame
if (!m_FrameCleared)
{
int index = m_FrameCounter % k_FramesInFlight;
NativeArray<uint> data = new NativeArray<uint>(1, Allocator.Temp);
data[0] = 0;
m_OutputBuffers[index].SetData(data, 0, 0, 1);
m_FrameCleared = true;
}
}
private void BufferReadComplete(Rendering.AsyncGPUReadbackRequest request)
{
using var profScope = new ProfilingScope(Profiling.BufferReadComplete);
Assert.IsTrue(request.done);
if (!request.hasError)
{
NativeArray<uint> data = request.GetData<uint>(0);
uint count = data[0];
if (count >= k_MaxBufferElements)
{
count = k_MaxBufferElements;
// Shader print buffer is full, some data is lost!
Debug.LogWarning("Debug Shader Print Buffer Full!");
}
string newOutputLine = "";
if (count > 0)
newOutputLine += "Frame #" + m_FrameCounter + ": ";
unsafe // Need to do ugly casts via pointers
{
uint* ptr = (uint*)data.GetUnsafePtr();
for (int i = 1; i < count;)
{
DebugValueType type = (DebugValueType)(data[i] & 0x0f);
bool hasTag = (data[i] & k_TypeHasTag) == k_TypeHasTag;
// ensure elem for tag after the header
if (hasTag && i + 1 < count)
{
uint tagEncoded = data[i + 1];
i++;
for (int j = 0; j < 4; j++)
{
char c = (char)(tagEncoded & 255);
// skip '\0', for low-level output (avoid string termination)
if (c == 0)
continue;
newOutputLine += c;
tagEncoded >>= 8;
}
newOutputLine += " ";
}
// ensure elem for payload after the header/tag
int elemSize = DebugValueTypeToElemSize(type);
if (i + elemSize > count)
break;
i++; // [i] == payload
switch (type)
{
case DebugValueType.TypeUint:
{
newOutputLine += $"{data[i]}u";
break;
}
case DebugValueType.TypeInt:
{
int valueInt = *(int*)&ptr[i];
newOutputLine += valueInt;
break;
}
case DebugValueType.TypeFloat:
{
float valueFloat = *(float*)&ptr[i];
newOutputLine += $"{valueFloat}f";
break;
}
case DebugValueType.TypeUint2:
{
uint* valueUint2 = &ptr[i];
newOutputLine += $"uint2({valueUint2[0]}, {valueUint2[1]})";
break;
}
case DebugValueType.TypeInt2:
{
int* valueInt2 = (int*)&ptr[i];
newOutputLine += $"int2({valueInt2[0]}, {valueInt2[1]})";
break;
}
case DebugValueType.TypeFloat2:
{
float* valueFloat2 = (float*)&ptr[i];
newOutputLine += $"float2({valueFloat2[0]}, {valueFloat2[1]})";
break;
}
case DebugValueType.TypeUint3:
{
uint* valueUint3 = &ptr[i];
newOutputLine += $"uint3({valueUint3[0]}, {valueUint3[1]}, {valueUint3[2]})";
break;
}
case DebugValueType.TypeInt3:
{
int* valueInt3 = (int*)&ptr[i];
newOutputLine += $"int3({valueInt3[0]}, {valueInt3[1]}, {valueInt3[2]})";
break;
}
case DebugValueType.TypeFloat3:
{
float* valueFloat3 = (float*)&ptr[i];
newOutputLine += $"float3({valueFloat3[0]}, {valueFloat3[1]}, {valueFloat3[2]})";
break;
}
case DebugValueType.TypeUint4:
{
uint* valueUint4 = &ptr[i];
newOutputLine += $"uint4({valueUint4[0]}, {valueUint4[1]}, {valueUint4[2]}, {valueUint4[3]})";
break;
}
case DebugValueType.TypeInt4:
{
int* valueInt4 = (int*)&ptr[i];
newOutputLine += $"int4({valueInt4[0]}, {valueInt4[1]}, {valueInt4[2]}, {valueInt4[3]})";
break;
}
case DebugValueType.TypeFloat4:
{
float* valueFloat4 = (float*)&ptr[i];
newOutputLine += $"float4({valueFloat4[0]}, {valueFloat4[1]}, {valueFloat4[2]}, {valueFloat4[3]})";
break;
}
case DebugValueType.TypeBool:
{
newOutputLine += ((data[i] == 0) ? "False" : "True");
break;
}
default:
i = (int)count; // Cannot handle the rest if there is an unknown type
break;
}
i += elemSize;
newOutputLine += " ";
}
}
if (count > 0)
{
m_OutputLine = newOutputLine;
m_OutputAction(newOutputLine);
}
}
else
{
const string errorMsg = "Error at read back!";
m_OutputLine = errorMsg;
m_OutputAction(errorMsg);
}
}
/// <summary>
/// Initiate async read-back of the GPU buffer to the CPU.
/// Prepare a new GPU buffer for the next frame.
/// </summary>
public void EndFrame()
{
int index = m_FrameCounter % k_FramesInFlight;
m_ReadbackRequests[index] = Rendering.AsyncGPUReadback.Request(m_OutputBuffers[index], m_BufferReadCompleteAction);
m_FrameCounter++;
m_FrameCleared = false;
}
/// <summary>
/// Initiate synchronous read-back of the GPU buffer to the CPU and executes output action. By default prints to the debug log.
/// </summary>
public void PrintImmediate()
{
int index = m_FrameCounter % k_FramesInFlight;
var request = Rendering.AsyncGPUReadback.Request(m_OutputBuffers[index]);
request.WaitForCompletion();
m_BufferReadCompleteAction(request);
m_FrameCounter++;
m_FrameCleared = false;
}
// Custom output API
/// <summary>
/// Get current print line.
/// </summary>
public string outputLine { get => m_OutputLine; }
/// <summary>
/// Action taken for each print line. By default prints to the debug log.
/// </summary>
public Action<string> outputAction { set => m_OutputAction = value; }
/// <summary>
/// The default output action. Print to the debug log.
/// </summary>
/// <param name="line">Line to be printed.</param>
public void DefaultOutput(string line)
{
Debug.Log(line);
}
}
/// <summary>
/// Shader constant input parameters.
/// </summary>
public struct ShaderDebugPrintInput
{
// Mouse input for the shader
/// <summary>
/// Mouse position.
/// GameView bottom-left == (0,0) top-right == (surface.width, surface.height) where surface == game display surface/rendertarget
/// For screen pixel coordinates, game-view should be set to "Free Aspect".
/// Works only in PlayMode.
/// </summary>
public Vector2 pos { get; set; }
/// <summary>
/// Left mouse button is pressed.
/// </summary>
public bool leftDown { get; set; }
/// <summary>
/// Right mouse button is pressed.
/// </summary>
public bool rightDown { get; set; }
/// <summary>
/// Middle mouse button is pressed.
/// </summary>
public bool middleDown { get; set; }
/// <summary>
/// Pretty print parameters for debug purposes.
/// </summary>
/// <returns>A string containing debug information</returns>
// NOTE: Separate from ToString on purpose.
public string String()
{
return $"Mouse: {pos.x}x{pos.y} Btns: Left:{leftDown} Right:{rightDown} Middle:{middleDown} ";
}
}
/// <summary>
/// Reads system input to produce ShaderDebugPrintInput parameters.
/// </summary>
public static class ShaderDebugPrintInputProducer
{
/// <summary>
/// Read system input.
/// </summary>
/// <returns>Input parameters for ShaderDebugPrintManager.</returns>
static public ShaderDebugPrintInput Get()
{
var r = new ShaderDebugPrintInput();
#if ENABLE_LEGACY_INPUT_MANAGER
r.pos = Input.mousePosition;
r.leftDown = Input.GetMouseButton(0);
r.rightDown = Input.GetMouseButton(1);
r.middleDown = Input.GetMouseButton(2);
#endif
#if ENABLE_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM_PACKAGE
// NOTE: needs Unity.InputSystem asmdef reference.
var mouse = InputSystem.Mouse.current;
r.pos = mouse.position.ReadValue();
r.leftDown = mouse.leftButton.isPressed;
r.rightDown = mouse.rightButton.isPressed;
r.middleDown = mouse.middleButton.isPressed;
#endif
return r;
}
}
}
@@ -0,0 +1,3 @@
fileFormatVersion: 2
guid: 78ef234ccb554950b06f0b7f554b1573
timeCreated: 1592835102
@@ -0,0 +1,287 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using UnityEditor;
namespace UnityEngine.Rendering
{
/// <summary>
/// The volume settings
/// </summary>
/// <typeparam name="T">A <see cref="MonoBehaviour"/> with <see cref="IAdditionalData"/></typeparam>
[Obsolete("This is not longer supported Please use DebugDisplaySettingsVolume. #from(6000.2)")]
public abstract partial class VolumeDebugSettings<T> : IVolumeDebugSettings
where T : MonoBehaviour, IAdditionalData
{
/// <summary>Current volume component to debug.</summary>
public int selectedComponent { get; set; } = 0;
/// <summary>Current camera to debug.</summary>
public Camera selectedCamera => selectedCameraIndex < 0 ? null : cameras.ElementAt(selectedCameraIndex);
/// <summary>
/// The selected camera index, use the property for better handling
/// </summary>
protected int m_SelectedCameraIndex = -1;
/// <summary>Selected camera index.</summary>
public int selectedCameraIndex
{
get
{
var count = cameras.Count();
return count > 0 ? Math.Clamp(m_SelectedCameraIndex, 0, count-1) : -1;
}
set
{
var count = cameras.Count();
m_SelectedCameraIndex = Math.Clamp(value, 0, count-1);
}
}
private Camera[] m_CamerasArray;
private List<Camera> m_Cameras = new List<Camera>();
/// <summary>Returns the collection of registered cameras.</summary>
public IEnumerable<Camera> cameras
{
get
{
m_Cameras.Clear();
#if UNITY_EDITOR
if (SceneView.lastActiveSceneView != null)
{
var sceneCamera = SceneView.lastActiveSceneView.camera;
if (sceneCamera != null)
m_Cameras.Add(sceneCamera);
}
#endif
if (m_CamerasArray == null || m_CamerasArray.Length != Camera.allCamerasCount)
{
m_CamerasArray = new Camera[Camera.allCamerasCount];
}
Camera.GetAllCameras(m_CamerasArray);
foreach (var camera in m_CamerasArray)
{
if (camera == null)
continue;
if (camera.cameraType != CameraType.Preview && camera.cameraType != CameraType.Reflection)
{
if (!camera.TryGetComponent<T>(out T additionalData))
additionalData = camera.gameObject.AddComponent<T>();
if (additionalData != null)
m_Cameras.Add(camera);
}
}
return m_Cameras;
}
}
/// <summary>Selected camera volume stack.</summary>
public abstract VolumeStack selectedCameraVolumeStack { get; }
/// <summary>Selected camera volume layer mask.</summary>
public abstract LayerMask selectedCameraLayerMask { get; }
/// <summary>Selected camera volume position.</summary>
public abstract Vector3 selectedCameraPosition { get; }
/// <summary>Type of the current component to debug.</summary>
public Type selectedComponentType
{
get => selectedComponent > 0 ? volumeComponentsPathAndType[selectedComponent - 1].Item2 : null;
set
{
var index = volumeComponentsPathAndType.FindIndex(t => t.Item2 == value);
if (index != -1)
selectedComponent = index + 1;
}
}
/// <summary>List of Volume component types.</summary>
public List<(string, Type)> volumeComponentsPathAndType => VolumeManager.instance.GetVolumeComponentsForDisplay(GraphicsSettings.currentRenderPipelineAssetType);
/// <summary>
/// Specifies the render pipeline for this volume settings
/// </summary>
[Obsolete("This property is obsolete and kept only for not breaking user code. VolumeDebugSettings will use current pipeline when it needs to gather volume component types and paths. #from(2023.2)")]
public virtual Type targetRenderPipeline { get; }
internal VolumeParameter GetParameter(VolumeComponent component, FieldInfo field)
{
return (VolumeParameter)field.GetValue(component);
}
internal VolumeParameter GetParameter(FieldInfo field)
{
VolumeStack stack = selectedCameraVolumeStack;
return stack == null ? null : GetParameter(stack.GetComponent(selectedComponentType), field);
}
internal VolumeParameter GetParameter(Volume volume, FieldInfo field)
{
var profile = volume.HasInstantiatedProfile() ? volume.profile : volume.sharedProfile;
if (!profile.TryGet(selectedComponentType, out VolumeComponent component))
return null;
var param = GetParameter(component, field);
if (!param.overrideState)
return null;
return param;
}
float[] weights = null;
float ComputeWeight(Volume volume, Vector3 triggerPos)
{
if (volume == null) return 0;
var profile = volume.HasInstantiatedProfile() ? volume.profile : volume.sharedProfile;
if (!volume.gameObject.activeInHierarchy) return 0;
if (!volume.enabled || profile == null || volume.weight <= 0f) return 0;
if (!profile.TryGet(selectedComponentType, out VolumeComponent component)) return 0;
if (!component.active) return 0;
float weight = Mathf.Clamp01(volume.weight);
if (!volume.isGlobal)
{
#if ENABLE_PHYSICS_MODULE
var colliders = volume.colliders;
// Find closest distance to volume, 0 means it's inside it
float closestDistanceSqr = float.PositiveInfinity;
foreach (var collider in colliders)
{
if (!collider.enabled)
continue;
var closestPoint = collider.ClosestPoint(triggerPos);
var d = (closestPoint - triggerPos).sqrMagnitude;
if (d < closestDistanceSqr)
closestDistanceSqr = d;
}
float blendDistSqr = volume.blendDistance * volume.blendDistance;
if (closestDistanceSqr > blendDistSqr)
weight = 0f;
else if (blendDistSqr > 0f)
weight *= 1f - (closestDistanceSqr / blendDistSqr);
#endif
}
return weight;
}
Volume[] volumes = null;
/// <summary>Get an array of volumes on the <see cref="selectedCameraLayerMask"/></summary>
/// <returns>An array of volumes sorted by influence.</returns>
public Volume[] GetVolumes()
{
return VolumeManager.instance.GetVolumes(selectedCameraLayerMask)
.Where(v => v.sharedProfile != null)
.Reverse().ToArray();
}
VolumeParameter[,] savedStates = null;
VolumeParameter[,] GetStates()
{
var fields = selectedComponentType
.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
.Where(t => t.FieldType.IsSubclassOf(typeof(VolumeParameter)))
.ToArray();
VolumeParameter[,] states = new VolumeParameter[volumes.Length, fields.Length];
for (int i = 0; i < volumes.Length; i++)
{
var profile = volumes[i].HasInstantiatedProfile() ? volumes[i].profile : volumes[i].sharedProfile;
if (!profile.TryGet(selectedComponentType, out VolumeComponent component))
continue;
for (int j = 0; j < fields.Length; j++)
{
var param = GetParameter(component, fields[j]); ;
states[i, j] = param.overrideState ? param : null;
}
}
return states;
}
bool ChangedStates(VolumeParameter[,] newStates)
{
if (savedStates.GetLength(1) != newStates.GetLength(1))
return true;
for (int i = 0; i < savedStates.GetLength(0); i++)
{
for (int j = 0; j < savedStates.GetLength(1); j++)
{
if ((savedStates[i, j] == null) != (newStates[i, j] == null))
return true;
}
}
return false;
}
/// <summary>
/// Refreshes the volumes, fetches the stored volumes on the panel
/// </summary>
/// <param name="newVolumes">The list of <see cref="Volume"/> to refresh</param>
/// <returns>If the volumes have been refreshed</returns>
public bool RefreshVolumes(Volume[] newVolumes)
{
bool ret = false;
if (volumes == null || !newVolumes.SequenceEqual(volumes))
{
volumes = (Volume[])newVolumes.Clone();
savedStates = GetStates();
ret = true;
}
else
{
var newStates = GetStates();
if (savedStates == null || ChangedStates(newStates))
{
savedStates = newStates;
ret = true;
}
}
var triggerPos = selectedCameraPosition;
weights = new float[volumes.Length];
for (int i = 0; i < volumes.Length; i++)
weights[i] = ComputeWeight(volumes[i], triggerPos);
return ret;
}
/// <summary>
/// Obtains the volume weight
/// </summary>
/// <param name="volume"><see cref="Volume"/></param>
/// <returns>The weight of the volume</returns>
public float GetVolumeWeight(Volume volume)
{
// TODO: Store the calculated weight in the stack for the volumes that have influence and return it here
var triggerPos = selectedCameraPosition;
return ComputeWeight(volume, triggerPos);
}
/// <summary>
/// Return if the <see cref="Volume"/> has influence
/// </summary>
/// <param name="volume"><see cref="Volume"/> to check the influence</param>
/// <returns>If the volume has influence</returns>
public bool VolumeHasInfluence(Volume volume)
{
// TODO: Store the calculated weight in the stack for the volumes that have influence and return it here
var triggerPos = selectedCameraPosition;
return ComputeWeight(volume, triggerPos) > 0.0f;
}
}
}
@@ -0,0 +1,11 @@
fileFormatVersion: 2
guid: 4fefac0c47bcdce4299384727a250dc9
MonoImporter:
externalObjects: {}
serializedVersion: 2
defaultReferences: []
executionOrder: 0
icon: {instanceID: 0}
userData:
assetBundleName:
assetBundleVariant:
@@ -0,0 +1,103 @@
fileFormatVersion: 2
guid: 127279d577f25ac4ea17dae3782e5074
TextureImporter:
internalIDToNameTable: []
externalObjects: {}
serializedVersion: 10
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
isReadable: 0
streamingMipmaps: 0
streamingMipmapsPriority: 0
grayScaleToAlpha: 0
generateCubemap: 6
cubemapConvolution: 0
seamlessCubemap: 0
textureFormat: 1
maxTextureSize: 2048
textureSettings:
serializedVersion: 2
filterMode: -1
aniso: -1
mipBias: -100
wrapU: 1
wrapV: 1
wrapW: -1
nPOTScale: 0
lightmap: 0
compressionQuality: 50
spriteMode: 1
spriteExtrude: 1
spriteMeshType: 0
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
spriteTessellationDetail: -1
textureType: 8
textureShape: 1
singleChannelComponent: 0
maxTextureSizeSet: 0
compressionQualitySet: 0
textureFormatSet: 0
platformSettings:
- serializedVersion: 3
buildTarget: DefaultTexturePlatform
maxTextureSize: 32
resizeAlgorithm: 1
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 1
- serializedVersion: 3
buildTarget: Standalone
maxTextureSize: 32
resizeAlgorithm: 1
textureFormat: -1
textureCompression: 0
compressionQuality: 50
crunchedCompression: 0
allowsAlphaSplitting: 0
overridden: 0
androidETC2FallbackOverride: 0
forceMaximumCompressionQuality_BC6H_BC7: 1
spriteSheet:
serializedVersion: 2
sprites: []
outline: []
physicsShape: []
bones: []
spriteID: eec12fb14a4bf99489cbcab7362ea366
internalID: 0
vertices: []
indices:
edges: []
weights: []
secondaryTextures: []
spritePackingTag:
pSDRemoveMatte: 0
pSDShowRemoveMatteOption: 0
userData:
assetBundleName:
assetBundleVariant: