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