Merged changes from branches/supertux-milestone2-grumbel/ to trunk/supertux/
[supertux.git] / src / supertux / sector.cpp
1 //  SuperTux -  A Jump'n Run
2 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
3 //
4 //  This program is free software: you can redistribute it and/or modify
5 //  it under the terms of the GNU General Public License as published by
6 //  the Free Software Foundation, either version 3 of the License, or
7 //  (at your option) any later version.
8 //
9 //  This program is distributed in the hope that it will be useful,
10 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 //  GNU General Public License for more details.
13 //
14 //  You should have received a copy of the GNU General Public License
15 //  along with this program.  If not, see <http://www.gnu.org/licenses/>.
16
17 #include "supertux/sector.hpp"
18
19 #include <algorithm>
20 #include <math.h>
21
22 #include "audio/sound_manager.hpp"
23 #include "badguy/jumpy.hpp"
24 #include "lisp/list_iterator.hpp"
25 #include "math/aatriangle.hpp"
26 #include "object/background.hpp"
27 #include "object/bullet.hpp"
28 #include "object/camera.hpp"
29 #include "object/coin.hpp"
30 #include "object/display_effect.hpp"
31 #include "object/gradient.hpp"
32 #include "object/invisible_block.hpp"
33 #include "object/particlesystem.hpp"
34 #include "object/particlesystem_interactive.hpp"
35 #include "object/player.hpp"
36 #include "object/portable.hpp"
37 #include "object/pulsing_light.hpp"
38 #include "object/smoke_cloud.hpp"
39 #include "object/text_object.hpp"
40 #include "object/tilemap.hpp"
41 #include "physfs/physfs_stream.hpp"
42 #include "scripting/squirrel_util.hpp"
43 #include "supertux/collision.hpp"
44 #include "supertux/constants.hpp"
45 #include "supertux/level.hpp"
46 #include "supertux/main.hpp"
47 #include "supertux/object_factory.hpp"
48 #include "supertux/spawn_point.hpp"
49 #include "supertux/tile.hpp"
50 #include "trigger/sequence_trigger.hpp"
51 #include "util/file_system.hpp"
52
53 Sector* Sector::_current = 0;
54
55 bool Sector::show_collrects = false;
56 bool Sector::draw_solids_only = false;
57
58 Sector::Sector(Level* parent) :
59   level(parent), 
60   currentmusic(LEVEL_MUSIC),
61   ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), 
62   gravity(10.0), 
63   player(0), 
64   camera(0), 
65   effect(0)
66 {
67   add_object(new Player(player_status, "Tux"));
68   add_object(new DisplayEffect("Effect"));
69   add_object(new TextObject("Text"));
70
71   sound_manager->preload("sounds/shoot.wav");
72
73   // create a new squirrel table for the sector
74   using namespace Scripting;
75
76   sq_collectgarbage(global_vm);
77
78   sq_newtable(global_vm);
79   sq_pushroottable(global_vm);
80   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
81     throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
82
83   sq_resetobject(&sector_table);
84   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &sector_table)))
85     throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
86   sq_addref(global_vm, &sector_table);
87   sq_pop(global_vm, 1);
88 }
89
90 Sector::~Sector()
91 {
92   using namespace Scripting;
93
94   deactivate();
95
96   for(ScriptList::iterator i = scripts.begin();
97       i != scripts.end(); ++i) {
98     HSQOBJECT& object = *i;
99     sq_release(global_vm, &object);
100   }
101   sq_release(global_vm, &sector_table);
102   sq_collectgarbage(global_vm);
103
104   update_game_objects();
105   assert(gameobjects_new.size() == 0);
106
107   for(GameObjects::iterator i = gameobjects.begin();
108       i != gameobjects.end(); ++i) {
109     GameObject* object = *i;
110     before_object_remove(object);
111     object->unref();
112   }
113
114   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
115       ++i)
116     delete *i;
117 }
118
119 Level*
120 Sector::get_level()
121 {
122   return level;
123 }
124
125 GameObject*
126 Sector::parse_object(const std::string& name, const Reader& reader)
127 {
128   if(name == "camera") {
129     Camera* camera = new Camera(this, "Camera");
130     camera->parse(reader);
131     return camera;
132   } else if(name == "particles-snow") {
133     SnowParticleSystem* partsys = new SnowParticleSystem();
134     partsys->parse(reader);
135     return partsys;
136   } else if(name == "particles-rain") {
137     RainParticleSystem* partsys = new RainParticleSystem();
138     partsys->parse(reader);
139     return partsys;
140   } else if(name == "particles-comets") {
141     CometParticleSystem* partsys = new CometParticleSystem();
142     partsys->parse(reader);
143     return partsys;
144   } else if(name == "particles-ghosts") {
145     GhostParticleSystem* partsys = new GhostParticleSystem();
146     partsys->parse(reader);
147     return partsys;
148   } else if(name == "particles-clouds") {
149     CloudParticleSystem* partsys = new CloudParticleSystem();
150     partsys->parse(reader);
151     return partsys;
152   } else if(name == "money") { // for compatibility with old maps
153     return new Jumpy(reader);
154   }
155
156   try {
157     return create_object(name, reader);
158   } catch(std::exception& e) {
159     log_warning << e.what() << "" << std::endl;
160   }
161
162   return 0;
163 }
164
165 void
166 Sector::parse(const Reader& sector)
167 {
168   bool has_background = false;
169   lisp::ListIterator iter(&sector);
170   while(iter.next()) {
171     const std::string& token = iter.item();
172     if(token == "name") {
173       iter.value()->get(name);
174     } else if(token == "gravity") {
175       iter.value()->get(gravity);
176     } else if(token == "music") {
177       iter.value()->get(music);
178     } else if(token == "spawnpoint") {
179       SpawnPoint* sp = new SpawnPoint(iter.lisp());
180       spawnpoints.push_back(sp);
181     } else if(token == "init-script") {
182       iter.value()->get(init_script);
183     } else if(token == "ambient-light") {
184       std::vector<float> vColor;
185       sector.get( "ambient-light", vColor );
186       if(vColor.size() < 3) {
187         log_warning << "(ambient-light) requires a color as argument" << std::endl;
188       } else {
189         ambient_light = Color( vColor );
190       }
191     } else {
192       GameObject* object = parse_object(token, *(iter.lisp()));
193       if(object) {
194         if(dynamic_cast<Background *>(object)) {
195           has_background = true;
196         } else if(dynamic_cast<Gradient *>(object)) {
197           has_background = true;
198         }
199         add_object(object);
200       }
201     }
202   }
203
204   if(!has_background) {
205     Gradient* gradient = new Gradient();
206     gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
207     add_object(gradient);
208   }
209
210   update_game_objects();
211
212   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
213
214   fix_old_tiles();
215   if(!camera) {
216     log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
217     update_game_objects();
218     add_object(new Camera(this, "Camera"));
219   }
220
221   update_game_objects();
222 }
223
224 void
225 Sector::parse_old_format(const Reader& reader)
226 {
227   name = "main";
228   reader.get("gravity", gravity);
229
230   std::string backgroundimage;
231   if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
232     if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
233     if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
234     if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
235     backgroundimage = "images/background/" + backgroundimage;
236     if (!PHYSFS_exists(backgroundimage.c_str())) {
237       log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
238       backgroundimage = "";
239     }
240   }
241
242   float bgspeed = .5;
243   reader.get("bkgd_speed", bgspeed);
244   bgspeed /= 100;
245
246   Color bkgd_top, bkgd_bottom;
247   int r = 0, g = 0, b = 128;
248   reader.get("bkgd_red_top", r);
249   reader.get("bkgd_green_top",  g);
250   reader.get("bkgd_blue_top",  b);
251   bkgd_top.red = static_cast<float> (r) / 255.0f;
252   bkgd_top.green = static_cast<float> (g) / 255.0f;
253   bkgd_top.blue = static_cast<float> (b) / 255.0f;
254
255   reader.get("bkgd_red_bottom",  r);
256   reader.get("bkgd_green_bottom", g);
257   reader.get("bkgd_blue_bottom", b);
258   bkgd_bottom.red = static_cast<float> (r) / 255.0f;
259   bkgd_bottom.green = static_cast<float> (g) / 255.0f;
260   bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
261
262   if(backgroundimage != "") {
263     Background* background = new Background();
264     background->set_image(backgroundimage, bgspeed);
265     add_object(background);
266   } else {
267     Gradient* gradient = new Gradient();
268     gradient->set_gradient(bkgd_top, bkgd_bottom);
269     add_object(gradient);
270   }
271
272   std::string particlesystem;
273   reader.get("particle_system", particlesystem);
274   if(particlesystem == "clouds")
275     add_object(new CloudParticleSystem());
276   else if(particlesystem == "snow")
277     add_object(new SnowParticleSystem());
278   else if(particlesystem == "rain")
279     add_object(new RainParticleSystem());
280
281   Vector startpos(100, 170);
282   reader.get("start_pos_x", startpos.x);
283   reader.get("start_pos_y", startpos.y);
284
285   SpawnPoint* spawn = new SpawnPoint;
286   spawn->pos = startpos;
287   spawn->name = "main";
288   spawnpoints.push_back(spawn);
289
290   music = "chipdisko.ogg";
291   // skip reading music filename. It's all .ogg now, anyway
292   /*
293     reader.get("music", music);
294   */
295   music = "music/" + music;
296
297   int width = 30, height = 15;
298   reader.get("width", width);
299   reader.get("height", height);
300
301   std::vector<unsigned int> tiles;
302   if(reader.get("interactive-tm", tiles)
303      || reader.get("tilemap", tiles)) {
304     TileMap* tilemap = new TileMap(level->get_tileset());
305     tilemap->set(width, height, tiles, LAYER_TILES, true);
306
307     // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
308     for(size_t x=0; x < tilemap->get_width(); ++x) {
309       for(size_t y=0; y < tilemap->get_height(); ++y) {
310         uint32_t id = tilemap->get_tile_id(x, y);
311         if(id == 112)
312           tilemap->change(x, y, 1311);
313       }
314     }
315
316     if (height < 19) tilemap->resize(width, 19);
317     add_object(tilemap);
318   }
319
320   if(reader.get("background-tm", tiles)) {
321     TileMap* tilemap = new TileMap(level->get_tileset());
322     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
323     if (height < 19) tilemap->resize(width, 19);
324     add_object(tilemap);
325   }
326
327   if(reader.get("foreground-tm", tiles)) {
328     TileMap* tilemap = new TileMap(level->get_tileset());
329     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
330
331     // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
332     if (height < 19) tilemap->resize(width, 19, 2035);
333
334     add_object(tilemap);
335   }
336
337   // read reset-points (now spawn-points)
338   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
339   if(resetpoints) {
340     lisp::ListIterator iter(resetpoints);
341     while(iter.next()) {
342       if(iter.item() == "point") {
343         Vector sp_pos;
344         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
345         {
346           SpawnPoint* sp = new SpawnPoint;
347           sp->name = "main";
348           sp->pos = sp_pos;
349           spawnpoints.push_back(sp);
350         }
351       } else {
352         log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
353       }
354     }
355   }
356
357   // read objects
358   const lisp::Lisp* objects = reader.get_lisp("objects");
359   if(objects) {
360     lisp::ListIterator iter(objects);
361     while(iter.next()) {
362       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
363       if(object) {
364         add_object(object);
365       } else {
366         log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
367       }
368     }
369   }
370
371   // add a camera
372   Camera* camera = new Camera(this, "Camera");
373   add_object(camera);
374
375   update_game_objects();
376
377   if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
378
379   fix_old_tiles();
380   update_game_objects();
381 }
382
383 void
384 Sector::fix_old_tiles()
385 {
386   for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
387     TileMap* solids = *i;
388     for(size_t x=0; x < solids->get_width(); ++x) {
389       for(size_t y=0; y < solids->get_height(); ++y) {
390         uint32_t    id   = solids->get_tile_id(x, y);
391         const Tile *tile = solids->get_tile(x, y);
392         Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
393
394         if(id == 112) {
395           add_object(new InvisibleBlock(pos));
396           solids->change(x, y, 0);
397         } else if(tile->getAttributes() & Tile::COIN) {
398           add_object(new Coin(pos));
399           solids->change(x, y, 0);
400         } else if(tile->getAttributes() & Tile::FULLBOX) {
401           add_object(new BonusBlock(pos, tile->getData()));
402           solids->change(x, y, 0);
403         } else if(tile->getAttributes() & Tile::BRICK) {
404           add_object(new Brick(pos, tile->getData()));
405           solids->change(x, y, 0);
406         } else if(tile->getAttributes() & Tile::GOAL) {
407           std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
408           add_object(new SequenceTrigger(pos, sequence));
409           solids->change(x, y, 0);
410         }
411       }
412     }
413   }
414
415   // add lights for special tiles
416   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
417     TileMap* tm = dynamic_cast<TileMap*>(*i);
418     if (!tm) continue;
419     for(size_t x=0; x < tm->get_width(); ++x) {
420       for(size_t y=0; y < tm->get_height(); ++y) {
421         uint32_t id = tm->get_tile_id(x, y);
422         Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
423         Vector center(pos.x + 16, pos.y + 16);
424
425         // torch
426         if (id == 1517) {
427           float pseudo_rnd = (float)((int)pos.x % 10) / 10;
428           add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
429         }
430         // lava or lavaflow
431         if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
432           // space lights a bit
433           if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
434                && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
435               || ((x % 3 == 0) && (y % 3 == 0))) {
436             float pseudo_rnd = (float)((int)pos.x % 10) / 10;
437             add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
438           }
439         }
440
441       }
442     }
443   }
444
445 }
446
447 HSQUIRRELVM
448 Sector::run_script(std::istream& in, const std::string& sourcename)
449 {
450   using namespace Scripting;
451
452   // garbage collect thread list
453   for(ScriptList::iterator i = scripts.begin();
454       i != scripts.end(); ) {
455     HSQOBJECT& object = *i;
456     HSQUIRRELVM vm = object_to_vm(object);
457
458     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
459       sq_release(global_vm, &object);
460       i = scripts.erase(i);
461       continue;
462     }
463
464     ++i;
465   }
466
467   HSQOBJECT object = create_thread(global_vm);
468   scripts.push_back(object);
469
470   HSQUIRRELVM vm = object_to_vm(object);
471
472   // set sector_table as roottable for the thread
473   sq_pushobject(vm, sector_table);
474   sq_setroottable(vm);
475
476   try {
477     compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
478   } catch(std::exception& e) {
479     log_warning << "Error running script: " << e.what() << std::endl;
480   }
481
482   return vm;
483 }
484
485 void
486 Sector::add_object(GameObject* object)
487 {
488   // make sure the object isn't already in the list
489 #ifdef DEBUG
490   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
491       ++i) {
492     if(*i == object) {
493       assert("object already added to sector" == 0);
494     }
495   }
496   for(GameObjects::iterator i = gameobjects_new.begin();
497       i != gameobjects_new.end(); ++i) {
498     if(*i == object) {
499       assert("object already added to sector" == 0);
500     }
501   }
502 #endif
503
504   object->ref();
505   gameobjects_new.push_back(object);
506 }
507
508 void
509 Sector::activate(const std::string& spawnpoint)
510 {
511   SpawnPoint* sp = 0;
512   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
513       ++i) {
514     if((*i)->name == spawnpoint) {
515       sp = *i;
516       break;
517     }
518   }
519   if(!sp) {
520     log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
521     if(spawnpoint != "main") {
522       activate("main");
523     } else {
524       activate(Vector(0, 0));
525     }
526   } else {
527     activate(sp->pos);
528   }
529 }
530
531 void
532 Sector::activate(const Vector& player_pos)
533 {
534   if(_current != this) {
535     if(_current != NULL)
536       _current->deactivate();
537     _current = this;
538
539     // register sectortable as sector in scripting
540     HSQUIRRELVM vm = Scripting::global_vm;
541     sq_pushroottable(vm);
542     sq_pushstring(vm, "sector", -1);
543     sq_pushobject(vm, sector_table);
544     if(SQ_FAILED(sq_createslot(vm, -3)))
545       throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
546     sq_pop(vm, 1);
547
548     for(GameObjects::iterator i = gameobjects.begin();
549         i != gameobjects.end(); ++i) {
550       GameObject* object = *i;
551
552       try_expose(object);
553     }
554   }
555   try_expose_me();
556
557   // spawn smalltux below spawnpoint
558   if (!player->is_big()) {
559     player->move(player_pos + Vector(0,32));
560   } else {
561     player->move(player_pos);
562   }
563
564   // spawning tux in the ground would kill him
565   if(!is_free_of_tiles(player->get_bbox())) {
566     log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
567     Vector npos = player->get_bbox().p1;
568     npos.y-=32;
569     player->move(npos);
570   }
571
572   camera->reset(player->get_pos());
573   update_game_objects();
574
575   //Run default.nut just before init script
576   //Check to see if it's in a levelset (info file)
577   std::string basedir = FileSystem::dirname(get_level()->filename);
578   if(PHYSFS_exists((basedir + "/info").c_str())) {
579     try {
580       IFileStream in(basedir + "/default.nut");
581       run_script(in, "default.nut");
582     } catch(std::exception& ) {
583       // doesn't exist or erroneous; do nothing
584     }
585   }
586
587   // Run init script
588   if(init_script != "") {
589     std::istringstream in(init_script);
590     run_script(in, "init-script");
591   }
592 }
593
594 void
595 Sector::deactivate()
596 {
597   if(_current != this)
598     return;
599
600   // remove sector entry from global vm
601   HSQUIRRELVM vm = Scripting::global_vm;
602   sq_pushroottable(vm);
603   sq_pushstring(vm, "sector", -1);
604   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
605     throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
606   sq_pop(vm, 1);
607
608   for(GameObjects::iterator i = gameobjects.begin();
609       i != gameobjects.end(); ++i) {
610     GameObject* object = *i;
611
612     try_unexpose(object);
613   }
614
615   try_unexpose_me();
616   _current = NULL;
617 }
618
619 Rect
620 Sector::get_active_region()
621 {
622   return Rect(
623     camera->get_translation() - Vector(1600, 1200),
624     camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
625 }
626
627 void
628 Sector::update(float elapsed_time)
629 {
630   player->check_bounds(camera);
631
632   /* update objects */
633   for(GameObjects::iterator i = gameobjects.begin();
634       i != gameobjects.end(); ++i) {
635     GameObject* object = *i;
636     if(!object->is_valid())
637       continue;
638
639     object->update(elapsed_time);
640   }
641
642   /* Handle all possible collisions. */
643   handle_collisions();
644   update_game_objects();
645 }
646
647 void
648 Sector::update_game_objects()
649 {
650   /** cleanup marked objects */
651   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
652       i != gameobjects.end(); /* nothing */) {
653     GameObject* object = *i;
654
655     if(object->is_valid()) {
656       ++i;
657       continue;
658     }
659
660     before_object_remove(object);
661
662     object->unref();
663     i = gameobjects.erase(i);
664   }
665
666   /* add newly created objects */
667   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
668       i != gameobjects_new.end(); ++i)
669   {
670     GameObject* object = *i;
671
672     before_object_add(object);
673
674     gameobjects.push_back(object);
675   }
676   gameobjects_new.clear();
677
678   /* update solid_tilemaps list */
679   //FIXME: this could be more efficient
680   solid_tilemaps.clear();
681   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
682       i != gameobjects.end(); ++i)
683   {
684     TileMap* tm = dynamic_cast<TileMap*>(*i);
685     if (!tm) continue;
686     if (tm->is_solid()) solid_tilemaps.push_back(tm);
687   }
688
689 }
690
691 bool
692 Sector::before_object_add(GameObject* object)
693 {
694   Bullet* bullet = dynamic_cast<Bullet*> (object);
695   if(bullet != NULL) {
696     bullets.push_back(bullet);
697   }
698
699   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
700   if(movingobject != NULL) {
701     moving_objects.push_back(movingobject);
702   }
703
704   Portable* portable = dynamic_cast<Portable*> (object);
705   if(portable != NULL) {
706     portables.push_back(portable);
707   }
708
709   TileMap* tilemap = dynamic_cast<TileMap*> (object);
710   if(tilemap != NULL && tilemap->is_solid()) {
711     solid_tilemaps.push_back(tilemap);
712   }
713
714   Camera* camera = dynamic_cast<Camera*> (object);
715   if(camera != NULL) {
716     if(this->camera != 0) {
717       log_warning << "Multiple cameras added. Ignoring" << std::endl;
718       return false;
719     }
720     this->camera = camera;
721   }
722
723   Player* player = dynamic_cast<Player*> (object);
724   if(player != NULL) {
725     if(this->player != 0) {
726       log_warning << "Multiple players added. Ignoring" << std::endl;
727       return false;
728     }
729     this->player = player;
730   }
731
732   DisplayEffect* effect = dynamic_cast<DisplayEffect*> (object);
733   if(effect != NULL) {
734     if(this->effect != 0) {
735       log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
736       return false;
737     }
738     this->effect = effect;
739   }
740
741   if(_current == this) {
742     try_expose(object);
743   }
744
745   return true;
746 }
747
748 void
749 Sector::try_expose(GameObject* object)
750 {
751   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
752   if(interface != NULL) {
753     HSQUIRRELVM vm = Scripting::global_vm;
754     sq_pushobject(vm, sector_table);
755     interface->expose(vm, -1);
756     sq_pop(vm, 1);
757   }
758 }
759
760 void
761 Sector::try_expose_me()
762 {
763   HSQUIRRELVM vm = Scripting::global_vm;
764   sq_pushobject(vm, sector_table);
765   Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
766   expose_object(vm, -1, interface, "settings", false);
767   sq_pop(vm, 1);
768 }
769
770 void
771 Sector::before_object_remove(GameObject* object)
772 {
773   Portable* portable = dynamic_cast<Portable*> (object);
774   if(portable != NULL) {
775     portables.erase(std::find(portables.begin(), portables.end(), portable));
776   }
777   Bullet* bullet = dynamic_cast<Bullet*> (object);
778   if(bullet != NULL) {
779     bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
780   }
781   MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
782   if(moving_object != NULL) {
783     moving_objects.erase(
784       std::find(moving_objects.begin(), moving_objects.end(), moving_object));
785   }
786
787   if(_current == this)
788     try_unexpose(object);
789 }
790
791 void
792 Sector::try_unexpose(GameObject* object)
793 {
794   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
795   if(interface != NULL) {
796     HSQUIRRELVM vm = Scripting::global_vm;
797     SQInteger oldtop = sq_gettop(vm);
798     sq_pushobject(vm, sector_table);
799     try {
800       interface->unexpose(vm, -1);
801     } catch(std::exception& e) {
802       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
803     }
804     sq_settop(vm, oldtop);
805   }
806 }
807
808 void
809 Sector::try_unexpose_me()
810 {
811   HSQUIRRELVM vm = Scripting::global_vm;
812   SQInteger oldtop = sq_gettop(vm);
813   sq_pushobject(vm, sector_table);
814   try {
815     Scripting::unexpose_object(vm, -1, "settings");
816   } catch(std::exception& e) {
817     log_warning << "Couldn't unregister object: " << e.what() << std::endl;
818   }
819   sq_settop(vm, oldtop);
820 }
821 void
822 Sector::draw(DrawingContext& context)
823 {
824   context.set_ambient_color( ambient_light );
825   context.push_transform();
826   context.set_translation(camera->get_translation());
827
828   for(GameObjects::iterator i = gameobjects.begin();
829       i != gameobjects.end(); ++i) {
830     GameObject* object = *i;
831     if(!object->is_valid())
832       continue;
833
834     if (draw_solids_only)
835     {
836       TileMap* tm = dynamic_cast<TileMap*>(object);
837       if (tm && !tm->is_solid())
838         continue;
839     }
840
841     object->draw(context);
842   }
843
844   if(show_collrects) {
845     Color col(0.2f, 0.2f, 0.2f, 0.7f);
846     for(MovingObjects::iterator i = moving_objects.begin();
847         i != moving_objects.end(); ++i) {
848       MovingObject* object = *i;
849       const Rect& rect = object->get_bbox();
850
851       context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
852     }
853   }
854
855   context.pop_transform();
856 }
857
858 /*-------------------------------------------------------------------------
859  * Collision Detection
860  *-------------------------------------------------------------------------*/
861
862 /** r1 is supposed to be moving, r2 a solid object */
863 void check_collisions(collision::Constraints* constraints,
864                       const Vector& movement, const Rect& r1, const Rect& r2,
865                       GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
866 {
867   if(!collision::intersects(r1, r2))
868     return;
869
870   MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
871   CollisionHit dummy;
872   if(other != NULL && !other->collides(*object, dummy))
873     return;
874   if(moving_object != NULL && !moving_object->collides(*other, dummy))
875     return;
876
877   // calculate intersection
878   float itop    = r1.get_bottom() - r2.get_top();
879   float ibottom = r2.get_bottom() - r1.get_top();
880   float ileft   = r1.get_right() - r2.get_left();
881   float iright  = r2.get_right() - r1.get_left();
882
883   if(fabsf(movement.y) > fabsf(movement.x)) {
884     if(ileft < SHIFT_DELTA) {
885       constraints->right = std::min(constraints->right, r2.get_left());
886       return;
887     } else if(iright < SHIFT_DELTA) {
888       constraints->left = std::max(constraints->left, r2.get_right());
889       return;
890     }
891   } else {
892     // shiftout bottom/top
893     if(itop < SHIFT_DELTA) {
894       constraints->bottom = std::min(constraints->bottom, r2.get_top());
895       return;
896     } else if(ibottom < SHIFT_DELTA) {
897       constraints->top = std::max(constraints->top, r2.get_bottom());
898       return;
899     }
900   }
901
902   constraints->ground_movement += addl_ground_movement;
903   if(other != NULL) {
904     HitResponse response = other->collision(*object, dummy);
905     if(response == PASSTHROUGH)
906       return;
907
908     if(other->get_movement() != Vector(0, 0)) {
909       // TODO what todo when we collide with 2 moving objects?!?
910       constraints->ground_movement = other->get_movement();
911     }
912   }
913
914   float vert_penetration = std::min(itop, ibottom);
915   float horiz_penetration = std::min(ileft, iright);
916   if(vert_penetration < horiz_penetration) {
917     if(itop < ibottom) {
918       constraints->bottom = std::min(constraints->bottom, r2.get_top());
919       constraints->hit.bottom = true;
920     } else {
921       constraints->top = std::max(constraints->top, r2.get_bottom());
922       constraints->hit.top = true;
923     }
924   } else {
925     if(ileft < iright) {
926       constraints->right = std::min(constraints->right, r2.get_left());
927       constraints->hit.right = true;
928     } else {
929       constraints->left = std::max(constraints->left, r2.get_right());
930       constraints->hit.left = true;
931     }
932   }
933 }
934
935 void
936 Sector::collision_tilemap(collision::Constraints* constraints,
937                           const Vector& movement, const Rect& dest) const
938 {
939   // calculate rectangle where the object will move
940   float x1 = dest.get_left();
941   float x2 = dest.get_right();
942   float y1 = dest.get_top();
943   float y2 = dest.get_bottom();
944
945   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
946     TileMap* solids = *i;
947
948     // test with all tiles in this rectangle
949     int starttilex = int(x1 - solids->get_x_offset()) / 32;
950     int starttiley = int(y1 - solids->get_y_offset()) / 32;
951     int max_x = int(x2 - solids->get_x_offset());
952     int max_y = int(y2+1 - solids->get_y_offset());
953
954     for(int x = starttilex; x*32 < max_x; ++x) {
955       for(int y = starttiley; y*32 < max_y; ++y) {
956         const Tile* tile = solids->get_tile(x, y);
957         if(!tile)
958           continue;
959         // skip non-solid tiles
960         if((tile->getAttributes() & Tile::SOLID) == 0)
961           continue;
962         // only handle unisolid when the player is falling down and when he was
963         // above the tile before
964         if(tile->getAttributes() & Tile::UNISOLID) {
965           if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
966             continue;
967         }
968
969         if(tile->getAttributes() & Tile::SLOPE) { // slope tile
970           AATriangle triangle;
971           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
972           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
973           triangle = AATriangle(p1, p2, tile->getData());
974
975           collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
976         } else { // normal rectangular tile
977           Rect rect(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset(), (x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
978           check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
979         }
980       }
981     }
982   }
983 }
984
985 uint32_t
986 Sector::collision_tile_attributes(const Rect& dest) const
987 {
988   float x1 = dest.p1.x;
989   float y1 = dest.p1.y;
990   float x2 = dest.p2.x;
991   float y2 = dest.p2.y + SHIFT_DELTA;
992
993   uint32_t result = 0;
994   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
995     TileMap* solids = *i;
996
997     // test with all tiles in this rectangle
998     int starttilex = int(x1 - solids->get_x_offset()) / 32;
999     int starttiley = int(y1 - solids->get_y_offset()) / 32;
1000     int max_x = int(x2 - solids->get_x_offset());
1001     int max_y = int(y2+1 - solids->get_y_offset());
1002
1003     for(int x = starttilex; x*32 < max_x; ++x) {
1004       for(int y = starttiley; y*32 < max_y; ++y) {
1005         const Tile* tile = solids->get_tile(x, y);
1006         if(!tile)
1007           continue;
1008         result |= tile->getAttributes();
1009       }
1010     }
1011   }
1012
1013   return result;
1014 }
1015
1016 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1017 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1018                            Vector& normal)
1019 {
1020   float itop = r1.get_bottom() - r2.get_top();
1021   float ibottom = r2.get_bottom() - r1.get_top();
1022   float ileft = r1.get_right() - r2.get_left();
1023   float iright = r2.get_right() - r1.get_left();
1024
1025   float vert_penetration = std::min(itop, ibottom);
1026   float horiz_penetration = std::min(ileft, iright);
1027   if(vert_penetration < horiz_penetration) {
1028     if(itop < ibottom) {
1029       hit.bottom = true;
1030       normal.y = vert_penetration;
1031     } else {
1032       hit.top = true;
1033       normal.y = -vert_penetration;
1034     }
1035   } else {
1036     if(ileft < iright) {
1037       hit.right = true;
1038       normal.x = horiz_penetration;
1039     } else {
1040       hit.left = true;
1041       normal.x = -horiz_penetration;
1042     }
1043   }
1044 }
1045
1046 void
1047 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1048 {
1049   using namespace collision;
1050
1051   const Rect& r1 = object1->dest;
1052   const Rect& r2 = object2->dest;
1053
1054   CollisionHit hit;
1055   if(intersects(object1->dest, object2->dest)) {
1056     Vector normal;
1057     get_hit_normal(r1, r2, hit, normal);
1058
1059     if(!object1->collides(*object2, hit))
1060       return;
1061     std::swap(hit.left, hit.right);
1062     std::swap(hit.top, hit.bottom);
1063     if(!object2->collides(*object1, hit))
1064       return;
1065     std::swap(hit.left, hit.right);
1066     std::swap(hit.top, hit.bottom);
1067
1068     HitResponse response1 = object1->collision(*object2, hit);
1069     std::swap(hit.left, hit.right);
1070     std::swap(hit.top, hit.bottom);
1071     HitResponse response2 = object2->collision(*object1, hit);
1072     if(response1 == CONTINUE && response2 == CONTINUE) {
1073       normal *= (0.5 + DELTA);
1074       object1->dest.move(-normal);
1075       object2->dest.move(normal);
1076     } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1077       normal *= (1 + DELTA);
1078       object1->dest.move(-normal);
1079     } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1080       normal *= (1 + DELTA);
1081       object2->dest.move(normal);
1082     }
1083   }
1084 }
1085
1086 void
1087 Sector::collision_static(collision::Constraints* constraints,
1088                          const Vector& movement, const Rect& dest,
1089                          GameObject& object)
1090 {
1091   collision_tilemap(constraints, movement, dest);
1092
1093   // collision with other (static) objects
1094   for(MovingObjects::iterator i = moving_objects.begin();
1095       i != moving_objects.end(); ++i) {
1096     MovingObject* moving_object = *i;
1097     if(moving_object->get_group() != COLGROUP_STATIC
1098        && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1099       continue;
1100     if(!moving_object->is_valid())
1101       continue;
1102
1103     if(moving_object != &object)
1104       check_collisions(constraints, movement, dest, moving_object->bbox,
1105                        &object, moving_object);
1106   }
1107 }
1108
1109 void
1110 Sector::collision_static_constrains(MovingObject& object)
1111 {
1112   using namespace collision;
1113   float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1114
1115   Constraints constraints;
1116   Vector movement = object.get_movement();
1117   Rect& dest = object.dest;
1118   float owidth = object.get_bbox().get_width();
1119   float oheight = object.get_bbox().get_height();
1120
1121   for(int i = 0; i < 2; ++i) {
1122     collision_static(&constraints, Vector(0, movement.y), dest, object);
1123     if(!constraints.has_constraints())
1124       break;
1125
1126     // apply calculated horizontal constraints
1127     if(constraints.bottom < infinity) {
1128       float height = constraints.bottom - constraints.top;
1129       if(height < oheight) {
1130         // we're crushed, but ignore this for now, we'll get this again
1131         // later if we're really crushed or things will solve itself when
1132         // looking at the vertical constraints
1133       }
1134       dest.p2.y = constraints.bottom - DELTA;
1135       dest.p1.y = dest.p2.y - oheight;
1136     } else if(constraints.top > -infinity) {
1137       dest.p1.y = constraints.top + DELTA;
1138       dest.p2.y = dest.p1.y + oheight;
1139     }
1140   }
1141   if(constraints.has_constraints()) {
1142     if(constraints.hit.bottom) {
1143       dest.move(constraints.ground_movement);
1144     }
1145     if(constraints.hit.top || constraints.hit.bottom) {
1146       constraints.hit.left = false;
1147       constraints.hit.right = false;
1148       object.collision_solid(constraints.hit);
1149     }
1150   }
1151
1152   constraints = Constraints();
1153   for(int i = 0; i < 2; ++i) {
1154     collision_static(&constraints, movement, dest, object);
1155     if(!constraints.has_constraints())
1156       break;
1157
1158     // apply calculated vertical constraints
1159     if(constraints.right < infinity) {
1160       float width = constraints.right - constraints.left;
1161       if(width + SHIFT_DELTA < owidth) {
1162 #if 0
1163         printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1164                constraints.left, constraints.right);
1165 #endif
1166         CollisionHit h;
1167         h.left = true;
1168         h.right = true;
1169         h.crush = true;
1170         object.collision_solid(h);
1171       } else {
1172         dest.p2.x = constraints.right - DELTA;
1173         dest.p1.x = dest.p2.x - owidth;
1174       }
1175     } else if(constraints.left > -infinity) {
1176       dest.p1.x = constraints.left + DELTA;
1177       dest.p2.x = dest.p1.x + owidth;
1178     }
1179   }
1180
1181   if(constraints.has_constraints()) {
1182     if( constraints.hit.left || constraints.hit.right
1183         || constraints.hit.top || constraints.hit.bottom
1184         || constraints.hit.crush )
1185       object.collision_solid(constraints.hit);
1186   }
1187
1188   // an extra pass to make sure we're not crushed horizontally
1189   constraints = Constraints();
1190   collision_static(&constraints, movement, dest, object);
1191   if(constraints.bottom < infinity) {
1192     float height = constraints.bottom - constraints.top;
1193     if(height + SHIFT_DELTA < oheight) {
1194 #if 0
1195       printf("Object %p crushed vertically...\n", &object);
1196 #endif
1197       CollisionHit h;
1198       h.top = true;
1199       h.bottom = true;
1200       h.crush = true;
1201       object.collision_solid(h);
1202     }
1203   }
1204 }
1205
1206 namespace {
1207 const float MAX_SPEED = 16.0f;
1208 }
1209
1210 void
1211 Sector::handle_collisions()
1212 {
1213   using namespace collision;
1214
1215   // calculate destination positions of the objects
1216   for(MovingObjects::iterator i = moving_objects.begin();
1217       i != moving_objects.end(); ++i) {
1218     MovingObject* moving_object = *i;
1219     Vector mov = moving_object->get_movement();
1220
1221     // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1222     if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1223       moving_object->movement = mov.unit() * MAX_SPEED;
1224       //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1225     }
1226
1227     moving_object->dest = moving_object->get_bbox();
1228     moving_object->dest.move(moving_object->get_movement());
1229   }
1230
1231   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1232   for(MovingObjects::iterator i = moving_objects.begin();
1233       i != moving_objects.end(); ++i) {
1234     MovingObject* moving_object = *i;
1235     if((moving_object->get_group() != COLGROUP_MOVING
1236         && moving_object->get_group() != COLGROUP_MOVING_STATIC
1237         && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1238        || !moving_object->is_valid())
1239       continue;
1240
1241     collision_static_constrains(*moving_object);
1242   }
1243
1244   // part2: COLGROUP_MOVING vs tile attributes
1245   for(MovingObjects::iterator i = moving_objects.begin();
1246       i != moving_objects.end(); ++i) {
1247     MovingObject* moving_object = *i;
1248     if((moving_object->get_group() != COLGROUP_MOVING
1249         && moving_object->get_group() != COLGROUP_MOVING_STATIC
1250         && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1251        || !moving_object->is_valid())
1252       continue;
1253
1254     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1255     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1256       moving_object->collision_tile(tile_attributes);
1257     }
1258   }
1259
1260   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1261   for(MovingObjects::iterator i = moving_objects.begin();
1262       i != moving_objects.end(); ++i) {
1263     MovingObject* moving_object = *i;
1264     if((moving_object->get_group() != COLGROUP_MOVING
1265         && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1266        || !moving_object->is_valid())
1267       continue;
1268
1269     for(MovingObjects::iterator i2 = moving_objects.begin();
1270         i2 != moving_objects.end(); ++i2) {
1271       MovingObject* moving_object_2 = *i2;
1272       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1273          || !moving_object_2->is_valid())
1274         continue;
1275
1276       if(intersects(moving_object->dest, moving_object_2->dest)) {
1277         Vector normal;
1278         CollisionHit hit;
1279         get_hit_normal(moving_object->dest, moving_object_2->dest,
1280                        hit, normal);
1281         if(!moving_object->collides(*moving_object_2, hit))
1282           continue;
1283         if(!moving_object_2->collides(*moving_object, hit))
1284           continue;
1285
1286         moving_object->collision(*moving_object_2, hit);
1287         moving_object_2->collision(*moving_object, hit);
1288       }
1289     }
1290   }
1291
1292   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1293   for(MovingObjects::iterator i = moving_objects.begin();
1294       i != moving_objects.end(); ++i) {
1295     MovingObject* moving_object = *i;
1296
1297     if((moving_object->get_group() != COLGROUP_MOVING
1298         && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1299        || !moving_object->is_valid())
1300       continue;
1301
1302     for(MovingObjects::iterator i2 = i+1;
1303         i2 != moving_objects.end(); ++i2) {
1304       MovingObject* moving_object_2 = *i2;
1305       if((moving_object_2->get_group() != COLGROUP_MOVING
1306           && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1307          || !moving_object_2->is_valid())
1308         continue;
1309
1310       collision_object(moving_object, moving_object_2);
1311     }
1312   }
1313
1314   // apply object movement
1315   for(MovingObjects::iterator i = moving_objects.begin();
1316       i != moving_objects.end(); ++i) {
1317     MovingObject* moving_object = *i;
1318
1319     moving_object->bbox = moving_object->dest;
1320     moving_object->movement = Vector(0, 0);
1321   }
1322 }
1323
1324 bool
1325 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1326 {
1327   using namespace collision;
1328
1329   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1330     TileMap* solids = *i;
1331
1332     // test with all tiles in this rectangle
1333     int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1334     int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1335     int max_x = int(rect.p2.x - solids->get_x_offset());
1336     int max_y = int(rect.p2.y - solids->get_y_offset());
1337
1338     for(int x = starttilex; x*32 <= max_x; ++x) {
1339       for(int y = starttiley; y*32 <= max_y; ++y) {
1340         const Tile* tile = solids->get_tile(x, y);
1341         if(!tile) continue;
1342         if(tile->getAttributes() & Tile::SLOPE) {
1343           AATriangle triangle;
1344           Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1345           Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1346           triangle = AATriangle(p1, p2, tile->getData());
1347           Constraints constraints;
1348           if(collision::rectangle_aatriangle(&constraints, rect, triangle) && (!ignoreUnisolid || !(tile->getAttributes() & Tile::UNISOLID))) return false;
1349         }
1350         if((tile->getAttributes() & Tile::SOLID) && (!ignoreUnisolid || !(tile->getAttributes() & Tile::UNISOLID))) return false;
1351       }
1352     }
1353   }
1354
1355   return true;
1356 }
1357
1358 bool
1359 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1360 {
1361   using namespace collision;
1362
1363   if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1364
1365   for(MovingObjects::const_iterator i = moving_objects.begin();
1366       i != moving_objects.end(); ++i) {
1367     const MovingObject* moving_object = *i;
1368     if (moving_object == ignore_object) continue;
1369     if (!moving_object->is_valid()) continue;
1370     if (moving_object->get_group() == COLGROUP_STATIC) {
1371       if(intersects(rect, moving_object->get_bbox())) return false;
1372     }
1373   }
1374
1375   return true;
1376 }
1377
1378 bool
1379 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1380 {
1381   using namespace collision;
1382
1383   if (!is_free_of_tiles(rect)) return false;
1384
1385   for(MovingObjects::const_iterator i = moving_objects.begin();
1386       i != moving_objects.end(); ++i) {
1387     const MovingObject* moving_object = *i;
1388     if (moving_object == ignore_object) continue;
1389     if (!moving_object->is_valid()) continue;
1390     if ((moving_object->get_group() == COLGROUP_MOVING)
1391         || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1392         || (moving_object->get_group() == COLGROUP_STATIC)) {
1393       if(intersects(rect, moving_object->get_bbox())) return false;
1394     }
1395   }
1396
1397   return true;
1398 }
1399
1400 bool
1401 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1402 {
1403   // TODO remove this function and move these checks elsewhere...
1404
1405   Bullet* new_bullet = 0;
1406   if((player_status->bonus == FIRE_BONUS &&
1407       (int)bullets.size() >= player_status->max_fire_bullets) ||
1408      (player_status->bonus == ICE_BONUS &&
1409       (int)bullets.size() >= player_status->max_ice_bullets))
1410     return false;
1411   new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1412   add_object(new_bullet);
1413
1414   sound_manager->play("sounds/shoot.wav");
1415
1416   return true;
1417 }
1418
1419 bool
1420 Sector::add_smoke_cloud(const Vector& pos)
1421 {
1422   add_object(new SmokeCloud(pos));
1423   return true;
1424 }
1425
1426 void
1427 Sector::play_music(MusicType type)
1428 {
1429   currentmusic = type;
1430   switch(currentmusic) {
1431     case LEVEL_MUSIC:
1432       sound_manager->play_music(music);
1433       break;
1434     case HERRING_MUSIC:
1435       sound_manager->play_music("music/invincible.music");
1436       break;
1437     case HERRING_WARNING_MUSIC:
1438       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1439       break;
1440     default:
1441       sound_manager->play_music("");
1442       break;
1443   }
1444 }
1445
1446 MusicType
1447 Sector::get_music_type()
1448 {
1449   return currentmusic;
1450 }
1451
1452 int
1453 Sector::get_total_badguys()
1454 {
1455   int total_badguys = 0;
1456   for(GameObjects::iterator i = gameobjects.begin();
1457       i != gameobjects.end(); ++i) {
1458     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1459     if (badguy && badguy->countMe)
1460       total_badguys++;
1461   }
1462
1463   return total_badguys;
1464 }
1465
1466 bool
1467 Sector::inside(const Rect& rect) const
1468 {
1469   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1470     TileMap* solids = *i;
1471     bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1472     bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1473
1474     if (horizontally && vertically)
1475       return true;
1476   }
1477   return false;
1478 }
1479
1480 float
1481 Sector::get_width() const
1482 {
1483   float width = 0;
1484   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1485       i != solid_tilemaps.end(); i++) {
1486     TileMap* solids = *i;
1487     if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1488       width = solids->get_width() * 32 + solids->get_x_offset();
1489     }
1490   }
1491
1492   return width;
1493 }
1494
1495 float
1496 Sector::get_height() const
1497 {
1498   float height = 0;
1499   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1500       i != solid_tilemaps.end(); i++) {
1501     TileMap* solids = *i;
1502     if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1503       height = solids->get_height() * 32 + solids->get_y_offset();
1504     }
1505   }
1506
1507   return height;
1508 }
1509
1510 void
1511 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1512 {
1513   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1514     TileMap* solids = *i;
1515     solids->change_all(old_tile_id, new_tile_id);
1516   }
1517 }
1518
1519 void
1520 Sector::set_ambient_light(float red, float green, float blue)
1521 {
1522   ambient_light.red = red;
1523   ambient_light.green = green;
1524   ambient_light.blue = blue;
1525 }
1526
1527 float
1528 Sector::get_ambient_red()
1529 {
1530   return ambient_light.red;
1531 }
1532
1533 float
1534 Sector::get_ambient_green()
1535 {
1536   return ambient_light.green;
1537 }
1538
1539 float
1540 Sector::get_ambient_blue()
1541 {
1542   return ambient_light.blue;
1543 }
1544
1545 void
1546 Sector::set_gravity(float gravity)
1547 {
1548   log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1549   this->gravity = gravity;
1550 }
1551
1552 float
1553 Sector::get_gravity() const
1554 {
1555   return gravity;
1556 }
1557
1558 /* EOF */