Fixed Tux picking up dead BadGuys: Will no longer pick up objects in collision group...
[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->pressed(Controller::JUMP) && (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 (on_ground() && !controller->hold(Controller::JUMP))
642     can_jump = true;
643
644   /* Handle vertical movement: */
645   handle_vertical_input();
646
647   /* Shoot! */
648   if (controller->pressed(Controller::ACTION) && (player_status->bonus == FIRE_BONUS || player_status->bonus == ICE_BONUS)) {
649     if(Sector::current()->add_bullet(
650          get_pos() + ((dir == LEFT)? Vector(0, bbox.get_height()/2)
651                       : Vector(32, bbox.get_height()/2)),
652          physic.get_velocity_x(), dir))
653       shooting_timer.start(SHOOTING_TIME);
654   }
655
656   /* Duck or Standup! */
657   if (controller->hold(Controller::DOWN)) {
658     do_duck();
659   } else {
660     do_standup();
661   }
662
663   /* grabbing */
664   try_grab();
665
666   if(!controller->hold(Controller::ACTION) && grabbed_object) {
667     // move the grabbed object a bit away from tux
668     Vector pos = get_pos() +
669         Vector(dir == LEFT ? -bbox.get_width()-1 : bbox.get_width()+1,
670                 bbox.get_height()*0.66666 - 32);
671     Rect dest(pos, pos + Vector(32, 32));
672     if(Sector::current()->is_free_of_movingstatics(dest)) {
673       MovingObject* moving_object = dynamic_cast<MovingObject*> (grabbed_object);
674       if(moving_object) {
675         moving_object->set_pos(pos);
676       } else {
677         log_debug << "Non MovingObjetc grabbed?!?" << std::endl;
678       }
679       grabbed_object->ungrab(*this, dir);
680       grabbed_object = NULL;
681     }
682   }
683 }
684
685 void
686 Player::try_grab()
687 {
688   if(controller->hold(Controller::ACTION) && !grabbed_object
689       && !duck) {
690   Sector* sector = Sector::current();
691     Vector pos;
692     if(dir == LEFT) {
693       pos = Vector(bbox.get_left() - 5, bbox.get_bottom() - 16);
694     } else {
695       pos = Vector(bbox.get_right() + 5, bbox.get_bottom() - 16);
696     }
697
698     for(Sector::Portables::iterator i = sector->portables.begin();
699         i != sector->portables.end(); ++i) {
700       Portable* portable = *i;
701       if(!portable->is_portable())
702         continue;
703
704       // make sure the Portable is a MovingObject
705       MovingObject* moving_object = dynamic_cast<MovingObject*> (portable);
706       assert(moving_object);
707       if(moving_object == NULL)
708         continue;
709
710       // make sure the Portable isn't currently non-solid
711       if(moving_object->get_group() == COLGROUP_DISABLED) continue;
712
713       // check if we are within reach
714       if(moving_object->get_bbox().contains(pos)) {
715         if (climbing) stop_climbing(*climbing);
716         grabbed_object = portable;
717         grabbed_object->grab(*this, get_pos(), dir);
718         break;
719       }
720     }
721   }
722 }
723
724 void
725 Player::handle_input_ghost()
726 {
727   float vx = 0;
728   float vy = 0;
729   if (controller->hold(Controller::LEFT)) {
730     dir = LEFT;
731     vx -= MAX_RUN_XM * 2;
732   }
733   if (controller->hold(Controller::RIGHT)) {
734     dir = RIGHT;
735     vx += MAX_RUN_XM * 2;
736   }
737   if ((controller->hold(Controller::UP)) || (controller->hold(Controller::JUMP))) {
738     vy -= MAX_RUN_XM * 2;
739   }
740   if (controller->hold(Controller::DOWN)) {
741     vy += MAX_RUN_XM * 2;
742   }
743   if (controller->hold(Controller::ACTION)) {
744     set_ghost_mode(false);
745   }
746   physic.set_velocity(vx, vy);
747   physic.set_acceleration(0, 0);
748 }
749
750 void
751 Player::add_coins(int count)
752 {
753   player_status->add_coins(count);
754 }
755
756 int
757 Player::get_coins()
758 {
759   return player_status->coins;
760 }
761
762 bool
763 Player::add_bonus(const std::string& bonustype)
764 {
765   BonusType type = NO_BONUS;
766
767   if(bonustype == "grow") {
768     type = GROWUP_BONUS;
769   } else if(bonustype == "fireflower") {
770     type = FIRE_BONUS;
771   } else if(bonustype == "iceflower") {
772     type = ICE_BONUS;
773   } else if(bonustype == "none") {
774     type = NO_BONUS;
775   } else {
776     std::ostringstream msg;
777     msg << "Unknown bonus type "  << bonustype;
778     throw std::runtime_error(msg.str());
779   }
780
781   return add_bonus(type);
782 }
783
784 bool
785 Player::add_bonus(BonusType type, bool animate)
786 {
787   // always ignore NO_BONUS
788   if (type == NO_BONUS) {
789     return true;
790   }
791
792   // ignore GROWUP_BONUS if we're already big
793   if (type == GROWUP_BONUS) {
794     if (player_status->bonus == GROWUP_BONUS)
795       return true;
796     if (player_status->bonus == FIRE_BONUS)
797       return true;
798     if (player_status->bonus == ICE_BONUS)
799       return true;
800   }
801
802   return set_bonus(type, animate);
803 }
804
805 bool
806 Player::set_bonus(BonusType type, bool animate)
807 {
808   if(player_status->bonus == NO_BONUS) {
809     if (!adjust_height(62.8f)) {
810       printf("can't adjust\n");
811       return false;
812     }
813     if(animate)
814       growing_timer.start(GROWING_TIME);
815     if (climbing) stop_climbing(*climbing);
816   }
817
818   if ((type == NO_BONUS) || (type == GROWUP_BONUS)) {
819     if ((player_status->bonus == FIRE_BONUS) && (animate)) {
820       // visually lose helmet
821       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
822       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
823       Vector paccel = Vector(0, 1000);
824       std::string action = (dir==LEFT)?"left":"right";
825       Sector::current()->add_object(new SpriteParticle("images/objects/particles/firetux-helmet.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
826       if (climbing) stop_climbing(*climbing);
827     }
828     if ((player_status->bonus == ICE_BONUS) && (animate)) {
829       // visually lose cap
830       Vector ppos = Vector((bbox.p1.x + bbox.p2.x) / 2, bbox.p1.y);
831       Vector pspeed = Vector(((dir==LEFT) ? +100 : -100), -300);
832       Vector paccel = Vector(0, 1000);
833       std::string action = (dir==LEFT)?"left":"right";
834       Sector::current()->add_object(new SpriteParticle("images/objects/particles/icetux-cap.sprite", action, ppos, ANCHOR_TOP, pspeed, paccel, LAYER_OBJECTS-1));
835       if (climbing) stop_climbing(*climbing);
836     }
837     player_status->max_fire_bullets = 0;
838     player_status->max_ice_bullets = 0;
839   }
840   if (type == FIRE_BONUS) player_status->max_fire_bullets++;
841   if (type == ICE_BONUS) player_status->max_ice_bullets++;
842
843   player_status->bonus = type;
844   return true;
845 }
846
847 void
848 Player::set_visible(bool visible)
849 {
850   this->visible = visible;
851   if( visible )
852     set_group(COLGROUP_MOVING);
853   else
854     set_group(COLGROUP_DISABLED);
855 }
856
857 bool
858 Player::get_visible()
859 {
860   return visible;
861 }
862
863 void
864 Player::kick()
865 {
866   kick_timer.start(KICK_TIME);
867 }
868
869 void
870 Player::draw(DrawingContext& context)
871 {
872   if(!visible)
873     return;
874
875   // if Tux is above camera, draw little "air arrow" to show where he is x-wise
876   if (Sector::current() && Sector::current()->camera && (get_bbox().p2.y - 16 < Sector::current()->camera->get_translation().y)) {
877     float px = get_pos().x + (get_bbox().p2.x - get_bbox().p1.x - airarrow.get()->get_width()) / 2;
878     float py = Sector::current()->camera->get_translation().y;
879     py += std::min(((py - (get_bbox().p2.y + 16)) / 4), 16.0f);
880     context.draw_surface(airarrow.get(), Vector(px, py), LAYER_HUD - 1);
881   }
882
883   TuxBodyParts* tux_body;
884
885   if (player_status->bonus == GROWUP_BONUS)
886     tux_body = big_tux;
887   else if (player_status->bonus == FIRE_BONUS)
888     tux_body = fire_tux;
889   else if (player_status->bonus == ICE_BONUS)
890     tux_body = ice_tux;
891   else
892     tux_body = small_tux;
893
894   int layer = LAYER_OBJECTS + 1;
895
896   /* Set Tux sprite action */
897   if (climbing)
898     {
899     tux_body->set_action("skid-left");
900     }
901   else if (backflipping)
902     {
903     if(dir == LEFT)
904       tux_body->set_action("backflip-left");
905     else // dir == RIGHT
906       tux_body->set_action("backflip-right");
907     }
908   else if (duck && is_big())
909     {
910     if(dir == LEFT)
911       tux_body->set_action("duck-left");
912     else // dir == RIGHT
913       tux_body->set_action("duck-right");
914     }
915   else if (skidding_timer.started() && !skidding_timer.check())
916     {
917     if(dir == LEFT)
918       tux_body->set_action("skid-left");
919     else // dir == RIGHT
920       tux_body->set_action("skid-right");
921     }
922   else if (kick_timer.started() && !kick_timer.check())
923     {
924     if(dir == LEFT)
925       tux_body->set_action("kick-left");
926     else // dir == RIGHT
927       tux_body->set_action("kick-right");
928     }
929   else if (butt_jump && is_big())
930     {
931     if(dir == LEFT)
932       tux_body->set_action("buttjump-left");
933     else // dir == RIGHT
934       tux_body->set_action("buttjump-right");
935     }
936   else if (!on_ground())
937     {
938     if(dir == LEFT)
939       tux_body->set_action("jump-left");
940     else // dir == RIGHT
941       tux_body->set_action("jump-right");
942     }
943   else
944     {
945     if (fabsf(physic.get_velocity_x()) < 1.0f) // standing
946       {
947       if(dir == LEFT)
948         tux_body->set_action("stand-left");
949       else // dir == RIGHT
950         tux_body->set_action("stand-right");
951       }
952     else // moving
953       {
954       if(dir == LEFT)
955         tux_body->set_action("walk-left");
956       else // dir == RIGHT
957         tux_body->set_action("walk-right");
958       }
959     }
960
961   if(idle_timer.check())
962     {
963     if(is_big())
964       {
965       if(dir == LEFT)
966         tux_body->head->set_action("idle-left", 1);
967       else // dir == RIGHT
968         tux_body->head->set_action("idle-right", 1);
969       }
970
971     }
972
973   // Tux is holding something
974   if ((grabbed_object != 0 && physic.get_velocity_y() == 0) ||
975       (shooting_timer.get_timeleft() > 0 && !shooting_timer.check()))
976     {
977     if (duck)
978       {
979       if(dir == LEFT)
980         tux_body->arms->set_action("duck+grab-left");
981       else // dir == RIGHT
982         tux_body->arms->set_action("duck+grab-right");
983       }
984     else
985       {
986       if(dir == LEFT)
987         tux_body->arms->set_action("grab-left");
988       else // dir == RIGHT
989         tux_body->arms->set_action("grab-right");
990       }
991     }
992
993   /* Draw Tux */
994   if(dying) {
995     smalltux_gameover->draw(context, get_pos(), LAYER_FLOATINGOBJECTS + 1);
996   }
997   else if ((growing_timer.get_timeleft() > 0) && (!duck)) {
998       if (dir == RIGHT) {
999         context.draw_surface(growingtux_right[int((growing_timer.get_timegone() *
1000                  GROWING_FRAMES) / GROWING_TIME)], get_pos(), layer);
1001       } else {
1002         context.draw_surface(growingtux_left[int((growing_timer.get_timegone() *
1003                 GROWING_FRAMES) / GROWING_TIME)], get_pos(), layer);
1004       }
1005     }
1006   else if (safe_timer.started() && size_t(game_time*40)%2)
1007     ;  // don't draw Tux
1008   else
1009     tux_body->draw(context, get_pos(), layer);
1010
1011 }
1012
1013 void
1014 Player::collision_tile(uint32_t tile_attributes)
1015 {
1016   if(tile_attributes & Tile::HURTS)
1017     kill(false);
1018
1019   if( swimming ){
1020     if( tile_attributes & Tile::WATER ){
1021       no_water = false;
1022     } else {
1023       swimming = false;
1024     }
1025   } else {
1026     if( tile_attributes & Tile::WATER ){
1027       swimming = true;
1028       no_water = false;
1029       sound_manager->play( "sounds/splash.ogg" );
1030     }
1031   }
1032 }
1033
1034 void
1035 Player::collision_solid(const CollisionHit& hit)
1036 {
1037   if(hit.bottom) {
1038     if(physic.get_velocity_y() > 0)
1039       physic.set_velocity_y(0);
1040
1041     on_ground_flag = true;
1042     floor_normal = hit.slope_normal;
1043   } else if(hit.top) {
1044     if(physic.get_velocity_y() < 0)
1045       physic.set_velocity_y(.2f);
1046   }
1047
1048   if(hit.left || hit.right) {
1049     physic.set_velocity_x(0);
1050   }
1051
1052   // crushed?
1053   if(hit.crush) {
1054     if(hit.left || hit.right) {
1055       kill(true);
1056     } else if(hit.top || hit.bottom) {
1057       kill(false);
1058     }
1059   }
1060 }
1061
1062 HitResponse
1063 Player::collision(GameObject& other, const CollisionHit& hit)
1064 {
1065   Bullet* bullet = dynamic_cast<Bullet*> (&other);
1066   if(bullet) {
1067     return FORCE_MOVE;
1068   }
1069
1070   if(hit.left || hit.right) {
1071     try_grab(); //grab objects right now, in update it will be too late
1072   }
1073 #ifdef DEBUG
1074   assert(dynamic_cast<MovingObject*> (&other) != NULL);
1075 #endif
1076   MovingObject* moving_object = static_cast<MovingObject*> (&other);
1077   if(moving_object->get_group() == COLGROUP_TOUCHABLE) {
1078     TriggerBase* trigger = dynamic_cast<TriggerBase*> (&other);
1079     if(trigger) {
1080       if(controller->pressed(Controller::UP))
1081         trigger->event(*this, TriggerBase::EVENT_ACTIVATE);
1082     }
1083
1084     return FORCE_MOVE;
1085   }
1086
1087   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
1088   if(badguy != NULL) {
1089     if(safe_timer.started() || invincible_timer.started())
1090       return FORCE_MOVE;
1091
1092     return CONTINUE;
1093   }
1094
1095   return CONTINUE;
1096 }
1097
1098 void
1099 Player::make_invincible()
1100 {
1101   sound_manager->play("sounds/invincible.wav");
1102   invincible_timer.start(TUX_INVINCIBLE_TIME);
1103   Sector::current()->play_music(HERRING_MUSIC);
1104 }
1105
1106 /* Kill Player! */
1107 void
1108 Player::kill(bool completely)
1109 {
1110   if(dying || deactivated)
1111     return;
1112
1113   if(!completely && (safe_timer.started() || invincible_timer.started()))
1114     return;
1115
1116   sound_manager->play("sounds/hurt.wav");
1117   if (climbing) stop_climbing(*climbing);
1118
1119   physic.set_velocity_x(0);
1120
1121   if(!completely && (is_big() || growing_timer.started())) {
1122     if(player_status->bonus == FIRE_BONUS
1123         || player_status->bonus == ICE_BONUS) {
1124       safe_timer.start(TUX_SAFE_TIME);
1125       set_bonus(GROWUP_BONUS, true);
1126     } else if(player_status->bonus == GROWUP_BONUS) {
1127       //growing_timer.start(GROWING_TIME);
1128       safe_timer.start(TUX_SAFE_TIME /* + GROWING_TIME */);
1129       adjust_height(30.8f);
1130       duck = false;
1131       set_bonus(NO_BONUS, true);
1132     } else if(player_status->bonus == NO_BONUS) {
1133       growing_timer.stop();
1134       safe_timer.start(TUX_SAFE_TIME);
1135       adjust_height(30.8f);
1136       duck = false;
1137     }
1138   } else {
1139     if (player_status->coins >= 25 && !GameSession::current()->get_reset_point_sectorname().empty())
1140     {
1141       for (int i = 0; i < 5; i++)
1142       {
1143         // the numbers: starting x, starting y, velocity y
1144         Sector::current()->add_object(new FallingCoin(get_pos() +
1145               Vector(systemRandom.rand(5), systemRandom.rand(-32,18)),
1146               systemRandom.rand(-100,100)));
1147       }
1148       player_status->coins -= std::max(player_status->coins/10, 25);
1149     }
1150     else
1151     {
1152       GameSession::current()->set_reset_point("", Vector());
1153     }
1154     physic.enable_gravity(true);
1155     physic.set_acceleration(0, 0);
1156     physic.set_velocity(0, -700);
1157     set_bonus(NO_BONUS, true);
1158     dying = true;
1159     dying_timer.start(3.0);
1160     set_group(COLGROUP_DISABLED);
1161
1162     DisplayEffect* effect = new DisplayEffect();
1163     effect->fade_out(3.0);
1164     Sector::current()->add_object(effect);
1165     sound_manager->stop_music(3.0);
1166   }
1167 }
1168
1169 void
1170 Player::move(const Vector& vector)
1171 {
1172   set_pos(vector);
1173
1174   // TODO: do we need the following? Seems irrelevant to moving the player
1175   if(is_big())
1176     set_size(31.8f, 63.8f);
1177   else
1178     set_size(31.8f, 31.8f);
1179   duck = false;
1180   last_ground_y = vector.y;
1181   if (climbing) stop_climbing(*climbing);
1182
1183   physic.reset();
1184 }
1185
1186 void
1187 Player::check_bounds(Camera* camera)
1188 {
1189   /* Keep tux in bounds: */
1190   if (get_pos().x < 0) {
1191     // Lock Tux to the size of the level, so that he doesn't fall of
1192     // on the left side
1193     set_pos(Vector(0, get_pos().y));
1194   }
1195
1196   /* fallen out of the level? */
1197   if (get_pos().y > Sector::current()->get_height()) {
1198     kill(true);
1199     return;
1200   }
1201
1202   // can happen if back scrolling is disabled
1203   if(get_pos().x < camera->get_translation().x) {
1204     set_pos(Vector(camera->get_translation().x, get_pos().y));
1205   }
1206   if(get_pos().x >= camera->get_translation().x + SCREEN_WIDTH - bbox.get_width())
1207   {
1208     set_pos(Vector(
1209           camera->get_translation().x + SCREEN_WIDTH - bbox.get_width(),
1210           get_pos().y));
1211   }
1212 }
1213
1214 void
1215 Player::add_velocity(const Vector& velocity)
1216 {
1217   physic.set_velocity(physic.get_velocity() + velocity);
1218 }
1219
1220 void
1221 Player::add_velocity(const Vector& velocity, const Vector& end_speed)
1222 {
1223   if (end_speed.x > 0)
1224     physic.set_velocity_x(std::min(physic.get_velocity_x() + velocity.x, end_speed.x));
1225   if (end_speed.x < 0)
1226     physic.set_velocity_x(std::max(physic.get_velocity_x() + velocity.x, end_speed.x));
1227   if (end_speed.y > 0)
1228     physic.set_velocity_y(std::min(physic.get_velocity_y() + velocity.y, end_speed.y));
1229   if (end_speed.y < 0)
1230     physic.set_velocity_y(std::max(physic.get_velocity_y() + velocity.y, end_speed.y));
1231 }
1232
1233 void
1234 Player::bounce(BadGuy& )
1235 {
1236   if(controller->hold(Controller::JUMP))
1237     physic.set_velocity_y(-520);
1238   else
1239     physic.set_velocity_y(-300);
1240 }
1241
1242 //Scripting Functions Below
1243
1244 void
1245 Player::deactivate()
1246 {
1247   if (deactivated)
1248     return;
1249   deactivated = true;
1250   physic.set_velocity_x(0);
1251   physic.set_velocity_y(0);
1252   physic.set_acceleration_x(0);
1253   physic.set_acceleration_y(0);
1254   if (climbing) stop_climbing(*climbing);
1255 }
1256
1257 void
1258 Player::activate()
1259 {
1260   if (!deactivated)
1261     return;
1262   deactivated = false;
1263 }
1264
1265 void Player::walk(float speed)
1266 {
1267   physic.set_velocity_x(speed);
1268 }
1269
1270 void
1271 Player::set_ghost_mode(bool enable)
1272 {
1273   if (ghost_mode == enable)
1274     return;
1275
1276   if (climbing) stop_climbing(*climbing);
1277
1278   if (enable) {
1279     ghost_mode = true;
1280     set_group(COLGROUP_DISABLED);
1281     physic.enable_gravity(false);
1282     log_debug << "You feel lightheaded. Use movement controls to float around, press ACTION to scare badguys." << std::endl;
1283   } else {
1284     ghost_mode = false;
1285     set_group(COLGROUP_MOVING);
1286     physic.enable_gravity(true);
1287     log_debug << "You feel solid again." << std::endl;
1288   }
1289 }
1290
1291
1292 void 
1293 Player::start_climbing(Climbable& climbable)
1294 {
1295   if (climbing == &climbable) return;
1296
1297   climbing = &climbable;
1298   physic.enable_gravity(false);
1299   physic.set_velocity(0, 0);
1300   physic.set_acceleration(0, 0);
1301 }
1302
1303 void 
1304 Player::stop_climbing(Climbable& /*climbable*/)
1305 {
1306   if (!climbing) return;
1307
1308   climbing = 0;
1309
1310   if (grabbed_object) {    
1311     grabbed_object->ungrab(*this, dir);
1312     grabbed_object = NULL;
1313   }
1314
1315   physic.enable_gravity(true);
1316   physic.set_velocity(0, 0);
1317   physic.set_acceleration(0, 0);
1318
1319   if ((controller->hold(Controller::JUMP)) || (controller->hold(Controller::UP))) {
1320     on_ground_flag = true;
1321     // TODO: This won't help. Why?
1322     do_jump(-300);
1323   }
1324 }
1325
1326 void
1327 Player::handle_input_climbing()
1328 {
1329   if (!climbing) {
1330     log_warning << "handle_input_climbing called with climbing set to 0. Input handling skipped" << std::endl;
1331     return;
1332   }
1333
1334   float vx = 0;
1335   float vy = 0;
1336   if (controller->hold(Controller::LEFT)) {
1337     dir = LEFT;
1338     vx -= MAX_CLIMB_XM;
1339   }
1340   if (controller->hold(Controller::RIGHT)) {
1341     dir = RIGHT;
1342     vx += MAX_CLIMB_XM;
1343   }
1344   if (controller->hold(Controller::UP)) {
1345     vy -= MAX_CLIMB_YM;
1346   }
1347   if (controller->hold(Controller::DOWN)) {
1348     vy += MAX_CLIMB_YM;
1349   }
1350   if (controller->hold(Controller::JUMP)) {
1351     if (can_jump) {
1352       stop_climbing(*climbing);
1353       return;
1354     }  
1355   } else {
1356     can_jump = true;
1357   }
1358   if (controller->hold(Controller::ACTION)) {
1359     stop_climbing(*climbing);
1360     return;
1361   }
1362   physic.set_velocity(vx, vy);
1363   physic.set_acceleration(0, 0);
1364 }
1365
1366