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