ade5d5d8df5990ac2eb7da955adbf1ede11ade89
[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     free(dir);
197
198 #else
199     datadir = APPDATADIR;
200 #endif
201     datadir += "/";
202     datadir += application;
203     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
204       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
205     }
206 #endif
207   }
208
209   // allow symbolic links
210   PHYSFS_permitSymbolicLinks(1);
211
212   //show search Path
213   char** searchpath = PHYSFS_getSearchPath();
214   for(char** i = searchpath; *i != NULL; i++)
215     log_info << "[" << *i << "] is in the search path" << std::endl;
216   PHYSFS_freeList(searchpath);
217 }
218
219 static void print_usage(const char* argv0)
220 {
221   fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
222   fprintf(stderr,
223           _("Options:\n"
224             "  -f, --fullscreen             Run in fullscreen mode\n"
225             "  -w, --window                 Run in window mode\n"
226             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
227             "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
228             "  --disable-sfx                Disable sound effects\n"
229             "  --disable-music              Disable music\n"
230             "  --help                       Show this help message\n"
231             "  --version                    Display SuperTux version and quit\n"
232             "  --console                    Enable ingame scripting console\n"
233             "  --noconsole                  Disable ingame scripting console\n"
234             "  --show-fps                   Display framerate in levels\n"
235             "  --no-show-fps                Do not display framerate in levels\n"
236             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
237             "  --play-demo FILE LEVEL       Play a recorded demo\n"
238             "\n"));
239 }
240
241 /**
242  * Options that should be evaluated prior to any initializations at all go here
243  */
244 static bool pre_parse_commandline(int argc, char** argv)
245 {
246   for(int i = 1; i < argc; ++i) {
247     std::string arg = argv[i];
248
249     if(arg == "--version") {
250       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
251       return true;
252     }
253   }
254
255   return false;
256 }
257
258 /**
259  * Options that should be evaluated after config is read go here
260  */
261 static bool parse_commandline(int argc, char** argv)
262 {
263   for(int i = 1; i < argc; ++i) {
264     std::string arg = argv[i];
265
266     if(arg == "--help") {
267       print_usage(argv[0]);
268       return true;
269     } else if(arg == "--fullscreen" || arg == "-f") {
270       config->use_fullscreen = true;
271     } else if(arg == "--window" || arg == "-w") {
272       config->use_fullscreen = false;
273     } else if(arg == "--geometry" || arg == "-g") {
274       if(i+1 >= argc) {
275         print_usage(argv[0]);
276         throw std::runtime_error("Need to specify a parameter for geometry switch");
277       }
278       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
279          != 2) {
280         print_usage(argv[0]);
281         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
282       }
283     } else if(arg == "--aspect" || arg == "-a") {
284       if(i+1 >= argc) {
285         print_usage(argv[0]);
286         throw std::runtime_error("Need to specify a parameter for aspect switch");
287       }
288       if(strcasecmp(argv[i+1], "auto") == 0) {
289         i++;
290         config->aspect_ratio = -1;
291       } else {
292         int aspect_width, aspect_height;
293         if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
294           print_usage(argv[0]);
295           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
296         }
297         config->aspect_ratio = static_cast<double>(aspect_width) /
298                                static_cast<double>(aspect_height);
299       }
300     } else if(arg == "--show-fps") {
301       config->show_fps = true;
302     } else if(arg == "--no-show-fps") {
303       config->show_fps = false;
304     } else if(arg == "--console") {
305       config->console_enabled = true;
306     } else if(arg == "--noconsole") {
307       config->console_enabled = false;
308     } else if(arg == "--disable-sfx") {
309       config->sound_enabled = false;
310     } else if(arg == "--disable-music") {
311       config->music_enabled = false;
312     } else if(arg == "--play-demo") {
313       if(i+1 >= argc) {
314         print_usage(argv[0]);
315         throw std::runtime_error("Need to specify a demo filename");
316       }
317       config->start_demo = argv[++i];
318     } else if(arg == "--record-demo") {
319       if(i+1 >= argc) {
320         print_usage(argv[0]);
321         throw std::runtime_error("Need to specify a demo filename");
322       }
323       config->record_demo = argv[++i];
324     } else if(arg == "-d") {
325       config->enable_script_debugger = true;
326     } else if(arg[0] != '-') {
327       config->start_level = arg;
328     } else {
329       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
330       return true;
331     }
332   }
333
334   return false;
335 }
336
337 static void init_sdl()
338 {
339   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
340     std::stringstream msg;
341     msg << "Couldn't initialize SDL: " << SDL_GetError();
342     throw std::runtime_error(msg.str());
343   }
344   // just to be sure
345   atexit(SDL_Quit);
346
347   SDL_EnableUNICODE(1);
348
349   // wait 100ms and clear SDL event queue because sometimes we have random
350   // joystick events in the queue on startup...
351   SDL_Delay(100);
352   SDL_Event dummy;
353   while(SDL_PollEvent(&dummy))
354       ;
355 }
356
357 static void init_rand()
358 {
359   config->random_seed = systemRandom.srand(config->random_seed);
360
361   //const char *how = config->random_seed? ", user fixed.": ", from time().";
362   //log_info << "Using random seed " << config->random_seed << how << std::endl;
363 }
364
365 void init_video()
366 {
367   static int desktop_width = 0;
368   static int desktop_height = 0;
369
370 /* unfortunately only newer SDLs have these infos */
371 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
372   /* find which resolution the user normally uses */
373   if(desktop_width == 0) {
374     const SDL_VideoInfo *info = SDL_GetVideoInfo();
375     desktop_width  = info->current_w;
376     desktop_height = info->current_h;
377   }
378 #endif
379
380   double aspect_ratio = config->aspect_ratio;
381
382   // try to guess aspect ratio of monitor if needed
383   if (aspect_ratio <= 0) {
384     if(config->use_fullscreen && desktop_width > 0) {
385       aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
386     } else {
387       aspect_ratio = 4.0 / 3.0;
388     }
389   }
390
391   // use aspect ratio to calculate logical resolution
392   if (aspect_ratio > 1) {
393     SCREEN_WIDTH  = static_cast<int> (600 * aspect_ratio + 0.5);
394     SCREEN_HEIGHT = 600;
395   } else {
396     SCREEN_WIDTH  = 600;
397     SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
398   }
399
400   context_pointer->init_renderer();
401   screen = SDL_GetVideoSurface();
402
403   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
404
405   // set icon
406   SDL_Surface* icon = IMG_Load_RW(
407       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
408   if(icon != 0) {
409     SDL_WM_SetIcon(icon, 0);
410     SDL_FreeSurface(icon);
411   }
412 #ifdef DEBUG
413   else {
414     log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
415   }
416 #endif
417
418   SDL_ShowCursor(0);
419
420   log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
421 }
422
423 static void init_audio()
424 {
425   sound_manager = new SoundManager();
426
427   sound_manager->enable_sound(config->sound_enabled);
428   sound_manager->enable_music(config->music_enabled);
429 }
430
431 static void quit_audio()
432 {
433   if(sound_manager != NULL) {
434     delete sound_manager;
435     sound_manager = NULL;
436   }
437 }
438
439 void wait_for_event(float min_delay, float max_delay)
440 {
441   assert(min_delay <= max_delay);
442
443   Uint32 min = (Uint32) (min_delay * 1000);
444   Uint32 max = (Uint32) (max_delay * 1000);
445
446   Uint32 ticks = SDL_GetTicks();
447   while(SDL_GetTicks() - ticks < min) {
448     SDL_Delay(10);
449     sound_manager->update();
450   }
451
452   // clear event queue
453   SDL_Event event;
454   while (SDL_PollEvent(&event))
455   {}
456
457   /* Handle events: */
458   bool running = false;
459   ticks = SDL_GetTicks();
460   while(running) {
461     while(SDL_PollEvent(&event)) {
462       switch(event.type) {
463         case SDL_QUIT:
464           main_loop->quit();
465           break;
466         case SDL_KEYDOWN:
467         case SDL_JOYBUTTONDOWN:
468         case SDL_MOUSEBUTTONDOWN:
469           running = false;
470       }
471     }
472     if(SDL_GetTicks() - ticks >= (max - min))
473       running = false;
474     sound_manager->update();
475     SDL_Delay(10);
476   }
477 }
478
479 #ifdef DEBUG
480 static Uint32 last_timelog_ticks = 0;
481 static const char* last_timelog_component = 0;
482
483 static inline void timelog(const char* component)
484 {
485   Uint32 current_ticks = SDL_GetTicks();
486
487   if(last_timelog_component != 0) {
488     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
489   }
490
491   last_timelog_ticks = current_ticks;
492   last_timelog_component = component;
493 }
494 #else
495 static inline void timelog(const char* )
496 {
497 }
498 #endif
499
500 int main(int argc, char** argv)
501 {
502   int result = 0;
503
504 #ifndef NO_CATCH
505   try {
506 #endif
507
508     if(pre_parse_commandline(argc, argv))
509       return 0;
510
511     Console::instance = new Console();
512     init_physfs(argv[0]);
513     init_sdl();
514
515     timelog("controller");
516     main_controller = new JoystickKeyboardController();
517     timelog("config");
518     init_config();
519     timelog("tinygettext");
520     init_tinygettext();
521     timelog("commandline");
522     if(parse_commandline(argc, argv))
523       return 0;
524     timelog("audio");
525     init_audio();
526     timelog("video");
527     DrawingContext context;
528     context_pointer = &context;
529     init_video();
530     Console::instance->init_graphics();
531     timelog("scripting");
532     Scripting::init_squirrel(config->enable_script_debugger);
533     timelog("resources");
534     load_shared();
535     timelog(0);
536
537     main_loop = new MainLoop();
538     if(config->start_level != "") {
539       // we have a normal path specified at commandline not physfs paths.
540       // So we simply mount that path here...
541       std::string dir = FileSystem::dirname(config->start_level);
542       PHYSFS_addToSearchPath(dir.c_str(), true);
543
544       if(config->start_level.size() > 4 &&
545               config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
546           init_rand();
547           main_loop->push_screen(new WorldMapNS::WorldMap(
548                       FileSystem::basename(config->start_level)));
549       } else {
550         init_rand();//If level uses random eg. for
551         // rain particles before we do this:
552         std::auto_ptr<GameSession> session (
553                 new GameSession(FileSystem::basename(config->start_level)));
554
555         config->random_seed =session->get_demo_random_seed(config->start_demo);
556         init_rand();//initialise generator with seed from session
557
558         if(config->start_demo != "")
559           session->play_demo(config->start_demo);
560
561         if(config->record_demo != "")
562           session->record_demo(config->record_demo);
563         main_loop->push_screen(session.release());
564       }
565     } else {
566       init_rand();
567       main_loop->push_screen(new TitleScreen());
568     }
569
570     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
571     main_loop->run(context);
572 #ifndef NO_CATCH
573   } catch(std::exception& e) {
574     log_fatal << "Unexpected exception: " << e.what() << std::endl;
575     result = 1;
576   } catch(...) {
577     log_fatal << "Unexpected exception" << std::endl;
578     result = 1;
579   }
580 #endif
581
582   delete main_loop;
583   main_loop = NULL;
584
585   free_options_menu();
586   unload_shared();
587   quit_audio();
588
589   if(config)
590     config->save();
591   delete config;
592   config = NULL;
593   delete main_controller;
594   main_controller = NULL;
595   delete Console::instance;
596   Console::instance = NULL;
597   Scripting::exit_squirrel();
598   delete texture_manager;
599   texture_manager = NULL;
600   SDL_Quit();
601   PHYSFS_deinit();
602
603   return result;
604 }