Experimental modification of jumping behaviour
[supertux.git] / src / object / player.cpp
1 //  $Id$
2 //
3 //  SuperTux
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <typeinfo>
22 #include <cmath>
23 #include <iostream>
24 #include <cassert>
25
26 #include "gettext.hpp"
27 #include "sprite/sprite_manager.hpp"
28 #include "audio/sound_manager.hpp"
29 #include "player.hpp"
30 #include "tile.hpp"
31 #include "sprite/sprite.hpp"
32 #include "sector.hpp"
33 #include "resources.hpp"
34 #include "statistics.hpp"
35 #include "game_session.hpp"
36 #include "object/tilemap.hpp"
37 #include "object/camera.hpp"
38 #include "object/particles.hpp"
39 #include "object/portable.hpp"
40 #include "object/bullet.hpp"
41 #include "trigger/trigger_base.hpp"
42 #include "control/joystickkeyboardcontroller.hpp"
43 #include "scripting/squirrel_util.hpp"
44 #include "main.hpp"
45 #include "platform.hpp"
46 #include "badguy/badguy.hpp"
47 #include "player_status.hpp"
48 #include "log.hpp"
49 #include "falling_coin.hpp"
50 #include "random_generator.hpp"
51 #include "object/sprite_particle.hpp"
52 #include "trigger/climbable.hpp"
53
54 static const int TILES_FOR_BUTTJUMP = 3;
55 static const float SHOOTING_TIME = .150f;
56 /// time before idle animation starts
57 static const float IDLE_TIME = 2.5f;
58
59 /** acceleration in horizontal direction when walking
60  * (all acceleratiosn are in  pixel/s^2) */
61 static const float WALK_ACCELERATION_X = 300;
62 /** acceleration in horizontal direction when running */ 
63 static const float RUN_ACCELERATION_X = 400;
64 /** acceleration when skidding */
65 static const float SKID_XM = 200;
66 /** time of skidding in seconds */
67 static const float SKID_TIME = .3f;
68 /** maximum walk velocity (pixel/s) */
69 static const float MAX_WALK_XM = 230;
70 /** maximum run velcoity (pixel/s) */
71 static const float MAX_RUN_XM = 320;
72 /** maximum horizontal climb velocity */
73 static const float MAX_CLIMB_XM = 48;
74 /** maximum vertical climb velocity */
75 static const float MAX_CLIMB_YM = 128;
76 /** instant velocity when tux starts to walk */
77 static const float WALK_SPEED = 100;
78
79 /** time of the kick (kicking mriceblock) animation */
80 static const float KICK_TIME = .3f;
81 /** time of tux cheering (currently unused) */
82 static const float CHEER_TIME = 1.0f;
83
84 /** if Tux cannot unduck for this long, he will get hurt */
85 static const float UNDUCK_HURT_TIME = 0.25f;
86
87 // growing animation
88 Surface* growingtux_left[GROWING_FRAMES];
89 Surface* growingtux_right[GROWING_FRAMES];
90
91 Surface* tux_life = 0;
92
93 TuxBodyParts* small_tux = 0;
94 TuxBodyParts* big_tux = 0;
95 TuxBodyParts* fire_tux = 0;
96 TuxBodyParts* ice_tux = 0;
97
98 namespace{
99   bool no_water = true;
100 }
101 void
102 TuxBodyParts::set_action(std::string action, int loops)
103 {
104   if(head != NULL)
105     head->set_action(action, loops);
106   if(body != NULL)
107     body->set_action(action, loops);
108   if(arms != NULL)
109     arms->set_action(action, loops);
110   if(feet != NULL)
111     feet->set_action(action, loops);
112 }
113
114 void
115 TuxBodyParts::draw(DrawingContext& context, const Vector& pos, int layer)
116 {
117   if(head != NULL)
118     head->draw(context, pos, layer-1);
119   if(body != NULL)
120     body->draw(context, pos, layer-3);
121   if(arms != NULL)
122     arms->draw(context, pos, layer+10);
123   if(feet != NULL)
124     feet->draw(context, pos, layer-2);
125 }
126
127 Player::Player(PlayerStatus* _player_status, const std::string& name)
128   : player_status(_player_status), grabbed_object(NULL), ghost_mode(false), climbing(0)
129 {
130   this->name = name;
131   controller = main_controller;
132   smalltux_gameover = sprite_manager->create("images/creatures/tux_small/smalltux-gameover.sprite");
133   smalltux_star = sprite_manager->create("images/creatures/tux_small/smalltux-star.sprite");
134   bigtux_star = sprite_manager->create("images/creatures/tux_big/bigtux-star.sprite");
135   airarrow.reset(new Surface("images/engine/hud/airarrow.png"));
136
137   sound_manager->preload("sounds/bigjump.wav");
138   sound_manager->preload("sounds/jump.wav");
139   sound_manager->preload("sounds/hurt.wav");
140   sound_manager->preload("sounds/skid.wav");
141   sound_manager->preload("sounds/flip.wav");
142   sound_manager->preload("sounds/invincible.wav");
143   sound_manager->preload("sounds/splash.ogg");
144
145   init();
146 }
147
148 Player::~Player()
149 {
150   if (climbing) stop_climbing(*climbing);
151   delete smalltux_gameover;
152   delete smalltux_star;
153   delete bigtux_star;
154 }
155
156 void
157 Player::init()
158 {
159   if(is_big())
160     set_size(31.8f, 62.8f);
161   else
162     set_size(31.8f, 30.8f);
163
164   dir = RIGHT;
165   old_dir = dir;
166   duck = false;
167   dead = false;
168
169   dying = false;
170   peeking = AUTO;
171   last_ground_y = 0;
172   fall_mode = ON_GROUND;
173   jumping = false;
174   can_jump = true;
175   butt_jump = false;
176   deactivated = false;
177   backflipping = false;
178   backflip_direction = 0;
179   visible = true;
180   swimming = false;
181   speedlimit = 0; //no special limit
182
183   on_ground_flag = false;
184   grabbed_object = NULL;
185
186   climbing = 0;
187
188   physic.reset();
189 }
190
191 void
192 Player::expose(HSQUIRRELVM vm, SQInteger table_idx)
193 {
194   if (name.empty())
195     return;
196
197   Scripting::expose_object(vm, table_idx, dynamic_cast<Scripting::Player *>(this), name, false);
198 }
199
200 void
201 Player::unexpose(HSQUIRRELVM vm, SQInteger table_idx)
202 {
203   if (name.empty())
204     return;
205
206   Scripting::unexpose_object(vm, table_idx, name);
207 }
208
209 float
210 Player::get_speedlimit()
211 {
212   return speedlimit;
213 }
214
215 void
216 Player::set_speedlimit(float newlimit)
217 {
218   speedlimit=newlimit;
219 }
220
221 void
222 Player::set_controller(Controller* controller)
223 {
224   this->controller = controller;
225 }
226
227 bool
228 Player::adjust_height(float new_height)
229 {
230   Rect bbox2 = bbox;
231   bbox2.move(Vector(0, bbox.get_height() - new_height));
232   bbox2.set_height(new_height);
233
234   if(new_height > bbox.get_height()) {
235     Rect additional_space = bbox2;
236     additional_space.set_height(new_height - bbox.get_height());
237     if(!Sector::current()->is_free_of_statics(additional_space, this, true))
238       return false;
239   }
240
241   // adjust bbox accordingly
242   // note that we use members of moving_object for this, so we can run this during CD, too
243   set_pos(bbox2.p1);
244   set_size(bbox2.get_width(), bbox2.get_height());
245   return true;
246 }
247
248 void
249 Player::trigger_sequence(std::string sequence_name)
250 {
251   if (climbing) stop_climbing(*climbing);
252   GameSession::current()->start_sequence(sequence_name);
253 }
254
255 void
256 Player::update(float elapsed_time)
257 {
258   if( no_water ){
259     swimming = false;
260   }
261   no_water = true;
262
263   if(dying && dying_timer.check()) {
264     dead = true;
265     return;
266   }
267
268   if(!dying && !deactivated)
269     handle_input();
270
271   // handle_input() calls apply_friction() when Tux is not walking, so we'll have to do this ourselves
272   if (deactivated)
273     apply_friction();
274
275   // extend/shrink tux collision rectangle so that we fall through/walk over 1
276   // tile holes
277   if(fabsf(physic.get_velocity_x()) > MAX_WALK_XM) {
278     set_width(34);
279   } else {
280     set_width(31.8f);
281   }
282
283   // on downward slopes, adjust vertical velocity so tux walks smoothly down
284   if (on_ground()) {
285     if(floor_normal.y != 0) {
286       if ((floor_normal.x * physic.get_velocity_x()) >= 0) {
287         physic.set_velocity_y(250);
288       }
289     }
290   }
291
292   // handle backflipping
293   if (backflipping) {
294     //prevent player from changing direction when backflipping
295     dir = (backflip_direction == 1) ? LEFT : RIGHT;
296     if (backflip_timer.started()) physic.set_velocity_x(100 * backflip_direction);
297   }
298
299   // set fall mode...
300   if(on_ground()) {
301     fall_mode = ON_GROUND;
302     last_ground_y = get_pos().y;
303   } else {
304     if(get_pos().y > last_ground_y)
305       fall_mode = FALLING;
306     else if(fall_mode == ON_GROUND)
307       fall_mode = JUMPING;
308   }
309
310   // check if we landed
311   if(on_ground()) {
312     jumping = false;
313     if (backflipping && (!backflip_timer.started())) {
314       backflipping = false;
315       backflip_direction = 0;
316
317       // if controls are currently deactivated, we take care of standing up ourselves
318       if (deactivated)
319         do_standup();
320     }
321   }
322
323   // calculate movement for this frame
324   movement = physic.get_movement(elapsed_time);
325
326   if(grabbed_object != NULL && !dying) {
327     Vector pos = get_pos() +
328       Vector(dir == LEFT ? -16 : 16, get_bbox().get_height()*0.66666 - 32);
329     grabbed_object->grab(*this, pos, dir);
330   }
331
332   if(grabbed_object != NULL && dying){
333     grabbed_object->ungrab(*this, dir);
334     grabbed_object = NULL;
335   }
336
337   on_ground_flag = false;
338
339   // when invincible, spawn particles
340   if (invincible_timer.started() && !dying)
341   {
342     if (systemRandom.rand(0, 2) == 0) {
343       float px = systemRandom.randf(bbox.p1.x+0, bbox.p2.x-0);
344       float py = systemRandom.randf(bbox.p1.y+0, bbox.p2.y-0);
345       Vector ppos = Vector(px, py);
346       Vector pspeed = Vector(0, 0);
347       Vector paccel = Vector(0, 0);
348       // draw bright sparkle when there is lots of time left, dark sparkle when invincibility is about to end
349       if (invincible_timer.get_timeleft() > TUX_INVINCIBLE_TIME_WARNING) {
350         // make every other a longer sparkle to make trail a bit fuzzy
351         if (size_t(game_time*20)%2) {
352           Sector::current()->add_object(new SpriteParticle("images/objects/particles/sparkle.sprite", "small", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
353         } else {
354           Sector::current()->add_object(new SpriteParticle("images/objects/particles/sparkle.sprite", "medium", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
355         }
356       } else {
357         Sector::current()->add_object(new SpriteParticle("images/objects/particles/sparkle.sprite", "dark", ppos, ANCHOR_MIDDLE, pspeed, paccel, LAYER_OBJECTS+1+5));
358       }
359     }
360   }
361
362 }
363
364 bool
365 Player::on_ground()
366 {
367   return on_ground_flag;
368 }
369
370 bool
371 Player::is_big()
372 {
373   if(player_status->bonus == NO_BONUS)
374     return false;
375
376   return true;
377 }
378
379 void
380 Player::apply_friction()
381 {
382   if ((on_ground()) && (fabs(physic.get_velocity_x()) < WALK_SPEED)) {
383     physic.set_velocity_x(0);
384     physic.set_acceleration_x(0);
385   } else if(physic.get_velocity_x() < 0) {
386     physic.set_acceleration_x(WALK_ACCELERATION_X * 1.5);
387     } else if(physic.get_velocity_x() > 0) {
388     physic.set_acceleration_x(WALK_ACCELERATION_X * -1.5);
389   }
390 }
391
392 void
393 Player::handle_horizontal_input()
394 {
395   float vx = physic.get_velocity_x();
396   float vy = physic.get_velocity_y();
397   float ax = physic.get_acceleration_x();
398   float ay = physic.get_acceleration_y();
399
400   float dirsign = 0;
401   if(!duck || physic.get_velocity_y() != 0) {
402     if(controller->hold(Controller::LEFT) && !controller->hold(Controller::RIGHT)) {
403       old_dir = dir;
404       dir = LEFT;
405       dirsign = -1;
406     } else if(!controller->hold(Controller::LEFT)
407               && controller->hold(Controller::RIGHT)) {
408       old_dir = dir;
409       dir = RIGHT;
410       dirsign = 1;
411     }
412   }
413
414   // do not run if action key is pressed or we're holding something
415   // so tux can only walk while shooting
416   if ( controller->hold(Controller::ACTION) || grabbed_object ) {
417     ax = dirsign * WALK_ACCELERATION_X;
418     // limit speed
419     if(vx >= MAX_WALK_XM && dirsign > 0) {
420       vx = MAX_WALK_XM;
421       ax = 0;
422     } else if(vx <= -MAX_WALK_XM && dirsign < 0) {
423       vx = -MAX_WALK_XM;
424       ax = 0;
425     }
426   } else {
427     if( vx * dirsign < MAX_WALK_XM ) {
428       ax = dirsign * WALK_ACCELERATION_X;
429     } else {
430       ax = dirsign * RUN_ACCELERATION_X;
431     }
432     // limit speed
433     if(vx >= MAX_RUN_XM && dirsign > 0) {
434       vx = MAX_RUN_XM;
435       ax = 0;
436     } else if(vx <= -MAX_RUN_XM && dirsign < 0) {
437       vx = -MAX_RUN_XM;
438       ax = 0;
439     }
440   }
441
442   // we can reach WALK_SPEED without any acceleration
443   if(dirsign != 0 && fabs(vx) < WALK_SPEED) {
444     vx = dirsign * WALK_SPEED;
445   }
446
447   //Check speedlimit.
448   if( speedlimit > 0 &&  vx * dirsign >= speedlimit ) {
449       vx = dirsign * speedlimit;
450       ax = 0;
451   }
452
453   // changing directions?
454   if(on_ground() && ((vx < 0 && dirsign >0) || (vx>0 && dirsign<0))) {
455     // let's skid!
456     if(fabs(vx)>SKID_XM && !skidding_timer.started()) {
457       skidding_timer.start(SKID_TIME);
458       sound_manager->play("sounds/skid.wav");
459       // dust some particles
460       Sector::current()->add_object(
461         new Particles(
462           Vector(dir == RIGHT ? get_bbox().p2.x : get_bbox().p1.x, get_bbox().p2.y),
463           dir == RIGHT ? 270+20 : 90-40, dir == RIGHT ? 270+40 : 90-20,
464           Vector(280, -260), Vector(0, 300), 3, Color(.4f, .4f, .4f), 3, .8f,
465           LAYER_OBJECTS+1));
466
467       ax *= 2.5;
468     } else {
469       ax *= 2;
470     }
471   }
472
473   physic.set_velocity(vx, vy);
474   physic.set_acceleration(ax, ay);
475
476   // we get slower when not pressing any keys
477   if(dirsign == 0) {
478     apply_friction();
479   }
480
481 }
482
483 void
484 Player::do_cheer()
485 {
486   do_duck();
487   do_backflip();
488   do_standup();
489 }
490
491 void
492 Player::do_duck() {
493   if (duck)
494     return;
495   if (!is_big())
496     return;
497
498   if (physic.get_velocity_y() != 0)
499     return;
500   if (!on_ground())
501     return;
502
503   if (adjust_height(31.8f)) {
504     duck = true;
505     unduck_hurt_timer.stop();
506   } else {
507     // FIXME: what now?
508   }
509 }
510
511 void
512 Player::do_standup() {
513   if (!duck)
514     return;
515   if (!is_big())
516     return;
517   if (backflipping)
518     return;
519
520   if (adjust_height(63.8f)) {
521     duck = false;
522     unduck_hurt_timer.stop();
523   } else {
524     // if timer is not already running, start it.
525     if (unduck_hurt_timer.get_period() == 0) {
526       unduck_hurt_timer.start(UNDUCK_HURT_TIME);
527     }
528     else if (unduck_hurt_timer.check()) {
529       kill(false);
530     }
531   }
532
533 }
534
535 void
536 Player::do_backflip() {
537   if (!duck)
538     return;
539   if (!on_ground())
540     return;
541
542   // TODO: we don't have an animation for firetux backflipping, so let's revert to bigtux
543   set_bonus(GROWUP_BONUS, true);
544
545   backflip_direction = (dir == LEFT)?(+1):(-1);
546   backflipping = true;
547   do_jump(-580);
548   sound_manager->play("sounds/flip.wav");
549   backflip_timer.start(0.15f);
550 }
551
552 void
553 Player::do_jump(float yspeed) {
554   if (!on_ground())
555     return;
556
557   physic.set_velocity_y(yspeed);
558   //bbox.move(Vector(0, -1));
559   jumping = true;
560   on_ground_flag = false;
561   can_jump = false;
562
563   // play sound
564   if (is_big()) {
565     sound_manager->play("sounds/bigjump.wav");
566   } else {
567     sound_manager->play("sounds/jump.wav");
568   }
569 }
570
571 void
572 Player::handle_vertical_input()
573 {
574   // Press jump key
575   if(controller->hold(Controller::JUMP) && (on_ground()) && (can_jump)) {
576     if (duck) {
577       // when running, only jump a little bit; else do a backflip
578       if ((physic.get_velocity_x() != 0) || (controller->hold(Controller::LEFT)) || (controller->hold(Controller::RIGHT))) do_jump(-300); else do_backflip();
579     } else {
580       // jump a bit higher if we are running; else do a normal jump
581       if (fabs(physic.get_velocity_x()) > MAX_WALK_XM) do_jump(-580); else do_jump(-520);
582     }
583   }
584   // Let go of jump key
585   else if(!controller->hold(Controller::JUMP)) {
586     if (!backflipping && jumping && physic.get_velocity_y() < 0) {
587       jumping = false;
588       physic.set_velocity_y(0);
589     }
590   }
591
592   /* In case the player has pressed Down while in a certain range of air,
593      enable butt jump action */
594   if (controller->hold(Controller::DOWN) && !butt_jump && !duck && is_big() && jumping) {
595     butt_jump = true;
596   }
597
598   /* When Down is not held anymore, disable butt jump */
599   if(butt_jump && !controller->hold(Controller::DOWN))
600     butt_jump = false;
601
602   // swimming
603   physic.set_acceleration_y(0);
604   if (swimming) {
605     if (controller->hold(Controller::UP) || controller->hold(Controller::JUMP))
606       physic.set_acceleration_y(-2000);
607     physic.set_velocity_y(physic.get_velocity_y() * 0.94);
608   }
609 }
610
611 void
612 Player::handle_input()
613 {
614   if (ghost_mode) {
615     handle_input_ghost();
616     return;
617   }
618   if (climbing) {
619     handle_input_climbing();
620     return;
621   }
622
623   /* Peeking */
624   if( controller->released( Controller::PEEK_LEFT ) ) {
625     peeking = AUTO;
626   }
627   if( controller->released( Controller::PEEK_RIGHT ) ) {
628     peeking = AUTO;
629   }
630   if( controller->pressed( Controller::PEEK_LEFT ) ) {
631     peeking = LEFT;
632   }
633   if( controller->pressed( Controller::PEEK_RIGHT ) ) {
634     peeking = RIGHT;
635   }
636
637   /* Handle horizontal movement: */
638   if (!backflipping) handle_horizontal_input();
639
640   /* Jump/jumping? */
641   if (!controller->hold(Controller::JUMP)) can_jump = true;
642
643   /* Handle vertical movement: */
644   handle_vertical_input();
645
646   /* Shoot! */
647   if (controller->pressed(Controller::ACTION) && (player_status->bonus == FIRE_BONUS || player_status->bonus == ICE_BONUS)) {
648     if(Sector::current()->add_bullet(
649          get_pos() + ((dir == LEFT)? Vector(0, bbox.get_height()/2)
650                       : Vector(32, bbox.get_height()/2)),
651          physic.get_velocity_x(), dir))
652       shooting_timer.start(SHOOTING_TIME);
653   }
654
655   /* Duck or Standup! */
656   if (controller->hold(Controller::DOWN)) {
657     do_duck();
658   } else {
659     do_standup();
660   }
661
662   /* grabbing */
663   try_grab();
664
665   if(!controller->hold(Controller::ACTION) && grabbed_object) {
666     // move the grabbed object a bit away from tux
667     Vector pos = get_pos() +
668         Vector(dir == LEFT ? -bbox.get_width()-1 : bbox.get_width()+1,
669                 bbox.get_height()*0.66666 - 32);
670     Rect dest(pos, pos + Vector(32, 32));
671     if(Sector::current()->is_free_of_movingstatics(dest)) {
672       MovingObject* moving_object = dynamic_cast<MovingObject*> (grabbed_object);
673       if(moving_object) {
674         moving_object->set_pos(pos);
675       } else {
676         log_debug << "Non MovingObjetc grabbed?!?" << std::endl;
677       }
678       grabbed_object->ungrab(*this, dir);
679       grabbed_object = NULL;
680     }
681   }
682 }
683
684 void
685 Player::try_grab()
686 {
687   if(controller->hold(Controller::ACTION) && !grabbed_object
688       && !duck) {
689   Sector* sector = Sector::current();
690     Vector pos;
691     if(dir == LEFT) {
692       pos = Vector(bbox.get_left() - 5, bbox.get_bottom() - 16);
693     } else {
694       pos = Vector(bbox.get_right() + 5, bbox.get_bottom() - 16);
695     }
696
697     for(Sector::Portables::iterator i = sector->portables.begin();
698         i != sector->portables.end(); ++i) {
699       Portable* portable = *i;
700       if(!portable->is_portable())
701         continue;
702
703       MovingObject* moving_object = dynamic_cast<MovingObject*> (portable);
704       assert(portable);
705       if(moving_object == NULL)
706         continue;
707
708       if(moving_object->get_bbox().contains(pos)) {
709         if (climbing) stop_climbing(*climbing);
710         grabbed_object = portable;
711         grabbed_object->grab(*this, get_pos(), dir);
712         break;
713       }
714     }
715   }
716 }
717
718 void
719 Player::handle_input_ghost()
720 {
721   float vx = 0;
722   float vy = 0;
723   if (controller->hold(Controller::LEFT)) {
724     dir = LEFT;
725     vx -= MAX_RUN_XM * 2;
726   }
727   if (controller->hold(Controller::RIGHT)) {
728     dir = RIGHT;
729     vx += MAX_RUN_XM * 2;
730   }
731   if ((controller->hold(Controller::UP)) || (controller->hold(Controller::JUMP))) {
732     vy -= MAX_RUN_XM * 2;
733   }
734   if (controller->hold(Controller::DOWN)) {
735     vy += MAX_RUN_XM * 2;
736   }
737   if (controller->hold(Controller::ACTION)) {
738     set_ghost_mode(false);
739   }
740   physic.set_velocity(vx, vy);
741   physic.set_acceleration(0, 0);
742 }
743
744 void
745 Player::add_coins(int count)
746 {
747   player_status->add_coins(count);
748 }
749
750 int
751 Player::get_coins()
752 {
753   return player_status->coins;
754 }
755
756 bool
757 Player::add_bonus(const std::string& bonustype)
758 {
759   BonusType type = NO_BONUS;
760
761   if(bonustype == "grow") {
762     type = GROWUP_BONUS;
763   } else if(bonustype == "fireflower") {
764     type = FIRE_BONUS;
765   } else if(bonustype == "iceflower") {
766     type = ICE_BONUS;
767   } else if(bonustype == "none") {
768     type = NO_BONUS;
769   } else {
770     std::ostringstream msg;
771     msg << "Unknown bonus type "  << bonustype;
772     throw std::runtime_error(msg.str());
773   }
774
775   return add_bonus(type);
776 }
777
778 bool
779 Player::add_bonus(BonusType type, bool animate)
780 {
781   // always ignore NO_BONUS
782   if (type == NO_BONUS) {
783     return true;
784   }
785
786   // ignore GROWUP_BONUS if we're already big
787   if (type == GROWUP_BONUS) {
788     if (player_status->bonus == GROWUP_BONUS)
789       return true;
790     if (player_status->bonus == FIRE_BONUS)
791       return true;
792     if (player_status->bonus == ICE_BONUS)
793       return true;
794   }
795
796   return set_bonus(type, animate);
797 }
798
799 bool
800 Player::set_bonus(BonusType type, bool animate)
801 {
802   if(player_status->bonus == NO_BONUS) {
803     if (!adjust_height(62.8f)) {
804       printf("can't adjust\n");
805       return false;
806     }
807     if(animate)
808       growing_timer.start(GROWING_TIME);
809     if (climbing) stop_climbing(*climbing);
810   }
811
812   if ((type == NO_BONUS) || (type == GROWUP_BONUS)) {
813     if ((player_status->bonus == FIRE_BONUS) && (animate)) {
814       // visually lose helmet
815       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
816       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
817       Vector paccel = Vector(0, 1000);
818       std::string action = (dir==LEFT)?"left":"right";
819       Sector::current()->add_object(new SpriteParticle("images/objects/particles/firetux-helmet.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
820       if (climbing) stop_climbing(*climbing);
821     }
822     if ((player_status->bonus == ICE_BONUS) && (animate)) {
823       // visually lose cap
824       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
825       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
826       Vector paccel = Vector(0, 1000);
827       std::string action = (dir==LEFT)?"left":"right";
828       Sector::current()->add_object(new SpriteParticle("images/objects/particles/icetux-cap.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
829       if (climbing) stop_climbing(*climbing);
830     }
831     player_status->max_fire_bullets = 0;
832     player_status->max_ice_bullets = 0;
833   }
834   if (type == FIRE_BONUS) player_status->max_fire_bullets++;
835   if (type == ICE_BONUS) player_status->max_ice_bullets++;
836
837   player_status->bonus = type;
838   return true;
839 }
840
841 void
842 Player::set_visible(bool visible)
843 {
844   this->visible = visible;
845   if( visible )
846     set_group(COLGROUP_MOVING);
847   else
848     set_group(COLGROUP_DISABLED);
849 }
850
851 bool
852 Player::get_visible()
853 {
854   return visible;
855 }
856
857 void
858 Player::kick()
859 {
860   kick_timer.start(KICK_TIME);
861 }
862
863 void
864 Player::draw(DrawingContext& context)
865 {
866   if(!visible)
867     return;
868
869   // if Tux is above camera, draw little "air arrow" to show where he is x-wise
870   if (Sector::current() && Sector::current()->camera && (get_bbox().p2.y - 16 < Sector::current()->camera->get_translation().y)) {
871     float px = get_pos().x + (get_bbox().p2.x - get_bbox().p1.x - airarrow.get()->get_width()) / 2;
872     float py = Sector::current()->camera->get_translation().y;
873     py += std::min(((py - (get_bbox().p2.y + 16)) / 4), 16.0f);
874     context.draw_surface(airarrow.get(), Vector(px, py), LAYER_HUD - 1);
875   }
876
877   TuxBodyParts* tux_body;
878
879   if (player_status->bonus == GROWUP_BONUS)
880     tux_body = big_tux;
881   else if (player_status->bonus == FIRE_BONUS)
882     tux_body = fire_tux;
883   else if (player_status->bonus == ICE_BONUS)
884     tux_body = ice_tux;
885   else
886     tux_body = small_tux;
887
888   int layer = LAYER_OBJECTS + 1;
889
890   /* Set Tux sprite action */
891   if (climbing)
892     {
893     tux_body->set_action("skid-left");
894     }
895   else if (backflipping)
896     {
897     if(dir == LEFT)
898       tux_body->set_action("backflip-left");
899     else // dir == RIGHT
900       tux_body->set_action("backflip-right");
901     }
902   else if (duck && is_big())
903     {
904     if(dir == LEFT)
905       tux_body->set_action("duck-left");
906     else // dir == RIGHT
907       tux_body->set_action("duck-right");
908     }
909   else if (skidding_timer.started() && !skidding_timer.check())
910     {
911     if(dir == LEFT)
912       tux_body->set_action("skid-left");
913     else // dir == RIGHT
914       tux_body->set_action("skid-right");
915     }
916   else if (kick_timer.started() && !kick_timer.check())
917     {
918     if(dir == LEFT)
919       tux_body->set_action("kick-left");
920     else // dir == RIGHT
921       tux_body->set_action("kick-right");
922     }
923   else if (butt_jump && is_big())
924     {
925     if(dir == LEFT)
926       tux_body->set_action("buttjump-left");
927     else // dir == RIGHT
928       tux_body->set_action("buttjump-right");
929     }
930   else if (!on_ground())
931     {
932     if(dir == LEFT)
933       tux_body->set_action("jump-left");
934     else // dir == RIGHT
935       tux_body->set_action("jump-right");
936     }
937   else
938     {
939     if (fabsf(physic.get_velocity_x()) < 1.0f) // standing
940       {
941       if(dir == LEFT)
942         tux_body->set_action("stand-left");
943       else // dir == RIGHT
944         tux_body->set_action("stand-right");
945       }
946     else // moving
947       {
948       if(dir == LEFT)
949         tux_body->set_action("walk-left");
950       else // dir == RIGHT
951         tux_body->set_action("walk-right");
952       }
953     }
954
955   if(idle_timer.check())
956     {
957     if(is_big())
958       {
959       if(dir == LEFT)
960         tux_body->head->set_action("idle-left", 1);
961       else // dir == RIGHT
962         tux_body->head->set_action("idle-right", 1);
963       }
964
965     }
966
967   // Tux is holding something
968   if ((grabbed_object != 0 && physic.get_velocity_y() == 0) ||
969       (shooting_timer.get_timeleft() > 0 && !shooting_timer.check()))
970     {
971     if (duck)
972       {
973       if(dir == LEFT)
974         tux_body->arms->set_action("duck+grab-left");
975       else // dir == RIGHT
976         tux_body->arms->set_action("duck+grab-right");
977       }
978     else
979       {
980       if(dir == LEFT)
981         tux_body->arms->set_action("grab-left");
982       else // dir == RIGHT
983         tux_body->arms->set_action("grab-right");
984       }
985     }
986
987   /* Draw Tux */
988   if(dying) {
989     smalltux_gameover->draw(context, get_pos(), LAYER_FLOATINGOBJECTS + 1);
990   }
991   else if ((growing_timer.get_timeleft() > 0) && (!duck)) {
992       if (dir == RIGHT) {
993         context.draw_surface(growingtux_right[int((growing_timer.get_timegone() *
994                  GROWING_FRAMES) / GROWING_TIME)], get_pos(), layer);
995       } else {
996         context.draw_surface(growingtux_left[int((growing_timer.get_timegone() *
997                 GROWING_FRAMES) / GROWING_TIME)], get_pos(), layer);
998       }
999     }
1000   else if (safe_timer.started() && size_t(game_time*40)%2)
1001     ;  // don't draw Tux
1002   else
1003     tux_body->draw(context, get_pos(), layer);
1004
1005 }
1006
1007 void
1008 Player::collision_tile(uint32_t tile_attributes)
1009 {
1010   if(tile_attributes & Tile::HURTS)
1011     kill(false);
1012
1013   if( swimming ){
1014     if( tile_attributes & Tile::WATER ){
1015       no_water = false;
1016     } else {
1017       swimming = false;
1018     }
1019   } else {
1020     if( tile_attributes & Tile::WATER ){
1021       swimming = true;
1022       no_water = false;
1023       sound_manager->play( "sounds/splash.ogg" );
1024     }
1025   }
1026 }
1027
1028 void
1029 Player::collision_solid(const CollisionHit& hit)
1030 {
1031   if(hit.bottom) {
1032     if(physic.get_velocity_y() > 0)
1033       physic.set_velocity_y(0);
1034
1035     on_ground_flag = true;
1036     floor_normal = hit.slope_normal;
1037   } else if(hit.top) {
1038     if(physic.get_velocity_y() < 0)
1039       physic.set_velocity_y(.2f);
1040   }
1041
1042   if(hit.left || hit.right) {
1043     physic.set_velocity_x(0);
1044   }
1045
1046   // crushed?
1047   if(hit.crush) {
1048     if(hit.left || hit.right) {
1049       kill(true);
1050     } else if(hit.top || hit.bottom) {
1051       kill(false);
1052     }
1053   }
1054 }
1055
1056 HitResponse
1057 Player::collision(GameObject& other, const CollisionHit& hit)
1058 {
1059   Bullet* bullet = dynamic_cast<Bullet*> (&other);
1060   if(bullet) {
1061     return FORCE_MOVE;
1062   }
1063
1064   if(hit.left || hit.right) {
1065     try_grab(); //grab objects right now, in update it will be too late
1066   }
1067 #ifdef DEBUG
1068   assert(dynamic_cast<MovingObject*> (&other) != NULL);
1069 #endif
1070   MovingObject* moving_object = static_cast<MovingObject*> (&other);
1071   if(moving_object->get_group() == COLGROUP_TOUCHABLE) {
1072     TriggerBase* trigger = dynamic_cast<TriggerBase*> (&other);
1073     if(trigger) {
1074       if(controller->pressed(Controller::UP))
1075         trigger->event(*this, TriggerBase::EVENT_ACTIVATE);
1076     }
1077
1078     return FORCE_MOVE;
1079   }
1080
1081   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
1082   if(badguy != NULL) {
1083     if (hit.bottom) on_ground_flag = true;
1084     if(safe_timer.started() || invincible_timer.started())
1085       return FORCE_MOVE;
1086
1087     return CONTINUE;
1088   }
1089
1090   return CONTINUE;
1091 }
1092
1093 void
1094 Player::make_invincible()
1095 {
1096   sound_manager->play("sounds/invincible.wav");
1097   invincible_timer.start(TUX_INVINCIBLE_TIME);
1098   Sector::current()->play_music(HERRING_MUSIC);
1099 }
1100
1101 /* Kill Player! */
1102 void
1103 Player::kill(bool completely)
1104 {
1105   if(dying || deactivated)
1106     return;
1107
1108   if(!completely && (safe_timer.started() || invincible_timer.started()))
1109     return;
1110
1111   sound_manager->play("sounds/hurt.wav");
1112   if (climbing) stop_climbing(*climbing);
1113
1114   physic.set_velocity_x(0);
1115
1116   if(!completely && (is_big() || growing_timer.started())) {
1117     if(player_status->bonus == FIRE_BONUS
1118         || player_status->bonus == ICE_BONUS) {
1119       safe_timer.start(TUX_SAFE_TIME);
1120       set_bonus(GROWUP_BONUS, true);
1121     } else if(player_status->bonus == GROWUP_BONUS) {
1122       //growing_timer.start(GROWING_TIME);
1123       safe_timer.start(TUX_SAFE_TIME /* + GROWING_TIME */);
1124       adjust_height(30.8f);
1125       duck = false;
1126       set_bonus(NO_BONUS, true);
1127     } else if(player_status->bonus == NO_BONUS) {
1128       growing_timer.stop();
1129       safe_timer.start(TUX_SAFE_TIME);
1130       adjust_height(30.8f);
1131       duck = false;
1132     }
1133   } else {
1134     if (player_status->coins >= 25 && !GameSession::current()->get_reset_point_sectorname().empty())
1135     {
1136       for (int i = 0; i < 5; i++)
1137       {
1138         // the numbers: starting x, starting y, velocity y
1139         Sector::current()->add_object(new FallingCoin(get_pos() +
1140               Vector(systemRandom.rand(5), systemRandom.rand(-32,18)),
1141               systemRandom.rand(-100,100)));
1142       }
1143       player_status->coins -= std::max(player_status->coins/10, 25);
1144     }
1145     else
1146     {
1147       GameSession::current()->set_reset_point("", Vector());
1148     }
1149     physic.enable_gravity(true);
1150     physic.set_acceleration(0, 0);
1151     physic.set_velocity(0, -700);
1152     set_bonus(NO_BONUS, true);
1153     dying = true;
1154     dying_timer.start(3.0);
1155     set_group(COLGROUP_DISABLED);
1156
1157     DisplayEffect* effect = new DisplayEffect();
1158     effect->fade_out(3.0);
1159     Sector::current()->add_object(effect);
1160     sound_manager->stop_music(3.0);
1161   }
1162 }
1163
1164 void
1165 Player::move(const Vector& vector)
1166 {
1167   set_pos(vector);
1168
1169   // TODO: do we need the following? Seems irrelevant to moving the player
1170   if(is_big())
1171     set_size(31.8f, 63.8f);
1172   else
1173     set_size(31.8f, 31.8f);
1174   duck = false;
1175   last_ground_y = vector.y;
1176   if (climbing) stop_climbing(*climbing);
1177
1178   physic.reset();
1179 }
1180
1181 void
1182 Player::check_bounds(Camera* camera)
1183 {
1184   /* Keep tux in bounds: */
1185   if (get_pos().x < 0) {
1186     // Lock Tux to the size of the level, so that he doesn't fall of
1187     // on the left side
1188     set_pos(Vector(0, get_pos().y));
1189   }
1190
1191   /* fallen out of the level? */
1192   if (get_pos().y > Sector::current()->get_height()) {
1193     kill(true);
1194     return;
1195   }
1196
1197   // can happen if back scrolling is disabled
1198   if(get_pos().x < camera->get_translation().x) {
1199     set_pos(Vector(camera->get_translation().x, get_pos().y));
1200   }
1201   if(get_pos().x >= camera->get_translation().x + SCREEN_WIDTH - bbox.get_width())
1202   {
1203     set_pos(Vector(
1204           camera->get_translation().x + SCREEN_WIDTH - bbox.get_width(),
1205           get_pos().y));
1206   }
1207 }
1208
1209 void
1210 Player::add_velocity(const Vector& velocity)
1211 {
1212   physic.set_velocity(physic.get_velocity() + velocity);
1213 }
1214
1215 void
1216 Player::add_velocity(const Vector& velocity, const Vector& end_speed)
1217 {
1218   if (end_speed.x > 0)
1219     physic.set_velocity_x(std::min(physic.get_velocity_x() + velocity.x, end_speed.x));
1220   if (end_speed.x < 0)
1221     physic.set_velocity_x(std::max(physic.get_velocity_x() + velocity.x, end_speed.x));
1222   if (end_speed.y > 0)
1223     physic.set_velocity_y(std::min(physic.get_velocity_y() + velocity.y, end_speed.y));
1224   if (end_speed.y < 0)
1225     physic.set_velocity_y(std::max(physic.get_velocity_y() + velocity.y, end_speed.y));
1226 }
1227
1228 void
1229 Player::bounce(BadGuy& )
1230 {
1231   //if(controller->hold(Controller::JUMP))
1232   //  physic.set_velocity_y(-520);
1233   //else
1234     physic.set_velocity_y(-300);
1235 }
1236
1237 //Scripting Functions Below
1238
1239 void
1240 Player::deactivate()
1241 {
1242   if (deactivated)
1243     return;
1244   deactivated = true;
1245   physic.set_velocity_x(0);
1246   physic.set_velocity_y(0);
1247   physic.set_acceleration_x(0);
1248   physic.set_acceleration_y(0);
1249   if (climbing) stop_climbing(*climbing);
1250 }
1251
1252 void
1253 Player::activate()
1254 {
1255   if (!deactivated)
1256     return;
1257   deactivated = false;
1258 }
1259
1260 void Player::walk(float speed)
1261 {
1262   physic.set_velocity_x(speed);
1263 }
1264
1265 void
1266 Player::set_ghost_mode(bool enable)
1267 {
1268   if (ghost_mode == enable)
1269     return;
1270
1271   if (climbing) stop_climbing(*climbing);
1272
1273   if (enable) {
1274     ghost_mode = true;
1275     set_group(COLGROUP_DISABLED);
1276     physic.enable_gravity(false);
1277     log_debug << "You feel lightheaded. Use movement controls to float around, press ACTION to scare badguys." << std::endl;
1278   } else {
1279     ghost_mode = false;
1280     set_group(COLGROUP_MOVING);
1281     physic.enable_gravity(true);
1282     log_debug << "You feel solid again." << std::endl;
1283   }
1284 }
1285
1286
1287 void 
1288 Player::start_climbing(Climbable& climbable)
1289 {
1290   if (climbing == &climbable) return;
1291
1292   climbing = &climbable;
1293   physic.enable_gravity(false);
1294   physic.set_velocity(0, 0);
1295   physic.set_acceleration(0, 0);
1296 }
1297
1298 void 
1299 Player::stop_climbing(Climbable& /*climbable*/)
1300 {
1301   if (!climbing) return;
1302
1303   climbing = 0;
1304
1305   if (grabbed_object) {    
1306     grabbed_object->ungrab(*this, dir);
1307     grabbed_object = NULL;
1308   }
1309
1310   physic.enable_gravity(true);
1311   physic.set_velocity(0, 0);
1312   physic.set_acceleration(0, 0);
1313
1314   if ((controller->hold(Controller::JUMP)) || (controller->hold(Controller::UP))) {
1315     on_ground_flag = true;
1316     // TODO: This won't help. Why?
1317     do_jump(-300);
1318   }
1319 }
1320
1321 void
1322 Player::handle_input_climbing()
1323 {
1324   if (!climbing) {
1325     log_warning << "handle_input_climbing called with climbing set to 0. Input handling skipped" << std::endl;
1326     return;
1327   }
1328
1329   float vx = 0;
1330   float vy = 0;
1331   if (controller->hold(Controller::LEFT)) {
1332     dir = LEFT;
1333     vx -= MAX_CLIMB_XM;
1334   }
1335   if (controller->hold(Controller::RIGHT)) {
1336     dir = RIGHT;
1337     vx += MAX_CLIMB_XM;
1338   }
1339   if (controller->hold(Controller::UP)) {
1340     vy -= MAX_CLIMB_YM;
1341   }
1342   if (controller->hold(Controller::DOWN)) {
1343     vy += MAX_CLIMB_YM;
1344   }
1345   if (controller->hold(Controller::JUMP)) {
1346     if (can_jump) {
1347       stop_climbing(*climbing);
1348       return;
1349     }  
1350   } else {
1351     can_jump = true;
1352   }
1353   if (controller->hold(Controller::ACTION)) {
1354     stop_climbing(*climbing);
1355     return;
1356   }
1357   physic.set_velocity(vx, vy);
1358   physic.set_acceleration(0, 0);
1359 }
1360
1361