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 "utils/lispreader.h"
34 #include "background.h"
35 #include "particlesystem.h"
38 #include "audio/sound_manager.h"
40 #include "resources.h"
41 #include "statistics.h"
42 #include "special/collision.h"
43 #include "math/rectangle.h"
44 #include "math/aatriangle.h"
45 #include "object/coin.h"
46 #include "object/block.h"
47 #include "object/invisible_block.h"
48 #include "object/platform.h"
49 #include "object/bullet.h"
50 #include "badguy/jumpy.h"
51 #include "badguy/snowball.h"
52 #include "badguy/bouncing_snowball.h"
53 #include "badguy/flame.h"
54 #include "badguy/mriceblock.h"
55 #include "badguy/mrbomb.h"
56 #include "badguy/dispenser.h"
57 #include "badguy/spike.h"
58 #include "trigger/door.h"
59 #include "trigger/sequence_trigger.h"
60 #include "trigger/secretarea_trigger.h"
62 Sector* Sector::_current = 0;
65 : gravity(10), player(0), solids(0), background(0), camera(0),
66 currentmusic(LEVEL_MUSIC)
68 song_title = "Mortimers_chipdisko.mod";
69 player = new Player();
75 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
80 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
88 Sector *Sector::create(const std::string& name, size_t width, size_t height)
90 Sector *sector = new Sector;
92 TileMap *background = new TileMap(LAYER_BACKGROUNDTILES, false, width, height);
93 TileMap *interactive = new TileMap(LAYER_TILES, true, width, height);
94 TileMap *foreground = new TileMap(LAYER_FOREGROUNDTILES, false, width, height);
95 sector->add_object(background);
96 sector->add_object(interactive);
97 sector->add_object(foreground);
98 sector->solids = interactive;
99 sector->camera = new Camera(sector);
100 sector->add_object(sector->camera);
101 sector->update_game_objects();
106 Sector::parse_object(const std::string& name, LispReader& reader)
108 if(name == "background") {
109 background = new Background(reader);
111 } else if(name == "camera") {
113 std::cerr << "Warning: More than 1 camera defined in sector.\n";
116 camera = new Camera(this);
117 camera->read(reader);
119 } else if(name == "tilemap") {
120 TileMap* tilemap = new TileMap(reader);
122 if(tilemap->is_solid()) {
124 std::cerr << "Warning multiple solid tilemaps in sector.\n";
131 } else if(name == "particles-snow") {
132 SnowParticleSystem* partsys = new SnowParticleSystem();
133 partsys->parse(reader);
135 } else if(name == "particles-clouds") {
136 CloudParticleSystem* partsys = new CloudParticleSystem();
137 partsys->parse(reader);
139 } else if(name == "door") {
140 return new Door(reader);
141 } else if(name == "secretarea") {
142 return new SecretAreaTrigger(reader);
143 } else if(name == "platform") {
144 return new Platform(reader);
145 } else if(name == "jumpy" || name == "money") {
146 return new Jumpy(reader);
147 } else if(name == "snowball") {
148 return new SnowBall(reader);
149 } else if(name == "bouncingsnowball") {
150 return new BouncingSnowball(reader);
151 } else if(name == "flame") {
152 return new Flame(reader);
153 } else if(name == "mriceblock") {
154 return new MrIceBlock(reader);
155 } else if(name == "mrbomb") {
156 return new MrBomb(reader);
157 } else if(name == "dispenser") {
158 return new Dispenser(reader);
159 } else if(name == "spike") {
160 return new Spike(reader);
163 else if(badguykind_from_string(name) != BAD_INVALID) {
164 return new BadGuy(badguykind_from_string(name), reader);
165 } else if(name == "trampoline") {
166 return new Trampoline(reader);
167 } else if(name == "flying-platform") {
168 return new FlyingPlatform(reader);
171 std::cerr << "Unknown object type '" << name << "'.\n";
176 Sector::parse(LispReader& lispreader)
180 for(lisp_object_t* cur = lispreader.get_lisp(); !lisp_nil_p(cur);
181 cur = lisp_cdr(cur)) {
182 std::string token = lisp_symbol(lisp_car(lisp_car(cur)));
183 // FIXME: doesn't handle empty data
184 lisp_object_t* data = lisp_car(lisp_cdr(lisp_car(cur)));
185 LispReader reader(lisp_cdr(lisp_car(cur)));
187 if(token == "name") {
188 name = lisp_string(data);
189 } else if(token == "gravity") {
190 gravity = lisp_real(data);
191 } else if(token == "music") {
192 song_title = lisp_string(data);
194 } else if(token == "spawn-points") {
195 SpawnPoint* sp = new SpawnPoint;
196 reader.read_string("name", sp->name);
197 reader.read_float("x", sp->pos.x);
198 reader.read_float("y", sp->pos.y);
199 spawnpoints.push_back(sp);
201 GameObject* object = parse_object(token, reader);
209 std::cerr << "sector '" << name << "' does not contain a camera.\n";
210 camera = new Camera(this);
214 throw std::runtime_error("sector does not contain a solid tile layer.");
218 Sector::parse_old_format(LispReader& reader)
223 reader.read_float("gravity", gravity);
225 std::string backgroundimage;
226 reader.read_string("background", backgroundimage);
228 reader.read_float("bkgd_speed", bgspeed);
231 Color bkgd_top, bkgd_bottom;
232 int r = 0, g = 0, b = 128;
233 reader.read_int("bkgd_red_top", r);
234 reader.read_int("bkgd_green_top", g);
235 reader.read_int("bkgd_blue_top", b);
240 reader.read_int("bkgd_red_bottom", r);
241 reader.read_int("bkgd_green_bottom", g);
242 reader.read_int("bkgd_blue_bottom", b);
244 bkgd_bottom.green = g;
245 bkgd_bottom.blue = b;
247 if(backgroundimage != "") {
248 background = new Background;
249 background->set_image(backgroundimage, bgspeed);
250 add_object(background);
252 background = new Background;
253 background->set_gradient(bkgd_top, bkgd_bottom);
254 add_object(background);
257 std::string particlesystem;
258 reader.read_string("particle_system", particlesystem);
259 if(particlesystem == "clouds")
260 add_object(new CloudParticleSystem());
261 else if(particlesystem == "snow")
262 add_object(new SnowParticleSystem());
264 Vector startpos(100, 170);
265 reader.read_float("start_pos_x", startpos.x);
266 reader.read_float("start_pos_y", startpos.y);
268 SpawnPoint* spawn = new SpawnPoint;
269 spawn->pos = startpos;
270 spawn->name = "main";
271 spawnpoints.push_back(spawn);
273 song_title = "Mortimers_chipdisko.mod";
274 reader.read_string("music", song_title);
277 int width, height = 15;
278 reader.read_int("width", width);
279 reader.read_int("height", height);
281 std::vector<unsigned int> tiles;
282 if(reader.read_int_vector("interactive-tm", tiles)
283 || reader.read_int_vector("tilemap", tiles)) {
284 TileMap* tilemap = new TileMap();
285 tilemap->set(width, height, tiles, LAYER_TILES, true);
292 if(reader.read_int_vector("background-tm", tiles)) {
293 TileMap* tilemap = new TileMap();
294 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
298 if(reader.read_int_vector("foreground-tm", tiles)) {
299 TileMap* tilemap = new TileMap();
300 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
304 // read reset-points (now spawn-points)
306 lisp_object_t* cur = 0;
307 if(reader.read_lisp("reset-points", cur)) {
308 while(!lisp_nil_p(cur)) {
309 lisp_object_t* data = lisp_car(cur);
310 LispReader reader(lisp_cdr(data));
313 if(reader.read_float("x", sp_pos.x) && reader.read_float("y", sp_pos.y))
315 SpawnPoint* sp = new SpawnPoint;
318 spawnpoints.push_back(sp);
328 lisp_object_t* cur = 0;
329 if(reader.read_lisp("objects", cur)) {
330 while(!lisp_nil_p(cur)) {
331 lisp_object_t* data = lisp_car(cur);
332 std::string object_type = lisp_symbol(lisp_car(data));
334 LispReader reader(lisp_cdr(data));
336 GameObject* object = parse_object(object_type, reader);
340 std::cerr << "Unknown object '" << object_type << "' in level.\n";
349 camera = new Camera(this);
354 Sector::fix_old_tiles()
357 for(size_t x=0; x < solids->get_width(); ++x) {
358 for(size_t y=0; y < solids->get_height(); ++y) {
359 const Tile* tile = solids->get_tile(x, y);
360 Vector pos(x*32, y*32);
362 if(tile->id == 112) {
363 add_object(new InvisibleBlock(pos));
364 solids->change(x, y, 0);
365 } else if(tile->id == 295) {
366 add_object(new Spike(pos, Spike::NORTH));
367 solids->change(x, y, 0);
368 } else if(tile->id == 296) {
369 add_object(new Spike(pos, Spike::EAST));
370 solids->change(x, y, 0);
371 } else if(tile->id == 297) {
372 add_object(new Spike(pos, Spike::SOUTH));
373 solids->change(x, y, 0);
374 } else if(tile->id == 298) {
375 add_object(new Spike(pos, Spike::WEST));
376 solids->change(x, y, 0);
377 } else if(tile->attributes & Tile::COIN) {
378 add_object(new Coin(pos));
379 solids->change(x, y, 0);
380 } else if(tile->attributes & Tile::FULLBOX) {
381 add_object(new BonusBlock(pos, tile->data));
382 solids->change(x, y, 0);
383 } else if(tile->attributes & Tile::BRICK) {
384 add_object(new Brick(pos, tile->data));
385 solids->change(x, y, 0);
386 } else if(tile->attributes & Tile::GOAL) {
387 add_object(new SequenceTrigger(pos, "endsequence"));
388 solids->change(x, y, 0);
395 Sector::write(LispWriter& writer)
397 writer.write_string("name", name);
398 writer.write_float("gravity", gravity);
399 writer.write_string("music", song_title);
402 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
404 SpawnPoint* spawn = *i;
405 writer.start_list("spawn-points");
406 writer.write_string("name", spawn->name);
407 writer.write_float("x", spawn->pos.x);
408 writer.write_float("y", spawn->pos.y);
409 writer.end_list("spawn-points");
413 for(GameObjects::iterator i = gameobjects.begin();
414 i != gameobjects.end(); ++i) {
415 Serializable* serializable = dynamic_cast<Serializable*> (*i);
417 serializable->write(writer);
422 Sector::do_vertical_flip()
424 // remove or fix later
426 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
428 TileMap* tilemap = dynamic_cast<TileMap*> (*i);
431 tilemap->do_vertical_flip();
434 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
436 badguy->start_position.y = solids->get_height()*32 - badguy->start_position.y - 32;
437 Trampoline* trampoline = dynamic_cast<Trampoline*> (*i);
439 trampoline->base.y = solids->get_height()*32 - trampoline->base.y - 32;
440 FlyingPlatform* flying_platform = dynamic_cast<FlyingPlatform*> (*i);
442 flying_platform->base.y = solids->get_height()*32 - flying_platform->base.y - 32;
443 Door* door = dynamic_cast<Door*> (*i);
445 door->set_area(door->get_area().x, solids->get_height()*32 - door->get_area().y - 32);
448 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
450 SpawnPoint* spawn = *i;
451 spawn->pos.y = solids->get_height()*32 - spawn->pos.y - 32;
457 Sector::add_object(GameObject* object)
459 // make sure the object isn't already in the list
461 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
464 assert("object already added to sector" == 0);
467 for(GameObjects::iterator i = gameobjects_new.begin();
468 i != gameobjects_new.end(); ++i) {
470 assert("object already added to sector" == 0);
475 gameobjects_new.push_back(object);
479 Sector::activate(const std::string& spawnpoint)
483 // Apply bonuses from former levels
484 switch (player_status.bonus)
486 case PlayerStatus::NO_BONUS:
489 case PlayerStatus::FLOWER_BONUS:
490 player->got_power = Player::FIRE_POWER; // FIXME: add ice power to here
493 case PlayerStatus::GROWUP_BONUS:
499 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
501 if((*i)->name == spawnpoint) {
507 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
509 player->move(sp->pos);
512 camera->reset(player->get_pos());
516 Sector::get_best_spawn_point(Vector pos)
518 Vector best_reset_point = Vector(-1,-1);
520 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
522 if((*i)->name != "main")
524 if((*i)->pos.x > best_reset_point.x && (*i)->pos.x < pos.x)
525 best_reset_point = (*i)->pos;
528 return best_reset_point;
532 Sector::action(float elapsed_time)
534 player->check_bounds(camera);
537 for(GameObjects::iterator i = gameobjects.begin();
538 i != gameobjects.end(); ++i) {
539 GameObject* object = *i;
540 if(!object->is_valid())
543 object->action(elapsed_time);
546 /* Handle all possible collisions. */
549 update_game_objects();
553 Sector::update_game_objects()
555 /** cleanup marked objects */
556 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
557 i != gameobjects.end(); /* nothing */) {
558 if((*i)->is_valid() == false) {
559 Bullet* bullet = dynamic_cast<Bullet*> (*i);
562 std::remove(bullets.begin(), bullets.end(), bullet),
566 InteractiveObject* interactive_object =
567 dynamic_cast<InteractiveObject*> (*i);
568 if(interactive_object) {
569 interactive_objects.erase(
570 std::remove(interactive_objects.begin(), interactive_objects.end(),
571 interactive_object), interactive_objects.end());
575 i = gameobjects.erase(i);
581 /* add newly created objects */
582 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
583 i != gameobjects_new.end(); ++i)
585 Bullet* bullet = dynamic_cast<Bullet*> (*i);
587 bullets.push_back(bullet);
589 InteractiveObject* interactive_object
590 = dynamic_cast<InteractiveObject*> (*i);
591 if(interactive_object)
592 interactive_objects.push_back(interactive_object);
595 gameobjects.push_back(*i);
597 gameobjects_new.clear();
601 Sector::draw(DrawingContext& context)
603 context.push_transform();
604 context.set_translation(camera->get_translation());
606 for(GameObjects::iterator i = gameobjects.begin();
607 i != gameobjects.end(); ++i) {
608 GameObject* object = *i;
609 if(!object->is_valid())
612 object->draw(context);
615 context.pop_transform();
618 static const float DELTA = .001;
621 Sector::collision_tilemap(MovingObject* object, int depth)
625 std::cout << "Max collision depth reached.\n";
627 object->movement = Vector(0, 0);
631 // calculate rectangle where the object will move
633 if(object->get_movement().x >= 0) {
634 x1 = object->get_pos().x;
635 x2 = object->get_bbox().p2.x + object->get_movement().x;
637 x1 = object->get_pos().x + object->get_movement().x;
638 x2 = object->get_bbox().p2.x;
641 if(object->get_movement().y >= 0) {
642 y1 = object->get_pos().y;
643 y2 = object->get_bbox().p2.y + object->get_movement().y;
645 y1 = object->get_pos().y + object->get_movement().y;
646 y2 = object->get_bbox().p2.y;
649 // test with all tiles in this rectangle
650 int starttilex = int(x1-1) / 32;
651 int starttiley = int(y1-1) / 32;
652 int max_x = int(x2+1);
653 int max_y = int(y2+1);
655 CollisionHit temphit, hit;
656 Rectangle dest = object->get_bbox();
657 dest.move(object->movement);
658 hit.time = -1; // represents an invalid value
659 for(int x = starttilex; x*32 < max_x; ++x) {
660 for(int y = starttiley; y*32 < max_y; ++y) {
661 const Tile* tile = solids->get_tile(x, y);
664 if(!(tile->attributes & Tile::SOLID))
666 if((tile->attributes & Tile::UNISOLID) && object->movement.y < 0)
669 if(tile->attributes & Tile::SLOPE) { // slope tile
671 Vector p1(x*32, y*32);
672 Vector p2((x+1)*32, (y+1)*32);
675 triangle = AATriangle(p1, p2, AATriangle::SOUTHWEST);
678 triangle = AATriangle(p1, p2, AATriangle::NORTHEAST);
681 triangle = AATriangle(p1, p2, AATriangle::SOUTHEAST);
684 triangle = AATriangle(p1, p2, AATriangle::NORTHWEST);
687 printf("Invalid slope angle in tile %d !\n", tile->id);
691 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
693 if(temphit.time > hit.time)
696 } else { // normal rectangular tile
697 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
698 if(Collision::rectangle_rectangle(temphit, dest,
699 object->movement, rect)) {
700 if(temphit.time > hit.time)
707 // did we collide at all?
711 // call collision function
712 HitResponse response = object->collision(*solids, hit);
713 if(response == ABORT_MOVE) {
714 object->movement = Vector(0, 0);
717 if(response == FORCE_MOVE) {
720 // move out of collision and try again
721 object->movement += hit.normal * (hit.depth + DELTA);
722 collision_tilemap(object, depth+1);
726 Sector::collision_object(MovingObject* object1, MovingObject* object2)
729 Rectangle dest1 = object1->get_bbox();
730 dest1.move(object1->get_movement());
731 Rectangle dest2 = object2->get_bbox();
732 dest2.move(object2->get_movement());
734 Vector movement = object1->get_movement() - object2->get_movement();
735 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
736 HitResponse response1 = object1->collision(*object2, hit);
738 HitResponse response2 = object2->collision(*object1, hit);
740 if(response1 != CONTINUE) {
741 if(response1 == ABORT_MOVE)
742 object1->movement = Vector(0, 0);
743 if(response2 == CONTINUE)
744 object2->movement += hit.normal * (hit.depth + DELTA);
745 } else if(response2 != CONTINUE) {
746 if(response2 == ABORT_MOVE)
747 object2->movement = Vector(0, 0);
748 if(response1 == CONTINUE)
749 object1->movement += -hit.normal * (hit.depth + DELTA);
751 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
752 object2->movement += hit.normal * (hit.depth/2 + DELTA);
758 Sector::collision_handler()
760 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
761 i != gameobjects.end(); ++i) {
762 GameObject* gameobject = *i;
763 if(!gameobject->is_valid())
765 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
768 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
769 movingobject->bbox.move(movingobject->movement);
770 movingobject->movement = Vector(0, 0);
774 // collision with tilemap
775 if(! (movingobject->movement == Vector(0, 0)))
776 collision_tilemap(movingobject, 0);
778 // collision with other objects
779 for(std::vector<GameObject*>::iterator i2 = i+1;
780 i2 != gameobjects.end(); ++i2) {
781 GameObject* other_object = *i2;
782 if(!other_object->is_valid()
783 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
785 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
789 collision_object(movingobject, movingobject2);
792 movingobject->bbox.move(movingobject->get_movement());
793 movingobject->movement = Vector(0, 0);
798 Sector::add_score(const Vector& pos, int s)
800 global_stats.add_points(SCORE_STAT, s);
802 add_object(new FloatingText(pos, s));
806 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
808 if(player->got_power == Player::FIRE_POWER) {
809 if(bullets.size() > MAX_FIRE_BULLETS-1)
811 } else if(player->got_power == Player::ICE_POWER) {
812 if(bullets.size() > MAX_ICE_BULLETS-1)
816 Bullet* new_bullet = 0;
817 if(player->got_power == Player::FIRE_POWER)
818 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
819 else if(player->got_power == Player::ICE_POWER)
820 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
822 throw std::runtime_error("wrong bullet type.");
823 add_object(new_bullet);
825 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
831 Sector::add_smoke_cloud(const Vector& pos)
833 add_object(new SmokeCloud(pos));
838 Sector::add_floating_text(const Vector& pos, const std::string& text)
840 add_object(new FloatingText(pos, text));
849 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
851 song_path = (char *) malloc(sizeof(char) * datadir.length() +
852 strlen(song_title.c_str()) + 8 + 5);
853 song_subtitle = strdup(song_title.c_str());
854 strcpy(strstr(song_subtitle, "."), "\0");
855 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
856 song_subtitle, strstr(song_title.c_str(), "."));
857 if(!SoundManager::get()->exists_music(song_path)) {
858 level_song_fast = level_song;
860 level_song_fast = SoundManager::get()->load_music(song_path);
867 Sector::play_music(int type)
870 switch(currentmusic) {
872 SoundManager::get()->play_music(level_song_fast);
875 SoundManager::get()->play_music(level_song);
878 SoundManager::get()->play_music(herring_song);
881 SoundManager::get()->halt_music();
887 Sector::get_music_type()
893 Sector::get_total_badguys()
895 int total_badguys = 0;
897 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
899 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
904 return total_badguys;
908 Sector::inside(const Rectangle& rect) const
910 if(rect.p1.x > solids->get_width() * 32
911 || rect.p1.y > solids->get_height() * 32
912 || rect.p2.x < 0 || rect.p2.y < 0)