ScummVM API documentation
statemachine.h
1 /* ScummVM - Graphic Adventure Engine
2  *
3  * ScummVM is the legal property of its developers, whose names
4  * are too numerous to list here. Please refer to the COPYRIGHT
5  * file distributed with this source distribution.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see <http://www.gnu.org/licenses/>.
19  *
20  */
21 
22 #ifndef MEDIASTATION_STATEMACHINE_H
23 #define MEDIASTATION_STATEMACHINE_H
24 
25 #include "common/textconsole.h"
26 #include "common/queue.h"
27 
28 namespace MediaStation {
29 
30 template<typename EventType>
32  EventType eventType;
33 };
34 
35 // The original had a very generalized finite state machine supported by state matrix, function pointer,
36 // and other classes, but that was judged needlessly complex to reimplement here. The state transition logic
37 // is embedded directly into this class.
38 template<typename StateType, typename EventType>
39 class StateMachine {
40 public:
41  virtual ~StateMachine() {};
42 
43  void queueEvent(EventType event);
44  void runIfNotNested();
45  void executeForever();
46 
47 protected:
48  StateType _currentState = StateType();
50  bool _handlingEvents = false;
51  virtual void executeNextState(EventType eventType) = 0;
52  void warnOnInvalidTransition(EventType eventType);
53 };
54 
55 template<typename StateType, typename EventType>
57  _events.push(event);
58 }
59 
60 template<typename StateType, typename EventType>
62  if (!_handlingEvents) {
63  _handlingEvents = true;
64  executeForever();
65  _handlingEvents = false;
66  }
67 }
68 
69 template<typename StateType, typename EventType>
71  while (!_events.empty()) {
72  EventType eventType = _events.pop();
73  executeNextState(eventType);
74  }
75 }
76 
77 template<typename StateType, typename EventType>
79  warning("Got invalid event %d for state %d", static_cast<uint>(eventType), static_cast<uint>(_currentState));
80 }
81 
82 } // End of namespace MediaStation
83 
84 #endif
Definition: actor.h:34
void warning(MSVC_PRINTF const char *s,...) GCC_PRINTF(1
Definition: statemachine.h:31
Definition: statemachine.h:39