8. Texture Mapping

UV coordinates, filtering, and mipmaps — how flat images wrap onto 3D surfaces

Lighting makes a triangle look three-dimensional, but it's still a single flat color. To make it look like brick, wood, skin, or anything else, we need to paint an image onto its surface. That image is a texture, and the process of mapping it onto geometry is texture mapping.

UV Coordinates

Every vertex in a textured mesh carries a UV coordinate — a 2D position in texture space. By convention:

  • U runs horizontally (0 = left edge, 1 = right edge)
  • V runs vertically (0 = bottom, 1 = top)
(0,1) ──────── (1,1)
  │              │
  │   texture    │
  │   image      │
  │              │
(0,0) ──────── (1,0)

When a triangle is rasterized, the UV coordinates at each vertex are interpolated across the face using barycentric coordinates — exactly the same mechanism from the rasterization article. Each pixel gets a (u, v) pair that tells the renderer where to sample from the texture.

uv(P) = lambda0 * uv0 + lambda1 * uv1 + lambda2 * uv2
Interactive

UV coordinate mapping

Hover over the triangle to see where each pixel samples from the texture.

Texel Lookup

The interpolated UV gives us a position in a continuous [0, 1] range, but the texture is a discrete grid of pixels called texels (texture elements). To get a color, we multiply by the texture dimensions:

tex_x = u * width
tex_y = v * height

This almost never lands exactly on a texel center. What we do with the fractional part is the filtering question.

Nearest-Neighbor Filtering

The simplest approach: round to the nearest texel and use its color.

color = texture[round(tex_x), round(tex_y)]

This is fast and preserves hard edges, but produces a blocky, pixelated look when the texture is magnified — each texel becomes a visible square.

Bilinear Filtering

Instead of picking the nearest texel, sample the four surrounding texels and blend them based on how close the sample point is to each:

tx = floor(tex_x)
ty = floor(tex_y)
fx = tex_x - tx       // fractional x (0 to 1)
fy = tex_y - ty       // fractional y (0 to 1)

top    = lerp(texel(tx, ty+1),   texel(tx+1, ty+1),   fx)
bottom = lerp(texel(tx, ty),     texel(tx+1, ty),     fx)
color  = lerp(bottom, top, fy)

Two horizontal lerps, one vertical — hence "bilinear." The result is smooth and free of blocky artifacts when magnifying, at the cost of slight blurriness.

Magnification vs. Minification

When a texture is magnified (stretched larger than its native resolution), you're sampling fewer texels than there are pixels — filtering smooths the result. When it's minified (shrunk smaller), many texels compete for a single pixel — that's where mipmaps come in.

Interactive

Nearest vs. bilinear filtering

Nearest
Bilinear
Adjust the zoom to see how each filtering mode handles magnification.

Texture Wrapping

What happens when a UV coordinate falls outside the [0, 1] range? The wrapping mode decides:

Repeat — the integer part is discarded, so the texture tiles seamlessly:

u_wrapped = u - floor(u)     // e.g. 2.3 → 0.3

Clamp to edge — values are clamped to [0, 1], stretching the border texels:

u_wrapped = clamp(u, 0, 1)   // e.g. 2.3 → 1.0

Mirrored repeat — the texture flips on each integer boundary:

u_wrapped = 1 - abs(mod(u, 2) - 1)

Repeat is the default in OpenGL and is used for tiling surfaces like floors and walls. Clamp is useful for decals and non-tiling textures where you don't want edge artifacts.

Interactive

Wrapping modes

Repeat tiles the texture. Clamp stretches the border. Mirror flips at each boundary.

Mipmaps

When a textured surface is far from the camera, hundreds of texels might map to a single pixel. Sampling just one of them produces sparkling, shimmering artifacts called aliasing.

Mipmaps (from the Latin multum in parvo — "much in a small space") solve this by pre-computing a chain of downscaled copies of the texture:

Level 0:  512 x 512   (original)
Level 1:  256 x 256   (averaged 2x2 blocks)
Level 2:  128 x 128
Level 3:   64 x 64
  ...
Level 9:    1 x 1

Each level is exactly half the resolution of the previous one. The total extra memory is only 1/3 of the original texture — a geometric series that converges quickly.

Choosing the Mip Level

The renderer estimates how much the texture is being minified at each pixel by computing the rate of change of UV with respect to screen coordinates (the texture gradient):

dU/dx, dU/dy, dV/dx, dV/dy

The maximum rate of change determines which mip level provides roughly a 1:1 texel-to-pixel ratio:

level = log2(max(|dU/dx|, |dU/dy|, |dV/dx|, |dV/dy|) * texture_size)

Trilinear Filtering

Bilinear filtering within a single mip level still produces a visible seam where the level changes. Trilinear filtering samples from the two nearest mip levels and blends between them:

color0 = bilinear_sample(mip_level_floor, u, v)
color1 = bilinear_sample(mip_level_ceil, u, v)
color  = lerp(color0, color1, frac(mip_level))

This eliminates the mip band boundaries and gives a smooth transition from near to far.

Interactive

Mipmap levels

Level 0 (512 x 512). Move the slider to simulate the surface receding.

Perspective-Correct Texture Mapping

There's a subtlety we already encountered in the rasterization article: interpolating UVs linearly in screen space produces incorrect results after perspective projection. Straight lines on the texture appear to bend and swim as the camera moves.

The fix is the same perspective-correct interpolation formula — divide by w before interpolating, then divide again after:

            lambda0 * (u0/w0) + lambda1 * (u1/w1) + lambda2 * (u2/w2)
u_correct = ─────────────────────────────────────────────────────────────
            lambda0 * (1/w0)  + lambda1 * (1/w1)  + lambda2 * (1/w2)

This is one of those things early games famously got wrong — the original PlayStation didn't do perspective-correct texturing, which is why textures on PS1 games have that characteristic wobbly, jittery look. The Nintendo 64, by contrast, did it in hardware from the start.

The PS1 Wobble

The PlayStation 1's GPU interpolated texture coordinates linearly in screen space with no perspective correction. Combined with its lack of a sub-pixel precision, this produced the iconic texture warping that defined an era of 3D games. It wasn't a stylistic choice — it was a hardware limitation.

UV Unwrapping

So far we've hand-assigned UV coordinates to single triangles. For a real 3D model with thousands of faces, generating good UVs is a significant challenge called UV unwrapping — conceptually, cutting the 3D surface open and flattening it onto a 2D sheet.

Think of peeling an orange and pressing the skin flat. The cuts determine where seams appear, and the flattening inevitably introduces some stretching or compression. Good unwrapping minimizes distortion while making efficient use of texture space.

Common approaches:

  • Planar projection — project UVs from a single direction (top-down, front-on). Works for flat surfaces.
  • Cylindrical/spherical projection — wrap UVs around the object. Good for bottles, globes, and other round shapes.
  • Seam-based unwrapping — the artist marks seam edges, and an algorithm flattens each connected region (called a chart or island) while minimizing stretch. This is what tools like Blender's "Smart UV Project" and "Unwrap" do.

The result is a UV atlas — a 2D layout of all the mesh's charts packed into the [0, 1] square. The texture artist then paints directly onto this atlas.

Texture Types

Textures aren't limited to color. The same UV mapping mechanism can deliver any per-pixel data to the shader:

Texture type Stores Used for
Diffuse / Albedo Surface color Base appearance
Normal map Perturbed surface normals Fake geometric detail
Specular / Roughness Shininess per pixel Varying material properties
Height / Displacement Surface elevation Parallax or actual geometry offset
Ambient occlusion Baked shadow data Soft self-shadowing
Emissive Self-illumination Glowing surfaces

A single mesh might sample from half a dozen textures per pixel. Modern engines bundle these into a material with a set of texture slots and a shader that combines them.

Putting It All Together

Here's the complete texture sampling pipeline for one pixel:

1. Rasterize the triangle (barycentric coordinates)
2. Interpolate UVs with perspective correction
3. Apply wrapping mode to bring UVs into range
4. Compute mip level from UV screen-space derivatives
5. Sample the texture:
   - Pick the two nearest mip levels
   - Bilinear filter each
   - Blend between them (trilinear)
6. Use the sampled color in the lighting equation

GPUs do all of this in a single texture() call in the fragment shader — a huge amount of math hidden behind one function.

What's Next

Texture mapping gives surfaces visual richness, but it's all about painting a flat image onto geometry. The next frontier is tracing the actual path of light through a scene — that's ray tracing, where shadows and reflections emerge naturally from the physics of light.