supertux/tile.[ch]pp: Move the unisolid solidity checks to the "Tile" object.
[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     assert(*i != object);
513   }
514   for(GameObjects::iterator i = gameobjects_new.begin();
515       i != gameobjects_new.end(); ++i) {
516     assert(*i != object);
517   }
518 #endif
519
520   object->ref();
521   gameobjects_new.push_back(object);
522 }
523
524 void
525 Sector::activate(const std::string& spawnpoint)
526 {
527   SpawnPoint* sp = 0;
528   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
529       ++i) {
530     if((*i)->name == spawnpoint) {
531       sp = *i;
532       break;
533     }
534   }
535   if(!sp) {
536     log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
537     if(spawnpoint != "main") {
538       activate("main");
539     } else {
540       activate(Vector(0, 0));
541     }
542   } else {
543     activate(sp->pos);
544   }
545 }
546
547 void
548 Sector::activate(const Vector& player_pos)
549 {
550   if(_current != this) {
551     if(_current != NULL)
552       _current->deactivate();
553     _current = this;
554
555     // register sectortable as sector in scripting
556     HSQUIRRELVM vm = scripting::global_vm;
557     sq_pushroottable(vm);
558     sq_pushstring(vm, "sector", -1);
559     sq_pushobject(vm, sector_table);
560     if(SQ_FAILED(sq_createslot(vm, -3)))
561       throw scripting::SquirrelError(vm, "Couldn't set sector in roottable");
562     sq_pop(vm, 1);
563
564     for(GameObjects::iterator i = gameobjects.begin();
565         i != gameobjects.end(); ++i) {
566       GameObject* object = *i;
567
568       try_expose(object);
569     }
570   }
571   try_expose_me();
572
573
574   // two-player hack: move other players to main player's position
575   // Maybe specify 2 spawnpoints in the level?
576   for(GameObjects::iterator i = gameobjects.begin();
577       i != gameobjects.end(); ++i) {
578     Player* p = dynamic_cast<Player*>(*i);
579     if (!p) continue;
580
581     // spawn smalltux below spawnpoint
582     if (!p->is_big()) {
583       p->move(player_pos + Vector(0,32));
584     } else {
585       p->move(player_pos);
586     }
587
588     // spawning tux in the ground would kill him
589     if(!is_free_of_tiles(p->get_bbox())) {
590       log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
591       Vector npos = p->get_bbox().p1;
592       npos.y-=32;
593       p->move(npos);
594     }
595   }
596
597   camera->reset(player->get_pos());
598   update_game_objects();
599
600   //Run default.nut just before init script
601   //Check to see if it's in a levelset (info file)
602   std::string basedir = FileSystem::dirname(get_level()->filename);
603   if(PHYSFS_exists((basedir + "/info").c_str())) {
604     try {
605       IFileStream in(basedir + "/default.nut");
606       run_script(in, "default.nut");
607     } catch(std::exception& ) {
608       // doesn't exist or erroneous; do nothing
609     }
610   }
611
612   // Run init script
613   if(init_script != "") {
614     std::istringstream in(init_script);
615     run_script(in, "init-script");
616   }
617 }
618
619 void
620 Sector::deactivate()
621 {
622   if(_current != this)
623     return;
624
625   // remove sector entry from global vm
626   HSQUIRRELVM vm = scripting::global_vm;
627   sq_pushroottable(vm);
628   sq_pushstring(vm, "sector", -1);
629   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
630     throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
631   sq_pop(vm, 1);
632
633   for(GameObjects::iterator i = gameobjects.begin();
634       i != gameobjects.end(); ++i) {
635     GameObject* object = *i;
636
637     try_unexpose(object);
638   }
639
640   try_unexpose_me();
641   _current = NULL;
642 }
643
644 Rectf
645 Sector::get_active_region()
646 {
647   return Rectf(
648     camera->get_translation() - Vector(1600, 1200),
649     camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
650 }
651
652 void
653 Sector::update(float elapsed_time)
654 {
655   player->check_bounds();
656
657   /* update objects */
658   for(GameObjects::iterator i = gameobjects.begin();
659       i != gameobjects.end(); ++i) {
660     GameObject* object = *i;
661     if(!object->is_valid())
662       continue;
663
664     object->update(elapsed_time);
665   }
666
667   /* Handle all possible collisions. */
668   handle_collisions();
669   update_game_objects();
670 }
671
672 void
673 Sector::update_game_objects()
674 {
675   /** cleanup marked objects */
676   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
677       i != gameobjects.end(); /* nothing */) {
678     GameObject* object = *i;
679
680     if(object->is_valid()) {
681       ++i;
682       continue;
683     }
684
685     before_object_remove(object);
686
687     object->unref();
688     i = gameobjects.erase(i);
689   }
690
691   /* add newly created objects */
692   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
693       i != gameobjects_new.end(); ++i)
694   {
695     GameObject* object = *i;
696
697     before_object_add(object);
698
699     gameobjects.push_back(object);
700   }
701   gameobjects_new.clear();
702
703   /* update solid_tilemaps list */
704   //FIXME: this could be more efficient
705   solid_tilemaps.clear();
706   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
707       i != gameobjects.end(); ++i)
708   {
709     TileMap* tm = dynamic_cast<TileMap*>(*i);
710     if (!tm) continue;
711     if (tm->is_solid()) solid_tilemaps.push_back(tm);
712   }
713
714 }
715
716 bool
717 Sector::before_object_add(GameObject* object)
718 {
719   Bullet* bullet = dynamic_cast<Bullet*> (object);
720   if(bullet != NULL) {
721     bullets.push_back(bullet);
722   }
723
724   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
725   if(movingobject != NULL) {
726     moving_objects.push_back(movingobject);
727   }
728
729   Portable* portable = dynamic_cast<Portable*> (object);
730   if(portable != NULL) {
731     portables.push_back(portable);
732   }
733
734   TileMap* tilemap = dynamic_cast<TileMap*> (object);
735   if(tilemap != NULL && tilemap->is_solid()) {
736     solid_tilemaps.push_back(tilemap);
737   }
738
739   Camera* camera = dynamic_cast<Camera*> (object);
740   if(camera != NULL) {
741     if(this->camera != 0) {
742       log_warning << "Multiple cameras added. Ignoring" << std::endl;
743       return false;
744     }
745     this->camera = camera;
746   }
747
748   Player* player = dynamic_cast<Player*> (object);
749   if(player != NULL) {
750     if(this->player != 0) {
751       log_warning << "Multiple players added. Ignoring" << std::endl;
752       return false;
753     }
754     this->player = player;
755   }
756
757   DisplayEffect* effect = dynamic_cast<DisplayEffect*> (object);
758   if(effect != NULL) {
759     if(this->effect != 0) {
760       log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
761       return false;
762     }
763     this->effect = effect;
764   }
765
766   if(_current == this) {
767     try_expose(object);
768   }
769
770   return true;
771 }
772
773 void
774 Sector::try_expose(GameObject* object)
775 {
776   ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
777   if(object_ != NULL) {
778     HSQUIRRELVM vm = scripting::global_vm;
779     sq_pushobject(vm, sector_table);
780     object_->expose(vm, -1);
781     sq_pop(vm, 1);
782   }
783 }
784
785 void
786 Sector::try_expose_me()
787 {
788   HSQUIRRELVM vm = scripting::global_vm;
789   sq_pushobject(vm, sector_table);
790   scripting::SSector* this_ = static_cast<scripting::SSector*> (this);
791   expose_object(vm, -1, this_, "settings", false);
792   sq_pop(vm, 1);
793 }
794
795 void
796 Sector::before_object_remove(GameObject* object)
797 {
798   Portable* portable = dynamic_cast<Portable*> (object);
799   if(portable != NULL) {
800     portables.erase(std::find(portables.begin(), portables.end(), portable));
801   }
802   Bullet* bullet = dynamic_cast<Bullet*> (object);
803   if(bullet != NULL) {
804     bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
805   }
806   MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
807   if(moving_object != NULL) {
808     moving_objects.erase(
809       std::find(moving_objects.begin(), moving_objects.end(), moving_object));
810   }
811
812   if(_current == this)
813     try_unexpose(object);
814 }
815
816 void
817 Sector::try_unexpose(GameObject* object)
818 {
819   ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
820   if(object_ != NULL) {
821     HSQUIRRELVM vm = scripting::global_vm;
822     SQInteger oldtop = sq_gettop(vm);
823     sq_pushobject(vm, sector_table);
824     try {
825       object_->unexpose(vm, -1);
826     } catch(std::exception& e) {
827       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
828     }
829     sq_settop(vm, oldtop);
830   }
831 }
832
833 void
834 Sector::try_unexpose_me()
835 {
836   HSQUIRRELVM vm = scripting::global_vm;
837   SQInteger oldtop = sq_gettop(vm);
838   sq_pushobject(vm, sector_table);
839   try {
840     scripting::unexpose_object(vm, -1, "settings");
841   } catch(std::exception& e) {
842     log_warning << "Couldn't unregister object: " << e.what() << std::endl;
843   }
844   sq_settop(vm, oldtop);
845 }
846 void
847 Sector::draw(DrawingContext& context)
848 {
849   context.set_ambient_color( ambient_light );
850   context.push_transform();
851   context.set_translation(camera->get_translation());
852
853   for(GameObjects::iterator i = gameobjects.begin();
854       i != gameobjects.end(); ++i) {
855     GameObject* object = *i;
856     if(!object->is_valid())
857       continue;
858
859     if (draw_solids_only)
860     {
861       TileMap* tm = dynamic_cast<TileMap*>(object);
862       if (tm && !tm->is_solid())
863         continue;
864     }
865
866     object->draw(context);
867   }
868
869   if(show_collrects) {
870     Color color(1.0f, 0.0f, 0.0f, 0.75f);
871     for(MovingObjects::iterator i = moving_objects.begin();
872         i != moving_objects.end(); ++i) {
873       MovingObject* object = *i;
874       const Rectf& rect = object->get_bbox();
875
876       context.draw_filled_rect(rect, color, LAYER_FOREGROUND1 + 10);
877     }
878   }
879
880   context.pop_transform();
881 }
882
883 /*-------------------------------------------------------------------------
884  * Collision Detection
885  *-------------------------------------------------------------------------*/
886
887 /** r1 is supposed to be moving, r2 a solid object */
888 void check_collisions(collision::Constraints* constraints,
889                       const Vector& obj_movement, const Rectf& obj_rect, const Rectf& other_rect,
890                       GameObject* object = NULL, MovingObject* other = NULL, const Vector& other_movement = Vector(0,0))
891 {
892   if(!collision::intersects(obj_rect, other_rect))
893     return;
894
895   MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
896   CollisionHit dummy;
897   if(other != NULL && !other->collides(*object, dummy))
898     return;
899   if(moving_object != NULL && !moving_object->collides(*other, dummy))
900     return;
901
902   // calculate intersection
903   float itop    = obj_rect.get_bottom() - other_rect.get_top();
904   float ibottom = other_rect.get_bottom() - obj_rect.get_top();
905   float ileft   = obj_rect.get_right() - other_rect.get_left();
906   float iright  = other_rect.get_right() - obj_rect.get_left();
907
908   if(fabsf(obj_movement.y) > fabsf(obj_movement.x)) {
909     if(ileft < SHIFT_DELTA) {
910       constraints->constrain_right(other_rect.get_left(), other_movement.x);
911       return;
912     } else if(iright < SHIFT_DELTA) {
913       constraints->constrain_left(other_rect.get_right(), other_movement.x);
914       return;
915     }
916   } else {
917     // shiftout bottom/top
918     if(itop < SHIFT_DELTA) {
919       constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
920       return;
921     } else if(ibottom < SHIFT_DELTA) {
922       constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
923       return;
924     }
925   }
926
927   constraints->ground_movement += other_movement;
928   if(other != NULL) {
929     HitResponse response = other->collision(*object, dummy);
930     if(response == ABORT_MOVE)
931       return;
932
933     if(other->get_movement() != Vector(0, 0)) {
934       // TODO what todo when we collide with 2 moving objects?!?
935       constraints->ground_movement = other->get_movement();
936     }
937   }
938
939   float vert_penetration = std::min(itop, ibottom);
940   float horiz_penetration = std::min(ileft, iright);
941   if(vert_penetration < horiz_penetration) {
942     if(itop < ibottom) {
943       constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
944       constraints->hit.bottom = true;
945     } else {
946       constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
947       constraints->hit.top = true;
948     }
949   } else {
950     if(ileft < iright) {
951       constraints->constrain_right(other_rect.get_left(), other_movement.x);
952       constraints->hit.right = true;
953     } else {
954       constraints->constrain_left(other_rect.get_right(), other_movement.x);
955       constraints->hit.left = true;
956     }
957   }
958 }
959
960 void
961 Sector::collision_tilemap(collision::Constraints* constraints,
962                           const Vector& movement, const Rectf& dest,
963                           MovingObject& object) const
964 {
965   // calculate rectangle where the object will move
966   float x1 = dest.get_left();
967   float x2 = dest.get_right();
968   float y1 = dest.get_top();
969   float y2 = dest.get_bottom();
970
971   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
972     TileMap* solids = *i;
973
974     // test with all tiles in this rectangle
975     Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
976
977     for(int x = test_tiles.left; x < test_tiles.right; ++x) {
978       for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
979         const Tile* tile = solids->get_tile(x, y);
980         if(!tile)
981           continue;
982         // skip non-solid tiles
983         if(!tile->is_solid ())
984           continue;
985         Rectf tile_bbox = solids->get_tile_bbox(x, y);
986
987         /* If the tile is a unisolid tile, the "is_solid()" function above
988          * didn't do a thorough check. Calculate the position and (relative)
989          * movement of the object and determine whether or not the tile is
990          * solid with regard to those parameters. */
991         if(tile->is_unisolid ()) {
992           Vector relative_movement = movement
993             - solids->get_movement(/* actual = */ true);
994
995           if (!tile->is_solid (tile_bbox, object.get_bbox(), relative_movement))
996             continue;
997         } /* if (tile->is_unisolid ()) */
998
999         if(tile->is_slope ()) { // slope tile
1000           AATriangle triangle;
1001           int slope_data = tile->getData();
1002           if (solids->get_drawing_effect() == VERTICAL_FLIP)
1003             slope_data = AATriangle::vertical_flip(slope_data);
1004           triangle = AATriangle(tile_bbox, slope_data);
1005
1006           collision::rectangle_aatriangle(constraints, dest, triangle,
1007               solids->get_movement(/* actual = */ false));
1008         } else { // normal rectangular tile
1009           check_collisions(constraints, movement, dest, tile_bbox, NULL, NULL,
1010               solids->get_movement(/* actual = */ false));
1011         }
1012       }
1013     }
1014   }
1015 }
1016
1017 uint32_t
1018 Sector::collision_tile_attributes(const Rectf& dest) const
1019 {
1020   float x1 = dest.p1.x;
1021   float y1 = dest.p1.y;
1022   float x2 = dest.p2.x;
1023   float y2 = dest.p2.y;
1024
1025   uint32_t result = 0;
1026   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1027     TileMap* solids = *i;
1028
1029     // test with all tiles in this rectangle
1030     Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1031     // For ice (only), add a little fudge to recognize tiles Tux is standing on.
1032     Rect test_tiles_ice = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2 + SHIFT_DELTA));
1033
1034     for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1035       int y;
1036       for(y = test_tiles.top; y < test_tiles.bottom; ++y) {
1037         const Tile* tile = solids->get_tile(x, y);
1038         if(!tile)
1039           continue;
1040         result |= tile->getAttributes();
1041       }
1042       for(; y < test_tiles_ice.bottom; ++y) {
1043         const Tile* tile = solids->get_tile(x, y);
1044         if(!tile)
1045           continue;
1046         result |= (tile->getAttributes() & Tile::ICE);
1047       }
1048     }
1049   }
1050
1051   return result;
1052 }
1053
1054 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1055 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1056                            Vector& normal)
1057 {
1058   float itop = r1.get_bottom() - r2.get_top();
1059   float ibottom = r2.get_bottom() - r1.get_top();
1060   float ileft = r1.get_right() - r2.get_left();
1061   float iright = r2.get_right() - r1.get_left();
1062
1063   float vert_penetration = std::min(itop, ibottom);
1064   float horiz_penetration = std::min(ileft, iright);
1065   if(vert_penetration < horiz_penetration) {
1066     if(itop < ibottom) {
1067       hit.bottom = true;
1068       normal.y = vert_penetration;
1069     } else {
1070       hit.top = true;
1071       normal.y = -vert_penetration;
1072     }
1073   } else {
1074     if(ileft < iright) {
1075       hit.right = true;
1076       normal.x = horiz_penetration;
1077     } else {
1078       hit.left = true;
1079       normal.x = -horiz_penetration;
1080     }
1081   }
1082 }
1083
1084 void
1085 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1086 {
1087   using namespace collision;
1088
1089   const Rectf& r1 = object1->dest;
1090   const Rectf& r2 = object2->dest;
1091
1092   CollisionHit hit;
1093   if(intersects(object1->dest, object2->dest)) {
1094     Vector normal;
1095     get_hit_normal(r1, r2, hit, normal);
1096
1097     if(!object1->collides(*object2, hit))
1098       return;
1099     std::swap(hit.left, hit.right);
1100     std::swap(hit.top, hit.bottom);
1101     if(!object2->collides(*object1, hit))
1102       return;
1103     std::swap(hit.left, hit.right);
1104     std::swap(hit.top, hit.bottom);
1105
1106     HitResponse response1 = object1->collision(*object2, hit);
1107     std::swap(hit.left, hit.right);
1108     std::swap(hit.top, hit.bottom);
1109     HitResponse response2 = object2->collision(*object1, hit);
1110     if(response1 == CONTINUE && response2 == CONTINUE) {
1111       normal *= (0.5 + DELTA);
1112       object1->dest.move(-normal);
1113       object2->dest.move(normal);
1114     } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1115       normal *= (1 + DELTA);
1116       object1->dest.move(-normal);
1117     } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1118       normal *= (1 + DELTA);
1119       object2->dest.move(normal);
1120     }
1121   }
1122 }
1123
1124 void
1125 Sector::collision_static(collision::Constraints* constraints,
1126                          const Vector& movement, const Rectf& dest,
1127                          MovingObject& object)
1128 {
1129   collision_tilemap(constraints, movement, dest, object);
1130
1131   // collision with other (static) objects
1132   for(MovingObjects::iterator i = moving_objects.begin();
1133       i != moving_objects.end(); ++i) {
1134     MovingObject* moving_object = *i;
1135     if(moving_object->get_group() != COLGROUP_STATIC
1136        && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1137       continue;
1138     if(!moving_object->is_valid())
1139       continue;
1140
1141     if(moving_object != &object)
1142       check_collisions(constraints, movement, dest, moving_object->bbox,
1143                        &object, moving_object);
1144   }
1145 }
1146
1147 void
1148 Sector::collision_static_constrains(MovingObject& object)
1149 {
1150   using namespace collision;
1151   float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1152
1153   Constraints constraints;
1154   Vector movement = object.get_movement();
1155   Rectf& dest = object.dest;
1156   float owidth = object.get_bbox().get_width();
1157   float oheight = object.get_bbox().get_height();
1158
1159   for(int i = 0; i < 2; ++i) {
1160     collision_static(&constraints, Vector(0, movement.y), dest, object);
1161     if(!constraints.has_constraints())
1162       break;
1163
1164     // apply calculated horizontal constraints
1165     if(constraints.get_position_bottom() < infinity) {
1166       float height = constraints.get_height ();
1167       if(height < oheight) {
1168         // we're crushed, but ignore this for now, we'll get this again
1169         // later if we're really crushed or things will solve itself when
1170         // looking at the vertical constraints
1171       }
1172       dest.p2.y = constraints.get_position_bottom() - DELTA;
1173       dest.p1.y = dest.p2.y - oheight;
1174     } else if(constraints.get_position_top() > -infinity) {
1175       dest.p1.y = constraints.get_position_top() + DELTA;
1176       dest.p2.y = dest.p1.y + oheight;
1177     }
1178   }
1179   if(constraints.has_constraints()) {
1180     if(constraints.hit.bottom) {
1181       dest.move(constraints.ground_movement);
1182     }
1183     if(constraints.hit.top || constraints.hit.bottom) {
1184       constraints.hit.left = false;
1185       constraints.hit.right = false;
1186       object.collision_solid(constraints.hit);
1187     }
1188   }
1189
1190   constraints = Constraints();
1191   for(int i = 0; i < 2; ++i) {
1192     collision_static(&constraints, movement, dest, object);
1193     if(!constraints.has_constraints())
1194       break;
1195
1196     // apply calculated vertical constraints
1197     float width = constraints.get_width ();
1198     if(width < infinity) {
1199       if(width + SHIFT_DELTA < owidth) {
1200 #if 0
1201         printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1202                constraints.get_position_left(), constraints.get_position_right());
1203 #endif
1204         CollisionHit h;
1205         h.left = true;
1206         h.right = true;
1207         h.crush = true;
1208         object.collision_solid(h);
1209       } else {
1210         float xmid = constraints.get_x_midpoint ();
1211         dest.p1.x = xmid - owidth/2;
1212         dest.p2.x = xmid + owidth/2;
1213       }
1214     } else if(constraints.get_position_right() < infinity) {
1215       dest.p2.x = constraints.get_position_right() - DELTA;
1216       dest.p1.x = dest.p2.x - owidth;
1217     } else if(constraints.get_position_left() > -infinity) {
1218       dest.p1.x = constraints.get_position_left() + DELTA;
1219       dest.p2.x = dest.p1.x + owidth;
1220     }
1221   }
1222
1223   if(constraints.has_constraints()) {
1224     if( constraints.hit.left || constraints.hit.right
1225         || constraints.hit.top || constraints.hit.bottom
1226         || constraints.hit.crush )
1227       object.collision_solid(constraints.hit);
1228   }
1229
1230   // an extra pass to make sure we're not crushed horizontally
1231   constraints = Constraints();
1232   collision_static(&constraints, movement, dest, object);
1233   if(constraints.get_position_bottom() < infinity) {
1234     float height = constraints.get_height ();
1235     if(height + SHIFT_DELTA < oheight) {
1236 #if 0
1237       printf("Object %p crushed vertically...\n", &object);
1238 #endif
1239       CollisionHit h;
1240       h.top = true;
1241       h.bottom = true;
1242       h.crush = true;
1243       object.collision_solid(h);
1244     }
1245   }
1246 }
1247
1248 namespace {
1249 const float MAX_SPEED = 16.0f;
1250 }
1251
1252 void
1253 Sector::handle_collisions()
1254 {
1255   using namespace collision;
1256
1257   // calculate destination positions of the objects
1258   for(MovingObjects::iterator i = moving_objects.begin();
1259       i != moving_objects.end(); ++i) {
1260     MovingObject* moving_object = *i;
1261     Vector mov = moving_object->get_movement();
1262
1263     // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1264     if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1265       moving_object->movement = mov.unit() * MAX_SPEED;
1266       //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1267     }
1268
1269     moving_object->dest = moving_object->get_bbox();
1270     moving_object->dest.move(moving_object->get_movement());
1271   }
1272
1273   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1274   for(MovingObjects::iterator i = moving_objects.begin();
1275       i != moving_objects.end(); ++i) {
1276     MovingObject* moving_object = *i;
1277     if((moving_object->get_group() != COLGROUP_MOVING
1278         && moving_object->get_group() != COLGROUP_MOVING_STATIC
1279         && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1280        || !moving_object->is_valid())
1281       continue;
1282
1283     collision_static_constrains(*moving_object);
1284   }
1285
1286   // part2: COLGROUP_MOVING vs tile attributes
1287   for(MovingObjects::iterator i = moving_objects.begin();
1288       i != moving_objects.end(); ++i) {
1289     MovingObject* moving_object = *i;
1290     if((moving_object->get_group() != COLGROUP_MOVING
1291         && moving_object->get_group() != COLGROUP_MOVING_STATIC
1292         && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1293        || !moving_object->is_valid())
1294       continue;
1295
1296     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1297     if(tile_attributes >= Tile::FIRST_INTERESTING_FLAG) {
1298       moving_object->collision_tile(tile_attributes);
1299     }
1300   }
1301
1302   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1303   for(MovingObjects::iterator i = moving_objects.begin();
1304       i != moving_objects.end(); ++i) {
1305     MovingObject* moving_object = *i;
1306     if((moving_object->get_group() != COLGROUP_MOVING
1307         && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1308        || !moving_object->is_valid())
1309       continue;
1310
1311     for(MovingObjects::iterator i2 = moving_objects.begin();
1312         i2 != moving_objects.end(); ++i2) {
1313       MovingObject* moving_object_2 = *i2;
1314       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1315          || !moving_object_2->is_valid())
1316         continue;
1317
1318       if(intersects(moving_object->dest, moving_object_2->dest)) {
1319         Vector normal;
1320         CollisionHit hit;
1321         get_hit_normal(moving_object->dest, moving_object_2->dest,
1322                        hit, normal);
1323         if(!moving_object->collides(*moving_object_2, hit))
1324           continue;
1325         if(!moving_object_2->collides(*moving_object, hit))
1326           continue;
1327
1328         moving_object->collision(*moving_object_2, hit);
1329         moving_object_2->collision(*moving_object, hit);
1330       }
1331     }
1332   }
1333
1334   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1335   for(MovingObjects::iterator i = moving_objects.begin();
1336       i != moving_objects.end(); ++i) {
1337     MovingObject* moving_object = *i;
1338
1339     if((moving_object->get_group() != COLGROUP_MOVING
1340         && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1341        || !moving_object->is_valid())
1342       continue;
1343
1344     for(MovingObjects::iterator i2 = i+1;
1345         i2 != moving_objects.end(); ++i2) {
1346       MovingObject* moving_object_2 = *i2;
1347       if((moving_object_2->get_group() != COLGROUP_MOVING
1348           && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1349          || !moving_object_2->is_valid())
1350         continue;
1351
1352       collision_object(moving_object, moving_object_2);
1353     }
1354   }
1355
1356   // apply object movement
1357   for(MovingObjects::iterator i = moving_objects.begin();
1358       i != moving_objects.end(); ++i) {
1359     MovingObject* moving_object = *i;
1360
1361     moving_object->bbox = moving_object->dest;
1362     moving_object->movement = Vector(0, 0);
1363   }
1364 }
1365
1366 bool
1367 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1368 {
1369   using namespace collision;
1370
1371   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1372     TileMap* solids = *i;
1373
1374     // test with all tiles in this rectangle
1375     Rect test_tiles = solids->get_tiles_overlapping(rect);
1376
1377     for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1378       for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1379         const Tile* tile = solids->get_tile(x, y);
1380         if(!tile) continue;
1381         if(!(tile->getAttributes() & Tile::SOLID))
1382           continue;
1383         if(tile->is_unisolid () && ignoreUnisolid)
1384           continue;
1385         if(tile->is_slope ()) {
1386           AATriangle triangle;
1387           Rectf tbbox = solids->get_tile_bbox(x, y);
1388           triangle = AATriangle(tbbox, tile->getData());
1389           Constraints constraints;
1390           if(!collision::rectangle_aatriangle(&constraints, rect, triangle))
1391             continue;
1392         }
1393         // We have a solid tile that overlaps the given rectangle.
1394         return false;
1395       }
1396     }
1397   }
1398
1399   return true;
1400 }
1401
1402 bool
1403 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1404 {
1405   using namespace collision;
1406
1407   if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1408
1409   for(MovingObjects::const_iterator i = moving_objects.begin();
1410       i != moving_objects.end(); ++i) {
1411     const MovingObject* moving_object = *i;
1412     if (moving_object == ignore_object) continue;
1413     if (!moving_object->is_valid()) continue;
1414     if (moving_object->get_group() == COLGROUP_STATIC) {
1415       if(intersects(rect, moving_object->get_bbox())) return false;
1416     }
1417   }
1418
1419   return true;
1420 }
1421
1422 bool
1423 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1424 {
1425   using namespace collision;
1426
1427   if (!is_free_of_tiles(rect)) return false;
1428
1429   for(MovingObjects::const_iterator i = moving_objects.begin();
1430       i != moving_objects.end(); ++i) {
1431     const MovingObject* moving_object = *i;
1432     if (moving_object == ignore_object) continue;
1433     if (!moving_object->is_valid()) continue;
1434     if ((moving_object->get_group() == COLGROUP_MOVING)
1435         || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1436         || (moving_object->get_group() == COLGROUP_STATIC)) {
1437       if(intersects(rect, moving_object->get_bbox())) return false;
1438     }
1439   }
1440
1441   return true;
1442 }
1443
1444 bool
1445 Sector::add_bullet(const Vector& pos, const PlayerStatus* player_status, float xm, Direction dir)
1446 {
1447   // TODO remove this function and move these checks elsewhere...
1448
1449   Bullet* new_bullet = 0;
1450   if((player_status->bonus == FIRE_BONUS &&
1451       (int)bullets.size() >= player_status->max_fire_bullets) ||
1452      (player_status->bonus == ICE_BONUS &&
1453       (int)bullets.size() >= player_status->max_ice_bullets))
1454     return false;
1455   new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1456   add_object(new_bullet);
1457
1458   sound_manager->play("sounds/shoot.wav");
1459
1460   return true;
1461 }
1462
1463 bool
1464 Sector::add_smoke_cloud(const Vector& pos)
1465 {
1466   add_object(new SmokeCloud(pos));
1467   return true;
1468 }
1469
1470 void
1471 Sector::play_music(MusicType type)
1472 {
1473   currentmusic = type;
1474   switch(currentmusic) {
1475     case LEVEL_MUSIC:
1476       sound_manager->play_music(music);
1477       break;
1478     case HERRING_MUSIC:
1479       sound_manager->play_music("music/invincible.ogg");
1480       break;
1481     case HERRING_WARNING_MUSIC:
1482       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1483       break;
1484     default:
1485       sound_manager->play_music("");
1486       break;
1487   }
1488 }
1489
1490 MusicType
1491 Sector::get_music_type()
1492 {
1493   return currentmusic;
1494 }
1495
1496 int
1497 Sector::get_total_badguys()
1498 {
1499   int total_badguys = 0;
1500   for(GameObjects::iterator i = gameobjects.begin();
1501       i != gameobjects.end(); ++i) {
1502     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1503     if (badguy && badguy->countMe)
1504       total_badguys++;
1505   }
1506
1507   return total_badguys;
1508 }
1509
1510 bool
1511 Sector::inside(const Rectf& rect) const
1512 {
1513   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1514     TileMap* solids = *i;
1515
1516     Rectf bbox = solids->get_bbox();
1517     bbox.p1.y = -INFINITY; // pretend the tilemap extends infinitely far upwards
1518
1519     if (bbox.contains(rect))
1520       return true;
1521   }
1522   return false;
1523 }
1524
1525 float
1526 Sector::get_width() const
1527 {
1528   float width = 0;
1529   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1530       i != solid_tilemaps.end(); i++) {
1531     TileMap* solids = *i;
1532     width = std::max(width, solids->get_bbox().get_right());
1533   }
1534
1535   return width;
1536 }
1537
1538 float
1539 Sector::get_height() const
1540 {
1541   float height = 0;
1542   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1543       i != solid_tilemaps.end(); i++) {
1544     TileMap* solids = *i;
1545     height = std::max(height, solids->get_bbox().get_bottom());
1546   }
1547
1548   return height;
1549 }
1550
1551 void
1552 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1553 {
1554   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1555     TileMap* solids = *i;
1556     solids->change_all(old_tile_id, new_tile_id);
1557   }
1558 }
1559
1560 void
1561 Sector::set_ambient_light(float red, float green, float blue)
1562 {
1563   ambient_light.red = red;
1564   ambient_light.green = green;
1565   ambient_light.blue = blue;
1566 }
1567
1568 float
1569 Sector::get_ambient_red()
1570 {
1571   return ambient_light.red;
1572 }
1573
1574 float
1575 Sector::get_ambient_green()
1576 {
1577   return ambient_light.green;
1578 }
1579
1580 float
1581 Sector::get_ambient_blue()
1582 {
1583   return ambient_light.blue;
1584 }
1585
1586 void
1587 Sector::set_gravity(float gravity)
1588 {
1589   log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1590   this->gravity = gravity;
1591 }
1592
1593 float
1594 Sector::get_gravity() const
1595 {
1596   return gravity;
1597 }
1598
1599 Player*
1600 Sector::get_nearest_player (const Vector& pos)
1601 {
1602   Player *nearest_player = NULL;
1603   float nearest_dist = std::numeric_limits<float>::max();
1604
1605   std::vector<Player*> players = Sector::current()->get_players();
1606   for (std::vector<Player*>::iterator playerIter = players.begin();
1607       playerIter != players.end();
1608       ++playerIter)
1609   {
1610     Player *this_player = *playerIter;
1611     if (this_player->is_dying() || this_player->is_dead())
1612       continue;
1613
1614     float this_dist = this_player->get_bbox ().distance(pos);
1615
1616     if (this_dist < nearest_dist) {
1617       nearest_player = this_player;
1618       nearest_dist = this_dist;
1619     }
1620   }
1621
1622   return nearest_player;
1623 } /* Player *get_nearest_player */
1624
1625 std::vector<MovingObject*>
1626 Sector::get_nearby_objects (const Vector& center, float max_distance)
1627 {
1628   std::vector<MovingObject*> ret;
1629   std::vector<Player*> players = Sector::current()->get_players();
1630
1631   for (size_t i = 0; i < players.size (); i++) {
1632     float distance = players[i]->get_bbox ().distance (center);
1633     if (distance <= max_distance)
1634       ret.push_back (players[i]);
1635   }
1636
1637   for (size_t i = 0; i < moving_objects.size (); i++) {
1638     float distance = moving_objects[i]->get_bbox ().distance (center);
1639     if (distance <= max_distance)
1640       ret.push_back (moving_objects[i]);
1641   }
1642
1643   return (ret);
1644 }
1645
1646 /* vim: set sw=2 sts=2 et : */
1647 /* EOF */