updating Nolok contrib templates
[supertux.git] / src / gameloop.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 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
7 //
8 //  This program is free software; you can redistribute it and/or
9 //  modify it under the terms of the GNU General Public License
10 //  as published by the Free Software Foundation; either version 2
11 //  of the License, or (at your option) any later version.
12 //
13 //  This program is distributed in the hope that it will be useful,
14 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 //  GNU General Public License for more details.
17 // 
18 //  You should have received a copy of the GNU General Public License
19 //  along with this program; if not, write to the Free Software
20 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
21 #include <config.h>
22
23 #include <iostream>
24 #include <sstream>
25 #include <cassert>
26 #include <cstdio>
27 #include <cstdlib>
28 #include <cmath>
29 #include <cstring>
30 #include <cerrno>
31 #include <unistd.h>
32 #include <ctime>
33 #include <stdexcept>
34
35 #include <SDL.h>
36
37 #ifndef WIN32
38 #include <sys/types.h>
39 #include <ctype.h>
40 #endif
41
42 #include "app/globals.h"
43 #include "gameloop.h"
44 #include "video/screen.h"
45 #include "app/setup.h"
46 #include "gui/menu.h"
47 #include "sector.h"
48 #include "level.h"
49 #include "tile.h"
50 #include "player_status.h"
51 #include "object/particlesystem.h"
52 #include "object/background.h"
53 #include "object/tilemap.h"
54 #include "object/camera.h"
55 #include "object/player.h"
56 #include "lisp/lisp.h"
57 #include "lisp/parser.h"
58 #include "resources.h"
59 #include "app/gettext.h"
60 #include "worldmap.h"
61 #include "misc.h"
62 #include "statistics.h"
63 #include "timer.h"
64 #include "object/fireworks.h"
65 #include "textscroller.h"
66
67 GameSession* GameSession::current_ = 0;
68
69 bool compare_last(std::string& haystack, std::string needle)
70 {
71   int haystack_size = haystack.size();
72   int needle_size = needle.size();
73
74   if(haystack_size < needle_size)
75     return false;
76
77   if(haystack.compare(haystack_size-needle_size, needle_size, needle) == 0)
78     return true;
79   return false;
80 }
81
82 GameSession::GameSession(const std::string& levelfile_, int mode,
83     Statistics* statistics)
84   : level(0), currentsector(0), st_gl_mode(mode),
85     end_sequence(NO_ENDSEQUENCE), levelfile(levelfile_),
86     best_level_statistics(statistics)
87 {
88   current_ = this;
89   
90   game_pause = false;
91   fps_fps = 0;
92
93   context = new DrawingContext();
94
95   restart_level();
96 }
97
98 void
99 GameSession::restart_level()
100 {
101   game_pause   = false;
102   exit_status  = ES_NONE;
103   end_sequence = NO_ENDSEQUENCE;
104
105   last_keys.clear();
106
107   delete level;
108   currentsector = 0;
109
110   level = new Level;
111   level->load(levelfile);
112
113   global_stats.reset();
114   global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
115   global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
116   global_stats.set_total_points(TIME_NEEDED_STAT, level->timelimit);
117
118   if(reset_sector != "") {
119     currentsector = level->get_sector(reset_sector);
120     if(!currentsector) {
121       std::stringstream msg;
122       msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
123       throw std::runtime_error(msg.str());
124     }
125     currentsector->activate(reset_pos);
126   } else {
127     currentsector = level->get_sector("main");
128     if(!currentsector)
129       throw std::runtime_error("Couldn't find main sector");
130     currentsector->activate("main");
131   }
132   
133   if(st_gl_mode == ST_GL_PLAY || st_gl_mode == ST_GL_LOAD_LEVEL_FILE)
134     levelintro();
135
136   start_timers();
137   currentsector->play_music(LEVEL_MUSIC);
138 }
139
140 GameSession::~GameSession()
141 {
142   delete level;
143   delete context;
144 }
145
146 void
147 GameSession::levelintro()
148 {
149   SoundManager::get()->halt_music();
150   
151   char str[60];
152
153   DrawingContext context;
154   for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
155       i != currentsector->gameobjects.end(); ++i) {
156     Background* background = dynamic_cast<Background*> (*i);
157     if(background) {
158       background->draw(context);
159     }
160   }
161
162 //  context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
163 //      CENTER_ALLIGN, LAYER_FOREGROUND1);
164   context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
165       LAYER_FOREGROUND1);
166
167   sprintf(str, "TUX x %d", player_status.lives);
168   context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
169       CENTER_ALLIGN, LAYER_FOREGROUND1);
170
171   if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
172     //TODO make author check case/blank-insensitive
173     context.draw_text(white_small_text,
174       std::string(_("contributed by ")) + level->get_author(), 
175       Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
176
177
178   if(best_level_statistics != NULL)
179     best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
180
181   context.do_drawing();
182
183   SDL_Event event;
184   wait_for_event(event,1000,3000,true);
185 }
186
187 /* Reset Timers */
188 void
189 GameSession::start_timers()
190 {
191   time_left.start(level->timelimit);
192   Ticks::pause_init();
193 }
194
195 void
196 GameSession::on_escape_press()
197 {
198   if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
199     return;   // don't let the player open the menu, when he is dying
200   
201   if(game_pause)
202     return;
203
204   if(st_gl_mode == ST_GL_TEST) {
205     exit_status = ES_LEVEL_ABORT;
206   } else if (!Menu::current()) {
207     Menu::set_current(game_menu);
208     Ticks::pause_start();
209   }
210 }
211
212 void
213 GameSession::process_events()
214 {
215   if (end_sequence != NO_ENDSEQUENCE)
216     {
217       Player& tux = *currentsector->player;
218          
219       tux.input.fire  = false;
220       tux.input.left  = false;
221       tux.input.right = true;
222       tux.input.down  = false; 
223
224       if (int(last_x_pos) == int(tux.get_pos().x))
225         tux.input.up    = true; 
226       else
227         tux.input.up    = false;
228
229       last_x_pos = tux.get_pos().x;
230
231       SDL_Event event;
232       while (SDL_PollEvent(&event))
233         {
234           /* Check for menu-events, if the menu is shown */
235           if (Menu::current())
236             {
237               Menu::current()->event(event);
238               if(!Menu::current())
239               Ticks::pause_stop();
240             }
241
242           switch(event.type)
243             {
244             case SDL_QUIT:        /* Quit event - quit: */
245               Termination::abort("Received window close", "");
246               break;
247               
248             case SDL_KEYDOWN:     /* A keypress! */
249               {
250                 SDLKey key = event.key.keysym.sym;
251            
252                 switch(key)
253                   {
254                   case SDLK_ESCAPE:    /* Escape: Open/Close the menu: */
255                     on_escape_press();
256                     break;
257                   default:
258                     break;
259                   }
260               }
261           
262             case SDL_JOYBUTTONDOWN:
263               if (event.jbutton.button == joystick_keymap.start_button)
264                 on_escape_press();
265               break;
266             }
267         }
268     }
269   else // normal mode
270     {
271       if(!Menu::current() && !game_pause)
272         Ticks::pause_stop();
273
274       SDL_Event event;
275       while (SDL_PollEvent(&event))
276         {
277           /* Check for menu-events, if the menu is shown */
278           if (Menu::current())
279             {
280               Menu::current()->event(event);
281               if(!Menu::current())
282                 Ticks::pause_stop();
283             }
284           else
285             {
286               Player& tux = *currentsector->player;
287   
288               switch(event.type)
289                 {
290                 case SDL_QUIT:        /* Quit event - quit: */
291                   Termination::abort("Received window close", "");
292                   break;
293
294                 case SDL_KEYDOWN:     /* A keypress! */
295                   {
296                     SDLKey key = event.key.keysym.sym;
297             
298                     if(tux.key_event(key, true))
299                       break;
300
301                     switch(key)
302                       {
303                       case SDLK_ESCAPE:    /* Escape: Open/Close the menu: */
304                         on_escape_press();
305                         break;
306                       default:
307                         break;
308                       }
309                   }
310                   break;
311                 case SDL_KEYUP:      /* A keyrelease! */
312                   {
313                     SDLKey key = event.key.keysym.sym;
314
315                     if(tux.key_event(key, false))
316                       break;
317
318                     switch(key)
319                       {
320                       case SDLK_a:
321                         if(debug_mode)
322                         {
323                           char buf[160];
324                           snprintf(buf, sizeof(buf), "P: %4.1f,%4.1f",
325                               tux.get_pos().x, tux.get_pos().y);
326                           context->draw_text(white_text, buf,
327                               Vector(0, SCREEN_HEIGHT - white_text->get_height()),
328                               LEFT_ALLIGN, LAYER_FOREGROUND1);
329                           context->do_drawing();
330                           SDL_Delay(1000);
331                         }
332                         break;
333                       case SDLK_p:
334                         if(!Menu::current())
335                           {
336                           // "lifeup" cheat activates pause cause of the 'p'
337                           // so work around to ignore it
338                             if(compare_last(last_keys, "lifeu"))
339                               break;
340
341                             if(game_pause)
342                               {
343                                 game_pause = false;
344                                 Ticks::pause_stop();
345                               }
346                             else
347                               {
348                                 game_pause = true;
349                                 Ticks::pause_start();
350                               }
351                           }
352                         break;
353                       default:
354                         break;
355                       }
356                   }
357
358                   /* Check if chacrater is ASCII */
359                   char ch[2];
360                   if((event.key.keysym.unicode & 0xFF80) == 0)
361                   {
362                       ch[0] = event.key.keysym.unicode & 0x7F;
363                       ch[1] = '\0';
364                   }
365                         last_keys.append(ch);  // add to cheat keys
366                         handle_cheats();
367                   break;
368
369                 case SDL_JOYAXISMOTION:
370                   if (event.jaxis.axis == joystick_keymap.x_axis)
371                     {
372                       if (event.jaxis.value < -joystick_keymap.dead_zone)
373                         {
374                           tux.input.left  = true;
375                           tux.input.right = false;
376                         }
377                       else if (event.jaxis.value > joystick_keymap.dead_zone)
378                         {
379                           tux.input.left  = false;
380                           tux.input.right = true;
381                         }
382                       else
383                         {
384                           tux.input.left  = false;
385                           tux.input.right = false;
386                         }
387                     }
388                   else if (event.jaxis.axis == joystick_keymap.y_axis)
389                     {
390                       if (event.jaxis.value > joystick_keymap.dead_zone)
391                         {
392                         tux.input.up = true;
393                         tux.input.down = false;
394                         }
395                       else if (event.jaxis.value < -joystick_keymap.dead_zone)
396                         {
397                         tux.input.up = false;
398                         tux.input.down = true;
399                         }
400                       else
401                         {
402                         tux.input.up = false;
403                         tux.input.down = false;
404                         }
405                     }
406                   break;
407
408                 case SDL_JOYHATMOTION:
409                   if(event.jhat.value & SDL_HAT_UP) {
410                     tux.input.up = true;
411                     tux.input.down = false;
412                   } else if(event.jhat.value & SDL_HAT_DOWN) {
413                     tux.input.up = false;
414                     tux.input.down = true;
415                   } else if(event.jhat.value & SDL_HAT_LEFT) {
416                     tux.input.left = true;
417                     tux.input.right = false;
418                   } else if(event.jhat.value & SDL_HAT_RIGHT) {
419                     tux.input.left = false;
420                     tux.input.right = true;
421                   } else if(event.jhat.value == SDL_HAT_CENTERED) {
422                     tux.input.left = false;
423                     tux.input.right = false;
424                     tux.input.up = false;
425                     tux.input.down = false;
426                   }
427                   break;
428             
429                 case SDL_JOYBUTTONDOWN:
430                   // FIXME: I assume we have to set old_jump and stuff here?!?
431                   if (event.jbutton.button == joystick_keymap.a_button)
432                     tux.input.jump = true;
433                   else if (event.jbutton.button == joystick_keymap.b_button)
434                     tux.input.fire = true;
435                   else if (event.jbutton.button == joystick_keymap.start_button)
436                     on_escape_press();
437                   break;
438                 case SDL_JOYBUTTONUP:
439                   if (event.jbutton.button == joystick_keymap.a_button)
440                     tux.input.jump = false;
441                   else if (event.jbutton.button == joystick_keymap.b_button)
442                     tux.input.fire = false;
443                   break;
444
445                 default:
446                   break;
447                 }  /* switch */
448             }
449         } /* while */
450     }
451 }
452
453 void
454 GameSession::handle_cheats()
455 {
456   Player& tux = *currentsector->player;
457   
458   // Cheating words (the goal of this is really for debugging,
459   // but could be used for some cheating, nothing wrong with that)
460   if(compare_last(last_keys, "grow")) {
461     tux.set_bonus(GROWUP_BONUS, false);
462     last_keys.clear();
463   }
464   if(compare_last(last_keys, "fire")) {
465     tux.set_bonus(FIRE_BONUS, false);
466     last_keys.clear();
467   }
468   if(compare_last(last_keys, "ice")) {
469     tux.set_bonus(ICE_BONUS, false);
470     last_keys.clear();
471   }
472   if(compare_last(last_keys, "lifeup")) {
473     player_status.lives++;
474     last_keys.clear();
475   }
476   if(compare_last(last_keys, "lifedown")) {
477     player_status.lives--;
478     last_keys.clear();
479   }
480   if(compare_last(last_keys, "grease")) {
481     tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
482     last_keys.clear();
483   }
484   if(compare_last(last_keys, "invincible")) {
485     // be invincle for the rest of the level
486     tux.invincible_timer.start(10000);
487     last_keys.clear();
488   }
489   if(compare_last(last_keys, "shrink")) {
490     // remove powerups
491     tux.kill(tux.SHRINK);
492     last_keys.clear();
493   }
494   if(compare_last(last_keys, "kill")) {
495     // kill Tux, but without losing a life
496     player_status.lives++;
497     tux.kill(tux.KILL);
498     last_keys.clear();
499   }
500   if(compare_last(last_keys, "grid")) {
501     // toggle debug grid
502     debug_grid = !debug_grid;
503     last_keys.clear();
504   }
505   if(compare_last(last_keys, "hover")) {
506     // toggle hover ability on/off
507     tux.enable_hover = !tux.enable_hover;
508     last_keys.clear();
509   }
510   if(compare_last(last_keys, "gotoend")) {
511     // goes to the end of the level
512     tux.move(Vector(
513           (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
514     currentsector->camera->reset(
515         Vector(tux.get_pos().x, tux.get_pos().y));
516     last_keys.clear();
517   }
518   if(compare_last(last_keys, "finish")) {
519     // finish current sector
520     exit_status = ES_LEVEL_FINISHED;
521     // don't add points to stats though...
522   }
523   // temporary to help player's choosing a flapping
524   if(compare_last(last_keys, "marek")) {
525     tux.flapping_mode = Player::MAREK_FLAP;
526     last_keys.clear();
527   }
528   if(compare_last(last_keys, "ricardo")) {
529     tux.flapping_mode = Player::RICARDO_FLAP;
530     last_keys.clear();
531   }
532   if(compare_last(last_keys, "ryan")) {
533     tux.flapping_mode = Player::RYAN_FLAP;
534     last_keys.clear();
535   }
536 }
537
538 void
539 GameSession::check_end_conditions()
540 {
541   Player* tux = currentsector->player;
542
543   /* End of level? */
544   if(end_sequence && endsequence_timer.check()) {
545     exit_status = ES_LEVEL_FINISHED;
546     return;
547   } else if (!end_sequence && tux->is_dead()) {
548     if (player_status.lives < 0) { // No more lives!?
549       exit_status = ES_GAME_OVER;
550     } else { // Still has lives, so reset Tux to the levelstart
551       restart_level();
552     }
553     
554     return;
555   }
556 }
557
558 void
559 GameSession::action(float elapsed_time)
560 {
561   // advance timers
562   if(!currentsector->player->growing_timer.started()) {
563     // Update Tux and the World
564     currentsector->action(elapsed_time);
565   }
566
567   // respawning in new sector?
568   if(newsector != "" && newspawnpoint != "") {
569     Sector* sector = level->get_sector(newsector);
570     if(sector == 0) {
571       std::cerr << "Sector '" << newsector << "' not found.\n";
572     }
573     sector->activate(newspawnpoint);
574     sector->play_music(LEVEL_MUSIC);
575     currentsector = sector;
576     newsector = "";
577     newspawnpoint = "";
578   }
579 }
580
581 void 
582 GameSession::draw()
583 {
584   currentsector->draw(*context);
585   drawstatus(*context);
586
587   if(game_pause)
588     draw_pause();
589
590   if(Menu::current()) {
591     Menu::current()->draw(*context);
592     mouse_cursor->draw(*context);
593   }
594
595   context->do_drawing();
596 }
597
598 void
599 GameSession::draw_pause()
600 {
601   int x = SCREEN_HEIGHT / 20;
602   for(int i = 0; i < x; ++i) {
603     context->draw_filled_rect(
604         Vector(i % 2 ? (pause_menu_frame * i)%SCREEN_WIDTH :
605           -((pause_menu_frame * i)%SCREEN_WIDTH)
606           ,(i*20+pause_menu_frame)%SCREEN_HEIGHT),
607         Vector(SCREEN_WIDTH,10),
608         Color(20,20,20, rand() % 20 + 1), LAYER_FOREGROUND1+1);
609   }
610   context->draw_filled_rect(
611       Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
612       Color(rand() % 50, rand() % 50, rand() % 50, 128), LAYER_FOREGROUND1);
613   context->draw_text(blue_text, _("PAUSE - Press 'P' To Play"),
614       Vector(SCREEN_WIDTH/2, 230), CENTER_ALLIGN, LAYER_FOREGROUND1+2);
615
616   const char* str1 = _("Playing: ");
617   const char* str2 = level->get_name().c_str();
618
619   context->draw_text(blue_text, str1,
620       Vector((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2, 340),
621       LEFT_ALLIGN, LAYER_FOREGROUND1+2);
622   context->draw_text(white_text, str2,
623       Vector(((SCREEN_WIDTH - (blue_text->get_text_width(str1) + white_text->get_text_width(str2)))/2)+blue_text->get_text_width(str1), 340),
624       LEFT_ALLIGN, LAYER_FOREGROUND1+2);
625 }
626   
627 void
628 GameSession::process_menu()
629 {
630   Menu* menu = Menu::current();
631   if(menu)
632     {
633       menu->action();
634
635       if(menu == game_menu)
636         {
637           switch (game_menu->check())
638             {
639             case MNID_CONTINUE:
640               Ticks::pause_stop();
641               break;
642             case MNID_ABORTLEVEL:
643               Ticks::pause_stop();
644               exit_status = ES_LEVEL_ABORT;
645               break;
646             }
647         }
648       else if(menu == options_menu)
649         {
650           process_options_menu();
651         }
652       else if(menu == load_game_menu )
653         {
654           process_load_game_menu();
655         }
656     }
657 }
658
659
660 GameSession::ExitStatus
661 GameSession::run()
662 {
663   Menu::set_current(0);
664   current_ = this;
665   
666   int fps_cnt = 0;
667   double fps_nextframe_ticks; // fps regulating code
668
669   // Eat unneeded events
670   SDL_Event event;
671   while(SDL_PollEvent(&event))
672   {}
673
674   draw();
675
676   Uint32 lastticks = SDL_GetTicks();
677   fps_ticks = SDL_GetTicks();
678   fps_nextframe_ticks = SDL_GetTicks(); // fps regulating code
679
680   while (exit_status == ES_NONE) {
681     Uint32 ticks = SDL_GetTicks();
682     float elapsed_time = float(ticks - lastticks) / 1000.;
683     if(!game_pause)
684       global_time += elapsed_time;
685     lastticks = ticks;
686
687     // 40fps is minimum
688     if(elapsed_time > 0.025){
689       elapsed_time = 0.025; 
690     }
691             
692     // fps regualting code  
693     const double wantedFps= 60.0; // set to 60 by now
694     while (fps_nextframe_ticks > SDL_GetTicks()){
695             /* just wait */
696             // If we really have to wait long, then do an imprecise SDL_Delay()
697             if (fps_nextframe_ticks - SDL_GetTicks() > 15){
698                 SDL_Delay(5);
699             }
700             
701     }
702     float diff = SDL_GetTicks() - fps_nextframe_ticks;
703     if (diff > 5.0)
704         fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / wantedFps); // sets the ticks that must have elapsed
705     else
706         fps_nextframe_ticks += 1000.0 / wantedFps; // sets the ticks that must have elapsed
707                                                // in order for the next frame to start.
708
709     
710     /* Handle events: */
711     currentsector->player->input.old_fire = currentsector->player->input.fire;
712     currentsector->player->input.old_up = currentsector->player->input.old_up;
713
714     process_events();
715     process_menu();
716
717     // Update the world state and all objects in the world
718     // Do that with a constante time-delta so that the game will run
719     // determistic and not different on different machines
720     if(!game_pause && !Menu::current())
721     {
722       // Update the world
723       check_end_conditions();
724       if (end_sequence == ENDSEQUENCE_RUNNING)
725         action(elapsed_time/2);
726       else if(end_sequence == NO_ENDSEQUENCE)
727         action(elapsed_time);
728     }
729     else
730     {
731       ++pause_menu_frame;
732       SDL_Delay(50);
733     }
734
735     draw();
736
737     /* Time stops in pause mode */
738     if(game_pause || Menu::current())
739     {
740       continue;
741     }
742
743     //frame_rate.update();
744     
745     /* Handle time: */
746     if (time_left.check() && !end_sequence)
747       currentsector->player->kill(Player::KILL);
748     
749     /* Handle music: */
750     if (currentsector->player->invincible_timer.started() && !end_sequence)
751     {
752       currentsector->play_music(HERRING_MUSIC);
753     }
754     /* are we low on time ? */
755     else if (time_left.get_timeleft() < TIME_WARNING && !end_sequence)
756     {
757       currentsector->play_music(HURRYUP_MUSIC);
758     }
759     /* or just normal music? */
760     else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
761     {
762       currentsector->play_music(LEVEL_MUSIC);
763     }
764
765     /* Calculate frames per second */
766     if(show_fps)
767     {
768       ++fps_cnt;
769       
770       if(SDL_GetTicks() - fps_ticks >= 500)
771       {
772         fps_fps = (float) fps_cnt / .5;
773         fps_cnt = 0;
774         fps_ticks = SDL_GetTicks();
775       }
776     }
777   }
778   
779   return exit_status;
780 }
781
782 void
783 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
784 {
785   newsector = sector;
786   newspawnpoint = spawnpoint;
787 }
788
789 void
790 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
791 {
792   reset_sector = sector;
793   reset_pos = pos;
794 }
795
796 void
797 GameSession::display_info_box(const std::string& text)
798 {
799   InfoBox* box = new InfoBox(text);
800
801   bool running = true;
802   while(running)  {
803     SDL_Event event;
804     while (SDL_PollEvent(&event)) {
805       switch(event.type) {
806         case SDL_KEYDOWN:
807           running = false;
808           break;
809       }
810     }
811
812     box->draw(*context);
813     draw();
814   }
815
816   delete box;
817 }
818
819 void
820 GameSession::start_sequence(const std::string& sequencename)
821 {
822   if(sequencename == "endsequence" || sequencename == "fireworks") {
823     if(end_sequence)
824       return;
825     
826     end_sequence = ENDSEQUENCE_RUNNING;
827     endsequence_timer.start(7.0); // 7 seconds until we finish the map
828     last_x_pos = -1;
829     SoundManager::get()->play_music(level_end_song, 0);
830     currentsector->player->invincible_timer.start(7.0);
831
832     // add left time to stats
833     global_stats.set_points(TIME_NEEDED_STAT,
834         int(time_left.get_period() - time_left.get_timeleft()));
835
836     if(sequencename == "fireworks") {
837       currentsector->add_object(new Fireworks());
838     }
839   } else if(sequencename == "stoptux") {
840     end_sequence =  ENDSEQUENCE_WAITING;
841   } else {
842     std::cout << "Unknown sequence '" << sequencename << "'.\n";
843   }
844 }
845
846 /* (Status): */
847 void
848 GameSession::drawstatus(DrawingContext& context)
849 {
850   char str[60];
851   
852   snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
853   context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
854   context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
855
856   if(st_gl_mode == ST_GL_TEST)
857     {
858       context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
859           LEFT_ALLIGN, LAYER_FOREGROUND1);
860     }
861
862   if(time_left.get_timeleft() < 0) {
863     context.draw_text(white_text, _("TIME's UP"), Vector(SCREEN_WIDTH/2, 0),
864         CENTER_ALLIGN, LAYER_FOREGROUND1);
865   } else if (time_left.get_timeleft() > TIME_WARNING
866       || int(global_time * 2.5) % 2) {
867     sprintf(str, " %d", int(time_left.get_timeleft()));
868     context.draw_text(white_text, _("TIME"),
869         Vector(SCREEN_WIDTH/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
870     context.draw_text(gold_text, str,
871         Vector(SCREEN_WIDTH/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
872   }
873
874   sprintf(str, " %d", player_status.distros);
875   context.draw_text(white_text, _("COINS"),
876       Vector(SCREEN_WIDTH - white_text->get_text_width(_("COINS"))-white_text->get_text_width("   99"), 0),
877         LEFT_ALLIGN, LAYER_FOREGROUND1);
878   context.draw_text(gold_text, str,
879       Vector(SCREEN_WIDTH - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
880
881   if (player_status.lives >= 5)
882     {
883       sprintf(str, "%dx", player_status.lives);
884       float x = SCREEN_WIDTH - gold_text->get_text_width(str) - tux_life->w;
885       context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
886       context.draw_surface(tux_life, Vector(SCREEN_WIDTH - 16, 20),
887           LAYER_FOREGROUND1);
888     }
889   else
890     {
891       for(int i= 0; i < player_status.lives; ++i)
892         context.draw_surface(tux_life, 
893             Vector(SCREEN_WIDTH - tux_life->w*4 +(tux_life->w*i), 20),
894             LAYER_FOREGROUND1);
895     }
896
897   context.draw_text(white_text, _("LIVES"),
898       Vector(SCREEN_WIDTH - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 20),
899       LEFT_ALLIGN, LAYER_FOREGROUND1);
900
901   if(show_fps)
902     {
903       sprintf(str, "%2.1f", fps_fps);
904       context.draw_text(white_text, "FPS", 
905           Vector(SCREEN_WIDTH - white_text->get_text_width("FPS     "), 40),
906           LEFT_ALLIGN, LAYER_FOREGROUND1);
907       context.draw_text(gold_text, str,
908           Vector(SCREEN_WIDTH-4*16, 40), LEFT_ALLIGN, LAYER_FOREGROUND1);
909     }
910 }
911
912 void
913 GameSession::drawresultscreen()
914 {
915   char str[80];
916
917   DrawingContext context;
918   for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
919       i != currentsector->gameobjects.end(); ++i) {
920     Background* background = dynamic_cast<Background*> (*i);
921     if(background) {
922       background->draw(context);
923     }
924   }
925
926   context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
927       CENTER_ALLIGN, LAYER_FOREGROUND1);
928
929   sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
930   context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
931
932   sprintf(str, _("COINS: %d"), player_status.distros);
933   context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
934
935   context.do_drawing();
936   
937   SDL_Event event;
938   wait_for_event(event,2000,5000,true);
939 }
940
941 std::string slotinfo(int slot)
942 {
943   std::string tmp;
944   std::string slotfile;
945   std::string title;
946   std::stringstream stream;
947   stream << slot;
948   slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
949
950   try {
951     lisp::Parser parser;
952     std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
953
954     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
955     if(!savegame)
956       throw std::runtime_error("file is not a supertux-savegame.");
957
958     savegame->get("title", title);
959   } catch(std::exception& e) {
960     return std::string(_("Slot")) + " " + stream.str() + " - " +
961       std::string(_("Free"));
962   }
963
964   return std::string("Slot ") + stream.str() + " - " + title;
965 }
966
967 bool process_load_game_menu()
968 {
969   int slot = load_game_menu->check();
970
971   if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
972     {
973       std::stringstream stream;
974       stream << slot;
975       std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
976
977       fadeout(256);
978       DrawingContext context;
979       context.draw_text(white_text, "Loading...",
980                         Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
981       context.do_drawing();
982
983       WorldMapNS::WorldMap worldmap;
984
985       worldmap.set_map_filename("/levels/world1/worldmap.stwm");
986       // Load the game or at least set the savegame_file variable
987       worldmap.loadgame(slotfile);
988
989       worldmap.display();
990
991       Menu::set_current(main_menu);
992
993       Ticks::pause_stop();
994       return true;
995     }
996   else
997     {
998       return false;
999     }
1000 }