OpenGL Overview
OpenGL (Open Graphics Library) is a cross-platform API for rendering 2D and 3D graphics. It provides a state machine interface for hardware-accelerated rendering and is widely used in games, CAD, and scientific visualization.
OpenGL Versions
OpenGL History:
1.0 (1992) - Initial release
2.0 (2004) - Programmable shaders
3.0 (2008) - Modern profile, deprecated fixed-function
4.0+ - Tessellation, compute shaders
OpenGL ES:
- Mobile/embedded version
- ES 2.0: basic shaders
- ES 3.0+: advanced features
WebGL:
- JavaScript API based on OpenGL ES
- Runs in web browsers
Vulkan:
- Low-level successor to OpenGL
- More control, more verbose
Basic OpenGL Program
// C++ OpenGL setup
#include <GL/glew.h>
#include <GLFW/glfw3.h>
int main() {
// Initialize GLFW
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
// Create window
GLFWwindow* window = glfwCreateWindow(800, 600,
"OpenGL", NULL, NULL);
glfwMakeContextCurrent(window);
// Initialize GLEW
glewInit();
// Render loop
while (!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT);
// Draw here
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
Vertex Buffer Objects (VBO)
// Upload vertex data to GPU
float vertices[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
GLuint VBO;
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices),
vertices, GL_STATIC_DRAW);
// Describe vertex layout
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
3 * sizeof(float), (void*)0);
glEnableVertexAttribArray(0);
Shaders in GLSL
// Vertex Shader
#version 330 core
layout (location = 0) in vec3 aPos;
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;
void main() {
gl_Position = projection * view * model
* vec4(aPos, 1.0);
}
// Fragment Shader
#version 330 core
out vec4 FragColor;
uniform vec3 objectColor;
uniform vec3 lightColor;
void main() {
FragColor = vec4(lightColor * objectColor, 1.0);
}
Key OpenGL Functions
State Management:
glEnable(GL_DEPTH_TEST)
glDisable(GL_BLEND)
glClearColor(r, g, b, a)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
Drawing:
glDrawArrays(GL_TRIANGLES, first, count)
glDrawElements(GL_TRIANGLES, count, type, offset)
Textures:
glGenTextures(1, &texture)
glBindTexture(GL_TEXTURE_2D, texture)
glTexImage2D(...)
glTexParameteri(...)
Framebuffer:
glGenFramebuffers(1, &fbo)
glBindFramebuffer(GL_FRAMEBUFFER, fbo)
Modern OpenGL Workflow
Typical rendering loop:
1. Clear buffers
2. Use shader program
3. Set uniforms (MVP matrix, light, color)
4. Bind VAO
5. Bind textures
6. Draw call (glDrawElements)
7. Swap buffers
VAO (Vertex Array Object):
- Stores vertex attribute configuration
- Simplifies setup per draw call
VBO โ stores vertex data on GPU
VAO โ stores how to interpret VBO data
EBO โ stores index data (optional)