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