-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlowNode.cs
1197 lines (969 loc) · 42.6 KB
/
FlowNode.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
#if UNITY_EDITOR
using UnityEditor;
#endif
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using NodeCanvas.Framework;
using NodeCanvas;
using ParadoxNotion;
using ParadoxNotion.Design;
using UnityEngine;
using FlowCanvas.Nodes;
namespace FlowCanvas{
public interface IMultiPortNode{
int portCount{get;set;}
}
///The base node class for FlowGraph systems
abstract public class FlowNode : Node, ISerializationCallbackReceiver {
[AttributeUsage(AttributeTargets.Class)]//helper attribute for context menu
protected class ContextDefinedInputsAttribute : Attribute{
public Type[] types;
public ContextDefinedInputsAttribute(params Type[] types){
this.types = types;
}
}
[AttributeUsage(AttributeTargets.Class)]//helper attribute for context menu
protected class ContextDefinedOutputsAttribute : Attribute{
public Type[] types;
public ContextDefinedOutputsAttribute(params Type[] types){
this.types = types;
}
}
public override bool isPortDependByGraph
{
get
{
return false;
}
}
[SerializeField] //The only thing we really need to serialize port wise, are the input port values that has been set by the user
private Dictionary<string, object> _inputPortValues;
private Dictionary<string, Port> inputPorts = new Dictionary<string, Port>( StringComparer.Ordinal );
private Dictionary<string, Port> outputPorts = new Dictionary<string, Port>( StringComparer.Ordinal );
sealed public override int maxInConnections{ get {return -1;} }
sealed public override int maxOutConnections{ get {return -1;} }
sealed public override bool allowAsPrime{ get {return false;} }
sealed public override Type outConnectionType{ get {return typeof(BinderConnection);} }
sealed public override bool showCommentsBottom{ get{return true;}}
///Store the changed input port values.
void ISerializationCallbackReceiver.OnBeforeSerialize(){
if (_inputPortValues == null){ _inputPortValues = new Dictionary<string, object>(); }
foreach (var port in inputPorts.Values.OfType<ValueInput>()){
if (!port.isConnected /*&& !port.isDefaultValue*/){
_inputPortValues[port.ID] = port.serializedValue;
}
}
}
//Nothing... Instead, deserialize input port value AFTER GatherPorts and Validation. We DONT want to call GatherPorts here.
void ISerializationCallbackReceiver.OnAfterDeserialize(){}
///This is called when the node is created, duplicated or otherwise needs validation
sealed public override void OnValidate(Graph flowGraph){
GatherPorts();
}
sealed public override void OnParentConnected(int i){}
sealed public override void OnChildConnected(int i){}
sealed public override void OnParentDisconnected(int i){}
sealed public override void OnChildDisconnected(int i){}
//Connect 2 ports together. Source is always an Input and target an Output port
static void ConnectPorts(Port source, Port target){
BinderConnection.Create(source, target);
}
///Bind the port delegates. Called at runtime
public void BindPorts(){
for (var i = 0; i < outConnections.Count; i++){
(outConnections[i] as BinderConnection).Bind();
}
}
///Unbind the ports
public void UnBindPorts(){
for (var i = 0; i < outConnections.Count; i++){
(outConnections[i] as BinderConnection).UnBind();
}
}
///Gets an input Port by it's ID name which commonly is the same as it's name
public Port GetInputPort(string ID){
Port input = null;
inputPorts.TryGetValue(ID, out input);
return input;
}
///Gets an output Port by it's ID name which commonly is the same as it's name
public Port GetOutputPort(string ID){
Port output = null;
outputPorts.TryGetValue(ID, out output);
return output;
}
///Gets the BinderConnection of an Input port based on it's ID
public BinderConnection GetInputConnectionForPortID(string ID){
return inConnections.OfType<BinderConnection>().FirstOrDefault(c => c.targetPortID == ID);
}
///Gets the BinderConnection of an Output port based on it's ID
public BinderConnection GetOutputConnectionForPortID(string ID){
return outConnections.OfType<BinderConnection>().FirstOrDefault(c => c.sourcePortID == ID);
}
///Returns the first input port assignable to the type provided
public Port GetFirstInputOfType(Type type){
return inputPorts.Values.OrderBy(p => p.GetType() == typeof(FlowInput)? 0 : 1 ).FirstOrDefault(p => p.type.RTIsAssignableFrom(type) );
}
///Returns the first output port of a type assignable to the port
public Port GetFirstOutputOfType(Type type){
return outputPorts.Values.OrderBy(p => p.GetType() == typeof(FlowInput)? 0 : 1 ).FirstOrDefault(p => type.RTIsAssignableFrom(p.type) );
}
public List<Port> GetInputValuePorts()
{
List<Port> list = new List<Port>();
foreach (var port in inputPorts.Values)
{
if (port is ValueInput)
list.Add(port);
}
return list;
}
public List<Port> GetOutputValuePorts()
{
List<Port> list = new List<Port>();
foreach (var port in outputPorts.Values)
{
if (port is ValueOutput)
list.Add(port);
}
return list;
}
///Set the Component or GameObject instance input port to Owner if not connected and not already set to another reference.
///By convention, the instance port is always considered to be the first.
//Called from Graph when started.
public void AssignSelfInstancePort(){
if (graphAgent == null){
return;
}
var instanceInput = inputPorts.Values.OfType<ValueInput>().FirstOrDefault();
if (instanceInput != null && !instanceInput.isConnected && instanceInput.isDefaultValue){
if (instanceInput.type == typeof(GameObject)){
instanceInput.serializedValue = graphAgent.gameObject;
}
if (typeof(Component).RTIsAssignableFrom(instanceInput.type)){
instanceInput.serializedValue = graphAgent.GetComponent(instanceInput.type);
}
}
}
///Gather and register the node ports.
public void GatherPorts(){
inputPorts.Clear();
outputPorts.Clear();
RegisterPorts();
#if UNITY_EDITOR
OnPortsGatheredInEditor();
#endif
DeserializeInputPortValues();
ValidateConnections();
}
///*IMPORTANT*
///Override for registration/definition of ports.
///If RegisterPorts is not overriden, reflection is used to register ports based on guidelines.
///It's MUCH BETTER AND FASTER if you use the API for port registration instead though!
virtual protected void RegisterPorts(){
DoReflectionBasedRegistration();
}
///Reflection based registration if RegisterPorts is not overriden. Nowhere used by default in FC.
void DoReflectionBasedRegistration(){
//FlowInputs. All void methods with one Flow parameter.
foreach (var method in this.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)){
var parameters = method.GetParameters();
if (method.ReturnType == typeof(void) && parameters.Length == 1 && parameters[0].ParameterType == typeof(Flow)){
var nameAtt = method.RTGetAttribute<NameAttribute>(false);
var name = nameAtt != null? nameAtt.name : method.Name.SplitCamelCase();
var pointer = method.RTCreateDelegate<FlowHandler>(this);
AddFlowInput(name, pointer);
}
}
//ValueOutputs. All readable public properties.
foreach (var prop in this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)){
if (prop.CanRead){
AddPropertyOutput(prop, this);
}
}
//Search for delegates fields
foreach (var field in this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)){
if ( typeof(Delegate).RTIsAssignableFrom(field.FieldType) ){
var nameAtt = field.RTGetAttribute<NameAttribute>(false);
var name = nameAtt != null? nameAtt.name : field.Name.SplitCamelCase();
var invokeMethod = field.FieldType.GetMethod("Invoke");
var parameters = invokeMethod.GetParameters();
//FlowOutputs. All FlowHandler fields.
if (field.FieldType == typeof(FlowHandler)){
var flowOut = AddFlowOutput(name);
field.SetValue(this, (FlowHandler)flowOut.Call);
}
//ValueInputs. All ValueHandler<T> fields.
if (invokeMethod.ReturnType != typeof(void) && parameters.Length == 0){
var delType = invokeMethod.ReturnType;
var portType = typeof(ValueInput<>).RTMakeGenericType( new Type[]{ delType } );
var port = (ValueInput)Activator.CreateInstance(portType, new object[]{ this, name, name });
var getterType = typeof(ValueHandler<>).RTMakeGenericType(new Type[]{ delType });
var getter = port.GetType().GetMethod("get_value").RTCreateDelegate(getterType, port);
field.SetValue(this, getter);
inputPorts[name] = port;
}
}
}
}
//Validate ports for connections
//This is done seperately for Source and Target since we don't get control of when GatherPorts will be called on each node apart from in order of list (and we dont care)
//So basicaly each node validates it's own inputs and outputs seperately.
void ValidateConnections(){
foreach (var cOut in outConnections.ToArray()){ //ToArray because connection might remove itself if invalid
if (cOut is BinderConnection){
(cOut as BinderConnection).GatherAndValidateSourcePort();
}
}
foreach (var cIn in inConnections.ToArray()){
if (cIn is BinderConnection){
(cIn as BinderConnection).GatherAndValidateTargetPort();
}
}
}
///Restore the serialized input port values
void DeserializeInputPortValues(){
if (_inputPortValues == null){
return;
}
foreach (var pair in _inputPortValues){
Port inputPort = null;
if ( inputPorts.TryGetValue(pair.Key, out inputPort)){
if (inputPort is ValueInput && pair.Value != null && inputPort.type.RTIsAssignableFrom(pair.Value.GetType())){
(inputPort as ValueInput).serializedValue = pair.Value;
}
}
}
}
//Port registration/definition methods, to be used within RegisterPorts override
//...
///Add a new FlowInput with name and pointer. Pointer is the method to run when the flow port is called. Returns the new FlowInput object.
public FlowInput AddFlowInput(string name, FlowHandler pointer, string ID = ""){
if (string.IsNullOrEmpty(ID)) ID = name;
return (FlowInput) (inputPorts[ID] = new FlowInput(this, name, ID, pointer) );
}
///Add a new FlowOutput with name. Returns the new FlowOutput object.
public FlowOutput AddFlowOutput(string name, string ID = ""){
if (string.IsNullOrEmpty(ID)) ID = name;
return (FlowOutput) (outputPorts[ID] = new FlowOutput(this, name, ID) );
}
///Recommended. Add a ValueInput of type T. Returns the new ValueInput<T> object.
public ValueInput<T> AddValueInput<T>(string name, string ID = ""){
if (string.IsNullOrEmpty(ID)) ID = name;
return (ValueInput<T>) (inputPorts[ID] = new ValueInput<T>(this, name, ID) );
}
///Recommended. Add a ValueOutput of type T. getter is the function to get the value from. Returns the new ValueOutput<T> object.
public ValueOutput<T> AddValueOutput<T>(string name, ValueHandler<T> getter, string ID = ""){
if (string.IsNullOrEmpty(ID)) ID = name;
return (ValueOutput<T>) (outputPorts[ID] = new ValueOutput<T>(this, name, ID, getter) );
}
///Add a WildInput port which is an object type forced to a specific type instead. It's very recommended to use the generic registration methods instead.
public ValueInput AddValueInput(string name, Type type, string ID = ""){
if (string.IsNullOrEmpty(ID)) ID = name;
return (ValueInput) (inputPorts[ID] = ValueInput.CreateInstance(type, this, name, ID) );
}
///Add a new WildOutput of unkown runtime type (similar to WildInput). getter is a function to get the port value from. Returns the new ValueOutput object.
public ValueOutput AddValueOutput(string name, Type type, ValueHandler<object> getter, string ID = ""){
if (string.IsNullOrEmpty(ID)) ID = name;
return (ValueOutput) (outputPorts[ID] = ValueOutput.CreateInstance(type, this, name, ID, getter) );
}
///Register a PropertyInfo as ValueOutput. Used only in reflection based registration.
public ValueOutput AddPropertyOutput(PropertyInfo prop, object instance){
if (!prop.CanRead){
Debug.LogError("Property is write only");
return null;
}
var nameAtt = prop.RTGetAttribute<NameAttribute>(false);
var name = nameAtt != null? nameAtt.name : prop.Name.SplitCamelCase();
var getterType = typeof(ValueHandler<>).RTMakeGenericType(new Type[]{ prop.PropertyType });
var getter = prop.RTGetGetMethod().RTCreateDelegate(getterType, instance);
var portType = typeof(ValueOutput<>).RTMakeGenericType( new Type[]{ prop.PropertyType } );
var port = (ValueOutput)Activator.CreateInstance(portType, new object[]{ this, name, name, getter });
return (ValueOutput) (outputPorts[name] = port);
}
/////
///Alternative Exit Call by providing a FlowOutput (otherwise, use 'flowOutput.Call(Flow f)' directly)
public void Call(FlowOutput port, Flow f){
port.Call(f);
}
//...
public void Fail(string error = null){
status = Status.Failure;
if (error != null){
Debug.LogError("["+graph.name+"]"+string.Format("<b>Flow Execution Error:</b> '{0}' - '{1}'", this.name+" ID:"+this.ID, error), graph.agent);
}
}
//...
public void SetStatus(Status status){
this.status = status;
}
//
virtual public string ExecuteToLua()
{
return @"
local flowOutput = self:GetFirstOutputOfType();
if(flowOutput ~= nil)then
flowOutput:Call();
else
print(self.name..'have not outputflow');
end";
}
////////////////////////////////////////
///////////GUI AND EDITOR STUFF/////////
////////////////////////////////////////
#if UNITY_EDITOR
private static Port clickedPort;
private static int dragDropMisses;
private static GUIStyle _leftLabelStyle;
private static GUIStyle _rightLabelStyle;
public Port[] orderedInputs;
public Port[] orderedOutputs;
public ValueInput firstValuePort;
//for input ports
private static GUIStyle leftLabelStyle{
get
{
if (_leftLabelStyle == null){
_leftLabelStyle = new GUIStyle(GUI.skin.GetStyle("label"));
_leftLabelStyle.alignment = TextAnchor.UpperLeft;
}
return _leftLabelStyle;
}
}
//for output ports
private static GUIStyle rightLabelStyle{
get
{
if (_rightLabelStyle == null){
_rightLabelStyle = new GUIStyle(GUI.skin.GetStyle("label"));
_rightLabelStyle.alignment = TextAnchor.UpperRight;
}
return _rightLabelStyle;
}
}
//when gathering ports and we are in Unity Editor
//gather the ordered inputs and outputs
void OnPortsGatheredInEditor(){
orderedInputs = inputPorts.Values.OrderBy(p => p.GetType() == typeof(FlowInput)? 0 : 1 ).ToArray();
orderedOutputs = outputPorts.Values.OrderBy(p => p.GetType() == typeof(FlowOutput)? 0 : 1 ).ToArray();
firstValuePort = orderedInputs.OfType<ValueInput>().FirstOrDefault();
}
//Get all output Connections of a port. Used only for when removing
BinderConnection[] GetOutPortConnections(Port port){
return outConnections.Cast<BinderConnection>().Where(c => c.sourcePort == port ).ToArray();
}
//Get all input Connections of a port. Used only for when removing
BinderConnection[] GetInPortConnections(Port port){
return inConnections.Cast<BinderConnection>().Where(c => c.targetPort == port ).ToArray();
}
//Seal it...
sealed protected override void DrawNodeConnections(Rect drawCanvas, bool fullDrawPass, Vector2 canvasMousePos, float zoomFactor){
var e = Event.current;
//Port container graphics
if (fullDrawPass || drawCanvas.Overlaps(nodeRect)){
GUI.Box(new Rect(nodeRect.x - 8, nodeRect.y + 2, 10, nodeRect.height), string.Empty, (GUIStyle)"nodePortContainer");
GUI.Box(new Rect(nodeRect.xMax - 2, nodeRect.y + 2, 10, nodeRect.height), string.Empty, (GUIStyle)"nodePortContainer");
}
///
if (fullDrawPass || drawCanvas.Overlaps(nodeRect)){
var portRect = new Rect(0,0,10,10);
//INPUT Ports
if (orderedInputs != null){
Port instancePort = null;
for (var i = 0; i < orderedInputs.Length; i++){
var port = orderedInputs[i];
var canConnect = true;
if ((port == clickedPort) ||
(clickedPort is FlowInput || clickedPort is ValueInput) ||
(port.isConnected && port is ValueInput) ||
(clickedPort != null && clickedPort.parent == port.parent) ||
(clickedPort != null && !TypeConverter.HasConvertion(clickedPort.type, port.type)) )
{
canConnect = false;
}
portRect.width = port.isConnected? 12:10;
portRect.height = portRect.width;
portRect.center = new Vector2(nodeRect.x - 5, port.pos.y);
port.pos = portRect.center;
//first gameobject or component port is considered to be the 'instance' port by convention
if (port == firstValuePort){
if ( (typeof(Component).IsAssignableFrom(port.type) || port.type == typeof(GameObject)) ){
instancePort = port;
}
}
//Port graphic
if (clickedPort != null && !canConnect && clickedPort != port){
GUI.color = new Color(1,1,1,0.3f);
}
GUI.Box(portRect, string.Empty, port.isConnected? (GUIStyle)"nodePortConnected" : (GUIStyle)"nodePortEmpty");
GUI.color = Color.white;
//Tooltip
if (portRect.Contains(e.mousePosition)){
var labelString = (canConnect || port.isConnected || port == clickedPort)? port.type.FriendlyName() : "Can't Connect Here";
var size = GUI.skin.GetStyle("box").CalcSize(new GUIContent(labelString));
var rect = new Rect(0, 0, size.x + 10, size.y + 5);
rect.x = portRect.x - size.x - 10;
rect.y = portRect.y - size.y/2;
GUI.Box(rect, labelString);
//Or value
} else {
if ( port is ValueInput && !port.isConnected){
//Only these types are shown their value
if ( port.type.IsValueType || port.type == typeof(Type) || port.type == typeof(string) || typeof(UnityEngine.Object).IsAssignableFrom(port.type) ){
var value = (port as ValueInput).serializedValue;
string labelString = null;
if (!(port as ValueInput).isDefaultValue ){
if (value is UnityEngine.Object && value as UnityEngine.Object != null){
labelString = string.Format("<b><color=#66ff33>{0}</color></b>", (value as UnityEngine.Object).name);
} else {
labelString = value.ToStringAdvanced();
}
} else if ( port == instancePort ){
var exists = true;
if (graphAgent != null && typeof(Component).IsAssignableFrom(port.type) ){
exists = graphAgent.GetComponent(port.type) != null;
}
var color = exists? "66ff33" : "ff3300";
labelString = string.Format("<color=#{0}><b>♟ <i>Self</i></b></color>", color);
} else {
GUI.color = new Color(1,1,1,0.15f);
labelString = value.ToStringAdvanced();
}
var size = GUI.skin.GetStyle("label").CalcSize(new GUIContent(labelString));
var rect = new Rect(0, 0, size.x, size.y);
rect.x = portRect.x - size.x - 5;
rect.y = portRect.y - size.y * 0.3f; //*0.3? something's wrong here. FIX
GUI.Label(rect, labelString);
GUI.color = Color.white;
}
}
}
if (Graph.allowClick){
//Right click removes connections
if (port.isConnected && e.type == EventType.ContextClick && portRect.Contains(e.mousePosition)){
foreach(var c in GetInPortConnections(port)){
graph.RemoveConnection(c);
}
e.Use();
return;
}
//Click initialize new drag & drop connection
if (e.type == EventType.MouseDown && e.button == 0 && portRect.Contains(e.mousePosition)){
if (port.CanAcceptConnections() ){
dragDropMisses = 0;
clickedPort = port;
e.Use();
}
}
//Drop on creates connection
if (e.type == EventType.MouseUp && e.button == 0 && clickedPort != null){
if (portRect.Contains(e.mousePosition) && port.CanAcceptConnections() ){
ConnectPorts(clickedPort, port);
clickedPort = null;
e.Use();
}
}
}
}
}
//OUTPUT Ports
if (orderedOutputs != null){
for (var i = 0; i < orderedOutputs.Length; i++){
var port = orderedOutputs[i];
var canConnect = true;
if ((port == clickedPort) ||
(clickedPort is FlowOutput || clickedPort is ValueOutput) ||
(port.isConnected && port is FlowOutput) ||
(clickedPort != null && clickedPort.parent == port.parent) ||
(clickedPort != null && !TypeConverter.HasConvertion(port.type, clickedPort.type)) )
{
canConnect = false;
}
portRect.width = port.isConnected? 12:10;
portRect.height = portRect.width;
portRect.center = new Vector2(nodeRect.xMax + 5, port.pos.y);
port.pos = portRect.center;
//Port graphic
if (clickedPort != null && !canConnect && clickedPort != port){
GUI.color = new Color(1,1,1,0.3f);
}
GUI.Box(portRect, string.Empty, port.isConnected? (GUIStyle)"nodePortConnected" : (GUIStyle)"nodePortEmpty");
GUI.color = Color.white;
//Tooltip
if (portRect.Contains(e.mousePosition)){
var labelString = (canConnect || port.isConnected || port == clickedPort)? port.type.FriendlyName() : "Can't Connect Here";
var size = GUI.skin.GetStyle("label").CalcSize(new GUIContent(labelString));
var rect = new Rect(0, 0, size.x + 10, size.y + 5);
rect.x = portRect.x + 15;
rect.y = portRect.y - portRect.height/2;
GUI.Box(rect, labelString);
}
if (Graph.allowClick){
//Right click removes connections
if (e.type == EventType.ContextClick && portRect.Contains(e.mousePosition)){
foreach(var c in GetOutPortConnections(port)){
graph.RemoveConnection(c);
}
e.Use();
return;
}
//Click initialize new drag & drop connection
if (e.type == EventType.MouseDown && e.button == 0 && portRect.Contains(e.mousePosition)){
if (port.CanAcceptConnections() ){
dragDropMisses = 0;
clickedPort = port;
e.Use();
}
}
//Drop on creates connection
if (e.type == EventType.MouseUp && e.button == 0 && clickedPort != null){
if (portRect.Contains(e.mousePosition) && port.CanAcceptConnections() ){
ConnectPorts(port, clickedPort);
clickedPort = null;
e.Use();
}
}
}
}
}
}
///ACCEPT CONNECTION
if (clickedPort != null && e.type == EventType.MouseUp){
///ON NODE
if (nodeRect.Contains(e.mousePosition)){
var cachePort = clickedPort;
var menu = new GenericMenu();
if (cachePort is ValueOutput || cachePort is FlowOutput){
if (orderedInputs != null){
foreach (var _port in orderedInputs.Where(p => p.CanAcceptConnections() && TypeConverter.HasConvertion(cachePort.type, p.type) )){
var port = _port;
menu.AddItem(new GUIContent(string.Format("To: '{0}'", port.name) ), false, ()=> { ConnectPorts(cachePort, port); } );
}
}
} else {
if (orderedOutputs != null){
foreach (var _port in orderedOutputs.Where(p => p.CanAcceptConnections() && TypeConverter.HasConvertion(p.type, cachePort.type) )){
var port = _port;
menu.AddItem(new GUIContent(string.Format("From: '{0}'", port.name) ), false, ()=> { ConnectPorts(port, cachePort); } );
}
}
}
//append menu items
menu = OnDragAndDropPortContextMenu(menu, cachePort);
//if there is only 1 option, just do it
if (menu.GetItemCount() == 1){
EditorUtils.GetMenuItems(menu)[0].func();
} else {
Graph.PostGUI += ()=> { menu.ShowAsContext(); };
}
clickedPort = null;
e.Use();
///
///ON CANVAS
} else {
dragDropMisses ++;
if (dragDropMisses == graph.allNodes.Count && clickedPort != null){
var cachePort = clickedPort;
clickedPort = null;
DoContextPortConnectionMenu(cachePort, e.mousePosition, zoomFactor);
e.Use();
}
}
}
//Temp connection line when linking
if (clickedPort != null && clickedPort.parent == this){
var xDiff = (clickedPort.pos.x - e.mousePosition.x) * 0.8f;
xDiff = e.mousePosition.x > clickedPort.pos.x? xDiff : -xDiff;
var tangA = clickedPort is FlowInput || clickedPort is ValueInput? new Vector2(xDiff, 0) : new Vector2(-xDiff, 0);
var tangB = tangA * -1;
Handles.DrawBezier(clickedPort.pos, e.mousePosition, clickedPort.pos + tangA , e.mousePosition + tangB, new Color(0.5f,0.5f,0.8f,0.8f), null, 3);
}
//Actualy draw the existing connections
for (var i = 0; i < outConnections.Count; i++){
var binder = outConnections[i] as BinderConnection;
if (binder != null){ //for in case it's MissingConnection
var sourcePort = binder.sourcePort;
var targetPort = binder.targetPort;
if (sourcePort != null && targetPort != null){
if (fullDrawPass || drawCanvas.Overlaps(RectUtils.GetBoundRect(sourcePort.pos, targetPort.pos) ) ){
binder.DrawConnectionGUI(sourcePort.pos, targetPort.pos);
}
}
}
}
}
///Let nodes handle ports draged on top of them
virtual protected GenericMenu OnDragAndDropPortContextMenu(GenericMenu menu, Port port){
return menu;
}
///Context menu for when dragging a connection on empty canvas
///Unfortunately I can't think of a more automatic way
void DoContextPortConnectionMenu(Port clickedPort, Vector2 mousePos, float zoomFactor){
Action<FlowNode> FinalizeConnection = (targetNode) => {
Port source = null;
Port target = null;
if (clickedPort is ValueOutput || clickedPort is FlowOutput){
source = clickedPort;
target = targetNode.GetFirstInputOfType(clickedPort.type);
} else {
source = targetNode.GetFirstOutputOfType(clickedPort.type);
target = clickedPort;
}
ConnectPorts(source, target);
Graph.currentSelection = targetNode;
};
var menu = new GenericMenu();
//SimplexWrapper
UnityEditor.GenericMenu.MenuFunction2 SelectedSimplex = (t) =>{
var genericType = typeof(SimplexNodeWrapper<>).MakeGenericType(new System.Type[]{ (System.Type)t });
var wrapper = (FlowNode)graph.AddNode(genericType, mousePos);
FinalizeConnection(wrapper);
};
//MethodInfo Wrapper
UnityEditor.GenericMenu.MenuFunction2 SelectedMethod = (object m) =>{
// var methodWrapper = graph.AddNode<ReflectedMethodNodeWrapper>(mousePos);
// methodWrapper.SetMethod((MethodInfo)m);
// FinalizeConnection(methodWrapper);
};
//Normal FG Node
GenericMenu.MenuFunction2 SelectedFlowNode = (t) =>{
var fNode = (FlowNode)graph.AddNode( (Type)t, mousePos);
FinalizeConnection(fNode);
};
///Append reflection
//Only the instance members are appended, along with extension methods
if (clickedPort is ValueOutput){
var methods = clickedPort.type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).ToList();
methods.AddRange( clickedPort.type.GetExtensionMethods() );
foreach (var m in methods.OrderBy(m => !m.IsStatic).OrderBy(m => m.IsSpecialName).OrderBy(m => m.DeclaringType != clickedPort.type ) ){
if (m.IsGenericMethod){
continue;
}
if (m.IsStatic && !m.GetParameters().Any(p => p.ParameterType.IsAssignableFrom(clickedPort.type))){
continue;
}
if (m.IsObsolete()){
continue;
}
var categoryName = clickedPort.type.FriendlyName() + "/";
if (m.DeclaringType != clickedPort.type){
categoryName += "More/";
}
var name = categoryName + m.SignatureName();
var icon = UnityEditor.EditorGUIUtility.ObjectContent(null, clickedPort.type).image;
menu.AddItem(new GUIContent(name, icon), false, SelectedMethod, m);
}
}
//Append FlowControl nodes anyway in case of Flow clicked port
//...
if (clickedPort is FlowOutput || clickedPort is FlowInput){
foreach(var info in EditorUtils.GetScriptInfosOfType(typeof(FlowControlNode))){
menu.AddItem(new GUIContent(info.category + "/" + info.name, info.icon, info.description), false, SelectedFlowNode, info.type );
}
}
//Append FlowNodes
//...
foreach(var info in EditorUtils.GetScriptInfosOfType(typeof(FlowNode))){
var definedInputTypesAtt = info.type.RTGetAttribute<ContextDefinedInputsAttribute>(true);
var definedOutputTypesAtt = info.type.RTGetAttribute<ContextDefinedOutputsAttribute>(true);
if ( (clickedPort is ValueOutput || clickedPort is FlowOutput) && definedInputTypesAtt != null){
if (definedInputTypesAtt.types.Any(t => t.IsAssignableFrom(clickedPort.type))){
menu.AddItem(new GUIContent(info.category + "/" + info.name, info.icon, info.description), false, SelectedFlowNode, info.type);
}
}
if ( (clickedPort is ValueInput || clickedPort is FlowInput) && definedOutputTypesAtt != null){
if (definedOutputTypesAtt.types.Any(t => clickedPort.type.IsAssignableFrom(t) )){
menu.AddItem(new GUIContent(info.category + "/" + info.name, info.icon, info.description), false, SelectedFlowNode, info.type);
}
}
}
//Append Simplex Nodes
//...
foreach (var info in EditorUtils.GetScriptInfosOfType(typeof(SimplexNode))){
var method = info.type.GetMethod("Invoke");
if (clickedPort is ValueOutput){
var parameterTypes = method.GetParameters().Select(p => p.ParameterType).ToArray();
if (parameterTypes.Length == 0)
continue;
if ( parameterTypes.Any(t => t.IsAssignableFrom(clickedPort.type)) )
menu.AddItem(new GUIContent(info.category + "/" + info.name, info.icon, info.description), false, SelectedSimplex, info.type);
}
if (clickedPort is FlowOutput){
if ( (method.ReturnType == typeof(void) || method.ReturnType == typeof(IEnumerator)) && !info.type.IsSubclassOf(typeof(ExtractorNode)) )
menu.AddItem(new GUIContent(info.category + "/" + info.name, info.icon, info.description), false, SelectedSimplex, info.type );
}
if (clickedPort is ValueInput){
if ((method.ReturnType == typeof(void) || method.ReturnType == typeof(IEnumerator)))
continue;
if (clickedPort.type.IsAssignableFrom(method.ReturnType))
menu.AddItem(new GUIContent(info.category + "/" + info.name, info.icon, info.description), false, SelectedSimplex, info.type);
}
if (clickedPort is FlowInput){
if ( (method.ReturnType == typeof(void) || method.ReturnType == typeof(IEnumerator)) && !info.type.IsSubclassOf(typeof(ExtractorNode)) )
menu.AddItem(new GUIContent(info.category + "/" + info.name, info.icon, info.description), false, SelectedSimplex, info.type );
}
}
///Append reflection
//methods accepting port type as a parameter
if (clickedPort is ValueOutput){
var types = UserTypePrefs.GetPreferedTypesList(typeof(object));
foreach (var type in types){
if (type == clickedPort.type){
continue;
}
foreach (var m in type.GetMethods(BindingFlags.Instance| BindingFlags.Static | BindingFlags.Public).OrderBy(m => m.IsSpecialName) ){
if (m.IsGenericMethod){
continue;
}
if (!m.GetParameters().Any(p => p.ParameterType.IsAssignableFrom(clickedPort.type))){
continue;
}
if (m.IsObsolete()){
continue;
}
var categoryName = "Functions[方法]/Reflected/" + type.FriendlyName() + "/";
var name = categoryName + m.SignatureName();
var icon = UnityEditor.EditorGUIUtility.ObjectContent(null, type).image;
menu.AddItem(new GUIContent(name, icon), false, SelectedMethod, m);
}
}
}
//methods returning port type
if (clickedPort is ValueInput){
var types = UserTypePrefs.GetPreferedTypesList(typeof(object));
types.Add(clickedPort.type);
foreach (var type in types){
foreach (var m in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).OrderBy(m => m.IsSpecialName) ){
if (m.IsGenericMethod || m.ReturnType == typeof(void) || !clickedPort.type.IsAssignableFrom(m.ReturnType) ){
continue;
}
if (m.IsObsolete()){
continue;
}
var categoryName = "Functions[方法]/Reflected/" + type.FriendlyName() + "/";
var name = categoryName + m.SignatureName();
var icon = UnityEditor.EditorGUIUtility.ObjectContent(null, type).image;
menu.AddItem(new GUIContent(name, icon), false, SelectedMethod, m);
}
}
}
//all void methods
if (clickedPort is FlowInput || clickedPort is FlowOutput) {
foreach (var type in UserTypePrefs.GetPreferedTypesList(typeof(object))){
foreach (var m in type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public).OrderBy(m => m.IsSpecialName) ){
if (m.IsGenericMethod || m.ReturnType != typeof(void)){
continue;
}
if (m.IsObsolete()){
continue;
}
var categoryName = "Functions[方法]/Reflected/" + type.FriendlyName() + "/";
var name = categoryName + m.SignatureName();
var icon = UnityEditor.EditorGUIUtility.ObjectContent(null, type).image;
menu.AddItem(new GUIContent(name, icon), false, SelectedMethod, m);
}
}
}
///
//Append Variable related nodes
//...
var variables = new Dictionary<IBlackboard, List<Variable>>();
if (graphBlackboard != null){
variables[graphBlackboard] = graphBlackboard.variables.Values.ToList();
}
foreach(var globalBB in GlobalBlackboard.allGlobals){
variables[globalBB] = globalBB.variables.Values.ToList();
}
if (clickedPort is ValueInput){
//Append the very special Owner variable
// if ( clickedPort.type == typeof(GameObject) ){
// menu.AddItem(new GUIContent("Variables[变量]/Self"), false, SelectedFlowNode, typeof(OwnerVariable) );
// }
//
// //New var
// menu.AddItem(new GUIContent(string.Format("Variables[变量]/Graph Variable ({0})", clickedPort.type.FriendlyName() )), false, ()=>
// {
// var genericType = typeof(GetVariable<>).MakeGenericType(new System.Type[]{ clickedPort.type });
// SelectedFlowNode(genericType);
// });
//
// menu.AddItem(new GUIContent(string.Format("Variables[变量]/Get Blackboard Variable/Get Other Of Type ({0})", clickedPort.type.FriendlyName() )), false, ()=>
// {
// var genericType = typeof(GetOtherVariable<>).MakeGenericType(new System.Type[]{ clickedPort.type });
// SelectedFlowNode(genericType);
// });
//BB var