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"
35 #include "background.h"
36 #include "particlesystem.h"
39 #include "audio/sound_manager.h"
41 #include "resources.h"
42 #include "statistics.h"
43 #include "special/collision.h"
44 #include "math/rectangle.h"
45 #include "math/aatriangle.h"
46 #include "object/coin.h"
47 #include "object/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 "trigger/sequence_trigger.h"
59 Sector* Sector::_current = 0;
62 : gravity(10), player(0), solids(0), background(0), camera(0),
63 currentmusic(LEVEL_MUSIC)
65 song_title = "Mortimers_chipdisko.mod";
66 player = new Player();
72 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
77 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
85 Sector *Sector::create(const std::string& name, size_t width, size_t height)
87 Sector *sector = new Sector;
89 TileMap *background = new TileMap(LAYER_BACKGROUNDTILES, false, width, height);
90 TileMap *interactive = new TileMap(LAYER_TILES, true, width, height);
91 TileMap *foreground = new TileMap(LAYER_FOREGROUNDTILES, false, width, height);
92 sector->add_object(background);
93 sector->add_object(interactive);
94 sector->add_object(foreground);
95 sector->solids = interactive;
96 sector->camera = new Camera(sector);
97 sector->add_object(sector->camera);
98 sector->update_game_objects();
103 Sector::parseObject(const std::string& name, LispReader& reader)
105 if(name == "background") {
106 background = new Background(reader);
108 } else if(name == "camera") {
110 std::cerr << "Warning: More than 1 camera defined in sector.\n";
113 camera = new Camera(this);
114 camera->read(reader);
116 } else if(name == "tilemap") {
117 TileMap* tilemap = new TileMap(reader);
119 if(tilemap->is_solid()) {
121 std::cerr << "Warning multiple solid tilemaps in sector.\n";
127 } else if(name == "particles-snow") {
128 SnowParticleSystem* partsys = new SnowParticleSystem();
129 partsys->parse(reader);
131 } else if(name == "particles-clouds") {
132 CloudParticleSystem* partsys = new CloudParticleSystem();
133 partsys->parse(reader);
135 } else if(name == "door") {
136 return new Door(reader);
137 } else if(name == "platform") {
138 return new Platform(reader);
139 } else if(name == "jumpy" || name == "money") {
140 return new Jumpy(reader);
141 } else if(name == "snowball") {
142 return new SnowBall(reader);
143 } else if(name == "bouncingsnowball") {
144 return new BouncingSnowball(reader);
145 } else if(name == "flame") {
146 return new Flame(reader);
147 } else if(name == "mriceblock") {
148 return new MrIceBlock(reader);
149 } else if(name == "mrbomb") {
150 return new MrBomb(reader);
153 else if(badguykind_from_string(name) != BAD_INVALID) {
154 return new BadGuy(badguykind_from_string(name), reader);
155 } else if(name == "trampoline") {
156 return new Trampoline(reader);
157 } else if(name == "flying-platform") {
158 return new FlyingPlatform(reader);
161 std::cerr << "Unknown object type '" << name << "'.\n";
166 Sector::parse(LispReader& lispreader)
170 for(lisp_object_t* cur = lispreader.get_lisp(); !lisp_nil_p(cur);
171 cur = lisp_cdr(cur)) {
172 std::string token = lisp_symbol(lisp_car(lisp_car(cur)));
173 // FIXME: doesn't handle empty data
174 lisp_object_t* data = lisp_car(lisp_cdr(lisp_car(cur)));
175 LispReader reader(lisp_cdr(lisp_car(cur)));
177 if(token == "name") {
178 name = lisp_string(data);
179 } else if(token == "gravity") {
180 gravity = lisp_real(data);
181 } else if(token == "music") {
182 song_title = lisp_string(data);
184 } else if(token == "spawn-points") {
185 SpawnPoint* sp = new SpawnPoint;
186 reader.read_string("name", sp->name);
187 reader.read_float("x", sp->pos.x);
188 reader.read_float("y", sp->pos.y);
189 spawnpoints.push_back(sp);
191 GameObject* object = parseObject(token, reader);
199 std::cerr << "sector '" << name << "' does not contain a camera.\n";
200 camera = new Camera(this);
204 throw std::runtime_error("sector does not contain a solid tile layer.");
208 Sector::parse_old_format(LispReader& reader)
213 reader.read_float("gravity", gravity);
215 std::string backgroundimage;
216 reader.read_string("background", backgroundimage);
218 reader.read_float("bkgd_speed", bgspeed);
221 Color bkgd_top, bkgd_bottom;
222 int r = 0, g = 0, b = 128;
223 reader.read_int("bkgd_red_top", r);
224 reader.read_int("bkgd_green_top", g);
225 reader.read_int("bkgd_blue_top", b);
230 reader.read_int("bkgd_red_bottom", r);
231 reader.read_int("bkgd_green_bottom", g);
232 reader.read_int("bkgd_blue_bottom", b);
234 bkgd_bottom.green = g;
235 bkgd_bottom.blue = b;
237 if(backgroundimage != "") {
238 background = new Background;
239 background->set_image(backgroundimage, bgspeed);
240 add_object(background);
242 background = new Background;
243 background->set_gradient(bkgd_top, bkgd_bottom);
244 add_object(background);
247 std::string particlesystem;
248 reader.read_string("particle_system", particlesystem);
249 if(particlesystem == "clouds")
250 add_object(new CloudParticleSystem());
251 else if(particlesystem == "snow")
252 add_object(new SnowParticleSystem());
254 Vector startpos(100, 170);
255 reader.read_float("start_pos_x", startpos.x);
256 reader.read_float("start_pos_y", startpos.y);
258 SpawnPoint* spawn = new SpawnPoint;
259 spawn->pos = startpos;
260 spawn->name = "main";
261 spawnpoints.push_back(spawn);
263 song_title = "Mortimers_chipdisko.mod";
264 reader.read_string("music", song_title);
267 int width, height = 15;
268 reader.read_int("width", width);
269 reader.read_int("height", height);
271 std::vector<unsigned int> tiles;
272 if(reader.read_int_vector("interactive-tm", tiles)
273 || reader.read_int_vector("tilemap", tiles)) {
274 TileMap* tilemap = new TileMap();
275 tilemap->set(width, height, tiles, LAYER_TILES, true);
280 for(size_t x=0; x < solids->get_width(); ++x) {
281 for(size_t y=0; y < solids->get_height(); ++y) {
282 const Tile* tile = solids->get_tile(x, y);
284 if(tile->attributes & Tile::COIN) {
285 Coin* coin = new Coin(Vector(x*32, y*32));
287 solids->change(x, y, 0);
288 } else if(tile->attributes & Tile::FULLBOX) {
289 BonusBlock* block = new BonusBlock(Vector(x*32, y*32), tile->data);
291 solids->change(x, y, 0);
292 } else if(tile->attributes & Tile::BRICK) {
293 Brick* brick = new Brick(Vector(x*32, y*32), tile->data);
295 solids->change(x, y, 0);
296 } else if(tile->attributes & Tile::GOAL) {
297 SequenceTrigger* trigger = new SequenceTrigger(Vector(x*32, y*32),
300 solids->change(x, y, 0);
306 if(reader.read_int_vector("background-tm", tiles)) {
307 TileMap* tilemap = new TileMap();
308 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
312 if(reader.read_int_vector("foreground-tm", tiles)) {
313 TileMap* tilemap = new TileMap();
314 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
318 // read reset-points (now spawn-points)
320 lisp_object_t* cur = 0;
321 if(reader.read_lisp("reset-points", cur)) {
322 while(!lisp_nil_p(cur)) {
323 lisp_object_t* data = lisp_car(cur);
324 LispReader reader(lisp_cdr(data));
327 if(reader.read_float("x", sp_pos.x) && reader.read_float("y", sp_pos.y))
329 SpawnPoint* sp = new SpawnPoint;
332 spawnpoints.push_back(sp);
342 lisp_object_t* cur = 0;
343 if(reader.read_lisp("objects", cur)) {
344 while(!lisp_nil_p(cur)) {
345 lisp_object_t* data = lisp_car(cur);
346 std::string object_type = lisp_symbol(lisp_car(data));
348 LispReader reader(lisp_cdr(data));
350 GameObject* object = parseObject(object_type, reader);
354 std::cerr << "Unknown object '" << object_type << "' in level.\n";
363 camera = new Camera(this);
368 Sector::write(LispWriter& writer)
370 writer.write_string("name", name);
371 writer.write_float("gravity", gravity);
372 writer.write_string("music", song_title);
375 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
377 SpawnPoint* spawn = *i;
378 writer.start_list("spawn-points");
379 writer.write_string("name", spawn->name);
380 writer.write_float("x", spawn->pos.x);
381 writer.write_float("y", spawn->pos.y);
382 writer.end_list("spawn-points");
386 for(GameObjects::iterator i = gameobjects.begin();
387 i != gameobjects.end(); ++i) {
388 Serializable* serializable = dynamic_cast<Serializable*> (*i);
390 serializable->write(writer);
395 Sector::do_vertical_flip()
397 // remove or fix later
399 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
401 TileMap* tilemap = dynamic_cast<TileMap*> (*i);
404 tilemap->do_vertical_flip();
407 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
409 badguy->start_position.y = solids->get_height()*32 - badguy->start_position.y - 32;
410 Trampoline* trampoline = dynamic_cast<Trampoline*> (*i);
412 trampoline->base.y = solids->get_height()*32 - trampoline->base.y - 32;
413 FlyingPlatform* flying_platform = dynamic_cast<FlyingPlatform*> (*i);
415 flying_platform->base.y = solids->get_height()*32 - flying_platform->base.y - 32;
416 Door* door = dynamic_cast<Door*> (*i);
418 door->set_area(door->get_area().x, solids->get_height()*32 - door->get_area().y - 32);
421 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
423 SpawnPoint* spawn = *i;
424 spawn->pos.y = solids->get_height()*32 - spawn->pos.y - 32;
430 Sector::add_object(GameObject* object)
432 // make sure the object isn't already in the list
434 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
437 assert("object already added to sector" == 0);
440 for(GameObjects::iterator i = gameobjects_new.begin();
441 i != gameobjects_new.end(); ++i) {
443 assert("object already added to sector" == 0);
448 gameobjects_new.push_back(object);
452 Sector::activate(const std::string& spawnpoint)
456 // Apply bonuses from former levels
457 switch (player_status.bonus)
459 case PlayerStatus::NO_BONUS:
462 case PlayerStatus::FLOWER_BONUS:
463 player->got_power = Player::FIRE_POWER; // FIXME: add ice power to here
466 case PlayerStatus::GROWUP_BONUS:
472 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
474 if((*i)->name == spawnpoint) {
480 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
482 player->move(sp->pos);
485 camera->reset(player->get_pos());
489 Sector::get_best_spawn_point(Vector pos)
491 Vector best_reset_point = Vector(-1,-1);
493 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
495 if((*i)->name != "main")
497 if((*i)->pos.x > best_reset_point.x && (*i)->pos.x < pos.x)
498 best_reset_point = (*i)->pos;
501 return best_reset_point;
505 Sector::action(float elapsed_time)
507 player->check_bounds(camera);
510 for(GameObjects::iterator i = gameobjects.begin();
511 i != gameobjects.end(); ++i) {
512 GameObject* object = *i;
513 if(!object->is_valid())
516 object->action(elapsed_time);
519 /* Handle all possible collisions. */
522 update_game_objects();
526 Sector::update_game_objects()
528 /** cleanup marked objects */
529 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
530 i != gameobjects.end(); /* nothing */) {
531 if((*i)->is_valid() == false) {
532 Bullet* bullet = dynamic_cast<Bullet*> (*i);
535 std::remove(bullets.begin(), bullets.end(), bullet),
539 InteractiveObject* interactive_object =
540 dynamic_cast<InteractiveObject*> (*i);
541 if(interactive_object) {
542 interactive_objects.erase(
543 std::remove(interactive_objects.begin(), interactive_objects.end(),
544 interactive_object), interactive_objects.end());
548 i = gameobjects.erase(i);
554 /* add newly created objects */
555 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
556 i != gameobjects_new.end(); ++i)
558 Bullet* bullet = dynamic_cast<Bullet*> (*i);
560 bullets.push_back(bullet);
562 InteractiveObject* interactive_object
563 = dynamic_cast<InteractiveObject*> (*i);
564 if(interactive_object)
565 interactive_objects.push_back(interactive_object);
568 gameobjects.push_back(*i);
570 gameobjects_new.clear();
574 Sector::draw(DrawingContext& context)
576 context.push_transform();
577 context.set_translation(camera->get_translation());
579 for(GameObjects::iterator i = gameobjects.begin();
580 i != gameobjects.end(); ++i) {
581 GameObject* object = *i;
582 if(!object->is_valid())
585 object->draw(context);
588 context.pop_transform();
592 Sector::collision_tilemap(MovingObject* object, int depth)
596 std::cout << "Max collision depth reached.\n";
598 object->movement = Vector(0, 0);
602 // calculate rectangle where the object will move
604 if(object->get_movement().x >= 0) {
605 x1 = object->get_pos().x;
606 x2 = object->get_bbox().p2.x + object->get_movement().x;
608 x1 = object->get_pos().x + object->get_movement().x;
609 x2 = object->get_bbox().p2.x;
612 if(object->get_movement().y >= 0) {
613 y1 = object->get_pos().y;
614 y2 = object->get_bbox().p2.y + object->get_movement().y;
616 y1 = object->get_pos().y + object->get_movement().y;
617 y2 = object->get_bbox().p2.y;
620 // test with all tiles in this rectangle
621 int starttilex = int(x1-1) / 32;
622 int starttiley = int(y1-1) / 32;
623 int max_x = int(x2+1);
624 int max_y = int(y2+1);
626 CollisionHit temphit, hit;
627 Rectangle dest = object->get_bbox();
628 dest.move(object->movement);
630 for(int x = starttilex; x*32 < max_x; ++x) {
631 for(int y = starttiley; y*32 < max_y; ++y) {
632 const Tile* tile = solids->get_tile(x, y);
635 if(!(tile->attributes & Tile::SOLID))
637 if((tile->attributes & Tile::UNISOLID) && object->movement.y < 0)
640 if(tile->attributes & Tile::SLOPE) { // slope tile
642 Vector p1(x*32, y*32);
643 Vector p2((x+1)*32, (y+1)*32);
646 triangle = AATriangle(p1, p2, AATriangle::SOUTHWEST);
649 triangle = AATriangle(p1, p2, AATriangle::NORTHEAST);
652 triangle = AATriangle(p1, p2, AATriangle::SOUTHEAST);
655 triangle = AATriangle(p1, p2, AATriangle::NORTHWEST);
658 printf("Invalid slope angle in tile %d !\n", tile->id);
662 if(Collision::rectangle_aatriangle(temphit, dest, triangle)) {
663 if(temphit.depth > hit.depth)
666 } else { // normal rectangular tile
667 Rectangle rect(x*32, y*32, (x+1)*32, (y+1)*32);
668 if(Collision::rectangle_rectangle(temphit, dest, rect)) {
669 if(temphit.depth > hit.depth)
676 // did we collide at all?
680 // call collision function
681 HitResponse response = object->collision(*solids, hit);
682 if(response == ABORT_MOVE) {
683 object->movement = Vector(0, 0);
686 if(response == FORCE_MOVE) {
689 // move out of collision and try again
690 object->movement += hit.normal * (hit.depth + .001);
691 collision_tilemap(object, depth+1);
695 Sector::collision_object(MovingObject* object1, MovingObject* object2)
698 Rectangle dest1 = object1->get_bbox();
699 dest1.move(object1->get_movement());
700 Rectangle dest2 = object2->get_bbox();
701 dest2.move(object2->get_movement());
702 if(Collision::rectangle_rectangle(hit, dest1, dest2)) {
703 HitResponse response = object1->collision(*object2, hit);
704 if(response == ABORT_MOVE) {
705 object1->movement = Vector(0, 0);
706 } else if(response == CONTINUE) {
707 object1->movement += hit.normal * (hit.depth/2 + .001);
710 response = object2->collision(*object1, hit);
711 if(response == ABORT_MOVE) {
712 object2->movement = Vector(0, 0);
713 } else if(response == CONTINUE) {
714 object2->movement += hit.normal * (hit.depth/2 + .001);
720 Sector::collision_handler()
722 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
723 i != gameobjects.end(); ++i) {
724 GameObject* gameobject = *i;
725 if(!gameobject->is_valid()
726 || gameobject->get_flags() & GameObject::FLAG_NO_COLLDET)
728 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
732 // collision with tilemap
733 if(! (movingobject->movement == Vector(0, 0)))
734 collision_tilemap(movingobject, 0);
736 // collision with other objects
737 for(std::vector<GameObject*>::iterator i2 = i+1;
738 i2 != gameobjects.end(); ++i2) {
739 GameObject* other_object = *i2;
740 if(!other_object->is_valid()
741 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
743 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
747 collision_object(movingobject, movingobject2);
750 movingobject->bbox.move(movingobject->get_movement());
751 movingobject->movement = Vector(0, 0);
756 Sector::add_score(const Vector& pos, int s)
758 global_stats.add_points(SCORE_STAT, s);
760 add_object(new FloatingText(pos, s));
764 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
766 if(player->got_power == Player::FIRE_POWER) {
767 if(bullets.size() > MAX_FIRE_BULLETS-1)
769 } else if(player->got_power == Player::ICE_POWER) {
770 if(bullets.size() > MAX_ICE_BULLETS-1)
774 Bullet* new_bullet = 0;
775 if(player->got_power == Player::FIRE_POWER)
776 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
777 else if(player->got_power == Player::ICE_POWER)
778 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
780 throw std::runtime_error("wrong bullet type.");
781 add_object(new_bullet);
783 SoundManager::get()->play_sound(IDToSound(SND_SHOOT));
789 Sector::add_smoke_cloud(const Vector& pos)
791 add_object(new SmokeCloud(pos));
796 Sector::add_particles(const Vector& epicenter, int min_angle, int max_angle, const Vector& initial_velocity, const Vector& acceleration, int number, Color color, int size, int life_time, int drawing_layer)
798 add_object(new Particles(epicenter, min_angle, max_angle, initial_velocity, acceleration, number, color, size, life_time, drawing_layer));
803 Sector::add_floating_text(const Vector& pos, const std::string& text)
805 add_object(new FloatingText(pos, text));
814 level_song = SoundManager::get()->load_music(datadir + "/music/" + song_title);
816 song_path = (char *) malloc(sizeof(char) * datadir.length() +
817 strlen(song_title.c_str()) + 8 + 5);
818 song_subtitle = strdup(song_title.c_str());
819 strcpy(strstr(song_subtitle, "."), "\0");
820 sprintf(song_path, "%s/music/%s-fast%s", datadir.c_str(),
821 song_subtitle, strstr(song_title.c_str(), "."));
822 if(!SoundManager::get()->exists_music(song_path)) {
823 level_song_fast = level_song;
825 level_song_fast = SoundManager::get()->load_music(song_path);
832 Sector::play_music(int type)
835 switch(currentmusic) {
837 SoundManager::get()->play_music(level_song_fast);
840 SoundManager::get()->play_music(level_song);
843 SoundManager::get()->play_music(herring_song);
846 SoundManager::get()->halt_music();
852 Sector::get_music_type()
858 Sector::get_total_badguys()
860 int total_badguys = 0;
862 for(GameObjects::iterator i = gameobjects_new.begin(); i != gameobjects_new.end(); ++i)
864 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
869 return total_badguys;
873 Sector::inside(const Rectangle& rect) const
875 if(rect.p1.x > solids->get_width() * 32
876 || rect.p1.y > solids->get_height() * 32
877 || rect.p2.x < 0 || rect.p2.y < 0)