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