1 // SuperTux - A Jump'n Run
2 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
4 // This program is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // This program is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with this program. If not, see <http://www.gnu.org/licenses/>.
17 #include "supertux/sector.hpp"
22 #include "audio/sound_manager.hpp"
23 #include "badguy/jumpy.hpp"
24 #include "lisp/list_iterator.hpp"
25 #include "math/aatriangle.hpp"
26 #include "object/background.hpp"
27 #include "object/bonus_block.hpp"
28 #include "object/brick.hpp"
29 #include "object/bullet.hpp"
30 #include "object/camera.hpp"
31 #include "object/cloud_particle_system.hpp"
32 #include "object/coin.hpp"
33 #include "object/comet_particle_system.hpp"
34 #include "object/display_effect.hpp"
35 #include "object/ghost_particle_system.hpp"
36 #include "object/gradient.hpp"
37 #include "object/invisible_block.hpp"
38 #include "object/particlesystem.hpp"
39 #include "object/particlesystem_interactive.hpp"
40 #include "object/player.hpp"
41 #include "object/portable.hpp"
42 #include "object/pulsing_light.hpp"
43 #include "object/rain_particle_system.hpp"
44 #include "object/smoke_cloud.hpp"
45 #include "object/snow_particle_system.hpp"
46 #include "object/text_object.hpp"
47 #include "object/tilemap.hpp"
48 #include "physfs/ifile_stream.hpp"
49 #include "scripting/squirrel_util.hpp"
50 #include "supertux/collision.hpp"
51 #include "supertux/constants.hpp"
52 #include "supertux/game_session.hpp"
53 #include "supertux/globals.hpp"
54 #include "supertux/level.hpp"
55 #include "supertux/object_factory.hpp"
56 #include "supertux/player_status.hpp"
57 #include "supertux/spawn_point.hpp"
58 #include "supertux/tile.hpp"
59 #include "trigger/sequence_trigger.hpp"
60 #include "util/file_system.hpp"
62 Sector* Sector::_current = 0;
64 bool Sector::show_collrects = false;
65 bool Sector::draw_solids_only = false;
67 Sector::Sector(Level* parent) :
73 currentmusic(LEVEL_MUSIC),
76 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ),
88 add_object(new Player(GameSession::current()->get_player_status(), "Tux"));
89 add_object(new DisplayEffect("Effect"));
90 add_object(new TextObject("Text"));
92 sound_manager->preload("sounds/shoot.wav");
94 // create a new squirrel table for the sector
95 using namespace scripting;
97 sq_collectgarbage(global_vm);
99 sq_newtable(global_vm);
100 sq_pushroottable(global_vm);
101 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
102 throw scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
104 sq_resetobject(§or_table);
105 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
106 throw scripting::SquirrelError(global_vm, "Couldn't get sector table");
107 sq_addref(global_vm, §or_table);
108 sq_pop(global_vm, 1);
113 using namespace scripting;
117 for(ScriptList::iterator i = scripts.begin();
118 i != scripts.end(); ++i) {
119 HSQOBJECT& object = *i;
120 sq_release(global_vm, &object);
122 sq_release(global_vm, §or_table);
123 sq_collectgarbage(global_vm);
125 update_game_objects();
126 assert(gameobjects_new.size() == 0);
128 for(GameObjects::iterator i = gameobjects.begin();
129 i != gameobjects.end(); ++i) {
130 GameObject* object = *i;
131 before_object_remove(object);
135 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
147 Sector::parse_object(const std::string& name, const Reader& reader)
149 if(name == "camera") {
150 Camera* camera = new Camera(this, "Camera");
151 camera->parse(reader);
153 } else if(name == "particles-snow") {
154 SnowParticleSystem* partsys = new SnowParticleSystem();
155 partsys->parse(reader);
157 } else if(name == "particles-rain") {
158 RainParticleSystem* partsys = new RainParticleSystem();
159 partsys->parse(reader);
161 } else if(name == "particles-comets") {
162 CometParticleSystem* partsys = new CometParticleSystem();
163 partsys->parse(reader);
165 } else if(name == "particles-ghosts") {
166 GhostParticleSystem* partsys = new GhostParticleSystem();
167 partsys->parse(reader);
169 } else if(name == "particles-clouds") {
170 CloudParticleSystem* partsys = new CloudParticleSystem();
171 partsys->parse(reader);
173 } else if(name == "money") { // for compatibility with old maps
174 return new Jumpy(reader);
177 return ObjectFactory::instance().create(name, reader);
178 } catch(std::exception& e) {
179 log_warning << e.what() << "" << std::endl;
186 Sector::parse(const Reader& sector)
188 bool has_background = false;
189 lisp::ListIterator iter(§or);
191 const std::string& token = iter.item();
192 if(token == "name") {
193 iter.value()->get(name);
194 } else if(token == "gravity") {
195 iter.value()->get(gravity);
196 } else if(token == "music") {
197 iter.value()->get(music);
198 } else if(token == "spawnpoint") {
199 SpawnPoint* sp = new SpawnPoint(*iter.lisp());
200 spawnpoints.push_back(sp);
201 } else if(token == "init-script") {
202 iter.value()->get(init_script);
203 } else if(token == "ambient-light") {
204 std::vector<float> vColor;
205 sector.get( "ambient-light", vColor );
206 if(vColor.size() < 3) {
207 log_warning << "(ambient-light) requires a color as argument" << std::endl;
209 ambient_light = Color( vColor );
212 GameObject* object = parse_object(token, *(iter.lisp()));
214 if(dynamic_cast<Background *>(object)) {
215 has_background = true;
216 } else if(dynamic_cast<Gradient *>(object)) {
217 has_background = true;
224 if(!has_background) {
225 Gradient* gradient = new Gradient();
226 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
227 add_object(gradient);
230 update_game_objects();
232 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
236 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
237 update_game_objects();
238 add_object(new Camera(this, "Camera"));
241 update_game_objects();
245 Sector::parse_old_format(const Reader& reader)
248 reader.get("gravity", gravity);
250 std::string backgroundimage;
251 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
252 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
253 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
254 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
255 backgroundimage = "images/background/" + backgroundimage;
256 if (!PHYSFS_exists(backgroundimage.c_str())) {
257 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
258 backgroundimage = "";
263 reader.get("bkgd_speed", bgspeed);
266 Color bkgd_top, bkgd_bottom;
267 int r = 0, g = 0, b = 128;
268 reader.get("bkgd_red_top", r);
269 reader.get("bkgd_green_top", g);
270 reader.get("bkgd_blue_top", b);
271 bkgd_top.red = static_cast<float> (r) / 255.0f;
272 bkgd_top.green = static_cast<float> (g) / 255.0f;
273 bkgd_top.blue = static_cast<float> (b) / 255.0f;
275 reader.get("bkgd_red_bottom", r);
276 reader.get("bkgd_green_bottom", g);
277 reader.get("bkgd_blue_bottom", b);
278 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
279 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
280 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
282 if(backgroundimage != "") {
283 Background* background = new Background();
284 background->set_image(backgroundimage, bgspeed);
285 add_object(background);
287 Gradient* gradient = new Gradient();
288 gradient->set_gradient(bkgd_top, bkgd_bottom);
289 add_object(gradient);
292 std::string particlesystem;
293 reader.get("particle_system", particlesystem);
294 if(particlesystem == "clouds")
295 add_object(new CloudParticleSystem());
296 else if(particlesystem == "snow")
297 add_object(new SnowParticleSystem());
298 else if(particlesystem == "rain")
299 add_object(new RainParticleSystem());
301 Vector startpos(100, 170);
302 reader.get("start_pos_x", startpos.x);
303 reader.get("start_pos_y", startpos.y);
305 SpawnPoint* spawn = new SpawnPoint;
306 spawn->pos = startpos;
307 spawn->name = "main";
308 spawnpoints.push_back(spawn);
310 music = "chipdisko.ogg";
311 // skip reading music filename. It's all .ogg now, anyway
313 reader.get("music", music);
315 music = "music/" + music;
317 int width = 30, height = 15;
318 reader.get("width", width);
319 reader.get("height", height);
321 std::vector<unsigned int> tiles;
322 if(reader.get("interactive-tm", tiles)
323 || reader.get("tilemap", tiles)) {
324 TileMap* tilemap = new TileMap(level->get_tileset());
325 tilemap->set(width, height, tiles, LAYER_TILES, true);
327 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
328 for(size_t x=0; x < tilemap->get_width(); ++x) {
329 for(size_t y=0; y < tilemap->get_height(); ++y) {
330 uint32_t id = tilemap->get_tile_id(x, y);
332 tilemap->change(x, y, 1311);
336 if (height < 19) tilemap->resize(width, 19);
340 if(reader.get("background-tm", tiles)) {
341 TileMap* tilemap = new TileMap(level->get_tileset());
342 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
343 if (height < 19) tilemap->resize(width, 19);
347 if(reader.get("foreground-tm", tiles)) {
348 TileMap* tilemap = new TileMap(level->get_tileset());
349 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
351 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
352 if (height < 19) tilemap->resize(width, 19, 2035);
357 // read reset-points (now spawn-points)
358 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
360 lisp::ListIterator iter(resetpoints);
362 if(iter.item() == "point") {
364 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
366 SpawnPoint* sp = new SpawnPoint;
369 spawnpoints.push_back(sp);
372 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
378 const lisp::Lisp* objects = reader.get_lisp("objects");
380 lisp::ListIterator iter(objects);
382 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
386 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
392 Camera* camera = new Camera(this, "Camera");
395 update_game_objects();
397 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
400 update_game_objects();
404 Sector::fix_old_tiles()
406 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
407 TileMap* solids = *i;
408 for(size_t x=0; x < solids->get_width(); ++x) {
409 for(size_t y=0; y < solids->get_height(); ++y) {
410 uint32_t id = solids->get_tile_id(x, y);
411 const Tile *tile = solids->get_tile(x, y);
412 Vector pos = solids->get_tile_position(x, y);
415 add_object(new InvisibleBlock(pos));
416 solids->change(x, y, 0);
417 } else if(tile->getAttributes() & Tile::COIN) {
418 add_object(new Coin(pos, solids));
419 solids->change(x, y, 0);
420 } else if(tile->getAttributes() & Tile::FULLBOX) {
421 add_object(new BonusBlock(pos, tile->getData()));
422 solids->change(x, y, 0);
423 } else if(tile->getAttributes() & Tile::BRICK) {
424 if( ( id == 78 ) || ( id == 105 ) ){
425 add_object( new Brick(pos, tile->getData(), "images/objects/bonus_block/brickIce.sprite") );
426 } else if( ( id == 77 ) || ( id == 104 ) ){
427 add_object( new Brick(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
429 log_warning << "attribute 'brick #t' is not supported for tile-id " << id << std::endl;
430 add_object( new Brick(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
432 solids->change(x, y, 0);
433 } else if(tile->getAttributes() & Tile::GOAL) {
434 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
435 add_object(new SequenceTrigger(pos, sequence));
436 solids->change(x, y, 0);
442 // add lights for special tiles
443 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
444 TileMap* tm = dynamic_cast<TileMap*>(*i);
446 for(size_t x=0; x < tm->get_width(); ++x) {
447 for(size_t y=0; y < tm->get_height(); ++y) {
448 uint32_t id = tm->get_tile_id(x, y);
449 Vector pos = tm->get_tile_position(x, y);
450 Vector center = pos + Vector(16, 16);
454 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
455 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
458 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
459 // space lights a bit
460 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
461 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
462 || ((x % 3 == 0) && (y % 3 == 0))) {
463 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
464 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
475 Sector::run_script(std::istream& in, const std::string& sourcename)
477 using namespace scripting;
479 // garbage collect thread list
480 for(ScriptList::iterator i = scripts.begin();
481 i != scripts.end(); ) {
482 HSQOBJECT& object = *i;
483 HSQUIRRELVM vm = object_to_vm(object);
485 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
486 sq_release(global_vm, &object);
487 i = scripts.erase(i);
494 HSQOBJECT object = create_thread(global_vm);
495 scripts.push_back(object);
497 HSQUIRRELVM vm = object_to_vm(object);
499 // set sector_table as roottable for the thread
500 sq_pushobject(vm, sector_table);
504 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
505 } catch(std::exception& e) {
506 log_warning << "Error running script: " << e.what() << std::endl;
513 Sector::add_object(GameObject* object)
515 // make sure the object isn't already in the list
517 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
519 assert(*i != object);
521 for(GameObjects::iterator i = gameobjects_new.begin();
522 i != gameobjects_new.end(); ++i) {
523 assert(*i != object);
528 gameobjects_new.push_back(object);
532 Sector::activate(const std::string& spawnpoint)
535 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
537 if((*i)->name == spawnpoint) {
543 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
544 if(spawnpoint != "main") {
547 activate(Vector(0, 0));
555 Sector::activate(const Vector& player_pos)
557 if(_current != this) {
559 _current->deactivate();
562 // register sectortable as sector in scripting
563 HSQUIRRELVM vm = scripting::global_vm;
564 sq_pushroottable(vm);
565 sq_pushstring(vm, "sector", -1);
566 sq_pushobject(vm, sector_table);
567 if(SQ_FAILED(sq_createslot(vm, -3)))
568 throw scripting::SquirrelError(vm, "Couldn't set sector in roottable");
571 for(GameObjects::iterator i = gameobjects.begin();
572 i != gameobjects.end(); ++i) {
573 GameObject* object = *i;
581 // two-player hack: move other players to main player's position
582 // Maybe specify 2 spawnpoints in the level?
583 for(GameObjects::iterator i = gameobjects.begin();
584 i != gameobjects.end(); ++i) {
585 Player* p = dynamic_cast<Player*>(*i);
588 // spawn smalltux below spawnpoint
590 p->move(player_pos + Vector(0,32));
595 // spawning tux in the ground would kill him
596 if(!is_free_of_tiles(p->get_bbox())) {
597 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
598 Vector npos = p->get_bbox().p1;
604 //FIXME: This is a really dirty workaround for this strange camera jump
605 player->move(player->get_pos()+Vector(-32, 0));
606 camera->reset(player->get_pos());
608 player->move(player->get_pos()+(Vector(32, 0)));
611 update_game_objects();
613 //Run default.nut just before init script
614 //Check to see if it's in a levelset (info file)
615 std::string basedir = FileSystem::dirname(get_level()->filename);
616 if(PHYSFS_exists((basedir + "/info").c_str())) {
618 IFileStream in(basedir + "/default.nut");
619 run_script(in, "default.nut");
620 } catch(std::exception& ) {
621 // doesn't exist or erroneous; do nothing
626 if(init_script != "") {
627 std::istringstream in(init_script);
628 run_script(in, "init-script");
638 // remove sector entry from global vm
639 HSQUIRRELVM vm = scripting::global_vm;
640 sq_pushroottable(vm);
641 sq_pushstring(vm, "sector", -1);
642 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
643 throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
646 for(GameObjects::iterator i = gameobjects.begin();
647 i != gameobjects.end(); ++i) {
648 GameObject* object = *i;
650 try_unexpose(object);
658 Sector::get_active_region()
661 camera->get_translation() - Vector(1600, 1200),
662 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
666 Sector::update(float elapsed_time)
668 player->check_bounds();
671 for(GameObjects::iterator i = gameobjects.begin();
672 i != gameobjects.end(); ++i) {
673 GameObject* object = *i;
674 if(!object->is_valid())
677 object->update(elapsed_time);
680 /* Handle all possible collisions. */
682 update_game_objects();
686 Sector::update_game_objects()
688 /** cleanup marked objects */
689 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
690 i != gameobjects.end(); /* nothing */) {
691 GameObject* object = *i;
693 if(object->is_valid()) {
698 before_object_remove(object);
701 i = gameobjects.erase(i);
704 /* add newly created objects */
705 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
706 i != gameobjects_new.end(); ++i)
708 GameObject* object = *i;
710 before_object_add(object);
712 gameobjects.push_back(object);
714 gameobjects_new.clear();
716 /* update solid_tilemaps list */
717 //FIXME: this could be more efficient
718 solid_tilemaps.clear();
719 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
720 i != gameobjects.end(); ++i)
722 TileMap* tm = dynamic_cast<TileMap*>(*i);
724 if (tm->is_solid()) solid_tilemaps.push_back(tm);
730 Sector::before_object_add(GameObject* object)
732 Bullet* bullet = dynamic_cast<Bullet*> (object);
734 bullets.push_back(bullet);
737 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
738 if(movingobject != NULL) {
739 moving_objects.push_back(movingobject);
742 Portable* portable = dynamic_cast<Portable*> (object);
743 if(portable != NULL) {
744 portables.push_back(portable);
747 TileMap* tilemap = dynamic_cast<TileMap*> (object);
748 if(tilemap != NULL && tilemap->is_solid()) {
749 solid_tilemaps.push_back(tilemap);
752 Camera* camera = dynamic_cast<Camera*> (object);
754 if(this->camera != 0) {
755 log_warning << "Multiple cameras added. Ignoring" << std::endl;
758 this->camera = camera;
761 Player* player = dynamic_cast<Player*> (object);
763 if(this->player != 0) {
764 log_warning << "Multiple players added. Ignoring" << std::endl;
767 this->player = player;
770 DisplayEffect* effect = dynamic_cast<DisplayEffect*> (object);
772 if(this->effect != 0) {
773 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
776 this->effect = effect;
779 if(_current == this) {
787 Sector::try_expose(GameObject* object)
789 ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
790 if(object_ != NULL) {
791 HSQUIRRELVM vm = scripting::global_vm;
792 sq_pushobject(vm, sector_table);
793 object_->expose(vm, -1);
799 Sector::try_expose_me()
801 HSQUIRRELVM vm = scripting::global_vm;
802 sq_pushobject(vm, sector_table);
803 scripting::SSector* this_ = static_cast<scripting::SSector*> (this);
804 expose_object(vm, -1, this_, "settings", false);
809 Sector::before_object_remove(GameObject* object)
811 Portable* portable = dynamic_cast<Portable*> (object);
812 if(portable != NULL) {
813 portables.erase(std::find(portables.begin(), portables.end(), portable));
815 Bullet* bullet = dynamic_cast<Bullet*> (object);
817 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
819 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
820 if(moving_object != NULL) {
821 moving_objects.erase(
822 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
826 try_unexpose(object);
830 Sector::try_unexpose(GameObject* object)
832 ScriptInterface* object_ = dynamic_cast<ScriptInterface*> (object);
833 if(object_ != NULL) {
834 HSQUIRRELVM vm = scripting::global_vm;
835 SQInteger oldtop = sq_gettop(vm);
836 sq_pushobject(vm, sector_table);
838 object_->unexpose(vm, -1);
839 } catch(std::exception& e) {
840 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
842 sq_settop(vm, oldtop);
847 Sector::try_unexpose_me()
849 HSQUIRRELVM vm = scripting::global_vm;
850 SQInteger oldtop = sq_gettop(vm);
851 sq_pushobject(vm, sector_table);
853 scripting::unexpose_object(vm, -1, "settings");
854 } catch(std::exception& e) {
855 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
857 sq_settop(vm, oldtop);
860 Sector::draw(DrawingContext& context)
862 context.set_ambient_color( ambient_light );
863 context.push_transform();
864 context.set_translation(camera->get_translation());
866 for(GameObjects::iterator i = gameobjects.begin();
867 i != gameobjects.end(); ++i) {
868 GameObject* object = *i;
869 if(!object->is_valid())
872 if (draw_solids_only)
874 TileMap* tm = dynamic_cast<TileMap*>(object);
875 if (tm && !tm->is_solid())
879 object->draw(context);
883 Color color(1.0f, 0.0f, 0.0f, 0.75f);
884 for(MovingObjects::iterator i = moving_objects.begin();
885 i != moving_objects.end(); ++i) {
886 MovingObject* object = *i;
887 const Rectf& rect = object->get_bbox();
889 context.draw_filled_rect(rect, color, LAYER_FOREGROUND1 + 10);
893 context.pop_transform();
896 /*-------------------------------------------------------------------------
897 * Collision Detection
898 *-------------------------------------------------------------------------*/
900 /** r1 is supposed to be moving, r2 a solid object */
901 void check_collisions(collision::Constraints* constraints,
902 const Vector& obj_movement, const Rectf& obj_rect, const Rectf& other_rect,
903 GameObject* object = NULL, MovingObject* other = NULL, const Vector& other_movement = Vector(0,0))
905 if(!collision::intersects(obj_rect, other_rect))
908 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
910 if(other != NULL && !other->collides(*object, dummy))
912 if(moving_object != NULL && !moving_object->collides(*other, dummy))
915 // calculate intersection
916 float itop = obj_rect.get_bottom() - other_rect.get_top();
917 float ibottom = other_rect.get_bottom() - obj_rect.get_top();
918 float ileft = obj_rect.get_right() - other_rect.get_left();
919 float iright = other_rect.get_right() - obj_rect.get_left();
921 if(fabsf(obj_movement.y) > fabsf(obj_movement.x)) {
922 if(ileft < SHIFT_DELTA) {
923 constraints->constrain_right(other_rect.get_left(), other_movement.x);
925 } else if(iright < SHIFT_DELTA) {
926 constraints->constrain_left(other_rect.get_right(), other_movement.x);
930 // shiftout bottom/top
931 if(itop < SHIFT_DELTA) {
932 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
934 } else if(ibottom < SHIFT_DELTA) {
935 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
940 constraints->ground_movement += other_movement;
942 HitResponse response = other->collision(*object, dummy);
943 if(response == ABORT_MOVE)
946 if(other->get_movement() != Vector(0, 0)) {
947 // TODO what todo when we collide with 2 moving objects?!?
948 constraints->ground_movement = other->get_movement();
952 float vert_penetration = std::min(itop, ibottom);
953 float horiz_penetration = std::min(ileft, iright);
954 if(vert_penetration < horiz_penetration) {
956 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
957 constraints->hit.bottom = true;
959 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
960 constraints->hit.top = true;
964 constraints->constrain_right(other_rect.get_left(), other_movement.x);
965 constraints->hit.right = true;
967 constraints->constrain_left(other_rect.get_right(), other_movement.x);
968 constraints->hit.left = true;
974 Sector::collision_tilemap(collision::Constraints* constraints,
975 const Vector& movement, const Rectf& dest,
976 MovingObject& object) const
978 // calculate rectangle where the object will move
979 float x1 = dest.get_left();
980 float x2 = dest.get_right();
981 float y1 = dest.get_top();
982 float y2 = dest.get_bottom();
984 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
985 TileMap* solids = *i;
987 // test with all tiles in this rectangle
988 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
990 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
991 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
992 const Tile* tile = solids->get_tile(x, y);
995 // skip non-solid tiles
996 if(!tile->is_solid ())
998 Rectf tile_bbox = solids->get_tile_bbox(x, y);
1000 /* If the tile is a unisolid tile, the "is_solid()" function above
1001 * didn't do a thorough check. Calculate the position and (relative)
1002 * movement of the object and determine whether or not the tile is
1003 * solid with regard to those parameters. */
1004 if(tile->is_unisolid ()) {
1005 Vector relative_movement = movement
1006 - solids->get_movement(/* actual = */ true);
1008 if (!tile->is_solid (tile_bbox, object.get_bbox(), relative_movement))
1010 } /* if (tile->is_unisolid ()) */
1012 if(tile->is_slope ()) { // slope tile
1013 AATriangle triangle;
1014 int slope_data = tile->getData();
1015 if (solids->get_drawing_effect() == VERTICAL_FLIP)
1016 slope_data = AATriangle::vertical_flip(slope_data);
1017 triangle = AATriangle(tile_bbox, slope_data);
1019 collision::rectangle_aatriangle(constraints, dest, triangle,
1020 solids->get_movement(/* actual = */ false));
1021 } else { // normal rectangular tile
1022 check_collisions(constraints, movement, dest, tile_bbox, NULL, NULL,
1023 solids->get_movement(/* actual = */ false));
1031 Sector::collision_tile_attributes(const Rectf& dest) const
1033 float x1 = dest.p1.x;
1034 float y1 = dest.p1.y;
1035 float x2 = dest.p2.x;
1036 float y2 = dest.p2.y;
1038 uint32_t result = 0;
1039 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1040 TileMap* solids = *i;
1042 // test with all tiles in this rectangle
1043 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1044 // For ice (only), add a little fudge to recognize tiles Tux is standing on.
1045 Rect test_tiles_ice = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2 + SHIFT_DELTA));
1047 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1049 for(y = test_tiles.top; y < test_tiles.bottom; ++y) {
1050 const Tile* tile = solids->get_tile(x, y);
1053 result |= tile->getAttributes();
1055 for(; y < test_tiles_ice.bottom; ++y) {
1056 const Tile* tile = solids->get_tile(x, y);
1059 result |= (tile->getAttributes() & Tile::ICE);
1067 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1068 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1071 float itop = r1.get_bottom() - r2.get_top();
1072 float ibottom = r2.get_bottom() - r1.get_top();
1073 float ileft = r1.get_right() - r2.get_left();
1074 float iright = r2.get_right() - r1.get_left();
1076 float vert_penetration = std::min(itop, ibottom);
1077 float horiz_penetration = std::min(ileft, iright);
1078 if(vert_penetration < horiz_penetration) {
1079 if(itop < ibottom) {
1081 normal.y = vert_penetration;
1084 normal.y = -vert_penetration;
1087 if(ileft < iright) {
1089 normal.x = horiz_penetration;
1092 normal.x = -horiz_penetration;
1098 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1100 using namespace collision;
1102 const Rectf& r1 = object1->dest;
1103 const Rectf& r2 = object2->dest;
1106 if(intersects(object1->dest, object2->dest)) {
1108 get_hit_normal(r1, r2, hit, normal);
1110 if(!object1->collides(*object2, hit))
1112 std::swap(hit.left, hit.right);
1113 std::swap(hit.top, hit.bottom);
1114 if(!object2->collides(*object1, hit))
1116 std::swap(hit.left, hit.right);
1117 std::swap(hit.top, hit.bottom);
1119 HitResponse response1 = object1->collision(*object2, hit);
1120 std::swap(hit.left, hit.right);
1121 std::swap(hit.top, hit.bottom);
1122 HitResponse response2 = object2->collision(*object1, hit);
1123 if(response1 == CONTINUE && response2 == CONTINUE) {
1124 normal *= (0.5 + DELTA);
1125 object1->dest.move(-normal);
1126 object2->dest.move(normal);
1127 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1128 normal *= (1 + DELTA);
1129 object1->dest.move(-normal);
1130 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1131 normal *= (1 + DELTA);
1132 object2->dest.move(normal);
1138 Sector::collision_static(collision::Constraints* constraints,
1139 const Vector& movement, const Rectf& dest,
1140 MovingObject& object)
1142 collision_tilemap(constraints, movement, dest, object);
1144 // collision with other (static) objects
1145 for(MovingObjects::iterator i = moving_objects.begin();
1146 i != moving_objects.end(); ++i) {
1147 MovingObject* moving_object = *i;
1148 if(moving_object->get_group() != COLGROUP_STATIC
1149 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1151 if(!moving_object->is_valid())
1154 if(moving_object != &object)
1155 check_collisions(constraints, movement, dest, moving_object->bbox,
1156 &object, moving_object);
1161 Sector::collision_static_constrains(MovingObject& object)
1163 using namespace collision;
1164 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1166 Constraints constraints;
1167 Vector movement = object.get_movement();
1168 Rectf& dest = object.dest;
1170 for(int i = 0; i < 2; ++i) {
1171 collision_static(&constraints, Vector(0, movement.y), dest, object);
1172 if(!constraints.has_constraints())
1175 // apply calculated horizontal constraints
1176 if(constraints.get_position_bottom() < infinity) {
1177 float height = constraints.get_height ();
1178 if(height < object.get_bbox().get_height()) {
1179 // we're crushed, but ignore this for now, we'll get this again
1180 // later if we're really crushed or things will solve itself when
1181 // looking at the vertical constraints
1183 dest.p2.y = constraints.get_position_bottom() - DELTA;
1184 dest.p1.y = dest.p2.y - object.get_bbox().get_height();
1185 } else if(constraints.get_position_top() > -infinity) {
1186 dest.p1.y = constraints.get_position_top() + DELTA;
1187 dest.p2.y = dest.p1.y + object.get_bbox().get_height();
1190 if(constraints.has_constraints()) {
1191 if(constraints.hit.bottom) {
1192 dest.move(constraints.ground_movement);
1194 if(constraints.hit.top || constraints.hit.bottom) {
1195 constraints.hit.left = false;
1196 constraints.hit.right = false;
1197 object.collision_solid(constraints.hit);
1201 constraints = Constraints();
1202 for(int i = 0; i < 2; ++i) {
1203 collision_static(&constraints, movement, dest, object);
1204 if(!constraints.has_constraints())
1207 // apply calculated vertical constraints
1208 float width = constraints.get_width ();
1209 if(width < infinity) {
1210 if(width + SHIFT_DELTA < object.get_bbox().get_width()) {
1212 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1213 constraints.get_position_left(), constraints.get_position_right());
1219 object.collision_solid(h);
1221 float xmid = constraints.get_x_midpoint ();
1222 dest.p1.x = xmid - object.get_bbox().get_width()/2;
1223 dest.p2.x = xmid + object.get_bbox().get_width()/2;
1225 } else if(constraints.get_position_right() < infinity) {
1226 dest.p2.x = constraints.get_position_right() - DELTA;
1227 dest.p1.x = dest.p2.x - object.get_bbox().get_width();
1228 } else if(constraints.get_position_left() > -infinity) {
1229 dest.p1.x = constraints.get_position_left() + DELTA;
1230 dest.p2.x = dest.p1.x + object.get_bbox().get_width();
1234 if(constraints.has_constraints()) {
1235 if( constraints.hit.left || constraints.hit.right
1236 || constraints.hit.top || constraints.hit.bottom
1237 || constraints.hit.crush )
1238 object.collision_solid(constraints.hit);
1241 // an extra pass to make sure we're not crushed horizontally
1242 constraints = Constraints();
1243 collision_static(&constraints, movement, dest, object);
1244 if(constraints.get_position_bottom() < infinity) {
1245 float height = constraints.get_height ();
1246 if(height + SHIFT_DELTA < object.get_bbox().get_height()) {
1248 printf("Object %p crushed vertically...\n", &object);
1254 object.collision_solid(h);
1260 const float MAX_SPEED = 16.0f;
1264 Sector::handle_collisions()
1266 using namespace collision;
1268 // calculate destination positions of the objects
1269 for(MovingObjects::iterator i = moving_objects.begin();
1270 i != moving_objects.end(); ++i) {
1271 MovingObject* moving_object = *i;
1272 Vector mov = moving_object->get_movement();
1274 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1275 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1276 moving_object->movement = mov.unit() * MAX_SPEED;
1277 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1280 moving_object->dest = moving_object->get_bbox();
1281 moving_object->dest.move(moving_object->get_movement());
1284 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1285 for(MovingObjects::iterator i = moving_objects.begin();
1286 i != moving_objects.end(); ++i) {
1287 MovingObject* moving_object = *i;
1288 if((moving_object->get_group() != COLGROUP_MOVING
1289 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1290 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1291 || !moving_object->is_valid())
1294 collision_static_constrains(*moving_object);
1297 // part2: COLGROUP_MOVING vs tile attributes
1298 for(MovingObjects::iterator i = moving_objects.begin();
1299 i != moving_objects.end(); ++i) {
1300 MovingObject* moving_object = *i;
1301 if((moving_object->get_group() != COLGROUP_MOVING
1302 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1303 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1304 || !moving_object->is_valid())
1307 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1308 if(tile_attributes >= Tile::FIRST_INTERESTING_FLAG) {
1309 moving_object->collision_tile(tile_attributes);
1313 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1314 for(MovingObjects::iterator i = moving_objects.begin();
1315 i != moving_objects.end(); ++i) {
1316 MovingObject* moving_object = *i;
1317 if((moving_object->get_group() != COLGROUP_MOVING
1318 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1319 || !moving_object->is_valid())
1322 for(MovingObjects::iterator i2 = moving_objects.begin();
1323 i2 != moving_objects.end(); ++i2) {
1324 MovingObject* moving_object_2 = *i2;
1325 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1326 || !moving_object_2->is_valid())
1329 if(intersects(moving_object->dest, moving_object_2->dest)) {
1332 get_hit_normal(moving_object->dest, moving_object_2->dest,
1334 if(!moving_object->collides(*moving_object_2, hit))
1336 if(!moving_object_2->collides(*moving_object, hit))
1339 moving_object->collision(*moving_object_2, hit);
1340 moving_object_2->collision(*moving_object, hit);
1345 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1346 for(MovingObjects::iterator i = moving_objects.begin();
1347 i != moving_objects.end(); ++i) {
1348 MovingObject* moving_object = *i;
1350 if((moving_object->get_group() != COLGROUP_MOVING
1351 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1352 || !moving_object->is_valid())
1355 for(MovingObjects::iterator i2 = i+1;
1356 i2 != moving_objects.end(); ++i2) {
1357 MovingObject* moving_object_2 = *i2;
1358 if((moving_object_2->get_group() != COLGROUP_MOVING
1359 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1360 || !moving_object_2->is_valid())
1363 collision_object(moving_object, moving_object_2);
1367 // apply object movement
1368 for(MovingObjects::iterator i = moving_objects.begin();
1369 i != moving_objects.end(); ++i) {
1370 MovingObject* moving_object = *i;
1372 moving_object->bbox = moving_object->dest;
1373 moving_object->movement = Vector(0, 0);
1378 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1380 using namespace collision;
1382 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1383 TileMap* solids = *i;
1385 // test with all tiles in this rectangle
1386 Rect test_tiles = solids->get_tiles_overlapping(rect);
1388 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1389 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1390 const Tile* tile = solids->get_tile(x, y);
1392 if(!(tile->getAttributes() & Tile::SOLID))
1394 if(tile->is_unisolid () && ignoreUnisolid)
1396 if(tile->is_slope ()) {
1397 AATriangle triangle;
1398 Rectf tbbox = solids->get_tile_bbox(x, y);
1399 triangle = AATriangle(tbbox, tile->getData());
1400 Constraints constraints;
1401 if(!collision::rectangle_aatriangle(&constraints, rect, triangle))
1404 // We have a solid tile that overlaps the given rectangle.
1414 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1416 using namespace collision;
1418 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1420 for(MovingObjects::const_iterator i = moving_objects.begin();
1421 i != moving_objects.end(); ++i) {
1422 const MovingObject* moving_object = *i;
1423 if (moving_object == ignore_object) continue;
1424 if (!moving_object->is_valid()) continue;
1425 if (moving_object->get_group() == COLGROUP_STATIC) {
1426 if(intersects(rect, moving_object->get_bbox())) return false;
1434 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1436 using namespace collision;
1438 if (!is_free_of_tiles(rect)) return false;
1440 for(MovingObjects::const_iterator i = moving_objects.begin();
1441 i != moving_objects.end(); ++i) {
1442 const MovingObject* moving_object = *i;
1443 if (moving_object == ignore_object) continue;
1444 if (!moving_object->is_valid()) continue;
1445 if ((moving_object->get_group() == COLGROUP_MOVING)
1446 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1447 || (moving_object->get_group() == COLGROUP_STATIC)) {
1448 if(intersects(rect, moving_object->get_bbox())) return false;
1456 Sector::add_bullet(const Vector& pos, const PlayerStatus* player_status, float xm, Direction dir)
1458 // TODO remove this function and move these checks elsewhere...
1460 Bullet* new_bullet = 0;
1461 if((player_status->bonus == FIRE_BONUS &&
1462 (int)bullets.size() >= player_status->max_fire_bullets) ||
1463 (player_status->bonus == ICE_BONUS &&
1464 (int)bullets.size() >= player_status->max_ice_bullets))
1466 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1467 add_object(new_bullet);
1469 sound_manager->play("sounds/shoot.wav");
1475 Sector::add_smoke_cloud(const Vector& pos)
1477 add_object(new SmokeCloud(pos));
1482 Sector::play_music(MusicType type)
1484 currentmusic = type;
1485 switch(currentmusic) {
1487 sound_manager->play_music(music);
1490 sound_manager->play_music("music/invincible.ogg");
1492 case HERRING_WARNING_MUSIC:
1493 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1496 sound_manager->play_music("");
1502 Sector::get_music_type()
1504 return currentmusic;
1508 Sector::get_total_badguys()
1510 int total_badguys = 0;
1511 for(GameObjects::iterator i = gameobjects.begin();
1512 i != gameobjects.end(); ++i) {
1513 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1514 if (badguy && badguy->countMe)
1518 return total_badguys;
1522 Sector::inside(const Rectf& rect) const
1524 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1525 TileMap* solids = *i;
1527 Rectf bbox = solids->get_bbox();
1528 bbox.p1.y = -INFINITY; // pretend the tilemap extends infinitely far upwards
1530 if (bbox.contains(rect))
1537 Sector::get_width() const
1540 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1541 i != solid_tilemaps.end(); i++) {
1542 TileMap* solids = *i;
1543 width = std::max(width, solids->get_bbox().get_right());
1550 Sector::get_height() const
1553 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1554 i != solid_tilemaps.end(); i++) {
1555 TileMap* solids = *i;
1556 height = std::max(height, solids->get_bbox().get_bottom());
1563 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1565 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1566 TileMap* solids = *i;
1567 solids->change_all(old_tile_id, new_tile_id);
1572 Sector::set_ambient_light(float red, float green, float blue)
1574 ambient_light.red = red;
1575 ambient_light.green = green;
1576 ambient_light.blue = blue;
1580 Sector::get_ambient_red()
1582 return ambient_light.red;
1586 Sector::get_ambient_green()
1588 return ambient_light.green;
1592 Sector::get_ambient_blue()
1594 return ambient_light.blue;
1598 Sector::set_gravity(float gravity)
1600 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1601 this->gravity = gravity;
1605 Sector::get_gravity() const
1611 Sector::get_nearest_player (const Vector& pos)
1613 Player *nearest_player = NULL;
1614 float nearest_dist = std::numeric_limits<float>::max();
1616 std::vector<Player*> players = Sector::current()->get_players();
1617 for (std::vector<Player*>::iterator playerIter = players.begin();
1618 playerIter != players.end();
1621 Player *this_player = *playerIter;
1622 if (this_player->is_dying() || this_player->is_dead())
1625 float this_dist = this_player->get_bbox ().distance(pos);
1627 if (this_dist < nearest_dist) {
1628 nearest_player = this_player;
1629 nearest_dist = this_dist;
1633 return nearest_player;
1634 } /* Player *get_nearest_player */
1636 std::vector<MovingObject*>
1637 Sector::get_nearby_objects (const Vector& center, float max_distance)
1639 std::vector<MovingObject*> ret;
1640 std::vector<Player*> players = Sector::current()->get_players();
1642 for (size_t i = 0; i < players.size (); i++) {
1643 float distance = players[i]->get_bbox ().distance (center);
1644 if (distance <= max_distance)
1645 ret.push_back (players[i]);
1648 for (size_t i = 0; i < moving_objects.size (); i++) {
1649 float distance = moving_objects[i]->get_bbox ().distance (center);
1650 if (distance <= max_distance)
1651 ret.push_back (moving_objects[i]);
1657 /* vim: set sw=2 sts=2 et : */