summary refs log tree commit diff
path: root/src/World/Chunk.cpp
blob: 73aab3d8ce1d277011ec84bef14781ffae6adf9b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "Chunk.hpp"
#include "BlockSide.hpp"

namespace MC {

void Chunk::set(uint32_t x, uint32_t y, uint32_t z, BlockType type) {
    m_blocks[x][y][z].type = type;
}

Mesh Chunk::mesh() {
    std::vector<Vector<3>> positions{};
    std::vector<Vector<2>> tex_coords{};
    std::vector<uint32_t> indices{};

    for (int x = 0; x < CHUNK_WIDTH; x++) {
        for (int y = 0; y < CHUNK_HEIGHT; y++) {
            for (int z = 0; z < CHUNK_WIDTH; z++) {
                auto type = m_blocks[x][y][z].type;
                if (type == BlockType::Air) {
                    continue;
                }

                for (auto side: BlockSide::all()) {
                    auto side_tex_coords = Chunk::face_tex_coords(type, side);
                    auto side_positions = side.face();

                    for (auto& position : side_positions) {
                        position = position + Vector<3>{static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)};
                    }

                    uint32_t s = positions.size();

                    positions.insert(positions.end(), side_positions.begin(), side_positions.end());
                    tex_coords.insert(tex_coords.end(), side_tex_coords.begin(), side_tex_coords.end());
                    indices.insert(indices.end(), {s, s + 1, s + 3, s + 1, s + 2, s + 3});
                }
            }
        }
    }

    return {positions, tex_coords, indices};
}

std::array<Vector<2>, 4> Chunk::face_tex_coords(BlockType type, BlockSide side) {
    switch (type) {
        case BlockType::Dirt:
            return {{
                {0.5f, 0.0f}, {1.0f, 0.0f}, {1.0f, 0.5f}, {0.5f, 0.5f},
            }};
        case BlockType::Grass:
            switch (side) {
                case BlockSide::Front:
                case BlockSide::Back:
                case BlockSide::Left:
                case BlockSide::Right:
                    return {{
                        {0.5f, 1.0f}, {0.0f, 1.0f},  {0.0f, 0.5f}, {0.5f, 0.5f},
                    }};
                case BlockSide::Top:
                    return {{
                        {0.0f, 0.0f}, {0.5f, 0.0f}, {0.5f, 0.5f}, {0.0f, 0.5f},
                    }};
                case BlockSide::Bottom:
                    return {{
                        {0.5f, 0.0f}, {1.0f, 0.0f}, {1.0f, 0.5f}, {0.5f, 0.5f},
                    }};
            }
        default:
            return {};
    }}

}