/
MaterialEditor.cs
3177 lines (2640 loc) · 130 KB
/
MaterialEditor.cs
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
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor.IMGUI.Controls;
using UnityEngine;
using UnityEditorInternal;
using UnityEngine.UIElements;
using UnityEngine.Rendering;
using Object = UnityEngine.Object;
using UnityEngine.Scripting;
using VirtualTexturing = UnityEngine.Rendering.VirtualTexturing;
using StackValidationResult = UnityEngine.Rendering.VirtualTexturing.EditorHelpers.StackValidationResult;
using System.IO;
namespace UnityEditor
{
[CustomEditor(typeof(Material))]
[CanEditMultipleObjects]
public partial class MaterialEditor : Editor
{
private static class Styles
{
public static readonly GUIStyle inspectorBigInner = "IN BigTitle inner";
public static readonly GUIContent reflectionProbePickerIcon = EditorGUIUtility.TrIconContent("ReflectionProbeSelector");
public static readonly GUIContent lightmapEmissiveLabelRealtimeGISupport = EditorGUIUtility.TrTextContent("Global Illumination", "Controls if the emission is Baked or Realtime.\n\nBaked only has effect in scenes where Baked Global Illumination is enabled.\n\nRealtime uses Realtime Global Illumination if enabled in the scene. Otherwise the emission won't light up other objects.");
public static readonly GUIContent lightmapEmissiveLabel = EditorGUIUtility.TrTextContent("Global Illumination", "Controls if the emission is Baked or Realtime.\n\nBaked only has effect in scenes where Baked Global Illumination is enabled.\n\nRealtime won't light up other objects since Realtime Global Illumination is not supported.");
public static GUIContent[] lightmapEmissiveStrings = { EditorGUIUtility.TextContent("Realtime"), EditorGUIUtility.TrTextContent("Baked"), EditorGUIUtility.TrTextContent("None") };
public static int[] lightmapEmissiveValues = { (int)MaterialGlobalIlluminationFlags.RealtimeEmissive, (int)MaterialGlobalIlluminationFlags.BakedEmissive, (int)MaterialGlobalIlluminationFlags.None };
public static string propBlockInfo = EditorGUIUtility.TrTextContent("MaterialPropertyBlock is used to modify these values").text;
public const int kNewShaderQueueValue = -1;
public const int kCustomQueueIndex = 4;
public static readonly GUIContent queueLabel = EditorGUIUtility.TrTextContent("Render Queue");
public static readonly GUIContent[] queueNames =
{
EditorGUIUtility.TrTextContent("From Shader"),
EditorGUIUtility.TrTextContent("Geometry", "Queue 2000"),
EditorGUIUtility.TrTextContent("AlphaTest", "Queue 2450"),
EditorGUIUtility.TrTextContent("Transparent", "Queue 3000"),
};
public static readonly int[] queueValues =
{
kNewShaderQueueValue,
(int)UnityEngine.Rendering.RenderQueue.Geometry,
(int)UnityEngine.Rendering.RenderQueue.AlphaTest,
(int)UnityEngine.Rendering.RenderQueue.Transparent,
};
public static GUIContent[] customQueueNames =
{
queueNames[0],
queueNames[1],
queueNames[2],
queueNames[3],
EditorGUIUtility.TextContent(""), // This name will be overriden during runtime
};
public static int[] customQueueValues =
{
queueValues[0],
queueValues[1],
queueValues[2],
queueValues[3],
0, // This value will be overriden during runtime
};
public static readonly GUIContent enableInstancingLabel = EditorGUIUtility.TrTextContent("Enable GPU Instancing");
public static readonly GUIContent doubleSidedGILabel = EditorGUIUtility.TrTextContent("Double Sided Global Illumination", "When enabled, the lightmapper accounts for both sides of the geometry when calculating Global Illumination. Backfaces are not rendered or added to lightmaps, but get treated as valid when seen from other objects. When using the Progressive Lightmapper backfaces bounce light using the same emission and albedo as frontfaces.");
public static readonly GUIContent emissionLabel = EditorGUIUtility.TrTextContent("Emission");
public const string undoAssignMaterial = "Assign Material";
public const string undoAssignSkyboxMaterial = "Assign Skybox Material";
public static readonly GUIContent parentContent = EditorGUIUtility.TrTextContent("Parent", "Specify the parent of this material.");
public static readonly GUIContent hierarchyIcon = EditorGUIUtility.IconContent("UnityEditor.SceneHierarchyWindow", "|Open Material Hierarchy Popup."); // right of | means tooltip
public static readonly GUIContent convertIcon = EditorGUIUtility.IconContent("d_RotateTool", "|This material is in a conversion process."); // right of | means tooltip
public const string timeUpdateButtonName = "TimeUpdateButton";
public const string selectedMeshButtonName = "SelectedMeshButton";
public const string lightModeButtonName = "LightModeButton";
public const string reflectionProbeDropdownName = "ReflectionProbeDropdown";
public const int kPadding = 3;
public const int kHierarchyIconWidth = 44;
public const float kSpaceForFoldoutArrow = 10f;
}
private static readonly List<MaterialEditor> s_MaterialEditors = new List<MaterialEditor>(4);
private int m_VariantCountCache = -1, m_HasMixedParentCache = -1;
private bool m_CheckSetup;
private static int s_ControlHash = "EditorTextField".GetHashCode();
const float kSpacingUnderTexture = 6f;
const float kMiniWarningMessageHeight = 27f;
private MaterialPropertyBlock m_PropertyBlock;
internal override string targetTitle
{
get
{
var typeName = AllTargetsAreVariants() ? "Material Variant" : "Material";
return (!m_AllowMultiObjectAccess || targets.Length == 1) ? target.name + " (" + typeName + ")" : targets.Length + " " + typeName + "s";
}
}
private enum PreviewType
{
Mesh = 0,
Plane = 1,
Skybox = 2
}
private static PreviewType GetPreviewType(Material mat)
{
if (mat == null)
return PreviewType.Mesh;
var tag = mat.GetTag("PreviewType", false, string.Empty).ToLower();
if (tag == "plane")
return PreviewType.Plane;
if (tag == "skybox")
return PreviewType.Skybox;
if (mat.shader != null && mat.shader.name.Contains("Skybox"))
return PreviewType.Skybox;
return PreviewType.Mesh;
}
private static bool DoesPreviewAllowRotation(PreviewType type)
{
return type != PreviewType.Plane;
}
public bool isVisible { get { return firstInspectedEditor || InternalEditorUtility.GetIsInspectorExpanded(target); } }
private Shader m_Shader;
private string m_InfoMessage;
private Vector2 m_PreviewDir = new Vector2(0, -20);
private int m_SelectedMesh;
private int m_TimeUpdate;
private int m_LightMode = 1;
private static readonly GUIContent s_TilingText = EditorGUIUtility.TrTextContent("Tiling");
private static readonly GUIContent s_OffsetText = EditorGUIUtility.TrTextContent("Offset");
const string kDefaultMaterialPreviewMesh = "DefaultMaterialPreviewMesh";
private ShaderGUI m_CustomShaderGUI;
string m_CustomEditorClassName;
public ShaderGUI customShaderGUI { get { return m_CustomShaderGUI; } }
bool m_InsidePropertiesGUI;
Renderer[] m_RenderersForAnimationMode;
Component m_MeshRendererComp;
internal enum ConvertAction { None, Flatten, Convert }
internal ConvertAction convertState;
private bool ShouldEditorBeHidden()
{
//When a MeshRenderer is hidden in the inspector, the MaterialEditor should also be hidden
//as showing a Material in the inspector without its supporting component feels wrong.
//This is more of a hack than a fix as we shouldnt be creating this editor in the first place when
//the supporting component is hidden, as the editor creation is a part of serialization and
//making changes at that level causes more issues this seems to be the best way to handle this case.
//This fix is for case 1289980
if (m_MeshRendererComp)
{
if (m_MeshRendererComp.hideFlags == HideFlags.HideInInspector)
return true;
return false;
}
PropertyEditor property = propertyViewer as PropertyEditor;
if (!property)
return false;
GameObject gameObject = property.tracker.activeEditors[0].target as GameObject;
if (!gameObject)
return false;
foreach (Component comp in gameObject.GetComponents<MeshRenderer>())
{
m_MeshRendererComp = comp;
if (comp.hideFlags == HideFlags.HideInInspector)
return true;
}
return false;
}
private Renderer rendererForAnimationMode
{
get
{
if (m_RenderersForAnimationMode == null)
return null;
if (m_RenderersForAnimationMode.Length == 0)
return null;
return m_RenderersForAnimationMode[0];
}
}
private struct AnimatedCheckData
{
public MaterialProperty property;
public Rect totalPosition;
public Color color;
public AnimatedCheckData(MaterialProperty property, Rect totalPosition, Color color)
{
this.property = property;
this.totalPosition = totalPosition;
this.color = color;
}
}
private static Stack<AnimatedCheckData> s_AnimatedCheckStack = new Stack<AnimatedCheckData>();
internal delegate void MaterialPropertyCallbackFunction(GenericMenu menu, MaterialProperty property, Renderer[] renderers);
internal static MaterialPropertyCallbackFunction contextualPropertyMenu;
internal class ReflectionProbePicker : PopupWindowContent
{
ReflectionProbe m_SelectedReflectionProbe;
public Transform Target
{
get { return m_SelectedReflectionProbe != null ? m_SelectedReflectionProbe.transform : null; }
}
public override Vector2 GetWindowSize()
{
return new Vector2(170, EditorGUI.kSingleLineHeight * 3f + 2f);
}
public void OnEnable()
{
m_SelectedReflectionProbe = EditorUtility.InstanceIDToObject(SessionState.GetInt("PreviewReflectionProbe", 0)) as ReflectionProbe;
}
public void OnDisable()
{
SessionState.SetInt("PreviewReflectionProbe", m_SelectedReflectionProbe ? m_SelectedReflectionProbe.GetInstanceID() : 0);
}
public override void OnGUI(Rect rc)
{
EditorGUILayout.LabelField("Select Reflection Probe", EditorStyles.boldLabel);
EditorGUILayout.Space();
m_SelectedReflectionProbe = EditorGUILayout.ObjectField("", m_SelectedReflectionProbe, typeof(ReflectionProbe), true) as ReflectionProbe;
}
}
ReflectionProbePicker m_ReflectionProbePicker = new ReflectionProbePicker();
public void SetShader(Shader shader)
{
SetShader(shader, true);
}
public void SetShader(Shader newShader, bool registerUndo)
{
bool updateMaterialEditors = false;
ShaderGUI customEditor = m_CustomShaderGUI;
CreateCustomShaderEditorIfNeeded(newShader);
m_Shader = newShader;
if (customEditor != m_CustomShaderGUI)
{
if (customEditor != null)
{
foreach (Material material in targets)
customEditor.OnClosed(material);
}
updateMaterialEditors = true;
}
foreach (Material material in targets)
{
Shader oldShader = material.shader;
Undo.RecordObject(material, "Assign shader");
BeginNoApplyMaterialPropertyDrawers();
{
if (m_CustomShaderGUI != null)
m_CustomShaderGUI.AssignNewShaderToMaterial(material, oldShader, newShader);
else
material.shader = newShader;
}
EndNoApplyMaterialPropertyDrawers();
EditorMaterialUtility.ResetDefaultTextures(material, false);
ApplyMaterialPropertyDrawers(material);
if (m_CustomShaderGUI != null)
m_CustomShaderGUI.ValidateMaterial(material);
}
if (updateMaterialEditors)
{
UpdateAllOpenMaterialEditors();
}
else
{
// ensure e.g., correctly rebuilt textures (case 879446)
OnShaderChanged();
}
}
private void UpdateAllOpenMaterialEditors()
{
// copy current list contents to array in case it changes during iteration
foreach (var materialEditor in s_MaterialEditors.ToArray())
materialEditor.DetectShaderEditorNeedsUpdate();
}
// Note: this is called from native code.
internal void OnSelectedShaderPopup(object shaderNameObj)
{
serializedObject.Update();
var shaderName = (string)shaderNameObj;
if (!string.IsNullOrEmpty(shaderName))
{
var shader = Shader.Find(shaderName);
if (shader != null)
SetShader(shader);
}
PropertiesChanged();
}
private bool HasMultipleMixedShaderValues()
{
bool mixed = false;
Shader sh = (targets[0] as Material).shader;
for (int i = 1; i < targets.Length; ++i)
{
if (sh != (targets[i] as Material).shader)
{
mixed = true;
break;
}
}
return mixed;
}
private void ShaderPopup(GUIStyle style)
{
bool wasEnabled = GUI.enabled;
Rect position = EditorGUILayout.GetControlRect();
position = EditorGUI.PrefixLabel(position, 47385, EditorGUIUtility.TempContent("Shader"));
EditorGUI.showMixedValue = HasMultipleMixedShaderValues();
var buttonContent = EditorGUIUtility.TempContent(m_Shader != null ? m_Shader.name : "No Shader Selected");
if (EditorGUI.DropdownButton(position, buttonContent, FocusType.Keyboard, style))
{
var dropdown = new ShaderSelectionDropdown(m_Shader, OnSelectedShaderPopup);
dropdown.Show(position);
GUIUtility.ExitGUI();
}
EditorGUI.showMixedValue = false;
GUI.enabled = wasEnabled;
}
bool HasMixedParent()
{
if (m_HasMixedParentCache != -1)
return m_HasMixedParentCache == 1;
m_HasMixedParentCache = 0;
if (targets.Length != 0)
{
var parent = ((Material)targets[0]).parent;
bool isVariant = ((Material)targets[0]).isVariant;
for (int i = 1; i < targets.Length; i++)
{
if (((Material)targets[i]).parent != parent || ((Material)targets[i]).isVariant != isVariant)
{
m_HasMixedParentCache = 1;
break;
}
}
}
return m_HasMixedParentCache == 1;
}
int GetVariantCount()
{
if (m_VariantCountCache == -1)
m_VariantCountCache = GetVariantCount(targets);
return m_VariantCountCache;
}
bool AllTargetsAreVariants()
{
return GetVariantCount() == targets.Length;
}
// returns true if mat is a child of any element of the targets array
private static bool IsChildOfAnyTarget(Material mat, Object[] targets)
{
foreach (var target in targets)
{
if (mat == target || mat.IsChildOf(target as Material))
return true;
}
return false;
}
private static Material HandleParentDragAndDrop(Rect rect, int controlID, EventType eventType, Object[] targets)
{
Material parent = (targets[0] as Material).parent;
// We handle drag and drop ourselves because we accept assets containing a material artifact
if (eventType == EventType.DragUpdated || eventType == EventType.DragPerform)
{
if (rect.Contains(Event.current.mousePosition) && GUI.enabled)
{
Object[] references = DragAndDrop.objectReferences;
Material validatedObject = EditorGUI.ValidateObjectFieldAssignment(references, typeof(Material), null, EditorGUI.ObjectFieldValidatorOptions.None) as Material;
if (validatedObject == null)
{
foreach (var asset in AssetDatabase.LoadAllAssetsAtPath(AssetDatabase.GetAssetPath(validatedObject)))
{
validatedObject = asset as Material;
if (validatedObject)
break;
}
}
if (validatedObject != null && !IsChildOfAnyTarget(validatedObject, targets))
{
DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
if (eventType == EventType.DragPerform)
{
GUI.changed = true;
DragAndDrop.AcceptDrag();
DragAndDrop.activeControlID = 0;
parent = validatedObject;
}
else
DragAndDrop.activeControlID = controlID;
}
Event.current.Use();
}
}
return parent;
}
private static bool HasMissingParent(Material material)
{
return material.isVariant && material.parent == null;
}
private static Material DoParentObjectField(Rect rect, Object[] targets)
{
// This is an augmented object field, preventing cyclic dependencies in the material hierarchy, handling missing parent, and with custom drap and drop rejection
int controlID = GUIUtility.GetControlID(FocusType.Keyboard, rect);
var eventType = Event.current.type;
Material parent = HandleParentDragAndDrop(rect, controlID, eventType, targets);
if (eventType == EventType.Repaint && HasMissingParent(targets[0] as Material))
{
GUIContent content = EditorGUIUtility.TempContent("Missing (Material)");
var mousePos = Event.current.mousePosition;
Rect buttonRect = EditorStyles.objectFieldButton.margin.Remove(new Rect(rect.xMax - 19, rect.y, 19, rect.height));
EditorGUI.BeginHandleMixedValueContentColor();
EditorStyles.objectField.Draw(rect, content, controlID, DragAndDrop.activeControlID == controlID, rect.Contains(mousePos));
EditorStyles.objectFieldButton.Draw(buttonRect, GUIContent.none, controlID, DragAndDrop.activeControlID == controlID, buttonRect.Contains(mousePos));
EditorGUI.EndHandleMixedValueContentColor();
return parent;
}
return EditorGUI.DoObjectField(rect, rect, controlID, parent, null, typeof(Material), null, true) as Material;
}
internal void ParentField(Rect rect, bool showMixedValue = false)
{
rect = EditorGUI.PrefixLabel(rect, Styles.parentContent);
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = showMixedValue;
var parent = DoParentObjectField(rect, targets);
EditorGUI.showMixedValue = false;
if (EditorGUI.EndChangeCheck())
{
convertState = ConvertAction.None;
Undo.RecordObjects(targets, "Assign parent");
foreach (Material target in targets)
target.parent = parent;
}
}
private bool DoHierarchyButton()
{
bool clicked = EditorGUILayout.DropdownButton(GUIContent.none, FocusType.Passive, GUILayout.MaxWidth(Styles.kHierarchyIconWidth));
Rect rect = GUILayoutUtility.topLevel.GetLast();
rect.x += 6;
if (convertState == ConvertAction.Convert)
{
float height = rect.height;
rect.height *= 0.8f;
rect.y += (height - rect.height) * 0.5f;
EditorGUI.LabelField(rect, Styles.convertIcon);
}
else
EditorGUI.LabelField(rect, Styles.hierarchyIcon);
return clicked;
}
private class ShaderSelectionDropdown : AdvancedDropdown
{
Action<object> m_OnSelectedShaderPopup;
Shader m_CurrentShader;
public ShaderSelectionDropdown(Shader shader, Action<object> onSelectedShaderPopup)
: base(new AdvancedDropdownState())
{
minimumSize = new Vector2(270, 308);
m_CurrentShader = shader;
m_OnSelectedShaderPopup = onSelectedShaderPopup;
m_DataSource = new ShaderDropdownDataSource(m_CurrentShader);
m_Gui = new MaterialDropdownGUI(m_DataSource);
}
protected override AdvancedDropdownItem BuildRoot()
{
return m_DataSource.mainTree;
}
protected override void ItemSelected(AdvancedDropdownItem item)
{
m_OnSelectedShaderPopup(((ShaderDropdownItem)item).fullName);
}
internal class ShaderDropdownDataSource : AdvancedDropdownDataSource
{
Shader m_CurrentShader;
internal ShaderDropdownDataSource(Shader currentShader) { m_CurrentShader = currentShader; }
protected override AdvancedDropdownItem FetchData()
{
m_SearchableElements = new List<AdvancedDropdownItem>();
var root = new AdvancedDropdownItem("Shaders");
var shaders = ShaderUtil.GetAllShaderInfo();
var shaderList = new List<string>();
var legacyList = new List<string>();
var notSupportedList = new List<string>();
var failedCompilationList = new List<string>();
foreach (var shader in shaders)
{
if (shader.name.StartsWith("Deprecated") || shader.name.StartsWith("Hidden"))
{
continue;
}
if (shader.hasErrors)
{
failedCompilationList.Add(shader.name);
continue;
}
if (!shader.supported)
{
notSupportedList.Add(shader.name);
continue;
}
if (shader.name.StartsWith("Legacy Shaders/"))
{
legacyList.Add(shader.name);
continue;
}
shaderList.Add(shader.name);
}
shaderList.Sort();
var unnestedList = shaderList.Where(s => s.Count(c => c == '/') == 0).ToList();
shaderList = shaderList.Where(s => s.Count(c => c == '/') > 0).ToList();
shaderList.AddRange(unnestedList);
legacyList.Sort();
notSupportedList.Sort();
failedCompilationList.Sort();
shaderList.ForEach(s => AddShaderToMenu("", root, s, s));
if (legacyList.Any() || notSupportedList.Any() || failedCompilationList.Any())
root.AddSeparator();
legacyList.ForEach(s => AddShaderToMenu("", root, s, s));
notSupportedList.ForEach(s => AddShaderToMenu("Not supported/", root, s, "Not supported/" + s));
failedCompilationList.ForEach(s => AddShaderToMenu("Failed to compile/", root, s, "Failed to compile/" + s));
return root;
}
private void AddShaderToMenu(string prefix, AdvancedDropdownItem parent, string fullShaderName, string shaderName)
{
var shaderNameParts = shaderName.Split('/');
if (shaderNameParts.Length > 1)
{
AddShaderToMenu(prefix, FindOrCreateChild(parent, shaderName), fullShaderName, shaderName.Substring(shaderNameParts[0].Length + 1));
}
else
{
var item = new ShaderDropdownItem(prefix, fullShaderName, shaderName);
parent.AddChild(item);
m_SearchableElements.Add(item);
if (m_CurrentShader != null && m_CurrentShader.name == fullShaderName)
{
selectedIDs.Add(item.id);
}
}
}
private AdvancedDropdownItem FindOrCreateChild(AdvancedDropdownItem parent, string path)
{
var shaderNameParts = path.Split('/');
var group = shaderNameParts[0];
foreach (var child in parent.children)
{
if (child.name == group)
return child;
}
var item = new AdvancedDropdownItem(group);
parent.AddChild(item);
return item;
}
protected override AdvancedDropdownItem Search(string searchString)
{
if (string.IsNullOrEmpty(searchString) || m_SearchableElements == null)
return null;
// Support multiple search words separated by spaces.
var searchWords = searchString.ToLower().Split(' ');
var matched = new List<List<AdvancedDropdownItem>>();
matched.Add(new List<AdvancedDropdownItem>());
bool found = false;
foreach (var e in m_SearchableElements)
{
if (e.children.Any())
continue;
var menuItem = (ShaderDropdownItem)e;
var name = menuItem.fullName.ToLower().Replace(" ", "");
if (AddMatchItem(e, name, searchWords, matched))
found = true;
}
if (!found)
{
foreach (var e in m_SearchableElements)
{
var menuItem = (ShaderDropdownItem)e;
var name = menuItem.fullName.Replace(" ", "");
AddMatchItem(e, name, searchWords, matched);
}
}
var searchTree = new AdvancedDropdownItem("Shaders");
for (int i = 0; i < matched.Count; i++)
{
matched[i].Sort((s2, s1) =>
{
var order = (int)((s2 as ShaderDropdownItem)?.fullName.Count(c => c == '/') - (s1 as ShaderDropdownItem)?.fullName.Count(c => c == '/'));
if (order == 0)
order = s2.name.CompareTo(s1.name);
return order;
});
foreach (var element in matched[i])
{
searchTree.AddChild(element);
}
}
return searchTree;
}
protected bool AddMatchItem(AdvancedDropdownItem e, string fullName, string[] searchWords, List<List<AdvancedDropdownItem>> matched)
{
int index = -1;
var splitName = searchWords[0].Contains('/') && searchWords.Length == 1 ? new string[1] { fullName } : fullName.Split('/');
// See if we match ALL the search words.
for (var w = 0; w < searchWords.Length; w++)
{
index = -1;
for (int i = 0; i < splitName.Length; i++)
{
if (splitName[i].Contains(searchWords[w]))
{
if(i >= index)
index = i;
}
else if(i == splitName.Length - 1 && index == -1)
return false;
}
}
// index 0 is reserved for Shader name matches thus the actual index is always higher by one
index++;
if (index == splitName.Length)
index = 0;
if (index >= matched.Count)
{
for (int i = matched.Count; i <= index; i++)
{
matched.Add(new List<AdvancedDropdownItem>());
}
}
matched[index].Add(e);
return true;
}
}
private class ShaderDropdownItem : AdvancedDropdownItem
{
string m_FullName;
string m_Prefix;
public string fullName => m_FullName;
public string prefix => m_Prefix;
public ShaderDropdownItem(string prefix, string fullName, string shaderName)
: base(shaderName)
{
m_FullName = fullName;
m_Prefix = prefix;
id = (prefix + fullName + shaderName).GetHashCode();
}
}
private class MaterialDropdownGUI : AdvancedDropdownGUI
{
public MaterialDropdownGUI(AdvancedDropdownDataSource dataSource)
: base(dataSource) { m_DataSource = dataSource; }
AdvancedDropdownDataSource m_DataSource;
private static class Styles
{
internal static GUIStyle lineStyleFaint = new GUIStyle("DD ItemStyle");
internal static GUIStyle checkMark = "DD ItemCheckmark";
public static GUIContent checkMarkContent = new GUIContent("✔");
static Styles()
{
float val = EditorGUIUtility.isProSkin ? 0.5f : 0.25f;
lineStyleFaint.active.textColor = new Color(val, val, val, 1f);
lineStyleFaint.focused.textColor = new Color(val, val, val, 1f);
lineStyleFaint.hover.textColor = new Color(val, val, val, 1f);
lineStyleFaint.normal.textColor = new Color(val, val, val, 1f);
}
}
internal override void DrawItem(AdvancedDropdownItem item, string name, Texture2D icon, bool enabled, bool drawArrow, bool selected, bool hasSearch)
{
var newScriptItem = item as ShaderDropdownItem;
string text;
if (hasSearch && newScriptItem != null)
{
DrawSearchItem(item, newScriptItem.name, newScriptItem.prefix + newScriptItem.fullName, selected);
text = newScriptItem.fullName.Contains('/') ? $"{name} ({newScriptItem.fullName})" : name;
}
else
{
text = name;
base.DrawItem(item, name, icon, enabled, drawArrow, selected, hasSearch);
}
if (Event.current.type == EventType.Repaint && hasSearch)
{
var tooltipRect = GUILayoutUtility.GetLastRect();
GUI.Label(tooltipRect, new GUIContent("", text));
}
}
private void DrawSearchItem(AdvancedDropdownItem item, string name, string path, bool selected)
{
path = $" ({path.Substring(0, path.Length - name.Length).Trim('/')})";
path = path.Equals(" ()") ? "" : path; // if the path we're left with is equal to " ()" - scrap it
var contentWithIcon = new GUIContent(name, path);
var rect = GUILayoutUtility.GetRect(contentWithIcon, Styles.lineStyleFaint, GUILayout.ExpandWidth(true));
var fullRect = new Rect(rect);
if (Event.current.type != EventType.Repaint)
return;
bool checkMark = false;
if (m_DataSource.selectedIDs.Any() && m_DataSource.selectedIDs.Contains(item.id))
{
checkMark = true;
var checkMarkRect = new Rect(fullRect);
checkMarkRect.width = iconSize.x + 1;
Styles.checkMark.Draw(checkMarkRect, Styles.checkMarkContent, selected, selected, selected, selected);
}
var emptySpace = Styles.lineStyleFaint.CalcSize(contentWithIcon);
rect.x += emptySpace.x + iconSize.x + 1;
if (!checkMark)
lineStyle.Draw(fullRect, new GUIContent(), selected, selected, selected, selected);
fullRect.x += iconSize.x + 1;
lineStyle.Draw(fullRect, contentWithIcon, selected & checkMark, selected & checkMark, selected & checkMark, selected & checkMark);
Styles.lineStyleFaint.Draw(rect, new GUIContent(path, path), selected, false, false, false);
}
}
}
public virtual void Awake()
{
if (GetPreviewType(target as Material) == PreviewType.Skybox)
m_PreviewDir = new Vector2(0, 50);
m_SelectedMesh = EditorPrefs.GetInt(kDefaultMaterialPreviewMesh);
}
private void DetectShaderEditorNeedsUpdate()
{
var material = target as Material;
bool shaderChanged = material && material.shader != m_Shader;
bool customEditorChanged = material && material.shader && m_CustomEditorClassName != ShaderUtil.GetCurrentCustomEditor(material.shader);
if (shaderChanged || customEditorChanged)
{
CreateCustomShaderEditorIfNeeded(material.shader);
if (shaderChanged)
{
m_Shader = material.shader;
OnShaderChanged();
}
InspectorWindow.RepaintAllInspectors();
}
}
private string ParseValidationResult(StackValidationResult validationResult)
{
string[] errorMessages = validationResult.errorMessage.Split('\n');
string result = "'" + validationResult.stackName + "' is invalid";
if (errorMessages.Length == 1)
result += " (1 issue)\n";
else
result += " (" + errorMessages.Length + " issues)\n";
for (int i = 0; i < errorMessages.Length; ++i)
{
result += " - " + errorMessages[i] + '\n';
}
return result;
}
private void DetectTextureStackValidationIssues()
{
if (PlayerSettings.GetVirtualTexturingSupportEnabled())
{
if (isVisible && m_Shader != null && !HasMultipleMixedShaderValues())
{
// We want additional spacing, but only when the material properties are visible
EditorGUILayout.Space(EditorGUIUtility.singleLineHeight / 2.0f);
}
// We don't want these message boxes to be indented
EditorGUI.indentLevel--;
var material = target as Material;
StackValidationResult[] stackValidationResults = VirtualTexturing.EditorHelpers.ValidateMaterialTextureStacks(material);
if (stackValidationResults.Length == 0)
return;
foreach (StackValidationResult validationResult in stackValidationResults)
{
string errorBoxText = ParseValidationResult(validationResult);
EditorGUILayout.HelpBox(errorBoxText, MessageType.Error);
}
// Reset the original indentation level
EditorGUI.indentLevel++;
}
}
public override void OnInspectorGUI()
{
if (ShouldEditorBeHidden())
return;
serializedObject.Update();
CheckSetup();
DetectShaderEditorNeedsUpdate();
if (isVisible && m_Shader != null && !HasMultipleMixedShaderValues())
{
// Show Material properties
if (PropertiesGUI())
{
foreach (Material material in targets)
{
if (m_CustomShaderGUI != null)
m_CustomShaderGUI.ValidateMaterial(material);
}
PropertiesChanged();
}
}
DetectTextureStackValidationIssues();
}
void CheckSetup()
{
if (!m_CheckSetup || m_Shader == null)
return;
m_CheckSetup = false;
if (m_CustomShaderGUI == null && !IsMaterialEditor(ShaderUtil.GetCurrentCustomEditor(m_Shader)))
{
Debug.LogWarningFormat("Could not create a custom UI for the shader '{0}'. The shader has the following: 'CustomEditor = {1}'. Does the custom editor specified include its namespace? And does the class either derive from ShaderGUI or MaterialEditor?", m_Shader.name, ShaderUtil.GetCurrentCustomEditor(m_Shader));
}
}
// A minimal list of settings to be shown in the Asset Store preview inspector
internal override void OnAssetStoreInspectorGUI()
{
OnInspectorGUI();
}
public void PropertiesChanged()
{
// @TODO: Show performance warnings for multi-selections too?
m_InfoMessage = null;
if (targets.Length == 1)
m_InfoMessage = Utils.PerformanceChecks.CheckMaterial(target as Material, EditorUserBuildSettings.activeBuildTarget);
}
protected virtual void OnShaderChanged()
{
}
protected override void OnHeaderGUI()
{
if (ShouldEditorBeHidden())
return;
Rect titleRect = DrawHeaderGUI(this, targetTitle, firstInspectedEditor ? 0 : Styles.kSpaceForFoldoutArrow);
int id = GUIUtility.GetControlID(45678, FocusType.Passive);
if (!firstInspectedEditor)
{
Rect renderRect = EditorGUI.GetInspectorTitleBarObjectFoldoutRenderRect(titleRect);
renderRect.y = titleRect.yMax - 17f; // align with bottom
bool oldVisible = InternalEditorUtility.GetIsInspectorExpanded(target);
bool newVisible = EditorGUI.DoObjectFoldout(oldVisible, titleRect, renderRect, targets, id);
// Toggle visibility
if (newVisible != oldVisible)
InternalEditorUtility.SetIsInspectorExpanded(target, newVisible);
}
}
internal override void OnHeaderControlsGUI()
{
// Clear cache in case material is modified externally
m_VariantCountCache = -1;
m_HasMixedParentCache = -1;
if (ShouldEditorBeHidden())
return;
serializedObject.Update();
var oldLabelWidth = EditorGUIUtility.labelWidth;
EditorGUIUtility.labelWidth = 50;
// Shader selection dropdown
using (new EditorGUI.DisabledScope(!IsEnabled() || GetVariantCount() != 0))
ShaderPopup("MiniPulldown");
// Edit button for custom shaders
if (m_Shader != null && !HasMultipleMixedShaderValues() && (m_Shader.hideFlags & HideFlags.DontSave) == 0)
{
if (GUILayout.Button("Edit...", EditorStyles.miniButton, GUILayout.ExpandWidth(false)))
AssetDatabase.OpenAsset(m_Shader);