• 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 BEE 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 — Bumble Bee</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 ──
        // Built facing +Z (head forward), like the rest of the family.
        const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('animationCanvas'), antialias: true, alpha: true });
        let scene, camera, bee, body, head;
        const antennae = [], wings = [], legs = [], abdomen = [], pollen = [];
        const mouth = { mandibles: [], palps: [], tongue: null }, sting = {};
        let membraneMat, ghostMats = [];

        // Seeded RNG so hairs, veins and facets are 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);
        const smooth = (a, b, x) => { const t = Math.min(1, Math.max(0, (x - a) / (b - a))); return t * t * (3 - 2 * t); };

        // ── 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 ball(r, color, x, y, z, sx = 1, sy = 1, sz = 1, ws = 16, hs = 12) {
            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, material) {
            const g = new THREE.BufferGeometry();
            g.setAttribute('position', new THREE.Float32BufferAttribute(arr, 3));
            return new THREE.LineSegments(g, material);
        }

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

        function qb(a, m, b, u) { const v = 1 - u; return v * v * a + 2 * u * v * m + u * u * b; }

        // 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);
            return new THREE.Mesh(geo, mat(color));
        }

        // Hairs / bristles on a limb segment (local +X axis, +Y dorsal)
        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, lmat(o.color, o.opacity));
        }

        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));
        }

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

        // Ellipsoid helpers (local to the ellipsoid centre)
        function ellRay(R, d) {   // surface point in direction d
            const k = 1 / Math.sqrt((d.x / R.x) ** 2 + (d.y / R.y) ** 2 + (d.z / R.z) ** 2);
            return V(d.x * k, d.y * k, d.z * k);
        }
        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 across an ellipsoid through a list of directions
        function ellLine(R, dirs, color, opacity, lift = 1.012) {
            return polyline(dirs.map(d => ellRay(R, d.clone().normalize()).multiplyScalar(lift)), lmat(color, opacity));
        }
        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 = ellRay(R, n);
                const d = ellNormal(R, p).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, lmat(color, opacity));
        }
        function ellipsoid(R, color, ws, hs) {
            const m = new THREE.Mesh(new THREE.SphereGeometry(1, ws, hs).rotateX(Math.PI / 2), mat(color));
            m.scale.copy(R);
            return m;
        }

        // ── Articulated chains ──
        // Each joint is a Group; its segment extends along local +X, the next
        // joint sits at the tip, and bending is rotation about local Z.
        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 = [], meshes = [];
            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);

                const m = limb(d.len, d.r0, d.rm, d.r1, d.color, d.radial || 8);
                j.add(m); meshes.push(m);
                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.6],
                    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.8, l1: d.r0 * 2.6, distal: 1.6, color: colors.light, opacity: 0.85 }));
                if (d.bands) d.bands.forEach(u => {
                    const b = ring(qb(d.r0, d.rm, d.r1, u) * 1.2, colors.light);
                    b.position.x = u * d.len;
                    j.add(b);
                });
                if (d.extra) d.extra(j, d);
                parent = j;
            });
            return { root, joints, meshes };
        }

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

        // ═════════════════════════ HEAD ═════════════════════════
        const R_HEAD = V(0.24, 0.25, 0.19);
        const R_EYE  = V(0.09, 0.2, 0.13);

        // Compound eye: hexagonal facets over a Fibonacci lattice on the
        // outward cap of a tall, oval eye wrapped onto the side of the head
        function compoundEye(side) {
            const g = new THREE.Group();
            g.add(ellipsoid(R_EYE, colors.mid, 16, 14));
            const out = V(side * 0.95, 0.05, 0.3).normalize();
            const N = 1000, pos = [];
            const avgR = (R_EYE.x + R_EYE.y + R_EYE.z) / 3;
            const hex = Math.sqrt(4 * Math.PI * avgR * avgR / N) * 0.56;
            const golden = Math.PI * (3 - Math.sqrt(5));
            const t1 = V(), t2 = V(), up = V(0, 1, 0);
            for (let i = 0; i < N; i++) {
                const y = 1 - (i + 0.5) / N * 2, r = Math.sqrt(1 - y * y), a = i * golden;
                const n = V(Math.cos(a) * r, y, Math.sin(a) * r);
                if (n.dot(out) < 0.05) continue;
                const p = ellRay(R_EYE, n);
                const nrm = ellNormal(R_EYE, p);
                t1.crossVectors(nrm, Math.abs(nrm.y) > 0.9 ? V(1, 0, 0) : up).normalize();
                t2.crossVectors(nrm, t1);
                p.addScaledVector(nrm, 0.003);
                let prev = null;
                for (let k = 0; k <= 6; k++) {
                    const ang = k / 6 * Math.PI * 2;
                    const v = p.clone().addScaledVector(t1, Math.cos(ang) * hex).addScaledVector(t2, Math.sin(ang) * hex);
                    if (prev) pos.push(prev.x, prev.y, prev.z, v.x, v.y, v.z);
                    prev = v;
                }
            }
            g.add(lineSegs(pos, lmat(colors.light, 0.8)));
            g.position.set(side * 0.19, 0.02, 0.0);
            return g;
        }

        // Elbowed antenna: long scape, pedicel, then a 10-segment flagellum
        // hinged sharply at the elbow
        function buildAntenna(side) {
            const defs = [
                { len: .22, r0: .022, rm: .026, r1: .02, color: colors.mid, angle: 1.05, radial: 8, hairs: 8 },   // scape
                { len: .05, r0: .02, rm: .024, r1: .018, color: colors.light, angle: -1.55, radial: 8 },          // pedicel (the elbow)
            ];
            for (let i = 0; i < 10; i++) {
                const r = 0.017 - i * 0.0004;
                defs.push({ len: .052, r0: r, rm: r * 1.08, r1: r * 0.95, color: i % 2 ? colors.mid : colors.primary,
                            angle: -0.06, radial: 6, hairs: 3, bands: [0.04] });
            }
            const ch = buildChain(defs);
            ch.root.position.set(side * 0.06, 0.1, 0.16);
            ch.root.rotation.y = yawFor(side, 0.4);
            antennae.push({ side, root: ch.root, joints: ch.joints, rest: defs.map(d => d.angle) });
            return ch.root;
        }

        // Mouthparts: toothed mandibles, and a folding proboscis — the galea
        // sheath and a long, hairy glossa that laps with a spoon-like flabellum
        function buildMouth(h) {
            h.add(ball(0.06, colors.mid, 0, -0.14, 0.15, 1.2, 0.5, 0.6, 12, 8));   // labrum
            [-1, 1].forEach(s => {
                const ch = buildChain([
                    { len: .11, r0: .03, rm: .03, r1: .02, color: colors.mid, angle: -0.5, radial: 6,
                      extra: (j, d) => {
                          const tt = [];
                          for (let k = 0; k < 4; k++) tt.push(d.len * (0.55 + k * 0.13), -0.01, 0, d.len * (0.55 + k * 0.13) + 0.012, -0.03, 0);
                          j.add(lineSegs(tt, lmat(colors.light, 0.9)));
                      } },
                ]);
                ch.root.position.set(s * 0.08, -0.17, 0.1);
                ch.root.rotation.y = yawFor(s, 0.5);
                h.add(ch.root);
                mouth.mandibles.push({ side: s, root: ch.root });
            });

            const gl = [
                { len: .14, r0: .034, rm: .036, r1: .026, color: colors.mid, angle: -2.25, radial: 8, hairs: 6 },     // galea / prementum
                { len: .12, r0: .024, rm: .024, r1: .02,  color: colors.primary, angle: 0.15, radial: 8, bands: [0.5] },
            ];
            for (let i = 0; i < 6; i++) gl.push({ len: .05, r0: .011, rm: .012, r1: .01, color: colors.light, angle: 0.05,
                                                  radial: 5, knuckle: false, hairs: 10 });
            gl[gl.length - 1].extra = (j, d) => j.add(ball(0.02, colors.light, d.len + 0.012, 0, 0, 1.3, 0.5, 1, 8, 6)); // flabellum
            const ch = buildChain(gl);
            ch.root.position.set(0, -0.19, 0.06);
            ch.root.rotation.y = -Math.PI / 2;     // +X → +Z (forward); joint 0 folds it back under the head
            h.add(ch.root);
            mouth.tongue = { joints: ch.joints, rest: gl.map(d => d.angle) };
            // Labial palps alongside
            [-1, 1].forEach(s => {
                const pp = buildChain([
                    { len: .1, r0: .01, rm: .011, r1: .009, color: colors.primary, angle: -2.1, radial: 5 },
                    { len: .08, r0: .009, rm: .009, r1: .006, color: colors.light, angle: 0.2, radial: 5, hairs: 4 },
                ]);
                pp.root.position.set(s * 0.035, -0.19, 0.07);
                pp.root.rotation.y = yawFor(s, 0.05);
                h.add(pp.root);
                mouth.palps.push(pp.joints[0]);
            });
        }

        function buildHead() {
            head = new THREE.Group();
            head.position.set(0, 0.02, 0.6);   // pivot at the neck
            const h = new THREE.Group();
            h.position.z = 0.18;
            head.add(h);

            h.add(ellipsoid(R_HEAD, colors.primary, 22, 16));
            h.add(compoundEye(-1));
            h.add(compoundEye(1));

            // Ocelli on the vertex
            [[0, 0.98, 0.2, 0.026], [-0.2, 0.97, -0.05, 0.022], [0.2, 0.97, -0.05, 0.022]].forEach(([x, y, z, r]) => {
                const p = ellRay(R_HEAD, V(x, y, z).normalize());
                h.add(ball(r, colors.light, p.x, p.y, p.z, 1, 1, 1, 8, 6));
                h.add(surfaceRing(r * 1.4, colors.mid, p, ellNormal(R_HEAD, p)));
            });
            // Clypeus outline
            const cl = [];
            for (let k = 0; k <= 20; k++) { const a = k / 20 * Math.PI * 2; cl.push(V(Math.sin(a) * 0.3, -0.35 + Math.cos(a) * 0.25, 1)); }
            h.add(ellLine(R_HEAD, cl, colors.light, 0.6));

            // Facial pile: dark on the face, pale tuft on the crown
            h.add(hairField(R_HEAD, 420, 0.03, 0.06, V(0, 0.1, -0.1), colors.mid, 0.55, n => Math.abs(n.x) < 0.7 && n.y < 0.6));
            h.add(hairField(R_HEAD, 160, 0.03, 0.06, V(0, 0.4, -0.5), colors.light, 0.6, n => n.y >= 0.6));

            h.add(buildAntenna(-1));
            h.add(buildAntenna(1));
            buildMouth(h);

            const neck = new THREE.Mesh(new THREE.CylinderGeometry(0.09, 0.11, 0.12, 12, 2, true).rotateX(Math.PI / 2), mat(colors.mid));
            neck.position.z = 0.0;
            head.add(neck);
            return head;
        }

        // ═════════════════════════ THORAX ═════════════════════════
        function buildThorax(g) {
            const C = V(0, 0.06, 0.26), R = V(0.4, 0.42, 0.44);
            const th = new THREE.Group(); th.position.copy(C);
            th.add(ellipsoid(R, colors.primary, 26, 20));
            // Scutum outline + scutellum ridge beneath the pile
            const sc = [], su = [];
            for (let k = 0; k <= 20; k++) { const a = (k / 20 - 0.5) * 2.4; sc.push(V(Math.sin(a) * 0.75, Math.cos(a), 0.15)); }
            for (let k = 0; k <= 16; k++) { const a = (k / 16 - 0.5) * 1.8; su.push(V(Math.sin(a) * 0.5, 0.75, -0.65 + Math.cos(a) * 0.05)); }
            th.add(ellLine(R, sc, colors.light, 0.45, 1.01));
            th.add(ellLine(R, su, colors.light, 0.6, 1.01));
            // Dense pile in bumble bee bands: pale collar, dark middle, pale rear
            th.add(hairField(R, 900, 0.05, 0.09, V(0, 0.1, 0.1),  colors.light,   0.6,  n => n.z > 0.32));
            th.add(hairField(R, 1100, 0.05, 0.09, V(0, 0.15, -0.2), colors.primary, 0.45, n => n.z <= 0.32 && n.z > -0.5));
            th.add(hairField(R, 550, 0.05, 0.09, V(0, 0.1, -0.4), colors.light,   0.55, n => n.z <= -0.5));
            g.add(th);
            // Tegulae over the wing bases
            [-1, 1].forEach(s => g.add(ball(0.05, colors.light, s * 0.33, 0.33, 0.37, 0.8, 0.5, 1.2, 10, 8)));
        }

        // ═════════════════════════ ABDOMEN ═════════════════════════
        const BANDS = [colors.light, colors.primary, colors.light, colors.mid, colors.light, colors.light];
        function buildAbdomen(g) {
            const radii = [0.33, 0.42, 0.44, 0.4, 0.3, 0.16];
            const defs = radii.map((r, i) => ({
                len: 0.25, r0: r * (i ? 0.92 : 0.6), rm: r * 1.04, r1: (radii[i + 1] || 0.08) * 0.9,
                color: i % 2 ? colors.mid : colors.primary,
                angle: i === 0 ? -0.18 : -0.06, radial: 16, knuckle: false,
                extra: (j, d) => {
                    // Overlapping tergite rim
                    const rim = ring(d.r1 * 1.08, colors.light, 0.05);
                    rim.position.x = d.len * 0.92;
                    j.add(rim);
                    // Pile for this band, lying back toward the tail
                    j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                        count: Math.round(420 * d.rm / 0.4), l0: 0.045, l1: 0.085, distal: 0.9,
                        color: BANDS[i], opacity: BANDS[i] === colors.light ? 0.6 : 0.45 }));
                    // Spiracles on the flanks
                    [-1, 1].forEach(s => {
                        const rr = qb(d.r0, d.rm, d.r1, 0.45) * 1.01;
                        j.add(surfaceRing(0.018, colors.light, V(0.45 * d.len, -rr * 0.3, s * rr * 0.95), V(0, -0.3, s).normalize()));
                    });
                }
            }));
            // Sting: barbed lancets in a sheath, retracted inside the tip
            const last = defs.length - 1;
            const lastLen = defs[last].len;
            const ch = buildChain(defs);
            const st = new THREE.Group();
            st.add(limb(0.2, 0.016, 0.012, 0.002, colors.light, 6));
            const barbs = [];
            for (let k = 0; k < 6; k++) {
                const x = 0.1 + k * 0.016;
                [-1, 1].forEach(s => barbs.push(x, 0, s * 0.004, x - 0.012, -0.004, s * 0.012));
            }
            st.add(lineSegs(barbs, lmat(colors.light, 0.9)));
            [-1, 1].forEach(s => st.add(ball(0.015, colors.mid, 0.02, 0, s * 0.02, 2, 0.6, 0.7, 8, 6)));   // sheath lobes
            st.rotation.z = -0.25;
            ch.joints[last].add(st);
            sting.group = st;
            sting.base = lastLen - 0.17;
            st.position.x = sting.base;

            ch.root.position.set(0, 0.02, -0.12);
            ch.root.rotation.y = Math.PI / 2;      // chain +X → body −Z
            g.add(ch.root);
            ch.joints.forEach((j, i) => abdomen.push({ joint: j, mesh: ch.meshes[i], rest: defs[i].angle, i }));
        }

        // ═════════════════════════ LEGS ═════════════════════════
        // coxa · trochanter · femur · tibia · basitarsus · 4 tarsomeres.
        // The hind tibia is flattened into a corbicula (pollen basket):
        // bare centre, long curved fringe bristles, and a pollen load that
        // grows as the bee forages; the hind basitarsus carries a pollen comb.
        function addClaws(j, d) {
            const L = d.len;
            [-1, 1].forEach(s => {
                const c = new THREE.QuadraticBezierCurve3(V(L, 0, s * 0.006), V(L + 0.03, 0.005, s * 0.016), V(L + 0.036, -0.028, s * 0.022));
                j.add(new THREE.Mesh(new THREE.TubeGeometry(c, 5, 0.0045, 4, false), mat(colors.light)));
            });
            j.add(ball(0.013, colors.primary, L + 0.012, -0.01, 0, 1.2, 0.5, 1, 8, 6));   // arolium pad
        }
        function legDefs(sc, pi, side) {
            const rs = Math.sqrt(sc), hind = pi === 2, fore = pi === 0;
            const A = [-0.55, 0.1, -0.3, -0.65, -0.25, -0.1, -0.08, -0.06, -0.05];
            const L = [.15, .07, .38, .36, hind ? .2 : .16, .07, .06, .05, .06];
            const R = [[.04, .045, .035], [.033, .034, .03], [.03, .036, .027], hind ? [.03, .065, .05] : [.026, .03, .024],
                       hind ? [.04, .045, .032] : [.02, .022, .018], [.015, .016, .014], [.013, .014, .012], [.012, .012, .011], [.011, .011, .009]];
            return L.map((len, i) => {
                const d = {
                    len: len * sc, r0: R[i][0] * rs, rm: R[i][1] * rs, r1: R[i][2] * rs,
                    color: i < 2 ? colors.mid : i === 3 && hind ? colors.light : i % 2 ? colors.primary : colors.mid,
                    angle: A[i], radial: i < 5 ? 8 : 6,
                    hairs: [0, 6, 40, hind ? 10 : 34, 26, 8, 6, 6, 6][i],
                    extra: i === 8 ? addClaws : null,
                };
                if (hind && i === 3) {
                    d.sy = 0.55;
                    d.extra = (j, dd) => {
                        // Fringe bristles curving around the basket
                        j.add(limbHairs(dd.len, dd.r0, dd.rm, dd.r1, { count: 26, ordered: true, arc: [Math.PI / 2, Math.PI], alt: true,
                            sy: 0.55, l0: 0.07, l1: 0.1, distal: 0.5, color: colors.light, opacity: 0.85 }));
                        // Pollen load, packed on the outer face
                        const load = new THREE.Mesh(new THREE.IcosahedronGeometry(0.075, 2), mat(colors.light));
                        load.position.set(dd.len * 0.55, 0, side * dd.rm * 1.1);
                        load.scale.set(1.3, 0.9, 0.7);
                        j.add(load);
                        pollen.push(load);
                    };
                }
                if (hind && i === 4) d.spines = 10;                    // pollen comb rows
                if (fore && i === 4) d.bands = [0.08];                 // antenna-cleaner notch
                return d;
            });
        }
        function buildLegs(g) {
            const pairs = [
                { attachZ: 0.46, fanAngle: Math.PI * 0.28, scale: 0.9 },
                { attachZ: 0.26, fanAngle: Math.PI * 0.5,  scale: 1.0 },
                { attachZ: 0.06, fanAngle: Math.PI * 0.72, scale: 1.18 },
            ];
            pairs.forEach((pair, pi) => {
                [-1, 1].forEach(side => {
                    const defs = legDefs(pair.scale, pi, side);
                    const ch = buildChain(defs);
                    ch.root.position.set(side * 0.24, -0.24, pair.attachZ);
                    ch.root.rotation.y = yawFor(side, pair.fanAngle);
                    g.add(ch.root);
                    const phase = ((pi + (side > 0 ? 0 : 1)) % 2) * Math.PI + pi * 0.3;
                    legs.push({ root: ch.root, joints: ch.joints, side, pair: pi, phase,
                                fa: pair.fanAngle, rest: defs.map(d => d.angle) });
                });
            });
        }

        // ═════════════════════════ WINGS ═════════════════════════
        // Fore and hind wings. Bee venation sits in the basal two-thirds
        // (marginal cell, three submarginal cells, pterostigma); the outer
        // wing is bare membrane. A row of hamuli on the hindwing's leading
        // edge hooks it to the forewing so the pair beat as one surface.
        function makeWing(len, wid, side, fore, membrane, veinMat, full) {
            const g = new THREE.Group();
            const outline = u => {
                const k = 0.25 + 0.75 * smooth(0, 0.2, u);
                const e = Math.sqrt(Math.max(0, 1 - Math.pow(u, 2.6)));
                return [wid * 0.3 * k * Math.pow(e, 0.7), -wid * 0.7 * k * e];
            };
            const P = (u, f) => { const [le, te] = outline(u); return V(side * u * len, 0, le + (te - le) * f); };

            const NU = 28, NF = 7, pos = [], idx = [];
            for (let i = 0; i <= NU; i++) for (let j = 0; j <= NF; j++) { const p = P(i / NU, j / NF); pos.push(p.x, p.y, p.z); }
            for (let i = 0; i < NU; i++) for (let j = 0; j < NF; j++) {
                const a = i * (NF + 1) + j, b = a + NF + 1;
                idx.push(a, b, a + 1, b, b + 1, a + 1);
            }
            const mg = new THREE.BufferGeometry();
            mg.setAttribute('position', new THREE.Float32BufferAttribute(pos, 3));
            mg.setIndex(idx);
            g.add(new THREE.Mesh(mg, membrane));
            const ol = [];
            for (let k = 0; k <= 50; k++) ol.push(P(k / 50, 0));
            for (let k = 50; k >= 0; k--) ol.push(P(k / 50, 1));
            g.add(polyline(ol, veinMat, true));
            if (!full) return g;

            const vp = [];
            const curve = (pts) => {    // polyline through (u,f) control points
                let prev = null;
                pts.forEach(([u, f]) => { const p = P(u, f); if (prev) vp.push(prev.x, prev.y, prev.z, p.x, p.y, p.z); prev = p; });
            };
            if (fore) {
                curve([[0, 0.08], [0.2, 0.1], [0.42, 0.06], [0.46, 0.02]]);                       // Sc+R to stigma
                curve([[0.46, 0.02], [0.6, 0.06], [0.74, 0.1], [0.8, 0.04]]);                    // marginal cell
                curve([[0.46, 0.06], [0.52, 0.2], [0.6, 0.24], [0.7, 0.24], [0.8, 0.04]]);
                curve([[0, 0.3], [0.25, 0.32], [0.5, 0.34], [0.72, 0.38]]);                       // M
                curve([[0, 0.55], [0.25, 0.55], [0.48, 0.58], [0.64, 0.66]]);                     // Cu
                curve([[0, 0.8], [0.2, 0.82], [0.35, 0.9]]);                                      // anal
                [[0.52, 0.2, 0.5, 0.34], [0.6, 0.24, 0.6, 0.36], [0.7, 0.24, 0.7, 0.38],           // submarginal crossveins
                 [0.25, 0.32, 0.25, 0.55], [0.48, 0.34, 0.48, 0.58], [0.2, 0.1, 0.2, 0.32]]
                    .forEach(([u0, f0, u1, f1]) => curve([[u0, f0], [u1, f1]]));
                // Pterostigma: hatched cell on the leading edge
                for (let k = 0; k <= 5; k++) curve([[0.4 + k * 0.012, 0], [0.4 + k * 0.012 + 0.006, 0.06]]);
            } else {
                curve([[0, 0.1], [0.3, 0.1], [0.55, 0.05]]);
                curve([[0, 0.35], [0.3, 0.34], [0.5, 0.4]]);
                curve([[0, 0.6], [0.25, 0.62], [0.4, 0.75]]);
                curve([[0.3, 0.1], [0.3, 0.34]]);
                curve([[0.25, 0.34], [0.25, 0.62]]);
                // Hamuli: tiny hooks along the leading edge
                const hk = [];
                for (let k = 0; k < 14; k++) {
                    const a = P(0.42 + k * 0.012, 0);
                    hk.push(a.x, a.y, a.z, a.x, a.y + 0.018, a.z + 0.006, a.x, a.y + 0.018, a.z + 0.006, a.x - side * 0.004, a.y + 0.012, a.z - 0.004);
                }
                g.add(lineSegs(hk, lmat(colors.light, 0.9)));
            }
            g.add(lineSegs(vp, veinMat));
            // Microtrichia: a dusting of fine hairs over the outer membrane
            const mt = [];
            for (let k = 0; k < 160; k++) {
                const u = 0.45 + rand() * 0.5, f = 0.1 + rand() * 0.85, p = P(u, f);
                mt.push(p.x, p.y + 0.002, p.z, p.x + side * 0.008, p.y + 0.004, p.z - 0.004);
            }
            g.add(lineSegs(mt, lmat(colors.light, 0.35)));
            const cpts = [];
            for (let k = 0; k <= 20; k++) cpts.push(P(k / 20 * 0.46, 0));
            g.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(cpts), 20, 0.008, 4, false), mat(colors.primary)));
            return g;
        }

        function buildWings(g) {
            membraneMat = new THREE.MeshBasicMaterial({ color: colors.light, wireframe: true, transparent: true, opacity: 0.14 });
            const veinMat = new THREE.LineBasicMaterial({ color: colors.primary, transparent: true, opacity: 0.95 });
            ghostMats = [[0.06, 0.28], [0.03, 0.14]].map(([m, v]) => ({
                membrane: new THREE.MeshBasicMaterial({ color: colors.light, wireframe: true, transparent: true, opacity: m }),
                vein: new THREE.LineBasicMaterial({ color: colors.light, transparent: true, opacity: v }),
            }));
            const defs = [
                { fore: true,  pos: [0.3, 0.34, 0.38], len: 1.95, wid: 0.62 },
                { fore: false, pos: [0.3, 0.28, 0.2],  len: 1.35, wid: 0.44 },
            ];
            defs.forEach(d => [-1, 1].forEach(side => {
                const root = new THREE.Group();
                root.position.set(side * d.pos[0], d.pos[1], d.pos[2]);
                const yaw = new THREE.Group();
                root.add(yaw);
                const strokes = [], pitches = [];
                for (let k = 0; k < 3; k++) {
                    const st = new THREE.Group(), pt = new THREE.Group();
                    st.add(pt); yaw.add(st);
                    const m = k === 0 ? { membrane: membraneMat, vein: veinMat } : ghostMats[k - 1];
                    pt.add(makeWing(d.len, d.wid, side, d.fore, m.membrane, m.vein, k === 0));
                    strokes.push(st); pitches.push(pt);
                }
                g.add(root);
                wings.push({ side, fore: d.fore, yaw, strokes, pitches });
            }));
        }

        function createBee() {
            const root = new THREE.Group();
            body = new THREE.Group();
            body.position.z = 0.35;     // spin about the middle of the bee
            root.add(body);
            body.add(buildHead());
            buildThorax(body);
            buildAbdomen(body);
            buildLegs(body);
            buildWings(body);
            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.4, Math.min(0.6, 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 whole bee fits any aspect ratio ──
        let camDist = 5, camEl = 0.3;
        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(10, Math.max(4.8, 2.6 / (tf * aspect), 1.8 / 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();

            bee = createBee();
            scene.add(bee);

            animate();
        }

        const _c1 = new THREE.Color(colors.light), _c2 = new THREE.Color(colors.primary);

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

            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.05, 0);

            // Behaviour cycle (18 s): hover → forage (tongue laps, baskets fill) → alert (sting out)
            const cyc = (t / 1000) % 18;
            const forage = smooth(3.5, 4.5, cyc) * (1 - smooth(9.5, 10.5, cyc));
            const load   = smooth(4, 10, cyc) * (1 - smooth(16.8, 17.8, cyc));
            const alert  = smooth(12, 12.6, cyc) * (1 - smooth(14.8, 15.6, cyc));
            const lap    = forage * (0.5 + 0.5 * Math.sin(t * 0.012));

            // Heavy hover: deep, round bob; nose dips to feed, tail tucks when alarmed
            bee.rotation.y = userSpin + t * 0.0003;
            bee.position.y = Math.sin(t * 0.0022) * 0.08;
            body.rotation.x = Math.sin(t * 0.0016) * 0.04 + forage * 0.1 - alert * 0.05;
            body.rotation.z = Math.sin(t * 0.002 + 0.8) * 0.03 + alert * Math.sin(t * 0.03) * 0.01;

            head.rotation.x = forage * 0.12 + Math.sin(t * 0.0011) * 0.03;
            head.rotation.y = Math.sin(t * 0.0006) * 0.1 * (1 - forage);

            // Proboscis unfolds from under the head and laps
            const T = mouth.tongue;
            T.joints[0].rotation.z = T.rest[0] + forage * 1.15;
            T.joints[1].rotation.z = T.rest[1] - forage * 0.05;
            for (let i = 2; i < T.joints.length; i++)
                T.joints[i].rotation.z = T.rest[i] * (1 - forage) + forage * (Math.sin(t * 0.012 - i * 0.7) * 0.12) - lap * 0.04;
            mouth.palps.forEach(p => p.rotation.z = -2.1 + forage * 1.0);
            // Mandibles work; flare open when alarmed
            mouth.mandibles.forEach(M => M.root.rotation.y = yawFor(M.side, 0.5 + Math.max(0, Math.sin(t * 0.004)) * 0.15 + alert * 0.35));

            for (const A of antennae) {
                A.root.rotation.y = yawFor(A.side, 0.4 + Math.sin(t * 0.0025 + A.side) * 0.1 - alert * 0.15);
                A.joints[0].rotation.z = A.rest[0] + Math.sin(t * 0.003 + A.side) * 0.06 - alert * 0.2;
                A.joints[1].rotation.z = A.rest[1] + Math.sin(t * 0.0037 + A.side * 2) * 0.12 + alert * 0.4;
            }

            // Abdomen: pumping breath; curls under with the sting out when alarmed
            for (const S of abdomen) {
                S.joint.rotation.z = S.rest + Math.sin(t * 0.0016 - S.i * 0.4) * 0.012 - alert * (S.i > 1 ? 0.12 : 0.04);
                const br = 1 + Math.sin(t * 0.005 - S.i * 0.5) * 0.03;
                S.mesh.scale.set(1, br, br);
            }
            sting.group.position.x = sting.base + alert * (0.14 + 0.02 * Math.sin(t * 0.02));
            sting.group.rotation.z = -0.25 - alert * 0.2;

            // Legs dangle; hind legs carry swelling pollen loads
            for (const L of legs) {
                const x = t * 0.0017 + L.phase;
                for (let k = 0; k < L.rest.length; k++) L.joints[k].rotation.z = L.rest[k];
                L.joints[2].rotation.z += Math.sin(x) * 0.06 - alert * 0.15;
                L.joints[3].rotation.z += Math.sin(x + 1.1) * 0.06;
                for (let k = 4; k < L.rest.length; k++) L.joints[k].rotation.z += Math.sin(x * 1.2 - k * 0.5) * 0.03;
                if (L.pair === 0) L.joints[3].rotation.z += forage * 0.35;   // forelegs reach in to the flower
                L.root.rotation.y = yawFor(L.side, L.fa + Math.cos(x) * 0.03 + alert * 0.08);
            }
            pollen.forEach(p => p.scale.set(0.3 + load * 1.1, 0.25 + load * 0.75, 0.2 + load * 0.55));

            // Wings: fore and hind hooked together, beating as one with motion-blur ghosts
            for (const W of wings) {
                W.yaw.rotation.y = W.side * ((W.fore ? 0.1 : 0.22) + Math.sin(t * 0.002) * 0.03);
                for (let k = 0; k < 3; k++) {
                    const ph = (t - k * 10) * 0.06;
                    W.strokes[k].rotation.z = W.side * (0.22 + 0.5 * Math.sin(ph) + (W.fore ? 0 : -0.04));
                    W.pitches[k].rotation.x = 0.45 * Math.cos(ph);
                }
            }
            membraneMat.color.copy(_c1).lerp(_c2, 0.5 + 0.5 * Math.sin(t * 0.0013));

            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.