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 {
29 #include "addon/addon_manager.hpp"
30 #include "audio/sound_manager.hpp"
31 #include "binreloc/binreloc.h"
32 #include "control/joystickkeyboardcontroller.hpp"
33 #include "math/random_generator.hpp"
34 #include "physfs/physfs_sdl.hpp"
35 #include "scripting/squirrel_util.hpp"
36 #include "supertux/gameconfig.hpp"
37 #include "supertux/mainloop.hpp"
38 #include "supertux/resources.hpp"
39 #include "supertux/globals.hpp"
40 #include "supertux/title_screen.hpp"
41 #include "util/file_system.hpp"
42 #include "util/gettext.hpp"
43 #include "video/drawing_context.hpp"
44 #include "supertux/globals.hpp"
45 #include "worldmap/worldmap.hpp"
47 namespace { DrawingContext *context_pointer; }
49 static void init_config()
51 g_config = new Config();
54 } catch(std::exception& e) {
55 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
59 static void init_tinygettext()
61 dictionary_manager.add_directory("locale");
62 dictionary_manager.set_charset("UTF-8");
64 // Config setting "locale" overrides language detection
65 if (g_config->locale != "") {
66 dictionary_manager.set_language( g_config->locale );
70 static void init_physfs(const char* argv0)
72 if(!PHYSFS_init(argv0)) {
73 std::stringstream msg;
74 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
75 throw std::runtime_error(msg.str());
78 // allow symbolic links
79 PHYSFS_permitSymbolicLinks(1);
81 // Initialize physfs (this is a slightly modified version of
82 // PHYSFS_setSaneConfig
83 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
84 const char* userdir = PHYSFS_getUserDir();
85 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
87 // Set configuration directory
88 sprintf(writedir, "%s.%s", userdir, application);
89 if(!PHYSFS_setWriteDir(writedir)) {
90 // try to create the directory
91 char* mkdir = new char[strlen(application) + 2];
92 sprintf(mkdir, ".%s", application);
93 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
94 std::ostringstream msg;
95 msg << "Failed creating configuration directory '"
96 << writedir << "': " << PHYSFS_getLastError();
99 throw std::runtime_error(msg.str());
103 if(!PHYSFS_setWriteDir(writedir)) {
104 std::ostringstream msg;
105 msg << "Failed to use configuration directory '"
106 << writedir << "': " << PHYSFS_getLastError();
108 throw std::runtime_error(msg.str());
111 PHYSFS_addToSearchPath(writedir, 0);
114 // when started from source dir...
115 std::string dir = PHYSFS_getBaseDir();
117 std::string testfname = dir;
118 testfname += "/credits.txt";
119 bool sourcedir = false;
120 FILE* f = fopen(testfname.c_str(), "r");
123 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
124 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
132 using namespace supertux_apple;
134 // when started from Application file on Mac OS X...
136 CFBundleRef mainBundle = CFBundleGetMainBundle();
137 assert(mainBundle != 0);
138 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
139 assert(mainBundleURL != 0);
140 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
141 assert(pathStr != 0);
142 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
143 CFRelease(mainBundleURL);
146 dir = std::string(path) + "/Contents/Resources/data";
147 testfname = dir + "/credits.txt";
149 f = fopen(testfname.c_str(), "r");
152 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
153 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
162 PHYSFS_addToSearchPath(".\\data", 1);
166 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
168 #ifdef ENABLE_BINRELOC
172 dir = br_find_data_dir(APPDATADIR);
177 datadir = APPDATADIR;
179 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
180 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
186 char** searchpath = PHYSFS_getSearchPath();
187 for(char** i = searchpath; *i != NULL; i++)
188 log_info << "[" << *i << "] is in the search path" << std::endl;
189 PHYSFS_freeList(searchpath);
192 static void print_usage(const char* argv0)
194 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
197 " -f, --fullscreen Run in fullscreen mode\n"
198 " -w, --window Run in window mode\n"
199 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
200 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
201 " -d, --default Reset video settings to default values\n"
202 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
203 " --disable-sfx Disable sound effects\n"
204 " --disable-music Disable music\n"
205 " -h, --help Show this help message and quit\n"
206 " -v, --version Show SuperTux version and quit\n"
207 " --console Enable ingame scripting console\n"
208 " --noconsole Disable ingame scripting console\n"
209 " --show-fps Display framerate in levels\n"
210 " --no-show-fps Do not display framerate in levels\n"
211 " --record-demo FILE LEVEL Record a demo to FILE\n"
212 " --play-demo FILE LEVEL Play a recorded demo\n"
213 " -s, --debug-scripts Enable script debugger.\n"
218 * Options that should be evaluated prior to any initializations at all go here
220 static bool pre_parse_commandline(int argc, char** argv)
222 for(int i = 1; i < argc; ++i) {
223 std::string arg = argv[i];
225 if(arg == "--version" || arg == "-v") {
226 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
229 if(arg == "--help" || arg == "-h") {
230 print_usage(argv[0]);
239 * Options that should be evaluated after config is read go here
241 static bool parse_commandline(int argc, char** argv)
243 for(int i = 1; i < argc; ++i) {
244 std::string arg = argv[i];
246 if(arg == "--fullscreen" || arg == "-f") {
247 g_config->use_fullscreen = true;
248 } else if(arg == "--default" || arg == "-d") {
249 g_config->use_fullscreen = false;
251 g_config->window_width = 800;
252 g_config->window_height = 600;
254 g_config->fullscreen_width = 800;
255 g_config->fullscreen_height = 600;
257 g_config->aspect_width = 0; // auto detect
258 g_config->aspect_height = 0;
260 } else if(arg == "--window" || arg == "-w") {
261 g_config->use_fullscreen = false;
262 } else if(arg == "--geometry" || arg == "-g") {
266 print_usage(argv[0]);
267 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
272 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
274 print_usage(argv[0]);
275 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
279 g_config->window_width = width;
280 g_config->window_height = height;
282 g_config->fullscreen_width = width;
283 g_config->fullscreen_height = height;
286 } else if(arg == "--aspect" || arg == "-a") {
290 print_usage(argv[0]);
291 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
295 int aspect_width = 0;
296 int aspect_height = 0;
297 if (strcmp(argv[i], "auto") == 0)
302 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
304 print_usage(argv[0]);
305 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
309 float aspect_ratio = static_cast<double>(g_config->aspect_width) /
310 static_cast<double>(g_config->aspect_height);
312 // use aspect ratio to calculate logical resolution
313 if (aspect_ratio > 1) {
314 g_config->aspect_width = static_cast<int> (600 * aspect_ratio + 0.5);
315 g_config->aspect_height = 600;
317 g_config->aspect_width = 600;
318 g_config->aspect_height = static_cast<int> (600 * 1/aspect_ratio + 0.5);
322 } else if(arg == "--renderer") {
326 print_usage(argv[0]);
327 throw std::runtime_error("Need to specify a renderer for renderer argument");
331 g_config->video = get_video_system(argv[i]);
333 } else if(arg == "--show-fps") {
334 g_config->show_fps = true;
335 } else if(arg == "--no-show-fps") {
336 g_config->show_fps = false;
337 } else if(arg == "--console") {
338 g_config->console_enabled = true;
339 } else if(arg == "--noconsole") {
340 g_config->console_enabled = false;
341 } else if(arg == "--disable-sfx") {
342 g_config->sound_enabled = false;
343 } else if(arg == "--disable-music") {
344 g_config->music_enabled = false;
345 } else if(arg == "--play-demo") {
347 print_usage(argv[0]);
348 throw std::runtime_error("Need to specify a demo filename");
350 g_config->start_demo = argv[++i];
351 } else if(arg == "--record-demo") {
353 print_usage(argv[0]);
354 throw std::runtime_error("Need to specify a demo filename");
356 g_config->record_demo = argv[++i];
357 } else if(arg == "--debug-scripts" || arg == "-s") {
358 g_config->enable_script_debugger = true;
359 } else if(arg[0] != '-') {
360 g_config->start_level = arg;
362 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
370 static void init_sdl()
372 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
373 std::stringstream msg;
374 msg << "Couldn't initialize SDL: " << SDL_GetError();
375 throw std::runtime_error(msg.str());
380 SDL_EnableUNICODE(1);
382 // wait 100ms and clear SDL event queue because sometimes we have random
383 // joystick events in the queue on startup...
386 while(SDL_PollEvent(&dummy))
390 static void init_rand()
392 g_config->random_seed = systemRandom.srand(g_config->random_seed);
394 //const char *how = config->random_seed? ", user fixed.": ", from time().";
395 //log_info << "Using random seed " << config->random_seed << how << std::endl;
400 // FIXME: Add something here
404 context_pointer->init_renderer();
405 g_screen = SDL_GetVideoSurface();
407 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
411 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
413 const char* icon_fname = "images/engine/icons/supertux.xpm";
417 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
418 } catch (const std::runtime_error& err) {
420 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
423 SDL_WM_SetIcon(icon, 0);
424 SDL_FreeSurface(icon);
428 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
434 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
435 << " Window: " << g_config->window_width << "x" << g_config->window_height
436 << " Fullscreen: " << g_config->fullscreen_width << "x" << g_config->fullscreen_height
437 << " Area: " << g_config->aspect_width << "x" << g_config->aspect_height << std::endl;
440 static void init_audio()
442 sound_manager = new SoundManager();
444 sound_manager->enable_sound(g_config->sound_enabled);
445 sound_manager->enable_music(g_config->music_enabled);
448 static void quit_audio()
450 if(sound_manager != NULL) {
451 delete sound_manager;
452 sound_manager = NULL;
456 void wait_for_event(float min_delay, float max_delay)
458 assert(min_delay <= max_delay);
460 Uint32 min = (Uint32) (min_delay * 1000);
461 Uint32 max = (Uint32) (max_delay * 1000);
463 Uint32 ticks = SDL_GetTicks();
464 while(SDL_GetTicks() - ticks < min) {
466 sound_manager->update();
471 while (SDL_PollEvent(&event))
475 bool running = false;
476 ticks = SDL_GetTicks();
478 while(SDL_PollEvent(&event)) {
484 case SDL_JOYBUTTONDOWN:
485 case SDL_MOUSEBUTTONDOWN:
489 if(SDL_GetTicks() - ticks >= (max - min))
491 sound_manager->update();
497 static Uint32 last_timelog_ticks = 0;
498 static const char* last_timelog_component = 0;
500 static inline void timelog(const char* component)
502 Uint32 current_ticks = SDL_GetTicks();
504 if(last_timelog_component != 0) {
505 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
508 last_timelog_ticks = current_ticks;
509 last_timelog_component = component;
512 static inline void timelog(const char* )
517 int supertux_main(int argc, char** argv)
523 if(pre_parse_commandline(argc, argv))
526 Console::instance = new Console();
527 init_physfs(argv[0]);
530 timelog("controller");
531 g_main_controller = new JoystickKeyboardController();
537 AddonManager::get_instance().load_addons();
539 timelog("tinygettext");
542 timelog("commandline");
543 if(parse_commandline(argc, argv))
550 DrawingContext context;
551 context_pointer = &context;
554 Console::instance->init_graphics();
556 timelog("scripting");
557 Scripting::init_squirrel(g_config->enable_script_debugger);
559 timelog("resources");
564 g_main_loop = new MainLoop();
565 if(g_config->start_level != "") {
566 // we have a normal path specified at commandline, not a physfs path.
567 // So we simply mount that path here...
568 std::string dir = FileSystem::dirname(g_config->start_level);
569 log_debug << "Adding dir: " << dir << std::endl;
570 PHYSFS_addToSearchPath(dir.c_str(), true);
572 if(g_config->start_level.size() > 4 &&
573 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
575 g_main_loop->push_screen(new WorldMapNS::WorldMap(
576 FileSystem::basename(g_config->start_level)));
578 init_rand();//If level uses random eg. for
579 // rain particles before we do this:
580 std::auto_ptr<GameSession> session (
581 new GameSession(FileSystem::basename(g_config->start_level)));
583 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
584 init_rand();//initialise generator with seed from session
586 if(g_config->start_demo != "")
587 session->play_demo(g_config->start_demo);
589 if(g_config->record_demo != "")
590 session->record_demo(g_config->record_demo);
591 g_main_loop->push_screen(session.release());
595 g_main_loop->push_screen(new TitleScreen());
598 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
599 g_main_loop->run(context);
600 } catch(std::exception& e) {
601 log_fatal << "Unexpected exception: " << e.what() << std::endl;
604 log_fatal << "Unexpected exception" << std::endl;
618 delete g_main_controller;
619 g_main_controller = NULL;
620 delete Console::instance;
621 Console::instance = NULL;
622 Scripting::exit_squirrel();
623 delete texture_manager;
624 texture_manager = NULL;