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