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