ScummVM API documentation
RunTime.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 QDENGINE_MINIGAMES_ADV_RUNTIME_H
23#define QDENGINE_MINIGAMES_ADV_RUNTIME_H
24
25#include "common/hashmap.h"
26
27#include "qdengine/minigames/adv/common.h"
28
29namespace Common {
30class SeekableReadStream;
31class SeekableWriteStream;
32}
33
34namespace QDEngine {
35
36class qdEngineInterface;
37class qdMinigameSceneInterface;
38
39class MinigameInterface;
40class TextManager;
41class TimeManager;
42class EventManager;
43class EffectManager;
44
46 mgVect3f crd;
47};
48
50 mgVect3f crd;
51};
52
55 int _sequenceIndex;
56 int _lastScore;
57 int _lastTime;
58 int _bestTime;
59 int _bestScore;
60
61 void write(Common::WriteStream &out) const;
62 void read(Common::ReadStream &out);
63};
64
65struct GameInfo {
66 GameInfo();
67 void persist(Common::SeekableReadStream &in);
68
69 void write(Common::WriteStream &out) const;
70 void read(Common::ReadStream &in);
71
72 void free();
73 static int version() {
74 return 9;
75 }
76 bool empty() const {
77 return _empty && _game._sequenceIndex < 0;
78 }
79
80 MinigameData _game;
81 bool _empty;
82 TimeManagerData _timeManagerData;
83 EffectManagerData _effectManagerData;
84 uint _dataSize;
85 void *_gameData;
86};
87
88typedef MinigameInterface *(*MinigameConsCallback)(MinigameManager *runtime);
89
90qdMiniGameInterface *create_adv_minigame(const char *name, MinigameConsCallback callback);
91
92bool close_adv_minigame(qdMiniGameInterface *game);
93
95 friend class TempValue;
96public:
97 MinigameManager(MinigameConsCallback callback);
99
100 // begin MiniGame virtual interface
101 bool init(const qdEngineInterface *engine_interface);
102 bool quant(float dt);
103 bool finit();
104
105 bool new_game(const qdEngineInterface *engine);
106 int save_game(const qdEngineInterface *engine, const qdMinigameSceneInterface *scene, char *buffer, int buffer_size);
107 int load_game(const qdEngineInterface *engine, const qdMinigameSceneInterface *scene, const char *buffer, int buffer_size);
108 // finish MiniGame virtual interface
109
110 // при необходимости заменяет на неизмененные предыдущим прохождением данные
111 bool processGameData(Common::SeekableReadStream &data);
112
113 mgVect2f mousePosition() const {
114 return _mousePos;
115 }
116 bool mouseLeftPressed() const;
117 bool mouseRightPressed() const;
118 bool keyPressed(int vKey, bool once = false) const;
119
120 mgVect2i screenSize() const {
121 return _screenSize;
122 }
123 float getTime() const {
124 return _gameTime;
125 }
126
127 GameInfo *getCurrentGameInfo() const { return _currentGameInfo; };
128 const MinigameData *getScore(int level, int game) const;
129
130 bool debugMode() const {
131 return _debugMode;
132 }
133
134 TextManager &textManager() const {
135 return *_textManager;
136 }
137
138 void signal(SystemEvent id);
139 void event(int eventID, const mgVect2f& pos, int factor = 1);
140 void event(int eventID, const mgVect2i& pos, int factor = 1) {
141 event(eventID, mgVect2f(pos.x, pos.y), factor);
142 }
143
144 // указывает вариант показа информации о победе (поворот собранной картинки и т.д.)
145 void setCompleteHelpVariant(int idx);
146 // указывает номер подсказки для показа, -1 - спрятать подсказку
147 void setGameHelpVariant(int idx);
148
149 // Возвращает параметр из прикрепленного к игре ini файла
150 const char *parameter(const char *name, bool required = true) const;
151 const char *parameter(const char *name, const char *def) const;
152
153 // Пересчитывает из экранных координат UI игры в 3D координаты R() объекта на мире
154 mgVect3f game2world(const mgVect3i &coord) const;
155 mgVect3f game2world(const mgVect3f &coord) const;
156 mgVect3f game2world(const mgVect2i &coord, int depth = 0) const;
157 mgVect3f game2world(const mgVect2f &coord, int depth = 0) const;
158 // Пересчитывает из мировых координат R() в 2D UI координаты и глубину
159 mgVect2f world2game(const mgVect3f& pos) const;
160 mgVect3f world2game(qdMinigameObjectInterface *obj) const;
161 // размер объекта
162 mgVect2f getSize(qdMinigameObjectInterface *obj) const;
163
164 // Меняет глубину объекта, не меняя его 2D положения на экране
165 void setDepth(qdMinigameObjectInterface *obj, int depth) const;
166 // Получает глубину объекта, чем меньше, тем ближе к игроку
167 float getDepth(qdMinigameObjectInterface *obj) const;
168 // Получает глубину точки, чем меньше, тем ближе к игроку
169 float getDepth(const mgVect3f& pos) const;
170
171 // получает интерфейс к динамическому игровому объекту по имени
172 QDObject getObject(const char *name) const;
173 // проверяет существование динамического объекта в сцене
174 bool testObject(const char *name) const;
175 // освобождает интерфейс
176 void release(QDObject& obj);
177
178 // задать текст для контрола
179 void setText(const char *name, const char *text) const;
180 void setText(const char *name, int toText, const char *format = "%d") const;
181
182 // спрятать объект за пределами экрана
183 void hide(qdMinigameObjectInterface *obj) const;
184
185 // случайное значение в диапазоне [min, max]
186 float rnd(float min, float max) const;
187 int rnd(int min, int max) const;
188 // случайный диапазон, из набора вероятностей
189 int rnd(const Std::vector<float> &prob) const;
190
191 // файл со списком игр по уровням
192 const char *gameListFileName() const {
193 return "resource/minigames.lst";
194 }
195
196 int getParameter(const char* name, const int& defValue);
197 bool getParameter(const char* name, int& out, bool obligatory);
198 float getParameter(const char* name, const float &defValue);
199 bool getParameter(const char* name, float &out, bool obligatory);
200 mgVect2f getParameter(const char* name, const mgVect2f& defValue);
201 bool getParameter(const char* name, mgVect2f& out, bool obligatory);
202 mgVect2i getParameter(const char* name, const mgVect2i& defValue);
203 bool getParameter(const char* name, mgVect2i& out, bool obligatory);
204
205private:
206 MinigameInterface *_game;
207
208 // Вывод текста с помощью объектов
209 TextManager *_textManager;
210 // Подсчет и визуализация времени
211 TimeManager *_timeManager;
212 // Обработка событий игры
213 EventManager *_eventManager;
214 // выводимые эффекты
215 EffectManager *_effectManager;
216
217 // Время в секундах с момента стара игры
218 float _gameTime;
219 // кеш проверенных на нажатие клавиш, для отслеживания непосредственно нажатия
220 mutable bool _lastKeyChecked[256];
221 // Размер играна
222 mgVect2i _screenSize;
223 // текущее положение мыши
224 mgVect2f _mousePos;
225 // подстройка мыши
226 mgVect2f _mouseAdjast;
227
228 // объект для передачи сигнала об окончании игры в триггеры
229 qdMinigameObjectInterface *_state_flag;
230 // объект для получения сигнала о постановке на паузу
231 qdMinigameObjectInterface *_pause_flag;
232 // справка по победе
233 QDObject _complete_help;
234 QDObject _complete_help_miniature;
235 // текущее состояние для включения справки
236 Common::String _complete_help_state_name;
237 // справка по игре
238 QDObject _game_help;
239 QDObject _game_help_trigger;
240 bool _game_help_enabled;
241 // текущее состояние для включения справки
242 Common::String _game_help_state_name;
243
244 // интерфейс к движку
245 const qdEngineInterface *_engine;
246 // интерфейс к текущей сцене
247 qdMinigameSceneInterface *_scene;
248
249 // игра запущена для отладки
250 bool _debugMode;
251 // rnd seed
252 int _seed;
253
254 // кнопки мыши инвертированы
255 bool _invertMouseButtons;
256
257 // имя файла и информацией о минииграх
258 Common::String _state_container_name;
259 // количество пройденных игр на каждом уровне
260 typedef Common::HashMap<int, int> Counters;
261 Counters _completeCounters;
262
263 struct GameInfoIndex {
264 GameInfoIndex(int idx, int level) : _gameNum(idx), _gameLevel(level) {}
265 int _gameNum;
266 int _gameLevel;
267
268 void write(Common::WriteStream &out) const;
269 void read(Common::ReadStream &in);
270
271 bool operator< (const GameInfoIndex& rs) const {
272 return _gameLevel == rs._gameLevel ? _gameNum < rs._gameNum : _gameLevel < rs._gameLevel;
273 }
274 };
275
276 struct GameInfoIndex_Hash {
277 uint operator()(const GameInfoIndex& x) const {
278 return (x._gameNum << 16) + x._gameLevel;
279 }
280 };
281
282 struct GameInfoIndex_EqualTo {
283 uint operator()(const GameInfoIndex& x, const GameInfoIndex& y) const {
284 return x._gameNum == y._gameNum && x._gameLevel == y._gameLevel;
285 }
286 };
287
288 // информация о пройденных играх
290 GameInfoMap _gameInfos;
291 // Информация о текущей игре, при выходе запишется
292 GameInfoIndex _currentGameIndex;
293 GameInfo *_currentGameInfo;
294
295 // проверить что все необходимые игры пройдены
296 bool testAllGamesWin();
297 // Непосредственно создает и инициализирует игру
298 bool createGame();
299 // обработка победы
300 void gameWin();
301 // обработка поражения
302 void gameLose();
303 // чтение данных об играх
304 bool loadState(bool current = true);
305 // сохранение данных в файл
306 void saveState(bool force = false);
307
308 // Полуить объект-счетчик
309 QDCounter getCounter(const char *name);
310 // Освободить счетчик
311 void release(QDCounter& counter);
312
313 MinigameConsCallback _callback = nullptr;
314};
315
316} // namespace QDEngine
317
318#endif // QDENGINE_MINIGAMES_ADV_RUNTIME_H
Definition: stream.h:385
Definition: stream.h:745
Definition: str.h:59
Definition: stream.h:77
Definition: MinigameInterface.h:27
Definition: RunTime.h:94
bool init(const qdEngineInterface *engine_interface)
Инициализация игры.
bool quant(float dt)
Обсчёт логики игры, параметр - время, которое должно пройти в игре (в секундах).
bool new_game(const qdEngineInterface *engine)
Инициализация миниигры, вызывается при старте и перезапуске игры.
int save_game(const qdEngineInterface *engine, const qdMinigameSceneInterface *scene, char *buffer, int buffer_size)
Сохранение данных, вызывается при сохранении сцены, на которую повешена миниигра.
int load_game(const qdEngineInterface *engine, const qdMinigameSceneInterface *scene, const char *buffer, int buffer_size)
Загрузка данных, вызывается при загрузке сцены, на которую повешена миниигра.
bool finit()
Деинициализация игры.
Definition: qd_minigame_interface.h:365
Definition: qd_minigame_interface.h:78
Интерфейс к сцене.
Definition: qd_minigame_interface.h:315
Definition: algorithm.h:29
Базовый класс для игровых ресурсов.
Definition: console.h:28
Definition: RunTime.h:49
Definition: RunTime.h:65
Definition: RunTime.h:53
Definition: RunTime.h:45