move over rewritten lispreader from tuxkart (with additional fixes), generalized...
[supertux.git] / src / title.cpp
1 //  $Id$
2 // 
3 //  SuperTux
4 //  Copyright (C) 2000 Bill Kendrick <bill@newbreedsoftware.com>
5 //  Copyright (C) 2004 Tobias Glaesser <tobi.web@gmx.de>
6 //
7 //  This program is free software; you can redistribute it and/or
8 //  modify it under the terms of the GNU General Public License
9 //  as published by the Free Software Foundation; either version 2
10 //  of the License, or (at your option) any later version.
11 //
12 //  This program is distributed in the hope that it will be useful,
13 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
14 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 //  GNU General Public License for more details.
16 // 
17 //  You should have received a copy of the GNU General Public License
18 //  along with this program; if not, write to the Free Software
19 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 //  02111-1307, USA.
21 #include <config.h>
22
23 #include <iostream>
24 #include <sstream>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <cmath>
31 #include <SDL.h>
32 #include <SDL_image.h>
33
34 #ifndef WIN32
35 #include <sys/types.h>
36 #include <ctype.h>
37 #endif
38
39 #include "defines.h"
40 #include "app/globals.h"
41 #include "title.h"
42 #include "video/screen.h"
43 #include "video/surface.h"
44 #include "gui/menu.h"
45 #include "timer.h"
46 #include "special/frame_rate.h"
47 #include "app/setup.h"
48 #include "lisp/lisp.h"
49 #include "lisp/parser.h"
50 #include "level.h"
51 #include "level_subset.h"
52 #include "gameloop.h"
53 #include "worldmap.h"
54 #include "leveleditor.h"
55 #include "scene.h"
56 #include "tile.h"
57 #include "sector.h"
58 #include "object/tilemap.h"
59 #include "object/camera.h"
60 #include "object/player.h"
61 #include "resources.h"
62 #include "app/gettext.h"
63 #include "misc.h"
64
65 static Surface* bkg_title;
66 static Surface* logo;
67 static Surface* img_choose_subset;
68
69 static bool walking;
70 static Timer2 random_timer;
71
72 static int frame;
73
74 static GameSession* titlesession;
75
76 static std::vector<LevelSubset*> contrib_subsets;
77 static LevelSubset* current_contrib_subset = 0;
78 static int first_level_index;
79
80 static std::set<std::string> worldmap_list;
81
82 static FrameRate frame_rate(100);  
83
84 /* If the demo was stopped - because game started, level
85    editor was excuted, etc - call this when you get back
86    to the title code.
87  */
88 void resume_demo()
89 {
90   // FIXME: shouldn't be needed if GameSession
91   // didn't relay on global variables
92   titlesession->get_current_sector()->activate();
93   titlesession->set_current();
94
95   frame_rate.update();
96 }
97
98 void update_load_save_game_menu(Menu* pmenu)
99 {
100   for(int i = 2; i < 7; ++i)
101     {
102       // FIXME: Insert a real savegame struct/class here instead of
103       // doing string vodoo
104       std::string tmp = slotinfo(i - 1);
105       pmenu->item[i].kind = MN_ACTION;
106       pmenu->item[i].change_text(tmp.c_str());
107     }
108 }
109
110 void free_contrib_menu()
111 {
112   for(std::vector<LevelSubset*>::iterator i = contrib_subsets.begin();
113       i != contrib_subsets.end(); ++i)
114     delete *i;
115
116   contrib_subsets.clear();
117   contrib_menu->clear();
118 }
119
120 void generate_contrib_menu()
121 {
122   /** Generating contrib levels list by making use of Level Subset  */
123   std::set<std::string> level_subsets = FileSystem::dsubdirs("/levels", "info");
124
125   free_contrib_menu();
126
127   contrib_menu->additem(MN_LABEL,_("Contrib Levels"),0,0);
128   contrib_menu->additem(MN_HL,"",0,0);
129   int i = 0;
130
131   for(std::set<std::string>::iterator it = worldmap_list.begin();
132           it != worldmap_list.end(); ++it) {
133     WorldMapNS::WorldMap worldmap;
134     worldmap.loadmap((*it).c_str());
135     contrib_menu->additem(MN_ACTION, worldmap.get_world_title(),0,0, i);
136     ++i;
137   }
138
139   contrib_menu->additem(MN_HL,"",0,0);
140
141   first_level_index = i;
142   for (std::set<std::string>::iterator it = level_subsets.begin(); it != level_subsets.end(); ++it)
143     {
144       LevelSubset* subset = new LevelSubset();
145       subset->load(*it);
146       if(subset->hide_from_contribs)
147         {
148         delete subset;
149         continue;
150         }
151       contrib_menu->additem(MN_GOTO, subset->title, 0, contrib_subset_menu, i);
152       contrib_subsets.push_back(subset);
153       ++i;
154     }
155
156   contrib_menu->additem(MN_HL,"",0,0);
157   contrib_menu->additem(MN_BACK,_("Back"),0,0);
158
159   level_subsets.clear();
160 }
161
162 std::string get_level_name(const std::string& filename)
163 {
164   try {
165     lisp::Parser parser;
166     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
167
168     const lisp::Lisp* level = root->get_lisp("supertux-level");
169     if(!level)
170       return "";
171
172     std::string name;
173     level->get("name", name);
174     return name;
175   } catch(std::exception& e) {
176     std::cerr << "Problem getting name of '" << filename << "'.\n";
177     return "";
178   }
179 }
180
181 void check_levels_contrib_menu()
182 {
183   static int current_subset = -1;
184
185   int index = contrib_menu->check();
186   if (index == -1)
187     return;
188
189   if((unsigned)index < worldmap_list.size())
190     {
191     WorldMapNS::WorldMap worldmap;
192     std::set<std::string>::iterator it = worldmap_list.begin();
193     for(int i = index; i > 0; --i)
194     ++it;
195
196     std::string map_filename = *it;
197
198     // some fading
199     fadeout(256);
200     DrawingContext context;
201       context.draw_text(white_text, "Loading...",
202                         Vector(screen->w/2, screen->h/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
203       context.do_drawing();
204
205     worldmap.set_map_filename(map_filename);
206
207     // hack to erase the extension
208     unsigned int ext_pos = it->find_last_of(".");
209     if(ext_pos != std::string::npos)
210       map_filename.erase(ext_pos, map_filename.size() - ext_pos);
211
212     // TODO: slots should be available for contrib maps
213     worldmap.loadgame(st_save_dir + "/" + map_filename + "-slot1.stsg");
214
215     worldmap.display();  // run the map
216
217     Menu::set_current(main_menu);
218     resume_demo();
219     }
220   else if (index < (int)contrib_subsets.size() + first_level_index)
221     {
222     index -= first_level_index;
223     if (current_subset != index)
224       {
225       current_subset = index;
226       // FIXME: This shouln't be busy looping
227       LevelSubset& subset = * (contrib_subsets[index]);
228
229       current_contrib_subset = &subset;
230
231       contrib_subset_menu->clear();
232
233       contrib_subset_menu->additem(MN_LABEL, subset.title, 0,0);
234       contrib_subset_menu->additem(MN_HL,"",0,0);
235
236       for (int i = 0; i < subset.get_num_levels(); ++i)
237       {
238         /** get level's title */
239         std::string filename = subset.get_level_filename(i);
240         std::string title = get_level_name(filename);
241         contrib_subset_menu->additem(MN_ACTION, title, 0, 0, i);
242       }
243
244       contrib_subset_menu->additem(MN_HL,"",0,0);      
245       contrib_subset_menu->additem(MN_BACK, _("Back"), 0, 0);
246
247       titlesession->get_current_sector()->activate();
248       titlesession->set_current();
249       }
250     }
251 }
252
253 void check_contrib_subset_menu()
254 {
255   int index = contrib_subset_menu->check();
256   if (index != -1)
257     {
258       if (contrib_subset_menu->get_item_by_id(index).kind == MN_ACTION)
259         {
260           std::cout << "Starting level: " << index << std::endl;
261           
262           GameSession session(
263               current_contrib_subset->get_level_filename(index), ST_GL_PLAY);
264           session.run();
265           player_status.reset();
266           Menu::set_current(main_menu);
267           resume_demo();
268         }
269     }  
270 }
271
272 void draw_demo(float elapsed_time)
273 {
274   Sector* world  = titlesession->get_current_sector();
275   Player* tux = world->player;
276
277   world->play_music(LEVEL_MUSIC);
278   
279   tux->key_event((SDLKey) keymap.right,DOWN);
280   
281   if(random_timer.check()) {
282     random_timer.start(float(rand() % 3000 + 3000) / 1000.);
283     walking = !walking;
284   } else {
285       if(walking)
286         tux->key_event((SDLKey) keymap.jump,UP);
287       else
288         tux->key_event((SDLKey) keymap.jump,DOWN);
289   }
290
291   // Wrap around at the end of the level back to the beginnig
292   if(world->solids->get_width() * 32 - 320 < tux->get_pos().x)
293     {
294       tux->level_begin();
295       world->camera->reset(tux->get_pos());
296     }
297
298   tux->can_jump = true;
299   float last_tux_x_pos = tux->get_pos().x;
300   world->action(elapsed_time);
301   
302
303   // disabled for now, since with the new jump code we easily get deadlocks
304   // Jump if tux stays in the same position for one loop, ie. if he is
305   // stuck behind a wall
306   if (last_tux_x_pos == tux->get_pos().x)
307     {
308       walking = false;
309     }
310
311   world->draw(*titlesession->context);
312 }
313
314 /* --- TITLE SCREEN --- */
315 void title(void)
316 {
317   walking = true;
318   LevelEditor* leveleditor;
319
320   Ticks::pause_init();
321
322   titlesession = new GameSession(get_resource_filename("levels/misc/menu.stl"),
323       ST_GL_DEMO_GAME);
324
325   /* Load images: */
326   bkg_title = new Surface(datadir + "/images/background/arctis.jpg", false);
327   logo = new Surface(datadir + "/images/title/logo.png", true);
328   img_choose_subset = new Surface(datadir + "/images/status/choose-level-subset.png", true);
329
330   /* Generating contrib maps by only using a string_list */
331   worldmap_list = FileSystem::dfiles("levels/worldmap", "", "icyisland.stwm");
332
333   titlesession->get_current_sector()->activate();
334   titlesession->set_current();
335
336   /* --- Main title loop: --- */
337   frame = 0;
338
339   random_timer.start(float(rand() % 2000 + 2000) / 1000.0);
340
341   Uint32 lastticks = SDL_GetTicks();
342   
343   Menu::set_current(main_menu);
344   DrawingContext& context = *titlesession->context;
345   while (Menu::current())
346     {
347       // Calculate the movement-factor
348       Uint32 ticks = SDL_GetTicks();
349       float elapsed_time = float(ticks - lastticks) / 1000.;
350       global_time += elapsed_time;
351       lastticks = ticks;
352       // 40fps is minimum
353       if(elapsed_time > .04)
354         elapsed_time = .04;
355       
356       /* Lower the speed so that Tux doesn't jump too hectically throught
357          the demo. */
358       elapsed_time /= 2;
359
360       SDL_Event event;
361       while (SDL_PollEvent(&event))
362         {
363           if (Menu::current())
364             {
365               Menu::current()->event(event);
366             }
367          // FIXME: QUIT signal should be handled more generic, not locally
368           if (event.type == SDL_QUIT)
369             Menu::set_current(0);
370         }
371   
372       /* Draw the background: */
373       draw_demo(elapsed_time);
374       
375       
376       if (Menu::current() == main_menu)
377         context.draw_surface(logo, Vector(screen->w/2 - logo->w/2, 30),
378             LAYER_FOREGROUND1+1);
379
380       context.draw_text(white_small_text, " SuperTux " PACKAGE_VERSION "\n",
381               Vector(0, screen->h - 70), LEFT_ALLIGN, LAYER_FOREGROUND1);
382       context.draw_text(white_small_text,
383         _("Copyright (c) 2003 SuperTux Devel Team\n"
384           "This game comes with ABSOLUTELY NO WARRANTY. This is free software, and you\n"
385           "are welcome to redistribute it under certain conditions; see the file COPYING\n"
386           "for details.\n"), Vector(0, screen->h - 70 + white_small_text->get_height()), LEFT_ALLIGN, LAYER_FOREGROUND1);
387
388       /* Don't draw menu, if quit is true */
389       Menu* menu = Menu::current();
390       if(menu)
391         {
392           menu->draw(context);
393           menu->action();
394           
395           if(menu == main_menu)
396             {
397               switch (main_menu->check())
398                 {
399                 case MNID_STARTGAME:
400                   // Start Game, ie. goto the slots menu
401                   update_load_save_game_menu(load_game_menu);
402                   break;
403                 case MNID_LEVELS_CONTRIB:
404                   // Contrib Menu
405                   puts("Entering contrib menu");
406                   generate_contrib_menu();
407                   break;
408                 case MNID_LEVELEDITOR:
409                   leveleditor = new LevelEditor();
410                   leveleditor->run();
411                   delete leveleditor;
412                   Menu::set_current(main_menu);
413                   resume_demo();
414                   break;
415                 case MNID_CREDITS:
416                   fadeout(500);
417                   display_text_file("credits.txt", SCROLL_SPEED_CREDITS, white_big_text , white_text, white_small_text, blue_text );
418                   fadeout(500);
419                   Menu::set_current(main_menu);
420                   break;
421                 case MNID_QUITMAINMENU:
422                   Menu::set_current(0);
423                   break;
424                 }
425             }
426           else if(menu == options_menu)
427             {
428               process_options_menu();
429             }
430           else if(menu == load_game_menu)
431             {
432               if(event.key.keysym.sym == SDLK_DELETE)
433                 {
434                 int slot = menu->get_active_item_id();
435                 std::stringstream stream;
436                 stream << slot;
437                 std::string str = _("Are you sure you want to delete slot") + stream.str() + "?";
438                 
439                 if(confirm_dialog(bkg_title, str.c_str()))
440                   {
441                   str = st_save_dir + "/slot" + stream.str() + ".stsg";
442                   printf("Removing: %s\n",str.c_str());
443                   remove(str.c_str());
444                   }
445
446                 update_load_save_game_menu(load_game_menu);
447                 Menu::set_current(main_menu);
448                 resume_demo();
449                 }
450               else if (process_load_game_menu())
451                 {
452                   resume_demo();
453                 }
454             }
455           else if(menu == contrib_menu)
456             {
457               check_levels_contrib_menu();
458             }
459           else if (menu == contrib_subset_menu)
460             {
461               check_contrib_subset_menu();
462             }
463         }
464
465       mouse_cursor->draw(context);
466      
467       context.do_drawing();
468
469       frame_rate.update();
470
471       /* Pause: */
472       frame++;
473     }
474   /* Free surfaces: */
475
476   free_contrib_menu();
477   worldmap_list.clear();
478   delete titlesession;
479   delete bkg_title;
480   delete logo;
481   delete img_choose_subset;
482 }
483