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