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 "badguy/nolok_01.h"
59 #include "trigger/door.h"
60 #include "trigger/sequence_trigger.h"
61 #include "trigger/secretarea_trigger.h"
63 Sector* Sector::_current = 0;
66 : gravity(10), player(0), solids(0), background(0), camera(0),
67 currentmusic(LEVEL_MUSIC)
69 song_title = "Mortimers_chipdisko.mod";
70 player = new Player();
76 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
81 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
89 Sector *Sector::create(const std::string& name, size_t width, size_t height)
91 Sector *sector = new Sector;
93 TileMap *background = new TileMap(LAYER_BACKGROUNDTILES, false, width, height);
94 TileMap *interactive = new TileMap(LAYER_TILES, true, width, height);
95 TileMap *foreground = new TileMap(LAYER_FOREGROUNDTILES, false, width, height);
96 sector->add_object(background);
97 sector->add_object(interactive);
98 sector->add_object(foreground);
99 sector->solids = interactive;
100 sector->camera = new Camera(sector);
101 sector->add_object(sector->camera);
102 sector->update_game_objects();
107 Sector::parse_object(const std::string& name, LispReader& reader)
109 if(name == "background") {
110 background = new Background(reader);
112 } else if(name == "camera") {
114 std::cerr << "Warning: More than 1 camera defined in sector.\n";
117 camera = new Camera(this);
118 camera->read(reader);
120 } else if(name == "tilemap") {
121 TileMap* tilemap = new TileMap(reader);
123 if(tilemap->is_solid()) {
125 std::cerr << "Warning multiple solid tilemaps in sector.\n";
132 } else if(name == "particles-snow") {
133 SnowParticleSystem* partsys = new SnowParticleSystem();
134 partsys->parse(reader);
136 } else if(name == "particles-clouds") {
137 CloudParticleSystem* partsys = new CloudParticleSystem();
138 partsys->parse(reader);
140 } else if(name == "door") {
141 return new Door(reader);
142 } else if(name == "secretarea") {
143 return new SecretAreaTrigger(reader);
144 } else if(name == "platform") {
145 return new Platform(reader);
146 } else if(name == "jumpy" || name == "money") {
147 return new Jumpy(reader);
148 } else if(name == "snowball") {
149 return new SnowBall(reader);
150 } else if(name == "bouncingsnowball") {
151 return new BouncingSnowball(reader);
152 } else if(name == "flame") {
153 return new Flame(reader);
154 } else if(name == "mriceblock") {
155 return new MrIceBlock(reader);
156 } else if(name == "mrbomb") {
157 return new MrBomb(reader);
158 } else if(name == "dispenser") {
159 return new Dispenser(reader);
160 } else if(name == "spike") {
161 return new Spike(reader);
162 } else if(name == "nolok_01") {
163 return new Nolok_01(reader);
166 else if(badguykind_from_string(name) != BAD_INVALID) {
167 return new BadGuy(badguykind_from_string(name), reader);
168 } else if(name == "trampoline") {
169 return new Trampoline(reader);
170 } else if(name == "flying-platform") {
171 return new FlyingPlatform(reader);
174 std::cerr << "Unknown object type '" << name << "'.\n";
179 Sector::parse(LispReader& lispreader)
183 for(lisp_object_t* cur = lispreader.get_lisp(); !lisp_nil_p(cur);
184 cur = lisp_cdr(cur)) {
185 std::string token = lisp_symbol(lisp_car(lisp_car(cur)));
186 // FIXME: doesn't handle empty data
187 lisp_object_t* data = lisp_car(lisp_cdr(lisp_car(cur)));
188 LispReader reader(lisp_cdr(lisp_car(cur)));
190 if(token == "name") {
191 name = lisp_string(data);
192 } else if(token == "gravity") {
193 gravity = lisp_real(data);
194 } else if(token == "music") {
195 song_title = lisp_string(data);
197 } else if(token == "spawn-points") {
198 SpawnPoint* sp = new SpawnPoint;
199 reader.read_string("name", sp->name);
200 reader.read_float("x", sp->pos.x);
201 reader.read_float("y", sp->pos.y);
202 spawnpoints.push_back(sp);
204 GameObject* object = parse_object(token, reader);
212 std::cerr << "sector '" << name << "' does not contain a camera.\n";
213 camera = new Camera(this);
217 throw std::runtime_error("sector does not contain a solid tile layer.");
221 Sector::parse_old_format(LispReader& reader)
226 reader.read_float("gravity", gravity);
228 std::string backgroundimage;
229 reader.read_string("background", backgroundimage);
231 reader.read_float("bkgd_speed", bgspeed);
234 Color bkgd_top, bkgd_bottom;
235 int r = 0, g = 0, b = 128;
236 reader.read_int("bkgd_red_top", r);
237 reader.read_int("bkgd_green_top", g);
238 reader.read_int("bkgd_blue_top", b);
243 reader.read_int("bkgd_red_bottom", r);
244 reader.read_int("bkgd_green_bottom", g);
245 reader.read_int("bkgd_blue_bottom", b);
247 bkgd_bottom.green = g;
248 bkgd_bottom.blue = b;
250 if(backgroundimage != "") {
251 background = new Background;
252 background->set_image(backgroundimage, bgspeed);
253 add_object(background);
255 background = new Background;
256 background->set_gradient(bkgd_top, bkgd_bottom);
257 add_object(background);
260 std::string particlesystem;
261 reader.read_string("particle_system", particlesystem);
262 if(particlesystem == "clouds")
263 add_object(new CloudParticleSystem());
264 else if(particlesystem == "snow")
265 add_object(new SnowParticleSystem());
267 Vector startpos(100, 170);
268 reader.read_float("start_pos_x", startpos.x);
269 reader.read_float("start_pos_y", startpos.y);
271 SpawnPoint* spawn = new SpawnPoint;
272 spawn->pos = startpos;
273 spawn->name = "main";
274 spawnpoints.push_back(spawn);
276 song_title = "Mortimers_chipdisko.mod";
277 reader.read_string("music", song_title);
280 int width, height = 15;
281 reader.read_int("width", width);
282 reader.read_int("height", height);
284 std::vector<unsigned int> tiles;
285 if(reader.read_int_vector("interactive-tm", tiles)
286 || reader.read_int_vector("tilemap", tiles)) {
287 TileMap* tilemap = new TileMap();
288 tilemap->set(width, height, tiles, LAYER_TILES, true);
295 if(reader.read_int_vector("background-tm", tiles)) {
296 TileMap* tilemap = new TileMap();
297 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
301 if(reader.read_int_vector("foreground-tm", tiles)) {
302 TileMap* tilemap = new TileMap();
303 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
307 // read reset-points (now spawn-points)
309 lisp_object_t* cur = 0;
310 if(reader.read_lisp("reset-points", cur)) {
311 while(!lisp_nil_p(cur)) {
312 lisp_object_t* data = lisp_car(cur);
313 LispReader reader(lisp_cdr(data));
316 if(reader.read_float("x", sp_pos.x) && reader.read_float("y", sp_pos.y))
318 SpawnPoint* sp = new SpawnPoint;
321 spawnpoints.push_back(sp);
331 lisp_object_t* cur = 0;
332 if(reader.read_lisp("objects", cur)) {
333 while(!lisp_nil_p(cur)) {
334 lisp_object_t* data = lisp_car(cur);
335 std::string object_type = lisp_symbol(lisp_car(data));
337 LispReader reader(lisp_cdr(data));
339 GameObject* object = parse_object(object_type, reader);
343 std::cerr << "Unknown object '" << object_type << "' in level.\n";
352 camera = new Camera(this);
357 Sector::fix_old_tiles()
360 for(size_t x=0; x < solids->get_width(); ++x) {
361 for(size_t y=0; y < solids->get_height(); ++y) {
362 const Tile* tile = solids->get_tile(x, y);
363 Vector pos(x*32, y*32);
365 if(tile->id == 112) {
366 add_object(new InvisibleBlock(pos));
367 solids->change(x, y, 0);
368 } else if(tile->id == 295) {
369 add_object(new Spike(pos, Spike::NORTH));
370 solids->change(x, y, 0);
371 } else if(tile->id == 296) {
372 add_object(new Spike(pos, Spike::EAST));
373 solids->change(x, y, 0);
374 } else if(tile->id == 297) {
375 add_object(new Spike(pos, Spike::SOUTH));
376 solids->change(x, y, 0);
377 } else if(tile->id == 298) {
378 add_object(new Spike(pos, Spike::WEST));
379 solids->change(x, y, 0);
380 } else if(tile->attributes & Tile::COIN) {
381 add_object(new Coin(pos));
382 solids->change(x, y, 0);
383 } else if(tile->attributes & Tile::FULLBOX) {
384 add_object(new BonusBlock(pos, tile->data));
385 solids->change(x, y, 0);
386 } else if(tile->attributes & Tile::BRICK) {
387 add_object(new Brick(pos, tile->data));
388 solids->change(x, y, 0);
389 } else if(tile->attributes & Tile::GOAL) {
390 add_object(new SequenceTrigger(pos, "endsequence"));
391 solids->change(x, y, 0);
398 Sector::write(LispWriter& writer)
400 writer.write_string("name", name);
401 writer.write_float("gravity", gravity);
402 writer.write_string("music", song_title);
405 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
407 SpawnPoint* spawn = *i;
408 writer.start_list("spawn-points");
409 writer.write_string("name", spawn->name);
410 writer.write_float("x", spawn->pos.x);
411 writer.write_float("y", spawn->pos.y);
412 writer.end_list("spawn-points");
416 for(GameObjects::iterator i = gameobjects.begin();
417 i != gameobjects.end(); ++i) {
418 Serializable* serializable = dynamic_cast<Serializable*> (*i);
420 serializable->write(writer);
425 Sector::do_vertical_flip()
427 // remove or fix later
429 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
431 TileMap* tilemap = dynamic_cast<TileMap*> (*i);
434 tilemap->do_vertical_flip();
437 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
439 badguy->start_position.y = solids->get_height()*32 - badguy->start_position.y - 32;
440 Trampoline* trampoline = dynamic_cast<Trampoline*> (*i);
442 trampoline->base.y = solids->get_height()*32 - trampoline->base.y - 32;
443 FlyingPlatform* flying_platform = dynamic_cast<FlyingPlatform*> (*i);
445 flying_platform->base.y = solids->get_height()*32 - flying_platform->base.y - 32;
446 Door* door = dynamic_cast<Door*> (*i);
448 door->set_area(door->get_area().x, solids->get_height()*32 - door->get_area().y - 32);
451 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
453 SpawnPoint* spawn = *i;
454 spawn->pos.y = solids->get_height()*32 - spawn->pos.y - 32;
460 Sector::add_object(GameObject* object)
462 // make sure the object isn't already in the list
464 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
467 assert("object already added to sector" == 0);
470 for(GameObjects::iterator i = gameobjects_new.begin();
471 i != gameobjects_new.end(); ++i) {
473 assert("object already added to sector" == 0);
478 gameobjects_new.push_back(object);
482 Sector::activate(const std::string& spawnpoint)
486 // Apply bonuses from former levels
487 switch (player_status.bonus)
489 case PlayerStatus::NO_BONUS:
492 case PlayerStatus::FLOWER_BONUS:
493 player->got_power = Player::FIRE_POWER; // FIXME: add ice power to here
496 case PlayerStatus::GROWUP_BONUS:
502 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
504 if((*i)->name == spawnpoint) {
510 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
512 player->move(sp->pos);
515 camera->reset(player->get_pos());
519 Sector::get_best_spawn_point(Vector pos)
521 Vector best_reset_point = Vector(-1,-1);
523 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
525 if((*i)->name != "main")
527 if((*i)->pos.x > best_reset_point.x && (*i)->pos.x < pos.x)
528 best_reset_point = (*i)->pos;
531 return best_reset_point;
535 Sector::action(float elapsed_time)
537 player->check_bounds(camera);
540 for(GameObjects::iterator i = gameobjects.begin();
541 i != gameobjects.end(); ++i) {
542 GameObject* object = *i;
543 if(!object->is_valid())
546 object->action(elapsed_time);
549 /* Handle all possible collisions. */
552 update_game_objects();
556 Sector::update_game_objects()
558 /** cleanup marked objects */
559 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
560 i != gameobjects.end(); /* nothing */) {
561 if((*i)->is_valid() == false) {
562 Bullet* bullet = dynamic_cast<Bullet*> (*i);
565 std::remove(bullets.begin(), bullets.end(), bullet),
569 InteractiveObject* interactive_object =
570 dynamic_cast<InteractiveObject*> (*i);
571 if(interactive_object) {
572 interactive_objects.erase(
573 std::remove(interactive_objects.begin(), interactive_objects.end(),
574 interactive_object), interactive_objects.end());
578 i = gameobjects.erase(i);
584 /* add newly created objects */
585 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
586 i != gameobjects_new.end(); ++i)
588 Bullet* bullet = dynamic_cast<Bullet*> (*i);
590 bullets.push_back(bullet);
592 InteractiveObject* interactive_object
593 = dynamic_cast<InteractiveObject*> (*i);
594 if(interactive_object)
595 interactive_objects.push_back(interactive_object);
598 gameobjects.push_back(*i);
600 gameobjects_new.clear();
604 Sector::draw(DrawingContext& context)
606 context.push_transform();
607 context.set_translation(camera->get_translation());
609 for(GameObjects::iterator i = gameobjects.begin();
610 i != gameobjects.end(); ++i) {
611 GameObject* object = *i;
612 if(!object->is_valid())
615 object->draw(context);
618 context.pop_transform();
621 static const float DELTA = .001;
624 Sector::collision_tilemap(MovingObject* object, int depth)
628 std::cout << "Max collision depth reached.\n";
630 object->movement = Vector(0, 0);
634 // calculate rectangle where the object will move
636 if(object->get_movement().x >= 0) {
637 x1 = object->get_pos().x;
638 x2 = object->get_bbox().p2.x + object->get_movement().x;
640 x1 = object->get_pos().x + object->get_movement().x;
641 x2 = object->get_bbox().p2.x;
644 if(object->get_movement().y >= 0) {
645 y1 = object->get_pos().y;
646 y2 = object->get_bbox().p2.y + object->get_movement().y;
648 y1 = object->get_pos().y + object->get_movement().y;
649 y2 = object->get_bbox().p2.y;
652 // test with all tiles in this rectangle
653 int starttilex = int(x1-1) / 32;
654 int starttiley = int(y1-1) / 32;
655 int max_x = int(x2+1);
656 int max_y = int(y2+1);
658 CollisionHit temphit, hit;
659 Rectangle dest = object->get_bbox();
660 dest.move(object->movement);
661 hit.time = -1; // represents an invalid value
662 for(int x = starttilex; x*32 < max_x; ++x) {
663 for(int y = starttiley; y*32 < max_y; ++y) {
664 const Tile* tile = solids->get_tile(x, y);
667 if(!(tile->attributes & Tile::SOLID))
669 if((tile->attributes & Tile::UNISOLID) && object->movement.y < 0)
672 if(tile->attributes & Tile::SLOPE) { // slope tile
674 Vector p1(x*32, y*32);
675 Vector p2((x+1)*32, (y+1)*32);
678 triangle = AATriangle(p1, p2, AATriangle::SOUTHWEST);
681 triangle = AATriangle(p1, p2, AATriangle::NORTHEAST);
684 triangle = AATriangle(p1, p2, AATriangle::SOUTHEAST);
687 triangle = AATriangle(p1, p2, AATriangle::NORTHWEST);
690 printf("Invalid slope angle in tile %d !\n", tile->id);
694 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
696 if(temphit.time > hit.time)
699 } else { // normal rectangular tile
700 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
701 if(Collision::rectangle_rectangle(temphit, dest,
702 object->movement, rect)) {
703 if(temphit.time > hit.time)
710 // did we collide at all?
714 // call collision function
715 HitResponse response = object->collision(*solids, hit);
716 if(response == ABORT_MOVE) {
717 object->movement = Vector(0, 0);
720 if(response == FORCE_MOVE) {
723 // move out of collision and try again
724 object->movement += hit.normal * (hit.depth + DELTA);
725 collision_tilemap(object, depth+1);
729 Sector::collision_object(MovingObject* object1, MovingObject* object2)
732 Rectangle dest1 = object1->get_bbox();
733 dest1.move(object1->get_movement());
734 Rectangle dest2 = object2->get_bbox();
735 dest2.move(object2->get_movement());
737 Vector movement = object1->get_movement() - object2->get_movement();
738 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
739 HitResponse response1 = object1->collision(*object2, hit);
741 HitResponse response2 = object2->collision(*object1, hit);
743 if(response1 != CONTINUE) {
744 if(response1 == ABORT_MOVE)
745 object1->movement = Vector(0, 0);
746 if(response2 == CONTINUE)
747 object2->movement += hit.normal * (hit.depth + DELTA);
748 } else if(response2 != CONTINUE) {
749 if(response2 == ABORT_MOVE)
750 object2->movement = Vector(0, 0);
751 if(response1 == CONTINUE)
752 object1->movement += -hit.normal * (hit.depth + DELTA);
754 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
755 object2->movement += hit.normal * (hit.depth/2 + DELTA);
761 Sector::collision_handler()
763 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
764 i != gameobjects.end(); ++i) {
765 GameObject* gameobject = *i;
766 if(!gameobject->is_valid())
768 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
771 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
772 movingobject->bbox.move(movingobject->movement);
773 movingobject->movement = Vector(0, 0);
777 // collision with tilemap
778 if(! (movingobject->movement == Vector(0, 0)))
779 collision_tilemap(movingobject, 0);
781 // collision with other objects
782 for(std::vector<GameObject*>::iterator i2 = i+1;
783 i2 != gameobjects.end(); ++i2) {
784 GameObject* other_object = *i2;
785 if(!other_object->is_valid()
786 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
788 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
792 collision_object(movingobject, movingobject2);
795 movingobject->bbox.move(movingobject->get_movement());
796 movingobject->movement = Vector(0, 0);
801 Sector::add_score(const Vector& pos, int s)
803 global_stats.add_points(SCORE_STAT, s);
805 add_object(new FloatingText(pos, s));
809 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
811 if(player->got_power == Player::FIRE_POWER) {
812 if(bullets.size() > MAX_FIRE_BULLETS-1)
814 } else if(player->got_power == Player::ICE_POWER) {
815 if(bullets.size() > MAX_ICE_BULLETS-1)
819 Bullet* new_bullet = 0;
820 if(player->got_power == Player::FIRE_POWER)
821 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
822 else if(player->got_power == Player::ICE_POWER)
823 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
825 throw std::runtime_error("wrong bullet type.");
826 add_object(new_bullet);
828 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
834 Sector::add_smoke_cloud(const Vector& pos)
836 add_object(new SmokeCloud(pos));
841 Sector::add_floating_text(const Vector& pos, const std::string& text)
843 add_object(new FloatingText(pos, text));
852 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
854 song_path = (char *) malloc(sizeof(char) * datadir.length() +
855 strlen(song_title.c_str()) + 8 + 5);
856 song_subtitle = strdup(song_title.c_str());
857 strcpy(strstr(song_subtitle, "."), "\0");
858 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
859 song_subtitle, strstr(song_title.c_str(), "."));
860 if(!SoundManager::get()->exists_music(song_path)) {
861 level_song_fast = level_song;
863 level_song_fast = SoundManager::get()->load_music(song_path);
870 Sector::play_music(int type)
873 switch(currentmusic) {
875 SoundManager::get()->play_music(level_song_fast);
878 SoundManager::get()->play_music(level_song);
881 SoundManager::get()->play_music(herring_song);
884 SoundManager::get()->halt_music();
890 Sector::get_music_type()
896 Sector::get_total_badguys()
898 int total_badguys = 0;
900 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
902 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
907 return total_badguys;
911 Sector::inside(const Rectangle& rect) const
913 if(rect.p1.x > solids->get_width() * 32
914 || rect.p1.y > solids->get_height() * 32
915 || rect.p2.x < 0 || rect.p2.y < 0)