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