Use more RAII in initialisation code
[supertux.git] / src / supertux / main.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
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.
8 //
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.
13 //
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/>.
16
17 #include "supertux/main.hpp"
18
19 #include <config.h>
20 #include <version.h>
21
22 #include <SDL_image.h>
23 #include <physfs.h>
24 #include <iostream>
25 #include <binreloc.h>
26 #include <tinygettext/log.hpp>
27 #include <boost/format.hpp>
28 #include <stdio.h>
29 extern "C" {
30 #include <findlocale.h>
31 }
32
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"
57
58 void
59 Main::init_config()
60 {
61   g_config.reset(new Config);
62   try {
63     g_config->load();
64   } catch(const std::exception& e) {
65     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
66   }
67
68   // init random number stuff
69   g_config->random_seed = gameRandom.srand(g_config->random_seed);
70   graphicsRandom.srand(0);
71   //const char *how = config->random_seed? ", user fixed.": ", from time().";
72   //log_info << "Using random seed " << config->random_seed << how << std::endl;
73 }
74
75 void
76 Main::init_tinygettext()
77 {
78   g_dictionary_manager.reset(new tinygettext::DictionaryManager);
79   tinygettext::Log::set_log_info_callback(0);
80   g_dictionary_manager->set_filesystem(std::unique_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
81
82   g_dictionary_manager->add_directory("locale");
83   g_dictionary_manager->set_charset("UTF-8");
84
85   // Config setting "locale" overrides language detection
86   if (g_config->locale != "")
87   {
88     g_dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
89   }
90   else
91   {
92     FL_Locale *locale;
93     FL_FindLocale(&locale);
94     tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
95     FL_FreeLocale(&locale);
96     g_dictionary_manager->set_language(language);
97   }
98 }
99
100 class PhysfsSubsystem
101 {
102 public:
103   PhysfsSubsystem(const char* argv0)
104   {
105     if(!PHYSFS_init(argv0)) {
106       std::stringstream msg;
107       msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
108       throw std::runtime_error(msg.str());
109     }
110
111     // allow symbolic links
112     PHYSFS_permitSymbolicLinks(1);
113
114     // Initialize physfs (this is a slightly modified version of
115     // PHYSFS_setSaneConfig)
116     const char *env_writedir;
117     std::string writedir;
118
119     if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
120       writedir = env_writedir;
121       if(!PHYSFS_setWriteDir(writedir.c_str())) {
122         std::ostringstream msg;
123         msg << "Failed to use configuration directory '"
124             <<  writedir << "': " << PHYSFS_getLastError();
125         throw std::runtime_error(msg.str());
126       }
127
128     } else {
129       std::string userdir = PHYSFS_getUserDir();
130
131       // Set configuration directory
132       writedir = userdir + WRITEDIR_NAME;
133       if(!PHYSFS_setWriteDir(writedir.c_str())) {
134         // try to create the directory
135         if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
136           std::ostringstream msg;
137           msg << "Failed creating configuration directory '"
138               << writedir << "': " << PHYSFS_getLastError();
139           throw std::runtime_error(msg.str());
140         }
141
142         if(!PHYSFS_setWriteDir(writedir.c_str())) {
143           std::ostringstream msg;
144           msg << "Failed to use configuration directory '"
145               <<  writedir << "': " << PHYSFS_getLastError();
146           throw std::runtime_error(msg.str());
147         }
148       }
149     }
150     PHYSFS_addToSearchPath(writedir.c_str(), 0);
151
152     // when started from source dir...
153     char* base_path = SDL_GetBasePath();
154     std::string dir = base_path;
155     SDL_free(base_path);
156
157     if (dir[dir.length() - 1] != '/')
158       dir += "/";
159     dir += "data";
160     std::string testfname = dir;
161     testfname += "/credits.txt";
162     bool sourcedir = false;
163     FILE* f = fopen(testfname.c_str(), "r");
164     if(f) {
165       fclose(f);
166       if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
167         log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
168       } else {
169         sourcedir = true;
170       }
171     }
172
173     if(!sourcedir) {
174       std::string datadir = PHYSFS_getBaseDir();
175       datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
176       datadir += "/" INSTALL_SUBDIR_SHARE;
177 #ifdef ENABLE_BINRELOC
178
179       char* dir;
180       br_init (NULL);
181       dir = br_find_data_dir(datadir.c_str());
182       datadir = dir;
183       free(dir);
184
185 #endif
186       if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
187         log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
188       }
189     }
190
191     //show search Path
192     char** searchpath = PHYSFS_getSearchPath();
193     for(char** i = searchpath; *i != NULL; i++)
194       log_info << "[" << *i << "] is in the search path" << std::endl;
195     PHYSFS_freeList(searchpath);
196   }
197
198   ~PhysfsSubsystem()
199   {
200     PHYSFS_deinit();
201   }
202 };
203
204 class SDLSubsystem
205 {
206 public:
207   SDLSubsystem()
208   {
209     if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0)
210     {
211       std::stringstream msg;
212       msg << "Couldn't initialize SDL: " << SDL_GetError();
213       throw std::runtime_error(msg.str());
214     }
215     // just to be sure
216     atexit(SDL_Quit);
217   }
218
219   ~SDLSubsystem()
220   {
221     SDL_Quit();
222   }
223 };
224
225 void
226 Main::init_video()
227 {
228   SDL_SetWindowTitle(VideoSystem::current()->get_renderer().get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
229
230   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
231   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
232   if (!icon)
233   {
234     log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
235   }
236   else
237   {
238     SDL_SetWindowIcon(VideoSystem::current()->get_renderer().get_window(), icon);
239     SDL_FreeSurface(icon);
240   }
241   SDL_ShowCursor(0);
242
243   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
244            << " Window: "     << g_config->window_size
245            << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
246            << " Area: "       << g_config->aspect_size << std::endl;
247 }
248
249 static Uint32 last_timelog_ticks = 0;
250 static const char* last_timelog_component = 0;
251
252 static inline void timelog(const char* component)
253 {
254   Uint32 current_ticks = SDL_GetTicks();
255
256   if(last_timelog_component != 0) {
257     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
258   }
259
260   last_timelog_ticks = current_ticks;
261   last_timelog_component = component;
262 }
263
264 void
265 Main::launch_game()
266 {
267   SDLSubsystem sdl_subsystem;
268   ConsoleBuffer console_buffer;
269
270   timelog("controller");
271   InputManager input_manager;
272
273   timelog("commandline");
274
275   timelog("video");
276   std::unique_ptr<VideoSystem> video_system = VideoSystem::create(g_config->video);
277   DrawingContext context(video_system->get_renderer(),
278                          video_system->get_lightmap());
279   init_video();
280
281   timelog("audio");
282   SoundManager sound_manager;
283   sound_manager.enable_sound(g_config->sound_enabled);
284   sound_manager.enable_music(g_config->music_enabled);
285
286   Console console(console_buffer);
287
288   timelog("scripting");
289   scripting::init_squirrel(g_config->enable_script_debugger);
290
291   timelog("resources");
292   TileManager tile_manager;
293   SpriteManager sprite_manager;
294   Resources resources;
295
296   timelog("addons");
297   AddonManager::get_instance().load_addons();
298
299   timelog(0);
300
301   const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));
302
303   GameManager game_manager;
304   ScreenManager screen_manager;
305
306   if(g_config->start_level != "") {
307     // we have a normal path specified at commandline, not a physfs path.
308     // So we simply mount that path here...
309     std::string dir = FileSystem::dirname(g_config->start_level);
310     std::string fileProtocol = "file://";
311     std::string::size_type position = dir.find(fileProtocol);
312     if(position != std::string::npos) {
313       dir = dir.replace(position, fileProtocol.length(), "");
314     }
315     log_debug << "Adding dir: " << dir << std::endl;
316     PHYSFS_addToSearchPath(dir.c_str(), true);
317
318     if(g_config->start_level.size() > 4 &&
319        g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0)
320     {
321       screen_manager.push_screen(std::unique_ptr<Screen>(
322                                               new worldmap::WorldMap(
323                                                 FileSystem::basename(g_config->start_level), *default_savegame)));
324     } else {
325       std::unique_ptr<GameSession> session (
326         new GameSession(FileSystem::basename(g_config->start_level), *default_savegame));
327
328       g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
329       init_rand();//initialise generator with seed from session
330
331       if(g_config->start_demo != "")
332         session->play_demo(g_config->start_demo);
333
334       if(g_config->record_demo != "")
335         session->record_demo(g_config->record_demo);
336       screen_manager.push_screen(std::move(session));
337     }
338   } else {
339     screen_manager.push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));
340   }
341
342   screen_manager.run(context);
343 }
344
345 int
346 Main::run(int argc, char** argv)
347 {
348   int result = 0;
349
350   try
351   {
352     CommandLineArguments args;
353
354     // Do this before pre_parse_commandline, because --help now shows the
355     // default user data dir.
356     PhysfsSubsystem physfs_subsystem(argv[0]);
357
358     try
359     {
360       args.parse_args(argc, argv);
361       g_log_level = args.get_log_level();
362     }
363     catch(const std::exception& err)
364     {
365       try
366       {
367         init_config();
368         args.merge_into(*g_config);
369         init_tinygettext();
370       }
371       catch(const std::exception& err_)
372       {
373         log_fatal << "failed to init config or tinygettext: " << err_.what() << std::endl;
374       }
375
376       std::cout << "Error: " << err.what() << std::endl;
377       return EXIT_FAILURE;
378     }
379
380     timelog("config");
381     init_config();
382     args.merge_into(*g_config);
383
384     timelog("tinygettext");
385     init_tinygettext();
386
387     switch (args.get_action())
388     {
389       case CommandLineArguments::PRINT_VERSION:
390         args.print_version();
391         return 0;
392
393       case CommandLineArguments::PRINT_HELP:
394         args.print_help(argv[0]);
395         return 0;
396
397       case CommandLineArguments::PRINT_DATADIR:
398         args.print_datadir();
399         return 0;
400
401       default:
402         launch_game();
403         break;
404     }
405   }
406   catch(const std::exception& e)
407   {
408     log_fatal << "Unexpected exception: " << e.what() << std::endl;
409     result = 1;
410   }
411   catch(...)
412   {
413     log_fatal << "Unexpected exception" << std::endl;
414     result = 1;
415   }
416
417   if(g_config)
418     g_config->save();
419   g_config.reset();
420
421   scripting::exit_squirrel();
422
423   g_dictionary_manager.reset();
424
425   return result;
426 }
427
428 /* EOF */