argh, clean out copy
[supertux.git] / src / main.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
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.
10 //
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.
15 //
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
19 //  02111-1307, USA.
20 #include <config.h>
21 #include <assert.h>
22
23 #include "log.hpp"
24 #include "main.hpp"
25
26 #include <stdexcept>
27 #include <sstream>
28 #include <ctime>
29 #include <cstdlib>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <unistd.h>
33 //#include <physfs.h>
34 #include <SDL.h>
35 //#include <SDL_image.h>
36
37 #ifdef MACOSX
38 namespace supertux_apple {
39 #include <CoreFoundation/CoreFoundation.h>
40 }
41 #endif
42
43 #include <unison/video/Window.hpp>
44 #include <unison/vfs/FileSystem.hpp>
45
46 #include "gameconfig.hpp"
47 #include "resources.hpp"
48 #include "gettext.hpp"
49 #include "audio/sound_manager.hpp"
50 #include "video/surface.hpp"
51 //#include "video/texture_manager.hpp"
52 #include "video/drawing_context.hpp"
53 #include "video/glutil.hpp"
54 #include "control/joystickkeyboardcontroller.hpp"
55 #include "options_menu.hpp"
56 #include "mainloop.hpp"
57 #include "title.hpp"
58 #include "game_session.hpp"
59 #include "scripting/level.hpp"
60 #include "scripting/squirrel_util.hpp"
61 #include "file_system.hpp"
62 #include "physfs/physfs_sdl.hpp"
63 #include "random_generator.hpp"
64 #include "worldmap/worldmap.hpp"
65 #include "binreloc/binreloc.h"
66
67 namespace { DrawingContext *context_pointer; }
68 SDL_Surface *screen;
69 JoystickKeyboardController* main_controller = 0;
70 TinyGetText::DictionaryManager dictionary_manager;
71
72 int SCREEN_WIDTH;
73 int SCREEN_HEIGHT;
74
75 static void init_config()
76 {
77   config = new Config();
78   try {
79     config->load();
80   } catch(std::exception& e) {
81     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
82   }
83 }
84
85 static void init_tinygettext()
86 {
87   dictionary_manager.add_directory("locale");
88   dictionary_manager.set_charset("UTF-8");
89
90   // Config setting "locale" overrides language detection
91   if (config->locale != "") {
92     dictionary_manager.set_language( config->locale );
93   }
94 }
95
96 static void init_physfs(const char* argv0)
97 {
98   Unison::VFS::FileSystem &fs = Unison::VFS::FileSystem::get();
99   std::string application = "supertux2";
100   std::string userdir = fs.get_user_dir();
101   std::string dirsep = fs.get_dir_sep();
102   std::string writedir = userdir + "." + application;
103   fs.set_write_dir(writedir);
104   fs.mount(writedir, "/", true);
105
106   // Search for archives and add them to the search path
107   const char* archiveExt = ".zip";
108   std::vector<std::string> rc = fs.ls("/");
109   for(std::vector<std::string>::iterator iter = rc.begin(); iter != rc.end(); ++iter)
110   {
111     std::string ext = iter->substr(iter->length() - 4);
112     if(strcasecmp(ext.c_str(), archiveExt) == 0)
113     {
114       std::string dir = fs.get_real_dir(*iter);
115       fs.mount(dir + fs.get_dir_sep() + *iter, "/", true);
116     }
117   }
118
119   // when started from source dir...
120   std::string dir = fs.get_base_dir();
121   dir += "/data";
122   std::string testfname = dir;
123   testfname += "/credits.txt";
124   bool sourcedir = false;
125   FILE* f = fopen(testfname.c_str(), "r");
126   if(f) {
127     fclose(f);
128     fs.mount(dir, "/", true);
129     sourcedir = true;
130     /*if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
131       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
132     } else {
133       sourcedir = true;
134     }*/
135   }
136
137 #ifdef MACOSX
138   // when started from Application file on Mac OS X...
139   char path[PATH_MAX];
140   CFBundleRef mainBundle = CFBundleGetMainBundle();
141   assert(mainBundle != 0);
142   CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
143   assert(mainBundleURL != 0);
144   CFStringRef pathStr = CFUrlCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
145   assert(pathStr != 0);
146   CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
147   CFRelease(mainBundleURL);
148   CFRelease(pathStr);
149
150   dir = std::string(path) + "/Contents/Resources/data";
151   testfname = dir + "/credits.txt";
152   sourcedir = false;
153   f = fopen(testfname.c_str(), "r");
154   if(f) {
155     fclose(f);
156     fs.mount(dir, "/", true);
157     sourcedir = true;
158     /*if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
159       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
160     } else {
161       sourcedir = true;
162     }*/
163   }
164 #endif
165
166 #ifdef _WIN32
167   fs.mount(".\\data", "/", true);
168   //PHYSFS_addToSearchPath(".\\data", 1);
169 #endif
170
171   if(!sourcedir) {
172 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
173     std::string datadir;
174 #ifdef ENABLE_BINRELOC
175
176     char* dir;
177     br_init (NULL);
178     dir = br_find_data_dir(APPDATADIR);
179     datadir = dir;
180     free(dir);
181
182 #else
183     datadir = APPDATADIR;
184 #endif
185     datadir += "/";
186     datadir += application;
187     fs.mount(datadir, "/", true);
188     /*if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
189       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
190     }*/
191 #endif
192   }
193
194   // allow symbolic links
195   //PHYSFS_permitSymbolicLinks(1);
196   //fs.follow_sym_links(true);
197
198   //show search Path
199   std::vector<std::string> searchpath = fs.get_search_path();
200   for(std::vector<std::string>::iterator iter = searchpath.begin(); iter != searchpath.end(); ++iter)
201     log_info << "[" << *iter << "] is in the search path" << std::endl;
202   /*
203   char** searchpath = PHYSFS_getSearchPath();
204   for(char** i = searchpath; *i != NULL; i++)
205     log_info << "[" << *i << "] is in the search path" << std::endl;
206   PHYSFS_freeList(searchpath);
207   */
208
209 #if 0
210   if(!PHYSFS_init(argv0)) {
211     std::stringstream msg;
212     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
213     throw std::runtime_error(msg.str());
214   }
215
216   // Initialize physfs (this is a slightly modified version of
217   // PHYSFS_setSaneConfig
218   const char* application = "supertux2"; //instead of PACKAGE_NAME so we can coexist with MS1
219   const char* userdir = PHYSFS_getUserDir();
220   const char* dirsep = PHYSFS_getDirSeparator();
221   char* writedir = new char[strlen(userdir) + strlen(application) + 2];
222
223   // Set configuration directory
224   sprintf(writedir, "%s.%s", userdir, application);
225   if(!PHYSFS_setWriteDir(writedir)) {
226     // try to create the directory
227     char* mkdir = new char[strlen(application) + 2];
228     sprintf(mkdir, ".%s", application);
229     if(!PHYSFS_setWriteDir(userdir) || !PHYSFS_mkdir(mkdir)) {
230       std::ostringstream msg;
231       msg << "Failed creating configuration directory '"
232           << writedir << "': " << PHYSFS_getLastError();
233       delete[] writedir;
234       delete[] mkdir;
235       throw std::runtime_error(msg.str());
236     }
237     delete[] mkdir;
238
239     if(!PHYSFS_setWriteDir(writedir)) {
240       std::ostringstream msg;
241       msg << "Failed to use configuration directory '"
242           <<  writedir << "': " << PHYSFS_getLastError();
243       delete[] writedir;
244       throw std::runtime_error(msg.str());
245     }
246   }
247   PHYSFS_addToSearchPath(writedir, 0);
248   delete[] writedir;
249
250   // Search for archives and add them to the search path
251   const char* archiveExt = "zip";
252   char** rc = PHYSFS_enumerateFiles("/");
253   size_t extlen = strlen(archiveExt);
254
255   for(char** i = rc; *i != 0; ++i) {
256     size_t l = strlen(*i);
257     if((l > extlen) && ((*i)[l - extlen - 1] == '.')) {
258       const char* ext = (*i) + (l - extlen);
259       if(strcasecmp(ext, archiveExt) == 0) {
260         const char* d = PHYSFS_getRealDir(*i);
261         char* str = new char[strlen(d) + strlen(dirsep) + l + 1];
262         sprintf(str, "%s%s%s", d, dirsep, *i);
263         PHYSFS_addToSearchPath(str, 1);
264         delete[] str;
265       }
266     }
267   }
268
269   PHYSFS_freeList(rc);
270
271   // when started from source dir...
272   std::string dir = PHYSFS_getBaseDir();
273   dir += "/data";
274   std::string testfname = dir;
275   testfname += "/credits.txt";
276   bool sourcedir = false;
277   FILE* f = fopen(testfname.c_str(), "r");
278   if(f) {
279     fclose(f);
280     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
281       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
282     } else {
283       sourcedir = true;
284     }
285   }
286
287 #ifdef MACOSX
288 {
289   using namespace supertux_apple;
290
291   // when started from Application file on Mac OS X...
292   char path[PATH_MAX];
293   CFBundleRef mainBundle = CFBundleGetMainBundle();
294   assert(mainBundle != 0);
295   CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
296   assert(mainBundleURL != 0);
297   CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
298   assert(pathStr != 0);
299   CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
300   CFRelease(mainBundleURL);
301   CFRelease(pathStr);
302
303   dir = std::string(path) + "/Contents/Resources/data";
304   testfname = dir + "/credits.txt";
305   sourcedir = false;
306   f = fopen(testfname.c_str(), "r");
307   if(f) {
308     fclose(f);
309     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
310       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
311     } else {
312       sourcedir = true;
313     }
314   }
315 }
316 #endif
317
318 #ifdef _WIN32
319   PHYSFS_addToSearchPath(".\\data", 1);
320 #endif
321
322   if(!sourcedir) {
323 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
324     std::string datadir;
325 #ifdef ENABLE_BINRELOC
326
327     char* dir;
328     br_init (NULL);
329     dir = br_find_data_dir(APPDATADIR);
330     datadir = dir;
331     free(dir);
332
333 #else
334     datadir = APPDATADIR;
335 #endif
336     datadir += "/";
337     datadir += application;
338     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
339       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
340     }
341 #endif
342   }
343
344   // allow symbolic links
345   PHYSFS_permitSymbolicLinks(1);
346
347   //show search Path
348   char** searchpath = PHYSFS_getSearchPath();
349   for(char** i = searchpath; *i != NULL; i++)
350     log_info << "[" << *i << "] is in the search path" << std::endl;
351   PHYSFS_freeList(searchpath);
352 #endif
353 }
354
355 static void print_usage(const char* argv0)
356 {
357   fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
358   fprintf(stderr,
359           _("Options:\n"
360             "  -f, --fullscreen             Run in fullscreen mode\n"
361             "  -w, --window                 Run in window mode\n"
362             "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
363             "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
364             "  --disable-sfx                Disable sound effects\n"
365             "  --disable-music              Disable music\n"
366             "  --help                       Show this help message\n"
367             "  --version                    Display SuperTux version and quit\n"
368             "  --console                    Enable ingame scripting console\n"
369             "  --noconsole                  Disable ingame scripting console\n"
370             "  --show-fps                   Display framerate in levels\n"
371             "  --no-show-fps                Do not display framerate in levels\n"
372             "  --record-demo FILE LEVEL     Record a demo to FILE\n"
373             "  --play-demo FILE LEVEL       Play a recorded demo\n"
374             "\n"));
375 }
376
377 /**
378  * Options that should be evaluated prior to any initializations at all go here
379  */
380 static bool pre_parse_commandline(int argc, char** argv)
381 {
382   for(int i = 1; i < argc; ++i) {
383     std::string arg = argv[i];
384
385     if(arg == "--version") {
386       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
387       return true;
388     }
389   }
390
391   return false;
392 }
393
394 /**
395  * Options that should be evaluated after config is read go here
396  */
397 static bool parse_commandline(int argc, char** argv)
398 {
399   for(int i = 1; i < argc; ++i) {
400     std::string arg = argv[i];
401
402     if(arg == "--help") {
403       print_usage(argv[0]);
404       return true;
405     } else if(arg == "--fullscreen" || arg == "-f") {
406       config->use_fullscreen = true;
407     } else if(arg == "--window" || arg == "-w") {
408       config->use_fullscreen = false;
409     } else if(arg == "--geometry" || arg == "-g") {
410       if(i+1 >= argc) {
411         print_usage(argv[0]);
412         throw std::runtime_error("Need to specify a parameter for geometry switch");
413       }
414       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
415          != 2) {
416         print_usage(argv[0]);
417         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
418       }
419     } else if(arg == "--aspect" || arg == "-a") {
420       if(i+1 >= argc) {
421         print_usage(argv[0]);
422         throw std::runtime_error("Need to specify a parameter for aspect switch");
423       }
424       if(strcasecmp(argv[i+1], "auto") == 0) {
425         i++;
426         config->aspect_ratio = -1;
427       } else {
428         int aspect_width, aspect_height;
429         if(sscanf(argv[++i], "%d:%d", &aspect_width, &aspect_height) != 2) {
430           print_usage(argv[0]);
431           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT");
432         }
433         config->aspect_ratio = static_cast<double>(aspect_width) /
434                                static_cast<double>(aspect_height);
435       }
436     } else if(arg == "--show-fps") {
437       config->show_fps = true;
438     } else if(arg == "--no-show-fps") {
439       config->show_fps = false;
440     } else if(arg == "--console") {
441       config->console_enabled = true;
442     } else if(arg == "--noconsole") {
443       config->console_enabled = false;
444     } else if(arg == "--disable-sfx") {
445       config->sound_enabled = false;
446     } else if(arg == "--disable-music") {
447       config->music_enabled = false;
448     } else if(arg == "--play-demo") {
449       if(i+1 >= argc) {
450         print_usage(argv[0]);
451         throw std::runtime_error("Need to specify a demo filename");
452       }
453       config->start_demo = argv[++i];
454     } else if(arg == "--record-demo") {
455       if(i+1 >= argc) {
456         print_usage(argv[0]);
457         throw std::runtime_error("Need to specify a demo filename");
458       }
459       config->record_demo = argv[++i];
460     } else if(arg == "-d") {
461       config->enable_script_debugger = true;
462     } else if(arg[0] != '-') {
463       config->start_level = arg;
464     } else {
465       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
466       return true;
467     }
468   }
469
470   return false;
471 }
472
473 static void init_sdl()
474 {
475   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
476     std::stringstream msg;
477     msg << "Couldn't initialize SDL: " << SDL_GetError();
478     throw std::runtime_error(msg.str());
479   }
480   // just to be sure
481   atexit(SDL_Quit);
482
483   SDL_EnableUNICODE(1);
484
485   // wait 100ms and clear SDL event queue because sometimes we have random
486   // joystick events in the queue on startup...
487   SDL_Delay(100);
488   SDL_Event dummy;
489   while(SDL_PollEvent(&dummy))
490       ;
491 }
492
493 static void init_rand()
494 {
495   config->random_seed = systemRandom.srand(config->random_seed);
496
497   //const char *how = config->random_seed? ", user fixed.": ", from time().";
498   //log_info << "Using random seed " << config->random_seed << how << std::endl;
499 }
500
501 void init_video()
502 {
503   static int desktop_width = 0;
504   static int desktop_height = 0;
505
506 /* unfortunately only newer SDLs have these infos */
507 #if SDL_MAJOR_VERSION > 1 || SDL_MINOR_VERSION > 2 || (SDL_MINOR_VERSION == 2 && SDL_PATCHLEVEL >= 10)
508   /* find which resolution the user normally uses */
509   if(desktop_width == 0) {
510     const SDL_VideoInfo *info = SDL_GetVideoInfo();
511     desktop_width  = info->current_w;
512     desktop_height = info->current_h;
513   }
514 #endif
515
516   double aspect_ratio = config->aspect_ratio;
517
518   // try to guess aspect ratio of monitor if needed
519   if (aspect_ratio <= 0) {
520 // TODO: commented out because 
521 // 1) it tends to guess wrong if widescreen-monitors don't stretch 800x600 to fit, but just display black borders
522 // 2) aspect ratios other than 4:3 are largely untested
523 /*
524     if(config->use_fullscreen && desktop_width > 0) {
525       aspect_ratio = static_cast<double>(desktop_width) / static_cast<double>(desktop_height);
526     } else {
527 */
528       aspect_ratio = 4.0 / 3.0;
529 /*
530     }
531 */
532   }
533
534   // use aspect ratio to calculate logical resolution
535   if (aspect_ratio > 1) {
536     SCREEN_WIDTH  = static_cast<int> (600 * aspect_ratio + 0.5);
537     SCREEN_HEIGHT = 600;
538   } else {
539     SCREEN_WIDTH  = 600;
540     SCREEN_HEIGHT = static_cast<int> (600 * 1/aspect_ratio + 0.5);
541   }
542
543   context_pointer->init_renderer();
544   screen = SDL_GetVideoSurface();
545
546   Unison::Video::Window::get().set_title(PACKAGE_NAME " " PACKAGE_VERSION);
547   Unison::Video::Window::get().set_icon(Unison::Video::Surface("images/engine/icons/supertux.xpm"));
548   //SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
549
550   // set icon
551   /*
552   SDL_Surface* icon = IMG_Load_RW(
553       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
554   if(icon != 0) {
555     SDL_WM_SetIcon(icon, 0);
556     SDL_FreeSurface(icon);
557   }
558 #ifdef DEBUG
559   else {
560     log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
561   }
562 #endif
563   */
564
565   SDL_ShowCursor(0);
566
567   log_info << (config->use_fullscreen?"fullscreen ":"window ") << SCREEN_WIDTH << "x" << SCREEN_HEIGHT << " Ratio: " << aspect_ratio << "\n";
568 }
569
570 static void init_audio()
571 {
572   sound_manager = new SoundManager();
573
574   sound_manager->enable_sound(config->sound_enabled);
575   sound_manager->enable_music(config->music_enabled);
576 }
577
578 static void quit_audio()
579 {
580   if(sound_manager != NULL) {
581     delete sound_manager;
582     sound_manager = NULL;
583   }
584 }
585
586 void wait_for_event(float min_delay, float max_delay)
587 {
588   assert(min_delay <= max_delay);
589
590   Uint32 min = (Uint32) (min_delay * 1000);
591   Uint32 max = (Uint32) (max_delay * 1000);
592
593   Uint32 ticks = SDL_GetTicks();
594   while(SDL_GetTicks() - ticks < min) {
595     SDL_Delay(10);
596     sound_manager->update();
597   }
598
599   // clear event queue
600   SDL_Event event;
601   while (SDL_PollEvent(&event))
602   {}
603
604   /* Handle events: */
605   bool running = false;
606   ticks = SDL_GetTicks();
607   while(running) {
608     while(SDL_PollEvent(&event)) {
609       switch(event.type) {
610         case SDL_QUIT:
611           main_loop->quit();
612           break;
613         case SDL_KEYDOWN:
614         case SDL_JOYBUTTONDOWN:
615         case SDL_MOUSEBUTTONDOWN:
616           running = false;
617       }
618     }
619     if(SDL_GetTicks() - ticks >= (max - min))
620       running = false;
621     sound_manager->update();
622     SDL_Delay(10);
623   }
624 }
625
626 #ifdef DEBUG
627 static Uint32 last_timelog_ticks = 0;
628 static const char* last_timelog_component = 0;
629
630 static inline void timelog(const char* component)
631 {
632   Uint32 current_ticks = SDL_GetTicks();
633
634   if(last_timelog_component != 0) {
635     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
636   }
637
638   last_timelog_ticks = current_ticks;
639   last_timelog_component = component;
640 }
641 #else
642 static inline void timelog(const char* )
643 {
644 }
645 #endif
646
647 int main(int argc, char** argv)
648 {
649   int result = 0;
650
651 #ifndef NO_CATCH
652   try {
653 #endif
654
655     if(pre_parse_commandline(argc, argv))
656       return 0;
657
658     Console::instance = new Console();
659     init_physfs(argv[0]);
660     init_sdl();
661
662     timelog("controller");
663     main_controller = new JoystickKeyboardController();
664     timelog("config");
665     init_config();
666     timelog("tinygettext");
667     init_tinygettext();
668     timelog("commandline");
669     if(parse_commandline(argc, argv))
670       return 0;
671     timelog("audio");
672     init_audio();
673     timelog("video");
674     DrawingContext context;
675     context_pointer = &context;
676     init_video();
677     Console::instance->init_graphics();
678     timelog("scripting");
679     Scripting::init_squirrel(config->enable_script_debugger);
680     timelog("resources");
681     load_shared();
682     timelog(0);
683
684     main_loop = new MainLoop();
685     if(config->start_level != "") {
686       // we have a normal path specified at commandline not physfs paths.
687       // So we simply mount that path here...
688       std::string dir = FileSystem::dirname(config->start_level);
689       Unison::VFS::FileSystem::get().mount(dir, "/", true);
690       //PHYSFS_addToSearchPath(dir.c_str(), true);
691
692       if(config->start_level.size() > 4 &&
693               config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
694           init_rand();
695           main_loop->push_screen(new WorldMapNS::WorldMap(
696                       FileSystem::basename(config->start_level)));
697       } else {
698         init_rand();//If level uses random eg. for
699         // rain particles before we do this:
700         std::auto_ptr<GameSession> session (
701                 new GameSession(FileSystem::basename(config->start_level)));
702
703         config->random_seed =session->get_demo_random_seed(config->start_demo);
704         init_rand();//initialise generator with seed from session
705
706         if(config->start_demo != "")
707           session->play_demo(config->start_demo);
708
709         if(config->record_demo != "")
710           session->record_demo(config->record_demo);
711         main_loop->push_screen(session.release());
712       }
713     } else {
714       init_rand();
715       main_loop->push_screen(new TitleScreen());
716     }
717
718     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
719     main_loop->run(context);
720 #ifndef NO_CATCH
721   } catch(std::exception& e) {
722     log_fatal << "Unexpected exception: " << e.what() << std::endl;
723     result = 1;
724   } catch(...) {
725     log_fatal << "Unexpected exception" << std::endl;
726     result = 1;
727   }
728 #endif
729
730   delete main_loop;
731   main_loop = NULL;
732
733   unload_shared();
734   quit_audio();
735
736   if(config)
737     config->save();
738   delete config;
739   config = NULL;
740   delete main_controller;
741   main_controller = NULL;
742   delete Console::instance;
743   Console::instance = NULL;
744   Scripting::exit_squirrel();
745   //delete texture_manager;
746   //texture_manager = NULL;
747   SDL_Quit();
748   //PHYSFS_deinit();
749
750   return result;
751 }