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