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