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