summaryrefslogtreecommitdiff
path: root/Other/NodeEditorExamples/Assets/UNEB/Utility/StateMachine.cs
blob: 9c3a89922169d0e5b70321d9b019f21044213f35 (plain)
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
using UnityEngine;
using System;
using System.Collections.Generic;

namespace Bonsai.Utility
{
    /// <summary>
    /// A finite state machine.
    /// </summary>
    /// <typeparam name="T">The date type to be stored by the machine states.</typeparam>
    public class StateMachine<T>
    {
        /// <summary>
        /// An event that fires when the machine finishes transitioning to another state.
        /// </summary>
        public event Action OnStateChangedEvent = delegate { };

        protected Dictionary<T, State> _states = new Dictionary<T, State>();

        /// <summary>
        /// Get all the state data.
        /// </summary>
        /// <returns></returns>
        public IEnumerable<T> Data()
        {
            return _states.Keys;
        }

        protected State _currentState;

        public State CurrentState
        {
            get { return _currentState; }
        }

        /// <summary>
        /// Adds a state to the machine.
        /// </summary>
        /// <param name="data"></param>
        public void AddState(T data)
        {
            var s = new State(data);
            _states.Add(data, s); ;
        }

        public void AddState(State s)
        {
            _states.Add(s.Value, s);
        }

        public void AddTransition(State start, State end, Func<bool> condition, Func<bool> onMakingTransition)
        {
            var t = new Transition(condition);
            t.onMakingTransition = onMakingTransition;

            AddTransition(start, end, t);
        }

        public void AddTransition(State start, State end, Transition t)
        {
            start.Add(t);
            t.SetNextState(end);
        }

        /// <summary>
        /// Add a transition that goes from start to end state.
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="t"></param>
        public void AddTransition(T start, T end, Transition t)
        {
            var startST = GetState(start);
            var endST = GetState(end);

            if (startST == null || endST == null) {
                Debug.LogError("State(s) are not in the state machine");
                return;
            }

            AddTransition(startST, endST, t);
        }

        /// <summary>
        /// Add two transitions.
        /// One from start to end.
        /// Another from end to start.
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <param name="startToEnd"></param>
        /// <param name="endToStart"></param>
        public void AddBiTransition(T start, T end, Transition startToEnd, Transition endToStart)
        {
            var startST = GetState(start);
            var endST = GetState(end);

            if (startST == null || endST == null) {
                Debug.LogError("State(s) are not in the state machine");
                return;
            }

            AddTransition(startST, endST, startToEnd);
            AddTransition(endST, startST, endToStart);
        }

        /// <summary>
        /// Gets the state associated with the data.
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        public State GetState(T data)
        {
            if (_states.ContainsKey(data)) {
                return _states[data];
            }

            return null;
        }

        /// <summary>
        /// Sets the current active state of the machine.
        /// </summary>
        /// <param name="data"></param>
        public void SetCurrentState(T data)
        {

            var state = GetState(data);

            if (state == null) {
                Debug.LogError(data + " is not in the state machine.");
            }

            else {
                _currentState = state;
            }
        }

        /// <summary>
        /// Handles moving to next state when conditions are met.
        /// </summary>
        public void Update()
        {
            if (_currentState == null) {
                return;
            }

            Transition validTrans = null;

            // Pick the next state if the transition conditions are met.
            for (int i = 0; i < _currentState.Transitions.Count; i++) {

                if (_currentState.Transitions[i].AllConditionsMet()) {
                    validTrans = _currentState.Transitions[i];
                    break;
                }
            }

            if (validTrans != null) {

                // Call on making transition.
                if (validTrans.onMakingTransition()) {

                    // Call on state exit.
                    if (_currentState.onStateExit != null)
                        _currentState.onStateExit();

                    // Change the state to the next one.
                    _currentState = validTrans.NextState;

                    // Call on state enter.
                    if (_currentState.onStateEnter != null)
                        _currentState.onStateEnter();

                    OnStateChangedEvent();
                }
            }
        }

        /// <summary>
        /// A transition between two states than only occurs if all
        /// its conditions are satisfied.
        /// </summary>
        public class Transition
        {
            private State _nextState = null;
            private List<Func<bool>> _conditions = new List<Func<bool>>();

            /// <summary>
            /// Called after the 'from' state exits and before the 'to' state enters.
            /// If this fails, then it goes back to the starting state.
            /// </summary>
            public Func<bool> onMakingTransition = () => { return true; };

            public Transition()
            {

            }

            /// <summary>
            /// Pass in initial conditions
            /// </summary>
            /// <param name="?"></param>
            public Transition(params Func<bool>[] conditions)
            {
                foreach (var c in conditions) {
                    AddCondition(c);
                }
            }

            /// <summary>
            /// Adds a condition that must be satisfied in order to do the transition.
            /// </summary>
            /// <param name="cond"></param>
            public void AddCondition(Func<bool> cond)
            {
                _conditions.Add(cond);
            }

            /// <summary>
            /// Tests if all the conditions of the transition are satisfied.
            /// </summary>
            /// <returns></returns>
            public bool AllConditionsMet()
            {
                for (int i = 0; i < _conditions.Count; i++) {

                    if (!_conditions[i]()) return false;
                }

                // All conditions returned true.
                return true;
            }

            /// <summary>
            /// Set the state that transition goes to.
            /// </summary>
            /// <param name="next"></param>
            public void SetNextState(State next)
            {
                _nextState = next;
            }

            /// <summary>
            /// The state that transition goes to.
            /// </summary>
            public State NextState
            {
                get { return _nextState; }
            }
        }

        /// <summary>
        /// A state of the machine.
        /// </summary>
        public class State
        {
            private T _data;
            private List<Transition> _transitions = new List<Transition>();

            /// <summary>
            /// Executes when the machine transitions into this state.
            /// </summary>
            public Action onStateEnter;

            /// <summary>
            /// Executes when the machine transitions out of this state.
            /// </summary>
            public Action onStateExit;

            /// <summary>
            /// Construct a state with its data.
            /// </summary>
            /// <param name="data"></param>
            public State(T data)
            {
                _data = data;
            }

            /// <summary>
            /// Adds a transition to the state.
            /// </summary>
            /// <param name="t"></param>
            public void Add(Transition t)
            {
                _transitions.Add(t);
            }

            /// <summary>
            /// The data held by the state.
            /// </summary>
            public T Value { get { return _data; } }

            /// <summary>
            /// The transitions connected to the state.
            /// </summary>
            public List<Transition> Transitions { get { return _transitions; } }
        }
    }
}