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