Create and use --print-datadir on supertux2.exe to determine the location of the...
[supertux.git] / src / supertux / main.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include <config.h>
18 #include <version.h>
19
20 #include <SDL_image.h>
21 #include <physfs.h>
22 #include <iostream>
23 #include <binreloc.h>
24 #include <tinygettext/log.hpp>
25 #include <boost/format.hpp>
26 #include <unistd.h>
27
28 #include "supertux/main.hpp"
29
30 #ifdef MACOSX
31 namespace supertux_apple {
32 #  include <CoreFoundation/CoreFoundation.h>
33 } // namespace supertux_apple
34 #endif
35
36 #include "addon/addon_manager.hpp"
37 #include "audio/sound_manager.hpp"
38 #include "control/joystickkeyboardcontroller.hpp"
39 #include "math/random_generator.hpp"
40 #include "physfs/ifile_stream.hpp"
41 #include "physfs/physfs_sdl.hpp"
42 #include "physfs/physfs_file_system.hpp"
43 #include "scripting/squirrel_util.hpp"
44 #include "supertux/gameconfig.hpp"
45 #include "supertux/globals.hpp"
46 #include "supertux/player_status.hpp"
47 #include "supertux/screen_manager.hpp"
48 #include "supertux/resources.hpp"
49 #include "supertux/title_screen.hpp"
50 #include "util/file_system.hpp"
51 #include "util/gettext.hpp"
52 #include "video/drawing_context.hpp"
53 #include "worldmap/worldmap.hpp"
54
55 namespace { DrawingContext *context_pointer; }
56
57 #ifdef _WIN32
58 # define WRITEDIR_NAME PACKAGE_NAME
59 #else
60 # define WRITEDIR_NAME "." PACKAGE_NAME
61 #endif
62
63 void 
64 Main::init_config()
65 {
66   g_config = new Config();
67   try {
68     g_config->load();
69   } catch(std::exception& e) {
70     log_info << "Couldn't load config file: " << e.what() << ", using default settings" << std::endl;
71   }
72 }
73
74 void
75 Main::init_tinygettext()
76 {
77   dictionary_manager = new tinygettext::DictionaryManager();
78   tinygettext::Log::set_log_info_callback(0);
79   dictionary_manager->set_filesystem(std::auto_ptr<tinygettext::FileSystem>(new PhysFSFileSystem));
80
81   dictionary_manager->add_directory("locale");
82   dictionary_manager->set_charset("UTF-8");
83
84   // Config setting "locale" overrides language detection
85   if (g_config->locale != "") 
86   {
87     dictionary_manager->set_language(tinygettext::Language::from_name(g_config->locale));
88   }
89 }
90
91 void
92 Main::init_physfs(const char* argv0)
93 {
94   if(!PHYSFS_init(argv0)) {
95     std::stringstream msg;
96     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
97     throw std::runtime_error(msg.str());
98   }
99
100   // allow symbolic links
101   PHYSFS_permitSymbolicLinks(1);
102
103   // Initialize physfs (this is a slightly modified version of
104   // PHYSFS_setSaneConfig)
105   const char *env_writedir;
106   std::string writedir;
107
108   if ((env_writedir = getenv("SUPERTUX2_USER_DIR")) != NULL) {
109     writedir = env_writedir;
110     if(!PHYSFS_setWriteDir(writedir.c_str())) {
111       std::ostringstream msg;
112       msg << "Failed to use configuration directory '"
113           <<  writedir << "': " << PHYSFS_getLastError();
114       throw std::runtime_error(msg.str());
115     }
116
117   } else {
118     std::string userdir = PHYSFS_getUserDir();
119
120     // Set configuration directory
121     writedir = userdir + WRITEDIR_NAME;
122     if(!PHYSFS_setWriteDir(writedir.c_str())) {
123       // try to create the directory
124       if(!PHYSFS_setWriteDir(userdir.c_str()) || !PHYSFS_mkdir(WRITEDIR_NAME)) {
125         std::ostringstream msg;
126         msg << "Failed creating configuration directory '"
127             << writedir << "': " << PHYSFS_getLastError();
128         throw std::runtime_error(msg.str());
129       }
130
131       if(!PHYSFS_setWriteDir(writedir.c_str())) {
132         std::ostringstream msg;
133         msg << "Failed to use configuration directory '"
134             <<  writedir << "': " << PHYSFS_getLastError();
135         throw std::runtime_error(msg.str());
136       }
137     }
138   }
139   PHYSFS_addToSearchPath(writedir.c_str(), 0);
140
141   // when started from source dir...
142   std::string dir = PHYSFS_getBaseDir();
143   if (dir[dir.length() - 1] != '/')
144     dir += "/";
145   dir += "data";
146   std::string testfname = dir;
147   testfname += "/credits.txt";
148   bool sourcedir = false;
149   FILE* f = fopen(testfname.c_str(), "r");
150   if(f) {
151     fclose(f);
152     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
153       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
154     } else {
155       sourcedir = true;
156     }
157   }
158
159 #ifdef MACOSX
160   {
161     using namespace supertux_apple;
162
163     // when started from Application file on Mac OS X...
164     char path[PATH_MAX];
165     CFBundleRef mainBundle = CFBundleGetMainBundle();
166     assert(mainBundle != 0);
167     CFURLRef mainBundleURL = CFBundleCopyBundleURL(mainBundle);
168     assert(mainBundleURL != 0);
169     CFStringRef pathStr = CFURLCopyFileSystemPath(mainBundleURL, kCFURLPOSIXPathStyle);
170     assert(pathStr != 0);
171     CFStringGetCString(pathStr, path, PATH_MAX, kCFStringEncodingUTF8);
172     CFRelease(mainBundleURL);
173     CFRelease(pathStr);
174
175     dir = std::string(path) + "/Contents/Resources/data";
176     testfname = dir + "/credits.txt";
177     sourcedir = false;
178     f = fopen(testfname.c_str(), "r");
179     if(f) {
180       fclose(f);
181       if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
182         log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
183       } else {
184         sourcedir = true;
185       }
186     }
187   }
188 #endif
189
190 #ifdef _WIN32
191   PHYSFS_addToSearchPath(".\\data", 1);
192 #endif
193
194   if(!sourcedir) {
195     std::string datadir = PHYSFS_getBaseDir();
196     datadir = datadir.substr(0, datadir.rfind(INSTALL_SUBDIR_BIN));
197     datadir += "/" INSTALL_SUBDIR_SHARE;
198 #ifdef ENABLE_BINRELOC
199
200     char* dir;
201     br_init (NULL);
202     dir = br_find_data_dir(datadir.c_str());
203     datadir = dir;
204     free(dir);
205
206 #endif
207     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
208       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
209     }
210   }
211
212   //show search Path
213   char** searchpath = PHYSFS_getSearchPath();
214   for(char** i = searchpath; *i != NULL; i++)
215     log_info << "[" << *i << "] is in the search path" << std::endl;
216   PHYSFS_freeList(searchpath);
217 }
218
219 void
220 Main::print_usage(const char* argv0)
221 {
222   std::string default_user_data_dir =
223       std::string(PHYSFS_getUserDir()) + WRITEDIR_NAME;
224
225   std::cerr << boost::format(_(
226                  "\n"
227                  "Usage: %s [OPTIONS] [LEVELFILE]\n\n"
228                  "Options:\n"
229                  "  -f, --fullscreen             Run in fullscreen mode\n"
230                  "  -w, --window                 Run in window mode\n"
231                  "  -g, --geometry WIDTHxHEIGHT  Run SuperTux in given resolution\n"
232                  "  -a, --aspect WIDTH:HEIGHT    Run SuperTux with given aspect ratio\n"
233                  "  -d, --default                Reset video settings to default values\n"
234                  "  --renderer RENDERER          Use sdl, opengl, or auto to render\n"
235                  "  --disable-sfx                Disable sound effects\n"
236                  "  --disable-music              Disable music\n"
237                  "  -h, --help                   Show this help message and quit\n"
238                  "  -v, --version                Show SuperTux version and quit\n"
239                  "  --console                    Enable ingame scripting console\n"
240                  "  --noconsole                  Disable ingame scripting console\n"
241                  "  --show-fps                   Display framerate in levels\n"
242                  "  --no-show-fps                Do not display framerate in levels\n"
243                  "  --record-demo FILE LEVEL     Record a demo to FILE\n"
244                  "  --play-demo FILE LEVEL       Play a recorded demo\n"
245                  "  -s, --debug-scripts          Enable script debugger.\n"
246                  "  --print-datadir              Print supertux's primary data directory.\n"
247                  "\n"
248                  "Environment variables:\n"
249                  "  SUPERTUX2_USER_DIR           Directory for user data (savegames, etc.);\n"
250                  "                               default %s\n"
251                  "\n"
252                  ))
253             % argv0 % default_user_data_dir
254             << std::flush;
255 }
256
257 /**
258  * Options that should be evaluated prior to any initializations at all go here
259  */
260 bool
261 Main::pre_parse_commandline(int argc, char** argv)
262 {
263   for(int i = 1; i < argc; ++i) {
264     std::string arg = argv[i];
265
266     if(arg == "--version" || arg == "-v") {
267       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
268       return true;
269     }
270     if(arg == "--help" || arg == "-h") {
271       print_usage(argv[0]);
272       return true;
273     }
274     if(arg == "--print-datadir") {
275       /*
276        * Print the datadir searchpath to stdout, one path per
277        * line. Then exit. Intended for use by the supertux-editor.
278        */
279       char **sp;
280       char *writeptr;
281       ssize_t write_ret;
282       size_t sp_index;
283       sp = PHYSFS_getSearchPath();
284       if (sp)
285         for (sp_index = 0; sp[sp_index]; sp_index ++)
286           {
287             writeptr = sp[sp_index];
288             write_ret = 0;
289             while (*writeptr)
290               {
291                 write_ret = write(STDOUT_FILENO, writeptr, strlen(writeptr));
292                 if (write_ret == -1)
293                   break;
294                 writeptr += write_ret;
295               }
296             write(STDOUT_FILENO, "\n", 1);
297             /* std::cout << sp[sp_index] << std::endl; */
298           }
299       PHYSFS_freeList(sp);
300       return true;
301     }
302   }
303
304   return false;
305 }
306
307 /**
308  * Options that should be evaluated after config is read go here
309  */
310 bool
311 Main::parse_commandline(int argc, char** argv)
312 {
313   for(int i = 1; i < argc; ++i) {
314     std::string arg = argv[i];
315
316     if(arg == "--fullscreen" || arg == "-f") {
317       g_config->use_fullscreen = true;
318     } else if(arg == "--default" || arg == "-d") {
319       g_config->use_fullscreen = false;
320       
321       g_config->window_size     = Size(800, 600);
322       g_config->fullscreen_size = Size(800, 600);
323       g_config->aspect_size     = Size(0, 0);  // auto detect
324       
325     } else if(arg == "--window" || arg == "-w") {
326       g_config->use_fullscreen = false;
327     } else if(arg == "--geometry" || arg == "-g") {
328       i += 1;
329       if(i >= argc) 
330       {
331         print_usage(argv[0]);
332         throw std::runtime_error("Need to specify a size (WIDTHxHEIGHT) for geometry argument");
333       } 
334       else 
335       {
336         int width, height;
337         if (sscanf(argv[i], "%dx%d", &width, &height) != 2)
338         {
339           print_usage(argv[0]);
340           throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
341         }
342         else
343         {
344           g_config->window_size     = Size(width, height);
345           g_config->fullscreen_size = Size(width, height);
346         }
347       }
348     } else if(arg == "--aspect" || arg == "-a") {
349       i += 1;
350       if(i >= argc) 
351       {
352         print_usage(argv[0]);
353         throw std::runtime_error("Need to specify a ratio (WIDTH:HEIGHT) for aspect ratio");
354       } 
355       else 
356       {
357         int aspect_width  = 0;
358         int aspect_height = 0;
359         if (strcmp(argv[i], "auto") == 0)
360         {
361           aspect_width  = 0;
362           aspect_height = 0;
363         }
364         else if (sscanf(argv[i], "%d:%d", &aspect_width, &aspect_height) != 2) 
365         {
366           print_usage(argv[0]);
367           throw std::runtime_error("Invalid aspect spec, should be WIDTH:HEIGHT or auto");
368         }
369         else 
370         {
371           float aspect_ratio = static_cast<float>(aspect_width) / static_cast<float>(aspect_height);
372
373           // use aspect ratio to calculate logical resolution
374           if (aspect_ratio > 1) {
375             g_config->aspect_size = Size(static_cast<int>(600 * aspect_ratio + 0.5),
376                                          600);
377           } else {
378             g_config->aspect_size = Size(600, 
379                                          static_cast<int>(600 * 1/aspect_ratio + 0.5));
380           }
381         }
382       }
383     } else if(arg == "--renderer") {
384       i += 1;
385       if(i >= argc) 
386       {
387         print_usage(argv[0]);
388         throw std::runtime_error("Need to specify a renderer for renderer argument");
389       } 
390       else 
391       {
392         g_config->video = VideoSystem::get_video_system(argv[i]);
393       }
394     } else if(arg == "--show-fps") {
395       g_config->show_fps = true;
396     } else if(arg == "--no-show-fps") {
397       g_config->show_fps = false;
398     } else if(arg == "--console") {
399       g_config->console_enabled = true;
400     } else if(arg == "--noconsole") {
401       g_config->console_enabled = false;
402     } else if(arg == "--disable-sfx") {
403       g_config->sound_enabled = false;
404     } else if(arg == "--disable-music") {
405       g_config->music_enabled = false;
406     } else if(arg == "--play-demo") {
407       if(i+1 >= argc) {
408         print_usage(argv[0]);
409         throw std::runtime_error("Need to specify a demo filename");
410       }
411       g_config->start_demo = argv[++i];
412     } else if(arg == "--record-demo") {
413       if(i+1 >= argc) {
414         print_usage(argv[0]);
415         throw std::runtime_error("Need to specify a demo filename");
416       }
417       g_config->record_demo = argv[++i];
418     } else if(arg == "--debug-scripts" || arg == "-s") {
419       g_config->enable_script_debugger = true;
420     } else if(arg[0] != '-') {
421       g_config->start_level = arg;
422     } else {
423       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
424       return true;
425     }
426   }
427
428   return false;
429 }
430
431 void
432 Main::init_sdl()
433 {
434   if(SDL_Init(SDL_INIT_TIMER | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0) {
435     std::stringstream msg;
436     msg << "Couldn't initialize SDL: " << SDL_GetError();
437     throw std::runtime_error(msg.str());
438   }
439   // just to be sure
440   atexit(SDL_Quit);
441
442   SDL_EnableUNICODE(1);
443
444   // wait 100ms and clear SDL event queue because sometimes we have random
445   // joystick events in the queue on startup...
446   SDL_Delay(100);
447   SDL_Event dummy;
448   while(SDL_PollEvent(&dummy))
449     ;
450 }
451
452 void
453 Main::init_rand()
454 {
455   g_config->random_seed = gameRandom.srand(g_config->random_seed);
456
457   graphicsRandom.srand(0);
458
459   //const char *how = config->random_seed? ", user fixed.": ", from time().";
460   //log_info << "Using random seed " << config->random_seed << how << std::endl;
461 }
462
463 void
464 Main::init_video()
465 {
466   // FIXME: Add something here
467   SCREEN_WIDTH  = 800;
468   SCREEN_HEIGHT = 600;
469
470   context_pointer->init_renderer();
471   g_screen = SDL_GetVideoSurface();
472
473   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
474
475   // set icon
476 #ifdef MACOSX
477   const char* icon_fname = "images/engine/icons/supertux-256x256.png";
478 #else
479   const char* icon_fname = "images/engine/icons/supertux.xpm";
480 #endif
481   SDL_Surface* icon;
482   try {
483     icon = IMG_Load_RW(get_physfs_SDLRWops(icon_fname), true);
484   } catch (const std::runtime_error& err) {
485     icon = 0;
486     log_warning << "Couldn't load icon '" << icon_fname << "': " << err.what() << std::endl;
487   }
488   if(icon != 0) {
489     SDL_WM_SetIcon(icon, 0);
490     SDL_FreeSurface(icon);
491   }
492   else {
493     log_warning << "Couldn't load icon '" << icon_fname << "'" << std::endl;
494   }
495
496   SDL_ShowCursor(0);
497
498   log_info << (g_config->use_fullscreen?"fullscreen ":"window ")
499            << " Window: "     << g_config->window_size
500            << " Fullscreen: " << g_config->fullscreen_size
501            << " Area: "       << g_config->aspect_size << std::endl;
502 }
503
504 void
505 Main::init_audio()
506 {
507   sound_manager = new SoundManager();
508
509   sound_manager->enable_sound(g_config->sound_enabled);
510   sound_manager->enable_music(g_config->music_enabled);
511 }
512
513 void
514 Main::quit_audio()
515 {
516   if(sound_manager != NULL) {
517     delete sound_manager;
518     sound_manager = NULL;
519   }
520 }
521
522 void
523 Main::wait_for_event(float min_delay, float max_delay)
524 {
525   assert(min_delay <= max_delay);
526
527   Uint32 min = (Uint32) (min_delay * 1000);
528   Uint32 max = (Uint32) (max_delay * 1000);
529
530   Uint32 ticks = SDL_GetTicks();
531   while(SDL_GetTicks() - ticks < min) {
532     SDL_Delay(10);
533     sound_manager->update();
534   }
535
536   // clear event queue
537   SDL_Event event;
538   while (SDL_PollEvent(&event))
539   {}
540
541   /* Handle events: */
542   bool running = false;
543   ticks = SDL_GetTicks();
544   while(running) {
545     while(SDL_PollEvent(&event)) {
546       switch(event.type) {
547         case SDL_QUIT:
548           g_screen_manager->quit();
549           break;
550         case SDL_KEYDOWN:
551         case SDL_JOYBUTTONDOWN:
552         case SDL_MOUSEBUTTONDOWN:
553           running = false;
554       }
555     }
556     if(SDL_GetTicks() - ticks >= (max - min))
557       running = false;
558     sound_manager->update();
559     SDL_Delay(10);
560   }
561 }
562
563 static Uint32 last_timelog_ticks = 0;
564 static const char* last_timelog_component = 0;
565
566 static inline void timelog(const char* component)
567 {
568   Uint32 current_ticks = SDL_GetTicks();
569
570   if(last_timelog_component != 0) {
571     log_info << "Component '" << last_timelog_component <<  "' finished after " << (current_ticks - last_timelog_ticks) / 1000.0 << " seconds" << std::endl;
572   }
573
574   last_timelog_ticks = current_ticks;
575   last_timelog_component = component;
576 }
577
578 int
579 Main::run(int argc, char** argv)
580 {
581   int result = 0;
582
583   try {
584     /* Do this before pre_parse_commandline, because --help now shows the
585      * default user data dir. */
586     init_physfs(argv[0]);
587
588     if(pre_parse_commandline(argc, argv))
589       return 0;
590
591     Console::instance = new Console();
592     init_sdl();
593
594     timelog("controller");
595     g_jk_controller = new JoystickKeyboardController();
596
597     timelog("config");
598     init_config();
599
600     timelog("addons");
601     AddonManager::get_instance().load_addons();
602
603     timelog("tinygettext");
604     init_tinygettext();
605
606     timelog("commandline");
607     if(parse_commandline(argc, argv))
608       return 0;
609
610     timelog("audio");
611     init_audio();
612
613     timelog("video");
614     DrawingContext context;
615     context_pointer = &context;
616     init_video();
617
618     Console::instance->init_graphics();
619
620     timelog("scripting");
621     scripting::init_squirrel(g_config->enable_script_debugger);
622
623     timelog("resources");
624     Resources::load_shared();
625
626     timelog(0);
627
628     const std::auto_ptr<PlayerStatus> default_playerstatus(new PlayerStatus());
629
630     g_screen_manager = new ScreenManager();
631
632     init_rand();
633
634     if(g_config->start_level != "") {
635       // we have a normal path specified at commandline, not a physfs path.
636       // So we simply mount that path here...
637       std::string dir = FileSystem::dirname(g_config->start_level);
638       log_debug << "Adding dir: " << dir << std::endl;
639       PHYSFS_addToSearchPath(dir.c_str(), true);
640
641       if(g_config->start_level.size() > 4 &&
642          g_config->start_level.compare(g_config->start_level.size() - 5, 5, ".stwm") == 0) {
643         g_screen_manager->push_screen(new worldmap::WorldMap(
644                                  FileSystem::basename(g_config->start_level), default_playerstatus.get()));
645       } else {
646         std::auto_ptr<GameSession> session (
647           new GameSession(FileSystem::basename(g_config->start_level), default_playerstatus.get()));
648
649         g_config->random_seed =session->get_demo_random_seed(g_config->start_demo);
650         init_rand();//initialise generator with seed from session
651
652         if(g_config->start_demo != "")
653           session->play_demo(g_config->start_demo);
654
655         if(g_config->record_demo != "")
656           session->record_demo(g_config->record_demo);
657         g_screen_manager->push_screen(session.release());
658       }
659     } else {
660       g_screen_manager->push_screen(new TitleScreen(default_playerstatus.get()));
661     }
662
663     g_screen_manager->run(context);
664   } catch(std::exception& e) {
665     log_fatal << "Unexpected exception: " << e.what() << std::endl;
666     result = 1;
667   } catch(...) {
668     log_fatal << "Unexpected exception" << std::endl;
669     result = 1;
670   }
671
672   delete g_screen_manager;
673   g_screen_manager = NULL;
674
675   Resources::unload_shared();
676   quit_audio();
677
678   if(g_config)
679     g_config->save();
680   delete g_config;
681   g_config = NULL;
682   delete g_jk_controller;
683   g_jk_controller = NULL;
684   delete Console::instance;
685   Console::instance = NULL;
686   scripting::exit_squirrel();
687   delete texture_manager;
688   texture_manager = NULL;
689   SDL_Quit();
690   PHYSFS_deinit();
691
692   return result;
693 }
694
695 /* EOF */