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>
25 namespace supertux_apple {
26 # include <CoreFoundation/CoreFoundation.h>
27 } // namespace supertux_apple
30 #include "addon/addon_manager.hpp"
31 #include "audio/sound_manager.hpp"
32 #include "binreloc/binreloc.h"
33 #include "control/joystickkeyboardcontroller.hpp"
34 #include "math/random_generator.hpp"
35 #include "physfs/ifile_stream.hpp"
36 #include "physfs/physfs_sdl.hpp"
37 #include "scripting/squirrel_util.hpp"
38 #include "supertux/gameconfig.hpp"
39 #include "supertux/globals.hpp"
40 #include "supertux/mainloop.hpp"
41 #include "supertux/resources.hpp"
42 #include "supertux/title_screen.hpp"
43 #include "util/file_system.hpp"
44 #include "util/gettext.hpp"
45 #include "video/drawing_context.hpp"
46 #include "worldmap/worldmap.hpp"
48 namespace { DrawingContext *context_pointer; }
50 static void init_config()
52 g_config = new Config();
55 } catch(std::exception& e) {
56 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
60 static void init_tinygettext()
62 dictionary_manager.add_directory("locale");
63 dictionary_manager.set_charset("UTF-8");
65 // Config setting "locale" overrides language detection
66 if (g_config->locale != "") {
67 dictionary_manager.set_language(tinygettext::Language::from_name(g_config->locale));
71 static void init_physfs(const char* argv0)
73 if(!PHYSFS_init(argv0)) {
74 std::stringstream msg;
75 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
76 throw std::runtime_error(msg.str());
79 // allow symbolic links
80 PHYSFS_permitSymbolicLinks(1);
82 // Initialize physfs (this is a slightly modified version of
83 // PHYSFS_setSaneConfig
84 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
85 const char* userdir = PHYSFS_getUserDir();
86 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
88 // Set configuration directory
89 sprintf(writedir, "%s.%s", userdir, application);
90 if(!PHYSFS_setWriteDir(writedir)) {
91 // try to create the directory
92 char* mkdir = new char[strlen(application) + 2];
93 sprintf(mkdir, ".%s", application);
94 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
95 std::ostringstream msg;
96 msg << "Failed creating configuration directory '"
97 << writedir << "': " << PHYSFS_getLastError();
100 throw std::runtime_error(msg.str());
104 if(!PHYSFS_setWriteDir(writedir)) {
105 std::ostringstream msg;
106 msg << "Failed to use configuration directory '"
107 << writedir << "': " << PHYSFS_getLastError();
109 throw std::runtime_error(msg.str());
112 PHYSFS_addToSearchPath(writedir, 0);
115 // when started from source dir...
116 std::string dir = PHYSFS_getBaseDir();
118 std::string testfname = dir;
119 testfname += "/credits.txt";
120 bool sourcedir = false;
121 FILE* f = fopen(testfname.c_str(), "r");
124 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
125 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
133 using namespace supertux_apple;
135 // when started from Application file on Mac OS X...
137 CFBundleRef mainBundle = CFBundleGetMainBundle();
138 assert(mainBundle != 0);
139 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
140 assert(mainBundleURL != 0);
141 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
142 assert(pathStr != 0);
143 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
144 CFRelease(mainBundleURL);
147 dir = std::string(path) + "/Contents/Resources/data";
148 testfname = dir + "/credits.txt";
150 f = fopen(testfname.c_str(), "r");
153 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
154 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
163 PHYSFS_addToSearchPath(".\\data", 1);
167 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
169 #ifdef ENABLE_BINRELOC
173 dir = br_find_data_dir(APPDATADIR);
178 datadir = APPDATADIR;
180 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
181 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
187 char** searchpath = PHYSFS_getSearchPath();
188 for(char** i = searchpath; *i != NULL; i++)
189 log_info << "[" << *i << "] is in the search path" << std::endl;
190 PHYSFS_freeList(searchpath);
193 static void print_usage(const char* argv0)
195 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
198 " -f, --fullscreen Run in fullscreen mode\n"
199 " -w, --window Run in window mode\n"
200 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
201 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
202 " -d, --default Reset video settings to default values\n"
203 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
204 " --disable-sfx Disable sound effects\n"
205 " --disable-music Disable music\n"
206 " -h, --help Show this help message and quit\n"
207 " -v, --version Show SuperTux version and quit\n"
208 " --console Enable ingame scripting console\n"
209 " --noconsole Disable ingame scripting console\n"
210 " --show-fps Display framerate in levels\n"
211 " --no-show-fps Do not display framerate in levels\n"
212 " --record-demo FILE LEVEL Record a demo to FILE\n"
213 " --play-demo FILE LEVEL Play a recorded demo\n"
214 " -s, --debug-scripts Enable script debugger.\n"
219 * Options that should be evaluated prior to any initializations at all go here
221 static bool pre_parse_commandline(int argc, char** argv)
223 for(int i = 1; i < argc; ++i) {
224 std::string arg = argv[i];
226 if(arg == "--version" || arg == "-v") {
227 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
230 if(arg == "--help" || arg == "-h") {
231 print_usage(argv[0]);
240 * Options that should be evaluated after config is read go here
242 static bool parse_commandline(int argc, char** argv)
244 for(int i = 1; i < argc; ++i) {
245 std::string arg = argv[i];
247 if(arg == "--fullscreen" || arg == "-f") {
248 g_config->use_fullscreen = true;
249 } else if(arg == "--default" || arg == "-d") {
250 g_config->use_fullscreen = false;
252 g_config->window_width = 800;
253 g_config->window_height = 600;
255 g_config->fullscreen_width = 800;
256 g_config->fullscreen_height = 600;
258 g_config->aspect_width = 0; // auto detect
259 g_config->aspect_height = 0;
261 } else if(arg == "--window" || arg == "-w") {
262 g_config->use_fullscreen = false;
263 } else if(arg == "--geometry" || arg == "-g") {
267 print_usage(argv[0]);
268 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
273 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
275 print_usage(argv[0]);
276 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
280 g_config->window_width = width;
281 g_config->window_height = height;
283 g_config->fullscreen_width = width;
284 g_config->fullscreen_height = height;
287 } else if(arg == "--aspect" || arg == "-a") {
291 print_usage(argv[0]);
292 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
296 int aspect_width = 0;
297 int aspect_height = 0;
298 if (strcmp(argv[i], "auto") == 0)
303 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
305 print_usage(argv[0]);
306 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
310 float aspect_ratio = static_cast<double>(g_config->aspect_width) /
311 static_cast<double>(g_config->aspect_height);
313 // use aspect ratio to calculate logical resolution
314 if (aspect_ratio > 1) {
315 g_config->aspect_width = static_cast<int> (600 * aspect_ratio + 0.5);
316 g_config->aspect_height = 600;
318 g_config->aspect_width = 600;
319 g_config->aspect_height = static_cast<int> (600 * 1/aspect_ratio + 0.5);
323 } else if(arg == "--renderer") {
327 print_usage(argv[0]);
328 throw std::runtime_error("Need to specify a renderer for renderer argument");
332 g_config->video = get_video_system(argv[i]);
334 } else if(arg == "--show-fps") {
335 g_config->show_fps = true;
336 } else if(arg == "--no-show-fps") {
337 g_config->show_fps = false;
338 } else if(arg == "--console") {
339 g_config->console_enabled = true;
340 } else if(arg == "--noconsole") {
341 g_config->console_enabled = false;
342 } else if(arg == "--disable-sfx") {
343 g_config->sound_enabled = false;
344 } else if(arg == "--disable-music") {
345 g_config->music_enabled = false;
346 } else if(arg == "--play-demo") {
348 print_usage(argv[0]);
349 throw std::runtime_error("Need to specify a demo filename");
351 g_config->start_demo = argv[++i];
352 } else if(arg == "--record-demo") {
354 print_usage(argv[0]);
355 throw std::runtime_error("Need to specify a demo filename");
357 g_config->record_demo = argv[++i];
358 } else if(arg == "--debug-scripts" || arg == "-s") {
359 g_config->enable_script_debugger = true;
360 } else if(arg[0] != '-') {
361 g_config->start_level = arg;
363 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
371 static void init_sdl()
373 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
374 std::stringstream msg;
375 msg << "Couldn't initialize SDL: " << SDL_GetError();
376 throw std::runtime_error(msg.str());
381 SDL_EnableUNICODE(1);
383 // wait 100ms and clear SDL event queue because sometimes we have random
384 // joystick events in the queue on startup...
387 while(SDL_PollEvent(&dummy))
391 static void init_rand()
393 g_config->random_seed = systemRandom.srand(g_config->random_seed);
395 //const char *how = config->random_seed? ", user fixed.": ", from time().";
396 //log_info << "Using random seed " << config->random_seed << how << std::endl;
401 // FIXME: Add something here
405 context_pointer->init_renderer();
406 g_screen = SDL_GetVideoSurface();
408 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
412 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
414 const char* icon_fname = "images/engine/icons/supertux.xpm";
418 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
419 } catch (const std::runtime_error& err) {
421 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
424 SDL_WM_SetIcon(icon, 0);
425 SDL_FreeSurface(icon);
429 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
435 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
436 << " Window: " << g_config->window_width << "x" << g_config->window_height
437 << " Fullscreen: " << g_config->fullscreen_width << "x" << g_config->fullscreen_height
438 << " Area: " << g_config->aspect_width << "x" << g_config->aspect_height << std::endl;
441 static void init_audio()
443 sound_manager = new SoundManager();
445 sound_manager->enable_sound(g_config->sound_enabled);
446 sound_manager->enable_music(g_config->music_enabled);
449 static void quit_audio()
451 if(sound_manager != NULL) {
452 delete sound_manager;
453 sound_manager = NULL;
457 void wait_for_event(float min_delay, float max_delay)
459 assert(min_delay <= max_delay);
461 Uint32 min = (Uint32) (min_delay * 1000);
462 Uint32 max = (Uint32) (max_delay * 1000);
464 Uint32 ticks = SDL_GetTicks();
465 while(SDL_GetTicks() - ticks < min) {
467 sound_manager->update();
472 while (SDL_PollEvent(&event))
476 bool running = false;
477 ticks = SDL_GetTicks();
479 while(SDL_PollEvent(&event)) {
485 case SDL_JOYBUTTONDOWN:
486 case SDL_MOUSEBUTTONDOWN:
490 if(SDL_GetTicks() - ticks >= (max - min))
492 sound_manager->update();
498 static Uint32 last_timelog_ticks = 0;
499 static const char* last_timelog_component = 0;
501 static inline void timelog(const char* component)
503 Uint32 current_ticks = SDL_GetTicks();
505 if(last_timelog_component != 0) {
506 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
509 last_timelog_ticks = current_ticks;
510 last_timelog_component = component;
513 static inline void timelog(const char* )
518 std::istream* physfs_open_file(const char* name)
520 return new IFileStream(name);
523 void physfs_free_list(char** name)
525 PHYSFS_freeList(name);
528 int supertux_main(int argc, char** argv)
534 if(pre_parse_commandline(argc, argv))
537 Console::instance = new Console();
538 init_physfs(argv[0]);
541 { // Let tinygettext use PhysFS
542 tinygettext::DirOp dir_op;
543 dir_op.enumerate_files = &PHYSFS_enumerateFiles;
544 dir_op.free_list = &physfs_free_list;
545 dir_op.open_file = &physfs_open_file;
547 dictionary_manager.set_dir_op(dir_op);
550 timelog("controller");
551 g_main_controller = new JoystickKeyboardController();
557 AddonManager::get_instance().load_addons();
559 timelog("tinygettext");
562 timelog("commandline");
563 if(parse_commandline(argc, argv))
570 DrawingContext context;
571 context_pointer = &context;
574 Console::instance->init_graphics();
576 timelog("scripting");
577 Scripting::init_squirrel(g_config->enable_script_debugger);
579 timelog("resources");
584 g_main_loop = new MainLoop();
585 if(g_config->start_level != "") {
586 // we have a normal path specified at commandline, not a physfs path.
587 // So we simply mount that path here...
588 std::string dir = FileSystem::dirname(g_config->start_level);
589 log_debug << "Adding dir: " << dir << std::endl;
590 PHYSFS_addToSearchPath(dir.c_str(), true);
592 if(g_config->start_level.size() > 4 &&
593 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
595 g_main_loop->push_screen(new WorldMapNS::WorldMap(
596 FileSystem::basename(g_config->start_level)));
598 init_rand();//If level uses random eg. for
599 // rain particles before we do this:
600 std::auto_ptr<GameSession> session (
601 new GameSession(FileSystem::basename(g_config->start_level)));
603 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
604 init_rand();//initialise generator with seed from session
606 if(g_config->start_demo != "")
607 session->play_demo(g_config->start_demo);
609 if(g_config->record_demo != "")
610 session->record_demo(g_config->record_demo);
611 g_main_loop->push_screen(session.release());
615 g_main_loop->push_screen(new TitleScreen());
618 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
619 g_main_loop->run(context);
620 } catch(std::exception& e) {
621 log_fatal << "Unexpected exception: " << e.what() << std::endl;
624 log_fatal << "Unexpected exception" << std::endl;
638 delete g_main_controller;
639 g_main_controller = NULL;
640 delete Console::instance;
641 Console::instance = NULL;
642 Scripting::exit_squirrel();
643 delete texture_manager;
644 texture_manager = NULL;