Three.js Texture Arrays (DataArrayTexture / sampler2DArray)
Bind many textures as one in Three.js with a DataArrayTexture, letting 1,600 instanced cubes each sample one of 16 layers via a per-instance attribute in a single draw call, compared with 16 separate textures and materials.
Key topics: three.js texture array, dataarraytexture, sampler2darray, instancing, draw calls, webgl2
Game Over
What this code does
- Texture Array: N same-size images live in one GPU object, sampled with `texture(sampler2DArray, vec3(uv, layer))`.
- Per-Instance Layer: an `aLayer` instanced attribute chooses each cube's image, so one material covers all of them.
- Draw Calls: separate textures need separate materials and draws; the array collapses them to one.
- Mipmaps: `generateMipmaps` builds per-layer mip chains for clean minification.
- Shader Cycling: the layer index can be animated in the shader, which suits flipbooks and terrain splats.
- Controls: binding mode, layer cycling and cube count.
Related Demos
Continue Learning
JavaScript Implementation
// Many textures behind one sampler: a 2D texture array
const layers = 16
const array = new THREE.DataArrayTexture(rgbaBytes, 256, 256, layers) // rgbaBytes = 256*256*4*layers
array.generateMipmaps = true
array.minFilter = THREE.LinearMipmapLinearFilter
array.needsUpdate = true
geometry.setAttribute('aLayer', new THREE.InstancedBufferAttribute(layerPerInstance, 1))
const material = new THREE.ShaderMaterial({
glslVersion: THREE.GLSL3,
uniforms: { uTextures: { value: array } },
vertexShader: 'in float aLayer; out vec2 vUv; out float vLayer; void main () { vUv = uv; vLayer = aLayer; gl_Position = projectionMatrix * modelViewMatrix * instanceMatrix * vec4(position, 1.0); }',
fragmentShader: 'precision highp sampler2DArray; uniform sampler2DArray uTextures; in vec2 vUv; in float vLayer; out vec4 c; void main () { c = texture(uTextures, vec3(vUv, vLayer)); }'
})