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