Skip to content
Part IA Michaelmas Term

GLSL Basics

What is GLSL?

GLSL (OpenGL Shading Language) is a C-like language for writing shaders:

  • Runs on the GPU
  • Supports vector and matrix operations natively
  • Hardware-optimised for graphics computations

Data Types

Scalar Types

TypeDescription
floatSingle-precision float
doubleDouble-precision float
intSigned integer
uintUnsigned integer
boolBoolean

Vector Types

TypeDescription
vec2, vec3, vec4Float vectors
ivec2, ivec3, ivec4Integer vectors
dvec2, dvec3, dvec4Double vectors

Matrix Types

TypeDescription
mat22×2 float matrix
mat33×3 float matrix
mat44×4 float matrix

Swizzling

Access and rearrange vector components using .xyzw, .rgba, or .stpq:

vec4 colour = vec4(1.0, 0.5, 0.0, 1.0);
vec3 rgb = colour.rgb;    // (1.0, 0.5, 0.0)
vec3 gbr = colour.gbr;    // (0.5, 1.0, 0.0)
vec2 rg = colour.xy;      // (1.0, 0.5)

Swizzling can also set values:

vec4 result = vec4(0.0);
result.rgb = vec3(1.0, 0.5, 0.25);

Storage Qualifiers

QualifierPurpose
inInput to shader (vertex attributes or interpolated)
outOutput from shader
uniformGlobal parameter, constant per draw call
constCompile-time constant
bufferGPU memory buffer (read/write)

Vertex Attributes vs Uniforms

Vertex Attributes

  • Different for each vertex
  • Stored in VBOs
  • Interpolated across triangles
  • Examples: position, normal, texture coordinates

Uniforms

  • Same value for all vertices/fragments in a draw call
  • Set once per object or frame
  • Examples: transformation matrices, light parameters, material properties
uniform mat4 mvp_matrix;
uniform vec3 light_position;
uniform vec3 material_colour;

Built-in Functions

Mathematical

float x = abs(v);       // Absolute value
float y = sqrt(v);     // Square root
float z = pow(v, n);   // Power
float w = sin(theta);  // Trigonometric functions

Vector Operations

float len = length(v);       // Vector magnitude
float d = distance(a, b);    // Distance between points
float dp = dot(a, b);        // Dot product
vec3 cp = cross(a, b);      // Cross product
vec3 n = normalize(v);       // Unit vector

Interpolation

vec3 result = mix(a, b, t);  // Linear interpolation: a*(1-t) + b*t
vec3 s = smoothstep(a, b, x);  // Hermite interpolation

Shader Version

Specify GLSL version at the top of each shader:

#version 330  // OpenGL 3.3
#version 450  // OpenGL 4.5

Summary

  • GLSL provides vector and matrix types with hardware support
  • Swizzling enables flexible component access
  • uniform for global data, in/out for per-vertex/per-fragment data
  • Built-in functions for common graphics operations

Past Paper Questions

2025 Paper 3 Question 4(b)(iii): Explain the main difference between uniform variables and vertex attributes. [2 marks]

2024 Paper 3 Question 4: Write GLSL declarations for a vertex shader that receives position and normal attributes, and applies an MVP matrix uniform.

2023 Paper 3 Question 4: What is swizzling in GLSL? Give an example.