|
| 1 | +#include <graphics/3d/mesh.h> |
| 2 | + |
| 3 | +/// <summary> |
| 4 | +/// Generates a mesh object of an n x n grid |
| 5 | +/// </summary> |
| 6 | +/// <param name="grid_size">The size of the grid (used for grid_size * grid_size)</param> |
| 7 | +/// <returns>A grid mesh</returns> |
| 8 | +Mesh generate_grid_mesh(const int grid_size) { |
| 9 | + vector<float> vertices; |
| 10 | + vector<unsigned int> indices; |
| 11 | + |
| 12 | + for (unsigned int z = 0; z <= grid_size; ++z) { |
| 13 | + for (unsigned int x = 0; x <= grid_size; ++x) { |
| 14 | + float u = static_cast<float>(x) / grid_size; |
| 15 | + float v = static_cast<float>(z) / grid_size; |
| 16 | + |
| 17 | + vertices.push_back(u * 2.0f - 1.0f); |
| 18 | + // y is modified at runtime |
| 19 | + vertices.push_back(0.0f); |
| 20 | + vertices.push_back(v * 2.0f - 1.0f); |
| 21 | + } |
| 22 | + } |
| 23 | + for (unsigned int z = 0; z < grid_size; ++z) { |
| 24 | + for (int x = 0; x < grid_size; ++x) { |
| 25 | + int row1 = z * (grid_size + 1); |
| 26 | + int row2 = (z + 1) * (grid_size + 1); |
| 27 | + |
| 28 | + indices.push_back(row1 + x); |
| 29 | + indices.push_back(row2 + x); |
| 30 | + indices.push_back(row1 + x + 1); |
| 31 | + |
| 32 | + indices.push_back(row1 + x + 1); |
| 33 | + indices.push_back(row2 + x); |
| 34 | + indices.push_back(row2 + x + 1); |
| 35 | + } |
| 36 | + } |
| 37 | + Mesh mesh; |
| 38 | + link_mesh(mesh, vertices, indices); |
| 39 | + return mesh; |
| 40 | +} |
| 41 | + |
| 42 | +void link_mesh(Mesh& mesh, const vector<float>& vertices, const vector<unsigned int>& indices) { |
| 43 | + glGenVertexArrays(1, &mesh.VAO); |
| 44 | + glGenBuffers(1, &mesh.VBO); |
| 45 | + glGenBuffers(1, &mesh.EBO); |
| 46 | + |
| 47 | + glBindVertexArray(mesh.VAO); |
| 48 | + |
| 49 | + glBindBuffer(GL_ARRAY_BUFFER, mesh.VBO); |
| 50 | + glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(float), vertices.data(), GL_STATIC_DRAW); |
| 51 | + |
| 52 | + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, mesh.EBO); |
| 53 | + glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.size() * sizeof(unsigned int), indices.data(), GL_STATIC_DRAW); |
| 54 | + |
| 55 | + glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); |
| 56 | + glEnableVertexAttribArray(0); |
| 57 | + |
| 58 | + glBindVertexArray(0); |
| 59 | + mesh.index_count = (unsigned int)indices.size(); |
| 60 | +} |
0 commit comments