a5fd7d4fb5b5b6e7f6d456dcfa7827494161322c
[supertux.git] / src / sector.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2006 Matthias Braun <matze@braunis.de>
5 //
6 //  This program is free software; you can redistribute it and/or
7 //  modify it under the terms of the GNU General Public License
8 //  as published by the Free Software Foundation; either version 2
9 //  of the License, or (at your option) any later version.
10 //
11 //  This program is distributed in the hope that it will be useful,
12 //  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 //  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 //  GNU General Public License for more details.
15 //
16 //  You should have received a copy of the GNU General Public License
17 //  along with this program; if not, write to the Free Software
18 //  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19 #include <config.h>
20
21 #include <memory>
22 #include <algorithm>
23 #include <stdexcept>
24 #include <iostream>
25 #include <fstream>
26 #include <sstream>
27 #include <stdexcept>
28 #include <float.h>
29 #include <math.h>
30 #include <limits>
31 #include <physfs.h>
32
33 #include "sector.hpp"
34 #include "object/player.hpp"
35 #include "object/gameobjs.hpp"
36 #include "object/camera.hpp"
37 #include "object/background.hpp"
38 #include "object/gradient.hpp"
39 #include "object/particlesystem.hpp"
40 #include "object/particlesystem_interactive.hpp"
41 #include "object/tilemap.hpp"
42 #include "lisp/parser.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/writer.hpp"
45 #include "lisp/list_iterator.hpp"
46 #include "tile.hpp"
47 #include "file_system.hpp"
48 #include "physfs/physfs_stream.hpp"
49 #include "audio/sound_manager.hpp"
50 #include "game_session.hpp"
51 #include "resources.hpp"
52 #include "statistics.hpp"
53 #include "object_factory.hpp"
54 #include "collision.hpp"
55 #include "spawn_point.hpp"
56 #include "math/rect.hpp"
57 #include "math/aatriangle.hpp"
58 #include "object/coin.hpp"
59 #include "object/block.hpp"
60 #include "object/invisible_block.hpp"
61 #include "object/light.hpp"
62 #include "object/pulsing_light.hpp"
63 #include "object/bullet.hpp"
64 #include "object/text_object.hpp"
65 #include "object/portable.hpp"
66 #include "badguy/jumpy.hpp"
67 #include "trigger/sequence_trigger.hpp"
68 #include "player_status.hpp"
69 #include "scripting/squirrel_util.hpp"
70 #include "script_interface.hpp"
71 #include "log.hpp"
72 #include "main.hpp"
73 #include "level.hpp"
74
75 Sector* Sector::_current = 0;
76
77 bool Sector::show_collrects = false;
78 bool Sector::draw_solids_only = false;
79
80 Sector::Sector(Level* parent)
81   : level(parent), currentmusic(LEVEL_MUSIC),
82   ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10.0), player(0), camera(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 lisp::Lisp& 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 lisp::Lisp& 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_vector( "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 lisp::Lisp& 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_vector("interactive-tm", tiles)
320       || reader.get_vector("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_vector("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_vector("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
465 void
466 Sector::write(lisp::Writer& writer)
467 {
468   writer.write_string("name", name);
469   writer.write_float("gravity", gravity);
470   writer.write_string("music", music);
471
472   // write spawnpoints
473   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
474       ++i) {
475     SpawnPoint* spawn = *i;
476     writer.start_list("spawn-points");
477     writer.write_string("name", spawn->name);
478     writer.write_float("x", spawn->pos.x);
479     writer.write_float("y", spawn->pos.y);
480     writer.end_list("spawn-points");
481   }
482
483   // write objects
484   for(GameObjects::iterator i = gameobjects.begin();
485       i != gameobjects.end(); ++i) {
486     Serializable* serializable = dynamic_cast<Serializable*> (*i);
487     if(serializable)
488       serializable->write(writer);
489   }
490 }
491
492 HSQUIRRELVM
493 Sector::run_script(std::istream& in, const std::string& sourcename)
494 {
495   using namespace Scripting;
496
497   // garbage collect thread list
498   for(ScriptList::iterator i = scripts.begin();
499       i != scripts.end(); ) {
500     HSQOBJECT& object = *i;
501     HSQUIRRELVM vm = object_to_vm(object);
502
503     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
504       sq_release(global_vm, &object);
505       i = scripts.erase(i);
506       continue;
507     }
508
509     ++i;
510   }
511
512   HSQOBJECT object = create_thread(global_vm);
513   scripts.push_back(object);
514
515   HSQUIRRELVM vm = object_to_vm(object);
516
517   // set sector_table as roottable for the thread
518   sq_pushobject(vm, sector_table);
519   sq_setroottable(vm);
520
521   compile_and_run(vm, in, sourcename);
522
523   return vm;
524 }
525
526 void
527 Sector::add_object(GameObject* object)
528 {
529   // make sure the object isn't already in the list
530 #ifdef DEBUG
531   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
532       ++i) {
533     if(*i == object) {
534       assert("object already added to sector" == 0);
535     }
536   }
537   for(GameObjects::iterator i = gameobjects_new.begin();
538       i != gameobjects_new.end(); ++i) {
539     if(*i == object) {
540       assert("object already added to sector" == 0);
541     }
542   }
543 #endif
544
545   object->ref();
546   gameobjects_new.push_back(object);
547 }
548
549 void
550 Sector::activate(const std::string& spawnpoint)
551 {
552   SpawnPoint* sp = 0;
553   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
554       ++i) {
555     if((*i)->name == spawnpoint) {
556       sp = *i;
557       break;
558     }
559   }
560   if(!sp) {
561     log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
562     if(spawnpoint != "main") {
563       activate("main");
564     } else {
565       activate(Vector(0, 0));
566     }
567   } else {
568     activate(sp->pos);
569   }
570 }
571
572 void
573 Sector::activate(const Vector& player_pos)
574 {
575   if(_current != this) {
576     if(_current != NULL)
577       _current->deactivate();
578     _current = this;
579
580     // register sectortable as sector in scripting
581     HSQUIRRELVM vm = Scripting::global_vm;
582     sq_pushroottable(vm);
583     sq_pushstring(vm, "sector", -1);
584     sq_pushobject(vm, sector_table);
585     if(SQ_FAILED(sq_createslot(vm, -3)))
586       throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
587     sq_pop(vm, 1);
588
589     for(GameObjects::iterator i = gameobjects.begin();
590         i != gameobjects.end(); ++i) {
591       GameObject* object = *i;
592
593       try_expose(object);
594     }
595   }
596   try_expose_me();
597
598   // spawn smalltux below spawnpoint
599   if (!player->is_big()) {
600     player->move(player_pos + Vector(0,32));
601   } else {
602     player->move(player_pos);
603   }
604
605   // spawning tux in the ground would kill him
606   if(!is_free_of_tiles(player->get_bbox())) {
607     log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
608     Vector npos = player->get_bbox().p1;
609     npos.y-=32;
610     player->move(npos);
611   }
612
613   camera->reset(player->get_pos());
614   update_game_objects();
615
616   //Run default.nut just before init script
617   //Check to see if it's in a levelset (info file)
618   std::string basedir = FileSystem::dirname(get_level()->filename);
619   if(PHYSFS_exists((basedir + "/info").c_str())) {
620     try {
621       IFileStream in(basedir + "/default.nut");
622       run_script(in, std::string("Sector(") + name + ") - default.nut");
623     } catch(std::exception& ) {
624       // doesn't exist or erroneous; do nothing
625     }
626   }
627
628   // Run init script
629   if(init_script != "") {
630     std::istringstream in(init_script);
631     run_script(in, std::string("Sector(") + name + ") - init");
632   }
633 }
634
635 void
636 Sector::deactivate()
637 {
638   if(_current != this)
639     return;
640
641   // remove sector entry from global vm
642   HSQUIRRELVM vm = Scripting::global_vm;
643   sq_pushroottable(vm);
644   sq_pushstring(vm, "sector", -1);
645   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
646     throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
647   sq_pop(vm, 1);
648
649   for(GameObjects::iterator i = gameobjects.begin();
650       i != gameobjects.end(); ++i) {
651     GameObject* object = *i;
652
653     try_unexpose(object);
654   }
655
656   try_unexpose_me();
657   _current = NULL;
658 }
659
660 Rect
661 Sector::get_active_region()
662 {
663   return Rect(
664     camera->get_translation() - Vector(1600, 1200),
665     camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
666 }
667
668 void
669 Sector::update(float elapsed_time)
670 {
671   player->check_bounds(camera);
672
673   /* update objects */
674   for(GameObjects::iterator i = gameobjects.begin();
675           i != gameobjects.end(); ++i) {
676     GameObject* object = *i;
677     if(!object->is_valid())
678       continue;
679
680     object->update(elapsed_time);
681   }
682
683   /* Handle all possible collisions. */
684   handle_collisions();
685   update_game_objects();
686 }
687
688 void
689 Sector::update_game_objects()
690 {
691   /** cleanup marked objects */
692   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
693       i != gameobjects.end(); /* nothing */) {
694     GameObject* object = *i;
695
696     if(object->is_valid()) {
697       ++i;
698       continue;
699     }
700
701     before_object_remove(object);
702
703     object->unref();
704     i = gameobjects.erase(i);
705   }
706
707   /* add newly created objects */
708   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
709       i != gameobjects_new.end(); ++i)
710   {
711     GameObject* object = *i;
712
713     before_object_add(object);
714
715     gameobjects.push_back(object);
716   }
717   gameobjects_new.clear();
718
719   /* update solid_tilemaps list */
720   //FIXME: this could be more efficient
721   solid_tilemaps.clear();
722   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
723       i != gameobjects.end(); ++i)
724   {
725     TileMap* tm = dynamic_cast<TileMap*>(*i);
726     if (!tm) continue;
727     if (tm->is_solid()) solid_tilemaps.push_back(tm);
728   }
729
730 }
731
732 bool
733 Sector::before_object_add(GameObject* object)
734 {
735   Bullet* bullet = dynamic_cast<Bullet*> (object);
736   if(bullet != NULL) {
737     bullets.push_back(bullet);
738   }
739
740   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
741   if(movingobject != NULL) {
742     moving_objects.push_back(movingobject);
743   }
744
745   Portable* portable = dynamic_cast<Portable*> (object);
746   if(portable != NULL) {
747     portables.push_back(portable);
748   }
749
750   TileMap* tilemap = dynamic_cast<TileMap*> (object);
751   if(tilemap != NULL && tilemap->is_solid()) {
752     solid_tilemaps.push_back(tilemap);
753   }
754
755   Camera* camera = dynamic_cast<Camera*> (object);
756   if(camera != NULL) {
757     if(this->camera != 0) {
758       log_warning << "Multiple cameras added. Ignoring" << std::endl;
759       return false;
760     }
761     this->camera = camera;
762   }
763
764   Player* player = dynamic_cast<Player*> (object);
765   if(player != NULL) {
766     if(this->player != 0) {
767       log_warning << "Multiple players added. Ignoring" << std::endl;
768       return false;
769     }
770     this->player = player;
771   }
772
773   UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
774   if(physic_object)
775   {
776     physic_object->physic.set_gravity(gravity);
777   }
778
779
780   if(_current == this) {
781     try_expose(object);
782   }
783
784   return true;
785 }
786
787 void
788 Sector::try_expose(GameObject* object)
789 {
790   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
791   if(interface != NULL) {
792     HSQUIRRELVM vm = Scripting::global_vm;
793     sq_pushobject(vm, sector_table);
794     interface->expose(vm, -1);
795     sq_pop(vm, 1);
796   }
797 }
798
799 void
800 Sector::try_expose_me()
801 {
802   HSQUIRRELVM vm = Scripting::global_vm;
803   sq_pushobject(vm, sector_table);
804   Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
805   expose_object(vm, -1, interface, "settings", false);
806   sq_pop(vm, 1);
807 }
808
809 void
810 Sector::before_object_remove(GameObject* object)
811 {
812   Portable* portable = dynamic_cast<Portable*> (object);
813   if(portable != NULL) {
814     portables.erase(std::find(portables.begin(), portables.end(), portable));
815   }
816   Bullet* bullet = dynamic_cast<Bullet*> (object);
817   if(bullet != NULL) {
818     bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
819   }
820   MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
821   if(moving_object != NULL) {
822     moving_objects.erase(
823         std::find(moving_objects.begin(), moving_objects.end(), moving_object));
824   }
825
826   if(_current == this)
827     try_unexpose(object);
828 }
829
830 void
831 Sector::try_unexpose(GameObject* object)
832 {
833   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
834   if(interface != NULL) {
835     HSQUIRRELVM vm = Scripting::global_vm;
836     SQInteger oldtop = sq_gettop(vm);
837     sq_pushobject(vm, sector_table);
838     try {
839       interface->unexpose(vm, -1);
840     } catch(std::exception& e) {
841       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
842     }
843     sq_settop(vm, oldtop);
844   }
845 }
846
847 void
848 Sector::try_unexpose_me()
849 {
850   HSQUIRRELVM vm = Scripting::global_vm;
851   SQInteger oldtop = sq_gettop(vm);
852   sq_pushobject(vm, sector_table);
853   try {
854     Scripting::unexpose_object(vm, -1, "settings");
855   } catch(std::exception& e) {
856     log_warning << "Couldn't unregister object: " << e.what() << std::endl;
857   }
858   sq_settop(vm, oldtop);
859 }
860 void
861 Sector::draw(DrawingContext& context)
862 {
863   context.set_ambient_color( ambient_light );
864   context.push_transform();
865   context.set_translation(camera->get_translation());
866
867   for(GameObjects::iterator i = gameobjects.begin();
868       i != gameobjects.end(); ++i) {
869     GameObject* object = *i;
870     if(!object->is_valid())
871       continue;
872
873     if (draw_solids_only)
874     {
875       TileMap* tm = dynamic_cast<TileMap*>(object);
876       if (tm && !tm->is_solid())
877         continue;
878     }
879
880     object->draw(context);
881   }
882
883   if(show_collrects) {
884     Color col(0.2f, 0.2f, 0.2f, 0.7f);
885     for(MovingObjects::iterator i = moving_objects.begin();
886             i != moving_objects.end(); ++i) {
887       MovingObject* object = *i;
888       const Rect& rect = object->get_bbox();
889
890       context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
891     }
892   }
893
894   context.pop_transform();
895 }
896
897 /*-------------------------------------------------------------------------
898  * Collision Detection
899  *-------------------------------------------------------------------------*/
900
901 static const float SHIFT_DELTA = 7.0f;
902
903 /** r1 is supposed to be moving, r2 a solid object */
904 void check_collisions(collision::Constraints* constraints,
905                       const Vector& movement, const Rect& r1, const Rect& r2,
906                       GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
907 {
908   if(!collision::intersects(r1, r2))
909     return;
910
911   MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
912   CollisionHit dummy;
913   if(other != NULL && !other->collides(*object, dummy))
914     return;
915   if(moving_object != NULL && !moving_object->collides(*other, dummy))
916     return;
917
918   // calculate intersection
919   float itop    = r1.get_bottom() - r2.get_top();
920   float ibottom = r2.get_bottom() - r1.get_top();
921   float ileft   = r1.get_right() - r2.get_left();
922   float iright  = r2.get_right() - r1.get_left();
923
924   if(fabsf(movement.y) > fabsf(movement.x)) {
925     if(ileft < SHIFT_DELTA) {
926       constraints->right = std::min(constraints->right, r2.get_left());
927       return;
928     } else if(iright < SHIFT_DELTA) {
929       constraints->left = std::max(constraints->left, r2.get_right());
930       return;
931     }
932   } else {
933     // shiftout bottom/top
934     if(itop < SHIFT_DELTA) {
935       constraints->bottom = std::min(constraints->bottom, r2.get_top());
936       return;
937     } else if(ibottom < SHIFT_DELTA) {
938       constraints->top = std::max(constraints->top, r2.get_bottom());
939       return;
940     }
941   }
942
943   constraints->ground_movement += addl_ground_movement;
944   if(other != NULL) {
945     HitResponse response = other->collision(*object, dummy);
946     if(response == PASSTHROUGH)
947       return;
948
949     if(other->get_movement() != Vector(0, 0)) {
950       // TODO what todo when we collide with 2 moving objects?!?
951       constraints->ground_movement += other->get_movement();
952     }
953   }
954
955   float vert_penetration = std::min(itop, ibottom);
956   float horiz_penetration = std::min(ileft, iright);
957   if(vert_penetration < horiz_penetration) {
958     if(itop < ibottom) {
959       constraints->bottom = std::min(constraints->bottom, r2.get_top());
960       constraints->hit.bottom = true;
961     } else {
962       constraints->top = std::max(constraints->top, r2.get_bottom());
963       constraints->hit.top = true;
964     }
965   } else {
966     if(ileft < iright) {
967       constraints->right = std::min(constraints->right, r2.get_left());
968       constraints->hit.right = true;
969     } else {
970       constraints->left = std::max(constraints->left, r2.get_right());
971       constraints->hit.left = true;
972     }
973   }
974 }
975
976 static const float DELTA = .001f;
977
978 void
979 Sector::collision_tilemap(collision::Constraints* constraints,
980                           const Vector& movement, const Rect& dest) const
981 {
982   // calculate rectangle where the object will move
983   float x1 = dest.get_left();
984   float x2 = dest.get_right();
985   float y1 = dest.get_top();
986   float y2 = dest.get_bottom();
987
988   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
989     TileMap* solids = *i;
990
991     // test with all tiles in this rectangle
992     int starttilex = int(x1 - solids->get_x_offset()) / 32;
993     int starttiley = int(y1 - solids->get_y_offset()) / 32;
994     int max_x = int(x2 - solids->get_x_offset());
995     int max_y = int(y2+1 - solids->get_y_offset());
996
997     for(int x = starttilex; x*32 < max_x; ++x) {
998       for(int y = starttiley; y*32 < max_y; ++y) {
999     const Tile* tile = solids->get_tile(x, y);
1000     if(!tile)
1001       continue;
1002     // skip non-solid tiles
1003     if((tile->getAttributes() & Tile::SOLID) == 0)
1004       continue;
1005     // only handle unisolid when the player is falling down and when he was
1006     // above the tile before
1007     if(tile->getAttributes() & Tile::UNISOLID) {
1008       if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
1009         continue;
1010     }
1011
1012     if(tile->getAttributes() & Tile::SLOPE) { // slope tile
1013       AATriangle triangle;
1014       Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1015       Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1016       triangle = AATriangle(p1, p2, tile->getData());
1017
1018       collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
1019     } else { // normal rectangular tile
1020       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());
1021       check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
1022     }
1023       }
1024     }
1025   }
1026 }
1027
1028 uint32_t
1029 Sector::collision_tile_attributes(const Rect& dest) const
1030 {
1031   float x1 = dest.p1.x;
1032   float y1 = dest.p1.y;
1033   float x2 = dest.p2.x;
1034   float y2 = dest.p2.y;
1035
1036   uint32_t result = 0;
1037   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1038     TileMap* solids = *i;
1039
1040     // test with all tiles in this rectangle
1041     int starttilex = int(x1 - solids->get_x_offset()) / 32;
1042     int starttiley = int(y1 - solids->get_y_offset()) / 32;
1043     int max_x = int(x2 - solids->get_x_offset());
1044     int max_y = int(y2+1 - solids->get_y_offset());
1045
1046     for(int x = starttilex; x*32 < max_x; ++x) {
1047       for(int y = starttiley; y*32 < max_y; ++y) {
1048     const Tile* tile = solids->get_tile(x, y);
1049     if(!tile)
1050       continue;
1051     result |= tile->getAttributes();
1052       }
1053     }
1054   }
1055
1056   return result;
1057 }
1058
1059 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1060 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1061                            Vector& normal)
1062 {
1063   float itop = r1.get_bottom() - r2.get_top();
1064   float ibottom = r2.get_bottom() - r1.get_top();
1065   float ileft = r1.get_right() - r2.get_left();
1066   float iright = r2.get_right() - r1.get_left();
1067
1068   float vert_penetration = std::min(itop, ibottom);
1069   float horiz_penetration = std::min(ileft, iright);
1070   if(vert_penetration < horiz_penetration) {
1071     if(itop < ibottom) {
1072       hit.bottom = true;
1073       normal.y = vert_penetration;
1074     } else {
1075       hit.top = true;
1076       normal.y = -vert_penetration;
1077     }
1078   } else {
1079     if(ileft < iright) {
1080       hit.right = true;
1081       normal.x = horiz_penetration;
1082     } else {
1083       hit.left = true;
1084       normal.x = -horiz_penetration;
1085     }
1086   }
1087 }
1088
1089 void
1090 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1091 {
1092   using namespace collision;
1093
1094   const Rect& r1 = object1->dest;
1095   const Rect& r2 = object2->dest;
1096
1097   CollisionHit hit;
1098   if(intersects(object1->dest, object2->dest)) {
1099     Vector normal;
1100     get_hit_normal(r1, r2, hit, normal);
1101
1102     if(!object1->collides(*object2, hit))
1103       return;
1104     std::swap(hit.left, hit.right);
1105     std::swap(hit.top, hit.bottom);
1106     if(!object2->collides(*object1, hit))
1107       return;
1108     std::swap(hit.left, hit.right);
1109     std::swap(hit.top, hit.bottom);
1110
1111     HitResponse response1 = object1->collision(*object2, hit);
1112     std::swap(hit.left, hit.right);
1113     std::swap(hit.top, hit.bottom);
1114     HitResponse response2 = object2->collision(*object1, hit);
1115     if(response1 == CONTINUE && response2 == CONTINUE) {
1116       normal *= (0.5 + DELTA);
1117       object1->dest.move(-normal);
1118       object2->dest.move(normal);
1119     } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1120       normal *= (1 + DELTA);
1121       object1->dest.move(-normal);
1122     } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1123       normal *= (1 + DELTA);
1124       object2->dest.move(normal);
1125     }
1126   }
1127 }
1128
1129 void
1130 Sector::collision_static(collision::Constraints* constraints,
1131                          const Vector& movement, const Rect& dest,
1132                          GameObject& object)
1133 {
1134   collision_tilemap(constraints, movement, dest);
1135
1136   // collision with other (static) objects
1137   for(MovingObjects::iterator i = moving_objects.begin();
1138       i != moving_objects.end(); ++i) {
1139     MovingObject* moving_object = *i;
1140     if(moving_object->get_group() != COLGROUP_STATIC
1141        && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1142       continue;
1143     if(!moving_object->is_valid())
1144       continue;
1145
1146     if(moving_object != &object)
1147       check_collisions(constraints, movement, dest, moving_object->bbox,
1148           &object, moving_object);
1149   }
1150 }
1151
1152 void
1153 Sector::collision_static_constrains(MovingObject& object)
1154 {
1155   using namespace collision;
1156   float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1157
1158   Constraints constraints;
1159   Vector movement = object.get_movement();
1160   Rect& dest = object.dest;
1161   float owidth = object.get_bbox().get_width();
1162   float oheight = object.get_bbox().get_height();
1163
1164   for(int i = 0; i < 2; ++i) {
1165     collision_static(&constraints, Vector(0, movement.y), dest, object);
1166     if(!constraints.has_constraints())
1167       break;
1168
1169     // apply calculated horizontal constraints
1170     if(constraints.bottom < infinity) {
1171       float height = constraints.bottom - constraints.top;
1172       if(height < oheight) {
1173         // we're crushed, but ignore this for now, we'll get this again
1174         // later if we're really crushed or things will solve itself when
1175         // looking at the vertical constraints
1176       }
1177       dest.p2.y = constraints.bottom - DELTA;
1178       dest.p1.y = dest.p2.y - oheight;
1179     } else if(constraints.top > -infinity) {
1180       dest.p1.y = constraints.top + DELTA;
1181       dest.p2.y = dest.p1.y + oheight;
1182     }
1183   }
1184   if(constraints.has_constraints()) {
1185     if(constraints.hit.bottom) {
1186       dest.move(constraints.ground_movement);
1187     }
1188     if(constraints.hit.top || constraints.hit.bottom) {
1189       constraints.hit.left = false;
1190       constraints.hit.right = false;
1191       object.collision_solid(constraints.hit);
1192     }
1193   }
1194
1195   constraints = Constraints();
1196   for(int i = 0; i < 2; ++i) {
1197     collision_static(&constraints, movement, dest, object);
1198     if(!constraints.has_constraints())
1199       break;
1200
1201     // apply calculated vertical constraints
1202     if(constraints.right < infinity) {
1203       float width = constraints.right - constraints.left;
1204       if(width + SHIFT_DELTA < owidth) {
1205 #if 0
1206         printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1207             constraints.left, constraints.right);
1208 #endif
1209         CollisionHit h;
1210         h.left = true;
1211         h.right = true;
1212         h.crush = true;
1213         object.collision_solid(h);
1214       } else {
1215         dest.p2.x = constraints.right - DELTA;
1216         dest.p1.x = dest.p2.x - owidth;
1217       }
1218     } else if(constraints.left > -infinity) {
1219       dest.p1.x = constraints.left + DELTA;
1220       dest.p2.x = dest.p1.x + owidth;
1221     }
1222   }
1223
1224   if(constraints.has_constraints()) {
1225     if( constraints.hit.left || constraints.hit.right
1226         || constraints.hit.top || constraints.hit.bottom
1227         || constraints.hit.crush )
1228       object.collision_solid(constraints.hit);
1229   }
1230
1231   // an extra pass to make sure we're not crushed horizontally
1232   constraints = Constraints();
1233   collision_static(&constraints, movement, dest, object);
1234   if(constraints.bottom < infinity) {
1235     float height = constraints.bottom - constraints.top;
1236     if(height + SHIFT_DELTA < oheight) {
1237 #if 0
1238       printf("Object %p crushed vertically...\n", &object);
1239 #endif
1240       CollisionHit h;
1241       h.top = true;
1242       h.bottom = true;
1243       h.crush = true;
1244       object.collision_solid(h);
1245     }
1246   }
1247 }
1248
1249 namespace {
1250   const float MAX_SPEED = 16.0f;
1251 }
1252
1253 void
1254 Sector::handle_collisions()
1255 {
1256   using namespace collision;
1257
1258   // calculate destination positions of the objects
1259   for(MovingObjects::iterator i = moving_objects.begin();
1260       i != moving_objects.end(); ++i) {
1261     MovingObject* moving_object = *i;
1262     Vector mov = moving_object->get_movement();
1263
1264     // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1265     if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1266       moving_object->movement = mov.unit() * MAX_SPEED;
1267       //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1268     }
1269
1270     moving_object->dest = moving_object->get_bbox();
1271     moving_object->dest.move(moving_object->get_movement());
1272   }
1273
1274   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1275   for(MovingObjects::iterator i = moving_objects.begin();
1276       i != moving_objects.end(); ++i) {
1277     MovingObject* moving_object = *i;
1278     if((moving_object->get_group() != COLGROUP_MOVING
1279           && moving_object->get_group() != COLGROUP_MOVING_STATIC
1280           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1281         || !moving_object->is_valid())
1282       continue;
1283
1284     collision_static_constrains(*moving_object);
1285   }
1286
1287
1288   // part2: COLGROUP_MOVING vs tile attributes
1289   for(MovingObjects::iterator i = moving_objects.begin();
1290       i != moving_objects.end(); ++i) {
1291     MovingObject* moving_object = *i;
1292     if((moving_object->get_group() != COLGROUP_MOVING
1293           && moving_object->get_group() != COLGROUP_MOVING_STATIC
1294           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1295         || !moving_object->is_valid())
1296       continue;
1297
1298     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1299     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1300       moving_object->collision_tile(tile_attributes);
1301     }
1302   }
1303
1304   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1305   for(MovingObjects::iterator i = moving_objects.begin();
1306       i != moving_objects.end(); ++i) {
1307     MovingObject* moving_object = *i;
1308     if((moving_object->get_group() != COLGROUP_MOVING
1309           && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1310         || !moving_object->is_valid())
1311       continue;
1312
1313     for(MovingObjects::iterator i2 = moving_objects.begin();
1314         i2 != moving_objects.end(); ++i2) {
1315       MovingObject* moving_object_2 = *i2;
1316       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1317          || !moving_object_2->is_valid())
1318         continue;
1319
1320       if(intersects(moving_object->dest, moving_object_2->dest)) {
1321         Vector normal;
1322         CollisionHit hit;
1323         get_hit_normal(moving_object->dest, moving_object_2->dest,
1324                        hit, normal);
1325         if(!moving_object->collides(*moving_object_2, hit))
1326           continue;
1327         if(!moving_object_2->collides(*moving_object, hit))
1328           continue;
1329
1330         moving_object->collision(*moving_object_2, hit);
1331         moving_object_2->collision(*moving_object, hit);
1332       }
1333     }
1334   }
1335
1336   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1337   for(MovingObjects::iterator i = moving_objects.begin();
1338       i != moving_objects.end(); ++i) {
1339     MovingObject* moving_object = *i;
1340
1341     if((moving_object->get_group() != COLGROUP_MOVING
1342           && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1343         || !moving_object->is_valid())
1344       continue;
1345
1346     for(MovingObjects::iterator i2 = i+1;
1347         i2 != moving_objects.end(); ++i2) {
1348       MovingObject* moving_object_2 = *i2;
1349       if((moving_object_2->get_group() != COLGROUP_MOVING
1350             && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1351          || !moving_object_2->is_valid())
1352         continue;
1353
1354       collision_object(moving_object, moving_object_2);
1355     }
1356   }
1357
1358   // apply object movement
1359   for(MovingObjects::iterator i = moving_objects.begin();
1360       i != moving_objects.end(); ++i) {
1361     MovingObject* moving_object = *i;
1362
1363     moving_object->bbox = moving_object->dest;
1364     moving_object->movement = Vector(0, 0);
1365   }
1366 }
1367
1368 bool
1369 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1370 {
1371   using namespace collision;
1372
1373   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1374     TileMap* solids = *i;
1375
1376     // test with all tiles in this rectangle
1377     int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1378     int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1379     int max_x = int(rect.p2.x - solids->get_x_offset());
1380     int max_y = int(rect.p2.y - solids->get_y_offset());
1381
1382     for(int x = starttilex; x*32 <= max_x; ++x) {
1383       for(int y = starttiley; y*32 <= max_y; ++y) {
1384     const Tile* tile = solids->get_tile(x, y);
1385     if(!tile) continue;
1386     if(tile->getAttributes() & Tile::SLOPE) {
1387       AATriangle triangle;
1388       Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1389       Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1390       triangle = AATriangle(p1, p2, tile->getData());
1391       Constraints constraints;
1392       return collision::rectangle_aatriangle(&constraints, rect, triangle);
1393     }
1394     if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1395     if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1396       }
1397     }
1398   }
1399
1400   return true;
1401 }
1402
1403 bool
1404 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1405 {
1406   using namespace collision;
1407
1408   if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1409
1410   for(MovingObjects::const_iterator i = moving_objects.begin();
1411       i != moving_objects.end(); ++i) {
1412     const MovingObject* moving_object = *i;
1413     if (moving_object == ignore_object) continue;
1414     if (!moving_object->is_valid()) continue;
1415     if (moving_object->get_group() == COLGROUP_STATIC) {
1416       if(intersects(rect, moving_object->get_bbox())) return false;
1417     }
1418   }
1419
1420   return true;
1421 }
1422
1423 bool
1424 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1425 {
1426   using namespace collision;
1427
1428   if (!is_free_of_tiles(rect)) return false;
1429
1430   for(MovingObjects::const_iterator i = moving_objects.begin();
1431       i != moving_objects.end(); ++i) {
1432     const MovingObject* moving_object = *i;
1433     if (moving_object == ignore_object) continue;
1434     if (!moving_object->is_valid()) continue;
1435     if ((moving_object->get_group() == COLGROUP_MOVING)
1436       || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1437       || (moving_object->get_group() == COLGROUP_STATIC)) {
1438       if(intersects(rect, moving_object->get_bbox())) return false;
1439     }
1440   }
1441
1442   return true;
1443 }
1444
1445 bool
1446 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1447 {
1448   // TODO remove this function and move these checks elsewhere...
1449
1450   Bullet* new_bullet = 0;
1451   if((player_status->bonus == FIRE_BONUS &&
1452       (int)bullets.size() >= player_status->max_fire_bullets) ||
1453      (player_status->bonus == ICE_BONUS &&
1454       (int)bullets.size() >= player_status->max_ice_bullets))
1455     return false;
1456   new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1457   add_object(new_bullet);
1458
1459   sound_manager->play("sounds/shoot.wav");
1460
1461   return true;
1462 }
1463
1464 bool
1465 Sector::add_smoke_cloud(const Vector& pos)
1466 {
1467   add_object(new SmokeCloud(pos));
1468   return true;
1469 }
1470
1471 void
1472 Sector::play_music(MusicType type)
1473 {
1474   currentmusic = type;
1475   switch(currentmusic) {
1476     case LEVEL_MUSIC:
1477       sound_manager->play_music(music);
1478       break;
1479     case HERRING_MUSIC:
1480       sound_manager->play_music("music/invincible.ogg");
1481       break;
1482     case HERRING_WARNING_MUSIC:
1483       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1484       break;
1485     default:
1486       sound_manager->play_music("");
1487       break;
1488   }
1489 }
1490
1491 MusicType
1492 Sector::get_music_type()
1493 {
1494   return currentmusic;
1495 }
1496
1497 int
1498 Sector::get_total_badguys()
1499 {
1500   int total_badguys = 0;
1501   for(GameObjects::iterator i = gameobjects.begin();
1502       i != gameobjects.end(); ++i) {
1503     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1504     if (badguy && badguy->countMe)
1505       total_badguys++;
1506   }
1507
1508   return total_badguys;
1509 }
1510
1511 bool
1512 Sector::inside(const Rect& rect) const
1513 {
1514   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1515     TileMap* solids = *i;
1516     bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1517     bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1518
1519     if (horizontally && vertically)
1520       return true;
1521   }
1522   return false;
1523 }
1524
1525 float
1526 Sector::get_width() const
1527 {
1528   float width = 0;
1529   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1530       i != solid_tilemaps.end(); i++) {
1531     TileMap* solids = *i;
1532     if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1533       width = solids->get_width() * 32 + solids->get_x_offset();
1534     }
1535   }
1536
1537   return width;
1538 }
1539
1540 float
1541 Sector::get_height() const
1542 {
1543   float height = 0;
1544   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1545       i != solid_tilemaps.end(); i++) {
1546     TileMap* solids = *i;
1547     if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1548       height = solids->get_height() * 32 + solids->get_y_offset();
1549     }
1550   }
1551
1552   return height;
1553 }
1554
1555 void
1556 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1557 {
1558   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1559     TileMap* solids = *i;
1560     solids->change_all(old_tile_id, new_tile_id);
1561   }
1562 }
1563
1564
1565 void
1566 Sector::set_ambient_light(float red, float green, float blue)
1567 {
1568   ambient_light.red = red;
1569   ambient_light.green = green;
1570   ambient_light.blue = blue;
1571 }
1572
1573 float
1574 Sector::get_ambient_red()
1575 {
1576   return ambient_light.red;
1577 }
1578
1579 float
1580 Sector::get_ambient_green()
1581 {
1582   return ambient_light.green;
1583 }
1584
1585 float
1586 Sector::get_ambient_blue()
1587 {
1588   return ambient_light.blue;
1589 }
1590
1591 void
1592 Sector::set_gravity(float gravity)
1593 {
1594   log_warning << "Changing a Sector's gravitational constant might have unforseen side-effects" << std::endl;
1595
1596   this->gravity = gravity;
1597
1598   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); ++i) {
1599     GameObject* game_object = *i;
1600     if(!game_object) continue;
1601     if(!game_object->is_valid()) continue;
1602     UsesPhysic *physics_object = dynamic_cast<UsesPhysic*>(game_object);
1603     if (!physics_object) continue;
1604
1605     physics_object->physic.set_gravity(gravity);
1606   }
1607 }
1608