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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(pages): finish the client modules behind brownout, knock, stream and diff
nirholas4625bbf2f405
diff --git a/pages/brownout.html b/pages/brownout.htmlindex d5a95207d..6eae096f4 100644--- a/pages/brownout.html+++ b/pages/brownout.html@@ -260,7 +260,7 @@</section></main>- <script type="module" src="/brownout-page.js"></script>+ <script type="module" src="/src/brownout-page.js"></script><script type="module" src="/i18n.js"></script></body></html>diff --git a/pages/knock.html b/pages/knock.htmlnew file mode 100644index 000000000..97fa677cb--- /dev/null+++ b/pages/knock.html@@ -0,0 +1,285 @@+<!doctype html>+<html lang="en">+ <head>+ <style>/* three.ws hidden-guard - make the `hidden` attribute authoritative; see scripts/lib/hidden-guard.mjs */[hidden]{display:none!important}</style>+ <script>/* three.ws theme boot */(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 name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Knock · three.ws</title>+ <meta name="description" content="Put a price on reaching you. Anyone, human or agent, can pay it to get one message through, and your 3D companion delivers it in person. The USDC settles straight to your wallet." />+ <meta name="theme-color" content="#0a0a0a" />+ <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="/fonts/fonts.css" />+ <link rel="canonical" href="https://three.ws/knock">+ <meta property="og:type" content="website">+ <meta property="og:site_name" content="three.ws">+ <meta property="og:title" content="Knock · three.ws">+ <meta property="og:description" content="Put a price on reaching you. Anyone, human or agent, can pay it to get one message through, and your 3D companion delivers it in person.">+ <meta property="og:url" content="https://three.ws/knock">+ <meta property="og:image" content="https://three.ws/api/page-og?s=main&t=Knock&d=Put+a+price+on+reaching+you.+Anyone%2C+human+or+agent%2C+can+pay+it+to+get+one+message+through%2C+and+your+3D+companion+delivers+it+in+person&p=%2Fknock">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:alt" content="Knock - three.ws">+ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="Knock · three.ws">+ <meta name="twitter:description" content="Put a price on reaching you. Your 3D companion delivers what gets through, in person.">+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=main&t=Knock&d=Put+a+price+on+reaching+you.+Anyone%2C+human+or+agent%2C+can+pay+it+to+get+one+message+through&p=%2Fknock">+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">+ <meta property="og:locale" content="en_US">+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebApplication","name":"three.ws Knock","applicationCategory":"CommunicationApplication","operatingSystem":"Web","description":"A priced, machine-payable door to a person. Pay someone's price to get one message through; their 3D companion delivers it in person.","url":"https://three.ws/knock","offers":{"@type":"Offer","price":"0","priceCurrency":"USD"}}</script>+ <style>+ :root{--bg:#0d0d0d;--bg-2:#141414;--card:#181818;--line:rgba(255,255,255,0.07);--line-2:rgba(255,255,255,0.12);--text:#e7e9ee;--muted:rgba(231,233,238,0.55);--dim:rgba(231,233,238,0.35);--blue:#3b82f6;--green:#22c55e;--amber:#f59e0b;--red:#ef4444;--radius:14px;--skeleton-base:rgba(255,255,255,0.04);--skeleton-sheen:rgba(255,255,255,0.08);}+ [data-theme="light"]{--bg:#f5f5f5;--bg-2:#ffffff;--card:#ffffff;--line:rgba(0,0,0,0.07);--line-2:rgba(0,0,0,0.12);--text:#111;--muted:rgba(0,0,0,0.55);--dim:rgba(0,0,0,0.35);--skeleton-base:rgba(0,0,0,0.04);--skeleton-sheen:rgba(0,0,0,0.08);}+ *{box-sizing:border-box;margin:0;padding:0;}+ html,body{background:var(--bg);color:var(--text);font-family:'Inter',system-ui,sans-serif;min-height:100vh;}+ a{color:inherit;text-decoration:none;}+ .shell{max-width:1080px;margin:0 auto;padding:0 20px 120px;}+ .hero{padding:48px 0 20px;}+ .hero h1{font-size:32px;font-weight:700;letter-spacing:-0.025em;}+ .hero p{color:var(--muted);margin-top:10px;font-size:15px;line-height:1.6;max-width:620px;}+ .hero-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:16px;}+ .btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;font-size:13px;font-weight:600;padding:9px 15px;border-radius:9px;background:var(--card);color:var(--text);border:1px solid var(--line-2);cursor:pointer;transition:border-color .15s,background .15s,transform .1s;font-family:inherit;}+ .btn:hover{border-color:var(--blue);}+ .btn:active{transform:translateY(1px);}+ .btn:focus-visible{outline:2px solid var(--blue);outline-offset:2px;}+ .btn[disabled]{opacity:.5;cursor:not-allowed;}+ .btn.is-ok{border-color:var(--green);color:var(--green);}+ .btn-primary{background:var(--blue);border-color:var(--blue);color:#fff;}+ .btn-primary:hover{background:#2f74e6;}+ .btn-sm{font-size:12px;padding:6px 11px;}+ .btn-danger:hover{border-color:var(--red);color:#fca5a5;}+ section{margin-top:36px;}+ .sec-head{margin-bottom:14px;}+ .sec-head h2{font-size:18px;font-weight:700;letter-spacing:-0.015em;}+ .sec-head p{color:var(--muted);font-size:13.5px;margin-top:5px;line-height:1.55;}+ .card{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:22px;}+ .skeleton{background:linear-gradient(90deg,var(--skeleton-base) 25%,var(--skeleton-sheen) 37%,var(--skeleton-base) 63%);background-size:400% 100%;animation:sheen 1.3s ease infinite;border-radius:8px;height:14px;margin-bottom:10px;}+ @keyframes sheen{0%{background-position:100% 50%}100%{background-position:0 50%}}+ .empty{border:1px dashed var(--line-2);border-radius:var(--radius);padding:34px 22px;text-align:center;color:var(--muted);font-size:13.5px;line-height:1.6;}+ .empty strong{display:block;color:var(--text);font-size:15px;margin-bottom:6px;}+ .error{background:rgba(239,68,68,.1);border:1px solid rgba(239,68,68,.3);color:#fca5a5;border-radius:9px;padding:10px 13px;font-size:13px;margin-top:12px;}+ .ok-note{color:var(--green);font-size:12.5px;margin-top:10px;}+ .grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px;}+ .door-card{display:flex;align-items:center;gap:12px;background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:14px;transition:border-color .15s,transform .1s;}+ .door-card:hover{border-color:var(--blue);transform:translateY(-1px);}+ .door-card:focus-visible{outline:2px solid var(--blue);outline-offset:2px;}+ .face{width:40px;height:40px;border-radius:50%;overflow:hidden;background:var(--bg-2);border:1px solid var(--line-2);flex-shrink:0;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:15px;color:var(--muted);}+ .face::after{content:attr(data-initial);}+ .face:has(img)::after{content:none;}+ .face img{width:100%;height:100%;object-fit:cover;}+ .door-card-body{min-width:0;flex:1;}+ .door-card-name{font-size:14px;font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}+ .door-card-handle{font-size:12px;color:var(--dim);}+ .door-card-headline{font-size:12px;color:var(--muted);margin-top:4px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}+ .door-card-price{font-size:13px;font-weight:700;color:var(--blue);flex-shrink:0;font-variant-numeric:tabular-nums;}+ .door-card-price.is-free{color:var(--green);}+ .stats{display:grid;grid-template-columns:repeat(3,1fr);gap:12px;margin-bottom:18px;}+ .stat{background:var(--bg-2);border:1px solid var(--line);border-radius:11px;padding:14px;}+ .stat b{display:block;font-size:22px;font-weight:700;letter-spacing:-0.02em;font-variant-numeric:tabular-nums;}+ .stat span{font-size:11.5px;color:var(--dim);text-transform:uppercase;letter-spacing:.06em;}+ .fields{display:grid;grid-template-columns:1fr 1fr;gap:14px;}+ label{display:grid;gap:6px;font-size:12.5px;font-weight:600;color:var(--muted);}+ label.wide{grid-column:1/-1;}+ input[type=text],input[type=number],textarea{width:100%;background:var(--bg-2);border:1px solid var(--line-2);border-radius:9px;padding:10px 12px;color:var(--text);font-family:inherit;font-size:14px;transition:border-color .15s;}+ input:focus,textarea:focus{outline:none;border-color:var(--blue);}+ textarea{min-height:82px;resize:vertical;line-height:1.55;}+ .hint{font-weight:400;font-size:11.5px;color:var(--dim);line-height:1.5;}+ .toggle{display:flex;align-items:center;gap:9px;font-size:13.5px;font-weight:600;color:var(--text);cursor:pointer;}+ .toggle input{width:17px;height:17px;accent-color:var(--blue);cursor:pointer;}+ .toggles{display:flex;gap:22px;flex-wrap:wrap;grid-column:1/-1;}+ .share{margin-top:18px;padding-top:18px;border-top:1px solid var(--line);display:grid;gap:10px;}+ .share-row{display:flex;align-items:center;gap:8px;}+ code.inline{flex:1;min-width:0;background:var(--bg-2);border:1px solid var(--line);border-radius:8px;padding:8px 11px;font-size:11.5px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;word-break:break-all;color:var(--muted);}+ .save-row{margin-top:18px;display:flex;align-items:center;gap:12px;flex-wrap:wrap;}+ ul.inbox{list-style:none;display:grid;gap:10px;}+ .knock{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;}+ .knock.is-new{border-color:rgba(59,130,246,.4);box-shadow:0 0 0 1px rgba(59,130,246,.12);}+ .knock-head{display:flex;align-items:center;gap:9px;flex-wrap:wrap;font-size:13.5px;}+ .knock-amount{font-size:11.5px;font-weight:700;color:var(--blue);background:rgba(59,130,246,.12);border-radius:999px;padding:2px 8px;font-variant-numeric:tabular-nums;}+ .knock-amount.is-free{color:var(--muted);background:var(--bg-2);}+ .knock-head time{margin-left:auto;font-size:11.5px;color:var(--dim);}+ .knock-body{margin-top:9px;}+ .knock-subject{font-size:13.5px;font-weight:600;margin-bottom:5px;}+ .knock-body p{color:var(--muted);font-size:13.5px;line-height:1.6;white-space:pre-wrap;word-break:break-word;}+ .knock-link{display:inline-block;margin-top:7px;font-size:12px;color:var(--blue);text-decoration:underline;text-underline-offset:2px;word-break:break-all;}+ .knock-reply{margin-top:10px;padding:9px 12px;border-left:3px solid var(--green);background:var(--bg-2);border-radius:0 8px 8px 0;font-size:13px;color:var(--muted);line-height:1.55;white-space:pre-wrap;}+ .knock-actions{display:flex;gap:7px;flex-wrap:wrap;margin-top:12px;}+ .reply-form{margin-top:12px;display:grid;gap:9px;}+ .reply-row{display:flex;gap:8px;}+ ul.blocks{list-style:none;display:grid;gap:7px;}+ ul.blocks li{display:flex;align-items:center;gap:10px;background:var(--bg-2);border:1px solid var(--line);border-radius:9px;padding:8px 12px;font-size:12.5px;}+ ul.blocks li span{flex:1;min-width:0;word-break:break-all;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;color:var(--muted);}+ .how{display:grid;grid-template-columns:repeat(auto-fit,minmax(220px,1fr));gap:12px;}+ .how div{background:var(--card);border:1px solid var(--line);border-radius:var(--radius);padding:16px;}+ .how b{display:block;font-size:13.5px;margin-bottom:5px;}+ .how p{color:var(--muted);font-size:12.5px;line-height:1.6;}+ @media(max-width:700px){.fields{grid-template-columns:1fr;}.stats{grid-template-columns:1fr;}.hero h1{font-size:26px;}}+ @media(prefers-reduced-motion:reduce){.skeleton{animation:none;}.door-card:hover{transform:none;}}+ </style>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="shell">+ <div class="hero">+ <h1>Knock</h1>+ <p>+ Put a price on reaching you. Anyone, a person or an agent, can pay it to get exactly+ one message through, and your 3D companion walks on screen and delivers it out loud,+ with their name and what they paid. The USDC settles straight to your wallet.+ </p>+ <div class="hero-actions">+ <a class="btn" href="/docs/knock">How it works</a>+ <a class="btn" href="/companion">Your companion</a>+ </div>+ </div>++ <section class="how" aria-label="How Knock works">+ <div><b>1. Set your price</b><p>Anything from $0.001 to $1,000, or free. It is what one message from a stranger costs.</p></div>+ <div><b>2. They pay it</b><p>A person pays with the wallet in their browser. An agent pays over x402 with no human in the loop.</p></div>+ <div><b>3. You hear it in person</b><p>Your companion walks on wherever you are on the site and says who is at the door and what they paid.</p></div>+ </section>++ <section aria-labelledby="owner-h">+ <div class="sec-head">+ <h2 id="owner-h">Your door</h2>+ <p>Shut until you open it. Nothing here is public except the price, your headline, and your greeting.</p>+ </div>++ <div id="owner-loading" class="card" aria-busy="true">+ <div class="skeleton" style="width:35%;height:20px;"></div>+ <div class="skeleton" style="width:70%;"></div>+ <div class="skeleton" style="width:55%;"></div>+ </div>++ <div id="signed-out" class="empty" hidden>+ <strong>Sign in to open your door</strong>+ Your price, your wallet, and everything that comes through it stays private to your account.+ <div class="hero-actions" style="justify-content:center;">+ <a class="btn btn-primary" href="/login?next=/knock">Sign in</a>+ </div>+ </div>++ <div id="owner" class="card" hidden>+ <div class="stats">+ <div class="stat"><b id="stat-pending">0</b><span>Waiting</span></div>+ <div class="stat"><b id="stat-total">0</b><span>All time</span></div>+ <div class="stat"><b id="stat-earned">$0.00</b><span>Earned</span></div>+ </div>++ <div class="fields">+ <div class="toggles">+ <label class="toggle"><input type="checkbox" id="door-open" /> Door open</label>+ <label class="toggle"><input type="checkbox" id="door-listed" /> List me in the directory</label>+ </div>+ <label>Price per knock (USDC)+ <input type="text" id="door-price" inputmode="decimal" placeholder="0.05" />+ <span class="hint">0 makes it free. Otherwise between $0.001 and $1,000.</span>+ </label>+ <label>Knocks per day+ <input type="number" id="door-cap" min="1" max="1000" />+ <span class="hint">After this, the door answers "full for today" and charges nobody.</span>+ </label>+ <label>Solana wallet (paid to you)+ <input type="text" id="door-solana" placeholder="Your USDC address on Solana" />+ <span class="hint">The home chain, and the lane an agent settles on by default.</span>+ </label>+ <label>Base wallet (optional)+ <input type="text" id="door-base" placeholder="0x…" />+ <span class="hint">Offered alongside Solana only when you set it.</span>+ </label>+ <label class="wide">Headline+ <input type="text" id="door-headline" maxlength="120" placeholder="What you are worth interrupting for" />+ </label>+ <label class="wide">Greeting+ <textarea id="door-greeting" maxlength="600" placeholder="What a visitor reads before they write. Tell them what you actually want to hear about."></textarea>+ </label>+ <label>Message length limit+ <input type="number" id="door-max" min="40" max="2000" />+ <span class="hint">Characters. Long enough to be useful, short enough to read.</span>+ </label>+ </div>++ <div class="error" id="settings-error" hidden></div>++ <div class="save-row">+ <button type="button" class="btn btn-primary" id="save">Save door</button>+ <span class="ok-note" id="save-note" hidden></span>+ </div>++ <div class="empty" id="no-handle" hidden style="margin-top:18px;">+ <strong>Pick a username first</strong>+ Your door lives at /knock/<username>, so it needs one.+ <div class="hero-actions" style="justify-content:center;"><a class="btn" href="/dashboard/settings">Choose a username</a></div>+ </div>++ <div class="share" id="share-block" hidden>+ <div class="share-row">+ <code class="inline" id="share-url"></code>+ <button type="button" class="btn btn-sm" id="copy-share" data-copy="">Copy link</button>+ </div>+ <div class="share-row">+ <code class="inline" id="endpoint-url"></code>+ <button type="button" class="btn btn-sm" id="copy-endpoint" data-copy="">Copy endpoint</button>+ </div>+ <span class="hint">The first is for people. The second is what an agent pays.</span>+ </div>+ </div>+ </section>++ <section aria-labelledby="inbox-h">+ <div class="sec-head">+ <h2 id="inbox-h">Who knocked</h2>+ <p>Every message that made it through, and what it was worth. Replying writes back to the receipt link the sender already holds.</p>+ </div>+ <div id="inbox-loading" class="card" aria-busy="true">+ <div class="skeleton" style="width:40%;"></div>+ <div class="skeleton" style="width:80%;"></div>+ </div>+ <div id="inbox-empty" class="empty" hidden>+ <strong>Nobody has knocked yet</strong>+ <span data-msg>Open your door and share the link. Anything that comes through lands here and gets announced by your companion.</span>+ </div>+ <ul class="inbox" id="inbox" hidden></ul>+ <div class="hero-actions" style="justify-content:center;">+ <button type="button" class="btn" id="load-more" hidden>Load more</button>+ </div>+ </section>++ <section aria-labelledby="blocks-h">+ <div class="sec-head">+ <h2 id="blocks-h">Blocked</h2>+ <p>Blocked senders get the same answer a shut door gives, so they cannot tell it was them.</p>+ </div>+ <div id="blocks-empty" class="empty" hidden><strong>Nobody blocked</strong>Block a sender from any knock in the list above.</div>+ <ul class="blocks" id="blocks" hidden></ul>+ </section>++ <section aria-labelledby="dir-h">+ <div class="sec-head">+ <h2 id="dir-h">Open doors</h2>+ <p>Everyone reachable right now, cheapest first.</p>+ </div>+ <div id="directory-loading" class="card" aria-busy="true">+ <div class="skeleton" style="width:30%;"></div>+ <div class="skeleton" style="width:60%;"></div>+ </div>+ <div id="directory-empty" class="empty" hidden>+ <strong>No open doors yet</strong>+ <span data-msg>Be the first. Open yours above and it appears here.</span>+ </div>+ <div class="grid" id="directory" hidden></div>+ </section>+ </main>++ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/src/knock/page.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/pages/stream.html b/pages/stream.htmlnew file mode 100644index 000000000..03da22458--- /dev/null+++ b/pages/stream.html@@ -0,0 +1,157 @@+<!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 name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Progressive Avatars · three.ws</title>+ <meta name="description" content="A 3D avatar should not be a blank box until the last byte arrives. A3S packs a GLB into layers whose first 50 KB is already a complete, skinned, spec-valid avatar, refined in place over plain HTTP range requests." />+ <link rel="canonical" href="https://three.ws/stream" />+ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:url" content="https://three.ws/stream" />+ <meta property="og:title" content="Progressive Avatars · three.ws" />+ <meta property="og:description" content="The first 50 KB of an A3S stream is already a complete, skinned avatar. Watch it race a classic GLB load." />+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Progressive+Avatars&d=The+first+50+KB+is+already+a+complete%2C+skinned+avatar.&p=%2Fstream" />+ <meta property="og:image:width" content="1200" />+ <meta property="og:image:height" content="630" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Progressive Avatars · three.ws" />+ <meta name="twitter:description" content="The first 50 KB of an A3S stream is already a complete, skinned avatar. Watch it race a classic GLB load." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Progressive+Avatars&d=The+first+50+KB+is+already+a+complete%2C+skinned+avatar.&p=%2Fstream" />+ <meta name="theme-color" content="#0a0a0a" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="stylesheet" href="/fonts/fonts.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <style>+ .st-shell { max-width: 1180px; margin: 0 auto; padding: clamp(20px, 5vw, 44px) 18px 80px; }+ .st-hero { margin-bottom: 26px; }+ .st-kicker { display: inline-flex; align-items: center; gap: 8px; font-size: .72rem; font-weight: 600; letter-spacing: .04em; text-transform: uppercase; color: var(--ink-dim, #888); margin: 0 0 10px; }+ .st-kicker::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: var(--success, #34d399); box-shadow: 0 0 8px color-mix(in srgb, var(--success, #34d399) 60%, transparent); }+ .st-title { font-family: var(--font-display, system-ui); font-size: clamp(1.7rem, 4.4vw, 2.4rem); font-weight: 700; color: var(--ink-bright, #fff); margin: 0 0 10px; line-height: 1.08; }+ .st-sub { color: var(--ink-dim, #999); font-size: .98rem; line-height: 1.65; margin: 0; max-width: 68ch; }+ .st-sub code { font-family: var(--font-mono, ui-monospace, monospace); font-size: .88em; background: color-mix(in srgb, var(--ink, #e8e8e8) 8%, transparent); padding: 1px 5px; border-radius: 4px; }++ .st-controls { display: flex; flex-wrap: wrap; gap: 14px; align-items: flex-end; margin: 26px 0 12px; }+ .st-field { display: flex; flex-direction: column; gap: 6px; }+ .st-field span { font-size: .72rem; text-transform: uppercase; letter-spacing: .05em; color: var(--ink-dim, #888); font-weight: 600; }+ .st-field select { background: color-mix(in srgb, var(--ink, #e8e8e8) 6%, transparent); color: var(--ink, #e8e8e8); border: 1px solid color-mix(in srgb, var(--ink, #e8e8e8) 16%, transparent); border-radius: 9px; padding: 9px 12px; font-size: .9rem; min-width: 160px; transition: border-color .18s ease, background .18s ease; }+ .st-field select:hover { border-color: color-mix(in srgb, var(--ink, #e8e8e8) 30%, transparent); }+ .st-field select:focus-visible { outline: 2px solid var(--accent, #6ea8ff); outline-offset: 2px; }+ .st-run { background: var(--ink-bright, #fff); color: #0a0a0a; border: 0; border-radius: 9px; padding: 10px 20px; font-size: .9rem; font-weight: 650; cursor: pointer; transition: transform .16s ease, opacity .16s ease, box-shadow .16s ease; }+ .st-run:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 6px 20px rgba(0,0,0,.32); }+ .st-run:active:not(:disabled) { transform: translateY(0); }+ .st-run:focus-visible { outline: 2px solid var(--accent, #6ea8ff); outline-offset: 3px; }+ .st-run:disabled { opacity: .55; cursor: progress; }+ .st-note { color: var(--ink-dim, #888); font-size: .82rem; line-height: 1.55; margin: 0 0 22px; max-width: 76ch; }++ .st-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 18px; }+ .st-panel { border: 1px solid color-mix(in srgb, var(--ink, #e8e8e8) 12%, transparent); border-radius: 14px; padding: 14px; background: color-mix(in srgb, var(--ink, #e8e8e8) 3%, transparent); transition: border-color .3s ease, box-shadow .3s ease; }+ .st-panel[data-state='live'] { border-color: color-mix(in srgb, var(--accent, #6ea8ff) 45%, transparent); }+ .st-panel[data-state='done'] { border-color: color-mix(in srgb, var(--success, #34d399) 40%, transparent); box-shadow: 0 0 0 1px color-mix(in srgb, var(--success, #34d399) 12%, transparent); }+ .st-panel-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; margin-bottom: 10px; }+ .st-panel-head h2 { font-size: .96rem; font-weight: 650; margin: 0; color: var(--ink-bright, #fff); }+ .st-status { font-size: .7rem; text-transform: uppercase; letter-spacing: .05em; color: var(--ink-dim, #888); font-variant-numeric: tabular-nums; }+ .st-panel[data-state='done'] .st-status { color: var(--success, #34d399); }+ .st-stage { position: relative; aspect-ratio: 1 / 1; border-radius: 10px; overflow: hidden; background: radial-gradient(ellipse at 50% 15%, color-mix(in srgb, var(--ink, #e8e8e8) 8%, transparent), transparent 70%); }+ .st-stage canvas { display: block; width: 100%; height: 100%; }+ .st-bar { height: 3px; border-radius: 2px; background: color-mix(in srgb, var(--ink, #e8e8e8) 10%, transparent); margin: 10px 0 12px; overflow: hidden; }+ .st-bar i { display: block; height: 100%; width: 0; border-radius: 2px; background: var(--accent, #6ea8ff); transition: width .12s linear; }+ .st-panel[data-state='done'] .st-bar i { background: var(--success, #34d399); }+ .st-metrics { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin: 0 0 12px; }+ .st-metrics div { display: flex; flex-direction: column; gap: 3px; }+ .st-metrics dt { font-size: .66rem; text-transform: uppercase; letter-spacing: .05em; color: var(--ink-dim, #888); }+ .st-metrics dd { margin: 0; font-size: 1.02rem; font-weight: 650; color: var(--ink-bright, #fff); font-variant-numeric: tabular-nums; }+ .st-log { list-style: none; margin: 0; padding: 8px 10px; height: 108px; overflow-y: auto; font-family: var(--font-mono, ui-monospace, monospace); font-size: .72rem; line-height: 1.7; color: var(--ink-dim, #888); background: color-mix(in srgb, var(--ink, #e8e8e8) 4%, transparent); border-radius: 8px; scrollbar-width: thin; }+ .st-log li[data-tone='good'] { color: var(--success, #34d399); }+ .st-log li[data-tone='bad'] { color: var(--danger, #f87171); }+ .st-verdict { margin: 22px 0 0; font-size: 1.02rem; font-weight: 600; color: var(--ink-bright, #fff); min-height: 1.5em; }++ .st-how { margin-top: 52px; border-top: 1px solid color-mix(in srgb, var(--ink, #e8e8e8) 10%, transparent); padding-top: 30px; }+ .st-how h2 { font-size: 1.15rem; margin: 0 0 14px; color: var(--ink-bright, #fff); }+ .st-how p { color: var(--ink-dim, #999); font-size: .93rem; line-height: 1.7; max-width: 74ch; margin: 0 0 14px; }+ .st-how pre { background: color-mix(in srgb, var(--ink, #e8e8e8) 5%, transparent); border: 1px solid color-mix(in srgb, var(--ink, #e8e8e8) 10%, transparent); border-radius: 10px; padding: 14px 16px; overflow-x: auto; font-size: .8rem; line-height: 1.65; }+ .st-how code { font-family: var(--font-mono, ui-monospace, monospace); }+ .st-how a { color: var(--ink, #e8e8e8); }+ .st-layers { display: grid; grid-template-columns: repeat(auto-fit, minmax(190px, 1fr)); gap: 12px; margin: 18px 0 22px; }+ .st-layer { border: 1px solid color-mix(in srgb, var(--ink, #e8e8e8) 12%, transparent); border-radius: 11px; padding: 13px 14px; }+ .st-layer b { display: block; font-size: .72rem; text-transform: uppercase; letter-spacing: .05em; color: var(--ink-dim, #888); font-weight: 600; margin-bottom: 6px; }+ .st-layer span { display: block; font-size: .88rem; color: var(--ink, #e8e8e8); line-height: 1.55; }+ @media (prefers-reduced-motion: reduce) { .st-run, .st-bar i, .st-panel { transition: none; } }+ </style>+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="st-shell">+ <section class="st-hero">+ <p class="st-kicker">Progressive delivery</p>+ <h1 class="st-title">A 3D avatar should not be a blank box</h1>+ <p class="st-sub">+ A GLB is atomic: nothing renders until the last byte lands. On a slow connection that is+ several seconds of empty frame on every embed. <strong>A3S</strong> repacks the same asset+ into nested layers, ordered so that any byte-prefix of the file is a complete, skinned,+ spec-valid avatar. The first layer is typically 4 to 17 percent of the original. Everything+ after it refines the mesh already on screen, over ordinary+ <code>Range</code> requests that any CDN already serves.+ </p>+ </section>++ <div id="stream-root"></div>++ <section class="st-how">+ <h2>How a prefix can be a whole avatar</h2>+ <p>+ The packer simplifies the mesh <em>successively</em>, finest to coarsest, so the vertices+ surviving at each level are a strict subset of the level below it. Rank every vertex by the+ coarsest level it reaches, sort the vertex buffer by that rank, and each level's vertices+ become a contiguous prefix. A refinement then only ever appends bytes, never rewrites them.+ Skinning rides along untouched, because a mesh simplifier only emits a new index buffer over+ the vertex array it was given.+ </p>+ <div class="st-layers">+ <div class="st-layer"><b>Layer 0</b><span>Coarse mesh, full skeleton, thumbnail textures. A valid GLB on its own.</span></div>+ <div class="st-layer"><b>Layer 1</b><span>New vertices, finer indices, and the animation clips.</span></div>+ <div class="st-layer"><b>Layer 2</b><span>More geometry, applied in place on the live scene.</span></div>+ <div class="st-layer"><b>Layer 3</b><span>Full detail and full-resolution textures.</span></div>+ </div>+ <p>+ Because layer 0 is a real GLB and not a custom blob, you can cut it out with nothing but+ <code>curl</code> and open it in any glTF tool:+ </p>+ <pre><code>npx @three-ws/avatar-stream pack avatar.glb -o avatar.a3s+npx @three-ws/avatar-stream inspect avatar.a3s+npx @three-ws/avatar-stream extract avatar.a3s -o preview.glb # a 50 KB avatar+npx @three-ws/avatar-stream verify avatar.a3s --deep # replays every layer</code></pre>+ <p>+ In a browser, the reader takes one ranged request to first frame and refines in the+ background, mutating the geometry already on screen rather than rebuilding the scene:+ </p>+ <pre><code>import { A3SPlayer } from '@three-ws/avatar-stream/three';++const player = await A3SPlayer.load('/api/avatar-stream?src=/avatars/michelle.glb', {+ THREE, GLTFLoader,+ onLayer: (l) => console.log(`level ${l.level}: ${l.triangleCount} triangles`),+});+scene.add(player.scene); // already skinned and posed+await player.refine(); // detail arrives without touching the camera or pose</code></pre>+ <p>+ The format is documented in+ <a href="https://github.com/nirholas/three.ws/blob/main/specs/AVATAR_STREAM.md">specs/AVATAR_STREAM.md</a>+ and the endpoint serving these streams is+ <a href="/api/avatar-stream?src=/avatars/michelle.glb&format=json">/api/avatar-stream</a>,+ which will hand you the layer table as JSON.+ </p>+ </section>+ </main>++ <script type="module" src="/src/stream-demo.js"></script>+ <div id="footer-container"></div>+ <script src="/footer.js"></script>+ <script type="module" src="/i18n.js"></script>+ </body>+</html>diff --git a/src/brownout-page.js b/src/brownout-page.jsnew file mode 100644index 000000000..87a9fd083--- /dev/null+++ b/src/brownout-page.js@@ -0,0 +1,242 @@+// /brownout: the degradation registry, its proof receipts, and the reader's+// own request.+//+// The live panel is the part worth having: it reads the provenance headers off+// this page's OWN call to /api/brownout and tells the visitor how their request,+// a moment ago, was actually served. A claim about resilience is cheap; the+// same claim measured on the request you just made is not.++const TIER_COPY = {+ live: 'came off the wire during your request',+ cache: 'a cache hit inside its intended lifetime',+ stale: 'older than intended, because an upstream could not answer',+ fallback: 'a different provider or method answered',+};++const VERDICT_LABEL = {+ pass: 'proven',+ fail: 'failed',+ not_exercised: 'not exercised',+ unrun: 'not yet run',+};++/**+ * Parse the `x-brownout` summary and `x-brownout-trace` breakdown.+ * A missing header is a real state (nothing was recorded), not an error.+ */+function parseProvenance(headers) {+ const summary = headers.get('x-brownout') || '';+ const trace = headers.get('x-brownout-trace') || '';+ if (!summary) return null;+ const fields = {};+ for (const pair of summary.split(';')) {+ const [k, v] = pair.split('=');+ if (k) fields[k.trim()] = (v ?? '').trim();+ }+ const sources = trace+ ? trace.split(',').map((entry) => {+ const parts = entry.split(';').map((p) => p.trim());+ return {+ name: parts[0] || '',+ outcome: (parts.find((p) => p.startsWith('o=')) || 'o=').slice(2),+ ms: Number((parts.find((p) => p.startsWith('t=')) || 't=0').slice(2)) || 0,+ };+ })+ : [];+ return {+ tier: fields.tier || null,+ degraded: fields.degraded === '1',+ ok: Number(fields.ok || 0),+ failed: Number(fields.failed || 0),+ ms: Number(fields.ms || 0),+ sources,+ };+}++const el = (tag, className, text) => {+ const node = document.createElement(tag);+ if (className) node.className = className;+ if (text != null) node.textContent = text;+ return node;+};++/** Whole seconds up to a minute, then minutes, then hours. Ages here span both. */+function humanAge(ms) {+ if (!Number.isFinite(ms) || ms < 0) return null;+ const s = Math.round(ms / 1000);+ if (s < 60) return `${s}s`;+ const m = Math.round(s / 60);+ if (m < 60) return `${m}m`;+ return `${Math.round(m / 60)}h`;+}++function renderLivePanel(prov) {+ const panel = document.getElementById('bo-live-panel');+ const tierEl = document.getElementById('bo-live-tier');+ const body = document.getElementById('bo-live-body');+ if (!panel || !prov) return;++ const tier = prov.tier || 'none';+ tierEl.dataset.tier = tier;+ tierEl.textContent = tier;++ const parts = [];+ parts.push(+ `The request that loaded this list touched ${prov.ok + prov.failed} source${prov.ok + prov.failed === 1 ? '' : 's'} ` ++ `in ${prov.ms}ms, and what you are reading ${TIER_COPY[tier] || 'was served from an unknown tier'}.`,+ );+ if (prov.failed > 0) {+ parts.push(+ `${prov.failed} of them did not answer, and you still got a page: that is the whole point, and it is why the header exists.`,+ );+ }+ body.textContent = parts.join(' ');++ if (prov.sources.length) {+ const trace = el('div', 'bo-trace');+ for (const s of prov.sources) trace.appendChild(traceRow(s));+ panel.appendChild(trace);+ }+ panel.hidden = false;+}++function traceRow(source) {+ const ok = source.outcome === 'ok' ? '1' : source.outcome === 'stale' ? 'stale' : '0';+ const row = el('div', 'bo-trace-row');+ row.dataset.ok = ok;+ row.appendChild(el('span', 'bo-trace-name', source.name));+ row.appendChild(el('span', 'bo-trace-out', source.outcome));+ row.appendChild(el('span', 'bo-trace-ms', `${source.ms}ms`));+ return row;+}++function renderStats(data) {+ const host = document.getElementById('bo-stats');+ if (!host) return;+ const stat = (value, label) => {+ const node = el('div', 'bo-stat');+ node.appendChild(el('b', null, String(value)));+ node.appendChild(el('span', null, label));+ return node;+ };+ host.replaceChildren();+ host.appendChild(stat(`${data.proven}/${data.total}`, 'fallbacks proven'));+ const failed = data.contracts.filter((c) => c.proof && c.proof.verdict !== 'pass').length;+ host.appendChild(stat(failed, failed === 1 ? 'contract not proven' : 'contracts not proven'));+ const refusals = data.contracts.reduce((n, c) => n + (c.proof?.failed_sources || 0), 0);+ host.appendChild(stat(refusals, 'upstream refusals survived'));+ if (data.last_proof_at) {+ const age = humanAge(Date.now() - Date.parse(data.last_proof_at));+ host.appendChild(stat(age ? `${age} ago` : 'unknown', 'last proof run'));+ }+}++function renderContract(contract) {+ const proof = contract.proof;+ const verdict = proof?.verdict || 'unrun';+ const card = el('article', 'bo-card');+ card.dataset.verdict = verdict;++ const head = el('div', 'bo-card-head');+ const titles = el('div');+ titles.appendChild(el('h3', null, contract.title));+ titles.appendChild(el('div', 'bo-endpoint', `${contract.endpoint}${contract.surface ? ` · ${contract.surface}` : ''}`));+ head.appendChild(titles);+ const badge = el('span', 'bo-verdict', VERDICT_LABEL[verdict] || verdict);+ badge.dataset.verdict = verdict;+ head.appendChild(badge);+ card.appendChild(head);++ const breaks = Object.entries(contract.breaks || {});+ if (breaks.length) {+ const line = el('p', 'bo-break');+ line.appendChild(document.createTextNode('We break '));+ breaks.forEach(([name, spec], i) => {+ if (i) line.appendChild(document.createTextNode(', '));+ line.appendChild(el('code', null, `${name} → ${spec}`));+ });+ if (proof) {+ line.appendChild(+ document.createTextNode(+ `, and the endpoint answered ${proof.status}${proof.tier ? ` from the ${proof.tier} tier` : ''}.`,+ ),+ );+ } else {+ line.appendChild(document.createTextNode('. This image has not run the prover yet.'));+ }+ card.appendChild(line);+ }++ if (proof?.trace?.length) {+ const trace = el('div', 'bo-trace');+ for (const s of proof.trace) trace.appendChild(traceRow(s));+ card.appendChild(trace);+ }++ if (proof?.problems?.length) {+ const list = el('ul', 'bo-problems');+ for (const p of proof.problems) list.appendChild(el('li', null, p));+ card.appendChild(list);+ }++ if (contract.why) card.appendChild(el('p', 'bo-why', contract.why));+ return card;+}++function renderError(message) {+ const host = document.getElementById('bo-results');+ if (!host) return;+ host.replaceChildren();+ const card = el('article', 'bo-card');+ card.dataset.verdict = 'fail';+ card.appendChild(el('h3', null, 'The registry could not be loaded'));+ card.appendChild(el('p', 'bo-why', message));+ const links = el('div', 'bo-links');+ const retry = el('a', null, 'Try again');+ retry.href = '/brownout';+ links.appendChild(retry);+ const raw = el('a', null, 'Open the JSON directly');+ raw.href = '/api/brownout';+ links.appendChild(raw);+ card.appendChild(links);+ host.appendChild(card);+}++async function main() {+ const status = document.getElementById('bo-status');+ let res;+ try {+ res = await fetch('/api/brownout', { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(15_000) });+ } catch (err) {+ if (status) status.textContent = 'The registry could not be reached.';+ renderError(`The request did not complete: ${err?.message || err}. The registry is static, so this is almost certainly a network problem at your end.`);+ return;+ }++ // Read the provenance of THIS request before anything else: it is the most+ // honest demonstration on the page, and it costs nothing.+ renderLivePanel(parseProvenance(res.headers));++ if (!res.ok) {+ if (status) status.textContent = 'The registry answered with an error.';+ renderError(`The registry endpoint answered ${res.status}.`);+ return;+ }++ const data = await res.json();+ renderStats(data);++ const host = document.getElementById('bo-results');+ host.replaceChildren();+ if (!data.contracts?.length) {+ host.appendChild(el('p', 'bo-why', 'No degradation contracts are declared yet.'));+ if (status) status.textContent = 'No contracts declared.';+ return;+ }+ const grid = el('div', 'bo-grid');+ for (const contract of data.contracts) grid.appendChild(renderContract(contract));+ host.appendChild(grid);+ if (status) status.textContent = `${data.contracts.length} degradation contracts listed.`;+}++main();diff --git a/src/model-diff.js b/src/model-diff.jsnew file mode 100644index 000000000..dc3bd6106--- /dev/null+++ b/src/model-diff.js@@ -0,0 +1,617 @@+// Model Diff page controller (/diff).+//+// Three jobs, in the order the visitor experiences them:+// 1. Get two models. Drag-drop, file picker, a pasted URL, or an example pair.+// 2. Compare them. The whole engine (@three-ws/glb-diff) runs here in the tab.+// 3. Show the result twice over: as a change set you can read and copy, and as+// a 3D scene where clicking a row frames the object it names.+//+// The privacy claim in the copy constrains the code, as it does on /rig-doctor:+// a dropped file is read with the File API and compared in this tab. It is never+// posted anywhere. A model given as a URL is a different matter and the page+// says so: it is fetched through the same-origin proxy at /api/glb, because an+// arbitrary CDN will not send an Access-Control-Allow-Origin header and the+// browser would refuse the read outright.+//+// The 3D stage is imported lazily. three.js plus the glTF loader stack is the+// heaviest thing on this page and the report is useful without it, so the+// import starts only once a model is actually in hand.++import { describeModel, diffDescriptions, formatBytes, formatMarkdown, SEVERITY_MEANING } from '@three-ws/glb-diff';++const $ = (id) => document.getElementById(id);++// Real models this site already serves, chosen so the four states a visitor can+// land in are each one click away: a rig that lost its skeleton, two unrelated+// characters, two close siblings, and a pair with nothing between them.+const EXAMPLE_PAIRS = [+ {+ label: 'A rig, then the same pose unrigged',+ a: '/avatars/default.glb',+ b: '/avatars/mannequin.glb',+ title: 'Every skeleton and clip gone: the breaking case',+ },+ {+ label: 'Two different characters',+ a: '/avatars/xbot.glb',+ b: '/avatars/michelle.glb',+ title: 'Different meshes, different clips, overlapping joint names',+ },+ {+ label: 'Sibling avatars',+ a: '/avatars/realistic-male.glb',+ b: '/avatars/realistic-female.glb',+ title: 'Same rig family, different geometry and textures',+ },+ {+ label: 'Nothing changed',+ a: '/avatars/cesium-man.glb',+ b: '/avatars/cesium-man.glb',+ title: 'What a clean comparison looks like',+ },+];++const SECTION_ORDER = [+ ['skins', 'Skeletons'],+ ['animations', 'Animations'],+ ['meshes', 'Meshes'],+ ['nodes', 'Nodes'],+ ['materials', 'Materials'],+ ['textures', 'Textures'],+];++const TOTAL_LABEL = {+ vertices: 'Vertices',+ triangles: 'Triangles',+ nodes: 'Nodes',+ meshes: 'Meshes',+ materials: 'Materials',+ textures: 'Textures',+ animations: 'Animations',+ skins: 'Skeletons',+ joints: 'Joints',+ scenes: 'Scenes',+ textureBytes: 'Texture bytes',+ sizeBytes: 'File size',+};++const state = {+ a: null,+ b: null,+ changeset: null,+ stage: null,+ stagePromise: null,+ mode: 'overlay',+ focused: null,+};++// ── Small helpers ────────────────────────────────────────────────────────────++function esc(value) {+ return String(value ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);+}++function num(value) {+ return Number(value || 0).toLocaleString();+}++function signed(value, isBytes) {+ if (value === 0) return '0';+ const body = isBytes ? formatBytes(Math.abs(value)) : num(Math.abs(value));+ return `${value > 0 ? '+' : '-'}${body}`;+}++function fieldText(change) {+ const opaque = { geometry: 'vertex data changed', pixels: 'image data changed', inverseBindMatrices: 'bind pose changed' };+ if (opaque[change.field]) return `${opaque[change.field]}${change.note ? ` (${change.note})` : ''}`;+ const show = (value) => {+ if (value === null || value === undefined) return 'none';+ if (Array.isArray(value)) return value.length > 4 ? `[${value.slice(0, 4).join(', ')}, +${value.length - 4}]` : `[${value.join(', ')}]`;+ if (typeof value === 'object') return JSON.stringify(value);+ return String(value);+ };+ return `${show(change.a)} to ${show(change.b)}${change.note ? ` (${change.note})` : ''}`;+}++// ── Loading a side ───────────────────────────────────────────────────────────++// Same-origin models are fetched directly. Anything else goes through the+// site's own GLB proxy, which exists precisely because a third-party CDN's CORS+// policy would otherwise make the model unreadable from a browser.+function proxied(url) {+ try {+ const resolved = new URL(url, location.href);+ if (resolved.origin === location.origin) return resolved.href;+ return `/api/glb?src=${encodeURIComponent(resolved.href)}`;+ } catch {+ return null;+ }+}++function setSlotState(role, slotState) {+ $(`dx-slot-${role}`).dataset.state = slotState;+}++function showSlotError(role, message) {+ const el = $(`dx-error-${role}`);+ el.textContent = message;+ el.hidden = !message;+ setSlotState(role, message ? 'error' : 'idle');+}++async function loadSide(role, bytes, name, sourceUrl) {+ showSlotError(role, '');+ setSlotState(role, 'loading');+ $(`dx-name-${role}`).textContent = name;+ $(`dx-meta-${role}`).textContent = formatBytes(bytes.byteLength);++ let description;+ try {+ description = await describeModel(new Uint8Array(bytes), { name });+ } catch (err) {+ showSlotError(role, `Not a readable glTF/GLB: ${err?.message || 'could not parse the file'}`);+ state[role] = null;+ renderReport();+ return;+ }++ state[role] = { description, bytes, name, url: sourceUrl || null };+ setSlotState(role, 'loaded');+ $(`dx-meta-${role}`).textContent =+ `${formatBytes(bytes.byteLength)} - ${num(description.totals.triangles)} tris - ${num(description.totals.joints)} joints`;++ const stage = await ensureStage();+ if (stage) {+ try {+ await stage.setModel(role, bytes);+ } catch (err) {+ // The report is the product; a viewport that refuses one exotic model+ // must not take the comparison down with it.+ showSlotError(role, `Compared fine, but the 3D view could not load it: ${err?.message || 'renderer error'}`);+ }+ }+ compare();+ syncShareUrl();+}++async function loadFromFile(role, file) {+ if (!file) return;+ try {+ const bytes = await file.arrayBuffer();+ await loadSide(role, bytes, file.name);+ } catch (err) {+ showSlotError(role, `Could not read the file: ${err?.message || 'unknown error'}`);+ }+}++async function loadFromUrl(role, rawUrl) {+ const url = String(rawUrl || '').trim();+ if (!url) return;+ const target = proxied(url);+ if (!target) {+ showSlotError(role, 'That does not look like a URL.');+ return;+ }+ setSlotState(role, 'loading');+ $(`dx-name-${role}`).textContent = 'Fetching...';+ try {+ const res = await fetch(target, { signal: AbortSignal.timeout(30_000) });+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const bytes = await res.arrayBuffer();+ const name = url.split('/').filter(Boolean).pop() || url;+ await loadSide(role, bytes, name, url);+ } catch (err) {+ $(`dx-name-${role}`).textContent = role === 'a' ? 'Drop the baseline .glb' : 'Drop the candidate .glb';+ showSlotError(role, `Could not fetch that model: ${err?.message || 'network error'}`);+ }+}++// ── The comparison ───────────────────────────────────────────────────────────++function compare() {+ if (!state.a || !state.b) {+ renderReport();+ return;+ }+ renderSkeleton();+ // Yield one frame so the skeleton actually paints before the comparison+ // takes the main thread. Without it the placeholder never appears and a+ // heavy pair looks like a frozen page.+ requestAnimationFrame(() => {+ state.changeset = diffDescriptions(state.a.description, state.b.description);+ renderReport();+ if (state.stage) {+ state.stage.applyChangeSet(state.changeset);+ $('dx-stage-bar').hidden = false;+ $('dx-legend').hidden = false;+ $('dx-play-wrap').hidden = !state.stage.hasClips();+ }+ });+}++function renderSkeleton() {+ $('dx-report').innerHTML =+ '<div class="dx-card"><div class="dx-skeleton"><i></i><i></i><i></i><i></i></div></div>';+}++function renderReport() {+ const host = $('dx-report');+ if (!state.a || !state.b) {+ const waiting = state.a || state.b ? 'One more to go.' : 'Drop a file on each side, paste two URLs, or pick an example pair.';+ host.innerHTML = `<div class="dx-card"><div class="dx-empty"><strong>Load two models</strong>${esc(waiting)} The comparison runs on your machine.</div></div>`;+ return;+ }+ const changes = state.changeset;+ if (!changes) return;++ host.innerHTML = [+ verdictHtml(changes),+ totalsHtml(changes),+ sectionsHtml(changes),+ actionsHtml(changes),+ ].join('');++ wireReport();+}++function verdictHtml(changes) {+ const s = changes.summary;+ const counts = changes.identical+ ? 'no differences'+ : `+${s.added} / -${s.removed} / ~${s.modified} / renamed ${s.renamed} / moved ${s.moved}`;+ const highlights = changes.highlights+ .map((h) => `<li class="dx-highlight dx-sev-${esc(h.severity)}">${esc(h.text)}</li>`)+ .join('');+ return `+ <div class="dx-verdict dx-sev-${esc(changes.severity)}">+ <div class="dx-verdict-top">+ <span class="dx-verdict-level">${esc(changes.severity)}</span>+ <span class="dx-verdict-counts">${esc(counts)}</span>+ </div>+ <p class="dx-verdict-why">${esc(SEVERITY_MEANING[changes.severity])}</p>+ ${highlights ? `<ul class="dx-highlights">${highlights}</ul>` : ''}+ </div>`;+}++function totalsHtml(changes) {+ const rows = Object.entries(changes.totals).filter(([, v]) => v.delta !== 0);+ if (!rows.length) return '';+ const body = rows+ .map(([key, v]) => {+ const isBytes = key.endsWith('Bytes');+ const fmt = isBytes ? formatBytes : num;+ const cls = v.delta > 0 ? 'dx-up' : 'dx-down';+ const pct = v.pct === null || v.pct === 0 ? '' : ` (${v.pct > 0 ? '+' : ''}${v.pct}%)`;+ return `<tr><td>${esc(TOTAL_LABEL[key] || key)}</td><td class="dx-num">${esc(fmt(v.a))}</td><td class="dx-num">${esc(fmt(v.b))}</td><td class="dx-num ${cls}">${esc(signed(v.delta, isBytes) + pct)}</td></tr>`;+ })+ .join('');+ return `+ <div class="dx-card">+ <div class="dx-card-head"><span>Totals</span></div>+ <table class="dx-totals">+ <thead><tr><th>metric</th><th class="dx-num">before</th><th class="dx-num">after</th><th class="dx-num">delta</th></tr></thead>+ <tbody>${body}</tbody>+ </table>+ </div>`;+}++function rowHtml({ mark, markClass, name, detail, fields, path }) {+ const inner = `+ <span class="dx-mark ${markClass}" aria-hidden="true">${mark}</span>+ <span>+ <span class="dx-row-name">${esc(name)}</span>+ ${detail ? ` <span class="dx-row-detail">${esc(detail)}</span>` : ''}+ ${fields && fields.length ? `<ul class="dx-fields">${fields.map((f) => `<li class="dx-field"><b>${esc(f.field)}</b> ${esc(fieldText(f))}</li>`).join('')}</ul>` : ''}+ </span>`;+ if (path) {+ return `<li><button type="button" class="dx-row" data-path="${esc(path)}" aria-pressed="false" title="Frame this node in the viewer">${inner}</button></li>`;+ }+ return `<li class="dx-row">${inner}</li>`;+}++function sectionsHtml(changes) {+ const blocks = SECTION_ORDER.map(([key, label]) => {+ const section = changes.sections[key];+ if (!section || !section.changed) return '';+ const isNodes = key === 'nodes';+ const rows = [+ ...section.removed.map((item) =>+ rowHtml({ mark: '-', markClass: 'dx-mark-del', name: item.name, detail: item.detail, path: isNodes ? item.name : null }),+ ),+ ...section.added.map((item) =>+ rowHtml({ mark: '+', markClass: 'dx-mark-add', name: item.name, detail: item.detail, path: isNodes ? item.name : null }),+ ),+ ...section.renamed.map((item) =>+ rowHtml({ mark: 'R', markClass: 'dx-mark-ren', name: `${item.from} to ${item.to}`, path: isNodes ? item.to : null }),+ ),+ ...(section.moved || []).map((item) =>+ rowHtml({ mark: 'M', markClass: 'dx-mark-mov', name: `${item.from} to ${item.to}`, detail: 'reparented', path: item.to }),+ ),+ ...section.modified.map((item) =>+ rowHtml({+ mark: '~',+ markClass: 'dx-mark-mod',+ name: item.name,+ detail: item.from && item.from !== item.name ? `was ${item.from}` : '',+ fields: item.changes,+ path: isNodes ? item.name : null,+ }),+ ),+ ].join('');+ const open = section.severity === 'breaking' || section.severity === 'major' ? ' open' : '';+ return `+ <details class="dx-section"${open}>+ <summary>+ <svg class="dx-caret" width="12" height="12" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="m9 6 6 6-6 6" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>+ <span class="dx-section-name dx-sev-${esc(section.severity)}" style="color: var(--dx-sev)">${esc(label)}</span>+ <span class="dx-section-count">${section.changed} changed, ${section.unchanged} same</span>+ </summary>+ <ul class="dx-rows">${rows}</ul>+ </details>`;+ }).join('');++ const extras = extensionsHtml(changes);+ if (!blocks && !extras) {+ return `<div class="dx-card"><div class="dx-empty"><strong>No differences</strong>Every scene, mesh, material, texture, skeleton and clip matches.</div></div>`;+ }+ return `<div class="dx-card">${blocks}${extras}</div>`;+}++function extensionsHtml(changes) {+ const ext = changes.extensions;+ const rows = [+ ...ext.required.added.map((n) => rowHtml({ mark: '+', markClass: 'dx-mark-add', name: n, detail: 'now required' })),+ ...ext.required.removed.map((n) => rowHtml({ mark: '-', markClass: 'dx-mark-del', name: n, detail: 'no longer required' })),+ ...ext.used.added.filter((n) => !ext.required.added.includes(n)).map((n) => rowHtml({ mark: '+', markClass: 'dx-mark-add', name: n })),+ ...ext.used.removed.filter((n) => !ext.required.removed.includes(n)).map((n) => rowHtml({ mark: '-', markClass: 'dx-mark-del', name: n })),+ ...changes.asset.map((c) => rowHtml({ mark: '~', markClass: 'dx-mark-mod', name: c.field, detail: fieldText(c) })),+ ];+ if (!rows.length) return '';+ return `+ <details class="dx-section">+ <summary>+ <svg class="dx-caret" width="12" height="12" viewBox="0 0 24 24" fill="none" aria-hidden="true"><path d="m9 6 6 6-6 6" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"/></svg>+ <span class="dx-section-name">Extensions and metadata</span>+ <span class="dx-section-count">${rows.length} changed</span>+ </summary>+ <ul class="dx-rows">${rows.join('')}</ul>+ </details>`;+}++function cliCommand() {+ const a = state.a?.url || state.a?.name || 'before.glb';+ const b = state.b?.url || state.b?.name || 'after.glb';+ return `npx @three-ws/glb-diff ${a} ${b} --fail-on breaking`;+}++function actionsHtml() {+ return `+ <div class="dx-card">+ <div class="dx-card-head"><span>Take it with you</span></div>+ <div style="padding: var(--space-md); display: flex; flex-direction: column; gap: var(--space-sm)">+ <div class="dx-actions">+ <button type="button" class="dx-btn" data-copy="markdown">Copy Markdown</button>+ <button type="button" class="dx-btn" data-copy="json">Copy JSON</button>+ <button type="button" class="dx-btn" data-download="json">Download change set</button>+ <button type="button" class="dx-btn" data-copy="link">Copy link</button>+ </div>+ <pre class="dx-cli">${esc(cliCommand())}</pre>+ <div class="dx-actions">+ <button type="button" class="dx-btn" data-copy="cli">Copy the CLI command</button>+ </div>+ </div>+ </div>`;+}++// ── Wiring ───────────────────────────────────────────────────────────────────++async function flash(button, message) {+ const original = button.textContent;+ button.textContent = message;+ button.disabled = true;+ setTimeout(() => {+ button.textContent = original;+ button.disabled = false;+ }, 1400);+}++async function copy(text, button, label) {+ try {+ await navigator.clipboard.writeText(text);+ flash(button, label);+ } catch {+ flash(button, 'Clipboard blocked');+ }+}++function wireReport() {+ for (const button of document.querySelectorAll('[data-path]')) {+ button.addEventListener('click', () => {+ const path = button.dataset.path;+ for (const other of document.querySelectorAll('[data-path]')) other.setAttribute('aria-pressed', 'false');+ button.setAttribute('aria-pressed', 'true');+ state.focused = path;+ state.stage?.focusPath(path);+ });+ }++ for (const button of document.querySelectorAll('[data-copy]')) {+ button.addEventListener('click', () => {+ const kind = button.dataset.copy;+ if (kind === 'markdown') return copy(formatMarkdown(state.changeset), button, 'Copied');+ if (kind === 'json') return copy(JSON.stringify(state.changeset, null, 2), button, 'Copied');+ if (kind === 'cli') return copy(cliCommand(), button, 'Copied');+ return copy(location.href, button, 'Copied');+ });+ }++ const download = document.querySelector('[data-download]');+ if (download) {+ download.addEventListener('click', () => {+ const blob = new Blob([JSON.stringify(state.changeset, null, 2)], { type: 'application/json' });+ const url = URL.createObjectURL(blob);+ const link = document.createElement('a');+ link.href = url;+ link.download = `${state.a.name.replace(/\.[^.]+$/, '')}-to-${state.b.name.replace(/\.[^.]+$/, '')}.diff.json`;+ link.click();+ URL.revokeObjectURL(url);+ flash(download, 'Saved');+ });+ }+}++async function ensureStage() {+ if (state.stage) return state.stage;+ if (!state.stagePromise) {+ state.stagePromise = import('./model-diff-stage.js')+ .then((mod) => mod.createDiffStage($('dx-stage')))+ .then((stage) => {+ state.stage = stage;+ $('dx-stage-empty').hidden = true;+ return stage;+ })+ .catch((err) => {+ // WebGL can be unavailable (headless, blocked, software-blacklisted).+ // The report still works, so say what happened and carry on.+ $('dx-stage-empty').innerHTML =+ `<strong>3D view unavailable</strong><span>${esc(err?.message || 'this browser refused a WebGL context')}. The comparison below still works.</span>`;+ state.stagePromise = null;+ return null;+ });+ }+ return state.stagePromise;+}++function wireSlot(role) {+ const slot = $(`dx-slot-${role}`);+ const input = $(`dx-file-${role}`);+ input.addEventListener('change', () => loadFromFile(role, input.files?.[0]));++ for (const type of ['dragenter', 'dragover']) {+ slot.addEventListener(type, (event) => {+ event.preventDefault();+ slot.dataset.state = 'dragging';+ });+ }+ for (const type of ['dragleave', 'drop']) {+ slot.addEventListener(type, (event) => {+ event.preventDefault();+ if (slot.dataset.state === 'dragging') slot.dataset.state = state[role] ? 'loaded' : 'idle';+ });+ }+ slot.addEventListener('drop', (event) => loadFromFile(role, event.dataTransfer?.files?.[0]));++ $(`dx-load-${role}`).addEventListener('click', () => loadFromUrl(role, $(`dx-url-${role}`).value));+ $(`dx-url-${role}`).addEventListener('keydown', (event) => {+ if (event.key === 'Enter') loadFromUrl(role, event.currentTarget.value);+ });+}++function wireExamples() {+ const host = $('dx-examples');+ for (const pair of EXAMPLE_PAIRS) {+ const button = document.createElement('button');+ button.type = 'button';+ button.className = 'dx-example';+ button.textContent = pair.label;+ button.title = pair.title;+ button.addEventListener('click', async () => {+ $('dx-url-a').value = pair.a;+ $('dx-url-b').value = pair.b;+ await loadFromUrl('a', pair.a);+ await loadFromUrl('b', pair.b);+ });+ host.appendChild(button);+ }+}++function wireStageControls() {+ for (const button of document.querySelectorAll('[data-mode]')) {+ button.addEventListener('click', () => {+ state.mode = button.dataset.mode;+ for (const other of document.querySelectorAll('[data-mode]')) {+ other.setAttribute('aria-pressed', String(other === button));+ }+ $('dx-wipe').hidden = state.mode !== 'wipe';+ state.stage?.setMode(state.mode);+ });+ }+ $('dx-wipe').addEventListener('input', (event) => state.stage?.setWipe(Number(event.target.value) / 100));+ $('dx-highlight').addEventListener('change', (event) => state.stage?.setHighlight(event.target.checked));+ $('dx-play').addEventListener('change', (event) => state.stage?.setPlaying(event.target.checked));++ $('dx-swap').addEventListener('click', async () => {+ const [a, b] = [state.a, state.b];+ if (!a && !b) return;+ state.a = b;+ state.b = a;+ const urlA = $('dx-url-a').value;+ $('dx-url-a').value = $('dx-url-b').value;+ $('dx-url-b').value = urlA;+ for (const role of ['a', 'b']) {+ const side = state[role];+ $(`dx-name-${role}`).textContent = side ? side.name : role === 'a' ? 'Drop the baseline .glb' : 'Drop the candidate .glb';+ $(`dx-meta-${role}`).textContent = side+ ? `${formatBytes(side.bytes.byteLength)} - ${num(side.description.totals.triangles)} tris - ${num(side.description.totals.joints)} joints`+ : '';+ setSlotState(role, side ? 'loaded' : 'idle');+ if (side && state.stage) await state.stage.setModel(role, side.bytes);+ }+ compare();+ syncShareUrl();+ });+}++// Keyboard shortcuts, so the comparison modes are reachable without hunting for+// the control strip. Skipped while a text field has focus.+function wireShortcuts() {+ document.addEventListener('keydown', (event) => {+ const tag = document.activeElement?.tagName;+ if (tag === 'INPUT' || tag === 'TEXTAREA' || event.metaKey || event.ctrlKey || event.altKey) return;+ const modes = { o: 'overlay', w: 'wipe', s: 'split' };+ const mode = modes[event.key.toLowerCase()];+ if (mode) {+ document.querySelector(`[data-mode="${mode}"]`)?.click();+ return;+ }+ if (event.key.toLowerCase() === 'h') $('dx-highlight').click();+ if (event.key.toLowerCase() === 'f') state.stage?.frameAll();+ });+}++// A pair given as URLs is shareable, so it goes in the address bar. A pair of+// dropped files is not, and pretending otherwise would produce a link that+// silently opens an empty page for whoever received it.+function syncShareUrl() {+ const params = new URLSearchParams();+ if (state.a?.url) params.set('a', state.a.url);+ if (state.b?.url) params.set('b', state.b.url);+ const query = params.toString();+ history.replaceState(null, '', query ? `${location.pathname}?${query}` : location.pathname);+}++async function restoreFromUrl() {+ const params = new URLSearchParams(location.search);+ const a = params.get('a');+ const b = params.get('b');+ if (a) {+ $('dx-url-a').value = a;+ await loadFromUrl('a', a);+ }+ if (b) {+ $('dx-url-b').value = b;+ await loadFromUrl('b', b);+ }+}++function init() {+ wireSlot('a');+ wireSlot('b');+ wireExamples();+ wireStageControls();+ wireShortcuts();+ restoreFromUrl();+}++if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);+else init();