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