Unified Messaging Subsystem
[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 #include "msg.hpp"
67
68 Sector* Sector::_current = 0;
69
70 Sector::Sector()
71   : gravity(10), player(0), solids(0), camera(0),
72     currentmusic(LEVEL_MUSIC)
73 {
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     msg_warning(e.what() << "");
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(music);
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     msg_warning("sector '" << name << "' does not contain a camera.");
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(
219             std::string("images/background/") + backgroundimage, bgspeed);
220     add_object(background);
221   } else {
222     Background* background = new Background;
223     background->set_gradient(bkgd_top, bkgd_bottom);
224     add_object(background);
225   }
226
227   std::string particlesystem;
228   reader.get("particle_system", particlesystem);
229   if(particlesystem == "clouds")
230     add_object(new CloudParticleSystem());
231   else if(particlesystem == "snow")
232     add_object(new SnowParticleSystem());
233   else if(particlesystem == "rain")
234     add_object(new RainParticleSystem());
235
236   Vector startpos(100, 170);
237   reader.get("start_pos_x", startpos.x);
238   reader.get("start_pos_y", startpos.y);
239
240   SpawnPoint* spawn = new SpawnPoint;
241   spawn->pos = startpos;
242   spawn->name = "main";
243   spawnpoints.push_back(spawn);
244
245   music = "chipdisko.ogg";
246   reader.get("music", music);
247   music = "music/" + music;
248
249   int width = 30, height = 15;
250   reader.get("width", width);
251   reader.get("height", height);
252   
253   std::vector<unsigned int> tiles;
254   if(reader.get_vector("interactive-tm", tiles)
255       || reader.get_vector("tilemap", tiles)) {
256     TileMap* tilemap = new TileMap();
257     tilemap->set(width, height, tiles, LAYER_TILES, true);
258     add_object(tilemap);
259   }
260
261   if(reader.get_vector("background-tm", tiles)) {
262     TileMap* tilemap = new TileMap();
263     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
264     add_object(tilemap);
265   }
266
267   if(reader.get_vector("foreground-tm", tiles)) {
268     TileMap* tilemap = new TileMap();
269     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
270     add_object(tilemap);
271   }
272
273   // read reset-points (now spawn-points)
274   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
275   if(resetpoints) {
276     lisp::ListIterator iter(resetpoints);
277     while(iter.next()) {
278       if(iter.item() == "point") {
279         Vector sp_pos;
280         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
281           {
282           SpawnPoint* sp = new SpawnPoint;
283           sp->name = "main";
284           sp->pos = sp_pos;
285           spawnpoints.push_back(sp);
286           }
287       } else {
288         msg_warning("Unknown token '" << iter.item() << "' in reset-points.");
289       }
290     }
291   }
292
293   // read objects
294   const lisp::Lisp* objects = reader.get_lisp("objects");
295   if(objects) {
296     lisp::ListIterator iter(objects);
297     while(iter.next()) {
298       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
299       if(object) {
300         add_object(object);
301       } else {
302         msg_warning("Unknown object '" << iter.item() << "' in level.");
303       }
304     }
305   }
306
307   // add a camera
308   Camera* camera = new Camera(this);
309   add_object(camera);
310
311   update_game_objects();
312
313   if(solids == 0)
314     throw std::runtime_error("sector does not contain a solid tile layer.");
315
316   fix_old_tiles();
317   update_game_objects();
318 }
319
320 void
321 Sector::fix_old_tiles()
322 {
323   // hack for now...
324   for(size_t x=0; x < solids->get_width(); ++x) {
325     for(size_t y=0; y < solids->get_height(); ++y) {
326       const Tile* tile = solids->get_tile(x, y);
327       Vector pos(x*32, y*32);
328       
329       if(tile->getID() == 112) {
330         add_object(new InvisibleBlock(pos));
331         solids->change(x, y, 0);
332       } else if(tile->getAttributes() & Tile::COIN) {
333         add_object(new Coin(pos));
334         solids->change(x, y, 0);
335       } else if(tile->getAttributes() & Tile::FULLBOX) {
336         add_object(new BonusBlock(pos, tile->getData()));
337         solids->change(x, y, 0);
338       } else if(tile->getAttributes() & Tile::BRICK) {
339         add_object(new Brick(pos, tile->getData()));
340         solids->change(x, y, 0);
341       } else if(tile->getAttributes() & Tile::GOAL) {
342         std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
343         add_object(new SequenceTrigger(pos, sequence));
344         solids->change(x, y, 0);
345       }
346     }
347   }
348 }
349
350 void
351 Sector::write(lisp::Writer& writer)
352 {
353   writer.write_string("name", name);
354   writer.write_float("gravity", gravity);
355   writer.write_string("music", music);
356
357   // write spawnpoints
358   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
359       ++i) {
360     SpawnPoint* spawn = *i;
361     writer.start_list("spawn-points");
362     writer.write_string("name", spawn->name);
363     writer.write_float("x", spawn->pos.x);
364     writer.write_float("y", spawn->pos.y);
365     writer.end_list("spawn-points");
366   }
367
368   // write objects
369   for(GameObjects::iterator i = gameobjects.begin();
370       i != gameobjects.end(); ++i) {
371     Serializable* serializable = dynamic_cast<Serializable*> (*i);
372     if(serializable)
373       serializable->write(writer);
374   }
375 }
376
377 void
378 Sector::add_object(GameObject* object)
379 {
380   // make sure the object isn't already in the list
381 #ifdef DEBUG
382   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
383       ++i) {
384     if(*i == object) {
385       assert("object already added to sector" == 0);
386     }
387   }
388   for(GameObjects::iterator i = gameobjects_new.begin();
389       i != gameobjects_new.end(); ++i) {
390     if(*i == object) {
391       assert("object already added to sector" == 0);
392     }
393   }
394 #endif
395
396   gameobjects_new.push_back(object);
397 }
398
399 void
400 Sector::activate(const std::string& spawnpoint)
401 {
402   SpawnPoint* sp = 0;
403   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
404       ++i) {
405     if((*i)->name == spawnpoint) {
406       sp = *i;
407       break;
408     }
409   }                                                                           
410   if(!sp) {
411     msg_warning("Spawnpoint '" << spawnpoint << "' not found.");
412     if(spawnpoint != "main") {
413       activate("main");
414     } else {
415       activate(Vector(0, 0));
416     }
417   } else {
418     activate(sp->pos);
419   }
420
421   // Run init script
422   if(init_script != "") {
423     ScriptInterpreter::add_script_object(this,
424         std::string("Sector(") + name + ") - init", init_script);
425   }
426 }
427
428 void
429 Sector::activate(const Vector& player_pos)
430 {
431   _current = this;
432
433   player->move(player_pos);
434   camera->reset(player->get_pos());
435 }
436
437 Rect
438 Sector::get_active_region()
439 {
440   return Rect(
441     camera->get_translation() - Vector(1600, 1200),
442     camera->get_translation() + Vector(1600, 1200));
443 }
444
445 void
446 Sector::update(float elapsed_time)
447 {
448   player->check_bounds(camera);
449
450 #if 0
451   CollisionGridIterator iter(*grid, get_active_region());
452   while(MovingObject* object = iter.next()) {
453     if(!object->is_valid())
454       continue;
455
456     object->update(elapsed_time);
457   }
458 #else
459   /* update objects */
460   for(GameObjects::iterator i = gameobjects.begin();
461           i != gameobjects.end(); ++i) {
462     GameObject* object = *i;
463     if(!object->is_valid())
464       continue;
465     
466     object->update(elapsed_time);
467   }
468 #endif
469   
470   /* Handle all possible collisions. */
471   handle_collisions();
472   update_game_objects();
473 }
474
475 void
476 Sector::update_game_objects()
477 {
478   /** cleanup marked objects */
479   for(std::vector<Bullet*>::iterator i = bullets.begin();
480       i != bullets.end(); /* nothing */) {
481     Bullet* bullet = *i;
482     if(bullet->is_valid()) {
483       ++i;
484       continue;
485     }
486
487     i = bullets.erase(i);
488   }
489   for(MovingObjects::iterator i = moving_objects.begin();
490       i != moving_objects.end(); /* nothing */) {
491     MovingObject* moving_object = *i;
492     if(moving_object->is_valid()) {
493       ++i;
494       continue;
495     }
496
497 #ifdef USE_GRID
498     grid->remove_object(moving_object);
499 #endif
500     
501     i = moving_objects.erase(i);
502   }
503   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
504       i != gameobjects.end(); /* nothing */) {
505     GameObject* object = *i;
506     
507     if(object->is_valid()) {
508       ++i;
509       continue;
510     }
511     
512     delete *i;
513     i = gameobjects.erase(i);
514   }
515
516   /* add newly created objects */
517   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
518       i != gameobjects_new.end(); ++i)
519   {
520     GameObject* object = *i;
521     
522     Bullet* bullet = dynamic_cast<Bullet*> (object);
523     if(bullet)
524       bullets.push_back(bullet);
525
526     MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
527     if(movingobject) {
528       moving_objects.push_back(movingobject);
529  #ifdef USE_GRID
530       grid->add_object(movingobject);
531 #endif
532     }
533     
534     TileMap* tilemap = dynamic_cast<TileMap*> (object);
535     if(tilemap && tilemap->is_solid()) {
536       if(solids == 0) {
537         solids = tilemap;
538       } else {
539         msg_warning("Another solid tilemaps added. Ignoring");
540       }
541     }
542
543     Camera* camera = dynamic_cast<Camera*> (object);
544     if(camera) {
545       if(this->camera != 0) {
546         msg_warning("Multiple cameras added. Ignoring");
547         continue;
548       }
549       this->camera = camera;
550     }
551
552     gameobjects.push_back(object);
553   }
554   gameobjects_new.clear();
555 }
556
557 void
558 Sector::draw(DrawingContext& context)
559 {
560   context.push_transform();
561   context.set_translation(camera->get_translation());
562
563   for(GameObjects::iterator i = gameobjects.begin();
564       i != gameobjects.end(); ++i) {
565     GameObject* object = *i; 
566     if(!object->is_valid())
567       continue;
568     
569     object->draw(context);
570   }
571
572   context.pop_transform();
573 }
574
575 static const float DELTA = .001;
576
577 void
578 Sector::collision_tilemap(MovingObject* object, CollisionHit& hit) const
579 {
580   // calculate rectangle where the object will move
581   float x1, x2;
582   if(object->get_movement().x >= 0) {
583     x1 = object->get_bbox().p1.x;
584     x2 = object->get_bbox().p2.x + object->get_movement().x;
585   } else {
586     x1 = object->get_bbox().p1.x + object->get_movement().x;
587     x2 = object->get_bbox().p2.x;
588   }
589   float y1, y2;
590   if(object->get_movement().y >= 0) {
591     y1 = object->get_bbox().p1.y;
592     y2 = object->get_bbox().p2.y + object->get_movement().y;
593   } else {
594     y1 = object->get_bbox().p1.y + object->get_movement().y;
595     y2 = object->get_bbox().p2.y;
596   }
597
598   // test with all tiles in this rectangle
599   int starttilex = int(x1) / 32;
600   int starttiley = int(y1) / 32;
601   int max_x = int(x2);
602   // the +1 is somehow needed to make characters stay on the floor
603   int max_y = int(y2+1);
604
605   CollisionHit temphit;
606   Rect dest = object->get_bbox();
607   dest.move(object->movement);
608   for(int x = starttilex; x*32 < max_x; ++x) {
609     for(int y = starttiley; y*32 < max_y; ++y) {
610       const Tile* tile = solids->get_tile(x, y);
611       if(!tile)
612         continue;
613       // skip non-solid tiles
614       if(tile->getAttributes() == 0)
615         continue;
616       // only handle unisolid when the player is falling down and when he was
617       // above the tile before
618       if(tile->getAttributes() & Tile::UNISOLID) {
619         if(object->movement.y < 0 || object->get_bbox().p2.y > y*32)
620           continue;
621       }
622
623       if(tile->getAttributes() & Tile::SLOPE) { // slope tile
624         AATriangle triangle;
625         Vector p1(x*32, y*32);
626         Vector p2((x+1)*32, (y+1)*32);
627         triangle = AATriangle(p1, p2, tile->getData());
628
629         if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
630               triangle)) {
631           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
632             hit = temphit;
633           }
634         }
635       } else { // normal rectangular tile
636         Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
637         if(Collision::rectangle_rectangle(temphit, dest,
638               object->movement, rect)) {
639           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
640             hit = temphit;
641           }
642         }
643       }
644     }
645   }
646 }
647
648 uint32_t
649 Sector::collision_tile_attributes(MovingObject* object) const
650 {
651   /** XXX This function doesn't work correctly as it will check all tiles
652    * in the bounding box of the object movement, this might include tiles
653    * that have actually never been touched by the object
654    * (though this only occures for very fast objects...)
655    */
656   
657   // calculate rectangle where the object will move
658   float x1, x2;
659   if(object->get_movement().x >= 0) {
660     x1 = object->get_bbox().p1.x;
661     x2 = object->get_bbox().p2.x + object->get_movement().x;
662   } else {
663     x1 = object->get_bbox().p1.x + object->get_movement().x;
664     x2 = object->get_bbox().p2.x;
665   }
666   float y1, y2;
667   if(object->get_movement().y >= 0) {
668     y1 = object->get_bbox().p1.y;
669     y2 = object->get_bbox().p2.y + object->get_movement().y;
670   } else {
671     y1 = object->get_bbox().p1.y + object->get_movement().y;
672     y2 = object->get_bbox().p2.y;
673   }
674
675   // test with all tiles in this rectangle
676   int starttilex = int(x1-1) / 32;
677   int starttiley = int(y1-1) / 32;
678   int max_x = int(x2+1);
679   int max_y = int(y2+1);
680
681   uint32_t result = 0;
682   for(int x = starttilex; x*32 < max_x; ++x) {
683     for(int y = starttiley; y*32 < max_y; ++y) {
684       const Tile* tile = solids->get_tile(x, y);
685       if(!tile)
686         continue;
687       result |= tile->getAttributes();
688     }
689   }
690
691   return result;
692 }
693
694 void
695 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
696 {
697   CollisionHit hit;
698   Rect dest1 = object1->get_bbox();
699   dest1.move(object1->get_movement());
700   Rect dest2 = object2->get_bbox();
701   dest2.move(object2->get_movement());
702
703   Vector movement = object1->get_movement() - object2->get_movement();
704   if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
705     HitResponse response1 = object1->collision(*object2, hit);
706     hit.normal *= -1;
707     HitResponse response2 = object2->collision(*object1, hit);
708
709     if(response1 != CONTINUE) {
710       if(response1 == ABORT_MOVE)
711         object1->movement = Vector(0, 0);
712       if(response2 == CONTINUE)
713         object2->movement += hit.normal * (hit.depth + DELTA);
714     } else if(response2 != CONTINUE) {
715       if(response2 == ABORT_MOVE)
716         object2->movement = Vector(0, 0);
717       if(response1 == CONTINUE)
718         object1->movement += -hit.normal * (hit.depth + DELTA);
719     } else {
720       object1->movement += -hit.normal * (hit.depth/2 + DELTA);
721       object2->movement += hit.normal * (hit.depth/2 + DELTA);
722     }
723   }
724 }
725
726 void
727 Sector::handle_collisions()
728 {
729   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
730   //   we do this up to 4 times and have to sort all results for the smallest
731   //   one before we can continue here
732   for(MovingObjects::iterator i = moving_objects.begin();
733       i != moving_objects.end(); ++i) {
734     MovingObject* moving_object = *i;
735     if((moving_object->get_group() != COLGROUP_MOVING
736           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
737         || !moving_object->is_valid())
738       continue;
739
740     // up to 4 tries
741     for(int t = 0; t < 4; ++t) {
742       CollisionHit hit;
743       hit.time = -1;
744       MovingObject* collided_with = NULL; 
745       
746       // collision with tilemap
747       collision_tilemap(moving_object, hit);
748     
749       // collision with other objects
750       Rect dest1 = moving_object->get_bbox();
751       dest1.move(moving_object->get_movement());
752       CollisionHit temphit;
753       
754       for(MovingObjects::iterator i2 = moving_objects.begin();
755           i2 != moving_objects.end(); ++i2) {
756         MovingObject* moving_object_2 = *i2;
757         if(moving_object_2->get_group() != COLGROUP_STATIC
758            || !moving_object_2->is_valid())
759           continue;
760         
761         Rect dest2 = moving_object_2->get_bbox();
762         dest2.move(moving_object_2->get_movement());
763         Vector movement 
764           = moving_object->get_movement() - moving_object_2->get_movement();
765         if(Collision::rectangle_rectangle(temphit, dest1, movement, dest2)
766             && temphit.time > hit.time) {
767           hit = temphit;
768           collided_with = moving_object_2;
769         }
770       }
771
772       if(hit.time < 0)
773         break;
774
775       // call collision callbacks
776       HitResponse response;
777       if(collided_with != 0) {
778         response = moving_object->collision(*collided_with, hit);
779         hit.normal *= -1;
780         collided_with->collision(*moving_object, hit);
781       } else {
782         response = moving_object->collision(*solids, hit);
783         hit.normal *= -1;
784       }
785    
786       if(response == CONTINUE) {
787         moving_object->movement += -hit.normal * (hit.depth + DELTA);
788       } else if(response == ABORT_MOVE) {
789         moving_object->movement = Vector(0, 0);
790         break;
791       } else { // force move
792         break;
793       }
794     }
795   }
796
797   // part2: COLGROUP_MOVING vs tile attributes
798   for(MovingObjects::iterator i = moving_objects.begin();
799       i != moving_objects.end(); ++i) {
800     MovingObject* moving_object = *i;
801     if((moving_object->get_group() != COLGROUP_MOVING
802           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
803         || !moving_object->is_valid())
804       continue;
805
806     uint32_t tile_attributes = collision_tile_attributes(moving_object);
807     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
808       moving_object->collision_tile(tile_attributes);
809     }
810   }
811
812   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
813   for(MovingObjects::iterator i = moving_objects.begin();
814       i != moving_objects.end(); ++i) {
815     MovingObject* moving_object = *i;
816     if(moving_object->get_group() != COLGROUP_MOVING
817         || !moving_object->is_valid())
818       continue;
819
820     for(MovingObjects::iterator i2 = moving_objects.begin();
821         i2 != moving_objects.end(); ++i2) {
822       MovingObject* moving_object_2 = *i2;
823       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
824          || !moving_object_2->is_valid())
825         continue;
826
827       collision_object(moving_object, moving_object_2);
828     } 
829   }
830
831   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
832   for(MovingObjects::iterator i = moving_objects.begin();
833       i != moving_objects.end(); ++i) {
834     MovingObject* moving_object = *i;
835
836     if(moving_object->get_group() != COLGROUP_MOVING
837         || !moving_object->is_valid())
838       continue;
839
840     for(MovingObjects::iterator i2 = i+1;
841         i2 != moving_objects.end(); ++i2) {
842       MovingObject* moving_object_2 = *i2;
843       if(moving_object_2->get_group() != COLGROUP_MOVING
844          || !moving_object_2->is_valid())
845         continue;
846
847       collision_object(moving_object, moving_object_2);
848     }    
849   }
850
851   // apply object movement
852   for(MovingObjects::iterator i = moving_objects.begin();
853       i != moving_objects.end(); ++i) {
854     MovingObject* moving_object = *i;
855
856     moving_object->bbox.move(moving_object->get_movement());
857     moving_object->movement = Vector(0, 0);
858   }
859 }
860
861 bool
862 Sector::is_free_space(const Rect& rect) const
863 {
864   // test with all tiles in this rectangle
865   int starttilex = int(rect.p1.x) / 32;
866   int starttiley = int(rect.p1.y) / 32;
867   int max_x = int(rect.p2.x);
868   int max_y = int(rect.p2.y);
869
870   for(int x = starttilex; x*32 < max_x; ++x) {
871     for(int y = starttiley; y*32 < max_y; ++y) {
872       const Tile* tile = solids->get_tile(x, y);
873       if(!tile)
874         continue;
875       if(tile->getAttributes() & Tile::SOLID)
876         return false;
877     }
878   }
879
880   for(MovingObjects::const_iterator i = moving_objects.begin();
881       i != moving_objects.end(); ++i) {
882     const MovingObject* moving_object = *i;
883     if(moving_object->get_group() != COLGROUP_STATIC
884         || !moving_object->is_valid())
885       continue;
886
887     if(Collision::intersects(rect, moving_object->get_bbox()))
888       return false;
889   }
890
891   return true;
892 }
893
894 bool
895 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
896 {
897   // TODO remove this function and move these checks elsewhere...
898   static const size_t MAX_FIRE_BULLETS = 2;
899   static const size_t MAX_ICE_BULLETS = 1;
900
901   Bullet* new_bullet = 0;
902   if(player_status->bonus == FIRE_BONUS) {
903     if(bullets.size() > MAX_FIRE_BULLETS-1)
904       return false;
905     new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
906   } else if(player_status->bonus == ICE_BONUS) {
907     if(bullets.size() > MAX_ICE_BULLETS-1)
908       return false;
909     new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
910   } else {
911     return false;
912   }
913   add_object(new_bullet);
914
915   sound_manager->play("sounds/shoot.wav");
916
917   return true;
918 }
919
920 bool
921 Sector::add_smoke_cloud(const Vector& pos)
922 {
923   add_object(new SmokeCloud(pos));
924   return true;
925 }
926
927 void
928 Sector::add_floating_text(const Vector& pos, const std::string& text)
929 {
930   add_object(new FloatingText(pos, text));
931 }
932
933 void
934 Sector::play_music(MusicType type)
935 {
936   currentmusic = type;
937   switch(currentmusic) {
938     case LEVEL_MUSIC:
939       sound_manager->play_music(music);
940       break;
941     case HERRING_MUSIC:
942       sound_manager->play_music("music/salcon.ogg");
943       break;
944     default:
945       sound_manager->play_music("");
946       break;
947   }
948 }
949
950 MusicType
951 Sector::get_music_type()
952 {
953   return currentmusic;
954 }
955
956 int
957 Sector::get_total_badguys()
958 {
959   int total_badguys = 0;
960   for(GameObjects::iterator i = gameobjects.begin();
961       i != gameobjects.end(); ++i) {
962     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
963     if (badguy && badguy->countMe)
964       total_badguys++;
965   }
966
967   return total_badguys;
968 }
969
970 bool
971 Sector::inside(const Rect& rect) const
972 {
973   if(rect.p1.x > solids->get_width() * 32 
974       || rect.p1.y > solids->get_height() * 32
975       || rect.p2.x < 0 || rect.p2.y < 0)
976     return false;
977
978   return true;
979 }