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