Write a simple graphics app using OpenGL in C++
- User
Write a simple graphics app using OpenGL in C++
- Assistant
Write a simple graphics app using OpenGL in C++
Creating a simple graphics application using OpenGL in C++ typically involves several steps:
Below is a complete example using GLFW for window management and GLAD for loading OpenGL function pointers. This example renders a simple colored triangle.
Assuming you have the following directory structure:
/project
│
├── main.cpp
├── glad/
│ ├── glad.c
│ ├── glad.h
│ └── KHR/
│ └── glad.h
└── include/
└── GLFW/
└── ... (GLFW headers)
main.cpp)#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
// Callback function for resizing the window
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
glViewport(0, 0, width, height);
}
// Process input: close window on pressing 'Escape'
void processInput(GLFWwindow *window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
}
// Vertex Shader source code
const char* vertexShaderSource = R"glsl(
#version 330 core
layout (location = 0) in vec3 aPos; // Position attribute
void main()
{
gl_Position = vec4(aPos, 1.0);
}
)glsl";
// Fragment Shader source code
const char* fragmentShaderSource = R"glsl(
#version 330 core
out vec4 FragColor; // Output color
void main()
{
FragColor = vec4(0.4, 0.6, 0.9, 1.0); // Set the color to a light blue
}
)glsl";
int main()
{
// Initialize GLFW
if (!glfwInit())
{
std::cerr << "Failed to initialize GLFW\n";
return -1;
}
// Set OpenGL version (3.3 Core)
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// For MacOS uncomment the following line
// glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
// Create a windowed mode window and its OpenGL context
GLFWwindow* window = glfwCreateWindow(800, 600, "Simple OpenGL App", NULL, NULL);
if (!window)
{
std::cerr << "Failed to create GLFW window\n";
glfwTerminate();
return -1;
}
// Make the window's context current
glfwMakeContextCurrent(window);
// Load OpenGL function pointers with GLAD
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cerr << "Failed to initialize GLAD\n";
return -1;
}
// Set the viewport
glViewport(0, 0, 800, 600);
// Register the callback function for window resize
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
// Build and compile the shader program
// Vertex Shader
unsigned int vertexShader = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
glCompileShader(vertexShader);
// Check for shader compile errors
int success;
char infoLog[512];
glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
std::cerr << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << "\n";
}
// Fragment Shader
unsigned int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
glCompileShader(fragmentShader);
// Check for shader compile errors
glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
if(!success)
{
glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
std::cerr<< "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << "\n";
}
// Link Shaders
unsigned int shaderProgram = glCreateProgram();
glAttachShader(shaderProgram, vertexShader);
glAttachShader(shaderProgram, fragmentShader);
glLinkProgram(shaderProgram);
// Check for linking errors
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
if(!success)
{
glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
std::cerr<< "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << "\n";
}
// Delete shaders as they're linked into our program now and no longer needed
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
// Set up vertex data and buffers and configure vertex attributes
float vertices[] = {
// Positions
0.0f, 0.5f, 0.0f, // Top
0.5f, -0.5f, 0.0f, // Right
-0.5f, -0.5f, 0.0f // Left
};
unsigned int VBO, VAO;
glGenVertexArrays(1, &VAO); // Vertex Array Object
glGenBuffers(1, &VBO); // Vertex Buffer Object
// Bind the Vertex Array Object first, then bind and set vertex buffers, and then configure vertex attributes
glBindVertexArray(VAO);
// Bind the VBO
glBindBuffer(GL_ARRAY_BUFFER, VBO);
// Copy the vertex data into buffer's memory
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Define the vertex attribute (position)
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
// You can unbind the VBO and VAO after setting them up
glBindBuffer(GL_ARRAY_BUFFER, 0);
glBindVertexArray(0);
// Render loop
while (!glfwWindowShouldClose(window))
{
// Input
processInput(window);
// Rendering commands here
glClearColor(0.2f, 0.3f, 0.3f, 1.0f); // Set clear color to dark teal
glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer
// Draw the triangle
glUseProgram(shaderProgram);
glBindVertexArray(VAO); // Bind VAO
glDrawArrays(GL_TRIANGLES, 0, 3); // Draw 3 vertices as one triangle
// Swap front and back buffers
glfwSwapBuffers(window);
// Poll for and process events
glfwPollEvents();
}
// De-allocate all resources once they've outlived their purpose
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
glDeleteProgram(shaderProgram);
// Terminate GLFW, clearing any resources allocated by GLFW.
glfwTerminate();
return 0;
}
To compile this application, ensure that you link against the GLFW and OpenGL libraries. Here's an example using g++ on Linux:
g++ main.cpp glad/glad.c -o SimpleOpenGLApp -lglfw -ldl -lGL
Notes:
glad and GLFW headers. You might need to add -I flags to specify include directories.-L flags for library directories.opengl32.lib and ensure that GLFW and GLAD binaries are correctly set up.-framework OpenGL -framework Cocoa -framework IOKit -framework CoreVideo and link GLFW appropriately.After successful compilation, run the application:
./SimpleOpenGLApp
A window should appear displaying a simple light blue background with a single white triangle in the center.
Initialization:
Shaders:
Buffers:
Render Loop:
Cleanup:
glfwWindowHint accordingly.This simple application serves as a foundation. From here, you can expand by adding more complex shaders, handling user input, loading textures, and rendering more intricate 3D models.
Not yet included in a published release.