Textures and Samplers

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

A texture is an image the GPU can read quickly and in a particular way: it is stored in a layout the hardware likes, it can be shrunk into a chain of smaller copies (mipmaps), and it is read through a sampler that decides how to blend neighbouring texels. The two objects are separate in Metal: the MTLTexture holds the pixels, the MTLSamplerState holds the reading rules, and any texture can be read with any sampler.

The facts were checked in November 2026. The page documents Metal 4 (26 operating systems and later), the Metal 3 API that coexists with it, MetalKit’s MTKTextureLoader and Metal Shading Language 4.1 (27 operating systems). It runs on iOS, iPadOS, macOS, tvOS and visionOS; compressed format support depends on the GPU family, as noted below. In the Metal Bookshelf running example the book gets its cover, spine and page textures here (the shared PNG files bookshelf-cover.png, bookshelf-spine.png, bookshelf-pages.png and bookshelf-wood.png, shipped with the site next to bookshelf.glb); the step after Buffers and Vertex Descriptors and before Lighting Fundamentals. The general theory is in Textures, Sampling and Mipmaps; the OpenGL version is Textures and Samplers in OpenGL.

Loading a texture with MTKTextureLoader

flowchart TD A{"Where is the image?"} A -- "File or asset catalog" --> B["MTKTextureLoader.newTexture(URL:options:) or newTexture(name:...)"] A -- "In memory as encoded data" --> C["newTexture(data:options:)"] A -- "CGImage or MDLTexture" --> D["newTexture(cgImage:options:) or newTexture(texture:options:)"] A -- "Raw pixels you made" --> E["MTLTextureDescriptor + replace(region:...)"] B --> F["MTLTexture"] C --> F D --> F E --> F

MTKTextureLoader decodes common image formats (such as PNG, JPEG and TIFF) from files, asset catalogs, in-memory data, CGImage and Model I/O textures into an MTLTexture. Each method exists in a throwing synchronous form and an asynchronous form with a completion handler; the newTextures variants load several at once. Loading is the slow part of starting a level, so prefer the asynchronous forms and load while the previous frame renders.

Loading the book textures
import MetalKit

struct BookTextures {
    let cover: MTLTexture
    let spine: MTLTexture
    let pages: MTLTexture
}

func loadBookTextures(device: MTLDevice, bundle: Bundle = .main) throws -> BookTextures {
    let loader = MTKTextureLoader(device: device)
    let options: [MTKTextureLoader.Option: Any] = [
        .SRGB: true,                                           // colour data, decode to linear in the shader
        .generateMipmaps: true,                                // build the whole chain
        .origin: MTKTextureLoader.Origin.bottomLeft,           // see the origin notes below
        .textureUsage: MTLTextureUsage.shaderRead.rawValue,    // read-only: lets Metal optimise
        .textureStorageMode: MTLStorageMode.private.rawValue   // GPU-only
    ]
    func load(_ name: String) throws -> MTLTexture {
        guard let url = bundle.url(forResource: name, withExtension: "png") else {
            throw CocoaError(.fileNoSuchFile)
        }
        let texture = try loader.newTexture(URL: url, options: options)
        texture.label = name
        return texture
    }
    return BookTextures(cover: try load("bookshelf-cover"),
                        spine: try load("bookshelf-spine"),
                        pages: try load("bookshelf-pages"))
}

The options (MTKTextureLoader.Option):

Option Meaning and advice

.SRGB

true stores the data with an sRGB pixel format (for example .rgba8Unorm_srgb), so sampling converts to linear automatically. Use it for base colour and emissive textures. Use false for data textures: normals, roughness, metallic, occlusion, masks. Left unset, the loader decides from the image’s colour space.

.generateMipmaps

true generates the mip chain on the GPU during loading. Without it you get one level.

.allocateMipmaps

true allocates storage for the chain but fills only level 0, for when you generate or upload levels yourself.

.origin

.topLeft, .bottomLeft, .flippedVertically choose whether the image is flipped while loading. Metal’s texture coordinate (0, 0) is the top left, but many authored uv sets (glTF aside) assume bottom-left. Pick one and be consistent with your model data; a flipped image is the sign of a mismatch.

.textureUsage

An MTLTextureUsage raw value: .shaderRead (the default), .shaderWrite, .renderTarget, .pixelFormatView. Declare only what you need.

.textureStorageMode

An MTLStorageMode raw value. .private is best for textures that are never touched by the CPU again; .shared is the default on Apple silicon.

.textureCPUCacheMode

An MTLCPUCacheMode raw value; seldom needed.

.cubeLayout

How cube map faces are arranged in a single source image (for example a vertical strip).

.loadAsArray

Load a multi-image source as an array texture.

Common mistakes: forgetting .SRGB so colours look washed out or too dark, setting .SRGB: true on a normal map and getting bent lighting, and relying on the loader for a texture you will render into: render targets are created from a descriptor with the .renderTarget usage.

Building a texture by hand

When the pixels come from code (a procedural noise, a 1x1 white default texture, a CPU-decoded image), describe the texture with an MTLTextureDescriptor:

import Metal

func makeSolidTexture(device: MTLDevice, color: SIMD4<UInt8>, label: String) -> MTLTexture? {
    let d = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .rgba8Unorm,
                                                     width: 1, height: 1,
                                                     mipmapped: false)
    d.usage = .shaderRead
    d.storageMode = .shared
    guard let texture = device.makeTexture(descriptor: d) else { return nil }
    texture.label = label
    var pixel = color
    texture.replace(region: MTLRegionMake2D(0, 0, 1, 1),
                    mipmapLevel: 0,
                    withBytes: &pixel,
                    bytesPerRow: MemoryLayout<SIMD4<UInt8>>.stride)
    return texture
}

Key descriptor properties:

Property Notes

textureType

.type2D (default), .type2DArray, .type3D, .typeCube, .type2DMultisample, and others.

pixelFormat

See the next section.

width, height, depth, arrayLength

Dimensions in texels.

mipmapLevelCount

1 means no chain. A full chain is floor(log2(max(width, height))) + 1. The convenience initialiser with mipmapped: true sets it for you.

sampleCount

1, or 2, 4, 8 for multisampled render targets.

usage

.shaderRead, .shaderWrite, .renderTarget, .pixelFormatView. Extra flags can disable compression optimisations.

storageMode

.shared, .private, .memoryless (render targets that live only in tile memory), and .managed on Intel Macs (deprecated in the 27 operating systems).

replace(region:mipmapLevel:withBytes:bytesPerRow:) works on shared and managed textures. A private texture is filled by a blit copy from a buffer or another texture, exactly like a private buffer. To generate the mip chain by hand, use the blit encoder:

func generateMipmaps(texture: MTLTexture, commandBuffer: MTLCommandBuffer) {
    guard texture.mipmapLevelCount > 1,
          let blit = commandBuffer.makeBlitCommandEncoder() else { return }
    blit.generateMipmaps(for: texture)
    blit.endEncoding()
}

In Metal 4 the same operation is generateMipmaps(texture:) on MTL4ComputeCommandEncoder.

Pixel formats and sRGB

The pixel format (MTLPixelFormat) fixes the channel count, bit depth and interpretation. The ones you meet daily:

Format Use

.rgba8Unorm, .bgra8Unorm

Linear 8-bit data (normal maps, masks). bgra8Unorm is the layout most drawables use.

.rgba8Unorm_srgb, .bgra8Unorm_srgb

Colour images. Reading converts sRGB to linear; writing to a render target converts linear to sRGB.

.r8Unorm, .rg8Unorm

One- and two-channel data: roughness, height, masks.

.rgba16Float, .rg11b10Float

HDR render targets and environment maps; see Image-Based Lighting and HDR.

.depth32Float, .depth32Float_stencil8

Depth buffers (see Transforms and Camera for reversed-Z).

.astc_4x4_ldr, .astc_4x4_srgb, …​ .astc_12x12_*

ASTC block-compressed: from 8 bits per texel (4x4) down to 0.89 bits per texel (12x12).

.bc1_rgba to .bc7_rgbaUnorm_srgb

BC block-compressed, the desktop formats.

Lighting must happen in linear space, which is why colour textures use the _srgb variants and the drawable is usually bgra8Unorm_srgb: the hardware converts on read and on write, with correct filtering. If a texture file is loaded as plain Unorm, you can view the same memory as sRGB without copying by creating a view: texture.makeTextureView(pixelFormat: .rgba8Unorm_srgb) (the texture needs .pixelFormatView usage). The full background is in Color Spaces, HDR and Tone Mapping.

Mipmaps

A pyramid of nine mip levels from 256 by 256 down to 1 by 1, each half the size of the previous one
Figure 1. A mipmap chain

A textured surface far away covers few pixels, but the GPU would have to average many texels to get each pixel’s colour, which is slow and, when it is skipped, shimmers and aliases. A mipmap chain stores pre-averaged copies at half the size each. At draw time the hardware measures how many texels one pixel covers (the screen-space derivative of the uv, \( \rho \)) and chooses the level

\[ \lambda = \log_2 \rho \]

so that a texel in that level is about one pixel. The chain costs one third more memory and makes both quality and speed better: small levels are cache friendly. Generate the chain for every colour texture that is seen at a distance. Skip it for UI, pixel-art at an exact scale, and textures you only sample at level 0 with read.

Mip levels are selected in the shader by derivatives, so they require the fragment stage (or explicit level(...) or gradient arguments in compute). In MSL you can force or bias the choice:

float4 a = tex.sample(s, uv);                    // automatic level
float4 b = tex.sample(s, uv, level(2.0));        // explicit level, no derivative needed
float4 c = tex.sample(s, uv, bias(-0.5));        // sharper, a little more aliasing

Samplers

Four small swatches comparing nearest, linear, linear with nearest mip, and trilinear filtering with the matching sampler settings
Figure 2. Texture filtering modes

A sampler turns a texture coordinate into a colour. MTLSamplerDescriptor controls it:

Property Values and effect

minFilter, magFilter

.nearest (the closest texel, blocky) or .linear (blend of the 4 nearest texels). magFilter applies when the texture is enlarged, minFilter when it is shrunk.

mipFilter

.notMipmapped (ignore the chain), .nearest (one level) or .linear (blend of two levels: trilinear filtering).

maxAnisotropy

1 to 16. Samples along the stretched footprint of a surface seen at a grazing angle, so floors and shelves stay sharp. Cost grows with the value; 4 to 8 is common.

sAddressMode, tAddressMode, rAddressMode

What happens outside 0 to 1; see the next figure.

borderColor

.transparentBlack, .opaqueBlack or .opaqueWhite, used by .clampToBorderColor.

lodMinClamp, lodMaxClamp

Limit the mip levels that can be chosen; useful for streaming, where only some levels are resident.

normalizedCoordinates

true (default) uses 0 to 1; false uses texel coordinates, for image-processing kernels.

compareFunction

Turns the sampler into a comparison sampler for shadow maps (see Shadows).

supportArgumentBuffers

Set to true when the sampler is encoded into an argument buffer or bound by gpuResourceID in Metal 4.

label

Always set it.

Four swatches showing clampToEdge, repeat, mirrorRepeat and clampToZero address modes around a central texture tile
Figure 3. Address modes
func makeSamplers(device: MTLDevice) -> (colour: MTLSamplerState, ui: MTLSamplerState)? {
    let d = MTLSamplerDescriptor()
    d.minFilter = .linear
    d.magFilter = .linear
    d.mipFilter = .linear           // trilinear
    d.maxAnisotropy = 8
    d.sAddressMode = .repeat
    d.tAddressMode = .repeat
    d.supportArgumentBuffers = true // needed for Metal 4 argument-table binding
    d.label = "Colour: trilinear, repeat, 8x anisotropic"

    let u = MTLSamplerDescriptor()
    u.minFilter = .linear
    u.magFilter = .linear
    u.mipFilter = .notMipmapped
    u.sAddressMode = .clampToEdge
    u.tAddressMode = .clampToEdge
    u.supportArgumentBuffers = true
    u.label = "UI: bilinear, clamp"

    guard let colour = device.makeSamplerState(descriptor: d),
          let ui = device.makeSamplerState(descriptor: u) else { return nil }
    return (colour, ui)
}

Create a handful of samplers at start-up and reuse them; there is no need for one per texture. Setting several filters together is the usual fix for shimmering: trilinear plus anisotropy removes most of it.

Sampling in MSL

#include <metal_stdlib>
using namespace metal;

struct VertexOut { float4 position [[position]]; float3 worldNormal; float2 uv; };

fragment float4 book_fragment(VertexOut in [[stage_in]],
                              texture2d<float> cover [[texture(0)]],
                              sampler          smp   [[sampler(0)]]) {
    float4 base = cover.sample(smp, in.uv);       // sRGB texture: already linear here
    return float4(base.rgb, 1.0);
}

// A sampler can also be a compile-time constant, with no binding needed:
constexpr sampler pointSampler(coord::normalized, filter::nearest, address::clamp_to_edge);

The texture template argument (float) is the type the sample returns after format conversion; use half for 8-bit colour data on Apple GPUs to save registers. Other useful functions: read(uint2 coord) (an unfiltered texel fetch, no sampler), get_width(), get_height(), gather (the four texels of a bilinear footprint) and sample_compare for shadow samplers.

Binding

Metal 3.

func bind(encoder: MTLRenderCommandEncoder, textures: BookTextures, sampler: MTLSamplerState) {
    encoder.setFragmentTexture(textures.cover, index: 0)
    encoder.setFragmentSamplerState(sampler, index: 0)
}

Metal 4. Textures and samplers are bound by their gpuResourceID, written into the argument table:

func bindMetal4(table: MTL4ArgumentTable, encoder: MTL4RenderCommandEncoder,
                textures: BookTextures, sampler: MTLSamplerState) {
    table.setTexture(textures.cover.gpuResourceID, index: 0)
    table.setSamplerState(sampler.gpuResourceID, index: 0)
    encoder.setArgumentTable(table, stages: .fragment)
}

The table needs maxTextureBindCount and maxSamplerStateBindCount large enough (see MTL4ArgumentTableDescriptor), and the texture must be resident through an MTLResidencySet; Metal 4 does not track which resources a draw uses. Both binding styles give the same shader. Dozens of textures at once are the subject of Argument Buffers and Bindless Resources.

Compressed textures

Block-compressed textures stay compressed in memory and in the texture cache, which cuts both footprint and bandwidth by a factor of 4 to 8 compared with RGBA8.

Family Support Notes

ASTC

Apple silicon GPUs (A8 and later, M1 and later), including Apple silicon Macs and Apple Vision Pro

The best choice on Apple platforms: block sizes from 4x4 to 12x12 trade quality for size; _srgb variants for colour; LDR and HDR profiles.

BC (BC1 to BC7)

Macs, including Apple silicon Macs

Use for assets shared with Windows and consoles. Not available on iPhone and iPad GPUs.

PVRTC

Older Apple GPUs

Deprecated in iOS 18 and macOS 15; convert to ASTC.

ETC2, EAC

Apple silicon GPUs

Present for ES-era content; prefer ASTC for new assets.

Compression happens offline, in your asset pipeline, never at load time. Apple’s texturetool command-line utility can write ASTC. The Bookshelf textures ship as PNG so the repository stays small; for a shipped game convert them to ASTC (and, for a cross-platform build, to KTX2 with toktx or ktx create from the KTX tools), then load them with the container support in your engine or with a small reader that creates the texture and uploads each level with replace or a blit.

Performance notes

  • Use the smallest format that holds the data: .r8Unorm for roughness, ASTC for colour, .rg11b10Float for HDR lightmaps.

  • Always declare usage honestly: extra usage flags such as .shaderWrite and .pixelFormatView can prevent the driver from choosing the most efficient layout, so request them only when needed.

  • Make textures private when the CPU is done with them.

  • Texture bandwidth dominates mobile GPUs: mipmaps, compression and half precision samples are the cheapest wins.

  • Do not create textures in the render loop; load while the game is running and use the streaming techniques of Resource Loading and Streaming.

  • Tools: the Metal debugger’s texture viewer shows each level, format and storage mode.

Common mistakes

  • A black texture: not resident (Metal 4), usage missing .shaderRead, or a texture(n) index that does not match the bound slot.

  • Washed-out colours: an sRGB image loaded as linear (or the reverse).

  • Shimmering in the distance: no mipmaps or mipFilter is .notMipmapped.

  • Blurry floors: maxAnisotropy is 1.

  • Atlas bleeding between neighbouring images: mip levels average across the boundary; add padding or use array textures.

  • Upside-down image: an origin mismatch between the loader option and the uv data.

What changed and where the books are outdated

Topic Older teaching Now

Compression

Metal Programming Guide (CLA) ch. 6 lists PVRTC among compressed formats.

PVRTC is deprecated in iOS 18 and macOS 15; use ASTC (or BC on Mac).

Library names

CLA uses Swift 4 and device.newDefaultLibrary().

makeDefaultLibrary() and Swift 6 naming; the sampler and texture APIs themselves are stable.

Binding

setFragmentTexture and setFragmentSamplerState per encoder.

Still valid in Metal 3; Metal 4 binds gpuResourceID values in an argument table and needs residency sets.

Textures in books

Metal by Tutorials (MBT) ch. 8 and CLA ch. 6 and 12 teach loading, mipmaps and samplers.

The concepts still apply; add the sRGB option, anisotropy and ASTC.

Storage

.managed for Mac textures.

Deprecated in the 27 operating systems; use .shared or .private.

See also