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_streambuf.hpp"
49 #include "scripting/scripting.hpp"
50 #include "scripting/squirrel_util.hpp"
51 #include "supertux/collision.hpp"
52 #include "supertux/constants.hpp"
53 #include "supertux/game_session.hpp"
54 #include "supertux/globals.hpp"
55 #include "supertux/level.hpp"
56 #include "supertux/object_factory.hpp"
57 #include "supertux/player_status.hpp"
58 #include "supertux/savegame.hpp"
59 #include "supertux/spawn_point.hpp"
60 #include "supertux/tile.hpp"
61 #include "trigger/secretarea_trigger.hpp"
62 #include "trigger/sequence_trigger.hpp"
63 #include "util/file_system.hpp"
65 Sector* Sector::_current = 0;
67 bool Sector::show_collrects = false;
68 bool Sector::draw_solids_only = false;
70 Sector::Sector(Level* parent) :
76 currentmusic(LEVEL_MUSIC),
79 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ),
92 add_object(std::make_shared<Player>(GameSession::current()->get_savegame().get_player_status(), "Tux"));
93 add_object(std::make_shared<DisplayEffect>("Effect"));
94 add_object(std::make_shared<TextObject>("Text"));
96 SoundManager::current()->preload("sounds/shoot.wav");
98 // create a new squirrel table for the sector
99 using namespace scripting;
101 sq_collectgarbage(global_vm);
103 sq_newtable(global_vm);
104 sq_pushroottable(global_vm);
105 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
106 throw scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
108 sq_resetobject(§or_table);
109 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
110 throw scripting::SquirrelError(global_vm, "Couldn't get sector table");
111 sq_addref(global_vm, §or_table);
112 sq_pop(global_vm, 1);
114 foremost_layer = calculate_foremost_layer();
119 using namespace scripting;
123 for(auto i = scripts.begin(); i != scripts.end(); ++i) {
124 HSQOBJECT& object = *i;
125 sq_release(global_vm, &object);
127 sq_release(global_vm, §or_table);
128 sq_collectgarbage(global_vm);
130 update_game_objects();
131 assert(gameobjects_new.size() == 0);
133 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
134 GameObjectPtr object = *i;
135 before_object_remove(object);
146 Sector::parse_object(const std::string& name_, const Reader& reader)
148 if(name_ == "camera") {
149 auto camera_ = std::make_shared<Camera>(this, "Camera");
150 camera_->parse(reader);
152 } else if(name_ == "particles-snow") {
153 auto partsys = std::make_shared<SnowParticleSystem>();
154 partsys->parse(reader);
156 } else if(name_ == "particles-rain") {
157 auto partsys = std::make_shared<RainParticleSystem>();
158 partsys->parse(reader);
160 } else if(name_ == "particles-comets") {
161 auto partsys = std::make_shared<CometParticleSystem>();
162 partsys->parse(reader);
164 } else if(name_ == "particles-ghosts") {
165 auto partsys = std::make_shared<GhostParticleSystem>();
166 partsys->parse(reader);
168 } else if(name_ == "particles-clouds") {
169 auto partsys = std::make_shared<CloudParticleSystem>();
170 partsys->parse(reader);
172 } else if(name_ == "money") { // for compatibility with old maps
173 return std::make_shared<Jumpy>(reader);
176 return ObjectFactory::instance().create(name_, reader);
177 } catch(std::exception& e) {
178 log_warning << e.what() << "" << std::endl;
185 Sector::parse(const Reader& sector)
187 bool has_background = false;
188 lisp::ListIterator iter(§or);
190 const std::string& token = iter.item();
191 if(token == "name") {
192 iter.value()->get(name);
193 } else if(token == "gravity") {
194 iter.value()->get(gravity);
195 } else if(token == "music") {
196 iter.value()->get(music);
197 } else if(token == "spawnpoint") {
198 auto sp = std::make_shared<SpawnPoint>(*iter.lisp());
199 spawnpoints.push_back(sp);
200 } else if(token == "init-script") {
201 iter.value()->get(init_script);
202 } else if(token == "ambient-light") {
203 std::vector<float> vColor;
204 sector.get( "ambient-light", vColor );
205 if(vColor.size() < 3) {
206 log_warning << "(ambient-light) requires a color as argument" << std::endl;
208 ambient_light = Color( vColor );
211 GameObjectPtr object = parse_object(token, *(iter.lisp()));
213 if(std::dynamic_pointer_cast<Background>(object)) {
214 has_background = true;
215 } else if(std::dynamic_pointer_cast<Gradient>(object)) {
216 has_background = true;
223 if(!has_background) {
224 auto gradient = std::make_shared<Gradient>();
225 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
226 add_object(gradient);
229 update_game_objects();
231 if(solid_tilemaps.size() < 1) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
235 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
236 update_game_objects();
237 add_object(std::make_shared<Camera>(this, "Camera"));
240 update_game_objects();
244 Sector::parse_old_format(const Reader& reader)
247 reader.get("gravity", gravity);
249 std::string backgroundimage;
250 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
251 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
252 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
253 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
254 backgroundimage = "images/background/" + backgroundimage;
255 if (!PHYSFS_exists(backgroundimage.c_str())) {
256 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
257 backgroundimage = "";
262 reader.get("bkgd_speed", bgspeed);
265 Color bkgd_top, bkgd_bottom;
266 int r = 0, g = 0, b = 128;
267 reader.get("bkgd_red_top", r);
268 reader.get("bkgd_green_top", g);
269 reader.get("bkgd_blue_top", b);
270 bkgd_top.red = static_cast<float> (r) / 255.0f;
271 bkgd_top.green = static_cast<float> (g) / 255.0f;
272 bkgd_top.blue = static_cast<float> (b) / 255.0f;
274 reader.get("bkgd_red_bottom", r);
275 reader.get("bkgd_green_bottom", g);
276 reader.get("bkgd_blue_bottom", b);
277 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
278 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
279 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
281 if(backgroundimage != "") {
282 auto background = std::make_shared<Background>();
283 background->set_image(backgroundimage, bgspeed);
284 add_object(background);
286 auto gradient = std::make_shared<Gradient>();
287 gradient->set_gradient(bkgd_top, bkgd_bottom);
288 add_object(gradient);
291 std::string particlesystem;
292 reader.get("particle_system", particlesystem);
293 if(particlesystem == "clouds")
294 add_object(std::make_shared<CloudParticleSystem>());
295 else if(particlesystem == "snow")
296 add_object(std::make_shared<SnowParticleSystem>());
297 else if(particlesystem == "rain")
298 add_object(std::make_shared<RainParticleSystem>());
300 Vector startpos(100, 170);
301 reader.get("start_pos_x", startpos.x);
302 reader.get("start_pos_y", startpos.y);
304 auto spawn = std::make_shared<SpawnPoint>();
305 spawn->pos = startpos;
306 spawn->name = "main";
307 spawnpoints.push_back(spawn);
309 music = "chipdisko.ogg";
310 // skip reading music filename. It's all .ogg now, anyway
312 reader.get("music", music);
314 music = "music/" + music;
316 int width = 30, height = 15;
317 reader.get("width", width);
318 reader.get("height", height);
320 std::vector<unsigned int> tiles;
321 if(reader.get("interactive-tm", tiles)
322 || reader.get("tilemap", tiles)) {
323 auto tilemap = std::make_shared<TileMap>(level->get_tileset());
324 tilemap->set(width, height, tiles, LAYER_TILES, true);
326 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
327 for(size_t x=0; x < tilemap->get_width(); ++x) {
328 for(size_t y=0; y < tilemap->get_height(); ++y) {
329 uint32_t id = tilemap->get_tile_id(x, y);
331 tilemap->change(x, y, 1311);
335 if (height < 19) tilemap->resize(width, 19);
339 if(reader.get("background-tm", tiles)) {
340 auto tilemap = std::make_shared<TileMap>(level->get_tileset());
341 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
342 if (height < 19) tilemap->resize(width, 19);
346 if(reader.get("foreground-tm", tiles)) {
347 auto tilemap = std::make_shared<TileMap>(level->get_tileset());
348 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
350 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
351 if (height < 19) tilemap->resize(width, 19, 2035);
356 // read reset-points (now spawn-points)
357 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
359 lisp::ListIterator iter(resetpoints);
361 if(iter.item() == "point") {
363 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
365 auto sp = std::make_shared<SpawnPoint>();
368 spawnpoints.push_back(sp);
371 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
377 const lisp::Lisp* objects = reader.get_lisp("objects");
379 lisp::ListIterator iter(objects);
381 auto object = parse_object(iter.item(), *(iter.lisp()));
385 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
391 auto camera_ = std::make_shared<Camera>(this, "Camera");
394 update_game_objects();
396 if(solid_tilemaps.size() < 1) { log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl; }
399 update_game_objects();
403 Sector::fix_old_tiles()
405 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
406 TileMap* solids = *i;
407 for(size_t x=0; x < solids->get_width(); ++x) {
408 for(size_t y=0; y < solids->get_height(); ++y) {
409 uint32_t id = solids->get_tile_id(x, y);
410 const Tile *tile = solids->get_tile(x, y);
411 Vector pos = solids->get_tile_position(x, y);
414 add_object(std::make_shared<InvisibleBlock>(pos));
415 solids->change(x, y, 0);
416 } else if(tile->getAttributes() & Tile::COIN) {
417 add_object(std::make_shared<Coin>(pos, solids));
418 solids->change(x, y, 0);
419 } else if(tile->getAttributes() & Tile::FULLBOX) {
420 add_object(std::make_shared<BonusBlock>(pos, tile->getData()));
421 solids->change(x, y, 0);
422 } else if(tile->getAttributes() & Tile::BRICK) {
423 if( ( id == 78 ) || ( id == 105 ) ){
424 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brickIce.sprite") );
425 } else if( ( id == 77 ) || ( id == 104 ) ){
426 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
428 log_warning << "attribute 'brick #t' is not supported for tile-id " << id << std::endl;
429 add_object( std::make_shared<Brick>(pos, tile->getData(), "images/objects/bonus_block/brick.sprite") );
431 solids->change(x, y, 0);
432 } else if(tile->getAttributes() & Tile::GOAL) {
433 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
434 add_object(std::make_shared<SequenceTrigger>(pos, sequence));
435 solids->change(x, y, 0);
441 // add lights for special tiles
442 for(auto i = gameobjects.begin(); i != gameobjects.end(); i++) {
443 TileMap* tm = dynamic_cast<TileMap*>(i->get());
445 for(size_t x=0; x < tm->get_width(); ++x) {
446 for(size_t y=0; y < tm->get_height(); ++y) {
447 uint32_t id = tm->get_tile_id(x, y);
448 Vector pos = tm->get_tile_position(x, y);
449 Vector center = pos + Vector(16, 16);
453 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
454 add_object(std::make_shared<PulsingLight>(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
457 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
458 // space lights a bit
459 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
460 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
461 || ((x % 3 == 0) && (y % 3 == 0))) {
462 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
463 add_object(std::make_shared<PulsingLight>(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
474 Sector::run_script(std::istream& in, const std::string& sourcename)
476 using namespace scripting;
478 // garbage collect thread list
479 for(auto i = scripts.begin(); i != scripts.end(); ) {
480 HSQOBJECT& object = *i;
481 HSQUIRRELVM vm = object_to_vm(object);
483 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
484 sq_release(global_vm, &object);
485 i = scripts.erase(i);
492 HSQOBJECT object = create_thread(global_vm);
493 scripts.push_back(object);
495 HSQUIRRELVM vm = object_to_vm(object);
497 // set sector_table as roottable for the thread
498 sq_pushobject(vm, sector_table);
502 compile_and_run(vm, in, "Sector " + name + " - " + sourcename);
503 } catch(std::exception& e) {
504 log_warning << "Error running script: " << e.what() << std::endl;
511 Sector::add_object(GameObjectPtr object)
513 // make sure the object isn't already in the list
515 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
516 assert(*i != object);
518 for(auto i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i) {
519 assert(*i != object);
523 gameobjects_new.push_back(object);
527 Sector::activate(const std::string& spawnpoint)
529 std::shared_ptr<SpawnPoint> sp;
530 for(auto i = spawnpoints.begin(); i != spawnpoints.end(); ++i) {
531 if((*i)->name == spawnpoint) {
537 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
538 if(spawnpoint != "main") {
541 activate(Vector(0, 0));
549 Sector::activate(const Vector& player_pos)
551 if(_current != this) {
553 _current->deactivate();
556 // register sectortable as sector in scripting
557 HSQUIRRELVM vm = scripting::global_vm;
558 sq_pushroottable(vm);
559 sq_pushstring(vm, "sector", -1);
560 sq_pushobject(vm, sector_table);
561 if(SQ_FAILED(sq_createslot(vm, -3)))
562 throw scripting::SquirrelError(vm, "Couldn't set sector in roottable");
565 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
566 GameObjectPtr object = *i;
574 // two-player hack: move other players to main player's position
575 // Maybe specify 2 spawnpoints in the level?
576 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
577 Player* p = dynamic_cast<Player*>(i->get());
580 // spawn smalltux below spawnpoint
582 p->move(player_pos + Vector(0,32));
587 // spawning tux in the ground would kill him
588 if(!is_free_of_tiles(p->get_bbox())) {
589 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
590 Vector npos = p->get_bbox().p1;
596 //FIXME: This is a really dirty workaround for this strange camera jump
597 player->move(player->get_pos()+Vector(-32, 0));
598 camera->reset(player->get_pos());
600 player->move(player->get_pos()+(Vector(32, 0)));
603 update_game_objects();
605 //Run default.nut just before init script
606 //Check to see if it's in a levelset (info file)
607 std::string basedir = FileSystem::dirname(get_level()->filename);
608 if(PHYSFS_exists((basedir + "/info").c_str())) {
610 IFileStreambuf ins(basedir + "/default.nut");
611 std::istream in(&ins);
612 run_script(in, "default.nut");
613 } catch(std::exception& ) {
614 // doesn't exist or erroneous; do nothing
619 if(init_script != "") {
620 std::istringstream in(init_script);
621 run_script(in, "init-script");
631 // remove sector entry from global vm
632 HSQUIRRELVM vm = scripting::global_vm;
633 sq_pushroottable(vm);
634 sq_pushstring(vm, "sector", -1);
635 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
636 throw scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
639 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
640 GameObjectPtr object = *i;
642 try_unexpose(object);
650 Sector::get_active_region()
653 camera->get_translation() - Vector(1600, 1200),
654 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
658 Sector::calculate_foremost_layer()
661 std::vector<std::string> secret_area_layers;
662 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
664 SecretAreaTrigger* trigger = dynamic_cast<SecretAreaTrigger*>(i->get());
665 if (!trigger) continue;
666 secret_area_layers.push_back(trigger->get_fade_tilemap_name());
669 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
671 TileMap* tm = dynamic_cast<TileMap*>(i->get());
673 if(tm->get_layer() > foremost_layer)
675 if (std::find(secret_area_layers.begin(), secret_area_layers.end(), tm->get_name())
676 != secret_area_layers.end() || tm->is_solid())
678 layer = tm->get_layer();
686 Sector::get_foremost_layer()
688 return foremost_layer;
692 Sector::update(float elapsed_time)
694 player->check_bounds();
697 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
698 GameObjectPtr& object = *i;
699 if(!object->is_valid())
702 object->update(elapsed_time);
705 /* Handle all possible collisions. */
707 update_game_objects();
711 Sector::update_game_objects()
713 /** cleanup marked objects */
714 for(auto i = gameobjects.begin();
715 i != gameobjects.end(); /* nothing */) {
716 GameObjectPtr& object = *i;
718 if(object->is_valid()) {
723 before_object_remove(object);
725 i = gameobjects.erase(i);
728 /* add newly created objects */
729 for(auto i = gameobjects_new.begin();
730 i != gameobjects_new.end(); ++i)
732 GameObjectPtr object = *i;
734 before_object_add(object);
736 gameobjects.push_back(object);
738 gameobjects_new.clear();
740 /* update solid_tilemaps list */
741 //FIXME: this could be more efficient
742 solid_tilemaps.clear();
743 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i)
745 TileMap* tm = dynamic_cast<TileMap*>(i->get());
747 if (tm->is_solid()) solid_tilemaps.push_back(tm);
753 Sector::before_object_add(GameObjectPtr object)
755 auto bullet = dynamic_cast<Bullet*>(object.get());
758 bullets.push_back(bullet);
761 auto movingobject = dynamic_cast<MovingObject*>(object.get());
764 moving_objects.push_back(movingobject);
767 auto portable = dynamic_cast<Portable*>(object.get());
770 portables.push_back(portable);
773 auto tilemap = dynamic_cast<TileMap*>(object.get());
774 if(tilemap && tilemap->is_solid()) {
775 solid_tilemaps.push_back(tilemap);
778 auto camera_ = dynamic_cast<Camera*>(object.get());
780 if(this->camera != 0) {
781 log_warning << "Multiple cameras added. Ignoring" << std::endl;
784 this->camera = camera_;
787 auto player_ = dynamic_cast<Player*>(object.get());
789 if(this->player != 0) {
790 log_warning << "Multiple players added. Ignoring" << std::endl;
793 this->player = player_;
796 auto effect_ = dynamic_cast<DisplayEffect*>(object.get());
798 if(this->effect != 0) {
799 log_warning << "Multiple DisplayEffects added. Ignoring" << std::endl;
802 this->effect = effect_;
805 if(_current == this) {
813 Sector::try_expose(GameObjectPtr object)
815 ScriptInterface* object_ = dynamic_cast<ScriptInterface*>(object.get());
816 if(object_ != NULL) {
817 HSQUIRRELVM vm = scripting::global_vm;
818 sq_pushobject(vm, sector_table);
819 object_->expose(vm, -1);
825 Sector::try_expose_me()
827 HSQUIRRELVM vm = scripting::global_vm;
828 sq_pushobject(vm, sector_table);
829 scripting::SSector* this_ = static_cast<scripting::SSector*>(this);
830 expose_object(vm, -1, this_, "settings", false);
835 Sector::before_object_remove(GameObjectPtr object)
837 Portable* portable = dynamic_cast<Portable*>(object.get());
839 portables.erase(std::find(portables.begin(), portables.end(), portable));
841 Bullet* bullet = dynamic_cast<Bullet*>(object.get());
843 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
845 MovingObject* moving_object = dynamic_cast<MovingObject*>(object.get());
847 moving_objects.erase(
848 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
852 try_unexpose(object);
856 Sector::try_unexpose(GameObjectPtr object)
858 ScriptInterface* object_ = dynamic_cast<ScriptInterface*>(object.get());
859 if(object_ != NULL) {
860 HSQUIRRELVM vm = scripting::global_vm;
861 SQInteger oldtop = sq_gettop(vm);
862 sq_pushobject(vm, sector_table);
864 object_->unexpose(vm, -1);
865 } catch(std::exception& e) {
866 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
868 sq_settop(vm, oldtop);
873 Sector::try_unexpose_me()
875 HSQUIRRELVM vm = scripting::global_vm;
876 SQInteger oldtop = sq_gettop(vm);
877 sq_pushobject(vm, sector_table);
879 scripting::unexpose_object(vm, -1, "settings");
880 } catch(std::exception& e) {
881 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
883 sq_settop(vm, oldtop);
886 Sector::draw(DrawingContext& context)
888 context.set_ambient_color( ambient_light );
889 context.push_transform();
890 context.set_translation(camera->get_translation());
892 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
893 GameObjectPtr& object = *i;
894 if(!object->is_valid())
897 if (draw_solids_only)
899 TileMap* tm = dynamic_cast<TileMap*>(object.get());
900 if (tm && !tm->is_solid())
904 object->draw(context);
908 Color color(1.0f, 0.0f, 0.0f, 0.75f);
909 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
910 MovingObject* object = *i;
911 const Rectf& rect = object->get_bbox();
913 context.draw_filled_rect(rect, color, LAYER_FOREGROUND1 + 10);
917 context.pop_transform();
920 /*-------------------------------------------------------------------------
921 * Collision Detection
922 *-------------------------------------------------------------------------*/
924 /** r1 is supposed to be moving, r2 a solid object */
925 void check_collisions(collision::Constraints* constraints,
926 const Vector& obj_movement, const Rectf& obj_rect, const Rectf& other_rect,
927 GameObject* object = NULL, MovingObject* other = NULL, const Vector& other_movement = Vector(0,0))
929 if(!collision::intersects(obj_rect, other_rect))
932 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
934 if(other != NULL && !other->collides(*object, dummy))
936 if(moving_object != NULL && !moving_object->collides(*other, dummy))
939 // calculate intersection
940 float itop = obj_rect.get_bottom() - other_rect.get_top();
941 float ibottom = other_rect.get_bottom() - obj_rect.get_top();
942 float ileft = obj_rect.get_right() - other_rect.get_left();
943 float iright = other_rect.get_right() - obj_rect.get_left();
945 if(fabsf(obj_movement.y) > fabsf(obj_movement.x)) {
946 if(ileft < SHIFT_DELTA) {
947 constraints->constrain_right(other_rect.get_left(), other_movement.x);
949 } else if(iright < SHIFT_DELTA) {
950 constraints->constrain_left(other_rect.get_right(), other_movement.x);
954 // shiftout bottom/top
955 if(itop < SHIFT_DELTA) {
956 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
958 } else if(ibottom < SHIFT_DELTA) {
959 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
964 constraints->ground_movement += other_movement;
966 HitResponse response = other->collision(*object, dummy);
967 if(response == ABORT_MOVE)
970 if(other->get_movement() != Vector(0, 0)) {
971 // TODO what todo when we collide with 2 moving objects?!?
972 constraints->ground_movement = other->get_movement();
976 float vert_penetration = std::min(itop, ibottom);
977 float horiz_penetration = std::min(ileft, iright);
978 if(vert_penetration < horiz_penetration) {
980 constraints->constrain_bottom(other_rect.get_top(), other_movement.y);
981 constraints->hit.bottom = true;
983 constraints->constrain_top(other_rect.get_bottom(), other_movement.y);
984 constraints->hit.top = true;
988 constraints->constrain_right(other_rect.get_left(), other_movement.x);
989 constraints->hit.right = true;
991 constraints->constrain_left(other_rect.get_right(), other_movement.x);
992 constraints->hit.left = true;
998 Sector::collision_tilemap(collision::Constraints* constraints,
999 const Vector& movement, const Rectf& dest,
1000 MovingObject& object) const
1002 // calculate rectangle where the object will move
1003 float x1 = dest.get_left();
1004 float x2 = dest.get_right();
1005 float y1 = dest.get_top();
1006 float y2 = dest.get_bottom();
1008 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1009 TileMap* solids = *i;
1011 // test with all tiles in this rectangle
1012 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1014 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1015 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1016 const Tile* tile = solids->get_tile(x, y);
1019 // skip non-solid tiles
1020 if(!tile->is_solid ())
1022 Rectf tile_bbox = solids->get_tile_bbox(x, y);
1024 /* If the tile is a unisolid tile, the "is_solid()" function above
1025 * didn't do a thorough check. Calculate the position and (relative)
1026 * movement of the object and determine whether or not the tile is
1027 * solid with regard to those parameters. */
1028 if(tile->is_unisolid ()) {
1029 Vector relative_movement = movement
1030 - solids->get_movement(/* actual = */ true);
1032 if (!tile->is_solid (tile_bbox, object.get_bbox(), relative_movement))
1034 } /* if (tile->is_unisolid ()) */
1036 if(tile->is_slope ()) { // slope tile
1037 AATriangle triangle;
1038 int slope_data = tile->getData();
1039 if (solids->get_drawing_effect() & VERTICAL_FLIP)
1040 slope_data = AATriangle::vertical_flip(slope_data);
1041 triangle = AATriangle(tile_bbox, slope_data);
1043 collision::rectangle_aatriangle(constraints, dest, triangle,
1044 solids->get_movement(/* actual = */ false));
1045 } else { // normal rectangular tile
1046 check_collisions(constraints, movement, dest, tile_bbox, NULL, NULL,
1047 solids->get_movement(/* actual = */ false));
1055 Sector::collision_tile_attributes(const Rectf& dest) const
1057 float x1 = dest.p1.x;
1058 float y1 = dest.p1.y;
1059 float x2 = dest.p2.x;
1060 float y2 = dest.p2.y;
1062 uint32_t result = 0;
1063 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1064 TileMap* solids = *i;
1066 // test with all tiles in this rectangle
1067 Rect test_tiles = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2));
1068 // For ice (only), add a little fudge to recognize tiles Tux is standing on.
1069 Rect test_tiles_ice = solids->get_tiles_overlapping(Rectf(x1, y1, x2, y2 + SHIFT_DELTA));
1071 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1073 for(y = test_tiles.top; y < test_tiles.bottom; ++y) {
1074 const Tile* tile = solids->get_tile(x, y);
1077 result |= tile->getAttributes();
1079 for(; y < test_tiles_ice.bottom; ++y) {
1080 const Tile* tile = solids->get_tile(x, y);
1083 result |= (tile->getAttributes() & Tile::ICE);
1091 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1092 static void get_hit_normal(const Rectf& r1, const Rectf& r2, CollisionHit& hit,
1095 float itop = r1.get_bottom() - r2.get_top();
1096 float ibottom = r2.get_bottom() - r1.get_top();
1097 float ileft = r1.get_right() - r2.get_left();
1098 float iright = r2.get_right() - r1.get_left();
1100 float vert_penetration = std::min(itop, ibottom);
1101 float horiz_penetration = std::min(ileft, iright);
1102 if(vert_penetration < horiz_penetration) {
1103 if(itop < ibottom) {
1105 normal.y = vert_penetration;
1108 normal.y = -vert_penetration;
1111 if(ileft < iright) {
1113 normal.x = horiz_penetration;
1116 normal.x = -horiz_penetration;
1122 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1124 using namespace collision;
1126 const Rectf& r1 = object1->dest;
1127 const Rectf& r2 = object2->dest;
1130 if(intersects(object1->dest, object2->dest)) {
1132 get_hit_normal(r1, r2, hit, normal);
1134 if(!object1->collides(*object2, hit))
1136 std::swap(hit.left, hit.right);
1137 std::swap(hit.top, hit.bottom);
1138 if(!object2->collides(*object1, hit))
1140 std::swap(hit.left, hit.right);
1141 std::swap(hit.top, hit.bottom);
1143 HitResponse response1 = object1->collision(*object2, hit);
1144 std::swap(hit.left, hit.right);
1145 std::swap(hit.top, hit.bottom);
1146 HitResponse response2 = object2->collision(*object1, hit);
1147 if(response1 == CONTINUE && response2 == CONTINUE) {
1148 normal *= (0.5 + DELTA);
1149 object1->dest.move(-normal);
1150 object2->dest.move(normal);
1151 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1152 normal *= (1 + DELTA);
1153 object1->dest.move(-normal);
1154 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1155 normal *= (1 + DELTA);
1156 object2->dest.move(normal);
1162 Sector::collision_static(collision::Constraints* constraints,
1163 const Vector& movement, const Rectf& dest,
1164 MovingObject& object)
1166 collision_tilemap(constraints, movement, dest, object);
1168 // collision with other (static) objects
1169 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1170 MovingObject* moving_object = *i;
1171 if(moving_object->get_group() != COLGROUP_STATIC
1172 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1174 if(!moving_object->is_valid())
1177 if(moving_object != &object)
1178 check_collisions(constraints, movement, dest, moving_object->bbox,
1179 &object, moving_object);
1184 Sector::collision_static_constrains(MovingObject& object)
1186 using namespace collision;
1187 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1189 Constraints constraints;
1190 Vector movement = object.get_movement();
1191 Rectf& dest = object.dest;
1193 for(int i = 0; i < 2; ++i) {
1194 collision_static(&constraints, Vector(0, movement.y), dest, object);
1195 if(!constraints.has_constraints())
1198 // apply calculated horizontal constraints
1199 if(constraints.get_position_bottom() < infinity) {
1200 float height = constraints.get_height ();
1201 if(height < object.get_bbox().get_height()) {
1202 // we're crushed, but ignore this for now, we'll get this again
1203 // later if we're really crushed or things will solve itself when
1204 // looking at the vertical constraints
1206 dest.p2.y = constraints.get_position_bottom() - DELTA;
1207 dest.p1.y = dest.p2.y - object.get_bbox().get_height();
1208 } else if(constraints.get_position_top() > -infinity) {
1209 dest.p1.y = constraints.get_position_top() + DELTA;
1210 dest.p2.y = dest.p1.y + object.get_bbox().get_height();
1213 if(constraints.has_constraints()) {
1214 if(constraints.hit.bottom) {
1215 dest.move(constraints.ground_movement);
1217 if(constraints.hit.top || constraints.hit.bottom) {
1218 constraints.hit.left = false;
1219 constraints.hit.right = false;
1220 object.collision_solid(constraints.hit);
1224 constraints = Constraints();
1225 for(int i = 0; i < 2; ++i) {
1226 collision_static(&constraints, movement, dest, object);
1227 if(!constraints.has_constraints())
1230 // apply calculated vertical constraints
1231 float width = constraints.get_width ();
1232 if(width < infinity) {
1233 if(width + SHIFT_DELTA < object.get_bbox().get_width()) {
1235 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1236 constraints.get_position_left(), constraints.get_position_right());
1242 object.collision_solid(h);
1244 float xmid = constraints.get_x_midpoint ();
1245 dest.p1.x = xmid - object.get_bbox().get_width()/2;
1246 dest.p2.x = xmid + object.get_bbox().get_width()/2;
1248 } else if(constraints.get_position_right() < infinity) {
1249 dest.p2.x = constraints.get_position_right() - DELTA;
1250 dest.p1.x = dest.p2.x - object.get_bbox().get_width();
1251 } else if(constraints.get_position_left() > -infinity) {
1252 dest.p1.x = constraints.get_position_left() + DELTA;
1253 dest.p2.x = dest.p1.x + object.get_bbox().get_width();
1257 if(constraints.has_constraints()) {
1258 if( constraints.hit.left || constraints.hit.right
1259 || constraints.hit.top || constraints.hit.bottom
1260 || constraints.hit.crush )
1261 object.collision_solid(constraints.hit);
1264 // an extra pass to make sure we're not crushed horizontally
1265 constraints = Constraints();
1266 collision_static(&constraints, movement, dest, object);
1267 if(constraints.get_position_bottom() < infinity) {
1268 float height = constraints.get_height ();
1269 if(height + SHIFT_DELTA < object.get_bbox().get_height()) {
1271 printf("Object %p crushed vertically...\n", &object);
1277 object.collision_solid(h);
1283 const float MAX_SPEED = 16.0f;
1287 Sector::handle_collisions()
1289 using namespace collision;
1291 // calculate destination positions of the objects
1292 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1293 MovingObject* moving_object = *i;
1294 Vector mov = moving_object->get_movement();
1296 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1297 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1298 moving_object->movement = mov.unit() * MAX_SPEED;
1299 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1302 moving_object->dest = moving_object->get_bbox();
1303 moving_object->dest.move(moving_object->get_movement());
1306 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1307 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1308 MovingObject* moving_object = *i;
1309 if((moving_object->get_group() != COLGROUP_MOVING
1310 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1311 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1312 || !moving_object->is_valid())
1315 collision_static_constrains(*moving_object);
1318 // part2: COLGROUP_MOVING vs tile attributes
1319 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1320 MovingObject* moving_object = *i;
1321 if((moving_object->get_group() != COLGROUP_MOVING
1322 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1323 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1324 || !moving_object->is_valid())
1327 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1328 if(tile_attributes >= Tile::FIRST_INTERESTING_FLAG) {
1329 moving_object->collision_tile(tile_attributes);
1333 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1334 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1335 MovingObject* moving_object = *i;
1336 if((moving_object->get_group() != COLGROUP_MOVING
1337 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1338 || !moving_object->is_valid())
1341 for(auto i2 = moving_objects.begin(); i2 != moving_objects.end(); ++i2) {
1342 MovingObject* moving_object_2 = *i2;
1343 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1344 || !moving_object_2->is_valid())
1347 if(intersects(moving_object->dest, moving_object_2->dest)) {
1350 get_hit_normal(moving_object->dest, moving_object_2->dest,
1352 if(!moving_object->collides(*moving_object_2, hit))
1354 if(!moving_object_2->collides(*moving_object, hit))
1357 moving_object->collision(*moving_object_2, hit);
1358 moving_object_2->collision(*moving_object, hit);
1363 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1364 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1365 MovingObject* moving_object = *i;
1367 if((moving_object->get_group() != COLGROUP_MOVING
1368 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1369 || !moving_object->is_valid())
1372 for(auto i2 = i+1; i2 != moving_objects.end(); ++i2) {
1373 MovingObject* moving_object_2 = *i2;
1374 if((moving_object_2->get_group() != COLGROUP_MOVING
1375 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1376 || !moving_object_2->is_valid())
1379 collision_object(moving_object, moving_object_2);
1383 // apply object movement
1384 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1385 MovingObject* moving_object = *i;
1387 moving_object->bbox = moving_object->dest;
1388 moving_object->movement = Vector(0, 0);
1393 Sector::is_free_of_tiles(const Rectf& rect, const bool ignoreUnisolid) const
1395 using namespace collision;
1397 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1398 TileMap* solids = *i;
1400 // test with all tiles in this rectangle
1401 Rect test_tiles = solids->get_tiles_overlapping(rect);
1403 for(int x = test_tiles.left; x < test_tiles.right; ++x) {
1404 for(int y = test_tiles.top; y < test_tiles.bottom; ++y) {
1405 const Tile* tile = solids->get_tile(x, y);
1407 if(!(tile->getAttributes() & Tile::SOLID))
1409 if(tile->is_unisolid () && ignoreUnisolid)
1411 if(tile->is_slope ()) {
1412 AATriangle triangle;
1413 Rectf tbbox = solids->get_tile_bbox(x, y);
1414 triangle = AATriangle(tbbox, tile->getData());
1415 Constraints constraints;
1416 if(!collision::rectangle_aatriangle(&constraints, rect, triangle))
1419 // We have a solid tile that overlaps the given rectangle.
1429 Sector::is_free_of_statics(const Rectf& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1431 using namespace collision;
1433 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1435 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1436 const MovingObject* moving_object = *i;
1437 if (moving_object == ignore_object) continue;
1438 if (!moving_object->is_valid()) continue;
1439 if (moving_object->get_group() == COLGROUP_STATIC) {
1440 if(intersects(rect, moving_object->get_bbox())) return false;
1448 Sector::is_free_of_movingstatics(const Rectf& rect, const MovingObject* ignore_object) const
1450 using namespace collision;
1452 if (!is_free_of_tiles(rect)) return false;
1454 for(auto i = moving_objects.begin(); i != moving_objects.end(); ++i) {
1455 const MovingObject* moving_object = *i;
1456 if (moving_object == ignore_object) continue;
1457 if (!moving_object->is_valid()) continue;
1458 if ((moving_object->get_group() == COLGROUP_MOVING)
1459 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1460 || (moving_object->get_group() == COLGROUP_STATIC)) {
1461 if(intersects(rect, moving_object->get_bbox())) return false;
1469 Sector::add_bullet(const Vector& pos, const PlayerStatus* player_status, float xm, Direction dir)
1471 // TODO remove this function and move these checks elsewhere...
1472 if((player_status->bonus == FIRE_BONUS &&
1473 (int)bullets.size() >= player_status->max_fire_bullets) ||
1474 (player_status->bonus == ICE_BONUS &&
1475 (int)bullets.size() >= player_status->max_ice_bullets))
1477 auto new_bullet = std::make_shared<Bullet>(pos, xm, dir, player_status->bonus);
1478 add_object(new_bullet);
1480 SoundManager::current()->play("sounds/shoot.wav");
1486 Sector::add_smoke_cloud(const Vector& pos)
1488 add_object(std::make_shared<SmokeCloud>(pos));
1493 Sector::play_music(MusicType type)
1495 currentmusic = type;
1496 switch(currentmusic) {
1498 SoundManager::current()->play_music(music);
1501 SoundManager::current()->play_music("music/invincible.ogg");
1503 case HERRING_WARNING_MUSIC:
1504 SoundManager::current()->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1507 SoundManager::current()->play_music("");
1513 Sector::get_music_type()
1515 return currentmusic;
1519 Sector::get_total_badguys()
1521 int total_badguys = 0;
1522 for(auto i = gameobjects.begin(); i != gameobjects.end(); ++i) {
1523 BadGuy* badguy = dynamic_cast<BadGuy*>(i->get());
1524 if (badguy && badguy->countMe)
1528 return total_badguys;
1532 Sector::inside(const Rectf& rect) const
1534 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1535 TileMap* solids = *i;
1537 Rectf bbox = solids->get_bbox();
1538 bbox.p1.y = -INFINITY; // pretend the tilemap extends infinitely far upwards
1540 if (bbox.contains(rect))
1547 Sector::get_width() const
1550 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1551 TileMap* solids = *i;
1552 width = std::max(width, solids->get_bbox().get_right());
1559 Sector::get_height() const
1562 for(auto i = solid_tilemaps.begin();
1563 i != solid_tilemaps.end(); i++) {
1564 TileMap* solids = *i;
1565 height = std::max(height, solids->get_bbox().get_bottom());
1572 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1574 for(auto i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1575 TileMap* solids = *i;
1576 solids->change_all(old_tile_id, new_tile_id);
1581 Sector::set_ambient_light(float red, float green, float blue)
1583 ambient_light.red = red;
1584 ambient_light.green = green;
1585 ambient_light.blue = blue;
1589 Sector::get_ambient_red()
1591 return ambient_light.red;
1595 Sector::get_ambient_green()
1597 return ambient_light.green;
1601 Sector::get_ambient_blue()
1603 return ambient_light.blue;
1607 Sector::set_gravity(float gravity_)
1609 log_warning << "Changing a Sector's gravitational constant might have unforeseen side-effects" << std::endl;
1610 this->gravity = gravity_;
1614 Sector::get_gravity() const
1620 Sector::get_nearest_player (const Vector& pos)
1622 Player *nearest_player = NULL;
1623 float nearest_dist = std::numeric_limits<float>::max();
1625 std::vector<Player*> players = Sector::current()->get_players();
1626 for (auto playerIter = players.begin(); playerIter != players.end(); ++playerIter)
1628 Player *this_player = *playerIter;
1629 if (this_player->is_dying() || this_player->is_dead())
1632 float this_dist = this_player->get_bbox ().distance(pos);
1634 if (this_dist < nearest_dist) {
1635 nearest_player = this_player;
1636 nearest_dist = this_dist;
1640 return nearest_player;
1641 } /* Player *get_nearest_player */
1643 std::vector<MovingObject*>
1644 Sector::get_nearby_objects (const Vector& center, float max_distance)
1646 std::vector<MovingObject*> ret;
1647 std::vector<Player*> players = Sector::current()->get_players();
1649 for (size_t i = 0; i < players.size (); i++) {
1650 float distance = players[i]->get_bbox ().distance (center);
1651 if (distance <= max_distance)
1652 ret.push_back (players[i]);
1655 for (size_t i = 0; i < moving_objects.size (); i++) {
1656 float distance = moving_objects[i]->get_bbox ().distance (center);
1657 if (distance <= max_distance)
1658 ret.push_back (moving_objects[i]);
1664 /* vim: set sw=2 sts=2 et : */