<MatzeB> my patch fixes another leak in the levelsubset code and cleans that up a...
[supertux.git] / src / level.cpp
1 //  $Id$
2 // 
3 //  SuperTux
4 //  Copyright (C) 2004 SuperTux Development Team, see AUTHORS for details
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
19 //  02111-1307, USA.
20
21 #include <map>
22 #include <stdlib.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <iostream>
26 #include "globals.h"
27 #include "setup.h"
28 #include "screen.h"
29 #include "level.h"
30 #include "physic.h"
31 #include "scene.h"
32 #include "tile.h"
33 #include "lispreader.h"
34 #include "resources.h"
35 #include "music_manager.h"
36
37 using namespace std;
38
39 LevelSubset::LevelSubset()
40     : image(0), levels(0)
41 {
42 }
43
44 LevelSubset::~LevelSubset()
45 {
46     delete image;
47 }
48
49 void LevelSubset::create(const std::string& subset_name)
50 {
51   Level new_lev;
52   LevelSubset new_subset;
53   new_subset.name = subset_name;
54   new_subset.title = "Unknown Title";
55   new_subset.description = "No description so far.";
56   new_subset.save();
57   new_lev.init_defaults();
58   new_lev.save(subset_name.c_str(),1);
59 }
60
61 void LevelSubset::parse (lisp_object_t* cursor)
62 {
63   while(!lisp_nil_p(cursor))
64     {
65       lisp_object_t* cur = lisp_car(cursor);
66       char *s;
67
68       if (!lisp_cons_p(cur) || !lisp_symbol_p (lisp_car(cur)))
69         {
70           printf("Not good");
71         }
72       else
73         {
74           if (strcmp(lisp_symbol(lisp_car(cur)), "title") == 0)
75             {
76               if(( s = lisp_string(lisp_car(lisp_cdr(cur)))) != NULL)
77                 {
78                   title = s;
79                 }
80             }
81           else if (strcmp(lisp_symbol(lisp_car(cur)), "description") == 0)
82             {
83               if(( s = lisp_string(lisp_car(lisp_cdr(cur)))) != NULL)
84                 {
85                   description = s;
86                 }
87             }
88         }
89       cursor = lisp_cdr (cursor);
90     }
91 }
92
93 void LevelSubset::load(char *subset)
94 {
95   FILE* fi;
96   char filename[1024];
97   char str[1024];
98   int i;
99   lisp_object_t* root_obj = 0;
100
101   name = subset;
102
103   snprintf(filename, 1024, "%s/levels/%s/info", st_dir, subset);
104   if(!faccessible(filename))
105     snprintf(filename, 1024, "%s/levels/%s/info", datadir.c_str(), subset);
106   if(faccessible(filename))
107     {
108       fi = fopen(filename, "r");
109       if (fi == NULL)
110         {
111           perror(filename);
112         }
113       lisp_stream_t stream;
114       lisp_stream_init_file (&stream, fi);
115       root_obj = lisp_read (&stream);
116
117       if (root_obj->type == LISP_TYPE_EOF || root_obj->type == LISP_TYPE_PARSE_ERROR)
118         {
119           printf("World: Parse Error in file %s", filename);
120         }
121
122       lisp_object_t* cur = lisp_car(root_obj);
123
124       if (!lisp_symbol_p (cur))
125         {
126           printf("World: Read error in %s",filename);
127         }
128
129       if (strcmp(lisp_symbol(cur), "supertux-level-subset") == 0)
130         {
131           parse(lisp_cdr(root_obj));
132
133         }
134
135       lisp_free(root_obj);
136       fclose(fi);
137
138       snprintf(str, 1024, "%s.png", filename);
139       if(faccessible(str))
140         {
141           image = new Surface(str,IGNORE_ALPHA);
142         }
143       else
144         {
145           snprintf(filename, 1024, "%s/images/status/level-subset-info.png", datadir.c_str());
146           image = new Surface(filename,IGNORE_ALPHA);
147         }
148     }
149
150   for(i=1; i != -1; ++i)
151     {
152       /* Get the number of levels in this subset */
153       snprintf(filename, 1024, "%s/levels/%s/level%d.stl", st_dir, subset,i);
154       if(!faccessible(filename))
155         {
156           snprintf(filename, 1024, "%s/levels/%s/level%d.stl", datadir.c_str(), subset,i);
157           if(!faccessible(filename))
158             break;
159         }
160     }
161   levels = --i;
162 }
163
164 void LevelSubset::save()
165 {
166   FILE* fi;
167   string filename;
168
169   /* Save data file: */
170   filename = "/levels/" + name + "/";
171
172   fcreatedir(filename.c_str());
173   filename = string(st_dir) + "/levels/" + name + "/info";
174   if(!fwriteable(filename.c_str()))
175     filename = datadir + "/levels/" + name + "/info";
176   if(fwriteable(filename.c_str()))
177     {
178       fi = fopen(filename.c_str(), "w");
179       if (fi == NULL)
180         {
181           perror(filename.c_str());
182         }
183
184       /* Write header: */
185       fprintf(fi,";SuperTux-Level-Subset\n");
186       fprintf(fi,"(supertux-level-subset\n");
187
188       /* Save title info: */
189       fprintf(fi,"  (title \"%s\")\n", title.c_str());
190
191       /* Save the description: */
192       fprintf(fi,"  (description \"%s\")\n", description.c_str());
193
194       fprintf( fi,")");
195       fclose(fi);
196
197     }
198 }
199
200 Level::Level()
201   : img_bkgd(0)
202 {
203   init_defaults();
204 }
205
206 Level::Level(const std::string& subset, int level)
207   : img_bkgd(0)
208 {
209   if(load(subset, level) < 0)
210     st_abort("Couldn't load level from subset", subset.c_str());
211 }
212
213 Level::Level(const std::string& filename)
214   : img_bkgd(0)
215 {
216   if(load(filename) < 0)
217     st_abort("Couldn't load level " , filename.c_str());
218 }
219
220 Level::~Level()
221 {
222   free_gfx();
223 }
224
225 void
226 Level::init_defaults()
227 {
228   name       = "UnNamed";
229   author     = "UnNamed";
230   theme      = "antarctica";
231   song_title = "Mortimers_chipdisko.mod";
232   bkgd_image = "arctis.png";
233   width      = 21;
234   start_pos_x = 100;
235   start_pos_y = 170;
236   time_left  = 100;
237   gravity    = 10.;
238   bkgd_top.red   = 0;
239   bkgd_top.green = 0;
240   bkgd_top.blue  = 0;
241   bkgd_bottom.red   = 255;
242   bkgd_bottom.green = 255;
243   bkgd_bottom.blue  = 255;
244
245   for(int i = 0; i < 15; ++i)
246     {
247       ia_tiles[i].resize(width+1, 0);
248       ia_tiles[i][width] = (unsigned int) '\0';
249
250       for(int y = 0; y < width; ++y)
251         ia_tiles[i][y] = 0;
252
253       bg_tiles[i].resize(width+1, 0);
254       bg_tiles[i][width] = (unsigned int) '\0';
255       for(int y = 0; y < width; ++y)
256         bg_tiles[i][y] = 0;
257
258       fg_tiles[i].resize(width+1, 0);
259       fg_tiles[i][width] = (unsigned int) '\0';
260       for(int y = 0; y < width; ++y)
261         fg_tiles[i][y] = 0;
262     }
263 }
264
265 int
266 Level::load(const std::string& subset, int level)
267 {
268   char filename[1024];
269
270   // Load data file:
271   snprintf(filename, 1024, "%s/levels/%s/level%d.stl", st_dir, subset.c_str(), level);
272   if(!faccessible(filename))
273     snprintf(filename, 1024, "%s/levels/%s/level%d.stl", datadir.c_str(), subset.c_str(), level);
274
275   return load(filename);
276 }
277
278 int 
279 Level::load(const std::string& filename)
280 {
281   lisp_object_t* root_obj = lisp_read_from_file(filename);
282   if (!root_obj)
283     {
284       std::cout << "Level: Couldn't load file: " << filename << std::endl;
285       return -1;
286     }
287
288   if (root_obj->type == LISP_TYPE_EOF || root_obj->type == LISP_TYPE_PARSE_ERROR)
289     {
290       printf("World: Parse Error in file %s", filename.c_str());
291       return -1;
292     }
293
294   vector<int> ia_tm;
295   vector<int> bg_tm;
296   vector<int> fg_tm;
297
298   int version = 0;
299   if (strcmp(lisp_symbol(lisp_car(root_obj)), "supertux-level") == 0)
300     {
301       LispReader reader(lisp_cdr(root_obj));
302       version = 0;
303       reader.read_int("version",  &version);
304       if(!reader.read_int("width",  &width))
305         st_abort("No width specified for level.", "");
306       if (!reader.read_int("start_pos_x", &start_pos_x)) start_pos_x = 100;
307       if (!reader.read_int("start_pos_y", &start_pos_y)) start_pos_y = 170;
308       time_left = 500;
309       if(!reader.read_int("time",  &time_left)) {
310         printf("Warning no time specified for level.\n");
311       }
312
313       bkgd_top.red = bkgd_top.green = bkgd_top.blue = 0;
314       reader.read_int("bkgd_red_top",  &bkgd_top.red);
315       reader.read_int("bkgd_green_top",  &bkgd_top.green);
316       reader.read_int("bkgd_blue_top",  &bkgd_top.blue);
317
318       bkgd_bottom.red = bkgd_bottom.green = bkgd_bottom.blue = 0;
319       reader.read_int("bkgd_red_bottom",  &bkgd_bottom.red);
320       reader.read_int("bkgd_green_bottom",  &bkgd_bottom.green);
321       reader.read_int("bkgd_blue_bottom",  &bkgd_bottom.blue);
322
323       gravity = 10;
324       reader.read_float("gravity",  &gravity);
325       name = "Noname";
326       reader.read_string("name",  &name);
327       author = "unknown author";
328       reader.read_string("author", &author);
329       if(!reader.read_string("theme",  &theme))
330         st_abort("No theme specified in level file", "");
331       song_title = "";
332       reader.read_string("music",  &song_title);
333       bkgd_image = "";
334       reader.read_string("background",  &bkgd_image);
335       particle_system = "";
336       reader.read_string("particle_system", &particle_system);
337
338       reader.read_int_vector("background-tm",  &bg_tm);
339
340       if (!reader.read_int_vector("interactive-tm", &ia_tm))
341         reader.read_int_vector("tilemap", &ia_tm);
342
343       reader.read_int_vector("foreground-tm",  &fg_tm);
344
345       { // Read ResetPoints
346         lisp_object_t* cur = 0;
347         if (reader.read_lisp("reset-points",  &cur))
348           {
349             while (!lisp_nil_p(cur))
350               {
351                 lisp_object_t* data = lisp_car(cur);
352
353                 ResetPoint pos;
354
355                 LispReader reader(lisp_cdr(data));
356                 if (reader.read_int("x", &pos.x)
357                     && reader.read_int("y", &pos.y))
358                   {
359                     reset_points.push_back(pos);
360                   }
361
362                 cur = lisp_cdr(cur);
363               }
364           }
365       }
366
367       { // Read BadGuys
368         lisp_object_t* cur = 0;
369         if (reader.read_lisp("objects",  &cur))
370           {
371             while (!lisp_nil_p(cur))
372               {
373                 lisp_object_t* data = lisp_car(cur);
374
375                 BadGuyData bg_data;
376                 bg_data.kind = badguykind_from_string(lisp_symbol(lisp_car(data)));
377                 LispReader reader(lisp_cdr(data));
378                 reader.read_int("x", &bg_data.x);
379                 reader.read_int("y", &bg_data.y);
380                 reader.read_bool("stay-on-platform", &bg_data.stay_on_platform);
381
382                 badguy_data.push_back(bg_data);
383
384                 cur = lisp_cdr(cur);
385               }
386           }
387       }
388
389       // Convert old levels to the new tile numbers
390       if (version == 0)
391         {
392           std::map<char, int> transtable;
393           transtable['.'] = 0;
394           transtable['x'] = 104;
395           transtable['X'] = 77;
396           transtable['y'] = 78;
397           transtable['Y'] = 105;
398           transtable['A'] = 83;
399           transtable['B'] = 102;
400           transtable['!'] = 103;
401           transtable['a'] = 84;
402           transtable['C'] = 85;
403           transtable['D'] = 86;
404           transtable['E'] = 87;
405           transtable['F'] = 88;
406           transtable['c'] = 89;
407           transtable['d'] = 90;
408           transtable['e'] = 91;
409           transtable['f'] = 92;
410
411           transtable['G'] = 93;
412           transtable['H'] = 94;
413           transtable['I'] = 95;
414           transtable['J'] = 96;
415
416           transtable['g'] = 97;
417           transtable['h'] = 98;
418           transtable['i'] = 99;
419           transtable['j'] = 100
420                             ;
421           transtable['#'] = 11;
422           transtable['['] = 13;
423           transtable['='] = 14;
424           transtable[']'] = 15;
425           transtable['$'] = 82;
426           transtable['^'] = 76;
427           transtable['*'] = 80;
428           transtable['|'] = 79;
429           transtable['\\'] = 81;
430           transtable['&'] = 75;
431
432           int x = 0;
433           int y = 0;
434           for(std::vector<int>::iterator i = ia_tm.begin(); i != ia_tm.end(); ++i)
435             {
436               if (*i == '0' || *i == '1' || *i == '2')
437                 {
438                   badguy_data.push_back(BadGuyData(static_cast<BadGuyKind>(*i-'0'),
439                                                    x*32, y*32, false));
440                   *i = 0;
441                 }
442               else
443                 {
444                   std::map<char, int>::iterator j = transtable.find(*i);
445                   if (j != transtable.end())
446                     *i = j->second;
447                   else
448                     printf("Error: conversion will fail, unsupported char: '%c' (%d)\n", *i, *i);
449                 }
450               ++x;
451               if (x >= width)
452                 {
453                   x = 0;
454                   ++y;
455                 }
456             }
457         }
458     }
459
460   for(int i = 0; i < 15; ++i)
461     {
462       ia_tiles[i].resize(width + 1, 0);
463       bg_tiles[i].resize(width + 1, 0);
464       fg_tiles[i].resize(width + 1, 0);
465     }
466
467   int i = 0;
468   int j = 0;
469   for(vector<int>::iterator it = ia_tm.begin(); it != ia_tm.end(); ++it, ++i)
470     {
471       ia_tiles[j][i] = (*it);
472       if(i == width - 1)
473         {
474           i = -1;
475           ++j;
476         }
477     }
478
479   i = j = 0;
480   for(vector<int>::iterator it = bg_tm.begin(); it != bg_tm.end(); ++it, ++i)
481     {
482
483       bg_tiles[j][i] = (*it);
484       if(i == width - 1)
485         {
486           i = -1;
487           ++j;
488         }
489     }
490
491   i = j = 0;
492   for(vector<int>::iterator it = fg_tm.begin(); it != fg_tm.end(); ++it, ++i)
493     {
494
495       fg_tiles[j][i] = (*it);
496       if(i == width - 1)
497         {
498           i = -1;
499           ++j;
500         }
501     }
502
503   lisp_free(root_obj);
504   return 0;
505 }
506
507 /* Save data for level: */
508
509 void 
510 Level::save(const  char * subset, int level)
511 {
512   char filename[1024];
513   char str[80];
514
515   /* Save data file: */
516   sprintf(str, "/levels/%s/", subset);
517   fcreatedir(str);
518   snprintf(filename, 1024, "%s/levels/%s/level%d.stl", st_dir, subset, level);
519   if(!fwriteable(filename))
520     snprintf(filename, 1024, "%s/levels/%s/level%d.stl", datadir.c_str(), subset, level);
521
522   FILE * fi = fopen(filename, "w");
523   if (fi == NULL)
524     {
525       perror(filename);
526       st_shutdown();
527       exit(-1);
528     }
529
530
531   /* Write header: */
532   fprintf(fi,";SuperTux-Level\n");
533   fprintf(fi,"(supertux-level\n");
534
535   fprintf(fi,"  (version %d)\n", 1);
536   fprintf(fi,"  (name \"%s\")\n", name.c_str());
537   fprintf(fi,"  (author \"%s\")\n", author.c_str());
538   fprintf(fi,"  (theme \"%s\")\n", theme.c_str());
539   fprintf(fi,"  (music \"%s\")\n", song_title.c_str());
540   fprintf(fi,"  (background \"%s\")\n", bkgd_image.c_str());
541   fprintf(fi,"  (particle_system \"%s\")\n", particle_system.c_str());
542   fprintf(fi,"  (bkgd_red_top %d)\n", bkgd_top.red);
543   fprintf(fi,"  (bkgd_green_top %d)\n", bkgd_top.green);
544   fprintf(fi,"  (bkgd_blue_top %d)\n", bkgd_top.blue);
545   fprintf(fi,"  (bkgd_red_bottom %d)\n", bkgd_bottom.red);
546   fprintf(fi,"  (bkgd_green_bottom %d)\n", bkgd_bottom.green);
547   fprintf(fi,"  (bkgd_blue_bottom %d)\n", bkgd_bottom.blue);
548   fprintf(fi,"  (time %d)\n", time_left);
549   fprintf(fi,"  (width %d)\n", width);
550   fprintf(fi,"  (gravity %2.1f)\n", gravity);
551   fprintf(fi,"  (background-tm ");
552
553   for(int y = 0; y < 15; ++y)
554     {
555       for(int i = 0; i < width; ++i)
556         fprintf(fi," %d ", bg_tiles[y][i]);
557     }
558
559   fprintf( fi,")\n");
560   fprintf(fi,"  (interactive-tm ");
561
562   for(int y = 0; y < 15; ++y)
563     {
564       for(int i = 0; i < width; ++i)
565         fprintf(fi," %d ", ia_tiles[y][i]);
566     }
567
568   fprintf( fi,")\n");
569   fprintf(fi,"  (foreground-tm ");
570
571   for(int y = 0; y < 15; ++y)
572     {
573       for(int i = 0; i < width; ++i)
574         fprintf(fi," %d ", fg_tiles[y][i]);
575     }
576
577   fprintf( fi,")\n");
578
579   fprintf( fi,"(reset-points\n");
580   for(std::vector<ResetPoint>::iterator i = reset_points.begin();
581       i != reset_points.end(); ++i)
582     fprintf( fi,"(point (x %d) (y %d))\n",i->x, i->y);
583   fprintf( fi,")\n");
584
585   fprintf( fi,"(objects\n");
586
587   for(std::vector<BadGuyData>::iterator it = badguy_data.begin();
588       it != badguy_data.end();
589       ++it)
590     fprintf( fi,"(%s (x %d) (y %d) (stay-on-platform %s))\n",
591              badguykind_to_string((*it).kind).c_str(),(*it).x,(*it).y,
592              it->stay_on_platform ? "#t" : "#f");
593
594   fprintf( fi,")\n");
595
596   fprintf( fi,")\n");
597
598   fclose(fi);
599 }
600
601
602 /* Unload data for this level: */
603
604 void
605 Level::cleanup()
606 {
607   for(int i=0; i < 15; ++i)
608     {
609       bg_tiles[i].clear();
610       ia_tiles[i].clear();
611       fg_tiles[i].clear();
612     }
613
614   reset_points.clear();
615   name.clear();
616   author.clear();
617   theme.clear();
618   song_title.clear();
619   bkgd_image.clear();
620
621   badguy_data.clear();
622 }
623
624 void 
625 Level::load_gfx()
626 {
627   if(!bkgd_image.empty())
628     {
629       char fname[1024];
630       snprintf(fname, 1024, "%s/background/%s", st_dir, bkgd_image.c_str());
631       if(!faccessible(fname))
632         snprintf(fname, 1024, "%s/images/background/%s", datadir.c_str(), bkgd_image.c_str());
633       img_bkgd = new Surface(fname, IGNORE_ALPHA);
634     }
635   else
636     {
637       img_bkgd = 0;
638     }
639 }
640
641 void
642 Level::free_gfx()
643 {
644   delete img_bkgd;
645 }
646
647 /* Load a level-specific graphic... */
648 void
649 Level::load_image(Surface** ptexture, string theme,const  char * file, int use_alpha)
650 {
651   char fname[1024];
652
653   snprintf(fname, 1024, "%s/themes/%s/%s", st_dir, theme.c_str(), file);
654   if(!faccessible(fname))
655     snprintf(fname, 1024, "%s/images/themes/%s/%s", datadir.c_str(), theme.c_str(), file);
656
657   *ptexture = new Surface(fname, use_alpha);
658 }
659
660 /* Change the size of a level (width) */
661 void 
662 Level::change_size (int new_width)
663 {
664   if(new_width < 21)
665     new_width = 21;
666
667   for(int y = 0; y < 15; ++y)
668     {
669       ia_tiles[y].resize(new_width, 0);
670       bg_tiles[y].resize(new_width, 0);
671       fg_tiles[y].resize(new_width, 0);
672     }
673
674   width = new_width;
675 }
676
677 void
678 Level::change(float x, float y, int tm, unsigned int c)
679 {
680   int yy = ((int)y / 32);
681   int xx = ((int)x / 32);
682
683   if (yy >= 0 && yy < 15 && xx >= 0 && xx <= width)
684     {
685       switch(tm)
686         {
687         case TM_BG:
688           bg_tiles[yy][xx] = c;
689           break;
690         case TM_IA:
691           ia_tiles[yy][xx] = c;
692           break;
693         case TM_FG:
694           fg_tiles[yy][xx] = c;
695           break;
696         }
697     }
698 }
699
700 void
701 Level::load_song()
702 {
703   char* song_path;
704   char* song_subtitle;
705
706   level_song = music_manager->load_music(datadir + "/music/" + song_title);
707
708   song_path = (char *) malloc(sizeof(char) * datadir.length() +
709                               strlen(song_title.c_str()) + 8 + 5);
710   song_subtitle = strdup(song_title.c_str());
711   strcpy(strstr(song_subtitle, "."), "\0");
712   sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(), 
713           song_subtitle, strstr(song_title.c_str(), "."));
714   if(!music_manager->exists_music(song_path)) {
715     level_song_fast = level_song;
716   } else {
717     level_song_fast = music_manager->load_music(song_path);
718   }
719   free(song_subtitle);
720   free(song_path);
721 }
722
723 MusicRef
724 Level::get_level_music()
725 {
726   return level_song;
727 }
728
729 MusicRef
730 Level::get_level_music_fast()
731 {
732   return level_song_fast;
733 }
734
735 unsigned int 
736 Level::gettileid(float x, float y)
737 {
738   int xx, yy;
739   unsigned int c;
740
741   yy = ((int)y / 32);
742   xx = ((int)x / 32);
743
744   if (yy >= 0 && yy < 15 && xx >= 0 && xx <= width)
745     c = ia_tiles[yy][xx];
746   else
747     c = 0;
748
749   return c;
750 }
751
752 /* EOF */