src/worldmap/worldmap.cpp

Go to the documentation of this file.
00001 //  SuperTux -  A Jump'n Run
00002 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
00003 //  Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
00004 //
00005 //  This program is free software: you can redistribute it and/or modify
00006 //  it under the terms of the GNU General Public License as published by
00007 //  the Free Software Foundation, either version 3 of the License, or
00008 //  (at your option) any later version.
00009 //
00010 //  This program is distributed in the hope that it will be useful,
00011 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013 //  GNU General Public License for more details.
00014 //
00015 //  You should have received a copy of the GNU General Public License
00016 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
00017 
00018 #include "worldmap/worldmap.hpp"
00019 
00020 #include <config.h>
00021 
00022 #include <assert.h>
00023 #include <fstream>
00024 #include <iostream>
00025 #include <physfs.h>
00026 #include <sstream>
00027 #include <stdexcept>
00028 #include <unistd.h>
00029 #include <vector>
00030 
00031 #include "audio/sound_manager.hpp"
00032 #include "control/joystickkeyboardcontroller.hpp"
00033 #include "gui/menu.hpp"
00034 #include "gui/menu_manager.hpp"
00035 #include "gui/mousecursor.hpp"
00036 #include "lisp/lisp.hpp"
00037 #include "lisp/list_iterator.hpp"
00038 #include "lisp/parser.hpp"
00039 #include "object/background.hpp"
00040 #include "object/decal.hpp"
00041 #include "object/tilemap.hpp"
00042 #include "physfs/ifile_stream.hpp"
00043 #include "scripting/squirrel_error.hpp"
00044 #include "scripting/squirrel_util.hpp"
00045 #include "sprite/sprite.hpp"
00046 #include "sprite/sprite_manager.hpp"
00047 #include "supertux/game_session.hpp"
00048 #include "supertux/globals.hpp"
00049 #include "supertux/screen_manager.hpp"
00050 #include "supertux/menu/menu_storage.hpp"
00051 #include "supertux/menu/options_menu.hpp"
00052 #include "supertux/menu/worldmap_menu.hpp"
00053 #include "supertux/player_status.hpp"
00054 #include "supertux/resources.hpp"
00055 #include "supertux/sector.hpp"
00056 #include "supertux/shrinkfade.hpp"
00057 #include "supertux/spawn_point.hpp"
00058 #include "supertux/textscroller.hpp"
00059 #include "supertux/tile_manager.hpp"
00060 #include "supertux/tile_set.hpp"
00061 #include "supertux/world.hpp"
00062 #include "util/file_system.hpp"
00063 #include "util/gettext.hpp"
00064 #include "util/log.hpp"
00065 #include "util/reader.hpp"
00066 #include "video/drawing_context.hpp"
00067 #include "video/surface.hpp"
00068 #include "worldmap/level.hpp"
00069 #include "worldmap/special_tile.hpp"
00070 #include "worldmap/sprite_change.hpp"
00071 #include "worldmap/tux.hpp"
00072 #include "worldmap/worldmap.hpp"
00073 
00074 static const float CAMERA_PAN_SPEED = 5.0;
00075 
00076 namespace worldmap {
00077 
00078 WorldMap* WorldMap::current_ = NULL;
00079 
00080 WorldMap::WorldMap(const std::string& filename, PlayerStatus* player_status, const std::string& force_spawnpoint) :
00081   tux(0),
00082   player_status(player_status),
00083   tileset(NULL), 
00084   free_tileset(false),
00085   worldmap_menu(),
00086   camera_offset(),
00087   name(),
00088   music(),
00089   init_script(),
00090   game_objects(),
00091   solid_tilemaps(),
00092   passive_message_timer(),
00093   passive_message(),
00094   map_filename(),
00095   levels_path(),
00096   special_tiles(),
00097   levels(),
00098   sprite_changes(),
00099   spawn_points(),
00100   teleporters(),
00101   total_stats(),
00102   worldmap_table(),
00103   scripts(),
00104   ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), 
00105   force_spawnpoint(force_spawnpoint),
00106   in_level(false), 
00107   pan_pos(),
00108   panning(false)
00109 {
00110   tux = new Tux(this);
00111   add_object(tux);
00112 
00113   name = "<no title>";
00114   music = "music/salcon.ogg";
00115 
00116   total_stats.reset();
00117 
00118   worldmap_menu.reset(new WorldmapMenu());
00119 
00120   // create a new squirrel table for the worldmap
00121   using namespace scripting;
00122 
00123   sq_collectgarbage(global_vm);
00124   sq_newtable(global_vm);
00125   sq_pushroottable(global_vm);
00126   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
00127     throw scripting::SquirrelError(global_vm, "Couldn't set worldmap_table delegate");
00128 
00129   sq_resetobject(&worldmap_table);
00130   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &worldmap_table)))
00131     throw scripting::SquirrelError(global_vm, "Couldn't get table from stack");
00132 
00133   sq_addref(global_vm, &worldmap_table);
00134   sq_pop(global_vm, 1);
00135 
00136   sound_manager->preload("sounds/warp.wav");
00137   
00138   // load worldmap objects
00139   load(filename);
00140 }
00141 
00142 WorldMap::~WorldMap()
00143 {
00144   using namespace scripting;
00145 
00146   if(free_tileset)
00147     delete tileset;
00148 
00149   for(GameObjects::iterator i = game_objects.begin();
00150       i != game_objects.end(); ++i) {
00151     GameObject* object = *i;
00152     try_unexpose(object);
00153     object->unref();
00154   }
00155 
00156   for(SpawnPoints::iterator i = spawn_points.begin();
00157       i != spawn_points.end(); ++i) {
00158     delete *i;
00159   }
00160 
00161   for(ScriptList::iterator i = scripts.begin();
00162       i != scripts.end(); ++i) {
00163     HSQOBJECT& object = *i;
00164     sq_release(global_vm, &object);
00165   }
00166   sq_release(global_vm, &worldmap_table);
00167 
00168   sq_collectgarbage(global_vm);
00169 
00170   if(current_ == this)
00171     current_ = NULL;
00172 }
00173 
00174 void
00175 WorldMap::add_object(GameObject* object)
00176 {
00177   TileMap* tilemap = dynamic_cast<TileMap*> (object);
00178   if(tilemap != 0 && tilemap->is_solid()) {
00179     solid_tilemaps.push_back(tilemap);
00180   }
00181 
00182   object->ref();
00183   try_expose(object);
00184   game_objects.push_back(object);
00185 }
00186 
00187 void
00188 WorldMap::try_expose(GameObject* object)
00189 {
00190   ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
00191   if(object_ != NULL) {
00192     HSQUIRRELVM vm = scripting::global_vm;
00193     sq_pushobject(vm, worldmap_table);
00194     object_->expose(vm, -1);
00195     sq_pop(vm, 1);
00196   }
00197 }
00198 
00199 void
00200 WorldMap::try_unexpose(GameObject* object)
00201 {
00202   ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
00203   if(object_ != NULL) {
00204     HSQUIRRELVM vm = scripting::global_vm;
00205     SQInteger oldtop = sq_gettop(vm);
00206     sq_pushobject(vm, worldmap_table);
00207     try {
00208       object_->unexpose(vm, -1);
00209     } catch(std::exception& e) {
00210       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
00211     }
00212     sq_settop(vm, oldtop);
00213   }
00214 }
00215 
00216 void
00217 WorldMap::move_to_spawnpoint(const std::string& spawnpoint, bool pan)
00218 {
00219   for(SpawnPoints::iterator i = spawn_points.begin(); i != spawn_points.end(); ++i) {
00220     SpawnPoint* sp = *i;
00221     if(sp->name == spawnpoint) {
00222       Vector p = sp->pos;
00223       tux->set_tile_pos(p);
00224       tux->set_direction(sp->auto_dir);
00225       if(pan) {
00226         panning = true;
00227         pan_pos = get_camera_pos_for_tux();
00228         clamp_camera_position(pan_pos);
00229       }
00230       return;
00231     }
00232   }
00233   log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
00234   if (spawnpoint != "main") {
00235     move_to_spawnpoint("main");
00236   }
00237 }
00238 
00239 void
00240 WorldMap::change(const std::string& filename, const std::string& force_spawnpoint)
00241 {
00242   g_screen_manager->exit_screen();
00243   g_screen_manager->push_screen(new WorldMap(filename, player_status, force_spawnpoint));
00244 }
00245 
00246 void
00247 WorldMap::load(const std::string& filename)
00248 {
00249   map_filename = filename;
00250   levels_path = FileSystem::dirname(map_filename);
00251 
00252   try {
00253     lisp::Parser parser;
00254     const lisp::Lisp* root = parser.parse(map_filename);
00255 
00256     const lisp::Lisp* level = root->get_lisp("supertux-level");
00257     if(level == NULL)
00258       throw std::runtime_error("file isn't a supertux-level file.");
00259 
00260     level->get("name", name);
00261 
00262     const lisp::Lisp* sector = level->get_lisp("sector");
00263     if(!sector)
00264       throw std::runtime_error("No sector specified in worldmap file.");
00265 
00266     const lisp::Lisp* tilesets_lisp = level->get_lisp("tilesets");
00267     if(tilesets_lisp != NULL) {
00268       tileset      = tile_manager->parse_tileset_definition(*tilesets_lisp);
00269       free_tileset = true;
00270     }
00271     std::string tileset_name;
00272     if(level->get("tileset", tileset_name)) {
00273       if(tileset != NULL) {
00274         log_warning << "multiple tilesets specified in level" << std::endl;
00275       } else {
00276         tileset = tile_manager->get_tileset(tileset_name);
00277       }
00278     }
00279     /* load default tileset */
00280     if(tileset == NULL) {
00281       tileset = tile_manager->get_tileset("images/worldmap.strf");
00282     }
00283     current_tileset = tileset;
00284 
00285     lisp::ListIterator iter(sector);
00286     while(iter.next()) {
00287       if(iter.item() == "tilemap") {
00288         add_object(new TileMap(*(iter.lisp())));
00289       } else if(iter.item() == "background") {
00290         add_object(new Background(*(iter.lisp())));
00291       } else if(iter.item() == "music") {
00292         iter.value()->get(music);
00293       } else if(iter.item() == "init-script") {
00294         iter.value()->get(init_script);
00295       } else if(iter.item() == "worldmap-spawnpoint") {
00296         SpawnPoint* sp = new SpawnPoint(*iter.lisp());
00297         spawn_points.push_back(sp);
00298       } else if(iter.item() == "level") {
00299         LevelTile* level = new LevelTile(levels_path, *iter.lisp());
00300         levels.push_back(level);
00301         add_object(level);
00302       } else if(iter.item() == "special-tile") {
00303         SpecialTile* special_tile = new SpecialTile(*iter.lisp());
00304         special_tiles.push_back(special_tile);
00305         add_object(special_tile);
00306       } else if(iter.item() == "sprite-change") {
00307         SpriteChange* sprite_change = new SpriteChange(*iter.lisp());
00308         sprite_changes.push_back(sprite_change);
00309         add_object(sprite_change);
00310       } else if(iter.item() == "teleporter") {
00311         Teleporter* teleporter = new Teleporter(*iter.lisp());
00312         teleporters.push_back(teleporter);
00313         add_object(teleporter);
00314       } else if(iter.item() == "decal") {
00315         Decal* decal = new Decal(*iter.lisp());
00316         add_object(decal);
00317       } else if(iter.item() == "ambient-light") {
00318         std::vector<float> vColor;
00319         sector->get( "ambient-light", vColor );
00320         if(vColor.size() < 3) {
00321           log_warning << "(ambient-light) requires a color as argument" << std::endl;
00322         } else {
00323           ambient_light = Color( vColor );
00324         }
00325       } else if(iter.item() == "name") {
00326         // skip
00327       } else {
00328         log_warning << "Unknown token '" << iter.item() << "' in worldmap" << std::endl;
00329       }
00330     }
00331     current_tileset = NULL;
00332 
00333     if(solid_tilemaps.size() == 0)
00334       throw std::runtime_error("No solid tilemap specified");
00335 
00336     move_to_spawnpoint("main");
00337 
00338   } catch(std::exception& e) {
00339     std::stringstream msg;
00340     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
00341       e.what();
00342     throw std::runtime_error(msg.str());
00343   }
00344 }
00345 
00346 void
00347 WorldMap::get_level_title(LevelTile& level)
00348 {
00350   level.title = "<no title>";
00351 
00352   try {
00353     lisp::Parser parser;
00354     const lisp::Lisp* root = parser.parse(levels_path + level.get_name());
00355 
00356     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
00357     if(!level_lisp)
00358       return;
00359 
00360     level_lisp->get("name", level.title);
00361   } catch(std::exception& e) {
00362     log_warning << "Problem when reading leveltitle: " << e.what() << std::endl;
00363     return;
00364   }
00365 }
00366 
00367 void WorldMap::calculate_total_stats()
00368 {
00369   total_stats.zero();
00370   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
00371     LevelTile* level = *i;
00372     if (level->solved) {
00373       total_stats += level->statistics;
00374     }
00375   }
00376 }
00377 
00378 void
00379 WorldMap::on_escape_press()
00380 {
00381   // Show or hide the menu
00382   if(!MenuManager::current()) {
00383     MenuManager::set_current(worldmap_menu.get());
00384     tux->set_direction(D_NONE);  // stop tux movement when menu is called
00385   } else {
00386     MenuManager::set_current(NULL);
00387   }
00388 }
00389 
00390 Vector
00391 WorldMap::get_next_tile(Vector pos, Direction direction)
00392 {
00393   switch(direction) {
00394     case D_WEST:
00395       pos.x -= 1;
00396       break;
00397     case D_EAST:
00398       pos.x += 1;
00399       break;
00400     case D_NORTH:
00401       pos.y -= 1;
00402       break;
00403     case D_SOUTH:
00404       pos.y += 1;
00405       break;
00406     case D_NONE:
00407       break;
00408   }
00409   return pos;
00410 }
00411 
00412 bool
00413 WorldMap::path_ok(Direction direction, const Vector& old_pos, Vector* new_pos)
00414 {
00415   *new_pos = get_next_tile(old_pos, direction);
00416 
00417   if (!(new_pos->x >= 0 && new_pos->x < get_width()
00418         && new_pos->y >= 0 && new_pos->y < get_height()))
00419   { // New position is outsite the tilemap
00420     return false;
00421   }
00422   else
00423   { // Check if the tile allows us to go to new_pos
00424     int old_tile_data = tile_data_at(old_pos);
00425     int new_tile_data = tile_data_at(*new_pos);
00426     switch(direction)
00427     {
00428       case D_WEST:
00429         return (old_tile_data & Tile::WORLDMAP_WEST
00430                 && new_tile_data & Tile::WORLDMAP_EAST);
00431 
00432       case D_EAST:
00433         return (old_tile_data & Tile::WORLDMAP_EAST
00434                 && new_tile_data & Tile::WORLDMAP_WEST);
00435 
00436       case D_NORTH:
00437         return (old_tile_data & Tile::WORLDMAP_NORTH
00438                 && new_tile_data & Tile::WORLDMAP_SOUTH);
00439 
00440       case D_SOUTH:
00441         return (old_tile_data & Tile::WORLDMAP_SOUTH
00442                 && new_tile_data & Tile::WORLDMAP_NORTH);
00443 
00444       case D_NONE:
00445         assert(!"path_ok() can't walk if direction is NONE");
00446     }
00447     return false;
00448   }
00449 }
00450 
00451 void
00452 WorldMap::finished_level(Level* gamelevel)
00453 {
00454   // TODO use Level* parameter here?
00455   LevelTile* level = at_level();
00456 
00457   bool old_level_state = level->solved;
00458   level->solved = true;
00459   level->sprite->set_action("solved");
00460 
00461   // deal with statistics
00462   level->statistics.merge(gamelevel->stats);
00463   calculate_total_stats();
00464 
00465   save_state();
00466 
00467   if (old_level_state != level->solved) {
00468     // Try to detect the next direction to which we should walk
00469     // FIXME: Mostly a hack
00470     Direction dir = D_NONE;
00471 
00472     int dirdata = available_directions_at(tux->get_tile_pos());
00473     // first, test for crossroads
00474     if (dirdata == Tile::WORLDMAP_CNSE ||
00475         dirdata == Tile::WORLDMAP_CNSW ||
00476         dirdata == Tile::WORLDMAP_CNEW ||
00477         dirdata == Tile::WORLDMAP_CSEW ||
00478         dirdata == Tile::WORLDMAP_CNSEW)
00479       dir = D_NONE;
00480     else if (dirdata & Tile::WORLDMAP_NORTH
00481              && tux->back_direction != D_NORTH)
00482       dir = D_NORTH;
00483     else if (dirdata & Tile::WORLDMAP_SOUTH
00484              && tux->back_direction != D_SOUTH)
00485       dir = D_SOUTH;
00486     else if (dirdata & Tile::WORLDMAP_EAST
00487              && tux->back_direction != D_EAST)
00488       dir = D_EAST;
00489     else if (dirdata & Tile::WORLDMAP_WEST
00490              && tux->back_direction != D_WEST)
00491       dir = D_WEST;
00492 
00493     if (dir != D_NONE) {
00494       tux->set_direction(dir);
00495     }
00496   }
00497 
00498   if (level->extro_script != "") {
00499     try {
00500       std::istringstream in(level->extro_script);
00501       run_script(in, "worldmap:extro_script");
00502     } catch(std::exception& e) {
00503       log_warning << "Couldn't run level-extro-script: " << e.what() << std::endl;
00504     }
00505   }
00506 }
00507 
00508 Vector
00509 WorldMap::get_camera_pos_for_tux() {
00510   Vector camera_offset;
00511   Vector tux_pos = tux->get_pos();
00512   camera_offset.x = tux_pos.x - SCREEN_WIDTH/2;
00513   camera_offset.y = tux_pos.y - SCREEN_HEIGHT/2;
00514   return camera_offset;
00515 }
00516 
00517 void
00518 WorldMap::clamp_camera_position(Vector& c) {
00519   if (c.x < 0)
00520     c.x = 0;
00521   if (c.y < 0)
00522     c.y = 0;
00523 
00524   if (c.x > (int)get_width()*32 - SCREEN_WIDTH)
00525     c.x = (int)get_width()*32 - SCREEN_WIDTH;
00526   if (c.y > (int)get_height()*32 - SCREEN_HEIGHT)
00527     c.y = (int)get_height()*32 - SCREEN_HEIGHT;
00528 
00529   if (int(get_width()*32) < SCREEN_WIDTH)
00530     c.x = get_width()*16.0 - SCREEN_WIDTH/2.0;
00531   if (int(get_height()*32) < SCREEN_HEIGHT)
00532     c.y = get_height()*16.0 - SCREEN_HEIGHT/2.0;
00533 }
00534 
00535 void
00536 WorldMap::update(float delta)
00537 {
00538   if(!in_level) {
00539     Menu* menu = MenuManager::current();
00540     if(menu != NULL) {
00541       if(menu == worldmap_menu.get()) {
00542         switch (worldmap_menu->check())
00543         {
00544           case MNID_RETURNWORLDMAP: // Return to game
00545             MenuManager::set_current(0);
00546             break;
00547           case MNID_QUITWORLDMAP: // Quit Worldmap
00548             g_screen_manager->exit_screen();
00549             break;
00550         }
00551       }
00552 
00553       return;
00554     }
00555 
00556     // update GameObjects
00557     for(size_t i = 0; i < game_objects.size(); ++i) {
00558       GameObject* object = game_objects[i];
00559       if(!panning || object != tux) {
00560         object->update(delta);
00561       }
00562     }
00563 
00564     // remove old GameObjects
00565     for(GameObjects::iterator i = game_objects.begin();
00566         i != game_objects.end(); ) {
00567       GameObject* object = *i;
00568       if(!object->is_valid()) {
00569         try_unexpose(object);
00570         object->unref();
00571         i = game_objects.erase(i);
00572       } else {
00573         ++i;
00574       }
00575     }
00576 
00577     /* update solid_tilemaps list */
00578     //FIXME: this could be more efficient
00579     solid_tilemaps.clear();
00580     for(std::vector<GameObject*>::iterator i = game_objects.begin();
00581         i != game_objects.end(); ++i)
00582     {
00583       TileMap* tm = dynamic_cast<TileMap*>(*i);
00584       if (!tm) continue;
00585       if (tm->is_solid()) solid_tilemaps.push_back(tm);
00586     }
00587 
00588     Vector requested_pos;
00589 
00590     // position "camera"
00591     if(!panning) {
00592       camera_offset = get_camera_pos_for_tux();
00593     } else {
00594       Vector delta = pan_pos - camera_offset;
00595       float mag = delta.norm();
00596       if(mag > CAMERA_PAN_SPEED) {
00597         delta *= CAMERA_PAN_SPEED/mag;
00598       }
00599       camera_offset += delta;
00600       if(camera_offset == pan_pos) {
00601         panning = false;
00602       }
00603     }
00604 
00605     requested_pos = camera_offset;
00606     clamp_camera_position(camera_offset);
00607 
00608     if(panning) {
00609       if(requested_pos.x != camera_offset.x) {
00610         pan_pos.x = camera_offset.x;
00611       }
00612       if(requested_pos.y != camera_offset.y) {
00613         pan_pos.y = camera_offset.y;
00614       }
00615     }
00616 
00617     // handle input
00618     Controller *controller = g_jk_controller->get_main_controller();
00619     bool enter_level = false;
00620     if(controller->pressed(Controller::ACTION)
00621        || controller->pressed(Controller::JUMP)
00622        || controller->pressed(Controller::MENU_SELECT)) {
00623       /* some people define UP and JUMP on the same key... */
00624       if(!controller->pressed(Controller::UP))
00625         enter_level = true;
00626     }
00627     if(controller->pressed(Controller::PAUSE_MENU))
00628       on_escape_press();
00629 
00630     // check for teleporters
00631     Teleporter* teleporter = at_teleporter(tux->get_tile_pos());
00632     if (teleporter && (teleporter->automatic || (enter_level && (!tux->is_moving())))) {
00633       enter_level = false;
00634       if (teleporter->worldmap != "") {
00635         change(teleporter->worldmap, teleporter->spawnpoint);
00636       } else {
00637         // TODO: an animation, camera scrolling or a fading would be a nice touch
00638         sound_manager->play("sounds/warp.wav");
00639         tux->back_direction = D_NONE;
00640         move_to_spawnpoint(teleporter->spawnpoint, true);
00641       }
00642     }
00643 
00644     // check for auto-play levels
00645     LevelTile* level = at_level();
00646     if (level && (level->auto_play) && (!level->solved) && (!tux->is_moving())) {
00647       enter_level = true;
00648     }
00649 
00650     if (enter_level && !tux->is_moving())
00651     {
00652       /* Check level action */
00653       LevelTile* level = at_level();
00654       if (!level) {
00655         //Respawn if player on a tile with no level and nowhere to go.
00656         int tile_data = tile_data_at(tux->get_tile_pos());
00657         if(!( tile_data & ( Tile::WORLDMAP_NORTH |  Tile::WORLDMAP_SOUTH | Tile::WORLDMAP_WEST | Tile::WORLDMAP_EAST ))){
00658           log_warning << "Player at illegal position " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << " respawning." << std::endl;
00659           move_to_spawnpoint("main");
00660           return;
00661         }
00662         log_warning << "No level to enter at: " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
00663         return;
00664       }
00665 
00666       if (level->pos == tux->get_tile_pos()) {
00667         try {
00668           Vector shrinkpos = Vector(level->pos.x*32 + 16 - camera_offset.x,
00669                                     level->pos.y*32 +  8 - camera_offset.y);
00670           std::string levelfile = levels_path + level->get_name();
00671 
00672           // update state and savegame
00673           save_state();
00674 
00675           g_screen_manager->push_screen(new GameSession(levelfile, player_status, &level->statistics),
00676                                    new ShrinkFade(shrinkpos, 1.0f));
00677           in_level = true;
00678         } catch(std::exception& e) {
00679           log_fatal << "Couldn't load level: " << e.what() << std::endl;
00680         }
00681       }
00682     }
00683     else
00684     {
00685       //      tux->set_direction(input_direction);
00686     }
00687   }
00688 }
00689 
00690 int
00691 WorldMap::tile_data_at(Vector p)
00692 {
00693   int dirs = 0;
00694 
00695   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
00696     TileMap* tilemap = *i;
00697     const Tile* tile = tilemap->get_tile((int)p.x, (int)p.y);
00698     int dirdata = tile->getData();
00699     dirs |= dirdata;
00700   }
00701 
00702   return dirs;
00703 }
00704 
00705 int
00706 WorldMap::available_directions_at(Vector p)
00707 {
00708   return tile_data_at(p) & Tile::WORLDMAP_DIR_MASK;
00709 }
00710 
00711 LevelTile*
00712 WorldMap::at_level()
00713 {
00714   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
00715     LevelTile* level = *i;
00716     if (level->pos == tux->get_tile_pos())
00717       return level;
00718   }
00719 
00720   return NULL;
00721 }
00722 
00723 SpecialTile*
00724 WorldMap::at_special_tile()
00725 {
00726   for(SpecialTiles::iterator i = special_tiles.begin();
00727       i != special_tiles.end(); ++i) {
00728     SpecialTile* special_tile = *i;
00729     if (special_tile->pos == tux->get_tile_pos())
00730       return special_tile;
00731   }
00732 
00733   return NULL;
00734 }
00735 
00736 SpriteChange*
00737 WorldMap::at_sprite_change(const Vector& pos)
00738 {
00739   for(SpriteChanges::iterator i = sprite_changes.begin();
00740       i != sprite_changes.end(); ++i) {
00741     SpriteChange* sprite_change = *i;
00742     if(sprite_change->pos == pos)
00743       return sprite_change;
00744   }
00745 
00746   return NULL;
00747 }
00748 
00749 Teleporter*
00750 WorldMap::at_teleporter(const Vector& pos)
00751 {
00752   for(std::vector<Teleporter*>::iterator i = teleporters.begin(); i != teleporters.end(); ++i) {
00753     Teleporter* teleporter = *i;
00754     if(teleporter->pos == pos) return teleporter;
00755   }
00756 
00757   return NULL;
00758 }
00759 
00760 void
00761 WorldMap::draw(DrawingContext& context)
00762 {
00763   if (int(get_width()*32) < SCREEN_WIDTH || int(get_height()*32) < SCREEN_HEIGHT)
00764     context.draw_filled_rect(Vector(0, 0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
00765                              Color(0.0f, 0.0f, 0.0f, 1.0f), LAYER_BACKGROUND0);
00766 
00767   context.set_ambient_color( ambient_light );
00768   context.push_transform();
00769   context.set_translation(camera_offset);
00770 
00771   for(GameObjects::iterator i = game_objects.begin();
00772       i != game_objects.end(); ++i) {
00773     GameObject* object = *i;
00774     if(!panning || object != tux) {
00775       object->draw(context);
00776     }
00777   }
00778 
00779   /*
00780   // FIXME: make this a runtime switch similar to draw_collrects/show_collrects?
00781   // draw visual indication of possible walk directions
00782   static int flipme = 0; 
00783   if (flipme++ & 0x04)
00784   for (int x = 0; x < get_width(); x++) {
00785   for (int y = 0; y < get_height(); y++) {
00786   int data = tile_data_at(Vector(x,y));
00787   int px = x * 32;
00788   int py = y * 32;
00789   const int W = 4;
00790   if (data & Tile::WORLDMAP_NORTH)    context.draw_filled_rect(Rect(px + 16-W, py       , px + 16+W, py + 16-W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
00791   if (data & Tile::WORLDMAP_SOUTH)    context.draw_filled_rect(Rect(px + 16-W, py + 16+W, px + 16+W, py + 32  ), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
00792   if (data & Tile::WORLDMAP_EAST)     context.draw_filled_rect(Rect(px + 16+W, py + 16-W, px + 32  , py + 16+W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
00793   if (data & Tile::WORLDMAP_WEST)     context.draw_filled_rect(Rect(px       , py + 16-W, px + 16-W, py + 16+W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
00794   if (data & Tile::WORLDMAP_DIR_MASK) context.draw_filled_rect(Rect(px + 16-W, py + 16-W, px + 16+W, py + 16+W), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
00795   if (data & Tile::WORLDMAP_STOP)     context.draw_filled_rect(Rect(px + 4   , py + 4   , px + 28  , py + 28  ), Color(0.2f, 0.2f, 0.2f, 0.7f), LAYER_FOREGROUND1 + 1000);
00796   }
00797   }
00798   */
00799 
00800   draw_status(context);
00801   context.pop_transform();
00802 }
00803 
00804 void
00805 WorldMap::draw_status(DrawingContext& context)
00806 {
00807   context.push_transform();
00808   context.set_translation(Vector(0, 0));
00809 
00810   player_status->draw(context);
00811 
00812   if (!tux->is_moving()) {
00813     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
00814       LevelTile* level = *i;
00815 
00816       if (level->pos == tux->get_tile_pos()) {
00817         if(level->title == "")
00818           get_level_title(*level);
00819 
00820         context.draw_text(Resources::normal_font, level->title,
00821                           Vector(SCREEN_WIDTH/2,
00822                                  SCREEN_HEIGHT - Resources::normal_font->get_height() - 30),
00823                           ALIGN_CENTER, LAYER_FOREGROUND1, WorldMap::level_title_color);
00824 
00825         // if level is solved, draw level picture behind stats
00826         /*
00827           if (level->solved) {
00828           if (const Surface* picture = level->get_picture()) {
00829           Vector pos = Vector(SCREEN_WIDTH - picture->get_width(), SCREEN_HEIGHT - picture->get_height());
00830           context.push_transform();
00831           context.set_alpha(0.5);
00832           context.draw_surface(picture, pos, LAYER_FOREGROUND1-1);
00833           context.pop_transform();
00834           }
00835           }
00836         */
00837 
00838         level->statistics.draw_worldmap_info(context);
00839         break;
00840       }
00841     }
00842 
00843     for(SpecialTiles::iterator i = special_tiles.begin();
00844         i != special_tiles.end(); ++i) {
00845       SpecialTile* special_tile = *i;
00846 
00847       if (special_tile->pos == tux->get_tile_pos()) {
00848         /* Display an in-map message in the map, if any as been selected */
00849         if(!special_tile->map_message.empty() && !special_tile->passive_message)
00850           context.draw_text(Resources::normal_font, special_tile->map_message,
00851                             Vector(SCREEN_WIDTH/2,
00852                                    SCREEN_HEIGHT - Resources::normal_font->get_height() - 60),
00853                             ALIGN_CENTER, LAYER_FOREGROUND1, WorldMap::message_color);
00854         break;
00855       }
00856     }
00857 
00858     // display teleporter messages
00859     Teleporter* teleporter = at_teleporter(tux->get_tile_pos());
00860     if (teleporter && (teleporter->message != "")) {
00861       Vector pos = Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - Resources::normal_font->get_height() - 30);
00862       context.draw_text(Resources::normal_font, teleporter->message, pos, ALIGN_CENTER, LAYER_FOREGROUND1, WorldMap::teleporter_message_color);
00863     }
00864 
00865   }
00866 
00867   /* Display a passive message in the map, if needed */
00868   if(passive_message_timer.started())
00869     context.draw_text(Resources::normal_font, passive_message,
00870                       Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - Resources::normal_font->get_height() - 60),
00871                       ALIGN_CENTER, LAYER_FOREGROUND1, WorldMap::message_color);
00872 
00873   context.pop_transform();
00874 }
00875 
00876 void
00877 WorldMap::setup()
00878 {
00879   sound_manager->play_music(music);
00880   MenuManager::set_current(NULL);
00881 
00882   current_ = this;
00883   load_state();
00884 
00885   // if force_spawnpoint was set, move Tux there, then clear force_spawnpoint
00886   if (force_spawnpoint != "") {
00887     move_to_spawnpoint(force_spawnpoint);
00888     force_spawnpoint = "";
00889   }
00890 
00891   tux->setup();
00892 
00893   // register worldmap_table as worldmap in scripting
00894   using namespace scripting;
00895 
00896   sq_pushroottable(global_vm);
00897   sq_pushstring(global_vm, "worldmap", -1);
00898   sq_pushobject(global_vm, worldmap_table);
00899   if(SQ_FAILED(sq_createslot(global_vm, -3)))
00900     throw SquirrelError(global_vm, "Couldn't set worldmap in roottable");
00901   sq_pop(global_vm, 1);
00902 
00903   //Run default.nut just before init script
00904   try {
00905     IFileStream in(levels_path + "/default.nut");
00906     run_script(in, "WorldMap::default.nut");
00907   } catch(std::exception& ) {
00908     // doesn't exist or erroneous; do nothing
00909   }
00910 
00911   if(init_script != "") {
00912     std::istringstream in(init_script);
00913     run_script(in, "WorldMap::init");
00914   }
00915 }
00916 
00917 void
00918 WorldMap::leave()
00919 {
00920   using namespace scripting;
00921 
00922   // save state of world and player
00923   save_state();
00924 
00925   // remove worldmap_table from roottable
00926   sq_pushroottable(global_vm);
00927   sq_pushstring(global_vm, "worldmap", -1);
00928   if(SQ_FAILED(sq_deleteslot(global_vm, -2, SQFalse)))
00929     throw SquirrelError(global_vm, "Couldn't unset worldmap in roottable");
00930   sq_pop(global_vm, 1);
00931 }
00932 
00933 void
00934 WorldMap::save_state()
00935 {
00936   using namespace scripting;
00937 
00938   HSQUIRRELVM vm = global_vm;
00939   int oldtop = sq_gettop(vm);
00940 
00941   try {
00942     // get state table
00943     sq_pushroottable(vm);
00944     sq_pushstring(vm, "state", -1);
00945     if(SQ_FAILED(sq_get(vm, -2)))
00946       throw scripting::SquirrelError(vm, "Couldn't get state table");
00947 
00948     // get or create worlds table
00949     sq_pushstring(vm, "worlds", -1);
00950     if(SQ_FAILED(sq_get(vm, -2))) {
00951       sq_pushstring(vm, "worlds", -1);
00952       sq_newtable(vm);
00953       if(SQ_FAILED(sq_createslot(vm, -3)))
00954         throw scripting::SquirrelError(vm, "Couldn't create state.worlds");
00955 
00956       sq_pushstring(vm, "worlds", -1);
00957       if(SQ_FAILED(sq_get(vm, -2)))
00958         throw scripting::SquirrelError(vm, "Couldn't create.get state.worlds");
00959     }
00960 
00961     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
00962     if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
00963       sq_pop(vm, 1);
00964 
00965     // construct new table for this worldmap
00966     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
00967     sq_newtable(vm);
00968 
00969     // store tux
00970     sq_pushstring(vm, "tux", -1);
00971     sq_newtable(vm);
00972 
00973     store_float(vm, "x", tux->get_tile_pos().x);
00974     store_float(vm, "y", tux->get_tile_pos().y);
00975     store_string(vm, "back", direction_to_string(tux->back_direction));
00976 
00977     sq_createslot(vm, -3);
00978 
00979     // levels...
00980     sq_pushstring(vm, "levels", -1);
00981     sq_newtable(vm);
00982 
00983     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
00984       LevelTile* level = *i;
00985 
00986       sq_pushstring(vm, level->get_name().c_str(), -1);
00987       sq_newtable(vm);
00988 
00989       store_bool(vm, "solved", level->solved);
00990       level->statistics.serialize_to_squirrel(vm);
00991 
00992       sq_createslot(vm, -3);
00993     }
00994 
00995     sq_createslot(vm, -3);
00996 
00997     // overall statistics...
00998     total_stats.serialize_to_squirrel(vm);
00999 
01000     // push world into worlds table
01001     sq_createslot(vm, -3);
01002   } catch(std::exception& ) {
01003     sq_settop(vm, oldtop);
01004   }
01005 
01006   sq_settop(vm, oldtop);
01007 
01008   if(World::current() != NULL)
01009     World::current()->save_state();
01010 }
01011 
01012 void
01013 WorldMap::load_state()
01014 {
01015   using namespace scripting;
01016 
01017   HSQUIRRELVM vm = global_vm;
01018   int oldtop = sq_gettop(vm);
01019 
01020   try {
01021     // get state table
01022     sq_pushroottable(vm);
01023     sq_pushstring(vm, "state", -1);
01024     if(SQ_FAILED(sq_get(vm, -2)))
01025       throw scripting::SquirrelError(vm, "Couldn't get state table");
01026 
01027     // get worlds table
01028     sq_pushstring(vm, "worlds", -1);
01029     if(SQ_FAILED(sq_get(vm, -2)))
01030       throw scripting::SquirrelError(vm, "Couldn't get state.worlds");
01031 
01032     // get table for our world
01033     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
01034     if(SQ_FAILED(sq_get(vm, -2)))
01035       throw scripting::SquirrelError(vm, "Couldn't get state.worlds.mapfilename");
01036 
01037     // load tux
01038     sq_pushstring(vm, "tux", -1);
01039     if(SQ_FAILED(sq_get(vm, -2)))
01040       throw scripting::SquirrelError(vm, "Couldn't get tux");
01041 
01042     Vector p;
01043     p.x = read_float(vm, "x");
01044     p.y = read_float(vm, "y");
01045     std::string back_str = read_string(vm, "back");
01046     tux->back_direction = string_to_direction(back_str);
01047     tux->set_tile_pos(p);
01048 
01049     sq_pop(vm, 1);
01050 
01051     // load levels
01052     sq_pushstring(vm, "levels", -1);
01053     if(SQ_FAILED(sq_get(vm, -2)))
01054       throw scripting::SquirrelError(vm, "Couldn't get levels");
01055 
01056     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
01057       LevelTile* level = *i;
01058       sq_pushstring(vm, level->get_name().c_str(), -1);
01059       if(SQ_SUCCEEDED(sq_get(vm, -2))) {
01060         level->solved = read_bool(vm, "solved");
01061         level->sprite->set_action(level->solved ? "solved" : "default");
01062         level->statistics.unserialize_from_squirrel(vm);
01063         sq_pop(vm, 1);
01064       }
01065     }
01066 
01067     // leave state table
01068     sq_pop(vm, 1);
01069 
01070     // load overall statistics
01071     total_stats.unserialize_from_squirrel(vm);
01072 
01073   } catch(std::exception& e) {
01074     log_debug << "Not loading worldmap state: " << e.what() << std::endl;
01075   }
01076   sq_settop(vm, oldtop);
01077 
01078   in_level = false;
01079 }
01080 
01081 size_t
01082 WorldMap::level_count()
01083 {
01084   return levels.size();
01085 }
01086 
01087 size_t
01088 WorldMap::solved_level_count()
01089 {
01090   size_t count = 0;
01091   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
01092     LevelTile* level = *i;
01093 
01094     if(level->solved)
01095       count++;
01096   }
01097 
01098   return count;
01099 }
01100 
01101 HSQUIRRELVM
01102 WorldMap::run_script(std::istream& in, const std::string& sourcename)
01103 {
01104   using namespace scripting;
01105 
01106   // garbage collect thread list
01107   for(ScriptList::iterator i = scripts.begin();
01108       i != scripts.end(); ) {
01109     HSQOBJECT& object = *i;
01110     HSQUIRRELVM vm = object_to_vm(object);
01111 
01112     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
01113       sq_release(global_vm, &object);
01114       i = scripts.erase(i);
01115       continue;
01116     }
01117 
01118     ++i;
01119   }
01120 
01121   HSQOBJECT object = create_thread(global_vm);
01122   scripts.push_back(object);
01123 
01124   HSQUIRRELVM vm = object_to_vm(object);
01125 
01126   // set worldmap_table as roottable for the thread
01127   sq_pushobject(vm, worldmap_table);
01128   sq_setroottable(vm);
01129 
01130   compile_and_run(vm, in, sourcename);
01131 
01132   return vm;
01133 }
01134 
01135 float
01136 WorldMap::get_width() const
01137 {
01138   float width = 0;
01139   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
01140     TileMap* solids = *i;
01141     if (solids->get_width() > width) width = solids->get_width();
01142   }
01143   return width;
01144 }
01145 
01146 float
01147 WorldMap::get_height() const
01148 {
01149   float height = 0;
01150   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
01151     TileMap* solids = *i;
01152     if (solids->get_height() > height) height = solids->get_height();
01153   }
01154   return height;
01155 }
01156 
01157 } // namespace worldmap
01158 
01159 /* EOF */

Generated on Mon Jun 9 03:38:25 2014 for SuperTux by  doxygen 1.5.1