TExcelTAD
Home › Shaders & Graphics Programming › Matrices in Shaders

Matrices in Shaders

A vertex shader's main job is one line: gl_Position = projection * view * model * position. That line takes a vertex from the mesh's own coordinates to clip space, where the rasterizer can find its pixel. Getting the matrices right, in the right order, with the right storage layout, and transforming normals correctly is where most "black screen" and "lighting looks wrong" bugs live. The math itself is covered in Math for Games; this lesson is about how it meets the GPU.

The chain of spaces

Matrix From → to Who sets it
model (modelMatrix, Unity unity_ObjectToWorld, Unreal "Local to World") object space → world space per object
view (viewMatrix) world → camera (view) space per camera; the inverse of the camera's world matrix
projection (projectionMatrix) view → clip space per camera: field of view, aspect, near/far
the GPU's divide by w clip → NDC (-1..1) fixed function
viewport transform NDC → pixels gl.viewport

With column vectors, as GLSL, GLM, Three.js and OpenGL use, the matrix nearest the vector is applied first:

glsl
// GLSL: read right to left. model first, projection last.
gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0);

HLSL code is often written with row vectors (mul(v, M)), and then the order reverses: mul(mul(mul(v, World), View), Proj). Unity's and Unreal's shader libraries hide this behind helpers (TransformObjectToHClip, TransformWorldToClip), but the rule is worth knowing: mul(M, v) treats v as a column vector, mul(v, M) as a row vector, and the two are the same product with a transposed M.

hlsl
float4 clipA = mul(ViewProj, mul(World, float4(pos, 1.0)));   // column-vector style
float4 clipB = mul(mul(float4(pos, 1.0), WorldT), ViewProjT); // row-vector style with transposed matrices

Precompute what you can: multiply projection * view once per camera on the CPU, and projection * view * model once per object if the shader does not need the intermediate spaces. One mat4 * vec4 costs 16 multiply-adds per vertex; three of them cost 48.

Storage order: the 16 numbers

A mat4 is uploaded as 16 floats. GLSL reads them column by column: the first four floats are column 0, the last four are column 3, so a translation (x, y, z) sits at indices 12, 13 and 14. Three.js (Matrix4.elements) and gl-matrix store matrices that way, so their arrays upload directly. If your code builds the array row by row, the GPU sees the transpose. The program below models both readings of the same array:

js · try it yourself
// A 4x4 matrix stored column-major, the way WebGL, GLSL, gl-matrix and Three.js (elements) expect it.
// Element (row r, column c) lives at index c * 4 + r.
function translation(x, y, z) {
  return new Float32Array([1, 0, 0, 0,   0, 1, 0, 0,   0, 0, 1, 0,   x, y, z, 1]);
}

// What GLSL computes for `M * v`: result[r] = sum over c of M[c][r] * v[c]
function mulColumnMajor(m, v) {
  const out = [0, 0, 0, 0];
  for (let r = 0; r < 4; r++) for (let c = 0; c < 4; c++) out[r] += m[c * 4 + r] * v[c];
  return out;
}

// The same 16 numbers read as if they were row-major: this is what happens when one side
// of the code thinks "row-major" and the other "column-major". The matrix is transposed.
function mulRowMajor(m, v) {
  const out = [0, 0, 0, 0];
  for (let r = 0; r < 4; r++) for (let c = 0; c < 4; c++) out[r] += m[r * 4 + c] * v[c];
  return out;
}

const T = translation(5, 6, 7);
const point = [1, 1, 1, 1];          // w = 1: a position, affected by translation
const dir = [1, 1, 1, 0];            // w = 0: a direction, not affected
const fmt = (v) => `(${v.join(', ')})`;
console.log('column-major M * point:', fmt(mulColumnMajor(T, point)));
console.log('column-major M * dir:  ', fmt(mulColumnMajor(T, dir)));
console.log('transposed   M * point:', fmt(mulRowMajor(T, point)));
console.log('transposed   M * dir:  ', fmt(mulRowMajor(T, dir)));
column-major M * point: (6, 7, 8, 1)
column-major M * dir:   (1, 1, 1, 0)
transposed   M * point: (1, 1, 1, 19)
transposed   M * dir:   (1, 1, 1, 18)

The transposed matrix leaves x, y, z alone and pushes the translation into w. After the GPU divides by w = 19, the whole object collapses into a dot near the center of the screen, or vanishes behind the camera if w goes negative. "My mesh is a tiny speck" and "nothing renders" are both classic symptoms.

In WebGL the upload call is gl.uniformMatrix4fv(location, false, array). The middle argument asks the driver to transpose for you, and in WebGL it must be false (WebGL 1 rejects true; WebGL2 accepts it, but then your array must really be row-major). Fix the layout in your math library instead of reaching for the flag.

Note: GLSL has a transpose() function and layout(row_major) for uniform blocks, and HLSL defaults constant buffers to column_major packing (with row_major and the DXC flag -Zpr to change it). Each engine picks one convention and sticks to it; when you write raw API code, you have to make the choice yourself and keep it consistent.

Transforming normals: the normal matrix

Positions and tangents can be transformed by the model matrix. Normals cannot, as soon as the matrix has a non-uniform scale. Squash a sphere vertically and its normals must tilt more upward, not less. The correct matrix for normals is the inverse transpose of the model matrix's upper 3×3, usually called the normal matrix:

js · try it yourself
// A surface tilted 45 degrees: its tangent runs down the slope, its normal points away from it.
const s = Math.SQRT1_2;
const tangent = [s, -s, 0];
const normal = [s, s, 0];
const scale = [2, 0.5, 1];                       // non-uniform scale: the model matrix (diagonal here)

const mul = (a, b) => a.map((x, i) => x * b[i]);
const dot = (a, b) => a.reduce((sum, x, i) => sum + x * b[i], 0);
const normalize = (v) => { const l = Math.hypot(...v); return v.map((x) => x / l); };
const fmt = (v) => `(${v.map((x) => x.toFixed(3)).join(', ')})`;

const t2 = normalize(mul(tangent, scale));                         // tangents use the model matrix
const naive = normalize(mul(normal, scale));                       // WRONG: normal * model matrix
const inverseTranspose = scale.map((k) => 1 / k);                  // for a diagonal matrix: 1/scale
const correct = normalize(mul(normal, inverseTranspose));

console.log('tangent after scaling:', fmt(t2));
console.log('naive normal:  ', fmt(naive), ' dot with tangent =', dot(naive, t2).toFixed(3));
console.log('normal matrix: ', fmt(correct), ' dot with tangent =', dot(correct, t2).toFixed(3));
tangent after scaling: (0.970, -0.243, 0.000)
naive normal:   (0.970, 0.243, 0.000)  dot with tangent = 0.882
normal matrix:  (0.243, 0.970, 0.000)  dot with tangent = 0.000

A normal must stay perpendicular to the surface (dot with any tangent = 0). The naive version breaks that; the inverse transpose keeps it. For rotations and uniform scales the two agree (a rotation's inverse is its transpose), which is why the bug only appears when an artist scales an object unevenly.

In GLSL:

glsl
// In world space. Precompute on the CPU when you can: inverse() per vertex is expensive.
mat3 normalMatrix = transpose(inverse(mat3(modelMatrix)));
vec3 worldNormal = normalize(normalMatrix * normal);

Three.js gives ShaderMaterial a normalMatrix uniform that goes to view space (inverse transpose of modelViewMatrix), so lights must be in view space too when you use it. Mixing a view-space normal with a world-space light direction is a very common bug: the lighting then rotates with the camera.

See the difference

Both spheres below are scaled by (1.6, 0.6, 1.0). The left one transforms normals by the model matrix; the right one by the normal matrix. Both visualize the world-space normal as a color and light from above. On the left the top is too dark and the shading bands are in the wrong place.

html · try it yourself
<style>body { margin: 0; background: #14141c } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x14141c);
const camera = new THREE.PerspectiveCamera(40, innerWidth / innerHeight, 0.1, 50);
camera.position.set(0, 0.6, 6);
camera.lookAt(0, 0, 0);

function makeMaterial(useNormalMatrix) {
  return new THREE.ShaderMaterial({
    defines: useNormalMatrix ? { USE_NORMAL_MATRIX: '' } : {},
    vertexShader: /* glsl */ `
      varying vec3 vWorldNormal;
      void main() {
        mat3 m = mat3(modelMatrix);
        #ifdef USE_NORMAL_MATRIX
          vWorldNormal = transpose(inverse(m)) * normal;     // correct
        #else
          vWorldNormal = m * normal;                         // wrong with non-uniform scale
        #endif
        gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0);
      }`,
    fragmentShader: /* glsl */ `
      varying vec3 vWorldNormal;
      void main() {
        vec3 n = normalize(vWorldNormal);
        float light = max(dot(n, normalize(vec3(0.2, 1.0, 0.4))), 0.0);
        vec3 tint = n * 0.5 + 0.5;
        gl_FragColor = vec4(tint * (0.15 + 0.85 * light), 1.0);
      }`,
  });
}

const geometry = new THREE.SphereGeometry(1, 64, 32);
const left = new THREE.Mesh(geometry, makeMaterial(false));
const right = new THREE.Mesh(geometry, makeMaterial(true));
for (const [mesh, x] of [[left, -1.7], [right, 1.7]]) {
  mesh.scale.set(1.6, 0.6, 1.0);
  mesh.position.x = x;
  scene.add(mesh);
}
renderer.setAnimationLoop((ms) => {
  left.rotation.z = right.rotation.z = Math.sin(ms / 1500) * 0.4;
  renderer.render(scene, camera);
});
</script>

Here inverse() runs per vertex to keep the example short. In a real renderer, compute the normal matrix once per object on the CPU (new THREE.Matrix3().getNormalMatrix(mesh.matrixWorld) in Three.js) and pass it as a uniform.

Checklist when the picture is wrong

  1. Is the order P * V * M * v (column vectors) or v * M * V * P (row vectors), never a mix?
  2. Is the array column-major, uploaded with transpose = false?
  3. Is the position's w equal to 1 (positions) and a direction's w equal to 0?
  4. Are normals transformed by the normal matrix, and are normal and light in the same space?
  5. Does the projection match the API's depth range (OpenGL/WebGL -1..1, Vulkan/D3D/Metal/WebGPU 0..1)?

Test yourself

In GLSL with column vectors, which matrix is applied first in P * V * M * v?

  1. P
  2. V
  3. M
  4. They are applied simultaneously

A mesh renders as a tiny dot after you upload a translation matrix built row by row. What is the likely cause?

  1. The near plane is too far
  2. The matrix arrived transposed, so the translation ended up in w
  3. The normal matrix is missing
  4. Depth testing is off

Why are normals transformed by the inverse transpose of the model matrix?

  1. It is faster
  2. It keeps normals perpendicular to the surface under non-uniform scale
  3. Normals are stored in clip space
  4. GLSL requires it for all vectors