Unified Messaging Subsystem
[supertux.git] / src / worldmap.cpp
index 3752292..816c92d 100644 (file)
 #include <stdexcept>
 #include <sstream>
 #include <unistd.h>
-
-#include "app/globals.h"
-#include "app/gettext.h"
-#include "app/setup.h"
-#include "video/surface.h"
-#include "video/screen.h"
-#include "video/drawing_context.h"
-#include "special/frame_rate.h"
-#include "special/sprite_manager.h"
-#include "audio/sound_manager.h"
-#include "lisp/parser.h"
-#include "lisp/lisp.h"
-#include "lisp/list_iterator.h"
-#include "lisp/writer.h"
-#include "gameloop.h"
-#include "sector.h"
-#include "worldmap.h"
-#include "resources.h"
-#include "misc.h"
-#include "player_status.h"
-#include "textscroller.h"
-
-#define map_message_TIME 2.8
+#include <physfs.h>
+
+#include "gettext.hpp"
+#include "msg.hpp"
+#include "video/surface.hpp"
+#include "video/screen.hpp"
+#include "video/drawing_context.hpp"
+#include "sprite/sprite_manager.hpp"
+#include "audio/sound_manager.hpp"
+#include "lisp/parser.hpp"
+#include "lisp/lisp.hpp"
+#include "lisp/list_iterator.hpp"
+#include "lisp/writer.hpp"
+#include "game_session.hpp"
+#include "sector.hpp"
+#include "worldmap.hpp"
+#include "resources.hpp"
+#include "misc.hpp"
+#include "player_status.hpp"
+#include "textscroller.hpp"
+#include "main.hpp"
+#include "spawn_point.hpp"
+#include "file_system.hpp"
+#include "gui/menu.hpp"
+#include "gui/mousecursor.hpp"
+#include "control/joystickkeyboardcontroller.hpp"
+#include "object/background.hpp"
+#include "object/tilemap.hpp"
+#include "scripting/script_interpreter.hpp"
+#include "exceptions.hpp"
 
 Menu* worldmap_menu  = 0;
 
 static const float TUXSPEED = 200;
+static const float map_message_TIME = 2.8;
 
 namespace WorldMapNS {
 
@@ -111,12 +119,10 @@ string_to_direction(const std::string& directory)
 Tux::Tux(WorldMap* worldmap_)
   : worldmap(worldmap_)
 {
-  tux_sprite = sprite_manager->create("worldmaptux");
+  tux_sprite = sprite_manager->create("images/worldmap/common/tux.sprite");
   
   offset = 0;
   moving = false;
-  tile_pos.x = worldmap->get_start_x();
-  tile_pos.y = worldmap->get_start_y();
   direction = D_NONE;
   input_direction = D_NONE;
 }
@@ -129,21 +135,19 @@ Tux::~Tux()
 void
 Tux::draw(DrawingContext& context)
 {
-  switch (player_status.bonus) {
+  switch (player_status->bonus) {
     case GROWUP_BONUS:
-      tux_sprite->set_action("large");
+      tux_sprite->set_action(moving ? "large-walking" : "large-stop");
       break;
     case FIRE_BONUS:
-      tux_sprite->set_action("fire");
+      tux_sprite->set_action(moving ? "fire-walking" : "fire-stop");
       break;
     case NO_BONUS:
-      tux_sprite->set_action("small");
+      tux_sprite->set_action(moving ? "small-walking" : "small-stop");
       break;
     default:
-#ifdef DBEUG
-      std::cerr << "Bonus type not handled in worldmap.\n";
-#endif
-      tux_sprite->set_action("large");
+      msg_debug("Bonus type not handled in worldmap.");
+      tux_sprite->set_action("large-stop");
       break;
   }
 
@@ -175,7 +179,7 @@ Tux::get_pos()
       break;
     }
   
-  return Vector((int)x, (int)y); 
+  return Vector(x, y);
 }
 
 void
@@ -190,13 +194,23 @@ Tux::stop()
 void
 Tux::set_direction(Direction dir)
 {
-input_direction = dir;
+  input_direction = dir;
 }
 
 void
-Tux::action(float delta)
+Tux::update(float delta)
 {
-  if (!moving)
+  // check controller
+  if(main_controller->pressed(Controller::UP))
+    input_direction = D_NORTH;
+  else if(main_controller->pressed(Controller::DOWN))
+    input_direction = D_SOUTH;
+  else if(main_controller->pressed(Controller::LEFT))
+    input_direction = D_WEST;
+  else if(main_controller->pressed(Controller::RIGHT))
+    input_direction = D_EAST;
+
+  if(!moving)
     {
       if (input_direction != D_NONE)
         { 
@@ -332,26 +346,18 @@ Tux::action(float delta)
 //---------------------------------------------------------------------------
 
 WorldMap::WorldMap()
+  : tux(0), solids(0)
 {
-  tile_manager = new TileManager("images/worldmap/antarctica.stwt");
-  
-  width  = 20;
-  height = 15;
+  tile_manager = new TileManager("images/worldmap.strf");
   
-  start_x = 4;
-  start_y = 5;
-
   tux = new Tux(this);
-  
-  leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", true);
-  leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", true);
-  messagedot   = new Surface(datadir +  "/images/worldmap/messagedot.png", true);
-  teleporterdot   = new Surface(datadir +  "/images/worldmap/teleporterdot.png", true);
-
-  enter_level = false;
+  add_object(tux);
+    
+  messagedot = new Surface("images/worldmap/common/messagedot.png");
+  teleporterdot = new Surface("images/worldmap/common/teleporterdot.png");
 
   name = "<no title>";
-  music = "salcon.mod";
+  music = "music/salcon.ogg";
   intro_displayed = false;
 
   total_stats.reset();
@@ -359,15 +365,45 @@ WorldMap::WorldMap()
 
 WorldMap::~WorldMap()
 {
-  delete tux;
+  clear_objects();
+  for(SpawnPoints::iterator i = spawn_points.begin();
+      i != spawn_points.end(); ++i) {
+    delete *i;
+  }
+  for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
+    Level& level = *i;
+    delete level.sprite;
+  }
+  
   delete tile_manager;
 
-  delete leveldot_green;
-  delete leveldot_red;
   delete messagedot;
   delete teleporterdot;
 }
 
+void
+WorldMap::add_object(GameObject* object)
+{
+  TileMap* tilemap = dynamic_cast<TileMap*> (object);
+  if(tilemap != 0 && tilemap->is_solid()) {
+    solids = tilemap;
+  }
+
+  game_objects.push_back(object);
+}
+
+void
+WorldMap::clear_objects()
+{
+  for(GameObjects::iterator i = game_objects.begin();
+      i != game_objects.end(); ++i)
+    delete *i;
+  game_objects.clear();
+  solids = 0;
+  tux = new Tux(this);
+  add_object(tux);
+}
+
 // Don't forget to set map_filename before calling this
 void
 WorldMap::load_map()
@@ -376,39 +412,50 @@ WorldMap::load_map()
 
   try {
     lisp::Parser parser;
-    std::string filename = get_resource_filename(map_filename);
-    std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
+    std::auto_ptr<lisp::Lisp> root (parser.parse(map_filename));
 
     const lisp::Lisp* lisp = root->get_lisp("supertux-worldmap");
     if(!lisp)
-      throw new std::runtime_error("file isn't a supertux-worldmap file.");
+      throw std::runtime_error("file isn't a supertux-worldmap file.");
 
+    clear_objects();
     lisp::ListIterator iter(lisp);
     while(iter.next()) {
       if(iter.item() == "tilemap") {
-        if(tilemap.size() > 0)
-          throw new std::runtime_error("multiple tilemaps specified");
-        
-        const lisp::Lisp* tilemap_lisp = iter.lisp();
-        tilemap_lisp->get("width",  width);
-        tilemap_lisp->get("height", height);
-        tilemap_lisp->get_vector("data", tilemap);
+        add_object(new TileMap(*(iter.lisp()), tile_manager));
+      } else if(iter.item() == "background") {
+        add_object(new Background(*(iter.lisp())));
       } else if(iter.item() == "properties") {
         const lisp::Lisp* props = iter.lisp();
         props->get("name", name);
         props->get("music", music);
-        props->get("intro-filename", intro_filename);
-        props->get("start_pos_x", start_x);
-        props->get("start_pos_y", start_y);
-      } else if(iter.item() == "special-tiles") {
-        parse_special_tiles(iter.lisp());
+      } else if(iter.item() == "intro-script") {
+        iter.value()->get(intro_script);
+      } else if(iter.item() == "spawnpoint") {
+        SpawnPoint* sp = new SpawnPoint(iter.lisp());
+        spawn_points.push_back(sp);
+      } else if(iter.item() == "level") {
+        parse_level_tile(iter.lisp());
+      } else if(iter.item() == "special-tile") {
+        parse_special_tile(iter.lisp());
       } else {
-        std::cerr << "Unknown token '" << iter.item() << "' in worldmap.\n";
+        msg_warning("Unknown token '" << iter.item() << "' in worldmap");
+      }
+    }
+    if(solids == 0)
+      throw std::runtime_error("No solid tilemap specified");
+
+    // search for main spawnpoint
+    for(SpawnPoints::iterator i = spawn_points.begin();
+        i != spawn_points.end(); ++i) {
+      SpawnPoint* sp = *i;
+      if(sp->name == "main") {
+        Vector p = sp->pos;
+        tux->set_tile_pos(p);
+        break;
       }
     }
 
-    delete tux;
-    tux = new Tux(this);
   } catch(std::exception& e) {
     std::stringstream msg;
     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
@@ -418,81 +465,90 @@ WorldMap::load_map()
 }
 
 void
-WorldMap::parse_special_tiles(const lisp::Lisp* lisp)
+WorldMap::parse_special_tile(const lisp::Lisp* lisp)
 {
-  lisp::ListIterator iter(lisp);
-  while(iter.next()) {
-    if(iter.item() == "special-tile") {
-      SpecialTile special_tile;
-
-      const lisp::Lisp* lisp = iter.lisp();
-      lisp->get("x", special_tile.pos.x);
-      lisp->get("y", special_tile.pos.y);
-      lisp->get("map-message", special_tile.map_message);
-      special_tile.passive_message = false;
-      lisp->get("passive-message", special_tile.passive_message);
-      special_tile.teleport_dest = Vector(-1,-1);
-      lisp->get("teleport-to-x", special_tile.teleport_dest.x);
-      lisp->get("teleport-to-y", special_tile.teleport_dest.y);
-      special_tile.invisible = false;
-      lisp->get("invisible-tile", special_tile.invisible);
-
+  SpecialTile special_tile;
+  
+  lisp->get("x", special_tile.pos.x);
+  lisp->get("y", special_tile.pos.y);
+  lisp->get("map-message", special_tile.map_message);
+  special_tile.passive_message = false;
+  lisp->get("passive-message", special_tile.passive_message);
+  special_tile.teleport_dest = Vector(-1,-1);
+  lisp->get("teleport-to-x", special_tile.teleport_dest.x);
+  lisp->get("teleport-to-y", special_tile.teleport_dest.y);
+  special_tile.invisible = false;
+  lisp->get("invisible-tile", special_tile.invisible);
+
+  special_tile.apply_action_north = true;
+  special_tile.apply_action_south = true;
+  special_tile.apply_action_east = true;
+  special_tile.apply_action_west = true;
+
+  std::string apply_direction;
+  lisp->get("apply-to-direction", apply_direction);
+  if(!apply_direction.empty()) {
+    special_tile.apply_action_north = false;
+    special_tile.apply_action_south = false;
+    special_tile.apply_action_east = false;
+    special_tile.apply_action_west = false;
+    if(apply_direction.find("north") != std::string::npos)
       special_tile.apply_action_north = true;
+    if(apply_direction.find("south") != std::string::npos)
       special_tile.apply_action_south = true;
+    if(apply_direction.find("east") != std::string::npos)
       special_tile.apply_action_east = true;
+    if(apply_direction.find("west") != std::string::npos)
       special_tile.apply_action_west = true;
+  }
+  
+  special_tiles.push_back(special_tile);
+}
 
-      std::string apply_direction;
-      lisp->get("apply-to-direction", apply_direction);
-      if(!apply_direction.empty()) {
-        special_tile.apply_action_north = false;
-        special_tile.apply_action_south = false;
-        special_tile.apply_action_east = false;
-        special_tile.apply_action_west = false;
-        if(apply_direction.find("north") != std::string::npos)
-          special_tile.apply_action_north = true;
-        if(apply_direction.find("south") != std::string::npos)
-          special_tile.apply_action_south = true;
-        if(apply_direction.find("east") != std::string::npos)
-          special_tile.apply_action_east = true;
-        if(apply_direction.find("west") != std::string::npos)
-          special_tile.apply_action_west = true;
-      }
-      
-      special_tiles.push_back(special_tile);
-    } else if(iter.item() == "level") {
-      Level level;
+void
+WorldMap::parse_level_tile(const lisp::Lisp* level_lisp)
+{
+  Level level;
 
-      lisp::Lisp* level_lisp = iter.lisp();
-      level.solved = false;
-                      
-      level.north = true;
-      level.east  = true;
-      level.south = true;
-      level.west  = true;
+  level.solved = false;
+                  
+  level.north = true;
+  level.east  = true;
+  level.south = true;
+  level.west  = true;
 
-      level_lisp->get("extro-filename", level.extro_filename);
-      level_lisp->get("next-worldmap", level.next_worldmap);
+  std::string sprite = "images/worldmap/common/leveldot.sprite";
+  level_lisp->get("sprite", sprite);
+  level.sprite = sprite_manager->create(sprite);
 
-      level.quit_worldmap = false;
-      level_lisp->get("quit-worldmap", level.quit_worldmap);
+  level_lisp->get("extro-script", level.extro_script);
+  level_lisp->get("next-worldmap", level.next_worldmap);
 
-      level_lisp->get("name", level.name);
-      level_lisp->get("x", level.pos.x);
-      level_lisp->get("y", level.pos.y);
+  level.quit_worldmap = false;
+  level_lisp->get("quit-worldmap", level.quit_worldmap);
 
-      level.auto_path = true;
-      level_lisp->get("auto-path", level.auto_path);
+  level_lisp->get("name", level.name);
+  
+  if (!PHYSFS_exists((levels_path + level.name).c_str()))
+  {
+       // Do we want to bail out instead...? We might get messages from modders
+       // who can't make their levels run because they're too dumb to watch
+       // their terminals...
+    msg_warning("level file '" << level.name
+      << "' does not exist and will not be added to the worldmap");
+    return;
+  }
 
-      level.vertical_flip = false;
-      level_lisp->get("vertical-flip", level.vertical_flip);
+  level_lisp->get("x", level.pos.x);
+  level_lisp->get("y", level.pos.y);
 
-      levels.push_back(level);
-    } else {
-      std::cerr << "Unknown token '" << iter.item() <<
-        "' in worldmap special-tiles list.";
-    }
-  }
+  level.auto_path = true;
+  level_lisp->get("auto-path", level.auto_path);
+
+  level.vertical_flip = false;
+  level_lisp->get("vertical-flip", level.vertical_flip);
+
+  levels.push_back(level);
 }
 
 void
@@ -503,8 +559,7 @@ WorldMap::get_level_title(Level& level)
 
   try {
     lisp::Parser parser;
-    std::auto_ptr<lisp::Lisp> root (
-        parser.parse(get_resource_filename(levels_path + level.name)));
+    std::auto_ptr<lisp::Lisp> root (parser.parse(levels_path + level.name));
 
     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
     if(!level_lisp)
@@ -512,7 +567,7 @@ WorldMap::get_level_title(Level& level)
     
     level_lisp->get("name", level.title);
   } catch(std::exception& e) {
-    std::cerr << "Problem when reading leveltitle: " << e.what() << "\n";
+    msg_warning("Problem when reading leveltitle: " << e.what());
     return;
   }
 }
@@ -533,103 +588,33 @@ void
 WorldMap::on_escape_press()
 {
   // Show or hide the menu
-  if(!Menu::current())
-    {
-    Menu::set_current(worldmap_menu); 
+  if(!Menu::current()) {
+    Menu::set_current(worldmap_menu);
     tux->set_direction(D_NONE);  // stop tux movement when menu is called
-    }
-  else
-    Menu::set_current(0); 
+  } else {
+    Menu::set_current(0);
+  }
 }
 
 void
 WorldMap::get_input()
 {
-  enter_level = false;
-  SDLKey key;
+  main_controller->update();
 
   SDL_Event event;
-  while (SDL_PollEvent(&event))
-    {
-      if (Menu::current())
-        {
-          Menu::current()->event(event);
-        }
-      else
-        {
-          switch(event.type)
-            {
-            case SDL_QUIT:
-              Termination::abort("Received window close", "");
-              break;
-          
-            case SDL_KEYDOWN:
-              key = event.key.keysym.sym;
-
-              if(key == SDLK_ESCAPE)
-                on_escape_press();
-              else if(key == SDLK_RETURN || key == keymap.power)
-                enter_level = true;
-              else if(key == SDLK_LEFT || key == keymap.power)
-                tux->set_direction(D_WEST);
-              else if(key == SDLK_RIGHT || key == keymap.right)
-                tux->set_direction(D_EAST);
-              else if(key == SDLK_UP || key == keymap.up ||
-                key == keymap.jump)
-                  // there might be ppl that use jump as up key
-                tux->set_direction(D_NORTH);
-              else if(key == SDLK_DOWN || key == keymap.down)
-                tux->set_direction(D_SOUTH);
-              break;
-
-            case SDL_JOYHATMOTION:
-              if(event.jhat.value & SDL_HAT_UP) {
-                tux->set_direction(D_NORTH);
-              } else if(event.jhat.value & SDL_HAT_DOWN) {
-                tux->set_direction(D_SOUTH);
-              } else if(event.jhat.value & SDL_HAT_LEFT) {
-                tux->set_direction(D_WEST);
-              } else if(event.jhat.value & SDL_HAT_RIGHT) {
-                tux->set_direction(D_EAST);
-              }
-              break;
-          
-            case SDL_JOYAXISMOTION:
-              if (event.jaxis.axis == joystick_keymap.x_axis)
-                {
-                  if (event.jaxis.value < -joystick_keymap.dead_zone)
-                    tux->set_direction(D_WEST);
-                  else if (event.jaxis.value > joystick_keymap.dead_zone)
-                    tux->set_direction(D_EAST);
-                }
-              else if (event.jaxis.axis == joystick_keymap.y_axis)
-                {
-                  if (event.jaxis.value > joystick_keymap.dead_zone)
-                    tux->set_direction(D_SOUTH);
-                  else if (event.jaxis.value < -joystick_keymap.dead_zone)
-                    tux->set_direction(D_NORTH);
-                }
-              break;
-
-            case SDL_JOYBUTTONDOWN:
-              if (event.jbutton.button == joystick_keymap.b_button)
-                enter_level = true;
-              else if (event.jbutton.button == joystick_keymap.start_button)
-                on_escape_press();
-              break;
-
-            default:
-              break;
-            }
-        }
-    }
+  while (SDL_PollEvent(&event)) {
+    if (Menu::current())
+      Menu::current()->event(event);
+    main_controller->process_event(event);
+    if(event.type == SDL_QUIT)
+      throw graceful_shutdown();
+  }
 }
 
 Vector
 WorldMap::get_next_tile(Vector pos, Direction direction)
 {
-  switch(direction)
-    {
+  switch(direction) {
     case D_WEST:
       pos.x -= 1;
       break;
@@ -644,7 +629,7 @@ WorldMap::get_next_tile(Vector pos, Direction direction)
       break;
     case D_NONE:
       break;
-    }
+  }
   return pos;
 }
 
@@ -653,8 +638,8 @@ WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
 {
   *new_pos = get_next_tile(old_pos, direction);
 
-  if (!(new_pos->x >= 0 && new_pos->x < width
-        && new_pos->y >= 0 && new_pos->y < height))
+  if (!(new_pos->x >= 0 && new_pos->x < solids->get_width()
+        && new_pos->y >= 0 && new_pos->y < solids->get_height()))
     { // New position is outsite the tilemap
       return false;
     }
@@ -688,6 +673,53 @@ WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
 void
 WorldMap::update(float delta)
 {
+  Menu* menu = Menu::current();
+  if(menu) {
+    menu->update();
+
+    if(menu == worldmap_menu) {
+      switch (worldmap_menu->check())
+      {
+        case MNID_RETURNWORLDMAP: // Return to game  
+          Menu::set_current(0);
+          break;
+        case MNID_QUITWORLDMAP: // Quit Worldmap
+          quit = true;                               
+          break;
+      }
+    } else if(menu == options_menu) {
+      process_options_menu();
+    }
+
+    return;
+  }
+
+  // update GameObjects
+  for(GameObjects::iterator i = game_objects.begin();
+      i != game_objects.end(); ++i) {
+    GameObject* object = *i;
+    object->update(delta);
+  }
+  // remove old GameObjects
+  for(GameObjects::iterator i = game_objects.begin();
+      i != game_objects.end(); ) {
+    GameObject* object = *i;
+    if(!object->is_valid()) {
+      delete object;
+      i = game_objects.erase(i);
+    } else {
+      ++i;
+    }
+  }
+  
+  bool enter_level = false;
+  if(main_controller->pressed(Controller::ACTION)
+      || main_controller->pressed(Controller::JUMP)
+      || main_controller->pressed(Controller::MENU_SELECT))
+    enter_level = true;
+  if(main_controller->pressed(Controller::PAUSE_MENU))
+    on_escape_press();
+  
   if (enter_level && !tux->is_moving())
     {
       /* Check special tile action */
@@ -697,7 +729,7 @@ WorldMap::update(float delta)
         if (special_tile->teleport_dest != Vector(-1,-1))
           {
           // TODO: an animation, camera scrolling or a fading would be a nice touch
-          SoundManager::get()->play_sound(IDToSound(SND_WARP));
+          sound_manager->play("sounds/warp.wav");
           tux->back_direction = D_NONE;
           tux->set_tile_pos(special_tile->teleport_dest);
           SDL_Delay(1000);
@@ -709,22 +741,22 @@ WorldMap::update(float delta)
       Level* level = at_level();
       if (!level)
         {
-        std::cout << "No level to enter at: "
-          << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y
-          << std::endl;
+        msg_warning("No level to enter at: "
+          << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y);
         return;
         }
 
 
       if (level->pos == tux->get_tile_pos())
         {
-          PlayerStatus old_player_status = player_status;
+          sound_manager->stop_music();
+          PlayerStatus old_player_status;
+          old_player_status = *player_status;
 
-          std::cout << "Enter the current level: " << level->name << std::endl;
           // do a shriking fade to the level
           shrink_fade(Vector((level->pos.x*32 + 16 + offset.x),
                              (level->pos.y*32 + 16 + offset.y)), 500);
-          GameSession session(get_resource_filename(levels_path + level->name),
+          GameSession session(levels_path + level->name,
                               ST_GL_LOAD_LEVEL_FILE, &level->statistics);
 
           switch (session.run())
@@ -734,6 +766,7 @@ WorldMap::update(float delta)
                 level_finished = true;
                 bool old_level_state = level->solved;
                 level->solved = true;
+                level->sprite->set_action("solved");
 
                 // deal with statistics
                 level->statistics.merge(global_stats);
@@ -762,10 +795,7 @@ WorldMap::update(float delta)
                     if (dir != D_NONE)
                       {
                         tux->set_direction(dir);
-                        //tux->update(delta);
                       }
-
-                    std::cout << "Walk to dir: " << dir << std::endl;
                   }
               }
 
@@ -774,9 +804,9 @@ WorldMap::update(float delta)
               level_finished = false;
               /* In case the player's abort the level, keep it using the old
                   status. But the minimum lives and no bonus. */
-              player_status.distros = old_player_status.distros;
-              player_status.lives = std::min(old_player_status.lives, player_status.lives);
-              player_status.bonus = NO_BONUS;
+              player_status->coins = old_player_status.coins;
+              player_status->lives = std::min(old_player_status.lives, player_status->lives);
+              player_status->bonus = NO_BONUS;
 
               break;
             case GameSession::ES_GAME_OVER:
@@ -795,7 +825,7 @@ WorldMap::update(float delta)
               context.draw_text(blue_text, _("GAMEOVER"), 
                   Vector(SCREEN_WIDTH/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
 
-              sprintf(str, _("COINS: %d"), player_status.distros);
+              sprintf(str, _("COINS: %d"), player_status->coins);
               context.draw_text(gold_text, str,
                   Vector(SCREEN_WIDTH/2, SCREEN_WIDTH - 32), CENTER_ALLIGN,
                   LAYER_FOREGROUND1);
@@ -804,11 +834,10 @@ WorldMap::update(float delta)
 
               context.do_drawing();
 
-              SDL_Event event;
-              wait_for_event(event,2000,6000,true);
+              wait_for_event(2.0, 6.0);
 
               quit = true;
-              player_status.reset();
+              player_status->reset();
               break;
               }
             case GameSession::ES_NONE:
@@ -817,7 +846,7 @@ WorldMap::update(float delta)
               break;
             }
 
-          SoundManager::get()->play_music(song);
+          sound_manager->play_music(music);
           Menu::set_current(0);
           if (!savegame_file.empty())
             savegame(savegame_file);
@@ -825,10 +854,16 @@ WorldMap::update(float delta)
       /* The porpose of the next checking is that if the player lost
          the level (in case there is one), don't show anything */
       if(level_finished) {
-        if (!level->extro_filename.empty()) {
-          // Display a text file
-          std::string filename = levels_path + level->extro_filename;
-          display_text_file(filename);
+        if (level->extro_script != "") {
+          try {
+            std::auto_ptr<ScriptInterpreter> interpreter 
+              (new ScriptInterpreter(levels_path));
+            std::istringstream in(level->extro_script);
+            interpreter->run_script(in, "level-extro-script");
+            add_object(interpreter.release());
+          } catch(std::exception& e) {
+            msg_warning("Couldn't run level-extro-script:" << e.what());
+          }
         }
 
         if (!level->next_worldmap.empty())
@@ -842,44 +877,14 @@ WorldMap::update(float delta)
     }
   else
     {
-      tux->action(delta);
 //      tux->set_direction(input_direction);
     }
-  
-  Menu* menu = Menu::current();
-  if(menu)
-    {
-      menu->action();
-
-      if(menu == worldmap_menu)
-        {
-          switch (worldmap_menu->check())
-            {
-            case MNID_RETURNWORLDMAP: // Return to game
-              break;
-            case MNID_QUITWORLDMAP: // Quit Worldmap
-              quit = true;
-              break;
-            }
-        }
-      else if(menu == options_menu)
-        {
-          process_options_menu();
-        }
-    }
 }
 
 const Tile*
 WorldMap::at(Vector p)
 {
-  assert(p.x >= 0 
-         && p.x < width
-         && p.y >= 0
-         && p.y < height);
-
-  int x = int(p.x);
-  int y = int(p.y);
-  return tile_manager->get(tilemap[width * y + x]);
+  return solids->get_tile((int) p.x, (int) p.y);
 }
 
 WorldMap::Level*
@@ -909,21 +914,16 @@ WorldMap::at_special_tile()
 void
 WorldMap::draw(DrawingContext& context)
 {
-  for(int y = 0; y < height; ++y)
-    for(int x = 0; x < width; ++x)
-      {
-        const Tile* tile = at(Vector(x, y));
-        tile->draw(context, Vector(x*32, y*32), LAYER_TILES);
-      }
-
+  for(GameObjects::iterator i = game_objects.begin();
+      i != game_objects.end(); ++i) {
+    GameObject* object = *i;
+    object->draw(context);
+  }
+  
   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
     {
-      if (i->solved)
-        context.draw_surface(leveldot_green,
-            Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
-      else
-        context.draw_surface(leveldot_red,
-            Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
+      const Level& level = *i;
+      level.sprite->draw(context, level.pos*32 + Vector(16, 16), LAYER_TILES+1);
     }
 
   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
@@ -940,7 +940,6 @@ WorldMap::draw(DrawingContext& context)
                 Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
     }
 
-  tux->draw(context);
   draw_status(context);
 }
 
@@ -949,38 +948,8 @@ WorldMap::draw_status(DrawingContext& context)
 {
   context.push_transform();
   context.set_translation(Vector(0, 0));
-  
-  char str[80];
-  sprintf(str, " %d", total_stats.get_points(SCORE_STAT));
-
-  context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
-  context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
-
-  sprintf(str, "%d", player_status.distros);
-  context.draw_text(white_text, _("COINS"), Vector(SCREEN_WIDTH/2 - 16*5, 0),
-      LEFT_ALLIGN, LAYER_FOREGROUND1);
-  context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2 + (16*5)/2, 0),
-        LEFT_ALLIGN, LAYER_FOREGROUND1);
-
-  if (player_status.lives >= 5)
-    {
-      sprintf(str, "%dx", player_status.lives);
-      context.draw_text(gold_text, str, 
-          Vector(SCREEN_WIDTH - gold_text->get_text_width(str) - tux_life->w, 0),
-          LEFT_ALLIGN, LAYER_FOREGROUND1);
-      context.draw_surface(tux_life, Vector(SCREEN_WIDTH -
-            gold_text->get_text_width("9"), 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
-    }
-  else
-    {
-      for(int i= 0; i < player_status.lives; ++i)
-        context.draw_surface(tux_life,
-            Vector(SCREEN_WIDTH - tux_life->w*4 + (tux_life->w*i), 0),
-            LAYER_FOREGROUND1);
-    }
-  context.draw_text(white_text, _("LIVES"),
-      Vector(SCREEN_WIDTH - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 0),
-      LEFT_ALLIGN, LAYER_FOREGROUND1);
+  player_status->draw(context);
 
   if (!tux->is_moving())
     {
@@ -1015,7 +984,7 @@ WorldMap::draw_status(DrawingContext& context)
         }
     }
   /* Display a passive message in the map, if needed */
-  if(passive_message_timer.check())
+  if(passive_message_timer.started())
     context.draw_text(gold_text, passive_message, 
             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
             CENTER_ALLIGN, LAYER_FOREGROUND1);
@@ -1030,12 +999,20 @@ WorldMap::display()
 
   quit = false;
 
-  song = SoundManager::get()->load_music(datadir +  "/music/" + music);
-  SoundManager::get()->play_music(song);
-
-  if(!intro_displayed && intro_filename != "") {
-    std::string filename = levels_path + intro_filename;
-    display_text_file(filename);
+  sound_manager->play_music(music);
+
+  if(!intro_displayed && intro_script != "") {
+    try {
+      std::auto_ptr<ScriptInterpreter> interpreter 
+        (new ScriptInterpreter(levels_path));
+      std::istringstream in(intro_script);
+      interpreter->run_script(in, "worldmap-intro-script");
+      add_object(interpreter.release());
+    } catch(std::exception& e) {
+      msg_warning("Couldn't execute worldmap-intro-script: "
+        << e.what());
+    }
+                                           
     intro_displayed = true;
   }
 
@@ -1044,34 +1021,37 @@ WorldMap::display()
   while(!quit) {
     Uint32 ticks = SDL_GetTicks();
     float elapsed_time = float(ticks - lastticks) / 1000;
-    global_time += elapsed_time;
+    game_time += elapsed_time;
     lastticks = ticks;
     
-    // 40 fps minimum
+    // 40 fps minimum // TODO use same code as in GameSession here
     if(elapsed_time > .025)
       elapsed_time = .025;
     
     Vector tux_pos = tux->get_pos();
-    
-    offset.x = -tux_pos.x + SCREEN_WIDTH/2;
-    offset.y = -tux_pos.y + SCREEN_HEIGHT/2;
+    offset.x = tux_pos.x - SCREEN_WIDTH/2;
+    offset.y = tux_pos.y - SCREEN_HEIGHT/2;
 
-    if (offset.x > 0) offset.x = 0;
-    if (offset.y > 0) offset.y = 0;
+    if (offset.x < 0)
+      offset.x = 0;
+    if (offset.y < 0)
+      offset.y = 0;
+
+    if (offset.x > solids->get_width()*32 - SCREEN_WIDTH)
+      offset.x = solids->get_width()*32 - SCREEN_WIDTH;
+    if (offset.y > solids->get_height()*32 - SCREEN_HEIGHT)
+      offset.y = solids->get_height()*32 - SCREEN_HEIGHT;
 
-    if (offset.x < SCREEN_WIDTH - width*32) offset.x = SCREEN_WIDTH - width*32;
-    if (offset.y < SCREEN_HEIGHT - height*32) offset.y = SCREEN_HEIGHT - height*32;
-  
     context.push_transform();
-    context.set_translation(-offset);
+    context.set_translation(offset);
     draw(context);
     context.pop_transform();
     get_input();
     update(elapsed_time);
+    sound_manager->update();
       
     if(Menu::current()) {
       Menu::current()->draw(context);
-      mouse_cursor->draw(context);
     }
 
     context.do_drawing();
@@ -1084,8 +1064,20 @@ WorldMap::savegame(const std::string& filename)
   if(filename == "")
     return;
 
-  std::ofstream file(filename.c_str(), std::ios::out);
-  lisp::Writer writer(file);
+  std::string dir = FileSystem::dirname(filename);
+  if(PHYSFS_exists(dir.c_str()) == 0 && PHYSFS_mkdir(dir.c_str()) != 0) {
+    std::ostringstream msg;
+    msg << "Couldn't create directory '" << dir << "' for savegame:"
+        << PHYSFS_getLastError();
+    throw std::runtime_error(msg.str());
+  }
+  if(!PHYSFS_isDirectory(dir.c_str())) {
+    std::ostringstream msg;
+    msg << "'" << dir << "' is not a directory.";
+    throw std::runtime_error(msg.str());
+  }
+  
+  lisp::Writer writer(filename);
 
   int nb_solved_levels = 0, total_levels = 0;
   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
@@ -1112,7 +1104,7 @@ WorldMap::savegame(const std::string& filename)
   writer.write_float("x", tux->get_tile_pos().x);
   writer.write_float("y", tux->get_tile_pos().y);
   writer.write_string("back", direction_to_string(tux->back_direction));
-  player_status.write(writer);
+  player_status->write(writer);
   writer.write_string("back", direction_to_string(tux->back_direction));
 
   writer.end_list("tux");
@@ -1141,76 +1133,85 @@ WorldMap::savegame(const std::string& filename)
 void
 WorldMap::loadgame(const std::string& filename)
 {
-  std::cout << "loadgame: " << filename << std::endl;
+  msg_debug("loadgame: " << filename);
   savegame_file = filename;
-
-  try {
-    lisp::Parser parser;
-    std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
   
-    const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
-    if(!savegame)
-      throw std::runtime_error("File is not a supertux-savegame file.");
-
-    /* Get the Map filename and then load it before setting level settings */
-    std::string cur_map_filename = map_filename;
-    savegame->get("map", map_filename);
-    load_map(); 
-
-    savegame->get("intro-displayed", intro_displayed);
-    savegame->get("lives", player_status.lives);
-    savegame->get("distros", player_status.distros);
-    savegame->get("max-score-multiplier", player_status.max_score_multiplier);
-    if (player_status.lives < 0)
-      player_status.reset();
-
-    const lisp::Lisp* tux_lisp = savegame->get_lisp("tux");
-    if(tux)
-    {
-      Vector p;
-      std::string back_str = "none";
+  if (PHYSFS_exists(filename.c_str())) // savegame exists
+  {
+    try {
+      lisp::Parser parser;
+      
+      std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
+    
+      const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
+      if(!savegame)
+        throw std::runtime_error("File is not a supertux-savegame file.");
+
+      /* Get the Map filename and then load it before setting level settings */
+      std::string cur_map_filename = map_filename;
+      savegame->get("map", map_filename);
+      load_map(); 
+
+      savegame->get("intro-displayed", intro_displayed);
+      savegame->get("lives", player_status->lives);
+      savegame->get("coins", player_status->coins);
+      savegame->get("max-score-multiplier", player_status->max_score_multiplier);
+      if (player_status->lives < 0)
+      player_status->reset();
+
+      const lisp::Lisp* tux_lisp = savegame->get_lisp("tux");
+      if(tux)
+      {
+        Vector p;
+        std::string back_str = "none";
 
-      tux_lisp->get("x", p.x);
-      tux_lisp->get("y", p.y);
-      tux_lisp->get("back", back_str);
-      player_status.read(*tux_lisp);
+        tux_lisp->get("x", p.x);
+        tux_lisp->get("y", p.y);
+        tux_lisp->get("back", back_str);
+          player_status->read(*tux_lisp);
       
-      tux->back_direction = string_to_direction(back_str);      
-      tux->set_tile_pos(p);
-    }
+        tux->back_direction = string_to_direction(back_str);      
+        tux->set_tile_pos(p);
+      }
 
-    const lisp::Lisp* levels_lisp = savegame->get_lisp("levels");
-    if(levels_lisp) {
-      lisp::ListIterator iter(levels_lisp);
-      while(iter.next()) {
-        if(iter.item() == "level") {
-          std::string name;
-          bool solved = false;
+      const lisp::Lisp* levels_lisp = savegame->get_lisp("levels");
+      if(levels_lisp) {
+        lisp::ListIterator iter(levels_lisp);
+        while(iter.next()) {
+          if(iter.item() == "level") {
+            std::string name;
+            bool solved = false;
 
-          const lisp::Lisp* level = iter.lisp();
-          level->get("name", name);
-          level->get("solved", solved);
+            const lisp::Lisp* level = iter.lisp();
+            level->get("name", name);
+            level->get("solved", solved);
 
-          for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
-          {
-            if (name == i->name)
+            for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
             {
-              i->solved = solved;
-              i->statistics.parse(*level);
-              break;
+              if (name == i->name)
+              {
+                i->solved = solved;
+                i->sprite->set_action(solved ? "solved" : "default");
+                i->statistics.parse(*level);
+                break;
+              }
             }
+          } else {
+            msg_warning("Unknown token '" << iter.item() 
+                      << "' in levels block in worldmap");
           }
-        } else {
-          std::cerr << "Unknown token '" << iter.item() 
-            << "' in levels block in worldmap.\n";
         }
       }
+    } catch(std::exception& e) {
+      msg_warning("Problem loading game '" << filename << "': " << e.what());
+      load_map();
+      player_status->reset();
     }
-  } catch(std::exception& e) {
-    std::cerr << "Problem loading game '" << filename << "': " << e.what() 
-      << "\n";
-    load_map();
-    player_status.reset();
+  }
+  else
+  {
+       load_map();
+    player_status->reset();
   }
 
   calculate_total_stats();