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