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