Fixing compiler errors on Mavericks (not sure if those appeared for everyone)
[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     if(mainBundle == 0)
175       throw "Assertion failed: mainBundle != 0";
176     CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
177     if(mainBundleURL == 0)
178       throw "Assertion failed: mainBundleURL != 0";
179     CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
180     if(pathStr == 0)
181       throw "Assertion failed: pathStr != 0";
182     CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
183     CFRelease(mainBundleURL);
184     CFRelease(pathStr);
185
186     dir = std::string(path) + "/Contents/Resources/data";
187     testfname = dir + "/credits.txt";
188     sourcedir = false;
189     f = fopen(testfname.c_str(), "r");
190     if(f) {
191       fclose(f);
192       if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
193         log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
194       } else {
195         sourcedir = true;
196       }
197     }
198   }
199 #endif
200
201 #ifdef _WIN32
202   PHYSFS_addToSearchPath(".\\data", 1);
203 #endif
204
205   if(!sourcedir) {
206     std::string datadir = PHYSFS_getBaseDir();
207     datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
208     datadir += "/" INSTALL_SUBDIR_SHARE;
209 #ifdef ENABLE_BINRELOC
210
211     char* dir;
212     br_init (NULL);
213     dir = br_find_data_dir(datadir.c_str());
214     datadir = dir;
215     free(dir);
216
217 #endif
218     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
219       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
220     }
221   }
222
223   //show search Path
224   char** searchpath = PHYSFS_getSearchPath();
225   for(char** i = searchpath; *i != NULL; i++)
226     log_info << "[" << *i << "] is in the search path" << std::endl;
227   PHYSFS_freeList(searchpath);
228 }
229
230 void
231 Main::print_usage(const char* argv0)
232 {
233   std::string default_user_data_dir =
234       std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
235
236   std::cerr << boost::format(_(
237                  "\n"
238                  "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
239                  "Options:\n"
240                  "  -f, --fullscreen             Run in fullscreen mode\n"
241                  "  -w, --window                 Run in window mode\n"
242                  "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
243                  "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
244                  "  -d, --default                Reset video settings to default values\n"
245                  "  --renderer RENDERER          Use sdl, opengl, or auto to render\n"
246                  "  --disable-sfx                Disable sound effects\n"
247                  "  --disable-music              Disable music\n"
248                  "  -h, --help                   Show this help message and quit\n"
249                  "  -v, --version                Show SuperTux version and quit\n"
250                  "  --console                    Enable ingame scripting console\n"
251                  "  --noconsole                  Disable ingame scripting console\n"
252                  "  --show-fps                   Display framerate in levels\n"
253                  "  --no-show-fps                Do not display framerate in levels\n"
254                  "  --record-demo FILE LEVEL     Record a demo to FILE\n"
255                  "  --play-demo FILE LEVEL       Play a recorded demo\n"
256                  "  -s, --debug-scripts          Enable script debugger.\n"
257                  "  --print-datadir              Print supertux's primary data directory.\n"
258                  "\n"
259                  "Environment variables:\n"
260                  "  SUPERTUX2_USER_DIR           Directory for user data (savegames, etc.);\n"
261                  "                               default %s\n"
262                  "\n"
263                  ))
264             % argv0 % default_user_data_dir
265             << std::flush;
266 }
267
268 /**
269  * Options that should be evaluated prior to any initializations at all go here
270  */
271 bool
272 Main::pre_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 == "--version" || arg == "-v") {
278       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
279       return true;
280     }
281     if(arg == "--help" || arg == "-h") {
282       print_usage(argv[0]);
283       return true;
284     }
285     if(arg == "--print-datadir") {
286       /*
287        * Print the datadir searchpath to stdout, one path per
288        * line. Then exit. Intended for use by the supertux-editor.
289        */
290       char **sp;
291       size_t sp_index;
292       sp = PHYSFS_getSearchPath();
293       if (sp)
294         for (sp_index = 0; sp[sp_index]; sp_index++)
295           std::cout << sp[sp_index] << std::endl;
296       PHYSFS_freeList(sp);
297       return true;
298     }
299   }
300
301   return false;
302 }
303
304 /**
305  * Options that should be evaluated after config is read go here
306  */
307 bool
308 Main::parse_commandline(int argc, char** argv)
309 {
310   for(int i = 1; i < argc; ++i) {
311     std::string arg = argv[i];
312
313     if(arg == "--fullscreen" || arg == "-f") {
314       g_config->use_fullscreen = true;
315     } else if(arg == "--default" || arg == "-d") {
316       g_config->use_fullscreen = false;
317       
318       g_config->window_size     = Size(800, 600);
319       g_config->fullscreen_size = Size(800, 600);
320       g_config->aspect_size     = Size(0, 0);  // auto detect
321       
322     } else if(arg == "--window" || arg == "-w") {
323       g_config->use_fullscreen = false;
324     } else if(arg == "--geometry" || arg == "-g") {
325       i += 1;
326       if(i >= argc) 
327       {
328         print_usage(argv[0]);
329         throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
330       } 
331       else 
332       {
333         int width, height;
334         if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
335         {
336           print_usage(argv[0]);
337           throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
338         }
339         else
340         {
341           g_config->window_size     = Size(width, height);
342           g_config->fullscreen_size = Size(width, height);
343         }
344       }
345     } else if(arg == "--aspect" || arg == "-a") {
346       i += 1;
347       if(i >= argc) 
348       {
349         print_usage(argv[0]);
350         throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
351       } 
352       else 
353       {
354         int aspect_width  = 0;
355         int aspect_height = 0;
356         if (strcmp(argv[i], "auto") == 0)
357         {
358           aspect_width  = 0;
359           aspect_height = 0;
360         }
361         else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2) 
362         {
363           print_usage(argv[0]);
364           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
365         }
366         else 
367         {
368           float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
369
370           // use aspect ratio to calculate logical resolution
371           if (aspect_ratio > 1) {
372             g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
373                                          600);
374           } else {
375             g_config->aspect_size = Size(600, 
376                                          static_cast<int>(600 * 1/aspect_ratio + 0.5));
377           }
378         }
379       }
380     } else if(arg == "--renderer") {
381       i += 1;
382       if(i >= argc) 
383       {
384         print_usage(argv[0]);
385         throw std::runtime_error("Need to specify a renderer for renderer argument");
386       } 
387       else 
388       {
389         g_config->video = VideoSystem::get_video_system(argv[i]);
390       }
391     } else if(arg == "--show-fps") {
392       g_config->show_fps = true;
393     } else if(arg == "--no-show-fps") {
394       g_config->show_fps = false;
395     } else if(arg == "--console") {
396       g_config->console_enabled = true;
397     } else if(arg == "--noconsole") {
398       g_config->console_enabled = false;
399     } else if(arg == "--disable-sfx") {
400       g_config->sound_enabled = false;
401     } else if(arg == "--disable-music") {
402       g_config->music_enabled = false;
403     } else if(arg == "--play-demo") {
404       if(i+1 >= argc) {
405         print_usage(argv[0]);
406         throw std::runtime_error("Need to specify a demo filename");
407       }
408       g_config->start_demo = argv[++i];
409     } else if(arg == "--record-demo") {
410       if(i+1 >= argc) {
411         print_usage(argv[0]);
412         throw std::runtime_error("Need to specify a demo filename");
413       }
414       g_config->record_demo = argv[++i];
415     } else if(arg == "--debug-scripts" || arg == "-s") {
416       g_config->enable_script_debugger = true;
417     } else if(arg[0] != '-') {
418       g_config->start_level = arg;
419     } else {
420       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
421       return true;
422     }
423   }
424
425   return false;
426 }
427
428 void
429 Main::init_sdl()
430 {
431   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
432     std::stringstream msg;
433     msg << "Couldn't initialize SDL: " << SDL_GetError();
434     throw std::runtime_error(msg.str());
435   }
436   // just to be sure
437   atexit(SDL_Quit);
438
439   SDL_EnableUNICODE(1);
440
441   // wait 100ms and clear SDL event queue because sometimes we have random
442   // joystick events in the queue on startup...
443   SDL_Delay(100);
444   SDL_Event dummy;
445   while(SDL_PollEvent(&dummy))
446     ;
447 }
448
449 void
450 Main::init_rand()
451 {
452   g_config->random_seed = gameRandom.srand(g_config->random_seed);
453
454   graphicsRandom.srand(0);
455
456   //const char *how = config->random_seed? ", user fixed.": ", from time().";
457   //log_info << "Using random seed " << config->random_seed << how << std::endl;
458 }
459
460 void
461 Main::init_video()
462 {
463   // FIXME: Add something here
464   SCREEN_WIDTH  = 800;
465   SCREEN_HEIGHT = 600;
466
467   context_pointer->init_renderer();
468   g_screen = SDL_GetVideoSurface();
469
470   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
471
472   // set icon
473 #ifdef MACOSX
474   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
475 #else
476   const char* icon_fname = "images/engine/icons/supertux.xpm";
477 #endif
478   SDL_Surface* icon;
479   try {
480     icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
481   } catch (const std::runtime_error& err) {
482     icon = 0;
483     log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
484   }
485   if(icon != 0) {
486     SDL_WM_SetIcon(icon, 0);
487     SDL_FreeSurface(icon);
488   }
489   else {
490     log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
491   }
492
493   SDL_ShowCursor(0);
494
495   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
496            << " Window: "     << g_config->window_size
497            << " Fullscreen: " << g_config->fullscreen_size
498            << " Area: "       << g_config->aspect_size << std::endl;
499 }
500
501 void
502 Main::init_audio()
503 {
504   sound_manager = new SoundManager();
505
506   sound_manager->enable_sound(g_config->sound_enabled);
507   sound_manager->enable_music(g_config->music_enabled);
508 }
509
510 void
511 Main::quit_audio()
512 {
513   if(sound_manager != NULL) {
514     delete sound_manager;
515     sound_manager = NULL;
516   }
517 }
518
519 void
520 Main::wait_for_event(float min_delay, float max_delay)
521 {
522   assert(min_delay <= max_delay);
523
524   Uint32 min = (Uint32) (min_delay * 1000);
525   Uint32 max = (Uint32) (max_delay * 1000);
526
527   Uint32 ticks = SDL_GetTicks();
528   while(SDL_GetTicks() - ticks < min) {
529     SDL_Delay(10);
530     sound_manager->update();
531   }
532
533   // clear event queue
534   SDL_Event event;
535   while (SDL_PollEvent(&event))
536   {}
537
538   /* Handle events: */
539   bool running = false;
540   ticks = SDL_GetTicks();
541   while(running) {
542     while(SDL_PollEvent(&event)) {
543       switch(event.type) {
544         case SDL_QUIT:
545           g_screen_manager->quit();
546           break;
547         case SDL_KEYDOWN:
548         case SDL_JOYBUTTONDOWN:
549         case SDL_MOUSEBUTTONDOWN:
550           running = false;
551       }
552     }
553     if(SDL_GetTicks() - ticks >= (max - min))
554       running = false;
555     sound_manager->update();
556     SDL_Delay(10);
557   }
558 }
559
560 static Uint32 last_timelog_ticks = 0;
561 static const char* last_timelog_component = 0;
562
563 static inline void timelog(const char* component)
564 {
565   Uint32 current_ticks = SDL_GetTicks();
566
567   if(last_timelog_component != 0) {
568     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
569   }
570
571   last_timelog_ticks = current_ticks;
572   last_timelog_component = component;
573 }
574
575 int
576 Main::run(int argc, char** argv)
577 {
578   int result = 0;
579
580   try {
581     /* Do this before pre_parse_commandline, because --help now shows the
582      * default user data dir. */
583     init_physfs(argv[0]);
584
585     if(pre_parse_commandline(argc, argv))
586       return 0;
587
588     init_sdl();
589     Console::instance = new Console();
590
591     timelog("controller");
592     g_jk_controller = new JoystickKeyboardController();
593
594     timelog("config");
595     init_config();
596
597     timelog("commandline");
598     if(parse_commandline(argc, argv))
599       return 0;
600
601     timelog("video");
602     DrawingContext context;
603     context_pointer = &context;
604     init_video();
605     
606     timelog("audio");
607     init_audio();
608     
609     timelog("tinygettext");
610     init_tinygettext();
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("addons");
621     AddonManager::get_instance().load_addons();
622
623     timelog(0);
624
625     const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
626
627     g_screen_manager = new ScreenManager();
628
629     init_rand();
630
631     if(g_config->start_level != "") {
632       // we have a normal path specified at commandline, not a physfs path.
633       // So we simply mount that path here...
634       std::string dir = FileSystem::dirname(g_config->start_level);
635       log_debug << "Adding dir: " << dir << std::endl;
636       PHYSFS_addToSearchPath(dir.c_str(), true);
637
638       if(g_config->start_level.size() > 4 &&
639          g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
640         g_screen_manager->push_screen(new worldmap::WorldMap(
641                                  FileSystem::basename(g_config->start_level), default_playerstatus.get()));
642       } else {
643         std::auto_ptr<GameSession> session (
644           new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
645
646         g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
647         init_rand();//initialise generator with seed from session
648
649         if(g_config->start_demo != "")
650           session->play_demo(g_config->start_demo);
651
652         if(g_config->record_demo != "")
653           session->record_demo(g_config->record_demo);
654         g_screen_manager->push_screen(session.release());
655       }
656     } else {
657       g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
658     }
659
660     g_screen_manager->run(context);
661   } catch(std::exception& e) {
662     log_fatal << "Unexpected exception: " << e.what() << std::endl;
663     result = 1;
664   } catch(...) {
665     log_fatal << "Unexpected exception" << std::endl;
666     result = 1;
667   }
668
669   delete g_screen_manager;
670   g_screen_manager = NULL;
671
672   Resources::unload_shared();
673   quit_audio();
674
675   if(g_config)
676     g_config->save();
677   delete g_config;
678   g_config = NULL;
679   delete g_jk_controller;
680   g_jk_controller = NULL;
681   delete Console::instance;
682   Console::instance = NULL;
683   scripting::exit_squirrel();
684   delete texture_manager;
685   texture_manager = NULL;
686   SDL_Quit();
687   PHYSFS_deinit();
688
689   return result;
690 }
691
692 /* EOF */