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