Some selfmade noise.
[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 <math.h>
30 #include <errno.h>
31 #include <unistd.h>
32 #include <SDL.h>
33 #include <SDL_image.h>
34 #include <physfs.h>
35 #include <algorithm>
36
37 #include "title.hpp"
38 #include "mainloop.hpp"
39 #include "video/drawing_context.hpp"
40 #include "video/surface.hpp"
41 #include "audio/sound_manager.hpp"
42 #include "gui/menu.hpp"
43 #include "timer.hpp"
44 #include "lisp/lisp.hpp"
45 #include "lisp/parser.hpp"
46 #include "level.hpp"
47 #include "world.hpp"
48 #include "game_session.hpp"
49 #include "worldmap/worldmap.hpp"
50 #include "player_status.hpp"
51 #include "tile.hpp"
52 #include "sector.hpp"
53 #include "object/tilemap.hpp"
54 #include "object/camera.hpp"
55 #include "object/player.hpp"
56 #include "resources.hpp"
57 #include "gettext.hpp"
58 #include "textscroller.hpp"
59 #include "fadeout.hpp"
60 #include "file_system.hpp"
61 #include "control/joystickkeyboardcontroller.hpp"
62 #include "control/codecontroller.hpp"
63 #include "main.hpp"
64 #include "log.hpp"
65 #include "options_menu.hpp"
66 #include "console.hpp"
67 #include "random_generator.hpp"
68 #include "addon_manager.hpp"
69
70 enum MainMenuIDs {
71   MNID_STARTGAME,
72   MNID_LEVELS_CONTRIB,
73   MNID_ADDONS,
74   MNID_OPTIONMENU,
75   MNID_LEVELEDITOR,
76   MNID_CREDITS,
77   MNID_QUITMAINMENU
78 };
79
80 void
81 TitleScreen::update_load_game_menu()
82 {
83   load_game_menu.reset(new Menu());
84
85   load_game_menu->add_label(_("Start Game"));
86   load_game_menu->add_hl();
87   for(int i = 1; i <= 5; ++i) {
88     load_game_menu->add_entry(i, get_slotinfo(i));
89   }
90   load_game_menu->add_hl();
91   load_game_menu->add_back(_("Back"));
92 }
93
94 void
95 TitleScreen::free_contrib_menu()
96 {
97   for(std::vector<World*>::iterator i = contrib_worlds.begin();
98       i != contrib_worlds.end(); ++i)
99     delete *i;
100
101   contrib_worlds.clear();
102 }
103
104 void
105 TitleScreen::generate_contrib_menu()
106 {
107   /** Generating contrib levels list by making use of Level Subset  */
108   std::vector<std::string> level_worlds;
109   char** files = PHYSFS_enumerateFiles("levels/");
110   for(const char* const* filename = files; *filename != 0; ++filename) {
111     std::string filepath = std::string("levels/") + *filename;
112     if(PHYSFS_isDirectory(filepath.c_str()))
113       level_worlds.push_back(filepath);
114   }
115   PHYSFS_freeList(files);
116
117   free_contrib_menu();
118   contrib_menu.reset(new Menu());
119
120   contrib_menu->add_label(_("Contrib Levels"));
121   contrib_menu->add_hl();
122
123   int i = 0;
124   for (std::vector<std::string>::iterator it = level_worlds.begin();
125       it != level_worlds.end(); ++it) {
126     try {
127       std::auto_ptr<World> world (new World());
128       world->load(*it + "/info");
129       if(world->hide_from_contribs) {
130         continue;
131       }
132       contrib_menu->add_entry(i++, world->title);
133       contrib_worlds.push_back(world.release());
134     } catch(std::exception& e) {
135 #ifdef DEBUG
136       log_warning << "Couldn't parse levelset info for '" << *it << "': " << e.what() << std::endl;
137 #endif
138     }
139   }
140
141   contrib_menu->add_hl();
142   contrib_menu->add_back(_("Back"));
143 }
144
145 std::string
146 TitleScreen::get_level_name(const std::string& filename)
147 {
148   try {
149     lisp::Parser parser;
150     const lisp::Lisp* root = parser.parse(filename);
151
152     const lisp::Lisp* level = root->get_lisp("supertux-level");
153     if(!level)
154       return "";
155
156     std::string name;
157     level->get("name", name);
158     return name;
159   } catch(std::exception& e) {
160           log_warning << "Problem getting name of '" << filename << "': "
161                   << e.what() << std::endl;
162     return "";
163   }
164 }
165
166 void
167 TitleScreen::check_levels_contrib_menu()
168 {
169   int index = contrib_menu->check();
170   if (index == -1)
171     return;
172
173   current_world = contrib_worlds[index];
174
175   if(!current_world->is_levelset) {
176     update_load_game_menu();
177     Menu::push_current(load_game_menu.get());
178   } else {
179     contrib_world_menu.reset(new Menu());
180
181     contrib_world_menu->add_label(current_world->title);
182     contrib_world_menu->add_hl();
183
184     for (unsigned int i = 0; i < current_world->get_num_levels(); ++i)
185     {
186       /** get level's title */
187       std::string filename = current_world->get_level_filename(i);
188       std::string title = get_level_name(filename);
189       contrib_world_menu->add_entry(i, title);
190     }
191
192     contrib_world_menu->add_hl();
193     contrib_world_menu->add_back(_("Back"));
194
195     Menu::push_current(contrib_world_menu.get());
196   }
197 }
198
199 void
200 TitleScreen::check_contrib_world_menu()
201 {
202   int index = contrib_world_menu->check();
203   if (index != -1) {
204     if (contrib_world_menu->get_item_by_id(index).kind == MN_ACTION) {
205       sound_manager->stop_music();
206       GameSession* session =
207         new GameSession(current_world->get_level_filename(index));
208       main_loop->push_screen(session);
209     }
210   }
211 }
212
213 namespace {
214   bool generate_addons_menu_sorter(const Addon& a1, const Addon& a2)
215   {
216     return a1.title < a2.title;
217   }
218
219   const int ADDON_LIST_START_ID = 10;
220 }
221
222 void
223 TitleScreen::generate_addons_menu()
224 {
225   AddonManager& adm = AddonManager::get_instance();
226
227   // refresh list of installed addons
228   installed_addons = adm.get_installed_addons();
229   
230   // build new Add-on list
231   addons.clear();
232
233   // add installed addons to list
234   addons.insert(addons.end(), installed_addons.begin(), installed_addons.end());
235
236   // add available addons to list
237   addons.insert(addons.end(), available_addons.begin(), available_addons.end());
238
239   // sort list
240   std::sort(addons.begin(), addons.end(), generate_addons_menu_sorter);
241
242   // remove available addons that are already installed
243   std::vector<Addon>::iterator it2 = addons.begin();
244   while (it2 != addons.end()) {
245     Addon addon = *it2;
246     if (addon.isInstalled) {
247       bool restart = false;
248       for (std::vector<Addon>::iterator it = addons.begin(); it != addons.end(); ++it) {
249         Addon addon2 = *it;
250         if ((addon2.equals(addon)) && (!addon2.isInstalled)) {
251           addons.erase(it);
252           restart = true;
253           break;
254         }
255       }
256       if (restart) {
257         it2 = addons.begin();
258         continue;
259       }
260     }
261     it2++;
262   }
263
264   // (re)generate menu
265   free_addons_menu();
266   addons_menu.reset(new Menu());
267
268   addons_menu->add_label(_("Add-ons"));
269   addons_menu->add_hl();
270   
271 #ifdef HAVE_LIBCURL
272   addons_menu->add_entry(0, std::string(_("Check Online")));
273 #else
274   addons_menu->add_deactive(0, std::string(_("Check Online (disabled)")));
275 #endif
276
277   //addons_menu->add_hl();
278
279   for (unsigned int i = 0; i < addons.size(); i++) {
280     Addon addon = addons[i];
281     std::string text = "";
282     if (addon.kind != "") text += addon.kind + " ";
283     text += std::string("\"") + addon.title + "\"";
284     if (addon.author != "") text += " by \"" + addon.author + "\"";
285     addons_menu->add_toggle(ADDON_LIST_START_ID + i, text, addon.isInstalled);
286   }
287
288   addons_menu->add_hl();
289   addons_menu->add_back(_("Back"));
290 }
291
292 void
293 TitleScreen::check_addons_menu()
294 {
295   int index = addons_menu->check();
296   if (index == -1) return;
297
298   // check if "Check Online" was chosen
299   if (index == 0) {
300     try {
301       available_addons = AddonManager::get_instance().get_available_addons();
302       generate_addons_menu();
303       Menu::set_current(addons_menu.get());
304       addons_menu->set_active_item(index);
305     } 
306     catch (std::runtime_error e) {
307       log_warning << "Check for available Add-ons failed: " << e.what() << std::endl;
308     }
309     return;
310   }
311
312   // if one of the Addons listed was chosen, take appropriate action
313   if ((index >= ADDON_LIST_START_ID) && (index < ADDON_LIST_START_ID) + addons.size()) {
314     Addon addon = addons[index - ADDON_LIST_START_ID];
315     if (!addon.isInstalled) {
316       try {
317         addon.install();
318         //generate_addons_menu();
319         //Menu::set_current(addons_menu.get());
320         //addons_menu->set_active_item(index);
321         Menu::set_current(0);
322       } 
323       catch (std::runtime_error e) {
324         log_warning << "Installation of Add-on failed: " << e.what() << std::endl;
325       }
326     } else {
327       try {
328         addon.remove();
329         //generate_addons_menu();
330         //Menu::set_current(addons_menu.get());
331         //addons_menu->set_active_item(index);
332         Menu::set_current(0);
333       } 
334       catch (std::runtime_error e) {
335         log_warning << "Removal of Add-on failed: " << e.what() << std::endl;
336       }
337     }
338   }
339
340 }
341
342 void
343 TitleScreen::free_addons_menu()
344 {
345 }
346
347 void
348 TitleScreen::make_tux_jump()
349 {
350   static bool jumpWasReleased = true;
351   Sector* sector  = titlesession->get_current_sector();
352   Player* tux = sector->player;
353
354   controller->update();
355   controller->press(Controller::RIGHT);
356
357   // Check if we should press the jump button
358   Rect lookahead = tux->get_bbox();
359   lookahead.p2.x += 96;
360   bool pathBlocked = !sector->is_free_of_statics(lookahead);
361   if ((pathBlocked && jumpWasReleased) || !tux->on_ground()) {
362     controller->press(Controller::JUMP);
363     jumpWasReleased = false;
364   } else {
365     jumpWasReleased = true;
366   }
367
368   // Wrap around at the end of the level back to the beginnig
369   if(sector->get_width() - 320 < tux->get_pos().x) {
370     sector->activate("main");
371     sector->camera->reset(tux->get_pos());
372   }
373 }
374
375 TitleScreen::TitleScreen()
376 {
377   controller.reset(new CodeController());
378   titlesession.reset(new GameSession("levels/misc/menu.stl"));
379
380   Player* player = titlesession->get_current_sector()->player;
381   player->set_controller(controller.get());
382   player->set_speedlimit(230); //MAX_WALK_XM
383
384   generate_main_menu();
385 }
386
387 void
388 TitleScreen::generate_main_menu()
389 {
390   main_menu.reset(new Menu());
391   main_menu->set_pos(SCREEN_WIDTH/2, SCREEN_HEIGHT/2 + 35);
392   main_menu->add_entry(MNID_STARTGAME, _("Start Game"));
393   main_menu->add_entry(MNID_LEVELS_CONTRIB, _("Contrib Levels"));
394   main_menu->add_entry(MNID_ADDONS, _("Add-ons"));
395   main_menu->add_submenu(_("Options"), get_options_menu());
396   main_menu->add_entry(MNID_CREDITS, _("Credits"));
397   main_menu->add_entry(MNID_QUITMAINMENU, _("Quit"));
398 }
399
400 TitleScreen::~TitleScreen()
401 {
402 }
403
404 void
405 TitleScreen::setup()
406 {
407   player_status->reset();
408
409   Sector* sector = titlesession->get_current_sector();
410   if(Sector::current() != sector) {
411     sector->play_music(LEVEL_MUSIC);
412     sector->activate(sector->player->get_pos());
413   }
414
415   Menu::set_current(main_menu.get());
416 }
417
418 void
419 TitleScreen::leave()
420 {
421   Sector* sector = titlesession->get_current_sector();
422   sector->deactivate();
423   Menu::set_current(NULL);
424 }
425
426 void
427 TitleScreen::draw(DrawingContext& context)
428 {
429   Sector* sector  = titlesession->get_current_sector();
430   sector->draw(context);
431
432   context.draw_text(white_small_text, "SuperTux " PACKAGE_VERSION "\n",
433       Vector(5, SCREEN_HEIGHT - 50), ALIGN_LEFT, LAYER_FOREGROUND1);
434   context.draw_text(white_small_text,
435       _(
436 "Copyright (c) 2007 SuperTux Devel Team\n"
437 "This game comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to\n"
438 "redistribute it under certain conditions; see the file COPYING for details.\n"
439 ),
440       Vector(5, SCREEN_HEIGHT - 50 + white_small_text->get_height() + 5),
441       ALIGN_LEFT, LAYER_FOREGROUND1);
442 }
443
444 void
445 TitleScreen::update(float elapsed_time)
446 {
447   main_loop->set_speed(0.6f);
448   Sector* sector  = titlesession->get_current_sector();
449   sector->update(elapsed_time);
450
451   make_tux_jump();
452
453   Menu* menu = Menu::current();
454   if(menu) {
455     menu->update();
456
457     if(menu == main_menu.get()) {
458       switch (main_menu->check()) {
459         case MNID_STARTGAME:
460           // Start Game, ie. goto the slots menu
461           if(main_world.get() == NULL) {
462             main_world.reset(new World());
463             main_world->load("levels/world1/info");
464           }
465           current_world = main_world.get();
466           update_load_game_menu();
467           Menu::push_current(load_game_menu.get());
468           break;
469         case MNID_LEVELS_CONTRIB:
470           // Contrib Menu
471           generate_contrib_menu();
472           Menu::push_current(contrib_menu.get());
473           break;
474         case MNID_ADDONS:
475           // Add-ons Menu
476           generate_addons_menu();
477           Menu::push_current(addons_menu.get());
478           break;
479         case MNID_CREDITS:
480           main_loop->push_screen(new TextScroller("credits.txt"),
481                                  new FadeOut(0.5));
482           break;
483         case MNID_QUITMAINMENU:
484           main_loop->quit(new FadeOut(0.25));
485                   sound_manager->stop_music(0.25);
486           break;
487       }
488     } else if(menu == load_game_menu.get()) {
489       /*
490       if(event.key.keysym.sym == SDLK_DELETE) {
491         int slot = menu->get_active_item_id();
492         std::stringstream stream;
493         stream << slot;
494         std::string str = _("Are you sure you want to delete slot") + stream.str() + "?";
495
496         if(confirm_dialog(bkg_title, str.c_str())) {
497           str = "save/slot" + stream.str() + ".stsg";
498           log_debug << "Removing: " << str << std::endl;
499           PHYSFS_delete(str.c_str());
500         }
501
502         update_load_save_game_menu(load_game_menu);
503         Menu::set_current(main_menu.get());
504       }*/
505       process_load_game_menu();
506     } else if(menu == contrib_menu.get()) {
507       check_levels_contrib_menu();
508     } else if(menu == addons_menu.get()) {
509       check_addons_menu();
510     } else if (menu == contrib_world_menu.get()) {
511       check_contrib_world_menu();
512     }
513   }
514
515   // reopen menu of user closed it (so that the app doesn't close when user
516   // accidently hit ESC)
517   if(Menu::current() == 0) {
518     generate_main_menu();
519     Menu::set_current(main_menu.get());
520   }
521 }
522
523 std::string
524 TitleScreen::get_slotinfo(int slot)
525 {
526   std::string tmp;
527   std::string title;
528
529   std::string basename = current_world->get_basedir();
530   basename = basename.substr(0, basename.length()-1);
531   std::string worlddirname = FileSystem::basename(basename);
532   std::ostringstream stream;
533   stream << "save/" << worlddirname << "_" << slot << ".stsg";
534   std::string slotfile = stream.str();
535
536   try {
537     lisp::Parser parser;
538     const lisp::Lisp* root = parser.parse(slotfile);
539
540     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
541     if(!savegame)
542       throw std::runtime_error("file is not a supertux-savegame.");
543
544     savegame->get("title", title);
545   } catch(std::exception& ) {
546     std::ostringstream slottitle;
547     slottitle << _("Slot") << " " << slot << " - " << _("Free");
548     return slottitle.str();
549   }
550
551   std::ostringstream slottitle;
552   slottitle << _("Slot") << " " << slot << " - " << title;
553   return slottitle.str();
554 }
555
556 bool
557 TitleScreen::process_load_game_menu()
558 {
559   int slot = load_game_menu->check();
560
561   if(slot == -1)
562     return false;
563
564   if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
565     return false;
566
567   std::string basename = current_world->get_basedir();
568   basename = basename.substr(0, basename.length()-1);
569   std::string worlddirname = FileSystem::basename(basename);
570   std::stringstream stream;
571   stream << "save/" << worlddirname << "_" << slot << ".stsg";
572   std::string slotfile = stream.str();
573
574   try {
575     current_world->set_savegame_filename(slotfile);
576     current_world->run();
577   } catch(std::exception& e) {
578     log_fatal << "Couldn't start world: " << e.what() << std::endl;
579   }
580
581   return true;
582 }