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