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