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