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/>.
17 #include "supertux/main.hpp"
22 #include <SDL_image.h>
27 namespace supertux_apple {
28 # include <CoreFoundation/CoreFoundation.h>
29 } // namespace supertux_apple
32 #include "tinygettext/log.hpp"
34 #include "addon/addon_manager.hpp"
35 #include "audio/sound_manager.hpp"
36 #include "binreloc/binreloc.h"
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/mainloop.hpp"
46 #include "supertux/resources.hpp"
47 #include "supertux/title_screen.hpp"
48 #include "util/file_system.hpp"
49 #include "util/gettext.hpp"
50 #include "video/drawing_context.hpp"
51 #include "worldmap/worldmap.hpp"
53 namespace { DrawingContext *context_pointer; }
58 g_config = new Config();
61 } catch(std::exception& e) {
62 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
67 Main::init_tinygettext()
69 tinygettext::Log::set_log_info_callback(0);
70 dictionary_manager.set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
72 dictionary_manager.add_directory("locale");
73 dictionary_manager.set_charset("UTF-8");
75 // Config setting "locale" overrides language detection
76 if (g_config->locale != "") {
77 dictionary_manager.set_language(tinygettext::Language::from_name(g_config->locale));
82 Main::init_physfs(const char* argv0)
84 if(!PHYSFS_init(argv0)) {
85 std::stringstream msg;
86 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
87 throw std::runtime_error(msg.str());
90 // allow symbolic links
91 PHYSFS_permitSymbolicLinks(1);
93 // Initialize physfs (this is a slightly modified version of
94 // PHYSFS_setSaneConfig
95 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
96 const char* userdir = PHYSFS_getUserDir();
97 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
99 // Set configuration directory
100 sprintf(writedir, "%s.%s", userdir, application);
101 if(!PHYSFS_setWriteDir(writedir)) {
102 // try to create the directory
103 char* mkdir = new char[strlen(application) + 2];
104 sprintf(mkdir, ".%s", application);
105 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
106 std::ostringstream msg;
107 msg << "Failed creating configuration directory '"
108 << writedir << "': " << PHYSFS_getLastError();
111 throw std::runtime_error(msg.str());
115 if(!PHYSFS_setWriteDir(writedir)) {
116 std::ostringstream msg;
117 msg << "Failed to use configuration directory '"
118 << writedir << "': " << PHYSFS_getLastError();
120 throw std::runtime_error(msg.str());
123 PHYSFS_addToSearchPath(writedir, 0);
126 // when started from source dir...
127 std::string dir = PHYSFS_getBaseDir();
129 std::string testfname = dir;
130 testfname += "/credits.txt";
131 bool sourcedir = false;
132 FILE* f = fopen(testfname.c_str(), "r");
135 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
136 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
144 using namespace supertux_apple;
146 // when started from Application file on Mac OS X...
148 CFBundleRef mainBundle = CFBundleGetMainBundle();
149 assert(mainBundle != 0);
150 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
151 assert(mainBundleURL != 0);
152 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
153 assert(pathStr != 0);
154 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
155 CFRelease(mainBundleURL);
158 dir = std::string(path) + "/Contents/Resources/data";
159 testfname = dir + "/credits.txt";
161 f = fopen(testfname.c_str(), "r");
164 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
165 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
174 PHYSFS_addToSearchPath(".\\data", 1);
178 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
180 #ifdef ENABLE_BINRELOC
184 dir = br_find_data_dir(APPDATADIR);
189 datadir = APPDATADIR;
191 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
192 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
198 char** searchpath = PHYSFS_getSearchPath();
199 for(char** i = searchpath; *i != NULL; i++)
200 log_info << "[" << *i << "] is in the search path" << std::endl;
201 PHYSFS_freeList(searchpath);
205 Main::print_usage(const char* argv0)
207 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
210 " -f, --fullscreen Run in fullscreen mode\n"
211 " -w, --window Run in window mode\n"
212 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
213 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
214 " -d, --default Reset video settings to default values\n"
215 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
216 " --disable-sfx Disable sound effects\n"
217 " --disable-music Disable music\n"
218 " -h, --help Show this help message and quit\n"
219 " -v, --version Show SuperTux version and quit\n"
220 " --console Enable ingame scripting console\n"
221 " --noconsole Disable ingame scripting console\n"
222 " --show-fps Display framerate in levels\n"
223 " --no-show-fps Do not display framerate in levels\n"
224 " --record-demo FILE LEVEL Record a demo to FILE\n"
225 " --play-demo FILE LEVEL Play a recorded demo\n"
226 " -s, --debug-scripts Enable script debugger.\n"
231 * Options that should be evaluated prior to any initializations at all go here
234 Main::pre_parse_commandline(int argc, char** argv)
236 for(int i = 1; i < argc; ++i) {
237 std::string arg = argv[i];
239 if(arg == "--version" || arg == "-v") {
240 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
243 if(arg == "--help" || arg == "-h") {
244 print_usage(argv[0]);
253 * Options that should be evaluated after config is read go here
256 Main::parse_commandline(int argc, char** argv)
258 for(int i = 1; i < argc; ++i) {
259 std::string arg = argv[i];
261 if(arg == "--fullscreen" || arg == "-f") {
262 g_config->use_fullscreen = true;
263 } else if(arg == "--default" || arg == "-d") {
264 g_config->use_fullscreen = false;
266 g_config->window_width = 800;
267 g_config->window_height = 600;
269 g_config->fullscreen_width = 800;
270 g_config->fullscreen_height = 600;
272 g_config->aspect_width = 0; // auto detect
273 g_config->aspect_height = 0;
275 } else if(arg == "--window" || arg == "-w") {
276 g_config->use_fullscreen = false;
277 } else if(arg == "--geometry" || arg == "-g") {
281 print_usage(argv[0]);
282 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
287 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
289 print_usage(argv[0]);
290 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
294 g_config->window_width = width;
295 g_config->window_height = height;
297 g_config->fullscreen_width = width;
298 g_config->fullscreen_height = height;
301 } else if(arg == "--aspect" || arg == "-a") {
305 print_usage(argv[0]);
306 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
310 int aspect_width = 0;
311 int aspect_height = 0;
312 if (strcmp(argv[i], "auto") == 0)
317 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
319 print_usage(argv[0]);
320 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
324 float aspect_ratio = static_cast<double>(g_config->aspect_width) /
325 static_cast<double>(g_config->aspect_height);
327 // use aspect ratio to calculate logical resolution
328 if (aspect_ratio > 1) {
329 g_config->aspect_width = static_cast<int> (600 * aspect_ratio + 0.5);
330 g_config->aspect_height = 600;
332 g_config->aspect_width = 600;
333 g_config->aspect_height = static_cast<int> (600 * 1/aspect_ratio + 0.5);
337 } else if(arg == "--renderer") {
341 print_usage(argv[0]);
342 throw std::runtime_error("Need to specify a renderer for renderer argument");
346 g_config->video = get_video_system(argv[i]);
348 } else if(arg == "--show-fps") {
349 g_config->show_fps = true;
350 } else if(arg == "--no-show-fps") {
351 g_config->show_fps = false;
352 } else if(arg == "--console") {
353 g_config->console_enabled = true;
354 } else if(arg == "--noconsole") {
355 g_config->console_enabled = false;
356 } else if(arg == "--disable-sfx") {
357 g_config->sound_enabled = false;
358 } else if(arg == "--disable-music") {
359 g_config->music_enabled = false;
360 } else if(arg == "--play-demo") {
362 print_usage(argv[0]);
363 throw std::runtime_error("Need to specify a demo filename");
365 g_config->start_demo = argv[++i];
366 } else if(arg == "--record-demo") {
368 print_usage(argv[0]);
369 throw std::runtime_error("Need to specify a demo filename");
371 g_config->record_demo = argv[++i];
372 } else if(arg == "--debug-scripts" || arg == "-s") {
373 g_config->enable_script_debugger = true;
374 } else if(arg[0] != '-') {
375 g_config->start_level = arg;
377 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
388 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
389 std::stringstream msg;
390 msg << "Couldn't initialize SDL: " << SDL_GetError();
391 throw std::runtime_error(msg.str());
396 SDL_EnableUNICODE(1);
398 // wait 100ms and clear SDL event queue because sometimes we have random
399 // joystick events in the queue on startup...
402 while(SDL_PollEvent(&dummy))
409 g_config->random_seed = systemRandom.srand(g_config->random_seed);
411 //const char *how = config->random_seed? ", user fixed.": ", from time().";
412 //log_info << "Using random seed " << config->random_seed << how << std::endl;
418 // FIXME: Add something here
422 context_pointer->init_renderer();
423 g_screen = SDL_GetVideoSurface();
425 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
429 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
431 const char* icon_fname = "images/engine/icons/supertux.xpm";
435 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
436 } catch (const std::runtime_error& err) {
438 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
441 SDL_WM_SetIcon(icon, 0);
442 SDL_FreeSurface(icon);
446 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
452 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
453 << " Window: " << g_config->window_width << "x" << g_config->window_height
454 << " Fullscreen: " << g_config->fullscreen_width << "x" << g_config->fullscreen_height
455 << " Area: " << g_config->aspect_width << "x" << g_config->aspect_height << std::endl;
461 sound_manager = new SoundManager();
463 sound_manager->enable_sound(g_config->sound_enabled);
464 sound_manager->enable_music(g_config->music_enabled);
470 if(sound_manager != NULL) {
471 delete sound_manager;
472 sound_manager = NULL;
477 Main::wait_for_event(float min_delay, float max_delay)
479 assert(min_delay <= max_delay);
481 Uint32 min = (Uint32) (min_delay * 1000);
482 Uint32 max = (Uint32) (max_delay * 1000);
484 Uint32 ticks = SDL_GetTicks();
485 while(SDL_GetTicks() - ticks < min) {
487 sound_manager->update();
492 while (SDL_PollEvent(&event))
496 bool running = false;
497 ticks = SDL_GetTicks();
499 while(SDL_PollEvent(&event)) {
505 case SDL_JOYBUTTONDOWN:
506 case SDL_MOUSEBUTTONDOWN:
510 if(SDL_GetTicks() - ticks >= (max - min))
512 sound_manager->update();
518 static Uint32 last_timelog_ticks = 0;
519 static const char* last_timelog_component = 0;
521 static inline void timelog(const char* component)
523 Uint32 current_ticks = SDL_GetTicks();
525 if(last_timelog_component != 0) {
526 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
529 last_timelog_ticks = current_ticks;
530 last_timelog_component = component;
533 static inline void timelog(const char* )
539 Main::main(int argc, char** argv)
545 if(pre_parse_commandline(argc, argv))
548 Console::instance = new Console();
549 init_physfs(argv[0]);
552 timelog("controller");
553 g_main_controller = new JoystickKeyboardController();
559 AddonManager::get_instance().load_addons();
561 timelog("tinygettext");
564 timelog("commandline");
565 if(parse_commandline(argc, argv))
572 DrawingContext context;
573 context_pointer = &context;
576 Console::instance->init_graphics();
578 timelog("scripting");
579 Scripting::init_squirrel(g_config->enable_script_debugger);
581 timelog("resources");
582 Resources::load_shared();
586 g_main_loop = new MainLoop();
587 if(g_config->start_level != "") {
588 // we have a normal path specified at commandline, not a physfs path.
589 // So we simply mount that path here...
590 std::string dir = FileSystem::dirname(g_config->start_level);
591 log_debug << "Adding dir: " << dir << std::endl;
592 PHYSFS_addToSearchPath(dir.c_str(), true);
594 if(g_config->start_level.size() > 4 &&
595 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
597 g_main_loop->push_screen(new WorldMapNS::WorldMap(
598 FileSystem::basename(g_config->start_level)));
600 init_rand();//If level uses random eg. for
601 // rain particles before we do this:
602 std::auto_ptr<GameSession> session (
603 new GameSession(FileSystem::basename(g_config->start_level)));
605 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
606 init_rand();//initialise generator with seed from session
608 if(g_config->start_demo != "")
609 session->play_demo(g_config->start_demo);
611 if(g_config->record_demo != "")
612 session->record_demo(g_config->record_demo);
613 g_main_loop->push_screen(session.release());
617 g_main_loop->push_screen(new TitleScreen());
620 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
621 g_main_loop->run(context);
622 } catch(std::exception& e) {
623 log_fatal << "Unexpected exception: " << e.what() << std::endl;
626 log_fatal << "Unexpected exception" << std::endl;
633 Resources::unload_shared();
640 delete g_main_controller;
641 g_main_controller = NULL;
642 delete Console::instance;
643 Console::instance = NULL;
644 Scripting::exit_squirrel();
645 delete texture_manager;
646 texture_manager = NULL;