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