Skip to main content

Textures and sampling

Choose a texture's dimensions, format, and usage before allocating it. An image sampled by a fragment shader, an offscreen render target, and an array of data values can all use textures, but they have different format and filtering requirements. Check the texture format reference and device capabilities when selecting a format.

Allocate and upload​

Use a sampled texture for shader reads. Add render attachment usage if a pass will write into it. Recreate a size-dependent texture when its dimensions change. See Commands, passes, and presentation for a framebuffer example.

To upload an ImageBitmap for sampling, allocate a texture with the dimensions of the bitmap and copy its pixels.

import {Texture} from '@luma.gl/core/api';

const texture = device.createTexture({
width: bitmap.width,
height: bitmap.height,
format: 'rgba8unorm',
usage: Texture.SAMPLE | Texture.COPY_DST | Texture.RENDER
});
texture.copyExternalImage({image: bitmap});

Choose a transfer method based on where the pixels live.

MethodDescription
Texture.writeData()Writes typed-array data into a texture subresource, including mip levels, array layers, depth slices, and optional row layout.
Texture.readDataAsync()Deprecated convenience wrapper. Prefer Texture.readBuffer() or DynamicTexture.readAsync().
Texture.writeBuffer()Copies data from a GPU buffer into a texture subresource using the provided destination region and layout.
Texture.readBuffer()Copies texture data into a caller-supplied GPU buffer. The source texture must support Texture.COPY_SRC.

Texture.copyImageData() remains available for compatibility, but it is a deprecated wrapper over Texture.writeData().

Choosing a texture upload method​

Use the texture write method that matches your source data:

  • copyExternalImage():
    • for browser image-like sources such as ImageBitmap, ImageData, canvases, videos, and images
  • VideoTexture:
  • HTML-in-Canvas:
    • for experimental DOM subtree rasterization into Canvas, WebGL, or WebGPU texture paths
  • writeData():
    • for CPU-side typed-array or ArrayBuffer uploads
  • writeBuffer():
    • for uploads sourced from a GPU buffer

writeData() and writeBuffer() use the same destination model:

  • mipLevel selects which mip to update
  • x, y, z select the origin inside that mip
  • width, height, depthOrArrayLayers define the written extent
  • byteOffset, bytesPerRow, rowsPerImage describe the source memory layout

This means the difference between writeData() and writeBuffer() is the source, not the shape of the update.

For readback, readBuffer() is similarly explicit: the destination buffer is caller-owned, and the texture being read must have been created with Texture.COPY_SRC.

Texture upload semantics​

For non-2D textures, z is interpreted by texture dimension:

  • cube: cube face index
  • 2d-array: array layer index
  • 3d: depth slice index

If you omit layout fields for writeData(), luma.gl computes a tightly packed layout for the write region you requested. For example, when writing a lower mip, row stride defaults are computed from that mip's width, not from the base level width.

Provide explicit layout fields when:

  • your rows are padded
  • multiple layers or slices are packed into the same source allocation
  • the source data begins after a nonzero byte offset

Row alignment​

When copying between buffers and textures on WebGPU, explicit row strides may need padding to 256-byte boundaries. Keep the logical image width separate from the padded buffer stride. Check the upload method's layout requirements before reusing a buffer prepared for another backend.

Sampling​

A primary purpose of textures is to allow the GPU to read from them.

vec4 texel = sampler2D(texture)

Filtering​

Texture formats that are filterable which means that during sampling texel values can be interpolated by the GPU for better results.

Texture filtering solves texture minification and magnification aliasing. It is separate from polygon coverage antialiasing; see Antialiasing and Multisampling for how the techniques fit together. Sampling is a highly configuratble process that is specified using by binding a separate Sampler object for each texture.

Sampling can be specified separately for

  • magnification
  • minification

The parameters used for sampling is specified in a sampler object.

Notes:

  • Not all texture formats are filterable. For less common texture formats it is possible to query the device to determine if filtering is supported.
  • Filtering with transparent textures can result in undesirable artifacts (darkening and false color halos) unless you work in premultiplied colors.

Mipmaps​

To improve sampling quality further when sampling from a distance (minFilter), mipmap filtering can be used. Mipmaps are a pyramid of lower resolution images that are stored for each texture image and used by the GPU when the texture is sampled at a distance.

Using mipmap filtering requires some extra setup. The texture being sampled must be created with the mipLevels property set to the appropriate number of mip levels, and each mip level must be initialized with a scaled down version of the mip level 0 image. Note that mip levels can be generated automatically by luma.gl, or each mip level can be set explicitly by the application.

On WebGPU, automatic mipmap generation is provided by DynamicTexture. For non-3D textures luma.gl uses a render path, and for 3D textures it uses a compute path. If the texture format does not support the required capabilities, mipmap generation throws when it is requested.

Mipmap usage is controlled via SamplerProps.mipmapFilter:

mipmapFilterminFilterDescriptionLinearitySpeed
nonenearestNo filtering, no mipmapsnone—
nonelinearFiltering, no mipmapsbilinearslowest
nearestnearestNo filtering, sharp switching between mipmapsnone—
nearestlinearNo filtering, smooth transition between mipmapslinear—
linearnearestFiltering, sharp switching between mipmapsbilinear with mipmapsfastest
linearlinearFiltering, smooth transition between mipmapstrilinear—

In addition, the anisotropy sampler property controls how many miplevels are used during sampling.

Notes:

  • Enabling mipmap filtering not only improves visual quality, but can also improve performance. When a scaled down, lower resolution mip level is selected this reduces memory bandwidth requirements.
  • Linear filtering is considered "bilinear" because it is a linear filter that is applied in two directions, sequentially. First, a linear filter is applied along the image's x axis (width), and then a second filter is applied along the y axis (height).
  • Linear mipmap filtering is considered "trilinear" since it also interpolates linearly between mip levels.

Video frames​

Use copied sampling when the same shader must run on WebGL 2 and WebGPU. Use an external texture when the WebGPU shader accepts texture_external and the frame is consumed immediately. The example starts with a generated video; camera input is optional.

GitHub
0.0s
Needluma.gl APIShader bindingNotes
One uploaded image or one copied video frameTextureGLSL sampler2D, WGSL texture_2d<f32>Concrete GPU allocation with ordinary texture sampling.
Async or replaceable copied texture dataDynamicTextureGLSL sampler2D, WGSL texture_2d<f32>Engine wrapper around a concrete luma Texture.
Playing HTMLVideoElement or caller-owned VideoFrameVideoTextureDepends on shader declarationLive engine binding source that resolves per draw.
Native WebGPU direct-video samplingExternalTextureWGSL texture_externalConcrete, short-lived WebGPU binding acquired from a video source.

Use an ordinary Texture when the shader needs normal texture features: textureSample, repeat address modes, mipmaps, render-target usage, storage usage, or one shader shape shared with non-video textures. A single video frame can be copied into such a texture with Texture.copyExternalImage().

Use VideoTexture when the application owns a live video source and wants luma.gl to update the binding as frames arrive. For an HTMLVideoElement named video, bind the same wrapper across draws.

import {Model, VideoTexture} from '@luma.gl/engine/api';

const videoTexture = new VideoTexture(device, {source: video});
const model = new Model(device, {source, bindings: {videoTexture}});

VideoTexture also accepts caller-owned VideoFrame objects, which is useful for decoded or timeline-selected frames:

let currentFrame: VideoFrame | null = null;

function showFrame(nextFrame: VideoFrame) {
const previousFrame = currentFrame;
currentFrame = nextFrame;
videoTexture.setSource(nextFrame);
previousFrame?.close();
}

// Keep currentFrame open while VideoTexture can still resolve it.
videoTexture.destroy();
currentFrame?.close();

Do not close the current frame immediately after setSource(). The frame must stay open through draw binding resolution; VideoTexture deliberately never calls VideoFrame.close() for you.

See VideoTexture for the engine binding and ExternalTexture for native external sampling. For compressed image assets, check the device's supported formats before upload.