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