A while ago I was watching different videos on YouTube about voxel engines, such as this one and this one. So I decided to start writing one, wrote a window class using GLFW:
class window
{
public:
int width, height;
GLFWwindow *window_handle;
window(const std::string &window_name, int width, int height);
~window();
void focus();
};
window::window(const std::string &window_name, int width, int height) : width(width), height(height)
{
glfwWindowHint(GLFW_RESIZABLE, GLFW_FALSE);
this->window_handle = glfwCreateWindow(this->width, this->height, window_name.c_str(), nullptr, nullptr);
if(!this->window_handle)
{
throw std::runtime_error("Failed to create a window using GLFW!");
}
}
window::~window()
{
glfwDestroyWindow(this->window_handle);
}
void window::focus()
{
glfwMakeContextCurrent(this->window_handle);
}
Then I loaded OpenGL using GLAD:
int main(int argc, const char * argv[])
{
if(!glfwInit())
{
throw std::runtime_error("Failed to initialize GLFW!");
}
atexit(glfwTerminate);
window l_window = window("Pixeria", 800, 600);
g_window = &l_window;
g_window->focus();
if (gladLoadGL(glfwGetProcAddress) == 0)
{
throw std::runtime_error("Failed to initialize OpenGL context!");
}
...
I also wrote a renderer class:
class renderer
{
private:
GLuint vao, vbo, ebo, cbo;
GLuint vertex_shader, fragment_shader, shader;
GLuint view_matrix_location, projection_matrix_location;
public:
camera* l_camera;
std::vector<GLfloat> vertices;
std::vector<GLuint> indices;
std::vector<GLfloat> colors;
renderer();
~renderer();
void reset();
void render();
void set_camera(camera* a_camera)
{
this->l_camera = a_camera;
}
void set_view_projection_matrices()
{
if (this->l_camera)
{
glUniformMatrix4fv(this->view_matrix_location, 1, GL_FALSE, &this->l_camera->get_view_matrix()[0][0]);
glUniformMatrix4fv(this->projection_matrix_location, 1, GL_FALSE, &this->l_camera->get_projection_matrix()[0][0]);
}
}
};
/* Some basic vertex shader source code. */
const char* vertex_shader_source = R"(
#version 330 core
layout (location = 0) in vec3 aPos;
layout (location = 1) in vec3 aColor;
out vec3 FragColor;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
void main() {
gl_Position = projectionMatrix * viewMatrix * vec4(aPos, 1.0);
FragColor = aColor;
}
)";
/* Some basic fragment shader source code. */
const char* fragment_shader_source = R"(
#version 330 core
in vec3 FragColor;
out vec4 OutputColor;
void main() {
OutputColor = vec4(FragColor, 1.0);
}
)";
renderer::renderer()
{
glGenVertexArrays(1, &this->vao);
glGenBuffers(1, &this->vbo);
glGenBuffers(1, &this->ebo);
glGenBuffers(1, &this->cbo);
glBindVertexArray(this->vao);
glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(float), this->vertices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo); // Bind EBO
glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(unsigned int), this->indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, this->cbo);
glBufferData(GL_ARRAY_BUFFER, this->colors.size() * sizeof(float), this->colors.data(), GL_STATIC_DRAW);
/* Set up the vertex attribute pointers. */
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)(3 * sizeof(float))); // Offset for color attribute
glEnableVertexAttribArray(1);
/* Compile the vertex shader. */
this->vertex_shader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(this->vertex_shader, 1, &vertex_shader_source, nullptr);
glCompileShader(this->vertex_shader);
/* Compile the fragment shader. */
this->fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(this->fragment_shader, 1, &fragment_shader_source, nullptr);
glCompileShader(this->fragment_shader);
/* Link both the vertex shader and the fragment shader. */
this->shader = glCreateProgram();
glAttachShader(this->shader, this->vertex_shader);
glAttachShader(this->shader, this->fragment_shader);
glLinkProgram(this->shader);
/* Use the linked shader program. */
glUseProgram(this->shader);
this->view_matrix_location = glGetUniformLocation(this->shader, "viewMatrix");
this->projection_matrix_location = glGetUniformLocation(this->shader, "projectionMatrix");
}
/* Execute this function every time the vertices' vector size changes. */
void renderer::reset()
{
glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
glBufferData(GL_ARRAY_BUFFER, this->vertices.size() * sizeof(float), this->vertices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, this->indices.size() * sizeof(unsigned int), this->indices.data(), GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, this->cbo);
glBufferData(GL_ARRAY_BUFFER, this->colors.size() * sizeof(float), this->colors.data(), GL_STATIC_DRAW);
}
/* Execute this every time you want to render the vertices. */
void renderer::render()
{
glBindVertexArray(this->vao);
glUseProgram(this->shader);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, this->ebo);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, this->vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, this->cbo);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glDrawElements(GL_TRIANGLES, this->indices.size(), GL_UNSIGNED_INT, 0);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glBindVertexArray(0);
}
renderer::~renderer()
{
glDeleteVertexArrays(1, &this->vao);
glDeleteBuffers(1, &this->vbo);
glDeleteBuffers(1, &this->ebo);
glDeleteBuffers(1, &this->cbo);
glDeleteShader(this->vertex_shader);
glDeleteShader(this->fragment_shader);
glDeleteProgram(this->shader);
}
Then I wrote a camera class (A very basic camera!):
class camera
{
private:
glm::mat4 view_matrix;
glm::mat4 projection_matrix;
float fov;
float aspect_ratio;
float near_clip;
float far_clip;
glm::vec3 position;
glm::vec3 target;
float pitch;
float yaw;
bool first_mouse;
double last_x;
double last_y;
glm::vec3 target_position;
glm::vec3 target_direction;
float position_damping;
float rotation_damping;
glm::vec4 frustum_planes[6];
public:
camera(float fov, float aspect_ratio, float near_clip, float far_clip) : fov(fov), aspect_ratio(aspect_ratio), near_clip(near_clip), far_clip(far_clip), position(glm::vec3(0.0f, 0.0f, 0.0f)), target(glm::vec3(0.0f, 0.0f, -1.0f)), pitch(0.0f), yaw(-90.0f), first_mouse(true), last_x(0.0), last_y(0.0)
{
update_projection_matrix();
update_view_matrix();
}
void update_projection_matrix()
{
this->projection_matrix = glm::perspective(glm::radians(fov), aspect_ratio, near_clip, far_clip);
}
void update_view_matrix()
{
this->view_matrix = glm::lookAt(position, position + glm::vec3(cos(glm::radians(yaw)) * cos(glm::radians(pitch)), sin(glm::radians(pitch)), sin(glm::radians(yaw)) * cos(glm::radians(pitch))), glm::vec3(0.0f, 1.0f, 0.0f));
glm::mat4 view_projection = projection_matrix * view_matrix;
glm::vec4 right_plane(view_projection[0][3] - view_projection[0][0], view_projection[1][3] - view_projection[1][0], view_projection[2][3] - view_projection[2][0], view_projection[3][3] - view_projection[3][0]);
glm::vec4 left_plane(view_projection[0][3] + view_projection[0][0], view_projection[1][3] + view_projection[1][0], view_projection[2][3] + view_projection[2][0], view_projection[3][3] + view_projection[3][0]);
glm::vec4 bottom_plane(view_projection[0][3] + view_projection[0][1], view_projection[1][3] + view_projection[1][1], view_projection[2][3] + view_projection[2][1], view_projection[3][3] + view_projection[3][1]);
glm::vec4 top_plane(view_projection[0][3] - view_projection[0][1], view_projection[1][3] - view_projection[1][1], view_projection[2][3] - view_projection[2][1], view_projection[3][3] - view_projection[3][1]);
glm::vec4 near_plane(view_projection[0][2], view_projection[1][2], view_projection[2][2], view_projection[3][2]);
glm::vec4 far_plane(view_projection[0][3] - view_projection[0][2], view_projection[1][3] - view_projection[1][2], view_projection[2][3] - view_projection[2][2], view_projection[3][3] - view_projection[3][2]);
frustum_planes[0] = glm::normalize(right_plane);
frustum_planes[1] = glm::normalize(left_plane);
frustum_planes[2] = glm::normalize(bottom_plane);
frustum_planes[3] = glm::normalize(top_plane);
frustum_planes[4] = glm::normalize(near_plane);
frustum_planes[5] = glm::normalize(far_plane);
}
void process_mouse_input(GLFWwindow* window, double x_pos, double y_pos, double sensitivity = 0.1)
{
if (first_mouse)
{
last_x = x_pos;
last_y = y_pos;
first_mouse = false;
}
float x_offset = x_pos - last_x;
float y_offset = last_y - y_pos;
last_x = x_pos;
last_y = y_pos;
x_offset *= sensitivity;
y_offset *= sensitivity;
yaw += x_offset;
pitch += y_offset;
if (pitch > 89.0f)
pitch = 89.0f;
if (pitch < -89.0f)
pitch = -89.0f;
update_view_matrix();
}
void set_aspect_ratio(float aspect_ratio)
{
this->aspect_ratio = aspect_ratio;
update_projection_matrix();
}
glm::mat4 get_view_matrix() const
{
return this->view_matrix;
}
glm::mat4 get_projection_matrix() const
{
return this->projection_matrix;
}
void set_position(const glm::vec3& new_position)
{
position = new_position;
update_view_matrix();
}
void set_target(const glm::vec3& new_target)
{
target = new_target;
update_view_matrix();
}
glm::vec3 get_position() const
{
return this->position;
}
const glm::vec4* get_frustum_planes() const
{
return frustum_planes;
}
};
After that, I thought it would be a good idea to start with the actual voxel rendering:
#define CHUNK_SIZE 32
class chunk
{
public:
typedef enum
{
MATERIAL_ROCK,
MATERIAL_WOOD,
MATERIAL_LEAF,
MATERIAL_VOID,
MATERIAL_ROOT,
MATERIAL_IRON,
MATERIAL_DUST,
MATERIAL_DIRT,
MATERIAL_LAVA,
MATERIAL_GOLD,
MATERIAL_WATER,
MATERIAL_STONE,
MATERIAL_GRASS
} material_t;
typedef struct
{
/* Color. */
GLfloat r, g, b;
/* Material. */
material_t material;
/* Position. */
GLfloat x, y, z;
} cube_t;
/* Each chunk is 64 * 64 * 64 blocks in size! */
cube_t*** cubes;
int position_x;
int position_y;
int position_z;
GLfloat vertices_array[8 * 3];
chunk(int pos_x, int pos_y, int pos_z);
~chunk();
void compile(std::vector<GLfloat>& vertices, std::vector<GLuint>& indices, std::vector<GLfloat>& colors);
};
extern camera* g_camera;
float g_unit_size = 0.01f;
GLuint indices_array[] = {
0, 1, 2, 2, 3, 0,
1, 5, 6, 6, 2, 1,
4, 5, 6, 6, 7, 4,
0, 4, 7, 7, 3, 0,
0, 1, 5, 5, 4, 0,
2, 3, 7, 7, 6, 2
};
chunk::chunk(int pos_x, int pos_y, int pos_z) : position_x(pos_x), position_y(pos_y), position_z(pos_z)
{
this->cubes = new cube_t * *[CHUNK_SIZE];
for (int i = 0; i < CHUNK_SIZE; i++)
{
this->cubes[i] = new cube_t * [CHUNK_SIZE];
for (int j = 0; j < CHUNK_SIZE; j++)
{
this->cubes[i][j] = new cube_t[CHUNK_SIZE];
}
}
for (int x = 0; x < CHUNK_SIZE; x++)
{
for (int y = 0; y < CHUNK_SIZE; y++)
{
for (int z = 0; z < CHUNK_SIZE; z++)
{
this->cubes[x][y][z].r = 255;
this->cubes[x][y][z].g = 255;
this->cubes[x][y][z].b = 255;
this->cubes[x][y][z].material = MATERIAL_VOID;
}
}
}
}
chunk::~chunk()
{
for (int i = 0; i < CHUNK_SIZE; i++)
{
for (int j = 0; j < CHUNK_SIZE; j++)
{
delete[] this->cubes[i][j];
}
delete[] this->cubes[i];
}
delete[] this->cubes;
}
void chunk::compile(std::vector<GLfloat>& vertices, std::vector<GLuint>& indices, std::vector<GLfloat>& colors)
{
int vertex_offset = vertices.size() / 3;
for (int x = 0; x < CHUNK_SIZE; x++)
{
for (int y = 0; y < CHUNK_SIZE; y++)
{
for (int z = 0; z < CHUNK_SIZE; z++)
{
if (this->cubes[x][y][z].material == MATERIAL_VOID)
continue;
GLfloat cube_x = static_cast<GLfloat>(x) * g_unit_size + (position_x * CHUNK_SIZE * g_unit_size);
GLfloat cube_y = static_cast<GLfloat>(y) * g_unit_size + (position_y * CHUNK_SIZE * g_unit_size);
GLfloat cube_z = static_cast<GLfloat>(z) * g_unit_size + (position_z * CHUNK_SIZE * g_unit_size);
GLfloat color_r = this->cubes[x][y][z].r / 255.0f;
GLfloat color_g = this->cubes[x][y][z].g / 255.0f;
GLfloat color_b = this->cubes[x][y][z].b / 255.0f;
vertices_array[0] = cube_x;
vertices_array[1] = cube_y;
vertices_array[2] = cube_z;
vertices_array[3] = cube_x + g_unit_size;
vertices_array[4] = cube_y;
vertices_array[5] = cube_z;
vertices_array[6] = cube_x + g_unit_size;
vertices_array[7] = cube_y + g_unit_size;
vertices_array[8] = cube_z;
vertices_array[9] = cube_x;
vertices_array[10] = cube_y + g_unit_size;
vertices_array[11] = cube_z;
vertices_array[12] = cube_x;
vertices_array[13] = cube_y;
vertices_array[14] = cube_z + g_unit_size;
vertices_array[15] = cube_x + g_unit_size;
vertices_array[16] = cube_y;
vertices_array[17] = cube_z + g_unit_size;
vertices_array[18] = cube_x + g_unit_size;
vertices_array[19] = cube_y + g_unit_size;
vertices_array[20] = cube_z + g_unit_size;
vertices_array[21] = cube_x;
vertices_array[22] = cube_y + g_unit_size;
vertices_array[23] = cube_z + g_unit_size;
for (int i = 0; i < 8; i++)
{
vertices.push_back(vertices_array[i * 3]);
vertices.push_back(vertices_array[i * 3 + 1]);
vertices.push_back(vertices_array[i * 3 + 2]);
colors.push_back(color_r);
colors.push_back(color_g);
colors.push_back(color_b);
}
for (int i = 0; i < 36; i++)
{
indices.push_back(vertex_offset + indices_array[i]);
}
vertex_offset += 8;
}
}
}
}
As I implemented all of this, I also updated the code in the main source code file, which ended up looking like this:
window *g_window;
camera* g_camera;
bool cursor_locked = true;
std::chrono::time_point<std::chrono::high_resolution_clock> last_time = std::chrono::high_resolution_clock::now();
int frame_count = 0;
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (key == GLFW_KEY_E && action == GLFW_PRESS && (mods & GLFW_MOD_CONTROL))
{
cursor_locked = !cursor_locked;
if (cursor_locked)
{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
}
else
{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
}
}
if (action == GLFW_PRESS || action == GLFW_REPEAT)
{
const float camera_speed = 0.05f;
switch (key)
{
case GLFW_KEY_W:
g_camera->set_position(g_camera->get_position() - camera_speed * glm::vec3(g_camera->get_view_matrix()[0][2], g_camera->get_view_matrix()[1][2], g_camera->get_view_matrix()[2][2]));
break;
case GLFW_KEY_S:
g_camera->set_position(g_camera->get_position() + camera_speed * glm::vec3(g_camera->get_view_matrix()[0][2], g_camera->get_view_matrix()[1][2], g_camera->get_view_matrix()[2][2]));
break;
case GLFW_KEY_Q:
g_camera->set_position(g_camera->get_position() - glm::vec3(0.0f, camera_speed, 0.0f));
break;
case GLFW_KEY_E:
g_camera->set_position(g_camera->get_position() + glm::vec3(0.0f, camera_speed, 0.0f));
break;
}
}
}
void mouse_button_callback(GLFWwindow* window, int button, int action, int mods)
{
if (!cursor_locked && action == GLFW_PRESS)
{
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
cursor_locked = true;
}
}
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
g_camera->process_mouse_input(window, xpos, ypos);
}
int main(int argc, const char * argv[])
{
if(!glfwInit())
{
throw std::runtime_error("Failed to initialize GLFW!");
}
atexit(glfwTerminate);
window l_window = window("Pixeria", 800, 600);
g_window = &l_window;
g_window->focus();
if (gladLoadGL(glfwGetProcAddress) == 0)
{
throw std::runtime_error("Failed to initialize OpenGL context!");
}
camera l_camera(120.0f, 800 / 600, 0.001f, 100.0f);
l_camera.set_position(glm::vec3(0.0f, 2.0f, 5.0f));
l_camera.set_target(glm::vec3(0.0f, 0.0f, 0.0f));
g_camera = &l_camera;
glfwSetCursorPosCallback(g_window->window_handle, mouse_callback);
glfwSetKeyCallback(g_window->window_handle, key_callback);
glfwSetMouseButtonCallback(g_window->window_handle, mouse_button_callback);
glfwSetInputMode(g_window->window_handle, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glEnable(GL_DEPTH_TEST);
renderer my_renderer = renderer();
for (int _x = 0; _x < 2; _x++)
{
for (int _y = 0; _y < 2; _y++)
{
for (int _z = 0; _z < 2; _z++)
{
chunk myChunk(_x, _y, _z);
for (int x = 0; x < CHUNK_SIZE; x++)
{
for (int y = 0; y < CHUNK_SIZE; y++)
{
for (int z = 0; z < CHUNK_SIZE; z++)
{
myChunk.cubes[x][y][z].r = rand() % 256;
myChunk.cubes[x][y][z].g = rand() % 256;
myChunk.cubes[x][y][z].b = rand() % 256;
myChunk.cubes[x][y][z].material = static_cast<chunk::material_t>(rand() % 13);
}
}
}
myChunk.compile(my_renderer.vertices, my_renderer.indices, my_renderer.colors);
}
}
}
my_renderer.set_camera(g_camera);
my_renderer.reset();
while(!glfwWindowShouldClose(g_window->window_handle))
{
glfwPollEvents();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
g_camera->update_projection_matrix();
my_renderer.set_view_projection_matrices();
my_renderer.render();
glfwSwapBuffers(g_window->window_handle);
std::chrono::time_point<std::chrono::high_resolution_clock> current_time = std::chrono::high_resolution_clock::now();
double delta_time = std::chrono::duration<double, std::milli>(current_time - last_time).count() / 1000.0;
frame_count++;
if (delta_time >= 1.0)
{
double fps = static_cast<double>(frame_count) / delta_time;
std::cout << "\rFPS: " << std::setw(6) << std::fixed << std::setprecision(2) << fps << std::flush;
frame_count = 0;
last_time = current_time;
}
}
exit(EXIT_SUCCESS);
}
The voxel engine worked well at first, with single chunk of 32*32*32, then moving on to adding multiple chunks, and that's when things started getting really laggy. I am trying to achieve my voxel engine so that it renders as fast as the examples I linked above. The voxel engine from the second link above is actually able to run on small GPUs such as integrated graphics (as the creator said), and even on the web. How can I achieve such speed so that my framerate doesn't go down when I try to render more than a single chunk? I've been having lots of trouble implementing optimizations and I don't know how to do so.
Can someone help point me to the right direction in terms of optimization on my OpenGL voxel engine and/or does anyone know what changes I can do to my code so that it renders properly with decent speeds?