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