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.

41.5 KB
Raw Blame
<!doctype html>
<html lang="en">
<head>
	<script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(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, viewport-fit=cover" />
<title data-i18n="viewer.meta_title">glTF / GLB Viewer · three.ws</title>
<meta name="description" content="Preview any public glTF or GLB model right in the browser, then pose it, restyle it, build a scene, place it in AR, embed it on your site, or download it."  data-i18n-attr="content:viewer.meta_description"/>
<meta name="robots" content="noindex" />
<meta property="og:title" content="glTF / GLB Viewer · three.ws"  data-i18n-attr="content:viewer.meta_og_title"/>
<meta property="og:description" content="Preview any public glTF or GLB model right in the browser, then take it further: pose, restyle, scene, AR, embed."  data-i18n-attr="content:viewer.meta_og_description"/>
<meta property="og:type" content="website" />
<!-- Meshopt decoder must register before <model-viewer> starts loading (Forge GLBs are meshopt-compressed). Classic script → runs during parse, before the model-viewer module. -->
<script src="/model-viewer-meshopt.js"></script>
<!-- This standalone browser viewer loads model-viewer 4.0.0 with SRI from Google's CDN.
     Every three.ws surface is on that one build, because two builds in one document make
     the second customElements.define('model-viewer') throw. What differs per surface is
     DELIVERY, not version: a top-level document like this one owns its whole page and can
     afford the integrity check, while the server-rendered EMBED surface (the ChatGPT
     widget in api/_mcp-studio/component.js) runs inside someone else's frame and takes
     its URL from api/_lib/model-viewer-cdn.js, which is also the origin that widget's CSP
     allowlists. /api/ar no longer inlines a model-viewer at all: it 302s to /ar/view, a
     bundled page, because Quick Look needs a generated USDZ a server-rendered HTML string
     cannot produce. That module names every delivery rung; scripts/check-model-viewer-version.mjs
     fails the build if any of them drifts off the shared version. -->
<script
  type="module"
  src="https://cdn.jsdelivr.net/npm/@google/[email protected]/dist/model-viewer.min.js"
  integrity="sha384-wjsPzEO+lXOf7d9csIDfAQpPt2OKuUU3m0K9qsdKIuzX4N8czSF6hdh23eAbZa3p"
  crossorigin="anonymous"
></script>
<style>
  :root { color-scheme: dark; --accent: #6ea8fe; }
  * { box-sizing: border-box; }
  html, body { margin: 0; height: 100%; }
  body {
    font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
    background: radial-gradient(130% 130% at 50% 0%, #14161c 0%, #0b0c10 60%, #08090c 100%);
    color: #e8eaf0;
    overflow: hidden;
  }
  .wrap { display: flex; flex-direction: column; height: 100dvh; }
  header.bar {
    display: flex; align-items: center; gap: 12px;
    padding: 12px 16px; border-bottom: 1px solid rgba(255,255,255,0.07);
    background: rgba(10,11,14,0.55); backdrop-filter: blur(8px);
  }
  .brand { display: flex; align-items: center; gap: 9px; text-decoration: none; color: #e8eaf0; font-weight: 700; letter-spacing: .01em; }
  .brand .dot { width: 9px; height: 9px; border-radius: 50%; background: var(--accent); box-shadow: 0 0 12px var(--accent); }
  .brand:hover { color: #fff; }
  /* The model name is the page's h1: styled as a quiet header line, not a display heading. */
  .title { flex: 1 1 auto; min-width: 0; margin: 0; font-size: 13.5px; font-weight: 500; color: #aeb6c4; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
  .stage { position: relative; flex: 1 1 auto; min-height: 0; }
  model-viewer {
    width: 100%; height: 100%;
    --poster-color: transparent; --progress-bar-color: var(--accent);
    background: transparent;
    transition: opacity .4s ease;
  }
  /* Veil with opacity, never display:none — a display:none model-viewer has zero
     layout size, defers loading, and its "load" event never fires. */
  model-viewer.veiled { opacity: 0; pointer-events: none; }
  .overlay {
    position: absolute; inset: 0; display: flex; flex-direction: column;
    align-items: center; justify-content: center; gap: 14px; text-align: center; padding: 28px;
  }
  .spinner { width: 38px; height: 38px; border-radius: 50%; border: 3px solid rgba(255,255,255,0.14); border-top-color: var(--accent); animation: spin .9s linear infinite; }
  @keyframes spin { to { transform: rotate(360deg); } }
  @media (prefers-reduced-motion: reduce) { .spinner { animation-duration: 2.4s; } }
  .h { margin: 0; font-size: 15px; font-weight: 600; }
  .muted { color: #9aa3b2; font-size: 13px; line-height: 1.5; max-width: 40ch; }
  .muted a { color: var(--accent); text-decoration: underline; text-underline-offset: 2px; }
  .muted a:hover { color: #dbe9ff; }
  .muted a:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 3px; }
  footer.bar {
    display: flex; align-items: center; gap: 8px; flex-wrap: wrap;
    padding: 11px 16px; border-top: 1px solid rgba(255,255,255,0.07);
    background: rgba(10,11,14,0.55); backdrop-filter: blur(8px);
  }
  /* The i18n runtime's floating language pill defaults to the bottom-right
     corner, which this page's action bar owns (it was covering the "Do more
     with this model" button). Lift it above the bar; body-scoped so this
     outranks the runtime's class-only rule regardless of injection order. */
  body .twx-i18n-fab {
    inset-block-end: calc(max(16px, env(safe-area-inset-bottom)) + 58px);
  }
  .spacer { flex: 1 1 auto; }
  a.btn, button.btn {
    appearance: none; cursor: pointer; text-decoration: none; display: inline-flex; align-items: center; gap: 7px;
    font-size: 13px; font-weight: 600; color: #e8eaf0;
    background: rgba(255,255,255,0.06); border: 1px solid rgba(255,255,255,0.14);
    border-radius: 10px; padding: 8px 13px; transition: background .15s, border-color .15s, transform .05s;
  }
  a.btn.primary { background: rgba(110,168,254,0.16); border-color: rgba(110,168,254,0.42); color: #dbe9ff; }
  a.btn:hover, button.btn:hover { background: rgba(255,255,255,0.12); border-color: rgba(255,255,255,0.28); }
  a.btn.primary:hover { background: rgba(110,168,254,0.26); }
  a.btn:active, button.btn:active { transform: translateY(1px); }
  a.btn:focus-visible, button.btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
  .hidden { display: none !important; }
  #ar-btn { display: none; }
  .badge {
    display: inline-flex; align-items: center; gap: 6px; text-decoration: none;
    font-size: 11.5px; font-weight: 700; letter-spacing: .01em;
    border-radius: 999px; padding: 4px 10px; border: 1px solid transparent; white-space: nowrap;
  }
  .badge.verified { color: #b6f2c8; background: rgba(52,199,109,.13); border-color: rgba(52,199,109,.34); }
  .badge.tampered { color: #ffc2c2; background: rgba(255,86,86,.13); border-color: rgba(255,86,86,.36); }
  .badge.unknown  { color: #9aa3b2; background: rgba(255,255,255,.05); border-color: rgba(255,255,255,.12); }
  .badge:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }

  /* ── "Do more" funnel sheet ─────────────────────────────────────────── */
  #more-btn { position: relative; }
  #more-btn.pulse::after {
    content: ""; position: absolute; inset: -3px; border-radius: 13px;
    border: 2px solid rgba(110,168,254,.55); animation: morepulse 1.6s ease-out 2; pointer-events: none;
  }
  @keyframes morepulse { 0% { opacity: 1; transform: scale(1); } 100% { opacity: 0; transform: scale(1.12); } }
  @media (prefers-reduced-motion: reduce) { #more-btn.pulse::after { animation: none; display: none; } }
  #sheet-wrap { position: fixed; inset: 0; z-index: 40; }
  #sheet-backdrop { position: absolute; inset: 0; background: rgba(4,5,8,.55); backdrop-filter: blur(2px); opacity: 0; transition: opacity .22s ease; }
  #sheet {
    position: absolute; left: 50%; bottom: 0; transform: translate(-50%, 24px);
    width: min(780px, 100%); max-height: min(78dvh, 640px); overflow-y: auto;
    background: #12141a; border: 1px solid rgba(255,255,255,.1); border-bottom: 0;
    border-radius: 18px 18px 0 0; padding: 18px 18px calc(18px + env(safe-area-inset-bottom));
    box-shadow: 0 -18px 60px rgba(0,0,0,.5);
    opacity: 0; transition: opacity .22s ease, transform .22s ease;
  }
  #sheet-wrap.open #sheet-backdrop { opacity: 1; }
  #sheet-wrap.open #sheet { opacity: 1; transform: translate(-50%, 0); }
  @media (prefers-reduced-motion: reduce) { #sheet, #sheet-backdrop { transition: none; } }
  .sheet-head { display: flex; align-items: baseline; gap: 10px; margin: 2px 2px 14px; }
  .sheet-title { font-size: 16px; font-weight: 700; }
  .sheet-sub { flex: 1 1 auto; color: #9aa3b2; font-size: 12.5px; }
  .sheet-close {
    appearance: none; cursor: pointer; border: 0; background: rgba(255,255,255,.07); color: #aeb6c4;
    width: 28px; height: 28px; border-radius: 50%; font-size: 13px; line-height: 1; flex: 0 0 auto;
    transition: background .15s, color .15s; align-self: center;
  }
  .sheet-close:hover { background: rgba(255,255,255,.14); color: #fff; }
  .sheet-close:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
  .cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(215px, 1fr)); gap: 10px; }
  .card {
    display: flex; flex-direction: column; gap: 4px; text-align: left; text-decoration: none;
    appearance: none; cursor: pointer; font: inherit; color: #e8eaf0;
    background: rgba(255,255,255,.04); border: 1px solid rgba(255,255,255,.1);
    border-radius: 13px; padding: 13px 14px;
    transition: background .15s, border-color .15s, transform .12s;
  }
  .card:hover { background: rgba(110,168,254,.09); border-color: rgba(110,168,254,.4); transform: translateY(-1px); }
  .card:active { transform: translateY(0); }
  .card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
  .card[disabled] { opacity: .55; cursor: progress; transform: none; }
  .card .k { display: flex; align-items: center; gap: 8px; font-size: 13.5px; font-weight: 700; }
  .card .k .glyph { color: var(--accent); font-size: 15px; min-width: 18px; text-align: center; flex: 0 0 auto; }
  .card .d { color: #9aa3b2; font-size: 12px; line-height: 1.45; }
</style>

	<link rel="canonical" href="https://three.ws/viewer">
	<meta property="og:site_name" content="three.ws">
	<meta property="og:locale" content="en_US">
	<meta property="og:url" content="https://three.ws/viewer">
	<meta property="og:image" content="https://three.ws/api/page-og?s=labs&amp;t=glTF+%2F+GLB+Viewer&amp;d=Preview+any+public+glTF%2FGLB+inline%2C+then+take+it+further%3A+pose+and+animate+it%2C+restyle+the+material%2C+build+a+scene%2C+place+it+in+AR%2C+embed+it+on+your+site%2C+or&amp;p=%2Fviewer">
	<meta property="og:image:width" content="1200">
	<meta property="og:image:height" content="630">
	<meta property="og:image:type" content="image/png">
	<meta property="og:image:alt" content="glTF / GLB Viewer — three.ws">
	<meta name="twitter:card" content="summary_large_image">
	<meta name="twitter:site" content="@trythreews">
	<meta name="twitter:title" content="glTF / GLB Viewer · three.ws" data-i18n-attr="content:viewer.meta_twitter_title">
	<meta name="twitter:description" content="Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens." data-i18n-attr="content:viewer.meta_twitter_description">
	<meta name="twitter:image" content="https://three.ws/api/page-og?s=labs&amp;t=glTF+%2F+GLB+Viewer&amp;d=Preview+any+public+glTF%2FGLB+inline%2C+then+take+it+further%3A+pose+and+animate+it%2C+restyle+the+material%2C+build+a+scene%2C+place+it+in+AR%2C+embed+it+on+your+site%2C+or&amp;p=%2Fviewer">
	<script type="application/ld+json">{"@context":"https://schema.org","@graph":[{"@type":"WebPage","name":"glTF / GLB Viewer","description":"Paste any public glTF/GLB URL and preview it inline — the lightweight, unauthenticated model viewer every 3D Studio tool's shared asset link opens.","url":"https://three.ws/viewer","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"},"primaryImageOfPage":"https://three.ws/api/page-og?s=labs&t=glTF+%2F+GLB+Viewer&d=Paste+any+public+glTF%2FGLB+URL+and+preview+it+inline+%E2%80%94+the+lightweight%2C+unauthenticated+model+viewer+every+3D+Studio+tool%27s+shared+asset+link+opens.&p=%2Fviewer"}]}</script>
</head>
<body>
<div class="wrap">
  <header class="bar">
    <a class="brand" href="https://three.ws" data-i18n-html="viewer.three_ws"><span class="dot" aria-hidden="true"></span>three.ws</a>
    <h1 id="title" class="title" data-i18n="viewer.gltf_glb_viewer">glTF / GLB viewer</h1>
    <!-- No aria-label: when the badge links out, its accessible name has to be the
         status a sighted visitor reads ("Verified · three.ws"), not a generic one. -->
    <a id="badge" class="badge hidden" target="_blank" rel="noopener noreferrer"></a>
    <!-- The physics grade, beside the authenticity badge: one says the asset is
         genuine, the other says a solver can actually use it. -->
    <sim-readiness id="sim-badge" align="end" hidden></sim-readiness>
    <!-- The real-time-engine fitness grade: draw calls, materials, texel
         density, LOD budget, collider. A different question than physics
         readiness, so its own badge rather than folding into sim-readiness. -->
    <engine-qa id="engine-qa-badge" align="end" hidden></engine-qa>
  </header>

  <div class="stage">
    <model-viewer id="mv" class="veiled" camera-controls auto-rotate touch-action="pan-y"
      rotation-per-second="14deg" interaction-prompt="auto"
      shadow-intensity="1" shadow-softness="0.9" exposure="1.5" environment-image="/environments/gallery/env.hdr" tone-mapping="aces"
      ar ar-modes="webxr scene-viewer quick-look" ar-scale="auto" reveal="auto" alt="Generated 3D model">
    </model-viewer>

    <div id="loading" class="overlay">
      <div class="spinner" aria-hidden="true"></div>
      <h2 class="h"><span data-i18n="viewer.loading_model">Loading model</span><span id="load-pct"></span></h2>
      <div id="load-note" class="muted" data-i18n="viewer.fetching_and_rendering_the_glb">Fetching and rendering the GLB. Large or high-detail models take a few seconds.</div>
      <div id="job-status" class="muted hidden" role="status" aria-live="polite"></div>
    </div>

    <div id="empty" class="overlay hidden">
      <h2 class="h" data-i18n="viewer.no_model_to_show">No model to show</h2>
      <div class="muted" data-i18n-html="viewer.this_viewer_opens_a_3d_model">This viewer opens a 3D model from a <code>?src=</code> link. Generate one for free at <a href="https://three.ws/forge">three.ws/forge</a>.</div>
      <a class="btn primary" href="https://three.ws/forge" data-i18n="viewer.create_a_3d_model">Create a 3D model</a>
    </div>

    <div id="error" class="overlay hidden">
      <h2 class="h" data-i18n="viewer.couldnt_display_this_model">Couldn't display this model</h2>
      <div id="errmsg" class="muted">The 3D model failed to load. You can still download the GLB file below.</div>
    </div>
  </div>

  <footer id="foot" class="bar hidden">
    <button id="ar-btn" class="btn" type="button" aria-label="View this model in augmented reality" data-i18n="viewer.view_in_ar" data-i18n-attr="aria-label:viewer.view_this_model_in_augmented_arialabel">View in AR</button>
    <div class="spacer"></div>
    <a id="download" class="btn" download aria-label="Download the GLB file" data-i18n="viewer.download_glb" data-i18n-attr="aria-label:viewer.download_the_glb_file_arialabel">Download GLB</a>
    <a id="make-own" class="btn primary" href="https://three.ws/forge" aria-label="Create your own 3D model with the three.ws Forge" data-i18n="viewer.make_your_own" data-i18n-attr="aria-label:viewer.create_your_own_3d_model_wit_arialabel">Make your own →</a>
    <button id="more-btn" class="btn primary hidden" type="button" aria-haspopup="dialog" aria-controls="sheet-wrap" aria-expanded="false" data-i18n="viewer.do_more_with_this_model">Do more with this model</button>
  </footer>

  <div id="sheet-wrap" class="hidden" role="dialog" aria-modal="true" aria-labelledby="sheet-title">
    <div id="sheet-backdrop"></div>
    <div id="sheet">
      <div class="sheet-head">
        <div id="sheet-title" class="sheet-title">Do more with this model</div>
        <div class="sheet-sub">It's yours. Take it further.</div>
        <button class="sheet-close" type="button" aria-label="Close" data-i18n-attr="aria-label:viewer.close_arialabel">✕</button>
      </div>
      <div class="cards">
        <a class="card hidden" id="act-animate" data-i18n-html="viewer.pose_animate_open_it_in_pose_studio">
          <span class="k"><span class="glyph" aria-hidden="true">▶</span>Pose &amp; animate</span>
          <span class="d">Open it in Pose Studio and drive it with the animation library.</span>
        </a>
        <a class="card" id="act-restyle" data-i18n-html="viewer.restyle_it_keep_the_mesh_re_skin">
          <span class="k"><span class="glyph" aria-hidden="true">◈</span>Restyle it</span>
          <span class="d">Keep the mesh, re-skin the material: chrome, wood, neon, anything.</span>
        </a>
        <a class="card" id="act-scene" data-i18n-html="viewer.build_a_scene_drop_it_into_scene">
          <span class="k"><span class="glyph" aria-hidden="true">⬢</span>Build a scene</span>
          <span class="d">Drop it into Scene Studio and compose a world around it.</span>
        </a>
        <a class="card" id="act-compose" data-i18n-html="viewer.combine_parts_mix_it_with_other_models">
          <span class="k"><span class="glyph" aria-hidden="true">⧉</span>Combine parts</span>
          <span class="d">Mix it with other models and forge new parts onto it.</span>
        </a>
        <button class="card" id="act-ar" type="button" data-i18n-html="viewer.see_it_in_your_room_place_it">
          <span class="k"><span class="glyph" aria-hidden="true">◎</span>See it in your room</span>
          <span class="d">Place it in AR: straight from your phone, or scan a QR from desktop.</span>
        </button>
        <button class="card" id="act-ar-studio" type="button" data-i18n-html="viewer.open_in_ar_studio_place_it_alongside">
          <span class="k"><span class="glyph" aria-hidden="true">▣</span>Open in AR Studio</span>
          <span class="d">Place it alongside other models in a live camera scene — and forge more without leaving the view.</span>
        </button>
        <button class="card" id="act-coin" type="button" data-i18n-html="viewer.launch_it_as_a_coin_open_a">
          <span class="k"><span class="glyph" aria-hidden="true">◉</span>Launch it as a coin</span>
          <span class="d" id="coin-d">Open a pump.fun launch with this model as the token image.</span>
        </button>
        <button class="card" id="act-embed" type="button" data-i18n-html="viewer.embed_it_anywhere_copy_an_iframe_snippet">
          <span class="k"><span class="glyph" aria-hidden="true">&lt;/&gt;</span>Embed it anywhere</span>
          <span class="d" id="embed-d">Copy an iframe snippet that shows this exact viewer on your site.</span>
        </button>
        <a class="card" id="act-forge" href="/forge" data-i18n-html="viewer.forge_another_describe_anything_and_get_a">
          <span class="k"><span class="glyph" aria-hidden="true">✦</span>Forge another</span>
          <span class="d">Describe anything and get a new 3D model, free.</span>
        </a>
      </div>
    </div>
  </div>
</div>

<script>
(function () {
  var mv = document.getElementById('mv');
  var loading = document.getElementById('loading');
  var empty = document.getElementById('empty');
  var errEl = document.getElementById('error');
  var errMsg = document.getElementById('errmsg');
  var foot = document.getElementById('foot');
  var titleEl = document.getElementById('title');
  var downloadEl = document.getElementById('download');
  var arBtn = document.getElementById('ar-btn');

  function show(el) { [loading, empty, errEl].forEach(function (n) { n.classList.add('hidden'); }); if (el) el.classList.remove('hidden'); }
  function fail(msg) { mv.classList.add('veiled'); errMsg.textContent = msg || 'The 3D model failed to load.'; show(errEl); }

  var params = new URLSearchParams(location.search);
  var src = params.get('src') || '';
  var title = params.get('title') || '';

  // Only ever load an https GLB — never data:/http:/blob: from an untrusted link.
  function isHttps(u) { try { return new URL(u).protocol === 'https:'; } catch (e) { return false; } }

  // The document title is "<model name> · <page title>". The page-title half is
  // translated copy, and the i18n runtime rewrites <title> from its catalog on
  // every pass (boot, injected content, locale switch), which would drop the
  // model name. Claim the element with data-i18n-owned so no pass touches it,
  // then compose the title here from the same catalog value the runtime uses.
  var titleTag = document.getElementsByTagName('title')[0];
  var baseDocTitle = (titleTag && titleTag.textContent) || 'glTF / GLB Viewer · three.ws';
  if (titleTag) titleTag.setAttribute('data-i18n-owned', '1');
  function localizedBase() {
    var api = window.threewsI18n;
    if (!api || typeof api.t !== 'function') return baseDocTitle;
    var v = api.t('viewer.meta_title');
    // A miss echoes the key back; keep the English source text in that case.
    return v && v !== 'viewer.meta_title' ? v : baseDocTitle;
  }
  function syncDocTitle() {
    var base = localizedBase();
    document.title = title ? title + ' · ' + base : base;
  }
  window.addEventListener('i18n:change', syncDocTitle);

  if (title) {
    titleEl.textContent = title;
    // The h1 now holds live data (the model name), so the catalog pass must not
    // put the generic page heading back over it.
    titleEl.setAttribute('data-i18n-owned', '1');
    mv.setAttribute('alt', title);
    syncDocTitle();
  }

  // ?job=<id>: a generation that is still rendering. A studio MCP tool hands this
  // link to agents that render no widget (Grok Bot and other browser agents), so
  // opening it has to finish the wait by itself: poll the public job endpoint and
  // swap to the ordinary ?src= view the moment the GLB lands, which also leaves a
  // shareable model link in the address bar.
  var job = params.get('job') || '';
  if (!src && job) { watchJob(job); return; }

  if (!src) { mv.classList.add('hidden'); foot.classList.add('hidden'); show(empty); return; }
  if (!isHttps(src)) {
    // Nothing to download either: never leave a dead Download button behind.
    downloadEl.classList.add('hidden');
    fail('That model link is not a valid https URL. Open a viewer link whose ?src= points at an https .glb file.');
    foot.classList.remove('hidden');
    return;
  }

  function watchJob(jobId) {
    var note = document.getElementById('load-note');
    var jobStatus = document.getElementById('job-status');
    var started = Date.now();
    var misses = 0;
    // Generous: a cold GPU worker plus a high-tier render runs well past ten
    // minutes on a bad day, and giving up early strands a model that will land.
    var MAX_WAIT_MS = 30 * 60 * 1000;
    var POLL_MS = 4000;
    if (note) note.classList.add('hidden');
    jobStatus.classList.remove('hidden');
    jobStatus.textContent = 'Checking on your model.';
    show(loading);

    function jobFail(msg) {
      // No GLB exists, so offer the next step instead of a dead Download button.
      downloadEl.classList.add('hidden');
      foot.classList.remove('hidden');
      fail(msg);
    }
    function next(ms) { setTimeout(tick, ms); }
    function tick() {
      if (Date.now() - started > MAX_WAIT_MS) {
        jobFail('This model is taking far longer than usual. Open this link again later, or make a new one at three.ws/forge.');
        return;
      }
      fetch('/api/gpt-forge?job=' + encodeURIComponent(jobId), { headers: { accept: 'application/json' } })
        .then(function (r) {
          return r.json().catch(function () { return {}; }).then(function (d) { return { status: r.status, ok: r.ok, d: d || {} }; });
        })
        .then(function (res) {
          var d = res.d;
          if (res.status === 400 || res.status === 404) {
            jobFail('That job link is not recognized. It may be mistyped or expired. Make a new model at three.ws/forge.');
            return;
          }
          if (res.status === 429) {
            jobStatus.textContent = 'Still rendering. Checking again shortly.';
            next(Math.max(5, Number(d.retry_after) || 10) * 1000);
            return;
          }
          if (!res.ok) throw new Error('status ' + res.status);
          misses = 0;
          if (d.status === 'done' && isHttps(d.glb_url)) {
            var name = title || (typeof d.prompt === 'string' ? d.prompt.trim().slice(0, 80) : '');
            location.replace('/viewer?src=' + encodeURIComponent(d.glb_url) + (name ? '&title=' + encodeURIComponent(name) : ''));
            return;
          }
          if (d.status === 'failed') {
            jobFail(d.error ? 'Generation failed: ' + d.error : 'Generation failed. Try again at three.ws/forge.');
            return;
          }
          var eta = Number(d.eta_remaining_seconds);
          jobStatus.textContent = (eta > 0 ? 'Still rendering, about ' + Math.round(eta) + 's to go.' : 'Still rendering.')
            + ' This page opens the model the moment it is ready.';
          next(POLL_MS);
        })
        .catch(function () {
          misses++;
          jobStatus.textContent = 'Lost the connection for a moment. Retrying.';
          next(Math.min(30000, POLL_MS * Math.pow(2, misses)));
        });
    }
    tick();
  }

  downloadEl.href = src;
  foot.classList.remove('hidden');
  show(loading);
  mv.setAttribute('src', src);

  // Real download progress: model-viewer emits `progress` with a 0..1
  // totalProgress. Surface it as a live percent on the loading overlay so a big
  // GLB on a slow connection reads as "62%", not an infinite spinner.
  var loadPct = document.getElementById('load-pct');
  mv.addEventListener('progress', function (e) {
    var p = e && e.detail ? e.detail.totalProgress : 0;
    if (!loadPct || typeof p !== 'number') return;
    // model-viewer reports 1 at the end of the fetch, before render finishes;
    // keep the label honest by capping the shown value at 99% until `load`.
    var pct = Math.max(0, Math.min(99, Math.round(p * 100)));
    loadPct.textContent = p >= 1 ? '' : ' · ' + pct + '%';
  });
  mv.addEventListener('load', function () {
    if (loadPct) loadPct.textContent = '';
    show(null);
    mv.classList.remove('veiled');
    // Expose the AR button only when the device/model can actually enter AR.
    if (mv.canActivateAR) { arBtn.style.display = 'inline-flex'; }
    revealFunnel();
  });
  mv.addEventListener('error', function () {
    fail('The 3D model could not be displayed. You can still download the GLB file.');
  });
  arBtn.addEventListener('click', function () { try { mv.activateAR(); } catch (e) {} });

  // ── "Do more" funnel: every generated model funnels into a next step:
  // animate, restyle, scene, parts, AR, a pump.fun coin, or an embed. ──────
  var moreBtn = document.getElementById('more-btn');
  var makeOwn = document.getElementById('make-own');
  var sheetWrap = document.getElementById('sheet-wrap');
  var sheetBackdrop = document.getElementById('sheet-backdrop');
  var sheetClose = sheetWrap.querySelector('.sheet-close');
  var enc = encodeURIComponent;
  var tOpt = title ? '&title=' + enc(title) : '';

  document.getElementById('act-animate').href = '/pose?src=' + enc(src) + tOpt;
  document.getElementById('act-restyle').href = '/restyle?url=' + enc(src);
  document.getElementById('act-scene').href = '/scene?model=' + enc(src) + (title ? '&name=' + enc(title) : '');
  document.getElementById('act-compose').href = '/compose?glb=' + enc(src);

  function revealFunnel() {
    makeOwn.classList.add('hidden');
    moreBtn.classList.remove('hidden');
    moreBtn.classList.add('pulse');
    probeSkeleton();
  }

  var lastFocus = null;
  function openSheet() {
    lastFocus = document.activeElement;
    sheetWrap.classList.remove('hidden');
    void sheetWrap.offsetWidth; // commit the hidden→shown frame so the transition runs
    sheetWrap.classList.add('open');
    moreBtn.classList.remove('pulse');
    moreBtn.setAttribute('aria-expanded', 'true');
    sheetClose.focus();
  }
  function closeSheet() {
    sheetWrap.classList.remove('open');
    moreBtn.setAttribute('aria-expanded', 'false');
    setTimeout(function () { sheetWrap.classList.add('hidden'); }, 240);
    if (lastFocus && lastFocus.focus) lastFocus.focus();
  }
  moreBtn.addEventListener('click', openSheet);
  sheetClose.addEventListener('click', closeSheet);
  sheetBackdrop.addEventListener('click', closeSheet);
  document.addEventListener('keydown', function (e) {
    if (sheetWrap.classList.contains('hidden')) return;
    if (e.key === 'Escape') { closeSheet(); return; }
    if (e.key !== 'Tab') return;
    // Keep Tab inside the dialog.
    var focusables = Array.prototype.filter.call(
      sheetWrap.querySelectorAll('button:not([disabled]), a[href]'),
      function (n) { return n.offsetParent !== null; }
    );
    if (!focusables.length) return;
    var first = focusables[0], last = focusables[focusables.length - 1];
    if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
    else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
  });

  // Pose Studio can only animate a model that ships a skeleton. Read just the
  // GLB's JSON chunk (from the HTTP cache; model-viewer already fetched it)
  // and reveal the Animate card unless the model positively has no skins.
  function probeSkeleton() {
    var animateCard = document.getElementById('act-animate');
    fetch(src, { cache: 'force-cache' })
      .then(function (r) {
        if (!r.ok || !r.body) throw new Error('unreadable');
        var reader = r.body.getReader();
        var buf = new Uint8Array(0);
        var need = 20; // 12-byte GLB header + first chunk header
        function pump() {
          return reader.read().then(function (step) {
            if (step.value) {
              var merged = new Uint8Array(buf.length + step.value.length);
              merged.set(buf); merged.set(step.value, buf.length);
              buf = merged;
            }
            if (buf.length >= 20 && need === 20) {
              var dv = new DataView(buf.buffer, buf.byteOffset, buf.length);
              if (dv.getUint32(0, true) !== 0x46546c67) return null; // not binary glTF: assume rigged-capable
              var jsonLen = dv.getUint32(12, true);
              if (jsonLen > 48e6) return null;
              need = 20 + jsonLen;
            }
            if (buf.length >= need && need > 20) {
              var json = JSON.parse(new TextDecoder().decode(buf.subarray(20, need)));
              return Array.isArray(json.skins) && json.skins.length > 0;
            }
            if (step.done) return null;
            return pump();
          });
        }
        return pump().finally(function () { reader.cancel().catch(function () {}); });
      })
      .then(function (hasSkins) {
        // Show on true or unknown (null); hide only when provably unrigged.
        if (hasSkins !== false) animateCard.classList.remove('hidden');
      })
      .catch(function () { animateCard.classList.remove('hidden'); });
  }

  // AR: device AR when this browser can enter it, else the /ar page
  // (which QR-hands-off to a phone from desktop).
  document.getElementById('act-ar').addEventListener('click', function () {
    if (mv.canActivateAR) { closeSheet(); try { mv.activateAR(); } catch (e) {} return; }
    location.href = '/ar?src=' + enc(src) + tOpt;
  });

  // AR Studio: the multi-model lane — this model joins (or starts) a live
  // camera scene where more models can be placed and forged around it.
  document.getElementById('act-ar-studio').addEventListener('click', function () {
    location.href = '/ar/studio?src=' + enc(src) + tOpt;
  });

  // Coin launch: snapshot the rendered model into a token image, hand it to
  // /launch via sessionStorage (a data URL never fits in a query string).
  var coinCard = document.getElementById('act-coin');
  // Look the description lines up on demand, never once at boot: the i18n runtime
  // rewrites each card's innerHTML when it applies a catalog, which replaces these
  // nodes. A reference captured now would be detached, and every status message
  // this page writes would land on an element the user cannot see.
  function cardDesc(id) { return document.getElementById(id); }
  function setCardDesc(id, text) { var el = cardDesc(id); if (el) el.textContent = text; }
  function captureTokenImage() {
    return new Promise(function (resolve, reject) {
      var raw;
      try { raw = mv.toDataURL('image/png'); } catch (e) { reject(e); return; }
      var img = new Image();
      img.onload = function () {
        try {
          var size = 512;
          var c = document.createElement('canvas');
          c.width = size; c.height = size;
          var ctx = c.getContext('2d');
          ctx.fillStyle = '#0b0c10'; ctx.fillRect(0, 0, size, size);
          var s = Math.min(img.width, img.height) || 1;
          ctx.drawImage(img, (img.width - s) / 2, (img.height - s) / 2, s, s, 0, 0, size, size);
          resolve(c.toDataURL('image/webp', 0.9));
        } catch (e) { reject(e); }
      };
      img.onerror = reject;
      img.src = raw;
    });
  }
  coinCard.addEventListener('click', function () {
    if (coinCard.disabled) return;
    coinCard.disabled = true;
    setCardDesc('coin-d', 'Rendering the token image…');
    var name = (title || 'My 3D creation').slice(0, 32);
    var desc = (title ? title + '. ' : '') + 'Forged in 3D on three.ws.';
    var q = '/launch?name=' + enc(name) + '&description=' + enc(desc.slice(0, 500));
    captureTokenImage()
      .then(function (dataUrl) {
        try { sessionStorage.setItem('twx.launch.image', dataUrl); q += '&imageSession=1'; } catch (e) {}
      })
      .catch(function () { /* no snapshot: the launch form still opens, user uploads an image */ })
      .then(function () { location.href = q; });
  });

  // Embed: copy a paste-anywhere iframe of this exact viewer.
  var embedCard = document.getElementById('act-embed');
  var embedBusy = false;
  function escAttr(s) { return s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;'); }
  embedCard.addEventListener('click', function () {
    // While the result line is showing, the snippet is already on the clipboard.
    // Ignoring the click keeps that line from being read back as the default.
    if (embedBusy) return;
    embedBusy = true;
    var embedDefault = cardDesc('embed-d').textContent;
    var pageUrl = location.origin + '/viewer?src=' + enc(src) + tOpt;
    var snippet = '<iframe src="' + escAttr(pageUrl) + '" width="640" height="480" '
      + 'style="border:0;border-radius:12px;background:#0b0c10" loading="lazy" '
      + 'allow="xr-spatial-tracking; fullscreen" title="' + escAttr(title || '3D model') + ' · three.ws 3D viewer"></iframe>';
    function done(ok) {
      setCardDesc('embed-d', ok ? 'Copied. Paste it into any HTML page.' : 'Copy failed: select and copy the address bar URL instead.');
      setTimeout(function () { setCardDesc('embed-d', embedDefault); embedBusy = false; }, 2600);
    }
    if (navigator.clipboard && navigator.clipboard.writeText) {
      navigator.clipboard.writeText(snippet).then(function () { done(true); }, function () { done(false); });
    } else {
      var ta = document.createElement('textarea');
      ta.value = snippet; ta.style.position = 'fixed'; ta.style.opacity = '0';
      document.body.appendChild(ta); ta.select();
      var ok = false;
      try { ok = document.execCommand('copy'); } catch (e) {}
      ta.remove();
      done(ok);
    }
  });

  // Provenance badge — ask the free verify endpoint whether this model carries a
  // genuine, untampered three.ws content credential. Designed verified / tampered
  // / unverified states; silent (badge stays hidden) if the check can't run.
  (function checkProvenance() {
    var badge = document.getElementById('badge');
    fetch('/api/provenance?src=' + encodeURIComponent(src), { headers: { accept: 'application/json' } })
      .then(function (r) { return r.ok ? r.json() : null; })
      .then(function (d) {
        if (!d || !d.status) return;
        var label = d.status === 'verified' ? '✓ ' + (d.badge || 'Verified · three.ws')
          : d.status === 'tampered' ? '⚠ Tampered' : 'Unverified';
        badge.textContent = label;
        badge.classList.add(d.status);
        badge.classList.remove('hidden');
        if (d.anchor && d.anchor.explorerUrl) { badge.href = d.anchor.explorerUrl; }
        else { badge.removeAttribute('href'); badge.style.cursor = 'default'; }
        if (d.reason) badge.title = d.reason;
      })
      .catch(function () {});
  })();

  // Simulation readiness. Deliberately NOT automatic: grading an arbitrary URL
  // makes the server fetch the whole GLB, and doing that on every viewer load
  // would spend real bandwidth answering a question most visitors did not ask.
  // So the badge starts as an offer and the expensive path stays behind a click.
  (function checkSimReadiness() {
    var el = document.getElementById('sim-badge');
    if (!el || !src) return;
    function run() {
      fetch('/api/sim-readiness?src=' + encodeURIComponent(src), { headers: { accept: 'application/json' } })
        .then(function (r) {
          return r.json().then(function (body) { return { ok: r.ok, status: r.status, body: body }; });
        })
        .then(function (res) {
          if (!res.ok) throw new Error((res.body && res.body.error) || ('HTTP ' + res.status));
          el.showReport(res.body, { gradedAt: res.body.gradedAt, cached: res.body.cached });
        })
        .catch(function (err) {
          el.failed(err && err.message ? err.message : 'The physics grade could not be fetched.', { onRetry: run });
        });
    }
    function offer() { el.ungraded({ onGrade: run }); }
    // The element is inert until its definition lands, so wait for the upgrade
    // before calling anything on it. A blocked script simply means no badge.
    var deadline = new Promise(function (resolve) { setTimeout(function () { resolve(false); }, 10000); });
    Promise.race([customElements.whenDefined('sim-readiness').then(function () { return true; }), deadline])
      .then(function (ready) { if (ready) offer(); });
  })();

  // Engine QA. Same "offer, not automatic" reasoning as simulation readiness
  // above: the base grade is cheap, but the LOD-chain upgrade is real
  // decimation work, so it stays behind its own explicit click too.
  (function checkEngineQa() {
    var el = document.getElementById('engine-qa-badge');
    if (!el || !src) return;
    function run(withLods) {
      var qs = '?url=' + encodeURIComponent(src) + (withLods ? '&lods=1' : '');
      fetch('/api/3d/engine-qa' + qs, { headers: { accept: 'application/json' } })
        .then(function (r) {
          return r.json().then(function (body) { return { ok: r.ok, status: r.status, body: body }; });
        })
        .then(function (res) {
          if (!res.ok) throw new Error((res.body && res.body.error) || ('HTTP ' + res.status));
          el.showReport(res.body.report, {
            gradedAt: res.body.ts,
            sourceUrl: res.body.url,
            stlUrl: '/api/3d/engine-qa?format=stl&url=' + encodeURIComponent(src),
            upgradeLabel: 'Build & grade LOD chain',
            onUpgrade: function () { run(true); },
          });
        })
        .catch(function (err) {
          el.failed(err && err.message ? err.message : 'The engine QA grade could not be fetched.', { onRetry: function () { run(withLods); } });
        });
    }
    function offer() { el.ungraded({ onGrade: function () { run(false); } }); }
    var deadline = new Promise(function (resolve) { setTimeout(function () { resolve(false); }, 10000); });
    Promise.race([customElements.whenDefined('engine-qa').then(function () { return true; }), deadline])
      .then(function (ready) { if (ready) offer(); });
  })();

  // If model-viewer itself never upgrades (script blocked), don't spin forever.
  setTimeout(function () {
    if (loading && !loading.classList.contains('hidden') && !customElements.get('model-viewer')) {
      fail('The 3D viewer could not load in this browser. Download the GLB and open it in any 3D viewer.');
    }
  }, 12000);

  // Watchdog for a load that hangs after the element upgraded (stalled fetch,
  // decoder wedge): surface the error state with the download link instead of
  // an infinite spinner. 90s clears even huge GLBs on slow connections.
  setTimeout(function () {
    // Guard on mv.loaded too: a slow-but-successful load whose `load` event we
    // somehow missed must not be flipped to an error after the fact.
    if (loading && !loading.classList.contains('hidden') && !mv.loaded) {
      fail('This model is taking too long to display. Download the GLB and open it in any 3D viewer.');
    }
  }, 90000);
})();
</script>
	<!-- The <sim-readiness> element, shared verbatim with /m/:id. -->
	<script type="module" src="/sim-readiness-panel.js"></script>
	<!-- The <engine-qa> element, shared verbatim with Rig Doctor. -->
	<script type="module" src="/engine-qa-panel.js"></script>
	<!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
	<script type="module" src="/i18n.js"></script>
</body>
</html>