Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat(dissolve): add the Dissolve page that turns any 3D model into a GPU particle storm with shape morphing and force fields

nirholasaaacc8b60fca
diff --git a/data/pages.json b/data/pages.json
index 3402c8431..fbc13122b 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -106,6 +106,14 @@
"changefreq": "weekly",
"added": "2026-09-10"
},
+ {
+ "path": "/dissolve",
+ "title": "Dissolve",
+ "description": "Turn any 3D model into a storm of up to a million GPU particles, morph one shape into another, bend the storm with black holes, vortexes and shockwaves, and let your microphone drive it. Record or share what you make.",
+ "priority": 0.7,
+ "changefreq": "weekly",
+ "added": "2026-10-12"
+ },
{
"path": "/choreograph",
"title": "Choreographer",
diff --git a/pages/dissolve.html b/pages/dissolve.html
new file mode 100644
index 000000000..6cce03932
--- /dev/null
+++ b/pages/dissolve.html
@@ -0,0 +1,148 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot: no-flash */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+ <title>Dissolve · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
+ <meta name="description" content="Turn any 3D model into a living storm of up to a million GPU particles, morph one avatar into another, then bend the storm with a black hole, a vortex, shockwaves and your voice." />
+ <meta name="theme-color" content="#04060b" />
+ <link rel="canonical" href="https://three.ws/dissolve" />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:title" content="Dissolve · three.ws" />
+ <meta property="og:description" content="Any 3D model becomes a million-particle storm you can morph, pull into a black hole and shatter with a shockwave. Runs entirely on your GPU." />
+ <meta property="og:url" content="https://three.ws/dissolve" />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=labs&amp;t=Dissolve&amp;d=Any+3D+model+becomes+a+million-particle+storm.+Morph+one+avatar+into+another%2C+pull+it+into+a+black+hole%2C+shatter+it+with+a+shockwave.&amp;p=%2Fdissolve" />
+ <meta property="og:image:alt" content="Dissolve on three.ws" />
+ <meta property="og:locale" content="en_US" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Dissolve · three.ws" />
+ <meta name="twitter:description" content="Any 3D model becomes a million-particle storm. Morph it, bend it, shatter it, all on your GPU." />
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=labs&amp;t=Dissolve&amp;d=Any+3D+model+becomes+a+million-particle+storm.+Morph+one+avatar+into+another%2C+pull+it+into+a+black+hole%2C+shatter+it+with+a+shockwave.&amp;p=%2Fdissolve" />
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/dissolve.css" />
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"Dissolve","description":"Turn any 3D model into a GPU particle storm, morph one model into another and bend it with forces.","url":"https://three.ws/dissolve","applicationCategory":"MultimediaApplication","operatingSystem":"Any","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ </head>
+ <body class="ds-body">
+ <header><div id="nav-container"></div></header>
+
+ <main class="ds-stage" id="dsStage">
+ <canvas class="ds-canvas" id="dsCanvas" role="img" aria-label="A 3D model dissolved into a storm of glowing particles"></canvas>
+
+ <div class="ds-hero" id="dsHero">
+ <div class="ds-chip"><span class="ds-chip-dot" aria-hidden="true"></span><span id="dsCount">GPU particles</span></div>
+ <h1>Dissolve</h1>
+ <p>Every model is a storm waiting to happen. Drag to pull it into a black hole.</p>
+ </div>
+
+ <div class="ds-loading" id="dsLoading" role="status" aria-live="polite" hidden>
+ <div class="ds-loading-card">
+ <div class="ds-loading-label" id="dsLoadingLabel">Loading</div>
+ <div class="ds-bar" aria-hidden="true"><div class="ds-bar-fill" id="dsBarFill"></div></div>
+ </div>
+ </div>
+
+ <div class="ds-fallback" id="dsFallback" hidden>
+ <h2 id="dsFallbackTitle">This browser cannot run Dissolve</h2>
+ <p id="dsFallbackBody"></p>
+ <a class="ds-btn ds-btn--primary" href="/viewer">Open the standard 3D viewer</a>
+ </div>
+
+ <div class="ds-rec" id="dsRec" hidden><span class="ds-rec-dot" aria-hidden="true"></span><span id="dsRecTime">0:00</span></div>
+
+ <button type="button" class="ds-dock-toggle" id="dsDockToggle" aria-expanded="true" aria-controls="dsDock">Controls</button>
+
+ <aside class="ds-dock" id="dsDock" aria-label="Dissolve controls">
+ <section class="ds-sec" aria-labelledby="dsSecShapes">
+ <h2 id="dsSecShapes">Shapes</h2>
+ <div class="ds-slot">
+ <span class="ds-slot-tag" aria-hidden="true">A</span>
+ <div class="ds-chips" id="dsShelfA" role="radiogroup" aria-label="Shape A"></div>
+ </div>
+ <div class="ds-slot">
+ <span class="ds-slot-tag ds-slot-tag--b" aria-hidden="true">B</span>
+ <div class="ds-chips" id="dsShelfB" role="radiogroup" aria-label="Shape B"></div>
+ </div>
+ <div class="ds-row">
+ <button type="button" class="ds-btn" id="dsPickA">Your GLB into A</button>
+ <button type="button" class="ds-btn" id="dsPickB">Your GLB into B</button>
+ <input type="file" id="dsFile" accept=".glb,.gltf,model/gltf-binary" hidden />
+ </div>
+ <form class="ds-url" id="dsUrlForm" autocomplete="off">
+ <label class="ds-sr" for="dsUrl">GLB link</label>
+ <input id="dsUrl" type="url" inputmode="url" placeholder="https://… .glb" spellcheck="false" />
+ <button type="submit" class="ds-btn" data-slot="A">To A</button>
+ <button type="submit" class="ds-btn" data-slot="B">To B</button>
+ </form>
+ </section>
+
+ <section class="ds-sec" aria-labelledby="dsSecMorph">
+ <h2 id="dsSecMorph">Morph</h2>
+ <div class="ds-row">
+ <button type="button" class="ds-btn ds-btn--primary" id="dsMorph">Morph to B</button>
+ <button type="button" class="ds-btn" id="dsSwap" title="Swap A and B (S)">Swap</button>
+ <button type="button" class="ds-btn ds-toggle" id="dsLoop" aria-pressed="false">Loop</button>
+ </div>
+ <label class="ds-range"><span>A</span>
+ <input type="range" id="dsMix" min="0" max="1000" value="0" aria-label="Blend between shape A and shape B" />
+ <span>B</span></label>
+ </section>
+
+ <section class="ds-sec" aria-labelledby="dsSecTools">
+ <h2 id="dsSecTools">Forces</h2>
+ <div class="ds-tools" id="dsTools" role="radiogroup" aria-label="Pointer tool">
+ <button type="button" role="radio" class="ds-tool" data-tool="orbit" aria-checked="false"><kbd>1</kbd>Orbit</button>
+ <button type="button" role="radio" class="ds-tool" data-tool="gravity" aria-checked="true"><kbd>2</kbd>Black hole</button>
+ <button type="button" role="radio" class="ds-tool" data-tool="vortex" aria-checked="false"><kbd>3</kbd>Vortex</button>
+ <button type="button" role="radio" class="ds-tool" data-tool="burst" aria-checked="false"><kbd>4</kbd>Shockwave</button>
+ </div>
+ <p class="ds-hint" id="dsToolHint"></p>
+ <div class="ds-row">
+ <button type="button" class="ds-btn ds-toggle" id="dsCollapse" aria-pressed="false" title="Let go and fall to the floor (C)">Collapse</button>
+ <button type="button" class="ds-btn" id="dsDetonate" title="Blow the shape apart (B)">Detonate</button>
+ </div>
+ </section>
+
+ <section class="ds-sec" aria-labelledby="dsSecLook">
+ <h2 id="dsSecLook">Look</h2>
+ <div class="ds-chips" id="dsPresets" role="radiogroup" aria-label="Look preset"></div>
+ <label class="ds-slider"><span>Size</span><input type="range" id="dsSize" min="0.3" max="2.6" step="0.01" /></label>
+ <label class="ds-slider"><span>Glow</span><input type="range" id="dsGlow" min="0" max="2.5" step="0.01" /></label>
+ <label class="ds-slider"><span>Chaos</span><input type="range" id="dsChaos" min="0" max="2" step="0.01" /></label>
+ <div class="ds-row">
+ <button type="button" class="ds-btn ds-toggle" id="dsOrbit" aria-pressed="true">Auto-orbit</button>
+ <button type="button" class="ds-btn ds-toggle" id="dsMic" aria-pressed="false" title="React to sound (M)">Mic</button>
+ </div>
+ </section>
+
+ <section class="ds-sec" aria-labelledby="dsSecShare">
+ <h2 id="dsSecShare">Capture</h2>
+ <div class="ds-row">
+ <button type="button" class="ds-btn" id="dsShot" title="Save a PNG (P)">Snapshot</button>
+ <button type="button" class="ds-btn" id="dsRecord" title="Record a clip (R)">Record</button>
+ <button type="button" class="ds-btn" id="dsShare">Copy link</button>
+ </div>
+ <label class="ds-select"><span>Particles</span>
+ <select id="dsQuality" aria-label="Particle count"></select>
+ </label>
+ </section>
+ <p class="ds-keys">Space morph · 1-4 tools · S swap · C collapse · B detonate · M mic · P snapshot · R record · H hide controls</p>
+ </aside>
+
+ <div class="ds-toast" id="dsToast" role="status" aria-live="polite" hidden></div>
+ </main>
+
+ <script src="/nav.js" defer></script>
+ <script type="module" src="/src/dissolve/page.js"></script>
+ </body>
+</html>
diff --git a/public/dissolve.css b/public/dissolve.css
new file mode 100644
index 000000000..45163b96f
--- /dev/null
+++ b/public/dissolve.css
@@ -0,0 +1,530 @@
+/* /dissolve: full-bleed particle stage with a floating control dock.
+ *
+ * Page tokens layer over /style.css. The stage is always dark: it is a lit
+ * scene, not a document, so the theme only recolours the dock.
+ */
+
+:root {
+ --ds-accent: #6ee7ff;
+ --ds-accent-2: #a78bfa;
+ --ds-ink: #eef4ff;
+ --ds-muted: rgba(226, 236, 255, 0.62);
+ --ds-panel: rgba(8, 12, 22, 0.72);
+ --ds-border: rgba(160, 190, 255, 0.16);
+ --ds-border-strong: rgba(160, 200, 255, 0.4);
+ --ds-surface: rgba(255, 255, 255, 0.05);
+ --ds-surface-hover: rgba(255, 255, 255, 0.1);
+ --ds-danger: #ff5d6c;
+ --ds-radius: 14px;
+}
+:root[data-theme='light'] {
+ --ds-panel: rgba(255, 255, 255, 0.82);
+ --ds-ink: #0b1220;
+ --ds-muted: rgba(11, 18, 32, 0.62);
+ --ds-border: rgba(10, 30, 70, 0.14);
+ --ds-border-strong: rgba(10, 30, 70, 0.42);
+ --ds-surface: rgba(10, 30, 70, 0.05);
+ --ds-surface-hover: rgba(10, 30, 70, 0.1);
+ --ds-accent: #0369a1;
+}
+
+.ds-body {
+ margin: 0;
+ background: #04060b;
+ color: var(--ds-ink);
+ overflow: hidden;
+ overscroll-behavior: none;
+}
+.ds-body > header {
+ position: relative;
+ z-index: 30;
+}
+
+.ds-stage {
+ position: fixed;
+ inset: 0;
+ z-index: 1;
+ overflow: hidden;
+ background: radial-gradient(1200px 800px at 50% 0%, rgba(40, 80, 200, 0.18), transparent 60%), #04060b;
+}
+.ds-stage.is-drop::after {
+ content: 'Drop a .glb to dissolve it into B';
+ position: absolute;
+ inset: 16px;
+ display: grid;
+ place-items: center;
+ border: 2px dashed var(--ds-accent);
+ border-radius: 22px;
+ background: rgba(4, 10, 24, 0.7);
+ color: var(--ds-ink);
+ font: 600 18px/1.3 var(--font-display, system-ui, sans-serif);
+ z-index: 20;
+ pointer-events: none;
+}
+.ds-canvas {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ display: block;
+ touch-action: none;
+ cursor: crosshair;
+ outline: none;
+}
+.ds-canvas[data-tool='orbit'] {
+ cursor: grab;
+}
+.ds-canvas[data-tool='orbit']:active {
+ cursor: grabbing;
+}
+
+/* ── Hero ── */
+.ds-hero {
+ position: absolute;
+ left: clamp(16px, 3vw, 40px);
+ top: clamp(72px, 10vh, 110px);
+ max-width: min(440px, 60vw);
+ pointer-events: none;
+ transition: opacity 0.6s ease, transform 0.6s ease;
+}
+.ds-hero.is-compact {
+ opacity: 0.85;
+}
+.ds-hero h1 {
+ margin: 10px 0 6px;
+ font: 700 clamp(34px, 5.4vw, 64px) / 1 var(--font-display, 'Space Grotesk', system-ui, sans-serif);
+ letter-spacing: -0.035em;
+ background: linear-gradient(120deg, #fff 10%, var(--ds-accent) 55%, var(--ds-accent-2));
+ -webkit-background-clip: text;
+ background-clip: text;
+ color: transparent;
+}
+.ds-hero p {
+ margin: 0;
+ color: var(--ds-muted);
+ font-size: 15px;
+ line-height: 1.5;
+}
+:root[data-theme='light'] .ds-hero h1 {
+ background: linear-gradient(120deg, #fff 10%, #7dd3fc 55%, #c4b5fd);
+ -webkit-background-clip: text;
+ background-clip: text;
+}
+:root[data-theme='light'] .ds-hero p,
+:root[data-theme='light'] .ds-chip {
+ color: rgba(226, 236, 255, 0.7);
+}
+.ds-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 12px;
+ border: 1px solid var(--ds-border);
+ border-radius: 999px;
+ background: rgba(8, 12, 22, 0.55);
+ backdrop-filter: blur(10px);
+ font: 600 11px/1 var(--font-mono, ui-monospace, monospace);
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ color: var(--ds-muted);
+}
+.ds-chip-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: var(--ds-accent);
+ box-shadow: 0 0 10px var(--ds-accent);
+ animation: ds-pulse 2.4s ease-in-out infinite;
+}
+@keyframes ds-pulse {
+ 50% {
+ opacity: 0.35;
+ }
+}
+
+/* ── Loading and fallback ── */
+.ds-loading {
+ position: absolute;
+ left: 50%;
+ bottom: 56px;
+ transform: translateX(-50%);
+ z-index: 12;
+ pointer-events: none;
+}
+.ds-loading[hidden],
+.ds-fallback[hidden],
+.ds-toast[hidden],
+.ds-rec[hidden] {
+ display: none;
+}
+.ds-loading-card {
+ min-width: min(360px, 82vw);
+ padding: 12px 16px;
+ border: 1px solid var(--ds-border);
+ border-radius: var(--ds-radius);
+ background: var(--ds-panel);
+ backdrop-filter: blur(16px);
+ color: #eef4ff;
+}
+.ds-loading-label {
+ font-size: 13px;
+ margin-bottom: 8px;
+}
+.ds-bar {
+ height: 4px;
+ border-radius: 4px;
+ background: rgba(255, 255, 255, 0.12);
+ overflow: hidden;
+}
+.ds-bar-fill {
+ height: 100%;
+ width: 100%;
+ transform-origin: left center;
+ background: linear-gradient(90deg, var(--ds-accent), var(--ds-accent-2));
+ transition: transform 0.18s linear;
+}
+.ds-bar-fill.is-indeterminate {
+ animation: ds-slide 1.1s ease-in-out infinite;
+}
+@keyframes ds-slide {
+ 50% {
+ transform: scaleX(0.45) translateX(120%);
+ }
+}
+.ds-fallback {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ align-content: center;
+ justify-items: center;
+ gap: 14px;
+ padding: 24px;
+ text-align: center;
+ z-index: 15;
+}
+.ds-fallback h2 {
+ margin: 0;
+ font: 700 26px/1.2 var(--font-display, system-ui, sans-serif);
+}
+.ds-fallback p {
+ margin: 0;
+ max-width: 480px;
+ color: var(--ds-muted);
+ line-height: 1.55;
+}
+
+/* ── Dock ── */
+.ds-dock {
+ position: absolute;
+ right: clamp(10px, 2vw, 24px);
+ top: clamp(64px, 9vh, 90px);
+ bottom: clamp(10px, 2vw, 24px);
+ width: 316px;
+ overflow-y: auto;
+ padding: 14px 16px 12px;
+ border: 1px solid var(--ds-border);
+ border-radius: 18px;
+ background: var(--ds-panel);
+ backdrop-filter: blur(18px) saturate(1.3);
+ z-index: 10;
+ scrollbar-width: thin;
+ transition: transform 0.28s ease, opacity 0.28s ease;
+}
+.ds-dock.is-closed {
+ transform: translateX(calc(100% + 32px));
+ opacity: 0;
+ pointer-events: none;
+}
+.ds-dock[hidden] {
+ display: none;
+}
+.ds-sec {
+ padding: 10px 0 12px;
+ border-bottom: 1px solid var(--ds-border);
+}
+.ds-sec:last-of-type {
+ border-bottom: 0;
+}
+.ds-sec h2 {
+ margin: 0 0 9px;
+ font: 700 11px/1 var(--font-mono, ui-monospace, monospace);
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: var(--ds-muted);
+}
+.ds-slot {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ margin-bottom: 8px;
+}
+.ds-slot-tag {
+ flex: none;
+ width: 22px;
+ height: 22px;
+ margin-top: 2px;
+ border-radius: 7px;
+ display: grid;
+ place-items: center;
+ font: 700 11px/1 var(--font-mono, ui-monospace, monospace);
+ background: var(--ds-accent);
+ color: #04141f;
+}
+.ds-slot-tag--b {
+ background: var(--ds-accent-2);
+ color: #12072e;
+}
+.ds-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 5px;
+ min-width: 0;
+}
+.ds-chip-btn,
+.ds-btn,
+.ds-tool {
+ font: 600 12px/1 var(--font-body, system-ui, sans-serif);
+ color: var(--ds-ink);
+ background: var(--ds-surface);
+ border: 1px solid var(--ds-border);
+ border-radius: 9px;
+ padding: 7px 10px;
+ cursor: pointer;
+ transition: background 0.14s ease, border-color 0.14s ease, transform 0.1s ease;
+}
+.ds-chip-btn:hover,
+.ds-btn:hover,
+.ds-tool:hover {
+ background: var(--ds-surface-hover);
+ border-color: var(--ds-border-strong);
+}
+.ds-chip-btn:active,
+.ds-btn:active,
+.ds-tool:active {
+ transform: scale(0.97);
+}
+.ds-chip-btn:focus-visible,
+.ds-btn:focus-visible,
+.ds-tool:focus-visible,
+.ds-dock-toggle:focus-visible,
+.ds-url input:focus-visible,
+.ds-select select:focus-visible,
+.ds-range input:focus-visible,
+.ds-slider input:focus-visible {
+ outline: 2px solid var(--ds-accent);
+ outline-offset: 2px;
+}
+.ds-chip-btn[aria-checked='true'],
+.ds-tool[aria-checked='true'],
+.ds-toggle[aria-pressed='true'] {
+ background: color-mix(in srgb, var(--ds-accent) 22%, transparent);
+ border-color: var(--ds-accent);
+}
+.ds-chip-btn[hidden] {
+ display: none;
+}
+.ds-btn--primary {
+ background: linear-gradient(120deg, var(--ds-accent), var(--ds-accent-2));
+ color: #04141f;
+ border-color: transparent;
+}
+.ds-btn--primary:hover {
+ filter: brightness(1.1);
+ background: linear-gradient(120deg, var(--ds-accent), var(--ds-accent-2));
+}
+.ds-btn:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+.ds-row {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-top: 8px;
+}
+.ds-url {
+ display: flex;
+ gap: 6px;
+ margin-top: 8px;
+}
+.ds-url input,
+.ds-select select {
+ flex: 1;
+ min-width: 0;
+ font: 500 12px/1 var(--font-body, system-ui, sans-serif);
+ color: var(--ds-ink);
+ background: var(--ds-surface);
+ border: 1px solid var(--ds-border);
+ border-radius: 9px;
+ padding: 8px 10px;
+}
+.ds-tools {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 6px;
+}
+.ds-tool {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 9px 10px;
+ text-align: left;
+}
+.ds-tool kbd {
+ font: 700 10px/1 var(--font-mono, ui-monospace, monospace);
+ padding: 3px 5px;
+ border-radius: 5px;
+ background: rgba(255, 255, 255, 0.1);
+ color: var(--ds-muted);
+}
+.ds-hint {
+ margin: 8px 0 0;
+ min-height: 32px;
+ font-size: 12px;
+ line-height: 1.4;
+ color: var(--ds-muted);
+}
+.ds-range,
+.ds-slider,
+.ds-select {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin-top: 10px;
+ font-size: 12px;
+ color: var(--ds-muted);
+}
+.ds-slider span,
+.ds-select span {
+ width: 52px;
+ flex: none;
+}
+.ds-range input,
+.ds-slider input {
+ flex: 1;
+ min-width: 0;
+ accent-color: var(--ds-accent);
+}
+.ds-keys {
+ margin: 4px 0 0;
+ font-size: 11px;
+ line-height: 1.5;
+ color: var(--ds-muted);
+}
+.ds-sr {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ white-space: nowrap;
+}
+.ds-dock-toggle {
+ position: absolute;
+ right: clamp(10px, 2vw, 24px);
+ bottom: clamp(10px, 2vw, 24px);
+ z-index: 11;
+ display: none;
+ padding: 11px 16px;
+ border: 1px solid var(--ds-border-strong);
+ border-radius: 999px;
+ background: var(--ds-panel);
+ backdrop-filter: blur(14px);
+ color: var(--ds-ink);
+ font: 700 13px/1 var(--font-body, system-ui, sans-serif);
+ cursor: pointer;
+}
+
+/* ── Toast and recording ── */
+.ds-toast {
+ position: absolute;
+ left: 50%;
+ bottom: 18px;
+ transform: translateX(-50%);
+ z-index: 25;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ max-width: min(560px, 92vw);
+ padding: 11px 16px;
+ border: 1px solid var(--ds-border-strong);
+ border-radius: 12px;
+ background: rgba(8, 12, 22, 0.92);
+ backdrop-filter: blur(14px);
+ color: #eef4ff;
+ font-size: 13px;
+ line-height: 1.4;
+}
+.ds-toast-action {
+ flex: none;
+ border: 0;
+ border-radius: 8px;
+ padding: 7px 10px;
+ background: var(--ds-accent);
+ color: #04141f;
+ font: 700 12px/1 var(--font-body, system-ui, sans-serif);
+ cursor: pointer;
+}
+.ds-rec {
+ position: absolute;
+ left: 50%;
+ top: 70px;
+ transform: translateX(-50%);
+ z-index: 12;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 12px;
+ border-radius: 999px;
+ background: rgba(8, 12, 22, 0.8);
+ border: 1px solid var(--ds-danger);
+ font: 700 12px/1 var(--font-mono, ui-monospace, monospace);
+ color: #fff;
+}
+.ds-rec-dot {
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ background: var(--ds-danger);
+ animation: ds-pulse 1s ease-in-out infinite;
+}
+
+/* ── Small screens: the dock becomes a bottom sheet ── */
+@media (max-width: 760px) {
+ .ds-dock-toggle {
+ display: block;
+ }
+ .ds-dock {
+ left: 10px;
+ right: 10px;
+ top: auto;
+ bottom: 64px;
+ width: auto;
+ max-height: 52vh;
+ }
+ .ds-dock.is-closed {
+ transform: translateY(calc(100% + 80px));
+ }
+ .ds-hero {
+ max-width: 80vw;
+ top: 70px;
+ }
+ .ds-hero p {
+ font-size: 13px;
+ }
+ .ds-loading {
+ bottom: 72px;
+ }
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .ds-chip-dot,
+ .ds-rec-dot,
+ .ds-bar-fill.is-indeterminate {
+ animation: none;
+ }
+ .ds-dock,
+ .ds-hero {
+ transition: none;
+ }
+}
diff --git a/scripts/dissolve-smoke.mjs b/scripts/dissolve-smoke.mjs
new file mode 100644
index 000000000..8896d3233
--- /dev/null
+++ b/scripts/dissolve-smoke.mjs
@@ -0,0 +1,16 @@
+// Smoke-drives /dissolve in headless Chromium: logs console errors and saves a screenshot.
+import { chromium } from 'playwright';
+
+const out = process.argv[2] || 'dissolve.png';
+const browser = await chromium.launch({ args: ['--use-gl=angle', '--use-angle=swiftshader', '--enable-unsafe-swiftshader', '--ignore-gpu-blocklist'] });
+const page = await browser.newPage({ viewport: { width: 1360, height: 820 } });
+page.on('console', (m) => ['error', 'warning'].includes(m.type()) && console.log(m.type(), m.text()));
+page.on('pageerror', (e) => console.log('pageerror', e.message));
+await page.goto('http://localhost:3000/dissolve?q=lite', { waitUntil: 'load' });
+await page.waitForFunction(() => window.__dissolve?.engine?.shapes?.A && window.__dissolve.engine.shapes.B, null, { timeout: 90000 }).catch((e) => console.log('timeout', e.message));
+await page.waitForTimeout(2500);
+await page.screenshot({ path: out });
+await page.click('#dsMorph');
+await page.waitForTimeout(5000);
+await page.screenshot({ path: out.replace('.png', '-b.png') });
+await browser.close();
diff --git a/src/dissolve/audio.js b/src/dissolve/audio.js
new file mode 100644
index 000000000..a218791e3
--- /dev/null
+++ b/src/dissolve/audio.js
@@ -0,0 +1,87 @@
+// Microphone to three smoothed energy levels (bass, mid, treble) that pump the
+// particle storm. The mic is opt-in, nothing is recorded and nothing leaves the
+// page: the analyser reads frequency bins and the page keeps only the numbers.
+
+/**
+ * Mean energy, 0..1, of the bins between two frequencies.
+ * `bins` is an analyser byte spectrum (0..255 per bin).
+ */
+export function bandLevel(bins, sampleRate, lowHz, highHz) {
+ if (!bins || bins.length === 0) return 0;
+ const hzPerBin = sampleRate / 2 / bins.length;
+ const from = Math.max(0, Math.floor(lowHz / hzPerBin));
+ const to = Math.min(bins.length - 1, Math.max(from, Math.ceil(highHz / hzPerBin)));
+ let sum = 0;
+ for (let i = from; i <= to; i++) sum += bins[i];
+ return sum / ((to - from + 1) * 255);
+}
+
+/** Bass, mid and treble for one spectrum. */
+export function bandLevels(bins, sampleRate) {
+ return {
+ bass: bandLevel(bins, sampleRate, 20, 160),
+ mid: bandLevel(bins, sampleRate, 160, 2000),
+ treble: bandLevel(bins, sampleRate, 2000, 9000),
+ };
+}
+
+/** One-pole smoother: fast attack so a kick lands, slow release so it breathes. */
+export function smoothLevel(previous, next, attack = 0.55, release = 0.12) {
+ const k = next > previous ? attack : release;
+ return previous + (next - previous) * k;
+}
+
+export class MicLevels {
+ constructor() {
+ this.levels = { bass: 0, mid: 0, treble: 0 };
+ this.active = false;
+ this._ctx = null;
+ this._stream = null;
+ this._analyser = null;
+ this._bins = null;
+ }
+
+ static isSupported() {
+ return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia && (window.AudioContext || window.webkitAudioContext));
+ }
+
+ /** Resolves once the mic is live. Rejects with the browser's own error. */
+ async start() {
+ if (this.active) return;
+ const stream = await navigator.mediaDevices.getUserMedia({
+ audio: { echoCancellation: false, noiseSuppression: false, autoGainControl: false },
+ });
+ const Ctx = window.AudioContext || window.webkitAudioContext;
+ const ctx = new Ctx();
+ const source = ctx.createMediaStreamSource(stream);
+ const analyser = ctx.createAnalyser();
+ analyser.fftSize = 1024;
+ analyser.smoothingTimeConstant = 0.6;
+ source.connect(analyser);
+ this._ctx = ctx;
+ this._stream = stream;
+ this._analyser = analyser;
+ this._bins = new Uint8Array(analyser.frequencyBinCount);
+ this.active = true;
+ }
+
+ /** Read the spectrum and update the smoothed levels. Call once per frame. */
+ sample() {
+ if (!this.active) return this.levels;
+ this._analyser.getByteFrequencyData(this._bins);
+ const raw = bandLevels(this._bins, this._ctx.sampleRate);
+ for (const key of ['bass', 'mid', 'treble']) {
+ this.levels[key] = smoothLevel(this.levels[key], raw[key]);
+ }
+ return this.levels;
+ }
+
+ stop() {
+ if (!this.active) return;
+ this.active = false;
+ for (const track of this._stream.getTracks()) track.stop();
+ this._ctx.close();
+ this._ctx = this._stream = this._analyser = this._bins = null;
+ this.levels = { bass: 0, mid: 0, treble: 0 };
+ }
+}
diff --git a/src/dissolve/engine.js b/src/dissolve/engine.js
new file mode 100644
index 000000000..19a9a1145
--- /dev/null
+++ b/src/dissolve/engine.js
@@ -0,0 +1,572 @@
+// The GPU particle engine behind /dissolve.
+//
+// Every particle lives in a texel of two float textures (position, velocity).
+// Each frame two fullscreen passes advance them (velocity, then position), and
+// a Points draw reads the result straight from those textures, so a million
+// particles never touch the CPU after the shapes are uploaded.
+//
+// Shapes arrive as ShapeClouds (src/dissolve/shape.js). Each one is Morton
+// sorted over the shared stage box so particle i of shape A and particle i of
+// shape B sit in the same relative place; a morph then moves feet to feet and
+// head to head, with a per-particle stagger that turns the blend into a ripple.
+
+import * as THREE from 'three';
+import { mortonOrder, mulberry32 } from './sample-core.js';
+
+export const STAGE_MIN = [-1.6, -1, -1.6];
+export const STAGE_MAX = [1.6, 1, 1.6];
+const MAX_WAVES = 4;
+
+export const TOOL = { none: 0, gravity: 1, vortex: 2 };
+
+export const DEFAULT_PARAMS = {
+ spring: 16,
+ damp: 5.2,
+ turb: 0.35,
+ arc: 0.6,
+ stagger: 0.7,
+ size: 1,
+ bright: 0.55,
+ gravity: 0,
+};
+
+const FULLSCREEN_VERT = /* glsl */ `
+ void main() { gl_Position = vec4(position.xy, 0.0, 1.0); }
+`;
+
+const COMMON_GLSL = /* glsl */ `
+ float hash11(float n) { return fract(sin(n) * 43758.5453123); }
+ // Per-particle morph progress: the stagger makes the blend a ripple instead
+ // of one flat cross-fade.
+ float progressFor(float mixv, float stagger, float seed) {
+ float p = clamp(mixv * (1.0 + stagger) - stagger * seed, 0.0, 1.0);
+ return p * p * (3.0 - 2.0 * p);
+ }
+`;
+
+const VELOCITY_FRAG = /* glsl */ `
+ uniform vec2 uRes;
+ uniform sampler2D tPos, tVel, tA, tB;
+ uniform float uDt, uTime, uMix, uStagger, uSpring, uDamp, uTurb, uGravity, uFloor, uBass, uMid, uArc;
+ uniform vec4 uAttr; // xyz world point, w strength
+ uniform float uMode; // 0 off, 1 gravity well, 2 vortex
+ uniform vec3 uAxis; // camera forward: spin axis for the well, jet axis
+ uniform vec4 uWave[${MAX_WAVES}]; // xyz centre, w birth time (negative = unused)
+ uniform float uWaveStrength;
+ ${COMMON_GLSL}
+
+ // Divergence-free flow: the curl of a sum of sine potentials. Particles swirl
+ // without bunching up or thinning out, which is what makes it read as fluid.
+ vec3 flow(vec3 p, float t) {
+ vec3 q = p * 1.35;
+ vec3 c1 = vec3(-cos(q.z * 1.0 + t * 1.1), -cos(q.x * 1.0 + t * 0.9), -cos(q.y * 1.0 + t * 1.0));
+ vec3 r = p * 2.6 + vec3(1.7, 9.2, 3.1);
+ vec3 c2 = vec3(-cos(r.y * 1.0 - t * 0.7), -cos(r.z * 1.0 + t * 1.3), -cos(r.x * 1.0 - t * 0.5));
+ return c1 + 0.5 * c2;
+ }
+
+ void main() {
+ vec2 uv = gl_FragCoord.xy / uRes;
+ vec4 pp = texture2D(tPos, uv);
+ vec4 vv = texture2D(tVel, uv);
+ vec3 pos = pp.xyz;
+ vec3 vel = vv.xyz;
+ vec4 a = texture2D(tA, uv);
+ vec4 b = texture2D(tB, uv);
+ float seed = a.w;
+
+ float prog = progressFor(uMix, uStagger, seed);
+ vec3 tgt = mix(a.xyz, b.xyz, prog);
+ float flight = sin(3.14159265 * prog);
+ vec3 travel = b.xyz - a.xyz;
+ vec3 side = cross(travel, vec3(0.0, 1.0, 0.0));
+ side = side / (length(side) + 1e-4);
+ tgt += side * flight * uArc * (seed - 0.5) * 1.4 * length(travel) * 0.5;
+ tgt.y += flight * uArc * (hash11(seed * 91.7) - 0.25) * 0.9;
+ tgt += tgt * uBass * 0.22;
+
+ vec3 acc = uSpring * (tgt - pos);
+ acc += flow(pos, uTime * 0.6) * (uTurb + uMid * 5.0) * 3.0;
+ acc -= uDamp * vel;
+ acc.y -= uGravity;
+
+ if (uMode > 0.5 && uAttr.w > 0.0) {
+ vec3 d = uAttr.xyz - pos;
+ if (uMode < 1.5) {
+ float r2 = dot(d, d) + 0.02;
+ float inv = inversesqrt(r2);
+ vec3 dir = d * inv;
+ float pull = min(uAttr.w * 3.2 / r2, 140.0);
+ acc += dir * pull;
+ acc += cross(uAxis, dir) * min(uAttr.w * 5.0 / (r2 + 0.08), 60.0);
+ acc -= uSpring * (tgt - pos) * clamp(uAttr.w * 0.8, 0.0, 0.92);
+ if (r2 < 0.014) {
+ // Past the horizon: thrown out along the spin axis as a relativistic jet.
+ float sgn = hash11(pos.x * 13.1 + pos.y * 7.7 + pos.z * 3.3 + uTime) > 0.5 ? 1.0 : -1.0;
+ float spd = 5.0 + 7.0 * hash11(pos.z * 17.3 + uTime * 1.7);
+ vel = uAxis * sgn * spd + flow(pos * 3.0, uTime) * 0.8;
+ gl_FragColor = vec4(vel, 1.0);
+ return;
+ }
+ } else {
+ vec3 rel = pos - uAttr.xyz;
+ float rr = length(rel.xz);
+ float fall = exp(-rr * rr / 1.6);
+ acc += vec3(-rel.z, 0.0, rel.x) / (rr + 0.25) * fall * uAttr.w * 34.0;
+ acc.y += fall * uAttr.w * 9.0;
+ acc -= uSpring * (tgt - pos) * fall * 0.85;
+ }
+ }
+
+ for (int i = 0; i < ${MAX_WAVES}; i++) {
+ vec4 w = uWave[i];
+ if (w.w < 0.0) continue;
+ float age = uTime - w.w;
+ if (age < 0.0 || age > 3.5) continue;
+ vec3 dd = pos - w.xyz;
+ float r = length(dd) + 1e-4;
+ float band = exp(-pow((r - age * 3.4) / 0.3, 2.0));
+ float fade = 1.0 - age / 3.5;
+ acc += dd / r * band * fade * uWaveStrength * 90.0;
+ acc.y += band * fade * uWaveStrength * 14.0;
+ acc -= uSpring * (tgt - pos) * band * 0.9;
+ }
+
+ vel += acc * uDt;
+ if (uGravity > 0.0 && pos.y <= uFloor + 0.002 && vel.y < 0.0) {
+ vel.y = -vel.y * 0.46;
+ vel.xz *= 0.9;
+ }
+ float sp = length(vel);
+ if (sp > 16.0) vel *= 16.0 / sp;
+ float heat = max(vv.w * exp(-uDt * 2.2), min(sp / 7.0, 1.0));
+ gl_FragColor = vec4(vel, heat);
+ }
+`;
+
+const POSITION_FRAG = /* glsl */ `
+ uniform vec2 uRes;
+ uniform sampler2D tPos, tVel;
+ uniform float uDt, uGravity, uFloor;
+ void main() {
+ vec2 uv = gl_FragCoord.xy / uRes;
+ vec4 p = texture2D(tPos, uv);
+ vec4 v = texture2D(tVel, uv);
+ p.xyz += v.xyz * uDt;
+ if (uGravity > 0.0 && p.y < uFloor) p.y = uFloor;
+ gl_FragColor = p;
+ }
+`;
+
+const POINT_VERT = /* glsl */ `
+ attribute vec2 ref;
+ uniform sampler2D tPos, tVel, tA, cA, cB;
+ uniform float uMix, uStagger, uSize, uPx, uBright, uFloor, uMirror;
+ varying vec3 vColor;
+ varying float vFade;
+ ${COMMON_GLSL}
+ void main() {
+ vec4 p = texture2D(tPos, ref);
+ vec4 v = texture2D(tVel, ref);
+ float seed = texture2D(tA, ref).w;
+ float prog = progressFor(uMix, uStagger, seed);
+ vec3 col = mix(texture2D(cA, ref).rgb, texture2D(cB, ref).rgb, prog);
+ col = pow(max(col, vec3(0.0)), vec3(0.8)) + 0.035;
+ float heat = clamp(v.w, 0.0, 1.0);
+ col = mix(col, vec3(0.35, 0.8, 1.6), heat * 0.55) * (1.0 + heat * 2.2);
+ vec3 world = p.xyz;
+ vFade = 1.0;
+ if (uMirror > 0.5) {
+ world.y = 2.0 * uFloor - world.y;
+ vFade = 0.22 * clamp(1.0 - (uFloor - world.y) * 0.45, 0.0, 1.0);
+ }
+ vColor = col * uBright * 0.16 * vFade;
+ vec4 mv = viewMatrix * vec4(world, 1.0);
+ gl_Position = projectionMatrix * mv;
+ gl_PointSize = max(1.0, uSize * uPx * (0.55 + 0.9 * fract(seed * 7.13)) * (1.0 + heat * 0.8) / -mv.z);
+ }
+`;
+
+const POINT_FRAG = /* glsl */ `
+ varying vec3 vColor;
+ varying float vFade;
+ void main() {
+ vec2 c = gl_PointCoord - 0.5;
+ float a = exp(-dot(c, c) * 20.0);
+ if (a < 0.03 || vFade <= 0.0) discard;
+ gl_FragColor = vec4(vColor, a);
+ }
+`;
+
+/** Probe the one capability the engine cannot run without. */
+export function probeSupport() {
+ const canvas = document.createElement('canvas');
+ const gl = canvas.getContext('webgl2');
+ if (!gl) return { ok: false, reason: 'webgl2' };
+ const float = !!gl.getExtension('EXT_color_buffer_float');
+ const half = !!gl.getExtension('EXT_color_buffer_half_float') || float;
+ const lose = gl.getExtension('WEBGL_lose_context');
+ if (lose) lose.loseContext();
+ if (!half) return { ok: false, reason: 'float-targets' };
+ return { ok: true, float };
+}
+
+export class DissolveEngine {
+ /**
+ * @param {THREE.WebGLRenderer} renderer shared with the page's composer
+ * @param {number} side texture side; particle count is side * side
+ */
+ constructor(renderer, side) {
+ this.renderer = renderer;
+ this.side = side;
+ this.count = side * side;
+ this.time = 0;
+ this.params = { ...DEFAULT_PARAMS };
+ this.mix = 0;
+ this.audio = { bass: 0, mid: 0 };
+ this.pointer = { mode: TOOL.none, strength: 0, point: new THREE.Vector3(), axis: new THREE.Vector3(0, 0, -1) };
+ this.waves = Array.from({ length: MAX_WAVES }, () => new THREE.Vector4(0, 0, 0, -1));
+ this.waveHead = 0;
+ this.waveStrength = 1;
+ this.springDip = 0;
+ this.floorY = -1;
+
+ const useFloat = renderer.extensions.has('EXT_color_buffer_float');
+ this.stateType = useFloat ? THREE.FloatType : THREE.HalfFloatType;
+
+ const makeTarget = () =>
+ new THREE.WebGLRenderTarget(side, side, {
+ type: this.stateType,
+ format: THREE.RGBAFormat,
+ minFilter: THREE.NearestFilter,
+ magFilter: THREE.NearestFilter,
+ depthBuffer: false,
+ stencilBuffer: false,
+ generateMipmaps: false,
+ });
+ this.pos = [makeTarget(), makeTarget()];
+ this.vel = [makeTarget(), makeTarget()];
+ this.flip = 0;
+
+ this.shapes = { A: null, B: null };
+ this.textures = {
+ posA: this._dataTexture(),
+ posB: this._dataTexture(),
+ colA: this._dataTexture(),
+ colB: this._dataTexture(),
+ };
+
+ this._buildSimulation();
+ this._buildPoints();
+ this._seedState();
+ }
+
+ _dataTexture() {
+ const t = new THREE.DataTexture(new Float32Array(this.count * 4), this.side, this.side, THREE.RGBAFormat, THREE.FloatType);
+ t.minFilter = THREE.NearestFilter;
+ t.magFilter = THREE.NearestFilter;
+ t.generateMipmaps = false;
+ t.needsUpdate = true;
+ return t;
+ }
+
+ _buildSimulation() {
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.BufferAttribute(new Float32Array([-1, -1, 0, 3, -1, 0, -1, 3, 0]), 3));
+ this.simCamera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
+ this.simScene = new THREE.Scene();
+ const res = new THREE.Vector2(this.side, this.side);
+ const shared = {
+ uRes: { value: res },
+ uDt: { value: 1 / 60 },
+ uGravity: { value: 0 },
+ uFloor: { value: this.floorY },
+ };
+ this.velMaterial = new THREE.ShaderMaterial({
+ vertexShader: FULLSCREEN_VERT,
+ fragmentShader: VELOCITY_FRAG,
+ depthTest: false,
+ depthWrite: false,
+ uniforms: {
+ ...shared,
+ tPos: { value: null },
+ tVel: { value: null },
+ tA: { value: this.textures.posA },
+ tB: { value: this.textures.posB },
+ uTime: { value: 0 },
+ uMix: { value: 0 },
+ uStagger: { value: this.params.stagger },
+ uSpring: { value: this.params.spring },
+ uDamp: { value: this.params.damp },
+ uTurb: { value: this.params.turb },
+ uArc: { value: this.params.arc },
+ uBass: { value: 0 },
+ uMid: { value: 0 },
+ uAttr: { value: new THREE.Vector4() },
+ uMode: { value: 0 },
+ uAxis: { value: new THREE.Vector3(0, 0, -1) },
+ uWave: { value: this.waves },
+ uWaveStrength: { value: 1 },
+ },
+ });
+ this.posMaterial = new THREE.ShaderMaterial({
+ vertexShader: FULLSCREEN_VERT,
+ fragmentShader: POSITION_FRAG,
+ depthTest: false,
+ depthWrite: false,
+ uniforms: { ...shared, tPos: { value: null }, tVel: { value: null } },
+ });
+ this.simMesh = new THREE.Mesh(geometry, this.velMaterial);
+ this.simMesh.frustumCulled = false;
+ this.simScene.add(this.simMesh);
+ }
+
+ _buildPoints() {
+ const refs = new Float32Array(this.count * 2);
+ const positions = new Float32Array(this.count * 3);
+ for (let y = 0; y < this.side; y++) {
+ for (let x = 0; x < this.side; x++) {
+ const i = y * this.side + x;
+ refs[i * 2] = (x + 0.5) / this.side;
+ refs[i * 2 + 1] = (y + 0.5) / this.side;
+ }
+ }
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
+ geometry.setAttribute('ref', new THREE.BufferAttribute(refs, 2));
+ const make = (mirror) =>
+ new THREE.ShaderMaterial({
+ vertexShader: POINT_VERT,
+ fragmentShader: POINT_FRAG,
+ transparent: true,
+ depthWrite: false,
+ depthTest: false,
+ blending: THREE.AdditiveBlending,
+ uniforms: {
+ tPos: { value: null },
+ tVel: { value: null },
+ tA: { value: this.textures.posA },
+ cA: { value: this.textures.colA },
+ cB: { value: this.textures.colB },
+ uMix: { value: 0 },
+ uStagger: { value: this.params.stagger },
+ uSize: { value: 0.012 },
+ uPx: { value: 1000 },
+ uBright: { value: this.params.bright },
+ uFloor: { value: this.floorY },
+ uMirror: { value: mirror ? 1 : 0 },
+ },
+ });
+ this.pointMaterial = make(false);
+ this.mirrorMaterial = make(true);
+ this.points = new THREE.Points(geometry, this.pointMaterial);
+ this.mirror = new THREE.Points(geometry, this.mirrorMaterial);
+ for (const p of [this.points, this.mirror]) p.frustumCulled = false;
+ this.group = new THREE.Group();
+ this.group.add(this.mirror, this.points);
+ }
+
+ /** Born from a loose shell, so the first shape materialises out of a cloud. */
+ _seedState() {
+ const rng = mulberry32(1337);
+ const pos = new Float32Array(this.count * 4);
+ for (let i = 0; i < this.count; i++) {
+ const u = rng() * 2 - 1;
+ const th = rng() * Math.PI * 2;
+ const r = 2.2 + rng() * 2.6;
+ const s = Math.sqrt(1 - u * u);
+ pos[i * 4] = Math.cos(th) * s * r;
+ pos[i * 4 + 1] = u * r * 0.7;
+ pos[i * 4 + 2] = Math.sin(th) * s * r;
+ pos[i * 4 + 3] = 0;
+ }
+ const seed = new THREE.DataTexture(pos, this.side, this.side, THREE.RGBAFormat, THREE.FloatType);
+ seed.minFilter = THREE.NearestFilter;
+ seed.magFilter = THREE.NearestFilter;
+ seed.needsUpdate = true;
+ this._blit(seed, this.pos[0]);
+ this._blit(seed, this.pos[1]);
+ seed.dispose();
+ const zero = new THREE.DataTexture(new Float32Array(this.count * 4), this.side, this.side, THREE.RGBAFormat, THREE.FloatType);
+ zero.minFilter = THREE.NearestFilter;
+ zero.magFilter = THREE.NearestFilter;
+ zero.needsUpdate = true;
+ this._blit(zero, this.vel[0]);
+ this._blit(zero, this.vel[1]);
+ zero.dispose();
+ }
+
+ _blit(texture, target) {
+ const material = new THREE.ShaderMaterial({
+ vertexShader: FULLSCREEN_VERT,
+ fragmentShader: /* glsl */ `
+ uniform sampler2D tSrc;
+ uniform vec2 uRes;
+ void main() { gl_FragColor = texture2D(tSrc, gl_FragCoord.xy / uRes); }
+ `,
+ uniforms: { tSrc: { value: texture }, uRes: { value: new THREE.Vector2(this.side, this.side) } },
+ depthTest: false,
+ depthWrite: false,
+ });
+ const previous = this.simMesh.material;
+ this.simMesh.material = material;
+ this._pass(target);
+ this.simMesh.material = previous;
+ material.dispose();
+ }
+
+ _pass(target) {
+ const r = this.renderer;
+ const prevTarget = r.getRenderTarget();
+ const prevAuto = r.autoClear;
+ r.autoClear = false;
+ r.setRenderTarget(target);
+ r.render(this.simScene, this.simCamera);
+ r.setRenderTarget(prevTarget);
+ r.autoClear = prevAuto;
+ }
+
+ /**
+ * Upload a ShapeCloud into slot 'A' or 'B'. Both slots are Morton sorted over
+ * the same stage box, which is what pairs their particles spatially.
+ */
+ setShape(slot, cloud) {
+ if (cloud.count !== this.count) throw new RangeError('Cloud size does not match the engine.');
+ const order = mortonOrder(cloud.positions, cloud.count, STAGE_MIN, STAGE_MAX);
+ const posTex = slot === 'A' ? this.textures.posA : this.textures.posB;
+ const colTex = slot === 'A' ? this.textures.colA : this.textures.colB;
+ const pos = posTex.image.data;
+ const col = colTex.image.data;
+ const rng = mulberry32(slot === 'A' ? 9001 : 4242);
+ for (let rank = 0; rank < this.count; rank++) {
+ const src = order[rank];
+ pos[rank * 4] = cloud.positions[src * 3];
+ pos[rank * 4 + 1] = cloud.positions[src * 3 + 1];
+ pos[rank * 4 + 2] = cloud.positions[src * 3 + 2];
+ // The seed rides in A's alpha only; the stagger reads it from there.
+ pos[rank * 4 + 3] = slot === 'A' ? rng() : 0;
+ col[rank * 4] = cloud.colors[src * 3];
+ col[rank * 4 + 1] = cloud.colors[src * 3 + 1];
+ col[rank * 4 + 2] = cloud.colors[src * 3 + 2];
+ col[rank * 4 + 3] = 1;
+ }
+ posTex.needsUpdate = true;
+ colTex.needsUpdate = true;
+ this.shapes[slot] = cloud;
+ if (slot === 'A' && !this.shapes.B) this._mirrorIntoB(posTex, colTex);
+ }
+
+ /** Until B is chosen, B is a copy of A so the slider never reveals an empty target. */
+ _mirrorIntoB() {
+ this.textures.posB.image.data.set(this.textures.posA.image.data);
+ this.textures.colB.image.data.set(this.textures.colA.image.data);
+ this.textures.posB.needsUpdate = true;
+ this.textures.colB.needsUpdate = true;
+ }
+
+ /** Swap which shape is A and which is B, and flip the blend to match. */
+ swap() {
+ const { posA, posB, colA, colB } = this.textures;
+ const seeds = new Float32Array(this.count);
+ const a = posA.image.data;
+ const b = posB.image.data;
+ for (let i = 0; i < this.count; i++) seeds[i] = a[i * 4 + 3];
+ const tmp = new Float32Array(a);
+ a.set(b);
+ b.set(tmp);
+ for (let i = 0; i < this.count; i++) {
+ a[i * 4 + 3] = seeds[i];
+ b[i * 4 + 3] = 0;
+ }
+ const tc = new Float32Array(colA.image.data);
+ colA.image.data.set(colB.image.data);
+ colB.image.data.set(tc);
+ for (const t of [posA, posB, colA, colB]) t.needsUpdate = true;
+ [this.shapes.A, this.shapes.B] = [this.shapes.B, this.shapes.A];
+ this.mix = 1 - this.mix;
+ }
+
+ setMix(v) {
+ this.mix = Math.min(1, Math.max(0, v));
+ }
+
+ setParam(name, value) {
+ this.params[name] = value;
+ }
+
+ /** Fire a shockwave from a world point. */
+ shockwave(point, strength = 1) {
+ this.waves[this.waveHead].set(point.x, point.y, point.z, this.time);
+ this.waveHead = (this.waveHead + 1) % MAX_WAVES;
+ this.waveStrength = strength;
+ this.springDip = 0.35;
+ }
+
+ /** Advance the simulation by `dt` seconds (clamped for stability). */
+ step(dt) {
+ const d = Math.min(dt, 1 / 30);
+ this.time += d;
+ this.springDip = Math.max(0, this.springDip - d);
+
+ const v = this.velMaterial.uniforms;
+ const dip = this.springDip > 0 ? 0.25 : 1;
+ const collapsed = this.params.gravity > 0;
+ v.uDt.value = d;
+ v.uTime.value = this.time;
+ v.uMix.value = this.mix;
+ v.uStagger.value = this.params.stagger;
+ v.uSpring.value = collapsed ? 0 : this.params.spring * dip;
+ v.uDamp.value = collapsed ? 0.35 : this.params.damp;
+ v.uTurb.value = this.params.turb;
+ v.uArc.value = this.params.arc;
+ v.uGravity.value = this.params.gravity;
+ v.uBass.value = this.audio.bass;
+ v.uMid.value = this.audio.mid;
+ v.uMode.value = this.pointer.mode;
+ v.uAttr.value.set(this.pointer.point.x, this.pointer.point.y, this.pointer.point.z, this.pointer.strength);
+ v.uAxis.value.copy(this.pointer.axis);
+ v.uWaveStrength.value = this.waveStrength;
+ const p = this.posMaterial.uniforms;
+ p.uDt.value = d;
+ p.uGravity.value = this.params.gravity;
+
+ const read = this.flip;
+ const write = 1 - this.flip;
+
+ v.tPos.value = this.pos[read].texture;
+ v.tVel.value = this.vel[read].texture;
+ this.simMesh.material = this.velMaterial;
+ this._pass(this.vel[write]);
+
+ p.tPos.value = this.pos[read].texture;
+ p.tVel.value = this.vel[write].texture;
+ this.simMesh.material = this.posMaterial;
+ this._pass(this.pos[write]);
+
+ this.flip = write;
+ for (const m of [this.pointMaterial, this.mirrorMaterial]) {
+ m.uniforms.tPos.value = this.pos[this.flip].texture;
+ m.uniforms.tVel.value = this.vel[this.flip].texture;
+ m.uniforms.uMix.value = this.mix;
+ m.uniforms.uStagger.value = this.params.stagger;
+ m.uniforms.uBright.value = this.params.bright;
+ }
+ }
+
+ /** Point size in world units, plus the pixel scale for the current viewport. */
+ setView(drawingBufferHeight, fovDegrees) {
+ const px = drawingBufferHeight / (2 * Math.tan((fovDegrees * Math.PI) / 360));
+ for (const m of [this.pointMaterial, this.mirrorMaterial]) {
+ m.uniforms.uPx.value = px;
+ m.uniforms.uSize.value = 0.012 * this.params.size * (this.side >= 1024 ? 0.55 : this.side >= 512 ? 0.7 : 1.0);
+ }
+ }
+
+ dispose() {
+ for (const t of [...this.pos, ...this.vel]) t.dispose();
+ for (const t of Object.values(this.textures)) t.dispose();
+ this.points.geometry.dispose();
+ for (const m of [this.velMaterial, this.posMaterial, this.pointMaterial, this.mirrorMaterial]) m.dispose();
+ this.simMesh.geometry.dispose();
+ }
+}
diff --git a/src/dissolve/page.js b/src/dissolve/page.js
new file mode 100644
index 000000000..01e0be01c
--- /dev/null
+++ b/src/dissolve/page.js
@@ -0,0 +1,913 @@
+// /dissolve: page controller.
+//
+// Owns the renderer, camera, post-processing and the DOM. All particle physics
+// is in engine.js, all geometry maths in sample-core.js; this file wires the
+// shelf, the pointer tools, the morph timeline, the mic, capture and share
+// links to them, and decides what the person sees while something loads or
+// fails.
+
+import * as THREE from 'three';
+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
+import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';
+import { EffectComposer } from 'three/addons/postprocessing/EffectComposer.js';
+import { RenderPass } from 'three/addons/postprocessing/RenderPass.js';
+import { UnrealBloomPass } from 'three/addons/postprocessing/UnrealBloomPass.js';
+import { OutputPass } from 'three/addons/postprocessing/OutputPass.js';
+import { getMeshoptDecoder } from '../viewer/internal.js';
+import { DissolveEngine, TOOL, probeSupport } from './engine.js';
+import { buildShapeCloud } from './shape.js';
+import { MicLevels } from './audio.js';
+import { CanvasRecorder, extensionFor } from './recorder.js';
+import { SHELF, PRESETS, QUALITY, shelfEntry, parseModelUrl, readState, writeState } from './shelf.js';
+
+const FOV = 40;
+const MORPH_SECONDS = 3.4;
+const LOOP_HOLD_SECONDS = 1.2;
+const QUALITY_KEY = 'twx_dissolve_quality';
+
+const $ = (id) => document.getElementById(id);
+const el = {
+ stage: $('dsStage'),
+ canvas: $('dsCanvas'),
+ hero: $('dsHero'),
+ count: $('dsCount'),
+ loading: $('dsLoading'),
+ loadingLabel: $('dsLoadingLabel'),
+ barFill: $('dsBarFill'),
+ fallback: $('dsFallback'),
+ fallbackTitle: $('dsFallbackTitle'),
+ fallbackBody: $('dsFallbackBody'),
+ rec: $('dsRec'),
+ recTime: $('dsRecTime'),
+ dock: $('dsDock'),
+ dockToggle: $('dsDockToggle'),
+ shelfA: $('dsShelfA'),
+ shelfB: $('dsShelfB'),
+ file: $('dsFile'),
+ pickA: $('dsPickA'),
+ pickB: $('dsPickB'),
+ urlForm: $('dsUrlForm'),
+ url: $('dsUrl'),
+ morph: $('dsMorph'),
+ swap: $('dsSwap'),
+ loop: $('dsLoop'),
+ mix: $('dsMix'),
+ tools: $('dsTools'),
+ toolHint: $('dsToolHint'),
+ collapse: $('dsCollapse'),
+ detonate: $('dsDetonate'),
+ presets: $('dsPresets'),
+ size: $('dsSize'),
+ glow: $('dsGlow'),
+ chaos: $('dsChaos'),
+ orbit: $('dsOrbit'),
+ mic: $('dsMic'),
+ shot: $('dsShot'),
+ record: $('dsRecord'),
+ share: $('dsShare'),
+ quality: $('dsQuality'),
+ toast: $('dsToast'),
+};
+
+const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+const TOOL_HINTS = {
+ orbit: 'Drag to turn the camera, scroll to zoom.',
+ gravity: 'Hold and drag to open a black hole. Particles that cross the horizon leave as jets.',
+ vortex: 'Hold and drag to spin a tornado through the shape.',
+ burst: 'Click anywhere to send a shockwave through the shape.',
+};
+
+// ── State ─────────────────────────────────────────────────────────────────
+const initial = readState(location.search);
+const state = {
+ a: initial.a,
+ b: initial.b,
+ preset: initial.preset,
+ quality: initial.quality || savedQuality() || defaultQuality(),
+ tool: 'gravity',
+ bloom: PRESETS[initial.preset].bloom,
+ autoOrbit: !reducedMotion,
+ loopOn: false,
+ collapsed: false,
+ tween: null,
+ pressed: false,
+ hovering: false,
+ engine: null,
+ models: new Map(), // key -> Promise<THREE.Group>
+ loadToken: { A: 0, B: 0 },
+ busy: 0,
+ labels: { A: '', B: '' },
+ custom: { A: null, B: null },
+};
+
+function savedQuality() {
+ try {
+ const q = localStorage.getItem(QUALITY_KEY);
+ return QUALITY[q] ? q : null;
+ } catch {
+ return null;
+ }
+}
+
+function defaultQuality() {
+ const weak = (navigator.hardwareConcurrency || 4) <= 4 || window.matchMedia('(pointer: coarse)').matches;
+ return weak ? 'lite' : 'standard';
+}
+
+// ── Toasts and loading ────────────────────────────────────────────────────
+let toastTimer = 0;
+function toast(message, { action = null, ms = 5200 } = {}) {
+ clearTimeout(toastTimer);
+ el.toast.replaceChildren();
+ const text = document.createElement('span');
+ text.textContent = message;
+ el.toast.append(text);
+ if (action) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'ds-toast-action';
+ btn.textContent = action.label;
+ btn.addEventListener('click', () => {
+ el.toast.hidden = true;
+ action.run();
+ });
+ el.toast.append(btn);
+ }
+ el.toast.hidden = false;
+ toastTimer = setTimeout(() => (el.toast.hidden = true), ms);
+}
+
+function setLoading(on, label = '', progress = null) {
+ el.loading.hidden = !on;
+ if (!on) return;
+ el.loadingLabel.textContent = label;
+ el.barFill.style.transform = `scaleX(${progress == null ? 0.08 : Math.max(0.04, progress)})`;
+ el.barFill.classList.toggle('is-indeterminate', progress == null);
+}
+
+function showFallback(title, body) {
+ el.fallbackTitle.textContent = title;
+ el.fallbackBody.textContent = body;
+ el.fallback.hidden = false;
+ el.dock.hidden = true;
+ el.dockToggle.hidden = true;
+ el.hero.hidden = true;
+}
+
+// ── Renderer, scene, post ─────────────────────────────────────────────────
+const support = probeSupport();
+if (!support.ok) {
+ showFallback(
+ 'This browser cannot run Dissolve',
+ support.reason === 'webgl2'
+ ? 'Dissolve simulates its particles on the GPU and needs WebGL 2. Turn on hardware acceleration, or try a current Chrome, Edge, Firefox or Safari.'
+ : 'Your GPU cannot render to floating-point textures, which the particle simulation needs. Update your graphics driver or try another browser.',
+ );
+} else {
+ boot();
+}
+
+function boot() {
+ const renderer = new THREE.WebGLRenderer({ canvas: el.canvas, antialias: false, powerPreference: 'high-performance', alpha: false });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
+ renderer.toneMapping = THREE.ACESFilmicToneMapping;
+ renderer.toneMappingExposure = 1.0;
+ renderer.setClearColor(0x04060b, 1);
+
+ const scene = new THREE.Scene();
+ const camera = new THREE.PerspectiveCamera(FOV, 1, 0.1, 80);
+ camera.position.set(0.0, 0.5, 5.4);
+
+ const controls = new OrbitControls(camera, el.canvas);
+ controls.target.set(0, -0.1, 0);
+ controls.enableDamping = true;
+ controls.dampingFactor = 0.07;
+ controls.minDistance = 1.6;
+ controls.maxDistance = 14;
+ controls.maxPolarAngle = Math.PI * 0.62;
+ controls.autoRotateSpeed = 0.7;
+ controls.enablePan = false;
+
+ const composer = new EffectComposer(renderer);
+ composer.addPass(new RenderPass(scene, camera));
+ const bloom = new UnrealBloomPass(new THREE.Vector2(1, 1), state.bloom, 0.5, 0.3);
+ composer.addPass(bloom);
+ composer.addPass(new OutputPass());
+
+ const backdrop = buildBackdrop();
+ scene.add(backdrop.group);
+
+ const loader = new GLTFLoader();
+ const draco = new DRACOLoader();
+ draco.setDecoderPath('/three/draco/gltf/');
+ loader.setDRACOLoader(draco);
+ getMeshoptDecoder().then((d) => loader.setMeshoptDecoder(d));
+
+ const mic = new MicLevels();
+ const recorder = new CanvasRecorder(el.canvas);
+ const pointerPlane = new THREE.Plane();
+ const ray = new THREE.Raycaster();
+ const ndc = new THREE.Vector2();
+ const forward = new THREE.Vector3();
+ const hit = new THREE.Vector3();
+
+ // ── Model loading ────────────────────────────────────────────────────
+ function loadGltf(url, onProgress) {
+ return new Promise((resolve, reject) => {
+ loader.load(
+ url,
+ (gltf) => resolve(gltf.scene),
+ (e) => e.lengthComputable && onProgress(e.loaded / e.total),
+ (err) => reject(err instanceof Error ? err : new Error('The model could not be loaded.')),
+ );
+ });
+ }
+
+ function modelSource(key) {
+ const entry = shelfEntry(key);
+ if (entry) return { url: entry.url, label: entry.label };
+ const custom = state.custom.A?.key === key ? state.custom.A : state.custom.B?.key === key ? state.custom.B : null;
+ if (custom) return { url: custom.url, label: custom.label };
+ const safe = parseModelUrl(key);
+ if (safe) return { url: safe, label: safe.split('/').pop().slice(0, 28) || 'Linked model' };
+ return null;
+ }
+
+ function getModel(key, onProgress) {
+ if (!state.models.has(key)) {
+ const source = modelSource(key);
+ if (!source) return Promise.reject(new Error('That model link is not valid.'));
+ const promise = loadGltf(source.url, onProgress).catch((err) => {
+ state.models.delete(key);
+ throw err;
+ });
+ state.models.set(key, promise);
+ }
+ return state.models.get(key);
+ }
+
+ async function setSlot(slot, key) {
+ const token = ++state.loadToken[slot];
+ const source = modelSource(key);
+ const label = source ? source.label : 'model';
+ state.busy++;
+ setLoading(true, `Loading ${label}`, null);
+ try {
+ const group = await getModel(key, (p) => token === state.loadToken[slot] && setLoading(true, `Loading ${label}`, p * 0.5));
+ if (token !== state.loadToken[slot]) return;
+ const engine = state.engine;
+ const cloud = await buildShapeCloud(group, engine.count, {
+ seed: slot === 'A' ? 7 : 11,
+ onProgress: (p) => token === state.loadToken[slot] && setLoading(true, `Dissolving ${label} into ${engine.count.toLocaleString()} points`, 0.5 + p * 0.5),
+ });
+ if (token !== state.loadToken[slot] || engine !== state.engine) return;
+ engine.setShape(slot, cloud);
+ state[slot.toLowerCase()] = key;
+ state.labels[slot] = label;
+ syncShelves();
+ syncUrl();
+ updateAria();
+ if (slot === 'A') el.hero.classList.add('is-compact');
+ } catch (err) {
+ if (token !== state.loadToken[slot]) return;
+ const reason = err && err.message ? err.message : 'The model could not be loaded.';
+ toast(`Could not dissolve ${label}. ${reason}`);
+ if (!state.engine.shapes[slot]) {
+ // First load failed and nothing is on stage: fall back to the default.
+ if (key !== 'agent') await setSlot(slot, slot === 'A' ? 'agent' : 'fox');
+ }
+ } finally {
+ state.busy--;
+ if (state.busy === 0) setLoading(false);
+ }
+ }
+
+ // ── Engine lifecycle ─────────────────────────────────────────────────
+ function createEngine() {
+ if (state.engine) {
+ scene.remove(state.engine.group);
+ state.engine.dispose();
+ }
+ const side = QUALITY[state.quality].side;
+ const engine = new DissolveEngine(renderer, side);
+ scene.add(engine.group);
+ state.engine = engine;
+ applyPreset(state.preset, { silent: true });
+ engine.setMix(0);
+ engine.params.gravity = state.collapsed ? 9 : 0;
+ el.mix.value = '0';
+ el.count.textContent = `${engine.count.toLocaleString()} GPU particles`;
+ resize();
+ }
+
+ function applyPreset(name, { silent = false } = {}) {
+ const p = PRESETS[name];
+ state.preset = name;
+ const engine = state.engine;
+ for (const key of ['spring', 'damp', 'turb', 'arc', 'stagger', 'size', 'bright']) engine.setParam(key, p[key]);
+ state.bloom = p.bloom;
+ bloom.strength = p.bloom;
+ el.size.value = p.size;
+ el.glow.value = p.bloom;
+ el.chaos.value = p.turb;
+ engine.setView(renderer.domElement.height, FOV);
+ syncPresets();
+ if (!silent) syncUrl();
+ }
+
+ // ── Layout ───────────────────────────────────────────────────────────
+ function resize() {
+ const w = el.stage.clientWidth;
+ const h = el.stage.clientHeight;
+ if (!w || !h) return;
+ renderer.setSize(w, h, false);
+ composer.setSize(w, h);
+ bloom.resolution.set(w, h);
+ camera.aspect = w / h;
+ // Keep the whole figure in frame on a portrait phone.
+ camera.fov = w / h < 0.8 ? FOV + 16 : FOV;
+ camera.updateProjectionMatrix();
+ if (state.engine) state.engine.setView(renderer.domElement.height, camera.fov);
+ }
+ new ResizeObserver(resize).observe(el.stage);
+
+ // ── Pointer tools ────────────────────────────────────────────────────
+ function updatePointer(e) {
+ const rect = el.canvas.getBoundingClientRect();
+ ndc.set(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1);
+ ray.setFromCamera(ndc, camera);
+ camera.getWorldDirection(forward);
+ pointerPlane.setFromNormalAndCoplanarPoint(forward, controls.target);
+ if (ray.ray.intersectPlane(pointerPlane, hit)) state.engine.pointer.point.copy(hit);
+ state.engine.pointer.axis.copy(forward);
+ }
+
+ function applyToolState() {
+ const engine = state.engine;
+ const tool = state.tool;
+ controls.enableRotate = tool === 'orbit';
+ el.canvas.dataset.tool = tool;
+ if (tool === 'gravity' || tool === 'vortex') {
+ engine.pointer.mode = tool === 'gravity' ? TOOL.gravity : TOOL.vortex;
+ const active = state.pressed ? 1 : state.hovering ? 0.28 : 0;
+ engine.pointer.strength = active;
+ } else {
+ engine.pointer.mode = TOOL.none;
+ engine.pointer.strength = 0;
+ }
+ }
+
+ el.canvas.addEventListener('pointerenter', (e) => {
+ if (e.pointerType === 'mouse') state.hovering = true;
+ });
+ el.canvas.addEventListener('pointerleave', () => {
+ state.hovering = false;
+ state.pressed = false;
+ });
+ el.canvas.addEventListener('pointermove', (e) => {
+ if (state.engine) updatePointer(e);
+ });
+ el.canvas.addEventListener('pointerdown', (e) => {
+ if (!state.engine) return;
+ updatePointer(e);
+ state.pressed = true;
+ if (state.tool === 'burst') state.engine.shockwave(state.engine.pointer.point, 1);
+ try {
+ el.canvas.setPointerCapture(e.pointerId);
+ } catch {
+ /* capture is a nicety; the tool still works without it */
+ }
+ });
+ const release = () => (state.pressed = false);
+ el.canvas.addEventListener('pointerup', release);
+ el.canvas.addEventListener('pointercancel', release);
+
+ function selectTool(tool) {
+ state.tool = tool;
+ for (const btn of el.tools.querySelectorAll('[data-tool]')) {
+ const on = btn.dataset.tool === tool;
+ btn.setAttribute('aria-checked', String(on));
+ btn.tabIndex = on ? 0 : -1;
+ }
+ el.toolHint.textContent = TOOL_HINTS[tool];
+ }
+ el.tools.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-tool]');
+ if (btn) selectTool(btn.dataset.tool);
+ });
+ el.tools.addEventListener('keydown', (e) => {
+ const order = [...el.tools.querySelectorAll('[data-tool]')];
+ const i = order.findIndex((b) => b.dataset.tool === state.tool);
+ const step = e.key === 'ArrowRight' || e.key === 'ArrowDown' ? 1 : e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 0;
+ if (!step) return;
+ e.preventDefault();
+ const next = order[(i + step + order.length) % order.length];
+ selectTool(next.dataset.tool);
+ next.focus();
+ });
+
+ // ── Morph timeline ───────────────────────────────────────────────────
+ function morphTo(target) {
+ const engine = state.engine;
+ if (!engine.shapes.B || engine.shapes.B === engine.shapes.A) {
+ toast('Pick a different shape for B first.');
+ return;
+ }
+ const from = engine.mix;
+ if (reducedMotion) {
+ engine.setMix(target);
+ syncMorphUi();
+ return;
+ }
+ state.tween = { from, to: target, t: 0, hold: 0 };
+ syncMorphUi();
+ }
+
+ function stepTween(dt) {
+ const tw = state.tween;
+ if (!tw) return;
+ if (tw.t < 1) {
+ tw.t = Math.min(1, tw.t + dt / MORPH_SECONDS);
+ const e = tw.t < 0.5 ? 4 * tw.t ** 3 : 1 - (-2 * tw.t + 2) ** 3 / 2;
+ state.engine.setMix(tw.from + (tw.to - tw.from) * e);
+ el.mix.value = String(Math.round(state.engine.mix * 1000));
+ if (tw.t >= 1) {
+ tw.hold = 0;
+ syncMorphUi();
+ }
+ return;
+ }
+ if (state.loopOn) {
+ tw.hold += dt;
+ if (tw.hold >= LOOP_HOLD_SECONDS) morphTo(tw.to > 0.5 ? 0 : 1);
+ } else {
+ state.tween = null;
+ }
+ }
+
+ function syncMorphUi() {
+ const atB = state.engine.mix > 0.5 && !(state.tween && state.tween.to < 0.5);
+ el.morph.textContent = atB ? 'Morph to A' : 'Morph to B';
+ }
+
+ el.morph.addEventListener('click', () => {
+ const e = state.engine;
+ const goingTo = state.tween ? (state.tween.to > 0.5 ? 0 : 1) : e.mix > 0.5 ? 0 : 1;
+ morphTo(goingTo);
+ });
+ el.swap.addEventListener('click', swap);
+ function swap() {
+ const e = state.engine;
+ if (!e.shapes.B) return;
+ e.swap();
+ [state.a, state.b] = [state.b, state.a];
+ [state.labels.A, state.labels.B] = [state.labels.B, state.labels.A];
+ [state.custom.A, state.custom.B] = [state.custom.B, state.custom.A];
+ state.tween = null;
+ el.mix.value = String(Math.round(e.mix * 1000));
+ syncShelves();
+ syncUrl();
+ syncMorphUi();
+ }
+ el.loop.addEventListener('click', () => {
+ state.loopOn = !state.loopOn;
+ el.loop.setAttribute('aria-pressed', String(state.loopOn));
+ if (state.loopOn && !state.tween) morphTo(state.engine.mix > 0.5 ? 0 : 1);
+ });
+ el.mix.addEventListener('input', () => {
+ state.tween = null;
+ state.engine.setMix(Number(el.mix.value) / 1000);
+ syncMorphUi();
+ });
+
+ // ── Forces ───────────────────────────────────────────────────────────
+ function setCollapse(on) {
+ state.collapsed = on;
+ state.engine.params.gravity = on ? 9 : 0;
+ el.collapse.setAttribute('aria-pressed', String(on));
+ }
+ el.collapse.addEventListener('click', () => setCollapse(!state.collapsed));
+ function detonate() {
+ state.engine.shockwave(new THREE.Vector3(0, -0.15, 0), 1.7);
+ }
+ el.detonate.addEventListener('click', detonate);
+
+ // ── Looks ────────────────────────────────────────────────────────────
+ function syncPresets() {
+ for (const btn of el.presets.children) {
+ const on = btn.dataset.preset === state.preset;
+ btn.setAttribute('aria-checked', String(on));
+ btn.tabIndex = on ? 0 : -1;
+ }
+ }
+ for (const [id, p] of Object.entries(PRESETS)) {
+ const btn = chip(p.label, 'preset', id);
+ btn.addEventListener('click', () => applyPreset(id));
+ el.presets.append(btn);
+ }
+ el.size.addEventListener('input', () => {
+ state.engine.setParam('size', Number(el.size.value));
+ state.engine.setView(renderer.domElement.height, camera.fov);
+ });
+ el.glow.addEventListener('input', () => {
+ state.bloom = Number(el.glow.value);
+ bloom.strength = state.bloom;
+ });
+ el.chaos.addEventListener('input', () => state.engine.setParam('turb', Number(el.chaos.value)));
+ el.orbit.addEventListener('click', () => {
+ state.autoOrbit = !state.autoOrbit;
+ el.orbit.setAttribute('aria-pressed', String(state.autoOrbit));
+ });
+ el.orbit.setAttribute('aria-pressed', String(state.autoOrbit));
+
+ // ── Mic ──────────────────────────────────────────────────────────────
+ async function toggleMic() {
+ if (mic.active) {
+ mic.stop();
+ state.engine.audio.bass = state.engine.audio.mid = 0;
+ el.mic.setAttribute('aria-pressed', 'false');
+ return;
+ }
+ if (!MicLevels.isSupported()) {
+ toast('This browser does not expose a microphone to web pages.');
+ return;
+ }
+ try {
+ await mic.start();
+ el.mic.setAttribute('aria-pressed', 'true');
+ toast('Listening. Bass swells the storm, mids stir it. Nothing is recorded.');
+ } catch (err) {
+ const denied = err && (err.name === 'NotAllowedError' || err.name === 'SecurityError');
+ toast(denied ? 'Microphone access was blocked. Allow it in the address bar, then press Mic again.' : `The microphone is not available: ${err && err.message ? err.message : 'unknown error'}.`);
+ }
+ }
+ el.mic.addEventListener('click', toggleMic);
+ if (!MicLevels.isSupported()) {
+ el.mic.disabled = true;
+ el.mic.title = 'This browser does not expose a microphone';
+ }
+
+ // ── Capture and share ────────────────────────────────────────────────
+ function download(blob, name) {
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(blob);
+ a.download = name;
+ document.body.append(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(a.href), 4000);
+ }
+ function stamp() {
+ return new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
+ }
+ function snapshot() {
+ composer.render();
+ el.canvas.toBlob((blob) => {
+ if (!blob) return toast('The snapshot could not be encoded.');
+ download(blob, `dissolve-${stamp()}.png`);
+ toast('Saved a PNG.');
+ }, 'image/png');
+ }
+ el.shot.addEventListener('click', snapshot);
+
+ let recTimer = 0;
+ let recStart = 0;
+ async function toggleRecord() {
+ if (recorder.recording) {
+ clearInterval(recTimer);
+ el.rec.hidden = true;
+ el.record.textContent = 'Record';
+ const mime = recorder.mime;
+ try {
+ const blob = await recorder.stop();
+ download(blob, `dissolve-${stamp()}.${extensionFor(mime)}`);
+ toast('Saved your clip.');
+ } catch (err) {
+ toast(`Recording failed: ${err.message}`);
+ }
+ return;
+ }
+ if (!CanvasRecorder.isSupported()) {
+ toast('This browser cannot record the canvas. Use Snapshot instead.');
+ return;
+ }
+ try {
+ recorder.start(60);
+ } catch (err) {
+ toast(err.message);
+ return;
+ }
+ recStart = performance.now();
+ el.rec.hidden = false;
+ el.record.textContent = 'Stop';
+ recTimer = setInterval(() => {
+ const s = Math.floor((performance.now() - recStart) / 1000);
+ el.recTime.textContent = `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
+ }, 250);
+ }
+ el.record.addEventListener('click', toggleRecord);
+
+ function shareUrl() {
+ const q = writeState({ a: state.a, b: state.b, preset: state.preset, quality: state.quality }, '');
+ return `${location.origin}${location.pathname}${q}`;
+ }
+ el.share.addEventListener('click', async () => {
+ const customised = state.custom.A || state.custom.B;
+ const url = shareUrl();
+ try {
+ await navigator.clipboard.writeText(url);
+ toast(customised ? 'Link copied. Files from your device cannot travel in a link, so those slots will show the defaults.' : 'Link copied. Anyone who opens it sees this exact pair.');
+ } catch {
+ toast(`Copy this link: ${url}`, { ms: 12000 });
+ }
+ });
+ function syncUrl() {
+ const shareable = (k) => (shelfEntry(k) || parseModelUrl(k) ? k : k === state.a ? 'agent' : 'fox');
+ const q = writeState({ a: shareable(state.a), b: shareable(state.b), preset: state.preset, quality: state.quality }, '');
+ history.replaceState(null, '', `${location.pathname}${q}`);
+ }
+
+ // ── Shelves, files, links ────────────────────────────────────────────
+ function chip(label, kind, id) {
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'ds-chip-btn';
+ btn.setAttribute('role', 'radio');
+ btn.setAttribute('aria-checked', 'false');
+ btn.dataset[kind] = id;
+ btn.textContent = label;
+ return btn;
+ }
+ function buildShelf(container, slot) {
+ for (const item of SHELF) {
+ const btn = chip(item.label, 'model', item.id);
+ btn.addEventListener('click', () => setSlot(slot, item.id));
+ container.append(btn);
+ }
+ const mine = chip('Yours', 'model', 'custom');
+ mine.hidden = true;
+ mine.dataset.custom = 'true';
+ container.append(mine);
+ }
+ buildShelf(el.shelfA, 'A');
+ buildShelf(el.shelfB, 'B');
+
+ function syncShelves() {
+ for (const [container, slot] of [[el.shelfA, 'A'], [el.shelfB, 'B']]) {
+ const key = state[slot.toLowerCase()];
+ const custom = state.custom[slot];
+ for (const btn of container.children) {
+ if (btn.dataset.custom) {
+ btn.hidden = !custom;
+ if (custom) btn.textContent = custom.label;
+ const on = !!custom && custom.key === key;
+ btn.setAttribute('aria-checked', String(on));
+ btn.tabIndex = on ? 0 : -1;
+ continue;
+ }
+ const on = btn.dataset.model === key;
+ btn.setAttribute('aria-checked', String(on));
+ btn.tabIndex = on || (!container.querySelector('[aria-checked="true"]') && btn === container.firstChild) ? 0 : -1;
+ }
+ }
+ }
+
+ let pickSlot = 'B';
+ el.pickA.addEventListener('click', () => ((pickSlot = 'A'), el.file.click()));
+ el.pickB.addEventListener('click', () => ((pickSlot = 'B'), el.file.click()));
+ el.file.addEventListener('change', () => {
+ const file = el.file.files && el.file.files[0];
+ el.file.value = '';
+ if (file) loadFile(file, pickSlot);
+ });
+ function loadFile(file, slot) {
+ if (!/\.(glb|gltf)$/i.test(file.name)) {
+ toast('Dissolve reads .glb and .gltf files. Convert other formats in the Forge first.');
+ return;
+ }
+ if (file.size > 80 * 1024 * 1024) {
+ toast('That file is over 80 MB. Compress it with meshopt or Draco, then try again.');
+ return;
+ }
+ const key = `file:${file.name}:${file.size}:${file.lastModified}`;
+ state.custom[slot] = { key, url: URL.createObjectURL(file), label: file.name.replace(/\.(glb|gltf)$/i, '').slice(0, 24) };
+ setSlot(slot, key);
+ }
+ el.urlForm.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const slot = e.submitter && e.submitter.dataset.slot ? e.submitter.dataset.slot : 'B';
+ const safe = parseModelUrl(el.url.value.trim());
+ if (!safe) {
+ toast('Use an https link to a .glb file.');
+ return;
+ }
+ state.custom[slot] = { key: safe, url: safe, label: safe.split('/').pop().slice(0, 24) || 'Linked model' };
+ setSlot(slot, safe);
+ });
+ for (const type of ['dragenter', 'dragover']) {
+ el.stage.addEventListener(type, (e) => {
+ if (e.dataTransfer && [...e.dataTransfer.types].includes('Files')) {
+ e.preventDefault();
+ el.stage.classList.add('is-drop');
+ }
+ });
+ }
+ el.stage.addEventListener('dragleave', (e) => {
+ if (e.target === el.stage) el.stage.classList.remove('is-drop');
+ });
+ el.stage.addEventListener('drop', (e) => {
+ e.preventDefault();
+ el.stage.classList.remove('is-drop');
+ const file = e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0];
+ if (file) loadFile(file, e.shiftKey ? 'A' : 'B');
+ });
+
+ // ── Quality ──────────────────────────────────────────────────────────
+ for (const [id, q] of Object.entries(QUALITY)) {
+ const opt = document.createElement('option');
+ opt.value = id;
+ opt.textContent = `${q.label} · ${(q.side * q.side).toLocaleString()}`;
+ el.quality.append(opt);
+ }
+ el.quality.value = state.quality;
+ el.quality.addEventListener('change', async () => {
+ state.quality = el.quality.value;
+ try {
+ localStorage.setItem(QUALITY_KEY, state.quality);
+ } catch {
+ /* the choice just will not persist */
+ }
+ await rebuild();
+ });
+
+ async function rebuild() {
+ const [a, b] = [state.a, state.b];
+ const mix = state.engine ? state.engine.mix : 0;
+ state.tween = null;
+ createEngine();
+ await setSlot('A', a);
+ if (b && b !== a) await setSlot('B', b);
+ state.engine.setMix(mix);
+ el.mix.value = String(Math.round(mix * 1000));
+ syncUrl();
+ }
+
+ // ── Chrome ───────────────────────────────────────────────────────────
+ el.dockToggle.addEventListener('click', () => {
+ const open = el.dock.classList.toggle('is-closed') === false;
+ el.dockToggle.setAttribute('aria-expanded', String(open));
+ });
+ if (window.matchMedia('(max-width: 760px)').matches) {
+ el.dock.classList.add('is-closed');
+ el.dockToggle.setAttribute('aria-expanded', 'false');
+ }
+
+ function updateAria() {
+ const a = state.labels.A;
+ const b = state.labels.B;
+ el.canvas.setAttribute('aria-label', a && b && a !== b ? `${a} dissolved into a storm of glowing particles, ready to morph into ${b}` : `${a || 'A 3D model'} dissolved into a storm of glowing particles`);
+ }
+
+ window.addEventListener('keydown', (e) => {
+ if (e.metaKey || e.ctrlKey || e.altKey) return;
+ const t = e.target;
+ if (t && (t.tagName === 'INPUT' || t.tagName === 'SELECT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
+ if (t && t.tagName === 'BUTTON' && e.key === ' ') return;
+ const map = { 1: 'orbit', 2: 'gravity', 3: 'vortex', 4: 'burst' };
+ if (map[e.key]) return selectTool(map[e.key]);
+ switch (e.key.toLowerCase()) {
+ case ' ':
+ e.preventDefault();
+ return el.morph.click();
+ case 's':
+ return swap();
+ case 'c':
+ return setCollapse(!state.collapsed);
+ case 'b':
+ return detonate();
+ case 'm':
+ return toggleMic();
+ case 'p':
+ return snapshot();
+ case 'r':
+ return toggleRecord();
+ case 'h':
+ return el.dockToggle.click();
+ }
+ });
+
+ // ── Frame loop ───────────────────────────────────────────────────────
+ let last = performance.now();
+ const tick = () => {
+ const now = performance.now();
+ const d = (now - last) / 1000;
+ last = now;
+ return d;
+ };
+ let slowFrames = 0;
+ let slowWarned = false;
+ function frame() {
+ requestAnimationFrame(frame);
+ const engine = state.engine;
+ if (!engine) return;
+ const dt = Math.min(tick(), 0.1);
+
+ const levels = mic.active ? mic.sample() : null;
+ if (levels) {
+ engine.audio.bass = levels.bass;
+ engine.audio.mid = levels.mid;
+ }
+ stepTween(dt);
+ applyToolState();
+ controls.autoRotate = state.autoOrbit && !state.pressed && state.tool !== 'orbit' ? true : state.autoOrbit && state.tool === 'orbit' && !state.pressed;
+ controls.update();
+ engine.step(dt);
+ backdrop.update(engine.time, levels ? levels.bass : 0);
+ composer.render();
+
+ if (dt > 1 / 24 && state.quality !== 'lite' && state.busy === 0) slowFrames++;
+ else slowFrames = Math.max(0, slowFrames - 1);
+ if (slowFrames > 150 && !slowWarned) {
+ slowWarned = true;
+ toast('This is running slowly on your GPU.', {
+ action: {
+ label: 'Switch to Lite',
+ run: () => {
+ el.quality.value = 'lite';
+ el.quality.dispatchEvent(new Event('change'));
+ },
+ },
+ ms: 10000,
+ });
+ }
+ }
+
+ // ── Go ───────────────────────────────────────────────────────────────
+ selectTool(state.tool);
+ syncPresets();
+ createEngine();
+ frame();
+ setSlot('A', state.a).then(() => (state.b !== state.a ? setSlot('B', state.b) : null));
+ document.addEventListener('visibilitychange', tick);
+ window.__dissolve = { state, get engine() { return state.engine; } };
+}
+
+// ── Backdrop: starfield, floor glow and rings that breathe with the bass ────
+function buildBackdrop() {
+ const group = new THREE.Group();
+ const n = 2600;
+ const pos = new Float32Array(n * 3);
+ for (let i = 0; i < n; i++) {
+ const r = 18 + Math.random() * 22;
+ const th = Math.random() * Math.PI * 2;
+ const u = Math.random() * 2 - 1;
+ const s = Math.sqrt(1 - u * u);
+ pos[i * 3] = Math.cos(th) * s * r;
+ pos[i * 3 + 1] = u * r;
+ pos[i * 3 + 2] = Math.sin(th) * s * r;
+ }
+ const stars = new THREE.Points(
+ new THREE.BufferGeometry().setAttribute('position', new THREE.BufferAttribute(pos, 3)),
+ new THREE.PointsMaterial({ color: 0x8fb4ff, size: 0.06, transparent: true, opacity: 0.55, depthWrite: false }),
+ );
+ group.add(stars);
+
+ const floor = new THREE.Mesh(
+ new THREE.CircleGeometry(4.2, 96),
+ new THREE.ShaderMaterial({
+ transparent: true,
+ depthWrite: false,
+ blending: THREE.AdditiveBlending,
+ uniforms: { uTime: { value: 0 }, uBass: { value: 0 } },
+ vertexShader: 'varying vec2 vP; void main(){ vP = position.xy; gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0); }',
+ fragmentShader: `
+ varying vec2 vP; uniform float uTime; uniform float uBass;
+ void main(){
+ float r = length(vP);
+ float glow = exp(-r*r*0.55) * 0.20;
+ float ring = 0.0;
+ for (int i = 1; i <= 4; i++) {
+ float rr = float(i) * 0.85 + uBass * 0.25;
+ ring += exp(-pow((r - rr) * 14.0, 2.0)) * (0.20 / float(i));
+ }
+ float fade = smoothstep(4.2, 1.2, r);
+ gl_FragColor = vec4(vec3(0.15, 0.55, 1.0) * (glow + ring * fade), 1.0);
+ }
+ `,
+ }),
+ );
+ floor.rotation.x = -Math.PI / 2;
+ floor.position.y = -1.002;
+ group.add(floor);
+
+ return {
+ group,
+ update(time, bass) {
+ floor.material.uniforms.uTime.value = time;
+ floor.material.uniforms.uBass.value = bass;
+ stars.rotation.y = time * 0.01;
+ },
+ };
+}
diff --git a/src/dissolve/recorder.js b/src/dissolve/recorder.js
new file mode 100644
index 000000000..af2ddf1a2
--- /dev/null
+++ b/src/dissolve/recorder.js
@@ -0,0 +1,66 @@
+// Capture the live canvas to a shareable clip. Pure mime negotiation plus a
+// thin MediaRecorder wrapper; the browser does all of the encoding.
+
+const MIME_PREFERENCE = [
+ 'video/webm;codecs=vp9',
+ 'video/webm;codecs=vp8',
+ 'video/webm',
+ 'video/mp4;codecs=avc1',
+ 'video/mp4',
+];
+
+/** First container the browser can actually record, or null. */
+export function pickMime(isTypeSupported) {
+ for (const mime of MIME_PREFERENCE) {
+ if (isTypeSupported(mime)) return mime;
+ }
+ return null;
+}
+
+export function extensionFor(mime) {
+ return mime && mime.startsWith('video/mp4') ? 'mp4' : 'webm';
+}
+
+export class CanvasRecorder {
+ constructor(canvas) {
+ this.canvas = canvas;
+ this.recorder = null;
+ this.chunks = [];
+ this.mime = null;
+ }
+
+ static isSupported() {
+ return typeof MediaRecorder !== 'undefined' && typeof HTMLCanvasElement.prototype.captureStream === 'function' && !!pickMime((m) => MediaRecorder.isTypeSupported(m));
+ }
+
+ get recording() {
+ return !!this.recorder && this.recorder.state === 'recording';
+ }
+
+ start(fps = 60) {
+ this.mime = pickMime((m) => MediaRecorder.isTypeSupported(m));
+ if (!this.mime) throw new Error('This browser cannot record video from a canvas.');
+ this.chunks = [];
+ const stream = this.canvas.captureStream(fps);
+ this.recorder = new MediaRecorder(stream, { mimeType: this.mime, videoBitsPerSecond: 12_000_000 });
+ this.recorder.ondataavailable = (e) => {
+ if (e.data && e.data.size > 0) this.chunks.push(e.data);
+ };
+ this.recorder.start(250);
+ }
+
+ /** Resolves with the finished clip as a Blob. */
+ stop() {
+ return new Promise((resolve, reject) => {
+ if (!this.recorder) return reject(new Error('Not recording.'));
+ const recorder = this.recorder;
+ recorder.onstop = () => {
+ for (const track of recorder.stream.getTracks()) track.stop();
+ this.recorder = null;
+ resolve(new Blob(this.chunks, { type: this.mime }));
+ };
+ recorder.onerror = (e) => reject(e.error || new Error('Recording failed.'));
+ recorder.stop();
+ });
+ }
+}
diff --git a/src/dissolve/sample-core.js b/src/dissolve/sample-core.js
new file mode 100644
index 000000000..9c7025ec7
--- /dev/null
+++ b/src/dissolve/sample-core.js
@@ -0,0 +1,252 @@
+// Pure geometry maths behind /dissolve. No three.js, no DOM, so every rule here
+// is held by tests/dissolve-core.test.js.
+//
+// • mulberry32 seeded RNG, so a shape dissolves into the same cloud
+// every time and a shared link reproduces a look
+// • allocateCounts split a particle budget across meshes by surface area
+// • sampleMesh area-weighted uniform points on a triangle mesh
+// • interpolate barycentric blend of any per-vertex attribute
+// • mortonOrder spatial sort that pairs shape A with shape B
+// • fitTransform scale and offset that seat a shape on the shared floor
+
+/** Small, fast, well-distributed seeded generator. Returns floats in [0, 1). */
+export function mulberry32(seed) {
+ let a = seed >>> 0;
+ return function next() {
+ a = (a + 0x6d2b79f5) >>> 0;
+ let t = a;
+ t = Math.imul(t ^ (t >>> 15), t | 1);
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+ };
+}
+
+/** Triangle count of an indexed or non-indexed position array. */
+export function triangleCount(positions, indices) {
+ return indices ? Math.floor(indices.length / 3) : Math.floor(positions.length / 9);
+}
+
+function vertexOf(indices, tri, corner) {
+ return indices ? indices[tri * 3 + corner] : tri * 3 + corner;
+}
+
+/** Surface area of every triangle. Degenerate triangles come out as 0. */
+export function triangleAreas(positions, indices) {
+ const n = triangleCount(positions, indices);
+ const areas = new Float64Array(n);
+ for (let t = 0; t < n; t++) {
+ const a = vertexOf(indices, t, 0) * 3;
+ const b = vertexOf(indices, t, 1) * 3;
+ const c = vertexOf(indices, t, 2) * 3;
+ const ux = positions[b] - positions[a];
+ const uy = positions[b + 1] - positions[a + 1];
+ const uz = positions[b + 2] - positions[a + 2];
+ const vx = positions[c] - positions[a];
+ const vy = positions[c + 1] - positions[a + 1];
+ const vz = positions[c + 2] - positions[a + 2];
+ const cx = uy * vz - uz * vy;
+ const cy = uz * vx - ux * vz;
+ const cz = ux * vy - uy * vx;
+ const area = 0.5 * Math.sqrt(cx * cx + cy * cy + cz * cz);
+ areas[t] = Number.isFinite(area) ? area : 0;
+ }
+ return areas;
+}
+
+/** Cumulative area table. `total` is 0 when the mesh has no surface at all. */
+export function buildCdf(areas) {
+ const cdf = new Float64Array(areas.length);
+ let total = 0;
+ for (let i = 0; i < areas.length; i++) {
+ total += areas[i];
+ cdf[i] = total;
+ }
+ return { cdf, total };
+}
+
+/** Index of the triangle that owns a draw `r` in [0, 1). Binary search. */
+export function pickTriangle(cdf, total, r) {
+ const target = r * total;
+ let lo = 0;
+ let hi = cdf.length - 1;
+ while (lo < hi) {
+ const mid = (lo + hi) >>> 1;
+ if (cdf[mid] > target) hi = mid;
+ else lo = mid + 1;
+ }
+ return lo;
+}
+
+/** Uniform barycentric coordinates via the square-root method. */
+export function randomBarycentric(r1, r2, out = [0, 0, 0]) {
+ const s = Math.sqrt(r1);
+ out[0] = 1 - s;
+ out[1] = s * (1 - r2);
+ out[2] = s * r2;
+ return out;
+}
+
+/**
+ * Split `count` particles across weights with the largest-remainder method, so
+ * the parts always sum to exactly `count` and no weight is rounded to nothing
+ * while a heavier one gains an extra particle.
+ */
+export function allocateCounts(weights, count) {
+ const n = weights.length;
+ const out = new Array(n).fill(0);
+ let sum = 0;
+ for (const w of weights) sum += w > 0 ? w : 0;
+ if (n === 0 || !(sum > 0) || count <= 0) return out;
+ const remainders = [];
+ let assigned = 0;
+ for (let i = 0; i < n; i++) {
+ const exact = ((weights[i] > 0 ? weights[i] : 0) / sum) * count;
+ const whole = Math.floor(exact);
+ out[i] = whole;
+ assigned += whole;
+ remainders.push({ i, frac: exact - whole });
+ }
+ remainders.sort((a, b) => b.frac - a.frac || a.i - b.i);
+ for (let k = 0; assigned < count; k = (k + 1) % n) {
+ if ((weights[remainders[k].i] > 0 ? weights[remainders[k].i] : 0) > 0) {
+ out[remainders[k].i]++;
+ assigned++;
+ }
+ }
+ return out;
+}
+
+/**
+ * Draw `count` uniform points on the surface of one mesh.
+ *
+ * `mesh.positions` is world-space xyz, `mesh.indices` is optional, `mesh.uvs`
+ * is optional. Returns the points plus, per point, the triangle it landed on
+ * and its barycentric weights, which is what colour lookup needs.
+ */
+export function sampleMesh(mesh, count, rng, precomputed = null) {
+ const { positions, indices = null, uvs = null } = mesh;
+ const { cdf, total } = precomputed || buildCdf(triangleAreas(positions, indices));
+ const out = {
+ positions: new Float32Array(count * 3),
+ uvs: uvs ? new Float32Array(count * 2) : null,
+ tri: new Uint32Array(count),
+ bary: new Float32Array(count * 3),
+ };
+ if (!(total > 0) || count === 0) return { ...out, count: 0 };
+ const w = [0, 0, 0];
+ for (let i = 0; i < count; i++) {
+ const t = pickTriangle(cdf, total, rng());
+ randomBarycentric(rng(), rng(), w);
+ const a = vertexOf(indices, t, 0);
+ const b = vertexOf(indices, t, 1);
+ const c = vertexOf(indices, t, 2);
+ for (let k = 0; k < 3; k++) {
+ out.positions[i * 3 + k] =
+ positions[a * 3 + k] * w[0] + positions[b * 3 + k] * w[1] + positions[c * 3 + k] * w[2];
+ }
+ if (uvs) {
+ for (let k = 0; k < 2; k++) {
+ out.uvs[i * 2 + k] = uvs[a * 2 + k] * w[0] + uvs[b * 2 + k] * w[1] + uvs[c * 2 + k] * w[2];
+ }
+ }
+ out.tri[i] = t;
+ out.bary[i * 3] = w[0];
+ out.bary[i * 3 + 1] = w[1];
+ out.bary[i * 3 + 2] = w[2];
+ }
+ return { ...out, count };
+}
+
+/** Barycentric blend of a per-vertex attribute for sample `i`. */
+export function interpolate(attribute, itemSize, indices, tri, bary, i, out) {
+ const a = vertexOf(indices, tri[i], 0);
+ const b = vertexOf(indices, tri[i], 1);
+ const c = vertexOf(indices, tri[i], 2);
+ for (let k = 0; k < itemSize; k++) {
+ out[k] =
+ attribute[a * itemSize + k] * bary[i * 3] +
+ attribute[b * itemSize + k] * bary[i * 3 + 1] +
+ attribute[c * itemSize + k] * bary[i * 3 + 2];
+ }
+ return out;
+}
+
+/** Spread the low 10 bits of `v` so there are two zero bits between each. */
+function spreadBits(v) {
+ v &= 0x3ff;
+ v = (v | (v << 16)) & 0x030000ff;
+ v = (v | (v << 8)) & 0x0300f00f;
+ v = (v | (v << 4)) & 0x030c30c3;
+ v = (v | (v << 2)) & 0x09249249;
+ return v >>> 0;
+}
+
+/** 30-bit Morton code for a point inside [min, max]. */
+export function mortonCode(x, y, z, min, max) {
+ const q = (v, axis) => {
+ const span = max[axis] - min[axis];
+ const f = span > 0 ? (v - min[axis]) / span : 0;
+ return Math.max(0, Math.min(1023, Math.floor(f * 1023)));
+ };
+ return (spreadBits(q(x, 0)) | (spreadBits(q(y, 1)) << 1) | (spreadBits(q(z, 2)) << 2)) >>> 0;
+}
+
+/**
+ * Permutation that lists points in Morton order over a shared box. Particle
+ * `i` of two clouds sorted over the SAME box lands at the same relative place
+ * in each, so a morph moves bottom to bottom and head to head instead of
+ * shuffling the whole body through itself. Supports up to 2^20 points.
+ */
+export function mortonOrder(positions, count, min, max) {
+ if (count > 1048576) throw new RangeError('mortonOrder supports at most 1048576 points');
+ const keys = new Float64Array(count);
+ for (let i = 0; i < count; i++) {
+ const code = mortonCode(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2], min, max);
+ keys[i] = code * 1048576 + i;
+ }
+ keys.sort();
+ const order = new Uint32Array(count);
+ for (let i = 0; i < count; i++) order[i] = keys[i] % 1048576;
+ return order;
+}
+
+/** Axis-aligned bounds of an xyz array. Empty input gives a unit box. */
+export function boundsOf(positions, count = positions.length / 3) {
+ if (count === 0) return { min: [-1, -1, -1], max: [1, 1, 1] };
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ for (let i = 0; i < count; i++) {
+ for (let k = 0; k < 3; k++) {
+ const v = positions[i * 3 + k];
+ if (v < min[k]) min[k] = v;
+ if (v > max[k]) max[k] = v;
+ }
+ }
+ return { min, max };
+}
+
+/** Height of the shared stage. Every shape is seated with its feet on -1. */
+export const STAGE_HEIGHT = 2;
+/** The widest a shape may get, so a long prop never leaves the frame. */
+export const STAGE_MAX_WIDTH = 3.2;
+
+/**
+ * Scale and offset that turn a model's raw bounds into stage space: feet on
+ * y = -1, centred on x and z, tall figures filling the stage height, and wide
+ * ones (a fox, a car) held to a width the camera can frame.
+ */
+export function fitTransform(min, max) {
+ const sx = max[0] - min[0];
+ const sy = max[1] - min[1];
+ const sz = max[2] - min[2];
+ const wide = Math.max(sx, sz);
+ const basis = Math.max(sy, 0.6 * wide);
+ let scale = basis > 0 ? STAGE_HEIGHT / basis : 1;
+ if (wide * scale > STAGE_MAX_WIDTH) scale = STAGE_MAX_WIDTH / wide;
+ const offset = [
+ -((min[0] + max[0]) / 2) * scale,
+ -1 - min[1] * scale,
+ -((min[2] + max[2]) / 2) * scale,
+ ];
+ return { scale, offset };
+}
diff --git a/src/dissolve/shape.js b/src/dissolve/shape.js
new file mode 100644
index 000000000..23d810ae8
--- /dev/null
+++ b/src/dissolve/shape.js
@@ -0,0 +1,207 @@
+// Turn a loaded glTF into a ShapeCloud: N points on its real surface, each
+// carrying the colour the model has at that spot (base-colour texture, vertex
+// colours and material colour, in that order of authority).
+//
+// A ShapeCloud is { count, positions: Float32Array(3N), colors: Float32Array(3N,
+// linear) }, already seated on the shared stage floor by fitTransform.
+
+import * as THREE from 'three';
+import {
+ mulberry32,
+ triangleAreas,
+ buildCdf,
+ allocateCounts,
+ sampleMesh,
+ interpolate,
+ boundsOf,
+ fitTransform,
+} from './sample-core.js';
+
+/** sRGB byte -> linear float, one table lookup per channel. */
+const SRGB_TO_LINEAR = (() => {
+ const lut = new Float32Array(256);
+ for (let i = 0; i < 256; i++) {
+ const c = i / 255;
+ lut[i] = c <= 0.04045 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4);
+ }
+ return lut;
+})();
+
+const MAX_TEXTURE_SIDE = 1024;
+
+/** Decode a three.js texture's image into RGBA pixels, downscaled if huge. */
+function readTexturePixels(texture) {
+ const image = texture && texture.image;
+ if (!image) return null;
+ const w = image.width || image.videoWidth;
+ const h = image.height || image.videoHeight;
+ if (!w || !h) return null;
+ const k = Math.min(1, MAX_TEXTURE_SIDE / Math.max(w, h));
+ const cw = Math.max(1, Math.round(w * k));
+ const ch = Math.max(1, Math.round(h * k));
+ const canvas = document.createElement('canvas');
+ canvas.width = cw;
+ canvas.height = ch;
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
+ ctx.drawImage(image, 0, 0, cw, ch);
+ return { data: ctx.getImageData(0, 0, cw, ch).data, width: cw, height: ch, flipY: texture.flipY };
+}
+
+/** World-space positions of a mesh, with skinning applied at the current pose. */
+function worldPositions(mesh) {
+ const position = mesh.geometry.getAttribute('position');
+ const count = position.count;
+ const out = new Float32Array(count * 3);
+ const v = new THREE.Vector3();
+ if (mesh.isSkinnedMesh) {
+ mesh.skeleton.update();
+ for (let i = 0; i < count; i++) {
+ mesh.getVertexPosition(i, v);
+ v.applyMatrix4(mesh.matrixWorld);
+ out[i * 3] = v.x;
+ out[i * 3 + 1] = v.y;
+ out[i * 3 + 2] = v.z;
+ }
+ } else {
+ for (let i = 0; i < count; i++) {
+ v.fromBufferAttribute(position, i).applyMatrix4(mesh.matrixWorld);
+ out[i * 3] = v.x;
+ out[i * 3 + 1] = v.y;
+ out[i * 3 + 2] = v.z;
+ }
+ }
+ return out;
+}
+
+function flatten(attribute) {
+ if (!attribute) return null;
+ const out = new Float32Array(attribute.count * attribute.itemSize);
+ for (let i = 0; i < attribute.count; i++) {
+ for (let k = 0; k < attribute.itemSize; k++) out[i * attribute.itemSize + k] = attribute.getComponent(i, k);
+ }
+ return out;
+}
+
+/** Pull every drawable mesh out of a scene as plain typed arrays. */
+export function collectMeshes(root) {
+ root.updateMatrixWorld(true);
+ const meshes = [];
+ root.traverse((node) => {
+ if (!node.isMesh || !node.visible || !node.geometry) return;
+ const geometry = node.geometry;
+ if (!geometry.getAttribute('position')) return;
+ const material = Array.isArray(node.material) ? node.material[0] : node.material;
+ const index = geometry.getIndex();
+ const colorAttr = geometry.getAttribute('color');
+ meshes.push({
+ positions: worldPositions(node),
+ indices: index ? Uint32Array.from(index.array) : null,
+ uvs: material && material.map ? flatten(geometry.getAttribute('uv')) : null,
+ vertexColors: colorAttr ? { data: flatten(colorAttr), itemSize: colorAttr.itemSize } : null,
+ material: {
+ color: material && material.color ? material.color.clone() : new THREE.Color(0.8, 0.8, 0.8),
+ emissive: material && material.emissive ? material.emissive.clone() : null,
+ pixels: material && material.map ? readTexturePixels(material.map) : null,
+ },
+ });
+ });
+ return meshes;
+}
+
+function yieldFrame() {
+ return new Promise((resolve) => requestAnimationFrame(() => resolve()));
+}
+
+/**
+ * Sample `count` points across every mesh, colour them, and seat the cloud on
+ * the stage. `onProgress(0..1)` reports real work done; the loop yields to the
+ * browser between chunks so the page stays responsive on a million points.
+ */
+export async function buildShapeCloud(root, count, { seed = 1, onProgress = () => {} } = {}) {
+ const meshes = collectMeshes(root);
+ if (meshes.length === 0) throw new Error('This model has no meshes to dissolve.');
+
+ const tables = meshes.map((m) => buildCdf(triangleAreas(m.positions, m.indices)));
+ const alloc = allocateCounts(tables.map((t) => t.total), count);
+ if (alloc.every((n) => n === 0)) throw new Error('This model has no surface area to dissolve.');
+
+ const rng = mulberry32(seed);
+ const positions = new Float32Array(count * 3);
+ const colors = new Float32Array(count * 3);
+ const scratch = [0, 0, 0, 0];
+ const tint = new THREE.Color();
+ let written = 0;
+ const CHUNK = 65536;
+
+ for (let m = 0; m < meshes.length; m++) {
+ const mesh = meshes[m];
+ let remaining = alloc[m];
+ while (remaining > 0) {
+ const take = Math.min(CHUNK, remaining);
+ const sample = sampleMesh(mesh, take, rng, tables[m]);
+ if (sample.count === 0) break;
+ const { pixels } = mesh.material;
+ tint.copy(mesh.material.color);
+ for (let i = 0; i < take; i++) {
+ const o = (written + i) * 3;
+ positions[o] = sample.positions[i * 3];
+ positions[o + 1] = sample.positions[i * 3 + 1];
+ positions[o + 2] = sample.positions[i * 3 + 2];
+ let r = tint.r;
+ let g = tint.g;
+ let b = tint.b;
+ if (pixels && sample.uvs) {
+ const u = sample.uvs[i * 2] - Math.floor(sample.uvs[i * 2]);
+ const vRaw = sample.uvs[i * 2 + 1] - Math.floor(sample.uvs[i * 2 + 1]);
+ // glTF textures are authored top-down (flipY false); others are not.
+ const v = pixels.flipY ? 1 - vRaw : vRaw;
+ const px = Math.min(pixels.width - 1, Math.floor(u * pixels.width));
+ const py = Math.min(pixels.height - 1, Math.floor(v * pixels.height));
+ const p = (py * pixels.width + px) * 4;
+ r *= SRGB_TO_LINEAR[pixels.data[p]];
+ g *= SRGB_TO_LINEAR[pixels.data[p + 1]];
+ b *= SRGB_TO_LINEAR[pixels.data[p + 2]];
+ }
+ if (mesh.vertexColors) {
+ interpolate(mesh.vertexColors.data, mesh.vertexColors.itemSize, mesh.indices, sample.tri, sample.bary, i, scratch);
+ r *= scratch[0];
+ g *= scratch[1];
+ b *= scratch[2];
+ }
+ if (mesh.material.emissive) {
+ r += mesh.material.emissive.r;
+ g += mesh.material.emissive.g;
+ b += mesh.material.emissive.b;
+ }
+ colors[o] = r;
+ colors[o + 1] = g;
+ colors[o + 2] = b;
+ }
+ written += take;
+ remaining -= take;
+ onProgress(written / count);
+ if (remaining > 0 || m < meshes.length - 1) await yieldFrame();
+ }
+ }
+ if (written < count) {
+ // A mesh with no surface can leave a gap. Fill it by repeating real
+ // samples so the cloud has exactly `count` live particles.
+ for (let i = written; i < count; i++) {
+ const src = (i % Math.max(1, written)) * 3;
+ for (let k = 0; k < 3; k++) {
+ positions[i * 3 + k] = positions[src + k];
+ colors[i * 3 + k] = colors[src + k];
+ }
+ }
+ }
+
+ const { min, max } = boundsOf(positions, count);
+ const { scale, offset } = fitTransform(min, max);
+ for (let i = 0; i < count; i++) {
+ positions[i * 3] = positions[i * 3] * scale + offset[0];
+ positions[i * 3 + 1] = positions[i * 3 + 1] * scale + offset[1];
+ positions[i * 3 + 2] = positions[i * 3 + 2] * scale + offset[2];
+ }
+ onProgress(1);
+ return { count, positions, colors };
+}
diff --git a/src/dissolve/shelf.js b/src/dissolve/shelf.js
new file mode 100644
index 000000000..c7330a149
--- /dev/null
+++ b/src/dissolve/shelf.js
@@ -0,0 +1,76 @@
+// The models /dissolve ships on its shelf. Every url is a real GLB served from
+// /public, and tests/dissolve-shelf.test.js keeps it that way.
+
+export const SHELF = [
+ { id: 'agent', label: 'Agent', url: '/avatars/default.glb' },
+ { id: 'xbot', label: 'X Bot', url: '/avatars/xbot.glb' },
+ { id: 'mannequin', label: 'Mannequin', url: '/avatars/mannequin.glb' },
+ { id: 'michelle', label: 'Michelle', url: '/avatars/michelle.glb' },
+ { id: 'realistic-female', label: 'Realistic F', url: '/avatars/realistic-female.glb' },
+ { id: 'realistic-male', label: 'Realistic M', url: '/avatars/realistic-male.glb' },
+ { id: 'cesium-man', label: 'Cesium Man', url: '/avatars/cesium-man.glb' },
+ { id: 'fox', label: 'Fox', url: '/avatars/fox.glb' },
+ { id: 'brainstem', label: 'Brainstem', url: '/avatars/brainstem.glb' },
+ { id: 'studio', label: 'Studio', url: '/avatars/studio.glb' },
+];
+
+export const PRESETS = {
+ storm: { label: 'Storm', spring: 16, damp: 5.2, turb: 0.35, arc: 0.6, stagger: 0.7, size: 1, bright: 0.55, bloom: 0.9 },
+ ember: { label: 'Ember', spring: 4, damp: 2.4, turb: 1.1, arc: 0.9, stagger: 0.9, size: 1.2, bright: 0.5, bloom: 1.2 },
+ crystal: { label: 'Crystal', spring: 34, damp: 9, turb: 0.04, arc: 0.15, stagger: 0.35, size: 0.7, bright: 0.7, bloom: 0.6 },
+ ink: { label: 'Ink', spring: 2.2, damp: 3.2, turb: 0.7, arc: 1.2, stagger: 1, size: 1.7, bright: 0.35, bloom: 1 },
+};
+
+export const QUALITY = {
+ lite: { label: 'Lite', side: 256 },
+ standard: { label: 'Standard', side: 512 },
+ ultra: { label: 'Ultra', side: 1024 },
+};
+
+/** Resolve a `?a=` / `?b=` value to a shelf entry, or null. */
+export function shelfEntry(id) {
+ return SHELF.find((s) => s.id === id) || null;
+}
+
+/** Only https (or same-origin) GLB links are loadable; everything else is refused up front. */
+export function parseModelUrl(raw, origin = 'https://three.ws') {
+ if (typeof raw !== 'string' || raw.length === 0 || raw.length > 2048) return null;
+ // Absolute https or a root-relative path. A bare word would otherwise
+ // resolve against our own origin and look valid.
+ if (!/^(https:\/\/|\/(?!\/))/.test(raw)) return null;
+ let url;
+ try {
+ url = new URL(raw, origin);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== 'https:' && url.origin !== origin) return null;
+ return url.href;
+}
+
+/** Share-link state, validated: unknown values fall back instead of throwing. */
+export function readState(search) {
+ const q = new URLSearchParams(search);
+ const pick = (key, allowed, fallback) => (allowed.includes(q.get(key)) ? q.get(key) : fallback);
+ const model = (key, fallback) => {
+ const v = q.get(key);
+ if (!v) return fallback;
+ if (shelfEntry(v)) return v;
+ return parseModelUrl(v) ? v : fallback;
+ };
+ return {
+ a: model('a', 'agent'),
+ b: model('b', 'fox'),
+ preset: pick('p', Object.keys(PRESETS), 'storm'),
+ quality: pick('q', Object.keys(QUALITY), null),
+ };
+}
+
+export function writeState({ a, b, preset, quality }, base = '') {
+ const q = new URLSearchParams();
+ q.set('a', a);
+ q.set('b', b);
+ q.set('p', preset);
+ if (quality) q.set('q', quality);
+ return `${base}?${q.toString()}`;
+}
diff --git a/tests/dissolve-core.test.js b/tests/dissolve-core.test.js
new file mode 100644
index 000000000..8aab4f817
--- /dev/null
+++ b/tests/dissolve-core.test.js
@@ -0,0 +1,312 @@
+/**
+ * The maths behind /dissolve (src/dissolve/*.js). The page turns a 3D model
+ * into hundreds of thousands of particles, so these rules decide whether the
+ * cloud is even and whether a morph moves like a body or like a shuffle:
+ *
+ * · points land ON the surface, spread by area and not by triangle count
+ * · the particle budget splits across meshes by area and always sums exactly
+ * · a seed reproduces a cloud, so a shared link reproduces a look
+ * · two shapes pair bottom-to-bottom through the Morton order
+ * · every shape is seated on the shared floor and held inside the frame
+ * · the mic bands, the recorder container and the smoothing behave
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ mulberry32,
+ triangleAreas,
+ buildCdf,
+ pickTriangle,
+ randomBarycentric,
+ allocateCounts,
+ sampleMesh,
+ interpolate,
+ mortonCode,
+ mortonOrder,
+ boundsOf,
+ fitTransform,
+ STAGE_HEIGHT,
+ STAGE_MAX_WIDTH,
+} from '../src/dissolve/sample-core.js';
+import { bandLevel, bandLevels, smoothLevel } from '../src/dissolve/audio.js';
+import { pickMime, extensionFor } from '../src/dissolve/recorder.js';
+
+/** A unit square in the XY plane as two triangles. */
+const SQUARE = {
+ positions: new Float32Array([0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]),
+ indices: new Uint32Array([0, 1, 2, 0, 2, 3]),
+ uvs: new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]),
+};
+
+describe('mulberry32', () => {
+ it('repeats for a seed and differs between seeds', () => {
+ const a = Array.from({ length: 5 }, mulberry32(7));
+ const b = Array.from({ length: 5 }, mulberry32(7));
+ const c = Array.from({ length: 5 }, mulberry32(8));
+ expect(a).toEqual(b);
+ expect(a).not.toEqual(c);
+ });
+
+ it('stays inside [0, 1)', () => {
+ const next = mulberry32(1);
+ for (let i = 0; i < 10000; i++) {
+ const v = next();
+ expect(v).toBeGreaterThanOrEqual(0);
+ expect(v).toBeLessThan(1);
+ }
+ });
+});
+
+describe('triangleAreas and the CDF', () => {
+ it('measures a unit square as two half-unit triangles', () => {
+ const areas = triangleAreas(SQUARE.positions, SQUARE.indices);
+ expect(Array.from(areas)).toEqual([0.5, 0.5]);
+ });
+
+ it('reads a non-indexed mesh three vertices at a time', () => {
+ const soup = new Float32Array([0, 0, 0, 2, 0, 0, 0, 2, 0]);
+ expect(Array.from(triangleAreas(soup, null))).toEqual([2]);
+ });
+
+ it('gives a degenerate triangle zero weight so nothing is ever drawn on it', () => {
+ const flat = new Float32Array([0, 0, 0, 1, 1, 1, 2, 2, 2]);
+ const { total } = buildCdf(triangleAreas(flat, null));
+ expect(total).toBe(0);
+ });
+
+ it('maps draws to triangles in proportion to area', () => {
+ const { cdf, total } = buildCdf(new Float64Array([1, 3]));
+ expect(pickTriangle(cdf, total, 0)).toBe(0);
+ expect(pickTriangle(cdf, total, 0.24)).toBe(0);
+ expect(pickTriangle(cdf, total, 0.26)).toBe(1);
+ expect(pickTriangle(cdf, total, 0.999999)).toBe(1);
+ });
+});
+
+describe('randomBarycentric', () => {
+ it('always sums to one with no negative weight', () => {
+ const next = mulberry32(3);
+ for (let i = 0; i < 5000; i++) {
+ const w = randomBarycentric(next(), next());
+ expect(w[0] + w[1] + w[2]).toBeCloseTo(1, 12);
+ expect(Math.min(...w)).toBeGreaterThanOrEqual(0);
+ }
+ });
+});
+
+describe('allocateCounts', () => {
+ it('sums to exactly the budget', () => {
+ for (const count of [1, 7, 1000, 262144]) {
+ const parts = allocateCounts([0.31, 12.5, 4, 0.0004, 9], count);
+ expect(parts.reduce((s, v) => s + v, 0)).toBe(count);
+ }
+ });
+
+ it('follows the weights and never funds a zero-weight mesh', () => {
+ const parts = allocateCounts([1, 0, 3], 100);
+ expect(parts).toEqual([25, 0, 75]);
+ });
+
+ it('returns all zeros when there is nothing to weigh', () => {
+ expect(allocateCounts([0, 0], 50)).toEqual([0, 0]);
+ expect(allocateCounts([], 50)).toEqual([]);
+ expect(allocateCounts([1, 2], 0)).toEqual([0, 0]);
+ });
+});
+
+describe('sampleMesh', () => {
+ it('puts every point on the surface of the square', () => {
+ const out = sampleMesh(SQUARE, 4000, mulberry32(11));
+ expect(out.count).toBe(4000);
+ for (let i = 0; i < out.count; i++) {
+ const x = out.positions[i * 3];
+ const y = out.positions[i * 3 + 1];
+ expect(out.positions[i * 3 + 2]).toBe(0);
+ expect(x).toBeGreaterThanOrEqual(-1e-6);
+ expect(x).toBeLessThanOrEqual(1 + 1e-6);
+ expect(y).toBeGreaterThanOrEqual(-1e-6);
+ expect(y).toBeLessThanOrEqual(1 + 1e-6);
+ }
+ });
+
+ it('covers the surface evenly: each quadrant gets about a quarter', () => {
+ const out = sampleMesh(SQUARE, 40000, mulberry32(5));
+ const quad = [0, 0, 0, 0];
+ for (let i = 0; i < out.count; i++) {
+ quad[(out.positions[i * 3] > 0.5 ? 1 : 0) + (out.positions[i * 3 + 1] > 0.5 ? 2 : 0)]++;
+ }
+ for (const q of quad) expect(q / out.count).toBeGreaterThan(0.23);
+ for (const q of quad) expect(q / out.count).toBeLessThan(0.27);
+ });
+
+ it('weights a big triangle over a small one', () => {
+ const mesh = {
+ positions: new Float32Array([0, 0, 0, 4, 0, 0, 0, 4, 0, 10, 10, 0, 10.5, 10, 0, 10, 10.5, 0]),
+ indices: new Uint32Array([0, 1, 2, 3, 4, 5]),
+ };
+ const out = sampleMesh(mesh, 10000, mulberry32(2));
+ let small = 0;
+ for (let i = 0; i < out.count; i++) if (out.tri[i] === 1) small++;
+ // areas are 8 and 0.125, so the small triangle owns 1.5% of the surface
+ expect(small / out.count).toBeGreaterThan(0.008);
+ expect(small / out.count).toBeLessThan(0.025);
+ });
+
+ it('reproduces the same cloud from the same seed', () => {
+ const a = sampleMesh(SQUARE, 100, mulberry32(9));
+ const b = sampleMesh(SQUARE, 100, mulberry32(9));
+ expect(Array.from(a.positions)).toEqual(Array.from(b.positions));
+ });
+
+ it('interpolates uvs with the same weights as positions', () => {
+ const out = sampleMesh(SQUARE, 500, mulberry32(4));
+ for (let i = 0; i < out.count; i++) {
+ expect(out.uvs[i * 2]).toBeCloseTo(out.positions[i * 3], 5);
+ expect(out.uvs[i * 2 + 1]).toBeCloseTo(out.positions[i * 3 + 1], 5);
+ }
+ });
+
+ it('returns an empty cloud for a mesh with no area instead of NaN points', () => {
+ const flat = { positions: new Float32Array([0, 0, 0, 1, 1, 1, 2, 2, 2]), indices: null };
+ const out = sampleMesh(flat, 10, mulberry32(1));
+ expect(out.count).toBe(0);
+ });
+});
+
+describe('interpolate', () => {
+ it('blends a per-vertex attribute with the sample weights', () => {
+ const colors = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]);
+ const out = [0, 0, 0];
+ interpolate(colors, 3, new Uint32Array([0, 1, 2]), new Uint32Array([0]), new Float32Array([0.5, 0.25, 0.25]), 0, out);
+ expect(out).toEqual([0.5, 0.25, 0.25]);
+ });
+});
+
+describe('mortonOrder', () => {
+ const min = [0, 0, 0];
+ const max = [1, 1, 1];
+
+ it('is a true permutation', () => {
+ const next = mulberry32(21);
+ const pts = new Float32Array(3000);
+ for (let i = 0; i < pts.length; i++) pts[i] = next();
+ const order = mortonOrder(pts, 1000, min, max);
+ expect(new Set(order).size).toBe(1000);
+ expect(Math.max(...order)).toBe(999);
+ });
+
+ it('keeps neighbours close: consecutive points are nearer than random pairs', () => {
+ const next = mulberry32(22);
+ const n = 4000;
+ const pts = new Float32Array(n * 3);
+ for (let i = 0; i < pts.length; i++) pts[i] = next();
+ const order = mortonOrder(pts, n, min, max);
+ const dist = (a, b) =>
+ Math.hypot(pts[a * 3] - pts[b * 3], pts[a * 3 + 1] - pts[b * 3 + 1], pts[a * 3 + 2] - pts[b * 3 + 2]);
+ let sorted = 0;
+ let random = 0;
+ for (let i = 1; i < n; i++) {
+ sorted += dist(order[i - 1], order[i]);
+ random += dist(i - 1, i);
+ }
+ expect(sorted).toBeLessThan(random * 0.4);
+ });
+
+ it('pairs the low end of one shape with the low end of another', () => {
+ const a = new Float32Array([0, 0, 0, 0, 1, 0, 0, 0.5, 0]);
+ const b = new Float32Array([5, 0.9, 5, 5, 0, 5, 5, 0.4, 5]);
+ const box = { min: [0, 0, 0], max: [5, 1, 5] };
+ const oa = mortonOrder(a, 3, box.min, box.max);
+ const ob = mortonOrder(b, 3, box.min, box.max);
+ // the lowest point of each shape sits first in its own order
+ expect(a[oa[0] * 3 + 1]).toBe(0);
+ expect(b[ob[0] * 3 + 1]).toBe(0);
+ });
+
+ it('refuses a cloud it cannot key without collisions', () => {
+ expect(() => mortonOrder(new Float32Array(3), 1048577, min, max)).toThrow(RangeError);
+ });
+
+ it('clamps points outside the box instead of wrapping', () => {
+ expect(mortonCode(-5, -5, -5, min, max)).toBe(0);
+ expect(mortonCode(9, 9, 9, min, max)).toBe(mortonCode(1, 1, 1, min, max));
+ });
+});
+
+describe('boundsOf', () => {
+ it('finds the box and tolerates an empty cloud', () => {
+ expect(boundsOf(new Float32Array([1, 2, 3, -1, 5, 0]))).toEqual({ min: [-1, 2, 0], max: [1, 5, 3] });
+ expect(boundsOf(new Float32Array(0))).toEqual({ min: [-1, -1, -1], max: [1, 1, 1] });
+ });
+});
+
+describe('fitTransform', () => {
+ const apply = (v, t) => v * t.scale;
+
+ it('seats a tall figure on the floor at stage height', () => {
+ const t = fitTransform([-0.3, 0, -0.2], [0.3, 1.8, 0.2]);
+ expect(apply(1.8, t) + t.offset[1]).toBeCloseTo(-1 + STAGE_HEIGHT, 6);
+ expect(apply(0, t) + t.offset[1]).toBeCloseTo(-1, 6);
+ });
+
+ it('centres a shape on x and z wherever it was authored', () => {
+ const t = fitTransform([10, 3, 20], [12, 5, 24]);
+ expect(apply(10, t) + t.offset[0]).toBeCloseTo(-(apply(12, t) + t.offset[0]), 6);
+ expect(apply(20, t) + t.offset[2]).toBeCloseTo(-(apply(24, t) + t.offset[2]), 6);
+ });
+
+ it('holds a long prop inside the frame width', () => {
+ const t = fitTransform([0, 0, 0], [30, 1, 2]);
+ expect(30 * t.scale).toBeLessThanOrEqual(STAGE_MAX_WIDTH + 1e-9);
+ });
+
+ it('does not divide by zero for a flat or empty box', () => {
+ const t = fitTransform([0, 0, 0], [0, 0, 0]);
+ expect(Number.isFinite(t.scale)).toBe(true);
+ expect(t.offset.every(Number.isFinite)).toBe(true);
+ });
+});
+
+describe('audio bands', () => {
+ const sampleRate = 48000;
+ const bins = new Uint8Array(512); // 46.875 Hz per bin
+
+ it('reads only the energy inside the band', () => {
+ bins.fill(0);
+ bins[2] = 255; // ~94 Hz, inside bass
+ const { bass, mid, treble } = bandLevels(bins, sampleRate);
+ expect(bass).toBeGreaterThan(0);
+ expect(mid).toBe(0);
+ expect(treble).toBe(0);
+ });
+
+ it('returns 1 for a saturated spectrum and 0 for silence or no data', () => {
+ bins.fill(255);
+ expect(bandLevel(bins, sampleRate, 160, 2000)).toBe(1);
+ expect(bandLevel(new Uint8Array(0), sampleRate, 20, 160)).toBe(0);
+ expect(bandLevel(null, sampleRate, 20, 160)).toBe(0);
+ });
+
+ it('attacks faster than it releases so a kick lands and then breathes out', () => {
+ const up = smoothLevel(0, 1);
+ const down = 1 - smoothLevel(1, 0);
+ expect(up).toBeGreaterThan(down);
+ });
+});
+
+describe('recorder mime negotiation', () => {
+ it('takes the best container the browser accepts', () => {
+ expect(pickMime((m) => m === 'video/webm' || m === 'video/mp4')).toBe('video/webm');
+ expect(pickMime((m) => m.startsWith('video/mp4'))).toBe('video/mp4;codecs=avc1');
+ });
+
+ it('reports no support instead of guessing', () => {
+ expect(pickMime(() => false)).toBeNull();
+ });
+
+ it('names the file after the container it got', () => {
+ expect(extensionFor('video/mp4;codecs=avc1')).toBe('mp4');
+ expect(extensionFor('video/webm;codecs=vp9')).toBe('webm');
+ expect(extensionFor(null)).toBe('webm');
+ });
+});
diff --git a/tests/dissolve-shelf.test.js b/tests/dissolve-shelf.test.js
new file mode 100644
index 000000000..a6cd09d96
--- /dev/null
+++ b/tests/dissolve-shelf.test.js
@@ -0,0 +1,77 @@
+/**
+ * The /dissolve shelf and share links (src/dissolve/shelf.js).
+ *
+ * · every shelf model is a real file on disk, not a dead link
+ * · a share link round-trips, and a hostile or stale one falls back safely
+ * · only https or same-origin model links are ever fetched
+ */
+
+import { describe, it, expect } from 'vitest';
+import { existsSync, statSync, readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+import { SHELF, PRESETS, QUALITY, shelfEntry, parseModelUrl, readState, writeState } from '../src/dissolve/shelf.js';
+
+const root = resolve(__dirname, '..');
+
+describe('shelf', () => {
+ it('points every model at a real GLB under public/', () => {
+ for (const item of SHELF) {
+ const file = resolve(root, 'public', item.url.replace(/^\//, ''));
+ expect(existsSync(file), item.url).toBe(true);
+ expect(statSync(file).size, item.url).toBeGreaterThan(1024);
+ // glTF binary magic
+ expect(readFileSync(file).subarray(0, 4).toString('ascii'), item.url).toBe('glTF');
+ }
+ });
+
+ it('has unique ids', () => {
+ expect(new Set(SHELF.map((s) => s.id)).size).toBe(SHELF.length);
+ });
+
+ it('finds an entry by id and nothing for an unknown one', () => {
+ expect(shelfEntry('fox').url).toBe('/avatars/fox.glb');
+ expect(shelfEntry('nope')).toBeNull();
+ });
+
+ it('gives every preset the parameters the engine reads', () => {
+ for (const p of Object.values(PRESETS)) {
+ for (const key of ['spring', 'damp', 'turb', 'arc', 'stagger', 'size', 'bright', 'bloom']) {
+ expect(Number.isFinite(p[key]), key).toBe(true);
+ }
+ }
+ });
+
+ it('keeps every quality tier a power-of-two texture side', () => {
+ for (const q of Object.values(QUALITY)) expect(Math.log2(q.side) % 1).toBe(0);
+ });
+});
+
+describe('parseModelUrl', () => {
+ it('accepts https and same-origin paths', () => {
+ expect(parseModelUrl('https://cdn.example.com/a.glb')).toBe('https://cdn.example.com/a.glb');
+ expect(parseModelUrl('/avatars/fox.glb')).toBe('https://three.ws/avatars/fox.glb');
+ });
+
+ it('refuses everything that is not a safe model link', () => {
+ for (const bad of ['http://evil.example/a.glb', 'javascript:alert(1)', 'data:model/gltf-binary;base64,AAAA', 'file:///etc/passwd', '', null, undefined, 42, 'https://' + 'a'.repeat(3000)]) {
+ expect(parseModelUrl(bad), String(bad).slice(0, 40)).toBeNull();
+ }
+ });
+});
+
+describe('share state', () => {
+ it('round-trips', () => {
+ const s = { a: 'xbot', b: 'fox', preset: 'ember', quality: 'ultra' };
+ expect(readState(writeState(s))).toEqual(s);
+ });
+
+ it('falls back on unknown values instead of trusting the link', () => {
+ const s = readState('?a=<script>&b=ftp://x&p=nuke&q=9000');
+ expect(s).toEqual({ a: 'agent', b: 'fox', preset: 'storm', quality: null });
+ });
+
+ it('keeps a valid external model link', () => {
+ const s = readState('?a=https%3A%2F%2Fcdn.example.com%2Fm.glb');
+ expect(s.a).toBe('https://cdn.example.com/m.glb');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 6beaa7ccd..2dec914cb 100644
--- a/vercel.json
+++ b/vercel.json
@@ -5240,6 +5240,10 @@
"src": "/sonar/?",
"dest": "/sonar.html"
},
+ {
+ "src": "/dissolve/?",
+ "dest": "/dissolve.html"
+ },
{
"src": "/choreograph/?",
"dest": "/choreograph.html"
diff --git a/vite.config.js b/vite.config.js
index f88f608f4..934c3b260 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1085,6 +1085,7 @@ const appConfig = {
animations: resolve(__dirname, 'pages/animations.html'),
gestures: resolve(__dirname, 'pages/gestures.html'),
sonar: resolve(__dirname, 'pages/sonar.html'),
+ dissolve: resolve(__dirname, 'pages/dissolve.html'),
choreograph: resolve(__dirname, 'pages/choreograph.html'),
'character-library': resolve(__dirname, 'pages/character-library.html'),
'sign-language': resolve(__dirname, 'pages/sign-language.html'),