3 // SuperTux - A Jump'n Run
4 // Copyright (C) 2006 Matthias Braun <matze@braunis.de>
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.
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.
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.
34 #include "object/player.hpp"
35 #include "object/gameobjs.hpp"
36 #include "object/camera.hpp"
37 #include "object/background.hpp"
38 #include "object/gradient.hpp"
39 #include "object/particlesystem.hpp"
40 #include "object/particlesystem_interactive.hpp"
41 #include "object/tilemap.hpp"
42 #include "lisp/parser.hpp"
43 #include "lisp/lisp.hpp"
44 #include "lisp/writer.hpp"
45 #include "lisp/list_iterator.hpp"
47 #include "audio/sound_manager.hpp"
48 #include "game_session.hpp"
49 #include "resources.hpp"
50 #include "statistics.hpp"
51 #include "object_factory.hpp"
52 #include "collision.hpp"
53 #include "spawn_point.hpp"
54 #include "math/rect.hpp"
55 #include "math/aatriangle.hpp"
56 #include "object/coin.hpp"
57 #include "object/block.hpp"
58 #include "object/invisible_block.hpp"
59 #include "object/light.hpp"
60 #include "object/pulsing_light.hpp"
61 #include "object/bullet.hpp"
62 #include "object/text_object.hpp"
63 #include "object/portable.hpp"
64 #include "badguy/jumpy.hpp"
65 #include "trigger/sequence_trigger.hpp"
66 #include "player_status.hpp"
67 #include "scripting/squirrel_util.hpp"
68 #include "script_interface.hpp"
73 Sector* Sector::_current = 0;
75 bool Sector::show_collrects = false;
76 bool Sector::draw_solids_only = false;
78 Sector::Sector(Level* parent)
79 : level(parent), currentmusic(LEVEL_MUSIC),
80 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10.0), player(0), camera(0)
82 add_object(new Player(player_status, "Tux"));
83 add_object(new DisplayEffect("Effect"));
84 add_object(new TextObject("Text"));
86 sound_manager->preload("sounds/shoot.wav");
88 // create a new squirrel table for the sector
89 using namespace Scripting;
91 sq_collectgarbage(global_vm);
93 sq_newtable(global_vm);
94 sq_pushroottable(global_vm);
95 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
96 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
98 sq_resetobject(§or_table);
99 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
100 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
101 sq_addref(global_vm, §or_table);
102 sq_pop(global_vm, 1);
107 using namespace Scripting;
111 for(ScriptList::iterator i = scripts.begin();
112 i != scripts.end(); ++i) {
113 HSQOBJECT& object = *i;
114 sq_release(global_vm, &object);
116 sq_release(global_vm, §or_table);
117 sq_collectgarbage(global_vm);
119 update_game_objects();
120 assert(gameobjects_new.size() == 0);
122 for(GameObjects::iterator i = gameobjects.begin();
123 i != gameobjects.end(); ++i) {
124 GameObject* object = *i;
125 before_object_remove(object);
129 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
141 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
143 if(name == "camera") {
144 Camera* camera = new Camera(this, "Camera");
145 camera->parse(reader);
147 } else if(name == "particles-snow") {
148 SnowParticleSystem* partsys = new SnowParticleSystem();
149 partsys->parse(reader);
151 } else if(name == "particles-rain") {
152 RainParticleSystem* partsys = new RainParticleSystem();
153 partsys->parse(reader);
155 } else if(name == "particles-comets") {
156 CometParticleSystem* partsys = new CometParticleSystem();
157 partsys->parse(reader);
159 } else if(name == "particles-ghosts") {
160 GhostParticleSystem* partsys = new GhostParticleSystem();
161 partsys->parse(reader);
163 } else if(name == "particles-clouds") {
164 CloudParticleSystem* partsys = new CloudParticleSystem();
165 partsys->parse(reader);
167 } else if(name == "money") { // for compatibility with old maps
168 return new Jumpy(reader);
172 return create_object(name, reader);
173 } catch(std::exception& e) {
174 log_warning << e.what() << "" << std::endl;
181 Sector::parse(const lisp::Lisp& sector)
183 bool has_background = false;
184 lisp::ListIterator iter(§or);
186 const std::string& token = iter.item();
187 if(token == "name") {
188 iter.value()->get(name);
189 } else if(token == "gravity") {
190 iter.value()->get(gravity);
191 } else if(token == "music") {
192 iter.value()->get(music);
193 } else if(token == "spawnpoint") {
194 SpawnPoint* sp = new SpawnPoint(iter.lisp());
195 spawnpoints.push_back(sp);
196 } else if(token == "init-script") {
197 iter.value()->get(init_script);
198 } else if(token == "ambient-light") {
199 std::vector<float> vColor;
200 sector.get_vector( "ambient-light", vColor );
201 if(vColor.size() < 3) {
202 log_warning << "(ambient-light) requires a color as argument" << std::endl;
204 ambient_light = Color( vColor );
207 GameObject* object = parse_object(token, *(iter.lisp()));
209 if(dynamic_cast<Background *>(object)) {
210 has_background = true;
211 } else if(dynamic_cast<Gradient *>(object)) {
212 has_background = true;
219 if(!has_background) {
220 Gradient* gradient = new Gradient();
221 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
222 add_object(gradient);
225 update_game_objects();
227 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
231 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
232 update_game_objects();
233 add_object(new Camera(this, "Camera"));
236 update_game_objects();
240 Sector::parse_old_format(const lisp::Lisp& reader)
243 reader.get("gravity", gravity);
245 std::string backgroundimage;
246 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
247 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
248 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
249 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
250 backgroundimage = "images/background/" + backgroundimage;
251 if (!PHYSFS_exists(backgroundimage.c_str())) {
252 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
253 backgroundimage = "";
258 reader.get("bkgd_speed", bgspeed);
261 Color bkgd_top, bkgd_bottom;
262 int r = 0, g = 0, b = 128;
263 reader.get("bkgd_red_top", r);
264 reader.get("bkgd_green_top", g);
265 reader.get("bkgd_blue_top", b);
266 bkgd_top.red = static_cast<float> (r) / 255.0f;
267 bkgd_top.green = static_cast<float> (g) / 255.0f;
268 bkgd_top.blue = static_cast<float> (b) / 255.0f;
270 reader.get("bkgd_red_bottom", r);
271 reader.get("bkgd_green_bottom", g);
272 reader.get("bkgd_blue_bottom", b);
273 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
274 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
275 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
277 if(backgroundimage != "") {
278 Background* background = new Background();
279 background->set_image(backgroundimage, bgspeed);
280 add_object(background);
282 Gradient* gradient = new Gradient();
283 gradient->set_gradient(bkgd_top, bkgd_bottom);
284 add_object(gradient);
287 std::string particlesystem;
288 reader.get("particle_system", particlesystem);
289 if(particlesystem == "clouds")
290 add_object(new CloudParticleSystem());
291 else if(particlesystem == "snow")
292 add_object(new SnowParticleSystem());
293 else if(particlesystem == "rain")
294 add_object(new RainParticleSystem());
296 Vector startpos(100, 170);
297 reader.get("start_pos_x", startpos.x);
298 reader.get("start_pos_y", startpos.y);
300 SpawnPoint* spawn = new SpawnPoint;
301 spawn->pos = startpos;
302 spawn->name = "main";
303 spawnpoints.push_back(spawn);
305 music = "chipdisko.ogg";
306 // skip reading music filename. It's all .ogg now, anyway
308 reader.get("music", music);
310 music = "music/" + music;
312 int width = 30, height = 15;
313 reader.get("width", width);
314 reader.get("height", height);
316 std::vector<unsigned int> tiles;
317 if(reader.get_vector("interactive-tm", tiles)
318 || reader.get_vector("tilemap", tiles)) {
319 TileMap* tilemap = new TileMap(level->get_tileset());
320 tilemap->set(width, height, tiles, LAYER_TILES, true);
322 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
323 for(size_t x=0; x < tilemap->get_width(); ++x) {
324 for(size_t y=0; y < tilemap->get_height(); ++y) {
325 uint32_t id = tilemap->get_tile_id(x, y);
327 tilemap->change(x, y, 1311);
331 if (height < 19) tilemap->resize(width, 19);
335 if(reader.get_vector("background-tm", tiles)) {
336 TileMap* tilemap = new TileMap(level->get_tileset());
337 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
338 if (height < 19) tilemap->resize(width, 19);
342 if(reader.get_vector("foreground-tm", tiles)) {
343 TileMap* tilemap = new TileMap(level->get_tileset());
344 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
346 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
347 if (height < 19) tilemap->resize(width, 19, 2035);
352 // read reset-points (now spawn-points)
353 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
355 lisp::ListIterator iter(resetpoints);
357 if(iter.item() == "point") {
359 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
361 SpawnPoint* sp = new SpawnPoint;
364 spawnpoints.push_back(sp);
367 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
373 const lisp::Lisp* objects = reader.get_lisp("objects");
375 lisp::ListIterator iter(objects);
377 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
381 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
387 Camera* camera = new Camera(this, "Camera");
390 update_game_objects();
392 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
395 update_game_objects();
399 Sector::fix_old_tiles()
401 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
402 TileMap* solids = *i;
403 for(size_t x=0; x < solids->get_width(); ++x) {
404 for(size_t y=0; y < solids->get_height(); ++y) {
405 uint32_t id = solids->get_tile_id(x, y);
406 const Tile *tile = solids->get_tile(x, y);
407 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
410 add_object(new InvisibleBlock(pos));
411 solids->change(x, y, 0);
412 } else if(tile->getAttributes() & Tile::COIN) {
413 add_object(new Coin(pos));
414 solids->change(x, y, 0);
415 } else if(tile->getAttributes() & Tile::FULLBOX) {
416 add_object(new BonusBlock(pos, tile->getData()));
417 solids->change(x, y, 0);
418 } else if(tile->getAttributes() & Tile::BRICK) {
419 add_object(new Brick(pos, tile->getData()));
420 solids->change(x, y, 0);
421 } else if(tile->getAttributes() & Tile::GOAL) {
422 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
423 add_object(new SequenceTrigger(pos, sequence));
424 solids->change(x, y, 0);
430 // add lights for special tiles
431 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
432 TileMap* tm = dynamic_cast<TileMap*>(*i);
434 for(size_t x=0; x < tm->get_width(); ++x) {
435 for(size_t y=0; y < tm->get_height(); ++y) {
436 uint32_t id = tm->get_tile_id(x, y);
437 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
438 Vector center(pos.x + 16, pos.y + 16);
442 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
443 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
446 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
447 // space lights a bit
448 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
449 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
450 || ((x % 3 == 0) && (y % 3 == 0))) {
451 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
452 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
464 Sector::write(lisp::Writer& writer)
466 writer.write_string("name", name);
467 writer.write_float("gravity", gravity);
468 writer.write_string("music", music);
471 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
473 SpawnPoint* spawn = *i;
474 writer.start_list("spawn-points");
475 writer.write_string("name", spawn->name);
476 writer.write_float("x", spawn->pos.x);
477 writer.write_float("y", spawn->pos.y);
478 writer.end_list("spawn-points");
482 for(GameObjects::iterator i = gameobjects.begin();
483 i != gameobjects.end(); ++i) {
484 Serializable* serializable = dynamic_cast<Serializable*> (*i);
486 serializable->write(writer);
491 Sector::run_script(std::istream& in, const std::string& sourcename)
493 using namespace Scripting;
495 // garbage collect thread list
496 for(ScriptList::iterator i = scripts.begin();
497 i != scripts.end(); ) {
498 HSQOBJECT& object = *i;
499 HSQUIRRELVM vm = object_to_vm(object);
501 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
502 sq_release(global_vm, &object);
503 i = scripts.erase(i);
510 HSQOBJECT object = create_thread(global_vm);
511 scripts.push_back(object);
513 HSQUIRRELVM vm = object_to_vm(object);
515 // set sector_table as roottable for the thread
516 sq_pushobject(vm, sector_table);
519 compile_and_run(vm, in, sourcename);
525 Sector::add_object(GameObject* object)
527 // make sure the object isn't already in the list
529 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
532 assert("object already added to sector" == 0);
535 for(GameObjects::iterator i = gameobjects_new.begin();
536 i != gameobjects_new.end(); ++i) {
538 assert("object already added to sector" == 0);
544 gameobjects_new.push_back(object);
548 Sector::activate(const std::string& spawnpoint)
551 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
553 if((*i)->name == spawnpoint) {
559 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
560 if(spawnpoint != "main") {
563 activate(Vector(0, 0));
571 Sector::activate(const Vector& player_pos)
573 if(_current != this) {
575 _current->deactivate();
578 // register sectortable as sector in scripting
579 HSQUIRRELVM vm = Scripting::global_vm;
580 sq_pushroottable(vm);
581 sq_pushstring(vm, "sector", -1);
582 sq_pushobject(vm, sector_table);
583 if(SQ_FAILED(sq_createslot(vm, -3)))
584 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
587 for(GameObjects::iterator i = gameobjects.begin();
588 i != gameobjects.end(); ++i) {
589 GameObject* object = *i;
596 // spawn smalltux below spawnpoint
597 if (!player->is_big()) {
598 player->move(player_pos + Vector(0,32));
600 player->move(player_pos);
603 // spawning tux in the ground would kill him
604 if(!is_free_of_tiles(player->get_bbox())) {
605 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
606 Vector npos = player->get_bbox().p1;
611 camera->reset(player->get_pos());
612 update_game_objects();
615 if(init_script != "") {
616 std::istringstream in(init_script);
617 run_script(in, std::string("Sector(") + name + ") - init");
627 // remove sector entry from global vm
628 HSQUIRRELVM vm = Scripting::global_vm;
629 sq_pushroottable(vm);
630 sq_pushstring(vm, "sector", -1);
631 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
632 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
635 for(GameObjects::iterator i = gameobjects.begin();
636 i != gameobjects.end(); ++i) {
637 GameObject* object = *i;
639 try_unexpose(object);
647 Sector::get_active_region()
650 camera->get_translation() - Vector(1600, 1200),
651 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
655 Sector::update(float elapsed_time)
657 player->check_bounds(camera);
660 for(GameObjects::iterator i = gameobjects.begin();
661 i != gameobjects.end(); ++i) {
662 GameObject* object = *i;
663 if(!object->is_valid())
666 object->update(elapsed_time);
669 /* Handle all possible collisions. */
671 update_game_objects();
675 Sector::update_game_objects()
677 /** cleanup marked objects */
678 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
679 i != gameobjects.end(); /* nothing */) {
680 GameObject* object = *i;
682 if(object->is_valid()) {
687 before_object_remove(object);
690 i = gameobjects.erase(i);
693 /* add newly created objects */
694 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
695 i != gameobjects_new.end(); ++i)
697 GameObject* object = *i;
699 before_object_add(object);
701 gameobjects.push_back(object);
703 gameobjects_new.clear();
705 /* update solid_tilemaps list */
706 //FIXME: this could be more efficient
707 solid_tilemaps.clear();
708 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
709 i != gameobjects.end(); ++i)
711 TileMap* tm = dynamic_cast<TileMap*>(*i);
713 if (tm->is_solid()) solid_tilemaps.push_back(tm);
719 Sector::before_object_add(GameObject* object)
721 Bullet* bullet = dynamic_cast<Bullet*> (object);
723 bullets.push_back(bullet);
726 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
727 if(movingobject != NULL) {
728 moving_objects.push_back(movingobject);
731 Portable* portable = dynamic_cast<Portable*> (object);
732 if(portable != NULL) {
733 portables.push_back(portable);
736 TileMap* tilemap = dynamic_cast<TileMap*> (object);
737 if(tilemap != NULL && tilemap->is_solid()) {
738 solid_tilemaps.push_back(tilemap);
741 Camera* camera = dynamic_cast<Camera*> (object);
743 if(this->camera != 0) {
744 log_warning << "Multiple cameras added. Ignoring" << std::endl;
747 this->camera = camera;
750 Player* player = dynamic_cast<Player*> (object);
752 if(this->player != 0) {
753 log_warning << "Multiple players added. Ignoring" << std::endl;
756 this->player = player;
759 UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
762 physic_object->physic.set_gravity(gravity);
766 if(_current == this) {
774 Sector::try_expose(GameObject* object)
776 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
777 if(interface != NULL) {
778 HSQUIRRELVM vm = Scripting::global_vm;
779 sq_pushobject(vm, sector_table);
780 interface->expose(vm, -1);
786 Sector::try_expose_me()
788 HSQUIRRELVM vm = Scripting::global_vm;
789 sq_pushobject(vm, sector_table);
790 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
791 expose_object(vm, -1, interface, "settings", false);
796 Sector::before_object_remove(GameObject* object)
798 Portable* portable = dynamic_cast<Portable*> (object);
799 if(portable != NULL) {
800 portables.erase(std::find(portables.begin(), portables.end(), portable));
802 Bullet* bullet = dynamic_cast<Bullet*> (object);
804 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
806 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
807 if(moving_object != NULL) {
808 moving_objects.erase(
809 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
813 try_unexpose(object);
817 Sector::try_unexpose(GameObject* object)
819 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
820 if(interface != NULL) {
821 HSQUIRRELVM vm = Scripting::global_vm;
822 SQInteger oldtop = sq_gettop(vm);
823 sq_pushobject(vm, sector_table);
825 interface->unexpose(vm, -1);
826 } catch(std::exception& e) {
827 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
829 sq_settop(vm, oldtop);
834 Sector::try_unexpose_me()
836 HSQUIRRELVM vm = Scripting::global_vm;
837 SQInteger oldtop = sq_gettop(vm);
838 sq_pushobject(vm, sector_table);
840 Scripting::unexpose_object(vm, -1, "settings");
841 } catch(std::exception& e) {
842 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
844 sq_settop(vm, oldtop);
847 Sector::draw(DrawingContext& context)
849 context.set_ambient_color( ambient_light );
850 context.push_transform();
851 context.set_translation(camera->get_translation());
853 for(GameObjects::iterator i = gameobjects.begin();
854 i != gameobjects.end(); ++i) {
855 GameObject* object = *i;
856 if(!object->is_valid())
859 if (draw_solids_only)
861 TileMap* tm = dynamic_cast<TileMap*>(object);
862 if (tm && !tm->is_solid())
866 object->draw(context);
870 Color col(0.2f, 0.2f, 0.2f, 0.7f);
871 for(MovingObjects::iterator i = moving_objects.begin();
872 i != moving_objects.end(); ++i) {
873 MovingObject* object = *i;
874 const Rect& rect = object->get_bbox();
876 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
880 context.pop_transform();
883 /*-------------------------------------------------------------------------
884 * Collision Detection
885 *-------------------------------------------------------------------------*/
887 static const float SHIFT_DELTA = 7.0f;
889 /** r1 is supposed to be moving, r2 a solid object */
890 void check_collisions(collision::Constraints* constraints,
891 const Vector& movement, const Rect& r1, const Rect& r2,
892 GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
894 if(!collision::intersects(r1, r2))
897 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
899 if(other != NULL && !other->collides(*object, dummy))
901 if(moving_object != NULL && !moving_object->collides(*other, dummy))
904 // calculate intersection
905 float itop = r1.get_bottom() - r2.get_top();
906 float ibottom = r2.get_bottom() - r1.get_top();
907 float ileft = r1.get_right() - r2.get_left();
908 float iright = r2.get_right() - r1.get_left();
910 if(fabsf(movement.y) > fabsf(movement.x)) {
911 if(ileft < SHIFT_DELTA) {
912 constraints->right = std::min(constraints->right, r2.get_left());
914 } else if(iright < SHIFT_DELTA) {
915 constraints->left = std::max(constraints->left, r2.get_right());
919 // shiftout bottom/top
920 if(itop < SHIFT_DELTA) {
921 constraints->bottom = std::min(constraints->bottom, r2.get_top());
923 } else if(ibottom < SHIFT_DELTA) {
924 constraints->top = std::max(constraints->top, r2.get_bottom());
929 constraints->ground_movement += addl_ground_movement;
931 HitResponse response = other->collision(*object, dummy);
932 if(response == PASSTHROUGH)
935 if(other->get_movement() != Vector(0, 0)) {
936 // TODO what todo when we collide with 2 moving objects?!?
937 constraints->ground_movement += other->get_movement();
941 float vert_penetration = std::min(itop, ibottom);
942 float horiz_penetration = std::min(ileft, iright);
943 if(vert_penetration < horiz_penetration) {
945 constraints->bottom = std::min(constraints->bottom, r2.get_top());
946 constraints->hit.bottom = true;
948 constraints->top = std::max(constraints->top, r2.get_bottom());
949 constraints->hit.top = true;
953 constraints->right = std::min(constraints->right, r2.get_left());
954 constraints->hit.right = true;
956 constraints->left = std::max(constraints->left, r2.get_right());
957 constraints->hit.left = true;
962 static const float DELTA = .001f;
965 Sector::collision_tilemap(collision::Constraints* constraints,
966 const Vector& movement, const Rect& dest) const
968 // calculate rectangle where the object will move
969 float x1 = dest.get_left();
970 float x2 = dest.get_right();
971 float y1 = dest.get_top();
972 float y2 = dest.get_bottom();
974 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
975 TileMap* solids = *i;
977 // test with all tiles in this rectangle
978 int starttilex = int(x1 - solids->get_x_offset()) / 32;
979 int starttiley = int(y1 - solids->get_y_offset()) / 32;
980 int max_x = int(x2 - solids->get_x_offset());
981 int max_y = int(y2+1 - solids->get_y_offset());
983 for(int x = starttilex; x*32 < max_x; ++x) {
984 for(int y = starttiley; y*32 < max_y; ++y) {
985 const Tile* tile = solids->get_tile(x, y);
988 // skip non-solid tiles
989 if((tile->getAttributes() & Tile::SOLID) == 0)
991 // only handle unisolid when the player is falling down and when he was
992 // above the tile before
993 if(tile->getAttributes() & Tile::UNISOLID) {
994 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
998 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
1000 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1001 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1002 triangle = AATriangle(p1, p2, tile->getData());
1004 collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
1005 } else { // normal rectangular tile
1006 Rect rect(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset(), (x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1007 check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
1015 Sector::collision_tile_attributes(const Rect& dest) const
1017 float x1 = dest.p1.x;
1018 float y1 = dest.p1.y;
1019 float x2 = dest.p2.x;
1020 float y2 = dest.p2.y;
1022 uint32_t result = 0;
1023 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1024 TileMap* solids = *i;
1026 // test with all tiles in this rectangle
1027 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1028 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1029 int max_x = int(x2 - solids->get_x_offset());
1030 int max_y = int(y2+1 - solids->get_y_offset());
1032 for(int x = starttilex; x*32 < max_x; ++x) {
1033 for(int y = starttiley; y*32 < max_y; ++y) {
1034 const Tile* tile = solids->get_tile(x, y);
1037 result |= tile->getAttributes();
1045 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1046 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1049 float itop = r1.get_bottom() - r2.get_top();
1050 float ibottom = r2.get_bottom() - r1.get_top();
1051 float ileft = r1.get_right() - r2.get_left();
1052 float iright = r2.get_right() - r1.get_left();
1054 float vert_penetration = std::min(itop, ibottom);
1055 float horiz_penetration = std::min(ileft, iright);
1056 if(vert_penetration < horiz_penetration) {
1057 if(itop < ibottom) {
1059 normal.y = vert_penetration;
1062 normal.y = -vert_penetration;
1065 if(ileft < iright) {
1067 normal.x = horiz_penetration;
1070 normal.x = -horiz_penetration;
1076 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1078 using namespace collision;
1080 const Rect& r1 = object1->dest;
1081 const Rect& r2 = object2->dest;
1084 if(intersects(object1->dest, object2->dest)) {
1086 get_hit_normal(r1, r2, hit, normal);
1088 if(!object1->collides(*object2, hit))
1090 std::swap(hit.left, hit.right);
1091 std::swap(hit.top, hit.bottom);
1092 if(!object2->collides(*object1, hit))
1094 std::swap(hit.left, hit.right);
1095 std::swap(hit.top, hit.bottom);
1097 HitResponse response1 = object1->collision(*object2, hit);
1098 std::swap(hit.left, hit.right);
1099 std::swap(hit.top, hit.bottom);
1100 HitResponse response2 = object2->collision(*object1, hit);
1101 if(response1 == CONTINUE && response2 == CONTINUE) {
1102 normal *= (0.5 + DELTA);
1103 object1->dest.move(-normal);
1104 object2->dest.move(normal);
1105 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1106 normal *= (1 + DELTA);
1107 object1->dest.move(-normal);
1108 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1109 normal *= (1 + DELTA);
1110 object2->dest.move(normal);
1116 Sector::collision_static(collision::Constraints* constraints,
1117 const Vector& movement, const Rect& dest,
1120 collision_tilemap(constraints, movement, dest);
1122 // collision with other (static) objects
1123 for(MovingObjects::iterator i = moving_objects.begin();
1124 i != moving_objects.end(); ++i) {
1125 MovingObject* moving_object = *i;
1126 if(moving_object->get_group() != COLGROUP_STATIC
1127 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1129 if(!moving_object->is_valid())
1132 if(moving_object != &object)
1133 check_collisions(constraints, movement, dest, moving_object->bbox,
1134 &object, moving_object);
1139 Sector::collision_static_constrains(MovingObject& object)
1141 using namespace collision;
1142 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1144 Constraints constraints;
1145 Vector movement = object.get_movement();
1146 Rect& dest = object.dest;
1147 float owidth = object.get_bbox().get_width();
1148 float oheight = object.get_bbox().get_height();
1150 for(int i = 0; i < 2; ++i) {
1151 collision_static(&constraints, Vector(0, movement.y), dest, object);
1152 if(!constraints.has_constraints())
1155 // apply calculated horizontal constraints
1156 if(constraints.bottom < infinity) {
1157 float height = constraints.bottom - constraints.top;
1158 if(height < oheight) {
1159 // we're crushed, but ignore this for now, we'll get this again
1160 // later if we're really crushed or things will solve itself when
1161 // looking at the vertical constraints
1163 dest.p2.y = constraints.bottom - DELTA;
1164 dest.p1.y = dest.p2.y - oheight;
1165 } else if(constraints.top > -infinity) {
1166 dest.p1.y = constraints.top + DELTA;
1167 dest.p2.y = dest.p1.y + oheight;
1170 if(constraints.has_constraints()) {
1171 if(constraints.hit.bottom) {
1172 dest.move(constraints.ground_movement);
1174 if(constraints.hit.top || constraints.hit.bottom) {
1175 constraints.hit.left = false;
1176 constraints.hit.right = false;
1177 object.collision_solid(constraints.hit);
1181 constraints = Constraints();
1182 for(int i = 0; i < 2; ++i) {
1183 collision_static(&constraints, movement, dest, object);
1184 if(!constraints.has_constraints())
1187 // apply calculated vertical constraints
1188 if(constraints.right < infinity) {
1189 float width = constraints.right - constraints.left;
1190 if(width + SHIFT_DELTA < owidth) {
1192 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1193 constraints.left, constraints.right);
1199 object.collision_solid(h);
1201 dest.p2.x = constraints.right - DELTA;
1202 dest.p1.x = dest.p2.x - owidth;
1204 } else if(constraints.left > -infinity) {
1205 dest.p1.x = constraints.left + DELTA;
1206 dest.p2.x = dest.p1.x + owidth;
1210 if(constraints.has_constraints()) {
1211 if( constraints.hit.left || constraints.hit.right
1212 || constraints.hit.top || constraints.hit.bottom
1213 || constraints.hit.crush )
1214 object.collision_solid(constraints.hit);
1217 // an extra pass to make sure we're not crushed horizontally
1218 constraints = Constraints();
1219 collision_static(&constraints, movement, dest, object);
1220 if(constraints.bottom < infinity) {
1221 float height = constraints.bottom - constraints.top;
1222 if(height + SHIFT_DELTA < oheight) {
1224 printf("Object %p crushed vertically...\n", &object);
1230 object.collision_solid(h);
1236 const float MAX_SPEED = 16.0f;
1240 Sector::handle_collisions()
1242 using namespace collision;
1244 // calculate destination positions of the objects
1245 for(MovingObjects::iterator i = moving_objects.begin();
1246 i != moving_objects.end(); ++i) {
1247 MovingObject* moving_object = *i;
1248 Vector mov = moving_object->get_movement();
1250 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1251 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1252 moving_object->movement = mov.unit() * MAX_SPEED;
1253 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1256 moving_object->dest = moving_object->get_bbox();
1257 moving_object->dest.move(moving_object->get_movement());
1260 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1261 for(MovingObjects::iterator i = moving_objects.begin();
1262 i != moving_objects.end(); ++i) {
1263 MovingObject* moving_object = *i;
1264 if((moving_object->get_group() != COLGROUP_MOVING
1265 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1266 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1267 || !moving_object->is_valid())
1270 collision_static_constrains(*moving_object);
1274 // part2: COLGROUP_MOVING vs tile attributes
1275 for(MovingObjects::iterator i = moving_objects.begin();
1276 i != moving_objects.end(); ++i) {
1277 MovingObject* moving_object = *i;
1278 if((moving_object->get_group() != COLGROUP_MOVING
1279 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1280 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1281 || !moving_object->is_valid())
1284 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1285 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1286 moving_object->collision_tile(tile_attributes);
1290 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1291 for(MovingObjects::iterator i = moving_objects.begin();
1292 i != moving_objects.end(); ++i) {
1293 MovingObject* moving_object = *i;
1294 if((moving_object->get_group() != COLGROUP_MOVING
1295 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1296 || !moving_object->is_valid())
1299 for(MovingObjects::iterator i2 = moving_objects.begin();
1300 i2 != moving_objects.end(); ++i2) {
1301 MovingObject* moving_object_2 = *i2;
1302 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1303 || !moving_object_2->is_valid())
1306 if(intersects(moving_object->dest, moving_object_2->dest)) {
1309 get_hit_normal(moving_object->dest, moving_object_2->dest,
1311 if(!moving_object->collides(*moving_object_2, hit))
1313 if(!moving_object_2->collides(*moving_object, hit))
1316 moving_object->collision(*moving_object_2, hit);
1317 moving_object_2->collision(*moving_object, hit);
1322 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1323 for(MovingObjects::iterator i = moving_objects.begin();
1324 i != moving_objects.end(); ++i) {
1325 MovingObject* moving_object = *i;
1327 if((moving_object->get_group() != COLGROUP_MOVING
1328 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1329 || !moving_object->is_valid())
1332 for(MovingObjects::iterator i2 = i+1;
1333 i2 != moving_objects.end(); ++i2) {
1334 MovingObject* moving_object_2 = *i2;
1335 if((moving_object_2->get_group() != COLGROUP_MOVING
1336 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1337 || !moving_object_2->is_valid())
1340 collision_object(moving_object, moving_object_2);
1344 // apply object movement
1345 for(MovingObjects::iterator i = moving_objects.begin();
1346 i != moving_objects.end(); ++i) {
1347 MovingObject* moving_object = *i;
1349 moving_object->bbox = moving_object->dest;
1350 moving_object->movement = Vector(0, 0);
1355 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1357 using namespace collision;
1359 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1360 TileMap* solids = *i;
1362 // test with all tiles in this rectangle
1363 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1364 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1365 int max_x = int(rect.p2.x - solids->get_x_offset());
1366 int max_y = int(rect.p2.y - solids->get_y_offset());
1368 for(int x = starttilex; x*32 <= max_x; ++x) {
1369 for(int y = starttiley; y*32 <= max_y; ++y) {
1370 const Tile* tile = solids->get_tile(x, y);
1372 if(tile->getAttributes() & Tile::SLOPE) {
1373 AATriangle triangle;
1374 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1375 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1376 triangle = AATriangle(p1, p2, tile->getData());
1377 Constraints constraints;
1378 return collision::rectangle_aatriangle(&constraints, rect, triangle);
1380 if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1381 if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1390 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1392 using namespace collision;
1394 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1396 for(MovingObjects::const_iterator i = moving_objects.begin();
1397 i != moving_objects.end(); ++i) {
1398 const MovingObject* moving_object = *i;
1399 if (moving_object == ignore_object) continue;
1400 if (!moving_object->is_valid()) continue;
1401 if (moving_object->get_group() == COLGROUP_STATIC) {
1402 if(intersects(rect, moving_object->get_bbox())) return false;
1410 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1412 using namespace collision;
1414 if (!is_free_of_tiles(rect)) return false;
1416 for(MovingObjects::const_iterator i = moving_objects.begin();
1417 i != moving_objects.end(); ++i) {
1418 const MovingObject* moving_object = *i;
1419 if (moving_object == ignore_object) continue;
1420 if (!moving_object->is_valid()) continue;
1421 if ((moving_object->get_group() == COLGROUP_MOVING)
1422 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1423 || (moving_object->get_group() == COLGROUP_STATIC)) {
1424 if(intersects(rect, moving_object->get_bbox())) return false;
1432 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1434 // TODO remove this function and move these checks elsewhere...
1436 Bullet* new_bullet = 0;
1437 if((player_status->bonus == FIRE_BONUS &&
1438 (int)bullets.size() >= player_status->max_fire_bullets) ||
1439 (player_status->bonus == ICE_BONUS &&
1440 (int)bullets.size() >= player_status->max_ice_bullets))
1442 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1443 add_object(new_bullet);
1445 sound_manager->play("sounds/shoot.wav");
1451 Sector::add_smoke_cloud(const Vector& pos)
1453 add_object(new SmokeCloud(pos));
1458 Sector::play_music(MusicType type)
1460 currentmusic = type;
1461 switch(currentmusic) {
1463 sound_manager->play_music(music);
1466 sound_manager->play_music("music/invincible.ogg");
1468 case HERRING_WARNING_MUSIC:
1469 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1472 sound_manager->play_music("");
1478 Sector::get_music_type()
1480 return currentmusic;
1484 Sector::get_total_badguys()
1486 int total_badguys = 0;
1487 for(GameObjects::iterator i = gameobjects.begin();
1488 i != gameobjects.end(); ++i) {
1489 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1490 if (badguy && badguy->countMe)
1494 return total_badguys;
1498 Sector::inside(const Rect& rect) const
1500 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1501 TileMap* solids = *i;
1502 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1503 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1505 if (horizontally && vertically)
1512 Sector::get_width() const
1515 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1516 i != solid_tilemaps.end(); i++) {
1517 TileMap* solids = *i;
1518 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1519 width = solids->get_width() * 32 + solids->get_x_offset();
1527 Sector::get_height() const
1530 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1531 i != solid_tilemaps.end(); i++) {
1532 TileMap* solids = *i;
1533 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1534 height = solids->get_height() * 32 + solids->get_y_offset();
1542 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1544 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1545 TileMap* solids = *i;
1546 solids->change_all(old_tile_id, new_tile_id);
1552 Sector::set_ambient_light(float red, float green, float blue)
1554 ambient_light.red = red;
1555 ambient_light.green = green;
1556 ambient_light.blue = blue;
1560 Sector::get_ambient_red()
1562 return ambient_light.red;
1566 Sector::get_ambient_green()
1568 return ambient_light.green;
1572 Sector::get_ambient_blue()
1574 return ambient_light.blue;
1578 Sector::set_gravity(float gravity)
1580 log_warning << "Changing a Sector's gravitational constant might have unforseen side-effects" << std::endl;
1582 this->gravity = gravity;
1584 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); ++i) {
1585 GameObject* game_object = *i;
1586 if(!game_object) continue;
1587 if(!game_object->is_valid()) continue;
1588 UsesPhysic *physics_object = dynamic_cast<UsesPhysic*>(game_object);
1589 if (!physics_object) continue;
1591 physics_object->physic.set_gravity(gravity);