3D engine that AI agents drive
Compute morph normals without a base NORMAL and guard NaN in skinning inputs (#496)
Nguyen Xuan Anc78131756340
diff --git a/changes/496-morph-normals.md b/changes/496-morph-normals.mdnew file mode 100644index 00000000..7c1612e4--- /dev/null+++ b/changes/496-morph-normals.md@@ -0,0 +1 @@+- Light morphs that have no authored base NORMAL (#496): the loader now computes the base normals from the triangles and per-target normal deltas from the morphed positions, so lighting follows the morph instead of dropping the deltas. A NaN or Infinity in a vertex POSITION or a morph POSITION delta becomes 0, and a non-finite inverse bind matrix becomes the identity, each with a load warning, so bounds, culling and skinning stay finite instead of refusing the file.diff --git a/changes/496-morph-normals.size.md b/changes/496-morph-normals.size.mdnew file mode 100644index 00000000..021a4af4--- /dev/null+++ b/changes/496-morph-normals.size.md@@ -0,0 +1,3 @@+- entry:gltf: +298 bytes gzip (51077 to 51375) for the per-target morph normal computation, the non-finite zeroing helper and the inverse bind matrix repair+- scene:gltf-box: +283 bytes gzip (80251 to 80534)+- goal:gltf-box: already over its 80000 goal before this change; +283 bytes pays for lighting that follows a morph on files without a base NORMAL and for loading files with NaN vertices or inverse bind matrices instead of refusing them, a real capability for downloaded models (#496), not a score gain.diff --git a/src/gltf.js b/src/gltf.jsindex 2ed7e6a9..1992b384 100644--- a/src/gltf.js+++ b/src/gltf.js@@ -802,6 +802,38 @@ function copyAttribute(attribute, size) {return values;}+/** Like copyAttribute, but a NaN or Infinity becomes 0 and is reported through `onNonFinite(count)` instead of refusing the file. */+function copyAttributeZeroingNonFinite(attribute, size, onNonFinite) {+ if (attribute.itemSize !== size) throw new Error(`Expected a ${size}-component mesh attribute.`);+ const values = attributeFloats(attribute);+ let nonFiniteCount = 0;+ for (let index = 0; index < values.length; index++) {+ if (Number.isFinite(values[index])) continue;+ values[index] = 0;+ nonFiniteCount++;+ }+ if (nonFiniteCount) onNonFinite(nonFiniteCount);+ return values;+}++/**+ * Per-target normal deltas for a primitive that has no authored base NORMAL: the normals of the morphed triangles minus+ * the base normals, so lighting follows the morph. A vertex whose morphed normal has no direction keeps the base normal.+ */+function computeMorphNormalDeltas(positions, indices, baseNormals, positionDeltas) {+ const morphedPositions = new Float32Array(positions.length);+ for (let index = 0; index < positions.length; index++) morphedPositions[index] = positions[index] + positionDeltas[index];+ const deltas = computeVertexNormals(morphedPositions, indices);+ for (let offset = 0; offset < deltas.length; offset += 3) {+ const length = Math.hypot(deltas[offset], deltas[offset + 1], deltas[offset + 2]);+ for (let axis = 0; axis < 3; axis++) {+ const morphedNormal = length > 1e-8 ? deltas[offset + axis] / length : baseNormals[offset + axis];+ deltas[offset + axis] = morphedNormal - baseNormals[offset + axis];+ }+ }+ return deltas;+}+/** The corner offsets of a triangle and its area-weighted normal (the cross product of two edges). */function triangleAt(positions, indices, corner) {const [first, second, third] = [indices[corner] * 3, indices[corner + 1] * 3, indices[corner + 2] * 3];@@ -844,7 +876,8 @@ function hasTriangleWithArea(positions, indices) {function convertGeometry(source, mirrored, primitive, secondUvSet, onIgnoredVertexAlpha, onRepair) {const { position, normal, uv, uv1, color, skinIndex, skinWeight } = source.attributes;- const positions = copyAttribute(position, 3);+ const zeroedBy = label => count => onRepair(`${count} non-finite ${label} value(s) were set to 0`);+ const positions = copyAttributeZeroingNonFinite(position, 3, zeroedBy('POSITION'));const indices = new Uint32Array(source.index?.count ?? position.count);for (let index = 0; index < indices.length; index++) {const value = source.index ? source.index.array[index] : index;@@ -878,6 +911,19 @@ function convertGeometry(source, mirrored, primitive, secondUvSet, onIgnoredVert}onRepair(`${repairedNormals.length} vertex normal(s) had zero length and were rebuilt from the triangles`);}+ if (primitive.targets?.length) {+ geometry.morphTargets = primitive.targets.map((target, index) => {+ const channels = {};+ if (target.POSITION !== undefined) channels.positions = copyAttributeZeroingNonFinite(source.morphPositions[index], 3, zeroedBy('morph POSITION'));+ if (target.NORMAL !== undefined && normal) channels.normals = copyAttribute(source.morphNormals[index], 3);+ // Without a base NORMAL the authored deltas have nothing to add to: derive them from the morphed positions.+ if (!normal && channels.positions) channels.normals = computeMorphNormalDeltas(positions, indices, normals, channels.positions);+ return channels;+ });+ if (!normal && geometry.morphTargets.some(channels => channels.normals)) {+ onRepair('it has morph targets but no base NORMAL; base and per-target normals are generated from the triangles');+ }+ }if (mirrored) {for (let index = 0; index < indices.length; index += 3) {const second = indices[index + 1];@@ -895,17 +941,6 @@ function convertGeometry(source, mirrored, primitive, secondUvSet, onIgnoredVertif (color) geometry.colors = convertVertexColors(color, position.count, onIgnoredVertexAlpha);if (skinIndex) geometry.skinIndices = new Uint16Array(copyAttribute(skinIndex, 4));if (skinWeight) geometry.skinWeights = copyAttribute(skinWeight, 4);- if (primitive.targets?.length) {- geometry.morphTargets = primitive.targets.map((target, index) => {- const channels = {};- if (target.POSITION !== undefined) channels.positions = copyAttribute(source.morphPositions[index], 3);- if (target.NORMAL !== undefined && normal) channels.normals = copyAttribute(source.morphNormals[index], 3);- return channels;- });- if (!normal && primitive.targets.some(target => target.NORMAL !== undefined)) {- onRepair('it has morph targets but no base NORMAL; normals are generated from the triangles and the morph normal deltas are dropped');- }- }return geometry;}@@ -914,16 +949,25 @@ function makeSkinBinding(node) {const pose = createSkinPose(count);const pendingPose = createSkinPose(count);const inverseBindMatrices = new Float32Array(count * 16);+ let repairedInverseBindMatrices = 0;const jointWorldMatrices = new Float32Array(count * 16);const pendingWorld = new Float32Array(count * 16);const joints = node.skeleton.bones.map((bone, index) => {- inverseBindMatrices.set(node.skeleton.boneInverses[index].elements, index * 16);+ const inverse = inverseBindMatrices.subarray(index * 16, index * 16 + 16);+ inverse.set(node.skeleton.boneInverses[index].elements);+ if (!inverse.every(Number.isFinite)) {+ // A non-finite inverse bind matrix would turn every vertex of the joint into NaN: bind that joint at the identity.+ inverse.set(IDENTITY_MATRIX);+ repairedInverseBindMatrices++;+ }return { name: bone.name, parent: node.skeleton.bones.indexOf(bone.parent) };});const skin = Object.assign(pose, { joints, inverseBindMatrices, jointWorldMatrices, bindMatrix: new Float32Array(node.bindMatrix.elements) });- return { node, skin, pendingPose, pendingWorld, palette: skin.jointMatrices, jointWorld: skin.jointWorldMatrices };+ return { node, skin, pendingPose, pendingWorld, palette: skin.jointMatrices, jointWorld: skin.jointWorldMatrices, repairedInverseBindMatrices };}+const IDENTITY_MATRIX = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];+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.');@@ -1263,6 +1307,10 @@ export async function parseGltf(data, options = {}) {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);}+ if (binding.repairedInverseBindMatrices) {+ const warning = `Skin of ${node.name ? `"${node.name}"` : association.nodes} has ${binding.repairedInverseBindMatrices} non-finite inverse bind matrix(es); they were replaced with the identity.`;+ if (!warnings.includes(warning)) warnings.push(warning);+ }commitSkinBinding(binding);part.skin = binding.skin;skinBindings.push({ ...binding, geometry });diff --git a/tests/gltf-morph-normals-and-nan.test.js b/tests/gltf-morph-normals-and-nan.test.jsnew file mode 100644index 00000000..7e183d30--- /dev/null+++ b/tests/gltf-morph-normals-and-nan.test.js@@ -0,0 +1,76 @@+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 in the XY plane (accessor 0) and a morph that lifts its third corner out of the plane (accessor 1). */+function morphDocument(edit) {+ const floats = new Float32Array([0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]);+ const bytes = new Uint8Array(floats.buffer);+ const document = {+ asset: { version: '2.0' },+ scene: 0,+ scenes: [{ nodes: [0] }],+ nodes: [{ name: 'Tri', mesh: 0 }],+ meshes: [{ name: 'Tri', primitives: [{ attributes: { POSITION: 0 }, targets: [{ POSITION: 1 }] }] }],+ accessors: [+ { bufferView: 0, byteOffset: 0, componentType: 5126, count: 3, type: 'VEC3', min: [0, 0, 0], max: [1, 1, 0] },+ { bufferView: 0, byteOffset: 36, componentType: 5126, count: 3, type: 'VEC3', min: [0, 0, 0], max: [0, 0, 1] },+ ],+ bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: bytes.length }],+ buffers: [{ byteLength: bytes.length, uri: `data:application/octet-stream;base64,${Buffer.from(bytes).toString('base64')}` }],+ };+ edit?.(document, floats);+ const edited = new Uint8Array(floats.buffer);+ document.buffers[0].uri = `data:application/octet-stream;base64,${Buffer.from(edited).toString('base64')}`;+ return JSON.stringify(document);+}++test('morph targets without a base NORMAL get per-target normals that follow the morphed triangles', async () => {+ const asset = await parseGltf(morphDocument());+ const { geometry } = asset.parts[0];+ assert.deepEqual(Array.from(geometry.normals), [0, 0, 1, 0, 0, 1, 0, 0, 1]);+ const deltas = geometry.morphTargets[0].normals;+ assert.equal(deltas.length, 9);+ // The morphed triangle (0,0,0), (1,0,0), (0,1,1) leans toward -Y/+Z: normal (0, -1, 1) / sqrt(2) at every vertex.+ const morphedNormal = [0, -Math.SQRT1_2, Math.SQRT1_2];+ for (let vertex = 0; vertex < 3; vertex++) {+ for (let axis = 0; axis < 3; axis++) {+ assert.ok(Math.abs(geometry.normals[vertex * 3 + axis] + deltas[vertex * 3 + axis] - morphedNormal[axis]) < 1e-6);+ }+ }+ assert.match(asset.warnings[0], /no base NORMAL; base and per-target normals are generated/);+ asset.dispose();+});++test('a NaN vertex position becomes 0 with a warning and the bounds stay finite', async () => {+ const asset = await parseGltf(morphDocument((document, floats) => {+ floats[5] = Number.NaN;+ floats[10] = Number.POSITIVE_INFINITY;+ }));+ assert.ok(Array.from(asset.parts[0].geometry.positions).every(Number.isFinite));+ assert.ok(Array.from(asset.parts[0].geometry.morphTargets[0].positions).every(Number.isFinite));+ assert.ok(asset.warnings.some(warning => /1 non-finite POSITION value\(s\) were set to 0/.test(warning)));+ assert.ok(asset.warnings.some(warning => /1 non-finite morph POSITION value\(s\) were set to 0/.test(warning)));+ assert.ok(Object.values(asset.bounds ?? { box: 0 }).flat(Infinity).every(value => typeof value !== 'number' || Number.isFinite(value)));+ asset.dispose();+});++test('a non-finite inverse bind matrix is replaced with the identity and the pose stays finite', async () => {+ const asset = await parseGltf(skinnedStripAsset((document, append, chunks) => {+ const inverseBindMatrices = chunks[document.skins[0].inverseBindMatrices];+ inverseBindMatrices[16 + 5] = Number.NaN;+ }));+ assert.ok(asset.warnings.some(warning => /1 non-finite inverse bind matrix\(es\); they were replaced with the identity/.test(warning)));+ assert.ok(Array.from(asset.parts[0].skin.jointMatrices).every(Number.isFinite));+ assert.ok(Array.from(asset.parts[0].skin.inverseBindMatrices).every(Number.isFinite));+ asset.dispose();+});++test('a NaN joint transform loads with a warning and a finite palette', async () => {+ const asset = await parseGltf(skinnedStripAsset((document, append, chunks) => {+ document.nodes[3].scale = [Number.NaN, 1, 1];+ }));+ assert.ok(Array.from(asset.parts[0].skin.jointMatrices).every(Number.isFinite));+ asset.dispose();+});diff --git a/tests/gltf-morph.test.js b/tests/gltf-morph.test.jsindex cd999100..09400e4d 100644--- a/tests/gltf-morph.test.js+++ b/tests/gltf-morph.test.js@@ -301,7 +301,6 @@ test('malformed deltas, defaults, accessor shapes and all animation channels rejdocument => { document.meshes[0].primitives.push({ attributes: { POSITION: 0, NORMAL: 1 }, targets: [{ POSITION: 2 }] }); },document => { document.meshes[0].weights = [0]; },document => { document.nodes[0].weights = [1e39, 0]; },- (document, append, chunks) => { chunks[2][0] = NaN; },(document, append) => { addWeightsClip(document, append); document.animations[0].samplers[0].output = 0; },(document, append) => { addWeightsClip(document, append); document.nodes[0].mesh = undefined; },(document, append) => { addWeightsClip(document, append); document.animations[0].channels[0].target.node = 99; },diff --git a/tests/gltf-tolerance.test.js b/tests/gltf-tolerance.test.jsindex 292ac5e9..4f7733e3 100644--- a/tests/gltf-tolerance.test.js+++ b/tests/gltf-tolerance.test.js@@ -59,7 +59,7 @@ test('a singular group node skips the meshes under it', async () => {assert.match(asset.warnings[0], /Skipped node "Child"/);});-test('morph targets without a base NORMAL load: normals are generated and the morph normal deltas are dropped', async () => {+test('morph targets without a base NORMAL load: normals are generated and the morph normal deltas are recomputed', async () => {const asset = await parseGltf(documentWith(FACE_NORMALS, document => {const primitive = document.meshes[0].primitives[0];delete primitive.attributes.NORMAL;@@ -68,7 +68,7 @@ test('morph targets without a base NORMAL load: normals are generated and the moassert.equal(asset.parts.length, 2);assert.deepEqual(Array.from(asset.parts[0].geometry.normals), FACE_NORMALS);assert.equal(asset.parts[0].geometry.morphTargets.length, 2);- assert.equal(asset.parts[0].geometry.morphTargets[0].normals, undefined);+ assert.equal(asset.parts[0].geometry.morphTargets[0].normals.length, 9);assert.match(asset.warnings[0], /^Repaired primitive 0 of mesh "Tri": it has morph targets but no base NORMAL/);});