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