Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(mesh-ops): repair, smooth and decimate a model in a browser worker with undo, wired into the Forge optimize panel
nirholas1c5fc8bbccf6
diff --git a/src/forge-optimize.js b/src/forge-optimize.jsindex 6e2bcf1a2..d1d4b9a2b 100644--- a/src/forge-optimize.js+++ b/src/forge-optimize.js@@ -12,10 +12,18 @@// GLB output renders inline (swaps the live <model-viewer> src); every other// format is download-only. Nothing fakes progress — the panel polls the job.//+// Above the server remesh sit the in-browser mesh tools (src/mesh-ops/): repair,+// smooth and decimate, run in a worker with undo and reset to original. Their+// edits swap the viewer and the download button just like a GLB remesh does;+// the server remesh still starts from the last saved (remote) model, because a+// local edit only exists as a blob in this tab.+//// The panel injects its own markup + styles so it survives independently of the// forge.html template: it only needs the result panel, viewer, and download// button to be present.+import { mountMeshTools } from './mesh-ops/panel.js';+const resultPanel = document.getElementById('state-result');const viewer = document.getElementById('viewer');const download = document.getElementById('download');@@ -138,6 +146,13 @@ if (resultPanel && viewer) {.opt-stats { display: flex; gap: var(--space-md); flex-wrap: wrap; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-dim); }.opt-stats strong { color: var(--ink); font-weight: 600; }.opt-stats.is-hidden { display: none; }+ .opt-section-title {+ margin: 0; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-dim);+ text-transform: uppercase; letter-spacing: 0.04em; padding-top: var(--space-sm);+ border-top: 1px solid var(--stroke);+ }+ .opt-local-note { margin: 0; font-size: var(--text-xs); color: var(--warning); line-height: 1.4; }+ .opt-local-note[hidden] { display: none; }`;document.head.appendChild(style);}@@ -148,13 +163,16 @@ if (resultPanel && viewer) {panel.dataset.open = 'false';panel.innerHTML = `<button class="optimize-toggle" type="button" aria-expanded="false">- <span>Optimize topology, quad remesh & game-ready low-poly</span>+ <span>Optimize: repair, smooth, decimate, quad remesh & low-poly</span><svg class="chev" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9" /></svg></button><div class="optimize-body">+ <div class="opt-local"></div>+ <p class="opt-section-title">Server remesh</p>+ <p class="opt-local-note" hidden>Server remesh starts from the saved model, not your in-browser edits. Download the edited GLB above to keep them.</p><div class="opt-field"><span>Mode</span><div class="seg opt-mode" role="group" aria-label="Remesh mode">@@ -203,6 +221,32 @@ if (resultPanel && viewer) {const runLabel = panel.querySelector('.opt-run-label');const statusEl = panel.querySelector('.opt-status');const stats = panel.querySelector('.opt-stats');+ const localNote = panel.querySelector('.opt-local-note');++ // The forge download button as forge.js left it, captured the first time a+ // local edit repoints it, so "Reset to original" can hand it back exactly.+ let originalDownload = null;+ function pointDownload(href, name, text) {+ if (!download) return;+ download.href = href;+ download.setAttribute('download', name);+ download.textContent = text;+ }+ const meshTools = mountMeshTools(panel.querySelector('.opt-local'), {+ onChange({ url, edited, filename }) {+ if (download && !originalDownload) {+ originalDownload = {+ href: download.getAttribute('href'),+ name: download.getAttribute('download') || 'forge.glb',+ text: download.textContent,+ };+ }+ viewer.setAttribute('src', url);+ localNote.hidden = !edited;+ if (edited) pointDownload(url, filename, 'Download GLB');+ else if (originalDownload) pointDownload(originalDownload.href, originalDownload.name, originalDownload.text);+ },+ });for (const [value, text] of FORMATS) {const opt = document.createElement('option');@@ -261,6 +305,9 @@ if (resultPanel && viewer) {if (download) download.textContent = 'Download GLB';panel.dataset.open = 'false';toggle.setAttribute('aria-expanded', 'false');+ originalDownload = null;+ localNote.hidden = true;+ meshTools.setSource(glbUrl, { label: state.label });}function setRunning(running) {@@ -344,6 +391,9 @@ if (resultPanel && viewer) {if (format === 'glb') {viewer.setAttribute('src', result);state.glbUrl = result; // chain further optimizations from the new mesh+ originalDownload = null;+ localNote.hidden = true;+ meshTools.setSource(result, { label: `${state.label} ${state.mode}` });}const safe =state.label.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge';@@ -379,6 +429,7 @@ if (resultPanel && viewer) {const open = panel.dataset.open === 'true';panel.dataset.open = String(!open);toggle.setAttribute('aria-expanded', String(!open));+ if (!open) meshTools.activate();});modeGroup.addEventListener('click', (e) => {diff --git a/src/forge-studio/forge-optimize.js b/src/forge-studio/forge-optimize.jsindex 6d2e78083..f5eba32f9 100644--- a/src/forge-studio/forge-optimize.js+++ b/src/forge-studio/forge-optimize.js@@ -12,10 +12,18 @@// GLB output renders inline (swaps the live <model-viewer> src); every other// format is download-only. Nothing fakes progress — the panel polls the job.//+// Above the server remesh sit the in-browser mesh tools (src/mesh-ops/): repair,+// smooth and decimate, run in a worker with undo and reset to original. Their+// edits swap the viewer and the download button just like a GLB remesh does;+// the server remesh still starts from the last saved (remote) model, because a+// local edit only exists as a blob in this tab.+//// The panel injects its own markup + styles so it survives independently of the// forge.html template: it only needs the result panel, viewer, and download// button to be present.+import { mountMeshTools } from '../mesh-ops/panel.js';+const resultPanel = document.getElementById('state-result');const viewer = document.getElementById('viewer');const download = document.getElementById('download');@@ -138,6 +146,13 @@ if (resultPanel && viewer) {.opt-stats { display: flex; gap: var(--space-md); flex-wrap: wrap; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-dim); }.opt-stats strong { color: var(--ink); font-weight: 600; }.opt-stats.is-hidden { display: none; }+ .opt-section-title {+ margin: 0; font-family: var(--font-mono); font-size: var(--text-xs); color: var(--ink-dim);+ text-transform: uppercase; letter-spacing: 0.04em; padding-top: var(--space-sm);+ border-top: 1px solid var(--stroke);+ }+ .opt-local-note { margin: 0; font-size: var(--text-xs); color: var(--warning); line-height: 1.4; }+ .opt-local-note[hidden] { display: none; }`;document.head.appendChild(style);}@@ -148,13 +163,16 @@ if (resultPanel && viewer) {panel.dataset.open = 'false';panel.innerHTML = `<button class="optimize-toggle" type="button" aria-expanded="false">- <span>Optimize topology — quad remesh & game-ready low-poly</span>+ <span>Optimize: repair, smooth, decimate, quad remesh & low-poly</span><svg class="chev" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="6 9 12 15 18 9" /></svg></button><div class="optimize-body">+ <div class="opt-local"></div>+ <p class="opt-section-title">Server remesh</p>+ <p class="opt-local-note" hidden>Server remesh starts from the saved model, not your in-browser edits. Download the edited GLB above to keep them.</p><div class="opt-field"><span>Mode</span><div class="seg opt-mode" role="group" aria-label="Remesh mode">@@ -203,6 +221,32 @@ if (resultPanel && viewer) {const runLabel = panel.querySelector('.opt-run-label');const statusEl = panel.querySelector('.opt-status');const stats = panel.querySelector('.opt-stats');+ const localNote = panel.querySelector('.opt-local-note');++ // The forge download button as forge.js left it, captured the first time a+ // local edit repoints it, so "Reset to original" can hand it back exactly.+ let originalDownload = null;+ function pointDownload(href, name, text) {+ if (!download) return;+ download.href = href;+ download.setAttribute('download', name);+ download.textContent = text;+ }+ const meshTools = mountMeshTools(panel.querySelector('.opt-local'), {+ onChange({ url, edited, filename }) {+ if (download && !originalDownload) {+ originalDownload = {+ href: download.getAttribute('href'),+ name: download.getAttribute('download') || 'forge.glb',+ text: download.textContent,+ };+ }+ viewer.setAttribute('src', url);+ localNote.hidden = !edited;+ if (edited) pointDownload(url, filename, 'Download GLB');+ else if (originalDownload) pointDownload(originalDownload.href, originalDownload.name, originalDownload.text);+ },+ });for (const [value, text] of FORMATS) {const opt = document.createElement('option');@@ -261,6 +305,9 @@ if (resultPanel && viewer) {if (download) download.textContent = 'Download GLB';panel.dataset.open = 'false';toggle.setAttribute('aria-expanded', 'false');+ originalDownload = null;+ localNote.hidden = true;+ meshTools.setSource(glbUrl, { label: state.label });}function setRunning(running) {@@ -344,6 +391,9 @@ if (resultPanel && viewer) {if (format === 'glb') {viewer.setAttribute('src', result);state.glbUrl = result; // chain further optimizations from the new mesh+ originalDownload = null;+ localNote.hidden = true;+ meshTools.setSource(result, { label: `${state.label} ${state.mode}` });}const safe =state.label.replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'forge';@@ -379,6 +429,7 @@ if (resultPanel && viewer) {const open = panel.dataset.open === 'true';panel.dataset.open = String(!open);toggle.setAttribute('aria-expanded', String(!open));+ if (!open) meshTools.activate();});modeGroup.addEventListener('click', (e) => {diff --git a/src/mesh-ops/client.js b/src/mesh-ops/client.jsnew file mode 100644index 000000000..a9e9d25c9--- /dev/null+++ b/src/mesh-ops/client.js@@ -0,0 +1,79 @@+// Main-thread handle on the mesh-ops worker.+//+// One worker per page, started on first use. If a browser refuses module+// workers (old WebViews, a blocked worker-src), the same runner is imported and+// run inline instead: slower to paint during the operation, never broken.++let worker = null;+let workerFailed = false;+let seq = 0;+const pending = new Map();++function startWorker() {+ if (worker || workerFailed) return worker;+ try {+ worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' });+ worker.addEventListener('message', (event) => {+ const msg = event.data || {};+ const job = pending.get(msg.id);+ if (!job) return;+ if (msg.phase) {+ job.onPhase?.(msg.phase);+ return;+ }+ pending.delete(msg.id);+ if (msg.ok) job.resolve(msg);+ else job.reject(new Error(msg.error || 'The mesh operation failed.'));+ });+ worker.addEventListener('error', (event) => {+ event.preventDefault?.();+ workerFailed = true;+ worker?.terminate();+ worker = null;+ for (const [id, job] of pending) {+ pending.delete(id);+ job.retryInline();+ }+ });+ } catch {+ workerFailed = true;+ worker = null;+ }+ return worker;+}++async function runInline(kind, bytes, op, params, onPhase) {+ const runner = await import('./runner.js');+ const input = new Uint8Array(bytes);+ if (kind === 'inspect') return runner.inspectGlb(input);+ const result = await runner.runMeshOp(input, op, params, onPhase);+ return { bytes: result.bytes, stats: result.stats, triangles: result.triangles };+}++function call(kind, bytes, op, params, onPhase) {+ const copy = bytes.slice(0);+ const w = startWorker();+ if (!w) return runInline(kind, copy, op, params, onPhase);+ return new Promise((resolve, reject) => {+ const id = ++seq;+ const retryInline = () => runInline(kind, bytes.slice(0), op, params, onPhase).then(resolve, reject);+ pending.set(id, { resolve, reject, onPhase, retryInline });+ w.postMessage({ id, kind, bytes: copy, op, params }, [copy]);+ });+}++/** Triangle count of a GLB ArrayBuffer. */+export async function inspect(bytes) {+ const result = await call('inspect', bytes);+ return { triangles: result.triangles };+}++/**+ * Run 'repair' | 'smooth' | 'decimate' on a GLB ArrayBuffer. Resolves to+ * `{ bytes: ArrayBuffer, stats, triangles }`; the input buffer is not consumed.+ */+export async function run(bytes, op, params, onPhase) {+ const result = await call('run', bytes, op, params, onPhase);+ const out = result.bytes instanceof ArrayBuffer ? result.bytes : result.bytes.buffer.slice(result.bytes.byteOffset, result.bytes.byteOffset + result.bytes.byteLength);+ return { bytes: out, stats: result.stats, triangles: result.triangles };+}diff --git a/src/mesh-ops/core.js b/src/mesh-ops/core.jsnew file mode 100644index 000000000..1f852ca90--- /dev/null+++ b/src/mesh-ops/core.js@@ -0,0 +1,815 @@+// Mesh operations that run in the browser: repair, smooth, decimate.+//+// Adapted from Modly (https://github.com/lightningpixel/modly), MIT License,+// Copyright (c) 2026 Lightning Pixel. Modly ships these as a Python mesh+// pipeline (trimesh merge/repair, Taubin smoothing, meshoptimizer decimation+// behind a weld). The parameter model and the weld-then-simplify order come+// from there; the implementations below are rewritten for the browser so a+// forge result can be cleaned up without a server round trip, and they keep+// every vertex attribute (UVs, colours, skin weights, morph targets) intact,+// which a position-only pipeline does not.+//+// Everything here works on one indexed triangle primitive in a plain shape:+//+// { indices: Uint32Array,+// attributes: { POSITION: { array, itemSize }, NORMAL: ..., TEXCOORD_0: ... },+// targets: [ { POSITION: { array, itemSize }, ... } ] }+//+// Attribute records may carry extra fields (glTF accessor type, normalized);+// they are passed through untouched. Nothing in this module touches glTF, the+// DOM, or a worker, so the same code runs in a Web Worker, on the main thread,+// and under vitest.+//+// The one idea every operation shares is the split between ATTRIBUTE vertices+// (what a GPU draws: a position plus its UV, normal, ...) and POSITION groups+// (every attribute vertex sitting at the same point in space). A UV seam is two+// attribute vertices in one position group. Topology questions (is this a hole,+// which way is out, who are my neighbours) are asked of position groups so a+// seam never reads as a crack; data is written per attribute vertex so the+// texture never moves.++import {+ connectedShells,+ edgeTopology,+ orientConsistently,+ signedVolume,+ triangleArea,+} from '../../api/_lib/print/topology.js';++// Weld tolerance as a fraction of the bounding-box diagonal. Loose enough to+// close the float noise a generator leaves between "the same" vertex on two+// triangles, tight enough to never fuse two genuinely distinct surfaces.+const WELD_FRACTION = 1e-6;+// Attribute values are compared after rounding to this many steps per unit.+// UVs and colours equal to five decimals are the same texel on any texture+// under 16K; normals and tangents are compared coarser (about 0.06 degrees) so+// float noise does not split a smooth surface, while a real hard edge, whose+// normals differ by tens of degrees, stays split.+const ATTRIBUTE_STEPS = 1e5;+const DIRECTION_STEPS = 1e3;+const DIRECTION_SEMANTICS = new Set(['NORMAL', 'TANGENT']);+// Default crease for recomputed normals: faces meeting at a sharper angle keep+// a hard edge. 60 degrees keeps a cube a cube and a sphere a sphere.+export const DEFAULT_CREASE_DEGREES = 60;++export const SMOOTH_DEFAULTS = Object.freeze({+ method: 'taubin',+ iterations: 10,+ lambda: 0.5,+ passband: 0.1,+ preserveBoundary: true,+});++// ── small helpers ────────────────────────────────────────────────────────────++export function vertexCount(mesh) {+ return mesh.attributes.POSITION.array.length / 3;+}++export function triangleCount(mesh) {+ return Math.floor(mesh.indices.length / 3);+}++export function bboxDiagonal(positions) {+ let minX = Infinity;+ let minY = Infinity;+ let minZ = Infinity;+ let maxX = -Infinity;+ let maxY = -Infinity;+ let maxZ = -Infinity;+ for (let i = 0; i < positions.length; i += 3) {+ const x = positions[i];+ const y = positions[i + 1];+ const z = positions[i + 2];+ if (x < minX) minX = x;+ if (y < minY) minY = y;+ if (z < minZ) minZ = z;+ if (x > maxX) maxX = x;+ if (y > maxY) maxY = y;+ if (z > maxZ) maxZ = z;+ }+ if (!Number.isFinite(minX)) return 0;+ return Math.hypot(maxX - minX, maxY - minY, maxZ - minZ);+}++function weldTolerance(positions, override) {+ if (override > 0) return override;+ return Math.max(bboxDiagonal(positions) * WELD_FRACTION, 1e-9);+}++function cloneRecord(record, array) {+ return { ...record, array };+}++/**+ * Rebuild every attribute (and every morph target attribute) through a vertex+ * remap. `remap[old]` is the new index, or 0xffffffff for a dropped vertex.+ * When several old vertices map to one new one, the first wins; callers only+ * merge vertices whose kept attributes are equal.+ */+export function remapMesh(mesh, remap, newCount, indices) {+ const remapRecords = (records) => {+ const out = {};+ for (const [name, record] of Object.entries(records)) {+ const { array, itemSize } = record;+ const next = new array.constructor(newCount * itemSize);+ const written = new Uint8Array(newCount);+ const oldCount = array.length / itemSize;+ for (let v = 0; v < oldCount; v += 1) {+ const n = remap[v];+ if (n === 0xffffffff || written[n]) continue;+ written[n] = 1;+ for (let k = 0; k < itemSize; k += 1) next[n * itemSize + k] = array[v * itemSize + k];+ }+ out[name] = cloneRecord(record, next);+ }+ return out;+ };+ return {+ ...mesh,+ indices,+ attributes: remapRecords(mesh.attributes),+ targets: (mesh.targets || []).map(remapRecords),+ };+}++/**+ * Drop vertices no triangle references. Survivors keep their original relative+ * order, so attribute arrays stay aligned with what the caller had.+ */+export function compactMesh(mesh) {+ const count = vertexCount(mesh);+ const used = new Uint8Array(count);+ for (let i = 0; i < mesh.indices.length; i += 1) used[mesh.indices[i]] = 1;+ const remap = new Uint32Array(count).fill(0xffffffff);+ let next = 0;+ for (let v = 0; v < count; v += 1) if (used[v]) remap[v] = next++;+ if (next === count) return { mesh, removed: 0 };+ const indices = new Uint32Array(mesh.indices.length);+ for (let i = 0; i < indices.length; i += 1) indices[i] = remap[mesh.indices[i]];+ return { mesh: remapMesh(mesh, remap, next, indices), removed: count - next };+}++/**+ * Position groups: every attribute vertex mapped to the id of the point in+ * space it sits on. Two vertices whose positions agree to `tolerance` share a+ * group, which is what makes a UV seam one edge instead of two.+ */+export function positionGroups(positions, tolerance) {+ const count = positions.length / 3;+ const groupOf = new Uint32Array(count);+ const seen = new Map();+ const inv = 1 / tolerance;+ let groups = 0;+ for (let v = 0; v < count; v += 1) {+ const key = `${Math.round(positions[v * 3] * inv)},${Math.round(positions[v * 3 + 1] * inv)},${Math.round(+ positions[v * 3 + 2] * inv,+ )}`;+ let g = seen.get(key);+ if (g === undefined) {+ g = groups++;+ seen.set(key, g);+ }+ groupOf[v] = g;+ }+ return { groupOf, groupCount: groups };+}++function vertexKey(mesh, v, posInv) {+ const parts = [];+ const pos = mesh.attributes.POSITION.array;+ parts.push(Math.round(pos[v * 3] * posInv), Math.round(pos[v * 3 + 1] * posInv), Math.round(pos[v * 3 + 2] * posInv));+ const pushRecords = (records) => {+ for (const [name, { array, itemSize }] of Object.entries(records)) {+ if (name === 'POSITION' && records === mesh.attributes) continue;+ const steps = DIRECTION_SEMANTICS.has(name) ? DIRECTION_STEPS : ATTRIBUTE_STEPS;+ for (let k = 0; k < itemSize; k += 1) parts.push(Math.round(array[v * itemSize + k] * steps));+ }+ };+ pushRecords(mesh.attributes);+ for (const target of mesh.targets || []) pushRecords(target);+ return parts.join(',');+}++/**+ * Merge attribute vertices that are the same vertex: same position (to the+ * weld tolerance) AND the same UV, colour, skin, normal direction and morph+ * deltas. Never merges across a UV seam or a hard edge, so the texture and the+ * shading are exactly what they were.+ */+export function weldVertices(mesh, opts = {}) {+ const positions = mesh.attributes.POSITION.array;+ const tolerance = weldTolerance(positions, opts.tolerance);+ const posInv = 1 / tolerance;+ const count = vertexCount(mesh);+ const remap = new Uint32Array(count);+ const seen = new Map();+ let next = 0;+ for (let v = 0; v < count; v += 1) {+ const key = vertexKey(mesh, v, posInv);+ let n = seen.get(key);+ if (n === undefined) {+ n = next++;+ seen.set(key, n);+ }+ remap[v] = n;+ }+ const indices = new Uint32Array(mesh.indices.length);+ for (let i = 0; i < indices.length; i += 1) indices[i] = remap[mesh.indices[i]];+ return {+ mesh: next === count ? { ...mesh, indices } : remapMesh(mesh, remap, next, indices),+ merged: count - next,+ tolerance,+ };+}++// ── normals ─────────────────────────────────────────────────────────────────++function buildIncidence(keyOf, keyCount, indices) {+ const triCount = indices.length / 3;+ const offsets = new Uint32Array(keyCount + 1);+ for (let i = 0; i < triCount * 3; i += 1) offsets[keyOf(indices[i]) + 1] += 1;+ for (let k = 0; k < keyCount; k += 1) offsets[k + 1] += offsets[k];+ const cursor = offsets.slice(0, keyCount);+ const faces = new Uint32Array(triCount * 3);+ for (let t = 0; t < triCount; t += 1) {+ for (let c = 0; c < 3; c += 1) {+ const k = keyOf(indices[t * 3 + c]);+ faces[cursor[k]++] = t;+ }+ }+ return { offsets, faces };+}++/**+ * Recompute vertex normals with a crease angle.+ *+ * Around every point in space (a POSITION group, so a UV seam is one point),+ * the surrounding faces are clustered into smoothing groups: two faces join a+ * group when their normals are within `creaseDegrees` of each other, and the+ * relation is transitive, so a sphere is one group and a cube corner is three.+ * Each corner of each triangle takes the area-weighted normal of its group.+ *+ * With `split: true` (repair), a vertex whose corners land in different groups+ * is split into one vertex per group, which is how a hard edge is drawn. With+ * `split: false` (smoothing, which must keep the vertex count), such a vertex+ * averages all of its groups, while vertices that were already split keep their+ * own hard edge.+ */+export function computeNormals(mesh, opts = {}) {+ const positions = mesh.attributes.POSITION.array;+ const count = vertexCount(mesh);+ const indices = mesh.indices;+ const triCount = indices.length / 3;+ const groups = opts.groups || positionGroups(positions, weldTolerance(positions, opts.tolerance));+ const cosCrease = Math.cos(((opts.creaseDegrees ?? DEFAULT_CREASE_DEGREES) * Math.PI) / 180);++ const area = new Float64Array(triCount * 3);+ const unit = new Float64Array(triCount * 3);+ for (let t = 0; t < triCount; t += 1) {+ const a = indices[t * 3] * 3;+ const b = indices[t * 3 + 1] * 3;+ const c = indices[t * 3 + 2] * 3;+ const ux = positions[b] - positions[a];+ const uy = positions[b + 1] - positions[a + 1];+ const uz = positions[b + 2] - positions[a + 2];+ const vx = positions[c] - positions[a];+ const vy = positions[c + 1] - positions[a + 1];+ const vz = positions[c + 2] - positions[a + 2];+ const nx = uy * vz - uz * vy;+ const ny = uz * vx - ux * vz;+ const nz = ux * vy - uy * vx;+ area[t * 3] = nx;+ area[t * 3 + 1] = ny;+ area[t * 3 + 2] = nz;+ const len = Math.hypot(nx, ny, nz) || 1;+ unit[t * 3] = nx / len;+ unit[t * 3 + 1] = ny / len;+ unit[t * 3 + 2] = nz / len;+ }++ // For every corner: the smoothed normal of its face's group at that point.+ const corner = new Float32Array(triCount * 9);+ const cornerCluster = new Int32Array(triCount * 3);+ const around = buildIncidence((v) => groups.groupOf[v], groups.groupCount, indices);+ const parent = [];+ const find = (x) => {+ while (parent[x] !== x) {+ parent[x] = parent[parent[x]];+ x = parent[x];+ }+ return x;+ };+ for (let g = 0; g < groups.groupCount; g += 1) {+ const start = around.offsets[g];+ const faces = around.faces.subarray(start, around.offsets[g + 1]);+ const k = faces.length;+ parent.length = k;+ for (let i = 0; i < k; i += 1) parent[i] = i;+ for (let i = 0; i < k; i += 1) {+ const fi = faces[i];+ for (let j = i + 1; j < k; j += 1) {+ const fj = faces[j];+ const dot = unit[fi * 3] * unit[fj * 3] + unit[fi * 3 + 1] * unit[fj * 3 + 1] + unit[fi * 3 + 2] * unit[fj * 3 + 2];+ if (dot >= cosCrease) {+ const ri = find(i);+ const rj = find(j);+ if (ri !== rj) parent[rj] = ri;+ }+ }+ }+ const sums = new Map();+ for (let i = 0; i < k; i += 1) {+ const r = find(i);+ const f = faces[i];+ const s = sums.get(r) || [0, 0, 0];+ s[0] += area[f * 3];+ s[1] += area[f * 3 + 1];+ s[2] += area[f * 3 + 2];+ sums.set(r, s);+ }+ for (let i = 0; i < k; i += 1) {+ const f = faces[i];+ const r = find(i);+ const s = sums.get(r);+ let len = Math.hypot(s[0], s[1], s[2]);+ let n = s;+ if (len === 0) {+ n = [unit[f * 3], unit[f * 3 + 1], unit[f * 3 + 2]];+ len = Math.hypot(n[0], n[1], n[2]) || 1;+ }+ for (let c = 0; c < 3; c += 1) {+ if (groups.groupOf[indices[f * 3 + c]] !== g) continue;+ const slot = f * 3 + c;+ corner[slot * 3] = n[0] / len;+ corner[slot * 3 + 1] = n[1] / len;+ corner[slot * 3 + 2] = n[2] / len;+ cornerCluster[slot] = start + r;+ }+ }+ }++ const previous = mesh.attributes.NORMAL;+ const normalRecord = (array) =>+ previous ? { ...previous, array, itemSize: 3, normalized: false } : { array, itemSize: 3, type: 'VEC3' };++ if (!opts.split) {+ const normals = new Float32Array(count * 3);+ const seen = new Map();+ for (let slot = 0; slot < triCount * 3; slot += 1) {+ const v = indices[slot];+ const key = v * 2 ** 21 + cornerCluster[slot];+ if (seen.has(key)) continue;+ seen.set(key, true);+ normals[v * 3] += corner[slot * 3];+ normals[v * 3 + 1] += corner[slot * 3 + 1];+ normals[v * 3 + 2] += corner[slot * 3 + 2];+ }+ for (let v = 0; v < count; v += 1) {+ const len = Math.hypot(normals[v * 3], normals[v * 3 + 1], normals[v * 3 + 2]);+ if (len === 0) normals[v * 3 + 1] = 1;+ else {+ normals[v * 3] /= len;+ normals[v * 3 + 1] /= len;+ normals[v * 3 + 2] /= len;+ }+ }+ return { mesh: { ...mesh, attributes: { ...mesh.attributes, NORMAL: normalRecord(normals) } }, splitVertices: 0 };+ }++ // Split: the first smoothing group a vertex meets keeps the vertex, every+ // further group gets a copy of it.+ const firstCluster = new Int32Array(count).fill(-1);+ const copies = new Map();+ const sources = [];+ const nextIndices = new Uint32Array(indices.length);+ let total = count;+ for (let slot = 0; slot < triCount * 3; slot += 1) {+ const v = indices[slot];+ const cl = cornerCluster[slot];+ if (firstCluster[v] === -1 || firstCluster[v] === cl) {+ firstCluster[v] = cl;+ nextIndices[slot] = v;+ continue;+ }+ const key = `${v}:${cl}`;+ let copy = copies.get(key);+ if (copy === undefined) {+ copy = total++;+ copies.set(key, copy);+ sources.push(v);+ }+ nextIndices[slot] = copy;+ }+ const extend = (records) => {+ const out = {};+ for (const [name, record] of Object.entries(records)) {+ const { array, itemSize } = record;+ if (!sources.length) {+ out[name] = record;+ continue;+ }+ const next = new array.constructor(total * itemSize);+ next.set(array);+ sources.forEach((src, i) => {+ for (let k = 0; k < itemSize; k += 1) next[(count + i) * itemSize + k] = array[src * itemSize + k];+ });+ out[name] = cloneRecord(record, next);+ }+ return out;+ };+ const attributes = extend(mesh.attributes);+ const normals = new Float32Array(total * 3);+ for (let slot = 0; slot < triCount * 3; slot += 1) {+ const v = nextIndices[slot];+ normals[v * 3] = corner[slot * 3];+ normals[v * 3 + 1] = corner[slot * 3 + 1];+ normals[v * 3 + 2] = corner[slot * 3 + 2];+ }+ attributes.NORMAL = normalRecord(normals);+ return {+ mesh: { ...mesh, indices: nextIndices, attributes, targets: (mesh.targets || []).map(extend) },+ splitVertices: sources.length,+ };+}++// ── repair ──────────────────────────────────────────────────────────────────++/**+ * Topology repair for a rendered (not printed) model: merge duplicate+ * vertices, drop collapsed / zero-area / duplicate faces, make every connected+ * patch wind the same way, turn closed shells outward, and recompute normals.+ * Never resamples the surface and never moves a UV.+ */+export function repairMesh(input, opts = {}) {+ const trianglesBefore = triangleCount(input);+ const verticesBefore = vertexCount(input);+ const welded = weldVertices(input, opts);+ let mesh = welded.mesh;+ const positions = mesh.attributes.POSITION.array;+ const groups = positionGroups(positions, welded.tolerance);+ const areaEpsilon = (welded.tolerance * welded.tolerance) / 2;++ // Faces are judged on position groups: a face whose corners share a point is+ // collapsed even when its UVs differ, and two faces over the same three+ // points are duplicates even when one is the mirror winding of the other.+ const src = mesh.indices;+ const keepAttr = [];+ const keepPos = [];+ const faceSeen = new Set();+ let collapsedFaces = 0;+ let zeroAreaFaces = 0;+ let duplicateFaces = 0;+ for (let t = 0; t + 2 < src.length; t += 3) {+ const a = src[t];+ const b = src[t + 1];+ const c = src[t + 2];+ const ga = groups.groupOf[a];+ const gb = groups.groupOf[b];+ const gc = groups.groupOf[c];+ if (ga === gb || gb === gc || ga === gc) {+ collapsedFaces += 1;+ continue;+ }+ if (triangleArea(positions, a, b, c) <= areaEpsilon) {+ zeroAreaFaces += 1;+ continue;+ }+ const lo = Math.min(ga, gb, gc);+ const hi = Math.max(ga, gb, gc);+ const key = `${lo},${ga + gb + gc - lo - hi},${hi}`;+ if (faceSeen.has(key)) {+ duplicateFaces += 1;+ continue;+ }+ faceSeen.add(key);+ keepAttr.push(a, b, c);+ keepPos.push(ga, gb, gc);+ }++ const attrIndices = Uint32Array.from(keepAttr);+ const posIndices = Uint32Array.from(keepPos);++ // Winding: propagate across shared edges in position space, then mirror+ // every flip onto the attribute index buffer.+ const oriented = orientConsistently(posIndices);+ const triCount = attrIndices.length / 3;+ const flip = (t) => {+ const b = attrIndices[t * 3 + 1];+ attrIndices[t * 3 + 1] = attrIndices[t * 3 + 2];+ attrIndices[t * 3 + 2] = b;+ const pb = oriented.indices[t * 3 + 1];+ oriented.indices[t * 3 + 1] = oriented.indices[t * 3 + 2];+ oriented.indices[t * 3 + 2] = pb;+ };+ for (let t = 0; t < triCount; t += 1) {+ if (oriented.indices[t * 3 + 1] !== posIndices[t * 3 + 1]) {+ const b = attrIndices[t * 3 + 1];+ attrIndices[t * 3 + 1] = attrIndices[t * 3 + 2];+ attrIndices[t * 3 + 2] = b;+ }+ }++ // Outward: a closed shell with negative enclosed volume is inside-out. Open+ // shells (a cape, a leaf) have no inside, so their winding is left alone.+ const topo = edgeTopology(oriented.indices);+ const shells = connectedShells(oriented.indices, topo.edges);+ const shellOf = new Int32Array(triCount);+ shells.forEach((tris, s) => {+ for (const t of tris) shellOf[t] = s;+ });+ const shellOpen = new Uint8Array(shells.length);+ for (const list of topo.edges.values()) {+ if (list.length === 1) shellOpen[shellOf[list[0]]] = 1;+ }+ let reversedShells = 0;+ shells.forEach((tris, s) => {+ if (shellOpen[s]) return;+ const local = new Uint32Array(tris.length * 3);+ tris.forEach((t, i) => {+ local[i * 3] = attrIndices[t * 3];+ local[i * 3 + 1] = attrIndices[t * 3 + 1];+ local[i * 3 + 2] = attrIndices[t * 3 + 2];+ });+ if (signedVolume(positions, local) < 0) {+ for (const t of tris) flip(t);+ reversedShells += 1;+ }+ });++ mesh = { ...mesh, indices: attrIndices };+ const compacted = compactMesh(mesh);+ mesh = compacted.mesh;+ const shaded = computeNormals(mesh, { creaseDegrees: opts.creaseDegrees, tolerance: welded.tolerance, split: true });+ mesh = shaded.mesh;+ const after = edgeTopology(positionIndexBuffer(mesh, welded.tolerance));++ return {+ mesh,+ stats: {+ trianglesBefore,+ trianglesAfter: triangleCount(mesh),+ verticesBefore,+ verticesAfter: vertexCount(mesh),+ mergedVertices: welded.merged,+ collapsedFaces,+ zeroAreaFaces,+ duplicateFaces,+ flippedFaces: oriented.flipped,+ reversedShells,+ hardEdgeVertices: shaded.splitVertices,+ openEdges: after.openEdges,+ nonManifoldEdges: after.nonManifoldEdges,+ },+ };+}++function positionIndexBuffer(mesh, tolerance) {+ const { groupOf } = positionGroups(mesh.attributes.POSITION.array, tolerance);+ const out = new Uint32Array(mesh.indices.length);+ for (let i = 0; i < out.length; i += 1) out[i] = groupOf[mesh.indices[i]];+ return out;+}++// ── smoothing ───────────────────────────────────────────────────────────────++/**+ * Taubin's second (inflating) factor for a given shrink factor and passband.+ * mu = 1 / (kpb - 1/lambda). With lambda 0.5 and kpb 0.1 this is about -0.526,+ * the classic pairing that smooths noise without the volume loss plain+ * Laplacian smoothing causes.+ */+export function taubinMu(lambda, passband = SMOOTH_DEFAULTS.passband) {+ return 1 / (passband - 1 / lambda);+}++/**+ * Laplacian or Taubin smoothing with uniform weights over position groups.+ * Only positions (and recomputed normals) change: vertex count, index buffer,+ * UVs, colours, skin weights and morph targets are untouched, so the texture+ * stays exactly where it was painted. Boundary rims are pinned by default so an+ * open edge does not creep inward iteration after iteration.+ */+export function smoothMesh(input, opts = {}) {+ const method = opts.method === 'laplacian' ? 'laplacian' : 'taubin';+ const iterations = Math.max(1, Math.min(200, Math.round(opts.iterations ?? SMOOTH_DEFAULTS.iterations)));+ const lambda = Math.max(0.01, Math.min(1, Number(opts.lambda ?? SMOOTH_DEFAULTS.lambda)));+ const passband = Math.max(0.01, Math.min(0.5, Number(opts.passband ?? SMOOTH_DEFAULTS.passband)));+ const mu = method === 'taubin' ? taubinMu(lambda, passband) : 0;+ const preserveBoundary = opts.preserveBoundary ?? SMOOTH_DEFAULTS.preserveBoundary;++ const positions = input.attributes.POSITION.array;+ const diag = bboxDiagonal(positions) || 1;+ const tolerance = weldTolerance(positions, opts.tolerance);+ const groups = positionGroups(positions, tolerance);+ const G = groups.groupCount;+ const count = vertexCount(input);++ const current = new Float64Array(G * 3);+ const seeded = new Uint8Array(G);+ for (let v = 0; v < count; v += 1) {+ const g = groups.groupOf[v];+ if (seeded[g]) continue;+ seeded[g] = 1;+ current[g * 3] = positions[v * 3];+ current[g * 3 + 1] = positions[v * 3 + 1];+ current[g * 3 + 2] = positions[v * 3 + 2];+ }+ const original = current.slice();++ // Neighbour lists over position groups, plus which groups sit on a rim.+ const posIndices = new Uint32Array(input.indices.length);+ for (let i = 0; i < posIndices.length; i += 1) posIndices[i] = groups.groupOf[input.indices[i]];+ const topo = edgeTopology(posIndices);+ const degree = new Uint32Array(G + 1);+ const pinned = new Uint8Array(G);+ const edgeList = [];+ for (const [key, faces] of topo.edges) {+ const a = Math.floor(key / 2 ** 26);+ const b = key - a * 2 ** 26;+ if (a === b) continue;+ edgeList.push(a, b);+ degree[a + 1] += 1;+ degree[b + 1] += 1;+ if (preserveBoundary && faces.length === 1) {+ pinned[a] = 1;+ pinned[b] = 1;+ }+ }+ for (let g = 0; g < G; g += 1) degree[g + 1] += degree[g];+ const neighbours = new Uint32Array(edgeList.length);+ const cursor = degree.slice(0, G);+ for (let i = 0; i < edgeList.length; i += 2) {+ const a = edgeList[i];+ const b = edgeList[i + 1];+ neighbours[cursor[a]++] = b;+ neighbours[cursor[b]++] = a;+ }++ const scratch = new Float64Array(G * 3);+ const step = (factor) => {+ for (let g = 0; g < G; g += 1) {+ const start = degree[g];+ const end = degree[g + 1];+ if (pinned[g] || end === start) {+ scratch[g * 3] = current[g * 3];+ scratch[g * 3 + 1] = current[g * 3 + 1];+ scratch[g * 3 + 2] = current[g * 3 + 2];+ continue;+ }+ let sx = 0;+ let sy = 0;+ let sz = 0;+ for (let i = start; i < end; i += 1) {+ const n = neighbours[i];+ sx += current[n * 3];+ sy += current[n * 3 + 1];+ sz += current[n * 3 + 2];+ }+ const k = 1 / (end - start);+ scratch[g * 3] = current[g * 3] + factor * (sx * k - current[g * 3]);+ scratch[g * 3 + 1] = current[g * 3 + 1] + factor * (sy * k - current[g * 3 + 1]);+ scratch[g * 3 + 2] = current[g * 3 + 2] + factor * (sz * k - current[g * 3 + 2]);+ }+ current.set(scratch);+ };+ for (let i = 0; i < iterations; i += 1) {+ step(lambda);+ if (method === 'taubin') step(mu);+ }++ const next = new positions.constructor(positions.length);+ for (let v = 0; v < count; v += 1) {+ const g = groups.groupOf[v];+ next[v * 3] = current[g * 3];+ next[v * 3 + 1] = current[g * 3 + 1];+ next[v * 3 + 2] = current[g * 3 + 2];+ }+ let maxMove = 0;+ let sumMove = 0;+ let moved = 0;+ for (let g = 0; g < G; g += 1) {+ const d = Math.hypot(+ current[g * 3] - original[g * 3],+ current[g * 3 + 1] - original[g * 3 + 1],+ current[g * 3 + 2] - original[g * 3 + 2],+ );+ if (d > 0) moved += 1;+ sumMove += d;+ if (d > maxMove) maxMove = d;+ }++ const volumeBefore = signedVolume(positions, input.indices);+ let mesh = {+ ...input,+ attributes: { ...input.attributes, POSITION: { ...input.attributes.POSITION, array: next } },+ };+ const volumeAfter = signedVolume(next, input.indices);+ if (input.attributes.NORMAL) mesh = computeNormals(mesh, { groups, creaseDegrees: opts.creaseDegrees }).mesh;++ return {+ mesh,+ stats: {+ method,+ iterations,+ lambda,+ mu,+ triangles: triangleCount(mesh),+ vertices: count,+ movedPoints: moved,+ pinnedPoints: pinned.reduce((s, p) => s + p, 0),+ maxDisplacement: maxMove / diag,+ meanDisplacement: G ? sumMove / G / diag : 0,+ volumeChange: Math.abs(volumeBefore) > 0 ? (volumeAfter - volumeBefore) / Math.abs(volumeBefore) : 0,+ },+ };+}++// ── decimation ──────────────────────────────────────────────────────────────++/**+ * Resolve a decimation request to a whole triangle target. `ratio` is the+ * fraction of triangles to keep; `targetTriangles` wins when both are given.+ */+export function resolveTarget(currentTriangles, { targetTriangles, ratio } = {}) {+ let target = Number(targetTriangles);+ if (!(target > 0)) {+ const r = Number(ratio);+ target = r > 0 ? currentTriangles * Math.min(1, r) : currentTriangles;+ }+ return Math.max(1, Math.min(currentTriangles, Math.round(target)));+}++/**+ * Quadric decimation through meshoptimizer, the same library Modly drives.+ * The primitive is welded first (losslessly: only identical vertices merge),+ * because a simplifier can only collapse edges that are actually shared.+ *+ * `simplifier` is meshoptimizer's MeshoptSimplifier after `await .ready`. It is+ * passed in rather than imported so this module stays free of WASM and can be+ * unit tested against the real library without a bundler.+ *+ * A first pass keeps UV seams and attribute borders locked, which is what keeps+ * a texture undistorted. Only when the seams alone stop it short of the target+ * does a second, permissive pass let collapses cross them; the stats say so.+ */+export function decimateMesh(input, opts = {}) {+ const { simplifier } = opts;+ if (!simplifier || typeof simplifier.simplify !== 'function') {+ throw new TypeError('decimateMesh needs MeshoptSimplifier (after `await MeshoptSimplifier.ready`)');+ }+ const trianglesBefore = triangleCount(input);+ const target = resolveTarget(trianglesBefore, opts);+ if (target >= trianglesBefore) {+ return { mesh: input, stats: { trianglesBefore, trianglesAfter: trianglesBefore, target, error: 0, seamsRelaxed: false } };+ }+ const welded = weldVertices(input).mesh;+ const positions = Float32Array.from(welded.attributes.POSITION.array);+ const indices = Uint32Array.from(welded.indices);+ const targetIndexCount = target * 3;+ const maxError = opts.maxError ?? 1;++ const normals = welded.attributes.NORMAL;+ const run = (flags) => {+ if (normals && typeof simplifier.simplifyWithAttributes === 'function') {+ return simplifier.simplifyWithAttributes(+ indices,+ positions,+ 3,+ Float32Array.from(normals.array),+ 3,+ [0.5, 0.5, 0.5],+ null,+ targetIndexCount,+ maxError,+ flags,+ );+ }+ return simplifier.simplify(indices, positions, 3, targetIndexCount, maxError, flags);+ };++ let [out, error] = run([]);+ let seamsRelaxed = false;+ if (out.length / 3 > target * 1.05) {+ const [relaxed, relaxedError] = run(['Permissive']);+ if (relaxed.length < out.length) {+ out = relaxed;+ error = relaxedError;+ seamsRelaxed = true;+ }+ }++ const { mesh } = compactMesh({ ...welded, indices: Uint32Array.from(out) });+ return {+ mesh,+ stats: {+ trianglesBefore,+ trianglesAfter: triangleCount(mesh),+ verticesBefore: vertexCount(input),+ verticesAfter: vertexCount(mesh),+ target,+ error,+ seamsRelaxed,+ },+ };+}diff --git a/src/mesh-ops/gltf.js b/src/mesh-ops/gltf.jsnew file mode 100644index 000000000..674f363fa--- /dev/null+++ b/src/mesh-ops/gltf.js@@ -0,0 +1,201 @@+// glTF document layer for the mesh operations in ./core.js.+//+// Reads every triangle primitive of a glTF-Transform Document into the plain+// shape core.js speaks, runs one operation, and writes the result back as fresh+// accessors. Materials, textures, skins, animations and the node hierarchy are+// never touched, which is the whole point of operating on the document rather+// than re-exporting a three.js scene: the texture bytes that come out are the+// texture bytes that went in.+//+// Shared by the browser worker (./worker.js) and the vitest suite, so it+// imports nothing that needs a DOM.++import { decimateMesh, repairMesh, smoothMesh, triangleCount } from './core.js';++const TRIANGLES = 4;++function isTriangles(prim) {+ const mode = prim.getMode();+ return mode === undefined || mode === null || mode === TRIANGLES;+}++function readRecord(accessor) {+ return {+ array: accessor.getArray().slice(),+ itemSize: accessor.getElementSize(),+ type: accessor.getType(),+ normalized: accessor.getNormalized(),+ };+}++/** One triangle primitive as core.js mesh data, or null for points/lines. */+export function readPrimitive(prim) {+ if (!isTriangles(prim)) return null;+ const position = prim.getAttribute('POSITION');+ if (!position) return null;+ const attributes = {};+ for (const semantic of prim.listSemantics()) attributes[semantic] = readRecord(prim.getAttribute(semantic));+ const count = position.getCount();+ const source = prim.getIndices();+ let indices;+ if (source) {+ indices = Uint32Array.from(source.getArray());+ } else {+ indices = new Uint32Array(count);+ for (let i = 0; i < count; i += 1) indices[i] = i;+ }+ if (indices.length % 3) indices = indices.subarray(0, indices.length - (indices.length % 3));+ const targets = prim.listTargets().map((target) => {+ const out = {};+ for (const semantic of target.listSemantics()) out[semantic] = readRecord(target.getAttribute(semantic));+ return out;+ });+ return { indices, attributes, targets };+}++function disposeIfOrphaned(accessor) {+ if (!accessor || accessor.isDisposed()) return;+ const users = accessor.listParents().filter((p) => p.propertyType !== 'Root');+ if (users.length === 0) accessor.dispose();+}++function makeAccessor(doc, buffer, record) {+ const accessor = doc+ .createAccessor()+ .setType(record.type || (record.itemSize === 1 ? 'SCALAR' : `VEC${record.itemSize}`))+ .setArray(record.array)+ .setBuffer(buffer);+ if (record.normalized) accessor.setNormalized(true);+ return accessor;+}++/** Replace a primitive's geometry with `mesh`, disposing accessors left unused. */+export function writePrimitive(doc, prim, mesh) {+ const buffer = doc.getRoot().listBuffers()[0] || doc.createBuffer();+ const old = new Set();+ for (const semantic of prim.listSemantics()) old.add(prim.getAttribute(semantic));+ if (prim.getIndices()) old.add(prim.getIndices());++ for (const semantic of prim.listSemantics()) {+ if (!mesh.attributes[semantic]) prim.setAttribute(semantic, null);+ }+ for (const [semantic, record] of Object.entries(mesh.attributes)) {+ prim.setAttribute(semantic, makeAccessor(doc, buffer, record));+ }+ const vertexTotal = mesh.attributes.POSITION.array.length / 3;+ const indexArray = vertexTotal <= 65535 ? Uint16Array.from(mesh.indices) : Uint32Array.from(mesh.indices);+ prim.setIndices(doc.createAccessor().setType('SCALAR').setArray(indexArray).setBuffer(buffer));++ const targets = prim.listTargets();+ targets.forEach((target, i) => {+ const records = mesh.targets?.[i] || {};+ for (const semantic of target.listSemantics()) {+ old.add(target.getAttribute(semantic));+ const record = records[semantic];+ target.setAttribute(semantic, record ? makeAccessor(doc, buffer, record) : null);+ }+ });+ for (const accessor of old) disposeIfOrphaned(accessor);+}++function trianglePrimitives(doc) {+ const out = [];+ for (const mesh of doc.getRoot().listMeshes()) {+ for (const prim of mesh.listPrimitives()) if (isTriangles(prim) && prim.getAttribute('POSITION')) out.push(prim);+ }+ return out;+}++function primitiveTriangles(prim) {+ const indices = prim.getIndices();+ const count = indices ? indices.getCount() : prim.getAttribute('POSITION').getCount();+ return Math.floor(count / 3);+}++/** Total triangles drawn by every triangle primitive in the document. */+export function countTriangles(doc) {+ let total = 0;+ for (const prim of trianglePrimitives(doc)) total += primitiveTriangles(prim);+ return total;+}++const SUM_KEYS = [+ 'trianglesBefore',+ 'trianglesAfter',+ 'verticesBefore',+ 'verticesAfter',+ 'mergedVertices',+ 'collapsedFaces',+ 'zeroAreaFaces',+ 'duplicateFaces',+ 'flippedFaces',+ 'reversedShells',+ 'hardEdgeVertices',+ 'openEdges',+ 'nonManifoldEdges',+ 'movedPoints',+ 'pinnedPoints',+];++function mergeStats(total, stats) {+ for (const key of SUM_KEYS) {+ if (typeof stats[key] === 'number') total[key] = (total[key] || 0) + stats[key];+ }+ if (typeof stats.maxDisplacement === 'number') total.maxDisplacement = Math.max(total.maxDisplacement || 0, stats.maxDisplacement);+ if (typeof stats.error === 'number') total.error = Math.max(total.error || 0, stats.error);+ if (stats.seamsRelaxed) total.seamsRelaxed = true;+ for (const key of ['method', 'iterations', 'lambda', 'mu']) if (key in stats) total[key] = stats[key];+}++export const OPERATIONS = Object.freeze(['repair', 'smooth', 'decimate']);++/**+ * Run one operation across every triangle primitive. Decimation targets are+ * distributed in proportion to each primitive's share of the triangles, so a+ * request for "20,000 triangles" means the whole model, not each part.+ *+ * @param {import('@gltf-transform/core').Document} doc+ * @param {'repair'|'smooth'|'decimate'} op+ * @param {object} params operation options from core.js+ * @param {{ simplifier?: object }} deps MeshoptSimplifier for decimation+ */+export function applyMeshOp(doc, op, params = {}, deps = {}) {+ if (!OPERATIONS.includes(op)) throw new RangeError(`unknown mesh operation "${op}"`);+ const prims = trianglePrimitives(doc);+ const before = countTriangles(doc);+ const totals = { op, primitives: prims.length, trianglesBefore: 0, trianglesAfter: 0 };+ if (!prims.length) return { ...totals, trianglesBefore: before, trianglesAfter: before };++ let ratio = 1;+ if (op === 'decimate') {+ const target = Number(params.targetTriangles) > 0 ? Number(params.targetTriangles) : before * Number(params.ratio || 1);+ ratio = Math.max(0, Math.min(1, target / Math.max(1, before)));+ totals.target = Math.max(1, Math.round(Math.min(before, target)));+ }++ for (const prim of prims) {+ const mesh = readPrimitive(prim);+ if (!mesh || triangleCount(mesh) === 0) continue;+ let result;+ if (op === 'repair') result = repairMesh(mesh, params);+ else if (op === 'smooth') result = smoothMesh(mesh, params);+ else {+ const own = triangleCount(mesh);+ result = decimateMesh(mesh, {+ targetTriangles: Math.max(1, Math.round(own * ratio)),+ maxError: params.maxError,+ simplifier: deps.simplifier,+ });+ }+ writePrimitive(doc, prim, result.mesh);+ const stats = { ...result.stats };+ if (op === 'smooth') {+ stats.trianglesBefore = stats.triangles;+ stats.trianglesAfter = stats.triangles;+ }+ mergeStats(totals, stats);+ }+ totals.trianglesBefore = before;+ totals.trianglesAfter = countTriangles(doc);+ return totals;+}diff --git a/src/mesh-ops/panel.js b/src/mesh-ops/panel.jsnew file mode 100644index 000000000..932127954--- /dev/null+++ b/src/mesh-ops/panel.js@@ -0,0 +1,632 @@+// In-browser mesh tools: repair, smooth and decimate any GLB, with undo.+//+// One component, mounted by every surface that shows a model: the forge result+// panel (src/forge-optimize.js and its forge-studio twin) and the model page+// (src/model-page.js). The host hands it a source URL; the panel fetches the+// bytes the first time it is opened, runs every operation in a module worker+// (./client.js), and reports each new version through `onChange` so the host+// can swap its viewer and its download button. Nothing leaves the browser.+//+// History is a stack of GLB versions. Undo pops one, "Reset to original" drops+// to the first, and every version keeps its triangle count so the before/after+// line is exact rather than estimated.+//+// Usage:+// const tools = mountMeshTools(host, { onChange: ({ url, edited }) => ... });+// tools.setSource('https://.../model.glb', { label: 'my model' });+// tools.activate(); // start fetching; call when the panel becomes visible++import { inspect, run } from './client.js';++const HISTORY_LIMIT = 10;+const MAX_SOURCE_BYTES = 150 * 1024 * 1024;++const OPS = {+ repair: {+ label: 'Repair',+ verb: 'Repairing',+ hint: 'Welds duplicate vertices, drops collapsed and duplicate faces, makes the winding consistent and points every shell outward, then rebuilds normals. Edges sharper than the crease angle stay hard.',+ },+ smooth: {+ label: 'Smooth',+ verb: 'Smoothing',+ hint: 'Relaxes surface noise without changing the vertex count, so UVs and textures stay put. Taubin keeps the volume; Laplacian shrinks it and suits heavy noise.',+ },+ decimate: {+ label: 'Decimate',+ verb: 'Decimating',+ hint: 'Collapses the edges that change the shape least until the triangle budget is met. UV seams are respected, so textures keep mapping.',+ },+};++const PHASES = { reading: 'Reading the model', processing: 'Processing geometry', writing: 'Writing the GLB' };++const fmt = (n) => (Number.isFinite(n) ? Math.round(n).toLocaleString() : '0');++function injectStyles() {+ if (document.getElementById('mesh-tools-styles')) return;+ const style = document.createElement('style');+ style.id = 'mesh-tools-styles';+ style.textContent = `+ .mt { display: flex; flex-direction: column; gap: var(--space-sm, 0.6rem); }+ .mt-head { display: flex; align-items: baseline; justify-content: space-between; gap: var(--space-sm, 0.6rem); flex-wrap: wrap; }+ .mt-title { font-family: var(--font-display, inherit); font-weight: 600; font-size: var(--text-sm, 0.9rem); color: var(--ink, #eee); }+ .mt-tag { font-family: var(--font-mono, monospace); font-size: var(--text-xs, 0.75rem); color: var(--ink-dim, #999); }+ .mt-tabs {+ display: inline-flex; gap: 2px; padding: 2px; align-self: flex-start;+ background: var(--surface-1, #16161d); border: 1px solid var(--stroke, rgba(255,255,255,0.12)); border-radius: var(--radius-md, 8px);+ }+ .mt-tab {+ background: transparent; border: 0; color: var(--ink-dim, #999); cursor: pointer;+ font-family: var(--font-mono, monospace); font-size: var(--text-xs, 0.75rem); padding: 0.4rem 0.8rem;+ border-radius: var(--radius-sm, 6px); transition: background 0.15s ease, color 0.15s ease;+ }+ .mt-tab:hover { color: var(--ink, #eee); }+ .mt-tab[aria-selected='true'] { background: var(--surface-3, rgba(255,255,255,0.1)); color: var(--ink, #eee); }+ .mt-tab:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: 2px; }+ .mt-pane { display: flex; flex-direction: column; gap: var(--space-sm, 0.6rem); }+ .mt-pane[hidden] { display: none; }+ .mt-hint { margin: 0; font-size: var(--text-xs, 0.75rem); color: var(--ink-dim, #999); line-height: 1.45; }+ .mt-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: var(--space-sm, 0.6rem) var(--space-md, 1rem); }+ .mt-field { display: flex; flex-direction: column; gap: 0.3rem; min-width: 0; }+ .mt-field > span, .mt-field > label {+ display: flex; justify-content: space-between; gap: 0.5rem;+ font-family: var(--font-mono, monospace); font-size: var(--text-xs, 0.75rem); color: var(--ink-dim, #999);+ text-transform: uppercase; letter-spacing: 0.04em;+ }+ .mt-field output { color: var(--ink, #eee); text-transform: none; letter-spacing: 0; }+ .mt-range { width: 100%; accent-color: var(--accent, #7c6cff); cursor: pointer; }+ .mt-range:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: 3px; border-radius: 4px; }+ .mt-number, .mt-select {+ background: var(--surface-1, #16161d); border: 1px solid var(--stroke, rgba(255,255,255,0.12)); border-radius: var(--radius-md, 8px);+ color: var(--ink, #eee); font-family: var(--font-mono, monospace); font-size: var(--text-xs, 0.75rem); padding: 0.45rem 0.6rem; width: 100%;+ transition: border-color 0.15s ease;+ }+ .mt-number:hover, .mt-select:hover { border-color: var(--stroke-strong, rgba(255,255,255,0.24)); }+ .mt-number:focus-visible, .mt-select:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: 1px; }+ .mt-check { display: inline-flex; align-items: center; gap: 0.45rem; font-size: var(--text-xs, 0.75rem); color: var(--ink, #eee); cursor: pointer; }+ .mt-check input { accent-color: var(--accent, #7c6cff); }+ .mt-check input:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: 2px; }+ .mt-preview { font-family: var(--font-mono, monospace); font-size: var(--text-xs, 0.75rem); color: var(--ink-dim, #999); }+ .mt-preview strong { color: var(--ink, #eee); font-weight: 600; }+ .mt-actions { display: flex; align-items: center; gap: var(--space-sm, 0.6rem); flex-wrap: wrap; }+ .mt-btn {+ display: inline-flex; align-items: center; gap: 0.4rem; cursor: pointer; text-decoration: none;+ background: var(--surface-1, #16161d); color: var(--ink, #eee); border: 1px solid var(--stroke, rgba(255,255,255,0.12));+ border-radius: var(--radius-md, 8px); padding: 0.45rem 0.8rem; font-family: var(--font-body, inherit); font-size: var(--text-xs, 0.78rem);+ transition: border-color 0.15s ease, background 0.15s ease, transform 0.15s ease, opacity 0.15s ease;+ }+ .mt-btn:hover:not(:disabled):not([aria-disabled='true']) { border-color: var(--stroke-strong, rgba(255,255,255,0.24)); background: var(--surface-2, rgba(255,255,255,0.06)); }+ .mt-btn:active:not(:disabled) { transform: translateY(1px); }+ .mt-btn:focus-visible { outline: 2px solid var(--accent, #7c6cff); outline-offset: 2px; }+ .mt-btn:disabled, .mt-btn[aria-disabled='true'] { opacity: 0.45; cursor: not-allowed; }+ .mt-btn.is-primary { background: var(--accent, #7c6cff); border-color: var(--accent, #7c6cff); color: var(--bg-0, #0a0a0a); font-weight: 600; }+ .mt-btn.is-primary:hover:not(:disabled) { background: var(--accent, #7c6cff); filter: brightness(1.08); }+ .mt-spinner {+ width: 0.85em; height: 0.85em; border: 2px solid currentColor; border-right-color: transparent;+ border-radius: 50%; animation: mt-spin 0.7s linear infinite;+ }+ @keyframes mt-spin { to { transform: rotate(360deg); } }+ .mt-status { font-family: var(--font-mono, monospace); font-size: var(--text-xs, 0.75rem); color: var(--ink-dim, #999); min-height: 1.2em; }+ .mt-status[data-kind='error'] { color: var(--danger, #ff6b6b); }+ .mt-status[data-kind='done'] { color: var(--success, #3ecf8e); }+ .mt-counts {+ display: flex; align-items: baseline; gap: 0.5rem; flex-wrap: wrap;+ font-family: var(--font-mono, monospace); font-size: var(--text-xs, 0.75rem); color: var(--ink-dim, #999);+ }+ .mt-counts strong { color: var(--ink, #eee); font-weight: 600; }+ .mt-counts .mt-delta { color: var(--success, #3ecf8e); }+ .mt-counts .mt-delta.is-up { color: var(--warning, #f5a524); }+ .mt-details { display: flex; flex-wrap: wrap; gap: 0.35rem; margin: 0; padding: 0; list-style: none; }+ .mt-details li {+ font-family: var(--font-mono, monospace); font-size: var(--text-2xs, 0.7rem); color: var(--ink-dim, #999);+ border: 1px solid var(--stroke, rgba(255,255,255,0.12)); border-radius: 999px; padding: 0.15rem 0.55rem;+ }+ .mt-details li strong { color: var(--ink, #eee); font-weight: 600; }+ .mt-history { display: flex; flex-wrap: wrap; align-items: center; gap: 0.3rem; font-size: var(--text-2xs, 0.7rem); color: var(--ink-dim, #999); font-family: var(--font-mono, monospace); }+ .mt-history span + span::before { content: '\\2192'; margin-right: 0.3rem; opacity: 0.6; }+ .mt-skeleton {+ height: 1.2rem; border-radius: var(--radius-md, 8px);+ background: linear-gradient(90deg, var(--surface-1, #16161d) 0%, var(--surface-2, rgba(255,255,255,0.06)) 50%, var(--surface-1, #16161d) 100%);+ background-size: 200% 100%; animation: mt-shimmer 1.2s ease-in-out infinite;+ }+ @keyframes mt-shimmer { from { background-position: 100% 0; } to { background-position: -100% 0; } }+ .mt[data-busy='true'] .mt-pane { opacity: 0.6; pointer-events: none; transition: opacity 0.15s ease; }+ @media (prefers-reduced-motion: reduce) {+ .mt-spinner { animation-duration: 1.6s; }+ .mt-skeleton { animation: none; }+ }+ `;+ document.head.appendChild(style);+}++let uid = 0;++function template(id) {+ const tab = (op, selected) => `+ <button class="mt-tab" type="button" role="tab" id="${id}-tab-${op}" data-op="${op}"+ aria-controls="${id}-pane-${op}" aria-selected="${selected}" tabindex="${selected ? 0 : -1}">${OPS[op].label}</button>`;+ return `+ <div class="mt-head">+ <span class="mt-title">Mesh tools</span>+ <span class="mt-tag">runs in your browser, nothing is uploaded</span>+ </div>+ <div class="mt-tabs" role="tablist" aria-label="Mesh operation">+ ${tab('repair', true)}${tab('smooth', false)}${tab('decimate', false)}+ </div>+ <div class="mt-pane" role="tabpanel" id="${id}-pane-repair" aria-labelledby="${id}-tab-repair" data-op="repair">+ <p class="mt-hint">${OPS.repair.hint}</p>+ <div class="mt-grid">+ <div class="mt-field">+ <label for="${id}-crease">Crease angle <output for="${id}-crease" data-out="crease">60°</output></label>+ <input class="mt-range" id="${id}-crease" type="range" min="0" max="180" step="5" value="60" data-param="crease" />+ </div>+ </div>+ </div>+ <div class="mt-pane" role="tabpanel" id="${id}-pane-smooth" aria-labelledby="${id}-tab-smooth" data-op="smooth" hidden>+ <p class="mt-hint">${OPS.smooth.hint}</p>+ <div class="mt-grid">+ <div class="mt-field">+ <label for="${id}-method">Method</label>+ <select class="mt-select" id="${id}-method" data-param="method">+ <option value="taubin" selected>Taubin (keeps volume)</option>+ <option value="laplacian">Laplacian</option>+ </select>+ </div>+ <div class="mt-field">+ <label for="${id}-iterations">Iterations <output for="${id}-iterations" data-out="iterations">10</output></label>+ <input class="mt-range" id="${id}-iterations" type="range" min="1" max="50" step="1" value="10" data-param="iterations" />+ </div>+ <div class="mt-field">+ <label for="${id}-lambda">Strength (λ) <output for="${id}-lambda" data-out="lambda">0.50</output></label>+ <input class="mt-range" id="${id}-lambda" type="range" min="0.05" max="1" step="0.05" value="0.5" data-param="lambda" />+ </div>+ </div>+ <label class="mt-check"><input type="checkbox" data-param="preserveBoundary" checked /> Keep open borders fixed</label>+ </div>+ <div class="mt-pane" role="tabpanel" id="${id}-pane-decimate" aria-labelledby="${id}-tab-decimate" data-op="decimate" hidden>+ <p class="mt-hint">${OPS.decimate.hint}</p>+ <div class="mt-grid">+ <div class="mt-field">+ <label for="${id}-ratio">Keep <output for="${id}-ratio" data-out="ratio">50%</output></label>+ <input class="mt-range" id="${id}-ratio" type="range" min="1" max="100" step="1" value="50" data-param="ratio" />+ </div>+ <div class="mt-field">+ <label for="${id}-target">Target triangles</label>+ <input class="mt-number" id="${id}-target" type="number" min="4" step="1" inputmode="numeric" data-param="target" />+ </div>+ </div>+ <div class="mt-preview" data-role="preview" aria-live="polite"></div>+ </div>+ <div class="mt-actions">+ <button class="mt-btn is-primary" type="button" data-action="apply">Apply repair</button>+ <button class="mt-btn" type="button" data-action="undo" disabled title="Undo (Ctrl+Z)">Undo</button>+ <button class="mt-btn" type="button" data-action="reset" disabled>Reset to original</button>+ <a class="mt-btn" data-action="download" aria-disabled="true" role="link">Download GLB</a>+ </div>+ <div class="mt-status" role="status" aria-live="polite"></div>+ <div class="mt-counts" data-role="counts" hidden></div>+ <ul class="mt-details" data-role="details" hidden></ul>+ <div class="mt-history" data-role="history" hidden></div>+ `;+}++function safeName(label) {+ return String(label || 'model').replace(/[^a-z0-9]+/gi, '-').slice(0, 48).replace(/^-|-$/g, '') || 'model';+}++function describe(stats) {+ const items = [];+ const add = (n, text) => {+ if (n > 0) items.push(`<li><strong>${fmt(n)}</strong> ${text}</li>`);+ };+ if (stats.op === 'repair') {+ add(stats.mergedVertices, 'vertices welded');+ add(stats.collapsedFaces + stats.zeroAreaFaces, 'degenerate faces removed');+ add(stats.duplicateFaces, 'duplicate faces removed');+ add(stats.flippedFaces, 'faces re-wound');+ add(stats.reversedShells, 'inside-out shells flipped');+ add(stats.hardEdgeVertices, 'vertices split for hard edges');+ if (stats.openEdges > 0) items.push(`<li><strong>${fmt(stats.openEdges)}</strong> open edges remain</li>`);+ if (stats.nonManifoldEdges > 0) items.push(`<li><strong>${fmt(stats.nonManifoldEdges)}</strong> non-manifold edges remain</li>`);+ if (!items.length) items.push('<li>Nothing needed fixing: the mesh was already clean</li>');+ } else if (stats.op === 'smooth') {+ items.push(`<li>${stats.method === 'laplacian' ? 'Laplacian' : 'Taubin'} × <strong>${fmt(stats.iterations)}</strong></li>`);+ add(stats.movedPoints, 'points moved');+ add(stats.pinnedPoints, 'border points pinned');+ if (typeof stats.maxDisplacement === 'number') {+ items.push(`<li>max shift <strong>${(stats.maxDisplacement * 100).toFixed(2)}%</strong> of size</li>`);+ }+ } else if (stats.op === 'decimate') {+ if (typeof stats.error === 'number') items.push(`<li>shape error <strong>${(stats.error * 100).toFixed(2)}%</strong></li>`);+ if (stats.seamsRelaxed) items.push('<li>UV seams relaxed to reach the budget</li>');+ }+ return items.join('');+}++/**+ * @param {HTMLElement} host element the tools render into+ * @param {{ onChange?: (v: { url: string, edited: boolean, triangles: number, op: string|null, filename: string }) => void }} opts+ */+export function mountMeshTools(host, { onChange } = {}) {+ injectStyles();+ const id = `mt${++uid}`;+ const root = document.createElement('div');+ root.className = 'mt';+ root.innerHTML = template(id);+ host.appendChild(root);++ const q = (sel) => root.querySelector(sel);+ const tabs = [...root.querySelectorAll('.mt-tab')];+ const panes = [...root.querySelectorAll('.mt-pane')];+ const applyBtn = q('[data-action="apply"]');+ const undoBtn = q('[data-action="undo"]');+ const resetBtn = q('[data-action="reset"]');+ const downloadLink = q('[data-action="download"]');+ const statusEl = q('.mt-status');+ const countsEl = q('[data-role="counts"]');+ const detailsEl = q('[data-role="details"]');+ const historyEl = q('[data-role="history"]');+ const previewEl = q('[data-role="preview"]');+ const input = (name) => q(`[data-param="${name}"]`);+ const output = (name) => q(`[data-out="${name}"]`);++ const state = {+ op: 'repair',+ sourceUrl: null,+ label: 'model',+ history: [], // [{ bytes, triangles, op, stats, url }]+ loading: null,+ failed: false,+ busy: false,+ token: 0,+ };++ const current = () => state.history[state.history.length - 1] || null;++ function setStatus(text, kind) {+ statusEl.textContent = text || '';+ if (kind) statusEl.dataset.kind = kind;+ else statusEl.removeAttribute('data-kind');+ }++ function setBusy(busy, label) {+ state.busy = busy;+ root.dataset.busy = String(busy);+ applyBtn.disabled = busy || !state.sourceUrl;+ applyBtn.innerHTML = busy ? `<span class="mt-spinner" aria-hidden="true"></span> ${label}…` : `Apply ${OPS[state.op].label.toLowerCase()}`;+ syncButtons();+ }++ function filename() {+ const steps = state.history.slice(1).map((v) => v.op);+ const suffix = steps.length ? `-${[...new Set(steps)].join('-')}` : '';+ return `${safeName(state.label)}${suffix}.glb`;+ }++ function syncButtons() {+ const edits = state.history.length - 1;+ undoBtn.disabled = state.busy || edits < 1;+ resetBtn.disabled = state.busy || edits < 1;+ const v = current();+ const href = v?.url || state.sourceUrl;+ if (href && !state.busy) {+ downloadLink.href = href;+ downloadLink.setAttribute('download', filename());+ downloadLink.removeAttribute('aria-disabled');+ downloadLink.removeAttribute('role');+ } else {+ downloadLink.removeAttribute('href');+ downloadLink.setAttribute('aria-disabled', 'true');+ downloadLink.setAttribute('role', 'link');+ }+ }++ function renderCounts() {+ const original = state.history[0];+ const v = current();+ if (!original || !v) {+ countsEl.hidden = !state.loading;+ countsEl.innerHTML = state.loading ? '<div class="mt-skeleton" style="width:100%" aria-hidden="true"></div>' : '';+ return;+ }+ countsEl.hidden = false;+ if (v === original) {+ countsEl.innerHTML = `<span><strong>${fmt(original.triangles)}</strong> triangles</span><span>original</span>`;+ return;+ }+ const delta = v.triangles - original.triangles;+ const pct = original.triangles ? Math.round((delta / original.triangles) * 100) : 0;+ const deltaText = delta === 0 ? 'unchanged' : `${delta > 0 ? '+' : ''}${pct}%`;+ countsEl.innerHTML = `+ <span>Before <strong>${fmt(original.triangles)}</strong></span>+ <span aria-hidden="true">→</span>+ <span>After <strong>${fmt(v.triangles)}</strong> triangles</span>+ <span class="mt-delta${delta > 0 ? ' is-up' : ''}">${deltaText}</span>`;+ }++ function renderHistory() {+ const steps = state.history.slice(1);+ historyEl.hidden = steps.length === 0;+ historyEl.innerHTML = steps.length+ ? `<span>Original</span>${steps.map((v) => `<span>${OPS[v.op].label}</span>`).join('')}`+ : '';+ }++ function renderDetails(stats) {+ const html = stats ? describe(stats) : '';+ detailsEl.hidden = !html;+ detailsEl.innerHTML = html;+ }++ function decimateTarget() {+ const v = current();+ const n = Number(input('target').value);+ if (Number.isFinite(n) && n > 0) return Math.round(n);+ return v ? Math.max(4, Math.round(v.triangles * (Number(input('ratio').value) / 100))) : 0;+ }++ function renderPreview() {+ const v = current();+ if (!v) {+ previewEl.innerHTML = state.loading ? 'Counting triangles…' : 'Open the model to see the live count.';+ return;+ }+ const target = Math.min(v.triangles, decimateTarget());+ previewEl.innerHTML = `<strong>${fmt(v.triangles)}</strong> → <strong>${fmt(target)}</strong> triangles`;+ }++ function syncRatioFromTarget() {+ const v = current();+ const n = Number(input('target').value);+ if (!v || !n) return;+ const pct = Math.max(1, Math.min(100, Math.round((n / v.triangles) * 100)));+ input('ratio').value = String(pct);+ output('ratio').textContent = `${pct}%`;+ }++ function syncTargetFromRatio() {+ const v = current();+ const pct = Number(input('ratio').value);+ output('ratio').textContent = `${pct}%`;+ if (v) input('target').value = String(Math.max(4, Math.round(v.triangles * (pct / 100))));+ }++ function selectTab(op, focus) {+ state.op = op;+ for (const t of tabs) {+ const on = t.dataset.op === op;+ t.setAttribute('aria-selected', String(on));+ t.tabIndex = on ? 0 : -1;+ if (on && focus) t.focus();+ }+ for (const p of panes) p.hidden = p.dataset.op !== op;+ if (!state.busy) applyBtn.textContent = `Apply ${OPS[op].label.toLowerCase()}`;+ if (op === 'decimate') renderPreview();+ }++ function emit() {+ const v = current();+ if (!v) return;+ onChange?.({+ url: v.url || state.sourceUrl,+ edited: state.history.length > 1,+ triangles: v.triangles,+ op: v.op,+ filename: filename(),+ });+ }++ function dropHistory() {+ for (const v of state.history) if (v.url) URL.revokeObjectURL(v.url);+ state.history = [];+ }++ async function load() {+ if (current()) return current();+ if (!state.sourceUrl) throw new Error('No model is loaded yet.');+ if (!state.loading) {+ const token = state.token;+ state.loading = (async () => {+ const res = await fetch(state.sourceUrl);+ if (!res.ok) throw new Error(`The model could not be downloaded (HTTP ${res.status}).`);+ const declared = Number(res.headers.get('content-length'));+ if (declared > MAX_SOURCE_BYTES) throw new Error('This model is over 150 MB, too large to edit in the browser.');+ const bytes = await res.arrayBuffer();+ if (bytes.byteLength > MAX_SOURCE_BYTES) throw new Error('This model is over 150 MB, too large to edit in the browser.');+ const { triangles } = await inspect(bytes);+ if (token !== state.token) return null;+ state.history = [{ bytes, triangles, op: null, stats: null, url: null }];+ return current();+ })().finally(() => {+ state.loading = null;+ });+ renderPreview();+ renderCounts();+ }+ return state.loading;+ }++ async function activate() {+ if (current() || state.loading || state.failed || !state.sourceUrl) return;+ setStatus('Reading the model…');+ try {+ const v = await load();+ if (!v) return;+ setStatus('');+ syncTargetFromRatio();+ renderCounts();+ renderPreview();+ syncButtons();+ } catch (err) {+ state.failed = true;+ setStatus(`${err.message || 'The model could not be read.'} Press Apply to try again.`, 'error');+ renderCounts();+ renderPreview();+ }+ }++ function paramsFor(op) {+ if (op === 'repair') return { creaseDegrees: Number(input('crease').value) };+ if (op === 'smooth') {+ return {+ method: input('method').value,+ iterations: Number(input('iterations').value),+ lambda: Number(input('lambda').value),+ preserveBoundary: input('preserveBoundary').checked,+ creaseDegrees: Number(input('crease').value),+ };+ }+ return { targetTriangles: decimateTarget() };+ }++ async function apply() {+ if (state.busy || !state.sourceUrl) return;+ const op = state.op;+ const token = state.token;+ setBusy(true, OPS[op].verb);+ setStatus('Reading the model…');+ try {+ const base = await load();+ if (!base || token !== state.token) return;+ state.failed = false;+ renderCounts();+ const params = paramsFor(op);+ if (op === 'decimate' && params.targetTriangles >= base.triangles) {+ setStatus(`The model already has ${fmt(base.triangles)} triangles. Pick a lower target.`, 'error');+ return;+ }+ const started = performance.now();+ const result = await run(base.bytes, op, params, (phase) => {+ if (token === state.token) setStatus(`${PHASES[phase] || phase}…`);+ });+ if (token !== state.token) return;+ const url = URL.createObjectURL(new Blob([result.bytes], { type: 'model/gltf-binary' }));+ state.history.push({ bytes: result.bytes, triangles: result.triangles, op, stats: result.stats, url });+ while (state.history.length > HISTORY_LIMIT + 1) {+ const [dropped] = state.history.splice(1, 1);+ if (dropped.url) URL.revokeObjectURL(dropped.url);+ }+ const seconds = ((performance.now() - started) / 1000).toFixed(1);+ setStatus(`${OPS[op].label} done in ${seconds}s.`, 'done');+ renderDetails(result.stats);+ afterHistoryChange();+ } catch (err) {+ if (token === state.token) setStatus(err.message || `${OPS[op].label} failed.`, 'error');+ } finally {+ if (token === state.token) setBusy(false);+ }+ }++ function afterHistoryChange() {+ syncTargetFromRatio();+ renderCounts();+ renderHistory();+ renderPreview();+ syncButtons();+ emit();+ }++ function undo() {+ if (state.busy || state.history.length < 2) return;+ const popped = state.history.pop();+ if (popped.url) setTimeout(() => URL.revokeObjectURL(popped.url), 1000);+ renderDetails(current().stats);+ setStatus(`Undid ${OPS[popped.op].label.toLowerCase()}.`);+ afterHistoryChange();+ }++ function resetToOriginal() {+ if (state.busy || state.history.length < 2) return;+ const removed = state.history.splice(1);+ setTimeout(() => {+ for (const v of removed) if (v.url) URL.revokeObjectURL(v.url);+ }, 1000);+ renderDetails(null);+ setStatus('Back to the original model.');+ afterHistoryChange();+ }++ // ---- wiring ---------------------------------------------------------------++ root.querySelector('.mt-tabs').addEventListener('click', (e) => {+ const tab = e.target.closest('.mt-tab');+ if (tab) selectTab(tab.dataset.op);+ });+ root.querySelector('.mt-tabs').addEventListener('keydown', (e) => {+ const i = tabs.findIndex((t) => t.dataset.op === state.op);+ let next = null;+ if (e.key === 'ArrowRight') next = (i + 1) % tabs.length;+ else if (e.key === 'ArrowLeft') next = (i - 1 + tabs.length) % tabs.length;+ else if (e.key === 'Home') next = 0;+ else if (e.key === 'End') next = tabs.length - 1;+ if (next === null) return;+ e.preventDefault();+ selectTab(tabs[next].dataset.op, true);+ });++ input('crease').addEventListener('input', () => {+ output('crease').textContent = `${input('crease').value}°`;+ });+ input('iterations').addEventListener('input', () => {+ output('iterations').textContent = input('iterations').value;+ });+ input('lambda').addEventListener('input', () => {+ output('lambda').textContent = Number(input('lambda').value).toFixed(2);+ });+ input('ratio').addEventListener('input', () => {+ syncTargetFromRatio();+ renderPreview();+ });+ input('target').addEventListener('input', () => {+ syncRatioFromTarget();+ renderPreview();+ });++ applyBtn.addEventListener('click', apply);+ undoBtn.addEventListener('click', undo);+ resetBtn.addEventListener('click', resetToOriginal);+ downloadLink.addEventListener('click', (e) => {+ if (downloadLink.getAttribute('aria-disabled') === 'true') e.preventDefault();+ });+ root.addEventListener('keydown', (e) => {+ if ((e.ctrlKey || e.metaKey) && !e.shiftKey && e.key.toLowerCase() === 'z' && !e.target.matches('input[type="number"]')) {+ e.preventDefault();+ undo();+ }+ });+ root.addEventListener('focusin', () => activate());++ function setSource(url, { label } = {}) {+ state.token += 1;+ dropHistory();+ state.loading = null;+ state.failed = false;+ state.sourceUrl = url || null;+ state.label = label || 'model';+ renderDetails(null);+ renderHistory();+ renderCounts();+ setStatus(url ? '' : 'No model is loaded yet.');+ input('target').value = '';+ setBusy(false);+ renderPreview();+ }++ selectTab('repair');+ setBusy(false);+ renderPreview();++ return {+ setSource,+ activate,+ /** True when the visible model is a local edit rather than the source URL. */+ get edited() {+ return state.history.length > 1;+ },+ destroy() {+ dropHistory();+ root.remove();+ },+ };+}diff --git a/src/mesh-ops/runner.js b/src/mesh-ops/runner.jsnew file mode 100644index 000000000..a7b4d5bc1--- /dev/null+++ b/src/mesh-ops/runner.js@@ -0,0 +1,106 @@+// GLB bytes in, GLB bytes out: one mesh operation end to end.+//+// Used by ./worker.js (the normal path, off the main thread) and directly by+// ./client.js when a browser cannot start a module worker. Decoders load on+// demand: meshoptimizer always (it is also the simplifier), Draco only when the+// file actually declares KHR_draco_mesh_compression, from the same decoder+// files the three.js viewers on this site already serve.+//+// Output is a plain GLB: geometry compression extensions are dropped so the+// result opens in every tool (slicers, DCCs, the STL exporter) and so a second+// operation can read it straight back. Textures are carried through byte for+// byte, including EXT_texture_webp.++import { WebIO } from '@gltf-transform/core';+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';+import { dequantize } from '@gltf-transform/functions';+import { MeshoptDecoder, MeshoptSimplifier } from 'meshoptimizer';++import { applyMeshOp, countTriangles } from './gltf.js';++const DRACO_EXTENSION = 'KHR_draco_mesh_compression';+const COMPRESSION_EXTENSIONS = new Set([DRACO_EXTENSION, 'EXT_meshopt_compression', 'KHR_mesh_quantization']);+const DRACO_BASE = '/three/draco/gltf/';++let dracoPromise = null;++/**+ * The Draco decoder module, built from /three/draco/gltf/. Fetched as text and+ * evaluated so it works the same in a module worker (no importScripts) and on+ * the main thread. Only ever reached for a Draco-compressed file.+ */+function loadDracoDecoder() {+ if (!dracoPromise) {+ dracoPromise = (async () => {+ const [wrapperRes, wasmRes] = await Promise.all([+ fetch(`${DRACO_BASE}draco_wasm_wrapper.js`),+ fetch(`${DRACO_BASE}draco_decoder.wasm`),+ ]);+ if (!wrapperRes.ok || !wasmRes.ok) throw new Error('The Draco decoder could not be downloaded.');+ const source = await wrapperRes.text();+ const wasmBinary = await wasmRes.arrayBuffer();+ const factory = new Function(`${source}\nreturn DracoDecoderModule;`)();+ return factory({ wasmBinary });+ })().catch((err) => {+ dracoPromise = null;+ throw err;+ });+ }+ return dracoPromise;+}++function declaredExtensions(bytes) {+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);+ if (bytes.byteLength < 20 || view.getUint32(0, true) !== 0x46546c67) return [];+ const jsonLength = view.getUint32(12, true);+ try {+ const json = JSON.parse(new TextDecoder().decode(bytes.subarray(20, 20 + jsonLength)));+ return [...(json.extensionsUsed || []), ...(json.extensionsRequired || [])];+ } catch {+ return [];+ }+}++async function createIO(bytes) {+ await MeshoptDecoder.ready;+ const deps = { 'meshopt.decoder': MeshoptDecoder };+ if (declaredExtensions(bytes).includes(DRACO_EXTENSION)) deps['draco3d.decoder'] = await loadDracoDecoder();+ return new WebIO().registerExtensions(ALL_EXTENSIONS).registerDependencies(deps);+}++/** Parse GLB bytes into a float, uncompressed document ready to edit. */+export async function readDocument(bytes) {+ const io = await createIO(bytes);+ const doc = await io.readBinary(bytes);+ await doc.transform(dequantize());+ return { doc, io };+}++/** Serialise a document as a plain GLB (no geometry compression). */+export async function writeDocument(doc, io) {+ for (const ext of doc.getRoot().listExtensionsUsed()) {+ if (COMPRESSION_EXTENSIONS.has(ext.extensionName)) ext.dispose();+ }+ return io.writeBinary(doc);+}++/** Triangle count of a GLB without changing it. */+export async function inspectGlb(bytes) {+ const { doc } = await readDocument(bytes);+ return { triangles: countTriangles(doc) };+}++/**+ * Run `op` on GLB `bytes`. `onPhase` receives 'reading' | 'processing' |+ * 'writing' as each real stage starts, for the panel's status line.+ */+export async function runMeshOp(bytes, op, params = {}, onPhase = () => {}) {+ onPhase('reading');+ const { doc, io } = await readDocument(bytes);+ onPhase('processing');+ if (op === 'decimate') await MeshoptSimplifier.ready;+ const stats = applyMeshOp(doc, op, params, { simplifier: MeshoptSimplifier });+ onPhase('writing');+ const out = await writeDocument(doc, io);+ return { bytes: out, stats, triangles: stats.trianglesAfter };+}diff --git a/src/mesh-ops/worker.js b/src/mesh-ops/worker.jsnew file mode 100644index 000000000..f0dfc0aab--- /dev/null+++ b/src/mesh-ops/worker.js@@ -0,0 +1,27 @@+// Module worker for the in-browser mesh tools. Keeps GLB parsing, the mesh+// algorithms and serialisation off the main thread so the viewer keeps+// rendering while a 300k-triangle model is repaired. Protocol:+//+// in { id, kind: 'inspect' | 'run', bytes: ArrayBuffer, op?, params? }+// out { id, phase } a real stage just started+// { id, ok: true, bytes?, stats?, triangles } done (bytes transferred)+// { id, ok: false, error } failed++import { inspectGlb, runMeshOp } from './runner.js';++self.addEventListener('message', async (event) => {+ const { id, kind, bytes, op, params } = event.data || {};+ try {+ const input = new Uint8Array(bytes);+ if (kind === 'inspect') {+ const result = await inspectGlb(input);+ self.postMessage({ id, ok: true, triangles: result.triangles });+ return;+ }+ const result = await runMeshOp(input, op, params, (phase) => self.postMessage({ id, phase }));+ const out = result.bytes.buffer.slice(result.bytes.byteOffset, result.bytes.byteOffset + result.bytes.byteLength);+ self.postMessage({ id, ok: true, bytes: out, stats: result.stats, triangles: result.triangles }, [out]);+ } catch (err) {+ self.postMessage({ id, ok: false, error: err?.message || String(err) });+ }+});diff --git a/tests/mesh-ops.test.js b/tests/mesh-ops.test.jsnew file mode 100644index 000000000..a4f74df12--- /dev/null+++ b/tests/mesh-ops.test.js@@ -0,0 +1,324 @@+// In-browser mesh tools (src/mesh-ops): repair, smoothing, decimation.+//+// The algorithms are pure, so they are tested on real geometry built here: a+// UV sphere with a texture seam (the shape every generated model has), and a+// cube assembled from separate triangles with the defects a generator emits+// (duplicate vertices, a collapsed face, a duplicated face, a reversed face, an+// inside-out shell). Decimation runs through the real meshoptimizer WASM, and+// the document layer is exercised end to end on a GLB written and read back by+// glTF-Transform, so nothing here is a stand-in for the code that ships.+import { describe, it, expect, beforeAll } from 'vitest';+import { Document, NodeIO } from '@gltf-transform/core';+import { MeshoptSimplifier } from 'meshoptimizer';++import {+ computeNormals,+ decimateMesh,+ repairMesh,+ resolveTarget,+ smoothMesh,+ taubinMu,+ triangleCount,+ vertexCount,+ weldVertices,+} from '../src/mesh-ops/core.js';+import { applyMeshOp, countTriangles, readPrimitive } from '../src/mesh-ops/gltf.js';+import { edgeTopology, signedVolume } from '../api/_lib/print/topology.js';++/** UV sphere with a duplicated seam column, smooth normals, and UVs. */+function uvSphere(segments = 48, rings = 24, radius = 1) {+ const positions = [];+ const normals = [];+ const uvs = [];+ for (let r = 0; r <= rings; r += 1) {+ const v = r / rings;+ const phi = v * Math.PI;+ for (let s = 0; s <= segments; s += 1) {+ const u = s / segments;+ const theta = u * Math.PI * 2;+ const x = Math.sin(phi) * Math.cos(theta);+ const y = Math.cos(phi);+ const z = Math.sin(phi) * Math.sin(theta);+ positions.push(x * radius, y * radius, z * radius);+ normals.push(x, y, z);+ uvs.push(u, v);+ }+ }+ const indices = [];+ const row = segments + 1;+ for (let r = 0; r < rings; r += 1) {+ for (let s = 0; s < segments; s += 1) {+ const a = r * row + s;+ const b = a + row;+ if (r !== 0) indices.push(a, a + 1, b);+ if (r !== rings - 1) indices.push(a + 1, b + 1, b);+ }+ }+ return {+ indices: Uint32Array.from(indices),+ attributes: {+ POSITION: { array: Float32Array.from(positions), itemSize: 3, type: 'VEC3' },+ NORMAL: { array: Float32Array.from(normals), itemSize: 3, type: 'VEC3' },+ TEXCOORD_0: { array: Float32Array.from(uvs), itemSize: 2, type: 'VEC2' },+ },+ targets: [],+ };+}++/** Add deterministic radial noise to a sphere: what smoothing exists to remove. */+function noisy(mesh, amount = 0.04) {+ const p = mesh.attributes.POSITION.array.slice();+ const groups = new Map();+ for (let v = 0; v < p.length / 3; v += 1) {+ const q = (x) => Math.round(x * 1e5) + 0;+ const key = `${q(p[v * 3])},${q(p[v * 3 + 1])},${q(p[v * 3 + 2])}`;+ if (!groups.has(key)) groups.set(key, 1 + amount * Math.sin(v * 12.9898) * Math.cos(v * 78.233));+ const k = groups.get(key);+ p[v * 3] *= k;+ p[v * 3 + 1] *= k;+ p[v * 3 + 2] *= k;+ }+ return { ...mesh, attributes: { ...mesh.attributes, POSITION: { ...mesh.attributes.POSITION, array: p } } };+}++const CUBE_CORNERS = [+ [-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1],+ [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1],+];+// Outward-wound quads (counter-clockwise seen from outside).+const CUBE_QUADS = [+ [0, 3, 2, 1], [4, 5, 6, 7], [0, 1, 5, 4], [2, 3, 7, 6], [1, 2, 6, 5], [0, 4, 7, 3],+];++/**+ * A closed cube written as triangle soup (every triangle owns its corners), so+ * welding has 36 corners to merge down to 8, plus one collapsed triangle, one+ * duplicated triangle, and one reversed triangle. `insideOut` reverses all.+ */+function brokenCube({ insideOut = false } = {}) {+ const tris = [];+ for (const [a, b, c, d] of CUBE_QUADS) tris.push([a, b, c], [a, c, d]);+ if (insideOut) for (const t of tris) t.reverse();+ tris[5] = [tris[5][0], tris[5][2], tris[5][1]];+ tris.push([...tris[0]]);+ tris.push([0, 0, 1]);+ const positions = [];+ for (const t of tris) for (const corner of t) positions.push(...CUBE_CORNERS[corner]);+ const count = positions.length / 3;+ const indices = new Uint32Array(count);+ for (let i = 0; i < count; i += 1) indices[i] = i;+ return {+ indices,+ attributes: { POSITION: { array: Float32Array.from(positions), itemSize: 3, type: 'VEC3' } },+ targets: [],+ };+}++beforeAll(async () => {+ await MeshoptSimplifier.ready;+});++describe('repair', () => {+ it('merges duplicate vertices and drops collapsed and duplicate faces', () => {+ const { mesh, stats } = repairMesh(brokenCube());+ expect(stats.trianglesBefore).toBe(14);+ expect(stats.collapsedFaces).toBe(1);+ expect(stats.duplicateFaces).toBe(1);+ expect(stats.trianglesAfter).toBe(12);+ expect(vertexCount(mesh)).toBeLessThanOrEqual(stats.verticesBefore);+ expect(stats.mergedVertices).toBeGreaterThan(0);+ });++ it('makes winding consistent and the closed shell face outward', () => {+ const { mesh, stats } = repairMesh(brokenCube());+ expect(stats.flippedFaces).toBe(1);+ expect(stats.openEdges).toBe(0);+ expect(edgeTopology(mesh.indices).flippedEdges).toBe(0);+ expect(signedVolume(mesh.attributes.POSITION.array, mesh.indices)).toBeCloseTo(8, 5);+ });++ it('turns an inside-out shell outward and reports it', () => {+ const { mesh, stats } = repairMesh(brokenCube({ insideOut: true }));+ expect(stats.reversedShells).toBe(1);+ expect(signedVolume(mesh.attributes.POSITION.array, mesh.indices)).toBeCloseTo(8, 5);+ });++ it('keeps UV seams split and hard edges hard while recomputing normals', () => {+ const sphere = uvSphere();+ expect(signedVolume(sphere.attributes.POSITION.array, sphere.indices)).toBeGreaterThan(0);+ const { mesh, stats } = repairMesh(sphere);+ // The seam column and pole fans are distinct UVs: none of it may merge.+ // The only vertices that go are the two pole corners no triangle uses.+ expect(stats.mergedVertices).toBe(0);+ expect(stats.trianglesAfter).toBe(stats.trianglesBefore);+ const used = new Set(sphere.indices);+ expect(vertexCount(mesh)).toBe(used.size);+ const kept = [...used].sort((a, b) => a - b);+ const uv = mesh.attributes.TEXCOORD_0.array;+ kept.forEach((old, i) => {+ expect(uv[i * 2]).toBe(sphere.attributes.TEXCOORD_0.array[old * 2]);+ expect(uv[i * 2 + 1]).toBe(sphere.attributes.TEXCOORD_0.array[old * 2 + 1]);+ });+ // Cube faces meet at 90 degrees: recomputed normals stay axis aligned.+ const repairedCube = repairMesh(brokenCube());+ const cube = repairedCube.mesh;+ // 8 welded corners, each split three ways for its three hard edges.+ expect(vertexCount(cube)).toBe(24);+ expect(repairedCube.stats.hardEdgeVertices).toBe(16);+ const n = cube.attributes.NORMAL.array;+ for (let v = 0; v < n.length / 3; v += 1) {+ const big = Math.max(Math.abs(n[v * 3]), Math.abs(n[v * 3 + 1]), Math.abs(n[v * 3 + 2]));+ expect(big).toBeCloseTo(1, 5);+ }+ });++ it('smooths shading across a UV seam instead of leaving a visible crease', () => {+ const sphere = uvSphere();+ const { attributes } = computeNormals(sphere).mesh;+ const p = sphere.attributes.POSITION.array;+ const n = attributes.NORMAL.array;+ for (const v of new Set(sphere.indices)) {+ const len = Math.hypot(p[v * 3], p[v * 3 + 1], p[v * 3 + 2]);+ const dot = (p[v * 3] * n[v * 3] + p[v * 3 + 1] * n[v * 3 + 1] + p[v * 3 + 2] * n[v * 3 + 2]) / len;+ expect(dot).toBeGreaterThan(0.99);+ }+ });+});++describe('smoothing', () => {+ it('derives the classic Taubin inflation factor', () => {+ expect(taubinMu(0.5, 0.1)).toBeCloseTo(-0.5263, 3);+ expect(taubinMu(0.5, 0.1)).toBeLessThan(-0.5);+ });++ it('preserves vertex count, index buffer and UVs exactly', () => {+ const sphere = noisy(uvSphere());+ const { mesh, stats } = smoothMesh(sphere, { iterations: 8, lambda: 0.5 });+ expect(vertexCount(mesh)).toBe(vertexCount(sphere));+ expect(mesh.indices).toBe(sphere.indices);+ expect(mesh.attributes.TEXCOORD_0).toBe(sphere.attributes.TEXCOORD_0);+ expect(stats.movedPoints).toBeGreaterThan(0);+ });++ it('moves both sides of a UV seam together so the seam never opens', () => {+ const { mesh } = smoothMesh(noisy(uvSphere()), { iterations: 5 });+ const segments = 48;+ const row = segments + 1;+ const p = mesh.attributes.POSITION.array;+ for (let r = 0; r <= 24; r += 1) {+ const first = r * row;+ const last = first + segments;+ expect(p[first * 3]).toBeCloseTo(p[last * 3], 6);+ expect(p[first * 3 + 1]).toBeCloseTo(p[last * 3 + 1], 6);+ expect(p[first * 3 + 2]).toBeCloseTo(p[last * 3 + 2], 6);+ }+ });++ it('removes noise, and Taubin keeps far more volume than Laplacian', () => {+ const rough = noisy(uvSphere(), 0.05);+ const deviation = (m) => {+ const p = m.attributes.POSITION.array;+ let sum = 0;+ for (let v = 0; v < p.length / 3; v += 1) sum += Math.abs(Math.hypot(p[v * 3], p[v * 3 + 1], p[v * 3 + 2]) - 1);+ return sum / (p.length / 3);+ };+ const taubin = smoothMesh(rough, { method: 'taubin', iterations: 10, lambda: 0.5 });+ const laplacian = smoothMesh(rough, { method: 'laplacian', iterations: 10, lambda: 0.5 });+ expect(Math.abs(taubin.stats.volumeChange)).toBeLessThan(Math.abs(laplacian.stats.volumeChange));+ expect(laplacian.stats.volumeChange).toBeLessThan(0);+ const before = rough.attributes.POSITION.array;+ let roughness = 0;+ let smoothed = 0;+ const p = taubin.mesh.attributes.POSITION.array;+ // Local roughness: distance between neighbours along a ring.+ for (let v = 1; v < before.length / 3; v += 1) {+ roughness += Math.abs(Math.hypot(before[v * 3], before[v * 3 + 1], before[v * 3 + 2]) - Math.hypot(before[v * 3 - 3], before[v * 3 - 2], before[v * 3 - 1]));+ smoothed += Math.abs(Math.hypot(p[v * 3], p[v * 3 + 1], p[v * 3 + 2]) - Math.hypot(p[v * 3 - 3], p[v * 3 - 2], p[v * 3 - 1]));+ }+ expect(smoothed).toBeLessThan(roughness * 0.5);+ expect(deviation(taubin.mesh)).toBeLessThan(0.05);+ });+});++describe('decimation', () => {+ it('resolves a target from a count or a ratio, clamped to the mesh', () => {+ expect(resolveTarget(1000, { ratio: 0.25 })).toBe(250);+ expect(resolveTarget(1000, { targetTriangles: 400, ratio: 0.1 })).toBe(400);+ expect(resolveTarget(1000, { targetTriangles: 5000 })).toBe(1000);+ });++ it('hits a triangle target within 5% on a textured mesh', () => {+ const sphere = uvSphere(96, 48);+ const before = triangleCount(sphere);+ for (const ratio of [0.5, 0.25, 0.1]) {+ const target = Math.round(before * ratio);+ const { mesh, stats } = decimateMesh(sphere, { targetTriangles: target, simplifier: MeshoptSimplifier });+ expect(stats.trianglesAfter).toBe(triangleCount(mesh));+ expect(Math.abs(stats.trianglesAfter - target) / target).toBeLessThan(0.05);+ expect(mesh.attributes.TEXCOORD_0.array.length / 2).toBe(vertexCount(mesh));+ }+ });++ it('decimates an unindexed soup by welding it first', () => {+ const sphere = uvSphere(64, 32);+ const soupCount = sphere.indices.length;+ const soup = { indices: new Uint32Array(soupCount), attributes: {}, targets: [] };+ for (const [name, rec] of Object.entries(sphere.attributes)) {+ const out = new Float32Array(soupCount * rec.itemSize);+ for (let i = 0; i < soupCount; i += 1) {+ for (let k = 0; k < rec.itemSize; k += 1) out[i * rec.itemSize + k] = rec.array[sphere.indices[i] * rec.itemSize + k];+ }+ soup.attributes[name] = { ...rec, array: out };+ }+ for (let i = 0; i < soupCount; i += 1) soup.indices[i] = i;+ expect(weldVertices(soup).merged).toBeGreaterThan(soupCount / 2);+ const target = Math.round(triangleCount(soup) / 4);+ const { stats } = decimateMesh(soup, { targetTriangles: target, simplifier: MeshoptSimplifier });+ expect(Math.abs(stats.trianglesAfter - target) / target).toBeLessThan(0.05);+ });+});++describe('document layer', () => {+ async function sphereGlb() {+ const doc = new Document();+ const buffer = doc.createBuffer();+ const sphere = uvSphere(64, 32);+ const prim = doc.createPrimitive();+ for (const [name, rec] of Object.entries(sphere.attributes)) {+ prim.setAttribute(name, doc.createAccessor().setType(rec.type).setArray(rec.array).setBuffer(buffer));+ }+ prim.setIndices(doc.createAccessor().setType('SCALAR').setArray(sphere.indices).setBuffer(buffer));+ const material = doc.createMaterial('paint').setBaseColorFactor([0.8, 0.3, 0.2, 1]);+ prim.setMaterial(material);+ const mesh = doc.createMesh('sphere').addPrimitive(prim);+ doc.createScene().addChild(doc.createNode('sphere').setMesh(mesh));+ return new NodeIO().writeBinary(doc);+ }++ it('decimates a whole GLB to a document-wide target and round-trips', async () => {+ const io = new NodeIO();+ const doc = await io.readBinary(await sphereGlb());+ const before = countTriangles(doc);+ const stats = applyMeshOp(doc, 'decimate', { ratio: 0.3 }, { simplifier: MeshoptSimplifier });+ expect(stats.trianglesBefore).toBe(before);+ expect(Math.abs(stats.trianglesAfter - stats.target) / stats.target).toBeLessThan(0.05);+ const reread = await io.readBinary(await io.writeBinary(doc));+ expect(countTriangles(reread)).toBe(stats.trianglesAfter);+ expect(reread.getRoot().listMaterials()[0].getName()).toBe('paint');+ expect(reread.getRoot().listAccessors().length).toBe(4);+ });++ it('repairs and smooths in place without changing the material or UV count', async () => {+ const io = new NodeIO();+ const doc = await io.readBinary(await sphereGlb());+ const prim = doc.getRoot().listMeshes()[0].listPrimitives()[0];+ const uvBefore = new Set(prim.getIndices().getArray()).size;+ const repaired = applyMeshOp(doc, 'repair');+ expect(repaired.duplicateFaces).toBe(0);+ const smoothed = applyMeshOp(doc, 'smooth', { iterations: 4 });+ expect(smoothed.trianglesAfter).toBe(repaired.trianglesAfter);+ const mesh = readPrimitive(doc.getRoot().listMeshes()[0].listPrimitives()[0]);+ expect(mesh.attributes.TEXCOORD_0.array.length / 2).toBe(uvBefore);+ expect(prim.getMaterial().getName()).toBe('paint');+ });+});