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