9cf47572ad8cb4a789feb076b2ffb3a097689d25
[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   // pause
309   if(!game_pause) {
310     speed_before_pause = main_loop->get_speed();
311     main_loop->set_speed(0);
312     Menu::set_current(game_menu.get());
313     game_menu->set_active_item(MNID_CONTINUE);
314     game_pause = true;
315   }
316
317   // unpause is done in update() after the menu is processed
318 }
319
320 void
321 GameSession::set_editmode(bool edit_mode)
322 {
323   if (this->edit_mode == edit_mode) return;
324   this->edit_mode = edit_mode;
325
326   currentsector->get_players()[0]->set_edit_mode(edit_mode);
327
328   if (edit_mode) {
329
330     // entering edit mode
331
332   } else {
333
334     // leaving edit mode
335     restart_level();
336
337   }
338 }
339
340 void
341 GameSession::force_ghost_mode()
342 {
343   currentsector->get_players()[0]->set_ghost_mode(true);
344 }
345
346 HSQUIRRELVM
347 GameSession::run_script(std::istream& in, const std::string& sourcename)
348 {
349   using namespace Scripting;
350
351   // garbage collect thread list
352   for(ScriptList::iterator i = scripts.begin();
353       i != scripts.end(); ) {
354     HSQOBJECT& object = *i;
355     HSQUIRRELVM vm = object_to_vm(object);
356
357     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
358       sq_release(global_vm, &object);
359       i = scripts.erase(i);
360       continue;
361     }
362
363     ++i;
364   }
365
366   HSQOBJECT object = create_thread(global_vm);
367   scripts.push_back(object);
368
369   HSQUIRRELVM vm = object_to_vm(object);
370
371   compile_and_run(vm, in, sourcename);
372
373   return vm;
374 }
375
376 void
377 GameSession::process_events()
378 {
379   // end of pause mode?
380   // XXX this looks like a fail-safe to unpause the game if there's no menu
381   // XXX having it enabled causes some unexpected problems
382   // XXX hopefully disabling it won't...
383   /*
384   if(!Menu::current() && game_pause) {
385     game_pause = false;
386   }
387   */
388
389   // playback a demo?
390   if(playback_demo_stream != 0) {
391     demo_controller->update();
392     char left = false;
393     char right = false;
394     char up = false;
395     char down = false;
396     char jump = false;
397     char action = false;
398     playback_demo_stream->get(left);
399     playback_demo_stream->get(right);
400     playback_demo_stream->get(up);
401     playback_demo_stream->get(down);
402     playback_demo_stream->get(jump);
403     playback_demo_stream->get(action);
404     demo_controller->press(Controller::LEFT, left);
405     demo_controller->press(Controller::RIGHT, right);
406     demo_controller->press(Controller::UP, up);
407     demo_controller->press(Controller::DOWN, down);
408     demo_controller->press(Controller::JUMP, jump);
409     demo_controller->press(Controller::ACTION, action);
410   }
411
412   // save input for demo?
413   if(capture_demo_stream != 0) {
414     capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
415     capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
416     capture_demo_stream ->put(main_controller->hold(Controller::UP));
417     capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
418     capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
419     capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
420   }
421 }
422
423 void
424 GameSession::check_end_conditions()
425 {
426   Player* tux = currentsector->player;
427
428   /* End of level? */
429   if(end_sequence && end_sequence->is_done()) {
430     finish(true);
431   } else if (!end_sequence && tux->is_dead()) {
432     restart_level();
433   }
434 }
435
436 void
437 GameSession::draw(DrawingContext& context)
438 {
439   currentsector->draw(context);
440   drawstatus(context);
441
442   if(game_pause)
443     draw_pause(context);
444 }
445
446 void
447 GameSession::draw_pause(DrawingContext& context)
448 {
449   context.draw_filled_rect(
450       Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
451       Color(0.0f, 0.0f, 0.0f, .25f), LAYER_FOREGROUND1);
452 }
453
454 void
455 GameSession::process_menu()
456 {
457   Menu* menu = Menu::current();
458   if(menu) {
459     menu->update();
460
461     if(menu == game_menu.get()) {
462       switch (game_menu->check()) {
463         case MNID_CONTINUE:
464           Menu::set_current(0);
465           toggle_pause();
466           break;
467         case MNID_ABORTLEVEL:
468           Menu::set_current(0);
469           main_loop->exit_screen();
470           break;
471       }
472     }
473   }
474 }
475
476 void
477 GameSession::setup()
478 {
479   Menu::set_current(NULL);
480   current_ = this;
481
482   if(currentsector != Sector::current()) {
483         currentsector->activate(currentsector->player->get_pos());
484   }
485   currentsector->play_music(LEVEL_MUSIC);
486
487   // Eat unneeded events
488   SDL_Event event;
489   while(SDL_PollEvent(&event))
490   {}
491 }
492
493 void
494 GameSession::update(float elapsed_time)
495 {
496   // handle controller
497   if(main_controller->pressed(Controller::PAUSE_MENU))
498     on_escape_press();
499
500   process_events();
501   process_menu();
502
503   // Unpause the game if the menu has been closed
504   if (game_pause && !Menu::current()) {
505     main_loop->set_speed(speed_before_pause);
506     game_pause = false;
507   }
508
509   check_end_conditions();
510
511   // respawning in new sector?
512   if(newsector != "" && newspawnpoint != "") {
513     Sector* sector = level->get_sector(newsector);
514     if(sector == 0) {
515       log_warning << "Sector '" << newsector << "' not found" << std::endl;
516     }
517     sector->activate(newspawnpoint);
518     sector->play_music(LEVEL_MUSIC);
519     currentsector = sector;
520     newsector = "";
521     newspawnpoint = "";
522   }
523
524   // Update the world state and all objects in the world
525   if(!game_pause) {
526     // Update the world
527     if (!end_sequence) {
528       play_time += elapsed_time; //TODO: make sure we don't count cutscene time
529       level->stats.time = play_time;
530       currentsector->update(elapsed_time);
531     } else {
532       if (!end_sequence->is_tux_stopped()) {
533         currentsector->update(elapsed_time);
534       } else {
535         end_sequence->update(elapsed_time);
536       }
537     }
538   }
539
540   // update sounds
541   if (currentsector && currentsector->camera) sound_manager->set_listener_position(currentsector->camera->get_center());
542
543   /* Handle music: */
544   if (end_sequence)
545     return;
546
547   if(currentsector->player->invincible_timer.started()) {
548     if(currentsector->player->invincible_timer.get_timeleft() <=
549        TUX_INVINCIBLE_TIME_WARNING) {
550       currentsector->play_music(HERRING_WARNING_MUSIC);
551     } else {
552       currentsector->play_music(HERRING_MUSIC);
553     }
554   } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
555     currentsector->play_music(LEVEL_MUSIC);
556   }
557 }
558
559 void
560 GameSession::finish(bool win)
561 {
562   using namespace WorldMapNS;
563
564   if (edit_mode) {
565     force_ghost_mode();
566     return;
567   }
568
569   if(win) {
570     if(WorldMap::current())
571       WorldMap::current()->finished_level(level.get());
572   }
573
574   main_loop->exit_screen();
575 }
576
577 void
578 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
579 {
580   newsector = sector;
581   newspawnpoint = spawnpoint;
582 }
583
584 void
585 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
586 {
587   reset_sector = sector;
588   reset_pos = pos;
589 }
590
591 std::string
592 GameSession::get_working_directory()
593 {
594   return FileSystem::dirname(levelfile);
595 }
596
597 void
598 GameSession::start_sequence(const std::string& sequencename)
599 {
600   // do not play sequences when in edit mode
601   if (edit_mode) {
602     force_ghost_mode();
603     return;
604   }
605
606   // handle special "stoptux" sequence
607   if (sequencename == "stoptux") {
608     if (!end_sequence) {
609       log_warning << "Final target reached without an active end sequence" << std::endl;
610       this->start_sequence("endsequence");
611     }
612     if (end_sequence) end_sequence->stop_tux();
613     return;
614   }
615
616   // abort if a sequence is already playing
617   if (end_sequence)
618           return;
619
620   if (sequencename == "endsequence") {
621     if (currentsector->get_players()[0]->physic.get_velocity_x() < 0) {
622       end_sequence = new EndSequenceWalkLeft();
623     } else {
624       end_sequence = new EndSequenceWalkRight();
625     }
626   } else if (sequencename == "fireworks") {
627     end_sequence = new EndSequenceFireworks();
628   } else {
629     log_warning << "Unknown sequence '" << sequencename << "'. Ignoring." << std::endl;
630     return;
631   }
632
633   /* slow down the game for end-sequence */
634   main_loop->set_speed(0.5f);
635
636   currentsector->add_object(end_sequence);
637   end_sequence->start();
638
639   sound_manager->play_music("music/leveldone.ogg", false);
640   currentsector->player->invincible_timer.start(10000.0f);
641
642   // Stop all clocks.
643   for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
644                   i != currentsector->gameobjects.end(); ++i)
645   {
646     GameObject* obj = *i;
647
648     LevelTime* lt = dynamic_cast<LevelTime*> (obj);
649     if(lt)
650       lt->stop();
651   }
652 }
653
654 /* (Status): */
655 void
656 GameSession::drawstatus(DrawingContext& context)
657 {
658   player_status->draw(context);
659
660   // draw level stats while end_sequence is running
661   if (end_sequence) {
662     level->stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());
663   }
664 }