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