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