• 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
  • Wireframe Spider
  • Wireframe Fly
  • Wireframe Scorpion
  • Wireframe Mosquito
  • Wireframe Bee
  • Wireframe Butterfly
  • Wireframe Locust

WIREFRAME SPIDER SOURCE CODE

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Aether — Spider</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { background: #000; overflow: hidden; height: 100vh; cursor: grab; touch-action: none; }
        body.dragging { cursor: grabbing; }
        #bgCanvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 1; }
        #animationCanvas { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 2; }
    </style>
</head>
<body>
    <canvas id="bgCanvas"></canvas>
    <canvas id="animationCanvas"></canvas>

    <script>
        const colors = {
            primary: 0x4db8d4,
            mid:     0x2a7f99,
            dark1:   0x0d2a3a,
            dark3:   0x000000,
            light:   0xaee8f5
        };

        // ── THEME SYNC ──
        function syncTheme() {
            try {
                let isDark = true;
                if (window.parent && window.parent.document) {
                    isDark = window.parent.document.documentElement.classList.contains('dark');
                }
                if (!isDark) {
                    document.body.style.backgroundColor = '#ffffff';
                    colors.dark3 = 0xffffff;
                    colors.dark1 = 0xcccccc;
                    if (typeof scene !== 'undefined' && scene) {
                        scene.background = new THREE.Color(colors.dark3);
                    }
                } else {
                    document.body.style.backgroundColor = '#000000';
                    colors.dark3 = 0x000000;
                    colors.dark1 = 0x0d2a3a;
                    if (typeof scene !== 'undefined' && scene) {
                        scene.background = new THREE.Color(colors.dark3);
                    }
                }
            } catch (e) {}
        }
        syncTheme();
        if (window.parent && window.parent.document) {
            try {
                var observer = new MutationObserver(syncTheme);
                observer.observe(window.parent.document.documentElement, { attributes: true, attributeFilter: ['class'] });
            } catch(e) {}
        }

        // ── Background ──
        const bgCanvas = document.getElementById('bgCanvas');
        const bgCtx = bgCanvas.getContext('2d');
        const pixelSize = 8;
        let cols, rows, pixels = [];

        const RAMP_STEPS = 48;
        const ramp = Array.from({ length: RAMP_STEPS + 1 }, (_, i) => {
            const b = (i / RAMP_STEPS) * 0.4;
            return `rgb(${Math.floor(b*10)},${Math.floor(b*30)},${Math.floor(b*50)})`;
        });

        function initBackground() {
            bgCanvas.width = window.innerWidth;
            bgCanvas.height = window.innerHeight;
            cols = Math.ceil(bgCanvas.width / pixelSize);
            rows = Math.ceil(bgCanvas.height / pixelSize);
            pixels = [];
            for (let i = 0; i < cols * rows; i++)
                pixels.push({ brightness: Math.random() * 0.3, speed: 0.001 + Math.random() * 0.003 });
        }

        let bgFrame = 0;
        function animateBackground() {
            if ((bgFrame++ & 1) === 0) {
                for (let y = 0; y < rows; y++) {
                    for (let x = 0; x < cols; x++) {
                        const p = pixels[y * cols + x];
                        p.brightness += p.speed * 2;
                        if (p.brightness > 0.4) p.brightness = 0;
                        bgCtx.fillStyle = ramp[Math.min(RAMP_STEPS, (p.brightness * RAMP_STEPS / 0.4) | 0)];
                        bgCtx.fillRect(x * pixelSize, y * pixelSize, pixelSize, pixelSize);
                    }
                }
            }
            requestAnimationFrame(animateBackground);
        }

        // ── Three.js ──
        const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('animationCanvas'), antialias: true, alpha: true });
        let scene, camera, spider, body, abdPivot, abd;
        const legs = [], palps = [], chelicerae = [], spinnerets = [], eyeMats = [];
        let dragline, draglineTip, dewMat;

        // Anatomy reference frames (body-local). Ellipsoids are described by
        // centre + semi-axes so surface details can be projected onto them.
        const C_CEPH = new THREE.Vector3(0, 0.06, 0.40);
        const R_CEPH = new THREE.Vector3(0.456, 0.336, 0.538);
        const C_ABD  = new THREE.Vector3(0, 0.05, -0.95);
        const R_ABD  = new THREE.Vector3(0.634, 0.547, 0.878);
        const WEB_Y  = -0.62;            // height of the sheet web the feet rest on
        const DRAG_END = new THREE.Vector3(0.2, WEB_Y, -2.05);

        // Seeded RNG so hair / spine placement is identical on every load
        function mulberry32(a) {
            return function () {
                a |= 0; a = a + 0x6D2B79F5 | 0;
                let t = Math.imul(a ^ a >>> 15, 1 | a);
                t = t + Math.imul(t ^ t >>> 7, 61 | t) ^ t;
                return ((t ^ t >>> 14) >>> 0) / 4294967296;
            };
        }
        const rand = mulberry32(20261128);
        const V = (x, y, z) => new THREE.Vector3(x, y, z);

        // ── Materials ── wireframe basic materials ignore lights, so share per colour
        const matCache = new Map();
        function mat(color) {
            if (!matCache.has(color))
                matCache.set(color, new THREE.MeshBasicMaterial({ color, wireframe: true }));
            return matCache.get(color);
        }
        const lineCache = new Map();
        function lmat(color, opacity = 1) {
            const key = color + ':' + opacity;
            if (!lineCache.has(key))
                lineCache.set(key, new THREE.LineBasicMaterial({ color, transparent: opacity < 1, opacity }));
            return lineCache.get(key);
        }

        // ── Geometry helpers ──
        function tube(p0, p1, radius, color, mid) {
            const pts = mid ? [p0, mid, p1] : [p0, p1];
            const curve = new THREE.CatmullRomCurve3(pts);
            return new THREE.Mesh(new THREE.TubeGeometry(curve, 8, radius, 6, false), mat(color));
        }

        function ball(r, color, x, y, z, sx = 1, sy = 1, sz = 1, ws = 20, hs = 20) {
            const m = new THREE.Mesh(new THREE.SphereGeometry(r, ws, hs), mat(color));
            m.position.set(x, y, z);
            m.scale.set(sx, sy, sz);
            return m;
        }

        function lineSegs(arr, color, opacity) {
            const g = new THREE.BufferGeometry();
            g.setAttribute('position', new THREE.Float32BufferAttribute(arr, 3));
            return new THREE.LineSegments(g, lmat(color, opacity));
        }

        function polyline(points, color, opacity, loop = false) {
            const g = new THREE.BufferGeometry().setFromPoints(points);
            return new (loop ? THREE.LineLoop : THREE.Line)(g, lmat(color, opacity));
        }

        // Quadratic radius profile: start → bulge → end
        function qb(a, m, b, u) { const v = 1 - u; return v * v * a + 2 * u * v * m + u * u * b; }

        // A lathed limb segment along local +X with a tapered, bulging profile
        function limb(len, r0, rm, r1, color, radial = 8) {
            const pts = [];
            for (let i = 0; i <= 8; i++) {
                const u = i / 8;
                pts.push(new THREE.Vector2(Math.max(qb(r0, rm, r1, u), 0.0015), u * len));
            }
            const geo = new THREE.LatheGeometry(pts, radial);
            geo.rotateZ(-Math.PI / 2);   // lathe axis Y → limb axis X
            return new THREE.Mesh(geo, mat(color));
        }

        // Hairs / spines growing out of a limb segment (local +X axis, +Y dorsal).
        //  arc: [centreAngle, spread] limits them to one face (0 = dorsal, π = ventral)
        //  ordered: evenly spaced alternating rows, as macro-spines are on real legs
        function limbHairs(len, r0, rm, r1, o) {
            const pos = [];
            for (let i = 0; i < o.count; i++) {
                const u = o.ordered ? 0.12 + (i / Math.max(1, o.count - 1)) * 0.76 : 0.04 + rand() * 0.92;
                const r = qb(r0, rm, r1, u);
                let phi;
                if (o.ordered) phi = o.arc[0] + (i % 2 ? 0.5 : -0.5) * o.arc[1];
                else phi = o.arc ? o.arc[0] + (rand() - 0.5) * o.arc[1] : rand() * Math.PI * 2;
                const cy = Math.cos(phi), cz = Math.sin(phi);
                const x = u * len, y = cy * r, z = cz * r;
                const L = o.l0 + rand() * (o.l1 - o.l0);
                const d = V(o.distal + (rand() - 0.5) * 0.3, cy, cz).normalize();
                pos.push(x, y, z, x + d.x * L, y + d.y * L, z + d.z * L);
            }
            return lineSegs(pos, o.color, o.opacity);
        }

        // Ring around the limb axis (annulation bands, joint collars)
        function ring(radius, color, tubeR = 0.12) {
            const geo = new THREE.TorusGeometry(radius, radius * tubeR, 3, 16);
            geo.rotateY(Math.PI / 2);
            return new THREE.Mesh(geo, mat(color));
        }

        // Ellipsoid helpers (local to the ellipsoid's centre)
        function ellY(R, x, z) {
            const k = 1 - (x / R.x) ** 2 - (z / R.z) ** 2;
            return k > 0 ? R.y * Math.sqrt(k) : null;
        }
        function ellNormal(R, p) {
            return V(p.x / (R.x * R.x), p.y / (R.y * R.y), p.z / (R.z * R.z)).normalize();
        }
        function randUnit() {
            const u = rand() * 2 - 1, a = rand() * Math.PI * 2, s = Math.sqrt(1 - u * u);
            return V(s * Math.cos(a), u, s * Math.sin(a));
        }

        // A line drawn on the top (or underside) of an ellipsoid through (x,z) samples
        function surfLine(R, xz, color, opacity, loop = false, below = false) {
            const pts = [];
            for (const [x, z] of xz) {
                const y = ellY(R, x, z);
                if (y === null) continue;
                pts.push(V(x, below ? -y : y, z).multiplyScalar(1.012));
            }
            return polyline(pts, color, opacity, loop);
        }

        // A coat of setae over an ellipsoid; sweep bends them to lie backwards
        function hairField(R, count, l0, l1, sweep, color, opacity, filter) {
            const pos = [];
            let made = 0, guard = 0;
            while (made < count && guard++ < count * 30) {
                const n = randUnit();
                if (filter && !filter(n)) continue;
                const p = V(R.x * n.x, R.y * n.y, R.z * n.z);
                const nrm = ellNormal(R, p);
                const d = nrm.clone().add(sweep).add(V((rand() - .5) * .35, (rand() - .5) * .2, (rand() - .5) * .35)).normalize();
                const L = l0 + rand() * (l1 - l0);
                pos.push(p.x, p.y, p.z, p.x + d.x * L, p.y + d.y * L, p.z + d.z * L);
                made++;
            }
            return lineSegs(pos, color, opacity);
        }

        // Small ring lying flat on a surface with normal n
        function surfaceRing(r, color, p, n) {
            const m = new THREE.Mesh(new THREE.TorusGeometry(r, r * 0.18, 3, 14), mat(color));
            m.position.copy(p);
            m.quaternion.setFromUnitVectors(V(0, 0, 1), n);
            return m;
        }

        // ── Articulated chains ──
        // Each joint is a Group; the segment mesh extends along that joint's +X,
        // the next joint sits at its tip, and bending is rotation about local Z.
        // That gives real knees: rotating the femur carries everything distal.
        function knuckle(r) {
            return new THREE.Mesh(new THREE.SphereGeometry(r, 8, 6), mat(colors.light));
        }

        function buildChain(defs) {
            const root = new THREE.Group();
            const joints = [];
            let parent = root;
            defs.forEach((d, i) => {
                const j = new THREE.Group();
                if (i > 0) j.position.x = defs[i - 1].len;
                j.rotation.z = d.angle;
                parent.add(j);
                joints.push(j);

                j.add(limb(d.len, d.r0, d.rm, d.r1, d.color, d.radial || 8));
                if (d.knuckle !== false) j.add(knuckle(d.r0 * 1.15));

                if (d.hairs) j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                    count: d.hairs, l0: d.r0 * 0.9, l1: d.r0 * 2.1, distal: 1.2,
                    color: colors.primary, opacity: 0.42 }));
                if (d.spines) j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                    count: d.spines, ordered: true, arc: [Math.PI, 1.7],
                    l0: d.r0 * 1.8, l1: d.r0 * 2.6, distal: 1.7,
                    color: colors.light, opacity: 0.95 }));
                if (d.dspines) j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                    count: d.dspines, ordered: true, arc: [0, 0.6],
                    l0: d.r0 * 1.6, l1: d.r0 * 2.2, distal: 1.8,
                    color: colors.light, opacity: 0.85 }));
                if (d.tricho) j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                    count: d.tricho, arc: [0, 0.8], l0: 0.08, l1: 0.13, distal: 0.25,
                    color: colors.light, opacity: 0.3 }));
                if (d.scopula) j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                    count: d.scopula, arc: [Math.PI, 1.5], l0: d.r1 * 0.9, l1: d.r1 * 1.8, distal: 0.5,
                    color: colors.light, opacity: 0.5 }));
                if (d.bands) d.bands.forEach(u => {
                    const b = ring(qb(d.r0, d.rm, d.r1, u) * 1.22, colors.light);
                    b.position.x = u * d.len;
                    j.add(b);
                });
                if (d.extra) d.extra(j, d);
                parent = j;
            });
            return { root, joints };
        }

        // Yaw that points a chain's +X along the outward spoke at fanAngle
        // (measured from +Z forward) on the given side.
        function yawFor(side, fa) {
            return side > 0 ? fa - Math.PI / 2 : -(Math.PI / 2 + fa);
        }

        // Two main tarsal claws, a median claw and a claw tuft
        function addClaws(j, d) {
            const L = d.len;
            const claw = (z, dz, dy, len, r) => {
                const c = new THREE.QuadraticBezierCurve3(V(L, 0, z), V(L + len * 0.85, 0.006, z + dz * 0.5), V(L + len, -dy, z + dz));
                j.add(new THREE.Mesh(new THREE.TubeGeometry(c, 6, r, 4, false), mat(colors.light)));
            };
            claw( 0.007,  0.012, 0.032, 0.048, 0.0045);
            claw(-0.007, -0.012, 0.032, 0.048, 0.0045);
            claw( 0,      0,     0.024, 0.030, 0.0035);
            const tuft = [];
            for (let i = 0; i < 12; i++) {
                const a = (i / 11 - 0.5) * 2.2;
                tuft.push(L * 0.94, -0.006, 0, L + 0.03, -0.022 - rand() * 0.01, Math.sin(a) * 0.026);
            }
            j.add(lineSegs(tuft, colors.light, 0.55));
        }

        // ── Leg segment table ──
        // coxa · trochanter · femur · patella · tibia · metatarsus · tarsus
        function legDefs(sc) {
            const rs = Math.sqrt(sc);
            return [
                { len: .15*sc, r0: .050*rs, rm: .056*rs, r1: .044*rs, color: colors.mid,     angle: .25 },
                { len: .07*sc, r0: .042*rs, rm: .040*rs, r1: .038*rs, color: colors.light,   angle: .12 },
                { len: .70*sc, r0: .036*rs, rm: .043*rs, r1: .030*rs, color: colors.primary, angle: .45,
                  hairs: 46, spines: 6, dspines: 3, bands: [.5] },
                { len: .16*sc, r0: .030*rs, rm: .033*rs, r1: .027*rs, color: colors.mid,     angle: -.75, hairs: 10 },
                { len: .60*sc, r0: .026*rs, rm: .030*rs, r1: .021*rs, color: colors.primary, angle: -.85,
                  hairs: 40, spines: 8, tricho: 3, bands: [.33, .66] },
                { len: .56*sc, r0: .019*rs, rm: .020*rs, r1: .014*rs, color: colors.primary, angle: -.40,
                  hairs: 34, spines: 6, tricho: 2, scopula: 18, bands: [.5] },
                { len: .24*sc, r0: .013*rs, rm: .012*rs, r1: .008*rs, color: colors.light,   angle: -.25,
                  hairs: 16, scopula: 34, extra: addClaws },
            ];
        }

        // Foot height & horizontal reach for a joint-angle set (chain-local)
        function footReach(ang, lens) {
            let c = 0, y = 0, h = 0;
            for (let i = 0; i < ang.length; i++) {
                c += ang[i];
                y += lens[i] * Math.sin(c);
                h += lens[i] * Math.cos(c);
            }
            return [y, h];
        }

        // One-joint IK: bisect the femur angle so the foot lands at targetY
        function solveFemur(leg, targetY) {
            const a = leg.ang;
            let lo = -0.55, hi = 1.4;
            for (let k = 0; k < 16; k++) {
                a[2] = (lo + hi) * 0.5;
                if (footReach(a, leg.lens)[0] < targetY) lo = a[2]; else hi = a[2];
            }
            a[2] = (lo + hi) * 0.5;
            leg.h = footReach(a, leg.lens)[1];
        }

        // ── Body parts ──
        function buildAbdomen() {
            // Pivot at the pedicel so the abdomen sways from the waist
            abdPivot = new THREE.Group();
            abdPivot.position.set(0, 0.04, -0.22);
            abd = new THREE.Group();
            abd.position.copy(C_ABD).sub(abdPivot.position);
            abdPivot.add(abd);

            // Poles run front-to-back so they don't bunch up under the dorsal markings
            const shell = new THREE.Mesh(new THREE.SphereGeometry(1, 36, 26).rotateX(Math.PI / 2), mat(colors.primary));
            shell.scale.copy(R_ABD);
            abd.add(shell);

            // Folium: stacked chevrons pointing forward, fading toward the rear
            for (let i = 0; i < 7; i++) {
                const zc = 0.46 - i * 0.19, w = 0.36 * (1 - i * 0.11), xz = [];
                for (let k = 0; k <= 22; k++) {
                    const u = -1 + 2 * k / 22;
                    xz.push([u * w, zc - Math.abs(u) * 0.17 + 0.018 * Math.cos(u * Math.PI * 3)]);
                }
                abd.add(surfLine(R_ABD, xz, colors.light, 0.9 - i * 0.09));
            }
            // Wavy folium outline
            [-1, 1].forEach(s => {
                const xz = [];
                for (let k = 0; k <= 40; k++) {
                    const z = 0.66 - k * 0.036;
                    const env = Math.sin(Math.PI * (0.66 - z) / 1.5);
                    xz.push([s * (0.08 + 0.24 * env + 0.022 * Math.sin(z * 24)), z]);
                }
                abd.add(surfLine(R_ABD, xz, colors.light, 0.55));
            });
            // Cardiac mark
            const cm = [];
            for (let k = 0; k < 28; k++) {
                const a = k / 28 * Math.PI * 2;
                cm.push([0.05 * Math.sin(a) * (0.75 + 0.25 * Math.cos(a)), 0.58 + 0.19 * Math.cos(a)]);
            }
            abd.add(surfLine(R_ABD, cm, colors.light, 0.95, true));
            // Sigilla: muscle-attachment dimples
            [[0.11, 0.30], [0.15, 0.10], [0.13, -0.12]].forEach(([x, z]) => {
                [-1, 1].forEach(s => {
                    const p = V(s * x, ellY(R_ABD, s * x, z), z).multiplyScalar(1.01);
                    abd.add(surfaceRing(0.022, colors.mid, p, ellNormal(R_ABD, p)));
                });
            });
            // Underside: epigastric furrow and book-lung slits
            const furrow = [];
            for (let k = 0; k <= 16; k++) furrow.push([-0.27 + k * 0.034, 0.6 + 0.04 * Math.cos((k / 16 - .5) * Math.PI)]);
            abd.add(surfLine(R_ABD, furrow, colors.light, 0.7, false, true));
            [-1, 1].forEach(s => {
                const slit = [];
                for (let k = 0; k < 16; k++) {
                    const a = k / 16 * Math.PI * 2;
                    slit.push([s * 0.15 + 0.05 * Math.cos(a), 0.69 + 0.018 * Math.sin(a)]);
                }
                abd.add(surfLine(R_ABD, slit, colors.light, 0.6, true, true));
            });

            // Coat of setae + sparse long bristles
            abd.add(hairField(R_ABD, 750, 0.035, 0.08, V(0, 0.1, -0.9), colors.primary, 0.36));
            abd.add(hairField(R_ABD, 70, 0.1, 0.16, V(0, 0.35, -0.6), colors.light, 0.45, n => n.y > 0));

            // Spinnerets: anterior, median and posterior pairs
            const sn = V(0, -0.42, -0.9).normalize();
            const sBase = new THREE.Group();
            sBase.position.set(R_ABD.x * sn.x, R_ABD.y * sn.y, R_ABD.z * sn.z).multiplyScalar(0.985);
            abd.add(sBase);
            const sDefs = [
                { off: [0.055, -0.02,  0.00], spread: 0.45, rz: -0.55, segs: [[.065, .026, .024, .018], [.04, .017, .016, .01]] },
                { off: [0.020,  0.00, -0.01], spread: 0.15, rz: -0.35, segs: [[.05, .012, .012, .007]] },
                { off: [0.045,  0.035,-0.02], spread: 0.35, rz: -0.15, segs: [[.07, .018, .017, .013], [.05, .012, .011, .005]] },
            ];
            sDefs.forEach((sd, k) => {
                [-1, 1].forEach(s => {
                    const ch = buildChain(sd.segs.map(([len, r0, rm, r1], i) => ({
                        len, r0, rm, r1, color: i ? colors.light : colors.mid, angle: i ? 0.25 : sd.rz, radial: 6
                    })));
                    ch.root.position.set(s * sd.off[0], sd.off[1], sd.off[2]);
                    ch.root.rotation.y = Math.PI / 2 - s * sd.spread;
                    sBase.add(ch.root);
                    spinnerets.push({ joint: ch.joints[0], rz: sd.rz, i: k * 2 + (s > 0 ? 1 : 0) });
                    if (k === 2 && s > 0) {
                        draglineTip = new THREE.Object3D();
                        draglineTip.position.x = sd.segs[1][0];
                        ch.joints[1].add(draglineTip);
                    }
                });
            });
            return abdPivot;
        }

        function buildCephalothorax(g) {
            const ceph = new THREE.Group();
            ceph.position.copy(C_CEPH);
            g.add(ceph);

            const shell = new THREE.Mesh(new THREE.SphereGeometry(1, 30, 22).rotateX(Math.PI / 2), mat(colors.primary));
            shell.scale.copy(R_CEPH);
            ceph.add(shell);

            // Fovea
            const fz = -0.12;
            const fy = ellY(R_CEPH, 0, fz);
            const fov = new THREE.Mesh(new THREE.OctahedronGeometry(0.065, 0), mat(colors.light));
            fov.position.set(0, fy + 0.01, fz); fov.scale.set(0.8, 0.35, 1.1);
            ceph.add(fov);

            // Radial striae from the fovea down the carapace
            for (let i = 0; i < 12; i++) {
                const a = (i + 0.5) / 12 * Math.PI * 2, xz = [];
                for (let s = 0.06; s < 0.6; s += 0.02) {
                    const x = Math.sin(a) * s * 0.9, z = fz + Math.cos(a) * s;
                    const k = 1 - (x / R_CEPH.x) ** 2 - (z / R_CEPH.z) ** 2;
                    if (k < 0.22) break;
                    xz.push([x, z]);
                }
                ceph.add(surfLine(R_CEPH, xz, colors.light, 0.45));
            }
            // Cervical groove: separates head region from thorax
            const cg = [];
            for (let k = 0; k <= 20; k++) {
                const u = -1 + 2 * k / 20;
                cg.push([u * 0.26, 0.1 - Math.abs(u) * 0.12 + 0.05 * (1 - u * u)]);
            }
            ceph.add(surfLine(R_CEPH, cg, colors.light, 0.6));

            // Marginal band around the carapace edge
            const yb = -0.07, sc = Math.sqrt(1 - (yb / R_CEPH.y) ** 2) * 1.012, band = [];
            for (let k = 0; k < 48; k++) {
                const a = k / 48 * Math.PI * 2;
                band.push(V(R_CEPH.x * sc * Math.sin(a), yb, R_CEPH.z * sc * Math.cos(a)));
            }
            ceph.add(polyline(band, colors.light, 0.75, true));

            // Setae, keeping the ocular area clear
            ceph.add(hairField(R_CEPH, 280, 0.02, 0.045, V(0, 0.25, -0.75), colors.primary, 0.45,
                n => n.y > -0.15 && n.z < 0.6));

            // ── EYES ── 8 eyes, projected onto the carapace front, each with socket ring and lens
            const eyeDefs = [
                [-0.09, 0.28, 0.056, 0],  // AME L (large)
                [ 0.09, 0.28, 0.056, 0],  // AME R (large)
                [-0.23, 0.21, 0.036, 1],  // ALE L
                [ 0.23, 0.21, 0.036, 1],  // ALE R
                [-0.12, 0.36, 0.030, 1],  // PME L
                [ 0.12, 0.36, 0.030, 1],  // PME R
                [-0.26, 0.30, 0.026, 1],  // PLE L
                [ 0.26, 0.30, 0.026, 1],  // PLE R
            ];
            const eyeA = new THREE.MeshBasicMaterial({ color: colors.light, wireframe: true, transparent: true });
            const eyeB = new THREE.MeshBasicMaterial({ color: colors.primary, wireframe: true, transparent: true });
            eyeMats.push(eyeA, eyeB);
            eyeDefs.forEach(([x, wy, r, kind]) => {
                const yl = wy - C_CEPH.y;
                const k = Math.max(0.02, 1 - (x / R_CEPH.x) ** 2 - (yl / R_CEPH.y) ** 2);
                const p = V(x, yl, R_CEPH.z * Math.sqrt(k));
                const n = ellNormal(R_CEPH, p);
                const c = p.clone().addScaledVector(n, r * 0.45);

                const eye = new THREE.Mesh(new THREE.SphereGeometry(r, 14, 12), kind ? eyeB : eyeA);
                eye.position.copy(c);
                ceph.add(eye);
                const lens = new THREE.Mesh(new THREE.IcosahedronGeometry(r * 0.5, 1), mat(colors.light));
                lens.position.copy(c).addScaledVector(n, r * 0.55);
                ceph.add(lens);
                ceph.add(surfaceRing(r * 1.15, colors.mid, c.clone().addScaledVector(n, -r * 0.2), n));
            });
            // Ocular bristles
            const br = [];
            for (let i = 0; i < 9; i++) {
                const x = (i - 4) * 0.035;
                const yl = 0.24 + (i % 2) * 0.03;
                const k = 1 - (x / R_CEPH.x) ** 2 - (yl / R_CEPH.y) ** 2;
                if (k <= 0) continue;
                const z = R_CEPH.z * Math.sqrt(k);
                const L = 0.11 + rand() * 0.06;
                br.push(x, yl, z, x * 1.3, yl + L * 0.62, z + L * 0.78);
            }
            ceph.add(lineSegs(br, colors.light, 0.7));

            // Carapace ridge line (body coords)
            const ridgeCurve = new THREE.CatmullRomCurve3([V(0, 0.37, 0.68), V(0, 0.40, 0.38), V(0, 0.34, 0.08)]);
            g.add(new THREE.Mesh(new THREE.TubeGeometry(ridgeCurve, 12, 0.016, 6, false), mat(colors.light)));

            // Sternum + labium on the underside
            g.add(ball(1, colors.mid, 0, -0.215, 0.40, 0.27, 0.045, 0.33, 18, 10));
            g.add(ball(1, colors.mid, 0, -0.19, 0.75, 0.07, 0.03, 0.06, 10, 8));
        }

        function buildChelicerae(g) {
            [-1, 1].forEach(s => {
                const ch = buildChain([
                    { len: .27, r0: .062, rm: .070, r1: .042, color: colors.mid, angle: -1.3, hairs: 30 },
                    { len: .13, r0: .020, rm: .017, r1: .002, color: colors.light, angle: -0.3, radial: 6 },
                ]);
                ch.root.position.set(s * 0.105, 0.11, 0.84);
                ch.root.rotation.y = yawFor(s, 0.12);
                ch.joints[1].rotation.y = -s * 1.15;   // fangs fold inward
                // Basal boss
                const boss = ball(0.03, colors.light, 0.05, 0.045, 0, 1, 1, 1, 8, 6);
                ch.joints[0].add(boss);
                g.add(ch.root);
                chelicerae.push({ side: s, base: ch.joints[0], fang: ch.joints[1] });
            });
        }

        function buildPalps(g) {
            [-1, 1].forEach(s => {
                const rest = [-0.35, 0.25, 0.75, -0.55, -0.5, -0.5];
                const ch = buildChain([
                    { len: .08, r0: .035, rm: .036, r1: .030, color: colors.mid,     angle: rest[0] },
                    { len: .05, r0: .028, rm: .030, r1: .026, color: colors.light,   angle: rest[1] },
                    { len: .19, r0: .024, rm: .028, r1: .022, color: colors.primary, angle: rest[2], hairs: 14, dspines: 2 },
                    { len: .07, r0: .022, rm: .024, r1: .021, color: colors.mid,     angle: rest[3], hairs: 5 },
                    { len: .11, r0: .021, rm: .024, r1: .022, color: colors.primary, angle: rest[4], hairs: 12 },
                    { len: .11, r0: .022, rm: .048, r1: .012, color: colors.light,   angle: rest[5], hairs: 10,
                      extra: (j) => {
                          // Palpal bulb with coiled embolus
                          j.add(ball(0.03, colors.primary, 0.05, -0.03, 0, 1, 1, 1, 10, 8));
                          const pts = [];
                          for (let k = 0; k <= 40; k++) {
                              const a = k / 40 * Math.PI * 4;
                              pts.push(V(0.03 + k / 40 * 0.05, -0.03 + Math.cos(a) * 0.034, Math.sin(a) * 0.034));
                          }
                          j.add(polyline(pts, colors.light, 0.85));
                      } },
                ]);
                ch.root.position.set(s * 0.2, 0.04, 0.78);
                ch.root.rotation.y = yawFor(s, 0.42);
                g.add(ch.root);
                palps.push({ side: s, root: ch.root, joints: ch.joints, rest });
            });
        }

        function buildLegs(g) {
            // fanAngle measured from +Z (forward): <90° sweeps forward, >90° back.
            // Legs I and IV are longest, as in most spiders.
            const pairs = [
                { attachZ: 0.62, fanAngle: Math.PI * 0.17, scale: 1.18 },
                { attachZ: 0.46, fanAngle: Math.PI * 0.36, scale: 1.02 },
                { attachZ: 0.30, fanAngle: Math.PI * 0.60, scale: 0.92 },
                { attachZ: 0.14, fanAngle: Math.PI * 0.80, scale: 1.10 },
            ];
            pairs.forEach((pair, pi) => {
                [-1, 1].forEach(side => {
                    const defs = legDefs(pair.scale);
                    const ch = buildChain(defs);
                    const dz = (pair.attachZ - C_CEPH.z) / R_CEPH.z;
                    const attach = V(side * R_CEPH.x * Math.sqrt(1 - dz * dz) * 0.86, -0.04, pair.attachZ);
                    ch.root.position.copy(attach);
                    ch.root.rotation.y = yawFor(side, pair.fanAngle);
                    g.add(ch.root);
                    // Joint collar where the coxa meets the body
                    const collar = ring(defs[0].r0 * 1.3, colors.light, 0.15);
                    ch.joints[0].add(collar);

                    // Alternating tetrapod: L1 R2 L3 R4 vs R1 L2 R3 L4, plus a slight front-to-back wave
                    const phase = ((pi + (side > 0 ? 1 : 0)) % 2) * Math.PI + pi * 0.25;
                    const leg = {
                        root: ch.root, joints: ch.joints, side, pair: pi, phase, attach,
                        fa: pair.fanAngle,
                        lens: defs.map(d => d.len),
                        rest: defs.map(d => d.angle),
                        ang: defs.map(d => d.angle),
                        h: 1.5,
                    };
                    legs.push(leg);
                });
            });
        }

        // ── Sheet web: spokes, frame, sagging capture spiral, hub, anchor lines, dew ──
        function buildWeb() {
            const web = new THREE.Group();
            web.position.y = WEB_Y;
            const N = 30, R = 2.35;
            const ang = Array.from({ length: N }, (_, i) => (i + (rand() - 0.5) * 0.4) / N * Math.PI * 2);
            const rad = ang.map(() => R * (0.86 + rand() * 0.14));
            const P = (a, r, y = 0) => [Math.cos(a) * r, y, Math.sin(a) * r];

            const spokes = [], frame = [], spiral = [], hub = [], anchors = [], dew = [];
            for (let i = 0; i < N; i++) {
                spokes.push(...P(ang[i], 0.1), ...P(ang[i], rad[i]));
                const j = (i + 1) % N;
                frame.push(...P(ang[i], rad[i]), ...P(ang[j], rad[j]));
            }
            // Capture spiral, sagging toward the hub between spokes
            const r0 = 0.38, pitch = 0.068, rMax = Math.min(...rad) * 0.93;
            let prev = null;
            for (let k = 0; ; k++) {
                let done = false;
                for (let i = 0; i < N; i++) {
                    const r = r0 + pitch * (k + i / N);
                    if (r > rMax) { done = true; break; }
                    const cur = { a: ang[i], r };
                    if (prev) {
                        let a0 = prev.a, a1 = cur.a;
                        if (a1 < a0) a1 += Math.PI * 2;
                        const sag = 0.01 + prev.r * 0.008;
                        let last = P(a0, prev.r);
                        for (let f = 1; f <= 3; f++) {
                            const u = f / 3;
                            const rr = prev.r + (r - prev.r) * u - sag * Math.sin(Math.PI * u);
                            const pt = P(a0 + (a1 - a0) * u, rr);
                            spiral.push(...last, ...pt);
                            last = pt;
                        }
                        if (rand() < 0.22) dew.push(...P(a0 + (a1 - a0) * 0.5, (prev.r + r) * 0.5 - sag, 0.004));
                    }
                    prev = cur;
                }
                if (done) break;
            }
            // Hub: irregular concentric rings
            for (let k = 0; k < 4; k++) {
                const hr = 0.05 + k * 0.045;
                for (let i = 0; i < N; i++) {
                    const j = (i + 1) % N;
                    hub.push(...P(ang[i], hr * (0.9 + rand() * 0.2)), ...P(ang[j], hr * (0.9 + rand() * 0.2)));
                }
            }
            // Anchor threads running off into the dark
            for (let i = 0; i < N; i += 5) {
                anchors.push(...P(ang[i], rad[i]), ...P(ang[i] + 0.08, 6.5, 1.4 + rand()));
            }

            web.add(lineSegs(spokes, colors.primary, 0.26));
            web.add(lineSegs(frame, colors.primary, 0.34));
            web.add(lineSegs(spiral, colors.primary, 0.2));
            web.add(lineSegs(hub, colors.light, 0.3));
            web.add(lineSegs(anchors, colors.primary, 0.16));

            const dg = new THREE.BufferGeometry();
            dg.setAttribute('position', new THREE.Float32BufferAttribute(dew, 3));
            dewMat = new THREE.PointsMaterial({ color: colors.light, size: 0.022, transparent: true, opacity: 0.6 });
            web.add(new THREE.Points(dg, dewMat));
            return web;
        }

        function createSpider() {
            const root = new THREE.Group();
            root.add(buildWeb());

            body = new THREE.Group();
            root.add(body);

            body.add(buildAbdomen());

            // ── PEDICEL ── narrow waist with segment rings
            const pedCurve = new THREE.CatmullRomCurve3([V(0, 0.02, -0.28), V(0, 0.05, -0.08), V(0, 0.02, 0.1)]);
            body.add(new THREE.Mesh(new THREE.TubeGeometry(pedCurve, 10, 0.068, 8, false), mat(colors.mid)));
            [-0.2, -0.04].forEach(z => {
                const r = new THREE.Mesh(new THREE.TorusGeometry(0.075, 0.008, 3, 16), mat(colors.light));
                r.position.set(0, 0.045, z);
                body.add(r);
            });

            buildCephalothorax(body);
            buildChelicerae(body);
            buildPalps(body);
            buildLegs(body);

            // Dragline from the posterior spinneret down to the web
            const dg = new THREE.BufferGeometry();
            dg.setAttribute('position', new THREE.Float32BufferAttribute(new Float32Array(25 * 3), 3));
            dragline = new THREE.Line(dg, lmat(colors.light, 0.55));
            dragline.frustumCulled = false;
            root.add(dragline);

            return root;
        }

        // ── Pointer interaction: drag to spin (with inertia) and tilt ──
        let dragging = false, lastX = 0, lastY = 0, spinVel = 0, userSpin = 0, pitch = 0;

        function onDown(x, y) { dragging = true; lastX = x; lastY = y; document.body.classList.add('dragging'); }
        function onMove(x, y) {
            if (!dragging) return;
            spinVel = (x - lastX) * 0.006;
            userSpin += spinVel;
            pitch = Math.max(-0.45, Math.min(0.55, pitch + (y - lastY) * 0.004));
            lastX = x; lastY = y;
        }
        function onUp() { dragging = false; document.body.classList.remove('dragging'); }

        window.addEventListener('pointerdown', e => onDown(e.clientX, e.clientY));
        window.addEventListener('pointermove', e => onMove(e.clientX, e.clientY));
        window.addEventListener('pointerup', onUp);
        window.addEventListener('pointercancel', onUp);

        // ── Camera: distance chosen so the full leg span fits any aspect ratio ──
        let camDist = 3.6, camEl = 0.62;
        function updateSize() {
            renderer.setSize(window.innerWidth, window.innerHeight);
            renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
        }
        function updateCamera() {
            const w = window.innerWidth, aspect = w / window.innerHeight;
            camera.fov = w < 480 ? 55 : w < 768 ? 50 : 45;
            const tf = Math.tan(camera.fov * Math.PI / 360);
            camDist = Math.min(8, Math.max(4.2, 2.3 / (tf * aspect), 1.9 / tf));
            camera.aspect = aspect;
            camera.updateProjectionMatrix();
        }

        function init() {
            initBackground();
            animateBackground();
            updateSize();

            scene = new THREE.Scene();
            scene.background = new THREE.Color(colors.dark3);

            camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000);
            updateCamera();

            spider = createSpider();
            scene.add(spider);

            animate();
        }

        const smooth = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };
        const _v = new THREE.Vector3(), _c = new THREE.Vector3();
        const OMEGA = 0.0032;

        function animate() {
            requestAnimationFrame(animate);
            const t = performance.now();

            // Camera orbit with drag tilt that eases back
            if (!dragging) {
                userSpin += spinVel;
                spinVel *= 0.95;
                pitch *= 0.97;
            }
            const el = camEl + pitch;
            camera.position.set(0, Math.sin(el) * camDist, Math.cos(el) * camDist);
            camera.lookAt(0, -0.15, 0);

            spider.rotation.y = userSpin + t * 0.00018;
            spider.position.y = Math.sin(t * 0.0007) * 0.03;

            // Every 18 s the spider rears up into a threat display
            const cyc = (t / 1000) % 18;
            const display = smooth(12, 13.2, cyc) * (1 - smooth(15.5, 16.8, cyc));
            // Treading comes and goes so the idle never feels mechanical
            const gait = (0.25 + 0.75 * Math.max(0, Math.sin(t * 0.00045))) * (1 - display * 0.8);

            body.position.y = Math.sin(t * 0.0012) * 0.03 + display * 0.06;
            body.rotation.x = -display * 0.12 + Math.sin(t * 0.0008) * 0.015;
            const by = body.position.y, sa = Math.sin(body.rotation.x), ca = Math.cos(body.rotation.x);

            // Abdomen breathing + sway from the pedicel
            const br = 1 + Math.sin(t * 0.0021) * 0.025;
            abd.scale.set(br, br, 1 + (br - 1) * 0.3);
            abdPivot.rotation.y = Math.sin(t * 0.0006) * 0.05;
            abdPivot.rotation.x = Math.sin(t * 0.0009) * 0.03 + display * 0.2;

            // Legs: gait + IK so planted feet stay on the web while the body moves
            for (const L of legs) {
                const x = t * OMEGA + L.phase;
                const lift = Math.pow(Math.max(0, Math.sin(x)), 1.5) * 0.1 * gait;
                const swing = Math.cos(x) * 0.06 * gait;
                const a = L.ang;
                for (let i = 0; i < a.length; i++) a[i] = L.rest[i];
                a[4] -= lift * 1.4;
                a[5] -= lift * 0.6;

                let raise = 0, fwd = 0;
                if (L.pair === 0) {
                    raise = display * (0.62 + Math.sin(t * 0.009 + L.side) * 0.05);
                    fwd = -display * 0.12;
                    a[4] += display * 0.7; a[5] += display * 0.55; a[6] += display * 0.3;
                } else if (L.pair === 1) {
                    raise = display * 0.1;
                }
                const faEff = L.fa + swing + fwd;
                const zb = L.attach.z + L.h * Math.cos(faEff);
                const target = (WEB_Y + lift + raise - by + zb * sa) / ca - L.attach.y;
                solveFemur(L, target);
                for (let i = 0; i < a.length; i++) L.joints[i].rotation.z = a[i];
                L.root.rotation.y = yawFor(L.side, faEff);
            }

            // Pedipalps feeling the air; drumming during the display
            for (const P of palps) {
                P.root.rotation.y = yawFor(P.side, 0.42 + Math.sin(t * 0.0026 + P.side) * 0.12);
                const drum = display * Math.max(0, Math.sin(t * 0.022 + (P.side > 0 ? 0 : Math.PI))) * 0.5;
                P.joints[2].rotation.z = P.rest[2] + Math.sin(t * 0.0031 + P.side * 1.7) * 0.14 + drum + display * 0.3;
                P.joints[4].rotation.z = P.rest[4] - Math.sin(t * 0.0042 + P.side) * 0.1;
            }

            // Chelicerae lift and fangs unfold during the display
            for (const C of chelicerae) {
                C.base.rotation.z = -1.3 + display * 0.3 + Math.sin(t * 0.0017 + C.side) * 0.02;
                C.fang.rotation.y = -C.side * (1.15 - display * 0.65 - Math.max(0, Math.sin(t * 0.0013)) * 0.08);
            }

            // Spinnerets twitch
            for (const S of spinnerets) S.joint.rotation.z = S.rz + Math.sin(t * 0.006 + S.i * 1.3) * 0.1;

            // Eyes glint, dew twinkles
            eyeMats[0].opacity = 0.7 + 0.3 * (0.5 + 0.5 * Math.sin(t * 0.0024));
            eyeMats[1].opacity = 0.65 + 0.25 * (0.5 + 0.5 * Math.sin(t * 0.0017 + 1));
            dewMat.opacity = 0.45 + 0.25 * Math.sin(t * 0.0019);

            // Dragline: sagging curve from spinneret tip to its anchor on the web
            spider.updateMatrixWorld(true);
            draglineTip.getWorldPosition(_v);
            spider.worldToLocal(_v);
            _c.copy(_v).add(DRAG_END).multiplyScalar(0.5);
            _c.y -= 0.12;
            const arr = dragline.geometry.attributes.position.array;
            for (let i = 0; i <= 24; i++) {
                const u = i / 24, w = 1 - u;
                arr[i*3]   = w*w*_v.x + 2*u*w*_c.x + u*u*DRAG_END.x;
                arr[i*3+1] = w*w*_v.y + 2*u*w*_c.y + u*u*DRAG_END.y;
                arr[i*3+2] = w*w*_v.z + 2*u*w*_c.z + u*u*DRAG_END.z;
            }
            dragline.geometry.attributes.position.needsUpdate = true;

            renderer.render(scene, camera);
        }

        window.addEventListener('resize', () => {
            updateSize(); initBackground();
            if (camera) updateCamera();
        });

        window.addEventListener('load', init);
    </script>
</body>
</html>
MikeHiggins.me.uk LinkedIn GitHub Bluesky Contra Upwork
© 2026 Mike Higgins. All rights reserved.