3877c007d61840c08d88e96d6d4d443350285f57
[supertux.git] / src / title.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2004 Tobias Glaesser <tobi.web@gmx.de>
5 //  Copyright (C) 2006 Matthias Braun <matze@braunis.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 <stdexcept>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <unistd.h>
31 #include <cmath>
32 #include <SDL.h>
33 #include <SDL_image.h>
34 #include <physfs.h>
35
36 #include "title.hpp"
37 #include "mainloop.hpp"
38 #include "video/drawing_context.hpp"
39 #include "video/surface.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "gui/menu.hpp"
42 #include "timer.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/parser.hpp"
45 #include "level.hpp"
46 #include "world.hpp"
47 #include "game_session.hpp"
48 #include "worldmap/worldmap.hpp"
49 #include "player_status.hpp"
50 #include "tile.hpp"
51 #include "sector.hpp"
52 #include "object/tilemap.hpp"
53 #include "object/camera.hpp"
54 #include "object/player.hpp"
55 #include "resources.hpp"
56 #include "gettext.hpp"
57 #include "textscroller.hpp"
58 #include "fadeout.hpp"
59 #include "file_system.hpp"
60 #include "control/joystickkeyboardcontroller.hpp"
61 #include "control/codecontroller.hpp"
62 #include "main.hpp"
63 #include "log.hpp"
64 #include "options_menu.hpp"
65 #include "console.hpp"
66 #include "random_generator.hpp"
67
68 enum MainMenuIDs {
69   MNID_STARTGAME,
70   MNID_LEVELS_CONTRIB,
71   MNID_OPTIONMENU,
72   MNID_LEVELEDITOR,
73   MNID_CREDITS,
74   MNID_QUITMAINMENU
75 };
76
77 void
78 TitleScreen::update_load_game_menu()
79 {
80   load_game_menu.reset(new Menu());
81
82   load_game_menu->add_label(_("Start Game"));
83   load_game_menu->add_hl();
84   for(int i = 1; i <= 5; ++i) {
85     load_game_menu->add_entry(i, get_slotinfo(i));
86   }
87   load_game_menu->add_hl();
88   load_game_menu->add_back(_("Back"));
89 }
90
91 void
92 TitleScreen::free_contrib_menu()
93 {
94   for(std::vector<World*>::iterator i = contrib_worlds.begin();
95       i != contrib_worlds.end(); ++i)
96     delete *i;
97
98   contrib_worlds.clear();
99 }
100
101 void
102 TitleScreen::generate_contrib_menu()
103 {
104   /** Generating contrib levels list by making use of Level Subset  */
105   std::vector<std::string> level_worlds;
106   char** files = PHYSFS_enumerateFiles("levels/");
107   for(const char* const* filename = files; *filename != 0; ++filename) {
108     std::string filepath = std::string("levels/") + *filename;
109     if(PHYSFS_isDirectory(filepath.c_str()))
110       level_worlds.push_back(filepath);
111   }
112   PHYSFS_freeList(files);
113
114   free_contrib_menu();
115   contrib_menu.reset(new Menu());
116
117   contrib_menu->add_label(_("Contrib Levels"));
118   contrib_menu->add_hl();
119
120   int i = 0;
121   for (std::vector<std::string>::iterator it = level_worlds.begin();
122       it != level_worlds.end(); ++it) {
123     try {
124       std::auto_ptr<World> world (new World());
125       world->load(*it + "/info");
126       if(world->hide_from_contribs) {
127         continue;
128       }
129       contrib_menu->add_entry(i++, world->title);
130       contrib_worlds.push_back(world.release());
131     } catch(std::exception& e) {
132 #ifdef DEBUG
133       log_warning << "Couldn't parse levelset info for '" << *it << "': " << e.what() << std::endl;
134 #endif
135     }
136   }
137
138   contrib_menu->add_hl();
139   contrib_menu->add_back(_("Back"));
140 }
141
142 std::string
143 TitleScreen::get_level_name(const std::string& filename)
144 {
145   try {
146     lisp::Parser parser;
147     std::auto_ptr<lisp::Lisp> root (parser.parse(filename));
148
149     const lisp::Lisp* level = root->get_lisp("supertux-level");
150     if(!level)
151       return "";
152
153     std::string name;
154     level->get("name", name);
155     return name;
156   } catch(std::exception& e) {
157     log_warning << "Problem getting name of '" << filename << "'." << std::endl;
158     return "";
159   }
160 }
161
162 void
163 TitleScreen::check_levels_contrib_menu()
164 {
165   int index = contrib_menu->check();
166   if (index == -1)
167     return;
168
169   current_world = contrib_worlds[index];
170
171   if(!current_world->is_levelset) {
172     update_load_game_menu();
173     Menu::push_current(load_game_menu.get());
174   } else {
175     contrib_world_menu.reset(new Menu());
176
177     contrib_world_menu->add_label(current_world->title);
178     contrib_world_menu->add_hl();
179
180     for (unsigned int i = 0; i < current_world->get_num_levels(); ++i)
181     {
182       /** get level's title */
183       std::string filename = current_world->get_level_filename(i);
184       std::string title = get_level_name(filename);
185       contrib_world_menu->add_entry(i, title);
186     }
187
188     contrib_world_menu->add_hl();
189     contrib_world_menu->add_back(_("Back"));
190
191     Menu::push_current(contrib_world_menu.get());
192   }
193 }
194
195 void
196 TitleScreen::check_contrib_world_menu()
197 {
198   int index = contrib_world_menu->check();
199   if (index != -1) {
200     if (contrib_world_menu->get_item_by_id(index).kind == MN_ACTION) {
201       sound_manager->stop_music();
202       GameSession* session =
203         new GameSession(current_world->get_level_filename(index));
204       main_loop->push_screen(session);
205     }
206   }
207 }
208
209 void
210 TitleScreen::make_tux_jump()
211 {
212   static Timer randomWaitTimer;
213   static Timer jumpPushTimer;
214   static float last_tux_x_pos = -1;
215   static float last_tux_y_pos = -1;
216
217   Sector* sector  = titlesession->get_current_sector();
218   Player* tux = sector->player;
219
220   //sector->play_music(LEVEL_MUSIC);
221
222   controller->update();
223   controller->press(Controller::RIGHT);
224
225   // Determine how far we moved since last frame
226   float dx = fabsf(last_tux_x_pos - tux->get_pos().x);
227   float dy = fabsf(last_tux_y_pos - tux->get_pos().y);
228
229   // Calculate space to check for obstacles
230   Rect lookahead = tux->get_bbox();
231   lookahead.move(Vector(96, 0));
232
233   // Check if we should press the jump button
234   bool randomJump = !randomWaitTimer.started();
235   bool notMoving = (fabsf(dx) + fabsf(dy)) < 0.1;
236   bool pathBlocked = !sector->is_free_of_statics(lookahead);
237   if (!controller->released(Controller::JUMP)
238       && (notMoving || pathBlocked || randomJump)) {
239     float jumpDuration;
240     if(pathBlocked)
241       jumpDuration = 0.5;
242     else
243       jumpDuration = systemRandom.randf(0.3, 0.8);
244     jumpPushTimer.start(jumpDuration);
245     randomWaitTimer.start(systemRandom.randf(3.0, 6.0));
246   }
247
248   // Keep jump button pressed
249   if (jumpPushTimer.started())
250     controller->press(Controller::JUMP);
251
252   // Remember last position, so we can determine if we moved
253   last_tux_x_pos = tux->get_pos().x;
254   last_tux_y_pos = tux->get_pos().y;
255
256   // Wrap around at the end of the level back to the beginnig
257   if(sector->get_width() - 320 < tux->get_pos().x) {
258     sector->activate("main");
259     sector->camera->reset(tux->get_pos());
260   }
261 }
262
263 TitleScreen::TitleScreen()
264 {
265   controller.reset(new CodeController());
266   titlesession.reset(new GameSession("levels/misc/menu.stl"));
267
268   Player* player = titlesession->get_current_sector()->player;
269   player->set_controller(controller.get());
270   player->set_speedlimit(230); //MAX_WALK_XM
271
272   main_menu.reset(new Menu());
273   main_menu->set_pos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2 + 35);
274   main_menu->add_entry(MNID_STARTGAME, _("Start Game"));
275   main_menu->add_entry(MNID_LEVELS_CONTRIB, _("Contrib Levels"));
276   main_menu->add_submenu(_("Options"), get_options_menu());
277   main_menu->add_entry(MNID_CREDITS, _("Credits"));
278   main_menu->add_entry(MNID_QUITMAINMENU, _("Quit"));
279 }
280
281 TitleScreen::~TitleScreen()
282 {
283 }
284
285 void
286 TitleScreen::setup()
287 {
288   player_status->reset();
289
290   Sector* sector = titlesession->get_current_sector();
291   if(Sector::current() != sector) {
292     sector->play_music(LEVEL_MUSIC);
293     sector->activate(sector->player->get_pos());
294   }
295
296   Menu::set_current(main_menu.get());
297 }
298
299 void
300 TitleScreen::leave()
301 {
302   Sector* sector = titlesession->get_current_sector();
303   sector->deactivate();
304   Menu::set_current(NULL);
305 }
306
307 void
308 TitleScreen::draw(DrawingContext& context)
309 {
310   Sector* sector  = titlesession->get_current_sector();
311   sector->draw(context);
312
313   context.draw_text(white_small_text, " SuperTux " PACKAGE_VERSION "\n",
314       Vector(0, SCREEN_HEIGHT - 50), LEFT_ALLIGN, LAYER_FOREGROUND1);
315   context.draw_text(white_small_text,
316       _(
317 "Copyright (c) 2006 SuperTux Devel Team\n"
318 "This game comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to\n"
319 "redistribute it under certain conditions; see the file COPYING for details.\n"
320 ),
321       Vector(0, SCREEN_HEIGHT - 50 + white_small_text->get_height() + 5),
322       LEFT_ALLIGN, LAYER_FOREGROUND1);
323 }
324
325 void
326 TitleScreen::update(float elapsed_time)
327 {
328   main_loop->set_speed(0.6);
329   Sector* sector  = titlesession->get_current_sector();
330   sector->update(elapsed_time);
331
332   make_tux_jump();
333
334   Menu* menu = Menu::current();
335   if(menu) {
336     menu->update();
337
338     if(menu == main_menu.get()) {
339       switch (main_menu->check()) {
340         case MNID_STARTGAME:
341           // Start Game, ie. goto the slots menu
342           if(main_world.get() == NULL) {
343             main_world.reset(new World());
344             main_world->load("levels/world1/info");
345           }
346           current_world = main_world.get();
347           update_load_game_menu();
348           Menu::push_current(load_game_menu.get());
349           break;
350         case MNID_LEVELS_CONTRIB:
351           // Contrib Menu
352           generate_contrib_menu();
353           Menu::push_current(contrib_menu.get());
354           break;
355         case MNID_CREDITS:
356           main_loop->push_screen(new TextScroller("credits.txt"),
357                                  new FadeOut(0.5));
358           break;
359         case MNID_QUITMAINMENU:
360           main_loop->quit(new FadeOut(0.25));
361           break;
362       }
363     } else if(menu == load_game_menu.get()) {
364       /*
365       if(event.key.keysym.sym == SDLK_DELETE) {
366         int slot = menu->get_active_item_id();
367         std::stringstream stream;
368         stream << slot;
369         std::string str = _("Are you sure you want to delete slot") + stream.str() + "?";
370
371         if(confirm_dialog(bkg_title, str.c_str())) {
372           str = "save/slot" + stream.str() + ".stsg";
373           log_debug << "Removing: " << str << std::endl;
374           PHYSFS_delete(str.c_str());
375         }
376
377         update_load_save_game_menu(load_game_menu);
378         Menu::set_current(main_menu.get());
379       }*/
380       process_load_game_menu();
381     } else if(menu == contrib_menu.get()) {
382       check_levels_contrib_menu();
383     } else if (menu == contrib_world_menu.get()) {
384       check_contrib_world_menu();
385     }
386   }
387
388   // reopen menu of user closed it (so that the app doesn't close when user
389   // accidently hit ESC)
390   if(Menu::current() == 0) {
391     Menu::set_current(main_menu.get());
392   }
393 }
394
395 std::string
396 TitleScreen::get_slotinfo(int slot)
397 {
398   std::string tmp;
399   std::string title;
400
401   std::string basename = current_world->get_basedir();
402   basename = basename.substr(0, basename.length()-1);
403   std::string worlddirname = FileSystem::basename(basename);
404   std::ostringstream stream;
405   stream << "save/" << worlddirname << "_" << slot << ".stsg";
406   std::string slotfile = stream.str();
407
408   try {
409     lisp::Parser parser;
410     std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
411
412     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
413     if(!savegame)
414       throw std::runtime_error("file is not a supertux-savegame.");
415
416     savegame->get("title", title);
417   } catch(std::exception& e) {
418     std::ostringstream slottitle;
419     slottitle << _("Slot") << " " << slot << " - " << _("Free");
420     return slottitle.str();
421   }
422
423   std::ostringstream slottitle;
424   slottitle << _("Slot") << " " << slot << " - " << title;
425   return slottitle.str();
426 }
427
428 bool
429 TitleScreen::process_load_game_menu()
430 {
431   int slot = load_game_menu->check();
432
433   if(slot == -1)
434     return false;
435
436   if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
437     return false;
438
439   std::string basename = current_world->get_basedir();
440   basename = basename.substr(0, basename.length()-1);
441   std::string worlddirname = FileSystem::basename(basename);
442   std::stringstream stream;
443   stream << "save/" << worlddirname << "_" << slot << ".stsg";
444   std::string slotfile = stream.str();
445
446   try {
447     current_world->set_savegame_filename(slotfile);
448     current_world->run();
449   } catch(std::exception& e) {
450     log_fatal << "Couldn't start world: " << e.what() << std::endl;
451   }
452
453   return true;
454 }