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"
58 #include "binreloc/binreloc.h"
60 SDL_Surface* screen = 0;
61 JoystickKeyboardController* main_controller = 0;
62 TinyGetText::DictionaryManager dictionary_manager;
64 static void init_config()
66 config = new Config();
69 } catch(std::exception& e) {
70 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
74 static void init_tinygettext()
76 dictionary_manager.add_directory("locale");
77 dictionary_manager.set_charset("UTF-8");
80 static void init_physfs(const char* argv0)
82 if(!PHYSFS_init(argv0)) {
83 std::stringstream msg;
84 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
85 throw std::runtime_error(msg.str());
88 // Initialize physfs (this is a slightly modified version of
89 // PHYSFS_setSaneConfig
90 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
91 const char* userdir = PHYSFS_getUserDir();
92 const char* dirsep = PHYSFS_getDirSeparator();
93 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
95 // Set configuration directory
96 sprintf(writedir, "%s.%s", userdir, application);
97 if(!PHYSFS_setWriteDir(writedir)) {
98 // try to create the directory
99 char* mkdir = new char[strlen(application) + 2];
100 sprintf(mkdir, ".%s", application);
101 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
102 std::ostringstream msg;
103 msg << "Failed creating configuration directory '"
104 << writedir << "': " << PHYSFS_getLastError();
107 throw std::runtime_error(msg.str());
111 if(!PHYSFS_setWriteDir(writedir)) {
112 std::ostringstream msg;
113 msg << "Failed to use configuration directory '"
114 << writedir << "': " << PHYSFS_getLastError();
116 throw std::runtime_error(msg.str());
119 PHYSFS_addToSearchPath(writedir, 0);
122 // Search for archives and add them to the search path
123 const char* archiveExt = "zip";
124 char** rc = PHYSFS_enumerateFiles("/");
125 size_t extlen = strlen(archiveExt);
127 for(char** i = rc; *i != 0; ++i) {
128 size_t l = strlen(*i);
129 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
130 const char* ext = (*i) + (l - extlen);
131 if(strcasecmp(ext, archiveExt) == 0) {
132 const char* d = PHYSFS_getRealDir(*i);
133 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
134 sprintf(str, "%s%s%s", d, dirsep, *i);
135 PHYSFS_addToSearchPath(str, 1);
143 // when started from source dir...
144 std::string dir = PHYSFS_getBaseDir();
146 std::string testfname = dir;
147 testfname += "/credits.txt";
148 bool sourcedir = false;
149 FILE* f = fopen(testfname.c_str(), "r");
152 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
153 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
160 // when started from Application file on Mac OS X...
161 dir = PHYSFS_getBaseDir();
162 dir += "SuperTux.app/Contents/Resources/data";
163 testfname = dir + "/credits.txt";
165 f = fopen(testfname.c_str(), "r");
168 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
169 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
177 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
179 #ifdef ENABLE_BINRELOC
183 dir = br_find_data_dir(APPDATADIR);
185 datadir += "/" PACKAGE_NAME;
189 datadir = APPDATADIR;
191 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
192 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
197 // allow symbolic links
198 PHYSFS_permitSymbolicLinks(1);
201 for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
202 log_info << "[" << *i << "] is in the search path" << std::endl;
205 static void print_usage(const char* argv0)
207 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
210 " -f, --fullscreen Run in fullscreen mode\n"
211 " -w, --window Run in window mode\n"
212 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
213 " --disable-sfx Disable sound effects\n"
214 " --disable-music Disable music\n"
215 " --help Show this help message\n"
216 " --version Display SuperTux version and quit\n"
217 " --console Enable ingame scripting console\n"
218 " --noconsole Disable ingame scripting console\n"
219 " --show-fps Display framerate in levels\n"
220 " --no-show-fps Do not display framerate in levels\n"
221 " --record-demo FILE LEVEL Record a demo to FILE\n"
222 " --play-demo FILE LEVEL Play a recorded demo\n"
227 * Options that should be evaluated prior to any initializations at all go here
229 static bool pre_parse_commandline(int argc, char** argv)
231 for(int i = 1; i < argc; ++i) {
232 std::string arg = argv[i];
234 if(arg == "--help") {
235 print_usage(argv[0]);
237 } else if(arg == "--version") {
238 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
247 * Options that should be evaluated after config is read go here
249 static bool parse_commandline(int argc, char** argv)
251 for(int i = 1; i < argc; ++i) {
252 std::string arg = argv[i];
254 if(arg == "--fullscreen" || arg == "-f") {
255 config->use_fullscreen = true;
256 } else if(arg == "--window" || arg == "-w") {
257 config->use_fullscreen = false;
258 } else if(arg == "--geometry" || arg == "-g") {
260 print_usage(argv[0]);
261 throw std::runtime_error("Need to specify a parameter for geometry switch");
263 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
265 print_usage(argv[0]);
266 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
268 } else if(arg == "--show-fps") {
269 config->show_fps = true;
270 } else if(arg == "--no-show-fps") {
271 config->show_fps = false;
272 } else if(arg == "--console") {
273 config->console_enabled = true;
274 } else if(arg == "--noconsole") {
275 config->console_enabled = false;
276 } else if(arg == "--disable-sfx") {
277 config->sound_enabled = false;
278 } else if(arg == "--disable-music") {
279 config->music_enabled = false;
280 } else if(arg == "--play-demo") {
282 print_usage(argv[0]);
283 throw std::runtime_error("Need to specify a demo filename");
285 config->start_demo = argv[++i];
286 } else if(arg == "--record-demo") {
288 print_usage(argv[0]);
289 throw std::runtime_error("Need to specify a demo filename");
291 config->record_demo = argv[++i];
292 } else if(arg == "-d") {
293 config->enable_script_debugger = true;
294 } else if(arg[0] != '-') {
295 config->start_level = arg;
297 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
305 static void init_sdl()
307 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
308 std::stringstream msg;
309 msg << "Couldn't initialize SDL: " << SDL_GetError();
310 throw std::runtime_error(msg.str());
315 SDL_EnableUNICODE(1);
317 // wait 100ms and clear SDL event queue because sometimes we have random
318 // joystick events in the queue on startup...
321 while(SDL_PollEvent(&dummy))
325 static void init_rand()
327 const char *how = config->random_seed? ", user fixed.": ", from time().";
329 config->random_seed = systemRandom.srand(config->random_seed);
331 log_info << "Using random seed " << config->random_seed << how << std::endl;
336 if(texture_manager != NULL)
337 texture_manager->save_textures();
339 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
340 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
341 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
342 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
344 int flags = SDL_OPENGL;
345 if(config->use_fullscreen)
346 flags |= SDL_FULLSCREEN;
347 int width = config->screenwidth;
348 int height = config->screenheight;
351 screen = SDL_SetVideoMode(width, height, bpp, flags);
353 std::stringstream msg;
354 msg << "Couldn't set video mode (" << width << "x" << height
355 << "-" << bpp << "bpp): " << SDL_GetError();
356 throw std::runtime_error(msg.str());
359 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
362 SDL_Surface* icon = IMG_Load_RW(
363 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
365 SDL_WM_SetIcon(icon, 0);
366 SDL_FreeSurface(icon);
370 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
374 // setup opengl state and transform
375 glDisable(GL_DEPTH_TEST);
376 glDisable(GL_CULL_FACE);
377 glEnable(GL_TEXTURE_2D);
379 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
381 glViewport(0, 0, screen->w, screen->h);
382 glMatrixMode(GL_PROJECTION);
384 // logical resolution here not real monitor resolution
385 glOrtho(0, 800, 600, 0, -1.0, 1.0);
386 glMatrixMode(GL_MODELVIEW);
388 glTranslatef(0, 0, 0);
390 check_gl_error("Setting up view matrices");
392 if(texture_manager != NULL)
393 texture_manager->reload_textures();
395 texture_manager = new TextureManager();
398 static void init_audio()
400 sound_manager = new SoundManager();
402 sound_manager->enable_sound(config->sound_enabled);
403 sound_manager->enable_music(config->music_enabled);
406 static void quit_audio()
408 if(sound_manager != NULL) {
409 delete sound_manager;
410 sound_manager = NULL;
414 void wait_for_event(float min_delay, float max_delay)
416 assert(min_delay <= max_delay);
418 Uint32 min = (Uint32) (min_delay * 1000);
419 Uint32 max = (Uint32) (max_delay * 1000);
421 Uint32 ticks = SDL_GetTicks();
422 while(SDL_GetTicks() - ticks < min) {
424 sound_manager->update();
429 while (SDL_PollEvent(&event))
433 bool running = false;
434 ticks = SDL_GetTicks();
436 while(SDL_PollEvent(&event)) {
442 case SDL_JOYBUTTONDOWN:
443 case SDL_MOUSEBUTTONDOWN:
447 if(SDL_GetTicks() - ticks >= (max - min))
449 sound_manager->update();
455 static Uint32 last_timelog_ticks = 0;
456 static const char* last_timelog_component = 0;
458 static inline void timelog(const char* component)
460 Uint32 current_ticks = SDL_GetTicks();
462 if(last_timelog_component != 0) {
463 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
466 last_timelog_ticks = current_ticks;
467 last_timelog_component = component;
470 static inline void timelog(const char* )
475 int main(int argc, char** argv)
481 if(pre_parse_commandline(argc, argv))
484 Console::instance = new Console();
485 init_physfs(argv[0]);
488 timelog("controller");
489 main_controller = new JoystickKeyboardController();
492 timelog("tinygettext");
494 timelog("commandline");
495 if(parse_commandline(argc, argv))
501 Console::instance->init_graphics();
502 timelog("scripting");
503 Scripting::init_squirrel(config->enable_script_debugger);
504 timelog("resources");
508 main_loop = new MainLoop();
509 if(config->start_level != "") {
510 // we have a normal path specified at commandline not physfs paths.
511 // So we simply mount that path here...
512 std::string dir = FileSystem::dirname(config->start_level);
513 PHYSFS_addToSearchPath(dir.c_str(), true);
515 if(config->start_level.size() > 4 &&
516 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
518 main_loop->push_screen(new WorldMapNS::WorldMap(
519 FileSystem::basename(config->start_level)));
521 init_rand();//If level uses random eg. for
522 // rain particles before we do this:
523 std::auto_ptr<GameSession> session (
524 new GameSession(FileSystem::basename(config->start_level)));
526 config->random_seed =session->get_demo_random_seed(config->start_demo);
527 init_rand();//initialise generator with seed from session
529 if(config->start_demo != "")
530 session->play_demo(config->start_demo);
532 if(config->record_demo != "")
533 session->record_demo(config->record_demo);
534 main_loop->push_screen(session.release());
538 main_loop->push_screen(new TitleScreen());
541 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
543 } catch(std::exception& e) {
544 log_fatal << "Unexpected exception: " << e.what() << std::endl;
547 log_fatal << "Unexpected exception" << std::endl;
562 delete main_controller;
563 main_controller = NULL;
564 delete Console::instance;
565 Console::instance = NULL;
566 Scripting::exit_squirrel();
567 delete texture_manager;
568 texture_manager = NULL;