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