• 01 - Games
  • 02 - Creative Instruments & Explorers
  • 03 - Language, Signals & Text
  • 04 - Developer & Web Utilities
  • 05 - Generators & Data
  • 06 - Colour Theory
  • 07 - Music 26
  • 08 - 3D, Shaders & Visuals
ARCHIVE
  • Pip
  • Great White
  • Canyon Run
  • Diamond Vessel
  • T-6 Jedi Shuttle
  • N1 Starfighter
  • Clawdia

T 6 JEDI SHUTTLE SOURCE CODE

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>T-6 Jedi Shuttle</title>
<style>
:root{--bg:#0d1014;--fg:#c9d1da;color-scheme:dark;box-sizing:border-box;padding-top:env(safe-area-inset-top,0px);padding-bottom:env(safe-area-inset-bottom,0px)}
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){--bg:#0d1014;--fg:#c9d1da}}
:root[data-theme="dark"]{--bg:#0d1014;--fg:#c9d1da}
html,body{margin:0;height:100%;overflow:hidden;background:var(--bg)}
#app{position:fixed;inset:0;background:var(--bg)}
#gl{position:absolute;inset:0;width:100%;height:100%;display:block}
#msg{position:fixed;left:50%;top:50%;transform:translate(-50%,-50%);max-width:min(32rem,calc(100% - 3rem));margin:0;color:var(--fg);font:400 1rem/1.5 system-ui,-apple-system,"Segoe UI",sans-serif;text-align:center}
</style>
</head>
<body>
<div id="app"></div>
<p id="msg" role="status" hidden></p>
<script type="module">
const THREE_URL = "https://cdn.jsdelivr.net/npm/three@0.170.0/build/three.module.js";
let THREE;

// ---------- helpers ----------
const D2R = Math.PI / 180;
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const clamp01 = v => clamp(v, 0, 1);
const smoother = v => { const t = clamp01(v); return t * t * t * (t * (t * 6 - 15) + 10); };
const phase = (a, b, x) => smoother((x - a) / (b - a));
const wrapDeg = a => ((a + 180) % 360 + 360) % 360 - 180;

// ---------- ship dimensions (metres, stations measured aft from the nose) ----------
const SHIP = { length: 22.8, span: 33, engW: 11.1, rootT: 1.6, tipT: .65, hullR: 1.85 };
const ST = { cockpit: [0, 4], collar: [4.2, 5.7], shell: [4.2, 18.7], engine: [19, 22.8], keel: [3.4, 19.6] };
const RING = { m: .025, z: 132, s0: 4.3, face: .3, rOut: 1.75 };
RING.rp = RING.m * RING.z / 2;
const PIN = { z: 12 };
PIN.rp = RING.m * PIN.z / 2;
PIN.c = RING.rp - PIN.rp;
PIN.ratio = RING.z / PIN.z;
const SHELL = { rOut: SHIP.hullR, rIn: 1.7 };
const CABIN = { r: 1.6, neckR: 1.25, neck: [3.95, 4.85], floor: -.95 };
const WING = { te: 20.8, rIn: 2.35, notchR: 6.3, notchS: 18.6, flatR: 13.4 };
WING.outline = [
  [1.2, 2.35], [1.25, 2.8], [2.49, 5.18], [3.74, 7.25], [4.98, 9.32], [6.23, 10.79], [7.48, 12.31],
  [8.72, 13.29], [9.97, 13.95], [11.21, 14.4], [12.46, 14.85], [13.7, 15.45], [14.95, 15.85],
  [16.2, 16.15], [18.69, 16.37], [19.93, 16.46], [20.4, 16.5],
  [WING.te, SHIP.span / 2], [WING.te, WING.notchR], [WING.notchS, WING.notchR], [WING.notchS, SHIP.hullR],
  [ST.shell[0] + .2, SHIP.hullR], [ST.shell[0] + .2, WING.rIn],
];
const wingT = r => r <= WING.flatR ? SHIP.rootT
  : SHIP.rootT + (SHIP.tipT - SHIP.rootT) * (r - WING.flatR) / (SHIP.span / 2 - WING.flatR);
const POD = { rc: 3.6, a: 1.4, b: 1.2, s: [5.8, 18.4] };
const NOSE = [[0, .35], [.35, .85], [.9, 1.22], [1.6, 1.45], [2.4, 1.58], [3, 1.6], [4, 1.6]];
const noseR = s => {
  if (s <= 0) return NOSE[0][1];
  for (let i = 0; i < NOSE.length - 1; i++) {
    if (s <= NOSE[i + 1][0]) return NOSE[i][1] + (NOSE[i + 1][1] - NOSE[i][1]) * (s - NOSE[i][0]) / (NOSE[i + 1][0] - NOSE[i][0]);
  }
  return NOSE[NOSE.length - 1][1];
};
const BELLY = { s: [1.4, 3.8], hw: .55, bottom: -SHIP.hullR, corner: .25 };
const ENG = { hw: SHIP.engW / 2, hh: SHIP.hullR, corner: .6, engZ: [-3.74, 0, 3.74], engR: 1.42 };
const GEAR = { stroke: 1.5, legs: [{ s: 2, z: 0 }, { s: 19.5, z: -4.2 }, { s: 19.5, z: 4.2 }], padR: .42 };
const LANDED_H = SHIP.hullR + GEAR.stroke;
const RAMP = { len: 4, w: 2.2, hingeS: 15.2 };
RAMP.angle = Math.asin((LANDED_H - SHIP.hullR) / RAMP.len) / D2R;
const CLIMB = 16;

// One input, p: 0 = in flight, 1 = landed.
function config(p) {
  p = clamp01(p);
  const roll = 90 * phase(0, .5, p);
  return {
    p, roll,
    stroke: GEAR.stroke * phase(.5, .75, p),
    ramp: RAMP.angle * phase(.75, 1, p),
    glow: 1 - phase(.5, .75, p),
    height: LANDED_H + CLIMB * (1 - phase(0, .75, p)),
    pinion: roll * PIN.ratio,
  };
}

// ---------- geometry builders ----------
const X = s => SHIP.length / 2 - s;

function lathe(pts, seg = 64) {
  const g = new THREE.LatheGeometry(pts.map(([s, r]) => new THREE.Vector2(Math.max(1e-4, r), X(s))), seg);
  g.rotateZ(-Math.PI / 2);
  return g;
}

function roundRect(hw, hh, c) {
  const s = new THREE.Shape();
  s.moveTo(-hw + c, -hh); s.lineTo(hw - c, -hh); s.absarc(hw - c, -hh + c, c, -Math.PI / 2, 0);
  s.lineTo(hw, hh - c); s.absarc(hw - c, hh - c, c, 0, Math.PI / 2);
  s.lineTo(-hw + c, hh); s.absarc(-hw + c, hh - c, c, Math.PI / 2, Math.PI);
  s.lineTo(-hw, -hh + c); s.absarc(-hw + c, -hh + c, c, Math.PI, Math.PI * 1.5);
  return s;
}

function gearShape(teeth, rp, m, internal, rOut, hole) {
  const tip = internal ? rp - m : rp + m, root = internal ? rp + 1.25 * m : rp - 1.25 * m;
  const path = internal ? new THREE.Path() : new THREE.Shape();
  for (let h = 0; h < teeth; h++) {
    const a0 = Math.PI / 2 + h / teeth * Math.PI * 2, u = Math.PI * 2 / teeth;
    [[root, a0 - u * .5], [root, a0 - u * .3], [tip, a0 - u * .14], [tip, a0 + u * .14], [root, a0 + u * .3]]
      .forEach(([r, a], k) => (h === 0 && k === 0) ? path.moveTo(r * Math.cos(a), r * Math.sin(a)) : path.lineTo(r * Math.cos(a), r * Math.sin(a)));
  }
  path.closePath();
  if (!internal) {
    if (hole) { const p = new THREE.Path(); p.absarc(0, 0, hole, 0, Math.PI * 2, true); path.holes.push(p); }
    return path;
  }
  const outer = new THREE.Shape();
  outer.absarc(0, 0, rOut, 0, Math.PI * 2, false);
  outer.holes.push(path);
  return outer;
}

function extrudeX(shape, s0, s1, curveSegments = 4) {
  const g = new THREE.ExtrudeGeometry(shape, { depth: s1 - s0, bevelEnabled: false, curveSegments });
  g.rotateY(-Math.PI / 2);
  g.translate(X(s0), 0, 0);
  return g;
}

function wingGeo(side) {
  const shape = new THREE.Shape(WING.outline.map(([s, r]) => new THREE.Vector2(X(s), side * r)));
  const g = new THREE.ExtrudeGeometry(shape, { depth: SHIP.rootT, bevelEnabled: false, curveSegments: 4 });
  g.translate(0, 0, -SHIP.rootT / 2);
  const pos = g.attributes.position;
  for (let i = 0; i < pos.count; i++) pos.setZ(i, pos.getZ(i) / SHIP.rootT * wingT(Math.abs(pos.getY(i))));
  g.computeVertexNormals();
  return g;
}

function wingDecal(pts, side, mat, off = .012) {
  const shape = new THREE.Shape(pts.map(([s, r]) => new THREE.Vector2(X(s), side * r)));
  const grp = new THREE.Group();
  for (const face of [1, -1]) {
    const g = new THREE.ShapeGeometry(shape, 4), pos = g.attributes.position;
    for (let i = 0; i < pos.count; i++) pos.setZ(i, face * (wingT(Math.abs(pos.getY(i))) / 2 + off));
    g.computeVertexNormals();
    grp.add(new THREE.Mesh(g, mat));
  }
  return grp;
}

function panelLines(polys, side, mat, off = .02) {
  const v = [];
  for (const poly of polys) for (const face of [1, -1]) for (let i = 0; i < poly.length - 1; i++) {
    const [s0, r0] = poly[i], [s1, r1] = poly[i + 1];
    v.push(new THREE.Vector3(X(s0), side * r0, face * (wingT(r0) / 2 + off)),
      new THREE.Vector3(X(s1), side * r1, face * (wingT(r1) / 2 + off)));
  }
  return new THREE.LineSegments(new THREE.BufferGeometry().setFromPoints(v), mat);
}

function leadingEdgeBand(inset) {
  const idx = WING.outline.findIndex(([s, r]) => s === WING.te && r === SHIP.span / 2);
  const edge = WING.outline.slice(0, idx + 1);
  const inner = edge.map(([s, r]) => [s + .35, Math.max(WING.rIn + .1, r - inset)]).reverse();
  return [...edge.slice(1), ...inner];
}

function roundedBox(w, h, d, segments = 2, radius = .1) {
  const seg = segments * 2 + 1;
  radius = Math.min(w / 2, h / 2, d / 2, radius);
  const g = new THREE.BoxGeometry(1, 1, 1, seg, seg, seg).toNonIndexed();
  const pos = g.attributes.position.array, nor = g.attributes.normal.array;
  const half = new THREE.Vector3(w, h, d).divideScalar(2).subScalar(radius);
  const p = new THREE.Vector3(), n = new THREE.Vector3(), m = .5 / seg;
  for (let i = 0; i < pos.length; i += 3) {
    p.fromArray(pos, i); n.copy(p);
    n.x -= Math.sign(n.x) * m; n.y -= Math.sign(n.y) * m; n.z -= Math.sign(n.z) * m; n.normalize();
    pos[i] = half.x * Math.sign(p.x) + n.x * radius;
    pos[i + 1] = half.y * Math.sign(p.y) + n.y * radius;
    pos[i + 2] = half.z * Math.sign(p.z) + n.z * radius;
    nor[i] = n.x; nor[i + 1] = n.y; nor[i + 2] = n.z;
  }
  g.deleteAttribute("uv");
  return g;
}

// ---------- the ship ----------
const COL = {
  hull: "#e8e3da", red: "#a3302c", grey: "#9a9ca0", dark: "#4b4f56", ink: "#33302c", glass: "#1f2b37",
  steel: "#b8b3a8", brass: "#c79a4a", floor: "#cfc8bb", amber: "#e2a23a", orange: "#c96a2b",
  accent: "#2b6fd8", glow: "#7fc3ff",
};

function buildShip() {
  const std = (color, o = {}) => new THREE.MeshStandardMaterial({ color, roughness: .55, metalness: .08, ...o });
  const DS = THREE.DoubleSide, accent = new THREE.Color(COL.accent);
  const decal = { polygonOffset: true, polygonOffsetFactor: -2, polygonOffsetUnits: -2 };
  const M = {
    hull: std(COL.hull, { side: DS }),
    shell: std(COL.hull, { side: DS }),
    wing: std(COL.hull, { roughness: .6 }),
    red: std(COL.red, { roughness: .5, side: DS, ...decal }),
    grey: std(COL.grey, { roughness: .6, side: DS, ...decal }),
    dark: std(COL.dark, { roughness: .6 }),
    glass: std(COL.glass, { roughness: .12, metalness: .35 }),
    steel: std(COL.steel, { roughness: .45, metalness: .65 }),
    brass: std(COL.brass, { roughness: .42, metalness: .7, emissive: accent, emissiveIntensity: 0 }),
    pinion: std("#9fa6ad", { roughness: .42, metalness: .7, emissive: accent, emissiveIntensity: 0 }),
    piston: std("#c9ced3", { roughness: .3, metalness: .8, emissive: accent, emissiveIntensity: 0 }),
    ramp: std("#9aa0a7", { roughness: .6, emissive: accent, emissiveIntensity: 0 }),
    floor: std(COL.floor, { roughness: .8 }),
    amber: std(COL.amber, { roughness: .6 }),
    orange: std(COL.orange, { roughness: .65 }),
    nozzle: std("#5a5e66", { roughness: .45, metalness: .6, side: DS }),
    glow: new THREE.MeshBasicMaterial({ color: COL.glow }),
    plume: new THREE.MeshBasicMaterial({ color: COL.glow, transparent: true, opacity: .5, blending: THREE.AdditiveBlending, depthWrite: false, side: DS }),
    line: new THREE.LineBasicMaterial({ color: COL.ink, transparent: true, opacity: .45 }),
    keel: std("#d7d1c6", { side: DS }),
    collar: std(COL.grey, { roughness: .6 }),
    motor: std(COL.dark, { roughness: .5, metalness: .3 }),
    shaft: std(COL.steel, { roughness: .45, metalness: .65 }),
    pod: std(COL.hull),
    screen: new THREE.MeshBasicMaterial({ color: "#7fd18b" }),
    porcelain: std("#f4f2ee", { roughness: .3, metalness: 0 }),
  };
  // Outer skin fades for the x-ray pass, so it lives in the transparent queue throughout.
  const skin = [M.hull, M.shell, M.wing, M.red, M.grey, M.keel, M.pod];
  for (const m of skin) m.transparent = true;
  // Cutaway: everything above this plane is clipped.
  const cut = new THREE.Plane(new THREE.Vector3(0, -1, 0), 1e4);
  for (const m of [M.hull, M.shell, M.keel, M.glass, M.dark, M.nozzle, M.collar, M.orange, M.floor, M.amber, M.steel]) m.clippingPlanes = [cut];

  const root = new THREE.Group(), fixed = new THREE.Group(), rot = new THREE.Group();
  root.add(fixed, rot);
  const add = (geo, mat, parent, cast = true) => {
    const mesh = new THREE.Mesh(geo, mat);
    mesh.castShadow = cast; mesh.receiveShadow = true; parent.add(mesh);
    return mesh;
  };

  // Cockpit (fixed)
  {
    const prof = [];
    for (let i = 0; i <= 40; i++) { const s = i / 40 * ST.cockpit[1]; prof.push([s, noseR(s)]); }
    prof.unshift([0, 0]); prof.push([ST.cockpit[1], CABIN.neckR]);
    add(lathe(prof), M.hull, fixed);
    const canopy = new THREE.Mesh(new THREE.SphereGeometry(1, 48, 24, 0, Math.PI * 2, 0, Math.PI / 2), M.glass);
    canopy.scale.set(1.55, .62, 1.12); canopy.position.set(X(1.35), .95, 0); fixed.add(canopy);
    for (const z of [-.55, 0, .55]) {
      const frame = add(new THREE.BoxGeometry(2.6, .06, .07), M.dark, fixed, false);
      frame.position.set(X(1.45), 1.33 - Math.abs(z) * .32, z); frame.rotation.z = -.24;
    }
    add(lathe([[.5, noseR(.5) + .01], [.95, noseR(.95) + .01]]), M.red, fixed, false);
    add(lathe([[3.55, 1.615], [3.95, 1.615]]), M.grey, fixed, false);
    const half = -BELLY.bottom / 2;
    add(roundedBox(BELLY.s[1] - BELLY.s[0], half * 2, BELLY.hw * 2, 3, BELLY.corner), M.hull, fixed)
      .position.set(X((BELLY.s[0] + BELLY.s[1]) / 2), -half, 0);
  }

  // Keel tube (fixed, runs through the rotating shell)
  {
    const [n0, n1] = CABIN.neck;
    add(lathe([[ST.keel[0], .001], [ST.keel[0], CABIN.neckR], [n1, CABIN.neckR], [n1 + .1, CABIN.r], [ST.keel[1], CABIN.r], [ST.keel[1], .001]], 72), M.keel, fixed);
  }

  // Drive pinion, shaft and motor (fixed frame)
  const pinion = new THREE.Group();
  {
    const g = new THREE.ExtrudeGeometry(gearShape(PIN.z, PIN.rp, RING.m, false, 0, .05), { depth: RING.face, bevelEnabled: false, curveSegments: 3 });
    g.rotateY(-Math.PI / 2); g.translate(X(RING.s0), 0, 0);
    add(g, M.pinion, pinion);
    pinion.position.set(0, PIN.c, 0); fixed.add(pinion);
    const shaft = add(new THREE.CylinderGeometry(.06, .06, .9, 16), M.shaft, fixed);
    shaft.rotation.z = Math.PI / 2; shaft.position.set(X(3.9), PIN.c, 0);
    const motor = add(new THREE.CylinderGeometry(.2, .2, .55, 24), M.motor, fixed);
    motor.rotation.z = Math.PI / 2; motor.position.set(X(3.6), PIN.c - .05, 0);
  }

  // Engine section (fixed) with three engines
  const glows = [], plumes = [];
  {
    add(extrudeX(roundRect(ENG.hw, ENG.hh, ENG.corner), ST.engine[0], 22.3, 10), M.hull, fixed);
    const back = new THREE.Mesh(new THREE.ShapeGeometry(roundRect(ENG.hw - .04, ENG.hh - .04, ENG.corner)), M.dark);
    back.rotation.y = -Math.PI / 2; back.position.x = X(22.3) - .01; fixed.add(back);
    const front = back.clone(); front.material = M.grey; front.position.x = X(ST.engine[0]) + .01; front.rotation.y = Math.PI / 2; fixed.add(front);
    for (const y of [ENG.hh + .005, -ENG.hh - .005]) {
      add(new THREE.BoxGeometry(3.3, .02, 1.2), M.red, fixed, false).position.set(X(20.65), y, 0);
      for (const z of [-3.3, 3.3]) add(new THREE.BoxGeometry(2.6, .02, 2.4), M.grey, fixed, false).position.set(X(20.9), y, z);
    }
    for (const sd of [-1, 1]) add(roundedBox(1.6, 1, .25, 2, .08), M.dark, fixed).position.set(X(20.6), .2, sd * (ENG.hw + .02));
    for (const z of ENG.engZ) {
      const r = ENG.engR;
      add(lathe([[22, r * .92], [22.3, r], [22.8, r * .98], [22.8, r * .8], [22.35, r * .72]], 48), M.nozzle, fixed).position.z = z;
      const disc = new THREE.Mesh(new THREE.CircleGeometry(r * .7, 40), M.glow.clone());
      disc.rotation.y = -Math.PI / 2; disc.position.set(X(22.4), 0, z); fixed.add(disc); glows.push(disc);
      const plume = new THREE.Mesh(new THREE.ConeGeometry(r * .7, 1, 40, 1, true), M.plume.clone());
      plume.rotation.z = Math.PI / 2; plume.position.set(X(22.8), 0, z); fixed.add(plume); plumes.push(plume);
    }
  }

  // Landing gear (fixed)
  const legs = GEAR.legs.map(({ s, z }) => {
    const base = new THREE.Group();
    base.position.set(X(s), -SHIP.hullR, z); fixed.add(base);
    add(new THREE.BoxGeometry(1.1, .02, 1.1), M.dark, base, false).position.y = -.006;
    add(new THREE.CylinderGeometry(.22, .22, 1.25, 24), M.steel, base).position.y = .66;
    const piston = new THREE.Group(); base.add(piston);
    add(new THREE.CylinderGeometry(.15, .15, 2, 20), M.piston, piston).position.y = 1.05;
    add(new THREE.CylinderGeometry(GEAR.padR, GEAR.padR * 1.08, .1, 32), M.dark, piston).position.y = .05;
    const doors = [-1, 1].map(sd => {
      const hinge = new THREE.Group(); hinge.position.set(0, -.01, sd * .55); base.add(hinge);
      add(new THREE.BoxGeometry(1.06, .04, .53), M.hull, hinge).position.set(0, -.02, -sd * .265);
      return { hinge, sd };
    });
    return { piston, doors };
  });

  // Cabin interior (fixed)
  const cabin = new THREE.Group(); fixed.add(cabin);
  {
    const fl = CABIN.floor;
    const box = (s0, s1, z0, z1, h, mat, y = fl) => {
      const b = add(new THREE.BoxGeometry(s1 - s0, h, z1 - z0), mat, cabin);
      b.position.set(X((s0 + s1) / 2), y + h / 2, (z0 + z1) / 2);
      return b;
    };
    const halfW = y => Math.sqrt(CABIN.r * CABIN.r - y * y) - .02;
    box(1.2, 3.4, -.85, .85, .04, M.floor, fl - .04);
    box(3.4, CABIN.neck[0], -halfW(fl), halfW(fl), .04, M.floor, fl - .04);
    box(CABIN.neck[0], CABIN.neck[1], -.75, .75, .04, M.floor, fl - .04);
    box(CABIN.neck[1], ST.keel[1], -halfW(fl), halfW(fl), .04, M.floor, fl - .04);
    box(1.3, 1.7, -.7, .7, .7, M.dark);
    for (const z of [-.45, .45]) { box(2, 2.5, z - .25, z + .25, .5, M.orange); box(2.45, 2.6, z - .25, z + .25, 1.15, M.orange); }
    for (let i = 0; i < 7; i++) box(4 + i * .13, 4.03 + i * .13, -.5, .5, .03, M.steel, fl + .02);
    for (const z of [-.52, .52]) box(3.95, 4.9, z - .02, z + .02, .05, M.steel, fl + .02);
    for (const sd of [-1, 1]) {
      box(5.1, 6.8, Math.min(sd * .75, sd * 1.25), Math.max(sd * .75, sd * 1.25), 1.5, M.orange);
      box(5.1, 6.8, sd * .76 - .015, sd * .76 + .015, 1.5, M.dark);
    }
    {
      const ring = add(new THREE.RingGeometry(.75, 1.2, 48), M.amber, cabin, false);
      ring.rotation.x = -Math.PI / 2; ring.position.set(X(8.8), fl + .005, 0);
      add(new THREE.CylinderGeometry(.55, .6, .85, 40), M.dark, cabin).position.set(X(8.8), fl + .42, 0);
      add(new THREE.CylinderGeometry(.5, .5, .02, 40), M.screen, cabin, false).position.set(X(8.8), fl + .86, 0);
      for (let i = 0; i < 6; i++) {
        const a = i / 6 * Math.PI * 2 + .5, s = 8.8 + Math.cos(a) * 1.25, z = Math.sin(a);
        box(s - .2, s + .2, z - .2, z + .2, .45, M.grey);
      }
    }
    {
      const s0 = RAMP.hingeS - RAMP.len, s1 = RAMP.hingeS;
      box(s0, s1, -.62, .62, .01, M.dark, fl + .001);
      for (const z of [-.66, .66]) box(s0, s1, z - .04, z + .04, .012, M.amber, fl + .001);
      for (const sd of [-1, 1]) box(s0 + .3, s1 - .3, Math.min(sd * .85, sd * 1.25), Math.max(sd * .85, sd * 1.25), .45, M.grey);
    }
    box(15.6, 18.4, -1.25, -.55, .95, M.steel);
    box(16.4, 17.4, -.4, .4, .45, M.porcelain);
    box(15.6, 18.4, .55, 1.25, .55, M.orange);
    for (const z of [-.5, .5]) box(15.5, 18.5, z - .02, z + .02, 1.9, M.keel);
    box(19.8, 21.6, -.9, .9, 1.1, M.dark);
    box(19.8, 21, -1.3, -1, 1.6, M.steel);
    box(19.8, 21, 1, 1.3, 1.6, M.steel);
  }

  // Rotating centre section
  {
    const [s0, s1] = ST.shell;
    add(lathe([[s0, SHELL.rIn], [s0, SHELL.rOut - .08], [s0 + .08, SHELL.rOut], [s1 - .08, SHELL.rOut], [s1, SHELL.rOut - .08], [s1, SHELL.rIn], [s0, SHELL.rIn]], 96), M.shell, rot);
    for (let i = 0; i < 6; i++) {
      const t = add(new THREE.TorusGeometry(SHELL.rOut + .01, .035, 8, 96), M.collar, rot, false);
      t.rotation.y = Math.PI / 2; t.position.x = X(ST.collar[0] + .25 + i * .24);
    }
    add(lathe([[ST.collar[0] + .15, SHELL.rOut + .005], [ST.collar[1], SHELL.rOut + .005]], 96), M.collar, rot, false);
    add(lathe([[17.4, SHELL.rOut + .006], [18.2, SHELL.rOut + .006]], 96), M.red, rot, false);
  }

  // Internal ring gear (rotates with the wing)
  {
    const g = new THREE.ExtrudeGeometry(gearShape(RING.z, RING.rp, RING.m, true, RING.rOut), { depth: RING.face, bevelEnabled: false, curveSegments: 2 });
    g.rotateY(-Math.PI / 2); g.translate(X(RING.s0), 0, 0);
    const ring = new THREE.Group(); add(g, M.brass, ring); rot.add(ring);
  }

  // Wing halves with markings
  {
    const stripeA = [[16.6, 6.4], [19.2, 6.4], [11.9, 13.3], [9.6, 13.3]];
    const stripeB = [[10.2, 5.2], [11.6, 5.2], [7.2, 10.6], [6.3, 10.6]];
    const stripeC = [[19, 8.6], [20.6, 8.6], [20.6, 10], [15.3, 15.4], [14.2, 15.4]];
    const seam = [[5.6, 5.3], [18.6, 5.3]];
    const band = leadingEdgeBand(1.1);
    for (const side of [1, -1]) {
      add(wingGeo(side), M.wing, rot);
      for (const p of [stripeA, stripeB, stripeC]) rot.add(wingDecal(p, side, M.red));
      rot.add(wingDecal(band, side, M.grey));
      rot.add(panelLines([[...stripeA, stripeA[0]], [...stripeB, stripeB[0]], [...stripeC, stripeC[0]], seam], side, M.line));
    }
  }

  // Wing-root pods
  {
    const [s0, s1] = POD.s;
    const prof = [[s0, 0], [s0 + .15, .45], [s0 + .5, .78], [s0 + 1.1, .96], [s0 + 1.8, 1], [s1 - 1.4, 1], [s1 - .5, .88], [s1, .5], [s1, 0]];
    for (const side of [1, -1]) {
      const pod = add(lathe(prof, 48), M.pod, rot);
      pod.scale.set(1, POD.a, POD.b); pod.position.y = side * POD.rc;
      for (const f of [-1, 1]) {
        const t = add(new THREE.TorusGeometry(.42, .06, 10, 36), M.dark, rot, false);
        t.position.set(X(6.9), side * (POD.rc + .15), f * (POD.b * .93));
        const c = add(new THREE.CircleGeometry(.4, 32), M.grey, rot, false);
        c.position.copy(t.position); c.position.z += f * .01; if (f < 0) c.rotation.y = Math.PI;
      }
      add(new THREE.SphereGeometry(.42, 24, 16), M.dark, rot).position.set(X(s1 - .7), side * (POD.rc + POD.a * .85), 0);
      const gun = add(new THREE.CylinderGeometry(.05, .05, 1.1, 8), M.dark, rot);
      gun.rotation.z = Math.PI / 2; gun.position.set(X(s1 - .2), side * (POD.rc + POD.a * .85), 0);
      const stripe = add(lathe([[9.8, 1.005], [10.6, 1.005]], 48), M.red, rot, false);
      stripe.scale.set(1, POD.a, POD.b); stripe.position.y = side * POD.rc;
    }
  }

  // Boarding ramp (hinged in the rotating section)
  const rampMount = new THREE.Group(); rampMount.rotation.x = -Math.PI / 2; rot.add(rampMount);
  const rampHinge = new THREE.Group(); rampHinge.position.set(X(RAMP.hingeS), -SHIP.hullR, 0); rampMount.add(rampHinge);
  {
    add(roundedBox(RAMP.len, .12, RAMP.w, 2, .04), M.ramp, rampHinge).position.set(RAMP.len / 2, .06, 0);
    for (let i = 1; i < 9; i++) add(new THREE.BoxGeometry(.06, .03, RAMP.w * .8), M.dark, rampHinge, false).position.set(i * (RAMP.len / 9), -.01, 0);
    add(new THREE.CylinderGeometry(.09, .09, RAMP.w, 16), M.steel, rampHinge).rotation.x = Math.PI / 2;
  }

  const coldGlow = new THREE.Color("#3a3f47"), hotGlow = new THREE.Color(COL.glow);
  function update(c, fx = {}) {
    rot.rotation.x = c.roll * D2R;
    pinion.rotation.x = c.pinion * D2R + Math.PI / PIN.z;
    for (const leg of legs) {
      const open = Math.min(1, c.stroke / .25);
      leg.piston.position.y = -c.stroke;
      for (const d of leg.doors) d.hinge.rotation.x = -d.sd * (Math.PI / 2) * open;
    }
    rampHinge.rotation.z = -c.ramp * D2R;
    for (const g of glows) g.material.color.copy(coldGlow).lerp(hotGlow, c.glow);
    for (const p of plumes) {
      const len = .2 + 5.5 * c.glow;
      p.scale.set(1, len, 1); p.position.x = X(22.8) - len / 2;
      p.visible = c.glow > .01; p.material.opacity = .42 * c.glow;
    }
    const pulse = (a, b) => Math.sin(Math.PI * clamp01((c.p - a) / (b - a)));
    M.brass.emissiveIntensity = .3 * pulse(0, .5);
    M.pinion.emissiveIntensity = .7 * pulse(0, .5);
    M.piston.emissiveIntensity = .7 * pulse(.5, .75);
    M.ramp.emissiveIntensity = .45 * pulse(.75, 1);
    const xray = fx.xray ?? 0, alpha = 1 - .82 * xray;
    for (const m of skin) { m.opacity = alpha; m.depthWrite = alpha > .6; }
    M.line.opacity = .45 * (1 - xray);
    cut.constant = (fx.cut ?? 0) > .001 ? root.position.y + .25 + (1 - fx.cut) * 6 : 1e4;
  }
  return { root, update };
}

// ---------- the stage: dark pad, studio lighting ----------
const DARK = { bg: "#0d1014", ground: "#14181d", grid: "#1b2026", mark: "#2c333c" };

const GROUND_VS = "varying vec3 vW; void main(){ vec4 w = modelMatrix * vec4(position, 1.0); vW = w.xyz; gl_Position = projectionMatrix * viewMatrix * w; }";
const GROUND_FS = `uniform vec3 uG; uniform vec3 uM; uniform vec3 uL; uniform vec3 uBg; uniform vec3 uC; varying vec3 vW;
void main(){
  vec2 p = vW.xz;
  float r = length(p);
  float m = 0.0;
  m = max(m, 1.0 - smoothstep(0.18, 0.26, abs(r - 21.0)));
  m = max(m, 1.0 - smoothstep(0.08, 0.14, abs(r - 23.0)));
  float dash = step(mod(r, 3.0), 1.6) * step(r, 19.0) * step(4.0, r);
  m = max(m, dash * (1.0 - smoothstep(0.12, 0.2, min(abs(p.x), abs(p.y)))));
  vec2 g = abs(fract(p / 2.0 + 0.5) - 0.5) * 2.0;
  float grid = 1.0 - smoothstep(0.0, 0.04, min(g.x, g.y));
  vec3 col = mix(uG, uL, grid * 0.6);
  col = mix(col, uM, m * 0.9);
  float n = fract(sin(dot(floor(vW.xz * 20.0), vec2(12.9898, 78.233))) * 43758.5453);
  col *= 0.985 + 0.03 * n;
  float d = length(vW.xz - uC.xz);
  gl_FragColor = vec4(mix(col, uBg, smoothstep(45.0, 110.0, d)), 1.0);
  #include <colorspace_fragment>
}`;

function createStage(canvas) {
  const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, powerPreference: "high-performance" });
  renderer.toneMapping = THREE.NeutralToneMapping;
  renderer.outputColorSpace = THREE.SRGBColorSpace;
  renderer.shadowMap.enabled = true;
  renderer.shadowMap.type = THREE.VSMShadowMap;
  renderer.localClippingEnabled = true;

  const scene = new THREE.Scene();
  scene.background = new THREE.Color(DARK.bg);
  scene.fog = new THREE.Fog(DARK.bg, 120, 320);
  const camera = new THREE.PerspectiveCamera(28, 16 / 9, .2, 800);

  // Dark studio environment: black room, a few soft boxes, a dim floor.
  {
    const env = new THREE.Scene();
    env.background = new THREE.Color("#141820");
    const panel = (w, h, at, k) => {
      const p = new THREE.Mesh(new THREE.PlaneGeometry(w, h), new THREE.MeshBasicMaterial({ color: new THREE.Color(.97, .98, 1).multiplyScalar(k), side: THREE.DoubleSide }));
      p.position.copy(at); p.lookAt(0, 0, 0); env.add(p);
    };
    panel(12, 12, new THREE.Vector3(0, 14, 2), 2.6);
    panel(3, 14, new THREE.Vector3(-12, 4, 6), 3);
    panel(3, 14, new THREE.Vector3(12, 4, -4), 2);
    panel(18, 2, new THREE.Vector3(0, 2, 14), 1.4);
    const floor = new THREE.Mesh(new THREE.CircleGeometry(40, 32), new THREE.MeshBasicMaterial({ color: "#23282f", side: THREE.DoubleSide }));
    floor.rotation.x = -Math.PI / 2; floor.position.y = -2; env.add(floor);
    const pmrem = new THREE.PMREMGenerator(renderer);
    scene.environment = pmrem.fromScene(env, .02).texture;
    scene.environmentIntensity = 1;
    pmrem.dispose();
  }

  const sunDir = new THREE.Vector3(.45, .85, .35).normalize();
  const sun = new THREE.DirectionalLight("#fff4e8", 2.6);
  sun.castShadow = true;
  const ext = 21;
  Object.assign(sun.shadow.camera, { left: -ext, right: ext, top: ext, bottom: -ext, near: 1, far: 140 });
  sun.shadow.mapSize.set(4096, 4096);
  sun.shadow.radius = 8; sun.shadow.blurSamples = 16; sun.shadow.bias = -4e-4; sun.shadow.normalBias = .03;
  scene.add(sun, sun.target);
  scene.add(new THREE.HemisphereLight("#c4d0e0", "#20252c", 1.1));
  const rim = new THREE.DirectionalLight("#8fb2ff", .9);
  rim.position.set(-.6, .3, -.75);
  scene.add(rim);

  const groundMat = new THREE.ShaderMaterial({
    vertexShader: GROUND_VS, fragmentShader: GROUND_FS, toneMapped: false,
    uniforms: {
      uG: { value: new THREE.Color(DARK.ground) }, uM: { value: new THREE.Color(DARK.mark) },
      uL: { value: new THREE.Color(DARK.grid) }, uBg: { value: new THREE.Color(DARK.bg) },
      uC: { value: new THREE.Vector3() },
    },
  });
  const ground = new THREE.Mesh(new THREE.PlaneGeometry(600, 600), groundMat);
  ground.rotation.x = -Math.PI / 2; scene.add(ground);
  const catcher = new THREE.Mesh(new THREE.PlaneGeometry(600, 600),
    new THREE.ShadowMaterial({ color: "#000000", opacity: .55, polygonOffset: true, polygonOffsetFactor: -4, polygonOffsetUnits: -8 }));
  catcher.rotation.x = -Math.PI / 2; catcher.receiveShadow = true; scene.add(catcher);

  const ship = buildShip();
  scene.add(ship.root);

  // Shadow camera follows the ship, snapped to whole texels so the shadow doesn't shimmer.
  const across = new THREE.Vector3().crossVectors(new THREE.Vector3(0, 1, 0), sunDir).normalize();
  const upish = new THREE.Vector3().crossVectors(sunDir, across);
  const mid = new THREE.Vector3();
  let texel = 2 * ext / sun.shadow.mapSize.x;

  function resize(w, h, pr, fov) {
    renderer.setPixelRatio(pr);
    renderer.setSize(w, h, false);
    camera.aspect = w / h; camera.fov = fov;
    camera.updateProjectionMatrix();
  }
  function setShadowSize(n) {
    sun.shadow.mapSize.set(n, n);
    sun.shadow.map?.dispose(); sun.shadow.map = null;
    texel = 2 * ext / n;
  }
  function frame(c, fx, cam) {
    ship.root.position.set(0, c.height, 0);
    ship.root.updateMatrixWorld();
    ship.update(c, fx);
    const tx = cam.tx, ty = cam.ty + c.height, tz = cam.tz;
    camera.position.set(
      tx + cam.d * Math.cos(cam.el) * Math.sin(cam.az),
      ty + cam.d * Math.sin(cam.el),
      tz + cam.d * Math.cos(cam.el) * Math.cos(cam.az));
    camera.lookAt(tx, ty, tz);
    camera.updateMatrixWorld();
    groundMat.uniforms.uC.value.set(tx, 0, tz);
    mid.set(0, c.height * .5, 0);
    const a = Math.round(mid.dot(across) / texel) * texel, b = Math.round(mid.dot(upish) / texel) * texel;
    sun.target.position.copy(across).multiplyScalar(a).addScaledVector(upish, b).addScaledVector(sunDir, mid.dot(sunDir));
    sun.position.copy(sun.target.position).addScaledVector(sunDir, 60);
    sun.target.updateMatrixWorld();
    renderer.render(scene, camera);
  }
  return { renderer, scene, camera, resize, setShadowSize, frame };
}

// ---------- the tour: one 34-second loop ----------
const LOOP = 34, RATE = 1 / 12;
const TIMELINE = [
  { t: 0, seq: "launch", view: "hero" },
  { t: 2.2, seq: "land" },
  { t: 2.7, view: "rear" },
  { t: 5.4, view: "drive" },
  { t: 5.9, fx: "cutaway" },
  { t: 8.6, fx: "cutaway" },
  { t: 8.9, view: "gear" },
  { t: 11.6, view: "side" },
  { t: 14.9, view: "plan" },
  { t: 15.4, fx: "cutaway" },
  { t: 19.8, fx: "cutaway" },
  { t: 20.2, view: "hero" },
  { t: 20.6, seq: "launch" },
  { t: 21.2, fx: "xray" },
  { t: 25.6, fx: "xray" },
  { t: 26, view: "rear" },
  { t: 30.2, fx: "orbit" },
];
const FX = ["cutaway", "xray", "orbit"];

const SEQS = TIMELINE.filter(e => e.seq);
const SEQ_P = [];
{
  let p = 0, prev = null;
  for (const e of SEQS) {
    if (prev) p = clamp01(p + (prev.seq === "land" ? 1 : -1) * RATE * (e.t - prev.t));
    SEQ_P.push(p); prev = e;
  }
}
function progressAt(t) {
  let i = 0;
  while (i < SEQS.length - 1 && SEQS[i + 1].t <= t) i++;
  return clamp01(SEQ_P[i] + (SEQS[i].seq === "land" ? 1 : -1) * RATE * (t - SEQS[i].t));
}
function fxAt(t) {
  const on = Object.fromEntries(FX.map(k => [k, 0]));
  for (const e of TIMELINE) if (e.fx && e.t <= t) on[e.fx] = on[e.fx] ? 0 : 1;
  return on;
}
const lastToggle = (k, t) => TIMELINE.filter(e => e.fx === k && e.t <= t).pop()?.t ?? -9;

const VIEWS = {
  hero: t => ({ tx: 0, ty: -1, tz: 0, az: 38 + 1.5 * t, el: 18, d: 104 }),
  rear: t => ({ tx: 0, ty: -1, tz: 0, az: 270 + .6 * t, el: 5, d: 86 }),
  side: t => ({ tx: 0, ty: -1.5, tz: 0, az: 184 + .5 * t, el: 5, d: 60 }),
  plan: t => ({ tx: -.5, ty: 0, tz: 0, az: 270, el: 88.5 - .15 * t, d: 66 }),
  drive: t => ({ tx: X(4.45), ty: .6, tz: 0, az: 232 + 2 * t, el: 34, d: 13 }),
  gear: t => ({ tx: X(13), ty: -2.2, tz: 0, az: 328 + 1.2 * t, el: 9, d: 44 }),
};
const SHOTS = TIMELINE.filter(e => e.view).map(e => [e.t, e.view]);

function blendCam(a, b, k) {
  const out = {};
  const dAz = (b.az - a.az + 540) % 360 - 180;
  for (const key in b) out[key] = key === "az" ? a.az + dAz * k : a[key] + (b[key] - a[key]) * k;
  const swing = Math.min(1, Math.abs(dAz) / 90);
  out.d += Math.max(0, Math.max(a.d, b.d) * (1 + .15 * swing) - out.d) * Math.sin(Math.PI * k) * swing;
  return out;
}
function camAt(t) {
  let i = 0;
  while (i < SHOTS.length - 1 && SHOTS[i + 1][0] <= t) i++;
  let cam = VIEWS[SHOTS[i][1]](t - SHOTS[i][0]);
  if (i > 0) {
    const k = phase(SHOTS[i][0], SHOTS[i][0] + 1.8, t);
    if (k < 1) cam = blendCam(VIEWS[SHOTS[i - 1][1]](t - SHOTS[i - 1][0]), cam, k);
  }
  if (fxAt(t).orbit) cam = { ...cam, az: cam.az + 12 * Math.max(0, t - lastToggle("orbit", t)) };
  return cam;
}

// ---------- run ----------
const DESIGN_ASPECT = 16 / 9, ZOOM = .9, WRAP_BLEND = 1.8;

function main() {
  const app = document.getElementById("app");
  const canvas = document.createElement("canvas");
  canvas.id = "gl";
  canvas.setAttribute("role", "img");
  canvas.setAttribute("aria-label", "Animated 3D shuttle rolling its wing, landing and taking off");
  app.appendChild(canvas);
  const stage = createStage(canvas);

  const tiers = [{ shadow: 4096, pr: 2 }, { shadow: 2048, pr: 1.5 }, { shadow: 1024, pr: 1 }];
  let tier = (matchMedia("(pointer: coarse)").matches || Math.min(innerWidth, innerHeight) < 700) ? 2 : 0;
  let distK = 1;
  const layout = () => {
    const W = Math.max(1, innerWidth), H = Math.max(1, innerHeight);
    const pr = Math.max(.5, Math.min(clamp(devicePixelRatio || 1, .75, tiers[tier].pr), Math.sqrt(5e6 / (W * H))));
    // Narrower than 16:9: widen the lens a little, then pull back, so the whole ship stays in frame.
    const k = Math.max(1, Math.pow(DESIGN_ASPECT / (W / H), .75)), kf = Math.min(k, 1.6);
    stage.resize(W, H, pr, 2 * Math.atan(Math.tan(14 * D2R) * kf) / D2R);
    distK = k / kf;
    stage.scene.fog.near = 120 * distK; stage.scene.fog.far = 320 * distK;
  };
  const applyTier = () => { stage.setShadowSize(tiers[tier].shadow); layout(); };
  applyTier();
  addEventListener("resize", layout);

  let clock = 0;
  const fxState = Object.fromEntries(FX.map(k => [k, { on: 0, t: -9 }]));
  const fade = (k, dur = .7) => { const s = fxState[k], z = phase(s.t, s.t + dur, clock); return s.on ? z : 1 - z; };
  const syncFx = t => {
    const want = fxAt(t);
    for (const k of FX) if (fxState[k].on !== want[k]) { fxState[k].on = want[k]; fxState[k].t = clock; }
  };
  const endCam = camAt(LOOP - .01);
  const goalAt = t => {
    let c = camAt(t);
    if (clock >= LOOP && t < WRAP_BLEND) c = blendCam(endCam, c, phase(0, WRAP_BLEND, t));
    return { ...c, d: c.d * ZOOM * distK };
  };
  const cam = goalAt(0);

  const perf = { n: 0, sum: 0, slow: 0, age: 0 };
  let last = performance.now();
  const tick = now => {
    const dt = Math.min(.1, Math.max(0, (now - last) / 1e3));
    last = now; clock += dt;

    // Step quality down if frames run long.
    if (tier < tiers.length - 1) {
      perf.age += dt;
      if (perf.age > .6) {
        perf.sum += dt; perf.n++;
        if (perf.sum >= .5 && perf.n >= 6) {
          perf.slow = perf.sum / perf.n > .022 ? perf.slow + 1 : 0;
          perf.sum = 0; perf.n = 0;
          if (perf.slow >= (perf.age < 6 ? 1 : 2)) { tier++; applyTier(); Object.assign(perf, { age: 0, slow: 0 }); }
        }
      }
    }

    const t = clock % LOOP;
    syncFx(t);
    const goal = goalAt(t);
    const k = 1 - Math.exp(-dt / .18);
    cam.az += wrapDeg(goal.az - cam.az) * k;
    for (const key of ["tx", "ty", "tz", "el", "d"]) cam[key] += (goal[key] - cam[key]) * k;
    stage.frame(config(progressAt(t)), { xray: fade("xray"), cut: fade("cutaway", .9) },
      { ...cam, az: cam.az * D2R, el: cam.el * D2R });
    requestAnimationFrame(tick);
  };

  const start = () => { last = performance.now(); requestAnimationFrame(tick); };
  stage.frame(config(0), {}, { ...cam, az: cam.az * D2R, el: cam.el * D2R });
  Promise.race([
    stage.renderer.compileAsync(stage.scene, stage.camera).catch(() => {}),
    new Promise(r => setTimeout(r, 1500)),
  ]).then(start);
}

function fail(msg) {
  const el = document.getElementById("msg");
  if (el) { el.textContent = msg; el.hidden = false; }
}

async function boot() {
  try { THREE = await import(THREE_URL); }
  catch { fail("The 3D library didn't load. Check your connection and reload the page."); return; }
  try { main(); }
  catch (e) { console.error(e); fail("This animation needs WebGL, which isn't available in this browser."); }
}
boot();
</script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.