-
Notifications
You must be signed in to change notification settings - Fork 871
Expand file tree
/
Copy pathDebugWindow.cs
More file actions
694 lines (569 loc) · 25.2 KB
/
DebugWindow.cs
File metadata and controls
694 lines (569 loc) · 25.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
#if ENABLE_INPUT_SYSTEM && ENABLE_INPUT_SYSTEM_PACKAGE
#define USE_INPUT_SYSTEM
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.Callbacks;
using UnityEditor.Rendering.Analytics;
using UnityEditorInternal;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.Rendering;
namespace UnityEditor.Rendering
{
#pragma warning disable 414
[Serializable]
sealed class WidgetStateDictionary : SerializedDictionary<string, DebugState> { }
sealed class DebugWindowSettings : ScriptableObject
{
// Keep these settings in a separate scriptable object so we can handle undo/redo on them
// without the rest of the debug window interfering
public int currentStateHash;
public int selectedPanel
{
get => Mathf.Max(0, DebugManager.instance.PanelIndex(selectedPanelDisplayName));
set
{
var displayName = DebugManager.instance.PanelDiplayName(value);
if (!string.IsNullOrEmpty(displayName))
selectedPanelDisplayName = displayName;
}
}
public string selectedPanelDisplayName;
void OnEnable()
{
hideFlags = HideFlags.HideAndDontSave;
}
}
[CoreRPHelpURL("Rendering-Debugger")]
sealed class DebugWindow : EditorWindowWithHelpButton, IHasCustomMenu
{
static Styles s_Styles;
static GUIStyle s_SplitterLeft;
static float splitterPos = 150f;
const float minSideBarWidth = 100;
const float minContentWidth = 100;
bool dragging = false;
[SerializeField]
WidgetStateDictionary m_WidgetStates;
[SerializeField]
DebugWindowSettings m_Settings;
bool m_IsDirty;
Vector2 m_PanelScroll;
Vector2 m_ContentScroll;
static bool s_TypeMapDirty;
static Dictionary<Type, Type> s_WidgetStateMap; // DebugUI.Widget type -> DebugState type
static Dictionary<Type, DebugUIDrawer> s_WidgetDrawerMap; // DebugUI.Widget type -> DebugUIDrawer
public static bool open
{
get => DebugManager.instance.displayEditorUI;
private set => DebugManager.instance.displayEditorUI = value;
}
[DidReloadScripts]
static void OnEditorReload()
{
s_TypeMapDirty = true;
//find if it where open, relink static event end propagate the info
open = (Resources.FindObjectsOfTypeAll<DebugWindow>()?.Length ?? 0) > 0;
}
static void RebuildTypeMaps()
{
// Map states to widget (a single state can map to several widget types if the value to
// serialize is the same)
var attrType = typeof(DebugStateAttribute);
var stateTypes = CoreUtils.GetAllTypesDerivedFrom<DebugState>()
.Where(
t => t.IsDefined(attrType, false)
&& !t.IsAbstract
);
s_WidgetStateMap = new Dictionary<Type, Type>();
foreach (var stateType in stateTypes)
{
var attr = (DebugStateAttribute)stateType.GetCustomAttributes(attrType, false)[0];
foreach (var t in attr.types)
s_WidgetStateMap.Add(t, stateType);
}
// Drawers
attrType = typeof(DebugUIDrawerAttribute);
var types = CoreUtils.GetAllTypesDerivedFrom<DebugUIDrawer>()
.Where(
t => t.IsDefined(attrType, false)
&& !t.IsAbstract
);
s_WidgetDrawerMap = new Dictionary<Type, DebugUIDrawer>();
foreach (var t in types)
{
var attr = (DebugUIDrawerAttribute)t.GetCustomAttributes(attrType, false)[0];
var inst = (DebugUIDrawer)Activator.CreateInstance(t);
s_WidgetDrawerMap.Add(attr.type, inst);
}
// Done
s_TypeMapDirty = false;
}
[MenuItem("Window/Analysis/Rendering Debugger", priority = 10005)]
static void Init()
{
var window = GetWindow<DebugWindow>();
window.titleContent = Styles.windowTitle;
window.minSize = new Vector2(800f, 300f);
}
[MenuItem("Window/Analysis/Rendering Debugger", validate = true)]
static bool ValidateMenuItem()
{
return RenderPipelineManager.currentPipeline != null;
}
void OnEnable()
{
open = true;
DebugManager.instance.refreshEditorRequested = false;
hideFlags = HideFlags.HideAndDontSave;
autoRepaintOnSceneChange = true;
if (m_Settings == null)
m_Settings = CreateInstance<DebugWindowSettings>();
// States are ScriptableObjects (necessary for Undo/Redo) but are not saved on disk so when the editor is closed then reopened, any existing debug window will have its states set to null
// Since we don't care about persistence in this case, we just re-init everything.
if (m_WidgetStates == null || !AreWidgetStatesValid())
m_WidgetStates = new WidgetStateDictionary();
if (s_WidgetStateMap == null || s_WidgetDrawerMap == null || s_TypeMapDirty)
RebuildTypeMaps();
Undo.undoRedoPerformed += OnUndoRedoPerformed;
DebugManager.instance.onSetDirty += MarkDirty;
// First init
UpdateWidgetStates();
EditorApplication.update -= Repaint;
var panels = DebugManager.instance.panels;
var selectedPanelIndex = m_Settings.selectedPanel;
if (selectedPanelIndex >= 0
&& selectedPanelIndex < panels.Count
&& panels[selectedPanelIndex].editorForceUpdate)
EditorApplication.update += Repaint;
GraphicsToolLifetimeAnalytic.WindowOpened<DebugWindow>();
}
// Note: this won't get called if the window is opened when the editor itself is closed
void OnDestroy()
{
open = false;
DebugManager.instance.onSetDirty -= MarkDirty;
Undo.ClearUndo(m_Settings);
DestroyWidgetStates();
}
private void OnDisable()
{
GraphicsToolLifetimeAnalytic.WindowClosed<DebugWindow>();
}
public void DestroyWidgetStates()
{
if (m_WidgetStates == null)
return;
// Clear all the states from memory
foreach (var state in m_WidgetStates)
{
var s = state.Value;
Undo.ClearUndo(s); // Don't leave dangling states in the global undo/redo stack
DestroyImmediate(s);
}
m_WidgetStates.Clear();
}
public void ReloadWidgetStates()
{
if (m_WidgetStates == null)
return;
// Clear states from memory that don't have a corresponding widget
List<string> keysToRemove = new ();
foreach (var state in m_WidgetStates)
{
var widget = DebugManager.instance.GetItem(state.Key);
if (widget == null)
{
var s = state.Value;
Undo.ClearUndo(s); // Don't leave dangling states in the global undo/redo stack
DestroyImmediate(s);
keysToRemove.Add(state.Key);
}
}
// Cleanup null entries because they can break the dictionary serialization
foreach (var key in keysToRemove)
{
m_WidgetStates.Remove(key);
}
UpdateWidgetStates();
}
bool AreWidgetStatesValid()
{
foreach (var state in m_WidgetStates)
{
if (state.Value == null)
{
return false;
}
}
return true;
}
void MarkDirty()
{
m_IsDirty = true;
}
// We use item states to keep a cached value of each serializable debug items in order to
// handle domain reloads, play mode entering/exiting and undo/redo
// Note: no removal of orphan states
void UpdateWidgetStates()
{
foreach (var panel in DebugManager.instance.panels)
UpdateWidgetStates(panel);
}
DebugState GetOrCreateDebugStateForValueField(DebugUI.Widget widget)
{
// Skip runtime & readonly only items
if (widget.isInactiveInEditor)
return null;
if (widget is not DebugUI.IValueField valueField)
return null;
string queryPath = widget.queryPath;
if (!m_WidgetStates.TryGetValue(queryPath, out var state) || state == null)
{
var widgetType = widget.GetType();
if (s_WidgetStateMap.TryGetValue(widgetType, out Type stateType))
{
Assert.IsNotNull(stateType);
state = (DebugState)CreateInstance(stateType);
state.queryPath = queryPath;
state.SetValue(valueField.GetValue(), valueField);
m_WidgetStates[queryPath] = state;
}
}
return state;
}
void UpdateWidgetStates(DebugUI.IContainer container)
{
// Skip runtime only containers, we won't draw them so no need to serialize them either
if (container is DebugUI.Widget actualWidget && actualWidget.isInactiveInEditor)
return;
// Recursively update widget states
foreach (var widget in container.children)
{
// Skip non-serializable widgets but still traverse them in case one of their
// children needs serialization support
var state = GetOrCreateDebugStateForValueField(widget);
if (state != null)
continue;
// Recurse if the widget is a container
if (widget is DebugUI.IContainer containerField)
UpdateWidgetStates(containerField);
}
}
public void ApplyStates(bool forceApplyAll = false)
{
// If we are in playmode, and the runtime UI is shown, avoid that the editor UI
// applies the data of the internal debug states, as they are not kept in sync
if (Application.isPlaying && DebugManager.instance.displayRuntimeUI)
return;
if (!forceApplyAll && DebugState.m_CurrentDirtyState != null)
{
ApplyState(DebugState.m_CurrentDirtyState.queryPath, DebugState.m_CurrentDirtyState);
}
else
{
foreach (var state in m_WidgetStates)
ApplyState(state.Key, state.Value);
}
DebugState.m_CurrentDirtyState = null;
}
void ApplyState(string queryPath, DebugState state)
{
if (state == null || !(DebugManager.instance.GetItem(queryPath) is DebugUI.IValueField widget))
return;
widget.SetValue(state.GetValue());
}
void OnUndoRedoPerformed()
{
int stateHash = ComputeStateHash();
// Something has been undone / redone, re-apply states to the debug tree
if (stateHash != m_Settings.currentStateHash)
{
ApplyStates(true);
m_Settings.currentStateHash = stateHash;
}
Repaint();
}
int ComputeStateHash()
{
unchecked
{
int hash = 13;
foreach (var state in m_WidgetStates)
hash = hash * 23 + state.Value.GetHashCode();
return hash;
}
}
void Update()
{
// If the render pipeline asset has been reloaded we force-refresh widget states in case
// some debug values need to be refresh/recreated as well (e.g. frame settings on HD)
if (DebugManager.instance.refreshEditorRequested)
{
ReloadWidgetStates();
m_IsDirty = true;
DebugManager.instance.refreshEditorRequested = false;
}
int? requestedPanelIndex = DebugManager.instance.GetRequestedEditorWindowPanelIndex();
if (requestedPanelIndex != null)
{
m_Settings.selectedPanel = requestedPanelIndex.Value;
}
if (m_IsDirty)
{
UpdateWidgetStates();
ApplyStates();
m_IsDirty = false;
Repaint();
}
}
void OnGUI()
{
if (s_Styles == null)
{
s_Styles = new Styles();
s_SplitterLeft = new GUIStyle();
}
var panels = DebugManager.instance.panels;
int itemCount = panels.Count(x => !x.isInactiveInEditor && x.children.Count(w => !w.isInactiveInEditor) > 0);
if (itemCount == 0)
{
EditorGUILayout.HelpBox("No debug item found.", MessageType.Info);
return;
}
GUILayout.BeginHorizontal(EditorStyles.toolbar);
GUILayout.FlexibleSpace();
if (GUILayout.Button(Styles.resetButtonContent, EditorStyles.toolbarButton))
{
DebugManager.instance.Reset();
DestroyWidgetStates();
UpdateWidgetStates();
InternalEditorUtility.RepaintAllViews();
}
GUILayout.EndHorizontal();
using (new EditorGUILayout.HorizontalScope())
{
// Side bar
using (var scrollScope = new EditorGUILayout.ScrollViewScope(m_PanelScroll, s_Styles.sectionScrollView, GUILayout.Width(splitterPos)))
{
if (m_Settings.selectedPanel >= panels.Count)
m_Settings.selectedPanel = 0;
// Validate container id
while (panels[m_Settings.selectedPanel].isInactiveInEditor || panels[m_Settings.selectedPanel].children.Count(x => !x.isInactiveInEditor) == 0)
{
m_Settings.selectedPanel++;
if (m_Settings.selectedPanel >= panels.Count)
m_Settings.selectedPanel = 0;
}
// Root children are containers
for (int i = 0; i < panels.Count; i++)
{
var panel = panels[i];
if (panel.isInactiveInEditor)
continue;
if (panel.children.Count(x => !x.isInactiveInEditor) == 0)
continue;
var elementRect = GUILayoutUtility.GetRect(EditorGUIUtility.TrTextContent(panel.displayName), s_Styles.sectionElement, GUILayout.ExpandWidth(true));
if (m_Settings.selectedPanel == i && Event.current.type == EventType.Repaint)
s_Styles.selected.Draw(elementRect, false, false, false, false);
EditorGUI.BeginChangeCheck();
GUI.Toggle(elementRect, m_Settings.selectedPanel == i, panel.displayName, s_Styles.sectionElement);
if (EditorGUI.EndChangeCheck())
{
Undo.RegisterCompleteObjectUndo(m_Settings, $"Debug Panel '{panel.displayName}' Selection");
var previousPanel = m_Settings.selectedPanel >= 0 && m_Settings.selectedPanel < panels.Count
? panels[m_Settings.selectedPanel]
: null;
if (previousPanel != null && previousPanel.editorForceUpdate && !panel.editorForceUpdate)
EditorApplication.update -= Repaint;
else if ((previousPanel == null || !previousPanel.editorForceUpdate) && panel.editorForceUpdate)
EditorApplication.update += Repaint;
m_Settings.selectedPanel = i;
}
}
m_PanelScroll = scrollScope.scrollPosition;
}
Rect splitterRect = new Rect(splitterPos - 3, 0, 6, Screen.height);
GUI.Box(splitterRect, "", s_SplitterLeft);
const float topMargin = 2f;
GUILayout.Space(topMargin);
// Main section - traverse current container
using (var changedScope = new EditorGUI.ChangeCheckScope())
{
using (new EditorGUILayout.VerticalScope())
{
var selectedPanel = panels[m_Settings.selectedPanel];
using (new EditorGUILayout.HorizontalScope())
{
var style = new GUIStyle(CoreEditorStyles.sectionHeaderStyle) { fontStyle = FontStyle.Bold };
EditorGUILayout.LabelField(new GUIContent(selectedPanel.displayName), style);
// Context menu
var rect = GUILayoutUtility.GetLastRect();
var contextMenuRect = new Rect(rect.xMax, rect.y + 4f, 16f, 16f);
CoreEditorUtils.ShowHelpButton(contextMenuRect, selectedPanel.documentationUrl, new GUIContent($"{selectedPanel.displayName} panel."));
}
const float leftMargin = 4f;
GUILayout.Space(leftMargin);
using (var scrollScope = new EditorGUILayout.ScrollViewScope(m_ContentScroll))
{
const float scrollViewTopMargin = 4f;
GUILayout.Space(scrollViewTopMargin);
TraverseContainerGUI(selectedPanel);
m_ContentScroll = scrollScope.scrollPosition;
const float scrollViewBottomMargin = 10f;
GUILayout.Space(scrollViewBottomMargin);
}
}
if (changedScope.changed)
{
m_Settings.currentStateHash = ComputeStateHash();
DebugManager.instance.ReDrawOnScreenDebug();
}
}
// Splitter events
if (Event.current != null)
{
switch (Event.current.rawType)
{
case EventType.MouseDown:
if (splitterRect.Contains(Event.current.mousePosition))
{
dragging = true;
}
break;
case EventType.MouseDrag:
if (dragging)
{
splitterPos += Event.current.delta.x;
splitterPos = Mathf.Clamp(splitterPos, minSideBarWidth, position.width - minContentWidth);
Repaint();
}
break;
case EventType.MouseUp:
if (dragging)
{
dragging = false;
}
break;
}
}
EditorGUIUtility.AddCursorRect(splitterRect, MouseCursor.ResizeHorizontal);
}
}
void OnWidgetGUI(DebugUI.Widget widget)
{
if (widget.isInactiveInEditor || widget.isHidden)
return;
if (widget.queryPath == null)
{
Debug.LogError($"Widget {widget.GetType()} query path is null");
return;
}
if (!s_WidgetDrawerMap.TryGetValue(widget.GetType(), out DebugUIDrawer drawer))
{
foreach (var pair in s_WidgetDrawerMap)
{
if (pair.Key.IsAssignableFrom(widget.GetType()))
{
drawer = pair.Value;
break;
}
}
}
if (drawer == null)
EditorGUILayout.LabelField("Drawer not found (" + widget.GetType() + ").");
else
{
var state = GetOrCreateDebugStateForValueField(widget);
drawer.Begin(widget, state);
if (drawer.OnGUI(widget, state))
{
if (widget is DebugUI.IContainer container)
TraverseContainerGUI(container);
}
drawer.End(widget, state);
}
}
void TraverseContainerGUI(DebugUI.IContainer container)
{
// /!\ SHAAAAAAAME ALERT /!\
// A container can change at runtime because of the way IMGUI works and how we handle
// onValueChanged on widget so we have to take this into account while iterating
try
{
foreach (var widget in container.children)
OnWidgetGUI(widget);
}
catch (InvalidOperationException)
{
Repaint();
}
}
public class Styles
{
public static float s_DefaultLabelWidth = 0.5f;
public static GUIContent windowTitle { get; } = EditorGUIUtility.TrTextContent("Rendering Debugger");
public static GUIContent resetButtonContent { get; } = EditorGUIUtility.TrTextContent("Reset");
public static GUIStyle foldoutHeaderStyle { get; } = new GUIStyle(EditorStyles.foldoutHeader)
{
fixedHeight = 20,
fontStyle = FontStyle.Bold,
margin = new RectOffset(0, 0, 0, 0)
};
public static GUIStyle labelWithZeroValueStyle { get; } = new GUIStyle(EditorStyles.label);
public readonly GUIStyle sectionScrollView = "PreferencesSectionBox";
public readonly GUIStyle sectionElement = new GUIStyle("PreferencesSection");
public readonly GUIStyle selected = "OL SelectedRow";
public static GUIStyle centeredLeft = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleLeft };
public static GUIStyle centeredLeftAlternate = new GUIStyle(EditorStyles.label) { alignment = TextAnchor.MiddleLeft };
public static float singleRowHeight = EditorGUIUtility.singleLineHeight + EditorGUIUtility.standardVerticalSpacing;
public static int foldoutColumnWidth = 70;
public Styles()
{
centeredLeftAlternate.normal.background = CoreEditorUtils.CreateColoredTexture2D(
EditorGUIUtility.isProSkin
? new Color(63 / 255.0f, 63 / 255.0f, 63 / 255.0f, 255 / 255.0f)
: new Color(211 / 255.0f, 211 / 255.0f, 211 / 255.0f, 211 / 255.0f),
"centeredLeftAlternate Background");
sectionScrollView = new GUIStyle(sectionScrollView);
sectionScrollView.overflow.bottom += 1;
sectionElement.alignment = TextAnchor.MiddleLeft;
labelWithZeroValueStyle.normal.textColor = Color.gray;
// Make sure that textures are unloaded on domain reloads.
void OnBeforeAssemblyReload()
{
DestroyImmediate(centeredLeftAlternate.normal.background);
AssemblyReloadEvents.beforeAssemblyReload -= OnBeforeAssemblyReload;
}
AssemblyReloadEvents.beforeAssemblyReload += OnBeforeAssemblyReload;
}
}
public void AddItemsToMenu(GenericMenu menu)
{
menu.AddItem(EditorGUIUtility.TrTextContent("Expand All"), false, () => SetExpanded(true));
menu.AddItem(EditorGUIUtility.TrTextContent("Collapse All"), false, () => SetExpanded(false));
}
void SetExpanded(bool value)
{
var panels = DebugManager.instance.panels;
foreach (var p in panels)
{
foreach (var w in p.children)
{
if (w.GetType() == typeof(DebugUI.Foldout))
{
if (m_WidgetStates.TryGetValue(w.queryPath, out DebugState state))
{
var foldout = (DebugUI.Foldout)w;
state.SetValue(value, foldout);
foldout.SetValue(value);
}
}
}
}
}
}
#pragma warning restore 414
}