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>
37 #include <SDL_image.h>
38 #include <SDL_opengl.h>
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 "control/joystickkeyboardcontroller.hpp"
49 #include "game_session.hpp"
50 #include "file_system.hpp"
51 #include "physfs/physfs_sdl.hpp"
52 #include "exceptions.hpp"
54 SDL_Surface* screen = 0;
55 JoystickKeyboardController* main_controller = 0;
56 TinyGetText::DictionaryManager dictionary_manager;
58 static void init_config()
60 config = new Config();
63 } catch(std::exception& e) {
64 msg_info("Couldn't load config file: " << e.what() << ", using default settings");
68 static void init_tinygettext()
70 dictionary_manager.add_directory("locale");
71 dictionary_manager.set_charset("UTF-8");
74 static void init_physfs(const char* argv0)
76 if(!PHYSFS_init(argv0)) {
77 std::stringstream msg;
78 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
79 throw std::runtime_error(msg.str());
82 // Initialize physfs (this is a slightly modified version of
83 // PHYSFS_setSaneConfig
84 const char* application = PACKAGE_NAME;
85 const char* userdir = PHYSFS_getUserDir();
86 const char* dirsep = PHYSFS_getDirSeparator();
87 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
89 // Set configuration directory
90 sprintf(writedir, "%s.%s", userdir, application);
91 if(!PHYSFS_setWriteDir(writedir)) {
92 // try to create the directory
93 char* mkdir = new char[strlen(application) + 2];
94 sprintf(mkdir, ".%s", application);
95 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
96 std::ostringstream msg;
97 msg << "Failed creating configuration directory '"
98 << writedir << "': " << PHYSFS_getLastError();
101 throw std::runtime_error(msg.str());
105 if(!PHYSFS_setWriteDir(writedir)) {
106 std::ostringstream msg;
107 msg << "Failed to use configuration directory '"
108 << writedir << "': " << PHYSFS_getLastError();
110 throw std::runtime_error(msg.str());
113 PHYSFS_addToSearchPath(writedir, 0);
116 // Search for archives and add them to the search path
117 const char* archiveExt = "zip";
118 char** rc = PHYSFS_enumerateFiles("/");
119 size_t extlen = strlen(archiveExt);
121 for(char** i = rc; *i != 0; ++i) {
122 size_t l = strlen(*i);
123 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
124 const char* ext = (*i) + (l - extlen);
125 if(strcasecmp(ext, archiveExt) == 0) {
126 const char* d = PHYSFS_getRealDir(*i);
127 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
128 sprintf(str, "%s%s%s", d, dirsep, *i);
129 PHYSFS_addToSearchPath(str, 1);
137 // when started from source dir...
138 std::string dir = PHYSFS_getBaseDir();
140 std::string testfname = dir;
141 testfname += "/credits.txt";
142 bool sourcedir = false;
143 FILE* f = fopen(testfname.c_str(), "r");
146 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
147 msg_warning("Couldn't add '" << dir
148 << "' to physfs searchpath: " << PHYSFS_getLastError());
155 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
157 #ifdef ENABLE_BINRELOC
158 char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
162 datadir = APPDATADIR;
164 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
165 msg_warning("Couldn't add '" << datadir
166 << "' to physfs searchpath: " << PHYSFS_getLastError());
171 // allow symbolic links
172 PHYSFS_permitSymbolicLinks(1);
175 for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
176 msg_info("[" << *i << "] is in the search path");
179 static void print_usage(const char* argv0)
181 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
184 " -f, --fullscreen Run in fullscreen mode\n"
185 " -w, --window Run in window mode\n"
186 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
187 " --disable-sfx Disable sound effects\n"
188 " --disable-music Disable music\n"
189 " --help Show this help message\n"
190 " --version Display SuperTux version and quit\n"
191 " --show-fps Display framerate in levels\n"
192 " --record-demo FILE LEVEL Record a demo to FILE\n"
193 " --play-demo FILE LEVEL Play a recorded demo\n"
197 static void parse_commandline(int argc, char** argv)
199 for(int i = 1; i < argc; ++i) {
200 std::string arg = argv[i];
202 if(arg == "--fullscreen" || arg == "-f") {
203 config->use_fullscreen = true;
204 } else if(arg == "--window" || arg == "-w") {
205 config->use_fullscreen = false;
206 } else if(arg == "--geometry" || arg == "-g") {
208 print_usage(argv[0]);
209 throw std::runtime_error("Need to specify a parameter for geometry switch");
211 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
213 print_usage(argv[0]);
214 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
216 } else if(arg == "--show-fps") {
217 config->show_fps = true;
218 } else if(arg == "--disable-sfx") {
219 config->sound_enabled = false;
220 } else if(arg == "--disable-music") {
221 config->music_enabled = false;
222 } else if(arg == "--play-demo") {
224 print_usage(argv[0]);
225 throw std::runtime_error("Need to specify a demo filename");
227 config->start_demo = argv[++i];
228 } else if(arg == "--record-demo") {
230 print_usage(argv[0]);
231 throw std::runtime_error("Need to specify a demo filename");
233 config->record_demo = argv[++i];
234 } else if(arg == "--help") {
235 print_usage(argv[0]);
236 throw graceful_shutdown();
237 } else if(arg == "--version") {
238 msg_info(PACKAGE_NAME << " " << PACKAGE_VERSION);
239 throw graceful_shutdown();
240 } else if(arg[0] != '-') {
241 config->start_level = arg;
243 msg_warning("Unknown option '" << arg << "'. Use --help to see a list of options");
247 // TODO joystick switchyes...
250 static void init_sdl()
252 if(SDL_Init(SDL_INIT_EVERYTHING) < 0) {
253 std::stringstream msg;
254 msg << "Couldn't initialize SDL: " << SDL_GetError();
255 throw std::runtime_error(msg.str());
258 SDL_EnableUNICODE(1);
260 // wait 100ms and clear SDL event queue because sometimes we have random
261 // joystick events in the queue on startup...
264 while(SDL_PollEvent(&dummy))
268 static void check_gl_error()
270 GLenum glerror = glGetError();
271 std::string errormsg;
273 if(glerror != GL_NO_ERROR) {
275 case GL_INVALID_ENUM:
276 errormsg = "Invalid enumeration value";
278 case GL_INVALID_VALUE:
279 errormsg = "Numeric argzment out of range";
281 case GL_INVALID_OPERATION:
282 errormsg = "Invalid operation";
284 case GL_STACK_OVERFLOW:
285 errormsg = "stack overflow";
287 case GL_STACK_UNDERFLOW:
288 errormsg = "stack underflow";
290 case GL_OUT_OF_MEMORY:
291 errormsg = "out of memory";
293 case GL_TABLE_TOO_LARGE:
294 errormsg = "table too large";
297 errormsg = "unknown error number";
300 std::stringstream msg;
301 msg << "OpenGL Error: " << errormsg;
302 throw std::runtime_error(msg.str());
308 if(texture_manager != NULL)
309 texture_manager->save_textures();
311 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
312 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
313 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
314 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
316 int flags = SDL_OPENGL;
317 if(config->use_fullscreen)
318 flags |= SDL_FULLSCREEN;
319 int width = config->screenwidth;
320 int height = config->screenheight;
323 screen = SDL_SetVideoMode(width, height, bpp, flags);
325 std::stringstream msg;
326 msg << "Couldn't set video mode (" << width << "x" << height
327 << "-" << bpp << "bpp): " << SDL_GetError();
328 throw std::runtime_error(msg.str());
331 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
334 SDL_Surface* icon = IMG_Load_RW(
335 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
337 SDL_WM_SetIcon(icon, 0);
338 SDL_FreeSurface(icon);
342 msg_warning("Couldn't find icon 'images/engine/icons/supertux.xpm'");
346 // setup opengl state and transform
347 glDisable(GL_DEPTH_TEST);
348 glDisable(GL_CULL_FACE);
349 glEnable(GL_TEXTURE_2D);
351 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
353 glViewport(0, 0, screen->w, screen->h);
354 glMatrixMode(GL_PROJECTION);
356 // logical resolution here not real monitor resolution
357 glOrtho(0, 800, 600, 0, -1.0, 1.0);
358 glMatrixMode(GL_MODELVIEW);
360 glTranslatef(0, 0, 0);
364 if(texture_manager != NULL)
365 texture_manager->reload_textures();
367 texture_manager = new TextureManager();
370 static void init_audio()
372 sound_manager = new SoundManager();
374 sound_manager->enable_sound(config->sound_enabled);
375 sound_manager->enable_music(config->music_enabled);
378 static void quit_audio()
381 delete sound_manager;
386 void wait_for_event(float min_delay, float max_delay)
388 assert(min_delay <= max_delay);
390 Uint32 min = (Uint32) (min_delay * 1000);
391 Uint32 max = (Uint32) (max_delay * 1000);
393 Uint32 ticks = SDL_GetTicks();
394 while(SDL_GetTicks() - ticks < min) {
396 sound_manager->update();
401 while (SDL_PollEvent(&event))
405 bool running = false;
406 ticks = SDL_GetTicks();
408 while(SDL_PollEvent(&event)) {
411 throw graceful_shutdown();
413 case SDL_JOYBUTTONDOWN:
414 case SDL_MOUSEBUTTONDOWN:
418 if(SDL_GetTicks() - ticks >= (max - min))
420 sound_manager->update();
426 static Uint32 last_timelog_ticks = 0;
427 static const char* last_timelog_component = 0;
429 static inline void timelog(const char* component)
431 Uint32 current_ticks = SDL_GetTicks();
433 if(last_timelog_component != 0) {
434 msg_info("Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds");
437 last_timelog_ticks = current_ticks;
438 last_timelog_component = component;
441 static inline void timelog(const char* )
446 int main(int argc, char** argv)
450 init_physfs(argv[0]);
452 timelog("controller");
453 main_controller = new JoystickKeyboardController();
456 timelog("tinygettext");
458 timelog("commandline");
459 parse_commandline(argc, argv);
467 timelog("resources");
470 if(config->start_level != "") {
471 // we have a normal path specified at commandline not physfs paths.
472 // So we simply mount that path here...
473 std::string dir = FileSystem::dirname(config->start_level);
474 PHYSFS_addToSearchPath(dir.c_str(), true);
476 FileSystem::basename(config->start_level), ST_GL_LOAD_LEVEL_FILE);
477 if(config->start_demo != "")
478 session.play_demo(config->start_demo);
479 if(config->record_demo != "")
480 session.record_demo(config->record_demo);
486 } catch(graceful_shutdown& e) {
487 } catch(std::exception& e) {
488 msg_fatal("Unexpected exception: " << e.what());
491 msg_fatal("Unexpected exception");
502 delete main_controller;
503 delete texture_manager;