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