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