Scripting scheduler is now paused while pause menu is shown
[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)
96 {
97   current_ = this;
98   currentsector = NULL;
99
100   game_pause = false;
101   Scripting::TimeScheduler::instance->set_pause(game_pause);
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   game_pause   = false;
120   Scripting::TimeScheduler::instance->set_pause(game_pause);
121   end_sequence = 0;
122
123   main_controller->reset();
124
125   currentsector = 0;
126
127   level.reset(new Level);
128   level->load(levelfile);
129   level->stats.total_coins = level->get_total_coins();
130   level->stats.total_badguys = level->get_total_badguys();
131   level->stats.total_secrets = level->get_total_count<SecretAreaTrigger>();
132   level->stats.reset();
133   if(reset_sector != "")level->stats.declare_invalid();
134
135   if(reset_sector != "") {
136     currentsector = level->get_sector(reset_sector);
137     if(!currentsector) {
138       std::stringstream msg;
139       msg << "Couldn't find sector '" << reset_sector << "' for resetting tux.";
140       throw std::runtime_error(msg.str());
141     }
142     currentsector->activate(reset_pos);
143   } else {
144     currentsector = level->get_sector("main");
145     if(!currentsector)
146       throw std::runtime_error("Couldn't find main sector");
147     currentsector->activate("main");
148   }
149
150   //levelintro();
151
152   sound_manager->stop_music();
153   currentsector->play_music(LEVEL_MUSIC);
154
155   if(capture_file != "") {
156     int newSeed=0;               // next run uses a new seed
157     while (newSeed == 0)            // which is the next non-zero random num.
158         newSeed = systemRandom.rand();
159     config->random_seed = systemRandom.srand(newSeed);
160     log_info << "Next run uses random seed " <<config->random_seed <<std::endl;
161     record_demo(capture_file);
162   }
163 }
164
165 GameSession::~GameSession()
166 {
167   delete capture_demo_stream;
168   delete playback_demo_stream;
169   delete demo_controller;
170
171   if (game_pause) {
172     game_pause = false;
173     Scripting::TimeScheduler::instance->set_pause(game_pause);
174   }
175
176   current_ = NULL;
177 }
178
179 void
180 GameSession::record_demo(const std::string& filename)
181 {
182   delete capture_demo_stream;
183
184   capture_demo_stream = new std::ofstream(filename.c_str());
185   if(!capture_demo_stream->good()) {
186     std::stringstream msg;
187     msg << "Couldn't open demo file '" << filename << "' for writing.";
188     throw std::runtime_error(msg.str());
189   }
190   capture_file = filename;
191
192   char buf[30];                            // save the seed in the demo file
193   snprintf(buf, sizeof(buf), "random_seed=%10d", config->random_seed);
194   for (int i=0; i==0 || buf[i-1]; i++)
195     capture_demo_stream->put(buf[i]);
196 }
197
198 int
199 GameSession::get_demo_random_seed(const std::string& filename)
200 {
201   std::istream* test_stream = new std::ifstream(filename.c_str());
202   if(test_stream->good()) {
203     char buf[30];                     // recall the seed from the demo file
204     int seed;
205     for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
206       test_stream->get(buf[i]);
207     if (sscanf(buf, "random_seed=%10d", &seed) == 1) {
208       log_info << "Random seed " << seed << " from demo file" << std::endl;
209          return seed;
210     }
211     else
212       log_info << "Demo file contains no random number" << std::endl;
213   }
214   return 0;
215 }
216
217 void
218 GameSession::play_demo(const std::string& filename)
219 {
220   delete playback_demo_stream;
221   delete demo_controller;
222
223   playback_demo_stream = new std::ifstream(filename.c_str());
224   if(!playback_demo_stream->good()) {
225     std::stringstream msg;
226     msg << "Couldn't open demo file '" << filename << "' for reading.";
227     throw std::runtime_error(msg.str());
228   }
229
230   Player& tux = *currentsector->player;
231   demo_controller = new CodeController();
232   tux.set_controller(demo_controller);
233
234   // skip over random seed, if it exists in the file
235   char buf[30];                            // ascii decimal seed
236   int seed;
237   for (int i=0; i<30 && (i==0 || buf[i-1]); i++)
238     playback_demo_stream->get(buf[i]);
239   if (sscanf(buf, "random_seed=%010d", &seed) != 1)
240     playback_demo_stream->seekg(0);     // old style w/o seed, restart at beg
241 }
242
243 void
244 GameSession::levelintro()
245 {
246   sound_manager->stop_music();
247
248   DrawingContext context;
249   for(Sector::GameObjects::iterator i = currentsector->gameobjects.begin();
250       i != currentsector->gameobjects.end(); ++i) {
251     Background* background = dynamic_cast<Background*> (*i);
252     if(background) {
253       background->draw(context);
254     }
255     Gradient* gradient = dynamic_cast<Gradient*> (*i);
256     if(gradient) {
257       gradient->draw(context);
258     }
259   }
260
261 //  context.draw_text(gold_text, level->get_name(), Vector(SCREEN_WIDTH/2, 160),
262 //      ALIGN_CENTER, LAYER_FOREGROUND1);
263   context.draw_center_text(gold_text, level->get_name(), Vector(0, 160),
264       LAYER_FOREGROUND1);
265
266   std::stringstream ss_coins;
267   ss_coins << _("Coins") << ": " << player_status->coins;
268   context.draw_text(white_text, ss_coins.str(), Vector(SCREEN_WIDTH/2, 210),
269       ALIGN_CENTER, LAYER_FOREGROUND1);
270
271   if((level->get_author().size()) && (level->get_author() != "SuperTux Team"))
272     context.draw_text(white_small_text,
273       std::string(_("contributed by ")) + level->get_author(),
274       Vector(SCREEN_WIDTH/2, 350), ALIGN_CENTER, LAYER_FOREGROUND1);
275
276   if(best_level_statistics != NULL)
277     best_level_statistics->draw_message_info(context, _("Best Level Statistics"));
278
279   wait_for_event(1.0, 3.0);
280 }
281
282 void
283 GameSession::on_escape_press()
284 {
285   if(currentsector->player->is_dying() || end_sequence)
286   {
287     // Let the timers run out, we fast-forward them to force past a sequence
288     if (end_sequence) end_sequence->stop();
289     currentsector->player->dying_timer.start(FLT_EPSILON);
290     return;   // don't let the player open the menu, when he is dying
291   }
292
293   if(level->on_menukey_script != "") {
294     std::istringstream in(level->on_menukey_script);
295     run_script(in, "OnMenuKeyScript");
296   } else {
297     toggle_pause();
298   }
299 }
300
301 void
302 GameSession::toggle_pause()
303 {
304   if(Menu::current() == NULL) {
305     Menu::set_current(game_menu.get());
306     game_menu->set_active_item(MNID_CONTINUE);
307     game_pause = true;
308     Scripting::TimeScheduler::instance->set_pause(game_pause);
309   } else {
310     Menu::set_current(NULL);
311     game_pause = false;
312     Scripting::TimeScheduler::instance->set_pause(game_pause);
313   }
314 }
315
316 HSQUIRRELVM
317 GameSession::run_script(std::istream& in, const std::string& sourcename)
318 {
319   using namespace Scripting;
320
321   // garbage collect thread list
322   for(ScriptList::iterator i = scripts.begin();
323       i != scripts.end(); ) {
324     HSQOBJECT& object = *i;
325     HSQUIRRELVM vm = object_to_vm(object);
326
327     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
328       sq_release(global_vm, &object);
329       i = scripts.erase(i);
330       continue;
331     }
332
333     ++i;
334   }
335
336   HSQOBJECT object = create_thread(global_vm);
337   scripts.push_back(object);
338
339   HSQUIRRELVM vm = object_to_vm(object);
340
341   compile_and_run(vm, in, sourcename);
342
343   return vm;
344 }
345
346 void
347 GameSession::process_events()
348 {
349   // end of pause mode?
350   if(!Menu::current() && game_pause) {
351     game_pause = false;
352     Scripting::TimeScheduler::instance->set_pause(game_pause);
353   }
354
355   // playback a demo?
356   if(playback_demo_stream != 0) {
357     demo_controller->update();
358     char left = false;
359     char right = false;
360     char up = false;
361     char down = false;
362     char jump = false;
363     char action = false;
364     playback_demo_stream->get(left);
365     playback_demo_stream->get(right);
366     playback_demo_stream->get(up);
367     playback_demo_stream->get(down);
368     playback_demo_stream->get(jump);
369     playback_demo_stream->get(action);
370     demo_controller->press(Controller::LEFT, left);
371     demo_controller->press(Controller::RIGHT, right);
372     demo_controller->press(Controller::UP, up);
373     demo_controller->press(Controller::DOWN, down);
374     demo_controller->press(Controller::JUMP, jump);
375     demo_controller->press(Controller::ACTION, action);
376   }
377
378   // save input for demo?
379   if(capture_demo_stream != 0) {
380     capture_demo_stream ->put(main_controller->hold(Controller::LEFT));
381     capture_demo_stream ->put(main_controller->hold(Controller::RIGHT));
382     capture_demo_stream ->put(main_controller->hold(Controller::UP));
383     capture_demo_stream ->put(main_controller->hold(Controller::DOWN));
384     capture_demo_stream ->put(main_controller->hold(Controller::JUMP));
385     capture_demo_stream ->put(main_controller->hold(Controller::ACTION));
386   }
387 }
388
389 void
390 GameSession::check_end_conditions()
391 {
392   Player* tux = currentsector->player;
393
394   /* End of level? */
395   if(end_sequence && end_sequence->is_done()) {
396     finish(true);
397   } else if (!end_sequence && tux->is_dead()) {
398     restart_level();
399   }
400 }
401
402 void
403 GameSession::draw(DrawingContext& context)
404 {
405   currentsector->draw(context);
406   drawstatus(context);
407
408   if(game_pause)
409     draw_pause(context);
410 }
411
412 void
413 GameSession::draw_pause(DrawingContext& context)
414 {
415   context.draw_filled_rect(
416       Vector(0,0), Vector(SCREEN_WIDTH, SCREEN_HEIGHT),
417       Color(.2f, .2f, .2f, .5f), LAYER_FOREGROUND1);
418 }
419
420 void
421 GameSession::process_menu()
422 {
423   Menu* menu = Menu::current();
424   if(menu) {
425     menu->update();
426
427     if(menu == game_menu.get()) {
428       switch (game_menu->check()) {
429         case MNID_CONTINUE:
430           Menu::set_current(0);
431           break;
432         case MNID_ABORTLEVEL:
433           Menu::set_current(0);
434           main_loop->exit_screen();
435           break;
436       }
437     }
438   }
439 }
440
441 void
442 GameSession::setup()
443 {
444   Menu::set_current(NULL);
445   current_ = this;
446
447   if(currentsector != Sector::current()) {
448         currentsector->activate(currentsector->player->get_pos());
449   }
450   currentsector->play_music(LEVEL_MUSIC);
451
452   // Eat unneeded events
453   SDL_Event event;
454   while(SDL_PollEvent(&event))
455   {}
456 }
457
458 void
459 GameSession::update(float elapsed_time)
460 {
461   // handle controller
462   if(main_controller->pressed(Controller::PAUSE_MENU))
463     on_escape_press();
464
465   process_events();
466   process_menu();
467
468   check_end_conditions();
469
470   // respawning in new sector?
471   if(newsector != "" && newspawnpoint != "") {
472     Sector* sector = level->get_sector(newsector);
473     if(sector == 0) {
474       log_warning << "Sector '" << newsector << "' not found" << std::endl;
475     }
476     sector->activate(newspawnpoint);
477     sector->play_music(LEVEL_MUSIC);
478     currentsector = sector;
479     newsector = "";
480     newspawnpoint = "";
481   }
482
483   // Update the world state and all objects in the world
484   if(!game_pause) {
485     // Update the world
486     if (!end_sequence) {
487       play_time += elapsed_time; //TODO: make sure we don't count cutscene time
488       level->stats.time = play_time;
489       currentsector->update(elapsed_time);
490     } else {
491       if (!end_sequence->is_tux_stopped()) {
492         currentsector->update(elapsed_time/2);
493       } else {
494         end_sequence->update(elapsed_time/2);
495       }
496     }
497   }
498
499   // update sounds
500   sound_manager->set_listener_position(currentsector->player->get_pos());
501
502   /* Handle music: */
503   if (end_sequence)
504     return;
505
506   if(currentsector->player->invincible_timer.started()) {
507     if(currentsector->player->invincible_timer.get_timeleft() <=
508        TUX_INVINCIBLE_TIME_WARNING) {
509       currentsector->play_music(HERRING_WARNING_MUSIC);
510     } else {
511       currentsector->play_music(HERRING_MUSIC);
512     }
513   } else if(currentsector->get_music_type() != LEVEL_MUSIC) {
514     currentsector->play_music(LEVEL_MUSIC);
515   }
516 }
517
518 void
519 GameSession::finish(bool win)
520 {
521   using namespace WorldMapNS;
522
523   if(win) {
524     if(WorldMap::current())
525       WorldMap::current()->finished_level(level.get());
526   }
527
528   main_loop->exit_screen();
529 }
530
531 void
532 GameSession::respawn(const std::string& sector, const std::string& spawnpoint)
533 {
534   newsector = sector;
535   newspawnpoint = spawnpoint;
536 }
537
538 void
539 GameSession::set_reset_point(const std::string& sector, const Vector& pos)
540 {
541   reset_sector = sector;
542   reset_pos = pos;
543 }
544
545 std::string
546 GameSession::get_working_directory()
547 {
548   return FileSystem::dirname(levelfile);
549 }
550
551 void
552 GameSession::display_info_box(const std::string& text)
553 {
554   InfoBox* box = new InfoBox(text);
555
556   bool running = true;
557   DrawingContext context;
558
559   while(running)  {
560
561     // TODO make a screen out of this, another mainloop is ugly
562     main_controller->update();
563     SDL_Event event;
564     while (SDL_PollEvent(&event)) {
565       main_controller->process_event(event);
566       if(event.type == SDL_QUIT)
567         main_loop->quit();
568     }
569
570     if(main_controller->pressed(Controller::JUMP)
571         || main_controller->pressed(Controller::ACTION)
572         || main_controller->pressed(Controller::PAUSE_MENU)
573         || main_controller->pressed(Controller::MENU_SELECT))
574       running = false;
575     else if(main_controller->pressed(Controller::DOWN))
576       box->scrolldown();
577     else if(main_controller->pressed(Controller::UP))
578       box->scrollup();
579     box->draw(context);
580     draw(context);
581     context.do_drawing();
582     sound_manager->update();
583   }
584
585   delete box;
586 }
587
588 void
589 GameSession::start_sequence(const std::string& sequencename)
590 {
591   // handle special "stoptux" sequence
592   if (sequencename == "stoptux") {
593     if (!end_sequence) {
594       log_warning << "Final target reached without an active end sequence" << std::endl;
595       this->start_sequence("endsequence");
596     }
597     if (end_sequence) end_sequence->stop_tux();
598     return;
599   }
600
601   // abort if a sequence is already playing
602   if (end_sequence) return;
603
604   if (sequencename == "endsequence") {
605
606     // Determine walking direction for Tux
607     /*float xst = 1.f, xend = 2.f;
608     for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin(); i != currentsector->gameobjects.end(); i++) {
609       SequenceTrigger* st = dynamic_cast<SequenceTrigger*>(*i);
610       if(!st)
611         continue;
612       if(st->get_sequence_name() == "stoptux")
613         xend = st->get_pos().x;
614       else if(st->get_sequence_name() == "endsequence")
615         xst = st->get_pos().y;
616     }
617
618     if (xst > xend) {
619       end_sequence = new EndSequenceWalkLeft();
620     } else {
621       end_sequence = new EndSequenceWalkRight();
622     }*/
623     if (currentsector->get_players()[0]->physic.get_velocity_x() < 0) {
624       end_sequence = new EndSequenceWalkLeft();
625     } else {
626       end_sequence = new EndSequenceWalkRight();
627     }
628   }
629   else if (sequencename == "fireworks") end_sequence = new EndSequenceFireworks();
630   else {
631     log_warning << "Unknown sequence '" << sequencename << "'. Ignoring." << std::endl;
632     return;
633   }
634
635   currentsector->add_object(end_sequence);
636   end_sequence->start();
637
638   sound_manager->play_music("music/leveldone.ogg", false);
639   currentsector->player->invincible_timer.start(10000.0f);
640
641   // Stop all clocks.
642   for(std::vector<GameObject*>::iterator i = currentsector->gameobjects.begin();
643                   i != currentsector->gameobjects.end(); ++i)
644   {
645     GameObject* obj = *i;
646
647     LevelTime* lt = dynamic_cast<LevelTime*> (obj);
648     if(lt)
649       lt->stop();
650   }
651 }
652
653 /* (Status): */
654 void
655 GameSession::drawstatus(DrawingContext& context)
656 {
657   player_status->draw(context);
658
659   // draw level stats while end_sequence is running
660   if (end_sequence) {
661     level->stats.draw_endseq_panel(context, best_level_statistics, statistics_backdrop.get());
662   }
663 }