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>
24 #include <tinygettext/log.hpp>
25 #include <boost/format.hpp>
28 #include "supertux/main.hpp"
31 namespace supertux_apple {
32 # include <CoreFoundation/CoreFoundation.h>
33 } // namespace supertux_apple
36 #include "addon/addon_manager.hpp"
37 #include "audio/sound_manager.hpp"
38 #include "control/joystickkeyboardcontroller.hpp"
39 #include "math/random_generator.hpp"
40 #include "physfs/ifile_stream.hpp"
41 #include "physfs/physfs_sdl.hpp"
42 #include "physfs/physfs_file_system.hpp"
43 #include "scripting/squirrel_util.hpp"
44 #include "supertux/gameconfig.hpp"
45 #include "supertux/globals.hpp"
46 #include "supertux/player_status.hpp"
47 #include "supertux/screen_manager.hpp"
48 #include "supertux/resources.hpp"
49 #include "supertux/title_screen.hpp"
50 #include "util/file_system.hpp"
51 #include "util/gettext.hpp"
52 #include "video/drawing_context.hpp"
53 #include "worldmap/worldmap.hpp"
55 namespace { DrawingContext *context_pointer; }
58 # define WRITEDIR_NAME PACKAGE_NAME
60 # define WRITEDIR_NAME "." PACKAGE_NAME
66 g_config = new Config();
69 } catch(std::exception& e) {
70 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
75 Main::init_tinygettext()
77 dictionary_manager = new tinygettext::DictionaryManager();
78 tinygettext::Log::set_log_info_callback(0);
79 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
81 dictionary_manager->add_directory("locale");
82 dictionary_manager->set_charset("UTF-8");
84 // Config setting "locale" overrides language detection
85 if (g_config->locale != "")
87 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
92 Main::init_physfs(const char* argv0)
94 if(!PHYSFS_init(argv0)) {
95 std::stringstream msg;
96 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
97 throw std::runtime_error(msg.str());
100 // allow symbolic links
101 PHYSFS_permitSymbolicLinks(1);
103 // Initialize physfs (this is a slightly modified version of
104 // PHYSFS_setSaneConfig)
105 const char *env_writedir;
106 std::string writedir;
108 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
109 writedir = env_writedir;
110 if(!PHYSFS_setWriteDir(writedir.c_str())) {
111 std::ostringstream msg;
112 msg << "Failed to use configuration directory '"
113 << writedir << "': " << PHYSFS_getLastError();
114 throw std::runtime_error(msg.str());
118 std::string userdir = PHYSFS_getUserDir();
120 // Set configuration directory
121 writedir = userdir + WRITEDIR_NAME;
122 if(!PHYSFS_setWriteDir(writedir.c_str())) {
123 // try to create the directory
124 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
125 std::ostringstream msg;
126 msg << "Failed creating configuration directory '"
127 << writedir << "': " << PHYSFS_getLastError();
128 throw std::runtime_error(msg.str());
131 if(!PHYSFS_setWriteDir(writedir.c_str())) {
132 std::ostringstream msg;
133 msg << "Failed to use configuration directory '"
134 << writedir << "': " << PHYSFS_getLastError();
135 throw std::runtime_error(msg.str());
139 PHYSFS_addToSearchPath(writedir.c_str(), 0);
141 // when started from source dir...
142 std::string dir = PHYSFS_getBaseDir();
143 if (dir[dir.length() - 1] != '/')
146 std::string testfname = dir;
147 testfname += "/credits.txt";
148 bool sourcedir = false;
149 FILE* 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;
161 using namespace supertux_apple;
163 // when started from Application file on Mac OS X...
165 CFBundleRef mainBundle = CFBundleGetMainBundle();
166 assert(mainBundle != 0);
167 CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
168 assert(mainBundleURL != 0);
169 CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
170 assert(pathStr != 0);
171 CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
172 CFRelease(mainBundleURL);
175 dir = std::string(path) + "/Contents/Resources/data";
176 testfname = dir + "/credits.txt";
178 f = fopen(testfname.c_str(), "r");
181 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
182 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
191 PHYSFS_addToSearchPath(".\\data", 1);
195 std::string datadir = PHYSFS_getBaseDir();
196 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
197 datadir += "/" INSTALL_SUBDIR_SHARE;
198 #ifdef ENABLE_BINRELOC
202 dir = br_find_data_dir(datadir.c_str());
207 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
208 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
213 char** searchpath = PHYSFS_getSearchPath();
214 for(char** i = searchpath; *i != NULL; i++)
215 log_info << "[" << *i << "] is in the search path" << std::endl;
216 PHYSFS_freeList(searchpath);
220 Main::print_usage(const char* argv0)
222 std::string default_user_data_dir =
223 std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
225 std::cerr << boost::format(_(
227 "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
229 " -f, --fullscreen Run in fullscreen mode\n"
230 " -w, --window Run in window mode\n"
231 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
232 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
233 " -d, --default Reset video settings to default values\n"
234 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
235 " --disable-sfx Disable sound effects\n"
236 " --disable-music Disable music\n"
237 " -h, --help Show this help message and quit\n"
238 " -v, --version Show SuperTux version and quit\n"
239 " --console Enable ingame scripting console\n"
240 " --noconsole Disable ingame scripting console\n"
241 " --show-fps Display framerate in levels\n"
242 " --no-show-fps Do not display framerate in levels\n"
243 " --record-demo FILE LEVEL Record a demo to FILE\n"
244 " --play-demo FILE LEVEL Play a recorded demo\n"
245 " -s, --debug-scripts Enable script debugger.\n"
246 " --print-datadir Print supertux's primary data directory.\n"
248 "Environment variables:\n"
249 " SUPERTUX2_USER_DIR Directory for user data (savegames, etc.);\n"
253 % argv0 % default_user_data_dir
258 * Options that should be evaluated prior to any initializations at all go here
261 Main::pre_parse_commandline(int argc, char** argv)
263 for(int i = 1; i < argc; ++i) {
264 std::string arg = argv[i];
266 if(arg == "--version" || arg == "-v") {
267 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
270 if(arg == "--help" || arg == "-h") {
271 print_usage(argv[0]);
274 if(arg == "--print-datadir") {
276 * Print the datadir searchpath to stdout, one path per
277 * line. Then exit. Intended for use by the supertux-editor.
283 sp = PHYSFS_getSearchPath();
285 for (sp_index = 0; sp[sp_index]; sp_index ++)
287 writeptr = sp[sp_index];
291 write_ret = write(STDOUT_FILENO, writeptr, strlen(writeptr));
294 writeptr += write_ret;
296 write(STDOUT_FILENO, "\n", 1);
297 /* std::cout << sp[sp_index] << std::endl; */
308 * Options that should be evaluated after config is read go here
311 Main::parse_commandline(int argc, char** argv)
313 for(int i = 1; i < argc; ++i) {
314 std::string arg = argv[i];
316 if(arg == "--fullscreen" || arg == "-f") {
317 g_config->use_fullscreen = true;
318 } else if(arg == "--default" || arg == "-d") {
319 g_config->use_fullscreen = false;
321 g_config->window_size = Size(800, 600);
322 g_config->fullscreen_size = Size(800, 600);
323 g_config->aspect_size = Size(0, 0); // auto detect
325 } else if(arg == "--window" || arg == "-w") {
326 g_config->use_fullscreen = false;
327 } else if(arg == "--geometry" || arg == "-g") {
331 print_usage(argv[0]);
332 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
337 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
339 print_usage(argv[0]);
340 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
344 g_config->window_size = Size(width, height);
345 g_config->fullscreen_size = Size(width, height);
348 } else if(arg == "--aspect" || arg == "-a") {
352 print_usage(argv[0]);
353 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
357 int aspect_width = 0;
358 int aspect_height = 0;
359 if (strcmp(argv[i], "auto") == 0)
364 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
366 print_usage(argv[0]);
367 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
371 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
373 // use aspect ratio to calculate logical resolution
374 if (aspect_ratio > 1) {
375 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
378 g_config->aspect_size = Size(600,
379 static_cast<int>(600 * 1/aspect_ratio + 0.5));
383 } else if(arg == "--renderer") {
387 print_usage(argv[0]);
388 throw std::runtime_error("Need to specify a renderer for renderer argument");
392 g_config->video = VideoSystem::get_video_system(argv[i]);
394 } else if(arg == "--show-fps") {
395 g_config->show_fps = true;
396 } else if(arg == "--no-show-fps") {
397 g_config->show_fps = false;
398 } else if(arg == "--console") {
399 g_config->console_enabled = true;
400 } else if(arg == "--noconsole") {
401 g_config->console_enabled = false;
402 } else if(arg == "--disable-sfx") {
403 g_config->sound_enabled = false;
404 } else if(arg == "--disable-music") {
405 g_config->music_enabled = false;
406 } else if(arg == "--play-demo") {
408 print_usage(argv[0]);
409 throw std::runtime_error("Need to specify a demo filename");
411 g_config->start_demo = argv[++i];
412 } else if(arg == "--record-demo") {
414 print_usage(argv[0]);
415 throw std::runtime_error("Need to specify a demo filename");
417 g_config->record_demo = argv[++i];
418 } else if(arg == "--debug-scripts" || arg == "-s") {
419 g_config->enable_script_debugger = true;
420 } else if(arg[0] != '-') {
421 g_config->start_level = arg;
423 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
434 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
435 std::stringstream msg;
436 msg << "Couldn't initialize SDL: " << SDL_GetError();
437 throw std::runtime_error(msg.str());
442 SDL_EnableUNICODE(1);
444 // wait 100ms and clear SDL event queue because sometimes we have random
445 // joystick events in the queue on startup...
448 while(SDL_PollEvent(&dummy))
455 g_config->random_seed = gameRandom.srand(g_config->random_seed);
457 graphicsRandom.srand(0);
459 //const char *how = config->random_seed? ", user fixed.": ", from time().";
460 //log_info << "Using random seed " << config->random_seed << how << std::endl;
466 // FIXME: Add something here
470 context_pointer->init_renderer();
471 g_screen = SDL_GetVideoSurface();
473 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
477 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
479 const char* icon_fname = "images/engine/icons/supertux.xpm";
483 icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
484 } catch (const std::runtime_error& err) {
486 log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
489 SDL_WM_SetIcon(icon, 0);
490 SDL_FreeSurface(icon);
493 log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
498 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
499 << " Window: " << g_config->window_size
500 << " Fullscreen: " << g_config->fullscreen_size
501 << " Area: " << g_config->aspect_size << std::endl;
507 sound_manager = new SoundManager();
509 sound_manager->enable_sound(g_config->sound_enabled);
510 sound_manager->enable_music(g_config->music_enabled);
516 if(sound_manager != NULL) {
517 delete sound_manager;
518 sound_manager = NULL;
523 Main::wait_for_event(float min_delay, float max_delay)
525 assert(min_delay <= max_delay);
527 Uint32 min = (Uint32) (min_delay * 1000);
528 Uint32 max = (Uint32) (max_delay * 1000);
530 Uint32 ticks = SDL_GetTicks();
531 while(SDL_GetTicks() - ticks < min) {
533 sound_manager->update();
538 while (SDL_PollEvent(&event))
542 bool running = false;
543 ticks = SDL_GetTicks();
545 while(SDL_PollEvent(&event)) {
548 g_screen_manager->quit();
551 case SDL_JOYBUTTONDOWN:
552 case SDL_MOUSEBUTTONDOWN:
556 if(SDL_GetTicks() - ticks >= (max - min))
558 sound_manager->update();
563 static Uint32 last_timelog_ticks = 0;
564 static const char* last_timelog_component = 0;
566 static inline void timelog(const char* component)
568 Uint32 current_ticks = SDL_GetTicks();
570 if(last_timelog_component != 0) {
571 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
574 last_timelog_ticks = current_ticks;
575 last_timelog_component = component;
579 Main::run(int argc, char** argv)
584 /* Do this before pre_parse_commandline, because --help now shows the
585 * default user data dir. */
586 init_physfs(argv[0]);
588 if(pre_parse_commandline(argc, argv))
591 Console::instance = new Console();
594 timelog("controller");
595 g_jk_controller = new JoystickKeyboardController();
601 AddonManager::get_instance().load_addons();
603 timelog("tinygettext");
606 timelog("commandline");
607 if(parse_commandline(argc, argv))
614 DrawingContext context;
615 context_pointer = &context;
618 Console::instance->init_graphics();
620 timelog("scripting");
621 scripting::init_squirrel(g_config->enable_script_debugger);
623 timelog("resources");
624 Resources::load_shared();
628 const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
630 g_screen_manager = new ScreenManager();
634 if(g_config->start_level != "") {
635 // we have a normal path specified at commandline, not a physfs path.
636 // So we simply mount that path here...
637 std::string dir = FileSystem::dirname(g_config->start_level);
638 log_debug << "Adding dir: " << dir << std::endl;
639 PHYSFS_addToSearchPath(dir.c_str(), true);
641 if(g_config->start_level.size() > 4 &&
642 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
643 g_screen_manager->push_screen(new worldmap::WorldMap(
644 FileSystem::basename(g_config->start_level), default_playerstatus.get()));
646 std::auto_ptr<GameSession> session (
647 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
649 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
650 init_rand();//initialise generator with seed from session
652 if(g_config->start_demo != "")
653 session->play_demo(g_config->start_demo);
655 if(g_config->record_demo != "")
656 session->record_demo(g_config->record_demo);
657 g_screen_manager->push_screen(session.release());
660 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
663 g_screen_manager->run(context);
664 } catch(std::exception& e) {
665 log_fatal << "Unexpected exception: " << e.what() << std::endl;
668 log_fatal << "Unexpected exception" << std::endl;
672 delete g_screen_manager;
673 g_screen_manager = NULL;
675 Resources::unload_shared();
682 delete g_jk_controller;
683 g_jk_controller = NULL;
684 delete Console::instance;
685 Console::instance = NULL;
686 scripting::exit_squirrel();
687 delete texture_manager;
688 texture_manager = NULL;