OpenGL Cheatsheet
Shaders (GLSL)
Use this OpenGL reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
Shader Compilation
// 1. Create shader object GLuint vert = glCreateShader(GL_VERTEX_SHADER); // 2. Upload source const char* src = "..."; glShaderSource(vert, 1, &src, nullptr); // nullptr = null-terminated strings // 3. Compile glCompileShader(vert); // 4. Check for errors GLint ok; glGetShaderiv(vert, GL_COMPILE_STATUS, &ok); if (!ok) { char log[1024]; glGetShaderInfoLog(vert, sizeof(log), nullptr, log); fprintf(stderr, "Shader error: %s\n", log); }
Shader types
| Constant | Stage |
|---|---|
GL_VERTEX_SHADER | Vertex |
GL_TESS_CONTROL_SHADER | Tessellation control (GL 4.0+) |
GL_TESS_EVALUATION_SHADER | Tessellation evaluation (GL 4.0+) |
GL_GEOMETRY_SHADER | Geometry |
GL_FRAGMENT_SHADER | Fragment |
GL_COMPUTE_SHADER | Compute (GL 4.3+) |
Program Linking
GLuint prog = glCreateProgram(); glAttachShader(prog, vert); glAttachShader(prog, frag); glLinkProgram(prog); GLint ok; glGetProgramiv(prog, GL_LINK_STATUS, &ok); if (!ok) { char log[1024]; glGetProgramInfoLog(prog, sizeof(log), nullptr, log); } glUseProgram(prog); // Cleanup shader objects after linking glDetachShader(prog, vert); glDeleteShader(vert); glDeleteShader(frag);
GLSL Data Types
Scalar types
| GLSL type | C++ equivalent |
|---|---|
bool | bool |
int | int32_t |
uint | uint32_t |
float | float |
double | double |
Vector types
| GLSL | Components |
|---|---|
vec2 / vec3 / vec4 | float ×2/3/4 |
ivec2 / ivec3 / ivec4 | int ×2/3/4 |
uvec2 / uvec3 / uvec4 | uint ×2/3/4 |
bvec2 / bvec3 / bvec4 | bool ×2/3/4 |
dvec2 / dvec3 / dvec4 | double ×2/3/4 |
Matrix types (column-major)
| GLSL | Dimensions |
|---|---|
mat2 / mat3 / mat4 | 2×2 / 3×3 / 4×4 float |
mat2x3 / mat3x2 … | CxR: matCOLSxROWS |
dmat2 … dmat4 | double matrices |
Uniforms
// Lookup by name (expensive — cache location) GLint loc = glGetUniformLocation(prog, "uModel"); // Set values glUniform1f(loc, 1.0f); glUniform2f(loc, x, y); glUniform3f(loc, x, y, z); glUniform4f(loc, x, y, z, w); glUniform1i(loc, 0); // sampler uniforms take the UNIT index glUniformMatrix4fv(loc, 1, GL_FALSE, glm::value_ptr(mat)); // GL_FALSE = column-major // Integer variants glUniform1iv(loc, count, intArray); glUniform2iv(loc, count, intArray); // ... (same pattern for ui = unsigned int) // DSA (GL 4.1+) — no glUseProgram needed glProgramUniform1f(prog, loc, 1.0f); glProgramUniformMatrix4fv(prog, loc, 1, GL_FALSE, ptr);
Uniform function naming pattern
glUniform{N}{type}[v] where:
- N = 1, 2, 3, or 4 (component count)
- type = f (float), i (int), ui (uint), d (double)
- v = optional; means "takes a pointer to array"
Matrix functions: glUniformMatrix{N}fv or glUniformMatrix{C}x{R}fv.
Uniform Blocks (UBO)
layout(std140, binding = 0) uniform Camera { mat4 view; mat4 proj; vec3 pos; float pad; // explicit padding to 16-byte boundary } uCamera; // Access: uCamera.view
// Explicit binding (GLSL 4.2+): already set by layout(binding=N) // Legacy: query and set block binding GLuint idx = glGetUniformBlockIndex(prog, "Camera"); glUniformBlockBinding(prog, idx, 0); // block "Camera" → binding point 0
Shader Storage Blocks (SSBO, GL 4.3+)
layout(std430, binding = 1) buffer PositionBuffer { vec4 data[]; // unsized array } positions;
GLuint ssboIdx = glGetProgramResourceIndex(prog, GL_SHADER_STORAGE_BLOCK, "PositionBuffer"); glShaderStorageBlockBinding(prog, ssboIdx, 1);
GLSL Built-in Functions
Math
| Function | Description |
|---|---|
abs(x) | Absolute value |
sign(x) | -1, 0, or 1 |
floor(x) / ceil(x) / round(x) | Rounding |
trunc(x) | Truncate to integer |
fract(x) | Fractional part |
mod(x, y) | Modulo |
min(x, y) / max(x, y) | Component-wise min/max |
clamp(x, lo, hi) | Clamp x to [lo, hi] |
mix(a, b, t) | Linear interpolate: a*(1-t) + b*t |
step(edge, x) | 0 if x < edge, else 1 |
smoothstep(lo, hi, x) | Hermite smooth step |
sqrt(x) / inversesqrt(x) | Square root / reciprocal sqrt |
pow(x, y) | x^y |
exp(x) / exp2(x) | e^x / 2^x |
log(x) / log2(x) | Natural log / log base 2 |
Trigonometry
| Function | Description |
|---|---|
sin(x) / cos(x) / tan(x) | Trig (radians) |
asin(x) / acos(x) / atan(y, x) | Inverse trig |
radians(deg) / degrees(rad) | Unit conversion |
sinh(x) / cosh(x) / tanh(x) | Hyperbolic |
Vector/Geometry
| Function | Description |
|---|---|
length(v) | Euclidean length |
distance(a, b) | Distance between points |
dot(a, b) | Dot product |
cross(a, b) | Cross product (vec3 only) |
normalize(v) | Unit vector |
reflect(I, N) | Reflect incident I around normal N |
refract(I, N, eta) | Refract with ratio eta |
faceforward(N, I, Nref) | Flip N to face the eye |
Texture
| Function | Description |
|---|---|
texture(sampler, uv) | Sample with implicit LOD |
textureLod(sampler, uv, lod) | Explicit LOD |
textureGrad(sampler, uv, dPdx, dPdy) | Explicit derivatives |
texelFetch(sampler, ivec, lod) | Fetch single texel (no filtering) |
textureSize(sampler, lod) | Returns ivec of dimensions |
textureOffset(sampler, uv, offset) | Constant texel offset |
textureProjOffset | Projective + offset |
imageLoad(image, coord) | Load from image unit |
imageStore(image, coord, data) | Write to image unit |
imageAtomicAdd(image, coord, val) | Atomic add to image |
Fragment-only derivatives
| Function | Description |
|---|---|
dFdx(p) | Partial derivative in x (screen-space) |
dFdy(p) | Partial derivative in y |
fwidth(p) | abs(dFdx(p)) + abs(dFdy(p)) |
dFdxFine(p) / dFdyFine(p) | Per-pixel derivatives (GL 4.5+) |
dFdxCoarse(p) / dFdyCoarse(p) | 2×2 block derivatives (GL 4.5+) |
Integer / bit operations
| Function | Description |
|---|---|
bitCount(x) | Population count |
findLSB(x) / findMSB(x) | Least/most significant bit |
bitfieldExtract(val, off, bits) | Extract bit field |
bitfieldInsert(base, ins, off, bits) | Insert bit field |
bitfieldReverse(x) | Reverse bits |
Qualifiers
Storage qualifiers
| Qualifier | Used in | Meaning |
|---|---|---|
in | Vertex / Fragment | Input from previous stage / vertex attrib |
out | Any | Output to next stage or framebuffer |
uniform | Any | CPU-supplied value, constant per draw |
buffer | Any | Shader storage block (read-write) |
shared | Compute | Shared within a work group |
const | Any | Compile-time constant |
Interpolation qualifiers (on in/out)
| Qualifier | Behavior |
|---|---|
smooth | Perspective-correct (default) |
noperspective | Linear interpolation |
flat | No interpolation; provoking vertex value used |
centroid | Sample at centroid (reduces aliasing with MSAA) |
sample | Per-sample interpolation |
Precision qualifiers (GLSL ES — also valid in desktop)
| Qualifier | Description |
|---|---|
highp | High precision (≥32-bit float) |
mediump | Medium precision |
lowp | Low precision (≥9-bit) |
Preprocessor
#version 460 core // must be first line; "core" = no deprecated features #extension GL_ARB_bindless_texture : enable #define PI 3.14159265359 #ifdef LIGHTING // conditional block #endif #pragma optimize(off) // driver-specific
Introspection (GL 4.3+)
// List all active uniforms GLint count; glGetProgramiv(prog, GL_ACTIVE_UNIFORMS, &count); for (int i = 0; i < count; i++) { char name[64]; GLsizei len; GLint size; GLenum type; glGetActiveUniform(prog, i, sizeof(name), &len, &size, &type, name); } // Programmatic resource query GLenum props[] = { GL_TYPE, GL_LOCATION, GL_ARRAY_SIZE }; GLint values[3]; GLuint idx = glGetProgramResourceIndex(prog, GL_UNIFORM, "uColor"); glGetProgramResourceiv(prog, GL_UNIFORM, idx, 3, props, 3, nullptr, values);
Binary Shaders / SPIR-V (GL 4.6+)
// Load precompiled SPIR-V glShaderBinary(1, &shader, GL_SHADER_BINARY_FORMAT_SPIR_V, spirvData, sizeBytes); glSpecializeShader(shader, "main", 0, nullptr, nullptr); // entry point // Cache program binary GLsizei len; GLenum format; glGetProgramiv(prog, GL_PROGRAM_BINARY_LENGTH, (GLint*)&len); std::vector<uint8_t> binary(len); glGetProgramBinary(prog, len, nullptr, &format, binary.data()); // Reload glProgramBinary(prog, format, binary.data(), len);