fix cr/lfs and remove trailing whitespaces...
[supertux.git] / src / game_session.cpp
index 8aa35aa..c2aaebd 100644 (file)
@@ -1,9 +1,7 @@
 //  $Id$
-// 
+//
 //  SuperTux
-//  Copyright (C) 2000 Bill Kendrick <bill@newbreedsoftware.com>
-//  Copyright (C) 2004 Tobias Glaesser <tobi.web@gmx.de>
-//  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
+//  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
 //
 //  This program is free software; you can redistribute it and/or
 //  modify it under the terms of the GNU General Public License
@@ -14,7 +12,7 @@
 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 //  GNU General Public License for more details.
-// 
+//
 //  You should have received a copy of the GNU General Public License
 //  along with this program; if not, write to the Free Software
 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
@@ -36,9 +34,8 @@
 
 #include "game_session.hpp"
 #include "log.hpp"
-#include "worldmap.hpp"
+#include "worldmap/worldmap.hpp"
 #include "mainloop.hpp"
-#include "video/screen.hpp"
 #include "audio/sound_manager.hpp"
 #include "gui/menu.hpp"
 #include "sector.hpp"
 #include "lisp/lisp.hpp"
 #include "lisp/parser.hpp"
 #include "resources.hpp"
-#include "worldmap.hpp"
-#include "misc.hpp"
 #include "statistics.hpp"
 #include "timer.hpp"
+#include "options_menu.hpp"
 #include "object/fireworks.hpp"
 #include "textscroller.hpp"
 #include "control/codecontroller.hpp"
 #include "gettext.hpp"
 #include "console.hpp"
 #include "flip_level_transformer.hpp"
+#include "trigger/secretarea_trigger.hpp"
+#include "random_generator.hpp"
+#include "scripting/squirrel_util.hpp"
 
 // the engine will be run with a logical framerate of 64fps.
 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
 // binary fraction...
 static const float LOGICAL_FPS = 64.0;
 
-namespace {
-  const char* consoleCommands[] = {
-         "foo",
-         "whereami",
-         "camera",
-         "grease",
-         "invincible",
-         "mortal",
-         "shrink", 
-         "kill",
-         "gotoend",
-         "flip",
-         "finish",
-          "restart",
-          "quit"
-  };
-}
+enum GameMenuIDs {
+  MNID_CONTINUE,
+  MNID_ABORTLEVEL
+};
 
-using namespace WorldMapNS;
+GameSession* GameSession::current_ = NULL;
 
-GameSession* GameSession::current_ = 0;
-
-GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
-    Statistics* statistics)
-  : level(0), currentsector(0), mode(mode),
+GameSession::GameSession(const std::string& levelfile_, Statistics* statistics)
+  : level(0), currentsector(0),
     end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
     levelfile(levelfile_), best_level_statistics(statistics),
-    capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
+    capture_demo_stream(0), playback_demo_stream(0), demo_controller(0),
+    play_time(0)
 {
   current_ = this;
-  currentsector = 0;
-  
-  game_pause = false;
-  fps_fps = 0;
+  currentsector = NULL;
 
-  for (uint16_t i=0; i < sizeof(::consoleCommands)/sizeof(typeof(consoleCommands[0])); i++) {
-    Console::instance->registerCommand(consoleCommands[i], this);
-  }
+  game_pause = false;
 
   statistics_backdrop.reset(new Surface("images/engine/menu/score-backdrop.png"));
 
   restart_level(true);
+
+  game_menu.reset(new Menu());
+  game_menu->add_label(_("Pause"));
+  game_menu->add_hl();
+  game_menu->add_entry(MNID_CONTINUE, _("Continue"));
+  game_menu->add_submenu(_("Options"), get_options_menu());
+  game_menu->add_hl();
+  game_menu->add_entry(MNID_ABORTLEVEL, _("Abort Level"));
 }
 
 void
@@ -131,28 +118,12 @@ GameSession::restart_level(bool fromBeginning)
 
   level.reset(new Level);
   level->load(levelfile);
-
-  global_stats.reset();
-  global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
-  global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
-  
-  // get time
-  int time = 0;
-  for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
-  {
-    Sector* sec = *i;
-
-    for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
-        j != sec->gameobjects.end(); ++j)
-    {
-      GameObject* obj = *j;
-      
-      LevelTime* lt = dynamic_cast<LevelTime*> (obj);
-      if(lt)
-        time += int(lt->get_level_time());
-    }
-  }
-  global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
+  level->stats.total_coins = level->get_total_coins();
+  level->stats.total_badguys = level->get_total_badguys();
+  level->stats.total_secrets = level->get_total_count<SecretAreaTrigger>();
+  level->stats.reset();
+  if (!fromBeginning)
+    level->stats.declare_invalid();
 
   if (fromBeginning) reset_sector="";
   if(reset_sector != "") {
@@ -169,14 +140,19 @@ GameSession::restart_level(bool fromBeginning)
       throw std::runtime_error("Couldn't find main sector");
     currentsector->activate("main");
   }
-  
-  if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
-    levelintro();
+
+  //levelintro();
 
   currentsector->play_music(LEVEL_MUSIC);
 
-  if(capture_file != "")
+  if(capture_file != "") {
+    int newSeed=0;               // next run uses a new seed
+    while (newSeed == 0)            // which is the next non-zero random num.
+        newSeed = systemRandom.rand();
+    config->random_seed = systemRandom.srand(newSeed);
+    log_info << "Next run uses random seed " <<config->random_seed <<std::endl;
     record_demo(capture_file);
+  }
 }
 
 GameSession::~GameSession()
@@ -194,14 +170,38 @@ void
 GameSession::record_demo(const std::string& filename)
 {
   delete capture_demo_stream;
-  
-  capture_demo_stream = new std::ofstream(filename.c_str()); 
+
+  capture_demo_stream = new std::ofstream(filename.c_str());
   if(!capture_demo_stream->good()) {
     std::stringstream msg;
     msg << "Couldn't open demo file '" << filename << "' for writing.";
     throw std::runtime_error(msg.str());
   }
   capture_file = filename;
+
+  char buf[30];                            // save the seed in the demo file
+  snprintf(buf, sizeof(buf), "random_seed=%10d", config->random_seed);
+  for (int i=0; i==0 || buf[i-1]; i++)
+    capture_demo_stream->put(buf[i]);
+}
+
+int
+GameSession::get_demo_random_seed(const std::string& filename)
+{
+  std::istream* test_stream = new std::ifstream(filename.c_str());
+  if(test_stream->good()) {
+    char buf[30];                     // recall the seed from the demo file
+    int seed;
+    for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
+      test_stream->get(buf[i]);
+    if (sscanf(buf, "random_seed=%10d", &seed) == 1) {
+      log_info << "Random seed " << seed << " from demo file" << std::endl;
+         return seed;
+    }
+    else
+      log_info << "Demo file contains no random number" << std::endl;
+  }
+  return 0;
 }
 
 void
@@ -209,7 +209,7 @@ GameSession::play_demo(const std::string& filename)
 {
   delete playback_demo_stream;
   delete demo_controller;
-  
+
   playback_demo_stream = new std::ifstream(filename.c_str());
   if(!playback_demo_stream->good()) {
     std::stringstream msg;
@@ -220,13 +220,19 @@ GameSession::play_demo(const std::string& filename)
   Player& tux = *currentsector->player;
   demo_controller = new CodeController();
   tux.set_controller(demo_controller);
+
+  // skip over random seed, if it exists in the file
+  char buf[30];                            // ascii decimal seed
+  int seed;
+  for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
+    playback_demo_stream->get(buf[i]);
+  if (sscanf(buf, "random_seed=%010d", &seed) != 1)
+    playback_demo_stream->seekg(0);     // old style w/o seed, restart at beg
 }
 
 void
 GameSession::levelintro()
 {
-  char str[60];
-
   sound_manager->stop_music();
 
   DrawingContext context;
@@ -247,17 +253,16 @@ GameSession::levelintro()
   context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
       LAYER_FOREGROUND1);
 
-  sprintf(str, "Coins: %d", player_status->coins);
-  context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
+  std::stringstream ss_coins;
+  ss_coins << _("Coins") << ": " << player_status->coins;
+  context.draw_text(white_text, ss_coins.str(), Vector(SCREEN_WIDTH/2, 210),
       CENTER_ALLIGN, LAYER_FOREGROUND1);
 
   if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
-    //TODO make author check case/blank-insensitive
     context.draw_text(white_small_text,
-      std::string(_("contributed by ")) + level->get_author(), 
+      std::string(_("contributed by ")) + level->get_author(),
       Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
 
-
   if(best_level_statistics != NULL)
     best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
 
@@ -269,18 +274,58 @@ GameSession::on_escape_press()
 {
   if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
     return;   // don't let the player open the menu, when he is dying
-  
-  if(mode == ST_GL_TEST) {
-    main_loop->exit_screen();
-  } else if (!Menu::current()) {
-    Menu::set_current(game_menu);
+
+  if(level->on_menukey_script != "") {
+    std::istringstream in(level->on_menukey_script);
+    run_script(in, "OnMenuKeyScript");
+  } else {
+    toggle_pause();
+  }
+}
+
+void
+GameSession::toggle_pause()
+{
+  if(Menu::current() == NULL) {
+    Menu::set_current(game_menu.get());
     game_menu->set_active_item(MNID_CONTINUE);
     game_pause = true;
   } else {
+    Menu::set_current(NULL);
     game_pause = false;
   }
 }
 
+HSQUIRRELVM
+GameSession::run_script(std::istream& in, const std::string& sourcename)
+{
+  using namespace Scripting;
+
+  // garbage collect thread list
+  for(ScriptList::iterator i = scripts.begin();
+      i != scripts.end(); ) {
+    HSQOBJECT& object = *i;
+    HSQUIRRELVM vm = object_to_vm(object);
+
+    if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
+      sq_release(global_vm, &object);
+      i = scripts.erase(i);
+      continue;
+    }
+
+    ++i;
+  }
+
+  HSQOBJECT object = create_thread(global_vm);
+  scripts.push_back(object);
+
+  HSQUIRRELVM vm = object_to_vm(object);
+
+  compile_and_run(vm, in, sourcename);
+
+  return vm;
+}
+
 void
 GameSession::process_events()
 {
@@ -298,9 +343,9 @@ GameSession::process_events()
     }
 
     end_sequence_controller->press(Controller::RIGHT);
-    
+
     if (int(last_x_pos) == int(tux.get_pos().x))
-      end_sequence_controller->press(Controller::JUMP);    
+      end_sequence_controller->press(Controller::JUMP);
     last_x_pos = tux.get_pos().x;
   }
 
@@ -333,84 +378,11 @@ GameSession::process_events()
     capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
     capture_demo_stream ->put(main_controller->hold(Controller::UP));
     capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
-    capture_demo_stream ->put(main_controller->hold(Controller::JUMP));   
+    capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
     capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
   }
 }
 
-bool
-GameSession::consoleCommand(std::string command, std::vector<std::string>)
-{
-  if (command == "foo") {
-    log_info << "bar" << std::endl;
-    return true;
-  }
-
-  if (currentsector == 0) return false;
-  Player& tux = *currentsector->player;
-  
-  // Cheating words (the goal of this is really for debugging,
-  // but could be used for some cheating, nothing wrong with that)
-  if (command == "grease") {
-    tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
-    return true;
-  }
-  if (command == "invincible") {
-    // be invincle for the rest of the level
-    tux.invincible_timer.start(10000);
-    return true;
-  }
-  if (command == "mortal") {
-    // give up invincibility
-    tux.invincible_timer.stop();
-    return true;
-  }
-  if (command == "shrink") {
-    // remove powerups
-    tux.kill(tux.SHRINK);
-    return true;
-  }
-  if (command == "kill") {
-    tux.kill(tux.KILL);
-    return true;
-  }
-  if (command == "restart") {
-    restart_level(true);
-    return true;
-  }
-  if (command == "whereami") {
-    log_info << "You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y << std::endl;
-    return true;
-  }
-  if (command == "gotoend") {
-    // goes to the end of the level
-    tux.move(Vector(
-          (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
-    currentsector->camera->reset(
-        Vector(tux.get_pos().x, tux.get_pos().y));
-    return true;
-  }
-  if (command == "flip") {
-    FlipLevelTransformer flip_transformer;
-    flip_transformer.transform(GameSession::current()->get_current_level());
-    return true;
-  }
-  if (command == "finish") {
-    finish(true);
-    return true;
-  }
-  if (command == "camera") {
-    log_info << "Camera is at " << Sector::current()->camera->get_translation().x << "," << Sector::current()->camera->get_translation().y << std::endl;
-    return true;
-  }
-  if (command == "quit") {
-    main_loop->quit();
-    return true;
-  }
-
-  return false;
-}
-
 void
 GameSession::check_end_conditions()
 {
@@ -421,20 +393,20 @@ GameSession::check_end_conditions()
     finish(true);
     return;
   } else if (!end_sequence && tux->is_dead()) {
-    if (player_status->coins < 0) { 
+    if (player_status->coins < 0) {
       // No more coins: restart level from beginning
       player_status->coins = 0;
       restart_level(true);
-    } else { 
+    } else {
       // Still has coins: restart level from last reset point
       restart_level(false);
     }
-    
+
     return;
   }
 }
 
-void 
+void
 GameSession::draw(DrawingContext& context)
 {
   currentsector->draw(context);
@@ -451,7 +423,7 @@ GameSession::draw_pause(DrawingContext& context)
       Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
       Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
 }
-  
+
 void
 GameSession::process_menu()
 {
@@ -459,7 +431,7 @@ GameSession::process_menu()
   if(menu) {
     menu->update();
 
-    if(menu == game_menu) {
+    if(menu == game_menu.get()) {
       switch (game_menu->check()) {
         case MNID_CONTINUE:
           Menu::set_current(0);
@@ -488,15 +460,15 @@ GameSession::setup()
 void
 GameSession::update(float elapsed_time)
 {
+  // handle controller
+  if(main_controller->pressed(Controller::PAUSE_MENU))
+    on_escape_press();
+
   process_events();
   process_menu();
 
   check_end_conditions();
 
-  // handle controller
-  if(main_controller->pressed(Controller::PAUSE_MENU))
-    on_escape_press();
-  
   // respawning in new sector?
   if(newsector != "" && newspawnpoint != "") {
     Sector* sector = level->get_sector(newsector);
@@ -512,13 +484,9 @@ GameSession::update(float elapsed_time)
 
   // Update the world state and all objects in the world
   if(!game_pause) {
-    // Update the world
-    if (end_sequence == ENDSEQUENCE_RUNNING) {
-      currentsector->update(elapsed_time/2);
-    } else if(end_sequence == NO_ENDSEQUENCE) {
-      if(!currentsector->player->growing_timer.started())
-        currentsector->update(elapsed_time);
-    } 
+    currentsector->update(elapsed_time * speed_factor);
+    play_time += elapsed_time;
+    currentsector->update(elapsed_time);
   }
 
   // update sounds
@@ -527,7 +495,7 @@ GameSession::update(float elapsed_time)
   /* Handle music: */
   if (end_sequence)
     return;
-  
+
   if(currentsector->player->invincible_timer.started()) {
     if(currentsector->player->invincible_timer.get_timeleft() <=
        TUX_INVINCIBLE_TIME_WARNING) {
@@ -540,129 +508,16 @@ GameSession::update(float elapsed_time)
   }
 }
 
-#if 0
-GameSession::ExitStatus
-GameSession::run()
-{
-  Menu::set_current(0);
-  current_ = this;
-  
-  int fps_cnt = 0;
-
-  // Eat unneeded events
-  SDL_Event event;
-  while(SDL_PollEvent(&event))
-  {}
-
-  draw();
-
-  Uint32 fps_ticks = SDL_GetTicks();
-  Uint32 fps_nextframe_ticks = SDL_GetTicks();
-  Uint32 ticks;
-  bool skipdraw = false;
-
-  while (exit_status == ES_NONE) {
-    // we run in a logical framerate so elapsed time is a constant
-    // This will make the game run determistic and not different on different
-    // machines
-    static const float elapsed_time = 1.0 / LOGICAL_FPS;
-    // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
-    if(!game_pause)
-      game_time += elapsed_time;
-
-    // regulate fps
-    ticks = SDL_GetTicks();
-    if(ticks > fps_nextframe_ticks) {
-      if(skipdraw == true) {
-        // already skipped last frame? we have to slow down the game then...
-        skipdraw = false;
-        fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
-      } else {
-        // don't draw all frames when we're getting too slow
-        skipdraw = true;
-      }
-    } else {
-      skipdraw = false;
-      while(fps_nextframe_ticks > ticks) {
-        /* just wait */
-        // If we really have to wait long, then do an imprecise SDL_Delay()
-        Uint32 diff = fps_nextframe_ticks - ticks;
-        if(diff > 15) {
-          SDL_Delay(diff - 10);
-        } 
-        ticks = SDL_GetTicks();
-      }
-    }
-    fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
-
-    process_events();
-    process_menu();
-
-    // Update the world state and all objects in the world
-    if(!game_pause)
-    {
-      // Update the world
-      check_end_conditions();
-      if (end_sequence == ENDSEQUENCE_RUNNING)
-        update(elapsed_time/2);
-      else if(end_sequence == NO_ENDSEQUENCE)
-        update(elapsed_time);
-    }
-
-    if(!skipdraw)
-      draw();
-
-    // update sounds
-    sound_manager->update();
-
-    /* Time stops in pause mode */
-    if(game_pause || Menu::current())
-    {
-      continue;
-    }
-
-    /* Handle music: */
-    if (currentsector->player->invincible_timer.started() && 
-            currentsector->player->invincible_timer.get_timeleft() 
-            > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
-    {
-      currentsector->play_music(HERRING_MUSIC);
-    }
-    /* or just normal music? */
-    else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
-    {
-      currentsector->play_music(LEVEL_MUSIC);
-    }
-
-    /* Calculate frames per second */
-    if(config->show_fps)
-    {
-      ++fps_cnt;
-      
-      if(SDL_GetTicks() - fps_ticks >= 500)
-      {
-        fps_fps = (float) fps_cnt / .5;
-        fps_cnt = 0;
-        fps_ticks = SDL_GetTicks();
-      }
-    }
-  }
-  // just in case
-  currentsector = 0;
-  main_controller->reset();
-  return exit_status;
-}
-#endif
-
 void
 GameSession::finish(bool win)
 {
+  using namespace WorldMapNS;
+
   if(win) {
     if(WorldMap::current())
-      WorldMap::current()->finished_level(levelfile);
+      WorldMap::current()->finished_level(level.get());
   }
-  
+
   main_loop->exit_screen();
 }
 
@@ -693,7 +548,7 @@ GameSession::display_info_box(const std::string& text)
 
   bool running = true;
   DrawingContext context;
-  
+
   while(running)  {
 
     // TODO make a screen out of this, another mainloop is ugly
@@ -730,6 +585,7 @@ GameSession::start_sequence(const std::string& sequencename)
     if(end_sequence)
       return;
 
+    speed_factor = 0.5;
     end_sequence = ENDSEQUENCE_RUNNING;
     endsequence_timer.start(7.3);
     last_x_pos = -1;
@@ -747,27 +603,6 @@ GameSession::start_sequence(const std::string& sequencename)
         lt->stop();
     }
 
-    // add time spent to statistics
-    int tottime = 0, remtime = 0;
-    for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
-    {
-      Sector* sec = *i;
-
-      for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
-          j != sec->gameobjects.end(); ++j)
-      {
-        GameObject* obj = *j;
-
-        LevelTime* lt = dynamic_cast<LevelTime*> (obj);
-        if(lt)
-        {
-          tottime += int(lt->get_level_time());
-          remtime += int(lt->get_remaining_time());
-        }
-      }
-    }
-    global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
-
     if(sequencename == "fireworks") {
       currentsector->add_object(new Fireworks());
     }
@@ -788,17 +623,8 @@ GameSession::drawstatus(DrawingContext& context)
 {
   player_status->draw(context);
 
-  if(config->show_fps) {
-    char str[60];
-    snprintf(str, sizeof(str), "%3.1f", fps_fps);
-    const char* fpstext = "FPS";
-    context.draw_text(white_text, fpstext, Vector(SCREEN_WIDTH - white_text->get_text_width(fpstext) - gold_text->get_text_width(" 99999") - BORDER_X, BORDER_Y + 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
-    context.draw_text(gold_text, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), RIGHT_ALLIGN, LAYER_FOREGROUND1);
-  }
-
   // draw level stats while end_sequence is running
   if (end_sequence) {
-    global_stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());
+    level->stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());
   }
 }
-