Fade out and pause music on death and resume on restart of level, fixes #1064
[supertux.git] / src / object / player.cpp
1 //  SuperTux
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software; you can redistribute it and/or
5 //  modify it under the terms of the GNU General Public License
6 //  as published by the Free Software Foundation; either version 2
7 //  of the License, or (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program; if not, write to the Free Software
16 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
17
18 #include "object/player.hpp"
19
20 #include "audio/sound_manager.hpp"
21 #include "badguy/badguy.hpp"
22 #include "control/input_manager.hpp"
23 #include "math/random_generator.hpp"
24 #include "object/bullet.hpp"
25 #include "object/camera.hpp"
26 #include "object/display_effect.hpp"
27 #include "object/falling_coin.hpp"
28 #include "object/particles.hpp"
29 #include "object/portable.hpp"
30 #include "object/sprite_particle.hpp"
31 #include "scripting/squirrel_util.hpp"
32 #include "supertux/game_session.hpp"
33 #include "supertux/globals.hpp"
34 #include "supertux/sector.hpp"
35 #include "supertux/tile.hpp"
36 #include "trigger/climbable.hpp"
37
38 #include <math.h>
39
40 //#define SWIMMING
41
42 namespace {
43 static const float BUTTJUMP_MIN_VELOCITY_Y = 400.0f;
44 static const float SHOOTING_TIME = .150f;
45 static const float GLIDE_TIME_PER_FLOWER = 0.5f;
46 static const float STONE_TIME_PER_FLOWER = 2.0f;
47
48 /** number of idle stages, including standing */
49 static const unsigned int IDLE_STAGE_COUNT = 5;
50 /**
51  * how long to play each idle animation in milliseconds
52  * '0' means the sprite action is played once before moving onto the next
53  * animation
54  */
55 static const int IDLE_TIME[] = { 5000, 0, 2500, 0, 2500 };
56 /** idle stages */
57 static const std::string IDLE_STAGES[] =
58 { "stand",
59   "idle",
60   "stand",
61   "idle",
62   "stand" };
63
64 /** acceleration in horizontal direction when walking
65  * (all accelerations are in  pixel/s^2) */
66 static const float WALK_ACCELERATION_X = 300;
67 /** acceleration in horizontal direction when running */
68 static const float RUN_ACCELERATION_X = 400;
69 /** acceleration when skidding */
70 static const float SKID_XM = 200;
71 /** time of skidding in seconds */
72 static const float SKID_TIME = .3f;
73 /** maximum walk velocity (pixel/s) */
74 static const float MAX_WALK_XM = 230;
75 /** maximum run velocity (pixel/s) */
76 static const float MAX_RUN_XM = 320;
77 /** bonus run velocity addition (pixel/s) */
78 static const float BONUS_RUN_XM = 80;
79 /** maximum horizontal climb velocity */
80 static const float MAX_CLIMB_XM = 96;
81 /** maximum vertical climb velocity */
82 static const float MAX_CLIMB_YM = 128;
83 /** maximum vertical glide velocity */
84 static const float MAX_GLIDE_YM = 128;
85 /** instant velocity when tux starts to walk */
86 static const float WALK_SPEED = 100;
87
88 /** multiplied by WALK_ACCELERATION to give friction */
89 static const float NORMAL_FRICTION_MULTIPLIER = 1.5f;
90 /** multiplied by WALK_ACCELERATION to give friction */
91 static const float ICE_FRICTION_MULTIPLIER = 0.1f;
92 static const float ICE_ACCELERATION_MULTIPLIER = 0.25f;
93
94 /** time of the kick (kicking mriceblock) animation */
95 static const float KICK_TIME = .3f;
96
97 /** if Tux cannot unduck for this long, he will get hurt */
98 static const float UNDUCK_HURT_TIME = 0.25f;
99 /** gravity is higher after the jump key is released before
100     the apex of the jump is reached */
101 static const float JUMP_EARLY_APEX_FACTOR = 3.0;
102
103 static const float JUMP_GRACE_TIME = 0.25f; /**< time before hitting the ground that the jump button may be pressed (and still trigger a jump) */
104
105 /* Tux's collision rectangle */
106 static const float TUX_WIDTH = 31.8f;
107 static const float RUNNING_TUX_WIDTH = 34;
108 static const float SMALL_TUX_HEIGHT = 30.8f;
109 static const float BIG_TUX_HEIGHT = 62.8f;
110 static const float DUCKED_TUX_HEIGHT = 31.8f;
111
112 bool no_water = true;
113 }
114
115 Player::Player(PlayerStatus* _player_status, const std::string& name_) :
116   deactivated(),
117   controller(),
118   scripting_controller(),
119   player_status(_player_status),
120   duck(),
121   dead(),
122   dying(),
123   winning(),
124   backflipping(),
125   backflip_direction(),
126   peekingX(),
127   peekingY(),
128   ability_time(),
129   stone(),
130   swimming(),
131   speedlimit(),
132   scripting_controller_old(0),
133   jump_early_apex(),
134   on_ice(),
135   ice_this_frame(),
136   lightsprite(SpriteManager::current()->create("images/creatures/tux/light.sprite")),
137   powersprite(SpriteManager::current()->create("images/creatures/tux/powerups.sprite")),
138   dir(),
139   old_dir(),
140   last_ground_y(),
141   fall_mode(),
142   on_ground_flag(),
143   jumping(),
144   can_jump(),
145   jump_button_timer(),
146   wants_buttjump(),
147   does_buttjump(),
148   invincible_timer(),
149   skidding_timer(),
150   safe_timer(),
151   kick_timer(),
152   shooting_timer(),
153   ability_timer(),
154   cooldown_timer(),
155   dying_timer(),
156   growing(),
157   backflip_timer(),
158   physic(),
159   visible(),
160   grabbed_object(NULL),
161   sprite(),
162   airarrow(),
163   floor_normal(),
164   ghost_mode(false),
165   edit_mode(false),
166   unduck_hurt_timer(),
167   idle_timer(),
168   idle_stage(0),
169   climbing(0)
170 {
171   this->name = name_;
172   controller = InputManager::current()->get_controller();
173   scripting_controller.reset(new CodeController());
174   // if/when we have complete penny gfx, we can
175   // load those instead of Tux's sprite in the
176   // constructor
177   sprite = SpriteManager::current()->create("images/creatures/tux/tux.sprite");
178   airarrow = Surface::create("images/engine/hud/airarrow.png");
179   idle_timer.start(IDLE_TIME[0]/1000.0f);
180
181   SoundManager::current()->preload("sounds/bigjump.wav");
182   SoundManager::current()->preload("sounds/jump.wav");
183   SoundManager::current()->preload("sounds/hurt.wav");
184   SoundManager::current()->preload("sounds/kill.wav");
185   SoundManager::current()->preload("sounds/skid.wav");
186   SoundManager::current()->preload("sounds/flip.wav");
187   SoundManager::current()->preload("sounds/invincible_start.ogg");
188   SoundManager::current()->preload("sounds/splash.wav");
189
190   init();
191 }
192
193 Player::~Player()
194 {
195   if (climbing) stop_climbing(*climbing);
196 }
197
198 void
199 Player::init()
200 {
201   if(is_big())
202     set_size(TUX_WIDTH, BIG_TUX_HEIGHT);
203   else
204     set_size(TUX_WIDTH, SMALL_TUX_HEIGHT);
205
206   dir = RIGHT;
207   old_dir = dir;
208   duck = false;
209   dead = false;
210
211   dying = false;
212   winning = false;
213   peekingX = AUTO;
214   peekingY = AUTO;
215   last_ground_y = 0;
216   fall_mode = ON_GROUND;
217   jumping = false;
218   jump_early_apex = false;
219   can_jump = true;
220   wants_buttjump = false;
221   does_buttjump = false;
222   growing = false;
223   deactivated = false;
224   backflipping = false;
225   backflip_direction = 0;
226   sprite->set_angle(0.0f);
227   powersprite->set_angle(0.0f);
228   lightsprite->set_angle(0.0f);
229   visible = true;
230   ability_time = 0;
231   stone = false;
232   swimming = false;
233   on_ice = false;
234   ice_this_frame = false;
235   speedlimit = 0; //no special limit
236   lightsprite->set_blend(Blend(GL_SRC_ALPHA, GL_ONE));
237
238   on_ground_flag = false;
239   grabbed_object = NULL;
240
241   climbing = 0;
242
243   physic.reset();
244 }
245
246 void
247 Player::expose(HSQUIRRELVM vm, SQInteger table_idx)
248 {
249   if (name.empty())
250     return;
251
252   scripting::expose_object(vm, table_idx, dynamic_cast<scripting::Player *>(this), name, false);
253 }
254
255 void
256 Player::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
257 {
258   if (name.empty())
259     return;
260
261   scripting::unexpose_object(vm, table_idx, name);
262 }
263
264 float
265 Player::get_speedlimit()
266 {
267   return speedlimit;
268 }
269
270 void
271 Player::set_speedlimit(float newlimit)
272 {
273   speedlimit=newlimit;
274 }
275
276 void
277 Player::set_controller(Controller* controller_)
278 {
279   this->controller = controller_;
280 }
281
282 void
283 Player::set_winning()
284 {
285   if( ! is_winning() ){
286     winning = true;
287     invincible_timer.start(10000.0f);
288   }
289 }
290
291 void
292 Player::use_scripting_controller(bool use_or_release)
293 {
294   if ((use_or_release == true) && (controller != scripting_controller.get())) {
295     scripting_controller_old = get_controller();
296     set_controller(scripting_controller.get());
297   }
298   if ((use_or_release == false) && (controller == scripting_controller.get())) {
299     set_controller(scripting_controller_old);
300     scripting_controller_old = 0;
301   }
302 }
303
304 void
305 Player::do_scripting_controller(std::string control, bool pressed)
306 {
307   for(int i = 0; Controller::controlNames[i] != 0; ++i) {
308     if(control == std::string(Controller::controlNames[i])) {
309       scripting_controller->press(Controller::Control(i), pressed);
310     }
311   }
312 }
313
314 bool
315 Player::adjust_height(float new_height)
316 {
317   Rectf bbox2 = bbox;
318   bbox2.move(Vector(0, bbox.get_height() - new_height));
319   bbox2.set_height(new_height);
320
321
322   if(new_height > bbox.get_height()) {
323     Rectf additional_space = bbox2;
324     additional_space.set_height(new_height - bbox.get_height());
325     if(!Sector::current()->is_free_of_statics(additional_space, this, true))
326       return false;
327   }
328
329   // adjust bbox accordingly
330   // note that we use members of moving_object for this, so we can run this during CD, too
331   set_pos(bbox2.p1);
332   set_size(bbox2.get_width(), bbox2.get_height());
333   return true;
334 }
335
336 void
337 Player::trigger_sequence(std::string sequence_name)
338 {
339   if (climbing) stop_climbing(*climbing);
340   backflipping = false;
341   backflip_direction = 0;
342   sprite->set_angle(0.0f);
343   powersprite->set_angle(0.0f);
344   lightsprite->set_angle(0.0f);
345   GameSession::current()->start_sequence(sequence_name);
346 }
347
348 void
349 Player::update(float elapsed_time)
350 {
351   if( no_water ){
352     swimming = false;
353   }
354   no_water = true;
355
356   if(dying && dying_timer.check()) {
357     set_bonus(NO_BONUS, true);
358     dead = true;
359     return;
360   }
361
362   if(!dying && !deactivated)
363     handle_input();
364
365   /*
366   // handle_input() calls apply_friction() when Tux is not walking, so we'll have to do this ourselves
367   if (deactivated)
368   apply_friction();
369   */
370
371   // extend/shrink tux collision rectangle so that we fall through/walk over 1
372   // tile holes
373   if(fabsf(physic.get_velocity_x()) > MAX_WALK_XM) {
374     set_width(RUNNING_TUX_WIDTH);
375   } else {
376     set_width(TUX_WIDTH);
377   }
378
379   // on downward slopes, adjust vertical velocity so tux walks smoothly down
380   if (on_ground() && !dying) {
381     if(floor_normal.y != 0) {
382       if ((floor_normal.x * physic.get_velocity_x()) >= 0) {
383         physic.set_velocity_y(250);
384       }
385     }
386   }
387
388   // handle backflipping
389   if (backflipping && !dying) {
390     //prevent player from changing direction when backflipping
391     dir = (backflip_direction == 1) ? LEFT : RIGHT;
392     if (backflip_timer.started()) physic.set_velocity_x(100 * backflip_direction);
393     //rotate sprite during flip
394     sprite->set_angle(sprite->get_angle() + (dir==LEFT?1:-1) * elapsed_time * (360.0f / 0.5f));
395     if (player_status->bonus == EARTH_BONUS || player_status->bonus == AIR_BONUS) {
396       powersprite->set_angle(sprite->get_angle());
397       if (player_status->bonus == EARTH_BONUS)
398         lightsprite->set_angle(sprite->get_angle());
399     }
400   }
401
402   // set fall mode...
403   if(on_ground()) {
404     fall_mode = ON_GROUND;
405     last_ground_y = get_pos().y;
406   } else {
407     if(get_pos().y > last_ground_y)
408       fall_mode = FALLING;
409     else if(fall_mode == ON_GROUND)
410       fall_mode = JUMPING;
411   }
412
413   // check if we landed
414   if(on_ground()) {
415     jumping = false;
416     if (backflipping && (backflip_timer.get_timegone() > 0.15f)) {
417       backflipping = false;
418       backflip_direction = 0;
419       physic.set_velocity_x(0);
420       if (!stone) {
421         sprite->set_angle(0.0f);
422         powersprite->set_angle(0.0f);
423         lightsprite->set_angle(0.0f);
424       }
425
426       // if controls are currently deactivated, we take care of standing up ourselves
427       if (deactivated)
428         do_standup();
429     }
430     if (player_status->bonus == AIR_BONUS)
431       ability_time = player_status->max_air_time * GLIDE_TIME_PER_FLOWER;
432   }
433
434   // calculate movement for this frame
435   movement = physic.get_movement(elapsed_time);
436
437   if(grabbed_object != NULL && !dying) {
438     position_grabbed_object();
439   }
440
441   if(grabbed_object != NULL && dying){
442     grabbed_object->ungrab(*this, dir);
443     grabbed_object = NULL;
444   }
445
446   if(!ice_this_frame && on_ground())
447     on_ice = false;
448
449   on_ground_flag = false;
450   ice_this_frame = false;
451
452   // when invincible, spawn particles
453   if (invincible_timer.started())
454   {
455     if (graphicsRandom.rand(0, 2) == 0) {
456       float px = graphicsRandom.randf(bbox.p1.x+0, bbox.p2.x-0);
457       float py = graphicsRandom.randf(bbox.p1.y+0, bbox.p2.y-0);
458       Vector ppos = Vector(px, py);
459       Vector pspeed = Vector(0, 0);
460       Vector paccel = Vector(0, 0);
461       Sector::current()->add_object(std::make_shared<SpriteParticle>(
462                                       "images/objects/particles/sparkle.sprite",
463                                       // draw bright sparkle when there is lots of time left,
464                                       // dark sparkle when invincibility is about to end
465                                       (invincible_timer.get_timeleft() > TUX_INVINCIBLE_TIME_WARNING) ?
466                                       // make every other a longer sparkle to make trail a bit fuzzy
467                                       (size_t(game_time*20)%2) ? "small" : "medium"
468                                       :
469                                       "dark", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
470     }
471   }
472
473   if (growing) {
474     if (sprite->animation_done()) growing = false;
475   }
476
477   // when climbing animate only while moving
478   if(climbing){
479     if((physic.get_velocity_x()==0)&&(physic.get_velocity_y()==0))
480       sprite->stop_animation();
481     else
482       sprite->set_animation_loops(-1);
483   }
484
485 }
486
487 bool
488 Player::on_ground()
489 {
490   return on_ground_flag;
491 }
492
493 bool
494 Player::is_big()
495 {
496   if(player_status->bonus == NO_BONUS)
497     return false;
498
499   return true;
500 }
501
502 void
503 Player::apply_friction()
504 {
505   if ((on_ground()) && (fabs(physic.get_velocity_x()) < WALK_SPEED)) {
506     physic.set_velocity_x(0);
507     physic.set_acceleration_x(0);
508   } else {
509     float friction = WALK_ACCELERATION_X * (on_ice ? ICE_FRICTION_MULTIPLIER : NORMAL_FRICTION_MULTIPLIER);
510     if(physic.get_velocity_x() < 0) {
511       physic.set_acceleration_x(friction);
512     } else if(physic.get_velocity_x() > 0) {
513       physic.set_acceleration_x(-friction);
514     } // no friction for physic.get_velocity_x() == 0
515   }
516 }
517
518 void
519 Player::handle_horizontal_input()
520 {
521   float vx = physic.get_velocity_x();
522   float vy = physic.get_velocity_y();
523   float ax = physic.get_acceleration_x();
524   float ay = physic.get_acceleration_y();
525
526   float dirsign = 0;
527   if(!duck || physic.get_velocity_y() != 0) {
528     if(controller->hold(Controller::LEFT) && !controller->hold(Controller::RIGHT)) {
529       old_dir = dir;
530       dir = LEFT;
531       dirsign = -1;
532     } else if(!controller->hold(Controller::LEFT)
533               && controller->hold(Controller::RIGHT)) {
534       old_dir = dir;
535       dir = RIGHT;
536       dirsign = 1;
537     }
538   }
539
540   // do not run if we're holding something which slows us down
541   if ( grabbed_object && grabbed_object->is_hampering() ) {
542     ax = dirsign * WALK_ACCELERATION_X;
543     // limit speed
544     if(vx >= MAX_WALK_XM && dirsign > 0) {
545       vx = MAX_WALK_XM;
546       ax = 0;
547     } else if(vx <= -MAX_WALK_XM && dirsign < 0) {
548       vx = -MAX_WALK_XM;
549       ax = 0;
550     }
551   } else {
552     if( vx * dirsign < MAX_WALK_XM ) {
553       ax = dirsign * WALK_ACCELERATION_X;
554     } else {
555       ax = dirsign * RUN_ACCELERATION_X;
556     }
557     // limit speed
558     if(vx >= MAX_RUN_XM + BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0) && dirsign > 0) {
559       vx = MAX_RUN_XM + BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0);
560       ax = 0;
561     } else if(vx <= -MAX_RUN_XM - BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0) && dirsign < 0) {
562       vx = -MAX_RUN_XM - BONUS_RUN_XM *((player_status->bonus == AIR_BONUS) ? 1 : 0);
563       ax = 0;
564     }
565   }
566
567   // we can reach WALK_SPEED without any acceleration
568   if(dirsign != 0 && fabs(vx) < WALK_SPEED) {
569     vx = dirsign * WALK_SPEED;
570   }
571
572   //Check speedlimit.
573   if( speedlimit > 0 &&  vx * dirsign >= speedlimit ) {
574     vx = dirsign * speedlimit;
575     ax = 0;
576   }
577
578   // changing directions?
579   if(on_ground() && ((vx < 0 && dirsign >0) || (vx>0 && dirsign<0))) {
580     // let's skid!
581     if(fabs(vx)>SKID_XM && !skidding_timer.started()) {
582       skidding_timer.start(SKID_TIME);
583       SoundManager::current()->play("sounds/skid.wav");
584       // dust some particles
585       Sector::current()->add_object(
586         std::make_shared<Particles>(
587           Vector(dir == LEFT ? get_bbox().p2.x : get_bbox().p1.x, get_bbox().p2.y),
588           dir == LEFT ? 50 : -70, dir == LEFT ? 70 : -50, 260, 280,
589           Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f, LAYER_OBJECTS+1));
590
591       ax *= 2.5;
592     } else {
593       ax *= 2;
594     }
595   }
596
597   if(on_ice) {
598     ax *= ICE_ACCELERATION_MULTIPLIER;
599   }
600
601   physic.set_velocity(vx, vy);
602   physic.set_acceleration(ax, ay);
603
604   // we get slower when not pressing any keys
605   if(dirsign == 0) {
606     apply_friction();
607   }
608
609 }
610
611 void
612 Player::do_cheer()
613 {
614   do_duck();
615   do_backflip();
616   do_standup();
617 }
618
619 void
620 Player::do_duck() {
621   if (duck)
622     return;
623   if (!is_big())
624     return;
625
626   if (physic.get_velocity_y() != 0)
627     return;
628   if (!on_ground())
629     return;
630   if (does_buttjump)
631     return;
632
633   if (adjust_height(DUCKED_TUX_HEIGHT)) {
634     duck = true;
635     growing = false;
636     unduck_hurt_timer.stop();
637   } else {
638     // FIXME: what now?
639   }
640 }
641
642 void
643 Player::do_standup() {
644   if (!duck)
645     return;
646   if (!is_big())
647     return;
648   if (backflipping)
649     return;
650   if (stone)
651     return;
652
653   if (adjust_height(BIG_TUX_HEIGHT)) {
654     duck = false;
655     unduck_hurt_timer.stop();
656   } else {
657     // if timer is not already running, start it.
658     if (unduck_hurt_timer.get_period() == 0) {
659       unduck_hurt_timer.start(UNDUCK_HURT_TIME);
660     }
661     else if (unduck_hurt_timer.check()) {
662       kill(false);
663     }
664   }
665
666 }
667
668 void
669 Player::do_backflip() {
670   if (!duck)
671     return;
672   if (!on_ground())
673     return;
674
675   backflip_direction = (dir == LEFT)?(+1):(-1);
676   backflipping = true;
677   do_jump((player_status->bonus == AIR_BONUS) ? -720 : -580);
678   SoundManager::current()->play("sounds/flip.wav");
679   backflip_timer.start(TUX_BACKFLIP_TIME);
680 }
681
682 void
683 Player::do_jump(float yspeed) {
684   if (!on_ground())
685     return;
686
687   physic.set_velocity_y(yspeed);
688   //bbox.move(Vector(0, -1));
689   jumping = true;
690   on_ground_flag = false;
691   can_jump = false;
692
693   // play sound
694   if (is_big()) {
695     SoundManager::current()->play("sounds/bigjump.wav");
696   } else {
697     SoundManager::current()->play("sounds/jump.wav");
698   }
699 }
700
701 void
702 Player::early_jump_apex()
703 {
704   if (!jump_early_apex)
705   {
706     jump_early_apex = true;
707     physic.set_gravity_modifier(JUMP_EARLY_APEX_FACTOR);
708   }
709 }
710
711 void
712 Player::do_jump_apex()
713 {
714   if (jump_early_apex)
715   {
716     jump_early_apex = false;
717     physic.set_gravity_modifier(1.0f);
718   }
719 }
720
721 void
722 Player::handle_vertical_input()
723 {
724   // Press jump key
725   if(controller->pressed(Controller::JUMP)) jump_button_timer.start(JUMP_GRACE_TIME);
726   if(controller->hold(Controller::JUMP) && jump_button_timer.started() && can_jump) {
727     jump_button_timer.stop();
728     if (duck) {
729       // when running, only jump a little bit; else do a backflip
730       if ((physic.get_velocity_x() != 0) ||
731           (controller->hold(Controller::LEFT)) ||
732           (controller->hold(Controller::RIGHT)))
733       {
734         do_jump(-300);
735       }
736       else
737       {
738         do_backflip();
739       }
740     } else {
741       // airflower allows for higher jumps-
742       // jump a bit higher if we are running; else do a normal jump
743       if(player_status->bonus == AIR_BONUS)
744         do_jump((fabs(physic.get_velocity_x()) > MAX_WALK_XM) ? -620 : -580);
745       else
746         do_jump((fabs(physic.get_velocity_x()) > MAX_WALK_XM) ? -580 : -520);
747     }
748     // airflower glide only when holding jump key
749   } else  if (controller->hold(Controller::JUMP) && player_status->bonus == AIR_BONUS && physic.get_velocity_y() > MAX_GLIDE_YM) {
750       if (ability_time > 0 && !ability_timer.started())
751         ability_timer.start(ability_time);
752       else if (ability_timer.started()) {
753         // glide stops after some duration or if buttjump is initiated
754         if ((ability_timer.get_timeleft() <= 0.05f) || controller->hold(Controller::DOWN)) {
755           ability_time = 0;
756           ability_timer.stop();
757         } else {
758           physic.set_velocity_y(MAX_GLIDE_YM);
759           physic.set_acceleration_y(0);
760         }
761       }
762     }
763
764
765   // Let go of jump key
766   else if(!controller->hold(Controller::JUMP)) {
767     if (!backflipping && jumping && physic.get_velocity_y() < 0) {
768       jumping = false;
769       early_jump_apex();
770     }
771     if (player_status->bonus == AIR_BONUS && ability_timer.started()){
772       ability_time = ability_timer.get_timeleft();
773       ability_timer.stop();
774     }
775   }
776
777   if(jump_early_apex && physic.get_velocity_y() >= 0) {
778     do_jump_apex();
779   }
780
781   /* In case the player has pressed Down while in a certain range of air,
782      enable butt jump action */
783   if (controller->hold(Controller::DOWN) && !duck && is_big() && !on_ground()) {
784     wants_buttjump = true;
785     if (physic.get_velocity_y() >= BUTTJUMP_MIN_VELOCITY_Y) does_buttjump = true;
786   }
787
788   /* When Down is not held anymore, disable butt jump */
789   if(!controller->hold(Controller::DOWN)) {
790     wants_buttjump = false;
791     does_buttjump = false;
792   }
793
794   // swimming
795   physic.set_acceleration_y(0);
796 #ifdef SWIMMING
797   if (swimming) {
798     if (controller->hold(Controller::UP) || controller->hold(Controller::JUMP))
799       physic.set_acceleration_y(-2000);
800     physic.set_velocity_y(physic.get_velocity_y() * 0.94);
801   }
802 #endif
803 }
804
805 void
806 Player::handle_input()
807 {
808   if (ghost_mode) {
809     handle_input_ghost();
810     return;
811   }
812   if (climbing) {
813     handle_input_climbing();
814     return;
815   }
816
817   /* Peeking */
818   if( controller->released( Controller::PEEK_LEFT ) || controller->released( Controller::PEEK_RIGHT ) ) {
819     peekingX = AUTO;
820   }
821   if( controller->released( Controller::PEEK_UP ) || controller->released( Controller::PEEK_DOWN ) ) {
822     peekingY = AUTO;
823   }
824   if( controller->pressed( Controller::PEEK_LEFT ) ) {
825     peekingX = LEFT;
826   }
827   if( controller->pressed( Controller::PEEK_RIGHT ) ) {
828     peekingX = RIGHT;
829   }
830   if(!backflipping && !jumping && on_ground()) {
831     if( controller->pressed( Controller::PEEK_UP ) ) {
832       peekingY = UP;
833     } else if( controller->pressed( Controller::PEEK_DOWN ) ) {
834       peekingY = DOWN;
835     }
836   }
837
838   /* Handle horizontal movement: */
839   if (!backflipping && !stone) handle_horizontal_input();
840
841   /* Jump/jumping? */
842   if (on_ground())
843     can_jump = true;
844
845   /* Handle vertical movement: */
846   if (!stone) handle_vertical_input();
847
848   /* Shoot! */
849   if (controller->pressed(Controller::ACTION) && (player_status->bonus == FIRE_BONUS || player_status->bonus == ICE_BONUS)) {
850     if((player_status->bonus == FIRE_BONUS &&
851       Sector::current()->get_active_bullets() < player_status->max_fire_bullets) ||
852       (player_status->bonus == ICE_BONUS &&
853       Sector::current()->get_active_bullets() < player_status->max_ice_bullets))
854     {
855       Vector pos = get_pos() + ((dir == LEFT)? Vector(0, bbox.get_height()/2) : Vector(32, bbox.get_height()/2));
856       auto new_bullet = std::make_shared<Bullet>(pos, physic.get_velocity_x(), dir, player_status->bonus);
857       Sector::current()->add_object(new_bullet);
858
859       SoundManager::current()->play("sounds/shoot.wav");
860       shooting_timer.start(SHOOTING_TIME);
861     }
862   }
863
864   /* Turn to Stone */
865   if (controller->pressed(Controller::DOWN) && player_status->bonus == EARTH_BONUS && !cooldown_timer.started()) {
866     if (controller->hold(Controller::ACTION) && !ability_timer.started()) {
867       ability_timer.start(player_status->max_earth_time * STONE_TIME_PER_FLOWER);
868       powersprite->stop_animation();
869       stone = true;
870       physic.set_gravity_modifier(1.0f); // Undo jump_early_apex
871     }
872   }
873
874   if (stone)
875     apply_friction();
876
877   /* Revert from Stone */
878   if (stone && (!controller->hold(Controller::ACTION) || ability_timer.get_timeleft() <= 0.5f)) {
879     cooldown_timer.start(ability_timer.get_timegone()/2.0f); //The longer stone form is used, the longer until it can be used again
880     ability_timer.stop();
881     sprite->set_angle(0.0f);
882     powersprite->set_angle(0.0f);
883     lightsprite->set_angle(0.0f);
884     stone = false;
885     for (int i = 0; i < 8; i++)
886     {
887       Vector ppos = Vector(get_bbox().get_left() + 8 + 16*((int)i/4), get_bbox().get_top() + 16*(i%4));
888       float grey = graphicsRandom.randf(.4f, .8f);
889       Color pcolor = Color(grey, grey, grey);
890       Sector::current()->add_object(std::make_shared<Particles>(ppos, -60, 240, 42, 81, Vector(0, 500),
891                                                                 8, pcolor, 4 + graphicsRandom.randf(-0.4, 0.4),
892                                                                 0.8 + graphicsRandom.randf(0, 0.4), LAYER_OBJECTS+2));
893     }
894   }
895
896   /* Duck or Standup! */
897   if (controller->hold(Controller::DOWN) && !stone) {
898     do_duck();
899   } else {
900     do_standup();
901   }
902
903   /* grabbing */
904   try_grab();
905
906   if(!controller->hold(Controller::ACTION) && grabbed_object) {
907     MovingObject* moving_object = dynamic_cast<MovingObject*> (grabbed_object);
908     if(moving_object) {
909       // move the grabbed object a bit away from tux
910       Rectf grabbed_bbox = moving_object->get_bbox();
911       Rectf dest_;
912       dest_.p2.y = bbox.get_top() + bbox.get_height()*0.66666;
913       dest_.p1.y = dest_.p2.y - grabbed_bbox.get_height();
914       if(dir == LEFT) {
915         dest_.p2.x = bbox.get_left() - 1;
916         dest_.p1.x = dest_.p2.x - grabbed_bbox.get_width();
917       } else {
918         dest_.p1.x = bbox.get_right() + 1;
919         dest_.p2.x = dest_.p1.x + grabbed_bbox.get_width();
920       }
921       if(Sector::current()->is_free_of_tiles(dest_, true)) {
922         moving_object->set_pos(dest_.p1);
923         if(controller->hold(Controller::UP)) {
924           grabbed_object->ungrab(*this, UP);
925         } else {
926           grabbed_object->ungrab(*this, dir);
927         }
928         grabbed_object = NULL;
929       }
930     } else {
931       log_debug << "Non MovingObject grabbed?!?" << std::endl;
932     }
933   }
934
935   /* stop backflipping at will */
936   if( backflipping && ( !controller->hold(Controller::JUMP) && !backflip_timer.started()) ){
937     backflipping = false;
938     backflip_direction = 0;
939     sprite->set_angle(0.0f);
940     powersprite->set_angle(0.0f);
941     lightsprite->set_angle(0.0f);
942   }
943 }
944
945 void
946 Player::position_grabbed_object()
947 {
948   MovingObject* moving_object = dynamic_cast<MovingObject*>(grabbed_object);
949   assert(moving_object);
950
951   // Position where we will hold the lower-inner corner
952   Vector pos(get_bbox().get_left() + get_bbox().get_width()/2,
953       get_bbox().get_top() + get_bbox().get_height()*0.66666);
954
955   // Adjust to find the grabbed object's upper-left corner
956   if (dir == LEFT)
957     pos.x -= moving_object->get_bbox().get_width();
958   pos.y -= moving_object->get_bbox().get_height();
959
960   grabbed_object->grab(*this, pos, dir);
961 }
962
963 void
964 Player::try_grab()
965 {
966   if(controller->hold(Controller::ACTION) && !grabbed_object
967      && !duck) {
968     Sector* sector = Sector::current();
969     Vector pos;
970     if(dir == LEFT) {
971       pos = Vector(bbox.get_left() - 5, bbox.get_bottom() - 16);
972     } else {
973       pos = Vector(bbox.get_right() + 5, bbox.get_bottom() - 16);
974     }
975
976     for(Sector::Portables::iterator i = sector->portables.begin();
977         i != sector->portables.end(); ++i) {
978       Portable* portable = *i;
979       if(!portable->is_portable())
980         continue;
981
982       // make sure the Portable is a MovingObject
983       MovingObject* moving_object = dynamic_cast<MovingObject*> (portable);
984       assert(moving_object);
985
986       // make sure the Portable isn't currently non-solid
987       if(moving_object->get_group() == COLGROUP_DISABLED) continue;
988
989       // check if we are within reach
990       if(moving_object->get_bbox().contains(pos)) {
991         if (climbing) stop_climbing(*climbing);
992         grabbed_object = portable;
993         position_grabbed_object();
994         break;
995       }
996     }
997   }
998 }
999
1000 void
1001 Player::handle_input_ghost()
1002 {
1003   float vx = 0;
1004   float vy = 0;
1005   if (controller->hold(Controller::LEFT)) {
1006     dir = LEFT;
1007     vx -= MAX_RUN_XM * 2;
1008   }
1009   if (controller->hold(Controller::RIGHT)) {
1010     dir = RIGHT;
1011     vx += MAX_RUN_XM * 2;
1012   }
1013   if ((controller->hold(Controller::UP)) || (controller->hold(Controller::JUMP))) {
1014     vy -= MAX_RUN_XM * 2;
1015   }
1016   if (controller->hold(Controller::DOWN)) {
1017     vy += MAX_RUN_XM * 2;
1018   }
1019   if (controller->hold(Controller::ACTION)) {
1020     set_ghost_mode(false);
1021   }
1022   physic.set_velocity(vx, vy);
1023   physic.set_acceleration(0, 0);
1024 }
1025
1026 void
1027 Player::add_coins(int count)
1028 {
1029   player_status->add_coins(count);
1030 }
1031
1032 int
1033 Player::get_coins()
1034 {
1035   return player_status->coins;
1036 }
1037
1038 bool
1039 Player::add_bonus(const std::string& bonustype)
1040 {
1041   BonusType type = NO_BONUS;
1042
1043   if(bonustype == "grow") {
1044     type = GROWUP_BONUS;
1045   } else if(bonustype == "fireflower") {
1046     type = FIRE_BONUS;
1047   } else if(bonustype == "iceflower") {
1048     type = ICE_BONUS;
1049   } else if(bonustype == "airflower") {
1050     type = AIR_BONUS;
1051   } else if(bonustype == "earthflower") {
1052     type = EARTH_BONUS;
1053   } else if(bonustype == "none") {
1054     type = NO_BONUS;
1055   } else {
1056     std::ostringstream msg;
1057     msg << "Unknown bonus type "  << bonustype;
1058     throw std::runtime_error(msg.str());
1059   }
1060
1061   return add_bonus(type);
1062 }
1063
1064 bool
1065 Player::add_bonus(BonusType type, bool animate)
1066 {
1067   // always ignore NO_BONUS
1068   if (type == NO_BONUS) {
1069     return true;
1070   }
1071
1072   // ignore GROWUP_BONUS if we're already big
1073   if (type == GROWUP_BONUS) {
1074     if (player_status->bonus != NO_BONUS)
1075       return true;
1076   }
1077
1078   return set_bonus(type, animate);
1079 }
1080
1081 bool
1082 Player::set_bonus(BonusType type, bool animate)
1083 {
1084   if((player_status->bonus == NO_BONUS) && (type != NO_BONUS)) {
1085     if (!adjust_height(BIG_TUX_HEIGHT)) {
1086       log_debug << "Can't adjust Tux height" << std::endl;
1087       return false;
1088     }
1089     if(animate) {
1090       growing = true;
1091       sprite->set_action((dir == LEFT)?"grow-left":"grow-right", 1);
1092     }
1093     if (climbing) stop_climbing(*climbing);
1094   }
1095
1096   if (type == NO_BONUS) {
1097     if (does_buttjump) does_buttjump = false;
1098   }
1099
1100   if ((type == NO_BONUS) || (type == GROWUP_BONUS)) {
1101     if ((player_status->bonus == FIRE_BONUS) && (animate)) {
1102       // visually lose helmet
1103       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1104       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1105       Vector paccel = Vector(0, 1000);
1106       std::string action = (dir==LEFT)?"left":"right";
1107       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/firetux-helmet.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1108       if (climbing) stop_climbing(*climbing);
1109     }
1110     if ((player_status->bonus == ICE_BONUS) && (animate)) {
1111       // visually lose cap
1112       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1113       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1114       Vector paccel = Vector(0, 1000);
1115       std::string action = (dir==LEFT)?"left":"right";
1116       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/icetux-cap.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1117       if (climbing) stop_climbing(*climbing);
1118     }
1119     if ((player_status->bonus == AIR_BONUS) && (animate)) {
1120       // visually lose hat
1121       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1122       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1123       Vector paccel = Vector(0, 1000);
1124       std::string action = (dir==LEFT)?"left":"right";
1125       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/airtux-hat.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1126       if (climbing) stop_climbing(*climbing);
1127     }
1128     if ((player_status->bonus == EARTH_BONUS) && (animate)) {
1129       // visually lose hard-hat
1130       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
1131       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
1132       Vector paccel = Vector(0, 1000);
1133       std::string action = (dir==LEFT)?"left":"right";
1134       Sector::current()->add_object(std::make_shared<SpriteParticle>("images/objects/particles/earthtux-hardhat.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
1135       if (climbing) stop_climbing(*climbing);
1136     }
1137     player_status->max_fire_bullets = 0;
1138     player_status->max_ice_bullets = 0;
1139     player_status->max_air_time = 0;
1140     player_status->max_earth_time = 0;
1141   }
1142   if (type == FIRE_BONUS) player_status->max_fire_bullets++;
1143   if (type == ICE_BONUS) player_status->max_ice_bullets++;
1144   if (type == AIR_BONUS) player_status->max_air_time++;
1145   if (type == EARTH_BONUS) player_status->max_earth_time++;
1146
1147   player_status->bonus = type;
1148   return true;
1149 }
1150
1151 void
1152 Player::set_visible(bool visible_)
1153 {
1154   this->visible = visible_;
1155   if( visible_ )
1156     set_group(COLGROUP_MOVING);
1157   else
1158     set_group(COLGROUP_DISABLED);
1159 }
1160
1161 bool
1162 Player::get_visible()
1163 {
1164   return visible;
1165 }
1166
1167 void
1168 Player::kick()
1169 {
1170   kick_timer.start(KICK_TIME);
1171 }
1172
1173 void
1174 Player::draw(DrawingContext& context)
1175 {
1176   if(!visible)
1177     return;
1178
1179   // if Tux is above camera, draw little "air arrow" to show where he is x-wise
1180   if (Sector::current() && Sector::current()->camera && (get_bbox().p2.y - 16 < Sector::current()->camera->get_translation().y)) {
1181     float px = get_pos().x + (get_bbox().p2.x - get_bbox().p1.x - airarrow.get()->get_width()) / 2;
1182     float py = Sector::current()->camera->get_translation().y;
1183     py += std::min(((py - (get_bbox().p2.y + 16)) / 4), 16.0f);
1184     context.draw_surface(airarrow, Vector(px, py), LAYER_HUD - 1);
1185   }
1186
1187   std::string sa_prefix = "";
1188   std::string sa_postfix = "";
1189
1190   if (player_status->bonus == GROWUP_BONUS)
1191     sa_prefix = "big";
1192   else if (player_status->bonus == FIRE_BONUS)
1193     sa_prefix = "fire";
1194   else if (player_status->bonus == ICE_BONUS)
1195     sa_prefix = "ice";
1196   else if (player_status->bonus == AIR_BONUS)
1197     sa_prefix = "air";
1198   else if (player_status->bonus == EARTH_BONUS)
1199     sa_prefix = "earth";
1200   else
1201     sa_prefix = "small";
1202
1203   if(dir == LEFT)
1204     sa_postfix = "-left";
1205   else
1206     sa_postfix = "-right";
1207
1208   /* Set Tux sprite action */
1209   if(dying) {
1210     sprite->set_action("gameover");
1211   }
1212   else if (growing) {
1213     sprite->set_action_continued("grow"+sa_postfix);
1214     // while growing, do not change action
1215     // do_duck() will take care of cancelling growing manually
1216     // update() will take care of cancelling when growing completed
1217   }
1218   else if (stone) {
1219     sprite->set_action(sprite->get_action()+"-stone");
1220   }
1221   else if (climbing) {
1222     sprite->set_action(sa_prefix+"-climbing"+sa_postfix);
1223   }
1224   else if (backflipping) {
1225     sprite->set_action(sa_prefix+"-backflip"+sa_postfix);
1226   }
1227   else if (duck && is_big()) {
1228     sprite->set_action(sa_prefix+"-duck"+sa_postfix);
1229   }
1230   else if (skidding_timer.started() && !skidding_timer.check()) {
1231     sprite->set_action(sa_prefix+"-skid"+sa_postfix);
1232   }
1233   else if (kick_timer.started() && !kick_timer.check()) {
1234     sprite->set_action(sa_prefix+"-kick"+sa_postfix);
1235   }
1236   else if ((wants_buttjump || does_buttjump) && is_big()) {
1237     sprite->set_action(sa_prefix+"-buttjump"+sa_postfix);
1238   }
1239   else if (!on_ground() || fall_mode != ON_GROUND) {
1240     if(physic.get_velocity_x() != 0 || fall_mode != ON_GROUND) {
1241         sprite->set_action(sa_prefix+"-jump"+sa_postfix);
1242     }
1243   }
1244   else {
1245     if (fabsf(physic.get_velocity_x()) < 1.0f) {
1246       // Determine which idle stage we're at
1247       if (sprite->get_action().find("-stand-") == std::string::npos && sprite->get_action().find("-idle-") == std::string::npos) {
1248         idle_stage = 0;
1249         idle_timer.start(IDLE_TIME[idle_stage]/1000.0f);
1250
1251         sprite->set_action_continued(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1252       }
1253       else if (idle_timer.check() || (IDLE_TIME[idle_stage] == 0 && sprite->animation_done())) {
1254         idle_stage++;
1255         if (idle_stage >= IDLE_STAGE_COUNT)
1256           idle_stage = 1;
1257
1258         idle_timer.start(IDLE_TIME[idle_stage]/1000.0f);
1259
1260         if (IDLE_TIME[idle_stage] == 0)
1261           sprite->set_action(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix, 1);
1262         else
1263           sprite->set_action(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1264       }
1265       else {
1266         sprite->set_action_continued(sa_prefix+("-" + IDLE_STAGES[idle_stage])+sa_postfix);
1267       }
1268     }
1269     else {
1270       sprite->set_action(sa_prefix+"-walk"+sa_postfix);
1271     }
1272   }
1273
1274   /* Set Tux powerup sprite action */
1275   if (player_status->bonus == EARTH_BONUS) {
1276     powersprite->set_action(sprite->get_action());
1277     lightsprite->set_action(sprite->get_action());
1278   } else if (player_status->bonus == AIR_BONUS)
1279     powersprite->set_action(sprite->get_action());
1280
1281   /*
1282   // Tux is holding something
1283   if ((grabbed_object != 0 && physic.get_velocity_y() == 0) ||
1284   (shooting_timer.get_timeleft() > 0 && !shooting_timer.check())) {
1285   if (duck) {
1286   } else {
1287   }
1288   }
1289   */
1290
1291   /* Draw Tux */
1292   if (safe_timer.started() && size_t(game_time*40)%2)
1293     ;  // don't draw Tux
1294   else if (player_status->bonus == EARTH_BONUS){ // draw special effects with earthflower bonus
1295     // shake at end of maximum stone duration
1296     Vector shake_delta = (stone && ability_timer.get_timeleft() < 1.0f) ? Vector(graphicsRandom.rand(-3,3), 0) : Vector(0,0);
1297     sprite->draw(context, get_pos() + shake_delta, LAYER_OBJECTS + 1);
1298     // draw hardhat
1299     powersprite->draw(context, get_pos() + shake_delta, LAYER_OBJECTS + 1);
1300     // light
1301     context.push_target();
1302     context.set_target(DrawingContext::LIGHTMAP);
1303     lightsprite->draw(context, get_pos(), 0);
1304     context.pop_target();
1305     // give an indicator that stone form cannot be used for a while
1306     if (cooldown_timer.started() && graphicsRandom.rand(0, 4) == 0) {
1307       float px = graphicsRandom.randf(bbox.p1.x, bbox.p2.x);
1308       float py = bbox.p2.y+8;
1309       Vector ppos = Vector(px, py);
1310       Sector::current()->add_object(std::make_shared<SpriteParticle>(
1311         "images/objects/particles/sparkle.sprite", "dark",
1312         ppos, ANCHOR_MIDDLE, Vector(0, 0), Vector(0, 0), LAYER_OBJECTS+1+5));
1313     }
1314   }
1315   else {
1316     if(dying)
1317       sprite->draw(context, get_pos(), Sector::current()->get_foremost_layer() + 1);
1318     else
1319       sprite->draw(context, get_pos(), LAYER_OBJECTS + 1);
1320
1321     if (player_status->bonus == AIR_BONUS)
1322       powersprite->draw(context, get_pos(), LAYER_OBJECTS + 1);
1323   }
1324
1325 }
1326
1327 void
1328 Player::collision_tile(uint32_t tile_attributes)
1329 {
1330   if(tile_attributes & Tile::HURTS)
1331     kill(false);
1332
1333 #ifdef SWIMMING
1334   if( swimming ){
1335     if( tile_attributes & Tile::WATER ){
1336       no_water = false;
1337     } else {
1338       swimming = false;
1339     }
1340   } else {
1341     if( tile_attributes & Tile::WATER ){
1342       swimming = true;
1343       no_water = false;
1344       SoundManager::current()->play( "sounds/splash.wav" );
1345     }
1346   }
1347 #endif
1348
1349   if(tile_attributes & Tile::ICE) {
1350     ice_this_frame = true;
1351     on_ice = true;
1352   }
1353 }
1354
1355 void
1356 Player::collision_solid(const CollisionHit& hit)
1357 {
1358   if(hit.bottom) {
1359     if(physic.get_velocity_y() > 0)
1360       physic.set_velocity_y(0);
1361
1362     on_ground_flag = true;
1363     floor_normal = hit.slope_normal;
1364
1365     // Butt Jump landed
1366     if (does_buttjump) {
1367       does_buttjump = false;
1368       physic.set_velocity_y(-300);
1369       on_ground_flag = false;
1370       Sector::current()->add_object(std::make_shared<Particles>(
1371                                       Vector(get_bbox().p2.x, get_bbox().p2.y),
1372                                       50, 70, 260, 280, Vector(0, 300), 3,
1373                                       Color(.4f, .4f, .4f), 3, .8f, LAYER_OBJECTS+1));
1374       Sector::current()->add_object(std::make_shared<Particles>(
1375                                       Vector(get_bbox().p1.x, get_bbox().p2.y),
1376                                       -70, -50, 260, 280, Vector(0, 300), 3,
1377                                       Color(.4f, .4f, .4f), 3, .8f, LAYER_OBJECTS+1));
1378       Sector::current()->camera->shake(.1f, 0, 5);
1379     }
1380
1381   } else if(hit.top) {
1382     if(physic.get_velocity_y() < 0)
1383       physic.set_velocity_y(.2f);
1384   }
1385
1386   if(hit.left || hit.right) {
1387     physic.set_velocity_x(0);
1388   }
1389
1390   // crushed?
1391   if(hit.crush) {
1392     if(hit.left || hit.right) {
1393       kill(true);
1394     } else if(hit.top || hit.bottom) {
1395       kill(false);
1396     }
1397   }
1398 }
1399
1400 HitResponse
1401 Player::collision(GameObject& other, const CollisionHit& hit)
1402 {
1403   Bullet* bullet = dynamic_cast<Bullet*> (&other);
1404   if(bullet) {
1405     return FORCE_MOVE;
1406   }
1407
1408   Player* player = dynamic_cast<Player*> (&other);
1409   if(player) {
1410     return ABORT_MOVE;
1411   }
1412
1413   if(hit.left || hit.right) {
1414     try_grab(); //grab objects right now, in update it will be too late
1415   }
1416   assert(dynamic_cast<MovingObject*> (&other) != NULL);
1417   MovingObject* moving_object = static_cast<MovingObject*> (&other);
1418   if(moving_object->get_group() == COLGROUP_TOUCHABLE) {
1419     TriggerBase* trigger = dynamic_cast<TriggerBase*> (&other);
1420     if(trigger) {
1421       if(controller->pressed(Controller::UP))
1422         trigger->event(*this, TriggerBase::EVENT_ACTIVATE);
1423     }
1424
1425     return FORCE_MOVE;
1426   }
1427
1428   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
1429   if(badguy != NULL) {
1430     if(safe_timer.started() || invincible_timer.started())
1431       return FORCE_MOVE;
1432     if(stone)
1433       return ABORT_MOVE;
1434
1435     return CONTINUE;
1436   }
1437
1438   return CONTINUE;
1439 }
1440
1441 void
1442 Player::make_invincible()
1443 {
1444   SoundManager::current()->play("sounds/invincible_start.ogg");
1445   invincible_timer.start(TUX_INVINCIBLE_TIME);
1446   Sector::current()->play_music(HERRING_MUSIC);
1447 }
1448
1449 /* Kill Player! */
1450 void
1451 Player::kill(bool completely)
1452 {
1453   if(dying || deactivated || is_winning() )
1454     return;
1455
1456   if(!completely && (safe_timer.started() || invincible_timer.started() || stone))
1457     return;
1458
1459   growing = false;
1460
1461   if (climbing) stop_climbing(*climbing);
1462
1463   physic.set_velocity_x(0);
1464
1465   sprite->set_angle(0.0f);
1466   powersprite->set_angle(0.0f);
1467   lightsprite->set_angle(0.0f);
1468
1469   if(!completely && is_big()) {
1470     SoundManager::current()->play("sounds/hurt.wav");
1471
1472     if(player_status->bonus == FIRE_BONUS
1473       || player_status->bonus == ICE_BONUS
1474       || player_status->bonus == AIR_BONUS
1475       || player_status->bonus == EARTH_BONUS) {
1476       safe_timer.start(TUX_SAFE_TIME);
1477       set_bonus(GROWUP_BONUS, true);
1478     } else if(player_status->bonus == GROWUP_BONUS) {
1479       safe_timer.start(TUX_SAFE_TIME /* + GROWING_TIME */);
1480       adjust_height(SMALL_TUX_HEIGHT);
1481       duck = false;
1482       backflipping = false;
1483       sprite->set_angle(0.0f);
1484       powersprite->set_angle(0.0f);
1485       lightsprite->set_angle(0.0f);
1486       set_bonus(NO_BONUS, true);
1487     } else if(player_status->bonus == NO_BONUS) {
1488       safe_timer.start(TUX_SAFE_TIME);
1489       adjust_height(SMALL_TUX_HEIGHT);
1490       duck = false;
1491     }
1492   } else {
1493     SoundManager::current()->play("sounds/kill.wav");
1494
1495     // do not die when in edit mode
1496     if (edit_mode) {
1497       set_ghost_mode(true);
1498       return;
1499     }
1500
1501     if (player_status->coins >= 25 && !GameSession::current()->get_reset_point_sectorname().empty())
1502     {
1503       for (int i = 0; i < 5; i++)
1504       {
1505         // the numbers: starting x, starting y, velocity y
1506         Sector::current()->add_object(std::make_shared<FallingCoin>(get_pos() +
1507                                                       Vector(graphicsRandom.rand(5), graphicsRandom.rand(-32,18)),
1508                                                       graphicsRandom.rand(-100,100)));
1509       }
1510       player_status->coins -= std::max(player_status->coins/10, 25);
1511     }
1512     else
1513     {
1514       GameSession::current()->set_reset_point("", Vector());
1515     }
1516     physic.enable_gravity(true);
1517     physic.set_gravity_modifier(1.0f); // Undo jump_early_apex
1518     safe_timer.stop();
1519     invincible_timer.stop();
1520     physic.set_acceleration(0, 0);
1521     physic.set_velocity(0, -700);
1522     set_bonus(NO_BONUS, true);
1523     dying = true;
1524     dying_timer.start(3.0);
1525     set_group(COLGROUP_DISABLED);
1526
1527     // TODO: need nice way to handle players dying in co-op mode
1528     Sector::current()->effect->fade_out(3.0);
1529     SoundManager::current()->pause_music(3.0);
1530   }
1531 }
1532
1533 void
1534 Player::move(const Vector& vector)
1535 {
1536   set_pos(vector);
1537
1538   // Reset size to get correct hitbox if Tux was eg. ducked before moving
1539   if(is_big())
1540     set_size(TUX_WIDTH, BIG_TUX_HEIGHT);
1541   else
1542     set_size(TUX_WIDTH, SMALL_TUX_HEIGHT);
1543   duck = false;
1544   backflipping = false;
1545   sprite->set_angle(0.0f);
1546   powersprite->set_angle(0.0f);
1547   lightsprite->set_angle(0.0f);
1548   last_ground_y = vector.y;
1549   if (climbing) stop_climbing(*climbing);
1550
1551   physic.reset();
1552 }
1553
1554 void
1555 Player::check_bounds()
1556 {
1557   /* Keep tux in sector bounds: */
1558   if (get_pos().x < 0) {
1559     // Lock Tux to the size of the level, so that he doesn't fall off
1560     // the left side
1561     set_pos(Vector(0, get_pos().y));
1562   }
1563
1564   if (get_bbox().get_right() > Sector::current()->get_width()) {
1565     // Lock Tux to the size of the level, so that he doesn't fall off
1566     // the right side
1567     set_pos(Vector(Sector::current()->get_width() - get_bbox().get_width(), get_pos().y));
1568   }
1569
1570   /* fallen out of the level? */
1571   if ((get_pos().y > Sector::current()->get_height()) && (!ghost_mode)) {
1572     kill(true);
1573     return;
1574   }
1575 }
1576
1577 void
1578 Player::add_velocity(const Vector& velocity)
1579 {
1580   physic.set_velocity(physic.get_velocity() + velocity);
1581 }
1582
1583 void
1584 Player::add_velocity(const Vector& velocity, const Vector& end_speed)
1585 {
1586   if (end_speed.x > 0)
1587     physic.set_velocity_x(std::min(physic.get_velocity_x() + velocity.x, end_speed.x));
1588   if (end_speed.x < 0)
1589     physic.set_velocity_x(std::max(physic.get_velocity_x() + velocity.x, end_speed.x));
1590   if (end_speed.y > 0)
1591     physic.set_velocity_y(std::min(physic.get_velocity_y() + velocity.y, end_speed.y));
1592   if (end_speed.y < 0)
1593     physic.set_velocity_y(std::max(physic.get_velocity_y() + velocity.y, end_speed.y));
1594 }
1595
1596 Vector
1597 Player::get_velocity()
1598 {
1599   return physic.get_velocity();
1600 }
1601
1602 void
1603 Player::bounce(BadGuy& )
1604 {
1605   if(!(player_status->bonus == AIR_BONUS))
1606     physic.set_velocity_y(controller->hold(Controller::JUMP) ? -520 : -300);
1607   else {
1608     physic.set_velocity_y(controller->hold(Controller::JUMP) ? -580 : -340);
1609     ability_time = player_status->max_air_time * GLIDE_TIME_PER_FLOWER;
1610   }
1611 }
1612
1613 //scripting Functions Below
1614
1615 void
1616 Player::deactivate()
1617 {
1618   if (deactivated)
1619     return;
1620   deactivated = true;
1621   physic.set_velocity_x(0);
1622   physic.set_velocity_y(0);
1623   physic.set_acceleration_x(0);
1624   physic.set_acceleration_y(0);
1625   if (climbing) stop_climbing(*climbing);
1626 }
1627
1628 void
1629 Player::activate()
1630 {
1631   if (!deactivated)
1632     return;
1633   deactivated = false;
1634 }
1635
1636 void Player::walk(float speed)
1637 {
1638   physic.set_velocity_x(speed);
1639 }
1640
1641 void Player::set_dir(bool right)
1642 {
1643   dir = right ? RIGHT : LEFT;
1644 }
1645
1646 void
1647 Player::set_ghost_mode(bool enable)
1648 {
1649   if (ghost_mode == enable)
1650     return;
1651
1652   if (climbing) stop_climbing(*climbing);
1653
1654   if (enable) {
1655     ghost_mode = true;
1656     set_group(COLGROUP_DISABLED);
1657     physic.enable_gravity(false);
1658     log_debug << "You feel lightheaded. Use movement controls to float around, press ACTION to scare badguys." << std::endl;
1659   } else {
1660     ghost_mode = false;
1661     set_group(COLGROUP_MOVING);
1662     physic.enable_gravity(true);
1663     log_debug << "You feel solid again." << std::endl;
1664   }
1665 }
1666
1667 void
1668 Player::set_edit_mode(bool enable)
1669 {
1670   edit_mode = enable;
1671 }
1672
1673 void
1674 Player::start_climbing(Climbable& climbable)
1675 {
1676   if (climbing || !&climbable) return;
1677
1678   climbing = &climbable;
1679   physic.enable_gravity(false);
1680   physic.set_velocity(0, 0);
1681   physic.set_acceleration(0, 0);
1682   if (backflipping) {
1683     backflipping = false;
1684     backflip_direction = 0;
1685     sprite->set_angle(0.0f);
1686     powersprite->set_angle(0.0f);
1687     lightsprite->set_angle(0.0f);
1688   }
1689 }
1690
1691 void
1692 Player::stop_climbing(Climbable& /*climbable*/)
1693 {
1694   if (!climbing) return;
1695
1696   climbing = 0;
1697
1698   if (grabbed_object) {
1699     grabbed_object->ungrab(*this, dir);
1700     grabbed_object = NULL;
1701   }
1702
1703   physic.enable_gravity(true);
1704   physic.set_velocity(0, 0);
1705   physic.set_acceleration(0, 0);
1706
1707   if ((controller->hold(Controller::JUMP)) || (controller->hold(Controller::UP))) {
1708     on_ground_flag = true;
1709     // TODO: This won't help. Why?
1710     do_jump(-300);
1711   }
1712 }
1713
1714 void
1715 Player::handle_input_climbing()
1716 {
1717   if (!climbing) {
1718     log_warning << "handle_input_climbing called with climbing set to 0. Input handling skipped" << std::endl;
1719     return;
1720   }
1721
1722   float vx = 0;
1723   float vy = 0;
1724   if (controller->hold(Controller::LEFT)) {
1725     dir = LEFT;
1726     vx -= MAX_CLIMB_XM;
1727   }
1728   if (controller->hold(Controller::RIGHT)) {
1729     dir = RIGHT;
1730     vx += MAX_CLIMB_XM;
1731   }
1732   if (controller->hold(Controller::UP)) {
1733     vy -= MAX_CLIMB_YM;
1734   }
1735   if (controller->hold(Controller::DOWN)) {
1736     vy += MAX_CLIMB_YM;
1737   }
1738   if (controller->hold(Controller::JUMP)) {
1739     if (can_jump) {
1740       stop_climbing(*climbing);
1741       return;
1742     }
1743   } else {
1744     can_jump = true;
1745   }
1746   if (controller->hold(Controller::ACTION)) {
1747     stop_climbing(*climbing);
1748     return;
1749   }
1750   physic.set_velocity(vx, vy);
1751   physic.set_acceleration(0, 0);
1752 }
1753
1754 /* EOF */