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