Disable scripting console and fps display via command line.
[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 <time.h>
29 #include <stdlib.h>
30 #include <sys/stat.h>
31 #include <sys/types.h>
32 #include <dirent.h>
33 #include <unistd.h>
34 #include <assert.h>
35 #include <physfs.h>
36 #include <SDL.h>
37 #include <SDL_image.h>
38 #include <GL/gl.h>
39
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"
50 #include "title.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"
59
60 SDL_Surface* screen = 0;
61 JoystickKeyboardController* main_controller = 0;
62 TinyGetText::DictionaryManager dictionary_manager;
63
64 static void init_config()
65 {
66   config = new Config();
67   try {
68     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 static void init_tinygettext()
75 {
76   dictionary_manager.add_directory("locale");
77   dictionary_manager.set_charset("UTF-8");
78 }
79
80 static void init_physfs(const char* argv0)
81 {
82   if(!PHYSFS_init(argv0)) {
83     std::stringstream msg;
84     msg << "Couldn't initialize physfs: " << PHYSFS_getLastError();
85     throw std::runtime_error(msg.str());
86   }
87
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];
94
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();
105       delete[] writedir;
106       delete[] mkdir;
107       throw std::runtime_error(msg.str());
108     }
109     delete[] mkdir;
110
111     if(!PHYSFS_setWriteDir(writedir)) {
112       std::ostringstream msg;
113       msg << "Failed to use configuration directory '"
114           <<  writedir << "': " << PHYSFS_getLastError();
115       delete[] writedir;
116       throw std::runtime_error(msg.str());
117     }
118   }
119   PHYSFS_addToSearchPath(writedir, 0);
120   delete[] writedir;
121
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);
126
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);
136         delete[] str;
137       }
138     }
139   }
140
141   PHYSFS_freeList(rc);
142
143   // when started from source dir...
144   std::string dir = PHYSFS_getBaseDir();
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   // 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";
164   sourcedir = false;
165   f = fopen(testfname.c_str(), "r");
166   if(f) {
167     fclose(f);
168     if(!PHYSFS_addToSearchPath(dir.c_str(), 1)) {
169       log_warning << "Couldn't add '" << dir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
170     } else {
171       sourcedir = true;
172     }
173   }
174 #endif
175
176   if(!sourcedir) {
177 #if defined(APPDATADIR) || defined(ENABLE_BINRELOC)
178     std::string datadir;
179 #ifdef ENABLE_BINRELOC
180
181     char* dir;
182     br_init (NULL); 
183     dir = br_find_data_dir(APPDATADIR); 
184     datadir = dir;
185     datadir += "/" PACKAGE_NAME;
186     free(dir); 
187
188 #else
189     datadir = APPDATADIR;
190 #endif
191     if(!PHYSFS_addToSearchPath(datadir.c_str(), 1)) {
192       log_warning << "Couldn't add '" << datadir << "' to physfs searchpath: " << PHYSFS_getLastError() << std::endl;
193     }
194 #endif
195   }
196
197   // allow symbolic links
198   PHYSFS_permitSymbolicLinks(1);
199
200   //show search Path
201   for(char** i = PHYSFS_getSearchPath(); *i != NULL; i++)
202     log_info << "[" << *i << "] is in the search path" << std::endl;
203 }
204
205 static void print_usage(const char* argv0)
206 {
207   fprintf(stderr, _("Usage: %s [OPTIONS] [LEVELFILE]\n\n"), argv0);
208   fprintf(stderr,
209           _("Options:\n"
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"
223             "\n"));
224 }
225
226 /**
227  * Options that should be evaluated prior to any initializations at all go here
228  */
229 static bool pre_parse_commandline(int argc, char** argv)
230 {
231   for(int i = 1; i < argc; ++i) {
232     std::string arg = argv[i];
233
234     if(arg == "--help") {
235       print_usage(argv[0]);
236       return true;
237     } else if(arg == "--version") {
238       std::cout << PACKAGE_NAME << " " << PACKAGE_VERSION << std::endl;
239       return true;
240     }
241   }
242
243   return false;
244 }
245
246 /**
247  * Options that should be evaluated after config is read go here
248  */
249 static bool parse_commandline(int argc, char** argv)
250 {
251   for(int i = 1; i < argc; ++i) {
252     std::string arg = argv[i];
253
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") {
259       if(i+1 >= argc) {
260         print_usage(argv[0]);
261         throw std::runtime_error("Need to specify a parameter for geometry switch");
262       }
263       if(sscanf(argv[++i], "%dx%d", &config->screenwidth, &config->screenheight)
264          != 2) {
265         print_usage(argv[0]);
266         throw std::runtime_error("Invalid geometry spec, should be WIDTHxHEIGHT");
267       }
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") {
281       if(i+1 >= argc) {
282         print_usage(argv[0]);
283         throw std::runtime_error("Need to specify a demo filename");
284       }
285       config->start_demo = argv[++i];
286     } else if(arg == "--record-demo") {
287       if(i+1 >= argc) {
288         print_usage(argv[0]);
289         throw std::runtime_error("Need to specify a demo filename");
290       }
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;
296     } else {
297       log_warning << "Unknown option '" << arg << "'. Use --help to see a list of options" << std::endl;
298       return true;
299     }
300   }
301
302   return false;
303 }
304
305 static void init_sdl()
306 {
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());
311   }
312   // just to be sure
313   atexit(SDL_Quit);
314
315   SDL_EnableUNICODE(1);
316
317   // wait 100ms and clear SDL event queue because sometimes we have random
318   // joystick events in the queue on startup...
319   SDL_Delay(100);
320   SDL_Event dummy;
321   while(SDL_PollEvent(&dummy))
322       ;
323 }
324
325 static void init_rand()
326 {
327   const char *how = config->random_seed? ", user fixed.": ", from time().";
328
329   config->random_seed = systemRandom.srand(config->random_seed);
330
331   log_info << "Using random seed " << config->random_seed << how << std::endl;
332 }
333
334 void init_video()
335 {
336   if(texture_manager != NULL)
337     texture_manager->save_textures();
338
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);
343
344   int flags = SDL_OPENGL;
345   if(config->use_fullscreen)
346     flags |= SDL_FULLSCREEN;
347   int width = config->screenwidth;
348   int height = config->screenheight;
349   int bpp = 0;
350
351   screen = SDL_SetVideoMode(width, height, bpp, flags);
352   if(screen == 0) {
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());
357   }
358
359   SDL_WM_SetCaption(PACKAGE_NAME " " PACKAGE_VERSION, 0);
360
361   // set icon
362   SDL_Surface* icon = IMG_Load_RW(
363       get_physfs_SDLRWops("images/engine/icons/supertux.xpm"), true);
364   if(icon != 0) {
365     SDL_WM_SetIcon(icon, 0);
366     SDL_FreeSurface(icon);
367   }
368 #ifdef DEBUG
369   else {
370     log_warning << "Couldn't find icon 'images/engine/icons/supertux.xpm'" << std::endl;
371   }
372 #endif
373
374   // setup opengl state and transform
375   glDisable(GL_DEPTH_TEST);
376   glDisable(GL_CULL_FACE);
377   glEnable(GL_TEXTURE_2D);
378   glEnable(GL_BLEND);
379   glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
380
381   glViewport(0, 0, screen->w, screen->h);
382   glMatrixMode(GL_PROJECTION);
383   glLoadIdentity();
384   // logical resolution here not real monitor resolution
385   glOrtho(0, 800, 600, 0, -1.0, 1.0);
386   glMatrixMode(GL_MODELVIEW);
387   glLoadIdentity();
388   glTranslatef(0, 0, 0);
389
390   check_gl_error("Setting up view matrices");
391
392   if(texture_manager != NULL)
393     texture_manager->reload_textures();
394   else
395     texture_manager = new TextureManager();
396 }
397
398 static void init_audio()
399 {
400   sound_manager = new SoundManager();
401
402   sound_manager->enable_sound(config->sound_enabled);
403   sound_manager->enable_music(config->music_enabled);
404 }
405
406 static void quit_audio()
407 {
408   if(sound_manager != NULL) {
409     delete sound_manager;
410     sound_manager = NULL;
411   }
412 }
413
414 void wait_for_event(float min_delay, float max_delay)
415 {
416   assert(min_delay <= max_delay);
417
418   Uint32 min = (Uint32) (min_delay * 1000);
419   Uint32 max = (Uint32) (max_delay * 1000);
420
421   Uint32 ticks = SDL_GetTicks();
422   while(SDL_GetTicks() - ticks < min) {
423     SDL_Delay(10);
424     sound_manager->update();
425   }
426
427   // clear event queue
428   SDL_Event event;
429   while (SDL_PollEvent(&event))
430   {}
431
432   /* Handle events: */
433   bool running = false;
434   ticks = SDL_GetTicks();
435   while(running) {
436     while(SDL_PollEvent(&event)) {
437       switch(event.type) {
438         case SDL_QUIT:
439           main_loop->quit();
440           break;
441         case SDL_KEYDOWN:
442         case SDL_JOYBUTTONDOWN:
443         case SDL_MOUSEBUTTONDOWN:
444           running = false;
445       }
446     }
447     if(SDL_GetTicks() - ticks >= (max - min))
448       running = false;
449     sound_manager->update();
450     SDL_Delay(10);
451   }
452 }
453
454 #ifdef DEBUG
455 static Uint32 last_timelog_ticks = 0;
456 static const char* last_timelog_component = 0;
457
458 static inline void timelog(const char* component)
459 {
460   Uint32 current_ticks = SDL_GetTicks();
461
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;
464   }
465
466   last_timelog_ticks = current_ticks;
467   last_timelog_component = component;
468 }
469 #else
470 static inline void timelog(const char* )
471 {
472 }
473 #endif
474
475 int main(int argc, char** argv)
476 {
477   int result = 0;
478
479   try {
480
481     if(pre_parse_commandline(argc, argv))
482       return 0;
483
484     Console::instance = new Console();
485     init_physfs(argv[0]);
486     init_sdl();
487
488     timelog("controller");
489     main_controller = new JoystickKeyboardController();
490     timelog("config");
491     init_config();
492     timelog("tinygettext");
493     init_tinygettext();
494     timelog("commandline");
495     if(parse_commandline(argc, argv))
496       return 0;
497     timelog("audio");
498     init_audio();
499     timelog("video");
500     init_video();
501     Console::instance->init_graphics();
502     timelog("scripting");
503     Scripting::init_squirrel(config->enable_script_debugger);
504     timelog("resources");
505     load_shared();
506     timelog(0);
507
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);
514
515       if(config->start_level.size() > 4 &&
516               config->start_level.compare(config->start_level.size() - 5, 5, ".stwm") == 0) {
517           init_rand();
518           main_loop->push_screen(new WorldMapNS::WorldMap(
519                       FileSystem::basename(config->start_level)));
520       } else {
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)));
525
526         config->random_seed =session->get_demo_random_seed(config->start_demo);
527         init_rand();//initialise generator with seed from session
528
529         if(config->start_demo != "")
530           session->play_demo(config->start_demo);
531
532         if(config->record_demo != "")
533           session->record_demo(config->record_demo);
534         main_loop->push_screen(session.release());
535       }
536     } else {
537       init_rand();
538       main_loop->push_screen(new TitleScreen());
539     }
540
541     //init_rand(); PAK: this call might subsume the above 3, but I'm chicken!
542     main_loop->run();
543   } catch(std::exception& e) {
544     log_fatal << "Unexpected exception: " << e.what() << std::endl;
545     result = 1;
546   } catch(...) {
547     log_fatal << "Unexpected exception" << std::endl;
548     result = 1;
549   }
550
551   delete main_loop;
552   main_loop = NULL;
553
554   free_options_menu();
555   unload_shared();
556   quit_audio();
557
558   if(config)
559     config->save();
560   delete config;
561   config = NULL;
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;
569   SDL_Quit();
570   PHYSFS_deinit();
571
572   return result;
573 }