-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Program.cs
1709 lines (1427 loc) · 55.6 KB
/
Program.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 Microsoft.Build.Locator;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.MSBuild;
using Microsoft.CodeAnalysis.Text;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Numerics;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SharpLogix
{
/*class NodeDefinition
{
protected string typename;
protected string[] inputs;
protected string[] outputs;
protected string default_output_name;
}
class BinaryOperationNode : NodeDefinition
{
public BinaryOperationNode(string name)
{
typename = name;
inputs = new string[] { "A", "B" };
outputs = new string[] { "*" };
default_output_name = "*";
}
}*/
struct NodeTypedConnector
{
public string name;
public string logixType;
public NodeTypedConnector(string name, string logixType)
{
this.name = name;
this.logixType = logixType;
}
}
struct NodeInfo
{
public string className;
public int defaultOutputIndex;
public NodeTypedConnector[] inputs;
public NodeTypedConnector[] outputs;
public string[] methods;
public string[] impulses;
public static NodeInfo Define(
string cName,
NodeTypedConnector[] nodeInputs,
NodeTypedConnector[] nodeOutputs,
int outputIndex)
{
return new NodeInfo
{
className = cName,
defaultOutputIndex = outputIndex,
inputs = nodeInputs,
outputs = nodeOutputs,
/* TODO Add methods and impulses ! */
methods = new string[0],
impulses = new string[0]
};
}
public string DefaultOutputName()
{
return outputs[defaultOutputIndex].name;
}
public string OutputTypeOf(string outputName)
{
foreach (var nodeConnector in outputs)
{
if (nodeConnector.name == outputName)
{
return nodeConnector.logixType;
}
}
return "INVALID_OUTPUT_" + outputName;
}
}
class NodeDB : Dictionary<string, NodeInfo>
{
public NodeInfo AddInputDefinition(string name, string nodeType)
{
NodeTypedConnector[] inputs = { };
NodeTypedConnector[] outputs = { new NodeTypedConnector("*", nodeType) };
return AddDefinition(name, inputs, outputs, 0);
}
public NodeInfo AddBinaryOperationDefinition(string name, string nodeType)
{
NodeTypedConnector[] inputs = {
new NodeTypedConnector("A", nodeType),
new NodeTypedConnector("B", nodeType)
};
NodeTypedConnector[] outputs = {
new NodeTypedConnector("*", nodeType)
};
return AddDefinition(name, inputs, outputs, 0);
}
public NodeInfo AddDefinition(
string name,
NodeTypedConnector[] inputs,
NodeTypedConnector[] outputs,
int defaultOutputIndex)
{
string completeName = "FrooxEngine.LogiX." + name;
NodeInfo nodeInfo = NodeInfo.Define(completeName, inputs, outputs, defaultOutputIndex);
this.Add(completeName, nodeInfo);
return nodeInfo;
}
public NodeInfo GetNodeInformation(string nodeName)
{
return this[nodeName];
}
public string DefaultOutputFor(string nodeName)
{
return this[nodeName].DefaultOutputName();
}
public string OutputTypeOf(string nodeName, string outputName)
{
return this[nodeName].OutputTypeOf(outputName);
}
}
struct Node
{
public string typename;
public string GenericTypeName()
{
return typename.Split(new char[] { '<' })[0];
}
}
struct NodeRef
{
public int nodeId;
public NodeRef(int id)
{
nodeId = id;
}
}
struct NodeRefGroup
{
List<NodeRef> nodes;
}
class ActiveElement
{
NodeRef node;
string defaultOutputName;
string selectedOutput;
};
class LogixLocalVariable
{
public int lastNodeID;
public string typeName;
public int definitionLevel;
public int lastUpdateLevel;
public int checkPointFromID;
public int checkPointID;
static public readonly int invalidID = -1;
public void SetLastNode(int nodeID, int level)
{
lastNodeID = nodeID;
lastUpdateLevel = level;
if (level == definitionLevel)
{
checkPointFromID = lastNodeID;
}
}
public bool UpdatedFromLowerLevels()
{
return lastUpdateLevel != definitionLevel;
}
public void SetCheckPoint(int registerNodeID)
{
checkPointID = registerNodeID;
}
public void RemoveCheckPoint()
{
checkPointID = invalidID;
}
public bool CheckpointSet()
{
return checkPointID != invalidID;
}
};
class LogixLocalVariables : Dictionary<string, LogixLocalVariable>
{
public int level = 0;
public static LogixLocalVariable invalidVar = new LogixLocalVariable()
{
lastNodeID = LogixLocalVariable.invalidID,
definitionLevel = LogixLocalVariable.invalidID,
lastUpdateLevel = LogixLocalVariable.invalidID,
checkPointFromID = LogixLocalVariable.invalidID,
checkPointID = LogixLocalVariable.invalidID,
};
public LogixLocalVariable AddVariable(string type, string name, int lastNodeID)
{
LogixLocalVariable localVar = new LogixLocalVariable
{
lastNodeID = lastNodeID,
definitionLevel = level,
lastUpdateLevel = level,
checkPointFromID = lastNodeID,
checkPointID = LogixLocalVariable.invalidID,
typeName = type
};
Add(name, localVar);
return localVar;
}
public bool HasIdentifier(string name)
{
return this.ContainsKey(name);
}
public LogixLocalVariable SetVariable(string name, int lastNodeID, int level)
{
var localVar = this[name];
localVar.SetLastNode(lastNodeID, level);
return localVar;
}
public void AddParameters(LogixLocalVariables parameters)
{
foreach (string parameterName in parameters.Keys)
{
this.Add(parameterName, parameters[parameterName]);
}
}
}
// NumericLiteral - Int -> IntInput. 0 Inputs. 1 Output. DefaultOutputName = *
// StringLiteral - String -> StringInput. 0 Inputs. 1 Output. DefaultOutputName = *
// Operator + -> Add. 2 Inputs. 1 Output. DefaultOutputName = *
//
// AssignmentOperation - NodeGroup. 0 Inputs. 1 Output (NodeGroup ID). DefaultOutputName = ??
class OperationNodes : List<int> { }
class LogixMethodParameter
{
public string name;
public string type; // FIXME : Infer this from the representing node ?
public NodeRef node;
public LogixMethodParameter(string paramName, string paramType, int nodeID)
{
name = paramName;
type = paramType;
node = new NodeRef(nodeID);
}
}
class LogixMethod
{
public string name;
public List<LogixMethodParameter> parameters;
public string returnType;
public int slotID;
public bool ReturnValue()
{
return returnType != "void";
}
public void SetReturnType(string typeName)
{
returnType = typeName;
}
static readonly LogixMethodParameter invalidParam = new LogixMethodParameter("", "", -1);
public LogixMethod(string methodName, int newSlotID)
{
name = methodName;
slotID = newSlotID;
parameters = new List<LogixMethodParameter>(4);
}
public void AddParameter(string name, string type, int nodeID)
{
parameters.Add(new LogixMethodParameter(name, type, nodeID));
}
public LogixMethodParameter GetParameter(string name)
{
foreach (LogixMethodParameter methodParam in parameters)
{
if (methodParam.name == name) return methodParam;
}
return invalidParam;
}
}
class Nodes : List<Node>
{
public readonly static Node invalidNode = new Node();
public Node GetNode(int nodeID)
{
if (nodeID >= this.Count)
{
return invalidNode;
}
return this[nodeID];
}
}
struct LogixSlot
{
public string name;
public LogixSlot(string slotName)
{
name = slotName;
}
}
class Slots : List<LogixSlot>
{
public int AddSlot(string name)
{
int slotID = Count;
Add(new LogixSlot(name));
return slotID;
}
public LogixSlot GetSlot(int slotID)
{
return this[slotID];
}
}
class SharpenedSyntaxWalker : CSharpSyntaxWalker
{
readonly NodeDB nodeDB;
readonly Nodes nodes;
readonly Slots slots;
int currentSlotID = -1;
readonly List<string> script;
System.Numerics.Vector2 nodePosition;
readonly FlowSequences flowSequences;
readonly CheckpointsZones checkpointsZones;
LogixLocalVariables methodParameters;
List<OperationNodes> currentOperationNodes;
readonly List<LogixLocalVariables> locals;
int currentBlockLevel;
bool localsAlreadyPrepared = false;
bool generateCheckpoints = false;
readonly Dictionary<string, NodeRef> globals;
readonly Dictionary<string, LogixMethod> methods;
string currentMethodName = "";
int currentReturnID = -1;
public int currentImpulseOutputNode = -1;
public string currentImpulseOutputName = null;
int currentSequenceID = -1;
int nextSequenceOutput = -1;
int currentCheckpointImpulse = -1;
NodeRef undefined;
enum IdentifierKind
{
INVALID,
Local,
Global,
Namespace,
Method,
Field
}
readonly Dictionary<TypeCode, string> literalLogixNodes;
readonly Dictionary<SyntaxKind, string> binaryOperationsNodes;
/* FIXME : Find a better name */
readonly Dictionary<string, string> typesList;
public static string Base64Encode(string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public string LogixNamespacePrefix(string suffix)
{
return "FrooxEngine.LogiX." + suffix;
}
public SharpenedSyntaxWalker()
{
nodeDB = new NodeDB();
nodes = new Nodes();
slots = new Slots();
currentSlotID = slots.AddSlot("ProgramSlot");
currentBlockLevel = 0;
locals = new List<LogixLocalVariables>(4);
LocalsAdd();
methodParameters = null; /* Initialized when required */
globals = new Dictionary<string, NodeRef>();
methods = new Dictionary<string, LogixMethod>(32);
binaryOperationsNodes = new Dictionary<SyntaxKind, string>();
currentOperationNodes = new List<OperationNodes>();
flowSequences = new FlowSequences();
checkpointsZones = new CheckpointsZones();
nodeDB.AddInputDefinition("Input.BoolInput", "System.Boolean");
nodeDB.AddInputDefinition("Input.ByteInput", "System.Byte");
nodeDB.AddInputDefinition("Input.SbyteInput", "System.SByte");
nodeDB.AddInputDefinition("Input.ShortInput", "System.Int16");
nodeDB.AddInputDefinition("Input.UshortInput", "System.UInt16");
nodeDB.AddInputDefinition("Input.IntInput", "System.Int32");
nodeDB.AddInputDefinition("Input.UintInput", "System.UInt32");
nodeDB.AddInputDefinition("Input.LongInput", "System.Int64");
nodeDB.AddInputDefinition("Input.UlongInput", "System.UInt64");
nodeDB.AddInputDefinition("Input.FloatInput", "System.Single");
nodeDB.AddInputDefinition("Input.DoubleInput", "System.Double");
nodeDB.AddInputDefinition("Input.CharInput", "System.Char");
nodeDB.AddInputDefinition("Input.StringInput", "System.String");
nodeDB.AddInputDefinition("Input.TimeNode", "System.DateTime");
nodeDB.AddInputDefinition("Input.ColorInput", "BaseX.color");
nodeDB.AddBinaryOperationDefinition("Operators.Add_Float", "System.Single");
nodeDB.AddBinaryOperationDefinition("Operators.Add_Int", "System.Int32");
nodeDB.AddBinaryOperationDefinition("Operators.Mul_Float", "System.Single");
nodeDB.AddBinaryOperationDefinition("Operators.Mul_Int", "System.Int32");
nodeDB.AddBinaryOperationDefinition("Operators.Div_Float", "System.Single");
nodeDB.AddBinaryOperationDefinition("Operators.Div_Int", "System.Int32");
nodeDB.AddBinaryOperationDefinition("Operators.Sub_Float", "System.Single");
nodeDB.AddBinaryOperationDefinition("Operators.Sub_Int", "System.Int32");
nodeDB.AddBinaryOperationDefinition("Operators.GreaterThan_Float", "System.Single");
nodeDB.AddBinaryOperationDefinition("Operators.GreaterOrEqual_Float", "System.Single");
nodeDB.AddBinaryOperationDefinition("Operators.Equals_Float", "System.Single");
nodeDB.AddBinaryOperationDefinition("Operators.LessThan_Float", "System.Single");
nodeDB.AddDefinition(
"Data.ReadDynamicVariable",
new NodeTypedConnector[] {
new NodeTypedConnector("Source", "`1"),
new NodeTypedConnector("VariableName", "System.String")
},
new NodeTypedConnector[] {
new NodeTypedConnector("Value", "`1"),
new NodeTypedConnector("FoundValue", "System.Boolean")
},
0);
nodeDB.AddDefinition(
"Data.WriteOrCreateDynamicVariable",
new NodeTypedConnector[] {
new NodeTypedConnector("Target", "FrooxEngine.Slot"),
new NodeTypedConnector("VariableName", "System.String"),
new NodeTypedConnector("Value", "`1"),
new NodeTypedConnector("CreateDirectlyOnTarget", "System.Boolean"),
new NodeTypedConnector("CreateNonPersistent", "System.Boolean")
},
new NodeTypedConnector[] { },
-1);
nodeDB.AddDefinition(
"Color.HSV_ToColor",
new NodeTypedConnector[] {
new NodeTypedConnector("H", "System.Single"),
new NodeTypedConnector("S", "System.Single"),
new NodeTypedConnector("V", "System.Single")
},
new NodeTypedConnector[]
{
new NodeTypedConnector("*", "BaseX.Color")
},
0);
nodeDB.AddDefinition(
"Data.ValueRegister",
new NodeTypedConnector[] { },
new NodeTypedConnector[] {
new NodeTypedConnector("*", "`1")
},
0);
literalLogixNodes = new Dictionary<TypeCode, string>();
literalLogixNodes.Add(TypeCode.Boolean, "BoolInput");
literalLogixNodes.Add(TypeCode.Byte, "ByteInput");
literalLogixNodes.Add(TypeCode.SByte, "SbyteInput");
literalLogixNodes.Add(TypeCode.Int16, "ShortInput");
literalLogixNodes.Add(TypeCode.UInt16, "UshortInput");
literalLogixNodes.Add(TypeCode.Int32, "IntInput");
literalLogixNodes.Add(TypeCode.UInt32, "UintInput");
literalLogixNodes.Add(TypeCode.Int64, "LongInput");
literalLogixNodes.Add(TypeCode.UInt64, "UlongInput");
literalLogixNodes.Add(TypeCode.Single, "FloatInput");
literalLogixNodes.Add(TypeCode.Double, "DoubleInput");
literalLogixNodes.Add(TypeCode.Char, "CharInput");
literalLogixNodes.Add(TypeCode.String, "StringInput");
/* FIXME : Autodetect the type. Try automatic coercion if possible. */
binaryOperationsNodes.Add(SyntaxKind.AddExpression, "Add_Int");
binaryOperationsNodes.Add(SyntaxKind.SubtractExpression, "Sub_Int");
binaryOperationsNodes.Add(SyntaxKind.MultiplyExpression, "Mul_Float");
binaryOperationsNodes.Add(SyntaxKind.DivideExpression, "Div_Int");
binaryOperationsNodes.Add(SyntaxKind.BitwiseAndExpression, "AND_Bool");
binaryOperationsNodes.Add(SyntaxKind.GreaterThanExpression, "GreaterThan_Float");
binaryOperationsNodes.Add(SyntaxKind.GreaterThanOrEqualExpression, "GreaterOrEqual_Float");
binaryOperationsNodes.Add(SyntaxKind.EqualsExpression, "Equals_Float");
binaryOperationsNodes.Add(SyntaxKind.LessThanExpression, "LessThan_Float");
/* And you might wonder where the LesserThanExpression expression went ?
* WELL, it's not directly supported in LogiX.
* So we'll have to hack around with "NOT GREATER_THAN"
*/
typesList = new Dictionary<string, string>(16);
typesList.Add("byte", typeof(byte).FullName);
typesList.Add("short", typeof(short).FullName);
typesList.Add("ushort", typeof(ushort).FullName);
typesList.Add("char", typeof(char).FullName);
typesList.Add("int", typeof(int).FullName);
typesList.Add("uint", typeof(uint).FullName);
typesList.Add("long", typeof(long).FullName);
typesList.Add("ulong", typeof(ulong).FullName);
typesList.Add("float", typeof(float).FullName);
typesList.Add("double", typeof(double).FullName);
typesList.Add("string", typeof(string).FullName);
typesList.Add("object", typeof(object).FullName);
typesList.Add("Color", "BaseX.color");
script = new List<string>(512);
string programTitle = Base64Encode("Test program");
Emit($"PROGRAM \"{programTitle}\" 2");
nodePosition.X = 0;
nodePosition.Y = 0;
}
public LogixLocalVariables LocalsGet()
{
return locals[locals.Count - 1];
}
public bool LocalVariableValid(LogixLocalVariable localVar)
{
return localVar.definitionLevel >= 0;
}
public LogixLocalVariables LocalsContainingIdentifier(string identifier)
{
for (int level = currentBlockLevel; level >= 0; level--)
{
LogixLocalVariables levelVariables = locals[level];
if (levelVariables.HasIdentifier(identifier))
{
return levelVariables;
}
}
return null;
}
public LogixLocalVariable LocalsGetVariable(string name)
{
LogixLocalVariables vars = LocalsContainingIdentifier(name);
if (vars == null)
{
Error($"Unknown variable {name}");
}
return vars[name];
}
private LogixLocalVariables LocalsAdd()
{
LogixLocalVariables localVars = new LogixLocalVariables
{
level = currentBlockLevel
};
locals.Add(localVars);
return localVars;
}
public LogixLocalVariables LocalsPush()
{
currentBlockLevel++;
return LocalsAdd();
}
public LogixLocalVariables LocalsPop()
{
currentBlockLevel--;
LogixLocalVariables currentLevel = LocalsGet();
locals.RemoveAt(locals.Count - 1);
return currentLevel;
}
public LogixLocalVariable LocalAdd(string type, string name, int nodeID)
{
return LocalsGet().AddVariable(type, name, nodeID);
}
public LogixLocalVariable LocalsSetVar(string name, int nodeID)
{
LogixLocalVariables varsWithName = LocalsContainingIdentifier(name);
if (varsWithName == null)
{
Error($"Unknown variable {name}");
}
return varsWithName.SetVariable(name, nodeID, currentBlockLevel);
}
public void PositionNextBottom()
{
nodePosition.Y += 75;
}
public void PositionNextForward(int forward = 150)
{
nodePosition.X += forward;
nodePosition.Y = 0;
}
public void PositionSet(Vector2 position)
{
nodePosition = position;
}
public Vector2 PositionGet()
{
return nodePosition;
}
private string GetDefaultOutput(int inputNodeID)
{
return nodeDB.DefaultOutputFor(nodes.GetNode(inputNodeID).GenericTypeName());
}
private bool CurrentImpulseValid()
{
return currentImpulseOutputName != null;
}
private void ImpulseNext(int outputNodeID, string nextImpulseName)
{
currentImpulseOutputNode = outputNodeID;
currentImpulseOutputName = nextImpulseName;
}
private void ConnectImpulse(
int currentNodeID,
string currentMethodName,
int previousNodeID,
string previousOutputName)
{
Emit($"IMPULSE {currentNodeID} '{currentMethodName}' {previousNodeID} '{previousOutputName}'");
}
private void ConnectLastImpulse(int inputNodeID, string inputName, string nextImpulseName)
{
if (CurrentImpulseValid())
{
ConnectImpulse(inputNodeID, inputName, currentImpulseOutputNode, currentImpulseOutputName);
ImpulseNext(inputNodeID, nextImpulseName);
}
}
private void Connect(int inputNodeID, string inputName, int outputNodeID)
{
/* FIXME : Don't always expect the default output to be '*'.
* Get the information correctly
*/
string outputName = GetDefaultOutput(outputNodeID);
Emit($"INPUT {inputNodeID} '{inputName}' {outputNodeID} '{outputName}'");
}
private void Emit(string scriptLine)
{
script.Add(scriptLine);
Console.WriteLine(scriptLine);
}
private void EmitPosition(int nodeID)
{
Emit($"POS {nodeID} {((int)nodePosition.X)} {(int)nodePosition.Y}");
}
public int AddNode(string typename, string name)
{
int newID = nodes.Count;
string completeTypename = "FrooxEngine.LogiX." + typename;
Node node = new Node
{
typename = completeTypename
};
nodes.Add(node);
Emit($"NODE {newID} '{completeTypename}' \"{Base64Encode($"Node {newID} {name}")}\"");
EmitPosition(newID);
PositionNextBottom();
if (currentOperationNodes.Count > 0)
{
currentOperationNodes[currentOperationNodes.Count-1].Add(newID);
}
return newID;
}
public void AddToCurrentOperation(int id)
{
int currentOperandsListIndex = currentOperationNodes.Count - 1;
if (currentOperandsListIndex < 0)
{
return;
}
currentOperationNodes[currentOperandsListIndex].Add(id);
}
int CollectionPush()
{
int collectionIndex = currentOperationNodes.Count;
currentOperationNodes.Add(new OperationNodes());
return collectionIndex;
}
OperationNodes invalidCollection = new OperationNodes();
OperationNodes CollectionGetLast()
{
OperationNodes collection = invalidCollection;
if (currentOperationNodes.Count > 0)
collection = currentOperationNodes[currentOperationNodes.Count - 1];
return collection;
}
private void Error(string message)
{
throw new Exception(message);
}
OperationNodes CollectionPop()
{
int nCollections = currentOperationNodes.Count;
if (nCollections == 0)
{
Error("Popping more collections than pushed !");
}
var poppedCollection = CollectionGetLast();
currentOperationNodes.RemoveAt(nCollections - 1);
return poppedCollection;
}
bool CollectionIsValid(OperationNodes collection)
{
return collection != invalidCollection;
}
public string GetScript()
{
return String.Join("\n", script) + "\n";
}
private int DefineLiteral(Type type, object value)
{
int nodeID = -1;
Type valueType = value.GetType();
if (literalLogixNodes.TryGetValue(Type.GetTypeCode(valueType), out string logixInputType))
{
string logixType = "Input." + logixInputType;
string valueContent = value.ToString();
/*if (logixInputType == "FloatInput")
{
valueContent = valueContent.TrimEnd(new char[] { ' ', 'f' });
}*/
nodeID = AddNode(logixType, $"Literal {valueType.Name}");
Emit($"SETCONST {nodeID} \"{Base64Encode(valueContent)}\"");
}
else
{
Console.WriteLine($"Cannot handle {type} literals yet");
throw new Exception();
}
return nodeID;
}
int tabs = 0;
public override void Visit(SyntaxNode node)
{
Console.Write(new string('\t', tabs));
Console.WriteLine(node.Kind());
Console.Write(new string('\t', tabs));
Console.WriteLine(node.GetText(Encoding.UTF8).ToString());
tabs++;
base.Visit(node);
tabs--;
}
/* FIXME
* - Préparer un séquenceur pour les blocs de contrôles de flux
* - Laisser la première séquence du séquenceur vide, pour la
* gestion des checkpoints
* - Connecter les impulse des checkpoints depuis la première
* sortie du séquenceur, puis à chaque sortie du précédent
* checkpoint
*/
public int AddSequenceImpulse()
{
int sequencerID = AddNode("ProgramFlow.SequenceImpulse", "Branching");
return sequencerID;
}
public void SequenceStop()
{
currentSequenceID = -1;
}
public int WriteTo(int registerNodeID, string registerType, int fromValueID)
{
return WriteTo(registerNodeID, registerType, fromValueID, GetDefaultOutput(fromValueID));
}
public int WriteTo(int registerNodeID, string registerType, int fromValueID, string fromOutput)
{
/* FIXME : Get the typename from the register node */
int writeNodeID = AddNode($"Actions.WriteValueNode<{typesList[registerType]}>", "Register write");
Connect(writeNodeID, "Value", fromValueID);
Emit($"WRITE {registerNodeID} {writeNodeID}");
return writeNodeID;
}
private string LogixType(string cSharpTypeName)
{
return typesList[cSharpTypeName];
}
private int RegisterCreateFor(LogixLocalVariable variable)
{
int registerNodeID = AddNode(
$"Data.ValueRegister<{LogixType(variable.typeName)}>",
$"Saving {variable.typeName}");
return registerNodeID;
}
class FlowSequence
{
public int nodeID;
public int currentOutput;
public int users;
public static FlowSequence invalidSequence = InvalidSequence();
private static FlowSequence InvalidSequence()
{
var sequence = new FlowSequence()
{
nodeID = -1,
currentOutput = -1,
users = 0
};
return sequence;
}
public static FlowSequence Sequence(int sequencerNodeID)
{
var sequence = new FlowSequence()
{
nodeID = sequencerNodeID,
currentOutput = 0,
users = 0
};
return sequence;
}
public string Output(int index)
{
return $"Sequence[{index}";
}
public string CurrentOutput()
{
return Output(currentOutput);
}
public string NextOutput()
{
currentOutput += 1;
return CurrentOutput();
}
public void StartUsing()
{
users += 1;
}
public void StopUsing()
{
users -= 1;
if (users < 0)
{
Console.Error.WriteLine("[FlowSequence] Too many calls to StopUsing !");
users = 0;
}
}
}
class FlowSequences : List<FlowSequence>
{
public FlowSequence AtLevel(int level)
{
return (level < this.Count ? this[level] : null);
}
public FlowSequence DefineFor(int level, int nodeID)
{
while (this.Count < level)
{
Add(FlowSequence.invalidSequence);
}
var sequence = FlowSequence.Sequence(nodeID);
Add(sequence);
return sequence;
}
private bool SequenceAlreadyAvailable(int level)
{
return (this.Count > level && this[level] != FlowSequence.invalidSequence);
}
public void StartUsing(int level)
{
if (!SequenceAlreadyAvailable(level))
{
throw new Exception($"No sequence defined for level {level}");
}
AtLevel(level).StartUsing();
}
public void StopUsing(int level)
{
if (!SequenceAlreadyAvailable(level))
{
Console.Error.WriteLine($"Invalid call to StopUsing({level})");
return;
}
var flowSequence = AtLevel(level);
flowSequence.users--;