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