Tux shows arm when firing.
[supertux.git] / src / world.cpp
1 //  $Id$
2 // 
3 //  SuperTux
4 //  Copyright (C) 2000 Bill Kendrick <bill@newbreedsoftware.com>
5 //  Copyright (C) 2004 Tobias Glaesser <tobi.web@gmx.de>
6 //  Copyright (C) 2004 Ingo Ruhnke <grumbel@gmx.de>
7 //
8 //  This program is free software; you can redistribute it and/or
9 //  modify it under the terms of the GNU General Public License
10 //  as published by the Free Software Foundation; either version 2
11 //  of the License, or (at your option) any later version.
12 //
13 //  This program is distributed in the hope that it will be useful,
14 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
15 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 //  GNU General Public License for more details.
17 // 
18 //  You should have received a copy of the GNU General Public License
19 //  along with this program; if not, write to the Free Software
20 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
21 //  02111-1307, USA.
22
23 #include <iostream>
24 #include <math.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include "globals.h"
28 #include "scene.h"
29 #include "screen.h"
30 #include "defines.h"
31 #include "world.h"
32 #include "level.h"
33 #include "tile.h"
34 #include "resources.h"
35 #include "gameobjs.h"
36 #include "viewport.h"
37 #include "display_manager.h"
38 #include "background.h"
39 #include "tilemap.h"
40
41 Surface* img_distro[4];
42
43 World* World::current_ = 0;
44
45 World::World(const std::string& filename)
46 {
47   // FIXME: Move this to action and draw and everywhere else where the
48   // world calls child functions
49   current_ = this;
50
51   level = new Level();
52   level->load(filename, this);
53
54   tux = new Player(displaymanager);
55   gameobjects.push_back(tux);
56
57   set_defaults();
58
59   get_level()->load_gfx();
60   // add background
61   activate_particle_systems();
62   background = new Background(displaymanager);
63   if(level->img_bkgd) {
64     background->set_image(level->img_bkgd, level->bkgd_speed);
65   } else {
66     background->set_gradient(level->bkgd_top, level->bkgd_bottom);
67   }
68   gameobjects.push_back(background);
69
70   // add tilemap
71   gameobjects.push_back(new TileMap(displaymanager, get_level()));
72   get_level()->load_song();
73
74   apply_bonuses();
75
76   scrolling_timer.init(true);
77 }
78
79 World::World(const std::string& subset, int level_nr)
80 {
81   // FIXME: Move this to action and draw and everywhere else where the
82   // world calls child functions
83   current_ = this;
84
85   level = new Level();
86   level->load(subset, level_nr, this);
87
88   tux = new Player(displaymanager);
89   gameobjects.push_back(tux);        
90
91   set_defaults();
92
93   get_level()->load_gfx();
94   activate_particle_systems();
95   background = new Background(displaymanager);
96   if(level->img_bkgd) {
97     background->set_image(level->img_bkgd, level->bkgd_speed);
98   } else {
99     background->set_gradient(level->bkgd_top, level->bkgd_bottom);
100   }
101   gameobjects.push_back(background);
102   // add tilemap
103   gameobjects.push_back(new TileMap(displaymanager, get_level()));  
104   get_level()->load_song();
105
106   apply_bonuses();
107
108   scrolling_timer.init(true);
109 }
110
111 void
112 World::apply_bonuses()
113 {
114   // Apply bonuses from former levels
115   switch (player_status.bonus)
116     {
117     case PlayerStatus::NO_BONUS:
118       break;
119                                                                                 
120     case PlayerStatus::FLOWER_BONUS:
121       tux->got_power = Player::FIRE_POWER;  // FIXME: add ice power to here
122       // fall through
123                                                                                 
124     case PlayerStatus::GROWUP_BONUS:
125       tux->grow();
126       break;
127     }
128 }
129
130 World::~World()
131 {
132   for (std::vector<GameObject*>::iterator i = gameobjects.begin();
133           i != gameobjects.end(); ++i) {
134     delete *i;
135   }
136
137   delete level;
138 }
139
140 void
141 World::set_defaults()
142 {
143   player_status.score_multiplier = 1;
144
145   counting_distros = false;
146   distro_counter = 0;
147
148   /* set current song/music */
149   currentmusic = LEVEL_MUSIC;
150 }
151
152 void
153 World::add_object(GameObject* object)
154 {
155   // XXX hack for now until new collision code is ready
156   BadGuy* badguy = dynamic_cast<BadGuy*> (object);
157   if(badguy)
158     bad_guys.push_back(badguy);
159   Bullet* bullet = dynamic_cast<Bullet*> (object);
160   if(bullet)
161     bullets.push_back(bullet);
162   Upgrade* upgrade = dynamic_cast<Upgrade*> (object);
163   if(upgrade)
164     upgrades.push_back(upgrade);
165   Trampoline* trampoline = dynamic_cast<Trampoline*> (object);
166   if(trampoline)
167     trampolines.push_back(trampoline);
168
169   gameobjects.push_back(object);
170 }
171
172 void
173 World::parse_objects(lisp_object_t* cur)
174 {
175   while(!lisp_nil_p(cur)) {
176     lisp_object_t* data = lisp_car(cur);
177     std::string object_type = lisp_symbol(lisp_car(data));
178     
179     LispReader reader(lisp_cdr(data));
180
181     if(object_type == "trampoline") {
182       add_object(new Trampoline(displaymanager, reader));
183     } else {
184       BadGuyKind kind = badguykind_from_string(object_type);
185       add_object(new BadGuy(displaymanager, kind, reader));
186     }
187       
188     cur = lisp_cdr(cur);
189   } 
190 }
191
192 void
193 World::activate_particle_systems()
194 {
195   if (level->particle_system == "clouds")
196     {
197       add_object(new CloudParticleSystem(displaymanager));
198     }
199   else if (level->particle_system == "snow")
200     {
201       add_object(new SnowParticleSystem(displaymanager));
202     }
203   else if (level->particle_system != "")
204     {
205       st_abort("unknown particle system specified in level", "");
206     }
207 }
208
209 void
210 World::draw()
211 {
212   /* Draw objects */
213   displaymanager.draw();
214 }
215
216 void
217 World::action(float elapsed_time)
218 {
219   /* update objects (don't use iterators here, because the list might change
220    * during the iteration)
221    */
222   for(size_t i = 0; i < gameobjects.size(); ++i)
223     gameobjects[i]->action(elapsed_time);
224
225   tux->check_bounds(displaymanager.get_viewport(),
226       level->back_scrolling, (bool)level->hor_autoscroll_speed);
227   scrolling(elapsed_time);                                                      
228
229   /* Handle all possible collisions. */
230   collision_handler();
231  
232   /** cleanup marked objects */
233   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
234       i != gameobjects.end(); /* nothing */) {
235     if((*i)->is_valid() == false) {
236       Drawable* drawable = dynamic_cast<Drawable*> (*i);
237       if(drawable)
238         displaymanager.remove_drawable(drawable);
239       BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
240       if(badguy) {
241         bad_guys.erase(std::remove(bad_guys.begin(), bad_guys.end(), badguy),
242             bad_guys.end());
243       }
244       Bullet* bullet = dynamic_cast<Bullet*> (*i);
245       if(bullet) {
246         bullets.erase(
247             std::remove(bullets.begin(), bullets.end(), bullet),
248             bullets.end());
249       }
250       Upgrade* upgrade = dynamic_cast<Upgrade*> (*i);
251       if(upgrade) {
252         upgrades.erase(
253             std::remove(upgrades.begin(), upgrades.end(), upgrade),
254             upgrades.end());
255       }
256       Trampoline* trampoline = dynamic_cast<Trampoline*> (*i);
257       if(trampoline) {
258         trampolines.erase(
259             std::remove(trampolines.begin(), trampolines.end(), trampoline),
260             trampolines.end());
261       }
262       
263       delete *i;
264       i = gameobjects.erase(i);
265     } else {
266       ++i;
267     }
268   }
269 }
270
271 /* the space that it takes for the screen to start scrolling, regarding */
272 /* screen bounds (in pixels) */
273 // should be higher than screen->w/2 (400)
274 #define X_SPACE (500-16)
275 // should be less than screen->h/2 (300)
276 #define Y_SPACE 250
277
278 // the time it takes to move the camera (in ms)
279 #define CHANGE_DIR_SCROLL_SPEED 2000
280
281 /* This functions takes cares of the scrolling */
282 void World::scrolling(float elapsed_time)
283 {
284   float scroll_x = displaymanager.get_viewport().get_translation().x;
285   float scroll_y = displaymanager.get_viewport().get_translation().y;
286   
287   /* Y-axis scrolling */
288
289   float tux_pos_y = tux->base.y + (tux->base.height/2);
290
291   if(level->height > VISIBLE_TILES_Y-1 && !tux->dying)
292     {
293     if (scroll_y < tux_pos_y - (screen->h - Y_SPACE))
294       scroll_y = tux_pos_y - (screen->h - Y_SPACE);
295     else if (scroll_y > tux_pos_y - Y_SPACE)
296       scroll_y = tux_pos_y - Y_SPACE;
297     }
298
299   // this code prevent the screen to scroll before the start or after the level's end
300   if(scroll_y > level->height * 32 - screen->h)
301     scroll_y = level->height * 32 - screen->h;
302   if(scroll_y < 0)
303     scroll_y = 0;
304
305   /* X-axis scrolling */
306
307   /* Auto scrolling */
308   if(level->hor_autoscroll_speed)
309   {
310     scroll_x += level->hor_autoscroll_speed * elapsed_time;
311     displaymanager.get_viewport().set_translation(Vector(scroll_x, scroll_y));
312     return;
313   }
314
315
316   /* Horizontal backscrolling */
317   float tux_pos_x = tux->base.x + (tux->base.width/2);
318
319   if(tux->old_dir != tux->dir && level->back_scrolling)
320     scrolling_timer.start(CHANGE_DIR_SCROLL_SPEED);
321
322   bool right = false;
323   bool left = false;
324   if (tux->physic.get_velocity_x() > 0)
325     right = true;
326   else if (tux->physic.get_velocity_x() < 0)
327     left = true;
328   else
329     {
330     if (tux->dir == RIGHT)
331       right = true;
332     else
333       left = true;
334     }
335
336   if(scrolling_timer.check())
337   {
338     float final_scroll_x;
339     float constant1;
340     float constant2;
341     if (right)
342       final_scroll_x = tux_pos_x - (screen->w - X_SPACE);
343     else
344       final_scroll_x = tux_pos_x - X_SPACE;
345
346     if((tux->physic.get_velocity_x() > 0 && tux->dir == RIGHT)
347         || (tux->physic.get_velocity_x() < 0 && tux->dir == LEFT))
348     {
349       constant1 = 1.0;
350       constant2 = .4;
351     }
352     else
353     {
354       constant1 = 0.;
355       constant2 = 0.;
356     }
357     
358     float number = 2.5/(elapsed_time * CHANGE_DIR_SCROLL_SPEED/1000)*exp((CHANGE_DIR_SCROLL_SPEED-scrolling_timer.get_left())/1400.);
359     if(left) number *= -1.;
360
361     scroll_x += number
362             + constant1 * tux->physic.get_velocity_x() * elapsed_time
363             + constant2 * tux->physic.get_acceleration_x() * elapsed_time *
364             elapsed_time;
365
366     if ((right && final_scroll_x - scroll_x < 0) || (left && final_scroll_x - scroll_x > 0))
367       scroll_x = final_scroll_x;
368     
369   }
370   else
371   {
372     if (right && scroll_x < tux_pos_x - (screen->w - X_SPACE))
373       scroll_x = tux_pos_x - (screen->w - X_SPACE);
374     else if (left && scroll_x > tux_pos_x - X_SPACE && level->back_scrolling)
375       scroll_x = tux_pos_x - X_SPACE;
376   }
377
378   // this code prevent the screen to scroll before the start or after the level's end
379   if(scroll_x > level->width * 32 - screen->w)
380     scroll_x = level->width * 32 - screen->w;
381   if(scroll_x < 0)
382     scroll_x = 0;
383
384   displaymanager.get_viewport().set_translation(Vector(scroll_x, scroll_y));
385 }
386
387 void
388 World::collision_handler()
389 {
390   // CO_BULLET & CO_BADGUY check
391   for(unsigned int i = 0; i < bullets.size(); ++i)
392     {
393       for (BadGuys::iterator j = bad_guys.begin(); j != bad_guys.end(); ++j)
394         {
395           if((*j)->dying != DYING_NOT)
396             continue;
397           
398           if(rectcollision(bullets[i]->base, (*j)->base))
399             {
400               // We have detected a collision and now call the
401               // collision functions of the collided objects.
402               (*j)->collision(bullets[i], CO_BULLET, COLLISION_NORMAL);
403               bullets[i]->collision(CO_BADGUY);
404               break; // bullet is invalid now, so break
405             }
406         }
407     }
408
409   /* CO_BADGUY & CO_BADGUY check */
410   for (BadGuys::iterator i = bad_guys.begin(); i != bad_guys.end(); ++i)
411     {
412       if((*i)->dying != DYING_NOT)
413         continue;
414       
415       BadGuys::iterator j = i;
416       ++j;
417       for (; j != bad_guys.end(); ++j)
418         {
419           if(j == i || (*j)->dying != DYING_NOT)
420             continue;
421
422           if(rectcollision((*i)->base, (*j)->base))
423             {
424               // We have detected a collision and now call the
425               // collision functions of the collided objects.
426               (*j)->collision(*i, CO_BADGUY);
427               (*i)->collision(*j, CO_BADGUY);
428             }
429         }
430     }
431
432   if(tux->dying != DYING_NOT) return;
433     
434   // CO_BADGUY & CO_PLAYER check 
435   for (BadGuys::iterator i = bad_guys.begin(); i != bad_guys.end(); ++i)
436     {
437       if((*i)->dying != DYING_NOT)
438         continue;
439       
440       if(rectcollision_offset((*i)->base, tux->base, 0, 0))
441         {
442           // We have detected a collision and now call the collision
443           // functions of the collided objects.
444           if (tux->previous_base.y < tux->base.y &&
445               tux->previous_base.y + tux->previous_base.height 
446               < (*i)->base.y + (*i)->base.height/2
447               && !tux->invincible_timer.started())
448             {
449               (*i)->collision(tux, CO_PLAYER, COLLISION_SQUISH);
450             }
451           else
452             {
453               tux->collision(*i, CO_BADGUY);
454               (*i)->collision(tux, CO_PLAYER, COLLISION_NORMAL);
455             }
456         }
457     }
458
459   // CO_UPGRADE & CO_PLAYER check
460   for(unsigned int i = 0; i < upgrades.size(); ++i)
461     {
462       if(rectcollision(upgrades[i]->base, tux->base))
463         {
464           // We have detected a collision and now call the collision
465           // functions of the collided objects.
466           upgrades[i]->collision(tux, CO_PLAYER, COLLISION_NORMAL);
467         }
468     }
469
470   // CO_TRAMPOLINE & (CO_PLAYER or CO_BADGUY)
471   for (Trampolines::iterator i = trampolines.begin(); i != trampolines.end(); ++i)
472   {
473     if (rectcollision((*i)->base, tux->base))
474     {
475       if (tux->previous_base.y < tux->base.y &&
476           tux->previous_base.y + tux->previous_base.height 
477           < (*i)->base.y + (*i)->base.height/2)
478       {
479         (*i)->collision(tux, CO_PLAYER, COLLISION_SQUISH);
480       }
481       else if (tux->previous_base.y <= tux->base.y)
482       {
483         tux->collision(*i, CO_TRAMPOLINE);
484         (*i)->collision(tux, CO_PLAYER, COLLISION_NORMAL);
485       }
486     }
487   }
488 }
489
490 void
491 World::add_score(const Vector& pos, int s)
492 {
493   player_status.score += s;
494
495   add_object(new FloatingScore(displaymanager, pos, s));
496 }
497
498 void
499 World::add_bouncy_distro(const Vector& pos)
500 {
501   add_object(new BouncyDistro(displaymanager, pos));
502 }
503
504 void
505 World::add_broken_brick(const Vector& pos, Tile* tile)
506 {
507   add_broken_brick_piece(pos, Vector(-1, -4), tile);
508   add_broken_brick_piece(pos + Vector(0, 16), Vector(-1.5, -3), tile);
509
510   add_broken_brick_piece(pos + Vector(16, 0), Vector(1, -4), tile);
511   add_broken_brick_piece(pos + Vector(16, 16), Vector(1.5, -3), tile);
512 }
513
514 void
515 World::add_broken_brick_piece(const Vector& pos, const Vector& movement,
516     Tile* tile)
517 {
518   add_object(new BrokenBrick(displaymanager, tile, pos, movement));
519 }
520
521 void
522 World::add_bouncy_brick(const Vector& pos)
523 {
524   add_object(new BouncyBrick(displaymanager, pos));
525 }
526
527 BadGuy*
528 World::add_bad_guy(float x, float y, BadGuyKind kind)
529 {
530   BadGuy* badguy = new BadGuy(displaymanager, kind, x, y);
531   add_object(badguy);
532   return badguy;
533 }
534
535 void
536 World::add_upgrade(const Vector& pos, Direction dir, UpgradeKind kind)
537 {
538   add_object(new Upgrade(displaymanager, pos, dir, kind));
539 }
540
541 bool
542 World::add_bullet(const Vector& pos, float xm, Direction dir)
543 {
544   if(tux->got_power == Player::FIRE_POWER)
545     {
546     if(bullets.size() > MAX_FIRE_BULLETS-1)
547       return false;
548     }
549   else if(tux->got_power == Player::ICE_POWER)
550     {
551     if(bullets.size() > MAX_ICE_BULLETS-1)
552       return false;
553     }
554
555   Bullet* new_bullet = 0;
556   if(tux->got_power == Player::FIRE_POWER)
557     new_bullet = new Bullet(displaymanager, pos, xm, dir, FIRE_BULLET);
558   else if(tux->got_power == Player::ICE_POWER)
559     new_bullet = new Bullet(displaymanager, pos, xm, dir, ICE_BULLET);
560   else
561     st_abort("wrong bullet type.", "");
562   add_object(new_bullet);
563   
564   play_sound(sounds[SND_SHOOT], SOUND_CENTER_SPEAKER);
565
566   return true;
567 }
568
569 void
570 World::play_music(int musictype)
571 {
572   currentmusic = musictype;
573   switch(currentmusic) {
574     case HURRYUP_MUSIC:
575       music_manager->play_music(get_level()->get_level_music_fast());
576       break;
577     case LEVEL_MUSIC:
578       music_manager->play_music(get_level()->get_level_music());
579       break;
580     case HERRING_MUSIC:
581       music_manager->play_music(herring_song);
582       break;
583     default:
584       music_manager->halt_music();
585       break;
586   }
587 }
588
589 int
590 World::get_music_type()
591 {
592   return currentmusic;
593 }
594
595 /* Break a brick: */
596 bool
597 World::trybreakbrick(float x, float y, bool small)
598 {
599   Level* plevel = get_level();
600   
601   Tile* tile = gettile(x, y);
602   if (tile->brick)
603     {
604       if (tile->data > 0)
605         {
606           /* Get a distro from it: */
607           add_bouncy_distro(
608               Vector(((int)(x + 1) / 32) * 32, (int)(y / 32) * 32));
609
610           // TODO: don't handle this in a global way but per-tile...
611           if (!counting_distros)
612             {
613               counting_distros = true;
614               distro_counter = 5;
615             }
616           else
617             {
618               distro_counter--;
619             }
620
621           if (distro_counter <= 0)
622             {
623               counting_distros = false;
624               plevel->change(x, y, TM_IA, tile->next_tile);
625             }
626
627           play_sound(sounds[SND_DISTRO], SOUND_CENTER_SPEAKER);
628           player_status.score = player_status.score + SCORE_DISTRO;
629           player_status.distros++;
630           return true;
631         }
632       else if (!small)
633         {
634           /* Get rid of it: */
635           plevel->change(x, y, TM_IA, tile->next_tile);
636           
637           /* Replace it with broken bits: */
638           add_broken_brick(Vector(
639                                  ((int)(x + 1) / 32) * 32,
640                                  (int)(y / 32) * 32), tile);
641           
642           /* Get some score: */
643           play_sound(sounds[SND_BRICK], SOUND_CENTER_SPEAKER);
644           player_status.score = player_status.score + SCORE_BRICK;
645           
646           return true;
647         }
648     }
649
650   return false;
651 }
652
653 /* Empty a box: */
654 void
655 World::tryemptybox(float x, float y, Direction col_side)
656 {
657   Tile* tile = gettile(x,y);
658   if (!tile->fullbox)
659     return;
660
661   // according to the collision side, set the upgrade direction
662   if(col_side == LEFT)
663     col_side = RIGHT;
664   else
665     col_side = LEFT;
666
667   int posx = ((int)(x+1) / 32) * 32;
668   int posy = (int)(y/32) * 32 - 32;
669   switch(tile->data)
670     {
671     case 1: // Box with a distro!
672       add_bouncy_distro(Vector(posx, posy));
673       play_sound(sounds[SND_DISTRO], SOUND_CENTER_SPEAKER);
674       player_status.score = player_status.score + SCORE_DISTRO;
675       player_status.distros++;
676       break;
677
678     case 2: // Add a fire flower upgrade!
679       if (tux->size == SMALL)     /* Tux is small, add mints! */
680         add_upgrade(Vector(posx, posy), col_side, UPGRADE_GROWUP);
681       else     /* Tux is big, add a fireflower: */
682         add_upgrade(Vector(posx, posy), col_side, UPGRADE_FIREFLOWER);
683       play_sound(sounds[SND_UPGRADE], SOUND_CENTER_SPEAKER);
684       break;
685     
686     case 5: // Add an ice flower upgrade!
687       if (tux->size == SMALL)     /* Tux is small, add mints! */
688         add_upgrade(Vector(posx, posy), col_side, UPGRADE_GROWUP);
689       else     /* Tux is big, add an iceflower: */
690         add_upgrade(Vector(posx, posy), col_side, UPGRADE_ICEFLOWER);
691       play_sound(sounds[SND_UPGRADE], SOUND_CENTER_SPEAKER);
692       break;
693
694     case 3: // Add a golden herring
695       add_upgrade(Vector(posx, posy), col_side, UPGRADE_HERRING);
696       break;
697
698     case 4: // Add a 1up extra
699       add_upgrade(Vector(posx, posy), col_side, UPGRADE_1UP);
700       break;
701     default:
702       break;
703     }
704
705   /* Empty the box: */
706   level->change(x, y, TM_IA, tile->next_tile);
707 }
708
709 /* Try to grab a distro: */
710 void
711 World::trygrabdistro(float x, float y, int bounciness)
712 {
713   Tile* tile = gettile(x, y);
714   if (tile && tile->distro)
715     {
716       level->change(x, y, TM_IA, tile->next_tile);
717       play_sound(sounds[SND_DISTRO], SOUND_CENTER_SPEAKER);
718
719       if (bounciness == BOUNCE)
720         {
721           add_bouncy_distro(Vector(((int)(x + 1) / 32) * 32,
722                                   (int)(y / 32) * 32));
723         }
724
725       player_status.score = player_status.score + SCORE_DISTRO;
726       player_status.distros++;
727     }
728 }
729
730 /* Try to bump a bad guy from below: */
731 void
732 World::trybumpbadguy(float x, float y)
733 {
734   // Bad guys: 
735   for (BadGuys::iterator i = bad_guys.begin(); i != bad_guys.end(); ++i)
736     {
737       if ((*i)->base.x >= x - 32 && (*i)->base.x <= x + 32 &&
738           (*i)->base.y >= y - 16 && (*i)->base.y <= y + 16)
739         {
740           (*i)->collision(tux, CO_PLAYER, COLLISION_BUMP);
741         }
742     }
743
744   // Upgrades:
745   for (unsigned int i = 0; i < upgrades.size(); i++)
746     {
747       if (upgrades[i]->base.height == 32 &&
748           upgrades[i]->base.x >= x - 32 && upgrades[i]->base.x <= x + 32 &&
749           upgrades[i]->base.y >= y - 16 && upgrades[i]->base.y <= y + 16)
750         {
751           upgrades[i]->collision(tux, CO_PLAYER, COLLISION_BUMP);
752         }
753     }
754 }
755
756 /* EOF */
757