872c2859a4c4092701d8173e1c6e6dfa35eba5a8
[supertux.git] / src / worldmap.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <iostream>
22 #include <fstream>
23 #include <vector>
24 #include <cassert>
25 #include <stdexcept>
26 #include <sstream>
27 #include <unistd.h>
28
29 #include "gettext.h"
30 #include "video/surface.h"
31 #include "video/screen.h"
32 #include "video/drawing_context.h"
33 #include "sprite/sprite_manager.h"
34 #include "audio/sound_manager.h"
35 #include "lisp/parser.h"
36 #include "lisp/lisp.h"
37 #include "lisp/list_iterator.h"
38 #include "lisp/writer.h"
39 #include "game_session.h"
40 #include "sector.h"
41 #include "worldmap.h"
42 #include "resources.h"
43 #include "misc.h"
44 #include "player_status.h"
45 #include "textscroller.h"
46 #include "main.h"
47 #include "spawn_point.h"
48 #include "file_system.h"
49 #include "gui/menu.h"
50 #include "gui/mousecursor.h"
51 #include "control/joystickkeyboardcontroller.h"
52 #include "object/background.h"
53 #include "object/tilemap.h"
54 #include "scripting/script_interpreter.h"
55
56 Menu* worldmap_menu  = 0;
57
58 static const float TUXSPEED = 200;
59 static const float map_message_TIME = 2.8;
60
61 namespace WorldMapNS {
62
63 Direction reverse_dir(Direction direction)
64 {
65   switch(direction)
66     {
67     case D_WEST:
68       return D_EAST;
69     case D_EAST:
70       return D_WEST;
71     case D_NORTH:
72       return D_SOUTH;
73     case D_SOUTH:
74       return D_NORTH;
75     case D_NONE:
76       return D_NONE;
77     }
78   return D_NONE;
79 }
80
81 std::string
82 direction_to_string(Direction direction)
83 {
84   switch(direction)
85     {
86     case D_WEST:
87       return "west";
88     case D_EAST:
89       return "east";
90     case D_NORTH:
91       return "north";
92     case D_SOUTH:
93       return "south";
94     default:
95       return "none";
96     }
97 }
98
99 Direction
100 string_to_direction(const std::string& directory)
101 {
102   if (directory == "west")
103     return D_WEST;
104   else if (directory == "east")
105     return D_EAST;
106   else if (directory == "north")
107     return D_NORTH;
108   else if (directory == "south")
109     return D_SOUTH;
110   else
111     return D_NONE;
112 }
113
114 //---------------------------------------------------------------------------
115
116 Tux::Tux(WorldMap* worldmap_)
117   : worldmap(worldmap_)
118 {
119   tux_sprite = sprite_manager->create("worldmaptux");
120   
121   offset = 0;
122   moving = false;
123   direction = D_NONE;
124   input_direction = D_NONE;
125 }
126
127 Tux::~Tux()
128 {
129   delete tux_sprite;
130 }
131
132 void
133 Tux::draw(DrawingContext& context)
134 {
135   switch (player_status.bonus) {
136     case GROWUP_BONUS:
137       tux_sprite->set_action("large");
138       break;
139     case FIRE_BONUS:
140       tux_sprite->set_action("fire");
141       break;
142     case NO_BONUS:
143       tux_sprite->set_action("small");
144       break;
145     default:
146 #ifdef DBEUG
147       std::cerr << "Bonus type not handled in worldmap.\n";
148 #endif
149       tux_sprite->set_action("large");
150       break;
151   }
152
153   tux_sprite->draw(context, get_pos(), LAYER_OBJECTS);
154 }
155
156
157 Vector
158 Tux::get_pos()
159 {
160   float x = tile_pos.x * 32;
161   float y = tile_pos.y * 32;
162
163   switch(direction)
164     {
165     case D_WEST:
166       x -= offset - 32;
167       break;
168     case D_EAST:
169       x += offset - 32;
170       break;
171     case D_NORTH:
172       y -= offset - 32;
173       break;
174     case D_SOUTH:
175       y += offset - 32;
176       break;
177     case D_NONE:
178       break;
179     }
180   
181   return Vector(x, y);
182 }
183
184 void
185 Tux::stop()
186 {
187   offset = 0;
188   direction = D_NONE;
189   input_direction = D_NONE;
190   moving = false;
191 }
192
193 void
194 Tux::set_direction(Direction dir)
195 {
196   input_direction = dir;
197 }
198
199 void
200 Tux::update(float delta)
201 {
202   // check controller
203   if(main_controller->pressed(Controller::UP))
204     input_direction = D_NORTH;
205   else if(main_controller->pressed(Controller::DOWN))
206     input_direction = D_SOUTH;
207   else if(main_controller->pressed(Controller::LEFT))
208     input_direction = D_WEST;
209   else if(main_controller->pressed(Controller::RIGHT))
210     input_direction = D_EAST;
211
212   if(!moving)
213     {
214       if (input_direction != D_NONE)
215         { 
216           WorldMap::Level* level = worldmap->at_level();
217
218           // We got a new direction, so lets start walking when possible
219           Vector next_tile;
220           if ((!level || level->solved)
221               && worldmap->path_ok(input_direction, tile_pos, &next_tile))
222             {
223               tile_pos = next_tile;
224               moving = true;
225               direction = input_direction;
226               back_direction = reverse_dir(direction);
227             }
228           else if (input_direction == back_direction)
229             {
230               moving = true;
231               direction = input_direction;
232               tile_pos = worldmap->get_next_tile(tile_pos, direction);
233               back_direction = reverse_dir(direction);
234             }
235         }
236     }
237   else
238     {
239       // Let tux walk
240       offset += TUXSPEED * delta;
241
242       if (offset > 32)
243         { // We reached the next tile, so we check what to do now
244           offset -= 32;
245
246           WorldMap::SpecialTile* special_tile = worldmap->at_special_tile();
247           if(special_tile && special_tile->passive_message)
248             {  // direction and the apply_action_ are opposites, since they "see"
249                // directions in a different way
250             if((direction == D_NORTH && special_tile->apply_action_south) ||
251                (direction == D_SOUTH && special_tile->apply_action_north) ||
252                (direction == D_WEST && special_tile->apply_action_east) ||
253                (direction == D_EAST && special_tile->apply_action_west))
254               {
255               worldmap->passive_message = special_tile->map_message;
256               worldmap->passive_message_timer.start(map_message_TIME);
257               }
258             }
259
260           if (worldmap->at(tile_pos)->getData() & Tile::WORLDMAP_STOP ||
261              (special_tile && !special_tile->passive_message) ||
262               worldmap->at_level())
263             {
264               if(special_tile && !special_tile->map_message.empty() &&
265                 !special_tile->passive_message)
266                 worldmap->passive_message_timer.start(0);
267               stop();
268             }
269           else
270             {
271               const Tile* tile = worldmap->at(tile_pos);
272               if (direction != input_direction)
273                 { 
274                   // Turn to a new direction
275                   const Tile* tile = worldmap->at(tile_pos);
276
277                   if((tile->getData() & Tile::WORLDMAP_NORTH 
278                       && input_direction == D_NORTH) ||
279                      (tile->getData() & Tile::WORLDMAP_SOUTH
280                       && input_direction == D_SOUTH) ||
281                      (tile->getData() & Tile::WORLDMAP_EAST
282                       && input_direction == D_EAST) ||
283                      (tile->getData() & Tile::WORLDMAP_WEST
284                       && input_direction == D_WEST))
285                     {  // player has changed direction during auto-movement
286                       direction = input_direction;
287                       back_direction = reverse_dir(direction);
288                     }
289                   else
290                     {  // player has changed to impossible tile
291                       back_direction = reverse_dir(direction);
292                       stop();
293                     }
294                 }
295               else
296                 {
297                 Direction dir = D_NONE;
298               
299                 if (tile->getData() & Tile::WORLDMAP_NORTH
300                     && back_direction != D_NORTH)
301                   dir = D_NORTH;
302                 else if (tile->getData() & Tile::WORLDMAP_SOUTH
303                     && back_direction != D_SOUTH)
304                   dir = D_SOUTH;
305                 else if (tile->getData() & Tile::WORLDMAP_EAST
306                     && back_direction != D_EAST)
307                   dir = D_EAST;
308                 else if (tile->getData() & Tile::WORLDMAP_WEST
309                     && back_direction != D_WEST)
310                   dir = D_WEST;
311
312                 if (dir != D_NONE)
313                   {
314                   direction = dir;
315                   input_direction = direction;
316                   back_direction = reverse_dir(direction);
317                   }
318                 else
319                   {
320                   // Should never be reached if tiledata is good
321                   stop();
322                   return;
323                   }
324                 }
325
326               // Walk automatically to the next tile
327               if(direction != D_NONE)
328                 {
329                 Vector next_tile;
330                 if (worldmap->path_ok(direction, tile_pos, &next_tile))
331                   {
332                   tile_pos = next_tile;
333                   }
334                 else
335                   {
336                   puts("Tilemap data is buggy");
337                   stop();
338                   }
339                 }
340             }
341         }
342     }
343 }
344
345 //---------------------------------------------------------------------------
346
347 WorldMap::WorldMap()
348   : tux(0), solids(0)
349 {
350   tile_manager = new TileManager("images/worldmap.strf");
351   
352   tux = new Tux(this);
353   add_object(tux);
354     
355   leveldot_green
356     = new Surface(datadir + "/images/tiles/worldmap/leveldot_green.png", true);
357   leveldot_red
358     = new Surface(datadir + "/images/tiles/worldmap/leveldot_red.png", true);
359   messagedot
360     = new Surface(datadir + "/images/tiles/worldmap/messagedot.png", true);
361   teleporterdot
362     = new Surface(datadir + "/images/tiles/worldmap/teleporterdot.png", true);
363
364   name = "<no title>";
365   music = "salcon.mod";
366   intro_displayed = false;
367
368   total_stats.reset();
369 }
370
371 WorldMap::~WorldMap()
372 {
373   clear_objects();
374   for(SpawnPoints::iterator i = spawn_points.begin();
375       i != spawn_points.end(); ++i) {
376     delete *i;
377   }
378     
379   delete tile_manager;
380
381   delete leveldot_green;
382   delete leveldot_red;
383   delete messagedot;
384   delete teleporterdot;
385 }
386
387 void
388 WorldMap::add_object(GameObject* object)
389 {
390   TileMap* tilemap = dynamic_cast<TileMap*> (object);
391   if(tilemap != 0 && tilemap->is_solid()) {
392     solids = tilemap;
393   }
394
395   game_objects.push_back(object);
396 }
397
398 void
399 WorldMap::clear_objects()
400 {
401   for(GameObjects::iterator i = game_objects.begin();
402       i != game_objects.end(); ++i)
403     delete *i;
404   game_objects.clear();
405   solids = 0;
406   tux = new Tux(this);
407   add_object(tux);
408 }
409
410 // Don't forget to set map_filename before calling this
411 void
412 WorldMap::load_map()
413 {
414   levels_path = FileSystem::dirname(map_filename);
415
416   try {
417     lisp::Parser parser;
418     std::string filename = get_resource_filename(map_filename);
419     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
420
421     const lisp::Lisp* lisp = root->get_lisp("supertux-worldmap");
422     if(!lisp)
423       throw new std::runtime_error("file isn't a supertux-worldmap file.");
424
425     clear_objects();
426     lisp::ListIterator iter(lisp);
427     while(iter.next()) {
428       if(iter.item() == "tilemap") {
429         add_object(new TileMap(*(iter.lisp()), tile_manager));
430       } else if(iter.item() == "background") {
431         add_object(new Background(*(iter.lisp())));
432       } else if(iter.item() == "properties") {
433         const lisp::Lisp* props = iter.lisp();
434         props->get("name", name);
435         props->get("music", music);
436       } else if(iter.item() == "intro-script") {
437         iter.value()->get(intro_script);
438       } else if(iter.item() == "spawnpoint") {
439         SpawnPoint* sp = new SpawnPoint(iter.lisp());
440         spawn_points.push_back(sp);
441       } else if(iter.item() == "level") {
442         parse_level_tile(iter.lisp());
443       } else if(iter.item() == "special-tile") {
444         parse_special_tile(iter.lisp());
445       } else {
446         std::cerr << "Unknown token '" << iter.item() << "' in worldmap.\n";
447       }
448     }
449     if(solids == 0)
450       throw std::runtime_error("No solid tilemap specified");
451
452     // search for main spawnpoint
453     for(SpawnPoints::iterator i = spawn_points.begin();
454         i != spawn_points.end(); ++i) {
455       SpawnPoint* sp = *i;
456       if(sp->name == "main") {
457         Vector p = sp->pos;
458         tux->set_tile_pos(p);
459         break;
460       }
461     }
462
463   } catch(std::exception& e) {
464     std::stringstream msg;
465     msg << "Problem when parsing worldmap '" << map_filename << "': " <<
466       e.what();
467     throw std::runtime_error(msg.str());
468   }
469 }
470
471 void
472 WorldMap::parse_special_tile(const lisp::Lisp* lisp)
473 {
474   SpecialTile special_tile;
475   
476   lisp->get("x", special_tile.pos.x);
477   lisp->get("y", special_tile.pos.y);
478   lisp->get("map-message", special_tile.map_message);
479   special_tile.passive_message = false;
480   lisp->get("passive-message", special_tile.passive_message);
481   special_tile.teleport_dest = Vector(-1,-1);
482   lisp->get("teleport-to-x", special_tile.teleport_dest.x);
483   lisp->get("teleport-to-y", special_tile.teleport_dest.y);
484   special_tile.invisible = false;
485   lisp->get("invisible-tile", special_tile.invisible);
486
487   special_tile.apply_action_north = true;
488   special_tile.apply_action_south = true;
489   special_tile.apply_action_east = true;
490   special_tile.apply_action_west = true;
491
492   std::string apply_direction;
493   lisp->get("apply-to-direction", apply_direction);
494   if(!apply_direction.empty()) {
495     special_tile.apply_action_north = false;
496     special_tile.apply_action_south = false;
497     special_tile.apply_action_east = false;
498     special_tile.apply_action_west = false;
499     if(apply_direction.find("north") != std::string::npos)
500       special_tile.apply_action_north = true;
501     if(apply_direction.find("south") != std::string::npos)
502       special_tile.apply_action_south = true;
503     if(apply_direction.find("east") != std::string::npos)
504       special_tile.apply_action_east = true;
505     if(apply_direction.find("west") != std::string::npos)
506       special_tile.apply_action_west = true;
507   }
508   
509   special_tiles.push_back(special_tile);
510 }
511
512 void
513 WorldMap::parse_level_tile(const lisp::Lisp* level_lisp)
514 {
515   Level level;
516
517   level.solved = false;
518                   
519   level.north = true;
520   level.east  = true;
521   level.south = true;
522   level.west  = true;
523
524   level_lisp->get("extro-script", level.extro_script);
525   level_lisp->get("next-worldmap", level.next_worldmap);
526
527   level.quit_worldmap = false;
528   level_lisp->get("quit-worldmap", level.quit_worldmap);
529
530   level_lisp->get("name", level.name);
531   level_lisp->get("x", level.pos.x);
532   level_lisp->get("y", level.pos.y);
533
534   level.auto_path = true;
535   level_lisp->get("auto-path", level.auto_path);
536
537   level.vertical_flip = false;
538   level_lisp->get("vertical-flip", level.vertical_flip);
539
540   levels.push_back(level);
541 }
542
543 void
544 WorldMap::get_level_title(Level& level)
545 {
546   /** get special_tile's title */
547   level.title = "<no title>";
548
549   try {
550     lisp::Parser parser;
551     std::auto_ptr<lisp::Lisp> root (
552         parser.parse(get_resource_filename(levels_path + level.name)));
553
554     const lisp::Lisp* level_lisp = root->get_lisp("supertux-level");
555     if(!level_lisp)
556       return;
557     
558     level_lisp->get("name", level.title);
559   } catch(std::exception& e) {
560     std::cerr << "Problem when reading leveltitle: " << e.what() << "\n";
561     return;
562   }
563 }
564
565 void WorldMap::calculate_total_stats()
566 {
567   total_stats.reset();
568   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
569     {
570     if (i->solved)
571       {
572       total_stats += i->statistics;
573       }
574     }
575 }
576
577 void
578 WorldMap::on_escape_press()
579 {
580   // Show or hide the menu
581   if(!Menu::current()) {
582     Menu::set_current(worldmap_menu);
583     tux->set_direction(D_NONE);  // stop tux movement when menu is called
584   } else {
585     Menu::set_current(0);
586   }
587 }
588
589 void
590 WorldMap::get_input()
591 {
592   main_controller->update();
593
594   SDL_Event event;
595   while (SDL_PollEvent(&event)) {
596     if (Menu::current())
597       Menu::current()->event(event);
598     main_controller->process_event(event);
599     if(event.type == SDL_QUIT)
600       throw std::runtime_error("Received window close");
601   }
602 }
603
604 Vector
605 WorldMap::get_next_tile(Vector pos, Direction direction)
606 {
607   switch(direction) {
608     case D_WEST:
609       pos.x -= 1;
610       break;
611     case D_EAST:
612       pos.x += 1;
613       break;
614     case D_NORTH:
615       pos.y -= 1;
616       break;
617     case D_SOUTH:
618       pos.y += 1;
619       break;
620     case D_NONE:
621       break;
622   }
623   return pos;
624 }
625
626 bool
627 WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
628 {
629   *new_pos = get_next_tile(old_pos, direction);
630
631   if (!(new_pos->x >= 0 && new_pos->x < solids->get_width()
632         && new_pos->y >= 0 && new_pos->y < solids->get_height()))
633     { // New position is outsite the tilemap
634       return false;
635     }
636   else
637     { // Check if the tile allows us to go to new_pos
638       switch(direction)
639         {
640         case D_WEST:
641           return (at(old_pos)->getData() & Tile::WORLDMAP_WEST
642               && at(*new_pos)->getData() & Tile::WORLDMAP_EAST);
643
644         case D_EAST:
645           return (at(old_pos)->getData() & Tile::WORLDMAP_EAST
646               && at(*new_pos)->getData() & Tile::WORLDMAP_WEST);
647
648         case D_NORTH:
649           return (at(old_pos)->getData() & Tile::WORLDMAP_NORTH
650               && at(*new_pos)->getData() & Tile::WORLDMAP_SOUTH);
651
652         case D_SOUTH:
653           return (at(old_pos)->getData() & Tile::WORLDMAP_SOUTH
654               && at(*new_pos)->getData() & Tile::WORLDMAP_NORTH);
655
656         case D_NONE:
657           assert(!"path_ok() can't work if direction is NONE");
658         }
659       return false;
660     }
661 }
662
663 void
664 WorldMap::update(float delta)
665 {
666   Menu* menu = Menu::current();
667   if(menu) {
668     menu->update();
669
670     if(menu == worldmap_menu) {
671       switch (worldmap_menu->check())
672       {
673         case MNID_RETURNWORLDMAP: // Return to game  
674           Menu::set_current(0);
675           break;
676         case MNID_QUITWORLDMAP: // Quit Worldmap
677           quit = true;                               
678           break;
679       }
680     } else if(menu == options_menu) {
681       process_options_menu();
682     }
683
684     return;
685   }
686
687   // update GameObjects
688   for(GameObjects::iterator i = game_objects.begin();
689       i != game_objects.end(); ++i) {
690     GameObject* object = *i;
691     object->update(delta);
692   }
693   // remove old GameObjects
694   for(GameObjects::iterator i = game_objects.begin();
695       i != game_objects.end(); ) {
696     GameObject* object = *i;
697     if(!object->is_valid()) {
698       delete object;
699       i = game_objects.erase(i);
700     } else {
701       ++i;
702     }
703   }
704   
705   bool enter_level = false;
706   if(main_controller->pressed(Controller::ACTION)
707       || main_controller->pressed(Controller::JUMP)
708       || main_controller->pressed(Controller::MENU_SELECT))
709     enter_level = true;
710   if(main_controller->pressed(Controller::PAUSE_MENU))
711     on_escape_press();
712   
713   if (enter_level && !tux->is_moving())
714     {
715       /* Check special tile action */
716       SpecialTile* special_tile = at_special_tile();
717       if(special_tile)
718         {
719         if (special_tile->teleport_dest != Vector(-1,-1))
720           {
721           // TODO: an animation, camera scrolling or a fading would be a nice touch
722           sound_manager->play_sound("warp");
723           tux->back_direction = D_NONE;
724           tux->set_tile_pos(special_tile->teleport_dest);
725           SDL_Delay(1000);
726           }
727         }
728
729       /* Check level action */
730       bool level_finished = true;
731       Level* level = at_level();
732       if (!level)
733         {
734         std::cout << "No level to enter at: "
735           << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y
736           << std::endl;
737         return;
738         }
739
740
741       if (level->pos == tux->get_tile_pos())
742         {
743           PlayerStatus old_player_status = player_status;
744
745           // do a shriking fade to the level
746           shrink_fade(Vector((level->pos.x*32 + 16 + offset.x),
747                              (level->pos.y*32 + 16 + offset.y)), 500);
748           GameSession session(get_resource_filename(levels_path + level->name),
749                               ST_GL_LOAD_LEVEL_FILE, &level->statistics);
750
751           switch (session.run())
752             {
753             case GameSession::ES_LEVEL_FINISHED:
754               {
755                 level_finished = true;
756                 bool old_level_state = level->solved;
757                 level->solved = true;
758
759                 // deal with statistics
760                 level->statistics.merge(global_stats);
761                 calculate_total_stats();
762
763                 if (old_level_state != level->solved && level->auto_path)
764                   { // Try to detect the next direction to which we should walk
765                     // FIXME: Mostly a hack
766                     Direction dir = D_NONE;
767                 
768                     const Tile* tile = at(tux->get_tile_pos());
769
770                     if (tile->getData() & Tile::WORLDMAP_NORTH
771                         && tux->back_direction != D_NORTH)
772                       dir = D_NORTH;
773                     else if (tile->getData() & Tile::WORLDMAP_SOUTH
774                         && tux->back_direction != D_SOUTH)
775                       dir = D_SOUTH;
776                     else if (tile->getData() & Tile::WORLDMAP_EAST
777                         && tux->back_direction != D_EAST)
778                       dir = D_EAST;
779                     else if (tile->getData() & Tile::WORLDMAP_WEST
780                         && tux->back_direction != D_WEST)
781                       dir = D_WEST;
782
783                     if (dir != D_NONE)
784                       {
785                         tux->set_direction(dir);
786                       }
787                   }
788               }
789
790               break;
791             case GameSession::ES_LEVEL_ABORT:
792               level_finished = false;
793               /* In case the player's abort the level, keep it using the old
794                   status. But the minimum lives and no bonus. */
795               player_status.coins = old_player_status.coins;
796               player_status.lives = std::min(old_player_status.lives, player_status.lives);
797               player_status.bonus = NO_BONUS;
798
799               break;
800             case GameSession::ES_GAME_OVER:
801               {
802               level_finished = false;
803               /* draw an end screen */
804               /* TODO: in the future, this should make a dialog a la SuperMario, asking
805               if the player wants to restart the world map with no score and from
806               level 1 */
807               char str[80];
808
809               DrawingContext context;
810               context.draw_gradient(Color (200,240,220), Color(200,200,220),
811                   LAYER_BACKGROUND0);
812
813               context.draw_text(blue_text, _("GAMEOVER"), 
814                   Vector(SCREEN_WIDTH/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
815
816               sprintf(str, _("COINS: %d"), player_status.coins);
817               context.draw_text(gold_text, str,
818                   Vector(SCREEN_WIDTH/2, SCREEN_WIDTH - 32), CENTER_ALLIGN,
819                   LAYER_FOREGROUND1);
820
821               total_stats.draw_message_info(context, _("Total Statistics"));
822
823               context.do_drawing();
824
825               wait_for_event(2.0, 6.0);
826
827               quit = true;
828               player_status.reset();
829               break;
830               }
831             case GameSession::ES_NONE:
832               assert(false);
833               // Should never be reached 
834               break;
835             }
836
837           sound_manager->play_music(song);
838           Menu::set_current(0);
839           if (!savegame_file.empty())
840             savegame(savegame_file);
841         }
842       /* The porpose of the next checking is that if the player lost
843          the level (in case there is one), don't show anything */
844       if(level_finished) {
845         if (level->extro_script != "") {
846           ScriptInterpreter* interpreter = new ScriptInterpreter(levels_path);
847           std::istringstream in(level->extro_script);
848           interpreter->load_script(in, "level-extro-script");
849           interpreter->start_script();
850           add_object(interpreter);
851         }
852
853         if (!level->next_worldmap.empty())
854           {
855           // Load given worldmap
856           loadmap(level->next_worldmap);
857           }
858         if (level->quit_worldmap)
859           quit = true;
860         }
861     }
862   else
863     {
864 //      tux->set_direction(input_direction);
865     }
866 }
867
868 const Tile*
869 WorldMap::at(Vector p)
870 {
871   return solids->get_tile((int) p.x, (int) p.y);
872 }
873
874 WorldMap::Level*
875 WorldMap::at_level()
876 {
877   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
878     {
879       if (i->pos == tux->get_tile_pos())
880         return &*i; 
881     }
882
883   return 0;
884 }
885
886 WorldMap::SpecialTile*
887 WorldMap::at_special_tile()
888 {
889   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
890     {
891       if (i->pos == tux->get_tile_pos())
892         return &*i; 
893     }
894
895   return 0;
896 }
897
898 void
899 WorldMap::draw(DrawingContext& context)
900 {
901   for(GameObjects::iterator i = game_objects.begin();
902       i != game_objects.end(); ++i) {
903     GameObject* object = *i;
904     object->draw(context);
905   }
906   
907   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
908     {
909       if (i->solved)
910         context.draw_surface(leveldot_green,
911             Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
912       else
913         context.draw_surface(leveldot_red,
914             Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
915     }
916
917   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
918     {
919       if(i->invisible)
920         continue;
921
922       if (i->teleport_dest != Vector(-1, -1))
923         context.draw_surface(teleporterdot,
924                 Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
925
926       else if (!i->map_message.empty() && !i->passive_message)
927         context.draw_surface(messagedot,
928                 Vector(i->pos.x*32, i->pos.y*32), LAYER_TILES+1);
929     }
930
931   draw_status(context);
932 }
933
934 void
935 WorldMap::draw_status(DrawingContext& context)
936 {
937   context.push_transform();
938   context.set_translation(Vector(0, 0));
939  
940   player_status.draw(context);
941
942   if (!tux->is_moving())
943     {
944       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
945         {
946           if (i->pos == tux->get_tile_pos())
947             {
948               if(i->title == "")
949                 get_level_title(*i);
950
951               context.draw_text(white_text, i->title, 
952                   Vector(SCREEN_WIDTH/2,
953                          SCREEN_HEIGHT - white_text->get_height() - 30),
954                   CENTER_ALLIGN, LAYER_FOREGROUND1);
955
956               i->statistics.draw_worldmap_info(context);
957               break;
958             }
959         }
960       for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
961         {
962           if (i->pos == tux->get_tile_pos())
963             {
964                /* Display an in-map message in the map, if any as been selected */
965               if(!i->map_message.empty() && !i->passive_message)
966                 context.draw_text(gold_text, i->map_message, 
967                     Vector(SCREEN_WIDTH/2,
968                            SCREEN_HEIGHT - white_text->get_height() - 60),
969                     CENTER_ALLIGN, LAYER_FOREGROUND1);
970               break;
971             }
972         }
973     }
974   /* Display a passive message in the map, if needed */
975   if(passive_message_timer.check())
976     context.draw_text(gold_text, passive_message, 
977             Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT - white_text->get_height() - 60),
978             CENTER_ALLIGN, LAYER_FOREGROUND1);
979
980   context.pop_transform();
981 }
982
983 void
984 WorldMap::display()
985 {
986   Menu::set_current(0);
987
988   quit = false;
989
990   song = sound_manager->load_music(datadir +  "/music/" + music);
991   sound_manager->play_music(song);
992
993   if(!intro_displayed && intro_script != "") {
994     ScriptInterpreter* interpreter = new ScriptInterpreter(levels_path);
995     std::istringstream in(intro_script);
996     interpreter->load_script(in, "worldmap-intro-script");
997     interpreter->start_script();
998     add_object(interpreter);
999                                            
1000     intro_displayed = true;
1001   }
1002
1003   Uint32 lastticks = SDL_GetTicks();
1004   DrawingContext context;
1005   while(!quit) {
1006     Uint32 ticks = SDL_GetTicks();
1007     float elapsed_time = float(ticks - lastticks) / 1000;
1008     global_time += elapsed_time;
1009     lastticks = ticks;
1010     
1011     // 40 fps minimum // TODO use same code as in GameSession here
1012     if(elapsed_time > .025)
1013       elapsed_time = .025;
1014     
1015     Vector tux_pos = tux->get_pos();
1016     offset.x = tux_pos.x - SCREEN_WIDTH/2;
1017     offset.y = tux_pos.y - SCREEN_HEIGHT/2;
1018
1019     if (offset.x < 0)
1020       offset.x = 0;
1021     if (offset.y < 0)
1022       offset.y = 0;
1023
1024     if (offset.x > solids->get_width()*32 - SCREEN_WIDTH)
1025       offset.x = solids->get_width()*32 - SCREEN_WIDTH;
1026     if (offset.y > solids->get_height()*32 - SCREEN_HEIGHT)
1027       offset.y = solids->get_height()*32 - SCREEN_HEIGHT;
1028
1029     context.push_transform();
1030     context.set_translation(offset);
1031     draw(context);
1032     context.pop_transform();
1033     get_input();
1034     update(elapsed_time);
1035       
1036     if(Menu::current()) {
1037       Menu::current()->draw(context);
1038     }
1039
1040     context.do_drawing();
1041   }
1042 }
1043
1044 void
1045 WorldMap::savegame(const std::string& filename)
1046 {
1047   if(filename == "")
1048     return;
1049
1050   std::ofstream file(filename.c_str(), std::ios::out);
1051   lisp::Writer writer(file);
1052
1053   int nb_solved_levels = 0, total_levels = 0;
1054   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i) {
1055     ++total_levels;
1056     if (i->solved)
1057       ++nb_solved_levels;
1058   }
1059   char nb_solved_levels_str[80], total_levels_str[80];
1060   sprintf(nb_solved_levels_str, "%d", nb_solved_levels);
1061   sprintf(total_levels_str, "%d", total_levels);
1062
1063   writer.write_comment("Worldmap save file");
1064
1065   writer.start_list("supertux-savegame");
1066
1067   writer.write_int("version", 1);
1068   writer.write_string("title",
1069       std::string(name + " - " + nb_solved_levels_str+"/"+total_levels_str));
1070   writer.write_string("map", map_filename);
1071   writer.write_bool("intro-displayed", intro_displayed);
1072
1073   writer.start_list("tux");
1074
1075   writer.write_float("x", tux->get_tile_pos().x);
1076   writer.write_float("y", tux->get_tile_pos().y);
1077   writer.write_string("back", direction_to_string(tux->back_direction));
1078   player_status.write(writer);
1079   writer.write_string("back", direction_to_string(tux->back_direction));
1080
1081   writer.end_list("tux");
1082
1083   writer.start_list("levels");
1084
1085   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1086     {
1087       if (i->solved)
1088         {
1089         writer.start_list("level");
1090
1091         writer.write_string("name", i->name);
1092         writer.write_bool("solved", true);
1093         i->statistics.write(writer);
1094
1095         writer.end_list("level");
1096         }
1097     }  
1098
1099   writer.end_list("levels");
1100
1101   writer.end_list("supertux-savegame");
1102 }
1103
1104 void
1105 WorldMap::loadgame(const std::string& filename)
1106 {
1107   std::cout << "loadgame: " << filename << std::endl;
1108   savegame_file = filename;
1109
1110   try {
1111     lisp::Parser parser;
1112     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
1113   
1114     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
1115     if(!savegame)
1116       throw std::runtime_error("File is not a supertux-savegame file.");
1117
1118     /* Get the Map filename and then load it before setting level settings */
1119     std::string cur_map_filename = map_filename;
1120     savegame->get("map", map_filename);
1121     load_map(); 
1122
1123     savegame->get("intro-displayed", intro_displayed);
1124     savegame->get("lives", player_status.lives);
1125     savegame->get("coins", player_status.coins);
1126     savegame->get("max-score-multiplier", player_status.max_score_multiplier);
1127     if (player_status.lives < 0)
1128       player_status.reset();
1129
1130     const lisp::Lisp* tux_lisp = savegame->get_lisp("tux");
1131     if(tux)
1132     {
1133       Vector p;
1134       std::string back_str = "none";
1135
1136       tux_lisp->get("x", p.x);
1137       tux_lisp->get("y", p.y);
1138       tux_lisp->get("back", back_str);
1139       player_status.read(*tux_lisp);
1140       
1141       tux->back_direction = string_to_direction(back_str);      
1142       tux->set_tile_pos(p);
1143     }
1144
1145     const lisp::Lisp* levels_lisp = savegame->get_lisp("levels");
1146     if(levels_lisp) {
1147       lisp::ListIterator iter(levels_lisp);
1148       while(iter.next()) {
1149         if(iter.item() == "level") {
1150           std::string name;
1151           bool solved = false;
1152
1153           const lisp::Lisp* level = iter.lisp();
1154           level->get("name", name);
1155           level->get("solved", solved);
1156
1157           for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1158           {
1159             if (name == i->name)
1160             {
1161               i->solved = solved;
1162               i->statistics.parse(*level);
1163               break;
1164             }
1165           }
1166         } else {
1167           std::cerr << "Unknown token '" << iter.item() 
1168                     << "' in levels block in worldmap.\n";
1169         }
1170       }
1171     }
1172   } catch(std::exception& e) {
1173     std::cerr << "Problem loading game '" << filename << "': " << e.what() 
1174               << "\n";
1175     load_map();
1176     player_status.reset();
1177   }
1178
1179   calculate_total_stats();
1180 }
1181
1182 void
1183 WorldMap::loadmap(const std::string& filename)
1184 {
1185   savegame_file = "";
1186   map_filename = filename;
1187   load_map();
1188 }
1189
1190 } // namespace WorldMapNS