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