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 "file_system.hpp"
48 #include "physfs/physfs_stream.hpp"
49 #include "audio/sound_manager.hpp"
50 #include "game_session.hpp"
51 #include "resources.hpp"
52 #include "statistics.hpp"
53 #include "object_factory.hpp"
54 #include "collision.hpp"
55 #include "spawn_point.hpp"
56 #include "math/rect.hpp"
57 #include "math/aatriangle.hpp"
58 #include "object/coin.hpp"
59 #include "object/block.hpp"
60 #include "object/invisible_block.hpp"
61 #include "object/light.hpp"
62 #include "object/pulsing_light.hpp"
63 #include "object/bullet.hpp"
64 #include "object/text_object.hpp"
65 #include "object/portable.hpp"
66 #include "badguy/jumpy.hpp"
67 #include "trigger/sequence_trigger.hpp"
68 #include "player_status.hpp"
69 #include "scripting/squirrel_util.hpp"
70 #include "script_interface.hpp"
75 Sector* Sector::_current = 0;
77 bool Sector::show_collrects = false;
78 bool Sector::draw_solids_only = false;
80 Sector::Sector(Level* parent)
81 : level(parent), currentmusic(LEVEL_MUSIC),
82 ambient_light( 1.0f, 1.0f, 1.0f, 1.0f ), gravity(10.0), player(0), camera(0)
84 add_object(new Player(player_status, "Tux"));
85 add_object(new DisplayEffect("Effect"));
86 add_object(new TextObject("Text"));
88 sound_manager->preload("sounds/shoot.wav");
90 // create a new squirrel table for the sector
91 using namespace Scripting;
93 sq_collectgarbage(global_vm);
95 sq_newtable(global_vm);
96 sq_pushroottable(global_vm);
97 if(SQ_FAILED(sq_setdelegate(global_vm, -2)))
98 throw Scripting::SquirrelError(global_vm, "Couldn't set sector_table delegate");
100 sq_resetobject(§or_table);
101 if(SQ_FAILED(sq_getstackobj(global_vm, -1, §or_table)))
102 throw Scripting::SquirrelError(global_vm, "Couldn't get sector table");
103 sq_addref(global_vm, §or_table);
104 sq_pop(global_vm, 1);
109 using namespace Scripting;
113 for(ScriptList::iterator i = scripts.begin();
114 i != scripts.end(); ++i) {
115 HSQOBJECT& object = *i;
116 sq_release(global_vm, &object);
118 sq_release(global_vm, §or_table);
119 sq_collectgarbage(global_vm);
121 update_game_objects();
122 assert(gameobjects_new.size() == 0);
124 for(GameObjects::iterator i = gameobjects.begin();
125 i != gameobjects.end(); ++i) {
126 GameObject* object = *i;
127 before_object_remove(object);
131 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
143 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
145 if(name == "camera") {
146 Camera* camera = new Camera(this, "Camera");
147 camera->parse(reader);
149 } else if(name == "particles-snow") {
150 SnowParticleSystem* partsys = new SnowParticleSystem();
151 partsys->parse(reader);
153 } else if(name == "particles-rain") {
154 RainParticleSystem* partsys = new RainParticleSystem();
155 partsys->parse(reader);
157 } else if(name == "particles-comets") {
158 CometParticleSystem* partsys = new CometParticleSystem();
159 partsys->parse(reader);
161 } else if(name == "particles-ghosts") {
162 GhostParticleSystem* partsys = new GhostParticleSystem();
163 partsys->parse(reader);
165 } else if(name == "particles-clouds") {
166 CloudParticleSystem* partsys = new CloudParticleSystem();
167 partsys->parse(reader);
169 } else if(name == "money") { // for compatibility with old maps
170 return new Jumpy(reader);
174 return create_object(name, reader);
175 } catch(std::exception& e) {
176 log_warning << e.what() << "" << std::endl;
183 Sector::parse(const lisp::Lisp& sector)
185 bool has_background = false;
186 lisp::ListIterator iter(§or);
188 const std::string& token = iter.item();
189 if(token == "name") {
190 iter.value()->get(name);
191 } else if(token == "gravity") {
192 iter.value()->get(gravity);
193 } else if(token == "music") {
194 iter.value()->get(music);
195 } else if(token == "spawnpoint") {
196 SpawnPoint* sp = new SpawnPoint(iter.lisp());
197 spawnpoints.push_back(sp);
198 } else if(token == "init-script") {
199 iter.value()->get(init_script);
200 } else if(token == "ambient-light") {
201 std::vector<float> vColor;
202 sector.get_vector( "ambient-light", vColor );
203 if(vColor.size() < 3) {
204 log_warning << "(ambient-light) requires a color as argument" << std::endl;
206 ambient_light = Color( vColor );
209 GameObject* object = parse_object(token, *(iter.lisp()));
211 if(dynamic_cast<Background *>(object)) {
212 has_background = true;
213 } else if(dynamic_cast<Gradient *>(object)) {
214 has_background = true;
221 if(!has_background) {
222 Gradient* gradient = new Gradient();
223 gradient->set_gradient(Color(0.3, 0.4, 0.75), Color(1, 1, 1));
224 add_object(gradient);
227 update_game_objects();
229 if(solid_tilemaps.size() < 1) log_warning << "sector '" << name << "' does not contain a solid tile layer." << std::endl;
233 log_warning << "sector '" << name << "' does not contain a camera." << std::endl;
234 update_game_objects();
235 add_object(new Camera(this, "Camera"));
238 update_game_objects();
242 Sector::parse_old_format(const lisp::Lisp& reader)
245 reader.get("gravity", gravity);
247 std::string backgroundimage;
248 if (reader.get("background", backgroundimage) && (backgroundimage != "")) {
249 if (backgroundimage == "arctis.png") backgroundimage = "arctis.jpg";
250 if (backgroundimage == "arctis2.jpg") backgroundimage = "arctis.jpg";
251 if (backgroundimage == "ocean.png") backgroundimage = "ocean.jpg";
252 backgroundimage = "images/background/" + backgroundimage;
253 if (!PHYSFS_exists(backgroundimage.c_str())) {
254 log_warning << "Background image \"" << backgroundimage << "\" not found. Ignoring." << std::endl;
255 backgroundimage = "";
260 reader.get("bkgd_speed", bgspeed);
263 Color bkgd_top, bkgd_bottom;
264 int r = 0, g = 0, b = 128;
265 reader.get("bkgd_red_top", r);
266 reader.get("bkgd_green_top", g);
267 reader.get("bkgd_blue_top", b);
268 bkgd_top.red = static_cast<float> (r) / 255.0f;
269 bkgd_top.green = static_cast<float> (g) / 255.0f;
270 bkgd_top.blue = static_cast<float> (b) / 255.0f;
272 reader.get("bkgd_red_bottom", r);
273 reader.get("bkgd_green_bottom", g);
274 reader.get("bkgd_blue_bottom", b);
275 bkgd_bottom.red = static_cast<float> (r) / 255.0f;
276 bkgd_bottom.green = static_cast<float> (g) / 255.0f;
277 bkgd_bottom.blue = static_cast<float> (b) / 255.0f;
279 if(backgroundimage != "") {
280 Background* background = new Background();
281 background->set_image(backgroundimage, bgspeed);
282 add_object(background);
284 Gradient* gradient = new Gradient();
285 gradient->set_gradient(bkgd_top, bkgd_bottom);
286 add_object(gradient);
289 std::string particlesystem;
290 reader.get("particle_system", particlesystem);
291 if(particlesystem == "clouds")
292 add_object(new CloudParticleSystem());
293 else if(particlesystem == "snow")
294 add_object(new SnowParticleSystem());
295 else if(particlesystem == "rain")
296 add_object(new RainParticleSystem());
298 Vector startpos(100, 170);
299 reader.get("start_pos_x", startpos.x);
300 reader.get("start_pos_y", startpos.y);
302 SpawnPoint* spawn = new SpawnPoint;
303 spawn->pos = startpos;
304 spawn->name = "main";
305 spawnpoints.push_back(spawn);
307 music = "chipdisko.ogg";
308 // skip reading music filename. It's all .ogg now, anyway
310 reader.get("music", music);
312 music = "music/" + music;
314 int width = 30, height = 15;
315 reader.get("width", width);
316 reader.get("height", height);
318 std::vector<unsigned int> tiles;
319 if(reader.get_vector("interactive-tm", tiles)
320 || reader.get_vector("tilemap", tiles)) {
321 TileMap* tilemap = new TileMap(level->get_tileset());
322 tilemap->set(width, height, tiles, LAYER_TILES, true);
324 // replace tile id 112 (old invisible tile) with 1311 (new invisible tile)
325 for(size_t x=0; x < tilemap->get_width(); ++x) {
326 for(size_t y=0; y < tilemap->get_height(); ++y) {
327 uint32_t id = tilemap->get_tile_id(x, y);
329 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(level->get_tileset());
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(level->get_tileset());
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 uint32_t id = solids->get_tile_id(x, y);
408 const Tile *tile = solids->get_tile(x, y);
409 Vector pos(solids->get_x_offset() + x*32, solids->get_y_offset() + y*32);
412 add_object(new InvisibleBlock(pos));
413 solids->change(x, y, 0);
414 } else if(tile->getAttributes() & Tile::COIN) {
415 add_object(new Coin(pos));
416 solids->change(x, y, 0);
417 } else if(tile->getAttributes() & Tile::FULLBOX) {
418 add_object(new BonusBlock(pos, tile->getData()));
419 solids->change(x, y, 0);
420 } else if(tile->getAttributes() & Tile::BRICK) {
421 add_object(new Brick(pos, tile->getData()));
422 solids->change(x, y, 0);
423 } else if(tile->getAttributes() & Tile::GOAL) {
424 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
425 add_object(new SequenceTrigger(pos, sequence));
426 solids->change(x, y, 0);
432 // add lights for special tiles
433 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); i++) {
434 TileMap* tm = dynamic_cast<TileMap*>(*i);
436 for(size_t x=0; x < tm->get_width(); ++x) {
437 for(size_t y=0; y < tm->get_height(); ++y) {
438 uint32_t id = tm->get_tile_id(x, y);
439 Vector pos(tm->get_x_offset() + x*32, tm->get_y_offset() + y*32);
440 Vector center(pos.x + 16, pos.y + 16);
444 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
445 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.9f, 1.0f, Color(1.0f, 1.0f, 0.6f, 1.0f)));
448 if ((id == 173) || (id == 1700) || (id == 1705) || (id == 1706)) {
449 // space lights a bit
450 if ((((tm->get_tile_id(x-1, y)) != tm->get_tile_id(x,y))
451 && (tm->get_tile_id(x, y-1) != tm->get_tile_id(x,y)))
452 || ((x % 3 == 0) && (y % 3 == 0))) {
453 float pseudo_rnd = (float)((int)pos.x % 10) / 10;
454 add_object(new PulsingLight(center, 1.0f + pseudo_rnd, 0.8f, 1.0f, Color(1.0f, 0.3f, 0.0f, 1.0f)));
466 Sector::write(lisp::Writer& writer)
468 writer.write_string("name", name);
469 writer.write_float("gravity", gravity);
470 writer.write_string("music", music);
473 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
475 SpawnPoint* spawn = *i;
476 writer.start_list("spawn-points");
477 writer.write_string("name", spawn->name);
478 writer.write_float("x", spawn->pos.x);
479 writer.write_float("y", spawn->pos.y);
480 writer.end_list("spawn-points");
484 for(GameObjects::iterator i = gameobjects.begin();
485 i != gameobjects.end(); ++i) {
486 Serializable* serializable = dynamic_cast<Serializable*> (*i);
488 serializable->write(writer);
493 Sector::run_script(std::istream& in, const std::string& sourcename)
495 using namespace Scripting;
497 // garbage collect thread list
498 for(ScriptList::iterator i = scripts.begin();
499 i != scripts.end(); ) {
500 HSQOBJECT& object = *i;
501 HSQUIRRELVM vm = object_to_vm(object);
503 if(sq_getvmstate(vm) != SQ_VMSTATE_SUSPENDED) {
504 sq_release(global_vm, &object);
505 i = scripts.erase(i);
512 HSQOBJECT object = create_thread(global_vm);
513 scripts.push_back(object);
515 HSQUIRRELVM vm = object_to_vm(object);
517 // set sector_table as roottable for the thread
518 sq_pushobject(vm, sector_table);
521 compile_and_run(vm, in, sourcename);
527 Sector::add_object(GameObject* object)
529 // make sure the object isn't already in the list
531 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
534 assert("object already added to sector" == 0);
537 for(GameObjects::iterator i = gameobjects_new.begin();
538 i != gameobjects_new.end(); ++i) {
540 assert("object already added to sector" == 0);
546 gameobjects_new.push_back(object);
550 Sector::activate(const std::string& spawnpoint)
553 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
555 if((*i)->name == spawnpoint) {
561 log_warning << "Spawnpoint '" << spawnpoint << "' not found." << std::endl;
562 if(spawnpoint != "main") {
565 activate(Vector(0, 0));
573 Sector::activate(const Vector& player_pos)
575 if(_current != this) {
577 _current->deactivate();
580 // register sectortable as sector in scripting
581 HSQUIRRELVM vm = Scripting::global_vm;
582 sq_pushroottable(vm);
583 sq_pushstring(vm, "sector", -1);
584 sq_pushobject(vm, sector_table);
585 if(SQ_FAILED(sq_createslot(vm, -3)))
586 throw Scripting::SquirrelError(vm, "Couldn't set sector in roottable");
589 for(GameObjects::iterator i = gameobjects.begin();
590 i != gameobjects.end(); ++i) {
591 GameObject* object = *i;
598 // spawn smalltux below spawnpoint
599 if (!player->is_big()) {
600 player->move(player_pos + Vector(0,32));
602 player->move(player_pos);
605 // spawning tux in the ground would kill him
606 if(!is_free_of_tiles(player->get_bbox())) {
607 log_warning << "Tried spawning Tux in solid matter. Compensating." << std::endl;
608 Vector npos = player->get_bbox().p1;
613 camera->reset(player->get_pos());
614 update_game_objects();
616 //Run default.nut just before init script
617 //Check to see if it's in a levelset (info file)
618 std::string basedir = FileSystem::dirname(get_level()->filename);
619 if(PHYSFS_exists((basedir + "/info").c_str())) {
621 IFileStream in(basedir + "/default.nut");
622 run_script(in, std::string("Sector(") + name + ") - default.nut");
623 } catch(std::exception& ) {
624 // doesn't exist or erroneous; do nothing
629 if(init_script != "") {
630 std::istringstream in(init_script);
631 run_script(in, std::string("Sector(") + name + ") - init");
641 // remove sector entry from global vm
642 HSQUIRRELVM vm = Scripting::global_vm;
643 sq_pushroottable(vm);
644 sq_pushstring(vm, "sector", -1);
645 if(SQ_FAILED(sq_deleteslot(vm, -2, SQFalse)))
646 throw Scripting::SquirrelError(vm, "Couldn't unset sector in roottable");
649 for(GameObjects::iterator i = gameobjects.begin();
650 i != gameobjects.end(); ++i) {
651 GameObject* object = *i;
653 try_unexpose(object);
661 Sector::get_active_region()
664 camera->get_translation() - Vector(1600, 1200),
665 camera->get_translation() + Vector(1600, 1200) + Vector(SCREEN_WIDTH,SCREEN_HEIGHT));
669 Sector::update(float elapsed_time)
671 player->check_bounds(camera);
674 for(GameObjects::iterator i = gameobjects.begin();
675 i != gameobjects.end(); ++i) {
676 GameObject* object = *i;
677 if(!object->is_valid())
680 object->update(elapsed_time);
683 /* Handle all possible collisions. */
685 update_game_objects();
689 Sector::update_game_objects()
691 /** cleanup marked objects */
692 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
693 i != gameobjects.end(); /* nothing */) {
694 GameObject* object = *i;
696 if(object->is_valid()) {
701 before_object_remove(object);
704 i = gameobjects.erase(i);
707 /* add newly created objects */
708 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
709 i != gameobjects_new.end(); ++i)
711 GameObject* object = *i;
713 before_object_add(object);
715 gameobjects.push_back(object);
717 gameobjects_new.clear();
719 /* update solid_tilemaps list */
720 //FIXME: this could be more efficient
721 solid_tilemaps.clear();
722 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
723 i != gameobjects.end(); ++i)
725 TileMap* tm = dynamic_cast<TileMap*>(*i);
727 if (tm->is_solid()) solid_tilemaps.push_back(tm);
733 Sector::before_object_add(GameObject* object)
735 Bullet* bullet = dynamic_cast<Bullet*> (object);
737 bullets.push_back(bullet);
740 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
741 if(movingobject != NULL) {
742 moving_objects.push_back(movingobject);
745 Portable* portable = dynamic_cast<Portable*> (object);
746 if(portable != NULL) {
747 portables.push_back(portable);
750 TileMap* tilemap = dynamic_cast<TileMap*> (object);
751 if(tilemap != NULL && tilemap->is_solid()) {
752 solid_tilemaps.push_back(tilemap);
755 Camera* camera = dynamic_cast<Camera*> (object);
757 if(this->camera != 0) {
758 log_warning << "Multiple cameras added. Ignoring" << std::endl;
761 this->camera = camera;
764 Player* player = dynamic_cast<Player*> (object);
766 if(this->player != 0) {
767 log_warning << "Multiple players added. Ignoring" << std::endl;
770 this->player = player;
773 UsesPhysic *physic_object = dynamic_cast<UsesPhysic *>(object);
776 physic_object->physic.set_gravity(gravity);
780 if(_current == this) {
788 Sector::try_expose(GameObject* object)
790 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
791 if(interface != NULL) {
792 HSQUIRRELVM vm = Scripting::global_vm;
793 sq_pushobject(vm, sector_table);
794 interface->expose(vm, -1);
800 Sector::try_expose_me()
802 HSQUIRRELVM vm = Scripting::global_vm;
803 sq_pushobject(vm, sector_table);
804 Scripting::SSector* interface = static_cast<Scripting::SSector*> (this);
805 expose_object(vm, -1, interface, "settings", false);
810 Sector::before_object_remove(GameObject* object)
812 Portable* portable = dynamic_cast<Portable*> (object);
813 if(portable != NULL) {
814 portables.erase(std::find(portables.begin(), portables.end(), portable));
816 Bullet* bullet = dynamic_cast<Bullet*> (object);
818 bullets.erase(std::find(bullets.begin(), bullets.end(), bullet));
820 MovingObject* moving_object = dynamic_cast<MovingObject*> (object);
821 if(moving_object != NULL) {
822 moving_objects.erase(
823 std::find(moving_objects.begin(), moving_objects.end(), moving_object));
827 try_unexpose(object);
831 Sector::try_unexpose(GameObject* object)
833 ScriptInterface* interface = dynamic_cast<ScriptInterface*> (object);
834 if(interface != NULL) {
835 HSQUIRRELVM vm = Scripting::global_vm;
836 SQInteger oldtop = sq_gettop(vm);
837 sq_pushobject(vm, sector_table);
839 interface->unexpose(vm, -1);
840 } catch(std::exception& e) {
841 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
843 sq_settop(vm, oldtop);
848 Sector::try_unexpose_me()
850 HSQUIRRELVM vm = Scripting::global_vm;
851 SQInteger oldtop = sq_gettop(vm);
852 sq_pushobject(vm, sector_table);
854 Scripting::unexpose_object(vm, -1, "settings");
855 } catch(std::exception& e) {
856 log_warning << "Couldn't unregister object: " << e.what() << std::endl;
858 sq_settop(vm, oldtop);
861 Sector::draw(DrawingContext& context)
863 context.set_ambient_color( ambient_light );
864 context.push_transform();
865 context.set_translation(camera->get_translation());
867 for(GameObjects::iterator i = gameobjects.begin();
868 i != gameobjects.end(); ++i) {
869 GameObject* object = *i;
870 if(!object->is_valid())
873 if (draw_solids_only)
875 TileMap* tm = dynamic_cast<TileMap*>(object);
876 if (tm && !tm->is_solid())
880 object->draw(context);
884 Color col(0.2f, 0.2f, 0.2f, 0.7f);
885 for(MovingObjects::iterator i = moving_objects.begin();
886 i != moving_objects.end(); ++i) {
887 MovingObject* object = *i;
888 const Rect& rect = object->get_bbox();
890 context.draw_filled_rect(rect, col, LAYER_FOREGROUND1 + 10);
894 context.pop_transform();
897 /*-------------------------------------------------------------------------
898 * Collision Detection
899 *-------------------------------------------------------------------------*/
901 static const float SHIFT_DELTA = 7.0f;
903 /** r1 is supposed to be moving, r2 a solid object */
904 void check_collisions(collision::Constraints* constraints,
905 const Vector& movement, const Rect& r1, const Rect& r2,
906 GameObject* object = NULL, MovingObject* other = NULL, const Vector& addl_ground_movement = Vector(0,0))
908 if(!collision::intersects(r1, r2))
911 MovingObject *moving_object = dynamic_cast<MovingObject*> (object);
913 if(other != NULL && !other->collides(*object, dummy))
915 if(moving_object != NULL && !moving_object->collides(*other, dummy))
918 // calculate intersection
919 float itop = r1.get_bottom() - r2.get_top();
920 float ibottom = r2.get_bottom() - r1.get_top();
921 float ileft = r1.get_right() - r2.get_left();
922 float iright = r2.get_right() - r1.get_left();
924 if(fabsf(movement.y) > fabsf(movement.x)) {
925 if(ileft < SHIFT_DELTA) {
926 constraints->right = std::min(constraints->right, r2.get_left());
928 } else if(iright < SHIFT_DELTA) {
929 constraints->left = std::max(constraints->left, r2.get_right());
933 // shiftout bottom/top
934 if(itop < SHIFT_DELTA) {
935 constraints->bottom = std::min(constraints->bottom, r2.get_top());
937 } else if(ibottom < SHIFT_DELTA) {
938 constraints->top = std::max(constraints->top, r2.get_bottom());
943 constraints->ground_movement += addl_ground_movement;
945 HitResponse response = other->collision(*object, dummy);
946 if(response == PASSTHROUGH)
949 if(other->get_movement() != Vector(0, 0)) {
950 // TODO what todo when we collide with 2 moving objects?!?
951 constraints->ground_movement += other->get_movement();
955 float vert_penetration = std::min(itop, ibottom);
956 float horiz_penetration = std::min(ileft, iright);
957 if(vert_penetration < horiz_penetration) {
959 constraints->bottom = std::min(constraints->bottom, r2.get_top());
960 constraints->hit.bottom = true;
962 constraints->top = std::max(constraints->top, r2.get_bottom());
963 constraints->hit.top = true;
967 constraints->right = std::min(constraints->right, r2.get_left());
968 constraints->hit.right = true;
970 constraints->left = std::max(constraints->left, r2.get_right());
971 constraints->hit.left = true;
977 Sector::collision_tilemap(collision::Constraints* constraints,
978 const Vector& movement, const Rect& dest) const
980 // calculate rectangle where the object will move
981 float x1 = dest.get_left();
982 float x2 = dest.get_right();
983 float y1 = dest.get_top();
984 float y2 = dest.get_bottom();
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 // skip non-solid tiles
1001 if((tile->getAttributes() & Tile::SOLID) == 0)
1003 // only handle unisolid when the player is falling down and when he was
1004 // above the tile before
1005 if(tile->getAttributes() & Tile::UNISOLID) {
1006 if(movement.y <= 0 || dest.get_bottom() - movement.y - SHIFT_DELTA > y*32)
1010 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
1011 AATriangle triangle;
1012 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1013 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1014 triangle = AATriangle(p1, p2, tile->getData());
1016 collision::rectangle_aatriangle(constraints, dest, triangle, solids->get_movement());
1017 } else { // normal rectangular tile
1018 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());
1019 check_collisions(constraints, movement, dest, rect, NULL, NULL, solids->get_movement());
1027 Sector::collision_tile_attributes(const Rect& dest) const
1029 float x1 = dest.p1.x;
1030 float y1 = dest.p1.y;
1031 float x2 = dest.p2.x;
1032 float y2 = dest.p2.y;
1034 uint32_t result = 0;
1035 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1036 TileMap* solids = *i;
1038 // test with all tiles in this rectangle
1039 int starttilex = int(x1 - solids->get_x_offset()) / 32;
1040 int starttiley = int(y1 - solids->get_y_offset()) / 32;
1041 int max_x = int(x2 - solids->get_x_offset());
1042 int max_y = int(y2+1 - solids->get_y_offset());
1044 for(int x = starttilex; x*32 < max_x; ++x) {
1045 for(int y = starttiley; y*32 < max_y; ++y) {
1046 const Tile* tile = solids->get_tile(x, y);
1049 result |= tile->getAttributes();
1057 /** fills in CollisionHit and Normal vector of 2 intersecting rectangle */
1058 static void get_hit_normal(const Rect& r1, const Rect& r2, CollisionHit& hit,
1061 float itop = r1.get_bottom() - r2.get_top();
1062 float ibottom = r2.get_bottom() - r1.get_top();
1063 float ileft = r1.get_right() - r2.get_left();
1064 float iright = r2.get_right() - r1.get_left();
1066 float vert_penetration = std::min(itop, ibottom);
1067 float horiz_penetration = std::min(ileft, iright);
1068 if(vert_penetration < horiz_penetration) {
1069 if(itop < ibottom) {
1071 normal.y = vert_penetration;
1074 normal.y = -vert_penetration;
1077 if(ileft < iright) {
1079 normal.x = horiz_penetration;
1082 normal.x = -horiz_penetration;
1088 Sector::collision_object(MovingObject* object1, MovingObject* object2) const
1090 using namespace collision;
1092 const Rect& r1 = object1->dest;
1093 const Rect& r2 = object2->dest;
1096 if(intersects(object1->dest, object2->dest)) {
1098 get_hit_normal(r1, r2, hit, normal);
1100 if(!object1->collides(*object2, hit))
1102 std::swap(hit.left, hit.right);
1103 std::swap(hit.top, hit.bottom);
1104 if(!object2->collides(*object1, hit))
1106 std::swap(hit.left, hit.right);
1107 std::swap(hit.top, hit.bottom);
1109 HitResponse response1 = object1->collision(*object2, hit);
1110 std::swap(hit.left, hit.right);
1111 std::swap(hit.top, hit.bottom);
1112 HitResponse response2 = object2->collision(*object1, hit);
1113 if(response1 == CONTINUE && response2 == CONTINUE) {
1114 normal *= (0.5 + DELTA);
1115 object1->dest.move(-normal);
1116 object2->dest.move(normal);
1117 } else if (response1 == CONTINUE && response2 == FORCE_MOVE) {
1118 normal *= (1 + DELTA);
1119 object1->dest.move(-normal);
1120 } else if (response1 == FORCE_MOVE && response2 == CONTINUE) {
1121 normal *= (1 + DELTA);
1122 object2->dest.move(normal);
1128 Sector::collision_static(collision::Constraints* constraints,
1129 const Vector& movement, const Rect& dest,
1132 collision_tilemap(constraints, movement, dest);
1134 // collision with other (static) objects
1135 for(MovingObjects::iterator i = moving_objects.begin();
1136 i != moving_objects.end(); ++i) {
1137 MovingObject* moving_object = *i;
1138 if(moving_object->get_group() != COLGROUP_STATIC
1139 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1141 if(!moving_object->is_valid())
1144 if(moving_object != &object)
1145 check_collisions(constraints, movement, dest, moving_object->bbox,
1146 &object, moving_object);
1151 Sector::collision_static_constrains(MovingObject& object)
1153 using namespace collision;
1154 float infinity = (std::numeric_limits<float>::has_infinity ? std::numeric_limits<float>::infinity() : std::numeric_limits<float>::max());
1156 Constraints constraints;
1157 Vector movement = object.get_movement();
1158 Rect& dest = object.dest;
1159 float owidth = object.get_bbox().get_width();
1160 float oheight = object.get_bbox().get_height();
1162 for(int i = 0; i < 2; ++i) {
1163 collision_static(&constraints, Vector(0, movement.y), dest, object);
1164 if(!constraints.has_constraints())
1167 // apply calculated horizontal constraints
1168 if(constraints.bottom < infinity) {
1169 float height = constraints.bottom - constraints.top;
1170 if(height < oheight) {
1171 // we're crushed, but ignore this for now, we'll get this again
1172 // later if we're really crushed or things will solve itself when
1173 // looking at the vertical constraints
1175 dest.p2.y = constraints.bottom - DELTA;
1176 dest.p1.y = dest.p2.y - oheight;
1177 } else if(constraints.top > -infinity) {
1178 dest.p1.y = constraints.top + DELTA;
1179 dest.p2.y = dest.p1.y + oheight;
1182 if(constraints.has_constraints()) {
1183 if(constraints.hit.bottom) {
1184 dest.move(constraints.ground_movement);
1186 if(constraints.hit.top || constraints.hit.bottom) {
1187 constraints.hit.left = false;
1188 constraints.hit.right = false;
1189 object.collision_solid(constraints.hit);
1193 constraints = Constraints();
1194 for(int i = 0; i < 2; ++i) {
1195 collision_static(&constraints, movement, dest, object);
1196 if(!constraints.has_constraints())
1199 // apply calculated vertical constraints
1200 if(constraints.right < infinity) {
1201 float width = constraints.right - constraints.left;
1202 if(width + SHIFT_DELTA < owidth) {
1204 printf("Object %p crushed horizontally... L:%f R:%f\n", &object,
1205 constraints.left, constraints.right);
1211 object.collision_solid(h);
1213 dest.p2.x = constraints.right - DELTA;
1214 dest.p1.x = dest.p2.x - owidth;
1216 } else if(constraints.left > -infinity) {
1217 dest.p1.x = constraints.left + DELTA;
1218 dest.p2.x = dest.p1.x + owidth;
1222 if(constraints.has_constraints()) {
1223 if( constraints.hit.left || constraints.hit.right
1224 || constraints.hit.top || constraints.hit.bottom
1225 || constraints.hit.crush )
1226 object.collision_solid(constraints.hit);
1229 // an extra pass to make sure we're not crushed horizontally
1230 constraints = Constraints();
1231 collision_static(&constraints, movement, dest, object);
1232 if(constraints.bottom < infinity) {
1233 float height = constraints.bottom - constraints.top;
1234 if(height + SHIFT_DELTA < oheight) {
1236 printf("Object %p crushed vertically...\n", &object);
1242 object.collision_solid(h);
1248 const float MAX_SPEED = 16.0f;
1252 Sector::handle_collisions()
1254 using namespace collision;
1256 // calculate destination positions of the objects
1257 for(MovingObjects::iterator i = moving_objects.begin();
1258 i != moving_objects.end(); ++i) {
1259 MovingObject* moving_object = *i;
1260 Vector mov = moving_object->get_movement();
1262 // make sure movement is never faster than MAX_SPEED. Norm is pretty fat, so two addl. checks are done before.
1263 if (((mov.x > MAX_SPEED * M_SQRT1_2) || (mov.y > MAX_SPEED * M_SQRT1_2)) && (mov.norm() > MAX_SPEED)) {
1264 moving_object->movement = mov.unit() * MAX_SPEED;
1265 //log_debug << "Temporarily reduced object's speed of " << mov.norm() << " to " << moving_object->movement.norm() << "." << std::endl;
1268 moving_object->dest = moving_object->get_bbox();
1269 moving_object->dest.move(moving_object->get_movement());
1272 // part1: COLGROUP_MOVING vs COLGROUP_STATIC and tilemap
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 collision_static_constrains(*moving_object);
1286 // part2: COLGROUP_MOVING vs tile attributes
1287 for(MovingObjects::iterator i = moving_objects.begin();
1288 i != moving_objects.end(); ++i) {
1289 MovingObject* moving_object = *i;
1290 if((moving_object->get_group() != COLGROUP_MOVING
1291 && moving_object->get_group() != COLGROUP_MOVING_STATIC
1292 && moving_object->get_group() != COLGROUP_MOVING_ONLY_STATIC)
1293 || !moving_object->is_valid())
1296 uint32_t tile_attributes = collision_tile_attributes(moving_object->dest);
1297 if(tile_attributes > Tile::FIRST_INTERESTING_FLAG) {
1298 moving_object->collision_tile(tile_attributes);
1302 // part2.5: COLGROUP_MOVING vs COLGROUP_TOUCHABLE
1303 for(MovingObjects::iterator i = moving_objects.begin();
1304 i != moving_objects.end(); ++i) {
1305 MovingObject* moving_object = *i;
1306 if((moving_object->get_group() != COLGROUP_MOVING
1307 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1308 || !moving_object->is_valid())
1311 for(MovingObjects::iterator i2 = moving_objects.begin();
1312 i2 != moving_objects.end(); ++i2) {
1313 MovingObject* moving_object_2 = *i2;
1314 if(moving_object_2->get_group() != COLGROUP_TOUCHABLE
1315 || !moving_object_2->is_valid())
1318 if(intersects(moving_object->dest, moving_object_2->dest)) {
1321 get_hit_normal(moving_object->dest, moving_object_2->dest,
1323 if(!moving_object->collides(*moving_object_2, hit))
1325 if(!moving_object_2->collides(*moving_object, hit))
1328 moving_object->collision(*moving_object_2, hit);
1329 moving_object_2->collision(*moving_object, hit);
1334 // part3: COLGROUP_MOVING vs COLGROUP_MOVING
1335 for(MovingObjects::iterator i = moving_objects.begin();
1336 i != moving_objects.end(); ++i) {
1337 MovingObject* moving_object = *i;
1339 if((moving_object->get_group() != COLGROUP_MOVING
1340 && moving_object->get_group() != COLGROUP_MOVING_STATIC)
1341 || !moving_object->is_valid())
1344 for(MovingObjects::iterator i2 = i+1;
1345 i2 != moving_objects.end(); ++i2) {
1346 MovingObject* moving_object_2 = *i2;
1347 if((moving_object_2->get_group() != COLGROUP_MOVING
1348 && moving_object_2->get_group() != COLGROUP_MOVING_STATIC)
1349 || !moving_object_2->is_valid())
1352 collision_object(moving_object, moving_object_2);
1356 // apply object movement
1357 for(MovingObjects::iterator i = moving_objects.begin();
1358 i != moving_objects.end(); ++i) {
1359 MovingObject* moving_object = *i;
1361 moving_object->bbox = moving_object->dest;
1362 moving_object->movement = Vector(0, 0);
1367 Sector::is_free_of_tiles(const Rect& rect, const bool ignoreUnisolid) const
1369 using namespace collision;
1371 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1372 TileMap* solids = *i;
1374 // test with all tiles in this rectangle
1375 int starttilex = int(rect.p1.x - solids->get_x_offset()) / 32;
1376 int starttiley = int(rect.p1.y - solids->get_y_offset()) / 32;
1377 int max_x = int(rect.p2.x - solids->get_x_offset());
1378 int max_y = int(rect.p2.y - solids->get_y_offset());
1380 for(int x = starttilex; x*32 <= max_x; ++x) {
1381 for(int y = starttiley; y*32 <= max_y; ++y) {
1382 const Tile* tile = solids->get_tile(x, y);
1384 if(tile->getAttributes() & Tile::SLOPE) {
1385 AATriangle triangle;
1386 Vector p1(x*32 + solids->get_x_offset(), y*32 + solids->get_y_offset());
1387 Vector p2((x+1)*32 + solids->get_x_offset(), (y+1)*32 + solids->get_y_offset());
1388 triangle = AATriangle(p1, p2, tile->getData());
1389 Constraints constraints;
1390 return collision::rectangle_aatriangle(&constraints, rect, triangle);
1392 if((tile->getAttributes() & Tile::SOLID) && !ignoreUnisolid) return false;
1393 if((tile->getAttributes() & Tile::SOLID) && !(tile->getAttributes() & Tile::UNISOLID)) return false;
1402 Sector::is_free_of_statics(const Rect& rect, const MovingObject* ignore_object, const bool ignoreUnisolid) const
1404 using namespace collision;
1406 if (!is_free_of_tiles(rect, ignoreUnisolid)) return false;
1408 for(MovingObjects::const_iterator i = moving_objects.begin();
1409 i != moving_objects.end(); ++i) {
1410 const MovingObject* moving_object = *i;
1411 if (moving_object == ignore_object) continue;
1412 if (!moving_object->is_valid()) continue;
1413 if (moving_object->get_group() == COLGROUP_STATIC) {
1414 if(intersects(rect, moving_object->get_bbox())) return false;
1422 Sector::is_free_of_movingstatics(const Rect& rect, const MovingObject* ignore_object) const
1424 using namespace collision;
1426 if (!is_free_of_tiles(rect)) return false;
1428 for(MovingObjects::const_iterator i = moving_objects.begin();
1429 i != moving_objects.end(); ++i) {
1430 const MovingObject* moving_object = *i;
1431 if (moving_object == ignore_object) continue;
1432 if (!moving_object->is_valid()) continue;
1433 if ((moving_object->get_group() == COLGROUP_MOVING)
1434 || (moving_object->get_group() == COLGROUP_MOVING_STATIC)
1435 || (moving_object->get_group() == COLGROUP_STATIC)) {
1436 if(intersects(rect, moving_object->get_bbox())) return false;
1444 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
1446 // TODO remove this function and move these checks elsewhere...
1448 Bullet* new_bullet = 0;
1449 if((player_status->bonus == FIRE_BONUS &&
1450 (int)bullets.size() >= player_status->max_fire_bullets) ||
1451 (player_status->bonus == ICE_BONUS &&
1452 (int)bullets.size() >= player_status->max_ice_bullets))
1454 new_bullet = new Bullet(pos, xm, dir, player_status->bonus);
1455 add_object(new_bullet);
1457 sound_manager->play("sounds/shoot.wav");
1463 Sector::add_smoke_cloud(const Vector& pos)
1465 add_object(new SmokeCloud(pos));
1470 Sector::play_music(MusicType type)
1472 currentmusic = type;
1473 switch(currentmusic) {
1475 sound_manager->play_music(music);
1478 sound_manager->play_music("music/invincible.ogg");
1480 case HERRING_WARNING_MUSIC:
1481 sound_manager->stop_music(TUX_INVINCIBLE_TIME_WARNING);
1484 sound_manager->play_music("");
1490 Sector::get_music_type()
1492 return currentmusic;
1496 Sector::get_total_badguys()
1498 int total_badguys = 0;
1499 for(GameObjects::iterator i = gameobjects.begin();
1500 i != gameobjects.end(); ++i) {
1501 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
1502 if (badguy && badguy->countMe)
1506 return total_badguys;
1510 Sector::inside(const Rect& rect) const
1512 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1513 TileMap* solids = *i;
1514 bool horizontally = ((rect.p2.x >= 0 + solids->get_x_offset()) && (rect.p1.x <= solids->get_width() * 32 + solids->get_x_offset()));
1515 bool vertically = (rect.p1.y <= solids->get_height() * 32 + solids->get_y_offset());
1517 if (horizontally && vertically)
1524 Sector::get_width() const
1527 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1528 i != solid_tilemaps.end(); i++) {
1529 TileMap* solids = *i;
1530 if ((solids->get_width() * 32 + solids->get_x_offset()) > width) {
1531 width = solids->get_width() * 32 + solids->get_x_offset();
1539 Sector::get_height() const
1542 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin();
1543 i != solid_tilemaps.end(); i++) {
1544 TileMap* solids = *i;
1545 if ((solids->get_height() * 32 + solids->get_y_offset()) > height) {
1546 height = solids->get_height() * 32 + solids->get_y_offset();
1554 Sector::change_solid_tiles(uint32_t old_tile_id, uint32_t new_tile_id)
1556 for(std::list<TileMap*>::const_iterator i = solid_tilemaps.begin(); i != solid_tilemaps.end(); i++) {
1557 TileMap* solids = *i;
1558 solids->change_all(old_tile_id, new_tile_id);
1564 Sector::set_ambient_light(float red, float green, float blue)
1566 ambient_light.red = red;
1567 ambient_light.green = green;
1568 ambient_light.blue = blue;
1572 Sector::get_ambient_red()
1574 return ambient_light.red;
1578 Sector::get_ambient_green()
1580 return ambient_light.green;
1584 Sector::get_ambient_blue()
1586 return ambient_light.blue;
1590 Sector::set_gravity(float gravity)
1592 log_warning << "Changing a Sector's gravitational constant might have unforseen side-effects" << std::endl;
1594 this->gravity = gravity;
1596 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end(); ++i) {
1597 GameObject* game_object = *i;
1598 if(!game_object) continue;
1599 if(!game_object->is_valid()) continue;
1600 UsesPhysic *physics_object = dynamic_cast<UsesPhysic*>(game_object);
1601 if (!physics_object) continue;
1603 physics_object->physic.set_gravity(gravity);