4 // Copyright (C) 2006 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>
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 "video/glutil.hpp"
47 #include "control/joystickkeyboardcontroller.hpp"
48 #include "options_menu.hpp"
49 #include "mainloop.hpp"
51 #include "game_session.hpp"
52 #include "scripting/level.hpp"
53 #include "scripting/squirrel_util.hpp"
54 #include "file_system.hpp"
55 #include "physfs/physfs_sdl.hpp"
57 SDL_Surface* screen = 0;
58 JoystickKeyboardController* main_controller = 0;
59 TinyGetText::DictionaryManager dictionary_manager;
61 static void init_config()
63 config = new Config();
66 } catch(std::exception& e) {
67 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
71 static void init_tinygettext()
73 dictionary_manager.add_directory("locale");
74 dictionary_manager.set_charset("UTF-8");
77 static void init_physfs(const char* argv0)
79 if(!PHYSFS_init(argv0)) {
80 std::stringstream msg;
81 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
82 throw std::runtime_error(msg.str());
85 // Initialize physfs (this is a slightly modified version of
86 // PHYSFS_setSaneConfig
87 const char* application = PACKAGE_NAME;
88 const char* userdir = PHYSFS_getUserDir();
89 const char* dirsep = PHYSFS_getDirSeparator();
90 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
92 // Set configuration directory
93 sprintf(writedir, "%s.%s", userdir, application);
94 if(!PHYSFS_setWriteDir(writedir)) {
95 // try to create the directory
96 char* mkdir = new char[strlen(application) + 2];
97 sprintf(mkdir, ".%s", application);
98 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
99 std::ostringstream msg;
100 msg << "Failed creating configuration directory '"
101 << writedir << "': " << PHYSFS_getLastError();
104 throw std::runtime_error(msg.str());
108 if(!PHYSFS_setWriteDir(writedir)) {
109 std::ostringstream msg;
110 msg << "Failed to use configuration directory '"
111 << writedir << "': " << PHYSFS_getLastError();
113 throw std::runtime_error(msg.str());
116 PHYSFS_addToSearchPath(writedir, 0);
119 // Search for archives and add them to the search path
120 const char* archiveExt = "zip";
121 char** rc = PHYSFS_enumerateFiles("/");
122 size_t extlen = strlen(archiveExt);
124 for(char** i = rc; *i != 0; ++i) {
125 size_t l = strlen(*i);
126 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
127 const char* ext = (*i) + (l - extlen);
128 if(strcasecmp(ext, archiveExt) == 0) {
129 const char* d = PHYSFS_getRealDir(*i);
130 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
131 sprintf(str, "%s%s%s", d, dirsep, *i);
132 PHYSFS_addToSearchPath(str, 1);
140 // when started from source dir...
141 std::string dir = PHYSFS_getBaseDir();
143 std::string testfname = dir;
144 testfname += "/credits.txt";
145 bool sourcedir = false;
146 FILE* f = fopen(testfname.c_str(), "r");
149 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
150 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
157 // when started from Application file on Mac OS X...
158 dir = PHYSFS_getBaseDir();
159 dir += "SuperTux.app/Contents/Resources/data";
160 testfname = dir + "/credits.txt";
162 f = fopen(testfname.c_str(), "r");
165 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
166 msg_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
174 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
176 #ifdef ENABLE_BINRELOC
177 char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
181 datadir = APPDATADIR;
183 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
184 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
189 // allow symbolic links
190 PHYSFS_permitSymbolicLinks(1);
193 for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
194 log_info << "[" << *i << "] is in the search path" << std::endl;
197 static void print_usage(const char* argv0)
199 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
202 " -f, --fullscreen Run in fullscreen mode\n"
203 " -w, --window Run in window mode\n"
204 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
205 " --disable-sfx Disable sound effects\n"
206 " --disable-music Disable music\n"
207 " --help Show this help message\n"
208 " --version Display SuperTux version and quit\n"
209 " --show-fps Display framerate in levels\n"
210 " --record-demo FILE LEVEL Record a demo to FILE\n"
211 " --play-demo FILE LEVEL Play a recorded demo\n"
215 static bool parse_commandline(int argc, char** argv)
217 for(int i = 1; i < argc; ++i) {
218 std::string arg = argv[i];
220 if(arg == "--fullscreen" || arg == "-f") {
221 config->use_fullscreen = true;
222 } else if(arg == "--window" || arg == "-w") {
223 config->use_fullscreen = false;
224 } else if(arg == "--geometry" || arg == "-g") {
226 print_usage(argv[0]);
227 throw std::runtime_error("Need to specify a parameter for geometry switch");
229 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
231 print_usage(argv[0]);
232 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
234 } else if(arg == "--show-fps") {
235 config->show_fps = true;
236 } else if(arg == "--disable-sfx") {
237 config->sound_enabled = false;
238 } else if(arg == "--disable-music") {
239 config->music_enabled = false;
240 } else if(arg == "--play-demo") {
242 print_usage(argv[0]);
243 throw std::runtime_error("Need to specify a demo filename");
245 config->start_demo = argv[++i];
246 } else if(arg == "--record-demo") {
248 print_usage(argv[0]);
249 throw std::runtime_error("Need to specify a demo filename");
251 config->record_demo = argv[++i];
252 } else if(arg == "-d") {
253 config->enable_script_debugger = true;
254 } else if(arg == "--help") {
255 print_usage(argv[0]);
257 } else if(arg == "--version") {
258 log_info << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
260 } else if(arg[0] != '-') {
261 config->start_level = arg;
263 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
270 static void init_sdl()
272 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
273 std::stringstream msg;
274 msg << "Couldn't initialize SDL: " << SDL_GetError();
275 throw std::runtime_error(msg.str());
280 SDL_EnableUNICODE(1);
282 // wait 100ms and clear SDL event queue because sometimes we have random
283 // joystick events in the queue on startup...
286 while(SDL_PollEvent(&dummy))
292 if(texture_manager != NULL)
293 texture_manager->save_textures();
295 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
296 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
297 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
298 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
300 int flags = SDL_OPENGL;
301 if(config->use_fullscreen)
302 flags |= SDL_FULLSCREEN;
303 int width = config->screenwidth;
304 int height = config->screenheight;
307 screen = SDL_SetVideoMode(width, height, bpp, flags);
309 std::stringstream msg;
310 msg << "Couldn't set video mode (" << width << "x" << height
311 << "-" << bpp << "bpp): " << SDL_GetError();
312 throw std::runtime_error(msg.str());
315 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
318 SDL_Surface* icon = IMG_Load_RW(
319 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
321 SDL_WM_SetIcon(icon, 0);
322 SDL_FreeSurface(icon);
326 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
330 // setup opengl state and transform
331 glDisable(GL_DEPTH_TEST);
332 glDisable(GL_CULL_FACE);
333 glEnable(GL_TEXTURE_2D);
335 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
337 glViewport(0, 0, screen->w, screen->h);
338 glMatrixMode(GL_PROJECTION);
340 // logical resolution here not real monitor resolution
341 glOrtho(0, 800, 600, 0, -1.0, 1.0);
342 glMatrixMode(GL_MODELVIEW);
344 glTranslatef(0, 0, 0);
346 check_gl_error("Setting up view matrices");
348 if(texture_manager != NULL)
349 texture_manager->reload_textures();
351 texture_manager = new TextureManager();
354 static void init_audio()
356 sound_manager = new SoundManager();
358 sound_manager->enable_sound(config->sound_enabled);
359 sound_manager->enable_music(config->music_enabled);
362 static void quit_audio()
364 if(sound_manager != NULL) {
365 delete sound_manager;
366 sound_manager = NULL;
370 void wait_for_event(float min_delay, float max_delay)
372 assert(min_delay <= max_delay);
374 Uint32 min = (Uint32) (min_delay * 1000);
375 Uint32 max = (Uint32) (max_delay * 1000);
377 Uint32 ticks = SDL_GetTicks();
378 while(SDL_GetTicks() - ticks < min) {
380 sound_manager->update();
385 while (SDL_PollEvent(&event))
389 bool running = false;
390 ticks = SDL_GetTicks();
392 while(SDL_PollEvent(&event)) {
398 case SDL_JOYBUTTONDOWN:
399 case SDL_MOUSEBUTTONDOWN:
403 if(SDL_GetTicks() - ticks >= (max - min))
405 sound_manager->update();
411 static Uint32 last_timelog_ticks = 0;
412 static const char* last_timelog_component = 0;
414 static inline void timelog(const char* component)
416 Uint32 current_ticks = SDL_GetTicks();
418 if(last_timelog_component != 0) {
419 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
422 last_timelog_ticks = current_ticks;
423 last_timelog_component = component;
426 static inline void timelog(const char* )
431 int main(int argc, char** argv)
436 Console::instance = new Console();
438 init_physfs(argv[0]);
441 timelog("controller");
442 main_controller = new JoystickKeyboardController();
445 timelog("tinygettext");
447 timelog("commandline");
448 if(parse_commandline(argc, argv))
454 Console::instance->init_graphics();
455 timelog("scripting");
456 Scripting::init_squirrel(config->enable_script_debugger);
457 timelog("resources");
461 main_loop = new MainLoop();
462 if(config->start_level != "") {
463 // we have a normal path specified at commandline not physfs paths.
464 // So we simply mount that path here...
465 std::string dir = FileSystem::dirname(config->start_level);
466 PHYSFS_addToSearchPath(dir.c_str(), true);
467 std::auto_ptr<GameSession> session
468 (new GameSession(FileSystem::basename(config->start_level)));
469 if(config->start_demo != "")
470 session->play_demo(config->start_demo);
471 if(config->record_demo != "")
472 session->record_demo(config->record_demo);
473 main_loop->push_screen(session.release());
475 main_loop->push_screen(new TitleScreen());
479 } catch(std::exception& e) {
480 log_fatal << "Unexpected exception: " << e.what() << std::endl;
483 log_fatal << "Unexpected exception" << std::endl;
498 delete main_controller;
499 main_controller = NULL;
500 delete Console::instance;
501 Console::instance = NULL;
502 Scripting::exit_squirrel();
503 delete texture_manager;
504 texture_manager = NULL;