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