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/>.
17 #include "supertux/main.hpp"
22 #include <SDL_image.h>
26 #include <tinygettext/log.hpp>
27 #include <boost/format.hpp>
30 #include <findlocale.h>
33 #include "addon/addon_manager.hpp"
34 #include "audio/sound_manager.hpp"
35 #include "control/input_manager.hpp"
36 #include "math/random_generator.hpp"
37 #include "physfs/ifile_stream.hpp"
38 #include "physfs/physfs_file_system.hpp"
39 #include "physfs/physfs_sdl.hpp"
40 #include "scripting/squirrel_util.hpp"
41 #include "supertux/game_manager.hpp"
42 #include "supertux/gameconfig.hpp"
43 #include "supertux/globals.hpp"
44 #include "supertux/command_line_arguments.hpp"
45 #include "supertux/player_status.hpp"
46 #include "supertux/resources.hpp"
47 #include "supertux/screen_fade.hpp"
48 #include "supertux/screen_manager.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 "video/lightmap.hpp"
54 #include "video/renderer.hpp"
55 #include "worldmap/worldmap.hpp"
57 namespace { DrawingContext *context_pointer; }
62 g_config = new Config();
65 } catch(std::exception& e) {
66 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
71 Main::init_tinygettext()
73 dictionary_manager = new tinygettext::DictionaryManager();
74 tinygettext::Log::set_log_info_callback(0);
75 dictionary_manager->set_filesystem(std::unique_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
77 dictionary_manager->add_directory("locale");
78 dictionary_manager->set_charset("UTF-8");
80 // Config setting "locale" overrides language detection
81 if (g_config->locale != "")
83 dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
86 FL_FindLocale(&locale);
87 tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
88 FL_FreeLocale(&locale);
89 dictionary_manager->set_language(language);
94 Main::init_physfs(const char* argv0)
96 if(!PHYSFS_init(argv0)) {
97 std::stringstream msg;
98 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
99 throw std::runtime_error(msg.str());
102 // allow symbolic links
103 PHYSFS_permitSymbolicLinks(1);
105 // Initialize physfs (this is a slightly modified version of
106 // PHYSFS_setSaneConfig)
107 const char *env_writedir;
108 std::string writedir;
110 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
111 writedir = env_writedir;
112 if(!PHYSFS_setWriteDir(writedir.c_str())) {
113 std::ostringstream msg;
114 msg << "Failed to use configuration directory '"
115 << writedir << "': " << PHYSFS_getLastError();
116 throw std::runtime_error(msg.str());
120 std::string userdir = PHYSFS_getUserDir();
122 // Set configuration directory
123 writedir = userdir + WRITEDIR_NAME;
124 if(!PHYSFS_setWriteDir(writedir.c_str())) {
125 // try to create the directory
126 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
127 std::ostringstream msg;
128 msg << "Failed creating configuration directory '"
129 << writedir << "': " << PHYSFS_getLastError();
130 throw std::runtime_error(msg.str());
133 if(!PHYSFS_setWriteDir(writedir.c_str())) {
134 std::ostringstream msg;
135 msg << "Failed to use configuration directory '"
136 << writedir << "': " << PHYSFS_getLastError();
137 throw std::runtime_error(msg.str());
141 PHYSFS_addToSearchPath(writedir.c_str(), 0);
143 // when started from source dir...
144 char* base_path = SDL_GetBasePath();
145 std::string dir = base_path;
148 if (dir[dir.length() - 1] != '/')
151 std::string testfname = dir;
152 testfname += "/credits.txt";
153 bool sourcedir = false;
154 FILE* f = fopen(testfname.c_str(), "r");
157 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
158 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
165 std::string datadir = PHYSFS_getBaseDir();
166 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
167 datadir += "/" INSTALL_SUBDIR_SHARE;
168 #ifdef ENABLE_BINRELOC
172 dir = br_find_data_dir(datadir.c_str());
177 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
178 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
183 char** searchpath = PHYSFS_getSearchPath();
184 for(char** i = searchpath; *i != NULL; i++)
185 log_info << "[" << *i << "] is in the search path" << std::endl;
186 PHYSFS_freeList(searchpath);
192 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) {
193 std::stringstream msg;
194 msg << "Couldn't initialize SDL: " << SDL_GetError();
195 throw std::runtime_error(msg.str());
204 g_config->random_seed = gameRandom.srand(g_config->random_seed);
206 graphicsRandom.srand(0);
208 //const char *how = config->random_seed? ", user fixed.": ", from time().";
209 //log_info << "Using random seed " << config->random_seed << how << std::endl;
215 SDL_SetWindowTitle(Renderer::instance()->get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
217 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
218 SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
221 log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
225 SDL_SetWindowIcon(Renderer::instance()->get_window(), icon);
226 SDL_FreeSurface(icon);
230 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
231 << " Window: " << g_config->window_size
232 << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
233 << " Area: " << g_config->aspect_size << std::endl;
239 sound_manager = new SoundManager();
241 sound_manager->enable_sound(g_config->sound_enabled);
242 sound_manager->enable_music(g_config->music_enabled);
248 if(sound_manager != NULL) {
249 delete sound_manager;
250 sound_manager = NULL;
254 static Uint32 last_timelog_ticks = 0;
255 static const char* last_timelog_component = 0;
257 static inline void timelog(const char* component)
259 Uint32 current_ticks = SDL_GetTicks();
261 if(last_timelog_component != 0) {
262 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
265 last_timelog_ticks = current_ticks;
266 last_timelog_component = component;
270 Main::run(int argc, char** argv)
276 CommandLineArguments args;
278 // Do this before pre_parse_commandline, because --help now shows the
279 // default user data dir.
280 init_physfs(argv[0]);
284 args.parse_args(argc, argv);
285 g_log_level = args.get_log_level();
287 catch(const std::exception& err)
292 args.merge_into(*g_config);
295 catch(const std::exception& err)
297 log_fatal << "failed to init config or tinygettext: " << err.what() << std::endl;
300 std::cout << "Error: " << err.what() << std::endl;
306 args.merge_into(*g_config);
308 timelog("tinygettext");
311 switch (args.get_action())
313 case CommandLineArguments::PRINT_VERSION:
314 args.print_version();
317 case CommandLineArguments::PRINT_HELP:
318 args.print_help(argv[0]);
321 case CommandLineArguments::PRINT_DATADIR:
322 args.print_datadir();
326 // continue and start the game as usual
331 Console::instance = new Console();
333 timelog("controller");
334 g_input_manager = new InputManager();
336 timelog("commandline");
339 std::unique_ptr<Renderer> renderer(VideoSystem::new_renderer());
340 std::unique_ptr<Lightmap> lightmap(VideoSystem::new_lightmap());
341 DrawingContext context(*renderer, *lightmap);
342 context_pointer = &context;
348 Console::instance->init_graphics();
350 timelog("scripting");
351 scripting::init_squirrel(g_config->enable_script_debugger);
353 timelog("resources");
354 Resources::load_shared();
357 AddonManager::get_instance().load_addons();
361 const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));
363 GameManager game_manager;
364 g_screen_manager = new ScreenManager();
368 if(g_config->start_level != "") {
369 // we have a normal path specified at commandline, not a physfs path.
370 // So we simply mount that path here...
371 std::string dir = FileSystem::dirname(g_config->start_level);
372 std::string fileProtocol = "file://";
373 std::string::size_type position = dir.find(fileProtocol);
374 if(position != std::string::npos) {
375 dir = dir.replace(position, fileProtocol.length(), "");
377 log_debug << "Adding dir: " << dir << std::endl;
378 PHYSFS_addToSearchPath(dir.c_str(), true);
380 if(g_config->start_level.size() > 4 &&
381 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
382 g_screen_manager->push_screen(std::unique_ptr<Screen>(
383 new worldmap::WorldMap(
384 FileSystem::basename(g_config->start_level), *default_savegame)));
386 std::unique_ptr<GameSession> session (
387 new GameSession(FileSystem::basename(g_config->start_level), *default_savegame));
389 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
390 init_rand();//initialise generator with seed from session
392 if(g_config->start_demo != "")
393 session->play_demo(g_config->start_demo);
395 if(g_config->record_demo != "")
396 session->record_demo(g_config->record_demo);
397 g_screen_manager->push_screen(std::move(session));
400 g_screen_manager->push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));
403 g_screen_manager->run(context);
404 } catch(std::exception& e) {
405 log_fatal << "Unexpected exception: " << e.what() << std::endl;
408 log_fatal << "Unexpected exception" << std::endl;
412 delete g_screen_manager;
413 g_screen_manager = NULL;
415 Resources::unload_shared();
422 delete g_input_manager;
423 g_input_manager = NULL;
424 delete Console::instance;
425 Console::instance = NULL;
426 scripting::exit_squirrel();
427 delete texture_manager;
428 texture_manager = NULL;
432 delete dictionary_manager;
433 dictionary_manager = nullptr;