3D engine that AI agents drive
JavaScript 3d3d-engineagentic-aiai-agentsblenderclaude-codegame-enginegaussian-splattinggltfjavascriptmcpmcp-servermodel-context-protocolpath-tracerpath-tracingpbrrenderingthreejs-alternativewebgl2webgpu
Fix three bugs from a sculpt, settle and rig hunt (#2393)
Nguyen Xuan Ande38ce0959f2
diff --git a/changes/2393.md b/changes/2393.mdnew file mode 100644index 00000000..2c33452c--- /dev/null+++ b/changes/2393.md@@ -0,0 +1 @@+- Fixes from a sculpt, settle and rig bug hunt: `settle` finds the ground under colliders above 10 km (#2393), a humanoid or quadruped preset fitted to a flat mesh is refused instead of collapsing every bone to one point (#2394), and `sculptGeometry` refuses unknown stroke fields and a `direction` on a stroke that ignores it (#2395)diff --git a/docs/sculpt.md b/docs/sculpt.mdindex 467b54b7..37dfd9c2 100644--- a/docs/sculpt.md+++ b/docs/sculpt.md@@ -25,6 +25,8 @@ All centers, radii and displacements use geometry-local units.| `displace` | Move along the supplied nonzero `direction`, normalized by the addon. | Signed distance. || `smooth` | Move toward the mean of connected triangle neighbors. One Jacobi step reads a fixed position snapshot. | Blend from 0 to 1. |+A stroke takes only `type`, `center`, `radius`, `strength` and, for `displace`, `direction`. Any other field, or a `direction` on `inflate` or `smooth`, throws.+For normalized distance `t = distance / radius`, the radial influence is `1 - 10t³ + 15t⁴ - 6t⁵` inside the brush and zero outside. Its first and second derivatives vanish at the center and boundary, avoiding an abrupt ridge where the brush ends. Inflate uses the input normals throughout one call, so a long sequence does not repeatedly rebuild normals. Separate calls allow later inflation to follow newly sculpted normals.Laplacian smoothing can shrink volume and soften boundaries. It does not preserve volume or guarantee collision-free topology.diff --git a/src/rig-presets.js b/src/rig-presets.jsindex 6c849184..51c30f90 100644--- a/src/rig-presets.js+++ b/src/rig-presets.js@@ -69,11 +69,28 @@ function quadrupedLayout(bounds) {return bones;}+// Bone offsets scale with these extents (x, y, z of the box); a zero one puts every bone on one point.+const SCALING_AXES = { humanoid: [1], quadruped: [0, 1, 2] };+// A mesh turned flat leaves rounding noise in its thin axis, so flat means thin next to the box's longest side.+const FLAT_RATIO = 1e-6;+const AXIS_NAMES = ['width', 'height', 'depth'];++function requireExtents(preset, bounds) {+ const extents = bounds.max.map((value, axis) => value - bounds.min[axis]);+ const flatBelow = Math.max(...extents) * FLAT_RATIO;+ const flat = SCALING_AXES[preset].filter(axis => !(extents[axis] > flatBelow));+ if (flat.length) {+ const missing = flat.map(axis => AXIS_NAMES[axis]).join(' and ');+ throw new RangeError(`A ${preset} armature needs a fit box with ${missing} above zero, or every bone lands on one point. Fit a taller mesh or pass bones.`);+ }+}+const LAYOUTS = { humanoid: humanoidLayout, quadruped: quadrupedLayout };/** Bones for a preset fitted to `bounds` ({ min, max } in armature space). `landmarks` replace a bone's head by name, or its tail as `<name>Tail`. */export function presetBones(preset, bounds, landmarks = {}) {if (!Object.hasOwn(LAYOUTS, preset)) throw new RangeError(`Armature preset must be one of ${RIG_PRESETS.join(', ')}.`);+ requireExtents(preset, bounds);const names = new Set();const bones = LAYOUTS[preset](bounds).map(bone => {names.add(bone.name);diff --git a/src/sculpt-strokes.js b/src/sculpt-strokes.jsindex 32d7ab8d..6227d2be 100644--- a/src/sculpt-strokes.js+++ b/src/sculpt-strokes.js@@ -15,11 +15,21 @@ function vector(input, name) {return Array.from(input, value => finite(value, name));}+const STROKE_FIELDS = ['type', 'center', 'radius', 'strength', 'direction'];+export function prepareStrokes(strokes) {return strokes.map(stroke => {if (!['inflate', 'displace', 'smooth'].includes(stroke?.type)) {throw new TypeError('Sculpt stroke type must be inflate, displace or smooth.');}+ for (const key of Object.keys(stroke)) {+ if (!STROKE_FIELDS.includes(key)) {+ throw new TypeError(`Sculpt stroke has an unsupported field "${key.slice(0, 48)}". Use type, center, radius, strength and, for displace, direction.`);+ }+ }+ if (stroke.type !== 'displace' && stroke.direction !== undefined) {+ throw new TypeError(`Only a displace stroke takes direction; remove it from this ${stroke.type} stroke.`);+ }const center = vector(stroke.center, 'center');const radius = finite(stroke.radius, 'radius');const strength = finite(stroke.strength, 'strength');diff --git a/src/settle.js b/src/settle.jsindex 75123078..276b8334 100644--- a/src/settle.js+++ b/src/settle.js@@ -124,7 +124,7 @@ function toLocal(collider, point) {}/** Top surface of one collider under (x, z): its height and unit normal, or null when the vertical line misses it. */-function surfaceUnder(collider, x, z) {+function surfaceUnder(collider, x, z, rayHeight) {if (collider.shape === 'ball') {const horizontal = Math.hypot(x - collider.translation[0], z - collider.translation[2]);if (horizontal >= collider.radius) return null;@@ -133,7 +133,7 @@ function surfaceUnder(collider, x, z) {return { height, normal };}const inverse = quat.invert(quat.create(), collider.rotation);- const origin = toLocal(collider, [x, 1e4, z]);+ const origin = toLocal(collider, [x, rayHeight, z]);const direction = vec3.transformQuat(vec3.create(), [0, -1, 0], inverse);let entry = -Infinity;let exit = Infinity;@@ -159,13 +159,19 @@ function surfaceUnder(collider, x, z) {const normalLocal = [0, 0, 0];normalLocal[entryAxis] = entrySign;const normal = vec3.transformQuat(vec3.create(), normalLocal, collider.rotation);- return { height: 1e4 - entry, normal };+ return { height: rayHeight - entry, normal };}-function groundUnder(colliders, x, z) {+/** A height above every collider, where the downward ray for ground height starts. */+function rayStartHeight(colliders) {+ const tops = colliders.map(collider => collider.translation[1] + (collider.shape === 'ball' ? collider.radius : Math.hypot(...collider.halfExtents)));+ return Math.max(...tops) + 1;+}++function groundUnder(colliders, x, z, rayHeight) {let best = null;for (const collider of colliders) {- const surface = surfaceUnder(collider, x, z);+ const surface = surfaceUnder(collider, x, z, rayHeight);if (surface && (!best || surface.height > best.height)) best = surface;}return best;@@ -197,6 +203,7 @@ function scatterCandidates(settings, skipped) {const meanRadius = boundingRadius(shape, [meanEdge, meanEdge, meanEdge]);const areaSize = (area.max[0] - area.min[0]) * (area.max[1] - area.min[1]);let columnHeight = Math.min(MAX_COLUMN_HEIGHT, Math.max(0.3, settings.count * (4 / 3) * Math.PI * meanRadius ** 3 / PACKING_FRACTION / areaSize));+ const rayHeight = rayStartHeight(colliders);const candidates = [];const flatSlope = Math.cos(maxSlope * Math.PI / 180);for (let index = 0; index < settings.count; index++) {@@ -209,7 +216,7 @@ function scatterCandidates(settings, skipped) {const radius = boundingRadius(shape, size);const x = area.min[0] + (area.max[0] - area.min[0]) * rolls[4];const z = area.min[1] + (area.max[1] - area.min[1]) * rolls[5];- const ground = groundUnder(colliders, x, z);+ const ground = groundUnder(colliders, x, z, rayHeight);if (!ground) {skipped.noGround++;continue;diff --git a/tests/rigging.test.js b/tests/rigging.test.jsindex 794dc21f..ee3d6b2c 100644--- a/tests/rigging.test.js+++ b/tests/rigging.test.js@@ -6,6 +6,7 @@ import { createAgentScene } from '../src/agent-scene.js';import { exportGlb } from '../src/export.js';import { mapHumanoidBones } from '../src/retarget.js';import { computeSkinWeights, createRigFromArmature, armatureProblems } from '../src/rig.js';+import { presetBones } from '../src/rig-presets.js';import { gradeRecipe } from '../bench/agent-modeling/check.mjs';import { taskById } from '../bench/agent-modeling/tasks.mjs';import { walkerRecipe } from '../bench/agent-modeling/walker.mjs';@@ -140,3 +141,16 @@ test('set-armatures replaces the rig and refuses to leave a skin without one', (scene.apply([{ type: 'set-armatures', armatures: [{ id: 'rig', preset: 'humanoid', fit: { bounds: { min: [-0.3, 0, -0.1], max: [0.3, 2, 0.1] } } }] }], { expectedRevision: scene.revision });assert.equal(scene.exportRecipe().armatures[0].bones.find(bone => bone.name === 'head').tail[1], 2);});++test('a preset fitted to a flat mesh is refused instead of putting every bone on one point', () => {+ const flatMesh = armature => ({+ format: 'crucible.scene', schemaVersion: 1,+ geometries: [{ id: 'sheet', type: 'plane' }],+ materials: [{ id: 'paint' }],+ armatures: [armature],+ nodes: [{ id: 'mesh', geometry: 'sheet', material: 'paint', rotation: [-0.7071067811865476, 0, 0, 0.7071067811865476] }],+ });+ assert.throws(() => createAgentScene(flatMesh({ id: 'rig', preset: 'humanoid', fit: { node: 'mesh' } })), /humanoid armature needs a fit box with height above zero/);+ assert.throws(() => presetBones('quadruped', { min: [0, 0, 0], max: [1, 1, 0] }), /width and height|depth/);+ assert.equal(presetBones('humanoid', { min: [0, 0, 0], max: [0, 2, 0] }).length > 0, true, 'a humanoid only scales with height');+});diff --git a/tests/sculpt.test.js b/tests/sculpt.test.jsindex f1cbad9a..90f2f52a 100644--- a/tests/sculpt.test.js+++ b/tests/sculpt.test.js@@ -114,3 +114,10 @@ test('UV seam duplication does not change area-weighted sculpt normals', () => {assert.deepEqual(ordinary.normals.subarray(0, 3), seamed.normals.subarray(0, 3));assert.deepEqual(ordinary.normals.subarray(0, 3), seamed.normals.subarray(12, 15));});++test('a stroke field the sculpt does not know, or a direction on a stroke that ignores it, is refused', () => {+ const stroke = { type: 'inflate', center: [0, 0, 0], radius: 2, strength: 0.1 };+ assert.throws(() => sculptGeometry(plane(), [{ ...stroke, radious: 3 }]), /unsupported field "radious"/);+ assert.throws(() => sculptGeometry(plane(), [{ ...stroke, direction: [0, 0, 1] }]), /Only a displace stroke takes direction.*inflate/);+ assert.throws(() => sculptGeometry(plane(), [{ ...stroke, type: 'smooth', direction: [0, 0, 1] }]), /smooth stroke/);+});diff --git a/tests/settle.test.js b/tests/settle.test.jsindex 4af98736..3001714b 100644--- a/tests/settle.test.js+++ b/tests/settle.test.js@@ -110,3 +110,13 @@ test('bad settings fail with the field and what to pass', () => {assert.throws(() => normalizeSettle({ colliders: BIN_WALLS, area: { min: [0, 0], max: [1, 1] }, count: 3, bounce: 1 }), /settle\.bounce/);assert.throws(() => normalizeSettle({ colliders: BIN_WALLS, instances: [{ translation: [0, 1, 0], size: [1, 1, 1] }], count: 3 }), /settle\.count/);});++test('a floor above ten kilometres receives props like the same floor at the origin', async () => {+ const area = { min: [-1, -1], max: [1, 1] };+ const floorAt = height => ({ shape: 'box', translation: [0, height, 0], halfExtents: [3, 0.1, 3] });+ const onGround = await settleProps({ colliders: [floorAt(0)], area, count: 5, seed: 4 });+ const high = await settleProps({ colliders: [floorAt(20000)], area, count: 5, seed: 4 });+ assert.equal(high.report.skipped.noGround, 0, 'the ground under a high floor is found');+ assert.equal(high.instances.length, onGround.instances.length);+ for (const instance of high.instances) assert.ok(Math.abs(instance.translation[1] - 20000.1) < 0.5, `rests on the high floor, got ${instance.translation[1]}`);+});