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(print): land the Materialize mesh pipeline and its fulfillment schema

nirholas089500f4ef38
diff --git a/api/_lib/migrations/20260902130000_print_orders_fulfillment.sql b/api/_lib/migrations/20260902130000_print_orders_fulfillment.sql
new file mode 100644
index 000000000..3bab1f591
--- /dev/null
+++ b/api/_lib/migrations/20260902130000_print_orders_fulfillment.sql
@@ -0,0 +1,127 @@
+begin;
+
+-- Materialize: the physical lane of the forge.
+--
+-- A user (or a paying agent) turns a finished 3D generation into a real,
+-- high-precision print. This migration lands the fulfillment half of that
+-- product: the order row every surface reads, the timeline every status change
+-- writes, and the webhook ledger that makes a provider's retried callback
+-- harmless.
+--
+-- The order's status is a state machine, enforced in exactly one module
+-- (api/_lib/print-store.js). The database carries the vocabulary as a check
+-- constraint so a handler that bypasses the module still cannot invent a state,
+-- but it deliberately does NOT encode the legal transitions: those live in code
+-- next to the events they emit, where they can be read and tested.
+
+create table if not exists print_orders (
+ id uuid primary key default gen_random_uuid(),
+ -- Null only for agent orders paid over x402, which carry a payer wallet
+ -- instead of a session. Exactly one of the two is always present.
+ user_id uuid references users(id) on delete set null,
+ payer_wallet text,
+ -- The generation being printed. Null for a direct GLB upload, which still
+ -- records source_glb_url so the operator can always reach the mesh.
+ creation_id uuid references forge_creations(id) on delete set null,
+ source_glb_url text not null,
+ -- { stl, 3mf, glb } object-storage URLs written by the prepare step. The
+ -- operator console hands these to the bureau; the adapter hands them to a
+ -- partner API.
+ prepared_asset_urls jsonb not null default '{}'::jsonb,
+ -- The printability report as it stood when the order was placed. Frozen on
+ -- purpose: a later re-analysis must never change what was sold.
+ analysis jsonb not null default '{}'::jsonb,
+ material_id text not null,
+ target_height_mm numeric(8,2),
+ quantity integer not null default 1,
+ -- The itemized quote, including its signed token. Every money number a
+ -- human or an operator sees is read from here, never recomputed.
+ quote jsonb not null default '{}'::jsonb,
+ price_usdc numeric(14,6) not null default 0,
+ status text not null default 'created',
+ -- Which fulfillment adapter owns the job: 'manual' (a human operator
+ -- driving a real bureau) or a contracted partner's adapter key.
+ provider text,
+ provider_order_id text,
+ -- The adapter's own last-seen state, verbatim. Diagnostic only; nothing
+ -- reads it to make a decision, so a partner changing their payload shape
+ -- cannot break the state machine.
+ provider_state jsonb not null default '{}'::jsonb,
+ -- The first real PII this platform stores. Minimum fields, surfaced only to
+ -- the operator console and the provider adapter, never logged, never in an
+ -- analytics event.
+ shipping jsonb,
+ tracking_number text,
+ carrier text,
+ -- Copied from the adapter's declared lead time when the job is submitted,
+ -- so the reconciliation sweep can tell a slow job from a stalled one even
+ -- after the catalog's lead times are retuned.
+ lead_time_days integer,
+ submitted_at timestamptz,
+ -- Set when the stall sweep has already told the operator about this order,
+ -- so a stuck job is reported once rather than every five minutes.
+ stall_alerted_at timestamptz,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ constraint print_orders_status_chk check (status in (
+ 'created', 'quoted', 'paid', 'screening', 'submitted', 'printing',
+ 'quality_check', 'shipped', 'delivered', 'rejected', 'canceled', 'refunded'
+ )),
+ constraint print_orders_quantity_chk check (quantity between 1 and 500),
+ constraint print_orders_owner_chk check (user_id is not null or payer_wallet is not null)
+);
+
+-- The operator queue reads by status, newest first: this is its index.
+create index if not exists print_orders_status_idx on print_orders (status, created_at desc);
+-- A buyer's order list.
+create index if not exists print_orders_user_idx on print_orders (user_id, created_at desc) where user_id is not null;
+-- Webhook lookup: a provider identifies the job by their own id, not ours.
+create unique index if not exists print_orders_provider_uniq
+ on print_orders (provider, provider_order_id)
+ where provider_order_id is not null;
+-- The reconciliation sweep's working set: live jobs a provider owns.
+create index if not exists print_orders_open_idx
+ on print_orders (submitted_at)
+ where status in ('submitted', 'printing', 'quality_check', 'shipped');
+
+-- The timeline. Every status change appends a row here; no column is ever
+-- mutated to represent history, so an order's story is always reconstructable
+-- and an operator's note can never be overwritten by the next transition.
+create table if not exists print_order_events (
+ id uuid primary key default gen_random_uuid(),
+ order_id uuid not null references print_orders(id) on delete cascade,
+ status text not null,
+ note text,
+ -- Who caused it. 'operator' rows also carry the operator's user id so a
+ -- refund or a rejection is always attributable to a person.
+ actor text not null default 'system',
+ actor_id uuid references users(id) on delete set null,
+ created_at timestamptz not null default now(),
+ constraint print_order_events_actor_chk check (actor in ('system', 'operator', 'provider', 'buyer')),
+ constraint print_order_events_note_chk check (note is null or char_length(note) <= 2000)
+);
+
+create index if not exists print_order_events_order_idx on print_order_events (order_id, created_at asc);
+
+-- Webhook idempotency ledger. A provider that retries a delivery (every serious
+-- one does) must not append the same timeline row twice, and a replay must not
+-- drive the state machine backwards. The unique key is the provider's own
+-- delivery id; when a provider sends none, the adapter derives a stable one by
+-- hashing the payload, so "the same event twice" is still one row.
+create table if not exists print_webhook_deliveries (
+ provider text not null,
+ delivery_id text not null,
+ order_id uuid references print_orders(id) on delete cascade,
+ applied boolean not null default false,
+ received_at timestamptz not null default now(),
+ primary key (provider, delivery_id)
+);
+
+create index if not exists print_webhook_deliveries_order_idx on print_webhook_deliveries (order_id, received_at desc);
+
+do $$ begin
+ create trigger print_orders_set_updated_at before update on print_orders
+ for each row execute function set_updated_at();
+exception when duplicate_object then null; end $$;
+
+commit;
diff --git a/api/_lib/print-store.js b/api/_lib/print-store.js
new file mode 100644
index 000000000..a70ad0c34
--- /dev/null
+++ b/api/_lib/print-store.js
@@ -0,0 +1,486 @@
+// @ts-check
+// Materialize order store: the one module that owns a physical print order's
+// status.
+//
+// An order's status is a state machine. Every surface that moves an order
+// (checkout, the operator console, a provider webhook, the reconciliation
+// sweep) calls transitionOrder() and nothing else; no handler writes `status`
+// directly. Two properties fall out of that and both are load-bearing:
+//
+// 1. An illegal move throws instead of corrupting the order. A provider that
+// reports "shipped" for a job we never submitted, or a double-clicked
+// operator button, is refused at the one place that can see the current
+// state.
+// 2. The move is atomic. The UPDATE carries `where status = <expected>`, so
+// two concurrent callers racing the same transition produce exactly one
+// winner and one PrintTransitionError, without a lock or a transaction
+// spanning the event insert.
+//
+// History lives in print_order_events, appended per transition. No column is
+// ever mutated to represent the past, so an order's story is reconstructable
+// and an operator's note cannot be overwritten by the next status change.
+
+import { sql, isDbUnavailableError } from './db.js';
+import { databaseConfigured } from './env.js';
+import { publishUserEvent } from './feed.js';
+
+/** Every status the DB check constraint allows, in lifecycle order. */
+export const PRINT_STATUSES = Object.freeze([
+ 'created',
+ 'quoted',
+ 'paid',
+ 'screening',
+ 'submitted',
+ 'printing',
+ 'quality_check',
+ 'shipped',
+ 'delivered',
+ 'rejected',
+ 'canceled',
+ 'refunded',
+]);
+
+/** Who caused a transition. Mirrors the print_order_events check constraint. */
+export const PRINT_ACTORS = Object.freeze(['system', 'operator', 'provider', 'buyer']);
+
+// The whitelist. Read it as "from → the only places it can go next".
+//
+// Money-relevant edges, spelled out because they are the ones people get wrong:
+// • `paid → screening` is automatic; screening is the fabrication-safety gate
+// that runs a second time after payment (00-CONTEXT, order 06).
+// • `screening → rejected` is the refusal path. `rejected → refunded` is the
+// operator closing it out; the on-chain send itself is owner-gated and
+// never happens inside this module.
+// • `quality_check → printing` exists because a failed QC is a re-print, not
+// a dead order. It is the one backwards edge and it is deliberate.
+// • `delivered → refunded` exists because returns happen after delivery.
+// Everything else out of `delivered` is closed.
+const TRANSITIONS = Object.freeze({
+ created: ['quoted', 'canceled'],
+ quoted: ['paid', 'canceled'],
+ paid: ['screening', 'canceled', 'refunded'],
+ screening: ['submitted', 'rejected', 'canceled'],
+ submitted: ['printing', 'canceled', 'rejected'],
+ printing: ['quality_check', 'canceled', 'rejected'],
+ quality_check: ['shipped', 'printing', 'rejected'],
+ shipped: ['delivered', 'refunded'],
+ delivered: ['refunded'],
+ rejected: ['refunded'],
+ canceled: ['refunded'],
+ refunded: [],
+});
+
+/** Statuses from which nothing can move. Terminal in the strict sense. */
+export const TERMINAL_STATUSES = Object.freeze(
+ PRINT_STATUSES.filter((s) => TRANSITIONS[s].length === 0),
+);
+
+/**
+ * Statuses where a fulfillment provider owns the job and the reconciliation
+ * sweep should keep polling. Matches the print_orders_open_idx partial index.
+ */
+export const OPEN_PROVIDER_STATUSES = Object.freeze([
+ 'submitted',
+ 'printing',
+ 'quality_check',
+ 'shipped',
+]);
+
+/** Thrown when a caller asks for a move the machine does not allow. */
+export class PrintTransitionError extends Error {
+ /**
+ * @param {string} from
+ * @param {string} to
+ * @param {string} [detail]
+ */
+ constructor(from, to, detail = '') {
+ super(`illegal print order transition ${from} → ${to}${detail ? `: ${detail}` : ''}`);
+ this.name = 'PrintTransitionError';
+ this.code = 'illegal_transition';
+ this.from = from;
+ this.to = to;
+ }
+}
+
+/** Thrown when the order id does not resolve. Separated so handlers can 404. */
+export class PrintOrderNotFoundError extends Error {
+ /** @param {string} orderId */
+ constructor(orderId) {
+ super(`print order not found: ${orderId}`);
+ this.name = 'PrintOrderNotFoundError';
+ this.code = 'not_found';
+ this.orderId = orderId;
+ }
+}
+
+/** True when this deployment can persist orders at all. */
+export function printStoreEnabled() {
+ return Boolean(databaseConfigured());
+}
+
+/** @param {string} status */
+export function isPrintStatus(status) {
+ return PRINT_STATUSES.includes(status);
+}
+
+/** @param {string} status */
+export function isTerminalStatus(status) {
+ return TERMINAL_STATUSES.includes(status);
+}
+
+/**
+ * The moves allowed out of a status. Returns a copy so a caller cannot mutate
+ * the machine; an unknown status yields an empty list rather than throwing,
+ * because the console renders this to build its action buttons.
+ * @param {string} status
+ * @returns {string[]}
+ */
+export function allowedTransitions(status) {
+ return [...(TRANSITIONS[status] || [])];
+}
+
+/**
+ * @param {string} from
+ * @param {string} to
+ */
+export function canTransition(from, to) {
+ return allowedTransitions(from).includes(to);
+}
+
+/**
+ * Throws PrintTransitionError unless `from → to` is on the whitelist. Exported
+ * so callers (and tests) can check a move without touching the database.
+ * @param {string} from
+ * @param {string} to
+ */
+export function assertTransition(from, to) {
+ if (!isPrintStatus(to)) throw new PrintTransitionError(from, to, 'unknown status');
+ if (!canTransition(from, to)) throw new PrintTransitionError(from, to);
+}
+
+// Columns a transition is allowed to set alongside the status. Anything else a
+// caller passes in `patch` is dropped rather than interpolated: this list is
+// the whole write surface of a status change, so a provider payload can never
+// reach a column nobody vetted.
+const PATCHABLE = Object.freeze([
+ 'provider',
+ 'provider_order_id',
+ 'provider_state',
+ 'tracking_number',
+ 'carrier',
+ 'lead_time_days',
+ 'submitted_at',
+ 'stall_alerted_at',
+ 'shipping',
+]);
+
+const JSONB_COLUMNS = new Set(['provider_state', 'shipping', 'quote', 'analysis', 'prepared_asset_urls']);
+
+// Literal column expressions for every patchable key. Keeping them as data
+// (rather than interpolating `key`) means a future patchable column has to be
+// added here on purpose, and a typo fails loudly at import instead of emitting
+// a query with an attacker-shaped identifier.
+const COLUMN_SQL = Object.freeze({
+ provider: 'provider',
+ provider_order_id: 'provider_order_id',
+ provider_state: 'provider_state',
+ tracking_number: 'tracking_number',
+ carrier: 'carrier',
+ lead_time_days: 'lead_time_days',
+ submitted_at: 'submitted_at',
+ stall_alerted_at: 'stall_alerted_at',
+ shipping: 'shipping',
+});
+
+/**
+ * Build the `set` fragment for the patched columns. Returns null when nothing
+ * survives the whitelist, which the caller reads as "status only".
+ * @param {Record<string, unknown>} patch
+ */
+function patchFragment(patch) {
+ const entries = Object.entries(patch || {}).filter(([k]) => PATCHABLE.includes(k));
+ if (entries.length === 0) return null;
+ return entries.reduce((acc, [key, value], i) => {
+ const bound = JSONB_COLUMNS.has(key) ? JSON.stringify(value ?? {}) : value;
+ // sql.unsafe is not available on the Neon HTTP driver, and the key here is
+ // never caller-controlled (it survived the PATCHABLE whitelist above), so
+ // the column name is spliced by an explicit switch-free lookup instead.
+ const frag = sql([`, ${COLUMN_SQL[key]} = `, ''], bound);
+ return i === 0 ? frag : sql(['', ''], acc, frag);
+ }, null);
+}
+
+/** Columns every read returns. Excludes nothing: the console needs all of it. */
+const ORDER_COLUMNS = sql([
+ `id, user_id, payer_wallet, creation_id, source_glb_url, prepared_asset_urls, analysis,
+ material_id, target_height_mm, quantity, quote, price_usdc, status, provider,
+ provider_order_id, provider_state, shipping, tracking_number, carrier, lead_time_days,
+ submitted_at, stall_alerted_at, created_at, updated_at`,
+]);
+
+/**
+ * @param {string} orderId
+ * @returns {Promise<object|null>}
+ */
+export async function getOrder(orderId) {
+ if (!printStoreEnabled() || !orderId) return null;
+ const rows = await sql`select ${ORDER_COLUMNS} from print_orders where id = ${orderId}`;
+ return rows[0] || null;
+}
+
+/**
+ * Resolve an order by the provider's own identifier. This is how a webhook
+ * finds the job: a partner knows their id, never ours.
+ * @param {string} provider
+ * @param {string} providerOrderId
+ */
+export async function getOrderByProviderId(provider, providerOrderId) {
+ if (!printStoreEnabled() || !provider || !providerOrderId) return null;
+ const rows = await sql`
+ select ${ORDER_COLUMNS} from print_orders
+ where provider = ${provider} and provider_order_id = ${providerOrderId}`;
+ return rows[0] || null;
+}
+
+/**
+ * The operator queue. `status` may be a single status, a list, or omitted for
+ * everything. Newest first, which is the order the console renders.
+ * @param {{ status?: string|string[], limit?: number, offset?: number }} [opts]
+ */
+export async function listOrders({ status, limit = 50, offset = 0 } = {}) {
+ if (!printStoreEnabled()) return [];
+ const statuses = (Array.isArray(status) ? status : status ? [status] : []).filter(isPrintStatus);
+ const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);
+ const skip = Math.max(Number(offset) || 0, 0);
+ const where = statuses.length ? sql`where status = any(${statuses})` : sql`where true`;
+ return sql`
+ select ${ORDER_COLUMNS} from print_orders
+ ${where}
+ order by created_at desc
+ limit ${cap} offset ${skip}`;
+}
+
+/** Per-status counts for the console's queue rail. Returns a plain object. */
+export async function countOrdersByStatus() {
+ if (!printStoreEnabled()) return {};
+ const rows = await sql`select status, count(*)::int as n from print_orders group by status`;
+ /** @type {Record<string, number>} */
+ const out = {};
+ for (const s of PRINT_STATUSES) out[s] = 0;
+ for (const r of rows) out[r.status] = r.n;
+ return out;
+}
+
+/**
+ * The timeline, oldest first: the order in which a human reads a story.
+ * @param {string} orderId
+ */
+export async function listOrderEvents(orderId) {
+ if (!printStoreEnabled() || !orderId) return [];
+ return sql`
+ select id, order_id, status, note, actor, actor_id, created_at
+ from print_order_events
+ where order_id = ${orderId}
+ order by created_at asc, id asc`;
+}
+
+/**
+ * Append a timeline row without changing the order's status. Used for notes an
+ * operator leaves on a job that is not moving yet, and for the provider's
+ * "still printing" heartbeats.
+ * @param {{ orderId: string, status: string, note?: string, actor?: string, actorId?: string|null }} input
+ */
+export async function appendOrderEvent({ orderId, status, note = '', actor = 'system', actorId = null }) {
+ if (!printStoreEnabled()) return null;
+ const safeActor = PRINT_ACTORS.includes(actor) ? actor : 'system';
+ const rows = await sql`
+ insert into print_order_events (order_id, status, note, actor, actor_id)
+ values (${orderId}, ${status}, ${note ? String(note).slice(0, 2000) : null}, ${safeActor}, ${actorId})
+ returning id, order_id, status, note, actor, actor_id, created_at`;
+ return rows[0] || null;
+}
+
+// What a buyer is told, per status. A status with no line here is internal
+// plumbing the buyer has no reason to see (`screening` is deliberately quiet:
+// telling someone their model is being safety-checked invites a fight with a
+// gate that has already decided).
+const BUYER_NOTICE = Object.freeze({
+ submitted: 'Your print is with the fulfillment lane.',
+ printing: 'Your print is on the machine.',
+ quality_check: 'Your print is finished and in quality check.',
+ shipped: 'Your print has shipped.',
+ delivered: 'Your print was delivered.',
+ rejected: 'Your print order could not be fulfilled.',
+ canceled: 'Your print order was canceled.',
+ refunded: 'Your print order was refunded.',
+});
+
+/**
+ * Move an order. The whole write surface of a status change.
+ *
+ * Concurrency: the UPDATE matches on the expected current status, so a lost
+ * race updates zero rows and raises PrintTransitionError with the state the
+ * winner left behind. Callers that legitimately race (a webhook and the
+ * reconciliation sweep reporting the same provider event) treat that as a
+ * no-op, which is why `expect` is separable from `to`.
+ *
+ * @param {object} input
+ * @param {string} input.orderId
+ * @param {string} input.to target status
+ * @param {string} [input.note] free text stored on the timeline row
+ * @param {string} [input.actor] system | operator | provider | buyer
+ * @param {string|null} [input.actorId] the operator's user id, when actor='operator'
+ * @param {Record<string, unknown>} [input.patch] whitelisted columns to set with the move
+ * @returns {Promise<{ order: object, event: object|null }>}
+ */
+export async function transitionOrder({ orderId, to, note = '', actor = 'system', actorId = null, patch = {} }) {
+ if (!printStoreEnabled()) throw new Error('print store requires a configured database');
+ const current = await getOrder(orderId);
+ if (!current) throw new PrintOrderNotFoundError(orderId);
+
+ assertTransition(current.status, to);
+
+ const extra = patchFragment(patch);
+ const rows = await sql`
+ update print_orders
+ set status = ${to}${extra || sql([''])}
+ where id = ${orderId} and status = ${current.status}
+ returning ${ORDER_COLUMNS}`;
+
+ if (rows.length === 0) {
+ // Somebody else moved it between our read and our write.
+ const now = await getOrder(orderId);
+ throw new PrintTransitionError(current.status, to, `order is now '${now?.status || 'gone'}'`);
+ }
+
+ const order = rows[0];
+ const event = await appendOrderEvent({ orderId, status: to, note, actor, actorId });
+ notifyBuyer(order, to);
+ return { order, event };
+}
+
+/**
+ * Tell the buyer, in their notification bell, that their order moved. Silent
+ * for agent orders (no user id to notify) and for statuses with no buyer-facing
+ * line. Fire-and-forget by contract: publishUserEvent never throws.
+ * @param {object} order
+ * @param {string} status
+ */
+function notifyBuyer(order, status) {
+ const line = BUYER_NOTICE[status];
+ if (!line || !order?.user_id) return;
+ publishUserEvent(order.user_id, {
+ type: 'print',
+ status,
+ order_id: order.id,
+ message: line,
+ tracking_number: order.tracking_number || null,
+ link: `/materialize/orders/${order.id}`,
+ });
+}
+
+/**
+ * Orders a provider owns that have been quiet longer than their declared lead
+ * time. The reconciliation sweep's working set.
+ *
+ * `graceDays` is added on top of the order's own lead_time_days, so a job is
+ * only a stall once it is late by a margin, not the moment it hits its
+ * estimate. Orders already alerted within `realertHours` are excluded, which is
+ * what stops a stuck job paging the operator every five minutes.
+ *
+ * @param {{ graceDays?: number, realertHours?: number, limit?: number }} [opts]
+ */
+export async function listStalledOrders({ graceDays = 2, realertHours = 24, limit = 50 } = {}) {
+ if (!printStoreEnabled()) return [];
+ const grace = Math.max(Number(graceDays) || 0, 0);
+ const realert = Math.max(Number(realertHours) || 0, 0);
+ const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);
+ return sql`
+ select ${ORDER_COLUMNS} from print_orders
+ where status = any(${[...OPEN_PROVIDER_STATUSES]})
+ and submitted_at is not null
+ and submitted_at < now() - make_interval(days => (coalesce(lead_time_days, 0) + ${grace})::int)
+ and (stall_alerted_at is null or stall_alerted_at < now() - make_interval(hours => ${realert}::int))
+ order by submitted_at asc
+ limit ${cap}`;
+}
+
+/**
+ * Orders a provider owns, for the reconciliation poll. Unlike listStalledOrders
+ * this returns everything live, late or not: polling is how we learn a job
+ * shipped when a webhook was lost.
+ * @param {{ limit?: number }} [opts]
+ */
+export async function listOpenProviderOrders({ limit = 100 } = {}) {
+ if (!printStoreEnabled()) return [];
+ const cap = Math.min(Math.max(Number(limit) || 100, 1), 500);
+ return sql`
+ select ${ORDER_COLUMNS} from print_orders
+ where status = any(${[...OPEN_PROVIDER_STATUSES]})
+ and provider is not null
+ and provider_order_id is not null
+ order by submitted_at asc nulls first
+ limit ${cap}`;
+}
+
+/**
+ * Record that the operator has been told about a stalled order, so the next
+ * sweep stays quiet. Deliberately not a transition: nothing about the order's
+ * lifecycle changed.
+ * @param {string[]} orderIds
+ */
+export async function markStallAlerted(orderIds) {
+ if (!printStoreEnabled() || !orderIds?.length) return 0;
+ const rows = await sql`
+ update print_orders set stall_alerted_at = now()
+ where id = any(${orderIds})
+ returning id`;
+ return rows.length;
+}
+
+/**
+ * Claim a webhook delivery. Returns true exactly once per (provider,
+ * delivery_id) pair: the insert is the lock, so a provider retrying a delivery
+ * (every serious one does) cannot append the timeline row twice even if two
+ * retries land concurrently on two containers.
+ *
+ * @param {{ provider: string, deliveryId: string, orderId?: string|null }} input
+ * @returns {Promise<{ fresh: boolean }>}
+ */
+export async function claimWebhookDelivery({ provider, deliveryId, orderId = null }) {
+ if (!printStoreEnabled()) throw new Error('webhook idempotency requires a configured database');
+ const rows = await sql`
+ insert into print_webhook_deliveries (provider, delivery_id, order_id)
+ values (${provider}, ${deliveryId}, ${orderId})
+ on conflict (provider, delivery_id) do nothing
+ returning delivery_id`;
+ return { fresh: rows.length > 0 };
+}
+
+/**
+ * Mark a claimed delivery as having actually driven a state change, so an
+ * operator reading the ledger can tell "we saw it and it was a duplicate" from
+ * "we saw it and it moved the order".
+ * @param {{ provider: string, deliveryId: string, orderId?: string|null }} input
+ */
+export async function markWebhookApplied({ provider, deliveryId, orderId = null }) {
+ if (!printStoreEnabled()) return;
+ await sql`
+ update print_webhook_deliveries
+ set applied = true, order_id = coalesce(${orderId}, order_id)
+ where provider = ${provider} and delivery_id = ${deliveryId}`;
+}
+
+/** Deliveries recorded for an order, newest first. Diagnostic read. */
+export async function listWebhookDeliveries(orderId, limit = 50) {
+ if (!printStoreEnabled() || !orderId) return [];
+ const cap = Math.min(Math.max(Number(limit) || 50, 1), 200);
+ return sql`
+ select provider, delivery_id, applied, received_at
+ from print_webhook_deliveries
+ where order_id = ${orderId}
+ order by received_at desc
+ limit ${cap}`;
+}
+
+export { isDbUnavailableError };
diff --git a/api/_lib/print/adapters/contract.js b/api/_lib/print/adapters/contract.js
new file mode 100644
index 000000000..a0fbc675b
--- /dev/null
+++ b/api/_lib/print/adapters/contract.js
@@ -0,0 +1,291 @@
+// @ts-check
+// The fulfillment adapter contract.
+//
+// A "provider" is whoever actually turns a prepared mesh into an object in a
+// box: a human operator driving a print bureau by hand (the `manual` adapter,
+// which is how this product launches) or a contracted partner's API. Both are
+// the same interface, because the day a partner contract lands their API must
+// be a config change rather than a rebuild.
+//
+// The design mirrors the forge's engine registry: adapters are data plus a
+// module. Capabilities are declared, not inferred, so routing an order to a
+// lane is a comparison against published facts (materials, bounding box,
+// origin country, lead time) rather than a try-and-see.
+//
+// THE RULE THAT MATTERS: an adapter never writes the database. It returns
+// vocabulary the store understands, and the caller drives transitionOrder().
+// That is what keeps a partner changing their payload shape from being able to
+// corrupt an order's state machine.
+//
+// ── the interface ────────────────────────────────────────────────────────────
+//
+// key string, stable, stored in print_orders.provider
+// label human name for the console
+// capabilities { materials, maxBboxMm, shipsFrom, leadTimeDays }
+// configured() → boolean. False hides the adapter from the registry.
+// submit(order, assets) → SubmitResult
+// status(providerOrderId) → StatusResult
+// cancel(order, reason) → CancelResult
+// verifyWebhook(raw, headers) → { ok, deliveryId, reason }
+// parseWebhook(payload) → WebhookEvent
+//
+// Every result shape is normalized through this module, so a malformed return
+// from any adapter fails at its own boundary with a named error instead of
+// travelling into the store as junk.
+
+import { createHash } from 'node:crypto';
+import { PRINT_STATUSES } from '../../print-store.js';
+
+/**
+ * The statuses a fulfillment provider is allowed to drive. Everything before
+ * `submitted` is ours (quoting, payment, safety screening) and no adapter may
+ * reach back into it; `refunded` is a money action and stays operator-only.
+ */
+export const ADAPTER_DRIVABLE_STATUSES = Object.freeze([
+ 'submitted',
+ 'printing',
+ 'quality_check',
+ 'shipped',
+ 'delivered',
+ 'canceled',
+ 'rejected',
+]);
+
+/** Thrown when an adapter returns something the store cannot use. */
+export class AdapterContractError extends Error {
+ /**
+ * @param {string} adapterKey
+ * @param {string} detail
+ */
+ constructor(adapterKey, detail) {
+ super(`adapter '${adapterKey}' violated the fulfillment contract: ${detail}`);
+ this.name = 'AdapterContractError';
+ this.code = 'adapter_contract';
+ this.adapterKey = adapterKey;
+ }
+}
+
+/** Thrown when a partner's API is unreachable or answers badly. */
+export class AdapterUpstreamError extends Error {
+ /**
+ * @param {string} adapterKey
+ * @param {string} detail
+ * @param {number} [status]
+ */
+ constructor(adapterKey, detail, status = 0) {
+ super(`adapter '${adapterKey}' upstream failure: ${detail}`);
+ this.name = 'AdapterUpstreamError';
+ this.code = 'adapter_upstream';
+ this.adapterKey = adapterKey;
+ this.status = status;
+ }
+}
+
+const REQUIRED_METHODS = Object.freeze([
+ 'configured',
+ 'submit',
+ 'status',
+ 'cancel',
+ 'verifyWebhook',
+ 'parseWebhook',
+]);
+
+/**
+ * Validate an adapter module's shape. Called by the registry at import time and
+ * by the conformance suite, so a new adapter cannot be registered half-built.
+ * @param {any} adapter
+ * @returns {any} the same adapter, for chaining
+ */
+export function assertAdapterShape(adapter) {
+ const key = adapter?.key;
+ if (typeof key !== 'string' || !/^[a-z][a-z0-9-]{1,31}$/.test(key)) {
+ throw new AdapterContractError(String(key), 'key must be lower-kebab, 2 to 32 chars');
+ }
+ if (typeof adapter.label !== 'string' || !adapter.label.trim()) {
+ throw new AdapterContractError(key, 'label is required');
+ }
+ for (const m of REQUIRED_METHODS) {
+ if (typeof adapter[m] !== 'function') {
+ throw new AdapterContractError(key, `missing method ${m}()`);
+ }
+ }
+ assertCapabilities(key, adapter.capabilities);
+ return adapter;
+}
+
+/**
+ * Capabilities are the adapter's published promises. They are what an order
+ * router compares against, so they are validated as strictly as any wire
+ * format.
+ * @param {string} key
+ * @param {any} caps
+ */
+export function assertCapabilities(key, caps) {
+ if (!caps || typeof caps !== 'object') {
+ throw new AdapterContractError(key, 'capabilities object is required');
+ }
+ const { materials, maxBboxMm, shipsFrom, leadTimeDays } = caps;
+ // '*' means "every material in the catalog"; the manual lane genuinely can
+ // run anything a bureau accepts, and pretending otherwise would be a lie
+ // that blocks orders.
+ const materialsOk = materials === '*' || (Array.isArray(materials) && materials.every((m) => typeof m === 'string' && m));
+ if (!materialsOk) throw new AdapterContractError(key, "capabilities.materials must be '*' or a list of material ids");
+ const bboxOk = maxBboxMm && ['x', 'y', 'z'].every((axis) => Number.isFinite(maxBboxMm[axis]) && maxBboxMm[axis] > 0);
+ if (!bboxOk) throw new AdapterContractError(key, 'capabilities.maxBboxMm must carry positive x, y, z');
+ if (typeof shipsFrom !== 'string' || !/^[A-Z]{2}$/.test(shipsFrom)) {
+ throw new AdapterContractError(key, 'capabilities.shipsFrom must be an ISO 3166-1 alpha-2 country code');
+ }
+ if (!Number.isInteger(leadTimeDays) || leadTimeDays < 1 || leadTimeDays > 120) {
+ throw new AdapterContractError(key, 'capabilities.leadTimeDays must be an integer between 1 and 120');
+ }
+ return caps;
+}
+
+/**
+ * Can this adapter physically run this order? A pure comparison against the
+ * declared capabilities: no network, no side effects.
+ * @param {any} adapter
+ * @param {{ material_id?: string, analysis?: { bbox_mm?: { x?: number, y?: number, z?: number } } }} order
+ * @returns {{ ok: boolean, reason: string }}
+ */
+export function adapterSupportsOrder(adapter, order) {
+ const caps = adapter?.capabilities;
+ if (!caps) return { ok: false, reason: 'adapter declares no capabilities' };
+ const material = order?.material_id || '';
+ if (caps.materials !== '*' && !caps.materials.includes(material)) {
+ return { ok: false, reason: `material '${material || 'none'}' is not offered by ${adapter.key}` };
+ }
+ const bbox = order?.analysis?.bbox_mm;
+ if (bbox && ['x', 'y', 'z'].some((a) => Number(bbox[a]) > caps.maxBboxMm[a])) {
+ return { ok: false, reason: `part exceeds ${adapter.key}'s build volume` };
+ }
+ return { ok: true, reason: '' };
+}
+
+/** @param {string} key @param {any} value @param {string} field */
+function requireDrivableStatus(key, value, field) {
+ if (!ADAPTER_DRIVABLE_STATUSES.includes(value)) {
+ throw new AdapterContractError(key, `${field} must be one of ${ADAPTER_DRIVABLE_STATUSES.join(', ')}, got '${value}'`);
+ }
+ return value;
+}
+
+/**
+ * Normalize what submit() returned.
+ * @param {string} key
+ * @param {any} result
+ * @returns {{ providerOrderId: string, status: string, leadTimeDays: number, note: string, state: object }}
+ */
+export function normalizeSubmitResult(key, result) {
+ if (!result || typeof result !== 'object') throw new AdapterContractError(key, 'submit() returned no result');
+ const providerOrderId = String(result.providerOrderId || '').trim();
+ if (!providerOrderId) throw new AdapterContractError(key, 'submit() must return a providerOrderId');
+ if (providerOrderId.length > 200) throw new AdapterContractError(key, 'providerOrderId is implausibly long');
+ const status = requireDrivableStatus(key, result.status || 'submitted', 'submit().status');
+ const leadTimeDays = Number.isInteger(result.leadTimeDays) ? result.leadTimeDays : null;
+ return {
+ providerOrderId,
+ status,
+ leadTimeDays: leadTimeDays ?? 0,
+ note: typeof result.note === 'string' ? result.note.slice(0, 2000) : '',
+ state: plainState(result.state),
+ };
+}
+
+/**
+ * Normalize what status() returned. `status: null` is legal and means "nothing
+ * changed": a provider that has no news is not an error.
+ * @param {string} key
+ * @param {any} result
+ * @returns {{ status: string|null, trackingNumber: string, carrier: string, note: string, state: object }}
+ */
+export function normalizeStatusResult(key, result) {
+ if (!result || typeof result !== 'object') throw new AdapterContractError(key, 'status() returned no result');
+ const status = result.status == null ? null : requireDrivableStatus(key, result.status, 'status().status');
+ return {
+ status,
+ trackingNumber: cleanShort(result.trackingNumber),
+ carrier: cleanShort(result.carrier),
+ note: typeof result.note === 'string' ? result.note.slice(0, 2000) : '',
+ state: plainState(result.state),
+ };
+}
+
+/**
+ * Normalize what parseWebhook() returned into one applyable event.
+ * @param {string} key
+ * @param {any} result
+ * @returns {{ providerOrderId: string, status: string|null, trackingNumber: string, carrier: string, note: string, state: object }}
+ */
+export function normalizeWebhookEvent(key, result) {
+ if (!result || typeof result !== 'object') throw new AdapterContractError(key, 'parseWebhook() returned no event');
+ const providerOrderId = String(result.providerOrderId || '').trim();
+ if (!providerOrderId) throw new AdapterContractError(key, 'parseWebhook() must identify the order');
+ const status = result.status == null ? null : requireDrivableStatus(key, result.status, 'parseWebhook().status');
+ return {
+ providerOrderId,
+ status,
+ trackingNumber: cleanShort(result.trackingNumber),
+ carrier: cleanShort(result.carrier),
+ note: typeof result.note === 'string' ? result.note.slice(0, 2000) : '',
+ state: plainState(result.state),
+ };
+}
+
+/**
+ * Normalize what cancel() returned.
+ * @param {string} key
+ * @param {any} result
+ */
+export function normalizeCancelResult(key, result) {
+ if (!result || typeof result !== 'object') throw new AdapterContractError(key, 'cancel() returned no result');
+ return {
+ ok: result.ok === true,
+ note: typeof result.note === 'string' ? result.note.slice(0, 2000) : '',
+ state: plainState(result.state),
+ };
+}
+
+/** @param {any} v */
+function cleanShort(v) {
+ return typeof v === 'string' ? v.trim().slice(0, 120) : '';
+}
+
+// Providers return whatever they like. We keep it for diagnostics but never
+// let a non-serializable or oversized blob reach a jsonb column.
+function plainState(state) {
+ if (!state || typeof state !== 'object') return {};
+ try {
+ const json = JSON.stringify(state);
+ if (json.length > 16_000) return { truncated: true, bytes: json.length };
+ return JSON.parse(json);
+ } catch {
+ return {};
+ }
+}
+
+/**
+ * A stable delivery id for a provider that sends none. Hashing the payload
+ * means "the same event twice" is still one row, which is the whole point of
+ * the idempotency ledger.
+ * @param {string} provider
+ * @param {string} rawBody
+ */
+export function derivedDeliveryId(provider, rawBody) {
+ return `sha256:${createHash('sha256').update(`${provider}:${rawBody}`).digest('hex')}`;
+}
+
+/**
+ * Map a provider's own status vocabulary onto ours through a declared table.
+ * Unknown provider statuses return null ("no news"), never a guess: inventing a
+ * transition from an unrecognized string is exactly how a state machine gets
+ * corrupted by a partner's release notes.
+ * @param {Record<string, string>} table
+ * @param {unknown} providerStatus
+ * @returns {string|null}
+ */
+export function mapProviderStatus(table, providerStatus) {
+ if (typeof providerStatus !== 'string') return null;
+ const mapped = table[providerStatus.trim().toLowerCase()];
+ return mapped && PRINT_STATUSES.includes(mapped) ? mapped : null;
+}
diff --git a/api/_lib/print/adapters/manual.js b/api/_lib/print/adapters/manual.js
new file mode 100644
index 000000000..de691e6ea
--- /dev/null
+++ b/api/_lib/print/adapters/manual.js
@@ -0,0 +1,128 @@
+// @ts-check
+// The `manual` fulfillment adapter: the launch lane.
+//
+// There is nothing simulated here. A print marketplace's first fulfillment lane
+// is always a human: an operator takes the prepared STL/3MF off the queue,
+// runs it on a real bureau's machines (or their own), and reports what
+// happened. This adapter is the machine-readable face of that person. Its
+// submit() puts the job on the operator's queue and pages the operator channel;
+// its status() reads back what the operator recorded through the console.
+//
+// Consequences worth stating, because they are what makes this honest rather
+// than a stub:
+// • The provider order id IS our order id. There is no second system, so
+// inventing an opaque handle would be a fiction the operator then has to
+// translate back by hand.
+// • status() is a database read, not a network call. The operator console's
+// transitions are the source of truth, so polling this adapter always
+// agrees with the order it is polling. That is exactly what the
+// reconciliation sweep needs to leave manual jobs alone until they are late.
+// • There is no webhook. verifyWebhook() refuses every delivery rather than
+// leaving an unauthenticated door open on a provider that cannot call it.
+
+import { getOrder } from '../../print-store.js';
+import { jobSummaryLines, notifyOperators } from '../ops-notify.js';
+
+export const key = 'manual';
+export const label = 'Manual fulfillment (operator console)';
+
+export const capabilities = Object.freeze({
+ // A human with a bureau relationship can run anything the catalog offers;
+ // the constraint is the part, not the lane.
+ materials: '*',
+ // The largest build envelope reachable across the resin and SLS machines a
+ // bureau operator routes to. A part larger than this needs splitting, which
+ // is out of launch scope (00-CONTEXT: multi-part assemblies are later).
+ maxBboxMm: { x: 380, y: 380, z: 600 },
+ shipsFrom: 'US',
+ // Hand-run jobs carry a bureau queue plus shipping. Ten days is the point
+ // past which an operator should be asked what happened, not a promise to
+ // the buyer: the buyer's estimate comes from the catalog's per-material
+ // lead time in the quote.
+ leadTimeDays: 10,
+});
+
+/** Always available: this lane needs a person, not a credential. */
+export function configured() {
+ return true;
+}
+
+/**
+ * Put the job on the operator queue and page the channel.
+ * @param {object} order
+ * @param {{ stl?: string, '3mf'?: string, glb?: string }} [assets]
+ */
+export async function submit(order, assets = {}) {
+ const formats = Object.keys(assets || {}).filter((k) => assets[k]);
+ await notifyOperators({
+ title: 'New print job ready to submit',
+ lines: [
+ ...jobSummaryLines(order),
+ formats.length ? `Prepared: ${formats.join(', ')}` : 'Prepared assets missing: check the order before running it',
+ ],
+ orderId: order?.id,
+ });
+ return {
+ providerOrderId: String(order?.id || ''),
+ status: 'submitted',
+ leadTimeDays: capabilities.leadTimeDays,
+ note: 'Queued for the operator console.',
+ state: { lane: 'manual', queued_at: new Date().toISOString(), formats },
+ };
+}
+
+/**
+ * What the operator has recorded. A read of our own order row, which for this
+ * lane is the provider's system of record.
+ * @param {string} providerOrderId
+ */
+export async function status(providerOrderId) {
+ const order = await getOrder(providerOrderId);
+ if (!order) {
+ // Not an error the sweep should retry: a manual job whose order is gone
+ // has nothing left to reconcile.
+ return { status: null, note: 'order not found', state: { lane: 'manual', missing: true } };
+ }
+ return {
+ // The order already carries the operator's latest word, so reporting it
+ // back is a no-op transition by construction. Returning null keeps the
+ // sweep from attempting a self-transition it would only have to refuse.
+ status: null,
+ trackingNumber: order.tracking_number || '',
+ carrier: order.carrier || '',
+ note: `Operator lane, currently ${order.status}.`,
+ state: { lane: 'manual', operator_status: order.status },
+ };
+}
+
+/**
+ * Tell the operator to stop. The order's own transition to `canceled` is the
+ * console's job; this is the page that makes sure nobody keeps printing.
+ * @param {object} order
+ * @param {string} [reason]
+ */
+export async function cancel(order, reason = '') {
+ await notifyOperators({
+ title: 'Print job cancellation requested',
+ lines: [...jobSummaryLines(order), reason ? `Reason: ${reason}` : 'No reason given'],
+ orderId: order?.id,
+ });
+ return { ok: true, note: 'Operator notified to stop the job.', state: { lane: 'manual', cancel_requested: true } };
+}
+
+/**
+ * The manual lane has no callback URL, so every delivery to it is either a
+ * misrouted partner payload or someone probing. Refusing outright is the only
+ * correct answer; a permissive default here would be an unauthenticated write
+ * into the state machine.
+ */
+export function verifyWebhook() {
+ return { ok: false, deliveryId: '', reason: 'the manual lane has no webhook; operators transition orders in the console' };
+}
+
+/** Unreachable in practice (verifyWebhook always refuses), and says so. */
+export function parseWebhook() {
+ throw new Error('manual adapter receives no webhooks');
+}
+
+export default { key, label, capabilities, configured, submit, status, cancel, verifyWebhook, parseWebhook };
diff --git a/api/_lib/print/analyze.js b/api/_lib/print/analyze.js
new file mode 100644
index 000000000..b774229d6
--- /dev/null
+++ b/api/_lib/print/analyze.js
@@ -0,0 +1,367 @@
+// The printability report: the one contract every downstream surface reads.
+//
+// Quotes multiply money by `volume_cm3`. The materialize page renders `score`
+// and its named deductions. The fabrication gate reads the geometry summary.
+// The operator console shows the frozen copy taken at order time. So this
+// module has two hard properties, and both are tested:
+//
+// 1. DETERMINISTIC. The same bytes produce byte-identical numbers. Every
+// sample here is taken on a fixed stride, never a random draw, and every
+// float that reaches the wire is rounded at a declared precision.
+// 2. HONEST ABOUT ITS LIMITS. A metric that was sampled rather than
+// exhaustively computed says so in `sampling`, and a number the manifold
+// kernel could not vouch for is labelled with its `source`. A print
+// report that quietly guesses is how a buyer gets a hollow shell they
+// paid solid-resin prices for.
+//
+// Units: glTF geometry is in meters. Everything the report publishes is in
+// millimeters, cubic centimeters, or square centimeters, because those are
+// the units a print bureau quotes in.
+
+import * as THREE from 'three';
+import { MeshBVH, ExtendedTriangle } from 'three-mesh-bvh';
+import { boundsOf, weldPositions } from './mesh-io.js';
+import { edgeCensus, shells, signedVolume, surfaceArea } from './topology.js';
+import { toManifold, isNotManifoldError } from './manifold.js';
+
+export const REPORT_VERSION = 1;
+
+// Weld tolerance in meters. 10 microns is far below any printable feature and
+// far above the float32 rounding a GLB's POSITION accessor introduces, so it
+// closes seams without merging genuinely distinct geometry.
+const WELD_TOLERANCE_M = 1e-5;
+
+// How many surface points the wall-thickness probe casts from. 2,000 BVH
+// raycasts is single-digit milliseconds and is dense enough that a thin
+// feature larger than a few percent of the surface cannot hide from it. The
+// number is fixed rather than scaled so two analyses of the same mesh agree.
+const WALL_SAMPLES = 2000;
+
+// Triangle budget for the exhaustive self-intersection scan. Above it the scan
+// runs on a deterministic stride and the report says so, because an O(n log n)
+// pass over a million triangles is not a request-time operation.
+const SELF_INTERSECTION_FULL_LIMIT = 120_000;
+const SELF_INTERSECTION_SAMPLES = 40_000;
+
+// Minimum printable wall per material class, millimeters. These are process
+// limits (what the machine can resolve), not vendor prices, which is why they
+// live beside the analyzer rather than in the tunable price catalog. The
+// catalog carries each material's own min wall for quoting; these drive the
+// "how big must I print this" recommendation, which exists before any
+// material is chosen.
+export const CLASS_MIN_WALL_MM = {
+ resin: 0.6,
+ sls_nylon: 0.8,
+ full_color: 2.0,
+ fdm_draft: 1.2,
+ metal: 1.0,
+};
+
+const round = (v, places) => {
+ const f = 10 ** places;
+ return Math.round(v * f) / f;
+};
+
+/**
+ * Deterministic surface sampling: walk triangles on a fixed stride and probe
+ * the barycentric point that is offset from the centroid, so a ray never
+ * leaves exactly along a shared edge (which returns a doubled hit and a
+ * meaningless distance).
+ */
+function sampleTriangles(triangleCount, wanted) {
+ const n = Math.min(triangleCount, wanted);
+ if (n <= 0) return [];
+ const stride = Math.max(1, Math.floor(triangleCount / n));
+ const out = [];
+ for (let t = 0; t < triangleCount && out.length < n; t += stride) out.push(t);
+ return out;
+}
+
+/**
+ * Wall thickness at a surface point: fire a ray along the inward normal and
+ * measure the distance to the first back-facing surface it meets. A hit at
+ * effectively zero distance is the origin triangle itself and is discarded.
+ *
+ * Returns the sorted thickness samples in meters.
+ */
+function sampleWallThickness(bvh, positions, indices, triangleIds, diagonal) {
+ const ray = new THREE.Ray();
+ const origin = new THREE.Vector3();
+ const dir = new THREE.Vector3();
+ const ab = new THREE.Vector3();
+ const ac = new THREE.Vector3();
+ const va = new THREE.Vector3();
+ const vb = new THREE.Vector3();
+ const vc = new THREE.Vector3();
+ // Push the ray origin just under the surface so the source triangle is
+ // behind it. One part in 100,000 of the model diagonal is well below any
+ // printable feature and well above float precision.
+ const epsilon = diagonal * 1e-5;
+ const samples = [];
+
+ for (const t of triangleIds) {
+ const a = indices[t * 3] * 3;
+ const b = indices[t * 3 + 1] * 3;
+ const c = indices[t * 3 + 2] * 3;
+ va.set(positions[a], positions[a + 1], positions[a + 2]);
+ vb.set(positions[b], positions[b + 1], positions[b + 2]);
+ vc.set(positions[c], positions[c + 1], positions[c + 2]);
+ ab.subVectors(vb, va);
+ ac.subVectors(vc, va);
+ dir.crossVectors(ab, ac);
+ if (dir.lengthSq() === 0) continue;
+ dir.normalize().negate();
+ // Barycentric (0.4, 0.35, 0.25): interior, and never the centroid, so a
+ // symmetric mesh does not concentrate every probe on one axis.
+ origin
+ .copy(va)
+ .multiplyScalar(0.4)
+ .addScaledVector(vb, 0.35)
+ .addScaledVector(vc, 0.25)
+ .addScaledVector(dir, epsilon);
+ ray.set(origin, dir);
+ const hit = bvh.raycastFirst(ray, THREE.DoubleSide, 0, diagonal * 2);
+ if (!hit) continue;
+ const thickness = hit.distance + epsilon;
+ if (thickness > epsilon * 2) samples.push(thickness);
+ }
+ samples.sort((x, y) => x - y);
+ return samples;
+}
+
+/** Value at a percentile of an ascending sample array. */
+function percentile(sorted, p) {
+ if (sorted.length === 0) return null;
+ const i = Math.min(sorted.length - 1, Math.max(0, Math.round((p / 100) * (sorted.length - 1))));
+ return sorted[i];
+}
+
+/**
+ * Count triangle pairs that pass through each other. Adjacent triangles (any
+ * shared welded vertex) are skipped: they meet by construction and are not a
+ * defect.
+ */
+function countSelfIntersections(bvh, positions, indices, triangleIds) {
+ const query = new ExtendedTriangle();
+ const box = new THREE.Box3();
+ let count = 0;
+ const seen = new Set();
+
+ for (const t of triangleIds) {
+ const ia = indices[t * 3];
+ const ib = indices[t * 3 + 1];
+ const ic = indices[t * 3 + 2];
+ query.a.set(positions[ia * 3], positions[ia * 3 + 1], positions[ia * 3 + 2]);
+ query.b.set(positions[ib * 3], positions[ib * 3 + 1], positions[ib * 3 + 2]);
+ query.c.set(positions[ic * 3], positions[ic * 3 + 1], positions[ic * 3 + 2]);
+ query.needsUpdate = true;
+ box.makeEmpty().expandByPoint(query.a).expandByPoint(query.b).expandByPoint(query.c);
+
+ bvh.shapecast({
+ intersectsBounds: (bounds) => bounds.intersectsBox(box),
+ intersectsTriangle: (other, otherIndex) => {
+ if (otherIndex === t) return false;
+ const oa = indices[otherIndex * 3];
+ const ob = indices[otherIndex * 3 + 1];
+ const oc = indices[otherIndex * 3 + 2];
+ if (
+ oa === ia || oa === ib || oa === ic ||
+ ob === ia || ob === ib || ob === ic ||
+ oc === ia || oc === ib || oc === ic
+ ) {
+ return false;
+ }
+ const key = t < otherIndex ? `${t}:${otherIndex}` : `${otherIndex}:${t}`;
+ if (seen.has(key)) return false;
+ if (other.intersectsTriangle(query)) {
+ seen.add(key);
+ count += 1;
+ }
+ return false;
+ },
+ });
+ }
+ return count;
+}
+
+/**
+ * Build a BVH over a welded soup. three-mesh-bvh wants a BufferGeometry, and
+ * its raycasts run in float32, which is why every distance it returns is
+ * treated as a sample rather than an exact measurement.
+ */
+function buildBvh(positions, indices) {
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.BufferAttribute(Float32Array.from(positions), 3));
+ geometry.setIndex(new THREE.BufferAttribute(Uint32Array.from(indices), 1));
+ return new MeshBVH(geometry);
+}
+
+/**
+ * Score the mesh 0-100 with named, individually explainable deductions. The UI
+ * renders this list verbatim, so every `detail` string is buyer-readable.
+ */
+function scoreReport(facts) {
+ const deductions = [];
+ const deduct = (id, points, detail) => {
+ if (points > 0) deductions.push({ id, points: round(points, 1), detail });
+ };
+
+ if (!facts.manifold) {
+ deduct('non_manifold', 30, 'The surface is not a closed solid, so it has to be reconstructed before printing.');
+ }
+ if (facts.open_edges > 0) {
+ // A handful of boundary edges is a small hole; thousands is a mesh that
+ // is really a surface. Scale the penalty by how much of the perimeter is
+ // open, capped so it can never dominate the whole score on its own.
+ const share = facts.edge_count > 0 ? facts.open_edges / facts.edge_count : 0;
+ deduct('open_edges', Math.min(20, 4 + share * 200), `${facts.open_edges} boundary edges form holes in the surface.`);
+ }
+ if (facts.non_manifold_edges > 0) {
+ deduct('non_manifold_edges', Math.min(12, 3 + facts.non_manifold_edges / 50), `${facts.non_manifold_edges} edges are shared by more than two faces.`);
+ }
+ if (facts.self_intersections > 0) {
+ deduct('self_intersections', Math.min(15, 5 + facts.self_intersections / 200), `${facts.self_intersections} pairs of faces pass through each other.`);
+ }
+ if (facts.shells > 1) {
+ deduct('multiple_shells', Math.min(10, 3 + facts.shells), `The model is ${facts.shells} separate bodies, which print as ${facts.shells} loose pieces.`);
+ }
+ if (facts.degenerate_triangles > 0) {
+ deduct('degenerate_triangles', Math.min(5, facts.degenerate_triangles / 100), `${facts.degenerate_triangles} triangles have zero area.`);
+ }
+ if (facts.min_wall_mm !== null && facts.min_wall_mm < CLASS_MIN_WALL_MM.resin) {
+ const ratio = facts.min_wall_mm / CLASS_MIN_WALL_MM.resin;
+ deduct('thin_walls', Math.min(18, 6 + (1 - ratio) * 12), `The thinnest measured wall is ${facts.min_wall_mm} mm, below the ${CLASS_MIN_WALL_MM.resin} mm a resin printer can hold at this size.`);
+ }
+ if (facts.triangles > 1_000_000) {
+ deduct('triangle_budget', 4, `${facts.triangles} triangles is heavier than any printer needs; it will be decimated during preparation.`);
+ }
+
+ const total = deductions.reduce((sum, d) => sum + d.points, 0);
+ return { score: Math.max(0, Math.round(100 - total)), deductions };
+}
+
+/**
+ * Recommended minimum print height per material class: how tall the object has
+ * to be printed for its thinnest wall to clear that process's resolution.
+ * Null when no wall could be measured (an open surface with nothing behind it).
+ */
+function recommendedHeights(minWallMm, heightMm) {
+ if (!minWallMm || !heightMm || minWallMm <= 0) return null;
+ const out = {};
+ for (const [cls, minWall] of Object.entries(CLASS_MIN_WALL_MM)) {
+ out[cls] = round(Math.max(heightMm, (heightMm * minWall) / minWallMm), 1);
+ }
+ return out;
+}
+
+/**
+ * Produce the printability report for a loaded mesh.
+ *
+ * @param {{ positions: Float64Array, indices: Uint32Array, triangleCount: number,
+ * vertexCount: number, hasTextures: boolean, colorSource: string, sizeBytes: number,
+ * materials: number, skippedPrimitives: number }} mesh from loadMesh()
+ * @param {{ sourceUrl?: string|null }} [opts]
+ */
+export async function analyzeMesh(mesh, opts = {}) {
+ const welded = weldPositions(mesh.positions, mesh.indices, WELD_TOLERANCE_M);
+ const bounds = boundsOf(welded.positions);
+ if (!bounds) {
+ throw new Error('mesh has no finite bounds');
+ }
+
+ const census = edgeCensus(welded.indices);
+ const shellInfo = shells(welded.indices, welded.positions.length / 3);
+ const triangleCount = welded.indices.length / 3;
+
+ // The manifold kernel is the arbiter of "is this a solid". When it accepts
+ // the mesh its volume is exact; when it refuses, the divergence-theorem sum
+ // over the soup is the best available number and is labelled as such.
+ let manifold = false;
+ let volumeM3 = null;
+ let volumeSource = 'signed_sum';
+ let genus = null;
+ try {
+ const solid = await toManifold(welded.positions, welded.indices);
+ manifold = true;
+ volumeM3 = Math.abs(solid.volume());
+ volumeSource = 'manifold';
+ genus = solid.genus();
+ solid.delete?.();
+ } catch (err) {
+ if (!isNotManifoldError(err)) throw err;
+ volumeM3 = Math.abs(signedVolume(welded.positions, welded.indices));
+ }
+
+ const bvh = buildBvh(welded.positions, welded.indices);
+ const wallIds = sampleTriangles(triangleCount, WALL_SAMPLES);
+ const wallSamples = sampleWallThickness(bvh, welded.positions, welded.indices, wallIds, bounds.diagonal);
+
+ const fullScan = triangleCount <= SELF_INTERSECTION_FULL_LIMIT;
+ const siIds = fullScan
+ ? sampleTriangles(triangleCount, triangleCount)
+ : sampleTriangles(triangleCount, SELF_INTERSECTION_SAMPLES);
+ const selfIntersections = countSelfIntersections(bvh, welded.positions, welded.indices, siIds);
+
+ const areaM2 = surfaceArea(welded.positions, welded.indices);
+ const heightMm = round(bounds.size[1] * 1000, 2);
+ const minWallM = percentile(wallSamples, 1);
+ const minWallMm = minWallM === null ? null : round(minWallM * 1000, 3);
+ const medianWallMm = wallSamples.length ? round(percentile(wallSamples, 50) * 1000, 3) : null;
+
+ const facts = {
+ manifold,
+ shells: shellInfo.count,
+ open_edges: census.openEdges,
+ non_manifold_edges: census.nonManifoldEdges,
+ edge_count: census.edgeCount,
+ degenerate_triangles: census.degenerateTriangles,
+ self_intersections: selfIntersections,
+ min_wall_mm: minWallMm,
+ triangles: triangleCount,
+ };
+ const { score, deductions } = scoreReport(facts);
+
+ return {
+ version: REPORT_VERSION,
+ manifold,
+ watertight: manifold && census.openEdges === 0,
+ shells: shellInfo.count,
+ open_edges: census.openEdges,
+ non_manifold_edges: census.nonManifoldEdges,
+ degenerate_triangles: census.degenerateTriangles,
+ self_intersections: selfIntersections,
+ self_intersections_exhaustive: fullScan,
+ genus,
+ triangles: triangleCount,
+ vertices: welded.positions.length / 3,
+ source_triangles: mesh.triangleCount,
+ source_vertices: mesh.vertexCount,
+ bbox_mm: {
+ x: round(bounds.size[0] * 1000, 2),
+ y: heightMm,
+ z: round(bounds.size[2] * 1000, 2),
+ diagonal: round(bounds.diagonal * 1000, 2),
+ },
+ volume_cm3: round(volumeM3 * 1e6, 4),
+ volume_source: volumeSource,
+ surface_area_cm2: round(areaM2 * 1e4, 3),
+ min_wall_mm: minWallMm,
+ median_wall_mm: medianWallMm,
+ recommended_min_height_mm: recommendedHeights(minWallMm, heightMm),
+ has_textures: Boolean(mesh.hasTextures),
+ color_source: mesh.colorSource || 'none',
+ materials: mesh.materials ?? null,
+ skipped_primitives: mesh.skippedPrimitives ?? 0,
+ size_bytes: mesh.sizeBytes ?? null,
+ sampling: {
+ weld_tolerance_mm: round(WELD_TOLERANCE_M * 1000, 4),
+ wall_rays_requested: WALL_SAMPLES,
+ wall_rays_hit: wallSamples.length,
+ wall_percentile: 1,
+ self_intersection_triangles_scanned: siIds.length,
+ },
+ score,
+ deductions,
+ source_url: opts.sourceUrl ?? null,
+ };
+}
diff --git a/api/_lib/print/bvh.js b/api/_lib/print/bvh.js
new file mode 100644
index 000000000..6c29a3b8f
--- /dev/null
+++ b/api/_lib/print/bvh.js
@@ -0,0 +1,323 @@
+// Materialize spatial queries: one BVH, three questions.
+//
+// The printability report needs to answer "how thin is the thinnest wall",
+// "does the surface pass through itself", and (for repair and hollowing) "is
+// this point inside the solid, and how far from its surface". All three are
+// ray/proximity queries over the same triangles, so they share one
+// three-mesh-bvh acceleration structure built once per call.
+//
+// Determinism is a contract of the report, so nothing here samples randomly:
+// surface points are chosen by a fixed stride over the triangle list, and the
+// probe ray directions are constants. The same bytes always produce the same
+// numbers.
+
+import { BufferGeometry, BufferAttribute, Ray, Vector3, DoubleSide } from 'three';
+import { MeshBVH } from 'three-mesh-bvh';
+
+// Probe directions for the inside/outside parity test. Deliberately not
+// axis-aligned: an axis ray through a box-modelled mesh grazes coplanar
+// triangles and miscounts crossings. Three directions let an open shell (where
+// a single ray can leak through a hole) resolve by majority vote.
+const PROBE_DIRS = [
+ [0.5227083, 0.3841105, 0.7607874],
+ [-0.7071068, 0.6172134, 0.3454941],
+ [0.2672612, -0.8017837, 0.5345225],
+];
+
+/** Build a BVH over an indexed Float64 soup. Returns { geometry, bvh }. */
+export function buildBvh(positions, indices) {
+ const geometry = new BufferGeometry();
+ geometry.setAttribute('position', new BufferAttribute(Float32Array.from(positions), 3));
+ geometry.setIndex(new BufferAttribute(Uint32Array.from(indices), 1));
+ const bvh = new MeshBVH(geometry);
+ return { geometry, bvh };
+}
+
+/** Unit outward normal of triangle `t`, from the winding of the welded soup. */
+export function triangleNormal(positions, indices, t, out = [0, 0, 0]) {
+ const a = indices[t * 3] * 3;
+ const b = indices[t * 3 + 1] * 3;
+ const c = indices[t * 3 + 2] * 3;
+ const ax = positions[b] - positions[a];
+ const ay = positions[b + 1] - positions[a + 1];
+ const az = positions[b + 2] - positions[a + 2];
+ const bx = positions[c] - positions[a];
+ const by = positions[c + 1] - positions[a + 1];
+ const bz = positions[c + 2] - positions[a + 2];
+ const nx = ay * bz - az * by;
+ const ny = az * bx - ax * bz;
+ const nz = ax * by - ay * bx;
+ const len = Math.hypot(nx, ny, nz) || 1;
+ out[0] = nx / len;
+ out[1] = ny / len;
+ out[2] = nz / len;
+ return out;
+}
+
+/** Centroid of triangle `t`. */
+export function triangleCentroid(positions, indices, t, out = [0, 0, 0]) {
+ const a = indices[t * 3] * 3;
+ const b = indices[t * 3 + 1] * 3;
+ const c = indices[t * 3 + 2] * 3;
+ for (let k = 0; k < 3; k += 1) {
+ out[k] = (positions[a + k] + positions[b + k] + positions[c + k]) / 3;
+ }
+ return out;
+}
+
+/**
+ * Measure local wall thickness at a deterministic sample of surface points.
+ *
+ * At each sampled triangle we step just inside the surface and cast a ray along
+ * the inward normal; the distance to the first surface it meets is the material
+ * thickness at that point. This is the same measurement a slicer's thin-wall
+ * warning uses, and it is the number that decides whether a printed detail
+ * survives depowdering or snaps off.
+ *
+ * Sampling is a fixed stride over the triangle list rather than a random draw,
+ * so a re-run over identical bytes returns identical numbers.
+ *
+ * @param {{ positions: Float64Array, indices: Uint32Array, bvh: MeshBVH }} mesh
+ * Positions MUST have consistent outward winding (feed the repaired solid),
+ * otherwise "inward" is meaningless on flipped faces.
+ * @param {{ samples?: number, diagonal: number }} opts
+ * @returns {{ min: number|null, median: number|null, p05: number|null, samples: number,
+ * measured: number }} distances in the mesh's own units
+ */
+export function sampleWallThickness({ positions, indices, bvh }, { samples = 2000, diagonal }) {
+ const triCount = indices.length / 3;
+ if (!triCount || !Number.isFinite(diagonal) || diagonal <= 0) {
+ return { min: null, median: null, p05: null, samples: 0, measured: 0 };
+ }
+ const stride = Math.max(1, Math.floor(triCount / samples));
+ // Step off the surface by a fraction of the model size so the ray does not
+ // re-hit its own origin triangle, and cap the ray so a probe that escapes
+ // through an opening is discarded instead of reporting the far wall.
+ const epsilon = diagonal * 1e-6;
+ const maxDistance = diagonal * 1.001;
+ const ray = new Ray(new Vector3(), new Vector3());
+ const normal = [0, 0, 0];
+ const centroid = [0, 0, 0];
+ const measured = [];
+ let taken = 0;
+
+ for (let t = 0; t < triCount; t += stride) {
+ taken += 1;
+ triangleNormal(positions, indices, t, normal);
+ triangleCentroid(positions, indices, t, centroid);
+ ray.origin.set(
+ centroid[0] - normal[0] * epsilon,
+ centroid[1] - normal[1] * epsilon,
+ centroid[2] - normal[2] * epsilon,
+ );
+ ray.direction.set(-normal[0], -normal[1], -normal[2]);
+ const hit = bvh.raycastFirst(ray, DoubleSide);
+ if (!hit || hit.distance > maxDistance) continue;
+ const thickness = hit.distance + epsilon;
+ if (thickness > 0) measured.push(thickness);
+ }
+
+ if (!measured.length) {
+ return { min: null, median: null, p05: null, samples: taken, measured: 0 };
+ }
+ measured.sort((a, b) => a - b);
+ const at = (q) => measured[Math.min(measured.length - 1, Math.floor(q * measured.length))];
+ return {
+ min: measured[0],
+ p05: at(0.05),
+ median: at(0.5),
+ samples: taken,
+ measured: measured.length,
+ };
+}
+
+/**
+ * Count triangle pairs whose interiors intersect. Self-intersections are what
+ * make a slicer produce interleaved inside/outside regions on a layer, which
+ * prints as a hollow blob where a solid was expected.
+ *
+ * Triangles that merely share a vertex or an edge are neighbours, not
+ * intersections, and are excluded. Above `fullScanLimit` triangles the scan
+ * walks a fixed stride instead of every face and reports `scanned: 'sampled'`,
+ * so a 2M-triangle upload cannot turn one free call into a minute of CPU.
+ *
+ * @returns {{ count: number, scanned: 'full'|'sampled', tested: number, capped: boolean }}
+ */
+export function countSelfIntersections(
+ { positions, indices, bvh, geometry },
+ { fullScanLimit = 120_000, maxReported = 5000 } = {},
+) {
+ const triCount = indices.length / 3;
+ const stride = triCount > fullScanLimit ? Math.ceil(triCount / fullScanLimit) : 1;
+ const pos = geometry.attributes.position.array;
+ const idx = geometry.index.array;
+
+ const a = new Vector3();
+ const b = new Vector3();
+ const c = new Vector3();
+ let count = 0;
+ let tested = 0;
+ let capped = false;
+
+ const box = { min: new Vector3(), max: new Vector3() };
+ for (let t = 0; t < triCount && !capped; t += stride) {
+ tested += 1;
+ const i0 = idx[t * 3];
+ const i1 = idx[t * 3 + 1];
+ const i2 = idx[t * 3 + 2];
+ a.set(pos[i0 * 3], pos[i0 * 3 + 1], pos[i0 * 3 + 2]);
+ b.set(pos[i1 * 3], pos[i1 * 3 + 1], pos[i1 * 3 + 2]);
+ c.set(pos[i2 * 3], pos[i2 * 3 + 1], pos[i2 * 3 + 2]);
+ box.min.set(Math.min(a.x, b.x, c.x), Math.min(a.y, b.y, c.y), Math.min(a.z, b.z, c.z));
+ box.max.set(Math.max(a.x, b.x, c.x), Math.max(a.y, b.y, c.y), Math.max(a.z, b.z, c.z));
+
+ bvh.shapecast({
+ intersectsBounds: (bounds) =>
+ bounds.max.x >= box.min.x &&
+ bounds.min.x <= box.max.x &&
+ bounds.max.y >= box.min.y &&
+ bounds.min.y <= box.max.y &&
+ bounds.max.z >= box.min.z &&
+ bounds.min.z <= box.max.z,
+ intersectsTriangle: (tri, other) => {
+ // Count each unordered pair once, and never a triangle against
+ // itself or a neighbour it legitimately touches.
+ if (other <= t) return false;
+ const j0 = idx[other * 3];
+ const j1 = idx[other * 3 + 1];
+ const j2 = idx[other * 3 + 2];
+ if (
+ j0 === i0 || j0 === i1 || j0 === i2 ||
+ j1 === i0 || j1 === i1 || j1 === i2 ||
+ j2 === i0 || j2 === i1 || j2 === i2
+ ) {
+ return false;
+ }
+ if (trianglesIntersect(a, b, c, tri.a, tri.b, tri.c)) {
+ count += 1;
+ if (count >= maxReported) {
+ capped = true;
+ return true;
+ }
+ }
+ return false;
+ },
+ });
+ }
+
+ return {
+ count,
+ scanned: stride === 1 ? 'full' : 'sampled',
+ tested,
+ capped,
+ };
+}
+
+// Moller's interval-overlap triangle/triangle test, reduced to the boolean the
+// caller needs. Coplanar pairs are treated as non-intersecting: coincident
+// coplanar faces are a duplicate-geometry artifact the manifold boolean merges
+// away, and counting them would flood the report with thousands of "errors" a
+// user cannot act on.
+function trianglesIntersect(a0, a1, a2, b0, b1, b2) {
+ const n1 = planeNormal(a0, a1, a2);
+ if (!n1) return false;
+ const d1 = -(n1.x * a0.x + n1.y * a0.y + n1.z * a0.z);
+ const db = [
+ n1.x * b0.x + n1.y * b0.y + n1.z * b0.z + d1,
+ n1.x * b1.x + n1.y * b1.y + n1.z * b1.z + d1,
+ n1.x * b2.x + n1.y * b2.y + n1.z * b2.z + d1,
+ ];
+ const eps = 1e-12;
+ for (let i = 0; i < 3; i += 1) if (Math.abs(db[i]) < eps) db[i] = 0;
+ if ((db[0] > 0 && db[1] > 0 && db[2] > 0) || (db[0] < 0 && db[1] < 0 && db[2] < 0)) return false;
+ if (db[0] === 0 && db[1] === 0 && db[2] === 0) return false;
+
+ const n2 = planeNormal(b0, b1, b2);
+ if (!n2) return false;
+ const d2 = -(n2.x * b0.x + n2.y * b0.y + n2.z * b0.z);
+ const da = [
+ n2.x * a0.x + n2.y * a0.y + n2.z * a0.z + d2,
+ n2.x * a1.x + n2.y * a1.y + n2.z * a1.z + d2,
+ n2.x * a2.x + n2.y * a2.y + n2.z * a2.z + d2,
+ ];
+ for (let i = 0; i < 3; i += 1) if (Math.abs(da[i]) < eps) da[i] = 0;
+ if ((da[0] > 0 && da[1] > 0 && da[2] > 0) || (da[0] < 0 && da[1] < 0 && da[2] < 0)) return false;
+
+ // Project both triangles onto the intersection line of the two planes and
+ // compare the resulting intervals.
+ const dir = [
+ n1.y * n2.z - n1.z * n2.y,
+ n1.z * n2.x - n1.x * n2.z,
+ n1.x * n2.y - n1.y * n2.x,
+ ];
+ const axis = Math.abs(dir[0]) > Math.abs(dir[1])
+ ? (Math.abs(dir[0]) > Math.abs(dir[2]) ? 0 : 2)
+ : (Math.abs(dir[1]) > Math.abs(dir[2]) ? 1 : 2);
+ const proj = (v) => (axis === 0 ? v.x : axis === 1 ? v.y : v.z);
+ const ia = lineInterval([proj(a0), proj(a1), proj(a2)], da);
+ const ib = lineInterval([proj(b0), proj(b1), proj(b2)], db);
+ if (!ia || !ib) return false;
+ return ia[0] <= ib[1] && ib[0] <= ia[1];
+}
+
+function planeNormal(p0, p1, p2) {
+ const ax = p1.x - p0.x;
+ const ay = p1.y - p0.y;
+ const az = p1.z - p0.z;
+ const bx = p2.x - p0.x;
+ const by = p2.y - p0.y;
+ const bz = p2.z - p0.z;
+ const x = ay * bz - az * by;
+ const y = az * bx - ax * bz;
+ const z = ax * by - ay * bx;
+ if (x === 0 && y === 0 && z === 0) return null;
+ return { x, y, z };
+}
+
+// The two edges of a triangle that cross the other plane give the segment the
+// triangle carves out of the intersection line.
+function lineInterval(p, d) {
+ const out = [];
+ for (let i = 0; i < 3; i += 1) {
+ const j = (i + 1) % 3;
+ if (d[i] === 0) out.push(p[i]);
+ if ((d[i] > 0 && d[j] < 0) || (d[i] < 0 && d[j] > 0)) {
+ out.push(p[i] + ((p[j] - p[i]) * d[i]) / (d[i] - d[j]));
+ }
+ }
+ if (out.length < 2) return null;
+ return [Math.min(...out), Math.max(...out)];
+}
+
+/**
+ * Build a signed-distance function over a triangle soup for manifold's
+ * levelSet reconstruction: positive inside, negative outside, in the mesh's
+ * own units.
+ *
+ * Distance is clamped to a narrow band around the surface. Marching only reads
+ * the zero crossing, so clamping is behaviour-preserving and lets the BVH
+ * abandon the vast majority of grid points (which sit far from any triangle)
+ * after a single node test.
+ *
+ * @param {{ bvh: MeshBVH }} mesh
+ * @param {{ band: number, votes?: number }} opts `votes` 3 for open shells,
+ * where a single probe ray can escape through a hole and misjudge the sign.
+ */
+export function signedDistanceFunction({ bvh }, { band, votes = 1 }) {
+ const point = new Vector3();
+ const ray = new Ray(new Vector3(), new Vector3());
+ const target = {};
+ const dirs = PROBE_DIRS.slice(0, Math.max(1, Math.min(3, votes)));
+ return (p) => {
+ point.set(p[0], p[1], p[2]);
+ const hit = bvh.closestPointToPoint(point, target, 0, band);
+ const distance = hit ? Math.min(hit.distance, band) : band;
+ let inside = 0;
+ for (const d of dirs) {
+ ray.origin.copy(point);
+ ray.direction.set(d[0], d[1], d[2]);
+ if (bvh.raycast(ray, DoubleSide).length % 2 === 1) inside += 1;
+ }
+ return (inside * 2 > dirs.length ? 1 : -1) * distance;
+ };
+}
diff --git a/api/_lib/print/manifold-kernel.js b/api/_lib/print/manifold-kernel.js
new file mode 100644
index 000000000..a0b944f1b
--- /dev/null
+++ b/api/_lib/print/manifold-kernel.js
@@ -0,0 +1,135 @@
+// Materialize's geometry kernel: one lazily-initialised manifold-3d instance.
+//
+// manifold-3d is the Manifold library compiled to WebAssembly. It is the only
+// dependency in this pipeline that owns memory outside the JS heap, so it gets
+// its own module: one instance per process, initialised on first use, with the
+// mesh conversions that every caller would otherwise re-write.
+//
+// Why a WASM kernel rather than a native binding: the API container is a
+// node-only image (see CLAUDE.md, Stack notes). A CGAL or OpenVDB binding would
+// need a compiler in the image and would break the moment the base image moved.
+// A .wasm file is just bytes the runtime already knows how to load.
+//
+// Every Manifold object holds WASM memory that the JS garbage collector cannot
+// see, so callers must delete() what they create. The helpers here return plain
+// JS soups precisely so that ownership stays short and local.
+
+let kernelPromise = null;
+
+/** The initialised manifold-3d module (Manifold, Mesh, and friends). */
+export async function getKernel() {
+ if (!kernelPromise) {
+ kernelPromise = (async () => {
+ const factory = (await import('manifold-3d')).default;
+ const wasm = await factory();
+ wasm.setup();
+ return wasm;
+ })();
+ }
+ return kernelPromise;
+}
+
+/**
+ * Wrap an indexed soup as a manifold-3d Mesh and merge vertices that sit within
+ * the kernel's tolerance of each other. `merge()` is what turns a glTF's
+ * seam-split vertices back into shared topology; without it every UV seam reads
+ * as an open boundary.
+ */
+export async function toKernelMesh(positions, indices) {
+ const { Mesh } = await getKernel();
+ const mesh = new Mesh({
+ numProp: 3,
+ vertProperties: Float32Array.from(positions),
+ triVerts: Uint32Array.from(indices),
+ });
+ mesh.merge();
+ return mesh;
+}
+
+/**
+ * Build a Manifold solid from an indexed soup, or return null when the soup is
+ * not a valid 2-manifold. Never throws: "this input is not a solid" is the
+ * normal case this whole pipeline exists to handle, not an exception.
+ */
+export async function toSolid(positions, indices) {
+ const { Manifold } = await getKernel();
+ const mesh = await toKernelMesh(positions, indices);
+ try {
+ const solid = Manifold.ofMesh(mesh);
+ if (solid.isEmpty()) {
+ solid.delete();
+ return null;
+ }
+ return solid;
+ } catch {
+ return null;
+ }
+}
+
+/** Read a Manifold solid back out as the indexed soup the exporters consume. */
+export function fromSolid(solid) {
+ const mesh = solid.getMesh();
+ const stride = mesh.numProp;
+ const vertexCount = mesh.vertProperties.length / stride;
+ const positions = new Float64Array(vertexCount * 3);
+ for (let v = 0; v < vertexCount; v += 1) {
+ positions[v * 3] = mesh.vertProperties[v * stride];
+ positions[v * 3 + 1] = mesh.vertProperties[v * stride + 1];
+ positions[v * 3 + 2] = mesh.vertProperties[v * stride + 2];
+ }
+ return { positions, indices: Uint32Array.from(mesh.triVerts) };
+}
+
+/** Axis-aligned bounds of a solid as a plain { min, max } box. */
+export function solidBounds(solid) {
+ const box = solid.boundingBox();
+ return { min: [...box.min], max: [...box.max] };
+}
+
+/**
+ * Collapse edges until the solid fits a triangle budget, by binary search on
+ * manifold's geometric tolerance. Searching on tolerance rather than driving a
+ * general-purpose decimator matters because manifold's simplify is
+ * manifoldness-preserving: the result is still a solid, which a mesh
+ * decimator's output is not guaranteed to be. A mesh that cannot reach the
+ * budget within `maxTolerance` is returned at the best reduction found rather
+ * than degraded further.
+ *
+ * Caller owns `solid`; the returned solid is a new object (or `solid` itself
+ * when no reduction was needed, flagged by `reduced: false`).
+ */
+export function simplifyToBudget(solid, budget, { maxTolerance, iterations = 12 } = {}) {
+ const before = solid.numTri();
+ if (!budget || before <= budget) return { solid, reduced: false, before, after: before, tolerance: 0 };
+ const box = solid.boundingBox();
+ const diagonal = Math.hypot(
+ box.max[0] - box.min[0],
+ box.max[1] - box.min[1],
+ box.max[2] - box.min[2],
+ );
+ let lo = 0;
+ let hi = maxTolerance ?? diagonal * 0.02;
+ let best = null;
+ let bestTolerance = 0;
+ for (let i = 0; i < iterations; i += 1) {
+ const mid = (lo + hi) / 2;
+ const candidate = solid.simplify(mid);
+ const tris = candidate.numTri();
+ if (tris <= budget) {
+ if (best) best.delete();
+ best = candidate;
+ bestTolerance = mid;
+ hi = mid;
+ } else {
+ candidate.delete();
+ lo = mid;
+ }
+ }
+ if (!best) {
+ // Budget unreachable inside the tolerance ceiling: take the strongest
+ // legal reduction rather than pretending the budget was met.
+ best = solid.simplify(hi);
+ bestTolerance = hi;
+ }
+ return { solid: best, reduced: true, before, after: best.numTri(), tolerance: bestTolerance };
+}
diff --git a/api/_lib/print/manifold.js b/api/_lib/print/manifold.js
new file mode 100644
index 000000000..82ca1caea
--- /dev/null
+++ b/api/_lib/print/manifold.js
@@ -0,0 +1,124 @@
+// The Manifold kernel, wrapped for this pipeline.
+//
+// Manifold (github.com/elalish/manifold, Apache-2.0) is the geometry kernel
+// behind manifoldCAD and OpenSCAD's fast backend: exact boolean operations on
+// solids, guaranteed manifold output, and a volume that is a real volume rather
+// than an estimate. It ships here as plain WebAssembly with no native binding,
+// which is exactly why it was chosen over a CGAL binding: the API container is
+// node-only, and a build that needs a compiler is a build that breaks.
+//
+// The kernel is instantiated once per process and reused. Instantiation is a
+// few tens of milliseconds and the module is stateless between calls, so a warm
+// Cloud Run instance pays it once.
+//
+// Memory discipline: Manifold objects live in WASM memory and are NOT
+// garbage-collected by JavaScript. Every function here that creates one either
+// deletes it before returning or hands ownership to the caller and says so in
+// its doc comment. Leaking them leaks the whole heap of a long-lived instance.
+
+let modulePromise = null;
+
+/** The Manifold toplevel (Manifold, Mesh, CrossSection, triangulate). */
+export async function getKernel() {
+ if (!modulePromise) {
+ modulePromise = (async () => {
+ const factory = (await import('manifold-3d')).default;
+ const wasm = await factory();
+ wasm.setup();
+ return wasm;
+ })();
+ }
+ return modulePromise;
+}
+
+/**
+ * Wrap an indexed triangle soup as a Manifold Mesh and merge coincident
+ * vertices. `merge()` is the kernel's own crack-closer: it links vertices that
+ * share a position but were split by a UV or normal seam, which is the single
+ * most common reason an otherwise closed AI-generated mesh reads as full of
+ * holes. The Mesh is a plain JS object; nothing needs deleting.
+ */
+export async function toKernelMesh(positions, indices) {
+ const { Mesh } = await getKernel();
+ const verts = new Float32Array(positions.length);
+ for (let i = 0; i < positions.length; i += 1) verts[i] = positions[i];
+ const mesh = new Mesh({
+ numProp: 3,
+ vertProperties: verts,
+ triVerts: indices instanceof Uint32Array ? indices : Uint32Array.from(indices),
+ });
+ const merged = mesh.merge();
+ return { mesh, merged };
+}
+
+/**
+ * Read a solid back out as an indexed soup. The caller owns the returned
+ * arrays; the Manifold is untouched.
+ */
+export function fromSolid(solid) {
+ const mesh = solid.getMesh();
+ const stride = mesh.numProp;
+ const vertexCount = mesh.vertProperties.length / stride;
+ const positions = new Float64Array(vertexCount * 3);
+ for (let v = 0; v < vertexCount; v += 1) {
+ positions[v * 3] = mesh.vertProperties[v * stride];
+ positions[v * 3 + 1] = mesh.vertProperties[v * stride + 1];
+ positions[v * 3 + 2] = mesh.vertProperties[v * stride + 2];
+ }
+ return { positions, indices: Uint32Array.from(mesh.triVerts) };
+}
+
+/**
+ * Try to read a soup as a solid. Returns the Manifold on success (the caller
+ * MUST delete it) or null when the kernel refuses the topology, which is not an
+ * error: it is the signal that the mesh needs repair first.
+ */
+export async function trySolid(positions, indices) {
+ const { Manifold } = await getKernel();
+ const { mesh, merged } = await toKernelMesh(positions, indices);
+ let solid = null;
+ try {
+ solid = Manifold.ofMesh(mesh);
+ } catch {
+ return { solid: null, merged, status: 'NotManifold' };
+ }
+ const status = solid.status();
+ if (status !== 'NoError') {
+ solid.delete();
+ return { solid: null, merged, status };
+ }
+ return { solid, merged, status };
+}
+
+/**
+ * Union a solid with itself through decompose: separating the disjoint pieces
+ * and unioning them back resolves overlapping shells and self-intersections
+ * into one clean boundary. Consumes `solid` and returns a new one the caller
+ * owns. A kernel failure returns the original rather than losing the geometry.
+ */
+export async function unionShells(solid) {
+ const { Manifold } = await getKernel();
+ let parts = [];
+ try {
+ parts = solid.decompose();
+ } catch {
+ return solid;
+ }
+ if (parts.length <= 1) {
+ for (const p of parts) p.delete();
+ return solid;
+ }
+ try {
+ const merged = Manifold.union(parts);
+ if (merged.status() !== 'NoError') {
+ merged.delete();
+ return solid;
+ }
+ solid.delete();
+ return merged;
+ } catch {
+ return solid;
+ } finally {
+ for (const p of parts) p.delete();
+ }
+}
diff --git a/api/_lib/print/mesh-io.js b/api/_lib/print/mesh-io.js
new file mode 100644
index 000000000..7669eecb2
--- /dev/null
+++ b/api/_lib/print/mesh-io.js
@@ -0,0 +1,390 @@
+// Materialize mesh loader: GLB bytes in, a flat world-space triangle soup out.
+//
+// Every other module in api/_lib/print/ works on ONE representation: indexed
+// Float64 positions in world space (meters, glTF's own unit), a Uint32 index
+// buffer, and an optional per-vertex RGB sampled from the source material. The
+// printability analyzer, the manifold repair, the STL writer and the 3MF writer
+// all consume that and nothing else, so glTF's node hierarchy, primitive
+// splits, compression codecs and texture indirection are decoded exactly once,
+// here.
+//
+// Why per-vertex color is loaded at all: full-color sandstone and binder-jet
+// printers take color per vertex, not per texture. 3MF's core spec carries a
+// colorgroup keyed off vertices, so sampling the base-color texture at each
+// vertex UV at LOAD time is what makes a colored print possible downstream. A
+// GLB with a 2K albedo becomes a mesh a color printer can actually reproduce.
+//
+// Input is bounded twice (bytes, then triangles) because the two failure modes
+// are different: a 400 MB download is a network/memory problem before anything
+// parses, and a 5M-triangle scene parses fine and then melts the repair stage.
+// Both raise a typed error naming the limit it hit, never a generic 500.
+
+import { Buffer } from 'node:buffer';
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { fetchModel, FetchModelError } from '../fetch-model.js';
+
+// Hard ceilings for a single analyze/prepare call. 100 MB covers every real
+// forge output (they land in the 2-30 MB band) plus hand-uploaded scan data;
+// 2M triangles is roughly 40x a dense forge mesh and is the point where the
+// manifold reconstruction stops being interactive.
+export const MAX_INPUT_BYTES = 100 * 1024 * 1024;
+export const MAX_TRIANGLES = 2_000_000;
+
+// glTF primitive.mode: only triangles enclose a volume. Points, lines and the
+// strip/fan modes are render aids; they are counted as skipped rather than
+// folded into geometry that money is quoted against.
+const MODE_TRIANGLES = 4;
+
+export class MeshIoError extends Error {
+ constructor(code, message, extra = {}) {
+ super(message);
+ this.name = 'MeshIoError';
+ this.code = code;
+ this.extra = extra;
+ }
+}
+
+let ioPromise = null;
+
+// One shared, fully-registered IO. Draco and meshopt are the two codecs our own
+// forge emits, so a loader that could not read them would reject exactly the
+// assets a user is most likely to want printed.
+async function getIO() {
+ if (!ioPromise) {
+ ioPromise = (async () => {
+ const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+ const dependencies = {};
+ try {
+ const draco = await import('draco3dgltf');
+ const create = draco.default ?? draco;
+ dependencies['draco3d.decoder'] = await create.createDecoderModule();
+ } catch {
+ // Only matters if the asset actually uses Draco; readBinary then
+ // throws a precise "missing dependency" the caller maps to 400.
+ }
+ try {
+ const { MeshoptDecoder } = await import('meshoptimizer');
+ await MeshoptDecoder.ready;
+ dependencies['meshopt.decoder'] = MeshoptDecoder;
+ } catch {
+ // Same reasoning as Draco above.
+ }
+ if (Object.keys(dependencies).length) io.registerDependencies(dependencies);
+ return io;
+ })();
+ }
+ return ioPromise;
+}
+
+// glTF world matrices are column-major (the spec's own convention), which is
+// also what gltf-transform's getWorldMatrix returns.
+function transformPoint(m, x, y, z) {
+ const w = m[3] * x + m[7] * y + m[11] * z + m[15] || 1;
+ return [
+ (m[0] * x + m[4] * y + m[8] * z + m[12]) / w,
+ (m[1] * x + m[5] * y + m[9] * z + m[13]) / w,
+ (m[2] * x + m[6] * y + m[10] * z + m[14]) / w,
+ ];
+}
+
+const clamp01 = (v) => (v < 0 ? 0 : v > 1 ? 1 : v);
+// glTF's default sampler wrap is REPEAT, so a UV outside [0,1] tiles.
+const wrap01 = (v) => {
+ const f = v - Math.floor(v);
+ return f < 0 ? f + 1 : f;
+};
+
+// sRGB encode a linear channel. baseColorFactor and COLOR_0 are linear per the
+// glTF spec; the base-color TEXTURE is already sRGB-encoded. 3MF and STL colors
+// are display values, so the linear inputs are encoded on the way out and the
+// texture sample is used as-is.
+function linearToSrgb(c) {
+ return c <= 0.0031308 ? c * 12.92 : 1.055 * Math.pow(c, 1 / 2.4) - 0.055;
+}
+
+// Decode one glTF texture image to raw RGBA once, memoized per Texture object
+// for the lifetime of a single load. sharp handles every image type glTF
+// allows (PNG, JPEG, WebP via KHR_texture_basisu fallbacks). A texture that
+// cannot be decoded degrades to the material's flat baseColorFactor rather
+// than failing the load: a print without color still prints.
+async function decodeTexture(texture, cache) {
+ if (!texture) return null;
+ if (cache.has(texture)) return cache.get(texture);
+ const entry = (async () => {
+ const image = texture.getImage();
+ if (!image || image.byteLength === 0) return null;
+ try {
+ const sharp = (await import('sharp')).default;
+ const { data, info } = await sharp(Buffer.from(image))
+ .ensureAlpha()
+ .raw()
+ .toBuffer({ resolveWithObject: true });
+ return { data, width: info.width, height: info.height, channels: info.channels };
+ } catch {
+ return null;
+ }
+ })();
+ cache.set(texture, entry);
+ return entry;
+}
+
+// Nearest-neighbour sample. Bilinear would buy nothing here: the consumer is a
+// printer nozzle averaging over a voxel far larger than a texel, and nearest
+// keeps the sample exactly reproducible for the determinism contract.
+function sampleTexel(img, u, v) {
+ const x = Math.min(img.width - 1, Math.floor(wrap01(u) * img.width));
+ // glTF UV origin is top-left, image row 0 is top, so no V flip is needed.
+ const y = Math.min(img.height - 1, Math.floor(wrap01(v) * img.height));
+ const i = (y * img.width + x) * img.channels;
+ return [img.data[i], img.data[i + 1], img.data[i + 2]];
+}
+
+// Resolve the base-color texture + factor for a primitive's material, following
+// KHR_materials_pbrSpecularGlossiness's diffuse channel when that is what the
+// asset used instead of metallic-roughness.
+function baseColorOf(material) {
+ if (!material) return { texture: null, factor: [1, 1, 1] };
+ const factor = material.getBaseColorFactor?.() || [1, 1, 1, 1];
+ return {
+ texture: material.getBaseColorTexture?.() || null,
+ factor: [clamp01(factor[0]), clamp01(factor[1]), clamp01(factor[2])],
+ };
+}
+
+/**
+ * Walk the default scene, bake node transforms, merge every triangle primitive
+ * into one indexed soup, and sample a per-vertex color where the source had
+ * one. Returns the single representation the rest of the print pipeline reads.
+ *
+ * @param {Uint8Array|Buffer} bytes raw .glb bytes
+ * @param {{ maxBytes?: number, maxTriangles?: number, color?: boolean }} [opts]
+ */
+export async function loadMesh(bytes, opts = {}) {
+ const maxBytes = opts.maxBytes ?? MAX_INPUT_BYTES;
+ const maxTriangles = opts.maxTriangles ?? MAX_TRIANGLES;
+ const wantColor = opts.color !== false;
+
+ if (!bytes || typeof bytes.byteLength !== 'number' || bytes.byteLength < 20) {
+ throw new MeshIoError('invalid_model', 'input is not a glTF/GLB buffer');
+ }
+ if (bytes.byteLength > maxBytes) {
+ throw new MeshIoError(
+ 'too_large',
+ `model is ${bytes.byteLength} bytes, over the ${maxBytes}-byte limit for a print job`,
+ { limitBytes: maxBytes, actualBytes: bytes.byteLength },
+ );
+ }
+
+ const input = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
+ const io = await getIO();
+ let doc;
+ try {
+ doc = await io.readBinary(input);
+ } catch (err) {
+ throw new MeshIoError('invalid_model', `not a valid GLB: ${err?.message || err}`);
+ }
+
+ const root = doc.getRoot();
+ const scene = root.getDefaultScene() ?? root.listScenes()[0] ?? null;
+ const roots = scene ? scene.listChildren() : root.listNodes();
+
+ const positions = [];
+ const indices = [];
+ const colors = wantColor ? [] : null;
+ const textureCache = new Map();
+ let skippedPrimitives = 0;
+ let texturedPrimitives = 0;
+ let triangles = 0;
+
+ // Node hierarchies can be re-entered through instancing; `seen` keeps a
+ // shared subtree from being baked twice into the same soup.
+ const seen = new Set();
+ const stack = [...roots].reverse();
+ const visited = [];
+ while (stack.length) {
+ const node = stack.pop();
+ if (!node || seen.has(node)) continue;
+ seen.add(node);
+ visited.push(node);
+ const children = node.listChildren();
+ for (let i = children.length - 1; i >= 0; i -= 1) stack.push(children[i]);
+ }
+
+ for (const node of visited) {
+ const mesh = node.getMesh();
+ if (!mesh) continue;
+ const matrix = node.getWorldMatrix();
+ for (const prim of mesh.listPrimitives()) {
+ if (prim.getMode() !== MODE_TRIANGLES) {
+ skippedPrimitives += 1;
+ continue;
+ }
+ const position = prim.getAttribute('POSITION');
+ if (!position) {
+ skippedPrimitives += 1;
+ continue;
+ }
+ const count = position.getCount();
+ const index = prim.getIndices();
+ const primTris = index ? Math.floor(index.getCount() / 3) : Math.floor(count / 3);
+ triangles += primTris;
+ if (triangles > maxTriangles) {
+ throw new MeshIoError(
+ 'too_complex',
+ `model exceeds the ${maxTriangles}-triangle limit for a print job; decimate it first (POST /api/3d/inspect suggests how)`,
+ { limitTriangles: maxTriangles },
+ );
+ }
+
+ const base = positions.length / 3;
+ const p = [0, 0, 0];
+ for (let i = 0; i < count; i += 1) {
+ position.getElement(i, p);
+ const [x, y, z] = transformPoint(matrix, p[0], p[1], p[2]);
+ positions.push(x, y, z);
+ }
+ if (index) {
+ const n = index.getCount();
+ for (let i = 0; i + 2 < n; i += 3) {
+ indices.push(base + index.getScalar(i), base + index.getScalar(i + 1), base + index.getScalar(i + 2));
+ }
+ } else {
+ for (let i = 0; i + 2 < count; i += 3) indices.push(base + i, base + i + 1, base + i + 2);
+ }
+
+ if (!colors) continue;
+ const { texture, factor } = baseColorOf(prim.getMaterial());
+ const uv = prim.getAttribute('TEXCOORD_0');
+ const vertexColor = prim.getAttribute('COLOR_0');
+ const img = texture && uv ? await decodeTexture(texture, textureCache) : null;
+ if (img) texturedPrimitives += 1;
+ const uvEl = [0, 0];
+ const cEl = [1, 1, 1, 1];
+ for (let i = 0; i < count; i += 1) {
+ let r;
+ let g;
+ let b;
+ if (img) {
+ uv.getElement(i, uvEl);
+ const [tr, tg, tb] = sampleTexel(img, uvEl[0], uvEl[1]);
+ // Texture is sRGB, factor is linear: encode the factor before
+ // modulating so the product stays in one color space.
+ r = (tr / 255) * linearToSrgb(factor[0]);
+ g = (tg / 255) * linearToSrgb(factor[1]);
+ b = (tb / 255) * linearToSrgb(factor[2]);
+ } else {
+ r = linearToSrgb(factor[0]);
+ g = linearToSrgb(factor[1]);
+ b = linearToSrgb(factor[2]);
+ }
+ if (vertexColor) {
+ vertexColor.getElement(i, cEl);
+ r *= linearToSrgb(clamp01(cEl[0]));
+ g *= linearToSrgb(clamp01(cEl[1]));
+ b *= linearToSrgb(clamp01(cEl[2]));
+ }
+ colors.push(
+ Math.round(clamp01(r) * 255),
+ Math.round(clamp01(g) * 255),
+ Math.round(clamp01(b) * 255),
+ );
+ }
+ }
+ }
+
+ if (indices.length < 3) {
+ throw new MeshIoError('no_geometry', 'model contains no triangle geometry to print');
+ }
+
+ return {
+ positions: Float64Array.from(positions),
+ indices: Uint32Array.from(indices),
+ colors: colors ? Uint8Array.from(colors) : null,
+ vertexCount: positions.length / 3,
+ triangleCount: indices.length / 3,
+ skippedPrimitives,
+ hasTextures: root.listTextures().length > 0,
+ colorSource: texturedPrimitives > 0 ? 'texture' : colors ? 'material' : 'none',
+ sizeBytes: input.byteLength,
+ materials: root.listMaterials().length,
+ document: doc,
+ };
+}
+
+/**
+ * Fetch a GLB by URL through the SSRF-hardened, size-capped fetcher and load
+ * it. Fetch failures are re-thrown as MeshIoError so a caller has exactly one
+ * error type to map onto HTTP.
+ */
+export async function loadMeshFromUrl(url, opts = {}) {
+ const maxBytes = opts.maxBytes ?? MAX_INPUT_BYTES;
+ let fetched;
+ try {
+ fetched = await fetchModel(url, { maxBytes, timeoutMs: opts.timeoutMs ?? 30_000 });
+ } catch (err) {
+ if (err instanceof FetchModelError) {
+ if (err.code === 'file_too_large') {
+ throw new MeshIoError('too_large', `model exceeds the ${maxBytes}-byte limit for a print job`, {
+ limitBytes: maxBytes,
+ });
+ }
+ if (['invalid_url', 'scheme_not_allowed', 'private_address', 'host_pin_mismatch'].includes(err.code)) {
+ throw new MeshIoError('invalid_url', err.message);
+ }
+ throw new MeshIoError('fetch_failed', `could not fetch model: ${err.message}`);
+ }
+ throw new MeshIoError('fetch_failed', `could not fetch model: ${err?.message || err}`);
+ }
+ const mesh = await loadMesh(fetched.bytes, opts);
+ return { ...mesh, sourceUrl: fetched.url, bytes: fetched.bytes };
+}
+
+/** Axis-aligned bounds of an indexed soup, in the mesh's own units (meters). */
+export function boundsOf(positions) {
+ const min = [Infinity, Infinity, Infinity];
+ const max = [-Infinity, -Infinity, -Infinity];
+ for (let i = 0; i < positions.length; i += 3) {
+ for (let a = 0; a < 3; a += 1) {
+ const v = positions[i + a];
+ if (v < min[a]) min[a] = v;
+ if (v > max[a]) max[a] = v;
+ }
+ }
+ if (!Number.isFinite(min[0])) return null;
+ const size = [max[0] - min[0], max[1] - min[1], max[2] - min[2]];
+ return {
+ min,
+ max,
+ size,
+ center: [(min[0] + max[0]) / 2, (min[1] + max[1]) / 2, (min[2] + max[2]) / 2],
+ diagonal: Math.hypot(size[0], size[1], size[2]),
+ longest: Math.max(size[0], size[1], size[2]),
+ };
+}
+
+/**
+ * Weld vertices by quantized position. Analysis and manifold reconstruction
+ * both need topology, and UV/normal seams split vertices that are
+ * geometrically identical. Counting those seams as boundary edges would
+ * report a perfectly closed model as full of holes.
+ */
+export function weldPositions(positions, indices, tolerance) {
+ const inv = 1 / tolerance;
+ const map = new Map();
+ const remap = new Uint32Array(positions.length / 3);
+ const unique = [];
+ for (let i = 0, v = 0; i < positions.length; i += 3, v += 1) {
+ const key = `${Math.round(positions[i] * inv)},${Math.round(positions[i + 1] * inv)},${Math.round(positions[i + 2] * inv)}`;
+ let id = map.get(key);
+ if (id === undefined) {
+ id = unique.length / 3;
+ map.set(key, id);
+ unique.push(positions[i], positions[i + 1], positions[i + 2]);
+ }
+ remap[v] = id;
+ }
+ const welded = new Uint32Array(indices.length);
+ for (let i = 0; i < indices.length; i += 1) welded[i] = remap[indices[i]];
+ return { positions: Float64Array.from(unique), indices: welded, remap };
+}
diff --git a/api/_lib/print/ops-notify.js b/api/_lib/print/ops-notify.js
new file mode 100644
index 000000000..4c0fb242f
--- /dev/null
+++ b/api/_lib/print/ops-notify.js
@@ -0,0 +1,129 @@
+// @ts-check
+// The operator channel for Materialize fulfillment.
+//
+// The manual lane is a real print operation: a human takes a job off a queue,
+// runs it through a bureau, and reports back. That only works if the human
+// learns a job exists within minutes of it being paid for, so this module is
+// part of the fulfillment path, not decoration around it.
+//
+// Three sinks, deliberately layered so no single missing credential silences
+// the queue:
+//
+// 1. Telegram, to a PRIVATE ops chat (TELEGRAM_PRINT_OPS_CHAT_ID, falling
+// back to the existing TELEGRAM_ALERTS_CHAT_ID). Same bot token and the
+// same retrying sender the ops alerts already use. Never the public
+// changelog channel: these messages carry order ids.
+// 2. The in-app bell, for every platform admin. This is what makes the
+// channel work on a deployment that has no dedicated ops chat id yet.
+// 3. ops_alerts, via sendOpsAlert, but only for the things an operator must
+// act on (a stall). That table is the durable record when both of the
+// above are unconfigured.
+//
+// PII discipline: an ops message carries the order id, the material, and the
+// destination COUNTRY. Never the recipient's name, street address, or phone.
+// Those exist only inside the console, behind the operator gate.
+
+import { sql } from './../db.js';
+import { fetchUpstream } from './../upstream-fetch.js';
+import { publishUserEvent } from './../feed.js';
+import { sendOpsAlert } from './../alerts.js';
+import { databaseConfigured } from './../env.js';
+
+const CONSOLE_PATH = '/materialize/ops';
+
+/** The private ops chat, or null when this deployment has none wired. */
+function telegramConfig() {
+ const token = process.env.TELEGRAM_BOT_TOKEN;
+ const chatId = process.env.TELEGRAM_PRINT_OPS_CHAT_ID || process.env.TELEGRAM_ALERTS_CHAT_ID;
+ if (!token || !chatId) return null;
+ return { token, chatId };
+}
+
+/** True when an operator would actually see a Telegram message right now. */
+export function operatorChannelConfigured() {
+ return telegramConfig() !== null;
+}
+
+/**
+ * @param {{ token: string, chatId: string }} cfg
+ * @param {string} text
+ */
+function post(cfg, text) {
+ return fetchUpstream(
+ `https://api.telegram.org/bot${cfg.token}/sendMessage`,
+ {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ chat_id: cfg.chatId,
+ text: text.slice(0, 4000),
+ disable_web_page_preview: true,
+ }),
+ keepalive: true,
+ },
+ { name: 'telegram:print-ops', timeoutMs: 5_000, attempts: 2 },
+ ).catch((err) => {
+ console.warn(`[print-ops] telegram delivery failed after retries: ${err?.message || err}`);
+ });
+}
+
+/** Every platform admin, for the in-app bell fan-out. */
+async function adminUserIds() {
+ if (!databaseConfigured()) return [];
+ try {
+ const rows = await sql`select id from users where is_admin = true limit 50`;
+ return rows.map((r) => r.id);
+ } catch (err) {
+ console.warn(`[print-ops] admin lookup failed: ${err?.message || err}`);
+ return [];
+ }
+}
+
+/**
+ * Notify the operators. Fire-and-forget by contract: a fulfillment transition
+ * must never fail because a chat was unreachable.
+ *
+ * @param {object} input
+ * @param {string} input.title one line, e.g. "New print job ready to submit"
+ * @param {string[]} [input.lines] body lines, already PII-scrubbed by the caller
+ * @param {string} [input.orderId]
+ * @param {boolean} [input.alert] also record to ops_alerts (use for stalls)
+ */
+export async function notifyOperators({ title, lines = [], orderId = '', alert = false }) {
+ const link = orderId ? `https://three.ws${CONSOLE_PATH}?order=${orderId}` : `https://three.ws${CONSOLE_PATH}`;
+ const body = [...lines, link].filter(Boolean).join('\n');
+
+ const cfg = telegramConfig();
+ if (cfg) post(cfg, `🖨 ${title}\n${body}`);
+
+ for (const userId of await adminUserIds()) {
+ publishUserEvent(userId, {
+ type: 'print',
+ status: 'operator',
+ order_id: orderId || null,
+ message: title,
+ link: orderId ? `${CONSOLE_PATH}?order=${orderId}` : CONSOLE_PATH,
+ });
+ }
+
+ if (alert) {
+ // A per-order signature: the alert dedup exists to coalesce a storm of the
+ // same fault, and two different stalled orders are not the same fault.
+ await sendOpsAlert(title, body, { signature: `print-ops:${orderId || title}`, severity: 'warn' }).catch(() => {});
+ }
+}
+
+/**
+ * The message a newly submitted manual job produces. Kept here rather than in
+ * the adapter so every ops line has one shape and one PII review surface.
+ * @param {object} order
+ */
+export function jobSummaryLines(order) {
+ const qty = Number(order?.quantity) || 1;
+ const country = order?.shipping?.country || 'unknown';
+ const height = order?.target_height_mm ? `${order.target_height_mm} mm tall` : 'height per quote';
+ return [
+ `Order ${String(order?.id || '').slice(0, 8)} · ${order?.material_id || 'material tbd'} · ${qty}x · ${height}`,
+ `Ship to ${country} · ${Number(order?.price_usdc || 0).toFixed(2)} USDC`,
+ ];
+}
diff --git a/api/_lib/print/repair.js b/api/_lib/print/repair.js
new file mode 100644
index 000000000..faab644d2
--- /dev/null
+++ b/api/_lib/print/repair.js
@@ -0,0 +1,318 @@
+// Turning a generated mesh into a solid a printer will accept.
+//
+// The order of operations is the whole design. Cheap topology first, because it
+// fixes the failures forge output actually has (UV seams read as holes, mirrored
+// duplicate shells, patches wound backwards, an open bottom where the generator
+// never closed the base), and it preserves the artist's triangles exactly. Only
+// when that is not enough does the voxel reconstruction run, which always
+// produces a manifold but resamples the surface and therefore softens detail.
+//
+// Every stage records before/after metrics. A repair the buyer cannot see is a
+// repair the buyer cannot trust, and the /materialize page renders these numbers
+// as the "what changed" list next to the model.
+
+import Module from 'manifold-3d';
+
+import { boundsOf, weldPositions } from './mesh-io.js';
+import {
+ boundaryLoops,
+ connectedComponents,
+ dropDegenerateTriangles,
+ edgeCensus,
+ orientConsistently,
+ signedVolume,
+ surfaceArea,
+} from './topology.js';
+import { buildSignedDistance, extractLevelSet } from './voxel-sdf.js';
+
+// Weld tolerance as a fraction of the bounding-box diagonal. Loose enough to
+// merge the duplicated vertices a UV seam creates, tight enough to leave two
+// genuinely distinct surfaces a hair apart alone.
+const WELD_FRACTION = 1e-5;
+
+let wasmPromise = null;
+
+/**
+ * The Manifold WASM module, initialized once per process. It is plain
+ * WebAssembly with no native binding, which is why it runs in the API container
+ * at all; the same single-instance pattern the Draco decoders use.
+ */
+export async function getManifold() {
+ if (!wasmPromise) {
+ wasmPromise = (async () => {
+ const wasm = await Module();
+ wasm.setup();
+ return wasm;
+ })().catch((err) => {
+ wasmPromise = null;
+ throw err;
+ });
+ }
+ return wasmPromise;
+}
+
+/** Flat arrays out of a Manifold solid, in the representation everything else here speaks. */
+export function solidToArrays(solid) {
+ const mesh = solid.getMesh();
+ const stride = mesh.numProp;
+ const count = mesh.vertProperties.length / stride;
+ const positions = new Float64Array(count * 3);
+ for (let i = 0; i < count; i += 1) {
+ positions[i * 3] = mesh.vertProperties[i * stride];
+ positions[i * 3 + 1] = mesh.vertProperties[i * stride + 1];
+ positions[i * 3 + 2] = mesh.vertProperties[i * stride + 2];
+ }
+ return { positions, indices: Uint32Array.from(mesh.triVerts) };
+}
+
+/**
+ * Hand a triangle soup to Manifold. Returns null rather than throwing when the
+ * soup is not a closed, non-self-intersecting 2-manifold, because "not yet a
+ * solid" is the normal case this pipeline exists to fix, not an error.
+ */
+export function toSolid(wasm, positions, indices) {
+ try {
+ const mesh = new wasm.Mesh({
+ numProp: 3,
+ vertProperties: Float32Array.from(positions),
+ triVerts: Uint32Array.from(indices),
+ });
+ const solid = wasm.Manifold.ofMesh(mesh);
+ if (solid.status() !== 'NoError' || solid.isEmpty()) return null;
+ return solid;
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Fan-fill every boundary loop. Each hole gets one new vertex at the loop's
+ * centroid and a triangle per rim edge, wound opposite to the rim so the patch
+ * agrees with the surface it closes.
+ *
+ * A centroid fan is the right tool here specifically because these holes are
+ * generator artifacts (a flat open base, a missing cap) rather than designed
+ * openings; it is stable, needs no projection plane, and never produces a
+ * self-intersecting patch on a convex rim.
+ */
+export function fillBoundaryLoops(positions, indices) {
+ const loops = boundaryLoops(indices);
+ if (!loops.length) return { positions, indices, filled: 0, addedTriangles: 0 };
+ const pos = Array.from(positions);
+ const tris = Array.from(indices);
+ let addedTriangles = 0;
+ for (const loop of loops) {
+ if (loop.length === 3) {
+ tris.push(loop[2], loop[1], loop[0]);
+ addedTriangles += 1;
+ continue;
+ }
+ let cx = 0, cy = 0, cz = 0;
+ for (const v of loop) {
+ cx += positions[v * 3];
+ cy += positions[v * 3 + 1];
+ cz += positions[v * 3 + 2];
+ }
+ const center = pos.length / 3;
+ pos.push(cx / loop.length, cy / loop.length, cz / loop.length);
+ for (let i = 0; i < loop.length; i += 1) {
+ const u = loop[i];
+ const v = loop[(i + 1) % loop.length];
+ tris.push(v, u, center);
+ addedTriangles += 1;
+ }
+ }
+ return {
+ positions: Float64Array.from(pos),
+ indices: Uint32Array.from(tris),
+ filled: loops.length,
+ addedTriangles,
+ };
+}
+
+/**
+ * The cheap repair: weld, drop what cannot hold volume, agree on a winding,
+ * close the holes, and make the whole thing point outward. Pure topology, no
+ * resampling, so the surface a buyer approved is the surface that prints.
+ */
+export function cleanTopology(mesh, opts = {}) {
+ const bounds = boundsOf(mesh.positions);
+ const tolerance = opts.weldTolerance ?? Math.max((bounds?.diagonal ?? 1) * WELD_FRACTION, Number.EPSILON);
+
+ const welded = weldPositions(mesh.positions, mesh.indices, tolerance);
+ const cleaned = dropDegenerateTriangles(welded.positions, welded.indices, {
+ minArea: (tolerance * tolerance) / 2,
+ });
+ const oriented = orientConsistently(cleaned.indices);
+ const before = edgeCensus(oriented.indices);
+ const filled = fillBoundaryLoops(welded.positions, oriented.indices);
+ const after = edgeCensus(filled.indices);
+
+ // Winding is only consistent per component after orientConsistently; a
+ // negative total signed volume means the biggest shell points inward.
+ let indices = filled.indices;
+ let volume = signedVolume(filled.positions, indices);
+ let flippedAll = false;
+ if (volume < 0) {
+ const flipped = Uint32Array.from(indices);
+ for (let i = 0; i + 2 < flipped.length; i += 3) {
+ const b = flipped[i + 1];
+ flipped[i + 1] = flipped[i + 2];
+ flipped[i + 2] = b;
+ }
+ indices = flipped;
+ volume = -volume;
+ flippedAll = true;
+ }
+
+ return {
+ positions: filled.positions,
+ indices,
+ metrics: {
+ weldTolerance: tolerance,
+ mergedVertices: mesh.positions.length / 3 - welded.positions.length / 3,
+ degenerateRemoved: cleaned.degenerate,
+ duplicateRemoved: cleaned.duplicate,
+ trianglesFlipped: oriented.flipped,
+ shellReversed: flippedAll,
+ holesFilled: filled.filled,
+ patchTriangles: filled.addedTriangles,
+ openEdgesBefore: before.open,
+ openEdgesAfter: after.open,
+ nonManifoldEdgesAfter: after.nonManifold,
+ signedVolume: volume,
+ },
+ };
+}
+
+/**
+ * Uniform scale about the mesh's own centre, then a translation that puts the
+ * base on z=0 of nothing in particular; callers that need a print bed origin
+ * do that in the exporter, where the up-axis convention belongs.
+ */
+export function scaleMesh(positions, factor) {
+ const out = new Float64Array(positions.length);
+ for (let i = 0; i < positions.length; i += 1) out[i] = positions[i] * factor;
+ return out;
+}
+
+/**
+ * Full repair. Returns a solid whenever one can be produced, plus the metrics
+ * describing how it was reached and which path ran.
+ *
+ * `strategy` is reported, never guessed at by the caller:
+ * 'already-solid' the input was already a closed manifold
+ * 'topology' welding, hole filling and re-winding were enough
+ * 'reconstructed' the voxel level set had to rebuild the surface
+ */
+export async function repairMesh(mesh, opts = {}) {
+ const wasm = opts.wasm || (await getManifold());
+ const started = Date.now();
+ const cleaned = cleanTopology(mesh, opts);
+
+ let solid = toSolid(wasm, cleaned.positions, cleaned.indices);
+ let strategy = solid ? (cleaned.metrics.holesFilled === 0 && cleaned.metrics.degenerateRemoved === 0 ? 'already-solid' : 'topology') : null;
+ let reconstruction = null;
+
+ if (!solid) {
+ // Topology could not save it: overlapping shells, edges shared by three
+ // faces, or holes whose rims do not close. Resample instead. This always
+ // produces a printable solid, at the cost of the original triangulation.
+ const field = buildSignedDistance(cleaned.positions, cleaned.indices, {
+ maxCells: opts.maxGridCells,
+ });
+ const extracted = extractLevelSet(wasm, field, { maxSamples: opts.maxSamples });
+ if (extracted.solid.isEmpty()) {
+ throw new Error('mesh could not be reconstructed into a printable solid');
+ }
+ solid = extracted.solid;
+ strategy = 'reconstructed';
+ reconstruction = { gridDims: field.dims, edgeLength: extracted.edgeLength };
+ }
+
+ const arrays = solidToArrays(solid);
+ const components = connectedComponents(arrays.indices);
+ return {
+ wasm,
+ solid,
+ positions: arrays.positions,
+ indices: arrays.indices,
+ strategy,
+ metrics: {
+ ...cleaned.metrics,
+ strategy,
+ reconstruction,
+ trianglesBefore: mesh.indices.length / 3,
+ trianglesAfter: arrays.indices.length / 3,
+ shells: components.count,
+ volume: solid.volume(),
+ surfaceArea: solid.surfaceArea(),
+ genus: solid.genus(),
+ elapsedMs: Date.now() - started,
+ },
+ };
+}
+
+/**
+ * Hollow a solid to a wall thickness, with drain holes.
+ *
+ * Resin is sold by volume, so a hollow print of a 10 cm figure can cost a third
+ * of the solid one. The erosion is a level-set offset of the solid's own
+ * distance field; the two drain holes are mandatory, not decorative, because a
+ * sealed resin shell traps uncured liquid and can burst under the vat's suction.
+ *
+ * Returns `{ solid, hollowed: false, reason }` rather than throwing when the
+ * geometry cannot take it: a thin ornament with no interior to remove is
+ * printed solid, and the buyer is quoted for a solid.
+ */
+export function hollowSolid(wasm, solid, { wallThickness, drainRadius, maxSamples } = {}) {
+ if (!(wallThickness > 0)) return { solid, hollowed: false, reason: 'no-wall-thickness' };
+ const arrays = solidToArrays(solid);
+ const bounds = boundsOf(arrays.positions);
+ if (!bounds) return { solid, hollowed: false, reason: 'empty' };
+ // Nothing to gain when the wall is most of the object.
+ if (wallThickness * 6 > bounds.longest) {
+ return { solid, hollowed: false, reason: 'too-small-to-hollow' };
+ }
+
+ const field = buildSignedDistance(arrays.positions, arrays.indices);
+ const eroded = extractLevelSet(wasm, field, { level: wallThickness, maxSamples });
+ if (eroded.solid.isEmpty()) {
+ return { solid, hollowed: false, reason: 'no-interior-at-this-wall-thickness' };
+ }
+
+ const shell = solid.subtract(eroded.solid);
+ if (shell.isEmpty() || shell.status() !== 'NoError') {
+ return { solid, hollowed: false, reason: 'shell-subtraction-failed' };
+ }
+
+ // Two drain holes on the lowest face, offset from each other so the resin has
+ // somewhere to leave and air somewhere to enter.
+ const r = drainRadius ?? Math.max(wallThickness * 1.5, bounds.longest * 0.012);
+ const depth = bounds.size[1] * 0.5;
+ const punch = (x, z) =>
+ wasm.Manifold.cylinder(depth, r, r, 24, true).translate([
+ bounds.center[0] + x,
+ bounds.min[1] + depth * 0.25,
+ bounds.center[2] + z,
+ ]);
+ const offset = Math.max(r * 2.5, bounds.longest * 0.05);
+ const drained = shell.subtract(punch(-offset, 0)).subtract(punch(offset, 0));
+ const finalSolid = drained.isEmpty() || drained.status() !== 'NoError' ? shell : drained;
+
+ return {
+ solid: finalSolid,
+ hollowed: true,
+ reason: null,
+ metrics: {
+ solidVolume: solid.volume(),
+ hollowVolume: finalSolid.volume(),
+ wallThickness,
+ drainHoles: finalSolid === shell ? 0 : 2,
+ drainRadius: r,
+ },
+ };
+}
+
+/** Analytic helpers the quote engine and the report share. */
+export const geometry = { boundsOf, signedVolume, surfaceArea };
diff --git a/api/_lib/print/sampling.js b/api/_lib/print/sampling.js
new file mode 100644
index 000000000..ac653cb0a
--- /dev/null
+++ b/api/_lib/print/sampling.js
@@ -0,0 +1,304 @@
+// Geometric sampling over an accelerated mesh: wall thickness, self-crossings,
+// and the signed distance field the reconstruction falls back on.
+//
+// All three questions are "what else is near this point", which is exactly what
+// a BVH answers, so one tree built from the welded soup serves all of them.
+// three-mesh-bvh is the accelerator; three's BufferGeometry is only the
+// container it wants, and no renderer, scene or material is ever constructed.
+//
+// Determinism is a contract of the printability report: the same bytes must
+// produce the same numbers, so every sample position comes from a seeded
+// generator with a fixed stream order, never from Math.random.
+
+import { BufferGeometry, BufferAttribute, Vector3, Ray, FrontSide } from 'three';
+import { MeshBVH } from 'three-mesh-bvh';
+
+// A 32-bit xorshift. Small, fast, and reproducible across engines, which is
+// what the determinism contract needs; the statistical quality demanded of it
+// (spread points over a surface) is far below what it delivers.
+export function seededRandom(seed = 0x9e3779b9) {
+ let state = seed >>> 0 || 1;
+ return () => {
+ state ^= state << 13;
+ state >>>= 0;
+ state ^= state >>> 17;
+ state ^= state << 5;
+ state >>>= 0;
+ return state / 4294967296;
+ };
+}
+
+/** Wrap an indexed soup in the BufferGeometry + BVH that the samplers need. */
+export function buildBvh(positions, indices) {
+ const geometry = new BufferGeometry();
+ geometry.setAttribute('position', new BufferAttribute(Float32Array.from(positions), 3));
+ geometry.setIndex(new BufferAttribute(Uint32Array.from(indices), 1));
+ return { geometry, bvh: new MeshBVH(geometry) };
+}
+
+function triangleNormal(positions, a, b, c, out) {
+ const ax = positions[a * 3];
+ const ay = positions[a * 3 + 1];
+ const az = positions[a * 3 + 2];
+ const ux = positions[b * 3] - ax;
+ const uy = positions[b * 3 + 1] - ay;
+ const uz = positions[b * 3 + 2] - az;
+ const vx = positions[c * 3] - ax;
+ const vy = positions[c * 3 + 1] - ay;
+ const vz = positions[c * 3 + 2] - az;
+ out.set(uy * vz - uz * vy, uz * vx - ux * vz, ux * vy - uy * vx);
+ const len = out.length();
+ if (len > 0) out.multiplyScalar(1 / len);
+ return len;
+}
+
+/**
+ * Minimum wall thickness, sampled by casting each sample point's inward normal
+ * back into the solid and measuring the distance to the first surface it hits.
+ *
+ * This is the metric that decides whether a print survives handling. A cape, a
+ * sword blade or a hair strand on a generated character is routinely 0.2 mm at
+ * the size a buyer wants, which snaps in the wash tank; knowing the thinnest
+ * wall as a FRACTION of the model's height is what lets the quote engine say
+ * "print this at 140 mm or taller" instead of shipping a broken object.
+ *
+ * Sampling is area-weighted (a big flat face is not over-sampled relative to a
+ * thin fin) via a cumulative-area table with a seeded uniform draw, and the
+ * result carries the sample count so the report can state its own resolution.
+ * Percentiles are reported alongside the minimum because a single 0.05 mm
+ * spike on a stray triangle should not condemn an otherwise printable model:
+ * `min` is the worst point, `p01` is the thinness that actually characterizes
+ * the mesh.
+ */
+export function sampleWallThickness(positions, indices, { samples = 2000, seed = 0x5eed1234 } = {}) {
+ const triCount = indices.length / 3;
+ if (triCount === 0) return null;
+
+ const { bvh } = buildBvh(positions, indices);
+ const areas = new Float64Array(triCount);
+ let totalArea = 0;
+ const normal = new Vector3();
+ for (let t = 0; t < triCount; t += 1) {
+ const len = triangleNormal(positions, indices[t * 3], indices[t * 3 + 1], indices[t * 3 + 2], normal);
+ areas[t] = len / 2;
+ totalArea += areas[t];
+ }
+ if (totalArea <= 0) return null;
+ const cumulative = new Float64Array(triCount);
+ let running = 0;
+ for (let t = 0; t < triCount; t += 1) {
+ running += areas[t];
+ cumulative[t] = running;
+ }
+
+ const random = seededRandom(seed);
+ const ray = new Ray();
+ const origin = new Vector3();
+ const thicknesses = [];
+ // Nudge the ray origin off the surface so it cannot re-hit its own face.
+ // Scaled to the model, not absolute, so it holds at any authoring unit.
+ const epsilon = Math.max(1e-9, Math.sqrt(totalArea) * 1e-6);
+ const wanted = Math.min(samples, triCount * 8);
+
+ for (let i = 0; i < wanted; i += 1) {
+ const pick = random() * totalArea;
+ let lo = 0;
+ let hi = triCount - 1;
+ while (lo < hi) {
+ const mid = (lo + hi) >> 1;
+ if (cumulative[mid] < pick) lo = mid + 1;
+ else hi = mid;
+ }
+ const t = lo;
+ let u = random();
+ let v = random();
+ if (u + v > 1) {
+ u = 1 - u;
+ v = 1 - v;
+ }
+ const a = indices[t * 3];
+ const b = indices[t * 3 + 1];
+ const c = indices[t * 3 + 2];
+ if (triangleNormal(positions, a, b, c, normal) <= 0) continue;
+ const w = 1 - u - v;
+ origin.set(
+ positions[a * 3] * w + positions[b * 3] * u + positions[c * 3] * v,
+ positions[a * 3 + 1] * w + positions[b * 3 + 1] * u + positions[c * 3 + 1] * v,
+ positions[a * 3 + 2] * w + positions[b * 3 + 2] * u + positions[c * 3 + 2] * v,
+ );
+ ray.direction.copy(normal).multiplyScalar(-1);
+ ray.origin.copy(origin).addScaledVector(ray.direction, epsilon);
+ const hit = bvh.raycastFirst(ray, FrontSide);
+ if (!hit) continue;
+ const thickness = hit.distance + epsilon;
+ if (thickness > 0 && Number.isFinite(thickness)) thicknesses.push(thickness);
+ }
+
+ if (thicknesses.length === 0) return { samples: wanted, hits: 0, min: null, p01: null, median: null };
+ thicknesses.sort((a, b) => a - b);
+ const at = (q) => thicknesses[Math.min(thicknesses.length - 1, Math.floor(q * thicknesses.length))];
+ return {
+ samples: wanted,
+ hits: thicknesses.length,
+ min: thicknesses[0],
+ p01: at(0.01),
+ median: at(0.5),
+ };
+}
+
+// Moller's triangle-triangle overlap test, interval form. Returns false for the
+// coplanar case: two coplanar triangles that merely share an edge or a vertex
+// are normal topology, and treating every such pair as a defect would report a
+// clean mesh as thousands of intersections.
+function trianglesIntersect(p, ia, ib) {
+ const v = (i, k) => [p[i * 3], p[i * 3 + 1], p[i * 3 + 2]][k];
+ const sub = (a, b) => [v(a, 0) - v(b, 0), v(a, 1) - v(b, 1), v(a, 2) - v(b, 2)];
+ const cross = (a, b) => [
+ a[1] * b[2] - a[2] * b[1],
+ a[2] * b[0] - a[0] * b[2],
+ a[0] * b[1] - a[1] * b[0],
+ ];
+ const dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
+
+ const n2 = cross(sub(ib[1], ib[0]), sub(ib[2], ib[0]));
+ const d2 = -dot(n2, [v(ib[0], 0), v(ib[0], 1), v(ib[0], 2)]);
+ const dist1 = ia.map((i) => dot(n2, [v(i, 0), v(i, 1), v(i, 2)]) + d2);
+ const scale = Math.max(Math.abs(n2[0]), Math.abs(n2[1]), Math.abs(n2[2])) || 1;
+ const eps = scale * 1e-12;
+ if (dist1.every((d) => d > eps) || dist1.every((d) => d < -eps)) return false;
+ if (dist1.every((d) => Math.abs(d) <= eps)) return false;
+
+ const n1 = cross(sub(ia[1], ia[0]), sub(ia[2], ia[0]));
+ const d1 = -dot(n1, [v(ia[0], 0), v(ia[0], 1), v(ia[0], 2)]);
+ const dist2 = ib.map((i) => dot(n1, [v(i, 0), v(i, 1), v(i, 2)]) + d1);
+ const scale1 = Math.max(Math.abs(n1[0]), Math.abs(n1[1]), Math.abs(n1[2])) || 1;
+ const eps1 = scale1 * 1e-12;
+ if (dist2.every((d) => d > eps1) || dist2.every((d) => d < -eps1)) return false;
+
+ // Project onto the intersection line's dominant axis and compare intervals.
+ const dir = cross(n1, n2);
+ let axis = 0;
+ let best = Math.abs(dir[0]);
+ if (Math.abs(dir[1]) > best) {
+ axis = 1;
+ best = Math.abs(dir[1]);
+ }
+ if (Math.abs(dir[2]) > best) axis = 2;
+
+ const interval = (tri, dists) => {
+ // The lone vertex on its own side of the other plane bridges to each of
+ // the other two, giving the segment where this triangle crosses the line.
+ let lone = 0;
+ for (let i = 0; i < 3; i += 1) {
+ const others = [0, 1, 2].filter((k) => k !== i);
+ if (dists[i] * dists[others[0]] <= 0 && dists[i] * dists[others[1]] <= 0) lone = i;
+ }
+ const o1 = (lone + 1) % 3;
+ const o2 = (lone + 2) % 3;
+ const proj = (i) => v(tri[i], axis);
+ const cut = (i) => proj(lone) + (proj(i) - proj(lone)) * (dists[lone] / (dists[lone] - dists[i]));
+ const t1 = dists[lone] === dists[o1] ? proj(lone) : cut(o1);
+ const t2 = dists[lone] === dists[o2] ? proj(lone) : cut(o2);
+ return t1 <= t2 ? [t1, t2] : [t2, t1];
+ };
+
+ const [aMin, aMax] = interval(ia, dist1);
+ const [bMin, bMax] = interval(ib, dist2);
+ return aMax >= bMin && bMax >= aMin;
+}
+
+/**
+ * Count pairs of triangles that pass through each other. Faces sharing a vertex
+ * are skipped: they touch by construction, and a shared-vertex pair is never
+ * the defect a slicer chokes on.
+ *
+ * Bounded on purpose. A pathological mesh can have millions of crossing pairs,
+ * and the caller needs a usable signal in bounded time, not an exact census, so
+ * the sweep stops at `maxPairs` findings or `budgetMs` and says which happened.
+ */
+export function countSelfIntersections(
+ positions,
+ indices,
+ { maxPairs = 2000, budgetMs = 4000 } = {},
+) {
+ const triCount = indices.length / 3;
+ const { bvh } = buildBvh(positions, indices);
+ const started = Date.now();
+ let pairs = 0;
+ let truncated = false;
+ const box = { min: new Vector3(), max: new Vector3() };
+
+ for (let t = 0; t < triCount; t += 1) {
+ if (pairs >= maxPairs || Date.now() - started > budgetMs) {
+ truncated = t < triCount - 1;
+ break;
+ }
+ const ia = [indices[t * 3], indices[t * 3 + 1], indices[t * 3 + 2]];
+ box.min.set(Infinity, Infinity, Infinity);
+ box.max.set(-Infinity, -Infinity, -Infinity);
+ for (const i of ia) {
+ box.min.min(new Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]));
+ box.max.max(new Vector3(positions[i * 3], positions[i * 3 + 1], positions[i * 3 + 2]));
+ }
+ bvh.shapecast({
+ intersectsBounds: (bounds) =>
+ bounds.min.x <= box.max.x &&
+ bounds.max.x >= box.min.x &&
+ bounds.min.y <= box.max.y &&
+ bounds.max.y >= box.min.y &&
+ bounds.min.z <= box.max.z &&
+ bounds.max.z >= box.min.z,
+ intersectsTriangle: (_tri, other) => {
+ // Each unordered pair is tested once, from the lower index.
+ if (other <= t) return false;
+ const ib = [indices[other * 3], indices[other * 3 + 1], indices[other * 3 + 2]];
+ if (ia.some((x) => ib.includes(x))) return false;
+ if (trianglesIntersect(positions, ia, ib)) {
+ pairs += 1;
+ if (pairs >= maxPairs) return true;
+ }
+ return false;
+ },
+ });
+ }
+ return { pairs, truncated, budgetMs, maxPairs };
+}
+
+/**
+ * A signed distance field over a closed surface: unsigned distance from the
+ * BVH, sign from ray parity. Parity is exact on a closed mesh and cheap (a
+ * single all-hits cast), which beats a closest-point pseudonormal sign that
+ * misreads concave creases exactly where hollowing needs it most.
+ *
+ * Used for two things: eroding a solid into a shell (hollowing), and rebuilding
+ * a surface that no amount of hole filling could make manifold.
+ */
+export function makeSignedDistance(positions, indices) {
+ const { bvh } = buildBvh(positions, indices);
+ const point = new Vector3();
+ const target = {};
+ const ray = new Ray(new Vector3(), new Vector3(1, 0, 0).normalize());
+ // An axis-aligned probe direction grazes axis-aligned geometry, which is
+ // most of it; an irrational direction hits nothing edge-on.
+ ray.direction.set(0.5773502691896258, 0.5567764362830022, 0.5972015665748936).normalize();
+ return (x, y, z) => {
+ point.set(x, y, z);
+ bvh.closestPointToPoint(point, target);
+ const distance = target.distance ?? point.distanceTo(target.point);
+ ray.origin.copy(point);
+ const hits = bvh.raycast(ray, FrontSide);
+ return hits.length % 2 === 1 ? -distance : distance;
+ };
+}
+
+/** Unsigned distance only: the offset-shell repair never needs a sign. */
+export function makeUnsignedDistance(positions, indices) {
+ const { bvh } = buildBvh(positions, indices);
+ const point = new Vector3();
+ const target = {};
+ return (x, y, z) => {
+ point.set(x, y, z);
+ bvh.closestPointToPoint(point, target);
+ return target.distance ?? point.distanceTo(target.point);
+ };
+}
diff --git a/api/_lib/print/topology.js b/api/_lib/print/topology.js
new file mode 100644
index 000000000..cf6a7b465
--- /dev/null
+++ b/api/_lib/print/topology.js
@@ -0,0 +1,389 @@
+// Mesh topology for print preparation: the questions a slicer will ask.
+//
+// A printer does not render triangles, it fills a volume, so every metric here
+// is about whether the triangle soup encloses one. Four failures account for
+// nearly every AI-generated mesh that a bureau rejects, and each one has a
+// distinct fix, so each is measured separately rather than rolled into a single
+// "bad mesh" verdict:
+//
+// open edges a hole in the surface: the solid has no inside
+// non-manifold edges three or more faces on one edge: no consistent inside
+// inconsistent winding some faces point in, some out: the inside flips
+// self-intersections the surface crosses itself: the inside is ambiguous
+//
+// Everything in this module is pure and index-based. It never touches glTF,
+// never touches WASM, and never allocates a Manifold, so the analyzer can run
+// the cheap topology pass before deciding whether the expensive reconstruction
+// is worth attempting.
+//
+// Conventions shared with mesh-io.js: positions are a flat Float64Array of
+// world-space triples, indices are a flat Uint32Array of triangle corners, and
+// an "edge key" is the two welded vertex ids in ascending order.
+
+// A directed half-edge is stored as one number so the maps below stay in the
+// integer keyspace: pairing two 32-bit ids into a float loses precision above
+// 2^53, so vertex ids are capped at 2^26 (67M) which is far past MAX_TRIANGLES.
+const ID_BITS = 26;
+const ID_LIMIT = 1 << ID_BITS;
+
+function edgeKey(a, b) {
+ return a < b ? a * ID_LIMIT + b : b * ID_LIMIT + a;
+}
+
+/**
+ * Drop triangles that cannot contribute surface: a repeated corner (a sliver
+ * collapsed by welding) or a zero-area face. Both are invisible to a renderer
+ * and fatal to a manifold reconstruction, which reads them as a hole.
+ */
+export function dropDegenerate(positions, indices, areaEpsilon = 0) {
+ const kept = [];
+ let removed = 0;
+ for (let i = 0; i + 2 < indices.length; i += 3) {
+ const a = indices[i];
+ const b = indices[i + 1];
+ const c = indices[i + 2];
+ if (a === b || b === c || a === c) {
+ removed += 1;
+ continue;
+ }
+ if (areaEpsilon > 0 && triangleArea(positions, a, b, c) <= areaEpsilon) {
+ removed += 1;
+ continue;
+ }
+ kept.push(a, b, c);
+ }
+ return { indices: Uint32Array.from(kept), removed };
+}
+
+export function triangleArea(positions, a, b, c) {
+ const ax = positions[a * 3];
+ const ay = positions[a * 3 + 1];
+ const az = positions[a * 3 + 2];
+ const ux = positions[b * 3] - ax;
+ const uy = positions[b * 3 + 1] - ay;
+ const uz = positions[b * 3 + 2] - az;
+ const vx = positions[c * 3] - ax;
+ const vy = positions[c * 3 + 1] - ay;
+ const vz = positions[c * 3 + 2] - az;
+ const cx = uy * vz - uz * vy;
+ const cy = uz * vx - ux * vz;
+ const cz = ux * vy - uy * vx;
+ return Math.hypot(cx, cy, cz) / 2;
+}
+
+/**
+ * Build the undirected edge -> incident triangle map plus the directed
+ * half-edge counts. One pass produces every topology number the report needs.
+ *
+ * Returns:
+ * edges Map<edgeKey, number[]> triangle ids touching that edge
+ * openEdges edges with exactly one incident triangle (a hole rim)
+ * nonManifoldEdges edges with three or more incident triangles
+ * flippedEdges edges whose two triangles traverse it the same way,
+ * which means one of the pair is wound backwards
+ */
+export function edgeTopology(indices) {
+ const edges = new Map();
+ const directed = new Set();
+ let flippedEdges = 0;
+ const triCount = indices.length / 3;
+ for (let t = 0; t < triCount; t += 1) {
+ const a = indices[t * 3];
+ const b = indices[t * 3 + 1];
+ const c = indices[t * 3 + 2];
+ const corners = [
+ [a, b],
+ [b, c],
+ [c, a],
+ ];
+ for (const [u, v] of corners) {
+ const key = edgeKey(u, v);
+ const list = edges.get(key);
+ if (list) list.push(t);
+ else edges.set(key, [t]);
+ const dir = u * ID_LIMIT + v;
+ if (directed.has(dir)) flippedEdges += 1;
+ else directed.add(dir);
+ }
+ }
+ let openEdges = 0;
+ let nonManifoldEdges = 0;
+ for (const list of edges.values()) {
+ if (list.length === 1) openEdges += 1;
+ else if (list.length > 2) nonManifoldEdges += 1;
+ }
+ return { edges, openEdges, nonManifoldEdges, flippedEdges, edgeCount: edges.size };
+}
+
+/**
+ * Group triangles into connected shells. Adjacency is "shares a welded edge",
+ * so two shells that merely touch at a point stay separate, which is what a
+ * printer sees too. A figurine plus its base plate is two shells; the repair
+ * step unions them into one solid.
+ */
+export function connectedShells(indices, edges) {
+ const triCount = indices.length / 3;
+ const parent = new Uint32Array(triCount);
+ for (let i = 0; i < triCount; i += 1) parent[i] = i;
+ const find = (x) => {
+ let r = x;
+ while (parent[r] !== r) r = parent[r];
+ while (parent[x] !== r) {
+ const next = parent[x];
+ parent[x] = r;
+ x = next;
+ }
+ return r;
+ };
+ const union = (a, b) => {
+ const ra = find(a);
+ const rb = find(b);
+ if (ra !== rb) parent[rb] = ra;
+ };
+ for (const list of edges.values()) {
+ for (let i = 1; i < list.length; i += 1) union(list[0], list[i]);
+ }
+ const groups = new Map();
+ for (let t = 0; t < triCount; t += 1) {
+ const root = find(t);
+ const g = groups.get(root);
+ if (g) g.push(t);
+ else groups.set(root, [t]);
+ }
+ // Biggest shell first: it is the one a caller wants to keep when a repair
+ // has to discard specks, and it makes the shell list stable to compare.
+ return [...groups.values()].sort((a, b) => b.length - a.length);
+}
+
+/**
+ * Make every triangle in a shell wind the same way, then make that way
+ * outward. Winding is what defines "inside" for both the volume integral and
+ * the manifold reconstruction; a mesh assembled from separately-authored parts
+ * routinely has half its faces inverted and looks perfect in a renderer with
+ * backface culling off.
+ *
+ * The traversal only crosses edges with exactly two faces, so a non-manifold
+ * junction stops propagation rather than corrupting it. Outward is decided per
+ * shell by the sign of its enclosed volume: a closed shell with inward normals
+ * integrates negative.
+ */
+export function orientShell(positions, indices, tris) {
+ const local = new Uint32Array(tris.length * 3);
+ for (let i = 0; i < tris.length; i += 1) {
+ local[i * 3] = indices[tris[i] * 3];
+ local[i * 3 + 1] = indices[tris[i] * 3 + 1];
+ local[i * 3 + 2] = indices[tris[i] * 3 + 2];
+ }
+ const { edges } = edgeTopology(local);
+ const visited = new Uint8Array(tris.length);
+ let flipped = 0;
+ for (let seed = 0; seed < tris.length; seed += 1) {
+ if (visited[seed]) continue;
+ visited[seed] = 1;
+ const stack = [seed];
+ while (stack.length) {
+ const t = stack.pop();
+ const a = local[t * 3];
+ const b = local[t * 3 + 1];
+ const c = local[t * 3 + 2];
+ const corners = [
+ [a, b],
+ [b, c],
+ [c, a],
+ ];
+ for (const [u, v] of corners) {
+ const list = edges.get(edgeKey(u, v));
+ if (!list || list.length !== 2) continue;
+ const other = list[0] === t ? list[1] : list[0];
+ if (visited[other]) continue;
+ visited[other] = 1;
+ // Neighbours agree when they traverse the shared edge in opposite
+ // directions. Same direction means the neighbour is mirrored.
+ const oa = local[other * 3];
+ const ob = local[other * 3 + 1];
+ const oc = local[other * 3 + 2];
+ const sameDirection =
+ (oa === u && ob === v) || (ob === u && oc === v) || (oc === u && oa === v);
+ if (sameDirection) {
+ local[other * 3 + 1] = oc;
+ local[other * 3 + 2] = ob;
+ flipped += 1;
+ }
+ stack.push(other);
+ }
+ }
+ }
+ if (signedVolume(positions, local) < 0) {
+ for (let i = 0; i < local.length; i += 3) {
+ const swap = local[i + 1];
+ local[i + 1] = local[i + 2];
+ local[i + 2] = swap;
+ }
+ flipped = tris.length - flipped;
+ }
+ return { indices: local, flipped };
+}
+
+/**
+ * Signed volume by the divergence theorem: exact for a closed, consistently
+ * wound surface, and the fastest correct answer there is. On an open surface it
+ * is only an estimate, which is why the printability report takes its volume
+ * from the reconstructed solid instead.
+ */
+export function signedVolume(positions, indices) {
+ let total = 0;
+ for (let i = 0; i + 2 < indices.length; i += 3) {
+ const a = indices[i] * 3;
+ const b = indices[i + 1] * 3;
+ const c = indices[i + 2] * 3;
+ const ax = positions[a];
+ const ay = positions[a + 1];
+ const az = positions[a + 2];
+ const bx = positions[b];
+ const by = positions[b + 1];
+ const bz = positions[b + 2];
+ const cx = positions[c];
+ const cy = positions[c + 1];
+ const cz = positions[c + 2];
+ total +=
+ (ax * (by * cz - bz * cy) - ay * (bx * cz - bz * cx) + az * (bx * cy - by * cx)) / 6;
+ }
+ return total;
+}
+
+export function surfaceArea(positions, indices) {
+ let total = 0;
+ for (let i = 0; i + 2 < indices.length; i += 3) {
+ total += triangleArea(positions, indices[i], indices[i + 1], indices[i + 2]);
+ }
+ return total;
+}
+
+/**
+ * Walk the boundary half-edges into closed loops. An open edge in a
+ * consistently wound surface is traversed exactly once, in the direction the
+ * surviving face uses, so the loop is recovered by chaining each edge's end
+ * vertex to the next edge that starts there.
+ *
+ * Loops that cannot be closed (a boundary vertex shared by two separate holes)
+ * are returned as far as they were walked and flagged, so the caller can report
+ * a partial fill rather than silently producing a bad patch.
+ */
+export function boundaryLoops(indices) {
+ const count = new Map();
+ for (let i = 0; i + 2 < indices.length; i += 3) {
+ const corners = [
+ [indices[i], indices[i + 1]],
+ [indices[i + 1], indices[i + 2]],
+ [indices[i + 2], indices[i]],
+ ];
+ for (const [u, v] of corners) {
+ const key = edgeKey(u, v);
+ const rec = count.get(key);
+ if (rec) rec.n += 1;
+ else count.set(key, { n: 1, u, v });
+ }
+ }
+ // Only a strictly single-sided edge is a hole rim; a 3-face junction is a
+ // different defect and is never patched here.
+ const next = new Map();
+ for (const rec of count.values()) {
+ if (rec.n !== 1) continue;
+ const from = rec.u;
+ const to = rec.v;
+ const bucket = next.get(from);
+ if (bucket) bucket.push(to);
+ else next.set(from, [to]);
+ }
+ const loops = [];
+ let unclosed = 0;
+ for (const [start, targets] of next) {
+ while (targets.length) {
+ const loop = [start];
+ let current = targets.pop();
+ let guard = 0;
+ let closed = false;
+ while (current !== undefined && guard < 1_000_000) {
+ if (current === start) {
+ closed = true;
+ break;
+ }
+ loop.push(current);
+ const bucket = next.get(current);
+ current = bucket && bucket.length ? bucket.pop() : undefined;
+ guard += 1;
+ }
+ if (closed && loop.length >= 3) loops.push(loop);
+ else unclosed += 1;
+ }
+ }
+ return { loops, unclosed };
+}
+
+/**
+ * Close every hole with a fan to the loop centroid. A centroid fan beats ear
+ * clipping here because hole rims on a generated mesh are rarely planar and
+ * almost never convex, and the fan is guaranteed to produce exactly one patch
+ * triangle per boundary edge, which is what makes the result manifold.
+ *
+ * A boundary half-edge (a to b) is missing the face that would traverse it as
+ * (b to a), so each patch triangle is wound (b, a, centroid).
+ */
+export function fillHoles(positions, indices) {
+ const { loops, unclosed } = boundaryLoops(indices);
+ if (loops.length === 0) {
+ return { positions, indices, filled: 0, addedTriangles: 0, unclosedLoops: unclosed };
+ }
+ const outPositions = Array.from(positions);
+ const outIndices = Array.from(indices);
+ let added = 0;
+ for (const loop of loops) {
+ let cx = 0;
+ let cy = 0;
+ let cz = 0;
+ for (const v of loop) {
+ cx += positions[v * 3];
+ cy += positions[v * 3 + 1];
+ cz += positions[v * 3 + 2];
+ }
+ const n = loop.length;
+ const centroid = outPositions.length / 3;
+ outPositions.push(cx / n, cy / n, cz / n);
+ for (let i = 0; i < n; i += 1) {
+ const a = loop[i];
+ const b = loop[(i + 1) % n];
+ outIndices.push(b, a, centroid);
+ added += 1;
+ }
+ }
+ return {
+ positions: Float64Array.from(outPositions),
+ indices: Uint32Array.from(outIndices),
+ filled: loops.length,
+ addedTriangles: added,
+ unclosedLoops: unclosed,
+ };
+}
+
+/**
+ * Extract one shell as a standalone indexed mesh with its own compact vertex
+ * range. Manifold reconstructs one shell at a time, and feeding it the whole
+ * soup's vertex array would carry every other shell's unreferenced vertices
+ * into the solid.
+ */
+export function extractShell(positions, indices) {
+ const remap = new Map();
+ const outPositions = [];
+ const outIndices = new Uint32Array(indices.length);
+ for (let i = 0; i < indices.length; i += 1) {
+ const v = indices[i];
+ let id = remap.get(v);
+ if (id === undefined) {
+ id = outPositions.length / 3;
+ remap.set(v, id);
+ outPositions.push(positions[v * 3], positions[v * 3 + 1], positions[v * 3 + 2]);
+ }
+ outIndices[i] = id;
+ }
+ return { positions: Float64Array.from(outPositions), indices: outIndices };
+}
diff --git a/api/_lib/print/voxel-sdf.js b/api/_lib/print/voxel-sdf.js
new file mode 100644
index 000000000..bbe5c5e28
--- /dev/null
+++ b/api/_lib/print/voxel-sdf.js
@@ -0,0 +1,192 @@
+// Signed distance over an arbitrary triangle soup, for the two operations that
+// cannot be done with topology alone: reconstructing a solid from a mesh whose
+// topology is beyond repair, and eroding a solid to hollow it.
+//
+// Why a voxel sign instead of ray parity: an AI-generated mesh has holes, and
+// ray parity through a hole flips the answer for an entire column of samples,
+// which reads as a tunnel bored through the middle of the print. Flood-filling
+// the outside instead means a hole smaller than one voxel simply cannot leak,
+// and a hole larger than one voxel is a hole the buyer should be told about
+// (the analyzer already reports it) rather than one silently sealed.
+//
+// Cost model, measured on this machine: the distance query is a three-mesh-bvh
+// closest-point call (microseconds) and Manifold's level-set evaluates it once
+// per grid sample. At the default budget that is ~250k samples and about two
+// seconds, so this path stays inside a request; the caller bounds it further by
+// passing a smaller `maxSamples`.
+
+import * as THREE from 'three';
+import { MeshBVH } from 'three-mesh-bvh';
+
+import { boundsOf } from './mesh-io.js';
+
+// Grid ceiling. 2.1M cells is a 128-cube: enough that a 10 cm print resolves
+// features under a millimetre, and small enough that the flood fill stays a
+// typed-array walk rather than a memory event.
+export const MAX_GRID_CELLS = 128 ** 3;
+// Sample ceiling for the level-set evaluation itself, which is the wall-clock
+// cost the caller actually feels.
+export const DEFAULT_MAX_SAMPLES = 400_000;
+
+const OUTSIDE = 1;
+
+/**
+ * Build the occupancy grid and flood-fill the outside.
+ *
+ * Triangles are rasterized conservatively (every cell their bounding box
+ * touches is marked as surface), so the fill can never cross the shell through
+ * a diagonal gap. What the fill reaches from the padded border is outside;
+ * everything else, surface cells included, is inside.
+ */
+function buildInsideMask(positions, indices, min, size, dims) {
+ const [nx, ny, nz] = dims;
+ const cell = [size[0] / nx, size[1] / ny, size[2] / nz];
+ const mask = new Uint8Array(nx * ny * nz);
+ const idx = (x, y, z) => (z * ny + y) * nx + x;
+
+ for (let t = 0; t + 2 < indices.length; t += 3) {
+ let lo0 = Infinity, lo1 = Infinity, lo2 = Infinity;
+ let hi0 = -Infinity, hi1 = -Infinity, hi2 = -Infinity;
+ for (let k = 0; k < 3; k += 1) {
+ const v = indices[t + k] * 3;
+ const x = positions[v], y = positions[v + 1], z = positions[v + 2];
+ if (x < lo0) lo0 = x; if (x > hi0) hi0 = x;
+ if (y < lo1) lo1 = y; if (y > hi1) hi1 = y;
+ if (z < lo2) lo2 = z; if (z > hi2) hi2 = z;
+ }
+ const x0 = Math.max(0, Math.floor((lo0 - min[0]) / cell[0]));
+ const x1 = Math.min(nx - 1, Math.floor((hi0 - min[0]) / cell[0]));
+ const y0 = Math.max(0, Math.floor((lo1 - min[1]) / cell[1]));
+ const y1 = Math.min(ny - 1, Math.floor((hi1 - min[1]) / cell[1]));
+ const z0 = Math.max(0, Math.floor((lo2 - min[2]) / cell[2]));
+ const z1 = Math.min(nz - 1, Math.floor((hi2 - min[2]) / cell[2]));
+ for (let z = z0; z <= z1; z += 1) {
+ for (let y = y0; y <= y1; y += 1) {
+ for (let x = x0; x <= x1; x += 1) mask[idx(x, y, z)] = 2;
+ }
+ }
+ }
+
+ // Flood the outside from every border cell. An explicit stack, not
+ // recursion: a 128-cube can queue millions of cells.
+ const stack = [];
+ for (let z = 0; z < nz; z += 1) {
+ for (let y = 0; y < ny; y += 1) {
+ for (let x = 0; x < nx; x += 1) {
+ const border = x === 0 || y === 0 || z === 0 || x === nx - 1 || y === ny - 1 || z === nz - 1;
+ if (!border) continue;
+ const i = idx(x, y, z);
+ if (mask[i] === 0) {
+ mask[i] = OUTSIDE;
+ stack.push(x, y, z);
+ }
+ }
+ }
+ }
+ while (stack.length) {
+ const z = stack.pop(), y = stack.pop(), x = stack.pop();
+ for (const [dx, dy, dz] of [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]) {
+ const a = x + dx, b = y + dy, c = z + dz;
+ if (a < 0 || b < 0 || c < 0 || a >= nx || b >= ny || c >= nz) continue;
+ const i = idx(a, b, c);
+ if (mask[i] !== 0) continue;
+ mask[i] = OUTSIDE;
+ stack.push(a, b, c);
+ }
+ }
+ return { mask, cell, idx };
+}
+
+/**
+ * A signed-distance sampler over a triangle soup. Positive inside, which is the
+ * convention Manifold's level-set extractor expects (its interior is where the
+ * function exceeds the level).
+ *
+ * @param {Float64Array} positions
+ * @param {Uint32Array} indices
+ * @param {{ padding?: number, maxCells?: number }} [opts] padding is a fraction
+ * of the longest bounding-box axis; the grid needs at least one empty cell
+ * outside the mesh for the flood fill to start.
+ */
+export function buildSignedDistance(positions, indices, opts = {}) {
+ const bounds = boundsOf(positions);
+ if (!bounds) throw new Error('cannot build a distance field for an empty mesh');
+ const pad = (opts.padding ?? 0.06) * bounds.longest;
+ const min = bounds.min.map((v) => v - pad);
+ const size = bounds.size.map((v) => v + pad * 2);
+ const maxCells = Math.min(opts.maxCells ?? MAX_GRID_CELLS, MAX_GRID_CELLS);
+
+ // One cell edge for all three axes keeps the distance field isotropic; the
+ // per-axis counts then follow the bounding box's own proportions.
+ const volume = size[0] * size[1] * size[2];
+ let edge = Math.cbrt(volume / maxCells);
+ if (!(edge > 0)) edge = bounds.longest / 32;
+ const dims = size.map((v) => Math.max(4, Math.min(256, Math.ceil(v / edge))));
+
+ const { mask, cell, idx } = buildInsideMask(positions, indices, min, size, dims);
+
+ const geometry = new THREE.BufferGeometry();
+ geometry.setAttribute('position', new THREE.BufferAttribute(Float32Array.from(positions), 3));
+ geometry.setIndex(new THREE.BufferAttribute(Uint32Array.from(indices), 1));
+ const bvh = new MeshBVH(geometry);
+
+ const point = new THREE.Vector3();
+ const hit = { point: new THREE.Vector3(), distance: 0, faceIndex: 0 };
+ const [nx, ny, nz] = dims;
+
+ function inside(x, y, z) {
+ const ix = Math.min(nx - 1, Math.max(0, Math.floor((x - min[0]) / cell[0])));
+ const iy = Math.min(ny - 1, Math.max(0, Math.floor((y - min[1]) / cell[1])));
+ const iz = Math.min(nz - 1, Math.max(0, Math.floor((z - min[2]) / cell[2])));
+ return mask[idx(ix, iy, iz)] !== OUTSIDE;
+ }
+
+ function distance(x, y, z) {
+ point.set(x, y, z);
+ bvh.closestPointToPoint(point, hit);
+ return hit.distance;
+ }
+
+ return {
+ bounds: { min, max: [min[0] + size[0], min[1] + size[1], min[2] + size[2]] },
+ dims,
+ cellEdge: Math.max(cell[0], cell[1], cell[2]),
+ bvh,
+ geometry,
+ inside,
+ distance,
+ /** Positive inside, negative outside, in the mesh's own units. */
+ sample(x, y, z) {
+ const d = distance(x, y, z);
+ return inside(x, y, z) ? d : -d;
+ },
+ };
+}
+
+/**
+ * Extract a guaranteed-manifold solid from a distance field at the given level.
+ * A positive level erodes (the surface moves inward), which is how hollowing
+ * finds its inner wall; level 0 reconstructs the original surface.
+ *
+ * `edgeLength` trades fidelity for triangles and time. It defaults to the
+ * field's own cell size, because asking for detail finer than the field
+ * resolves only adds triangles that carry no information.
+ */
+export function extractLevelSet(wasm, field, { level = 0, edgeLength, maxSamples = DEFAULT_MAX_SAMPLES } = {}) {
+ const span = [
+ field.bounds.max[0] - field.bounds.min[0],
+ field.bounds.max[1] - field.bounds.min[1],
+ field.bounds.max[2] - field.bounds.min[2],
+ ];
+ let edge = edgeLength || field.cellEdge;
+ // Hold the evaluation inside the sample budget: the level-set walks a grid of
+ // its own, and its cost is what the caller waits on.
+ const budgetEdge = Math.cbrt((span[0] * span[1] * span[2]) / maxSamples);
+ if (edge < budgetEdge) edge = budgetEdge;
+ const solid = wasm.Manifold.levelSet(
+ (p) => field.sample(p[0], p[1], p[2]) - level,
+ { min: field.bounds.min, max: field.bounds.max },
+ edge,
+ );
+ return { solid, edgeLength: edge };
+}
diff --git a/package-lock.json b/package-lock.json
index dc2dc21e4..4b2245065 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -173,6 +173,7 @@
"express": "^5.2.1",
"fast-check": "^4.8.0",
"fast-xml-parser": "^5.7.3",
+ "fflate": "^0.8.3",
"gltf-validator": "^2.0.0-dev.3.10",
"helius-sdk": "^3.0.0",
"idb-keyval": "^6.3.0",
@@ -183,6 +184,7 @@
"livekit-client": "^2.19.2",
"livepeer": "^3.5.0",
"lru-cache": "^11.5.2",
+ "manifold-3d": "^3.5.1",
"marked": "^18.0.7",
"meshoptimizer": "^1.1.1",
"mppx": "^0.6.31",
@@ -8798,6 +8800,12 @@
"url": "https://opencollective.com/js-sdsl"
}
},
+ "node_modules/@jscadui/3mf-export": {
+ "version": "0.5.0",
+ "resolved": "https://registry.npmjs.org/@jscadui/3mf-export/-/3mf-export-0.5.0.tgz",
+ "integrity": "sha512-y5vZktqCjyi7wA38zqNlLIdZUIRZoOO9vCjLzwmL4bR0hk7B/Zm1IeffzJPFe1vFc0C1IEv3hm8caDv3doRk9g==",
+ "license": "MIT"
+ },
"node_modules/@jup-ag/api": {
"version": "6.0.48",
"license": "MIT"
@@ -13354,6 +13362,12 @@
"node": ">= 8.0.0"
}
},
+ "node_modules/@shuding/opentype.js/node_modules/fflate": {
+ "version": "0.7.5",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.7.5.tgz",
+ "integrity": "sha512-QieYf//cis6ywHNi5qW1+PXPQ4bC+XVJAtS4AXIML8P76GroEiOxm/oQtn1f02UkJY1+KsXMJcC+R2v/Eg4G3g==",
+ "license": "MIT"
+ },
"node_modules/@signinwithethereum/siwe": {
"version": "4.2.0",
"license": "Apache-2.0",
@@ -24831,7 +24845,9 @@
"license": "MIT"
},
"node_modules/fflate": {
- "version": "0.7.4",
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
+ "integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
"license": "MIT"
},
"node_modules/file-uri-to-path": {
@@ -30830,6 +30846,52 @@
"tmpl": "1.0.5"
}
},
+ "node_modules/manifold-3d": {
+ "version": "3.5.1",
+ "resolved": "https://registry.npmjs.org/manifold-3d/-/manifold-3d-3.5.1.tgz",
+ "integrity": "sha512-/+m6kxYMMhnPutcQ5oSmFJiJ+gyP/0fmuUCb9Qeaunvecm/bfqogKYDDJarsnWiFioSMtKheF+lGmSlnYCik9g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@gltf-transform/core": "^4.2.0",
+ "@gltf-transform/extensions": "^4.2.0",
+ "@gltf-transform/functions": "^4.2.0",
+ "@jridgewell/resolve-uri": "^3.1.2",
+ "@jridgewell/trace-mapping": "^0.3.31",
+ "@jscadui/3mf-export": "^0.5.0",
+ "commander": "^13.1.0",
+ "convert-source-map": "^2.0.0",
+ "fast-xml-parser": "^5.4.2",
+ "fflate": "^0.8.0",
+ "magic-string": "^0.30.21"
+ },
+ "bin": {
+ "manifold-cad": "bin/manifold-cad"
+ },
+ "peerDependencies": {
+ "@gltf-transform/core": "^4.2.0",
+ "@gltf-transform/extensions": "^4.2.0",
+ "@gltf-transform/functions": "^4.2.0",
+ "esbuild-wasm": "^0.27.3"
+ }
+ },
+ "node_modules/manifold-3d/node_modules/commander": {
+ "version": "13.1.0",
+ "resolved": "https://registry.npmjs.org/commander/-/commander-13.1.0.tgz",
+ "integrity": "sha512-/rFeCpNJQbhSZjGVwO9RFV3xPqbnERS8MmIQzCtD/zl6gpJuV/bMLuN92oG3F7d8oDEHHRrujSXNUr8fpjntKw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/manifold-3d/node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
"node_modules/marked": {
"version": "18.0.7",
"license": "MIT",
diff --git a/package.json b/package.json
index 37b740d9b..2d3ab42e1 100644
--- a/package.json
+++ b/package.json
@@ -521,6 +521,7 @@
"express": "^5.2.1",
"fast-check": "^4.8.0",
"fast-xml-parser": "^5.7.3",
+ "fflate": "^0.8.3",
"gltf-validator": "^2.0.0-dev.3.10",
"helius-sdk": "^3.0.0",
"idb-keyval": "^6.3.0",
@@ -531,6 +532,7 @@
"livekit-client": "^2.19.2",
"livepeer": "^3.5.0",
"lru-cache": "^11.5.2",
+ "manifold-3d": "^3.5.1",
"marked": "^18.0.7",
"meshoptimizer": "^1.1.1",
"mppx": "^0.6.31",