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