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