Skip to content
VibeCodeBench
Back to the app

The code

Lantern Cats by Claude Haiku 5.5

Exactly as the AI wrote it. Shown as text, so nothing runs on this page.

index.html

works · auto-checked (Checked by an automated pass. Not hand-played yet.)24.9 KB · 554 lines · loads cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js
Download
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>Lantern Cats</title>
<style>
html,body{margin:0;height:100%;overflow:hidden;background:#070a1f;touch-action:none;-webkit-user-select:none;user-select:none;font-family:system-ui,-apple-system,"Segoe UI",sans-serif}
canvas{position:fixed;left:0;top:0;width:100%;height:100%;display:block;touch-action:none}
#hud{position:fixed;left:16px;top:14px;color:#ffe3b3;font-size:16px;text-shadow:0 0 8px #ff8a2a;pointer-events:none;transition:opacity 2s;z-index:4}
#mute{position:fixed;right:16px;bottom:16px;min-width:112px;height:64px;padding:0 22px;border-radius:32px;border:2px solid rgba(255,214,150,.85);background:rgba(28,16,44,.85);color:#ffe3b3;font:600 20px system-ui,-apple-system,sans-serif;cursor:pointer;z-index:5}
#mute:active{transform:scale(.96)}
</style>
</head>
<body>
<div id="hud">Lantern Cats: touch and drag to guide one of them</div>
<button id="mute" type="button">Mute</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(function () {
  'use strict';
  var T = window.THREE;
  var hud = document.getElementById('hud');
  var muteBtn = document.getElementById('mute');
  if (!T) { hud.textContent = 'three.js did not load. Check the connection and reload.'; return; }

  var canvas = document.createElement('canvas');
  document.body.insertBefore(canvas, hud);
  var renderer;
  try { renderer = new T.WebGLRenderer({ canvas: canvas, antialias: true }); }
  catch (err) { hud.textContent = 'WebGL is not available on this device.'; return; }
  var pr = Math.min(window.devicePixelRatio || 1, 2);
  renderer.setPixelRatio(pr);
  renderer.setClearColor(0x070a1f, 1);

  var demo = /#demo$/i.test(location.href);
  var muted = false;
  var t = 0, demoClock = 0;
  var seed = 1234567;
  function rnd() { seed = (seed * 16807) % 2147483647; return seed / 2147483647; }
  function rr(a, b) { return a + rnd() * (b - a); }

  var scene = new T.Scene();
  scene.fog = new T.Fog(0x3a2a55, 120, 430);
  var camera = new T.PerspectiveCamera(50, 1, 0.5, 700);
  scene.add(new T.HemisphereLight(0xb8c8ff, 0x2a2238, 0.9));
  var moonLight = new T.DirectionalLight(0xdfe8ff, 0.55);
  moonLight.position.set(-80, 120, -60);
  scene.add(moonLight);

  function makeGlow() {
    var cv = document.createElement('canvas'); cv.width = cv.height = 64;
    var g = cv.getContext('2d');
    var gr = g.createRadialGradient(32, 32, 0, 32, 32, 32);
    gr.addColorStop(0, 'rgba(255,255,255,1)');
    gr.addColorStop(0.3, 'rgba(255,255,255,0.45)');
    gr.addColorStop(1, 'rgba(255,255,255,0)');
    g.fillStyle = gr; g.fillRect(0, 0, 64, 64);
    return new T.CanvasTexture(cv);
  }
  var glow = makeGlow();

  // Sky dome with a vertical gradient
  var skyGeo = new T.SphereGeometry(480, 24, 16);
  var skyPos = skyGeo.attributes.position, skyCol = [];
  var cTop = new T.Color(0x060a24), cHor = new T.Color(0x4b2d5e), cc = new T.Color();
  var i;
  for (i = 0; i < skyPos.count; i++) {
    var sy = skyPos.getY(i) / 480;
    if (sy >= 0) cc.copy(cHor).lerp(cTop, Math.pow(sy, 0.6));
    else cc.copy(cHor).multiplyScalar(0.55);
    skyCol.push(cc.r, cc.g, cc.b);
  }
  skyGeo.setAttribute('color', new T.Float32BufferAttribute(skyCol, 3));
  scene.add(new T.Mesh(skyGeo, new T.MeshBasicMaterial({ vertexColors: true, side: T.BackSide, fog: false })));

  var starArr = [];
  for (i = 0; i < 420; i++) {
    var sx = rnd() - 0.5, sy2 = rnd() * 0.9 + 0.1, sz = rnd() - 0.5;
    var sl = Math.sqrt(sx * sx + sy2 * sy2 + sz * sz);
    starArr.push(sx / sl * 420, sy2 / sl * 420, sz / sl * 420);
  }
  var starGeo = new T.BufferGeometry();
  starGeo.setAttribute('position', new T.Float32BufferAttribute(starArr, 3));
  scene.add(new T.Points(starGeo, new T.PointsMaterial({ color: 0xffffff, size: 1.6, sizeAttenuation: false, transparent: true, opacity: 0.75, fog: false })));

  var moon = new T.Mesh(new T.SphereGeometry(10, 24, 16), new T.MeshBasicMaterial({ color: 0xfff1d2, fog: false }));
  moon.position.set(120, 110, -330);
  scene.add(moon);
  var halo = new T.Sprite(new T.SpriteMaterial({ map: glow, color: 0xffd9a0, transparent: true, opacity: 0.55, blending: T.AdditiveBlending, depthWrite: false, fog: false }));
  halo.position.copy(moon.position); halo.scale.set(90, 90, 1);
  scene.add(halo);

  // Far bank (ground) and the river (water) that starts at z = -26
  var ground = new T.Mesh(new T.PlaneGeometry(900, 460), new T.MeshStandardMaterial({ color: 0x1b2032, roughness: 1 }));
  ground.rotation.x = -Math.PI / 2;
  ground.position.set(0, 0, -256);
  scene.add(ground);

  // Water reflects the real scene: a mirrored camera renders into a texture that the water samples
  var reflRT = new T.WebGLRenderTarget(512, 288, { minFilter: T.LinearFilter, magFilter: T.LinearFilter });
  var vcam = new T.PerspectiveCamera(50, 16 / 9, 0.5, 700);
  var texMat = new T.Matrix4();
  var biasM = new T.Matrix4().set(0.5, 0, 0, 0.5, 0, 0.5, 0, 0.5, 0, 0, 0.5, 0.5, 0, 0, 0, 1);
  var waterMat = new T.ShaderMaterial({
    uniforms: {
      tRef: { value: reflRT.texture }, tm: { value: texMat },
      tint: { value: new T.Color(0x0a1d3f) }, time: { value: 0 }
    },
    vertexShader: 'uniform mat4 tm; varying vec4 vUv; void main() { vUv = tm * vec4(position, 1.0); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }',
    fragmentShader: 'uniform sampler2D tRef; uniform vec3 tint; uniform float time; varying vec4 vUv; void main() { vec2 uv = vUv.xy / vUv.w; uv += vec2(sin(uv.y * 140.0 + time * 1.6), cos(uv.x * 90.0 - time * 1.2)) * 0.0035; vec3 r = texture2D(tRef, uv).rgb; gl_FragColor = vec4(mix(tint, r * 1.05, 0.8), 1.0); }'
  });
  var wgeo = new T.PlaneGeometry(900, 600);
  wgeo.rotateX(-Math.PI / 2);
  wgeo.translate(0, 0.03, 274);
  var water = new T.Mesh(wgeo, waterMat);
  scene.add(water);

  // Town on the far bank: instanced houses with lit windows
  var houses = [];
  var row, hx0;
  for (row = 0; row < 4; row++) {
    for (hx0 = -92; hx0 <= 92; hx0 += 6.4) {
      if (rnd() < 0.2) continue;
      var hw = 2.8 + rnd() * 1.8, hd = 2.8 + rnd() * 1.6, hh = 2.6 + rnd() * 3.2;
      houses.push({ x: hx0 + (rnd() - 0.5) * 2.2, z: -32 - row * 6.5 + (rnd() - 0.5) * 1.2, w: hw, d: hd, h: hh, top: hh + 2.2 });
    }
  }
  var winCv = document.createElement('canvas'); winCv.width = winCv.height = 128;
  var wctx = winCv.getContext('2d');
  wctx.fillStyle = '#000'; wctx.fillRect(0, 0, 128, 128);
  var wy, wx;
  for (wy = 0; wy < 4; wy++) for (wx = 0; wx < 3; wx++) {
    if (rnd() < 0.55) { wctx.fillStyle = rnd() < 0.7 ? '#ffc56b' : '#ff9a5a'; wctx.fillRect(14 + wx * 38, 12 + wy * 28, 18, 16); }
  }
  var wallMat = new T.MeshStandardMaterial({ color: 0x2e2648, emissive: 0xffffff, emissiveMap: new T.CanvasTexture(winCv), emissiveIntensity: 0.9, roughness: 0.9 });
  var roofMat = new T.MeshStandardMaterial({ color: 0x3a1f2e, roughness: 0.8 });
  var wallGeo = new T.BoxGeometry(1, 1, 1);
  var roofGeo = new T.ConeGeometry(0.7071, 1, 4); roofGeo.rotateY(Math.PI / 4);
  var walls = new T.InstancedMesh(wallGeo, wallMat, houses.length);
  var roofs = new T.InstancedMesh(roofGeo, roofMat, houses.length);
  var m4 = new T.Matrix4(), qI = new T.Quaternion(), vP = new T.Vector3(), vS = new T.Vector3();
  houses.forEach(function (hs, n) {
    walls.setMatrixAt(n, m4.compose(vP.set(hs.x, hs.h / 2, hs.z), qI, vS.set(hs.w, hs.h, hs.d)));
    roofs.setMatrixAt(n, m4.compose(vP.set(hs.x, hs.h + 1.1, hs.z), qI, vS.set(hs.w * 1.04, 2.2, hs.d * 1.04)));
  });
  walls.instanceMatrix.needsUpdate = true; roofs.instanceMatrix.needsUpdate = true;
  scene.add(walls); scene.add(roofs);

  // Strings of festival lights across the town
  var bulbPos = [], bulbCol = [];
  var strings = new T.Group();
  [[-33, 12.5], [-39, 13.5], [-45, 12], [-51, 13]].forEach(function (sg) {
    var pts = [], j;
    for (j = 0; j <= 60; j++) {
      var u = j / 60;
      pts.push(new T.Vector3(-96 + u * 192, sg[1] - 12.8 * u * (1 - u), sg[0]));
    }
    strings.add(new T.Line(new T.BufferGeometry().setFromPoints(pts), new T.LineBasicMaterial({ color: 0xffc27a, transparent: true, opacity: 0.6 })));
    for (j = 0; j < pts.length; j += 3) { bulbPos.push(pts[j].x, pts[j].y, pts[j].z); bulbCol.push(1, 0.75, 0.4); }
  });
  var bulbGeo = new T.BufferGeometry();
  bulbGeo.setAttribute('position', new T.Float32BufferAttribute(bulbPos, 3));
  bulbGeo.setAttribute('color', new T.Float32BufferAttribute(bulbCol, 3));
  strings.add(new T.Points(bulbGeo, new T.PointsMaterial({ size: 1.8, map: glow, vertexColors: true, transparent: true, depthWrite: false, blending: T.AdditiveBlending })));
  scene.add(strings);

  // Two paper-lantern cats: a chain of segments that follows the head
  var SEG = 14, TAIL = 7, N = 1 + SEG + TAIL;
  function segRad(k) {
    if (k === 0) return 1.25;
    if (k <= SEG) return 1.05 - 0.2 * (k - 1) / (SEG - 1);
    return 0.8 - 0.55 * (k - SEG - 1) / (TAIL - 1);
  }
  function gapOf(k) { return k === 1 ? 1.9 : 1.25; }

  function makeCat(o) {
    var root = new T.Group();
    var bodyMat = new T.MeshStandardMaterial({ color: o.col, emissive: o.emis, emissiveIntensity: 0.9, roughness: 0.55 });
    var sphere = new T.SphereGeometry(1, 16, 12);
    var segs = [], k, m;
    for (k = 1; k < N; k++) {
      m = new T.Mesh(sphere, bodyMat);
      m.scale.setScalar(segRad(k));
      root.add(m); segs.push(m);
    }
    var head = new T.Group(); root.add(head);
    head.add(new T.Mesh(new T.SphereGeometry(1.25, 18, 14), bodyMat));
    var earGeo = new T.ConeGeometry(0.5, 1.2, 12);
    var earL = new T.Mesh(earGeo, bodyMat), earR = new T.Mesh(earGeo, bodyMat);
    earL.position.set(-0.7, 1.15, 0.05); earR.position.set(0.7, 1.15, 0.05);
    head.add(earL); head.add(earR);
    var eyeMat = new T.MeshBasicMaterial({ color: o.eye }), eyeGeo = new T.SphereGeometry(0.17, 10, 8);
    var eyeL = new T.Mesh(eyeGeo, eyeMat), eyeR = new T.Mesh(eyeGeo, eyeMat);
    eyeL.position.set(-0.5, 0.25, 1.1); eyeR.position.set(0.5, 0.25, 1.1);
    head.add(eyeL); head.add(eyeR);
    var nose = new T.Mesh(new T.SphereGeometry(0.14, 8, 6), new T.MeshBasicMaterial({ color: 0xff8fa6 }));
    nose.position.set(0, -0.12, 1.25); head.add(nose);
    var wp = [];
    [-1, 1].forEach(function (sd) {
      [0.05, -0.25, -0.55].forEach(function (yy) { wp.push(sd * 0.9, yy, 1.0, sd * 3.0, yy - 0.15, 1.5); });
    });
    var whGeo = new T.BufferGeometry();
    whGeo.setAttribute('position', new T.Float32BufferAttribute(wp, 3));
    var wh = new T.Group();
    wh.add(new T.LineSegments(whGeo, new T.LineBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0.7 })));
    head.add(wh);
    scene.add(root);
    var core = [], disp = [];
    for (k = 0; k < N; k++) { core.push(new T.Vector3(o.x - k * 1.3, o.y, o.z)); disp.push(new T.Vector3()); }
    return {
      head: head, segs: segs, earL: earL, earR: earR, wh: wh, core: core, disp: disp,
      vel: new T.Vector3(o.vx, 0, 0), fwd: new T.Vector3(1, 0, 0), tgt: new T.Vector3(o.x, o.y, o.z),
      wt: 0, mode: 'wander', modeT: o.modeT, fing: new T.Vector3(), fingT: 0, phase: o.phase, sp: o.sp
    };
  }
  var cats = [
    makeCat({ col: 0xff8a3d, emis: 0xff5a14, eye: 0xfff27a, x: -14, y: 14, z: -10, vx: 6, phase: 0, sp: 10, modeT: 6 }),
    makeCat({ col: 0xd9e0ec, emis: 0x9db3d8, eye: 0x9fe8ff, x: 16, y: 12, z: -20, vx: -5, phase: 2.2, sp: 9.2, modeT: 8 })
  ];
  var orange = cats[0], silver = cats[1];

  var tmpT = new T.Vector3(), des = new T.Vector3(), tang = new T.Vector3(), side = new T.Vector3();
  var UP = new T.Vector3(0, 1, 0), ZERO = new T.Vector3(), mtx = new T.Matrix4(), tv = new T.Vector3(), tv2 = new T.Vector3();

  // Keep points out of houses (a house is a box with a pitched roof)
  function pushOut(p, r) {
    for (var n = 0; n < houses.length; n++) {
      var h = houses[n];
      if (p.y > h.top + r) continue;
      var dx = p.x - h.x, dz = p.z - h.z;
      var ex = h.w / 2 + r, ez = h.d / 2 + r;
      if (Math.abs(dx) >= ex || Math.abs(dz) >= ez) continue;
      if (ex - Math.abs(dx) < ez - Math.abs(dz)) p.x = h.x + (dx < 0 ? -ex : ex);
      else p.z = h.z + (dz < 0 ? -ez : ez);
    }
  }

  function steer(c, o, dt) {
    c.modeT -= dt;
    if (c.modeT <= 0) {
      c.mode = c.mode === 'chase' ? 'wander' : 'chase';
      c.modeT = c.mode === 'chase' ? 9 : 5;
    }
    var h = c.core[0], sp = c.sp;
    if (c.fingT > 0) {
      c.fingT -= dt; tmpT.copy(c.fing); sp = c.sp * 1.7;
    } else if (c.mode === 'chase') {
      tmpT.copy(o.core[4]).addScaledVector(o.vel, 0.8); sp = c.sp * 1.12;
    } else {
      c.wt -= dt;
      if (c.wt <= 0 || h.distanceTo(c.tgt) < 3) {
        c.wt = rr(2.5, 5.5);
        c.tgt.set(rr(-44, 44), rr(10, 19), rr(-46, 8));
      }
      tmpT.copy(c.tgt);
    }
    var dx = tmpT.x - h.x, dy = tmpT.y - h.y, dz = tmpT.z - h.z;
    var L = Math.sqrt(dx * dx + dy * dy + dz * dz) || 1;
    var ds = Math.min(sp, L * 0.8);
    des.set(dx / L * ds, dy / L * ds, dz / L * ds);
    c.vel.lerp(des, Math.min(1, dt * 1.4));
    c.vel.y += Math.sin(t * 0.9 + c.phase) * dt * 1.5;
    var vl = c.vel.length();
    if (vl > sp * 1.2) c.vel.multiplyScalar(sp * 1.2 / vl);
    h.addScaledVector(c.vel, dt);
    h.x = Math.max(-50, Math.min(50, h.x));
    h.y = Math.max(9.5, Math.min(21, h.y));
    h.z = Math.max(-52, Math.min(12, h.z));
  }

  // Body: each segment follows the one in front of it, then gets a wave and house push-out
  function chain(c) {
    var core = c.core, k;
    pushOut(core[0], segRad(0));
    for (k = 1; k < N; k++) {
      var p = core[k - 1], q = core[k];
      tang.subVectors(q, p);
      var len = tang.length();
      if (len < 1e-5) { tang.set(0, 0, 1); len = 1; }
      q.copy(p).addScaledVector(tang, gapOf(k) / len);
      pushOut(q, segRad(k));
    }
    for (k = 0; k < N; k++) {
      var a = core[Math.max(0, k - 1)], b = core[Math.min(N - 1, k + 1)];
      tang.subVectors(a, b);
      side.crossVectors(tang, UP);
      if (side.lengthSq() < 1e-6) side.set(1, 0, 0); else side.normalize();
      var amp = k <= SEG ? 0.1 + 0.5 * k / SEG : 0.7 + 0.9 * (k - SEG) / TAIL;
      var ph = t * 2.6 + c.phase - k * 0.55;
      var d = c.disp[k];
      d.copy(core[k]).addScaledVector(side, amp * Math.sin(ph));
      d.y += 0.35 * amp * Math.sin(ph * 0.5 + 1.3);
      pushOut(d, segRad(k));
    }
  }

  // Keep the two cats from passing through each other
  function separate(x, y) {
    for (var i1 = 0; i1 < N; i1++) for (var j1 = 0; j1 < N; j1++) {
      var p = x.disp[i1], q = y.disp[j1];
      var minD = segRad(i1) + segRad(j1) + 0.4;
      var dX = p.x - q.x, dY = p.y - q.y, dZ = p.z - q.z;
      var d2 = dX * dX + dY * dY + dZ * dZ;
      if (d2 >= minD * minD) continue;
      var dd = Math.sqrt(d2) || 0.001;
      var push = (minD - dd) * 0.5;
      var nx = dX / dd * push, ny = dY / dd * push, nz = dZ / dd * push;
      p.x += nx; p.y += ny; p.z += nz;
      q.x -= nx; q.y -= ny; q.z -= nz;
    }
  }

  function applyCat(c, dt) {
    var k;
    for (k = 1; k < N; k++) c.segs[k - 1].position.copy(c.disp[k]);
    c.head.position.copy(c.disp[0]);
    if (c.vel.lengthSq() > 0.01) { tv.copy(c.vel).normalize(); c.fwd.lerp(tv, Math.min(1, dt * 4)); }
    if (c.fwd.lengthSq() < 1e-6) c.fwd.set(1, 0, 0);
    c.fwd.normalize();
    tv2.copy(c.fwd).negate();
    mtx.lookAt(ZERO, tv2, UP);
    c.head.quaternion.setFromRotationMatrix(mtx);
    c.earL.rotation.z = 0.45 + 0.22 * Math.sin(t * 6 + c.phase);
    c.earR.rotation.z = -0.45 - 0.22 * Math.sin(t * 6 + c.phase + 0.6);
    c.wh.rotation.z = 0.12 * Math.sin(t * 5 + c.phase);
  }

  // Floating lanterns
  var NL = 150, lanPos = new Float32Array(NL * 3), lanCol = new Float32Array(NL * 3), lanVel = new Float32Array(NL), lanPh = new Float32Array(NL);
  function spawnLantern(n, y) {
    lanPos[n * 3] = rr(-90, 90); lanPos[n * 3 + 1] = y; lanPos[n * 3 + 2] = rr(-70, 10);
    lanVel[n] = rr(1.2, 2.6); lanPh[n] = rnd() * 6.28;
    var kk = rnd();
    lanCol[n * 3] = 1.0; lanCol[n * 3 + 1] = 0.5 + 0.35 * kk; lanCol[n * 3 + 2] = 0.15 + 0.2 * kk;
  }
  for (i = 0; i < NL; i++) spawnLantern(i, rr(0, 50));
  var lanPosAttr = new T.BufferAttribute(lanPos, 3); lanPosAttr.setUsage(T.DynamicDrawUsage);
  var lanGeo = new T.BufferGeometry();
  lanGeo.setAttribute('position', lanPosAttr);
  lanGeo.setAttribute('color', new T.BufferAttribute(lanCol, 3));
  scene.add(new T.Points(lanGeo, new T.PointsMaterial({ size: 2.6, map: glow, vertexColors: true, transparent: true, depthWrite: false, blending: T.AdditiveBlending })));
  function updateLanterns(dt) {
    for (var n = 0; n < NL; n++) {
      lanPos[n * 3 + 1] += lanVel[n] * dt;
      lanPos[n * 3] += Math.sin(t * 0.7 + lanPh[n]) * 1.2 * dt;
      if (lanPos[n * 3 + 1] > 55) spawnLantern(n, rr(0, 3));
    }
    lanPosAttr.needsUpdate = true;
  }

  // Sparks
  var NS = 160, spPos = new Float32Array(NS * 3), spCol = new Float32Array(NS * 3), spVel = new Float32Array(NS * 3), spLife = new Float32Array(NS), spMax = new Float32Array(NS);
  function spawnSpark(n) {
    var c = rnd() < 0.5 ? orange : silver;
    var p = c.disp[Math.floor(rnd() * N)];
    spPos[n * 3] = p.x + rr(-1, 1); spPos[n * 3 + 1] = p.y + rr(-1, 1); spPos[n * 3 + 2] = p.z + rr(-1, 1);
    spVel[n * 3] = rr(-1.5, 1.5); spVel[n * 3 + 1] = rr(0.5, 3); spVel[n * 3 + 2] = rr(-1.5, 1.5);
    spMax[n] = rr(1.2, 2.4); spLife[n] = spMax[n];
  }
  for (i = 0; i < NS; i++) { spawnSpark(i); spLife[i] = rr(0, spMax[i]); }
  var spPosAttr = new T.BufferAttribute(spPos, 3); spPosAttr.setUsage(T.DynamicDrawUsage);
  var spColAttr = new T.BufferAttribute(spCol, 3); spColAttr.setUsage(T.DynamicDrawUsage);
  var spGeo = new T.BufferGeometry();
  spGeo.setAttribute('position', spPosAttr); spGeo.setAttribute('color', spColAttr);
  scene.add(new T.Points(spGeo, new T.PointsMaterial({ size: 1.2, map: glow, vertexColors: true, transparent: true, depthWrite: false, blending: T.AdditiveBlending })));
  function updateSparks(dt) {
    for (var n = 0; n < NS; n++) {
      spLife[n] -= dt;
      if (spLife[n] <= 0) spawnSpark(n);
      var b = n * 3;
      spPos[b] += spVel[b] * dt; spPos[b + 1] += spVel[b + 1] * dt; spPos[b + 2] += spVel[b + 2] * dt;
      spVel[b + 1] -= 0.6 * dt;
      var f = Math.max(0, spLife[n] / spMax[n]);
      spCol[b] = 1.0 * f; spCol[b + 1] = 0.82 * f; spCol[b + 2] = 0.45 * f;
    }
    spPosAttr.needsUpdate = true; spColAttr.needsUpdate = true;
  }

  // Camera: slow drift that follows the middle of the two cats
  var focus = new T.Vector3(0, 12, -10), camLook = new T.Vector3();
  function updateCamera(dt) {
    var cx = (orange.core[0].x + silver.core[0].x) * 0.5;
    var k = 1 - Math.exp(-dt * 0.6);
    focus.x += (cx - focus.x) * k;
    var dist = Math.max(64, 74 / camera.aspect) * (1 + 0.05 * Math.sin(t * 0.05));
    camera.position.set(focus.x * 0.5 + Math.sin(t * 0.045) * 12, 15.5 + Math.sin(t * 0.031) * 1.6, dist + Math.cos(t * 0.04) * 3);
    camLook.set(focus.x * 0.6, 9 + Math.sin(t * 0.07) * 0.5, -12);
    camera.lookAt(camLook);
  }

  function renderReflection() {
    vcam.position.set(camera.position.x, -camera.position.y, camera.position.z);
    vcam.lookAt(camLook.x, -camLook.y, camLook.z);
    vcam.updateMatrixWorld(true);
    texMat.multiplyMatrices(biasM, vcam.projectionMatrix);
    texMat.multiply(vcam.matrixWorldInverse);
    water.visible = false;
    renderer.setRenderTarget(reflRT);
    renderer.render(scene, vcam);
    renderer.setRenderTarget(null);
    water.visible = true;
  }

  // Touch and mouse: the nearest cat follows the finger for a while
  var ray = new T.Raycaster(), ndc = new T.Vector2();
  var floorPlane = new T.Plane(new T.Vector3(0, 1, 0), -13), hitPt = new T.Vector3();
  function pointOnPlane(e) {
    ndc.set((e.clientX / window.innerWidth) * 2 - 1, -(e.clientY / window.innerHeight) * 2 + 1);
    ray.setFromCamera(ndc, camera);
    return ray.ray.intersectPlane(floorPlane, hitPt) ? hitPt.clone() : null;
  }
  var activeCat = null, dragging = false;
  function follow(e) {
    var p = pointOnPlane(e);
    if (!p) return;
    if (!activeCat) {
      var best = null, bd = Infinity;
      cats.forEach(function (c) {
        var h = c.core[0], d = (h.x - p.x) * (h.x - p.x) + (h.z - p.z) * (h.z - p.z);
        if (d < bd) { bd = d; best = c; }
      });
      activeCat = best;
    }
    activeCat.fing.copy(p); activeCat.fingT = 4;
  }
  canvas.addEventListener('pointerdown', function (e) {
    e.preventDefault();
    demo = false;
    audioStart();
    dragging = true; activeCat = null;
    try { canvas.setPointerCapture(e.pointerId); } catch (err) {}
    follow(e);
  });
  canvas.addEventListener('pointermove', function (e) { if (dragging) follow(e); });
  function endDrag() { dragging = false; activeCat = null; }
  window.addEventListener('pointerup', endDrag);
  window.addEventListener('pointercancel', endDrag);
  setTimeout(function () { hud.style.opacity = '0'; }, 9000);

  // Demo mode (#demo): a 20 second hands-free loop with a simulated finger
  var simP = new T.Vector3();
  function simulateFinger(c) {
    if (c < 2 || c > 16) return;
    var a = (c - 2) * 0.55;
    simP.set(orange.core[0].x + Math.cos(a) * 7, 13, -12 + Math.sin(a * 1.6) * 6);
    orange.fing.copy(simP); orange.fingT = 0.5;
  }

  // Soft melody made with code (Web Audio), with a light echo
  var AC = null, master = null, sendBus = null, nextT = 0, stepN = 0;
  var STEP = 60 / 92 / 2;
  var SCALE = [220, 261.63, 293.66, 329.63, 392, 440, 523.25, 587.33, 659.25];
  var CHORDS = [[110, 130.81, 164.81], [87.31, 110, 130.81], [130.81, 164.81, 196], [98, 123.47, 146.83]];
  var MELODY = [];
  (function () {
    var sd = 987654, idx = 3;
    function r() { sd = (sd * 16807) % 2147483647; return sd / 2147483647; }
    for (var n = 0; n < 32; n++) {
      if (n % 8 === 7 || r() < 0.15) { MELODY.push(-1); continue; }
      idx += r() < 0.5 ? -1 : 1;
      idx = Math.max(0, Math.min(SCALE.length - 1, idx));
      MELODY.push(idx);
    }
  })();
  function tone(f, when, dur, vol) {
    var o = AC.createOscillator(), g = AC.createGain();
    o.type = 'sine'; o.frequency.value = f;
    g.gain.setValueAtTime(0.0001, when);
    g.gain.exponentialRampToValueAtTime(vol, when + 0.05);
    g.gain.exponentialRampToValueAtTime(0.0001, when + dur);
    o.connect(g); g.connect(master); g.connect(sendBus);
    o.start(when); o.stop(when + dur + 0.1);
  }
  function pad(chord, when, dur) {
    chord.forEach(function (f) {
      var o = AC.createOscillator(), g = AC.createGain();
      o.type = 'sine'; o.frequency.value = f;
      g.gain.setValueAtTime(0.0001, when);
      g.gain.exponentialRampToValueAtTime(0.035, when + 1.0);
      g.gain.exponentialRampToValueAtTime(0.0001, when + dur + 0.6);
      o.connect(g); g.connect(master);
      o.start(when); o.stop(when + dur + 0.7);
    });
  }
  function schedule() {
    if (!AC) return;
    if (nextT < AC.currentTime) nextT = AC.currentTime + 0.05;
    while (nextT < AC.currentTime + 0.3) {
      var n = MELODY[stepN % 32];
      if (n >= 0) tone(SCALE[n], nextT, STEP * 1.8, 0.12);
      if (stepN % 16 === 0) pad(CHORDS[Math.floor(stepN / 16) % CHORDS.length], nextT, STEP * 16);
      nextT += STEP; stepN++;
    }
  }
  function audioStart() {
    try {
      if (AC) { if (AC.state === 'suspended') AC.resume(); return; }
      var Ctx = window.AudioContext || window.webkitAudioContext;
      if (!Ctx) return;
      AC = new Ctx();
      master = AC.createGain(); master.gain.value = muted ? 0 : 0.2; master.connect(AC.destination);
      sendBus = AC.createGain(); sendBus.gain.value = 0.35;
      var dl = AC.createDelay(1.5); dl.delayTime.value = 0.49;
      var fb = AC.createGain(); fb.gain.value = 0.42;
      var lp = AC.createBiquadFilter(); lp.type = 'lowpass'; lp.frequency.value = 2200;
      sendBus.connect(dl); dl.connect(lp); lp.connect(fb); fb.connect(dl); lp.connect(master);
      nextT = AC.currentTime + 0.15; stepN = 0;
      setInterval(schedule, 110);
    } catch (err) { AC = null; }
  }
  function applyMute() {
    muteBtn.textContent = muted ? 'Sound on' : 'Mute';
    try { if (master) master.gain.setTargetAtTime(muted ? 0 : 0.2, AC.currentTime, 0.05); } catch (err) {}
  }
  muteBtn.addEventListener('click', function () { audioStart(); muted = !muted; applyMute(); });

  // Layout
  function resize() {
    var w = window.innerWidth, h = window.innerHeight;
    renderer.setSize(w, h, false);
    camera.aspect = w / h; camera.updateProjectionMatrix();
    var rw = Math.max(64, Math.round(w * pr * 0.5)), rh = Math.max(64, Math.round(h * pr * 0.5));
    reflRT.setSize(rw, rh);
    vcam.aspect = rw / rh; vcam.updateProjectionMatrix();
  }
  window.addEventListener('resize', resize);

  // Main loop
  var lastNow = 0;
  function frame(now) {
    var s = now / 1000;
    var dt = lastNow ? Math.min(0.05, Math.max(0.001, s - lastNow)) : 0.016;
    lastNow = s;
    t += dt;
    if (demo) { demoClock = (demoClock + dt) % 20; simulateFinger(demoClock); }
    steer(orange, silver, dt);
    steer(silver, orange, dt);
    chain(orange); chain(silver);
    separate(orange, silver);
    applyCat(orange, dt); applyCat(silver, dt);
    updateLanterns(dt); updateSparks(dt);
    updateCamera(dt);
    waterMat.uniforms.time.value = t;
    renderReflection();
    renderer.render(scene, camera);
    requestAnimationFrame(frame);
  }
  resize();
  requestAnimationFrame(frame);
})();
</script>
</body>
</html>