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 "video/lightmap.hpp"
33 #include "supertux/main.hpp"
35 #include "addon/addon_manager.hpp"
36 #include "audio/sound_manager.hpp"
37 #include "control/joystickkeyboardcontroller.hpp"
38 #include "math/random_generator.hpp"
39 #include "physfs/ifile_stream.hpp"
40 #include "physfs/physfs_sdl.hpp"
41 #include "physfs/physfs_file_system.hpp"
42 #include "scripting/squirrel_util.hpp"
43 #include "supertux/gameconfig.hpp"
44 #include "supertux/globals.hpp"
45 #include "supertux/player_status.hpp"
46 #include "supertux/screen_manager.hpp"
47 #include "supertux/resources.hpp"
48 #include "supertux/title_screen.hpp"
49 #include "util/file_system.hpp"
50 #include "util/gettext.hpp"
51 #include "video/drawing_context.hpp"
52 #include "worldmap/worldmap.hpp"
54 namespace { DrawingContext *context_pointer; }
57 # define WRITEDIR_NAME PACKAGE_NAME
59 # define WRITEDIR_NAME "." PACKAGE_NAME
65 g_config = new Config();
68 } catch(std::exception& e) {
69 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
74 Main::init_tinygettext()
76 dictionary_manager = new tinygettext::DictionaryManager();
77 tinygettext::Log::set_log_info_callback(0);
78 dictionary_manager->set_filesystem(std::unique_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
80 dictionary_manager->add_directory("locale");
81 dictionary_manager->set_charset("UTF-8");
83 // Config setting "locale" overrides language detection
84 if (g_config->locale != "")
86 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
89 FL_FindLocale(&locale);
90 tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
91 FL_FreeLocale(&locale);
92 dictionary_manager->set_language(language);
97 Main::init_physfs(const char* argv0)
99 if(!PHYSFS_init(argv0)) {
100 std::stringstream msg;
101 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
102 throw std::runtime_error(msg.str());
105 // allow symbolic links
106 PHYSFS_permitSymbolicLinks(1);
108 // Initialize physfs (this is a slightly modified version of
109 // PHYSFS_setSaneConfig)
110 const char *env_writedir;
111 std::string writedir;
113 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
114 writedir = env_writedir;
115 if(!PHYSFS_setWriteDir(writedir.c_str())) {
116 std::ostringstream msg;
117 msg << "Failed to use configuration directory '"
118 << writedir << "': " << PHYSFS_getLastError();
119 throw std::runtime_error(msg.str());
123 std::string userdir = PHYSFS_getUserDir();
125 // Set configuration directory
126 writedir = userdir + WRITEDIR_NAME;
127 if(!PHYSFS_setWriteDir(writedir.c_str())) {
128 // try to create the directory
129 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
130 std::ostringstream msg;
131 msg << "Failed creating configuration directory '"
132 << writedir << "': " << PHYSFS_getLastError();
133 throw std::runtime_error(msg.str());
136 if(!PHYSFS_setWriteDir(writedir.c_str())) {
137 std::ostringstream msg;
138 msg << "Failed to use configuration directory '"
139 << writedir << "': " << PHYSFS_getLastError();
140 throw std::runtime_error(msg.str());
144 PHYSFS_addToSearchPath(writedir.c_str(), 0);
146 // when started from source dir...
147 char* base_path = SDL_GetBasePath();
148 std::string dir = base_path;
151 if (dir[dir.length() - 1] != '/')
154 std::string testfname = dir;
155 testfname += "/credits.txt";
156 bool sourcedir = false;
157 FILE* f = fopen(testfname.c_str(), "r");
160 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
161 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
168 std::string datadir = PHYSFS_getBaseDir();
169 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
170 datadir += "/" INSTALL_SUBDIR_SHARE;
171 #ifdef ENABLE_BINRELOC
175 dir = br_find_data_dir(datadir.c_str());
180 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
181 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
186 char** searchpath = PHYSFS_getSearchPath();
187 for(char** i = searchpath; *i != NULL; i++)
188 log_info << "[" << *i << "] is in the search path" << std::endl;
189 PHYSFS_freeList(searchpath);
193 Main::print_usage(const char* argv0)
195 std::string default_user_data_dir =
196 std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
198 std::cerr << boost::format(_(
200 "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
202 " -f, --fullscreen Run in fullscreen mode\n"
203 " -w, --window Run in window mode\n"
204 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
205 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
206 " -d, --default Reset video settings to default values\n"
207 " --renderer RENDERER Use sdl, opengl, or auto to render\n"
208 " --disable-sfx Disable sound effects\n"
209 " --disable-music Disable music\n"
210 " -h, --help Show this help message and quit\n"
211 " -v, --version Show SuperTux version and quit\n"
212 " --console Enable ingame scripting console\n"
213 " --noconsole Disable ingame scripting console\n"
214 " --show-fps Display framerate in levels\n"
215 " --no-show-fps Do not display framerate in levels\n"
216 " --record-demo FILE LEVEL Record a demo to FILE\n"
217 " --play-demo FILE LEVEL Play a recorded demo\n"
218 " -s, --debug-scripts Enable script debugger.\n"
219 " --print-datadir Print supertux's primary data directory.\n"
221 "Environment variables:\n"
222 " SUPERTUX2_USER_DIR Directory for user data (savegames, etc.);\n"
226 % argv0 % default_user_data_dir
231 * Options that should be evaluated prior to any initializations at all go here
234 Main::pre_parse_commandline(int argc, char** argv)
236 for(int i = 1; i < argc; ++i) {
237 std::string arg = argv[i];
239 if(arg == "--version" || arg == "-v") {
240 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
243 if(arg == "--help" || arg == "-h") {
244 print_usage(argv[0]);
247 if(arg == "--print-datadir") {
249 * Print the datadir searchpath to stdout, one path per
250 * line. Then exit. Intended for use by the supertux-editor.
254 sp = PHYSFS_getSearchPath();
256 for (sp_index = 0; sp[sp_index]; sp_index++)
257 std::cout << sp[sp_index] << std::endl;
267 * Options that should be evaluated after config is read go here
270 Main::parse_commandline(int argc, char** argv)
272 for(int i = 1; i < argc; ++i) {
273 std::string arg = argv[i];
275 if(arg == "--fullscreen" || arg == "-f") {
276 g_config->use_fullscreen = true;
277 } else if(arg == "--default" || arg == "-d") {
278 g_config->use_fullscreen = false;
280 g_config->window_size = Size(800, 600);
281 g_config->fullscreen_size = Size(800, 600);
282 g_config->fullscreen_refresh_rate = 0;
283 g_config->aspect_size = Size(0, 0); // auto detect
285 } else if(arg == "--window" || arg == "-w") {
286 g_config->use_fullscreen = false;
287 } else if(arg == "--geometry" || arg == "-g") {
291 print_usage(argv[0]);
292 throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
297 if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
299 print_usage(argv[0]);
300 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
304 g_config->window_size = Size(width, height);
305 g_config->fullscreen_size = Size(width, height);
306 g_config->fullscreen_refresh_rate = 0;
309 } else if(arg == "--aspect" || arg == "-a") {
313 print_usage(argv[0]);
314 throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
318 int aspect_width = 0;
319 int aspect_height = 0;
320 if (strcmp(argv[i], "auto") == 0)
325 else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2)
327 print_usage(argv[0]);
328 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
332 float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
334 // use aspect ratio to calculate logical resolution
335 if (aspect_ratio > 1) {
336 g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
339 g_config->aspect_size = Size(600,
340 static_cast<int>(600 * 1/aspect_ratio + 0.5));
344 } else if(arg == "--renderer") {
348 print_usage(argv[0]);
349 throw std::runtime_error("Need to specify a renderer for renderer argument");
353 g_config->video = VideoSystem::get_video_system(argv[i]);
355 } else if(arg == "--show-fps") {
356 g_config->show_fps = true;
357 } else if(arg == "--no-show-fps") {
358 g_config->show_fps = false;
359 } else if(arg == "--console") {
360 g_config->console_enabled = true;
361 } else if(arg == "--noconsole") {
362 g_config->console_enabled = false;
363 } else if(arg == "--disable-sfx") {
364 g_config->sound_enabled = false;
365 } else if(arg == "--disable-music") {
366 g_config->music_enabled = false;
367 } else if(arg == "--play-demo") {
369 print_usage(argv[0]);
370 throw std::runtime_error("Need to specify a demo filename");
372 g_config->start_demo = argv[++i];
373 } else if(arg == "--record-demo") {
375 print_usage(argv[0]);
376 throw std::runtime_error("Need to specify a demo filename");
378 g_config->record_demo = argv[++i];
379 } else if(arg == "--debug-scripts" || arg == "-s") {
380 g_config->enable_script_debugger = true;
381 } else if(arg[0] != '-') {
382 g_config->start_level = arg;
384 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
394 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) {
395 std::stringstream msg;
396 msg << "Couldn't initialize SDL: " << SDL_GetError();
397 throw std::runtime_error(msg.str());
402 // wait 100ms and clear SDL event queue because sometimes we have random
403 // joystick events in the queue on startup...
406 while(SDL_PollEvent(&dummy))
413 g_config->random_seed = gameRandom.srand(g_config->random_seed);
415 graphicsRandom.srand(0);
417 //const char *how = config->random_seed? ", user fixed.": ", from time().";
418 //log_info << "Using random seed " << config->random_seed << how << std::endl;
424 SDL_SetWindowTitle(Renderer::instance()->get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
426 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
427 SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
430 log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
434 SDL_SetWindowIcon(Renderer::instance()->get_window(), icon);
435 SDL_FreeSurface(icon);
439 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
440 << " Window: " << g_config->window_size
441 << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
442 << " Area: " << g_config->aspect_size << std::endl;
448 sound_manager = new SoundManager();
450 sound_manager->enable_sound(g_config->sound_enabled);
451 sound_manager->enable_music(g_config->music_enabled);
457 if(sound_manager != NULL) {
458 delete sound_manager;
459 sound_manager = NULL;
464 Main::wait_for_event(float min_delay, float max_delay)
466 assert(min_delay <= max_delay);
468 Uint32 min = (Uint32) (min_delay * 1000);
469 Uint32 max = (Uint32) (max_delay * 1000);
471 Uint32 ticks = SDL_GetTicks();
472 while(SDL_GetTicks() - ticks < min) {
474 sound_manager->update();
479 while (SDL_PollEvent(&event))
483 bool running = false;
484 ticks = SDL_GetTicks();
486 while(SDL_PollEvent(&event)) {
489 g_screen_manager->quit();
492 case SDL_JOYBUTTONDOWN:
493 case SDL_MOUSEBUTTONDOWN:
497 if(SDL_GetTicks() - ticks >= (max - min))
499 sound_manager->update();
504 static Uint32 last_timelog_ticks = 0;
505 static const char* last_timelog_component = 0;
507 static inline void timelog(const char* component)
509 Uint32 current_ticks = SDL_GetTicks();
511 if(last_timelog_component != 0) {
512 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
515 last_timelog_ticks = current_ticks;
516 last_timelog_component = component;
520 Main::run(int argc, char** argv)
525 /* Do this before pre_parse_commandline, because --help now shows the
526 * default user data dir. */
527 init_physfs(argv[0]);
529 if(pre_parse_commandline(argc, argv))
533 Console::instance = new Console();
535 timelog("controller");
536 g_jk_controller = new JoystickKeyboardController();
541 timelog("commandline");
542 if(parse_commandline(argc, argv))
546 std::unique_ptr<Renderer> renderer(VideoSystem::new_renderer());
547 std::unique_ptr<Lightmap> lightmap(VideoSystem::new_lightmap());
548 DrawingContext context(*renderer, *lightmap);
549 context_pointer = &context;
555 timelog("tinygettext");
558 Console::instance->init_graphics();
560 timelog("scripting");
561 scripting::init_squirrel(g_config->enable_script_debugger);
563 timelog("resources");
564 Resources::load_shared();
567 AddonManager::get_instance().load_addons();
571 const std::unique_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
573 g_screen_manager = new ScreenManager();
577 if(g_config->start_level != "") {
578 // we have a normal path specified at commandline, not a physfs path.
579 // So we simply mount that path here...
580 std::string dir = FileSystem::dirname(g_config->start_level);
581 std::string fileProtocol = "file://";
582 std::string::size_type position = dir.find(fileProtocol);
583 if(position != std::string::npos) {
584 dir = dir.replace(position, fileProtocol.length(), "");
586 log_debug << "Adding dir: " << dir << std::endl;
587 PHYSFS_addToSearchPath(dir.c_str(), true);
589 if(g_config->start_level.size() > 4 &&
590 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
591 g_screen_manager->push_screen(new worldmap::WorldMap(
592 FileSystem::basename(g_config->start_level), default_playerstatus.get()));
594 std::unique_ptr<GameSession> session (
595 new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
597 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
598 init_rand();//initialise generator with seed from session
600 if(g_config->start_demo != "")
601 session->play_demo(g_config->start_demo);
603 if(g_config->record_demo != "")
604 session->record_demo(g_config->record_demo);
605 g_screen_manager->push_screen(session.release());
608 g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
611 g_screen_manager->run(context);
612 } catch(std::exception& e) {
613 log_fatal << "Unexpected exception: " << e.what() << std::endl;
616 log_fatal << "Unexpected exception" << std::endl;
620 delete g_screen_manager;
621 g_screen_manager = NULL;
623 Resources::unload_shared();
630 delete g_jk_controller;
631 g_jk_controller = NULL;
632 delete Console::instance;
633 Console::instance = NULL;
634 scripting::exit_squirrel();
635 delete texture_manager;
636 texture_manager = NULL;