File size: 2,351 Bytes
18a519f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System.Collections.Generic;

namespace Unity.VisualScripting
{
    [TypeIcon(typeof(IBranchUnit))]
    public abstract class SwitchUnit<T> : Unit, IBranchUnit
    {
        // Using L<KVP> instead of Dictionary to allow null key
        [DoNotSerialize]
        public List<KeyValuePair<T, ControlOutput>> branches { get; private set; }

        [Inspectable, Serialize]
        public List<T> options { get; set; } = new List<T>();

        /// <summary>
        /// The entry point for the switch.
        /// </summary>
        [DoNotSerialize]
        [PortLabelHidden]
        public ControlInput enter { get; private set; }

        /// <summary>
        /// The value on which to switch.
        /// </summary>
        [DoNotSerialize]
        [PortLabelHidden]
        public ValueInput selector { get; private set; }

        /// <summary>
        /// The branch to take if the input value does not match any other option.
        /// </summary>
        [DoNotSerialize]
        public ControlOutput @default { get; private set; }

        public override bool canDefine => options != null;

        protected override void Definition()
        {
            enter = ControlInput(nameof(enter), Enter);

            selector = ValueInput<T>(nameof(selector));

            Requirement(selector, enter);

            branches = new List<KeyValuePair<T, ControlOutput>>();

            foreach (var option in options)
            {
                var key = "%" + option;

                if (!controlOutputs.Contains(key))
                {
                    var branch = ControlOutput(key);
                    branches.Add(new KeyValuePair<T, ControlOutput>(option, branch));
                    Succession(enter, branch);
                }
            }

            @default = ControlOutput(nameof(@default));
            Succession(enter, @default);
        }

        protected virtual bool Matches(T a, T b)
        {
            return Equals(a, b);
        }

        public ControlOutput Enter(Flow flow)
        {
            var selector = flow.GetValue<T>(this.selector);

            foreach (var branch in branches)
            {
                if (Matches(branch.Key, selector))
                {
                    return branch.Value;
                }
            }

            return @default;
        }
    }
}