Three.js MRT GPU Picking & ID-Buffer Outlines
Multiple render targets in Three.js, where one pass writes colour, normals and a 24-bit object-ID buffer, used for pixel-exact GPU picking with readRenderTargetPixels and selection outlines from edge detection on the ID buffer.
Key topics: three.js multiple render targets, mrt, gpu picking, object id buffer, selection outline, readrendertargetpixels
Game Over
What this code does
- MRT: `new WebGLRenderTarget(w, h, { count: 3 })` with `layout(location = N) out` writes three textures in one draw.
- ID Buffer: each object's index is packed into RGB, so 16 million objects can be distinguished.
- GPU Picking: one texel of attachment 2 under the cursor (`readRenderTargetPixels(…, textureIndex = 2)`) gives the exact object, with no raycasting.
- Outlines: the composite pass marks pixels whose ID differs from a neighbour's for the hovered or selected object.
- Inspection: view each attachment (colour, normals, false-coloured IDs) directly.
- Controls: view and clear selection (hover to highlight, click to select).
Related Demos
Continue Learning
JavaScript Implementation
// One render pass, three outputs: colour, normal and object id
const mrt = new THREE.WebGLRenderTarget(width, height, { count: 3, minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter })
const material = new THREE.ShaderMaterial({
glslVersion: THREE.GLSL3,
uniforms: { uId: { value: new THREE.Vector3(id / 255, 0, 0) } },
vertexShader,
fragmentShader: `
uniform vec3 uId;
layout(location = 0) out vec4 outColor;
layout(location = 1) out vec4 outNormal;
layout(location = 2) out vec4 outId;
void main () { outColor = vec4(1.0); outNormal = vec4(0.5); outId = vec4(uId, 1.0); }`
})
// GPU picking: read one texel of attachment 2 under the cursor
const px = new Uint8Array(4)
renderer.readRenderTargetPixels(mrt, x, y, 1, 1, px, undefined, 2)
const pickedId = px[0] | (px[1] << 8) | (px[2] << 16)