-
Notifications
You must be signed in to change notification settings - Fork 869
Expand file tree
/
Copy pathVFXGraph.cs
More file actions
1541 lines (1335 loc) · 59.7 KB
/
VFXGraph.cs
File metadata and controls
1541 lines (1335 loc) · 59.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
//#define USE_SHADER_AS_SUBASSET
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using Unity.Profiling;
using UnityEditor.ShaderGraph.Internal;
using UnityEditor.VFX.Block;
using UnityEditor.VFX.UI;
using UnityEngine;
using UnityEngine.VFX;
using UnityEngine.Profiling;
using UnityObject = UnityEngine.Object;
namespace UnityEditor.VFX
{
[InitializeOnLoad]
class VFXGraphPreprocessor : AssetPostprocessor
{
static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
List<string> assetToReimport = null;
#if VFX_HAS_TIMELINE
UnityEditor.VFX.Migration.ActivationToControlTrack.SanitizePlayable(importedAssets);
#endif
if (deletedAssets.Any())
{
VFXViewWindow.GetAllWindows().ToList().ForEach(x => x.UpdateHistory());
}
var isAnySubgraphImported = importedAssets.Any(VisualEffectAssetModificationProcessor.IsVFXSubgraphExtension);
foreach (var assetPath in importedAssets)
{
bool isVFX = VisualEffectAssetModificationProcessor.HasVFXExtension(assetPath);
if (isVFX)
{
VisualEffectResource resource = VisualEffectResource.GetResourceAtPath(assetPath);
if (resource == null)
continue;
VFXGraph graph = resource.GetOrCreateGraph(); //resource.graph should be already != null at this stage but GetOrCreateGraph is also assigning the visualEffectResource. It's required for UpdateSubAssets
if (graph != null)
{
bool wasGraphSanitized = graph.sanitized;
try
{
graph.SanitizeForImport();
if (!wasGraphSanitized && graph.sanitized)
{
assetToReimport ??= new List<string>();
assetToReimport.Add(assetPath);
}
}
catch (Exception exception)
{
Debug.LogErrorFormat("Exception during sanitization of {0} : {1}", assetPath, exception);
}
var window = VFXViewWindow.GetWindow(graph, false, false);
if (window != null)
{
window.UpdateTitle(assetPath);
// Force blackboard update only when a subgraph gets re-imported
if (isAnySubgraphImported)
{
window.graphView?.blackboard.Update(true);
}
}
}
else
{
Debug.LogErrorFormat("VisualEffectGraphResource without graph : {0}", assetPath);
}
}
}
//Relaunch previously skipped OnCompileResource
if (assetToReimport != null)
{
AssetDatabase.StartAssetEditing();
foreach (var assetPath in assetToReimport)
{
try
{
AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate);
}
catch (Exception exception)
{
Debug.LogErrorFormat("Exception during reimport of {0} : {1}", assetPath, exception);
}
}
AssetDatabase.StopAssetEditing();
}
}
static string[] OnAddResourceDependencies(string assetPath)
{
VisualEffectResource resource = VisualEffectResource.GetResourceAtPath(assetPath);
if (resource != null)
{
if (resource.graph is VFXGraph)
return resource.GetOrCreateGraph().UpdateImportDependencies();
Debug.LogError("VisualEffectGraphResource without graph");
}
return null;
}
static void OnCompileResource(VisualEffectResource resource)
{
if (resource != null)
{
VFXGraph graph = resource.graph as VFXGraph;
if (graph != null)
{
if (!graph.sanitized)
{
//Early return, the reimport will be forced with the next OnPostprocessAllAssets after Sanitize
resource.ClearRuntimeData();
}
else
{
//Workaround, use backup system to prevent any modification of the graph during compilation
//The responsible of this unexpected change is PrepareSubgraphs => RecurseSubgraphRecreateCopy => ResyncSlots
//It will let the VFXGraph in a really bad state after compilation.
graph = resource.GetOrCreateGraph();
var dependencies = new HashSet<ScriptableObject>();
dependencies.Add(graph);
graph.CollectDependencies(dependencies);
var backup = VFXMemorySerializer.StoreObjectsToByteArray(dependencies.ToArray(), CompressionLevel.None);
graph.errorManager.RefreshCompilationReport();
graph.CompileForImport();
VFXGraph.restoringGraph = true;
try
{
VFXMemorySerializer.ExtractObjects(backup, false);
}
finally
{
VFXGraph.restoringGraph = false;
}
//The backup during undo/redo is actually calling UnknownChange after ExtractObjects
//You have to avoid because it will call ResyncSlot
}
}
else
Debug.LogError("OnCompileResource error - VisualEffectResource without graph");
}
}
static void OnSetupMaterial(VisualEffectResource resource, Material material, UnityObject model)
{
if (resource != null)
{
// sanity checks
if (resource.graph == null)
{
Debug.LogError("OnSetupMaterial error - VisualEffectResource without graph");
return;
}
if (!(model is VFXModel))
{
Debug.LogError("OnSetupMaterial error - Passed object is not a VFXModel");
return;
}
//if (resource.graph != ((VFXModel)model).GetGraph())
//{
// Debug.LogError("OnSetupMaterial error - VisualEffectResource and VFXModel graph do not match");
// return;
//}
if (!resource.GetOrCreateGraph().sanitized)
{
Debug.LogError("OnSetupMaterial error - Graph hasn't been sanitized");
return;
}
// Actual call
if (model is IVFXSubRenderer)
{
((IVFXSubRenderer)model).SetupMaterial(material);
}
}
}
static VFXGraphPreprocessor()
{
EditorApplication.update += CheckCompilationVersion;
VisualEffectResource.onAddResourceDependencies = OnAddResourceDependencies;
VisualEffectResource.onCompileResource = OnCompileResource;
VisualEffectResource.onSetupMaterial = OnSetupMaterial;
}
static void CheckCompilationVersion()
{
EditorApplication.update -= CheckCompilationVersion;
UnityObject vfxmanager = AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/VFXManager.asset").FirstOrDefault();
SerializedObject serializedVFXManager = new SerializedObject(vfxmanager);
var compiledVersionProperty = serializedVFXManager.FindProperty("m_CompiledVersion");
var runtimeVersionProperty = serializedVFXManager.FindProperty("m_RuntimeVersion");
if (compiledVersionProperty.intValue != VFXGraphCompiledData.compiledVersion || runtimeVersionProperty.intValue != VisualEffectAsset.currentRuntimeDataVersion)
{
string[] allVisualEffectAssets = AssetDatabase.FindAssets("t:VisualEffectAsset");
compiledVersionProperty.intValue = (int)VFXGraphCompiledData.compiledVersion;
runtimeVersionProperty.intValue = (int)VisualEffectAsset.currentRuntimeDataVersion;
serializedVFXManager.ApplyModifiedProperties();
AssetDatabase.StartAssetEditing();
try
{
foreach (var guid in AssetDatabase.FindAssets("t:VisualEffectAsset"))
{
var path = AssetDatabase.GUIDToAssetPath(guid);
AssetDatabase.ImportAsset(path);
}
VFXAssetManager.ImportAllVFXShaders();
}
finally
{
AssetDatabase.StopAssetEditing();
}
}
}
}
class VFXAssetManager : EditorWindow
{
public static Dictionary<VisualEffectObject, string> GetAllVisualEffectObjects()
{
var allVisualEffectObjects = new Dictionary<VisualEffectObject, string>();
var vfxObjectsGuid = AssetDatabase.FindAssets("t:VisualEffectObject");
foreach (var guid in vfxObjectsGuid)
{
var assetPath = AssetDatabase.GUIDToAssetPath(guid);
var vfxObj = AssetDatabase.LoadAssetAtPath<VisualEffectObject>(assetPath);
if (vfxObj != null)
{
allVisualEffectObjects[vfxObj] = assetPath;
}
}
return allVisualEffectObjects;
}
public static Dictionary<Shader, string> GetAllShaderGraph()
{
var allShaderGraphObjects = new Dictionary<Shader, string>();
var shaderGraphGuids = AssetDatabase.FindAssets("t:Shader");
foreach (var guid in shaderGraphGuids)
{
var assetPath = AssetDatabase.GUIDToAssetPath(guid);
var shaderGraph = AssetDatabase.LoadAssetAtPath<Shader>(assetPath);
if (shaderGraph != null)
{
allShaderGraphObjects[shaderGraph] = assetPath;
}
}
return allShaderGraphObjects;
}
// Import VFX shader graph assets
// Because some shader compatible with VFX can be there before the Visual Effect package is installed
// We must re-import them to generate the ShaderGraphVfxAsset
public static void ImportAllVFXShaders()
{
var currentSrpBinder = VFXLibrary.currentSRPBinder;
if (currentSrpBinder != null)
{
foreach (var (shader, path) in GetAllShaderGraph())
{
var assets = AssetDatabase.LoadAllAssetsAtPath(path);
if (assets.OfType<ShaderGraphVfxAsset>().Any())
{
continue;
}
if (shader != null && currentSrpBinder.IsShaderVFXCompatible(shader))
{
AssetDatabase.ImportAsset(path, ImportAssetOptions.ForceUpdate);
}
}
}
}
public static void Build(bool forceDirty = false)
{
AssetDatabase.StartAssetEditing();
try
{
foreach (var vfxObj in GetAllVisualEffectObjects())
{
if (VFXViewPreference.advancedLogs)
Debug.Log($"Recompile VFX asset: {vfxObj.Key} ({vfxObj.Value})");
var resource = VisualEffectResource.GetResourceAtPath(vfxObj.Value);
if (resource != null)
{
AssetDatabase.ImportAsset(vfxObj.Value);
if (forceDirty)
EditorUtility.SetDirty(resource);
}
}
VFXExpression.ClearCache();
ImportAllVFXShaders();
}
finally
{
AssetDatabase.StopAssetEditing();
}
EditorUtility.UnloadUnusedAssetsImmediate();
GC.Collect();
}
[MenuItem("Edit/VFX/Rebuild And Save All VFX Graphs", priority = 10319)]
public static void BuildAndSave()
{
Build(true);
AssetDatabase.SaveAssets();
}
}
class VisualEffectAssetModificationProcessor : UnityEditor.AssetModificationProcessor
{
public static bool HasVFXExtension(string filePath)
{
if (!string.IsNullOrEmpty(filePath) &&
(filePath.EndsWith(VisualEffectResource.Extension, StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(VisualEffectSubgraphBlock.Extension, StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(VisualEffectSubgraphOperator.Extension, StringComparison.OrdinalIgnoreCase)))
{
// See this PR https://github.com/Unity-Technologies/Graphics/pull/6890
#if UNITY_STANDALONE_OSX || UNITY_EDITOR_OSX
return !AssetDatabase.IsValidFolder(filePath);
#else
return true;
#endif
}
return false;
}
public static bool IsVFXSubgraphExtension(string filePath)
{
return filePath.EndsWith(VisualEffectSubgraphBlock.Extension, StringComparison.OrdinalIgnoreCase)
|| filePath.EndsWith(VisualEffectSubgraphOperator.Extension, StringComparison.OrdinalIgnoreCase);
}
static string[] OnWillSaveAssets(string[] paths)
{
Profiler.BeginSample("VisualEffectAssetModicationProcessor.OnWillSaveAssets");
bool started = false;
try {
foreach (string path in paths.Where(HasVFXExtension))
{
if (!started)
{
started = true;
AssetDatabase.StartAssetEditing();
}
var vfxResource = VisualEffectResource.GetResourceAtPath(path);
vfxResource?.WriteAssetWithSubAssets();
}
}
finally
{
if (started)
AssetDatabase.StopAssetEditing();
}
Profiler.EndSample();
return paths;
}
}
static class VisualEffectResourceExtensions
{
public static VFXGraph GetOrCreateGraph(this VisualEffectResource resource)
{
VFXGraph graph = resource.graph as VFXGraph;
if (graph == null)
{
string assetPath = AssetDatabase.GetAssetPath(resource);
AssetDatabase.ImportAsset(assetPath);
graph = resource.GetContents().OfType<VFXGraph>().FirstOrDefault();
}
if (graph == null)
{
graph = ScriptableObject.CreateInstance<VFXGraph>();
resource.graph = graph;
graph.hideFlags |= HideFlags.HideInHierarchy;
graph.visualEffectResource = resource;
// in this case we must update the subassets so that the graph is added to the resource dependencies
graph.UpdateSubAssets();
}
graph.visualEffectResource = resource;
return graph;
}
public static void UpdateSubAssets(this VisualEffectResource resource)
{
resource.GetOrCreateGraph().UpdateSubAssets();
}
public static void WriteAssetWithSubAssets(this VisualEffectResource resource)
{
var graph = resource.GetOrCreateGraph();
graph.UpdateSubAssets();
resource.WriteAsset();
}
public static bool IsAssetEditable(this VisualEffectResource resource)
{
return AssetDatabase.IsOpenForEdit((UnityEngine.Object)resource.asset ?? resource.subgraph, StatusQueryOptions.UseCachedIfPossible);
}
}
static class VisualEffectObjectExtensions
{
public static VisualEffectResource GetOrCreateResource(this VisualEffectObject asset)
{
string assetPath = AssetDatabase.GetAssetPath(asset);
VisualEffectResource resource = VisualEffectResource.GetResourceAtPath(assetPath);
if (resource == null && !string.IsNullOrEmpty(assetPath))
{
resource = new VisualEffectResource();
resource.SetAssetPath(assetPath);
}
return resource;
}
public static VisualEffectResource GetResource(this VisualEffectObject asset)
{
string assetPath = AssetDatabase.GetAssetPath(asset);
VisualEffectResource resource = VisualEffectResource.GetResourceAtPath(assetPath);
if (resource == null && !string.IsNullOrEmpty(assetPath))
throw new NullReferenceException($"VFX resource does not exist for this asset at path: {assetPath}");
return resource;
}
}
class VFXGraph : VFXModel
{
// Please add increment reason for each version below
// 1: Size refactor
// 2: Change some SetAttribute to spaceable slot
// 3: Remove Masked from blendMode in Outputs and split feature to UseAlphaClipping
// 4: TransformVector|Position|Direction & DistanceToSphere|Plane|Line have now spaceable outputs
// 5: Harmonized position blocks composition: PositionAABox was the only one with Overwrite position
// 6: Remove automatic strip orientation from quad strip context
// 7: Add CameraBuffer type
// 8: Bounds computation introduces a BoundsSettingMode for VFXDataParticles
// 9: Update HDRP decal angle fade encoding
// 10: Position Mesh and Skinned Mesh out of experimental (changing the list of flag and output types)
// 11: Instancing
// 12: Change space value of VFXSpace.None from 'int.MaxValue' to '-1'
// 13: Unexpected incorrect synchronization of output with ShaderGraph
// 14: ShaderGraph integration uses the material variant workflow
// 15: New ShaderGraph integration uses independent output
// 16: Add a collection of custom attributes (to be listed in blackboard)
// 17: New Flipbook player and split the different Flipbook modes in UVMode into separate variables
// 18: Change ProbabilitySampling m_IntegratedRandomDeprecated changed to m_Mode
public static readonly int CurrentVersion = 18;
public override void OnSRPChanged()
{
m_GraphSanitized = false;
m_ExpressionGraphDirty = true;
}
public VisualEffectResource visualEffectResource
{
get
{
return m_Owner;
}
set
{
if (m_Owner != value)
{
m_Owner = value;
m_Owner.graph = this;
m_ExpressionGraphDirty = true;
}
}
}
[SerializeField]
VFXUI m_UIInfos;
public VFXUI UIInfos
{
get
{
if (m_UIInfos == null)
{
m_UIInfos = ScriptableObject.CreateInstance<VFXUI>();
}
return m_UIInfos;
}
}
[SerializeField]
List<VFXCustomAttributeDescriptor> m_CustomAttributes;
// Do not serialize custom attributes imported from sub-graphs
readonly List<VFXCustomAttributeDescriptor> m_DependenciesCustomAttributes = new();
public IEnumerable<VFXCustomAttributeDescriptor> customAttributes => (m_CustomAttributes ??= new List<VFXCustomAttributeDescriptor>()).Concat(m_DependenciesCustomAttributes);
public VFXParameterInfo[] m_ParameterInfo;
private VFXErrorManager m_ErrorManager;
private readonly VFXSystemNames m_SystemNames = new();
private readonly VFXAttributesManager m_AttributesManager = new();
public VFXErrorManager errorManager => m_ErrorManager ??= new VFXErrorManager();
public VFXSystemNames systemNames => m_SystemNames;
public VFXAttributesManager attributesManager => m_AttributesManager;
public void BuildParameterInfo()
{
m_ParameterInfo = VFXParameterInfo.BuildParameterInfo(this);
VisualEffectEditor.RepaintAllEditors();
}
public override bool AcceptChild(VFXModel model, int index = -1)
{
return !(model is VFXGraph); // Can hold any model except other VFXGraph
}
public void SyncCustomAttributes()
{
m_CustomAttributes.RemoveAll(x => x == null);
foreach (var attributeDescriptor in customAttributes.ToArray())
{
attributeDescriptor.graph = this;
m_AttributesManager.TryRegisterCustomAttribute(attributeDescriptor.attributeName, attributeDescriptor.type, attributeDescriptor.description, out _);
var usages = GetCustomAttributeUsage(attributeDescriptor.attributeName).ToArray();
attributeDescriptor.ClearSubgraphUse();
foreach (var usage in usages.Where(VFXSubgraphUtility.IsSubgraphModel))
{
attributeDescriptor.AddSubgraphUse(usage.name);
}
// Remove custom attributes from sub-graphs that are not used by sub-graph anymore
if (attributeDescriptor.usedInSubgraphs == null && m_DependenciesCustomAttributes.Contains(attributeDescriptor))
{
m_DependenciesCustomAttributes.Remove(attributeDescriptor);
SetCustomAttributeDirty();
}
// Check if custom attribute is used, but not in sub-graph and not yet in the serialized collection
if (attributeDescriptor.usedInSubgraphs == null && usages.Length > 0 && !m_CustomAttributes.Contains(attributeDescriptor))
{
m_CustomAttributes.Add(attributeDescriptor);
attributeDescriptor.isReadOnly = false;
SetCustomAttributeDirty();
}
// Move custom attributes used in subgraph into the transient collection
else if (attributeDescriptor.usedInSubgraphs != null && m_CustomAttributes.Contains(attributeDescriptor))
{
m_CustomAttributes.Remove(attributeDescriptor);
if (!m_DependenciesCustomAttributes.Contains(attributeDescriptor))
{
m_DependenciesCustomAttributes.Add(attributeDescriptor);
}
attributeDescriptor.isReadOnly = true;
SetCustomAttributeDirty();
}
}
// Remove custom attributes from attribute manager if they do not exist anymore
foreach (var customAttribute in m_AttributesManager.GetCustomAttributes().ToArray())
{
if (customAttributes.All(x => string.Compare(x.attributeName, customAttribute.name, StringComparison.OrdinalIgnoreCase) != 0))
{
m_AttributesManager.UnregisterCustomAttribute(customAttribute.name);
}
}
}
public bool TryAddCustomAttribute(string attributeName, VFXValueType type, string description, bool isReadOnly, out VFXAttribute newAttribute)
{
var signature = CustomAttributeUtility.GetSignature(type);
if (m_AttributesManager.TryRegisterCustomAttribute(attributeName, signature, description, out newAttribute))
{
var customAttribute = CreateInstance<VFXCustomAttributeDescriptor>();
customAttribute.attributeName = newAttribute.name;
customAttribute.type = CustomAttributeUtility.GetSignature(type);
customAttribute.description = description;
customAttribute.graph = this;
customAttribute.isReadOnly = isReadOnly;
if (!isReadOnly)
{
m_CustomAttributes.Add(customAttribute);
}
else
{
m_DependenciesCustomAttributes.Add(customAttribute);
}
if (!isReadOnly) // if not from subgraph
Invalidate(InvalidationCause.kStructureChanged);
return true;
}
return false;
}
public bool IsCustomAttributeUsed(string attributeName)
{
// First look at operators
if (children
.OfType<IVFXAttributeUsage>()
.SelectMany(x => x.usedAttributes)
.Any(x => string.Compare(x.name, attributeName, StringComparison.OrdinalIgnoreCase) == 0))
return true;
// Look in context blocks
if (children
.OfType<VFXContext>()
.SelectMany(x => x.children)
.OfType<IVFXAttributeUsage>()
.SelectMany(x => x.usedAttributes)
.Distinct()
.Any(x => string.Compare(x.name, attributeName, StringComparison.OrdinalIgnoreCase) == 0))
return true;
return false;
}
public void SetCustomAttributeOrder(string attributeName, int order)
{
if (TryFindCustomAttributeDescriptor(attributeName, out var attributeDescriptor))
{
m_CustomAttributes.Remove(attributeDescriptor);
m_CustomAttributes.Insert(order, attributeDescriptor);
Invalidate(InvalidationCause.kStructureChanged);
}
}
public bool TryFindCustomAttributeDescriptor(string attributeName, out VFXCustomAttributeDescriptor attributeDescriptor)
{
attributeDescriptor = customAttributes.SingleOrDefault(x => string.Compare(attributeName, x.attributeName, StringComparison.OrdinalIgnoreCase) == 0);
return attributeDescriptor != null;
}
public IEnumerable<string> GetUnusedCustomAttributes()
{
var objs = new HashSet<ScriptableObject>();
CollectDependencies(objs, true);
var nodesUsingCustomAttribute = objs
.OfType<IVFXAttributeUsage>()
.SelectMany(x => x.usedAttributes)
.Where(x => this.attributesManager.IsCustom(x.name))
.Select(x => x.name)
.ToArray();
return this.attributesManager.GetCustomAttributeNames().Except(nodesUsingCustomAttribute);
}
public VFXAttribute DuplicateCustomAttribute(string attributeName)
{
var newAttribute = m_AttributesManager.Duplicate(attributeName);
var currentIndex = m_CustomAttributes.FindIndex(x => x.attributeName == attributeName);
var order = currentIndex >= 0 ? currentIndex + 1 : m_CustomAttributes.Count;
if (TryAddCustomAttribute(newAttribute.name, newAttribute.type, newAttribute.description, false, out var attribute))
{
SetCustomAttributeOrder(attribute.name, order);
}
return attribute;
}
public void RemoveCustomAttribute(string attributeName)
{
var existingAttribute = this.FindCustomAttribute(attributeName);
if (existingAttribute != null)
{
foreach (var usage in GetCustomAttributeUsage(attributeName).ToArray())
{
if (Selection.Contains(usage))
Selection.Remove(usage);
RemoveModel(usage);
}
m_AttributesManager.UnregisterCustomAttribute(attributeName);
m_CustomAttributes.Remove(existingAttribute);
Invalidate(this, InvalidationCause.kStructureChanged);
}
}
public bool TryRenameCustomAttribute(string oldName, string newName)
{
var customAttributeDescriptor = FindCustomAttribute(oldName);
var usingNodes = GetRecursiveChildren()
.OfType<IVFXAttributeUsage>()
.Where(x => x.usedAttributes.Any(x => string.Compare(x.name, oldName, StringComparison.OrdinalIgnoreCase) == 0))
.ToArray();
var result = this.m_AttributesManager.TryRename(oldName, newName);
if (result == RenameStatus.Success)
{
customAttributeDescriptor.attributeName = newName;
foreach (var customAttributeNode in usingNodes)
{
customAttributeNode.Rename(oldName, newName);
}
Invalidate(this, InvalidationCause.kStructureChanged);
return true;
}
// Already renamed
if (result == RenameStatus.NotFound && FindCustomAttribute(newName) != null)
{
return true;
}
if (result == RenameStatus.NameUsed)
{
Debug.LogWarning("You are trying to rename a custom attribute with a name that is already used by another custom attribute");
}
return false;
}
public bool TryUpdateCustomAttribute(string attributeName, CustomAttributeUtility.Signature type, string description, bool? isReadOnly = null)
{
var customAttributeDescriptor = this.FindCustomAttribute(attributeName);
if (this.attributesManager.TryUpdate(attributeName, type, description))
{
customAttributeDescriptor.type = type;
customAttributeDescriptor.description = description;
var usingNodes = GetRecursiveChildren()
.OfType<IVFXAttributeUsage>()
.Where(x => x.usedAttributes.Any(x => string.Compare(x.name, attributeName, StringComparison.OrdinalIgnoreCase) == 0));
foreach (var node in usingNodes)
{
((VFXModel)node).Invalidate(InvalidationCause.kSettingChanged);
}
if (isReadOnly == false || (isReadOnly == null && !customAttributeDescriptor.isReadOnly)) // if not from subgraph
Invalidate(this, InvalidationCause.kStructureChanged);
return true;
}
if (customAttributeDescriptor != null && isReadOnly.HasValue && isReadOnly.Value != customAttributeDescriptor.isReadOnly)
{
customAttributeDescriptor.isReadOnly = isReadOnly.Value;
if (isReadOnly.Value)
{
m_CustomAttributes.Remove(customAttributeDescriptor);
if (!m_DependenciesCustomAttributes.Contains(customAttributeDescriptor))
{
m_DependenciesCustomAttributes.Add(customAttributeDescriptor);
}
}
else
{
if (!m_CustomAttributes.Contains(customAttributeDescriptor))
{
m_CustomAttributes.Add(customAttributeDescriptor);
}
m_DependenciesCustomAttributes.Remove(customAttributeDescriptor);
}
}
return false;
}
public void SetCustomAttributeExpanded(string attributeName, bool isExpanded)
{
var customAttributeDescriptor = this.FindCustomAttribute(attributeName);
customAttributeDescriptor.isExpanded = isExpanded;
}
public object Backup()
{
Profiler.BeginSample("VFXGraph.Backup");
var dependencies = new HashSet<ScriptableObject>();
dependencies.Add(this);
CollectDependencies(dependencies);
var result = VFXMemorySerializer.StoreObjectsToByteArray(dependencies.ToArray(), CompressionLevel.Fastest);
Profiler.EndSample();
return result;
}
public void Restore(object str)
{
Profiler.BeginSample("VFXGraph.Restore");
var scriptableObject = VFXMemorySerializer.ExtractObjects(str as byte[], false);
var graph = scriptableObject.OfType<VFXGraph>().Single();
graph.SyncCustomAttributes();
Profiler.BeginSample("VFXGraph.Restore SendUnknownChange");
foreach (var model in scriptableObject.OfType<VFXModel>())
{
model.OnUnknownChange();
}
Profiler.EndSample();
Profiler.EndSample();
m_SystemNames.Sync(this);
m_ExpressionGraphDirty = true;
m_ExpressionValuesDirty = true;
m_DependentDirty = true;
SetCustomAttributeDirty();
}
public override void CollectDependencies(HashSet<ScriptableObject> objs, bool ownedOnly = true)
{
Profiler.BeginSample("VFXEditor.CollectDependencies");
try
{
if (m_UIInfos != null)
objs.Add(m_UIInfos);
m_CustomAttributes?.ForEach(x => { if (x != null) objs.Add(x); });
base.CollectDependencies(objs, ownedOnly);
}
finally
{
Profiler.EndSample();
}
}
static readonly ProfilerMarker k_ProfilerMarkerSanitizeGraph = new("VFXEditor.SanitizeGraph");
public void SanitizeGraph()
{
if (m_GraphSanitized)
return;
using var profilerScope = k_ProfilerMarkerSanitizeGraph.Auto();
var objs = new HashSet<ScriptableObject>();
CollectDependencies(objs);
if (version < 7)
{
SanitizeCameraBuffers(objs);
}
SyncCustomAttributes();
foreach (var model in objs.OfType<VFXModel>())
{
try
{
model.Sanitize(m_GraphVersion); // This can modify dependencies but newly created model are supposed safe so we dont care about retrieving new dependencies
}
catch (Exception e)
{
Debug.LogError(string.Format("Exception while sanitizing model: {0} of type {1}: {2} {3}", model.name, model.GetType(), e, e.StackTrace));
}
}
if (m_UIInfos != null)
try
{
m_UIInfos.Sanitize(this);
}
catch (Exception e)
{
Debug.LogError(string.Format("Exception while sanitizing VFXUI: : {0} {1}", e, e.StackTrace));
}
systemNames.Sync(this);
if (version < 11)
{
visualEffectResource.instancingMode = VFXInstancingMode.Disabled;
}
if (version < 14)
{
objs
.OfType<IVFXAttributeUsage>()
.SelectMany(x => x.usedAttributes)
.Where(x => m_AttributesManager.IsCustom(x.name))
.GroupBy(x => x.name)
.Select(x => x.First())
.Where(x => customAttributes.All(y => y.attributeName != x.name))
.ToList()
.ForEach(x => TryAddCustomAttribute(x.name, x.type, string.Empty, false, out _));
}
int resourceCurrentVersion = 0;
// Stop using reflection after 2020.2;
FieldInfo info = typeof(VisualEffectResource).GetField("CurrentVersion", BindingFlags.Static | System.Reflection.BindingFlags.Public);
if (info != null)
resourceCurrentVersion = (int)info.GetValue(null);
if (m_ResourceVersion < resourceCurrentVersion) // Graph not up to date
{
if (m_ResourceVersion < 1) // Version before gradient interpreted as linear
{
foreach (var model in objs.OfType<VFXSlotGradient>())
{
Gradient value = (Gradient)model.value;
GradientColorKey[] keys = value.colorKeys;
for (int i = 0; i < keys.Length; ++i)
{
var colorKey = keys[i];
colorKey.color = colorKey.color.linear;
keys[i] = colorKey;
}
value.colorKeys = keys;
model.value = new Gradient();
model.value = value;
}
}
}
m_ResourceVersion = resourceCurrentVersion;
m_GraphSanitized = true;
m_GraphVersion = CurrentVersion;
UpdateSubAssets(); //Force remove no more referenced object from the asset & *important* register as persistent new dependencies
}
private IEnumerable<VFXModel> GetCustomAttributeUsage(string attributeName)
{
bool IsAttributeUsed(IVFXAttributeUsage attributeUsage, string attrName)
{
return attributeUsage.usedAttributes.Any(x => string.Compare(x.name, attrName, StringComparison.OrdinalIgnoreCase) == 0);
}
foreach (var child in children.Where(x => x is IVFXAttributeUsage))
{
if (IsAttributeUsed((IVFXAttributeUsage)child, attributeName))
yield return child;
}
foreach (var context in children.OfType<VFXContext>())
{
foreach (var block in context.children)
{
if (IsAttributeUsed(block, attributeName))
yield return block;
}
}
}
private VFXCustomAttributeDescriptor FindCustomAttribute(string attributeName)
{
return customAttributes.FirstOrDefault(x => string.Compare(attributeName, x.attributeName, StringComparison.OrdinalIgnoreCase) == 0);
}
private void SanitizeCameraBuffers(HashSet<ScriptableObject> objs)
{
List<Tuple<int, string, int, string>> links = new List<Tuple<int, string, int, string>>();
var cameraSlots = objs.Where(obj => obj is VFXSlot && (obj as VFXSlot).value is CameraType).ToArray();
for (int i = 0; i < cameraSlots.Length; ++i)
{
var cameraSlot = cameraSlots[i] as VFXSlot;
var depthBufferSlot = cameraSlot.children.First(slot => slot.name == "depthBuffer");
SanitizeCameraBufferLinks(depthBufferSlot, i, cameraSlots, links);
var colorBufferSlot = cameraSlot.children.First(slot => slot.name == "colorBuffer");
SanitizeCameraBufferLinks(colorBufferSlot, i, cameraSlots, links);
objs.Remove(cameraSlots[i]);
cameraSlots[i] = cameraSlot.Recreate();
objs.Add(cameraSlots[i]);
}
foreach (var link in links)
{
var cameraSlotFrom = cameraSlots[link.Item1] as VFXSlot;