Three.js From Zero · Article s16-07

The Mandelbrot Set — One Pixel, One Universe

An interactive escape-time fragment shader: drag, scroll-zoom toward the cursor, smooth coloring, cosine palettes — and the float32 precision wall at ×100,000. Part of the MasterAllArts Creative 3D Roadmap.

Part of the MasterAllArts Creative 3D Roadmap .

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

Season 16 · Article 07 · Beautiful Math

The most famous image in mathematics is generated by one line: square a number, add a constant, repeat. Every pixel on this canvas runs that line a few hundred times, every frame, and the boundary that emerges contains infinite copies of itself. Drag to pan, scroll to dive — and somewhere around 100,000× magnification you'll hit a wall that teaches you more about your GPU than any spec sheet.

— fps · — iter · zoom ×1

Drag to pan, scroll to zoom toward the cursor, double-click to dive 2.5× where you click. The bookmarks take you to the classic landmarks: seahorse valley's spiraling tails, elephant valley's trunk parade, and a perfect miniature Mandelbrot sitting on the needle — the set quotes itself, at every scale, forever. Push iterations up when deep details look soft.

The whole algorithm, honestly

z = 0
repeat:  z = z² + c        // z, c are complex numbers; c is this pixel
if |z| ever escapes to infinity → c is OUTSIDE (color by how fast)
if |z| stays bounded forever     → c is INSIDE (color it black)

That's the entire thing. The set is just "the c values where iteration never blows up." We can't check forever, so we iterate a few hundred times and call survivors inside — that's why deep zooms need the iterations slider: near the boundary, points take longer and longer to make up their minds, and a low cap miscounts them as inside, smearing detail into black.

Notice the shape of the problem: every pixel is independent, every pixel runs the same short program, and there are a million of them. After reaction–diffusion you already know what that means: this is a fragment shader's natural prey. My old atlas drew this on a 2D canvas, one pixel at a time, in JavaScript — fine for a postcard, hopeless for a flythrough. The GPU version pans and zooms at 60fps without breaking a sweat.

Step 1 — Three uniforms are a 2D camera

The fragment shader needs to know which complex number each pixel represents. Center, scale, aspect — that's a complete pan/zoom camera, no matrices required:

vec2 c = uCenter + vec2(
  (vUv.x - 0.5) * uScale * uAspect,
  (vUv.y - 0.5) * uScale
);

All navigation happens in JavaScript by writing two numbers. Pan: move uCenter. Zoom: shrink uScale. The "zoom toward the cursor" feel — the thing that separates a fractal explorer from a fractal screensaver — is four lines:

const before = screenToComplex(mouseX, mouseY);   // where the cursor points now
scale *= factor;                                   // zoom...
center.x = before.x + (center.x - before.x) * factor;  // ...keeping that point
center.y = before.y + (center.y - before.y) * factor;  // under the cursor

Step 2 — The escape loop in GLSL

vec2 z = vec2(0.0);
float n = -1.0;
for (int i = 0; i < 1000; i++) {          // constant bound: GLSL's rule
  if (float(i) >= uMaxIter) break;        // dynamic limit: our rule
  z = vec2(z.x * z.x - z.y * z.y, 2.0 * z.x * z.y) + c;   // z² + c
  if (dot(z, z) > 256.0) { n = float(i); break; }          // escaped
}

Two quirks worth internalizing. GLSL demands a compile-time constant loop bound — so you loop to a generous constant and break on a uniform, which compiles everywhere and costs nothing. And complex multiplication doesn't exist in GLSL; the vec2(x² − y², 2xy) line is complex squaring, written out.

Step 3 — Smooth coloring, or: killing the bands

Coloring by raw escape count gives ugly concentric bands — n is an integer, and neighboring pixels jump a whole color step. The classic fix reads how far past the escape radius z overshot, recovering the fractional iteration where escape "really" happened:

float nu = n + 1.0 - log2(0.5 * log(dot(z, z)));   // continuous escape time
float t  = nu * 0.015 + uTime * 0.02;               // slow palette drift

One logarithm and the bands melt into silk. This formula is forty years old and still in every serious fractal renderer; it works because |z| grows roughly like a double exponential once it escapes, so log-of-log linearizes it.

Step 4 — Cosine palettes: infinite gradients in one line

vec3 col = 0.5 + 0.5 * cos(6.28318 * (t + vec3(0.00, 0.33, 0.67)));

Inigo Quilez's cosine palette: three phase-shifted cosines, one per channel. Shift the phases and you get a different infinite, seamlessly-looping gradient — no texture, no lookup table, no banding. The uTime term in t makes the whole palette slowly crawl along the contours, which is what gives the still image its lava-lamp life. This one-liner belongs in your permanent toolkit next to the golden angle and the spatial hash.

The precision wall

Keep zooming. Somewhere past ×100,000 the silk turns to Minecraft: blocky, jagged, pixel-doubled. Nothing is wrong with the math — the numbers ran out. A 32-bit float carries about 7 significant digits, and when your view is 10⁻⁵ wide around a center near magnitude 1, neighboring pixels need digits float32 simply doesn't have. Two adjacent pixels compute the same c, and detail collapses.

Pitfall: highp is not double. Desktop GPUs run fragment shaders in float32 no matter what you ask for — there is no double in WebGL. The deep-zoom videos you've seen use perturbation theory: compute ONE point in arbitrary precision on the CPU, then have the GPU compute only each pixel's tiny difference from it — differences fit comfortably in float32. Knowing where the wall is, and that there's a door through it, is the difference between a demo and an explorer.

What the controls teach

  • iterations — resolution of patience, not pixels. Watch the black boundary recede and sharpen as survivors get reclassified.
  • seahorse valley (−0.7453 + 0.1127i) — the boundary's most photographed neighborhood; count the spiral arms.
  • elephant valley (0.2925 + 0.0149i) — period-doubling on parade.
  • mini-brot (−1.7549 + 0i) — an entire copy of the set, ~1/1000th the size, on the needle. There are infinitely many; every one is connected to the mainland by a filament thinner than any float.

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';

// fullscreen quad + ShaderMaterial (same rig as S16-06)
// uniforms: uCenter, uScale, uAspect, uMaxIter, uTime    (Step 1)
// escape loop + smooth coloring + cosine palette         (Steps 2–4)
// pointer events write uCenter/uScale — that's the camera
</script>