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
44 Chunk::Chunk(Chunk &&other) noexcept
46 , gravity(std::move(other.gravity))
47 , generated(other.generated)
48 , lighted(other.lighted)
49 , position(other.position)
50 , ref_count(other.ref_count)
51 , dirty_mesh(other.dirty_mesh)
52 , dirty_save(other.dirty_save) {
53 std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
54 std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
55 std::copy(other.light, other.light + sizeof(light), light);
59 Chunk &Chunk::operator =(Chunk &&other) noexcept {
61 std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
62 gravity = std::move(other.gravity);
63 std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
64 std::copy(other.light, other.light + sizeof(light), light);
65 generated = other.generated;
66 lighted = other.lighted;
67 position = other.position;
68 std::swap(ref_count, other.ref_count);
69 dirty_mesh = other.dirty_save;
70 dirty_save = other.dirty_save;
80 RoughLocation::Fine pos;
82 SetNode(Chunk *chunk, RoughLocation::Fine pos)
83 : chunk(chunk), pos(pos) { }
85 int Get() const noexcept { return chunk->GetLight(pos); }
86 void Set(int level) noexcept { chunk->SetLight(pos, level); }
88 const BlockType &GetType() const noexcept { return chunk->Type(Chunk::ToIndex(pos)); }
90 int EmitLevel() const noexcept { return GetType().luminosity; }
91 bool EmitsLight() const noexcept { return EmitLevel() > 0; }
93 bool HasNext(Block::Face face) noexcept {
94 const BlockType &type = GetType();
95 if (type.block_light && !type.luminosity) return false;
96 const BlockLookup next(chunk, pos, face);
99 SetNode GetNext(Block::Face face) noexcept {
100 const BlockLookup next(chunk, pos, face);
101 return SetNode(&next.GetChunk(), next.GetBlockPos());
111 UnsetNode(Chunk *chunk, RoughLocation::Fine pos)
112 : SetNode(chunk, pos), level(Get()) { }
114 UnsetNode(const SetNode &set)
115 : SetNode(set), level(Get()) { }
118 bool HasNext(Block::Face face) noexcept {
119 const BlockLookup next(chunk, pos, face);
122 UnsetNode GetNext(Block::Face face) noexcept { return UnsetNode(SetNode::GetNext(face)); }
126 std::queue<SetNode> light_queue;
127 std::queue<UnsetNode> dark_queue;
129 void work_light() noexcept {
130 while (!light_queue.empty()) {
131 SetNode node = light_queue.front();
134 int level = node.Get() - 1;
135 for (int face = 0; face < Block::FACE_COUNT; ++face) {
136 if (node.HasNext(Block::Face(face))) {
137 SetNode other = node.GetNext(Block::Face(face));
138 if (other.Get() < level) {
140 light_queue.emplace(other);
147 void work_dark() noexcept {
148 while (!dark_queue.empty()) {
149 UnsetNode node = dark_queue.front();
152 for (int face = 0; face < Block::FACE_COUNT; ++face) {
153 if (node.HasNext(Block::Face(face))) {
154 UnsetNode other = node.GetNext(Block::Face(face));
155 if (other.Get() != 0 && other.Get() < node.level) {
156 if (other.EmitsLight()) {
157 other.Set(other.EmitLevel());
158 light_queue.emplace(other);
162 dark_queue.emplace(other);
164 light_queue.emplace(other);
173 void Chunk::SetBlock(int index, const Block &block) noexcept {
174 const BlockType &old_type = Type(blocks[index]);
175 const BlockType &new_type = Type(block);
177 blocks[index] = block;
180 if (old_type.gravity && !new_type.gravity) {
181 gravity.erase(index);
182 } else if (new_type.gravity && !old_type.gravity) {
183 gravity.insert(index);
186 if (!lighted || &old_type == &new_type) return;
188 if (new_type.luminosity > old_type.luminosity) {
190 SetLight(index, new_type.luminosity);
191 light_queue.emplace(this, ToPos(index));
193 } else if (new_type.luminosity < old_type.luminosity) {
195 dark_queue.emplace(this, ToPos(index));
198 SetLight(index, new_type.luminosity);
199 light_queue.emplace(this, ToPos(index));
201 } else if (new_type.block_light && !old_type.block_light) {
203 if (GetLight(index) > 0) {
204 dark_queue.emplace(this, ToPos(index));
209 } else if (!new_type.block_light && old_type.block_light) {
212 RoughLocation::Fine pos(ToPos(index));
213 for (int face = 0; face < Block::FACE_COUNT; ++face) {
214 BlockLookup next_block(this, pos, Block::Face(face));
216 level = std::max(level, next_block.GetLight());
220 SetLight(index, level - 1);
221 light_queue.emplace(this, pos);
227 void Chunk::ScanLights() {
229 RoughLocation::Fine pos(0, 0, 0);
230 for (; pos.z < side; ++pos.z) {
231 for (pos.y = 0; pos.y < side; ++pos.y) {
232 for (pos.x = 0; pos.x < side; ++pos.x, ++idx) {
233 const BlockType &type = Type(blocks[idx]);
234 if (type.luminosity) {
235 SetLight(idx, type.luminosity);
236 light_queue.emplace(this, pos);
245 void Chunk::ScanActive() {
247 for (int index = 0; index < size; ++index) {
248 if (Type(index).gravity) {
249 gravity.insert(gravity.end(), index);
254 void Chunk::SetNeighbor(Block::Face face, Chunk &other) noexcept {
255 neighbor[face] = &other;
256 other.neighbor[Block::Opposite(face)] = this;
259 void Chunk::Unlink() noexcept {
260 for (int face = 0; face < Block::FACE_COUNT; ++face) {
261 if (neighbor[face]) {
262 neighbor[face]->neighbor[Block::Opposite(Block::Face(face))] = nullptr;
263 neighbor[face] = nullptr;
269 void Chunk::SetLight(int index, int level) noexcept {
270 if (light[index] != level) {
271 light[index] = level;
276 int Chunk::GetLight(int index) const noexcept {
280 float Chunk::GetVertexLight(const RoughLocation::Fine &pos, const BlockMesh::Position &vtx, const EntityMesh::Normal &norm) const noexcept {
281 int index = ToIndex(pos);
282 float light = GetLight(index);
284 Block::Face direct_face(Block::NormalFace(norm));
286 BlockLookup direct(const_cast<Chunk *>(this), pos, Block::NormalFace(norm));
288 float direct_light = direct.GetLight();
289 if (direct_light > light) {
290 light = direct_light;
296 if (Type(BlockAt(index)).luminosity > 0 || direct.GetType().block_light) {
301 switch (Block::Axis(direct_face)) {
303 edge[0] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
304 edge[1] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
307 edge[0] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
308 edge[1] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
311 edge[0] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
312 edge[1] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
319 BlockLookup next[2] = {
320 direct.Next(edge[0]),
321 direct.Next(edge[1]),
325 if (next[0].GetType().block_light) {
328 light += next[0].GetLight();
333 if (next[1].GetType().block_light) {
336 light += next[1].GetLight();
342 BlockLookup corner = next[0].Next(edge[1]);
344 if (corner.GetType().block_light) {
347 light += corner.GetLight();
351 } else if (next[1]) {
352 BlockLookup corner = next[1].Next(edge[0]);
354 if (corner.GetType().block_light) {
357 light += corner.GetLight();
366 return (light / num) - (occlusion * 0.8f);
370 glm::vec3 Chunk::GravityAt(const ExactLocation &coords) const noexcept {
372 for (int index : gravity) {
373 RoughLocation::Fine block_pos(ToPos(index));
374 ExactLocation block_coords(position, ToCoords(block_pos));
375 // trust that block type hasn't changed
376 grav += Type(index).gravity->GetGravity(
377 coords.Difference(block_coords).Absolute(),
378 ToTransform(block_pos, index));
384 bool Chunk::IsSurface(const RoughLocation::Fine &pos) const noexcept {
385 const Block &block = BlockAt(pos);
386 if (!Type(block).visible) {
389 for (int face = 0; face < Block::FACE_COUNT; ++face) {
390 BlockLookup next = BlockLookup(const_cast<Chunk *>(this), pos, Block::Face(face));
391 if (!next || !next.GetType().visible) {
399 bool Chunk::Intersection(
401 const ExactLocation::Coarse &reference,
407 coll.depth = std::numeric_limits<float>::infinity();
408 for (int z = 0; z < side; ++z) {
409 for (int y = 0; y < side; ++y) {
410 for (int x = 0; x < side; ++x, ++idx) {
411 const BlockType &type = Type(idx);
412 if (!type.collision || !type.shape) {
417 if (type.shape->Intersects(ray, ToTransform(reference, RoughLocation::Fine(x, y, z), idx), cur_dist, cur_norm)) {
418 if (cur_dist < coll.depth) {
420 coll.depth = cur_dist;
421 coll.normal = cur_norm;
428 if (coll.block < 0) {
431 coll.normal = glm::vec3(BlockAt(coll.block).Transform() * glm::vec4(coll.normal, 0.0f));
436 bool Chunk::Intersection(
438 const glm::mat4 &Mbox,
439 const glm::mat4 &Mchunk,
440 std::vector<WorldCollision> &col
446 if (!blank::Intersection(box, Mbox, Bounds(), Mchunk, penetration, normal)) {
450 // box's origin relative to the chunk
451 const glm::vec3 box_coords(Mbox[3] - Mchunk[3]);
452 const float box_rad = box.OriginRadius();
454 // assume a bounding radius of 2 for blocks
455 constexpr float block_rad = 2.0f;
456 const float bb_radius = box_rad + block_rad;
458 const RoughLocation::Fine begin(max(
459 RoughLocation::Fine(0),
460 RoughLocation::Fine(floor(box_coords - bb_radius))
462 const RoughLocation::Fine end(min(
463 RoughLocation::Fine(side - 1),
464 RoughLocation::Fine(ceil(box_coords + bb_radius))
467 for (RoughLocation::Fine pos(begin); pos.z < end.y; ++pos.z) {
468 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
469 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
470 int idx = ToIndex(pos);
471 const BlockType &type = Type(idx);
472 if (!type.collision || !type.shape) {
475 if (type.shape->Intersects(Mchunk * ToTransform(pos, idx), box, Mbox, penetration, normal)) {
476 col.emplace_back(this, idx, penetration, normal);
485 bool Chunk::Intersection(
486 const Entity &entity,
487 const glm::mat4 &Mentity,
488 const glm::mat4 &Mchunk,
489 std::vector<WorldCollision> &col
491 // entity's origin relative to the chunk
492 const glm::vec3 entity_coords(Mentity[3] - Mchunk[3]);
493 const float ec_radius = entity.Radius() + Radius();
495 if (distance2(entity_coords, Center()) > ec_radius * ec_radius) {
503 // assume a bounding radius of 2 for blocks
504 constexpr float block_rad = 2.0f;
505 const float eb_radius = entity.Radius() + block_rad;
507 const RoughLocation::Fine begin(max(
508 RoughLocation::Fine(0),
509 RoughLocation::Fine(floor(entity_coords - eb_radius))
511 const RoughLocation::Fine end(min(
512 RoughLocation::Fine(side),
513 RoughLocation::Fine(ceil(entity_coords + eb_radius))
516 for (RoughLocation::Fine pos(begin); pos.z < end.z; ++pos.z) {
517 for (pos.y = begin.y; pos.y < end.y; ++pos.y) {
518 for (pos.x = begin.x; pos.x < end.x; ++pos.x) {
519 int idx = ToIndex(pos);
520 const BlockType &type = Type(idx);
521 if (!type.collision || !type.shape) {
524 if (type.shape->Intersects(Mchunk * ToTransform(pos, idx), entity.Bounds(), Mentity, penetration, normal)) {
525 col.emplace_back(this, idx, penetration, normal);
537 BlockMesh::Buffer buf;
541 void Chunk::Update(BlockMesh &model) noexcept {
542 int vtx_count = 0, idx_count = 0;
543 for (const auto &block : blocks) {
544 const BlockType &type = Type(block);
545 if (type.visible && type.shape) {
546 vtx_count += type.shape->VertexCount();
547 idx_count += type.shape->IndexCount();
551 buf.Reserve(vtx_count, idx_count);
555 BlockMesh::Index vtx_counter = 0;
556 for (size_t z = 0; z < side; ++z) {
557 for (size_t y = 0; y < side; ++y) {
558 for (size_t x = 0; x < side; ++x, ++idx) {
559 const BlockType &type = Type(BlockAt(idx));
560 const RoughLocation::Fine pos(x, y, z);
562 if (!type.visible || !type.shape || Obstructed(pos).All()) continue;
564 type.FillBlockMesh(buf, ToTransform(pos, idx), vtx_counter);
565 size_t vtx_begin = vtx_counter;
566 vtx_counter += type.shape->VertexCount();
568 for (size_t vtx = vtx_begin; vtx < vtx_counter; ++vtx) {
569 buf.lights.emplace_back(GetVertexLight(
572 type.shape->VertexNormal(vtx - vtx_begin, BlockAt(idx).Transform())
584 Block::FaceSet Chunk::Obstructed(const RoughLocation::Fine &pos) const noexcept {
585 Block::FaceSet result;
587 for (int f = 0; f < Block::FACE_COUNT; ++f) {
588 Block::Face face = Block::Face(f);
589 BlockLookup next(const_cast<Chunk *>(this), pos, face);
590 if (next && next.GetType().FaceFilled(next.GetBlock(), Block::Opposite(face))) {
598 glm::mat4 Chunk::ToTransform(const RoughLocation::Fine &pos, int idx) const noexcept {
599 return glm::translate(ToCoords(pos)) * BlockAt(idx).Transform();
602 glm::mat4 Chunk::ToTransform(const ExactLocation::Coarse &ref, const RoughLocation::Fine &pos, int idx) const noexcept {
603 return glm::translate(ExactLocation::Fine((position - ref) * ExactLocation::Extent()) + ToCoords(pos)) * BlockAt(idx).Transform();
607 BlockLookup::BlockLookup(Chunk *c, const RoughLocation::Fine &p) noexcept
609 while (pos.x >= Chunk::side) {
610 if (chunk->HasNeighbor(Block::FACE_RIGHT)) {
611 chunk = &chunk->GetNeighbor(Block::FACE_RIGHT);
612 pos.x -= Chunk::side;
619 if (chunk->HasNeighbor(Block::FACE_LEFT)) {
620 chunk = &chunk->GetNeighbor(Block::FACE_LEFT);
621 pos.x += Chunk::side;
627 while (pos.y >= Chunk::side) {
628 if (chunk->HasNeighbor(Block::FACE_UP)) {
629 chunk = &chunk->GetNeighbor(Block::FACE_UP);
630 pos.y -= Chunk::side;
637 if (chunk->HasNeighbor(Block::FACE_DOWN)) {
638 chunk = &chunk->GetNeighbor(Block::FACE_DOWN);
639 pos.y += Chunk::side;
645 while (pos.z >= Chunk::side) {
646 if (chunk->HasNeighbor(Block::FACE_FRONT)) {
647 chunk = &chunk->GetNeighbor(Block::FACE_FRONT);
648 pos.z -= Chunk::side;
655 if (chunk->HasNeighbor(Block::FACE_BACK)) {
656 chunk = &chunk->GetNeighbor(Block::FACE_BACK);
657 pos.z += Chunk::side;
665 BlockLookup::BlockLookup(Chunk *c, const RoughLocation::Fine &p, Block::Face face) noexcept
667 pos += Block::FaceNormal(face);
668 if (!Chunk::InBounds(pos)) {
669 pos -= Block::FaceNormal(face) * ExactLocation::Extent();
670 chunk = &chunk->GetNeighbor(face);
675 ChunkLoader::ChunkLoader(
677 const Generator &gen,
678 const WorldSave &save
686 void ChunkLoader::Update(int dt) {
687 // check if there's chunks waiting to be loaded
688 // load until one of load or generation limits was hit
689 constexpr int max_load = 10;
690 constexpr int max_gen = 1;
693 while (loaded < max_load && generated < max_gen && store.HasMissing()) {
701 // store a few chunks as well
702 constexpr int max_save = 10;
704 for (Chunk &chunk : store) {
705 if (chunk.ShouldUpdateSave()) {
708 if (saved >= max_save) {
715 int ChunkLoader::ToLoad() const noexcept {
716 return store.EstimateMissing();
719 bool ChunkLoader::LoadOne() {
720 if (!store.HasMissing()) return false;
722 ExactLocation::Coarse pos = store.NextMissing();
723 Chunk *chunk = store.Allocate(pos);
725 // chunk store corrupted?
729 bool generated = false;
730 if (save.Exists(pos)) {
737 ChunkIndex *index = store.ClosestIndex(pos);
742 ExactLocation::Coarse begin(pos - ExactLocation::Coarse(1));
743 ExactLocation::Coarse end(pos + ExactLocation::Coarse(2));
744 for (ExactLocation::Coarse iter(begin); iter.z < end.z; ++iter.z) {
745 for (iter.y = begin.y; iter.y < end.y; ++iter.y) {
746 for (iter.x = begin.x; iter.x < end.x; ++iter.x) {
747 if (index->IsBorder(iter)) continue;
748 Chunk *light_chunk = index->Get(iter);
749 if (!light_chunk) continue;
750 if (index->HasAllSurrounding(iter)) {
751 if (!light_chunk->Lighted()) {
752 light_chunk->ScanLights();
754 light_chunk->InvalidateMesh();
764 void ChunkLoader::LoadN(std::size_t n) {
765 std::size_t end = std::min(n, std::size_t(ToLoad()));
766 for (std::size_t i = 0; i < end && store.HasMissing(); ++i) {
772 ChunkRenderer::ChunkRenderer(ChunkIndex &index)
774 , models(index.TotalChunks())
776 , fog_density(0.0f) {
780 ChunkRenderer::~ChunkRenderer() {
784 int ChunkRenderer::MissingChunks() const noexcept {
785 return index.MissingChunks();
788 void ChunkRenderer::LoadTextures(const AssetLoader &loader, const ResourceIndex &tex_index) {
790 loader.LoadTextures(tex_index, block_tex);
791 block_tex.FilterNearest();
794 void ChunkRenderer::Update(int dt) {
795 for (int i = 0, updates = 0; updates < dt && i < index.TotalChunks(); ++i) {
796 if (!index[i]) continue;
797 if (!index[i]->Lighted() && index.HasAllSurrounding(index[i]->Position())) {
798 index[i]->ScanLights();
800 if (index[i]->ShouldUpdateMesh()) {
801 index[i]->Update(models[i]);
807 void ChunkRenderer::Render(Viewport &viewport) {
808 BlockLighting &chunk_prog = viewport.ChunkProgram();
809 chunk_prog.SetTexture(block_tex);
810 chunk_prog.SetFogDensity(fog_density);
812 for (int i = 0; i < index.TotalChunks(); ++i) {
813 if (!index[i]) continue;
814 // TODO: optimize chunk culling, shoudn't be that hard
815 glm::mat4 m(index[i]->Transform(index.Base()));
816 glm::mat4 mvp(chunk_prog.GetVP() * m);
817 if (!CullTest(Chunk::Bounds(), mvp)) {
818 if (index[i]->ShouldUpdateMesh()) {
819 index[i]->Update(models[i]);
828 ChunkIndex::ChunkIndex(ChunkStore &store, const ExactLocation::Coarse &base, int extent)
832 , side_length(2 * extent + 1)
833 , total_length(side_length * side_length * side_length)
836 , stride(1, side_length, side_length * side_length)
837 , chunks(total_length, nullptr) {
841 ChunkIndex::~ChunkIndex() {
845 bool ChunkIndex::InRange(const ExactLocation::Coarse &pos) const noexcept {
846 return Distance(pos) <= extent;
849 bool ChunkIndex::IsBorder(const ExactLocation::Coarse &pos) const noexcept {
850 return Distance(pos) == extent;
853 int ChunkIndex::Distance(const ExactLocation::Coarse &pos) const noexcept {
854 return manhattan_radius(pos - base);
857 bool ChunkIndex::HasAllSurrounding(const ExactLocation::Coarse &pos) const noexcept {
858 ExactLocation::Coarse begin(pos - ExactLocation::Coarse(1));
859 ExactLocation::Coarse end(pos + ExactLocation::Coarse(2));
860 for (ExactLocation::Coarse iter(begin); iter.z < end.z; ++iter.z) {
861 for (iter.y = begin.y; iter.y < end.y; ++iter.y) {
862 for (iter.x = begin.x; iter.x < end.x; ++iter.x) {
863 if (!Get(iter)) return false;
870 int ChunkIndex::IndexOf(const ExactLocation::Coarse &pos) const noexcept {
871 ExactLocation::Coarse mod_pos(
876 return mod_pos.x * stride.x
877 + mod_pos.y * stride.y
878 + mod_pos.z * stride.z;
881 ExactLocation::Coarse ChunkIndex::PositionOf(int i) const noexcept {
882 ExactLocation::Coarse zero_pos(
883 (i / stride.x) % side_length,
884 (i / stride.y) % side_length,
885 (i / stride.z) % side_length
887 ExactLocation::Coarse zero_base(
892 ExactLocation::Coarse base_relative(zero_pos - zero_base);
893 if (base_relative.x > extent) base_relative.x -= side_length;
894 else if (base_relative.x < -extent) base_relative.x += side_length;
895 if (base_relative.y > extent) base_relative.y -= side_length;
896 else if (base_relative.y < -extent) base_relative.y += side_length;
897 if (base_relative.z > extent) base_relative.z -= side_length;
898 else if (base_relative.z < -extent) base_relative.z += side_length;
899 return base + base_relative;
902 Chunk *ChunkIndex::Get(const ExactLocation::Coarse &pos) noexcept {
904 return chunks[IndexOf(pos)];
910 const Chunk *ChunkIndex::Get(const ExactLocation::Coarse &pos) const noexcept {
912 return chunks[IndexOf(pos)];
918 void ChunkIndex::Rebase(const ExactLocation::Coarse &new_base) {
919 if (new_base == base) return;
921 ExactLocation::Coarse diff(new_base - base);
923 if (manhattan_radius(diff) > extent) {
924 // that's more than half, so probably not worth shifting
933 Shift(Block::FACE_RIGHT);
937 Shift(Block::FACE_LEFT);
941 Shift(Block::FACE_UP);
945 Shift(Block::FACE_DOWN);
949 Shift(Block::FACE_FRONT);
953 Shift(Block::FACE_BACK);
959 int ChunkIndex::GetCol(int c) const noexcept {
961 if (c < 0) c += side_length;
965 void ChunkIndex::Shift(Block::Face f) {
966 int a_axis = Block::Axis(f);
967 int b_axis = (a_axis + 1) % 3;
968 int c_axis = (a_axis + 2) % 3;
969 int dir = Block::Direction(f);
971 int a = GetCol(base[a_axis] + (extent * dir));
972 int a_stride = a * stride[a_axis];
973 for (int b = 0; b < side_length; ++b) {
974 int b_stride = b * stride[b_axis];
975 for (int c = 0; c < side_length; ++c) {
976 int bc_stride = b_stride + c * stride[c_axis];
977 int index = a_stride + bc_stride;
979 int neighbor = ((a - dir + side_length) % side_length) * stride[a_axis] + bc_stride;
980 if (chunks[neighbor] && chunks[neighbor]->HasNeighbor(f)) {
981 Set(index, chunks[neighbor]->GetNeighbor(f));
987 void ChunkIndex::Clear() noexcept {
988 for (int i = 0; i < total_length && total_indexed > 0; ++i) {
993 void ChunkIndex::Scan() noexcept {
994 for (Chunk &chunk : store) {
999 void ChunkIndex::Register(Chunk &chunk) noexcept {
1000 if (InRange(chunk.Position())) {
1001 Set(IndexOf(chunk.Position()), chunk);
1005 void ChunkIndex::Set(int index, Chunk &chunk) noexcept {
1007 chunks[index] = &chunk;
1012 void ChunkIndex::Unset(int index) noexcept {
1013 if (chunks[index]) {
1014 chunks[index]->UnRef();
1015 chunks[index] = nullptr;
1020 ExactLocation::Coarse ChunkIndex::NextMissing() noexcept {
1021 if (MissingChunks() > 0) {
1022 int roundtrip = last_missing;
1023 last_missing = (last_missing + 1) % total_length;
1024 while (chunks[last_missing]) {
1025 last_missing = (last_missing + 1) % total_length;
1026 if (last_missing == roundtrip) {
1031 return PositionOf(last_missing);
1035 ChunkStore::ChunkStore(const BlockTypeRegistry &types)
1043 ChunkStore::~ChunkStore() {
1047 ChunkIndex &ChunkStore::MakeIndex(const ExactLocation::Coarse &pos, int extent) {
1048 indices.emplace_back(*this, pos, extent);
1049 return indices.back();
1052 void ChunkStore::UnregisterIndex(ChunkIndex &index) {
1053 for (auto i = indices.begin(), end = indices.end(); i != end; ++i) {
1054 if (&*i == &index) {
1063 ChunkIndex *ChunkStore::ClosestIndex(const ExactLocation::Coarse &pos) {
1064 ChunkIndex *closest_index = nullptr;
1065 int closest_distance = std::numeric_limits<int>::max();
1067 for (ChunkIndex &index : indices) {
1068 int distance = index.Distance(pos);
1069 if (distance < closest_distance) {
1070 closest_index = &index;
1071 closest_distance = distance;
1075 return closest_index;
1078 Chunk *ChunkStore::Get(const ExactLocation::Coarse &pos) {
1079 for (ChunkIndex &index : indices) {
1080 Chunk *chunk = index.Get(pos);
1088 Chunk *ChunkStore::Allocate(const ExactLocation::Coarse &pos) {
1089 Chunk *chunk = Get(pos);
1094 loaded.emplace(loaded.begin(), types);
1096 loaded.splice(loaded.begin(), free, free.begin());
1097 loaded.front().Unlink();
1099 chunk = &loaded.front();
1100 chunk->Position(pos);
1101 for (ChunkIndex &index : indices) {
1102 if (index.InRange(pos)) {
1103 index.Register(*chunk);
1106 for (int i = 0; i < Block::FACE_COUNT; ++i) {
1107 Block::Face face = Block::Face(i);
1108 ExactLocation::Coarse neighbor_pos(pos + Block::FaceNormal(face));
1109 Chunk *neighbor = Get(neighbor_pos);
1111 chunk->SetNeighbor(face, *neighbor);
1117 bool ChunkStore::HasMissing() const noexcept {
1118 for (const ChunkIndex &index : indices) {
1119 if (index.MissingChunks() > 0) {
1126 int ChunkStore::EstimateMissing() const noexcept {
1128 for (const ChunkIndex &index : indices) {
1129 missing += index.MissingChunks();
1134 ExactLocation::Coarse ChunkStore::NextMissing() noexcept {
1135 for (ChunkIndex &index : indices) {
1136 if (index.MissingChunks()) {
1137 return index.NextMissing();
1140 return ExactLocation::Coarse(0, 0, 0);
1143 void ChunkStore::Clean() {
1144 for (auto i = loaded.begin(), end = loaded.end(); i != end;) {
1145 if (i->Referenced() || i->ShouldUpdateSave()) {
1150 free.splice(free.end(), loaded, chunk);
1152 chunk->InvalidateMesh();