]> git.localhorst.tv Git - blank.git/blob - src/world/chunk.cpp
show player orientation in debug overlay
[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         int &blkid,
444         float &dist,
445         glm::vec3 &normal
446 ) const noexcept {
447         int idx = 0;
448         blkid = -1;
449         dist = std::numeric_limits<float>::infinity();
450         for (int z = 0; z < depth; ++z) {
451                 for (int y = 0; y < height; ++y) {
452                         for (int x = 0; x < width; ++x, ++idx) {
453                                 const BlockType &type = Type(idx);
454                                 if (!type.visible) {
455                                         continue;
456                                 }
457                                 float cur_dist;
458                                 glm::vec3 cur_norm;
459                                 if (type.shape->Intersects(ray, M * ToTransform(Pos(x, y, z), idx), cur_dist, cur_norm)) {
460                                         if (cur_dist < dist) {
461                                                 blkid = idx;
462                                                 dist = cur_dist;
463                                                 normal = cur_norm;
464                                         }
465                                 }
466                         }
467                 }
468         }
469
470         if (blkid < 0) {
471                 return false;
472         } else {
473                 normal = glm::vec3(BlockAt(blkid).Transform() * glm::vec4(normal, 0.0f));
474                 return true;
475         }
476 }
477
478 bool Chunk::Intersection(
479         const AABB &box,
480         const glm::mat4 &Mbox,
481         const glm::mat4 &Mchunk,
482         std::vector<WorldCollision> &col
483 ) const noexcept {
484         bool any = false;
485         float penetration;
486         glm::vec3 normal;
487
488         if (!blank::Intersection(box, Mbox, Bounds(), Mchunk, penetration, normal)) {
489                 return false;
490         }
491         for (int idx = 0, z = 0; z < depth; ++z) {
492                 for (int y = 0; y < height; ++y) {
493                         for (int x = 0; x < width; ++x, ++idx) {
494                                 const BlockType &type = Type(idx);
495                                 if (!type.collision) {
496                                         continue;
497                                 }
498                                 if (type.shape->Intersects(Mchunk * ToTransform(Pos(x, y, z), idx), box, Mbox, penetration, normal)) {
499                                         col.emplace_back(this, idx, penetration, normal);
500                                         any = true;
501                                 }
502                         }
503                 }
504         }
505         return any;
506 }
507
508
509 namespace {
510
511 BlockModel::Buffer buf;
512
513 }
514
515 void Chunk::CheckUpdate() noexcept {
516         if (ShouldUpdateModel()) {
517                 Update();
518         }
519 }
520
521 void Chunk::Update() noexcept {
522         int vtx_count = 0, idx_count = 0;
523         for (const auto &block : blocks) {
524                 const Shape *shape = Type(block).shape;
525                 vtx_count += shape->VertexCount();
526                 idx_count += shape->VertexIndexCount();
527         }
528         buf.Clear();
529         buf.Reserve(vtx_count, idx_count);
530
531         int idx = 0;
532         BlockModel::Index vtx_counter = 0;
533         for (size_t z = 0; z < depth; ++z) {
534                 for (size_t y = 0; y < height; ++y) {
535                         for (size_t x = 0; x < width; ++x, ++idx) {
536                                 const BlockType &type = Type(BlockAt(idx));
537                                 const Pos pos(x, y, z);
538
539                                 if (!type.visible || Obstructed(pos).All()) continue;
540
541                                 type.FillBlockModel(buf, ToTransform(pos, idx), vtx_counter);
542                                 size_t vtx_begin = vtx_counter;
543                                 vtx_counter += type.shape->VertexCount();
544
545                                 for (size_t vtx = vtx_begin; vtx < vtx_counter; ++vtx) {
546                                         buf.lights.emplace_back(GetVertexLight(
547                                                 pos,
548                                                 buf.vertices[vtx],
549                                                 type.shape->VertexNormal(vtx - vtx_begin, BlockAt(idx).Transform())
550                                         ));
551                                 }
552                         }
553                 }
554         }
555
556         model.Update(buf);
557         ClearModel();
558 }
559
560 Block::FaceSet Chunk::Obstructed(const Pos &pos) const noexcept {
561         Block::FaceSet result;
562
563         for (int f = 0; f < Block::FACE_COUNT; ++f) {
564                 Block::Face face = Block::Face(f);
565                 BlockLookup next(const_cast<Chunk *>(this), pos, face);
566                 if (next && next.GetType().FaceFilled(next.GetBlock(), Block::Opposite(face))) {
567                         result.Set(face);
568                 }
569         }
570
571         return result;
572 }
573
574 glm::mat4 Chunk::ToTransform(const Pos &pos, int idx) const noexcept {
575         return glm::translate(ToCoords(pos)) * BlockAt(idx).Transform();
576 }
577
578
579 BlockLookup::BlockLookup(Chunk *c, const Chunk::Pos &p) noexcept
580 : chunk(c), pos(p) {
581         while (pos.x >= Chunk::width) {
582                 if (chunk->HasNeighbor(Block::FACE_RIGHT)) {
583                         chunk = &chunk->GetNeighbor(Block::FACE_RIGHT);
584                         pos.x -= Chunk::width;
585                 } else {
586                         chunk = nullptr;
587                         return;
588                 }
589         }
590         while (pos.x < 0) {
591                 if (chunk->HasNeighbor(Block::FACE_LEFT)) {
592                         chunk = &chunk->GetNeighbor(Block::FACE_LEFT);
593                         pos.x += Chunk::width;
594                 } else {
595                         chunk = nullptr;
596                         return;
597                 }
598         }
599         while (pos.y >= Chunk::height) {
600                 if (chunk->HasNeighbor(Block::FACE_UP)) {
601                         chunk = &chunk->GetNeighbor(Block::FACE_UP);
602                         pos.y -= Chunk::height;
603                 } else {
604                         chunk = nullptr;
605                         return;
606                 }
607         }
608         while (pos.y < 0) {
609                 if (chunk->HasNeighbor(Block::FACE_DOWN)) {
610                         chunk = &chunk->GetNeighbor(Block::FACE_DOWN);
611                         pos.y += Chunk::height;
612                 } else {
613                         chunk = nullptr;
614                         return;
615                 }
616         }
617         while (pos.z >= Chunk::depth) {
618                 if (chunk->HasNeighbor(Block::FACE_FRONT)) {
619                         chunk = &chunk->GetNeighbor(Block::FACE_FRONT);
620                         pos.z -= Chunk::depth;
621                 } else {
622                         chunk = nullptr;
623                         return;
624                 }
625         }
626         while (pos.z < 0) {
627                 if (chunk->HasNeighbor(Block::FACE_BACK)) {
628                         chunk = &chunk->GetNeighbor(Block::FACE_BACK);
629                         pos.z += Chunk::depth;
630                 } else {
631                         chunk = nullptr;
632                         return;
633                 }
634         }
635 }
636
637 BlockLookup::BlockLookup(Chunk *c, const Chunk::Pos &p, Block::Face face) noexcept
638 : chunk(c), pos(p) {
639         pos += Block::FaceNormal(face);
640         if (!Chunk::InBounds(pos)) {
641                 pos -= Block::FaceNormal(face) * Chunk::Extent();
642                 chunk = &chunk->GetNeighbor(face);
643         }
644 }
645
646
647 ChunkLoader::ChunkLoader(
648         const Config &config,
649         const BlockTypeRegistry &reg,
650         const Generator &gen,
651         const WorldSave &save
652 ) noexcept
653 : base(0, 0, 0)
654 , reg(reg)
655 , gen(gen)
656 , save(save)
657 , loaded()
658 , to_load()
659 , to_free()
660 , gen_timer(config.gen_limit)
661 , load_dist(config.load_dist)
662 , unload_dist(config.unload_dist) {
663         gen_timer.Start();
664 }
665
666 namespace {
667
668 struct ChunkLess {
669
670         explicit ChunkLess(const Chunk::Pos &base) noexcept
671         : base(base) { }
672
673         bool operator ()(const Chunk::Pos &a, const Chunk::Pos &b) const noexcept {
674                 Chunk::Pos da(base - a);
675                 Chunk::Pos db(base - b);
676                 return
677                         da.x * da.x + da.y * da.y + da.z * da.z <
678                         db.x * db.x + db.y * db.y + db.z * db.z;
679         }
680
681         Chunk::Pos base;
682
683 };
684
685 }
686
687 void ChunkLoader::Queue(const Chunk::Pos &from, const Chunk::Pos &to) {
688         for (int z = from.z; z < to.z; ++z) {
689                 for (int y = from.y; y < to.y; ++y) {
690                         for (int x = from.x; x < to.x; ++x) {
691                                 Chunk::Pos pos(x, y, z);
692                                 if (Known(pos)) {
693                                         continue;
694                                 } else if (pos == base) {
695                                         Load(pos);
696
697                                 //      light testing
698                                 //      for (int i = 0; i < 16; ++i) {
699                                 //              for (int j = 0; j < 16; ++j) {
700                                 //                      loaded.back().SetBlock(Chunk::Pos{  i, j,  0 }, Block(1));
701                                 //                      loaded.back().SetBlock(Chunk::Pos{  i, j, 15 }, Block(1));
702                                 //                      loaded.back().SetBlock(Chunk::Pos{  0, j,  i }, Block(1));
703                                 //                      loaded.back().SetBlock(Chunk::Pos{ 15, j,  i }, Block(1));
704                                 //              }
705                                 //      }
706                                 //      loaded.back().SetBlock(Chunk::Pos{  1,  0,  1 }, Block(13));
707                                 //      loaded.back().SetBlock(Chunk::Pos{ 14,  0,  1 }, Block(13));
708                                 //      loaded.back().SetBlock(Chunk::Pos{  1,  0, 14 }, Block(13));
709                                 //      loaded.back().SetBlock(Chunk::Pos{ 14,  0, 14 }, Block(13));
710                                 //      loaded.back().SetBlock(Chunk::Pos{  1, 15,  1 }, Block(13));
711                                 //      loaded.back().SetBlock(Chunk::Pos{ 14, 15,  1 }, Block(13));
712                                 //      loaded.back().SetBlock(Chunk::Pos{  1, 15, 14 }, Block(13));
713                                 //      loaded.back().SetBlock(Chunk::Pos{ 14, 15, 14 }, Block(13));
714                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  7,  0 }, Block(13));
715                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  7,  0 }, Block(13));
716                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  8,  0 }, Block(13));
717                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  8,  0 }, Block(13));
718                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  7, 15 }, Block(13));
719                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  7, 15 }, Block(13));
720                                 //      loaded.back().SetBlock(Chunk::Pos{  7,  8, 15 }, Block(13));
721                                 //      loaded.back().SetBlock(Chunk::Pos{  8,  8, 15 }, Block(13));
722                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  7,  7 }, Block(13));
723                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  7,  8 }, Block(13));
724                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  8,  7 }, Block(13));
725                                 //      loaded.back().SetBlock(Chunk::Pos{  0,  8,  8 }, Block(13));
726                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  7,  7 }, Block(13));
727                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  7,  8 }, Block(13));
728                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  8,  7 }, Block(13));
729                                 //      loaded.back().SetBlock(Chunk::Pos{ 15,  8,  8 }, Block(13));
730                                 //      loaded.back().Invalidate();
731                                 //      loaded.back().CheckUpdate();
732
733                                 //      orientation testing
734                                 //      for (int i = 0; i < Block::FACE_COUNT; ++i) {
735                                 //              for (int j = 0; j < Block::TURN_COUNT; ++j) {
736                                 //                      loaded.back().BlockAt(512 * j + 2 * i) = Block(3 * (j + 1), Block::Face(i), Block::Turn(j));
737                                 //              }
738                                 //      }
739                                 //      loaded.back().Invalidate();
740                                 //      loaded.back().CheckUpdate();
741                                 } else {
742                                         to_load.emplace_back(pos);
743                                 }
744                         }
745                 }
746         }
747         to_load.sort(ChunkLess(base));
748 }
749
750 Chunk &ChunkLoader::Load(const Chunk::Pos &pos) {
751         loaded.emplace_back(reg);
752         Chunk &chunk = loaded.back();
753         chunk.Position(pos);
754         if (save.Exists(pos)) {
755                 save.Read(chunk);
756         } else {
757                 gen(chunk);
758         }
759         Insert(chunk);
760         return chunk;
761 }
762
763 void ChunkLoader::Insert(Chunk &chunk) noexcept {
764         for (Chunk &other : loaded) {
765                 chunk.SetNeighbor(other);
766         }
767 }
768
769 std::list<Chunk>::iterator ChunkLoader::Remove(std::list<Chunk>::iterator chunk) noexcept {
770         // fetch next entry while chunk's still in the list
771         std::list<Chunk>::iterator next = chunk;
772         ++next;
773         // unlink neighbors so they won't reference a dead chunk
774         chunk->ClearNeighbors();
775         // if it should be saved, do it now
776         if (chunk->ShouldUpdateSave()) {
777                 save.Write(*chunk);
778         }
779         // and move it from loaded to free list
780         to_free.splice(to_free.end(), loaded, chunk);
781         return next;
782 }
783
784 Chunk *ChunkLoader::Loaded(const Chunk::Pos &pos) noexcept {
785         for (Chunk &chunk : loaded) {
786                 if (chunk.Position() == pos) {
787                         return &chunk;
788                 }
789         }
790         return nullptr;
791 }
792
793 bool ChunkLoader::Queued(const Chunk::Pos &pos) noexcept {
794         for (const Chunk::Pos &chunk : to_load) {
795                 if (chunk == pos) {
796                         return true;
797                 }
798         }
799         return false;
800 }
801
802 bool ChunkLoader::Known(const Chunk::Pos &pos) noexcept {
803         if (Loaded(pos)) return true;
804         return Queued(pos);
805 }
806
807 Chunk &ChunkLoader::ForceLoad(const Chunk::Pos &pos) {
808         Chunk *chunk = Loaded(pos);
809         if (chunk) {
810                 return *chunk;
811         }
812
813         for (auto iter(to_load.begin()), end(to_load.end()); iter != end; ++iter) {
814                 if (*iter == pos) {
815                         to_load.erase(iter);
816                         break;
817                 }
818         }
819
820         return Load(pos);
821 }
822
823 bool ChunkLoader::OutOfRange(const Chunk::Pos &pos) const noexcept {
824         return std::abs(base.x - pos.x) > unload_dist
825                         || std::abs(base.y - pos.y) > unload_dist
826                         || std::abs(base.z - pos.z) > unload_dist;
827 }
828
829 void ChunkLoader::Rebase(const Chunk::Pos &new_base) {
830         if (new_base == base) {
831                 return;
832         }
833         base = new_base;
834
835         // unload far away chunks
836         for (auto iter(loaded.begin()), end(loaded.end()); iter != end;) {
837                 if (OutOfRange(*iter)) {
838                         iter = Remove(iter);
839                 } else {
840                         ++iter;
841                 }
842         }
843         // abort far away queued chunks
844         for (auto iter(to_load.begin()), end(to_load.end()); iter != end;) {
845                 if (OutOfRange(*iter)) {
846                         iter = to_load.erase(iter);
847                 } else {
848                         ++iter;
849                 }
850         }
851         // add missing new chunks
852         QueueSurrounding(base);
853 }
854
855 void ChunkLoader::QueueSurrounding(const Chunk::Pos &pos) {
856         const Chunk::Pos offset(load_dist, load_dist, load_dist);
857         Queue(pos - offset, pos + offset);
858 }
859
860 void ChunkLoader::Update(int dt) {
861         // check if a chunk load is scheduled for this frame
862         // and if there's chunks waiting to be loaded
863         gen_timer.Update(dt);
864         if (gen_timer.Hit()) {
865                 // we may
866                 // load until one of load or generation limits was hit
867                 constexpr int max_load = 10;
868                 constexpr int max_gen = 1;
869                 int loaded = 0;
870                 int generated = 0;
871                 while (!to_load.empty() && loaded < max_load && generated < max_gen) {
872                         if (LoadOne()) {
873                                 ++generated;
874                         } else {
875                                 ++loaded;
876                         }
877                 }
878         }
879
880         constexpr int max_save = 10;
881         int saved = 0;
882         for (Chunk &chunk : loaded) {
883                 if (chunk.ShouldUpdateSave()) {
884                         save.Write(chunk);
885                         ++saved;
886                         if (saved >= max_save) {
887                                 break;
888                         }
889                 }
890         }
891 }
892
893 void ChunkLoader::LoadN(std::size_t n) {
894         std::size_t end = std::min(n, ToLoad());
895         for (std::size_t i = 0; i < end; ++i) {
896                 LoadOne();
897         }
898 }
899
900 bool ChunkLoader::LoadOne() {
901         if (to_load.empty()) return false;
902
903         // take position of next chunk in queue
904         Chunk::Pos pos(to_load.front());
905         to_load.pop_front();
906
907         // look if the same chunk was already generated and still lingering
908         for (auto iter(to_free.begin()), end(to_free.end()); iter != end; ++iter) {
909                 if (iter->Position() == pos) {
910                         loaded.splice(loaded.end(), to_free, iter);
911                         Insert(loaded.back());
912                         return false;
913                 }
914         }
915
916         // if the free list is empty, allocate a new chunk
917         // otherwise clear an unused one
918         if (to_free.empty()) {
919                 loaded.emplace_back(reg);
920         } else {
921                 to_free.front().ClearNeighbors();
922                 loaded.splice(loaded.end(), to_free, to_free.begin());
923         }
924
925         bool generated = false;
926         Chunk &chunk = loaded.back();
927         chunk.Position(pos);
928         if (save.Exists(pos)) {
929                 save.Read(chunk);
930         } else {
931                 gen(chunk);
932                 generated = true;
933         }
934         Insert(chunk);
935         return generated;
936 }
937
938 }