-
Notifications
You must be signed in to change notification settings - Fork 877
Expand file tree
/
Copy pathDebugUI.Fields.cs
More file actions
1902 lines (1672 loc) · 70.7 KB
/
Copy pathDebugUI.Fields.cs
File metadata and controls
1902 lines (1672 loc) · 70.7 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
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#if ENABLE_UIELEMENTS_MODULE && (UNITY_EDITOR || DEVELOPMENT_BUILD)
#define ENABLE_RENDERING_DEBUGGER_UI
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;
using Assert = UnityEngine.Assertions.Assert;
#if ENABLE_RENDERING_DEBUGGER_UI
using UnityEngine.UIElements;
#endif
namespace UnityEngine.Rendering
{
internal interface ISupportsLegacyStateHandling
{
bool RequiresLegacyStateHandling();
}
public partial class DebugUI
{
/// <summary>
/// Generic field.
/// </summary>
/// <example>
/// <code>
/// public class CustomRectField : DebugUI.Field<Rect>
/// {
/// protected override VisualElement Create()
/// {
/// var field = new RectField()
/// {
/// label = displayName,
/// };
/// return field;
/// }
/// }
/// </code>
/// </example>
/// <typeparam name="T">The type of data managed by the field.</typeparam>
public abstract class Field<T> : Widget
#pragma warning disable CS0618 // Type or member is obsolete
, IValueField
#pragma warning restore CS0618 // Type or member is obsolete
, ISupportsLegacyStateHandling
{
/// <summary>
/// Getter for this field.
/// </summary>
public Func<T> getter { get; set; }
/// <summary>
/// Setter for this field.
/// </summary>
public Action<T> setter { get; set; }
// This should be an `event` but they don't play nice with object initializers in the
// version of C# we use.
/// <summary>
/// Callback used when the value of the field changes.
/// </summary>
public Action<Field<T>, T> onValueChanged;
/// <summary>
/// Function used to validate the value when updating the field.
/// </summary>
/// <param name="value">Input value.</param>
/// <returns>Validated value.</returns>
object IValueField.ValidateValue(object value)
{
return ValidateValue((T)value);
}
/// <summary>
/// Function used to validate the value when updating the field.
/// </summary>
/// <param name="value">Input value.</param>
/// <returns>Validated value.</returns>
public virtual T ValidateValue(T value)
{
return value;
}
/// <summary>
/// Get the value of the field.
/// </summary>
/// <returns>Value of the field.</returns>
object IValueField.GetValue()
{
return GetValue();
}
/// <summary>
/// Get the value of the field.
/// </summary>
/// <returns>Value of the field.</returns>
public T GetValue()
{
Assert.IsNotNull(getter);
return getter();
}
/// <summary>
/// Set the value of the field.
/// </summary>
/// <param name="value">Input value.</param>
public void SetValue(object value)
{
SetValue((T)value);
}
/// <summary>
/// Set the value of the field.
/// </summary>
/// <param name="value">Input value.</param>
public virtual void SetValue(T value)
{
if (setter == null)
return;
var v = ValidateValue(value);
if (v == null || !v.Equals(getter()))
{
#if UNITY_EDITOR
T previousValue = GetValue();
onWidgetValueChangedAnalytic?.Invoke(queryPath, previousValue, v);
#endif
setter(v);
onValueChanged?.Invoke(this, v);
}
}
internal static Action<string, T, T> onWidgetValueChangedAnalytic;
// In order to support the legacy DebugState system, we are inspecting the closure of the `getter` lambda, to see if the captured
// data is using the ISerializedDebugDisplaySettings interface. We know that any data that uses the new interface does not need
// legacy state handling. This is a temporary solution until we fully migrate to the new system and remove DebugState.
bool ISupportsLegacyStateHandling.RequiresLegacyStateHandling()
{
bool FieldsHaveISerializedDebugDisplaySettings(object obj)
{
if (obj == null)
return false;
var fields = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public);
foreach (var field in fields)
{
var value = field.GetValue(obj);
if (value is ISerializedDebugDisplaySettings)
return true;
}
return false;
}
var getterClosure = getter.Target;
if (getterClosure != null)
{
bool foundISerializedDebugDisplaySettings = FieldsHaveISerializedDebugDisplaySettings(getterClosure);
return !foundISerializedDebugDisplaySettings;
}
return false;
}
}
/// <summary>
/// Boolean field.
/// </summary>
public class BoolField : Field<bool>
{
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var toggle = new UIElements.Toggle();
BaseFieldHelper.ConfigureBaseField(this, toggle);
return toggle;
}
#endif
}
/// <summary>
/// An array of checkboxes that Unity displays in a horizontal row.
/// </summary>
public class HistoryBoolField : BoolField
{
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var valueContainer = new UIElements.VisualElement();
valueContainer.AddToClassList("debug-window-historyboolfield");
var label = new Label(displayName)
{
style = { width = ValueTuple.GetLabelWidth(m_Context) }
};
label.AddToClassList("debug-window-search-filter-target");
valueContainer.Add(label);
var boolField = new DebugUI.BoolField()
{
displayName = string.Empty,
tooltip = tooltip,
getter = getter,
setter = setter,
};
childWidgets.Add(boolField);
valueContainer.Add(boolField.ToVisualElement(m_Context));
foreach (var value in historyGetter)
{
var historyBoolField = new DebugUI.BoolField()
{
displayName = string.Empty,
getter = value
};
childWidgets.Add(historyBoolField);
var field = historyBoolField.ToVisualElement(m_Context);
field.SetEnabled(false);
valueContainer.Add(field);
}
valueContainer.AddToClassList(UIElements.BaseField<bool>.alignedFieldUssClassName);
return valueContainer;
}
#endif
internal List<Widget> childWidgets { private set; get; } = new List<Widget>();
/// <summary>
/// History getter for this field.
/// </summary>
public Func<bool>[] historyGetter { get; set; }
/// <summary>
/// Depth of the field's history.
/// </summary>
public int historyDepth => historyGetter?.Length ?? 0;
/// <summary>
/// Get the value of the field at a certain history index.
/// </summary>
/// <param name="historyIndex">Index of the history to query.</param>
/// <returns>Value of the field at the provided history index.</returns>
public bool GetHistoryValue(int historyIndex)
{
Assert.IsNotNull(historyGetter);
Assert.IsTrue(historyIndex >= 0 && historyIndex < historyGetter.Length, "out of range historyIndex");
Assert.IsNotNull(historyGetter[historyIndex]);
return historyGetter[historyIndex]();
}
}
/// <summary>
/// A slider for an integer.
/// </summary>
public class IntField : Field<int>
{
/// <summary>
/// Minimum value function.
/// </summary>
public Func<int> min;
/// <summary>
/// Maximum value function.
/// </summary>
public Func<int> max;
// Runtime-only
/// <summary>
/// Step increment.
/// </summary>
public int incStep = 1;
/// <summary>
/// Step increment multiplier.
/// </summary>
[Obsolete("Use incStepMult instead #from(6000.5) (UnityUpgradable) -> incStepMult")]
public int intStepMult = 10;
/// <summary>
/// Step increment multiplier.
/// </summary>
public int incStepMult = 10;
/// <summary>
/// Function used to validate the value when updating the field.
/// </summary>
/// <param name="value">Input value.</param>
/// <returns>Validated value.</returns>
public override int ValidateValue(int value)
{
if (min != null) value = Mathf.Max(value, min());
if (max != null) value = Mathf.Min(value, max());
return value;
}
internal override void OnDecrement(bool fast)
{
int currentValue = GetValue();
int step = fast ? incStepMult : incStep;
int minValue = min != null ? min() : int.MinValue;
// Check if subtraction would cause overflow, set to max value instead of wrapping around
int newValue = currentValue >= minValue + step ? currentValue - step : minValue;
SetValue(newValue);
}
internal override void OnIncrement(bool fast)
{
int currentValue = GetValue();
int step = fast ? incStepMult : incStep;
int maxValue = max != null ? max() : int.MaxValue;
// Check if addition would cause overflow, set to max value instead of wrapping around
int newValue = currentValue <= maxValue-step ? currentValue + step : maxValue;
SetValue(newValue);
}
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
if (m_Context.IsAnyRuntimeContext())
{
var field = new UIElements.IntegerField();
DebugUIStepperHelper.AddStepper(
field,
SetValue,
GetValue,
onDecrement: OnDecrement,
onIncrement: OnIncrement
);
BaseFieldHelper.ConfigureBaseField(this, field);
return field;
}
if (min != null || max != null)
{
var field = new UIElements.SliderInt(min?.Invoke() ?? int.MinValue, max?.Invoke() ?? int.MaxValue);
BaseFieldHelper.ConfigureBaseField(this, field);
field.showInputField = true;
return field;
}
else
{
var field = new UIElements.IntegerField();
BaseFieldHelper.ConfigureBaseField(this, field);
return field;
}
}
#endif
}
/// <summary>
/// A slider for a positive integer.
/// </summary>
public class UIntField : Field<uint>
{
/// <summary>
/// Minimum value function.
/// </summary>
public Func<uint> min;
/// <summary>
/// Maximum value function.
/// </summary>
public Func<uint> max;
// Runtime-only
/// <summary>
/// Step increment.
/// </summary>
public uint incStep = 1u;
/// <summary>
/// Step increment multiplier.
/// </summary>
[Obsolete("Use incStepMult instead #from(6000.5) (UnityUpgradable) -> incStepMult")]
public uint intStepMult = 10u;
/// <summary>
/// Step increment multiplier.
/// </summary>
public uint incStepMult = 10u;
/// <summary>
/// Function used to validate the value when updating the field.
/// </summary>
/// <param name="value">Input value.</param>
/// <returns>Validated value.</returns>
public override uint ValidateValue(uint value)
{
if (min != null) value = (uint)Mathf.Max(value, min());
if (max != null) value = (uint)Mathf.Min(value, max());
return value;
}
internal override void OnDecrement(bool fast)
{
uint currentValue = GetValue();
uint step = fast ? incStepMult : incStep;
uint minValue = min != null ? min() : uint.MinValue;
// Check if subtraction would cause overflow, set to max value instead of wrapping around
uint newValue = currentValue >= minValue + step ? currentValue - step : minValue;
SetValue(newValue);
}
internal override void OnIncrement(bool fast)
{
uint currentValue = GetValue();
uint step = fast ? incStepMult : incStep;
uint maxValue = max != null ? max() : uint.MaxValue;
// Check if addition would cause overflow, set to max value instead of wrapping around
uint newValue = currentValue <= maxValue-step ? currentValue + step : maxValue;
SetValue(newValue);
}
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var field = new UIElements.UnsignedIntegerField();
if (m_Context.IsAnyRuntimeContext())
{
field.RegisterCallback<FocusOutEvent>(evt =>
{
var validatedValue = ValidateValue(field.value);
if (validatedValue != field.value)
{
field.SetValueWithoutNotify(validatedValue);
SetValue(validatedValue);
}
});
DebugUIStepperHelper.AddStepper(
field,
SetValue,
GetValue,
onDecrement: OnDecrement,
onIncrement: OnIncrement
);
}
BaseFieldHelper.ConfigureBaseField(this, field);
field.RegisterCallback<ChangeEvent<uint>>((evt) =>
{
field.SetValueWithoutNotify(ValidateValue(evt.newValue));
});
return field;
}
#endif
}
/// <summary>
/// A slider for a float.
/// </summary>
public class FloatField : Field<float>
{
/// <summary>
/// Minimum value function.
/// </summary>
public Func<float> min;
/// <summary>
/// Maximum value function.
/// </summary>
public Func<float> max;
// Runtime-only
/// <summary>
/// Step increment.
/// </summary>
public float incStep = 0.1f;
/// <summary>
/// Step increment multiplier.
/// </summary>
public float incStepMult = 10f;
/// <summary>
/// Number of decimals.
/// </summary>
public int decimals = 3;
/// <summary>
/// Function used to validate the value when updating the field.
/// </summary>
/// <param name="value">Input value.</param>
/// <returns>Validated value.</returns>
public override float ValidateValue(float value)
{
if (min != null) value = Mathf.Max(value, min());
if (max != null) value = Mathf.Min(value, max());
return value;
}
#if ENABLE_RENDERING_DEBUGGER_UI
internal override void OnDecrement(bool fast)
{
float currentValue = GetValue();
float step = fast ? incStepMult : incStep;
float minValue = min != null ? min() : float.MinValue;
// Check if subtraction would cause overflow, set to max value instead of wrapping around
float newValue = currentValue >= minValue + step ? currentValue - step : minValue;
// Float precision: detect desired number of decimal places based on the step, and round to that
newValue = DebugUIStepperHelper.RoundToPrecision(newValue, currentValue, step);
SetValue(newValue);
}
internal override void OnIncrement(bool fast)
{
float currentValue = GetValue();
float step = fast ? incStepMult : incStep;
float maxValue = max != null ? max() : float.MaxValue;
// Check if addition would cause overflow, set to max value instead of wrapping around
float newValue = currentValue <= maxValue-step ? currentValue + step : maxValue;
// Float precision: detect desired number of decimal places based on the step, and round to that
newValue = DebugUIStepperHelper.RoundToPrecision(newValue, currentValue, step);
SetValue(newValue);
}
/// <inheritdoc/>
protected override VisualElement Create()
{
if (m_Context.IsAnyRuntimeContext())
{
var field = new UIElements.FloatField();
DebugUIStepperHelper.AddStepper(
field,
SetValue,
GetValue,
onDecrement: OnDecrement,
onIncrement: OnIncrement
);
BaseFieldHelper.ConfigureBaseField(this, field);
return field;
}
if (min != null || max != null)
{
var field = new UIElements.Slider(min?.Invoke() ?? float.MinValue, max?.Invoke() ?? float.MaxValue);
BaseFieldHelper.ConfigureBaseField(this, field);
field.showInputField = true;
return field;
}
else
{
var field = new UIElements.FloatField();
BaseFieldHelper.ConfigureBaseField(this, field);
return field;
}
}
#endif
}
/// <summary>
/// Field that displays <see cref="RenderingLayerMask"/>
/// </summary>
public class RenderingLayerField : Field<RenderingLayerMask>, IContainer
{
static readonly NameAndTooltip s_RenderingLayerColors = new()
{
name = "Layers Color",
tooltip = "Select the display color for each Rendering Layer"
};
private string[] m_RenderingLayersNames = Array.Empty<string>();
private int m_DefinedRenderingLayersCount = -1;
private int maxRenderingLayerCount
{
get
{
#if UNITY_EDITOR
if (UnityEditor.Rendering.EditorGraphicsSettings.
TryGetFirstRenderPipelineSettingsFromInterface<UnityEditor.Rendering.RenderingLayersLimitSettings>(out var settings))
return Mathf.Min(settings.maxSupportedRenderingLayers, RenderingLayerMask.GetRenderingLayerCount());
#endif
return RenderingLayerMask.GetRenderingLayerCount();
}
}
#if ENABLE_RENDERING_DEBUGGER_UI
protected override VisualElement Create()
{
var maskField = new UIElements.MaskField(displayName, new List<string>(m_RenderingLayersNames), 0);
maskField.labelElement.AddToClassList("debug-window-search-filter-target");
maskField.RegisterCallback<ChangeEvent<int>>(evt =>
{
SetValue(evt.newValue);
});
this.ScheduleTracked(maskField, () => maskField.schedule.Execute(() =>
{
var value = GetValue();
maskField.SetValueWithoutNotify(Convert.ToInt32(value));
})
.Every(100));
maskField.AddToClassList(UIElements.BaseField<int>.alignedFieldUssClassName);
HackPopupHoverColor(maskField, m_Context);
var content = new VisualElement();
content.AddToClassList("debug-window-renderinglayerfield__content");
foreach (var child in children)
{
var childUIElement = child.ToVisualElement(m_Context);
if (childUIElement != null)
{
childUIElement.RemoveFromClassList("debug-window-foldout");
content.Add(childUIElement);
}
}
VisualElement container = new VisualElement();
container.AddToClassList("unity-inspector-element");
container.AddToClassList("debug-window-renderinglayerfield");
container.Add(maskField);
container.Add(content);
return container;
}
#endif
private void Resize()
{
m_DefinedRenderingLayersCount = RenderingLayerMask.GetDefinedRenderingLayerCount();
// Fill layer names
m_RenderingLayersNames = new string[maxRenderingLayerCount];
for (int i = 0; i < maxRenderingLayerCount; i++)
{
var definedLayerName = RenderingLayerMask.RenderingLayerToName(i);
if (string.IsNullOrEmpty(definedLayerName))
definedLayerName = $"Unused Rendering Layer {i}";
m_RenderingLayersNames[i] = definedLayerName;
}
// Foldout + Color for each layer
m_RenderingLayersColors.Clear();
var layersColor = new DebugUI.Foldout()
{
nameAndTooltip = s_RenderingLayerColors,
flags = Flags.EditorOnly,
parent = this,
};
m_RenderingLayersColors.Add(layersColor);
for (int i = 0; i < m_RenderingLayersNames.Length; i++)
{
var index = i; // capture the variable for the color field index
layersColor.children.Add(new DebugUI.ColorField
{
displayName = m_RenderingLayersNames[index],
getter = () =>
{
Assert.IsNotNull(getRenderingLayerColor, "Please specify a method for getting the rendering layer color");
return getRenderingLayerColor(index);
},
setter = value =>
{
Assert.IsNotNull(setRenderingLayerColor, "Please specify a method for setting the rendering layer color");
setRenderingLayerColor(value, index);
}
});
}
GenerateQueryPath();
}
/// <summary>
/// Obtains the list of the available rendering layer names
/// </summary>
public string[] renderingLayersNames
{
get
{
if (m_DefinedRenderingLayersCount != RenderingLayerMask.GetDefinedRenderingLayerCount())
{
Resize();
}
return m_RenderingLayersNames;
}
}
private ObservableList<Widget> m_RenderingLayersColors = new ObservableList<Widget>();
/// <summary>
/// Gets the list of widgets representing the rendering layer colors.
/// </summary>
public ObservableList<Widget> children
{
get
{
if (m_DefinedRenderingLayersCount != RenderingLayerMask.GetDefinedRenderingLayerCount())
{
Resize();
}
return m_RenderingLayersColors;
}
}
/// <summary>
/// Obtains the color in a given index
/// </summary>
public Func<int, Vector4> getRenderingLayerColor { get; set; }
/// <summary>
/// Sets the color for a given index
/// </summary>
public Action<Vector4, int> setRenderingLayerColor { get; set; }
internal override void GenerateQueryPath()
{
base.GenerateQueryPath();
int numChildren = children.Count;
for (int i = 0; i < numChildren; i++)
children[i].GenerateQueryPath();
}
}
/// <summary>
/// Generic <see cref="EnumField"/> that stores enumNames and enumValues
/// </summary>
/// <typeparam name="T">The inner type of the field</typeparam>
public abstract class EnumField<T> : Field<T>
{
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var field = new UIElements.PopupField<string>()
{
label = displayName,
choices = enumNames.Select(e => e.text).ToList()
};
field.AddToClassList("debug-window-enumfield");
field.labelElement.AddToClassList("debug-window-search-filter-target");
field.AddToClassList(UIElements.BaseField<int>.alignedFieldUssClassName);
this.ScheduleTracked(field, () => field.schedule.Execute(() =>
{
T value = GetValue();
var index = Array.IndexOf(enumValues, value);
if (index >= 0 && index < enumNames.Length)
{
var expectedValue = enumNames[index].text;
if (field.value != expectedValue)
{
field.SetValueWithoutNotify(expectedValue);
}
}
}).Every(100));
m_AdditionalSearchText = string.Join(",", field.choices);
return field;
}
#endif
/// <summary>
/// List of names of the enumerator entries.
/// </summary>
public GUIContent[] enumNames;
private int[] m_EnumValues;
/// <summary>
/// List of values of the enumerator entries.
/// </summary>
public int[] enumValues
{
get => m_EnumValues;
set
{
if (value?.Distinct().Count() != value?.Count())
Debug.LogWarning($"{displayName} - The values of the enum are duplicated, this might lead to a errors displaying the enum");
m_EnumValues = value;
}
}
// Space-delimit PascalCase (https://stackoverflow.com/questions/155303/net-how-can-you-split-a-caps-delimited-string-into-an-array)
static Regex s_NicifyRegEx = new("([a-z](?=[A-Z])|[A-Z](?=[A-Z][a-z]))", RegexOptions.Compiled);
/// <summary>
/// Automatically fills the enum names with a given <see cref="Type"/>
/// </summary>
/// <param name="enumType">The enum type</param>
/// <param name="removeZeroElement">Whether the item with the value zero should be removed from enumNames and enumValues</param>
protected void AutoFillFromType(Type enumType, bool removeZeroElement = false)
{
if (enumType == null || !enumType.IsEnum)
throw new ArgumentException($"{nameof(enumType)} must not be null and it must be an Enum type");
using (ListPool<GUIContent>.Get(out var tmpNames))
using (ListPool<int>.Get(out var tmpValues))
{
var enumEntries = enumType.GetFields(BindingFlags.Public | BindingFlags.Static)
.Where(fieldInfo => !fieldInfo.IsDefined(typeof(ObsoleteAttribute)) && !fieldInfo.IsDefined(typeof(HideInInspector)));
foreach (var fieldInfo in enumEntries)
{
var description = fieldInfo.GetCustomAttribute<InspectorNameAttribute>();
var displayName = new GUIContent(description == null ? s_NicifyRegEx.Replace(fieldInfo.Name, "$1 ") : description.displayName);
int fieldValue = (int)Enum.Parse(enumType, fieldInfo.Name);
if (removeZeroElement && fieldValue == 0)
continue;
tmpNames.Add(displayName);
tmpValues.Add(fieldValue);
}
enumNames = tmpNames.ToArray();
enumValues = tmpValues.ToArray();
}
}
}
#if ENABLE_RENDERING_DEBUGGER_UI
private static void HackPopupHoverColor(VisualElement popupField, in DebugUI.Context context)
{
if (context == DebugUI.Context.Runtime)
{
// For some reason. it seems impossible to override the hover color of the popup field.
// This works because C# style overrides have higher precedence than any USS stuff.
Color hoverColor = new Color32(0x66, 0x66, 0x66, 0xFF); // Should match --widget-background-color-hover
popupField.RegisterCallback<MouseEnterEvent>(evt =>
{
var inputElement = popupField.Q<VisualElement>(className: "unity-base-field__input");
if (inputElement != null)
inputElement.style.backgroundColor = hoverColor;
});
popupField.RegisterCallback<MouseLeaveEvent>(evt =>
{
var inputElement = popupField.Q<VisualElement>(className: "unity-base-field__input");
if (inputElement != null)
inputElement.style.backgroundColor = new StyleColor(StyleKeyword.Null);
});
}
}
#endif
/// <summary>
/// A dropdown that contains the values from an enum.
/// </summary>
public class EnumField : EnumField<int>
{
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var field = new UIElements.PopupField<string>()
{
label = displayName,
choices = enumNames.Select(e => e.text).ToList()
};
field.AddToClassList("debug-window-enumfield");
field.labelElement.AddToClassList("debug-window-search-filter-target");
field.AddToClassList(UIElements.BaseField<int>.alignedFieldUssClassName);
HackPopupHoverColor(field, m_Context);
field.RegisterCallback<ChangeEvent<string>>(evt =>
{
for (int i = 0; i < enumNames.Length; i++)
{
if (evt.newValue == enumNames[i].text)
{
SetValue(enumValues[i]);
break;
}
}
});
this.ScheduleTracked(field, () => field.schedule.Execute(() =>
{
if (currentIndex >= 0 && currentIndex < enumNames.Length)
field.SetValueWithoutNotify(enumNames[currentIndex].text);
}).Every(100));
m_AdditionalSearchText = string.Join(",", field.choices);
return field;
}
#endif
internal int[] quickSeparators;
private int[] m_Indexes;
internal int[] indexes => m_Indexes ??= Enumerable.Range(0, enumNames?.Length ?? 0).ToArray();
/// <summary>
/// Get the enumeration value index.
/// </summary>
public Func<int> getIndex { get; set; }
/// <summary>
/// Set the enumeration value index.
/// </summary>
public Action<int> setIndex { get; set; }
/// <summary>
/// Current enumeration value index.
/// </summary>
public int currentIndex
{
get => getIndex();
set => setIndex(value);
}
private Type m_Type;
/// <summary>
/// Generates enumerator values and names automatically based on the provided type.
/// </summary>
public Type autoEnum
{
set
{
if (m_Type != value)
{
AutoFillFromType(value);
InitQuickSeparators();
m_Type = value;
}
}
}
internal void InitQuickSeparators()
{
var enumNamesPrefix = enumNames.Select(x =>
{
string[] splitted = x.text.Split('/');
if (splitted.Length == 1)
return "";
else
return splitted[0];
});
quickSeparators = new int[enumNamesPrefix.Distinct().Count()];
string lastPrefix = null;
for (int i = 0, wholeNameIndex = 0; i < quickSeparators.Length; ++i)
{
var currentTestedPrefix = enumNamesPrefix.ElementAt(wholeNameIndex);
while (lastPrefix == currentTestedPrefix)
{
currentTestedPrefix = enumNamesPrefix.ElementAt(++wholeNameIndex);
}
lastPrefix = currentTestedPrefix;
quickSeparators[i] = wholeNameIndex++;
}
}
/// <summary>
/// Set the value of the field.
/// </summary>
/// <param name="value">Input value.</param>
public override void SetValue(int value)
{
Assert.IsNotNull(setter);
var validValue = ValidateValue(value);
// There might be cases that the value does not map the index, look for the correct index
var newCurrentIndex = Array.IndexOf(enumValues, validValue);
if (currentIndex != newCurrentIndex && !validValue.Equals(getter()))
{
#if UNITY_EDITOR
int previousValue = GetValue();
onWidgetValueChangedAnalytic?.Invoke(queryPath, previousValue, validValue);
#endif
setter(validValue);
onValueChanged?.Invoke(this, validValue);
if (newCurrentIndex > -1)
currentIndex = newCurrentIndex;
}
}
}
/// <summary>
/// A dropdown that contains a list of Unity objects.
/// </summary>
public class ObjectPopupField : Field<Object>
{
#if ENABLE_RENDERING_DEBUGGER_UI
/// <inheritdoc/>
protected override VisualElement Create()
{
var choices = new List<UnityEngine.Object>() { null };
choices.AddRange(getObjects());
var field = new UIElements.PopupField<UnityEngine.Object>()
{
label = displayName,
choices = choices,
formatListItemCallback = o => o != null ? o.name : "None",
formatSelectedValueCallback = o => o != null ? o.name : "None"
};