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