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