4 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
31 #include <sys/types.h>
35 //#include <SDL_image.h>
38 namespace supertux_apple {
39 #include <CoreFoundation/CoreFoundation.h>
43 #include <unison/video/Window.hpp>
44 #include <unison/vfs/FileSystem.hpp>
46 #include "gameconfig.hpp"
47 #include "resources.hpp"
48 #include "gettext.hpp"
49 #include "audio/sound_manager.hpp"
50 #include "video/surface.hpp"
51 //#include "video/texture_manager.hpp"
52 #include "video/drawing_context.hpp"
53 #include "video/glutil.hpp"
54 #include "control/joystickkeyboardcontroller.hpp"
55 #include "options_menu.hpp"
56 #include "mainloop.hpp"
58 #include "game_session.hpp"
59 #include "scripting/level.hpp"
60 #include "scripting/squirrel_util.hpp"
61 #include "file_system.hpp"
62 #include "physfs/physfs_sdl.hpp"
63 #include "random_generator.hpp"
64 #include "worldmap/worldmap.hpp"
65 #include "binreloc/binreloc.h"
67 namespace { DrawingContext *context_pointer; }
69 JoystickKeyboardController* main_controller = 0;
70 TinyGetText::DictionaryManager dictionary_manager;
75 static void init_config()
77 config = new Config();
80 } catch(std::exception& e) {
81 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
85 static void init_tinygettext()
87 dictionary_manager.add_directory("locale");
88 dictionary_manager.set_charset("UTF-8");
90 // Config setting "locale" overrides language detection
91 if (config->locale != "") {
92 dictionary_manager.set_language( config->locale );
96 static void init_physfs(const char* argv0)
98 Unison::VFS::FileSystem &fs = Unison::VFS::FileSystem::get();
99 std::string application = "supertux2";
100 std::string userdir = fs.get_user_dir();
101 std::string dirsep = fs.get_dir_sep();
102 std::string writedir = userdir + "." + application;
103 fs.set_write_dir(writedir);
104 fs.mount(writedir, "/", true);
106 // Search for archives and add them to the search path
107 const char* archiveExt = ".zip";
108 std::vector<std::string> rc = fs.ls("/");
109 for(std::vector<std::string>::iterator iter = rc.begin(); iter != rc.end(); ++iter)
111 std::string ext = iter->substr(iter->length() - 4);
112 if(strcasecmp(ext.c_str(), archiveExt) == 0)
114 std::string dir = fs.get_real_dir(*iter);
115 fs.mount(dir + fs.get_dir_sep() + *iter, "/", true);
119 // when started from source dir...
120 std::string dir = fs.get_base_dir();
122 std::string testfname = dir;
123 testfname += "/credits.txt";
124 bool sourcedir = false;
125 FILE* f = fopen(testfname.c_str(), "r");
128 fs.mount(dir, "/", true);
130 /*if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
131 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
138 // when started from Application file on Mac OS X...
140 CFBundleRef mainBundle = CFBundleGetMainBundle();
141 assert(mainBundle != 0);
142 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
143 assert(mainBundleURL != 0);
144 CFStringRef pathStr = CFUrlCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
145 assert(pathStr != 0);
146 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
147 CFRelease(mainBundleURL);
150 dir = std::string(path) + "/Contents/Resources/data";
151 testfname = dir + "/credits.txt";
153 f = fopen(testfname.c_str(), "r");
156 fs.mount(dir, "/", true);
158 /*if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
159 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
167 fs.mount(".\\data", "/", true);
168 //PHYSFS_addToSearchPath(".\\data", 1);
172 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
174 #ifdef ENABLE_BINRELOC
178 dir = br_find_data_dir(APPDATADIR);
183 datadir = APPDATADIR;
186 datadir += application;
187 fs.mount(datadir, "/", true);
188 /*if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
189 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
194 // allow symbolic links
195 //PHYSFS_permitSymbolicLinks(1);
196 //fs.follow_sym_links(true);
199 std::vector<std::string> searchpath = fs.get_search_path();
200 for(std::vector<std::string>::iterator iter = searchpath.begin(); iter != searchpath.end(); ++iter)
201 log_info << "[" << *iter << "] is in the search path" << std::endl;
203 char** searchpath = PHYSFS_getSearchPath();
204 for(char** i = searchpath; *i != NULL; i++)
205 log_info << "[" << *i << "] is in the search path" << std::endl;
206 PHYSFS_freeList(searchpath);
210 if(!PHYSFS_init(argv0)) {
211 std::stringstream msg;
212 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
213 throw std::runtime_error(msg.str());
216 // Initialize physfs (this is a slightly modified version of
217 // PHYSFS_setSaneConfig
218 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
219 const char* userdir = PHYSFS_getUserDir();
220 const char* dirsep = PHYSFS_getDirSeparator();
221 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
223 // Set configuration directory
224 sprintf(writedir, "%s.%s", userdir, application);
225 if(!PHYSFS_setWriteDir(writedir)) {
226 // try to create the directory
227 char* mkdir = new char[strlen(application) + 2];
228 sprintf(mkdir, ".%s", application);
229 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
230 std::ostringstream msg;
231 msg << "Failed creating configuration directory '"
232 << writedir << "': " << PHYSFS_getLastError();
235 throw std::runtime_error(msg.str());
239 if(!PHYSFS_setWriteDir(writedir)) {
240 std::ostringstream msg;
241 msg << "Failed to use configuration directory '"
242 << writedir << "': " << PHYSFS_getLastError();
244 throw std::runtime_error(msg.str());
247 PHYSFS_addToSearchPath(writedir, 0);
250 // Search for archives and add them to the search path
251 const char* archiveExt = "zip";
252 char** rc = PHYSFS_enumerateFiles("/");
253 size_t extlen = strlen(archiveExt);
255 for(char** i = rc; *i != 0; ++i) {
256 size_t l = strlen(*i);
257 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
258 const char* ext = (*i) + (l - extlen);
259 if(strcasecmp(ext, archiveExt) == 0) {
260 const char* d = PHYSFS_getRealDir(*i);
261 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
262 sprintf(str, "%s%s%s", d, dirsep, *i);
263 PHYSFS_addToSearchPath(str, 1);
271 // when started from source dir...
272 std::string dir = PHYSFS_getBaseDir();
274 std::string testfname = dir;
275 testfname += "/credits.txt";
276 bool sourcedir = false;
277 FILE* f = fopen(testfname.c_str(), "r");
280 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
281 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
289 using namespace supertux_apple;
291 // when started from Application file on Mac OS X...
293 CFBundleRef mainBundle = CFBundleGetMainBundle();
294 assert(mainBundle != 0);
295 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
296 assert(mainBundleURL != 0);
297 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
298 assert(pathStr != 0);
299 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
300 CFRelease(mainBundleURL);
303 dir = std::string(path) + "/Contents/Resources/data";
304 testfname = dir + "/credits.txt";
306 f = fopen(testfname.c_str(), "r");
309 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
310 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
319 PHYSFS_addToSearchPath(".\\data", 1);
323 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
325 #ifdef ENABLE_BINRELOC
329 dir = br_find_data_dir(APPDATADIR);
334 datadir = APPDATADIR;
337 datadir += application;
338 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
339 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
344 // allow symbolic links
345 PHYSFS_permitSymbolicLinks(1);
348 char** searchpath = PHYSFS_getSearchPath();
349 for(char** i = searchpath; *i != NULL; i++)
350 log_info << "[" << *i << "] is in the search path" << std::endl;
351 PHYSFS_freeList(searchpath);
355 static void print_usage(const char* argv0)
357 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
360 " -f, --fullscreen Run in fullscreen mode\n"
361 " -w, --window Run in window mode\n"
362 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
363 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
364 " --disable-sfx Disable sound effects\n"
365 " --disable-music Disable music\n"
366 " --help Show this help message\n"
367 " --version Display SuperTux version and quit\n"
368 " --console Enable ingame scripting console\n"
369 " --noconsole Disable ingame scripting console\n"
370 " --show-fps Display framerate in levels\n"
371 " --no-show-fps Do not display framerate in levels\n"
372 " --record-demo FILE LEVEL Record a demo to FILE\n"
373 " --play-demo FILE LEVEL Play a recorded demo\n"
378 * Options that should be evaluated prior to any initializations at all go here
380 static bool pre_parse_commandline(int argc, char** argv)
382 for(int i = 1; i < argc; ++i) {
383 std::string arg = argv[i];
385 if(arg == "--version") {
386 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
395 * Options that should be evaluated after config is read go here
397 static bool parse_commandline(int argc, char** argv)
399 for(int i = 1; i < argc; ++i) {
400 std::string arg = argv[i];
402 if(arg == "--help") {
403 print_usage(argv[0]);
405 } else if(arg == "--fullscreen" || arg == "-f") {
406 config->use_fullscreen = true;
407 } else if(arg == "--window" || arg == "-w") {
408 config->use_fullscreen = false;
409 } else if(arg == "--geometry" || arg == "-g") {
411 print_usage(argv[0]);
412 throw std::runtime_error("Need to specify a parameter for geometry switch");
414 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
416 print_usage(argv[0]);
417 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
419 } else if(arg == "--aspect" || arg == "-a") {
421 print_usage(argv[0]);
422 throw std::runtime_error("Need to specify a parameter for aspect switch");
424 if(strcasecmp(argv[i+1], "auto") == 0) {
426 config->aspect_ratio = -1;
428 int aspect_width, aspect_height;
429 if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
430 print_usage(argv[0]);
431 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
433 config->aspect_ratio = static_cast<double>(aspect_width) /
434 static_cast<double>(aspect_height);
436 } else if(arg == "--show-fps") {
437 config->show_fps = true;
438 } else if(arg == "--no-show-fps") {
439 config->show_fps = false;
440 } else if(arg == "--console") {
441 config->console_enabled = true;
442 } else if(arg == "--noconsole") {
443 config->console_enabled = false;
444 } else if(arg == "--disable-sfx") {
445 config->sound_enabled = false;
446 } else if(arg == "--disable-music") {
447 config->music_enabled = false;
448 } else if(arg == "--play-demo") {
450 print_usage(argv[0]);
451 throw std::runtime_error("Need to specify a demo filename");
453 config->start_demo = argv[++i];
454 } else if(arg == "--record-demo") {
456 print_usage(argv[0]);
457 throw std::runtime_error("Need to specify a demo filename");
459 config->record_demo = argv[++i];
460 } else if(arg == "-d") {
461 config->enable_script_debugger = true;
462 } else if(arg[0] != '-') {
463 config->start_level = arg;
465 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
473 static void init_sdl()
475 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
476 std::stringstream msg;
477 msg << "Couldn't initialize SDL: " << SDL_GetError();
478 throw std::runtime_error(msg.str());
483 SDL_EnableUNICODE(1);
485 // wait 100ms and clear SDL event queue because sometimes we have random
486 // joystick events in the queue on startup...
489 while(SDL_PollEvent(&dummy))
493 static void init_rand()
495 config->random_seed = systemRandom.srand(config->random_seed);
497 //const char *how = config->random_seed? ", user fixed.": ", from time().";
498 //log_info << "Using random seed " << config->random_seed << how << std::endl;
503 static int desktop_width = 0;
504 static int desktop_height = 0;
506 /* unfortunately only newer SDLs have these infos */
507 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
508 /* find which resolution the user normally uses */
509 if(desktop_width == 0) {
510 const SDL_VideoInfo *info = SDL_GetVideoInfo();
511 desktop_width = info->current_w;
512 desktop_height = info->current_h;
516 double aspect_ratio = config->aspect_ratio;
518 // try to guess aspect ratio of monitor if needed
519 if (aspect_ratio <= 0) {
520 // TODO: commented out because
521 // 1) it tends to guess wrong if widescreen-monitors don't stretch 800x600 to fit, but just display black borders
522 // 2) aspect ratios other than 4:3 are largely untested
524 if(config->use_fullscreen && desktop_width > 0) {
525 aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
528 aspect_ratio = 4.0 / 3.0;
534 // use aspect ratio to calculate logical resolution
535 if (aspect_ratio > 1) {
536 SCREEN_WIDTH = static_cast<int> (600 * aspect_ratio + 0.5);
540 SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
543 context_pointer->init_renderer();
544 screen = SDL_GetVideoSurface();
546 Unison::Video::Window::get().set_title(PACKAGE_NAME " " PACKAGE_VERSION);
547 Unison::Video::Window::get().set_icon(Unison::Video::Surface("images/engine/icons/supertux.xpm"));
548 //SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
552 SDL_Surface* icon = IMG_Load_RW(
553 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
555 SDL_WM_SetIcon(icon, 0);
556 SDL_FreeSurface(icon);
560 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
567 log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
570 static void init_audio()
572 sound_manager = new SoundManager();
574 sound_manager->enable_sound(config->sound_enabled);
575 sound_manager->enable_music(config->music_enabled);
578 static void quit_audio()
580 if(sound_manager != NULL) {
581 delete sound_manager;
582 sound_manager = NULL;
586 void wait_for_event(float min_delay, float max_delay)
588 assert(min_delay <= max_delay);
590 Uint32 min = (Uint32) (min_delay * 1000);
591 Uint32 max = (Uint32) (max_delay * 1000);
593 Uint32 ticks = SDL_GetTicks();
594 while(SDL_GetTicks() - ticks < min) {
596 sound_manager->update();
601 while (SDL_PollEvent(&event))
605 bool running = false;
606 ticks = SDL_GetTicks();
608 while(SDL_PollEvent(&event)) {
614 case SDL_JOYBUTTONDOWN:
615 case SDL_MOUSEBUTTONDOWN:
619 if(SDL_GetTicks() - ticks >= (max - min))
621 sound_manager->update();
627 static Uint32 last_timelog_ticks = 0;
628 static const char* last_timelog_component = 0;
630 static inline void timelog(const char* component)
632 Uint32 current_ticks = SDL_GetTicks();
634 if(last_timelog_component != 0) {
635 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
638 last_timelog_ticks = current_ticks;
639 last_timelog_component = component;
642 static inline void timelog(const char* )
647 int main(int argc, char** argv)
655 if(pre_parse_commandline(argc, argv))
658 Console::instance = new Console();
659 init_physfs(argv[0]);
662 timelog("controller");
663 main_controller = new JoystickKeyboardController();
666 timelog("tinygettext");
668 timelog("commandline");
669 if(parse_commandline(argc, argv))
674 DrawingContext context;
675 context_pointer = &context;
677 Console::instance->init_graphics();
678 timelog("scripting");
679 Scripting::init_squirrel(config->enable_script_debugger);
680 timelog("resources");
684 main_loop = new MainLoop();
685 if(config->start_level != "") {
686 // we have a normal path specified at commandline not physfs paths.
687 // So we simply mount that path here...
688 std::string dir = FileSystem::dirname(config->start_level);
689 Unison::VFS::FileSystem::get().mount(dir, "/", true);
690 //PHYSFS_addToSearchPath(dir.c_str(), true);
692 if(config->start_level.size() > 4 &&
693 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
695 main_loop->push_screen(new WorldMapNS::WorldMap(
696 FileSystem::basename(config->start_level)));
698 init_rand();//If level uses random eg. for
699 // rain particles before we do this:
700 std::auto_ptr<GameSession> session (
701 new GameSession(FileSystem::basename(config->start_level)));
703 config->random_seed =session->get_demo_random_seed(config->start_demo);
704 init_rand();//initialise generator with seed from session
706 if(config->start_demo != "")
707 session->play_demo(config->start_demo);
709 if(config->record_demo != "")
710 session->record_demo(config->record_demo);
711 main_loop->push_screen(session.release());
715 main_loop->push_screen(new TitleScreen());
718 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
719 main_loop->run(context);
721 } catch(std::exception& e) {
722 log_fatal << "Unexpected exception: " << e.what() << std::endl;
725 log_fatal << "Unexpected exception" << std::endl;
740 delete main_controller;
741 main_controller = NULL;
742 delete Console::instance;
743 Console::instance = NULL;
744 Scripting::exit_squirrel();
745 //delete texture_manager;
746 //texture_manager = NULL;