Skip to content

3D engine that AI agents drive

Name the bad field when fracture and explosion input is wrong (#2449)

Nguyen Xuan An423da0ebdb8b
diff --git a/changes/2449.md b/changes/2449.md
new file mode 100644
index 00000000..d8c0a836
--- /dev/null
+++ b/changes/2449.md
@@ -0,0 +1 @@
+- `fractureMesh`, `fragmentPhysics` and `registerExplosionGrids` name the bad field when given NaN geometry, a stray index, a zero or NaN density or an unknown fuel (#2449, #2450, #2451)
diff --git a/changes/2449.size.md b/changes/2449.size.md
new file mode 100644
index 00000000..d038f62d
--- /dev/null
+++ b/changes/2449.size.md
@@ -0,0 +1,2 @@
+- entry:fracture: the checks name a NaN vertex, a stray index and a zero density instead of failing later with a wrong error or a massless body
+- scene:agent-scene+lazy: same checks, bundled with the fracture addon
diff --git a/docs/physics.md b/docs/physics.md
index 8e9f50ae..8af4aca7 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -476,7 +476,7 @@ const parts = fragmentPhysics(fracture, { translation: [0, 2, 0], strength: 20,
`fractureMesh` returns `fragments`, `glue` and `volume`. Each fragment has `positions`, `normals`, `indices`, `volume` and `center` in the part's local space, and `groups`: the outside faces are material slot 0 and the new inside faces slot 1, each as a `{ slot, start, count }` range of `indices`. Fragment volumes sum to the part volume. `glue` lists each neighbouring pair `{ a, b, anchor, area }`.
-`fragmentPhysics` turns that into bodies, convex hull colliders and one fixed joint per neighbouring pair, each with `breakImpulse: strength`. A fixed joint takes `breakImpulse` (N s, above 0): in the bake the joint is removed on the first step in which either of its bodies takes a contact impulse (contact force times the timestep) at or above it. A body resting under its own weight takes about `mass * 9.81 / 60`, so a strength above that holds a structure up and a ball or a falling slab below it breaks the glue. All the joints of a hit fragment that are weaker than the hit break together; the rest of the structure stays glued. `recording.jointBreaks` lists `{ frame, joint, impulse }`. Recipes take `breakImpulse` on a fixed `physics.joints` entry, and `scene_inspect` reports `jointBreaks`.
+`fragmentPhysics` refuses a `density` at or below 0, a negative or NaN `friction` and a `translation` or `rotation` that is not finite, and `fractureMesh` names a NaN position or a stray index. `fragmentPhysics` turns that into bodies, convex hull colliders and one fixed joint per neighbouring pair, each with `breakImpulse: strength`. A fixed joint takes `breakImpulse` (N s, above 0): in the bake the joint is removed on the first step in which either of its bodies takes a contact impulse (contact force times the timestep) at or above it. A body resting under its own weight takes about `mass * 9.81 / 60`, so a strength above that holds a structure up and a ball or a falling slab below it breaks the glue. All the joints of a hit fragment that are weaker than the hit break together; the rest of the structure stays glued. `recording.jointBreaks` lists `{ frame, joint, impulse }`. Recipes take `breakImpulse` on a fixed `physics.joints` entry, and `scene_inspect` reports `jointBreaks`.
### Fracture from a recipe or the MCP tool
diff --git a/src/explosion-grids.js b/src/explosion-grids.js
index d2e69c41..3ed4c4df 100644
--- a/src/explosion-grids.js
+++ b/src/explosion-grids.js
@@ -150,6 +150,9 @@ export function explosionGridBytes(name) {
* Returns the frame names. Same fuel and seed give the same bytes.
*/
export function registerExplosionGrids(fuel, seed, velocity = false) {
+ if (!Object.hasOwn(FUEL_OPTIONS, fuel)) {
+ throw new RangeError(`registerExplosionGrids: fuel is ${JSON.stringify(fuel)}; use one of ${Object.keys(FUEL_OPTIONS).join(', ')}`);
+ }
const names = explosionGridNames(fuel, seed, velocity);
const emptyName = explosionEmptyGridName(velocity);
// The MCP server sends these grids with the call (explosionGridNamesFor), so the preview page has them already and bakes nothing.
diff --git a/src/fracture.js b/src/fracture.js
index 07b38294..28c659ed 100644
--- a/src/fracture.js
+++ b/src/fracture.js
@@ -67,10 +67,21 @@ function validateOptions(options) {
return { seed, cells, impact, impactRadius };
}
+function vertexOf({ positions, normals }, vertex) {
+ if (!Number.isInteger(vertex) || vertex < 0 || vertex * 3 + 2 >= positions.length) {
+ throw failure('fracture geometry index', vertex, `an integer below ${positions.length / 3}, a vertex of the positions`);
+ }
+ const point = [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]];
+ const normal = normals ? [normals[vertex * 3], normals[vertex * 3 + 1], normals[vertex * 3 + 2]] : [0, 0, 0];
+ if (![...point, ...normal].every(Number.isFinite)) {
+ throw failure('fracture geometry vertex', `${vertex} with a NaN or Infinity position or normal`, 'finite numbers in both');
+ }
+ return { point, normal };
+}
+
/** The source triangles as convex polygons with a vertex normal each, after checking it is a closed, outward, convex solid. */
function sourcePolygons(geometry) {
- const { positions, indices } = geometry;
- const normals = geometry.normals;
+ const { indices } = geometry;
const triangleCount = indices.length / 3;
if (!Number.isInteger(triangleCount) || triangleCount < 4) {
throw failure('fracture geometry', `${triangleCount} triangles`, 'a closed mesh with at least 4 triangles, such as a box');
@@ -81,15 +92,10 @@ function sourcePolygons(geometry) {
const polygons = [];
const planes = [];
for (let triangle = 0; triangle < triangleCount; triangle++) {
- const vertices = [0, 1, 2].map(corner => {
- const vertex = indices[triangle * 3 + corner];
- const point = [positions[vertex * 3], positions[vertex * 3 + 1], positions[vertex * 3 + 2]];
- const normal = normals ? [normals[vertex * 3], normals[vertex * 3 + 1], normals[vertex * 3 + 2]] : [0, 0, 0];
- return { point, normal };
- });
+ const vertices = [0, 1, 2].map(corner => vertexOf(geometry, indices[triangle * 3 + corner]));
const faceNormal = normalized(cross(subtract(vertices[1].point, vertices[0].point), subtract(vertices[2].point, vertices[0].point)));
if (faceNormal[0] === 0 && faceNormal[1] === 0 && faceNormal[2] === 0) continue;
- if (!normals) vertices.forEach(vertex => { vertex.normal = faceNormal; });
+ if (!geometry.normals) vertices.forEach(vertex => { vertex.normal = faceNormal; });
polygons.push({ vertices, slot: OUTSIDE_SLOT });
planes.push({ normal: faceNormal, offset: dot(faceNormal, vertices[0].point) });
}
@@ -300,6 +306,12 @@ export function fractureMesh(geometry, rawOptions) {
return { fragments, glue, volume: polygonsVolume(polygons) };
}
+function checkFiniteList(field, value, length) {
+ if (!Array.isArray(value) || value.length !== length || !value.every(Number.isFinite)) {
+ throw failure(field, JSON.stringify(value), `${length} finite numbers`);
+ }
+}
+
function distinctHullPoints(positions) {
const distinct = new Map();
for (let index = 0; index < positions.length; index += 3) {
@@ -318,6 +330,14 @@ export function fragmentPhysics(fracture, { translation = [0, 0, 0], rotation =
if (!(Number.isFinite(strength) && strength > 0)) {
throw failure('glue strength', strength, 'an impulse above 0 in N s, such as 5');
}
+ if (!(Number.isFinite(density) && density > 0)) {
+ throw failure('fragment density', density, 'a number above 0, such as 1');
+ }
+ if (friction !== undefined && !(Number.isFinite(friction) && friction >= 0)) {
+ throw failure('fragment friction', friction, '0 or more, such as 0.5');
+ }
+ checkFiniteList('fragment translation', translation, 3);
+ checkFiniteList('fragment rotation', rotation, 4);
const bodies = [];
const colliders = [];
fracture.fragments.forEach((fragment, index) => {
diff --git a/tests/explosion-grids-input.test.js b/tests/explosion-grids-input.test.js
new file mode 100644
index 00000000..ea5b468c
--- /dev/null
+++ b/tests/explosion-grids-input.test.js
@@ -0,0 +1,9 @@
+import test from 'node:test';
+import assert from 'node:assert/strict';
+import { registerExplosionGrids } from '../src/explosion-grids.js';
+
+test('registerExplosionGrids refuses a fuel it has no options for instead of baking a made-up blast', () => {
+ for (const fuel of ['bogus', undefined, 'constructor']) {
+ assert.throws(() => registerExplosionGrids(fuel, 1), /registerExplosionGrids: fuel is .*use one of dry, oily/);
+ }
+});
diff --git a/tests/fracture.test.js b/tests/fracture.test.js
index e044b082..5002fece 100644
--- a/tests/fracture.test.js
+++ b/tests/fracture.test.js
@@ -131,3 +131,29 @@ test('breakImpulse is only for fixed joints and must be positive', async () => {
definition.joints[0] = { name: 'j', type: 'fixed', bodyA: 'a', bodyB: 'b', breakImpulse: -1 };
await assert.rejects(createPhysicsScene(definition, { frameCount: 2 }), /breakImpulse/);
});
+
+test('bad geometry is refused by the field that is wrong, not by the cell count', () => {
+ const brokenPosition = box(0);
+ brokenPosition.positions[4] = NaN;
+ assert.throws(() => fractureMesh(brokenPosition, { cells: 4 }), /fracture geometry vertex is [0-9]+ with a NaN or Infinity position or normal; use finite numbers/);
+ const brokenNormal = box(0);
+ brokenNormal.normals[2] = Infinity;
+ assert.throws(() => fractureMesh(brokenNormal, { cells: 4 }), /fracture geometry vertex is [0-9]+ with a NaN or Infinity/);
+ const strayIndex = box(0);
+ strayIndex.indices[0] = 9999;
+ assert.throws(() => fractureMesh(strayIndex, { cells: 4 }), /fracture geometry index is 9999; use an integer below/);
+});
+
+test('fragmentPhysics refuses a density, friction or pose the solver cannot use', () => {
+ const fracture = fractureMesh(box(0), { cells: 3 });
+ for (const density of [0, -2, NaN, Infinity]) {
+ assert.throws(() => fragmentPhysics(fracture, { strength: 5, density }), /fragment density is .*above 0/);
+ }
+ for (const friction of [-1, NaN]) {
+ assert.throws(() => fragmentPhysics(fracture, { strength: 5, friction }), /fragment friction is .*0 or more/);
+ }
+ assert.throws(() => fragmentPhysics(fracture, { strength: 5, translation: [0, 1] }), /fragment translation is .*3 finite numbers/);
+ assert.throws(() => fragmentPhysics(fracture, { strength: 5, translation: [NaN, 0, 0] }), /fragment translation/);
+ assert.throws(() => fragmentPhysics(fracture, { strength: 5, rotation: [0, 0, 1] }), /fragment rotation is .*4 finite numbers/);
+ assert.equal(fragmentPhysics(fracture, { strength: 5, friction: 0 }).colliders[0].friction, 0);
+});