add some hacky code to allow passing sfc files with -b
[openc2e.git] / Engine.cpp
blob3fca23edd22bb714f5776f5dcee4ba6582485f85
1 /*
2 * Engine.cpp
3 * openc2e
5 * Created by Alyssa Milburn on Tue Nov 28 2006.
6 * Copyright (c) 2006-2008 Alyssa Milburn. All rights reserved.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation; either
11 * version 2 of the License, or (at your option) any later version.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
20 #include "Room.h"
21 #include "Engine.h"
22 #include "World.h"
23 #include "MetaRoom.h"
24 #include "caosVM.h" // for setupCommandPointers()
25 #include "caosScript.h" // for executeNetwork()
26 #include "PointerAgent.h"
27 #include "dialect.h" // registerDelegates
28 #include "NullBackend.h"
29 #include "NullAudioBackend.h"
30 #include "SFCFile.h"
32 #include <boost/filesystem/path.hpp>
33 #include <boost/filesystem/operations.hpp>
34 #include <boost/filesystem/convenience.hpp>
35 #include <boost/program_options.hpp>
36 #include <boost/format.hpp>
37 namespace fs = boost::filesystem;
38 namespace po = boost::program_options;
40 #ifndef _WIN32
41 #include <sys/types.h> // passwd*
42 #include <pwd.h> // getpwuid
43 #endif
45 #ifdef _WIN32
46 #include <shlobj.h>
47 #include <windows.h>
48 #endif
50 Engine engine;
52 Engine::Engine() {
53 done = false;
54 dorendering = true;
55 fastticks = false;
56 refreshdisplay = false;
58 bmprenderer = false;
60 tickdata = 0;
61 for (unsigned int i = 0; i < 10; i++) ticktimes[i] = 0;
62 ticktimeptr = 0;
63 version = 0; // TODO: something something
65 srand(time(NULL)); // good a place as any :)
67 cmdline_enable_sound = true;
68 cmdline_norun = false;
70 palette = 0;
72 addPossibleBackend("null", shared_ptr<Backend>(new NullBackend()));
73 addPossibleAudioBackend("null", shared_ptr<AudioBackend>(new NullAudioBackend()));
76 Engine::~Engine() {
79 void Engine::addPossibleBackend(std::string s, boost::shared_ptr<Backend> b) {
80 assert(!backend);
81 assert(b);
82 preferred_backend = s;
83 possible_backends[s] = b;
86 void Engine::addPossibleAudioBackend(std::string s, boost::shared_ptr<AudioBackend> b) {
87 assert(!audio);
88 assert(b);
89 preferred_audiobackend = s;
90 possible_audiobackends[s] = b;
93 void Engine::setBackend(shared_ptr<Backend> b) {
94 backend = b;
95 lasttimestamp = backend->ticks();
97 // load palette for C1
98 if (world.gametype == "c1") {
99 // TODO: case-sensitivity for the lose
100 fs::path palpath(world.data_directories[0] / "/Palettes/palette.dta");
101 if (fs::exists(palpath) && !fs::is_directory(palpath)) {
102 palette = new unsigned char[768];
104 std::ifstream f(palpath.native_directory_string().c_str(), std::ios::binary);
105 f >> std::noskipws;
106 f.read((char *)palette, 768);
108 for (unsigned int i = 0; i < 768; i++) {
109 palette[i] = palette[i] * 4;
112 backend->setPalette((uint8 *)palette);
113 } else
114 throw creaturesException("Couldn't find C1 palette data!");
118 std::string Engine::executeNetwork(std::string in) {
119 // now parse and execute the CAOS we obtained
120 caosVM vm(0); // needs to be outside 'try' so we can reset outputstream on exception
121 try {
122 std::istringstream s(in);
123 caosScript script(world.gametype, "<network>"); // XXX
124 script.parse(s);
125 script.installScripts();
126 std::ostringstream o;
127 vm.setOutputStream(o);
128 vm.runEntirely(script.installer);
129 vm.outputstream = 0; // otherwise would point to dead stack
130 return o.str();
131 } catch (std::exception &e) {
132 vm.outputstream = 0; // otherwise would point to dead stack
133 return std::string("### EXCEPTION: ") + e.what();
137 bool Engine::needsUpdate() {
138 return (!world.paused) && (fastticks || (backend->ticks() > (tickdata + world.ticktime)));
141 void Engine::update() {
142 tickdata = backend->ticks();
144 // tick the world
145 world.tick();
147 // draw the world
148 if (dorendering || refreshdisplay) {
149 refreshdisplay = false;
151 if (backend->selfRender()) {
152 // TODO: this makes race/pace hilariously inaccurate, since render time isn't included
153 backend->requestRender();
154 } else {
155 world.drawWorld();
159 // play C1 music
160 // TODO: this doesn't seem to actually be every 7 seconds, but actually somewhat random
161 // TODO: this should be linked to 'real' time, so it doesn't go crazy when game speed is modified
162 // TODO: is this the right place for this?
163 if (version == 1 && (world.tickcount % 70) == 0) {
164 int piece = 1 + (rand() % 28);
165 std::string filename = boost::str(boost::format("MU%02d") % piece);
166 boost::shared_ptr<AudioSource> s = world.playAudio(filename, AgentRef(), false, false, true);
167 if (s) s->setVolume(0.4f);
170 // update our data for things like pace, race, ticktime, etc
171 ticktimes[ticktimeptr] = backend->ticks() - tickdata;
172 ticktimeptr++;
173 if (ticktimeptr == 10) ticktimeptr = 0;
174 float avgtime = 0;
175 for (unsigned int i = 0; i < 10; i++) avgtime += ((float)ticktimes[i] / world.ticktime);
176 world.pace = avgtime / 10;
178 world.race = backend->ticks() - lasttimestamp;
179 lasttimestamp = backend->ticks();
182 bool Engine::tick() {
183 assert(backend);
184 backend->handleEvents();
186 // tick+draw the world, if necessary
187 bool needupdate = needsUpdate();
188 if (needupdate)
189 update();
191 processEvents();
192 if (needupdate)
193 handleKeyboardScrolling();
195 return needupdate;
198 void Engine::handleKeyboardScrolling() {
199 // keyboard-based scrolling
200 static float accelspeed = 8, decelspeed = .5, maxspeed = 64;
201 static float velx = 0;
202 static float vely = 0;
204 bool wasdMode = false;
205 caosVar v = world.variables["engine_wasd"];
206 if (v.hasInt()) {
207 switch (v.getInt()) {
208 case 1: // enable if CTRL is held
209 wasdMode = backend->keyDown(17); // CTRL
210 break;
211 case 2: // enable unconditionally
212 // (this needs agent support to suppress chat bubbles etc)
213 wasdMode = true;
214 break;
215 case 0: // disable
216 wasdMode = false;
217 break;
218 default: // disable
219 std::cout << "Warning: engine_wasd_scrolling is set to unknown value " << v.getInt() << std::endl;
220 world.variables["engine_wasd_scrolling"] = caosVar(0);
221 wasdMode = false;
222 break;
226 // check keys
227 bool leftdown = backend->keyDown(37)
228 || (wasdMode && a_down);
229 bool rightdown = backend->keyDown(39)
230 || (wasdMode && d_down);
231 bool updown = backend->keyDown(38)
232 || (wasdMode && w_down);
233 bool downdown = backend->keyDown(40)
234 || (wasdMode && s_down);
236 if (leftdown)
237 velx -= accelspeed;
238 if (rightdown)
239 velx += accelspeed;
240 if (!leftdown && !rightdown) {
241 velx *= decelspeed;
242 if (fabs(velx) < 0.1) velx = 0;
244 if (updown)
245 vely -= accelspeed;
246 if (downdown)
247 vely += accelspeed;
248 if (!updown && !downdown) {
249 vely *= decelspeed;
250 if (fabs(vely) < 0.1) vely = 0;
253 // enforced maximum speed
254 if (velx >= maxspeed) velx = maxspeed;
255 else if (velx <= -maxspeed) velx = -maxspeed;
256 if (vely >= maxspeed) vely = maxspeed;
257 else if (vely <= -maxspeed) vely = -maxspeed;
259 // do the actual movement
260 if (velx || vely) {
261 int adjustx = world.camera.getX(), adjusty = world.camera.getY();
262 int adjustbyx = (int)velx, adjustbyy = (int) vely;
264 world.camera.moveTo(adjustx + adjustbyx, adjusty + adjustbyy, jump);
268 void Engine::processEvents() {
269 SomeEvent event;
270 while (backend->pollEvent(event)) {
271 switch (event.type) {
272 case eventresizewindow:
273 handleResizedWindow(event);
274 break;
276 case eventmousemove:
277 handleMouseMove(event);
278 break;
280 case eventmousebuttonup:
281 case eventmousebuttondown:
282 handleMouseButton(event);
283 break;
285 case eventkeydown:
286 handleKeyDown(event);
287 break;
289 case eventspecialkeydown:
290 handleSpecialKeyDown(event);
291 break;
293 case eventspecialkeyup:
294 handleSpecialKeyUp(event);
295 break;
297 case eventquit:
298 done = true;
299 break;
301 default:
302 break;
307 void Engine::handleResizedWindow(SomeEvent &event) {
308 // notify agents
309 for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) {
310 if (!*i) continue;
311 (*i)->queueScript(123, 0); // window resized script
315 void Engine::handleMouseMove(SomeEvent &event) {
316 // move the cursor
317 world.hand()->handleEvent(event);
319 // notify agents
320 for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) {
321 if (!*i) continue;
322 if ((*i)->imsk_mouse_move) {
323 caosVar x; x.setFloat(world.hand()->pointerX());
324 caosVar y; y.setFloat(world.hand()->pointerY());
325 (*i)->queueScript(75, 0, x, y); // Raw Mouse Move
330 void Engine::handleMouseButton(SomeEvent &event) {
331 // notify agents
332 for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) {
333 if (!*i) continue;
334 if ((event.type == eventmousebuttonup && (*i)->imsk_mouse_up) ||
335 (event.type == eventmousebuttondown && (*i)->imsk_mouse_down)) {
336 // set the button value as necessary
337 caosVar button;
338 switch (event.button) { // Backend guarantees that only one button will be set on a mousebuttondown event.
339 // the values here make fuzzie suspicious that c2e combines these events
340 // nornagon seems to think c2e doesn't
341 case buttonleft: button.setInt(1); break;
342 case buttonright: button.setInt(2); break;
343 case buttonmiddle: button.setInt(4); break;
344 default: break;
347 // if it was a mouse button we're interested in, then fire the relevant raw event
348 if (button.getInt() != 0) {
349 if (event.type == eventmousebuttonup)
350 (*i)->queueScript(77, 0, button); // Raw Mouse Up
351 else
352 (*i)->queueScript(76, 0, button); // Raw Mouse Down
355 if ((event.type == eventmousebuttondown &&
356 (event.button == buttonwheelup || event.button == buttonwheeldown) &&
357 (*i)->imsk_mouse_wheel)) {
358 // fire the mouse wheel event with the relevant delta value
359 caosVar delta;
360 if (event.button == buttonwheeldown)
361 delta.setInt(-120);
362 else
363 delta.setInt(120);
364 (*i)->queueScript(78, 0, delta); // Raw Mouse Wheel
368 world.hand()->handleEvent(event);
371 void Engine::handleKeyDown(SomeEvent &event) {
372 switch (event.key) {
373 case 'w': w_down = true; break;
374 case 'a': a_down = true; break;
375 case 's': s_down = true; break;
376 case 'd': d_down = true; break;
379 // tell the agent with keyboard focus
380 if (world.focusagent) {
381 TextEntryPart *t = (TextEntryPart *)((CompoundAgent *)world.focusagent.get())->part(world.focuspart);
382 if (t)
383 t->handleKey(event.key);
386 // notify agents
387 caosVar k;
388 k.setInt(event.key);
389 for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) {
390 if (!*i) continue;
391 if ((*i)->imsk_translated_char)
392 (*i)->queueScript(79, 0, k); // translated char script
396 void Engine::handleSpecialKeyUp(SomeEvent &event) {
397 switch (event.key) {
398 case 0x57:
399 w_down = false;
400 break;
401 case 0x41:
402 a_down = false;
403 break;
404 case 0x53:
405 s_down = false;
406 break;
407 case 0x44:
408 d_down = false;
409 break;
413 void Engine::handleSpecialKeyDown(SomeEvent &event) {
414 switch (event.key) {
415 case 0x57:
416 w_down = true;
417 break;
418 case 0x41:
419 a_down = true;
420 break;
421 case 0x53:
422 s_down = true;
423 break;
424 case 0x44:
425 d_down = true;
426 break;
430 // handle debug keys, if they're enabled
431 caosVar v = world.variables["engine_debug_keys"];
432 if (v.hasInt() && v.getInt() == 1) {
433 if (backend->keyDown(16)) { // shift down
434 MetaRoom *n; // for pageup/pagedown
436 switch (event.key) {
437 case 45: // insert
438 world.showrooms = !world.showrooms;
439 break;
441 case 19: // pause
442 // TODO: debug pause game
443 break;
445 case 32: // space
446 // TODO: force tick
447 break;
449 case 33: // pageup
450 // TODO: previous metaroom
451 if ((world.map.getMetaRoomCount() - 1) == world.camera.getMetaRoom()->id)
452 break;
453 n = world.map.getMetaRoom(world.camera.getMetaRoom()->id + 1);
454 if (n)
455 world.camera.goToMetaRoom(n->id);
456 break;
458 case 34: // pagedown
459 // TODO: next metaroom
460 if (world.camera.getMetaRoom()->id == 0)
461 break;
462 n = world.map.getMetaRoom(world.camera.getMetaRoom()->id - 1);
463 if (n)
464 world.camera.goToMetaRoom(n->id);
465 break;
467 default: break; // to shut up warnings
472 // tell the agent with keyboard focus
473 if (world.focusagent) {
474 TextEntryPart *t = (TextEntryPart *)((CompoundAgent *)world.focusagent.get())->part(world.focuspart);
475 if (t)
476 t->handleSpecialKey(event.key);
479 // notify agents
480 caosVar k;
481 k.setInt(event.key);
482 for (std::list<boost::shared_ptr<Agent> >::iterator i = world.agents.begin(); i != world.agents.end(); i++) {
483 if (!*i) continue;
484 if ((*i)->imsk_key_down)
485 (*i)->queueScript(73, 0, k); // key down script
489 static const char data_default[] = "./data";
491 static void opt_version() {
492 // We already showed the primary version bit, just throw in some random legalese
493 std::cout <<
494 "This is free software; see the source for copying conditions. There is NO" << std::endl <<
495 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." << std::endl << std::endl <<
496 "...please don't sue us." << std::endl;
499 bool Engine::parseCommandLine(int argc, char *argv[]) {
500 // variables for command-line flags
501 int optret;
502 std::vector<std::string> data_vec;
504 // generate help for backend options
505 std::string available_backends;
506 for (std::map<std::string, boost::shared_ptr<Backend> >::iterator i = possible_backends.begin(); i != possible_backends.end(); i++) {
507 if (available_backends.empty()) available_backends = i->first;
508 else available_backends += ", " + i->first;
510 available_backends = "Select the backend (options: " + available_backends + "), default is " + preferred_backend;
512 std::string available_audiobackends;
513 for (std::map<std::string, boost::shared_ptr<AudioBackend> >::iterator i = possible_audiobackends.begin(); i != possible_audiobackends.end(); i++) {
514 if (available_audiobackends.empty()) available_audiobackends = i->first;
515 else available_audiobackends += ", " + i->first;
517 available_audiobackends = "Select the audio backend (options: " + available_audiobackends + "), default is " + preferred_audiobackend;
519 // parse the command-line flags
520 po::options_description desc;
521 desc.add_options()
522 ("help,h", "Display help on command-line options")
523 ("version,V", "Display openc2e version")
524 ("silent,s", "Disable all sounds")
525 ("backend,k", po::value<std::string>(&preferred_backend)->composing(), available_backends.c_str())
526 ("audiobackend,o", po::value<std::string>(&preferred_audiobackend)->composing(), available_audiobackends.c_str())
527 ("data-path,d", po::value< std::vector<std::string> >(&data_vec)->composing(),
528 "Sets or adds a path to a data directory")
529 ("bootstrap,b", po::value< std::vector<std::string> >(&cmdline_bootstrap)->composing(),
530 "Sets or adds a path or COS file to bootstrap from")
531 ("gametype,g", po::value< std::string >(&world.gametype), "Set the game type (c1, c2, cv or c3)")
532 ("gamename,m", po::value< std::string >(&gamename), "Set the game name")
533 ("norun,n", "Don't run the game, just execute scripts")
534 ("autokill,a", "Enable autokill")
535 ("autostop", "Enable autostop (or disable it, for CV)")
537 po::variables_map vm;
538 po::store(po::parse_command_line(argc, argv, desc), vm);
539 po::notify(vm);
541 cmdline_enable_sound = !vm.count("silent");
542 cmdline_norun = vm.count("norun");
544 if (vm.count("help")) {
545 std::cout << desc << std::endl;
546 return false;
549 if (vm.count("version")) {
550 opt_version();
551 return false;
554 if (vm.count("autokill")) {
555 world.autokill = true;
558 if (vm.count("autostop")) {
559 world.autostop = true;
562 if (vm.count("data-path") == 0) {
563 std::cout << "Warning: No data path specified, trying default of '" << data_default << "', see --help if you need to specify one." << std::endl;
564 data_vec.push_back(data_default);
567 // add all the data directories to the list
568 for (std::vector<std::string>::iterator i = data_vec.begin(); i != data_vec.end(); i++) {
569 fs::path datadir(*i, fs::native);
570 if (!fs::exists(datadir)) {
571 throw creaturesException("data path '" + *i + "' doesn't exist");
573 world.data_directories.push_back(datadir);
576 // make a vague attempt at blacklisting some characters inside the gamename
577 // (it's used in directory names, registry keys, etc)
578 std::string invalidchars = "\\/:*?\"<>|";
579 for (unsigned int i = 0; i < invalidchars.size(); i++) {
580 if (gamename.find(invalidchars[i]) != gamename.npos)
581 throw creaturesException(std::string("The character ") + invalidchars[i] + " is not valid in a gamename.");
584 return true;
587 bool Engine::initialSetup() {
588 assert(world.data_directories.size() > 0);
590 // autodetect gametype if necessary
591 if (world.gametype.empty()) {
592 std::cout << "Warning: No gametype specified, ";
593 // TODO: is this sane? especially unsure about about.exe
594 if (!world.findFile("Creatures.exe").empty()) {
595 std::cout << "found Creatures.exe, assuming C1 (c1)";
596 world.gametype = "c1";
597 } else if (!world.findFile("Creatures2.exe").empty()) {
598 std::cout << "found Creatures2.exe, assuming C2 (c2)";
599 world.gametype = "c2";
600 } else if (!world.findFile("Sea-Monkeys.ico").empty()) {
601 std::cout << "found Sea-Monkeys.ico, assuming Sea-Monkeys (sm)";
602 world.gametype = "sm";
603 } else if (!world.findFile("about.exe").empty()) {
604 std::cout << "found about.exe, assuming CA, CP or CV (cv)";
605 world.gametype = "cv";
606 } else {
607 std::cout << "assuming C3/DS (c3)";
608 world.gametype = "c3";
610 std::cout << ", see --help if you need to specify one." << std::endl;
613 // set engine version
614 // TODO: set gamename
615 if (world.gametype == "c1") {
616 if (gamename.empty()) gamename = "Creatures 1";
617 version = 1;
618 } else if (world.gametype == "c2") {
619 if (gamename.empty()) gamename = "Creatures 2";
620 version = 2;
621 } else if (world.gametype == "c3") {
622 if (gamename.empty()) gamename = "Creatures 3";
623 version = 3;
624 } else if (world.gametype == "cv") {
625 if (gamename.empty()) gamename = "Creatures Village";
626 version = 3;
627 world.autostop = !world.autostop;
628 } else if (world.gametype == "sm") {
629 if (gamename.empty()) gamename = "Sea-Monkeys";
630 version = 3;
631 bmprenderer = true;
632 } else
633 throw creaturesException(boost::str(boost::format("unknown gametype '%s'!") % world.gametype));
635 // finally, add our cache directory to the end
636 world.data_directories.push_back(storageDirectory());
638 // initial setup
639 registerDelegates();
640 std::cout << "* Reading catalogue files..." << std::endl;
641 world.initCatalogue();
642 std::cout << "* Initial setup..." << std::endl;
643 world.init(); // just reads mouse cursor (we want this after the catalogue reading so we don't play "guess the filename")
644 if (engine.version > 2) {
645 std::cout << "* Reading PRAY files..." << std::endl;
646 world.praymanager.update();
649 #ifdef _WIN32
650 // Here we need to set the working directory since apparently windows != clever
651 char exepath[MAX_PATH] = "";
652 GetModuleFileName(0, exepath, sizeof(exepath) - 1);
653 char *exedir = strrchr(exepath, '\\');
654 if(exedir) {
655 // null terminate the string
656 *exedir = 0;
657 // Set working directory
658 SetCurrentDirectory(exepath);
660 else // err, oops
661 std::cerr << "Warning: Setting working directory to " << exepath << " failed.";
662 #endif
664 if (cmdline_norun) preferred_backend = "null";
665 if (preferred_backend != "null") std::cout << "* Initialising backend " << preferred_backend << "..." << std::endl;
666 shared_ptr<Backend> b = possible_backends[preferred_backend];
667 if (!b) throw creaturesException("No such backend " + preferred_backend);
668 b->init(); setBackend(b);
669 possible_backends.clear();
671 if (cmdline_norun || !cmdline_enable_sound) preferred_audiobackend = "null";
672 if (preferred_audiobackend != "null") std::cout << "* Initialising audio backend " << preferred_audiobackend << "..." << std::endl;
673 shared_ptr<AudioBackend> a = possible_audiobackends[preferred_audiobackend];
674 if (!a) throw creaturesException("No such audio backend " + preferred_audiobackend);
675 try{
676 a->init(); audio = a;
677 } catch (creaturesException &e) {
678 std::cerr << "* Couldn't initialize backend " << preferred_audiobackend << ": " << e.what() << std::endl << "* Continuing without sound." << std::endl;
679 audio = shared_ptr<AudioBackend>(new NullAudioBackend());
680 audio->init();
682 possible_audiobackends.clear();
684 world.camera.setBackend(backend); // TODO: hrr
686 int listenport = backend->networkInit();
687 if (listenport != -1) {
688 // inform the user of the port used, and store it in the relevant file
689 std::cout << "Listening for connections on port " << listenport << "." << std::endl;
690 #ifndef _WIN32
691 fs::path p = fs::path(homeDirectory().native_directory_string() + "/.creaturesengine", fs::native);
692 if (!fs::exists(p))
693 fs::create_directory(p);
694 if (fs::is_directory(p)) {
695 std::ofstream f((p.native_directory_string() + "/port").c_str(), std::ios::trunc);
696 f << boost::str(boost::format("%d") % listenport);
698 #endif
701 if (world.data_directories.size() < 3) {
702 // TODO: This is a hack for DS, basically. Not sure if it works properly. - fuzzie
703 caosVar name; name.setString("engine_no_auxiliary_bootstrap_1");
704 caosVar contents; contents.setInt(1);
705 eame_variables[name] = contents;
708 // execute the initial scripts!
709 std::cout << "* Executing initial scripts..." << std::endl;
710 if (cmdline_bootstrap.size() == 0) {
711 world.executeBootstrap(false);
712 } else {
713 std::vector<std::string> scripts;
715 if (engine.version < 3 && cmdline_bootstrap.size() != 1)
716 throw creaturesException("multiple bootstrap files provided in C1/C2 mode");
718 for (std::vector< std::string >::iterator bsi = cmdline_bootstrap.begin(); bsi != cmdline_bootstrap.end(); bsi++) {
719 fs::path scriptdir(*bsi, fs::native);
720 if (engine.version > 2 || fs::extension(scriptdir) == ".cos") {
721 // pass it to the world to execute (it handles both files and directories)
723 if (!fs::exists(scriptdir)) {
724 std::cerr << "Warning: Couldn't find a specified script directory (trying " << *bsi << ")!\n";
725 continue;
728 world.executeBootstrap(scriptdir);
729 } else {
730 // in c1/c2 mode, if not a cos file, assume it's an SFC file
731 if (!fs::exists(scriptdir) || fs::is_directory(scriptdir))
732 throw creaturesException("non-existant bootstrap file provided in C1/C2 mode");
733 // TODO: the default SFCFile loading code is in World, maybe this should be too..
734 SFCFile sfc;
735 std::ifstream f(scriptdir.native_directory_string().c_str(), std::ios::binary);
736 f >> std::noskipws;
737 sfc.read(&f);
738 sfc.copyToWorld();
743 // if there aren't any metarooms, we can't run a useful game, the user probably
744 // wanted to execute a CAOS script or something went badly wrong.
745 if (!cmdline_norun && world.map.getMetaRoomCount() == 0) {
746 shutdown();
747 throw creaturesException("No metarooms found in given bootstrap directories or files");
750 std::cout << "* Done startup." << std::endl;
752 if (cmdline_norun) {
753 // TODO: see comment above about avoiding backend when norun is set
754 std::cout << "Told not to run the world, so stopping now." << std::endl;
755 shutdown();
756 return false;
759 return true;
762 void Engine::shutdown() {
763 world.shutdown();
764 backend->shutdown();
765 audio->shutdown();
766 freeDelegates(); // does nothing if there are none (ie, no call to initialSetup)
769 fs::path Engine::homeDirectory() {
770 fs::path p;
772 #ifndef _WIN32
773 char *envhome = getenv("HOME");
774 if (envhome)
775 p = fs::path(envhome, fs::native);
776 if ((!envhome) || (!fs::is_directory(p)))
777 p = fs::path(getpwuid(getuid())->pw_dir, fs::native);
778 if (!fs::is_directory(p)) {
779 std::cerr << "Can't work out what your home directory is, giving up and using /tmp for now." << std::endl;
780 p = fs::path("/tmp", fs::native); // sigh
782 #else
783 TCHAR szPath[_MAX_PATH];
784 SHGetSpecialFolderPath(NULL, szPath, CSIDL_PERSONAL, TRUE);
786 p = fs::path(szPath, fs::native);
787 if (!fs::exists(p) || !fs::is_directory(p))
788 throw creaturesException("Windows reported that your My Documents folder is at '" + std::string(szPath) + "' but there's no directory there!");
789 #endif
791 return p;
794 fs::path Engine::storageDirectory() {
795 #ifndef _WIN32
796 std::string dirname = "/.openc2e";
797 #else
798 std::string dirname = "/My Games";
799 #endif
801 // main storage dir
802 fs::path p = fs::path(homeDirectory().native_directory_string() + dirname, fs::native);
803 if (!fs::exists(p))
804 fs::create_directory(p);
805 else if (!fs::is_directory(p))
806 throw creaturesException("Your openc2e data directory " + p.native_directory_string() + " is a file, not a directory. That's bad.");
808 // game-specific storage dir
809 p = fs::path(p.native_directory_string() + std::string("/" + gamename), fs::native);
810 if (!fs::exists(p))
811 fs::create_directory(p);
812 else if (!fs::is_directory(p))
813 throw creaturesException("Your openc2e game data directory " + p.native_directory_string() + " is a file, not a directory. That's bad.");
815 return p;
818 /* vim: set noet: */