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 "trigger/door.h"
50 #include "object/bullet.h"
51 #include "badguy/jumpy.h"
52 #include "badguy/snowball.h"
53 #include "badguy/bouncing_snowball.h"
54 #include "badguy/flame.h"
55 #include "badguy/mriceblock.h"
56 #include "badguy/mrbomb.h"
57 #include "badguy/dispenser.h"
58 #include "trigger/sequence_trigger.h"
59 #include "trigger/secretarea_trigger.h"
61 Sector* Sector::_current = 0;
64 : gravity(10), player(0), solids(0), background(0), camera(0),
65 currentmusic(LEVEL_MUSIC)
67 song_title = "Mortimers_chipdisko.mod";
68 player = new Player();
74 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
79 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
87 Sector *Sector::create(const std::string& name, size_t width, size_t height)
89 Sector *sector = new Sector;
91 TileMap *background = new TileMap(LAYER_BACKGROUNDTILES, false, width, height);
92 TileMap *interactive = new TileMap(LAYER_TILES, true, width, height);
93 TileMap *foreground = new TileMap(LAYER_FOREGROUNDTILES, false, width, height);
94 sector->add_object(background);
95 sector->add_object(interactive);
96 sector->add_object(foreground);
97 sector->solids = interactive;
98 sector->camera = new Camera(sector);
99 sector->add_object(sector->camera);
100 sector->update_game_objects();
105 Sector::parseObject(const std::string& name, LispReader& reader)
107 if(name == "background") {
108 background = new Background(reader);
110 } else if(name == "camera") {
112 std::cerr << "Warning: More than 1 camera defined in sector.\n";
115 camera = new Camera(this);
116 camera->read(reader);
118 } else if(name == "tilemap") {
119 TileMap* tilemap = new TileMap(reader);
121 if(tilemap->is_solid()) {
123 std::cerr << "Warning multiple solid tilemaps in sector.\n";
130 } else if(name == "particles-snow") {
131 SnowParticleSystem* partsys = new SnowParticleSystem();
132 partsys->parse(reader);
134 } else if(name == "particles-clouds") {
135 CloudParticleSystem* partsys = new CloudParticleSystem();
136 partsys->parse(reader);
138 } else if(name == "door") {
139 return new Door(reader);
140 } else if(name == "secretarea") {
141 return new SecretAreaTrigger(reader);
142 } else if(name == "platform") {
143 return new Platform(reader);
144 } else if(name == "jumpy" || name == "money") {
145 return new Jumpy(reader);
146 } else if(name == "snowball") {
147 return new SnowBall(reader);
148 } else if(name == "bouncingsnowball") {
149 return new BouncingSnowball(reader);
150 } else if(name == "flame") {
151 return new Flame(reader);
152 } else if(name == "mriceblock") {
153 return new MrIceBlock(reader);
154 } else if(name == "mrbomb") {
155 return new MrBomb(reader);
156 } else if(name == "dispenser") {
157 return new Dispenser(reader);
160 else if(badguykind_from_string(name) != BAD_INVALID) {
161 return new BadGuy(badguykind_from_string(name), reader);
162 } else if(name == "trampoline") {
163 return new Trampoline(reader);
164 } else if(name == "flying-platform") {
165 return new FlyingPlatform(reader);
168 std::cerr << "Unknown object type '" << name << "'.\n";
173 Sector::parse(LispReader& lispreader)
177 for(lisp_object_t* cur = lispreader.get_lisp(); !lisp_nil_p(cur);
178 cur = lisp_cdr(cur)) {
179 std::string token = lisp_symbol(lisp_car(lisp_car(cur)));
180 // FIXME: doesn't handle empty data
181 lisp_object_t* data = lisp_car(lisp_cdr(lisp_car(cur)));
182 LispReader reader(lisp_cdr(lisp_car(cur)));
184 if(token == "name") {
185 name = lisp_string(data);
186 } else if(token == "gravity") {
187 gravity = lisp_real(data);
188 } else if(token == "music") {
189 song_title = lisp_string(data);
191 } else if(token == "spawn-points") {
192 SpawnPoint* sp = new SpawnPoint;
193 reader.read_string("name", sp->name);
194 reader.read_float("x", sp->pos.x);
195 reader.read_float("y", sp->pos.y);
196 spawnpoints.push_back(sp);
198 GameObject* object = parseObject(token, reader);
206 std::cerr << "sector '" << name << "' does not contain a camera.\n";
207 camera = new Camera(this);
211 throw std::runtime_error("sector does not contain a solid tile layer.");
215 Sector::parse_old_format(LispReader& reader)
220 reader.read_float("gravity", gravity);
222 std::string backgroundimage;
223 reader.read_string("background", backgroundimage);
225 reader.read_float("bkgd_speed", bgspeed);
228 Color bkgd_top, bkgd_bottom;
229 int r = 0, g = 0, b = 128;
230 reader.read_int("bkgd_red_top", r);
231 reader.read_int("bkgd_green_top", g);
232 reader.read_int("bkgd_blue_top", b);
237 reader.read_int("bkgd_red_bottom", r);
238 reader.read_int("bkgd_green_bottom", g);
239 reader.read_int("bkgd_blue_bottom", b);
241 bkgd_bottom.green = g;
242 bkgd_bottom.blue = b;
244 if(backgroundimage != "") {
245 background = new Background;
246 background->set_image(backgroundimage, bgspeed);
247 add_object(background);
249 background = new Background;
250 background->set_gradient(bkgd_top, bkgd_bottom);
251 add_object(background);
254 std::string particlesystem;
255 reader.read_string("particle_system", particlesystem);
256 if(particlesystem == "clouds")
257 add_object(new CloudParticleSystem());
258 else if(particlesystem == "snow")
259 add_object(new SnowParticleSystem());
261 Vector startpos(100, 170);
262 reader.read_float("start_pos_x", startpos.x);
263 reader.read_float("start_pos_y", startpos.y);
265 SpawnPoint* spawn = new SpawnPoint;
266 spawn->pos = startpos;
267 spawn->name = "main";
268 spawnpoints.push_back(spawn);
270 song_title = "Mortimers_chipdisko.mod";
271 reader.read_string("music", song_title);
274 int width, height = 15;
275 reader.read_int("width", width);
276 reader.read_int("height", height);
278 std::vector<unsigned int> tiles;
279 if(reader.read_int_vector("interactive-tm", tiles)
280 || reader.read_int_vector("tilemap", tiles)) {
281 TileMap* tilemap = new TileMap();
282 tilemap->set(width, height, tiles, LAYER_TILES, true);
289 if(reader.read_int_vector("background-tm", tiles)) {
290 TileMap* tilemap = new TileMap();
291 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
295 if(reader.read_int_vector("foreground-tm", tiles)) {
296 TileMap* tilemap = new TileMap();
297 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
301 // read reset-points (now spawn-points)
303 lisp_object_t* cur = 0;
304 if(reader.read_lisp("reset-points", cur)) {
305 while(!lisp_nil_p(cur)) {
306 lisp_object_t* data = lisp_car(cur);
307 LispReader reader(lisp_cdr(data));
310 if(reader.read_float("x", sp_pos.x) && reader.read_float("y", sp_pos.y))
312 SpawnPoint* sp = new SpawnPoint;
315 spawnpoints.push_back(sp);
325 lisp_object_t* cur = 0;
326 if(reader.read_lisp("objects", cur)) {
327 while(!lisp_nil_p(cur)) {
328 lisp_object_t* data = lisp_car(cur);
329 std::string object_type = lisp_symbol(lisp_car(data));
331 LispReader reader(lisp_cdr(data));
333 GameObject* object = parseObject(object_type, reader);
337 std::cerr << "Unknown object '" << object_type << "' in level.\n";
346 camera = new Camera(this);
351 Sector::fix_old_tiles()
354 for(size_t x=0; x < solids->get_width(); ++x) {
355 for(size_t y=0; y < solids->get_height(); ++y) {
356 const Tile* tile = solids->get_tile(x, y);
357 Vector pos(x*32, y*32);
359 if(tile->id == 112) {
360 add_object(new InvisibleBlock(pos));
361 solids->change(x, y, 0);
362 } else if(tile->attributes & Tile::COIN) {
363 add_object(new Coin(pos));
364 solids->change(x, y, 0);
365 } else if(tile->attributes & Tile::FULLBOX) {
366 add_object(new BonusBlock(pos, tile->data));
367 solids->change(x, y, 0);
368 } else if(tile->attributes & Tile::BRICK) {
369 add_object(new Brick(pos, tile->data));
370 solids->change(x, y, 0);
371 } else if(tile->attributes & Tile::GOAL) {
372 add_object(new SequenceTrigger(pos, "endsequence"));
373 solids->change(x, y, 0);
380 Sector::write(LispWriter& writer)
382 writer.write_string("name", name);
383 writer.write_float("gravity", gravity);
384 writer.write_string("music", song_title);
387 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
389 SpawnPoint* spawn = *i;
390 writer.start_list("spawn-points");
391 writer.write_string("name", spawn->name);
392 writer.write_float("x", spawn->pos.x);
393 writer.write_float("y", spawn->pos.y);
394 writer.end_list("spawn-points");
398 for(GameObjects::iterator i = gameobjects.begin();
399 i != gameobjects.end(); ++i) {
400 Serializable* serializable = dynamic_cast<Serializable*> (*i);
402 serializable->write(writer);
407 Sector::do_vertical_flip()
409 // remove or fix later
411 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
413 TileMap* tilemap = dynamic_cast<TileMap*> (*i);
416 tilemap->do_vertical_flip();
419 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
421 badguy->start_position.y = solids->get_height()*32 - badguy->start_position.y - 32;
422 Trampoline* trampoline = dynamic_cast<Trampoline*> (*i);
424 trampoline->base.y = solids->get_height()*32 - trampoline->base.y - 32;
425 FlyingPlatform* flying_platform = dynamic_cast<FlyingPlatform*> (*i);
427 flying_platform->base.y = solids->get_height()*32 - flying_platform->base.y - 32;
428 Door* door = dynamic_cast<Door*> (*i);
430 door->set_area(door->get_area().x, solids->get_height()*32 - door->get_area().y - 32);
433 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
435 SpawnPoint* spawn = *i;
436 spawn->pos.y = solids->get_height()*32 - spawn->pos.y - 32;
442 Sector::add_object(GameObject* object)
444 // make sure the object isn't already in the list
446 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
449 assert("object already added to sector" == 0);
452 for(GameObjects::iterator i = gameobjects_new.begin();
453 i != gameobjects_new.end(); ++i) {
455 assert("object already added to sector" == 0);
460 gameobjects_new.push_back(object);
464 Sector::activate(const std::string& spawnpoint)
468 // Apply bonuses from former levels
469 switch (player_status.bonus)
471 case PlayerStatus::NO_BONUS:
474 case PlayerStatus::FLOWER_BONUS:
475 player->got_power = Player::FIRE_POWER; // FIXME: add ice power to here
478 case PlayerStatus::GROWUP_BONUS:
484 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
486 if((*i)->name == spawnpoint) {
492 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
494 player->move(sp->pos);
497 camera->reset(player->get_pos());
501 Sector::get_best_spawn_point(Vector pos)
503 Vector best_reset_point = Vector(-1,-1);
505 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
507 if((*i)->name != "main")
509 if((*i)->pos.x > best_reset_point.x && (*i)->pos.x < pos.x)
510 best_reset_point = (*i)->pos;
513 return best_reset_point;
517 Sector::action(float elapsed_time)
519 player->check_bounds(camera);
522 for(GameObjects::iterator i = gameobjects.begin();
523 i != gameobjects.end(); ++i) {
524 GameObject* object = *i;
525 if(!object->is_valid())
528 object->action(elapsed_time);
531 /* Handle all possible collisions. */
534 update_game_objects();
538 Sector::update_game_objects()
540 /** cleanup marked objects */
541 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
542 i != gameobjects.end(); /* nothing */) {
543 if((*i)->is_valid() == false) {
544 Bullet* bullet = dynamic_cast<Bullet*> (*i);
547 std::remove(bullets.begin(), bullets.end(), bullet),
551 InteractiveObject* interactive_object =
552 dynamic_cast<InteractiveObject*> (*i);
553 if(interactive_object) {
554 interactive_objects.erase(
555 std::remove(interactive_objects.begin(), interactive_objects.end(),
556 interactive_object), interactive_objects.end());
560 i = gameobjects.erase(i);
566 /* add newly created objects */
567 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
568 i != gameobjects_new.end(); ++i)
570 Bullet* bullet = dynamic_cast<Bullet*> (*i);
572 bullets.push_back(bullet);
574 InteractiveObject* interactive_object
575 = dynamic_cast<InteractiveObject*> (*i);
576 if(interactive_object)
577 interactive_objects.push_back(interactive_object);
580 gameobjects.push_back(*i);
582 gameobjects_new.clear();
586 Sector::draw(DrawingContext& context)
588 context.push_transform();
589 context.set_translation(camera->get_translation());
591 for(GameObjects::iterator i = gameobjects.begin();
592 i != gameobjects.end(); ++i) {
593 GameObject* object = *i;
594 if(!object->is_valid())
597 object->draw(context);
600 context.pop_transform();
604 Sector::collision_tilemap(MovingObject* object, int depth)
608 std::cout << "Max collision depth reached.\n";
610 object->movement = Vector(0, 0);
614 // calculate rectangle where the object will move
616 if(object->get_movement().x >= 0) {
617 x1 = object->get_pos().x;
618 x2 = object->get_bbox().p2.x + object->get_movement().x;
620 x1 = object->get_pos().x + object->get_movement().x;
621 x2 = object->get_bbox().p2.x;
624 if(object->get_movement().y >= 0) {
625 y1 = object->get_pos().y;
626 y2 = object->get_bbox().p2.y + object->get_movement().y;
628 y1 = object->get_pos().y + object->get_movement().y;
629 y2 = object->get_bbox().p2.y;
632 // test with all tiles in this rectangle
633 int starttilex = int(x1-1) / 32;
634 int starttiley = int(y1-1) / 32;
635 int max_x = int(x2+1);
636 int max_y = int(y2+1);
638 CollisionHit temphit, hit;
639 Rectangle dest = object->get_bbox();
640 dest.move(object->movement);
641 hit.time = -1; // represents an invalid value
642 for(int x = starttilex; x*32 < max_x; ++x) {
643 for(int y = starttiley; y*32 < max_y; ++y) {
644 const Tile* tile = solids->get_tile(x, y);
647 if(!(tile->attributes & Tile::SOLID))
649 if((tile->attributes & Tile::UNISOLID) && object->movement.y < 0)
652 if(tile->attributes & Tile::SLOPE) { // slope tile
654 Vector p1(x*32, y*32);
655 Vector p2((x+1)*32, (y+1)*32);
658 triangle = AATriangle(p1, p2, AATriangle::SOUTHWEST);
661 triangle = AATriangle(p1, p2, AATriangle::NORTHEAST);
664 triangle = AATriangle(p1, p2, AATriangle::SOUTHEAST);
667 triangle = AATriangle(p1, p2, AATriangle::NORTHWEST);
670 printf("Invalid slope angle in tile %d !\n", tile->id);
674 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
676 if(temphit.time > hit.time)
679 } else { // normal rectangular tile
680 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
681 if(Collision::rectangle_rectangle(temphit, dest,
682 object->movement, rect)) {
683 if(temphit.time > hit.time)
690 // did we collide at all?
694 // call collision function
695 HitResponse response = object->collision(*solids, hit);
696 if(response == ABORT_MOVE) {
697 object->movement = Vector(0, 0);
700 if(response == FORCE_MOVE) {
703 // move out of collision and try again
704 object->movement += hit.normal * (hit.depth + .05);
705 collision_tilemap(object, depth+1);
709 Sector::collision_object(MovingObject* object1, MovingObject* object2)
712 Rectangle dest1 = object1->get_bbox();
713 dest1.move(object1->get_movement());
714 Rectangle dest2 = object2->get_bbox();
715 dest2.move(object2->get_movement());
717 Vector movement = object1->get_movement() - object2->get_movement();
718 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
719 HitResponse response1 = object1->collision(*object2, hit);
721 HitResponse response2 = object2->collision(*object1, hit);
723 if(response1 != CONTINUE) {
724 if(response1 == ABORT_MOVE)
725 object1->movement = Vector(0, 0);
726 if(response2 == CONTINUE)
727 object2->movement += hit.normal * (hit.depth + .05);
728 } else if(response2 != CONTINUE) {
729 if(response2 == ABORT_MOVE)
730 object2->movement = Vector(0, 0);
731 if(response1 == CONTINUE)
732 object1->movement += -hit.normal * (hit.depth + .05);
734 object1->movement += -hit.normal * (hit.depth/2 + .05);
735 object2->movement += hit.normal * (hit.depth/2 + .05);
741 Sector::collision_handler()
743 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
744 i != gameobjects.end(); ++i) {
745 GameObject* gameobject = *i;
746 if(!gameobject->is_valid()
747 || gameobject->get_flags() & GameObject::FLAG_NO_COLLDET)
749 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
753 // collision with tilemap
754 if(! (movingobject->movement == Vector(0, 0)))
755 collision_tilemap(movingobject, 0);
757 // collision with other objects
758 for(std::vector<GameObject*>::iterator i2 = i+1;
759 i2 != gameobjects.end(); ++i2) {
760 GameObject* other_object = *i2;
761 if(!other_object->is_valid()
762 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
764 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
768 collision_object(movingobject, movingobject2);
771 movingobject->bbox.move(movingobject->get_movement());
772 movingobject->movement = Vector(0, 0);
777 Sector::add_score(const Vector& pos, int s)
779 global_stats.add_points(SCORE_STAT, s);
781 add_object(new FloatingText(pos, s));
785 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
787 if(player->got_power == Player::FIRE_POWER) {
788 if(bullets.size() > MAX_FIRE_BULLETS-1)
790 } else if(player->got_power == Player::ICE_POWER) {
791 if(bullets.size() > MAX_ICE_BULLETS-1)
795 Bullet* new_bullet = 0;
796 if(player->got_power == Player::FIRE_POWER)
797 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
798 else if(player->got_power == Player::ICE_POWER)
799 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
801 throw std::runtime_error("wrong bullet type.");
802 add_object(new_bullet);
804 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
810 Sector::add_smoke_cloud(const Vector& pos)
812 add_object(new SmokeCloud(pos));
817 Sector::add_floating_text(const Vector& pos, const std::string& text)
819 add_object(new FloatingText(pos, text));
828 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
830 song_path = (char *) malloc(sizeof(char) * datadir.length() +
831 strlen(song_title.c_str()) + 8 + 5);
832 song_subtitle = strdup(song_title.c_str());
833 strcpy(strstr(song_subtitle, "."), "\0");
834 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
835 song_subtitle, strstr(song_title.c_str(), "."));
836 if(!SoundManager::get()->exists_music(song_path)) {
837 level_song_fast = level_song;
839 level_song_fast = SoundManager::get()->load_music(song_path);
846 Sector::play_music(int type)
849 switch(currentmusic) {
851 SoundManager::get()->play_music(level_song_fast);
854 SoundManager::get()->play_music(level_song);
857 SoundManager::get()->play_music(herring_song);
860 SoundManager::get()->halt_music();
866 Sector::get_music_type()
872 Sector::get_total_badguys()
874 int total_badguys = 0;
876 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
878 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
883 return total_badguys;
887 Sector::inside(const Rectangle& rect) const
889 if(rect.p1.x > solids->get_width() * 32
890 || rect.p1.y > solids->get_height() * 32
891 || rect.p2.x < 0 || rect.p2.y < 0)