1 #include "BlockLookup.hpp"
3 #include "ChunkIndex.hpp"
4 #include "ChunkLoader.hpp"
5 #include "ChunkRenderer.hpp"
6 #include "ChunkStore.hpp"
8 #include "Generator.hpp"
9 #include "WorldCollision.hpp"
10 #include "../app/Assets.hpp"
11 #include "../geometry/distance.hpp"
12 #include "../graphics/BlockLighting.hpp"
13 #include "../graphics/BlockMesh.hpp"
14 #include "../graphics/Viewport.hpp"
15 #include "../io/WorldSave.hpp"
23 #include <glm/gtx/io.hpp>
28 constexpr int Chunk::side;
29 constexpr int Chunk::size;
32 Chunk::Chunk(const BlockTypeRegistry &types) noexcept
47 Chunk::Chunk(Chunk &&other) noexcept
49 , gravity(std::move(other.gravity))
50 , generated(other.generated)
51 , lighted(other.lighted)
52 , position(other.position)
53 , ref_count(other.ref_count)
54 , dirty_mesh(other.dirty_mesh)
55 , dirty_save(other.dirty_save) {
56 std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
57 std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
58 std::copy(other.light, other.light + sizeof(light), light);
62 Chunk &Chunk::operator =(Chunk &&other) noexcept {
64 std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
65 gravity = std::move(other.gravity);
66 std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
67 std::copy(other.light, other.light + sizeof(light), light);
68 generated = other.generated;
69 lighted = other.lighted;
70 position = other.position;
71 std::swap(ref_count, other.ref_count);
72 dirty_mesh = other.dirty_save;
73 dirty_save = other.dirty_save;
83 RoughLocation::Fine pos;
85 SetNode(Chunk *chunk, RoughLocation::Fine pos)
86 : chunk(chunk), pos(pos) { }
88 int Get() const noexcept { return chunk->GetLight(pos); }
89 void Set(int level) noexcept { chunk->SetLight(pos, level); }
91 const BlockType &GetType() const noexcept { return chunk->Type(Chunk::ToIndex(pos)); }
93 int EmitLevel() const noexcept { return GetType().luminosity; }
94 bool EmitsLight() const noexcept { return EmitLevel() > 0; }
96 bool HasNext(Block::Face face) noexcept {
97 const BlockType &type = GetType();
98 if (type.block_light && !type.luminosity) return false;
99 const BlockLookup next(chunk, pos, face);
102 SetNode GetNext(Block::Face face) noexcept {
103 const BlockLookup next(chunk, pos, face);
104 return SetNode(&next.GetChunk(), next.GetBlockPos());
114 UnsetNode(Chunk *chunk, RoughLocation::Fine pos)
115 : SetNode(chunk, pos), level(Get()) { }
117 UnsetNode(const SetNode &set)
118 : SetNode(set), level(Get()) { }
121 bool HasNext(Block::Face face) noexcept {
122 const BlockLookup next(chunk, pos, face);
125 UnsetNode GetNext(Block::Face face) noexcept { return UnsetNode(SetNode::GetNext(face)); }
129 std::queue<SetNode> light_queue;
130 std::queue<UnsetNode> dark_queue;
132 void work_light() noexcept {
133 while (!light_queue.empty()) {
134 SetNode node = light_queue.front();
137 int level = node.Get() - 1;
138 for (int face = 0; face < Block::FACE_COUNT; ++face) {
139 if (node.HasNext(Block::Face(face))) {
140 SetNode other = node.GetNext(Block::Face(face));
141 if (other.Get() < level) {
143 light_queue.emplace(other);
150 void work_dark() noexcept {
151 while (!dark_queue.empty()) {
152 UnsetNode node = dark_queue.front();
155 for (int face = 0; face < Block::FACE_COUNT; ++face) {
156 if (node.HasNext(Block::Face(face))) {
157 UnsetNode other = node.GetNext(Block::Face(face));
158 if (other.Get() != 0 && other.Get() < node.level) {
159 if (other.EmitsLight()) {
160 other.Set(other.EmitLevel());
161 light_queue.emplace(other);
165 dark_queue.emplace(other);
167 light_queue.emplace(other);
176 void Chunk::SetBlock(int index, const Block &block) noexcept {
177 const BlockType &old_type = Type(blocks[index]);
178 const BlockType &new_type = Type(block);
180 blocks[index] = block;
183 if (old_type.gravity && !new_type.gravity) {
184 gravity.erase(index);
185 } else if (new_type.gravity && !old_type.gravity) {
186 gravity.insert(index);
189 if (!lighted || &old_type == &new_type) return;
191 if (new_type.luminosity > old_type.luminosity) {
193 SetLight(index, new_type.luminosity);
194 light_queue.emplace(this, ToPos(index));
196 } else if (new_type.luminosity < old_type.luminosity) {
198 dark_queue.emplace(this, ToPos(index));
201 SetLight(index, new_type.luminosity);
202 light_queue.emplace(this, ToPos(index));
204 } else if (new_type.block_light && !old_type.block_light) {
206 if (GetLight(index) > 0) {
207 dark_queue.emplace(this, ToPos(index));
212 } else if (!new_type.block_light && old_type.block_light) {
215 RoughLocation::Fine pos(ToPos(index));
216 for (int face = 0; face < Block::FACE_COUNT; ++face) {
217 BlockLookup next_block(this, pos, Block::Face(face));
219 level = std::max(level, next_block.GetLight());
223 SetLight(index, level - 1);
224 light_queue.emplace(this, pos);
230 void Chunk::ScanLights() {
232 RoughLocation::Fine pos(0, 0, 0);
233 for (; pos.z < side; ++pos.z) {
234 for (pos.y = 0; pos.y < side; ++pos.y) {
235 for (pos.x = 0; pos.x < side; ++pos.x, ++idx) {
236 const BlockType &type = Type(blocks[idx]);
237 if (type.luminosity) {
238 SetLight(idx, type.luminosity);
239 light_queue.emplace(this, pos);
248 void Chunk::ScanActive() {
250 for (int index = 0; index < size; ++index) {
251 if (Type(index).gravity) {
252 gravity.insert(gravity.end(), index);
257 void Chunk::SetNeighbor(Block::Face face, Chunk &other) noexcept {
258 neighbor[face] = &other;
259 other.neighbor[Block::Opposite(face)] = this;
262 void Chunk::Unlink() noexcept {
263 for (int face = 0; face < Block::FACE_COUNT; ++face) {
264 if (neighbor[face]) {
265 neighbor[face]->neighbor[Block::Opposite(Block::Face(face))] = nullptr;
266 neighbor[face] = nullptr;
272 void Chunk::SetLight(int index, int level) noexcept {
273 if (light[index] != level) {
274 light[index] = level;
279 int Chunk::GetLight(int index) const noexcept {
283 float Chunk::GetVertexLight(const RoughLocation::Fine &pos, const BlockMesh::Position &vtx, const EntityMesh::Normal &norm) const noexcept {
284 int index = ToIndex(pos);
285 float light = GetLight(index);
287 Block::Face direct_face(Block::NormalFace(norm));
289 BlockLookup direct(const_cast<Chunk *>(this), pos, Block::NormalFace(norm));
291 float direct_light = direct.GetLight();
292 if (direct_light > light) {
293 light = direct_light;
299 if (Type(BlockAt(index)).luminosity > 0 || direct.GetType().block_light) {
304 switch (Block::Axis(direct_face)) {
306 edge[0] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
307 edge[1] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
310 edge[0] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
311 edge[1] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
314 edge[0] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
315 edge[1] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
322 BlockLookup next[2] = {
323 direct.Next(edge[0]),
324 direct.Next(edge[1]),
328 if (next[0].GetType().block_light) {
331 light += next[0].GetLight();
336 if (next[1].GetType().block_light) {
339 light += next[1].GetLight();
345 BlockLookup corner = next[0].Next(edge[1]);
347 if (corner.GetType().block_light) {
350 light += corner.GetLight();
354 } else if (next[1]) {
355 BlockLookup corner = next[1].Next(edge[0]);
357 if (corner.GetType().block_light) {
360 light += corner.GetLight();
369 return (light / num) - (occlusion * 0.8f);
373 glm::vec3 Chunk::GravityAt(const ExactLocation &coords) const noexcept {
374 glm::vec3 grav(0.0f);
375 for (int index : gravity) {
376 RoughLocation::Fine block_pos(ToPos(index));
377 ExactLocation block_coords(position, ToCoords(block_pos));
378 // trust that block type hasn't changed
379 grav += Type(index).gravity->GetGravity(
380 coords.Difference(block_coords).Absolute(),
381 ToTransform(block_pos, index));
387 bool Chunk::IsSurface(const RoughLocation::Fine &pos) const noexcept {
388 const Block &block = BlockAt(pos);
389 if (!Type(block).visible) {
392 for (int face = 0; face < Block::FACE_COUNT; ++face) {
393 BlockLookup next = BlockLookup(const_cast<Chunk *>(this), pos, Block::Face(face));
394 if (!next || !next.GetType().visible) {
402 bool Chunk::Intersection(
404 const ExactLocation::Coarse &reference,
410 coll.depth = std::numeric_limits<float>::infinity();
411 for (int z = 0; z < side; ++z) {
412 for (int y = 0; y < side; ++y) {
413 for (int x = 0; x < side; ++x, ++idx) {
414 const BlockType &type = Type(idx);
415 if (!type.collision || !type.shape) {
418 RoughLocation::Fine pos(x, y, z);
420 // center of the blok relative to the ray
421 glm::vec3 relative_center(glm::vec3((position - reference) * ExactLocation::Extent() + pos) + 0.5f);
422 if (ray.DistanceSquared(relative_center) > 3.0f) {
428 if (type.shape->Intersects(ray, ToTransform(reference, pos, idx), cur_dist, cur_norm)) {
429 if (cur_dist < coll.depth) {
431 coll.depth = cur_dist;
432 coll.normal = cur_norm;
439 if (coll.block < 0) {
442 coll.normal = glm::vec3(BlockAt(coll.block).Transform() * glm::vec4(coll.normal, 0.0f));
447 bool Chunk::Intersection(
449 const glm::mat4 &Mbox,
450 const glm::mat4 &Mchunk,
451 std::vector<WorldCollision> &col
457 if (!blank::Intersection(box, Mbox, Bounds(), Mchunk, penetration, normal)) {
461 // box's origin relative to the chunk
462 const glm::vec3 box_coords(Mbox[3] - Mchunk[3]);
463 const float box_rad = box.OriginRadius();
465 // assume a bounding radius of 2 for blocks
466 constexpr float block_rad = 2.0f;
467 const float bb_radius = box_rad + block_rad;
469 const RoughLocation::Fine begin(max(
470 RoughLocation::Fine(0),
471 RoughLocation::Fine(floor(box_coords - bb_radius))
473 const RoughLocation::Fine end(min(
474 RoughLocation::Fine(side - 1),
475 RoughLocation::Fine(ceil(box_coords + bb_radius))
478 for (RoughLocation::Fine pos(begin); pos.z < end.y; ++pos.z) {
479 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
480 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
481 int idx = ToIndex(pos);
482 const BlockType &type = Type(idx);
483 if (!type.collision || !type.shape) {
486 if (type.shape->Intersects(Mchunk * ToTransform(pos, idx), box, Mbox, penetration, normal)) {
487 col.emplace_back(this, idx, penetration, normal);
496 bool Chunk::Intersection(
497 const Entity &entity,
498 const glm::mat4 &Mentity,
499 const glm::mat4 &Mchunk,
500 std::vector<WorldCollision> &col
502 // entity's origin relative to the chunk
503 const glm::vec3 entity_coords(Mentity[3] - Mchunk[3]);
504 const float ec_radius = entity.Radius() + Radius();
506 if (distance2(entity_coords, Center()) > ec_radius * ec_radius) {
514 // assume a bounding radius of 2 for blocks
515 constexpr float block_rad = 2.0f;
516 const float eb_radius = entity.Radius() + block_rad;
518 const RoughLocation::Fine begin(max(
519 RoughLocation::Fine(0),
520 RoughLocation::Fine(floor(entity_coords - eb_radius))
522 const RoughLocation::Fine end(min(
523 RoughLocation::Fine(side),
524 RoughLocation::Fine(ceil(entity_coords + eb_radius))
527 for (RoughLocation::Fine pos(begin); pos.z < end.z; ++pos.z) {
528 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
529 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
530 int idx = ToIndex(pos);
531 const BlockType &type = Type(idx);
532 if (!type.collision || !type.shape) {
535 if (type.shape->Intersects(Mchunk * ToTransform(pos, idx), entity.Bounds(), Mentity, penetration, normal)) {
536 col.emplace_back(this, idx, penetration, normal);
548 BlockMesh::Buffer buf;
552 void Chunk::Update(BlockMesh &model) noexcept {
553 int vtx_count = 0, idx_count = 0;
554 for (const auto &block : blocks) {
555 const BlockType &type = Type(block);
556 if (type.visible && type.shape) {
557 vtx_count += type.shape->VertexCount();
558 idx_count += type.shape->IndexCount();
562 buf.Reserve(vtx_count, idx_count);
566 BlockMesh::Index vtx_counter = 0;
567 for (size_t z = 0; z < side; ++z) {
568 for (size_t y = 0; y < side; ++y) {
569 for (size_t x = 0; x < side; ++x, ++idx) {
570 const BlockType &type = Type(BlockAt(idx));
571 const RoughLocation::Fine pos(x, y, z);
573 if (!type.visible || !type.shape || Obstructed(pos).All()) continue;
575 type.FillBlockMesh(buf, ToTransform(pos, idx), vtx_counter);
576 size_t vtx_begin = vtx_counter;
577 vtx_counter += type.shape->VertexCount();
579 for (size_t vtx = vtx_begin; vtx < vtx_counter; ++vtx) {
580 buf.lights.emplace_back(GetVertexLight(
583 type.shape->VertexNormal(vtx - vtx_begin, BlockAt(idx).Transform())
595 Block::FaceSet Chunk::Obstructed(const RoughLocation::Fine &pos) const noexcept {
596 Block::FaceSet result;
598 for (int f = 0; f < Block::FACE_COUNT; ++f) {
599 Block::Face face = Block::Face(f);
600 BlockLookup next(const_cast<Chunk *>(this), pos, face);
601 if (next && next.GetType().FaceFilled(next.GetBlock(), Block::Opposite(face))) {
609 glm::mat4 Chunk::ToTransform(const RoughLocation::Fine &pos, int idx) const noexcept {
610 return glm::translate(ToCoords(pos)) * BlockAt(idx).Transform();
613 glm::mat4 Chunk::ToTransform(const ExactLocation::Coarse &ref, const RoughLocation::Fine &pos, int idx) const noexcept {
614 return glm::translate(ExactLocation::Fine((position - ref) * ExactLocation::Extent()) + ToCoords(pos)) * BlockAt(idx).Transform();
618 BlockLookup::BlockLookup(Chunk *c, const RoughLocation::Fine &p) noexcept
620 while (pos.x >= Chunk::side) {
621 if (chunk->HasNeighbor(Block::FACE_RIGHT)) {
622 chunk = &chunk->GetNeighbor(Block::FACE_RIGHT);
623 pos.x -= Chunk::side;
630 if (chunk->HasNeighbor(Block::FACE_LEFT)) {
631 chunk = &chunk->GetNeighbor(Block::FACE_LEFT);
632 pos.x += Chunk::side;
638 while (pos.y >= Chunk::side) {
639 if (chunk->HasNeighbor(Block::FACE_UP)) {
640 chunk = &chunk->GetNeighbor(Block::FACE_UP);
641 pos.y -= Chunk::side;
648 if (chunk->HasNeighbor(Block::FACE_DOWN)) {
649 chunk = &chunk->GetNeighbor(Block::FACE_DOWN);
650 pos.y += Chunk::side;
656 while (pos.z >= Chunk::side) {
657 if (chunk->HasNeighbor(Block::FACE_FRONT)) {
658 chunk = &chunk->GetNeighbor(Block::FACE_FRONT);
659 pos.z -= Chunk::side;
666 if (chunk->HasNeighbor(Block::FACE_BACK)) {
667 chunk = &chunk->GetNeighbor(Block::FACE_BACK);
668 pos.z += Chunk::side;
676 BlockLookup::BlockLookup(Chunk *c, const RoughLocation::Fine &p, Block::Face face) noexcept
678 pos += Block::FaceNormal(face);
679 if (!Chunk::InBounds(pos)) {
680 pos -= Block::FaceNormal(face) * ExactLocation::Extent();
681 chunk = &chunk->GetNeighbor(face);
686 ChunkLoader::ChunkLoader(
688 const Generator &gen,
689 const WorldSave &save
697 void ChunkLoader::Update(int dt) {
698 // check if there's chunks waiting to be loaded
699 // load until one of load or generation limits was hit
700 constexpr int max_load = 10;
701 constexpr int max_gen = 1;
704 while (loaded < max_load && generated < max_gen && store.HasMissing()) {
712 // store a few chunks as well
713 constexpr int max_save = 10;
715 for (Chunk &chunk : store) {
716 if (chunk.ShouldUpdateSave()) {
719 if (saved >= max_save) {
726 int ChunkLoader::ToLoad() const noexcept {
727 return store.EstimateMissing();
730 bool ChunkLoader::LoadOne() {
731 if (!store.HasMissing()) return false;
733 ExactLocation::Coarse pos = store.NextMissing();
734 Chunk *chunk = store.Allocate(pos);
736 // chunk store corrupted?
740 bool generated = false;
741 if (save.Exists(pos)) {
748 ChunkIndex *index = store.ClosestIndex(pos);
753 ExactLocation::Coarse begin(pos - ExactLocation::Coarse(1));
754 ExactLocation::Coarse end(pos + ExactLocation::Coarse(2));
755 for (ExactLocation::Coarse iter(begin); iter.z < end.z; ++iter.z) {
756 for (iter.y = begin.y; iter.y < end.y; ++iter.y) {
757 for (iter.x = begin.x; iter.x < end.x; ++iter.x) {
758 if (index->IsBorder(iter)) continue;
759 Chunk *light_chunk = index->Get(iter);
760 if (!light_chunk) continue;
761 if (index->HasAllSurrounding(iter)) {
762 if (!light_chunk->Lighted()) {
763 light_chunk->ScanLights();
765 light_chunk->InvalidateMesh();
775 void ChunkLoader::LoadN(std::size_t n) {
776 std::size_t end = std::min(n, std::size_t(ToLoad()));
777 for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
783 ChunkRenderer::ChunkRenderer(ChunkIndex &index)
785 , models(index.TotalChunks())
787 , fog_density(0.0f) {
791 ChunkRenderer::~ChunkRenderer() {
795 int ChunkRenderer::MissingChunks() const noexcept {
796 return index.MissingChunks();
799 void ChunkRenderer::LoadTextures(const AssetLoader &loader, const ResourceIndex &tex_index) {
801 loader.LoadTextures(tex_index, block_tex);
802 block_tex.FilterNearest();
805 void ChunkRenderer::Update(int dt) {
806 for (int i = 0, updates = 0; updates < dt && i < index.TotalChunks(); ++i) {
807 if (!index[i]) continue;
808 if (!index[i]->Lighted() && index.HasAllSurrounding(index[i]->Position())) {
809 index[i]->ScanLights();
811 if (index[i]->ShouldUpdateMesh()) {
812 index[i]->Update(models[i]);
818 void ChunkRenderer::Render(Viewport &viewport) {
819 BlockLighting &chunk_prog = viewport.ChunkProgram();
820 chunk_prog.SetTexture(block_tex);
821 chunk_prog.SetFogDensity(fog_density);
823 Frustum frustum(transpose(chunk_prog.GetVP()));
826 for (int i = 0; i < index.TotalChunks(); ++i) {
827 if (!index[i]) continue;
828 box.min = (index[i]->Position() - index.Base()) * ExactLocation::Extent();
829 box.max = box.min + ExactLocation::FExtent();
831 if (!CullTest(box, frustum)) {
832 if (index[i]->ShouldUpdateMesh()) {
833 index[i]->Update(models[i]);
835 if (!models[i].Empty()) {
836 chunk_prog.SetM(index[i]->Transform(index.Base()));
844 ChunkIndex::ChunkIndex(ChunkStore &store, const ExactLocation::Coarse &base, int extent)
848 , side_length(2 * extent + 1)
849 , total_length(side_length * side_length * side_length)
852 , stride(1, side_length, side_length * side_length)
853 , chunks(total_length, nullptr) {
857 ChunkIndex::~ChunkIndex() {
861 bool ChunkIndex::InRange(const ExactLocation::Coarse &pos) const noexcept {
862 return Distance(pos) <= extent;
865 bool ChunkIndex::IsBorder(const ExactLocation::Coarse &pos) const noexcept {
866 return Distance(pos) == extent;
869 int ChunkIndex::Distance(const ExactLocation::Coarse &pos) const noexcept {
870 return manhattan_radius(pos - base);
873 bool ChunkIndex::HasAllSurrounding(const ExactLocation::Coarse &pos) const noexcept {
874 ExactLocation::Coarse begin(pos - ExactLocation::Coarse(1));
875 ExactLocation::Coarse end(pos + ExactLocation::Coarse(2));
876 for (ExactLocation::Coarse iter(begin); iter.z < end.z; ++iter.z) {
877 for (iter.y = begin.y; iter.y < end.y; ++iter.y) {
878 for (iter.x = begin.x; iter.x < end.x; ++iter.x) {
879 if (!Get(iter)) return false;
886 int ChunkIndex::IndexOf(const ExactLocation::Coarse &pos) const noexcept {
887 ExactLocation::Coarse mod_pos(
892 return mod_pos.x * stride.x
893 + mod_pos.y * stride.y
894 + mod_pos.z * stride.z;
897 ExactLocation::Coarse ChunkIndex::PositionOf(int i) const noexcept {
898 ExactLocation::Coarse zero_pos(
899 (i / stride.x) % side_length,
900 (i / stride.y) % side_length,
901 (i / stride.z) % side_length
903 ExactLocation::Coarse zero_base(
908 ExactLocation::Coarse base_relative(zero_pos - zero_base);
909 if (base_relative.x > extent) base_relative.x -= side_length;
910 else if (base_relative.x < -extent) base_relative.x += side_length;
911 if (base_relative.y > extent) base_relative.y -= side_length;
912 else if (base_relative.y < -extent) base_relative.y += side_length;
913 if (base_relative.z > extent) base_relative.z -= side_length;
914 else if (base_relative.z < -extent) base_relative.z += side_length;
915 return base + base_relative;
918 Chunk *ChunkIndex::Get(const ExactLocation::Coarse &pos) noexcept {
920 return chunks[IndexOf(pos)];
926 const Chunk *ChunkIndex::Get(const ExactLocation::Coarse &pos) const noexcept {
928 return chunks[IndexOf(pos)];
934 void ChunkIndex::Rebase(const ExactLocation::Coarse &new_base) {
935 if (new_base == base) return;
937 ExactLocation::Coarse diff(new_base - base);
939 if (manhattan_radius(diff) > extent) {
940 // that's more than half, so probably not worth shifting
949 Shift(Block::FACE_RIGHT);
953 Shift(Block::FACE_LEFT);
957 Shift(Block::FACE_UP);
961 Shift(Block::FACE_DOWN);
965 Shift(Block::FACE_FRONT);
969 Shift(Block::FACE_BACK);
975 int ChunkIndex::GetCol(int c) const noexcept {
977 if (c < 0) c += side_length;
981 void ChunkIndex::Shift(Block::Face f) {
982 int a_axis = Block::Axis(f);
983 int b_axis = (a_axis + 1) % 3;
984 int c_axis = (a_axis + 2) % 3;
985 int dir = Block::Direction(f);
987 int a = GetCol(base[a_axis] + (extent * dir));
988 int a_stride = a * stride[a_axis];
989 for (int b = 0; b < side_length; ++b) {
990 int b_stride = b * stride[b_axis];
991 for (int c = 0; c < side_length; ++c) {
992 int bc_stride = b_stride + c * stride[c_axis];
993 int index = a_stride + bc_stride;
995 int neighbor = ((a - dir + side_length) % side_length) * stride[a_axis] + bc_stride;
996 if (chunks[neighbor] && chunks[neighbor]->HasNeighbor(f)) {
997 Set(index, chunks[neighbor]->GetNeighbor(f));
1003 void ChunkIndex::Clear() noexcept {
1004 for (int i = 0; i < total_length && total_indexed > 0; ++i) {
1009 void ChunkIndex::Scan() noexcept {
1010 for (Chunk &chunk : store) {
1015 void ChunkIndex::Register(Chunk &chunk) noexcept {
1016 if (InRange(chunk.Position())) {
1017 Set(IndexOf(chunk.Position()), chunk);
1021 void ChunkIndex::Set(int index, Chunk &chunk) noexcept {
1023 chunks[index] = &chunk;
1028 void ChunkIndex::Unset(int index) noexcept {
1029 if (chunks[index]) {
1030 chunks[index]->UnRef();
1031 chunks[index] = nullptr;
1036 ExactLocation::Coarse ChunkIndex::NextMissing() noexcept {
1037 if (MissingChunks() > 0) {
1038 int roundtrip = last_missing;
1039 last_missing = (last_missing + 1) % total_length;
1040 while (chunks[last_missing]) {
1041 last_missing = (last_missing + 1) % total_length;
1042 if (last_missing == roundtrip) {
1047 return PositionOf(last_missing);
1051 ChunkStore::ChunkStore(const BlockTypeRegistry &types)
1059 ChunkStore::~ChunkStore() {
1063 ChunkIndex &ChunkStore::MakeIndex(const ExactLocation::Coarse &pos, int extent) {
1064 indices.emplace_back(*this, pos, extent);
1065 return indices.back();
1068 void ChunkStore::UnregisterIndex(ChunkIndex &index) {
1069 for (auto i = indices.begin(), end = indices.end(); i != end; ++i) {
1070 if (&*i == &index) {
1079 ChunkIndex *ChunkStore::ClosestIndex(const ExactLocation::Coarse &pos) {
1080 ChunkIndex *closest_index = nullptr;
1081 int closest_distance = std::numeric_limits<int>::max();
1083 for (ChunkIndex &index : indices) {
1084 int distance = index.Distance(pos);
1085 if (distance < closest_distance) {
1086 closest_index = &index;
1087 closest_distance = distance;
1091 return closest_index;
1094 Chunk *ChunkStore::Get(const ExactLocation::Coarse &pos) noexcept {
1095 for (ChunkIndex &index : indices) {
1096 Chunk *chunk = index.Get(pos);
1104 const Chunk *ChunkStore::Get(const ExactLocation::Coarse &pos) const noexcept {
1105 for (const ChunkIndex &index : indices) {
1106 const Chunk *chunk = index.Get(pos);
1114 Chunk *ChunkStore::Allocate(const ExactLocation::Coarse &pos) {
1115 Chunk *chunk = Get(pos);
1120 loaded.emplace(loaded.begin(), types);
1122 loaded.splice(loaded.begin(), free, free.begin());
1123 loaded.front().Unlink();
1125 chunk = &loaded.front();
1126 chunk->Position(pos);
1127 for (ChunkIndex &index : indices) {
1128 if (index.InRange(pos)) {
1129 index.Register(*chunk);
1132 for (int i = 0; i < Block::FACE_COUNT; ++i) {
1133 Block::Face face = Block::Face(i);
1134 ExactLocation::Coarse neighbor_pos(pos + Block::FaceNormal(face));
1135 Chunk *neighbor = Get(neighbor_pos);
1137 chunk->SetNeighbor(face, *neighbor);
1143 bool ChunkStore::HasMissing() const noexcept {
1144 for (const ChunkIndex &index : indices) {
1145 if (index.MissingChunks() > 0) {
1152 int ChunkStore::EstimateMissing() const noexcept {
1154 for (const ChunkIndex &index : indices) {
1155 missing += index.MissingChunks();
1160 ExactLocation::Coarse ChunkStore::NextMissing() noexcept {
1161 for (ChunkIndex &index : indices) {
1162 if (index.MissingChunks()) {
1163 return index.NextMissing();
1166 return ExactLocation::Coarse(0, 0, 0);
1169 void ChunkStore::Clean() {
1170 for (auto i = loaded.begin(), end = loaded.end(); i != end;) {
1171 if (i->Referenced() || i->ShouldUpdateSave()) {
1176 free.splice(free.end(), loaded, chunk);
1178 chunk->InvalidateMesh();