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