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()) {
105 char exe_file[PATH_MAX];
106 if(readlink("/proc/self/exe", exe_file, PATH_MAX) >= 0) {
107 exedir = std::string(dirname(exe_file));
110 std::cerr << "Couldn't read /proc/self/exe \n";
115 std::string testdir = exedir + "/data/";
116 if(access(testdir.c_str(), F_OK) == 0) {
120 testdir = exedir + "/../share/supertux/";
121 if(datadir.empty() && access(testdir.c_str(), F_OK) == 0) {
127 // use default location
128 if(datadir.empty()) {
129 datadir = DATA_PREFIX;
134 throw std::runtime_error("Couldn't find datadir");
137 static void init_tinygettext()
139 dictionary_manager.add_directory(datadir + "/locale");
140 dictionary_manager.set_charset("UTF-8");
143 static void print_usage(const char* argv0)
145 fprintf(stderr, _("Usage: %s [OPTIONS] LEVELFILE\n\n"), argv0);
148 " -f, --fullscreen Run in fullscreen mode.\n"
149 " -w, --window Run in window mode.\n"
150 " -g, --geometry WIDTHxHEIGHT Run SuperTux in give resolution\n"
151 " --help Show this help message\n"
152 " --version Display SuperTux version and quit\n"
156 static void parse_commandline(int argc, char** argv)
158 for(int i = 1; i < argc; ++i) {
159 std::string arg = argv[i];
161 if(arg == "--fullscreen" || arg == "-f") {
162 config->use_fullscreen = true;
163 } else if(arg == "--window" || arg == "-w") {
164 config->use_fullscreen = false;
165 } else if(arg == "--geometry" || arg == "-g") {
167 print_usage(argv[0]);
168 throw std::runtime_error("Need to specify a parameter for geometry switch");
170 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
172 print_usage(argv[0]);
173 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
175 } else if(arg == "--show-fps") {
176 config->show_fps = true;
177 } else if(arg == "--play-demo") {
179 print_usage(argv[0]);
180 throw std::runtime_error("Need to specify a demo filename");
182 config->start_demo = argv[++i];
183 } else if(arg == "--record-demo") {
185 print_usage(argv[0]);
186 throw std::runtime_error("Need to specify a demo filename");
188 config->record_demo = argv[++i];
189 } else if(arg == "--help") {
190 print_usage(argv[0]);
191 throw std::runtime_error("");
192 } else if(arg == "--version") {
193 std::cerr << PACKAGE_NAME << " " << PACKAGE_VERSION << "\n";
194 throw std::runtime_error("");
195 } else if(arg[0] != '-') {
196 config->start_level = arg;
198 std::cerr << "Unknown option '" << arg << "'.\n";
199 std::cerr << "Use --help to see a list of options.\n";
203 // TODO joystick switchyes...
206 static void init_sdl()
208 if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
209 std::stringstream msg;
210 msg << "Couldn't initialize SDL: " << SDL_GetError();
211 throw std::runtime_error(msg.str());
214 SDL_EnableUNICODE(1);
216 // wait 100ms and clear SDL event queue because sometimes we have random
217 // joystick events in the queue on startup...
220 while(SDL_PollEvent(&dummy))
224 static void check_gl_error()
226 GLenum glerror = glGetError();
227 std::string errormsg;
229 if(glerror != GL_NO_ERROR) {
231 case GL_INVALID_ENUM:
232 errormsg = "Invalid enumeration value";
234 case GL_INVALID_VALUE:
235 errormsg = "Numeric argzment out of range";
237 case GL_INVALID_OPERATION:
238 errormsg = "Invalid operation";
240 case GL_STACK_OVERFLOW:
241 errormsg = "stack overflow";
243 case GL_STACK_UNDERFLOW:
244 errormsg = "stack underflow";
246 case GL_OUT_OF_MEMORY:
247 errormsg = "out of memory";
249 case GL_TABLE_TOO_LARGE:
250 errormsg = "table too large";
253 errormsg = "unknown error number";
256 std::stringstream msg;
257 msg << "OpenGL Error: " << errormsg;
258 throw std::runtime_error(msg.str());
264 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
265 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
266 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
267 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
269 int flags = SDL_OPENGL;
270 if(config->use_fullscreen)
271 flags |= SDL_FULLSCREEN;
272 int width = config->screenwidth;
273 int height = config->screenheight;
276 screen = SDL_SetVideoMode(width, height, bpp, flags);
278 std::stringstream msg;
279 msg << "Couldn't set video mode (" << width << "x" << height
280 << "-" << bpp << "bpp): " << SDL_GetError();
281 throw std::runtime_error(msg.str());
284 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
287 SDL_Surface* icon = IMG_Load(
288 get_resource_filename("images/engine/icons/supertux.xpm").c_str());
290 SDL_WM_SetIcon(icon, 0);
291 SDL_FreeSurface(icon);
295 std::cerr << "Warning: Couldn't find icon 'images/engine/icons/supertux.xpm'.\n";
299 // setup opengl state and transform
300 glDisable(GL_DEPTH_TEST);
301 glDisable(GL_CULL_FACE);
303 glViewport(0, 0, screen->w, screen->h);
304 glMatrixMode(GL_PROJECTION);
306 // logical resolution here not real monitor resolution
307 glOrtho(0, 800, 600, 0, -1.0, 1.0);
308 glMatrixMode(GL_MODELVIEW);
310 glTranslatef(0, 0, 0);
314 Surface::reload_all();
317 static void init_audio()
319 sound_manager = new SoundManager();
321 int format = MIX_DEFAULT_FORMAT;
322 if(Mix_OpenAudio(config->audio_frequency, format, config->audio_channels,
323 config->audio_chunksize) < 0) {
324 std::cerr << "Couldn't initialize audio ("
325 << config->audio_frequency << "HZ, " << config->audio_channels
326 << " Channels, Format " << format << ", ChunkSize "
327 << config->audio_chunksize << "): " << SDL_GetError() << "\n";
330 sound_manager->set_audio_device_available(true);
331 sound_manager->enable_sound(config->sound_enabled);
332 sound_manager->enable_music(config->music_enabled);
334 if(Mix_AllocateChannels(config->audio_voices) < 0) {
335 std::cerr << "Couldn't allocate '" << config->audio_voices << "' audio voices: "
336 << SDL_GetError() << "\n";
341 static void quit_audio()
344 if(sound_manager->audio_device_available())
347 delete sound_manager;
352 void wait_for_event(float min_delay, float max_delay)
354 assert(min_delay <= max_delay);
356 Uint32 min = (Uint32) (min_delay * 1000);
357 Uint32 max = (Uint32) (max_delay * 1000);
363 while (SDL_PollEvent(&event))
367 bool running = false;
368 Uint32 ticks = SDL_GetTicks();
370 while(SDL_PollEvent(&event)) {
373 throw std::runtime_error("received window close");
375 case SDL_JOYBUTTONDOWN:
376 case SDL_MOUSEBUTTONDOWN:
380 if(SDL_GetTicks() - ticks >= (max - min))
386 int main(int argc, char** argv)
388 #ifndef DEBUG // we want backtraces in debug mode so don't catch exceptions
393 main_controller = new JoystickKeyboardController();
397 parse_commandline(argc, argv);
403 if(config->start_level != "") {
404 GameSession session(config->start_level, ST_GL_LOAD_LEVEL_FILE);
405 if(config->start_demo != "")
406 session.play_demo(config->start_demo);
407 if(config->record_demo != "")
408 session.record_demo(config->record_demo);
416 } catch(std::exception& e) {
417 std::cerr << "Unexpected exception: " << e.what() << std::endl;
420 std::cerr << "Unexpected exception." << std::endl;
428 Surface::debug_check();
435 delete main_controller;