2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
21 #include <SDL_image.h>
25 #include <tinygettext/log.hpp>
27 #include "supertux/main.hpp"
30 namespace supertux_apple {
31 # include <CoreFoundation/CoreFoundation.h>
32 } // namespace supertux_apple
35 #include "addon/addon_manager.hpp"
36 #include "audio/sound_manager.hpp"
37 #include "control/joystickkeyboardcontroller.hpp"
38 #include "control/haptic_manager.hpp"
39 #include "math/random_generator.hpp"
40 #include "physfs/ifile_stream.hpp"
41 #include "physfs/physfs_sdl.hpp"
42 #include "physfs/physfs_file_system.hpp"
43 #include "scripting/squirrel_util.hpp"
44 #include "supertux/gameconfig.hpp"
45 #include "supertux/globals.hpp"
46 #include "supertux/player_status.hpp"
47 #include "supertux/screen_manager.hpp"
48 #include "supertux/resources.hpp"
49 #include "supertux/title_screen.hpp"
50 #include "util/file_system.hpp"
51 #include "util/gettext.hpp"
52 #include "video/drawing_context.hpp"
53 #include "worldmap/worldmap.hpp"
55 namespace { DrawingContext *context_pointer; }
60 g_config = new Config();
63 } catch(std::exception& e) {
64 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
69 Main::init_tinygettext()
71 dictionary_manager = new tinygettext::DictionaryManager();
72 tinygettext::Log::set_log_info_callback(0);
73 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
75 dictionary_manager->add_directory("locale");
76 dictionary_manager->set_charset("UTF-8");
78 // Config setting "locale" overrides language detection
79 if (g_config->locale != "")
81 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
86 Main::init_physfs(const char* argv0)
88 if(!PHYSFS_init(argv0)) {
89 std::stringstream msg;
90 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
91 throw std::runtime_error(msg.str());
94 // allow symbolic links
95 PHYSFS_permitSymbolicLinks(1);
97 // Initialize physfs (this is a slightly modified version of
98 // PHYSFS_setSaneConfig)
99 const char* application = PACKAGE_NAME;
100 const char* userdir = PHYSFS_getUserDir();
102 char* writedir = new char[strlen(userdir) + strlen(application) +
109 // Set configuration directory
116 userdir, application);
117 if(!PHYSFS_setWriteDir(writedir)) {
118 // try to create the directory
119 char* mkdir = new char[strlen(application) +
132 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
133 std::ostringstream msg;
134 msg << "Failed creating configuration directory '"
135 << writedir << "': " << PHYSFS_getLastError();
138 throw std::runtime_error(msg.str());
142 if(!PHYSFS_setWriteDir(writedir)) {
143 std::ostringstream msg;
144 msg << "Failed to use configuration directory '"
145 << writedir << "': " << PHYSFS_getLastError();
147 throw std::runtime_error(msg.str());
150 PHYSFS_addToSearchPath(writedir, 0);
153 // when started from source dir...
154 std::string dir = PHYSFS_getBaseDir();
156 std::string testfname = dir;
157 testfname += "/credits.txt";
158 bool sourcedir = false;
159 FILE* f = fopen(testfname.c_str(), "r");
162 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
163 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
171 using namespace supertux_apple;
173 // when started from Application file on Mac OS X...
175 CFBundleRef mainBundle = CFBundleGetMainBundle();
176 assert(mainBundle != 0);
177 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
178 assert(mainBundleURL != 0);
179 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
180 assert(pathStr != 0);
181 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
182 CFRelease(mainBundleURL);
185 dir = std::string(path) + "/Contents/Resources/data";
186 testfname = dir + "/credits.txt";
188 f = fopen(testfname.c_str(), "r");
191 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
192 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
201 PHYSFS_addToSearchPath(".\\data", 1);
205 std::string datadir = PHYSFS_getBaseDir();
206 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
207 datadir += "/" INSTALL_SUBDIR_SHARE;
208 #ifdef ENABLE_BINRELOC
212 dir = br_find_data_dir(datadir.c_str());
217 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
218 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
223 char** searchpath = PHYSFS_getSearchPath();
224 for(char** i = searchpath; *i != NULL; i++)
225 log_info << "[" << *i << "] is in the search path" << std::endl;
226 PHYSFS_freeList(searchpath);
230 Main::print_usage(const char* argv0)
232 std::cerr << _("Usage: ") << argv0 << _(" [OPTIONS] [LEVELFILE]\n\n")
234 " -f, --fullscreen Run in fullscreen mode\n"
235 " -w, --window Run in window mode\n"
236 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
237 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
238 " -d, --default Reset video settings to default values\n"
239 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
240 " --disable-sfx Disable sound effects\n"
241 " --disable-music Disable music\n"
242 " -h, --help Show this help message and quit\n"
243 " -v, --version Show SuperTux version and quit\n"
244 " --console Enable ingame scripting console\n"
245 " --noconsole Disable ingame scripting console\n"
246 " --show-fps Display framerate in levels\n"
247 " --no-show-fps Do not display framerate in levels\n"
248 " --record-demo FILE LEVEL Record a demo to FILE\n"
249 " --play-demo FILE LEVEL Play a recorded demo\n"
250 " -s, --debug-scripts Enable script debugger.\n"
256 * Options that should be evaluated prior to any initializations at all go here
259 Main::pre_parse_commandline(int argc, char** argv)
261 for(int i = 1; i < argc; ++i) {
262 std::string arg = argv[i];
264 if(arg == "--version" || arg == "-v") {
265 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
268 if(arg == "--help" || arg == "-h") {
269 print_usage(argv[0]);
278 * Options that should be evaluated after config is read go here
281 Main::parse_commandline(int argc, char** argv)
283 for(int i = 1; i < argc; ++i) {
284 std::string arg = argv[i];
286 if(arg == "--fullscreen" || arg == "-f") {
287 g_config->use_fullscreen = true;
288 } else if(arg == "--default" || arg == "-d") {
289 g_config->use_fullscreen = false;
291 g_config->window_size = Size(800, 600);
292 g_config->fullscreen_size = Size(800, 600);
293 g_config->aspect_size = Size(0, 0); // auto detect
295 } else if(arg == "--window" || arg == "-w") {
296 g_config->use_fullscreen = false;
297 } else if(arg == "--geometry" || arg == "-g") {
301 print_usage(argv[0]);
302 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
307 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
309 print_usage(argv[0]);
310 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
314 g_config->window_size = Size(width, height);
315 g_config->fullscreen_size = Size(width, height);
318 } else if(arg == "--aspect" || arg == "-a") {
322 print_usage(argv[0]);
323 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
327 int aspect_width = 0;
328 int aspect_height = 0;
329 if (strcmp(argv[i], "auto") == 0)
334 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
336 print_usage(argv[0]);
337 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
341 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
343 // use aspect ratio to calculate logical resolution
344 if (aspect_ratio > 1) {
345 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
348 g_config->aspect_size = Size(600,
349 static_cast<int>(600 * 1/aspect_ratio + 0.5));
353 } else if(arg == "--renderer") {
357 print_usage(argv[0]);
358 throw std::runtime_error("Need to specify a renderer for renderer argument");
362 g_config->video = VideoSystem::get_video_system(argv[i]);
364 } else if(arg == "--show-fps") {
365 g_config->show_fps = true;
366 } else if(arg == "--no-show-fps") {
367 g_config->show_fps = false;
368 } else if(arg == "--console") {
369 g_config->console_enabled = true;
370 } else if(arg == "--noconsole") {
371 g_config->console_enabled = false;
372 } else if(arg == "--disable-sfx") {
373 g_config->sound_enabled = false;
374 } else if(arg == "--disable-music") {
375 g_config->music_enabled = false;
376 } else if(arg == "--play-demo") {
378 print_usage(argv[0]);
379 throw std::runtime_error("Need to specify a demo filename");
381 g_config->start_demo = argv[++i];
382 } else if(arg == "--record-demo") {
384 print_usage(argv[0]);
385 throw std::runtime_error("Need to specify a demo filename");
387 g_config->record_demo = argv[++i];
388 } else if(arg == "--debug-scripts" || arg == "-s") {
389 g_config->enable_script_debugger = true;
390 } else if(arg[0] != '-') {
391 g_config->start_level = arg;
393 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
406 init_flags = SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK;
407 #ifdef SDL_INIT_HAPTIC
408 init_flags |= SDL_INIT_HAPTIC;
411 if(SDL_Init(init_flags) < 0) {
412 std::stringstream msg;
413 msg << "Couldn't initialize SDL: " << SDL_GetError();
414 throw std::runtime_error(msg.str());
419 SDL_EnableUNICODE(1);
421 // wait 100ms and clear SDL event queue because sometimes we have random
422 // joystick events in the queue on startup...
425 while(SDL_PollEvent(&dummy))
432 g_config->random_seed = systemRandom.srand(g_config->random_seed);
434 //const char *how = config->random_seed? ", user fixed.": ", from time().";
435 //log_info << "Using random seed " << config->random_seed << how << std::endl;
441 // FIXME: Add something here
445 context_pointer->init_renderer();
446 g_screen = SDL_GetVideoSurface();
448 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
452 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
454 const char* icon_fname = "images/engine/icons/supertux.xpm";
458 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
459 } catch (const std::runtime_error& err) {
461 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
464 SDL_WM_SetIcon(icon, 0);
465 SDL_FreeSurface(icon);
468 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
473 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
474 << " Window: " << g_config->window_size
475 << " Fullscreen: " << g_config->fullscreen_size
476 << " Area: " << g_config->aspect_size << std::endl;
482 sound_manager = new SoundManager();
484 sound_manager->enable_sound(g_config->sound_enabled);
485 sound_manager->enable_music(g_config->music_enabled);
491 if(sound_manager != NULL) {
492 delete sound_manager;
493 sound_manager = NULL;
498 Main::wait_for_event(float min_delay, float max_delay)
500 assert(min_delay <= max_delay);
502 Uint32 min = (Uint32) (min_delay * 1000);
503 Uint32 max = (Uint32) (max_delay * 1000);
505 Uint32 ticks = SDL_GetTicks();
506 while(SDL_GetTicks() - ticks < min) {
508 sound_manager->update();
513 while (SDL_PollEvent(&event))
517 bool running = false;
518 ticks = SDL_GetTicks();
520 while(SDL_PollEvent(&event)) {
523 g_screen_manager->quit();
526 case SDL_JOYBUTTONDOWN:
527 case SDL_MOUSEBUTTONDOWN:
531 if(SDL_GetTicks() - ticks >= (max - min))
533 sound_manager->update();
538 static Uint32 last_timelog_ticks = 0;
539 static const char* last_timelog_component = 0;
541 static inline void timelog(const char* component)
543 Uint32 current_ticks = SDL_GetTicks();
545 if(last_timelog_component != 0) {
546 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
549 last_timelog_ticks = current_ticks;
550 last_timelog_component = component;
554 Main::run(int argc, char** argv)
560 if(pre_parse_commandline(argc, argv))
563 Console::instance = new Console();
564 init_physfs(argv[0]);
568 g_haptic_manager = new HapticManager();
570 timelog("controller");
571 g_main_controller = new JoystickKeyboardController();
577 AddonManager::get_instance().load_addons();
579 timelog("tinygettext");
582 timelog("commandline");
583 if(parse_commandline(argc, argv))
590 DrawingContext context;
591 context_pointer = &context;
594 Console::instance->init_graphics();
596 timelog("scripting");
597 scripting::init_squirrel(g_config->enable_script_debugger);
599 timelog("resources");
600 Resources::load_shared();
604 const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
606 g_screen_manager = new ScreenManager();
610 if(g_config->start_level != "") {
611 // we have a normal path specified at commandline, not a physfs path.
612 // So we simply mount that path here...
613 std::string dir = FileSystem::dirname(g_config->start_level);
614 log_debug << "Adding dir: " << dir << std::endl;
615 PHYSFS_addToSearchPath(dir.c_str(), true);
617 if(g_config->start_level.size() > 4 &&
618 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
619 g_screen_manager->push_screen(new worldmap::WorldMap(
620 FileSystem::basename(g_config->start_level), default_playerstatus.get()));
622 std::auto_ptr<GameSession> session (
623 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
625 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
626 init_rand();//initialise generator with seed from session
628 if(g_config->start_demo != "")
629 session->play_demo(g_config->start_demo);
631 if(g_config->record_demo != "")
632 session->record_demo(g_config->record_demo);
633 g_screen_manager->push_screen(session.release());
636 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
639 g_screen_manager->run(context);
640 } catch(std::exception& e) {
641 log_fatal << "Unexpected exception: " << e.what() << std::endl;
644 log_fatal << "Unexpected exception" << std::endl;
648 delete g_screen_manager;
649 g_screen_manager = NULL;
651 Resources::unload_shared();
658 delete g_main_controller;
659 g_main_controller = NULL;
660 delete Console::instance;
661 Console::instance = NULL;
662 scripting::exit_squirrel();
663 delete texture_manager;
664 texture_manager = NULL;