Updated code to support new stuff from 0.1.2.
[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
20 #include <iostream>
21 #include <fstream>
22 #include <vector>
23 #include <cassert>
24 #include <unistd.h>
25
26 #include "app/globals.h"
27 #include "video/surface.h"
28 #include "video/screen.h"
29 #include "video/drawing_context.h"
30 #include "utils/lispreader.h"
31 #include "special/frame_rate.h"
32 #include "gameloop.h"
33 #include "app/setup.h"
34 #include "sector.h"
35 #include "worldmap.h"
36 #include "audio/sound_manager.h"
37 #include "resources.h"
38 #include "app/gettext.h"
39 #include "misc.h"
40
41 #define map_message_TIME 2800
42
43 Menu* worldmap_menu  = 0;
44
45 namespace WorldMapNS {
46
47 Direction reverse_dir(Direction direction)
48 {
49   switch(direction)
50     {
51     case D_WEST:
52       return D_EAST;
53     case D_EAST:
54       return D_WEST;
55     case D_NORTH:
56       return D_SOUTH;
57     case D_SOUTH:
58       return D_NORTH;
59     case D_NONE:
60       return D_NONE;
61     }
62   return D_NONE;
63 }
64
65 std::string
66 direction_to_string(Direction direction)
67 {
68   switch(direction)
69     {
70     case D_WEST:
71       return "west";
72     case D_EAST:
73       return "east";
74     case D_NORTH:
75       return "north";
76     case D_SOUTH:
77       return "south";
78     default:
79       return "none";
80     }
81 }
82
83 Direction
84 string_to_direction(const std::string& directory)
85 {
86   if (directory == "west")
87     return D_WEST;
88   else if (directory == "east")
89     return D_EAST;
90   else if (directory == "north")
91     return D_NORTH;
92   else if (directory == "south")
93     return D_SOUTH;
94   else
95     return D_NONE;
96 }
97
98 TileManager::TileManager()
99 {
100   std::string stwt_filename = datadir +  "/images/worldmap/antarctica.stwt";
101   lisp_object_t* root_obj = lisp_read_from_file(stwt_filename);
102  
103   if (!root_obj)
104     Termination::abort("Couldn't load file", stwt_filename);
105
106   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap-tiles") == 0)
107     {
108       lisp_object_t* cur = lisp_cdr(root_obj);
109
110       while(!lisp_nil_p(cur))
111         {
112           lisp_object_t* element = lisp_car(cur);
113
114           if (strcmp(lisp_symbol(lisp_car(element)), "tile") == 0)
115             {
116               int id = 0;
117               std::string filename = "<invalid>";
118
119               Tile* tile = new Tile;             
120               tile->north = tile->east = tile->south = tile->west = true;
121               tile->stop  = true;
122               tile->auto_walk = false;
123   
124               LispReader reader(lisp_cdr(element));
125               reader.read_int("id", id);
126
127               std::string temp;
128               reader.read_string("possible-directions", temp);
129               if(!temp.empty())
130                 {
131                 tile->north = tile->east = tile->south = tile->west = false;
132                 if(temp.find("north") != std::string::npos)
133                   tile->north = true;
134                 if(temp.find("south") != std::string::npos)
135                   tile->south = true;
136                 if(temp.find("east") != std::string::npos)
137                   tile->east = true;
138                 if(temp.find("west") != std::string::npos)
139                   tile->west = true;
140                 }
141
142               /* For backward compatibility */
143               reader.read_bool("north", tile->north);
144               reader.read_bool("south", tile->south);
145               reader.read_bool("west",  tile->west);
146               reader.read_bool("east",  tile->east);
147
148               reader.read_bool("stop",  tile->stop);
149               reader.read_bool("auto-walk",  tile->auto_walk);
150               reader.read_string("image", filename);
151
152               reader.read_string("one-way", temp);
153               tile->one_way = BOTH_WAYS;
154               if(!temp.empty())
155                 {
156                 if(temp == "north-south")
157                   tile->one_way = NORTH_SOUTH_WAY;
158                 else if(temp == "south-north")
159                   tile->one_way = SOUTH_NORTH_WAY;
160                 else if(temp == "east-west")
161                   tile->one_way = EAST_WEST_WAY;
162                 else if(temp == "west-east")
163                   tile->one_way = WEST_EAST_WAY;
164                 }
165
166               tile->sprite = new Surface(
167                            datadir +  "/images/worldmap/" + filename, 
168                            true);
169
170               if (id >= int(tiles.size()))
171                 tiles.resize(id+1);
172
173               tiles[id] = tile;
174             }
175           else
176             {
177               puts("Unhandled symbol");
178             }
179
180           cur = lisp_cdr(cur);
181         }
182     }
183   else
184     {
185       assert(0);
186     }
187
188   lisp_free(root_obj);
189 }
190
191 TileManager::~TileManager()
192 {
193   for(std::vector<Tile*>::iterator i = tiles.begin(); i != tiles.end(); ++i)
194     delete *i;
195 }
196
197 Tile*
198 TileManager::get(int i)
199 {
200   assert(i >=0 && i < int(tiles.size()));
201   return tiles[i];
202 }
203
204 //---------------------------------------------------------------------------
205
206 Tux::Tux(WorldMap* worldmap_)
207   : worldmap(worldmap_)
208 {
209   largetux_sprite = new Surface(datadir +  "/images/worldmap/tux.png", true);
210   firetux_sprite = new Surface(datadir +  "/images/worldmap/firetux.png", true);
211   smalltux_sprite = new Surface(datadir +  "/images/worldmap/smalltux.png", true);
212
213   offset = 0;
214   moving = false;
215   tile_pos.x = worldmap->get_start_x();
216   tile_pos.y = worldmap->get_start_y();
217   direction = D_NONE;
218   input_direction = D_NONE;
219 }
220
221 Tux::~Tux()
222 {
223   delete smalltux_sprite;
224   delete firetux_sprite;
225   delete largetux_sprite;
226 }
227
228 void
229 Tux::draw(DrawingContext& context, const Vector& offset)
230 {
231   Vector pos = get_pos();
232   switch (player_status.bonus)
233     {
234     case PlayerStatus::GROWUP_BONUS:
235       context.draw_surface(largetux_sprite,
236           Vector(pos.x + offset.x, pos.y + offset.y - 10), LAYER_OBJECTS);
237       break;
238     case PlayerStatus::FLOWER_BONUS:
239       context.draw_surface(firetux_sprite,
240           Vector(pos.x + offset.x, pos.y + offset.y - 10), LAYER_OBJECTS);
241       break;
242     case PlayerStatus::NO_BONUS:
243       context.draw_surface(smalltux_sprite,
244           Vector(pos.x + offset.x, pos.y + offset.y - 10), LAYER_OBJECTS);
245       break;
246     }
247 }
248
249
250 Vector
251 Tux::get_pos()
252 {
253   float x = tile_pos.x * 32;
254   float y = tile_pos.y * 32;
255
256   switch(direction)
257     {
258     case D_WEST:
259       x -= offset - 32;
260       break;
261     case D_EAST:
262       x += offset - 32;
263       break;
264     case D_NORTH:
265       y -= offset - 32;
266       break;
267     case D_SOUTH:
268       y += offset - 32;
269       break;
270     case D_NONE:
271       break;
272     }
273   
274   return Vector((int)x, (int)y); 
275 }
276
277 void
278 Tux::stop()
279 {
280   offset = 0;
281   direction = D_NONE;
282   input_direction = D_NONE;
283   moving = false;
284 }
285
286 void
287 Tux::set_direction(Direction dir)
288 {
289 input_direction = dir;
290 }
291
292 void
293 Tux::action(float delta)
294 {
295   if (!moving)
296     {
297       if (input_direction != D_NONE)
298         { 
299           WorldMap::SpecialTile* special_tile = worldmap->at_special_tile();
300
301           // We got a new direction, so lets start walking when possible
302           Vector next_tile;
303           if ((!special_tile || special_tile->solved || special_tile->level_name.empty())
304               && worldmap->path_ok(input_direction, tile_pos, &next_tile))
305             {
306               tile_pos = next_tile;
307               moving = true;
308               direction = input_direction;
309               back_direction = reverse_dir(direction);
310             }
311           else if (input_direction == back_direction)
312             {
313               moving = true;
314               direction = input_direction;
315               tile_pos = worldmap->get_next_tile(tile_pos, direction);
316               back_direction = reverse_dir(direction);
317             }
318         }
319     }
320   else
321     {
322       // Let tux walk a few pixels (20 pixel/sec)
323       offset += 20.0f * delta;
324
325       if (offset > 32)
326         { // We reached the next tile, so we check what to do now
327           offset -= 32;
328
329           WorldMap::SpecialTile* special_tile = worldmap->at_special_tile();
330           if(special_tile && special_tile->passive_message)
331             {  // direction and the apply_action_ are opposites, since they "see"
332                // directions in a different way
333             if((direction == D_NORTH && special_tile->apply_action_south) ||
334                (direction == D_SOUTH && special_tile->apply_action_north) ||
335                (direction == D_WEST && special_tile->apply_action_east) ||
336                (direction == D_EAST && special_tile->apply_action_west))
337               {
338               worldmap->passive_message = special_tile->map_message;
339               worldmap->passive_message_timer.start(map_message_TIME);
340               }
341             }
342
343           if (worldmap->at(tile_pos)->stop || (special_tile && 
344               !special_tile->passive_message))
345             {
346               if(special_tile && !special_tile->map_message.empty() &&
347                 !special_tile->passive_message)
348                 worldmap->passive_message_timer.stop();
349               stop();
350             }
351           else
352             {
353               if (worldmap->at(tile_pos)->auto_walk || direction != input_direction)
354                 { // Turn to a new direction
355                   Tile* tile = worldmap->at(tile_pos);
356
357                   if(direction != input_direction && 
358                      ((tile->north && input_direction == D_NORTH) ||
359                      (tile->south && input_direction == D_SOUTH) ||
360                      (tile->east && input_direction == D_EAST) ||
361                      (tile->west && input_direction == D_WEST)))
362                     {  // player has changed direction during auto-movement
363                     direction = input_direction;
364                     back_direction = reverse_dir(direction);
365                     }
366                   else if(direction != input_direction)
367                     {  // player has changed to impossible tile
368                       back_direction = reverse_dir(direction);
369                       stop();
370                     }
371                   else
372                     {
373                     Direction dir = D_NONE;
374                   
375                     if (tile->north && back_direction != D_NORTH)
376                       dir = D_NORTH;
377                     else if (tile->south && back_direction != D_SOUTH)
378                       dir = D_SOUTH;
379                     else if (tile->east && back_direction != D_EAST)
380                       dir = D_EAST;
381                     else if (tile->west && back_direction != D_WEST)
382                       dir = D_WEST;
383
384                     if (dir != D_NONE)
385                       {
386                       direction = dir;
387                       input_direction = direction;
388                       back_direction = reverse_dir(direction);
389                       }
390                     else
391                       {
392                       // Should never be reached if tiledata is good
393                       stop();
394                       return;
395                       }
396                     }
397                   }
398
399               // Walk automatically to the next tile
400               if(direction != D_NONE)
401                 {
402                 Vector next_tile;
403                 if (worldmap->path_ok(direction, tile_pos, &next_tile))
404                   {
405                   tile_pos = next_tile;
406                   }
407                 else
408                   {
409                   puts("Tilemap data is buggy");
410                   stop();
411                   }
412                 }
413             }
414         }
415     }
416 }
417
418 //---------------------------------------------------------------------------
419 Tile::Tile()
420 {
421 }
422
423 Tile::~Tile()
424 {
425   delete sprite;
426 }
427
428 //---------------------------------------------------------------------------
429
430 WorldMap::WorldMap()
431 {
432   tile_manager = new TileManager();
433   //tux = new Tux(this);
434   
435   width  = 20;
436   height = 15;
437   
438   start_x = 4;
439   start_y = 5;
440   
441   leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", true);
442   leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", true);
443   messagedot   = new Surface(datadir +  "/images/worldmap/messagedot.png", true);
444   teleporterdot   = new Surface(datadir +  "/images/worldmap/teleporterdot.png", true);
445
446   enter_level = false;
447
448   name = "<no title>";
449   music = "SALCON.MOD";
450 }
451
452 WorldMap::~WorldMap()
453 {
454   delete tux;
455   delete tile_manager;
456
457   delete leveldot_green;
458   delete leveldot_red;
459   delete messagedot;
460   delete teleporterdot;
461 }
462
463 void
464 WorldMap::load_map()
465 {
466   lisp_object_t* root_obj = lisp_read_from_file(datadir + "/levels/worldmap/" + map_filename);
467   if (!root_obj)
468     Termination::abort("Couldn't load file", datadir + "/levels/worldmap/" + map_filename);
469
470   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap") == 0)
471     {
472       lisp_object_t* cur = lisp_cdr(root_obj);
473
474       while(!lisp_nil_p(cur))
475         {
476           lisp_object_t* element = lisp_car(cur);
477
478           if (strcmp(lisp_symbol(lisp_car(element)), "tilemap") == 0)
479             {
480               LispReader reader(lisp_cdr(element));
481               reader.read_int("width",  width);
482               reader.read_int("height", height);
483               reader.read_int_vector("data", tilemap);
484             }
485           else if (strcmp(lisp_symbol(lisp_car(element)), "properties") == 0)
486             {
487               LispReader reader(lisp_cdr(element));
488               reader.read_string("name", name, true);
489               reader.read_string("music", music);
490               reader.read_int("start_pos_x", start_x);
491               reader.read_int("start_pos_y", start_y);
492             }
493           else if (strcmp(lisp_symbol(lisp_car(element)), "special-tiles") == 0 ||
494                    strcmp(lisp_symbol(lisp_car(element)), "levels") == 0)
495             {
496               lisp_object_t* cur = lisp_cdr(element);
497               
498               while(!lisp_nil_p(cur))
499                 {
500                   lisp_object_t* element = lisp_car(cur);
501
502                   if (strcmp(lisp_symbol(lisp_car(element)), "special-tile") == 0)
503                     {
504                       SpecialTile special_tile;
505                       LispReader reader(lisp_cdr(element));
506                       special_tile.solved = false;
507                       
508                       special_tile.north = true;
509                       special_tile.east  = true;
510                       special_tile.south = true;
511                       special_tile.west  = true;
512
513                       reader.read_int("x", special_tile.x);
514                       reader.read_int("y", special_tile.y);
515                       reader.read_string("level", special_tile.level_name, true);
516
517                       special_tile.vertical_flip = false;
518                       reader.read_bool("vertical-flip", special_tile.vertical_flip);
519
520                       special_tile.map_message.erase();
521                       reader.read_string("map-message", special_tile.map_message);
522                       special_tile.passive_message = false;
523                       reader.read_bool("passive-message", special_tile.passive_message);
524
525                       special_tile.teleport_dest_x = special_tile.teleport_dest_y = -1;
526                       reader.read_int("teleport-to-x", special_tile.teleport_dest_x);
527                       reader.read_int("teleport-to-y", special_tile.teleport_dest_y);
528
529                       special_tile.invisible = false;
530                       reader.read_bool("invisible-tile", special_tile.invisible);
531
532                       special_tile.apply_action_north = special_tile.apply_action_south =
533                           special_tile.apply_action_east = special_tile.apply_action_west =
534                           true;
535                       std::string apply_direction;
536                       reader.read_string("apply-to-direction", apply_direction);
537                       if(!apply_direction.empty())
538                         {
539                         special_tile.apply_action_north = special_tile.apply_action_south =
540                             special_tile.apply_action_east = special_tile.apply_action_west =
541                             false;
542                         if(apply_direction.find("north") != std::string::npos)
543                           special_tile.apply_action_north = true;
544                         if(apply_direction.find("south") != std::string::npos)
545                           special_tile.apply_action_south = true;
546                         if(apply_direction.find("east") != std::string::npos)
547                           special_tile.apply_action_east = true;
548                         if(apply_direction.find("west") != std::string::npos)
549                           special_tile.apply_action_west = true;
550                         }
551
552                       reader.read_string("extro-filename", special_tile.extro_filename);
553                       reader.read_string("next-world", special_tile.next_worldmap);
554                       special_tile.quit_worldmap = false;
555                       reader.read_bool("exit-game", special_tile.quit_worldmap);
556
557                       special_tile.auto_path = true;
558                       reader.read_bool("auto-path", special_tile.auto_path);
559
560                       special_tiles.push_back(special_tile);
561                     }
562
563                   /* Kept for backward compability */
564                   else if (strcmp(lisp_symbol(lisp_car(element)), "level") == 0)
565                     {
566                       SpecialTile special_tile;
567                       LispReader reader(lisp_cdr(element));
568                       special_tile.solved = false;
569                       
570                       special_tile.north = true;
571                       special_tile.east  = true;
572                       special_tile.south = true;
573                       special_tile.west  = true;
574
575                       special_tile.invisible = false;
576
577                       special_tile.apply_action_north = special_tile.apply_action_south =
578                           special_tile.apply_action_east = special_tile.apply_action_west =
579                           true;
580                       special_tile.vertical_flip = false;
581                       special_tile.teleport_dest_x = special_tile.teleport_dest_y = -1;
582
583                       reader.read_string("extro-filename", special_tile.extro_filename);
584                       if(!special_tile.extro_filename.empty())
585                         special_tile.quit_worldmap = true;
586                       reader.read_string("name", special_tile.level_name, true);
587                       reader.read_int("x", special_tile.x);
588                       reader.read_int("y", special_tile.y);
589
590
591                       special_tiles.push_back(special_tile);
592                     }
593                   
594                   cur = lisp_cdr(cur);      
595                 }
596             }
597           else
598             {
599               
600             }
601           
602           cur = lisp_cdr(cur);
603         }
604     }
605
606     lisp_free(root_obj);
607     tux = new Tux(this);
608 }
609
610 void WorldMap::get_level_title(SpecialTile& special_tile)
611 {
612   /** get special_tile's title */
613   special_tile.title = "<no title>";
614
615   LispReader* reader = LispReader::load(datadir + "/levels/" + special_tile.level_name, "supertux-level");
616   if(!reader)
617     {
618     std::cerr << "Error: Could not open level file. Ignoring...\n";
619     return;
620     }
621
622   reader->read_string("name", special_tile.title, true);
623   delete reader;
624 }
625
626 void
627 WorldMap::on_escape_press()
628 {
629   // Show or hide the menu
630   if(!Menu::current())
631     {
632     Menu::set_current(worldmap_menu); 
633     tux->set_direction(D_NONE);  // stop tux movement when menu is called
634     }
635   else
636     Menu::set_current(0); 
637 }
638
639 void
640 WorldMap::get_input()
641 {
642   enter_level = false;
643    
644   SDL_Event event;
645   while (SDL_PollEvent(&event))
646     {
647       if (Menu::current())
648         {
649           Menu::current()->event(event);
650         }
651       else
652         {
653           switch(event.type)
654             {
655             case SDL_QUIT:
656               Termination::abort("Received window close", "");
657               break;
658           
659             case SDL_KEYDOWN:
660               switch(event.key.keysym.sym)
661                 {
662                 case SDLK_ESCAPE:
663                   on_escape_press();
664                   break;
665                 case SDLK_LCTRL:
666                 case SDLK_RETURN:
667                   enter_level = true;
668                   break;
669
670                 case SDLK_LEFT:
671                   tux->set_direction(D_WEST);
672                   break;
673                 case SDLK_RIGHT:
674                   tux->set_direction(D_EAST);
675                   break;
676                 case SDLK_UP:
677                   tux->set_direction(D_NORTH);
678                   break;
679                 case SDLK_DOWN:
680                   tux->set_direction(D_SOUTH);
681                   break;
682
683                 default:
684                   break;
685                 }
686               break;
687           
688             case SDL_JOYAXISMOTION:
689               if (event.jaxis.axis == joystick_keymap.x_axis)
690                 {
691                   if (event.jaxis.value < -joystick_keymap.dead_zone)
692                     tux->set_direction(D_WEST);
693                   else if (event.jaxis.value > joystick_keymap.dead_zone)
694                     tux->set_direction(D_EAST);
695                 }
696               else if (event.jaxis.axis == joystick_keymap.y_axis)
697                 {
698                   if (event.jaxis.value > joystick_keymap.dead_zone)
699                     tux->set_direction(D_SOUTH);
700                   else if (event.jaxis.value < -joystick_keymap.dead_zone)
701                     tux->set_direction(D_NORTH);
702                 }
703               break;
704
705             case SDL_JOYBUTTONDOWN:
706               if (event.jbutton.button == joystick_keymap.b_button)
707                 enter_level = true;
708               else if (event.jbutton.button == joystick_keymap.start_button)
709                 on_escape_press();
710               break;
711
712             default:
713               break;
714             }
715         }
716     }
717 }
718
719 Vector
720 WorldMap::get_next_tile(Vector pos, Direction direction)
721 {
722   switch(direction)
723     {
724     case D_WEST:
725       pos.x -= 1;
726       break;
727     case D_EAST:
728       pos.x += 1;
729       break;
730     case D_NORTH:
731       pos.y -= 1;
732       break;
733     case D_SOUTH:
734       pos.y += 1;
735       break;
736     case D_NONE:
737       break;
738     }
739   return pos;
740 }
741
742 bool
743 WorldMap::path_ok(Direction direction, Vector old_pos, Vector* new_pos)
744 {
745   *new_pos = get_next_tile(old_pos, direction);
746
747   if (!(new_pos->x >= 0 && new_pos->x < width
748         && new_pos->y >= 0 && new_pos->y < height))
749     { // New position is outsite the tilemap
750       return false;
751     }
752   else if(at(*new_pos)->one_way != BOTH_WAYS)
753     {
754 std::cerr << "one way only\n";
755       if((at(*new_pos)->one_way == NORTH_SOUTH_WAY && direction != D_SOUTH) ||
756          (at(*new_pos)->one_way == SOUTH_NORTH_WAY && direction != D_NORTH) ||
757          (at(*new_pos)->one_way == EAST_WEST_WAY && direction != D_WEST) ||
758          (at(*new_pos)->one_way == WEST_EAST_WAY && direction != D_EAST))
759         return false;
760       return true;
761     }
762   else
763     { // Check if we the tile allows us to go to new_pos
764       switch(direction)
765         {
766         case D_WEST:
767           return (at(old_pos)->west && at(*new_pos)->east);
768
769         case D_EAST:
770           return (at(old_pos)->east && at(*new_pos)->west);
771
772         case D_NORTH:
773           return (at(old_pos)->north && at(*new_pos)->south);
774
775         case D_SOUTH:
776           return (at(old_pos)->south && at(*new_pos)->north);
777
778         case D_NONE:
779           assert(!"path_ok() can't work if direction is NONE");
780         }
781       return false;
782     }
783 }
784
785 void
786 WorldMap::update(float delta)
787 {
788   if (enter_level && !tux->is_moving())
789     {
790       bool level_finished = true;
791       SpecialTile* special_tile = at_special_tile();
792       if (!special_tile)
793         {
794         std::cout << "Nothing to enter at: "
795           << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
796         return;
797         }
798
799
800       if(!special_tile->level_name.empty())
801         {
802           if (special_tile->x == tux->get_tile_pos().x && 
803               special_tile->y == tux->get_tile_pos().y)
804             {
805               PlayerStatus old_player_status = player_status;
806
807               std::cout << "Enter the current level: " << special_tile->level_name << std::endl;
808               // do a shriking fade to the special_tile
809               shrink_fade(Vector((special_tile->x*32 + 16 + offset.x),(special_tile->y*32 + 16
810                       + offset.y)), 500);
811               GameSession session(datadir +  "/levels/" + special_tile->level_name,
812                                   ST_GL_LOAD_LEVEL_FILE, special_tile->vertical_flip);
813
814               switch (session.run())
815                 {
816                 case GameSession::ES_LEVEL_FINISHED:
817                   {
818                     level_finished = true;
819                     bool old_level_state = special_tile->solved;
820                     special_tile->solved = true;
821
822                     if (session.get_current_sector()->player->got_power !=
823                           session.get_current_sector()->player->NONE_POWER)
824                       player_status.bonus = PlayerStatus::FLOWER_BONUS;
825                     else if (session.get_current_sector()->player->size == BIG)
826                       player_status.bonus = PlayerStatus::GROWUP_BONUS;
827                     else
828                       player_status.bonus = PlayerStatus::NO_BONUS;
829
830                     if (old_level_state != special_tile->solved && special_tile->auto_path)
831                       { // Try to detect the next direction to which we should walk
832                         // FIXME: Mostly a hack
833                         Direction dir = D_NONE;
834                     
835                         Tile* tile = at(tux->get_tile_pos());
836
837                         if (tile->north && tux->back_direction != D_NORTH)
838                           dir = D_NORTH;
839                         else if (tile->south && tux->back_direction != D_SOUTH)
840                           dir = D_SOUTH;
841                         else if (tile->east && tux->back_direction != D_EAST)
842                           dir = D_EAST;
843                         else if (tile->west && tux->back_direction != D_WEST)
844                           dir = D_WEST;
845
846                         if (dir != D_NONE)
847                           {
848                             tux->set_direction(dir);
849                             //tux->update(delta);
850                           }
851
852                         std::cout << "Walk to dir: " << dir << std::endl;
853                       }
854                   }
855
856                   break;
857                 case GameSession::ES_LEVEL_ABORT:
858                   level_finished = false;
859                   /* In case the player's abort the special_tile, keep it using the old
860                       status. But the minimum lives and no bonus. */
861                   player_status.score = old_player_status.score;
862                   player_status.distros = old_player_status.distros;
863                   player_status.lives = std::min(old_player_status.lives, player_status.lives);
864                   player_status.bonus = player_status.NO_BONUS;
865
866                   break;
867                 case GameSession::ES_GAME_OVER:
868                   {
869                   level_finished = false;
870                   /* draw an end screen */
871                   /* in the future, this should make a dialog a la SuperMario, asking
872                   if the player wants to restart the world map with no score and from
873                   special_tile 1 */
874                   char str[80];
875
876                   DrawingContext context;
877                   context.draw_gradient(Color (200,240,220), Color(200,200,220),
878                       LAYER_BACKGROUND0);
879
880                   context.draw_text_center(blue_text, _("GAMEOVER"), 
881                       Vector(0, 200), LAYER_FOREGROUND1);
882
883                   sprintf(str, _("SCORE: %d"), player_status.score);
884                   context.draw_text_center(gold_text, str,
885                       Vector(0, 230), LAYER_FOREGROUND1);
886
887                   sprintf(str, _("COINS: %d"), player_status.distros);
888                   context.draw_text_center(gold_text, str,
889                       Vector(0, screen->w - 32), LAYER_FOREGROUND1);
890
891                   context.do_drawing();
892   
893                   SDL_Event event;
894                   wait_for_event(event,2000,5000,true);
895
896                   quit = true;
897                   player_status.reset();
898                   break;
899                   }
900                 case GameSession::ES_NONE:
901                   assert(false);
902                   // Should never be reached 
903                   break;
904                 }
905
906               SoundManager::get()->play_music(song);
907               Menu::set_current(0);
908               if (!savegame_file.empty())
909                 savegame(savegame_file);
910             }
911         }
912       /* The porpose of the next checking is that if the player lost
913          the special_tile (in case there is one), don't show anything */
914       if(level_finished)
915         {
916         if (!special_tile->extro_filename.empty())
917           {
918           // Display a text file
919           display_text_file(special_tile->extro_filename, SCROLL_SPEED_MESSAGE, white_big_text , white_text, white_small_text, blue_text );
920           }
921         if (special_tile->teleport_dest_x != -1 && special_tile->teleport_dest_y != -1)
922           {
923           // TODO: an animation, camera scrolling or a fading would be a nice touch
924           SoundManager::get()->play_sound(IDToSound(SND_WARP));
925           tux->back_direction = D_NONE;
926           tux->set_tile_pos(Vector(special_tile->teleport_dest_x, special_tile->teleport_dest_y));
927           SDL_Delay(1000);
928           }
929         if (!special_tile->next_worldmap.empty())
930           {
931           // Load given worldmap
932           loadmap(special_tile->next_worldmap);
933           }
934         if (special_tile->quit_worldmap)
935           quit = true;
936         }
937     }
938   else
939     {
940       tux->action(delta);
941 //      tux->set_direction(input_direction);
942     }
943   
944   Menu* menu = Menu::current();
945   if(menu)
946     {
947       menu->action();
948
949       if(menu == worldmap_menu)
950         {
951           switch (worldmap_menu->check())
952             {
953             case MNID_RETURNWORLDMAP: // Return to game
954               break;
955             case MNID_QUITWORLDMAP: // Quit Worldmap
956               quit = true;
957               break;
958             }
959         }
960       else if(menu == options_menu)
961         {
962           process_options_menu();
963         }
964     }
965 }
966
967 Tile*
968 WorldMap::at(Vector p)
969 {
970   assert(p.x >= 0 
971          && p.x < width
972          && p.y >= 0
973          && p.y < height);
974
975   int x = int(p.x);
976   int y = int(p.y);
977   return tile_manager->get(tilemap[width * y + x]);
978 }
979
980 WorldMap::SpecialTile*
981 WorldMap::at_special_tile()
982 {
983   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
984     {
985       if (i->x == tux->get_tile_pos().x && 
986           i->y == tux->get_tile_pos().y)
987         return &*i; 
988     }
989
990   return 0;
991 }
992
993
994 void
995 WorldMap::draw(DrawingContext& context, const Vector& offset)
996 {
997   for(int y = 0; y < height; ++y)
998     for(int x = 0; x < width; ++x)
999       {
1000         Tile* tile = at(Vector(x, y));
1001         context.draw_surface(tile->sprite,
1002             Vector(x*32 + offset.x, y*32 + offset.y), LAYER_TILES);
1003       }
1004   
1005   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1006     {
1007       if(i->invisible)
1008         continue;
1009       if(i->level_name.empty())
1010         {
1011         if (i->teleport_dest_x != -1 && i->teleport_dest_y != -1)
1012           context.draw_surface(teleporterdot,
1013               Vector(i->x*32 + offset.x, i->y*32 + offset.y), LAYER_TILES+1);
1014
1015         else if (!i->map_message.empty() && !i->passive_message)
1016           context.draw_surface(messagedot,
1017               Vector(i->x*32 + offset.x, i->y*32 + offset.y), LAYER_TILES+1);
1018
1019         continue;
1020         }
1021
1022       if (i->solved)
1023         context.draw_surface(leveldot_green,
1024             Vector(i->x*32 + offset.x, i->y*32 + offset.y), LAYER_TILES+1);
1025       else
1026         context.draw_surface(leveldot_red,
1027             Vector(i->x*32 + offset.x, i->y*32 + offset.y), LAYER_TILES+1);
1028     }
1029
1030   tux->draw(context, offset);
1031   draw_status(context);
1032 }
1033
1034 void
1035 WorldMap::draw_status(DrawingContext& context)
1036 {
1037   char str[80];
1038   sprintf(str, " %d", player_status.score);
1039
1040   context.draw_text(white_text, _("SCORE"), Vector(0, 0), LAYER_FOREGROUND1);
1041   context.draw_text(gold_text, str, Vector(96, 0), LAYER_FOREGROUND1);
1042
1043   sprintf(str, "%d", player_status.distros);
1044   context.draw_text(white_text, _("COINS"), Vector(screen->w/2 - 16*5, 0),
1045       LAYER_FOREGROUND1);
1046   context.draw_text(gold_text, str, Vector(screen->w/2 + (16*5)/2, 0),
1047         LAYER_FOREGROUND1);
1048
1049   if (player_status.lives >= 5)
1050     {
1051       sprintf(str, "%dx", player_status.lives);
1052       context.draw_text(gold_text, str, 
1053           Vector(screen->w - gold_text->get_text_width(str) - tux_life->w, 0),
1054           LAYER_FOREGROUND1);
1055       context.draw_surface(tux_life, Vector(screen->w -
1056             gold_text->get_text_width("9"), 0), LAYER_FOREGROUND1);
1057     }
1058   else
1059     {
1060       for(int i= 0; i < player_status.lives; ++i)
1061         context.draw_surface(tux_life,
1062             Vector(screen->w - tux_life->w*4 + (tux_life->w*i), 0),
1063             LAYER_FOREGROUND1);
1064     }
1065   context.draw_text(white_text, _("LIVES"),
1066       Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 0),
1067       LAYER_FOREGROUND1);
1068
1069   if (!tux->is_moving())
1070     {
1071       for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1072         {
1073           if (i->x == tux->get_tile_pos().x && 
1074               i->y == tux->get_tile_pos().y)
1075             {
1076               if(!i->level_name.empty())
1077                 {
1078                 if(i->title == "")
1079                   get_level_title(*i);
1080
1081                 context.draw_text_center(white_text, i->title, 
1082                     Vector(0, screen->h - white_text->get_height() - 30),
1083                     LAYER_FOREGROUND1);
1084                 }
1085
1086               /* Display an in-map message in the map, if any as been selected */
1087               if(!i->map_message.empty() && !i->passive_message)
1088                 context.draw_text_center(gold_text, i->map_message, 
1089                     Vector(0, screen->h - white_text->get_height() - 60),
1090                     LAYER_FOREGROUND1);
1091               break;
1092             }
1093         }
1094     }
1095   /* Display a passive message in the map, if needed */
1096   if(passive_message_timer.check())
1097     context.draw_text_center(gold_text, passive_message, 
1098             Vector(0, screen->h - white_text->get_height() - 60),
1099             LAYER_FOREGROUND1);
1100 }
1101
1102 void
1103 WorldMap::display()
1104 {
1105   Menu::set_current(0);
1106
1107   quit = false;
1108
1109   song = SoundManager::get()->load_music(datadir +  "/music/" + music);
1110   SoundManager::get()->play_music(song);
1111
1112   FrameRate frame_rate(10);
1113   frame_rate.set_frame_limit(false);
1114
1115   frame_rate.start();
1116
1117   DrawingContext context;
1118   while(!quit)
1119     {
1120       float delta = frame_rate.get();
1121
1122       delta *= 1.3f;
1123
1124       if (delta > 10.0f)
1125         delta = .3f;
1126         
1127       frame_rate.update();
1128
1129       Vector tux_pos = tux->get_pos();
1130       if (1)
1131         {
1132           offset.x = -tux_pos.x + screen->w/2;
1133           offset.y = -tux_pos.y + screen->h/2;
1134
1135           if (offset.x > 0) offset.x = 0;
1136           if (offset.y > 0) offset.y = 0;
1137
1138           if (offset.x < screen->w - width*32) offset.x = screen->w - width*32;
1139           if (offset.y < screen->h - height*32) offset.y = screen->h - height*32;
1140         } 
1141
1142       draw(context, offset);
1143       get_input();
1144       update(delta);
1145       
1146       if(Menu::current())
1147         {
1148           Menu::current()->draw(context);
1149           mouse_cursor->draw(context);
1150         }
1151
1152       context.do_drawing();
1153
1154       SDL_Delay(20);
1155     }
1156 }
1157
1158 void
1159 WorldMap::savegame(const std::string& filename)
1160 {
1161   if(filename == "")
1162     return;
1163
1164   std::cout << "savegame: " << filename << std::endl;
1165   std::ofstream out(filename.c_str());
1166
1167   int nb_solved_levels = 0;
1168   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1169     {
1170       if (i->solved)
1171         ++nb_solved_levels;
1172     }
1173
1174   out << "(supertux-savegame\n"
1175       << "  (version 1)\n"
1176       << "  (title  \"" << name << " - " << nb_solved_levels << "/" << special_tiles.size() << "\")\n"
1177       << "  (map    \"" << map_filename << "\")\n"
1178       << "  (lives   " << player_status.lives << ")\n"
1179       << "  (score   " << player_status.score << ")\n"
1180       << "  (distros " << player_status.distros << ")\n"
1181       << "  (tux (x " << tux->get_tile_pos().x << ") (y " << tux->get_tile_pos().y << ")\n"
1182       << "       (back \"" << direction_to_string(tux->back_direction) << "\")\n"
1183       << "       (bonus \"" << bonus_to_string(player_status.bonus) <<  "\"))\n"
1184       << "  (levels\n";
1185   
1186   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1187     {
1188       if (i->solved && !i->level_name.empty())
1189         {
1190           out << "     (level (name \"" << i->level_name << "\")\n"
1191               << "            (solved #t))\n";
1192         }
1193     }  
1194
1195   out << "   )\n"
1196       << " )\n\n;; EOF ;;" << std::endl;
1197 }
1198
1199 void
1200 WorldMap::loadgame(const std::string& filename)
1201 {
1202   std::cout << "loadgame: " << filename << std::endl;
1203   savegame_file = filename;
1204   map_filename = "icyisland.stwm";
1205
1206   if (access(filename.c_str(), F_OK) != 0)
1207     {
1208     load_map();
1209     return;
1210     }
1211   
1212   lisp_object_t* savegame = lisp_read_from_file(filename);
1213   if (!savegame)
1214     {
1215       std::cout << "WorldMap:loadgame: File not found: " << filename << std::endl;
1216       load_map();
1217       return;
1218     }
1219
1220   lisp_object_t* cur = savegame;
1221
1222   if (strcmp(lisp_symbol(lisp_car(cur)), "supertux-savegame") != 0)
1223     {
1224     load_map();
1225     return;
1226     }
1227
1228   cur = lisp_cdr(cur);
1229   LispReader reader(cur);
1230
1231   /* Get the Map filename and then load it before setting special_tile settings */
1232   reader.read_string("map", map_filename);
1233   load_map(); 
1234
1235   reader.read_int("lives", player_status.lives);
1236   reader.read_int("score", player_status.score);
1237   reader.read_int("distros", player_status.distros);
1238
1239   if (player_status.lives < 0)
1240     player_status.lives = START_LIVES;
1241
1242   lisp_object_t* tux_cur = 0;
1243   if (reader.read_lisp("tux", tux_cur))
1244     {
1245       Vector p;
1246       std::string back_str = "none";
1247       std::string bonus_str = "none";
1248
1249       LispReader tux_reader(tux_cur);
1250       tux_reader.read_float("x", p.x);
1251       tux_reader.read_float("y", p.y);
1252       tux_reader.read_string("back", back_str);
1253       tux_reader.read_string("bonus", bonus_str);
1254       
1255       player_status.bonus = string_to_bonus(bonus_str);
1256       tux->back_direction = string_to_direction(back_str);      
1257       tux->set_tile_pos(p);
1258     }
1259
1260   lisp_object_t* level_cur = 0;
1261   if (reader.read_lisp("levels", level_cur))
1262     {
1263       while(level_cur)
1264         {
1265           lisp_object_t* sym  = lisp_car(lisp_car(level_cur));
1266           lisp_object_t* data = lisp_cdr(lisp_car(level_cur));
1267
1268           if (strcmp(lisp_symbol(sym), "level") == 0)
1269             {
1270               std::string name;
1271               bool solved = false;
1272
1273               LispReader level_reader(data);
1274               level_reader.read_string("name", name, true);
1275               level_reader.read_bool("solved", solved);
1276
1277               for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1278                 {
1279                   if (name == i->level_name)
1280                     i->solved = solved;
1281                 }
1282             }
1283
1284           level_cur = lisp_cdr(level_cur);
1285         }
1286     }
1287  
1288   lisp_free(savegame);
1289 }
1290
1291 void
1292 WorldMap::loadmap(const std::string& filename)
1293 {
1294   savegame_file = "";
1295   map_filename = filename;
1296   load_map();
1297 }
1298
1299 } // namespace WorldMapNS
1300
1301 /* Local Variables: */
1302 /* mode:c++ */
1303 /* End: */
1304