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(materialize): the surface where a generation becomes an object you can hold
nirholas8035e6e44d3b
diff --git a/STRUCTURE.md b/STRUCTURE.mdindex 88c3fa02d..feecc81a6 100644--- a/STRUCTURE.md+++ b/STRUCTURE.md@@ -156,7 +156,7 @@ bottom.| Forge thumbnail coverage | [api/_lib/forge-thumbs.js](api/_lib/forge-thumbs.js) + cron [api/cron/forge-thumbnail-backfill.js](api/cron/forge-thumbnail-backfill.js) (`*/5`) | Live | Gives every finished forge model a real picture. The dominant free NVIDIA/TRELLIS lane is geometry-first and paints no reference image, so ~83% of finished `forge_creations` land with `preview_image_url = NULL` and render as gradient placeholders on every browse surface (showcase, gallery, `/community`, `/search`, creator portfolios). This cron claims the newest previewless models, renders each GLB to a 768² PNG via the shared headless-chromium renderer ([api/_lib/render-glb.js](api/_lib/render-glb.js)), uploads it, and fills the preview slot — object confirmed in R2 **before** the key is committed (same ORB-safety invariant as avatars), and **fill-only** so a maker's captured poster always wins. Self-provisioning claim ledger (`forge_thumbnail_backfill`, created at runtime), bounded attempts, lease-based reclaim, browser-death batch abort with attempt refund. `?dry_run=1` reports coverage. Tests: [tests/forge-thumbs.test.js](tests/forge-thumbs.test.js). || Catalog quality gate (what earns a slot in the public catalog) | [api/_lib/seed-quality.js](api/_lib/seed-quality.js), consumed by [api/cron/forge-seed-cron.js](api/cron/forge-seed-cron.js) | Live · mesh stage always on, vision stage behind `SEED_CRON_VISION` | The bar every platform-seeded model clears before it reaches [/characters](public/characters.html) or [/objects](pages/objects.html). Nobody asked for seeded content, so it has to earn its slot: a user who generates a coarse mesh chose to, a visitor browsing the catalog did not. Two stages, cheapest first. **Mesh sanity** is free and deterministic (reuses [api/_lib/glb-quality.js](api/_lib/glb-quality.js), the interactive forge's own scorer, plus catalog bounds: vertex floor/ceiling, byte floor/ceiling, must-carry-a-texture, non-collapsed bbox, and a mesh-count rule that applies to `avatar` only because a prop may legitimately be a pile of parts): a degenerate blob is rejected here for the price of a GLB fetch and never costs a model call. **Vision judge** renders one view and asks two questions: realism via `judgeOnce` imported (never forked) from [api/_lib/quality-bench.js](api/_lib/quality-bench.js) so the gate and the regression bench can never disagree about what a score means, plus a catalog-specific rig-readiness check (one complete humanoid with separated limbs, or a bust / blob / crowd?). **Fails closed on mesh, fails soft on vision:** an unreachable judge publishes on the mesh verdict marked `vision_unavailable`, because recording a Vertex outage as a quality reject would corrupt the accept-rate maths. Rejects are copied (never moved) to `forge/rejected/` with a full-verdict JSON sidecar, which is the tuning dataset. `SEED_GATE_VERSION` stamps every verdict since an accept rate is only comparable within one version. Two transports (in-process for Cloud Run, remote via `/api/render/avatar-clip` + `/api/vision` for a credential-less workstation) share one decision path. Docs: [docs/seed-quality.md](docs/seed-quality.md). Tests: [tests/seed-quality.test.js](tests/seed-quality.test.js) || Forge-Off (community voting + weekly board) | Store [api/_lib/forge-store.js](api/_lib/forge-store.js) (`castVote`/`removeVote`/`listShowcase` sort+voter/`forgeOffWeekStart`), endpoint [api/forge-vote.js](api/forge-vote.js), board read [api/forge-gallery.js](api/forge-gallery.js) (`scope=community&sort=top&window=week`), weekly crown cron [api/cron/forge-off-crown.js](api/cron/forge-off-crown.js) (`7 0 * * 1`), UI [src/forge-showcase.js](src/forge-showcase.js) + `/forge-studio` twin [src/forge-studio/forge-showcase.js](src/forge-studio/forge-showcase.js), schema [migration 20260625120000_forge_board.sql](api/_lib/migrations/20260625120000_forge_board.sql) | Live | Turns the "Fresh from the Forge" strip on [/forge](pages/forge.html) into a live board: auth-free upvotes (one per browser, keyed to the same `forge:cid` id as "Your creations"), a Fresh/Top-this-week sort toggle, optimistic vote pills that reconcile against the authoritative `vote_count` (recomputed from `forge_votes`, never a drifting counter), and a Monday-00:07-UTC cron that permanently crowns each week's top-voted creation into `forge_board_winners`. The crown is the writer the [Sketchfab showcase](docs/sketchfab.md) cron's strongest tier had been waiting on. Docs: [docs/forge-off.md](docs/forge-off.md). Tests: [tests/api/forge-gallery-community.test.js](tests/api/forge-gallery-community.test.js) |-| Materialize (generation to a physical object) | Page [pages/materialize.html](pages/materialize.html) `→ /materialize` + [src/materialize-lib.js](src/materialize-lib.js), order tracking [src/materialize-order.js](src/materialize-order.js) `→ /materialize/orders/:id`, operator console [pages/materialize-ops.html](pages/materialize-ops.html) + [src/materialize-ops.js](src/materialize-ops.js) `→ /materialize/ops`, certificate page [pages/certificate.html](pages/certificate.html) `→ /cert/:id` + [src/certificate-page.js](src/certificate-page.js), insert card [pages/print-insert.html](pages/print-insert.html) `→ /materialize/insert/:id`. Engine [api/_lib/print/](api/_lib/print) (mesh-io, topology, bvh, voxel-sdf, analyze, repair, export-stl, export-3mf, quote, gate, rules, certificate, editions, adapters, fulfillment, ops-notify). State machine [api/_lib/print-store.js](api/_lib/print-store.js). HTTP [api/print/](api/print) (catalog, quote, prepare, upload, orders, orders/[id], orders/[id]/confirm, certs/[id], editions, ops/[action], webhook/[provider]) plus the agent lane [api/x402/print-order.js](api/x402/print-order.js). Catalog [data/print-catalog.json](data/print-catalog.json). Sweep [api/cron/print-orders-sync.js](api/cron/print-orders-sync.js) | Live | The physical lane of the forge: any generation becomes a real print, shipped. One `POST /api/print/quote` both analyzes the mesh (manifold check, shells, open edges, thinnest wall, exact volume via the Manifold WASM kernel, a 0-100 score with buyer-readable deductions) and prices it from one tunable catalog file, returning an HMAC-signed 24h quote token that carries every priced parameter so checkout cannot be replayed or edited. Prepare reconstructs the solid, fills holes, scales, optionally hollows with drain holes, and writes STL / 3MF (with per-vertex colour sampled from the source texture, which is what makes a full-colour print possible) / repaired GLB. Checkout is USDC on Solana for humans and x402 for agents, on the same pipeline: `POST /api/x402/print-order` validates the token and address BEFORE issuing the 402, so a malformed order is refused for free. Fulfillment is an adapter layer (manual operator lane plus a partner API) behind a whitelisted state machine; provider webhooks are HMAC-verified against the raw bytes and idempotent by delivery id. Every shipped print gets a Solana-attested certificate hashing the exact manufactured file. **The fabrication gate runs twice and is not advisory:** deterministically at quote time (before money moves, returning 451 with the category and the policy link) and again on the paid order through the LLM chain, with `submitOrder()` refusing anything without a recorded `allow` verdict. Docs: [docs/materialize.md](docs/materialize.md), operator runbook [docs/ops/materialize-fulfillment.md](docs/ops/materialize-fulfillment.md). Spec: [specs/PRINT_PIPELINE.md](specs/PRINT_PIPELINE.md). Tests: [tests/api/print-fabrication-gate.test.js](tests/api/print-fabrication-gate.test.js), [tests/api/print-gate-wiring.test.js](tests/api/print-gate-wiring.test.js), [tests/api/print-exporters.test.js](tests/api/print-exporters.test.js), [tests/print-store.test.js](tests/print-store.test.js), [tests/print-adapter-contract.test.js](tests/print-adapter-contract.test.js), [tests/print-certificate.test.js](tests/print-certificate.test.js), [tests/print-ops-authorization.test.js](tests/print-ops-authorization.test.js), [tests/print-webhook-idempotency.test.js](tests/print-webhook-idempotency.test.js), [tests/print-orders-sync.test.js](tests/print-orders-sync.test.js), [tests/print-fulfillment-routing.test.js](tests/print-fulfillment-routing.test.js) |+| Materialize (generation to a physical object) | Page [pages/materialize.html](pages/materialize.html) `→ /materialize` + [src/materialize.js](src/materialize.js) + [src/materialize-lib.js](src/materialize-lib.js), order tracking [pages/materialize-order.html](pages/materialize-order.html) + [src/materialize-order.js](src/materialize-order.js) `→ /materialize/orders/:id`, operator console [pages/materialize-ops.html](pages/materialize-ops.html) + [src/materialize-ops.js](src/materialize-ops.js) `→ /materialize/ops`, certificate page [pages/certificate.html](pages/certificate.html) `→ /cert/:id` + [src/certificate-page.js](src/certificate-page.js), insert card [pages/print-insert.html](pages/print-insert.html) `→ /materialize/insert/:id`. Engine [api/_lib/print/](api/_lib/print) (mesh-io, topology, bvh, voxel-sdf, analyze, repair, export-stl, export-3mf, quote, gate, rules, certificate, editions, adapters, fulfillment, ops-notify). State machine [api/_lib/print-store.js](api/_lib/print-store.js). HTTP [api/print/](api/print) (catalog, quote, prepare, upload, orders, orders/[id], orders/[id]/confirm, certs/[id], editions, ops/[action], webhook/[provider]) plus the agent lane [api/x402/print-order.js](api/x402/print-order.js). Catalog [data/print-catalog.json](data/print-catalog.json). Sweep [api/cron/print-orders-sync.js](api/cron/print-orders-sync.js) | Live | The physical lane of the forge: any generation becomes a real print, shipped. One `POST /api/print/quote` both analyzes the mesh (manifold check, shells, open edges, thinnest wall, exact volume via the Manifold WASM kernel, a 0-100 score with buyer-readable deductions) and prices it from one tunable catalog file, returning an HMAC-signed 24h quote token that carries every priced parameter so checkout cannot be replayed or edited. Prepare reconstructs the solid, fills holes, scales, optionally hollows with drain holes, and writes STL / 3MF (with per-vertex colour sampled from the source texture, which is what makes a full-colour print possible) / repaired GLB. Checkout is USDC on Solana for humans and x402 for agents, on the same pipeline: `POST /api/x402/print-order` validates the token and address BEFORE issuing the 402, so a malformed order is refused for free. Fulfillment is an adapter layer (manual operator lane plus a partner API) behind a whitelisted state machine; provider webhooks are HMAC-verified against the raw bytes and idempotent by delivery id. Every shipped print gets a Solana-attested certificate hashing the exact manufactured file. **The fabrication gate runs twice and is not advisory:** deterministically at quote time (before money moves, returning 451 with the category and the policy link) and again on the paid order through the LLM chain, with `submitOrder()` refusing anything without a recorded `allow` verdict. Docs: [docs/materialize.md](docs/materialize.md), operator runbook [docs/ops/materialize-fulfillment.md](docs/ops/materialize-fulfillment.md). Spec: [specs/PRINT_PIPELINE.md](specs/PRINT_PIPELINE.md). Tests: [tests/api/print-fabrication-gate.test.js](tests/api/print-fabrication-gate.test.js), [tests/api/print-gate-wiring.test.js](tests/api/print-gate-wiring.test.js), [tests/api/print-exporters.test.js](tests/api/print-exporters.test.js), [tests/print-store.test.js](tests/print-store.test.js), [tests/print-adapter-contract.test.js](tests/print-adapter-contract.test.js), [tests/print-certificate.test.js](tests/print-certificate.test.js), [tests/print-ops-authorization.test.js](tests/print-ops-authorization.test.js), [tests/print-webhook-idempotency.test.js](tests/print-webhook-idempotency.test.js), [tests/print-orders-sync.test.js](tests/print-orders-sync.test.js), [tests/print-fulfillment-routing.test.js](tests/print-fulfillment-routing.test.js), [tests/print-quote-engine.test.js](tests/print-quote-engine.test.js), [tests/materialize-lib.test.js](tests/materialize-lib.test.js) || Realism quality bench | Benchmark [data/quality-bench/prompts.json](data/quality-bench/prompts.json) (23 fixed prompts + 3 CC0 reference photos), runner [scripts/quality-bench.mjs](scripts/quality-bench.mjs), shared generate/render/judge core [api/_lib/quality-bench.js](api/_lib/quality-bench.js), dashboard [api/quality-bench.js](api/quality-bench.js) + [pages/quality-bench.html](pages/quality-bench.html) `→ /quality-bench` (internal, not in `data/pages.json`), weekly smoke cron [api/cron/quality-bench.js](api/cron/quality-bench.js) (`23 3 * * 1`) | Live | The measurement loop the realism campaign hangs on: fires the fixed prompt set through the real `/api/forge` path, renders 3 canonical views per result with the same headless three.js renderer as the avatar clip/OG-card renders ([api/_lib/render-clip.js](api/_lib/render-clip.js)), and scores every view with Vertex Gemini vision (`gemini-2.5-pro`, temperature 0, scored twice and averaged, judge never sees forge's internal prompt-enhancement text). Runs are committed append-only JSON under `data/quality-bench/runs/`; the dashboard renders score trends by lane/tier/subject-class, a worst-5 critique gallery, and the full results table. `node scripts/quality-bench.mjs --compare=latest,previous` exits nonzero on a >1.0 mean drop — run it before/after any forge change that could affect quality. Docs: [data/quality-bench/README.md](data/quality-bench/README.md). || Likeness bench (Phase 1 verification metric) | Scoring core [api/_lib/likeness-score.js](api/_lib/likeness-score.js), face-embedding runtime [api/_lib/face-embed.js](api/_lib/face-embed.js), store + distribution queries [api/_lib/likeness-store.js](api/_lib/likeness-store.js) ([schema](api/_lib/migrations/20260814000000_avatar_likeness_scores.sql)), weekly sweep [api/cron/likeness-eval.js](api/cron/likeness-eval.js) (`47 3 * * 1`), by-hand runner [scripts/likeness-eval.mjs](scripts/likeness-eval.mjs), internal board [api/likeness-bench.js](api/likeness-bench.js) + [pages/likeness-bench.html](pages/likeness-bench.html) `→ /likeness-bench` (admin or `x-ops-secret`, not in `data/pages.json`) | Live · applied 2026-08-14 (this file alone, via `apply-migrations.mjs --apply --file`, because `db:migrate` would have applied seven other agents' pending migrations with it). The header comment still reads "Draft, NOT applied" and must stay that way: an applied migration is an immutable record and editing its bytes trips the drift guard | The number the roadmap gates Phase 1 on, measured instead of asserted. The realism bench scores whether a generation looks real and never asks whose face it is; the reconstruction worker's ISE eval scores face *shape* offline against a synthetic set and stores nothing. This closes the gap: it renders a finished reconstruction head-framed at three yaws (head-on 0°, three-quarter 35°, profile 65°) with the platform's own `headshot` preset, embeds every render and every input capture with OSS face recognition (YuNet detection, MIT + SFace 128-d identity, Apache-2.0, both hash-pinned from OpenCV Zoo and run on `onnxruntime-web`'s WASM backend so there is no native install step), and files a 1-5 score against the generation record in `forge_creations`. The 1-5 mapping is anchored on SFace's own published decision boundary (cosine 0.363 = 3.0, so the roadmap's 4/5 gate is cosine 0.68, roughly twice the same-identity threshold) rather than on taste. **Refuses rather than fabricates:** `captures_unusable`, `render_unusable` and a genuinely low score are three separate statuses, and a budget-truncated sweep is withheld from the distribution. Reports `turn_falloff` (identity lost between head-on and the worst view), which is the only place a frontally-flattering texture transfer is visible. **Stores no biometrics:** no capture URLs, no crops, no embeddings, only the measurement. Docs: [docs/likeness-eval.md](docs/likeness-eval.md). Tests: [tests/likeness-score.test.js](tests/likeness-score.test.js) || Payment-outcome board (x402 failure visibility) | Endpoint [api/ops/payment-outcomes.js](api/ops/payment-outcomes.js), page [pages/payment-outcomes.html](pages/payment-outcomes.html) `-> /payment-outcomes` (admin session or `x-ops-secret`, `noindex`, not in `data/pages.json`), sensors [api/_lib/ops/x402-settle-health.js](api/_lib/ops/x402-settle-health.js) + [api/_lib/x402/wallet-balance-monitor.js](api/_lib/x402/wallet-balance-monitor.js) + [api/_lib/x402/sponsor-runway.js](api/_lib/x402/sponsor-runway.js) + [api/_lib/custodial-key-health.js](api/_lib/custodial-key-health.js) | Live | Every way an x402 payment can fail, in one read, before it halts the economy. The 2026-07-11 audit found the griefing classes (verify-reject floods, settle failures, sponsor-fee starvation) were only visible after the economy stopped: `recordPaymentMetric` was already emitting the events and nothing surfaced them. Four panels: inbound rates over 1h/3h/24h from the durable `x402_audit_log` (settle success, verify reject, replay reject with its own `inbound_attempts` denominator, top failure reasons by stage, replay stage split), the outbound ring settle sensor with its triage hint, every configured ring wallet against **its own** floor plus the measured sponsor runway, and stranded custody. The wallet panel is per-wallet on purpose: settle-floor starvation and dry wallets look identical from outside and have opposite fixes, and a board showing only the sponsor renders a starved payer as healthy. Panels are read independently and a failed one names itself in `degraded` (207 Multi-Status) rather than blanking the board; on the page a rate with no attempts renders `n/a` and an unmeasured custody total renders `not measured`, because a green zero on a reading that never happened is worse than no board. Docs: [docs/ops/payment-outcomes.md](docs/ops/payment-outcomes.md). |diff --git a/docs/materialize.md b/docs/materialize.mdindex 151ea1427..2d5dbbcbf 100644--- a/docs/materialize.md+++ b/docs/materialize.md@@ -109,6 +109,73 @@ timeline you can read at `GET /api/print/orders/:id`, and the page at---+## Using the page++Everything above is one screen at [/materialize](https://three.ws/materialize).+There is no wizard and no step counter: the model, the material, the size and+the price are all on screen at once, and changing any of them re-prices the+others in front of you.++**Getting a model onto it**, in the order most people arrive:++| Where you start | What to click |+|---|---|+| A model page, `/m/:id` | **Materialize**, next to Download GLB |+| A finished generation on [/forge](https://three.ws/forge) | **Materialize** in the result bar |+| A card in [/creations](https://three.ws/creations) | **Materialize** on the card |+| Nothing in particular | Open `/materialize` and pick from the rail, paste a `.glb` URL, or drop a file |++A deep link works too: `/materialize?creation=<id>` for a forge creation and+`/materialize?glb=<url>` for anything else. Both preselect the model, so a link+you send someone opens on the thing you meant.++**What the page does with it.** The mesh is measured on the server the moment it+is selected, and the printability card shows the result as facts a buyer can act+on: whether it is a closed solid, how many separate pieces it is, the thinnest+wall **at the size currently selected**, and whether it carries colour. Anything+the analyzer deducted points for is listed underneath, and the ones a repair pass+can actually fix are marked. **Repair** runs `POST /api/print/prepare`, swaps the+viewer to the rebuilt solid, and lists exactly what changed: holes closed,+vertices merged, slivers dropped, faces re-wound, and the score before and after.++**Material cards are measured against your model, not just listed.** A material+that cannot take this mesh at any printable height says why on its own face and+cannot be selected, so a full-colour card on an untextured model reads+"this model has no texture" rather than failing after you click it.++**The size slider ends where reality does.** Its bounds come from+`fitHeightRange()` on the server: the low end is the height at which the mesh's+thinnest wall reaches the material's minimum, the high end is where its widest+axis fills the print bed. Both ends are labelled with the constraint that set+them. Beside the model, a silhouette of an everyday object (a coin, a mug, a+hand, a person) is drawn at true proportion against the print, so "140 mm" is+also "about one and a half times a coffee mug". Height is what you choose, but+the footprint is shown beside it: a model whose long axis is not vertical is much+wider than it is tall, and the doorstep is the wrong place to discover that.++### True-scale AR++The **See it at true size** button places the object on your actual floor at the+exact height you are ordering. It is not an approximation: the viewer is given+`ar-scale="fixed"` and a `scale` factor taken from the same number the price was+computed from, so the thing on your desk is the thing in the cart.++Desktop browsers cannot place objects in a room, so on a desktop the same button+hands over a QR code to this page instead of disappearing. Scan it and the phone+opens with the same model, material and size.++### Checkout++Signed out, the order button opens a sign-in step that carries your quote back+with it, so nothing is lost. Signed in, it asks for the minimum a courier needs+(name, street, city, postal code, country, and optionally a second line, a region+and a phone) and nothing else. Changing the country re-prices shipping before+anything is charged, because shipping is zone-based. The payment step shows the+Solana Pay link and a QR for a phone wallet, and watches the chain for the+payment itself; you can close it and follow the order from its own page instead.++---+## Materials`GET /api/print/catalog` is the live source of truth. As of catalog version 1:@@ -228,6 +295,71 @@ company, or any block explorer staying online.A certificate whose signature is still in flight is a real certificate whoseproof has not landed yet, and the page says exactly that rather than pretending.+The reconciliation sweep (`/api/cron/print-orders-sync`) retries the send and+backfills the QR, so a bad RPC minute at shipping time costs nothing.++### Verifying one yourself++Nothing here needs an account, and none of it trusts us:++```bash+# 1. Read the certificate. It is public: the QR on the box resolves to it.+curl -s https://three.ws/api/print/certs/<certId> | jq '.certificate | {glb_sha256, memo, solana_signature, network}'++# 2. Download the model it names and hash the bytes.+curl -sL "<creation.glb_url from the response>" | shasum -a 256++# 3. The two hashes match, or this is not the model that was printed.+```++The `memo` field is the exact string that was signed on-chain, rendered on the+certificate page too, so the last step is reading the transaction's memo+instruction and confirming it is character-for-character the same. `/cert` with+no id is the lookup page: type the number printed on the card.++### Editions++`edition_of` is the creator's, not ours. On any model you forged, `/m/<id>` shows+a **Physical editions** panel where you set one number: how many physical copies+of that model may ever exist. Leave it empty and it is an open edition, which is+every model's default.++```bash+# Read the scarcity of a model (public).+curl -s "https://three.ws/api/print/editions?creation_id=<uuid>"+# → { "edition": { "limit": 25, "issued": 3, "remaining": 22, "soldOut": false } }++# Cap it (the creator's session only).+curl -s -X POST https://three.ws/api/print/editions \+ -H 'content-type: application/json' --cookie "$SESSION" \+ -d '{"creation_id":"<uuid>","edition_of":25}'+```++Three rules make the number mean something:++- **It is enforced where the price is set.** A sold-out model is refused by+ `/api/print/quote` and by both checkout lanes with a message naming how many+ are left, so nobody pays for a copy that cannot exist.+- **It counts shipped certificates, not open orders**, so an abandoned checkout+ never strands the last copy of an edition.+- **It cannot shrink below its own history.** Capping a series at 5 after 7 have+ shipped is refused, because a certificate reading "edition 7 of 5" would be a+ lie that is already in someone's hands.++A print of a model that was uploaded rather than forged still gets an edition+number: those series are keyed by the content hash, so identical bytes belong to+one series instead of each upload minting its own "edition 1 of 1".++### The cluster, and the mainnet gate++Certificates attest on **devnet** unless `PRINT_CERT_CLUSTER=mainnet` says+otherwise, and anything unrecognised in that variable stays devnet rather than+guessing its way onto real money. Mainnet needs a second key,+`PRINT_CERT_MAINNET_APPROVAL`, carrying the owner's recorded approval: an+irreversible on-chain send is an owner decision, not a deploy-time default.+Without it a mainnet certificate is issued, hashed, and left unattested with the+reason recorded, rather than quietly downgraded to a devnet signature that would+misrepresent what the certificate says it is.---diff --git a/pages/materialize.html b/pages/materialize.htmlindex 6b56fc481..b86379d69 100644--- a/pages/materialize.html+++ b/pages/materialize.html@@ -453,7 +453,10 @@<div class="mz-panel" id="mz-size-panel"><div class="mz-size-row"><h2 class="mz-h2">Size</h2>- <span class="mz-size-value" id="mz-size-value">-</span>+ <div style="text-align: right;">+ <span class="mz-size-value" id="mz-size-value">-</span>+ <span class="mz-meta" id="mz-size-foot" hidden style="display: block;"></span>+ </div></div><input type="range" class="mz-slider" id="mz-size" min="10" max="200" step="1" value="100" aria-label="Printed height in millimetres" /><div class="mz-track-ends">diff --git a/src/materialize-lib.js b/src/materialize-lib.jsindex fa455476e..ec9efbe07 100644--- a/src/materialize-lib.js+++ b/src/materialize-lib.js@@ -159,10 +159,15 @@ const SCORE_BANDS = [* The printability card's whole content: the band, the headline facts a buyer* actually asks about, and the deductions as fixable line items.*/-export function printabilityView(report) {+export function printabilityView(report, { targetHeightMm } = {}) {if (!report) return null;const score = Math.max(0, Math.min(100, Math.round(Number(report.score) || 0)));const band = SCORE_BANDS.find((b) => score >= b.min) || SCORE_BANDS[SCORE_BANDS.length - 1];+ const nativeHeight = report.bbox_mm?.y;+ const wallAtSize =+ report.min_wall_mm > 0 && nativeHeight > 0+ ? report.min_wall_mm * ((targetHeightMm || nativeHeight) / nativeHeight)+ : null;const facts = [{id: 'solid',@@ -178,9 +183,12 @@ export function printabilityView(report) {},{id: 'wall',+ // A wall thickness only means something at a size. The analyzer measures+ // the mesh at whatever scale the generator emitted, so the number shown+ // is that measurement carried to the height actually being ordered.label: 'Thinnest wall',- value: report.min_wall_mm ? `${(report.min_wall_mm / (report.bbox_mm?.y || 1) * 100).toFixed(2)} percent of height` : 'Not measured',- ok: Boolean(report.min_wall_mm),+ value: wallAtSize === null ? 'Not measured' : `${formatMm(wallAtSize)}${targetHeightMm ? ` at ${formatMm(targetHeightMm)} tall` : ''}`,+ ok: wallAtSize === null ? false : wallAtSize >= 0.6,},{id: 'colour',@@ -189,30 +197,38 @@ export function printabilityView(report) {ok: true,},];- const issues = (report.deductions || []).map((d) => ({- id: d.id,- label: d.label || d.id,- detail: d.detail || d.message || '',- points: d.points,- // Repair closes shells, drops slivers and re-winds faces. It cannot invent- // colour data or decide a mesh is one object, so those are stated as facts- // rather than offered as a button that would do nothing.- repairable: REPAIRABLE.has(d.id),- }));+ const issues = (report.deductions || []).map((d) => {+ const known = DEDUCTIONS[d.id];+ return {+ id: d.id,+ label: d.label || known?.label || 'Flagged by the analyzer',+ detail: d.detail || d.message || '',+ points: d.points,+ // Repair closes holes, drops slivers and re-winds faces. It cannot decide+ // that four separate bodies are one object, so that is stated as a fact+ // rather than offered as a button that would do nothing.+ repairable: Boolean(known?.repairable),+ };+ });return { score, tone: band.tone, label: band.label, facts, issues, repairableCount: issues.filter((i) => i.repairable).length };}-const REPAIRABLE = new Set([- 'not_manifold',- 'open_edges',- 'open_shell',- 'non_manifold_edges',- 'self_intersections',- 'degenerate_triangles',- 'inconsistent_winding',- 'triangle_budget',- 'thin_walls',-]);+// Every deduction api/_lib/print/analyze.js can emit, in the buyer's words, and+// whether the repair pass can actually resolve it. The analyzer names issues by+// id and explains them in `detail`; the id itself is not a sentence, and showing+// it raw ("multiple_shells") is how a measured report starts reading like a+// stack trace. `repairable` gates the Repair button: offering it for something a+// repair cannot change is worse than not offering it at all.+const DEDUCTIONS = {+ non_manifold: { label: 'Not a solid yet', repairable: true },+ open_edges: { label: 'Holes in the surface', repairable: true },+ non_manifold_edges: { label: 'Edges shared by too many faces', repairable: true },+ self_intersections: { label: 'The surface crosses itself', repairable: true },+ degenerate_triangles: { label: 'Sliver triangles', repairable: true },+ thin_walls: { label: 'Thin walls', repairable: true },+ triangle_budget: { label: 'Heavier than any printer needs', repairable: true },+ multiple_shells: { label: 'Separate pieces', repairable: false },+};/*** The `scale` attribute that makes model-viewer place the object at its real@@ -250,6 +266,25 @@ export function rejectionView(rejection) {};}+/**+ * The scarcity line under the total. Silent for the common case, an open+ * edition nobody has printed: a "0 of unlimited" row would be noise on every+ * quote. It speaks the moment the number means something.+ *+ * @param {{ limit: number|null, issued: number, remaining: number|null }|null|undefined} edition+ * @returns {string}+ */+export function editionNote(edition) {+ if (!edition) return '';+ if (edition.limit === null) {+ return edition.issued+ ? `Open edition · ${edition.issued} printed so far, each with its own numbered certificate`+ : '';+ }+ if (edition.remaining === 0) return `Limited edition of ${edition.limit} · sold out`;+ return `Limited edition of ${edition.limit} · you would be number ${edition.issued + 1}, ${edition.remaining} left`;+}+/** Order timeline steps, in the order they happen, with the ones that branch. */export const ORDER_STEPS = Object.freeze([{ id: 'quoted', label: 'Quoted', blurb: 'Price locked from your model.' },diff --git a/src/materialize-order.js b/src/materialize-order.jsindex 1391347ef..b8f0d91ef 100644--- a/src/materialize-order.js+++ b/src/materialize-order.js@@ -35,6 +35,20 @@ const WAITING_COPY = {let timer = null;+// Material id to display name, filled from the public catalog on first load.+const catalogNames = new Map();++async function loadCatalogNames() {+ try {+ const res = await fetch('/api/print/catalog');+ if (!res.ok) return;+ const body = await res.json();+ for (const m of body.materials || []) catalogNames.set(m.id, m.name);+ } catch {+ // The order still reads correctly with the raw id; this is only polish.+ }+}+function orderIdFromPath() {const match = location.pathname.match(/\/materialize\/orders\/([0-9a-f-]{36})/i);return match ? match[1] : null;@@ -106,12 +120,18 @@ function render(order, events) {$('mo-main').hidden = false;const quote = order.quote || {};- const materialName = quote.material?.name || order.material_id;+ // The frozen quote names the material; a very early order may only carry the+ // id, and the catalog turns that into the name the buyer chose. "pla-draft"+ // is a database key, not something anyone ordered.+ const materialName = quote.material?.name || catalogNames.get(order.material_id) || order.material_id;+ // lead_time_days is only stamped on the row when the job is submitted, so+ // until then the number the buyer agreed to is the one in their own quote.+ const leadDays = order.lead_time_days ?? quote.leadTimeDays ?? null;document.title = `${materialName} print · ${order.status} · three.ws`;$('mo-eyebrow').textContent = `Materialize order ${order.id.slice(0, 8)}`;$('mo-title').textContent = statusHeadline(order);- $('mo-sub').textContent = subtitleFor(order);+ $('mo-sub').textContent = subtitleFor(order, leadDays);$('mo-specs').innerHTML = [['Material', materialName],@@ -149,10 +169,12 @@ function statusHeadline(order) {return map[order.status] || 'Your print';}-function subtitleFor(order) {+function subtitleFor(order, leadDays) {if (order.status === 'delivered') return 'Printed from your model and delivered. The certificate below links the object back to the exact file it was made from.';if (TERMINAL.has(order.status)) return 'Nothing further will happen on this order. Any refund is recorded on the timeline below.';- return `${formatLeadTime(order.lead_time_days)} from the day it was paid. Every step below carries the moment it actually happened.`;+ return leadDays+ ? `${formatLeadTime(leadDays)} from the day it is paid. Every step below carries the moment it actually happened.`+ : 'Every step below carries the moment it actually happened.';}function renderModel(order) {@@ -272,6 +294,6 @@ document.addEventListener('visibilitychange', () => {else load();});-load();+loadCatalogNames().finally(load);export { ORDER_STEPS };diff --git a/src/materialize.js b/src/materialize.jsindex 999dfb76c..4bee3f0ca 100644--- a/src/materialize.js+++ b/src/materialize.js@@ -24,6 +24,7 @@ import {arScaleAttribute,clampHeight,defaultHeight,+ editionNote,formatLeadTime,formatMm,formatUsdc,@@ -180,6 +181,7 @@ function wireStatic() {$('mz-size')?.addEventListener('input', () => {state.heightMm = Number($('mz-size').value);renderSizeReadout();+ renderPrintability();scheduleQuote();});$('mz-qty')?.addEventListener('change', () => {@@ -207,7 +209,7 @@ function wireStatic() {scheduleQuote();});$('mz-repair')?.addEventListener('click', runRepair);- $('mz-ar-btn')?.addEventListener('click', () => $('mz-viewer')?.activateAR?.());+ $('mz-ar-btn')?.addEventListener('click', openAr);$('mz-sheet-close')?.addEventListener('click', closeSheet);$('mz-sheet')?.addEventListener('click', (e) => {@@ -235,7 +237,10 @@ function fillCountries() {async function whoAmI() {try {const body = await api('/api/auth/me');- state.user = body?.user || body || null;+ // It answers 200 with { user: null } when nobody is signed in, so the+ // envelope is never the fallback: reading it as the user made an+ // anonymous visitor look authenticated and skipped the sign-in gate.+ state.user = body?.user ?? null;} catch {state.user = null;}@@ -244,37 +249,83 @@ async function whoAmI() {// ── the creations rail ──────────────────────────────────────────────────────+/**+ * The rail of things you can print right now, in the order a person would want+ * them: this browser's own forged models first, then the account's, then the+ * public feed.+ *+ * Three sources rather than one because "your creations" has three different+ * meanings here. The forge persists anonymously against a browser handle, so a+ * signed-out visitor still has creations; a signed-in account with a claimed+ * username has a profile feed; and someone arriving with neither should still+ * be one click from printing something, which is what the community feed is+ * for. A picker that can only ever say "nothing here" is a dead end, and this+ * page is too expensive to arrive at and bounce off.+ */async function loadRail() {const rail = $('mz-rail');if (!rail) return;- const username = state.user?.username;- if (!username) {- rail.innerHTML = `<p class="mz-rail-empty">Sign in and your own creations appear here, ready to print. Or <a href="/create" style="color:inherit">generate one now</a>, or drop a file on the left.</p>`;- return;++ const sources = [+ {+ label: 'Your creations',+ load: async () => {+ const body = await api('/api/forge-gallery', { headers: { 'x-forge-client': forgeClientKey() } });+ return body?.creations || [];+ },+ },+ ];+ if (state.user?.username) {+ sources.push({+ label: 'Your creations',+ load: async () => {+ const body = await api(`/api/users/${encodeURIComponent(state.user.username)}/creations?type=model`);+ return body?.creations || body?.items || [];+ },+ });}- try {- const body = await api(`/api/users/${encodeURIComponent(username)}/creations?type=model`);- const items = (body?.creations || body?.items || []).filter((c) => c.glb_url || c.model_url);- if (!items.length) {- rail.innerHTML = `<p class="mz-rail-empty">Nothing forged yet. <a href="/create" style="color:inherit">Make your first model</a> and it will show up here.</p>`;- return;- }- rail.innerHTML = items- .slice(0, 12)- .map((c) => {- const poster = c.preview_image_url || c.thumbnail_url || '';- const label = esc((c.prompt || c.title || 'Untitled').slice(0, 70));- return `<button type="button" class="mz-rail-card" data-creation="${esc(c.id)}" title="${label}">- ${poster ? `<img src="${esc(poster)}" alt="" loading="lazy" />` : ''}- <figcaption>${label}</figcaption>- </button>`;- })- .join('');- for (const card of rail.querySelectorAll('[data-creation]')) {- card.addEventListener('click', () => selectSource({ creationId: card.dataset.creation, label: 'your creation' }));+ sources.push({+ label: 'Fresh from the forge',+ load: async () => {+ const body = await api('/api/forge-gallery?scope=community&limit=12');+ return body?.creations || [];+ },+ });++ let reachedAny = false;+ for (const source of sources) {+ let items = [];+ try {+ items = (await source.load()).filter((c) => c.id && (c.glb_url || c.model_url || c.glbUrl));+ reachedAny = true;+ } catch {+ continue;}- } catch {- rail.innerHTML = `<p class="mz-rail-empty">Your creations could not be loaded just now. Paste a model URL or drop a file on the left, and try this panel again shortly.</p>`;+ if (!items.length) continue;+ $('mz-rail-title').textContent = source.label;+ renderRail(rail, items);+ return;+ }++ rail.innerHTML = reachedAny+ ? `<p class="mz-rail-empty">Nothing forged yet. <a href="/create" style="color:inherit">Generate a model</a> and it appears here, or drop a .glb on the left.</p>`+ : `<p class="mz-rail-empty">The gallery could not be reached just now. Paste a model URL or drop a file on the left, and this panel will fill in on the next visit.</p>`;+}++function renderRail(rail, items) {+ rail.innerHTML = items+ .slice(0, 12)+ .map((c) => {+ const poster = c.preview_image_url || c.thumbnail_url || c.previewImageUrl || '';+ const label = esc((c.prompt || c.title || 'Untitled').slice(0, 70));+ return `<button type="button" class="mz-rail-card" data-creation="${esc(c.id)}" title="${label}">+ ${poster ? `<img src="${esc(poster)}" alt="" loading="lazy" />` : ''}+ <figcaption>${label}</figcaption>+ </button>`;+ })+ .join('');+ for (const card of rail.querySelectorAll('[data-creation]')) {+ card.addEventListener('click', () => selectSource({ creationId: card.dataset.creation, label: 'your creation' }));}}@@ -332,9 +383,11 @@ async function selectSource(source) {state.fits = body.fits || [];state.source = { ...source, url: body.sourceUrl, creation: body.creation || null };showModel(body.sourceUrl);- renderPrintability();renderMaterials();+ // pickInitialMaterial settles the size, and the printability card reads+ // the thinnest wall AT that size, so the card is rendered after it.pickInitialMaterial();+ renderPrintability();setStageBusy(null);} catch (err) {setStageBusy(null);@@ -408,7 +461,7 @@ function showModel(url) {// ── printability ────────────────────────────────────────────────────────────function renderPrintability() {- const view = printabilityView(state.report);+ const view = printabilityView(state.report, { targetHeightMm: state.heightMm });if (!view) return;const CIRCUMFERENCE = 2 * Math.PI * 19;@@ -622,16 +675,19 @@ function applySliderBounds() {$('mz-size-min').textContent = `${formatMm(bounds.min)} · ${bounds.minNote}`;$('mz-size-max').textContent = `${bounds.maxNote} · ${formatMm(bounds.max)}`;- $('mz-presets').innerHTML = (state.catalog.sizePresets || [])- .map((p) => {- const inRange = p.heightMm >= bounds.min && p.heightMm <= bounds.max;- return `<button type="button" class="mz-chip" data-preset="${p.heightMm}" ${inRange ? '' : 'disabled'}- aria-pressed="${state.heightMm === p.heightMm}"- title="${esc(inRange ? p.blurb : `${p.name} is outside what this material can print for this model`)}">- ${esc(p.name)} · ${formatMm(p.heightMm)}- </button>`;- })- .join('');+ const presets = (state.catalog.sizePresets || []).filter((p) => p.heightMm >= bounds.min && p.heightMm <= bounds.max);+ $('mz-presets').innerHTML = presets.length+ ? presets+ .map(+ (p) => `<button type="button" class="mz-chip" data-preset="${p.heightMm}"+ aria-pressed="${state.heightMm === p.heightMm}" title="${esc(p.blurb)}">+ ${esc(p.name)} · ${formatMm(p.heightMm)}+ </button>`,+ )+ .join('')+ // A row of presets nobody can click is noise. When this model in this+ // material only prints across a narrow band, say what the band is.+ : `<p class="mz-meta" style="margin:0;">This model prints between ${formatMm(bounds.min)} and ${formatMm(bounds.max)} in ${esc(materialById(state.materialId)?.name || 'this material')}, so none of the standard sizes apply.</p>`;for (const chip of $('mz-presets').querySelectorAll('[data-preset]')) {chip.addEventListener('click', () => {state.heightMm = clampHeight(Number(chip.dataset.preset), bounds);@@ -641,10 +697,24 @@ function applySliderBounds() {});}renderSizeReadout();+ if (state.report) renderPrintability();}function renderSizeReadout() {$('mz-size-value').textContent = formatMm(state.heightMm);+ // Height is what a buyer chooses, but it is not what arrives: a model whose+ // long axis is not vertical is far wider than it is tall, and finding that+ // out at the doorstep is the wrong time. The footprint comes from the report,+ // so it is right even before the first quote lands.+ const bbox = state.report?.bbox_mm;+ const note = $('mz-size-foot');+ if (note && bbox?.y > 0 && state.heightMm) {+ const scale = state.heightMm / bbox.y;+ note.textContent = `${formatMm(bbox.x * scale, { unit: false })} x ${formatMm(bbox.z * scale)} footprint`;+ note.hidden = false;+ } else if (note) {+ note.hidden = true;+ }for (const chip of $('mz-presets').querySelectorAll('[data-preset]')) {chip.setAttribute('aria-pressed', String(Number(chip.dataset.preset) === state.heightMm));}@@ -747,8 +817,15 @@ function applyArScale() {}viewer.setAttribute('scale', attr);viewer.setAttribute('ar-scale', 'fixed');- button.hidden = !(viewer.canActivateAR ?? true);- button.title = `Places it on your floor at ${formatMm(state.heightMm)} tall, the exact size you are ordering.`;+ // The button is always offered. A desktop browser cannot place anything, but+ // hiding it there would mean the single best reason to open this page on a+ // phone is invisible on the machine most people arrive with, so the desktop+ // path hands over a QR instead of disappearing.+ button.hidden = false;+ state.canPlaceAr = Boolean(viewer.canActivateAR);+ button.title = state.canPlaceAr+ ? `Places it on your floor at ${formatMm(state.heightMm)} tall, the exact size you are ordering.`+ : 'Open this page on a phone to place it on your desk at true size.';}function renderQuoteBody(html) {@@ -779,6 +856,7 @@ function renderQuote(body) {if (!quote) return;const rows = quoteRows(quote);const holderLine = rows.find((r) => r.id === 'holder_discount');+ const edition = editionNote(body.edition);renderQuoteBody(`<ul class="mz-quote-lines">@@ -797,6 +875,7 @@ function renderQuote(body) {<span class="mz-total-amount">${esc(formatUsdc(quote.total))} <span style="font-size:13px;font-weight:600;">${esc(quote.currency)}</span></span></div><p class="mz-total-note">${esc(formatLeadTime(quote.leadTimeDays))} · ${esc(formatMm(quote.geometry.boxMm.x, { unit: false }))} x ${esc(formatMm(quote.geometry.boxMm.y, { unit: false }))} x ${esc(formatMm(quote.geometry.boxMm.z))} boxed · ${esc(String(quote.geometry.massGramsEach))} g each</p>+ ${edition ? `<p class="mz-total-note">${esc(edition)}</p>` : ''}${quote.quoteOnRequest? `<div class="mz-notice mz-notice-info" style="margin-top:0.9rem;"><h3>This one is priced by hand</h3><p>Metal is quoted against the actual geometry by an engineer, not by the calculator. The number above is an estimate; ask for a firm quote and we will come back with it.</p></div>@@ -833,6 +912,33 @@ function closeSheet() {sheetReturnFocus?.focus?.();}+/**+ * Put it on the buyer's floor, or hand them the way to.+ *+ * On a phone this is one tap into WebXR, Scene Viewer or Quick Look at the exact+ * ordered size. On a desktop, where no browser can place anything, it becomes a+ * QR to this same page: the buyer keeps their material, size and quantity and+ * simply continues on the device that has a camera.+ */+async function openAr() {+ const viewer = $('mz-viewer');+ if (state.canPlaceAr && viewer?.activateAR) {+ viewer.activateAR();+ return;+ }+ openSheet(+ 'Open it on your phone',+ `It places at ${formatMm(state.heightMm)} tall, the exact size you are ordering.`,+ `<p style="font-size:13.5px;line-height:1.6;color:var(--mz-ink-2);margin:0 0 0.5rem;">+ This browser cannot place objects in a room. Scan this with a phone and the page opens+ with the same model, material and size, ready to put on your desk.+ </p>+ <canvas class="mz-qr" id="mz-ar-qr" width="240" height="240" aria-label="QR code to open this page on a phone"></canvas>+ <p class="mz-mono" style="text-align:center;">${esc(location.href)}</p>`,+ );+ await drawQrInto('mz-ar-qr', location.href);+}+function openCheckout() {if (!state.token) return;if (!state.user) {@@ -934,10 +1040,15 @@ async function submitOrder(shipping) {});return;}+ const platformSide = err.code === 'checkout_unavailable';openSheet(- 'The order could not be opened',+ platformSide ? 'Checkout is offline right now' : 'The order could not be opened','Nothing was charged.',- `<div class="mz-notice mz-notice-error"><p>${esc(err.message)}</p></div>+ `<div class="mz-notice mz-notice-error"><p>${esc(+ platformSide+ ? 'This is on our side, not yours: the payment rail is not answering. Your quote stays valid for 24 hours, so this exact price and size will still be here shortly.'+ : err.message,+ )}</p></div><button type="button" class="mz-btn mz-btn-block" id="mz-order-back" style="margin-top:0.9rem;">Back to the address</button>`,);$('mz-order-back')?.addEventListener('click', () => renderShippingStep(shipping));@@ -970,8 +1081,12 @@ function renderPaymentStep(result) {pollPayment(order.id, result.track_url);}-async function drawQr(url) {- const canvas = $('mz-qr');+function drawQr(url) {+ return drawQrInto('mz-qr', url);+}++async function drawQrInto(id, url) {+ const canvas = $(id);if (!canvas) return;try {const mod = await import('qrcode');diff --git a/tests/materialize-lib.test.js b/tests/materialize-lib.test.jsindex adbea8c72..ae17b9e16 100644--- a/tests/materialize-lib.test.js+++ b/tests/materialize-lib.test.js@@ -20,6 +20,7 @@ import {sliderBounds,timelineView,validateShipping,+ editionNote,} from '../src/materialize-lib.js';const REFERENCES = [@@ -301,3 +302,27 @@ describe('validateShipping', () => {expect(SHIPPING_COUNTRIES.some((c) => c.code === 'US')).toBe(true);});});++describe('editionNote', () => {+ it('says nothing about an open edition nobody has printed', () => {+ expect(editionNote({ limit: null, issued: 0, remaining: null })).toBe('');+ expect(editionNote(null)).toBe('');+ expect(editionNote(undefined)).toBe('');+ });++ it('counts an open edition once copies exist', () => {+ expect(editionNote({ limit: null, issued: 4, remaining: null })).toBe(+ 'Open edition · 4 printed so far, each with its own numbered certificate',+ );+ });++ it('tells a buyer which number they would be', () => {+ expect(editionNote({ limit: 25, issued: 2, remaining: 23 })).toBe(+ 'Limited edition of 25 · you would be number 3, 23 left',+ );+ });++ it('says sold out rather than offering a number that cannot exist', () => {+ expect(editionNote({ limit: 5, issued: 5, remaining: 0 })).toBe('Limited edition of 5 · sold out');+ });+});