3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Stop NaN from zero-area triangles and non-finite positions (#2420)
Nguyen Xuan An20e7e56576bd
diff --git a/changes/2420.md b/changes/2420.mdnew file mode 100644index 00000000..b9914d81--- /dev/null+++ b/changes/2420.md@@ -0,0 +1 @@+- Zero-area and non-finite inputs in closestPointOnTriangle, simplifyGeometry and recomputeNormals now return the nearest edge point or throw an error that names the vertex (#2420, #2421, #2422).diff --git a/changes/2420.size.md b/changes/2420.size.mdnew file mode 100644index 00000000..a6416019--- /dev/null+++ b/changes/2420.size.md@@ -0,0 +1,2 @@+- entry:sculpt: recomputeNormals now names a non-finite vertex instead of blaming the stroke; 120 bytes.+- scene:agent-scene+lazy: the zero-area closest-point fallback and two finite-position guards stop NaN geometry from the shrinkwrap, surface-distance and LOD paths; 479 bytes.diff --git a/src/geometry-normals.js b/src/geometry-normals.jsindex 87ef805e..d3fe3b73 100644--- a/src/geometry-normals.js+++ b/src/geometry-normals.js@@ -1,4 +1,8 @@+import { findNonFiniteVertex } from './triangle-math.js';+export function recomputeNormals(source, positions, fallbackNormals = source.normals) {+ const badVertex = findNonFiniteVertex(positions);+ if (badVertex >= 0) throw new RangeError(`Cannot recompute normals: vertex ${badVertex} has a NaN or infinite position. Pass finite positions.`);const groups = new Map();const vertexGroups = new Array(positions.length / 3);const normals = new Float32Array(positions.length);diff --git a/src/geometry-simplify.js b/src/geometry-simplify.jsindex 114ce2b6..f54a70ef 100644--- a/src/geometry-simplify.js+++ b/src/geometry-simplify.js@@ -7,6 +7,8 @@// Every plane counts once (not by face area), so the square root of a quadric cost is a distance in the units of the// positions and scales with the mesh: tiny triangles do not make a collapse look cheaper.+import { findNonFiniteVertex } from './triangle-math.js';+const PER_VERTEX_ATTRIBUTES = [['normals', 3], ['uvs', 2], ['lightUvs', 2], ['colors', 3], ['skyVisibility', 1]];const MINIMUM_NORMAL_AGREEMENT = 0.2;const MINIMUM_TRIANGLES = 4;@@ -73,6 +75,8 @@ function validateGeometry(geometry) {if (geometry[field]) throw new RangeError(`simplifyGeometry cannot reduce skinned or morphed geometry (${field}); its per-vertex weights would break.`);}validateIndexValues(geometry.indices, vertexCount);+ const badVertex = findNonFiniteVertex(geometry.positions);+ if (badVertex >= 0) throw new RangeError(`simplifyGeometry found a NaN or infinite position at vertex ${badVertex}: pass finite x, y, z for every vertex.`);}function validateIndexValues(indices, vertexCount) {diff --git a/src/triangle-math.js b/src/triangle-math.jsindex e12d9ae8..63091a10 100644--- a/src/triangle-math.js+++ b/src/triangle-math.js@@ -34,8 +34,16 @@ export function triangleNormal(triangle, out) {return out;}-/** Writes the point of the triangle nearest to the query point (Ericson, Real-Time Collision Detection). */+/**+ * Writes the point of the triangle nearest to the query point (Ericson, Real-Time Collision Detection).+ * A triangle with no area divides by zero in the region tests, so it falls back to its nearest edge.+ */export function closestPointOnTriangle(point, triangle, out) {+ closestPointByRegions(point, triangle, out);+ return Number.isFinite(out[0] + out[1] + out[2]) ? out : closestPointOnEdges(point, triangle, out);+}++function closestPointByRegions(point, triangle, out) {const [ax, ay, az, bx, by, bz, cx, cy, cz] = triangle;const abX = bx - ax;const abY = by - ay;@@ -82,6 +90,38 @@ export function closestPointOnTriangle(point, triangle, out) {return setPoint(out, ax + abX * secondWeight + acX * thirdWeight, ay + abY * secondWeight + acY * thirdWeight, az + abZ * secondWeight + acZ * thirdWeight);}+// A triangle with no area has no interior to project onto: the answer is the nearest point of its three edges.+function closestPointOnEdges(point, triangle, out) {+ let nearest = Infinity;+ for (let corner = 0; corner < 3; corner++) {+ const start = corner * 3;+ const end = (corner + 1) % 3 * 3;+ let lengthSquared = 0;+ let along = 0;+ for (let axis = 0; axis < 3; axis++) {+ const step = triangle[end + axis] - triangle[start + axis];+ lengthSquared += step * step;+ along += step * (point[axis] - triangle[start + axis]);+ }+ const fraction = lengthSquared > 0 ? Math.min(1, Math.max(0, along / lengthSquared)) : 0;+ const x = triangle[start] + (triangle[end] - triangle[start]) * fraction;+ const y = triangle[start + 1] + (triangle[end + 1] - triangle[start + 1]) * fraction;+ const z = triangle[start + 2] + (triangle[end + 2] - triangle[start + 2]) * fraction;+ const distance = Math.hypot(point[0] - x, point[1] - y, point[2] - z);+ if (distance < nearest) {+ nearest = distance;+ setPoint(out, x, y, z);+ }+ }+ return out;+}++/** Index of the first vertex with a NaN or infinite coordinate in a flat x, y, z array, or -1. */+export function findNonFiniteVertex(positions) {+ const bad = positions.findIndex(value => !Number.isFinite(value));+ return bad < 0 ? -1 : Math.floor(bad / 3);+}+function setPoint(out, x, y, z) {out[0] = x;out[1] = y;diff --git a/tests/geometry-surface-nan-guards.test.js b/tests/geometry-surface-nan-guards.test.jsnew file mode 100644index 00000000..63ca8aaa--- /dev/null+++ b/tests/geometry-surface-nan-guards.test.js@@ -0,0 +1,55 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { closestPointOnTriangle } from '../src/triangle-math.js';+import { simplifyGeometry } from '../src/geometry-simplify.js';+import { recomputeNormals } from '../src/geometry-normals.js';++function flatGrid(cells) {+ const positions = [];+ const indices = [];+ for (let row = 0; row <= cells; row++) for (let column = 0; column <= cells; column++) positions.push(column, row, 0);+ for (let row = 0; row < cells; row++) {+ for (let column = 0; column < cells; column++) {+ const corner = row * (cells + 1) + column;+ const below = corner + cells + 1;+ indices.push(corner, corner + 1, below + 1, corner, below + 1, below);+ }+ }+ return { positions: new Float32Array(positions), indices: new Uint32Array(indices) };+}++test('closestPointOnTriangle stays finite for a triangle with a repeated corner', () => {+ const repeatedCorner = Float64Array.of(0, 2, 2, 0, 2, 2, 0, 0, -1);+ const nearest = closestPointOnTriangle([3, 0, 3], repeatedCorner, [0, 0, 0]);+ assert.ok(Array.from(nearest).every(Number.isFinite), `got ${Array.from(nearest)}`);+ // The nearest piece is the edge from (0,2,2) to (0,0,-1), at a fraction of 1/13 along it.+ assert.ok(Math.abs(nearest[1] - (2 - 2 / 13)) < 1e-9 && Math.abs(nearest[2] - (2 - 3 / 13)) < 1e-9 && nearest[0] === 0);+});++test('closestPointOnTriangle returns the nearest edge point for a collinear triangle', () => {+ const triangle = Float64Array.of(0, 0, 0, 2, 0, 0, 1, 0, 0);+ for (const queryX of [-1, 0.25, 0.75, 1.5, 3]) {+ const nearest = closestPointOnTriangle([queryX, 1, 1], triangle, [0, 0, 0]);+ assert.deepEqual(Array.from(nearest), [Math.min(2, Math.max(0, queryX)), 0, 0]);+ }+});++test('simplifyGeometry names the first non-finite vertex instead of returning NaN geometry', () => {+ const geometry = flatGrid(6);+ geometry.positions[9 * 3 + 1] = NaN;+ assert.throws(() => simplifyGeometry(geometry, { ratios: [0.5] }), error => error instanceof RangeError && /vertex 9/.test(error.message) && /finite/.test(error.message));+ const infinite = flatGrid(2);+ infinite.positions[2] = Infinity;+ assert.throws(() => simplifyGeometry(infinite, { ratios: [0.5] }), /vertex 0/);+});++test('recomputeNormals names a non-finite position instead of blaming the stroke', () => {+ const grid = flatGrid(2);+ const normals = new Float32Array(grid.positions.length);+ for (let vertex = 0; vertex < normals.length / 3; vertex++) normals[vertex * 3 + 2] = 1;+ const source = { positions: grid.positions, normals, indices: grid.indices };+ const moved = grid.positions.slice();+ moved[4 * 3] = NaN;+ assert.throws(() => recomputeNormals(source, moved), error => /vertex 4/.test(error.message) && !/cancel/.test(error.message));+ assert.equal(recomputeNormals(source, grid.positions).length, grid.positions.length);+});