get_nearest_player won't return dying or dead players
[supertux.git] / src / badguy / badguy.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 "badguy.hpp"
22 #include "object/camera.hpp"
23 #include "object/tilemap.hpp"
24 #include "tile.hpp"
25 #include "statistics.hpp"
26 #include "game_session.hpp"
27 #include "log.hpp"
28 #include "level.hpp"
29 #include "object/bullet.hpp"
30 #include "main.hpp"
31 #include "object/particles.hpp"
32 #include "random_generator.hpp"
33
34 static const float SQUISH_TIME = 2;
35 static const float X_OFFSCREEN_DISTANCE = 1600;
36 static const float Y_OFFSCREEN_DISTANCE = 1200;
37
38 BadGuy::BadGuy(const Vector& pos, const std::string& sprite_name, int layer)
39   : MovingSprite(pos, sprite_name, layer, COLGROUP_DISABLED), countMe(true),
40     dir(LEFT), start_dir(AUTO), frozen(false), ignited(false),
41     state(STATE_INIT), on_ground_flag(false)
42 {
43   start_position = bbox.p1;
44
45   sound_manager->preload("sounds/squish.wav");
46   sound_manager->preload("sounds/fall.wav");
47 }
48
49 BadGuy::BadGuy(const Vector& pos, Direction direction, const std::string& sprite_name, int layer)
50   : MovingSprite(pos, sprite_name, layer, COLGROUP_DISABLED), countMe(true),
51     dir(direction), start_dir(direction), frozen(false), ignited(false),
52     state(STATE_INIT), on_ground_flag(false)
53 {
54   start_position = bbox.p1;
55
56   sound_manager->preload("sounds/squish.wav");
57   sound_manager->preload("sounds/fall.wav");
58 }
59
60 BadGuy::BadGuy(const lisp::Lisp& reader, const std::string& sprite_name, int layer)
61   : MovingSprite(reader, sprite_name, layer, COLGROUP_DISABLED), countMe(true), dir(LEFT), start_dir(AUTO), frozen(false), ignited(false), state(STATE_INIT), on_ground_flag(false)
62 {
63   start_position = bbox.p1;
64
65   std::string dir_str = "auto";
66   reader.get("direction", dir_str);
67   start_dir = str2dir( dir_str );
68   dir = start_dir;
69
70   reader.get("dead-script", dead_script);
71
72   sound_manager->preload("sounds/squish.wav");
73   sound_manager->preload("sounds/fall.wav");
74 }
75
76 void
77 BadGuy::draw(DrawingContext& context)
78 {
79   if(!sprite)
80     return;
81   if(state == STATE_INIT || state == STATE_INACTIVE)
82     return;
83   if(state == STATE_FALLING) {
84     DrawingEffect old_effect = context.get_drawing_effect();
85     context.set_drawing_effect((DrawingEffect) (old_effect | VERTICAL_FLIP));
86     sprite->draw(context, get_pos(), layer);
87     context.set_drawing_effect(old_effect);
88   } else {
89     sprite->draw(context, get_pos(), layer);
90   }
91 }
92
93 void
94 BadGuy::update(float elapsed_time)
95 {
96   if(!Sector::current()->inside(bbox)) {
97     is_active_flag = false;
98     remove_me();
99     return;
100   }
101   if(is_offscreen()) {
102     if (state == STATE_ACTIVE) deactivate();
103     set_state(STATE_INACTIVE);
104   }
105
106   switch(state) {
107     case STATE_ACTIVE:
108       is_active_flag = true;
109       active_update(elapsed_time);
110       break;
111     case STATE_INIT:
112     case STATE_INACTIVE:
113       is_active_flag = false;
114       inactive_update(elapsed_time);
115       try_activate();
116       break;
117     case STATE_SQUISHED:
118       is_active_flag = false;
119       if(state_timer.check()) {
120         remove_me();
121         break;
122       }
123       movement = physic.get_movement(elapsed_time);
124       break;
125     case STATE_FALLING:
126       is_active_flag = false;
127       movement = physic.get_movement(elapsed_time);
128       break;
129   }
130
131   on_ground_flag = false;
132 }
133
134 Direction
135 BadGuy::str2dir( std::string dir_str )
136 {
137   if( dir_str == "auto" )
138     return AUTO;
139   if( dir_str == "left" )
140     return LEFT;
141   if( dir_str == "right" )
142     return RIGHT;
143
144   //default to "auto"
145   log_warning << "Badguy::str2dir: unknown direction \"" << dir_str << "\"" << std::endl;;
146   return AUTO;
147 }
148
149 void
150 BadGuy::activate()
151 {
152 }
153
154 void
155 BadGuy::deactivate()
156 {
157 }
158
159 void
160 BadGuy::write(lisp::Writer& )
161 {
162   log_warning << "tried to write out a generic badguy" << std::endl;
163 }
164
165 void
166 BadGuy::active_update(float elapsed_time)
167 {
168   movement = physic.get_movement(elapsed_time);
169 }
170
171 void
172 BadGuy::inactive_update(float )
173 {
174 }
175
176 void
177 BadGuy::collision_tile(uint32_t tile_attributes)
178 {
179   if(tile_attributes & Tile::HURTS) {
180     if (tile_attributes & Tile::FIRE) {
181       if (is_flammable()) ignite();
182     }
183     else if (tile_attributes & Tile::ICE) {
184       if (is_freezable()) freeze();
185     }
186     else {
187       kill_fall();
188     }
189   }
190 }
191
192 HitResponse
193 BadGuy::collision(GameObject& other, const CollisionHit& hit)
194 {
195   if (!is_active()) return ABORT_MOVE;
196
197   BadGuy* badguy = dynamic_cast<BadGuy*> (&other);
198   if(badguy && badguy->is_active() && badguy->get_group() == COLGROUP_MOVING) {
199
200     // hit from above?
201     if (badguy->get_bbox().p2.y < (bbox.p1.y + 16)) {
202       if(collision_squished(*badguy)) {
203         return ABORT_MOVE;
204       }
205     }
206
207     return collision_badguy(*badguy, hit);
208   }
209
210   Player* player = dynamic_cast<Player*> (&other);
211   if(player) {
212
213     // hit from above?
214     if (player->get_bbox().p2.y < (bbox.p1.y + 16)) {
215       if(collision_squished(*player)) {
216         return ABORT_MOVE;
217       }
218     }
219
220     return collision_player(*player, hit);
221   }
222
223   Bullet* bullet = dynamic_cast<Bullet*> (&other);
224   if(bullet)
225     return collision_bullet(*bullet, hit);
226
227   return FORCE_MOVE;
228 }
229
230 void
231 BadGuy::collision_solid(const CollisionHit& hit)
232 {
233   physic.set_velocity_x(0);
234   physic.set_velocity_y(0);
235   update_on_ground_flag(hit);
236 }
237
238 HitResponse
239 BadGuy::collision_player(Player& player, const CollisionHit& )
240 {
241   if(player.is_invincible()) {
242     kill_fall();
243     return ABORT_MOVE;
244   }
245
246   if(frozen)
247     unfreeze();
248   player.kill(false);
249   return FORCE_MOVE;
250 }
251
252 HitResponse
253 BadGuy::collision_badguy(BadGuy& , const CollisionHit& )
254 {
255   return FORCE_MOVE;
256 }
257
258 bool
259 BadGuy::collision_squished(GameObject& )
260 {
261   return false;
262 }
263
264 HitResponse
265 BadGuy::collision_bullet(Bullet& bullet, const CollisionHit& hit)
266 {
267   if (is_frozen()) {
268     if(bullet.get_type() == FIRE_BONUS) {
269       // fire bullet thaws frozen badguys
270       unfreeze();
271       bullet.remove_me();
272       return ABORT_MOVE;
273     } else {
274       // other bullets ricochet
275       bullet.ricochet(*this, hit);
276       return FORCE_MOVE;
277     }
278   }
279   else if (is_ignited()) {
280     if(bullet.get_type() == ICE_BONUS) {
281       // ice bullets extinguish ignited badguys
282       extinguish();
283       bullet.remove_me();
284       return ABORT_MOVE;
285     } else {
286       // other bullets are absorbed by ignited badguys
287       bullet.remove_me();
288       return FORCE_MOVE;
289     }
290   }
291   else if(bullet.get_type() == FIRE_BONUS && is_flammable()) {
292     // fire bullets ignite flammable badguys
293     ignite();
294     bullet.remove_me();
295     return ABORT_MOVE;
296   }
297   else if(bullet.get_type() == ICE_BONUS && is_freezable()) {
298     // ice bullets freeze freezable badguys
299     freeze();
300     bullet.remove_me();
301     return ABORT_MOVE;
302   }
303   else {
304     // in all other cases, bullets ricochet
305     bullet.ricochet(*this, hit);
306     return FORCE_MOVE;
307   }
308 }
309
310 void
311 BadGuy::kill_squished(GameObject& object)
312 {
313   sound_manager->play("sounds/squish.wav", get_pos());
314   physic.enable_gravity(true);
315   physic.set_velocity_x(0);
316   physic.set_velocity_y(0);
317   set_state(STATE_SQUISHED);
318   set_group(COLGROUP_MOVING_ONLY_STATIC);
319   Player* player = dynamic_cast<Player*>(&object);
320   if (player) {
321     if (countMe) Sector::current()->get_level()->stats.badguys++;
322     player->bounce(*this);
323   }
324
325   // start dead-script
326   if(dead_script != "") {
327     std::istringstream stream(dead_script);
328     Sector::current()->run_script(stream, "dead-script");
329   }
330 }
331
332 void
333 BadGuy::kill_fall()
334 {
335   sound_manager->play("sounds/fall.wav", get_pos());
336   if (countMe) Sector::current()->get_level()->stats.badguys++;
337   physic.set_velocity_y(0);
338   physic.enable_gravity(true);
339   set_state(STATE_FALLING);
340
341   // start dead-script
342   if(dead_script != "") {
343     std::istringstream stream(dead_script);
344     Sector::current()->run_script(stream, "dead-script");
345   }
346 }
347
348 void
349 BadGuy::run_dead_script()
350 {
351    if (countMe)
352      Sector::current()->get_level()->stats.badguys++;
353    
354    // start dead-script
355   if(dead_script != "") {
356     std::istringstream stream(dead_script);
357     Sector::current()->run_script(stream, "dead-script");
358   }
359 }
360
361 void
362 BadGuy::set_state(State state)
363 {
364   if(this->state == state)
365     return;
366
367   State laststate = this->state;
368   this->state = state;
369   switch(state) {
370     case STATE_SQUISHED:
371       state_timer.start(SQUISH_TIME);
372       break;
373     case STATE_ACTIVE:
374       set_group(COLGROUP_MOVING);
375       bbox.set_pos(start_position);
376       break;
377     case STATE_INACTIVE:
378       // was the badguy dead anyway?
379       if(laststate == STATE_SQUISHED || laststate == STATE_FALLING) {
380         remove_me();
381       }
382       set_group(COLGROUP_DISABLED);
383       break;
384     case STATE_FALLING:
385       set_group(COLGROUP_DISABLED);
386       break;
387     default:
388       break;
389   }
390 }
391
392 bool
393 BadGuy::is_offscreen()
394 {
395   float scroll_x = Sector::current()->camera->get_translation().x;
396   float scroll_y = Sector::current()->camera->get_translation().y;
397
398   if(bbox.p2.x < scroll_x - X_OFFSCREEN_DISTANCE
399       || bbox.p1.x > scroll_x + X_OFFSCREEN_DISTANCE + SCREEN_WIDTH
400       || bbox.p2.y < scroll_y - Y_OFFSCREEN_DISTANCE
401       || bbox.p1.y > scroll_y + Y_OFFSCREEN_DISTANCE + SCREEN_HEIGHT)
402     return true;
403
404   return false;
405 }
406
407 void
408 BadGuy::try_activate()
409 {
410   float scroll_x = Sector::current()->camera->get_translation().x;
411   float scroll_y = Sector::current()->camera->get_translation().y;
412
413   /* Activate badguys if they're just around the screen to avoid
414    * the effect of having badguys suddenly popping up from nowhere.
415    */
416   //Badguy left of screen
417   if (start_position.x > scroll_x - X_OFFSCREEN_DISTANCE &&
418       start_position.x < scroll_x - bbox.get_width() &&
419       start_position.y > scroll_y - Y_OFFSCREEN_DISTANCE &&
420       start_position.y < scroll_y + SCREEN_HEIGHT + Y_OFFSCREEN_DISTANCE) {
421     if (start_dir != AUTO) dir = start_dir; else dir = RIGHT;
422     set_state(STATE_ACTIVE);
423     activate();
424   //Badguy right of screen
425   } else if (start_position.x > scroll_x +  SCREEN_WIDTH &&
426       start_position.x < scroll_x + SCREEN_WIDTH + X_OFFSCREEN_DISTANCE &&
427       start_position.y > scroll_y - Y_OFFSCREEN_DISTANCE &&
428       start_position.y < scroll_y + SCREEN_HEIGHT + Y_OFFSCREEN_DISTANCE) {
429     if (start_dir != AUTO) dir = start_dir; else dir = LEFT;
430     set_state(STATE_ACTIVE);
431     activate();
432   //Badguy over or under screen
433   } else if (start_position.x > scroll_x - X_OFFSCREEN_DISTANCE &&
434        start_position.x < scroll_x + SCREEN_WIDTH + X_OFFSCREEN_DISTANCE &&
435        ((start_position.y > scroll_y + SCREEN_HEIGHT &&
436          start_position.y < scroll_y + SCREEN_HEIGHT + Y_OFFSCREEN_DISTANCE) ||
437         (start_position.y > scroll_y - Y_OFFSCREEN_DISTANCE &&
438          start_position.y < scroll_y - bbox.get_height()  ))) {
439      if (start_dir != AUTO) dir = start_dir;
440      else{
441          // if nearest player is to our right, start facing right
442          Player* player = get_nearest_player();
443          if (player && (player->get_bbox().p1.x > get_bbox().p2.x)) {
444              dir = RIGHT;
445          } else {
446                  dir = LEFT;
447          }
448      }
449      set_state(STATE_ACTIVE);
450      activate();
451   } else if(state == STATE_INIT
452       && start_position.x > scroll_x - X_OFFSCREEN_DISTANCE
453       && start_position.x < scroll_x + X_OFFSCREEN_DISTANCE + SCREEN_WIDTH
454       && start_position.y > scroll_y - Y_OFFSCREEN_DISTANCE
455       && start_position.y < scroll_y + Y_OFFSCREEN_DISTANCE + SCREEN_HEIGHT ) {
456     if (start_dir != AUTO) {
457       dir = start_dir;
458     } else {
459       // if nearest player is to our right, start facing right
460       Player* player = get_nearest_player();
461       if (player && (player->get_bbox().p1.x > get_bbox().p2.x)) {
462         dir = RIGHT;
463       } else {
464         dir = LEFT;
465       }
466     }
467     set_state(STATE_ACTIVE);
468     activate();
469   }
470 }
471
472 bool
473 BadGuy::might_fall(int height)
474 {
475   // make sure we check for at least a 1-pixel fall
476   assert(height > 0);
477
478   float x1;
479   float x2;
480   float y1 = bbox.p2.y + 1;
481   float y2 = bbox.p2.y + 1 + height;
482   if (dir == LEFT) {
483     x1 = bbox.p1.x - 1;
484     x2 = bbox.p1.x - 1;
485   } else {
486     x1 = bbox.p2.x + 1;
487     x2 = bbox.p2.x + 1;
488   }
489   return Sector::current()->is_free_of_statics(Rect(x1, y1, x2, y2));
490 }
491
492 Player*
493 BadGuy::get_nearest_player()
494 {
495   // FIXME: does not really return nearest player
496
497   std::vector<Player*> players = Sector::current()->get_players();
498   for (std::vector<Player*>::iterator playerIter = players.begin(); playerIter != players.end(); ++playerIter) {
499     Player* player = *playerIter;
500     if (player->is_dying() || player->is_dead()) continue;
501     return player;
502   }
503
504   return 0;
505 }
506
507 void
508 BadGuy::update_on_ground_flag(const CollisionHit& hit)
509 {
510   if (hit.bottom) {
511     on_ground_flag = true;
512     floor_normal = hit.slope_normal;
513   }
514 }
515
516 bool
517 BadGuy::on_ground()
518 {
519   return on_ground_flag;
520 }
521
522 bool
523 BadGuy::is_active()
524 {
525   return is_active_flag;
526 }
527
528 Vector
529 BadGuy::get_floor_normal()
530 {
531   return floor_normal;
532 }
533
534 void
535 BadGuy::freeze()
536 {
537   set_group(COLGROUP_MOVING_STATIC);
538   frozen = true;
539 }
540
541 void
542 BadGuy::unfreeze()
543 {
544   set_group(COLGROUP_MOVING);
545   frozen = false;
546 }
547
548 bool
549 BadGuy::is_freezable() const
550 {
551   return false;
552 }
553
554 bool
555 BadGuy::is_frozen() const
556 {
557   return frozen;
558 }
559
560 void
561 BadGuy::ignite()
562 {
563   kill_fall();
564 }
565
566 void
567 BadGuy::extinguish()
568 {
569 }
570
571 bool
572 BadGuy::is_flammable() const
573 {
574   return true;
575 }
576
577 bool
578 BadGuy::is_ignited() const
579 {
580   return ignited;
581 }