Added m_ prefixes to Console
[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
69 void
70 Main::init_tinygettext()
71 {
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));
75
76   g_dictionary_manager->add_directory("locale");
77   g_dictionary_manager->set_charset("UTF-8");
78
79   // Config setting "locale" overrides language detection
80   if (g_config->locale != "")
81   {
82     g_dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
83   } else {
84     FL_Locale *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);
89   }
90 }
91
92 void
93 Main::init_physfs(const char* argv0)
94 {
95   if(!PHYSFS_init(argv0)) {
96     std::stringstream msg;
97     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
98     throw std::runtime_error(msg.str());
99   }
100
101   // allow symbolic links
102   PHYSFS_permitSymbolicLinks(1);
103
104   // Initialize physfs (this is a slightly modified version of
105   // PHYSFS_setSaneConfig)
106   const char *env_writedir;
107   std::string writedir;
108
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());
116     }
117
118   } else {
119     std::string userdir = PHYSFS_getUserDir();
120
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());
130       }
131
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());
137       }
138     }
139   }
140   PHYSFS_addToSearchPath(writedir.c_str(), 0);
141
142   // when started from source dir...
143   char* base_path = SDL_GetBasePath();
144   std::string dir = base_path;
145   SDL_free(base_path);
146
147   if (dir[dir.length() - 1] != '/')
148     dir += "/";
149   dir += "data";
150   std::string testfname = dir;
151   testfname += "/credits.txt";
152   bool sourcedir = false;
153   FILE* f = fopen(testfname.c_str(), "r");
154   if(f) {
155     fclose(f);
156     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
157       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
158     } else {
159       sourcedir = true;
160     }
161   }
162
163   if(!sourcedir) {
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
168
169     char* dir;
170     br_init (NULL);
171     dir = br_find_data_dir(datadir.c_str());
172     datadir = dir;
173     free(dir);
174
175 #endif
176     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
177       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
178     }
179   }
180
181   //show search Path
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);
186 }
187
188 void
189 Main::init_sdl()
190 {
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());
195   }
196   // just to be sure
197   atexit(SDL_Quit);
198 }
199
200 void
201 Main::init_rand()
202 {
203   g_config->random_seed = gameRandom.srand(g_config->random_seed);
204
205   graphicsRandom.srand(0);
206
207   //const char *how = config->random_seed? ", user fixed.": ", from time().";
208   //log_info << "Using random seed " << config->random_seed << how << std::endl;
209 }
210
211 void
212 Main::init_video()
213 {
214   SDL_SetWindowTitle(VideoSystem::current()->get_renderer().get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
215
216   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
217   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
218   if (!icon)
219   {
220     log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
221   }
222   else
223   {
224     SDL_SetWindowIcon(VideoSystem::current()->get_renderer().get_window(), icon);
225     SDL_FreeSurface(icon);
226   }
227   SDL_ShowCursor(0);
228
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;
233 }
234
235 static Uint32 last_timelog_ticks = 0;
236 static const char* last_timelog_component = 0;
237
238 static inline void timelog(const char* component)
239 {
240   Uint32 current_ticks = SDL_GetTicks();
241
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;
244   }
245
246   last_timelog_ticks = current_ticks;
247   last_timelog_component = component;
248 }
249
250 int
251 Main::run(int argc, char** argv)
252 {
253   int result = 0;
254
255   try
256   {
257     CommandLineArguments args;
258
259     // Do this before pre_parse_commandline, because --help now shows the
260     // default user data dir.
261     init_physfs(argv[0]);
262
263     try
264     {
265       args.parse_args(argc, argv);
266       g_log_level = args.get_log_level();
267     }
268     catch(const std::exception& err)
269     {
270       try
271       {
272         init_config();
273         args.merge_into(*g_config);
274         init_tinygettext();
275       }
276       catch(const std::exception& err_)
277       {
278         log_fatal << "failed to init config or tinygettext: " << err_.what() << std::endl;
279       }
280
281       std::cout << "Error: " << err.what() << std::endl;
282       return EXIT_FAILURE;
283     }
284
285     timelog("config");
286     init_config();
287     args.merge_into(*g_config);
288
289     timelog("tinygettext");
290     init_tinygettext();
291
292     switch (args.get_action())
293     {
294       case CommandLineArguments::PRINT_VERSION:
295         args.print_version();
296         return 0;
297
298       case CommandLineArguments::PRINT_HELP:
299         args.print_help(argv[0]);
300         return 0;
301
302       case CommandLineArguments::PRINT_DATADIR:
303         args.print_datadir();
304         return 0;
305
306       default:
307         // continue and start the game as usual
308         break;
309     }
310
311     init_sdl();
312     //ConsoleBuffer console_buffer;
313
314     timelog("controller");
315     InputManager input_manager;
316
317     timelog("commandline");
318
319     timelog("video");
320     std::unique_ptr<VideoSystem> video_system = VideoSystem::create(g_config->video);
321     DrawingContext context(video_system->get_renderer(),
322                            video_system->get_lightmap());
323     init_video();
324
325     timelog("audio");
326     SoundManager sound_manager;
327     sound_manager.enable_sound(g_config->sound_enabled);
328     sound_manager.enable_music(g_config->music_enabled);
329
330     Console console;
331
332     timelog("scripting");
333     scripting::init_squirrel(g_config->enable_script_debugger);
334
335     timelog("resources");
336     TileManager tile_manager;
337     SpriteManager sprite_manager;
338     Resources resources;
339
340     timelog("addons");
341     AddonManager::get_instance().load_addons();
342
343     timelog(0);
344
345     const std::unique_ptr<Savegame> default_savegame(new Savegame(std::string()));
346
347     GameManager game_manager;
348     ScreenManager screen_manager;
349
350     init_rand();
351
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(), "");
360       }
361       log_debug << "Adding dir: " << dir << std::endl;
362       PHYSFS_addToSearchPath(dir.c_str(), true);
363
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)));
369       } else {
370         std::unique_ptr<GameSession> session (
371           new GameSession(FileSystem::basename(g_config->start_level), *default_savegame));
372
373         g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
374         init_rand();//initialise generator with seed from session
375
376         if(g_config->start_demo != "")
377           session->play_demo(g_config->start_demo);
378
379         if(g_config->record_demo != "")
380           session->record_demo(g_config->record_demo);
381         ScreenManager::current()->push_screen(std::move(session));
382       }
383     } else {
384       ScreenManager::current()->push_screen(std::unique_ptr<Screen>(new TitleScreen(*default_savegame)));
385     }
386
387     ScreenManager::current()->run(context);
388   } catch(std::exception& e) {
389     log_fatal << "Unexpected exception: " << e.what() << std::endl;
390     result = 1;
391   } catch(...) {
392     log_fatal << "Unexpected exception" << std::endl;
393     result = 1;
394   }
395
396   if(g_config)
397     g_config->save();
398   g_config.reset();
399
400   scripting::exit_squirrel();
401
402   SDL_Quit();
403   PHYSFS_deinit();
404
405   g_dictionary_manager.reset();
406
407   return result;
408 }
409
410 /* EOF */