- memleak fix and menu fix from MatzeB
[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 <assert.h>
24 #include "globals.h"
25 #include "texture.h"
26 #include "screen.h"
27 #include "lispreader.h"
28 #include "gameloop.h"
29 #include "setup.h"
30 #include "worldmap.h"
31 #include "resources.h"
32
33 namespace WorldMapNS {
34
35 Direction reverse_dir(Direction direction)
36 {
37   switch(direction)
38     {
39     case WEST:
40       return EAST;
41     case EAST:
42       return WEST;
43     case NORTH:
44       return SOUTH;
45     case SOUTH:
46       return NORTH;
47     case NONE:
48       return NONE;
49     }
50   return NONE;
51 }
52
53 std::string
54 direction_to_string(Direction direction)
55 {
56   switch(direction)
57     {
58     case WEST:
59       return "west";
60     case EAST:
61       return "east";
62     case NORTH:
63       return "north";
64     case SOUTH:
65       return "south";
66     default:
67       return "none";
68     }
69 }
70
71 Direction
72 string_to_direction(const std::string& directory)
73 {
74   if (directory == "west")
75     return WEST;
76   else if (directory == "east")
77     return EAST;
78   else if (directory == "north")
79     return NORTH;
80   else if (directory == "south")
81     return SOUTH;
82   else
83     return NONE;
84 }
85
86 TileManager::TileManager()
87 {
88   std::string stwt_filename = datadir +  "images/worldmap/antarctica.stwt";
89   lisp_object_t* root_obj = lisp_read_from_file(stwt_filename);
90  
91   if (!root_obj)
92     st_abort("Couldn't load file", stwt_filename);
93
94   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap-tiles") == 0)
95     {
96       lisp_object_t* cur = lisp_cdr(root_obj);
97
98       while(!lisp_nil_p(cur))
99         {
100           lisp_object_t* element = lisp_car(cur);
101
102           if (strcmp(lisp_symbol(lisp_car(element)), "tile") == 0)
103             {
104               int id = 0;
105               std::string filename = "<invalid>";
106
107               Tile* tile = new Tile;             
108               tile->north = true;
109               tile->east  = true;
110               tile->south = true;
111               tile->west  = true;
112               tile->stop  = true;
113   
114               LispReader reader(lisp_cdr(element));
115               reader.read_int("id",  &id);
116               reader.read_bool("north", &tile->north);
117               reader.read_bool("south", &tile->south);
118               reader.read_bool("west",  &tile->west);
119               reader.read_bool("east",  &tile->east);
120               reader.read_bool("stop",  &tile->stop);
121               reader.read_string("image",  &filename);
122
123               tile->sprite = new Surface(
124                            datadir +  "/images/worldmap/" + filename, 
125                            USE_ALPHA);
126
127               if (id >= int(tiles.size()))
128                 tiles.resize(id+1);
129
130               tiles[id] = tile;
131             }
132           else
133             {
134               puts("Unhandled symbol");
135             }
136
137           cur = lisp_cdr(cur);
138         }
139     }
140   else
141     {
142       assert(0);
143     }
144
145   lisp_free(root_obj);
146 }
147
148 TileManager::~TileManager()
149 {
150   for(std::vector<Tile*>::iterator i = tiles.begin(); i != tiles.end(); ++i)
151     delete *i;
152 }
153
154 Tile*
155 TileManager::get(int i)
156 {
157   assert(i >=0 && i < int(tiles.size()));
158   return tiles[i];
159 }
160
161 //---------------------------------------------------------------------------
162
163 Tux::Tux(WorldMap* worldmap_)
164   : worldmap(worldmap_)
165 {
166   sprite = new Surface(datadir +  "/images/worldmap/tux.png", USE_ALPHA);
167   offset = 0;
168   moving = false;
169   tile_pos.x = 4;
170   tile_pos.y = 5;
171   direction = NONE;
172   input_direction = NONE;
173 }
174
175 Tux::~Tux()
176 {
177   delete sprite;
178 }
179
180 void
181 Tux::draw(const Point& offset)
182 {
183   Point pos = get_pos();
184   sprite->draw(pos.x + offset.x, 
185                pos.y + offset.y - 10);
186 }
187
188
189 Point
190 Tux::get_pos()
191 {
192   float x = tile_pos.x * 32;
193   float y = tile_pos.y * 32;
194
195   switch(direction)
196     {
197     case WEST:
198       x -= offset - 32;
199       break;
200     case EAST:
201       x += offset - 32;
202       break;
203     case NORTH:
204       y -= offset - 32;
205       break;
206     case SOUTH:
207       y += offset - 32;
208       break;
209     case NONE:
210       break;
211     }
212   
213   return Point((int)x, (int)y); 
214 }
215
216 void
217 Tux::stop()
218 {
219   offset = 0;
220   direction = NONE;
221   moving = false;
222 }
223
224 void
225 Tux::update(float delta)
226 {
227   if (!moving)
228     {
229       if (input_direction != NONE)
230         { 
231           WorldMap::Level* level = worldmap->at_level();
232
233           // We got a new direction, so lets start walking when possible
234           Point next_tile;
235           if ((!level || level->solved)
236               && worldmap->path_ok(input_direction, tile_pos, &next_tile))
237             {
238               tile_pos = next_tile;
239               moving = true;
240               direction = input_direction;
241               back_direction = reverse_dir(direction);
242             }
243           else if (input_direction == back_direction)
244             {
245               std::cout << "Back triggered" << std::endl;
246               moving = true;
247               direction = input_direction;
248               tile_pos = worldmap->get_next_tile(tile_pos, direction);
249               back_direction = reverse_dir(direction);
250             }
251         }
252     }
253   else
254     {
255       // Let tux walk a few pixels (20 pixel/sec)
256       offset += 20.0f * delta;
257
258       if (offset > 32)
259         { // We reached the next tile, so we check what to do now
260           offset -= 32;
261
262           if (worldmap->at(tile_pos)->stop || worldmap->at_level())
263             {
264               stop();
265             }
266           else
267             {
268               // Walk automatically to the next tile
269               Point next_tile;
270               if (worldmap->path_ok(direction, tile_pos, &next_tile))
271                 {
272                   tile_pos = next_tile;
273                 }
274               else
275                 {
276                   puts("Tilemap data is buggy");
277                   stop();
278                 }
279             }
280         }
281     }
282 }
283
284 //---------------------------------------------------------------------------
285 Tile::Tile()
286 {
287 }
288
289 Tile::~Tile()
290 {
291   delete sprite;
292 }
293
294 //---------------------------------------------------------------------------
295
296 WorldMap::WorldMap()
297 {
298   tile_manager = new TileManager();
299   tux = new Tux(this);
300
301   width  = 20;
302   height = 15;
303
304   level_sprite = new Surface(datadir +  "/images/worldmap/levelmarker.png", USE_ALPHA);
305   leveldot_green = new Surface(datadir +  "/images/worldmap/leveldot_green.png", USE_ALPHA);
306   leveldot_red = new Surface(datadir +  "/images/worldmap/leveldot_red.png", USE_ALPHA);
307
308   input_direction = NONE;
309   enter_level = false;
310
311   name = "<no file>";
312   music = "SALCON.MOD";
313
314   load_map();
315 }
316
317 WorldMap::~WorldMap()
318 {
319   delete tux;
320   delete tile_manager;
321
322   delete level_sprite;
323   delete leveldot_green;
324   delete leveldot_red;
325 }
326
327 void
328 WorldMap::load_map()
329 {
330   std::string filename = datadir +  "levels/default/worldmap.stwm";
331   
332   lisp_object_t* root_obj = lisp_read_from_file(filename);
333   if (!root_obj)
334     st_abort("Couldn't load file", filename);
335   
336   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-worldmap") == 0)
337     {
338       lisp_object_t* cur = lisp_cdr(root_obj);
339
340       while(!lisp_nil_p(cur))
341         {
342           lisp_object_t* element = lisp_car(cur);
343
344           if (strcmp(lisp_symbol(lisp_car(element)), "tilemap") == 0)
345             {
346               LispReader reader(lisp_cdr(element));
347               reader.read_int("width",  &width);
348               reader.read_int("height", &height);
349               reader.read_int_vector("data", &tilemap);
350             }
351           else if (strcmp(lisp_symbol(lisp_car(element)), "properties") == 0)
352             {
353               LispReader reader(lisp_cdr(element));
354               reader.read_string("name",  &name);
355               reader.read_string("music", &music);
356             }
357           else if (strcmp(lisp_symbol(lisp_car(element)), "levels") == 0)
358             {
359               lisp_object_t* cur = lisp_cdr(element);
360               
361               while(!lisp_nil_p(cur))
362                 {
363                   lisp_object_t* element = lisp_car(cur);
364                   
365                   if (strcmp(lisp_symbol(lisp_car(element)), "level") == 0)
366                     {
367                       Level level;
368                       LispReader reader(lisp_cdr(element));
369                       level.solved = false;
370                       
371                       level.north = true;
372                       level.east  = true;
373                       level.south = true;
374                       level.west  = true;
375
376                       reader.read_string("name",  &level.name);
377                       reader.read_int("x", &level.x);
378                       reader.read_int("y", &level.y);
379
380                       get_level_title(&level);   // get level's title
381
382                       levels.push_back(level);
383                     }
384                   
385                   cur = lisp_cdr(cur);      
386                 }
387             }
388           else
389             {
390               
391             }
392           
393           cur = lisp_cdr(cur);
394         }
395     }
396
397     lisp_free(root_obj);
398 }
399
400 void WorldMap::get_level_title(Levels::pointer level)
401 {
402   /** get level's title */
403   level->title = "<no title>";
404
405   FILE * fi;
406   lisp_object_t* root_obj = 0;
407   fi = fopen((datadir +  "levels/" + level->name).c_str(), "r");
408   if (fi == NULL)
409   {
410     perror((datadir +  "levels/" + level->name).c_str());
411     return;
412   }
413
414   lisp_stream_t stream;
415   lisp_stream_init_file (&stream, fi);
416   root_obj = lisp_read (&stream);
417
418   if (root_obj->type == LISP_TYPE_EOF || root_obj->type == LISP_TYPE_PARSE_ERROR)
419   {
420     printf("World: Parse Error in file %s", level->name.c_str());
421   }
422
423   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-level") == 0)
424   {
425     LispReader reader(lisp_cdr(root_obj));
426     reader.read_string("name",  &level->title);
427   }
428
429   lisp_free(root_obj);
430
431   fclose(fi);
432 }
433
434 void
435 WorldMap::on_escape_press()
436 {
437   // Show or hide the menu
438   if(!Menu::current())
439     Menu::set_current(worldmap_menu); 
440   else
441     Menu::set_current(0); 
442 }
443
444 void
445 WorldMap::get_input()
446 {
447   enter_level = false;
448   input_direction = NONE;
449    
450   SDL_Event event;
451   while (SDL_PollEvent(&event))
452     {
453       if (Menu::current())
454         {
455           Menu::current()->event(event);
456         }
457       else
458         {
459           switch(event.type)
460             {
461             case SDL_QUIT:
462               st_abort("Received window close", "");
463               break;
464           
465             case SDL_KEYDOWN:
466               switch(event.key.keysym.sym)
467                 {
468                 case SDLK_ESCAPE:
469                   on_escape_press();
470                   break;
471                 case SDLK_LCTRL:
472                 case SDLK_RETURN:
473                   enter_level = true;
474                   break;
475                 default:
476                   break;
477                 }
478               break;
479           
480             case SDL_JOYAXISMOTION:
481               if (event.jaxis.axis == joystick_keymap.x_axis)
482                 {
483                   if (event.jaxis.value < -joystick_keymap.dead_zone)
484                     input_direction = WEST;
485                   else if (event.jaxis.value > joystick_keymap.dead_zone)
486                     input_direction = EAST;
487                 }
488               else if (event.jaxis.axis == joystick_keymap.y_axis)
489                 {
490                   if (event.jaxis.value > joystick_keymap.dead_zone)
491                     input_direction = SOUTH;
492                   else if (event.jaxis.value < -joystick_keymap.dead_zone)
493                     input_direction = NORTH;
494                 }
495               break;
496
497             case SDL_JOYBUTTONDOWN:
498               if (event.jbutton.button == joystick_keymap.b_button)
499                 enter_level = true;
500               else if (event.jbutton.button == joystick_keymap.start_button)
501                 on_escape_press();
502               break;
503
504             default:
505               break;
506             }
507         }
508     }
509
510   if (!Menu::current())
511     {
512       Uint8 *keystate = SDL_GetKeyState(NULL);
513   
514       if (keystate[SDLK_LEFT])
515         input_direction = WEST;
516       else if (keystate[SDLK_RIGHT])
517         input_direction = EAST;
518       else if (keystate[SDLK_UP])
519         input_direction = NORTH;
520       else if (keystate[SDLK_DOWN])
521         input_direction = SOUTH;
522     }
523 }
524
525 Point
526 WorldMap::get_next_tile(Point pos, Direction direction)
527 {
528   switch(direction)
529     {
530     case WEST:
531       pos.x -= 1;
532       break;
533     case EAST:
534       pos.x += 1;
535       break;
536     case NORTH:
537       pos.y -= 1;
538       break;
539     case SOUTH:
540       pos.y += 1;
541       break;
542     case NONE:
543       break;
544     }
545   return pos;
546 }
547
548 bool
549 WorldMap::path_ok(Direction direction, Point old_pos, Point* new_pos)
550 {
551   *new_pos = get_next_tile(old_pos, direction);
552
553   if (!(new_pos->x >= 0 && new_pos->x < width
554         && new_pos->y >= 0 && new_pos->y < height))
555     { // New position is outsite the tilemap
556       return false;
557     }
558   else
559     { // Check if we the tile allows us to go to new_pos
560       switch(direction)
561         {
562         case WEST:
563           return (at(old_pos)->west && at(*new_pos)->east);
564
565         case EAST:
566           return (at(old_pos)->east && at(*new_pos)->west);
567
568         case NORTH:
569           return (at(old_pos)->north && at(*new_pos)->south);
570
571         case SOUTH:
572           return (at(old_pos)->south && at(*new_pos)->north);
573
574         case NONE:
575           assert(!"path_ok() can't work if direction is NONE");
576         }
577       return false;
578     }
579 }
580
581 void
582 WorldMap::update()
583 {
584   if (enter_level && !tux->is_moving())
585     {
586       Level* level = at_level();
587       if (level)
588         {
589           if (level->x == tux->get_tile_pos().x && 
590               level->y == tux->get_tile_pos().y)
591             {
592               std::cout << "Enter the current level: " << level->name << std::endl;;
593               GameSession session(datadir +  "levels/" + level->name,
594                                   1, ST_GL_LOAD_LEVEL_FILE);
595
596               switch (session.run())
597                 {
598                 case GameSession::LEVEL_FINISHED:
599                   level->solved = true;
600                   break;
601                 case GameSession::LEVEL_ABORT:
602                   // Reseting the player_status might be a worthy
603                   // consideration, but I don't think we need it
604                   // 'cause only the bad players will use it to
605                   // 'cheat' a few items and that isn't necesarry a
606                   // bad thing (ie. better they continue that way,
607                   // then stop playing the game all together since it
608                   // is to hard)
609                   break;
610                 case GameSession::GAME_OVER:
611                   quit = true;
612                   break;
613                 case GameSession::NONE:
614                   // Should never be reached 
615                   break;
616                 }
617
618               music_manager->play_music(song);
619               Menu::set_current(0);
620               if (!savegame_file.empty())
621                 savegame(savegame_file);
622               return;
623             }
624         }
625       else
626         {
627           std::cout << "Nothing to enter at: "
628                     << tux->get_tile_pos().x << ", " << tux->get_tile_pos().y << std::endl;
629         }
630     }
631   else
632     {
633       tux->set_direction(input_direction);
634       tux->update(0.33f);
635     }
636   
637   Menu* menu = Menu::current();
638   if(menu)
639     {
640       menu->action();
641
642       if(menu == worldmap_menu)
643         {
644           switch (worldmap_menu->check())
645             {
646             case MNID_RETURNWORLDMAP: // Return to game
647               break;
648             case MNID_SAVEGAME:
649               if (!savegame_file.empty())
650                 savegame(savegame_file);
651               break;
652                 
653             case MNID_QUITWORLDMAP: // Quit Worldmap
654               quit = true;
655               break;
656             }
657         }
658       else if(menu == options_menu)
659         {
660           process_options_menu();
661         }
662     }
663 }
664
665 Tile*
666 WorldMap::at(Point p)
667 {
668   assert(p.x >= 0 
669          && p.x < width
670          && p.y >= 0
671          && p.y < height);
672
673   return tile_manager->get(tilemap[width * p.y + p.x]);
674 }
675
676 WorldMap::Level*
677 WorldMap::at_level()
678 {
679   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
680     {
681       if (i->x == tux->get_tile_pos().x && 
682           i->y == tux->get_tile_pos().y)
683         return &*i; 
684     }
685
686   return 0;
687 }
688
689
690 void
691 WorldMap::draw(const Point& offset)
692 {
693   for(int y = 0; y < height; ++y)
694     for(int x = 0; x < width; ++x)
695       {
696         Tile* tile = at(Point(x, y));
697         tile->sprite->draw(x*32 + offset.x,
698                            y*32 + offset.y);
699       }
700   
701   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
702     {
703       if (i->solved)
704         leveldot_green->draw(i->x*32 + offset.x, 
705                              i->y*32 + offset.y);
706       else
707         leveldot_red->draw(i->x*32 + offset.x, 
708                            i->y*32 + offset.y);        
709     }
710
711   tux->draw(offset);
712   draw_status();
713 }
714
715 void
716 WorldMap::draw_status()
717 {
718   char str[80];
719   sprintf(str, "%d", player_status.score);
720   white_text->draw("SCORE", 0, 0);
721   gold_text->draw(str, 96, 0);
722
723   sprintf(str, "%d", player_status.distros);
724   white_text->draw_align("COINS", 320-64, 0,  A_LEFT, A_TOP);
725   gold_text->draw_align(str, 320+64, 0, A_RIGHT, A_TOP);
726
727   white_text->draw("LIVES", 480, 0);
728   if (player_status.lives >= 5)
729     {
730       sprintf(str, "%dx", player_status.lives);
731       gold_text->draw(str, 585, 0);
732       tux_life->draw(565+(18*3), 0);
733     }
734   else
735     {
736       for(int i= 0; i < player_status.lives; ++i)
737         tux_life->draw(565+(18*i),0);
738     }
739
740   if (!tux->is_moving())
741     {
742       for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
743         {
744           if (i->x == tux->get_tile_pos().x && 
745               i->y == tux->get_tile_pos().y)
746             {
747               white_text->draw_align(i->title.c_str(), screen->w/2, screen->h,  A_HMIDDLE, A_BOTTOM);
748               break;
749             }
750         }
751     }
752 }
753
754 void
755 WorldMap::display()
756 {
757   Menu::set_current(0);
758
759   quit = false;
760
761   song = music_manager->load_music(datadir +  "/music/" + music);
762   music_manager->play_music(song);
763
764   while(!quit) {
765     Point tux_pos = tux->get_pos();
766     if (1)
767       {
768         offset.x = -tux_pos.x + screen->w/2;
769         offset.y = -tux_pos.y + screen->h/2;
770
771         if (offset.x > 0) offset.x = 0;
772         if (offset.y > 0) offset.y = 0;
773
774         if (offset.x < screen->w - width*32) offset.x = screen->w - width*32;
775         if (offset.y < screen->h - height*32) offset.y = screen->h - height*32;
776       } 
777
778     draw(offset);
779     get_input();
780     update();
781
782   if(Menu::current())
783     {
784       Menu::current()->draw();
785       mouse_cursor->draw();
786     }
787     flipscreen();
788
789     SDL_Delay(20);
790   }
791 }
792
793 void
794 WorldMap::savegame(const std::string& filename)
795 {
796   std::cout << "savegame: " << filename << std::endl;
797   std::ofstream out(filename.c_str());
798
799   int nb_solved_levels = 0;
800   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
801     {
802       if (i->solved)
803         ++nb_solved_levels;
804     }
805
806   out << "(supertux-savegame\n"
807       << "  (version 1)\n"
808       << "  (title  \"Icyisland - " << nb_solved_levels << "/" << levels.size() << "\")\n"
809       << "  (lives   " << player_status.lives << ")\n"
810       << "  (score   " << player_status.score << ")\n"
811       << "  (distros " << player_status.distros << ")\n"
812       << "  (tux     (x " << tux->get_tile_pos().x << ") (y " << tux->get_tile_pos().y << ")"
813       << " (back \"" << direction_to_string(tux->back_direction) << "\"))\n"
814       << "  (levels\n";
815   
816   for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
817     {
818       if (i->solved)
819         {
820           out << "     (level (name \"" << i->name << "\")\n"
821               << "            (solved #t))\n";
822         }
823     }  
824
825   out << "   )\n"
826       << " )\n\n;; EOF ;;" << std::endl;
827 }
828
829 void
830 WorldMap::loadgame(const std::string& filename)
831 {
832   std::cout << "loadgame: " << filename << std::endl;
833   savegame_file = filename;
834
835   if (access(filename.c_str(), F_OK) != 0)
836     return;
837   
838   lisp_object_t* savegame = lisp_read_from_file(filename);
839   lisp_object_t* cur = savegame;
840
841   if (strcmp(lisp_symbol(lisp_car(cur)), "supertux-savegame") != 0)
842     return;
843
844   cur = lisp_cdr(cur);
845   LispReader reader(cur);
846
847   reader.read_int("lives",  &player_status.lives);
848   reader.read_int("score",  &player_status.score);
849   reader.read_int("distros", &player_status.distros);
850
851   if (player_status.lives < 0)
852     player_status.lives = START_LIVES;
853
854   lisp_object_t* tux_cur = 0;
855   if (reader.read_lisp("tux", &tux_cur))
856     {
857       Point p;
858       std::string back_str = "none";
859
860       LispReader tux_reader(tux_cur);
861       tux_reader.read_int("x", &p.x);
862       tux_reader.read_int("y", &p.y);
863       tux_reader.read_string("back", &back_str);
864       
865       tux->back_direction = string_to_direction(back_str);      
866       tux->set_tile_pos(p);
867     }
868
869   lisp_object_t* level_cur = 0;
870   if (reader.read_lisp("levels", &level_cur))
871     {
872       while(level_cur)
873         {
874           lisp_object_t* sym  = lisp_car(lisp_car(level_cur));
875           lisp_object_t* data = lisp_cdr(lisp_car(level_cur));
876
877           if (strcmp(lisp_symbol(sym), "level") == 0)
878             {
879               std::string name;
880               bool solved = false;
881
882               LispReader level_reader(data);
883               level_reader.read_string("name",   &name);
884               level_reader.read_bool("solved", &solved);
885
886               for(Levels::iterator i = levels.begin(); i != levels.end(); ++i)
887                 {
888                   if (name == i->name)
889                     i->solved = solved;
890                 }
891             }
892
893           level_cur = lisp_cdr(level_cur);
894         }
895     }
896  
897   lisp_free(savegame);
898 }
899
900 } // namespace WorldMapNS
901
902 /* Local Variables: */
903 /* mode:c++ */
904 /* End: */
905