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