Skip to content

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

feat(3d-diff): diff two GLBs through the catalog API, the glb-diff package and the studio MCP tools

nirholasc3a2af352628
diff --git a/api/3d/diff.js b/api/3d/diff.js
new file mode 100644
index 000000000..d087a2fb9
--- /dev/null
+++ b/api/3d/diff.js
@@ -0,0 +1,156 @@
+// GET/POST /api/3d/diff — FREE, keyless structural diff of two glTF/GLB models.
+//
+// The question this answers is not "are these two files different" (a re-export
+// always is, down to the byte) but "what changed, and will it break anything
+// that depends on this model". Byte comparison, checksums, and file size all
+// fail at that: they cannot tell a lossless recompression from a rig that
+// quietly lost three finger joints, and the second one is what takes an avatar
+// off the screen in production.
+//
+// Input:
+// GET /api/3d/diff?a=<url>&b=<url>[&format=json|markdown|text]
+// POST /api/3d/diff body { "a": "<url>", "b": "<url>", "format": "json" }
+//
+// Output (format=json, the default): the change set from @three-ws/glb-diff:
+// { version, identical, severity, summary, totals, sections, extensions,
+// asset, highlights, ts }
+// `severity` is the field to gate on: none < cosmetic < minor < major < breaking.
+// `format=markdown` returns a pull-request-ready report as text/markdown, and
+// `format=text` returns the plain terminal report, so a CI job can post the
+// result without carrying a renderer of its own.
+//
+// The engine is the published package (packages/glb-diff), the same code the
+// /diff page runs in the browser and the `glb-diff` CLI runs in a terminal. One
+// implementation, three surfaces: a verdict from this endpoint can never
+// disagree with what the page shows.
+
+import { cors, wrap, error, json, text, rateLimited, readJson } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { fetchModel, FetchModelError } from '../_lib/fetch-model.js';
+import { describeModel, diffDescriptions, formatMarkdown, formatText } from '@three-ws/glb-diff';
+
+// Same free-tier ceiling as /api/3d/inspect, applied per side. Two models at
+// 32 MiB each is the honest upper bound on what one anonymous call may cost.
+const MAX_BYTES = 32 * 1024 * 1024;
+
+const FORMATS = new Set(['json', 'markdown', 'text']);
+
+function httpError(status, code, message, extra = {}) {
+ const e = new Error(message);
+ e.status = status;
+ e.code = code;
+ e.extra = extra;
+ return e;
+}
+
+// Fetch one side through the SSRF-hardened, size-capped fetcher and translate
+// its typed errors into this endpoint's HTTP contract. `side` names which input
+// failed, because "could not fetch model" with two URLs in play is a support
+// ticket rather than an error message.
+async function fetchSide(side, url) {
+ if (!url) throw httpError(400, 'missing_url', `query param "${side}" is required (a public https URL of a .glb/.gltf)`);
+ try {
+ const { bytes, url: finalUrl } = await fetchModel(url, { maxBytes: MAX_BYTES, timeoutMs: 20_000 });
+ return { bytes, url: finalUrl };
+ } catch (err) {
+ if (err instanceof FetchModelError) {
+ if (err.code === 'file_too_large') {
+ throw httpError(413, 'too_large', `model "${side}" exceeds the ${MAX_BYTES}-byte free-tier cap`);
+ }
+ if (['invalid_url', 'scheme_not_allowed', 'private_address', 'host_pin_mismatch'].includes(err.code)) {
+ throw httpError(400, 'invalid_url', `model "${side}": ${err.message}`);
+ }
+ throw httpError(502, 'fetch_failed', `could not fetch model "${side}": ${err.message}`, {
+ retry: 'check the URL is public and returns the model bytes',
+ });
+ }
+ throw httpError(502, 'fetch_failed', `could not fetch model "${side}": ${err?.message || err}`);
+ }
+}
+
+function filenameOf(url, fallback) {
+ try {
+ return new URL(url).pathname.split('/').filter(Boolean).pop() || fallback;
+ } catch {
+ return fallback;
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+ if (req.method !== 'GET' && req.method !== 'POST') {
+ res.setHeader('allow', 'GET, POST');
+ return error(res, 405, 'method_not_allowed', 'use GET (?a=&b=) or POST ({ a, b })');
+ }
+
+ // Two fetches plus two full parses is heavier than /inspect, so the per-IP
+ // budget is tighter. Still free and keyless: the limit exists to bound abuse,
+ // not to push anyone toward an account.
+ const ip = clientIp(req);
+ const rl = await limits.apiIp(ip, { limit: 30, window: '1 m' });
+ if (!rl.success) return rateLimited(res, rl, 'too many diff requests');
+
+ let input = {};
+ if (req.method === 'GET') {
+ input = { a: req.query?.a, b: req.query?.b, format: req.query?.format };
+ } else {
+ try {
+ input = (await readJson(req)) || {};
+ } catch (e) {
+ return error(res, e.status === 415 ? 415 : 400, 'invalid_json', e.message || 'invalid JSON body');
+ }
+ }
+
+ const format = String(input.format || 'json').toLowerCase();
+ if (!FORMATS.has(format)) {
+ return error(res, 400, 'invalid_format', `format must be one of: ${[...FORMATS].join(', ')}`);
+ }
+
+ const urlA = String(input.a || '').trim();
+ const urlB = String(input.b || '').trim();
+
+ let sideA;
+ let sideB;
+ try {
+ // Sequential rather than concurrent: a caller who passed one bad URL gets
+ // that specific error without the endpoint having spent a second full
+ // download on the other side first.
+ sideA = await fetchSide('a', urlA);
+ sideB = await fetchSide('b', urlB);
+ } catch (e) {
+ return error(res, e.status || 502, e.code || 'fetch_failed', e.message, e.extra || {});
+ }
+
+ let changeset;
+ try {
+ const [a, b] = await Promise.all([
+ describeModel(sideA.bytes, { name: filenameOf(sideA.url, 'a.glb') }),
+ describeModel(sideB.bytes, { name: filenameOf(sideB.url, 'b.glb') }),
+ ]);
+ changeset = diffDescriptions(a, b);
+ } catch (e) {
+ return error(res, 400, 'invalid_model', `not a valid glTF/GLB: ${e.message || 'could not parse model'}`);
+ }
+
+ // URL-sourced requests are deterministic for a given pair, so the edge may
+ // hold them briefly. The identical-inputs case is the common one in CI.
+ const cache = req.method === 'GET' ? 'public, max-age=60, s-maxage=300' : 'no-store';
+
+ if (format === 'markdown') {
+ return text(res, 200, formatMarkdown(changeset), {
+ 'content-type': 'text/markdown; charset=utf-8',
+ 'cache-control': cache,
+ });
+ }
+ if (format === 'text') {
+ return text(res, 200, formatText(changeset, { color: false }), { 'cache-control': cache });
+ }
+
+ res.setHeader('cache-control', cache);
+ return json(res, 200, {
+ ...changeset,
+ a: { ...changeset.a, url: sideA.url },
+ b: { ...changeset.b, url: sideB.url },
+ ts: new Date().toISOString(),
+ });
+});
diff --git a/api/_lib/3d-catalog/diff.js b/api/_lib/3d-catalog/diff.js
new file mode 100644
index 000000000..cea18a9a0
--- /dev/null
+++ b/api/_lib/3d-catalog/diff.js
@@ -0,0 +1,132 @@
+// Catalog entry for the free 3D Diff endpoint. The /api/3d index globs
+// api/_lib/3d-catalog/*.js and merges every default export into the public API
+// catalog + the generated OpenAPI doc, so this descriptor is what makes
+// /api/3d/diff discoverable to an agent that has never seen this platform.
+
+export default {
+ id: 'diff',
+ name: '3D Model Diff',
+ path: '/api/3d/diff',
+ methods: ['GET', 'POST'],
+ free: true,
+ keyless: true,
+ category: '3d',
+ tags: ['3d', 'gltf', 'glb', 'diff', 'regression', 'ci', 'version-control'],
+ summary: 'Compare two glTF/GLB models and report what changed, with a severity you can gate a build on.',
+ description:
+ 'Fetches two glTF/GLB models and returns a structural change set: geometry, hierarchy, ' +
+ 'materials, textures, skeletons, and animation clips, each classified as added, removed, ' +
+ 'renamed, moved, or modified. Rename and move detection works the way git does (match by ' +
+ 'name, then by content hash, then by similarity), so re-exporting a file does not read as ' +
+ 'a rewrite. Every change carries a severity: none, cosmetic, minor, major, breaking. ' +
+ 'Set format=markdown or format=text to get a rendered report instead of JSON.',
+ useCase:
+ 'A pipeline that optimizes, rigs, restyles, or re-exports a model needs to know whether the ' +
+ 'output is still the same asset. Byte comparison cannot tell a lossless recompression from ' +
+ 'a rig that lost three finger joints; this can, and the losing case is the one that takes an ' +
+ 'avatar off the screen. Gate CI on severity, or post the Markdown report on the pull request.',
+ input: {
+ query: {
+ a: { type: 'string', format: 'uri', required: true, description: 'Public https URL of the baseline .glb/.gltf (max 32 MiB).' },
+ b: { type: 'string', format: 'uri', required: true, description: 'Public https URL of the candidate .glb/.gltf (max 32 MiB).' },
+ format: {
+ type: 'string',
+ required: false,
+ description: 'json (default), markdown for a pull-request comment, or text for the terminal report.',
+ },
+ },
+ body: { description: 'POST { "a": "…", "b": "…", "format": "json" } as application/json.' },
+ },
+ inputSchema: {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['a', 'b'],
+ properties: {
+ a: { type: 'string', format: 'uri', description: 'Baseline model URL.' },
+ b: { type: 'string', format: 'uri', description: 'Candidate model URL.' },
+ format: { type: 'string', enum: ['json', 'markdown', 'text'], default: 'json' },
+ },
+ },
+ outputSchema: {
+ $schema: 'https://json-schema.org/draft/2020-12/schema',
+ type: 'object',
+ required: ['version', 'identical', 'severity', 'summary', 'totals', 'sections', 'highlights', 'ts'],
+ properties: {
+ version: { type: 'integer', description: 'Change-set schema version.' },
+ identical: { type: 'boolean' },
+ severity: { type: 'string', enum: ['none', 'cosmetic', 'minor', 'major', 'breaking'] },
+ a: { type: 'object', properties: { name: { type: ['string', 'null'] }, url: { type: 'string' }, sizeBytes: { type: 'integer' } } },
+ b: { type: 'object', properties: { name: { type: ['string', 'null'] }, url: { type: 'string' }, sizeBytes: { type: 'integer' } } },
+ summary: {
+ type: 'object',
+ properties: {
+ changed: { type: 'integer' },
+ added: { type: 'integer' },
+ removed: { type: 'integer' },
+ modified: { type: 'integer' },
+ renamed: { type: 'integer' },
+ moved: { type: 'integer' },
+ },
+ },
+ totals: {
+ type: 'object',
+ description: 'Per-metric before/after with delta and percent change (vertices, triangles, joints, sizeBytes, ...).',
+ additionalProperties: {
+ type: 'object',
+ properties: {
+ a: { type: 'number' },
+ b: { type: 'number' },
+ delta: { type: 'number' },
+ pct: { type: ['number', 'null'] },
+ },
+ },
+ },
+ sections: {
+ type: 'object',
+ description: 'One block per object kind, each with added/removed/renamed/modified lists.',
+ properties: {
+ nodes: { type: 'object' },
+ meshes: { type: 'object' },
+ materials: { type: 'object' },
+ textures: { type: 'object' },
+ animations: { type: 'object' },
+ skins: { type: 'object' },
+ },
+ },
+ extensions: { type: 'object', properties: { used: { type: 'object' }, required: { type: 'object' } } },
+ asset: { type: 'array', items: { type: 'object' } },
+ highlights: {
+ type: 'array',
+ description: 'Plain-language sentences, worst first.',
+ items: {
+ type: 'object',
+ required: ['severity', 'text'],
+ properties: { severity: { type: 'string' }, text: { type: 'string' } },
+ },
+ },
+ ts: { type: 'string', format: 'date-time' },
+ },
+ },
+ example: {
+ request: 'GET /api/3d/diff?a=https://three.ws/avatars/cesium-man.glb&b=https://three.ws/avatars/michelle.glb',
+ response: {
+ version: 1,
+ identical: false,
+ severity: 'breaking',
+ a: { name: 'cesium-man.glb', url: 'https://three.ws/avatars/cesium-man.glb', sizeBytes: 438044 },
+ b: { name: 'michelle.glb', url: 'https://three.ws/avatars/michelle.glb', sizeBytes: 849756 },
+ summary: { changed: 111, added: 75, removed: 26, modified: 1, renamed: 1, moved: 0 },
+ totals: {
+ triangles: { a: 4672, b: 28106, delta: 23434, pct: 501.6 },
+ joints: { a: 19, b: 65, delta: 46, pct: 242.1 },
+ sizeBytes: { a: 438044, b: 849756, delta: 411712, pct: 94 },
+ },
+ highlights: [
+ { severity: 'breaking', text: 'Skeleton "Armature" was removed. The model is no longer rigged.' },
+ { severity: 'breaking', text: 'Mesh "Cesium_Man" was removed (4,672 triangles gone).' },
+ { severity: 'major', text: 'Triangle count is up 23,434 (+501.6%).' },
+ ],
+ ts: '2026-08-28T00:00:00.000Z',
+ },
+ },
+};
diff --git a/api/_lib/3d-catalog/index.js b/api/_lib/3d-catalog/index.js
index 4460bd691..5cd949e90 100644
--- a/api/_lib/3d-catalog/index.js
+++ b/api/_lib/3d-catalog/index.js
@@ -27,6 +27,7 @@ import { pathToFileURL } from 'node:url';
import { basename, dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
+import diffEntry from './diff.js';
import generateEntry from './generate.js';
import inspectEntry from './inspect.js';
@@ -40,6 +41,7 @@ import inspectEntry from './inspect.js';
// >>> Adding an endpoint: drop `api/_lib/3d-catalog/<slug>.js` AND add its
// >>> import + line here. The import is what makes it exist in production.
const STATIC_ENTRIES = [
+ { mod: diffEntry, source: 'diff.js' },
{ mod: generateEntry, source: 'generate.js' },
{ mod: inspectEntry, source: 'inspect.js' },
];
diff --git a/api/_mcp3d/catalog.js b/api/_mcp3d/catalog.js
index 9d688ce7b..2bde10386 100644
--- a/api/_mcp3d/catalog.js
+++ b/api/_mcp3d/catalog.js
@@ -8,6 +8,7 @@ import { toolDefs as spatialDefs } from './tools/spatial.js';
import { toolDefs as arDefs } from './tools/ar.js';
import { toolDefs as provenanceDefs } from './tools/provenance.js';
import { toolDefs as personaIdentityDefs } from './tools/persona-identity.js';
+import { toolDefs as preflightDefs } from './tools/preflight.js';
import { toolDefs as modelDefs } from '../_mcp/tools/models.js';
import { toolDefs as animationDefs } from '../_mcp/tools/animations.js';
@@ -22,7 +23,7 @@ const reusedModelDefs = modelDefs.filter(
// The animation library (list_animations + apply_animation) completes the
// pipeline: text_to_3d → auto_rig_model → apply_animation. Same retarget engine
// the main server exposes — reused here, not duplicated.
-const baseDefs = [...studioDefs, ...spatialDefs, ...arDefs, ...provenanceDefs, ...personaIdentityDefs, ...reusedModelDefs, ...animationDefs];
+const baseDefs = [...studioDefs, ...spatialDefs, ...arDefs, ...provenanceDefs, ...personaIdentityDefs, ...preflightDefs, ...reusedModelDefs, ...animationDefs];
// Free, public entry point — listed first so discovery clients see it up top.
// Annotations: a static, local overview built at module load — read-only,
diff --git a/api/_mcp3d/pricing.js b/api/_mcp3d/pricing.js
index 8d27ee446..61d3b2a5b 100644
--- a/api/_mcp3d/pricing.js
+++ b/api/_mcp3d/pricing.js
@@ -111,6 +111,9 @@ export const FREE_TOOLS = Object.freeze(
'validate_spatial_response',
'export_ar',
'verify_provenance',
+ // Free on purpose and permanently. An assurance check that costs money is one
+ // nobody calls, and one nobody calls prevents nothing.
+ 'x402_preflight',
'persona_identity',
'persona_tip',
'persona_send',
diff --git a/mcp-server/src/tools/_studio-core.js b/mcp-server/src/tools/_studio-core.js
index 2f2132bd0..70b0f444e 100644
--- a/mcp-server/src/tools/_studio-core.js
+++ b/mcp-server/src/tools/_studio-core.js
@@ -937,7 +937,15 @@ function extractGlbUrl(output) {
return null;
}
+// Generous: a cold Replicate model can take a while to accept the job, and
+// failing early here wastes the user's prompt for nothing.
+const SUBMIT_TIMEOUT_MS = 30_000;
+
async function submitPrediction({ version, input }) {
+ // The poll loop below is bounded per request, but the submit that starts it
+ // was not: a stalled connection here held the whole tool invocation open with
+ // no prediction to poll for. Submitting is not idempotent (a retry buys a
+ // second GPU run), so this is a deadline only, never a retry.
const res = await fetch(`${REPLICATE_BASE}/predictions`, {
method: 'POST',
headers: replicateAuthHeaders(),
diff --git a/packages/glb-diff/LICENSE b/packages/glb-diff/LICENSE
new file mode 100644
index 000000000..dff21b7f4
--- /dev/null
+++ b/packages/glb-diff/LICENSE
@@ -0,0 +1,20 @@
+Copyright 2026 nirholas
+
+All rights reserved.
+
+This software is proprietary and may not be used, copied, modified, distributed,
+translated, or made available to any third party without the express written
+permission of the copyright owner.
+
+No rights are granted by implication, estoppel, or otherwise. Use of this
+software is subject to the terms of a separate license agreement with the
+copyright owner.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT.
+
+IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY CLAIM, DAMAGES, OR
+OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,
+ARISING FROM, OUT OF, OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
+DEALINGS IN THE SOFTWARE.
diff --git a/packages/glb-diff/package.json b/packages/glb-diff/package.json
new file mode 100644
index 000000000..8a248bcf6
--- /dev/null
+++ b/packages/glb-diff/package.json
@@ -0,0 +1,69 @@
+{
+ "name": "@three-ws/glb-diff",
+ "version": "0.1.0",
+ "description": "Structural diff for glTF/GLB. Tells you what actually changed between two 3D models: geometry, materials, textures, skeletons, animations, with git-style rename and move detection. Isomorphic library plus a CI-ready CLI.",
+ "type": "module",
+ "main": "./src/index.js",
+ "module": "./src/index.js",
+ "types": "./src/index.d.ts",
+ "bin": {
+ "glb-diff": "./src/cli.js"
+ },
+ "exports": {
+ ".": {
+ "types": "./src/index.d.ts",
+ "import": "./src/index.js",
+ "default": "./src/index.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "files": [
+ "src",
+ "README.md",
+ "LICENSE"
+ ],
+ "scripts": {
+ "test": "vitest run --root ../.. packages/glb-diff"
+ },
+ "keywords": [
+ "gltf",
+ "glb",
+ "diff",
+ "3d",
+ "gltf-transform",
+ "version-control",
+ "regression",
+ "ci",
+ "rename-detection",
+ "three.ws"
+ ],
+ "author": "nirholas <[email protected]>",
+ "license": "Apache-2.0",
+ "homepage": "https://three.ws/diff",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/nirholas/three.ws.git",
+ "directory": "packages/glb-diff"
+ },
+ "bugs": {
+ "url": "https://github.com/nirholas/three.ws/issues"
+ },
+ "engines": {
+ "node": ">=18"
+ },
+ "dependencies": {
+ "@gltf-transform/core": "^4.4.0",
+ "@gltf-transform/extensions": "^4.4.0"
+ },
+ "peerDependencies": {
+ "meshoptimizer": "^1.1.1"
+ },
+ "peerDependenciesMeta": {
+ "meshoptimizer": {
+ "optional": true
+ }
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/packages/glb-diff/src/cli.js b/packages/glb-diff/src/cli.js
new file mode 100755
index 000000000..d4387ee7f
--- /dev/null
+++ b/packages/glb-diff/src/cli.js
@@ -0,0 +1,148 @@
+#!/usr/bin/env node
+// glb-diff: what changed between two 3D models.
+//
+// glb-diff before.glb after.glb
+// glb-diff before.glb https://example.com/after.glb --markdown
+// glb-diff base.glb candidate.glb --fail-on major
+//
+// Exit codes are the contract a CI job depends on, so they are deliberate:
+// 0 the diff ran and stayed below --fail-on (default: never fails on changes)
+// 1 the diff ran and the severity reached --fail-on
+// 2 the tool could not run (bad arguments, unreadable input, unparseable model)
+// A tool that returns 1 for both "your model regressed" and "I could not open
+// the file" is useless in a pipeline, which is why 2 exists.
+
+import { readFile } from 'node:fs/promises';
+import process from 'node:process';
+import { diffModels } from './index.js';
+import { formatMarkdown, formatText } from './format.js';
+import { atLeast, SEVERITIES } from './severity.js';
+
+const USAGE = `glb-diff <before> <after> [options]
+
+ <before>, <after> a .glb/.gltf file path or an http(s) URL
+
+Options
+ --json print the full change set as JSON
+ --markdown print a Markdown report (for a pull-request comment)
+ --fail-on <level> exit 1 when severity reaches this level
+ (${SEVERITIES.slice(1).join(' | ')})
+ --verbose include unchanged totals in the table
+ --no-color disable ANSI colour
+ -h, --help show this help
+
+Examples
+ glb-diff avatar.v1.glb avatar.v2.glb
+ glb-diff base.glb optimized.glb --fail-on breaking
+ glb-diff a.glb b.glb --json > changes.json
+`;
+
+function parseArgs(argv) {
+ const opts = { positional: [], json: false, markdown: false, failOn: null, color: true, verbose: false, help: false };
+ for (let i = 0; i < argv.length; i++) {
+ const arg = argv[i];
+ if (arg === '--json') opts.json = true;
+ else if (arg === '--markdown' || arg === '--md') opts.markdown = true;
+ else if (arg === '--verbose') opts.verbose = true;
+ else if (arg === '--no-color') opts.color = false;
+ else if (arg === '-h' || arg === '--help') opts.help = true;
+ else if (arg === '--fail-on') {
+ const level = argv[++i];
+ if (!SEVERITIES.includes(level)) throw new Error(`--fail-on expects one of: ${SEVERITIES.slice(1).join(', ')}`);
+ opts.failOn = level;
+ } else if (arg.startsWith('--fail-on=')) {
+ const level = arg.slice('--fail-on='.length);
+ if (!SEVERITIES.includes(level)) throw new Error(`--fail-on expects one of: ${SEVERITIES.slice(1).join(', ')}`);
+ opts.failOn = level;
+ } else if (arg.startsWith('-')) {
+ throw new Error(`unknown option: ${arg}`);
+ } else {
+ opts.positional.push(arg);
+ }
+ }
+ return opts;
+}
+
+// A model is either on disk or behind a URL. Both are first-class: comparing a
+// local build against the copy already live on a CDN is the single most common
+// reason to reach for this, and making the user download it first would be
+// pointless friction.
+async function loadModel(ref) {
+ if (/^https?:\/\//i.test(ref)) {
+ const res = await fetch(ref, { redirect: 'follow' });
+ if (!res.ok) throw new Error(`${ref}: HTTP ${res.status}`);
+ return new Uint8Array(await res.arrayBuffer());
+ }
+ return new Uint8Array(await readFile(ref));
+}
+
+function label(ref) {
+ if (/^https?:\/\//i.test(ref)) {
+ try {
+ return new URL(ref).pathname.split('/').filter(Boolean).pop() || ref;
+ } catch {
+ return ref;
+ }
+ }
+ return ref.split('/').pop() || ref;
+}
+
+async function main() {
+ let opts;
+ try {
+ opts = parseArgs(process.argv.slice(2));
+ } catch (err) {
+ process.stderr.write(`${err.message}\n\n${USAGE}`);
+ return 2;
+ }
+
+ if (opts.help || opts.positional.length === 0) {
+ process.stdout.write(USAGE);
+ return opts.help ? 0 : 2;
+ }
+ if (opts.positional.length !== 2) {
+ process.stderr.write(`expected exactly two models, got ${opts.positional.length}\n\n${USAGE}`);
+ return 2;
+ }
+
+ const [refA, refB] = opts.positional;
+ let bytesA;
+ let bytesB;
+ try {
+ [bytesA, bytesB] = await Promise.all([loadModel(refA), loadModel(refB)]);
+ } catch (err) {
+ process.stderr.write(`could not read input: ${err.message}\n`);
+ return 2;
+ }
+
+ let changeset;
+ try {
+ changeset = await diffModels(bytesA, bytesB, { nameA: label(refA), nameB: label(refB) });
+ } catch (err) {
+ process.stderr.write(`could not parse model: ${err.message}\n`);
+ return 2;
+ }
+
+ if (opts.json) process.stdout.write(`${JSON.stringify(changeset, null, 2)}\n`);
+ else if (opts.markdown) process.stdout.write(`${formatMarkdown(changeset)}\n`);
+ else {
+ const color = opts.color && process.stdout.isTTY && !process.env.NO_COLOR;
+ process.stdout.write(`${formatText(changeset, { color, verbose: opts.verbose })}\n`);
+ }
+
+ if (opts.failOn && atLeast(changeset.severity, opts.failOn)) {
+ process.stderr.write(`glb-diff: severity "${changeset.severity}" reached --fail-on "${opts.failOn}"\n`);
+ return 1;
+ }
+ return 0;
+}
+
+main().then(
+ (code) => {
+ process.exitCode = code;
+ },
+ (err) => {
+ process.stderr.write(`glb-diff: ${err?.stack || err}\n`);
+ process.exitCode = 2;
+ },
+);
diff --git a/packages/glb-diff/src/describe.js b/packages/glb-diff/src/describe.js
new file mode 100644
index 000000000..d8c99efd5
--- /dev/null
+++ b/packages/glb-diff/src/describe.js
@@ -0,0 +1,464 @@
+// Turn a glTF Document into a flat, JSON-safe description of everything the
+// diff cares about.
+//
+// This is the seam that makes the rest of the engine testable and portable.
+// After describeDocument() runs there is no glTF-Transform object left in play,
+// only plain data, so the matcher and the differ are ordinary functions over
+// arrays that a unit test can build by hand. It is also what lets a description
+// be computed once in the browser, cached, and diffed repeatedly against
+// several candidates without re-parsing bytes.
+//
+// Two identity values hang off every entry and the distinction between them is
+// the whole trick:
+// key what the asset calls this thing (name, or hierarchy path for nodes)
+// fingerprint what this thing IS, with the name deliberately excluded
+// Matching on `key` finds the obvious pairs. Matching leftovers on `fingerprint`
+// is what turns "one object removed, one object added" into "renamed", which is
+// the difference between a diff you can read and a wall of noise.
+
+import { hashBytes, hashNumbers, hashString, hashValue } from './hash.js';
+import { isGLB, readDocument } from './document.js';
+
+export const DESCRIPTION_VERSION = 1;
+
+// glTF primitive modes that produce triangles, and how many vertices each
+// triangle consumes. Anything else (points, lines) contributes zero triangles.
+const TRIANGLE_MODES = new Set([4, 5, 6]);
+
+const PRIMITIVE_MODE_NAMES = {
+ 0: 'POINTS',
+ 1: 'LINES',
+ 2: 'LINE_LOOP',
+ 3: 'LINE_STRIP',
+ 4: 'TRIANGLES',
+ 5: 'TRIANGLE_STRIP',
+ 6: 'TRIANGLE_FAN',
+};
+
+// Attribute semantics whose values participate in the geometry hash, in a fixed
+// order so the hash is stable. Positions decide "is this the same shape";
+// normals and UVs decide "was it re-baked"; skin weights decide "was it
+// re-skinned", which is a change a positions-only hash would miss entirely and
+// which breaks animation in exactly the way this tool exists to catch.
+const HASHED_SEMANTICS = ['POSITION', 'NORMAL', 'TANGENT', 'TEXCOORD_0', 'TEXCOORD_1', 'COLOR_0', 'JOINTS_0', 'WEIGHTS_0'];
+
+function nameOf(prop, fallback) {
+ const n = prop && typeof prop.getName === 'function' ? prop.getName() : '';
+ return n || fallback;
+}
+
+// glTF names are optional, and plenty of exporters ship none. Inventing
+// "mesh.0" would be worse than useless: it reads like a real name in the report
+// and, worse, would match an unrelated object that happens to be third in the
+// other file. Unnamed objects get a label that admits what it is and a key
+// scoped to their index, so they only ever pair with the same slot on the other
+// side.
+function identify(prop, type, index) {
+ const raw = prop && typeof prop.getName === 'function' ? prop.getName() : '';
+ if (raw) return { name: raw, key: raw, unnamed: false };
+ return { name: `(unnamed ${type} ${index})`, key: `#${type}.${index}`, unnamed: true };
+}
+
+function round(value, places = 5) {
+ if (!Number.isFinite(value)) return 0;
+ const f = 10 ** places;
+ return Math.round(value * f) / f;
+}
+
+function roundArray(arr, places = 5) {
+ if (!arr) return null;
+ return Array.from(arr, (v) => round(v, places));
+}
+
+// ── Geometry ─────────────────────────────────────────────────────────────────
+
+function describePrimitive(prim, materialNames) {
+ const position = prim.getAttribute('POSITION');
+ const vertices = position ? position.getCount() : 0;
+ const indices = prim.getIndices();
+ const mode = prim.getMode();
+ const indexCount = indices ? indices.getCount() : 0;
+ let triangles = 0;
+ if (TRIANGLE_MODES.has(mode)) {
+ const count = indices ? indexCount : vertices;
+ triangles = mode === 4 ? Math.floor(count / 3) : Math.max(0, count - 2);
+ }
+
+ const semantics = prim.listSemantics().slice().sort();
+ const material = prim.getMaterial();
+
+ // The per-primitive geometry hash. Attribute arrays are hashed in a fixed
+ // order under a seed naming the semantic, so a model that gained a UV set
+ // does not hash the same as one that lost a color set of equal length.
+ let geometry = hashString(`mode:${mode}`);
+ for (const semantic of HASHED_SEMANTICS) {
+ const attr = prim.getAttribute(semantic);
+ if (!attr) continue;
+ geometry = hashString(
+ geometry + hashNumbers(attr.getArray(), { seed: semantic, quantize: !semantic.startsWith('JOINTS') }),
+ );
+ }
+ if (indices) geometry = hashString(geometry + hashNumbers(indices.getArray(), { quantize: false, seed: 'INDICES' }));
+
+ const targets = prim.listTargets().length;
+
+ return {
+ mode,
+ modeName: PRIMITIVE_MODE_NAMES[mode] || `MODE_${mode}`,
+ material: material ? nameOf(material, `material.${materialNames.get(material) ?? '?'}`) : null,
+ attributes: semantics,
+ vertices,
+ triangles,
+ indexed: Boolean(indices),
+ morphTargets: targets,
+ geometryHash: geometry,
+ };
+}
+
+function boundsOf(prim) {
+ const position = prim.getAttribute('POSITION');
+ if (!position) return null;
+ const min = position.getMin([]);
+ const max = position.getMax([]);
+ if (!min || !max || min.length < 3) return null;
+ return { min: roundArray(min), max: roundArray(max) };
+}
+
+function unionBounds(a, b) {
+ if (!a) return b;
+ if (!b) return a;
+ return {
+ min: a.min.map((v, i) => Math.min(v, b.min[i])),
+ max: a.max.map((v, i) => Math.max(v, b.max[i])),
+ };
+}
+
+function describeMesh(mesh, index, materialNames) {
+ const id = identify(mesh, 'mesh', index);
+ const primitives = mesh.listPrimitives().map((p) => describePrimitive(p, materialNames));
+ let bounds = null;
+ for (const prim of mesh.listPrimitives()) bounds = unionBounds(bounds, boundsOf(prim));
+
+ const vertices = primitives.reduce((sum, p) => sum + p.vertices, 0);
+ const triangles = primitives.reduce((sum, p) => sum + p.triangles, 0);
+ const geometryHash = hashString(primitives.map((p) => p.geometryHash).join('|'));
+
+ return {
+ type: 'mesh',
+ index,
+ name: id.name,
+ unnamed: id.unnamed,
+ primitives,
+ vertices,
+ triangles,
+ bounds,
+ geometryHash,
+ key: id.key,
+ fingerprint: hashString(`${geometryHash}|${primitives.map((p) => p.material || '').join(',')}`),
+ };
+}
+
+// ── Hierarchy ────────────────────────────────────────────────────────────────
+
+// Walk the scene graph and give every node a stable path. Siblings that share a
+// name get a positional suffix, because a rig with three nodes called "Bone"
+// under one parent is real and a path that cannot tell them apart would report
+// phantom moves on every export.
+function describeNodes(root, meshByProp) {
+ const out = [];
+ const seen = new Set();
+ let index = 0;
+
+ const visit = (node, parentPath, parentName, depth) => {
+ const siblings = parentPath === null ? [] : null;
+ void siblings;
+ const raw = nameOf(node, `#node.${index}`);
+ const path = parentPath ? `${parentPath}/${raw}` : raw;
+ let unique = path;
+ let bump = 1;
+ while (seen.has(unique)) unique = `${path}#${bump++}`;
+ seen.add(unique);
+
+ const mesh = node.getMesh();
+ const skin = node.getSkin();
+ const camera = node.getCamera();
+ const children = node.listChildren();
+ const translation = roundArray(node.getTranslation());
+ const rotation = roundArray(node.getRotation());
+ const scale = roundArray(node.getScale());
+ const meshDesc = mesh ? meshByProp.get(mesh) : null;
+
+ out.push({
+ type: 'node',
+ index: index++,
+ name: raw,
+ path: unique,
+ parent: parentName,
+ depth,
+ translation,
+ rotation,
+ scale,
+ mesh: meshDesc ? meshDesc.name : null,
+ skin: skin ? nameOf(skin, 'skin') : null,
+ camera: camera ? nameOf(camera, 'camera') : null,
+ childCount: children.length,
+ key: unique,
+ // Name-free identity: where it sits, what it carries, how it is posed.
+ // A node that keeps its geometry and transform but changes name is a
+ // rename; one that keeps its name and changes geometry is an edit.
+ fingerprint: hashValue({
+ t: translation,
+ r: rotation,
+ s: scale,
+ g: meshDesc ? meshDesc.geometryHash : null,
+ skin: Boolean(skin),
+ children: children.length,
+ depth,
+ }),
+ });
+
+ for (const child of children) visit(child, unique, raw, depth + 1);
+ };
+
+ for (const scene of root.listScenes()) {
+ for (const node of scene.listChildren()) visit(node, '', null, 0);
+ }
+ // Nodes reachable from no scene still ship in the file and still cost bytes,
+ // so they are described rather than silently dropped.
+ const covered = new Set(out.map((n) => n.name));
+ for (const node of root.listNodes()) {
+ if (node.getParentNode()) continue;
+ const raw = nameOf(node, 'node');
+ if (covered.has(raw)) continue;
+ visit(node, '(detached)', null, 0);
+ }
+ return out;
+}
+
+// ── Appearance ───────────────────────────────────────────────────────────────
+
+const TEXTURE_SLOTS = [
+ ['baseColor', 'getBaseColorTexture'],
+ ['metallicRoughness', 'getMetallicRoughnessTexture'],
+ ['normal', 'getNormalTexture'],
+ ['occlusion', 'getOcclusionTexture'],
+ ['emissive', 'getEmissiveTexture'],
+];
+
+function describeMaterial(material, index, textureByProp) {
+ const id = identify(material, 'material', index);
+ const slots = {};
+ for (const [slot, getter] of TEXTURE_SLOTS) {
+ const tex = material[getter]();
+ const desc = tex ? textureByProp.get(tex) : null;
+ slots[slot] = desc ? desc.name : tex ? 'texture' : null;
+ }
+ const core = {
+ baseColorFactor: roundArray(material.getBaseColorFactor()),
+ metallic: round(material.getMetallicFactor()),
+ roughness: round(material.getRoughnessFactor()),
+ emissiveFactor: roundArray(material.getEmissiveFactor()),
+ normalScale: round(material.getNormalScale()),
+ occlusionStrength: round(material.getOcclusionStrength()),
+ alphaMode: material.getAlphaMode(),
+ alphaCutoff: round(material.getAlphaCutoff()),
+ doubleSided: material.getDoubleSided(),
+ textures: slots,
+ };
+ const extensions = material
+ .listExtensions()
+ .map((e) => e.extensionName)
+ .sort();
+ return {
+ type: 'material',
+ index,
+ name: id.name,
+ unnamed: id.unnamed,
+ ...core,
+ extensions,
+ key: id.key,
+ fingerprint: hashValue({ ...core, extensions }),
+ };
+}
+
+function describeTexture(texture, index) {
+ const id = identify(texture, 'texture', index);
+ const image = texture.getImage();
+ const size = texture.getSize();
+ const [width, height] = size || [0, 0];
+ const bytes = image ? image.byteLength : 0;
+ const pixelHash = image ? hashBytes(image) : null;
+ return {
+ type: 'texture',
+ index,
+ name: id.name,
+ unnamed: id.unnamed,
+ mimeType: texture.getMimeType() || null,
+ uri: texture.getURI() || null,
+ width,
+ height,
+ bytes,
+ pixelHash,
+ key: id.key,
+ fingerprint: pixelHash || hashValue({ width, height, bytes, mime: texture.getMimeType() }),
+ };
+}
+
+// ── Motion ───────────────────────────────────────────────────────────────────
+
+function samplerDuration(sampler) {
+ const input = sampler.getInput();
+ if (!input) return 0;
+ const max = input.getMax([]);
+ if (Array.isArray(max) && Number.isFinite(max[0])) return max[0];
+ const array = input.getArray();
+ return array && array.length ? array[array.length - 1] : 0;
+}
+
+function describeAnimation(animation, index) {
+ const id = identify(animation, 'animation', index);
+ const channels = animation.listChannels();
+ const samplers = animation.listSamplers();
+ let duration = 0;
+ for (const sampler of samplers) duration = Math.max(duration, samplerDuration(sampler));
+
+ // Which node each channel drives, and along which path. This is the list that
+ // decides whether a clip still plays after a rig edit, so it is compared
+ // entry by entry rather than summarized into a count.
+ const targets = channels
+ .map((ch) => {
+ const node = ch.getTargetNode();
+ return `${node ? nameOf(node, 'node') : '(none)'}.${ch.getTargetPath()}`;
+ })
+ .sort();
+
+ const interpolations = [...new Set(samplers.map((s) => s.getInterpolation()))].sort();
+ const keyframes = samplers.reduce((sum, s) => {
+ const input = s.getInput();
+ return sum + (input ? input.getCount() : 0);
+ }, 0);
+
+ return {
+ type: 'animation',
+ index,
+ name: id.name,
+ unnamed: id.unnamed,
+ duration: round(duration, 4),
+ channels: channels.length,
+ samplers: samplers.length,
+ keyframes,
+ interpolations,
+ targets,
+ key: id.key,
+ fingerprint: hashValue({ duration: round(duration, 4), targets, keyframes, interpolations }),
+ };
+}
+
+function describeSkin(skin, index) {
+ const id = identify(skin, 'skin', index);
+ const joints = skin.listJoints().map((j) => nameOf(j, 'joint'));
+ const ibm = skin.getInverseBindMatrices();
+ const bindHash = ibm ? hashNumbers(ibm.getArray()) : null;
+ const skeleton = skin.getSkeleton();
+ return {
+ type: 'skin',
+ index,
+ name: id.name,
+ unnamed: id.unnamed,
+ joints,
+ jointCount: joints.length,
+ skeleton: skeleton ? nameOf(skeleton, 'root') : null,
+ bindHash,
+ key: id.key,
+ fingerprint: hashValue({ joints, bindHash }),
+ };
+}
+
+// ── Entry point ──────────────────────────────────────────────────────────────
+
+/**
+ * Describe a parsed Document.
+ * @param {import('@gltf-transform/core').Document} document
+ * @param {{ name?: string, sizeBytes?: number, container?: 'glb'|'gltf' }} [meta]
+ */
+export function describeDocument(document, meta = {}) {
+ const root = document.getRoot();
+ const asset = root.getAsset();
+
+ const materialProps = root.listMaterials();
+ const textureProps = root.listTextures();
+ const meshProps = root.listMeshes();
+
+ const materialIndex = new Map(materialProps.map((m, i) => [m, i]));
+ const textureByProp = new Map();
+ const textures = textureProps.map((t, i) => {
+ const desc = describeTexture(t, i);
+ textureByProp.set(t, desc);
+ return desc;
+ });
+ const materials = materialProps.map((m, i) => describeMaterial(m, i, textureByProp));
+ const meshByProp = new Map();
+ const meshes = meshProps.map((m, i) => {
+ const desc = describeMesh(m, i, materialIndex);
+ meshByProp.set(m, desc);
+ return desc;
+ });
+ const nodes = describeNodes(root, meshByProp);
+ const animations = root.listAnimations().map((a, i) => describeAnimation(a, i));
+ const skins = root.listSkins().map((s, i) => describeSkin(s, i));
+
+ const totals = {
+ scenes: root.listScenes().length,
+ nodes: nodes.length,
+ meshes: meshes.length,
+ materials: materials.length,
+ textures: textures.length,
+ animations: animations.length,
+ skins: skins.length,
+ joints: skins.reduce((sum, s) => sum + s.jointCount, 0),
+ vertices: meshes.reduce((sum, m) => sum + m.vertices, 0),
+ triangles: meshes.reduce((sum, m) => sum + m.triangles, 0),
+ textureBytes: textures.reduce((sum, t) => sum + t.bytes, 0),
+ sizeBytes: meta.sizeBytes ?? 0,
+ };
+
+ return {
+ version: DESCRIPTION_VERSION,
+ name: meta.name || null,
+ container: meta.container || null,
+ asset: {
+ generator: asset.generator || null,
+ version: asset.version || null,
+ copyright: asset.copyright || null,
+ },
+ extensionsUsed: root
+ .listExtensionsUsed()
+ .map((x) => x.extensionName)
+ .sort(),
+ extensionsRequired: root
+ .listExtensionsRequired()
+ .map((x) => x.extensionName)
+ .sort(),
+ totals,
+ nodes,
+ meshes,
+ materials,
+ textures,
+ animations,
+ skins,
+ };
+}
+
+/**
+ * Read bytes and describe them in one call.
+ * @param {Uint8Array} bytes
+ * @param {{ name?: string }} [meta]
+ */
+export async function describeModel(bytes, meta = {}) {
+ const document = await readDocument(bytes);
+ return describeDocument(document, {
+ ...meta,
+ sizeBytes: bytes.byteLength,
+ container: isGLB(bytes) ? 'glb' : 'gltf',
+ });
+}
diff --git a/packages/glb-diff/src/diff.js b/packages/glb-diff/src/diff.js
new file mode 100644
index 000000000..6991323e9
--- /dev/null
+++ b/packages/glb-diff/src/diff.js
@@ -0,0 +1,535 @@
+// The diff itself: two descriptions in, one change set out.
+//
+// Everything here is a pure function over the plain data describe.js produces,
+// which is what makes the output reproducible: the same two files always yield
+// the same change set, byte for byte, on any machine. That matters because the
+// change set is meant to be committed, posted to a pull request, and compared
+// against yesterday's.
+
+import { canonicalize } from './hash.js';
+import { jaccard, matchEntries, ratio } from './match.js';
+import { maxSeverity } from './severity.js';
+
+export const CHANGESET_VERSION = 1;
+
+function equalish(a, b) {
+ if (a === b) return true;
+ if (a === null || b === null || a === undefined || b === undefined) return false;
+ if (typeof a === 'object' || typeof b === 'object') return canonicalize(a) === canonicalize(b);
+ return false;
+}
+
+/** Record a field-level change, or nothing when the field held still. */
+function field(changes, name, a, b, severity, note) {
+ if (equalish(a, b)) return;
+ changes.push({ field: name, a: a ?? null, b: b ?? null, severity, ...(note ? { note } : {}) });
+}
+
+function listDelta(a = [], b = []) {
+ const setA = new Set(a);
+ const setB = new Set(b);
+ return {
+ added: b.filter((v) => !setA.has(v)),
+ removed: a.filter((v) => !setB.has(v)),
+ };
+}
+
+function emptySection() {
+ return { added: [], removed: [], renamed: [], modified: [], unchanged: 0, similarityLimited: false };
+}
+
+function summarize(section) {
+ const severities = [
+ ...section.added.map((x) => x.severity),
+ ...section.removed.map((x) => x.severity),
+ ...section.modified.map((x) => x.severity),
+ ...(section.moved || []).map(() => 'major'),
+ ...section.renamed.map(() => 'cosmetic'),
+ ];
+ section.severity = maxSeverity(severities);
+ section.changed =
+ section.added.length +
+ section.removed.length +
+ section.modified.length +
+ section.renamed.length +
+ (section.moved ? section.moved.length : 0);
+ return section;
+}
+
+// ── Sections ─────────────────────────────────────────────────────────────────
+
+function diffNodes(a, b) {
+ const section = { ...emptySection(), moved: [] };
+ const match = matchEntries(a.nodes, b.nodes, {
+ threshold: 0.62,
+ similarity: (x, y) =>
+ 0.4 * (x.name === y.name ? 1 : 0) +
+ 0.2 * (x.parent === y.parent ? 1 : 0) +
+ 0.2 * ratio(x.childCount, y.childCount) +
+ 0.1 * (x.mesh === y.mesh ? 1 : 0) +
+ 0.1 * (x.depth === y.depth ? 1 : 0),
+ });
+ section.similarityLimited = match.similarityLimited;
+
+ for (const node of match.removed) {
+ section.removed.push({
+ name: node.path,
+ // A node carrying geometry or a skin is load-bearing: a scene that
+ // attached to it by name has nothing left to attach to.
+ severity: node.mesh || node.skin ? 'breaking' : 'major',
+ detail: node.mesh ? `carried mesh "${node.mesh}"` : node.skin ? `carried skin "${node.skin}"` : 'empty node',
+ });
+ }
+ for (const node of match.added) {
+ section.added.push({
+ name: node.path,
+ severity: 'major',
+ detail: node.mesh ? `carries mesh "${node.mesh}"` : 'empty node',
+ });
+ }
+
+ for (const { a: x, b: y } of match.pairs) {
+ const changes = [];
+ field(changes, 'translation', x.translation, y.translation, 'minor');
+ field(changes, 'rotation', x.rotation, y.rotation, 'minor');
+ field(changes, 'scale', x.scale, y.scale, 'minor');
+ field(changes, 'mesh', x.mesh, y.mesh, 'major');
+ field(changes, 'skin', x.skin, y.skin, 'major');
+ field(changes, 'children', x.childCount, y.childCount, 'major');
+
+ if (x.name !== y.name) section.renamed.push({ from: x.path, to: y.path, name: y.name });
+ else if (x.parent !== y.parent) section.moved.push({ from: x.path, to: y.path, name: y.name });
+
+ if (changes.length) {
+ section.modified.push({ name: y.path, from: x.path, changes, severity: maxSeverity(changes.map((c) => c.severity)) });
+ } else if (x.name === y.name && x.parent === y.parent) {
+ section.unchanged++;
+ }
+ }
+ return summarize(section);
+}
+
+function diffMeshes(a, b) {
+ const section = emptySection();
+ const match = matchEntries(a.meshes, b.meshes, {
+ threshold: 0.6,
+ similarity: (x, y) =>
+ 0.45 * ratio(x.vertices, y.vertices) +
+ 0.2 * ratio(x.triangles, y.triangles) +
+ 0.15 * ratio(x.primitives.length, y.primitives.length) +
+ 0.2 *
+ jaccard(
+ x.primitives.flatMap((p) => p.attributes),
+ y.primitives.flatMap((p) => p.attributes),
+ ),
+ });
+ section.similarityLimited = match.similarityLimited;
+
+ for (const mesh of match.removed) {
+ section.removed.push({
+ name: mesh.name,
+ severity: 'breaking',
+ detail: `${mesh.triangles.toLocaleString()} triangles gone`,
+ });
+ }
+ for (const mesh of match.added) {
+ section.added.push({ name: mesh.name, severity: 'major', detail: `${mesh.triangles.toLocaleString()} triangles` });
+ }
+
+ for (const { a: x, b: y } of match.pairs) {
+ const changes = [];
+ if (x.geometryHash !== y.geometryHash) {
+ changes.push({
+ field: 'geometry',
+ a: x.geometryHash,
+ b: y.geometryHash,
+ severity: 'major',
+ note:
+ x.vertices === y.vertices && x.triangles === y.triangles
+ ? 'same vertex and triangle count, different vertex data'
+ : 'vertex data rewritten',
+ });
+ }
+ field(changes, 'vertices', x.vertices, y.vertices, 'major');
+ field(changes, 'triangles', x.triangles, y.triangles, 'major');
+ field(changes, 'primitives', x.primitives.length, y.primitives.length, 'major');
+ field(changes, 'bounds', x.bounds, y.bounds, 'minor');
+ field(
+ changes,
+ 'materials',
+ x.primitives.map((p) => p.material),
+ y.primitives.map((p) => p.material),
+ 'minor',
+ );
+ field(
+ changes,
+ 'attributes',
+ [...new Set(x.primitives.flatMap((p) => p.attributes))].sort(),
+ [...new Set(y.primitives.flatMap((p) => p.attributes))].sort(),
+ 'major',
+ );
+ field(
+ changes,
+ 'morphTargets',
+ x.primitives.reduce((s, p) => s + p.morphTargets, 0),
+ y.primitives.reduce((s, p) => s + p.morphTargets, 0),
+ 'major',
+ );
+
+ if (x.name !== y.name) section.renamed.push({ from: x.name, to: y.name, name: y.name });
+ if (changes.length) {
+ section.modified.push({ name: y.name, from: x.name, changes, severity: maxSeverity(changes.map((c) => c.severity)) });
+ } else if (x.name === y.name) {
+ section.unchanged++;
+ }
+ }
+ return summarize(section);
+}
+
+function diffMaterials(a, b) {
+ const section = emptySection();
+ const match = matchEntries(a.materials, b.materials, {
+ threshold: 0.62,
+ similarity: (x, y) =>
+ 0.3 * (x.alphaMode === y.alphaMode ? 1 : 0) +
+ 0.3 *
+ jaccard(
+ Object.entries(x.textures).filter(([, v]) => v).map(([k]) => k),
+ Object.entries(y.textures).filter(([, v]) => v).map(([k]) => k),
+ ) +
+ 0.2 * ratio(1 + x.metallic, 1 + y.metallic) +
+ 0.2 * ratio(1 + x.roughness, 1 + y.roughness),
+ });
+ section.similarityLimited = match.similarityLimited;
+
+ for (const m of match.removed) section.removed.push({ name: m.name, severity: 'major', detail: 'material removed' });
+ for (const m of match.added) section.added.push({ name: m.name, severity: 'minor', detail: 'material added' });
+
+ for (const { a: x, b: y } of match.pairs) {
+ const changes = [];
+ field(changes, 'baseColorFactor', x.baseColorFactor, y.baseColorFactor, 'minor');
+ field(changes, 'metallic', x.metallic, y.metallic, 'minor');
+ field(changes, 'roughness', x.roughness, y.roughness, 'minor');
+ field(changes, 'emissiveFactor', x.emissiveFactor, y.emissiveFactor, 'minor');
+ field(changes, 'normalScale', x.normalScale, y.normalScale, 'minor');
+ field(changes, 'occlusionStrength', x.occlusionStrength, y.occlusionStrength, 'minor');
+ field(changes, 'alphaMode', x.alphaMode, y.alphaMode, 'minor');
+ field(changes, 'alphaCutoff', x.alphaCutoff, y.alphaCutoff, 'minor');
+ field(changes, 'doubleSided', x.doubleSided, y.doubleSided, 'minor');
+ field(changes, 'extensions', x.extensions, y.extensions, 'minor');
+ for (const slot of Object.keys(x.textures)) {
+ field(changes, `texture.${slot}`, x.textures[slot], y.textures[slot], 'minor');
+ }
+
+ if (x.name !== y.name) section.renamed.push({ from: x.name, to: y.name, name: y.name });
+ if (changes.length) {
+ section.modified.push({ name: y.name, from: x.name, changes, severity: maxSeverity(changes.map((c) => c.severity)) });
+ } else if (x.name === y.name) {
+ section.unchanged++;
+ }
+ }
+ return summarize(section);
+}
+
+function diffTextures(a, b) {
+ const section = emptySection();
+ const match = matchEntries(a.textures, b.textures, {
+ threshold: 0.6,
+ similarity: (x, y) =>
+ 0.4 * (x.width === y.width && x.height === y.height ? 1 : 0) +
+ 0.3 * (x.mimeType === y.mimeType ? 1 : 0) +
+ 0.3 * ratio(x.bytes, y.bytes),
+ });
+ section.similarityLimited = match.similarityLimited;
+
+ for (const t of match.removed) {
+ section.removed.push({ name: t.name, severity: 'minor', detail: `${t.width}x${t.height}, ${t.bytes} bytes` });
+ }
+ for (const t of match.added) {
+ section.added.push({ name: t.name, severity: 'minor', detail: `${t.width}x${t.height}, ${t.bytes} bytes` });
+ }
+
+ for (const { a: x, b: y } of match.pairs) {
+ const changes = [];
+ field(changes, 'width', x.width, y.width, 'minor');
+ field(changes, 'height', x.height, y.height, 'minor');
+ field(changes, 'mimeType', x.mimeType, y.mimeType, 'minor');
+ field(changes, 'bytes', x.bytes, y.bytes, 'cosmetic');
+ if (x.pixelHash !== y.pixelHash) {
+ changes.push({ field: 'pixels', a: x.pixelHash, b: y.pixelHash, severity: 'minor', note: 'image data changed' });
+ }
+
+ if (x.name !== y.name) section.renamed.push({ from: x.name, to: y.name, name: y.name });
+ if (changes.length) {
+ section.modified.push({ name: y.name, from: x.name, changes, severity: maxSeverity(changes.map((c) => c.severity)) });
+ } else if (x.name === y.name) {
+ section.unchanged++;
+ }
+ }
+ return summarize(section);
+}
+
+function diffAnimations(a, b) {
+ const section = emptySection();
+ const match = matchEntries(a.animations, b.animations, {
+ threshold: 0.6,
+ similarity: (x, y) => 0.65 * jaccard(x.targets, y.targets) + 0.35 * ratio(x.duration, y.duration),
+ });
+ section.similarityLimited = match.similarityLimited;
+
+ for (const clip of match.removed) {
+ section.removed.push({ name: clip.name, severity: 'breaking', detail: `${clip.duration}s clip gone` });
+ }
+ for (const clip of match.added) {
+ section.added.push({ name: clip.name, severity: 'minor', detail: `${clip.duration}s clip` });
+ }
+
+ for (const { a: x, b: y } of match.pairs) {
+ const changes = [];
+ field(changes, 'duration', x.duration, y.duration, 'major');
+ field(changes, 'channels', x.channels, y.channels, 'major');
+ field(changes, 'keyframes', x.keyframes, y.keyframes, 'minor');
+ field(changes, 'interpolations', x.interpolations, y.interpolations, 'minor');
+ const targets = listDelta(x.targets, y.targets);
+ if (targets.removed.length) {
+ changes.push({
+ field: 'targets',
+ a: targets.removed,
+ b: [],
+ severity: 'breaking',
+ note: `${targets.removed.length} channel target(s) no longer driven`,
+ });
+ }
+ if (targets.added.length) {
+ changes.push({ field: 'targets', a: [], b: targets.added, severity: 'major', note: `${targets.added.length} new channel target(s)` });
+ }
+
+ if (x.name !== y.name) section.renamed.push({ from: x.name, to: y.name, name: y.name });
+ if (changes.length) {
+ section.modified.push({ name: y.name, from: x.name, changes, severity: maxSeverity(changes.map((c) => c.severity)) });
+ } else if (x.name === y.name) {
+ section.unchanged++;
+ }
+ }
+ return summarize(section);
+}
+
+function diffSkins(a, b) {
+ const section = emptySection();
+ const match = matchEntries(a.skins, b.skins, {
+ threshold: 0.5,
+ similarity: (x, y) => jaccard(x.joints, y.joints),
+ });
+ section.similarityLimited = match.similarityLimited;
+
+ for (const skin of match.removed) {
+ section.removed.push({ name: skin.name, severity: 'breaking', detail: `${skin.jointCount} joints gone` });
+ }
+ for (const skin of match.added) {
+ section.added.push({ name: skin.name, severity: 'major', detail: `${skin.jointCount} joints` });
+ }
+
+ for (const { a: x, b: y } of match.pairs) {
+ const changes = [];
+ const joints = listDelta(x.joints, y.joints);
+ if (joints.removed.length) {
+ changes.push({
+ field: 'joints',
+ a: joints.removed,
+ b: [],
+ severity: 'breaking',
+ // Named-bone lookup is how every retargeter and every baked clip
+ // finds a joint, so a removed or renamed bone is a silent no-op at
+ // runtime rather than an error anyone sees.
+ note: `${joints.removed.length} joint name(s) removed; clips addressing them will not play`,
+ });
+ }
+ if (joints.added.length) {
+ changes.push({ field: 'joints', a: [], b: joints.added, severity: 'major', note: `${joints.added.length} joint name(s) added` });
+ }
+ field(changes, 'jointCount', x.jointCount, y.jointCount, 'major');
+ field(changes, 'skeleton', x.skeleton, y.skeleton, 'major');
+ if (x.bindHash !== y.bindHash) {
+ changes.push({
+ field: 'inverseBindMatrices',
+ a: x.bindHash,
+ b: y.bindHash,
+ severity: 'major',
+ note: 'bind pose changed; existing clips will deform differently',
+ });
+ }
+
+ if (x.name !== y.name) section.renamed.push({ from: x.name, to: y.name, name: y.name });
+ if (changes.length) {
+ section.modified.push({ name: y.name, from: x.name, changes, severity: maxSeverity(changes.map((c) => c.severity)) });
+ } else if (x.name === y.name) {
+ section.unchanged++;
+ }
+ }
+ return summarize(section);
+}
+
+// ── Assembly ─────────────────────────────────────────────────────────────────
+
+function deltaBlock(a, b) {
+ const out = {};
+ for (const key of Object.keys(a)) {
+ const from = a[key] ?? 0;
+ const to = b[key] ?? 0;
+ out[key] = {
+ a: from,
+ b: to,
+ delta: to - from,
+ pct: from === 0 ? (to === 0 ? 0 : null) : Math.round(((to - from) / from) * 1000) / 10,
+ };
+ }
+ return out;
+}
+
+// The plain-language layer. A change set is precise but long; these are the
+// three or four sentences someone actually reads before deciding whether to
+// look closer, ordered worst first.
+function buildHighlights(sections, totals, extensions, asset) {
+ const out = [];
+ const push = (severity, text) => out.push({ severity, text });
+
+ for (const skin of sections.skins.modified) {
+ const lost = skin.changes.find((c) => c.field === 'joints' && c.a.length);
+ if (lost) push('breaking', `Skeleton "${skin.name}" lost ${lost.a.length} joint(s): ${lost.a.slice(0, 4).join(', ')}${lost.a.length > 4 ? ', ...' : ''}. Clips that target them will not play.`);
+ }
+ // Removals are grouped once past a couple of entries. A highlight list that
+ // prints one line per removed mesh stops being a summary and becomes the raw
+ // section it was supposed to summarize.
+ const group = (items, one, many) => {
+ if (!items.length) return;
+ if (items.length <= 2) for (const item of items) push('breaking', one(item));
+ else push('breaking', many(items));
+ };
+ group(
+ sections.skins.removed,
+ (skin) => `Skeleton "${skin.name}" was removed. The model is no longer rigged.`,
+ (items) => `${items.length} skeletons were removed. The model is no longer rigged.`,
+ );
+ group(
+ sections.animations.removed,
+ (clip) => `Animation "${clip.name}" was removed. Anything that plays it by name will fail.`,
+ (items) => `${items.length} animations were removed (${namesOf(items)}). Anything that plays them by name will fail.`,
+ );
+ group(
+ sections.meshes.removed,
+ (mesh) => `Mesh "${mesh.name}" was removed (${mesh.detail}).`,
+ (items) => `${items.length} meshes were removed (${namesOf(items)}).`,
+ );
+
+ const geometryEdits = sections.meshes.modified.filter((m) => m.changes.some((c) => c.field === 'geometry'));
+ if (geometryEdits.length) {
+ push('major', `${geometryEdits.length} mesh(es) have different vertex data: ${geometryEdits.slice(0, 3).map((m) => `"${m.name}"`).join(', ')}${geometryEdits.length > 3 ? ', ...' : ''}.`);
+ }
+ if (totals.triangles.delta !== 0) {
+ const dir = totals.triangles.delta > 0 ? 'up' : 'down';
+ push('major', `Triangle count is ${dir} ${Math.abs(totals.triangles.delta).toLocaleString()} (${totals.triangles.pct === null ? 'from zero' : `${totals.triangles.pct > 0 ? '+' : ''}${totals.triangles.pct}%`}).`);
+ }
+ const clipEdits = sections.animations.modified;
+ if (clipEdits.length) {
+ const worst = clipEdits.find((c) => c.severity === 'breaking');
+ push(
+ worst ? 'breaking' : 'major',
+ `${clipEdits.length} animation(s) changed: ${clipEdits.slice(0, 3).map((c) => `"${c.name}"`).join(', ')}${clipEdits.length > 3 ? ', ...' : ''}.`,
+ );
+ }
+ if (sections.nodes.moved.length) {
+ push('major', `${sections.nodes.moved.length} node(s) moved to a different parent, which changes where anything attached to them ends up.`);
+ }
+ if (extensions.required.added.length) {
+ push('major', `New required extension(s): ${extensions.required.added.join(', ')}. A viewer without support will refuse the file.`);
+ }
+
+ const textureEdits = sections.textures.modified.filter((t) => t.changes.some((c) => c.field === 'pixels'));
+ if (textureEdits.length) push('minor', `${textureEdits.length} texture(s) were re-encoded or repainted.`);
+ if (sections.materials.changed) push('minor', `${sections.materials.changed} material change(s).`);
+ if (totals.sizeBytes.delta !== 0 && totals.sizeBytes.a > 0) {
+ const dir = totals.sizeBytes.delta > 0 ? 'larger' : 'smaller';
+ // A sub-0.1% delta rounds to "0%", which reads as a contradiction next to a
+ // real byte count, so the percentage is dropped rather than printed as zero.
+ const pct = totals.sizeBytes.pct === 0 ? '' : ` (${totals.sizeBytes.pct > 0 ? '+' : ''}${totals.sizeBytes.pct}%)`;
+ push('minor', `File is ${formatBytes(Math.abs(totals.sizeBytes.delta))} ${dir}${pct}.`);
+ }
+
+ const renames = sections.nodes.renamed.length + sections.meshes.renamed.length + sections.materials.renamed.length + sections.animations.renamed.length + sections.skins.renamed.length + sections.textures.renamed.length;
+ if (renames) push('cosmetic', `${renames} object(s) kept their content and changed name.`);
+ if (asset.length) push('cosmetic', `Asset metadata changed: ${asset.map((c) => c.field).join(', ')}.`);
+
+ return out;
+}
+
+// First few names plus a count, so a grouped highlight still says which objects
+// it is talking about.
+function namesOf(items, limit = 3) {
+ const shown = items.slice(0, limit).map((i) => `"${i.name}"`).join(', ');
+ return items.length > limit ? `${shown} and ${items.length - limit} more` : shown;
+}
+
+export function formatBytes(n) {
+ if (!Number.isFinite(n)) return '0 B';
+ if (n < 1024) return `${n} B`;
+ if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
+ return `${(n / (1024 * 1024)).toFixed(2)} MB`;
+}
+
+/**
+ * Diff two model descriptions.
+ * @param {ReturnType<import('./describe.js').describeDocument>} a the baseline
+ * @param {ReturnType<import('./describe.js').describeDocument>} b the candidate
+ */
+export function diffDescriptions(a, b) {
+ const sections = {
+ nodes: diffNodes(a, b),
+ meshes: diffMeshes(a, b),
+ materials: diffMaterials(a, b),
+ textures: diffTextures(a, b),
+ animations: diffAnimations(a, b),
+ skins: diffSkins(a, b),
+ };
+
+ const assetChanges = [];
+ field(assetChanges, 'generator', a.asset.generator, b.asset.generator, 'cosmetic');
+ field(assetChanges, 'version', a.asset.version, b.asset.version, 'cosmetic');
+ field(assetChanges, 'copyright', a.asset.copyright, b.asset.copyright, 'cosmetic');
+
+ const extensions = {
+ used: listDelta(a.extensionsUsed, b.extensionsUsed),
+ required: listDelta(a.extensionsRequired, b.extensionsRequired),
+ };
+
+ const totals = deltaBlock(a.totals, b.totals);
+ const severity = maxSeverity([
+ ...Object.values(sections).map((s) => s.severity),
+ ...assetChanges.map((c) => c.severity),
+ extensions.required.added.length ? 'major' : 'none',
+ extensions.required.removed.length ? 'minor' : 'none',
+ extensions.used.added.length || extensions.used.removed.length ? 'minor' : 'none',
+ ]);
+
+ const changed = Object.values(sections).reduce((sum, s) => sum + s.changed, 0) + assetChanges.length + extensions.used.added.length + extensions.used.removed.length + extensions.required.added.length + extensions.required.removed.length;
+
+ return {
+ version: CHANGESET_VERSION,
+ identical: changed === 0,
+ severity,
+ a: { name: a.name, sizeBytes: a.totals.sizeBytes, container: a.container, generator: a.asset.generator },
+ b: { name: b.name, sizeBytes: b.totals.sizeBytes, container: b.container, generator: b.asset.generator },
+ summary: {
+ changed,
+ added: Object.values(sections).reduce((s, x) => s + x.added.length, 0),
+ removed: Object.values(sections).reduce((s, x) => s + x.removed.length, 0),
+ modified: Object.values(sections).reduce((s, x) => s + x.modified.length, 0),
+ renamed: Object.values(sections).reduce((s, x) => s + x.renamed.length, 0),
+ moved: sections.nodes.moved.length,
+ },
+ totals,
+ sections,
+ extensions,
+ asset: assetChanges,
+ highlights: buildHighlights(sections, totals, extensions, assetChanges),
+ };
+}
diff --git a/packages/glb-diff/src/document.js b/packages/glb-diff/src/document.js
new file mode 100644
index 000000000..d95a6a0f8
--- /dev/null
+++ b/packages/glb-diff/src/document.js
@@ -0,0 +1,63 @@
+// glTF/GLB reading, shared by the library, the CLI, and the browser page.
+//
+// Deliberately mirrors the reader three.ws already runs in production
+// (src/gltf-inspect.js): same WebIO, same full extension registry, same lazy
+// meshopt decoder. Any divergence here would mean the diff sees a different
+// model than the viewer does, which is the one bug this tool cannot afford.
+
+import { WebIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+
+const GLB_MAGIC = 0x46546c67; // "glTF"
+
+export function isGLB(bytes) {
+ if (!bytes || bytes.byteLength < 4) return false;
+ const view = new DataView(bytes.buffer, bytes.byteOffset, Math.min(4, bytes.byteLength));
+ return view.getUint32(0, true) === GLB_MAGIC;
+}
+
+// EXT_meshopt_compression is registered by ALL_EXTENSIONS but cannot decode
+// without its wasm decoder supplied as a dependency, and most optimized web
+// assets ship meshopt-compressed. Without the decoder those models throw on
+// read, so the diff would refuse exactly the files people most want to compare
+// (an optimized build against its source). Loaded lazily and memoized: a caller
+// diffing two uncompressed models never pays for the wasm.
+let decoderPromise = null;
+function loadMeshoptDecoder() {
+ if (!decoderPromise) {
+ decoderPromise = import('meshoptimizer')
+ .then(async (mod) => {
+ const decoder = mod.MeshoptDecoder;
+ if (!decoder) return null;
+ if (decoder.ready) await decoder.ready;
+ return decoder;
+ })
+ .catch(() => null);
+ }
+ return decoderPromise;
+}
+
+export async function createIO() {
+ const io = new WebIO().registerExtensions(ALL_EXTENSIONS);
+ const decoder = await loadMeshoptDecoder();
+ if (decoder) io.registerDependencies({ 'meshopt.decoder': decoder });
+ return io;
+}
+
+/**
+ * Read raw bytes into a glTF-Transform Document.
+ * @param {Uint8Array} bytes binary GLB or JSON glTF
+ * @returns {Promise<import('@gltf-transform/core').Document>}
+ */
+export async function readDocument(bytes) {
+ const io = await createIO();
+ if (isGLB(bytes)) return io.readBinary(bytes);
+ const text = new TextDecoder().decode(bytes);
+ let json;
+ try {
+ json = JSON.parse(text);
+ } catch {
+ throw new Error('input is not a valid GLB or JSON glTF');
+ }
+ return io.readJSON({ json, resources: {} });
+}
diff --git a/packages/glb-diff/src/format.js b/packages/glb-diff/src/format.js
new file mode 100644
index 000000000..ad04e9e23
--- /dev/null
+++ b/packages/glb-diff/src/format.js
@@ -0,0 +1,231 @@
+// Rendering a change set for humans.
+//
+// Two targets, one shape. The terminal report is what you read while iterating;
+// the Markdown report is what a CI job posts on a pull request so the reviewer
+// sees "this export dropped 3 joints" without downloading either file. Both are
+// built from the same ordered walk of the change set so they never disagree.
+
+import { formatBytes } from './diff.js';
+import { SEVERITY_MEANING } from './severity.js';
+
+// Written as a code point rather than a literal escape so the source stays
+// copy-pasteable through editors and diff viewers that swallow control bytes.
+const ESC = String.fromCharCode(27);
+
+const ANSI = {
+ reset: `${ESC}[0m`,
+ bold: `${ESC}[1m`,
+ dim: `${ESC}[2m`,
+ red: `${ESC}[31m`,
+ green: `${ESC}[32m`,
+ yellow: `${ESC}[33m`,
+ blue: `${ESC}[34m`,
+ magenta: `${ESC}[35m`,
+ cyan: `${ESC}[36m`,
+};
+
+const SEVERITY_COLOR = {
+ none: 'dim',
+ cosmetic: 'dim',
+ minor: 'cyan',
+ major: 'yellow',
+ breaking: 'red',
+};
+
+const SECTION_ORDER = ['skins', 'animations', 'meshes', 'nodes', 'materials', 'textures'];
+
+const SECTION_LABEL = {
+ skins: 'Skeletons',
+ animations: 'Animations',
+ meshes: 'Meshes',
+ nodes: 'Nodes',
+ materials: 'Materials',
+ textures: 'Textures',
+};
+
+const TOTAL_LABEL = {
+ vertices: 'vertices',
+ triangles: 'triangles',
+ nodes: 'nodes',
+ meshes: 'meshes',
+ materials: 'materials',
+ textures: 'textures',
+ animations: 'animations',
+ skins: 'skins',
+ joints: 'joints',
+ scenes: 'scenes',
+ textureBytes: 'texture bytes',
+ sizeBytes: 'file size',
+};
+
+function paint(enabled) {
+ if (!enabled) return (text) => text;
+ return (text, ...styles) => styles.map((s) => ANSI[s] || '').join('') + text + ANSI.reset;
+}
+
+function num(n) {
+ return Number(n || 0).toLocaleString('en-US');
+}
+
+function signed(n) {
+ if (n === 0) return '0';
+ return n > 0 ? `+${num(n)}` : `-${num(Math.abs(n))}`;
+}
+
+function bytesSigned(n) {
+ return n > 0 ? `+${formatBytes(n)}` : `-${formatBytes(-n)}`;
+}
+
+function valueText(v) {
+ if (v === null || v === undefined) return 'none';
+ if (Array.isArray(v)) return v.length > 6 ? `[${v.slice(0, 6).join(', ')}, ...+${v.length - 6}]` : `[${v.join(', ')}]`;
+ if (typeof v === 'object') return JSON.stringify(v);
+ return String(v);
+}
+
+// A hash is 16 opaque characters; printing both sides in full says nothing a
+// reader can act on, so hashes collapse to a verdict and the note carries the
+// meaning.
+const OPAQUE_FIELDS = new Set(['geometry', 'pixels', 'inverseBindMatrices']);
+
+function changeLine(change) {
+ if (OPAQUE_FIELDS.has(change.field)) return `${change.field}: changed${change.note ? ` (${change.note})` : ''}`;
+ return `${change.field}: ${valueText(change.a)} -> ${valueText(change.b)}${change.note ? ` (${change.note})` : ''}`;
+}
+
+/**
+ * Render a change set as a terminal report.
+ * @param {object} changeset
+ * @param {{ color?: boolean, verbose?: boolean }} [opts]
+ */
+export function formatText(changeset, opts = {}) {
+ const c = paint(opts.color !== false);
+ const lines = [];
+ const nameA = changeset.a.name || 'A';
+ const nameB = changeset.b.name || 'B';
+
+ lines.push(`${c('glb-diff', 'bold')} ${c(nameA, 'dim')} -> ${c(nameB, 'bold')}`);
+
+ if (changeset.identical) {
+ lines.push(c(' identical: every scene, mesh, material, texture, skeleton and clip matches.', 'green'));
+ return lines.join('\n');
+ }
+
+ const sevColor = SEVERITY_COLOR[changeset.severity] || 'yellow';
+ const s = changeset.summary;
+ lines.push(
+ ` ${c(changeset.severity.toUpperCase(), sevColor, 'bold')} ${num(s.changed)} change(s): ` +
+ `${c(`+${s.added}`, 'green')} ${c(`-${s.removed}`, 'red')} ${c(`~${s.modified}`, 'yellow')} ` +
+ `${c(`renamed ${s.renamed}`, 'dim')} ${c(`moved ${s.moved}`, 'dim')}`,
+ );
+ lines.push(` ${c(SEVERITY_MEANING[changeset.severity], 'dim')}`);
+ lines.push('');
+
+ for (const h of changeset.highlights) {
+ const mark = h.severity === 'breaking' ? '!!' : h.severity === 'major' ? ' !' : ' ';
+ lines.push(` ${c(mark, SEVERITY_COLOR[h.severity] || 'dim')} ${h.text}`);
+ }
+ if (changeset.highlights.length) lines.push('');
+
+ // Totals table. Only rows that moved, unless --verbose asks for the lot: a
+ // wall of zeroes is what makes people stop reading diff output.
+ const rows = Object.entries(changeset.totals).filter(([, v]) => opts.verbose || v.delta !== 0);
+ if (rows.length) {
+ lines.push(c(' totals', 'bold'));
+ const width = Math.max(...rows.map(([k]) => (TOTAL_LABEL[k] || k).length));
+ for (const [key, v] of rows) {
+ const label = (TOTAL_LABEL[key] || key).padEnd(width);
+ const isBytes = key.endsWith('Bytes');
+ const fmt = isBytes ? formatBytes : num;
+ const delta =
+ v.delta === 0 ? c('same', 'dim') : c(isBytes ? bytesSigned(v.delta) : signed(v.delta), v.delta > 0 ? 'yellow' : 'cyan');
+ lines.push(` ${label} ${String(fmt(v.a)).padStart(12)} -> ${String(fmt(v.b)).padStart(12)} ${delta}`);
+ }
+ lines.push('');
+ }
+
+ for (const key of SECTION_ORDER) {
+ const section = changeset.sections[key];
+ if (!section || !section.changed) continue;
+ lines.push(`${c(SECTION_LABEL[key], 'bold')} ${c(`(${section.changed} changed, ${section.unchanged} unchanged)`, 'dim')}`);
+ for (const item of section.removed) lines.push(` ${c('-', 'red')} ${item.name} ${c(item.detail || '', 'dim')}`);
+ for (const item of section.added) lines.push(` ${c('+', 'green')} ${item.name} ${c(item.detail || '', 'dim')}`);
+ for (const item of section.renamed) lines.push(` ${c('R', 'magenta')} ${item.from} ${c('->', 'dim')} ${item.to}`);
+ for (const item of section.moved || []) lines.push(` ${c('M', 'blue')} ${item.from} ${c('->', 'dim')} ${item.to}`);
+ for (const item of section.modified) {
+ lines.push(` ${c('~', 'yellow')} ${item.name}${item.from && item.from !== item.name ? c(` (was ${item.from})`, 'dim') : ''}`);
+ for (const change of item.changes) lines.push(` ${c(changeLine(change), SEVERITY_COLOR[change.severity] || 'dim')}`);
+ }
+ if (section.similarityLimited) {
+ lines.push(` ${c('note: too many candidates to run rename detection here; unpaired items are listed as added/removed.', 'dim')}`);
+ }
+ lines.push('');
+ }
+
+ const ext = changeset.extensions;
+ if (ext.used.added.length || ext.used.removed.length || ext.required.added.length || ext.required.removed.length) {
+ lines.push(c('Extensions', 'bold'));
+ for (const name of ext.required.added) lines.push(` ${c('+', 'green')} ${name} ${c('(required)', 'yellow')}`);
+ for (const name of ext.required.removed) lines.push(` ${c('-', 'red')} ${name} ${c('(was required)', 'dim')}`);
+ for (const name of ext.used.added.filter((n) => !ext.required.added.includes(n))) lines.push(` ${c('+', 'green')} ${name}`);
+ for (const name of ext.used.removed.filter((n) => !ext.required.removed.includes(n))) lines.push(` ${c('-', 'red')} ${name}`);
+ lines.push('');
+ }
+
+ if (changeset.asset.length) {
+ lines.push(c('Asset metadata', 'bold'));
+ for (const change of changeset.asset) lines.push(` ${c('~', 'yellow')} ${changeLine(change)}`);
+ lines.push('');
+ }
+
+ return lines.join('\n').replace(/\n+$/, '\n');
+}
+
+/**
+ * Render a change set as Markdown, sized for a pull-request comment.
+ * @param {object} changeset
+ */
+export function formatMarkdown(changeset) {
+ const nameA = changeset.a.name || 'A';
+ const nameB = changeset.b.name || 'B';
+ const out = [`### 3D diff: \`${nameA}\` to \`${nameB}\``, ''];
+
+ if (changeset.identical) {
+ out.push('The two models are structurally identical.');
+ return out.join('\n');
+ }
+
+ out.push(`**${changeset.severity}**: ${SEVERITY_MEANING[changeset.severity]}`, '');
+ for (const h of changeset.highlights) {
+ out.push(`- ${h.severity === 'breaking' ? `**${h.text}**` : h.text}`);
+ }
+ out.push('');
+
+ const rows = Object.entries(changeset.totals).filter(([, v]) => v.delta !== 0);
+ if (rows.length) {
+ out.push('| metric | before | after | delta |', '| --- | ---: | ---: | ---: |');
+ for (const [key, v] of rows) {
+ const isBytes = key.endsWith('Bytes');
+ const fmt = isBytes ? formatBytes : num;
+ out.push(`| ${TOTAL_LABEL[key] || key} | ${fmt(v.a)} | ${fmt(v.b)} | ${isBytes ? bytesSigned(v.delta) : signed(v.delta)} |`);
+ }
+ out.push('');
+ }
+
+ for (const key of SECTION_ORDER) {
+ const section = changeset.sections[key];
+ if (!section || !section.changed) continue;
+ out.push(`<details><summary>${SECTION_LABEL[key]} (${section.changed} changed)</summary>`, '');
+ for (const item of section.removed) out.push(`- \`-\` **${item.name}** ${item.detail || ''}`);
+ for (const item of section.added) out.push(`- \`+\` **${item.name}** ${item.detail || ''}`);
+ for (const item of section.renamed) out.push(`- \`R\` \`${item.from}\` to \`${item.to}\``);
+ for (const item of section.moved || []) out.push(`- \`M\` \`${item.from}\` to \`${item.to}\``);
+ for (const item of section.modified) {
+ out.push(`- \`~\` **${item.name}**`);
+ for (const change of item.changes) out.push(` - ${changeLine(change)}`);
+ }
+ out.push('', '</details>', '');
+ }
+
+ return out.join('\n');
+}
diff --git a/packages/glb-diff/src/hash.js b/packages/glb-diff/src/hash.js
new file mode 100644
index 000000000..5d952163f
--- /dev/null
+++ b/packages/glb-diff/src/hash.js
@@ -0,0 +1,114 @@
+// Deterministic, allocation-free hashing for model content.
+//
+// Every "did this actually change?" question in the diff reduces to comparing
+// two hashes, so the hash has to be three things at once: stable across
+// re-exports, cheap enough to run over every vertex of a real avatar, and
+// available in both Node and the browser (Web Crypto's digest is async and
+// SubtleCrypto is https-only, which rules it out for a page that must work off
+// a file:// scratch build).
+//
+// The construction is FNV-1a run in two independent 32-bit lanes with different
+// offset bases, concatenated into a 128-bit-wide-looking 16-char hex string. Two
+// lanes rather than one because a single 32-bit space collides at roughly 1 in
+// 65k over 300 objects (birthday bound), which is far too often for a tool whose
+// whole claim is "these two meshes are the same mesh".
+
+const LANE_A_OFFSET = 0x811c9dc5;
+const LANE_B_OFFSET = 0x01000193;
+const PRIME = 0x01000193;
+
+// Quantization step for float comparison. A re-export through Blender, gltfpack,
+// or a Draco round trip perturbs positions in the 1e-6 range; genuine edits move
+// vertices by orders of magnitude more. Rounding to 1e-4 of a unit (0.1mm at
+// real-world scale) makes "unchanged geometry" survive the pipeline without
+// letting a real edit hide.
+export const FLOAT_QUANTUM = 1e4;
+
+function mix(h, value) {
+ return Math.imul(h ^ (value | 0), PRIME) >>> 0;
+}
+
+function toHex(a, b) {
+ return (a >>> 0).toString(16).padStart(8, '0') + (b >>> 0).toString(16).padStart(8, '0');
+}
+
+/** Hash a UTF-16 string. Used for names, enums, and pre-serialized structures. */
+export function hashString(str) {
+ let a = LANE_A_OFFSET;
+ let b = LANE_B_OFFSET;
+ const s = String(str);
+ for (let i = 0; i < s.length; i++) {
+ const c = s.charCodeAt(i);
+ a = mix(a, c);
+ b = mix(b, c + i);
+ }
+ return toHex(a, b);
+}
+
+/**
+ * Hash a numeric array with float tolerance. Integer arrays (indices, joints)
+ * pass through unquantized because rounding them would be lossy in the wrong
+ * direction: index 3 and index 4 are not "nearly the same".
+ * @param {ArrayLike<number>|null|undefined} arr
+ * @param {{ quantize?: boolean, seed?: string }} [opts]
+ */
+export function hashNumbers(arr, opts = {}) {
+ const quantize = opts.quantize !== false;
+ let a = LANE_A_OFFSET;
+ let b = LANE_B_OFFSET;
+ if (opts.seed) {
+ const seed = String(opts.seed);
+ for (let i = 0; i < seed.length; i++) {
+ a = mix(a, seed.charCodeAt(i));
+ b = mix(b, seed.charCodeAt(i) + i);
+ }
+ }
+ if (!arr) return toHex(a, b);
+ const n = arr.length;
+ a = mix(a, n);
+ b = mix(b, n);
+ for (let i = 0; i < n; i++) {
+ const v = arr[i];
+ const q = quantize ? Math.round(v * FLOAT_QUANTUM) : v;
+ a = mix(a, q);
+ b = mix(b, q / 4294967296);
+ }
+ return toHex(a, b);
+}
+
+/** Hash raw bytes. Used for encoded texture payloads, where the bytes are the truth. */
+export function hashBytes(bytes) {
+ let a = LANE_A_OFFSET;
+ let b = LANE_B_OFFSET;
+ if (!bytes) return toHex(a, b);
+ const n = bytes.length;
+ a = mix(a, n);
+ b = mix(b, n);
+ for (let i = 0; i < n; i++) {
+ a = mix(a, bytes[i]);
+ b = mix(b, bytes[i] + (i & 0xff));
+ }
+ return toHex(a, b);
+}
+
+/**
+ * Hash an arbitrary JSON-safe value with key order normalized, so two objects
+ * that differ only in property order hash the same. Numbers go through the same
+ * quantization as vertex data, which is what lets a baseColorFactor that came
+ * back as 0.7999999523162842 match the 0.8 it was authored as.
+ */
+export function hashValue(value) {
+ return hashString(canonicalize(value));
+}
+
+export function canonicalize(value) {
+ if (value === null || value === undefined) return 'null';
+ if (typeof value === 'number') {
+ if (!Number.isFinite(value)) return String(value);
+ return String(Math.round(value * FLOAT_QUANTUM) / FLOAT_QUANTUM);
+ }
+ if (typeof value !== 'object') return JSON.stringify(value);
+ if (Array.isArray(value)) return `[${value.map(canonicalize).join(',')}]`;
+ const keys = Object.keys(value).sort();
+ return `{${keys.map((k) => `${JSON.stringify(k)}:${canonicalize(value[k])}`).join(',')}}`;
+}
diff --git a/packages/glb-diff/src/index.d.ts b/packages/glb-diff/src/index.d.ts
new file mode 100644
index 000000000..697a6648e
--- /dev/null
+++ b/packages/glb-diff/src/index.d.ts
@@ -0,0 +1,106 @@
+export type Severity = 'none' | 'cosmetic' | 'minor' | 'major' | 'breaking';
+
+export interface FieldChange {
+ field: string;
+ a: unknown;
+ b: unknown;
+ severity: Severity;
+ note?: string;
+}
+
+export interface SectionItem {
+ name: string;
+ severity: Severity;
+ detail?: string;
+}
+
+export interface ModifiedItem {
+ name: string;
+ from?: string;
+ changes: FieldChange[];
+ severity: Severity;
+}
+
+export interface RenameItem {
+ from: string;
+ to: string;
+ name: string;
+}
+
+export interface DiffSection {
+ added: SectionItem[];
+ removed: SectionItem[];
+ renamed: RenameItem[];
+ moved?: RenameItem[];
+ modified: ModifiedItem[];
+ unchanged: number;
+ changed: number;
+ severity: Severity;
+ similarityLimited: boolean;
+}
+
+export interface TotalDelta {
+ a: number;
+ b: number;
+ delta: number;
+ pct: number | null;
+}
+
+export interface ChangeSet {
+ version: number;
+ identical: boolean;
+ severity: Severity;
+ a: { name: string | null; sizeBytes: number; container: string | null; generator: string | null };
+ b: { name: string | null; sizeBytes: number; container: string | null; generator: string | null };
+ summary: { changed: number; added: number; removed: number; modified: number; renamed: number; moved: number };
+ totals: Record<string, TotalDelta>;
+ sections: {
+ nodes: DiffSection;
+ meshes: DiffSection;
+ materials: DiffSection;
+ textures: DiffSection;
+ animations: DiffSection;
+ skins: DiffSection;
+ };
+ extensions: { used: { added: string[]; removed: string[] }; required: { added: string[]; removed: string[] } };
+ asset: FieldChange[];
+ highlights: { severity: Severity; text: string }[];
+}
+
+export interface ModelDescription {
+ version: number;
+ name: string | null;
+ container: string | null;
+ asset: { generator: string | null; version: string | null; copyright: string | null };
+ extensionsUsed: string[];
+ extensionsRequired: string[];
+ totals: Record<string, number>;
+ nodes: Record<string, unknown>[];
+ meshes: Record<string, unknown>[];
+ materials: Record<string, unknown>[];
+ textures: Record<string, unknown>[];
+ animations: Record<string, unknown>[];
+ skins: Record<string, unknown>[];
+}
+
+export declare function diffModels(
+ bytesA: Uint8Array,
+ bytesB: Uint8Array,
+ opts?: { nameA?: string; nameB?: string },
+): Promise<ChangeSet>;
+
+export declare function describeModel(bytes: Uint8Array, meta?: { name?: string }): Promise<ModelDescription>;
+export declare function describeDocument(document: unknown, meta?: Record<string, unknown>): ModelDescription;
+export declare function diffDescriptions(a: ModelDescription, b: ModelDescription): ChangeSet;
+export declare function formatText(changeset: ChangeSet, opts?: { color?: boolean; verbose?: boolean }): string;
+export declare function formatMarkdown(changeset: ChangeSet): string;
+export declare function readDocument(bytes: Uint8Array): Promise<unknown>;
+export declare function isGLB(bytes: Uint8Array): boolean;
+export declare function atLeast(severity: Severity, threshold: Severity): boolean;
+export declare function maxSeverity(values: (Severity | null | undefined)[]): Severity;
+export declare function severityRank(severity: Severity): number;
+export declare function formatBytes(n: number): string;
+export declare const SEVERITIES: Severity[];
+export declare const SEVERITY_MEANING: Record<Severity, string>;
+export declare const CHANGESET_VERSION: number;
+export declare const DESCRIPTION_VERSION: number;
diff --git a/packages/glb-diff/src/index.js b/packages/glb-diff/src/index.js
new file mode 100644
index 000000000..bf23ee126
--- /dev/null
+++ b/packages/glb-diff/src/index.js
@@ -0,0 +1,53 @@
+// @three-ws/glb-diff
+//
+// Structural diff for glTF/GLB. Answers the question a byte comparison cannot:
+// not "are these files different" (a re-export always is) but "what changed,
+// and will it break anything downstream".
+//
+// The pipeline is three steps and every one of them is a public export, because
+// the interesting uses are not always the whole thing end to end:
+//
+// describeModel(bytes) bytes -> a plain, JSON-safe description
+// diffDescriptions(a, b) two descriptions -> a change set
+// formatText(changeset) a change set -> something you can read
+//
+// Splitting them means a browser can describe a file once, keep the (small)
+// description, and diff it against many candidates without re-parsing; and a
+// build can store descriptions as artifacts and diff yesterday against today
+// without keeping the models themselves.
+
+export { describeDocument, describeModel, DESCRIPTION_VERSION } from './describe.js';
+export { diffDescriptions, formatBytes, CHANGESET_VERSION } from './diff.js';
+export { formatText, formatMarkdown } from './format.js';
+export { readDocument, isGLB } from './document.js';
+export { SEVERITIES, SEVERITY_MEANING, atLeast, maxSeverity, severityRank } from './severity.js';
+export { matchEntries, jaccard, ratio } from './match.js';
+
+import { describeModel } from './describe.js';
+import { diffDescriptions } from './diff.js';
+
+/**
+ * Diff two models given their raw bytes.
+ *
+ * @param {Uint8Array} bytesA the baseline
+ * @param {Uint8Array} bytesB the candidate
+ * @param {{ nameA?: string, nameB?: string }} [opts] labels carried into the report
+ * @returns {Promise<object>} the change set
+ *
+ * @example
+ * import { readFile } from 'node:fs/promises';
+ * import { diffModels, formatText } from '@three-ws/glb-diff';
+ *
+ * const before = await readFile('avatar.v1.glb');
+ * const after = await readFile('avatar.v2.glb');
+ * const changes = await diffModels(before, after, { nameA: 'v1', nameB: 'v2' });
+ * console.log(formatText(changes));
+ * if (changes.severity === 'breaking') process.exit(1);
+ */
+export async function diffModels(bytesA, bytesB, opts = {}) {
+ const [a, b] = await Promise.all([
+ describeModel(bytesA, { name: opts.nameA || 'A' }),
+ describeModel(bytesB, { name: opts.nameB || 'B' }),
+ ]);
+ return diffDescriptions(a, b);
+}
diff --git a/packages/glb-diff/src/match.js b/packages/glb-diff/src/match.js
new file mode 100644
index 000000000..6498f4fcd
--- /dev/null
+++ b/packages/glb-diff/src/match.js
@@ -0,0 +1,118 @@
+// Pairing entries across two models.
+//
+// A diff is only as good as its matching. Compare by name alone and every
+// exporter that renumbers "Mesh.001" reports the whole file as rewritten;
+// compare by content alone and a rename looks like a deletion plus an unrelated
+// addition. So this runs the same three-tier strategy git uses for file renames,
+// applied to glTF objects:
+//
+// 1. by key the names agree, so the objects correspond
+// 2. by fingerprint the names disagree but the content is byte-identical, so
+// it is a rename
+// 3. by similarity neither agrees, but one candidate is close enough that
+// calling it "the same object, edited and renamed" is more
+// honest than reporting an add and a remove
+//
+// Anything still unpaired after all three really is an addition or a removal.
+
+/** Two counts as a 0..1 closeness ratio. Equal counts score 1, a zero against a nonzero scores 0. */
+export function ratio(a, b) {
+ const x = Math.abs(Number(a) || 0);
+ const y = Math.abs(Number(b) || 0);
+ if (x === 0 && y === 0) return 1;
+ const hi = Math.max(x, y);
+ if (hi === 0) return 1;
+ return Math.min(x, y) / hi;
+}
+
+/** Overlap of two lists as a 0..1 Jaccard index. Empty against empty scores 1. */
+export function jaccard(a, b) {
+ const setA = new Set(a || []);
+ const setB = new Set(b || []);
+ if (setA.size === 0 && setB.size === 0) return 1;
+ let shared = 0;
+ for (const v of setA) if (setB.has(v)) shared++;
+ return shared / (setA.size + setB.size - shared);
+}
+
+// Above this many candidate pairs the similarity pass is skipped: it is O(n*m)
+// and a 40k-comparison ceiling already covers a 200-object model against another
+// 200-object model, which is far past any real avatar. When it trips, the result
+// says so rather than quietly downgrading renames into add/remove noise.
+const MAX_SIMILARITY_PAIRS = 40_000;
+
+/**
+ * @template T
+ * @param {T[]} listA
+ * @param {T[]} listB
+ * @param {{ similarity?: (a: T, b: T) => number, threshold?: number }} [opts]
+ * @returns {{ pairs: {a: T, b: T, via: 'key'|'fingerprint'|'similarity', score: number}[], added: T[], removed: T[], similarityLimited: boolean }}
+ */
+export function matchEntries(listA, listB, opts = {}) {
+ const threshold = opts.threshold ?? 0.6;
+ const pairs = [];
+ const usedA = new Set();
+ const usedB = new Set();
+
+ const pairBy = (field, via) => {
+ const bucketB = new Map();
+ listB.forEach((entry, i) => {
+ if (usedB.has(i)) return;
+ const value = entry[field];
+ if (value === null || value === undefined) return;
+ if (!bucketB.has(value)) bucketB.set(value, []);
+ bucketB.get(value).push(i);
+ });
+ listA.forEach((entry, i) => {
+ if (usedA.has(i)) return;
+ const value = entry[field];
+ if (value === null || value === undefined) return;
+ const candidates = bucketB.get(value);
+ if (!candidates || candidates.length === 0) return;
+ // Duplicates on either side are paired in document order, which is the
+ // only stable choice when the file itself offers no way to tell two
+ // identically named siblings apart.
+ const j = candidates.shift();
+ usedA.add(i);
+ usedB.add(j);
+ pairs.push({ a: entry, b: listB[j], via, score: 1 });
+ });
+ };
+
+ pairBy('key', 'key');
+ pairBy('fingerprint', 'fingerprint');
+
+ const restA = listA.map((e, i) => ({ e, i })).filter(({ i }) => !usedA.has(i));
+ const restB = listB.map((e, i) => ({ e, i })).filter(({ i }) => !usedB.has(i));
+
+ let similarityLimited = false;
+ if (opts.similarity && restA.length && restB.length) {
+ if (restA.length * restB.length > MAX_SIMILARITY_PAIRS) {
+ similarityLimited = true;
+ } else {
+ const scored = [];
+ for (const a of restA) {
+ for (const b of restB) {
+ const score = opts.similarity(a.e, b.e);
+ if (score >= threshold) scored.push({ a, b, score });
+ }
+ }
+ // Best match first, and each entry may only be claimed once, so a strong
+ // pairing is never displaced by a weaker one that happened to come first.
+ scored.sort((x, y) => y.score - x.score);
+ for (const { a, b, score } of scored) {
+ if (usedA.has(a.i) || usedB.has(b.i)) continue;
+ usedA.add(a.i);
+ usedB.add(b.i);
+ pairs.push({ a: a.e, b: b.e, via: 'similarity', score });
+ }
+ }
+ }
+
+ return {
+ pairs,
+ removed: listA.filter((_, i) => !usedA.has(i)),
+ added: listB.filter((_, i) => !usedB.has(i)),
+ similarityLimited,
+ };
+}
diff --git a/packages/glb-diff/src/severity.js b/packages/glb-diff/src/severity.js
new file mode 100644
index 000000000..f412ace96
--- /dev/null
+++ b/packages/glb-diff/src/severity.js
@@ -0,0 +1,38 @@
+// How bad is this change?
+//
+// The ladder is defined by what a downstream consumer notices, not by how large
+// the byte delta is. A 40 MB texture swap is `minor` because everything still
+// loads and plays; deleting one joint is `breaking` because every clip that
+// addressed that joint by name silently stops moving, which is the single most
+// expensive failure in this pipeline and the reason the tool exists.
+
+export const SEVERITIES = ['none', 'cosmetic', 'minor', 'major', 'breaking'];
+
+const RANK = new Map(SEVERITIES.map((s, i) => [s, i]));
+
+export function severityRank(severity) {
+ return RANK.get(severity) ?? 0;
+}
+
+/** The worst severity in a list. Returns 'none' for an empty list. */
+export function maxSeverity(values) {
+ let worst = 'none';
+ for (const value of values) {
+ if (!value) continue;
+ if (severityRank(value) > severityRank(worst)) worst = value;
+ }
+ return worst;
+}
+
+/** True when `severity` is at least as bad as `threshold`. Drives the CLI exit code. */
+export function atLeast(severity, threshold) {
+ return severityRank(severity) >= severityRank(threshold);
+}
+
+export const SEVERITY_MEANING = {
+ none: 'The two models are structurally identical.',
+ cosmetic: 'Only metadata changed. Nothing a renderer or a clip can observe.',
+ minor: 'Appearance changed. The model still loads, animates, and keeps its shape.',
+ major: 'Geometry or hierarchy changed. Anything positioned against this model should be re-checked.',
+ breaking: 'Something a consumer references by name is gone. Clips, attachments, or materials bound to it will fail.',
+};
diff --git a/packages/glb-diff/tests/glb-diff.test.js b/packages/glb-diff/tests/glb-diff.test.js
new file mode 100644
index 000000000..901179853
--- /dev/null
+++ b/packages/glb-diff/tests/glb-diff.test.js
@@ -0,0 +1,294 @@
+// Tests for @three-ws/glb-diff.
+//
+// Two layers, deliberately. Most cases build glTF Documents in memory so the
+// input is exact: a test that says "moving one vertex is a major change" moves
+// exactly one vertex. The last block runs the whole pipeline over real rigged
+// avatars shipped in this repo, because an engine that only ever sees synthetic
+// four-triangle meshes is an engine nobody has actually tested.
+
+import { describe, expect, it } from 'vitest';
+import { Document } from '@gltf-transform/core';
+import { readFile } from 'node:fs/promises';
+import { fileURLToPath } from 'node:url';
+import path from 'node:path';
+
+import { describeDocument, describeModel } from '../src/describe.js';
+import { diffDescriptions } from '../src/diff.js';
+import { diffModels } from '../src/index.js';
+import { formatMarkdown, formatText } from '../src/format.js';
+import { atLeast, maxSeverity, SEVERITIES } from '../src/severity.js';
+import { jaccard, matchEntries, ratio } from '../src/match.js';
+import { canonicalize, hashNumbers, hashString } from '../src/hash.js';
+
+const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
+const asset = (name) => path.join(REPO_ROOT, 'animation-sources', name);
+
+// A minimal but complete rigged model: one triangle skinned to two joints,
+// driven by one clip. Small enough to reason about, complete enough that every
+// section of the diff has something to compare.
+function buildModel(overrides = {}) {
+ const {
+ meshName = 'Body',
+ nodeName = 'Root',
+ positions = [0, 0, 0, 1, 0, 0, 0, 1, 0],
+ materialName = 'Skin',
+ baseColor = [1, 1, 1, 1],
+ joints = ['Hips', 'Spine'],
+ clipName = 'idle',
+ clipTimes = [0, 1],
+ reparent = false,
+ } = overrides;
+
+ const doc = new Document();
+ const buffer = doc.createBuffer();
+
+ const position = doc
+ .createAccessor()
+ .setType('VEC3')
+ .setArray(new Float32Array(positions))
+ .setBuffer(buffer);
+
+ const material = doc.createMaterial(materialName).setBaseColorFactor(baseColor);
+ const prim = doc.createPrimitive().setAttribute('POSITION', position).setMaterial(material);
+ const mesh = doc.createMesh(meshName).addPrimitive(prim);
+
+ const root = doc.createNode(nodeName).setMesh(mesh);
+ const jointNodes = joints.map((name) => doc.createNode(name));
+ const skin = doc.createSkin('Armature');
+ for (const joint of jointNodes) skin.addJoint(joint);
+ if (jointNodes[0]) skin.setSkeleton(jointNodes[0]);
+ root.setSkin(skin);
+
+ const input = doc
+ .createAccessor()
+ .setType('SCALAR')
+ .setArray(new Float32Array(clipTimes))
+ .setBuffer(buffer);
+ const output = doc
+ .createAccessor()
+ .setType('VEC3')
+ .setArray(new Float32Array(clipTimes.flatMap(() => [0, 0, 0])))
+ .setBuffer(buffer);
+ const sampler = doc.createAnimationSampler().setInput(input).setOutput(output).setInterpolation('LINEAR');
+ const channel = doc
+ .createAnimationChannel()
+ .setTargetNode(jointNodes[0] || root)
+ .setTargetPath('translation')
+ .setSampler(sampler);
+ doc.createAnimation(clipName).addSampler(sampler).addChannel(channel);
+
+ const scene = doc.createScene('Scene');
+ if (reparent) {
+ // Same nodes, different hierarchy: the joints hang off the mesh node
+ // instead of sitting beside it at the scene root.
+ for (const joint of jointNodes) root.addChild(joint);
+ scene.addChild(root);
+ } else {
+ scene.addChild(root);
+ for (const joint of jointNodes) scene.addChild(joint);
+ }
+ return doc;
+}
+
+const describeBuilt = (overrides, name) => describeDocument(buildModel(overrides), { name, sizeBytes: 1024, container: 'glb' });
+
+describe('hash', () => {
+ it('is stable and order independent for objects', () => {
+ expect(canonicalize({ b: 2, a: 1 })).toBe(canonicalize({ a: 1, b: 2 }));
+ expect(hashString('abc')).toBe(hashString('abc'));
+ expect(hashString('abc')).not.toBe(hashString('abd'));
+ });
+
+ it('absorbs float noise from a re-export but not a real edit', () => {
+ expect(hashNumbers([1, 2, 3.000001])).toBe(hashNumbers([1, 2, 3]));
+ expect(hashNumbers([1, 2, 3.01])).not.toBe(hashNumbers([1, 2, 3]));
+ });
+
+ it('does not treat a gained value as a reordered one', () => {
+ expect(hashNumbers([1, 2, 3])).not.toBe(hashNumbers([3, 2, 1]));
+ expect(hashNumbers([1, 2, 3])).not.toBe(hashNumbers([1, 2, 3, 4]));
+ });
+});
+
+describe('severity ladder', () => {
+ it('orders from none to breaking', () => {
+ expect(SEVERITIES).toEqual(['none', 'cosmetic', 'minor', 'major', 'breaking']);
+ expect(maxSeverity(['minor', 'breaking', 'cosmetic'])).toBe('breaking');
+ expect(maxSeverity([])).toBe('none');
+ expect(atLeast('major', 'minor')).toBe(true);
+ expect(atLeast('minor', 'major')).toBe(false);
+ });
+});
+
+describe('matcher', () => {
+ it('pairs on key first, then fingerprint, then similarity', () => {
+ const a = [
+ { key: 'same', fingerprint: 'f1', size: 10 },
+ { key: 'oldname', fingerprint: 'f2', size: 20 },
+ { key: 'edited', fingerprint: 'f3', size: 30 },
+ ];
+ const b = [
+ { key: 'same', fingerprint: 'f9', size: 10 },
+ { key: 'newname', fingerprint: 'f2', size: 20 },
+ { key: 'edited-and-renamed', fingerprint: 'f8', size: 31 },
+ ];
+ const result = matchEntries(a, b, { similarity: (x, y) => ratio(x.size, y.size) });
+ const via = Object.fromEntries(result.pairs.map((p) => [p.a.key, p.via]));
+ expect(via.same).toBe('key');
+ expect(via.oldname).toBe('fingerprint');
+ expect(via.edited).toBe('similarity');
+ expect(result.added).toHaveLength(0);
+ expect(result.removed).toHaveLength(0);
+ });
+
+ it('reports genuinely new and gone entries', () => {
+ const result = matchEntries([{ key: 'gone', fingerprint: 'x' }], [{ key: 'fresh', fingerprint: 'y' }], {
+ similarity: () => 0,
+ });
+ expect(result.removed.map((r) => r.key)).toEqual(['gone']);
+ expect(result.added.map((r) => r.key)).toEqual(['fresh']);
+ });
+
+ it('scores overlap and closeness', () => {
+ expect(jaccard(['a', 'b'], ['a', 'b'])).toBe(1);
+ expect(jaccard([], [])).toBe(1);
+ expect(jaccard(['a'], ['b'])).toBe(0);
+ expect(ratio(10, 10)).toBe(1);
+ expect(ratio(0, 0)).toBe(1);
+ expect(ratio(5, 10)).toBe(0.5);
+ });
+});
+
+describe('diff', () => {
+ it('calls an unchanged model identical', () => {
+ const changes = diffDescriptions(describeBuilt({}, 'a'), describeBuilt({}, 'b'));
+ expect(changes.identical).toBe(true);
+ expect(changes.severity).toBe('none');
+ expect(changes.summary.changed).toBe(0);
+ });
+
+ it('detects a rename instead of an add plus a remove', () => {
+ const changes = diffDescriptions(describeBuilt({}, 'a'), describeBuilt({ meshName: 'Torso' }, 'b'));
+ expect(changes.sections.meshes.renamed).toEqual([{ from: 'Body', to: 'Torso', name: 'Torso' }]);
+ expect(changes.sections.meshes.added).toHaveLength(0);
+ expect(changes.sections.meshes.removed).toHaveLength(0);
+ });
+
+ it('calls a moved vertex a major change and names the mesh', () => {
+ const changes = diffDescriptions(
+ describeBuilt({}, 'a'),
+ describeBuilt({ positions: [0, 0, 0, 1, 0, 0, 0, 2, 0] }, 'b'),
+ );
+ expect(changes.severity).toBe('major');
+ const mesh = changes.sections.meshes.modified.find((m) => m.name === 'Body');
+ expect(mesh.changes.some((c) => c.field === 'geometry')).toBe(true);
+ expect(changes.highlights.some((h) => h.text.includes('"Body"'))).toBe(true);
+ });
+
+ it('calls a removed joint breaking and names it', () => {
+ const changes = diffDescriptions(describeBuilt({}, 'a'), describeBuilt({ joints: ['Hips'] }, 'b'));
+ expect(changes.severity).toBe('breaking');
+ const skin = changes.sections.skins.modified.find((s) => s.name === 'Armature');
+ const joints = skin.changes.find((c) => c.field === 'joints' && c.a.length);
+ expect(joints.a).toEqual(['Spine']);
+ expect(changes.highlights[0].severity).toBe('breaking');
+ expect(changes.highlights[0].text).toContain('Spine');
+ });
+
+ it('calls a recoloured material a minor change', () => {
+ const changes = diffDescriptions(describeBuilt({}, 'a'), describeBuilt({ baseColor: [1, 0, 0, 1] }, 'b'));
+ expect(changes.severity).toBe('minor');
+ const material = changes.sections.materials.modified.find((m) => m.name === 'Skin');
+ expect(material.changes.map((c) => c.field)).toContain('baseColorFactor');
+ });
+
+ it('reports a reparented node as moved, not as added and removed', () => {
+ const changes = diffDescriptions(describeBuilt({}, 'a'), describeBuilt({ reparent: true }, 'b'));
+ expect(changes.sections.nodes.moved.map((m) => m.name).sort()).toEqual(['Hips', 'Spine']);
+ expect(changes.sections.nodes.added).toHaveLength(0);
+ expect(changes.sections.nodes.removed).toHaveLength(0);
+ });
+
+ it('reports a retimed clip', () => {
+ const changes = diffDescriptions(describeBuilt({}, 'a'), describeBuilt({ clipTimes: [0, 2] }, 'b'));
+ const clip = changes.sections.animations.modified.find((c) => c.name === 'idle');
+ expect(clip.changes.find((c) => c.field === 'duration')).toMatchObject({ a: 1, b: 2 });
+ });
+
+ it('carries totals with deltas and percentages', () => {
+ const changes = diffDescriptions(
+ describeBuilt({}, 'a'),
+ describeBuilt({ joints: ['Hips', 'Spine', 'Chest'] }, 'b'),
+ );
+ expect(changes.totals.joints).toMatchObject({ a: 2, b: 3, delta: 1, pct: 50 });
+ });
+
+ it('is deterministic', () => {
+ const once = JSON.stringify(diffDescriptions(describeBuilt({}, 'a'), describeBuilt({ meshName: 'Torso' }, 'b')));
+ const twice = JSON.stringify(diffDescriptions(describeBuilt({}, 'a'), describeBuilt({ meshName: 'Torso' }, 'b')));
+ expect(once).toBe(twice);
+ });
+});
+
+describe('formatting', () => {
+ const changes = diffDescriptions(describeBuilt({}, 'before.glb'), describeBuilt({ joints: ['Hips'] }, 'after.glb'));
+
+ it('writes a plain-text report with no escape codes when colour is off', () => {
+ const text = formatText(changes, { color: false });
+ expect(text).toContain('BREAKING');
+ expect(text).toContain('Skeletons');
+ expect(text).not.toContain(String.fromCharCode(27));
+ });
+
+ it('writes Markdown a pull request can render', () => {
+ const md = formatMarkdown(changes);
+ expect(md.startsWith('### 3D diff:')).toBe(true);
+ expect(md).toContain('<details><summary>Skeletons');
+ });
+
+ it('says so plainly when nothing changed', () => {
+ const same = diffDescriptions(describeBuilt({}, 'a'), describeBuilt({}, 'b'));
+ expect(formatText(same, { color: false })).toContain('identical');
+ expect(formatMarkdown(same)).toContain('structurally identical');
+ });
+});
+
+describe('real avatars', () => {
+ it('describes a rigged Mixamo avatar', async () => {
+ const bytes = new Uint8Array(await readFile(asset('xbot-idle.glb')));
+ const model = await describeModel(bytes, { name: 'xbot-idle.glb' });
+ expect(model.totals.skins).toBe(1);
+ expect(model.totals.joints).toBeGreaterThan(50);
+ expect(model.totals.triangles).toBeGreaterThan(1000);
+ expect(model.nodes.some((n) => n.path.includes('mixamorig:Hips'))).toBe(true);
+ });
+
+ it('finds only the clip change between two exports of the same rig', async () => {
+ const [a, b] = await Promise.all([
+ readFile(asset('xbot-idle.glb')),
+ readFile(asset('xbot-walk.glb')),
+ ]);
+ const changes = await diffModels(new Uint8Array(a), new Uint8Array(b), {
+ nameA: 'xbot-idle.glb',
+ nameB: 'xbot-walk.glb',
+ });
+ expect(changes.sections.meshes.changed).toBe(0);
+ expect(changes.sections.skins.changed).toBe(0);
+ expect(changes.sections.nodes.changed).toBe(0);
+ expect(changes.sections.animations.renamed).toEqual([{ from: 'idle', to: 'walk', name: 'walk' }]);
+ });
+
+ it('calls two different characters breaking', async () => {
+ const [a, b] = await Promise.all([
+ readFile(asset('robot-walking.glb')),
+ readFile(asset('xbot-walk.glb')),
+ ]);
+ const changes = await diffModels(new Uint8Array(a), new Uint8Array(b), {
+ nameA: 'robot-walking.glb',
+ nameB: 'xbot-walk.glb',
+ });
+ expect(changes.severity).toBe('breaking');
+ expect(changes.sections.skins.removed.length).toBeGreaterThan(0);
+ expect(changes.totals.triangles.delta).toBeGreaterThan(0);
+ });
+});