-
Notifications
You must be signed in to change notification settings - Fork 185
/
ale_interface.cpp
404 lines (356 loc) · 13.2 KB
/
ale_interface.cpp
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
/* *****************************************************************************
* The lines 201 - 204 are based on Xitari's code, from Google Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* *****************************************************************************
* A.L.E (Arcade Learning Environment)
* Copyright (c) 2009-2013 by Yavar Naddaf, Joel Veness, Marc G. Bellemare and
* the Reinforcement Learning and Artificial Intelligence Laboratory
* Released under the GNU General Public License; see License.txt for details.
*
* Based on: Stella -- "An Atari 2600 VCS Emulator"
* Copyright (c) 1995-2007 by Bradford W. Mott and the Stella team
*
* *****************************************************************************
* ale_interface.cpp
*
* The shared library interface.
**************************************************************************** */
#include "ale_interface.hpp"
#include <stddef.h>
#include <algorithm>
#include <cassert>
#include <cctype>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <iterator>
#include <sstream>
#include <stdexcept>
#include <vector>
#include "common/ColourPalette.hpp"
#include "common/Constants.h"
#include "emucore/Console.hxx"
#include "emucore/Props.hxx"
#include "environment/ale_screen.hpp"
#include "games/RomSettings.hpp"
using namespace ale;
// Display ALE welcome message
std::string ALEInterface::welcomeMessage() {
std::ostringstream oss;
oss << "A.L.E: Arcade Learning Environment (version " << Version << ")\n"
<< "[Powered by Stella]\n" << "Use -help for help screen.";
return oss.str();
}
void ALEInterface::disableBufferedIO() {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stdin, NULL, _IONBF, 0);
std::cin.rdbuf()->pubsetbuf(0, 0);
std::cout.rdbuf()->pubsetbuf(0, 0);
std::cin.sync_with_stdio();
std::cout.sync_with_stdio();
}
void ALEInterface::createOSystem(std::unique_ptr<OSystem> &theOSystem,
std::unique_ptr<Settings> &theSettings) {
#if (defined(WIN32) || defined(__MINGW32__))
theOSystem.reset(new OSystemWin32());
theSettings.reset(new SettingsWin32(theOSystem.get()));
#else
theOSystem.reset(new OSystemUNIX());
theSettings.reset(new SettingsUNIX(theOSystem.get()));
#endif
theOSystem->settings().loadConfig();
}
void ALEInterface::checkForUnsupportedRom(std::unique_ptr<OSystem>& theOSystem) {
const Properties properties = theOSystem->console().properties();
const std::string md5 = properties.get(Cartridge_MD5);
bool found = false;
std::ifstream ss("md5.txt");
std::string item;
while (!found && std::getline(ss, item)) {
if (!item.compare(0, md5.size(), md5)) {
const std::string rom_candidate = item.substr(md5.size() + 1);
found = true;
}
}
if (!found) {
// If the md5 doesn't match our master list, warn the user.
Logger::Warning << std::endl;
Logger::Warning << "WARNING: Possibly unsupported ROM: mismatched MD5." << std::endl;
Logger::Warning << "Cartridge_MD5: " << md5 << std::endl;
const std::string name = properties.get(Cartridge_Name);
Logger::Warning << "Cartridge_name: " << name << std::endl;
Logger::Warning << std::endl;
}
}
void ALEInterface::loadSettings(const std::string& romfile,
std::unique_ptr<OSystem> &theOSystem) {
// Load the configuration from a config file (passed on the command
// line), if provided
std::string configFile = theOSystem->settings().getString("config", false);
if (!configFile.empty()) {
theOSystem->settings().loadConfig(configFile.c_str());
}
theOSystem->settings().validate();
theOSystem->create();
// Attempt to load the ROM
if (romfile == "") {
Logger::Error << "No ROM File specified." << std::endl;
exit(1);
} else if (!FilesystemNode::fileExists(romfile)) {
Logger::Error << "ROM file " << romfile << " not found." << std::endl;
exit(1);
} else if (theOSystem->createConsole(romfile)) {
checkForUnsupportedRom(theOSystem);
Logger::Info << "Running ROM file..." << std::endl;
theOSystem->settings().setString("rom_file", romfile);
} else {
Logger::Error << "Unable to create console for " << romfile << std::endl;
exit(1);
}
// Must force the resetting of the OSystem's random seed, which is set before we change
// choose our random seed.
Logger::Info << "Random seed is "
<< theOSystem->settings().getInt("random_seed") << std::endl;
theOSystem->resetRNGSeed();
std::string currentDisplayFormat = theOSystem->console().getFormat();
theOSystem->colourPalette().setPalette("standard", currentDisplayFormat);
}
ALEInterface::ALEInterface() {
disableBufferedIO();
Logger::Info << welcomeMessage() << std::endl;
createOSystem(theOSystem, theSettings);
}
ALEInterface::ALEInterface(bool display_screen) {
disableBufferedIO();
Logger::Info << welcomeMessage() << std::endl;
createOSystem(theOSystem, theSettings);
this->setBool("display_screen", display_screen);
}
ALEInterface::~ALEInterface() {
}
// Loads and initializes a game. After this call the game should be
// ready to play. Resets the OSystem/Console/Environment/etc. This is
// necessary after changing a setting. Optionally specify a new rom to
// load.
void ALEInterface::loadROM(std::string rom_file = "") {
assert(theOSystem.get());
if (rom_file.empty()) {
rom_file = theOSystem->romFile();
}
loadSettings(rom_file, theOSystem);
romSettings.reset(buildRomRLWrapper(rom_file));
environment.reset(new StellaEnvironment(theOSystem.get(), romSettings.get()));
max_num_frames = theOSystem->settings().getInt("max_num_frames_per_episode");
environment->reset();
#ifndef __USE_SDL
if (theOSystem->p_display_screen != NULL) {
Logger::Error
<< "Screen display requires directive __USE_SDL to be defined." << std::endl;
Logger::Error << "Please recompile this code with flag '-D__USE_SDL'."
<< std::endl;
Logger::Error
<< "Also ensure ALE has been compiled with USE_SDL active (see ALE makefile)."
<< std::endl;
exit(1);
}
#endif
}
// Get the value of a setting.
std::string ALEInterface::getString(const std::string& key) {
assert(theSettings.get());
return theSettings->getString(key);
}
int ALEInterface::getInt(const std::string& key) {
assert(theSettings.get());
return theSettings->getInt(key);
}
bool ALEInterface::getBool(const std::string& key) {
assert(theSettings.get());
return theSettings->getBool(key);
}
float ALEInterface::getFloat(const std::string& key) {
assert(theSettings.get());
return theSettings->getFloat(key);
}
// Set the value of a setting.
void ALEInterface::setString(const std::string& key, const std::string& value) {
assert(theSettings.get());
assert(theOSystem.get());
theSettings->setString(key, value);
theSettings->validate();
}
void ALEInterface::setInt(const std::string& key, const int value) {
assert(theSettings.get());
assert(theOSystem.get());
theSettings->setInt(key, value);
theSettings->validate();
}
void ALEInterface::setBool(const std::string& key, const bool value) {
assert(theSettings.get());
assert(theOSystem.get());
theSettings->setBool(key, value);
theSettings->validate();
}
void ALEInterface::setFloat(const std::string& key, const float value) {
assert(theSettings.get());
assert(theOSystem.get());
theSettings->setFloat(key, value);
theSettings->validate();
}
// Resets the game, but not the full system.
void ALEInterface::reset_game() {
environment->reset();
}
// Indicates if the game has ended.
bool ALEInterface::game_over() const {
return environment->isTerminal();
}
// The remaining number of lives.
int ALEInterface::lives() {
if (!romSettings.get()) {
throw std::runtime_error("ROM not set");
}
return romSettings->lives();
}
// Applies an action to the game and returns the reward. It is the
// user's responsibility to check if the game has ended and reset
// when necessary - this method will keep pressing buttons on the
// game over screen.
reward_t ALEInterface::act(Action action) {
reward_t reward = environment->act(action, PLAYER_B_NOOP);
if (theOSystem->p_display_screen != NULL) {
theOSystem->p_display_screen->display_screen();
while (theOSystem->p_display_screen->manual_control_engaged()) {
Action user_action = theOSystem->p_display_screen->getUserAction();
reward += environment->act(user_action, PLAYER_B_NOOP);
theOSystem->p_display_screen->display_screen();
}
}
return reward;
}
// Returns the vector of modes available for the current game.
// This should be called only after the rom is loaded.
ModeVect ALEInterface::getAvailableModes() {
return romSettings->getAvailableModes();
}
// Sets the mode of the game.
// The mode must be an available mode.
// This should be called only after the rom is loaded.
void ALEInterface::setMode(game_mode_t m) {
//We first need to make sure m is an available mode
ModeVect available = romSettings->getAvailableModes();
if(find(available.begin(), available.end(), m) != available.end()) {
environment->setMode(m);
} else {
throw std::runtime_error("Invalid game mode requested");
}
}
//Returns the vector of difficulties available for the current game.
//This should be called only after the rom is loaded.
DifficultyVect ALEInterface::getAvailableDifficulties() {
return romSettings->getAvailableDifficulties();
}
// Sets the difficulty of the game.
// The difficulty must be an available mode.
// This should be called only after the rom is loaded.
void ALEInterface::setDifficulty(difficulty_t m) {
DifficultyVect available = romSettings->getAvailableDifficulties();
if(find(available.begin(), available.end(), m) != available.end()) {
environment->setDifficulty(m);
} else {
throw std::runtime_error("Invalid difficulty requested");
}
}
// Returns the vector of legal actions. This should be called only
// after the rom is loaded.
ActionVect ALEInterface::getLegalActionSet() {
if (!romSettings.get()) {
throw std::runtime_error("ROM not set");
}
return romSettings->getAllActions();
}
// Returns the vector of the minimal set of actions needed to play
// the game.
ActionVect ALEInterface::getMinimalActionSet() {
if (!romSettings.get()) {
throw std::runtime_error("ROM not set");
}
return romSettings->getMinimalActionSet();
}
// Returns the frame number since the loading of the ROM
int ALEInterface::getFrameNumber() {
return environment->getFrameNumber();
}
// Returns the frame number since the start of the current episode
int ALEInterface::getEpisodeFrameNumber() const {
return environment->getEpisodeFrameNumber();
}
// Returns the current game screen
const ALEScreen& ALEInterface::getScreen() {
return environment->getScreen();
}
//This method should receive an empty vector to fill it with
//the grayscale colours
void ALEInterface::getScreenGrayscale(
std::vector<unsigned char>& grayscale_output_buffer) {
size_t w = environment->getScreen().width();
size_t h = environment->getScreen().height();
size_t screen_size = w * h;
pixel_t *ale_screen_data = environment->getScreen().getArray();
theOSystem->colourPalette().applyPaletteGrayscale(grayscale_output_buffer,
ale_screen_data, screen_size);
}
//This method should receive a vector to fill it with
//the RGB colours. The first positions contain the red colours,
//followed by the green colours and then the blue colours
void ALEInterface::getScreenRGB(std::vector<unsigned char>& output_rgb_buffer) {
size_t w = environment->getScreen().width();
size_t h = environment->getScreen().height();
size_t screen_size = w * h;
pixel_t *ale_screen_data = environment->getScreen().getArray();
theOSystem->colourPalette().applyPaletteRGB(output_rgb_buffer, ale_screen_data, screen_size);
}
// Returns the current RAM content
const ALERAM& ALEInterface::getRAM() {
return environment->getRAM();
}
// Saves the state of the system
void ALEInterface::saveState() {
environment->save();
}
// Loads the state of the system
void ALEInterface::loadState() {
environment->load();
}
ALEState ALEInterface::cloneState() {
return environment->cloneState();
}
void ALEInterface::restoreState(const ALEState& state) {
return environment->restoreState(state);
}
ALEState ALEInterface::cloneSystemState() {
return environment->cloneSystemState();
}
void ALEInterface::restoreSystemState(const ALEState& state) {
return environment->restoreSystemState(state);
}
void ALEInterface::saveScreenPNG(const std::string& filename) {
ScreenExporter exporter(theOSystem->colourPalette());
exporter.save(environment->getScreen(), filename);
}
ScreenExporter *ALEInterface::createScreenExporter(
const std::string &filename) const {
return new ScreenExporter(theOSystem->colourPalette(), filename);
}