3 // SuperTux - A Jump'n Run
4 // Copyright (C) 2004 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.
29 #include "app/globals.h"
31 #include "player_status.h"
32 #include "object/gameobjs.h"
33 #include "object/camera.h"
34 #include "object/background.h"
35 #include "object/particlesystem.h"
36 #include "object/tilemap.h"
37 #include "lisp/parser.h"
38 #include "lisp/lisp.h"
39 #include "lisp/writer.h"
40 #include "lisp/list_iterator.h"
42 #include "audio/sound_manager.h"
44 #include "resources.h"
45 #include "statistics.h"
46 #include "collision_grid.h"
47 #include "collision_grid_iterator.h"
48 #include "object_factory.h"
49 #include "special/collision.h"
50 #include "math/rectangle.h"
51 #include "math/aatriangle.h"
52 #include "object/coin.h"
53 #include "object/block.h"
54 #include "object/invisible_block.h"
55 #include "object/bullet.h"
56 #include "badguy/jumpy.h"
57 #include "badguy/spike.h"
58 #include "trigger/sequence_trigger.h"
62 Sector* Sector::_current = 0;
65 : gravity(10), player(0), solids(0), camera(0),
66 currentmusic(LEVEL_MUSIC)
68 song_title = "Mortimers_chipdisko.mod";
69 player = new Player();
72 grid = new CollisionGrid(32000, 32000);
77 update_game_objects();
78 assert(gameobjects_new.size() == 0);
82 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
87 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
96 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
98 if(name == "camera") {
99 Camera* camera = new Camera(this);
100 camera->parse(reader);
102 } else if(name == "particles-snow") {
103 SnowParticleSystem* partsys = new SnowParticleSystem();
104 partsys->parse(reader);
106 } else if(name == "particles-rain") {
107 RainParticleSystem* partsys = new RainParticleSystem();
108 partsys->parse(reader);
110 } else if(name == "particles-clouds") {
111 CloudParticleSystem* partsys = new CloudParticleSystem();
112 partsys->parse(reader);
114 } else if(name == "money") { // for compatibility with old maps
115 return new Jumpy(reader);
119 return create_object(name, reader);
120 } catch(std::exception& e) {
121 std::cerr << e.what() << "\n";
128 Sector::parse(const lisp::Lisp& sector)
132 lisp::ListIterator iter(§or);
134 const std::string& token = iter.item();
135 if(token == "name") {
136 iter.value()->get(name);
137 } else if(token == "gravity") {
138 iter.value()->get(gravity);
139 } else if(token == "music") {
140 iter.value()->get(song_title);
142 } else if(token == "spawnpoint") {
143 const lisp::Lisp* spawnpoint_lisp = iter.lisp();
145 SpawnPoint* sp = new SpawnPoint;
146 spawnpoint_lisp->get("name", sp->name);
147 spawnpoint_lisp->get("x", sp->pos.x);
148 spawnpoint_lisp->get("y", sp->pos.y);
149 spawnpoints.push_back(sp);
151 GameObject* object = parse_object(token, *(iter.lisp()));
158 update_game_objects();
160 update_game_objects();
162 std::cerr << "sector '" << name << "' does not contain a camera.\n";
163 camera = new Camera(this);
167 throw std::runtime_error("sector does not contain a solid tile layer.");
171 Sector::parse_old_format(const lisp::Lisp& reader)
176 reader.get("gravity", gravity);
178 std::string backgroundimage;
179 reader.get("background", backgroundimage);
181 reader.get("bkgd_speed", bgspeed);
184 Color bkgd_top, bkgd_bottom;
185 int r = 0, g = 0, b = 128;
186 reader.get("bkgd_red_top", r);
187 reader.get("bkgd_green_top", g);
188 reader.get("bkgd_blue_top", b);
193 reader.get("bkgd_red_bottom", r);
194 reader.get("bkgd_green_bottom", g);
195 reader.get("bkgd_blue_bottom", b);
197 bkgd_bottom.green = g;
198 bkgd_bottom.blue = b;
200 if(backgroundimage != "") {
201 Background* background = new Background;
202 background->set_image(backgroundimage, bgspeed);
203 add_object(background);
205 Background* background = new Background;
206 background->set_gradient(bkgd_top, bkgd_bottom);
207 add_object(background);
210 std::string particlesystem;
211 reader.get("particle_system", particlesystem);
212 if(particlesystem == "clouds")
213 add_object(new CloudParticleSystem());
214 else if(particlesystem == "snow")
215 add_object(new SnowParticleSystem());
216 else if(particlesystem == "rain")
217 add_object(new RainParticleSystem());
219 Vector startpos(100, 170);
220 reader.get("start_pos_x", startpos.x);
221 reader.get("start_pos_y", startpos.y);
223 SpawnPoint* spawn = new SpawnPoint;
224 spawn->pos = startpos;
225 spawn->name = "main";
226 spawnpoints.push_back(spawn);
228 song_title = "Mortimers_chipdisko.mod";
229 reader.get("music", song_title);
232 int width, height = 15;
233 reader.get("width", width);
234 reader.get("height", height);
236 std::vector<unsigned int> tiles;
237 if(reader.get_vector("interactive-tm", tiles)
238 || reader.get_vector("tilemap", tiles)) {
239 TileMap* tilemap = new TileMap();
240 tilemap->set(width, height, tiles, LAYER_TILES, true);
244 if(reader.get_vector("background-tm", tiles)) {
245 TileMap* tilemap = new TileMap();
246 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
250 if(reader.get_vector("foreground-tm", tiles)) {
251 TileMap* tilemap = new TileMap();
252 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
256 // read reset-points (now spawn-points)
257 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
259 lisp::ListIterator iter(resetpoints);
261 if(iter.item() == "point") {
263 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
265 SpawnPoint* sp = new SpawnPoint;
268 spawnpoints.push_back(sp);
271 std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
277 const lisp::Lisp* objects = reader.get_lisp("objects");
279 lisp::ListIterator iter(objects);
281 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
285 std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
291 Camera* camera = new Camera(this);
294 update_game_objects();
296 update_game_objects();
298 throw std::runtime_error("sector does not contain a solid tile layer.");
302 Sector::fix_old_tiles()
305 for(size_t x=0; x < solids->get_width(); ++x) {
306 for(size_t y=0; y < solids->get_height(); ++y) {
307 const Tile* tile = solids->get_tile(x, y);
308 Vector pos(x*32, y*32);
310 if(tile->getID() == 112) {
311 add_object(new InvisibleBlock(pos));
312 solids->change(x, y, 0);
313 } else if(tile->getID() == 295) {
314 add_object(new Spike(pos, Spike::NORTH));
315 solids->change(x, y, 0);
316 } else if(tile->getID() == 296) {
317 add_object(new Spike(pos, Spike::EAST));
318 solids->change(x, y, 0);
319 } else if(tile->getID() == 297) {
320 add_object(new Spike(pos, Spike::SOUTH));
321 solids->change(x, y, 0);
322 } else if(tile->getID() == 298) {
323 add_object(new Spike(pos, Spike::WEST));
324 solids->change(x, y, 0);
325 } else if(tile->getAttributes() & Tile::COIN) {
326 add_object(new Coin(pos));
327 solids->change(x, y, 0);
328 } else if(tile->getAttributes() & Tile::FULLBOX) {
329 add_object(new BonusBlock(pos, tile->getData()));
330 solids->change(x, y, 0);
331 } else if(tile->getAttributes() & Tile::BRICK) {
332 add_object(new Brick(pos, tile->getData()));
333 solids->change(x, y, 0);
334 } else if(tile->getAttributes() & Tile::GOAL) {
335 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
336 add_object(new SequenceTrigger(pos, sequence));
337 solids->change(x, y, 0);
344 Sector::write(lisp::Writer& writer)
346 writer.write_string("name", name);
347 writer.write_float("gravity", gravity);
348 writer.write_string("music", song_title);
351 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
353 SpawnPoint* spawn = *i;
354 writer.start_list("spawn-points");
355 writer.write_string("name", spawn->name);
356 writer.write_float("x", spawn->pos.x);
357 writer.write_float("y", spawn->pos.y);
358 writer.end_list("spawn-points");
362 for(GameObjects::iterator i = gameobjects.begin();
363 i != gameobjects.end(); ++i) {
364 Serializable* serializable = dynamic_cast<Serializable*> (*i);
366 serializable->write(writer);
371 Sector::add_object(GameObject* object)
373 // make sure the object isn't already in the list
375 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
378 assert("object already added to sector" == 0);
381 for(GameObjects::iterator i = gameobjects_new.begin();
382 i != gameobjects_new.end(); ++i) {
384 assert("object already added to sector" == 0);
389 gameobjects_new.push_back(object);
393 Sector::activate(const std::string& spawnpoint)
397 // Apply bonuses from former levels
398 switch (player_status.bonus)
400 case PlayerStatus::NO_BONUS:
403 case PlayerStatus::FLOWER_BONUS:
404 player->got_power = Player::FIRE_POWER; // FIXME: add ice power to here
407 case PlayerStatus::GROWUP_BONUS:
413 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
415 if((*i)->name == spawnpoint) {
421 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
423 player->move(sp->pos);
426 camera->reset(player->get_pos());
430 Sector::get_best_spawn_point(Vector pos)
432 Vector best_reset_point = Vector(-1,-1);
434 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
436 if((*i)->name != "main")
438 if((*i)->pos.x > best_reset_point.x && (*i)->pos.x < pos.x)
439 best_reset_point = (*i)->pos;
442 return best_reset_point;
446 Sector::get_active_region()
449 camera->get_translation() - Vector(1600, 1200),
450 camera->get_translation() + Vector(1600, 1200));
454 Sector::action(float elapsed_time)
456 player->check_bounds(camera);
459 CollisionGridIterator iter(*grid, get_active_region());
460 while(MovingObject* object = iter.next()) {
461 if(!object->is_valid())
464 object->action(elapsed_time);
468 for(GameObjects::iterator i = gameobjects.begin();
469 i != gameobjects.end(); ++i) {
470 GameObject* object = *i;
471 if(!object->is_valid())
474 object->action(elapsed_time);
478 /* Handle all possible collisions. */
480 update_game_objects();
484 Sector::update_game_objects()
486 /** cleanup marked objects */
487 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
488 i != gameobjects.end(); /* nothing */) {
489 GameObject* object = *i;
491 if(object->is_valid()) {
496 Bullet* bullet = dynamic_cast<Bullet*> (object);
499 std::remove(bullets.begin(), bullets.end(), bullet),
502 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
504 grid->remove_object(movingobject);
507 i = gameobjects.erase(i);
510 /* add newly created objects */
511 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
512 i != gameobjects_new.end(); ++i)
514 GameObject* object = *i;
516 Bullet* bullet = dynamic_cast<Bullet*> (object);
518 bullets.push_back(bullet);
520 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
522 grid->add_object(movingobject);
524 TileMap* tilemap = dynamic_cast<TileMap*> (object);
525 if(tilemap && tilemap->is_solid()) {
529 std::cerr << "Another solid tilemaps added. Ignoring.";
533 Camera* camera = dynamic_cast<Camera*> (object);
535 if(this->camera != 0) {
536 std::cerr << "Warning: Multiple cameras added. Ignoring.";
539 this->camera = camera;
542 gameobjects.push_back(object);
544 gameobjects_new.clear();
548 Sector::draw(DrawingContext& context)
550 context.push_transform();
551 context.set_translation(camera->get_translation());
554 CollisionGridIterator iter(*grid, get_active_region());
555 while(MovingObject* object = iter.next()) {
556 if(!object->is_valid())
559 object->draw(context);
562 for(GameObjects::iterator i = gameobjects.begin();
563 i != gameobjects.end(); ++i) {
564 GameObject* object = *i;
565 if(!object->is_valid())
568 object->draw(context);
572 context.pop_transform();
575 static const float DELTA = .001;
578 Sector::collision_tilemap(MovingObject* object, int depth)
582 std::cout << "Max collision depth reached.\n";
584 object->movement = Vector(0, 0);
588 // calculate rectangle where the object will move
590 if(object->get_movement().x >= 0) {
591 x1 = object->get_pos().x;
592 x2 = object->get_bbox().p2.x + object->get_movement().x;
594 x1 = object->get_pos().x + object->get_movement().x;
595 x2 = object->get_bbox().p2.x;
598 if(object->get_movement().y >= 0) {
599 y1 = object->get_pos().y;
600 y2 = object->get_bbox().p2.y + object->get_movement().y;
602 y1 = object->get_pos().y + object->get_movement().y;
603 y2 = object->get_bbox().p2.y;
606 // test with all tiles in this rectangle
607 int starttilex = int(x1-1) / 32;
608 int starttiley = int(y1-1) / 32;
609 int max_x = int(x2+1);
610 int max_y = int(y2+1);
612 CollisionHit temphit, hit;
613 Rectangle dest = object->get_bbox();
614 dest.move(object->movement);
615 hit.time = -1; // represents an invalid value
616 for(int x = starttilex; x*32 < max_x; ++x) {
617 for(int y = starttiley; y*32 < max_y; ++y) {
618 const Tile* tile = solids->get_tile(x, y);
621 if(!(tile->getAttributes() & Tile::SOLID))
623 if((tile->getAttributes() & Tile::UNISOLID) && object->movement.y < 0)
626 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
628 Vector p1(x*32, y*32);
629 Vector p2((x+1)*32, (y+1)*32);
630 triangle = AATriangle(p1, p2, tile->getData());
632 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
634 if(temphit.time > hit.time)
637 } else { // normal rectangular tile
638 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
639 if(Collision::rectangle_rectangle(temphit, dest,
640 object->movement, rect)) {
641 if(temphit.time > hit.time)
648 // did we collide at all?
652 // call collision function
653 HitResponse response = object->collision(*solids, hit);
654 if(response == ABORT_MOVE) {
655 object->movement = Vector(0, 0);
658 if(response == FORCE_MOVE) {
661 // move out of collision and try again
662 object->movement += hit.normal * (hit.depth + DELTA);
663 collision_tilemap(object, depth+1);
667 Sector::collision_object(MovingObject* object1, MovingObject* object2)
670 Rectangle dest1 = object1->get_bbox();
671 dest1.move(object1->get_movement());
672 Rectangle dest2 = object2->get_bbox();
673 dest2.move(object2->get_movement());
675 Vector movement = object1->get_movement() - object2->get_movement();
676 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
677 HitResponse response1 = object1->collision(*object2, hit);
679 HitResponse response2 = object2->collision(*object1, hit);
681 if(response1 != CONTINUE) {
682 if(response1 == ABORT_MOVE)
683 object1->movement = Vector(0, 0);
684 if(response2 == CONTINUE)
685 object2->movement += hit.normal * (hit.depth + DELTA);
686 } else if(response2 != CONTINUE) {
687 if(response2 == ABORT_MOVE)
688 object2->movement = Vector(0, 0);
689 if(response1 == CONTINUE)
690 object1->movement += -hit.normal * (hit.depth + DELTA);
692 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
693 object2->movement += hit.normal * (hit.depth/2 + DELTA);
699 Sector::collision_handler()
702 grid->check_collisions();
704 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
705 i != gameobjects.end(); ++i) {
706 GameObject* gameobject = *i;
707 if(!gameobject->is_valid())
709 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
712 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
713 movingobject->bbox.move(movingobject->movement);
714 movingobject->movement = Vector(0, 0);
718 // collision with tilemap
719 if(! (movingobject->movement == Vector(0, 0)))
720 collision_tilemap(movingobject, 0);
722 // collision with other objects
723 for(std::vector<GameObject*>::iterator i2 = i+1;
724 i2 != gameobjects.end(); ++i2) {
725 GameObject* other_object = *i2;
726 if(!other_object->is_valid()
727 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
729 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
733 collision_object(movingobject, movingobject2);
736 movingobject->bbox.move(movingobject->get_movement());
737 movingobject->movement = Vector(0, 0);
743 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
745 // TODO remove this function and move these checks elsewhere...
746 static const size_t MAX_FIRE_BULLETS = 2;
747 static const size_t MAX_ICE_BULLETS = 1;
749 if(player->got_power == Player::FIRE_POWER) {
750 if(bullets.size() > MAX_FIRE_BULLETS-1)
752 } else if(player->got_power == Player::ICE_POWER) {
753 if(bullets.size() > MAX_ICE_BULLETS-1)
757 Bullet* new_bullet = 0;
758 if(player->got_power == Player::FIRE_POWER)
759 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
760 else if(player->got_power == Player::ICE_POWER)
761 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
763 throw std::runtime_error("wrong bullet type.");
764 add_object(new_bullet);
766 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
772 Sector::add_smoke_cloud(const Vector& pos)
774 add_object(new SmokeCloud(pos));
779 Sector::add_floating_text(const Vector& pos, const std::string& text)
781 add_object(new FloatingText(pos, text));
790 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
792 song_path = (char *) malloc(sizeof(char) * datadir.length() +
793 strlen(song_title.c_str()) + 8 + 5);
794 song_subtitle = strdup(song_title.c_str());
795 strcpy(strstr(song_subtitle, "."), "\0");
796 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
797 song_subtitle, strstr(song_title.c_str(), "."));
798 if(!SoundManager::get()->exists_music(song_path)) {
799 level_song_fast = level_song;
801 level_song_fast = SoundManager::get()->load_music(song_path);
808 Sector::play_music(int type)
811 switch(currentmusic) {
813 SoundManager::get()->play_music(level_song_fast);
816 SoundManager::get()->play_music(level_song);
819 SoundManager::get()->play_music(herring_song);
822 SoundManager::get()->halt_music();
828 Sector::get_music_type()
834 Sector::get_total_badguys()
836 int total_badguys = 0;
837 for(GameObjects::iterator i = gameobjects.begin();
838 i != gameobjects.end(); ++i) {
839 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
844 return total_badguys;
848 Sector::inside(const Rectangle& rect) const
850 if(rect.p1.x > solids->get_width() * 32
851 || rect.p1.y > solids->get_height() * 32
852 || rect.p2.x < 0 || rect.p2.y < 0)