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;
78 using namespace WorldMapNS;
80 GameSession* GameSession::current_ = 0;
82 GameSession::GameSession(const std::string& levelfile_, GameSessionMode mode,
83 Statistics* statistics)
84 : level(0), currentsector(0), mode(mode),
85 end_sequence(NO_ENDSEQUENCE), end_sequence_controller(0),
86 levelfile(levelfile_), best_level_statistics(statistics),
87 capture_demo_stream(0), playback_demo_stream(0), demo_controller(0)
95 Console::registerCommandReceiver(this);
101 GameSession::restart_level(bool fromBeginning)
104 end_sequence = NO_ENDSEQUENCE;
106 main_controller->reset();
112 level->load(levelfile);
114 global_stats.reset();
115 global_stats.set_total_points(COINS_COLLECTED_STAT, level->get_total_coins());
116 global_stats.set_total_points(BADGUYS_KILLED_STAT, level->get_total_badguys());
120 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
124 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
125 j != sec->gameobjects.end(); ++j)
127 GameObject* obj = *j;
129 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
131 time += int(lt->get_level_time());
134 global_stats.set_total_points(TIME_NEEDED_STAT, (time == 0) ? -1 : time);
136 if (fromBeginning) reset_sector="";
137 if(reset_sector != "") {
138 currentsector = level->get_sector(reset_sector);
140 std::stringstream msg;
141 msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
142 throw std::runtime_error(msg.str());
144 currentsector->activate(reset_pos);
146 currentsector = level->get_sector("main");
148 throw std::runtime_error("Couldn't find main sector");
149 currentsector->activate("main");
152 if(mode == ST_GL_PLAY || mode == ST_GL_LOAD_LEVEL_FILE)
155 currentsector->play_music(LEVEL_MUSIC);
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;
169 Console::unregisterCommandReceiver(this);
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 sound_manager->stop_music();
213 DrawingContext context;
214 for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
215 i != currentsector->gameobjects.end(); ++i) {
216 Background* background = dynamic_cast<Background*> (*i);
218 background->draw(context);
220 Gradient* gradient = dynamic_cast<Gradient*> (*i);
222 gradient->draw(context);
226 // context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
227 // CENTER_ALLIGN, LAYER_FOREGROUND1);
228 context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
231 sprintf(str, "Coins: %d", player_status->coins);
232 context.draw_text(white_text, str, Vector(SCREEN_WIDTH/2, 210),
233 CENTER_ALLIGN, LAYER_FOREGROUND1);
235 if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
236 //TODO make author check case/blank-insensitive
237 context.draw_text(white_small_text,
238 std::string(_("contributed by ")) + level->get_author(),
239 Vector(SCREEN_WIDTH/2, 350), CENTER_ALLIGN, LAYER_FOREGROUND1);
242 if(best_level_statistics != NULL)
243 best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
245 wait_for_event(1.0, 3.0);
249 GameSession::on_escape_press()
251 if(currentsector->player->is_dying() || end_sequence != NO_ENDSEQUENCE)
252 return; // don't let the player open the menu, when he is dying
254 if(mode == ST_GL_TEST) {
255 main_loop->exit_screen();
256 } else if (!Menu::current()) {
257 Menu::set_current(game_menu);
258 game_menu->set_active_item(MNID_CONTINUE);
266 GameSession::process_events()
268 Player& tux = *currentsector->player;
270 // end of pause mode?
271 if(!Menu::current() && game_pause) {
275 if (end_sequence != NO_ENDSEQUENCE) {
276 if(end_sequence_controller == 0) {
277 end_sequence_controller = new CodeController();
278 tux.set_controller(end_sequence_controller);
281 end_sequence_controller->press(Controller::RIGHT);
283 if (int(last_x_pos) == int(tux.get_pos().x))
284 end_sequence_controller->press(Controller::JUMP);
285 last_x_pos = tux.get_pos().x;
289 if(playback_demo_stream != 0) {
290 demo_controller->update();
297 playback_demo_stream->get(left);
298 playback_demo_stream->get(right);
299 playback_demo_stream->get(up);
300 playback_demo_stream->get(down);
301 playback_demo_stream->get(jump);
302 playback_demo_stream->get(action);
303 demo_controller->press(Controller::LEFT, left);
304 demo_controller->press(Controller::RIGHT, right);
305 demo_controller->press(Controller::UP, up);
306 demo_controller->press(Controller::DOWN, down);
307 demo_controller->press(Controller::JUMP, jump);
308 demo_controller->press(Controller::ACTION, action);
311 // save input for demo?
312 if(capture_demo_stream != 0) {
313 capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
314 capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
315 capture_demo_stream ->put(main_controller->hold(Controller::UP));
316 capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
317 capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
318 capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
323 GameSession::consoleCommand(std::string command)
325 if (command == "foo") {
330 //TODO: Build command list automatically
331 if (command == "cmdlist") {
332 msg_info("foo, cmdlist, cheats, whereami, camera");
335 //TODO: remove (or at least hide) this before release
336 if (command == "cheats") {
337 msg_info("grow, fire, ice, lifeup, numberofthebeast, lifedown, grease, invincible, mortal, shrink, kill, gotoend, flip, finish");
341 if (currentsector == 0) return false;
342 Player& tux = *currentsector->player;
344 // Cheating words (the goal of this is really for debugging,
345 // but could be used for some cheating, nothing wrong with that)
346 if (command == "grow") {
347 tux.set_bonus(GROWUP_BONUS, false);
350 if (command == "fire") {
351 tux.set_bonus(FIRE_BONUS, false);
354 if (command == "ice") {
355 tux.set_bonus(ICE_BONUS, false);
358 if (command == "lifeup") {
359 player_status->incLives();
362 if (command == "numberofthebeast") {
363 player_status->coins += 55;
366 if (command == "lifedown") {
367 player_status->coins = std::max(player_status->coins-25, 0);
370 if (command == "grease") {
371 tux.physic.set_velocity_x(tux.physic.get_velocity_x()*3);
374 if (command == "invincible") {
375 // be invincle for the rest of the level
376 tux.invincible_timer.start(10000);
379 if (command == "mortal") {
380 // give up invincibility
381 tux.invincible_timer.stop();
384 if (command == "shrink") {
386 tux.kill(tux.SHRINK);
389 if (command == "kill") {
393 if (command == "whereami") {
394 msg_info("You are at x " << tux.get_pos().x << ", y " << tux.get_pos().y);
398 if(command == "grid")) {
400 debug_grid = !debug_grid;
404 if (command == "gotoend") {
405 // goes to the end of the level
407 (currentsector->solids->get_width()*32) - (SCREEN_WIDTH*2), 0));
408 currentsector->camera->reset(
409 Vector(tux.get_pos().x, tux.get_pos().y));
412 if (command == "flip") {
413 FlipLevelTransformer flip_transformer;
414 flip_transformer.transform(GameSession::current()->get_current_level());
417 if (command == "finish") {
418 if(WorldMap::current() != NULL) {
419 WorldMap::current()->finished_level(levelfile);
424 if (command == "camera") {
425 msg_info("Camera is at "
426 << Sector::current()->camera->get_translation().x << ","
427 << Sector::current()->camera->get_translation().y);
435 GameSession::check_end_conditions()
437 Player* tux = currentsector->player;
440 if(end_sequence && endsequence_timer.check()) {
443 // add time spent to statistics
444 int tottime = 0, remtime = 0;
445 for(std::vector<Sector*>::iterator i = level->sectors.begin(); i != level->sectors.end(); ++i)
449 for(std::vector<GameObject*>::iterator j = sec->gameobjects.begin();
450 j != sec->gameobjects.end(); ++j)
452 GameObject* obj = *j;
454 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
457 tottime += int(lt->get_level_time());
458 remtime += int(lt->get_remaining_time());
462 global_stats.set_points(TIME_NEEDED_STAT, (tottime == 0 ? -1 : (tottime-remtime)));
465 } else if (!end_sequence && tux->is_dead()) {
466 if (player_status->coins < 0) {
467 // No more coins: restart level from beginning
468 player_status->coins = 0;
471 // Still has coins: restart level from last reset point
472 restart_level(false);
480 GameSession::draw(DrawingContext& context)
482 currentsector->draw(context);
490 GameSession::draw_pause(DrawingContext& context)
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 main_loop->exit_screen();
514 } else if(menu == options_menu) {
515 process_options_menu();
523 Menu::set_current(NULL);
526 // Eat unneeded events
528 while(SDL_PollEvent(&event))
533 GameSession::update(float elapsed_time)
538 check_end_conditions();
541 if(main_controller->pressed(Controller::PAUSE_MENU))
544 // respawning in new sector?
545 if(newsector != "" && newspawnpoint != "") {
546 Sector* sector = level->get_sector(newsector);
548 msg_warning("Sector '" << newsector << "' not found");
550 sector->activate(newspawnpoint);
551 sector->play_music(LEVEL_MUSIC);
552 currentsector = sector;
557 // Update the world state and all objects in the world
560 if (end_sequence == ENDSEQUENCE_RUNNING) {
561 currentsector->update(elapsed_time/2);
562 } else if(end_sequence == NO_ENDSEQUENCE) {
563 if(!currentsector->player->growing_timer.started())
564 currentsector->update(elapsed_time);
569 sound_manager->set_listener_position(currentsector->player->get_pos());
572 if (currentsector->player->invincible_timer.started() &&
573 currentsector->player->invincible_timer.get_timeleft()
574 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence) {
575 currentsector->play_music(HERRING_MUSIC);
576 } else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence) {
577 currentsector->play_music(LEVEL_MUSIC);
582 GameSession::ExitStatus
585 Menu::set_current(0);
590 // Eat unneeded events
592 while(SDL_PollEvent(&event))
597 Uint32 fps_ticks = SDL_GetTicks();
598 Uint32 fps_nextframe_ticks = SDL_GetTicks();
600 bool skipdraw = false;
602 while (exit_status == ES_NONE) {
603 // we run in a logical framerate so elapsed time is a constant
604 // This will make the game run determistic and not different on different
606 static const float elapsed_time = 1.0 / LOGICAL_FPS;
607 // old code... float elapsed_time = float(ticks - lastticks) / 1000.;
609 game_time += elapsed_time;
612 ticks = SDL_GetTicks();
613 if(ticks > fps_nextframe_ticks) {
614 if(skipdraw == true) {
615 // already skipped last frame? we have to slow down the game then...
617 fps_nextframe_ticks -= (Uint32) (1000.0 / LOGICAL_FPS);
619 // don't draw all frames when we're getting too slow
624 while(fps_nextframe_ticks > ticks) {
626 // If we really have to wait long, then do an imprecise SDL_Delay()
627 Uint32 diff = fps_nextframe_ticks - ticks;
629 SDL_Delay(diff - 10);
631 ticks = SDL_GetTicks();
634 fps_nextframe_ticks = ticks + (Uint32) (1000.0 / LOGICAL_FPS);
639 // Update the world state and all objects in the world
643 check_end_conditions();
644 if (end_sequence == ENDSEQUENCE_RUNNING)
645 update(elapsed_time/2);
646 else if(end_sequence == NO_ENDSEQUENCE)
647 update(elapsed_time);
654 sound_manager->update();
656 /* Time stops in pause mode */
657 if(game_pause || Menu::current())
663 if (currentsector->player->invincible_timer.started() &&
664 currentsector->player->invincible_timer.get_timeleft()
665 > TUX_INVINCIBLE_TIME_WARNING && !end_sequence)
667 currentsector->play_music(HERRING_MUSIC);
669 /* or just normal music? */
670 else if(currentsector->get_music_type() != LEVEL_MUSIC && !end_sequence)
672 currentsector->play_music(LEVEL_MUSIC);
675 /* Calculate frames per second */
680 if(SDL_GetTicks() - fps_ticks >= 500)
682 fps_fps = (float) fps_cnt / .5;
684 fps_ticks = SDL_GetTicks();
691 main_controller->reset();
697 GameSession::finish(bool win)
700 if(WorldMap::current())
701 WorldMap::current()->finished_level(levelfile);
704 main_loop->exit_screen();
708 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
711 newspawnpoint = spawnpoint;
715 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
717 reset_sector = sector;
722 GameSession::get_working_directory()
724 return FileSystem::dirname(levelfile);
728 GameSession::display_info_box(const std::string& text)
730 InfoBox* box = new InfoBox(text);
733 DrawingContext context;
737 main_controller->update();
739 while (SDL_PollEvent(&event)) {
740 main_controller->process_event(event);
741 if(event.type == SDL_QUIT)
742 throw graceful_shutdown();
745 if(main_controller->pressed(Controller::JUMP)
746 || main_controller->pressed(Controller::ACTION)
747 || main_controller->pressed(Controller::PAUSE_MENU)
748 || main_controller->pressed(Controller::MENU_SELECT))
750 else if(main_controller->pressed(Controller::DOWN))
752 else if(main_controller->pressed(Controller::UP))
756 context.do_drawing();
757 sound_manager->update();
764 GameSession::start_sequence(const std::string& sequencename)
766 if(sequencename == "endsequence" || sequencename == "fireworks") {
770 end_sequence = ENDSEQUENCE_RUNNING;
771 endsequence_timer.start(7.3);
773 sound_manager->play_music("music/leveldone.ogg", false);
774 currentsector->player->invincible_timer.start(7.3);
777 for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
778 i != currentsector->gameobjects.end(); ++i)
780 GameObject* obj = *i;
782 LevelTime* lt = dynamic_cast<LevelTime*> (obj);
787 if(sequencename == "fireworks") {
788 currentsector->add_object(new Fireworks());
790 } else if(sequencename == "stoptux") {
792 msg_warning("Final target reached without "
793 << "an active end sequence");
794 this->start_sequence("endsequence");
796 end_sequence = ENDSEQUENCE_WAITING;
798 msg_warning("Unknown sequence '" << sequencename << "'");
804 GameSession::drawstatus(DrawingContext& context)
806 player_status->draw(context);
808 if(config->show_fps) {
810 snprintf(str, sizeof(str), "%3.1f", fps_fps);
811 const char* fpstext = "FPS";
812 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);
813 context.draw_text(gold_text, str, Vector(SCREEN_WIDTH - BORDER_X, BORDER_Y + 20), RIGHT_ALLIGN, LAYER_FOREGROUND1);