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