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>
35 #include <SDL_image.h>
38 #include "gameconfig.hpp"
39 #include "resources.hpp"
40 #include "gettext.hpp"
41 #include "audio/sound_manager.hpp"
42 #include "video/surface.hpp"
43 #include "video/texture_manager.hpp"
44 #include "video/glutil.hpp"
45 #include "control/joystickkeyboardcontroller.hpp"
46 #include "options_menu.hpp"
47 #include "mainloop.hpp"
49 #include "game_session.hpp"
50 #include "scripting/level.hpp"
51 #include "scripting/squirrel_util.hpp"
52 #include "file_system.hpp"
53 #include "physfs/physfs_sdl.hpp"
54 #include "random_generator.hpp"
55 #include "worldmap/worldmap.hpp"
56 #include "binreloc/binreloc.h"
58 SDL_Surface* screen = 0;
59 JoystickKeyboardController* main_controller = 0;
60 TinyGetText::DictionaryManager dictionary_manager;
65 static void init_config()
67 config = new Config();
70 } catch(std::exception& e) {
71 log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
75 static void init_tinygettext()
77 dictionary_manager.add_directory("locale");
78 dictionary_manager.set_charset("UTF-8");
81 static void init_physfs(const char* argv0)
83 if(!PHYSFS_init(argv0)) {
84 std::stringstream msg;
85 msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
86 throw std::runtime_error(msg.str());
89 // Initialize physfs (this is a slightly modified version of
90 // PHYSFS_setSaneConfig
91 const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
92 const char* userdir = PHYSFS_getUserDir();
93 const char* dirsep = PHYSFS_getDirSeparator();
94 char* writedir = new char[strlen(userdir) + strlen(application) + 2];
96 // Set configuration directory
97 sprintf(writedir, "%s.%s", userdir, application);
98 if(!PHYSFS_setWriteDir(writedir)) {
99 // try to create the directory
100 char* mkdir = new char[strlen(application) + 2];
101 sprintf(mkdir, ".%s", application);
102 if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
103 std::ostringstream msg;
104 msg << "Failed creating configuration directory '"
105 << writedir << "': " << PHYSFS_getLastError();
108 throw std::runtime_error(msg.str());
112 if(!PHYSFS_setWriteDir(writedir)) {
113 std::ostringstream msg;
114 msg << "Failed to use configuration directory '"
115 << writedir << "': " << PHYSFS_getLastError();
117 throw std::runtime_error(msg.str());
120 PHYSFS_addToSearchPath(writedir, 0);
123 // Search for archives and add them to the search path
124 const char* archiveExt = "zip";
125 char** rc = PHYSFS_enumerateFiles("/");
126 size_t extlen = strlen(archiveExt);
128 for(char** i = rc; *i != 0; ++i) {
129 size_t l = strlen(*i);
130 if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
131 const char* ext = (*i) + (l - extlen);
132 if(strcasecmp(ext, archiveExt) == 0) {
133 const char* d = PHYSFS_getRealDir(*i);
134 char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
135 sprintf(str, "%s%s%s", d, dirsep, *i);
136 PHYSFS_addToSearchPath(str, 1);
144 // when started from source dir...
145 std::string dir = PHYSFS_getBaseDir();
147 std::string testfname = dir;
148 testfname += "/credits.txt";
149 bool sourcedir = false;
150 FILE* f = fopen(testfname.c_str(), "r");
153 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
154 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
161 // when started from Application file on Mac OS X...
162 dir = PHYSFS_getBaseDir();
163 dir += "SuperTux.app/Contents/Resources/data";
164 testfname = dir + "/credits.txt";
166 f = fopen(testfname.c_str(), "r");
169 if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
170 log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
178 PHYSFS_addToSearchPath(".\\data", 1);
182 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
184 #ifdef ENABLE_BINRELOC
188 dir = br_find_data_dir(APPDATADIR);
190 datadir += "/" PACKAGE_NAME;
194 datadir = APPDATADIR;
196 if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
197 log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
202 // allow symbolic links
203 PHYSFS_permitSymbolicLinks(1);
206 char** searchpath = PHYSFS_getSearchPath();
207 for(char** i = searchpath; *i != NULL; i++)
208 log_info << "[" << *i << "] is in the search path" << std::endl;
209 PHYSFS_freeList(searchpath);
212 static void print_usage(const char* argv0)
214 fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
217 " -f, --fullscreen Run in fullscreen mode\n"
218 " -w, --window Run in window mode\n"
219 " -g, --geometry WIDTHxHEIGHT Run SuperTux in given resolution\n"
220 " -a, --aspect WIDTH:HEIGHT Run SuperTux with given aspect ratio\n"
221 " --disable-sfx Disable sound effects\n"
222 " --disable-music Disable music\n"
223 " --help Show this help message\n"
224 " --version Display SuperTux version and quit\n"
225 " --console Enable ingame scripting console\n"
226 " --noconsole Disable ingame scripting console\n"
227 " --show-fps Display framerate in levels\n"
228 " --no-show-fps Do not display framerate in levels\n"
229 " --record-demo FILE LEVEL Record a demo to FILE\n"
230 " --play-demo FILE LEVEL Play a recorded demo\n"
235 * Options that should be evaluated prior to any initializations at all go here
237 static bool pre_parse_commandline(int argc, char** argv)
239 for(int i = 1; i < argc; ++i) {
240 std::string arg = argv[i];
242 if(arg == "--help") {
243 print_usage(argv[0]);
245 } else if(arg == "--version") {
246 std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
255 * Options that should be evaluated after config is read go here
257 static bool parse_commandline(int argc, char** argv)
259 for(int i = 1; i < argc; ++i) {
260 std::string arg = argv[i];
262 if(arg == "--fullscreen" || arg == "-f") {
263 config->use_fullscreen = true;
264 } else if(arg == "--window" || arg == "-w") {
265 config->use_fullscreen = false;
266 } else if(arg == "--geometry" || arg == "-g") {
268 print_usage(argv[0]);
269 throw std::runtime_error("Need to specify a parameter for geometry switch");
271 if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
273 print_usage(argv[0]);
274 throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
276 } else if(arg == "--aspect" || arg == "-a") {
278 print_usage(argv[0]);
279 throw std::runtime_error("Need to specify a parameter for aspect switch");
281 if(sscanf(argv[++i], "%d:%d", &config->aspectwidth, &config->aspectheight)
283 print_usage(argv[0]);
284 throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
286 } else if(arg == "--show-fps") {
287 config->show_fps = true;
288 } else if(arg == "--no-show-fps") {
289 config->show_fps = false;
290 } else if(arg == "--console") {
291 config->console_enabled = true;
292 } else if(arg == "--noconsole") {
293 config->console_enabled = false;
294 } else if(arg == "--disable-sfx") {
295 config->sound_enabled = false;
296 } else if(arg == "--disable-music") {
297 config->music_enabled = false;
298 } else if(arg == "--play-demo") {
300 print_usage(argv[0]);
301 throw std::runtime_error("Need to specify a demo filename");
303 config->start_demo = argv[++i];
304 } else if(arg == "--record-demo") {
306 print_usage(argv[0]);
307 throw std::runtime_error("Need to specify a demo filename");
309 config->record_demo = argv[++i];
310 } else if(arg == "-d") {
311 config->enable_script_debugger = true;
312 } else if(arg[0] != '-') {
313 config->start_level = arg;
315 log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
323 static void init_sdl()
325 if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
326 std::stringstream msg;
327 msg << "Couldn't initialize SDL: " << SDL_GetError();
328 throw std::runtime_error(msg.str());
333 SDL_EnableUNICODE(1);
335 // wait 100ms and clear SDL event queue because sometimes we have random
336 // joystick events in the queue on startup...
339 while(SDL_PollEvent(&dummy))
343 static void init_rand()
345 config->random_seed = systemRandom.srand(config->random_seed);
347 //const char *how = config->random_seed? ", user fixed.": ", from time().";
348 //log_info << "Using random seed " << config->random_seed << how << std::endl;
353 if(texture_manager != NULL)
354 texture_manager->save_textures();
356 SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
357 SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
358 SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
359 SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
361 int flags = SDL_OPENGL;
362 if(config->use_fullscreen)
363 flags |= SDL_FULLSCREEN;
364 int width = config->screenwidth;
365 int height = config->screenheight;
368 screen = SDL_SetVideoMode(width, height, bpp, flags);
370 std::stringstream msg;
371 msg << "Couldn't set video mode (" << width << "x" << height
372 << "-" << bpp << "bpp): " << SDL_GetError();
373 throw std::runtime_error(msg.str());
376 SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
379 SDL_Surface* icon = IMG_Load_RW(
380 get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
382 SDL_WM_SetIcon(icon, 0);
383 SDL_FreeSurface(icon);
387 log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
391 // use aspect ratio to calculate logical resolution
392 if (config->aspectwidth > config->aspectheight) {
394 SCREEN_WIDTH=600*config->aspectwidth/config->aspectheight;
398 SCREEN_HEIGHT=600*config->aspectheight/config->aspectwidth;
401 // setup opengl state and transform
402 glDisable(GL_DEPTH_TEST);
403 glDisable(GL_CULL_FACE);
404 glEnable(GL_TEXTURE_2D);
406 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
408 glViewport(0, 0, screen->w, screen->h);
409 glMatrixMode(GL_PROJECTION);
411 // logical resolution here not real monitor resolution
412 glOrtho(0, SCREEN_WIDTH, SCREEN_HEIGHT, 0, -1.0, 1.0);
413 glMatrixMode(GL_MODELVIEW);
415 glTranslatef(0, 0, 0);
417 check_gl_error("Setting up view matrices");
419 if(texture_manager != NULL)
420 texture_manager->reload_textures();
422 texture_manager = new TextureManager();
425 static void init_audio()
427 sound_manager = new SoundManager();
429 sound_manager->enable_sound(config->sound_enabled);
430 sound_manager->enable_music(config->music_enabled);
433 static void quit_audio()
435 if(sound_manager != NULL) {
436 delete sound_manager;
437 sound_manager = NULL;
441 void wait_for_event(float min_delay, float max_delay)
443 assert(min_delay <= max_delay);
445 Uint32 min = (Uint32) (min_delay * 1000);
446 Uint32 max = (Uint32) (max_delay * 1000);
448 Uint32 ticks = SDL_GetTicks();
449 while(SDL_GetTicks() - ticks < min) {
451 sound_manager->update();
456 while (SDL_PollEvent(&event))
460 bool running = false;
461 ticks = SDL_GetTicks();
463 while(SDL_PollEvent(&event)) {
469 case SDL_JOYBUTTONDOWN:
470 case SDL_MOUSEBUTTONDOWN:
474 if(SDL_GetTicks() - ticks >= (max - min))
476 sound_manager->update();
482 static Uint32 last_timelog_ticks = 0;
483 static const char* last_timelog_component = 0;
485 static inline void timelog(const char* component)
487 Uint32 current_ticks = SDL_GetTicks();
489 if(last_timelog_component != 0) {
490 log_info << "Component '" << last_timelog_component << "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
493 last_timelog_ticks = current_ticks;
494 last_timelog_component = component;
497 static inline void timelog(const char* )
502 int main(int argc, char** argv)
510 if(pre_parse_commandline(argc, argv))
513 Console::instance = new Console();
514 init_physfs(argv[0]);
517 timelog("controller");
518 main_controller = new JoystickKeyboardController();
521 timelog("tinygettext");
523 timelog("commandline");
524 if(parse_commandline(argc, argv))
530 Console::instance->init_graphics();
531 timelog("scripting");
532 Scripting::init_squirrel(config->enable_script_debugger);
533 timelog("resources");
537 main_loop = new MainLoop();
538 if(config->start_level != "") {
539 // we have a normal path specified at commandline not physfs paths.
540 // So we simply mount that path here...
541 std::string dir = FileSystem::dirname(config->start_level);
542 PHYSFS_addToSearchPath(dir.c_str(), true);
544 if(config->start_level.size() > 4 &&
545 config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
547 main_loop->push_screen(new WorldMapNS::WorldMap(
548 FileSystem::basename(config->start_level)));
550 init_rand();//If level uses random eg. for
551 // rain particles before we do this:
552 std::auto_ptr<GameSession> session (
553 new GameSession(FileSystem::basename(config->start_level)));
555 config->random_seed =session->get_demo_random_seed(config->start_demo);
556 init_rand();//initialise generator with seed from session
558 if(config->start_demo != "")
559 session->play_demo(config->start_demo);
561 if(config->record_demo != "")
562 session->record_demo(config->record_demo);
563 main_loop->push_screen(session.release());
567 main_loop->push_screen(new TitleScreen());
570 //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
573 } catch(std::exception& e) {
574 log_fatal << "Unexpected exception: " << e.what() << std::endl;
577 log_fatal << "Unexpected exception" << std::endl;
593 delete main_controller;
594 main_controller = NULL;
595 delete Console::instance;
596 Console::instance = NULL;
597 Scripting::exit_squirrel();
598 delete texture_manager;
599 texture_manager = NULL;