-
Notifications
You must be signed in to change notification settings - Fork 408
/
Copy pathBaseGraphView.cs
1472 lines (1205 loc) · 42.2 KB
/
BaseGraphView.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.UIElements;
using UnityEngine.UIElements;
using UnityEditor.Experimental.GraphView;
using System.Linq;
using System;
using UnityEditor.SceneManagement;
using System.Reflection;
using Status = UnityEngine.UIElements.DropdownMenuAction.Status;
using Object = UnityEngine.Object;
namespace GraphProcessor
{
/// <summary>
/// Base class to write a custom view for a node
/// </summary>
public class BaseGraphView : GraphView, IDisposable
{
public delegate void ComputeOrderUpdatedDelegate();
public delegate void NodeDuplicatedDelegate(BaseNode duplicatedNode, BaseNode newNode);
/// <summary>
/// Graph that owns of the node
/// </summary>
public BaseGraph graph;
/// <summary>
/// Connector listener that will create the edges between ports
/// </summary>
public BaseEdgeConnectorListener connectorListener;
/// <summary>
/// List of all node views in the graph
/// </summary>
/// <typeparam name="BaseNodeView"></typeparam>
/// <returns></returns>
public List< BaseNodeView > nodeViews = new List< BaseNodeView >();
/// <summary>
/// Dictionary of the node views accessed view the node instance, faster than a Find in the node view list
/// </summary>
/// <typeparam name="BaseNode"></typeparam>
/// <typeparam name="BaseNodeView"></typeparam>
/// <returns></returns>
public Dictionary< BaseNode, BaseNodeView > nodeViewsPerNode = new Dictionary< BaseNode, BaseNodeView >();
/// <summary>
/// List of all edge views in the graph
/// </summary>
/// <typeparam name="EdgeView"></typeparam>
/// <returns></returns>
public List< EdgeView > edgeViews = new List< EdgeView >();
/// <summary>
/// List of all group views in the graph
/// </summary>
/// <typeparam name="GroupView"></typeparam>
/// <returns></returns>
public List< GroupView > groupViews = new List< GroupView >();
#if UNITY_2020_1_OR_NEWER
/// <summary>
/// List of all sticky note views in the graph
/// </summary>
/// <typeparam name="StickyNoteView"></typeparam>
/// <returns></returns>
public List< StickyNoteView > stickyNoteViews = new List<StickyNoteView>();
#endif
/// <summary>
/// List of all stack node views in the graph
/// </summary>
/// <typeparam name="BaseStackNodeView"></typeparam>
/// <returns></returns>
public List< BaseStackNodeView > stackNodeViews = new List< BaseStackNodeView >();
Dictionary< Type, PinnedElementView > pinnedElements = new Dictionary< Type, PinnedElementView >();
CreateNodeMenuWindow createNodeMenu;
/// <summary>
/// Triggered just after the graph is initialized
/// </summary>
public event Action initialized;
/// <summary>
/// Triggered just after the compute order of the graph is updated
/// </summary>
public event ComputeOrderUpdatedDelegate computeOrderUpdated;
// Safe event relay from BaseGraph (safe because you are sure to always point on a valid BaseGraph
// when one of these events is called), a graph switch can occur between two call tho
/// <summary>
/// Same event than BaseGraph.onExposedParameterListChanged
/// Safe event (not triggered in case the graph is null).
/// </summary>
public event Action onExposedParameterListChanged;
/// <summary>
/// Same event than BaseGraph.onExposedParameterModified
/// Safe event (not triggered in case the graph is null).
/// </summary>
public event Action< ExposedParameter > onExposedParameterModified;
/// <summary>
/// Triggered when a node is duplicated (crt-d) or copy-pasted (crtl-c/crtl-v)
/// </summary>
public event NodeDuplicatedDelegate nodeDuplicated;
/// <summary>
/// Object to handle nodes that shows their UI in the inspector.
/// </summary>
[SerializeField]
protected NodeInspectorObject nodeInspector
{
get
{
if (graph.nodeInspectorReference == null)
graph.nodeInspectorReference = CreateNodeInspectorObject();
return graph.nodeInspectorReference as NodeInspectorObject;
}
}
/// <summary>
/// Workaround object for creating exposed parameter property fields.
/// </summary>
public ExposedParameterFieldFactory exposedParameterFactory { get; private set; }
public SerializedObject serializedGraph { get; private set; }
Dictionary<Type, (Type nodeType, MethodInfo initalizeNodeFromObject)> nodeTypePerCreateAssetType = new Dictionary<Type, (Type, MethodInfo)>();
public BaseGraphView(EditorWindow window)
{
serializeGraphElements = SerializeGraphElementsCallback;
canPasteSerializedData = CanPasteSerializedDataCallback;
unserializeAndPaste = UnserializeAndPasteCallback;
graphViewChanged = GraphViewChangedCallback;
viewTransformChanged = ViewTransformChangedCallback;
elementResized = ElementResizedCallback;
RegisterCallback< KeyDownEvent >(KeyDownCallback);
RegisterCallback< DragPerformEvent >(DragPerformedCallback);
RegisterCallback< DragUpdatedEvent >(DragUpdatedCallback);
RegisterCallback< MouseDownEvent >(MouseDownCallback);
RegisterCallback< MouseUpEvent >(MouseUpCallback);
InitializeManipulators();
SetupZoom(0.05f, 2f);
Undo.undoRedoPerformed += ReloadView;
createNodeMenu = ScriptableObject.CreateInstance< CreateNodeMenuWindow >();
createNodeMenu.Initialize(this, window);
this.StretchToParentSize();
}
protected virtual NodeInspectorObject CreateNodeInspectorObject()
{
var inspector = ScriptableObject.CreateInstance<NodeInspectorObject>();
inspector.name = "Node Inspector";
inspector.hideFlags = HideFlags.HideAndDontSave ^ HideFlags.NotEditable;
return inspector;
}
#region Callbacks
protected override bool canCopySelection
{
get { return selection.Any(e => e is BaseNodeView || e is GroupView); }
}
protected override bool canCutSelection
{
get { return selection.Any(e => e is BaseNodeView || e is GroupView); }
}
string SerializeGraphElementsCallback(IEnumerable<GraphElement> elements)
{
var data = new CopyPasteHelper();
foreach (BaseNodeView nodeView in elements.Where(e => e is BaseNodeView))
{
data.copiedNodes.Add(JsonSerializer.SerializeNode(nodeView.nodeTarget));
foreach (var port in nodeView.nodeTarget.GetAllPorts())
{
if (port.portData.vertical)
{
foreach (var edge in port.GetEdges())
data.copiedEdges.Add(JsonSerializer.Serialize(edge));
}
}
}
foreach (GroupView groupView in elements.Where(e => e is GroupView))
data.copiedGroups.Add(JsonSerializer.Serialize(groupView.group));
foreach (EdgeView edgeView in elements.Where(e => e is EdgeView))
data.copiedEdges.Add(JsonSerializer.Serialize(edgeView.serializedEdge));
ClearSelection();
return JsonUtility.ToJson(data, true);
}
bool CanPasteSerializedDataCallback(string serializedData)
{
try {
return JsonUtility.FromJson(serializedData, typeof(CopyPasteHelper)) != null;
} catch {
return false;
}
}
void UnserializeAndPasteCallback(string operationName, string serializedData)
{
var data = JsonUtility.FromJson< CopyPasteHelper >(serializedData);
RegisterCompleteObjectUndo(operationName);
Dictionary<string, BaseNode> copiedNodesMap = new Dictionary<string, BaseNode>();
var unserializedGroups = data.copiedGroups.Select(g => JsonSerializer.Deserialize<Group>(g)).ToList();
foreach (var serializedNode in data.copiedNodes)
{
var node = JsonSerializer.DeserializeNode(serializedNode);
if (node == null)
continue ;
string sourceGUID = node.GUID;
graph.nodesPerGUID.TryGetValue(sourceGUID, out var sourceNode);
//Call OnNodeCreated on the new fresh copied node
node.createdFromDuplication = true;
node.createdWithinGroup = unserializedGroups.Any(g => g.innerNodeGUIDs.Contains(sourceGUID));
node.OnNodeCreated();
//And move a bit the new node
node.position.position += new Vector2(20, 20);
var newNodeView = AddNode(node);
// If the nodes were copied from another graph, then the source is null
if (sourceNode != null)
nodeDuplicated?.Invoke(sourceNode, node);
copiedNodesMap[sourceGUID] = node;
//Select the new node
AddToSelection(nodeViewsPerNode[node]);
}
foreach (var group in unserializedGroups)
{
//Same than for node
group.OnCreated();
// try to centre the created node in the screen
group.position.position += new Vector2(20, 20);
var oldGUIDList = group.innerNodeGUIDs.ToList();
group.innerNodeGUIDs.Clear();
foreach (var guid in oldGUIDList)
{
graph.nodesPerGUID.TryGetValue(guid, out var node);
// In case group was copied from another graph
if (node == null)
{
copiedNodesMap.TryGetValue(guid, out node);
group.innerNodeGUIDs.Add(node.GUID);
}
else
{
group.innerNodeGUIDs.Add(copiedNodesMap[guid].GUID);
}
}
AddGroup(group);
}
foreach (var serializedEdge in data.copiedEdges)
{
var edge = JsonSerializer.Deserialize<SerializableEdge>(serializedEdge);
edge.Deserialize();
// Find port of new nodes:
copiedNodesMap.TryGetValue(edge.inputNode.GUID, out var oldInputNode);
copiedNodesMap.TryGetValue(edge.outputNode.GUID, out var oldOutputNode);
// We avoid to break the graph by replacing unique connections:
if (oldInputNode == null && !edge.inputPort.portData.acceptMultipleEdges || !edge.outputPort.portData.acceptMultipleEdges)
continue;
oldInputNode = oldInputNode ?? edge.inputNode;
oldOutputNode = oldOutputNode ?? edge.outputNode;
var inputPort = oldInputNode.GetPort(edge.inputPort.fieldName, edge.inputPortIdentifier);
var outputPort = oldOutputNode.GetPort(edge.outputPort.fieldName, edge.outputPortIdentifier);
var newEdge = SerializableEdge.CreateNewEdge(graph, inputPort, outputPort);
if (nodeViewsPerNode.ContainsKey(oldInputNode) && nodeViewsPerNode.ContainsKey(oldOutputNode))
{
var edgeView = CreateEdgeView();
edgeView.userData = newEdge;
edgeView.input = nodeViewsPerNode[oldInputNode].GetPortViewFromFieldName(newEdge.inputFieldName, newEdge.inputPortIdentifier);
edgeView.output = nodeViewsPerNode[oldOutputNode].GetPortViewFromFieldName(newEdge.outputFieldName, newEdge.outputPortIdentifier);
Connect(edgeView);
}
}
}
public virtual EdgeView CreateEdgeView()
{
return new EdgeView();
}
GraphViewChange GraphViewChangedCallback(GraphViewChange changes)
{
if (changes.elementsToRemove != null)
{
RegisterCompleteObjectUndo("Remove Graph Elements");
// Destroy priority of objects
// We need nodes to be destroyed first because we can have a destroy operation that uses node connections
changes.elementsToRemove.Sort((e1, e2) => {
int GetPriority(GraphElement e)
{
if (e is BaseNodeView)
return 0;
else
return 1;
}
return GetPriority(e1).CompareTo(GetPriority(e2));
});
//Handle ourselves the edge and node remove
changes.elementsToRemove.RemoveAll(e => {
switch (e)
{
case EdgeView edge:
Disconnect(edge);
return true;
case BaseNodeView nodeView:
// For vertical nodes, we need to delete them ourselves as it's not handled by GraphView
foreach (var pv in nodeView.inputPortViews.Concat(nodeView.outputPortViews))
if (pv.orientation == Orientation.Vertical)
foreach (var edge in pv.GetEdges().ToList())
Disconnect(edge);
nodeInspector.NodeViewRemoved(nodeView);
ExceptionToLog.Call(() => nodeView.OnRemoved());
graph.RemoveNode(nodeView.nodeTarget);
UpdateSerializedProperties();
RemoveElement(nodeView);
if (Selection.activeObject == nodeInspector)
UpdateNodeInspectorSelection();
SyncSerializedPropertyPathes();
return true;
case GroupView group:
graph.RemoveGroup(group.group);
UpdateSerializedProperties();
RemoveElement(group);
return true;
case ExposedParameterFieldView blackboardField:
graph.RemoveExposedParameter(blackboardField.parameter);
UpdateSerializedProperties();
return true;
case BaseStackNodeView stackNodeView:
graph.RemoveStackNode(stackNodeView.stackNode);
UpdateSerializedProperties();
RemoveElement(stackNodeView);
return true;
#if UNITY_2020_1_OR_NEWER
case StickyNoteView stickyNoteView:
graph.RemoveStickyNote(stickyNoteView.note);
UpdateSerializedProperties();
RemoveElement(stickyNoteView);
return true;
#endif
}
return false;
});
}
return changes;
}
void GraphChangesCallback(GraphChanges changes)
{
if (changes.removedEdge != null)
{
var edge = edgeViews.FirstOrDefault(e => e.serializedEdge == changes.removedEdge);
DisconnectView(edge);
}
}
void ViewTransformChangedCallback(GraphView view)
{
if (graph != null)
{
graph.position = viewTransform.position;
graph.scale = viewTransform.scale;
}
}
void ElementResizedCallback(VisualElement elem)
{
var groupView = elem as GroupView;
if (groupView != null)
groupView.group.size = groupView.GetPosition().size;
}
public override List< Port > GetCompatiblePorts(Port startPort, NodeAdapter nodeAdapter)
{
var compatiblePorts = new List< Port >();
compatiblePorts.AddRange(ports.Where(p => {
var portView = p as PortView;
if (portView.owner == (startPort as PortView).owner)
return false;
if (p.direction == startPort.direction)
return false;
//Check for type assignability
if (!BaseGraph.TypesAreConnectable(startPort.portType, p.portType))
return false;
//Check if the edge already exists
if (portView.GetEdges().Any(e => e.input == startPort || e.output == startPort))
return false;
return true;
}));
return compatiblePorts;
}
/// <summary>
/// Build the contextual menu shown when right clicking inside the graph view
/// </summary>
/// <param name="evt"></param>
public override void BuildContextualMenu(ContextualMenuPopulateEvent evt)
{
base.BuildContextualMenu(evt);
BuildGroupContextualMenu(evt, 1);
BuildStickyNoteContextualMenu(evt, 2);
BuildViewContextualMenu(evt);
BuildSelectAssetContextualMenu(evt);
BuildSaveAssetContextualMenu(evt);
BuildHelpContextualMenu(evt);
}
/// <summary>
/// Add the New Group entry to the context menu
/// </summary>
/// <param name="evt"></param>
protected virtual void BuildGroupContextualMenu(ContextualMenuPopulateEvent evt, int menuPosition = -1)
{
if (menuPosition == -1)
menuPosition = evt.menu.MenuItems().Count;
Vector2 position = (evt.currentTarget as VisualElement).ChangeCoordinatesTo(contentViewContainer, evt.localMousePosition);
evt.menu.InsertAction(menuPosition, "Create Group", (e) => AddSelectionsToGroup(AddGroup(new Group("Create Group", position))), DropdownMenuAction.AlwaysEnabled);
}
/// <summary>
/// -Add the New Sticky Note entry to the context menu
/// </summary>
/// <param name="evt"></param>
protected virtual void BuildStickyNoteContextualMenu(ContextualMenuPopulateEvent evt, int menuPosition = -1)
{
if (menuPosition == -1)
menuPosition = evt.menu.MenuItems().Count;
#if UNITY_2020_1_OR_NEWER
Vector2 position = (evt.currentTarget as VisualElement).ChangeCoordinatesTo(contentViewContainer, evt.localMousePosition);
evt.menu.InsertAction(menuPosition, "Create Sticky Note", (e) => AddStickyNote(new StickyNote("Create Note", position)), DropdownMenuAction.AlwaysEnabled);
#endif
}
/// <summary>
/// Add the View entry to the context menu
/// </summary>
/// <param name="evt"></param>
protected virtual void BuildViewContextualMenu(ContextualMenuPopulateEvent evt)
{
evt.menu.AppendAction("View/Processor", (e) => ToggleView< ProcessorView >(), (e) => GetPinnedElementStatus< ProcessorView >());
}
/// <summary>
/// Add the Select Asset entry to the context menu
/// </summary>
/// <param name="evt"></param>
protected virtual void BuildSelectAssetContextualMenu(ContextualMenuPopulateEvent evt)
{
evt.menu.AppendAction("Select Asset", (e) => EditorGUIUtility.PingObject(graph), DropdownMenuAction.AlwaysEnabled);
}
/// <summary>
/// Add the Save Asset entry to the context menu
/// </summary>
/// <param name="evt"></param>
protected virtual void BuildSaveAssetContextualMenu(ContextualMenuPopulateEvent evt)
{
evt.menu.AppendAction("Save Asset", (e) => {
EditorUtility.SetDirty(graph);
AssetDatabase.SaveAssets();
}, DropdownMenuAction.AlwaysEnabled);
}
/// <summary>
/// Add the Help entry to the context menu
/// </summary>
/// <param name="evt"></param>
protected void BuildHelpContextualMenu(ContextualMenuPopulateEvent evt)
{
evt.menu.AppendAction("Help/Reset Pinned Windows", e => {
foreach (var kp in pinnedElements)
kp.Value.ResetPosition();
});
}
protected virtual void KeyDownCallback(KeyDownEvent e)
{
if (e.keyCode == KeyCode.S && e.commandKey)
{
SaveGraphToDisk();
e.StopPropagation();
}
else if(nodeViews.Count > 0 && e.commandKey && e.altKey)
{
// Node Aligning shortcuts
switch(e.keyCode)
{
case KeyCode.LeftArrow:
nodeViews[0].AlignToLeft();
e.StopPropagation();
break;
case KeyCode.RightArrow:
nodeViews[0].AlignToRight();
e.StopPropagation();
break;
case KeyCode.UpArrow:
nodeViews[0].AlignToTop();
e.StopPropagation();
break;
case KeyCode.DownArrow:
nodeViews[0].AlignToBottom();
e.StopPropagation();
break;
case KeyCode.C:
nodeViews[0].AlignToCenter();
e.StopPropagation();
break;
case KeyCode.M:
nodeViews[0].AlignToMiddle();
e.StopPropagation();
break;
}
}
}
void MouseUpCallback(MouseUpEvent e)
{
schedule.Execute(() => {
if (DoesSelectionContainsInspectorNodes())
UpdateNodeInspectorSelection();
}).ExecuteLater(1);
}
void MouseDownCallback(MouseDownEvent e)
{
// When left clicking on the graph (not a node or something else)
if (e.button == 0)
{
// Close all settings windows:
nodeViews.ForEach(v => v.CloseSettings());
}
if (DoesSelectionContainsInspectorNodes())
UpdateNodeInspectorSelection();
}
bool DoesSelectionContainsInspectorNodes()
{
var selectedNodes = selection.Where(s => s is BaseNodeView).ToList();
var selectedNodesNotInInspector = selectedNodes.Except(nodeInspector.selectedNodes).ToList();
var nodeInInspectorWithoutSelectedNodes = nodeInspector.selectedNodes.Except(selectedNodes).ToList();
return selectedNodesNotInInspector.Any() || nodeInInspectorWithoutSelectedNodes.Any();
}
void DragPerformedCallback(DragPerformEvent e)
{
var mousePos = (e.currentTarget as VisualElement).ChangeCoordinatesTo(contentViewContainer, e.localMousePosition);
var dragData = DragAndDrop.GetGenericData("DragSelection") as List< ISelectable >;
// Drag and Drop for elements inside the graph
if (dragData != null)
{
var exposedParameterFieldViews = dragData.OfType<ExposedParameterFieldView>();
if (exposedParameterFieldViews.Any())
{
foreach (var paramFieldView in exposedParameterFieldViews)
{
RegisterCompleteObjectUndo("Create Parameter Node");
var paramNode = BaseNode.CreateFromType< ParameterNode >(mousePos);
paramNode.parameterGUID = paramFieldView.parameter.guid;
AddNode(paramNode);
}
}
}
// External objects drag and drop
if (DragAndDrop.objectReferences.Length > 0)
{
RegisterCompleteObjectUndo("Create Node From Object(s)");
foreach (var obj in DragAndDrop.objectReferences)
{
var objectType = obj.GetType();
foreach (var kp in nodeTypePerCreateAssetType)
{
if (kp.Key.IsAssignableFrom(objectType))
{
try
{
var node = BaseNode.CreateFromType(kp.Value.nodeType, mousePos);
if ((bool)kp.Value.initalizeNodeFromObject.Invoke(node, new []{obj}))
{
AddNode(node);
break;
}
}
catch (Exception exception)
{
Debug.LogException(exception);
}
}
}
}
}
}
void DragUpdatedCallback(DragUpdatedEvent e)
{
var dragData = DragAndDrop.GetGenericData("DragSelection") as List<ISelectable>;
var dragObjects = DragAndDrop.objectReferences;
bool dragging = false;
if (dragData != null)
{
// Handle drag from exposed parameter view
if (dragData.OfType<ExposedParameterFieldView>().Any())
{
dragging = true;
}
}
if (dragObjects.Length > 0)
dragging = true;
if (dragging)
DragAndDrop.visualMode = DragAndDropVisualMode.Generic;
UpdateNodeInspectorSelection();
}
#endregion
#region Initialization
void ReloadView()
{
// Force the graph to reload his data (Undo have updated the serialized properties of the graph
// so the one that are not serialized need to be synchronized)
graph.Deserialize();
// Get selected nodes
var selectedNodeGUIDs = new List<string>();
foreach (var e in selection)
{
if (e is BaseNodeView v && this.Contains(v))
selectedNodeGUIDs.Add(v.nodeTarget.GUID);
}
// Remove everything
RemoveNodeViews();
RemoveEdges();
RemoveGroups();
#if UNITY_2020_1_OR_NEWER
RemoveStrickyNotes();
#endif
RemoveStackNodeViews();
UpdateSerializedProperties();
// And re-add with new up to date datas
InitializeNodeViews();
InitializeEdgeViews();
InitializeGroups();
InitializeStickyNotes();
InitializeStackNodes();
Reload();
UpdateComputeOrder();
// Restore selection after re-creating all views
// selection = nodeViews.Where(v => selectedNodeGUIDs.Contains(v.nodeTarget.GUID)).Select(v => v as ISelectable).ToList();
foreach (var guid in selectedNodeGUIDs)
{
AddToSelection(nodeViews.FirstOrDefault(n => n.nodeTarget.GUID == guid));
}
UpdateNodeInspectorSelection();
}
public void Initialize(BaseGraph graph)
{
if (this.graph != null)
{
SaveGraphToDisk();
// Close pinned windows from old graph:
ClearGraphElements();
NodeProvider.UnloadGraph(graph);
}
this.graph = graph;
exposedParameterFactory = new ExposedParameterFieldFactory(graph);
UpdateSerializedProperties();
connectorListener = CreateEdgeConnectorListener();
// When pressing ctrl-s, we save the graph
EditorSceneManager.sceneSaved += _ => SaveGraphToDisk();
RegisterCallback<KeyDownEvent>(e => {
if (e.keyCode == KeyCode.S && e.actionKey)
SaveGraphToDisk();
});
ClearGraphElements();
InitializeGraphView();
InitializeNodeViews();
InitializeEdgeViews();
InitializeViews();
InitializeGroups();
InitializeStickyNotes();
InitializeStackNodes();
initialized?.Invoke();
UpdateComputeOrder();
InitializeView();
NodeProvider.LoadGraph(graph);
// Register the nodes that can be created from assets
foreach (var nodeInfo in NodeProvider.GetNodeMenuEntries(graph))
{
var interfaces = nodeInfo.type.GetInterfaces();
var exceptInheritedInterfaces = interfaces.Except(interfaces.SelectMany(t => t.GetInterfaces()));
foreach (var i in exceptInheritedInterfaces)
{
if (i.IsGenericType && i.GetGenericTypeDefinition() == typeof(ICreateNodeFrom<>))
{
var genericArgumentType = i.GetGenericArguments()[0];
var initializeFunction = nodeInfo.type.GetMethod(
nameof(ICreateNodeFrom<Object>.InitializeNodeFromObject),
BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance,
null, new Type[]{ genericArgumentType}, null
);
// We only add the type that implements the interface, not it's children
if (initializeFunction.DeclaringType == nodeInfo.type)
nodeTypePerCreateAssetType[genericArgumentType] = (nodeInfo.type, initializeFunction);
}
}
}
}
public void ClearGraphElements()
{
RemoveGroups();
RemoveNodeViews();
RemoveEdges();
RemoveStackNodeViews();
RemovePinnedElementViews();
#if UNITY_2020_1_OR_NEWER
RemoveStrickyNotes();
#endif
}
void UpdateSerializedProperties()
{
if(graph != null)
serializedGraph = new SerializedObject(graph);
}
/// <summary>
/// Allow you to create your own edge connector listener
/// </summary>
/// <returns></returns>
protected virtual BaseEdgeConnectorListener CreateEdgeConnectorListener()
=> new BaseEdgeConnectorListener(this);
void InitializeGraphView()
{
graph.onExposedParameterListChanged += OnExposedParameterListChanged;
graph.onExposedParameterModified += (s) => onExposedParameterModified?.Invoke(s);
graph.onGraphChanges += GraphChangesCallback;
viewTransform.position = graph.position;
viewTransform.scale = graph.scale;
nodeCreationRequest = (c) => SearchWindow.Open(new SearchWindowContext(c.screenMousePosition), createNodeMenu);
}
void OnExposedParameterListChanged()
{
UpdateSerializedProperties();
onExposedParameterListChanged?.Invoke();
}
void InitializeNodeViews()
{
graph.nodes.RemoveAll(n => n == null);
foreach (var node in graph.nodes)
{
var v = AddNodeView(node);
}
}
void InitializeEdgeViews()
{
// Sanitize edges in case a node broke something while loading
graph.edges.RemoveAll(edge => edge == null || edge.inputNode == null || edge.outputNode == null);
foreach (var serializedEdge in graph.edges)
{
nodeViewsPerNode.TryGetValue(serializedEdge.inputNode, out var inputNodeView);
nodeViewsPerNode.TryGetValue(serializedEdge.outputNode, out var outputNodeView);
if (inputNodeView == null || outputNodeView == null)
continue;
var edgeView = CreateEdgeView();
edgeView.userData = serializedEdge;
edgeView.input = inputNodeView.GetPortViewFromFieldName(serializedEdge.inputFieldName, serializedEdge.inputPortIdentifier);
edgeView.output = outputNodeView.GetPortViewFromFieldName(serializedEdge.outputFieldName, serializedEdge.outputPortIdentifier);
ConnectView(edgeView);
}
}
void InitializeViews()
{
foreach (var pinnedElement in graph.pinnedElements)
{
if (pinnedElement.opened)
OpenPinned(pinnedElement.editorType.type);
}
}
void InitializeGroups()
{
foreach (var group in graph.groups)
AddGroupView(group);
}
void InitializeStickyNotes()
{
#if UNITY_2020_1_OR_NEWER
foreach (var group in graph.stickyNotes)
AddStickyNoteView(group);
#endif
}
void InitializeStackNodes()
{
foreach (var stackNode in graph.stackNodes)
AddStackNodeView(stackNode);
}
protected virtual void InitializeManipulators()
{
this.AddManipulator(new ContentDragger());
this.AddManipulator(new SelectionDragger());
this.AddManipulator(new RectangleSelector());
}
protected virtual void Reload() {}
#endregion
#region Graph content modification
public void UpdateNodeInspectorSelection()
{
if (nodeInspector.previouslySelectedObject != Selection.activeObject)
nodeInspector.previouslySelectedObject = Selection.activeObject;
HashSet<BaseNodeView> selectedNodeViews = new HashSet<BaseNodeView>();
nodeInspector.selectedNodes.Clear();
foreach (var e in selection)
{
if (e is BaseNodeView v && this.Contains(v) && v.nodeTarget.needsInspector)
selectedNodeViews.Add(v);
}
nodeInspector.UpdateSelectedNodes(selectedNodeViews);
if (Selection.activeObject != nodeInspector && selectedNodeViews.Count > 0)
Selection.activeObject = nodeInspector;
}
public BaseNodeView AddNode(BaseNode node)
{
// This will initialize the node using the graph instance
graph.AddNode(node);
UpdateSerializedProperties();
var view = AddNodeView(node);
// Call create after the node have been initialized
ExceptionToLog.Call(() => view.OnCreated());
UpdateComputeOrder();
return view;
}
public BaseNodeView AddNodeView(BaseNode node)
{
var viewType = NodeProvider.GetNodeViewTypeFromType(node.GetType());
if (viewType == null)
viewType = typeof(BaseNodeView);
var baseNodeView = Activator.CreateInstance(viewType) as BaseNodeView;
baseNodeView.Initialize(this, node);
AddElement(baseNodeView);
nodeViews.Add(baseNodeView);
nodeViewsPerNode[node] = baseNodeView;
return baseNodeView;
}
public void RemoveNode(BaseNode node)
{
var view = nodeViewsPerNode[node];
RemoveNodeView(view);
graph.RemoveNode(node);
}
public void RemoveNodeView(BaseNodeView nodeView)
{
RemoveElement(nodeView);
nodeViews.Remove(nodeView);
nodeViewsPerNode.Remove(nodeView.nodeTarget);
}
void RemoveNodeViews()
{
foreach (var nodeView in nodeViews)
RemoveElement(nodeView);
nodeViews.Clear();
nodeViewsPerNode.Clear();
}
void RemoveStackNodeViews()
{
foreach (var stackView in stackNodeViews)
RemoveElement(stackView);
stackNodeViews.Clear();
}
void RemovePinnedElementViews()
{
foreach (var pinnedView in pinnedElements.Values)
{