aa998fd39edb297e5305d4338e76147afbc706e0
[supertux.git] / src / main.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
19 //  02111-1307, USA.
20 #include <config.h>
21 #include <assert.h>
22
23 #include "log.hpp"
24 #include "main.hpp"
25
26 #include <stdexcept>
27 #include <sstream>
28 #include <ctime>
29 #include <cstdlib>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 #include <physfs.h>
34 #include <SDL.h>
35 #include <SDL_image.h>
36
37 #include "gameconfig.hpp"
38 #include "resources.hpp"
39 #include "gettext.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "video/surface.hpp"
42 #include "video/texture_manager.hpp"
43 #include "video/drawing_context.hpp"
44 #include "video/glutil.hpp"
45 #include "control/joystickkeyboardcontroller.hpp"
46 #include "options_menu.hpp"
47 #include "mainloop.hpp"
48 #include "title.hpp"
49 #include "game_session.hpp"
50 #include "scripting/level.hpp"
51 #include "scripting/squirrel_util.hpp"
52 #include "file_system.hpp"
53 #include "physfs/physfs_sdl.hpp"
54 #include "random_generator.hpp"
55 #include "worldmap/worldmap.hpp"
56 #include "binreloc/binreloc.h"
57
58 namespace { DrawingContext *context_pointer; }
59 SDL_Surface *screen;
60 JoystickKeyboardController* main_controller = 0;
61 TinyGetText::DictionaryManager dictionary_manager;
62
63 int SCREEN_WIDTH;
64 int SCREEN_HEIGHT;
65
66 static void init_config()
67 {
68   config = new Config();
69   try {
70     config->load();
71   } catch(std::exception& e) {
72     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
73   }
74 }
75
76 static void init_tinygettext()
77 {
78   dictionary_manager.add_directory("locale");
79   dictionary_manager.set_charset("UTF-8");
80
81   // Config setting "locale" overrides language detection
82   if (config->locale != "") {
83     dictionary_manager.set_language( config->locale );
84   }
85 }
86
87 static void init_physfs(const char* argv0)
88 {
89   if(!PHYSFS_init(argv0)) {
90     std::stringstream msg;
91     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
92     throw std::runtime_error(msg.str());
93   }
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   const char* dirsep = PHYSFS_getDirSeparator();
100   char* writedir = new char[strlen(userdir) + strlen(application) + 2];
101
102   // Set configuration directory
103   sprintf(writedir, "%s.%s", userdir, application);
104   if(!PHYSFS_setWriteDir(writedir)) {
105     // try to create the directory
106     char* mkdir = new char[strlen(application) + 2];
107     sprintf(mkdir, ".%s", application);
108     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
109       std::ostringstream msg;
110       msg << "Failed creating configuration directory '"
111           << writedir << "': " << PHYSFS_getLastError();
112       delete[] writedir;
113       delete[] mkdir;
114       throw std::runtime_error(msg.str());
115     }
116     delete[] mkdir;
117
118     if(!PHYSFS_setWriteDir(writedir)) {
119       std::ostringstream msg;
120       msg << "Failed to use configuration directory '"
121           <<  writedir << "': " << PHYSFS_getLastError();
122       delete[] writedir;
123       throw std::runtime_error(msg.str());
124     }
125   }
126   PHYSFS_addToSearchPath(writedir, 0);
127   delete[] writedir;
128
129   // Search for archives and add them to the search path
130   const char* archiveExt = "zip";
131   char** rc = PHYSFS_enumerateFiles("/");
132   size_t extlen = strlen(archiveExt);
133
134   for(char** i = rc; *i != 0; ++i) {
135     size_t l = strlen(*i);
136     if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
137       const char* ext = (*i) + (l - extlen);
138       if(strcasecmp(ext, archiveExt) == 0) {
139         const char* d = PHYSFS_getRealDir(*i);
140         char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
141         sprintf(str, "%s%s%s", d, dirsep, *i);
142         PHYSFS_addToSearchPath(str, 1);
143         delete[] str;
144       }
145     }
146   }
147
148   PHYSFS_freeList(rc);
149
150   // when started from source dir...
151   std::string dir = PHYSFS_getBaseDir();
152   dir += "/data";
153   std::string testfname = dir;
154   testfname += "/credits.txt";
155   bool sourcedir = false;
156   FILE* f = fopen(testfname.c_str(), "r");
157   if(f) {
158     fclose(f);
159     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
160       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
161     } else {
162       sourcedir = true;
163     }
164   }
165
166 #ifdef MACOSX
167   // when started from Application file on Mac OS X...
168   dir = PHYSFS_getBaseDir();
169   dir += "SuperTux.app/Contents/Resources/data";
170   testfname = dir + "/credits.txt";
171   sourcedir = false;
172   f = fopen(testfname.c_str(), "r");
173   if(f) {
174     fclose(f);
175     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
176       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
177     } else {
178       sourcedir = true;
179     }
180   }
181 #endif
182
183 #ifdef _WIN32
184   PHYSFS_addToSearchPath(".\\data", 1);
185 #endif
186
187   if(!sourcedir) {
188 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
189     std::string datadir;
190 #ifdef ENABLE_BINRELOC
191
192     char* dir;
193     br_init (NULL);
194     dir = br_find_data_dir(APPDATADIR);
195     datadir = dir;
196     datadir += "/" PACKAGE_NAME;
197     free(dir);
198
199 #else
200     datadir = APPDATADIR;
201 #endif
202     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
203       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
204     }
205 #endif
206   }
207
208   // allow symbolic links
209   PHYSFS_permitSymbolicLinks(1);
210
211   //show search Path
212   char** searchpath = PHYSFS_getSearchPath();
213   for(char** i = searchpath; *i != NULL; i++)
214     log_info << "[" << *i << "] is in the search path" << std::endl;
215   PHYSFS_freeList(searchpath);
216 }
217
218 static void print_usage(const char* argv0)
219 {
220   fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
221   fprintf(stderr,
222           _("Options:\n"
223             "  -f, --fullscreen             Run in fullscreen mode\n"
224             "  -w, --window                 Run in window mode\n"
225             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
226             "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
227             "  --disable-sfx                Disable sound effects\n"
228             "  --disable-music              Disable music\n"
229             "  --help                       Show this help message\n"
230             "  --version                    Display SuperTux version and quit\n"
231             "  --console                    Enable ingame scripting console\n"
232             "  --noconsole                  Disable ingame scripting console\n"
233             "  --show-fps                   Display framerate in levels\n"
234             "  --no-show-fps                Do not display framerate in levels\n"
235             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
236             "  --play-demo FILE LEVEL       Play a recorded demo\n"
237             "\n"));
238 }
239
240 /**
241  * Options that should be evaluated prior to any initializations at all go here
242  */
243 static bool pre_parse_commandline(int argc, char** argv)
244 {
245   for(int i = 1; i < argc; ++i) {
246     std::string arg = argv[i];
247
248     if(arg == "--version") {
249       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
250       return true;
251     }
252   }
253
254   return false;
255 }
256
257 /**
258  * Options that should be evaluated after config is read go here
259  */
260 static bool parse_commandline(int argc, char** argv)
261 {
262   for(int i = 1; i < argc; ++i) {
263     std::string arg = argv[i];
264
265     if(arg == "--help") {
266       print_usage(argv[0]);
267       return true;
268     } else if(arg == "--fullscreen" || arg == "-f") {
269       config->use_fullscreen = true;
270     } else if(arg == "--window" || arg == "-w") {
271       config->use_fullscreen = false;
272     } else if(arg == "--geometry" || arg == "-g") {
273       if(i+1 >= argc) {
274         print_usage(argv[0]);
275         throw std::runtime_error("Need to specify a parameter for geometry switch");
276       }
277       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
278          != 2) {
279         print_usage(argv[0]);
280         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
281       }
282     } else if(arg == "--aspect" || arg == "-a") {
283       if(i+1 >= argc) {
284         print_usage(argv[0]);
285         throw std::runtime_error("Need to specify a parameter for aspect switch");
286       }
287       if(strcasecmp(argv[i+1], "auto") == 0) {
288         i++;
289         config->aspect_ratio = -1;
290       } else {
291         int aspect_width, aspect_height;
292         if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
293           print_usage(argv[0]);
294           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
295         }
296         config->aspect_ratio = static_cast<double>(aspect_width) /
297                                static_cast<double>(aspect_height);
298       }
299     } else if(arg == "--show-fps") {
300       config->show_fps = true;
301     } else if(arg == "--no-show-fps") {
302       config->show_fps = false;
303     } else if(arg == "--console") {
304       config->console_enabled = true;
305     } else if(arg == "--noconsole") {
306       config->console_enabled = false;
307     } else if(arg == "--disable-sfx") {
308       config->sound_enabled = false;
309     } else if(arg == "--disable-music") {
310       config->music_enabled = false;
311     } else if(arg == "--play-demo") {
312       if(i+1 >= argc) {
313         print_usage(argv[0]);
314         throw std::runtime_error("Need to specify a demo filename");
315       }
316       config->start_demo = argv[++i];
317     } else if(arg == "--record-demo") {
318       if(i+1 >= argc) {
319         print_usage(argv[0]);
320         throw std::runtime_error("Need to specify a demo filename");
321       }
322       config->record_demo = argv[++i];
323     } else if(arg == "-d") {
324       config->enable_script_debugger = true;
325     } else if(arg[0] != '-') {
326       config->start_level = arg;
327     } else {
328       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
329       return true;
330     }
331   }
332
333   return false;
334 }
335
336 static void init_sdl()
337 {
338   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
339     std::stringstream msg;
340     msg << "Couldn't initialize SDL: " << SDL_GetError();
341     throw std::runtime_error(msg.str());
342   }
343   // just to be sure
344   atexit(SDL_Quit);
345
346   SDL_EnableUNICODE(1);
347
348   // wait 100ms and clear SDL event queue because sometimes we have random
349   // joystick events in the queue on startup...
350   SDL_Delay(100);
351   SDL_Event dummy;
352   while(SDL_PollEvent(&dummy))
353       ;
354 }
355
356 static void init_rand()
357 {
358   config->random_seed = systemRandom.srand(config->random_seed);
359
360   //const char *how = config->random_seed? ", user fixed.": ", from time().";
361   //log_info << "Using random seed " << config->random_seed << how << std::endl;
362 }
363
364 void init_video()
365 {
366   static int desktop_width = 0;
367   static int desktop_height = 0;
368
369 /* unfortunately only newer SDLs have these infos */
370 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
371   /* find which resolution the user normally uses */
372   if(desktop_width == 0) {
373     const SDL_VideoInfo *info = SDL_GetVideoInfo();
374     desktop_width  = info->current_w;
375     desktop_height = info->current_h;
376   }
377 #endif
378
379   double aspect_ratio = config->aspect_ratio;
380
381   // try to guess aspect ratio of monitor if needed
382   if (aspect_ratio <= 0) {
383     if(config->use_fullscreen && desktop_width > 0) {
384       aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
385     } else {
386       aspect_ratio = 4.0 / 3.0;
387     }
388   }
389
390   // use aspect ratio to calculate logical resolution
391   if (aspect_ratio > 1) {
392     SCREEN_WIDTH  = static_cast<int> (600 * aspect_ratio + 0.5);
393     SCREEN_HEIGHT = 600;
394   } else {
395     SCREEN_WIDTH  = 600;
396     SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
397   }
398
399   context_pointer->init_renderer();
400   screen = SDL_GetVideoSurface();
401
402   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
403
404   // set icon
405   SDL_Surface* icon = IMG_Load_RW(
406       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
407   if(icon != 0) {
408     SDL_WM_SetIcon(icon, 0);
409     SDL_FreeSurface(icon);
410   }
411 #ifdef DEBUG
412   else {
413     log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
414   }
415 #endif
416
417   SDL_ShowCursor(0);
418
419   log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
420 }
421
422 static void init_audio()
423 {
424   sound_manager = new SoundManager();
425
426   sound_manager->enable_sound(config->sound_enabled);
427   sound_manager->enable_music(config->music_enabled);
428 }
429
430 static void quit_audio()
431 {
432   if(sound_manager != NULL) {
433     delete sound_manager;
434     sound_manager = NULL;
435   }
436 }
437
438 void wait_for_event(float min_delay, float max_delay)
439 {
440   assert(min_delay <= max_delay);
441
442   Uint32 min = (Uint32) (min_delay * 1000);
443   Uint32 max = (Uint32) (max_delay * 1000);
444
445   Uint32 ticks = SDL_GetTicks();
446   while(SDL_GetTicks() - ticks < min) {
447     SDL_Delay(10);
448     sound_manager->update();
449   }
450
451   // clear event queue
452   SDL_Event event;
453   while (SDL_PollEvent(&event))
454   {}
455
456   /* Handle events: */
457   bool running = false;
458   ticks = SDL_GetTicks();
459   while(running) {
460     while(SDL_PollEvent(&event)) {
461       switch(event.type) {
462         case SDL_QUIT:
463           main_loop->quit();
464           break;
465         case SDL_KEYDOWN:
466         case SDL_JOYBUTTONDOWN:
467         case SDL_MOUSEBUTTONDOWN:
468           running = false;
469       }
470     }
471     if(SDL_GetTicks() - ticks >= (max - min))
472       running = false;
473     sound_manager->update();
474     SDL_Delay(10);
475   }
476 }
477
478 #ifdef DEBUG
479 static Uint32 last_timelog_ticks = 0;
480 static const char* last_timelog_component = 0;
481
482 static inline void timelog(const char* component)
483 {
484   Uint32 current_ticks = SDL_GetTicks();
485
486   if(last_timelog_component != 0) {
487     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
488   }
489
490   last_timelog_ticks = current_ticks;
491   last_timelog_component = component;
492 }
493 #else
494 static inline void timelog(const char* )
495 {
496 }
497 #endif
498
499 int main(int argc, char** argv)
500 {
501   int result = 0;
502
503 #ifndef NO_CATCH
504   try {
505 #endif
506
507     if(pre_parse_commandline(argc, argv))
508       return 0;
509
510     Console::instance = new Console();
511     init_physfs(argv[0]);
512     init_sdl();
513
514     timelog("controller");
515     main_controller = new JoystickKeyboardController();
516     timelog("config");
517     init_config();
518     timelog("tinygettext");
519     init_tinygettext();
520     timelog("commandline");
521     if(parse_commandline(argc, argv))
522       return 0;
523     timelog("audio");
524     init_audio();
525     timelog("video");
526     DrawingContext context;
527     context_pointer = &context;
528     init_video();
529     Console::instance->init_graphics();
530     timelog("scripting");
531     Scripting::init_squirrel(config->enable_script_debugger);
532     timelog("resources");
533     load_shared();
534     timelog(0);
535
536     main_loop = new MainLoop();
537     if(config->start_level != "") {
538       // we have a normal path specified at commandline not physfs paths.
539       // So we simply mount that path here...
540       std::string dir = FileSystem::dirname(config->start_level);
541       PHYSFS_addToSearchPath(dir.c_str(), true);
542
543       if(config->start_level.size() > 4 &&
544               config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
545           init_rand();
546           main_loop->push_screen(new WorldMapNS::WorldMap(
547                       FileSystem::basename(config->start_level)));
548       } else {
549         init_rand();//If level uses random eg. for
550         // rain particles before we do this:
551         std::auto_ptr<GameSession> session (
552                 new GameSession(FileSystem::basename(config->start_level)));
553
554         config->random_seed =session->get_demo_random_seed(config->start_demo);
555         init_rand();//initialise generator with seed from session
556
557         if(config->start_demo != "")
558           session->play_demo(config->start_demo);
559
560         if(config->record_demo != "")
561           session->record_demo(config->record_demo);
562         main_loop->push_screen(session.release());
563       }
564     } else {
565       init_rand();
566       main_loop->push_screen(new TitleScreen());
567     }
568
569     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
570     main_loop->run(context);
571 #ifndef NO_CATCH
572   } catch(std::exception& e) {
573     log_fatal << "Unexpected exception: " << e.what() << std::endl;
574     result = 1;
575   } catch(...) {
576     log_fatal << "Unexpected exception" << std::endl;
577     result = 1;
578   }
579 #endif
580
581   delete main_loop;
582   main_loop = NULL;
583
584   free_options_menu();
585   unload_shared();
586   quit_audio();
587
588   if(config)
589     config->save();
590   delete config;
591   config = NULL;
592   delete main_controller;
593   main_controller = NULL;
594   delete Console::instance;
595   Console::instance = NULL;
596   Scripting::exit_squirrel();
597   delete texture_manager;
598   texture_manager = NULL;
599   SDL_Quit();
600   PHYSFS_deinit();
601
602   return result;
603 }