-
Notifications
You must be signed in to change notification settings - Fork 4
/
FiniteStateMachine.h
159 lines (136 loc) · 2.54 KB
/
FiniteStateMachine.h
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
#pragma once
#include <vector>
#include <map>
#include <string>
#include <cassert>
namespace Patterns
{
template <typename T>
class State
{
public:
// A functor for callbacks
class Functor
{
public:
virtual ~Functor() {}
template<typename T> void operator()(State<T>& state)
{
}
};
public:
// The ID of the state.
inline T getID()
{
return mID;
}
inline const std::string& getName() const
{
return mName;
}
explicit State(T id,
std::string name = "default",
Functor* onEnter = 0,
Functor* onExit = 0,
Functor* onUpdate = 0)
: mName(name)
, mID(id)
, mOnEnter (onEnter)
, mOnExit(onExit)
, mOnUpdate(onUpdate)
{
}
virtual void enter()
{
if (mOnEnter)
{
(*mOnEnter)(*this);
}
}
virtual void exit()
{
if (mOnExit)
{
(*mOnExit)(*this);
}
}
virtual void update()
{
if (mOnUpdate)
{
(*mOnUpdate)(*this);
}
}
private:
std::string mName;
T mID;
Functor* mOnEnter;
Functor* mOnExit;
Functor* mOnUpdate;
};
template <typename T>
class FiniteStateMachine
{
// A Finite State Machine
// - An FSM consists of a set of states,
// - and at any given time, an FSM can exist in only one
// State out of these possible set of states.
// A map to represent the a set of states.
protected:
std::map<T, State<T>*> mStates;
// The current state.
State<T>* mCurrentState;
public:
FiniteStateMachine()
: mCurrentState(0)
{
}
void add(State<T> *state)
{
if (state == 0)
return;
mStates[state->getID()] = state;
}
void add(T stateID, State<T>* state)
{
mStates.add(stateID, state);
}
State<T>* getState(T stateID)
{
return mStates[stateID];
}
State<T>* getCurrentState()
{
return mCurrentState;
}
void setCurrentState(T stateID)
{
State<T>* state = getState(stateID);
assert(state != 0);
setCurrentState(state);
}
void setCurrentState(State<T>* state)
{
if (mCurrentState == state)
{
return;
}
if (mCurrentState != 0)
{
mCurrentState->exit();
}
mCurrentState = state;
if (mCurrentState != 0)
{
mCurrentState->enter();
}
}
void update()
{
if (mCurrentState != 0)
{
mCurrentState->update();
}
}
};
}