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