00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017 #include <config.h>
00018 #include <version.h>
00019
00020 #include <SDL_image.h>
00021 #include <physfs.h>
00022 #include <iostream>
00023 #include <binreloc.h>
00024 #include <tinygettext/log.hpp>
00025 #include <boost/format.hpp>
00026 extern "C" {
00027 #include <findlocale.h>
00028 }
00029
00030 #include "supertux/main.hpp"
00031
00032 #ifdef MACOSX
00033 namespace supertux_apple {
00034 # include <CoreFoundation/CoreFoundation.h>
00035 }
00036 #endif
00037
00038 #include "addon/addon_manager.hpp"
00039 #include "audio/sound_manager.hpp"
00040 #include "control/joystickkeyboardcontroller.hpp"
00041 #include "math/random_generator.hpp"
00042 #include "physfs/ifile_stream.hpp"
00043 #include "physfs/physfs_sdl.hpp"
00044 #include "physfs/physfs_file_system.hpp"
00045 #include "scripting/squirrel_util.hpp"
00046 #include "supertux/gameconfig.hpp"
00047 #include "supertux/globals.hpp"
00048 #include "supertux/player_status.hpp"
00049 #include "supertux/screen_manager.hpp"
00050 #include "supertux/resources.hpp"
00051 #include "supertux/title_screen.hpp"
00052 #include "util/file_system.hpp"
00053 #include "util/gettext.hpp"
00054 #include "video/drawing_context.hpp"
00055 #include "worldmap/worldmap.hpp"
00056
00057 namespace { DrawingContext *context_pointer; }
00058
00059 #ifdef _WIN32
00060 # define WRITEDIR_NAME PACKAGE_NAME
00061 #else
00062 # define WRITEDIR_NAME "." PACKAGE_NAME
00063 #endif
00064
00065 void
00066 Main::init_config()
00067 {
00068 g_config = new Config();
00069 try {
00070 g_config->load();
00071 } catch(std::exception& e) {
00072 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
00073 }
00074 }
00075
00076 void
00077 Main::init_tinygettext()
00078 {
00079 dictionary_manager = new tinygettext::DictionaryManager();
00080 tinygettext::Log::set_log_info_callback(0);
00081 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
00082
00083 dictionary_manager->add_directory("locale");
00084 dictionary_manager->set_charset("UTF-8");
00085
00086
00087 if (g_config->locale != "")
00088 {
00089 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
00090 } else {
00091 FL_Locale *locale;
00092 FL_FindLocale(&locale, FL_MESSAGES);
00093 tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
00094 FL_FreeLocale(&locale);
00095 dictionary_manager->set_language(language);
00096 }
00097 }
00098
00099 void
00100 Main::init_physfs(const char* argv0)
00101 {
00102 if(!PHYSFS_init(argv0)) {
00103 std::stringstream msg;
00104 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
00105 throw std::runtime_error(msg.str());
00106 }
00107
00108
00109 PHYSFS_permitSymbolicLinks(1);
00110
00111
00112
00113 const char *env_writedir;
00114 std::string writedir;
00115
00116 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
00117 writedir = env_writedir;
00118 if(!PHYSFS_setWriteDir(writedir.c_str())) {
00119 std::ostringstream msg;
00120 msg << "Failed to use configuration directory '"
00121 << writedir << "': " << PHYSFS_getLastError();
00122 throw std::runtime_error(msg.str());
00123 }
00124
00125 } else {
00126 std::string userdir = PHYSFS_getUserDir();
00127
00128
00129 writedir = userdir + WRITEDIR_NAME;
00130 if(!PHYSFS_setWriteDir(writedir.c_str())) {
00131
00132 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
00133 std::ostringstream msg;
00134 msg << "Failed creating configuration directory '"
00135 << writedir << "': " << PHYSFS_getLastError();
00136 throw std::runtime_error(msg.str());
00137 }
00138
00139 if(!PHYSFS_setWriteDir(writedir.c_str())) {
00140 std::ostringstream msg;
00141 msg << "Failed to use configuration directory '"
00142 << writedir << "': " << PHYSFS_getLastError();
00143 throw std::runtime_error(msg.str());
00144 }
00145 }
00146 }
00147 PHYSFS_addToSearchPath(writedir.c_str(), 0);
00148
00149
00150 std::string dir = PHYSFS_getBaseDir();
00151 if (dir[dir.length() - 1] != '/')
00152 dir += "/";
00153 dir += "data";
00154 std::string testfname = dir;
00155 testfname += "/credits.txt";
00156 bool sourcedir = false;
00157 FILE* f = fopen(testfname.c_str(), "r");
00158 if(f) {
00159 fclose(f);
00160 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
00161 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
00162 } else {
00163 sourcedir = true;
00164 }
00165 }
00166
00167 #ifdef MACOSX
00168 {
00169 using namespace supertux_apple;
00170
00171
00172 char path[PATH_MAX];
00173 CFBundleRef mainBundle = CFBundleGetMainBundle();
00174 assert(mainBundle != 0);
00175 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
00176 assert(mainBundleURL != 0);
00177 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
00178 assert(pathStr != 0);
00179 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
00180 CFRelease(mainBundleURL);
00181 CFRelease(pathStr);
00182
00183 dir = std::string(path) + "/Contents/Resources/data";
00184 testfname = dir + "/credits.txt";
00185 sourcedir = false;
00186 f = fopen(testfname.c_str(), "r");
00187 if(f) {
00188 fclose(f);
00189 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
00190 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
00191 } else {
00192 sourcedir = true;
00193 }
00194 }
00195 }
00196 #endif
00197
00198 #ifdef _WIN32
00199 PHYSFS_addToSearchPath(".\\data", 1);
00200 #endif
00201
00202 if(!sourcedir) {
00203 std::string datadir = PHYSFS_getBaseDir();
00204 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
00205 datadir += "/" INSTALL_SUBDIR_SHARE;
00206 #ifdef ENABLE_BINRELOC
00207
00208 char* dir;
00209 br_init (NULL);
00210 dir = br_find_data_dir(datadir.c_str());
00211 datadir = dir;
00212 free(dir);
00213
00214 #endif
00215 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
00216 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
00217 }
00218 }
00219
00220
00221 char** searchpath = PHYSFS_getSearchPath();
00222 for(char** i = searchpath; *i != NULL; i++)
00223 log_info << "[" << *i << "] is in the search path" << std::endl;
00224 PHYSFS_freeList(searchpath);
00225 }
00226
00227 void
00228 Main::print_usage(const char* argv0)
00229 {
00230 std::string default_user_data_dir =
00231 std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
00232
00233 std::cerr << boost::format(_(
00234 "\n"
00235 "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
00236 "Options:\n"
00237 " -f, --fullscreen Run in fullscreen mode\n"
00238 " -w, --window Run in window mode\n"
00239 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
00240 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
00241 " -d, --default Reset video settings to default values\n"
00242 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
00243 " --disable-sfx Disable sound effects\n"
00244 " --disable-music Disable music\n"
00245 " -h, --help Show this help message and quit\n"
00246 " -v, --version Show SuperTux version and quit\n"
00247 " --console Enable ingame scripting console\n"
00248 " --noconsole Disable ingame scripting console\n"
00249 " --show-fps Display framerate in levels\n"
00250 " --no-show-fps Do not display framerate in levels\n"
00251 " --record-demo FILE LEVEL Record a demo to FILE\n"
00252 " --play-demo FILE LEVEL Play a recorded demo\n"
00253 " -s, --debug-scripts Enable script debugger.\n"
00254 " --print-datadir Print supertux's primary data directory.\n"
00255 "\n"
00256 "Environment variables:\n"
00257 " SUPERTUX2_USER_DIR Directory for user data (savegames, etc.);\n"
00258 " default %s\n"
00259 "\n"
00260 ))
00261 % argv0 % default_user_data_dir
00262 << std::flush;
00263 }
00264
00268 bool
00269 Main::pre_parse_commandline(int argc, char** argv)
00270 {
00271 for(int i = 1; i < argc; ++i) {
00272 std::string arg = argv[i];
00273
00274 if(arg == "--version" || arg == "-v") {
00275 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
00276 return true;
00277 }
00278 if(arg == "--help" || arg == "-h") {
00279 print_usage(argv[0]);
00280 return true;
00281 }
00282 if(arg == "--print-datadir") {
00283
00284
00285
00286
00287 char **sp;
00288 size_t sp_index;
00289 sp = PHYSFS_getSearchPath();
00290 if (sp)
00291 for (sp_index = 0; sp[sp_index]; sp_index++)
00292 std::cout << sp[sp_index] << std::endl;
00293 PHYSFS_freeList(sp);
00294 return true;
00295 }
00296 }
00297
00298 return false;
00299 }
00300
00304 bool
00305 Main::parse_commandline(int argc, char** argv)
00306 {
00307 for(int i = 1; i < argc; ++i) {
00308 std::string arg = argv[i];
00309
00310 if(arg == "--fullscreen" || arg == "-f") {
00311 g_config->use_fullscreen = true;
00312 } else if(arg == "--default" || arg == "-d") {
00313 g_config->use_fullscreen = false;
00314
00315 g_config->window_size = Size(800, 600);
00316 g_config->fullscreen_size = Size(800, 600);
00317 g_config->aspect_size = Size(0, 0);
00318
00319 } else if(arg == "--window" || arg == "-w") {
00320 g_config->use_fullscreen = false;
00321 } else if(arg == "--geometry" || arg == "-g") {
00322 i += 1;
00323 if(i >= argc)
00324 {
00325 print_usage(argv[0]);
00326 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
00327 }
00328 else
00329 {
00330 int width, height;
00331 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
00332 {
00333 print_usage(argv[0]);
00334 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
00335 }
00336 else
00337 {
00338 g_config->window_size = Size(width, height);
00339 g_config->fullscreen_size = Size(width, height);
00340 }
00341 }
00342 } else if(arg == "--aspect" || arg == "-a") {
00343 i += 1;
00344 if(i >= argc)
00345 {
00346 print_usage(argv[0]);
00347 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
00348 }
00349 else
00350 {
00351 int aspect_width = 0;
00352 int aspect_height = 0;
00353 if (strcmp(argv[i], "auto") == 0)
00354 {
00355 aspect_width = 0;
00356 aspect_height = 0;
00357 }
00358 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
00359 {
00360 print_usage(argv[0]);
00361 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
00362 }
00363 else
00364 {
00365 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
00366
00367
00368 if (aspect_ratio > 1) {
00369 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
00370 600);
00371 } else {
00372 g_config->aspect_size = Size(600,
00373 static_cast<int>(600 * 1/aspect_ratio + 0.5));
00374 }
00375 }
00376 }
00377 } else if(arg == "--renderer") {
00378 i += 1;
00379 if(i >= argc)
00380 {
00381 print_usage(argv[0]);
00382 throw std::runtime_error("Need to specify a renderer for renderer argument");
00383 }
00384 else
00385 {
00386 g_config->video = VideoSystem::get_video_system(argv[i]);
00387 }
00388 } else if(arg == "--show-fps") {
00389 g_config->show_fps = true;
00390 } else if(arg == "--no-show-fps") {
00391 g_config->show_fps = false;
00392 } else if(arg == "--console") {
00393 g_config->console_enabled = true;
00394 } else if(arg == "--noconsole") {
00395 g_config->console_enabled = false;
00396 } else if(arg == "--disable-sfx") {
00397 g_config->sound_enabled = false;
00398 } else if(arg == "--disable-music") {
00399 g_config->music_enabled = false;
00400 } else if(arg == "--play-demo") {
00401 if(i+1 >= argc) {
00402 print_usage(argv[0]);
00403 throw std::runtime_error("Need to specify a demo filename");
00404 }
00405 g_config->start_demo = argv[++i];
00406 } else if(arg == "--record-demo") {
00407 if(i+1 >= argc) {
00408 print_usage(argv[0]);
00409 throw std::runtime_error("Need to specify a demo filename");
00410 }
00411 g_config->record_demo = argv[++i];
00412 } else if(arg == "--debug-scripts" || arg == "-s") {
00413 g_config->enable_script_debugger = true;
00414 } else if(arg[0] != '-') {
00415 g_config->start_level = arg;
00416 } else {
00417 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
00418 return true;
00419 }
00420 }
00421
00422 return false;
00423 }
00424
00425 void
00426 Main::init_sdl()
00427 {
00428 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
00429 std::stringstream msg;
00430 msg << "Couldn't initialize SDL: " << SDL_GetError();
00431 throw std::runtime_error(msg.str());
00432 }
00433
00434 atexit(SDL_Quit);
00435
00436 SDL_EnableUNICODE(1);
00437
00438
00439
00440 SDL_Delay(100);
00441 SDL_Event dummy;
00442 while(SDL_PollEvent(&dummy))
00443 ;
00444 }
00445
00446 void
00447 Main::init_rand()
00448 {
00449 g_config->random_seed = gameRandom.srand(g_config->random_seed);
00450
00451 graphicsRandom.srand(0);
00452
00453
00454
00455 }
00456
00457 void
00458 Main::init_video()
00459 {
00460
00461 SCREEN_WIDTH = 800;
00462 SCREEN_HEIGHT = 600;
00463
00464 context_pointer->init_renderer();
00465 g_screen = SDL_GetVideoSurface();
00466
00467 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
00468
00469
00470 #ifdef MACOSX
00471 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
00472 #else
00473 const char* icon_fname = "images/engine/icons/supertux.xpm";
00474 #endif
00475 SDL_Surface* icon;
00476 try {
00477 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
00478 } catch (const std::runtime_error& err) {
00479 icon = 0;
00480 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
00481 }
00482 if(icon != 0) {
00483 SDL_WM_SetIcon(icon, 0);
00484 SDL_FreeSurface(icon);
00485 }
00486 else {
00487 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
00488 }
00489
00490 SDL_ShowCursor(0);
00491
00492 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
00493 << " Window: " << g_config->window_size
00494 << " Fullscreen: " << g_config->fullscreen_size
00495 << " Area: " << g_config->aspect_size << std::endl;
00496 }
00497
00498 void
00499 Main::init_audio()
00500 {
00501 sound_manager = new SoundManager();
00502
00503 sound_manager->enable_sound(g_config->sound_enabled);
00504 sound_manager->enable_music(g_config->music_enabled);
00505 }
00506
00507 void
00508 Main::quit_audio()
00509 {
00510 if(sound_manager != NULL) {
00511 delete sound_manager;
00512 sound_manager = NULL;
00513 }
00514 }
00515
00516 void
00517 Main::wait_for_event(float min_delay, float max_delay)
00518 {
00519 assert(min_delay <= max_delay);
00520
00521 Uint32 min = (Uint32) (min_delay * 1000);
00522 Uint32 max = (Uint32) (max_delay * 1000);
00523
00524 Uint32 ticks = SDL_GetTicks();
00525 while(SDL_GetTicks() - ticks < min) {
00526 SDL_Delay(10);
00527 sound_manager->update();
00528 }
00529
00530
00531 SDL_Event event;
00532 while (SDL_PollEvent(&event))
00533 {}
00534
00535
00536 bool running = false;
00537 ticks = SDL_GetTicks();
00538 while(running) {
00539 while(SDL_PollEvent(&event)) {
00540 switch(event.type) {
00541 case SDL_QUIT:
00542 g_screen_manager->quit();
00543 break;
00544 case SDL_KEYDOWN:
00545 case SDL_JOYBUTTONDOWN:
00546 case SDL_MOUSEBUTTONDOWN:
00547 running = false;
00548 }
00549 }
00550 if(SDL_GetTicks() - ticks >= (max - min))
00551 running = false;
00552 sound_manager->update();
00553 SDL_Delay(10);
00554 }
00555 }
00556
00557 static Uint32 last_timelog_ticks = 0;
00558 static const char* last_timelog_component = 0;
00559
00560 static inline void timelog(const char* component)
00561 {
00562 Uint32 current_ticks = SDL_GetTicks();
00563
00564 if(last_timelog_component != 0) {
00565 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
00566 }
00567
00568 last_timelog_ticks = current_ticks;
00569 last_timelog_component = component;
00570 }
00571
00572 int
00573 Main::run(int argc, char** argv)
00574 {
00575 int result = 0;
00576
00577 try {
00578
00579
00580 init_physfs(argv[0]);
00581
00582 if(pre_parse_commandline(argc, argv))
00583 return 0;
00584
00585 Console::instance = new Console();
00586 init_sdl();
00587
00588 timelog("controller");
00589 g_jk_controller = new JoystickKeyboardController();
00590
00591 timelog("config");
00592 init_config();
00593
00594 timelog("addons");
00595 AddonManager::get_instance().load_addons();
00596
00597 timelog("tinygettext");
00598 init_tinygettext();
00599
00600 timelog("commandline");
00601 if(parse_commandline(argc, argv))
00602 return 0;
00603
00604 timelog("audio");
00605 init_audio();
00606
00607 timelog("video");
00608 DrawingContext context;
00609 context_pointer = &context;
00610 init_video();
00611
00612 Console::instance->init_graphics();
00613
00614 timelog("scripting");
00615 scripting::init_squirrel(g_config->enable_script_debugger);
00616
00617 timelog("resources");
00618 Resources::load_shared();
00619
00620 timelog(0);
00621
00622 const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
00623
00624 g_screen_manager = new ScreenManager();
00625
00626 init_rand();
00627
00628 if(g_config->start_level != "") {
00629
00630
00631 std::string dir = FileSystem::dirname(g_config->start_level);
00632 log_debug << "Adding dir: " << dir << std::endl;
00633 PHYSFS_addToSearchPath(dir.c_str(), true);
00634
00635 if(g_config->start_level.size() > 4 &&
00636 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
00637 g_screen_manager->push_screen(new worldmap::WorldMap(
00638 FileSystem::basename(g_config->start_level), default_playerstatus.get()));
00639 } else {
00640 std::auto_ptr<GameSession> session (
00641 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
00642
00643 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
00644 init_rand();
00645
00646 if(g_config->start_demo != "")
00647 session->play_demo(g_config->start_demo);
00648
00649 if(g_config->record_demo != "")
00650 session->record_demo(g_config->record_demo);
00651 g_screen_manager->push_screen(session.release());
00652 }
00653 } else {
00654 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
00655 }
00656
00657 g_screen_manager->run(context);
00658 } catch(std::exception& e) {
00659 log_fatal << "Unexpected exception: " << e.what() << std::endl;
00660 result = 1;
00661 } catch(...) {
00662 log_fatal << "Unexpected exception" << std::endl;
00663 result = 1;
00664 }
00665
00666 delete g_screen_manager;
00667 g_screen_manager = NULL;
00668
00669 Resources::unload_shared();
00670 quit_audio();
00671
00672 if(g_config)
00673 g_config->save();
00674 delete g_config;
00675 g_config = NULL;
00676 delete g_jk_controller;
00677 g_jk_controller = NULL;
00678 delete Console::instance;
00679 Console::instance = NULL;
00680 scripting::exit_squirrel();
00681 delete texture_manager;
00682 texture_manager = NULL;
00683 SDL_Quit();
00684 PHYSFS_deinit();
00685
00686 return result;
00687 }
00688
00689