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)
181 TileMap::loading_worldmap = false;
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 TileMap::loading_worldmap = false;
246 reader.get("gravity", gravity);
248 std::string backgroundimage;
249 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
250 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
251 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
252 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
253 backgroundimage = "images/background/" + backgroundimage;
254 if (!PHYSFS_exists(backgroundimage.c_str())) {
255 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
256 backgroundimage = "";
261 reader.get("bkgd_speed", bgspeed);
264 Color bkgd_top, bkgd_bottom;
265 int r = 0, g = 0, b = 128;
266 reader.get("bkgd_red_top", r);
267 reader.get("bkgd_green_top", g);
268 reader.get("bkgd_blue_top", b);
269 bkgd_top.red = static_cast<float> (r) / 255.0f;
270 bkgd_top.green = static_cast<float> (g) / 255.0f;
271 bkgd_top.blue = static_cast<float> (b) / 255.0f;
273 reader.get("bkgd_red_bottom", r);
274 reader.get("bkgd_green_bottom", g);
275 reader.get("bkgd_blue_bottom", b);
276 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
277 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
278 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
280 if(backgroundimage != "") {
281 Background* background = new Background();
282 background->set_image(backgroundimage, bgspeed);
283 add_object(background);
285 Gradient* gradient = new Gradient();
286 gradient->set_gradient(bkgd_top, bkgd_bottom);
287 add_object(gradient);
290 std::string particlesystem;
291 reader.get("particle_system", particlesystem);
292 if(particlesystem == "clouds")
293 add_object(new CloudParticleSystem());
294 else if(particlesystem == "snow")
295 add_object(new SnowParticleSystem());
296 else if(particlesystem == "rain")
297 add_object(new RainParticleSystem());
299 Vector startpos(100, 170);
300 reader.get("start_pos_x", startpos.x);
301 reader.get("start_pos_y", startpos.y);
303 SpawnPoint* spawn = new SpawnPoint;
304 spawn->pos = startpos;
305 spawn->name = "main";
306 spawnpoints.push_back(spawn);
308 music = "chipdisko.ogg";
309 // skip reading music filename. It's all .ogg now, anyway
311 reader.get("music", music);
313 music = "music/" + music;
315 int width = 30, height = 15;
316 reader.get("width", width);
317 reader.get("height", height);
319 std::vector<unsigned int> tiles;
320 if(reader.get_vector("interactive-tm", tiles)
321 || reader.get_vector("tilemap", tiles)) {
322 TileMap* tilemap = new TileMap();
323 tilemap->set(width, height, tiles, LAYER_TILES, true);
325 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
326 for(size_t x=0; x < tilemap->get_width(); ++x) {
327 for(size_t y=0; y < tilemap->get_height(); ++y) {
328 const Tile* tile = tilemap->get_tile(x, y);
329 if(tile->getID() == 112) tilemap->change(x, y, 1311);
333 if (height < 19) tilemap->resize(width, 19);
337 if(reader.get_vector("background-tm", tiles)) {
338 TileMap* tilemap = new TileMap();
339 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
340 if (height < 19) tilemap->resize(width, 19);
344 if(reader.get_vector("foreground-tm", tiles)) {
345 TileMap* tilemap = new TileMap();
346 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
348 // fill additional space in foreground with tiles of ID 2035 (lightmap/black)
349 if (height < 19) tilemap->resize(width, 19, 2035);
354 // read reset-points (now spawn-points)
355 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
357 lisp::ListIterator iter(resetpoints);
359 if(iter.item() == "point") {
361 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
363 SpawnPoint* sp = new SpawnPoint;
366 spawnpoints.push_back(sp);
369 log_warning << "Unknown token '" << iter.item() << "' in reset-points." << std::endl;
375 const lisp::Lisp* objects = reader.get_lisp("objects");
377 lisp::ListIterator iter(objects);
379 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
383 log_warning << "Unknown object '" << iter.item() << "' in level." << std::endl;
389 Camera* camera = new Camera(this, "Camera");
392 update_game_objects();
394 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
397 update_game_objects();
401 Sector::fix_old_tiles()
403 for(std::list<TileMap*>::iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
404 TileMap* solids = *i;
405 for(size_t x=0; x < solids->get_width(); ++x) {
406 for(size_t y=0; y < solids->get_height(); ++y) {
407 const Tile* tile = solids->get_tile(x, y);
408 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
410 if(tile->getID() == 112) {
411 add_object(new InvisibleBlock(pos));
412 solids->change(x, y, 0);
413 } else if(tile->getAttributes() & Tile::COIN) {
414 add_object(new Coin(pos));
415 solids->change(x, y, 0);
416 } else if(tile->getAttributes() & Tile::FULLBOX) {
417 add_object(new BonusBlock(pos, tile->getData()));
418 solids->change(x, y, 0);
419 } else if(tile->getAttributes() & Tile::BRICK) {
420 add_object(new Brick(pos, tile->getData()));
421 solids->change(x, y, 0);
422 } else if(tile->getAttributes() & Tile::GOAL) {
423 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
424 add_object(new SequenceTrigger(pos, sequence));
425 solids->change(x, y, 0);
431 // add lights for special tiles
432 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
433 TileMap* tm = dynamic_cast<TileMap*>(*i);
435 for(size_t x=0; x < tm->get_width(); ++x) {
436 for(size_t y=0; y < tm->get_height(); ++y) {
437 const Tile* tile = tm->get_tile(x, y);
438 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
439 Vector center(pos.x + 16, pos.y + 16);
442 if (tile->getID() == 1517) {
443 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
444 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
447 if ((tile->getID() == 173) || (tile->getID() == 1700) || (tile->getID() == 1705) || (tile->getID() == 1706)) {
448 // space lights a bit
449 if (((tm->get_tile(x-1, y)->getID() != tm->get_tile(x,y)->getID())
450 && (tm->get_tile(x, y-1)->getID() != tm->get_tile(x,y)->getID()))
451 || ((x % 3 == 0) && (y % 3 == 0))) {
452 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
453 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
465 Sector::write(lisp::Writer& writer)
467 writer.write_string("name", name);
468 writer.write_float("gravity", gravity);
469 writer.write_string("music", music);
472 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
474 SpawnPoint* spawn = *i;
475 writer.start_list("spawn-points");
476 writer.write_string("name", spawn->name);
477 writer.write_float("x", spawn->pos.x);
478 writer.write_float("y", spawn->pos.y);
479 writer.end_list("spawn-points");
483 for(GameObjects::iterator i = gameobjects.begin();
484 i != gameobjects.end(); ++i) {
485 Serializable* serializable = dynamic_cast<Serializable*> (*i);
487 serializable->write(writer);
492 Sector::run_script(std::istream& in, const std::string& sourcename)
494 using namespace Scripting;
496 // garbage collect thread list
497 for(ScriptList::iterator i = scripts.begin();
498 i != scripts.end(); ) {
499 HSQOBJECT& object = *i;
500 HSQUIRRELVM vm = object_to_vm(object);
502 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
503 sq_release(global_vm, &object);
504 i = scripts.erase(i);
511 HSQOBJECT object = create_thread(global_vm);
512 scripts.push_back(object);
514 HSQUIRRELVM vm = object_to_vm(object);
516 // set sector_table as roottable for the thread
517 sq_pushobject(vm, sector_table);
520 compile_and_run(vm, in, sourcename);
526 Sector::add_object(GameObject* object)
528 // make sure the object isn't already in the list
530 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
533 assert("object already added to sector" == 0);
536 for(GameObjects::iterator i = gameobjects_new.begin();
537 i != gameobjects_new.end(); ++i) {
539 assert("object already added to sector" == 0);
545 gameobjects_new.push_back(object);
549 Sector::activate(const std::string& spawnpoint)
552 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
554 if((*i)->name == spawnpoint) {
560 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
561 if(spawnpoint != "main") {
564 activate(Vector(0, 0));
572 Sector::activate(const Vector& player_pos)
574 if(_current != this) {
576 _current->deactivate();
579 // register sectortable as sector in scripting
580 HSQUIRRELVM vm = Scripting::global_vm;
581 sq_pushroottable(vm);
582 sq_pushstring(vm, "sector", -1);
583 sq_pushobject(vm, sector_table);
584 if(SQ_FAILED(sq_createslot(vm, -3)))
585 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
588 for(GameObjects::iterator i = gameobjects.begin();
589 i != gameobjects.end(); ++i) {
590 GameObject* object = *i;
597 // spawn smalltux below spawnpoint
598 if (!player->is_big()) {
599 player->move(player_pos + Vector(0,32));
601 player->move(player_pos);
604 // spawning tux in the ground would kill him
605 if(!is_free_of_tiles(player->get_bbox())) {
606 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
607 Vector npos = player->get_bbox().p1;
612 camera->reset(player->get_pos());
613 update_game_objects();
616 if(init_script != "") {
617 std::istringstream in(init_script);
618 run_script(in, std::string("Sector(") + name + ") - init");
628 // remove sector entry from global vm
629 HSQUIRRELVM vm = Scripting::global_vm;
630 sq_pushroottable(vm);
631 sq_pushstring(vm, "sector", -1);
632 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
633 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
636 for(GameObjects::iterator i = gameobjects.begin();
637 i != gameobjects.end(); ++i) {
638 GameObject* object = *i;
640 try_unexpose(object);
648 Sector::get_active_region()
651 camera->get_translation() - Vector(1600, 1200),
652 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
656 Sector::update(float elapsed_time)
658 player->check_bounds(camera);
661 for(GameObjects::iterator i = gameobjects.begin();
662 i != gameobjects.end(); ++i) {
663 GameObject* object = *i;
664 if(!object->is_valid())
667 object->update(elapsed_time);
670 /* Handle all possible collisions. */
672 update_game_objects();
676 Sector::update_game_objects()
678 /** cleanup marked objects */
679 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
680 i != gameobjects.end(); /* nothing */) {
681 GameObject* object = *i;
683 if(object->is_valid()) {
688 before_object_remove(object);
691 i = gameobjects.erase(i);
694 /* add newly created objects */
695 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
696 i != gameobjects_new.end(); ++i)
698 GameObject* object = *i;
700 before_object_add(object);
702 gameobjects.push_back(object);
704 gameobjects_new.clear();
706 /* update solid_tilemaps list */
707 //FIXME: this could be more efficient
708 solid_tilemaps.clear();
709 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
710 i != gameobjects.end(); ++i)
712 TileMap* tm = dynamic_cast<TileMap*>(*i);
714 if (tm->is_solid()) solid_tilemaps.push_back(tm);
720 Sector::before_object_add(GameObject* object)
722 Bullet* bullet = dynamic_cast<Bullet*> (object);
724 bullets.push_back(bullet);
727 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
728 if(movingobject != NULL) {
729 moving_objects.push_back(movingobject);
732 Portable* portable = dynamic_cast<Portable*> (object);
733 if(portable != NULL) {
734 portables.push_back(portable);
737 TileMap* tilemap = dynamic_cast<TileMap*> (object);
738 if(tilemap != NULL && tilemap->is_solid()) {
739 solid_tilemaps.push_back(tilemap);
742 Camera* camera = dynamic_cast<Camera*> (object);
744 if(this->camera != 0) {
745 log_warning << "Multiple cameras added. Ignoring" << std::endl;
748 this->camera = camera;
751 Player* player = dynamic_cast<Player*> (object);
753 if(this->player != 0) {
754 log_warning << "Multiple players added. Ignoring" << std::endl;
757 this->player = player;
760 UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
763 physic_object->physic.set_gravity(gravity);
767 if(_current == this) {
775 Sector::try_expose(GameObject* object)
777 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
778 if(interface != NULL) {
779 HSQUIRRELVM vm = Scripting::global_vm;
780 sq_pushobject(vm, sector_table);
781 interface->expose(vm, -1);
787 Sector::try_expose_me()
789 HSQUIRRELVM vm = Scripting::global_vm;
790 sq_pushobject(vm, sector_table);
791 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
792 expose_object(vm, -1, interface, "settings", false);
797 Sector::before_object_remove(GameObject* object)
799 Portable* portable = dynamic_cast<Portable*> (object);
800 if(portable != NULL) {
801 portables.erase(std::find(portables.begin(), portables.end(), portable));
803 Bullet* bullet = dynamic_cast<Bullet*> (object);
805 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
807 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
808 if(moving_object != NULL) {
809 moving_objects.erase(
810 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
814 try_unexpose(object);
818 Sector::try_unexpose(GameObject* object)
820 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
821 if(interface != NULL) {
822 HSQUIRRELVM vm = Scripting::global_vm;
823 SQInteger oldtop = sq_gettop(vm);
824 sq_pushobject(vm, sector_table);
826 interface->unexpose(vm, -1);
827 } catch(std::exception& e) {
828 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
830 sq_settop(vm, oldtop);
835 Sector::try_unexpose_me()
837 HSQUIRRELVM vm = Scripting::global_vm;
838 SQInteger oldtop = sq_gettop(vm);
839 sq_pushobject(vm, sector_table);
841 Scripting::unexpose_object(vm, -1, "settings");
842 } catch(std::exception& e) {
843 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
845 sq_settop(vm, oldtop);
848 Sector::draw(DrawingContext& context)
850 context.set_ambient_color( ambient_light );
851 context.push_transform();
852 context.set_translation(camera->get_translation());
854 for(GameObjects::iterator i = gameobjects.begin();
855 i != gameobjects.end(); ++i) {
856 GameObject* object = *i;
857 if(!object->is_valid())
860 if (draw_solids_only)
862 TileMap* tm = dynamic_cast<TileMap*>(object);
863 if (tm && !tm->is_solid())
867 object->draw(context);
871 Color col(0.2f, 0.2f, 0.2f, 0.7f);
872 for(MovingObjects::iterator i = moving_objects.begin();
873 i != moving_objects.end(); ++i) {
874 MovingObject* object = *i;
875 const Rect& rect = object->get_bbox();
877 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
881 context.pop_transform();
884 /*-------------------------------------------------------------------------
885 * Collision Detection
886 *-------------------------------------------------------------------------*/
888 static const float SHIFT_DELTA = 7.0f;
890 /** r1 is supposed to be moving, r2 a solid object */
891 void check_collisions(collision::Constraints* constraints,
892 const Vector& movement, const Rect& r1, const Rect& r2,
893 GameObject* object = NULL, MovingObject* other = NULL)
895 if(!collision::intersects(r1, r2))
898 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
900 if(other != NULL && !other->collides(*object, dummy))
902 if(moving_object != NULL && !moving_object->collides(*other, dummy))
905 // calculate intersection
906 float itop = r1.get_bottom() - r2.get_top();
907 float ibottom = r2.get_bottom() - r1.get_top();
908 float ileft = r1.get_right() - r2.get_left();
909 float iright = r2.get_right() - r1.get_left();
911 if(fabsf(movement.y) > fabsf(movement.x)) {
912 if(ileft < SHIFT_DELTA) {
913 constraints->right = std::min(constraints->right, r2.get_left());
915 } else if(iright < SHIFT_DELTA) {
916 constraints->left = std::max(constraints->left, r2.get_right());
920 // shiftout bottom/top
921 if(itop < SHIFT_DELTA) {
922 constraints->bottom = std::min(constraints->bottom, r2.get_top());
924 } else if(ibottom < SHIFT_DELTA) {
925 constraints->top = std::max(constraints->top, r2.get_bottom());
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);
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);
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/salcon.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;