OpenGL Shading Language 101
📌 Overview
What is GLSL?
GLSL (OpenGL Shading Language) is a C-like programming language used to write shaders—small programs that run on the GPU. Unlike CPU languages such as C, which process data sequentially, GLSL is designed for parallel execution on thousands of pixels or vertices at once.
This means that instead of writing loops to apply an operation element by element, you can often use built-in vector and matrix types to operate on multiple components simultaneously.
ℹ️ Key Concepts
Vector Types in GLSL
GLSL provides native vector types:
vec2
: 2-component floating-point vectorvec3
: 3-component floating-point vectorvec4
: 4-component floating-point vector
These are heavily used for positions, colors, and directions in graphics.
Example:
vec3 position = vec3(1.0, 2.0, 3.0);
vec4 color = vec4(1.0, 0.0, 0.0, 1.0); // RGBA red
Vector Operations (the big difference from C!)
In C, if you want to add two 3D vectors, you’d typically write:
float a[3] = {1.0, 2.0, 3.0};
float b[3] = {4.0, 5.0, 6.0};
float result[3];
for (int i = 0; i < 3; i++) {
result[i] = a[i] + b[i];
}
In GLSL, the same thing is one line:
vec3 a = vec3(1.0, 2.0, 3.0);
vec3 b = vec3(4.0, 5.0, 6.0);
vec3 result = a + b;
Similarly, you can multiply vectors by scalars or component-wise:
vec3 scaled = a * 2.0; // scale all components
vec3 multiplied = a * b; // multiply component-wise
This implicit element-wise behavior makes shader code very concise.
Swizzling (extra sugar you don’t get in C)
GLSL lets you “swizzle” components:
vec4 color = vec4(0.2, 0.4, 0.6, 1.0);
vec3 rgb = color.rgb; // take first 3 components
vec2 rg = color.rg; // take red and green
vec4 weird = color.zyxw; // reorder components
This is extremely handy for graphics, e.g., extracting or rearranging channels.
Why This Matters in Shaders
Shaders are all about performance and brevity. GPUs are optimized to do vector and matrix math in parallel, so GLSL makes this the default way of thinking:
Transforming vertex positions with a 4×4 matrix? → one line with
mat4 * vec4
.Blending colors? → just add or mix
vec3
values.Normalizing directions? →
normalize(vec3)
.
No loops, no manual indexing, no boilerplate—just math that reads like math.
âś… Key takeaway:
GLSL elevates vector and matrix operations to first-class citizens, so what would be a verbose loop in C becomes a clean, expressive single statement in GLSL. This makes it easier to reason about graphics math and lets the GPU exploit parallelism automatically.