fixed missing include assert
[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 "main.h"
24
25 #include <stdexcept>
26 #include <iostream>
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 #ifndef WIN32
35 #include <libgen.h>
36 #endif
37 #include <SDL.h>
38 #include <SDL_mixer.h>
39 #include <SDL_image.h>
40 #include <SDL_opengl.h>
41
42 #include "gameconfig.h"
43 #include "resources.h"
44 #include "gettext.h"
45 #include "audio/sound_manager.h"
46 #include "video/surface.h"
47 #include "control/joystickkeyboardcontroller.h"
48 #include "misc.h"
49 #include "title.h"
50 #include "game_session.h"
51 #include "file_system.h"
52
53 SDL_Surface* screen = 0;
54 JoystickKeyboardController* main_controller = 0;
55 TinyGetText::DictionaryManager dictionary_manager;
56
57 static void init_config()
58 {
59   config = new Config();
60   try {
61     config->load();
62   } catch(std::exception& e) {
63 #ifdef DEBUG
64     std::cerr << "Couldn't load config file: " << e.what() << "\n";
65 #endif
66   }
67 }
68
69 static void find_directories()
70 {
71   const char* home = getenv("HOME");
72   if(home == 0) {
73 #ifdef DEBUG
74     std::cerr << "Couldn't find home directory.\n";
75 #endif
76     home = ".";
77   }
78
79   user_dir = home;
80   user_dir += "/.supertux";
81
82   // create directories
83   std::string savedir = user_dir + "/save";
84   mkdir(user_dir.c_str(), 0755);
85   mkdir(savedir.c_str(), 0755);
86
87   // try current directory as datadir
88   if(datadir.empty()) {
89     if(FileSystem::faccessible("./data/credits.txt")) {
90       datadir = "./data/";
91     }
92   }
93
94   // Detect datadir with some linux magic
95 #ifndef WIN32
96   if(datadir.empty()) {
97     char exe_file[PATH_MAX];
98     if(readlink("/proc/self/exe", exe_file, PATH_MAX) < 0) {
99 #ifdef DEBUG
100       std::cerr << "Couldn't read /proc/self/exe \n";
101 #endif
102     } else {
103       std::string exedir = std::string(dirname(exe_file)) + "/";
104       std::string testdir = exedir + "./data/";
105       if(access(testdir.c_str(), F_OK) == 0) {
106         datadir = testdir;
107       }
108       
109       testdir = exedir + "../share/supertux/";
110       if(datadir.empty() && access(testdir.c_str(), F_OK) == 0) {
111         datadir = testdir;
112       }
113     }  
114   }
115 #endif
116   
117 #ifdef DATA_PREFIX
118   // use default location
119   if(datadir.empty()) {
120     datadir = DATA_PREFIX;
121   }
122 #endif
123
124   if(datadir.empty())
125     throw std::runtime_error("Couldn't find datadir");
126 }
127
128 static void init_tinygettext()
129 {
130   dictionary_manager.add_directory(datadir + "/locale");
131   dictionary_manager.set_charset("iso8859-1");
132 }
133
134 static void print_usage(const char* argv0)
135 {
136   fprintf(stderr, _("Usage: %s [OPTIONS] LEVELFILE\n\n"), argv0);
137   fprintf(stderr,
138           _("Options:\n"
139             "  -f, --fullscreen             Run in fullscreen mode.\n"
140             "  -w, --window                 Run in window mode.\n"
141             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in give resolution\n"
142             "  --help                       Show this help message\n"
143             "  --version                    Display SuperTux version and quit\n"
144             "\n"));
145 }
146
147 static void parse_commandline(int argc, char** argv)
148 {
149   for(int i = 1; i < argc; ++i) {
150     std::string arg = argv[i];
151
152     if(arg == "--fullscreen" || arg == "-f") {
153       config->use_fullscreen = true;
154     } else if(arg == "--window" || arg == "-w") {
155       config->use_fullscreen = false;
156     } else if(arg == "--geometry" || arg == "-g") {
157       if(i+1 >= argc) {
158         print_usage(argv[0]);
159         throw std::runtime_error("Need to specify a parameter for geometry switch");
160       }
161       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
162          != 2) {
163         print_usage(argv[0]);
164         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
165       }
166     } else if(arg == "--show-fps") {
167       config->show_fps = true;
168     } else if(arg == "--play-demo") {
169       if(i+1 >= argc) {
170         print_usage(argv[0]);
171         throw std::runtime_error("Need to specify a demo filename");
172       }
173       config->start_demo = argv[++i];
174     } else if(arg == "--record-demo") {
175       if(i+1 >= argc) {
176         print_usage(argv[0]);
177         throw std::runtime_error("Need to specify a demo filename");
178       }
179       config->record_demo = argv[++i];
180     } else if(arg == "--help") {
181       print_usage(argv[0]);
182       throw std::runtime_error("");
183     } else if(arg == "--version") {
184       std::cerr << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n";
185       throw std::runtime_error("");
186     } else if(arg[0] != '-') {
187       config->start_level = arg;
188     } else {
189       std::cerr << "Unknown option '" << arg << "'.\n";
190       std::cerr << "Use --help to see a list of options.\n";
191     }
192   }
193
194   // TODO joystick switchyes...
195 }
196
197 static void init_sdl()
198 {
199   if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
200     std::stringstream msg;
201     msg << "Couldn't initialize SDL: " << SDL_GetError();
202     throw std::runtime_error(msg.str());
203   }
204
205   SDL_EnableUNICODE(1);
206
207   // wait 100ms and clear SDL event queue because sometimes we have random
208   // joystick events in the queue on startup...
209   SDL_Delay(100);
210   SDL_Event dummy;
211   while(SDL_PollEvent(&dummy))
212       ;
213 }
214
215 static void check_gl_error()
216 {
217   GLenum glerror = glGetError();
218   std::string errormsg;
219   
220   if(glerror != GL_NO_ERROR) {
221     switch(glerror) {
222       case GL_INVALID_ENUM:
223         errormsg = "Invalid enumeration value";
224         break;
225       case GL_INVALID_VALUE:
226         errormsg = "Numeric argzment out of range";
227         break;
228       case GL_INVALID_OPERATION:
229         errormsg = "Invalid operation";
230         break;
231       case GL_STACK_OVERFLOW:
232         errormsg = "stack overflow";
233         break;
234       case GL_STACK_UNDERFLOW:
235         errormsg = "stack underflow";
236         break;
237       case GL_OUT_OF_MEMORY:
238         errormsg = "out of memory";
239         break;
240       case GL_TABLE_TOO_LARGE:
241         errormsg = "table too large";
242         break;
243       default:
244         errormsg = "unknown error number";
245         break;
246     }
247     std::stringstream msg;
248     msg << "OpenGL Error: " << errormsg;
249     throw std::runtime_error(msg.str());
250   }
251 }
252
253 void init_video()
254 {
255   SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); 
256   SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
257   SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
258   SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
259   
260   int flags = SDL_OPENGL;
261   if(config->use_fullscreen)
262     flags |= SDL_FULLSCREEN;
263   int width = config->screenwidth;
264   int height = config->screenheight;
265   int bpp = 0;
266
267   screen = SDL_SetVideoMode(width, height, bpp, flags);
268   if(screen == 0) {
269     std::stringstream msg;
270     msg << "Couldn't set video mode (" << width << "x" << height
271         << "-" << bpp << "bpp): " << SDL_GetError();
272     throw std::runtime_error(msg.str());
273   }
274
275   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
276
277   // set icon
278   SDL_Surface* icon = IMG_Load(
279     get_resource_filename("images/supertux.xpm").c_str());
280   if(icon != 0) {
281     SDL_WM_SetIcon(icon, 0);
282     SDL_FreeSurface(icon);
283   }
284 #ifdef DEBUG
285   else {
286     std::cerr << "Warning: Couldn't find icon 'images/supertux.xpm'.\n";
287   }
288 #endif
289
290   // setup opengl state and transform
291   glDisable(GL_DEPTH_TEST);
292   glDisable(GL_CULL_FACE);
293
294   glViewport(0, 0, screen->w, screen->h);
295   glMatrixMode(GL_PROJECTION);
296   glLoadIdentity();
297   // logical resolution here not real monitor resolution
298   glOrtho(0, 800, 600, 0, -1.0, 1.0);
299   glMatrixMode(GL_MODELVIEW);
300   glLoadIdentity();
301   glTranslatef(0, 0, 0);
302
303   check_gl_error();
304
305   Surface::reload_all();
306 }
307
308 static void init_audio()
309 {
310   sound_manager = new SoundManager();
311   
312   int format = MIX_DEFAULT_FORMAT;
313   if(Mix_OpenAudio(config->audio_frequency, format, config->audio_channels,
314                    config->audio_chunksize) < 0) {
315     std::cerr << "Couldn't initialize audio ("
316               << config->audio_frequency << "HZ, " << config->audio_channels
317               << " Channels, Format " << format << ", ChunkSize "
318               << config->audio_chunksize << "): " << SDL_GetError() << "\n";
319     return;
320   }
321   sound_manager->set_audio_device_available(true);
322   sound_manager->enable_sound(config->sound_enabled);
323   sound_manager->enable_music(config->music_enabled);
324   
325   if(Mix_AllocateChannels(config->audio_voices) < 0) {
326     std::cerr << "Couldn't allocate '" << config->audio_voices << "' audio voices: "
327               << SDL_GetError() << "\n";
328     return;
329   }
330 }
331
332 static void quit_audio()
333 {
334   if(sound_manager) {
335     if(sound_manager->audio_device_available())
336       Mix_CloseAudio();
337
338     delete sound_manager;
339     sound_manager = 0;
340   }
341 }
342
343 void wait_for_event(float min_delay, float max_delay)
344 {
345   assert(min_delay <= max_delay);
346   
347   Uint32 min = (Uint32) (min_delay * 1000);
348   Uint32 max = (Uint32) (max_delay * 1000);
349
350   SDL_Delay(min);
351
352   // clear even queue
353   SDL_Event event;
354   while (SDL_PollEvent(&event))
355   {}
356
357   /* Handle events: */
358   bool running = false;
359   Uint32 ticks = SDL_GetTicks();
360   while(running) {
361     while(SDL_PollEvent(&event)) {
362       switch(event.type) {
363         case SDL_QUIT:
364           throw std::runtime_error("received window close");
365         case SDL_KEYDOWN:
366         case SDL_JOYBUTTONDOWN:
367         case SDL_MOUSEBUTTONDOWN:
368           running = false;
369       }
370     }
371     if(SDL_GetTicks() - ticks >= (max - min))
372       running = false;
373     SDL_Delay(10);
374   }
375 }
376
377 int main(int argc, char** argv) 
378 {
379 #ifndef DEBUG // we want backtraces in debug mode so don't catch exceptions
380   try {
381 #endif
382     srand(time(0));
383     init_sdl();
384     main_controller = new JoystickKeyboardController();    
385     find_directories();
386     init_config();
387     init_tinygettext();
388     parse_commandline(argc, argv);
389     init_audio();
390     init_video();
391
392     setup_menu();
393     load_shared();
394     if(config->start_level != "") {
395       GameSession session(config->start_level, ST_GL_LOAD_LEVEL_FILE);
396       if(config->start_demo != "")
397         session.play_demo(config->start_demo);
398       if(config->record_demo != "")
399         session.record_demo(config->record_demo);
400       session.run();
401     } else {
402       // normal game
403       title();
404     }    
405     
406 #ifndef DEBUG
407   } catch(std::exception& e) {
408     std::cerr << "Unexpected exception: " << e.what() << std::endl;
409     return 1;
410   } catch(...) {
411     std::cerr << "Unexpected exception." << std::endl;
412     return 1;
413   }
414 #endif
415
416   free_menu();
417   unload_shared();
418 #ifdef DEBUG
419   Surface::debug_check();
420 #endif
421   quit_audio();
422
423   if(config)
424     config->save();
425   delete config;
426   delete main_controller;
427   SDL_Quit();
428   
429   return 0;
430 }