19b0f9f2d479ed82156b6bc04e43668ab25fa81c
[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   unsigned int 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 int wantedFps= 60; // 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     fps_nextframe_ticks = SDL_GetTicks() + (1000 / wantedFps); // sets the ticks that must have elapsed
703                                                // in order for the next frame to start.
704
705     
706     /* Handle events: */
707     currentsector->player->input.old_fire = currentsector->player->input.fire;
708     currentsector->player->input.old_up = currentsector->player->input.old_up;
709
710     process_events();
711     process_menu();
712
713     // Update the world state and all objects in the world
714     // Do that with a constante time-delta so that the game will run
715     // determistic and not different on different machines
716     if(!game_pause && !Menu::current())
717     {
718       // Update the world
719       check_end_conditions();
720       if (end_sequence == ENDSEQUENCE_RUNNING)
721         action(elapsed_time/2);
722       else if(end_sequence == NO_ENDSEQUENCE)
723         action(elapsed_time);
724     }
725     else
726     {
727       ++pause_menu_frame;
728       SDL_Delay(50);
729     }
730
731     draw();
732
733     /* Time stops in pause mode */
734     if(game_pause || Menu::current())
735     {
736       continue;
737     }
738
739     //frame_rate.update();
740     
741     /* Handle time: */
742     if (time_left.check() && !end_sequence)
743       currentsector->player->kill(Player::KILL);
744     
745     /* Handle music: */
746     if (currentsector->player->invincible_timer.started() && !end_sequence)
747     {
748       currentsector->play_music(HERRING_MUSIC);
749     }
750     /* are we low on time ? */
751     else if (time_left.get_timeleft() < TIME_WARNING && !end_sequence)
752     {
753       currentsector->play_music(HURRYUP_MUSIC);
754     }
755     /* or just normal music? */
756     else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
757     {
758       currentsector->play_music(LEVEL_MUSIC);
759     }
760
761     /* Calculate frames per second */
762     if(show_fps)
763     {
764       ++fps_cnt;
765       
766       if(SDL_GetTicks() - fps_ticks >= 500)
767       {
768         fps_fps = (float) fps_cnt / .5;
769         fps_cnt = 0;
770         fps_ticks = SDL_GetTicks();
771       }
772     }
773   }
774   
775   return exit_status;
776 }
777
778 void
779 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
780 {
781   newsector = sector;
782   newspawnpoint = spawnpoint;
783 }
784
785 void
786 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
787 {
788   reset_sector = sector;
789   reset_pos = pos;
790 }
791
792 void
793 GameSession::display_info_box(const std::string& text)
794 {
795   InfoBox* box = new InfoBox(text);
796
797   bool running = true;
798   while(running)  {
799     SDL_Event event;
800     while (SDL_PollEvent(&event)) {
801       switch(event.type) {
802         case SDL_KEYDOWN:
803           running = false;
804           break;
805       }
806     }
807
808     box->draw(*context);
809     draw();
810   }
811
812   delete box;
813 }
814
815 void
816 GameSession::start_sequence(const std::string& sequencename)
817 {
818   if(sequencename == "endsequence" || sequencename == "fireworks") {
819     if(end_sequence)
820       return;
821     
822     end_sequence = ENDSEQUENCE_RUNNING;
823     endsequence_timer.start(7.0); // 7 seconds until we finish the map
824     last_x_pos = -1;
825     SoundManager::get()->play_music(level_end_song, 0);
826     currentsector->player->invincible_timer.start(7.0);
827
828     // add left time to stats
829     global_stats.set_points(TIME_NEEDED_STAT,
830         int(time_left.get_period() - time_left.get_timeleft()));
831
832     if(sequencename == "fireworks") {
833       currentsector->add_object(new Fireworks());
834     }
835   } else if(sequencename == "stoptux") {
836     end_sequence =  ENDSEQUENCE_WAITING;
837   } else {
838     std::cout << "Unknown sequence '" << sequencename << "'.\n";
839   }
840 }
841
842 /* (Status): */
843 void
844 GameSession::drawstatus(DrawingContext& context)
845 {
846   char str[60];
847   
848   snprintf(str, 60, " %d", global_stats.get_points(SCORE_STAT));
849   context.draw_text(white_text, _("SCORE"), Vector(0, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
850   context.draw_text(gold_text, str, Vector(96, 0), LEFT_ALLIGN, LAYER_FOREGROUND1);
851
852   if(st_gl_mode == ST_GL_TEST)
853     {
854       context.draw_text(white_text, _("Press ESC To Return"), Vector(0,20),
855           LEFT_ALLIGN, LAYER_FOREGROUND1);
856     }
857
858   if(time_left.get_timeleft() < 0) {
859     context.draw_text(white_text, _("TIME's UP"), Vector(SCREEN_WIDTH/2, 0),
860         CENTER_ALLIGN, LAYER_FOREGROUND1);
861   } else if (time_left.get_timeleft() > TIME_WARNING
862       || int(global_time * 2.5) % 2) {
863     sprintf(str, " %d", int(time_left.get_timeleft()));
864     context.draw_text(white_text, _("TIME"),
865         Vector(SCREEN_WIDTH/2, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
866     context.draw_text(gold_text, str,
867         Vector(SCREEN_WIDTH/2 + 4*16, 0), CENTER_ALLIGN, LAYER_FOREGROUND1);
868   }
869
870   sprintf(str, " %d", player_status.distros);
871   context.draw_text(white_text, _("COINS"),
872       Vector(SCREEN_WIDTH - white_text->get_text_width(_("COINS"))-white_text->get_text_width("   99"), 0),
873         LEFT_ALLIGN, LAYER_FOREGROUND1);
874   context.draw_text(gold_text, str,
875       Vector(SCREEN_WIDTH - gold_text->get_text_width(" 99"), 0),LEFT_ALLIGN, LAYER_FOREGROUND1);
876
877   if (player_status.lives >= 5)
878     {
879       sprintf(str, "%dx", player_status.lives);
880       float x = SCREEN_WIDTH - gold_text->get_text_width(str) - tux_life->w;
881       context.draw_text(gold_text, str, Vector(x, 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
882       context.draw_surface(tux_life, Vector(SCREEN_WIDTH - 16, 20),
883           LAYER_FOREGROUND1);
884     }
885   else
886     {
887       for(int i= 0; i < player_status.lives; ++i)
888         context.draw_surface(tux_life, 
889             Vector(SCREEN_WIDTH - tux_life->w*4 +(tux_life->w*i), 20),
890             LAYER_FOREGROUND1);
891     }
892
893   context.draw_text(white_text, _("LIVES"),
894       Vector(SCREEN_WIDTH - white_text->get_text_width(_("LIVES")) - white_text->get_text_width("   99"), 20),
895       LEFT_ALLIGN, LAYER_FOREGROUND1);
896
897   if(show_fps)
898     {
899       sprintf(str, "%2.1f", fps_fps);
900       context.draw_text(white_text, "FPS", 
901           Vector(SCREEN_WIDTH - white_text->get_text_width("FPS     "), 40),
902           LEFT_ALLIGN, LAYER_FOREGROUND1);
903       context.draw_text(gold_text, str,
904           Vector(SCREEN_WIDTH-4*16, 40), LEFT_ALLIGN, LAYER_FOREGROUND1);
905     }
906 }
907
908 void
909 GameSession::drawresultscreen()
910 {
911   char str[80];
912
913   DrawingContext context;
914   for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
915       i != currentsector->gameobjects.end(); ++i) {
916     Background* background = dynamic_cast<Background*> (*i);
917     if(background) {
918       background->draw(context);
919     }
920   }
921
922   context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
923       CENTER_ALLIGN, LAYER_FOREGROUND1);
924
925   sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
926   context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
927
928   sprintf(str, _("COINS: %d"), player_status.distros);
929   context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 256), CENTER_ALLIGN, LAYER_FOREGROUND1);
930
931   context.do_drawing();
932   
933   SDL_Event event;
934   wait_for_event(event,2000,5000,true);
935 }
936
937 std::string slotinfo(int slot)
938 {
939   std::string tmp;
940   std::string slotfile;
941   std::string title;
942   std::stringstream stream;
943   stream << slot;
944   slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
945
946   try {
947     lisp::Parser parser;
948     std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
949
950     const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
951     if(!savegame)
952       throw std::runtime_error("file is not a supertux-savegame.");
953
954     savegame->get("title", title);
955   } catch(std::exception& e) {
956     return std::string(_("Slot")) + " " + stream.str() + " - " +
957       std::string(_("Free"));
958   }
959
960   return std::string("Slot ") + stream.str() + " - " + title;
961 }
962
963 bool process_load_game_menu()
964 {
965   int slot = load_game_menu->check();
966
967   if(slot != -1 && load_game_menu->get_item_by_id(slot).kind == MN_ACTION)
968     {
969       std::stringstream stream;
970       stream << slot;
971       std::string slotfile = st_save_dir + "/slot" + stream.str() + ".stsg";
972
973       fadeout(256);
974       DrawingContext context;
975       context.draw_text(white_text, "Loading...",
976                         Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2), CENTER_ALLIGN, LAYER_FOREGROUND1);
977       context.do_drawing();
978
979       WorldMapNS::WorldMap worldmap;
980
981       worldmap.set_map_filename("/levels/world1/worldmap.stwm");
982       // Load the game or at least set the savegame_file variable
983       worldmap.loadgame(slotfile);
984
985       worldmap.display();
986
987       Menu::set_current(main_menu);
988
989       Ticks::pause_stop();
990       return true;
991     }
992   else
993     {
994       return false;
995     }
996 }