Skip to content
VibeCodeBench
Back to the app

The code

Jelly Cat by Gemini 4 Hydrogen

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.)98.3 KB · 2,737 lines · loads cdn.jsdelivr.net/npm/[email protected]/build/three.min.js
Download
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <title>Orange Jelly Cat</title>
  <style>
    :root {
      --bg-top: #fff5ea;
      --bg-bottom: #f6dec8;
      --ink: #4b2610;
      --ink-soft: rgba(75, 38, 16, 0.68);
      --glass: rgba(255, 250, 244, 0.78);
      --glass-border: rgba(255, 255, 255, 0.85);
      --accent: #ff7b1c;
      --accent-deep: #e25600;
      --accent-glow: rgba(255, 123, 28, 0.34);
    }

    * {
      box-sizing: border-box;
      -webkit-tap-highlight-color: transparent;
      user-select: none;
      -webkit-user-select: none;
    }

    html, body {
      margin: 0;
      padding: 0;
      width: 100%;
      height: 100%;
      overflow: hidden;
      background: radial-gradient(circle at 50% 35%, var(--bg-top) 0%, var(--bg-bottom) 100%);
      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
      color: var(--ink);
    }

    #scene-canvas {
      display: block;
      width: 100%;
      height: 100%;
      touch-action: none;
      cursor: grab;
    }

    #scene-canvas.grabbing {
      cursor: grabbing;
    }

    #scene-canvas.on-cat {
      cursor: pointer;
    }

    /* Subtle top pill hint + audio toggle */
    .top-bar {
      position: fixed;
      top: max(12px, env(safe-area-inset-top));
      left: 12px;
      right: 12px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      gap: 10px;
      pointer-events: none;
      z-index: 10;
    }

    .hint-pill {
      pointer-events: none;
      padding: 8px 14px;
      border-radius: 999px;
      background: var(--glass);
      border: 1px solid var(--glass-border);
      backdrop-filter: blur(12px);
      -webkit-backdrop-filter: blur(12px);
      box-shadow: 0 6px 20px rgba(120, 60, 20, 0.08);
      font-size: 13px;
      font-weight: 600;
      color: var(--ink-soft);
      letter-spacing: 0.01em;
      line-height: 1.25;
      max-width: calc(100% - 64px);
    }

    .sound-btn {
      pointer-events: auto;
      min-width: 48px;
      height: 48px;
      padding: 0 14px;
      border-radius: 999px;
      border: 1px solid var(--glass-border);
      background: var(--glass);
      backdrop-filter: blur(12px);
      -webkit-backdrop-filter: blur(12px);
      box-shadow: 0 6px 20px rgba(120, 60, 20, 0.1);
      color: var(--ink);
      font-size: 18px;
      font-weight: 700;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      cursor: pointer;
      touch-action: manipulation;
      transition: transform 0.14s ease, background 0.14s ease;
    }

    .sound-btn:active {
      transform: scale(0.94);
    }

    .sound-btn.muted {
      opacity: 0.65;
    }

    /* Bottom control dock */
    .controls-dock {
      position: fixed;
      left: 50%;
      bottom: max(14px, env(safe-area-inset-bottom));
      transform: translateX(-50%);
      width: min(94vw, 560px);
      padding: 12px 14px;
      border-radius: 26px;
      background: var(--glass);
      border: 1.5px solid var(--glass-border);
      backdrop-filter: blur(16px);
      -webkit-backdrop-filter: blur(16px);
      box-shadow: 0 14px 36px rgba(130, 58, 12, 0.14);
      display: flex;
      align-items: center;
      gap: 14px;
      z-index: 10;
    }

    .drop-btn {
      flex: 0 0 auto;
      min-height: 54px;
      padding: 0 20px;
      border: none;
      border-radius: 18px;
      background: linear-gradient(180deg, #ff993b 0%, var(--accent) 55%, var(--accent-deep) 100%);
      color: #fffaf4;
      font-size: 15px;
      font-weight: 800;
      letter-spacing: 0.01em;
      box-shadow:
        0 6px 16px var(--accent-glow),
        inset 0 2px 3px rgba(255, 255, 255, 0.55);
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      cursor: pointer;
      touch-action: manipulation;
      transition: transform 0.12s cubic-bezier(0.2, 0.9, 0.3, 1.4), box-shadow 0.12s ease;
    }

    .drop-btn:active {
      transform: scale(0.94) translateY(1px);
      box-shadow: 0 3px 10px var(--accent-glow);
    }

    .slider-wrap {
      flex: 1 1 auto;
      min-width: 0;
      display: flex;
      flex-direction: column;
      gap: 6px;
    }

    .slider-labels {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      font-weight: 700;
      color: var(--ink-soft);
      padding: 0 2px;
    }

    .slider-labels .firmness-readout {
      color: var(--accent-deep);
      font-weight: 800;
    }

    input[type="range"].jelly-slider {
      -webkit-appearance: none;
      appearance: none;
      width: 100%;
      height: 34px;
      margin: 0;
      background: transparent;
      cursor: pointer;
      touch-action: pan-x;
    }

    input[type="range"].jelly-slider:focus {
      outline: none;
    }

    input[type="range"].jelly-slider::-webkit-slider-runnable-track {
      height: 14px;
      border-radius: 999px;
      background: linear-gradient(90deg, #ffd19e 0%, #ff9338 55%, #e55900 100%);
      box-shadow: inset 0 2px 4px rgba(110, 42, 0, 0.2), 0 1px 0 rgba(255, 255, 255, 0.8);
    }

    input[type="range"].jelly-slider::-webkit-slider-thumb {
      -webkit-appearance: none;
      appearance: none;
      width: 30px;
      height: 30px;
      border-radius: 50%;
      margin-top: -8px;
      background: radial-gradient(circle at 32% 28%, #ffffff 0%, #ffe6cb 45%, #ff8929 100%);
      border: 2.5px solid #ffffff;
      box-shadow: 0 4px 10px rgba(155, 62, 0, 0.35);
      transition: transform 0.12s ease;
    }

    input[type="range"].jelly-slider:active::-webkit-slider-thumb {
      transform: scale(1.12);
    }

    input[type="range"].jelly-slider::-moz-range-track {
      height: 14px;
      border-radius: 999px;
      background: linear-gradient(90deg, #ffd19e 0%, #ff9338 55%, #e55900 100%);
      box-shadow: inset 0 2px 4px rgba(110, 42, 0, 0.2), 0 1px 0 rgba(255, 255, 255, 0.8);
    }

    input[type="range"].jelly-slider::-moz-range-thumb {
      width: 30px;
      height: 30px;
      border-radius: 50%;
      background: radial-gradient(circle at 32% 28%, #ffffff 0%, #ffe6cb 45%, #ff8929 100%);
      border: 2.5px solid #ffffff;
      box-shadow: 0 4px 10px rgba(155, 62, 0, 0.35);
    }

    /* Demo mode virtual finger indicator */
    .demo-cursor {
      position: fixed;
      width: 36px;
      height: 36px;
      margin-left: -18px;
      margin-top: -18px;
      border-radius: 50%;
      background: radial-gradient(circle at 35% 35%, rgba(255, 255, 255, 0.95), rgba(255, 145, 50, 0.58));
      border: 2.5px solid rgba(255, 255, 255, 0.95);
      box-shadow: 0 4px 18px rgba(255, 110, 20, 0.45);
      pointer-events: none;
      opacity: 0;
      transform: scale(1);
      transition: opacity 0.25s ease, transform 0.12s ease;
      z-index: 20;
    }

    .demo-cursor.visible {
      opacity: 0.92;
    }

    .demo-cursor.pressing {
      transform: scale(0.76);
      box-shadow: 0 2px 24px rgba(255, 95, 0, 0.72);
    }

    .demo-badge {
      position: fixed;
      top: max(68px, calc(env(safe-area-inset-top) + 54px));
      left: 12px;
      padding: 6px 12px;
      border-radius: 999px;
      background: rgba(255, 123, 28, 0.16);
      border: 1px solid rgba(255, 123, 28, 0.35);
      color: var(--accent-deep);
      font-size: 12px;
      font-weight: 800;
      pointer-events: none;
      display: none;
      z-index: 10;
    }

    .demo-badge.active {
      display: inline-block;
    }

    .purr-badge {
      position: fixed;
      top: 16%;
      left: 50%;
      transform: translateX(-50%) translateY(8px) scale(0.92);
      padding: 6px 14px;
      border-radius: 999px;
      background: rgba(255, 246, 232, 0.86);
      border: 1px solid rgba(255, 152, 56, 0.45);
      color: #c94e00;
      font-size: 14px;
      font-weight: 800;
      letter-spacing: 0.03em;
      pointer-events: none;
      opacity: 0;
      transition: opacity 0.28s ease, transform 0.28s ease;
      z-index: 9;
    }

    .purr-badge.active {
      opacity: 1;
      transform: translateX(-50%) translateY(0) scale(1);
    }

    @media (max-width: 520px) {
      .controls-dock {
        flex-direction: column;
        align-items: stretch;
        gap: 10px;
        padding: 12px 14px;
      }
      .drop-btn {
        width: 100%;
        min-height: 50px;
      }
      .hint-pill {
        font-size: 12px;
        padding: 7px 11px;
      }
    }
  </style>
</head>
<body>
  <canvas id="scene-canvas"></canvas>

  <div class="top-bar">
    <div class="hint-pill">Poke, squeeze, pull ears, cheeks &amp; tail · Rub head to purr</div>
    <button id="sound-btn" class="sound-btn" type="button" aria-label="Toggle sound">🔊</button>
  </div>

  <div id="demo-badge" class="demo-badge">Auto Demo · Touch anywhere to play</div>
  <div id="purr-badge" class="purr-badge">purr~ ♪</div>
  <div id="demo-cursor" class="demo-cursor"></div>

  <div class="controls-dock">
    <button id="drop-btn" class="drop-btn" type="button">
      <span>⬇</span>
      <span>Drop Cat</span>
    </button>
    <div class="slider-wrap">
      <div class="slider-labels">
        <span>Soft Pudding</span>
        <span id="firmness-readout" class="firmness-readout">Jelly</span>
        <span>Firm Gummy</span>
      </div>
      <input id="firmness-slider" class="jelly-slider" type="range" min="0" max="1" step="0.01" value="0.35" aria-label="Jelly firmness from soft pudding to firm gummy" />
    </div>
  </div>

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/build/three.min.js"></script>
  <script>
  (function () {
    'use strict';

    if (!window.THREE) {
      document.body.innerHTML = '<div style="padding:24px;font-family:sans-serif;color:#5a2c0c;">3D library failed to load. Please check connection and reload.</div>';
      return;
    }

    // =========================================================================
    // 1. PROCEDURAL WET JELLY & PURR AUDIO ENGINE (Web Audio API)
    // =========================================================================
    class JellyAudio {
      constructor() {
        this.ctx = null;
        this.master = null;
        this.comp = null;
        this.noiseBuffer = null;
        this.muted = false;
        this.initialized = false;
        this.lastPullSoundAt = 0;

        // Continuous purr synthesizer nodes
        this.purrGain = null;
        this.purrLfo = null;
        this.purrBreathLfo = null;
        this.purrFilter = null;
        this.purrStarted = false;
      }

      unlock() {
        if (this.muted) return;
        try {
          if (!this.ctx) {
            const AC = window.AudioContext || window.webkitAudioContext;
            if (!AC) return;
            this.ctx = new AC();
            this.comp = this.ctx.createDynamicsCompressor();
            this.comp.threshold.value = -14;
            this.comp.knee.value = 18;
            this.comp.ratio.value = 6;
            this.comp.attack.value = 0.004;
            this.comp.release.value = 0.12;

            this.master = this.ctx.createGain();
            this.master.gain.value = 0.85;
            this.comp.connect(this.master);
            this.master.connect(this.ctx.destination);

            // Prebuild 1.0s white noise buffer for wet squishes & purr breath
            const sr = this.ctx.sampleRate;
            this.noiseBuffer = this.ctx.createBuffer(1, sr, sr);
            const data = this.noiseBuffer.getChannelData(0);
            for (let i = 0; i < sr; i++) {
              data[i] = Math.random() * 2 - 1;
            }
            this.initialized = true;
            this.setupPurr();
          }
          if (this.ctx.state === 'suspended') {
            this.ctx.resume().catch(function () {});
          }
        } catch (e) {
          // Ignore audio unavailability in restricted environments
        }
      }

      setMuted(m) {
        this.muted = m;
        if (this.master && this.ctx) {
          try {
            this.master.gain.setTargetAtTime(m ? 0.0 : 0.85, this.ctx.currentTime, 0.03);
          } catch (e) {}
        }
      }

      setupPurr() {
        if (!this.ctx || this.purrStarted) return;
        const t = this.ctx.currentTime;

        // Warm throaty carrier
        const osc1 = this.ctx.createOscillator();
        osc1.type = 'sawtooth';
        osc1.frequency.setValueAtTime(56, t);

        const osc2 = this.ctx.createOscillator();
        osc2.type = 'triangle';
        osc2.frequency.setValueAtTime(112, t);

        const oscGain = this.ctx.createGain();
        oscGain.gain.value = 0.22;

        // Soft breathy purr air noise
        const noise = this.ctx.createBufferSource();
        noise.buffer = this.noiseBuffer;
        noise.loop = true;

        const noiseBP = this.ctx.createBiquadFilter();
        noiseBP.type = 'bandpass';
        noiseBP.frequency.value = 340;
        noiseBP.Q.value = 1.6;

        const noiseGain = this.ctx.createGain();
        noiseGain.gain.value = 0.18;

        // Warm throat lowpass filter
        this.purrFilter = this.ctx.createBiquadFilter();
        this.purrFilter.type = 'lowpass';
        this.purrFilter.frequency.setValueAtTime(220, t);
        this.purrFilter.Q.value = 2.4;

        // 25 Hz classic cat purr flutter + 0.55 Hz inhale/exhale swell
        const flutterGain = this.ctx.createGain();
        flutterGain.gain.setValueAtTime(0.42, t);

        this.purrLfo = this.ctx.createOscillator();
        this.purrLfo.type = 'sine';
        this.purrLfo.frequency.setValueAtTime(25.5, t);
        const lfoDepth = this.ctx.createGain();
        lfoDepth.gain.setValueAtTime(0.38, t);
        this.purrLfo.connect(lfoDepth);
        lfoDepth.connect(flutterGain.gain);

        const breathGain = this.ctx.createGain();
        breathGain.gain.setValueAtTime(0.72, t);
        this.purrBreathLfo = this.ctx.createOscillator();
        this.purrBreathLfo.type = 'sine';
        this.purrBreathLfo.frequency.setValueAtTime(0.62, t);
        const breathDepth = this.ctx.createGain();
        breathDepth.gain.setValueAtTime(0.28, t);
        this.purrBreathLfo.connect(breathDepth);
        breathDepth.connect(breathGain.gain);

        // Slow pitch inflection during inhale/exhale
        const pitchDepth = this.ctx.createGain();
        pitchDepth.gain.setValueAtTime(6.0, t);
        this.purrBreathLfo.connect(pitchDepth);
        pitchDepth.connect(osc1.frequency);

        this.purrGain = this.ctx.createGain();
        this.purrGain.gain.setValueAtTime(0.0001, t);

        osc1.connect(oscGain);
        osc2.connect(oscGain);
        oscGain.connect(this.purrFilter);
        noise.connect(noiseBP);
        noiseBP.connect(noiseGain);
        noiseGain.connect(this.purrFilter);

        this.purrFilter.connect(flutterGain);
        flutterGain.connect(breathGain);
        breathGain.connect(this.purrGain);
        this.purrGain.connect(this.comp);

        osc1.start(t);
        osc2.start(t);
        noise.start(t);
        this.purrLfo.start(t);
        this.purrBreathLfo.start(t);
        this.purrStarted = true;
      }

      updatePurr(level) {
        if (!this.initialized || !this.purrGain || !this.ctx) return;
        if (this.ctx.state !== 'running') return;
        const target = this.muted ? 0.0 : Math.max(0.0, Math.min(1.0, level)) * 0.42;
        const t = this.ctx.currentTime;
        this.purrGain.gain.setTargetAtTime(Math.max(0.0001, target), t, 0.08);
        if (this.purrFilter) {
          this.purrFilter.frequency.setTargetAtTime(190 + level * 110, t, 0.1);
        }
      }

      playWetBloop(firmness, strength, pitchBoost) {
        if (this.muted || !this.initialized || !this.ctx || this.ctx.state !== 'running') return;
        try {
          const t = this.ctx.currentTime;
          const dur = 0.065 + (1 - firmness) * 0.045;
          const baseF = (150 + firmness * 135) * (pitchBoost || 1.0);
          const endF = baseF * (1.85 + firmness * 0.55);

          const osc = this.ctx.createOscillator();
          osc.type = 'sine';
          osc.frequency.setValueAtTime(baseF, t);
          osc.frequency.exponentialRampToValueAtTime(endF, t + dur);

          const g = this.ctx.createGain();
          const vol = Math.min(0.45, 0.14 + strength * 0.24);
          g.gain.setValueAtTime(0.001, t);
          g.gain.linearRampToValueAtTime(vol, t + 0.008);
          g.gain.exponentialRampToValueAtTime(0.0001, t + dur + 0.02);

          osc.connect(g);
          g.connect(this.comp);
          osc.start(t);
          osc.stop(t + dur + 0.03);

          // Tiny glossy wet film noise chirp
          const ns = this.ctx.createBufferSource();
          ns.buffer = this.noiseBuffer;
          const bp = this.ctx.createBiquadFilter();
          bp.type = 'bandpass';
          bp.frequency.setValueAtTime(650 + firmness * 550, t);
          bp.frequency.exponentialRampToValueAtTime(1400 + firmness * 900, t + 0.04);
          bp.Q.value = 6.5;

          const ng = this.ctx.createGain();
          ng.gain.setValueAtTime(0.001, t);
          ng.gain.linearRampToValueAtTime(vol * 0.32, t + 0.004);
          ng.gain.exponentialRampToValueAtTime(0.0001, t + 0.045);

          ns.connect(bp);
          bp.connect(ng);
          ng.connect(this.comp);
          ns.start(t);
          ns.stop(t + 0.055);
        } catch (e) {}
      }

      playStretchMicro(firmness, stretchAmount) {
        if (this.muted || !this.initialized || !this.ctx || this.ctx.state !== 'running') return;
        const now = performance.now();
        if (now - this.lastPullSoundAt < 95) return;
        this.lastPullSoundAt = now;
        try {
          const t = this.ctx.currentTime;
          const ns = this.ctx.createBufferSource();
          ns.buffer = this.noiseBuffer;

          const bp = this.ctx.createBiquadFilter();
          bp.type = 'bandpass';
          const freq = 520 + firmness * 380 + Math.min(1, stretchAmount) * 620;
          bp.frequency.setValueAtTime(freq, t);
          bp.frequency.exponentialRampToValueAtTime(freq * 1.35, t + 0.045);
          bp.Q.value = 9.0;

          const g = this.ctx.createGain();
          g.gain.setValueAtTime(0.001, t);
          g.gain.linearRampToValueAtTime(0.065, t + 0.01);
          g.gain.exponentialRampToValueAtTime(0.0001, t + 0.055);

          ns.connect(bp);
          bp.connect(g);
          g.connect(this.comp);
          ns.start(t);
          ns.stop(t + 0.065);
        } catch (e) {}
      }

      playSnapWobble(firmness, stretchAmount) {
        if (this.muted || !this.initialized || !this.ctx || this.ctx.state !== 'running') return;
        try {
          const t = this.ctx.currentTime;
          const count = 3;
          const wobbleHz = 2.5 + firmness * 3.5;
          const step = 0.5 / wobbleHz;
          for (let i = 0; i < count; i++) {
            const st = t + i * step;
            const amp = Math.min(0.32, (0.12 + stretchAmount * 0.25) * Math.pow(0.58, i));
            const osc = this.ctx.createOscillator();
            osc.type = 'sine';
            const f0 = (165 + firmness * 160) * (1 + 0.14 * i);
            osc.frequency.setValueAtTime(f0, st);
            osc.frequency.exponentialRampToValueAtTime(f0 * 1.65, st + 0.065);

            const g = this.ctx.createGain();
            g.gain.setValueAtTime(0.001, st);
            g.gain.linearRampToValueAtTime(amp, st + 0.008);
            g.gain.exponentialRampToValueAtTime(0.0001, st + 0.08);
            osc.connect(g);
            g.connect(this.comp);
            osc.start(st);
            osc.stop(st + 0.09);
          }
        } catch (e) {}
      }

      playDropSplat(firmness, impactSpeed) {
        if (this.muted || !this.initialized || !this.ctx || this.ctx.state !== 'running') return;
        try {
          const t = this.ctx.currentTime;
          const intensity = Math.min(1.0, impactSpeed / 10.0);

          // Cushion jelly thump-blub
          const thump = this.ctx.createOscillator();
          thump.type = 'sine';
          thump.frequency.setValueAtTime(145 + firmness * 75, t);
          thump.frequency.exponentialRampToValueAtTime(52 + firmness * 30, t + 0.14);

          const tg = this.ctx.createGain();
          tg.gain.setValueAtTime(0.001, t);
          tg.gain.linearRampToValueAtTime(0.36 * intensity, t + 0.01);
          tg.gain.exponentialRampToValueAtTime(0.0001, t + 0.18);
          thump.connect(tg);
          tg.connect(this.comp);
          thump.start(t);
          thump.stop(t + 0.2);

          // Wet plate slap squish
          const ns = this.ctx.createBufferSource();
          ns.buffer = this.noiseBuffer;
          const bp = this.ctx.createBiquadFilter();
          bp.type = 'bandpass';
          bp.frequency.setValueAtTime(420 + firmness * 260, t);
          bp.frequency.exponentialRampToValueAtTime(1150 + firmness * 500, t + 0.07);
          bp.Q.value = 3.5;

          const ng = this.ctx.createGain();
          ng.gain.setValueAtTime(0.001, t);
          ng.gain.linearRampToValueAtTime(0.24 * intensity, t + 0.006);
          ng.gain.exponentialRampToValueAtTime(0.0001, t + 0.095);
          ns.connect(bp);
          bp.connect(ng);
          ng.connect(this.comp);
          ns.start(t);
          ns.stop(t + 0.11);

          // Secondary wet wobble bloops following the splat
          const wobHz = 2.3 + firmness * 3.4;
          const period = 0.5 / wobHz;
          for (let i = 1; i <= 3; i++) {
            const bt = t + i * period;
            const osc = this.ctx.createOscillator();
            osc.type = 'sine';
            const f = (125 + firmness * 130) * (1 + i * 0.15);
            osc.frequency.setValueAtTime(f, bt);
            osc.frequency.exponentialRampToValueAtTime(f * 1.55, bt + 0.065);
            const g = this.ctx.createGain();
            g.gain.setValueAtTime(0.001, bt);
            g.gain.linearRampToValueAtTime(0.16 * intensity * Math.pow(0.6, i - 1), bt + 0.008);
            g.gain.exponentialRampToValueAtTime(0.0001, bt + 0.08);
            osc.connect(g);
            g.connect(this.comp);
            osc.start(bt);
            osc.stop(bt + 0.09);
          }
        } catch (e) {}
      }

      playPlateClink() {
        if (this.muted || !this.initialized || !this.ctx || this.ctx.state !== 'running') return;
        try {
          const t = this.ctx.currentTime;
          const freqs = [1740, 3120];
          for (let i = 0; i < freqs.length; i++) {
            const osc = this.ctx.createOscillator();
            osc.type = 'sine';
            osc.frequency.setValueAtTime(freqs[i], t);
            const g = this.ctx.createGain();
            g.gain.setValueAtTime(0.001, t);
            g.gain.linearRampToValueAtTime(i === 0 ? 0.07 : 0.035, t + 0.003);
            g.gain.exponentialRampToValueAtTime(0.0001, t + 0.11);
            osc.connect(g);
            g.connect(this.comp);
            osc.start(t);
            osc.stop(t + 0.12);
          }
        } catch (e) {}
      }
    }

    // =========================================================================
    // 2. SEAMLESS CHUBBY SITTING CAT SDF & SURFACE NETS MESH BUILDER
    // =========================================================================
    function smin(a, b, k) {
      const h = Math.max(k - Math.abs(a - b), 0.0) / k;
      return Math.min(a, b) - h * h * k * 0.25;
    }

    function smax(a, b, k) {
      return -smin(-a, -b, k);
    }

    function sdEllipsoid(px, py, pz, rx, ry, rz) {
      const k0 = Math.hypot(px / rx, py / ry, pz / rz);
      if (k0 < 1e-6) return -Math.min(rx, ry, rz);
      const k1 = Math.hypot(px / (rx * rx), py / (ry * ry), pz / (rz * rz));
      return (k0 * (k0 - 1.0)) / k1;
    }

    function sdRoundCone(px, py, pz, ax, ay, az, bx, by, bz, r1, r2) {
      const bax = bx - ax, bay = by - ay, baz = bz - az;
      const l2 = bax * bax + bay * bay + baz * baz;
      const rr = r1 - r2;
      const a2 = l2 - rr * rr;
      const il2 = 1.0 / l2;
      const pax = px - ax, pay = py - ay, paz = pz - az;
      const y = pax * bax + pay * bay + paz * baz;
      const z = y - l2;
      const dx = pax * l2 - bax * y;
      const dy = pay * l2 - bay * y;
      const dz = paz * l2 - baz * y;
      const x2 = dx * dx + dy * dy + dz * dz;
      const y2 = y * y * l2;
      const z2 = z * z * l2;
      const k = Math.sign(rr) * rr * rr * x2;
      if (Math.sign(z) * a2 * z2 > k) return Math.sqrt(x2 + z2) * il2 - r2;
      if (Math.sign(y) * a2 * y2 < k) return Math.sqrt(x2 + y2) * il2 - r1;
      return (Math.sqrt(x2 * a2 * il2) + y * rr) * il2 - r1;
    }

    function evalCatParts(px, py, pz) {
      // Lower plump belly + sitting hips
      const dBelly = sdEllipsoid(px, py - 0.52, pz + 0.04, 0.67, 0.54, 0.63);
      // Upper chest
      const dChest = sdEllipsoid(px, py - 0.89, pz - 0.03, 0.48, 0.42, 0.46);
      let dTorso = smin(dBelly, dChest, 0.24);

      // Plump sitting haunches (left & right)
      const dHaunchL = sdEllipsoid(px + 0.42, py - 0.34, pz + 0.15, 0.27, 0.30, 0.35);
      const dHaunchR = sdEllipsoid(px - 0.42, py - 0.34, pz + 0.15, 0.27, 0.30, 0.35);
      dTorso = smin(dTorso, dHaunchL, 0.12);
      dTorso = smin(dTorso, dHaunchR, 0.12);

      // Cute stubby front paws resting on plate
      const dPawL = smin(
        sdRoundCone(px, py, pz, -0.20, 0.16, 0.44, -0.19, 0.48, 0.34, 0.145, 0.12),
        sdEllipsoid(px + 0.20, py - 0.12, pz - 0.55, 0.135, 0.105, 0.145),
        0.05
      );
      const dPawR = smin(
        sdRoundCone(px, py, pz, 0.20, 0.16, 0.44, 0.19, 0.48, 0.34, 0.145, 0.12),
        sdEllipsoid(px - 0.20, py - 0.12, pz - 0.55, 0.135, 0.105, 0.145),
        0.05
      );
      dTorso = smin(dTorso, dPawL, 0.07);
      dTorso = smin(dTorso, dPawR, 0.07);

      // Big round chubby cat head
      let dHead = sdEllipsoid(px, py - 1.38, pz - 0.13, 0.56, 0.46, 0.49);
      // Tiny puffy muzzle cushions
      const dMuzL = sdEllipsoid(px + 0.095, py - 1.25, pz - 0.56, 0.115, 0.085, 0.095);
      const dMuzR = sdEllipsoid(px - 0.095, py - 1.25, pz - 0.56, 0.115, 0.085, 0.095);
      dHead = smin(dHead, dMuzL, 0.04);
      dHead = smin(dHead, dMuzR, 0.04);

      // Puffy pullable cheeks
      const dCheekL = sdEllipsoid(px + 0.41, py - 1.24, pz - 0.34, 0.23, 0.185, 0.21);
      const dCheekR = sdEllipsoid(px - 0.41, py - 1.24, pz - 0.34, 0.23, 0.185, 0.21);
      dHead = smin(dHead, dCheekL, 0.07);
      dHead = smin(dHead, dCheekR, 0.07);

      // Slightly flattened triangular-rounded cat ears with subtle front ear cup
      const earPz = (pz - 0.09) * 1.32 + 0.09;
      let dEarL = sdRoundCone(px, py, earPz, -0.32, 1.65, 0.10, -0.47, 2.05, 0.07, 0.185, 0.042) / 1.32;
      const dCupL = sdEllipsoid(px + 0.37, py - 1.83, pz - 0.23, 0.10, 0.14, 0.09);
      dEarL = smax(dEarL, -dCupL, 0.035);

      let dEarR = sdRoundCone(px, py, earPz, 0.32, 1.65, 0.10, 0.47, 2.05, 0.07, 0.185, 0.042) / 1.32;
      const dCupR = sdEllipsoid(px - 0.37, py - 1.83, pz - 0.23, 0.10, 0.14, 0.09);
      dEarR = smax(dEarR, -dCupR, 0.035);

      dHead = smin(dHead, dEarL, 0.065);
      dHead = smin(dHead, dEarR, 0.065);

      let dBodyHead = smin(dTorso, dHead, 0.14);

      // Plush curved jelly tail sweeping cleanly around the right side
      const dt1 = sdRoundCone(px, py, pz, 0.00, 0.24, -0.58, 0.46, 0.19, -0.54, 0.115, 0.12);
      const dt2 = sdRoundCone(px, py, pz, 0.46, 0.19, -0.54, 0.87, 0.20, -0.26, 0.12, 0.13);
      const dt3 = sdRoundCone(px, py, pz, 0.87, 0.20, -0.26, 1.00, 0.23, 0.12, 0.13, 0.14);
      const dt4 = sdRoundCone(px, py, pz, 1.00, 0.23, 0.12, 0.86, 0.35, 0.42, 0.14, 0.145);
      const dTailBase = smin(dt1, dt2, 0.035);
      const dTailTip = smin(dt3, dt4, 0.035);
      const dTail = smin(dTailBase, dTailTip, 0.035);

      let d = smin(dBodyHead, dTail, 0.055);
      // Cushion flat underside resting on the plate
      d = smax(d, 0.024 - py, 0.052);

      return {
        d,
        dTorso,
        dBelly,
        dHead,
        dEarL,
        dEarR,
        dCheekL,
        dCheekR,
        dPawL,
        dPawR,
        dTailBase,
        dTailTip,
        dTail
      };
    }

    function catSDF(px, py, pz) {
      return evalCatParts(px, py, pz).d;
    }

    function catGrad(px, py, pz) {
      const eps = 0.0025;
      const gx = catSDF(px + eps, py, pz) - catSDF(px - eps, py, pz);
      const gy = catSDF(px, py + eps, pz) - catSDF(px, py - eps, pz);
      const gz = catSDF(px, py, pz + eps) - catSDF(px, py, pz - eps);
      const len = Math.hypot(gx, gy, gz) || 1.0;
      return [gx / len, gy / len, gz / len];
    }

    function buildCatSurfaceNetMesh() {
      const minX = -1.28, maxX = 1.44;
      const minY = -0.16, maxY = 2.26;
      const minZ = -1.10, maxZ = 1.10;
      const h = 0.058;

      const nx = Math.ceil((maxX - minX) / h) + 1;
      const ny = Math.ceil((maxY - minY) / h) + 1;
      const nz = Math.ceil((maxZ - minZ) / h) + 1;

      const idx = (i, j, k) => (k * ny + j) * nx + i;
      const total = nx * ny * nz;
      const field = new Float32Array(total);

      for (let k = 0; k < nz; k++) {
        const z = minZ + k * h;
        for (let j = 0; j < ny; j++) {
          const y = minY + j * h;
          const row = (k * ny + j) * nx;
          for (let i = 0; i < nx; i++) {
            const x = minX + i * h;
            field[row + i] = catSDF(x, y, z);
          }
        }
      }

      const cellToVert = new Int32Array(total);
      cellToVert.fill(-1);

      const verts = [];
      const CUBE_OFFSETS = [
        [0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0],
        [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]
      ];
      const CUBE_EDGES = [
        [0, 1], [2, 3], [4, 5], [6, 7],
        [0, 2], [1, 3], [4, 6], [5, 7],
        [0, 4], [1, 5], [2, 6], [3, 7]
      ];
      const vals = new Float32Array(8);

      for (let k = 0; k < nz - 1; k++) {
        for (let j = 0; j < ny - 1; j++) {
          for (let i = 0; i < nx - 1; i++) {
            let mask = 0;
            for (let m = 0; m < 8; m++) {
              const o = CUBE_OFFSETS[m];
              const v = field[idx(i + o[0], j + o[1], k + o[2])];
              vals[m] = v;
              if (v < 0) mask |= (1 << m);
            }
            if (mask === 0 || mask === 255) continue;

            let sx = 0, sy = 0, sz = 0, cnt = 0;
            for (let e = 0; e < 12; e++) {
              const a = CUBE_EDGES[e][0];
              const b = CUBE_EDGES[e][1];
              if (((mask >> a) & 1) === ((mask >> b) & 1)) continue;
              const va = vals[a];
              const vb = vals[b];
              const t = Math.max(0, Math.min(1, va / (va - vb)));
              const oa = CUBE_OFFSETS[a];
              const ob = CUBE_OFFSETS[b];
              sx += minX + (i + oa[0] + t * (ob[0] - oa[0])) * h;
              sy += minY + (j + oa[1] + t * (ob[1] - oa[1])) * h;
              sz += minZ + (k + oa[2] + t * (ob[2] - oa[2])) * h;
              cnt++;
            }

            let px = sx / cnt;
            let py = sy / cnt;
            let pz = sz / cnt;
            // Project gently onto SDF=0 for crisp geometry
            const d = catSDF(px, py, pz);
            const g = catGrad(px, py, pz);
            const step = Math.max(-h * 0.45, Math.min(h * 0.45, d));
            px -= g[0] * step;
            py -= g[1] * step;
            pz -= g[2] * step;

            cellToVert[idx(i, j, k)] = verts.length / 3;
            verts.push(px, py, pz);
          }
        }
      }

      const indices = [];
      const addQuad = (a, b, c, d, flip) => {
        if (a < 0 || b < 0 || c < 0 || d < 0) return;
        if (!flip) {
          indices.push(a, b, c, a, c, d);
        } else {
          indices.push(a, c, b, a, d, c);
        }
      };

      // X-edges
      for (let k = 1; k < nz - 1; k++) {
        for (let j = 1; j < ny - 1; j++) {
          for (let i = 0; i < nx - 1; i++) {
            const v0 = field[idx(i, j, k)];
            const v1 = field[idx(i + 1, j, k)];
            if ((v0 < 0) === (v1 < 0)) continue;
            const a = cellToVert[idx(i, j - 1, k - 1)];
            const b = cellToVert[idx(i, j, k - 1)];
            const c = cellToVert[idx(i, j, k)];
            const d = cellToVert[idx(i, j - 1, k)];
            addQuad(a, b, c, d, v0 >= 0);
          }
        }
      }

      // Y-edges
      for (let k = 1; k < nz - 1; k++) {
        for (let j = 0; j < ny - 1; j++) {
          for (let i = 1; i < nx - 1; i++) {
            const v0 = field[idx(i, j, k)];
            const v1 = field[idx(i, j + 1, k)];
            if ((v0 < 0) === (v1 < 0)) continue;
            const a = cellToVert[idx(i - 1, j, k - 1)];
            const b = cellToVert[idx(i, j, k - 1)];
            const c = cellToVert[idx(i, j, k)];
            const d = cellToVert[idx(i - 1, j, k)];
            addQuad(a, d, c, b, v0 >= 0);
          }
        }
      }

      // Z-edges
      for (let k = 0; k < nz - 1; k++) {
        for (let j = 1; j < ny - 1; j++) {
          for (let i = 1; i < nx - 1; i++) {
            const v0 = field[idx(i, j, k)];
            const v1 = field[idx(i, j, k + 1)];
            if ((v0 < 0) === (v1 < 0)) continue;
            const a = cellToVert[idx(i - 1, j - 1, k)];
            const b = cellToVert[idx(i, j - 1, k)];
            const c = cellToVert[idx(i, j, k)];
            const d = cellToVert[idx(i - 1, j, k)];
            addQuad(a, b, c, d, v0 >= 0);
          }
        }
      }

      // Build vertex adjacency for Taubin smoothing (silky-smooth, zero shrinkage)
      const vCount = verts.length / 3;
      const neighbors = Array.from({ length: vCount }, () => []);
      for (let t = 0; t < indices.length; t += 3) {
        const i0 = indices[t], i1 = indices[t + 1], i2 = indices[t + 2];
        if (!neighbors[i0].includes(i1)) neighbors[i0].push(i1);
        if (!neighbors[i0].includes(i2)) neighbors[i0].push(i2);
        if (!neighbors[i1].includes(i0)) neighbors[i1].push(i0);
        if (!neighbors[i1].includes(i2)) neighbors[i1].push(i2);
        if (!neighbors[i2].includes(i0)) neighbors[i2].push(i0);
        if (!neighbors[i2].includes(i1)) neighbors[i2].push(i1);
      }

      let pos = new Float32Array(verts);
      let tmp = new Float32Array(verts.length);
      const smoothStep = (lambda) => {
        for (let v = 0; v < vCount; v++) {
          const nb = neighbors[v];
          if (nb.length === 0) {
            tmp[v * 3] = pos[v * 3];
            tmp[v * 3 + 1] = pos[v * 3 + 1];
            tmp[v * 3 + 2] = pos[v * 3 + 2];
            continue;
          }
          let ax = 0, ay = 0, az = 0;
          for (let k = 0; k < nb.length; k++) {
            const ni = nb[k] * 3;
            ax += pos[ni];
            ay += pos[ni + 1];
            az += pos[ni + 2];
          }
          const inv = 1 / nb.length;
          const vi = v * 3;
          tmp[vi] = pos[vi] + lambda * (ax * inv - pos[vi]);
          tmp[vi + 1] = pos[vi + 1] + lambda * (ay * inv - pos[vi + 1]);
          tmp[vi + 2] = pos[vi + 2] + lambda * (az * inv - pos[vi + 2]);
        }
        const swap = pos;
        pos = tmp;
        tmp = swap;
      };

      for (let pass = 0; pass < 3; pass++) {
        smoothStep(0.5);
        smoothStep(-0.525);
      }
      // Gentle final re-projection onto SDF=0 to keep ears/cheeks/tail crisp
      for (let v = 0; v < vCount; v++) {
        const vi = v * 3;
        const d = catSDF(pos[vi], pos[vi + 1], pos[vi + 2]);
        const g = catGrad(pos[vi], pos[vi + 1], pos[vi + 2]);
        pos[vi] -= g[0] * d * 0.55;
        pos[vi + 1] -= g[1] * d * 0.55;
        pos[vi + 2] -= g[2] * d * 0.55;
      }

      const geo = new THREE.BufferGeometry();
      geo.setAttribute('position', new THREE.BufferAttribute(pos.slice(), 3));
      geo.setIndex(indices);
      geo.computeVertexNormals();
      geo.boundingSphere = new THREE.Sphere(new THREE.Vector3(0, 1.0, 0), 3.4);
      geo.boundingBox = new THREE.Box3(new THREE.Vector3(-3, -1, -3), new THREE.Vector3(3, 4, 3));

      return { geometry: geo, restPositions: pos, vCount };
    }

    // =========================================================================
    // 3. SOFT-BODY JELLY PHYSICS SYSTEM (Nodes + Skinning + Poke Ripples)
    // =========================================================================
    // 12 coupled anatomical nodes
    const NODE_DEFS = [
      { id: 'torso',    rest: [ 0.00, 0.55,  0.00], parent: -1, couple: 0.00 }, // 0
      { id: 'head',     rest: [ 0.00, 1.38,  0.13], parent:  0, couple: 0.42 }, // 1
      { id: 'earL',     rest: [-0.42, 1.92,  0.08], parent:  1, couple: 0.45 }, // 2
      { id: 'earR',     rest: [ 0.42, 1.92,  0.08], parent:  1, couple: 0.45 }, // 3
      { id: 'cheekL',   rest: [-0.44, 1.24,  0.35], parent:  1, couple: 0.40 }, // 4
      { id: 'cheekR',   rest: [ 0.44, 1.24,  0.35], parent:  1, couple: 0.40 }, // 5
      { id: 'belly',    rest: [ 0.00, 0.52,  0.52], parent:  0, couple: 0.46 }, // 6
      { id: 'back',     rest: [ 0.00, 0.60, -0.52], parent:  0, couple: 0.42 }, // 7
      { id: 'tailMid',  rest: [ 0.72, 0.21, -0.34], parent:  0, couple: 0.30 }, // 8
      { id: 'tailTip',  rest: [ 0.88, 0.33,  0.34], parent:  8, couple: 0.55 }, // 9
      { id: 'pawL',     rest: [-0.20, 0.17,  0.52], parent:  0, couple: 0.40 }, // 10
      { id: 'pawR',     rest: [ 0.20, 0.17,  0.52], parent:  0, couple: 0.40 }  // 11
    ];

    const NODES_COUNT = NODE_DEFS.length;

    function computeVertexWeightsAndRegions(restPos, vCount) {
      const weights = new Float32Array(vCount * NODES_COUNT);
      const regions = new Uint8Array(vCount);
      // Region codes:
      // 0: torso/belly, 1: head, 2: earL, 3: earR, 4: cheekL, 5: cheekR, 6: tail

      for (let v = 0; v < vCount; v++) {
        const x = restPos[v * 3];
        const y = restPos[v * 3 + 1];
        const z = restPos[v * 3 + 2];
        const parts = evalCatParts(x, y, z);

        // Compute clean anatomical membership from SDF part proximity
        const wRaw = new Float32Array(NODES_COUNT);
        const wFn = (d, sharpness) => Math.exp(-Math.max(0, d) * sharpness);

        // Isolate tail cleanly from right haunch
        const isTailDom = parts.dTail < Math.min(parts.dTorso, parts.dHead) + 0.025;
        if (isTailDom) {
          const dMid = Math.hypot(x - 0.65, y - 0.21, z + 0.35);
          const dTip = Math.hypot(x - 0.90, y - 0.30, z - 0.28);
          wRaw[8] = Math.exp(-dMid * 2.5);
          wRaw[9] = Math.exp(-dTip * 2.2);
          wRaw[0] = Math.exp(-Math.hypot(x, y - 0.24, z + 0.58) * 3.8) * 0.55;
          regions[v] = 6;
        } else {
          wRaw[0] = wFn(parts.dTorso, 4.2) * 0.85;
          wRaw[1] = wFn(parts.dHead, 5.5) * 0.95;
          wRaw[2] = wFn(parts.dEarL, 12.0) * (y > 1.56 ? 1.45 : 0.15);
          wRaw[3] = wFn(parts.dEarR, 12.0) * (y > 1.56 ? 1.45 : 0.15);
          wRaw[4] = wFn(parts.dCheekL, 10.5) * (x < -0.18 && z > 0.08 ? 1.35 : 0.15);
          wRaw[5] = wFn(parts.dCheekR, 10.5) * (x > 0.18 && z > 0.08 ? 1.35 : 0.15);
          wRaw[6] = wFn(parts.dBelly, 5.0) * Math.max(0.05, (z + 0.3) * 0.9);
          wRaw[7] = wFn(parts.dTorso, 4.5) * Math.max(0.05, (-z + 0.25) * 0.85);
          wRaw[8] = 0.0;
          wRaw[9] = 0.0;
          wRaw[10] = wFn(parts.dPawL, 12.0) * 1.1;
          wRaw[11] = wFn(parts.dPawR, 12.0) * 1.1;

          // Determine interactive hit region
          if (parts.dEarL < 0.055 && y > 1.58 && x < -0.12) regions[v] = 2;
          else if (parts.dEarR < 0.055 && y > 1.58 && x > 0.12) regions[v] = 3;
          else if (parts.dCheekL < 0.065 && x < -0.22 && y > 1.08 && y < 1.44 && z > 0.12) regions[v] = 4;
          else if (parts.dCheekR < 0.065 && x > 0.22 && y > 1.08 && y < 1.44 && z > 0.12) regions[v] = 5;
          else if (y > 1.08) regions[v] = 1;
          else regions[v] = 0;
        }

        let sum = 0;
        for (let n = 0; n < NODES_COUNT; n++) sum += wRaw[n];
        if (sum < 1e-5) {
          wRaw[0] = 1.0;
          sum = 1.0;
        }
        const inv = 1.0 / sum;
        for (let n = 0; n < NODES_COUNT; n++) {
          weights[v * NODES_COUNT + n] = wRaw[n] * inv;
        }
      }

      return { weights, regions };
    }

    function computePointWeights(px, py, pz) {
      const parts = evalCatParts(px, py, pz);
      const wRaw = new Float32Array(NODES_COUNT);
      const wFn = (d, sharpness) => Math.exp(-Math.max(0, d) * sharpness);
      const isTailDom = parts.dTail < Math.min(parts.dTorso, parts.dHead) + 0.025;
      if (isTailDom) {
        wRaw[8] = Math.exp(-Math.hypot(px - 0.65, py - 0.21, pz + 0.35) * 2.5);
        wRaw[9] = Math.exp(-Math.hypot(px - 0.90, py - 0.30, pz - 0.28) * 2.2);
        wRaw[0] = Math.exp(-Math.hypot(px, py - 0.24, pz + 0.58) * 3.8) * 0.55;
      } else {
        wRaw[0] = wFn(parts.dTorso, 4.2) * 0.85;
        wRaw[1] = wFn(parts.dHead, 5.5) * 0.95;
        wRaw[2] = wFn(parts.dEarL, 12.0) * (py > 1.56 ? 1.45 : 0.15);
        wRaw[3] = wFn(parts.dEarR, 12.0) * (py > 1.56 ? 1.45 : 0.15);
        wRaw[4] = wFn(parts.dCheekL, 10.5) * (px < -0.18 && pz > 0.08 ? 1.35 : 0.15);
        wRaw[5] = wFn(parts.dCheekR, 10.5) * (px > 0.18 && pz > 0.08 ? 1.35 : 0.15);
        wRaw[6] = wFn(parts.dBelly, 5.0) * Math.max(0.05, (pz + 0.3) * 0.9);
        wRaw[7] = wFn(parts.dTorso, 4.5) * Math.max(0.05, (-pz + 0.25) * 0.85);
        wRaw[10] = wFn(parts.dPawL, 12.0) * 1.1;
        wRaw[11] = wFn(parts.dPawR, 12.0) * 1.1;
      }
      let sum = 0;
      for (let n = 0; n < NODES_COUNT; n++) sum += wRaw[n];
      if (sum < 1e-5) { wRaw[0] = 1; sum = 1; }
      for (let n = 0; n < NODES_COUNT; n++) wRaw[n] /= sum;
      return wRaw;
    }

    // =========================================================================
    // 4. THREE.JS SCENE, ENVIRONMENT, PLATE, JELLY CAT, BUBBLES & FACE RIG
    // =========================================================================
    const canvas = document.getElementById('scene-canvas');
    const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: false, powerPreference: 'high-performance' });
    renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
    renderer.setSize(window.innerWidth, window.innerHeight, false);
    renderer.outputEncoding = THREE.sRGBEncoding;
    renderer.toneMapping = THREE.ACESFilmicToneMapping;
    renderer.toneMappingExposure = 1.08;
    renderer.physicallyCorrectLights = true;
    renderer.shadowMap.enabled = true;
    renderer.shadowMap.type = THREE.PCFSoftShadowMap;

    const scene = new THREE.Scene();
    scene.background = new THREE.Color(0xf8ebdd);
    scene.fog = new THREE.Fog(0xf8ebdd, 11.0, 22.0);

    const camera = new THREE.PerspectiveCamera(37, window.innerWidth / window.innerHeight, 0.1, 40);

    // Synthesize Studio Softbox Environment Map for juicy specular highlights & refraction
    (function setupEnvMap() {
      const pmrem = new THREE.PMREMGenerator(renderer);
      const envScene = new THREE.Scene();
      envScene.background = new THREE.Color(0xfceadd);

      const addPanel = (color, intensity, pos, rot, size) => {
        const m = new THREE.Mesh(
          new THREE.PlaneGeometry(size[0], size[1]),
          new THREE.MeshBasicMaterial({ color: new THREE.Color(color).multiplyScalar(intensity), side: THREE.DoubleSide })
        );
        m.position.set(pos[0], pos[1], pos[2]);
        m.rotation.set(rot[0], rot[1], rot[2]);
        envScene.add(m);
      };

      // Top-left crisp window softbox (gives classic glossy candy reflection)
      addPanel('#ffffff', 4.6, [-4.5, 5.2, 4.2], [0.65, 0.72, 0], [4.2, 5.2]);
      // Top-right warm studio key box
      addPanel('#fff5e6', 3.4, [5.0, 4.4, 3.0], [0.55, -0.85, 0], [3.6, 4.0]);
      // Back rim strip (illuminates clear orange jelly from behind)
      addPanel('#ffd59a', 4.0, [0, 3.8, -5.5], [0.55, 0, 0], [8.5, 3.2]);
      // Warm peach tabletop bounce below
      addPanel('#ffd9b3', 1.4, [0, -3.8, 0], [-Math.PI / 2, 0, 0], [14, 14]);

      const envRT = pmrem.fromScene(envScene, 0.035);
      scene.environment = envRT.texture;
      pmrem.dispose();
    })();

    // Lighting
    const hemiLight = new THREE.HemisphereLight(0xfff6eb, 0xf2c9a6, 1.35);
    scene.add(hemiLight);

    const keyLight = new THREE.DirectionalLight(0xfff8ef, 3.1);
    keyLight.position.set(-2.6, 5.4, 3.6);
    keyLight.castShadow = true;
    keyLight.shadow.mapSize.set(1024, 1024);
    keyLight.shadow.camera.near = 1.0;
    keyLight.shadow.camera.far = 14.0;
    keyLight.shadow.camera.left = -2.4;
    keyLight.shadow.camera.right = 2.4;
    keyLight.shadow.camera.top = 2.6;
    keyLight.shadow.camera.bottom = -2.2;
    keyLight.shadow.bias = -0.0005;
    scene.add(keyLight);

    const backRimLight = new THREE.DirectionalLight(0xffb45a, 2.7);
    backRimLight.position.set(1.8, 3.8, -4.2);
    scene.add(backRimLight);

    // Warm internal orange glow point light (lights the porcelain plate right under the cat!)
    const innerCatLight = new THREE.PointLight(0xff7d14, 4.4, 4.2, 2.0);
    innerCatLight.position.set(0.05, 0.72, 0.05);
    scene.add(innerCatLight);

    // Turntable group so user can rotate plate & cat smoothly
    const turntable = new THREE.Group();
    scene.add(turntable);

    // Sunlit warm cream tabletop surface
    const tableCanvas = document.createElement('canvas');
    tableCanvas.width = 512;
    tableCanvas.height = 512;
    const tctx = tableCanvas.getContext('2d');
    const tGrad = tctx.createRadialGradient(256, 256, 20, 256, 256, 256);
    tGrad.addColorStop(0, '#fff5ea');
    tGrad.addColorStop(0.45, '#f8e6d4');
    tGrad.addColorStop(1, '#efd4bb');
    tctx.fillStyle = tGrad;
    tctx.fillRect(0, 0, 512, 512);
    const tableTex = new THREE.CanvasTexture(tableCanvas);
    tableTex.encoding = THREE.sRGBEncoding;

    const tableMesh = new THREE.Mesh(
      new THREE.CircleGeometry(14, 64),
      new THREE.MeshStandardMaterial({ map: tableTex, roughness: 0.85, metalness: 0.0 })
    );
    tableMesh.rotation.x = -Math.PI / 2;
    tableMesh.position.y = -0.10;
    tableMesh.receiveShadow = true;
    scene.add(tableMesh);

    // Small glazed ceramic dessert plate via LatheGeometry
    const plateCanvas = document.createElement('canvas');
    plateCanvas.width = 512;
    plateCanvas.height = 512;
    const pctx = plateCanvas.getContext('2d');
    pctx.fillStyle = '#fdfaf5';
    pctx.fillRect(0, 0, 512, 512);
    // Subtle concentric glaze bands & delicate tangerine-apricot ceramic rim pinstripe
    const pGrad = pctx.createRadialGradient(256, 256, 40, 256, 256, 256);
    pGrad.addColorStop(0.0, '#ffffff');
    pGrad.addColorStop(0.68, '#faf4eb');
    pGrad.addColorStop(0.86, '#f6ecdf');
    pGrad.addColorStop(0.915, '#f29548');
    pGrad.addColorStop(0.935, '#faf3e8');
    pGrad.addColorStop(1.0, '#efe3d4');
    pctx.fillStyle = pGrad;
    pctx.fillRect(0, 0, 512, 512);

    const plateTex = new THREE.CanvasTexture(plateCanvas);
    plateTex.encoding = THREE.sRGBEncoding;

    const plateProfile = [
      new THREE.Vector2(0.00,  0.00),
      new THREE.Vector2(0.85,  0.00),
      new THREE.Vector2(1.16,  0.015),
      new THREE.Vector2(1.36,  0.075),
      new THREE.Vector2(1.52,  0.175),
      new THREE.Vector2(1.58,  0.205),
      new THREE.Vector2(1.61,  0.185),
      new THREE.Vector2(1.56,  0.125),
      new THREE.Vector2(1.30,  0.015),
      new THREE.Vector2(0.96, -0.065),
      new THREE.Vector2(0.88, -0.095),
      new THREE.Vector2(0.80, -0.095),
      new THREE.Vector2(0.76, -0.055),
      new THREE.Vector2(0.00, -0.055)
    ];
    const plateGeo = new THREE.LatheGeometry(plateProfile, 72);
    // Map planar top UVs so radial plate texture renders cleanly
    const pPos = plateGeo.attributes.position;
    const pUv = plateGeo.attributes.uv;
    for (let i = 0; i < pPos.count; i++) {
      const px = pPos.getX(i);
      const pz = pPos.getZ(i);
      pUv.setXY(i, 0.5 + (px / 3.24), 0.5 + (pz / 3.24));
    }
    pUv.needsUpdate = true;
    plateGeo.computeVertexNormals();

    const plateMat = new THREE.MeshPhysicalMaterial({
      map: plateTex,
      color: 0xffffff,
      roughness: 0.14,
      metalness: 0.0,
      clearcoat: 0.9,
      clearcoatRoughness: 0.07
    });
    const plateMesh = new THREE.Mesh(plateGeo, plateMat);
    plateMesh.position.set(0.08, 0, 0.0);
    plateMesh.receiveShadow = true;
    plateMesh.castShadow = true;
    turntable.add(plateMesh);

    // Soft glowing orange caustic puddle right on the plate under the clear jelly cat
    const causticCanvas = document.createElement('canvas');
    causticCanvas.width = 256;
    causticCanvas.height = 256;
    const cctx = causticCanvas.getContext('2d');
    const cGrad = cctx.createRadialGradient(128, 128, 10, 128, 128, 126);
    cGrad.addColorStop(0.0, 'rgba(255, 130, 22, 0.58)');
    cGrad.addColorStop(0.45, 'rgba(255, 162, 56, 0.34)');
    cGrad.addColorStop(0.75, 'rgba(255, 195, 110, 0.12)');
    cGrad.addColorStop(1.0, 'rgba(255, 195, 110, 0.0)');
    cctx.fillStyle = cGrad;
    cctx.fillRect(0, 0, 256, 256);
    const causticTex = new THREE.CanvasTexture(causticCanvas);
    causticTex.encoding = THREE.sRGBEncoding;

    const causticDisc = new THREE.Mesh(
      new THREE.PlaneGeometry(2.15, 2.15),
      new THREE.MeshBasicMaterial({
        map: causticTex,
        transparent: true,
        depthWrite: false,
        opacity: 0.92
      })
    );
    causticDisc.rotation.x = -Math.PI / 2;
    causticDisc.position.set(0.06, 0.008, -0.02);
    turntable.add(causticDisc);

    // Build the seamless chubby sitting cat mesh
    const { geometry: catGeo, restPositions, vCount } = buildCatSurfaceNetMesh();
    const { weights: vertWeights, regions: vertRegions } = computeVertexWeightsAndRegions(restPositions, vCount);

    const jellyUniforms = {
      uPurrGlow: { value: 0.0 },
      uKeyLightViewDir: { value: new THREE.Vector3(-0.35, 0.65, 0.65) }
    };

    const jellyMat = new THREE.MeshPhysicalMaterial({
      color: new THREE.Color('#ffaa38'),
      roughness: 0.048,
      metalness: 0.0,
      transmission: 0.90,
      ior: 1.37,
      thickness: 0.75,
      attenuationColor: new THREE.Color('#ff5e00'),
      attenuationDistance: 1.15,
      clearcoat: 1.0,
      clearcoatRoughness: 0.032,
      specularIntensity: 1.0,
      specularColor: new THREE.Color('#fff5e6'),
      envMapIntensity: 1.35,
      sheen: 0.25,
      sheenRoughness: 0.35,
      sheenColor: new THREE.Color('#ffd59a')
    });

    jellyMat.onBeforeCompile = function (shader) {
      shader.uniforms.uPurrGlow = jellyUniforms.uPurrGlow;
      shader.uniforms.uKeyLightViewDir = jellyUniforms.uKeyLightViewDir;

      shader.vertexShader = 'varying vec3 vJellyLocalPos;\n' + shader.vertexShader;
      shader.vertexShader = shader.vertexShader.replace(
        '#include <begin_vertex>',
        '#include <begin_vertex>\nvJellyLocalPos = transformed;'
      );

      shader.fragmentShader =
        'varying vec3 vJellyLocalPos;\nuniform float uPurrGlow;\nuniform vec3 uKeyLightViewDir;\n' +
        shader.fragmentShader;

      shader.fragmentShader = shader.fragmentShader.replace(
        '#include <tonemapping_fragment>',
        `
        vec3 jViewDir = normalize(vViewPosition);
        vec3 jNorm = normalize(normal);
        float jFresnel = pow(1.0 - clamp(abs(dot(jNorm, jViewDir)), 0.0, 1.0), 2.8);
        float coreDist = length(vJellyLocalPos - vec3(0.0, 0.85, 0.06));
        float innerGlow = exp(-coreDist * coreDist * 1.38);
        float backLight = pow(clamp(dot(jViewDir, -normalize(uKeyLightViewDir)), 0.0, 1.0), 2.0);
        float wrapLight = clamp(dot(jNorm, normalize(uKeyLightViewDir)) * 0.5 + 0.5, 0.0, 1.0);
        vec3 sssColor = vec3(1.0, 0.45, 0.06) * (0.28 * innerGlow + 0.24 * backLight + 0.12 * wrapLight);
        sssColor += vec3(1.0, 0.64, 0.18) * (uPurrGlow * 0.25 * (0.45 + 0.55 * innerGlow));
        vec3 rimColor = vec3(1.0, 0.82, 0.48) * (jFresnel * 0.28);
        gl_FragColor.rgb += sssColor + rimColor;
        #include <tonemapping_fragment>
        `
      );
    };

    const catGroup = new THREE.Group();
    turntable.add(catGroup);

    const catMesh = new THREE.Mesh(catGeo, jellyMat);
    catMesh.castShadow = true;
    catMesh.frustumCulled = false;
    catGroup.add(catMesh);

    // =========================================================================
    // 5. TINY AIR BUBBLES INSIDE THE CLEAR JELLY (Captured by Transmission!)
    // =========================================================================
    const BUBBLE_SPECS = [
      { pos: [-0.22, 0.58,  0.18], r: 0.042 },
      { pos: [ 0.26, 0.66,  0.12], r: 0.032 },
      { pos: [-0.05, 0.42,  0.24], r: 0.050 },
      { pos: [ 0.14, 0.85,  0.04], r: 0.028 },
      { pos: [-0.28, 0.80, -0.10], r: 0.036 },
      { pos: [ 0.05, 0.55, -0.22], r: 0.044 },
      { pos: [-0.18, 1.32,  0.18], r: 0.026 },
      { pos: [ 0.24, 1.46,  0.08], r: 0.030 },
      { pos: [-0.06, 1.56,  0.12], r: 0.021 },
      { pos: [-0.36, 1.76,  0.09], r: 0.020 },
      { pos: [ 0.37, 1.79,  0.08], r: 0.018 },
      { pos: [ 0.62, 0.21, -0.44], r: 0.024 },
      { pos: [ 0.90, 0.24,  0.05], r: 0.029 },
      { pos: [ 0.86, 0.33,  0.34], r: 0.022 },
      { pos: [ 0.32, 0.36,  0.16], r: 0.034 },
      { pos: [-0.38, 0.34, -0.08], r: 0.038 }
    ];

    const bubbleGeo = new THREE.SphereGeometry(1, 16, 14);
    const bubbleMat = new THREE.ShaderMaterial({
      uniforms: {
        uLightDir: { value: new THREE.Vector3(-0.4, 0.75, 0.5).normalize() }
      },
      vertexShader: `
        varying vec3 vNormalV;
        varying vec3 vViewDir;
        void main() {
          vec4 mvPos = modelViewMatrix * vec4(position, 1.0);
          vNormalV = normalize(normalMatrix * normal);
          vViewDir = normalize(-mvPos.xyz);
          gl_Position = projectionMatrix * mvPos;
        }
      `,
      fragmentShader: `
        varying vec3 vNormalV;
        varying vec3 vViewDir;
        uniform vec3 uLightDir;
        void main() {
          vec3 N = normalize(vNormalV);
          vec3 V = normalize(vViewDir);
          float fres = pow(1.0 - clamp(dot(N, V), 0.0, 1.0), 2.2);
          float spec = pow(max(dot(reflect(-uLightDir, N), V), 0.0), 36.0);
          vec3 core = vec3(1.0, 0.62, 0.16);
          vec3 rim = vec3(1.0, 0.96, 0.86);
          vec3 col = mix(core, rim, fres * 0.92) + vec3(1.0) * spec * 1.15;
          gl_FragColor = vec4(col, 1.0);
        }
      `
    });

    const bubbles = BUBBLE_SPECS.map((b, i) => {
      const mesh = new THREE.Mesh(bubbleGeo, bubbleMat);
      mesh.scale.setScalar(b.r);
      mesh.frustumCulled = false;
      catGroup.add(mesh);
      return {
        mesh,
        rest: b.pos,
        r: b.r,
        phase: i * 1.37,
        weights: computePointWeights(b.pos[0], b.pos[1], b.pos[2])
      };
    });

    // =========================================================================
    // 6. EXPRESSIVE FACE RIG (Eye Tracking, Head-Rub Squinting, Blush, Nose, :3)
    // =========================================================================
    function findNearestVertex(tx, ty, tz) {
      let bestIdx = 0;
      let bestD2 = Infinity;
      for (let v = 0; v < vCount; v++) {
        const dx = restPositions[v * 3] - tx;
        const dy = restPositions[v * 3 + 1] - ty;
        const dz = restPositions[v * 3 + 2] - tz;
        const d2 = dx * dx + dy * dy + dz * dz;
        if (d2 < bestD2) {
          bestD2 = d2;
          bestIdx = v;
        }
      }
      return bestIdx;
    }

    const eyeLAnchorV = findNearestVertex(-0.20, 1.40, 0.56);
    const eyeRAnchorV = findNearestVertex( 0.20, 1.40, 0.56);
    const noseAnchorV = findNearestVertex( 0.00, 1.30, 0.62);
    const blushLAnchorV = findNearestVertex(-0.34, 1.24, 0.50);
    const blushRAnchorV = findNearestVertex( 0.34, 1.24, 0.50);

    function createEyeRig() {
      const root = new THREE.Group();
      root.frustumCulled = false;

      const openGroup = new THREE.Group();
      root.add(openGroup);

      // Warm creamy-peach glossy sclera oval nestled gently into face surface
      const sclera = new THREE.Mesh(
        new THREE.SphereGeometry(0.072, 22, 18),
        new THREE.MeshPhysicalMaterial({
          color: 0xfff3de,
          roughness: 0.08,
          clearcoat: 1.0,
          clearcoatRoughness: 0.04
        })
      );
      sclera.scale.set(0.95, 1.08, 0.36);
      sclera.frustumCulled = false;
      openGroup.add(sclera);

      // Tracking pupil + rich caramel-espresso iris + twin white catchlights
      const pupilGroup = new THREE.Group();
      pupilGroup.position.z = 0.015;
      openGroup.add(pupilGroup);

      const iris = new THREE.Mesh(
        new THREE.SphereGeometry(0.056, 20, 16),
        new THREE.MeshPhysicalMaterial({
          color: 0x2a1004,
          emissive: 0x120500,
          roughness: 0.04,
          clearcoat: 1.0
        })
      );
      iris.scale.set(0.94, 1.08, 0.36);
      iris.frustumCulled = false;
      pupilGroup.add(iris);

      // Subtle warm amber crescent glow in lower iris
      const irisGlow = new THREE.Mesh(
        new THREE.SphereGeometry(0.042, 16, 12),
        new THREE.MeshBasicMaterial({ color: 0xd96210 })
      );
      irisGlow.position.set(0, -0.012, 0.004);
      irisGlow.scale.set(0.92, 0.72, 0.34);
      irisGlow.frustumCulled = false;
      pupilGroup.add(irisGlow);

      const pupilCore = new THREE.Mesh(
        new THREE.SphereGeometry(0.036, 16, 12),
        new THREE.MeshBasicMaterial({ color: 0x110501 })
      );
      pupilCore.position.set(0, 0.002, 0.010);
      pupilCore.scale.set(0.90, 1.05, 0.32);
      pupilCore.frustumCulled = false;
      pupilGroup.add(pupilCore);

      // Crisp specular catchlight dots
      const catch1 = new THREE.Mesh(
        new THREE.SphereGeometry(0.015, 10, 10),
        new THREE.MeshBasicMaterial({ color: 0xffffff })
      );
      catch1.position.set(-0.018, 0.022, 0.021);
      catch1.scale.set(1, 1, 0.45);
      catch1.frustumCulled = false;
      pupilGroup.add(catch1);

      const catch2 = new THREE.Mesh(
        new THREE.SphereGeometry(0.008, 10, 10),
        new THREE.MeshBasicMaterial({ color: 0xffffff })
      );
      catch2.position.set(0.017, -0.016, 0.021);
      catch2.scale.set(1, 1, 0.45);
      catch2.frustumCulled = false;
      pupilGroup.add(catch2);

      // Happy curved `^` squint lid (shown when squinting / purring)
      const squintCurve = new THREE.CatmullRomCurve3([
        new THREE.Vector3(-0.062, -0.012, 0.012),
        new THREE.Vector3(-0.028,  0.022, 0.022),
        new THREE.Vector3( 0.000,  0.032, 0.024),
        new THREE.Vector3( 0.028,  0.022, 0.022),
        new THREE.Vector3( 0.062, -0.012, 0.012)
      ]);
      const squintMat = new THREE.MeshBasicMaterial({ color: 0x451b05, transparent: true, opacity: 0.0 });
      const squintLid = new THREE.Mesh(
        new THREE.TubeGeometry(squintCurve, 18, 0.0125, 8, false),
        squintMat
      );
      squintLid.frustumCulled = false;
      root.add(squintLid);

      return { root, openGroup, pupilGroup, squintLid, squintMat };
    }

    const eyeL = createEyeRig();
    const eyeR = createEyeRig();
    catGroup.add(eyeL.root);
    catGroup.add(eyeR.root);

    // Cute translucent gummy nose + `:3` smile
    const faceMouthGroup = new THREE.Group();
    faceMouthGroup.frustumCulled = false;
    catGroup.add(faceMouthGroup);

    const noseMesh = new THREE.Mesh(
      new THREE.SphereGeometry(0.036, 16, 14),
      new THREE.MeshPhysicalMaterial({
        color: 0xff4c18,
        emissive: 0x4a1200,
        roughness: 0.12,
        clearcoat: 1.0
      })
    );
    noseMesh.scale.set(1.25, 0.85, 0.65);
    noseMesh.frustumCulled = false;
    faceMouthGroup.add(noseMesh);

    const smileCurveL = new THREE.CatmullRomCurve3([
      new THREE.Vector3( 0.000, -0.022, 0.002),
      new THREE.Vector3(-0.022, -0.050, 0.000),
      new THREE.Vector3(-0.056, -0.044, -0.010),
      new THREE.Vector3(-0.072, -0.024, -0.018)
    ]);
    const smileCurveR = new THREE.CatmullRomCurve3([
      new THREE.Vector3(0.000, -0.022,  0.002),
      new THREE.Vector3(0.022, -0.050,  0.000),
      new THREE.Vector3(0.056, -0.044, -0.010),
      new THREE.Vector3(0.072, -0.024, -0.018)
    ]);
    const smileMat = new THREE.MeshBasicMaterial({ color: 0x6a2806 });
    const smileL = new THREE.Mesh(new THREE.TubeGeometry(smileCurveL, 14, 0.0085, 7, false), smileMat);
    const smileR = new THREE.Mesh(new THREE.TubeGeometry(smileCurveR, 14, 0.0085, 7, false), smileMat);
    smileL.frustumCulled = false;
    smileR.frustumCulled = false;
    faceMouthGroup.add(smileL, smileR);

    // Soft cheek blush pads
    const blushMat = new THREE.MeshBasicMaterial({
      color: 0xff6b52,
      transparent: true,
      opacity: 0.22,
      depthWrite: false
    });
    const blushGeo = new THREE.SphereGeometry(0.088, 16, 12);
    const blushL = new THREE.Mesh(blushGeo, blushMat);
    const blushR = new THREE.Mesh(blushGeo, blushMat);
    blushL.scale.set(1.2, 0.72, 0.16);
    blushR.scale.set(1.2, 0.72, 0.16);
    blushL.frustumCulled = false;
    blushR.frustumCulled = false;
    catGroup.add(blushL, blushR);

    // =========================================================================
    // 7. PHYSICS STATE & DEFORMATION KERNEL
    // =========================================================================
    const audio = new JellyAudio();

    const nodes = NODE_DEFS.map(d => ({
      id: d.id,
      rest: new THREE.Vector3(d.rest[0], d.rest[1], d.rest[2]),
      pos: new THREE.Vector3(d.rest[0], d.rest[1], d.rest[2]),
      vel: new THREE.Vector3(0, 0, 0),
      parent: d.parent,
      couple: d.couple
    }));

    const phys = {
      firmness: 0.35, // 0 = soft pudding, 1 = firm gummy
      dropY: 0.0,
      dropVy: 0.0,
      squash: 0.0,
      squashV: 0.0,
      shearX: 0.0,
      shearZ: 0.0,
      shearVx: 0.0,
      shearVz: 0.0,

      // Surface poke / squeeze impulses
      impulses: [], // { origin: Vector3, dir: Vector3, radius, amp, vel, live }

      // Active pointer grab/poke/squeeze
      grabActive: false,
      grabRegion: 0,
      grabNodeIdx: 0,
      grabRestPoint: new THREE.Vector3(),
      grabTargetDelta: new THREE.Vector3(),
      grabMode: 'none', // 'pull', 'poke', 'squeeze', 'rub'
      livePokeImpulse: null,

      // Head rub / purr / blink / eye tracking
      pettingMeter: 0.0,
      rubHeat: 0.0,
      blinkTimer: 2.8,
      blinkVal: 0.0,
      pointerWorld: new THREE.Vector3(0, 1.35, 3.0),
      eyeLookX: 0.0,
      eyeLookY: 0.0,

      // Turntable camera orbit
      orbitYaw: 0.08,
      orbitPitch: 0.34,
      targetYaw: 0.08,
      targetPitch: 0.34
    };

    function spawnPokeImpulse(localPos, localDir, strength, radius) {
      if (phys.impulses.length >= 6) {
        phys.impulses.shift();
      }
      const imp = {
        origin: localPos.clone(),
        dir: localDir.clone().normalize(),
        radius: radius || 0.34,
        amp: 0.0,
        vel: strength,
        live: false
      };
      phys.impulses.push(imp);
      return imp;
    }

    function triggerDrop() {
      audio.unlock();
      phys.dropY = 3.25;
      phys.dropVy = -0.35;
      phys.squash = 0.14; // slight vertical elongation as it falls
      phys.squashV = 0.0;
      for (let i = 0; i < nodes.length; i++) {
        nodes[i].vel.y += 0.35;
      }
      audio.playWetBloop(phys.firmness, 0.55, 1.15);
    }

    function updatePhysics(dt) {
      const f = phys.firmness;
      // Spring parameters tuned smoothly from soft pudding (2.2 Hz) to firm gummy (5.8 Hz)
      const kNode = 195 + f * f * 650 + f * 480;   // 195 .. 1325
      const zeta = 0.105 + f * 0.065;              // 0.105 .. 0.170
      const cNode = 2.0 * zeta * Math.sqrt(kNode);

      const kSquash = 210 + f * 960;
      const cSquash = 2.0 * (0.115 + f * 0.055) * Math.sqrt(kSquash);

      const kShear = 165 + f * 780;
      const cShear = 2.0 * (0.11 + f * 0.05) * Math.sqrt(kShear);

      const kImp = 260 + f * 1050;
      const cImp = 2.0 * (0.12 + f * 0.06) * Math.sqrt(kImp);

      // Soft pudding has subtle natural gravity slump
      const puddingSag = (1.0 - f) * (1.0 - f) * 0.045;

      const subSteps = 4;
      const subDt = dt / subSteps;

      for (let s = 0; s < subSteps; s++) {
        // 1. Drop & landing impact
        if (phys.dropY > 0 || phys.dropVy > 0) {
          phys.dropVy -= 24.5 * subDt;
          phys.dropY += phys.dropVy * subDt;
          if (phys.dropY <= 0) {
            const impact = Math.abs(phys.dropVy);
            phys.dropY = 0;
            if (impact > 0.7) {
              phys.squashV -= impact * (1.65 - f * 0.65);
              phys.shearVx += (Math.random() - 0.5) * impact * 0.32;
              phys.shearVz += (Math.random() - 0.5) * impact * 0.32;
              for (let i = 0; i < nodes.length; i++) {
                nodes[i].vel.y -= impact * (0.32 + 0.15 * (nodes[i].rest.y > 1.2 ? 1 : 0));
                if (i === 2 || i === 3) nodes[i].vel.y -= impact * 0.55; // floppy ears!
                if (i === 4 || i === 5) nodes[i].vel.x += (i === 4 ? -1 : 1) * impact * 0.38; // jiggling cheeks!
                if (i === 9) nodes[i].vel.y -= impact * 0.48; // tail slap!
              }
              if (s === 0 || impact > 1.6) {
                audio.playDropSplat(f, impact);
              }
              // Firm gummy bounces slightly; soft pudding splats flat
              const restitution = 0.05 + f * f * 0.32;
              phys.dropVy = impact * restitution;
              if (phys.dropVy < 0.55) phys.dropVy = 0;
            } else {
              phys.dropVy = 0;
            }
          }
        }

        // 2. Squash & lateral shear jelly modes
        const targetSquash = phys.grabActive && phys.grabMode === 'squeeze'
          ? Math.max(-0.34, Math.min(0.15, phys.grabTargetDelta.y * 0.42))
          : -puddingSag;

        const aSquash = -kSquash * (phys.squash - targetSquash) - cSquash * phys.squashV;
        phys.squashV += aSquash * subDt;
        phys.squash = Math.max(-0.46, Math.min(0.42, phys.squash + phys.squashV * subDt));

        const aShearX = -kShear * phys.shearX - cShear * phys.shearVx;
        const aShearZ = -kShear * phys.shearZ - cShear * phys.shearVz;
        phys.shearVx += aShearX * subDt;
        phys.shearVz += aShearZ * subDt;
        phys.shearX = Math.max(-0.45, Math.min(0.45, phys.shearX + phys.shearVx * subDt));
        phys.shearZ = Math.max(-0.45, Math.min(0.45, phys.shearZ + phys.shearVz * subDt));

        // 3. Coupled 12-node skeleton springs
        for (let i = 0; i < nodes.length; i++) {
          const nd = nodes[i];
          let tx = nd.rest.x;
          let ty = nd.rest.y;
          let tz = nd.rest.z;

          if (nd.parent >= 0) {
            const pNode = nodes[nd.parent];
            const pdx = pNode.pos.x - pNode.rest.x;
            const pdy = pNode.pos.y - pNode.rest.y;
            const pdz = pNode.pos.z - pNode.rest.z;
            tx += pdx * nd.couple;
            ty += pdy * nd.couple;
            tz += pdz * nd.couple;
          }

          const ax = -kNode * (nd.pos.x - tx) - cNode * nd.vel.x;
          const ay = -kNode * (nd.pos.y - ty) - cNode * nd.vel.y;
          const az = -kNode * (nd.pos.z - tz) - cNode * nd.vel.z;

          nd.vel.x += ax * subDt;
          nd.vel.y += ay * subDt;
          nd.vel.z += az * subDt;

          nd.pos.x += nd.vel.x * subDt;
          nd.pos.y += nd.vel.y * subDt;
          nd.pos.z += nd.vel.z * subDt;

          // Pull / drag constraint on active grabbed handle
          if (phys.grabActive && i === phys.grabNodeIdx && phys.grabMode === 'pull') {
            const maxPull = 1.05 - f * 0.42;
            const px = Math.max(-maxPull, Math.min(maxPull, phys.grabTargetDelta.x));
            const py = Math.max(-maxPull * 0.75, Math.min(maxPull, phys.grabTargetDelta.y));
            const pz = Math.max(-maxPull, Math.min(maxPull, phys.grabTargetDelta.z));
            const blend = 0.55;
            nd.pos.x += (nd.rest.x + px - nd.pos.x) * blend;
            nd.pos.y += (nd.rest.y + py - nd.pos.y) * blend;
            nd.pos.z += (nd.rest.z + pz - nd.pos.z) * blend;
            nd.vel.multiplyScalar(0.82);
          }

          // Clamp extreme excursions
          const dx = nd.pos.x - nd.rest.x;
          const dy = nd.pos.y - nd.rest.y;
          const dz = nd.pos.z - nd.rest.z;
          const dist = Math.hypot(dx, dy, dz);
          if (dist > 1.25) {
            const sc = 1.25 / dist;
            nd.pos.set(nd.rest.x + dx * sc, nd.rest.y + dy * sc, nd.rest.z + dz * sc);
          }
        }

        // 4. Surface poke wave impulses
        for (let p = phys.impulses.length - 1; p >= 0; p--) {
          const imp = phys.impulses[p];
          if (imp.live) continue;
          const aImp = -kImp * imp.amp - cImp * imp.vel;
          imp.vel += aImp * subDt;
          imp.amp += imp.vel * subDt;
          if (Math.abs(imp.amp) < 0.0012 && Math.abs(imp.vel) < 0.015) {
            phys.impulses.splice(p, 1);
          }
        }
      }

      // 5. Petting, purr glow, blink, and eye tracking
      if (phys.rubHeat > 0.01) {
        phys.pettingMeter = Math.min(1.0, phys.pettingMeter + phys.rubHeat * 1.45 * dt + dt * 0.85);
        phys.rubHeat = Math.max(0.0, phys.rubHeat - dt * 3.4);
      } else {
        phys.pettingMeter = Math.max(0.0, phys.pettingMeter - dt * 0.65);
      }
      audio.updatePurr(phys.pettingMeter);
      jellyUniforms.uPurrGlow.value = phys.pettingMeter;

      phys.blinkTimer -= dt;
      if (phys.blinkTimer <= 0) {
        phys.blinkTimer = 3.2 + Math.random() * 2.8;
      }
      // 0.16s natural quick blink at start of cycle
      const blinkCycle = phys.blinkTimer > 3.0 ? (3.2 - phys.blinkTimer) : -1;
      phys.blinkVal = (blinkCycle >= 0 && blinkCycle < 0.16)
        ? Math.sin((blinkCycle / 0.16) * Math.PI)
        : 0.0;
    }

    // Apply all jelly deformations onto the Surface Nets mesh, bubbles, and face rig
    const nodeDisp = new Float32Array(NODES_COUNT * 3);
    const posAttr = catGeo.attributes.position;
    const posArr = posAttr.array;

    function applyJellyDeformation(timeSec) {
      const f = phys.firmness;
      const scaleY = Math.max(0.52, 1.0 + phys.squash);
      const scaleXZ = 1.0 / Math.sqrt(scaleY);

      for (let n = 0; n < NODES_COUNT; n++) {
        nodeDisp[n * 3]     = nodes[n].pos.x - nodes[n].rest.x;
        nodeDisp[n * 3 + 1] = nodes[n].pos.y - nodes[n].rest.y;
        nodeDisp[n * 3 + 2] = nodes[n].pos.z - nodes[n].rest.z;
      }

      // Subtle cozy purr micro-tremor on head & chest while purring
      const purrTremor = phys.pettingMeter > 0.05
        ? Math.sin(timeSec * 25.5 * Math.PI * 2) * 0.0045 * phys.pettingMeter
        : 0.0;

      const impCount = phys.impulses.length;

      for (let v = 0; v < vCount; v++) {
        const vi = v * 3;
        const rx = restPositions[vi];
        const ry = restPositions[vi + 1];
        const rz = restPositions[vi + 2];

        // Blended skeleton node displacement
        let dx = 0, dy = 0, dz = 0;
        const wi = v * NODES_COUNT;
        for (let n = 0; n < NODES_COUNT; n++) {
          const w = vertWeights[wi + n];
          if (w > 0.002) {
            dx += w * nodeDisp[n * 3];
            dy += w * nodeDisp[n * 3 + 1];
            dz += w * nodeDisp[n * 3 + 2];
          }
        }

        let px = rx + dx;
        let py = ry + dy;
        let pz = rz + dz;

        // Global volume-preserving squash/stretch + shear wobble (anchored at y=0)
        const hNorm = Math.max(0, py);
        const hShear = hNorm * (0.45 + 0.35 * hNorm);
        px = px * scaleXZ + phys.shearX * hShear + purrTremor;
        pz = pz * scaleXZ + phys.shearZ * hShear;
        py = py * scaleY;

        // Soft-pudding gentle belly settle
        const sag = (1.0 - f) * (1.0 - f) * 0.045;
        if (sag > 0.001 && py > 0.06) {
          const midFactor = Math.exp(-Math.pow(py - 0.65, 2) * 1.6);
          const rad = Math.hypot(px, pz);
          if (rad > 0.01) {
            px += (px / rad) * sag * midFactor * 0.85;
            pz += (pz / rad) * sag * midFactor * 0.85;
          }
        }

        // Local surface poke dents & volume-conserving bulge ring
        for (let p = 0; p < impCount; p++) {
          const imp = phys.impulses[p];
          if (Math.abs(imp.amp) < 0.0008) continue;
          const ix = px - imp.origin.x;
          const iy = py - imp.origin.y;
          const iz = pz - imp.origin.z;
          const d2 = ix * ix + iy * iy + iz * iz;
          const r2 = imp.radius * imp.radius;
          if (d2 > r2 * 5.2) continue;

          const u = d2 / r2;
          const dent = Math.exp(-u);
          const ringBulge = (u * 0.55) * Math.exp(-u * 0.85);
          const s = imp.amp * dent;
          px += imp.dir.x * s;
          py += imp.dir.y * s;
          pz += imp.dir.z * s;

          // Slight radial outward puff around the poke crater
          const radialLen = Math.hypot(ix, iy, iz);
          if (radialLen > 0.005) {
            const bulge = -imp.amp * 0.28 * ringBulge;
            px += (ix / radialLen) * bulge;
            py += (iy / radialLen) * bulge;
            pz += (iz / radialLen) * bulge;
          }
        }

        // Keep cat cleanly above plate top when resting
        if (py < 0.015) py = 0.015;

        posArr[vi] = px;
        posArr[vi + 1] = py;
        posArr[vi + 2] = pz;
      }

      posAttr.needsUpdate = true;
      catGeo.computeVertexNormals();

      // Update cat vertical drop height
      catGroup.position.y = phys.dropY;

      // Update inner bubbles inside the deformed jelly
      for (let i = 0; i < bubbles.length; i++) {
        const b = bubbles[i];
        let dx = 0, dy = 0, dz = 0;
        for (let n = 0; n < NODES_COUNT; n++) {
          const w = b.weights[n];
          if (w > 0.002) {
            dx += w * nodeDisp[n * 3];
            dy += w * nodeDisp[n * 3 + 1];
            dz += w * nodeDisp[n * 3 + 2];
          }
        }
        const by = (b.rest[1] + dy) * scaleY + Math.sin(timeSec * 1.4 + b.phase) * 0.005;
        const hShear = Math.max(0, by) * (0.45 + 0.35 * Math.max(0, by));
        const bx = (b.rest[0] + dx) * scaleXZ + phys.shearX * hShear;
        const bz = (b.rest[2] + dz) * scaleXZ + phys.shearZ * hShear;
        b.mesh.position.set(bx, Math.max(0.06, by), bz);
        b.mesh.scale.set(b.r * scaleXZ, b.r * scaleY, b.r * scaleXZ);
      }

      // Position & orient eyes, nose, smile, and blush directly from live deformed face vertices
      const normArr = catGeo.attributes.normal.array;
      const tmpPos = new THREE.Vector3();
      const tmpNorm = new THREE.Vector3();
      const tmpQuat = new THREE.Quaternion();
      const zAxis = new THREE.Vector3(0, 0, 1);

      const placeOnFace = (mesh, anchorV, pushOut) => {
        const vi = anchorV * 3;
        tmpPos.set(posArr[vi], posArr[vi + 1], posArr[vi + 2]);
        tmpNorm.set(normArr[vi], normArr[vi + 1], normArr[vi + 2]).normalize();
        mesh.position.copy(tmpPos).addScaledVector(tmpNorm, pushOut);
        tmpQuat.setFromUnitVectors(zAxis, tmpNorm);
        mesh.quaternion.copy(tmpQuat);
      };

      placeOnFace(eyeL.root, eyeLAnchorV, 0.006);
      placeOnFace(eyeR.root, eyeRAnchorV, 0.006);
      placeOnFace(faceMouthGroup, noseAnchorV, 0.012);
      placeOnFace(blushL, blushLAnchorV, 0.008);
      placeOnFace(blushR, blushRAnchorV, 0.008);

      // Eye tracking toward finger / mouse in head-local space
      const worldEyeMid = new THREE.Vector3(0, 1.38 + phys.dropY, 0.56).applyMatrix4(turntable.matrixWorld);
      const toPointer = new THREE.Vector3().subVectors(phys.pointerWorld, worldEyeMid);
      // Transform pointer offset into turntable space
      const invTurntable = new THREE.Matrix4().copy(turntable.matrixWorld).invert();
      const localDir = toPointer.clone().transformDirection(invTurntable);

      const targetLookX = Math.max(-1, Math.min(1, localDir.x * 1.4));
      const targetLookY = Math.max(-1, Math.min(1, localDir.y * 1.4));
      phys.eyeLookX += (targetLookX - phys.eyeLookX) * 0.22;
      phys.eyeLookY += (targetLookY - phys.eyeLookY) * 0.22;

      eyeL.pupilGroup.position.x = phys.eyeLookX * 0.022;
      eyeL.pupilGroup.position.y = phys.eyeLookY * 0.019;
      eyeR.pupilGroup.position.x = phys.eyeLookX * 0.022;
      eyeR.pupilGroup.position.y = phys.eyeLookY * 0.019;

      // Squinting & happy ^ ^ eyelids (both natural blink and head-rub purr squint)
      const squint = Math.max(phys.blinkVal, phys.pettingMeter * 0.96);
      const openScaleY = Math.max(0.06, 1.0 - squint * 0.94);
      eyeL.openGroup.scale.y = openScaleY;
      eyeR.openGroup.scale.y = openScaleY;
      eyeL.openGroup.visible = squint < 0.92;
      eyeR.openGroup.visible = squint < 0.92;

      const lidOpacity = Math.max(0, (squint - 0.35) / 0.65);
      eyeL.squintMat.opacity = lidOpacity;
      eyeR.squintMat.opacity = lidOpacity;
      eyeL.squintLid.visible = lidOpacity > 0.02;
      eyeR.squintLid.visible = lidOpacity > 0.02;

      // Blush & internal glow response to purring & drop height
      blushMat.opacity = 0.22 + phys.pettingMeter * 0.44;
      const heightFade = Math.max(0.25, 1.0 - phys.dropY * 0.22);
      causticDisc.scale.setScalar((1.0 + Math.max(0, -phys.squash) * 0.65) * (1.0 + phys.dropY * 0.14));
      causticDisc.material.opacity = (0.88 + phys.pettingMeter * 0.12) * heightFade;
      innerCatLight.position.set(0.05 + phys.shearX * 0.5, 0.72 * scaleY + phys.dropY, 0.05 + phys.shearZ * 0.5);
      innerCatLight.intensity = 4.3 + phys.pettingMeter * 1.4;
    }

    // =========================================================================
    // 8. INTERACTION (One-Finger Touch & Mouse: Poke, Squeeze, Pull, Rub, Orbit)
    // =========================================================================
    const raycaster = new THREE.Raycaster();
    const pointerNDC = new THREE.Vector2();
    const dragPlane = new THREE.Plane();
    const hitPointWorld = new THREE.Vector3();
    const tmpRayHit = new THREE.Vector3();

    const inputState = {
      down: false,
      pointerId: null,
      mode: 'none', // 'cat', 'orbit'
      startX: 0,
      startY: 0,
      lastX: 0,
      lastY: 0,
      movedDist: 0,
      hoverOnCat: false
    };

    const purrBadge = document.getElementById('purr-badge');
    const demoCursor = document.getElementById('demo-cursor');
    const demoBadge = document.getElementById('demo-badge');
    const soundBtn = document.getElementById('sound-btn');
    const dropBtn = document.getElementById('drop-btn');
    const firmnessSlider = document.getElementById('firmness-slider');
    const firmnessReadout = document.getElementById('firmness-readout');

    function updateFirmnessLabel(val) {
      if (val < 0.24) firmnessReadout.textContent = 'Soft Pudding';
      else if (val < 0.56) firmnessReadout.textContent = 'Jiggly Jelly';
      else if (val < 0.82) firmnessReadout.textContent = 'Chewy Gel';
      else firmnessReadout.textContent = 'Firm Gummy';
    }
    updateFirmnessLabel(phys.firmness);

    firmnessSlider.addEventListener('input', () => {
      audio.unlock();
      phys.firmness = parseFloat(firmnessSlider.value);
      updateFirmnessLabel(phys.firmness);
    });

    dropBtn.addEventListener('click', () => {
      triggerDrop();
    });

    soundBtn.addEventListener('click', () => {
      const next = !audio.muted;
      audio.setMuted(next);
      if (!next) audio.unlock();
      soundBtn.textContent = next ? '🔇' : '🔊';
      soundBtn.classList.toggle('muted', next);
    });

    function screenToNDC(clientX, clientY) {
      const rect = canvas.getBoundingClientRect();
      pointerNDC.x = ((clientX - rect.left) / rect.width) * 2 - 1;
      pointerNDC.y = -((clientY - rect.top) / rect.height) * 2 + 1;
    }

    function updatePointerWorldLook(clientX, clientY) {
      screenToNDC(clientX, clientY);
      raycaster.setFromCamera(pointerNDC, camera);
      // Intersect a camera-facing plane slightly in front of the cat's head so eyes track smoothly
      const headWorld = new THREE.Vector3(0, 1.38 + phys.dropY, 0.65).applyMatrix4(turntable.matrixWorld);
      const camDir = new THREE.Vector3();
      camera.getWorldDirection(camDir);
      const lookPlane = new THREE.Plane().setFromNormalAndCoplanarPoint(camDir, headWorld);
      if (raycaster.ray.intersectPlane(lookPlane, tmpRayHit)) {
        phys.pointerWorld.copy(tmpRayHit);
      }
    }

    function handleStartInteraction(clientX, clientY) {
      updatePointerWorldLook(clientX, clientY);
      screenToNDC(clientX, clientY);
      raycaster.setFromCamera(pointerNDC, camera);

      const hits = raycaster.intersectObject(catMesh, false);
      if (hits.length > 0) {
        const hit = hits[0];
        const invMat = new THREE.Matrix4().copy(catGroup.matrixWorld).invert();
        const localHit = hit.point.clone().applyMatrix4(invMat);

        // Identify anatomical region via hit triangle vertex
        const vIdx = hit.face ? hit.face.a : 0;
        const reg = vertRegions[vIdx];

        inputState.mode = 'cat';
        phys.grabActive = true;
        phys.grabRegion = reg;
        phys.grabTargetDelta.set(0, 0, 0);

        const localNormal = hit.face
          ? hit.face.normal.clone().normalize()
          : localHit.clone().sub(new THREE.Vector3(0, 0.9, 0)).normalize();

        // Map region to pullable handle or poke/squeeze mode
        if (reg === 2) {
          phys.grabMode = 'pull';
          phys.grabNodeIdx = 2; // earL
        } else if (reg === 3) {
          phys.grabMode = 'pull';
          phys.grabNodeIdx = 3; // earR
        } else if (reg === 4) {
          phys.grabMode = 'pull';
          phys.grabNodeIdx = 4; // cheekL
        } else if (reg === 5) {
          phys.grabMode = 'pull';
          phys.grabNodeIdx = 5; // cheekR
        } else if (reg === 6) {
          phys.grabMode = 'pull';
          // Choose tailTip vs tailMid based on proximity
          const dTip = localHit.distanceTo(nodes[9].rest);
          const dMid = localHit.distanceTo(nodes[8].rest);
          phys.grabNodeIdx = dTip < dMid + 0.18 ? 9 : 8;
        } else if (reg === 1) {
          // Head: poking gently + ready for rub-squint or pull/squeeze
          phys.grabMode = 'poke';
          phys.grabNodeIdx = 1;
        } else {
          // Belly / Torso: poke & squeeze
          phys.grabMode = 'squeeze';
          phys.grabNodeIdx = localHit.z > 0.15 ? 6 : 0;
        }

        hitPointWorld.copy(hit.point);
        phys.grabRestPoint.copy(localHit);

        // Setup camera-facing drag plane at exact grab point
        const camDir = new THREE.Vector3();
        camera.getWorldDirection(camDir);
        dragPlane.setFromNormalAndCoplanarPoint(camDir, hitPointWorld);

        // Immediate tactile jelly poke impulse + wet bloop!
        const pokeStrength = -(0.16 + (1.0 - phys.firmness) * 0.10);
        const imp = spawnPokeImpulse(localHit, localNormal, 0.0, 0.38);
        imp.amp = pokeStrength * 0.55;
        imp.vel = pokeStrength * 12.0;
        phys.livePokeImpulse = imp;

        // Nudge corresponding node softly inward
        const nd = nodes[phys.grabNodeIdx];
        const pushScale = 1.65 - phys.firmness * 0.55;
        nd.vel.addScaledVector(localNormal, -pushScale);
        if (phys.grabMode === 'squeeze') {
          phys.squashV -= 0.75 * (1.2 - phys.firmness * 0.4);
        }

        audio.playWetBloop(phys.firmness, 0.72, reg >= 2 ? 1.18 : 0.94);
        canvas.classList.add('grabbing');
        return;
      }

      // Check plate tap
      const plateHits = raycaster.intersectObject(plateMesh, false);
      if (plateHits.length > 0) {
        audio.playPlateClink();
        phys.squashV -= 0.55;
        phys.shearVx += (Math.random() - 0.5) * 0.6;
        phys.shearVz += (Math.random() - 0.5) * 0.6;
      }

      // Background / plate drag rotates turntable smoothly
      inputState.mode = 'orbit';
      canvas.classList.add('grabbing');
    }

    function handleMoveInteraction(clientX, clientY) {
      updatePointerWorldLook(clientX, clientY);

      if (!inputState.down) {
        // Desktop non-pressed mouse: hover cursor feedback & gentle mouse head-rub support
        screenToNDC(clientX, clientY);
        raycaster.setFromCamera(pointerNDC, camera);
        const hits = raycaster.intersectObject(catMesh, false);
        const onCat = hits.length > 0;
        if (onCat !== inputState.hoverOnCat) {
          inputState.hoverOnCat = onCat;
          canvas.classList.toggle('on-cat', onCat);
        }
        if (onCat) {
          const hit = hits[0];
          const vIdx = hit.face ? hit.face.a : 0;
          if (vertRegions[vIdx] === 1) {
            const dx = clientX - inputState.lastX;
            const dy = clientY - inputState.lastY;
            const stepDist = Math.hypot(dx, dy);
            if (stepDist > 1.5 && stepDist < 65) {
              phys.rubHeat = Math.min(1.0, phys.rubHeat + stepDist * 0.015);
            }
          }
        }
        inputState.lastX = clientX;
        inputState.lastY = clientY;
        return;
      }

      const dx = clientX - inputState.lastX;
      const dy = clientY - inputState.lastY;
      const stepDist = Math.hypot(dx, dy);
      inputState.movedDist += stepDist;
      inputState.lastX = clientX;
      inputState.lastY = clientY;

      if (inputState.mode === 'orbit') {
        phys.targetYaw += dx * 0.0075;
        phys.targetPitch = Math.max(0.14, Math.min(0.88, phys.targetPitch + dy * 0.0055));
        return;
      }

      if (inputState.mode === 'cat' && phys.grabActive) {
        screenToNDC(clientX, clientY);
        raycaster.setFromCamera(pointerNDC, camera);
        if (!raycaster.ray.intersectPlane(dragPlane, tmpRayHit)) return;

        const worldDelta = new THREE.Vector3().subVectors(tmpRayHit, hitPointWorld);
        const invRot = new THREE.Matrix4().copy(turntable.matrixWorld).invert();
        const localDelta = worldDelta.clone().transformDirection(invRot);
        phys.grabTargetDelta.copy(localDelta);

        if (phys.grabMode === 'pull') {
          // Stretch ear, cheek, or tail!
          const stretchLen = localDelta.length();
          if (stretchLen > 0.08) {
            audio.playStretchMicro(phys.firmness, stretchLen);
          }
          // Subtle empathetic head/body tilt toward pull
          phys.shearVx += localDelta.x * 0.06;
          phys.shearVz += localDelta.z * 0.06;
        } else if (phys.grabRegion === 1) {
          // Touching & rubbing the head makes it squint and purr + gently wobbles head!
          if (stepDist > 1.0) {
            phys.rubHeat = Math.min(1.0, phys.rubHeat + stepDist * 0.036);
          }
          nodes[1].vel.x += localDelta.x * 0.25;
          nodes[1].vel.y += localDelta.y * 0.16;
          nodes[1].vel.z += localDelta.z * 0.25;
          if (phys.livePokeImpulse) {
            phys.livePokeImpulse.amp = -0.075;
          }
        } else {
          // Squeeze & jiggle the chubby belly / body!
          const squeezeY = Math.max(-0.65, Math.min(0.28, localDelta.y));
          nodes[phys.grabNodeIdx].vel.x += localDelta.x * 0.35;
          nodes[phys.grabNodeIdx].vel.z += localDelta.z * 0.35;
          phys.shearVx += localDelta.x * 0.12;
          phys.shearVz += localDelta.z * 0.12;
          phys.grabTargetDelta.y = squeezeY;
          if (phys.livePokeImpulse) {
            phys.livePokeImpulse.amp = -0.14 - Math.max(0, -squeezeY) * 0.14;
          }
          if (stepDist > 5) {
            audio.playStretchMicro(phys.firmness, Math.abs(squeezeY));
          }
        }
      }
    }

    function handleEndInteraction() {
      if (phys.grabActive) {
        if (phys.grabMode === 'pull') {
          const stretch = phys.grabTargetDelta.length();
          if (stretch > 0.08) {
            audio.playSnapWobble(phys.firmness, Math.min(1.0, stretch));
          }
        } else if (phys.grabMode === 'squeeze' && phys.grabTargetDelta.length() > 0.09) {
          audio.playSnapWobble(phys.firmness, 0.5);
        }
      }
      if (phys.livePokeImpulse) {
        phys.livePokeImpulse.live = false;
        phys.livePokeImpulse = null;
      }
      phys.grabActive = false;
      phys.grabMode = 'none';
      inputState.down = false;
      inputState.pointerId = null;
      inputState.mode = 'none';
      canvas.classList.remove('grabbing');
    }

    // =========================================================================
    // 9. #DEMO HANDS-FREE 20-SECOND LOOP (Terminates immediately on real touch)
    // =========================================================================
    let isDemoActive = window.location.hash === '#demo' || window.location.href.endsWith('#demo');
    let demoElapsed = 0;
    let demoPrevPhase = '';

    function stopDemo() {
      if (!isDemoActive) return;
      isDemoActive = false;
      demoBadge.classList.remove('active');
      demoCursor.classList.remove('visible', 'pressing');
      handleEndInteraction();
      // Reset slider to pleasant midpoint if stopped mid-demo
      phys.firmness = parseFloat(firmnessSlider.value);
    }

    if (isDemoActive) {
      demoBadge.classList.add('active');
    }

    window.addEventListener('hashchange', () => {
      if (window.location.hash === '#demo') {
        isDemoActive = true;
        demoElapsed = 0;
        demoPrevPhase = '';
        demoBadge.classList.add('active');
      }
    });

    // Any real user touch / pointer press immediately stops #demo
    window.addEventListener('pointerdown', (e) => {
      if (e.isTrusted && isDemoActive) {
        stopDemo();
      }
    }, { capture: true, passive: true });

    window.addEventListener('touchstart', (e) => {
      if (e.isTrusted && isDemoActive) {
        stopDemo();
      }
    }, { capture: true, passive: true });

    // Real pointer events on canvas
    canvas.addEventListener('pointerdown', (e) => {
      if (isDemoActive) stopDemo();
      audio.unlock();
      if (inputState.down) return;
      inputState.down = true;
      inputState.pointerId = e.pointerId;
      inputState.startX = e.clientX;
      inputState.startY = e.clientY;
      inputState.lastX = e.clientX;
      inputState.lastY = e.clientY;
      inputState.movedDist = 0;
      try { canvas.setPointerCapture(e.pointerId); } catch (err) {}
      handleStartInteraction(e.clientX, e.clientY);
    });

    canvas.addEventListener('pointermove', (e) => {
      if (isDemoActive) return;
      if (inputState.down && e.pointerId !== inputState.pointerId) return;
      handleMoveInteraction(e.clientX, e.clientY);
    });

    const onPointerDone = (e) => {
      if (inputState.down && e.pointerId === inputState.pointerId) {
        try { canvas.releasePointerCapture(e.pointerId); } catch (err) {}
        handleEndInteraction();
      }
    };
    canvas.addEventListener('pointerup', onPointerDone);
    canvas.addEventListener('pointercancel', onPointerDone);

    function projectLocalToScreen(lx, ly, lz) {
      const wp = new THREE.Vector3(lx, ly + phys.dropY, lz).applyMatrix4(turntable.matrixWorld);
      wp.project(camera);
      const rect = canvas.getBoundingClientRect();
      return {
        x: rect.left + (wp.x * 0.5 + 0.5) * rect.width,
        y: rect.top + (-wp.y * 0.5 + 0.5) * rect.height
      };
    }

    function stepDemo(dt) {
      if (!isDemoActive) return;
      demoElapsed = (demoElapsed + dt) % 20.0;
      const t = demoElapsed;

      const setCursor = (lx, ly, lz, pressing) => {
        const sc = projectLocalToScreen(lx, ly, lz);
        demoCursor.style.left = sc.x + 'px';
        demoCursor.style.top = sc.y + 'px';
        demoCursor.classList.add('visible');
        demoCursor.classList.toggle('pressing', !!pressing);
        updatePointerWorldLook(sc.x, sc.y);
      };

      const releasePull = () => {
        if (phys.grabActive) {
          phys.grabActive = false;
          phys.grabMode = 'none';
          if (phys.livePokeImpulse) {
            phys.livePokeImpulse.live = false;
            phys.livePokeImpulse = null;
          }
        }
      };

      // 0.0 - 2.2s: Drop from above!
      if (t < 2.2) {
        if (demoPrevPhase !== 'drop1') {
          demoPrevPhase = 'drop1';
          releasePull();
          phys.firmness = 0.35;
          firmnessSlider.value = '0.35';
          updateFirmnessLabel(0.35);
          phys.targetYaw = 0.08;
          phys.targetPitch = 0.34;
          triggerDrop();
        }
        setCursor(0.35, 1.45, 0.85, false);
      }
      // 2.2 - 4.7s: Poke & squeeze chubby belly!
      else if (t < 4.7) {
        const u = t - 2.2;
        if (u < 0.55) {
          if (demoPrevPhase !== 'poke1') {
            demoPrevPhase = 'poke1';
            spawnPokeImpulse(new THREE.Vector3(0.0, 0.55, 0.62), new THREE.Vector3(0, 0, -1), -2.4, 0.38);
            nodes[6].vel.z -= 2.2;
            phys.squashV -= 0.7;
          }
          setCursor(0.0, 0.55, 0.64, true);
        } else if (u < 1.15) {
          setCursor(-0.18, 0.52, 0.64, false);
        } else if (u < 2.15) {
          if (demoPrevPhase !== 'squeeze') {
            demoPrevPhase = 'squeeze';
            phys.grabActive = true;
            phys.grabMode = 'squeeze';
            phys.grabNodeIdx = 6;
          }
          const sq = Math.sin(((u - 1.15) / 1.0) * Math.PI);
          phys.grabTargetDelta.set(0, -0.68 * sq, 0);
          setCursor(0.0, 0.56 - sq * 0.24, 0.62, true);
        } else {
          if (demoPrevPhase !== 'squeezeEnd') {
            demoPrevPhase = 'squeezeEnd';
            releasePull();
          }
          setCursor(0.0, 0.78, 0.68, false);
        }
      }
      // 4.7 - 7.7s: Pull Left Ear & Right Ear!
      else if (t < 7.7) {
        const u = t - 4.7;
        if (u < 1.15) {
          if (demoPrevPhase !== 'earL') {
            demoPrevPhase = 'earL';
            phys.grabActive = true;
            phys.grabMode = 'pull';
            phys.grabNodeIdx = 2;
          }
          const k = Math.sin(Math.min(1, u / 1.05) * Math.PI * 0.5);
          phys.grabTargetDelta.set(-0.42 * k, 0.44 * k, 0.08 * k);
          setCursor(-0.44 - 0.36 * k, 1.94 + 0.38 * k, 0.12, true);
        } else if (u < 1.55) {
          if (demoPrevPhase !== 'earLRel') {
            demoPrevPhase = 'earLRel';
            releasePull();
          }
          setCursor(0.0, 1.85, 0.4, false);
        } else if (u < 2.65) {
          if (demoPrevPhase !== 'earR') {
            demoPrevPhase = 'earR';
            phys.grabActive = true;
            phys.grabMode = 'pull';
            phys.grabNodeIdx = 3;
          }
          const k = Math.sin(Math.min(1, (u - 1.55) / 1.0) * Math.PI * 0.5);
          phys.grabTargetDelta.set(0.42 * k, 0.42 * k, 0.08 * k);
          setCursor(0.44 + 0.36 * k, 1.94 + 0.36 * k, 0.12, true);
        } else {
          if (demoPrevPhase !== 'earRRel') {
            demoPrevPhase = 'earRRel';
            releasePull();
          }
          setCursor(0.55, 1.55, 0.45, false);
        }
      }
      // 7.7 - 10.2s: Pull Chubby Cheek!
      else if (t < 10.2) {
        const u = t - 7.7;
        if (u < 1.45) {
          if (demoPrevPhase !== 'cheekR') {
            demoPrevPhase = 'cheekR';
            phys.grabActive = true;
            phys.grabMode = 'pull';
            phys.grabNodeIdx = 5;
          }
          const k = Math.sin(Math.min(1, u / 1.35) * Math.PI * 0.5);
          phys.grabTargetDelta.set(0.48 * k, 0.04 * k, 0.18 * k);
          setCursor(0.46 + 0.40 * k, 1.24, 0.44, true);
        } else {
          if (demoPrevPhase !== 'cheekRel') {
            demoPrevPhase = 'cheekRel';
            releasePull();
          }
          setCursor(0.75, 1.10, 0.55, false);
        }
      }
      // 10.2 - 13.4s: Orbit slightly & Pull Curved Jelly Tail!
      else if (t < 13.4) {
        const u = t - 10.2;
        phys.targetYaw = -0.58 * Math.sin(Math.min(1, u / 2.8) * Math.PI);
        if (u > 0.45 && u < 2.1) {
          if (demoPrevPhase !== 'tailPull') {
            demoPrevPhase = 'tailPull';
            phys.grabActive = true;
            phys.grabMode = 'pull';
            phys.grabNodeIdx = 9;
          }
          const k = Math.sin(Math.min(1, (u - 0.45) / 1.45) * Math.PI * 0.5);
          phys.grabTargetDelta.set(0.54 * k, 0.46 * k, 0.16 * k);
          setCursor(0.90 + 0.46 * k, 0.34 + 0.40 * k, 0.36, true);
        } else {
          if (demoPrevPhase !== 'tailRel' && u >= 2.1) {
            demoPrevPhase = 'tailRel';
            releasePull();
          }
          setCursor(0.88, 0.42, 0.42, false);
        }
      }
      // 13.4 - 16.5s: Rub Head -> Squinting & Purring!
      else if (t < 16.5) {
        const u = t - 13.4;
        phys.targetYaw = 0.08;
        if (demoPrevPhase !== 'rubHead') {
          demoPrevPhase = 'rubHead';
          releasePull();
        }
        const rubX = Math.sin(u * 8.5) * 0.28;
        const rubZ = 0.20 + Math.cos(u * 4.2) * 0.06;
        phys.rubHeat = 1.0;
        nodes[1].vel.x += Math.cos(u * 8.5) * 0.16;
        setCursor(rubX, 1.78, rubZ, true);
      }
      // 16.5 - 20.0s: Soft Pudding vs Firm Gummy slider + Finale Drop!
      else {
        const u = t - 16.5;
        if (u < 1.5) {
          if (demoPrevPhase !== 'pudding') {
            demoPrevPhase = 'pudding';
            phys.firmness = 0.04;
            firmnessSlider.value = '0.04';
            updateFirmnessLabel(0.04);
            spawnPokeImpulse(new THREE.Vector3(-0.15, 0.65, 0.58), new THREE.Vector3(0.2, 0, -1), -2.8, 0.44);
            phys.shearVx += 1.6;
          }
          setCursor(-0.15, 0.65, 0.60, u < 0.5);
        } else {
          if (demoPrevPhase !== 'gummyDrop') {
            demoPrevPhase = 'gummyDrop';
            phys.firmness = 0.94;
            firmnessSlider.value = '0.94';
            updateFirmnessLabel(0.94);
            triggerDrop();
          }
          setCursor(0.25, 1.25, 0.72, false);
        }
      }
    }

    // =========================================================================
    // 10. RESPONSIVE CAMERA & MAIN RENDER LOOP
    // =========================================================================
    function updateCameraAspect() {
      const w = window.innerWidth;
      const h = window.innerHeight;
      renderer.setSize(w, h, false);
      camera.aspect = w / h;
      camera.updateProjectionMatrix();
    }
    window.addEventListener('resize', updateCameraAspect);
    updateCameraAspect();

    let lastTime = performance.now();
    const tmpWorldLightDir = new THREE.Vector3();

    function animate(now) {
      requestAnimationFrame(animate);
      const rawDt = (now - lastTime) * 0.001;
      lastTime = now;
      const dt = Math.max(0.001, Math.min(0.033, rawDt));
      const timeSec = now * 0.001;

      if (isDemoActive) {
        stepDemo(dt);
      }

      updatePhysics(dt);

      // Smooth turntable orbit & responsive camera framing (fits portrait & desktop)
      phys.orbitYaw += (phys.targetYaw - phys.orbitYaw) * Math.min(1, dt * 10);
      phys.orbitPitch += (phys.targetPitch - phys.orbitPitch) * Math.min(1, dt * 10);
      turntable.rotation.y = phys.orbitYaw;

      const aspect = window.innerWidth / Math.max(1, window.innerHeight);
      const dist = aspect < 0.85 ? 5.65 : (aspect < 1.15 ? 5.05 : 4.75);
      const targetY = aspect < 0.85 ? 0.78 : 0.88;

      camera.position.set(
        0.0,
        targetY + Math.sin(phys.orbitPitch) * dist,
        Math.cos(phys.orbitPitch) * dist
      );
      camera.lookAt(0.05, targetY, 0.0);
      camera.updateMatrixWorld();
      turntable.updateMatrixWorld();

      // Update key light direction in view space for accurate jelly subsurface scatter
      tmpWorldLightDir.copy(backRimLight.position).normalize();
      tmpWorldLightDir.transformDirection(camera.matrixWorldInverse);
      jellyUniforms.uKeyLightViewDir.value.copy(tmpWorldLightDir);

      applyJellyDeformation(timeSec);

      // Update floating "purr~" badge visibility
      purrBadge.classList.toggle('active', phys.pettingMeter > 0.22);

      renderer.render(scene, camera);
    }

    requestAnimationFrame(animate);
  })();
  </script>
</body>
</html>