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