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 <findlocale.h>
31 #include "video/renderer.hpp"
32 #include "supertux/main.hpp"
34 #include "addon/addon_manager.hpp"
35 #include "audio/sound_manager.hpp"
36 #include "control/joystickkeyboardcontroller.hpp"
37 #include "math/random_generator.hpp"
38 #include "physfs/ifile_stream.hpp"
39 #include "physfs/physfs_sdl.hpp"
40 #include "physfs/physfs_file_system.hpp"
41 #include "scripting/squirrel_util.hpp"
42 #include "supertux/gameconfig.hpp"
43 #include "supertux/globals.hpp"
44 #include "supertux/player_status.hpp"
45 #include "supertux/screen_manager.hpp"
46 #include "supertux/resources.hpp"
47 #include "supertux/title_screen.hpp"
48 #include "util/file_system.hpp"
49 #include "util/gettext.hpp"
50 #include "video/drawing_context.hpp"
51 #include "worldmap/worldmap.hpp"
53 namespace { DrawingContext *context_pointer; }
56 # define WRITEDIR_NAME PACKAGE_NAME
58 # define WRITEDIR_NAME "." PACKAGE_NAME
64 g_config = new Config();
67 } catch(std::exception& e) {
68 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
73 Main::init_tinygettext()
75 dictionary_manager = new tinygettext::DictionaryManager();
76 tinygettext::Log::set_log_info_callback(0);
77 dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
79 dictionary_manager->add_directory("locale");
80 dictionary_manager->set_charset("UTF-8");
82 // Config setting "locale" overrides language detection
83 if (g_config->locale != "")
85 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
88 FL_FindLocale(&locale);
89 tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
90 FL_FreeLocale(&locale);
91 dictionary_manager->set_language(language);
96 Main::init_physfs(const char* argv0)
98 if(!PHYSFS_init(argv0)) {
99 std::stringstream msg;
100 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
101 throw std::runtime_error(msg.str());
104 // allow symbolic links
105 PHYSFS_permitSymbolicLinks(1);
107 // Initialize physfs (this is a slightly modified version of
108 // PHYSFS_setSaneConfig)
109 const char *env_writedir;
110 std::string writedir;
112 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
113 writedir = env_writedir;
114 if(!PHYSFS_setWriteDir(writedir.c_str())) {
115 std::ostringstream msg;
116 msg << "Failed to use configuration directory '"
117 << writedir << "': " << PHYSFS_getLastError();
118 throw std::runtime_error(msg.str());
122 std::string userdir = PHYSFS_getUserDir();
124 // Set configuration directory
125 writedir = userdir + WRITEDIR_NAME;
126 if(!PHYSFS_setWriteDir(writedir.c_str())) {
127 // try to create the directory
128 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
129 std::ostringstream msg;
130 msg << "Failed creating configuration directory '"
131 << writedir << "': " << PHYSFS_getLastError();
132 throw std::runtime_error(msg.str());
135 if(!PHYSFS_setWriteDir(writedir.c_str())) {
136 std::ostringstream msg;
137 msg << "Failed to use configuration directory '"
138 << writedir << "': " << PHYSFS_getLastError();
139 throw std::runtime_error(msg.str());
143 PHYSFS_addToSearchPath(writedir.c_str(), 0);
145 // when started from source dir...
146 char* base_path = SDL_GetBasePath();
147 std::string dir = base_path;
150 if (dir[dir.length() - 1] != '/')
153 std::string testfname = dir;
154 testfname += "/credits.txt";
155 bool sourcedir = false;
156 FILE* f = fopen(testfname.c_str(), "r");
159 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
160 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
167 std::string datadir = PHYSFS_getBaseDir();
168 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
169 datadir += "/" INSTALL_SUBDIR_SHARE;
170 #ifdef ENABLE_BINRELOC
174 dir = br_find_data_dir(datadir.c_str());
179 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
180 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
185 char** searchpath = PHYSFS_getSearchPath();
186 for(char** i = searchpath; *i != NULL; i++)
187 log_info << "[" << *i << "] is in the search path" << std::endl;
188 PHYSFS_freeList(searchpath);
192 Main::print_usage(const char* argv0)
194 std::string default_user_data_dir =
195 std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
197 std::cerr << boost::format(_(
199 "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
201 " -f, --fullscreen Run in fullscreen mode\n"
202 " -w, --window Run in window mode\n"
203 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
204 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
205 " -d, --default Reset video settings to default values\n"
206 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
207 " --disable-sfx Disable sound effects\n"
208 " --disable-music Disable music\n"
209 " -h, --help Show this help message and quit\n"
210 " -v, --version Show SuperTux version and quit\n"
211 " --console Enable ingame scripting console\n"
212 " --noconsole Disable ingame scripting console\n"
213 " --show-fps Display framerate in levels\n"
214 " --no-show-fps Do not display framerate in levels\n"
215 " --record-demo FILE LEVEL Record a demo to FILE\n"
216 " --play-demo FILE LEVEL Play a recorded demo\n"
217 " -s, --debug-scripts Enable script debugger.\n"
218 " --print-datadir Print supertux's primary data directory.\n"
220 "Environment variables:\n"
221 " SUPERTUX2_USER_DIR Directory for user data (savegames, etc.);\n"
225 % argv0 % default_user_data_dir
230 * Options that should be evaluated prior to any initializations at all go here
233 Main::pre_parse_commandline(int argc, char** argv)
235 for(int i = 1; i < argc; ++i) {
236 std::string arg = argv[i];
238 if(arg == "--version" || arg == "-v") {
239 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
242 if(arg == "--help" || arg == "-h") {
243 print_usage(argv[0]);
246 if(arg == "--print-datadir") {
248 * Print the datadir searchpath to stdout, one path per
249 * line. Then exit. Intended for use by the supertux-editor.
253 sp = PHYSFS_getSearchPath();
255 for (sp_index = 0; sp[sp_index]; sp_index++)
256 std::cout << sp[sp_index] << std::endl;
266 * Options that should be evaluated after config is read go here
269 Main::parse_commandline(int argc, char** argv)
271 for(int i = 1; i < argc; ++i) {
272 std::string arg = argv[i];
274 if(arg == "--fullscreen" || arg == "-f") {
275 g_config->use_fullscreen = true;
276 } else if(arg == "--default" || arg == "-d") {
277 g_config->use_fullscreen = false;
279 g_config->window_size = Size(800, 600);
280 g_config->fullscreen_size = Size(800, 600);
281 g_config->fullscreen_refresh_rate = 0;
282 g_config->aspect_size = Size(0, 0); // auto detect
284 } else if(arg == "--window" || arg == "-w") {
285 g_config->use_fullscreen = false;
286 } else if(arg == "--geometry" || arg == "-g") {
290 print_usage(argv[0]);
291 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
296 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
298 print_usage(argv[0]);
299 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
303 g_config->window_size = Size(width, height);
304 g_config->fullscreen_size = Size(width, height);
305 g_config->fullscreen_refresh_rate = 0;
308 } else if(arg == "--aspect" || arg == "-a") {
312 print_usage(argv[0]);
313 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
317 int aspect_width = 0;
318 int aspect_height = 0;
319 if (strcmp(argv[i], "auto") == 0)
324 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
326 print_usage(argv[0]);
327 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
331 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
333 // use aspect ratio to calculate logical resolution
334 if (aspect_ratio > 1) {
335 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
338 g_config->aspect_size = Size(600,
339 static_cast<int>(600 * 1/aspect_ratio + 0.5));
343 } else if(arg == "--renderer") {
347 print_usage(argv[0]);
348 throw std::runtime_error("Need to specify a renderer for renderer argument");
352 g_config->video = VideoSystem::get_video_system(argv[i]);
354 } else if(arg == "--show-fps") {
355 g_config->show_fps = true;
356 } else if(arg == "--no-show-fps") {
357 g_config->show_fps = false;
358 } else if(arg == "--console") {
359 g_config->console_enabled = true;
360 } else if(arg == "--noconsole") {
361 g_config->console_enabled = false;
362 } else if(arg == "--disable-sfx") {
363 g_config->sound_enabled = false;
364 } else if(arg == "--disable-music") {
365 g_config->music_enabled = false;
366 } else if(arg == "--play-demo") {
368 print_usage(argv[0]);
369 throw std::runtime_error("Need to specify a demo filename");
371 g_config->start_demo = argv[++i];
372 } else if(arg == "--record-demo") {
374 print_usage(argv[0]);
375 throw std::runtime_error("Need to specify a demo filename");
377 g_config->record_demo = argv[++i];
378 } else if(arg == "--debug-scripts" || arg == "-s") {
379 g_config->enable_script_debugger = true;
380 } else if(arg[0] != '-') {
381 g_config->start_level = arg;
383 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
393 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
394 std::stringstream msg;
395 msg << "Couldn't initialize SDL: " << SDL_GetError();
396 throw std::runtime_error(msg.str());
401 // SDL_EnableUNICODE(1); //old code, mofif by giby
402 // SDL_JoystickID myID = SDL_JoystickInstanceID(myOpenedStick);
405 // wait 100ms and clear SDL event queue because sometimes we have random
406 // joystick events in the queue on startup...
409 while(SDL_PollEvent(&dummy))
416 g_config->random_seed = gameRandom.srand(g_config->random_seed);
418 graphicsRandom.srand(0);
420 //const char *how = config->random_seed? ", user fixed.": ", from time().";
421 //log_info << "Using random seed " << config->random_seed << how << std::endl;
427 SDL_SetWindowTitle(Renderer::instance()->get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
429 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
430 SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
433 log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
437 SDL_SetWindowIcon(Renderer::instance()->get_window(), icon);
438 SDL_FreeSurface(icon);
442 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
443 << " Window: " << g_config->window_size
444 << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
445 << " Area: " << g_config->aspect_size << std::endl;
451 sound_manager = new SoundManager();
453 sound_manager->enable_sound(g_config->sound_enabled);
454 sound_manager->enable_music(g_config->music_enabled);
460 if(sound_manager != NULL) {
461 delete sound_manager;
462 sound_manager = NULL;
467 Main::wait_for_event(float min_delay, float max_delay)
469 assert(min_delay <= max_delay);
471 Uint32 min = (Uint32) (min_delay * 1000);
472 Uint32 max = (Uint32) (max_delay * 1000);
474 Uint32 ticks = SDL_GetTicks();
475 while(SDL_GetTicks() - ticks < min) {
477 sound_manager->update();
482 while (SDL_PollEvent(&event))
486 bool running = false;
487 ticks = SDL_GetTicks();
489 while(SDL_PollEvent(&event)) {
492 g_screen_manager->quit();
495 case SDL_JOYBUTTONDOWN:
496 case SDL_MOUSEBUTTONDOWN:
500 if(SDL_GetTicks() - ticks >= (max - min))
502 sound_manager->update();
507 static Uint32 last_timelog_ticks = 0;
508 static const char* last_timelog_component = 0;
510 static inline void timelog(const char* component)
512 Uint32 current_ticks = SDL_GetTicks();
514 if(last_timelog_component != 0) {
515 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
518 last_timelog_ticks = current_ticks;
519 last_timelog_component = component;
523 Main::run(int argc, char** argv)
528 /* Do this before pre_parse_commandline, because --help now shows the
529 * default user data dir. */
530 init_physfs(argv[0]);
532 if(pre_parse_commandline(argc, argv))
536 Console::instance = new Console();
538 timelog("controller");
539 g_jk_controller = new JoystickKeyboardController();
544 timelog("commandline");
545 if(parse_commandline(argc, argv))
549 std::auto_ptr<Renderer> renderer(VideoSystem::new_renderer());
550 std::auto_ptr<Lightmap> lightmap(VideoSystem::new_lightmap());
551 DrawingContext context(*renderer, *lightmap);
552 context_pointer = &context;
558 timelog("tinygettext");
561 Console::instance->init_graphics();
563 timelog("scripting");
564 scripting::init_squirrel(g_config->enable_script_debugger);
566 timelog("resources");
567 Resources::load_shared();
570 AddonManager::get_instance().load_addons();
574 const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
576 g_screen_manager = new ScreenManager();
580 if(g_config->start_level != "") {
581 // we have a normal path specified at commandline, not a physfs path.
582 // So we simply mount that path here...
583 std::string dir = FileSystem::dirname(g_config->start_level);
584 std::string fileProtocol = "file://";
585 std::string::size_type position = dir.find(fileProtocol);
586 if(position != std::string::npos) {
587 dir = dir.replace(position, fileProtocol.length(), "");
589 log_debug << "Adding dir: " << dir << std::endl;
590 PHYSFS_addToSearchPath(dir.c_str(), true);
592 if(g_config->start_level.size() > 4 &&
593 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
594 g_screen_manager->push_screen(new worldmap::WorldMap(
595 FileSystem::basename(g_config->start_level), default_playerstatus.get()));
597 std::auto_ptr<GameSession> session (
598 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
600 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
601 init_rand();//initialise generator with seed from session
603 if(g_config->start_demo != "")
604 session->play_demo(g_config->start_demo);
606 if(g_config->record_demo != "")
607 session->record_demo(g_config->record_demo);
608 g_screen_manager->push_screen(session.release());
611 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
614 g_screen_manager->run(context);
615 } catch(std::exception& e) {
616 log_fatal << "Unexpected exception: " << e.what() << std::endl;
619 log_fatal << "Unexpected exception" << std::endl;
623 delete g_screen_manager;
624 g_screen_manager = NULL;
626 Resources::unload_shared();
633 delete g_jk_controller;
634 g_jk_controller = NULL;
635 delete Console::instance;
636 Console::instance = NULL;
637 scripting::exit_squirrel();
638 delete texture_manager;
639 texture_manager = NULL;