]> git.localhorst.tv Git - blank.git/blob - src/world/chunk.cpp
use collision structures for ray tests
[blank.git] / src / world / chunk.cpp
1 #include "BlockLookup.hpp"
2 #include "Chunk.hpp"
3 #include "ChunkLoader.hpp"
4
5 #include "Generator.hpp"
6 #include "WorldCollision.hpp"
7 #include "../io/WorldSave.hpp"
8
9 #include <algorithm>
10 #include <limits>
11 #include <ostream>
12 #include <queue>
13
14
15 namespace blank {
16
17 constexpr int Chunk::width;
18 constexpr int Chunk::height;
19 constexpr int Chunk::depth;
20 constexpr int Chunk::size;
21
22
23 Chunk::Chunk(const BlockTypeRegistry &types) noexcept
24 : types(&types)
25 , neighbor{0}
26 , blocks{}
27 , light{0}
28 , model()
29 , position(0, 0, 0)
30 , dirty_model(false)
31 , dirty_save(false) {
32
33 }
34
35 Chunk::Chunk(Chunk &&other) noexcept
36 : types(other.types)
37 , model(std::move(other.model))
38 , position(other.position)
39 , dirty_model(other.dirty_model)
40 , dirty_save(other.dirty_save) {
41         std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
42         std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
43         std::copy(other.light, other.light + sizeof(light), light);
44 }
45
46 Chunk &Chunk::operator =(Chunk &&other) noexcept {
47         types = other.types;
48         std::copy(other.neighbor, other.neighbor + sizeof(neighbor), neighbor);
49         std::copy(other.blocks, other.blocks + sizeof(blocks), blocks);
50         std::copy(other.light, other.light + sizeof(light), light);
51         model = std::move(other.model);
52         position = other.position;
53         dirty_model = other.dirty_save;
54         dirty_save = other.dirty_save;
55         return *this;
56 }
57
58
59 namespace {
60
61 struct SetNode {
62
63         Chunk *chunk;
64         Chunk::Pos pos;
65
66         SetNode(Chunk *chunk, Chunk::Pos pos)
67         : chunk(chunk), pos(pos) { }
68
69         int Get() const noexcept { return chunk->GetLight(pos); }
70         void Set(int level) noexcept { chunk->SetLight(pos, level); }
71
72         const BlockType &GetType() const noexcept { return chunk->Type(Chunk::ToIndex(pos)); }
73
74         bool HasNext(Block::Face face) noexcept {
75                 const BlockType &type = GetType();
76                 if (type.block_light && !type.luminosity) return false;
77                 const BlockLookup next(chunk, pos, face);
78                 return next;
79         }
80         SetNode GetNext(Block::Face face) noexcept {
81                 const BlockLookup next(chunk, pos, face);
82                 return SetNode(&next.GetChunk(), next.GetBlockPos());
83         }
84
85 };
86
87 struct UnsetNode
88 : public SetNode {
89
90         int level;
91
92         UnsetNode(Chunk *chunk, Chunk::Pos pos)
93         : SetNode(chunk, pos), level(Get()) { }
94
95         UnsetNode(const SetNode &set)
96         : SetNode(set), level(Get()) { }
97
98
99         bool HasNext(Block::Face face) noexcept {
100                 const BlockLookup next(chunk, pos, face);
101                 return next;
102         }
103         UnsetNode GetNext(Block::Face face) noexcept { return UnsetNode(SetNode::GetNext(face)); }
104
105 };
106
107 std::queue<SetNode> light_queue;
108 std::queue<UnsetNode> dark_queue;
109
110 void work_light() noexcept {
111         while (!light_queue.empty()) {
112                 SetNode node = light_queue.front();
113                 light_queue.pop();
114
115                 int level = node.Get() - 1;
116                 for (int face = 0; face < Block::FACE_COUNT; ++face) {
117                         if (node.HasNext(Block::Face(face))) {
118                                 SetNode other = node.GetNext(Block::Face(face));
119                                 if (other.Get() < level) {
120                                         other.Set(level);
121                                         light_queue.emplace(other);
122                                 }
123                         }
124                 }
125         }
126 }
127
128 void work_dark() noexcept {
129         while (!dark_queue.empty()) {
130                 UnsetNode node = dark_queue.front();
131                 dark_queue.pop();
132
133                 for (int face = 0; face < Block::FACE_COUNT; ++face) {
134                         if (node.HasNext(Block::Face(face))) {
135                                 UnsetNode other = node.GetNext(Block::Face(face));
136                                 // TODO: if there a light source here with the same level this will err
137                                 if (other.Get() != 0 && other.Get() < node.level) {
138                                         other.Set(0);
139                                         dark_queue.emplace(other);
140                                 } else {
141                                         light_queue.emplace(other);
142                                 }
143                         }
144                 }
145         }
146 }
147
148 }
149
150 void Chunk::SetBlock(int index, const Block &block) noexcept {
151         const BlockType &old_type = Type(blocks[index]);
152         const BlockType &new_type = Type(block);
153
154         blocks[index] = block;
155         Invalidate();
156
157         if (&old_type == &new_type) return;
158
159         if (new_type.luminosity > old_type.luminosity) {
160                 // light added
161                 SetLight(index, new_type.luminosity);
162                 light_queue.emplace(this, ToPos(index));
163                 work_light();
164         } else if (new_type.luminosity < old_type.luminosity) {
165                 // light removed
166                 dark_queue.emplace(this, ToPos(index));
167                 SetLight(index, 0);
168                 work_dark();
169                 SetLight(index, new_type.luminosity);
170                 light_queue.emplace(this, ToPos(index));
171                 work_light();
172         } else if (new_type.block_light && !old_type.block_light) {
173                 // obstacle added
174                 if (GetLight(index) > 0) {
175                         dark_queue.emplace(this, ToPos(index));
176                         SetLight(index, 0);
177                         work_dark();
178                         work_light();
179                 }
180         } else if (!new_type.block_light && old_type.block_light) {
181                 // obstacle removed
182                 int level = 0;
183                 Pos pos(ToPos(index));
184                 for (int face = 0; face < Block::FACE_COUNT; ++face) {
185                         BlockLookup next_block(this, pos, Block::Face(face));
186                         if (next_block) {
187                                 level = std::max(level, next_block.GetLight());
188                         }
189                 }
190                 if (level > 1) {
191                         SetLight(index, level - 1);
192                         light_queue.emplace(this, pos);
193                         work_light();
194                 }
195         }
196 }
197
198 namespace {
199
200 // propagate light from a's edge to b
201 void edge_light(
202         Chunk &a, const Chunk::Pos &a_pos,
203         Chunk &b, const Chunk::Pos &b_pos
204 ) noexcept {
205         if (a.GetLight(a_pos) > 1) {
206                 const BlockType &b_type = b.Type(Chunk::ToIndex(b_pos));
207                 if (!b_type.block_light) {
208                         light_queue.emplace(&a, a_pos);
209                 }
210                 if (b_type.visible) {
211                         b.Invalidate();
212                 }
213         }
214 }
215
216 }
217
218 void Chunk::SetNeighbor(Chunk &other) noexcept {
219         if (other.position == position + Pos(-1, 0, 0)) {
220                 if (neighbor[Block::FACE_LEFT] != &other) {
221                         neighbor[Block::FACE_LEFT] = &other;
222                         other.neighbor[Block::FACE_RIGHT] = this;
223                         for (int z = 0; z < depth; ++z) {
224                                 for (int y = 0; y < height; ++y) {
225                                         Pos my_pos(0, y, z);
226                                         Pos other_pos(width - 1, y, z);
227                                         edge_light(*this, my_pos, other, other_pos);
228                                         edge_light(other, other_pos, *this, my_pos);
229                                 }
230                         }
231                         work_light();
232                 }
233         } else if (other.position == position + Pos(1, 0, 0)) {
234                 if (neighbor[Block::FACE_RIGHT] != &other) {
235                         neighbor[Block::FACE_RIGHT] = &other;
236                         other.neighbor[Block::FACE_LEFT] = this;
237                         for (int z = 0; z < depth; ++z) {
238                                 for (int y = 0; y < height; ++y) {
239                                         Pos my_pos(width - 1, y, z);
240                                         Pos other_pos(0, y, z);
241                                         edge_light(*this, my_pos, other, other_pos);
242                                         edge_light(other, other_pos, *this, my_pos);
243                                 }
244                         }
245                         work_light();
246                 }
247         } else if (other.position == position + Pos(0, -1, 0)) {
248                 if (neighbor[Block::FACE_DOWN] != &other) {
249                         neighbor[Block::FACE_DOWN] = &other;
250                         other.neighbor[Block::FACE_UP] = this;
251                         for (int z = 0; z < depth; ++z) {
252                                 for (int x = 0; x < width; ++x) {
253                                         Pos my_pos(x, 0, z);
254                                         Pos other_pos(x, height - 1, z);
255                                         edge_light(*this, my_pos, other, other_pos);
256                                         edge_light(other, other_pos, *this, my_pos);
257                                 }
258                         }
259                         work_light();
260                 }
261         } else if (other.position == position + Pos(0, 1, 0)) {
262                 if (neighbor[Block::FACE_UP] != &other) {
263                         neighbor[Block::FACE_UP] = &other;
264                         other.neighbor[Block::FACE_DOWN] = this;
265                         for (int z = 0; z < depth; ++z) {
266                                 for (int x = 0; x < width; ++x) {
267                                         Pos my_pos(x, height - 1, z);
268                                         Pos other_pos(x, 0, z);
269                                         edge_light(*this, my_pos, other, other_pos);
270                                         edge_light(other, other_pos, *this, my_pos);
271                                 }
272                         }
273                         work_light();
274                 }
275         } else if (other.position == position + Pos(0, 0, -1)) {
276                 if (neighbor[Block::FACE_BACK] != &other) {
277                         neighbor[Block::FACE_BACK] = &other;
278                         other.neighbor[Block::FACE_FRONT] = this;
279                         for (int y = 0; y < height; ++y) {
280                                 for (int x = 0; x < width; ++x) {
281                                         Pos my_pos(x, y, 0);
282                                         Pos other_pos(x, y, depth - 1);
283                                         edge_light(*this, my_pos, other, other_pos);
284                                         edge_light(other, other_pos, *this, my_pos);
285                                 }
286                         }
287                         work_light();
288                 }
289         } else if (other.position == position + Pos(0, 0, 1)) {
290                 if (neighbor[Block::FACE_FRONT] != &other) {
291                         neighbor[Block::FACE_FRONT] = &other;
292                         other.neighbor[Block::FACE_BACK] = this;
293                         for (int y = 0; y < height; ++y) {
294                                 for (int x = 0; x < width; ++x) {
295                                         Pos my_pos(x, y, depth - 1);
296                                         Pos other_pos(x, y, 0);
297                                         edge_light(*this, my_pos, other, other_pos);
298                                         edge_light(other, other_pos, *this, my_pos);
299                                 }
300                         }
301                         work_light();
302                 }
303         }
304 }
305
306 void Chunk::ClearNeighbors() noexcept {
307         for (int face = 0; face < Block::FACE_COUNT; ++face) {
308                 if (neighbor[face]) {
309                         neighbor[face]->neighbor[Block::Opposite(Block::Face(face))] = nullptr;
310                         neighbor[face] = nullptr;
311                 }
312         }
313 }
314
315
316 void Chunk::SetLight(int index, int level) noexcept {
317         if (light[index] != level) {
318                 light[index] = level;
319                 Invalidate();
320         }
321 }
322
323 int Chunk::GetLight(int index) const noexcept {
324         return light[index];
325 }
326
327 float Chunk::GetVertexLight(const Pos &pos, const BlockModel::Position &vtx, const EntityModel::Normal &norm) const noexcept {
328         int index = ToIndex(pos);
329         float light = GetLight(index);
330
331         Block::Face direct_face(Block::NormalFace(norm));
332         // tis okay
333         BlockLookup direct(const_cast<Chunk *>(this), pos, Block::NormalFace(norm));
334         if (direct) {
335                 float direct_light = direct.GetLight();
336                 if (direct_light > light) {
337                         light = direct_light;
338                 }
339         } else {
340                 return light;
341         }
342
343         if (Type(BlockAt(index)).luminosity > 0 || direct.GetType().block_light) {
344                 return light;
345         }
346
347         Block::Face edge[2];
348         switch (Block::Axis(direct_face)) {
349                 case 0: // X
350                         edge[0] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
351                         edge[1] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
352                         break;
353                 case 1: // Y
354                         edge[0] = (vtx.z - pos.z) > 0.5f ? Block::FACE_FRONT : Block::FACE_BACK;
355                         edge[1] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
356                         break;
357                 case 2: // Z
358                         edge[0] = (vtx.x - pos.x) > 0.5f ? Block::FACE_RIGHT : Block::FACE_LEFT;
359                         edge[1] = (vtx.y - pos.y) > 0.5f ? Block::FACE_UP : Block::FACE_DOWN;
360                         break;
361         }
362
363         int num = 1;
364         int occlusion = 0;
365
366         BlockLookup next[2] = {
367                 direct.Next(edge[0]),
368                 direct.Next(edge[1]),
369         };
370
371         if (next[0]) {
372                 if (next[0].GetType().block_light) {
373                         ++occlusion;
374                 } else {
375                         light += next[0].GetLight();
376                         ++num;
377                 }
378         }
379         if (next[1]) {
380                 if (next[1].GetType().block_light) {
381                         ++occlusion;
382                 } else {
383                         light += next[1].GetLight();
384                         ++num;
385                 }
386         }
387         if (occlusion < 2) {
388                 if (next[0]) {
389                         BlockLookup corner = next[0].Next(edge[1]);
390                         if (corner) {
391                                 if (corner.GetType().block_light) {
392                                         ++occlusion;
393                                 } else {
394                                         light += corner.GetLight();
395                                         ++num;
396                                 }
397                         }
398                 } else if (next[1]) {
399                         BlockLookup corner = next[1].Next(edge[0]);
400                         if (corner) {
401                                 if (corner.GetType().block_light) {
402                                         ++occlusion;
403                                 } else {
404                                         light += corner.GetLight();
405                                         ++num;
406                                 }
407                         }
408                 }
409         } else {
410                 ++occlusion;
411         }
412
413         return (light / num) - (occlusion * 0.8f);
414 }
415
416
417 bool Chunk::IsSurface(const Pos &pos) const noexcept {
418         const Block &block = BlockAt(pos);
419         if (!Type(block).visible) {
420                 return false;
421         }
422         for (int face = 0; face < Block::FACE_COUNT; ++face) {
423                 BlockLookup next = BlockLookup(const_cast<Chunk *>(this), pos, Block::Face(face));
424                 if (!next || !next.GetType().visible) {
425                         return true;
426                 }
427         }
428         return false;
429 }
430
431
432 void Chunk::Draw() noexcept {
433         if (ShouldUpdateModel()) {
434                 Update();
435         }
436         model.Draw();
437 }
438
439
440 bool Chunk::Intersection(
441         const Ray &ray,
442         const glm::mat4 &M,
443         WorldCollision &coll
444 ) noexcept {
445         int idx = 0;
446         coll.chunk = this;
447         coll.block = -1;
448         coll.depth = std::numeric_limits<float>::infinity();
449         for (int z = 0; z < depth; ++z) {
450                 for (int y = 0; y < height; ++y) {
451                         for (int x = 0; x < width; ++x, ++idx) {
452                                 const BlockType &type = Type(idx);
453                                 if (!type.visible) {
454                                         continue;
455                                 }
456                                 float cur_dist;
457                                 glm::vec3 cur_norm;
458                                 if (type.shape->Intersects(ray, M * ToTransform(Pos(x, y, z), idx), cur_dist, cur_norm)) {
459                                         if (cur_dist < coll.depth) {
460                                                 coll.block = idx;
461                                                 coll.depth = cur_dist;
462                                                 coll.normal = cur_norm;
463                                         }
464                                 }
465                         }
466                 }
467         }
468
469         if (coll.block < 0) {
470                 return false;
471         } else {
472                 coll.normal = glm::vec3(BlockAt(coll.block).Transform() * glm::vec4(coll.normal, 0.0f));
473                 return true;
474         }
475 }
476
477 bool Chunk::Intersection(
478         const AABB &box,
479         const glm::mat4 &Mbox,
480         const glm::mat4 &Mchunk,
481         std::vector<WorldCollision> &col
482 ) noexcept {
483         bool any = false;
484         float penetration;
485         glm::vec3 normal;
486
487         if (!blank::Intersection(box, Mbox, Bounds(), Mchunk, penetration, normal)) {
488                 return false;
489         }
490         for (int idx = 0, z = 0; z < depth; ++z) {
491                 for (int y = 0; y < height; ++y) {
492                         for (int x = 0; x < width; ++x, ++idx) {
493                                 const BlockType &type = Type(idx);
494                                 if (!type.collision) {
495                                         continue;
496                                 }
497                                 if (type.shape->Intersects(Mchunk * ToTransform(Pos(x, y, z), idx), box, Mbox, penetration, normal)) {
498                                         col.emplace_back(this, idx, penetration, normal);
499                                         any = true;
500                                 }
501                         }
502                 }
503         }
504         return any;
505 }
506
507
508 namespace {
509
510 BlockModel::Buffer buf;
511
512 }
513
514 void Chunk::CheckUpdate() noexcept {
515         if (ShouldUpdateModel()) {
516                 Update();
517         }
518 }
519
520 void Chunk::Update() noexcept {
521         int vtx_count = 0, idx_count = 0;
522         for (const auto &block : blocks) {
523                 const Shape *shape = Type(block).shape;
524                 vtx_count += shape->VertexCount();
525                 idx_count += shape->VertexIndexCount();
526         }
527         buf.Clear();
528         buf.Reserve(vtx_count, idx_count);
529
530         int idx = 0;
531         BlockModel::Index vtx_counter = 0;
532         for (size_t z = 0; z < depth; ++z) {
533                 for (size_t y = 0; y < height; ++y) {
534                         for (size_t x = 0; x < width; ++x, ++idx) {
535                                 const BlockType &type = Type(BlockAt(idx));
536                                 const Pos pos(x, y, z);
537
538                                 if (!type.visible || Obstructed(pos).All()) continue;
539
540                                 type.FillBlockModel(buf, ToTransform(pos, idx), vtx_counter);
541                                 size_t vtx_begin = vtx_counter;
542                                 vtx_counter += type.shape->VertexCount();
543
544                                 for (size_t vtx = vtx_begin; vtx < vtx_counter; ++vtx) {
545                                         buf.lights.emplace_back(GetVertexLight(
546                                                 pos,
547                                                 buf.vertices[vtx],
548                                                 type.shape->VertexNormal(vtx - vtx_begin, BlockAt(idx).Transform())
549                                         ));
550                                 }
551                         }
552                 }
553         }
554
555         model.Update(buf);
556         ClearModel();
557 }
558
559 Block::FaceSet Chunk::Obstructed(const Pos &pos) const noexcept {
560         Block::FaceSet result;
561
562         for (int f = 0; f < Block::FACE_COUNT; ++f) {
563                 Block::Face face = Block::Face(f);
564                 BlockLookup next(const_cast<Chunk *>(this), pos, face);
565                 if (next && next.GetType().FaceFilled(next.GetBlock(), Block::Opposite(face))) {
566                         result.Set(face);
567                 }
568         }
569
570         return result;
571 }
572
573 glm::mat4 Chunk::ToTransform(const Pos &pos, int idx) const noexcept {
574         return glm::translate(ToCoords(pos)) * BlockAt(idx).Transform();
575 }
576
577
578 BlockLookup::BlockLookup(Chunk *c, const Chunk::Pos &p) noexcept
579 : chunk(c), pos(p) {
580         while (pos.x >= Chunk::width) {
581                 if (chunk->HasNeighbor(Block::FACE_RIGHT)) {
582                         chunk = &chunk->GetNeighbor(Block::FACE_RIGHT);
583                         pos.x -= Chunk::width;
584                 } else {
585                         chunk = nullptr;
586                         return;
587                 }
588         }
589         while (pos.x < 0) {
590                 if (chunk->HasNeighbor(Block::FACE_LEFT)) {
591                         chunk = &chunk->GetNeighbor(Block::FACE_LEFT);
592                         pos.x += Chunk::width;
593                 } else {
594                         chunk = nullptr;
595                         return;
596                 }
597         }
598         while (pos.y >= Chunk::height) {
599                 if (chunk->HasNeighbor(Block::FACE_UP)) {
600                         chunk = &chunk->GetNeighbor(Block::FACE_UP);
601                         pos.y -= Chunk::height;
602                 } else {
603                         chunk = nullptr;
604                         return;
605                 }
606         }
607         while (pos.y < 0) {
608                 if (chunk->HasNeighbor(Block::FACE_DOWN)) {
609                         chunk = &chunk->GetNeighbor(Block::FACE_DOWN);
610                         pos.y += Chunk::height;
611                 } else {
612                         chunk = nullptr;
613                         return;
614                 }
615         }
616         while (pos.z >= Chunk::depth) {
617                 if (chunk->HasNeighbor(Block::FACE_FRONT)) {
618                         chunk = &chunk->GetNeighbor(Block::FACE_FRONT);
619                         pos.z -= Chunk::depth;
620                 } else {
621                         chunk = nullptr;
622                         return;
623                 }
624         }
625         while (pos.z < 0) {
626                 if (chunk->HasNeighbor(Block::FACE_BACK)) {
627                         chunk = &chunk->GetNeighbor(Block::FACE_BACK);
628                         pos.z += Chunk::depth;
629                 } else {
630                         chunk = nullptr;
631                         return;
632                 }
633         }
634 }
635
636 BlockLookup::BlockLookup(Chunk *c, const Chunk::Pos &p, Block::Face face) noexcept
637 : chunk(c), pos(p) {
638         pos += Block::FaceNormal(face);
639         if (!Chunk::InBounds(pos)) {
640                 pos -= Block::FaceNormal(face) * Chunk::Extent();
641                 chunk = &chunk->GetNeighbor(face);
642         }
643 }
644
645
646 ChunkLoader::ChunkLoader(
647         const Config &config,
648         const BlockTypeRegistry &reg,
649         const Generator &gen,
650         const WorldSave &save
651 ) noexcept
652 : base(0, 0, 0)
653 , reg(reg)
654 , gen(gen)
655 , save(save)
656 , loaded()
657 , to_load()
658 , to_free()
659 , gen_timer(config.gen_limit)
660 , load_dist(config.load_dist)
661 , unload_dist(config.unload_dist) {
662         gen_timer.Start();
663 }
664
665 namespace {
666
667 struct ChunkLess {
668
669         explicit ChunkLess(const Chunk::Pos &base) noexcept
670         : base(base) { }
671
672         bool operator ()(const Chunk::Pos &a, const Chunk::Pos &b) const noexcept {
673                 Chunk::Pos da(base - a);
674                 Chunk::Pos db(base - b);
675                 return
676                         da.x * da.x + da.y * da.y + da.z * da.z <
677                         db.x * db.x + db.y * db.y + db.z * db.z;
678         }
679
680         Chunk::Pos base;
681
682 };
683
684 }
685
686 void ChunkLoader::Queue(const Chunk::Pos &from, const Chunk::Pos &to) {
687         for (int z = from.z; z < to.z; ++z) {
688                 for (int y = from.y; y < to.y; ++y) {
689                         for (int x = from.x; x < to.x; ++x) {
690                                 Chunk::Pos pos(x, y, z);
691                                 if (Known(pos)) {
692                                         continue;
693                                 } else if (pos == base) {
694                                         Load(pos);
695
696                                 //      light testing
697                                 //      for (int i = 0; i < 16; ++i) {
698                                 //              for (int j = 0; j < 16; ++j) {
699                                 //                      loaded.back().SetBlock(Chunk::Pos{  i, j,  0 }, Block(1));
700                                 //                      loaded.back().SetBlock(Chunk::Pos{  i, j, 15 }, Block(1));
701                                 //                      loaded.back().SetBlock(Chunk::Pos{  0, j,  i }, Block(1));
702                                 //                      loaded.back().SetBlock(Chunk::Pos{ 15, j,  i }, Block(1));
703                                 //              }
704                                 //      }
705                                 //      loaded.back().SetBlock(Chunk::Pos{  1,  0,  1 }, Block(13));
706                                 //      loaded.back().SetBlock(Chunk::Pos{ 14,  0,  1 }, Block(13));
707                                 //      loaded.back().SetBlock(Chunk::Pos{  1,  0, 14 }, Block(13));
708                                 //      loaded.back().SetBlock(Chunk::Pos{ 14,  0, 14 }, Block(13));
709                                 //      loaded.back().SetBlock(Chunk::Pos{  1, 15,  1 }, Block(13));
710                                 //      loaded.back().SetBlock(Chunk::Pos{ 14, 15,  1 }, Block(13));
711                                 //      loaded.back().SetBlock(Chunk::Pos{  1, 15, 14 }, Block(13));
712                                 //      loaded.back().SetBlock(Chunk::Pos{ 14, 15, 14 }, Block(13));
713                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  7,  0 }, Block(13));
714                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  7,  0 }, Block(13));
715                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  8,  0 }, Block(13));
716                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  8,  0 }, Block(13));
717                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  7, 15 }, Block(13));
718                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  7, 15 }, Block(13));
719                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  8, 15 }, Block(13));
720                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  8, 15 }, Block(13));
721                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  7,  7 }, Block(13));
722                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  7,  8 }, Block(13));
723                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  8,  7 }, Block(13));
724                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  8,  8 }, Block(13));
725                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  7,  7 }, Block(13));
726                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  7,  8 }, Block(13));
727                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  8,  7 }, Block(13));
728                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  8,  8 }, Block(13));
729                                 //      loaded.back().Invalidate();
730                                 //      loaded.back().CheckUpdate();
731
732                                 //      orientation testing
733                                 //      for (int i = 0; i < Block::FACE_COUNT; ++i) {
734                                 //              for (int j = 0; j < Block::TURN_COUNT; ++j) {
735                                 //                      loaded.back().BlockAt(512 * j + 2 * i) = Block(3 * (j + 1), Block::Face(i), Block::Turn(j));
736                                 //              }
737                                 //      }
738                                 //      loaded.back().Invalidate();
739                                 //      loaded.back().CheckUpdate();
740                                 } else {
741                                         to_load.emplace_back(pos);
742                                 }
743                         }
744                 }
745         }
746         to_load.sort(ChunkLess(base));
747 }
748
749 Chunk &ChunkLoader::Load(const Chunk::Pos &pos) {
750         loaded.emplace_back(reg);
751         Chunk &chunk = loaded.back();
752         chunk.Position(pos);
753         if (save.Exists(pos)) {
754                 save.Read(chunk);
755         } else {
756                 gen(chunk);
757         }
758         Insert(chunk);
759         return chunk;
760 }
761
762 void ChunkLoader::Insert(Chunk &chunk) noexcept {
763         for (Chunk &other : loaded) {
764                 chunk.SetNeighbor(other);
765         }
766 }
767
768 std::list<Chunk>::iterator ChunkLoader::Remove(std::list<Chunk>::iterator chunk) noexcept {
769         // fetch next entry while chunk's still in the list
770         std::list<Chunk>::iterator next = chunk;
771         ++next;
772         // unlink neighbors so they won't reference a dead chunk
773         chunk->ClearNeighbors();
774         // if it should be saved, do it now
775         if (chunk->ShouldUpdateSave()) {
776                 save.Write(*chunk);
777         }
778         // and move it from loaded to free list
779         to_free.splice(to_free.end(), loaded, chunk);
780         return next;
781 }
782
783 Chunk *ChunkLoader::Loaded(const Chunk::Pos &pos) noexcept {
784         for (Chunk &chunk : loaded) {
785                 if (chunk.Position() == pos) {
786                         return &chunk;
787                 }
788         }
789         return nullptr;
790 }
791
792 bool ChunkLoader::Queued(const Chunk::Pos &pos) noexcept {
793         for (const Chunk::Pos &chunk : to_load) {
794                 if (chunk == pos) {
795                         return true;
796                 }
797         }
798         return false;
799 }
800
801 bool ChunkLoader::Known(const Chunk::Pos &pos) noexcept {
802         if (Loaded(pos)) return true;
803         return Queued(pos);
804 }
805
806 Chunk &ChunkLoader::ForceLoad(const Chunk::Pos &pos) {
807         Chunk *chunk = Loaded(pos);
808         if (chunk) {
809                 return *chunk;
810         }
811
812         for (auto iter(to_load.begin()), end(to_load.end()); iter != end; ++iter) {
813                 if (*iter == pos) {
814                         to_load.erase(iter);
815                         break;
816                 }
817         }
818
819         return Load(pos);
820 }
821
822 bool ChunkLoader::OutOfRange(const Chunk::Pos &pos) const noexcept {
823         return std::abs(base.x - pos.x) > unload_dist
824                         || std::abs(base.y - pos.y) > unload_dist
825                         || std::abs(base.z - pos.z) > unload_dist;
826 }
827
828 void ChunkLoader::Rebase(const Chunk::Pos &new_base) {
829         if (new_base == base) {
830                 return;
831         }
832         base = new_base;
833
834         // unload far away chunks
835         for (auto iter(loaded.begin()), end(loaded.end()); iter != end;) {
836                 if (OutOfRange(*iter)) {
837                         iter = Remove(iter);
838                 } else {
839                         ++iter;
840                 }
841         }
842         // abort far away queued chunks
843         for (auto iter(to_load.begin()), end(to_load.end()); iter != end;) {
844                 if (OutOfRange(*iter)) {
845                         iter = to_load.erase(iter);
846                 } else {
847                         ++iter;
848                 }
849         }
850         // add missing new chunks
851         QueueSurrounding(base);
852 }
853
854 void ChunkLoader::QueueSurrounding(const Chunk::Pos &pos) {
855         const Chunk::Pos offset(load_dist, load_dist, load_dist);
856         Queue(pos - offset, pos + offset);
857 }
858
859 void ChunkLoader::Update(int dt) {
860         // check if a chunk load is scheduled for this frame
861         // and if there's chunks waiting to be loaded
862         gen_timer.Update(dt);
863         if (gen_timer.Hit()) {
864                 // we may
865                 // load until one of load or generation limits was hit
866                 constexpr int max_load = 10;
867                 constexpr int max_gen = 1;
868                 int loaded = 0;
869                 int generated = 0;
870                 while (!to_load.empty() && loaded < max_load && generated < max_gen) {
871                         if (LoadOne()) {
872                                 ++generated;
873                         } else {
874                                 ++loaded;
875                         }
876                 }
877         }
878
879         constexpr int max_save = 10;
880         int saved = 0;
881         for (Chunk &chunk : loaded) {
882                 if (chunk.ShouldUpdateSave()) {
883                         save.Write(chunk);
884                         ++saved;
885                         if (saved >= max_save) {
886                                 break;
887                         }
888                 }
889         }
890 }
891
892 void ChunkLoader::LoadN(std::size_t n) {
893         std::size_t end = std::min(n, ToLoad());
894         for (std::size_t i = 0; i < end; ++i) {
895                 LoadOne();
896         }
897 }
898
899 bool ChunkLoader::LoadOne() {
900         if (to_load.empty()) return false;
901
902         // take position of next chunk in queue
903         Chunk::Pos pos(to_load.front());
904         to_load.pop_front();
905
906         // look if the same chunk was already generated and still lingering
907         for (auto iter(to_free.begin()), end(to_free.end()); iter != end; ++iter) {
908                 if (iter->Position() == pos) {
909                         loaded.splice(loaded.end(), to_free, iter);
910                         Insert(loaded.back());
911                         return false;
912                 }
913         }
914
915         // if the free list is empty, allocate a new chunk
916         // otherwise clear an unused one
917         if (to_free.empty()) {
918                 loaded.emplace_back(reg);
919         } else {
920                 to_free.front().ClearNeighbors();
921                 loaded.splice(loaded.end(), to_free, to_free.begin());
922         }
923
924         bool generated = false;
925         Chunk &chunk = loaded.back();
926         chunk.Position(pos);
927         if (save.Exists(pos)) {
928                 save.Read(chunk);
929         } else {
930                 gen(chunk);
931                 generated = true;
932         }
933         Insert(chunk);
934         return generated;
935 }
936
937 }