-
Notifications
You must be signed in to change notification settings - Fork 870
Expand file tree
/
Copy pathVFXAssetEditor.cs
More file actions
1076 lines (925 loc) · 47.3 KB
/
VFXAssetEditor.cs
File metadata and controls
1076 lines (925 loc) · 47.3 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
using System;
using System.IO;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using UnityEditorInternal;
using UnityEditor;
using UnityEngine;
using UnityEngine.VFX;
using UnityEditor.Callbacks;
using UnityEditor.UIElements;
using UnityEditor.VFX;
using UnityEditor.VFX.UI;
using UnityEngine.UIElements;
using UnityObject = UnityEngine.Object;
class VFXExternalShaderProcessor : AssetPostprocessor
{
public const string k_ShaderDirectory = "Shaders";
public const string k_ShaderExt = ".vfxshader";
public static bool allowExternalization { get { return EditorPrefs.GetBool(VFXViewPreference.allowShaderExternalizationKey, false); } }
void OnPreprocessAsset()
{
if (!allowExternalization)
return;
bool isVFX = assetPath.EndsWith(VisualEffectResource.Extension, StringComparison.OrdinalIgnoreCase);
if (isVFX)
{
string vfxName = Path.GetFileNameWithoutExtension(assetPath);
string vfxDirectory = Path.GetDirectoryName(assetPath);
string shaderDirectory = vfxDirectory + "/" + k_ShaderDirectory + "/" + vfxName;
if (!Directory.Exists(shaderDirectory))
{
return;
}
VisualEffectAsset asset = AssetDatabase.LoadAssetAtPath<VisualEffectAsset>(assetPath);
if (asset == null)
return;
bool oneFound = false;
VisualEffectResource resource = asset.GetResource();
if (resource == null)
return;
VFXShaderSourceDesc[] descs = resource.shaderSources;
foreach (var shaderPath in Directory.GetFiles(shaderDirectory))
{
if (shaderPath.EndsWith(k_ShaderExt, StringComparison.OrdinalIgnoreCase))
{
System.IO.StreamReader file = new System.IO.StreamReader(shaderPath);
string shaderLine = file.ReadLine();
file.Close();
if (shaderLine == null || !shaderLine.StartsWith("//"))
continue;
string[] shaderParams = shaderLine.Split(',');
string shaderName = shaderParams[0].Substring(2);
int index;
if (!int.TryParse(shaderParams[1], out index))
continue;
if (index < 0 || index >= descs.Length)
continue;
if (descs[index].name != shaderName)
continue;
string shaderSource = File.ReadAllText(shaderPath);
//remove the first two lines that where added when externalized
shaderSource = shaderSource.Substring(shaderSource.IndexOf("\n", shaderSource.IndexOf("\n") + 1) + 1);
descs[index].source = shaderSource;
oneFound = true;
}
}
if (oneFound)
{
resource.shaderSources = descs;
}
}
}
}
[CustomEditor(typeof(VisualEffectAsset))]
[CanEditMultipleObjects]
class VisualEffectAssetEditor : UnityEditor.Editor
{
#if UNITY_2021_1_OR_NEWER
[OnOpenAsset(OnOpenAssetAttributeMode.Validate)]
public static bool WillOpenInUnity(EntityId entityId)
{
var obj = EditorUtility.EntityIdToObject(entityId);
if (obj is VFXGraph || obj is VFXModel || obj is VFXUI)
return true;
else if (obj is VisualEffectAsset)
return true;
else if (obj is VisualEffectSubgraph)
return true;
return false;
}
#endif
[OnOpenAsset(1)]
public static bool OnOpenVFX(EntityId entityId, int line)
{
var obj = EditorUtility.EntityIdToObject(entityId);
if (obj is VFXGraph || obj is VFXModel || obj is VFXUI)
{
// for visual effect graph editor ScriptableObject select them when double clicking on them.
//Since .vfx importer is a copyasset, the default is to open it with an external editor.
Selection.activeEntityId = entityId;
return true;
}
else if (obj is VisualEffectAsset vfxAsset)
{
var window = VFXViewWindow.GetWindow(vfxAsset, false);
if (window == null)
{
window = VFXViewWindow.GetWindow(vfxAsset, true);
}
window.LoadAsset(vfxAsset, null);
window.Focus();
return true;
}
else if (obj is VisualEffectSubgraph)
{
VisualEffectResource resource = VisualEffectResource.GetResourceAtPath(AssetDatabase.GetAssetPath(obj));
var window = VFXViewWindow.GetWindow(resource, false);
if (window == null)
{
window = VFXViewWindow.GetWindow(resource, true);
window.LoadResource(resource, null);
}
window.Focus();
return true;
}
else if (obj is Material || obj is Shader || obj is ComputeShader)
{
var path = AssetDatabase.GetAssetPath(entityId);
if (path.EndsWith(VisualEffectResource.Extension, StringComparison.OrdinalIgnoreCase))
{
var resource = VisualEffectResource.GetResourceAtPath(path);
if (resource != null)
{
int index = resource.GetShaderIndex(obj);
//Shader Sources aren't kept in library, index can return -1 in that case
//This behavior might be fixed after retrieving 02d730ef10eb5fc898d37682254c47588c3b8bed changes
if (index >= 0)
{
resource.ShowGeneratedShaderFile(index, line);
return true;
}
}
}
}
return false;
}
ReorderableList m_ReorderableList;
List<IVFXSubRenderer> m_OutputContexts = new List<IVFXSubRenderer>();
VFXGraph m_CurrentGraph;
bool showUpdateModeCategory = true;
bool showInitialStateCategory = true;
bool showInstancingCategory = true;
bool showShadersCategory = true;
bool showOutputOrderCategory = true;
void OnReorder(ReorderableList list)
{
for (int i = 0; i < m_OutputContexts.Count(); ++i)
{
m_OutputContexts[i].vfxSystemSortPriority = i;
}
if (VFXViewWindow.GetAllWindows().All(x => x.graphView?.controller?.graph.visualEffectResource.GetEntityId() != m_CurrentGraph.visualEffectResource.GetEntityId() || !x.hasFocus))
{
// Do we need a compileReporter here?
AssetDatabase.ImportAsset(AssetDatabase.GetAssetPath(m_CurrentGraph.visualEffectResource));
}
}
private void DrawOutputContextItem(Rect rect, int index, bool isActive, bool isFocused)
{
var context = m_OutputContexts[index] as VFXContext;
var contextData = context.GetData();
var systemName = contextData ? context.GetGraph().systemNames.GetUniqueSystemName(contextData) : string.Empty;
var contextLetter = context.letter;
var contextName = string.IsNullOrEmpty(context.label) ? context.name.Replace('\n', ' ') : context.label;
var fullName = string.Format("{0}{1}/{2}", systemName, contextLetter != '\0' ? "/" + contextLetter : string.Empty, contextName.Replace('\n', ' '));
EditorGUI.LabelField(rect, EditorGUIUtility.TempContent(fullName));
}
static Mesh s_CubeWireFrame;
void OnEnable()
{
m_OutputContexts.Clear();
VisualEffectAsset vfxTarget = target as VisualEffectAsset;
var resource = vfxTarget.GetResource();
if (resource != null) //Can be null if VisualEffectAsset is in Asset Bundle
{
m_CurrentGraph = resource.GetOrCreateGraph();
m_CurrentGraph.systemNames.Sync(m_CurrentGraph);
m_OutputContexts.AddRange(m_CurrentGraph.children.OfType<IVFXSubRenderer>().OrderBy(t => t.vfxSystemSortPriority));
}
if (s_PlayPauseIcons == null)
{
s_PlayPauseIcons = new[]
{
EditorGUIUtility.TrIconContent("PlayButton", "Animate preview"),
EditorGUIUtility.TrIconContent("PauseButton", "Pause preview animation"),
};
}
m_ReorderableList = new ReorderableList(m_OutputContexts, typeof(IVFXSubRenderer), true, false, false, false);
m_ReorderableList.showDefaultBackground = false;
m_ReorderableList.onReorderCallback = OnReorder;
m_ReorderableList.drawElementCallback = DrawOutputContextItem;
var targetResources = targets.Cast<VisualEffectAsset>().Select(t => t.GetResource()).Where(t => t != null).ToArray();
if (targetResources.Any())
{
resourceObject = new SerializedObject(targetResources);
resourceUpdateModeProperty = resourceObject.FindProperty("m_Infos.m_UpdateMode");
cullingFlagsProperty = resourceObject.FindProperty("m_Infos.m_CullingFlags");
motionVectorRenderModeProperty = resourceObject.FindProperty("m_Infos.m_RendererSettings.motionVectorGenerationMode");
prewarmDeltaTime = resourceObject.FindProperty("m_Infos.m_PreWarmDeltaTime");
prewarmStepCount = resourceObject.FindProperty("m_Infos.m_PreWarmStepCount");
initialEventName = resourceObject.FindProperty("m_Infos.m_InitialEventName");
instancingModeProperty = resourceObject.FindProperty("m_Infos.m_InstancingMode");
instancingCapacityProperty = resourceObject.FindProperty("m_Infos.m_InstancingCapacity");
}
if (targets?.Length > 0)
{
targetObject = new SerializedObject(targets);
instancingDisabledReasonProperty = targetObject.FindProperty("m_Infos.m_InstancingDisabledReason");
}
}
private void CreateVisualEffect()
{
Debug.Assert(m_VisualEffectGO == null);
m_PreviewUtility?.Cleanup();
m_PreviewUtility = new PreviewRenderUtility();
m_PreviewUtility.camera.fieldOfView = 60.0f;
m_PreviewUtility.camera.allowHDR = true;
m_PreviewUtility.camera.allowMSAA = false;
m_PreviewUtility.camera.farClipPlane = 10000.0f;
m_PreviewUtility.camera.clearFlags = CameraClearFlags.SolidColor;
m_PreviewUtility.ambientColor = new Color(.1f, .1f, .1f, 1.0f);
m_PreviewUtility.lights[0].transform.rotation = Quaternion.Euler(40f, 40f, 0);
m_VisualEffectGO = new GameObject("VisualEffect (Preview)");
m_VisualEffectGO.hideFlags = HideFlags.DontSave;
m_VisualEffect = m_VisualEffectGO.AddComponent<VisualEffect>();
m_VisualEffect.pause = true;
m_RemainingFramesToRender = 1;
m_PreviewUtility.AddManagedGO(m_VisualEffectGO);
m_VisualEffectGO.transform.localPosition = Vector3.zero;
m_VisualEffectGO.transform.localRotation = Quaternion.identity;
m_VisualEffectGO.transform.localScale = Vector3.one;
VisualEffectAsset vfxTarget = target as VisualEffectAsset;
m_VisualEffect.visualEffectAsset = vfxTarget;
m_CurrentBounds = new Bounds(Vector3.zero, Vector3.one);
m_Distance = null;
m_Angles = Vector2.zero;
if (s_CubeWireFrame == null)
{
s_CubeWireFrame = new Mesh();
var vertices = new Vector3[]
{
new Vector3(-0.5f, -0.5f, -0.5f),
new Vector3(-0.5f, -0.5f, 0.5f),
new Vector3(-0.5f, 0.5f, 0.5f),
new Vector3(-0.5f, 0.5f, -0.5f),
new Vector3(0.5f, -0.5f, -0.5f),
new Vector3(0.5f, -0.5f, 0.5f),
new Vector3(0.5f, 0.5f, 0.5f),
new Vector3(0.5f, 0.5f, -0.5f)
};
var indices = new int[]
{
0, 1,
0, 3,
0, 4,
6, 2,
6, 5,
6, 7,
1, 2,
1, 5,
3, 7,
3, 2,
4, 5,
4, 7
};
s_CubeWireFrame.vertices = vertices;
s_CubeWireFrame.SetIndices(indices, MeshTopology.Lines, 0);
}
}
PreviewRenderUtility m_PreviewUtility;
GameObject m_VisualEffectGO;
VisualEffect m_VisualEffect;
Vector2 m_Angles;
float? m_Distance;
int m_RemainingFramesToRender;
Bounds m_CurrentBounds;
const int kSafeFrame = 2;
public override bool HasPreviewGUI()
{
return !serializedObject.isEditingMultipleObjects;
}
void ComputeFarNear(float distance)
{
if (m_CurrentBounds.size != Vector3.zero)
{
float maxBounds = Mathf.Sqrt(m_CurrentBounds.size.x * m_CurrentBounds.size.x + m_CurrentBounds.size.y * m_CurrentBounds.size.y + m_CurrentBounds.size.z * m_CurrentBounds.size.z);
m_PreviewUtility.camera.farClipPlane = distance + maxBounds * 1.1f;
m_PreviewUtility.camera.nearClipPlane = Mathf.Max(0.0001f, (distance - maxBounds));
m_PreviewUtility.camera.nearClipPlane = Mathf.Max(0.0001f, (distance - maxBounds));
}
}
public override void OnPreviewSettings()
{
EditorGUI.BeginChangeCheck();
int isAnimatedState = m_IsAnimated ? 1 : 0;
m_IsAnimated = PreviewGUI.CycleButton(isAnimatedState, s_PlayPauseIcons) == 1;
if (EditorGUI.EndChangeCheck())
{
m_VisualEffect.pause = !m_IsAnimated;
if (!m_IsAnimated)
{
StopRendering();
}
}
GUI.enabled = m_IsAnimated;
// Random id=10012 because when set to 0 the button get highlighted by default !?
if (EditorGUILayout.IconButton(10012, EditorGUIUtility.TrIconContent("Refresh", "Restart VFX"), EditorStyles.toolbarButton, null))
{
m_VisualEffect.Reinit();
}
GUI.enabled = true;
}
private static GUIContent[] s_PlayPauseIcons;
private bool m_IsAnimated;
private Rect m_LastArea;
public override void OnInteractivePreviewGUI(Rect r, GUIStyle background)
{
if (m_VisualEffectGO == null)
CreateVisualEffect();
bool isRepaint = Event.current.type == EventType.Repaint;
Renderer renderer = m_VisualEffectGO.GetComponent<Renderer>();
if (renderer == null)
return;
if (isRepaint && r != m_LastArea)
RequestSingleFrame();
if (VFXPreviewGUI.TryDrag2D(ref m_Angles, m_LastArea))
RequestSingleFrame();
if (renderer.bounds.size != Vector3.zero)
{
m_CurrentBounds = renderer.bounds;
//make sure that none of the bounds values are 0
if (m_CurrentBounds.size.x == 0)
{
Vector3 size = m_CurrentBounds.size;
size.x = (m_CurrentBounds.size.y + m_CurrentBounds.size.z) * 0.1f;
m_CurrentBounds.size = size;
}
if (m_CurrentBounds.size.y == 0)
{
Vector3 size = m_CurrentBounds.size;
size.y = (m_CurrentBounds.size.x + m_CurrentBounds.size.z) * 0.1f;
m_CurrentBounds.size = size;
}
if (m_CurrentBounds.size.z == 0)
{
Vector3 size = m_CurrentBounds.size;
size.z = (m_CurrentBounds.size.x + m_CurrentBounds.size.y) * 0.1f;
m_CurrentBounds.size = size;
}
}
if (!m_Distance.HasValue && m_RemainingFramesToRender == 1)
{
float maxBounds = Mathf.Sqrt(m_CurrentBounds.size.x * m_CurrentBounds.size.x +
m_CurrentBounds.size.y * m_CurrentBounds.size.y +
m_CurrentBounds.size.z * m_CurrentBounds.size.z);
m_Distance = Mathf.Max(0.01f, maxBounds * 1.25f);
ComputeFarNear(0f);
}
else
{
ComputeFarNear(m_Distance.GetValueOrDefault(0f));
}
if (Event.current.isScrollWheel)
{
m_Distance *= 1 + Event.current.delta.y * .015f;
RequestSingleFrame();
}
if (m_Mat == null)
m_Mat = (Material)EditorGUIUtility.LoadRequired("SceneView/HandleLines.mat");
if (!isRepaint)
{
if (m_RemainingFramesToRender > 0)
Repaint();
return;
}
if (r.width > 50 && r.height > 50)
m_LastArea = r;
bool needsRender = m_IsAnimated || m_RemainingFramesToRender > 0;
if (needsRender)
{
//Forcing fixed intensity in case of lazily addition of HDAdditionalLightData
m_PreviewUtility.lights[0].intensity = 1.4f;
m_PreviewUtility.lights[1].intensity = 1.4f;
m_RemainingFramesToRender--;
m_PreviewUtility.BeginPreview(m_LastArea, background);
Quaternion rot = Quaternion.Euler(0, m_Angles.x, 0) * Quaternion.Euler(m_Angles.y, 0, 0);
m_PreviewUtility.camera.transform.position = m_CurrentBounds.center + rot * new Vector3(0, 0, -m_Distance.GetValueOrDefault(0));
m_PreviewUtility.camera.transform.localRotation = rot;
if (m_Distance.HasValue)
m_PreviewUtility.DrawMesh(s_CubeWireFrame, Matrix4x4.TRS(m_CurrentBounds.center, Quaternion.identity, m_CurrentBounds.size), m_Mat, 0);
m_PreviewUtility.Render(true);
m_PreviewUtility.EndAndDrawPreview(m_LastArea);
}
if (!m_IsAnimated && m_RemainingFramesToRender == 0)
StopRendering();
if (m_IsAnimated)
Repaint();
else
EditorGUI.DrawPreviewTexture(m_LastArea, m_PreviewUtility.renderTexture);
}
void RequestSingleFrame()
{
if (m_RemainingFramesToRender < 0)
m_RemainingFramesToRender = 1;
}
void StopRendering()
{
m_RemainingFramesToRender = -1;
}
Material m_Mat;
void OnDisable()
{
if (!UnityObject.ReferenceEquals(m_VisualEffectGO, null))
{
UnityObject.DestroyImmediate(m_VisualEffectGO);
}
if (m_PreviewUtility != null)
{
m_PreviewUtility.Cleanup();
}
}
private static readonly GUIContent[] k_CullingOptionsContents = new GUIContent[]
{
EditorGUIUtility.TrTextContent("Recompute bounds and simulate when visible"),
EditorGUIUtility.TrTextContent("Always recompute bounds, simulate only when visible"),
EditorGUIUtility.TrTextContent("Always recompute bounds and simulate")
};
static readonly VFXCullingFlags[] k_CullingOptionsValue = new VFXCullingFlags[]
{
VFXCullingFlags.CullSimulation | VFXCullingFlags.CullBoundsUpdate,
VFXCullingFlags.CullSimulation,
VFXCullingFlags.CullNone,
};
private static readonly GUIContent k_InstancingContent = EditorGUIUtility.TrTextContent("Instancing");
private static readonly GUIContent k_InstancingModeContent = EditorGUIUtility.TrTextContent("Instancing Mode", "Selects how the visual effect will be handled regarding instancing.");
private static readonly GUIContent k_InstancingCapacityContent = EditorGUIUtility.TrTextContent("Max Batch Capacity", "Max number of instances that can be grouped together in a single batch.");
SerializedObject resourceObject;
SerializedProperty resourceUpdateModeProperty;
SerializedProperty cullingFlagsProperty;
SerializedProperty motionVectorRenderModeProperty;
SerializedProperty prewarmDeltaTime;
SerializedProperty prewarmStepCount;
SerializedProperty initialEventName;
SerializedProperty instancingModeProperty;
SerializedProperty instancingCapacityProperty;
SerializedObject targetObject;
SerializedProperty instancingDisabledReasonProperty;
private static readonly float k_MinimalCommonDeltaTime = 1.0f / 800.0f;
private static readonly uint k_MaximumStepCount = 2400u; // 3 seconds at minimal delta time
public static void DisplayPrewarmInspectorGUI(SerializedObject resourceObject, SerializedProperty prewarmDeltaTime, SerializedProperty prewarmStepCount)
{
if (!prewarmDeltaTime.hasMultipleDifferentValues && !prewarmStepCount.hasMultipleDifferentValues)
{
var currentDeltaTime = prewarmDeltaTime.floatValue;
int currentStepCount = (int)prewarmStepCount.uintValue;
var currentTotalTime = currentDeltaTime * currentStepCount;
EditorGUI.BeginChangeCheck();
currentTotalTime = EditorGUILayout.FloatField(EditorGUIUtility.TrTextContent("PreWarm Total Time", "Sets the time in seconds to advance the current effect to when it is initially played. "), currentTotalTime);
if (EditorGUI.EndChangeCheck())
{
if (currentStepCount <= 0 && currentTotalTime != 0.0f)
{
currentStepCount = 1;
prewarmStepCount.uintValue = (uint)currentStepCount;
}
currentDeltaTime = currentTotalTime / currentStepCount;
prewarmDeltaTime.floatValue = currentDeltaTime;
resourceObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
currentStepCount = EditorGUILayout.IntField(EditorGUIUtility.TrTextContent("PreWarm Step Count", "Sets the number of simulation steps the prewarm should be broken down to. "), (int)currentStepCount);
if (EditorGUI.EndChangeCheck())
{
bool hasPrewarm = currentTotalTime != 0.0f;
currentStepCount = Math.Clamp(currentStepCount, hasPrewarm ? 1 : 0, (int)k_MaximumStepCount);
currentDeltaTime = hasPrewarm ? currentTotalTime / currentStepCount : 0.0f;
prewarmDeltaTime.floatValue = Math.Max(k_MinimalCommonDeltaTime, currentDeltaTime);
prewarmStepCount.uintValue = (uint)currentStepCount;
resourceObject.ApplyModifiedProperties();
}
EditorGUI.BeginChangeCheck();
currentDeltaTime = EditorGUILayout.FloatField(EditorGUIUtility.TrTextContent("PreWarm Delta Time", "Sets the time in seconds for each step to achieve the desired total prewarm time."), currentDeltaTime);
if (EditorGUI.EndChangeCheck())
{
currentDeltaTime = Math.Max(k_MinimalCommonDeltaTime, currentDeltaTime);
float totalTime = currentDeltaTime * currentStepCount;
if (totalTime > currentTotalTime || currentStepCount == k_MaximumStepCount)
{
currentTotalTime = totalTime;
}
else
{
var candidateStepCount_A = Mathf.FloorToInt(currentTotalTime / currentDeltaTime);
var candidateStepCount_B = Mathf.RoundToInt(currentTotalTime / currentDeltaTime);
var totalTime_A = currentDeltaTime * candidateStepCount_A;
var totalTime_B = currentDeltaTime * candidateStepCount_B;
if (Mathf.Abs(totalTime_A - currentTotalTime) < Mathf.Abs(totalTime_B - currentTotalTime))
{
currentStepCount = candidateStepCount_A;
}
else
{
currentStepCount = candidateStepCount_B;
}
currentStepCount = Math.Clamp(currentStepCount, 1, (int)k_MaximumStepCount);
prewarmStepCount.uintValue = (uint)currentStepCount;
}
prewarmDeltaTime.floatValue = currentDeltaTime;
resourceObject.ApplyModifiedProperties();
}
}
else
{
//Multi selection case, can't resolve total time easily
EditorGUI.BeginChangeCheck();
// Total time disabled in this case
EditorGUI.BeginDisabled(true);
EditorGUI.showMixedValue = true;
EditorGUILayout.FloatField(EditorGUIUtility.TrTextContent("PreWarm Total Time", "Sets the time in seconds to advance the current effect to when it is initially played. "), 0);
EditorGUI.EndDisabled();
EditorGUI.showMixedValue = prewarmStepCount.hasMultipleDifferentValues;
EditorGUILayout.PropertyField(prewarmStepCount, EditorGUIUtility.TrTextContent("PreWarm Step Count", "Sets the number of simulation steps the prewarm should be broken down to."));
EditorGUI.showMixedValue = prewarmDeltaTime.hasMultipleDifferentValues;
EditorGUILayout.PropertyField(prewarmDeltaTime, EditorGUIUtility.TrTextContent("PreWarm Delta Time", "Sets the time in seconds for each step to achieve the desired total prewarm time."));
if (EditorGUI.EndChangeCheck())
{
prewarmStepCount.uintValue = Math.Clamp(prewarmStepCount.uintValue, 1u, k_MaximumStepCount);
prewarmDeltaTime.floatValue = Math.Max(prewarmDeltaTime.floatValue, k_MinimalCommonDeltaTime);
resourceObject.ApplyModifiedProperties();
}
}
}
public override VisualElement CreateInspectorGUI()
{
// Create a new root VisualElement
var root = new VisualElement { style = { marginLeft = -15f } };
var imguiContainer = new IMGUIContainer(OnInspectorGUIEmbedded);
root.Add(imguiContainer);
// Template section uses UIToolkit
var importers = new List<VisualEffectImporter>();
var paths = targets.Select(AssetDatabase.GetAssetPath).ToArray();
foreach (var path in paths)
{
var importer = AssetImporter.GetAtPath(path) as VisualEffectImporter;
if (importer != null)
{
importers.Add(importer);
}
}
if (importers.Count > 0)
{
root.styleSheets.Add(VFXView.LoadStyleSheet("VisualEffectAssetEditor"));
var header = new Foldout { text = "Template Info" };
header.AddToClassList("inspector-header");
header.focusable = false;
root.Add(header);
var allImportersSerializedObject = new SerializedObject(importers.ToArray());
var useAsTemplateProperty = allImportersSerializedObject.FindProperty("m_UseAsTemplate");
var useAsTemplateCheckbox = new Toggle("Use as Template") { tooltip = "When enabled, this asset will be used as a template for new Visual Effect Assets" };
useAsTemplateCheckbox.BindProperty(useAsTemplateProperty);
header.Add(useAsTemplateCheckbox);
var expander = new Foldout { text = "Template", style = { marginLeft = 15f } };
header.Add(expander);
// Name field
var nameTooltip = targets.Length == 1
? "Name of the template displayed in the template window"
: "When multiple Visual Effect Assets are selected, the template name cannot be edited to avoid conflicts";
var nameField = new TextField("Name", 128, false, false, '*') { tooltip = nameTooltip, isDelayed = true };
nameField.BindProperty(allImportersSerializedObject.FindProperty("m_Template.name"));
nameField.enabledSelf = importers.Count == 1;
if (importers.Count > 1)
{
nameField.RegisterCallback<ContextualMenuPopulateEvent>(evt =>
{
evt.menu.ClearItems();
evt.StopImmediatePropagation();
});
}
expander.Add(nameField);
// Category field
var categoryField = new TextField("Category", 64, false, false, '*') { tooltip = "Category of the template, used to organize templates in the Template window.", isDelayed = true };
categoryField.BindProperty(allImportersSerializedObject.FindProperty("m_Template.category"));
expander.Add(categoryField);
// Description field
var descriptionField = new TextField("Description", 512, true, false, '*') { tooltip = "Description of the template, used to provide additional information about the template.", isDelayed = true };
descriptionField.BindProperty(allImportersSerializedObject.FindProperty("m_Template.description"));
expander.Add(descriptionField);
// Icon field
var iconField = new ObjectField("Icon") { objectType = typeof(Texture2D), tooltip = "Icon of the template, used to represent the template in the Template window." };
iconField.BindProperty(allImportersSerializedObject.FindProperty("m_Template.icon"));
expander.Add(iconField);
// Thumbnail field
var thumbnailField = new ObjectField("Thumbnail") { objectType = typeof(Texture2D), tooltip = "Thumbnail of the template, used to represent the template in the Template window details view." };
thumbnailField.BindProperty(allImportersSerializedObject.FindProperty("m_Template.thumbnail"));
expander.Add(thumbnailField);
header.TrackSerializedObjectValue(allImportersSerializedObject, x =>
{
// Does not work
/*foreach (var t in targets)
{
EditorUtility.SetDirty(t);
AssetDatabase.SaveAssetIfDirty(t);
}*/
// This works
AssetDatabase.ForceReserializeAssets(paths, ForceReserializeAssetsOptions.ReserializeMetadata);
});
}
return root;
}
private void OnInspectorGUIEmbedded()
{
resourceObject.Update();
GUI.enabled = AssetDatabase.IsOpenForEdit(this.target, StatusQueryOptions.UseCachedIfPossible);
VFXUpdateMode initialUpdateMode = (VFXUpdateMode)0;
bool? initialFixedDeltaTime = null;
bool? initialProcessEveryFrame = null;
bool? initialIgnoreGameTimeScale = null;
if (resourceUpdateModeProperty.hasMultipleDifferentValues)
{
var resourceUpdateModeProperties = resourceUpdateModeProperty.serializedObject.targetObjects
.Select(o => new SerializedObject(o)
.FindProperty(resourceUpdateModeProperty.propertyPath))
.ToArray(); //N.B.: This will create garbage
var allDeltaTime = resourceUpdateModeProperties.Select(o => ((VFXUpdateMode)o.intValue & VFXUpdateMode.DeltaTime) == VFXUpdateMode.DeltaTime)
.Distinct();
var allProcessEveryFrame = resourceUpdateModeProperties.Select(o => ((VFXUpdateMode)o.intValue & VFXUpdateMode.ExactFixedTimeStep) == VFXUpdateMode.ExactFixedTimeStep)
.Distinct();
var allIgnoreScale = resourceUpdateModeProperties.Select(o => ((VFXUpdateMode)o.intValue & VFXUpdateMode.IgnoreTimeScale) == VFXUpdateMode.IgnoreTimeScale)
.Distinct();
if (allDeltaTime.Count() == 1)
initialFixedDeltaTime = !allDeltaTime.First();
if (allProcessEveryFrame.Count() == 1)
initialProcessEveryFrame = allProcessEveryFrame.First();
if (allIgnoreScale.Count() == 1)
initialIgnoreGameTimeScale = allIgnoreScale.First();
}
else
{
initialUpdateMode = (VFXUpdateMode)resourceUpdateModeProperty.intValue;
initialFixedDeltaTime = !((initialUpdateMode & VFXUpdateMode.DeltaTime) == VFXUpdateMode.DeltaTime);
initialProcessEveryFrame = (initialUpdateMode & VFXUpdateMode.ExactFixedTimeStep) == VFXUpdateMode.ExactFixedTimeStep;
initialIgnoreGameTimeScale = (initialUpdateMode & VFXUpdateMode.IgnoreTimeScale) == VFXUpdateMode.IgnoreTimeScale;
}
EditorGUI.showMixedValue = !initialFixedDeltaTime.HasValue;
var deltaTimeContent = EditorGUIUtility.TrTextContent("Fixed Delta Time", "If enabled, use visual effect manager fixed delta time mode, otherwise, use the default Time.deltaTime.");
var processEveryFrameContent = EditorGUIUtility.TrTextContent("Exact Fixed Time", "Only relevant when using Fixed Delta Time. When enabled, several updates can be processed per frame (e.g.: if a frame is 10ms and the fixed frame rate is set to 5 ms, the effect will update twice with a 5ms deltaTime instead of once with a 10ms deltaTime). This method is expensive and should only be used for high-end scenarios.");
var ignoreTimeScaleContent = EditorGUIUtility.TrTextContent("Ignore Time Scale", "When enabled, the computed visual effect delta time ignores the game Time Scale value (Play Rate is still applied).");
VisualEffectAsset asset = (VisualEffectAsset)target;
VisualEffectResource resource = asset.GetResource();
using (VisualEffectEditor.ShowAssetHeader(EditorGUIUtility.TrTextContent("Update mode"), showUpdateModeCategory, out showUpdateModeCategory))
{
if (showUpdateModeCategory)
{
EditorGUI.BeginChangeCheck();
bool newFixedDeltaTime = EditorGUILayout.Toggle(deltaTimeContent, initialFixedDeltaTime ?? false);
bool newExactFixedTimeStep = false;
EditorGUI.showMixedValue = !initialProcessEveryFrame.HasValue;
EditorGUI.BeginDisabledGroup((!initialFixedDeltaTime.HasValue || !initialFixedDeltaTime.Value) && !resourceUpdateModeProperty.hasMultipleDifferentValues);
newExactFixedTimeStep = EditorGUILayout.Toggle(processEveryFrameContent, initialProcessEveryFrame ?? false);
EditorGUI.EndDisabledGroup();
EditorGUI.showMixedValue = !initialIgnoreGameTimeScale.HasValue;
bool newIgnoreTimeScale = EditorGUILayout.Toggle(ignoreTimeScaleContent, initialIgnoreGameTimeScale ?? false);
if (EditorGUI.EndChangeCheck())
{
if (!resourceUpdateModeProperty.hasMultipleDifferentValues)
{
var newUpdateMode = (VFXUpdateMode)0;
if (!newFixedDeltaTime)
newUpdateMode = newUpdateMode | VFXUpdateMode.DeltaTime;
if (newExactFixedTimeStep)
newUpdateMode = newUpdateMode | VFXUpdateMode.ExactFixedTimeStep;
if (newIgnoreTimeScale)
newUpdateMode = newUpdateMode | VFXUpdateMode.IgnoreTimeScale;
resourceUpdateModeProperty.intValue = (int)newUpdateMode;
resourceObject.ApplyModifiedProperties();
}
else
{
var resourceUpdateModeProperties = resourceUpdateModeProperty.serializedObject.targetObjects.Select(o => new SerializedObject(o).FindProperty(resourceUpdateModeProperty.propertyPath));
foreach (var property in resourceUpdateModeProperties)
{
var updateMode = (VFXUpdateMode)property.intValue;
if (initialFixedDeltaTime.HasValue)
{
if (!newFixedDeltaTime)
updateMode = updateMode | VFXUpdateMode.DeltaTime;
else
updateMode = updateMode & ~VFXUpdateMode.DeltaTime;
}
else
{
if (newFixedDeltaTime)
updateMode = updateMode & ~VFXUpdateMode.DeltaTime;
}
if (newExactFixedTimeStep)
updateMode = updateMode | VFXUpdateMode.ExactFixedTimeStep;
else if (initialProcessEveryFrame.HasValue)
updateMode = updateMode & ~VFXUpdateMode.ExactFixedTimeStep;
if (newIgnoreTimeScale)
updateMode = updateMode | VFXUpdateMode.IgnoreTimeScale;
else if (initialIgnoreGameTimeScale.HasValue)
updateMode = updateMode & ~VFXUpdateMode.IgnoreTimeScale;
property.intValue = (int)updateMode;
property.serializedObject.ApplyModifiedProperties();
}
}
}
//The following should be working, and works for newly created systems, but fails for old systems,
//due probably to incorrectly pasting the VFXData when creating them.
// bool hasAutomaticBoundsSystems = resource.GetOrCreateGraph().children
// .OfType<VFXDataParticle>().Any(d => d.boundsMode == BoundsSettingMode.Automatic);
bool hasAutomaticBoundsSystems = resource.GetOrCreateGraph().children
.OfType<VFXBasicInitialize>()
.Select(x => x.GetData())
.OfType<VFXDataParticle>()
.Any(x => x.boundsMode == BoundsSettingMode.Automatic);
using (new EditorGUI.DisabledScope(hasAutomaticBoundsSystems))
{
EditorGUILayout.BeginHorizontal();
EditorGUI.showMixedValue = cullingFlagsProperty.hasMultipleDifferentValues;
string forceSimulateTooltip = hasAutomaticBoundsSystems
? " When using systems with Bounds Mode set to Automatic, this has to be set to Always recompute bounds and simulate."
: "";
EditorGUI.BeginChangeCheck();
int newOption = EditorGUILayout.Popup(
EditorGUIUtility.TrTextContent("Culling Flags", "Specifies how the system recomputes its bounds and simulates when off-screen." + forceSimulateTooltip),
Array.IndexOf(k_CullingOptionsValue, (VFXCullingFlags)cullingFlagsProperty.intValue),
k_CullingOptionsContents);
if (EditorGUI.EndChangeCheck())
{
cullingFlagsProperty.intValue = (int)k_CullingOptionsValue[newOption];
resourceObject.ApplyModifiedProperties();
}
}
EditorGUILayout.EndHorizontal();
}
}
DrawInstancingGUI();
using (VisualEffectEditor.ShowAssetHeader(EditorGUIUtility.TrTextContent("Initial state"), showInitialStateCategory, out showInitialStateCategory))
{
if (showInitialStateCategory && prewarmDeltaTime != null && prewarmStepCount != null)
{
DisplayPrewarmInspectorGUI(resourceObject, prewarmDeltaTime, prewarmStepCount);
}
if (showInitialStateCategory && initialEventName != null)
{
EditorGUI.BeginChangeCheck();
EditorGUI.showMixedValue = initialEventName.hasMultipleDifferentValues;
EditorGUILayout.PropertyField(initialEventName, new GUIContent("Initial Event Name", "Sets the name of the event which triggers once the system is activated. Default: ‘OnPlay’."));
if (EditorGUI.EndChangeCheck())
{
resourceObject.ApplyModifiedProperties();
}
}
}
if (!serializedObject.isEditingMultipleObjects)
{
asset = (VisualEffectAsset)target;
resource = asset.GetResource();
m_OutputContexts.Clear();
m_OutputContexts.AddRange(resource.GetOrCreateGraph().children.OfType<IVFXSubRenderer>().OrderBy(t => t.vfxSystemSortPriority));
using (VisualEffectEditor.ShowAssetHeader(EditorGUIUtility.TrTextContent("Output Render Order"), showOutputOrderCategory, out showOutputOrderCategory))
{
if (showOutputOrderCategory)
{
m_ReorderableList.DoLayoutList();
}
}
using (VisualEffectEditor.ShowAssetHeader(EditorGUIUtility.TrTextContent("Shaders"), showShadersCategory, out showShadersCategory))
{
if (showShadersCategory)
{
string assetPath = AssetDatabase.GetAssetPath(asset);
UnityObject[] objects = AssetDatabase.LoadAllAssetsAtPath(assetPath);
string directory = Path.GetDirectoryName(assetPath) + "/" + VFXExternalShaderProcessor.k_ShaderDirectory + "/" + asset.name + "/";
foreach (var shader in objects)
{
if (shader is ComputeShader or Shader)
{
GUILayout.BeginHorizontal();
int index = resource.GetShaderIndex(shader);
EditorGUILayout.LabelField(shader.name.Replace('\n', ' '));
if (index >= 0)
{
if (VFXExternalShaderProcessor.allowExternalization && index < resource.GetShaderSourceCount())
{
string shaderSourceName = resource.GetShaderSourceName(index);
string externalPath = directory + shaderSourceName;
externalPath = directory + shaderSourceName.Replace('/', '_') + VFXExternalShaderProcessor.k_ShaderExt;
if (System.IO.File.Exists(externalPath))
{
if (GUILayout.Button("Reveal External", GUILayout.Width(80)))
{
EditorUtility.RevealInFinder(externalPath);
}
}
else
{
if (GUILayout.Button("Externalize", GUILayout.Width(80)))
{
Directory.CreateDirectory(directory);
File.WriteAllText(externalPath, "//" + shaderSourceName + "," + index.ToString() + "\n//Don't delete the previous line or this one\n" + resource.GetShaderSource(index));
}
}
}
if (GUILayout.Button("Show Generated", GUILayout.Width(110)))
{
resource.ShowGeneratedShaderFile(index);
}
}
if (GUILayout.Button("Select", GUILayout.Width(50)))
{
Selection.activeObject = shader;
}
GUILayout.EndHorizontal();
}
}
}
}
}
GUI.enabled = false;
}
private void DrawInstancingGUI()
{
using (VisualEffectEditor.ShowAssetHeader(k_InstancingContent, showInstancingCategory, out showInstancingCategory))
{
if (showInstancingCategory)
{
EditorGUI.BeginChangeCheck();
VFXInstancingDisabledReason disabledReason = (VFXInstancingDisabledReason)instancingDisabledReasonProperty.intValue;
bool forceDisabled = disabledReason != VFXInstancingDisabledReason.None;
if (forceDisabled)
{
System.Text.StringBuilder reasonString = new System.Text.StringBuilder("Instancing not available:");
GetInstancingDisabledReasons(reasonString, disabledReason);
EditorGUILayout.HelpBox(reasonString.ToString(), MessageType.Info);
}
VFXInstancingMode instancingMode = forceDisabled ? VFXInstancingMode.Disabled : (VFXInstancingMode)instancingModeProperty.intValue;
EditorGUI.BeginDisabled(forceDisabled);
instancingMode = (VFXInstancingMode)EditorGUILayout.EnumPopup(k_InstancingModeContent, instancingMode);
EditorGUI.EndDisabled();
int instancingCapacity = instancingCapacityProperty.intValue;
if (instancingMode == VFXInstancingMode.Custom)
{
instancingCapacity = EditorGUILayout.DelayedIntField(k_InstancingCapacityContent, instancingCapacity);
}