Custom BufferGeometry
The built-in shapes are all made the same way: arrays of numbers wrapped in a BufferGeometry. When you need a shape nobody ships (a terrain from a height map, a road along a curve, a level built from a tile grid, a mesh generated by your own code), you fill those arrays yourself. It is also the best way to understand what a GPU really draws.
Attributes and triangles
A BufferGeometry stores per-vertex attributes, each a typed array plus an item size:
| Attribute | Item size | Meaning |
|---|---|---|
position |
3 | x, y, z of each vertex (required) |
normal |
3 | the direction the surface faces at the vertex (needed for lighting) |
uv |
2 | texture coordinates, 0–1 across a texture |
color |
3 or 4 | per-vertex color (used when the material has vertexColors: true) |
Without an index, every three vertices form one triangle. With an index (setIndex), triangles are lists of vertex numbers, so a vertex shared by several triangles is stored once. Triangles are counter-clockwise when you look at their front side; that winding order decides which side is the front, and therefore which side is culled.
Here is a four-sided pyramid built by hand: 5 vertices, 6 triangles (4 sides and a base made of 2).
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }</style>
<script type="module">
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#161b27');
const camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.1, 50);
camera.position.set(0, 1.6, 4.5);
camera.lookAt(0, 0.4, 0);
scene.add(new THREE.HemisphereLight('#fff', '#334', 1));
const sun = new THREE.DirectionalLight('#fff', 2.5);
sun.position.set(2, 4, 3);
scene.add(sun);
const positions = new Float32Array([
0, 1.2, 0, // 0 apex
-1, 0, 1, // 1 front left
1, 0, 1, // 2 front right
1, 0, -1, // 3 back right
-1, 0, -1, // 4 back left
]);
const indices = [
0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 1, // sides, counter-clockwise seen from outside
1, 4, 3, 1, 3, 2, // base, seen from below
];
const shared = new THREE.BufferGeometry();
shared.setAttribute('position', new THREE.BufferAttribute(positions, 3));
shared.setIndex(indices);
shared.computeVertexNormals(); // averages the normals of the faces around each vertex
// The same shape with every triangle owning its own vertices: sharp, flat faces.
const faceted = shared.toNonIndexed();
faceted.computeVertexNormals();
const mat = new THREE.MeshStandardMaterial({ color: '#ffca28' });
const a = new THREE.Mesh(shared, mat);
const b = new THREE.Mesh(faceted, mat);
a.position.x = -1.4;
b.position.x = 1.4;
scene.add(a, b);
console.log('indexed:', shared.attributes.position.count, 'vertices,', shared.index.count / 3, 'triangles');
console.log('non-indexed:', faceted.attributes.position.count, 'vertices');
renderer.setAnimationLoop((t) => {
a.rotation.y = b.rotation.y = t / 2000;
renderer.render(scene, camera);
});
</script>The left pyramid looks oddly soft: its 5 vertices are shared, so computeVertexNormals() averages the normals of all faces that meet at a vertex, and the lighting blends across the edges. The right one, made with toNonIndexed(), has 18 vertices (one set per triangle), so each face gets its own normal and the edges are sharp. Smooth surfaces (terrain, characters) share vertices; hard-edged ones (crates, rocks, low-poly art) don't. Real models mix both, which is why a "cube" exported from Blender has 24 vertices.
Building an index for a grid
Grids are the most common generated mesh: terrain, water, tile floors. A grid of cols × rows cells has (cols + 1) × (rows + 1) vertices and two triangles per cell. This model builds the index for a 3 × 2 grid and prints it:
// Index buffer for a grid of cells, vertices numbered row by row.
function gridIndex(cols, rows) {
const index = [];
const stride = cols + 1; // vertices per row
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
const a = r * stride + c; // top-left corner of the cell
const b = a + 1; // top-right
const d = a + stride; // bottom-left
const e = d + 1; // bottom-right
index.push(a, d, b, b, d, e); // two counter-clockwise triangles (seen from +Y)
}
}
return index;
}
const cols = 3, rows = 2;
const idx = gridIndex(cols, rows);
console.log(`${(cols + 1) * (rows + 1)} vertices, ${idx.length / 3} triangles`);
for (let i = 0; i < idx.length; i += 6) console.log(`cell ${i / 6}: [${idx.slice(i, i + 3)}] [${idx.slice(i + 3, i + 6)}]`);12 vertices, 12 triangles
cell 0: [0,4,1] [1,4,5]
cell 1: [1,5,2] [2,5,6]
cell 2: [2,6,3] [3,6,7]
cell 3: [4,8,5] [5,8,9]
cell 4: [5,9,6] [6,9,10]
cell 5: [6,10,7] [7,10,11]
The vertices lie on the XZ plane with rows going toward +Z, so seen from above (+Y), a → d → b runs counter-clockwise and the triangles face up.
A procedural terrain
Now the real thing: a 64 × 64 terrain whose heights come from seeded value noise (random heights on a coarse lattice, smoothly interpolated, several octaves added together; see Noise). Vertex colors paint sand, grass, rock and snow by height. Click Wireframe to see the grid.
<style>html, body { margin: 0; height: 100%; overflow: hidden } canvas { display: block }
button { position: fixed; left: 8px; top: 8px; font: 13px system-ui, sans-serif }</style>
<button id="wire">Wireframe</button>
<script type="module">
import * as THREE from 'three';
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
document.body.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color('#9cc9ef');
scene.fog = new THREE.Fog('#9cc9ef', 30, 70);
const camera = new THREE.PerspectiveCamera(50, innerWidth / innerHeight, 0.1, 200);
scene.add(new THREE.HemisphereLight('#e8f4ff', '#4a5a3a', 1.2));
const sun = new THREE.DirectionalLight('#fff4e0', 2.5);
sun.position.set(-10, 15, 5);
scene.add(sun);
// Seeded random numbers (mulberry32) so the island is the same on every run.
function mulberry32(seed) {
return () => {
seed |= 0; seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const rng = mulberry32(7);
const LATTICE = 17;
const lattice = Array.from({ length: LATTICE * LATTICE }, () => rng());
const smooth = (t) => t * t * (3 - 2 * t);
function valueNoise(x, y) { // x, y in lattice cells
const xi = Math.floor(x), yi = Math.floor(y), tx = smooth(x - xi), ty = smooth(y - yi);
const v = (i, j) => lattice[((j % LATTICE) + LATTICE) % LATTICE * LATTICE + ((i % LATTICE) + LATTICE) % LATTICE];
const top = v(xi, yi) * (1 - tx) + v(xi + 1, yi) * tx;
const bottom = v(xi, yi + 1) * (1 - tx) + v(xi + 1, yi + 1) * tx;
return top * (1 - ty) + bottom * ty;
}
function height(x, z) { // world x, z in [-20, 20]
let h = 0, amp = 1, freq = 0.08;
for (let o = 0; o < 4; o++) { h += amp * valueNoise(x * freq + 8, z * freq + 8); amp *= 0.5; freq *= 2; }
const falloff = Math.max(0, 1 - Math.hypot(x, z) / 20); // sink the edges into the sea
return (h - 0.55) * 9 * falloff + 3 * falloff - 1;
}
const SIZE = 40, SEG = 64, N = SEG + 1;
const pos = new Float32Array(N * N * 3), col = new Float32Array(N * N * 3);
const c = new THREE.Color();
for (let r = 0; r < N; r++) {
for (let q = 0; q < N; q++) {
const i = r * N + q, x = (q / SEG - 0.5) * SIZE, z = (r / SEG - 0.5) * SIZE, y = height(x, z);
pos.set([x, y, z], i * 3);
c.set(y < 0.3 ? '#d8c690' : y < 2.5 ? '#5e9c4a' : y < 4.5 ? '#7d7468' : '#f2f4f6');
col.set([c.r, c.g, c.b], i * 3);
}
}
const index = [];
for (let r = 0; r < SEG; r++) for (let q = 0; q < SEG; q++) {
const a = r * N + q, b = a + 1, d = a + N, e = d + 1;
index.push(a, d, b, b, d, e);
}
const geo = new THREE.BufferGeometry();
geo.setAttribute('position', new THREE.BufferAttribute(pos, 3));
geo.setAttribute('color', new THREE.BufferAttribute(col, 3));
geo.setIndex(index);
geo.computeVertexNormals();
const terrainMat = new THREE.MeshStandardMaterial({ vertexColors: true, flatShading: true });
scene.add(new THREE.Mesh(geo, terrainMat));
const sea = new THREE.Mesh(new THREE.PlaneGeometry(200, 200), new THREE.MeshStandardMaterial({ color: '#2f6ea5', roughness: 0.3 }));
sea.rotation.x = -Math.PI / 2;
scene.add(sea);
console.log(`terrain: ${N * N} vertices, ${index.length / 3} triangles`);
console.log(`height at the centre: ${height(0, 0).toFixed(2)}`);
document.getElementById('wire').onclick = () => { terrainMat.wireframe = !terrainMat.wireframe; };
renderer.setAnimationLoop((t) => {
const a = t / 9000;
camera.position.set(Math.sin(a) * 28, 14, Math.cos(a) * 28);
camera.lookAt(0, 0, 0);
renderer.render(scene, camera);
});
</script>Ideas to try: change the seed (mulberry32(7)), the octave count, or the color thresholds; remove flatShading for a smooth look; raise SEG to 128 and watch the triangle count.
Updating geometry every frame
You can animate vertices (waves, deformation) by writing into the attribute's array and flagging it:
const p = geo.attributes.position;
for (let i = 0; i < p.count; i++) {
p.setY(i, Math.sin(p.getX(i) + time) * 0.3);
}
p.needsUpdate = true; // upload the changed array to the GPU
geo.computeVertexNormals(); // only if lighting must follow the new shape (costly)Uploading a large buffer every frame is not free. For effects such as water, a vertex shader that moves vertices on the GPU is much cheaper (see the Shaders course). Also note that changing positions does not update the bounding sphere that frustum culling uses: call geo.computeBoundingSphere() if the shape grows, or objects may vanish at the screen edge.
Test yourself
A non-indexed geometry has 36 vertices in its position attribute. How many triangles does it draw?
- 6
- 12
- 18
- 36
Why does a hand-made indexed pyramid look smooth-shaded after computeVertexNormals()?
- The material defaults to smooth shading
- Shared vertices get the average normal of all faces around them, so lighting blends across edges
- Indexed geometry is subdivided
- The index buffer stores normals
You change a mesh's vertex positions in JavaScript. What must you set so the GPU sees the change?
mesh.needsUpdate = truegeometry.attributes.position.needsUpdate = truematerial.needsUpdate = true- Nothing; it is automatic