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