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 // create a new squirrel table for the sector
87 using namespace Scripting;
89 sq_collectgarbage(global_vm);
91 sq_newtable(global_vm);
92 sq_pushroottable(global_vm);
93 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
94 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
96 sq_resetobject(§or_table);
97 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
98 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
99 sq_addref(global_vm, §or_table);
100 sq_pop(global_vm, 1);
105 using namespace Scripting;
109 for(ScriptList::iterator i = scripts.begin();
110 i != scripts.end(); ++i) {
111 HSQOBJECT& object = *i;
112 sq_release(global_vm, &object);
114 sq_release(global_vm, §or_table);
115 sq_collectgarbage(global_vm);
117 update_game_objects();
118 assert(gameobjects_new.size() == 0);
120 for(GameObjects::iterator i = gameobjects.begin();
121 i != gameobjects.end(); ++i) {
122 GameObject* object = *i;
123 before_object_remove(object);
127 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
139 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
141 if(name == "camera") {
142 Camera* camera = new Camera(this, "Camera");
143 camera->parse(reader);
145 } else if(name == "particles-snow") {
146 SnowParticleSystem* partsys = new SnowParticleSystem();
147 partsys->parse(reader);
149 } else if(name == "particles-rain") {
150 RainParticleSystem* partsys = new RainParticleSystem();
151 partsys->parse(reader);
153 } else if(name == "particles-comets") {
154 CometParticleSystem* partsys = new CometParticleSystem();
155 partsys->parse(reader);
157 } else if(name == "particles-ghosts") {
158 GhostParticleSystem* partsys = new GhostParticleSystem();
159 partsys->parse(reader);
161 } else if(name == "particles-clouds") {
162 CloudParticleSystem* partsys = new CloudParticleSystem();
163 partsys->parse(reader);
165 } else if(name == "money") { // for compatibility with old maps
166 return new Jumpy(reader);
170 return create_object(name, reader);
171 } catch(std::exception& e) {
172 log_warning << e.what() << "" << std::endl;
179 Sector::parse(const lisp::Lisp& sector)
181 bool has_background = false;
182 lisp::ListIterator iter(§or);
184 const std::string& token = iter.item();
185 if(token == "name") {
186 iter.value()->get(name);
187 } else if(token == "gravity") {
188 iter.value()->get(gravity);
189 } else if(token == "music") {
190 iter.value()->get(music);
191 } else if(token == "spawnpoint") {
192 SpawnPoint* sp = new SpawnPoint(iter.lisp());
193 spawnpoints.push_back(sp);
194 } else if(token == "init-script") {
195 iter.value()->get(init_script);
196 } else if(token == "ambient-light") {
197 std::vector<float> vColor;
198 sector.get_vector( "ambient-light", vColor );
199 if(vColor.size() < 3) {
200 log_warning << "(ambient-light) requires a color as argument" << std::endl;
202 ambient_light = Color( vColor );
205 GameObject* object = parse_object(token, *(iter.lisp()));
207 if(dynamic_cast<Background *>(object)) {
208 has_background = true;
209 } else if(dynamic_cast<Gradient *>(object)) {
210 has_background = true;
217 if(!has_background) {
218 Gradient* gradient = new Gradient();
219 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
220 add_object(gradient);
223 update_game_objects();
225 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
229 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
230 update_game_objects();
231 add_object(new Camera(this, "Camera"));
234 update_game_objects();
238 Sector::parse_old_format(const lisp::Lisp& reader)
241 reader.get("gravity", gravity);
243 std::string backgroundimage;
244 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
245 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
246 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
247 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
248 backgroundimage = "images/background/" + backgroundimage;
249 if (!PHYSFS_exists(backgroundimage.c_str())) {
250 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
251 backgroundimage = "";
256 reader.get("bkgd_speed", bgspeed);
259 Color bkgd_top, bkgd_bottom;
260 int r = 0, g = 0, b = 128;
261 reader.get("bkgd_red_top", r);
262 reader.get("bkgd_green_top", g);
263 reader.get("bkgd_blue_top", b);
264 bkgd_top.red = static_cast<float> (r) / 255.0f;
265 bkgd_top.green = static_cast<float> (g) / 255.0f;
266 bkgd_top.blue = static_cast<float> (b) / 255.0f;
268 reader.get("bkgd_red_bottom", r);
269 reader.get("bkgd_green_bottom", g);
270 reader.get("bkgd_blue_bottom", b);
271 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
272 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
273 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
275 if(backgroundimage != "") {
276 Background* background = new Background();
277 background->set_image(backgroundimage, bgspeed);
278 add_object(background);
280 Gradient* gradient = new Gradient();
281 gradient->set_gradient(bkgd_top, bkgd_bottom);
282 add_object(gradient);
285 std::string particlesystem;
286 reader.get("particle_system", particlesystem);
287 if(particlesystem == "clouds")
288 add_object(new CloudParticleSystem());
289 else if(particlesystem == "snow")
290 add_object(new SnowParticleSystem());
291 else if(particlesystem == "rain")
292 add_object(new RainParticleSystem());
294 Vector startpos(100, 170);
295 reader.get("start_pos_x", startpos.x);
296 reader.get("start_pos_y", startpos.y);
298 SpawnPoint* spawn = new SpawnPoint;
299 spawn->pos = startpos;
300 spawn->name = "main";
301 spawnpoints.push_back(spawn);
303 music = "chipdisko.ogg";
304 // skip reading music filename. It's all .ogg now, anyway
306 reader.get("music", music);
308 music = "music/" + music;
310 int width = 30, height = 15;
311 reader.get("width", width);
312 reader.get("height", height);
314 std::vector<unsigned int> tiles;
315 if(reader.get_vector("interactive-tm", tiles)
316 || reader.get_vector("tilemap", tiles)) {
317 TileMap* tilemap = new TileMap(level->get_tileset());
318 tilemap->set(width, height, tiles, LAYER_TILES, true);
320 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
321 for(size_t x=0; x < tilemap->get_width(); ++x) {
322 for(size_t y=0; y < tilemap->get_height(); ++y) {
323 uint32_t id = tilemap->get_tile_id(x, y);
325 tilemap->change(x, y, 1311);
329 if (height < 19) tilemap->resize(width, 19);
333 if(reader.get_vector("background-tm", tiles)) {
334 TileMap* tilemap = new TileMap(level->get_tileset());
335 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
336 if (height < 19) tilemap->resize(width, 19);
340 if(reader.get_vector("foreground-tm", tiles)) {
341 TileMap* tilemap = new TileMap(level->get_tileset());
342 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
344 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
345 if (height < 19) tilemap->resize(width, 19, 2035);
350 // read reset-points (now spawn-points)
351 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
353 lisp::ListIterator iter(resetpoints);
355 if(iter.item() == "point") {
357 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
359 SpawnPoint* sp = new SpawnPoint;
362 spawnpoints.push_back(sp);
365 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
371 const lisp::Lisp* objects = reader.get_lisp("objects");
373 lisp::ListIterator iter(objects);
375 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
379 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
385 Camera* camera = new Camera(this, "Camera");
388 update_game_objects();
390 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
393 update_game_objects();
397 Sector::fix_old_tiles()
399 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
400 TileMap* solids = *i;
401 for(size_t x=0; x < solids->get_width(); ++x) {
402 for(size_t y=0; y < solids->get_height(); ++y) {
403 uint32_t id = solids->get_tile_id(x, y);
404 const Tile *tile = solids->get_tile(x, y);
405 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
408 add_object(new InvisibleBlock(pos));
409 solids->change(x, y, 0);
410 } else if(tile->getAttributes() & Tile::COIN) {
411 add_object(new Coin(pos));
412 solids->change(x, y, 0);
413 } else if(tile->getAttributes() & Tile::FULLBOX) {
414 add_object(new BonusBlock(pos, tile->getData()));
415 solids->change(x, y, 0);
416 } else if(tile->getAttributes() & Tile::BRICK) {
417 add_object(new Brick(pos, tile->getData()));
418 solids->change(x, y, 0);
419 } else if(tile->getAttributes() & Tile::GOAL) {
420 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
421 add_object(new SequenceTrigger(pos, sequence));
422 solids->change(x, y, 0);
428 // add lights for special tiles
429 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
430 TileMap* tm = dynamic_cast<TileMap*>(*i);
432 for(size_t x=0; x < tm->get_width(); ++x) {
433 for(size_t y=0; y < tm->get_height(); ++y) {
434 uint32_t id = tm->get_tile_id(x, y);
435 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
436 Vector center(pos.x + 16, pos.y + 16);
440 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
441 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
444 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
445 // space lights a bit
446 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
447 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
448 || ((x % 3 == 0) && (y % 3 == 0))) {
449 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
450 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
462 Sector::write(lisp::Writer& writer)
464 writer.write_string("name", name);
465 writer.write_float("gravity", gravity);
466 writer.write_string("music", music);
469 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
471 SpawnPoint* spawn = *i;
472 writer.start_list("spawn-points");
473 writer.write_string("name", spawn->name);
474 writer.write_float("x", spawn->pos.x);
475 writer.write_float("y", spawn->pos.y);
476 writer.end_list("spawn-points");
480 for(GameObjects::iterator i = gameobjects.begin();
481 i != gameobjects.end(); ++i) {
482 Serializable* serializable = dynamic_cast<Serializable*> (*i);
484 serializable->write(writer);
489 Sector::run_script(std::istream& in, const std::string& sourcename)
491 using namespace Scripting;
493 // garbage collect thread list
494 for(ScriptList::iterator i = scripts.begin();
495 i != scripts.end(); ) {
496 HSQOBJECT& object = *i;
497 HSQUIRRELVM vm = object_to_vm(object);
499 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
500 sq_release(global_vm, &object);
501 i = scripts.erase(i);
508 HSQOBJECT object = create_thread(global_vm);
509 scripts.push_back(object);
511 HSQUIRRELVM vm = object_to_vm(object);
513 // set sector_table as roottable for the thread
514 sq_pushobject(vm, sector_table);
517 compile_and_run(vm, in, sourcename);
523 Sector::add_object(GameObject* object)
525 // make sure the object isn't already in the list
527 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
530 assert("object already added to sector" == 0);
533 for(GameObjects::iterator i = gameobjects_new.begin();
534 i != gameobjects_new.end(); ++i) {
536 assert("object already added to sector" == 0);
542 gameobjects_new.push_back(object);
546 Sector::activate(const std::string& spawnpoint)
549 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
551 if((*i)->name == spawnpoint) {
557 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
558 if(spawnpoint != "main") {
561 activate(Vector(0, 0));
569 Sector::activate(const Vector& player_pos)
571 if(_current != this) {
573 _current->deactivate();
576 // register sectortable as sector in scripting
577 HSQUIRRELVM vm = Scripting::global_vm;
578 sq_pushroottable(vm);
579 sq_pushstring(vm, "sector", -1);
580 sq_pushobject(vm, sector_table);
581 if(SQ_FAILED(sq_createslot(vm, -3)))
582 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
585 for(GameObjects::iterator i = gameobjects.begin();
586 i != gameobjects.end(); ++i) {
587 GameObject* object = *i;
594 // spawn smalltux below spawnpoint
595 if (!player->is_big()) {
596 player->move(player_pos + Vector(0,32));
598 player->move(player_pos);
601 // spawning tux in the ground would kill him
602 if(!is_free_of_tiles(player->get_bbox())) {
603 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
604 Vector npos = player->get_bbox().p1;
609 camera->reset(player->get_pos());
610 update_game_objects();
613 if(init_script != "") {
614 std::istringstream in(init_script);
615 run_script(in, std::string("Sector(") + name + ") - init");
625 // remove sector entry from global vm
626 HSQUIRRELVM vm = Scripting::global_vm;
627 sq_pushroottable(vm);
628 sq_pushstring(vm, "sector", -1);
629 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
630 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
633 for(GameObjects::iterator i = gameobjects.begin();
634 i != gameobjects.end(); ++i) {
635 GameObject* object = *i;
637 try_unexpose(object);
645 Sector::get_active_region()
648 camera->get_translation() - Vector(1600, 1200),
649 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
653 Sector::update(float elapsed_time)
655 player->check_bounds(camera);
658 for(GameObjects::iterator i = gameobjects.begin();
659 i != gameobjects.end(); ++i) {
660 GameObject* object = *i;
661 if(!object->is_valid())
664 object->update(elapsed_time);
667 /* Handle all possible collisions. */
669 update_game_objects();
673 Sector::update_game_objects()
675 /** cleanup marked objects */
676 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
677 i != gameobjects.end(); /* nothing */) {
678 GameObject* object = *i;
680 if(object->is_valid()) {
685 before_object_remove(object);
688 i = gameobjects.erase(i);
691 /* add newly created objects */
692 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
693 i != gameobjects_new.end(); ++i)
695 GameObject* object = *i;
697 before_object_add(object);
699 gameobjects.push_back(object);
701 gameobjects_new.clear();
703 /* update solid_tilemaps list */
704 //FIXME: this could be more efficient
705 solid_tilemaps.clear();
706 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
707 i != gameobjects.end(); ++i)
709 TileMap* tm = dynamic_cast<TileMap*>(*i);
711 if (tm->is_solid()) solid_tilemaps.push_back(tm);
717 Sector::before_object_add(GameObject* object)
719 Bullet* bullet = dynamic_cast<Bullet*> (object);
721 bullets.push_back(bullet);
724 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
725 if(movingobject != NULL) {
726 moving_objects.push_back(movingobject);
729 Portable* portable = dynamic_cast<Portable*> (object);
730 if(portable != NULL) {
731 portables.push_back(portable);
734 TileMap* tilemap = dynamic_cast<TileMap*> (object);
735 if(tilemap != NULL && tilemap->is_solid()) {
736 solid_tilemaps.push_back(tilemap);
739 Camera* camera = dynamic_cast<Camera*> (object);
741 if(this->camera != 0) {
742 log_warning << "Multiple cameras added. Ignoring" << std::endl;
745 this->camera = camera;
748 Player* player = dynamic_cast<Player*> (object);
750 if(this->player != 0) {
751 log_warning << "Multiple players added. Ignoring" << std::endl;
754 this->player = player;
757 UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
760 physic_object->physic.set_gravity(gravity);
764 if(_current == this) {
772 Sector::try_expose(GameObject* object)
774 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
775 if(interface != NULL) {
776 HSQUIRRELVM vm = Scripting::global_vm;
777 sq_pushobject(vm, sector_table);
778 interface->expose(vm, -1);
784 Sector::try_expose_me()
786 HSQUIRRELVM vm = Scripting::global_vm;
787 sq_pushobject(vm, sector_table);
788 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
789 expose_object(vm, -1, interface, "settings", false);
794 Sector::before_object_remove(GameObject* object)
796 Portable* portable = dynamic_cast<Portable*> (object);
797 if(portable != NULL) {
798 portables.erase(std::find(portables.begin(), portables.end(), portable));
800 Bullet* bullet = dynamic_cast<Bullet*> (object);
802 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
804 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
805 if(moving_object != NULL) {
806 moving_objects.erase(
807 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
811 try_unexpose(object);
815 Sector::try_unexpose(GameObject* object)
817 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
818 if(interface != NULL) {
819 HSQUIRRELVM vm = Scripting::global_vm;
820 SQInteger oldtop = sq_gettop(vm);
821 sq_pushobject(vm, sector_table);
823 interface->unexpose(vm, -1);
824 } catch(std::exception& e) {
825 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
827 sq_settop(vm, oldtop);
832 Sector::try_unexpose_me()
834 HSQUIRRELVM vm = Scripting::global_vm;
835 SQInteger oldtop = sq_gettop(vm);
836 sq_pushobject(vm, sector_table);
838 Scripting::unexpose_object(vm, -1, "settings");
839 } catch(std::exception& e) {
840 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
842 sq_settop(vm, oldtop);
845 Sector::draw(DrawingContext& context)
847 context.set_ambient_color( ambient_light );
848 context.push_transform();
849 context.set_translation(camera->get_translation());
851 for(GameObjects::iterator i = gameobjects.begin();
852 i != gameobjects.end(); ++i) {
853 GameObject* object = *i;
854 if(!object->is_valid())
857 if (draw_solids_only)
859 TileMap* tm = dynamic_cast<TileMap*>(object);
860 if (tm && !tm->is_solid())
864 object->draw(context);
868 Color col(0.2f, 0.2f, 0.2f, 0.7f);
869 for(MovingObjects::iterator i = moving_objects.begin();
870 i != moving_objects.end(); ++i) {
871 MovingObject* object = *i;
872 const Rect& rect = object->get_bbox();
874 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
878 context.pop_transform();
881 /*-------------------------------------------------------------------------
882 * Collision Detection
883 *-------------------------------------------------------------------------*/
885 static const float SHIFT_DELTA = 7.0f;
887 /** r1 is supposed to be moving, r2 a solid object */
888 void check_collisions(collision::Constraints* constraints,
889 const Vector& movement, const Rect& r1, const Rect& r2,
890 GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
892 if(!collision::intersects(r1, r2))
895 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
897 if(other != NULL && !other->collides(*object, dummy))
899 if(moving_object != NULL && !moving_object->collides(*other, dummy))
902 // calculate intersection
903 float itop = r1.get_bottom() - r2.get_top();
904 float ibottom = r2.get_bottom() - r1.get_top();
905 float ileft = r1.get_right() - r2.get_left();
906 float iright = r2.get_right() - r1.get_left();
908 if(fabsf(movement.y) > fabsf(movement.x)) {
909 if(ileft < SHIFT_DELTA) {
910 constraints->right = std::min(constraints->right, r2.get_left());
912 } else if(iright < SHIFT_DELTA) {
913 constraints->left = std::max(constraints->left, r2.get_right());
917 // shiftout bottom/top
918 if(itop < SHIFT_DELTA) {
919 constraints->bottom = std::min(constraints->bottom, r2.get_top());
921 } else if(ibottom < SHIFT_DELTA) {
922 constraints->top = std::max(constraints->top, r2.get_bottom());
927 constraints->ground_movement += addl_ground_movement;
929 HitResponse response = other->collision(*object, dummy);
930 if(response == PASSTHROUGH)
933 if(other->get_movement() != Vector(0, 0)) {
934 // TODO what todo when we collide with 2 moving objects?!?
935 constraints->ground_movement += other->get_movement();
939 float vert_penetration = std::min(itop, ibottom);
940 float horiz_penetration = std::min(ileft, iright);
941 if(vert_penetration < horiz_penetration) {
943 constraints->bottom = std::min(constraints->bottom, r2.get_top());
944 constraints->hit.bottom = true;
946 constraints->top = std::max(constraints->top, r2.get_bottom());
947 constraints->hit.top = true;
951 constraints->right = std::min(constraints->right, r2.get_left());
952 constraints->hit.right = true;
954 constraints->left = std::max(constraints->left, r2.get_right());
955 constraints->hit.left = true;
960 static const float DELTA = .001f;
963 Sector::collision_tilemap(collision::Constraints* constraints,
964 const Vector& movement, const Rect& dest) const
966 // calculate rectangle where the object will move
967 float x1 = dest.get_left();
968 float x2 = dest.get_right();
969 float y1 = dest.get_top();
970 float y2 = dest.get_bottom();
972 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
973 TileMap* solids = *i;
975 // test with all tiles in this rectangle
976 int starttilex = int(x1 - solids->get_x_offset()) / 32;
977 int starttiley = int(y1 - solids->get_y_offset()) / 32;
978 int max_x = int(x2 - solids->get_x_offset());
979 int max_y = int(y2+1 - solids->get_y_offset());
981 for(int x = starttilex; x*32 < max_x; ++x) {
982 for(int y = starttiley; y*32 < max_y; ++y) {
983 const Tile* tile = solids->get_tile(x, y);
986 // skip non-solid tiles
987 if((tile->getAttributes() & Tile::SOLID) == 0)
989 // only handle unisolid when the player is falling down and when he was
990 // above the tile before
991 if(tile->getAttributes() & Tile::UNISOLID) {
992 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
996 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
998 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
999 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1000 triangle = AATriangle(p1, p2, tile->getData());
1002 collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
1003 } else { // normal rectangular tile
1004 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());
1005 check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
1013 Sector::collision_tile_attributes(const Rect& dest) const
1015 float x1 = dest.p1.x;
1016 float y1 = dest.p1.y;
1017 float x2 = dest.p2.x;
1018 float y2 = dest.p2.y;
1020 uint32_t result = 0;
1021 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1022 TileMap* solids = *i;
1024 // test with all tiles in this rectangle
1025 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1026 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1027 int max_x = int(x2 - solids->get_x_offset());
1028 int max_y = int(y2+1 - solids->get_y_offset());
1030 for(int x = starttilex; x*32 < max_x; ++x) {
1031 for(int y = starttiley; y*32 < max_y; ++y) {
1032 const Tile* tile = solids->get_tile(x, y);
1035 result |= tile->getAttributes();
1043 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1044 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1047 float itop = r1.get_bottom() - r2.get_top();
1048 float ibottom = r2.get_bottom() - r1.get_top();
1049 float ileft = r1.get_right() - r2.get_left();
1050 float iright = r2.get_right() - r1.get_left();
1052 float vert_penetration = std::min(itop, ibottom);
1053 float horiz_penetration = std::min(ileft, iright);
1054 if(vert_penetration < horiz_penetration) {
1055 if(itop < ibottom) {
1057 normal.y = vert_penetration;
1060 normal.y = -vert_penetration;
1063 if(ileft < iright) {
1065 normal.x = horiz_penetration;
1068 normal.x = -horiz_penetration;
1074 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1076 using namespace collision;
1078 const Rect& r1 = object1->dest;
1079 const Rect& r2 = object2->dest;
1082 if(intersects(object1->dest, object2->dest)) {
1084 get_hit_normal(r1, r2, hit, normal);
1086 if(!object1->collides(*object2, hit))
1088 std::swap(hit.left, hit.right);
1089 std::swap(hit.top, hit.bottom);
1090 if(!object2->collides(*object1, hit))
1092 std::swap(hit.left, hit.right);
1093 std::swap(hit.top, hit.bottom);
1095 HitResponse response1 = object1->collision(*object2, hit);
1096 std::swap(hit.left, hit.right);
1097 std::swap(hit.top, hit.bottom);
1098 HitResponse response2 = object2->collision(*object1, hit);
1099 if(response1 == CONTINUE && response2 == CONTINUE) {
1100 normal *= (0.5 + DELTA);
1101 object1->dest.move(-normal);
1102 object2->dest.move(normal);
1103 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1104 normal *= (1 + DELTA);
1105 object1->dest.move(-normal);
1106 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1107 normal *= (1 + DELTA);
1108 object2->dest.move(normal);
1114 Sector::collision_static(collision::Constraints* constraints,
1115 const Vector& movement, const Rect& dest,
1118 collision_tilemap(constraints, movement, dest);
1120 // collision with other (static) objects
1121 for(MovingObjects::iterator i = moving_objects.begin();
1122 i != moving_objects.end(); ++i) {
1123 MovingObject* moving_object = *i;
1124 if(moving_object->get_group() != COLGROUP_STATIC
1125 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1127 if(!moving_object->is_valid())
1130 if(moving_object != &object)
1131 check_collisions(constraints, movement, dest, moving_object->bbox,
1132 &object, moving_object);
1137 Sector::collision_static_constrains(MovingObject& object)
1139 using namespace collision;
1140 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1142 Constraints constraints;
1143 Vector movement = object.get_movement();
1144 Rect& dest = object.dest;
1145 float owidth = object.get_bbox().get_width();
1146 float oheight = object.get_bbox().get_height();
1148 for(int i = 0; i < 2; ++i) {
1149 collision_static(&constraints, Vector(0, movement.y), dest, object);
1150 if(!constraints.has_constraints())
1153 // apply calculated horizontal constraints
1154 if(constraints.bottom < infinity) {
1155 float height = constraints.bottom - constraints.top;
1156 if(height < oheight) {
1157 // we're crushed, but ignore this for now, we'll get this again
1158 // later if we're really crushed or things will solve itself when
1159 // looking at the vertical constraints
1161 dest.p2.y = constraints.bottom - DELTA;
1162 dest.p1.y = dest.p2.y - oheight;
1163 } else if(constraints.top > -infinity) {
1164 dest.p1.y = constraints.top + DELTA;
1165 dest.p2.y = dest.p1.y + oheight;
1168 if(constraints.has_constraints()) {
1169 if(constraints.hit.bottom) {
1170 dest.move(constraints.ground_movement);
1172 if(constraints.hit.top || constraints.hit.bottom) {
1173 constraints.hit.left = false;
1174 constraints.hit.right = false;
1175 object.collision_solid(constraints.hit);
1179 constraints = Constraints();
1180 for(int i = 0; i < 2; ++i) {
1181 collision_static(&constraints, movement, dest, object);
1182 if(!constraints.has_constraints())
1185 // apply calculated vertical constraints
1186 if(constraints.right < infinity) {
1187 float width = constraints.right - constraints.left;
1188 if(width + SHIFT_DELTA < owidth) {
1190 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1191 constraints.left, constraints.right);
1197 object.collision_solid(h);
1199 dest.p2.x = constraints.right - DELTA;
1200 dest.p1.x = dest.p2.x - owidth;
1202 } else if(constraints.left > -infinity) {
1203 dest.p1.x = constraints.left + DELTA;
1204 dest.p2.x = dest.p1.x + owidth;
1208 if(constraints.has_constraints()) {
1209 if( constraints.hit.left || constraints.hit.right
1210 || constraints.hit.top || constraints.hit.bottom
1211 || constraints.hit.crush )
1212 object.collision_solid(constraints.hit);
1215 // an extra pass to make sure we're not crushed horizontally
1216 constraints = Constraints();
1217 collision_static(&constraints, movement, dest, object);
1218 if(constraints.bottom < infinity) {
1219 float height = constraints.bottom - constraints.top;
1220 if(height + SHIFT_DELTA < oheight) {
1222 printf("Object %p crushed vertically...\n", &object);
1228 object.collision_solid(h);
1234 const float MAX_SPEED = 16.0f;
1238 Sector::handle_collisions()
1240 using namespace collision;
1242 // calculate destination positions of the objects
1243 for(MovingObjects::iterator i = moving_objects.begin();
1244 i != moving_objects.end(); ++i) {
1245 MovingObject* moving_object = *i;
1246 Vector mov = moving_object->get_movement();
1248 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1249 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1250 moving_object->movement = mov.unit() * MAX_SPEED;
1251 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1254 moving_object->dest = moving_object->get_bbox();
1255 moving_object->dest.move(moving_object->get_movement());
1258 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1259 for(MovingObjects::iterator i = moving_objects.begin();
1260 i != moving_objects.end(); ++i) {
1261 MovingObject* moving_object = *i;
1262 if((moving_object->get_group() != COLGROUP_MOVING
1263 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1264 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1265 || !moving_object->is_valid())
1268 collision_static_constrains(*moving_object);
1272 // part2: COLGROUP_MOVING vs tile attributes
1273 for(MovingObjects::iterator i = moving_objects.begin();
1274 i != moving_objects.end(); ++i) {
1275 MovingObject* moving_object = *i;
1276 if((moving_object->get_group() != COLGROUP_MOVING
1277 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1278 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1279 || !moving_object->is_valid())
1282 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1283 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1284 moving_object->collision_tile(tile_attributes);
1288 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1289 for(MovingObjects::iterator i = moving_objects.begin();
1290 i != moving_objects.end(); ++i) {
1291 MovingObject* moving_object = *i;
1292 if((moving_object->get_group() != COLGROUP_MOVING
1293 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1294 || !moving_object->is_valid())
1297 for(MovingObjects::iterator i2 = moving_objects.begin();
1298 i2 != moving_objects.end(); ++i2) {
1299 MovingObject* moving_object_2 = *i2;
1300 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1301 || !moving_object_2->is_valid())
1304 if(intersects(moving_object->dest, moving_object_2->dest)) {
1307 get_hit_normal(moving_object->dest, moving_object_2->dest,
1309 if(!moving_object->collides(*moving_object_2, hit))
1311 if(!moving_object_2->collides(*moving_object, hit))
1314 moving_object->collision(*moving_object_2, hit);
1315 moving_object_2->collision(*moving_object, hit);
1320 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1321 for(MovingObjects::iterator i = moving_objects.begin();
1322 i != moving_objects.end(); ++i) {
1323 MovingObject* moving_object = *i;
1325 if((moving_object->get_group() != COLGROUP_MOVING
1326 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1327 || !moving_object->is_valid())
1330 for(MovingObjects::iterator i2 = i+1;
1331 i2 != moving_objects.end(); ++i2) {
1332 MovingObject* moving_object_2 = *i2;
1333 if((moving_object_2->get_group() != COLGROUP_MOVING
1334 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1335 || !moving_object_2->is_valid())
1338 collision_object(moving_object, moving_object_2);
1342 // apply object movement
1343 for(MovingObjects::iterator i = moving_objects.begin();
1344 i != moving_objects.end(); ++i) {
1345 MovingObject* moving_object = *i;
1347 moving_object->bbox = moving_object->dest;
1348 moving_object->movement = Vector(0, 0);
1353 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1355 using namespace collision;
1357 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1358 TileMap* solids = *i;
1360 // test with all tiles in this rectangle
1361 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1362 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1363 int max_x = int(rect.p2.x - solids->get_x_offset());
1364 int max_y = int(rect.p2.y - solids->get_y_offset());
1366 for(int x = starttilex; x*32 <= max_x; ++x) {
1367 for(int y = starttiley; y*32 <= max_y; ++y) {
1368 const Tile* tile = solids->get_tile(x, y);
1370 if(tile->getAttributes() & Tile::SLOPE) {
1371 AATriangle triangle;
1372 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1373 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1374 triangle = AATriangle(p1, p2, tile->getData());
1375 Constraints constraints;
1376 return collision::rectangle_aatriangle(&constraints, rect, triangle);
1378 if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1379 if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1388 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1390 using namespace collision;
1392 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1394 for(MovingObjects::const_iterator i = moving_objects.begin();
1395 i != moving_objects.end(); ++i) {
1396 const MovingObject* moving_object = *i;
1397 if (moving_object == ignore_object) continue;
1398 if (!moving_object->is_valid()) continue;
1399 if (moving_object->get_group() == COLGROUP_STATIC) {
1400 if(intersects(rect, moving_object->get_bbox())) return false;
1408 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1410 using namespace collision;
1412 if (!is_free_of_tiles(rect)) return false;
1414 for(MovingObjects::const_iterator i = moving_objects.begin();
1415 i != moving_objects.end(); ++i) {
1416 const MovingObject* moving_object = *i;
1417 if (moving_object == ignore_object) continue;
1418 if (!moving_object->is_valid()) continue;
1419 if ((moving_object->get_group() == COLGROUP_MOVING)
1420 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1421 || (moving_object->get_group() == COLGROUP_STATIC)) {
1422 if(intersects(rect, moving_object->get_bbox())) return false;
1430 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1432 // TODO remove this function and move these checks elsewhere...
1434 Bullet* new_bullet = 0;
1435 if((player_status->bonus == FIRE_BONUS &&
1436 (int)bullets.size() >= player_status->max_fire_bullets) ||
1437 (player_status->bonus == ICE_BONUS &&
1438 (int)bullets.size() >= player_status->max_ice_bullets))
1440 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1441 add_object(new_bullet);
1443 sound_manager->play("sounds/shoot.wav");
1449 Sector::add_smoke_cloud(const Vector& pos)
1451 add_object(new SmokeCloud(pos));
1456 Sector::play_music(MusicType type)
1458 currentmusic = type;
1459 switch(currentmusic) {
1461 sound_manager->play_music(music);
1464 sound_manager->play_music("music/salcon.ogg");
1466 case HERRING_WARNING_MUSIC:
1467 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1470 sound_manager->play_music("");
1476 Sector::get_music_type()
1478 return currentmusic;
1482 Sector::get_total_badguys()
1484 int total_badguys = 0;
1485 for(GameObjects::iterator i = gameobjects.begin();
1486 i != gameobjects.end(); ++i) {
1487 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1488 if (badguy && badguy->countMe)
1492 return total_badguys;
1496 Sector::inside(const Rect& rect) const
1498 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1499 TileMap* solids = *i;
1500 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1501 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1503 if (horizontally && vertically)
1510 Sector::get_width() const
1513 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1514 i != solid_tilemaps.end(); i++) {
1515 TileMap* solids = *i;
1516 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1517 width = solids->get_width() * 32 + solids->get_x_offset();
1525 Sector::get_height() const
1528 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1529 i != solid_tilemaps.end(); i++) {
1530 TileMap* solids = *i;
1531 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1532 height = solids->get_height() * 32 + solids->get_y_offset();
1540 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1542 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1543 TileMap* solids = *i;
1544 solids->change_all(old_tile_id, new_tile_id);
1550 Sector::set_ambient_light(float red, float green, float blue)
1552 ambient_light.red = red;
1553 ambient_light.green = green;
1554 ambient_light.blue = blue;
1558 Sector::get_ambient_red()
1560 return ambient_light.red;
1564 Sector::get_ambient_green()
1566 return ambient_light.green;
1570 Sector::get_ambient_blue()
1572 return ambient_light.blue;