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 msg_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 " --show-fps Display framerate in levels\n"
219 " --record-demo FILE LEVEL Record a demo to FILE\n"
220 " --play-demo FILE LEVEL Play a recorded demo\n"
225 * Options that should be evaluated prior to any initializations at all go here
227 static bool pre_parse_commandline(int argc, char** argv)
229 for(int i = 1; i < argc; ++i) {
230 std::string arg = argv[i];
232 if(arg == "--help") {
233 print_usage(argv[0]);
235 } else if(arg == "--version") {
236 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
245 * Options that should be evaluated after config is read go here
247 static bool parse_commandline(int argc, char** argv)
249 for(int i = 1; i < argc; ++i) {
250 std::string arg = argv[i];
252 if(arg == "--fullscreen" || arg == "-f") {
253 config->use_fullscreen = true;
254 } else if(arg == "--window" || arg == "-w") {
255 config->use_fullscreen = false;
256 } else if(arg == "--geometry" || arg == "-g") {
258 print_usage(argv[0]);
259 throw std::runtime_error("Need to specify a parameter for geometry switch");
261 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
263 print_usage(argv[0]);
264 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
266 } else if(arg == "--show-fps") {
267 config->show_fps = true;
268 } else if(arg == "--console") {
269 config->console_enabled = true;
270 } else if(arg == "--disable-sfx") {
271 config->sound_enabled = false;
272 } else if(arg == "--disable-music") {
273 config->music_enabled = false;
274 } else if(arg == "--play-demo") {
276 print_usage(argv[0]);
277 throw std::runtime_error("Need to specify a demo filename");
279 config->start_demo = argv[++i];
280 } else if(arg == "--record-demo") {
282 print_usage(argv[0]);
283 throw std::runtime_error("Need to specify a demo filename");
285 config->record_demo = argv[++i];
286 } else if(arg == "-d") {
287 config->enable_script_debugger = true;
288 } else if(arg[0] != '-') {
289 config->start_level = arg;
291 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
298 static void init_sdl()
300 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
301 std::stringstream msg;
302 msg << "Couldn't initialize SDL: " << SDL_GetError();
303 throw std::runtime_error(msg.str());
308 SDL_EnableUNICODE(1);
310 // wait 100ms and clear SDL event queue because sometimes we have random
311 // joystick events in the queue on startup...
314 while(SDL_PollEvent(&dummy))
318 static void init_rand()
320 const char *how = config->random_seed? ", user fixed.": ", from time().";
322 config->random_seed = systemRandom.srand(config->random_seed);
324 log_info << "Using random seed " << config->random_seed << how << std::endl;
329 if(texture_manager != NULL)
330 texture_manager->save_textures();
332 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
333 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
334 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
335 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
337 int flags = SDL_OPENGL;
338 if(config->use_fullscreen)
339 flags |= SDL_FULLSCREEN;
340 int width = config->screenwidth;
341 int height = config->screenheight;
344 screen = SDL_SetVideoMode(width, height, bpp, flags);
346 std::stringstream msg;
347 msg << "Couldn't set video mode (" << width << "x" << height
348 << "-" << bpp << "bpp): " << SDL_GetError();
349 throw std::runtime_error(msg.str());
352 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
355 SDL_Surface* icon = IMG_Load_RW(
356 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
358 SDL_WM_SetIcon(icon, 0);
359 SDL_FreeSurface(icon);
363 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
367 // setup opengl state and transform
368 glDisable(GL_DEPTH_TEST);
369 glDisable(GL_CULL_FACE);
370 glEnable(GL_TEXTURE_2D);
372 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
374 glViewport(0, 0, screen->w, screen->h);
375 glMatrixMode(GL_PROJECTION);
377 // logical resolution here not real monitor resolution
378 glOrtho(0, 800, 600, 0, -1.0, 1.0);
379 glMatrixMode(GL_MODELVIEW);
381 glTranslatef(0, 0, 0);
383 check_gl_error("Setting up view matrices");
385 if(texture_manager != NULL)
386 texture_manager->reload_textures();
388 texture_manager = new TextureManager();
391 static void init_audio()
393 sound_manager = new SoundManager();
395 sound_manager->enable_sound(config->sound_enabled);
396 sound_manager->enable_music(config->music_enabled);
399 static void quit_audio()
401 if(sound_manager != NULL) {
402 delete sound_manager;
403 sound_manager = NULL;
407 void wait_for_event(float min_delay, float max_delay)
409 assert(min_delay <= max_delay);
411 Uint32 min = (Uint32) (min_delay * 1000);
412 Uint32 max = (Uint32) (max_delay * 1000);
414 Uint32 ticks = SDL_GetTicks();
415 while(SDL_GetTicks() - ticks < min) {
417 sound_manager->update();
422 while (SDL_PollEvent(&event))
426 bool running = false;
427 ticks = SDL_GetTicks();
429 while(SDL_PollEvent(&event)) {
435 case SDL_JOYBUTTONDOWN:
436 case SDL_MOUSEBUTTONDOWN:
440 if(SDL_GetTicks() - ticks >= (max - min))
442 sound_manager->update();
448 static Uint32 last_timelog_ticks = 0;
449 static const char* last_timelog_component = 0;
451 static inline void timelog(const char* component)
453 Uint32 current_ticks = SDL_GetTicks();
455 if(last_timelog_component != 0) {
456 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
459 last_timelog_ticks = current_ticks;
460 last_timelog_component = component;
463 static inline void timelog(const char* )
468 int main(int argc, char** argv)
474 if(pre_parse_commandline(argc, argv))
477 Console::instance = new Console();
478 init_physfs(argv[0]);
481 timelog("controller");
482 main_controller = new JoystickKeyboardController();
485 timelog("tinygettext");
487 timelog("commandline");
488 if(parse_commandline(argc, argv))
494 Console::instance->init_graphics();
495 timelog("scripting");
496 Scripting::init_squirrel(config->enable_script_debugger);
497 timelog("resources");
501 main_loop = new MainLoop();
502 if(config->start_level != "") {
503 // we have a normal path specified at commandline not physfs paths.
504 // So we simply mount that path here...
505 std::string dir = FileSystem::dirname(config->start_level);
506 PHYSFS_addToSearchPath(dir.c_str(), true);
508 if(config->start_level.size() > 4 &&
509 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
511 main_loop->push_screen(new WorldMapNS::WorldMap(
512 FileSystem::basename(config->start_level)));
514 init_rand();//If level uses random eg. for
515 // rain particles before we do this:
516 std::auto_ptr<GameSession> session (
517 new GameSession(FileSystem::basename(config->start_level)));
519 config->random_seed =session->get_demo_random_seed(config->start_demo);
520 init_rand();//initialise generator with seed from session
522 if(config->start_demo != "")
523 session->play_demo(config->start_demo);
525 if(config->record_demo != "")
526 session->record_demo(config->record_demo);
527 main_loop->push_screen(session.release());
531 main_loop->push_screen(new TitleScreen());
534 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
536 } catch(std::exception& e) {
537 log_fatal << "Unexpected exception: " << e.what() << std::endl;
540 log_fatal << "Unexpected exception" << std::endl;
555 delete main_controller;
556 main_controller = NULL;
557 delete Console::instance;
558 Console::instance = NULL;
559 Scripting::exit_squirrel();
560 delete texture_manager;
561 texture_manager = NULL;