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.
38 #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)
88 music_playing = false;
91 context = new DrawingContext();
97 GameSession::restart_level()
100 exit_status = ES_NONE;
101 end_sequence = NO_ENDSEQUENCE;
103 main_controller->reset();
109 level->load(levelfile);
111 global_stats.reset();
112 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
113 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
117 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
121 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
122 j != sec->gameobjects.end(); ++j)
124 GameObject* obj = *j;
126 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
128 time += int(lt->get_level_time());
131 global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
133 if(reset_sector != "") {
134 currentsector = level->get_sector(reset_sector);
136 std::stringstream msg;
137 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
138 throw std::runtime_error(msg.str());
140 currentsector->activate(reset_pos);
142 currentsector = level->get_sector("main");
144 throw std::runtime_error("Couldn't find main sector");
145 currentsector->activate("main");
148 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
153 currentsector->play_music(LEVEL_MUSIC);
154 music_playing = true;
157 if(capture_file != "")
158 record_demo(capture_file);
161 GameSession::~GameSession()
163 delete capture_demo_stream;
164 delete playback_demo_stream;
165 delete demo_controller;
167 delete end_sequence_controller;
175 GameSession::record_demo(const std::string& filename)
177 delete capture_demo_stream;
179 capture_demo_stream = new std::ofstream(filename.c_str());
180 if(!capture_demo_stream->good()) {
181 std::stringstream msg;
182 msg << "Couldn't open demo file '" << filename << "' for writing.";
183 throw std::runtime_error(msg.str());
185 capture_file = filename;
189 GameSession::play_demo(const std::string& filename)
191 delete playback_demo_stream;
192 delete demo_controller;
194 playback_demo_stream = new std::ifstream(filename.c_str());
195 if(!playback_demo_stream->good()) {
196 std::stringstream msg;
197 msg << "Couldn't open demo file '" << filename << "' for reading.";
198 throw std::runtime_error(msg.str());
201 Player& tux = *currentsector->player;
202 demo_controller = new CodeController();
203 tux.set_controller(demo_controller);
207 GameSession::levelintro()
211 DrawingContext context;
212 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
213 i != currentsector->gameobjects.end(); ++i) {
214 Background* background = dynamic_cast<Background*> (*i);
216 background->draw(context);
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),
225 sprintf(str, "TUX x %d", player_status->lives);
226 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
227 CENTER_ALLIGN, LAYER_FOREGROUND1);
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);
236 if(best_level_statistics != NULL)
237 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
239 context.do_drawing();
241 wait_for_event(1.0, 3.0);
245 GameSession::on_escape_press()
247 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
248 return; // don't let the player open the menu, when he is dying
250 if(mode == ST_GL_TEST) {
251 exit_status = ES_LEVEL_ABORT;
252 } else if (!Menu::current()) {
253 Menu::set_current(game_menu);
254 game_menu->set_active_item(MNID_CONTINUE);
262 GameSession::process_events()
264 Player& tux = *currentsector->player;
265 main_controller->update();
267 // end of pause mode?
268 if(!Menu::current() && game_pause) {
272 if (end_sequence != NO_ENDSEQUENCE) {
273 if(end_sequence_controller == 0) {
274 end_sequence_controller = new CodeController();
275 tux.set_controller(end_sequence_controller);
278 end_sequence_controller->press(Controller::RIGHT);
280 if (int(last_x_pos) == int(tux.get_pos().x))
281 end_sequence_controller->press(Controller::JUMP);
282 last_x_pos = tux.get_pos().x;
285 main_controller->update();
287 while (SDL_PollEvent(&event)) {
288 /* Check for menu-events, if the menu is shown */
290 Menu::current()->event(event);
291 main_controller->process_event(event);
292 if(event.type == SDL_QUIT)
293 throw graceful_shutdown();
297 if(playback_demo_stream != 0) {
298 demo_controller->update();
305 playback_demo_stream->get(left);
306 playback_demo_stream->get(right);
307 playback_demo_stream->get(up);
308 playback_demo_stream->get(down);
309 playback_demo_stream->get(jump);
310 playback_demo_stream->get(action);
311 demo_controller->press(Controller::LEFT, left);
312 demo_controller->press(Controller::RIGHT, right);
313 demo_controller->press(Controller::UP, up);
314 demo_controller->press(Controller::DOWN, down);
315 demo_controller->press(Controller::JUMP, jump);
316 demo_controller->press(Controller::ACTION, action);
319 // save input for demo?
320 if(capture_demo_stream != 0) {
321 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
322 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
323 capture_demo_stream ->put(main_controller->hold(Controller::UP));
324 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
325 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
326 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
331 GameSession::try_cheats()
333 if(currentsector == 0)
335 Player& tux = *currentsector->player;
337 // Cheating words (the goal of this is really for debugging,
338 // but could be used for some cheating, nothing wrong with that)
339 if(main_controller->check_cheatcode("grow")) {
340 tux.set_bonus(GROWUP_BONUS, false);
342 if(main_controller->check_cheatcode("fire")) {
343 tux.set_bonus(FIRE_BONUS, false);
345 if(main_controller->check_cheatcode("ice")) {
346 tux.set_bonus(ICE_BONUS, false);
348 if(main_controller->check_cheatcode("lifeup")) {
349 player_status->lives++;
351 if(main_controller->check_cheatcode("lifedown")) {
352 player_status->lives--;
354 if(main_controller->check_cheatcode("grease")) {
355 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
357 if(main_controller->check_cheatcode("invincible")) {
358 // be invincle for the rest of the level
359 tux.invincible_timer.start(10000);
361 if(main_controller->check_cheatcode("mortal")) {
362 // give up invincibility
363 tux.invincible_timer.stop();
365 if(main_controller->check_cheatcode("shrink")) {
367 tux.kill(tux.SHRINK);
369 if(main_controller->check_cheatcode("kill")) {
370 // kill Tux, but without losing a life
371 player_status->lives++;
374 if(main_controller->check_cheatcode("whereami")) {
375 std::cout << "You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y << "." << std::endl;
378 if(main_controller->check_cheatcode("grid")) {
380 debug_grid = !debug_grid;
383 if(main_controller->check_cheatcode("gotoend")) {
384 // goes to the end of the level
386 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
387 currentsector->camera->reset(
388 Vector(tux.get_pos().x, tux.get_pos().y));
390 if(main_controller->check_cheatcode("flip")) {
391 FlipLevelTransformer flip_transformer;
392 flip_transformer.transform(GameSession::current()->get_current_level());
394 if(main_controller->check_cheatcode("finish")) {
395 // finish current sector
396 exit_status = ES_LEVEL_FINISHED;
397 // don't add points to stats though...
402 GameSession::check_end_conditions()
404 Player* tux = currentsector->player;
407 if(end_sequence && endsequence_timer.check()) {
408 exit_status = ES_LEVEL_FINISHED;
410 // add time spent to statistics
411 int tottime = 0, remtime = 0;
412 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
416 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
417 j != sec->gameobjects.end(); ++j)
419 GameObject* obj = *j;
421 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
424 tottime += int(lt->get_level_time());
425 remtime += int(lt->get_remaining_time());
429 global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
432 } else if (!end_sequence && tux->is_dead()) {
433 if (player_status->lives < 0) { // No more lives!?
434 exit_status = ES_GAME_OVER;
435 } else { // Still has lives, so reset Tux to the levelstart
444 GameSession::update(float elapsed_time)
447 if(main_controller->pressed(Controller::PAUSE_MENU))
451 if(!currentsector->player->growing_timer.started()) {
452 // Update Tux and the World
453 currentsector->update(elapsed_time);
456 // respawning in new sector?
457 if(newsector != "" && newspawnpoint != "") {
458 Sector* sector = level->get_sector(newsector);
460 std::cerr << "Sector '" << newsector << "' not found.\n";
462 sector->activate(newspawnpoint);
463 sector->play_music(LEVEL_MUSIC);
464 currentsector = sector;
470 sound_manager->set_listener_position(currentsector->player->get_pos());
476 currentsector->draw(*context);
477 drawstatus(*context);
482 if(Menu::current()) {
483 Menu::current()->draw(*context);
486 context->do_drawing();
490 GameSession::draw_pause()
492 context->draw_filled_rect(
493 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
494 Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
498 GameSession::process_menu()
500 Menu* menu = Menu::current();
504 if(menu == game_menu) {
505 switch (game_menu->check()) {
507 Menu::set_current(0);
509 case MNID_ABORTLEVEL:
510 Menu::set_current(0);
511 exit_status = ES_LEVEL_ABORT;
514 } else if(menu == options_menu) {
515 process_options_menu();
516 } else if(menu == load_game_menu ) {
517 process_load_game_menu();
523 GameSession::ExitStatus
526 Menu::set_current(0);
531 // Eat unneeded events
533 while(SDL_PollEvent(&event))
538 Uint32 fps_ticks = SDL_GetTicks();
539 Uint32 fps_nextframe_ticks = SDL_GetTicks();
541 bool skipdraw = false;
543 while (exit_status == ES_NONE) {
544 // we run in a logical framerate so elapsed time is a constant
545 static const float elapsed_time = 1.0 / LOGICAL_FPS;
546 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
548 game_time += elapsed_time;
551 ticks = SDL_GetTicks();
552 if(ticks > fps_nextframe_ticks) {
553 if(skipdraw == true) {
554 // already skipped last frame? we have to slow down the game then...
556 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
558 // don't draw all frames when we're getting too slow
563 while(fps_nextframe_ticks > ticks) {
565 // If we really have to wait long, then do an imprecise SDL_Delay()
566 Uint32 diff = fps_nextframe_ticks - ticks;
568 SDL_Delay(diff - 10);
570 ticks = SDL_GetTicks();
573 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
576 float diff = SDL_GetTicks() - fps_nextframe_ticks;
578 // sets the ticks that must have elapsed
579 fps_nextframe_ticks = SDL_GetTicks() + (1000.0 / LOGICAL_FPS);
581 // sets the ticks that must have elapsed
582 // in order for the next frame to start.
583 fps_nextframe_ticks += 1000.0 / LOGICAL_FPS;
590 // Update the world state and all objects in the world
591 // Do that with a constante time-delta so that the game will run
592 // determistic and not different on different machines
593 if(!game_pause && !Menu::current())
596 check_end_conditions();
597 if (end_sequence == ENDSEQUENCE_RUNNING)
598 update(elapsed_time/2);
599 else if(end_sequence == NO_ENDSEQUENCE)
600 update(elapsed_time);
611 sound_manager->update();
613 /* Time stops in pause mode */
614 if(game_pause || Menu::current())
619 //frame_rate.update();
622 if (currentsector->player->invincible_timer.started() &&
623 currentsector->player->invincible_timer.get_timeleft()
624 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
626 currentsector->play_music(HERRING_MUSIC);
628 /* or just normal music? */
629 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
631 currentsector->play_music(LEVEL_MUSIC);
634 /* Calculate frames per second */
639 if(SDL_GetTicks() - fps_ticks >= 500)
641 fps_fps = (float) fps_cnt / .5;
643 fps_ticks = SDL_GetTicks();
650 main_controller->reset();
655 GameSession::finish(bool win)
658 exit_status = ES_LEVEL_FINISHED;
660 exit_status = ES_LEVEL_ABORT;
664 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
667 newspawnpoint = spawnpoint;
671 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
673 reset_sector = sector;
678 GameSession::get_working_directory()
680 return FileSystem::dirname(levelfile);
684 GameSession::display_info_box(const std::string& text)
686 InfoBox* box = new InfoBox(text);
691 main_controller->update();
693 while (SDL_PollEvent(&event)) {
694 main_controller->process_event(event);
695 if(event.type == SDL_QUIT)
696 throw graceful_shutdown();
699 if(main_controller->pressed(Controller::JUMP)
700 || main_controller->pressed(Controller::ACTION)
701 || main_controller->pressed(Controller::PAUSE_MENU)
702 || main_controller->pressed(Controller::MENU_SELECT))
704 else if(main_controller->pressed(Controller::DOWN))
706 else if(main_controller->pressed(Controller::UP))
710 sound_manager->update();
717 GameSession::start_sequence(const std::string& sequencename)
719 if(sequencename == "endsequence" || sequencename == "fireworks") {
723 end_sequence = ENDSEQUENCE_RUNNING;
724 endsequence_timer.start(7.0); // 7 seconds until we finish the map
726 sound_manager->play_music("music/leveldone.ogg", false);
727 currentsector->player->invincible_timer.start(7.0);
729 if(sequencename == "fireworks") {
730 currentsector->add_object(new Fireworks());
732 } else if(sequencename == "stoptux") {
734 std::cout << "WARNING: Final target reached without "
735 << "an active end sequence." << std::endl;
736 this->start_sequence("endsequence");
738 end_sequence = ENDSEQUENCE_WAITING;
740 std::cout << "Unknown sequence '" << sequencename << "'.\n";
746 GameSession::drawstatus(DrawingContext& context)
748 player_status->draw(context);
750 if(config->show_fps) {
752 snprintf(str, sizeof(str), "%3.1f", fps_fps);
753 context.draw_text(white_text, "FPS",
754 Vector(SCREEN_WIDTH -
755 white_text->get_text_width("FPS ") - BORDER_X, BORDER_Y + 40),
756 LEFT_ALLIGN, LAYER_FOREGROUND1);
757 context.draw_text(gold_text, str,
758 Vector(SCREEN_WIDTH-4*16 - BORDER_X, BORDER_Y + 40),
759 LEFT_ALLIGN, LAYER_FOREGROUND1);
764 GameSession::drawresultscreen()
768 DrawingContext context;
769 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
770 i != currentsector->gameobjects.end(); ++i) {
771 Background* background = dynamic_cast<Background*> (*i);
773 background->draw(context);
777 context.draw_text(blue_text, _("Result:"), Vector(SCREEN_WIDTH/2, 200),
778 CENTER_ALLIGN, LAYER_FOREGROUND1);
780 // sprintf(str, _("SCORE: %d"), global_stats.get_points(SCORE_STAT));
781 // context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
783 // y == 256 before removal of score
784 sprintf(str, _("COINS: %d"), player_status->coins);
785 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH/2, 224), CENTER_ALLIGN, LAYER_FOREGROUND1);
787 context.do_drawing();
789 wait_for_event(2.0, 5.0);
792 std::string slotinfo(int slot)
795 std::string slotfile;
797 std::stringstream stream;
799 slotfile = "save/slot" + stream.str() + ".stsg";
803 std::auto_ptr<lisp::Lisp> root (parser.parse(slotfile));
805 const lisp::Lisp* savegame = root->get_lisp("supertux-savegame");
807 throw std::runtime_error("file is not a supertux-savegame.");
809 savegame->get("title", title);
810 } catch(std::exception& e) {
811 return std::string(_("Slot")) + " " + stream.str() + " - " +
812 std::string(_("Free"));
815 return std::string("Slot ") + stream.str() + " - " + title;
818 bool process_load_game_menu()
820 int slot = load_game_menu->check();
825 if(load_game_menu->get_item_by_id(slot).kind != MN_ACTION)
828 std::stringstream stream;
830 std::string slotfile = "save/slot" + stream.str() + ".stsg";
832 sound_manager->stop_music();
834 DrawingContext context;
835 context.draw_text(white_text, "Loading...",
836 Vector(SCREEN_WIDTH/2, SCREEN_HEIGHT/2),
837 CENTER_ALLIGN, LAYER_FOREGROUND1);
838 context.do_drawing();
840 WorldMapNS::WorldMap worldmap;
842 worldmap.set_map_filename("/levels/world1/worldmap.stwm");
843 // Load the game or at least set the savegame_file variable
844 worldmap.loadgame(slotfile);
848 Menu::set_current(main_menu);