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"
72 Sector* Sector::_current = 0;
74 bool Sector::show_collrects = false;
75 bool Sector::draw_solids_only = false;
77 Sector::Sector(Level* parent)
78 : level(parent), currentmusic(LEVEL_MUSIC),
79 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10.0), player(0), camera(0)
81 add_object(new Player(player_status, "Tux"));
82 add_object(new DisplayEffect("Effect"));
83 add_object(new TextObject("Text"));
85 // create a new squirrel table for the sector
86 using namespace Scripting;
88 sq_collectgarbage(global_vm);
90 sq_newtable(global_vm);
91 sq_pushroottable(global_vm);
92 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
93 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
95 sq_resetobject(§or_table);
96 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
97 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
98 sq_addref(global_vm, §or_table);
104 using namespace Scripting;
108 for(ScriptList::iterator i = scripts.begin();
109 i != scripts.end(); ++i) {
110 HSQOBJECT& object = *i;
111 sq_release(global_vm, &object);
113 sq_release(global_vm, §or_table);
114 sq_collectgarbage(global_vm);
116 update_game_objects();
117 assert(gameobjects_new.size() == 0);
119 for(GameObjects::iterator i = gameobjects.begin();
120 i != gameobjects.end(); ++i) {
121 GameObject* object = *i;
122 before_object_remove(object);
126 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
138 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
140 if(name == "camera") {
141 Camera* camera = new Camera(this, "Camera");
142 camera->parse(reader);
144 } else if(name == "particles-snow") {
145 SnowParticleSystem* partsys = new SnowParticleSystem();
146 partsys->parse(reader);
148 } else if(name == "particles-rain") {
149 RainParticleSystem* partsys = new RainParticleSystem();
150 partsys->parse(reader);
152 } else if(name == "particles-comets") {
153 CometParticleSystem* partsys = new CometParticleSystem();
154 partsys->parse(reader);
156 } else if(name == "particles-ghosts") {
157 GhostParticleSystem* partsys = new GhostParticleSystem();
158 partsys->parse(reader);
160 } else if(name == "particles-clouds") {
161 CloudParticleSystem* partsys = new CloudParticleSystem();
162 partsys->parse(reader);
164 } else if(name == "money") { // for compatibility with old maps
165 return new Jumpy(reader);
169 return create_object(name, reader);
170 } catch(std::exception& e) {
171 log_warning << e.what() << "" << std::endl;
178 Sector::parse(const lisp::Lisp& sector)
180 lisp::ListIterator iter(§or);
182 const std::string& token = iter.item();
183 if(token == "name") {
184 iter.value()->get(name);
185 } else if(token == "gravity") {
186 iter.value()->get(gravity);
187 } else if(token == "music") {
188 iter.value()->get(music);
189 } else if(token == "spawnpoint") {
190 SpawnPoint* sp = new SpawnPoint(iter.lisp());
191 spawnpoints.push_back(sp);
192 } else if(token == "init-script") {
193 iter.value()->get(init_script);
194 } else if(token == "ambient-light") {
195 std::vector<float> vColor;
196 sector.get_vector( "ambient-light", vColor );
197 if(vColor.size() < 3) {
198 log_warning << "(ambient-light) requires a color as argument" << std::endl;
200 ambient_light = Color( vColor );
203 GameObject* object = parse_object(token, *(iter.lisp()));
210 update_game_objects();
212 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
216 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
217 update_game_objects();
218 add_object(new Camera(this, "Camera"));
221 update_game_objects();
225 Sector::parse_old_format(const lisp::Lisp& reader)
228 reader.get("gravity", gravity);
230 std::string backgroundimage;
231 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
232 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
233 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
234 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
235 backgroundimage = "images/background/" + backgroundimage;
236 if (!PHYSFS_exists(backgroundimage.c_str())) {
237 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
238 backgroundimage = "";
243 reader.get("bkgd_speed", bgspeed);
246 Color bkgd_top, bkgd_bottom;
247 int r = 0, g = 0, b = 128;
248 reader.get("bkgd_red_top", r);
249 reader.get("bkgd_green_top", g);
250 reader.get("bkgd_blue_top", b);
251 bkgd_top.red = static_cast<float> (r) / 255.0f;
252 bkgd_top.green = static_cast<float> (g) / 255.0f;
253 bkgd_top.blue = static_cast<float> (b) / 255.0f;
255 reader.get("bkgd_red_bottom", r);
256 reader.get("bkgd_green_bottom", g);
257 reader.get("bkgd_blue_bottom", b);
258 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
259 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
260 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
262 if(backgroundimage != "") {
263 Background* background = new Background();
264 background->set_image(backgroundimage, bgspeed);
265 add_object(background);
267 Gradient* gradient = new Gradient();
268 gradient->set_gradient(bkgd_top, bkgd_bottom);
269 add_object(gradient);
272 std::string particlesystem;
273 reader.get("particle_system", particlesystem);
274 if(particlesystem == "clouds")
275 add_object(new CloudParticleSystem());
276 else if(particlesystem == "snow")
277 add_object(new SnowParticleSystem());
278 else if(particlesystem == "rain")
279 add_object(new RainParticleSystem());
281 Vector startpos(100, 170);
282 reader.get("start_pos_x", startpos.x);
283 reader.get("start_pos_y", startpos.y);
285 SpawnPoint* spawn = new SpawnPoint;
286 spawn->pos = startpos;
287 spawn->name = "main";
288 spawnpoints.push_back(spawn);
290 music = "chipdisko.ogg";
291 // skip reading music filename. It's all .ogg now, anyway
293 reader.get("music", music);
295 music = "music/" + music;
297 int width = 30, height = 15;
298 reader.get("width", width);
299 reader.get("height", height);
301 std::vector<unsigned int> tiles;
302 if(reader.get_vector("interactive-tm", tiles)
303 || reader.get_vector("tilemap", tiles)) {
304 TileMap* tilemap = new TileMap();
305 tilemap->set(width, height, tiles, LAYER_TILES, true);
307 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
308 for(size_t x=0; x < tilemap->get_width(); ++x) {
309 for(size_t y=0; y < tilemap->get_height(); ++y) {
310 const Tile* tile = tilemap->get_tile(x, y);
311 if(tile->getID() == 112) tilemap->change(x, y, 1311);
315 if (height < 19) tilemap->resize(width, 19);
319 if(reader.get_vector("background-tm", tiles)) {
320 TileMap* tilemap = new TileMap();
321 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
322 if (height < 19) tilemap->resize(width, 19);
326 if(reader.get_vector("foreground-tm", tiles)) {
327 TileMap* tilemap = new TileMap();
328 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
330 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
331 if (height < 19) tilemap->resize(width, 19, 2035);
336 // read reset-points (now spawn-points)
337 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
339 lisp::ListIterator iter(resetpoints);
341 if(iter.item() == "point") {
343 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
345 SpawnPoint* sp = new SpawnPoint;
348 spawnpoints.push_back(sp);
351 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
357 const lisp::Lisp* objects = reader.get_lisp("objects");
359 lisp::ListIterator iter(objects);
361 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
365 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
371 Camera* camera = new Camera(this, "Camera");
374 update_game_objects();
376 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
379 update_game_objects();
383 Sector::fix_old_tiles()
385 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
386 TileMap* solids = *i;
387 for(size_t x=0; x < solids->get_width(); ++x) {
388 for(size_t y=0; y < solids->get_height(); ++y) {
389 const Tile* tile = solids->get_tile(x, y);
390 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
392 if(tile->getID() == 112) {
393 add_object(new InvisibleBlock(pos));
394 solids->change(x, y, 0);
395 } else if(tile->getAttributes() & Tile::COIN) {
396 add_object(new Coin(pos));
397 solids->change(x, y, 0);
398 } else if(tile->getAttributes() & Tile::FULLBOX) {
399 add_object(new BonusBlock(pos, tile->getData()));
400 solids->change(x, y, 0);
401 } else if(tile->getAttributes() & Tile::BRICK) {
402 add_object(new Brick(pos, tile->getData()));
403 solids->change(x, y, 0);
404 } else if(tile->getAttributes() & Tile::GOAL) {
405 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
406 add_object(new SequenceTrigger(pos, sequence));
407 solids->change(x, y, 0);
413 // add lights for special tiles
414 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
415 TileMap* tm = dynamic_cast<TileMap*>(*i);
417 for(size_t x=0; x < tm->get_width(); ++x) {
418 for(size_t y=0; y < tm->get_height(); ++y) {
419 const Tile* tile = tm->get_tile(x, y);
420 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
421 Vector center(pos.x + 16, pos.y + 16);
424 if (tile->getID() == 1517) {
425 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
426 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
429 if ((tile->getID() == 173) || (tile->getID() == 1700) || (tile->getID() == 1705) || (tile->getID() == 1706)) {
430 // space lights a bit
431 if (((tm->get_tile(x-1, y)->getID() != tm->get_tile(x,y)->getID())
432 && (tm->get_tile(x, y-1)->getID() != tm->get_tile(x,y)->getID()))
433 || ((x % 3 == 0) && (y % 3 == 0))) {
434 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
435 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
447 Sector::write(lisp::Writer& writer)
449 writer.write_string("name", name);
450 writer.write_float("gravity", gravity);
451 writer.write_string("music", music);
454 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
456 SpawnPoint* spawn = *i;
457 writer.start_list("spawn-points");
458 writer.write_string("name", spawn->name);
459 writer.write_float("x", spawn->pos.x);
460 writer.write_float("y", spawn->pos.y);
461 writer.end_list("spawn-points");
465 for(GameObjects::iterator i = gameobjects.begin();
466 i != gameobjects.end(); ++i) {
467 Serializable* serializable = dynamic_cast<Serializable*> (*i);
469 serializable->write(writer);
474 Sector::run_script(std::istream& in, const std::string& sourcename)
476 using namespace Scripting;
478 // garbage collect thread list
479 for(ScriptList::iterator i = scripts.begin();
480 i != scripts.end(); ) {
481 HSQOBJECT& object = *i;
482 HSQUIRRELVM vm = object_to_vm(object);
484 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
485 sq_release(global_vm, &object);
486 i = scripts.erase(i);
493 HSQOBJECT object = create_thread(global_vm);
494 scripts.push_back(object);
496 HSQUIRRELVM vm = object_to_vm(object);
498 // set sector_table as roottable for the thread
499 sq_pushobject(vm, sector_table);
502 compile_and_run(vm, in, sourcename);
508 Sector::add_object(GameObject* object)
510 // make sure the object isn't already in the list
512 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
515 assert("object already added to sector" == 0);
518 for(GameObjects::iterator i = gameobjects_new.begin();
519 i != gameobjects_new.end(); ++i) {
521 assert("object already added to sector" == 0);
527 gameobjects_new.push_back(object);
531 Sector::activate(const std::string& spawnpoint)
534 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
536 if((*i)->name == spawnpoint) {
542 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
543 if(spawnpoint != "main") {
546 activate(Vector(0, 0));
554 Sector::activate(const Vector& player_pos)
556 if(_current != this) {
558 _current->deactivate();
561 // register sectortable as sector in scripting
562 HSQUIRRELVM vm = Scripting::global_vm;
563 sq_pushroottable(vm);
564 sq_pushstring(vm, "sector", -1);
565 sq_pushobject(vm, sector_table);
566 if(SQ_FAILED(sq_createslot(vm, -3)))
567 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
570 for(GameObjects::iterator i = gameobjects.begin();
571 i != gameobjects.end(); ++i) {
572 GameObject* object = *i;
579 // spawn smalltux below spawnpoint
580 if (!player->is_big()) {
581 player->move(player_pos + Vector(0,32));
583 player->move(player_pos);
586 // spawning tux in the ground would kill him
587 if(!is_free_of_tiles(player->get_bbox())) {
588 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
589 Vector npos = player->get_bbox().p1;
594 camera->reset(player->get_pos());
595 update_game_objects();
598 if(init_script != "") {
599 std::istringstream in(init_script);
600 run_script(in, std::string("Sector(") + name + ") - init");
610 // remove sector entry from global vm
611 HSQUIRRELVM vm = Scripting::global_vm;
612 sq_pushroottable(vm);
613 sq_pushstring(vm, "sector", -1);
614 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
615 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
618 for(GameObjects::iterator i = gameobjects.begin();
619 i != gameobjects.end(); ++i) {
620 GameObject* object = *i;
622 try_unexpose(object);
630 Sector::get_active_region()
633 camera->get_translation() - Vector(1600, 1200),
634 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
638 Sector::update(float elapsed_time)
640 player->check_bounds(camera);
643 for(GameObjects::iterator i = gameobjects.begin();
644 i != gameobjects.end(); ++i) {
645 GameObject* object = *i;
646 if(!object->is_valid())
649 object->update(elapsed_time);
652 /* Handle all possible collisions. */
654 update_game_objects();
658 Sector::update_game_objects()
660 /** cleanup marked objects */
661 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
662 i != gameobjects.end(); /* nothing */) {
663 GameObject* object = *i;
665 if(object->is_valid()) {
670 before_object_remove(object);
673 i = gameobjects.erase(i);
676 /* add newly created objects */
677 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
678 i != gameobjects_new.end(); ++i)
680 GameObject* object = *i;
682 before_object_add(object);
684 gameobjects.push_back(object);
686 gameobjects_new.clear();
690 Sector::before_object_add(GameObject* object)
692 Bullet* bullet = dynamic_cast<Bullet*> (object);
694 bullets.push_back(bullet);
697 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
698 if(movingobject != NULL) {
699 moving_objects.push_back(movingobject);
702 Portable* portable = dynamic_cast<Portable*> (object);
703 if(portable != NULL) {
704 portables.push_back(portable);
707 TileMap* tilemap = dynamic_cast<TileMap*> (object);
708 if(tilemap != NULL && tilemap->is_solid()) {
709 solid_tilemaps.push_back(tilemap);
712 Camera* camera = dynamic_cast<Camera*> (object);
714 if(this->camera != 0) {
715 log_warning << "Multiple cameras added. Ignoring" << std::endl;
718 this->camera = camera;
721 Player* player = dynamic_cast<Player*> (object);
723 if(this->player != 0) {
724 log_warning << "Multiple players added. Ignoring" << std::endl;
727 this->player = player;
730 UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
733 physic_object->physic.set_gravity(gravity);
737 if(_current == this) {
745 Sector::try_expose(GameObject* object)
747 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
748 if(interface != NULL) {
749 HSQUIRRELVM vm = Scripting::global_vm;
750 sq_pushobject(vm, sector_table);
751 interface->expose(vm, -1);
757 Sector::try_expose_me()
759 HSQUIRRELVM vm = Scripting::global_vm;
760 sq_pushobject(vm, sector_table);
761 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
762 expose_object(vm, -1, interface, "settings", false);
767 Sector::before_object_remove(GameObject* object)
769 Portable* portable = dynamic_cast<Portable*> (object);
770 if(portable != NULL) {
771 portables.erase(std::find(portables.begin(), portables.end(), portable));
773 Bullet* bullet = dynamic_cast<Bullet*> (object);
775 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
777 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
778 if(moving_object != NULL) {
779 moving_objects.erase(
780 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
784 try_unexpose(object);
788 Sector::try_unexpose(GameObject* object)
790 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
791 if(interface != NULL) {
792 HSQUIRRELVM vm = Scripting::global_vm;
793 SQInteger oldtop = sq_gettop(vm);
794 sq_pushobject(vm, sector_table);
796 interface->unexpose(vm, -1);
797 } catch(std::exception& e) {
798 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
800 sq_settop(vm, oldtop);
805 Sector::try_unexpose_me()
807 HSQUIRRELVM vm = Scripting::global_vm;
808 SQInteger oldtop = sq_gettop(vm);
809 sq_pushobject(vm, sector_table);
811 Scripting::unexpose_object(vm, -1, "settings");
812 } catch(std::exception& e) {
813 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
815 sq_settop(vm, oldtop);
818 Sector::draw(DrawingContext& context)
820 context.set_ambient_color( ambient_light );
821 context.push_transform();
822 context.set_translation(camera->get_translation());
824 for(GameObjects::iterator i = gameobjects.begin();
825 i != gameobjects.end(); ++i) {
826 GameObject* object = *i;
827 if(!object->is_valid())
830 if (draw_solids_only)
832 TileMap* tm = dynamic_cast<TileMap*>(object);
833 if (tm && !tm->is_solid())
837 object->draw(context);
841 Color col(0.2f, 0.2f, 0.2f, 0.7f);
842 for(MovingObjects::iterator i = moving_objects.begin();
843 i != moving_objects.end(); ++i) {
844 MovingObject* object = *i;
845 const Rect& rect = object->get_bbox();
847 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
851 context.pop_transform();
854 /*-------------------------------------------------------------------------
855 * Collision Detection
856 *-------------------------------------------------------------------------*/
858 static const float SHIFT_DELTA = 7.0f;
860 /** r1 is supposed to be moving, r2 a solid object */
861 void check_collisions(collision::Constraints* constraints,
862 const Vector& movement, const Rect& r1, const Rect& r2,
863 GameObject* object = NULL, MovingObject* other = NULL)
865 if(!collision::intersects(r1, r2))
868 // calculate intersection
869 float itop = r1.get_bottom() - r2.get_top();
870 float ibottom = r2.get_bottom() - r1.get_top();
871 float ileft = r1.get_right() - r2.get_left();
872 float iright = r2.get_right() - r1.get_left();
874 if(fabsf(movement.y) > fabsf(movement.x)) {
875 if(ileft < SHIFT_DELTA) {
876 constraints->right = std::min(constraints->right, r2.get_left());
878 } else if(iright < SHIFT_DELTA) {
879 constraints->left = std::max(constraints->left, r2.get_right());
883 // shiftout bottom/top
884 if(itop < SHIFT_DELTA) {
885 constraints->bottom = std::min(constraints->bottom, r2.get_top());
887 } else if(ibottom < SHIFT_DELTA) {
888 constraints->top = std::max(constraints->top, r2.get_bottom());
895 HitResponse response = other->collision(*object, dummy);
896 if(response == PASSTHROUGH)
898 if(other->get_movement() != Vector(0, 0)) {
899 // TODO what todo when we collide with 2 moving objects?!?
900 constraints->ground_movement = other->get_movement();
904 float vert_penetration = std::min(itop, ibottom);
905 float horiz_penetration = std::min(ileft, iright);
906 if(vert_penetration < horiz_penetration) {
908 constraints->bottom = std::min(constraints->bottom, r2.get_top());
909 constraints->hit.bottom = true;
911 constraints->top = std::max(constraints->top, r2.get_bottom());
912 constraints->hit.top = true;
916 constraints->right = std::min(constraints->right, r2.get_left());
917 constraints->hit.right = true;
919 constraints->left = std::max(constraints->left, r2.get_right());
920 constraints->hit.left = true;
925 static const float DELTA = .001f;
928 Sector::collision_tilemap(collision::Constraints* constraints,
929 const Vector& movement, const Rect& dest) const
931 // calculate rectangle where the object will move
932 float x1 = dest.get_left();
933 float x2 = dest.get_right();
934 float y1 = dest.get_top();
935 float y2 = dest.get_bottom();
937 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
938 TileMap* solids = *i;
940 // test with all tiles in this rectangle
941 int starttilex = int(x1 - solids->get_x_offset()) / 32;
942 int starttiley = int(y1 - solids->get_y_offset()) / 32;
943 int max_x = int(x2 - solids->get_x_offset());
944 int max_y = int(y2+1 - solids->get_y_offset());
946 for(int x = starttilex; x*32 < max_x; ++x) {
947 for(int y = starttiley; y*32 < max_y; ++y) {
948 const Tile* tile = solids->get_tile(x, y);
951 // skip non-solid tiles
952 if((tile->getAttributes() & Tile::SOLID) == 0)
954 // only handle unisolid when the player is falling down and when he was
955 // above the tile before
956 if(tile->getAttributes() & Tile::UNISOLID) {
957 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
961 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
963 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
964 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
965 triangle = AATriangle(p1, p2, tile->getData());
967 collision::rectangle_aatriangle(constraints, dest, triangle);
968 } else { // normal rectangular tile
969 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());
970 check_collisions(constraints, movement, dest, rect);
978 Sector::collision_tile_attributes(const Rect& dest) const
980 float x1 = dest.p1.x;
981 float y1 = dest.p1.y;
982 float x2 = dest.p2.x;
983 float y2 = dest.p2.y;
986 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
987 TileMap* solids = *i;
989 // test with all tiles in this rectangle
990 int starttilex = int(x1 - solids->get_x_offset()) / 32;
991 int starttiley = int(y1 - solids->get_y_offset()) / 32;
992 int max_x = int(x2 - solids->get_x_offset());
993 int max_y = int(y2+1 - solids->get_y_offset());
995 for(int x = starttilex; x*32 < max_x; ++x) {
996 for(int y = starttiley; y*32 < max_y; ++y) {
997 const Tile* tile = solids->get_tile(x, y);
1000 result |= tile->getAttributes();
1008 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1009 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1012 float itop = r1.get_bottom() - r2.get_top();
1013 float ibottom = r2.get_bottom() - r1.get_top();
1014 float ileft = r1.get_right() - r2.get_left();
1015 float iright = r2.get_right() - r1.get_left();
1017 float vert_penetration = std::min(itop, ibottom);
1018 float horiz_penetration = std::min(ileft, iright);
1019 if(vert_penetration < horiz_penetration) {
1020 if(itop < ibottom) {
1022 normal.y = vert_penetration;
1025 normal.y = -vert_penetration;
1028 if(ileft < iright) {
1030 normal.x = horiz_penetration;
1033 normal.x = -horiz_penetration;
1039 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1041 using namespace collision;
1043 const Rect& r1 = object1->dest;
1044 const Rect& r2 = object2->dest;
1047 if(intersects(object1->dest, object2->dest)) {
1049 get_hit_normal(r1, r2, hit, normal);
1051 HitResponse response1 = object1->collision(*object2, hit);
1052 std::swap(hit.left, hit.right);
1053 std::swap(hit.top, hit.bottom);
1054 HitResponse response2 = object2->collision(*object1, hit);
1055 assert( response1 != SOLID && response1 != PASSTHROUGH );
1056 assert( response2 != SOLID && response2 != PASSTHROUGH );
1057 if(response1 == CONTINUE && response2 == CONTINUE) {
1058 normal *= (0.5 + DELTA);
1059 object1->dest.move(-normal);
1060 object2->dest.move(normal);
1061 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1062 normal *= (1 + DELTA);
1063 object1->dest.move(-normal);
1064 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1065 normal *= (1 + DELTA);
1066 object2->dest.move(normal);
1072 Sector::collision_static(collision::Constraints* constraints,
1073 const Vector& movement, const Rect& dest,
1076 collision_tilemap(constraints, movement, dest);
1078 // collision with other (static) objects
1079 for(MovingObjects::iterator i = moving_objects.begin();
1080 i != moving_objects.end(); ++i) {
1081 MovingObject* moving_object = *i;
1082 if(moving_object->get_group() != COLGROUP_STATIC
1083 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1085 if(!moving_object->is_valid())
1088 if(moving_object != &object)
1089 check_collisions(constraints, movement, dest, moving_object->bbox,
1090 &object, moving_object);
1095 Sector::collision_static_constrains(MovingObject& object)
1097 using namespace collision;
1098 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1100 Constraints constraints;
1101 Vector movement = object.get_movement();
1102 Rect& dest = object.dest;
1103 float owidth = object.get_bbox().get_width();
1104 float oheight = object.get_bbox().get_height();
1106 for(int i = 0; i < 2; ++i) {
1107 collision_static(&constraints, Vector(0, movement.y), dest, object);
1108 if(!constraints.has_constraints())
1111 // apply calculated horizontal constraints
1112 if(constraints.bottom < infinity) {
1113 float height = constraints.bottom - constraints.top;
1114 if(height < oheight) {
1115 // we're crushed, but ignore this for now, we'll get this again
1116 // later if we're really crushed or things will solve itself when
1117 // looking at the vertical constraints
1119 dest.p2.y = constraints.bottom - DELTA;
1120 dest.p1.y = dest.p2.y - oheight;
1121 } else if(constraints.top > -infinity) {
1122 dest.p1.y = constraints.top + DELTA;
1123 dest.p2.y = dest.p1.y + oheight;
1126 if(constraints.has_constraints()) {
1127 if(constraints.hit.bottom) {
1128 dest.move(constraints.ground_movement);
1130 if(constraints.hit.top || constraints.hit.bottom) {
1131 constraints.hit.left = false;
1132 constraints.hit.right = false;
1133 object.collision_solid(constraints.hit);
1137 constraints = Constraints();
1138 for(int i = 0; i < 2; ++i) {
1139 collision_static(&constraints, movement, dest, object);
1140 if(!constraints.has_constraints())
1143 // apply calculated vertical constraints
1144 if(constraints.right < infinity) {
1145 float width = constraints.right - constraints.left;
1146 if(width + SHIFT_DELTA < owidth) {
1147 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1148 constraints.left, constraints.right);
1153 object.collision_solid(h);
1155 dest.p2.x = constraints.right - DELTA;
1156 dest.p1.x = dest.p2.x - owidth;
1158 } else if(constraints.left > -infinity) {
1159 dest.p1.x = constraints.left + DELTA;
1160 dest.p2.x = dest.p1.x + owidth;
1164 if(constraints.has_constraints()) {
1165 if( constraints.hit.left || constraints.hit.right
1166 || constraints.hit.top || constraints.hit.bottom
1167 || constraints.hit.crush )
1168 object.collision_solid(constraints.hit);
1171 // an extra pass to make sure we're not crushed horizontally
1172 constraints = Constraints();
1173 collision_static(&constraints, movement, dest, object);
1174 if(constraints.bottom < infinity) {
1175 float height = constraints.bottom - constraints.top;
1176 if(height + SHIFT_DELTA < oheight) {
1177 printf("Object %p crushed vertically...\n", &object);
1182 object.collision_solid(h);
1188 const float MAX_SPEED = 16.0f;
1192 Sector::handle_collisions()
1194 using namespace collision;
1196 // calculate destination positions of the objects
1197 for(MovingObjects::iterator i = moving_objects.begin();
1198 i != moving_objects.end(); ++i) {
1199 MovingObject* moving_object = *i;
1200 Vector mov = moving_object->get_movement();
1202 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1203 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1204 moving_object->movement = mov.unit() * MAX_SPEED;
1205 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1208 moving_object->dest = moving_object->get_bbox();
1209 moving_object->dest.move(moving_object->get_movement());
1212 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
1213 for(MovingObjects::iterator i = moving_objects.begin();
1214 i != moving_objects.end(); ++i) {
1215 MovingObject* moving_object = *i;
1216 if((moving_object->get_group() != COLGROUP_MOVING
1217 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1218 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1219 || !moving_object->is_valid())
1222 collision_static_constrains(*moving_object);
1226 // part2: COLGROUP_MOVING vs tile attributes
1227 for(MovingObjects::iterator i = moving_objects.begin();
1228 i != moving_objects.end(); ++i) {
1229 MovingObject* moving_object = *i;
1230 if((moving_object->get_group() != COLGROUP_MOVING
1231 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1232 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1233 || !moving_object->is_valid())
1236 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1237 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1238 moving_object->collision_tile(tile_attributes);
1242 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1243 for(MovingObjects::iterator i = moving_objects.begin();
1244 i != moving_objects.end(); ++i) {
1245 MovingObject* moving_object = *i;
1246 if((moving_object->get_group() != COLGROUP_MOVING
1247 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1248 || !moving_object->is_valid())
1251 for(MovingObjects::iterator i2 = moving_objects.begin();
1252 i2 != moving_objects.end(); ++i2) {
1253 MovingObject* moving_object_2 = *i2;
1254 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1255 || !moving_object_2->is_valid())
1258 if(intersects(moving_object->dest, moving_object_2->dest)) {
1261 get_hit_normal(moving_object->dest, moving_object_2->dest,
1263 moving_object->collision(*moving_object_2, hit);
1264 moving_object_2->collision(*moving_object, hit);
1269 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1270 for(MovingObjects::iterator i = moving_objects.begin();
1271 i != moving_objects.end(); ++i) {
1272 MovingObject* moving_object = *i;
1274 if((moving_object->get_group() != COLGROUP_MOVING
1275 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1276 || !moving_object->is_valid())
1279 for(MovingObjects::iterator i2 = i+1;
1280 i2 != moving_objects.end(); ++i2) {
1281 MovingObject* moving_object_2 = *i2;
1282 if((moving_object_2->get_group() != COLGROUP_MOVING
1283 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1284 || !moving_object_2->is_valid())
1287 collision_object(moving_object, moving_object_2);
1291 // apply object movement
1292 for(MovingObjects::iterator i = moving_objects.begin();
1293 i != moving_objects.end(); ++i) {
1294 MovingObject* moving_object = *i;
1296 moving_object->bbox = moving_object->dest;
1297 moving_object->movement = Vector(0, 0);
1302 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1304 using namespace collision;
1306 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1307 TileMap* solids = *i;
1309 // test with all tiles in this rectangle
1310 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1311 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1312 int max_x = int(rect.p2.x - solids->get_x_offset());
1313 int max_y = int(rect.p2.y - solids->get_y_offset());
1315 for(int x = starttilex; x*32 <= max_x; ++x) {
1316 for(int y = starttiley; y*32 <= max_y; ++y) {
1317 const Tile* tile = solids->get_tile(x, y);
1319 if(tile->getAttributes() & Tile::SLOPE) {
1320 AATriangle triangle;
1321 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1322 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1323 triangle = AATriangle(p1, p2, tile->getData());
1324 Constraints constraints;
1325 return collision::rectangle_aatriangle(&constraints, rect, triangle);
1327 if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1328 if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1337 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1339 using namespace collision;
1341 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1343 for(MovingObjects::const_iterator i = moving_objects.begin();
1344 i != moving_objects.end(); ++i) {
1345 const MovingObject* moving_object = *i;
1346 if (moving_object == ignore_object) continue;
1347 if (!moving_object->is_valid()) continue;
1348 if (moving_object->get_group() == COLGROUP_STATIC) {
1349 if(intersects(rect, moving_object->get_bbox())) return false;
1357 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1359 using namespace collision;
1361 if (!is_free_of_tiles(rect)) return false;
1363 for(MovingObjects::const_iterator i = moving_objects.begin();
1364 i != moving_objects.end(); ++i) {
1365 const MovingObject* moving_object = *i;
1366 if (moving_object == ignore_object) continue;
1367 if (!moving_object->is_valid()) continue;
1368 if ((moving_object->get_group() == COLGROUP_MOVING)
1369 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1370 || (moving_object->get_group() == COLGROUP_STATIC)) {
1371 if(intersects(rect, moving_object->get_bbox())) return false;
1379 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1381 // TODO remove this function and move these checks elsewhere...
1383 Bullet* new_bullet = 0;
1384 if((player_status->bonus == FIRE_BONUS &&
1385 (int)bullets.size() >= player_status->max_fire_bullets) ||
1386 (player_status->bonus == ICE_BONUS &&
1387 (int)bullets.size() >= player_status->max_ice_bullets))
1389 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1390 add_object(new_bullet);
1392 sound_manager->play("sounds/shoot.wav");
1398 Sector::add_smoke_cloud(const Vector& pos)
1400 add_object(new SmokeCloud(pos));
1405 Sector::play_music(MusicType type)
1407 currentmusic = type;
1408 switch(currentmusic) {
1410 sound_manager->play_music(music);
1413 sound_manager->play_music("music/salcon.ogg");
1415 case HERRING_WARNING_MUSIC:
1416 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1419 sound_manager->play_music("");
1425 Sector::get_music_type()
1427 return currentmusic;
1431 Sector::get_total_badguys()
1433 int total_badguys = 0;
1434 for(GameObjects::iterator i = gameobjects.begin();
1435 i != gameobjects.end(); ++i) {
1436 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1437 if (badguy && badguy->countMe)
1441 return total_badguys;
1445 Sector::inside(const Rect& rect) const
1447 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1448 TileMap* solids = *i;
1449 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1450 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1451 if (horizontally && vertically) return true;
1457 Sector::get_width() const
1460 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1461 TileMap* solids = *i;
1462 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) width = (solids->get_width() * 32 + solids->get_x_offset());
1468 Sector::get_height() const
1471 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1472 TileMap* solids = *i;
1473 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) height = (solids->get_height() * 32 + solids->get_y_offset());
1479 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1481 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1482 TileMap* solids = *i;
1483 solids->change_all(old_tile_id, new_tile_id);
1489 Sector::set_ambient_light(float red, float green, float blue)
1491 ambient_light.red = red;
1492 ambient_light.green = green;
1493 ambient_light.blue = blue;
1497 Sector::get_ambient_red()
1499 return ambient_light.red;
1503 Sector::get_ambient_green()
1505 return ambient_light.green;
1509 Sector::get_ambient_blue()
1511 return ambient_light.blue;