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