299fff515e07703a2759ddd83f5b5b3e2a8adc42
[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->statistics);
869
870               switch (session.run())
871                 {
872                 case GameSession::ES_LEVEL_FINISHED:
873                   {
874                     level_finished = true;
875                     bool old_level_state = level->solved;
876                     level->solved = true;
877
878                     // deal with statistics
879                     level->statistics.merge(global_stats);
880                     calculate_total_stats();
881
882                     if (session.get_current_sector()->player->got_power !=
883                           session.get_current_sector()->player->NONE_POWER)
884                       player_status.bonus = PlayerStatus::FLOWER_BONUS;
885                     else if (session.get_current_sector()->player->size == BIG)
886                       player_status.bonus = PlayerStatus::GROWUP_BONUS;
887                     else
888                       player_status.bonus = PlayerStatus::NO_BONUS;
889
890                     if (old_level_state != level->solved && level->auto_path)
891                       { // Try to detect the next direction to which we should walk
892                         // FIXME: Mostly a hack
893                         Direction dir = D_NONE;
894                     
895                         Tile* tile = at(tux->get_tile_pos());
896
897                         if (tile->north && tux->back_direction != D_NORTH)
898                           dir = D_NORTH;
899                         else if (tile->south && tux->back_direction != D_SOUTH)
900                           dir = D_SOUTH;
901                         else if (tile->east && tux->back_direction != D_EAST)
902                           dir = D_EAST;
903                         else if (tile->west && tux->back_direction != D_WEST)
904                           dir = D_WEST;
905
906                         if (dir != D_NONE)
907                           {
908                             tux->set_direction(dir);
909                             //tux->update(delta);
910                           }
911
912                         std::cout << "Walk to dir: " << dir << std::endl;
913                       }
914                   }
915
916                   break;
917                 case GameSession::ES_LEVEL_ABORT:
918                   level_finished = false;
919                   /* In case the player's abort the level, keep it using the old
920                       status. But the minimum lives and no bonus. */
921                   player_status.distros = old_player_status.distros;
922                   player_status.lives = std::min(old_player_status.lives, player_status.lives);
923                   player_status.bonus = player_status.NO_BONUS;
924
925                   break;
926                 case GameSession::ES_GAME_OVER:
927                   {
928                   level_finished = false;
929                   /* draw an end screen */
930                   /* TODO: in the future, this should make a dialog a la SuperMario, asking
931                   if the player wants to restart the world map with no score and from
932                   level 1 */
933                   char str[80];
934
935                   DrawingContext context;
936                   context.draw_gradient(Color (200,240,220), Color(200,200,220),
937                       LAYER_BACKGROUND0);
938
939                   context.draw_text(blue_text, _("GAMEOVER"), 
940                       Vector(screen->w/2, 200), CENTER_ALLIGN, LAYER_FOREGROUND1);
941
942                   sprintf(str, _("COINS: %d"), player_status.distros);
943                   context.draw_text(gold_text, str,
944                       Vector(screen->w/2, screen->w - 32), CENTER_ALLIGN, LAYER_FOREGROUND1);
945
946                   total_stats.draw_message_info(context, _("Total Statistics"));
947
948                   context.do_drawing();
949   
950                   SDL_Event event;
951                   wait_for_event(event,2000,6000,true);
952
953                   quit = true;
954                   player_status.reset();
955                   break;
956                   }
957                 case GameSession::ES_NONE:
958                   assert(false);
959                   // Should never be reached 
960                   break;
961                 }
962
963               SoundManager::get()->play_music(song);
964               Menu::set_current(0);
965               if (!savegame_file.empty())
966                 savegame(savegame_file);
967             }
968       /* The porpose of the next checking is that if the player lost
969          the level (in case there is one), don't show anything */
970       if(level_finished)
971         {
972         if (!level->extro_filename.empty())
973           {
974           // Display a text file
975           display_text_file(level->extro_filename, SCROLL_SPEED_MESSAGE, white_big_text , white_text, white_small_text, blue_text );
976           }
977
978         if (!level->next_worldmap.empty())
979           {
980           // Load given worldmap
981           loadmap(level->next_worldmap);
982           }
983         if (level->quit_worldmap)
984           quit = true;
985         }
986     }
987   else
988     {
989       tux->action(delta);
990 //      tux->set_direction(input_direction);
991     }
992   
993   Menu* menu = Menu::current();
994   if(menu)
995     {
996       menu->action();
997
998       if(menu == worldmap_menu)
999         {
1000           switch (worldmap_menu->check())
1001             {
1002             case MNID_RETURNWORLDMAP: // Return to game
1003               break;
1004             case MNID_QUITWORLDMAP: // Quit Worldmap
1005               quit = true;
1006               break;
1007             }
1008         }
1009       else if(menu == options_menu)
1010         {
1011           process_options_menu();
1012         }
1013     }
1014 }
1015
1016 Tile*
1017 WorldMap::at(Vector p)
1018 {
1019   assert(p.x >= 0 
1020          && p.x < width
1021          && p.y >= 0
1022          && p.y < height);
1023
1024   int x = int(p.x);
1025   int y = int(p.y);
1026   return tile_manager->get(tilemap[width * y + x]);
1027 }
1028
1029 WorldMap::Level*
1030 WorldMap::at_level()
1031 {
1032   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1033     {
1034       if (i->pos == tux->get_tile_pos())
1035         return &*i; 
1036     }
1037
1038   return 0;
1039 }
1040
1041 WorldMap::SpecialTile*
1042 WorldMap::at_special_tile()
1043 {
1044   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1045     {
1046       if (i->pos == tux->get_tile_pos())
1047         return &*i; 
1048     }
1049
1050   return 0;
1051 }
1052
1053
1054 void
1055 WorldMap::draw(DrawingContext& context, const Vector& offset)
1056 {
1057   for(int y = 0; y < height; ++y)
1058     for(int x = 0; x < width; ++x)
1059       {
1060         Tile* tile = at(Vector(x, y));
1061         tile->draw(context, Vector(x*32 + offset.x, y*32 + offset.y));
1062       }
1063
1064   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1065     {
1066       if (i->solved)
1067         context.draw_surface(leveldot_green,
1068             Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
1069       else
1070         context.draw_surface(leveldot_red,
1071             Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
1072     }
1073
1074   for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1075     {
1076       if(i->invisible)
1077         continue;
1078
1079       if (i->teleport_dest != Vector(-1, -1))
1080         context.draw_surface(teleporterdot,
1081                 Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
1082
1083       else if (!i->map_message.empty() && !i->passive_message)
1084         context.draw_surface(messagedot,
1085                 Vector(i->pos.x*32 + offset.x, i->pos.y*32 + offset.y), LAYER_TILES+1);
1086     }
1087
1088   tux->draw(context, offset);
1089   draw_status(context);
1090 }
1091
1092 void
1093 WorldMap::draw_status(DrawingContext& context)
1094 {
1095   char str[80];
1096   sprintf(str, " %d", total_stats.get_points(SCORE_STAT));
1097
1098   context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
1099   context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
1100
1101   sprintf(str, "%d", player_status.distros);
1102   context.draw_text(white_text, _("COINS"), Vector(screen->w/2 - 16*5, 0),
1103       LEFT_ALLIGN, LAYER_FOREGROUND1);
1104   context.draw_text(gold_text, str, Vector(screen->w/2 + (16*5)/2, 0),
1105         LEFT_ALLIGN, LAYER_FOREGROUND1);
1106
1107   if (player_status.lives >= 5)
1108     {
1109       sprintf(str, "%dx", player_status.lives);
1110       context.draw_text(gold_text, str, 
1111           Vector(screen->w - gold_text->get_text_width(str) - tux_life->w, 0),
1112           LEFT_ALLIGN, LAYER_FOREGROUND1);
1113       context.draw_surface(tux_life, Vector(screen->w -
1114             gold_text->get_text_width("9"), 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
1115     }
1116   else
1117     {
1118       for(int i= 0; i < player_status.lives; ++i)
1119         context.draw_surface(tux_life,
1120             Vector(screen->w - tux_life->w*4 + (tux_life->w*i), 0),
1121             LAYER_FOREGROUND1);
1122     }
1123   context.draw_text(white_text, _("LIVES"),
1124       Vector(screen->w - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 0),
1125       LEFT_ALLIGN, LAYER_FOREGROUND1);
1126
1127   if (!tux->is_moving())
1128     {
1129       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1130         {
1131           if (i->pos == tux->get_tile_pos())
1132             {
1133               if(i->title == "")
1134                 get_level_title(*i);
1135
1136               context.draw_text(white_text, i->title, 
1137                   Vector(screen->w/2,
1138                          screen->h - white_text->get_height() - 30),
1139                   CENTER_ALLIGN, LAYER_FOREGROUND1);
1140
1141               i->statistics.draw_worldmap_info(context);
1142               break;
1143             }
1144         }
1145       for(SpecialTiles::iterator i = special_tiles.begin(); i != special_tiles.end(); ++i)
1146         {
1147           if (i->pos == tux->get_tile_pos())
1148             {
1149                /* Display an in-map message in the map, if any as been selected */
1150               if(!i->map_message.empty() && !i->passive_message)
1151                 context.draw_text(gold_text, i->map_message, 
1152                     Vector(screen->w/2,
1153                            screen->h - white_text->get_height() - 60),
1154                     CENTER_ALLIGN, LAYER_FOREGROUND1);
1155               break;
1156             }
1157         }
1158     }
1159   /* Display a passive message in the map, if needed */
1160   if(passive_message_timer.check())
1161     context.draw_text(gold_text, passive_message, 
1162             Vector(screen->w/2, screen->h - white_text->get_height() - 60),
1163             CENTER_ALLIGN, LAYER_FOREGROUND1);
1164 }
1165
1166 void
1167 WorldMap::display()
1168 {
1169   Menu::set_current(0);
1170
1171   quit = false;
1172
1173   song = SoundManager::get()->load_music(datadir +  "/music/" + music);
1174   SoundManager::get()->play_music(song);
1175
1176   FrameRate frame_rate(10);
1177   frame_rate.set_frame_limit(false);
1178
1179   frame_rate.start();
1180
1181   DrawingContext context;
1182   while(!quit)
1183     {
1184       float delta = frame_rate.get();
1185
1186       delta *= 1.3f;
1187
1188       if (delta > 10.0f)
1189         delta = .3f;
1190         
1191       frame_rate.update();
1192
1193       Vector tux_pos = tux->get_pos();
1194       if (1)
1195         {
1196           offset.x = -tux_pos.x + screen->w/2;
1197           offset.y = -tux_pos.y + screen->h/2;
1198
1199           if (offset.x > 0) offset.x = 0;
1200           if (offset.y > 0) offset.y = 0;
1201
1202           if (offset.x < screen->w - width*32) offset.x = screen->w - width*32;
1203           if (offset.y < screen->h - height*32) offset.y = screen->h - height*32;
1204         } 
1205
1206       draw(context, offset);
1207       get_input();
1208       update(delta);
1209       
1210       if(Menu::current())
1211         {
1212           Menu::current()->draw(context);
1213           mouse_cursor->draw(context);
1214         }
1215
1216       context.do_drawing();
1217
1218       SDL_Delay(20);
1219     }
1220 }
1221
1222 void
1223 WorldMap::savegame(const std::string& filename)
1224 {
1225   if(filename == "")
1226     return;
1227
1228   std::cout << "savegame: " << filename << std::endl;
1229
1230    std::ofstream file(filename.c_str(), std::ios::out);
1231    LispWriter* writer = new LispWriter(file);
1232
1233   int nb_solved_levels = 0, total_levels = 0;
1234   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1235     {
1236       ++total_levels;
1237       if (i->solved)
1238         ++nb_solved_levels;
1239     }
1240   char nb_solved_levels_str[80], total_levels_str[80];
1241   sprintf(nb_solved_levels_str, "%d", nb_solved_levels);
1242   sprintf(total_levels_str, "%d", total_levels);
1243
1244   writer->write_comment("Worldmap save file");
1245
1246   writer->start_list("supertux-savegame");
1247
1248   writer->write_int("version", 1);
1249   writer->write_string("title", std::string(name + " - " + nb_solved_levels_str + "/" + total_levels_str));
1250   writer->write_string("map", map_filename);
1251   writer->write_int("lives", player_status.lives);
1252   writer->write_int("distros", player_status.lives);
1253   writer->write_int("max-score-multiplier", player_status.max_score_multiplier);
1254
1255   writer->start_list("tux");
1256
1257   writer->write_float("x", tux->get_tile_pos().x);
1258   writer->write_float("y", tux->get_tile_pos().y);
1259   writer->write_string("back", direction_to_string(tux->back_direction));
1260   writer->write_string("bonus", bonus_to_string(player_status.bonus));
1261
1262   writer->end_list("tux");
1263
1264   writer->start_list("levels");
1265
1266   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1267     {
1268       if (i->solved)
1269         {
1270         writer->start_list("level");
1271
1272         writer->write_string("name", i->name);
1273         writer->write_bool("solved", true);
1274         i->statistics.write(*writer);
1275
1276         writer->end_list("level");
1277         }
1278     }  
1279
1280   writer->end_list("levels");
1281
1282   writer->end_list("supertux-savegame");
1283 }
1284
1285 void
1286 WorldMap::loadgame(const std::string& filename)
1287 {
1288   std::cout << "loadgame: " << filename << std::endl;
1289   savegame_file = filename;
1290
1291   if (access(filename.c_str(), F_OK) != 0)
1292     {
1293     load_map();
1294
1295     player_status.reset();
1296
1297     return;
1298     }
1299   
1300   lisp_object_t* savegame = lisp_read_from_file(filename);
1301   if (!savegame)
1302     {
1303       std::cout << "WorldMap:loadgame: File not found: " << filename << std::endl;
1304       load_map();
1305       return;
1306     }
1307
1308   lisp_object_t* cur = savegame;
1309
1310   if (strcmp(lisp_symbol(lisp_car(cur)), "supertux-savegame") != 0)
1311     {
1312     load_map();
1313     return;
1314     }
1315
1316   cur = lisp_cdr(cur);
1317   LispReader reader(cur);
1318
1319   /* Get the Map filename and then load it before setting level settings */
1320   std::string cur_map_filename = map_filename;
1321   reader.read_string("map", map_filename);
1322 //  if(cur_map_filename != map_filename)
1323     load_map(); 
1324
1325   reader.read_int("lives", player_status.lives);
1326   reader.read_int("distros", player_status.distros);
1327   reader.read_int("max-score-multiplier", player_status.max_score_multiplier);
1328
1329   if (player_status.lives < 0)
1330     player_status.lives = START_LIVES;
1331
1332   lisp_object_t* tux_cur = 0;
1333   if (reader.read_lisp("tux", tux_cur))
1334     {
1335       Vector p;
1336       std::string back_str = "none";
1337       std::string bonus_str = "none";
1338
1339       LispReader tux_reader(tux_cur);
1340       tux_reader.read_float("x", p.x);
1341       tux_reader.read_float("y", p.y);
1342       tux_reader.read_string("back", back_str);
1343       tux_reader.read_string("bonus", bonus_str);
1344       
1345       player_status.bonus = string_to_bonus(bonus_str);
1346       tux->back_direction = string_to_direction(back_str);      
1347       tux->set_tile_pos(p);
1348     }
1349
1350   lisp_object_t* level_cur = 0;
1351   if (reader.read_lisp("levels", level_cur))
1352     {
1353       while(level_cur)
1354         {
1355           lisp_object_t* sym  = lisp_car(lisp_car(level_cur));
1356           lisp_object_t* data = lisp_cdr(lisp_car(level_cur));
1357
1358           if (strcmp(lisp_symbol(sym), "level") == 0)
1359             {
1360               std::string name;
1361               bool solved = false;
1362
1363               LispReader level_reader(data);
1364               level_reader.read_string("name", name);
1365               level_reader.read_bool("solved", solved);
1366
1367               for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
1368                 {
1369                   if (name == i->name)
1370                     {
1371                     i->solved = solved;
1372                     i->statistics.parse(level_reader);
1373                     break;
1374                     }
1375                 }
1376             }
1377
1378           level_cur = lisp_cdr(level_cur);
1379         }
1380     }
1381  
1382   lisp_free(savegame);
1383
1384   calculate_total_stats();
1385 }
1386
1387 void
1388 WorldMap::loadmap(const std::string& filename)
1389 {
1390   savegame_file = "";
1391   map_filename = filename;
1392   load_map();
1393 }
1394
1395 } // namespace WorldMapNS
1396
1397 /* Local Variables: */
1398 /* mode:c++ */
1399 /* End: */
1400