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