-
Notifications
You must be signed in to change notification settings - Fork 877
Expand file tree
/
Copy pathVFXContextUI.cs
More file actions
1035 lines (879 loc) · 39.3 KB
/
Copy pathVFXContextUI.cs
File metadata and controls
1035 lines (879 loc) · 39.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.Collections.Generic;
using System.Linq;
using UnityEditor.Experimental.GraphView;
using UnityEditor.VFX.Block;
using UnityEngine;
using UnityEngine.VFX;
using UnityEngine.UIElements;
using UnityEngine.Profiling;
using PositionType = UnityEngine.UIElements.Position;
namespace UnityEditor.VFX.UI
{
class VFXContextUI : VFXNodeUI
{
// TODO: Unused except for debugging
readonly CustomStyleProperty<Color> RectColorProperty = new CustomStyleProperty<Color>("--rect-color");
Image m_HeaderIcon;
Image m_HeaderSpace;
Label m_Subtitle;
VisualElement m_Footer;
Image m_FooterIcon;
Label m_FooterTitle;
VisualElement m_FlowInputConnectorContainer;
VisualElement m_FlowOutputConnectorContainer;
VisualElement m_BlockContainer;
VisualElement m_NoBlock;
VisualElement m_DragDisplay;
Label m_Label;
TextField m_TextField;
public new VFXContextController controller
{
get { return base.controller as VFXContextController; }
}
protected override void OnNewController()
{
foreach (var descriptor in VFXLibrary.GetBlocks())
{
var model = descriptor.CreateInstance();
if (controller.model.AcceptChild(model))
{
m_CanHaveBlocks = true;
break;
}
}
}
public bool canHaveBlocks { get => m_CanHaveBlocks; }
public static string ContextEnumToClassName(string name)
{
if (name[0] == 'k')
{
Debug.LogError("Fix this since k should have been removed from enums");
}
return name.ToLower();
}
public void UpdateLabel()
{
var graph = controller.model.GetGraph();
if (graph != null && controller.model.contextType == VFXContextType.Spawner)
m_Label.text = graph.systemNames.GetUniqueSystemName(controller.model.GetData());
else
m_Label.text = controller.model.label;
}
protected override void SelfChange()
{
base.SelfChange();
Profiler.BeginSample("VFXContextUI.CreateBlockProvider");
if (m_BlockProvider == null)
{
m_BlockProvider = new VFXBlockProvider(controller, (variant, mPos) =>
{
if (variant.modelType != typeof(VisualEffectSubgraphBlock))
{
UpdateSelectionWithNewBlocks();
AddBlock(mPos, variant);
}
else
{
var path = variant.settings.Single(x => x.Key == "path").Value as string;
var subgraphBlock = AssetDatabase.LoadAssetAtPath<VisualEffectSubgraphBlock>(path);
var view = GetFirstAncestorOfType<VFXView>();
var graph = subgraphBlock.GetResource().GetOrCreateGraph();
if (view.HasCustomAttributeConflicts(graph.attributesManager.GetCustomAttributes()))
{
return;
}
// Prevent cyclic recursion
if (controller.model.GetGraph() == graph)
{
Debug.LogWarning("Cannot add this subgraph because it would create a cyclic recursion");
return;
}
int blockIndex = GetDragBlockIndex(mPos);
VFXBlock newModel = ScriptableObject.CreateInstance<VFXSubgraphBlock>();
newModel.SetSettingValue("m_Subgraph", subgraphBlock);
UpdateSelectionWithNewBlocks();
using var growContext = new GrowContext(this);
controller.AddBlock(blockIndex, newModel, true);
}
});
}
Profiler.EndSample();
if (inputContainer.childCount == 0 && !hasSettings)
{
mainContainer.AddToClassList("empty");
}
else
{
mainContainer.RemoveFromClassList("empty");
}
m_Divider.visible = hasSettings;
m_HeaderIcon.image = GetIconForVFXType(controller.model.inputType);
m_HeaderIcon.visible = m_HeaderIcon.image != null;
var subTitle = controller.subtitle;
m_Subtitle.text = controller.subtitle;
if (string.IsNullOrEmpty(subTitle))
{
m_Subtitle.AddToClassList("empty");
}
else
{
m_Subtitle.RemoveFromClassList("empty");
}
Profiler.BeginSample("VFXContextUI.SetAllStyleClasses");
VFXContextType contextType = controller.model.contextType;
foreach (VFXContextType value in System.Enum.GetValues(typeof(VFXContextType)))
{
if (value != contextType)
RemoveFromClassList(ContextEnumToClassName(value.ToString()));
}
AddToClassList(ContextEnumToClassName(contextType.ToString()));
var inputType = controller.model.inputType;
if (inputType == VFXDataType.None)
{
inputType = controller.model.ownedType;
}
foreach (VFXDataType value in System.Enum.GetValues(typeof(VFXDataType)))
{
if (inputType != value)
RemoveFromClassList("inputType" + ContextEnumToClassName(value.ToString()));
}
AddToClassList("inputType" + ContextEnumToClassName(inputType.ToString()));
var outputType = controller.model.outputType;
foreach (VFXDataType value in System.Enum.GetValues(typeof(VFXDataType)))
{
if (value != outputType)
RemoveFromClassList("outputType" + ContextEnumToClassName(value.ToString()));
}
AddToClassList("outputType" + ContextEnumToClassName(outputType.ToString()));
var type = controller.model.ownedType;
foreach (VFXDataType value in System.Enum.GetValues(typeof(VFXDataType)))
{
if (value != type)
RemoveFromClassList("type" + ContextEnumToClassName(value.ToString()));
}
AddToClassList("type" + ContextEnumToClassName(type.ToString()));
var space = controller.model.space;
foreach (VFXSpace val in System.Enum.GetValues(typeof(VFXSpace)))
{
if (val != space || !controller.model.spaceable)
m_HeaderSpace.RemoveFromClassList("space" + val.ToString());
}
if (controller.model.spaceable)
m_HeaderSpace.AddToClassList("space" + (controller.model.space).ToString());
Profiler.EndSample();
if (controller.model.outputType == VFXDataType.None)
{
if (m_Footer.parent != null)
m_Footer.RemoveFromHierarchy();
}
else
{
if (m_Footer.parent == null)
mainContainer.Add(m_Footer);
if (controller.model.outputFlowSlot.Any())
{
m_FooterTitle.text = controller.model.outputType.ToString();
m_FooterIcon.image = GetIconForVFXType(controller.model.outputType);
}
else
{
m_FooterTitle.text = string.Empty;
m_FooterIcon.image = null;
}
m_FooterIcon.visible = m_FooterIcon.image != null;
}
Profiler.BeginSample("VFXContextUI.CreateInputFlow");
HashSet<VisualElement> newInAnchors = new HashSet<VisualElement>();
foreach (var inanchorcontroller in controller.flowInputAnchors.Take(VFXContext.kMaxFlowCount))
{
var existing = m_FlowInputConnectorContainer.Children().Select(t => t as VFXFlowAnchor).FirstOrDefault(t => t.controller == inanchorcontroller);
if (existing == null)
{
var anchor = VFXFlowAnchor.Create(inanchorcontroller);
m_FlowInputConnectorContainer.Add(anchor);
newInAnchors.Add(anchor);
}
else
{
newInAnchors.Add(existing);
}
}
foreach (var nonLongerExistingAnchor in m_FlowInputConnectorContainer.Children().Where(t => !newInAnchors.Contains(t)).ToList()) // ToList to make a copy because the enumerable will change when we delete
{
m_FlowInputConnectorContainer.Remove(nonLongerExistingAnchor);
}
Profiler.EndSample();
Profiler.BeginSample("VFXContextUI.CreateInputFlow");
HashSet<VisualElement> newOutAnchors = new HashSet<VisualElement>();
foreach (var outanchorcontroller in controller.flowOutputAnchors.Take(VFXContext.kMaxFlowCount))
{
var existing = m_FlowOutputConnectorContainer.Children().Select(t => t as VFXFlowAnchor).FirstOrDefault(t => t.controller == outanchorcontroller);
if (existing == null)
{
var anchor = VFXFlowAnchor.Create(outanchorcontroller);
m_FlowOutputConnectorContainer.Add(anchor);
newOutAnchors.Add(anchor);
}
else
{
newOutAnchors.Add(existing);
}
}
foreach (var nonLongerExistingAnchor in m_FlowOutputConnectorContainer.Children().Where(t => !newOutAnchors.Contains(t)).ToList()) // ToList to make a copy because the enumerable will change when we delete
{
m_FlowOutputConnectorContainer.Remove(nonLongerExistingAnchor);
}
Profiler.EndSample();
UpdateLabel();
if (string.IsNullOrEmpty(m_Label.text))
{
m_Label.AddToClassList("empty");
}
else
{
m_Label.RemoveFromClassList("empty");
}
foreach (var inEdge in m_FlowInputConnectorContainer.Children().OfType<VFXFlowAnchor>().SelectMany(t => t.connections))
inEdge.UpdateEdgeControl();
foreach (var outEdge in m_FlowOutputConnectorContainer.Children().OfType<VFXFlowAnchor>().SelectMany(t => t.connections))
outEdge.UpdateEdgeControl();
RefreshContext();
}
VisualElement m_Divider;
public VFXContextUI() : base("uxml/VFXContext")
{
capabilities |= Capabilities.Selectable | Capabilities.Movable | Capabilities.Deletable | Capabilities.Ascendable;
styleSheets.Add(VFXView.LoadStyleSheet("VFXContext"));
styleSheets.Add(VFXView.LoadStyleSheet("Selectable"));
AddToClassList("VFXContext");
AddToClassList("selectable");
this.mainContainer.style.overflow = Overflow.Visible;
m_Divider = this.mainContainer.Q("divider");
m_FlowInputConnectorContainer = this.Q("flow-inputs");
m_FlowOutputConnectorContainer = this.Q("flow-outputs");
m_HeaderIcon = titleContainer.Q<Image>("icon");
m_HeaderSpace = titleContainer.Q<Image>("header-space");
m_HeaderSpace.AddManipulator(new Clickable(OnSpace));
m_Subtitle = this.Q<Label>("subtitle");
m_BlockContainer = this.Q("block-container");
m_NoBlock = m_BlockContainer.Q("no-blocks");
m_Footer = this.Q("footer");
m_FooterTitle = m_Footer.Q<Label>("title-label");
m_FooterIcon = m_Footer.Q<Image>("icon");
m_DragDisplay = new VisualElement();
m_DragDisplay.AddToClassList("dragdisplay");
m_Label = this.Q<Label>("user-label");
m_TextField = this.Q<TextField>("user-title-textfield");
m_TextField.maxLength = 175;
m_TextField.style.display = DisplayStyle.None;
m_Label.RegisterCallback<MouseDownEvent>(OnTitleMouseDown);
m_TextField.RegisterCallback<ChangeEvent<string>>(OnTitleChange);
m_TextField.Q(TextField.textInputUssName).RegisterCallback<FocusOutEvent>(OnTitleBlur, TrickleDown.TrickleDown);
this.Q("selection-border").SendToBack();
RegisterCallback<DragUpdatedEvent>(OnDragUpdated);
RegisterCallback<DragPerformEvent>(OnDragPerform);
RegisterCallback<DragExitedEvent>(OnDragExited);
RegisterCallback<DragLeaveEvent>(OnDragExited);
}
bool m_CanHaveBlocks = false;
void OnSpace()
{
if (controller.model.space == VFXSpace.World)
controller.model.space = VFXSpace.Local;
else
controller.model.space = VFXSpace.World;
}
private bool HasDroppableAttributeItems(IEnumerable<AttributeItem> attributeItems)
{
foreach (var attributeItem in GetDroppableAttributeItems(attributeItems))
{
return true;
}
return false;
}
private IEnumerable<AttributeItem> GetDroppableAttributeItems(IEnumerable<AttributeItem> attributeItems)
{
if (controller.model.contextType == VFXContextType.Spawner)
{
foreach (var attributeItem in attributeItems)
{
if (AttributeProviderSpawner.kSupportedAttributesFromSpawnContext.Contains(attributeItem.title))
yield return attributeItem;
}
yield break;
}
foreach (var attributeItem in attributeItems)
{
if (!attributeItem.isReadOnly)
yield return attributeItem;
}
}
private bool CanDrop(IEnumerable<VFXBlockUI> blocks)
{
bool accept = true;
if (blocks.Count() == 0) return false;
foreach (var block in blocks)
{
if (!controller.model.AcceptChild(block.controller.model))
{
accept = false;
break;
}
}
return accept;
}
private void PlaceDragIndicator(int index)
{
var y = GetBlockIndexY(index, false);
m_DragDisplay.RemoveFromHierarchy();
m_DragDisplay.style.top = y;
m_BlockContainer.Add(m_DragDisplay);
}
private void RemoveDragIndicator()
{
if (m_DragDisplay.parent != null)
m_BlockContainer.Remove(m_DragDisplay);
}
bool m_DragStarted;
private float GetBlockIndexY(int index, bool middle)
{
float y = 0;
if (controller.blockControllers.Count == 0)
{
return 0;
}
if (index >= controller.blockControllers.Count)
{
return blocks[controller.blockControllers.Last()].layout.yMax;
}
else if (middle)
{
return blocks[controller.blockControllers[index]].layout.center.y;
}
else
{
y = blocks[controller.blockControllers[index]].layout.yMin;
if (index > 0)
{
y = (y + blocks[controller.blockControllers[index - 1]].layout.yMax) * 0.5f;
}
}
return y;
}
private int GetDragBlockIndex(Vector2 mousePosition)
{
for (int i = 0; i < controller.blockControllers.Count; ++i)
{
float y = GetBlockIndexY(i, true);
if (mousePosition.y < y)
{
return i;
}
}
return controller.blockControllers.Count;
}
private void OnDragUpdated(DragUpdatedEvent evt)
{
Vector2 mousePosition = m_BlockContainer.WorldToLocal(evt.mousePosition);
int blockIndex = GetDragBlockIndex(mousePosition);
if (DragAndDrop.GetGenericData("DragSelection") is List<ISelectable> dragSelection)
{
var blocksUI = dragSelection.OfType<VFXBlockUI>().ToArray();
var dragBlocks = CanDrop(blocksUI);
if (dragBlocks)
{
DragAndDrop.visualMode = evt.ctrlKey ? DragAndDropVisualMode.Copy : DragAndDropVisualMode.Move;
if (!m_DragStarted)
{
// TODO: Do something on first DragUpdated event (initiate drag)
m_DragStarted = true;
AddToClassList("dropping");
}
PlaceDragIndicator(blockIndex);
}
else
{
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
evt.StopPropagation();
}
}
else
{
var references = DragAndDrop.objectReferences.OfType<VisualEffectSubgraphBlock>();
if (references.Any() && (!controller.viewController.model.isSubgraph || !references.Any(t => t.GetResource().GetOrCreateGraph().subgraphDependencies.Contains(controller.viewController.model.subgraph) || t.GetResource() == controller.viewController.model)))
{
var compatibleReferences = references
.Where(x => x != null && x.GetResource().GetOrCreateGraph().children.OfType<VFXBlockSubgraphContext>().First().compatibleContextType.HasFlag(controller.model.contextType));
if (compatibleReferences.Any())
{
DragAndDrop.visualMode = DragAndDropVisualMode.Move;
evt.StopPropagation();
PlaceDragIndicator(blockIndex);
if (!m_DragStarted)
{
// TODO: Do something on first DragUpdated event (initiate drag)
m_DragStarted = true;
AddToClassList("dropping");
}
}
else
{
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
evt.StopPropagation();
}
}
else
{
var attributeItems = GetFirstAncestorOfType<VFXView>().selection.OfType<VFXBlackboardAttributeField>().Select(x => x.attribute).ToArray();
if (HasDroppableAttributeItems(attributeItems))
{
if (!m_DragStarted)
{
// TODO: Do something on first DragUpdated event (initiate drag)
m_DragStarted = true;
AddToClassList("dropping");
}
PlaceDragIndicator(blockIndex);
DragAndDrop.visualMode = DragAndDropVisualMode.Move;
}
else
{
DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
evt.StopPropagation();
}
}
}
}
void OnDragPerform(DragPerformEvent evt)
{
RemoveDragIndicator();
if (DragAndDrop.GetGenericData("DragSelection") is List<ISelectable> dragSelection)
{
Vector2 mousePosition = m_BlockContainer.WorldToLocal(evt.mousePosition);
int blockIndex = GetDragBlockIndex(mousePosition);
var blocksUI = dragSelection.OfType<VFXBlockUI>().ToArray();
var dropBlocks = CanDrop(blocksUI);
if (dropBlocks)
{
BlocksDropped(blockIndex, blocksUI, evt.ctrlKey);
DragAndDrop.AcceptDrag();
evt.StopPropagation();
}
}
else
{
var references = DragAndDrop.objectReferences.OfType<VisualEffectSubgraphBlock>().ToArray();
if (references.Any() && (!controller.viewController.model.isSubgraph || !references.Any(t => t.GetResource().GetOrCreateGraph().subgraphDependencies.Contains(controller.viewController.model.subgraph) || t.GetResource() == controller.viewController.model)))
{
VFXView view = GetFirstAncestorOfType<VFXView>();
foreach (var reference in references)
{
var graph = reference != null ? reference.GetResource().GetOrCreateGraph() : null;
if (graph != null && graph.children.OfType<VFXBlockSubgraphContext>().First().compatibleContextType.HasFlag(controller.model.contextType))
{
DragAndDrop.AcceptDrag();
if (view.HasCustomAttributeConflicts(graph.attributesManager.GetCustomAttributes()))
{
break;
}
Vector2 mousePosition = m_BlockContainer.WorldToLocal(evt.mousePosition);
int blockIndex = GetDragBlockIndex(mousePosition);
VFXBlock newModel = ScriptableObject.CreateInstance<VFXSubgraphBlock>();
newModel.SetSettingValue("m_Subgraph", reference);
UpdateSelectionWithNewBlocks();
controller.AddBlock(blockIndex, newModel);
}
else if (reference != null)
{
Debug.LogWarning($"Could not drag & drop asset '{reference.name}' because it's not supported in a context of type '{controller.model.contextType}'");
}
}
evt.StopPropagation();
}
else
{
var data = DragAndDrop.GetGenericData("DragSelection");
if (data is List<IParameterItem> items)
{
var attributeItems = GetDroppableAttributeItems(items.OfType<AttributeItem>()).ToArray();
if (attributeItems.Length > 0)
{
var mousePosition = m_BlockContainer.WorldToLocal(evt.mousePosition);
var blockIndex = GetDragBlockIndex(mousePosition);
foreach (var attributeItem in attributeItems)
{
var setAttribute = controller.model.contextType != VFXContextType.Spawner
? (VFXBlock)ScriptableObject.CreateInstance<SetAttribute>()
: ScriptableObject.CreateInstance<VFXSpawnerSetAttribute>();
setAttribute.SetSettingValue("attribute", attributeItem.title);
controller.model.AddChild(setAttribute, blockIndex);
}
DragAndDrop.AcceptDrag();
evt.StopPropagation();
}
}
}
}
m_DragStarted = false;
RemoveFromClassList("dropping");
}
private void BlocksDropped(int blockIndex, IEnumerable<VFXBlockUI> draggedBlocks, bool copy)
{
HashSet<VFXContextController> contexts = new HashSet<VFXContextController>();
foreach (var draggedBlock in draggedBlocks)
{
contexts.Add(draggedBlock.context.controller);
}
using (var growContext = new GrowContext(this))
{
controller.BlocksDropped(blockIndex, draggedBlocks.Select(t => t.controller), copy);
foreach (var context in contexts)
{
context.ApplyChanges();
}
}
}
void OnDragExited(EventBase e)
{
// TODO: Do something when current drag is canceled
RemoveDragIndicator();
m_DragStarted = false;
}
private VFXBlockUI InstantiateBlock(VFXBlockController blockController)
{
Profiler.BeginSample("VFXContextUI.InstantiateBlock");
Profiler.BeginSample("VFXContextUI.new VFXBlockUI");
var blockUI = new VFXBlockUI();
Profiler.EndSample();
blockUI.controller = blockController;
blocks[blockController] = blockUI;
Profiler.EndSample();
return blockUI;
}
Dictionary<VFXBlockController, VFXBlockUI> blocks = new Dictionary<VFXBlockController, VFXBlockUI>();
private void RefreshContext()
{
Profiler.BeginSample("VFXContextUI.RefreshContext");
var blockControllers = controller.blockControllers;
int blockControllerCount = blockControllers.Count();
bool somethingChanged = m_BlockContainer.childCount < blockControllerCount || (!m_CanHaveBlocks && m_NoBlock.parent != null);
int cptBlock = 0;
foreach (var child in m_BlockContainer.Children().OfType<VFXBlockUI>())
{
if (!somethingChanged && blockControllerCount > cptBlock && child.controller != blockControllers[cptBlock])
{
somethingChanged = true;
}
cptBlock++;
}
if (somethingChanged || cptBlock != blockControllerCount)
{
VFXView view = GetFirstAncestorOfType<VFXView>();
foreach (var controllerToRemove in blocks.Keys.Except(blockControllers).ToArray())
{
view.RemoveNodeEdges(blocks[controllerToRemove]);
m_BlockContainer.Remove(blocks[controllerToRemove]);
blocks.Remove(controllerToRemove);
}
if (blockControllers.Any() || !m_CanHaveBlocks)
{
m_NoBlock.RemoveFromHierarchy();
}
else if (m_NoBlock.parent == null)
{
m_BlockContainer.Add(m_NoBlock);
}
if (blockControllers.Any())
{
VFXBlockUI prevBlock = null;
var addedBlocks = new List<ISelectable>();
foreach (var blockController in blockControllers)
{
if (!blocks.TryGetValue(blockController, out var blockUI))
{
blockUI = InstantiateBlock(blockController);
m_BlockContainer.Insert(prevBlock == null ? 0 : m_BlockContainer.IndexOf(prevBlock) + 1, blockUI);
if (m_UpdateSelectionWithNewBlocks)
{
addedBlocks.Add(blockUI);
}
//Refresh error can only be called after the block has been instantiated
blockController.model.RefreshErrors();
}
if (prevBlock != null)
blockUI.PlaceInFront(prevBlock);
else
{
blockUI.SendToBack();
blockUI.AddToClassList("first");
}
prevBlock = blockUI;
}
if (addedBlocks.Any())
{
view.ClearSelection();
view.AddRangeToSelection(addedBlocks);
}
m_UpdateSelectionWithNewBlocks = false;
}
}
Profiler.EndSample();
}
Texture2D GetIconForVFXType(VFXDataType type)
{
switch (type)
{
case VFXDataType.SpawnEvent:
return VFXView.LoadImage("Execution");
case VFXDataType.Particle:
return VFXView.LoadImage("Particles");
case VFXDataType.ParticleStrip:
return VFXView.LoadImage("ParticleStrips");
}
return null;
}
internal class GrowContext : IDisposable
{
VFXContextUI m_Context;
float m_PrevSize;
public GrowContext(VFXContextUI context)
{
m_Context = context;
m_PrevSize = context.layout.size.y;
}
void IDisposable.Dispose()
{
VFXView view = m_Context.GetFirstAncestorOfType<VFXView>();
m_Context.controller.ApplyChanges();
m_Context.panel.InternalValidateLayout();
view.PushUnderContext(m_Context, m_Context.layout.size.y - m_PrevSize);
}
}
void AddBlock(Vector2 position, Variant variant)
{
int blockIndex = -1;
var blocks = m_BlockContainer.Query().OfType<VFXBlockUI>().ToList();
for (int i = 0; i < blocks.Count; ++i)
{
Rect worldBounds = blocks[i].worldBound;
if (worldBounds.Contains(position))
{
if (position.y > worldBounds.center.y)
{
blockIndex = i + 1;
}
else
{
blockIndex = i;
}
break;
}
}
using (new GrowContext(this))
{
controller.AddBlock(blockIndex, (VFXBlock)variant.CreateInstance(), true /* freshly created block, should init space */);
}
}
private void OnCreateBlock(DropdownMenuAction evt)
{
Vector2 referencePosition = evt.eventInfo.mousePosition;
OnCreateBlock(referencePosition);
}
public void OnCreateBlock(Vector2 referencePosition)
{
VFXView view = GetFirstAncestorOfType<VFXView>();
Vector2 screenPosition = view.ViewToScreenPosition(referencePosition);
VFXFilterWindow.Show(view, referencePosition, screenPosition, m_BlockProvider);
}
VFXBlockProvider m_BlockProvider = null;
// TODO: Remove, unused except for debugging
// Declare new USS rect-color and use it
protected override void OnCustomStyleResolved(ICustomStyle styles)
{
base.OnCustomStyleResolved(styles);
styles.TryGetValue(RectColorProperty, out m_RectColor);
}
// TODO: Remove, unused except for debugging
Color m_RectColor = Color.magenta;
Color rectColor { get { return m_RectColor; } }
public IEnumerable<VFXBlockUI> GetAllBlocks()
{
foreach (VFXBlockUI block in m_BlockContainer.Children().OfType<VFXBlockUI>())
{
yield return block;
}
}
public IEnumerable<VFXFlowAnchor> GetFlowAnchors(bool input, bool output)
{
if (input)
foreach (VFXFlowAnchor anchor in m_FlowInputConnectorContainer.Children())
{
yield return anchor;
}
if (output)
foreach (VFXFlowAnchor anchor in m_FlowOutputConnectorContainer.Children())
{
yield return anchor;
}
}
private class VFXContextOnlyVFXNodeProvider : VFXNodeProvider
{
public VFXContextOnlyVFXNodeProvider(VFXViewController controller, Action<Variant, Vector2> onAddBlock, Func<IVFXModelDescriptor, bool> filter) :
base(controller, onAddBlock, filter, new Type[] { typeof(VFXContext) })
{
}
}
bool ProviderFilter(IVFXModelDescriptor descriptor)
{
if (!descriptor.modelType.IsSubclassOf(typeof(VFXAbstractParticleOutput)))
return false;
var toContext = (VFXContext)descriptor.unTypedModel;
foreach (var links in controller.model.inputFlowSlot.Select((t, i) => new { index = i, links = t.link }))
{
foreach (var link in links.links)
{
if (!VFXContext.CanLink(link.context, toContext, links.index, link.slotIndex))
return false;
}
}
return toContext.contextType == VFXContextType.Output;
}
void OnConvertContext(DropdownMenuAction action)
{
VFXView view = this.GetFirstAncestorOfType<VFXView>();
VFXFilterWindow.Show(view, action.eventInfo.mousePosition, view.ViewToScreenPosition(action.eventInfo.mousePosition), new VFXContextOnlyVFXNodeProvider(view.controller, ConvertContext, ProviderFilter));
}
void ConvertContext(Variant variant, Vector2 mPos)
{
VFXView view = GetFirstAncestorOfType<VFXView>();
VFXViewController viewController = controller.viewController;
if (view == null) return;
mPos = view.contentViewContainer.ChangeCoordinatesTo(view, controller.position);
var newNodeController = view.AddNode(variant, mPos);
var newContextController = newNodeController as VFXContextController;
newContextController.model.label = controller.model.label;
//transfer blocks
foreach (var block in controller.model.children.ToArray()) // To array needed as the IEnumerable content will change
newContextController.AddBlock(-1, block);
//transfer settings
List<KeyValuePair<string, object>> settings = new();
foreach (var setting in newContextController.model.GetSettings(true))
{
if (!newContextController.model.CanTransferSetting(setting))
continue;
if (!setting.valid || setting.field.GetCustomAttributes(typeof(VFXSettingAttribute), true).Length == 0)
continue;
var sourceSetting = controller.model.GetSetting(setting.name);
if (!sourceSetting.valid)
continue;
object value;
if (VFXConverter.TryConvertTo(sourceSetting.value, setting.field.FieldType, out value))
settings.Add(new(setting.field.Name, value));
}
newContextController.model.SetSettingValues(settings);
//transfer flow edges
if (controller.flowInputAnchors.Count == 1)
{
foreach (var output in controller.flowInputAnchors[0].connections.Select(t => t.output).ToArray())
newContextController.model.LinkFrom(output.context.model, output.slotIndex);
}
// Apply the slot changes that can be the result of settings changes
newContextController.ApplyChanges();
VFXSlot firstTextureSlot = null;
//transfer master slot values
foreach (var slot in newContextController.model.inputSlots)
{
VFXSlot mySlot = controller.model.inputSlots.FirstOrDefault(t => t.name == slot.name);
if (mySlot == null)
{
if (slot.valueType == VFXValueType.Texture2D && firstTextureSlot == null)
firstTextureSlot = slot;
continue;
}
object value;
if (VFXConverter.TryConvertTo(mySlot.value, slot.property.type, out value))
slot.value = value;
}
//Hack to copy the first texture in the first texture slot if not found by name
if (firstTextureSlot != null)
{
VFXSlot mySlot = controller.model.inputSlots.FirstOrDefault(t => t.valueType == VFXValueType.Texture2D);
if (mySlot != null)
firstTextureSlot.value = mySlot.value;
}
foreach (var anchor in newContextController.inputPorts)
{
string path = anchor.path;
var myAnchor = controller.inputPorts.FirstOrDefault(t => t.path == path);
if (myAnchor == null || !myAnchor.HasLink())
continue;
//There should be only one
var output = myAnchor.connections.First().output;
viewController.CreateLink(anchor, output);
}
// Apply the change so that it won't unlink the blocks links
controller.ApplyChanges();
viewController.RemoveElement(controller);
}
public override void BuildContextualMenu(ContextualMenuPopulateEvent evt)
{
if (evt.target is VFXContextUI || evt.target is VFXBlockUI)
{
if (m_CanHaveBlocks)
{
evt.menu.InsertAction(0, "Create Block", OnCreateBlock, e => DropdownMenuAction.Status.Normal);
evt.menu.AppendSeparator();
}
}
if (evt.target is VFXContextUI && controller.model is VFXAbstractParticleOutput)
{
evt.menu.InsertAction(1, "Convert Output", OnConvertContext, e => DropdownMenuAction.Status.Normal);
}
}
void OnTitleMouseDown(MouseDownEvent e)
{
if (e.clickCount == 2)
{
OnRename();
e.StopPropagation();
focusController.IgnoreEvent(e);
}
}
public void OnRename()
{
m_Label.RemoveFromClassList("empty");
m_Label.style.display = DisplayStyle.None;
m_TextField.value = m_Label.text;