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