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