Three.js Ray Marching SDF Shapes Gallery

Sphere-traced signed distance fields in a Three.js fullscreen shader, including a box↔sphere morph, torus, octahedron and smooth-union blobs, with soft shadows, ambient occlusion and a step-count heatmap.

Key topics: three.js ray marching, signed distance field, sdf, sphere tracing, smooth union, glsl shader

What this code does

- Sphere Tracing: each pixel steps along its ray by the SDF value, the largest safe step that cannot overshoot a surface.
- SDF Primitives: box, sphere, torus, octahedron, capsule and cylinder are each a few lines of exact distance math.
- Smooth Union: `smin(a, b, k)` blends distances so shapes melt together; k sets the fillet radius.
- Normals & Lighting: normals are the SDF gradient by central differences, and soft shadows come from the closest miss along a shadow ray.
- Ambient Occlusion: sampling the SDF a few steps along the normal estimates how enclosed each point is.
- Controls: smooth-union k, morph animation, box→sphere morph, shaded/normals/step-count views and soft shadows.

Continue Learning

JavaScript Implementation

ES6+
// Sphere-tracing an SDF in a fullscreen fragment shader
const material = new THREE.ShaderMaterial({
  uniforms: { uTime: { value: 0 }, uAspect: { value: width / height } },
  vertexShader: 'varying vec2 vUv; void main () { vUv = uv; gl_Position = vec4(position.xy, 0.0, 1.0); }',
  fragmentShader: `
    uniform float uTime; uniform float uAspect; varying vec2 vUv;
    float smin (float a, float b, float k) { float h = clamp(0.5 + 0.5 * (b - a) / k, 0.0, 1.0); return mix(b, a, h) - k * h * (1.0 - h); }
    float map (vec3 p) {
      float a = length(p - vec3(sin(uTime), 0.0, 0.0)) - 0.6;
      float b = length(p - vec3(0.0, cos(uTime) * 0.7, 0.0)) - 0.5;
      return min(smin(a, b, 0.4), p.y + 1.0);
    }
    void main () {
      vec3 ro = vec3(0.0, 0.5, 3.0);
      vec3 rd = normalize(vec3((vUv - 0.5) * vec2(uAspect, 1.0), -1.2));
      float t = 0.0;
      for (int i = 0; i < 100; i++) { float d = map(ro + rd * t); if (d < 0.001 || t > 20.0) break; t += d; }
      vec3 p = ro + rd * t;
      vec2 e = vec2(0.001, 0.0);
      vec3 n = normalize(vec3(map(p + e.xyy) - map(p - e.xyy), map(p + e.yxy) - map(p - e.yxy), map(p + e.yyx) - map(p - e.yyx)));
      float diff = max(dot(n, normalize(vec3(0.6, 0.8, 0.4))), 0.0);
      gl_FragColor = vec4(t < 20.0 ? vec3(0.65, 0.4, 0.95) * (0.2 + diff) : vec3(0.1, 0.12, 0.2), 1.0);
    }`
})
scene.add(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), material))

function animate (t) { requestAnimationFrame(animate); material.uniforms.uTime.value = t / 1000; renderer.render(scene, camera) }
animate(0)