Three.js Uniform Buffer Objects (UniformsGroup / UBO)

Share scene data across 400 materials in Three.js with a WebGL2 uniform buffer (UniformsGroup), holding four lights, fog and time in one std140 block uploaded once per frame, compared with per-material uniforms.

Key topics: three.js uniformsgroup, uniform buffer object, ubo, std140, webgl2, shader uniforms

What this code does

- The Cost: classic uniforms are set per program per draw, so shared values are pushed hundreds of times a frame.
- UniformsGroup: a named group of `Uniform`s maps to a GLSL `layout(std140) uniform SceneData { … }` block.
- Upload Once: changing values in the group updates one GPU buffer that every bound program reads.
- std140 Layout: vec3s pad to 16 bytes, so data is packed as vec4s (position + intensity, colour, fog + density).
- Comparison: switch to per-material uniforms to see render() CPU time rise as 400 materials are rewritten each frame.
- Controls: data path, fog density and light speed.

Continue Learning

JavaScript Implementation

ES6+
// Share data across many materials with a uniform buffer object (WebGL2 UBO)
const sceneData = new THREE.UniformsGroup()
sceneData.setName('SceneData') // must match the block name in GLSL
sceneData.add(new THREE.Uniform(new THREE.Vector4())) // lightPos
sceneData.add(new THREE.Uniform(0))                   // time
const material = new THREE.ShaderMaterial({
  glslVersion: THREE.GLSL3,
  uniformsGroups: [sceneData],
  vertexShader,
  fragmentShader: `
    layout(std140) uniform SceneData { vec4 lightPos; float time; };
    out vec4 outColor;
    void main () { outColor = vec4(vec3(0.5 + 0.5 * sin(time)), 1.0); }`
})
// update once per frame: sceneData.uniforms[1].value = clock.elapsedTime