4 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
6 // This program is free software; you can redistribute it and/or
7 // modify it under the terms of the GNU General Public License
8 // as published by the Free Software Foundation; either version 2
9 // of the License, or (at your option) any later version.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License
17 // along with this program; if not, write to the Free Software
18 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
31 #include <sys/types.h>
35 #include <SDL_image.h>
38 namespace supertux_apple {
39 #include <CoreFoundation/CoreFoundation.h>
43 #include "gameconfig.hpp"
44 #include "resources.hpp"
45 #include "gettext.hpp"
46 #include "audio/sound_manager.hpp"
47 #include "video/surface.hpp"
48 #include "video/texture_manager.hpp"
49 #include "video/drawing_context.hpp"
50 #include "video/glutil.hpp"
51 #include "control/joystickkeyboardcontroller.hpp"
52 #include "options_menu.hpp"
53 #include "mainloop.hpp"
55 #include "game_session.hpp"
56 #include "scripting/level.hpp"
57 #include "scripting/squirrel_util.hpp"
58 #include "file_system.hpp"
59 #include "physfs/physfs_sdl.hpp"
60 #include "random_generator.hpp"
61 #include "worldmap/worldmap.hpp"
62 #include "addon/addon_manager.hpp"
63 #include "binreloc/binreloc.h"
65 namespace { DrawingContext *context_pointer; }
67 JoystickKeyboardController* main_controller = 0;
68 TinyGetText::DictionaryManager dictionary_manager;
73 static void init_config()
75 config = new Config();
78 } catch(std::exception& e) {
79 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
83 static void init_tinygettext()
85 dictionary_manager.add_directory("locale");
86 dictionary_manager.set_charset("UTF-8");
88 // Config setting "locale" overrides language detection
89 if (config->locale != "") {
90 dictionary_manager.set_language( config->locale );
94 static void init_physfs(const char* argv0)
96 if(!PHYSFS_init(argv0)) {
97 std::stringstream msg;
98 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
99 throw std::runtime_error(msg.str());
102 // allow symbolic links
103 PHYSFS_permitSymbolicLinks(1);
105 // Initialize physfs (this is a slightly modified version of
106 // PHYSFS_setSaneConfig
107 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
108 const char* userdir = PHYSFS_getUserDir();
109 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
111 // Set configuration directory
112 sprintf(writedir, "%s.%s", userdir, application);
113 if(!PHYSFS_setWriteDir(writedir)) {
114 // try to create the directory
115 char* mkdir = new char[strlen(application) + 2];
116 sprintf(mkdir, ".%s", application);
117 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
118 std::ostringstream msg;
119 msg << "Failed creating configuration directory '"
120 << writedir << "': " << PHYSFS_getLastError();
123 throw std::runtime_error(msg.str());
127 if(!PHYSFS_setWriteDir(writedir)) {
128 std::ostringstream msg;
129 msg << "Failed to use configuration directory '"
130 << writedir << "': " << PHYSFS_getLastError();
132 throw std::runtime_error(msg.str());
135 PHYSFS_addToSearchPath(writedir, 0);
138 // when started from source dir...
139 std::string dir = PHYSFS_getBaseDir();
141 std::string testfname = dir;
142 testfname += "/credits.txt";
143 bool sourcedir = false;
144 FILE* f = fopen(testfname.c_str(), "r");
147 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
148 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
156 using namespace supertux_apple;
158 // when started from Application file on Mac OS X...
160 CFBundleRef mainBundle = CFBundleGetMainBundle();
161 assert(mainBundle != 0);
162 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
163 assert(mainBundleURL != 0);
164 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
165 assert(pathStr != 0);
166 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
167 CFRelease(mainBundleURL);
170 dir = std::string(path) + "/Contents/Resources/data";
171 testfname = dir + "/credits.txt";
173 f = fopen(testfname.c_str(), "r");
176 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
177 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
186 PHYSFS_addToSearchPath(".\\data", 1);
190 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
192 #ifdef ENABLE_BINRELOC
196 dir = br_find_data_dir(APPDATADIR);
201 datadir = APPDATADIR;
203 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
204 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);
216 static void print_usage(const char* argv0)
218 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
221 " -f, --fullscreen Run in fullscreen mode\n"
222 " -w, --window Run in window mode\n"
223 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
224 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
225 " -d, --default Reset video settings to default values\n"
226 " --disable-sfx Disable sound effects\n"
227 " --disable-music Disable music\n"
228 " --help Show this help message\n"
229 " --version Display SuperTux version and quit\n"
230 " --console Enable ingame scripting console\n"
231 " --noconsole Disable ingame scripting console\n"
232 " --show-fps Display framerate in levels\n"
233 " --no-show-fps Do not display framerate in levels\n"
234 " --record-demo FILE LEVEL Record a demo to FILE\n"
235 " --play-demo FILE LEVEL Play a recorded demo\n"
240 * Options that should be evaluated prior to any initializations at all go here
242 static bool pre_parse_commandline(int argc, char** argv)
244 for(int i = 1; i < argc; ++i) {
245 std::string arg = argv[i];
247 if(arg == "--version") {
248 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
257 * Options that should be evaluated after config is read go here
259 static bool parse_commandline(int argc, char** argv)
261 for(int i = 1; i < argc; ++i) {
262 std::string arg = argv[i];
264 if(arg == "--help") {
265 print_usage(argv[0]);
267 } else if(arg == "--fullscreen" || arg == "-f") {
268 config->use_fullscreen = true;
269 } else if(arg == "--default" || arg == "-d") {
270 config->use_fullscreen = false;
272 config->window_width = 800;
273 config->window_height = 600;
275 config->fullscreen_width = 800;
276 config->fullscreen_height = 600;
278 config->aspect_width = 4;
279 config->aspect_height = 3;
281 } else if(arg == "--window" || arg == "-w") {
282 config->use_fullscreen = false;
283 } else if(arg == "--geometry" || arg == "-g") {
287 print_usage(argv[0]);
288 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
293 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
295 print_usage(argv[0]);
296 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
300 config->window_width = width;
301 config->window_height = height;
303 config->fullscreen_width = width;
304 config->fullscreen_height = height;
307 } else if(arg == "--aspect" || arg == "-a") {
311 print_usage(argv[0]);
312 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
316 int aspect_width = 0;
317 int aspect_height = 0;
318 if (strcmp(argv[i], "auto") == 0)
323 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
325 print_usage(argv[0]);
326 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
330 float aspect_ratio = static_cast<double>(config->aspect_width) /
331 static_cast<double>(config->aspect_height);
333 // use aspect ratio to calculate logical resolution
334 if (aspect_ratio > 1) {
335 config->aspect_width = static_cast<int> (600 * aspect_ratio + 0.5);
336 config->aspect_height = 600;
338 config->aspect_width = 600;
339 config->aspect_height = static_cast<int> (600 * 1/aspect_ratio + 0.5);
343 } else if(arg == "--show-fps") {
344 config->show_fps = true;
345 } else if(arg == "--no-show-fps") {
346 config->show_fps = false;
347 } else if(arg == "--console") {
348 config->console_enabled = true;
349 } else if(arg == "--noconsole") {
350 config->console_enabled = false;
351 } else if(arg == "--disable-sfx") {
352 config->sound_enabled = false;
353 } else if(arg == "--disable-music") {
354 config->music_enabled = false;
355 } else if(arg == "--play-demo") {
357 print_usage(argv[0]);
358 throw std::runtime_error("Need to specify a demo filename");
360 config->start_demo = argv[++i];
361 } else if(arg == "--record-demo") {
363 print_usage(argv[0]);
364 throw std::runtime_error("Need to specify a demo filename");
366 config->record_demo = argv[++i];
367 } else if(arg == "-d") {
368 config->enable_script_debugger = true;
369 } else if(arg[0] != '-') {
370 config->start_level = arg;
372 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
380 static void init_sdl()
382 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
383 std::stringstream msg;
384 msg << "Couldn't initialize SDL: " << SDL_GetError();
385 throw std::runtime_error(msg.str());
390 SDL_EnableUNICODE(1);
392 // wait 100ms and clear SDL event queue because sometimes we have random
393 // joystick events in the queue on startup...
396 while(SDL_PollEvent(&dummy))
400 static void init_rand()
402 config->random_seed = systemRandom.srand(config->random_seed);
404 //const char *how = config->random_seed? ", user fixed.": ", from time().";
405 //log_info << "Using random seed " << config->random_seed << how << std::endl;
410 // FIXME: Add something here
414 context_pointer->init_renderer();
415 screen = SDL_GetVideoSurface();
417 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
421 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
423 const char* icon_fname = "images/engine/icons/supertux.xpm";
425 SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
427 SDL_WM_SetIcon(icon, 0);
428 SDL_FreeSurface(icon);
432 log_warning << "Couldn't find icon '" << icon_fname << "'" << std::endl;
438 log_info << (config->use_fullscreen?"fullscreen ":"window ")
439 << " Window: " << config->window_width << "x" << config->window_height
440 << " Fullscreen: " << config->fullscreen_width << "x" << config->fullscreen_height
441 << " Area: " << config->aspect_width << "x" << config->aspect_height << std::endl;
444 static void init_audio()
446 sound_manager = new SoundManager();
448 sound_manager->enable_sound(config->sound_enabled);
449 sound_manager->enable_music(config->music_enabled);
452 static void quit_audio()
454 if(sound_manager != NULL) {
455 delete sound_manager;
456 sound_manager = NULL;
460 void wait_for_event(float min_delay, float max_delay)
462 assert(min_delay <= max_delay);
464 Uint32 min = (Uint32) (min_delay * 1000);
465 Uint32 max = (Uint32) (max_delay * 1000);
467 Uint32 ticks = SDL_GetTicks();
468 while(SDL_GetTicks() - ticks < min) {
470 sound_manager->update();
475 while (SDL_PollEvent(&event))
479 bool running = false;
480 ticks = SDL_GetTicks();
482 while(SDL_PollEvent(&event)) {
488 case SDL_JOYBUTTONDOWN:
489 case SDL_MOUSEBUTTONDOWN:
493 if(SDL_GetTicks() - ticks >= (max - min))
495 sound_manager->update();
501 static Uint32 last_timelog_ticks = 0;
502 static const char* last_timelog_component = 0;
504 static inline void timelog(const char* component)
506 Uint32 current_ticks = SDL_GetTicks();
508 if(last_timelog_component != 0) {
509 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
512 last_timelog_ticks = current_ticks;
513 last_timelog_component = component;
516 static inline void timelog(const char* )
521 int main(int argc, char** argv)
529 if(pre_parse_commandline(argc, argv))
532 Console::instance = new Console();
533 init_physfs(argv[0]);
536 timelog("controller");
537 main_controller = new JoystickKeyboardController();
543 AddonManager::get_instance().load_addons();
545 timelog("tinygettext");
548 timelog("commandline");
549 if(parse_commandline(argc, argv))
556 DrawingContext context;
557 context_pointer = &context;
560 Console::instance->init_graphics();
562 timelog("scripting");
563 Scripting::init_squirrel(config->enable_script_debugger);
565 timelog("resources");
570 main_loop = new MainLoop();
571 if(config->start_level != "") {
572 // we have a normal path specified at commandline not physfs paths.
573 // So we simply mount that path here...
574 std::string dir = FileSystem::dirname(config->start_level);
575 PHYSFS_addToSearchPath(dir.c_str(), true);
577 if(config->start_level.size() > 4 &&
578 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
580 main_loop->push_screen(new WorldMapNS::WorldMap(
581 FileSystem::basename(config->start_level)));
583 init_rand();//If level uses random eg. for
584 // rain particles before we do this:
585 std::auto_ptr<GameSession> session (
586 new GameSession(FileSystem::basename(config->start_level)));
588 config->random_seed =session->get_demo_random_seed(config->start_demo);
589 init_rand();//initialise generator with seed from session
591 if(config->start_demo != "")
592 session->play_demo(config->start_demo);
594 if(config->record_demo != "")
595 session->record_demo(config->record_demo);
596 main_loop->push_screen(session.release());
600 main_loop->push_screen(new TitleScreen());
603 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
604 main_loop->run(context);
606 } catch(std::exception& e) {
607 log_fatal << "Unexpected exception: " << e.what() << std::endl;
610 log_fatal << "Unexpected exception" << std::endl;
625 delete main_controller;
626 main_controller = NULL;
627 delete Console::instance;
628 Console::instance = NULL;
629 Scripting::exit_squirrel();
630 delete texture_manager;
631 texture_manager = NULL;