A 2D tile-based sandbox game.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WorldPlane.cc 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include "WorldPlane.h"
  2. #include "World.h"
  3. namespace Swan {
  4. static Chunk::ChunkPos chunkPos(int x, int y) {
  5. int chx = x / CHUNK_WIDTH;
  6. if (x < 0 && x % CHUNK_WIDTH != 0) chx -= 1;
  7. int chy = y / CHUNK_HEIGHT;
  8. if (y < 0 && y % CHUNK_HEIGHT != 0) chy -= 1;
  9. return Chunk::ChunkPos(chx, chy);
  10. }
  11. static Chunk::RelPos relPos(int x, int y) {
  12. int rx = x % CHUNK_WIDTH;
  13. if (rx < 0) rx += CHUNK_WIDTH;
  14. int ry = y % CHUNK_HEIGHT;
  15. if (ry < 0) ry += CHUNK_HEIGHT;
  16. return Chunk::RelPos(rx, ry);
  17. }
  18. Entity &WorldPlane::spawnEntity(const std::string &name, const Vec2 &pos) {
  19. if (world_->ents_.find(name) == world_->ents_.end()) {
  20. fprintf(stderr, "Tried to spawn non-existant entity %s!",
  21. name.c_str());
  22. abort();
  23. }
  24. Entity *ent = world_->ents_[name]->create(pos);
  25. entities_.push_back(std::unique_ptr<Entity>(ent));
  26. fprintf(stderr, "Spawned %s at %f,%f.\n", name.c_str(), pos.x_, pos.y_);
  27. return *ent;
  28. }
  29. Chunk &WorldPlane::getChunk(int x, int y) {
  30. Chunk::ChunkPos pos = chunkPos(x, y);
  31. auto iter = chunks_.find(pos);
  32. if (iter == chunks_.end()) {
  33. iter = chunks_.emplace(pos, new Chunk(pos)).first;
  34. gen_->genChunk(*this, *iter->second, pos.x_, pos.y_);
  35. iter->second->redraw(world_->tile_map_);
  36. fprintf(stderr, "Generated chunk %i,%i\n", pos.x_, pos.y_);
  37. }
  38. return *iter->second;
  39. }
  40. void WorldPlane::setTileID(int x, int y, Tile::ID id) {
  41. getChunk(x, y).setTileID(world_->tile_map_, relPos(x, y), id);
  42. }
  43. Tile &WorldPlane::getTile(int x, int y) {
  44. return getChunk(x, y).getTile(world_->tile_map_, relPos(x, y));
  45. }
  46. Entity &WorldPlane::spawnPlayer() {
  47. return gen_->spawnPlayer(*this);
  48. }
  49. void WorldPlane::draw(Win &win) {
  50. for (auto &ch: chunks_)
  51. ch.second->draw(win);
  52. for (auto &ent: entities_)
  53. ent->draw(win);
  54. }
  55. void WorldPlane::update(float dt) {
  56. for (auto &ent: entities_)
  57. ent->update(*this, dt);
  58. }
  59. void WorldPlane::tick() {
  60. for (auto &ent: entities_)
  61. ent->tick();
  62. }
  63. }