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