more adjustments to collision detection, tux is correctly placed above badguys again...
[supertux.git] / src / sector.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 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 <memory>
22 #include <algorithm>
23 #include <stdexcept>
24 #include <iostream>
25 #include <fstream>
26 #include <sstream>
27 #include <stdexcept>
28 #include <float.h>
29
30 #include "sector.hpp"
31 #include "player_status.hpp"
32 #include "object/gameobjs.hpp"
33 #include "object/camera.hpp"
34 #include "object/background.hpp"
35 #include "object/particlesystem.hpp"
36 #include "object/particlesystem_interactive.hpp"
37 #include "object/tilemap.hpp"
38 #include "lisp/parser.hpp"
39 #include "lisp/lisp.hpp"
40 #include "lisp/writer.hpp"
41 #include "lisp/list_iterator.hpp"
42 #include "tile.hpp"
43 #include "audio/sound_manager.hpp"
44 #include "game_session.hpp"
45 #include "resources.hpp"
46 #include "statistics.hpp"
47 #include "collision_grid.hpp"
48 #include "collision_grid_iterator.hpp"
49 #include "object_factory.hpp"
50 #include "collision.hpp"
51 #include "spawn_point.hpp"
52 #include "math/rect.hpp"
53 #include "math/aatriangle.hpp"
54 #include "object/coin.hpp"
55 #include "object/block.hpp"
56 #include "object/invisible_block.hpp"
57 #include "object/bullet.hpp"
58 #include "object/text_object.hpp"
59 #include "badguy/jumpy.hpp"
60 #include "trigger/sequence_trigger.hpp"
61 #include "player_status.hpp"
62 #include "scripting/script_interpreter.hpp"
63 #include "scripting/sound.hpp"
64 #include "scripting/scripted_object.hpp"
65 #include "scripting/text.hpp"
66
67 Sector* Sector::_current = 0;
68
69 Sector::Sector()
70   : gravity(10), player(0), solids(0), camera(0),
71     currentmusic(LEVEL_MUSIC)
72 {
73   song_title = "chipdisko.ogg";
74   player = new Player(player_status);
75   add_object(player);
76
77 #ifdef USE_GRID
78   grid = new CollisionGrid(32000, 32000);
79 #else
80   grid = 0;
81 #endif
82 }
83
84 Sector::~Sector()
85 {
86   update_game_objects();
87   assert(gameobjects_new.size() == 0);
88
89   delete grid;
90
91   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
92       ++i) {
93     delete *i;
94   }
95
96   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
97       ++i)
98     delete *i;
99     
100   if(_current == this)
101     _current = 0;
102 }
103
104 GameObject*
105 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
106 {
107   if(name == "camera") {
108     Camera* camera = new Camera(this);
109     camera->parse(reader);
110     return camera;
111   } else if(name == "particles-snow") {
112     SnowParticleSystem* partsys = new SnowParticleSystem();
113     partsys->parse(reader);
114     return partsys;
115   } else if(name == "particles-rain") {
116     RainParticleSystem* partsys = new RainParticleSystem();
117     partsys->parse(reader);
118     return partsys;
119   } else if(name == "particles-comets") {
120     CometParticleSystem* partsys = new CometParticleSystem();
121     partsys->parse(reader);
122     return partsys;
123   } else if(name == "particles-ghosts") {
124     GhostParticleSystem* partsys = new GhostParticleSystem();
125     partsys->parse(reader);
126     return partsys;
127   } else if(name == "particles-clouds") {
128     CloudParticleSystem* partsys = new CloudParticleSystem();
129     partsys->parse(reader);
130     return partsys;
131   } else if(name == "money") { // for compatibility with old maps
132     return new Jumpy(reader);
133   } 
134
135   try {
136     return create_object(name, reader);
137   } catch(std::exception& e) {
138     std::cerr << e.what() << "\n";
139   }
140   
141   return 0;
142 }
143
144 void
145 Sector::parse(const lisp::Lisp& sector)
146 {
147   _current = this;
148   
149   lisp::ListIterator iter(&sector);
150   while(iter.next()) {
151     const std::string& token = iter.item();
152     if(token == "name") {
153       iter.value()->get(name);
154     } else if(token == "gravity") {
155       iter.value()->get(gravity);
156     } else if(token == "music") {
157       iter.value()->get(song_title);
158     } else if(token == "spawnpoint") {
159       SpawnPoint* sp = new SpawnPoint(iter.lisp());
160       spawnpoints.push_back(sp);
161     } else if(token == "init-script") {
162       iter.value()->get(init_script);
163     } else {
164       GameObject* object = parse_object(token, *(iter.lisp()));
165       if(object) {
166         add_object(object);
167       }
168     }
169   }
170
171   update_game_objects();
172
173   if(!solids)
174     throw std::runtime_error("sector does not contain a solid tile layer.");
175
176   fix_old_tiles();
177   if(!camera) {
178     std::cerr << "sector '" << name << "' does not contain a camera.\n";
179     update_game_objects();
180     add_object(new Camera(this));
181   }
182
183   update_game_objects();
184 }
185
186 void
187 Sector::parse_old_format(const lisp::Lisp& reader)
188 {
189   _current = this;
190   
191   name = "main";
192   reader.get("gravity", gravity);
193
194   std::string backgroundimage;
195   reader.get("background", backgroundimage);
196   float bgspeed = .5;
197   reader.get("bkgd_speed", bgspeed);
198   bgspeed /= 100;
199
200   Color bkgd_top, bkgd_bottom;
201   int r = 0, g = 0, b = 128;
202   reader.get("bkgd_red_top", r);
203   reader.get("bkgd_green_top",  g);
204   reader.get("bkgd_blue_top",  b);
205   bkgd_top.red = static_cast<float> (r) / 255.0f;
206   bkgd_top.green = static_cast<float> (g) / 255.0f;
207   bkgd_top.blue = static_cast<float> (b) / 255.0f;
208   
209   reader.get("bkgd_red_bottom",  r);
210   reader.get("bkgd_green_bottom", g);
211   reader.get("bkgd_blue_bottom", b);
212   bkgd_bottom.red = static_cast<float> (r) / 255.0f;
213   bkgd_bottom.green = static_cast<float> (g) / 255.0f;
214   bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
215   
216   if(backgroundimage != "") {
217     Background* background = new Background;
218     background->set_image(backgroundimage, bgspeed);
219     add_object(background);
220   } else {
221     Background* background = new Background;
222     background->set_gradient(bkgd_top, bkgd_bottom);
223     add_object(background);
224   }
225
226   std::string particlesystem;
227   reader.get("particle_system", particlesystem);
228   if(particlesystem == "clouds")
229     add_object(new CloudParticleSystem());
230   else if(particlesystem == "snow")
231     add_object(new SnowParticleSystem());
232   else if(particlesystem == "rain")
233     add_object(new RainParticleSystem());
234
235   Vector startpos(100, 170);
236   reader.get("start_pos_x", startpos.x);
237   reader.get("start_pos_y", startpos.y);
238
239   SpawnPoint* spawn = new SpawnPoint;
240   spawn->pos = startpos;
241   spawn->name = "main";
242   spawnpoints.push_back(spawn);
243
244   song_title = "chipdisko.ogg";
245   reader.get("music", song_title);
246
247   int width = 30, height = 15;
248   reader.get("width", width);
249   reader.get("height", height);
250   
251   std::vector<unsigned int> tiles;
252   if(reader.get_vector("interactive-tm", tiles)
253       || reader.get_vector("tilemap", tiles)) {
254     TileMap* tilemap = new TileMap();
255     tilemap->set(width, height, tiles, LAYER_TILES, true);
256     add_object(tilemap);
257   }
258
259   if(reader.get_vector("background-tm", tiles)) {
260     TileMap* tilemap = new TileMap();
261     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
262     add_object(tilemap);
263   }
264
265   if(reader.get_vector("foreground-tm", tiles)) {
266     TileMap* tilemap = new TileMap();
267     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
268     add_object(tilemap);
269   }
270
271   // read reset-points (now spawn-points)
272   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
273   if(resetpoints) {
274     lisp::ListIterator iter(resetpoints);
275     while(iter.next()) {
276       if(iter.item() == "point") {
277         Vector sp_pos;
278         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
279           {
280           SpawnPoint* sp = new SpawnPoint;
281           sp->name = "main";
282           sp->pos = sp_pos;
283           spawnpoints.push_back(sp);
284           }
285       } else {
286         std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
287       }
288     }
289   }
290
291   // read objects
292   const lisp::Lisp* objects = reader.get_lisp("objects");
293   if(objects) {
294     lisp::ListIterator iter(objects);
295     while(iter.next()) {
296       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
297       if(object) {
298         add_object(object);
299       } else {
300         std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
301       }
302     }
303   }
304
305   // add a camera
306   Camera* camera = new Camera(this);
307   add_object(camera);
308
309   update_game_objects();
310
311   if(solids == 0)
312     throw std::runtime_error("sector does not contain a solid tile layer.");
313
314   fix_old_tiles();
315   update_game_objects();
316 }
317
318 void
319 Sector::fix_old_tiles()
320 {
321   // hack for now...
322   for(size_t x=0; x < solids->get_width(); ++x) {
323     for(size_t y=0; y < solids->get_height(); ++y) {
324       const Tile* tile = solids->get_tile(x, y);
325       Vector pos(x*32, y*32);
326       
327       if(tile->getID() == 112) {
328         add_object(new InvisibleBlock(pos));
329         solids->change(x, y, 0);
330       } else if(tile->getAttributes() & Tile::COIN) {
331         add_object(new Coin(pos));
332         solids->change(x, y, 0);
333       } else if(tile->getAttributes() & Tile::FULLBOX) {
334         add_object(new BonusBlock(pos, tile->getData()));
335         solids->change(x, y, 0);
336       } else if(tile->getAttributes() & Tile::BRICK) {
337         add_object(new Brick(pos, tile->getData()));
338         solids->change(x, y, 0);
339       } else if(tile->getAttributes() & Tile::GOAL) {
340         std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
341         add_object(new SequenceTrigger(pos, sequence));
342         solids->change(x, y, 0);
343       }
344     }
345   }
346 }
347
348 void
349 Sector::write(lisp::Writer& writer)
350 {
351   writer.write_string("name", name);
352   writer.write_float("gravity", gravity);
353   writer.write_string("music", song_title);
354
355   // write spawnpoints
356   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
357       ++i) {
358     SpawnPoint* spawn = *i;
359     writer.start_list("spawn-points");
360     writer.write_string("name", spawn->name);
361     writer.write_float("x", spawn->pos.x);
362     writer.write_float("y", spawn->pos.y);
363     writer.end_list("spawn-points");
364   }
365
366   // write objects
367   for(GameObjects::iterator i = gameobjects.begin();
368       i != gameobjects.end(); ++i) {
369     Serializable* serializable = dynamic_cast<Serializable*> (*i);
370     if(serializable)
371       serializable->write(writer);
372   }
373 }
374
375 void
376 Sector::add_object(GameObject* object)
377 {
378   // make sure the object isn't already in the list
379 #ifdef DEBUG
380   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
381       ++i) {
382     if(*i == object) {
383       assert("object already added to sector" == 0);
384     }
385   }
386   for(GameObjects::iterator i = gameobjects_new.begin();
387       i != gameobjects_new.end(); ++i) {
388     if(*i == object) {
389       assert("object already added to sector" == 0);
390     }
391   }
392 #endif
393
394   gameobjects_new.push_back(object);
395 }
396
397 void
398 Sector::activate(const std::string& spawnpoint)
399 {
400   SpawnPoint* sp = 0;
401   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
402       ++i) {
403     if((*i)->name == spawnpoint) {
404       sp = *i;
405       break;
406     }
407   }                                                                           
408   if(!sp) {
409     std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
410     if(spawnpoint != "main") {
411       activate("main");
412     } else {
413       activate(Vector(0, 0));
414     }
415   } else {
416     activate(sp->pos);
417   }
418
419   // Run init script
420   if(init_script != "") {
421     ScriptInterpreter::add_script_object(this,
422         std::string("Sector(") + name + ") - init", init_script);
423   }
424 }
425
426 void
427 Sector::activate(const Vector& player_pos)
428 {
429   _current = this;
430
431   player->move(player_pos);
432   camera->reset(player->get_pos());
433 }
434
435 Rect
436 Sector::get_active_region()
437 {
438   return Rect(
439     camera->get_translation() - Vector(1600, 1200),
440     camera->get_translation() + Vector(1600, 1200));
441 }
442
443 void
444 Sector::update(float elapsed_time)
445 {
446   player->check_bounds(camera);
447
448 #if 0
449   CollisionGridIterator iter(*grid, get_active_region());
450   while(MovingObject* object = iter.next()) {
451     if(!object->is_valid())
452       continue;
453
454     object->update(elapsed_time);
455   }
456 #else
457   /* update objects */
458   for(GameObjects::iterator i = gameobjects.begin();
459           i != gameobjects.end(); ++i) {
460     GameObject* object = *i;
461     if(!object->is_valid())
462       continue;
463     
464     object->update(elapsed_time);
465   }
466 #endif
467   
468   /* Handle all possible collisions. */
469   handle_collisions();
470   update_game_objects();
471 }
472
473 void
474 Sector::update_game_objects()
475 {
476   /** cleanup marked objects */
477   for(std::vector<Bullet*>::iterator i = bullets.begin();
478       i != bullets.end(); /* nothing */) {
479     Bullet* bullet = *i;
480     if(bullet->is_valid()) {
481       ++i;
482       continue;
483     }
484
485     i = bullets.erase(i);
486   }
487   for(MovingObjects::iterator i = moving_objects.begin();
488       i != moving_objects.end(); /* nothing */) {
489     MovingObject* moving_object = *i;
490     if(moving_object->is_valid()) {
491       ++i;
492       continue;
493     }
494
495 #ifdef USE_GRID
496     grid->remove_object(moving_object);
497 #endif
498     
499     i = moving_objects.erase(i);
500   }
501   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
502       i != gameobjects.end(); /* nothing */) {
503     GameObject* object = *i;
504     
505     if(object->is_valid()) {
506       ++i;
507       continue;
508     }
509     
510     delete *i;
511     i = gameobjects.erase(i);
512   }
513
514   /* add newly created objects */
515   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
516       i != gameobjects_new.end(); ++i)
517   {
518     GameObject* object = *i;
519     
520     Bullet* bullet = dynamic_cast<Bullet*> (object);
521     if(bullet)
522       bullets.push_back(bullet);
523
524     MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
525     if(movingobject) {
526       moving_objects.push_back(movingobject);
527  #ifdef USE_GRID
528       grid->add_object(movingobject);
529 #endif
530     }
531     
532     TileMap* tilemap = dynamic_cast<TileMap*> (object);
533     if(tilemap && tilemap->is_solid()) {
534       if(solids == 0) {
535         solids = tilemap;
536       } else {
537         std::cerr << "Another solid tilemaps added. Ignoring.";
538       }
539     }
540
541     Camera* camera = dynamic_cast<Camera*> (object);
542     if(camera) {
543       if(this->camera != 0) {
544         std::cerr << "Warning: Multiple cameras added. Ignoring.";
545         continue;
546       }
547       this->camera = camera;
548     }
549
550     gameobjects.push_back(object);
551   }
552   gameobjects_new.clear();
553 }
554
555 void
556 Sector::draw(DrawingContext& context)
557 {
558   context.push_transform();
559   context.set_translation(camera->get_translation());
560
561   for(GameObjects::iterator i = gameobjects.begin();
562       i != gameobjects.end(); ++i) {
563     GameObject* object = *i; 
564     if(!object->is_valid())
565       continue;
566     
567     object->draw(context);
568   }
569
570   context.pop_transform();
571 }
572
573 static const float DELTA = .001;
574
575 void
576 Sector::collision_tilemap(MovingObject* object, CollisionHit& hit) const
577 {
578   // calculate rectangle where the object will move
579   float x1, x2;
580   if(object->get_movement().x >= 0) {
581     x1 = object->get_bbox().p1.x;
582     x2 = object->get_bbox().p2.x + object->get_movement().x;
583   } else {
584     x1 = object->get_bbox().p1.x + object->get_movement().x;
585     x2 = object->get_bbox().p2.x;
586   }
587   float y1, y2;
588   if(object->get_movement().y >= 0) {
589     y1 = object->get_bbox().p1.y;
590     y2 = object->get_bbox().p2.y + object->get_movement().y;
591   } else {
592     y1 = object->get_bbox().p1.y + object->get_movement().y;
593     y2 = object->get_bbox().p2.y;
594   }
595
596   // test with all tiles in this rectangle
597   int starttilex = int(x1) / 32;
598   int starttiley = int(y1) / 32;
599   int max_x = int(x2);
600   // the +1 is somehow needed to make characters stay on the floor
601   int max_y = int(y2+1);
602
603   CollisionHit temphit;
604   Rect dest = object->get_bbox();
605   dest.move(object->movement);
606   for(int x = starttilex; x*32 < max_x; ++x) {
607     for(int y = starttiley; y*32 < max_y; ++y) {
608       const Tile* tile = solids->get_tile(x, y);
609       if(!tile)
610         continue;
611       // skip non-solid tiles
612       if(tile->getAttributes() == 0)
613         continue;
614       // only handle unisolid when the player is falling down and when he was
615       // above the tile before
616       if(tile->getAttributes() & Tile::UNISOLID) {
617         if(object->movement.y < 0 || object->get_bbox().p2.y > y*32)
618           continue;
619       }
620
621       if(tile->getAttributes() & Tile::SLOPE) { // slope tile
622         AATriangle triangle;
623         Vector p1(x*32, y*32);
624         Vector p2((x+1)*32, (y+1)*32);
625         triangle = AATriangle(p1, p2, tile->getData());
626
627         if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
628               triangle)) {
629           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
630             hit = temphit;
631           }
632         }
633       } else { // normal rectangular tile
634         Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
635         if(Collision::rectangle_rectangle(temphit, dest,
636               object->movement, rect)) {
637           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
638             hit = temphit;
639           }
640         }
641       }
642     }
643   }
644 }
645
646 uint32_t
647 Sector::collision_tile_attributes(MovingObject* object) const
648 {
649   /** XXX This function doesn't work correctly as it will check all tiles
650    * in the bounding box of the object movement, this might include tiles
651    * that have actually never been touched by the object
652    * (though this only occures for very fast objects...)
653    */
654   
655   // calculate rectangle where the object will move
656   float x1, x2;
657   if(object->get_movement().x >= 0) {
658     x1 = object->get_bbox().p1.x;
659     x2 = object->get_bbox().p2.x + object->get_movement().x;
660   } else {
661     x1 = object->get_bbox().p1.x + object->get_movement().x;
662     x2 = object->get_bbox().p2.x;
663   }
664   float y1, y2;
665   if(object->get_movement().y >= 0) {
666     y1 = object->get_bbox().p1.y;
667     y2 = object->get_bbox().p2.y + object->get_movement().y;
668   } else {
669     y1 = object->get_bbox().p1.y + object->get_movement().y;
670     y2 = object->get_bbox().p2.y;
671   }
672
673   // test with all tiles in this rectangle
674   int starttilex = int(x1-1) / 32;
675   int starttiley = int(y1-1) / 32;
676   int max_x = int(x2+1);
677   int max_y = int(y2+1);
678
679   uint32_t result = 0;
680   for(int x = starttilex; x*32 < max_x; ++x) {
681     for(int y = starttiley; y*32 < max_y; ++y) {
682       const Tile* tile = solids->get_tile(x, y);
683       if(!tile)
684         continue;
685       result |= tile->getAttributes();
686     }
687   }
688
689   return result;
690 }
691
692 void
693 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
694 {
695   CollisionHit hit;
696   Rect dest1 = object1->get_bbox();
697   dest1.move(object1->get_movement());
698   Rect dest2 = object2->get_bbox();
699   dest2.move(object2->get_movement());
700
701   Vector movement = object1->get_movement() - object2->get_movement();
702   if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
703     HitResponse response1 = object1->collision(*object2, hit);
704     hit.normal *= -1;
705     HitResponse response2 = object2->collision(*object1, hit);
706
707     if(response1 != CONTINUE) {
708       if(response1 == ABORT_MOVE)
709         object1->movement = Vector(0, 0);
710       if(response2 == CONTINUE)
711         object2->movement += hit.normal * (hit.depth + DELTA);
712     } else if(response2 != CONTINUE) {
713       if(response2 == ABORT_MOVE)
714         object2->movement = Vector(0, 0);
715       if(response1 == CONTINUE)
716         object1->movement += -hit.normal * (hit.depth + DELTA);
717     } else {
718       object1->movement += -hit.normal * (hit.depth/2 + DELTA);
719       object2->movement += hit.normal * (hit.depth/2 + DELTA);
720     }
721   }
722 }
723
724 void
725 Sector::handle_collisions()
726 {
727   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
728   //   we do this up to 4 times and have to sort all results for the smallest
729   //   one before we can continue here
730   for(MovingObjects::iterator i = moving_objects.begin();
731       i != moving_objects.end(); ++i) {
732     MovingObject* moving_object = *i;
733     if((moving_object->get_group() != COLGROUP_MOVING
734           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
735         || !moving_object->is_valid())
736       continue;
737
738     // up to 4 tries
739     for(int t = 0; t < 4; ++t) {
740       CollisionHit hit;
741       hit.time = -1;
742       MovingObject* collided_with = NULL; 
743       
744       // collision with tilemap
745       collision_tilemap(moving_object, hit);
746     
747       // collision with other objects
748       Rect dest1 = moving_object->get_bbox();
749       dest1.move(moving_object->get_movement());
750       CollisionHit temphit;
751       
752       for(MovingObjects::iterator i2 = moving_objects.begin();
753           i2 != moving_objects.end(); ++i2) {
754         MovingObject* moving_object_2 = *i2;
755         if(moving_object_2->get_group() != COLGROUP_STATIC
756            || !moving_object_2->is_valid())
757           continue;
758         
759         Rect dest2 = moving_object_2->get_bbox();
760         dest2.move(moving_object_2->get_movement());
761         Vector movement 
762           = moving_object->get_movement() - moving_object_2->get_movement();
763         if(Collision::rectangle_rectangle(temphit, dest1, movement, dest2)
764             && temphit.time > hit.time) {
765           hit = temphit;
766           collided_with = moving_object_2;
767         }
768       }
769
770       if(hit.time < 0)
771         break;
772
773       // call collision callbacks
774       HitResponse response;
775       if(collided_with != 0) {
776         response = moving_object->collision(*collided_with, hit);
777         hit.normal *= -1;
778         collided_with->collision(*moving_object, hit);
779       } else {
780         response = moving_object->collision(*solids, hit);
781         hit.normal *= -1;
782       }
783    
784       if(response == CONTINUE) {
785         moving_object->movement += -hit.normal * (hit.depth + DELTA);
786       } else if(response == ABORT_MOVE) {
787         moving_object->movement = Vector(0, 0);
788         break;
789       } else { // force move
790         break;
791       }
792     }
793   }
794
795   // part2: COLGROUP_MOVING vs tile attributes
796   for(MovingObjects::iterator i = moving_objects.begin();
797       i != moving_objects.end(); ++i) {
798     MovingObject* moving_object = *i;
799     if((moving_object->get_group() != COLGROUP_MOVING
800           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
801         || !moving_object->is_valid())
802       continue;
803
804     uint32_t tile_attributes = collision_tile_attributes(moving_object);
805     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
806       moving_object->collision_tile(tile_attributes);
807     }
808   }
809
810   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
811   for(MovingObjects::iterator i = moving_objects.begin();
812       i != moving_objects.end(); ++i) {
813     MovingObject* moving_object = *i;
814     if(moving_object->get_group() != COLGROUP_MOVING
815         || !moving_object->is_valid())
816       continue;
817
818     for(MovingObjects::iterator i2 = moving_objects.begin();
819         i2 != moving_objects.end(); ++i2) {
820       MovingObject* moving_object_2 = *i2;
821       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
822          || !moving_object_2->is_valid())
823         continue;
824
825       collision_object(moving_object, moving_object_2);
826     } 
827   }
828
829   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
830   for(MovingObjects::iterator i = moving_objects.begin();
831       i != moving_objects.end(); ++i) {
832     MovingObject* moving_object = *i;
833
834     if(moving_object->get_group() != COLGROUP_MOVING
835         || !moving_object->is_valid())
836       continue;
837
838     for(MovingObjects::iterator i2 = i+1;
839         i2 != moving_objects.end(); ++i2) {
840       MovingObject* moving_object_2 = *i2;
841       if(moving_object_2->get_group() != COLGROUP_MOVING
842          || !moving_object_2->is_valid())
843         continue;
844
845       collision_object(moving_object, moving_object_2);
846     }    
847   }
848
849   // apply object movement
850   for(MovingObjects::iterator i = moving_objects.begin();
851       i != moving_objects.end(); ++i) {
852     MovingObject* moving_object = *i;
853
854     moving_object->bbox.move(moving_object->get_movement());
855     moving_object->movement = Vector(0, 0);
856   }
857 }
858
859 bool
860 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
861 {
862   // TODO remove this function and move these checks elsewhere...
863   static const size_t MAX_FIRE_BULLETS = 2;
864   static const size_t MAX_ICE_BULLETS = 1;
865
866   Bullet* new_bullet = 0;
867   if(player_status->bonus == FIRE_BONUS) {
868     if(bullets.size() > MAX_FIRE_BULLETS-1)
869       return false;
870     new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
871   } else if(player_status->bonus == ICE_BONUS) {
872     if(bullets.size() > MAX_ICE_BULLETS-1)
873       return false;
874     new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
875   } else {
876     return false;
877   }
878   add_object(new_bullet);
879
880   sound_manager->play("sounds/shoot.wav");
881
882   return true;
883 }
884
885 bool
886 Sector::add_smoke_cloud(const Vector& pos)
887 {
888   add_object(new SmokeCloud(pos));
889   return true;
890 }
891
892 void
893 Sector::add_floating_text(const Vector& pos, const std::string& text)
894 {
895   add_object(new FloatingText(pos, text));
896 }
897
898 void
899 Sector::play_music(MusicType type)
900 {
901   currentmusic = type;
902   switch(currentmusic) {
903     case LEVEL_MUSIC:
904       sound_manager->play_music(std::string("music/") + song_title);
905       break;
906     case HERRING_MUSIC:
907       sound_manager->play_music("music/salcon.ogg");
908       break;
909     default:
910       sound_manager->play_music("");
911       break;
912   }
913 }
914
915 MusicType
916 Sector::get_music_type()
917 {
918   return currentmusic;
919 }
920
921 int
922 Sector::get_total_badguys()
923 {
924   int total_badguys = 0;
925   for(GameObjects::iterator i = gameobjects.begin();
926       i != gameobjects.end(); ++i) {
927     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
928     if (badguy && badguy->countMe)
929       total_badguys++;
930   }
931
932   return total_badguys;
933 }
934
935 bool
936 Sector::inside(const Rect& rect) const
937 {
938   if(rect.p1.x > solids->get_width() * 32 
939       || rect.p1.y > solids->get_height() * 32
940       || rect.p2.x < 0 || rect.p2.y < 0)
941     return false;
942
943   return true;
944 }