3D engine that AI agents drive
Load quantized morph targets and skins with a zero-scale joint (#496)
Nguyen Xuan An6152db9cad02
diff --git a/changes/496-quantized-joints.md b/changes/496-quantized-joints.mdnew file mode 100644index 00000000..ed23a916--- /dev/null+++ b/changes/496-quantized-joints.md@@ -0,0 +1 @@+- `loadGltf` and `parseGltf` load morph targets with normalized int8 or int16 POSITION deltas (KHR_mesh_quantization) and keep a skin whose joint has zero scale, collapsing its vertices to a point with a warning (issue #496).diff --git a/changes/496-quantized-joints.size.md b/changes/496-quantized-joints.size.mdnew file mode 100644index 00000000..fd1bab7e--- /dev/null+++ b/changes/496-quantized-joints.size.md@@ -0,0 +1,3 @@+- scene:gltf-box: quantized int8 and int16 morph targets and zero-scale skin joints load instead of refusing the file, 129 bytes; 2 of 30 sampled Objaverse models were still refused for these.+- scene:gltf-box+lazy: the same loader change, 129 bytes.+- goal:gltf-box: the 215 bytes over the goal buy loading the last two refused Objaverse sample models.diff --git a/src/gltf.js b/src/gltf.jsindex f5709d6b..2ed7e6a9 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -361,7 +361,7 @@ function validateDocument(document, limits, allowedExtensions) {const accessor = document.accessors?.[accessorIndex];// A morph NORMAL without a base NORMAL is dropped at conversion with a warning, so it needs no base attribute here.if (primitive.attributes?.[semantic] === undefined && semantic !== 'NORMAL') throw new Error('Morph target channels require corresponding base attributes.');- if (!Number.isInteger(accessorIndex) || !accessor || accessor.type !== 'VEC3' || accessor.componentType !== 5126 || accessor.normalized || accessor.count !== position.count) throw new Error('Morph target channels require matching float VEC3 accessors.');+ if (!Number.isInteger(accessorIndex) || !accessor || accessor.type !== 'VEC3' || ![5120, 5122, 5126].includes(accessor.componentType) || (accessor.normalized && accessor.componentType === 5126) || accessor.count !== position.count) throw new Error('Morph target channels require matching VEC3 (float, or int8 or int16 with KHR_mesh_quantization) accessors.');if (semantic === 'POSITION' && (!Array.isArray(accessor.min) || !Array.isArray(accessor.max) || accessor.min.length !== 3 || accessor.max.length !== 3|| accessor.min.some((value, axis) => typeof value !== 'number' || !Number.isFinite(Math.fround(value)) || typeof accessor.max[axis] !== 'number' || !Number.isFinite(Math.fround(accessor.max[axis])) || value > accessor.max[axis]))) throw new Error('Morph POSITION requires finite ordered min/max bounds.');}@@ -927,7 +927,12 @@ function makeSkinBinding(node) {function prepareSkinBinding(binding, geometry) {const { node, skin, pendingPose, pendingWorld } = binding;if (skin.jointMatrices !== binding.palette || skin.jointWorldMatrices !== binding.jointWorld || binding.palette.length !== pendingPose.jointMatrices.length || binding.jointWorld.length !== pendingWorld.length) throw new Error('Imported skin palette identities must remain unchanged.');- for (let joint = 0; joint < node.skeleton.bones.length; joint++) pendingWorld.set(node.skeleton.bones[joint].matrixWorld.elements, joint * 16);+ for (let joint = 0; joint < node.skeleton.bones.length; joint++) {+ const jointWorld = pendingWorld.subarray(joint * 16, joint * 16 + 16);+ jointWorld.set(node.skeleton.bones[joint].matrixWorld.elements);+ // A joint at zero scale collapses its vertices to a point instead of refusing the pose.+ if (collapseSingularMatrix(jointWorld, undefined, COLLAPSED_JOINT_SCALE)) binding.collapsedJoints = true;+ }updateSkinPose(pendingPose, pendingWorld, skin.inverseBindMatrices, node.matrixWorld.elements, skin.bindMatrix);validateSkinPose(pendingPose, geometry, node.matrixWorld.elements);}@@ -959,20 +964,21 @@ function prepareMorphBinding(binding) {}const COLLAPSED_SCALE = 2e-4;+const COLLAPSED_JOINT_SCALE = 1e-2;const collapseScratch = new Matrix4();/*** Replaces a singular or non-finite world matrix, in place, with a uniform scale of 0.0002 at the same position so the* part is a speck that stays finite and invertible. Returns true when it replaced the matrix.*/-function collapseSingularMatrix(elements) {+function collapseSingularMatrix(elements, determinantFloor = 1e-12, collapsedScale = COLLAPSED_SCALE) {const finite = elements.every(Number.isFinite);const determinant = finite ? collapseScratch.fromArray(elements).determinant() : NaN;- if (finite && Number.isFinite(determinant) && Math.abs(determinant) >= 1e-12) return false;+ if (finite && Number.isFinite(determinant) && Math.abs(determinant) >= determinantFloor) return false;const position = [elements[12], elements[13], elements[14]];const keepPosition = position.every(Number.isFinite);elements.fill(0);- elements[0] = elements[5] = elements[10] = COLLAPSED_SCALE;+ elements[0] = elements[5] = elements[10] = collapsedScale;elements[15] = 1;if (keepPosition) elements.set(position, 12);return true;@@ -1253,6 +1259,10 @@ export async function parseGltf(data, options = {}) {if (node.isSkinnedMesh) {const binding = makeSkinBinding(node);prepareSkinBinding(binding, geometry);+ if (binding.collapsedJoints) {+ const warning = `Skin of ${node.name ? `"${node.name}"` : association.nodes} has a joint with zero or non-finite scale; its vertices collapse to a point while it is singular.`;+ if (!warnings.includes(warning)) warnings.push(warning);+ }commitSkinBinding(binding);part.skin = binding.skin;skinBindings.push({ ...binding, geometry });@@ -1304,9 +1314,9 @@ export async function parseGltf(data, options = {}) {for (const node of sourceNodes.values()) {if (skinJointIndices.has(node.association.nodes)) jointNodes.add(node);}- // A mesh or group node posed to zero scale draws nothing; only skin joints still refuse a singular pose.+ // A node posed to zero scale draws nothing; a zero-scale skin joint collapses its vertices to a point.for (const node of nodes) {- if (!jointNodes.has(node)) toleratedNodes.add(node);+ toleratedNodes.add(node);}const meshIdsByNode = new Map([...sourceNodes.values()].map(node => [node, []]));for (let index = 0; index < bindings.length; index++) {diff --git a/tests/agent-asset-motion.test.js b/tests/agent-asset-motion.test.jsindex 07cfa97e..f3cc68e6 100644--- a/tests/agent-asset-motion.test.js+++ b/tests/agent-asset-motion.test.js@@ -83,7 +83,6 @@ test('invalid authored poses roll back decoder private state and complete adapteconst before = pose(scene);const canonical = scene.exportRecipe();for (const commands of [- [{ type: 'set-asset-node', id: 'node-3', scale: [1e-40, 1e-40, 1e-40] }],[{ type: 'set-asset-node', id: 'node-3', rotation: [0, 0, 0, 0] }],[{ type: 'set-asset-node', id: 'mesh-0', translation: [1, 0, 0] }],[{ type: 'set-asset-node', id: 'node-3' }],diff --git a/tests/gltf-tolerance-clip.test.js b/tests/gltf-tolerance-clip.test.jsindex ea60a27b..e4902065 100644--- a/tests/gltf-tolerance-clip.test.js+++ b/tests/gltf-tolerance-clip.test.js@@ -1,6 +1,7 @@import assert from 'node:assert/strict';import test from 'node:test';import { parseGltf } from '../src/gltf.js';+import { skinnedStripAsset } from './fixtures/skinned-strip.js';/** One triangle with normals (accessors 0 and 1) and a clip keying node 0's scale at 0 s and 1 s (accessors 2 and 3). */function documentWithScaleClip(firstScale, lastScale, edit) {@@ -47,3 +48,29 @@ test('a node that starts at zero scale shows again when a clip scales it up', asassert.ok(partScaleAt(asset, 0) < 1e-3);assert.equal(partScaleAt(asset, 1), 1);});++test('a morph target with normalized int16 POSITION deltas loads and is scaled into floats', async () => {+ const asset = await parseGltf(documentWithScaleClip([1, 1, 1], [1, 1, 1], document => {+ const quantized = new Int16Array([0, 0, 32767, 0, 0, 16384, 0, 0, 0]);+ const buffer = document.buffers[0];+ const previous = Buffer.from(buffer.uri.split(',')[1], 'base64');+ const combined = Buffer.concat([previous, Buffer.from(quantized.buffer)]);+ buffer.byteLength = combined.length;+ buffer.uri = `data:application/octet-stream;base64,${combined.toString('base64')}`;+ document.bufferViews.push({ buffer: 0, byteOffset: previous.length, byteLength: 18 });+ document.accessors.push({ bufferView: 1, componentType: 5122, normalized: true, count: 3, type: 'VEC3', min: [0, 0, 0], max: [0, 0, 32767] });+ document.meshes[0].primitives[0].targets = [{ POSITION: 4 }];+ }));+ const deltas = asset.parts[0].geometry.morphTargets[0].positions;+ assert.equal(deltas[2], 1);+ assert.ok(Math.abs(deltas[5] - 16384 / 32767) < 1e-6);+});++test('a skin joint at zero scale loads with a warning and the skinned vertices collapse instead of refusing the file', async () => {+ const asset = await parseGltf(skinnedStripAsset(document => {+ document.nodes[3].scale = [0, 0, 0];+ }));+ assert.equal(asset.parts.length, 1);+ assert.ok(asset.warnings.some(warning => /joint with zero or non-finite scale/.test(warning)));+ assert.ok(asset.parts[0].skin.jointMatrices.every(Number.isFinite));+});diff --git a/tests/gltf.test.js b/tests/gltf.test.jsindex b5347063..f0c8abf9 100644--- a/tests/gltf.test.js+++ b/tests/gltf.test.js@@ -586,7 +586,7 @@ test('skin preflight guards joints, influence shapes, raw zero weights, indices}), { maxJoints: 2 }), /skin pose joints/);});-test('invalid skeletal animation fails before public matrices or palettes change', async () => {+test('a skeletal animation that scales a joint to zero collapses it to a point and restores with the base pose', async () => {const asset = await parseGltf(skinnedStripAsset((document, append) => {const scales = append(new Float32Array([1, 1, 1, 0, 1, 1]), 'VEC3');document.animations[0].samplers[0].output = scales;@@ -596,10 +596,10 @@ test('invalid skeletal animation fails before public matrices or palettes changeconst matrix = Array.from(part.matrix);const palette = Array.from(part.skin.jointMatrices);const world = Array.from(part.skin.jointWorldMatrices);- assert.throws(() => asset.applyAnimation(2), /singular/);+ asset.applyAnimation(2);+ assert.ok(Array.from(part.skin.jointMatrices).every(Number.isFinite));assert.deepEqual(Array.from(part.matrix), matrix);- assert.deepEqual(Array.from(part.skin.jointMatrices), palette);- assert.deepEqual(Array.from(part.skin.jointWorldMatrices), world);+ assert.notDeepEqual(Array.from(part.skin.jointWorldMatrices), world);asset.applyAnimation(0);assert.deepEqual(Array.from(part.skin.jointMatrices), palette);asset.dispose();