* "Outsourced" cheats from GameSession to scripting system.
[supertux.git] / src / game_session.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <fstream>
22 #include <sstream>
23 #include <cassert>
24 #include <cstdio>
25 #include <cstdlib>
26 #include <cmath>
27 #include <cstring>
28 #include <cerrno>
29 #include <unistd.h>
30 #include <ctime>
31 #include <stdexcept>
32
33 #include <SDL.h>
34
35 #include "game_session.hpp"
36 #include "log.hpp"
37 #include "worldmap.hpp"
38 #include "mainloop.hpp"
39 #include "video/screen.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "gui/menu.hpp"
42 #include "sector.hpp"
43 #include "level.hpp"
44 #include "tile.hpp"
45 #include "player_status.hpp"
46 #include "object/particlesystem.hpp"
47 #include "object/background.hpp"
48 #include "object/gradient.hpp"
49 #include "object/tilemap.hpp"
50 #include "object/camera.hpp"
51 #include "object/player.hpp"
52 #include "object/level_time.hpp"
53 #include "lisp/lisp.hpp"
54 #include "lisp/parser.hpp"
55 #include "resources.hpp"
56 #include "misc.hpp"
57 #include "statistics.hpp"
58 #include "timer.hpp"
59 #include "object/fireworks.hpp"
60 #include "textscroller.hpp"
61 #include "control/codecontroller.hpp"
62 #include "control/joystickkeyboardcontroller.hpp"
63 #include "main.hpp"
64 #include "file_system.hpp"
65 #include "gameconfig.hpp"
66 #include "gettext.hpp"
67 #include "console.hpp"
68 #include "flip_level_transformer.hpp"
69
70 // the engine will be run with a logical framerate of 64fps.
71 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
72 // binary fraction...
73 static const float LOGICAL_FPS = 64.0;
74
75 using namespace WorldMapNS;
76
77 GameSession* GameSession::current_ = 0;
78
79 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
80     Statistics* statistics)
81   : level(0), currentsector(0), mode(mode),
82     end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
83     levelfile(levelfile_), best_level_statistics(statistics),
84     capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
85 {
86   current_ = this;
87   currentsector = 0;
88   
89   game_pause = false;
90   fps_fps = 0;
91
92   statistics_backdrop.reset(new Surface("images/engine/menu/score-backdrop.png"));
93
94   restart_level(true);
95 }
96
97 void
98 GameSession::restart_level(bool fromBeginning)
99 {
100   game_pause   = false;
101   end_sequence = NO_ENDSEQUENCE;
102
103   main_controller->reset();
104
105   currentsector = 0;
106
107   level.reset(new Level);
108   level->load(levelfile);
109
110   global_stats.reset();
111   global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
112   global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
113   
114   // get time
115   int time = 0;
116   for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
117   {
118     Sector* sec = *i;
119
120     for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
121         j != sec->gameobjects.end(); ++j)
122     {
123       GameObject* obj = *j;
124       
125       LevelTime* lt = dynamic_cast<LevelTime*> (obj);
126       if(lt)
127         time += int(lt->get_level_time());
128     }
129   }
130   global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
131
132   if (fromBeginning) reset_sector="";
133   if(reset_sector != "") {
134     currentsector = level->get_sector(reset_sector);
135     if(!currentsector) {
136       std::stringstream msg;
137       msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
138       throw std::runtime_error(msg.str());
139     }
140     currentsector->activate(reset_pos);
141   } else {
142     currentsector = level->get_sector("main");
143     if(!currentsector)
144       throw std::runtime_error("Couldn't find main sector");
145     currentsector->activate("main");
146   }
147   
148   if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
149     levelintro();
150
151   currentsector->play_music(LEVEL_MUSIC);
152
153   if(capture_file != "")
154     record_demo(capture_file);
155 }
156
157 GameSession::~GameSession()
158 {
159   delete capture_demo_stream;
160   delete playback_demo_stream;
161   delete demo_controller;
162
163   delete end_sequence_controller;
164
165   current_ = NULL;
166 }
167
168 void
169 GameSession::record_demo(const std::string& filename)
170 {
171   delete capture_demo_stream;
172   
173   capture_demo_stream = new std::ofstream(filename.c_str()); 
174   if(!capture_demo_stream->good()) {
175     std::stringstream msg;
176     msg << "Couldn't open demo file '" << filename << "' for writing.";
177     throw std::runtime_error(msg.str());
178   }
179   capture_file = filename;
180 }
181
182 void
183 GameSession::play_demo(const std::string& filename)
184 {
185   delete playback_demo_stream;
186   delete demo_controller;
187   
188   playback_demo_stream = new std::ifstream(filename.c_str());
189   if(!playback_demo_stream->good()) {
190     std::stringstream msg;
191     msg << "Couldn't open demo file '" << filename << "' for reading.";
192     throw std::runtime_error(msg.str());
193   }
194
195   Player& tux = *currentsector->player;
196   demo_controller = new CodeController();
197   tux.set_controller(demo_controller);
198 }
199
200 void
201 GameSession::levelintro()
202 {
203   char str[60];
204
205   sound_manager->stop_music();
206
207   DrawingContext context;
208   for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
209       i != currentsector->gameobjects.end(); ++i) {
210     Background* background = dynamic_cast<Background*> (*i);
211     if(background) {
212       background->draw(context);
213     }
214     Gradient* gradient = dynamic_cast<Gradient*> (*i);
215     if(gradient) {
216       gradient->draw(context);
217     }
218   }
219
220 //  context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
221 //      CENTER_ALLIGN, LAYER_FOREGROUND1);
222   context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
223       LAYER_FOREGROUND1);
224
225   sprintf(str, "Coins: %d", player_status->coins);
226   context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
227       CENTER_ALLIGN, LAYER_FOREGROUND1);
228
229   if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
230     //TODO make author check case/blank-insensitive
231     context.draw_text(white_small_text,
232       std::string(_("contributed by ")) + level->get_author(), 
233       Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
234
235
236   if(best_level_statistics != NULL)
237     best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
238
239   wait_for_event(1.0, 3.0);
240 }
241
242 void
243 GameSession::on_escape_press()
244 {
245   if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
246     return;   // don't let the player open the menu, when he is dying
247   
248   if(mode == ST_GL_TEST) {
249     main_loop->exit_screen();
250   } else if (!Menu::current()) {
251     Menu::set_current(game_menu);
252     game_menu->set_active_item(MNID_CONTINUE);
253     game_pause = true;
254   } else {
255     game_pause = false;
256   }
257 }
258
259 void
260 GameSession::process_events()
261 {
262   Player& tux = *currentsector->player;
263
264   // end of pause mode?
265   if(!Menu::current() && game_pause) {
266     game_pause = false;
267   }
268
269   if (end_sequence != NO_ENDSEQUENCE) {
270     if(end_sequence_controller == 0) {
271       end_sequence_controller = new CodeController();
272       tux.set_controller(end_sequence_controller);
273     }
274
275     end_sequence_controller->press(Controller::RIGHT);
276     
277     if (int(last_x_pos) == int(tux.get_pos().x))
278       end_sequence_controller->press(Controller::JUMP);    
279     last_x_pos = tux.get_pos().x;
280   }
281
282   // playback a demo?
283   if(playback_demo_stream != 0) {
284     demo_controller->update();
285     char left = false;
286     char right = false;
287     char up = false;
288     char down = false;
289     char jump = false;
290     char action = false;
291     playback_demo_stream->get(left);
292     playback_demo_stream->get(right);
293     playback_demo_stream->get(up);
294     playback_demo_stream->get(down);
295     playback_demo_stream->get(jump);
296     playback_demo_stream->get(action);
297     demo_controller->press(Controller::LEFT, left);
298     demo_controller->press(Controller::RIGHT, right);
299     demo_controller->press(Controller::UP, up);
300     demo_controller->press(Controller::DOWN, down);
301     demo_controller->press(Controller::JUMP, jump);
302     demo_controller->press(Controller::ACTION, action);
303   }
304
305   // save input for demo?
306   if(capture_demo_stream != 0) {
307     capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
308     capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
309     capture_demo_stream ->put(main_controller->hold(Controller::UP));
310     capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
311     capture_demo_stream ->put(main_controller->hold(Controller::JUMP));   
312     capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
313   }
314 }
315
316 void
317 GameSession::check_end_conditions()
318 {
319   Player* tux = currentsector->player;
320
321   /* End of level? */
322   if(end_sequence && endsequence_timer.check()) {
323     finish(true);
324     return;
325   } else if (!end_sequence && tux->is_dead()) {
326     if (player_status->coins < 0) { 
327       // No more coins: restart level from beginning
328       player_status->coins = 0;
329       restart_level(true);
330     } else { 
331       // Still has coins: restart level from last reset point
332       restart_level(false);
333     }
334     
335     return;
336   }
337 }
338
339 void 
340 GameSession::draw(DrawingContext& context)
341 {
342   currentsector->draw(context);
343   drawstatus(context);
344
345   if(game_pause)
346     draw_pause(context);
347 }
348
349 void
350 GameSession::draw_pause(DrawingContext& context)
351 {
352   context.draw_filled_rect(
353       Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
354       Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
355 }
356   
357 void
358 GameSession::process_menu()
359 {
360   Menu* menu = Menu::current();
361   if(menu) {
362     menu->update();
363
364     if(menu == game_menu) {
365       switch (game_menu->check()) {
366         case MNID_CONTINUE:
367           Menu::set_current(0);
368           break;
369         case MNID_ABORTLEVEL:
370           Menu::set_current(0);
371           main_loop->exit_screen();
372           break;
373       }
374     }
375   }
376 }
377
378 void
379 GameSession::setup()
380 {
381   Menu::set_current(NULL);
382   current_ = this;
383
384   // Eat unneeded events
385   SDL_Event event;
386   while(SDL_PollEvent(&event))
387   {}
388 }
389
390 void
391 GameSession::update(float elapsed_time)
392 {
393   process_events();
394   process_menu();
395
396   check_end_conditions();
397
398   // handle controller
399   if(main_controller->pressed(Controller::PAUSE_MENU))
400     on_escape_press();
401   
402   // respawning in new sector?
403   if(newsector != "" && newspawnpoint != "") {
404     Sector* sector = level->get_sector(newsector);
405     if(sector == 0) {
406       log_warning << "Sector '" << newsector << "' not found" << std::endl;
407     }
408     sector->activate(newspawnpoint);
409     sector->play_music(LEVEL_MUSIC);
410     currentsector = sector;
411     newsector = "";
412     newspawnpoint = "";
413   }
414
415   // Update the world state and all objects in the world
416   if(!game_pause) {
417     // Update the world
418     if (end_sequence == ENDSEQUENCE_RUNNING) {
419       currentsector->update(elapsed_time/2);
420     } else if(end_sequence == NO_ENDSEQUENCE) {
421       if(!currentsector->player->growing_timer.started())
422         currentsector->update(elapsed_time);
423     } 
424   }
425
426   // update sounds
427   sound_manager->set_listener_position(currentsector->player->get_pos());
428
429   /* Handle music: */
430   if (end_sequence)
431     return;
432   
433   if(currentsector->player->invincible_timer.started()) {
434     if(currentsector->player->invincible_timer.get_timeleft() <=
435        TUX_INVINCIBLE_TIME_WARNING) {
436       currentsector->play_music(HERRING_WARNING_MUSIC);
437     } else {
438       currentsector->play_music(HERRING_MUSIC);
439     }
440   } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
441     currentsector->play_music(LEVEL_MUSIC);
442   }
443 }
444
445 #if 0
446 GameSession::ExitStatus
447 GameSession::run()
448 {
449   Menu::set_current(0);
450   current_ = this;
451   
452   int fps_cnt = 0;
453
454   // Eat unneeded events
455   SDL_Event event;
456   while(SDL_PollEvent(&event))
457   {}
458
459   draw();
460
461   Uint32 fps_ticks = SDL_GetTicks();
462   Uint32 fps_nextframe_ticks = SDL_GetTicks();
463   Uint32 ticks;
464   bool skipdraw = false;
465
466   while (exit_status == ES_NONE) {
467     // we run in a logical framerate so elapsed time is a constant
468     // This will make the game run determistic and not different on different
469     // machines
470     static const float elapsed_time = 1.0 / LOGICAL_FPS;
471     // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
472     if(!game_pause)
473       game_time += elapsed_time;
474
475     // regulate fps
476     ticks = SDL_GetTicks();
477     if(ticks > fps_nextframe_ticks) {
478       if(skipdraw == true) {
479         // already skipped last frame? we have to slow down the game then...
480         skipdraw = false;
481         fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
482       } else {
483         // don't draw all frames when we're getting too slow
484         skipdraw = true;
485       }
486     } else {
487       skipdraw = false;
488       while(fps_nextframe_ticks > ticks) {
489         /* just wait */
490         // If we really have to wait long, then do an imprecise SDL_Delay()
491         Uint32 diff = fps_nextframe_ticks - ticks;
492         if(diff > 15) {
493           SDL_Delay(diff - 10);
494         } 
495         ticks = SDL_GetTicks();
496       }
497     }
498     fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
499
500     process_events();
501     process_menu();
502
503     // Update the world state and all objects in the world
504     if(!game_pause)
505     {
506       // Update the world
507       check_end_conditions();
508       if (end_sequence == ENDSEQUENCE_RUNNING)
509         update(elapsed_time/2);
510       else if(end_sequence == NO_ENDSEQUENCE)
511         update(elapsed_time);
512     }
513
514     if(!skipdraw)
515       draw();
516
517     // update sounds
518     sound_manager->update();
519
520     /* Time stops in pause mode */
521     if(game_pause || Menu::current())
522     {
523       continue;
524     }
525
526     /* Handle music: */
527     if (currentsector->player->invincible_timer.started() && 
528             currentsector->player->invincible_timer.get_timeleft() 
529             > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
530     {
531       currentsector->play_music(HERRING_MUSIC);
532     }
533     /* or just normal music? */
534     else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
535     {
536       currentsector->play_music(LEVEL_MUSIC);
537     }
538
539     /* Calculate frames per second */
540     if(config->show_fps)
541     {
542       ++fps_cnt;
543       
544       if(SDL_GetTicks() - fps_ticks >= 500)
545       {
546         fps_fps = (float) fps_cnt / .5;
547         fps_cnt = 0;
548         fps_ticks = SDL_GetTicks();
549       }
550     }
551   }
552  
553   // just in case
554   currentsector = 0;
555   main_controller->reset();
556   return exit_status;
557 }
558 #endif
559
560 void
561 GameSession::finish(bool win)
562 {
563   if(win) {
564     if(WorldMap::current())
565       WorldMap::current()->finished_level(levelfile);
566   }
567   
568   main_loop->exit_screen();
569 }
570
571 void
572 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
573 {
574   newsector = sector;
575   newspawnpoint = spawnpoint;
576 }
577
578 void
579 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
580 {
581   reset_sector = sector;
582   reset_pos = pos;
583 }
584
585 std::string
586 GameSession::get_working_directory()
587 {
588   return FileSystem::dirname(levelfile);
589 }
590
591 void
592 GameSession::display_info_box(const std::string& text)
593 {
594   InfoBox* box = new InfoBox(text);
595
596   bool running = true;
597   DrawingContext context;
598   
599   while(running)  {
600
601     // TODO make a screen out of this, another mainloop is ugly
602     main_controller->update();
603     SDL_Event event;
604     while (SDL_PollEvent(&event)) {
605       main_controller->process_event(event);
606       if(event.type == SDL_QUIT)
607         main_loop->quit();
608     }
609
610     if(main_controller->pressed(Controller::JUMP)
611         || main_controller->pressed(Controller::ACTION)
612         || main_controller->pressed(Controller::PAUSE_MENU)
613         || main_controller->pressed(Controller::MENU_SELECT))
614       running = false;
615     else if(main_controller->pressed(Controller::DOWN))
616       box->scrolldown();
617     else if(main_controller->pressed(Controller::UP))
618       box->scrollup();
619     box->draw(context);
620     draw(context);
621     context.do_drawing();
622     sound_manager->update();
623   }
624
625   delete box;
626 }
627
628 void
629 GameSession::start_sequence(const std::string& sequencename)
630 {
631   if(sequencename == "endsequence" || sequencename == "fireworks") {
632     if(end_sequence)
633       return;
634
635     end_sequence = ENDSEQUENCE_RUNNING;
636     endsequence_timer.start(7.3);
637     last_x_pos = -1;
638     sound_manager->play_music("music/leveldone.ogg", false);
639     currentsector->player->invincible_timer.start(7.3);
640
641     // Stop all clocks.
642     for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
643         i != currentsector->gameobjects.end(); ++i)
644     {
645       GameObject* obj = *i;
646
647       LevelTime* lt = dynamic_cast<LevelTime*> (obj);
648       if(lt)
649         lt->stop();
650     }
651
652     // add time spent to statistics
653     int tottime = 0, remtime = 0;
654     for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
655     {
656       Sector* sec = *i;
657
658       for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
659           j != sec->gameobjects.end(); ++j)
660       {
661         GameObject* obj = *j;
662
663         LevelTime* lt = dynamic_cast<LevelTime*> (obj);
664         if(lt)
665         {
666           tottime += int(lt->get_level_time());
667           remtime += int(lt->get_remaining_time());
668         }
669       }
670     }
671     global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
672
673     if(sequencename == "fireworks") {
674       currentsector->add_object(new Fireworks());
675     }
676   } else if(sequencename == "stoptux") {
677     if(!end_sequence) {
678       log_warning << "Final target reached without an active end sequence" << std::endl;
679       this->start_sequence("endsequence");
680     }
681     end_sequence =  ENDSEQUENCE_WAITING;
682   } else {
683     log_warning << "Unknown sequence '" << sequencename << "'" << std::endl;
684   }
685 }
686
687 /* (Status): */
688 void
689 GameSession::drawstatus(DrawingContext& context)
690 {
691   player_status->draw(context);
692
693   if(config->show_fps) {
694     char str[60];
695     snprintf(str, sizeof(str), "%3.1f", fps_fps);
696     const char* fpstext = "FPS";
697     context.draw_text(white_text, fpstext, Vector(SCREEN_WIDTH - white_text->get_text_width(fpstext) - gold_text->get_text_width(" 99999") - BORDER_X, BORDER_Y + 20), LEFT_ALLIGN, LAYER_FOREGROUND1);
698     context.draw_text(gold_text, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), RIGHT_ALLIGN, LAYER_FOREGROUND1);
699   }
700
701   // draw level stats while end_sequence is running
702   if (end_sequence) {
703     global_stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());
704   }
705 }
706