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.
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"
43 #include "game_session.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 "collision.h"
50 #include "math/rect.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"
59 #include "player_status.h"
60 #include "scripting/script_interpreter.h"
64 Sector* Sector::_current = 0;
67 : gravity(10), player(0), solids(0), camera(0),
68 interpreter(0), currentmusic(LEVEL_MUSIC)
70 song_title = "Mortimers_chipdisko.mod";
71 player = new Player(&player_status);
74 grid = new CollisionGrid(32000, 32000);
79 update_game_objects();
80 assert(gameobjects_new.size() == 0);
84 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
89 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
98 Sector::parse_object(const std::string& name, const lisp::Lisp& reader)
100 if(name == "camera") {
101 Camera* camera = new Camera(this);
102 camera->parse(reader);
104 } else if(name == "particles-snow") {
105 SnowParticleSystem* partsys = new SnowParticleSystem();
106 partsys->parse(reader);
108 } else if(name == "particles-rain") {
109 RainParticleSystem* partsys = new RainParticleSystem();
110 partsys->parse(reader);
112 } else if(name == "particles-clouds") {
113 CloudParticleSystem* partsys = new CloudParticleSystem();
114 partsys->parse(reader);
116 } else if(name == "money") { // for compatibility with old maps
117 return new Jumpy(reader);
121 return create_object(name, reader);
122 } catch(std::exception& e) {
123 std::cerr << e.what() << "\n";
130 Sector::parse(const lisp::Lisp& sector)
134 lisp::ListIterator iter(§or);
136 const std::string& token = iter.item();
137 if(token == "name") {
138 iter.value()->get(name);
139 } else if(token == "gravity") {
140 iter.value()->get(gravity);
141 } else if(token == "music") {
142 iter.value()->get(song_title);
144 } else if(token == "spawnpoint") {
145 const lisp::Lisp* spawnpoint_lisp = iter.lisp();
147 SpawnPoint* sp = new SpawnPoint;
148 spawnpoint_lisp->get("name", sp->name);
149 spawnpoint_lisp->get("x", sp->pos.x);
150 spawnpoint_lisp->get("y", sp->pos.y);
151 spawnpoints.push_back(sp);
152 } else if(token == "init-script") {
153 iter.value()->get(init_script);
155 GameObject* object = parse_object(token, *(iter.lisp()));
162 update_game_objects();
165 std::cerr << "sector '" << name << "' does not contain a camera.\n";
166 update_game_objects();
167 add_object(new Camera(this));
170 throw std::runtime_error("sector does not contain a solid tile layer.");
172 update_game_objects();
176 Sector::parse_old_format(const lisp::Lisp& reader)
181 reader.get("gravity", gravity);
183 std::string backgroundimage;
184 reader.get("background", backgroundimage);
186 reader.get("bkgd_speed", bgspeed);
189 Color bkgd_top, bkgd_bottom;
190 int r = 0, g = 0, b = 128;
191 reader.get("bkgd_red_top", r);
192 reader.get("bkgd_green_top", g);
193 reader.get("bkgd_blue_top", b);
198 reader.get("bkgd_red_bottom", r);
199 reader.get("bkgd_green_bottom", g);
200 reader.get("bkgd_blue_bottom", b);
202 bkgd_bottom.green = g;
203 bkgd_bottom.blue = b;
205 if(backgroundimage != "") {
206 Background* background = new Background;
207 background->set_image(backgroundimage, bgspeed);
208 add_object(background);
210 Background* background = new Background;
211 background->set_gradient(bkgd_top, bkgd_bottom);
212 add_object(background);
215 std::string particlesystem;
216 reader.get("particle_system", particlesystem);
217 if(particlesystem == "clouds")
218 add_object(new CloudParticleSystem());
219 else if(particlesystem == "snow")
220 add_object(new SnowParticleSystem());
221 else if(particlesystem == "rain")
222 add_object(new RainParticleSystem());
224 Vector startpos(100, 170);
225 reader.get("start_pos_x", startpos.x);
226 reader.get("start_pos_y", startpos.y);
228 SpawnPoint* spawn = new SpawnPoint;
229 spawn->pos = startpos;
230 spawn->name = "main";
231 spawnpoints.push_back(spawn);
233 song_title = "Mortimers_chipdisko.mod";
234 reader.get("music", song_title);
237 int width, height = 15;
238 reader.get("width", width);
239 reader.get("height", height);
241 std::vector<unsigned int> tiles;
242 if(reader.get_vector("interactive-tm", tiles)
243 || reader.get_vector("tilemap", tiles)) {
244 TileMap* tilemap = new TileMap();
245 tilemap->set(width, height, tiles, LAYER_TILES, true);
249 if(reader.get_vector("background-tm", tiles)) {
250 TileMap* tilemap = new TileMap();
251 tilemap->set(width, height, tiles, LAYER_BACKGROUNDTILES, false);
255 if(reader.get_vector("foreground-tm", tiles)) {
256 TileMap* tilemap = new TileMap();
257 tilemap->set(width, height, tiles, LAYER_FOREGROUNDTILES, false);
261 // read reset-points (now spawn-points)
262 const lisp::Lisp* resetpoints = reader.get_lisp("reset-points");
264 lisp::ListIterator iter(resetpoints);
266 if(iter.item() == "point") {
268 if(reader.get("x", sp_pos.x) && reader.get("y", sp_pos.y))
270 SpawnPoint* sp = new SpawnPoint;
273 spawnpoints.push_back(sp);
276 std::cerr << "Unknown token '" << iter.item() << "' in reset-points.\n";
282 const lisp::Lisp* objects = reader.get_lisp("objects");
284 lisp::ListIterator iter(objects);
286 GameObject* object = parse_object(iter.item(), *(iter.lisp()));
290 std::cerr << "Unknown object '" << iter.item() << "' in level.\n";
296 Camera* camera = new Camera(this);
299 update_game_objects();
301 update_game_objects();
303 throw std::runtime_error("sector does not contain a solid tile layer.");
307 Sector::fix_old_tiles()
310 for(size_t x=0; x < solids->get_width(); ++x) {
311 for(size_t y=0; y < solids->get_height(); ++y) {
312 const Tile* tile = solids->get_tile(x, y);
313 Vector pos(x*32, y*32);
315 if(tile->getID() == 112) {
316 add_object(new InvisibleBlock(pos));
317 solids->change(x, y, 0);
318 } else if(tile->getID() == 295) {
319 add_object(new Spike(pos, Spike::NORTH));
320 solids->change(x, y, 0);
321 } else if(tile->getID() == 296) {
322 add_object(new Spike(pos, Spike::EAST));
323 solids->change(x, y, 0);
324 } else if(tile->getID() == 297) {
325 add_object(new Spike(pos, Spike::SOUTH));
326 solids->change(x, y, 0);
327 } else if(tile->getID() == 298) {
328 add_object(new Spike(pos, Spike::WEST));
329 solids->change(x, y, 0);
330 } else if(tile->getAttributes() & Tile::COIN) {
331 add_object(new Coin(pos));
332 solids->change(x, y, 0);
333 } else if(tile->getAttributes() & Tile::FULLBOX) {
334 add_object(new BonusBlock(pos, tile->getData()));
335 solids->change(x, y, 0);
336 } else if(tile->getAttributes() & Tile::BRICK) {
337 add_object(new Brick(pos, tile->getData()));
338 solids->change(x, y, 0);
339 } else if(tile->getAttributes() & Tile::GOAL) {
340 std::string sequence = tile->getData() == 0 ? "endsequence" : "stoptux";
341 add_object(new SequenceTrigger(pos, sequence));
342 solids->change(x, y, 0);
349 Sector::write(lisp::Writer& writer)
351 writer.write_string("name", name);
352 writer.write_float("gravity", gravity);
353 writer.write_string("music", song_title);
356 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
358 SpawnPoint* spawn = *i;
359 writer.start_list("spawn-points");
360 writer.write_string("name", spawn->name);
361 writer.write_float("x", spawn->pos.x);
362 writer.write_float("y", spawn->pos.y);
363 writer.end_list("spawn-points");
367 for(GameObjects::iterator i = gameobjects.begin();
368 i != gameobjects.end(); ++i) {
369 Serializable* serializable = dynamic_cast<Serializable*> (*i);
371 serializable->write(writer);
376 Sector::add_object(GameObject* object)
378 // make sure the object isn't already in the list
380 for(GameObjects::iterator i = gameobjects.begin(); i != gameobjects.end();
383 assert("object already added to sector" == 0);
386 for(GameObjects::iterator i = gameobjects_new.begin();
387 i != gameobjects_new.end(); ++i) {
389 assert("object already added to sector" == 0);
394 gameobjects_new.push_back(object);
398 Sector::activate(const std::string& spawnpoint)
401 for(SpawnPoints::iterator i = spawnpoints.begin(); i != spawnpoints.end();
403 if((*i)->name == spawnpoint) {
409 std::cerr << "Spawnpoint '" << spawnpoint << "' not found.\n";
410 if(spawnpoint != "main") {
413 activate(Vector(0, 0));
420 if(init_script != "") {
422 // TODO we should keep the interpreter across sessions (or some variables)
423 // so that you can store information across levels/sectors...
426 interpreter = new ScriptInterpreter();
427 std::string sourcename = std::string("Sector(") + name + ") - init";
428 std::istringstream in(init_script);
429 printf("Load script.\n");
430 interpreter->load_script(in, sourcename);
431 printf("run script.\n");
432 interpreter->run_script();
433 } catch(std::exception& e) {
434 std::cerr << "Couldn't execute init script: " << e.what() << "\n";
440 Sector::activate(const Vector& player_pos)
444 player->move(player_pos);
445 camera->reset(player->get_pos());
449 Sector::get_active_region()
452 camera->get_translation() - Vector(1600, 1200),
453 camera->get_translation() + Vector(1600, 1200));
457 Sector::action(float elapsed_time)
459 player->check_bounds(camera);
462 CollisionGridIterator iter(*grid, get_active_region());
463 while(MovingObject* object = iter.next()) {
464 if(!object->is_valid())
467 object->action(elapsed_time);
471 for(GameObjects::iterator i = gameobjects.begin();
472 i != gameobjects.end(); ++i) {
473 GameObject* object = *i;
474 if(!object->is_valid())
477 object->action(elapsed_time);
481 /* Handle all possible collisions. */
483 update_game_objects();
487 Sector::update_game_objects()
489 /** cleanup marked objects */
490 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
491 i != gameobjects.end(); /* nothing */) {
492 GameObject* object = *i;
494 if(object->is_valid()) {
499 Bullet* bullet = dynamic_cast<Bullet*> (object);
502 std::remove(bullets.begin(), bullets.end(), bullet),
505 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
507 grid->remove_object(movingobject);
510 i = gameobjects.erase(i);
513 /* add newly created objects */
514 for(std::vector<GameObject*>::iterator i = gameobjects_new.begin();
515 i != gameobjects_new.end(); ++i)
517 GameObject* object = *i;
519 Bullet* bullet = dynamic_cast<Bullet*> (object);
521 bullets.push_back(bullet);
523 MovingObject* movingobject = dynamic_cast<MovingObject*> (object);
525 grid->add_object(movingobject);
527 TileMap* tilemap = dynamic_cast<TileMap*> (object);
528 if(tilemap && tilemap->is_solid()) {
532 std::cerr << "Another solid tilemaps added. Ignoring.";
536 Camera* camera = dynamic_cast<Camera*> (object);
538 if(this->camera != 0) {
539 std::cerr << "Warning: Multiple cameras added. Ignoring.";
542 this->camera = camera;
545 gameobjects.push_back(object);
547 gameobjects_new.clear();
551 Sector::draw(DrawingContext& context)
553 context.push_transform();
554 context.set_translation(camera->get_translation());
557 CollisionGridIterator iter(*grid, get_active_region());
558 while(MovingObject* object = iter.next()) {
559 if(!object->is_valid())
562 object->draw(context);
565 for(GameObjects::iterator i = gameobjects.begin();
566 i != gameobjects.end(); ++i) {
567 GameObject* object = *i;
568 if(!object->is_valid())
571 object->draw(context);
575 context.pop_transform();
578 static const float DELTA = .001;
581 Sector::collision_tilemap(MovingObject* object, int depth)
585 std::cout << "Max collision depth reached.\n";
587 object->movement = Vector(0, 0);
591 // calculate rectangle where the object will move
593 if(object->get_movement().x >= 0) {
594 x1 = object->get_pos().x;
595 x2 = object->get_bbox().p2.x + object->get_movement().x;
597 x1 = object->get_pos().x + object->get_movement().x;
598 x2 = object->get_bbox().p2.x;
601 if(object->get_movement().y >= 0) {
602 y1 = object->get_pos().y;
603 y2 = object->get_bbox().p2.y + object->get_movement().y;
605 y1 = object->get_pos().y + object->get_movement().y;
606 y2 = object->get_bbox().p2.y;
609 // test with all tiles in this rectangle
610 int starttilex = int(x1-1) / 32;
611 int starttiley = int(y1-1) / 32;
612 int max_x = int(x2+1);
613 int max_y = int(y2+1);
615 CollisionHit temphit, hit;
616 Rect dest = object->get_bbox();
617 dest.move(object->movement);
618 hit.time = -1; // represents an invalid value
619 for(int x = starttilex; x*32 < max_x; ++x) {
620 for(int y = starttiley; y*32 < max_y; ++y) {
621 const Tile* tile = solids->get_tile(x, y);
624 // skip non-solid tiles
625 if(!(tile->getAttributes() & Tile::SOLID))
627 // only handle unisolid when the player is falling down and when he was
628 // above the tile before
629 if(tile->getAttributes() & Tile::UNISOLID) {
630 if(object->movement.y < 0 || object->get_bbox().p2.y > y*32)
634 if(tile->getAttributes() & Tile::SLOPE) { // slope tile
636 Vector p1(x*32, y*32);
637 Vector p2((x+1)*32, (y+1)*32);
638 triangle = AATriangle(p1, p2, tile->getData());
640 if(Collision::rectangle_aatriangle(temphit, dest, object->movement,
642 if(temphit.time > hit.time)
645 } else { // normal rectangular tile
646 Rect rect(x*32, y*32, (x+1)*32, (y+1)*32);
647 if(Collision::rectangle_rectangle(temphit, dest,
648 object->movement, rect)) {
649 if(temphit.time > hit.time)
656 // did we collide at all?
660 // call collision function
661 HitResponse response = object->collision(*solids, hit);
662 if(response == ABORT_MOVE) {
663 object->movement = Vector(0, 0);
666 if(response == FORCE_MOVE) {
669 // move out of collision and try again
670 object->movement += hit.normal * (hit.depth + DELTA);
671 collision_tilemap(object, depth+1);
675 Sector::collision_object(MovingObject* object1, MovingObject* object2)
678 Rect dest1 = object1->get_bbox();
679 dest1.move(object1->get_movement());
680 Rect dest2 = object2->get_bbox();
681 dest2.move(object2->get_movement());
683 Vector movement = object1->get_movement() - object2->get_movement();
684 if(Collision::rectangle_rectangle(hit, dest1, movement, dest2)) {
685 HitResponse response1 = object1->collision(*object2, hit);
687 HitResponse response2 = object2->collision(*object1, hit);
689 if(response1 != CONTINUE) {
690 if(response1 == ABORT_MOVE)
691 object1->movement = Vector(0, 0);
692 if(response2 == CONTINUE)
693 object2->movement += hit.normal * (hit.depth + DELTA);
694 } else if(response2 != CONTINUE) {
695 if(response2 == ABORT_MOVE)
696 object2->movement = Vector(0, 0);
697 if(response1 == CONTINUE)
698 object1->movement += -hit.normal * (hit.depth + DELTA);
700 object1->movement += -hit.normal * (hit.depth/2 + DELTA);
701 object2->movement += hit.normal * (hit.depth/2 + DELTA);
707 Sector::collision_handler()
710 grid->check_collisions();
712 for(std::vector<GameObject*>::iterator i = gameobjects.begin();
713 i != gameobjects.end(); ++i) {
714 GameObject* gameobject = *i;
715 if(!gameobject->is_valid())
717 MovingObject* movingobject = dynamic_cast<MovingObject*> (gameobject);
720 if(movingobject->get_flags() & GameObject::FLAG_NO_COLLDET) {
721 movingobject->bbox.move(movingobject->movement);
722 movingobject->movement = Vector(0, 0);
726 // collision with tilemap
727 if(! (movingobject->movement == Vector(0, 0)))
728 collision_tilemap(movingobject, 0);
730 // collision with other objects
731 for(std::vector<GameObject*>::iterator i2 = i+1;
732 i2 != gameobjects.end(); ++i2) {
733 GameObject* other_object = *i2;
734 if(!other_object->is_valid()
735 || other_object->get_flags() & GameObject::FLAG_NO_COLLDET)
737 MovingObject* movingobject2 = dynamic_cast<MovingObject*> (other_object);
741 collision_object(movingobject, movingobject2);
744 movingobject->bbox.move(movingobject->get_movement());
745 movingobject->movement = Vector(0, 0);
751 Sector::add_bullet(const Vector& pos, float xm, Direction dir)
753 // TODO remove this function and move these checks elsewhere...
754 static const size_t MAX_FIRE_BULLETS = 2;
755 static const size_t MAX_ICE_BULLETS = 1;
757 Bullet* new_bullet = 0;
758 if(player_status.bonus == FIRE_BONUS) {
759 if(bullets.size() > MAX_FIRE_BULLETS-1)
761 new_bullet = new Bullet(pos, xm, dir, FIRE_BULLET);
762 } else if(player_status.bonus == ICE_BONUS) {
763 if(bullets.size() > MAX_ICE_BULLETS-1)
765 new_bullet = new Bullet(pos, xm, dir, ICE_BULLET);
769 add_object(new_bullet);
771 sound_manager->play_sound("shoot");
777 Sector::add_smoke_cloud(const Vector& pos)
779 add_object(new SmokeCloud(pos));
784 Sector::add_floating_text(const Vector& pos, const std::string& text)
786 add_object(new FloatingText(pos, text));
792 level_song = sound_manager->load_music(
793 get_resource_filename("/music/" + song_title));
797 Sector::play_music(MusicType type)
800 switch(currentmusic) {
802 sound_manager->play_music(level_song);
805 sound_manager->play_music(herring_song);
808 sound_manager->halt_music();
814 Sector::get_music_type()
820 Sector::get_total_badguys()
822 int total_badguys = 0;
823 for(GameObjects::iterator i = gameobjects.begin();
824 i != gameobjects.end(); ++i) {
825 BadGuy* badguy = dynamic_cast<BadGuy*> (*i);
830 return total_badguys;
834 Sector::inside(const Rect& rect) const
836 if(rect.p1.x > solids->get_width() * 32
837 || rect.p1.y > solids->get_height() * 32
838 || rect.p2.x < 0 || rect.p2.y < 0)