70 lines
2.2 KiB
C++
70 lines
2.2 KiB
C++
#include <GL/glew.h>
|
|
#include "bettola/game/chunk.h"
|
|
#include "chunk_mesh.h"
|
|
|
|
ChunkMesh::ChunkMesh(int chunk_x, int chunk_z, const BettolaLib::Game::Chunk& chunk) {
|
|
/* Generate vertices from the heightmap. */
|
|
for(int z = 0; z < BettolaLib::Game::CHUNK_HEIGHT; ++z) {
|
|
for(int x = 0; x < BettolaLib::Game::CHUNK_WIDTH; ++x) {
|
|
/* Vertex position. */
|
|
_vertices.push_back((float)(chunk_x * (BettolaLib::Game::CHUNK_WIDTH-1) + x));
|
|
_vertices.push_back(chunk.heightmap[z * BettolaLib::Game::CHUNK_WIDTH+x] * 5.0f); /* 5x scale height */
|
|
_vertices.push_back((float)(chunk_z * (BettolaLib::Game::CHUNK_HEIGHT-1) + z));
|
|
}
|
|
}
|
|
|
|
/* Generate indices for the triangles. */
|
|
for(int z = 0; z < BettolaLib::Game::CHUNK_HEIGHT-1; ++z) {
|
|
for(int x = 0; x < BettolaLib::Game::CHUNK_WIDTH-1; ++x) {
|
|
int top_left = z * BettolaLib::Game::CHUNK_WIDTH + x;
|
|
int top_right = top_left + 1;
|
|
int bottom_left = (z+1) * BettolaLib::Game::CHUNK_WIDTH + x;
|
|
int bottom_right = bottom_left + 1;
|
|
|
|
/* First triangle of the quad. */
|
|
_indices.push_back(top_left);
|
|
_indices.push_back(bottom_left);
|
|
_indices.push_back(top_right);
|
|
|
|
/* Second triangle of the quad. */
|
|
_indices.push_back(top_right);
|
|
_indices.push_back(bottom_left);
|
|
_indices.push_back(bottom_right);
|
|
}
|
|
}
|
|
|
|
_setup_mesh();
|
|
}
|
|
|
|
ChunkMesh::~ChunkMesh(void) {
|
|
glDeleteVertexArrays(1, &_vao);
|
|
glDeleteBuffers(1, &_vbo);
|
|
glDeleteBuffers(1, &_ebo);
|
|
}
|
|
|
|
void ChunkMesh::_setup_mesh(void) {
|
|
glGenVertexArrays(1, &_vao);
|
|
glGenBuffers(1, &_vbo);
|
|
glGenBuffers(1, &_ebo);
|
|
|
|
glBindVertexArray(_vao);
|
|
|
|
glBindBuffer(GL_ARRAY_BUFFER, _vbo);
|
|
glBufferData(GL_ARRAY_BUFFER, _vertices.size()*sizeof(float), _vertices.data(), GL_STATIC_DRAW);
|
|
|
|
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _ebo);
|
|
glBufferData(GL_ELEMENT_ARRAY_BUFFER, _indices.size()*sizeof(unsigned int), _indices.data(), GL_STATIC_DRAW);
|
|
|
|
/* Position attrib. */
|
|
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void*)0);
|
|
glEnableVertexAttribArray(0);
|
|
|
|
glBindVertexArray(0);
|
|
}
|
|
|
|
void ChunkMesh::draw(void) {
|
|
glBindVertexArray(_vao);
|
|
glDrawElements(GL_TRIANGLES, _indices.size(), GL_UNSIGNED_INT, 0);
|
|
glBindVertexArray(0);
|
|
}
|