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"
56 #include "random_generator.hpp"
57 #include "worldmap/worldmap.hpp"
59 SDL_Surface* screen = 0;
60 JoystickKeyboardController* main_controller = 0;
61 TinyGetText::DictionaryManager dictionary_manager;
63 static void init_config()
65 config = new Config();
68 } catch(std::exception& e) {
69 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
73 static void init_tinygettext()
75 dictionary_manager.add_directory("locale");
76 dictionary_manager.set_charset("UTF-8");
79 static void init_physfs(const char* argv0)
81 if(!PHYSFS_init(argv0)) {
82 std::stringstream msg;
83 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
84 throw std::runtime_error(msg.str());
87 // Initialize physfs (this is a slightly modified version of
88 // PHYSFS_setSaneConfig
89 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
90 const char* userdir = PHYSFS_getUserDir();
91 const char* dirsep = PHYSFS_getDirSeparator();
92 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
94 // Set configuration directory
95 sprintf(writedir, "%s.%s", userdir, application);
96 if(!PHYSFS_setWriteDir(writedir)) {
97 // try to create the directory
98 char* mkdir = new char[strlen(application) + 2];
99 sprintf(mkdir, ".%s", application);
100 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
101 std::ostringstream msg;
102 msg << "Failed creating configuration directory '"
103 << writedir << "': " << PHYSFS_getLastError();
106 throw std::runtime_error(msg.str());
110 if(!PHYSFS_setWriteDir(writedir)) {
111 std::ostringstream msg;
112 msg << "Failed to use configuration directory '"
113 << writedir << "': " << PHYSFS_getLastError();
115 throw std::runtime_error(msg.str());
118 PHYSFS_addToSearchPath(writedir, 0);
121 // Search for archives and add them to the search path
122 const char* archiveExt = "zip";
123 char** rc = PHYSFS_enumerateFiles("/");
124 size_t extlen = strlen(archiveExt);
126 for(char** i = rc; *i != 0; ++i) {
127 size_t l = strlen(*i);
128 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
129 const char* ext = (*i) + (l - extlen);
130 if(strcasecmp(ext, archiveExt) == 0) {
131 const char* d = PHYSFS_getRealDir(*i);
132 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
133 sprintf(str, "%s%s%s", d, dirsep, *i);
134 PHYSFS_addToSearchPath(str, 1);
142 // when started from source dir...
143 std::string dir = PHYSFS_getBaseDir();
145 std::string testfname = dir;
146 testfname += "/credits.txt";
147 bool sourcedir = false;
148 FILE* f = fopen(testfname.c_str(), "r");
151 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
152 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
159 // when started from Application file on Mac OS X...
160 dir = PHYSFS_getBaseDir();
161 dir += "SuperTux.app/Contents/Resources/data";
162 testfname = dir + "/credits.txt";
164 f = fopen(testfname.c_str(), "r");
167 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
168 msg_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
176 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
178 #ifdef ENABLE_BINRELOC
179 char* brdatadir = br_strcat(DATADIR, "/" PACKAGE_NAME);
183 datadir = APPDATADIR;
185 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
186 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
191 // allow symbolic links
192 PHYSFS_permitSymbolicLinks(1);
195 for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
196 log_info << "[" << *i << "] is in the search path" << std::endl;
199 static void print_usage(const char* argv0)
201 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
204 " -f, --fullscreen Run in fullscreen mode\n"
205 " -w, --window Run in window mode\n"
206 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
207 " --disable-sfx Disable sound effects\n"
208 " --disable-music Disable music\n"
209 " --help Show this help message\n"
210 " --version Display SuperTux version and quit\n"
211 " --show-fps Display framerate in levels\n"
212 " --record-demo FILE LEVEL Record a demo to FILE\n"
213 " --play-demo FILE LEVEL Play a recorded demo\n"
217 static bool parse_commandline(int argc, char** argv)
219 for(int i = 1; i < argc; ++i) {
220 std::string arg = argv[i];
222 if(arg == "--fullscreen" || arg == "-f") {
223 config->use_fullscreen = true;
224 } else if(arg == "--window" || arg == "-w") {
225 config->use_fullscreen = false;
226 } else if(arg == "--geometry" || arg == "-g") {
228 print_usage(argv[0]);
229 throw std::runtime_error("Need to specify a parameter for geometry switch");
231 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
233 print_usage(argv[0]);
234 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
236 } else if(arg == "--show-fps") {
237 config->show_fps = true;
238 } else if(arg == "--disable-sfx") {
239 config->sound_enabled = false;
240 } else if(arg == "--disable-music") {
241 config->music_enabled = false;
242 } else if(arg == "--play-demo") {
244 print_usage(argv[0]);
245 throw std::runtime_error("Need to specify a demo filename");
247 config->start_demo = argv[++i];
248 } else if(arg == "--record-demo") {
250 print_usage(argv[0]);
251 throw std::runtime_error("Need to specify a demo filename");
253 config->record_demo = argv[++i];
254 } else if(arg == "-d") {
255 config->enable_script_debugger = true;
256 } else if(arg == "--help") {
257 print_usage(argv[0]);
259 } else if(arg == "--version") {
260 log_info << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
262 } else if(arg[0] != '-') {
263 config->start_level = arg;
265 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
272 static void init_sdl()
274 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
275 std::stringstream msg;
276 msg << "Couldn't initialize SDL: " << SDL_GetError();
277 throw std::runtime_error(msg.str());
282 SDL_EnableUNICODE(1);
284 // wait 100ms and clear SDL event queue because sometimes we have random
285 // joystick events in the queue on startup...
288 while(SDL_PollEvent(&dummy))
292 static void init_rand()
294 const char *how = config->random_seed? ", user fixed.": ", from time().";
296 config->random_seed = systemRandom.srand(config->random_seed);
298 log_info << "Using random seed " << config->random_seed << how << std::endl;
303 if(texture_manager != NULL)
304 texture_manager->save_textures();
306 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
307 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
308 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
309 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
311 int flags = SDL_OPENGL;
312 if(config->use_fullscreen)
313 flags |= SDL_FULLSCREEN;
314 int width = config->screenwidth;
315 int height = config->screenheight;
318 screen = SDL_SetVideoMode(width, height, bpp, flags);
320 std::stringstream msg;
321 msg << "Couldn't set video mode (" << width << "x" << height
322 << "-" << bpp << "bpp): " << SDL_GetError();
323 throw std::runtime_error(msg.str());
326 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
329 SDL_Surface* icon = IMG_Load_RW(
330 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
332 SDL_WM_SetIcon(icon, 0);
333 SDL_FreeSurface(icon);
337 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
341 // setup opengl state and transform
342 glDisable(GL_DEPTH_TEST);
343 glDisable(GL_CULL_FACE);
344 glEnable(GL_TEXTURE_2D);
346 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
348 glViewport(0, 0, screen->w, screen->h);
349 glMatrixMode(GL_PROJECTION);
351 // logical resolution here not real monitor resolution
352 glOrtho(0, 800, 600, 0, -1.0, 1.0);
353 glMatrixMode(GL_MODELVIEW);
355 glTranslatef(0, 0, 0);
357 check_gl_error("Setting up view matrices");
359 if(texture_manager != NULL)
360 texture_manager->reload_textures();
362 texture_manager = new TextureManager();
365 static void init_audio()
367 sound_manager = new SoundManager();
369 sound_manager->enable_sound(config->sound_enabled);
370 sound_manager->enable_music(config->music_enabled);
373 static void quit_audio()
375 if(sound_manager != NULL) {
376 delete sound_manager;
377 sound_manager = NULL;
381 void wait_for_event(float min_delay, float max_delay)
383 assert(min_delay <= max_delay);
385 Uint32 min = (Uint32) (min_delay * 1000);
386 Uint32 max = (Uint32) (max_delay * 1000);
388 Uint32 ticks = SDL_GetTicks();
389 while(SDL_GetTicks() - ticks < min) {
391 sound_manager->update();
396 while (SDL_PollEvent(&event))
400 bool running = false;
401 ticks = SDL_GetTicks();
403 while(SDL_PollEvent(&event)) {
409 case SDL_JOYBUTTONDOWN:
410 case SDL_MOUSEBUTTONDOWN:
414 if(SDL_GetTicks() - ticks >= (max - min))
416 sound_manager->update();
422 static Uint32 last_timelog_ticks = 0;
423 static const char* last_timelog_component = 0;
425 static inline void timelog(const char* component)
427 Uint32 current_ticks = SDL_GetTicks();
429 if(last_timelog_component != 0) {
430 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
433 last_timelog_ticks = current_ticks;
434 last_timelog_component = component;
437 static inline void timelog(const char* )
442 int main(int argc, char** argv)
447 Console::instance = new Console();
448 init_physfs(argv[0]);
451 timelog("controller");
452 main_controller = new JoystickKeyboardController();
455 timelog("tinygettext");
457 timelog("commandline");
458 if(parse_commandline(argc, argv))
464 Console::instance->init_graphics();
465 timelog("scripting");
466 Scripting::init_squirrel(config->enable_script_debugger);
467 timelog("resources");
471 main_loop = new MainLoop();
472 if(config->start_level != "") {
473 // we have a normal path specified at commandline not physfs paths.
474 // So we simply mount that path here...
475 std::string dir = FileSystem::dirname(config->start_level);
476 PHYSFS_addToSearchPath(dir.c_str(), true);
478 if(config->start_level.size() > 4 &&
479 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
481 main_loop->push_screen(new WorldMapNS::WorldMap(
482 FileSystem::basename(config->start_level)));
484 init_rand();//If level uses random eg. for
485 // rain particles before we do this:
486 std::auto_ptr<GameSession> session (
487 new GameSession(FileSystem::basename(config->start_level)));
489 config->random_seed =session->get_demo_random_seed(config->start_demo);
490 init_rand();//initialise generator with seed from session
492 if(config->start_demo != "")
493 session->play_demo(config->start_demo);
495 if(config->record_demo != "")
496 session->record_demo(config->record_demo);
497 main_loop->push_screen(session.release());
501 main_loop->push_screen(new TitleScreen());
504 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
507 } catch(std::exception& e) {
508 log_fatal << "Unexpected exception: " << e.what() << std::endl;
511 log_fatal << "Unexpected exception" << std::endl;
526 delete main_controller;
527 main_controller = NULL;
528 delete Console::instance;
529 Console::instance = NULL;
530 Scripting::exit_squirrel();
531 delete texture_manager;
532 texture_manager = NULL;