• 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 MOSQUITO 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 — Mosquito</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 spider, fly and scorpion.
        const renderer = new THREE.WebGLRenderer({ canvas: document.getElementById('animationCanvas'), antialias: true, alpha: true });
        let scene, camera, mosquito, body, head, proboscis;
        const antennae = [], wings = [], halteres = [], legs = [], abdomen = [], palps = [];
        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.13, 0.13, 0.12);
        const R_EYE  = V(0.1, 0.13, 0.12);

        // Compound eye: a hexagonal facet at every point of a Fibonacci
        // lattice over the outward-facing cap of the eye ellipsoid
        function compoundEye(side) {
            const g = new THREE.Group();
            g.add(ellipsoid(R_EYE, colors.mid, 16, 12));
            const out = V(side * 0.85, 0.12, 0.5).normalize();
            const N = 950, 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.0) 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.085, 0.01, 0.02);
            return g;
        }

        // Plumose antenna: a big pedicel (Johnston's organ) then 13
        // flagellomeres, each carrying a whorl of fine radiating hairs
        function whorl(x, n, L, distal) {
            const pos = [];
            for (let k = 0; k < n; k++) {
                const a = k / n * Math.PI * 2 + x * 40;
                const d = V(distal, Math.cos(a), Math.sin(a)).normalize();
                const l = L * (0.8 + rand() * 0.35);
                pos.push(x, 0, 0, x + d.x * l, d.y * l, d.z * l);
            }
            return lineSegs(pos, lmat(colors.light, 0.55));
        }
        function buildAntenna(side) {
            const defs = [
                { len: .05, r0: .03, rm: .038, r1: .02, color: colors.mid, angle: .55, radial: 10 },   // pedicel
            ];
            for (let i = 0; i < 13; i++) {
                const r = 0.009 - i * 0.0004, L = 0.15 - i * 0.008;
                defs.push({ len: .07, r0: r, rm: r * 1.2, r1: r * 0.9, color: colors.primary,
                            angle: i === 0 ? 0.05 : -0.035, radial: 6,
                            extra: (j) => j.add(whorl(0.004, 18, L, 0.5)) });
            }
            const ch = buildChain(defs);
            ch.root.position.set(side * 0.04, 0.06, 0.1);
            ch.root.rotation.y = yawFor(side, 0.28);
            antennae.push({ side, root: ch.root, joints: ch.joints, rest: defs.map(d => d.angle) });
            return ch.root;
        }

        // Proboscis: a scaly, jointed labium sheath with the stylet bundle
        // (labrum, paired mandibles and serrated maxillae) hidden inside.
        // While probing, the labium bows and the stylets slide out of the tip.
        function buildProboscis() {
            const N = 6, defs = [];
            for (let i = 0; i < N; i++) {
                const r = 0.022 - i * 0.0012;
                defs.push({ len: .19, r0: r, rm: r * 1.05, r1: r * 0.95, color: i % 2 ? colors.mid : colors.primary,
                            angle: i === 0 ? -0.42 : -0.03, radial: 8, knuckle: false, hairs: 10,
                            bands: i === 2 ? [0.5] : null });
            }
            const lastLen = defs[N - 1].len;
            defs[N - 1].extra = (j) => {
                // Labella: twin lobes at the tip
                [-1, 1].forEach(s => j.add(ball(0.018, colors.light, lastLen + 0.012, 0, s * 0.01, 1.5, 0.8, 0.8, 8, 6)));
                // Stylet bundle
                const st = new THREE.Group();
                const lab = limb(0.32, 0.007, 0.007, 0.002, colors.light, 5);
                st.add(lab);
                [-1, 1].forEach(s => {
                    const mx = limb(0.3, 0.004, 0.004, 0.001, colors.light, 4);
                    mx.position.z = s * 0.006;
                    st.add(mx);
                    // Saw-tooth serrations at the maxilla tips
                    const teeth = [];
                    for (let k = 0; k < 6; k++) {
                        const x = 0.22 + k * 0.013;
                        teeth.push(x, 0, s * 0.006, x - 0.008, 0, s * 0.014);
                    }
                    st.add(lineSegs(teeth, lmat(colors.light, 0.9)));
                });
                st.position.x = lastLen - 0.3;
                j.add(st);
                proboscis.stylets = st;
                proboscis.styletBase = lastLen - 0.3;
            };
            proboscis = {};
            const ch = buildChain(defs);
            ch.root.position.set(0, -0.08, 0.1);
            ch.root.rotation.y = -Math.PI / 2;     // +X → +Z (forward), pitched down by joint 0
            proboscis.joints = ch.joints;
            proboscis.rest = defs.map(d => d.angle);
            return ch.root;
        }

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

            h.add(ellipsoid(R_HEAD, colors.primary, 20, 14));
            h.add(compoundEye(-1));
            h.add(compoundEye(1));
            h.add(hairField(R_HEAD, 90, 0.015, 0.035, V(0, 0.3, -0.6), colors.light, 0.5, n => n.y > 0.2 && n.z < 0.5));
            // Clypeus
            h.add(ball(0.05, colors.mid, 0, -0.03, 0.11, 1, 0.8, 0.7, 10, 8));

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

            // Short maxillary palps, 5-jointed, flanking the proboscis
            [-1, 1].forEach(s => {
                const pd = [];
                for (let k = 0; k < 5; k++) pd.push({ len: .045, r0: .01, rm: .012, r1: .009, color: k % 2 ? colors.light : colors.mid,
                                                      angle: k ? -0.02 : -0.7, radial: 6, hairs: 4 });
                const ch = buildChain(pd);
                ch.root.position.set(s * 0.03, -0.08, 0.1);
                ch.root.rotation.y = yawFor(s, 0.12);
                h.add(ch.root);
                palps.push({ side: s, joints: ch.joints });
            });

            const neck = new THREE.Mesh(new THREE.CylinderGeometry(0.05, 0.06, 0.1, 10, 2, true).rotateX(Math.PI / 2), mat(colors.mid));
            neck.position.z = 0.02;
            head.add(neck);
            return head;
        }

        // ═════════════════════════ THORAX ═════════════════════════
        function buildThorax(g) {
            const C = V(0, 0.12, 0.08), R = V(0.21, 0.27, 0.3);
            const th = new THREE.Group(); th.position.copy(C);
            th.add(ellipsoid(R, colors.primary, 28, 20));

            // Scale pattern on the scutum: median stripe and a lyre motif
            const med = [];
            for (let k = 0; k <= 16; k++) { const a = Math.PI * (0.1 + k / 16 * 0.75); med.push(V(0, Math.sin(a), Math.cos(a))); }
            th.add(ellLine(R, med, colors.light, 0.85));
            [-1, 1].forEach(s => {
                const lyre = [], side = [];
                for (let k = 0; k <= 16; k++) {
                    const a = Math.PI * (0.18 + k / 16 * 0.62);
                    lyre.push(V(s * (0.22 + 0.18 * Math.sin(a * 2.2)), Math.sin(a), Math.cos(a)));
                }
                th.add(ellLine(R, lyre, colors.light, 0.7));
                for (let k = 0; k <= 12; k++) side.push(V(s, -0.25 + 0.2 * Math.sin(k / 12 * Math.PI), 0.8 - k * 0.14));
                th.add(ellLine(R, side, colors.light, 0.45));   // pleural suture
                // Thoracic spiracle
                const p = ellRay(R, V(s, 0.05, 0.45).normalize()).multiplyScalar(1.01);
                th.add(surfaceRing(0.02, colors.light, p, ellNormal(R, p)));
            });
            // Rows of acrostichal / dorsocentral bristles
            const br = [];
            [-0.42, -0.14, 0.14, 0.42].forEach(x => {
                for (let z = -0.55; z <= 0.75; z += 0.18) {
                    const p = ellRay(R, V(x, 0.9, z).normalize());
                    const d = ellNormal(R, p).add(V(0, 0.2, -0.8)).normalize();
                    const L = 0.05 + rand() * 0.04;
                    br.push(p.x, p.y, p.z, p.x + d.x * L, p.y + d.y * L, p.z + d.z * L);
                }
            });
            th.add(lineSegs(br, lmat(colors.light, 0.75)));
            th.add(hairField(R, 260, 0.012, 0.028, V(0, 0.1, -0.7), colors.primary, 0.38));
            g.add(th);

            // Trilobed scutellum and the postnotum behind it
            [-1, 0, 1].forEach(k => g.add(ball(0.045, colors.light, k * 0.06, 0.33, -0.2 + Math.abs(k) * 0.01, 1, 0.6, 0.9, 10, 8)));
            const sb = [];
            [-1, 0, 1].forEach(k => { for (let m = 0; m < 3; m++) sb.push(k * 0.06 + (m - 1) * 0.012, 0.35, -0.23, k * 0.06 + (m - 1) * 0.02, 0.38, -0.32); });
            g.add(lineSegs(sb, lmat(colors.light, 0.85)));
            g.add(ball(0.09, colors.mid, 0, 0.22, -0.26, 1, 0.7, 0.6, 12, 8));
        }

        // ═════════════════════════ ABDOMEN ═════════════════════════
        function buildAbdomen(g) {
            const N = 8, defs = [];
            for (let i = 0; i < N; i++) {
                const t = i / (N - 1);
                const r = 0.1 * (1 - t * 0.5);
                defs.push({
                    len: 0.3, r0: r * 0.92, rm: r * 1.06, r1: r * 0.9,
                    color: i % 2 ? colors.mid : colors.primary,
                    angle: i === 0 ? -0.06 : -0.025, radial: 12, knuckle: false,
                    extra: (j, d) => {
                        // Pale basal scale band + intersegmental ring
                        j.add(ring(d.r0 * 1.03, colors.light, 0.06));
                        const band = ring(qb(d.r0, d.rm, d.r1, 0.12) * 1.04, colors.light, 0.05);
                        band.position.x = 0.12 * d.len;
                        j.add(band);
                        // Flat scales lying back along the tergite
                        j.add(limbHairs(d.len, d.r0, d.rm, d.r1, {
                            count: 34, l0: d.r0 * 0.25, l1: d.r0 * 0.5, distal: 4, color: colors.light, opacity: 0.4 }));
                        // Posterior fringe of setae
                        const fr = [];
                        for (let k = 0; k < 14; k++) {
                            const a = k / 14 * Math.PI * 2, rr = d.r1;
                            fr.push(d.len * 0.96, Math.cos(a) * rr, Math.sin(a) * rr,
                                    d.len + 0.05, Math.cos(a) * rr * 1.8, Math.sin(a) * rr * 1.8);
                        }
                        j.add(lineSegs(fr, lmat(colors.primary, 0.5)));
                        // Spiracles on the flanks
                        [-1, 1].forEach(s => {
                            const rr = qb(d.r0, d.rm, d.r1, 0.4) * 1.01;
                            j.add(surfaceRing(0.012, colors.light, V(0.4 * d.len, -rr * 0.2, s * rr), V(0, -0.2, s).normalize()));
                        });
                    }
                });
            }
            // Cerci: a pair of small paddles at the tip
            const ch = buildChain(defs);
            [-1, 1].forEach(s => ch.joints[N - 1].add(ball(0.022, colors.light, defs[N - 1].len + 0.03, 0.01, s * 0.02, 1.6, 0.5, 0.9, 8, 6)));
            ch.root.position.set(0, 0.04, -0.2);
            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 · 5 tarsomeres — very long and
        // thin, scaled, with pale bands at each tarsomere base
        function addClaws(j, d) {
            const L = d.len;
            [-1, 1].forEach(s => {
                const c = new THREE.QuadraticBezierCurve3(V(L, 0, s * 0.003), V(L + 0.02, 0.004, s * 0.008), V(L + 0.026, -0.018, s * 0.012));
                j.add(new THREE.Mesh(new THREE.TubeGeometry(c, 5, 0.003, 4, false), mat(colors.light)));
            });
        }
        function legDefs(sc, raised) {
            const rs = Math.sqrt(sc);
            const A = raised ? [-.15, .1, 1.0, -.95, .22, .16, .12, .1, .1]
                             : [-.45, .1, .38, -1.25, -.25, -.12, -.08, -.06, -.05];
            const L = [.1, .05, .58, .64, .36, .16, .11, .08, .06];
            const R = [[.03, .033, .026], [.022, .023, .02], [.017, .022, .015], [.013, .014, .011],
                       [.009, .009, .008], [.0075, .0075, .007], [.0065, .0065, .006], [.0058, .0058, .0054], [.005, .005, .004]];
            return L.map((len, i) => ({
                len: len * sc, r0: R[i][0] * rs, rm: R[i][1] * rs, r1: R[i][2] * rs,
                color: i < 2 ? colors.mid : i < 4 ? colors.primary : (i % 2 ? colors.light : colors.primary),
                angle: A[i], radial: i < 4 ? 8 : 5, knuckle: i < 4,
                hairs: i === 2 ? 34 : i === 3 ? 30 : i >= 4 ? 7 : 0,
                bands: i === 2 ? [0.92] : i >= 4 ? [0.06] : null,
                spines: i === 3 ? 4 : 0,
                extra: i === 8 ? addClaws : null,
            }));
        }
        function buildLegs(g) {
            const pairs = [
                { attachZ:  0.2,  fanAngle: Math.PI * 0.26, scale: 1.0,  raised: false }, // fore — reaching ahead
                { attachZ:  0.08, fanAngle: Math.PI * 0.52, scale: 1.1,  raised: false }, // mid — dangling out
                { attachZ: -0.04, fanAngle: Math.PI * 0.80, scale: 1.25, raised: true  }, // hind — lifted, the classic pose
            ];
            pairs.forEach((pair, pi) => {
                [-1, 1].forEach(side => {
                    const defs = legDefs(pair.scale, pair.raised);
                    const ch = buildChain(defs);
                    ch.root.position.set(side * 0.14, -0.1, 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 ═════════════════════════
        // Long, narrow wings with mosquito venation (forked R2+3 and M1+2),
        // scales along every vein and a fringe of scales on the trailing edge.
        function makeWing(len, wid, side, membrane, veinMat, full) {
            const g = new THREE.Group();
            const outline = u => {
                const k = 0.22 + 0.78 * smooth(0, 0.18, u);
                const e = Math.sqrt(Math.max(0, 1 - Math.pow(u, 3)));
                return [wid * 0.3 * k * Math.pow(e, 0.5), -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 = 30, NF = 5, 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 s = (u, a) => smooth(a, a + 0.25, u);
            const R1  = u => 0.16 - 0.15 * u * u;
            const R23 = u => R1(u) + 0.14 * s(u, 0.32);
            const M   = () => 0.52;
            const veins = [
                { u0: 0,    u1: 0.45, f: u => 0.08 * (1 - (u / 0.45) ** 2) },        // subcosta
                { u0: 0,    u1: 0.97, f: R1 },                                         // R1
                { u0: 0.32, u1: 1,    f: R23 },                                        // R2+3 → R2
                { u0: 0.62, u1: 1,    f: u => R23(u) + 0.09 * s(u, 0.62) },           // R3
                { u0: 0.28, u1: 1,    f: u => R1(u) + 0.27 * s(u, 0.28) },            // R4+5
                { u0: 0,    u1: 1,    f: M },                                          // M1+2 → M1
                { u0: 0.6,  u1: 1,    f: u => M() + 0.13 * s(u, 0.6) },               // M3+4
                { u0: 0,    u1: 0.82, f: u => 0.72 + 0.28 * Math.pow(u / 0.82, 3) },  // CuA
                { u0: 0,    u1: 0.55, f: u => 0.88 + 0.12 * (u / 0.55) ** 2 },        // anal
            ];
            const vp = [], sc = [];
            veins.forEach(v => {
                let prev = null;
                for (let k = 0; k <= 24; k++) {
                    const u = v.u0 + (v.u1 - v.u0) * k / 24;
                    const p = P(u, v.f(u));
                    if (prev) vp.push(prev.x, prev.y, prev.z, p.x, p.y, p.z);
                    prev = p;
                }
                // Scales along the vein, angled toward the tip
                for (let u = v.u0 + 0.03; u < v.u1 - 0.02; u += 0.028) {
                    const a = P(u, v.f(u));
                    [-1, 1].forEach(sd => {
                        const b = P(u + 0.02, v.f(u) + sd * 0.05);
                        sc.push(a.x, a.y + 0.002, a.z, b.x, b.y + 0.002, b.z);
                    });
                }
            });
            // Crossveins: r, r-m and m-cu
            [[0.55, R1, R23], [0.45, u => R1(u) + 0.27 * s(u, 0.28), M], [0.5, M, u => 0.72 + 0.28 * Math.pow(u / 0.82, 3)]]
                .forEach(([u, fa, fb]) => { const a = P(u, fa(u)), b = P(u + 0.01, fb(u)); vp.push(a.x, a.y, a.z, b.x, b.y, b.z); });
            g.add(lineSegs(vp, veinMat));
            g.add(lineSegs(sc, lmat(colors.light, 0.45)));

            // Fringe scales on the trailing edge and tip
            const fr = [];
            for (let u = 0.08; u <= 1.0; u += 0.007) {
                const a = P(u, 1), out = a.clone().sub(P(u, 0.5)).normalize();
                const L = 0.045 + 0.02 * Math.sin(u * 40);
                fr.push(a.x, a.y, a.z, a.x + out.x * L, a.y, a.z + out.z * L - 0.01);
            }
            g.add(lineSegs(fr, lmat(colors.light, 0.4)));

            // Costa: a scaly leading-edge spar
            const cpts = [];
            for (let k = 0; k <= 20; k++) cpts.push(P(k / 20 * 0.98, 0));
            g.add(new THREE.Mesh(new THREE.TubeGeometry(new THREE.CatmullRomCurve3(cpts), 30, 0.006, 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 }),
            }));
            [-1, 1].forEach(side => {
                const root = new THREE.Group();
                root.position.set(side * 0.16, 0.26, 0.02);
                root.add(ball(0.025, colors.light, 0, 0, 0, 1, 0.6, 1.3, 8, 6));   // wing-base sclerite
                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(2.0, 0.42, side, m.membrane, m.vein, k === 0));
                    strokes.push(st); pitches.push(pt);
                }
                g.add(root);
                wings.push({ side, yaw, strokes, pitches });

                // Haltere: the drumstick balance organ behind each wing
                const hc = buildChain([{ len: .11, r0: .008, rm: .007, r1: .006, color: colors.light, angle: 0.25, radial: 5,
                                         extra: (j, d) => j.add(ball(0.026, colors.light, d.len + 0.015, 0, 0, 1.2, 0.9, 0.9, 10, 8)) }]);
                hc.root.position.set(side * 0.15, 0.13, -0.17);
                hc.root.rotation.y = yawFor(side, Math.PI * 0.62);
                g.add(hc.root);
                halteres.push({ side, joint: hc.joints[0] });
            });
        }

        function createMosquito() {
            const root = new THREE.Group();
            body = new THREE.Group();
            body.position.z = 0.5;     // spin about the middle (proboscis tip to abdomen tip)
            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 insect fits any aspect ratio ──
        let camDist = 5, camEl = 0.32;
        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.7 / (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();

            mosquito = createMosquito();
            scene.add(mosquito);

            animate();
        }

        const _c1 = new THREE.Color(colors.light), _c2 = new THREE.Color(colors.primary);
        const bump = (x, c, w) => Math.exp(-(((x - c) / w) ** 2));

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

            // Behaviour cycle (18 s): hover → probe the air (abdomen fills) → evasive jinks
            const cyc = (t / 1000) % 18;
            const probe = smooth(4.5, 5.5, cyc) * (1 - smooth(10, 11, cyc));
            const fill  = smooth(6, 10, cyc) * (1 - smooth(13, 17.5, cyc));
            const jink  = bump(cyc, 13.1, 0.12) - bump(cyc, 13.7, 0.14) + 0.7 * bump(cyc, 14.5, 0.12);

            // Hover: quick, jittery bob, plus sideways darts with a bank
            mosquito.rotation.y = userSpin + t * 0.0003;
            mosquito.position.y = Math.sin(t * 0.0018) * 0.06 + Math.sin(t * 0.0041) * 0.02;
            body.position.x = jink * 0.35;
            body.rotation.z = -jink * 0.35 + Math.sin(t * 0.0015) * 0.02;
            body.rotation.x = Math.sin(t * 0.0023) * 0.03 + probe * 0.08 + fill * 0.03;

            // Head and proboscis: labium bows while the stylets slide in and out
            head.rotation.x = probe * 0.14 + Math.sin(t * 0.0011) * 0.03;
            head.rotation.y = Math.sin(t * 0.0007) * 0.08;
            const thrust = probe * (0.5 + 0.5 * Math.sin(t * 0.009));
            proboscis.joints.forEach((j, i) => {
                const bow = i >= 2 && i <= 4 ? (i === 3 ? 0.22 : 0.12) : 0;
                j.rotation.z = proboscis.rest[i] + probe * bow * (0.6 + 0.4 * thrust) + Math.sin(t * 0.0013 + i) * 0.005;
            });
            proboscis.stylets.position.x = proboscis.styletBase + thrust * 0.26;

            // Palps twitch, antennae sway, whorls riding along
            palps.forEach(P => P.joints[0].rotation.z = -0.7 + Math.sin(t * 0.003 + P.side) * 0.06);
            for (const A of antennae) {
                A.root.rotation.y = yawFor(A.side, 0.28 + Math.sin(t * 0.0024 + A.side) * 0.07);
                A.joints[0].rotation.z = A.rest[0] + Math.sin(t * 0.0029) * 0.05;
                for (let i = 1; i < A.joints.length; i++)
                    A.joints[i].rotation.z = A.rest[i] + Math.sin(t * 0.004 - i * 0.4 + A.side) * 0.02;
            }

            // Abdomen: travelling flex and breathing, swelling as it fills
            for (const S of abdomen) {
                S.joint.rotation.z = S.rest + Math.sin(t * 0.0016 - S.i * 0.4) * 0.01 - fill * 0.006;
                const w = Math.sin(Math.PI * (S.i + 0.5) / 8);
                const s = 1 + Math.sin(t * 0.0045 - S.i * 0.6) * 0.025 + fill * 0.32 * w;
                S.mesh.scale.set(1 + fill * 0.04, s, s);
            }

            // Legs dangle and drift; hind legs rise and fall slowly
            for (const L of legs) {
                const x = t * 0.0016 + L.phase;
                const a = L.rest;
                for (let k = 0; k < a.length; k++) L.joints[k].rotation.z = a[k];
                L.joints[2].rotation.z += Math.sin(x) * 0.05;
                L.joints[3].rotation.z += Math.sin(x + 1.2) * 0.05;
                for (let k = 4; k < a.length; k++) L.joints[k].rotation.z += Math.sin(x * 1.3 - k * 0.6) * 0.03;
                if (L.pair === 2) L.joints[2].rotation.z += Math.sin(t * 0.0009 + L.side * 0.4) * 0.12;
                L.root.rotation.y = yawFor(L.side, L.fa + Math.cos(x) * 0.03 - jink * L.side * 0.05);
            }

            // Wings: continuous fast beat with motion-blur ghosts; halteres beat in antiphase
            for (const W of wings) {
                W.yaw.rotation.y = W.side * (0.14 + Math.sin(t * 0.002) * 0.04);
                for (let k = 0; k < 3; k++) {
                    const ph = (t - k * 9) * 0.07;
                    W.strokes[k].rotation.z = W.side * (0.15 + 0.55 * Math.sin(ph) + jink * W.side * 0.15);
                    W.pitches[k].rotation.x = 0.4 * Math.cos(ph);
                }
            }
            for (const H of halteres) H.joint.rotation.z = 0.25 - 0.7 * Math.sin(t * 0.07);

            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.