GPU data
Mipmaps and texture sampling
When a pixel shader reads a texture, the GPU does not just fetch one texel. It works out how big the pixel is on the texture, picks a smaller copy of the texture that matches, and blends a few texels together. This page explains each step: why shrinking a texture flickers, how a mip chain fixes it, how mips are made, how the GPU chooses a level, and the filters and wrap modes that a sampler controls. The last part shows how RASM does it.
In short
- When one pixel covers many texels, a single sample picks one of them almost at random. The result flickers and shows patterns: aliasing.
- A mip chain stores the texture again at 1/2, 1/4, 1/8 … of its size, each level filtered from the one above. It costs only 1/3 more memory.
- The GPU measures how fast the texture coordinates change between neighboring pixels (the derivatives) and picks the level λ = log2(texels per pixel).
- Bilinear blends 4 texels inside one level; trilinear also blends two levels; anisotropic takes several samples along a stretched footprint.
- Color mips must be averaged in linear light, not on the stored sRGB values.
- The wrap mode decides what is read outside 0 to 1: repeat, mirror, or clamp.
1The problem: shrinking a texture
A texture is a grid of texels. The screen is a grid of pixels. The two grids almost never match.
Close: magnification
One texel covers several pixels.
Far away: minification
One pixel covers many texels. This is the hard case.
The right color for a pixel is the average of all texels under it. But a far-away pixel may cover hundreds of texels, and averaging hundreds of texels for every pixel is far too slow. The fix is to do the averaging once, ahead of time.
2The mip chain
A mipmap (from the Latin multum in parvo, "much in a small place") is a list of copies of the texture. Level 0 is the original. Each next level is half as wide and half as high, and each of its texels is the average of 2×2 texels of the level above. The chain stops at 1×1.
| Level | Size | Memory (4 bytes per texel) | A pixel at this level covers about |
|---|---|---|---|
| 0 | 1024 × 1024 | 4 MiB | 1 texel of level 0 |
| 1 | 512 × 512 | 1 MiB | 2 × 2 texels of level 0 |
| 2 | 256 × 256 | 256 KiB | 4 × 4 |
| 3 | 128 × 128 | 64 KiB | 8 × 8 |
| … | … | … | … |
| 10 | 1 × 1 | 4 bytes | the whole texture |
| all 11 levels | 5.33 MiB (4 MiB × 4/3) | ||
Sizes that are not a power of two work the same way: each level is the size above divided by 2, rounded down, but never below 1. A 1000 × 600 texture has 10 levels: 1000×600, 500×300, 250×150, 125×75, 62×37, 31×18, 15×9, 7×4, 3×2, 1×1. Rounding down means a level does not cover exactly 2×2 texels at the edges, which a good filter takes into account.
3Making the mips
The filter
The simplest filter is the box filter: each new texel is the plain average of the 2×2 texels above it. It is fast and good enough for many textures. Wider filters look at more texels and give sharper, cleaner results. Each picture shows one row of texels and the weight each texel gets:
Box
2 texels per output (in 1D), equal weights.
Slightly blurry; can keep some aliasing
Tent (triangle)
4 texels per output, more weight in the middle.
Smoother
Mitchell–Netravali, Kaiser, Lanczos
4 to 8 texels per output, with small negative weights at the sides.
Sharper, less aliasing; Lanczos can add faint halos
The source of each level is a second choice:
From the level above
Fast.
Small errors add up
From level 0 directly
Better.
More work for the small levels
Near the edges a wide filter needs texels from outside the image. For a texture that tiles (a brick wall that repeats), it should take them from the opposite edge; otherwise the small levels show a seam.
Color must be averaged in linear light
Color textures are stored in sRGB: the stored number is not proportional to the light (see color spaces). Averaging the stored numbers gives the wrong brightness. Take a 2×2 block of black (0) and white (255) texels:
Average the stored numbers
(0 + 255 + 255 + 0) / 4 = 128. Too dark: far mips go darker.
Decode → average → encode
Decode to linear: 0, 1, 1, 0. Average: 0.5. Encode: 0.735 → 188. The true average.
With the wrong average, a fine black-and-white pattern turns visibly darker as it moves away. With the right one, its brightness stays the same.
Textures that are not plain color
Color (sRGB)
Decode, average, encode (above).
Color with alpha
Weight each color by its alpha before averaging (premultiply), so that invisible texels do not bleed their color into the edges. Alpha itself is linear.
For cut-out foliage, small levels lose coverage and leaves thin out; some tools rescale alpha per level to keep it.
Data (roughness, metalness, occlusion)
Average the stored numbers directly: they are already linear.
Normal maps
Average the vectors, then renormalize; the average of unit vectors is shorter than 1.
Better tools also store the lost length as extra roughness.
Where to make them
Offline, in the asset tool
Store all levels in the file (KTX2, DDS), often block-compressed. Good for shipping games and apps.
None at load time; best filters
CPU, at load
Resize level by level in memory, upload all levels. Good for loading plain PNG and JPEG files.
CPU time per texture
GPU, blit chain
Copy level i into level i+1 with a linear filter, one command per level, a barrier between each. Good for render targets and runtime textures.
Fast; box-like filter only
GPU, compute
One shader makes many levels at once (single-pass downsamplers). Good for many textures per frame and depth pyramids.
Fast; any filter
4How the GPU picks a level
The GPU must know how many texels one pixel covers. It finds out from the neighbors. Pixel shaders always run in blocks of 2×2 pixels (a quad). Every pixel of the quad computes its texture coordinate uv, and the GPU subtracts them: the difference between horizontal neighbors is ∂uv/∂x, between vertical neighbors ∂uv/∂y. These are the derivatives.
The full rule, as the Vulkan and Direct3D specifications give it, for a texture of w × h texels:
ρx = sqrt( (∂u/∂x · w)² + (∂v/∂x · h)² ) texels per pixel, along screen x
ρy = sqrt( (∂u/∂y · w)² + (∂v/∂y · h)² ) texels per pixel, along screen y
λ = log2( max(ρx, ρy) ) + bias
λ = clamp(λ, minLod, maxLod)
λ ≤ 0 magnification: use level 0 with the magnification filter
λ > 0 minification: use level λ with the minification filter
Each step of λ by 1 is one level, because each level halves the size. λ is rarely a whole number; what happens with the fraction is the mip filter (section 5). The bias shifts every choice: a negative bias makes textures sharper (and noisier), a positive one blurrier.
Derivatives can break
The neighbors must run the same code. Inside an if that differs between the 4 pixels of a quad, some neighbors do not compute uv, and the derivative is undefined. A jump in uv also breaks it: at the seam of a texture atlas, or where uv wraps from 0.99 to 0.01, the GPU sees a huge change and picks the smallest level, which shows as a thin line of wrong color. A pixel that a discard killed has left its quad too; a demote keeps it as a helper that still computes uv.
When there are no neighbors
Compute shaders and vertex shaders have no quads, so they have no automatic derivatives. There the shader names the level itself: SampleLevel(uv, lod), or passes its own derivatives: SampleGrad(uv, ddx, ddy). A plain Load(x, y, level) reads one texel with no filter at all.
5Filtering: nearest, bilinear, trilinear
The sample point almost never lands on the center of a texel. The filter decides what to return.
x = 0.3 · 4 − 0.5 = 0.7 between texels 0 and 1, 70% of the way
y = 0.6 · 4 − 0.5 = 1.9 between texels 1 and 2, 90% of the way
(0,1): 0.3 · 0.1 = 0.03 (1,1): 0.7 · 0.1 = 0.07
(0,2): 0.3 · 0.9 = 0.27 (1,2): 0.7 · 0.9 = 0.63
Nearest
Return the texel that holds the point: texel (1, 2) above. Blocky up close, which suits pixel art.
1 read
Bilinear
Blend the 4 texel centers around the point. The weights add up to 1. Smooth, but a level is still chosen for the whole sample, so a visible line appears where λ crosses a whole number.
4 reads
The mip filter adds a second choice: what to do with the fraction of λ. Nearest takes the closer level. Linear samples the two levels around λ and blends them by the fraction. Bilinear inside each level plus linear between levels is called trilinear filtering.
Mip filter: nearest
Takes the closer level. The level jumps, and the jump shows as a line on the surface.
Mip filter: linear
Samples the two levels around λ and blends them by the fraction. No jump, no line.
| Min filter | Mip filter | Common name | Reads | Look |
|---|---|---|---|---|
| nearest | none (level 0 only) | point | 1 | sharp, aliases when far |
| linear | none | bilinear, no mips | 4 | smooth up close, aliases when far |
| nearest | nearest | point, mipmapped | 1 | blocky, no shimmer |
| linear | nearest | bilinear | 4 | smooth, visible lines between levels |
| linear | linear | trilinear | 8 | smooth, no lines |
Try the five rows of the table on a real floor. The picture below computes every pixel the way a GPU does: its uv, the derivatives from its neighbors, λ, then the filter.
6Anisotropic filtering
On a floor seen at a low angle, a pixel's footprint is not a square: it is long and thin. It covers few texels across, but many texels along the view direction. λ uses the longer side, so the whole sample comes from a small, blurry level, even though the short side wanted a sharp one.
The usual rule (from the anisotropic filtering extension that most GPUs follow):
ρmax = max(ρx, ρy) ρmin = min(ρx, ρy)
N = min( ceil(ρmax / ρmin), maxAnisotropy ) number of samples
λ = log2( ρmax / N ) level of each sample
Each of the N samples is itself trilinear, so 16× anisotropy can mean up to 128 texel reads. GPUs are good at this, and they take fewer samples where the footprint is nearly square. The sampler sets maxAnisotropy; 8 or 16 is common.
7Wrap modes
Texture coordinates outside 0 to 1 are allowed. The wrap mode (or address mode) of the sampler decides which texel they read. It also matters inside the range: bilinear filtering at the edge reads one texel beyond it.
8Worked example
A floor uses a 1024 × 1024 texture, trilinear filtering and up to 8× anisotropy. Three pixels at three distances; click through them.
Pixel A: close to the camera
One texel spreads over about 2 × 2 pixels. Mips cannot add detail that the texture does not have. Up close, the only question is how to blend between texels. Bilinear gives smooth gradients; nearest gives visible squares.
Pixel B: in the middle
The pixel is a little bigger than a level 1 texel, so the result is almost all level 1. As the floor moves away, the weight slides smoothly toward level 2: no line where the level changes.
Pixel C: far away, at a grazing angle
Anisotropy keeps the floor sharp across the view, three levels finer than plain trilinear. This is why distant roads and floors look much better with it switched on.
9Pitfalls
- Shimmer and moiré on distant surfaces
- No mips. Make the full chain.
- Black or garbage far away
- Mips allocated but not filled. Fill every level, or limit the view to the levels that exist.
- Mips are never used
- The sampler's maximum level was left at 0 (in Vulkan, the default maxLod is 0). Set it to the number of levels, or "no limit".
- Fine patterns get darker with distance
- sRGB color averaged as stored numbers. Average in linear light.
- Neighbor's colors bleed in at a distance
- An atlas without padding. Pad each tile; stop the chain before tiles merge.
- Random wrong levels, lines at material edges
- A texture sampled inside divergent branches. Sample before the branch, or use an explicit level or derivatives.
- A thin line of the opposite edge's color
- Repeat mode on a non-tiling texture. Clamp to edge.
10In RASM
RASM makes the full mip chain of an image on the CPU, on the worker thread that decodes it, and the main thread uploads all levels at once (texture uploads). A KTX2 file brings its mips (texture compression). Sampling uses six fixed samplers: trilinear with 8× anisotropy, or nearest, each with three wrap modes.
loadTexture's worker (decodeTexture) and a glTF image's job (runImageWork) make the levels; finishTextureLoad copies them. A texture the app fills with one level through RenderContext::fillTexture gets the same filter from buildMipChain, in the caller's thread. A Basis KTX2 file without mips is transcoded to RGBA8 and goes through buildMipChain on the worker.Where RASM follows the textbook, and where it differs
| Part | This page | RASM |
|---|---|---|
| Which textures get mips | any minified texture | TextureUsage::SAMPLED textures in R8G8B8A8_UNORM, R8G8B8A8_SRGB or B8G8R8A8_SRGB get the full chain (VulkanDevice::createTexture), and KTX2 textures the file's levels. Render targets and depth textures have 1 level. |
| Where mips are made | offline, CPU or GPU | Images: CPU, on the worker that decodes them, in buildTextureLevels (src/rhi/mipChain.cpp); an app's one-level RenderContext::fillTexture in its own thread (buildMipChain). KTX2: offline, in the file; a Basis file without them gets RGBA8 mips from buildMipChain on the worker. No GPU blits or compute (why: texture uploads). |
| Filter | box or wider | stb_image_resize2's default for shrinking (Mitchell), each level made from the level above. |
| Linear-light color | section 3 | Yes: _SRGB formats go through stbir_resize_uint8_srgb with STBIR_RGBA, which decodes to linear, weights by alpha, and keeps alpha linear. |
| Data and normal maps | average directly; renormalize normals | UNORM textures use stbir_resize_uint8_linear with STBIR_4CHANNEL: plain averages, no alpha weighting. The levels of a glTF normal texture are renormalized after each resize, so each texel is a unit direction; loadTexture does not know the slot and does not renormalize. |
| Edges of tiling textures | wrap when filtering | The resizer clamps at the edges, also for textures sampled with repeat. Small levels of a tiling texture can show a faint seam. |
| Upload | staging buffer and copy | The staging ring and a GPU copy (GPU memory), or host image copy where it costs the GPU nothing for the format: vkTransitionImageLayout moves the image to the shader-read layout and vkCopyMemoryToImage writes every level from CPU memory (texture uploads). |
| Level choice | λ from derivatives, clamped | The hardware rule. Every sampler has maxLod = VK_LOD_CLAMP_NONE, minimum 0 and no bias, so one sampler serves textures with any number of levels. |
| Filters | nearest to anisotropic | LINEAR_* samplers: linear mag, min and mip filter (trilinear) with 8× anisotropy, capped by the device's limit. NEAREST_*: nearest everything, nearest mip, no anisotropy. |
| Wrap modes | 4 modes, per axis | Repeat, mirrored repeat and clamp to edge; no border. The same mode on every axis. |
| glTF samplers | separate wrap per axis, separate min and mag filters | toSamplerType reads only wrapS (used for both axes) and magFilter (nearest or linear for everything). wrapT and minFilter are ignored. |
| Explicit levels | SampleLevel, Load | The material shaders use Sample with automatic derivatives. The Hi-Z build reads depth with Load, and builds its own depth pyramid with a minimum instead of an average (see occlusion culling). |
The six samplers
SamplerType | Mag / min / mip filter | Wrap | Anisotropy | Used for |
|---|---|---|---|---|
LINEAR_REPEAT | linear / linear / linear | repeat | 8× | the default for material textures |
LINEAR_MIRRORED_REPEAT | linear / linear / linear | mirrored repeat | 8× | glTF textures that ask for it |
LINEAR_CLAMP | linear / linear / linear | clamp to edge | 8× | render target color attachments |
NEAREST_REPEAT | nearest / nearest / nearest | repeat | off | glTF textures with a nearest magFilter |
NEAREST_MIRRORED_REPEAT | nearest / nearest / nearest | mirrored repeat | off | the same, mirrored |
NEAREST_CLAMP | nearest / nearest / nearest | clamp to edge | off | depth textures for occlusion culling |
The sampler is chosen per bindless slot, when the slot is written (see bindless resources).
Where it lives in code
| What | Where |
|---|---|
| Level count, image and view | VulkanDevice::createTexture in src/rhi/vulkan/vulkanDevice.cpp |
| Mip generation | buildTextureLevels in src/rhi/mipChain.cpp, called by decodeTexture and runImageWork on the workers; buildMipChain, called by RenderContext::fillTexture and, for KTX2 without mips, by decodeKtx |
| Upload | RenderContext::fillTexture; VulkanDevice::fillTexture (host copy) or UploadManager::uploadTexture (staging) |
| Sampler objects | VulkanDevice::createSampler in src/rhi/vulkan/vulkanDevice.cpp; rhi::SamplerDesc in src/rhi/device.h |
| The six sampler settings | samplerDesc in src/rhi/renderContext.cpp; SamplerType in include/rasm/render/resource.h |
| glTF sampler mapping | toSamplerType in src/assets/material.cpp |
| When pixels arrive | AssetLoader::Impl::finishTextureLoad in src/assets/texture.cpp; AssetLoader::Impl::loadMaterial in src/assets/material.cpp |
fillTexturemust fill every level thatcreateTextureallocated: the view covers all of them, and an unfilled level is read as garbage at a distance.- A load's worker makes every level, and its count is
getFullMipCount, the texture's:fillTexturerefuses another count. - Color textures (_SRGB) take the sRGB resize path; data textures (_UNORM) take the linear one. The format decides, so a texture must be created with the right one (see color spaces).
- Keep
maxLodatVK_LOD_CLAMP_NONE. A sampler with the Vulkan default of 0 would use level 0 only. - Sample with automatic derivatives only outside branches that differ within a quad.
The resizer clamps at the edges also for tiling textures. Each glTF image gets its mips in a job of its own, so a model's images run on several workers at once.
Further reading
- Lance Williams, Pyramidal Parametrics, SIGGRAPH 1983: the paper that introduced mipmaps.
- The Vulkan specification, chapter "Image Operations": level-of-detail selection, filtering and addressing.
- Tomas Akenine-Möller and others, Real-Time Rendering, 4th edition: the chapter on texturing.
- Don Mitchell and Arun Netravali, Reconstruction Filters in Computer Graphics, SIGGRAPH 1988.