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>
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.
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.
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.
37 #include "game_session.hpp"
39 #include "video/screen.hpp"
40 #include "audio/sound_manager.hpp"
41 #include "gui/menu.hpp"
45 #include "player_status.hpp"
46 #include "object/particlesystem.hpp"
47 #include "object/background.hpp"
48 #include "object/tilemap.hpp"
49 #include "object/camera.hpp"
50 #include "object/player.hpp"
51 #include "object/level_time.hpp"
52 #include "lisp/lisp.hpp"
53 #include "lisp/parser.hpp"
54 #include "resources.hpp"
55 #include "worldmap.hpp"
57 #include "statistics.hpp"
59 #include "object/fireworks.hpp"
60 #include "textscroller.hpp"
61 #include "control/codecontroller.hpp"
62 #include "control/joystickkeyboardcontroller.hpp"
64 #include "file_system.hpp"
65 #include "gameconfig.hpp"
66 #include "gettext.hpp"
67 #include "exceptions.hpp"
68 #include "flip_level_transformer.hpp"
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"
73 static const float LOGICAL_FPS = 64.0;
75 GameSession* GameSession::current_ = 0;
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)
90 context = new DrawingContext();
96 GameSession::restart_level()
99 exit_status = ES_NONE;
100 end_sequence = NO_ENDSEQUENCE;
102 main_controller->reset();
108 level->load(levelfile);
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());
116 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
120 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
121 j != sec->gameobjects.end(); ++j)
123 GameObject* obj = *j;
125 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
127 time += int(lt->get_level_time());
130 global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
132 if(reset_sector != "") {
133 currentsector = level->get_sector(reset_sector);
135 std::stringstream msg;
136 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
137 throw std::runtime_error(msg.str());
139 currentsector->activate(reset_pos);
141 currentsector = level->get_sector("main");
143 throw std::runtime_error("Couldn't find main sector");
144 currentsector->activate("main");
147 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
150 currentsector->play_music(LEVEL_MUSIC);
152 if(capture_file != "")
153 record_demo(capture_file);
156 GameSession::~GameSession()
158 delete capture_demo_stream;
159 delete playback_demo_stream;
160 delete demo_controller;
162 delete end_sequence_controller;
170 GameSession::record_demo(const std::string& filename)
172 delete capture_demo_stream;
174 capture_demo_stream = new std::ofstream(filename.c_str());
175 if(!capture_demo_stream->good()) {
176 std::stringstream msg;
177 msg << "Couldn't open demo file '" << filename << "' for writing.";
178 throw std::runtime_error(msg.str());
180 capture_file = filename;
184 GameSession::play_demo(const std::string& filename)
186 delete playback_demo_stream;
187 delete demo_controller;
189 playback_demo_stream = new std::ifstream(filename.c_str());
190 if(!playback_demo_stream->good()) {
191 std::stringstream msg;
192 msg << "Couldn't open demo file '" << filename << "' for reading.";
193 throw std::runtime_error(msg.str());
196 Player& tux = *currentsector->player;
197 demo_controller = new CodeController();
198 tux.set_controller(demo_controller);
202 GameSession::levelintro()
206 sound_manager->stop_music();
208 DrawingContext context;
209 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
210 i != currentsector->gameobjects.end(); ++i) {
211 Background* background = dynamic_cast<Background*> (*i);
213 background->draw(context);
217 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
218 // CENTER_ALLIGN, LAYER_FOREGROUND1);
219 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
222 sprintf(str, "TUX x %d", player_status->lives);
223 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
224 CENTER_ALLIGN, LAYER_FOREGROUND1);
226 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
227 //TODO make author check case/blank-insensitive
228 context.draw_text(white_small_text,
229 std::string(_("contributed by ")) + level->get_author(),
230 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
233 if(best_level_statistics != NULL)
234 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
236 context.do_drawing();
238 wait_for_event(1.0, 3.0);
242 GameSession::on_escape_press()
244 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
245 return; // don't let the player open the menu, when he is dying
247 if(mode == ST_GL_TEST) {
248 exit_status = ES_LEVEL_ABORT;
249 } else if (!Menu::current()) {
250 Menu::set_current(game_menu);
251 game_menu->set_active_item(MNID_CONTINUE);
259 GameSession::process_events()
261 Player& tux = *currentsector->player;
262 main_controller->update();
264 // end of pause mode?
265 if(!Menu::current() && game_pause) {
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);
275 end_sequence_controller->press(Controller::RIGHT);
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;
282 main_controller->update();
284 while (SDL_PollEvent(&event)) {
285 /* Check for menu-events, if the menu is shown */
287 Menu::current()->event(event);
288 main_controller->process_event(event);
289 if(event.type == SDL_QUIT)
290 throw graceful_shutdown();
294 if(playback_demo_stream != 0) {
295 demo_controller->update();
302 playback_demo_stream->get(left);
303 playback_demo_stream->get(right);
304 playback_demo_stream->get(up);
305 playback_demo_stream->get(down);
306 playback_demo_stream->get(jump);
307 playback_demo_stream->get(action);
308 demo_controller->press(Controller::LEFT, left);
309 demo_controller->press(Controller::RIGHT, right);
310 demo_controller->press(Controller::UP, up);
311 demo_controller->press(Controller::DOWN, down);
312 demo_controller->press(Controller::JUMP, jump);
313 demo_controller->press(Controller::ACTION, action);
316 // save input for demo?
317 if(capture_demo_stream != 0) {
318 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
319 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
320 capture_demo_stream ->put(main_controller->hold(Controller::UP));
321 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
322 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
323 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
328 GameSession::try_cheats()
330 if(currentsector == 0)
332 Player& tux = *currentsector->player;
334 // Cheating words (the goal of this is really for debugging,
335 // but could be used for some cheating, nothing wrong with that)
336 if(main_controller->check_cheatcode("grow")) {
337 tux.set_bonus(GROWUP_BONUS, false);
339 if(main_controller->check_cheatcode("fire")) {
340 tux.set_bonus(FIRE_BONUS, false);
342 if(main_controller->check_cheatcode("ice")) {
343 tux.set_bonus(ICE_BONUS, false);
345 if(main_controller->check_cheatcode("lifeup")) {
346 player_status->lives++;
348 if(main_controller->check_cheatcode("lifedown")) {
349 player_status->lives--;
351 if(main_controller->check_cheatcode("grease")) {
352 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
354 if(main_controller->check_cheatcode("invincible")) {
355 // be invincle for the rest of the level
356 tux.invincible_timer.start(10000);
358 if(main_controller->check_cheatcode("mortal")) {
359 // give up invincibility
360 tux.invincible_timer.stop();
362 if(main_controller->check_cheatcode("shrink")) {
364 tux.kill(tux.SHRINK);
366 if(main_controller->check_cheatcode("kill")) {
367 // kill Tux, but without losing a life
368 player_status->lives++;
371 if(main_controller->check_cheatcode("whereami")) {
372 msg_info("You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y);
375 if(main_controller->check_cheatcode("grid")) {
377 debug_grid = !debug_grid;
380 if(main_controller->check_cheatcode("gotoend")) {
381 // goes to the end of the level
383 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
384 currentsector->camera->reset(
385 Vector(tux.get_pos().x, tux.get_pos().y));
387 if(main_controller->check_cheatcode("flip")) {
388 FlipLevelTransformer flip_transformer;
389 flip_transformer.transform(GameSession::current()->get_current_level());
391 if(main_controller->check_cheatcode("finish")) {
392 // finish current sector
393 exit_status = ES_LEVEL_FINISHED;
394 // don't add points to stats though...
396 if(main_controller->check_cheatcode("camera")) {
397 msg_info("Camera is at "
398 << Sector::current()->camera->get_translation().x << ","
399 << Sector::current()->camera->get_translation().y);
404 GameSession::check_end_conditions()
406 Player* tux = currentsector->player;
409 if(end_sequence && endsequence_timer.check()) {
410 exit_status = ES_LEVEL_FINISHED;
412 // add time spent to statistics
413 int tottime = 0, remtime = 0;
414 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
418 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
419 j != sec->gameobjects.end(); ++j)
421 GameObject* obj = *j;
423 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
426 tottime += int(lt->get_level_time());
427 remtime += int(lt->get_remaining_time());
431 global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
434 } else if (!end_sequence && tux->is_dead()) {
435 if (player_status->lives < 0) { // No more lives!?
436 exit_status = ES_GAME_OVER;
437 } else { // Still has lives, so reset Tux to the levelstart
446 GameSession::update(float elapsed_time)
449 if(main_controller->pressed(Controller::PAUSE_MENU))
453 if(!currentsector->player->growing_timer.started()) {
454 // Update Tux and the World
455 currentsector->update(elapsed_time);
458 // respawning in new sector?
459 if(newsector != "" && newspawnpoint != "") {
460 Sector* sector = level->get_sector(newsector);
462 msg_warning("Sector '" << newsector << "' not found");
464 sector->activate(newspawnpoint);
465 sector->play_music(LEVEL_MUSIC);
466 currentsector = sector;
472 sound_manager->set_listener_position(currentsector->player->get_pos());
478 currentsector->draw(*context);
479 drawstatus(*context);
484 if(Menu::current()) {
485 Menu::current()->draw(*context);
488 context->do_drawing();
492 GameSession::draw_pause()
494 context->draw_filled_rect(
495 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
496 Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
500 GameSession::process_menu()
502 Menu* menu = Menu::current();
506 if(menu == game_menu) {
507 switch (game_menu->check()) {
509 Menu::set_current(0);
511 case MNID_ABORTLEVEL:
512 Menu::set_current(0);
513 exit_status = ES_LEVEL_ABORT;
516 } else if(menu == options_menu) {
517 process_options_menu();
518 } else if(menu == load_game_menu ) {
519 process_load_game_menu();
525 GameSession::ExitStatus
528 Menu::set_current(0);
533 // Eat unneeded events
535 while(SDL_PollEvent(&event))
540 Uint32 fps_ticks = SDL_GetTicks();
541 Uint32 fps_nextframe_ticks = SDL_GetTicks();
543 bool skipdraw = false;
545 while (exit_status == ES_NONE) {
546 // we run in a logical framerate so elapsed time is a constant
547 static const float elapsed_time = 1.0 / LOGICAL_FPS;
548 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
550 game_time += elapsed_time;
553 ticks = SDL_GetTicks();
554 if(ticks > fps_nextframe_ticks) {
555 if(skipdraw == true) {
556 // already skipped last frame? we have to slow down the game then...
558 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
560 // don't draw all frames when we're getting too slow
565 while(fps_nextframe_ticks > ticks) {
567 // If we really have to wait long, then do an imprecise SDL_Delay()
568 Uint32 diff = fps_nextframe_ticks - ticks;
570 SDL_Delay(diff - 10);
572 ticks = SDL_GetTicks();
575 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
578 float diff = SDL_GetTicks() - fps_nextframe_ticks;
580 // sets the ticks that must have elapsed
581 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
583 // sets the ticks that must have elapsed
584 // in order for the next frame to start.
585 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
592 // Update the world state and all objects in the world
593 // Do that with a constante time-delta so that the game will run
594 // determistic and not different on different machines
595 if(!game_pause && !Menu::current())
598 check_end_conditions();
599 if (end_sequence == ENDSEQUENCE_RUNNING)
600 update(elapsed_time/2);
601 else if(end_sequence == NO_ENDSEQUENCE)
602 update(elapsed_time);
613 sound_manager->update();
615 /* Time stops in pause mode */
616 if(game_pause || Menu::current())
621 //frame_rate.update();
624 if (currentsector->player->invincible_timer.started() &&
625 currentsector->player->invincible_timer.get_timeleft()
626 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
628 currentsector->play_music(HERRING_MUSIC);
630 /* or just normal music? */
631 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
633 currentsector->play_music(LEVEL_MUSIC);
636 /* Calculate frames per second */
641 if(SDL_GetTicks() - fps_ticks >= 500)
643 fps_fps = (float) fps_cnt / .5;
645 fps_ticks = SDL_GetTicks();
652 main_controller->reset();
657 GameSession::finish(bool win)
660 exit_status = ES_LEVEL_FINISHED;
662 exit_status = ES_LEVEL_ABORT;
666 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
669 newspawnpoint = spawnpoint;
673 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
675 reset_sector = sector;
680 GameSession::get_working_directory()
682 return FileSystem::dirname(levelfile);
686 GameSession::display_info_box(const std::string& text)
688 InfoBox* box = new InfoBox(text);
693 main_controller->update();
695 while (SDL_PollEvent(&event)) {
696 main_controller->process_event(event);
697 if(event.type == SDL_QUIT)
698 throw graceful_shutdown();
701 if(main_controller->pressed(Controller::JUMP)
702 || main_controller->pressed(Controller::ACTION)
703 || main_controller->pressed(Controller::PAUSE_MENU)
704 || main_controller->pressed(Controller::MENU_SELECT))
706 else if(main_controller->pressed(Controller::DOWN))
708 else if(main_controller->pressed(Controller::UP))
712 sound_manager->update();
719 GameSession::start_sequence(const std::string& sequencename)
721 if(sequencename == "endsequence" || sequencename == "fireworks") {
725 end_sequence = ENDSEQUENCE_RUNNING;
726 endsequence_timer.start(7.3);
728 sound_manager->play_music("music/leveldone.ogg", false);
729 currentsector->player->invincible_timer.start(7.3);
732 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
733 i != currentsector->gameobjects.end(); ++i)
735 GameObject* obj = *i;
737 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
742 if(sequencename == "fireworks") {
743 currentsector->add_object(new Fireworks());
745 } else if(sequencename == "stoptux") {
747 msg_warning("Final target reached without "
748 << "an active end sequence");
749 this->start_sequence("endsequence");
751 end_sequence = ENDSEQUENCE_WAITING;
753 msg_warning("Unknown sequence '" << sequencename << "'");
759 GameSession::drawstatus(DrawingContext& context)
761 player_status->draw(context);
763 if(config->show_fps) {
765 snprintf(str, sizeof(str), "%3.1f", fps_fps);
766 context.draw_text(white_text, "FPS",
767 Vector(SCREEN_WIDTH -
768 white_text->get_text_width("FPS ") - BORDER_X, BORDER_Y + 40),
769 LEFT_ALLIGN, LAYER_FOREGROUND1);
770 context.draw_text(gold_text, str,
771 Vector(SCREEN_WIDTH-4*16 - BORDER_X, BORDER_Y + 40),
772 LEFT_ALLIGN, LAYER_FOREGROUND1);
777 GameSession::drawresultscreen()
781 DrawingContext context;
782 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
783 i != currentsector->gameobjects.end(); ++i) {
784 Background* background = dynamic_cast<Background*> (*i);
786 background->draw(context);
790 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
791 CENTER_ALLIGN, LAYER_FOREGROUND1);
793 // sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
794 // context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
796 // y == 256 before removal of score
797 sprintf(str, _("COINS: %d"), player_status->coins);
798 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
800 context.do_drawing();
802 wait_for_event(2.0, 5.0);
805 std::string slotinfo(int slot)
808 std::string slotfile;
810 std::stringstream stream;
812 slotfile = "save/slot" + stream.str() + ".stsg";
816 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
818 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
820 throw std::runtime_error("file is not a supertux-savegame.");
822 savegame->get("title", title);
823 } catch(std::exception& e) {
824 return std::string(_("Slot")) + " " + stream.str() + " - " +
825 std::string(_("Free"));
828 return std::string("Slot ") + stream.str() + " - " + title;
831 bool process_load_game_menu()
833 int slot = load_game_menu->check();
838 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
841 std::stringstream stream;
843 std::string slotfile = "save/slot" + stream.str() + ".stsg";
845 sound_manager->stop_music();
847 DrawingContext context;
848 context.draw_text(white_text, "Loading...",
849 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
850 CENTER_ALLIGN, LAYER_FOREGROUND1);
851 context.do_drawing();
853 WorldMapNS::WorldMap worldmap;
855 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
856 // Load the game or at least set the savegame_file variable
857 worldmap.loadgame(slotfile);
861 Menu::set_current(main_menu);