supertux/collision.[ch]pp: Use "contrain_*" rather than "min_*" and "max_*".
[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     if(*i == object) {
518       assert("object already added to sector" == 0);
519     }
520   }
521   for(GameObjects::iterator i = gameobjects_new.begin();
522       i != gameobjects_new.end(); ++i) {
523     if(*i == object) {
524       assert("object already added to sector" == 0);
525     }
526   }
527 #endif
528
529   object->ref();
530   gameobjects_new.push_back(object);
531 }
532
533 void
534 Sector::activate(const std::string& spawnpoint)
535 {
536   SpawnPoint* sp = 0;
537   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
538       ++i) {
539     if((*i)->name == spawnpoint) {
540       sp = *i;
541       break;
542     }
543   }
544   if(!sp) {
545     log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
546     if(spawnpoint != "main") {
547       activate("main");
548     } else {
549       activate(Vector(0, 0));
550     }
551   } else {
552     activate(sp->pos);
553   }
554 }
555
556 void
557 Sector::activate(const Vector& player_pos)
558 {
559   if(_current != this) {
560     if(_current != NULL)
561       _current->deactivate();
562     _current = this;
563
564     // register sectortable as sector in scripting
565     HSQUIRRELVM vm = scripting::global_vm;
566     sq_pushroottable(vm);
567     sq_pushstring(vm, "sector", -1);
568     sq_pushobject(vm, sector_table);
569     if(SQ_FAILED(sq_createslot(vm, -3)))
570       throw scripting::SquirrelError(vm, "Couldn't set sector in roottable");
571     sq_pop(vm, 1);
572
573     for(GameObjects::iterator i = gameobjects.begin();
574         i != gameobjects.end(); ++i) {
575       GameObject* object = *i;
576
577       try_expose(object);
578     }
579   }
580   try_expose_me();
581
582   // spawn smalltux below spawnpoint
583   if (!player->is_big()) {
584     player->move(player_pos + Vector(0,32));
585   } else {
586     player->move(player_pos);
587   }
588
589   // spawning tux in the ground would kill him
590   if(!is_free_of_tiles(player->get_bbox())) {
591     log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
592     Vector npos = player->get_bbox().p1;
593     npos.y-=32;
594     player->move(npos);
595   }
596
597   camera->reset(player->get_pos());
598   update_game_objects();
599
600   //Run default.nut just before init script
601   //Check to see if it's in a levelset (info file)
602   std::string basedir = FileSystem::dirname(get_level()->filename);
603   if(PHYSFS_exists((basedir + "/info").c_str())) {
604     try {
605       IFileStream in(basedir + "/default.nut");
606       run_script(in, "default.nut");
607     } catch(std::exception& ) {
608       // doesn't exist or erroneous; do nothing
609     }
610   }
611
612   // Run init script
613   if(init_script != "") {
614     std::istringstream in(init_script);
615     run_script(in, "init-script");
616   }
617 }
618
619 void
620 Sector::deactivate()
621 {
622   if(_current != this)
623     return;
624
625   // remove sector entry from global vm
626   HSQUIRRELVM vm = scripting::global_vm;
627   sq_pushroottable(vm);
628   sq_pushstring(vm, "sector", -1);
629   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
630     throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
631   sq_pop(vm, 1);
632
633   for(GameObjects::iterator i = gameobjects.begin();
634       i != gameobjects.end(); ++i) {
635     GameObject* object = *i;
636
637     try_unexpose(object);
638   }
639
640   try_unexpose_me();
641   _current = NULL;
642 }
643
644 Rectf
645 Sector::get_active_region()
646 {
647   return Rectf(
648     camera->get_translation() - Vector(1600, 1200),
649     camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
650 }
651
652 void
653 Sector::update(float elapsed_time)
654 {
655   player->check_bounds(camera);
656
657   /* update objects */
658   for(GameObjects::iterator i = gameobjects.begin();
659       i != gameobjects.end(); ++i) {
660     GameObject* object = *i;
661     if(!object->is_valid())
662       continue;
663
664     object->update(elapsed_time);
665   }
666
667   /* Handle all possible collisions. */
668   handle_collisions();
669   update_game_objects();
670 }
671
672 void
673 Sector::update_game_objects()
674 {
675   /** cleanup marked objects */
676   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
677       i != gameobjects.end(); /* nothing */) {
678     GameObject* object = *i;
679
680     if(object->is_valid()) {
681       ++i;
682       continue;
683     }
684
685     before_object_remove(object);
686
687     object->unref();
688     i = gameobjects.erase(i);
689   }
690
691   /* add newly created objects */
692   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
693       i != gameobjects_new.end(); ++i)
694   {
695     GameObject* object = *i;
696
697     before_object_add(object);
698
699     gameobjects.push_back(object);
700   }
701   gameobjects_new.clear();
702
703   /* update solid_tilemaps list */
704   //FIXME: this could be more efficient
705   solid_tilemaps.clear();
706   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
707       i != gameobjects.end(); ++i)
708   {
709     TileMap* tm = dynamic_cast<TileMap*>(*i);
710     if (!tm) continue;
711     if (tm->is_solid()) solid_tilemaps.push_back(tm);
712   }
713
714 }
715
716 bool
717 Sector::before_object_add(GameObject* object)
718 {
719   Bullet* bullet = dynamic_cast<Bullet*> (object);
720   if(bullet != NULL) {
721     bullets.push_back(bullet);
722   }
723
724   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
725   if(movingobject != NULL) {
726     moving_objects.push_back(movingobject);
727   }
728
729   Portable* portable = dynamic_cast<Portable*> (object);
730   if(portable != NULL) {
731     portables.push_back(portable);
732   }
733
734   TileMap* tilemap = dynamic_cast<TileMap*> (object);
735   if(tilemap != NULL && tilemap->is_solid()) {
736     solid_tilemaps.push_back(tilemap);
737   }
738
739   Camera* camera = dynamic_cast<Camera*> (object);
740   if(camera != NULL) {
741     if(this->camera != 0) {
742       log_warning << "Multiple cameras added. Ignoring" << std::endl;
743       return false;
744     }
745     this->camera = camera;
746   }
747
748   Player* player = dynamic_cast<Player*> (object);
749   if(player != NULL) {
750     if(this->player != 0) {
751       log_warning << "Multiple players added. Ignoring" << std::endl;
752       return false;
753     }
754     this->player = player;
755   }
756
757   DisplayEffect* effect = dynamic_cast<DisplayEffect*> (object);
758   if(effect != NULL) {
759     if(this->effect != 0) {
760       log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
761       return false;
762     }
763     this->effect = effect;
764   }
765
766   if(_current == this) {
767     try_expose(object);
768   }
769
770   return true;
771 }
772
773 void
774 Sector::try_expose(GameObject* object)
775 {
776   ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
777   if(object_ != NULL) {
778     HSQUIRRELVM vm = scripting::global_vm;
779     sq_pushobject(vm, sector_table);
780     object_->expose(vm, -1);
781     sq_pop(vm, 1);
782   }
783 }
784
785 void
786 Sector::try_expose_me()
787 {
788   HSQUIRRELVM vm = scripting::global_vm;
789   sq_pushobject(vm, sector_table);
790   scripting::SSector* this_ = static_cast<scripting::SSector*> (this);
791   expose_object(vm, -1, this_, "settings", false);
792   sq_pop(vm, 1);
793 }
794
795 void
796 Sector::before_object_remove(GameObject* object)
797 {
798   Portable* portable = dynamic_cast<Portable*> (object);
799   if(portable != NULL) {
800     portables.erase(std::find(portables.begin(), portables.end(), portable));
801   }
802   Bullet* bullet = dynamic_cast<Bullet*> (object);
803   if(bullet != NULL) {
804     bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
805   }
806   MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
807   if(moving_object != NULL) {
808     moving_objects.erase(
809       std::find(moving_objects.begin(), moving_objects.end(), moving_object));
810   }
811
812   if(_current == this)
813     try_unexpose(object);
814 }
815
816 void
817 Sector::try_unexpose(GameObject* object)
818 {
819   ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
820   if(object_ != NULL) {
821     HSQUIRRELVM vm = scripting::global_vm;
822     SQInteger oldtop = sq_gettop(vm);
823     sq_pushobject(vm, sector_table);
824     try {
825       object_->unexpose(vm, -1);
826     } catch(std::exception& e) {
827       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
828     }
829     sq_settop(vm, oldtop);
830   }
831 }
832
833 void
834 Sector::try_unexpose_me()
835 {
836   HSQUIRRELVM vm = scripting::global_vm;
837   SQInteger oldtop = sq_gettop(vm);
838   sq_pushobject(vm, sector_table);
839   try {
840     scripting::unexpose_object(vm, -1, "settings");
841   } catch(std::exception& e) {
842     log_warning << "Couldn't unregister object: " << e.what() << std::endl;
843   }
844   sq_settop(vm, oldtop);
845 }
846 void
847 Sector::draw(DrawingContext& context)
848 {
849   context.set_ambient_color( ambient_light );
850   context.push_transform();
851   context.set_translation(camera->get_translation());
852
853   for(GameObjects::iterator i = gameobjects.begin();
854       i != gameobjects.end(); ++i) {
855     GameObject* object = *i;
856     if(!object->is_valid())
857       continue;
858
859     if (draw_solids_only)
860     {
861       TileMap* tm = dynamic_cast<TileMap*>(object);
862       if (tm && !tm->is_solid())
863         continue;
864     }
865
866     object->draw(context);
867   }
868
869   if(show_collrects) {
870     Color col(0.2f, 0.2f, 0.2f, 0.7f);
871     for(MovingObjects::iterator i = moving_objects.begin();
872         i != moving_objects.end(); ++i) {
873       MovingObject* object = *i;
874       const Rectf& rect = object->get_bbox();
875
876       context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
877     }
878   }
879
880   context.pop_transform();
881 }
882
883 /*-------------------------------------------------------------------------
884  * Collision Detection
885  *-------------------------------------------------------------------------*/
886
887 /** r1 is supposed to be moving, r2 a solid object */
888 void check_collisions(collision::Constraints* constraints,
889                       const Vector& movement, const Rectf& r1, const Rectf& r2,
890                       GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
891 {
892   if(!collision::intersects(r1, r2))
893     return;
894
895   MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
896   CollisionHit dummy;
897   if(other != NULL && !other->collides(*object, dummy))
898     return;
899   if(moving_object != NULL && !moving_object->collides(*other, dummy))
900     return;
901
902   // calculate intersection
903   float itop    = r1.get_bottom() - r2.get_top();
904   float ibottom = r2.get_bottom() - r1.get_top();
905   float ileft   = r1.get_right() - r2.get_left();
906   float iright  = r2.get_right() - r1.get_left();
907
908   if(fabsf(movement.y) > fabsf(movement.x)) {
909     if(ileft < SHIFT_DELTA) {
910       constraints->constrain_right(r2.get_left());
911       return;
912     } else if(iright < SHIFT_DELTA) {
913       constraints->constrain_left(r2.get_right());
914       return;
915     }
916   } else {
917     // shiftout bottom/top
918     if(itop < SHIFT_DELTA) {
919       constraints->constrain_bottom(r2.get_top());
920       return;
921     } else if(ibottom < SHIFT_DELTA) {
922       constraints->constrain_top(r2.get_bottom());
923       return;
924     }
925   }
926
927   constraints->ground_movement += addl_ground_movement;
928   if(other != NULL) {
929     HitResponse response = other->collision(*object, dummy);
930     if(response == ABORT_MOVE)
931       return;
932
933     if(other->get_movement() != Vector(0, 0)) {
934       // TODO what todo when we collide with 2 moving objects?!?
935       constraints->ground_movement = other->get_movement();
936     }
937   }
938
939   float vert_penetration = std::min(itop, ibottom);
940   float horiz_penetration = std::min(ileft, iright);
941   if(vert_penetration < horiz_penetration) {
942     if(itop < ibottom) {
943       constraints->constrain_bottom(r2.get_top());
944       constraints->hit.bottom = true;
945     } else {
946       constraints->constrain_top(r2.get_bottom());
947       constraints->hit.top = true;
948     }
949   } else {
950     if(ileft < iright) {
951       constraints->constrain_right(r2.get_left());
952       constraints->hit.right = true;
953     } else {
954       constraints->constrain_left(r2.get_right());
955       constraints->hit.left = true;
956     }
957   }
958 }
959
960 /* Returns zero if a unisolid tile is non-solid due to the movement direction,
961  * non-zero if the tile is solid due to direction. */
962 int check_movement_unisolid (const Vector& movement, const Tile* tile)
963 {
964   int slope_info;
965   double mv_x;
966   double mv_y;
967   double mv_tan;
968   double slope_tan;
969
970 #define MV_NON_SOLID 0
971 #define MV_SOLID 1
972
973   /* If the tile is not a slope, this is very easy. */
974   if ((tile->getAttributes() & Tile::SLOPE) == 0)
975   {
976     if (movement.y >= 0) /* moving down */
977       return MV_SOLID;
978     else /* moving up */
979       return MV_NON_SOLID;
980   }
981
982   /* Initialize mv_x and mv_y. Depending on the slope the axis are inverted so
983    * that we can always use the "SOUTHEAST" case of the slope. The southeast
984    * case is the following:
985    *     .
986    *    /!
987    *   / !
988    *  +--+
989    */
990   mv_x = (double) movement.x;
991   mv_y = (double) movement.y;
992
993   slope_info = tile->getData();
994   switch (slope_info & AATriangle::DIRECTION_MASK)
995   {
996     case AATriangle::SOUTHEAST: /*    . */
997       /* do nothing */          /*   /! */
998       break;                    /*  / ! */
999                                 /* +--+ */
1000     case AATriangle::SOUTHWEST: /* .    */
1001       mv_x *= (-1.0);           /* !\   */
1002       break;                    /* ! \  */
1003                                 /* +--+ */
1004     case AATriangle::NORTHEAST: /* +--+ */
1005       mv_y *= (-1.0);           /*  \ ! */
1006       break;                    /*   \! */
1007                                 /*    ' */
1008     case AATriangle::NORTHWEST: /* +--+ */
1009       mv_x *= (-1.0);           /* ! /  */
1010       mv_y *= (-1.0);           /* !/   */
1011       break;                    /* '    */
1012   } /* switch (slope_info & DIRECTION_MASK) */
1013
1014   /* Handle the easy cases first */
1015   /* If we're moving to the right and down, then the slope is solid. */
1016   if ((mv_x >= 0.0) && (mv_y >= 0.0)) /* 4th quadrant */
1017     return MV_SOLID;
1018   /* If we're moving to the left and up, then the slope is not solid. */
1019   else if ((mv_x <= 0.0) && (mv_y <= 0.0)) /* 2nd quadrant */
1020     return MV_NON_SOLID;
1021
1022   /* The pure up-down and left-right movements have already been handled. */
1023   assert (mv_x != 0.0);
1024   assert (mv_y != 0.0);
1025
1026   /* calculate tangent of movement */
1027   mv_tan = (-1.0) * mv_y / mv_x;
1028
1029   /* determine tangent of the slope */
1030   slope_tan = 1.0;
1031   if (((slope_info & AATriangle::DEFORM_MASK) == DEFORM_BOTTOM)
1032       || ((slope_info & AATriangle::DEFORM_MASK) == DEFORM_TOP))
1033     slope_tan = 0.5; /* ~= 26.6 deg */
1034   else if (((slope_info & AATriangle::DEFORM_MASK) == DEFORM_LEFT)
1035       || ((slope_info & AATriangle::DEFORM_MASK) == DEFORM_RIGHT))
1036     slope_tan = 2.0; /* ~= 63.4 deg */
1037
1038   /* up and right */
1039   if (mv_x > 0.0) /* 1st quadrant */
1040   {
1041     assert (mv_y < 0.0);
1042     if (mv_tan <= slope_tan)
1043       return MV_SOLID;
1044     else
1045       return MV_NON_SOLID;
1046   }
1047   /* down and left */
1048   else if (mv_x < 0.0) /* 3rd quadrant */
1049   {
1050     assert (mv_y > 0.0);
1051     if (mv_tan >= slope_tan)
1052       return MV_SOLID;
1053     else
1054       return MV_NON_SOLID;
1055   }
1056
1057   assert (1 != 1);
1058   return (-1);
1059
1060 #undef MV_NON_SOLID
1061 #undef MV_SOLID
1062 } /* int check_movement_unisolid */
1063
1064 int is_above_line (float l_x, float l_y, float m,
1065     float p_x, float p_y)
1066 {
1067   float interp_y = (l_y + (m * (p_x - l_x)));
1068   if (interp_y == p_y)
1069     return (1);
1070   else if (interp_y > p_y)
1071     return (1);
1072   else
1073     return (0);
1074 }
1075
1076 int is_below_line (float l_x, float l_y, float m,
1077     float p_x, float p_y)
1078 {
1079   if (is_above_line (l_x, l_y, m, p_x, p_y))
1080     return (0);
1081   else
1082     return (1);
1083 }
1084
1085 int check_position_unisolid (const Rectf& obj_bbox,
1086     const Rectf& tile_bbox,
1087     const Tile* tile)
1088 {
1089   int slope_info;
1090   float tile_x;
1091   float tile_y;
1092   float gradient;
1093   float delta_x;
1094   float delta_y;
1095   float obj_x;
1096   float obj_y;
1097
1098 #define POS_NON_SOLID 0
1099 #define POS_SOLID 1
1100
1101   /* If this is not a slope, this is - again - easy */
1102   if ((tile->getAttributes() & Tile::SLOPE) == 0)
1103   {
1104     if ((obj_bbox.get_bottom () - SHIFT_DELTA) <= tile_bbox.get_top ())
1105       return POS_SOLID;
1106     else
1107       return POS_NON_SOLID;
1108   }
1109
1110   /* There are 20 different cases. For each case, calculate a line that
1111    * describes the slope's surface. The line is defined by x, y, and m, the
1112    * gradient. */
1113   slope_info = tile->getData();
1114   switch (slope_info
1115       & (AATriangle::DIRECTION_MASK | AATriangle::DEFORM_MASK))
1116   {
1117     case AATriangle::SOUTHWEST:
1118     case AATriangle::SOUTHWEST | DEFORM_TOP:
1119     case AATriangle::SOUTHWEST | DEFORM_LEFT:
1120     case AATriangle::NORTHEAST:
1121     case AATriangle::NORTHEAST | DEFORM_TOP:
1122     case AATriangle::NORTHEAST | DEFORM_LEFT:
1123       tile_x = tile_bbox.get_left ();
1124       tile_y = tile_bbox.get_top ();
1125       gradient = 1.0;
1126       break;
1127
1128     case AATriangle::SOUTHEAST:
1129     case AATriangle::SOUTHEAST | DEFORM_TOP:
1130     case AATriangle::SOUTHEAST | DEFORM_RIGHT:
1131     case AATriangle::NORTHWEST:
1132     case AATriangle::NORTHWEST | DEFORM_TOP:
1133     case AATriangle::NORTHWEST | DEFORM_RIGHT:
1134       tile_x = tile_bbox.get_right ();
1135       tile_y = tile_bbox.get_top ();
1136       gradient = -1.0;
1137       break;
1138
1139     case AATriangle::SOUTHEAST | DEFORM_BOTTOM:
1140     case AATriangle::SOUTHEAST | DEFORM_LEFT:
1141     case AATriangle::NORTHWEST | DEFORM_BOTTOM:
1142     case AATriangle::NORTHWEST | DEFORM_LEFT:
1143       tile_x = tile_bbox.get_left ();
1144       tile_y = tile_bbox.get_bottom ();
1145       gradient = -1.0;
1146       break;
1147
1148     case AATriangle::SOUTHWEST | DEFORM_BOTTOM:
1149     case AATriangle::SOUTHWEST | DEFORM_RIGHT:
1150     case AATriangle::NORTHEAST | DEFORM_BOTTOM:
1151     case AATriangle::NORTHEAST | DEFORM_RIGHT:
1152       tile_x = tile_bbox.get_right ();
1153       tile_y = tile_bbox.get_bottom ();
1154       gradient = 1.0;
1155       break;
1156
1157     default:
1158       assert (23 == 42);
1159   }
1160
1161   /* delta_x, delta_y: Gradient aware version of SHIFT_DELTA. Here, we set the
1162    * sign of the values only. Also, we determine here which corner of the
1163    * object's bounding box is the interesting one for us. */
1164   delta_x = 1.0 * SHIFT_DELTA;
1165   delta_y = 1.0 * SHIFT_DELTA;
1166   switch (slope_info & AATriangle::DIRECTION_MASK)
1167   {
1168     case AATriangle::SOUTHWEST:
1169       delta_x *= 1.0;
1170       delta_y *= -1.0;
1171       obj_x = obj_bbox.get_left ();
1172       obj_y = obj_bbox.get_bottom ();
1173       break;
1174
1175     case AATriangle::SOUTHEAST:
1176       delta_x *= -1.0;
1177       delta_y *= -1.0;
1178       obj_x = obj_bbox.get_right ();
1179       obj_y = obj_bbox.get_bottom ();
1180       break;
1181
1182     case AATriangle::NORTHWEST:
1183       delta_x *= 1.0;
1184       delta_y *= 1.0;
1185       obj_x = obj_bbox.get_left ();
1186       obj_y = obj_bbox.get_top ();
1187       break;
1188
1189     case AATriangle::NORTHEAST:
1190       delta_x *= -1.0;
1191       delta_y *= 1.0;
1192       obj_x = obj_bbox.get_right ();
1193       obj_y = obj_bbox.get_top ();
1194       break;
1195   }
1196
1197   /* Adapt the delta_x, delta_y and the gradient for the 26.6 deg and 63.4 deg
1198    * cases. */
1199   switch (slope_info & AATriangle::DEFORM_MASK)
1200   {
1201     case 0:
1202       delta_x *= .70710678118654752440; /* 1/sqrt(2) */
1203       delta_y *= .70710678118654752440; /* 1/sqrt(2) */
1204       break;
1205
1206     case DEFORM_BOTTOM:
1207     case DEFORM_TOP:
1208       delta_x *= .44721359549995793928; /* 1/sqrt(5) */
1209       delta_y *= .89442719099991587856; /* 2/sqrt(5) */
1210       gradient *= 0.5;
1211       break;
1212
1213     case DEFORM_LEFT:
1214     case DEFORM_RIGHT:
1215       delta_x *= .89442719099991587856; /* 2/sqrt(5) */
1216       delta_y *= .44721359549995793928; /* 1/sqrt(5) */
1217       gradient *= 2.0;
1218       break;
1219   }
1220
1221   /* With a south slope, check if all points are above the line. If one point
1222    * isn't, the slope is not solid. => You can pass through a south-slope from
1223    * below but not from above. */
1224   if (((slope_info & AATriangle::DIRECTION_MASK) == AATriangle::SOUTHWEST)
1225       || ((slope_info & AATriangle::DIRECTION_MASK) == AATriangle::SOUTHEAST))
1226   {
1227     if (is_below_line (tile_x, tile_y, gradient, obj_x + delta_x, obj_y + delta_y))
1228       return (POS_NON_SOLID);
1229     else
1230       return (POS_SOLID);
1231   }
1232   /* northwest or northeast. Same as above, but inverted. You can pass from top
1233    * to bottom but not vice versa. */
1234   else
1235   {
1236     if (is_above_line (tile_x, tile_y, gradient, obj_x + delta_x, obj_y + delta_y))
1237       return (POS_NON_SOLID);
1238     else
1239       return (POS_SOLID);
1240   }
1241
1242 #undef POS_NON_SOLID
1243 #undef POS_SOLID
1244 } /* int check_position_unisolid */
1245
1246 void
1247 Sector::collision_tilemap(collision::Constraints* constraints,
1248                           const Vector& movement, const Rectf& dest,
1249                           MovingObject& object) const
1250 {
1251   // calculate rectangle where the object will move
1252   float x1 = dest.get_left();
1253   float x2 = dest.get_right();
1254   float y1 = dest.get_top();
1255   float y2 = dest.get_bottom();
1256
1257   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1258     TileMap* solids = *i;
1259
1260     // test with all tiles in this rectangle
1261     Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1262
1263     for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1264       for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1265         const Tile* tile = solids->get_tile(x, y);
1266         if(!tile)
1267           continue;
1268         // skip non-solid tiles
1269         if((tile->getAttributes() & Tile::SOLID) == 0)
1270           continue;
1271         Rectf tile_bbox = solids->get_tile_bbox(x, y);
1272
1273         // only handle unisolid when the player is falling down and when he was
1274         // above the tile before
1275         if(tile->getAttributes() & Tile::UNISOLID) {
1276           int status;
1277
1278           /* Check if the tile is solid given the current movement. This works
1279            * for south-slopes (which are solid when moving "down") and
1280            * north-slopes (which are solid when moving "up". "up" and "down" is
1281            * in quotation marks because because the slope's gradient is taken
1282            * Also, this uses the movement relative to the tilemaps own movement
1283            * (if any).  --octo */
1284           status = check_movement_unisolid (movement - solids->get_movement (), tile);
1285           /* If zero is returned, the unisolid tile is non-solid. */
1286           if (status == 0)
1287             continue;
1288
1289           /* Check whether the object is already *in* the tile. If so, the tile
1290            * is non-solid. Otherwise, if the object is "above" (south slopes)
1291            * or "below" (north slopes), the tile will be solid. */
1292           status = check_position_unisolid (object.get_bbox(), tile_bbox, tile);
1293           if (status == 0)
1294             continue;
1295         }
1296
1297         if(tile->getAttributes() & Tile::SLOPE) { // slope tile
1298           AATriangle triangle;
1299           int slope_data = tile->getData();
1300           if (solids->get_drawing_effect() == VERTICAL_FLIP)
1301             slope_data = AATriangle::vertical_flip(slope_data);
1302           triangle = AATriangle(tile_bbox, slope_data);
1303
1304           collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
1305         } else { // normal rectangular tile
1306           check_collisions(constraints, movement, dest, tile_bbox, NULL, NULL, solids->get_movement());
1307         }
1308       }
1309     }
1310   }
1311 }
1312
1313 uint32_t
1314 Sector::collision_tile_attributes(const Rectf& dest) const
1315 {
1316   float x1 = dest.p1.x;
1317   float y1 = dest.p1.y;
1318   float x2 = dest.p2.x;
1319   float y2 = dest.p2.y;
1320
1321   uint32_t result = 0;
1322   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1323     TileMap* solids = *i;
1324
1325     // test with all tiles in this rectangle
1326     Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1327     // For ice (only), add a little fudge to recognize tiles Tux is standing on.
1328     Rect test_tiles_ice = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2 + SHIFT_DELTA));
1329
1330     for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1331       int y;
1332       for(y = test_tiles.top; y < test_tiles.bottom; ++y) {
1333         const Tile* tile = solids->get_tile(x, y);
1334         if(!tile)
1335           continue;
1336         result |= tile->getAttributes();
1337       }
1338       for(; y < test_tiles_ice.bottom; ++y) {
1339         const Tile* tile = solids->get_tile(x, y);
1340         if(!tile)
1341           continue;
1342         result |= (tile->getAttributes() & Tile::ICE);
1343       }
1344     }
1345   }
1346
1347   return result;
1348 }
1349
1350 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1351 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1352                            Vector& normal)
1353 {
1354   float itop = r1.get_bottom() - r2.get_top();
1355   float ibottom = r2.get_bottom() - r1.get_top();
1356   float ileft = r1.get_right() - r2.get_left();
1357   float iright = r2.get_right() - r1.get_left();
1358
1359   float vert_penetration = std::min(itop, ibottom);
1360   float horiz_penetration = std::min(ileft, iright);
1361   if(vert_penetration < horiz_penetration) {
1362     if(itop < ibottom) {
1363       hit.bottom = true;
1364       normal.y = vert_penetration;
1365     } else {
1366       hit.top = true;
1367       normal.y = -vert_penetration;
1368     }
1369   } else {
1370     if(ileft < iright) {
1371       hit.right = true;
1372       normal.x = horiz_penetration;
1373     } else {
1374       hit.left = true;
1375       normal.x = -horiz_penetration;
1376     }
1377   }
1378 }
1379
1380 void
1381 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1382 {
1383   using namespace collision;
1384
1385   const Rectf& r1 = object1->dest;
1386   const Rectf& r2 = object2->dest;
1387
1388   CollisionHit hit;
1389   if(intersects(object1->dest, object2->dest)) {
1390     Vector normal;
1391     get_hit_normal(r1, r2, hit, normal);
1392
1393     if(!object1->collides(*object2, hit))
1394       return;
1395     std::swap(hit.left, hit.right);
1396     std::swap(hit.top, hit.bottom);
1397     if(!object2->collides(*object1, hit))
1398       return;
1399     std::swap(hit.left, hit.right);
1400     std::swap(hit.top, hit.bottom);
1401
1402     HitResponse response1 = object1->collision(*object2, hit);
1403     std::swap(hit.left, hit.right);
1404     std::swap(hit.top, hit.bottom);
1405     HitResponse response2 = object2->collision(*object1, hit);
1406     if(response1 == CONTINUE && response2 == CONTINUE) {
1407       normal *= (0.5 + DELTA);
1408       object1->dest.move(-normal);
1409       object2->dest.move(normal);
1410     } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1411       normal *= (1 + DELTA);
1412       object1->dest.move(-normal);
1413     } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1414       normal *= (1 + DELTA);
1415       object2->dest.move(normal);
1416     }
1417   }
1418 }
1419
1420 void
1421 Sector::collision_static(collision::Constraints* constraints,
1422                          const Vector& movement, const Rectf& dest,
1423                          MovingObject& object)
1424 {
1425   collision_tilemap(constraints, movement, dest, object);
1426
1427   // collision with other (static) objects
1428   for(MovingObjects::iterator i = moving_objects.begin();
1429       i != moving_objects.end(); ++i) {
1430     MovingObject* moving_object = *i;
1431     if(moving_object->get_group() != COLGROUP_STATIC
1432        && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1433       continue;
1434     if(!moving_object->is_valid())
1435       continue;
1436
1437     if(moving_object != &object)
1438       check_collisions(constraints, movement, dest, moving_object->bbox,
1439                        &object, moving_object);
1440   }
1441 }
1442
1443 void
1444 Sector::collision_static_constrains(MovingObject& object)
1445 {
1446   using namespace collision;
1447   float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1448
1449   Constraints constraints;
1450   Vector movement = object.get_movement();
1451   Rectf& dest = object.dest;
1452   float owidth = object.get_bbox().get_width();
1453   float oheight = object.get_bbox().get_height();
1454
1455   for(int i = 0; i < 2; ++i) {
1456     collision_static(&constraints, Vector(0, movement.y), dest, object);
1457     if(!constraints.has_constraints())
1458       break;
1459
1460     // apply calculated horizontal constraints
1461     if(constraints.bottom < infinity) {
1462       float height = constraints.bottom - constraints.top;
1463       if(height < oheight) {
1464         // we're crushed, but ignore this for now, we'll get this again
1465         // later if we're really crushed or things will solve itself when
1466         // looking at the vertical constraints
1467       }
1468       dest.p2.y = constraints.bottom - DELTA;
1469       dest.p1.y = dest.p2.y - oheight;
1470     } else if(constraints.top > -infinity) {
1471       dest.p1.y = constraints.top + DELTA;
1472       dest.p2.y = dest.p1.y + oheight;
1473     }
1474   }
1475   if(constraints.has_constraints()) {
1476     if(constraints.hit.bottom) {
1477       dest.move(constraints.ground_movement);
1478     }
1479     if(constraints.hit.top || constraints.hit.bottom) {
1480       constraints.hit.left = false;
1481       constraints.hit.right = false;
1482       object.collision_solid(constraints.hit);
1483     }
1484   }
1485
1486   constraints = Constraints();
1487   for(int i = 0; i < 2; ++i) {
1488     collision_static(&constraints, movement, dest, object);
1489     if(!constraints.has_constraints())
1490       break;
1491
1492     // apply calculated vertical constraints
1493     float width = constraints.right - constraints.left;
1494     if(width < infinity) {
1495       if(width + SHIFT_DELTA < owidth) {
1496 #if 0
1497         printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1498                constraints.left, constraints.right);
1499 #endif
1500         CollisionHit h;
1501         h.left = true;
1502         h.right = true;
1503         h.crush = true;
1504         object.collision_solid(h);
1505       } else {
1506         float xmid = (constraints.left + constraints.right) / 2;
1507         dest.p1.x = xmid - owidth/2;
1508         dest.p2.x = xmid + owidth/2;
1509       }
1510     } else if(constraints.right < infinity) {
1511       dest.p2.x = constraints.right - DELTA;
1512       dest.p1.x = dest.p2.x - owidth;
1513     } else if(constraints.left > -infinity) {
1514       dest.p1.x = constraints.left + DELTA;
1515       dest.p2.x = dest.p1.x + owidth;
1516     }
1517   }
1518
1519   if(constraints.has_constraints()) {
1520     if( constraints.hit.left || constraints.hit.right
1521         || constraints.hit.top || constraints.hit.bottom
1522         || constraints.hit.crush )
1523       object.collision_solid(constraints.hit);
1524   }
1525
1526   // an extra pass to make sure we're not crushed horizontally
1527   constraints = Constraints();
1528   collision_static(&constraints, movement, dest, object);
1529   if(constraints.bottom < infinity) {
1530     float height = constraints.bottom - constraints.top;
1531     if(height + SHIFT_DELTA < oheight) {
1532 #if 0
1533       printf("Object %p crushed vertically...\n", &object);
1534 #endif
1535       CollisionHit h;
1536       h.top = true;
1537       h.bottom = true;
1538       h.crush = true;
1539       object.collision_solid(h);
1540     }
1541   }
1542 }
1543
1544 namespace {
1545 const float MAX_SPEED = 16.0f;
1546 }
1547
1548 void
1549 Sector::handle_collisions()
1550 {
1551   using namespace collision;
1552
1553   // calculate destination positions of the objects
1554   for(MovingObjects::iterator i = moving_objects.begin();
1555       i != moving_objects.end(); ++i) {
1556     MovingObject* moving_object = *i;
1557     Vector mov = moving_object->get_movement();
1558
1559     // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1560     if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1561       moving_object->movement = mov.unit() * MAX_SPEED;
1562       //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1563     }
1564
1565     moving_object->dest = moving_object->get_bbox();
1566     moving_object->dest.move(moving_object->get_movement());
1567   }
1568
1569   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1570   for(MovingObjects::iterator i = moving_objects.begin();
1571       i != moving_objects.end(); ++i) {
1572     MovingObject* moving_object = *i;
1573     if((moving_object->get_group() != COLGROUP_MOVING
1574         && moving_object->get_group() != COLGROUP_MOVING_STATIC
1575         && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1576        || !moving_object->is_valid())
1577       continue;
1578
1579     collision_static_constrains(*moving_object);
1580   }
1581
1582   // part2: COLGROUP_MOVING vs tile attributes
1583   for(MovingObjects::iterator i = moving_objects.begin();
1584       i != moving_objects.end(); ++i) {
1585     MovingObject* moving_object = *i;
1586     if((moving_object->get_group() != COLGROUP_MOVING
1587         && moving_object->get_group() != COLGROUP_MOVING_STATIC
1588         && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1589        || !moving_object->is_valid())
1590       continue;
1591
1592     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1593     if(tile_attributes >= Tile::FIRST_INTERESTING_FLAG) {
1594       moving_object->collision_tile(tile_attributes);
1595     }
1596   }
1597
1598   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1599   for(MovingObjects::iterator i = moving_objects.begin();
1600       i != moving_objects.end(); ++i) {
1601     MovingObject* moving_object = *i;
1602     if((moving_object->get_group() != COLGROUP_MOVING
1603         && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1604        || !moving_object->is_valid())
1605       continue;
1606
1607     for(MovingObjects::iterator i2 = moving_objects.begin();
1608         i2 != moving_objects.end(); ++i2) {
1609       MovingObject* moving_object_2 = *i2;
1610       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1611          || !moving_object_2->is_valid())
1612         continue;
1613
1614       if(intersects(moving_object->dest, moving_object_2->dest)) {
1615         Vector normal;
1616         CollisionHit hit;
1617         get_hit_normal(moving_object->dest, moving_object_2->dest,
1618                        hit, normal);
1619         if(!moving_object->collides(*moving_object_2, hit))
1620           continue;
1621         if(!moving_object_2->collides(*moving_object, hit))
1622           continue;
1623
1624         moving_object->collision(*moving_object_2, hit);
1625         moving_object_2->collision(*moving_object, hit);
1626       }
1627     }
1628   }
1629
1630   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1631   for(MovingObjects::iterator i = moving_objects.begin();
1632       i != moving_objects.end(); ++i) {
1633     MovingObject* moving_object = *i;
1634
1635     if((moving_object->get_group() != COLGROUP_MOVING
1636         && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1637        || !moving_object->is_valid())
1638       continue;
1639
1640     for(MovingObjects::iterator i2 = i+1;
1641         i2 != moving_objects.end(); ++i2) {
1642       MovingObject* moving_object_2 = *i2;
1643       if((moving_object_2->get_group() != COLGROUP_MOVING
1644           && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1645          || !moving_object_2->is_valid())
1646         continue;
1647
1648       collision_object(moving_object, moving_object_2);
1649     }
1650   }
1651
1652   // apply object movement
1653   for(MovingObjects::iterator i = moving_objects.begin();
1654       i != moving_objects.end(); ++i) {
1655     MovingObject* moving_object = *i;
1656
1657     moving_object->bbox = moving_object->dest;
1658     moving_object->movement = Vector(0, 0);
1659   }
1660 }
1661
1662 bool
1663 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1664 {
1665   using namespace collision;
1666
1667   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1668     TileMap* solids = *i;
1669
1670     // test with all tiles in this rectangle
1671     Rect test_tiles = solids->get_tiles_overlapping(rect);
1672
1673     for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1674       for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1675         const Tile* tile = solids->get_tile(x, y);
1676         if(!tile) continue;
1677         if(!(tile->getAttributes() & Tile::SOLID))
1678           continue;
1679         if((tile->getAttributes() & Tile::UNISOLID) && ignoreUnisolid)
1680           continue;
1681         if(tile->getAttributes() & Tile::SLOPE) {
1682           AATriangle triangle;
1683           Rectf tbbox = solids->get_tile_bbox(x, y);
1684           triangle = AATriangle(tbbox, tile->getData());
1685           Constraints constraints;
1686           if(!collision::rectangle_aatriangle(&constraints, rect, triangle))
1687             continue;
1688         }
1689         // We have a solid tile that overlaps the given rectangle.
1690         return false;
1691       }
1692     }
1693   }
1694
1695   return true;
1696 }
1697
1698 bool
1699 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1700 {
1701   using namespace collision;
1702
1703   if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1704
1705   for(MovingObjects::const_iterator i = moving_objects.begin();
1706       i != moving_objects.end(); ++i) {
1707     const MovingObject* moving_object = *i;
1708     if (moving_object == ignore_object) continue;
1709     if (!moving_object->is_valid()) continue;
1710     if (moving_object->get_group() == COLGROUP_STATIC) {
1711       if(intersects(rect, moving_object->get_bbox())) return false;
1712     }
1713   }
1714
1715   return true;
1716 }
1717
1718 bool
1719 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1720 {
1721   using namespace collision;
1722
1723   if (!is_free_of_tiles(rect)) return false;
1724
1725   for(MovingObjects::const_iterator i = moving_objects.begin();
1726       i != moving_objects.end(); ++i) {
1727     const MovingObject* moving_object = *i;
1728     if (moving_object == ignore_object) continue;
1729     if (!moving_object->is_valid()) continue;
1730     if ((moving_object->get_group() == COLGROUP_MOVING)
1731         || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1732         || (moving_object->get_group() == COLGROUP_STATIC)) {
1733       if(intersects(rect, moving_object->get_bbox())) return false;
1734     }
1735   }
1736
1737   return true;
1738 }
1739
1740 bool
1741 Sector::add_bullet(const Vector& pos, const PlayerStatus* player_status, float xm, Direction dir)
1742 {
1743   // TODO remove this function and move these checks elsewhere...
1744
1745   Bullet* new_bullet = 0;
1746   if((player_status->bonus == FIRE_BONUS &&
1747       (int)bullets.size() >= player_status->max_fire_bullets) ||
1748      (player_status->bonus == ICE_BONUS &&
1749       (int)bullets.size() >= player_status->max_ice_bullets))
1750     return false;
1751   new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1752   add_object(new_bullet);
1753
1754   sound_manager->play("sounds/shoot.wav");
1755
1756   return true;
1757 }
1758
1759 bool
1760 Sector::add_smoke_cloud(const Vector& pos)
1761 {
1762   add_object(new SmokeCloud(pos));
1763   return true;
1764 }
1765
1766 void
1767 Sector::play_music(MusicType type)
1768 {
1769   currentmusic = type;
1770   switch(currentmusic) {
1771     case LEVEL_MUSIC:
1772       sound_manager->play_music(music);
1773       break;
1774     case HERRING_MUSIC:
1775       sound_manager->play_music("music/invincible.music");
1776       break;
1777     case HERRING_WARNING_MUSIC:
1778       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1779       break;
1780     default:
1781       sound_manager->play_music("");
1782       break;
1783   }
1784 }
1785
1786 MusicType
1787 Sector::get_music_type()
1788 {
1789   return currentmusic;
1790 }
1791
1792 int
1793 Sector::get_total_badguys()
1794 {
1795   int total_badguys = 0;
1796   for(GameObjects::iterator i = gameobjects.begin();
1797       i != gameobjects.end(); ++i) {
1798     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1799     if (badguy && badguy->countMe)
1800       total_badguys++;
1801   }
1802
1803   return total_badguys;
1804 }
1805
1806 bool
1807 Sector::inside(const Rectf& rect) const
1808 {
1809   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1810     TileMap* solids = *i;
1811
1812     Rectf bbox = solids->get_bbox();
1813     bbox.p1.y = -INFINITY; // pretend the tilemap extends infinitely far upwards
1814
1815     if (bbox.contains(rect))
1816       return true;
1817   }
1818   return false;
1819 }
1820
1821 float
1822 Sector::get_width() const
1823 {
1824   float width = 0;
1825   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1826       i != solid_tilemaps.end(); i++) {
1827     TileMap* solids = *i;
1828     width = std::max(width, solids->get_bbox().get_right());
1829   }
1830
1831   return width;
1832 }
1833
1834 float
1835 Sector::get_height() const
1836 {
1837   float height = 0;
1838   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1839       i != solid_tilemaps.end(); i++) {
1840     TileMap* solids = *i;
1841     height = std::max(height, solids->get_bbox().get_bottom());
1842   }
1843
1844   return height;
1845 }
1846
1847 void
1848 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1849 {
1850   for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1851     TileMap* solids = *i;
1852     solids->change_all(old_tile_id, new_tile_id);
1853   }
1854 }
1855
1856 void
1857 Sector::set_ambient_light(float red, float green, float blue)
1858 {
1859   ambient_light.red = red;
1860   ambient_light.green = green;
1861   ambient_light.blue = blue;
1862 }
1863
1864 float
1865 Sector::get_ambient_red()
1866 {
1867   return ambient_light.red;
1868 }
1869
1870 float
1871 Sector::get_ambient_green()
1872 {
1873   return ambient_light.green;
1874 }
1875
1876 float
1877 Sector::get_ambient_blue()
1878 {
1879   return ambient_light.blue;
1880 }
1881
1882 void
1883 Sector::set_gravity(float gravity)
1884 {
1885   log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1886   this->gravity = gravity;
1887 }
1888
1889 float
1890 Sector::get_gravity() const
1891 {
1892   return gravity;
1893 }
1894
1895 /* EOF */