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