Capítulo 851 de 859

Chapter 851: Uniform Types (Manual)

Core Idea

Rules for matching a ShaderMaterial/RawShaderMaterial uniform's JavaScript value to its GLSL type, including how to represent arrays of primitives and structured (struct-shaped) uniforms so three.js can process them correctly.

Key Concepts

  • Every uniform needs a value: and that value's type/shape must correspond to the GLSL variable's declared type.
  • Primitive arrays aren't nested arrays: a GLSL array of a primitive type (e.g. vec2[5]) must be supplied as either an array of the matching THREE object (five Vector2s) or as one flat array of numbers (ten numbers) — not an array of arrays for that innermost primitive dimension.
  • Nested arrays of vectors/matrices: that "no nested array for primitives" rule doesn't apply transitively — an array of vec2[5] arrays is legitimately an array of arrays, each containing five Vector2s (or ten flat numbers).
  • Structured uniforms: to mirror a GLSL struct in JS, uniform data must be organized as plain objects with matching field names, so three.js can walk and upload the structure correctly.
  • Arrays of structs: the same object-shape convention extends to arrays — an array of plain objects, each matching the struct's field layout.

Code Examples

const entry1 = { position: new THREE.Vector3(), direction: new THREE.Vector3(0, 0, 1) };
const entry2 = { position: new THREE.Vector3(1, 1, 1), direction: new THREE.Vector3(0, 1, 0) };

const uniforms = {
  data: { value: [entry1, entry2] },
};
  • What it demonstrates: representing an array of a GLSL struct as an array of plain JS objects whose fields match the struct's members.

Key Takeaways

  1. A uniform's value type must exactly match its GLSL declaration's type/shape.
  2. Arrays of GLSL primitives are represented as an array of the matching THREE object type or a single flat number array — never as arrays-of-arrays at that innermost level.
  3. That flattening rule doesn't cascade — outer array dimensions (e.g. an array of vector arrays) are still real nested arrays.
  4. GLSL structs (and arrays of structs) map to plain JS objects (or arrays of them) with matching field names.

Connects To

  • ShaderMaterial / RawShaderMaterial: the material types whose uniforms option this chapter's rules apply to.