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