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 "sprite/sprite_manager.hpp"
42 #include "supertux/command_line_arguments.hpp"
43 #include "supertux/game_manager.hpp"
44 #include "supertux/gameconfig.hpp"
45 #include "supertux/globals.hpp"
46 #include "supertux/player_status.hpp"
47 #include "supertux/resources.hpp"
48 #include "supertux/screen_fade.hpp"
49 #include "supertux/screen_manager.hpp"
50 #include "supertux/title_screen.hpp"
51 #include "util/file_system.hpp"
52 #include "util/gettext.hpp"
53 #include "video/drawing_context.hpp"
54 #include "video/lightmap.hpp"
55 #include "video/renderer.hpp"
56 #include "worldmap/worldmap.hpp"
61 g_config.reset(new Config);
64 } catch(const std::exception& e) {
65 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
70 Main::init_tinygettext()
72 g_dictionary_manager.reset(new tinygettext::DictionaryManager);
73 tinygettext::Log::set_log_info_callback(0);
74 g_dictionary_manager->set_filesystem(std::unique_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
76 g_dictionary_manager->add_directory("locale");
77 g_dictionary_manager->set_charset("UTF-8");
79 // Config setting "locale" overrides language detection
80 if (g_config->locale != "")
82 g_dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
85 FL_FindLocale(&locale);
86 tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
87 FL_FreeLocale(&locale);
88 g_dictionary_manager->set_language(language);
93 Main::init_physfs(const char* argv0)
95 if(!PHYSFS_init(argv0)) {
96 std::stringstream msg;
97 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
98 throw std::runtime_error(msg.str());
101 // allow symbolic links
102 PHYSFS_permitSymbolicLinks(1);
104 // Initialize physfs (this is a slightly modified version of
105 // PHYSFS_setSaneConfig)
106 const char *env_writedir;
107 std::string writedir;
109 if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
110 writedir = env_writedir;
111 if(!PHYSFS_setWriteDir(writedir.c_str())) {
112 std::ostringstream msg;
113 msg << "Failed to use configuration directory '"
114 << writedir << "': " << PHYSFS_getLastError();
115 throw std::runtime_error(msg.str());
119 std::string userdir = PHYSFS_getUserDir();
121 // Set configuration directory
122 writedir = userdir + WRITEDIR_NAME;
123 if(!PHYSFS_setWriteDir(writedir.c_str())) {
124 // try to create the directory
125 if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
126 std::ostringstream msg;
127 msg << "Failed creating configuration directory '"
128 << writedir << "': " << PHYSFS_getLastError();
129 throw std::runtime_error(msg.str());
132 if(!PHYSFS_setWriteDir(writedir.c_str())) {
133 std::ostringstream msg;
134 msg << "Failed to use configuration directory '"
135 << writedir << "': " << PHYSFS_getLastError();
136 throw std::runtime_error(msg.str());
140 PHYSFS_addToSearchPath(writedir.c_str(), 0);
142 // when started from source dir...
143 char* base_path = SDL_GetBasePath();
144 std::string dir = base_path;
147 if (dir[dir.length() - 1] != '/')
150 std::string testfname = dir;
151 testfname += "/credits.txt";
152 bool sourcedir = false;
153 FILE* f = fopen(testfname.c_str(), "r");
156 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
157 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
164 std::string datadir = PHYSFS_getBaseDir();
165 datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
166 datadir += "/" INSTALL_SUBDIR_SHARE;
167 #ifdef ENABLE_BINRELOC
171 dir = br_find_data_dir(datadir.c_str());
176 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
177 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
182 char** searchpath = PHYSFS_getSearchPath();
183 for(char** i = searchpath; *i != NULL; i++)
184 log_info << "[" << *i << "] is in the search path" << std::endl;
185 PHYSFS_freeList(searchpath);
191 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) {
192 std::stringstream msg;
193 msg << "Couldn't initialize SDL: " << SDL_GetError();
194 throw std::runtime_error(msg.str());
203 g_config->random_seed = gameRandom.srand(g_config->random_seed);
205 graphicsRandom.srand(0);
207 //const char *how = config->random_seed? ", user fixed.": ", from time().";
208 //log_info << "Using random seed " << config->random_seed << how << std::endl;
214 SDL_SetWindowTitle(VideoSystem::current()->get_renderer().get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
216 const char* icon_fname = "images/engine/icons/supertux-256x256.png";
217 SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
220 log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
224 SDL_SetWindowIcon(VideoSystem::current()->get_renderer().get_window(), icon);
225 SDL_FreeSurface(icon);
229 log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
230 << " Window: " << g_config->window_size
231 << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
232 << " Area: " << g_config->aspect_size << std::endl;
235 static Uint32 last_timelog_ticks = 0;
236 static const char* last_timelog_component = 0;
238 static inline void timelog(const char* component)
240 Uint32 current_ticks = SDL_GetTicks();
242 if(last_timelog_component != 0) {
243 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
246 last_timelog_ticks = current_ticks;
247 last_timelog_component = component;
251 Main::run(int argc, char** argv)
257 CommandLineArguments args;
259 // Do this before pre_parse_commandline, because --help now shows the
260 // default user data dir.
261 init_physfs(argv[0]);
265 args.parse_args(argc, argv);
266 g_log_level = args.get_log_level();
268 catch(const std::exception& err)
273 args.merge_into(*g_config);
276 catch(const std::exception& err_)
278 log_fatal << "failed to init config or tinygettext: " << err_.what() << std::endl;
281 std::cout << "Error: " << err.what() << std::endl;
287 args.merge_into(*g_config);
289 timelog("tinygettext");
292 switch (args.get_action())
294 case CommandLineArguments::PRINT_VERSION:
295 args.print_version();
298 case CommandLineArguments::PRINT_HELP:
299 args.print_help(argv[0]);
302 case CommandLineArguments::PRINT_DATADIR:
303 args.print_datadir();
307 // continue and start the game as usual
314 timelog("controller");
315 InputManager input_manager;
317 timelog("commandline");
320 std::unique_ptr<VideoSystem> video_system = VideoSystem::create(g_config->video);
321 DrawingContext context(video_system->get_renderer(),
322 video_system->get_lightmap());
326 SoundManager sound_manager;
327 sound_manager.enable_sound(g_config->sound_enabled);
328 sound_manager.enable_music(g_config->music_enabled);
330 Console::current()->init_graphics();
332 timelog("scripting");
333 scripting::init_squirrel(g_config->enable_script_debugger);
335 timelog("resources");
336 TileManager tile_manager;
337 SpriteManager sprite_manager;
341 AddonManager::get_instance().load_addons();
345 const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));
347 GameManager game_manager;
348 ScreenManager screen_manager;
352 if(g_config->start_level != "") {
353 // we have a normal path specified at commandline, not a physfs path.
354 // So we simply mount that path here...
355 std::string dir = FileSystem::dirname(g_config->start_level);
356 std::string fileProtocol = "file://";
357 std::string::size_type position = dir.find(fileProtocol);
358 if(position != std::string::npos) {
359 dir = dir.replace(position, fileProtocol.length(), "");
361 log_debug << "Adding dir: " << dir << std::endl;
362 PHYSFS_addToSearchPath(dir.c_str(), true);
364 if(g_config->start_level.size() > 4 &&
365 g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
366 ScreenManager::current()->push_screen(std::unique_ptr<Screen>(
367 new worldmap::WorldMap(
368 FileSystem::basename(g_config->start_level), *default_savegame)));
370 std::unique_ptr<GameSession> session (
371 new GameSession(FileSystem::basename(g_config->start_level), *default_savegame));
373 g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
374 init_rand();//initialise generator with seed from session
376 if(g_config->start_demo != "")
377 session->play_demo(g_config->start_demo);
379 if(g_config->record_demo != "")
380 session->record_demo(g_config->record_demo);
381 ScreenManager::current()->push_screen(std::move(session));
384 ScreenManager::current()->push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));
387 ScreenManager::current()->run(context);
388 } catch(std::exception& e) {
389 log_fatal << "Unexpected exception: " << e.what() << std::endl;
392 log_fatal << "Unexpected exception" << std::endl;
400 scripting::exit_squirrel();
405 g_dictionary_manager.reset();