Merge branch 'feature/menu-cleanup'
[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 "supertux/game_manager.hpp"
42 #include "supertux/gameconfig.hpp"
43 #include "supertux/globals.hpp"
44 #include "supertux/player_status.hpp"
45 #include "supertux/resources.hpp"
46 #include "supertux/screen_fade.hpp"
47 #include "supertux/screen_manager.hpp"
48 #include "supertux/title_screen.hpp"
49 #include "util/file_system.hpp"
50 #include "util/gettext.hpp"
51 #include "video/drawing_context.hpp"
52 #include "video/lightmap.hpp"
53 #include "video/renderer.hpp"
54 #include "worldmap/worldmap.hpp"
55
56 namespace { DrawingContext *context_pointer; }
57
58 #ifdef _WIN32
59 # define WRITEDIR_NAME PACKAGE_NAME
60 #else
61 # define WRITEDIR_NAME "." PACKAGE_NAME
62 #endif
63
64 void 
65 Main::init_config()
66 {
67   g_config = new Config();
68   try {
69     g_config->load();
70   } catch(std::exception& e) {
71     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
72   }
73 }
74
75 void
76 Main::init_tinygettext()
77 {
78   dictionary_manager = new tinygettext::DictionaryManager();
79   tinygettext::Log::set_log_info_callback(0);
80   dictionary_manager->set_filesystem(std::unique_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
81
82   dictionary_manager->add_directory("locale");
83   dictionary_manager->set_charset("UTF-8");
84
85   // Config setting "locale" overrides language detection
86   if (g_config->locale != "") 
87   {
88     dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
89   } else {
90     FL_Locale *locale;
91     FL_FindLocale(&locale);
92     tinygettext::Language language = tinygettext::Language::from_spec( locale->lang?locale->lang:"", locale->country?locale->country:"", locale->variant?locale->variant:"");
93     FL_FreeLocale(&locale);
94     dictionary_manager->set_language(language);
95   }
96 }
97
98 void
99 Main::init_physfs(const char* argv0)
100 {
101   if(!PHYSFS_init(argv0)) {
102     std::stringstream msg;
103     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
104     throw std::runtime_error(msg.str());
105   }
106
107   // allow symbolic links
108   PHYSFS_permitSymbolicLinks(1);
109
110   // Initialize physfs (this is a slightly modified version of
111   // PHYSFS_setSaneConfig)
112   const char *env_writedir;
113   std::string writedir;
114
115   if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
116     writedir = env_writedir;
117     if(!PHYSFS_setWriteDir(writedir.c_str())) {
118       std::ostringstream msg;
119       msg << "Failed to use configuration directory '"
120           <<  writedir << "': " << PHYSFS_getLastError();
121       throw std::runtime_error(msg.str());
122     }
123
124   } else {
125     std::string userdir = PHYSFS_getUserDir();
126
127     // Set configuration directory
128     writedir = userdir + WRITEDIR_NAME;
129     if(!PHYSFS_setWriteDir(writedir.c_str())) {
130       // try to create the directory
131       if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
132         std::ostringstream msg;
133         msg << "Failed creating configuration directory '"
134             << writedir << "': " << PHYSFS_getLastError();
135         throw std::runtime_error(msg.str());
136       }
137
138       if(!PHYSFS_setWriteDir(writedir.c_str())) {
139         std::ostringstream msg;
140         msg << "Failed to use configuration directory '"
141             <<  writedir << "': " << PHYSFS_getLastError();
142         throw std::runtime_error(msg.str());
143       }
144     }
145   }
146   PHYSFS_addToSearchPath(writedir.c_str(), 0);
147
148   // when started from source dir...
149   char* base_path = SDL_GetBasePath();
150   std::string dir = base_path;
151   SDL_free(base_path);
152
153   if (dir[dir.length() - 1] != '/')
154     dir += "/";
155   dir += "data";
156   std::string testfname = dir;
157   testfname += "/credits.txt";
158   bool sourcedir = false;
159   FILE* f = fopen(testfname.c_str(), "r");
160   if(f) {
161     fclose(f);
162     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
163       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
164     } else {
165       sourcedir = true;
166     }
167   }
168
169   if(!sourcedir) {
170     std::string datadir = PHYSFS_getBaseDir();
171     datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
172     datadir += "/" INSTALL_SUBDIR_SHARE;
173 #ifdef ENABLE_BINRELOC
174
175     char* dir;
176     br_init (NULL);
177     dir = br_find_data_dir(datadir.c_str());
178     datadir = dir;
179     free(dir);
180
181 #endif
182     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
183       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
184     }
185   }
186
187   //show search Path
188   char** searchpath = PHYSFS_getSearchPath();
189   for(char** i = searchpath; *i != NULL; i++)
190     log_info << "[" << *i << "] is in the search path" << std::endl;
191   PHYSFS_freeList(searchpath);
192 }
193
194 void
195 Main::print_usage(const char* argv0)
196 {
197   std::string default_user_data_dir =
198       std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
199
200   std::cerr << boost::format(_(
201                  "\n"
202                  "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
203                  "Options:\n"
204                  "  -f, --fullscreen             Run in fullscreen mode\n"
205                  "  -w, --window                 Run in window mode\n"
206                  "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
207                  "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
208                  "  -d, --default                Reset video settings to default values\n"
209                  "  --renderer RENDERER          Use sdl, opengl, or auto to render\n"
210                  "  --disable-sfx                Disable sound effects\n"
211                  "  --disable-music              Disable music\n"
212                  "  -h, --help                   Show this help message and quit\n"
213                  "  -v, --version                Show SuperTux version and quit\n"
214                  "  --console                    Enable ingame scripting console\n"
215                  "  --noconsole                  Disable ingame scripting console\n"
216                  "  --show-fps                   Display framerate in levels\n"
217                  "  --no-show-fps                Do not display framerate in levels\n"
218                  "  --record-demo FILE LEVEL     Record a demo to FILE\n"
219                  "  --play-demo FILE LEVEL       Play a recorded demo\n"
220                  "  -s, --debug-scripts          Enable script debugger.\n"
221                  "  --print-datadir              Print supertux's primary data directory.\n"
222                  "\n"
223                  "Environment variables:\n"
224                  "  SUPERTUX2_USER_DIR           Directory for user data (savegames, etc.);\n"
225                  "                               default %s\n"
226                  "\n"
227                  ))
228             % argv0 % default_user_data_dir
229             << std::flush;
230 }
231
232 /**
233  * Options that should be evaluated prior to any initializations at all go here
234  */
235 bool
236 Main::pre_parse_commandline(int argc, char** argv)
237 {
238   for(int i = 1; i < argc; ++i) {
239     std::string arg = argv[i];
240
241     if(arg == "--version" || arg == "-v") {
242       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
243       return true;
244     }
245     if(arg == "--help" || arg == "-h") {
246       print_usage(argv[0]);
247       return true;
248     }
249     if(arg == "--print-datadir") {
250       /*
251        * Print the datadir searchpath to stdout, one path per
252        * line. Then exit. Intended for use by the supertux-editor.
253        */
254       char **sp;
255       size_t sp_index;
256       sp = PHYSFS_getSearchPath();
257       if (sp)
258         for (sp_index = 0; sp[sp_index]; sp_index++)
259           std::cout << sp[sp_index] << std::endl;
260       PHYSFS_freeList(sp);
261       return true;
262     }
263   }
264
265   return false;
266 }
267
268 /**
269  * Options that should be evaluated after config is read go here
270  */
271 bool
272 Main::parse_commandline(int argc, char** argv)
273 {
274   for(int i = 1; i < argc; ++i) {
275     std::string arg = argv[i];
276
277     if(arg == "--fullscreen" || arg == "-f") {
278       g_config->use_fullscreen = true;
279     } else if(arg == "--default" || arg == "-d") {
280       g_config->use_fullscreen = false;
281       
282       g_config->window_size     = Size(800, 600);
283       g_config->fullscreen_size = Size(800, 600);
284       g_config->fullscreen_refresh_rate = 0;
285       g_config->aspect_size     = Size(0, 0);  // auto detect
286       
287     } else if(arg == "--window" || arg == "-w") {
288       g_config->use_fullscreen = false;
289     } else if(arg == "--geometry" || arg == "-g") {
290       i += 1;
291       if(i >= argc) 
292       {
293         print_usage(argv[0]);
294         throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
295       } 
296       else 
297       {
298         int width, height;
299         if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
300         {
301           print_usage(argv[0]);
302           throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
303         }
304         else
305         {
306           g_config->window_size     = Size(width, height);
307           g_config->fullscreen_size = Size(width, height);
308           g_config->fullscreen_refresh_rate = 0;
309         }
310       }
311     } else if(arg == "--aspect" || arg == "-a") {
312       i += 1;
313       if(i >= argc) 
314       {
315         print_usage(argv[0]);
316         throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
317       } 
318       else 
319       {
320         int aspect_width  = 0;
321         int aspect_height = 0;
322         if (strcmp(argv[i], "auto") == 0)
323         {
324           aspect_width  = 0;
325           aspect_height = 0;
326         }
327         else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2) 
328         {
329           print_usage(argv[0]);
330           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
331         }
332         else 
333         {
334           float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
335
336           // use aspect ratio to calculate logical resolution
337           if (aspect_ratio > 1) {
338             g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
339                                          600);
340           } else {
341             g_config->aspect_size = Size(600, 
342                                          static_cast<int>(600 * 1/aspect_ratio + 0.5));
343           }
344         }
345       }
346     } else if(arg == "--renderer") {
347       i += 1;
348       if(i >= argc) 
349       {
350         print_usage(argv[0]);
351         throw std::runtime_error("Need to specify a renderer for renderer argument");
352       } 
353       else 
354       {
355         g_config->video = VideoSystem::get_video_system(argv[i]);
356       }
357     } else if(arg == "--show-fps") {
358       g_config->show_fps = true;
359     } else if(arg == "--no-show-fps") {
360       g_config->show_fps = false;
361     } else if(arg == "--console") {
362       g_config->console_enabled = true;
363     } else if(arg == "--noconsole") {
364       g_config->console_enabled = false;
365     } else if(arg == "--disable-sfx") {
366       g_config->sound_enabled = false;
367     } else if(arg == "--disable-music") {
368       g_config->music_enabled = false;
369     } else if(arg == "--play-demo") {
370       if(i+1 >= argc) {
371         print_usage(argv[0]);
372         throw std::runtime_error("Need to specify a demo filename");
373       }
374       g_config->start_demo = argv[++i];
375     } else if(arg == "--record-demo") {
376       if(i+1 >= argc) {
377         print_usage(argv[0]);
378         throw std::runtime_error("Need to specify a demo filename");
379       }
380       g_config->record_demo = argv[++i];
381     } else if(arg == "--debug-scripts" || arg == "-s") {
382       g_config->enable_script_debugger = true;
383     } else if(arg[0] != '-') {
384       g_config->start_level = arg;
385     } else {
386       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
387     }
388   }
389
390   return false;
391 }
392
393 void
394 Main::init_sdl()
395 {
396   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK | SDL_INIT_GAMECONTROLLER) < 0) {
397     std::stringstream msg;
398     msg << "Couldn't initialize SDL: " << SDL_GetError();
399     throw std::runtime_error(msg.str());
400   }
401   // just to be sure
402   atexit(SDL_Quit);
403 }
404
405 void
406 Main::init_rand()
407 {
408   g_config->random_seed = gameRandom.srand(g_config->random_seed);
409
410   graphicsRandom.srand(0);
411
412   //const char *how = config->random_seed? ", user fixed.": ", from time().";
413   //log_info << "Using random seed " << config->random_seed << how << std::endl;
414 }
415
416 void
417 Main::init_video()
418 {
419   SDL_SetWindowTitle(Renderer::instance()->get_window(), PACKAGE_NAME " " PACKAGE_VERSION);
420
421   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
422   SDL_Surface* icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
423   if (!icon)
424   {
425     log_warning << "Couldn't load icon '" << icon_fname << "': " << SDL_GetError() << std::endl;
426   }
427   else
428   {
429     SDL_SetWindowIcon(Renderer::instance()->get_window(), icon);
430     SDL_FreeSurface(icon);
431   }
432   SDL_ShowCursor(0);
433
434   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
435            << " Window: "     << g_config->window_size
436            << " Fullscreen: " << g_config->fullscreen_size << "@" << g_config->fullscreen_refresh_rate
437            << " Area: "       << g_config->aspect_size << std::endl;
438 }
439
440 void
441 Main::init_audio()
442 {
443   sound_manager = new SoundManager();
444
445   sound_manager->enable_sound(g_config->sound_enabled);
446   sound_manager->enable_music(g_config->music_enabled);
447 }
448
449 void
450 Main::quit_audio()
451 {
452   if(sound_manager != NULL) {
453     delete sound_manager;
454     sound_manager = NULL;
455   }
456 }
457
458 static Uint32 last_timelog_ticks = 0;
459 static const char* last_timelog_component = 0;
460
461 static inline void timelog(const char* component)
462 {
463   Uint32 current_ticks = SDL_GetTicks();
464
465   if(last_timelog_component != 0) {
466     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
467   }
468
469   last_timelog_ticks = current_ticks;
470   last_timelog_component = component;
471 }
472
473 int
474 Main::run(int argc, char** argv)
475 {
476   int result = 0;
477
478   try {
479     /* Do this before pre_parse_commandline, because --help now shows the
480      * default user data dir. */
481     init_physfs(argv[0]);
482
483     if(pre_parse_commandline(argc, argv))
484       return 0;
485
486     init_sdl();
487     Console::instance = new Console();
488
489     timelog("controller");
490     g_input_manager = new InputManager();
491
492     timelog("config");
493     init_config();
494
495     timelog("commandline");
496     if(parse_commandline(argc, argv))
497       return 0;
498
499     timelog("video");
500     std::unique_ptr<Renderer> renderer(VideoSystem::new_renderer());
501     std::unique_ptr<Lightmap> lightmap(VideoSystem::new_lightmap());
502     DrawingContext context(*renderer, *lightmap);
503     context_pointer = &context;
504     init_video();
505     
506     timelog("audio");
507     init_audio();
508     
509     timelog("tinygettext");
510     init_tinygettext();
511
512     Console::instance->init_graphics();
513
514     timelog("scripting");
515     scripting::init_squirrel(g_config->enable_script_debugger);
516
517     timelog("resources");
518     Resources::load_shared();
519     
520     timelog("addons");
521     AddonManager::get_instance().load_addons();
522
523     timelog(0);
524
525     const std::unique_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
526
527     GameManager game_manager;
528     g_screen_manager = new ScreenManager();
529
530     init_rand();
531
532     if(g_config->start_level != "") {
533       // we have a normal path specified at commandline, not a physfs path.
534       // So we simply mount that path here...
535       std::string dir = FileSystem::dirname(g_config->start_level);
536       std::string fileProtocol = "file://";
537       std::string::size_type position = dir.find(fileProtocol);
538       if(position != std::string::npos) {
539          dir = dir.replace(position, fileProtocol.length(), "");
540       }
541       log_debug << "Adding dir: " << dir << std::endl;
542       PHYSFS_addToSearchPath(dir.c_str(), true);
543
544       if(g_config->start_level.size() > 4 &&
545          g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
546         g_screen_manager->push_screen(std::unique_ptr<Screen>(
547                                         new worldmap::WorldMap(
548                                           FileSystem::basename(g_config->start_level), default_playerstatus.get())));
549       } else {
550         std::unique_ptr<GameSession> session (
551           new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
552
553         g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
554         init_rand();//initialise generator with seed from session
555
556         if(g_config->start_demo != "")
557           session->play_demo(g_config->start_demo);
558
559         if(g_config->record_demo != "")
560           session->record_demo(g_config->record_demo);
561         g_screen_manager->push_screen(std::move(session));
562       }
563     } else {
564       g_screen_manager->push_screen(std::unique_ptr<Screen>(new TitleScreen(default_playerstatus.get())));
565     }
566
567     g_screen_manager->run(context);
568   } catch(std::exception& e) {
569     log_fatal << "Unexpected exception: " << e.what() << std::endl;
570     result = 1;
571   } catch(...) {
572     log_fatal << "Unexpected exception" << std::endl;
573     result = 1;
574   }
575
576   delete g_screen_manager;
577   g_screen_manager = NULL;
578
579   Resources::unload_shared();
580   quit_audio();
581
582   if(g_config)
583     g_config->save();
584   delete g_config;
585   g_config = NULL;
586   delete g_input_manager;
587   g_input_manager = NULL;
588   delete Console::instance;
589   Console::instance = NULL;
590   scripting::exit_squirrel();
591   delete texture_manager;
592   texture_manager = NULL;
593   SDL_Quit();
594   PHYSFS_deinit();
595
596   return result;
597 }
598
599 /* EOF */