Added menu option to select language
[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 #include <GL/gl.h>
37
38 #include "gameconfig.hpp"
39 #include "resources.hpp"
40 #include "gettext.hpp"
41 #include "audio/sound_manager.hpp"
42 #include "video/surface.hpp"
43 #include "video/texture_manager.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 SDL_Surface* screen = 0;
59 JoystickKeyboardController* main_controller = 0;
60 TinyGetText::DictionaryManager dictionary_manager;
61
62 int SCREEN_WIDTH;
63 int SCREEN_HEIGHT;
64
65 static void init_config()
66 {
67   config = new Config();
68   try {
69     config->load();
70   } catch(std::exception& e) {
71     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
72   }
73 }
74
75 static void init_tinygettext()
76 {
77   dictionary_manager.add_directory("locale");
78   dictionary_manager.set_charset("UTF-8");
79
80   // Config setting "locale" overrides language detection
81   if (config->locale != "") {
82     dictionary_manager.set_language( config->locale );
83   }
84 }
85
86 static void 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   // Initialize physfs (this is a slightly modified version of
95   // PHYSFS_setSaneConfig
96   const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
97   const char* userdir = PHYSFS_getUserDir();
98   const char* dirsep = PHYSFS_getDirSeparator();
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   // Search for archives and add them to the search path
129   const char* archiveExt = "zip";
130   char** rc = PHYSFS_enumerateFiles("/");
131   size_t extlen = strlen(archiveExt);
132
133   for(char** i = rc; *i != 0; ++i) {
134     size_t l = strlen(*i);
135     if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
136       const char* ext = (*i) + (l - extlen);
137       if(strcasecmp(ext, archiveExt) == 0) {
138         const char* d = PHYSFS_getRealDir(*i);
139         char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
140         sprintf(str, "%s%s%s", d, dirsep, *i);
141         PHYSFS_addToSearchPath(str, 1);
142         delete[] str;
143       }
144     }
145   }
146
147   PHYSFS_freeList(rc);
148
149   // when started from source dir...
150   std::string dir = PHYSFS_getBaseDir();
151   dir += "/data";
152   std::string testfname = dir;
153   testfname += "/credits.txt";
154   bool sourcedir = false;
155   FILE* f = fopen(testfname.c_str(), "r");
156   if(f) {
157     fclose(f);
158     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
159       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
160     } else {
161       sourcedir = true;
162     }
163   }
164
165 #ifdef MACOSX
166   // when started from Application file on Mac OS X...
167   dir = PHYSFS_getBaseDir();
168   dir += "SuperTux.app/Contents/Resources/data";
169   testfname = dir + "/credits.txt";
170   sourcedir = false;
171   f = fopen(testfname.c_str(), "r");
172   if(f) {
173     fclose(f);
174     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
175       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
176     } else {
177       sourcedir = true;
178     }
179   }
180 #endif
181
182 #ifdef _WIN32
183   PHYSFS_addToSearchPath(".\\data", 1);
184 #endif
185
186   if(!sourcedir) {
187 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
188     std::string datadir;
189 #ifdef ENABLE_BINRELOC
190
191     char* dir;
192     br_init (NULL);
193     dir = br_find_data_dir(APPDATADIR);
194     datadir = dir;
195     datadir += "/" PACKAGE_NAME;
196     free(dir);
197
198 #else
199     datadir = APPDATADIR;
200 #endif
201     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
202       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
203     }
204 #endif
205   }
206
207   // allow symbolic links
208   PHYSFS_permitSymbolicLinks(1);
209
210   //show search Path
211   char** searchpath = PHYSFS_getSearchPath();
212   for(char** i = searchpath; *i != NULL; i++)
213     log_info << "[" << *i << "] is in the search path" << std::endl;
214   PHYSFS_freeList(searchpath);
215 }
216
217 static void print_usage(const char* argv0)
218 {
219   fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
220   fprintf(stderr,
221           _("Options:\n"
222             "  -f, --fullscreen             Run in fullscreen mode\n"
223             "  -w, --window                 Run in window mode\n"
224             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
225             "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
226             "  --disable-sfx                Disable sound effects\n"
227             "  --disable-music              Disable music\n"
228             "  --help                       Show this help message\n"
229             "  --version                    Display SuperTux version and quit\n"
230             "  --console                    Enable ingame scripting console\n"
231             "  --noconsole                  Disable ingame scripting console\n"
232             "  --show-fps                   Display framerate in levels\n"
233             "  --no-show-fps                Do not display framerate in levels\n"
234             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
235             "  --play-demo FILE LEVEL       Play a recorded demo\n"
236             "\n"));
237 }
238
239 /**
240  * Options that should be evaluated prior to any initializations at all go here
241  */
242 static bool pre_parse_commandline(int argc, char** argv)
243 {
244   for(int i = 1; i < argc; ++i) {
245     std::string arg = argv[i];
246
247     if(arg == "--version") {
248       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
249       return true;
250     }
251   }
252
253   return false;
254 }
255
256 /**
257  * Options that should be evaluated after config is read go here
258  */
259 static bool 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 == "--help") {
265       print_usage(argv[0]);
266       return true;
267     } else if(arg == "--fullscreen" || arg == "-f") {
268       config->use_fullscreen = true;
269     } else if(arg == "--window" || arg == "-w") {
270       config->use_fullscreen = false;
271     } else if(arg == "--geometry" || arg == "-g") {
272       if(i+1 >= argc) {
273         print_usage(argv[0]);
274         throw std::runtime_error("Need to specify a parameter for geometry switch");
275       }
276       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
277          != 2) {
278         print_usage(argv[0]);
279         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
280       }
281     } else if(arg == "--aspect" || arg == "-a") {
282       if(i+1 >= argc) {
283         print_usage(argv[0]);
284         throw std::runtime_error("Need to specify a parameter for aspect switch");
285       }
286       if(strcasecmp(argv[i+1], "auto") == 0) {
287         i++;
288         config->aspect_ratio = -1;
289       } else {
290         int aspect_width, aspect_height;
291         if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
292           print_usage(argv[0]);
293           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
294         }
295         config->aspect_ratio = static_cast<double>(aspect_width) /
296                                static_cast<double>(aspect_height);
297       }
298     } else if(arg == "--show-fps") {
299       config->show_fps = true;
300     } else if(arg == "--no-show-fps") {
301       config->show_fps = false;
302     } else if(arg == "--console") {
303       config->console_enabled = true;
304     } else if(arg == "--noconsole") {
305       config->console_enabled = false;
306     } else if(arg == "--disable-sfx") {
307       config->sound_enabled = false;
308     } else if(arg == "--disable-music") {
309       config->music_enabled = false;
310     } else if(arg == "--play-demo") {
311       if(i+1 >= argc) {
312         print_usage(argv[0]);
313         throw std::runtime_error("Need to specify a demo filename");
314       }
315       config->start_demo = argv[++i];
316     } else if(arg == "--record-demo") {
317       if(i+1 >= argc) {
318         print_usage(argv[0]);
319         throw std::runtime_error("Need to specify a demo filename");
320       }
321       config->record_demo = argv[++i];
322     } else if(arg == "-d") {
323       config->enable_script_debugger = true;
324     } else if(arg[0] != '-') {
325       config->start_level = arg;
326     } else {
327       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
328       return true;
329     }
330   }
331
332   return false;
333 }
334
335 static void init_sdl()
336 {
337   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
338     std::stringstream msg;
339     msg << "Couldn't initialize SDL: " << SDL_GetError();
340     throw std::runtime_error(msg.str());
341   }
342   // just to be sure
343   atexit(SDL_Quit);
344
345   SDL_EnableUNICODE(1);
346
347   // wait 100ms and clear SDL event queue because sometimes we have random
348   // joystick events in the queue on startup...
349   SDL_Delay(100);
350   SDL_Event dummy;
351   while(SDL_PollEvent(&dummy))
352       ;
353 }
354
355 static void init_rand()
356 {
357   config->random_seed = systemRandom.srand(config->random_seed);
358
359   //const char *how = config->random_seed? ", user fixed.": ", from time().";
360   //log_info << "Using random seed " << config->random_seed << how << std::endl;
361 }
362
363 void init_video()
364 {
365   static int desktop_width = 0;
366   static int desktop_height = 0;
367
368   if(texture_manager != NULL)
369     texture_manager->save_textures();
370
371 /* unfortunately only newer SDLs have these infos */
372 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
373   /* find which resolution the user normally uses */
374   if(desktop_width == 0) {
375     const SDL_VideoInfo *info = SDL_GetVideoInfo();
376     desktop_width  = info->current_w;
377     desktop_height = info->current_h;
378   }
379
380   if(config->try_vsync) {
381     /* we want vsync for smooth scrolling */
382         SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 1);
383   }
384 #endif
385
386   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
387   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
388   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
389   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
390
391   int flags = SDL_OPENGL;
392   if(config->use_fullscreen)
393     flags |= SDL_FULLSCREEN;
394   int width = config->screenwidth;
395   int height = config->screenheight;
396   int bpp = 0;
397
398   screen = SDL_SetVideoMode(width, height, bpp, flags);
399   if(screen == 0) {
400     std::stringstream msg;
401     msg << "Couldn't set video mode (" << width << "x" << height
402         << "-" << bpp << "bpp): " << SDL_GetError();
403     throw std::runtime_error(msg.str());
404   }
405
406   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
407
408   // set icon
409   SDL_Surface* icon = IMG_Load_RW(
410       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
411   if(icon != 0) {
412     SDL_WM_SetIcon(icon, 0);
413     SDL_FreeSurface(icon);
414   }
415 #ifdef DEBUG
416   else {
417     log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
418   }
419 #endif
420
421   SDL_ShowCursor(0);
422
423   double aspect_ratio = config->aspect_ratio;
424
425   // try to guess aspect ratio of monitor if needed
426   if (aspect_ratio <= 0) {
427     if(config->use_fullscreen && desktop_width > 0) {
428       aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
429     } else {
430       aspect_ratio = 4.0 / 3.0;
431     }
432   }
433
434   // use aspect ratio to calculate logical resolution
435   if (aspect_ratio > 1) {
436     SCREEN_WIDTH  = static_cast<int> (600 * aspect_ratio + 0.5);
437     SCREEN_HEIGHT = 600;
438   } else {
439     SCREEN_WIDTH  = 600;
440     SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
441   }
442
443   log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
444
445   // setup opengl state and transform
446   glDisable(GL_DEPTH_TEST);
447   glDisable(GL_CULL_FACE);
448   glEnable(GL_TEXTURE_2D);
449   glEnable(GL_BLEND);
450   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
451
452   glViewport(0, 0, screen->w, screen->h);
453   glMatrixMode(GL_PROJECTION);
454   glLoadIdentity();
455   // logical resolution here not real monitor resolution
456   glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1.0, 1.0);
457   glMatrixMode(GL_MODELVIEW);
458   glLoadIdentity();
459   glTranslatef(0, 0, 0);
460
461   check_gl_error("Setting up view matrices");
462
463   if(texture_manager != NULL)
464     texture_manager->reload_textures();
465   else
466     texture_manager = new TextureManager();
467 }
468
469 static void init_audio()
470 {
471   sound_manager = new SoundManager();
472
473   sound_manager->enable_sound(config->sound_enabled);
474   sound_manager->enable_music(config->music_enabled);
475 }
476
477 static void quit_audio()
478 {
479   if(sound_manager != NULL) {
480     delete sound_manager;
481     sound_manager = NULL;
482   }
483 }
484
485 void wait_for_event(float min_delay, float max_delay)
486 {
487   assert(min_delay <= max_delay);
488
489   Uint32 min = (Uint32) (min_delay * 1000);
490   Uint32 max = (Uint32) (max_delay * 1000);
491
492   Uint32 ticks = SDL_GetTicks();
493   while(SDL_GetTicks() - ticks < min) {
494     SDL_Delay(10);
495     sound_manager->update();
496   }
497
498   // clear event queue
499   SDL_Event event;
500   while (SDL_PollEvent(&event))
501   {}
502
503   /* Handle events: */
504   bool running = false;
505   ticks = SDL_GetTicks();
506   while(running) {
507     while(SDL_PollEvent(&event)) {
508       switch(event.type) {
509         case SDL_QUIT:
510           main_loop->quit();
511           break;
512         case SDL_KEYDOWN:
513         case SDL_JOYBUTTONDOWN:
514         case SDL_MOUSEBUTTONDOWN:
515           running = false;
516       }
517     }
518     if(SDL_GetTicks() - ticks >= (max - min))
519       running = false;
520     sound_manager->update();
521     SDL_Delay(10);
522   }
523 }
524
525 #ifdef DEBUG
526 static Uint32 last_timelog_ticks = 0;
527 static const char* last_timelog_component = 0;
528
529 static inline void timelog(const char* component)
530 {
531   Uint32 current_ticks = SDL_GetTicks();
532
533   if(last_timelog_component != 0) {
534     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
535   }
536
537   last_timelog_ticks = current_ticks;
538   last_timelog_component = component;
539 }
540 #else
541 static inline void timelog(const char* )
542 {
543 }
544 #endif
545
546 int main(int argc, char** argv)
547 {
548   int result = 0;
549
550 #ifndef NO_CATCH
551   try {
552 #endif
553
554     if(pre_parse_commandline(argc, argv))
555       return 0;
556
557     Console::instance = new Console();
558     init_physfs(argv[0]);
559     init_sdl();
560
561     timelog("controller");
562     main_controller = new JoystickKeyboardController();
563     timelog("config");
564     init_config();
565     timelog("tinygettext");
566     init_tinygettext();
567     timelog("commandline");
568     if(parse_commandline(argc, argv))
569       return 0;
570     timelog("audio");
571     init_audio();
572     timelog("video");
573     init_video();
574     Console::instance->init_graphics();
575     timelog("scripting");
576     Scripting::init_squirrel(config->enable_script_debugger);
577     timelog("resources");
578     load_shared();
579     timelog(0);
580
581     main_loop = new MainLoop();
582     if(config->start_level != "") {
583       // we have a normal path specified at commandline not physfs paths.
584       // So we simply mount that path here...
585       std::string dir = FileSystem::dirname(config->start_level);
586       PHYSFS_addToSearchPath(dir.c_str(), true);
587
588       if(config->start_level.size() > 4 &&
589               config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
590           init_rand();
591           main_loop->push_screen(new WorldMapNS::WorldMap(
592                       FileSystem::basename(config->start_level)));
593       } else {
594         init_rand();//If level uses random eg. for
595         // rain particles before we do this:
596         std::auto_ptr<GameSession> session (
597                 new GameSession(FileSystem::basename(config->start_level)));
598
599         config->random_seed =session->get_demo_random_seed(config->start_demo);
600         init_rand();//initialise generator with seed from session
601
602         if(config->start_demo != "")
603           session->play_demo(config->start_demo);
604
605         if(config->record_demo != "")
606           session->record_demo(config->record_demo);
607         main_loop->push_screen(session.release());
608       }
609     } else {
610       init_rand();
611       main_loop->push_screen(new TitleScreen());
612     }
613
614     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
615     main_loop->run();
616 #ifndef NO_CATCH
617   } catch(std::exception& e) {
618     log_fatal << "Unexpected exception: " << e.what() << std::endl;
619     result = 1;
620   } catch(...) {
621     log_fatal << "Unexpected exception" << std::endl;
622     result = 1;
623   }
624 #endif
625
626   delete main_loop;
627   main_loop = NULL;
628
629   free_options_menu();
630   unload_shared();
631   quit_audio();
632
633   if(config)
634     config->save();
635   delete config;
636   config = NULL;
637   delete main_controller;
638   main_controller = NULL;
639   delete Console::instance;
640   Console::instance = NULL;
641   Scripting::exit_squirrel();
642   delete texture_manager;
643   texture_manager = NULL;
644   SDL_Quit();
645   PHYSFS_deinit();
646
647   return result;
648 }