A game about forced loneliness, made by TACStudios
1using System.Collections.Generic;
2
3namespace Unity.VisualScripting
4{
5 [TypeIcon(typeof(IBranchUnit))]
6 public abstract class SwitchUnit<T> : Unit, IBranchUnit
7 {
8 // Using L<KVP> instead of Dictionary to allow null key
9 [DoNotSerialize]
10 public List<KeyValuePair<T, ControlOutput>> branches { get; private set; }
11
12 [Inspectable, Serialize]
13 public List<T> options { get; set; } = new List<T>();
14
15 /// <summary>
16 /// The entry point for the switch.
17 /// </summary>
18 [DoNotSerialize]
19 [PortLabelHidden]
20 public ControlInput enter { get; private set; }
21
22 /// <summary>
23 /// The value on which to switch.
24 /// </summary>
25 [DoNotSerialize]
26 [PortLabelHidden]
27 public ValueInput selector { get; private set; }
28
29 /// <summary>
30 /// The branch to take if the input value does not match any other option.
31 /// </summary>
32 [DoNotSerialize]
33 public ControlOutput @default { get; private set; }
34
35 public override bool canDefine => options != null;
36
37 protected override void Definition()
38 {
39 enter = ControlInput(nameof(enter), Enter);
40
41 selector = ValueInput<T>(nameof(selector));
42
43 Requirement(selector, enter);
44
45 branches = new List<KeyValuePair<T, ControlOutput>>();
46
47 foreach (var option in options)
48 {
49 var key = "%" + option;
50
51 if (!controlOutputs.Contains(key))
52 {
53 var branch = ControlOutput(key);
54 branches.Add(new KeyValuePair<T, ControlOutput>(option, branch));
55 Succession(enter, branch);
56 }
57 }
58
59 @default = ControlOutput(nameof(@default));
60 Succession(enter, @default);
61 }
62
63 protected virtual bool Matches(T a, T b)
64 {
65 return Equals(a, b);
66 }
67
68 public ControlOutput Enter(Flow flow)
69 {
70 var selector = flow.GetValue<T>(this.selector);
71
72 foreach (var branch in branches)
73 {
74 if (Matches(branch.Key, selector))
75 {
76 return branch.Value;
77 }
78 }
79
80 return @default;
81 }
82 }
83}