graphics3d
cg fundamentals
vectors, matrices, cameras, rasterizing, ray tracing, light, shadows and color, drawn small.
a scene is points and directions. matrices move them in front of a camera, the projection and the divide by w flatten them onto the screen, and then each pixel works out what it sees and how much light reaches it.
- a vertex's trip
- P · V · M · p then ÷ w, then the viewport
- dot product
- |a| |b| cos θ lighting runs on it
- order
- T · R · S scale first, move last
- depth
- 2 × near half the depth buffer is used up before it
- pbr
- D · V · F ggx, smith and schlick, per gltf
- srgb 0.5
- 21% of the light. mix in linear
- reading shader and three.js code
- placing a camera, picking near and far
- choosing a lighting model
- fixing acne, dark mixes and washed-out color
on this page
the ideas under every 3d renderer, from a fragment shader to a game engine: vectors and matrices that move points, a camera that flattens them onto the screen, two ways to fill in the pixels, and how light, shadows and color get worked out. each section has the math as code you can run and a small figure to drag.
vectors + matrices
a vector is a direction with a length: three numbers, x, y and z. a point is written the same way, as an offset from the origin. the difference only shows when something moves them, in the next section.
the dot product multiplies matching parts and adds them up. it also equals the two lengths times the cosine of the angle between them, so for two vectors of length 1 it is the cosine itself: 1 when they point the same way, 0 at 90°, −1 when they’re opposite. lighting runs on it.
the cross product is perpendicular to both, and as long as the area of the parallelogram they span. order matters: b × a points the other way. a triangle with corners p, q and r has the normal (q − p) × (r − p), so the order of its corners decides which side it faces.
type Vec3 = [number, number, number];
const dot = (a: Vec3, b: Vec3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const cross = (a: Vec3, b: Vec3): Vec3 => [
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
];
const length = (a: Vec3) => Math.hypot(a[0], a[1], a[2]);
const normalize = (a: Vec3): Vec3 => {
const n = length(a); // 0 for the zero vector, which has no direction: check before dividing
return [a[0] / n, a[1] / n, a[2] / n];
};
// the angle in radians. Math.acos(dot / lengths) can be handed 1.0000000000000002 and return NaN
const angle = (a: Vec3, b: Vec3) => Math.atan2(length(cross(a, b)), dot(a, b));
dot([3, 1, 0], [1, 2, 0]); // 5
angle([3, 1, 0], [1, 2, 0]); // 0.785..., which is 45°
cross([1, 0, 0], [0, 1, 0]); // [0, 0, 1]: x × y is z
glsl has them built in. reflect wants a normal of length 1:1
float d = dot(a, b);
vec3 n = normalize(cross(q - p, r - p)); // the normal of the triangle p, q, r
vec3 m = reflect(-l, n); // where light from l bounces to, phong's r below
drag a tip, or tab to it and use the arrow keys
- a · b
- 3·1 + 1·2 = 5
- θ, the angle
- 45.0°
- |a| |b| cos θ
- 3.16 · 2.24 · 0.71 = 5.00
- a × b
- (0, 0, 5)
the dot product is positive: they point less than 90° apart. the cross product points out of the screen, since b is counter-clockwise from a. the gray bar is b's shadow on a: a · b / |a| long.
two arrows from the origin on a grid, a in cyan at (3, 1) and b in amber at (1, 2). drag either tip, or tab to it and use the arrow keys, and the readout follows: the dot product, 5 at the start, worked out both ways, the angle, 45 degrees, and the cross product, (0, 0, 5), which points out of the screen while b is counter-clockwise from a. a gray bar marks b's shadow on a, a · b / |a| long.
a matrix is a grid of numbers that maps vectors to vectors. its columns are where the x, y and z axes land, so you can read a matrix by its columns. multiplying two gives one matrix that does both.
glsl stores matrices column by column: a mat4 built from 16 numbers takes them a column at a time, and m[1] is the second column, not the second row.2 uniformMatrix4fv with transpose false expects the same order.3 three.js keeps its elements column by column too, but its set() takes the numbers row by row, the way you’d write them on paper.4
- acos can return NaN. rounding can push dot / lengths a hair past 1. clamp it to −1 and 1, or use the atan2 form above.
- normalize before using a dot product as a cosine. it is only the cosine when both lengths are 1.
transforms
translate, rotate and scale are each a 4 × 4 matrix. the fourth coordinate, w, is what lets one matrix move things: a point has w = 1, so it picks up the translation in the last column, and a direction has w = 0, so it turns and stretches but never moves.
matrices apply right to left. T · R · S scales first, then rotates, then translates. three.js builds every object’s matrix from its position, rotation and scale in that order.4 swap two and you get somewhere else: rotate after translating and the object swings around the origin instead of turning in place.
// 4 × 4 matrices as 16 numbers, column by column, the order webgl and glsl use
const translation = (x, y, z) => [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1];
const scaling = (x, y, z) => [x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1];
const rotationZ = (rad) => {
const c = Math.cos(rad);
const s = Math.sin(rad);
return [c, s, 0, 0, -s, c, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
};
// a · b: one matrix that does b first, then a
const multiply = (a, b) => {
const out = new Array(16).fill(0);
for (let c = 0; c < 4; c++)
for (let r = 0; r < 4; r++)
for (let k = 0; k < 4; k++) out[c * 4 + r] += a[k * 4 + r] * b[c * 4 + k];
return out;
};
// m · (x, y, z, w)
const apply = (m, [x, y, z, w]) =>
[0, 1, 2, 3].map((r) => m[r] * x + m[4 + r] * y + m[8 + r] * z + m[12 + r] * w);
const model = multiply(multiply(translation(3, 0, 0), rotationZ(Math.PI / 2)), scaling(2, 1, 1));
apply(model, [1, 0, 0, 1]); // ≈ [3, 2, 0, 1]: stretched to 2, turned to (0, 2), moved to (3, 2)
apply(model, [1, 0, 0, 0]); // ≈ [0, 2, 0, 0]: a direction turns and stretches but stays put
cyan then moved 3 right: its tip is at (3, 1). amber then turned 90° about the origin, not about itself, so it swung around to (0, 4).
an arrow at the origin with its tip at (1, 0), turned and moved 3 to the right in both orders. cyan is T · R: it turns in place, then moves, so at 90 degrees its tip ends at (3, 1). amber is R · T: it moves first, then the turn swings it around the origin, so its tip ends at (0, 4). buttons step through the start, one step and both steps, and a slider sets the turn from 0 to 180 degrees.
in a vertex shader the whole chain is one line, read from the right: the model matrix places the vertex in the world, the view matrix moves the world in front of the camera, the projection flattens it. three.js splits it into a model-view matrix and a projection matrix, and does the same multiply.5
#version 300 es
uniform mat4 model, view, projection;
uniform mat3 normalMatrix; // transpose(inverse(mat3(model))), worked out once per object
in vec3 position;
in vec3 normal;
out vec3 worldNormal;
void main() {
worldNormal = normalize(normalMatrix * normal);
gl_Position = projection * view * model * vec4(position, 1.0);
}
- normals need the inverse transpose. under an uneven scale, a normal moved like a direction tilts off its surface. the inverse transpose of the model matrix’s upper 3 × 3 keeps it perpendicular. glsl has
inverse()andtranspose(),1 and three.js keeps the result asnormalMatrix.4 - radians.
Math.sin, glsl and three.js rotations take radians. three.js’s camera fov is the one in degrees.4,6
camera + projection
after the model matrix, two more matrices take a vertex to the screen. the view matrix moves the world so the eye sits at the origin, looking down −z, with up along +y.7 the projection matrix squeezes what the camera can see into a box. then the gpu divides x, y and z by w, which gives normalized device coordinates, −1 to 1 on each axis, and maps those to pixels.8
that’s gluPerspective’s matrix. fov is the field of view up and down, aspect is width over height, and near and far are distances in front of the camera.9 its last row copies the distance, −z, into w, and dividing by w is the perspective: the same offset lands half as far from the middle at twice the distance. anything outside −w to w on any axis gets clipped.8
// gluPerspective's matrix, column by column. fov is vertical, in degrees
function perspective(fov, aspect, near, far) {
const f = 1 / Math.tan((fov * Math.PI) / 360);
const nf = near - far;
return [f / aspect, 0, 0, 0, 0, f, 0, 0, 0, 0, (far + near) / nf, -1, 0, 0, (2 * far * near) / nf, 0];
}
// a point already in the camera's frame to a pixel of a width by height picture
function toPixel(p, [x, y, z], width, height) {
const clip = [p[0] * x, p[5] * y, p[10] * z + p[14], -z]; // p · (x, y, z, 1)
const ndc = clip.slice(0, 3).map((c) => c / clip[3]); // the divide by w
return [((ndc[0] + 1) / 2) * width, ((1 - ndc[1]) / 2) * height, ndc[2]]; // y flips: row 0 is the top
}
toPixel(perspective(50, 1.5, 1, 12), [1.5, -0.5, -6.5], 300, 200); // ≈ [199.5, 116.5, 0.85]
from above. the camera looks right
the picture it makes
dashed: eye level, where the ground meets the horizon
| post | w, distance | ndc x | height |
|---|---|---|---|
| cyan | 4.0 | −0.43 | 27% |
| amber | 6.5 | 0.33 | 16% |
50° tall is 69.9° wide at this aspect, and f = 1 / tan(25.0°) = 2.14. the cyan post: ndc x = (f / aspect) · x / w = 1.43 · (−1.2) / 4.0 = −0.43.
a camera at eye height and two posts on the ground, seen from above on one side and as the picture the camera makes on the other. the cyan post starts 4 in front and the amber one 6.5, and a table gives each one's w, its ndc x after the divide, and its height in the picture: the nearer post is taller and wider by the same 1 / w. a slider sets the field of view from 20 to 120 degrees, starting at 50, three.js's default, which is 69.9 degrees across at this 3:2 aspect. drag a post, or tab to it and use the arrow keys.
depth isn’t spread evenly. ndc z goes as 1 / distance, so the depth buffer spends most of its values close to the camera. with near 0.1 and far 100, half of them are used up by 0.2 in front, and everything past 10 shares the last 0.9%. near is what matters: move it out to 1 and the halfway point moves to 1.98, while pulling far in to 50 barely changes it. the halfway point always sits within 2 × near. gluPerspective’s notes put it as about log₂(far / near) bits of depth precision lost, and say near must never be 0.9
three.js’s PerspectiveCamera takes the same four numbers and defaults to a fov of 50, an aspect of 1, near 0.1 and far 2000.6
const camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100);
camera.position.set(0, 1, 5);
camera.lookAt(0, 0, 0);
// after a resize, or any change to fov, aspect, near or far
camera.aspect = width / height;
camera.updateProjectionMatrix();
- fov is vertical. in gluPerspective and in three.js. the width it covers depends on the aspect: 50° tall is 69.9° wide at 3:2. an aspect that doesn’t match the canvas stretches the picture.9
- z-fighting is mostly about near. two surfaces close together flicker when the depth buffer can’t tell them apart. push near out as far as the scene allows.
- the camera looks down −z. a point in front of it has a negative z in view space, and w is −z, so a point behind it gets a negative w and is clipped.
rasterization vs ray tracing
two ways to find what each pixel shows. rasterization starts from the triangles: for each one, find the pixels it covers. ray tracing starts from the pixels: for each one, send a ray into the scene and find the first thing it hits. gpus are built to rasterize. ray tracing costs more per pixel, but follows light where rasterizing can’t, to reflections, refractions and shadows.
for a triangle, an edge function says which side of an edge a point is on: zero on the line, positive on one side, negative on the other. it is linear, so one pixel to the right adds a constant, which is how hardware steps it.10
a pixel is drawn when its center is inside all three edges. a center exactly on an edge needs a tie-breaker. opengl only asks that exactly one of two triangles sharing the edge draws it,11 and direct3d’s top-left rule spells one out: a center on a top or a left edge is in, so a shared edge is drawn once.12
// zero on the line a → b. at the third corner it is twice the triangle's signed area
const edge = (a, b, p) => (p.x - a.x) * (b.y - a.y) - (p.y - a.y) * (b.x - a.x);
function rasterize([a, b, c], plot) {
if (edge(a, b, c) < 0) [b, c] = [c, b]; // wind it so the inside is positive
const area = edge(a, b, c);
const xs = [a.x, b.x, c.x];
const ys = [a.y, b.y, c.y];
// the pixels whose centers can be inside: the bounding box
for (let y = Math.ceil(Math.min(...ys) - 0.5); y <= Math.floor(Math.max(...ys) - 0.5); y++)
for (let x = Math.ceil(Math.min(...xs) - 0.5); x <= Math.floor(Math.max(...xs) - 0.5); x++) {
const p = { x: x + 0.5, y: y + 0.5 }; // the pixel's center
const w = [edge(b, c, p), edge(c, a, p), edge(a, b, p)];
// a center exactly on an edge (a 0) is left out here. the top-left rule decides those
if (w.every((e) => e > 0)) plot(x, y, w.map((e) => e / area)); // the corners' weights
}
}
the three edge values over twice the area are the pixel’s barycentric weights. they blend whatever the corners carry: colors, normals, texture coordinates. after a perspective projection the gpu divides each corner’s value by its w before blending, so textures don’t slide, and blends depth without that divide.11 a depth buffer then keeps the nearest surface at each pixel.
ray tracing needs one test per kind of shape. for a sphere it is a quadratic:
// the nearest t past tMin where origin + t · dir is on the sphere, or null. dir has length 1
function hitSphere(origin, dir, center, radius, tMin = 1e-4) {
const oc = origin.map((v, i) => v - center[i]);
const b = oc[0] * dir[0] + oc[1] * dir[1] + oc[2] * dir[2];
const c = oc[0] * oc[0] + oc[1] * oc[1] + oc[2] * oc[2] - radius * radius;
const disc = b * b - c; // t² + 2bt + c = 0
if (disc < 0) return null;
const root = Math.sqrt(disc);
if (-b - root > tMin) return -b - root; // the near side
if (-b + root > tMin) return -b + root; // the far side, for a ray that starts inside
return null;
}
hitSphere([0, 0, 0], [0, 0, -1], [0, 0, -5], 1); // 4
whitted’s 1980 paper made it recursive. at each hit, more rays go out toward the lights, for shadows, and along the reflected and refracted directions, so each pixel gets a tree of rays.13
pixel (7, 5): edges 30, 44, 25, all positive: inside. over twice the area, 99, they are the weights 0.30, 0.44, 0.25.
inside so far: 39. pixels tested: 54 of 120, the box around the triangle
one 16 by 12 grid of pixels, filled two ways and stepped a pixel at a time. rasterize loops over the 120 pixels in the triangle's bounding box and tests each center against the three edges: 54 are inside, and the readout gives the edge values and the barycentric weights. trace sends one ray through each of the 192 pixels at a sphere: 68 hit, shaded by lambert's n · l. it opens part way through either loop, at pixel (7, 5), and a stepper steps, plays or scrubs it.
- start rays off the surface. a ray leaving a surface can hit that same surface again at t ≈ 0, from rounding, and the surface speckles with false shadows. start it a hair along, the
tMinabove. - interpolate with the divide by w. blending texture coordinates straight across the screen warps textures on anything seen at an angle. the gpu does it right for you; a hand-written rasterizer has to.
lighting models (lambert, phong, pbr)
a lighting model answers one question per pixel. given the normal n, the direction to the light l and the direction to the viewer v, all of length 1, how much light leaves toward the viewer?
lambert. a matte surface sends light out equally in every direction, and the light it gets goes with the cosine of the angle between n and l.14 so it is , and the viewer doesn’t matter.
phong. phong’s 1975 model adds a highlight: the cosine of the angle between the light’s mirror direction r and the viewer, raised to a power. the bigger the power, the smaller and sharper the highlight. he used powers from 1 to 10 and called the numbers empirical. the same paper also interpolates the normal across each polygon, which is what makes highlights look smooth on a faceted mesh.15
blinn-phong. blinn’s 1977 version measures the highlight with h, the direction halfway between l and v: the way a mirror would have to face to send the light into the eye. it takes the cosine between n and h to a power, typically 50 or 60, and with the light and the eye far away, h only changes when the light moves.14 for the same highlight it needs about 4 times phong’s power, since the angle from n to h is about half the angle from r to v.
pbr. physically based models treat a surface as countless tiny mirrors, microfacets. cook and torrance’s model multiplies three things: d, how many facets face h; g, how many are neither shadowed nor hidden by their neighbors; and f, fresnel, how much a facet reflects at that angle.16 the gltf 2.0 spec writes down a version many renderers share: ggx for d, a smith visibility term v that folds g together with the rest of the denominator, and schlick’s approximation for f.17
α is the roughness squared, which makes the roughness slider feel even.17 ggx is the trowbridge-reitz distribution. blinn’s 1977 paper already offered it, and walter and others found it again in 2007 and called it ggx. its tails are longer than those of the beckmann distribution cook and torrance used, and that matches many real surfaces.14,18,17 schlick’s fresnel is one line where the full equations take many: f0 is what the surface reflects head on, rising toward 1 at grazing angles.19 for non-metals gltf fixes f0 at 0.04, an index of refraction of 1.5. for metals, f0 is the base color and there is no diffuse part.17 unreal engine 4 moved to the same pieces in 2013, ggx, a smith-style g and schlick’s fresnel, and found ggx cost little more than blinn-phong.20
// n, l, v have length 1. each returns light toward the viewer, in linear light, for a light of strength 1
float lambert(vec3 n, vec3 l) {
return max(dot(n, l), 0.0);
}
float blinnPhong(vec3 n, vec3 l, vec3 v, float shininess) {
vec3 h = normalize(l + v);
return dot(n, l) > 0.0 ? pow(max(dot(n, h), 0.0), shininess) : 0.0;
}
// the gltf 2.0 dielectric: ggx, height-correlated smith, schlick with f0 = 0.04
vec3 pbr(vec3 n, vec3 l, vec3 v, vec3 albedo, float roughness) {
float nl = max(dot(n, l), 0.0);
float nv = max(dot(n, v), 1e-4);
vec3 h = normalize(l + v);
float nh = max(dot(n, h), 0.0);
float vh = max(dot(v, h), 0.0);
float a = max(roughness * roughness, 1e-3); // α = 0 is a perfect mirror, which this form can't evaluate
float a2 = a * a;
float d = nh * nh * (a2 - 1.0) + 1.0;
float D = a2 / (3.14159265 * d * d);
float V = 0.5 / (nl * sqrt(nv * nv * (1.0 - a2) + a2) + nv * sqrt(nl * nl * (1.0 - a2) + a2));
float F = 0.04 + 0.96 * pow(1.0 - vh, 5.0);
return ((1.0 - F) * albedo / 3.14159265 + F * D * V) * nl;
}
the ring is the light: drag on the sphere, or focus it and use the arrow keys
lambert + 0.5 · max(n · h, 0)^shininess
shininess 32: the angle from n to h is about half the angle from r to v, so the same exponent spreads wider than phong's.
a gray sphere shaded pixel by pixel on a canvas, lit from up and to the left. buttons switch between lambert, phong, blinn-phong and pbr with ggx. a slider sets the shininess, in powers of 2 from 1 to 256, for phong and blinn-phong, or the roughness, 0.05 to 1, for pbr. drag on the sphere, or focus it and use the arrow keys, to move the light. the readout gives the formula, and for phong how far off the mirror direction the highlight dims to half: 11.9 degrees at a shininess of 32.
- normalize after interpolating. a normal blended between corners comes out shorter than 1, and the highlight dims and smears.
- l points from the surface to the light, not the way the light travels. flip it and the lit side goes dark.
- light in linear, then encode once. the next section.
shadows
a point is in shadow when something sits between it and the light. a ray tracer asks directly: send a ray toward the light and see if it hits anything. a rasterizer uses a shadow map, williams’s 1978 trick. render the scene once from the light, keeping only depth: how far the light gets before it hits something. then move each point the camera sees into the light’s view and compare. if it is farther from the light than the stored depth, something nearer is in the way. it costs about twice as much as rendering the scene without shadows.21
uniform sampler2D shadowMap; // depth from the light's view, 0 to 1
uniform mat4 lightViewProjection;
uniform float bias;
// 1.0 if the light reaches a point in the world, 0.0 if something nearer is in the way
float lit(vec3 worldPos) {
vec4 p = lightViewProjection * vec4(worldPos, 1.0);
vec3 q = p.xyz / p.w * 0.5 + 0.5; // ndc to 0..1: a texture coordinate and a depth
float stored = texture(shadowMap, q.xy).r; // the nearest thing the light hit there
return q.z - bias > stored ? 0.0 : 1.0;
}
two things go wrong. the map keeps one depth per texel, and a surface tilted to the light changes depth across a texel, so part of every texel ends up behind its own stored value and shadows itself: speckles and moiré on lit surfaces, called shadow acne.22 williams already subtracted a bias to stop it.21 too much bias lets light through where it shouldn’t: shadows come loose from the things that cast them, called peter panning.22 in the figure, the low ledge’s shadow goes first, since the gap between it and the ground is small.
the bias acne needs is at most the change in depth across half a texel, so a sharper map needs less. in the figure’s scene that is 0.36 at 8 texels, 0.18 at 16 and 0.09 at 32. engines also scale the bias with the surface’s slope to the light, and soften the edges by filtering several texels, percentage closer filtering.22
- acne
- 18
- lit ground shadowed by its own texel. it clears at a bias of 0.14
- leaks
- 0
- shadow read as lit, from too much bias. the ledge's shadow leaks from 0.54
- edges
- 2
- within a texel of a shadow's edge, where the texel saw the other side
a side view of a shadow map. a light from the upper left, a tall box and a low ledge on the ground. the light's view is a row of texels, each with a cyan ray to the first thing it hits. each point along the ground is a bar, amber where the map says lit and gray where it says shadowed, with a red dot under a wrong one. a bar under the ground marks where the shadows really are. buttons pick 8, 16, 32 or 64 texels and a slider sets the bias from 0 to 0.6. it opens at 16 texels and no bias, with 18 points of acne. the acne clears at a bias of 0.14, and past 0.54 the ledge's shadow starts to leak.
three.js does all of this behind a few switches: renderer.shadowMap.enabled, castShadow on the light and the objects, receiveShadow on the ground. all are off by default, and light.shadow starts with a bias and a normalBias of 0 and a 512 × 512 map.23
renderer.shadowMap.enabled = true;
light.castShadow = true;
light.shadow.mapSize.set(1024, 1024);
light.shadow.bias = -0.0005; // three.js adds it to the depth, so negative is toward the light. tune it by eye
box.castShadow = true;
ground.receiveShadow = true;
- tune the bias on a surface almost edge-on to the light. that is where acne shows first, and where too much bias shows too.
- fit the light’s view to the scene. the map’s texels spread over everything the light’s projection covers. a tight box, with tight near and far planes, gives sharper shadows and less peter panning.22
color spaces + gamma
an 8-bit color channel doesn’t store light. srgb stores it on a curve that spends more of the 256 codes on the darks: the darkest 10% of the light gets 35% of the range. so a stored 0.5 is about 21% of white’s light, and half of white’s light is stored as 0.735: 188 of 255, #bcbcbc.24
light adds: two lamps on a wall give the sum of their light. so lighting, blending and blurring belong in linear light. decode a color when you read it, do the math, and encode once at the end. mixing the stored values instead comes out too dark in the middle. halfway from red to green is #808000 mixed as stored values, 20% of white’s light, against #bcbc00 mixed as light, 47%.25
// the srgb transfer function from css color 4, one channel at a time. c is 0 to 1
vec3 toLinear(vec3 c) {
return mix(pow((c + 0.055) / 1.055, vec3(2.4)), c / 12.92, step(c, vec3(0.04045)));
}
vec3 toSrgb(vec3 c) {
return mix(1.055 * pow(c, vec3(1.0 / 2.4)) - 0.055, c * 12.92, step(c, vec3(0.0031308)));
}
css mixes hex, named and rgb() colors as stored srgb values by default, for compatibility, though the spec itself says that gives overly dark or grayish mixes, and names srgb-linear as the space for mixing lights. a gradient can ask for it, in chrome 111, firefox 127 and safari 16.2 and later:26
.stored {
background: linear-gradient(to right, red, lime); /* mixed as stored values */
}
.light {
background: linear-gradient(to right in srgb-linear, red, lime); /* mixed as light */
}
mixed as stored values: what css does with hex colors
#808080 gives 22% of white's light
mixed as light, then stored
#bcbcbc gives 50% of white's light
one channel on its way from 0 to 1, 50% along. the cyan strip stores 128 of 255, which is 22% of the light. the amber strip has 50% of the light, stored as 188 of 255. dashed: a straight line, if stored values were light.
two strips between the same two colors, black to white, red to green or blue to yellow. the cyan one mixes the stored srgb values, the way css mixes hex colors, the amber one mixes the light and then stores it. a slider moves a marker along both and reads each one's hex color and its share of white's light: halfway from black to white, #808080, 128 of 255, gives 22%, and #bcbcbc, 188 of 255, gives 50%. below, the srgb curve from stored value to light, with both strips' points on it at the slider, and a dashed straight line for comparison.
webgl 2 can do both steps in hardware. a texture stored as SRGB8_ALPHA8 is decoded to linear when it is sampled, and a framebuffer with srgb encoding re-encodes after blending.27 three.js works in linear srgb, and encodes to renderer.outputColorSpace, srgb by default, at the end of its shaders. a texture’s colorSpace starts as NoColorSpace. set it to SRGBColorSpace for color images, and leave it for data like normal and roughness maps.28
- encode once. encoding twice washes the picture out to gray. never encoding leaves it too dark and too contrasty.
- data textures aren’t colors. normals, roughness, depth: decoding them as srgb bends the numbers.
pitfalls
- degrees and radians.
Math.sin, glsl and three.js rotations use radians. three.js’s camera fov is in degrees.4,6 - which way y goes. gl’s window coordinates start at the bottom left of the viewport.8 a canvas, the dom and most image files start at the top left.
- which way depth goes. webgl’s ndc z runs from −1 at near to 1 at far. three.js builds a 0 to 1 version of the same matrix for webgpu.6
- the zero vector. normalizing it divides by 0 and gives NaN, which then spreads to everything it touches.
- exact ties. a center on an edge, a ray starting on a surface, a depth equal to the stored one: each needs a rule, the top-left rule,
tMin, the bias.
sources
-
the opengl es shading language 3.00 spec (opens in a new tab), section 8.5 for
dot,cross,length,normalizeandreflect, which computes i − 2 (n · i) n and needs n normalized, and section 8.6 fortransposeandinverse. ↩ ↩2 -
the opengl es shading language 3.00 spec (opens in a new tab), section 4.1.6: the first number in a matrix type is its columns, and constructors fill it in column-major order. section 5.6: one subscript picks a column, so
m[1]is the second column. ↩ -
the opengl es 3.0.6 spec (opens in a new tab), section 2.12.6.1: with
transposefalse,UniformMatrix4fvtakes the matrix in column-major order. the webgl 2.0 spec (opens in a new tab) describes an api that conforms closely to opengl es 3.0. ↩ -
three.js r186: Matrix4.js (opens in a new tab), where
set()takes its arguments in row-major order,elementsis column-major, andcompose()builds the matrix from position, rotation and scale; Object3D.js (opens in a new tab), whoseupdateMatrix()callscompose(); Matrix3.js (opens in a new tab), wheregetNormalMatrix()is the inverse transpose of the upper 3 × 3; and Euler.js (opens in a new tab), whose angles are in radians. ↩ ↩2 ↩3 ↩4 ↩5 -
three.js r186, the project_vertex (opens in a new tab) shader chunk:
modelViewMatrixtimes the position, thenprojectionMatrixtimes that, intogl_Position. ↩ -
three.js r186: PerspectiveCamera.js (opens in a new tab), whose constructor defaults to a fov of 50, an aspect of 1, near 0.1 and far 2000, with fov the vertical angle in degrees, and whose
updateProjectionMatrix()must be called after any change; andmakePerspective()in Matrix4.js (opens in a new tab), with one depth mapping for webgl and one for webgpu that runs from 0 to 1. ↩ ↩2 ↩3 ↩4 -
the gluLookAt (opens in a new tab) reference page: the view matrix maps the eye to the origin and the point looked at onto the negative z axis, with up mapped to positive y. ↩
-
the opengl es 3.0.6 spec (opens in a new tab), section 2.13 for the divide by w into normalized device coordinates, 2.13.1 for the viewport, whose x and y give its lower left corner, and 2.18 for the clip volume, −w to w on each axis. ↩ ↩2 ↩3
-
the gluPerspective (opens in a new tab) reference page: fovy is the vertical angle in degrees, the aspect should match the viewport’s, f is the cotangent of fovy / 2, the matrix itself, and the note that about log₂(zFar / zNear) bits of depth precision are lost, so zNear must never be 0. ↩ ↩2 ↩3
-
juan pineda, a parallel algorithm for polygon rasterization (opens in a new tab), siggraph 1988. checked against its abstract on the acm siggraph history archive (opens in a new tab): each edge of a polygon as a linear edge function, above zero on one side and below zero on the other, interpolated by the same kind of hardware that interpolates color and z, and computed for neighboring pixels in parallel. ↩
-
the opengl es 3.0.6 spec (opens in a new tab), section 3.6.1: fragment centers inside the triangle are produced, a center on an edge shared by two triangles is produced by exactly one of them, attributes are blended with barycentric weights divided by each corner’s w (equation 3.7), and depth is blended without that divide (equation 3.8). ↩ ↩2
-
microsoft’s rasterization rules (opens in a new tab) for direct3d: the top-left rule, and what counts as a top, bottom, left and right edge. ↩
-
turner whitted, an improved illumination model for shaded display (opens in a new tab), communications of the acm, june 1980. checked against its abstract on the acm siggraph history archive (opens in a new tab): a tree of rays per pixel, from the viewer to the first surface and from there to other surfaces and to the lights, for reflection, shadows and refraction. ↩
-
james blinn, models of light reflection for computer synthesized pictures (opens in a new tab), siggraph 1977: lambert’s law, the halfway direction h and the cosine between n and h taken to a power, typically 50 or 60, h computed once per light when the light and the eye are far away, and trowbridge and reitz’s facet distribution. ↩ ↩2 ↩3
-
bui tuong phong, illumination for computer generated pictures (opens in a new tab), communications of the acm, june 1975: the normal interpolated along each edge (equation 2), and the shading function with its specular term, a power n of the cosine between the reflected light and the line of sight, with n from 1 to 10, set by eye (equation 3, page 315). ↩
-
robert cook and kenneth torrance, a reflectance model for computer graphics (opens in a new tab), siggraph 1981, with a longer version in acm transactions on graphics in 1982. checked against its abstract on the acm siggraph history archive (opens in a new tab), which lists beckmann and spizzichino among its references, and against the pbr book’s further reading (opens in a new tab) on reflection models, which calls it a variant of torrance and sparrow’s microfacet model. ↩
-
the gltf 2.0 spec (opens in a new tab), appendix b: the trowbridge-reitz / ggx distribution, the height-correlated smith term folded into a visibility function, schlick’s fresnel, α = roughness², a dielectric with an index of refraction of 1.5, so f0 = 0.04, mixed with a lambertian diffuse by fresnel, metals with f0 taken from the base color, α = 0 kept out of the formula, and the note that walter et al. found ggx fits measured data better than beckmann. ↩ ↩2 ↩3 ↩4
-
bruce walter, stephen marschner, hongsong li and kenneth torrance, microfacet models for refraction through rough surfaces (opens in a new tab), eurographics symposium on rendering 2007. checked against the pbr book’s microfacet section (opens in a new tab): walter and others derived the trowbridge-reitz distribution on their own and called it ggx, and its long tails, longer than beckmann’s, match many real surfaces. ↩
-
christophe schlick, an inexpensive brdf model for physically-based rendering (opens in a new tab), computer graphics forum, 1994, equation 15: fresnel as f + (1 − f)(1 − u)^5, with u the cosine of the angle, checked against the author’s copy, eur2.ps.gz (opens in a new tab). ↩
-
brian karis, real shading in unreal engine 4 (opens in a new tab), siggraph 2013 course notes: lambert for diffuse, ggx for the distribution, worth its small extra cost over blinn-phong, schlick’s g and fresnel, and α = roughness², taken from disney’s model. ↩
-
lance williams, casting curved shadows on curved surfaces (opens in a new tab), siggraph 1978: a z-buffer view from the light, then each point the observer sees moved into it and tested, a bias subtracted so surfaces don’t shadow themselves, and a cost of roughly twice rendering the scene. ↩ ↩2
-
microsoft’s common techniques to improve shadow depth maps (opens in a new tab): shadow acne, peter panning from too large a depth offset, slope-scaled depth bias, tight near and far planes for the light, and percentage closer filtering for softer edges. ↩ ↩2 ↩3 ↩4
-
three.js r186: WebGLShadowMap.js (opens in a new tab), where
enabledstarts false, Object3D.js (opens in a new tab), wherecastShadowandreceiveShadowstart false, LightShadow.js (opens in a new tab), withbiasandnormalBiasat 0 andmapSizeat 512 by 512, and the shadowmap_pars_fragment (opens in a new tab) chunk, which adds the bias to the point’s depth before the compare, so a negative bias moves it toward the light. ↩ -
css color 4 (opens in a new tab), section 10.2: the srgb transfer function, linear up to 0.04045 and a 2.4 power above it. the shares of light are computed from it. ↩
-
the shares of white’s light use the y row of the srgb to xyz matrix in css color 4 (opens in a new tab)’s sample code, section 19: about 0.2126 of red, 0.7152 of green and 0.0722 of blue, in linear light. ↩
-
css color 4 (opens in a new tab), section 13.2: srgb-linear for mixing lights, srgb’s overly dark or grayish mixes, and legacy colors interpolated as gamma-encoded srgb for web compatibility. css images 4 (opens in a new tab), section 3.1, for the color space in
linear-gradient(), and mdn’s linear-gradient() (opens in a new tab) compatibility table for the browser versions. ↩ -
the opengl es 3.0.6 spec (opens in a new tab), section 3.8.16, srgb textures converted to linear as part of filtering, and section 4.1.8, colors converted back to srgb after blending into an srgb framebuffer. ↩
-
three.js r186: ColorManagement.js (opens in a new tab), with linear srgb as the working color space; WebGLRenderer.js (opens in a new tab), with
outputColorSpaceset to srgb; Texture.js (opens in a new tab), withcolorSpacestarting asNoColorSpace; the colorspace_pars_fragment (opens in a new tab) chunk, the transfer function in glsl; and the colorspace_fragment (opens in a new tab) chunk, the last step of a material’s fragment shader, as in meshphysical (opens in a new tab), which converts the color for the output. ↩