small fixes
[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 "scripting/squirrel_util.hpp"
64 #include "script_interface.hpp"
65 #include "log.hpp"
66
67 Sector* Sector::_current = 0;
68
69 bool Sector::show_collrects = false;
70 bool Sector::draw_solids_only = false;
71
72 Sector::Sector(Level* parent)
73   : level(parent), currentmusic(LEVEL_MUSIC), gravity(10),
74     player(0), solids(0), camera(0)
75 {
76   add_object(new Player(player_status));
77   add_object(new DisplayEffect());
78   add_object(new TextObject());
79
80 #ifdef USE_GRID
81   grid.reset(new CollisionGrid(32000, 32000));
82 #endif
83
84   // create a new squirrel table for the sector
85   using namespace Scripting;
86
87   sq_collectgarbage(global_vm);
88
89   sq_newtable(global_vm);
90   sq_pushroottable(global_vm);
91   if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
92     throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
93
94   sq_resetobject(&sector_table);
95   if(SQ_FAILED(sq_getstackobj(global_vm, -1, &sector_table)))
96     throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
97   sq_addref(global_vm, &sector_table);
98   sq_pop(global_vm, 1);
99 }
100
101 Sector::~Sector()
102 {
103   using namespace Scripting;
104   
105   deactivate();
106
107   for(ScriptList::iterator i = scripts.begin();
108       i != scripts.end(); ++i) {
109     HSQOBJECT& object = *i;
110     sq_release(global_vm, &object);
111   }
112   sq_release(global_vm, &sector_table);
113   sq_collectgarbage(global_vm);
114  
115   update_game_objects();
116   assert(gameobjects_new.size() == 0);
117
118   for(GameObjects::iterator i = gameobjects.begin();
119       i != gameobjects.end(); ++i) {
120     GameObject* object = *i;
121     before_object_remove(object);
122     object->unref();
123   }
124
125   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
126       ++i)
127     delete *i;
128 }
129
130 Level*
131 Sector::get_level()
132 {
133   return level;
134 }
135
136 GameObject*
137 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
138 {
139   if(name == "camera") {
140     Camera* camera = new Camera(this);
141     camera->parse(reader);
142     return camera;
143   } else if(name == "particles-snow") {
144     SnowParticleSystem* partsys = new SnowParticleSystem();
145     partsys->parse(reader);
146     return partsys;
147   } else if(name == "particles-rain") {
148     RainParticleSystem* partsys = new RainParticleSystem();
149     partsys->parse(reader);
150     return partsys;
151   } else if(name == "particles-comets") {
152     CometParticleSystem* partsys = new CometParticleSystem();
153     partsys->parse(reader);
154     return partsys;
155   } else if(name == "particles-ghosts") {
156     GhostParticleSystem* partsys = new GhostParticleSystem();
157     partsys->parse(reader);
158     return partsys;
159   } else if(name == "particles-clouds") {
160     CloudParticleSystem* partsys = new CloudParticleSystem();
161     partsys->parse(reader);
162     return partsys;
163   } else if(name == "money") { // for compatibility with old maps
164     return new Jumpy(reader);
165   } 
166
167   try {
168     return create_object(name, reader);
169   } catch(std::exception& e) {
170     log_warning << e.what() << "" << std::endl;
171   }
172   
173   return 0;
174 }
175
176 void
177 Sector::parse(const lisp::Lisp& sector)
178 {  
179   lisp::ListIterator iter(&sector);
180   while(iter.next()) {
181     const std::string& token = iter.item();
182     if(token == "name") {
183       iter.value()->get(name);
184     } else if(token == "gravity") {
185       iter.value()->get(gravity);
186     } else if(token == "music") {
187       iter.value()->get(music);
188     } else if(token == "spawnpoint") {
189       SpawnPoint* sp = new SpawnPoint(iter.lisp());
190       spawnpoints.push_back(sp);
191     } else if(token == "init-script") {
192       iter.value()->get(init_script);
193     } else {
194       GameObject* object = parse_object(token, *(iter.lisp()));
195       if(object) {
196         add_object(object);
197       }
198     }
199   }
200
201   update_game_objects();
202
203   if(!solids)
204     throw std::runtime_error("sector does not contain a solid tile layer.");
205
206   fix_old_tiles();
207   if(!camera) {
208     log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
209     update_game_objects();
210     add_object(new Camera(this));
211   }
212
213   update_game_objects();
214 }
215
216 void
217 Sector::parse_old_format(const lisp::Lisp& reader)
218 {
219   name = "main";
220   reader.get("gravity", gravity);
221
222   std::string backgroundimage;
223   reader.get("background", backgroundimage);
224   float bgspeed = .5;
225   reader.get("bkgd_speed", bgspeed);
226   bgspeed /= 100;
227
228   Color bkgd_top, bkgd_bottom;
229   int r = 0, g = 0, b = 128;
230   reader.get("bkgd_red_top", r);
231   reader.get("bkgd_green_top",  g);
232   reader.get("bkgd_blue_top",  b);
233   bkgd_top.red = static_cast<float> (r) / 255.0f;
234   bkgd_top.green = static_cast<float> (g) / 255.0f;
235   bkgd_top.blue = static_cast<float> (b) / 255.0f;
236   
237   reader.get("bkgd_red_bottom",  r);
238   reader.get("bkgd_green_bottom", g);
239   reader.get("bkgd_blue_bottom", b);
240   bkgd_bottom.red = static_cast<float> (r) / 255.0f;
241   bkgd_bottom.green = static_cast<float> (g) / 255.0f;
242   bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
243   
244   if(backgroundimage != "") {
245     Background* background = new Background();
246     background->set_image(
247             std::string("images/background/") + backgroundimage, bgspeed);
248     add_object(background);
249   } else {
250     Gradient* gradient = new Gradient();
251     gradient->set_gradient(bkgd_top, bkgd_bottom);
252     add_object(gradient);
253   }
254
255   std::string particlesystem;
256   reader.get("particle_system", particlesystem);
257   if(particlesystem == "clouds")
258     add_object(new CloudParticleSystem());
259   else if(particlesystem == "snow")
260     add_object(new SnowParticleSystem());
261   else if(particlesystem == "rain")
262     add_object(new RainParticleSystem());
263
264   Vector startpos(100, 170);
265   reader.get("start_pos_x", startpos.x);
266   reader.get("start_pos_y", startpos.y);
267
268   SpawnPoint* spawn = new SpawnPoint;
269   spawn->pos = startpos;
270   spawn->name = "main";
271   spawnpoints.push_back(spawn);
272
273   music = "chipdisko.ogg";
274   reader.get("music", music);
275   music = "music/" + music;
276
277   int width = 30, height = 15;
278   reader.get("width", width);
279   reader.get("height", height);
280   
281   std::vector<unsigned int> tiles;
282   if(reader.get_vector("interactive-tm", tiles)
283       || reader.get_vector("tilemap", tiles)) {
284     TileMap* tilemap = new TileMap();
285     tilemap->set(width, height, tiles, LAYER_TILES, true);
286     add_object(tilemap);
287   }
288
289   if(reader.get_vector("background-tm", tiles)) {
290     TileMap* tilemap = new TileMap();
291     tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
292     add_object(tilemap);
293   }
294
295   if(reader.get_vector("foreground-tm", tiles)) {
296     TileMap* tilemap = new TileMap();
297     tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
298     add_object(tilemap);
299   }
300
301   // read reset-points (now spawn-points)
302   const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
303   if(resetpoints) {
304     lisp::ListIterator iter(resetpoints);
305     while(iter.next()) {
306       if(iter.item() == "point") {
307         Vector sp_pos;
308         if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
309           {
310           SpawnPoint* sp = new SpawnPoint;
311           sp->name = "main";
312           sp->pos = sp_pos;
313           spawnpoints.push_back(sp);
314           }
315       } else {
316         log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
317       }
318     }
319   }
320
321   // read objects
322   const lisp::Lisp* objects = reader.get_lisp("objects");
323   if(objects) {
324     lisp::ListIterator iter(objects);
325     while(iter.next()) {
326       GameObject* object = parse_object(iter.item(), *(iter.lisp()));
327       if(object) {
328         add_object(object);
329       } else {
330         log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
331       }
332     }
333   }
334
335   // add a camera
336   Camera* camera = new Camera(this);
337   add_object(camera);
338
339   update_game_objects();
340
341   if(solids == 0)
342     throw std::runtime_error("sector does not contain a solid tile layer.");
343
344   fix_old_tiles();
345   update_game_objects();
346 }
347
348 void
349 Sector::fix_old_tiles()
350 {
351   // hack for now...
352   for(size_t x=0; x < solids->get_width(); ++x) {
353     for(size_t y=0; y < solids->get_height(); ++y) {
354       const Tile* tile = solids->get_tile(x, y);
355       Vector pos(x*32, y*32);
356       
357       if(tile->getID() == 112) {
358         add_object(new InvisibleBlock(pos));
359         solids->change(x, y, 0);
360       } else if(tile->getAttributes() & Tile::COIN) {
361         add_object(new Coin(pos));
362         solids->change(x, y, 0);
363       } else if(tile->getAttributes() & Tile::FULLBOX) {
364         add_object(new BonusBlock(pos, tile->getData()));
365         solids->change(x, y, 0);
366       } else if(tile->getAttributes() & Tile::BRICK) {
367         add_object(new Brick(pos, tile->getData()));
368         solids->change(x, y, 0);
369       } else if(tile->getAttributes() & Tile::GOAL) {
370         std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
371         add_object(new SequenceTrigger(pos, sequence));
372         solids->change(x, y, 0);
373       }
374     }
375   }
376 }
377
378 void
379 Sector::write(lisp::Writer& writer)
380 {
381   writer.write_string("name", name);
382   writer.write_float("gravity", gravity);
383   writer.write_string("music", music);
384
385   // write spawnpoints
386   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
387       ++i) {
388     SpawnPoint* spawn = *i;
389     writer.start_list("spawn-points");
390     writer.write_string("name", spawn->name);
391     writer.write_float("x", spawn->pos.x);
392     writer.write_float("y", spawn->pos.y);
393     writer.end_list("spawn-points");
394   }
395
396   // write objects
397   for(GameObjects::iterator i = gameobjects.begin();
398       i != gameobjects.end(); ++i) {
399     Serializable* serializable = dynamic_cast<Serializable*> (*i);
400     if(serializable)
401       serializable->write(writer);
402   }
403 }
404
405 HSQUIRRELVM
406 Sector::run_script(std::istream& in, const std::string& sourcename)
407 {
408   using namespace Scripting;
409
410   // garbage collect thread list
411   for(ScriptList::iterator i = scripts.begin();
412       i != scripts.end(); ) {
413     HSQOBJECT& object = *i;
414     HSQUIRRELVM vm = object_to_vm(object);
415
416     if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
417       sq_release(global_vm, &object);
418       i = scripts.erase(i);
419       continue;
420     }
421     
422     ++i;
423   }
424   
425   HSQOBJECT object = create_thread(global_vm);
426   scripts.push_back(object);
427
428   HSQUIRRELVM vm = object_to_vm(object);
429
430   // set sector_table as roottable for the thread
431   sq_pushobject(vm, sector_table);
432   sq_setroottable(vm);
433
434   compile_and_run(vm, in, sourcename);
435
436   return vm;
437 }
438
439 void
440 Sector::add_object(GameObject* object)
441 {
442   // make sure the object isn't already in the list
443 #ifdef DEBUG
444   for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
445       ++i) {
446     if(*i == object) {
447       assert("object already added to sector" == 0);
448     }
449   }
450   for(GameObjects::iterator i = gameobjects_new.begin();
451       i != gameobjects_new.end(); ++i) {
452     if(*i == object) {
453       assert("object already added to sector" == 0);
454     }
455   }
456 #endif
457
458   object->ref();
459   gameobjects_new.push_back(object);
460 }
461
462 void
463 Sector::activate(const std::string& spawnpoint)
464 {
465   SpawnPoint* sp = 0;
466   for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
467       ++i) {
468     if((*i)->name == spawnpoint) {
469       sp = *i;
470       break;
471     }
472   }                                                                           
473   if(!sp) {
474     log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
475     if(spawnpoint != "main") {
476       activate("main");
477     } else {
478       activate(Vector(0, 0));
479     }
480   } else {
481     activate(sp->pos);
482   }
483 }
484
485 void
486 Sector::activate(const Vector& player_pos)
487 {
488   if(_current != this) {
489     if(_current != NULL)
490       _current->deactivate();
491     _current = this;
492
493     // register sectortable as sector in scripting
494     HSQUIRRELVM vm = Scripting::global_vm;
495     sq_pushroottable(vm);
496     sq_pushstring(vm, "sector", -1);
497     sq_pushobject(vm, sector_table);
498     if(SQ_FAILED(sq_createslot(vm, -3)))
499       throw Scripting::SquirrelError(vm, "Couldn't set 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_expose(object);
507     }
508   }
509
510   player->move(player_pos);
511   camera->reset(player->get_pos());
512   update_game_objects();
513
514   // Run init script
515   if(init_script != "") {
516     std::istringstream in(init_script);
517     run_script(in, std::string("Sector(") + name + ") - init");
518   }
519 }
520
521 void
522 Sector::deactivate()
523 {
524   if(_current != this)
525     return;
526
527   // remove sector entry from global vm
528   HSQUIRRELVM vm = Scripting::global_vm;
529   sq_pushroottable(vm);
530   sq_pushstring(vm, "sector", -1);
531   if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
532     throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
533   sq_pop(vm, 1);
534   
535   for(GameObjects::iterator i = gameobjects.begin();
536       i != gameobjects.end(); ++i) {
537     GameObject* object = *i;
538     
539     try_unexpose(object);
540   }
541
542   _current = NULL;
543 }
544
545 Rect
546 Sector::get_active_region()
547 {
548   return Rect(
549     camera->get_translation() - Vector(1600, 1200),
550     camera->get_translation() + Vector(1600, 1200));
551 }
552
553 void
554 Sector::update(float elapsed_time)
555 {
556   player->check_bounds(camera);
557
558 #if 0
559   CollisionGridIterator iter(*grid, get_active_region());
560   while(MovingObject* object = iter.next()) {
561     if(!object->is_valid())
562       continue;
563
564     object->update(elapsed_time);
565   }
566 #else
567   /* update objects */
568   for(GameObjects::iterator i = gameobjects.begin();
569           i != gameobjects.end(); ++i) {
570     GameObject* object = *i;
571     if(!object->is_valid())
572       continue;
573     
574     object->update(elapsed_time);
575   }
576 #endif
577   
578   /* Handle all possible collisions. */
579   handle_collisions();
580   update_game_objects();
581 }
582
583 void
584 Sector::update_game_objects()
585 {
586   /** cleanup marked objects */
587   for(std::vector<Bullet*>::iterator i = bullets.begin();
588       i != bullets.end(); /* nothing */) {
589     Bullet* bullet = *i;
590     if(bullet->is_valid()) {
591       ++i;
592       continue;
593     }
594
595     i = bullets.erase(i);
596   }
597   for(MovingObjects::iterator i = moving_objects.begin();
598       i != moving_objects.end(); /* nothing */) {
599     MovingObject* moving_object = *i;
600     if(moving_object->is_valid()) {
601       ++i;
602       continue;
603     }
604
605 #ifdef USE_GRID
606     grid->remove_object(moving_object);
607 #endif
608     
609     i = moving_objects.erase(i);
610   }
611   for(std::vector<GameObject*>::iterator i = gameobjects.begin();
612       i != gameobjects.end(); /* nothing */) {
613     GameObject* object = *i;
614     
615     if(object->is_valid()) {
616       ++i;
617       continue;
618     }
619
620     before_object_remove(object);
621     
622     object->unref();
623     i = gameobjects.erase(i);
624   }
625
626   /* add newly created objects */
627   for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
628       i != gameobjects_new.end(); ++i)
629   {
630     GameObject* object = *i;
631
632     before_object_add(object);
633     
634     gameobjects.push_back(object);
635   }
636   gameobjects_new.clear();
637 }
638
639 bool
640 Sector::before_object_add(GameObject* object)
641 {
642   Bullet* bullet = dynamic_cast<Bullet*> (object);
643   if(bullet)
644     bullets.push_back(bullet);
645
646   MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
647   if(movingobject) {
648     moving_objects.push_back(movingobject);
649 #ifdef USE_GRID
650     grid->add_object(movingobject);
651 #endif
652   }
653   
654   TileMap* tilemap = dynamic_cast<TileMap*> (object);
655   if(tilemap && tilemap->is_solid()) {
656     if(solids == 0) {
657       solids = tilemap;
658     } else {
659       log_warning << "Another solid tilemaps added. Ignoring" << std::endl;
660     }
661   }
662
663   Camera* camera = dynamic_cast<Camera*> (object);
664   if(camera) {
665     if(this->camera != 0) {
666       log_warning << "Multiple cameras added. Ignoring" << std::endl;
667       return false;
668     }
669     this->camera = camera;
670   }
671
672   Player* player = dynamic_cast<Player*> (object);
673   if(player) {
674     if(this->player != 0) {
675       log_warning << "Multiple players added. Ignoring" << std::endl;
676       return false;
677     }
678     this->player = player;
679   }
680
681   if(_current == this) {
682     try_expose(object);
683   }
684   
685   return true;
686 }
687
688 void
689 Sector::try_expose(GameObject* object)
690 {
691   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
692   if(interface != NULL) {
693     HSQUIRRELVM vm = Scripting::global_vm;
694     sq_pushobject(vm, sector_table);
695     interface->expose(vm, -1);
696     sq_pop(vm, 1);
697   }
698 }
699
700 void
701 Sector::before_object_remove(GameObject* object)
702 {
703   if(_current == this)
704     try_unexpose(object);
705 }
706
707 void
708 Sector::try_unexpose(GameObject* object)
709 {
710   ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
711   if(interface != NULL) {
712     HSQUIRRELVM vm = Scripting::global_vm;
713     SQInteger oldtop = sq_gettop(vm);
714     sq_pushobject(vm, sector_table);
715     try {
716       interface->unexpose(vm, -1);
717     } catch(std::exception& e) {
718       log_warning << "Couldn't unregister object: " << e.what() << std::endl;
719     }
720     sq_settop(vm, oldtop);
721   }
722
723
724 void
725 Sector::draw(DrawingContext& context)
726 {
727   context.push_transform();
728   context.set_translation(camera->get_translation());
729
730   for(GameObjects::iterator i = gameobjects.begin();
731       i != gameobjects.end(); ++i) {
732     GameObject* object = *i; 
733     if(!object->is_valid())
734       continue;
735
736     if (draw_solids_only)
737     {
738       TileMap* tm = dynamic_cast<TileMap*>(object);
739       if (tm && !tm->is_solid())
740         continue;
741     }
742
743     object->draw(context);
744   }
745
746   if(show_collrects) {
747     Color col(0.2, 0.2, 0.2, 0.7);
748     for(MovingObjects::iterator i = moving_objects.begin();
749             i != moving_objects.end(); ++i) {
750       MovingObject* object = *i;
751       const Rect& rect = object->get_bbox();
752
753       context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
754     }
755   }
756
757   context.pop_transform();
758 }
759
760 static const float DELTA = .001;
761
762 void
763 Sector::collision_tilemap(const Rect& dest, const Vector& movement,
764                           CollisionHit& hit) const
765 {
766   // calculate rectangle where the object will move
767   float x1 = dest.get_left();
768   float x2 = dest.get_right();
769   float y1 = dest.get_top();
770   float y2 = dest.get_bottom();
771
772   // test with all tiles in this rectangle
773   int starttilex = int(x1) / 32;
774   int starttiley = int(y1) / 32;
775   int max_x = int(x2 + (1 - DELTA));
776   int max_y = int(y2 + (1 - DELTA));
777
778   CollisionHit temphit;
779   for(int x = starttilex; x*32 < max_x; ++x) {
780     for(int y = starttiley; y*32 < max_y; ++y) {
781       const Tile* tile = solids->get_tile(x, y);
782       if(!tile)
783         continue;
784       // skip non-solid tiles
785       if(tile->getAttributes() == 0)
786         continue;
787       // only handle unisolid when the player is falling down and when he was
788       // above the tile before
789       if(tile->getAttributes() & Tile::UNISOLID) {
790         if(movement.y < 0 || dest.get_top() - movement.y > y*32)
791           continue;
792       }
793
794       if(tile->getAttributes() & Tile::SLOPE) { // slope tile
795         AATriangle triangle;
796         Vector p1(x*32, y*32);
797         Vector p2((x+1)*32, (y+1)*32);
798         triangle = AATriangle(p1, p2, tile->getData());
799
800         if(Collision::rectangle_aatriangle(temphit, dest, movement,
801               triangle)) {
802           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
803             hit = temphit;
804           }
805         }
806       } else { // normal rectangular tile
807         Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
808         if(Collision::rectangle_rectangle(temphit, dest, movement, rect)) {
809           if(temphit.time > hit.time && (tile->getAttributes() & Tile::SOLID)) {
810             hit = temphit;
811           }
812         }
813       }
814     }
815   }
816 }
817
818 uint32_t
819 Sector::collision_tile_attributes(const Rect& dest) const
820 {
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 }