* Use overloading in Lisp and Writer
[supertux.git] / src / worldmap / worldmap.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
5 //  Copyright (C) 2006 Christoph Sommer <christoph.sommer@2006.expires.deltadevelopment.de>
6 //
7 //  This program is free software; you can redistribute it and/or
8 //  modify it under the terms of the GNU General Public License
9 //  as published by the Free Software Foundation; either version 2
10 //  of the License, or (at your option) any later version.
11 //
12 //  This program is distributed in the hope that it will be useful,
13 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 //  GNU General Public License for more details.
16 //
17 //  You should have received a copy of the GNU General Public License
18 //  along with this program; if not, write to the Free Software
19 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
20 #include <config.h>
21
22 #include <iostream>
23 #include <fstream>
24 #include <vector>
25 #include <cassert>
26 #include <stdexcept>
27 #include <sstream>
28 #include <unistd.h>
29 #include <physfs.h>
30
31 #include "worldmap.hpp"
32
33 #include "gettext.hpp"
34 #include "log.hpp"
35 #include "mainloop.hpp"
36 #include "shrinkfade.hpp"
37 #include "video/surface.hpp"
38 #include "video/drawing_context.hpp"
39 #include "sprite/sprite.hpp"
40 #include "sprite/sprite_manager.hpp"
41 #include "audio/sound_manager.hpp"
42 #include "lisp/parser.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/list_iterator.hpp"
45 #include "lisp/writer.hpp"
46 #include "game_session.hpp"
47 #include "sector.hpp"
48 #include "worldmap.hpp"
49 #include "resources.hpp"
50 #include "log.hpp"
51 #include "world.hpp"
52 #include "player_status.hpp"
53 #include "textscroller.hpp"
54 #include "main.hpp"
55 #include "spawn_point.hpp"
56 #include "file_system.hpp"
57 #include "physfs/physfs_stream.hpp"
58 #include "tile_manager.hpp"
59 #include "tile_set.hpp"
60 #include "gui/menu.hpp"
61 #include "gui/mousecursor.hpp"
62 #include "control/joystickkeyboardcontroller.hpp"
63 #include "object/background.hpp"
64 #include "object/tilemap.hpp"
65 #include "options_menu.hpp"
66 #include "scripting/squirrel_error.hpp"
67 #include "scripting/squirrel_util.hpp"
68 #include "worldmap/level.hpp"
69 #include "worldmap/special_tile.hpp"
70 #include "worldmap/tux.hpp"
71 #include "worldmap/sprite_change.hpp"
72
73 static const float CAMERA_PAN_SPEED = 5.0;
74
75 namespace WorldMapNS {
76
77 enum WorldMapMenuIDs {
78   MNID_RETURNWORLDMAP,
79   MNID_QUITWORLDMAP
80 };
81
82 WorldMap* WorldMap::current_ = NULL;
83
84 Direction reverse_dir(Direction direction)
85 {
86   switch(direction)
87     {
88     case D_WEST:
89       return D_EAST;
90     case D_EAST:
91       return D_WEST;
92     case D_NORTH:
93       return D_SOUTH;
94     case D_SOUTH:
95       return D_NORTH;
96     case D_NONE:
97       return D_NONE;
98     }
99   return D_NONE;
100 }
101
102 std::string
103 direction_to_string(Direction direction)
104 {
105   switch(direction)
106     {
107     case D_WEST:
108       return "west";
109     case D_EAST:
110       return "east";
111     case D_NORTH:
112       return "north";
113     case D_SOUTH:
114       return "south";
115     default:
116       return "none";
117     }
118 }
119
120 Direction
121 string_to_direction(const std::string& directory)
122 {
123   if (directory == "west")
124     return D_WEST;
125   else if (directory == "east")
126     return D_EAST;
127   else if (directory == "north")
128     return D_NORTH;
129   else if (directory == "south")
130     return D_SOUTH;
131   else if (directory == "none")
132     return D_NONE;
133   else {
134     log_warning << "unknown direction: \"" << directory << "\"" << std::endl;
135     return D_NONE;
136   }
137 }
138
139 //---------------------------------------------------------------------------
140
141 WorldMap::WorldMap(const std::string& filename, const std::string& force_spawnpoint)
142   : tux(0), tileset(NULL), free_tileset(false),
143     ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), force_spawnpoint(force_spawnpoint),
144     in_level(false), panning(false)
145 {
146   tux = new Tux(this);
147   add_object(tux);
148
149   name = "<no title>";
150   music = "music/salcon.ogg";
151
152   total_stats.reset();
153
154   worldmap_menu.reset(new Menu());
155   worldmap_menu->add_label(_("Pause"));
156   worldmap_menu->add_hl();
157   worldmap_menu->add_entry(MNID_RETURNWORLDMAP, _("Continue"));
158   worldmap_menu->add_submenu(_("Options"), get_options_menu());
159   worldmap_menu->add_hl();
160   worldmap_menu->add_entry(MNID_QUITWORLDMAP, _("Quit World"));
161
162   // create a new squirrel table for the worldmap
163   using namespace Scripting;
164
165   sq_collectgarbage(global_vm);
166   sq_newtable(global_vm);
167   sq_pushroottable(global_vm);
168   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
169     throw Scripting::SquirrelError(global_vm, "Couldn't set worldmap_table delegate");
170
171   sq_resetobject(&worldmap_table);
172   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &worldmap_table)))
173     throw Scripting::SquirrelError(global_vm, "Couldn't get table from stack");
174
175   sq_addref(global_vm, &worldmap_table);
176   sq_pop(global_vm, 1);
177
178   sound_manager->preload("sounds/warp.wav");
179   
180   // load worldmap objects
181   load(filename);
182 }
183
184 WorldMap::~WorldMap()
185 {
186   using namespace Scripting;
187
188   if(free_tileset)
189     delete tileset;
190
191   for(GameObjects::iterator i = game_objects.begin();
192       i != game_objects.end(); ++i) {
193     GameObject* object = *i;
194     try_unexpose(object);
195     object->unref();
196   }
197
198   for(SpawnPoints::iterator i = spawn_points.begin();
199       i != spawn_points.end(); ++i) {
200     delete *i;
201   }
202
203   for(ScriptList::iterator i = scripts.begin();
204       i != scripts.end(); ++i) {
205     HSQOBJECT& object = *i;
206     sq_release(global_vm, &object);
207   }
208   sq_release(global_vm, &worldmap_table);
209
210   sq_collectgarbage(global_vm);
211
212   if(current_ == this)
213     current_ = NULL;
214 }
215
216 void
217 WorldMap::add_object(GameObject* object)
218 {
219   TileMap* tilemap = dynamic_cast<TileMap*> (object);
220   if(tilemap != 0 && tilemap->is_solid()) {
221     solid_tilemaps.push_back(tilemap);
222   }
223
224   object->ref();
225   try_expose(object);
226   game_objects.push_back(object);
227 }
228
229 void
230 WorldMap::try_expose(GameObject* object)
231 {
232   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
233   if(interface != NULL) {
234     HSQUIRRELVM vm = Scripting::global_vm;
235     sq_pushobject(vm, worldmap_table);
236     interface->expose(vm, -1);
237     sq_pop(vm, 1);
238   }
239 }
240
241 void
242 WorldMap::try_unexpose(GameObject* object)
243 {
244   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
245   if(interface != NULL) {
246     HSQUIRRELVM vm = Scripting::global_vm;
247     SQInteger oldtop = sq_gettop(vm);
248     sq_pushobject(vm, worldmap_table);
249     try {
250       interface->unexpose(vm, -1);
251     } catch(std::exception& e) {
252       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
253     }
254     sq_settop(vm, oldtop);
255   }
256 }
257
258 void
259 WorldMap::move_to_spawnpoint(const std::string& spawnpoint, bool pan)
260 {
261   for(SpawnPoints::iterator i = spawn_points.begin(); i != spawn_points.end(); ++i) {
262     SpawnPoint* sp = *i;
263     if(sp->name == spawnpoint) {
264       Vector p = sp->pos;
265       tux->set_tile_pos(p);
266       tux->set_direction(sp->auto_dir);
267       if(pan) {
268         panning = true;
269         pan_pos = get_camera_pos_for_tux();
270         clamp_camera_position(pan_pos);
271       }
272       return;
273     }
274   }
275   log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
276   if (spawnpoint != "main") {
277     move_to_spawnpoint("main");
278   }
279 }
280
281 void
282 WorldMap::change(const std::string& filename, const std::string& force_spawnpoint)
283 {
284   main_loop->exit_screen();
285   main_loop->push_screen(new WorldMap(filename, force_spawnpoint));
286 }
287
288 void
289 WorldMap::load(const std::string& filename)
290 {
291   map_filename = filename;
292   levels_path = FileSystem::dirname(map_filename);
293
294   try {
295     lisp::Parser parser;
296     const lisp::Lisp* root = parser.parse(map_filename);
297
298     const lisp::Lisp* level = root->get_lisp("supertux-level");
299     if(level == NULL)
300       throw std::runtime_error("file isn't a supertux-level file.");
301
302     level->get("name", name);
303
304     const lisp::Lisp* sector = level->get_lisp("sector");
305     if(!sector)
306       throw std::runtime_error("No sector specified in worldmap file.");
307
308     const lisp::Lisp* tilesets_lisp = level->get_lisp("tilesets");
309     if(tilesets_lisp != NULL) {
310       tileset      = tile_manager->parse_tileset_definition(*tilesets_lisp);
311       free_tileset = true;
312     }
313     std::string tileset_name;
314     if(level->get("tileset", tileset_name)) {
315       if(tileset != NULL) {
316         log_warning << "multiple tilesets specified in level" << std::endl;
317       } else {
318         tileset = tile_manager->get_tileset(tileset_name);
319       }
320     }
321     /* load default tileset */
322     if(tileset == NULL) {
323       tileset = tile_manager->get_tileset("images/worldmap.strf");
324     }
325     current_tileset = tileset;
326
327     lisp::ListIterator iter(sector);
328     while(iter.next()) {
329       if(iter.item() == "tilemap") {
330         add_object(new TileMap(*(iter.lisp())));
331       } else if(iter.item() == "background") {
332         add_object(new Background(*(iter.lisp())));
333       } else if(iter.item() == "music") {
334         iter.value()->get(music);
335       } else if(iter.item() == "init-script") {
336         iter.value()->get(init_script);
337       } else if(iter.item() == "worldmap-spawnpoint") {
338         SpawnPoint* sp = new SpawnPoint(iter.lisp());
339         spawn_points.push_back(sp);
340       } else if(iter.item() == "level") {
341         LevelTile* level = new LevelTile(levels_path, iter.lisp());
342         levels.push_back(level);
343         add_object(level);
344       } else if(iter.item() == "special-tile") {
345         SpecialTile* special_tile = new SpecialTile(iter.lisp());
346         special_tiles.push_back(special_tile);
347         add_object(special_tile);
348       } else if(iter.item() == "sprite-change") {
349         SpriteChange* sprite_change = new SpriteChange(iter.lisp());
350         sprite_changes.push_back(sprite_change);
351         add_object(sprite_change);
352       } else if(iter.item() == "teleporter") {
353         Teleporter* teleporter = new Teleporter(iter.lisp());
354         teleporters.push_back(teleporter);
355         add_object(teleporter);
356       } else if(iter.item() == "ambient-light") {
357         std::vector<float> vColor;
358         sector->get( "ambient-light", vColor );
359         if(vColor.size() < 3) {
360           log_warning << "(ambient-light) requires a color as argument" << std::endl;
361         } else {
362           ambient_light = Color( vColor );
363         }
364       } else if(iter.item() == "name") {
365         // skip
366       } else {
367         log_warning << "Unknown token '" << iter.item() << "' in worldmap" << std::endl;
368       }
369     }
370     current_tileset = NULL;
371
372     if(solid_tilemaps.size() == 0)
373       throw std::runtime_error("No solid tilemap specified");
374
375     move_to_spawnpoint("main");
376
377   } catch(std::exception& e) {
378     std::stringstream msg;
379     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
380       e.what();
381     throw std::runtime_error(msg.str());
382   }
383 }
384
385 void
386 WorldMap::get_level_title(LevelTile& level)
387 {
388   /** get special_tile's title */
389   level.title = "<no title>";
390
391   try {
392     lisp::Parser parser;
393     const lisp::Lisp* root = parser.parse(levels_path + level.get_name());
394
395     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
396     if(!level_lisp)
397       return;
398
399     level_lisp->get("name", level.title);
400   } catch(std::exception& e) {
401     log_warning << "Problem when reading leveltitle: " << e.what() << std::endl;
402     return;
403   }
404 }
405
406 void WorldMap::calculate_total_stats()
407 {
408   total_stats.zero();
409   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
410     LevelTile* level = *i;
411     if (level->solved) {
412       total_stats += level->statistics;
413     }
414   }
415 }
416
417 void
418 WorldMap::on_escape_press()
419 {
420   // Show or hide the menu
421   if(!Menu::current()) {
422     Menu::set_current(worldmap_menu.get());
423     tux->set_direction(D_NONE);  // stop tux movement when menu is called
424   } else {
425     Menu::set_current(NULL);
426   }
427 }
428
429 Vector
430 WorldMap::get_next_tile(Vector pos, Direction direction)
431 {
432   switch(direction) {
433     case D_WEST:
434       pos.x -= 1;
435       break;
436     case D_EAST:
437       pos.x += 1;
438       break;
439     case D_NORTH:
440       pos.y -= 1;
441       break;
442     case D_SOUTH:
443       pos.y += 1;
444       break;
445     case D_NONE:
446       break;
447   }
448   return pos;
449 }
450
451 bool
452 WorldMap::path_ok(Direction direction, const Vector& old_pos, Vector* new_pos)
453 {
454   *new_pos = get_next_tile(old_pos, direction);
455
456   if (!(new_pos->x >= 0 && new_pos->x < get_width()
457         && new_pos->y >= 0 && new_pos->y < get_height()))
458     { // New position is outsite the tilemap
459       return false;
460     }
461   else
462     { // Check if the tile allows us to go to new_pos
463       int old_tile_data = tile_data_at(old_pos);
464       int new_tile_data = tile_data_at(*new_pos);
465       switch(direction)
466         {
467         case D_WEST:
468           return (old_tile_data & Tile::WORLDMAP_WEST
469               && new_tile_data & Tile::WORLDMAP_EAST);
470
471         case D_EAST:
472           return (old_tile_data & Tile::WORLDMAP_EAST
473               && new_tile_data & Tile::WORLDMAP_WEST);
474
475         case D_NORTH:
476           return (old_tile_data & Tile::WORLDMAP_NORTH
477               && new_tile_data & Tile::WORLDMAP_SOUTH);
478
479         case D_SOUTH:
480           return (old_tile_data & Tile::WORLDMAP_SOUTH
481               && new_tile_data & Tile::WORLDMAP_NORTH);
482
483         case D_NONE:
484           assert(!"path_ok() can't walk if direction is NONE");
485         }
486       return false;
487     }
488 }
489
490 void
491 WorldMap::finished_level(Level* gamelevel)
492 {
493   // TODO use Level* parameter here?
494   LevelTile* level = at_level();
495
496   bool old_level_state = level->solved;
497   level->solved = true;
498   level->sprite->set_action("solved");
499
500   // deal with statistics
501   level->statistics.merge(gamelevel->stats);
502   calculate_total_stats();
503
504   save_state();
505
506   if (old_level_state != level->solved) {
507     // Try to detect the next direction to which we should walk
508     // FIXME: Mostly a hack
509     Direction dir = D_NONE;
510
511     int dirdata = available_directions_at(tux->get_tile_pos());
512     // first, test for crossroads
513     if (dirdata == Tile::WORLDMAP_CNSE ||
514         dirdata == Tile::WORLDMAP_CNSW ||
515         dirdata == Tile::WORLDMAP_CNEW ||
516         dirdata == Tile::WORLDMAP_CSEW ||
517         dirdata == Tile::WORLDMAP_CNSEW)
518       dir = D_NONE;
519     else if (dirdata & Tile::WORLDMAP_NORTH
520         && tux->back_direction != D_NORTH)
521       dir = D_NORTH;
522     else if (dirdata & Tile::WORLDMAP_SOUTH
523         && tux->back_direction != D_SOUTH)
524       dir = D_SOUTH;
525     else if (dirdata & Tile::WORLDMAP_EAST
526         && tux->back_direction != D_EAST)
527       dir = D_EAST;
528     else if (dirdata & Tile::WORLDMAP_WEST
529         && tux->back_direction != D_WEST)
530       dir = D_WEST;
531
532     if (dir != D_NONE) {
533       tux->set_direction(dir);
534     }
535   }
536
537   if (level->extro_script != "") {
538     try {
539       std::istringstream in(level->extro_script);
540       run_script(in, "worldmap:extro_script");
541     } catch(std::exception& e) {
542       log_fatal << "Couldn't run level-extro-script: " << e.what() << std::endl;
543     }
544   }
545 }
546
547 Vector
548 WorldMap::get_camera_pos_for_tux() {
549   Vector camera_offset;
550   Vector tux_pos = tux->get_pos();
551   camera_offset.x = tux_pos.x - SCREEN_WIDTH/2;
552   camera_offset.y = tux_pos.y - SCREEN_HEIGHT/2;
553   return camera_offset;
554 }
555
556 void
557 WorldMap::clamp_camera_position(Vector& c) {
558   if (c.x < 0)
559     c.x = 0;
560   if (c.y < 0)
561     c.y = 0;
562
563   if (c.x > (int)get_width()*32 - SCREEN_WIDTH)
564     c.x = (int)get_width()*32 - SCREEN_WIDTH;
565   if (c.y > (int)get_height()*32 - SCREEN_HEIGHT)
566     c.y = (int)get_height()*32 - SCREEN_HEIGHT;
567
568   if (int(get_width()*32) < SCREEN_WIDTH)
569     c.x = get_width()*16.0 - SCREEN_WIDTH/2.0;
570   if (int(get_height()*32) < SCREEN_HEIGHT)
571     c.y = get_height()*16.0 - SCREEN_HEIGHT/2.0;
572 }
573
574 void
575 WorldMap::update(float delta)
576 {
577   if(!in_level) {
578     Menu* menu = Menu::current();
579     if(menu != NULL) {
580       menu->update();
581
582       if(menu == worldmap_menu.get()) {
583         switch (worldmap_menu->check())
584         {
585           case MNID_RETURNWORLDMAP: // Return to game
586             Menu::set_current(0);
587             break;
588           case MNID_QUITWORLDMAP: // Quit Worldmap
589             main_loop->exit_screen();
590             break;
591         }
592       }
593
594       return;
595     }
596
597     // update GameObjects
598     for(size_t i = 0; i < game_objects.size(); ++i) {
599       GameObject* object = game_objects[i];
600       if(!panning || object != tux) {
601           object->update(delta);
602       }
603     }
604
605     // remove old GameObjects
606     for(GameObjects::iterator i = game_objects.begin();
607         i != game_objects.end(); ) {
608       GameObject* object = *i;
609       if(!object->is_valid()) {
610         try_unexpose(object);
611         object->unref();
612         i = game_objects.erase(i);
613       } else {
614         ++i;
615       }
616     }
617
618     /* update solid_tilemaps list */
619     //FIXME: this could be more efficient
620     solid_tilemaps.clear();
621     for(std::vector<GameObject*>::iterator i = game_objects.begin();
622         i != game_objects.end(); ++i)
623     {
624       TileMap* tm = dynamic_cast<TileMap*>(*i);
625       if (!tm) continue;
626       if (tm->is_solid()) solid_tilemaps.push_back(tm);
627     }
628
629     Vector requested_pos;
630
631     // position "camera"
632     if(!panning) {
633       camera_offset = get_camera_pos_for_tux();
634     } else {
635       Vector delta = pan_pos - camera_offset;
636       float mag = delta.norm();
637       if(mag > CAMERA_PAN_SPEED) {
638         delta *= CAMERA_PAN_SPEED/mag;
639       }
640       camera_offset += delta;
641       if(camera_offset == pan_pos) {
642         panning = false;
643       }
644     }
645
646     requested_pos = camera_offset;
647     clamp_camera_position(camera_offset);
648
649     if(panning) {
650         if(requested_pos.x != camera_offset.x) {
651             pan_pos.x = camera_offset.x;
652         }
653         if(requested_pos.y != camera_offset.y) {
654             pan_pos.y = camera_offset.y;
655         }
656     }
657
658     // handle input
659     bool enter_level = false;
660     if(main_controller->pressed(Controller::ACTION)
661         || main_controller->pressed(Controller::JUMP)
662         || main_controller->pressed(Controller::MENU_SELECT)) {
663       /* some people define UP and JUMP on the same key... */
664       if(!main_controller->pressed(Controller::UP))
665         enter_level = true;
666     }
667     if(main_controller->pressed(Controller::PAUSE_MENU))
668       on_escape_press();
669
670     // check for teleporters
671     Teleporter* teleporter = at_teleporter(tux->get_tile_pos());
672     if (teleporter && (teleporter->automatic || (enter_level && (!tux->is_moving())))) {
673       enter_level = false;
674       if (teleporter->worldmap != "") {
675         change(teleporter->worldmap, teleporter->spawnpoint);
676       } else {
677         // TODO: an animation, camera scrolling or a fading would be a nice touch
678         sound_manager->play("sounds/warp.wav");
679         tux->back_direction = D_NONE;
680         move_to_spawnpoint(teleporter->spawnpoint, true);
681       }
682     }
683
684     // check for auto-play levels
685     LevelTile* level = at_level();
686     if (level && (level->auto_play) && (!level->solved) && (!tux->is_moving())) {
687       enter_level = true;
688     }
689
690     if (enter_level && !tux->is_moving())
691       {
692         /* Check level action */
693         LevelTile* level = at_level();
694         if (!level) {
695           //Respawn if player on a tile with no level and nowhere to go.
696           int tile_data = tile_data_at(tux->get_tile_pos());
697           if(!( tile_data & ( Tile::WORLDMAP_NORTH |  Tile::WORLDMAP_SOUTH | Tile::WORLDMAP_WEST | Tile::WORLDMAP_EAST ))){
698             log_warning << "Player at illegal position " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << " respawning." << std::endl;
699             move_to_spawnpoint("main");
700             return;
701           }
702           log_warning << "No level to enter at: " << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
703           return;
704         }
705
706         if (level->pos == tux->get_tile_pos()) {
707           try {
708             Vector shrinkpos = Vector(level->pos.x*32 + 16 - camera_offset.x,
709                                       level->pos.y*32 +  8 - camera_offset.y);
710             std::string levelfile = levels_path + level->get_name();
711
712             // update state and savegame
713             save_state();
714
715             main_loop->push_screen(new GameSession(levelfile, &level->statistics),
716                                    new ShrinkFade(shrinkpos, 1.0f));
717             in_level = true;
718           } catch(std::exception& e) {
719             log_fatal << "Couldn't load level: " << e.what() << std::endl;
720           }
721         }
722       }
723     else
724       {
725   //      tux->set_direction(input_direction);
726       }
727   }
728 }
729
730 int
731 WorldMap::tile_data_at(Vector p)
732 {
733   int dirs = 0;
734
735   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
736     TileMap* tilemap = *i;
737     const Tile* tile = tilemap->get_tile((int)p.x, (int)p.y);
738     int dirdata = tile->getData();
739     dirs |= dirdata;
740   }
741
742   return dirs;
743 }
744
745 int
746 WorldMap::available_directions_at(Vector p)
747 {
748   return tile_data_at(p) & Tile::WORLDMAP_DIR_MASK;
749 }
750
751 LevelTile*
752 WorldMap::at_level()
753 {
754   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
755     LevelTile* level = *i;
756     if (level->pos == tux->get_tile_pos())
757       return level;
758   }
759
760   return NULL;
761 }
762
763 SpecialTile*
764 WorldMap::at_special_tile()
765 {
766   for(SpecialTiles::iterator i = special_tiles.begin();
767       i != special_tiles.end(); ++i) {
768     SpecialTile* special_tile = *i;
769     if (special_tile->pos == tux->get_tile_pos())
770       return special_tile;
771   }
772
773   return NULL;
774 }
775
776 SpriteChange*
777 WorldMap::at_sprite_change(const Vector& pos)
778 {
779   for(SpriteChanges::iterator i = sprite_changes.begin();
780       i != sprite_changes.end(); ++i) {
781     SpriteChange* sprite_change = *i;
782     if(sprite_change->pos == pos)
783       return sprite_change;
784   }
785
786   return NULL;
787 }
788
789 Teleporter*
790 WorldMap::at_teleporter(const Vector& pos)
791 {
792   for(std::vector<Teleporter*>::iterator i = teleporters.begin(); i != teleporters.end(); ++i) {
793     Teleporter* teleporter = *i;
794     if(teleporter->pos == pos) return teleporter;
795   }
796
797   return NULL;
798 }
799
800 void
801 WorldMap::draw(DrawingContext& context)
802 {
803   if (int(get_width()*32) < SCREEN_WIDTH || int(get_height()*32) < SCREEN_HEIGHT)
804     context.draw_filled_rect(Vector(0, 0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
805       Color(0.0f, 0.0f, 0.0f, 1.0f), LAYER_BACKGROUND0);
806
807   context.set_ambient_color( ambient_light );
808   context.push_transform();
809   context.set_translation(camera_offset);
810
811   for(GameObjects::iterator i = game_objects.begin();
812       i != game_objects.end(); ++i) {
813     GameObject* object = *i;
814     if(!panning || object != tux) {
815       object->draw(context);
816     }
817   }
818
819 /*
820   // FIXME: make this a runtime switch similar to draw_collrects/show_collrects?
821   // draw visual indication of possible walk directions
822   static int flipme = 0; 
823   if (flipme++ & 0x04)
824   for (int x = 0; x < get_width(); x++) {
825     for (int y = 0; y < get_height(); y++) {
826       int data = tile_data_at(Vector(x,y));
827       int px = x * 32;
828       int py = y * 32;
829       const int W = 4;
830       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);
831       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);
832       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);
833       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);
834       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);
835       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);
836     }
837   }
838 */
839
840   draw_status(context);
841   context.pop_transform();
842 }
843
844 void
845 WorldMap::draw_status(DrawingContext& context)
846 {
847   context.push_transform();
848   context.set_translation(Vector(0, 0));
849
850   player_status->draw(context);
851
852   if (!tux->is_moving()) {
853     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
854       LevelTile* level = *i;
855
856       if (level->pos == tux->get_tile_pos()) {
857         if(level->title == "")
858           get_level_title(*level);
859
860         context.draw_text(normal_font, level->title,
861                           Vector(SCREEN_WIDTH/2,
862                                  SCREEN_HEIGHT - normal_font->get_height() - 30),
863                           ALIGN_CENTER, LAYER_FOREGROUND1, WorldMap::level_title_color);
864
865         // if level is solved, draw level picture behind stats
866         /*
867         if (level->solved) {
868           if (const Surface* picture = level->get_picture()) {
869             Vector pos = Vector(SCREEN_WIDTH - picture->get_width(), SCREEN_HEIGHT - picture->get_height());
870             context.push_transform();
871             context.set_alpha(0.5);
872             context.draw_surface(picture, pos, LAYER_FOREGROUND1-1);
873             context.pop_transform();
874           }
875         }
876         */
877
878         level->statistics.draw_worldmap_info(context);
879         break;
880       }
881     }
882
883     for(SpecialTiles::iterator i = special_tiles.begin();
884         i != special_tiles.end(); ++i) {
885       SpecialTile* special_tile = *i;
886
887       if (special_tile->pos == tux->get_tile_pos()) {
888         /* Display an in-map message in the map, if any as been selected */
889         if(!special_tile->map_message.empty() && !special_tile->passive_message)
890           context.draw_text(normal_font, special_tile->map_message,
891               Vector(SCREEN_WIDTH/2,
892                 SCREEN_HEIGHT - normal_font->get_height() - 60),
893               ALIGN_CENTER, LAYER_FOREGROUND1, WorldMap::message_color);
894         break;
895       }
896     }
897
898     // display teleporter messages
899     Teleporter* teleporter = at_teleporter(tux->get_tile_pos());
900     if (teleporter && (teleporter->message != "")) {
901       Vector pos = Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - normal_font->get_height() - 30);
902       context.draw_text(normal_font, teleporter->message, pos, ALIGN_CENTER, LAYER_FOREGROUND1, WorldMap::teleporter_message_color);
903     }
904
905   }
906
907   /* Display a passive message in the map, if needed */
908   if(passive_message_timer.started())
909     context.draw_text(normal_font, passive_message,
910             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - normal_font->get_height() - 60),
911             ALIGN_CENTER, LAYER_FOREGROUND1, WorldMap::message_color);
912
913   context.pop_transform();
914 }
915
916 void
917 WorldMap::setup()
918 {
919   sound_manager->play_music(music);
920   Menu::set_current(NULL);
921
922   current_ = this;
923   load_state();
924
925   // if force_spawnpoint was set, move Tux there, then clear force_spawnpoint
926   if (force_spawnpoint != "") {
927     move_to_spawnpoint(force_spawnpoint);
928     force_spawnpoint = "";
929   }
930
931   tux->setup();
932
933   // register worldmap_table as worldmap in scripting
934   using namespace Scripting;
935
936   sq_pushroottable(global_vm);
937   sq_pushstring(global_vm, "worldmap", -1);
938   sq_pushobject(global_vm, worldmap_table);
939   if(SQ_FAILED(sq_createslot(global_vm, -3)))
940     throw SquirrelError(global_vm, "Couldn't set worldmap in roottable");
941   sq_pop(global_vm, 1);
942
943   //Run default.nut just before init script
944   try {
945     IFileStream in(levels_path + "/default.nut");
946     run_script(in, "WorldMap::default.nut");
947   } catch(std::exception& ) {
948     // doesn't exist or erroneous; do nothing
949   }
950
951
952   if(init_script != "") {
953     std::istringstream in(init_script);
954     run_script(in, "WorldMap::init");
955   }
956 }
957
958 void
959 WorldMap::leave()
960 {
961   using namespace Scripting;
962
963   // save state of world and player
964   save_state();
965
966   // remove worldmap_table from roottable
967   sq_pushroottable(global_vm);
968   sq_pushstring(global_vm, "worldmap", -1);
969   if(SQ_FAILED(sq_deleteslot(global_vm, -2, SQFalse)))
970     throw SquirrelError(global_vm, "Couldn't unset worldmap in roottable");
971   sq_pop(global_vm, 1);
972 }
973
974 void
975 WorldMap::save_state()
976 {
977   using namespace Scripting;
978
979   HSQUIRRELVM vm = global_vm;
980   int oldtop = sq_gettop(vm);
981
982   try {
983     // get state table
984     sq_pushroottable(vm);
985     sq_pushstring(vm, "state", -1);
986     if(SQ_FAILED(sq_get(vm, -2)))
987       throw Scripting::SquirrelError(vm, "Couldn't get state table");
988
989     // get or create worlds table
990     sq_pushstring(vm, "worlds", -1);
991     if(SQ_FAILED(sq_get(vm, -2))) {
992       sq_pushstring(vm, "worlds", -1);
993       sq_newtable(vm);
994       if(SQ_FAILED(sq_createslot(vm, -3)))
995         throw Scripting::SquirrelError(vm, "Couldn't create state.worlds");
996
997       sq_pushstring(vm, "worlds", -1);
998       if(SQ_FAILED(sq_get(vm, -2)))
999         throw Scripting::SquirrelError(vm, "Couldn't create.get state.worlds");
1000     }
1001
1002     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
1003     if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
1004       sq_pop(vm, 1);
1005
1006     // construct new table for this worldmap
1007     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
1008     sq_newtable(vm);
1009
1010     // store tux
1011     sq_pushstring(vm, "tux", -1);
1012     sq_newtable(vm);
1013
1014     store_float(vm, "x", tux->get_tile_pos().x);
1015     store_float(vm, "y", tux->get_tile_pos().y);
1016     store_string(vm, "back", direction_to_string(tux->back_direction));
1017
1018     sq_createslot(vm, -3);
1019
1020     // levels...
1021     sq_pushstring(vm, "levels", -1);
1022     sq_newtable(vm);
1023
1024     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
1025       LevelTile* level = *i;
1026
1027       sq_pushstring(vm, level->get_name().c_str(), -1);
1028       sq_newtable(vm);
1029
1030         store_bool(vm, "solved", level->solved);
1031       level->statistics.serialize_to_squirrel(vm);
1032
1033       sq_createslot(vm, -3);
1034     }
1035
1036     sq_createslot(vm, -3);
1037
1038     // overall statistics...
1039     total_stats.serialize_to_squirrel(vm);
1040
1041     // push world into worlds table
1042     sq_createslot(vm, -3);
1043   } catch(std::exception& ) {
1044     sq_settop(vm, oldtop);
1045   }
1046
1047   sq_settop(vm, oldtop);
1048
1049   if(World::current() != NULL)
1050     World::current()->save_state();
1051 }
1052
1053 void
1054 WorldMap::load_state()
1055 {
1056   using namespace Scripting;
1057
1058   HSQUIRRELVM vm = global_vm;
1059   int oldtop = sq_gettop(vm);
1060
1061   try {
1062     // get state table
1063     sq_pushroottable(vm);
1064     sq_pushstring(vm, "state", -1);
1065     if(SQ_FAILED(sq_get(vm, -2)))
1066       throw Scripting::SquirrelError(vm, "Couldn't get state table");
1067
1068     // get worlds table
1069     sq_pushstring(vm, "worlds", -1);
1070     if(SQ_FAILED(sq_get(vm, -2)))
1071       throw Scripting::SquirrelError(vm, "Couldn't get state.worlds");
1072
1073     // get table for our world
1074     sq_pushstring(vm, map_filename.c_str(), map_filename.length());
1075     if(SQ_FAILED(sq_get(vm, -2)))
1076       throw Scripting::SquirrelError(vm, "Couldn't get state.worlds.mapfilename");
1077
1078     // load tux
1079     sq_pushstring(vm, "tux", -1);
1080     if(SQ_FAILED(sq_get(vm, -2)))
1081       throw Scripting::SquirrelError(vm, "Couldn't get tux");
1082
1083     Vector p;
1084     p.x = read_float(vm, "x");
1085     p.y = read_float(vm, "y");
1086     std::string back_str = read_string(vm, "back");
1087     tux->back_direction = string_to_direction(back_str);
1088     tux->set_tile_pos(p);
1089
1090     sq_pop(vm, 1);
1091
1092     // load levels
1093     sq_pushstring(vm, "levels", -1);
1094     if(SQ_FAILED(sq_get(vm, -2)))
1095       throw Scripting::SquirrelError(vm, "Couldn't get levels");
1096
1097     for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
1098       LevelTile* level = *i;
1099       sq_pushstring(vm, level->get_name().c_str(), -1);
1100       if(SQ_SUCCEEDED(sq_get(vm, -2))) {
1101         level->solved = read_bool(vm, "solved");
1102         level->sprite->set_action(level->solved ? "solved" : "default");
1103         level->statistics.unserialize_from_squirrel(vm);
1104         sq_pop(vm, 1);
1105       }
1106     }
1107
1108     // leave state table
1109     sq_pop(vm, 1);
1110
1111     // load overall statistics
1112     total_stats.unserialize_from_squirrel(vm);
1113
1114   } catch(std::exception& e) {
1115     log_debug << "Not loading worldmap state: " << e.what() << std::endl;
1116   }
1117   sq_settop(vm, oldtop);
1118
1119   in_level = false;
1120 }
1121
1122 size_t
1123 WorldMap::level_count()
1124 {
1125   return levels.size();
1126 }
1127
1128 size_t
1129 WorldMap::solved_level_count()
1130 {
1131   size_t count = 0;
1132   for(LevelTiles::iterator i = levels.begin(); i != levels.end(); ++i) {
1133     LevelTile* level = *i;
1134
1135     if(level->solved)
1136       count++;
1137   }
1138
1139   return count;
1140 }
1141
1142 HSQUIRRELVM
1143 WorldMap::run_script(std::istream& in, const std::string& sourcename)
1144 {
1145   using namespace Scripting;
1146
1147   // garbage collect thread list
1148   for(ScriptList::iterator i = scripts.begin();
1149       i != scripts.end(); ) {
1150     HSQOBJECT& object = *i;
1151     HSQUIRRELVM vm = object_to_vm(object);
1152
1153     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
1154       sq_release(global_vm, &object);
1155       i = scripts.erase(i);
1156       continue;
1157     }
1158
1159     ++i;
1160   }
1161
1162   HSQOBJECT object = create_thread(global_vm);
1163   scripts.push_back(object);
1164
1165   HSQUIRRELVM vm = object_to_vm(object);
1166
1167   // set worldmap_table as roottable for the thread
1168   sq_pushobject(vm, worldmap_table);
1169   sq_setroottable(vm);
1170
1171   compile_and_run(vm, in, sourcename);
1172
1173   return vm;
1174 }
1175
1176 float
1177 WorldMap::get_width() const
1178 {
1179   float width = 0;
1180   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1181     TileMap* solids = *i;
1182     if (solids->get_width() > width) width = solids->get_width();
1183   }
1184   return width;
1185 }
1186
1187 float
1188 WorldMap::get_height() const
1189 {
1190   float height = 0;
1191   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1192     TileMap* solids = *i;
1193     if (solids->get_height() > height) height = solids->get_height();
1194   }
1195   return height;
1196 }
1197
1198 } // namespace WorldMapNS