Skip to content

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

feat(readme-3d): add the readme-3d page, API and package for embedding 3D models in READMEs

nirholasa4d4e4cc1fe1
diff --git a/api/readme-3d.js b/api/readme-3d.js
new file mode 100644
index 000000000..697329d61
--- /dev/null
+++ b/api/readme-3d.js
@@ -0,0 +1,114 @@
+/**
+ * README 3D: turn any model URL into a block GitHub renders as interactive 3D.
+ *
+ * POST /api/readme-3d { url, budget?, facets?, name?, details? }
+ * → { markdown, facets, source_facets, bytes, github_limit_bytes, fits_github }
+ *
+ * `markdown` is a ```stl fence ready to paste into a README (or wrapped in a
+ * <details> disclosure when `details: true`). GitHub renders ASCII STL fences
+ * natively but stops rendering a markdown file past 512 KB, so the mesh is
+ * decimated to a byte budget (default 150 KB, max 400 KB) with the readme-3d
+ * package's own meshoptimizer pass. The model is fetched through the same
+ * SSRF-hardened fetcher as the MCP 3D tools. Accepts .glb, .gltf (single
+ * file), .obj and .stl. Package: packages/readme-3d. Page: /readme-3d.
+ */
+
+import { convertBytes, toMarkdown, GITHUB_MARKDOWN_LIMIT } from '../packages/readme-3d/src/index.js';
+import { cors, error, json, method, rateLimited, readJson, wrap } from './_lib/http.js';
+import { clientIp, limits } from './_lib/rate-limit.js';
+import { fetchModel, FetchModelError } from './_lib/fetch-model.js';
+
+const MAX_SOURCE_BYTES = 40 * 1024 * 1024;
+const DEFAULT_BUDGET_BYTES = 150 * 1024;
+const MIN_BUDGET_BYTES = 8 * 1024;
+const MAX_BUDGET_BYTES = 400 * 1024;
+const MAX_FACETS = 6000;
+
+const CALLER_FAULT = new Set([
+ 'invalid_url',
+ 'scheme_not_allowed',
+ 'private_address',
+ 'blocked_host',
+ 'dns_failed',
+ 'too_many_redirects',
+ 'file_too_large',
+]);
+
+function modelExtension(bytes, filename) {
+ if (bytes.length >= 4 && bytes[0] === 0x67 && bytes[1] === 0x6c && bytes[2] === 0x54 && bytes[3] === 0x46) {
+ return '.glb';
+ }
+ const m = /\.(glb|gltf|obj|stl)$/i.exec(filename || '');
+ return m ? `.${m[1].toLowerCase()}` : null;
+}
+
+function intInRange(value, min, max, fallback) {
+ if (value === undefined || value === null) return fallback;
+ const n = Number(value);
+ if (!Number.isFinite(n)) return NaN;
+ return Math.min(max, Math.max(min, Math.floor(n)));
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const rl = await limits.readme3dIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ let body;
+ try {
+ body = await readJson(req, 16 * 1024);
+ } catch (err) {
+ return error(res, err.status || 400, 'invalid_body', err.message);
+ }
+ if (!body || typeof body !== 'object' || typeof body.url !== 'string' || !body.url.trim()) {
+ return error(res, 400, 'validation_error', 'url (a public https model URL) is required');
+ }
+
+ const budget = intInRange(body.budget, MIN_BUDGET_BYTES, MAX_BUDGET_BYTES, DEFAULT_BUDGET_BYTES);
+ const facets = intInRange(body.facets, 16, MAX_FACETS, MAX_FACETS);
+ if (Number.isNaN(budget) || Number.isNaN(facets)) {
+ return error(res, 400, 'validation_error', 'budget (bytes) and facets must be numbers');
+ }
+ const name = String(body.name ?? 'model').replace(/[^\w.-]+/g, '-').slice(0, 48) || 'model';
+
+ let model;
+ try {
+ model = await fetchModel(body.url.trim(), { maxBytes: MAX_SOURCE_BYTES, timeoutMs: 25_000 });
+ } catch (err) {
+ if (err instanceof FetchModelError) {
+ const status = CALLER_FAULT.has(err.code) ? (err.code === 'file_too_large' ? 413 : 400) : 502;
+ return error(res, status, err.code, err.message);
+ }
+ throw err;
+ }
+
+ const ext = modelExtension(model.bytes, model.filename);
+ if (!ext) {
+ return error(res, 415, 'unsupported_format', 'the URL must serve a .glb, .gltf, .obj or .stl model');
+ }
+
+ let result;
+ try {
+ result = await convertBytes(model.bytes, ext, { budget, facets, name });
+ } catch (err) {
+ return error(res, 422, 'conversion_failed', err.message);
+ }
+
+ const markdown = toMarkdown(result.stl, { details: body.details === true });
+ const markdownBytes = Buffer.byteLength(markdown);
+ return json(
+ res,
+ 200,
+ {
+ markdown,
+ facets: result.facets,
+ source_facets: result.sourceFacets,
+ bytes: markdownBytes,
+ github_limit_bytes: GITHUB_MARKDOWN_LIMIT,
+ fits_github: markdownBytes < GITHUB_MARKDOWN_LIMIT,
+ },
+ { 'cache-control': 'no-store' },
+ );
+});
diff --git a/docs/api/readme-3d.md b/docs/api/readme-3d.md
new file mode 100644
index 000000000..90e66f0d5
--- /dev/null
+++ b/docs/api/readme-3d.md
@@ -0,0 +1,40 @@
+# README 3D API
+
+Turns a model URL into a fenced block that GitHub renders as an interactive 3D viewer.
+
+```bash
+curl -X POST https://three.ws/api/readme-3d \
+ -H 'content-type: application/json' \
+ -d '{"url":"https://three.ws/avatars/fox.glb","budget":150000}'
+```
+
+## Request
+
+| Field | Type | Default | Notes |
+|---|---|---|---|
+| `url` | string | required | Public https URL of a `.glb`, `.gltf` (single file), `.obj` or `.stl`. Fetched through the SSRF guard; max 40 MB. |
+| `budget` | number | 153600 | Target size in bytes of the STL, clamped to 8 KB to 400 KB. |
+| `facets` | number | 6000 | Upper bound on triangles, 16 to 6000. The budget usually binds first. |
+| `name` | string | `model` | Solid name written into the STL. |
+| `details` | boolean | `false` | Wrap the block in a `<details>` disclosure. |
+
+## Response
+
+```json
+{
+ "markdown": "```stl\nsolid model\n…\n```\n",
+ "facets": 1500,
+ "source_facets": 10194,
+ "bytes": 214000,
+ "github_limit_bytes": 524288,
+ "fits_github": true
+}
+```
+
+GitHub stops rendering a markdown file larger than 512 KB, so keep the README's total size in mind: `npx readme-3d check README.md` reports the headroom.
+
+## Errors
+
+`400` invalid body or blocked URL, `413` source over 40 MB, `415` not a supported model, `422` the file could not be parsed, `429` rate limit (12 per 10 minutes per IP), `502` the model host failed.
+
+The converter is the [`readme-3d`](../../packages/readme-3d) package (`convertBytes`). In product it is reachable from the Forge download menu, the avatar page, the avatar dashboard, model pages and the [/readme-3d](https://three.ws/readme-3d) page.
diff --git a/packages/readme-3d/README.md b/packages/readme-3d/README.md
index 2f4cfec91..d070cd627 100644
--- a/packages/readme-3d/README.md
+++ b/packages/readme-3d/README.md
@@ -4304,12 +4304,21 @@ GitHub renders markdown files up to **512 KB** - beyond that the whole file disp
You don't even need a model. [three.ws Forge](https://three.ws/forge) generates a textured GLB from a text prompt, free, no account:
```bash
-curl -s -X POST https://three.ws/api/forge -H 'content-type: application/json' \
- -d '{"prompt":"a friendly robot mascot, full body"}' # → { glbUrl }
-curl -sL -o mascot.glb "<glbUrl>"
+# Submit a text→3D job, then poll until status is "done"
+RES=$(curl -s -X POST https://three.ws/api/forge -H 'content-type: application/json' \
+ -d '{"prompt":"a friendly robot mascot, full body"}')
+JOB=$(jq -r '.job_id // empty' <<<"$RES")
+until [ "$(jq -r .status <<<"$RES")" = done ]; do
+ [ "$(jq -r .status <<<"$RES")" = failed ] && { echo "$RES" >&2; exit 1; }
+ sleep 5; RES=$(curl -s "https://three.ws/api/forge?job=$JOB")
+done
+curl -sL -o mascot.glb "$(jq -r .glb_url <<<"$RES")"
npx readme-3d mascot.glb --budget 150kb >> README.md
```
+Forge is a job API: `POST /api/forge` returns a `job_id` (a lane that finishes inside the request answers `done` with the `glb_url` immediately), and `GET /api/forge?job=<id>` reports `status` until it is `done` with a `glb_url`.
+Or skip the CLI: `POST https://three.ws/api/readme-3d` with `{"url": "<glb_url>"}` returns the finished block.
+
Walkthrough: [text → 3D → README in five minutes](docs/tutorials/03-text-to-3d-avatar.md).
## More examples
diff --git a/packages/readme-3d/src/index.js b/packages/readme-3d/src/index.js
index ca68eed89..428809232 100644
--- a/packages/readme-3d/src/index.js
+++ b/packages/readme-3d/src/index.js
@@ -34,13 +34,18 @@ export function parseByteSize(value) {
return Math.floor(parseFloat(m[1]) * mult);
}
-/** Load any supported model file into a Z-up triangle soup. */
-export async function loadTriangles(path, { up } = {}) {
- const ext = extname(path).toLowerCase();
- if (!['.glb', '.gltf', '.stl', '.ast', '.obj'].includes(ext)) {
- throw new Error(`unsupported input format: ${ext || path} (use .glb, .gltf, .stl, .ast, or .obj)`);
+const SUPPORTED_EXTENSIONS = ['.glb', '.gltf', '.stl', '.ast', '.obj'];
+
+function assertSupported(ext, label) {
+ if (!SUPPORTED_EXTENSIONS.includes(ext)) {
+ throw new Error(`unsupported input format: ${ext || label} (use .glb, .gltf, .stl, .ast, or .obj)`);
}
- const bytes = await readFile(path);
+}
+
+/** Parse model bytes of a known extension into a Z-up triangle soup. */
+export async function loadTrianglesFromBytes(bytes, ext, { up, label = 'input' } = {}) {
+ ext = ext.toLowerCase();
+ assertSupported(ext, label);
let triangles;
let sourceUp;
if (ext === '.glb' || ext === '.gltf') {
@@ -49,16 +54,21 @@ export async function loadTriangles(path, { up } = {}) {
} else if (ext === '.stl' || ext === '.ast') {
triangles = parseStl(bytes);
sourceUp = up ?? 'z';
- } else if (ext === '.obj') {
- triangles = parseObj(bytes.toString('utf8'));
- sourceUp = up ?? 'y';
} else {
- throw new Error(`unsupported input format: ${ext || path} (use .glb, .gltf, .stl, .ast, or .obj)`);
+ triangles = parseObj(Buffer.from(bytes).toString('utf8'));
+ sourceUp = up ?? 'y';
}
- if (!triangles.length) throw new Error(`no triangles found in ${path}`);
+ if (!triangles.length) throw new Error(`no triangles found in ${label}`);
return sourceUp === 'y' ? yUpToZUp(triangles) : triangles;
}
+/** Load any supported model file into a Z-up triangle soup. */
+export async function loadTriangles(path, { up } = {}) {
+ const ext = extname(path).toLowerCase();
+ assertSupported(ext, path);
+ return loadTrianglesFromBytes(await readFile(path), ext, { up, label: path });
+}
+
/**
* Convert a model file into GitHub-renderable ASCII STL.
*
@@ -72,6 +82,19 @@ export async function loadTriangles(path, { up } = {}) {
* up source up-axis 'y' | 'z' (defaults per format)
*/
export async function convert(path, opts = {}) {
+ return convertTriangles(await loadTriangles(path, { up: opts.up }), opts);
+}
+
+/**
+ * Same as convert(), for model bytes already in memory (an HTTP upload or a
+ * fetched URL). `ext` names the format: '.glb', '.gltf', '.obj' or '.stl'.
+ */
+export async function convertBytes(bytes, ext, opts = {}) {
+ return convertTriangles(await loadTrianglesFromBytes(bytes, ext, { up: opts.up }), opts);
+}
+
+/** Simplify, normalize and serialize an already-loaded Z-up triangle soup. */
+export async function convertTriangles(source, opts = {}) {
const {
facets = 1500,
budget,
@@ -79,10 +102,8 @@ export async function convert(path, opts = {}) {
precision = 2,
normalize: doNormalize = true,
size = 100,
- up,
} = opts;
- const source = await loadTriangles(path, { up });
const budgetBytes = budget ? parseByteSize(budget) : null;
// ~150 bytes per facet at precision 2 is a reliable first estimate.
diff --git a/packages/readme-3d/test/convert.test.js b/packages/readme-3d/test/convert.test.js
index 94e42c046..260cc9161 100644
--- a/packages/readme-3d/test/convert.test.js
+++ b/packages/readme-3d/test/convert.test.js
@@ -9,6 +9,7 @@ import { fileURLToPath } from 'node:url';
import { Document, NodeIO } from '@gltf-transform/core';
import {
convert,
+ convertBytes,
toMarkdown,
checkMarkdownFile,
parseByteSize,
@@ -64,6 +65,16 @@ test('convert() GLB end-to-end: real glTF in, GitHub STL out', async () => {
assert.ok(result.stl.includes('vertex 50.00 50.00 100.00'));
});
+test('convertBytes() matches convert() for the same GLB bytes', async () => {
+ const dir = await tmp();
+ const glb = join(dir, 'cube.glb');
+ await writeCubeGlb(glb);
+ const fromPath = await convert(glb, { name: 'cube' });
+ const fromBytes = await convertBytes(await readFile(glb), '.glb', { name: 'cube' });
+ assert.equal(fromBytes.stl, fromPath.stl);
+ await assert.rejects(convertBytes(new Uint8Array(4), '.xyz'), /unsupported input format/);
+});
+
test('convert() honors a byte budget', async () => {
const dir = await tmp();
const stlPath = join(dir, 'grid.stl');
diff --git a/pages/readme-3d.html b/pages/readme-3d.html
new file mode 100644
index 000000000..1fc3e4a6c
--- /dev/null
+++ b/pages/readme-3d.html
@@ -0,0 +1,133 @@
+<!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" />
+ <title>README 3D · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <meta name="theme-color" content="#000000" />
+ <meta name="description" content="Put an interactive 3D model in any GitHub README. Paste a GLB, glTF, OBJ or STL URL and get a block GitHub renders as a rotatable 3D viewer, sized to fit GitHub's markdown limit." />
+
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/readme-3d" />
+ <meta property="og:title" content="README 3D · three.ws" />
+ <meta property="og:description" content="Turn any 3D model into a block GitHub renders as an interactive viewer in your README." />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&amp;t=README+3D&amp;d=Turn+any+3D+model+into+a+block+GitHub+renders+as+an+interactive+viewer.&amp;p=%2Freadme-3d" />
+ <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" />
+ <link rel="canonical" href="https://three.ws/readme-3d" />
+
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/manifest.webmanifest" />
+ <link rel="stylesheet" href="/style.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ </head>
+ <body>
+ <div id="nav-container"></div>
+
+ <main class="r3-wrap">
+ <p class="r3-crumb"><a href="/">Home</a> / <a href="/forge">Forge</a> / README 3D</p>
+ <h1 class="r3-h1">3D models in your GitHub README</h1>
+ <p class="r3-lede">
+ GitHub renders a <code>```stl</code> code fence as an interactive 3D viewer. Paste a model URL
+ and get a block you can drop into any README, issue or pull request, simplified to fit
+ GitHub's 512 KB markdown limit.
+ </p>
+
+ <section class="r3-card" aria-labelledby="r3-try">
+ <h2 class="r3-h2" id="r3-try">Try it</h2>
+ <form id="r3-form" class="r3-form" novalidate>
+ <label class="r3-field r3-field-url">
+ <span>Model URL (.glb, .gltf, .obj or .stl, public https)</span>
+ <input id="r3-url" name="url" type="url" inputmode="url" autocomplete="off" required
+ placeholder="https://three.ws/avatars/fox.glb" />
+ </label>
+ <label class="r3-field">
+ <span>Size budget</span>
+ <select id="r3-budget" name="budget">
+ <option value="60000">Small (60 KB), hero model in a busy README</option>
+ <option value="150000" selected>Medium (150 KB), detailed hero model</option>
+ <option value="300000">Large (300 KB), dedicated model page</option>
+ </select>
+ </label>
+ <button type="submit" id="r3-go" class="r3-btn r3-btn-primary">Convert</button>
+ </form>
+ <div class="r3-samples" role="group" aria-label="Example models">
+ <span class="r3-dim">Examples:</span>
+ <button type="button" class="r3-chip" data-url="https://three.ws/avatars/fox.glb">Fox</button>
+ <button type="button" class="r3-chip" data-url="https://three.ws/avatars/mannequin.glb">Mannequin</button>
+ <button type="button" class="r3-chip" data-url="https://three.ws/avatars/default.glb">Default avatar</button>
+ </div>
+
+ <div id="r3-status" class="r3-status" role="status" aria-live="polite"></div>
+
+ <div id="r3-result" class="r3-result" hidden>
+ <div class="r3-preview-col">
+ <canvas id="r3-canvas" class="r3-canvas" width="480" height="360"
+ aria-label="Preview of the simplified model. Drag to rotate."></canvas>
+ <p class="r3-dim r3-small">What GitHub will render. Drag to rotate.</p>
+ </div>
+ <div class="r3-out-col">
+ <dl class="r3-stats" id="r3-stats"></dl>
+ <div class="r3-actions">
+ <button type="button" id="r3-copy" class="r3-btn r3-btn-primary">Copy for README</button>
+ <button type="button" id="r3-download" class="r3-btn">Download .md</button>
+ </div>
+ <label class="r3-field">
+ <span>Markdown (truncated here, the copied block is complete)</span>
+ <textarea id="r3-md" readonly rows="8" spellcheck="false"></textarea>
+ </label>
+ </div>
+ </div>
+ </section>
+
+ <section class="r3-grid">
+ <article class="r3-card">
+ <h2 class="r3-h2">From anywhere on three.ws</h2>
+ <p class="r3-note">
+ Every model you make has a one-click path: <strong>Forge</strong> results (download menu,
+ <em>GitHub README 3D</em>), your <strong>avatar page</strong> (Download menu,
+ <em>README 3D</em>), the <strong>avatar dashboard</strong> (card menu), and any
+ <strong>model page</strong> (<em>Copy for GitHub README</em>).
+ </p>
+ </article>
+ <article class="r3-card">
+ <h2 class="r3-h2">From the command line</h2>
+ <pre class="r3-code"><code>npx readme-3d model.glb --budget 150kb &gt;&gt; README.md
+npx readme-3d check README.md</code></pre>
+ <p class="r3-note">The <a href="https://github.com/nirholas/readme-3d">readme-3d</a> package also takes OBJ and STL.</p>
+ </article>
+ <article class="r3-card">
+ <h2 class="r3-h2">From the API</h2>
+ <pre class="r3-code"><code>curl -X POST https://three.ws/api/readme-3d \
+ -H 'content-type: application/json' \
+ -d '{"url":"https://three.ws/avatars/fox.glb","budget":150000}'
+# → { "markdown": "```stl\n…", "facets": 1500, "fits_github": true }</code></pre>
+ <p class="r3-note">Free, no key. 12 conversions per 10 minutes per IP.</p>
+ </article>
+ </section>
+
+ <section class="r3-card">
+ <h2 class="r3-h2">Make a model first</h2>
+ <p class="r3-note">
+ No model yet? <a href="/forge">Forge</a> generates a textured GLB from a text prompt in about a minute.
+ Generate, open the download menu, pick <em>GitHub README 3D</em>, and paste.
+ </p>
+ </section>
+ </main>
+
+ <script type="module" src="/src/readme-3d.js"></script>
+ <script src="/nav.js" defer></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ <script type="module" src="/i18n.js"></script>
+ </body>
+</html>
diff --git a/src/readme-3d-copy.js b/src/readme-3d-copy.js
new file mode 100644
index 000000000..8b7b472e7
--- /dev/null
+++ b/src/readme-3d-copy.js
@@ -0,0 +1,86 @@
+// "Copy as GitHub README 3D": turns a model URL into a ```stl fence that
+// GitHub renders as an interactive 3D viewer, via POST /api/readme-3d
+// (packages/readme-3d does the decimation). Shared by the forge export menu,
+// the avatar page, the model page and the /readme-3d page so every surface
+// reports the same sizes and fails the same way.
+
+const ENDPOINT = '/api/readme-3d';
+
+export class Readme3dError extends Error {
+ constructor(message, code = 'readme_3d_failed') {
+ super(message);
+ this.code = code;
+ }
+}
+
+/** @returns {Promise<{ markdown: string, facets: number, sourceFacets: number, bytes: number, fitsGithub: boolean }>} */
+export async function fetchReadme3d(modelUrl, { name, budget, details } = {}) {
+ let absolute;
+ try {
+ absolute = new URL(modelUrl, location.href);
+ } catch {
+ throw new Readme3dError('this model has no usable URL', 'invalid_url');
+ }
+ if (absolute.protocol !== 'https:' && absolute.protocol !== 'http:') {
+ throw new Readme3dError(
+ 'only a saved model can be converted: reset your mesh edits and try again',
+ 'unsaved_model',
+ );
+ }
+ const res = await fetch(ENDPOINT, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ url: absolute.href, name, budget, details }),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 429) {
+ throw new Readme3dError('too many conversions, wait a few minutes and retry', 'rate_limited');
+ }
+ if (!res.ok) {
+ throw new Readme3dError(
+ data.error_description || data.error || `the converter returned ${res.status}`,
+ data.error || 'readme_3d_failed',
+ );
+ }
+ return {
+ markdown: data.markdown,
+ facets: data.facets,
+ sourceFacets: data.source_facets,
+ bytes: data.bytes,
+ fitsGithub: data.fits_github,
+ };
+}
+
+function saveMarkdownFile(markdown, filename) {
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(new Blob([markdown], { type: 'text/markdown' }));
+ a.download = filename;
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(a.href), 30_000);
+}
+
+/**
+ * Convert and put the block on the clipboard. When the browser refuses the
+ * clipboard (insecure context, or a gesture lost to the network wait), the
+ * block is saved as a .md file instead, so the work is never thrown away.
+ * @returns {Promise<{ delivery: 'clipboard' | 'file', facets: number, bytes: number, fitsGithub: boolean, markdown: string }>}
+ */
+export async function copyReadme3d(modelUrl, opts = {}) {
+ const result = await fetchReadme3d(modelUrl, opts);
+ let delivery = 'clipboard';
+ try {
+ await navigator.clipboard.writeText(result.markdown);
+ } catch {
+ delivery = 'file';
+ saveMarkdownFile(result.markdown, `${opts.name || 'model'}-readme-3d.md`);
+ }
+ return { ...result, delivery };
+}
+
+export function describeResult(r) {
+ const kb = Math.round(r.bytes / 1024);
+ const where = r.delivery === 'file' ? 'saved as .md' : 'copied';
+ return `${where} ✓ ${r.facets.toLocaleString()} facets, ${kb} KB`;
+}
diff --git a/src/readme-3d.css b/src/readme-3d.css
new file mode 100644
index 000000000..91a428d1e
--- /dev/null
+++ b/src/readme-3d.css
@@ -0,0 +1,111 @@
+/* README 3D page (/readme-3d). Tokens come from public/tokens.css, so the page
+ follows the light and dark themes with no overrides of its own. */
+
+.r3-wrap {
+ width: 100%;
+ max-width: 1040px;
+ margin: 0 auto;
+ padding: calc(var(--space-md) * 2) var(--space-md) calc(var(--space-md) * 4);
+}
+.r3-crumb { font: var(--text-sm) var(--font-body); color: var(--ink-dim); margin: 0 0 var(--space-lg); }
+.r3-crumb a { color: inherit; }
+.r3-crumb a:hover { color: var(--ink); }
+.r3-h1 { font-family: var(--font-display); font-size: var(--text-xl); color: var(--ink-bright); margin: 0; line-height: 1.15; }
+.r3-h2 { font-size: var(--text-lg); color: var(--ink-bright); margin: 0 0 var(--space-sm); }
+.r3-lede { color: var(--ink-dim); font-size: var(--text-md); line-height: 1.55; margin: var(--space-sm) 0 var(--space-lg); max-width: 62ch; }
+.r3-note { color: var(--ink-dim); font-size: var(--text-sm); line-height: 1.55; margin: var(--space-sm) 0 0; }
+.r3-note a, .r3-lede a { color: var(--ink); }
+.r3-dim { color: var(--ink-dim); }
+.r3-small { font-size: var(--text-xs); margin: var(--space-xs) 0 0; }
+.r3-wrap code { font-family: var(--font-mono, ui-monospace, monospace); font-size: 0.92em; }
+
+.r3-card {
+ background: var(--card-bg);
+ border: 1px solid var(--card-border);
+ border-radius: var(--radius-control);
+ padding: var(--space-md);
+ margin-bottom: var(--space-md);
+ min-width: 0;
+}
+.r3-grid { display: grid; gap: var(--space-md); grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); }
+.r3-grid .r3-card { margin-bottom: 0; }
+
+.r3-form { display: grid; gap: var(--space-md); grid-template-columns: 1fr; align-items: end; }
+@media (min-width: 760px) { .r3-form { grid-template-columns: 1fr minmax(220px, 280px) auto; } }
+.r3-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; font-size: var(--text-sm); color: var(--ink-dim); }
+.r3-field input, .r3-field select, .r3-field textarea {
+ width: 100%;
+ font: var(--text-sm) var(--font-body);
+ color: var(--ink);
+ background: var(--surface-2);
+ border: 1px solid var(--stroke-strong);
+ border-radius: var(--radius-control);
+ padding: var(--space-sm);
+ min-width: 0;
+}
+.r3-field textarea { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-xs); resize: vertical; }
+.r3-field input:focus-visible, .r3-field select:focus-visible, .r3-field textarea:focus-visible,
+.r3-btn:focus-visible, .r3-chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
+
+.r3-btn {
+ font: 600 var(--text-sm) var(--font-body);
+ color: var(--btn-secondary-fg);
+ background: var(--btn-secondary-bg);
+ border: 1px solid var(--btn-secondary-border);
+ border-radius: var(--radius-control);
+ padding: var(--space-sm) var(--space-md);
+ cursor: pointer;
+ transition: background 0.15s ease, transform 0.1s ease;
+}
+.r3-btn:hover { background: var(--btn-secondary-bg-hover); }
+.r3-btn:active { background: var(--btn-secondary-bg-active); transform: translateY(1px); }
+.r3-btn-primary { color: var(--btn-primary-fg); background: var(--btn-primary-bg); border-color: var(--btn-primary-border); }
+.r3-btn-primary:hover { background: var(--btn-primary-bg-hover); }
+.r3-btn-primary:active { background: var(--btn-primary-bg-active); }
+.r3-btn[disabled] { opacity: 0.55; cursor: progress; }
+
+.r3-samples { display: flex; flex-wrap: wrap; align-items: center; gap: var(--space-sm); margin-top: var(--space-md); font-size: var(--text-sm); }
+.r3-chip {
+ font: var(--text-sm) var(--font-body);
+ color: var(--ink);
+ background: var(--surface-2);
+ border: 1px solid var(--stroke);
+ border-radius: 999px;
+ padding: 2px 12px;
+ cursor: pointer;
+ transition: background 0.15s ease;
+}
+.r3-chip:hover { background: var(--surface-3); }
+.r3-chip:active { background: var(--surface-3); transform: translateY(1px); }
+
+.r3-status { min-height: 1.4em; margin-top: var(--space-md); font-size: var(--text-sm); color: var(--ink-dim); }
+.r3-status.is-error { color: var(--danger); }
+.r3-skeleton {
+ display: inline-block; width: 14em; max-width: 100%; height: 0.9em; border-radius: 4px; vertical-align: middle;
+ background: linear-gradient(90deg, var(--surface-2), var(--surface-3), var(--surface-2));
+ background-size: 200% 100%; animation: r3-shimmer 1.2s linear infinite;
+}
+@keyframes r3-shimmer { to { background-position: -200% 0; } }
+@media (prefers-reduced-motion: reduce) { .r3-skeleton { animation: none; } .r3-btn { transition: none; } }
+
+.r3-result { display: grid; gap: var(--space-md); grid-template-columns: 1fr; margin-top: var(--space-md); }
+.r3-result[hidden] { display: none; }
+@media (min-width: 760px) { .r3-result { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); } }
+.r3-canvas {
+ width: 100%; height: auto; aspect-ratio: 4 / 3; display: block;
+ background: var(--surface-2); border: 1px solid var(--stroke); border-radius: var(--radius-control);
+ cursor: grab; touch-action: none;
+}
+.r3-canvas:active { cursor: grabbing; }
+.r3-out-col { display: flex; flex-direction: column; gap: var(--space-md); min-width: 0; }
+.r3-stats { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: var(--space-sm); margin: 0; }
+.r3-stats div { background: var(--surface-2); border: 1px solid var(--stroke); border-radius: var(--radius-control); padding: var(--space-sm); min-width: 0; }
+.r3-stats dt { font-size: var(--text-xs); color: var(--ink-dim); }
+.r3-stats dd { margin: 2px 0 0; font-size: var(--text-md); color: var(--ink-bright); font-weight: 600; overflow-wrap: anywhere; }
+.r3-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm); }
+
+.r3-code {
+ margin: 0; padding: var(--space-sm); overflow-x: auto;
+ background: var(--surface-2); border: 1px solid var(--stroke); border-radius: var(--radius-control);
+ font-size: var(--text-xs); line-height: 1.5; color: var(--ink);
+}
diff --git a/src/readme-3d.js b/src/readme-3d.js
new file mode 100644
index 000000000..ddeb7c9b9
--- /dev/null
+++ b/src/readme-3d.js
@@ -0,0 +1,177 @@
+/**
+ * /readme-3d: convert a model URL into a GitHub-renderable ```stl block.
+ *
+ * Calls POST /api/readme-3d through the shared client (readme-3d-copy.js) and
+ * previews the returned STL with three.js, so what the visitor sees here is
+ * the exact geometry GitHub will render.
+ */
+
+import './readme-3d.css';
+import { fetchReadme3d } from './readme-3d-copy.js';
+
+const $ = (id) => document.getElementById(id);
+const form = $('r3-form');
+const urlInput = $('r3-url');
+const budgetSelect = $('r3-budget');
+const goBtn = $('r3-go');
+const statusEl = $('r3-status');
+const resultEl = $('r3-result');
+const statsEl = $('r3-stats');
+const mdArea = $('r3-md');
+const copyBtn = $('r3-copy');
+const downloadBtn = $('r3-download');
+const canvas = $('r3-canvas');
+
+const TEXTAREA_PREVIEW_CHARS = 1800;
+const DEFAULT_URL = 'https://three.ws/avatars/fox.glb';
+
+let current = null;
+let preview = null;
+
+function setStatus(html, isError = false) {
+ statusEl.innerHTML = html;
+ statusEl.classList.toggle('is-error', isError);
+}
+
+function stat(label, value) {
+ return `<div><dt>${label}</dt><dd>${value}</dd></div>`;
+}
+
+function renderStats(r) {
+ const kb = (r.bytes / 1024).toFixed(0);
+ statsEl.innerHTML =
+ stat('Facets', `${r.facets.toLocaleString()}`) +
+ stat('Source facets', r.sourceFacets.toLocaleString()) +
+ stat('Block size', `${kb} KB ${r.fitsGithub ? '✓' : '(over GitHub limit)'}`);
+}
+
+async function ensurePreview() {
+ if (preview) return preview;
+ const [THREE, { STLLoader }, { OrbitControls }] = await Promise.all([
+ import('three'),
+ import('three/addons/loaders/STLLoader.js'),
+ import('three/addons/controls/OrbitControls.js'),
+ ]);
+ const renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true });
+ renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
+ const scene = new THREE.Scene();
+ const camera = new THREE.PerspectiveCamera(40, 4 / 3, 0.1, 2000);
+ scene.add(new THREE.HemisphereLight(0xffffff, 0x445566, 1.6));
+ const key = new THREE.DirectionalLight(0xffffff, 2.2);
+ key.position.set(120, -160, 200);
+ scene.add(key);
+ const controls = new OrbitControls(camera, canvas);
+ controls.enableDamping = true;
+ controls.autoRotate = !matchMedia('(prefers-reduced-motion: reduce)').matches;
+ controls.autoRotateSpeed = 1.5;
+ preview = { THREE, STLLoader, renderer, scene, camera, controls, mesh: null };
+
+ const resize = () => {
+ const w = canvas.clientWidth;
+ const h = canvas.clientHeight;
+ if (!w || !h) return;
+ renderer.setSize(w, h, false);
+ camera.aspect = w / h;
+ camera.updateProjectionMatrix();
+ };
+ new ResizeObserver(resize).observe(canvas);
+ resize();
+ renderer.setAnimationLoop(() => {
+ controls.update();
+ renderer.render(scene, camera);
+ });
+ return preview;
+}
+
+async function showPreview(markdown) {
+ const stl = markdown.replace(/^[\s\S]*?```stl\n/, '').replace(/\n```[\s\S]*$/, '');
+ const p = await ensurePreview();
+ const geometry = new p.STLLoader().parse(stl);
+ geometry.computeVertexNormals();
+ if (p.mesh) {
+ p.scene.remove(p.mesh);
+ p.mesh.geometry.dispose();
+ } else {
+ p.material = new p.THREE.MeshStandardMaterial({ color: 0x9fb4ff, roughness: 0.55, metalness: 0.1 });
+ }
+ p.mesh = new p.THREE.Mesh(geometry, p.material);
+ p.mesh.rotation.x = -Math.PI / 2; // STL is Z-up, three.js is Y-up
+ p.scene.add(p.mesh);
+ geometry.computeBoundingBox();
+ const size = geometry.boundingBox.getSize(new p.THREE.Vector3());
+ const radius = Math.max(size.x, size.y, size.z) * 1.4 || 100;
+ p.camera.position.set(radius * 0.9, radius * 0.5, radius * 1.4);
+ p.controls.target.set(0, size.z / 2, 0);
+ p.controls.update();
+}
+
+async function convert(modelUrl) {
+ goBtn.disabled = true;
+ resultEl.hidden = true;
+ setStatus('<span class="r3-skeleton"></span> Fetching and simplifying the model…');
+ try {
+ const result = await fetchReadme3d(modelUrl, { name: 'model', budget: Number(budgetSelect.value) });
+ current = result;
+ renderStats(result);
+ const text = result.markdown;
+ mdArea.value =
+ text.length > TEXTAREA_PREVIEW_CHARS ? `${text.slice(0, TEXTAREA_PREVIEW_CHARS)}\n…` : text;
+ resultEl.hidden = false;
+ await showPreview(text);
+ setStatus(
+ result.fitsGithub
+ ? 'Ready. Paste the block into a README, issue or pull request on GitHub.'
+ : 'This block is over GitHub\'s 512 KB markdown limit. Pick a smaller size budget.',
+ !result.fitsGithub,
+ );
+ } catch (err) {
+ current = null;
+ const why = err?.message || 'the conversion failed';
+ setStatus(`Could not convert this model: ${why}.`, true);
+ } finally {
+ goBtn.disabled = false;
+ }
+}
+
+form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const value = urlInput.value.trim();
+ if (!value) {
+ setStatus('Enter a public https URL to a .glb, .gltf, .obj or .stl file.', true);
+ urlInput.focus();
+ return;
+ }
+ convert(value);
+});
+
+document.querySelectorAll('.r3-chip').forEach((chip) => {
+ chip.addEventListener('click', () => {
+ urlInput.value = chip.dataset.url;
+ convert(chip.dataset.url);
+ });
+});
+
+copyBtn.addEventListener('click', async () => {
+ if (!current) return;
+ try {
+ await navigator.clipboard.writeText(current.markdown);
+ setStatus('Copied. Paste it into your README.');
+ } catch {
+ setStatus('Your browser blocked the clipboard. Use Download .md instead.', true);
+ }
+});
+
+downloadBtn.addEventListener('click', () => {
+ if (!current) return;
+ const a = document.createElement('a');
+ a.href = URL.createObjectURL(new Blob([current.markdown], { type: 'text/markdown' }));
+ a.download = 'model-readme-3d.md';
+ document.body.appendChild(a);
+ a.click();
+ a.remove();
+ setTimeout(() => URL.revokeObjectURL(a.href), 30_000);
+});
+
+const preset = new URLSearchParams(location.search).get('url');
+urlInput.value = preset || DEFAULT_URL;
+convert(urlInput.value);