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"
25 constexpr int Chunk::side;
26 constexpr int Chunk::size;
29 Chunk::Chunk(const BlockTypeRegistry &types) noexcept
43 Chunk::Chunk(Chunk &&other) noexcept
45 , generated(other.generated)
46 , lighted(other.lighted)
47 , position(other.position)
48 , ref_count(other.ref_count)
49 , dirty_mesh(other.dirty_mesh)
50 , dirty_save(other.dirty_save) {
51 std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
52 std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
53 std::copy(other.light, other.light + sizeof(light), light);
57 Chunk &Chunk::operator =(Chunk &&other) noexcept {
59 std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
60 std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
61 std::copy(other.light, other.light + sizeof(light), light);
62 generated = other.generated;
63 lighted = other.lighted;
64 position = other.position;
65 std::swap(ref_count, other.ref_count);
66 dirty_mesh = other.dirty_save;
67 dirty_save = other.dirty_save;
77 RoughLocation::Fine pos;
79 SetNode(Chunk *chunk, RoughLocation::Fine pos)
80 : chunk(chunk), pos(pos) { }
82 int Get() const noexcept { return chunk->GetLight(pos); }
83 void Set(int level) noexcept { chunk->SetLight(pos, level); }
85 const BlockType &GetType() const noexcept { return chunk->Type(Chunk::ToIndex(pos)); }
87 int EmitLevel() const noexcept { return GetType().luminosity; }
88 bool EmitsLight() const noexcept { return EmitLevel() > 0; }
90 bool HasNext(Block::Face face) noexcept {
91 const BlockType &type = GetType();
92 if (type.block_light && !type.luminosity) return false;
93 const BlockLookup next(chunk, pos, face);
96 SetNode GetNext(Block::Face face) noexcept {
97 const BlockLookup next(chunk, pos, face);
98 return SetNode(&next.GetChunk(), next.GetBlockPos());
108 UnsetNode(Chunk *chunk, RoughLocation::Fine pos)
109 : SetNode(chunk, pos), level(Get()) { }
111 UnsetNode(const SetNode &set)
112 : SetNode(set), level(Get()) { }
115 bool HasNext(Block::Face face) noexcept {
116 const BlockLookup next(chunk, pos, face);
119 UnsetNode GetNext(Block::Face face) noexcept { return UnsetNode(SetNode::GetNext(face)); }
123 std::queue<SetNode> light_queue;
124 std::queue<UnsetNode> dark_queue;
126 void work_light() noexcept {
127 while (!light_queue.empty()) {
128 SetNode node = light_queue.front();
131 int level = node.Get() - 1;
132 for (int face = 0; face < Block::FACE_COUNT; ++face) {
133 if (node.HasNext(Block::Face(face))) {
134 SetNode other = node.GetNext(Block::Face(face));
135 if (other.Get() < level) {
137 light_queue.emplace(other);
144 void work_dark() noexcept {
145 while (!dark_queue.empty()) {
146 UnsetNode node = dark_queue.front();
149 for (int face = 0; face < Block::FACE_COUNT; ++face) {
150 if (node.HasNext(Block::Face(face))) {
151 UnsetNode other = node.GetNext(Block::Face(face));
152 if (other.Get() != 0 && other.Get() < node.level) {
153 if (other.EmitsLight()) {
154 other.Set(other.EmitLevel());
155 light_queue.emplace(other);
159 dark_queue.emplace(other);
161 light_queue.emplace(other);
170 void Chunk::SetBlock(int index, const Block &block) noexcept {
171 const BlockType &old_type = Type(blocks[index]);
172 const BlockType &new_type = Type(block);
174 blocks[index] = block;
177 if (!lighted || &old_type == &new_type) return;
179 if (new_type.luminosity > old_type.luminosity) {
181 SetLight(index, new_type.luminosity);
182 light_queue.emplace(this, ToPos(index));
184 } else if (new_type.luminosity < old_type.luminosity) {
186 dark_queue.emplace(this, ToPos(index));
189 SetLight(index, new_type.luminosity);
190 light_queue.emplace(this, ToPos(index));
192 } else if (new_type.block_light && !old_type.block_light) {
194 if (GetLight(index) > 0) {
195 dark_queue.emplace(this, ToPos(index));
200 } else if (!new_type.block_light && old_type.block_light) {
203 RoughLocation::Fine pos(ToPos(index));
204 for (int face = 0; face < Block::FACE_COUNT; ++face) {
205 BlockLookup next_block(this, pos, Block::Face(face));
207 level = std::max(level, next_block.GetLight());
211 SetLight(index, level - 1);
212 light_queue.emplace(this, pos);
218 void Chunk::ScanLights() {
220 RoughLocation::Fine pos(0, 0, 0);
221 for (; pos.z < side; ++pos.z) {
222 for (pos.y = 0; pos.y < side; ++pos.y) {
223 for (pos.x = 0; pos.x < side; ++pos.x, ++idx) {
224 const BlockType &type = Type(blocks[idx]);
225 if (type.luminosity) {
226 SetLight(idx, type.luminosity);
227 light_queue.emplace(this, pos);
236 void Chunk::SetNeighbor(Block::Face face, Chunk &other) noexcept {
237 neighbor[face] = &other;
238 other.neighbor[Block::Opposite(face)] = this;
241 void Chunk::Unlink() noexcept {
242 for (int face = 0; face < Block::FACE_COUNT; ++face) {
243 if (neighbor[face]) {
244 neighbor[face]->neighbor[Block::Opposite(Block::Face(face))] = nullptr;
245 neighbor[face] = nullptr;
251 void Chunk::SetLight(int index, int level) noexcept {
252 if (light[index] != level) {
253 light[index] = level;
258 int Chunk::GetLight(int index) const noexcept {
262 float Chunk::GetVertexLight(const RoughLocation::Fine &pos, const BlockMesh::Position &vtx, const EntityMesh::Normal &norm) const noexcept {
263 int index = ToIndex(pos);
264 float light = GetLight(index);
266 Block::Face direct_face(Block::NormalFace(norm));
268 BlockLookup direct(const_cast<Chunk *>(this), pos, Block::NormalFace(norm));
270 float direct_light = direct.GetLight();
271 if (direct_light > light) {
272 light = direct_light;
278 if (Type(BlockAt(index)).luminosity > 0 || direct.GetType().block_light) {
283 switch (Block::Axis(direct_face)) {
285 edge[0] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
286 edge[1] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
289 edge[0] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
290 edge[1] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
293 edge[0] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
294 edge[1] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
301 BlockLookup next[2] = {
302 direct.Next(edge[0]),
303 direct.Next(edge[1]),
307 if (next[0].GetType().block_light) {
310 light += next[0].GetLight();
315 if (next[1].GetType().block_light) {
318 light += next[1].GetLight();
324 BlockLookup corner = next[0].Next(edge[1]);
326 if (corner.GetType().block_light) {
329 light += corner.GetLight();
333 } else if (next[1]) {
334 BlockLookup corner = next[1].Next(edge[0]);
336 if (corner.GetType().block_light) {
339 light += corner.GetLight();
348 return (light / num) - (occlusion * 0.8f);
352 bool Chunk::IsSurface(const RoughLocation::Fine &pos) const noexcept {
353 const Block &block = BlockAt(pos);
354 if (!Type(block).visible) {
357 for (int face = 0; face < Block::FACE_COUNT; ++face) {
358 BlockLookup next = BlockLookup(const_cast<Chunk *>(this), pos, Block::Face(face));
359 if (!next || !next.GetType().visible) {
367 bool Chunk::Intersection(
369 const ExactLocation::Coarse &reference,
375 coll.depth = std::numeric_limits<float>::infinity();
376 for (int z = 0; z < side; ++z) {
377 for (int y = 0; y < side; ++y) {
378 for (int x = 0; x < side; ++x, ++idx) {
379 const BlockType &type = Type(idx);
380 if (!type.collision || !type.shape) {
385 if (type.shape->Intersects(ray, ToTransform(reference, RoughLocation::Fine(x, y, z), idx), cur_dist, cur_norm)) {
386 if (cur_dist < coll.depth) {
388 coll.depth = cur_dist;
389 coll.normal = cur_norm;
396 if (coll.block < 0) {
399 coll.normal = glm::vec3(BlockAt(coll.block).Transform() * glm::vec4(coll.normal, 0.0f));
404 bool Chunk::Intersection(
406 const glm::mat4 &Mbox,
407 const glm::mat4 &Mchunk,
408 std::vector<WorldCollision> &col
414 if (!blank::Intersection(box, Mbox, Bounds(), Mchunk, penetration, normal)) {
418 // box's origin relative to the chunk
419 const glm::vec3 box_coords(Mbox[3] - Mchunk[3]);
420 const float box_rad = box.OriginRadius();
422 // assume a bounding radius of 2 for blocks
423 constexpr float block_rad = 2.0f;
424 const float bb_radius = box_rad + block_rad;
426 const RoughLocation::Fine begin(max(
427 RoughLocation::Fine(0),
428 RoughLocation::Fine(floor(box_coords - bb_radius))
430 const RoughLocation::Fine end(min(
431 RoughLocation::Fine(side - 1),
432 RoughLocation::Fine(ceil(box_coords + bb_radius))
435 for (RoughLocation::Fine pos(begin); pos.z < end.y; ++pos.z) {
436 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
437 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
438 int idx = ToIndex(pos);
439 const BlockType &type = Type(idx);
440 if (!type.collision || !type.shape) {
443 if (type.shape->Intersects(Mchunk * ToTransform(pos, idx), box, Mbox, penetration, normal)) {
444 col.emplace_back(this, idx, penetration, normal);
453 bool Chunk::Intersection(
454 const Entity &entity,
455 const glm::mat4 &Mentity,
456 const glm::mat4 &Mchunk,
457 std::vector<WorldCollision> &col
459 // entity's origin relative to the chunk
460 const glm::vec3 entity_coords(Mentity[3] - Mchunk[3]);
461 const float ec_radius = entity.Radius() + Radius();
463 if (distance2(entity_coords, Center()) > ec_radius * ec_radius) {
471 // assume a bounding radius of 2 for blocks
472 constexpr float block_rad = 2.0f;
473 const float eb_radius = entity.Radius() + block_rad;
475 const RoughLocation::Fine begin(max(
476 RoughLocation::Fine(0),
477 RoughLocation::Fine(floor(entity_coords - eb_radius))
479 const RoughLocation::Fine end(min(
480 RoughLocation::Fine(side),
481 RoughLocation::Fine(ceil(entity_coords + eb_radius))
484 for (RoughLocation::Fine pos(begin); pos.z < end.z; ++pos.z) {
485 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
486 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
487 int idx = ToIndex(pos);
488 const BlockType &type = Type(idx);
489 if (!type.collision || !type.shape) {
492 if (type.shape->Intersects(Mchunk * ToTransform(pos, idx), entity.Bounds(), Mentity, penetration, normal)) {
493 col.emplace_back(this, idx, penetration, normal);
505 BlockMesh::Buffer buf;
509 void Chunk::Update(BlockMesh &model) noexcept {
510 int vtx_count = 0, idx_count = 0;
511 for (const auto &block : blocks) {
512 const BlockType &type = Type(block);
513 if (type.visible && type.shape) {
514 vtx_count += type.shape->VertexCount();
515 idx_count += type.shape->IndexCount();
519 buf.Reserve(vtx_count, idx_count);
523 BlockMesh::Index vtx_counter = 0;
524 for (size_t z = 0; z < side; ++z) {
525 for (size_t y = 0; y < side; ++y) {
526 for (size_t x = 0; x < side; ++x, ++idx) {
527 const BlockType &type = Type(BlockAt(idx));
528 const RoughLocation::Fine pos(x, y, z);
530 if (!type.visible || !type.shape || Obstructed(pos).All()) continue;
532 type.FillBlockMesh(buf, ToTransform(pos, idx), vtx_counter);
533 size_t vtx_begin = vtx_counter;
534 vtx_counter += type.shape->VertexCount();
536 for (size_t vtx = vtx_begin; vtx < vtx_counter; ++vtx) {
537 buf.lights.emplace_back(GetVertexLight(
540 type.shape->VertexNormal(vtx - vtx_begin, BlockAt(idx).Transform())
552 Block::FaceSet Chunk::Obstructed(const RoughLocation::Fine &pos) const noexcept {
553 Block::FaceSet result;
555 for (int f = 0; f < Block::FACE_COUNT; ++f) {
556 Block::Face face = Block::Face(f);
557 BlockLookup next(const_cast<Chunk *>(this), pos, face);
558 if (next && next.GetType().FaceFilled(next.GetBlock(), Block::Opposite(face))) {
566 glm::mat4 Chunk::ToTransform(const RoughLocation::Fine &pos, int idx) const noexcept {
567 return glm::translate(ToCoords(pos)) * BlockAt(idx).Transform();
570 glm::mat4 Chunk::ToTransform(const ExactLocation::Coarse &ref, const RoughLocation::Fine &pos, int idx) const noexcept {
571 return glm::translate(ExactLocation::Fine((position - ref) * ExactLocation::Extent()) + ToCoords(pos)) * BlockAt(idx).Transform();
575 BlockLookup::BlockLookup(Chunk *c, const RoughLocation::Fine &p) noexcept
577 while (pos.x >= Chunk::side) {
578 if (chunk->HasNeighbor(Block::FACE_RIGHT)) {
579 chunk = &chunk->GetNeighbor(Block::FACE_RIGHT);
580 pos.x -= Chunk::side;
587 if (chunk->HasNeighbor(Block::FACE_LEFT)) {
588 chunk = &chunk->GetNeighbor(Block::FACE_LEFT);
589 pos.x += Chunk::side;
595 while (pos.y >= Chunk::side) {
596 if (chunk->HasNeighbor(Block::FACE_UP)) {
597 chunk = &chunk->GetNeighbor(Block::FACE_UP);
598 pos.y -= Chunk::side;
605 if (chunk->HasNeighbor(Block::FACE_DOWN)) {
606 chunk = &chunk->GetNeighbor(Block::FACE_DOWN);
607 pos.y += Chunk::side;
613 while (pos.z >= Chunk::side) {
614 if (chunk->HasNeighbor(Block::FACE_FRONT)) {
615 chunk = &chunk->GetNeighbor(Block::FACE_FRONT);
616 pos.z -= Chunk::side;
623 if (chunk->HasNeighbor(Block::FACE_BACK)) {
624 chunk = &chunk->GetNeighbor(Block::FACE_BACK);
625 pos.z += Chunk::side;
633 BlockLookup::BlockLookup(Chunk *c, const RoughLocation::Fine &p, Block::Face face) noexcept
635 pos += Block::FaceNormal(face);
636 if (!Chunk::InBounds(pos)) {
637 pos -= Block::FaceNormal(face) * ExactLocation::Extent();
638 chunk = &chunk->GetNeighbor(face);
643 ChunkLoader::ChunkLoader(
645 const Generator &gen,
646 const WorldSave &save
654 void ChunkLoader::Update(int dt) {
655 // check if there's chunks waiting to be loaded
656 // load until one of load or generation limits was hit
657 constexpr int max_load = 10;
658 constexpr int max_gen = 1;
661 while (loaded < max_load && generated < max_gen && store.HasMissing()) {
669 // store a few chunks as well
670 constexpr int max_save = 10;
672 for (Chunk &chunk : store) {
673 if (chunk.ShouldUpdateSave()) {
676 if (saved >= max_save) {
683 int ChunkLoader::ToLoad() const noexcept {
684 return store.EstimateMissing();
687 bool ChunkLoader::LoadOne() {
688 if (!store.HasMissing()) return false;
690 ExactLocation::Coarse pos = store.NextMissing();
691 Chunk *chunk = store.Allocate(pos);
693 // chunk store corrupted?
697 bool generated = false;
698 if (save.Exists(pos)) {
705 ChunkIndex *index = store.ClosestIndex(pos);
710 ExactLocation::Coarse begin(pos - ExactLocation::Coarse(1));
711 ExactLocation::Coarse end(pos + ExactLocation::Coarse(2));
712 for (ExactLocation::Coarse iter(begin); iter.z < end.z; ++iter.z) {
713 for (iter.y = begin.y; iter.y < end.y; ++iter.y) {
714 for (iter.x = begin.x; iter.x < end.x; ++iter.x) {
715 if (index->IsBorder(iter)) continue;
716 Chunk *light_chunk = index->Get(iter);
717 if (!light_chunk) continue;
718 if (index->HasAllSurrounding(iter)) {
719 if (!light_chunk->Lighted()) {
720 light_chunk->ScanLights();
722 light_chunk->InvalidateMesh();
732 void ChunkLoader::LoadN(std::size_t n) {
733 std::size_t end = std::min(n, std::size_t(ToLoad()));
734 for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
740 ChunkRenderer::ChunkRenderer(ChunkIndex &index)
742 , models(index.TotalChunks())
744 , fog_density(0.0f) {
748 ChunkRenderer::~ChunkRenderer() {
752 int ChunkRenderer::MissingChunks() const noexcept {
753 return index.MissingChunks();
756 void ChunkRenderer::LoadTextures(const AssetLoader &loader, const ResourceIndex &tex_index) {
758 loader.LoadTextures(tex_index, block_tex);
759 block_tex.FilterNearest();
762 void ChunkRenderer::Update(int dt) {
763 for (int i = 0, updates = 0; updates < dt && i < index.TotalChunks(); ++i) {
764 if (!index[i]) continue;
765 if (!index[i]->Lighted() && index.HasAllSurrounding(index[i]->Position())) {
766 index[i]->ScanLights();
768 if (index[i]->ShouldUpdateMesh()) {
769 index[i]->Update(models[i]);
775 void ChunkRenderer::Render(Viewport &viewport) {
776 BlockLighting &chunk_prog = viewport.ChunkProgram();
777 chunk_prog.SetTexture(block_tex);
778 chunk_prog.SetFogDensity(fog_density);
780 for (int i = 0; i < index.TotalChunks(); ++i) {
781 if (!index[i]) continue;
782 // TODO: optimize chunk culling, shoudn't be that hard
783 glm::mat4 m(index[i]->Transform(index.Base()));
784 glm::mat4 mvp(chunk_prog.GetVP() * m);
785 if (!CullTest(Chunk::Bounds(), mvp)) {
786 if (index[i]->ShouldUpdateMesh()) {
787 index[i]->Update(models[i]);
796 ChunkIndex::ChunkIndex(ChunkStore &store, const ExactLocation::Coarse &base, int extent)
800 , side_length(2 * extent + 1)
801 , total_length(side_length * side_length * side_length)
804 , stride(1, side_length, side_length * side_length)
805 , chunks(total_length, nullptr) {
809 ChunkIndex::~ChunkIndex() {
813 bool ChunkIndex::InRange(const ExactLocation::Coarse &pos) const noexcept {
814 return Distance(pos) <= extent;
817 bool ChunkIndex::IsBorder(const ExactLocation::Coarse &pos) const noexcept {
818 return Distance(pos) == extent;
821 int ChunkIndex::Distance(const ExactLocation::Coarse &pos) const noexcept {
822 return manhattan_radius(pos - base);
825 bool ChunkIndex::HasAllSurrounding(const ExactLocation::Coarse &pos) const noexcept {
826 ExactLocation::Coarse begin(pos - ExactLocation::Coarse(1));
827 ExactLocation::Coarse end(pos + ExactLocation::Coarse(2));
828 for (ExactLocation::Coarse iter(begin); iter.z < end.z; ++iter.z) {
829 for (iter.y = begin.y; iter.y < end.y; ++iter.y) {
830 for (iter.x = begin.x; iter.x < end.x; ++iter.x) {
831 if (!Get(iter)) return false;
838 int ChunkIndex::IndexOf(const ExactLocation::Coarse &pos) const noexcept {
839 ExactLocation::Coarse mod_pos(
844 return mod_pos.x * stride.x
845 + mod_pos.y * stride.y
846 + mod_pos.z * stride.z;
849 ExactLocation::Coarse ChunkIndex::PositionOf(int i) const noexcept {
850 ExactLocation::Coarse zero_pos(
851 (i / stride.x) % side_length,
852 (i / stride.y) % side_length,
853 (i / stride.z) % side_length
855 ExactLocation::Coarse zero_base(
860 ExactLocation::Coarse base_relative(zero_pos - zero_base);
861 if (base_relative.x > extent) base_relative.x -= side_length;
862 else if (base_relative.x < -extent) base_relative.x += side_length;
863 if (base_relative.y > extent) base_relative.y -= side_length;
864 else if (base_relative.y < -extent) base_relative.y += side_length;
865 if (base_relative.z > extent) base_relative.z -= side_length;
866 else if (base_relative.z < -extent) base_relative.z += side_length;
867 return base + base_relative;
870 Chunk *ChunkIndex::Get(const ExactLocation::Coarse &pos) noexcept {
872 return chunks[IndexOf(pos)];
878 const Chunk *ChunkIndex::Get(const ExactLocation::Coarse &pos) const noexcept {
880 return chunks[IndexOf(pos)];
886 void ChunkIndex::Rebase(const ExactLocation::Coarse &new_base) {
887 if (new_base == base) return;
889 ExactLocation::Coarse diff(new_base - base);
891 if (manhattan_radius(diff) > extent) {
892 // that's more than half, so probably not worth shifting
901 Shift(Block::FACE_RIGHT);
905 Shift(Block::FACE_LEFT);
909 Shift(Block::FACE_UP);
913 Shift(Block::FACE_DOWN);
917 Shift(Block::FACE_FRONT);
921 Shift(Block::FACE_BACK);
927 int ChunkIndex::GetCol(int c) const noexcept {
929 if (c < 0) c += side_length;
933 void ChunkIndex::Shift(Block::Face f) {
934 int a_axis = Block::Axis(f);
935 int b_axis = (a_axis + 1) % 3;
936 int c_axis = (a_axis + 2) % 3;
937 int dir = Block::Direction(f);
939 int a = GetCol(base[a_axis] + (extent * dir));
940 int a_stride = a * stride[a_axis];
941 for (int b = 0; b < side_length; ++b) {
942 int b_stride = b * stride[b_axis];
943 for (int c = 0; c < side_length; ++c) {
944 int bc_stride = b_stride + c * stride[c_axis];
945 int index = a_stride + bc_stride;
947 int neighbor = ((a - dir + side_length) % side_length) * stride[a_axis] + bc_stride;
948 if (chunks[neighbor] && chunks[neighbor]->HasNeighbor(f)) {
949 Set(index, chunks[neighbor]->GetNeighbor(f));
955 void ChunkIndex::Clear() noexcept {
956 for (int i = 0; i < total_length && total_indexed > 0; ++i) {
961 void ChunkIndex::Scan() noexcept {
962 for (Chunk &chunk : store) {
967 void ChunkIndex::Register(Chunk &chunk) noexcept {
968 if (InRange(chunk.Position())) {
969 Set(IndexOf(chunk.Position()), chunk);
973 void ChunkIndex::Set(int index, Chunk &chunk) noexcept {
975 chunks[index] = &chunk;
980 void ChunkIndex::Unset(int index) noexcept {
982 chunks[index]->UnRef();
983 chunks[index] = nullptr;
988 ExactLocation::Coarse ChunkIndex::NextMissing() noexcept {
989 if (MissingChunks() > 0) {
990 int roundtrip = last_missing;
991 last_missing = (last_missing + 1) % total_length;
992 while (chunks[last_missing]) {
993 last_missing = (last_missing + 1) % total_length;
994 if (last_missing == roundtrip) {
999 return PositionOf(last_missing);
1003 ChunkStore::ChunkStore(const BlockTypeRegistry &types)
1011 ChunkStore::~ChunkStore() {
1015 ChunkIndex &ChunkStore::MakeIndex(const ExactLocation::Coarse &pos, int extent) {
1016 indices.emplace_back(*this, pos, extent);
1017 return indices.back();
1020 void ChunkStore::UnregisterIndex(ChunkIndex &index) {
1021 for (auto i = indices.begin(), end = indices.end(); i != end; ++i) {
1022 if (&*i == &index) {
1031 ChunkIndex *ChunkStore::ClosestIndex(const ExactLocation::Coarse &pos) {
1032 ChunkIndex *closest_index = nullptr;
1033 int closest_distance = std::numeric_limits<int>::max();
1035 for (ChunkIndex &index : indices) {
1036 int distance = index.Distance(pos);
1037 if (distance < closest_distance) {
1038 closest_index = &index;
1039 closest_distance = distance;
1043 return closest_index;
1046 Chunk *ChunkStore::Get(const ExactLocation::Coarse &pos) {
1047 for (ChunkIndex &index : indices) {
1048 Chunk *chunk = index.Get(pos);
1056 Chunk *ChunkStore::Allocate(const ExactLocation::Coarse &pos) {
1057 Chunk *chunk = Get(pos);
1062 loaded.emplace(loaded.begin(), types);
1064 loaded.splice(loaded.begin(), free, free.begin());
1065 loaded.front().Unlink();
1067 chunk = &loaded.front();
1068 chunk->Position(pos);
1069 for (ChunkIndex &index : indices) {
1070 if (index.InRange(pos)) {
1071 index.Register(*chunk);
1074 for (int i = 0; i < Block::FACE_COUNT; ++i) {
1075 Block::Face face = Block::Face(i);
1076 ExactLocation::Coarse neighbor_pos(pos + Block::FaceNormal(face));
1077 Chunk *neighbor = Get(neighbor_pos);
1079 chunk->SetNeighbor(face, *neighbor);
1085 bool ChunkStore::HasMissing() const noexcept {
1086 for (const ChunkIndex &index : indices) {
1087 if (index.MissingChunks() > 0) {
1094 int ChunkStore::EstimateMissing() const noexcept {
1096 for (const ChunkIndex &index : indices) {
1097 missing += index.MissingChunks();
1102 ExactLocation::Coarse ChunkStore::NextMissing() noexcept {
1103 for (ChunkIndex &index : indices) {
1104 if (index.MissingChunks()) {
1105 return index.NextMissing();
1108 return ExactLocation::Coarse(0, 0, 0);
1111 void ChunkStore::Clean() {
1112 for (auto i = loaded.begin(), end = loaded.end(); i != end;) {
1113 if (i->Referenced() || i->ShouldUpdateSave()) {
1118 free.splice(free.end(), loaded, chunk);
1120 chunk->InvalidateMesh();