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