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 # include <CoreFoundation/CoreFoundation.h>
41 #include "gameconfig.hpp"
42 #include "resources.hpp"
43 #include "gettext.hpp"
44 #include "audio/sound_manager.hpp"
45 #include "video/surface.hpp"
46 #include "video/texture_manager.hpp"
47 #include "video/drawing_context.hpp"
48 #include "video/glutil.hpp"
49 #include "control/joystickkeyboardcontroller.hpp"
50 #include "options_menu.hpp"
51 #include "mainloop.hpp"
53 #include "game_session.hpp"
54 #include "scripting/level.hpp"
55 #include "scripting/squirrel_util.hpp"
56 #include "file_system.hpp"
57 #include "physfs/physfs_sdl.hpp"
58 #include "random_generator.hpp"
59 #include "worldmap/worldmap.hpp"
60 #include "binreloc/binreloc.h"
62 namespace { DrawingContext *context_pointer; }
64 JoystickKeyboardController* main_controller = 0;
65 TinyGetText::DictionaryManager dictionary_manager;
70 static void init_config()
72 config = new Config();
75 } catch(std::exception& e) {
76 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
80 static void init_tinygettext()
82 dictionary_manager.add_directory("locale");
83 dictionary_manager.set_charset("UTF-8");
85 // Config setting "locale" overrides language detection
86 if (config->locale != "") {
87 dictionary_manager.set_language( config->locale );
91 static void 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 // Initialize physfs (this is a slightly modified version of
100 // PHYSFS_setSaneConfig
101 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
102 const char* userdir = PHYSFS_getUserDir();
103 const char* dirsep = PHYSFS_getDirSeparator();
104 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
106 // Set configuration directory
107 sprintf(writedir, "%s.%s", userdir, application);
108 if(!PHYSFS_setWriteDir(writedir)) {
109 // try to create the directory
110 char* mkdir = new char[strlen(application) + 2];
111 sprintf(mkdir, ".%s", application);
112 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
113 std::ostringstream msg;
114 msg << "Failed creating configuration directory '"
115 << writedir << "': " << PHYSFS_getLastError();
118 throw std::runtime_error(msg.str());
122 if(!PHYSFS_setWriteDir(writedir)) {
123 std::ostringstream msg;
124 msg << "Failed to use configuration directory '"
125 << writedir << "': " << PHYSFS_getLastError();
127 throw std::runtime_error(msg.str());
130 PHYSFS_addToSearchPath(writedir, 0);
133 // Search for archives and add them to the search path
134 const char* archiveExt = "zip";
135 char** rc = PHYSFS_enumerateFiles("/");
136 size_t extlen = strlen(archiveExt);
138 for(char** i = rc; *i != 0; ++i) {
139 size_t l = strlen(*i);
140 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
141 const char* ext = (*i) + (l - extlen);
142 if(strcasecmp(ext, archiveExt) == 0) {
143 const char* d = PHYSFS_getRealDir(*i);
144 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
145 sprintf(str, "%s%s%s", d, dirsep, *i);
146 PHYSFS_addToSearchPath(str, 1);
154 // when started from source dir...
155 std::string dir = PHYSFS_getBaseDir();
157 std::string testfname = dir;
158 testfname += "/credits.txt";
159 bool sourcedir = false;
160 FILE* f = fopen(testfname.c_str(), "r");
163 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
164 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
171 // when started from Application file on Mac OS X...
173 CFBundleRef mainBundle = CFBundleGetMainBundle();
174 assert(mainBundle != 0);
175 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
176 assert(mainBundleURL != 0);
177 CFStringRef pathStr = CFUrlCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
178 assert(pathStr != 0);
179 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
180 CFRelease(mainBundleURL);
183 dir = std::string(path) + "/Contents/Resources/data";
184 testfname = dir + "/credits.txt";
186 f = fopen(testfname.c_str(), "r");
189 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
190 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
198 PHYSFS_addToSearchPath(".\\data", 1);
202 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
204 #ifdef ENABLE_BINRELOC
208 dir = br_find_data_dir(APPDATADIR);
213 datadir = APPDATADIR;
216 datadir += application;
217 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
218 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
223 // allow symbolic links
224 PHYSFS_permitSymbolicLinks(1);
227 char** searchpath = PHYSFS_getSearchPath();
228 for(char** i = searchpath; *i != NULL; i++)
229 log_info << "[" << *i << "] is in the search path" << std::endl;
230 PHYSFS_freeList(searchpath);
233 static void print_usage(const char* argv0)
235 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
238 " -f, --fullscreen Run in fullscreen mode\n"
239 " -w, --window Run in window mode\n"
240 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
241 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
242 " --disable-sfx Disable sound effects\n"
243 " --disable-music Disable music\n"
244 " --help Show this help message\n"
245 " --version Display SuperTux version and quit\n"
246 " --console Enable ingame scripting console\n"
247 " --noconsole Disable ingame scripting console\n"
248 " --show-fps Display framerate in levels\n"
249 " --no-show-fps Do not display framerate in levels\n"
250 " --record-demo FILE LEVEL Record a demo to FILE\n"
251 " --play-demo FILE LEVEL Play a recorded demo\n"
256 * Options that should be evaluated prior to any initializations at all go here
258 static bool pre_parse_commandline(int argc, char** argv)
260 for(int i = 1; i < argc; ++i) {
261 std::string arg = argv[i];
263 if(arg == "--version") {
264 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
273 * Options that should be evaluated after config is read go here
275 static bool parse_commandline(int argc, char** argv)
277 for(int i = 1; i < argc; ++i) {
278 std::string arg = argv[i];
280 if(arg == "--help") {
281 print_usage(argv[0]);
283 } else if(arg == "--fullscreen" || arg == "-f") {
284 config->use_fullscreen = true;
285 } else if(arg == "--window" || arg == "-w") {
286 config->use_fullscreen = false;
287 } else if(arg == "--geometry" || arg == "-g") {
289 print_usage(argv[0]);
290 throw std::runtime_error("Need to specify a parameter for geometry switch");
292 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
294 print_usage(argv[0]);
295 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
297 } else if(arg == "--aspect" || arg == "-a") {
299 print_usage(argv[0]);
300 throw std::runtime_error("Need to specify a parameter for aspect switch");
302 if(strcasecmp(argv[i+1], "auto") == 0) {
304 config->aspect_ratio = -1;
306 int aspect_width, aspect_height;
307 if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
308 print_usage(argv[0]);
309 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
311 config->aspect_ratio = static_cast<double>(aspect_width) /
312 static_cast<double>(aspect_height);
314 } else if(arg == "--show-fps") {
315 config->show_fps = true;
316 } else if(arg == "--no-show-fps") {
317 config->show_fps = false;
318 } else if(arg == "--console") {
319 config->console_enabled = true;
320 } else if(arg == "--noconsole") {
321 config->console_enabled = false;
322 } else if(arg == "--disable-sfx") {
323 config->sound_enabled = false;
324 } else if(arg == "--disable-music") {
325 config->music_enabled = false;
326 } else if(arg == "--play-demo") {
328 print_usage(argv[0]);
329 throw std::runtime_error("Need to specify a demo filename");
331 config->start_demo = argv[++i];
332 } else if(arg == "--record-demo") {
334 print_usage(argv[0]);
335 throw std::runtime_error("Need to specify a demo filename");
337 config->record_demo = argv[++i];
338 } else if(arg == "-d") {
339 config->enable_script_debugger = true;
340 } else if(arg[0] != '-') {
341 config->start_level = arg;
343 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
351 static void init_sdl()
353 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
354 std::stringstream msg;
355 msg << "Couldn't initialize SDL: " << SDL_GetError();
356 throw std::runtime_error(msg.str());
361 SDL_EnableUNICODE(1);
363 // wait 100ms and clear SDL event queue because sometimes we have random
364 // joystick events in the queue on startup...
367 while(SDL_PollEvent(&dummy))
371 static void init_rand()
373 config->random_seed = systemRandom.srand(config->random_seed);
375 //const char *how = config->random_seed? ", user fixed.": ", from time().";
376 //log_info << "Using random seed " << config->random_seed << how << std::endl;
381 static int desktop_width = 0;
382 static int desktop_height = 0;
384 /* unfortunately only newer SDLs have these infos */
385 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
386 /* find which resolution the user normally uses */
387 if(desktop_width == 0) {
388 const SDL_VideoInfo *info = SDL_GetVideoInfo();
389 desktop_width = info->current_w;
390 desktop_height = info->current_h;
394 double aspect_ratio = config->aspect_ratio;
396 // try to guess aspect ratio of monitor if needed
397 if (aspect_ratio <= 0) {
398 if(config->use_fullscreen && desktop_width > 0) {
399 aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
401 aspect_ratio = 4.0 / 3.0;
405 // use aspect ratio to calculate logical resolution
406 if (aspect_ratio > 1) {
407 SCREEN_WIDTH = static_cast<int> (600 * aspect_ratio + 0.5);
411 SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
414 context_pointer->init_renderer();
415 screen = SDL_GetVideoSurface();
417 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
420 SDL_Surface* icon = IMG_Load_RW(
421 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
423 SDL_WM_SetIcon(icon, 0);
424 SDL_FreeSurface(icon);
428 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
434 log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
437 static void init_audio()
439 sound_manager = new SoundManager();
441 sound_manager->enable_sound(config->sound_enabled);
442 sound_manager->enable_music(config->music_enabled);
445 static void quit_audio()
447 if(sound_manager != NULL) {
448 delete sound_manager;
449 sound_manager = NULL;
453 void wait_for_event(float min_delay, float max_delay)
455 assert(min_delay <= max_delay);
457 Uint32 min = (Uint32) (min_delay * 1000);
458 Uint32 max = (Uint32) (max_delay * 1000);
460 Uint32 ticks = SDL_GetTicks();
461 while(SDL_GetTicks() - ticks < min) {
463 sound_manager->update();
468 while (SDL_PollEvent(&event))
472 bool running = false;
473 ticks = SDL_GetTicks();
475 while(SDL_PollEvent(&event)) {
481 case SDL_JOYBUTTONDOWN:
482 case SDL_MOUSEBUTTONDOWN:
486 if(SDL_GetTicks() - ticks >= (max - min))
488 sound_manager->update();
494 static Uint32 last_timelog_ticks = 0;
495 static const char* last_timelog_component = 0;
497 static inline void timelog(const char* component)
499 Uint32 current_ticks = SDL_GetTicks();
501 if(last_timelog_component != 0) {
502 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
505 last_timelog_ticks = current_ticks;
506 last_timelog_component = component;
509 static inline void timelog(const char* )
514 int main(int argc, char** argv)
522 if(pre_parse_commandline(argc, argv))
525 Console::instance = new Console();
526 init_physfs(argv[0]);
529 timelog("controller");
530 main_controller = new JoystickKeyboardController();
533 timelog("tinygettext");
535 timelog("commandline");
536 if(parse_commandline(argc, argv))
541 DrawingContext context;
542 context_pointer = &context;
544 Console::instance->init_graphics();
545 timelog("scripting");
546 Scripting::init_squirrel(config->enable_script_debugger);
547 timelog("resources");
551 main_loop = new MainLoop();
552 if(config->start_level != "") {
553 // we have a normal path specified at commandline not physfs paths.
554 // So we simply mount that path here...
555 std::string dir = FileSystem::dirname(config->start_level);
556 PHYSFS_addToSearchPath(dir.c_str(), true);
558 if(config->start_level.size() > 4 &&
559 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
561 main_loop->push_screen(new WorldMapNS::WorldMap(
562 FileSystem::basename(config->start_level)));
564 init_rand();//If level uses random eg. for
565 // rain particles before we do this:
566 std::auto_ptr<GameSession> session (
567 new GameSession(FileSystem::basename(config->start_level)));
569 config->random_seed =session->get_demo_random_seed(config->start_demo);
570 init_rand();//initialise generator with seed from session
572 if(config->start_demo != "")
573 session->play_demo(config->start_demo);
575 if(config->record_demo != "")
576 session->record_demo(config->record_demo);
577 main_loop->push_screen(session.release());
581 main_loop->push_screen(new TitleScreen());
584 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
585 main_loop->run(context);
587 } catch(std::exception& e) {
588 log_fatal << "Unexpected exception: " << e.what() << std::endl;
591 log_fatal << "Unexpected exception" << std::endl;
606 delete main_controller;
607 main_controller = NULL;
608 delete Console::instance;
609 Console::instance = NULL;
610 Scripting::exit_squirrel();
611 delete texture_manager;
612 texture_manager = NULL;