Add GLM and make the triangle move

This commit is contained in:
Nathan Chapman 2025-07-02 08:09:31 -06:00
parent 27452c30a5
commit 56cf609849
2 changed files with 42 additions and 18 deletions

View File

@ -5,6 +5,7 @@ set(CMAKE_CXX_STANDARD 17)
find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)
find_package(glm REQUIRED)
find_package(glfw3 REQUIRED)
add_executable(opengl_test src/main.cpp)
@ -12,5 +13,6 @@ add_executable(opengl_test src/main.cpp)
target_link_libraries(opengl_test
OpenGL::GL
GLEW::GLEW
glm::glm
glfw
)

View File

@ -2,6 +2,7 @@
#include <string.h>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <cmath>
// Window dimensions
const GLint WIDTH = 800, HEIGHT = 600;
@ -12,8 +13,10 @@ static const char *vertex_shader = " \n\
\n\
layout (location = 0) in vec3 pos; \n\
\n\
uniform float x_move; \n\
\n\
void main() { \n\
gl_Position = vec4(pos.x, pos.y, pos.z, 1.0); \n\
gl_Position = vec4(pos.x + x_move, pos.y, pos.z, 1.0); \n\
}";
// Fragment shader
@ -51,7 +54,7 @@ bool add_shader(GLuint *program, const char *shader_code, GLenum shader_type) {
return true;
}
bool compile_shaders(GLuint *shader_program) {
bool compile_shaders(GLuint *shader_program, GLuint *x_move) {
*shader_program = glCreateProgram();
if (!shader_program) {
@ -83,6 +86,8 @@ bool compile_shaders(GLuint *shader_program) {
return false;
}
*x_move = glGetUniformLocation(*shader_program, "x_move");
return true;
}
@ -109,7 +114,11 @@ void create_triangle(GLuint *VAO, GLuint *VBO) {
}
int main() {
GLuint VAO, VBO, shader_program;
GLuint VAO, VBO, shader_program, x_move;
bool direction = true;
float tri_offset = 0.0f;
float tri_max_offset = 0.7f;
float tri_increment = 0.005f;
// Initialize GLFW
glfwInitHint(GLFW_PLATFORM, GLFW_PLATFORM_WAYLAND);
@ -168,18 +177,31 @@ int main() {
// Create our triangle
create_triangle(&VAO, &VBO);
compile_shaders(&shader_program);
compile_shaders(&shader_program, &x_move);
// Loop until window is closed
while (!glfwWindowShouldClose(window)) {
// Get and handle user input events
glfwPollEvents();
if (direction) {
tri_offset += tri_increment;
} else {
tri_offset -= tri_increment;
}
if (std::abs(tri_offset) >= tri_max_offset) {
direction = !direction;
}
// Clear window
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
glUseProgram(shader_program);
glUniform1f(x_move, tri_offset);
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);