fade out console
[supertux.git] / src / sector.cpp
1 //  $Id$
2 //
3 //  SuperTux -  A Jump'n Run
4 //  Copyright (C) 2004 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
30 #include "sector.hpp"
31 #include "player_status.hpp"
32 #include "object/gameobjs.hpp"
33 #include "object/camera.hpp"
34 #include "object/background.hpp"
35 #include "object/gradient.hpp"
36 #include "object/particlesystem.hpp"
37 #include "object/particlesystem_interactive.hpp"
38 #include "object/tilemap.hpp"
39 #include "lisp/parser.hpp"
40 #include "lisp/lisp.hpp"
41 #include "lisp/writer.hpp"
42 #include "lisp/list_iterator.hpp"
43 #include "tile.hpp"
44 #include "audio/sound_manager.hpp"
45 #include "game_session.hpp"
46 #include "resources.hpp"
47 #include "statistics.hpp"
48 #include "collision_grid.hpp"
49 #include "collision_grid_iterator.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 "badguy/jumpy.hpp"
61 #include "trigger/sequence_trigger.hpp"
62 #include "player_status.hpp"
63 #include "script_manager.hpp"
64 #include "scripting/wrapper_util.hpp"
65 #include "script_interface.hpp"
66 #include "log.hpp"
67
68 Sector* Sector::_current = 0;
69
70 Sector::Sector()
71   : currentmusic(LEVEL_MUSIC), gravity(10),
72     player(0), solids(0), camera(0)
73 {
74   add_object(new Player(player_status));
75   add_object(new DisplayEffect());
76   add_object(new TextObject());
77
78 #ifdef USE_GRID
79   grid.reset(new CollisionGrid(32000, 32000));
80 #endif
81
82   script_manager.reset(new ScriptManager(ScriptManager::instance));
83
84   // create a new squirrel table for the sector
85   HSQUIRRELVM vm = ScriptManager::instance->get_vm();
86   
87   sq_newtable(vm);
88   sq_pushroottable(vm);
89   if(SQ_FAILED(sq_setdelegate(vm, -2)))
90     throw Scripting::SquirrelError(vm, "Couldn't set sector_table delegate");
91
92   sq_resetobject(&sector_table);
93   if(SQ_FAILED(sq_getstackobj(vm, -1, &sector_table)))
94     throw Scripting::SquirrelError(vm, "Couldn't get sector table");
95   sq_addref(vm, &sector_table);
96   sq_pop(vm, 1);
97 }
98
99 Sector::~Sector()
100 {
101   deactivate();
102   
103   script_manager.reset(NULL);
104   sq_release(ScriptManager::instance->get_vm(), &sector_table);
105  
106   update_game_objects();
107   assert(gameobjects_new.size() == 0);
108
109   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
110       ++i) {
111     before_object_remove(*i);
112     delete *i;
113   }
114
115   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
116       ++i)
117     delete *i;
118 }
119
120 GameObject*
121 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
122 {
123   if(name == "camera") {
124     Camera* camera = new Camera(this);
125     camera->parse(reader);
126     return camera;
127   } else if(name == "particles-snow") {
128     SnowParticleSystem* partsys = new SnowParticleSystem();
129     partsys->parse(reader);
130     return partsys;
131   } else if(name == "particles-rain") {
132     RainParticleSystem* partsys = new RainParticleSystem();
133     partsys->parse(reader);
134     return partsys;
135   } else if(name == "particles-comets") {
136     CometParticleSystem* partsys = new CometParticleSystem();
137     partsys->parse(reader);
138     return partsys;
139   } else if(name == "particles-ghosts") {
140     GhostParticleSystem* partsys = new GhostParticleSystem();
141     partsys->parse(reader);
142     return partsys;
143   } else if(name == "particles-clouds") {
144     CloudParticleSystem* partsys = new CloudParticleSystem();
145     partsys->parse(reader);
146     return partsys;
147   } else if(name == "money") { // for compatibility with old maps
148     return new Jumpy(reader);
149   } 
150
151   try {
152     return create_object(name, reader);
153   } catch(std::exception& e) {
154     log_warning << e.what() << "" << std::endl;
155   }
156   
157   return 0;
158 }
159
160 void
161 Sector::parse(const lisp::Lisp& sector)
162 {  
163   lisp::ListIterator iter(&sector);
164   while(iter.next()) {
165     const std::string& token = iter.item();
166     if(token == "name") {
167       iter.value()->get(name);
168     } else if(token == "gravity") {
169       iter.value()->get(gravity);
170     } else if(token == "music") {
171       iter.value()->get(music);
172     } else if(token == "spawnpoint") {
173       SpawnPoint* sp = new SpawnPoint(iter.lisp());
174       spawnpoints.push_back(sp);
175     } else if(token == "init-script") {
176       iter.value()->get(init_script);
177     } else {
178       GameObject* object = parse_object(token, *(iter.lisp()));
179       if(object) {
180         add_object(object);
181       }
182     }
183   }
184
185   update_game_objects();
186
187   if(!solids)
188     throw std::runtime_error("sector does not contain a solid tile layer.");
189
190   fix_old_tiles();
191   if(!camera) {
192     log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
193     update_game_objects();
194     add_object(new Camera(this));
195   }
196
197   update_game_objects();
198 }
199
200 void
201 Sector::parse_old_format(const lisp::Lisp& reader)
202 {
203   name = "main";
204   reader.get("gravity", gravity);
205
206   std::string backgroundimage;
207   reader.get("background", backgroundimage);
208   float bgspeed = .5;
209   reader.get("bkgd_speed", bgspeed);
210   bgspeed /= 100;
211
212   Color bkgd_top, bkgd_bottom;
213   int r = 0, g = 0, b = 128;
214   reader.get("bkgd_red_top", r);
215   reader.get("bkgd_green_top",  g);
216   reader.get("bkgd_blue_top",  b);
217   bkgd_top.red = static_cast<float> (r) / 255.0f;
218   bkgd_top.green = static_cast<float> (g) / 255.0f;
219   bkgd_top.blue = static_cast<float> (b) / 255.0f;
220   
221   reader.get("bkgd_red_bottom",  r);
222   reader.get("bkgd_green_bottom", g);
223   reader.get("bkgd_blue_bottom", b);
224   bkgd_bottom.red = static_cast<float> (r) / 255.0f;
225   bkgd_bottom.green = static_cast<float> (g) / 255.0f;
226   bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
227   
228   if(backgroundimage != "") {
229     Background* background = new Background();
230     background->set_image(
231             std::string("images/background/") + backgroundimage, bgspeed);
232     add_object(background);
233   } else {
234     Gradient* gradient = new Gradient();
235     gradient->set_gradient(bkgd_top, bkgd_bottom);
236     add_object(gradient);
237   }
238
239   std::string particlesystem;
240   reader.get("particle_system", particlesystem);
241   if(particlesystem == "clouds")
242     add_object(new CloudParticleSystem());
243   else if(particlesystem == "snow")
244     add_object(new SnowParticleSystem());
245   else if(particlesystem == "rain")
246     add_object(new RainParticleSystem());
247
248   Vector startpos(100, 170);
249   reader.get("start_pos_x", startpos.x);
250   reader.get("start_pos_y", startpos.y);
251
252   SpawnPoint* spawn = new SpawnPoint;
253   spawn->pos = startpos;
254   spawn->name = "main";
255   spawnpoints.push_back(spawn);
256
257   music = "chipdisko.ogg";
258   reader.get("music", music);
259   music = "music/" + music;
260
261   int width = 30, height = 15;
262   reader.get("width", width);
263   reader.get("height", height);
264   
265   std::vector<unsigned int> tiles;
266   if(reader.get_vector("interactive-tm", tiles)
267       || reader.get_vector("tilemap", tiles)) {
268     TileMap* tilemap = new TileMap();
269     tilemap->set(width, height, tiles, LAYER_TILES, true);
270     add_object(tilemap);
271   }
272
273   if(reader.get_vector("background-tm", tiles)) {
274     TileMap* tilemap = new TileMap();
275     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
276     add_object(tilemap);
277   }
278
279   if(reader.get_vector("foreground-tm", tiles)) {
280     TileMap* tilemap = new TileMap();
281     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
282     add_object(tilemap);
283   }
284
285   // read reset-points (now spawn-points)
286   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
287   if(resetpoints) {
288     lisp::ListIterator iter(resetpoints);
289     while(iter.next()) {
290       if(iter.item() == "point") {
291         Vector sp_pos;
292         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
293           {
294           SpawnPoint* sp = new SpawnPoint;
295           sp->name = "main";
296           sp->pos = sp_pos;
297           spawnpoints.push_back(sp);
298           }
299       } else {
300         log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
301       }
302     }
303   }
304
305   // read objects
306   const lisp::Lisp* objects = reader.get_lisp("objects");
307   if(objects) {
308     lisp::ListIterator iter(objects);
309     while(iter.next()) {
310       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
311       if(object) {
312         add_object(object);
313       } else {
314         log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
315       }
316     }
317   }
318
319   // add a camera
320   Camera* camera = new Camera(this);
321   add_object(camera);
322
323   update_game_objects();
324
325   if(solids == 0)
326     throw std::runtime_error("sector does not contain a solid tile layer.");
327
328   fix_old_tiles();
329   update_game_objects();
330 }
331
332 void
333 Sector::fix_old_tiles()
334 {
335   // hack for now...
336   for(size_t x=0; x < solids->get_width(); ++x) {
337     for(size_t y=0; y < solids->get_height(); ++y) {
338       const Tile* tile = solids->get_tile(x, y);
339       Vector pos(x*32, y*32);
340       
341       if(tile->getID() == 112) {
342         add_object(new InvisibleBlock(pos));
343         solids->change(x, y, 0);
344       } else if(tile->getAttributes() & Tile::COIN) {
345         add_object(new Coin(pos));
346         solids->change(x, y, 0);
347       } else if(tile->getAttributes() & Tile::FULLBOX) {
348         add_object(new BonusBlock(pos, tile->getData()));
349         solids->change(x, y, 0);
350       } else if(tile->getAttributes() & Tile::BRICK) {
351         add_object(new Brick(pos, tile->getData()));
352         solids->change(x, y, 0);
353       } else if(tile->getAttributes() & Tile::GOAL) {
354         std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
355         add_object(new SequenceTrigger(pos, sequence));
356         solids->change(x, y, 0);
357       }
358     }
359   }
360 }
361
362 void
363 Sector::write(lisp::Writer& writer)
364 {
365   writer.write_string("name", name);
366   writer.write_float("gravity", gravity);
367   writer.write_string("music", music);
368
369   // write spawnpoints
370   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
371       ++i) {
372     SpawnPoint* spawn = *i;
373     writer.start_list("spawn-points");
374     writer.write_string("name", spawn->name);
375     writer.write_float("x", spawn->pos.x);
376     writer.write_float("y", spawn->pos.y);
377     writer.end_list("spawn-points");
378   }
379
380   // write objects
381   for(GameObjects::iterator i = gameobjects.begin();
382       i != gameobjects.end(); ++i) {
383     Serializable* serializable = dynamic_cast<Serializable*> (*i);
384     if(serializable)
385       serializable->write(writer);
386   }
387 }
388
389 HSQUIRRELVM
390 Sector::run_script(std::istream& in, const std::string& sourcename)
391 {
392   // create new thread and keep a weakref
393   HSQUIRRELVM vm = script_manager->create_thread();
394
395   // set sector_table as roottable for the thread
396   sq_pushobject(vm, sector_table);
397   sq_setroottable(vm);
398
399   Scripting::compile_and_run(vm, in, sourcename);
400
401   return vm;
402 }
403
404 void
405 Sector::add_object(GameObject* object)
406 {
407   // make sure the object isn't already in the list
408 #ifdef DEBUG
409   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
410       ++i) {
411     if(*i == object) {
412       assert("object already added to sector" == 0);
413     }
414   }
415   for(GameObjects::iterator i = gameobjects_new.begin();
416       i != gameobjects_new.end(); ++i) {
417     if(*i == object) {
418       assert("object already added to sector" == 0);
419     }
420   }
421 #endif
422
423   gameobjects_new.push_back(object);
424 }
425
426 void
427 Sector::activate(const std::string& spawnpoint)
428 {
429   SpawnPoint* sp = 0;
430   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
431       ++i) {
432     if((*i)->name == spawnpoint) {
433       sp = *i;
434       break;
435     }
436   }                                                                           
437   if(!sp) {
438     log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
439     if(spawnpoint != "main") {
440       activate("main");
441     } else {
442       activate(Vector(0, 0));
443     }
444   } else {
445     activate(sp->pos);
446   }
447 }
448
449 void
450 Sector::activate(const Vector& player_pos)
451 {
452   if(_current != this) {
453     if(_current != NULL)
454       _current->deactivate();
455     _current = this;
456
457     // register sectortable as current_sector in scripting
458     HSQUIRRELVM vm = ScriptManager::instance->get_vm();
459     sq_pushroottable(vm);
460     sq_pushstring(vm, "sector", -1);
461     sq_pushobject(vm, sector_table);
462     if(SQ_FAILED(sq_createslot(vm, -3)))
463       throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
464     sq_pop(vm, 1);
465
466     for(GameObjects::iterator i = gameobjects.begin();
467         i != gameobjects.end(); ++i) {
468       GameObject* object = *i;
469
470       try_expose(object);
471     }
472   }
473
474   player->move(player_pos);
475   camera->reset(player->get_pos());
476   update_game_objects();
477
478   // Run init script
479   if(init_script != "") {
480     std::istringstream in(init_script);
481     run_script(in, std::string("Sector(") + name + ") - init");
482   }
483 }
484
485 void
486 Sector::deactivate()
487 {
488   if(_current != this)
489     return;
490
491   // remove sector entry from global vm
492   HSQUIRRELVM vm = ScriptManager::instance->get_vm();
493   sq_pushroottable(vm);
494   sq_pushstring(vm, "sector", -1);
495   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
496     throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
497   sq_pop(vm, 1);
498   
499   for(GameObjects::iterator i = gameobjects.begin();
500       i != gameobjects.end(); ++i) {
501     GameObject* object = *i;
502     
503     try_unexpose(object);
504   }
505
506   _current = NULL;
507 }
508
509 Rect
510 Sector::get_active_region()
511 {
512   return Rect(
513     camera->get_translation() - Vector(1600, 1200),
514     camera->get_translation() + Vector(1600, 1200));
515 }
516
517 void
518 Sector::update(float elapsed_time)
519 {
520   script_manager->update();
521
522   player->check_bounds(camera);
523
524 #if 0
525   CollisionGridIterator iter(*grid, get_active_region());
526   while(MovingObject* object = iter.next()) {
527     if(!object->is_valid())
528       continue;
529
530     object->update(elapsed_time);
531   }
532 #else
533   /* update objects */
534   for(GameObjects::iterator i = gameobjects.begin();
535           i != gameobjects.end(); ++i) {
536     GameObject* object = *i;
537     if(!object->is_valid())
538       continue;
539     
540     object->update(elapsed_time);
541   }
542 #endif
543   
544   /* Handle all possible collisions. */
545   handle_collisions();
546   update_game_objects();
547 }
548
549 void
550 Sector::update_game_objects()
551 {
552   /** cleanup marked objects */
553   for(std::vector<Bullet*>::iterator i = bullets.begin();
554       i != bullets.end(); /* nothing */) {
555     Bullet* bullet = *i;
556     if(bullet->is_valid()) {
557       ++i;
558       continue;
559     }
560
561     i = bullets.erase(i);
562   }
563   for(MovingObjects::iterator i = moving_objects.begin();
564       i != moving_objects.end(); /* nothing */) {
565     MovingObject* moving_object = *i;
566     if(moving_object->is_valid()) {
567       ++i;
568       continue;
569     }
570
571 #ifdef USE_GRID
572     grid->remove_object(moving_object);
573 #endif
574     
575     i = moving_objects.erase(i);
576   }
577   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
578       i != gameobjects.end(); /* nothing */) {
579     GameObject* object = *i;
580     
581     if(object->is_valid()) {
582       ++i;
583       continue;
584     }
585
586     before_object_remove(object);
587     
588     delete *i;
589     i = gameobjects.erase(i);
590   }
591
592   /* add newly created objects */
593   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
594       i != gameobjects_new.end(); ++i)
595   {
596     GameObject* object = *i;
597
598     before_object_add(object);
599     
600     gameobjects.push_back(object);
601   }
602   gameobjects_new.clear();
603 }
604
605 bool
606 Sector::before_object_add(GameObject* object)
607 {
608   Bullet* bullet = dynamic_cast<Bullet*> (object);
609   if(bullet)
610     bullets.push_back(bullet);
611
612   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
613   if(movingobject) {
614     moving_objects.push_back(movingobject);
615 #ifdef USE_GRID
616     grid->add_object(movingobject);
617 #endif
618   }
619   
620   TileMap* tilemap = dynamic_cast<TileMap*> (object);
621   if(tilemap && tilemap->is_solid()) {
622     if(solids == 0) {
623       solids = tilemap;
624     } else {
625       log_warning << "Another solid tilemaps added. Ignoring" << std::endl;
626     }
627   }
628
629   Camera* camera = dynamic_cast<Camera*> (object);
630   if(camera) {
631     if(this->camera != 0) {
632       log_warning << "Multiple cameras added. Ignoring" << std::endl;
633       return false;
634     }
635     this->camera = camera;
636   }
637
638   Player* player = dynamic_cast<Player*> (object);
639   if(player) {
640     if(this->player != 0) {
641       log_warning << "Multiple players added. Ignoring" << std::endl;
642       return false;
643     }
644     this->player = player;
645   }
646
647   if(_current == this) {
648     try_expose(object);
649   }
650   
651   return true;
652 }
653
654 void
655 Sector::try_expose(GameObject* object)
656 {
657   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
658   if(interface != NULL) {
659     HSQUIRRELVM vm = script_manager->get_vm();
660     sq_pushobject(vm, sector_table);
661     interface->expose(vm, -1);
662     sq_pop(vm, 1);
663   }
664 }
665
666 void
667 Sector::before_object_remove(GameObject* object)
668 {
669   if(_current == this)
670     try_unexpose(object);
671 }
672
673 void
674 Sector::try_unexpose(GameObject* object)
675 {
676   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
677   if(interface != NULL) {
678     HSQUIRRELVM vm = script_manager->get_vm();
679     int oldtop = sq_gettop(vm);
680     sq_pushobject(vm, sector_table);
681     try {
682       interface->unexpose(vm, -1);
683     } catch(std::exception& e) {
684       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
685     }
686     sq_settop(vm, oldtop);
687   }
688
689
690 void
691 Sector::draw(DrawingContext& context)
692 {
693   context.push_transform();
694   context.set_translation(camera->get_translation());
695
696   for(GameObjects::iterator i = gameobjects.begin();
697       i != gameobjects.end(); ++i) {
698     GameObject* object = *i; 
699     if(!object->is_valid())
700       continue;
701     
702     object->draw(context);
703   }
704
705   context.pop_transform();
706 }
707
708 static const float DELTA = .001;
709
710 void
711 Sector::collision_tilemap(const Rect& dest, const Vector& movement,
712                           CollisionHit& hit) const
713 {
714   // calculate rectangle where the object will move
715   float x1 = dest.get_left();
716   float x2 = dest.get_right();
717   float y1 = dest.get_top();
718   float y2 = dest.get_bottom();
719
720   // test with all tiles in this rectangle
721   int starttilex = int(x1) / 32;
722   int starttiley = int(y1) / 32;
723   int max_x = int(x2 + (1 - DELTA));
724   int max_y = int(y2 + (1 - DELTA));
725
726   CollisionHit temphit;
727   for(int x = starttilex; x*32 < max_x; ++x) {
728     for(int y = starttiley; y*32 < max_y; ++y) {
729       const Tile* tile = solids->get_tile(x, y);
730       if(!tile)
731         continue;
732       // skip non-solid tiles
733       if(tile->getAttributes() == 0)
734         continue;
735       // only handle unisolid when the player is falling down and when he was
736       // above the tile before
737       if(tile->getAttributes() & Tile::UNISOLID) {
738         if(movement.y < 0 || dest.get_top() - movement.y > y*32)
739           continue;
740       }
741
742       if(tile->getAttributes() & Tile::SLOPE) { // slope tile
743         AATriangle triangle;
744         Vector p1(x*32, y*32);
745         Vector p2((x+1)*32, (y+1)*32);
746         triangle = AATriangle(p1, p2, tile->getData());
747
748         if(Collision::rectangle_aatriangle(temphit, dest, movement,
749               triangle)) {
750           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
751             hit = temphit;
752           }
753         }
754       } else { // normal rectangular tile
755         Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
756         if(Collision::rectangle_rectangle(temphit, dest, movement, rect)) {
757           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
758             hit = temphit;
759           }
760         }
761       }
762     }
763   }
764 }
765
766 uint32_t
767 Sector::collision_tile_attributes(const Rect& dest) const
768 {
769   /** XXX This function doesn't work correctly as it will check all tiles
770    * in the bounding box of the object movement, this might include tiles
771    * that have actually never been touched by the object
772    * (though this only occures for very fast objects...)
773    */
774  
775 #if 0
776   // calculate rectangle where the object will move
777   float x1, x2;
778   if(object->get_movement().x >= 0) {
779     x1 = object->get_bbox().p1.x;
780     x2 = object->get_bbox().p2.x + object->get_movement().x;
781   } else {
782     x1 = object->get_bbox().p1.x + object->get_movement().x;
783     x2 = object->get_bbox().p2.x;
784   }
785   float y1, y2;
786   if(object->get_movement().y >= 0) {
787     y1 = object->get_bbox().p1.y;
788     y2 = object->get_bbox().p2.y + object->get_movement().y;
789   } else {
790     y1 = object->get_bbox().p1.y + object->get_movement().y;
791     y2 = object->get_bbox().p2.y;
792   }
793 #endif
794   float x1 = dest.p1.x;
795   float y1 = dest.p1.y;
796   float x2 = dest.p2.x;
797   float y2 = dest.p2.y;
798
799   // test with all tiles in this rectangle
800   int starttilex = int(x1) / 32;
801   int starttiley = int(y1) / 32;
802   int max_x = int(x2);
803   int max_y = int(y2);
804
805   uint32_t result = 0;
806   for(int x = starttilex; x*32 < max_x; ++x) {
807     for(int y = starttiley; y*32 < max_y; ++y) {
808       const Tile* tile = solids->get_tile(x, y);
809       if(!tile)
810         continue;
811       result |= tile->getAttributes();
812     }
813   }
814
815   return result;
816 }
817
818 void
819 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
820 {
821   CollisionHit hit;
822
823   Vector movement = object1->get_movement() - object2->get_movement();
824   if(Collision::rectangle_rectangle(hit, object1->dest, movement, object2->dest)) {
825     HitResponse response1 = object1->collision(*object2, hit);
826     hit.normal *= -1;
827     HitResponse response2 = object2->collision(*object1, hit);
828
829     if(response1 != CONTINUE) {
830       if(response1 == ABORT_MOVE)
831         object1->dest = object1->get_bbox();
832       if(response2 == CONTINUE)
833         object2->dest.move(hit.normal * (hit.depth + DELTA));
834     } else if(response2 != CONTINUE) {
835       if(response2 == ABORT_MOVE)
836         object2->dest = object2->get_bbox();
837       if(response1 == CONTINUE)
838         object1->dest.move(-hit.normal * (hit.depth + DELTA));
839     } else {
840       object1->dest.move(-hit.normal * (hit.depth/2 + DELTA));
841       object2->dest.move(hit.normal * (hit.depth/2 + DELTA));
842     }
843   }
844 }
845
846 bool
847 Sector::collision_static(MovingObject* object, const Vector& movement)
848 {
849   GameObject* collided_with = solids;
850   CollisionHit hit;
851   hit.time = -1;
852
853   collision_tilemap(object->dest, movement, hit);
854
855   // collision with other (static) objects
856   CollisionHit temphit;
857   for(MovingObjects::iterator i2 = moving_objects.begin();
858       i2 != moving_objects.end(); ++i2) {
859     MovingObject* moving_object_2 = *i2;
860     if(moving_object_2->get_group() != COLGROUP_STATIC
861         || !moving_object_2->is_valid())
862       continue;
863         
864     Rect dest = moving_object_2->dest;
865
866     Vector rel_movement 
867       = movement - moving_object_2->get_movement();
868
869     if(Collision::rectangle_rectangle(temphit, object->dest, rel_movement, dest)
870         && temphit.time > hit.time) {
871       hit = temphit;
872       collided_with = moving_object_2;
873     }
874   }
875
876   if(hit.time < 0)
877     return true;
878
879   HitResponse response = object->collision(*collided_with, hit);
880   hit.normal *= -1;
881   if(collided_with != solids) {
882     MovingObject* moving_object = (MovingObject*) collided_with;
883     HitResponse other_response = moving_object->collision(*object, hit);
884     if(other_response == ABORT_MOVE) {
885       moving_object->dest = moving_object->get_bbox();
886     } else if(other_response == FORCE_MOVE) {
887       // the static object "wins" move tux out of the collision
888       object->dest.move(-hit.normal * (hit.depth + DELTA));
889       return false;
890     } else if(other_response == PASS_MOVEMENT) {
891       object->dest.move(moving_object->get_movement());
892       //object->movement += moving_object->get_movement();
893     }
894   }
895
896   if(response == CONTINUE) {
897     object->dest.move(-hit.normal * (hit.depth + DELTA));
898     return false;
899   } else if(response == ABORT_MOVE) {
900     object->dest = object->get_bbox();
901     return true;
902   }
903   
904   // force move
905   return false;
906 }
907
908 void
909 Sector::handle_collisions()
910 {
911   // calculate destination positions of the objects
912   for(MovingObjects::iterator i = moving_objects.begin();
913       i != moving_objects.end(); ++i) {
914     MovingObject* moving_object = *i;
915
916     moving_object->dest = moving_object->get_bbox();
917     moving_object->dest.move(moving_object->get_movement());
918   }
919     
920   // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
921   //   we do this up to 4 times and have to sort all results for the smallest
922   //   one before we can continue here
923   for(MovingObjects::iterator i = moving_objects.begin();
924       i != moving_objects.end(); ++i) {
925     MovingObject* moving_object = *i;
926     if((moving_object->get_group() != COLGROUP_MOVING
927           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
928         || !moving_object->is_valid())
929       continue;
930
931     Vector movement = moving_object->get_movement();
932
933     // test if x or y movement is dominant
934     if(fabsf(moving_object->get_movement().x) < fabsf(moving_object->get_movement().y)) {
935
936       // test in x direction first, then y direction
937       moving_object->dest.move(Vector(0, -movement.y));
938       for(int i = 0; i < 2; ++i) {
939         bool res = collision_static(moving_object, Vector(movement.x, 0));
940         if(res)
941           break;
942       }
943       moving_object->dest.move(Vector(0, movement.y));
944       for(int i = 0; i < 2; ++i) {
945         bool res = collision_static(moving_object, Vector(0, movement.y));
946         if(res)
947           break;
948       }
949       
950     } else {
951
952       // test in y direction first, then x direction
953       moving_object->dest.move(Vector(-movement.x, 0));
954       for(int i = 0; i < 2; ++i) {
955         bool res = collision_static(moving_object, Vector(0, movement.y));
956         if(res)
957           break;
958       }
959       moving_object->dest.move(Vector(movement.x, 0)); 
960       for(int i = 0; i < 2; ++i) {
961         bool res = collision_static(moving_object, Vector(movement.x, 0));
962         if(res)
963           break;
964       }
965     }
966   }
967
968   // part2: COLGROUP_MOVING vs tile attributes
969   for(MovingObjects::iterator i = moving_objects.begin();
970       i != moving_objects.end(); ++i) {
971     MovingObject* moving_object = *i;
972     if((moving_object->get_group() != COLGROUP_MOVING
973           && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
974         || !moving_object->is_valid())
975       continue;
976
977     uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
978     if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
979       moving_object->collision_tile(tile_attributes);
980     }
981   }
982
983   // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
984   for(MovingObjects::iterator i = moving_objects.begin();
985       i != moving_objects.end(); ++i) {
986     MovingObject* moving_object = *i;
987     if(moving_object->get_group() != COLGROUP_MOVING
988         || !moving_object->is_valid())
989       continue;
990
991     for(MovingObjects::iterator i2 = moving_objects.begin();
992         i2 != moving_objects.end(); ++i2) {
993       MovingObject* moving_object_2 = *i2;
994       if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
995          || !moving_object_2->is_valid())
996         continue;
997
998       collision_object(moving_object, moving_object_2);
999     } 
1000   }
1001
1002   // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1003   for(MovingObjects::iterator i = moving_objects.begin();
1004       i != moving_objects.end(); ++i) {
1005     MovingObject* moving_object = *i;
1006
1007     if(moving_object->get_group() != COLGROUP_MOVING
1008         || !moving_object->is_valid())
1009       continue;
1010
1011     for(MovingObjects::iterator i2 = i+1;
1012         i2 != moving_objects.end(); ++i2) {
1013       MovingObject* moving_object_2 = *i2;
1014       if(moving_object_2->get_group() != COLGROUP_MOVING
1015          || !moving_object_2->is_valid())
1016         continue;
1017
1018       collision_object(moving_object, moving_object_2);
1019     }    
1020   }
1021
1022   // apply object movement
1023   for(MovingObjects::iterator i = moving_objects.begin();
1024       i != moving_objects.end(); ++i) {
1025     MovingObject* moving_object = *i;
1026
1027     moving_object->bbox = moving_object->dest;
1028     moving_object->movement = Vector(0, 0);
1029   }
1030 }
1031
1032 bool
1033 Sector::is_free_space(const Rect& rect) const
1034 {
1035   // test with all tiles in this rectangle
1036   int starttilex = int(rect.p1.x) / 32;
1037   int starttiley = int(rect.p1.y) / 32;
1038   int max_x = int(rect.p2.x);
1039   int max_y = int(rect.p2.y);
1040
1041   for(int x = starttilex; x*32 < max_x; ++x) {
1042     for(int y = starttiley; y*32 < max_y; ++y) {
1043       const Tile* tile = solids->get_tile(x, y);
1044       if(!tile)
1045         continue;
1046       if(tile->getAttributes() & Tile::SOLID)
1047         return false;
1048     }
1049   }
1050
1051   for(MovingObjects::const_iterator i = moving_objects.begin();
1052       i != moving_objects.end(); ++i) {
1053     const MovingObject* moving_object = *i;
1054     if(moving_object->get_group() != COLGROUP_STATIC
1055         || !moving_object->is_valid())
1056       continue;
1057
1058     if(Collision::intersects(rect, moving_object->get_bbox()))
1059       return false;
1060   }
1061
1062   return true;
1063 }
1064
1065 bool
1066 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1067 {
1068   // TODO remove this function and move these checks elsewhere...
1069   static const size_t MAX_FIRE_BULLETS = 2;
1070   static const size_t MAX_ICE_BULLETS = 1;
1071
1072   Bullet* new_bullet = 0;
1073   if(player_status->bonus == FIRE_BONUS) {
1074     if(bullets.size() > MAX_FIRE_BULLETS-1)
1075       return false;
1076     new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
1077   } else if(player_status->bonus == ICE_BONUS) {
1078     if(bullets.size() > MAX_ICE_BULLETS-1)
1079       return false;
1080     new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
1081   } else {
1082     return false;
1083   }
1084   add_object(new_bullet);
1085
1086   sound_manager->play("sounds/shoot.wav");
1087
1088   return true;
1089 }
1090
1091 bool
1092 Sector::add_smoke_cloud(const Vector& pos)
1093 {
1094   add_object(new SmokeCloud(pos));
1095   return true;
1096 }
1097
1098 void
1099 Sector::add_floating_text(const Vector& pos, const std::string& text)
1100 {
1101   add_object(new FloatingText(pos, text));
1102 }
1103
1104 void
1105 Sector::play_music(MusicType type)
1106 {
1107   currentmusic = type;
1108   switch(currentmusic) {
1109     case LEVEL_MUSIC:
1110       sound_manager->play_music(music);
1111       break;
1112     case HERRING_MUSIC:
1113       sound_manager->play_music("music/salcon.ogg");
1114       break;
1115     case HERRING_WARNING_MUSIC:
1116       sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1117       break;
1118     default:
1119       sound_manager->play_music("");
1120       break;
1121   }
1122 }
1123
1124 MusicType
1125 Sector::get_music_type()
1126 {
1127   return currentmusic;
1128 }
1129
1130 int
1131 Sector::get_total_badguys()
1132 {
1133   int total_badguys = 0;
1134   for(GameObjects::iterator i = gameobjects.begin();
1135       i != gameobjects.end(); ++i) {
1136     BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1137     if (badguy && badguy->countMe)
1138       total_badguys++;
1139   }
1140
1141   return total_badguys;
1142 }
1143
1144 bool
1145 Sector::inside(const Rect& rect) const
1146 {
1147   if(rect.p1.x > solids->get_width() * 32 
1148       || rect.p1.y > solids->get_height() * 32
1149       || rect.p2.x < 0 || rect.p2.y < 0)
1150     return false;
1151
1152   return true;
1153 }