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

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