4 // Copyright (C) 2005 Matthias Braun <matze@braunis.de>
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.
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.
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
31 #include <sys/types.h>
39 #include <SDL_mixer.h>
40 #include <SDL_image.h>
41 #include <SDL_opengl.h>
43 #include "gameconfig.h"
44 #include "resources.h"
46 #include "audio/sound_manager.h"
47 #include "video/surface.h"
48 #include "control/joystickkeyboardcontroller.h"
51 #include "game_session.h"
52 #include "file_system.h"
55 #define mkdir(dir, mode) mkdir(dir)
58 SDL_Surface* screen = 0;
59 JoystickKeyboardController* main_controller = 0;
60 TinyGetText::DictionaryManager dictionary_manager;
62 static void init_config()
64 config = new Config();
67 } catch(std::exception& e) {
69 std::cerr << "Couldn't load config file: " << e.what() << "\n";
74 static void find_directories()
76 const char* home = getenv("HOME");
79 std::cerr << "Couldn't find home directory.\n";
85 user_dir += "/.supertux";
88 std::string savedir = user_dir + "/save";
89 mkdir(user_dir.c_str(), 0755);
90 mkdir(savedir.c_str(), 0755);
92 // try current directory as datadir
94 if(FileSystem::faccessible("./data/credits.txt")) {
99 // Detect datadir with some linux magic
100 if(datadir.empty()) {
101 char exe_file[PATH_MAX];
103 strcpy(exe_file, ".");
105 if(readlink("/proc/self/exe", exe_file, PATH_MAX) < 0) {
107 std::cerr << "Couldn't read /proc/self/exe \n";
109 strcpy(exe_file, ".");
112 std::string exedir = std::string(dirname(exe_file)) + "/";
113 std::string testdir = exedir + "./data/";
114 if(access(testdir.c_str(), F_OK) == 0) {
118 testdir = exedir + "../share/supertux/";
119 if(datadir.empty() && access(testdir.c_str(), F_OK) == 0) {
125 // use default location
126 if(datadir.empty()) {
127 datadir = DATA_PREFIX;
132 throw std::runtime_error("Couldn't find datadir");
135 static void init_tinygettext()
137 dictionary_manager.add_directory(datadir + "/locale");
138 dictionary_manager.set_charset("UTF-8");
141 static void print_usage(const char* argv0)
143 fprintf(stderr, _("Usage: %s [OPTIONS] LEVELFILE\n\n"), argv0);
146 " -f, --fullscreen Run in fullscreen mode.\n"
147 " -w, --window Run in window mode.\n"
148 " -g, --geometry WIDTHxHEIGHT Run SuperTux in give resolution\n"
149 " --help Show this help message\n"
150 " --version Display SuperTux version and quit\n"
154 static void parse_commandline(int argc, char** argv)
156 for(int i = 1; i < argc; ++i) {
157 std::string arg = argv[i];
159 if(arg == "--fullscreen" || arg == "-f") {
160 config->use_fullscreen = true;
161 } else if(arg == "--window" || arg == "-w") {
162 config->use_fullscreen = false;
163 } else if(arg == "--geometry" || arg == "-g") {
165 print_usage(argv[0]);
166 throw std::runtime_error("Need to specify a parameter for geometry switch");
168 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
170 print_usage(argv[0]);
171 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
173 } else if(arg == "--show-fps") {
174 config->show_fps = true;
175 } else if(arg == "--play-demo") {
177 print_usage(argv[0]);
178 throw std::runtime_error("Need to specify a demo filename");
180 config->start_demo = argv[++i];
181 } else if(arg == "--record-demo") {
183 print_usage(argv[0]);
184 throw std::runtime_error("Need to specify a demo filename");
186 config->record_demo = argv[++i];
187 } else if(arg == "--help") {
188 print_usage(argv[0]);
189 throw std::runtime_error("");
190 } else if(arg == "--version") {
191 std::cerr << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n";
192 throw std::runtime_error("");
193 } else if(arg[0] != '-') {
194 config->start_level = arg;
196 std::cerr << "Unknown option '" << arg << "'.\n";
197 std::cerr << "Use --help to see a list of options.\n";
201 // TODO joystick switchyes...
204 static void init_sdl()
206 if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
207 std::stringstream msg;
208 msg << "Couldn't initialize SDL: " << SDL_GetError();
209 throw std::runtime_error(msg.str());
212 SDL_EnableUNICODE(1);
214 // wait 100ms and clear SDL event queue because sometimes we have random
215 // joystick events in the queue on startup...
218 while(SDL_PollEvent(&dummy))
222 static void check_gl_error()
224 GLenum glerror = glGetError();
225 std::string errormsg;
227 if(glerror != GL_NO_ERROR) {
229 case GL_INVALID_ENUM:
230 errormsg = "Invalid enumeration value";
232 case GL_INVALID_VALUE:
233 errormsg = "Numeric argzment out of range";
235 case GL_INVALID_OPERATION:
236 errormsg = "Invalid operation";
238 case GL_STACK_OVERFLOW:
239 errormsg = "stack overflow";
241 case GL_STACK_UNDERFLOW:
242 errormsg = "stack underflow";
244 case GL_OUT_OF_MEMORY:
245 errormsg = "out of memory";
247 case GL_TABLE_TOO_LARGE:
248 errormsg = "table too large";
251 errormsg = "unknown error number";
254 std::stringstream msg;
255 msg << "OpenGL Error: " << errormsg;
256 throw std::runtime_error(msg.str());
262 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
263 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
264 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
265 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
267 int flags = SDL_OPENGL;
268 if(config->use_fullscreen)
269 flags |= SDL_FULLSCREEN;
270 int width = config->screenwidth;
271 int height = config->screenheight;
274 screen = SDL_SetVideoMode(width, height, bpp, flags);
276 std::stringstream msg;
277 msg << "Couldn't set video mode (" << width << "x" << height
278 << "-" << bpp << "bpp): " << SDL_GetError();
279 throw std::runtime_error(msg.str());
282 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
285 SDL_Surface* icon = IMG_Load(
286 get_resource_filename("images/engine/icons/supertux.xpm").c_str());
288 SDL_WM_SetIcon(icon, 0);
289 SDL_FreeSurface(icon);
293 std::cerr << "Warning: Couldn't find icon 'images/engine/icons/supertux.xpm'.\n";
297 // setup opengl state and transform
298 glDisable(GL_DEPTH_TEST);
299 glDisable(GL_CULL_FACE);
301 glViewport(0, 0, screen->w, screen->h);
302 glMatrixMode(GL_PROJECTION);
304 // logical resolution here not real monitor resolution
305 glOrtho(0, 800, 600, 0, -1.0, 1.0);
306 glMatrixMode(GL_MODELVIEW);
308 glTranslatef(0, 0, 0);
312 Surface::reload_all();
315 static void init_audio()
317 sound_manager = new SoundManager();
319 int format = MIX_DEFAULT_FORMAT;
320 if(Mix_OpenAudio(config->audio_frequency, format, config->audio_channels,
321 config->audio_chunksize) < 0) {
322 std::cerr << "Couldn't initialize audio ("
323 << config->audio_frequency << "HZ, " << config->audio_channels
324 << " Channels, Format " << format << ", ChunkSize "
325 << config->audio_chunksize << "): " << SDL_GetError() << "\n";
328 sound_manager->set_audio_device_available(true);
329 sound_manager->enable_sound(config->sound_enabled);
330 sound_manager->enable_music(config->music_enabled);
332 if(Mix_AllocateChannels(config->audio_voices) < 0) {
333 std::cerr << "Couldn't allocate '" << config->audio_voices << "' audio voices: "
334 << SDL_GetError() << "\n";
339 static void quit_audio()
342 if(sound_manager->audio_device_available())
345 delete sound_manager;
350 void wait_for_event(float min_delay, float max_delay)
352 assert(min_delay <= max_delay);
354 Uint32 min = (Uint32) (min_delay * 1000);
355 Uint32 max = (Uint32) (max_delay * 1000);
361 while (SDL_PollEvent(&event))
365 bool running = false;
366 Uint32 ticks = SDL_GetTicks();
368 while(SDL_PollEvent(&event)) {
371 throw std::runtime_error("received window close");
373 case SDL_JOYBUTTONDOWN:
374 case SDL_MOUSEBUTTONDOWN:
378 if(SDL_GetTicks() - ticks >= (max - min))
384 int main(int argc, char** argv)
386 #ifndef DEBUG // we want backtraces in debug mode so don't catch exceptions
391 main_controller = new JoystickKeyboardController();
395 parse_commandline(argc, argv);
401 if(config->start_level != "") {
402 GameSession session(config->start_level, ST_GL_LOAD_LEVEL_FILE);
403 if(config->start_demo != "")
404 session.play_demo(config->start_demo);
405 if(config->record_demo != "")
406 session.record_demo(config->record_demo);
414 } catch(std::exception& e) {
415 std::cerr << "Unexpected exception: " << e.what() << std::endl;
418 std::cerr << "Unexpected exception." << std::endl;
426 Surface::debug_check();
433 delete main_controller;