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