]> git.localhorst.tv Git - blank.git/blob - src/chunk.hpp
use player-relative coordinates for rendering
[blank.git] / src / chunk.hpp
1 #ifndef BLANK_CHUNK_HPP_
2 #define BLANK_CHUNK_HPP_
3
4 #include "block.hpp"
5 #include "geometry.hpp"
6 #include "model.hpp"
7
8 #include <vector>
9 #include <glm/glm.hpp>
10
11
12 namespace blank {
13
14 /// cube of size 16 (256 tiles, 4096 blocks)
15 class Chunk {
16
17 public:
18         Chunk();
19
20         Chunk(Chunk &&);
21         Chunk &operator =(Chunk &&);
22
23         static constexpr int Width() { return 16; }
24         static constexpr int Height() { return 16; }
25         static constexpr int Depth() { return 16; }
26         static glm::vec3 Extent() { return glm::vec3(Width(), Height(), Depth()); }
27         static constexpr int Size() { return Width() * Height() * Depth(); }
28
29         static constexpr bool InBounds(const glm::vec3 &pos) {
30                 return
31                         pos.x >= 0 && pos.x < Width() &&
32                         pos.y >= 0 && pos.y < Height() &&
33                         pos.z >= 0 && pos.z < Depth();
34         }
35         static constexpr int ToIndex(const glm::vec3 &pos) {
36                 return int(pos.x) + int(pos.y) * Width() + int(pos.z) * Width() * Height();
37         }
38         static constexpr bool InBounds(int idx) {
39                 return idx >= 0 && idx < Size();
40         }
41         static glm::vec3 ToCoords(int idx) {
42                 return glm::vec3(
43                         0.5f + idx % Width(),
44                         0.5f + (idx / Width()) % Height(),
45                         0.5f + idx / (Width() * Height())
46                 );
47         }
48
49         void Invalidate() { dirty = true; }
50
51         Block &BlockAt(int index) { return blocks[index]; }
52         const Block &BlockAt(int index) const { return blocks[index]; }
53         Block &BlockAt(const glm::vec3 &pos) { return BlockAt(ToIndex(pos)); }
54         const Block &BlockAt(const glm::vec3 &pos) const { return BlockAt(ToIndex(pos)); }
55
56         bool Intersection(
57                 const Ray &,
58                 const glm::mat4 &M,
59                 int *blkid = nullptr,
60                 float *dist = nullptr,
61                 glm::vec3 *normal = nullptr) const;
62
63         void Position(const glm::vec3 &);
64         const glm::vec3 &Position() const { return position; }
65         glm::mat4 Transform(const glm::vec3 &offset) const;
66
67         void Draw();
68
69 private:
70         int VertexCount() const;
71         void Update();
72
73 private:
74         std::vector<Block> blocks;
75         Model model;
76         glm::vec3 position;
77         bool dirty;
78
79 };
80
81 }
82
83 #endif