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