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