84893569f462cb26b6bafff646855aabdea7494e
[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 <assert.h>
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <math.h>
27 #include <string.h>
28 #include <errno.h>
29 #include <unistd.h>
30 #include <time.h>
31 #include <stdexcept>
32
33 #include <SDL.h>
34
35 #include "game_session.hpp"
36 #include "log.hpp"
37 #include "console.hpp"
38 #include "worldmap/worldmap.hpp"
39 #include "mainloop.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 "statistics.hpp"
57 #include "timer.hpp"
58 #include "options_menu.hpp"
59 #include "textscroller.hpp"
60 #include "control/codecontroller.hpp"
61 #include "control/joystickkeyboardcontroller.hpp"
62 #include "main.hpp"
63 #include "file_system.hpp"
64 #include "gameconfig.hpp"
65 #include "gettext.hpp"
66 #include "console.hpp"
67 #include "flip_level_transformer.hpp"
68 #include "trigger/secretarea_trigger.hpp"
69 #include "trigger/sequence_trigger.hpp"
70 #include "random_generator.hpp"
71 #include "scripting/squirrel_util.hpp"
72 #include "object/endsequence_walkright.hpp"
73 #include "object/endsequence_walkleft.hpp"
74 #include "object/endsequence_fireworks.hpp"
75 #include "direction.hpp"
76 #include "scripting/time_scheduler.hpp"
77
78 // the engine will be run with a logical framerate of 64fps.
79 // We chose 64fps here because it is a power of 2, so 1/64 gives an "even"
80 // binary fraction...
81 static const float LOGICAL_FPS = 64.0;
82
83 enum GameMenuIDs {
84   MNID_CONTINUE,
85   MNID_ABORTLEVEL
86 };
87
88 GameSession* GameSession::current_ = NULL;
89
90 GameSession::GameSession(const std::string& levelfile_, Statistics* statistics)
91   : level(0), currentsector(0),
92     end_sequence(0),
93     levelfile(levelfile_), best_level_statistics(statistics),
94     capture_demo_stream(0), playback_demo_stream(0), demo_controller(0),
95     play_time(0), edit_mode(false)
96 {
97   current_ = this;
98   currentsector = NULL;
99
100   game_pause = false;
101   speed_before_pause = main_loop->get_speed();
102
103   statistics_backdrop.reset(new Surface("images/engine/menu/score-backdrop.png"));
104
105   restart_level();
106
107   game_menu.reset(new Menu());
108   game_menu->add_label(_("Pause"));
109   game_menu->add_hl();
110   game_menu->add_entry(MNID_CONTINUE, _("Continue"));
111   game_menu->add_submenu(_("Options"), get_options_menu());
112   game_menu->add_hl();
113   game_menu->add_entry(MNID_ABORTLEVEL, _("Abort Level"));
114 }
115
116 void
117 GameSession::restart_level()
118 {
119
120   if (edit_mode) {
121     force_ghost_mode();
122     return;
123   }
124
125   game_pause   = false;
126   end_sequence = 0;
127
128   main_controller->reset();
129
130   currentsector = 0;
131
132   level.reset(new Level);
133   level->load(levelfile);
134   level->stats.total_coins = level->get_total_coins();
135   level->stats.total_badguys = level->get_total_badguys();
136   level->stats.total_secrets = level->get_total_count<SecretAreaTrigger>();
137   level->stats.reset();
138
139   if(reset_sector != "") {
140     currentsector = level->get_sector(reset_sector);
141     if(!currentsector) {
142       std::stringstream msg;
143       msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
144       throw std::runtime_error(msg.str());
145     }
146     level->stats.declare_invalid();
147     currentsector->activate(reset_pos);
148   } else {
149     currentsector = level->get_sector("main");
150     if(!currentsector)
151       throw std::runtime_error("Couldn't find main sector");
152     play_time = 0;
153     currentsector->activate("main");
154   }
155
156   //levelintro();
157
158   sound_manager->stop_music();
159   currentsector->play_music(LEVEL_MUSIC);
160
161   if(capture_file != "") {
162     int newSeed=0;               // next run uses a new seed
163     while (newSeed == 0)            // which is the next non-zero random num.
164         newSeed = systemRandom.rand();
165     config->random_seed = systemRandom.srand(newSeed);
166     log_info << "Next run uses random seed " <<config->random_seed <<std::endl;
167     record_demo(capture_file);
168   }
169 }
170
171 GameSession::~GameSession()
172 {
173   delete capture_demo_stream;
174   delete playback_demo_stream;
175   delete demo_controller;
176   free_options_menu();
177
178   current_ = NULL;
179 }
180
181 void
182 GameSession::record_demo(const std::string& filename)
183 {
184   delete capture_demo_stream;
185
186   capture_demo_stream = new std::ofstream(filename.c_str());
187   if(!capture_demo_stream->good()) {
188     std::stringstream msg;
189     msg << "Couldn't open demo file '" << filename << "' for writing.";
190     throw std::runtime_error(msg.str());
191   }
192   capture_file = filename;
193
194   char buf[30];                            // save the seed in the demo file
195   snprintf(buf, sizeof(buf), "random_seed=%10d", config->random_seed);
196   for (int i=0; i==0 || buf[i-1]; i++)
197     capture_demo_stream->put(buf[i]);
198 }
199
200 int
201 GameSession::get_demo_random_seed(const std::string& filename)
202 {
203   std::istream* test_stream = new std::ifstream(filename.c_str());
204   if(test_stream->good()) {
205     char buf[30];                     // recall the seed from the demo file
206     int seed;
207     for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
208       test_stream->get(buf[i]);
209     if (sscanf(buf, "random_seed=%10d", &seed) == 1) {
210       log_info << "Random seed " << seed << " from demo file" << std::endl;
211          return seed;
212     }
213     else
214       log_info << "Demo file contains no random number" << std::endl;
215   }
216   return 0;
217 }
218
219 void
220 GameSession::play_demo(const std::string& filename)
221 {
222   delete playback_demo_stream;
223   delete demo_controller;
224
225   playback_demo_stream = new std::ifstream(filename.c_str());
226   if(!playback_demo_stream->good()) {
227     std::stringstream msg;
228     msg << "Couldn't open demo file '" << filename << "' for reading.";
229     throw std::runtime_error(msg.str());
230   }
231
232   Player& tux = *currentsector->player;
233   demo_controller = new CodeController();
234   tux.set_controller(demo_controller);
235
236   // skip over random seed, if it exists in the file
237   char buf[30];                            // ascii decimal seed
238   int seed;
239   for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
240     playback_demo_stream->get(buf[i]);
241   if (sscanf(buf, "random_seed=%010d", &seed) != 1)
242     playback_demo_stream->seekg(0);     // old style w/o seed, restart at beg
243 }
244
245 void
246 GameSession::levelintro()
247 {
248   sound_manager->stop_music();
249
250   DrawingContext context;
251   for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
252       i != currentsector->gameobjects.end(); ++i) {
253     Background* background = dynamic_cast<Background*> (*i);
254     if(background) {
255       background->draw(context);
256     }
257     Gradient* gradient = dynamic_cast<Gradient*> (*i);
258     if(gradient) {
259       gradient->draw(context);
260     }
261   }
262
263 //  context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
264 //      ALIGN_CENTER, LAYER_FOREGROUND1);
265   context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
266       LAYER_FOREGROUND1);
267
268   std::stringstream ss_coins;
269   ss_coins << _("Coins") << ": " << player_status->coins;
270   context.draw_text(white_text, ss_coins.str(), Vector(SCREEN_WIDTH/2, 210),
271       ALIGN_CENTER, LAYER_FOREGROUND1);
272
273   if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
274     context.draw_text(white_small_text,
275       std::string(_("contributed by ")) + level->get_author(),
276       Vector(SCREEN_WIDTH/2, 350), ALIGN_CENTER, LAYER_FOREGROUND1);
277
278   if(best_level_statistics != NULL)
279     best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
280
281   wait_for_event(1.0, 3.0);
282 }
283
284 void
285 GameSession::on_escape_press()
286 {
287   if(currentsector->player->is_dying() || end_sequence)
288   {
289     // Let the timers run out, we fast-forward them to force past a sequence
290     if (end_sequence)
291       end_sequence->stop();
292
293     currentsector->player->dying_timer.start(FLT_EPSILON);
294     return;   // don't let the player open the menu, when he is dying
295   }
296
297   if(level->on_menukey_script != "") {
298     std::istringstream in(level->on_menukey_script);
299     run_script(in, "OnMenuKeyScript");
300   } else {
301     toggle_pause();
302   }
303 }
304
305 void
306 GameSession::toggle_pause()
307 {
308   if(!game_pause) {
309     speed_before_pause = main_loop->get_speed();
310     main_loop->set_speed(0);
311     Menu::set_current(game_menu.get());
312     game_menu->set_active_item(MNID_CONTINUE);
313     game_pause = true;
314   } else {
315     main_loop->set_speed(speed_before_pause);
316     Menu::set_current(NULL);
317     game_pause = false;
318   }
319 }
320
321 void
322 GameSession::set_editmode(bool edit_mode)
323 {
324   if (this->edit_mode == edit_mode) return;
325   this->edit_mode = edit_mode;
326
327   currentsector->get_players()[0]->set_edit_mode(edit_mode);
328
329   if (edit_mode) {
330
331     // entering edit mode
332
333   } else {
334
335     // leaving edit mode
336     restart_level();
337
338   }
339 }
340
341 void
342 GameSession::force_ghost_mode()
343 {
344   currentsector->get_players()[0]->set_ghost_mode(true);
345 }
346
347 HSQUIRRELVM
348 GameSession::run_script(std::istream& in, const std::string& sourcename)
349 {
350   using namespace Scripting;
351
352   // garbage collect thread list
353   for(ScriptList::iterator i = scripts.begin();
354       i != scripts.end(); ) {
355     HSQOBJECT& object = *i;
356     HSQUIRRELVM vm = object_to_vm(object);
357
358     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
359       sq_release(global_vm, &object);
360       i = scripts.erase(i);
361       continue;
362     }
363
364     ++i;
365   }
366
367   HSQOBJECT object = create_thread(global_vm);
368   scripts.push_back(object);
369
370   HSQUIRRELVM vm = object_to_vm(object);
371
372   compile_and_run(vm, in, sourcename);
373
374   return vm;
375 }
376
377 void
378 GameSession::process_events()
379 {
380   // end of pause mode?
381   // XXX this looks like a fail-safe to unpause the game if there's no menu
382   // XXX having it enabled causes some unexpected problems
383   // XXX hopefully disabling it won't...
384   /*
385   if(!Menu::current() && game_pause) {
386     game_pause = false;
387   }
388   */
389
390   // playback a demo?
391   if(playback_demo_stream != 0) {
392     demo_controller->update();
393     char left = false;
394     char right = false;
395     char up = false;
396     char down = false;
397     char jump = false;
398     char action = false;
399     playback_demo_stream->get(left);
400     playback_demo_stream->get(right);
401     playback_demo_stream->get(up);
402     playback_demo_stream->get(down);
403     playback_demo_stream->get(jump);
404     playback_demo_stream->get(action);
405     demo_controller->press(Controller::LEFT, left);
406     demo_controller->press(Controller::RIGHT, right);
407     demo_controller->press(Controller::UP, up);
408     demo_controller->press(Controller::DOWN, down);
409     demo_controller->press(Controller::JUMP, jump);
410     demo_controller->press(Controller::ACTION, action);
411   }
412
413   // save input for demo?
414   if(capture_demo_stream != 0) {
415     capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
416     capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
417     capture_demo_stream ->put(main_controller->hold(Controller::UP));
418     capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
419     capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
420     capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
421   }
422 }
423
424 void
425 GameSession::check_end_conditions()
426 {
427   Player* tux = currentsector->player;
428
429   /* End of level? */
430   if(end_sequence && end_sequence->is_done()) {
431     finish(true);
432   } else if (!end_sequence && tux->is_dead()) {
433     restart_level();
434   }
435 }
436
437 void
438 GameSession::draw(DrawingContext& context)
439 {
440   currentsector->draw(context);
441   drawstatus(context);
442
443   if(game_pause)
444     draw_pause(context);
445 }
446
447 void
448 GameSession::draw_pause(DrawingContext& context)
449 {
450   context.draw_filled_rect(
451       Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
452       Color(0.0f, 0.0f, 0.0f, .25f), LAYER_FOREGROUND1);
453 }
454
455 void
456 GameSession::process_menu()
457 {
458   Menu* menu = Menu::current();
459   if(menu) {
460     menu->update();
461
462     if(menu == game_menu.get()) {
463       switch (game_menu->check()) {
464         case MNID_CONTINUE:
465           Menu::set_current(0);
466           toggle_pause();
467           break;
468         case MNID_ABORTLEVEL:
469           Menu::set_current(0);
470           main_loop->exit_screen();
471           break;
472       }
473     }
474   }
475 }
476
477 void
478 GameSession::setup()
479 {
480   Menu::set_current(NULL);
481   current_ = this;
482
483   if(currentsector != Sector::current()) {
484         currentsector->activate(currentsector->player->get_pos());
485   }
486   currentsector->play_music(LEVEL_MUSIC);
487
488   // Eat unneeded events
489   SDL_Event event;
490   while(SDL_PollEvent(&event))
491   {}
492 }
493
494 void
495 GameSession::update(float elapsed_time)
496 {
497   // handle controller
498   if(main_controller->pressed(Controller::PAUSE_MENU))
499     on_escape_press();
500
501   process_events();
502   process_menu();
503
504   check_end_conditions();
505
506   // respawning in new sector?
507   if(newsector != "" && newspawnpoint != "") {
508     Sector* sector = level->get_sector(newsector);
509     if(sector == 0) {
510       log_warning << "Sector '" << newsector << "' not found" << std::endl;
511     }
512     sector->activate(newspawnpoint);
513     sector->play_music(LEVEL_MUSIC);
514     currentsector = sector;
515     newsector = "";
516     newspawnpoint = "";
517   }
518
519   // Update the world state and all objects in the world
520   if(!game_pause) {
521     // Update the world
522     if (!end_sequence) {
523       play_time += elapsed_time; //TODO: make sure we don't count cutscene time
524       level->stats.time = play_time;
525       currentsector->update(elapsed_time);
526     } else {
527       if (!end_sequence->is_tux_stopped()) {
528         currentsector->update(elapsed_time);
529       } else {
530         end_sequence->update(elapsed_time);
531       }
532     }
533   }
534
535   // update sounds
536   if (currentsector && currentsector->camera) sound_manager->set_listener_position(currentsector->camera->get_center());
537
538   /* Handle music: */
539   if (end_sequence)
540     return;
541
542   if(currentsector->player->invincible_timer.started()) {
543     if(currentsector->player->invincible_timer.get_timeleft() <=
544        TUX_INVINCIBLE_TIME_WARNING) {
545       currentsector->play_music(HERRING_WARNING_MUSIC);
546     } else {
547       currentsector->play_music(HERRING_MUSIC);
548     }
549   } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
550     currentsector->play_music(LEVEL_MUSIC);
551   }
552 }
553
554 void
555 GameSession::finish(bool win)
556 {
557   using namespace WorldMapNS;
558
559   if (edit_mode) {
560     force_ghost_mode();
561     return;
562   }
563
564   if(win) {
565     if(WorldMap::current())
566       WorldMap::current()->finished_level(level.get());
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::start_sequence(const std::string& sequencename)
594 {
595   // do not play sequences when in edit mode
596   if (edit_mode) {
597     force_ghost_mode();
598     return;
599   }
600
601   // handle special "stoptux" sequence
602   if (sequencename == "stoptux") {
603     if (!end_sequence) {
604       log_warning << "Final target reached without an active end sequence" << std::endl;
605       this->start_sequence("endsequence");
606     }
607     if (end_sequence) end_sequence->stop_tux();
608     return;
609   }
610
611   // abort if a sequence is already playing
612   if (end_sequence)
613           return;
614
615   if (sequencename == "endsequence") {
616     if (currentsector->get_players()[0]->physic.get_velocity_x() < 0) {
617       end_sequence = new EndSequenceWalkLeft();
618     } else {
619       end_sequence = new EndSequenceWalkRight();
620     }
621   } else if (sequencename == "fireworks") {
622     end_sequence = new EndSequenceFireworks();
623   } else {
624     log_warning << "Unknown sequence '" << sequencename << "'. Ignoring." << std::endl;
625     return;
626   }
627
628   /* slow down the game for end-sequence */
629   main_loop->set_speed(0.5f);
630
631   currentsector->add_object(end_sequence);
632   end_sequence->start();
633
634   sound_manager->play_music("music/leveldone.ogg", false);
635   currentsector->player->invincible_timer.start(10000.0f);
636
637   // Stop all clocks.
638   for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
639                   i != currentsector->gameobjects.end(); ++i)
640   {
641     GameObject* obj = *i;
642
643     LevelTime* lt = dynamic_cast<LevelTime*> (obj);
644     if(lt)
645       lt->stop();
646   }
647 }
648
649 /* (Status): */
650 void
651 GameSession::drawstatus(DrawingContext& context)
652 {
653   player_status->draw(context);
654
655   // draw level stats while end_sequence is running
656   if (end_sequence) {
657     level->stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());
658   }
659 }