Three.js From Zero · Article s16-02

Phyllotaxis — One Angle, Ten Thousand Spheres

The golden angle packs 10,000 instanced spheres into a sunflower, a dome, and a Fibonacci sphere — one draw call, with a slider that shows why 137.508° is special. Part of the MasterAllArts Creative 3D Roadmap.

Part of the MasterAllArts Creative 3D Roadmap .

← Three.js From Zero S16-02 · Beautiful Math

Season 16 · Article 02 · Beautiful Math

A sunflower head solves an optimization problem every time it grows: pack seeds as densely as possible, forever, with one rule. The rule is a single rotation angle — 137.508°, the golden angle — and it is the most instancing-friendly algorithm in all of generative art. Ten thousand spheres, one draw call, and a slider that lets you feel why irrationality matters.

— fps · — instances · 1 draw call

Drag to orbit. Now do the one experiment this whole article exists for: grab the angle slider and move it slightly — from 137.508 to 137.6. The seamless packing shatters into spiral arms. Go to 137.0 and you get gaps; land near a rational fraction of 360° (try 138.462 ≈ 360·5/13) and the points collapse into 13 straight spokes with dead space between them. Only at the golden angle does every sphere get an equal share of the area. Then hit replay growth and watch the head assemble itself seed-by-seed from the center, the way the plant actually does it.

The whole algorithm is two lines

This is Vogel's model of the sunflower (1979). Seed number n gets polar coordinates:

θ(n) = n × 137.508°        // each seed: one more golden-angle turn
r(n) = c × √n              // radius grows with the square root

Both lines are load-bearing. The square root is what makes density uniform: the area of a disk grows with r², so if n seeds must fill area ∝ r², then r must grow like √n. Get this wrong (use r ∝ n) and your seeds thin out toward the rim like a sad firework.

The angle is deeper. If you turn by any rational fraction of a full circle — say 360°·(5/13) — then after 13 seeds you're facing exactly the way you started, and seed 14 lands on the same ray as seed 1. You get 13 spokes, and the space between them is wasted forever. To never repeat, you want an angle that is as far from every fraction as possible. There is a precise answer to that demand: the golden ratio φ is, in the formal continued-fraction sense, the most irrational number there is. The golden angle is just the full circle divided by φ²: 360°/φ² ≈ 137.5077°. Plants found it by natural selection; you get it in one line:

const GOLDEN_ANGLE = Math.PI * (3 - Math.sqrt(5));   // radians, ≈ 137.5077°

My old 2D atlas version of this is a 30-line canvas sketch — dots on a flat disk. The 3D upgrade isn't just cosmetic: real flower heads are domes, seed cones are spirals in 3D, and the same angle also solves point distribution on a sphere — which is why graphics people keep phyllotaxis in their pocket long after they stop caring about flowers.

Step 1 — InstancedMesh: the 10,000-things tool

Naively you'd create 10,000 Mesh objects. That's 10,000 draw calls and 10,000 scene-graph nodes — your frame rate dies at the CPU, long before the GPU breaks a sweat. InstancedMesh is Three.js's answer: one geometry, one material, one draw call, and a big buffer of per-instance transform matrices.

const MAX_COUNT = 30000;
const geometry = new THREE.SphereGeometry(0.5, 12, 8);   // low-poly: it's tiny on screen
const material = new THREE.MeshStandardMaterial({ roughness: 0.35, metalness: 0.1 });
const mesh = new THREE.InstancedMesh(geometry, material, MAX_COUNT);
scene.add(mesh);

Allocate the maximum you'll ever need up front — the buffer size is fixed at construction. To show fewer, you don't rebuild anything: you just lower mesh.count. Remember that; it becomes the growth animation for free.

Step 2 — Placing instances: the dummy Object3D pattern

Instance transforms are raw 4×4 matrices. Nobody composes matrices by hand — the idiom is a single throwaway Object3D that you reposition and re-use as a matrix calculator:

const dummy = new THREE.Object3D();

for (let i = 0; i < N; i++) {
  const n = i + 1;
  const theta = n * angleRad;
  const r = c * Math.sqrt(n);

  dummy.position.set(Math.cos(theta) * r, 0, Math.sin(theta) * r);
  dummy.scale.setScalar(floretSize);
  dummy.updateMatrix();
  mesh.setMatrixAt(i, dummy.matrix);
}
mesh.count = N;
mesh.instanceMatrix.needsUpdate = true;

One nice detail: pick c = targetRadius / √N so the head stays the same size no matter how many seeds you pour in — the count slider then changes density, not diameter, which is the perceptually interesting thing.

Pitfall: the update flag, again. setMatrixAt writes into a plain typed array. Nothing reaches the GPU until mesh.instanceMatrix.needsUpdate = true. Same deal as dynamic BufferAttributes in the Lorenz article — if your instances all sit at the origin in a single overlapping blob, this flag is what you forgot.

Step 3 — Three shapes, one rule

The shape selector isn't three algorithms — it's one spiral and three projections:

  • Disk — Vogel's model verbatim: y = 0.
  • Dome — lift the disk onto a paraboloid: y = (R² − r²) / k. Center seeds rise highest, rim seeds stay grounded — instantly reads as a real flower head.
  • Sphere — the Fibonacci sphere. Walk latitude evenly from pole to pole while longitude turns by the golden angle each step:
// i-th of N points, near-uniform on the unit sphere
const z = 1 - (2 * (i + 0.5)) / N;        // latitude: evenly spaced heights
const rxy = Math.sqrt(1 - z * z);          // ring radius at that height
const theta = (i + 1) * GOLDEN_ANGLE;      // longitude: golden spiral
dummy.position.set(Math.cos(theta) * rxy * R, z * R, Math.sin(theta) * rxy * R);

That five-liner is the most copy-pasted point-distribution trick in graphics — environment map sampling, particle emitters, hair roots, foliage scattering. "Evenly spaced heights × golden longitude" is worth memorizing.

Step 4 — Per-instance color

InstancedMesh has a color buffer too, and it composes with any material — lighting included — without touching shaders:

const c = new THREE.Color();
const center = new THREE.Color('#ff6030');
const rim    = new THREE.Color('#3a2cff');

for (let i = 0; i < N; i++) {
  c.copy(center).lerp(rim, i / N);   // seed index ≈ age ≈ distance from center
  mesh.setColorAt(i, c);
}
mesh.instanceColor.needsUpdate = true;

Note what we're encoding: instance index is the seed's age — in phyllotaxis, age and radius are the same thing (r ∝ √n). Same principle as coloring the Lorenz particles by speed: the system hands you a meaningful scalar, you feed it to a lerp.

Step 5 — The growth replay is one integer

Because instances are laid out in birth order, "grow the flower" is literally just animating mesh.count from 0 to N. No allocation, no per-frame relayout — the GPU draws a prefix of the buffer:

// in the render loop, while growing:
const t = Math.min(1, (now - growStart) / 3500);
const eased = t * t * (3 - 2 * t);              // smoothstep
mesh.count = Math.max(1, Math.floor(eased * N));

This is the cheapest convincing growth animation in Three.js, and it only works if your generation order means something. Generative-art lesson: lay out your instances in an order you'd want to reveal them in.

What the sliders teach

  • angle — the headline act. 137.508° packs seamlessly; ±0.1° breaks into curved arms (those arms are Fibonacci-numbered, count them); rational angles make spokes. The pattern is violently sensitive because every seed's position multiplies the error by its index — seed 10,000 feels a 0.01° error as a 100° displacement.
  • count — density, not size, thanks to the c = R/√N normalization. Push 30,000 and check the fps counter: still one draw call.
  • spread — scales the whole head; florets scale with it so packing stays tight.
  • shape — same indices, same angle, three projections.

The skeleton

<script type="importmap">
{ "imports": {
    "three": "https://unpkg.com/three@0.170.0/build/three.module.js",
    "three/addons/": "https://unpkg.com/three@0.170.0/examples/jsm/" } }
</script>
<script type="module">
import * as THREE from 'three';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

// scene / camera / renderer / lights / controls
// InstancedMesh(geometry, material, MAX) once          (Step 1)
// layout(): dummy.position → setMatrixAt + setColorAt  (Steps 2–4)
// render loop: animate mesh.count while growing        (Step 5)
</script>