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 "worldmap.hpp"
40 #include "mainloop.hpp"
41 #include "video/screen.hpp"
42 #include "audio/sound_manager.hpp"
43 #include "gui/menu.hpp"
47 #include "player_status.hpp"
48 #include "object/particlesystem.hpp"
49 #include "object/background.hpp"
50 #include "object/gradient.hpp"
51 #include "object/tilemap.hpp"
52 #include "object/camera.hpp"
53 #include "object/player.hpp"
54 #include "object/level_time.hpp"
55 #include "lisp/lisp.hpp"
56 #include "lisp/parser.hpp"
57 #include "resources.hpp"
58 #include "worldmap.hpp"
60 #include "statistics.hpp"
62 #include "object/fireworks.hpp"
63 #include "textscroller.hpp"
64 #include "control/codecontroller.hpp"
65 #include "control/joystickkeyboardcontroller.hpp"
67 #include "file_system.hpp"
68 #include "gameconfig.hpp"
69 #include "gettext.hpp"
70 #include "exceptions.hpp"
71 #include "flip_level_transformer.hpp"
73 // the engine will be run with a logical framerate of 64fps.
74 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
76 static const float LOGICAL_FPS = 64.0;
79 const char* consoleCommands[] = {
102 using namespace WorldMapNS;
104 GameSession* GameSession::current_ = 0;
106 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
107 Statistics* statistics)
108 : level(0), currentsector(0), mode(mode),
109 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
110 levelfile(levelfile_), best_level_statistics(statistics),
111 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
119 for (uint16_t i=0; i < sizeof(::consoleCommands)/sizeof(typeof(consoleCommands[0])); i++) {
120 Console::registerCommand(consoleCommands[i], this);
127 GameSession::restart_level(bool fromBeginning)
130 end_sequence = NO_ENDSEQUENCE;
132 main_controller->reset();
138 level->load(levelfile);
140 global_stats.reset();
141 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
142 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
146 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
150 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
151 j != sec->gameobjects.end(); ++j)
153 GameObject* obj = *j;
155 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
157 time += int(lt->get_level_time());
160 global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
162 if (fromBeginning) reset_sector="";
163 if(reset_sector != "") {
164 currentsector = level->get_sector(reset_sector);
166 std::stringstream msg;
167 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
168 throw std::runtime_error(msg.str());
170 currentsector->activate(reset_pos);
172 currentsector = level->get_sector("main");
174 throw std::runtime_error("Couldn't find main sector");
175 currentsector->activate("main");
178 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
181 currentsector->play_music(LEVEL_MUSIC);
183 if(capture_file != "")
184 record_demo(capture_file);
187 GameSession::~GameSession()
189 delete capture_demo_stream;
190 delete playback_demo_stream;
191 delete demo_controller;
193 delete end_sequence_controller;
195 for (uint16_t i=0; i < sizeof(::consoleCommands)/sizeof(typeof(consoleCommands[0])); i++) {
196 Console::unregisterCommand(consoleCommands[i], this);
203 GameSession::record_demo(const std::string& filename)
205 delete capture_demo_stream;
207 capture_demo_stream = new std::ofstream(filename.c_str());
208 if(!capture_demo_stream->good()) {
209 std::stringstream msg;
210 msg << "Couldn't open demo file '" << filename << "' for writing.";
211 throw std::runtime_error(msg.str());
213 capture_file = filename;
217 GameSession::play_demo(const std::string& filename)
219 delete playback_demo_stream;
220 delete demo_controller;
222 playback_demo_stream = new std::ifstream(filename.c_str());
223 if(!playback_demo_stream->good()) {
224 std::stringstream msg;
225 msg << "Couldn't open demo file '" << filename << "' for reading.";
226 throw std::runtime_error(msg.str());
229 Player& tux = *currentsector->player;
230 demo_controller = new CodeController();
231 tux.set_controller(demo_controller);
235 GameSession::levelintro()
239 sound_manager->stop_music();
241 DrawingContext context;
242 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
243 i != currentsector->gameobjects.end(); ++i) {
244 Background* background = dynamic_cast<Background*> (*i);
246 background->draw(context);
248 Gradient* gradient = dynamic_cast<Gradient*> (*i);
250 gradient->draw(context);
254 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
255 // CENTER_ALLIGN, LAYER_FOREGROUND1);
256 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
259 sprintf(str, "Coins: %d", player_status->coins);
260 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
261 CENTER_ALLIGN, LAYER_FOREGROUND1);
263 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
264 //TODO make author check case/blank-insensitive
265 context.draw_text(white_small_text,
266 std::string(_("contributed by ")) + level->get_author(),
267 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
270 if(best_level_statistics != NULL)
271 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
273 wait_for_event(1.0, 3.0);
277 GameSession::on_escape_press()
279 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
280 return; // don't let the player open the menu, when he is dying
282 if(mode == ST_GL_TEST) {
283 main_loop->exit_screen();
284 } else if (!Menu::current()) {
285 Menu::set_current(game_menu);
286 game_menu->set_active_item(MNID_CONTINUE);
294 GameSession::process_events()
296 Player& tux = *currentsector->player;
298 // end of pause mode?
299 if(!Menu::current() && game_pause) {
303 if (end_sequence != NO_ENDSEQUENCE) {
304 if(end_sequence_controller == 0) {
305 end_sequence_controller = new CodeController();
306 tux.set_controller(end_sequence_controller);
309 end_sequence_controller->press(Controller::RIGHT);
311 if (int(last_x_pos) == int(tux.get_pos().x))
312 end_sequence_controller->press(Controller::JUMP);
313 last_x_pos = tux.get_pos().x;
317 if(playback_demo_stream != 0) {
318 demo_controller->update();
325 playback_demo_stream->get(left);
326 playback_demo_stream->get(right);
327 playback_demo_stream->get(up);
328 playback_demo_stream->get(down);
329 playback_demo_stream->get(jump);
330 playback_demo_stream->get(action);
331 demo_controller->press(Controller::LEFT, left);
332 demo_controller->press(Controller::RIGHT, right);
333 demo_controller->press(Controller::UP, up);
334 demo_controller->press(Controller::DOWN, down);
335 demo_controller->press(Controller::JUMP, jump);
336 demo_controller->press(Controller::ACTION, action);
339 // save input for demo?
340 if(capture_demo_stream != 0) {
341 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
342 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
343 capture_demo_stream ->put(main_controller->hold(Controller::UP));
344 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
345 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
346 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
351 GameSession::consoleCommand(std::string command)
353 if (command == "foo") {
354 msg_info << "bar" << std::endl;
358 if (currentsector == 0) return false;
359 Player& tux = *currentsector->player;
361 // Cheating words (the goal of this is really for debugging,
362 // but could be used for some cheating, nothing wrong with that)
363 if (command == "grow") {
364 tux.set_bonus(GROWUP_BONUS, false);
367 if (command == "fire") {
368 tux.set_bonus(FIRE_BONUS, false);
371 if (command == "ice") {
372 tux.set_bonus(ICE_BONUS, false);
375 if (command == "lifeup") {
376 player_status->incLives();
379 if (command == "numberofthebeast") {
380 player_status->coins += 55;
383 if (command == "lifedown") {
384 player_status->coins = std::max(player_status->coins-25, 0);
387 if (command == "grease") {
388 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
391 if (command == "invincible") {
392 // be invincle for the rest of the level
393 tux.invincible_timer.start(10000);
396 if (command == "mortal") {
397 // give up invincibility
398 tux.invincible_timer.stop();
401 if (command == "shrink") {
403 tux.kill(tux.SHRINK);
406 if (command == "kill") {
410 if (command == "restart") {
414 if (command == "whereami") {
415 msg_info << "You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y << std::endl;
418 if (command == "gotoend") {
419 // goes to the end of the level
421 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
422 currentsector->camera->reset(
423 Vector(tux.get_pos().x, tux.get_pos().y));
426 if (command == "flip") {
427 FlipLevelTransformer flip_transformer;
428 flip_transformer.transform(GameSession::current()->get_current_level());
431 if (command == "finish") {
435 if (command == "camera") {
436 msg_info << "Camera is at " << Sector::current()->camera->get_translation().x << "," << Sector::current()->camera->get_translation().y << std::endl;
439 if (command == "quit") {
440 msg_info << "Please implement me! :-)" << std::endl;
448 GameSession::check_end_conditions()
450 Player* tux = currentsector->player;
453 if(end_sequence && endsequence_timer.check()) {
456 // add time spent to statistics
457 int tottime = 0, remtime = 0;
458 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
462 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
463 j != sec->gameobjects.end(); ++j)
465 GameObject* obj = *j;
467 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
470 tottime += int(lt->get_level_time());
471 remtime += int(lt->get_remaining_time());
475 global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
478 } else if (!end_sequence && tux->is_dead()) {
479 if (player_status->coins < 0) {
480 // No more coins: restart level from beginning
481 player_status->coins = 0;
484 // Still has coins: restart level from last reset point
485 restart_level(false);
493 GameSession::draw(DrawingContext& context)
495 currentsector->draw(context);
503 GameSession::draw_pause(DrawingContext& context)
505 context.draw_filled_rect(
506 Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
507 Color(.2, .2, .2, .5), LAYER_FOREGROUND1);
511 GameSession::process_menu()
513 Menu* menu = Menu::current();
517 if(menu == game_menu) {
518 switch (game_menu->check()) {
520 Menu::set_current(0);
522 case MNID_ABORTLEVEL:
523 Menu::set_current(0);
524 main_loop->exit_screen();
527 } else if(menu == options_menu) {
528 process_options_menu();
536 Menu::set_current(NULL);
539 // Eat unneeded events
541 while(SDL_PollEvent(&event))
546 GameSession::update(float elapsed_time)
551 check_end_conditions();
554 if(main_controller->pressed(Controller::PAUSE_MENU))
557 // respawning in new sector?
558 if(newsector != "" && newspawnpoint != "") {
559 Sector* sector = level->get_sector(newsector);
561 msg_warning << "Sector '" << newsector << "' not found" << std::endl;
563 sector->activate(newspawnpoint);
564 sector->play_music(LEVEL_MUSIC);
565 currentsector = sector;
570 // Update the world state and all objects in the world
573 if (end_sequence == ENDSEQUENCE_RUNNING) {
574 currentsector->update(elapsed_time/2);
575 } else if(end_sequence == NO_ENDSEQUENCE) {
576 if(!currentsector->player->growing_timer.started())
577 currentsector->update(elapsed_time);
582 sound_manager->set_listener_position(currentsector->player->get_pos());
585 if (currentsector->player->invincible_timer.started() &&
586 currentsector->player->invincible_timer.get_timeleft()
587 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence) {
588 currentsector->play_music(HERRING_MUSIC);
589 } else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence) {
590 currentsector->play_music(LEVEL_MUSIC);
595 GameSession::ExitStatus
598 Menu::set_current(0);
603 // Eat unneeded events
605 while(SDL_PollEvent(&event))
610 Uint32 fps_ticks = SDL_GetTicks();
611 Uint32 fps_nextframe_ticks = SDL_GetTicks();
613 bool skipdraw = false;
615 while (exit_status == ES_NONE) {
616 // we run in a logical framerate so elapsed time is a constant
617 // This will make the game run determistic and not different on different
619 static const float elapsed_time = 1.0 / LOGICAL_FPS;
620 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
622 game_time += elapsed_time;
625 ticks = SDL_GetTicks();
626 if(ticks > fps_nextframe_ticks) {
627 if(skipdraw == true) {
628 // already skipped last frame? we have to slow down the game then...
630 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
632 // don't draw all frames when we're getting too slow
637 while(fps_nextframe_ticks > ticks) {
639 // If we really have to wait long, then do an imprecise SDL_Delay()
640 Uint32 diff = fps_nextframe_ticks - ticks;
642 SDL_Delay(diff - 10);
644 ticks = SDL_GetTicks();
647 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
652 // Update the world state and all objects in the world
656 check_end_conditions();
657 if (end_sequence == ENDSEQUENCE_RUNNING)
658 update(elapsed_time/2);
659 else if(end_sequence == NO_ENDSEQUENCE)
660 update(elapsed_time);
667 sound_manager->update();
669 /* Time stops in pause mode */
670 if(game_pause || Menu::current())
676 if (currentsector->player->invincible_timer.started() &&
677 currentsector->player->invincible_timer.get_timeleft()
678 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
680 currentsector->play_music(HERRING_MUSIC);
682 /* or just normal music? */
683 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
685 currentsector->play_music(LEVEL_MUSIC);
688 /* Calculate frames per second */
693 if(SDL_GetTicks() - fps_ticks >= 500)
695 fps_fps = (float) fps_cnt / .5;
697 fps_ticks = SDL_GetTicks();
704 main_controller->reset();
710 GameSession::finish(bool win)
713 if(WorldMap::current())
714 WorldMap::current()->finished_level(levelfile);
717 main_loop->exit_screen();
721 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
724 newspawnpoint = spawnpoint;
728 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
730 reset_sector = sector;
735 GameSession::get_working_directory()
737 return FileSystem::dirname(levelfile);
741 GameSession::display_info_box(const std::string& text)
743 InfoBox* box = new InfoBox(text);
746 DrawingContext context;
750 main_controller->update();
752 while (SDL_PollEvent(&event)) {
753 main_controller->process_event(event);
754 if(event.type == SDL_QUIT)
755 throw graceful_shutdown();
758 if(main_controller->pressed(Controller::JUMP)
759 || main_controller->pressed(Controller::ACTION)
760 || main_controller->pressed(Controller::PAUSE_MENU)
761 || main_controller->pressed(Controller::MENU_SELECT))
763 else if(main_controller->pressed(Controller::DOWN))
765 else if(main_controller->pressed(Controller::UP))
769 context.do_drawing();
770 sound_manager->update();
777 GameSession::start_sequence(const std::string& sequencename)
779 if(sequencename == "endsequence" || sequencename == "fireworks") {
783 end_sequence = ENDSEQUENCE_RUNNING;
784 endsequence_timer.start(7.3);
786 sound_manager->play_music("music/leveldone.ogg", false);
787 currentsector->player->invincible_timer.start(7.3);
790 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
791 i != currentsector->gameobjects.end(); ++i)
793 GameObject* obj = *i;
795 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
800 if(sequencename == "fireworks") {
801 currentsector->add_object(new Fireworks());
803 } else if(sequencename == "stoptux") {
805 msg_warning << "Final target reached without an active end sequence" << std::endl;
806 this->start_sequence("endsequence");
808 end_sequence = ENDSEQUENCE_WAITING;
810 msg_warning << "Unknown sequence '" << sequencename << "'" << std::endl;
816 GameSession::drawstatus(DrawingContext& context)
818 player_status->draw(context);
820 if(config->show_fps) {
822 snprintf(str, sizeof(str), "%3.1f", fps_fps);
823 const char* fpstext = "FPS";
824 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);
825 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), RIGHT_ALLIGN, LAYER_FOREGROUND1);