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/>.
20 #include <SDL_image.h>
24 #include <tinygettext/log.hpp>
25 #include <boost/format.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 "math/random_generator.hpp"
39 #include "physfs/ifile_stream.hpp"
40 #include "physfs/physfs_sdl.hpp"
41 #include "physfs/physfs_file_system.hpp"
42 #include "scripting/squirrel_util.hpp"
43 #include "supertux/gameconfig.hpp"
44 #include "supertux/globals.hpp"
45 #include "supertux/player_status.hpp"
46 #include "supertux/screen_manager.hpp"
47 #include "supertux/resources.hpp"
48 #include "supertux/title_screen.hpp"
49 #include "util/file_system.hpp"
50 #include "util/gettext.hpp"
51 #include "video/drawing_context.hpp"
52 #include "worldmap/worldmap.hpp"
54 namespace { DrawingContext *context_pointer; }
57 # define WRITEDIR_NAME PACKAGE_NAME
59 # define WRITEDIR_NAME "." PACKAGE_NAME
65 g_config = new Config();
68 } catch(std::exception& e) {
69 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
74 Main::init_tinygettext()
76 dictionary_manager = new tinygettext::DictionaryManager();
77 tinygettext::Log::set_log_info_callback(0);
78 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
80 dictionary_manager->add_directory("locale");
81 dictionary_manager->set_charset("UTF-8");
83 // Config setting "locale" overrides language detection
84 if (g_config->locale != "")
86 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
91 Main::init_physfs(const char* argv0)
93 if(!PHYSFS_init(argv0)) {
94 std::stringstream msg;
95 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
96 throw std::runtime_error(msg.str());
99 // allow symbolic links
100 PHYSFS_permitSymbolicLinks(1);
102 // Initialize physfs (this is a slightly modified version of
103 // PHYSFS_setSaneConfig)
104 const char *env_writedir;
105 std::string writedir;
107 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
108 writedir = env_writedir;
109 if(!PHYSFS_setWriteDir(writedir.c_str())) {
110 std::ostringstream msg;
111 msg << "Failed to use configuration directory '"
112 << writedir << "': " << PHYSFS_getLastError();
113 throw std::runtime_error(msg.str());
117 std::string userdir = PHYSFS_getUserDir();
119 // Set configuration directory
120 writedir = userdir + WRITEDIR_NAME;
121 if(!PHYSFS_setWriteDir(writedir.c_str())) {
122 // try to create the directory
123 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
124 std::ostringstream msg;
125 msg << "Failed creating configuration directory '"
126 << writedir << "': " << PHYSFS_getLastError();
127 throw std::runtime_error(msg.str());
130 if(!PHYSFS_setWriteDir(writedir.c_str())) {
131 std::ostringstream msg;
132 msg << "Failed to use configuration directory '"
133 << writedir << "': " << PHYSFS_getLastError();
134 throw std::runtime_error(msg.str());
138 PHYSFS_addToSearchPath(writedir.c_str(), 0);
140 // when started from source dir...
141 std::string dir = PHYSFS_getBaseDir();
143 std::string testfname = dir;
144 testfname += "/credits.txt";
145 bool sourcedir = false;
146 FILE* f = fopen(testfname.c_str(), "r");
149 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
150 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
158 using namespace supertux_apple;
160 // when started from Application file on Mac OS X...
162 CFBundleRef mainBundle = CFBundleGetMainBundle();
163 assert(mainBundle != 0);
164 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
165 assert(mainBundleURL != 0);
166 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
167 assert(pathStr != 0);
168 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
169 CFRelease(mainBundleURL);
172 dir = std::string(path) + "/Contents/Resources/data";
173 testfname = dir + "/credits.txt";
175 f = fopen(testfname.c_str(), "r");
178 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
179 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
188 PHYSFS_addToSearchPath(".\\data", 1);
192 std::string datadir = PHYSFS_getBaseDir();
193 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
194 datadir += "/" INSTALL_SUBDIR_SHARE;
195 #ifdef ENABLE_BINRELOC
199 dir = br_find_data_dir(datadir.c_str());
204 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
205 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
210 char** searchpath = PHYSFS_getSearchPath();
211 for(char** i = searchpath; *i != NULL; i++)
212 log_info << "[" << *i << "] is in the search path" << std::endl;
213 PHYSFS_freeList(searchpath);
217 Main::print_usage(const char* argv0)
219 std::string default_user_data_dir =
220 std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
222 std::cerr << boost::format(_(
224 "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
226 " -f, --fullscreen Run in fullscreen mode\n"
227 " -w, --window Run in window mode\n"
228 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
229 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
230 " -d, --default Reset video settings to default values\n"
231 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
232 " --disable-sfx Disable sound effects\n"
233 " --disable-music Disable music\n"
234 " -h, --help Show this help message and quit\n"
235 " -v, --version Show SuperTux version and quit\n"
236 " --console Enable ingame scripting console\n"
237 " --noconsole Disable ingame scripting console\n"
238 " --show-fps Display framerate in levels\n"
239 " --no-show-fps Do not display framerate in levels\n"
240 " --record-demo FILE LEVEL Record a demo to FILE\n"
241 " --play-demo FILE LEVEL Play a recorded demo\n"
242 " -s, --debug-scripts Enable script debugger.\n"
244 "Environment variables:\n"
245 " SUPERTUX2_USER_DIR Directory for user data (savegames, etc.);\n"
249 % argv0 % default_user_data_dir
254 * Options that should be evaluated prior to any initializations at all go here
257 Main::pre_parse_commandline(int argc, char** argv)
259 for(int i = 1; i < argc; ++i) {
260 std::string arg = argv[i];
262 if(arg == "--version" || arg == "-v") {
263 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
266 if(arg == "--help" || arg == "-h") {
267 print_usage(argv[0]);
276 * Options that should be evaluated after config is read go here
279 Main::parse_commandline(int argc, char** argv)
281 for(int i = 1; i < argc; ++i) {
282 std::string arg = argv[i];
284 if(arg == "--fullscreen" || arg == "-f") {
285 g_config->use_fullscreen = true;
286 } else if(arg == "--default" || arg == "-d") {
287 g_config->use_fullscreen = false;
289 g_config->window_size = Size(800, 600);
290 g_config->fullscreen_size = Size(800, 600);
291 g_config->aspect_size = Size(0, 0); // auto detect
293 } else if(arg == "--window" || arg == "-w") {
294 g_config->use_fullscreen = false;
295 } else if(arg == "--geometry" || arg == "-g") {
299 print_usage(argv[0]);
300 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
305 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
307 print_usage(argv[0]);
308 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
312 g_config->window_size = Size(width, height);
313 g_config->fullscreen_size = Size(width, height);
316 } else if(arg == "--aspect" || arg == "-a") {
320 print_usage(argv[0]);
321 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
325 int aspect_width = 0;
326 int aspect_height = 0;
327 if (strcmp(argv[i], "auto") == 0)
332 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
334 print_usage(argv[0]);
335 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
339 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
341 // use aspect ratio to calculate logical resolution
342 if (aspect_ratio > 1) {
343 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
346 g_config->aspect_size = Size(600,
347 static_cast<int>(600 * 1/aspect_ratio + 0.5));
351 } else if(arg == "--renderer") {
355 print_usage(argv[0]);
356 throw std::runtime_error("Need to specify a renderer for renderer argument");
360 g_config->video = VideoSystem::get_video_system(argv[i]);
362 } else if(arg == "--show-fps") {
363 g_config->show_fps = true;
364 } else if(arg == "--no-show-fps") {
365 g_config->show_fps = false;
366 } else if(arg == "--console") {
367 g_config->console_enabled = true;
368 } else if(arg == "--noconsole") {
369 g_config->console_enabled = false;
370 } else if(arg == "--disable-sfx") {
371 g_config->sound_enabled = false;
372 } else if(arg == "--disable-music") {
373 g_config->music_enabled = false;
374 } else if(arg == "--play-demo") {
376 print_usage(argv[0]);
377 throw std::runtime_error("Need to specify a demo filename");
379 g_config->start_demo = argv[++i];
380 } else if(arg == "--record-demo") {
382 print_usage(argv[0]);
383 throw std::runtime_error("Need to specify a demo filename");
385 g_config->record_demo = argv[++i];
386 } else if(arg == "--debug-scripts" || arg == "-s") {
387 g_config->enable_script_debugger = true;
388 } else if(arg[0] != '-') {
389 g_config->start_level = arg;
391 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
402 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
403 std::stringstream msg;
404 msg << "Couldn't initialize SDL: " << SDL_GetError();
405 throw std::runtime_error(msg.str());
410 SDL_EnableUNICODE(1);
412 // wait 100ms and clear SDL event queue because sometimes we have random
413 // joystick events in the queue on startup...
416 while(SDL_PollEvent(&dummy))
423 g_config->random_seed = gameRandom.srand(g_config->random_seed);
425 graphicsRandom.srand(0);
427 //const char *how = config->random_seed? ", user fixed.": ", from time().";
428 //log_info << "Using random seed " << config->random_seed << how << std::endl;
434 // FIXME: Add something here
438 context_pointer->init_renderer();
439 g_screen = SDL_GetVideoSurface();
441 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
445 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
447 const char* icon_fname = "images/engine/icons/supertux.xpm";
451 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
452 } catch (const std::runtime_error& err) {
454 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
457 SDL_WM_SetIcon(icon, 0);
458 SDL_FreeSurface(icon);
461 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
466 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
467 << " Window: " << g_config->window_size
468 << " Fullscreen: " << g_config->fullscreen_size
469 << " Area: " << g_config->aspect_size << std::endl;
475 sound_manager = new SoundManager();
477 sound_manager->enable_sound(g_config->sound_enabled);
478 sound_manager->enable_music(g_config->music_enabled);
484 if(sound_manager != NULL) {
485 delete sound_manager;
486 sound_manager = NULL;
491 Main::wait_for_event(float min_delay, float max_delay)
493 assert(min_delay <= max_delay);
495 Uint32 min = (Uint32) (min_delay * 1000);
496 Uint32 max = (Uint32) (max_delay * 1000);
498 Uint32 ticks = SDL_GetTicks();
499 while(SDL_GetTicks() - ticks < min) {
501 sound_manager->update();
506 while (SDL_PollEvent(&event))
510 bool running = false;
511 ticks = SDL_GetTicks();
513 while(SDL_PollEvent(&event)) {
516 g_screen_manager->quit();
519 case SDL_JOYBUTTONDOWN:
520 case SDL_MOUSEBUTTONDOWN:
524 if(SDL_GetTicks() - ticks >= (max - min))
526 sound_manager->update();
531 static Uint32 last_timelog_ticks = 0;
532 static const char* last_timelog_component = 0;
534 static inline void timelog(const char* component)
536 Uint32 current_ticks = SDL_GetTicks();
538 if(last_timelog_component != 0) {
539 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
542 last_timelog_ticks = current_ticks;
543 last_timelog_component = component;
547 Main::run(int argc, char** argv)
552 /* Do this before pre_parse_commandline, because --help now shows the
553 * default user data dir. */
554 init_physfs(argv[0]);
556 if(pre_parse_commandline(argc, argv))
559 Console::instance = new Console();
562 timelog("controller");
563 g_jk_controller = new JoystickKeyboardController();
569 AddonManager::get_instance().load_addons();
571 timelog("tinygettext");
574 timelog("commandline");
575 if(parse_commandline(argc, argv))
582 DrawingContext context;
583 context_pointer = &context;
586 Console::instance->init_graphics();
588 timelog("scripting");
589 scripting::init_squirrel(g_config->enable_script_debugger);
591 timelog("resources");
592 Resources::load_shared();
596 const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
598 g_screen_manager = new ScreenManager();
602 if(g_config->start_level != "") {
603 // we have a normal path specified at commandline, not a physfs path.
604 // So we simply mount that path here...
605 std::string dir = FileSystem::dirname(g_config->start_level);
606 log_debug << "Adding dir: " << dir << std::endl;
607 PHYSFS_addToSearchPath(dir.c_str(), true);
609 if(g_config->start_level.size() > 4 &&
610 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
611 g_screen_manager->push_screen(new worldmap::WorldMap(
612 FileSystem::basename(g_config->start_level), default_playerstatus.get()));
614 std::auto_ptr<GameSession> session (
615 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
617 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
618 init_rand();//initialise generator with seed from session
620 if(g_config->start_demo != "")
621 session->play_demo(g_config->start_demo);
623 if(g_config->record_demo != "")
624 session->record_demo(g_config->record_demo);
625 g_screen_manager->push_screen(session.release());
628 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
631 g_screen_manager->run(context);
632 } catch(std::exception& e) {
633 log_fatal << "Unexpected exception: " << e.what() << std::endl;
636 log_fatal << "Unexpected exception" << std::endl;
640 delete g_screen_manager;
641 g_screen_manager = NULL;
643 Resources::unload_shared();
650 delete g_jk_controller;
651 g_jk_controller = NULL;
652 delete Console::instance;
653 Console::instance = NULL;
654 scripting::exit_squirrel();
655 delete texture_manager;
656 texture_manager = NULL;