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 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. #include "WorldPlane.h"
  2. #include <math.h>
  3. #include <iostream>
  4. #include <algorithm>
  5. #include "log.h"
  6. #include "World.h"
  7. #include "Game.h"
  8. #include "Clock.h"
  9. #include "Win.h"
  10. namespace Swan {
  11. static ChunkPos chunkPos(TilePos pos) {
  12. // This might look weird, but it reduces an otherwise complex series of operations
  13. // including conditional branches into like four x64 instructions.
  14. // Basically, the problem is that we want 'floor(pos.x / CHUNK_WIDTH)', but
  15. // integer division rounds towards zero, it doesn't round down.
  16. // Solution: Move the position far to the right in the number line, do the math there
  17. // with integer division which always rounds down (because the numbers are always >0),
  18. // then move the result back to something hovering around 0 again.
  19. return ChunkPos(
  20. ((long long)pos.x + (LLONG_MAX / 2) + 1) / CHUNK_WIDTH - ((LLONG_MAX / 2) / CHUNK_WIDTH) - 1,
  21. ((long long)pos.y + (LLONG_MAX / 2) + 1) / CHUNK_HEIGHT - ((LLONG_MAX / 2) / CHUNK_HEIGHT) - 1);
  22. }
  23. static Chunk::RelPos relPos(TilePos pos) {
  24. // This uses a similar trick to chunkPos to turn a mess of conditional moves
  25. // and math instructions into literally one movabs and one 'and'
  26. return Chunk::RelPos(
  27. (pos.x + (long long)CHUNK_WIDTH * ((LLONG_MAX / 2) / CHUNK_WIDTH)) % CHUNK_WIDTH,
  28. (pos.y + (long long)CHUNK_HEIGHT * ((LLONG_MAX / 2) / CHUNK_HEIGHT)) % CHUNK_HEIGHT);
  29. }
  30. Context WorldPlane::getContext() {
  31. return {
  32. .game = *world_->game_,
  33. .world = *world_,
  34. .plane = *this,
  35. .resources = world_->resources_
  36. };
  37. }
  38. WorldPlane::WorldPlane(
  39. ID id, World *world, std::unique_ptr<WorldGen> gen,
  40. std::vector<std::unique_ptr<EntityCollection>> &&colls):
  41. id_(id), world_(world), gen_(std::move(gen)),
  42. lighting_(std::make_unique<LightServer>(*this)),
  43. entColls_(std::move(colls)) {
  44. for (auto &coll: entColls_) {
  45. entCollsByType_[coll->type()] = coll.get();
  46. entCollsByName_[coll->name()] = coll.get();
  47. }
  48. }
  49. EntityRef WorldPlane::spawnEntity(const std::string &name, const Entity::PackObject &obj) {
  50. return entCollsByName_.at(name)->spawn(getContext(), obj);
  51. }
  52. bool WorldPlane::hasChunk(ChunkPos pos) {
  53. return chunks_.find(pos) != chunks_.end();
  54. }
  55. // This function will be a bit weird because it's a really fucking hot function.
  56. Chunk &WorldPlane::getChunk(ChunkPos pos) {
  57. // First, look through all chunks which have been in use this tick
  58. for (auto [chpos, chunk]: tickChunks_) {
  59. if (chpos == pos)
  60. return *chunk;
  61. }
  62. Chunk &chunk = slowGetChunk(pos);
  63. tickChunks_.push_back({ pos, &chunk });
  64. return chunk;
  65. }
  66. Chunk &WorldPlane::slowGetChunk(ChunkPos pos) {
  67. ZoneScopedN("WorldPlane slowGetChunk");
  68. auto iter = chunks_.find(pos);
  69. // Create chunk if that turns out to be necessary
  70. if (iter == chunks_.end()) {
  71. iter = chunks_.emplace(pos, Chunk(pos)).first;
  72. Chunk &chunk = iter->second;
  73. gen_->genChunk(*this, chunk);
  74. activeChunks_.push_back(&chunk);
  75. chunkInitList_.push_back(&chunk);
  76. // Need to tell the light engine too
  77. NewLightChunk lc;
  78. for (int y = 0; y < CHUNK_HEIGHT; ++y) {
  79. for (int x = 0; x < CHUNK_WIDTH; ++x) {
  80. Tile::ID id = chunk.getTileID({ x, y });
  81. Tile &tile = world_->getTileByID(id);
  82. if (tile.isSolid_) {
  83. lc.blocks[y * CHUNK_HEIGHT + x] = true;
  84. }
  85. if (tile.lightLevel_ > 0) {
  86. lc.light_sources[{ x, y }] = tile.lightLevel_;
  87. }
  88. }
  89. }
  90. lighting_->onChunkAdded(pos, std::move(lc));
  91. // Otherwise, it might not be active, so let's activate it
  92. } else if (!iter->second.isActive()) {
  93. iter->second.keepActive();
  94. activeChunks_.push_back(&iter->second);
  95. chunkInitList_.push_back(&iter->second);
  96. }
  97. return iter->second;
  98. }
  99. void WorldPlane::setTileID(TilePos pos, Tile::ID id) {
  100. Chunk &chunk = getChunk(chunkPos(pos));
  101. Chunk::RelPos rp = relPos(pos);
  102. Tile::ID old = chunk.getTileID(rp);
  103. if (id != old) {
  104. Tile &newTile = world_->getTileByID(id);
  105. Tile &oldTile = world_->getTileByID(old);
  106. chunk.setTileID(rp, id, newTile.image_.texture_.get());
  107. chunk.markModified();
  108. if (!oldTile.isSolid_ && newTile.isSolid_) {
  109. lighting_->onSolidBlockAdded(pos);
  110. } else if (oldTile.isSolid_ && !newTile.isSolid_) {
  111. lighting_->onSolidBlockRemoved(pos);
  112. }
  113. if (newTile.lightLevel_ != oldTile.lightLevel_) {
  114. if (oldTile.lightLevel_ > 0) {
  115. removeLight(pos, oldTile.lightLevel_);
  116. }
  117. if (newTile.lightLevel_ > 0) {
  118. addLight(pos, newTile.lightLevel_);
  119. }
  120. }
  121. }
  122. }
  123. void WorldPlane::setTile(TilePos pos, const std::string &name) {
  124. setTileID(pos, world_->getTileID(name));
  125. }
  126. Tile::ID WorldPlane::getTileID(TilePos pos) {
  127. return getChunk(chunkPos(pos)).getTileID(relPos(pos));
  128. }
  129. Tile &WorldPlane::getTile(TilePos pos) {
  130. return world_->getTileByID(getTileID(pos));
  131. }
  132. Iter<Entity *> WorldPlane::getEntsInArea(Vec2 center, float radius) {
  133. return Iter<Entity *>([] { return std::nullopt; });
  134. // TODO: this
  135. /*
  136. return mapFilter(entities_.begin(), entities_.end(), [=](std::unique_ptr<Entity> &ent)
  137. -> std::optional<Entity *> {
  138. // Filter out things which don't have bodies
  139. auto *has_body = dynamic_cast<BodyTrait::HasBody *>(ent.get());
  140. if (has_body == nullptr)
  141. return std::nullopt;
  142. // Filter out things which are too far away from 'center'
  143. auto &body = has_body->getBody();
  144. auto bounds = body.getBounds();
  145. Vec2 entcenter = bounds.pos + (bounds.size / 2);
  146. auto dist = (entcenter - center).length();
  147. if (dist > radius)
  148. return std::nullopt;
  149. return ent.get();
  150. });
  151. */
  152. }
  153. EntityRef WorldPlane::spawnPlayer() {
  154. return gen_->spawnPlayer(getContext());
  155. }
  156. void WorldPlane::breakTile(TilePos pos) {
  157. // If the block is already air, do nothing
  158. Tile::ID id = getTileID(pos);
  159. Tile::ID air = world_->getTileID("@::air");
  160. if (id == air)
  161. return;
  162. // Change tile to air and emit event
  163. setTileID(pos, air);
  164. world_->evtTileBreak_.emit(getContext(), pos, world_->getTileByID(id));
  165. }
  166. SDL_Color WorldPlane::backgroundColor() {
  167. return gen_->backgroundColor(world_->player_->pos);
  168. }
  169. void WorldPlane::draw(Win &win) {
  170. ZoneScopedN("WorldPlane draw");
  171. std::lock_guard<std::mutex> lock(mut_);
  172. auto ctx = getContext();
  173. auto &pbody = *(world_->player_);
  174. gen_->drawBackground(ctx, win, pbody.pos);
  175. ChunkPos pcpos = ChunkPos(
  176. (int)floor(pbody.pos.x / CHUNK_WIDTH),
  177. (int)floor(pbody.pos.y / CHUNK_HEIGHT));
  178. // Just init one chunk per frame
  179. if (chunkInitList_.size() > 0) {
  180. Chunk *chunk = chunkInitList_.front();
  181. chunkInitList_.pop_front();
  182. chunk->render(ctx, win.renderer_);
  183. }
  184. for (int x = -1; x <= 1; ++x) {
  185. for (int y = -1; y <= 1; ++y) {
  186. auto iter = chunks_.find(pcpos + ChunkPos(x, y));
  187. if (iter != chunks_.end())
  188. iter->second.draw(ctx, win);
  189. }
  190. }
  191. for (auto &coll: entColls_)
  192. coll->draw(ctx, win);
  193. if (debugBoxes_.size() > 0) {
  194. for (auto &pos: debugBoxes_) {
  195. win.drawRect(pos, Vec2(1, 1));
  196. }
  197. }
  198. }
  199. void WorldPlane::update(float dt) {
  200. ZoneScopedN("WorldPlane update");
  201. std::lock_guard<std::mutex> lock(mut_);
  202. auto ctx = getContext();
  203. debugBoxes_.clear();
  204. for (auto &coll: entColls_)
  205. coll->update(ctx, dt);
  206. }
  207. void WorldPlane::tick(float dt) {
  208. ZoneScopedN("WorldPlane tick");
  209. std::lock_guard<std::mutex> lock(mut_);
  210. auto ctx = getContext();
  211. // Any chunk which has been in use since last tick should be kept alive
  212. for (std::pair<ChunkPos, Chunk *> &ch: tickChunks_)
  213. ch.second->keepActive();
  214. tickChunks_.clear();
  215. for (auto &coll: entColls_)
  216. coll->tick(ctx, dt);
  217. // Tick all chunks, figure out if any of them should be deleted or compressed
  218. auto iter = activeChunks_.begin();
  219. auto last = activeChunks_.end();
  220. while (iter != last) {
  221. auto &chunk = *iter;
  222. auto action = chunk->tick(dt);
  223. switch (action) {
  224. case Chunk::TickAction::DEACTIVATE:
  225. info << "Compressing inactive modified chunk " << chunk->pos_;
  226. chunk->compress();
  227. iter = activeChunks_.erase(iter);
  228. last = activeChunks_.end();
  229. break;
  230. case Chunk::TickAction::DELETE:
  231. info << "Deleting inactive unmodified chunk " << chunk->pos_;
  232. chunks_.erase(chunk->pos_);
  233. iter = activeChunks_.erase(iter);
  234. last = activeChunks_.end();
  235. break;
  236. case Chunk::TickAction::NOTHING:
  237. ++iter;
  238. break;
  239. }
  240. }
  241. }
  242. void WorldPlane::debugBox(TilePos pos) {
  243. debugBoxes_.push_back(pos);
  244. }
  245. void WorldPlane::addLight(TilePos pos, float level) {
  246. getChunk(chunkPos(pos));
  247. lighting_->onLightAdded(pos, level);
  248. }
  249. void WorldPlane::removeLight(TilePos pos, float level) {
  250. getChunk(chunkPos(pos));
  251. lighting_->onLightRemoved(pos, level);
  252. }
  253. void WorldPlane::onLightChunkUpdated(const LightChunk &chunk, ChunkPos pos) {
  254. std::lock_guard<std::mutex> lock(mut_);
  255. Chunk &realChunk = getChunk(pos);
  256. realChunk.setLightData(chunk.lightLevels);
  257. }
  258. }