3D engine that AI agents drive
Settle scattered props with rigid bodies and keep them as static parts
Nguyen Xuan An018ae9430f1d
diff --git a/changes/980.md b/changes/980.mdnew file mode 100644index 00000000..89f873d8--- /dev/null+++ b/changes/980.md@@ -0,0 +1 @@+- The new `settle` step (`addons/settle`, and the `settle` operation of `scene_apply`) drops scattered boxes and balls onto scene colliders as rigid bodies and keeps where they rest as static parts, with density, spacing, size and rotation variation, max slope, no initial overlap and stacking on earlier settles, the same seed giving the same transforms (#980)diff --git a/docs/clutter.md b/docs/clutter.mdindex 54d92f7d..dd2d73b0 100644--- a/docs/clutter.md+++ b/docs/clutter.md@@ -75,6 +75,10 @@ On an 80 × 100 m area, eye 1.3 m above the ground, built in Node:`riverbed` and `scree` are dense by design. Lower `pebbles` or `cullDistance` for phones.+## Settling stones into a pile++Clutter tiles are meshes, so they stay where they were scattered. To drop stones and let them lie against a wall or each other, use the settle step ([Settling props](physics.md#settling-props)): list the stone poses as `instances`, or let it scatter boxes and balls over an area. It returns resting transforms to draw as static parts.+## Limits- Stones are untextured. Up close they read as smooth, mottled stones, not as scanned rock.diff --git a/docs/physics.md b/docs/physics.mdindex b8d99647..8025522e 100644--- a/docs/physics.md+++ b/docs/physics.md@@ -561,6 +561,55 @@ renderer.render(frame);- The culling bounds and the shadow map follow the new positions.- Per vertex a cloth steps on welded particles, so copy each vertex from its particle (`weldVertices(...).particleOfVertex`) and recompute normals (`recomputeNormals`) before the call.+## Settling props++`@codepawlhq/67js/addons/settle` drops props as rigid bodies onto colliders, runs Rapier at 60 Hz for a bounded time and returns the resting transforms, so rubble, crates and pebbles lie against each other instead of hovering where they were placed. The caller keeps the result as static parts. Same seed and inputs give the same transforms byte for byte (they are rounded to 1e-5).++```js+import { loadPhysicsEngine } from '@codepawlhq/67js/addons/physics';+import { settleInstances } from '@codepawlhq/67js/addons/settle';++await loadPhysicsEngine();+const { instances, report } = settleInstances({+ colliders: [+ { shape: 'box', translation: [0, -0.1, 0], halfExtents: [4, 0.1, 4] },+ { shape: 'box', translation: [0, 1, -2], halfExtents: [4, 1, 0.2] },+ ],+ area: { min: [-2, -1.7], max: [2, -0.5] }, count: 80, size: [0.1, 0.25], seed: 5,+});+// instances: [{ translation, rotation (quaternion), size }]; report: { requested, placed, skipped, fellOff, unsettled, duration }+```++| Setting | Default | Meaning |+| --- | --- | --- |+| `colliders` | required | Up to 64 `box` ({ translation, rotation, halfExtents }) or `ball` ({ translation, radius }) shapes to land on. List earlier settled props here to stack on them. |+| `shape` | `box` | Prop shape, `box` or `ball`. |+| `area`, `count` or `density` | required | Where to scatter, and how many (256 at most) or how many per square metre. |+| `instances` | none | Instead of `area`, `count`, `density` and `size`: your own start poses `[{ translation, rotation, size }]` (size is three edge lengths for a box, a diameter for a ball). |+| `size` | `[0.1, 0.25]` | Smallest and largest edge (box) or diameter (ball), in metres. |+| `aspect` | 0.3 | Per-axis edge variation of a box, 0 to 1. |+| `rotation` | 1 | Start tumble, 0 (yaw only) to 1 (any orientation). |+| `spacing` | 0.01 | Minimum gap between props and colliders at the start, so no prop starts overlapping. |+| `maxSlope` | 60 | Props are not placed where the ground below is steeper than this, in degrees. |+| `duration` | 3 | Seconds simulated, 0.5 to 6. |+| `friction`, `restitution` | 0.6, 0.1 | Contact material of props and colliders. |++A prop that falls off the world is left out (`report.fellOff`); one still moving at the end is kept (`report.unsettled`; raise `duration`). `report.skipped` counts rejected placement attempts, not props. Props use continuous collision detection, so thin ones do not tunnel through a floor.++In a recipe the same step is the `settle` operation of `scene_apply` (see [Recipe settle](#recipe-settle)). Clutter tiles (`addons/clutter`) are streamed meshes, not instance lists, so to settle stones list the poses you want as `instances`.++### Recipe settle++```json+{ "type": "settle", "settle": {+ "id": "rubble", "geometry": "block", "material": ["stone", "rust"],+ "colliders": ["floor", "wall"],+ "area": { "min": [-2, -1.7], "max": [2, -0.5] }, "count": 80, "size": [0.1, 0.25], "seed": 5+} }+```++`colliders` are node IDs. A node needs a `box` or `sphere` geometry (a sphere must have equal scale on all axes); a group node stands for its mesh children. `geometry` is a recipe `box` or `sphere` geometry and decides the prop shape; `material` is an ID or a list of up to 8 that props pick from by seed. The operation adds a group node `rubble` and one static child per resting prop, `rubble-0`, `rubble-1` and so on, with no physics section. List `rubble` in a later settle's `colliders` to stack on it. Settling needs the Rapier peer loaded like recipe physics does, and `scene_capabilities` topic `settle` has the field list. Remove the group and its children before settling again under the same ID.+## Force fieldsOne list of up to 8 fields, `fields` on the `particles` section and on the `cloth` section, accelerates every particle, hair strand and cloth particle through the same evaluation (`src/force-fields.js`, `evaluateForceFields`). Each field has a `type`:diff --git a/package.json b/package.jsonindex 8add6fa2..d509a6fe 100644--- a/package.json+++ b/package.json@@ -82,6 +82,7 @@"./addons/shrinkwrap": "./build/shrinkwrap.js","./addons/surface-attachment": "./build/surface-attachment.js","./addons/physics": "./build/physics.js",+ "./addons/settle": "./build/settle.js","./addons/spume": "./build/spume.js","./addons/retarget": "./build/retarget.js","./addons/crowd-skinning": "./build/crowd-skinning.js",diff --git a/scripts/mcp-server.mjs b/scripts/mcp-server.mjsindex 09fc0923..c293e936 100644--- a/scripts/mcp-server.mjs+++ b/scripts/mcp-server.mjs@@ -734,6 +734,7 @@ const otherOperations = [z.strictObject({ type: z.literal('set-camera'), ...cameraFields }),z.strictObject({ type: z.literal('set-motion'), motion: recipeMotionReference.nullable() }),z.strictObject({ type: z.literal('bake-motion'), nodes: z.array(identifier).min(1).max(32), start: nonnegative.optional(), end: nonnegative.optional(), step: positive.optional(), tolerance: z.record(z.string(), z.number()).optional() }),+ z.strictObject({ type: z.literal('settle'), settle: z.record(z.string(), z.unknown()).describe('Drop props onto nodes and keep them as static parts; fields in scene_capabilities topic settle.') }),z.strictObject({ type: z.literal('set-armatures'), armatures: armaturesReference.nullable() }),z.strictObject({ type: z.literal('set-physics'), physics: z.record(z.string(), z.unknown()).nullable().describe('Same object as recipe.physics in scene_create.') }),z.strictObject({ type: z.literal('set-cloth'), cloth: z.record(z.string(), z.unknown()).nullable() }),diff --git a/src/agent-apply-report.js b/src/agent-apply-report.jsindex afd67c14..225b56bd 100644--- a/src/agent-apply-report.js+++ b/src/agent-apply-report.js@@ -108,6 +108,9 @@ function describeOperation(working, operation, maxText) {else working[name] = structuredClone(next);return { changed: operation[name] === null ? `cleared ${name}` : `set ${name}` };}+ if (type === 'settle') {+ return { changed: `settled props under ${operation.settle?.id}; scene_inspect lists them` };+ }if (type === 'bake-motion') {return { changed: `baked ${shortList(operation.nodes ?? [], maxText)} to keys` };}diff --git a/src/agent-scene-capabilities.js b/src/agent-scene-capabilities.jsindex 940524bd..6a320ef3 100644--- a/src/agent-scene-capabilities.js+++ b/src/agent-scene-capabilities.js@@ -227,7 +227,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({operations: Object.freeze(['set-node', 'set-material', 'set-camera', 'add-node', 'remove-node','add-geometry', 'remove-geometry', 'add-material', 'remove-material',- 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'set-timeline', 'set-particles', 'set-bake', 'set-post-passes', 'set-game', 'edit-mesh', 'set-mesh-stack', 'bake-motion',+ 'set-environment', 'set-effects', 'set-shadow', 'set-motion', 'set-armatures', 'set-physics', 'set-cloth', 'set-timeline', 'set-particles', 'set-bake', 'set-post-passes', 'set-game', 'edit-mesh', 'set-mesh-stack', 'bake-motion', 'settle',]),materialTags: Object.freeze(['surface', 'unlit', 'liquid', 'foam', 'foliage', 'grass', 'water']),// A flat water sheet; the largest sets the level. A bed d metres down keeps exp(-absorption * d) per channel (RGB per metre).@@ -343,6 +343,7 @@ export const AGENT_SCENE_CAPABILITIES = Object.freeze({}),motionModifiers: 'Track extrapolation constant|linear; modifiers [{type: cycles|stepped|noise|generator|limits|envelope, ...}], 8 at most; cycles and stepped remap time first.',motionLimits: Object.freeze({ maxTracks: 128, maxKeyframesPerTrack: 64, maxKeyframes: 2048, maxDuration: 30 }),+ settle: 'scene_apply settle { settle: { id, geometry (box or sphere), material (ID or up to 8), colliders [node IDs to land on: boxes and spheres; a group node stands for its children, so a later settle stacks on an earlier one], area { min [x, z], max [x, z] }, count (256 at most) or density (per m2), size [min, max] m (0.1-0.25), aspect 0-1 (0.3, box edge variation), rotation 0-1 (1, tumble; 0 is yaw only), spacing m (0.01), maxSlope deg (60), seed, duration s (3, 6 at most), friction, restitution } } or instances [{ translation, rotation, size }] in place of area/count/density/size: drops the props as rigid bodies (Rapier) onto the colliders at 60 Hz and writes the resting transforms as static child nodes id-0, id-1... of a group node id. Same seed, same transforms. Props that start overlapping or on ground steeper than maxSlope are skipped; ones that fall off the world are left out. Needs the physics peer.',motionBake: 'scene_apply bake-motion { nodes (32 at most), start 0, end (motion or physics duration), step 1/30 (512 samples), tolerance { position m, angle deg, scale } }: samples tracks, IK, constraints, drivers and physics into LINEAR tracks and removes those sources (an IK solver or the physics world only when all its nodes are baked). tolerance drops keys within it; without it a track keeps every sample, 64 keys at most. Procedural scenes only.',});diff --git a/src/agent-scene-modules.js b/src/agent-scene-modules.jsindex a2e9971a..be7528a9 100644--- a/src/agent-scene-modules.js+++ b/src/agent-scene-modules.js@@ -9,6 +9,7 @@ const MODULE_LOADERS = {text: () => import('./text-geometry.js'),motion: () => import('./agent-motion.js'),motionBake: () => import('./agent-motion-bake.js'),+ settle: () => import('./agent-settle.js'),drive: () => import('./agent-drive.js'),physics: () => import('./agent-physics.js'),cloth: () => import('./agent-cloth.js'),@@ -54,6 +55,7 @@ const MODULE_MARKERS = {text: ['"type":"text"'],motion: ['"motion":{', '"bake-motion"'],motionBake: ['"bake-motion"'],+ settle: ['"type":"settle"'],drive: ['"drive":{'],physics: ['"physics":{'],cloth: ['"cloth":{'],@@ -101,9 +103,10 @@ export function needsMeshBooleans(value) {return JSON.stringify(value ?? null).includes('"op":"boolean"');}-/** True when a recipe or an operation list carries a physics section, so the host loads the solver first. */+/** True when a recipe or an operation list carries a physics section or a settle operation, so the host loads the solver first. */export function needsPhysics(value) {- return JSON.stringify(value ?? null).includes('"physics":{');+ const text = JSON.stringify(value ?? null);+ return text.includes('"physics":{') || text.includes('"type":"settle"');}/** Names of the on-demand modules a recipe, or a list of edit operations, needs. */diff --git a/src/agent-scene.js b/src/agent-scene.jsindex 0eee6301..83752d9e 100644--- a/src/agent-scene.js+++ b/src/agent-scene.js@@ -1909,6 +1909,10 @@ export function createAgentScene(input, inputLimits = {}, options = {}) {agentSceneModule('motionBake').bakeMotion(candidate, operation, motionBakeSource(state));continue;}+ if (operation.type === 'settle') {+ agentSceneModule('settle').applySettle(candidate, operation);+ continue;+ }if (operation.type === 'edit-mesh') {knownKeys(operation, ['type', 'geometry', 'edits', 'replace'], 'operation');const target = meshGeometryTarget(candidate, operation, type => `Add a mesh geometry with base: { type: '${type}', ... } to edit it.`);diff --git a/src/agent-settle.js b/src/agent-settle.jsnew file mode 100644index 00000000..a8883c9f--- /dev/null+++ b/src/agent-settle.js@@ -0,0 +1,111 @@+import { mat4, quat, vec3 } from 'gl-matrix';+import { invalidField } from './field-error.js';+import { SETTLE_LIMITS, settleInstances } from './settle.js';+import { createRandom } from './vegetation-geometry.js';++export { loadPhysicsEngine, physicsEngineLoaded } from './physics.js';++// The settle operation: scattered props fall onto recipe nodes as rigid bodies, then stay where they came to rest as+// ordinary static parts under one group node. A later settle can list that group as a collider and stack on it.++const OPERATION_FIELDS = ['type', 'settle'];+const MAX_MATERIALS = 8;+const GEOMETRY_SHAPES = { box: 'box', sphere: 'ball' };++function requireId(value, path) {+ if (typeof value !== 'string' || !value.trim() || value.length > 100) {+ throw invalidField(path, value, 'an ID of 1 to 100 characters, such as "rubble"', TypeError);+ }+ return value;+}++function worldMatrixOf(node, nodesById) {+ const local = mat4.fromRotationTranslationScale(mat4.create(), node.rotation ?? [0, 0, 0, 1], node.translation ?? [0, 0, 0], node.scale ?? [1, 1, 1]);+ if (node.parent === null || node.parent === undefined) return local;+ return mat4.multiply(local, worldMatrixOf(nodesById.get(node.parent), nodesById), local);+}++function colliderFromNode(node, geometry, nodesById) {+ const matrix = worldMatrixOf(node, nodesById);+ const scale = mat4.getScaling(vec3.create(), matrix);+ const translation = Array.from(mat4.getTranslation(vec3.create(), matrix));+ const rotation = Array.from(mat4.getRotation(quat.create(), matrix));+ if (geometry.type === 'box') return { shape: 'box', translation, rotation, halfExtents: Array.from(scale, edge => edge / 2) };+ if (Math.max(...scale) - Math.min(...scale) > 1e-4 * Math.max(...scale)) {+ throw invalidField(`settle.colliders (${node.id})`, Array.from(scale), 'a sphere with equal scale on all axes, or a box; a stretched sphere is not a ball');+ }+ return { shape: 'ball', translation, rotation: [0, 0, 0, 1], radius: scale[0] };+}++/** The colliders a node list stands for: a mesh node is one, a group node is its mesh descendants (earlier settles). */+function collidersFor(recipe, nodeIds) {+ const nodesById = new Map(recipe.nodes.map(node => [node.id, node]));+ const geometriesById = new Map(recipe.geometries.map(geometry => [geometry.id, geometry]));+ const colliders = [];+ const visit = (node, path) => {+ if (node.geometry !== undefined) {+ const geometry = geometriesById.get(node.geometry);+ if (!GEOMETRY_SHAPES[geometry?.type]) {+ throw invalidField(path, node.id, 'a node whose geometry is a box or a sphere, since those are the shapes a settle can land on; use a box for a wall or floor');+ }+ colliders.push(colliderFromNode(node, geometry, nodesById));+ }+ for (const child of recipe.nodes.filter(candidate => candidate.parent === node.id)) visit(child, path);+ };+ nodeIds.forEach((nodeId, index) => {+ const node = nodesById.get(nodeId);+ if (!node) throw invalidField(`settle.colliders[${index}]`, nodeId, `the ID of a recipe node, one of ${[...nodesById.keys()].slice(0, 5).join(', ') || 'none yet'}`);+ visit(node, `settle.colliders[${index}]`);+ });+ if (colliders.length > SETTLE_LIMITS.maxColliders) {+ throw invalidField('settle.colliders', `${colliders.length} shapes`, `nodes that stand for at most ${SETTLE_LIMITS.maxColliders} boxes and spheres; list fewer nodes, or one wall as a single box`);+ }+ return colliders;+}++function materialsFor(recipe, material) {+ const list = Array.isArray(material) ? material : [material];+ if (!list.length || list.length > MAX_MATERIALS) {+ throw invalidField('settle.material', material, `a material ID or a list of 1 to ${MAX_MATERIALS} IDs, such as "stone"`, TypeError);+ }+ return list.map(id => {+ if (!recipe.materials.some(candidate => candidate.id === id)) {+ throw invalidField('settle.material', id, `the ID of a recipe material, one of ${recipe.materials.slice(0, 5).map(candidate => candidate.id).join(', ') || 'none yet'}`);+ }+ return id;+ });+}++/**+ * Apply one settle operation to a candidate recipe: `{ type: 'settle', settle: { id, geometry, material, colliders: [node IDs],+ * ...settle settings } }`. Adds a group node `id` and one static child `id-<n>` per prop that came to rest. The solver must+ * be loaded (await loadPhysicsEngine()).+ */+export function applySettle(recipe, operation) {+ for (const key of Object.keys(operation)) {+ if (!OPERATION_FIELDS.includes(key)) throw invalidField(key, operation[key], `no such field; put the settle fields inside "settle"`, TypeError);+ }+ const { settle } = operation;+ if (!settle || typeof settle !== 'object' || Array.isArray(settle)) throw invalidField('settle', settle, 'an object, such as { "id": "rubble", "geometry": "block", "material": "stone", "colliders": ["floor"], "area": { "min": [-1, -1], "max": [1, 1] }, "count": 40 }', TypeError);+ const { id, geometry: geometryId, material, colliders: colliderNodeIds, ...settings } = settle;+ requireId(id, 'settle.id');+ const geometry = recipe.geometries.find(candidate => candidate.id === geometryId);+ if (!geometry) throw invalidField('settle.geometry', geometryId, `the ID of a recipe geometry, one of ${recipe.geometries.slice(0, 5).map(candidate => candidate.id).join(', ') || 'none yet'}`);+ const shape = GEOMETRY_SHAPES[geometry.type];+ if (!shape) throw invalidField('settle.geometry', geometryId, 'a box or sphere geometry, such as { "id": "block", "type": "box" }; a settle prop is a box or a ball');+ if (recipe.nodes.some(node => node.id === id || node.id.startsWith(`${id}-`))) {+ throw invalidField('settle.id', id, 'an ID no node or node prefix uses yet; remove the earlier group first, or pick a new ID such as "rubble-2"');+ }+ if (!Array.isArray(colliderNodeIds)) throw invalidField('settle.colliders', colliderNodeIds, 'a list of node IDs to land on, such as ["floor", "wall"]', TypeError);+ const materials = materialsFor(recipe, material);+ const { instances } = settleInstances({ ...settings, shape, colliders: collidersFor(recipe, colliderNodeIds) });+ const pickMaterial = createRandom((settings.seed ?? 1) + 7919);+ recipe.nodes.push({ id, parent: null, translation: [0, 0, 0], rotation: [0, 0, 0, 1], scale: [1, 1, 1] });+ instances.forEach((instance, index) => {+ const scale = shape === 'ball' ? instance.size.map(edge => edge / 2) : instance.size;+ recipe.nodes.push({+ id: `${id}-${index}`, parent: id, geometry: geometryId, material: materials[Math.floor(pickMaterial() * materials.length)],+ translation: instance.translation, rotation: instance.rotation, scale,+ });+ });+}diff --git a/src/settle.js b/src/settle.jsnew file mode 100644index 00000000..b26bffcd--- /dev/null+++ b/src/settle.js@@ -0,0 +1,313 @@+// Settle: drop props onto scene colliders as rigid bodies, run Rapier at a fixed step for a bounded time and return the+// resting transforms, so scattered rubble, crates and pebbles lie against each other instead of hovering where they were+// placed. The caller writes the result back as static parts (the `settle` scene operation does). Placement and the solver+// are both deterministic: the same seed and inputs give the same transforms byte for byte.++import { quat, vec3 } from 'gl-matrix';+import { invalidField } from './field-error.js';+import { bakePhysicsScene, loadPhysicsEngine } from './physics.js';+import { createRandom } from './vegetation-geometry.js';++export const SETTLE_LIMITS = Object.freeze({ maxProps: 256, maxColliders: 64, maxDuration: 6, maxAttemptsPerProp: 60 });+const FRAMES_PER_SECOND = 60;+const PLACEMENT_ATTEMPTS_BEFORE_RAISING = 20;+const COLUMN_GROWTH = 1.15;+const PACKING_FRACTION = 0.2;+const MAX_COLUMN_HEIGHT = 40;+const ROUNDING = 1e5;+const SHAPES = ['box', 'ball'];++const SETTINGS_FIELDS = ['colliders', 'shape', 'instances', 'area', 'count', 'density', 'size', 'aspect', 'rotation', 'spacing', 'maxSlope', 'seed', 'duration', 'friction', 'restitution'];+const COLLIDER_FIELDS = ['shape', 'translation', 'rotation', 'halfExtents', 'radius'];+const INSTANCE_FIELDS = ['translation', 'rotation', 'size'];++function finiteNumber(value, path, minimum, maximum) {+ if (typeof value !== 'number' || !Number.isFinite(value) || value < minimum || value > maximum) {+ throw invalidField(path, value, `a number from ${minimum} to ${maximum}, such as ${Math.min(Math.max(1, minimum), maximum)}`);+ }+ return value;+}++function numberList(value, size, path) {+ if (!Array.isArray(value) || value.length !== size || !value.every(Number.isFinite)) {+ throw invalidField(path, value, `an array of ${size} finite numbers, such as [${Array(size).fill(0).join(', ')}]`, TypeError);+ }+ return value;+}++function knownKeys(value, fields, path) {+ if (!value || typeof value !== 'object' || Array.isArray(value)) throw invalidField(path, value, 'an object, such as {}', TypeError);+ for (const key of Object.keys(value)) {+ if (!fields.includes(key)) throw invalidField(`${path}.${key}`, value[key], `no such field; use one of ${fields.join(', ')}`, TypeError);+ }+}++function normalizeCollider(input, path) {+ knownKeys(input, COLLIDER_FIELDS, path);+ const shape = input.shape === 'cuboid' ? 'box' : input.shape;+ if (!SHAPES.includes(shape)) throw invalidField(`${path}.shape`, input.shape, `one of ${SHAPES.join(', ')}`);+ const collider = { shape, translation: numberList(input.translation ?? [0, 0, 0], 3, `${path}.translation`) };+ if (shape === 'box') {+ const halfExtents = numberList(input.halfExtents, 3, `${path}.halfExtents`);+ if (halfExtents.some(extent => !(extent > 0))) throw invalidField(`${path}.halfExtents`, halfExtents, 'three positive half sizes, such as [1, 0.1, 1]');+ const rotation = numberList(input.rotation ?? [0, 0, 0, 1], 4, `${path}.rotation`);+ if (!Math.hypot(...rotation)) throw invalidField(`${path}.rotation`, rotation, 'a nonzero quaternion, such as [0, 0, 0, 1]');+ return { ...collider, halfExtents, rotation: quat.normalize(quat.create(), rotation) };+ }+ return { ...collider, radius: finiteNumber(input.radius, `${path}.radius`, 1e-4, 1e6), rotation: quat.create() };+}++function normalizeInstance(input, shape, path) {+ knownKeys(input, INSTANCE_FIELDS, path);+ const translation = numberList(input.translation, 3, `${path}.translation`);+ const rotation = quat.normalize(quat.create(), numberList(input.rotation ?? [0, 0, 0, 1], 4, `${path}.rotation`));+ const size = shape === 'box' ? numberList(input.size, 3, `${path}.size`) : [input.size, input.size, input.size];+ if (!size.every(edge => Number.isFinite(edge) && edge >= 0.001 && edge <= 100)) {+ throw invalidField(`${path}.size`, input.size, shape === 'box' ? 'three edge lengths from 0.001 to 100 metres, such as [0.2, 0.1, 0.3]' : 'a diameter from 0.001 to 100 metres, such as 0.2');+ }+ return { translation, rotation, size };+}++/** Validate settings at the public boundary; returns the plain form `settleInstances` runs. */+export function normalizeSettle(input) {+ knownKeys(input, SETTINGS_FIELDS, 'settle');+ const shape = input.shape ?? 'box';+ if (!SHAPES.includes(shape)) throw invalidField('settle.shape', shape, `one of ${SHAPES.join(', ')}`);+ if (!Array.isArray(input.colliders) || input.colliders.length > SETTLE_LIMITS.maxColliders) {+ throw invalidField('settle.colliders', Array.isArray(input.colliders) ? `${input.colliders.length} entries` : input.colliders, `a list of at most ${SETTLE_LIMITS.maxColliders} colliders, such as [{ "shape": "box", "halfExtents": [2, 0.1, 2] }]`, TypeError);+ }+ const settings = {+ shape,+ colliders: input.colliders.map((collider, index) => normalizeCollider(collider, `settle.colliders[${index}]`)),+ seed: Math.trunc(finiteNumber(input.seed ?? 1, 'settle.seed', 0, 2 ** 32 - 1)),+ duration: finiteNumber(input.duration ?? 3, 'settle.duration', 0.5, SETTLE_LIMITS.maxDuration),+ friction: finiteNumber(input.friction ?? 0.6, 'settle.friction', 0, 10),+ restitution: finiteNumber(input.restitution ?? 0.1, 'settle.restitution', 0, 1),+ spacing: finiteNumber(input.spacing ?? 0.01, 'settle.spacing', 0, 10),+ maxSlope: finiteNumber(input.maxSlope ?? 60, 'settle.maxSlope', 0, 90),+ aspect: finiteNumber(input.aspect ?? 0.3, 'settle.aspect', 0, 1),+ rotation: finiteNumber(input.rotation ?? 1, 'settle.rotation', 0, 1),+ };+ if (!settings.colliders.length) throw invalidField('settle.colliders', [], 'at least one collider to land on, such as [{ "shape": "box", "halfExtents": [2, 0.1, 2] }]');+ if (input.instances !== undefined) {+ if (!Array.isArray(input.instances) || !input.instances.length || input.instances.length > SETTLE_LIMITS.maxProps) {+ throw invalidField('settle.instances', Array.isArray(input.instances) ? `${input.instances.length} entries` : input.instances, `a list of 1 to ${SETTLE_LIMITS.maxProps} instances, such as [{ "translation": [0, 1, 0], "size": [0.2, 0.2, 0.2] }]`, TypeError);+ }+ for (const field of ['area', 'count', 'density', 'size']) {+ if (input[field] !== undefined) throw invalidField(`settle.${field}`, input[field], 'a field left out when instances lists the props', TypeError);+ }+ return { ...settings, instances: input.instances.map((instance, index) => normalizeInstance(instance, shape, `settle.instances[${index}]`)) };+ }+ const { area } = input;+ if (!area) throw invalidField('settle.area', area, 'an area { "min": [x, z], "max": [x, z] } to scatter over, or a list of instances', TypeError);+ knownKeys(area, ['min', 'max'], 'settle.area');+ const min = numberList(area.min, 2, 'settle.area.min');+ const max = numberList(area.max, 2, 'settle.area.max');+ if (max[0] <= min[0] || max[1] <= min[1]) throw invalidField('settle.area', area, 'min below max on both axes, such as { "min": [-1, -1], "max": [1, 1] }');+ const size = numberList(input.size ?? [0.1, 0.25], 2, 'settle.size');+ if (!(size[0] >= 0.001 && size[1] >= size[0] && size[1] <= 100)) throw invalidField('settle.size', size, 'a [smallest, largest] size from 0.001 to 100 metres, such as [0.1, 0.25]');+ if ((input.count === undefined) === (input.density === undefined)) {+ throw invalidField('settle.count', input.count, 'exactly one of count (props) or density (props per square metre)', TypeError);+ }+ const areaSize = (max[0] - min[0]) * (max[1] - min[1]);+ const count = input.count !== undefined+ ? Math.trunc(finiteNumber(input.count, 'settle.count', 1, SETTLE_LIMITS.maxProps))+ : Math.min(SETTLE_LIMITS.maxProps, Math.max(1, Math.round(finiteNumber(input.density, 'settle.density', 1e-6, 1e6) * areaSize)));+ return { ...settings, area: { min, max }, size, count };+}++const upVector = vec3.fromValues(0, 1, 0);++function toLocal(collider, point) {+ const offset = vec3.sub(vec3.create(), point, collider.translation);+ return vec3.transformQuat(offset, offset, quat.invert(quat.create(), collider.rotation));+}++/** 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) {+ if (collider.shape === 'ball') {+ const horizontal = Math.hypot(x - collider.translation[0], z - collider.translation[2]);+ if (horizontal >= collider.radius) return null;+ const height = collider.translation[1] + Math.sqrt(collider.radius ** 2 - horizontal ** 2);+ const normal = vec3.normalize(vec3.create(), [x - collider.translation[0], height - collider.translation[1], z - collider.translation[2]]);+ return { height, normal };+ }+ const inverse = quat.invert(quat.create(), collider.rotation);+ const origin = toLocal(collider, [x, 1e4, z]);+ const direction = vec3.transformQuat(vec3.create(), [0, -1, 0], inverse);+ let entry = -Infinity;+ let exit = Infinity;+ let entryAxis = -1;+ let entrySign = 1;+ for (let axis = 0; axis < 3; axis++) {+ const half = collider.halfExtents[axis];+ if (Math.abs(direction[axis]) < 1e-12) {+ if (Math.abs(origin[axis]) > half) return null;+ continue;+ }+ const near = (-half - origin[axis]) / direction[axis];+ const far = (half - origin[axis]) / direction[axis];+ const nearT = Math.min(near, far);+ if (nearT > entry) {+ entry = nearT;+ entryAxis = axis;+ entrySign = near < far ? -1 : 1;+ }+ exit = Math.min(exit, Math.max(near, far));+ }+ if (entry > exit || exit < 0 || entryAxis < 0) return null;+ const normalLocal = [0, 0, 0];+ normalLocal[entryAxis] = entrySign;+ const normal = vec3.transformQuat(vec3.create(), normalLocal, collider.rotation);+ return { height: 1e4 - entry, normal };+}++function groundUnder(colliders, x, z) {+ let best = null;+ for (const collider of colliders) {+ const surface = surfaceUnder(collider, x, z);+ if (surface && (!best || surface.height > best.height)) best = surface;+ }+ return best;+}++function clearanceFrom(collider, point) {+ if (collider.shape === 'ball') return vec3.distance(point, collider.translation) - collider.radius;+ const local = toLocal(collider, point);+ const outside = local.map((component, axis) => Math.max(Math.abs(component) - collider.halfExtents[axis], 0));+ return Math.hypot(...outside);+}++function boundingRadius(shape, size) {+ return shape === 'ball' ? size[0] / 2 : Math.hypot(...size) / 2;+}++function tumbleRotation(random, tumble) {+ const yaw = random() * 360;+ const pitch = (random() * 2 - 1) * 90 * tumble;+ const roll = (random() * 2 - 1) * 90 * tumble;+ return quat.fromEuler(quat.create(), pitch, yaw, roll);+}++/** Generates candidate props over the area: spaced apart, off steep ground and clear of every collider. */+function scatterCandidates(settings, skipped) {+ const random = createRandom(settings.seed);+ const { area, colliders, shape, size: sizeRange, aspect, spacing, maxSlope } = settings;+ const meanEdge = (sizeRange[0] + sizeRange[1]) / 2;+ 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 candidates = [];+ const flatSlope = Math.cos(maxSlope * Math.PI / 180);+ for (let index = 0; index < settings.count; index++) {+ for (let attempt = 0; attempt < SETTLE_LIMITS.maxAttemptsPerProp; attempt++) {+ if (attempt > 0 && attempt % PLACEMENT_ATTEMPTS_BEFORE_RAISING === 0) columnHeight = Math.min(MAX_COLUMN_HEIGHT, columnHeight * COLUMN_GROWTH);+ // Every attempt draws the same number of rolls, so a rejection never shifts the later props.+ const rolls = Array.from({ length: 10 }, random);+ const base = sizeRange[0] + (sizeRange[1] - sizeRange[0]) * rolls[0];+ const size = shape === 'ball' ? [base, base, base] : [0, 1, 2].map(axis => base * (1 + aspect * (rolls[1 + axis] * 2 - 1) * 0.5));+ 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);+ if (!ground) {+ skipped.noGround++;+ continue;+ }+ if (vec3.dot(ground.normal, upVector) < flatSlope) {+ skipped.tooSteep++;+ continue;+ }+ const translation = [x, ground.height + radius + spacing + columnHeight * rolls[6], z];+ if (colliders.some(collider => clearanceFrom(collider, translation) < radius + spacing)) {+ skipped.overlap++;+ continue;+ }+ if (candidates.some(other => vec3.distance(other.translation, translation) < other.radius + radius + spacing)) {+ skipped.overlap++;+ continue;+ }+ const rotation = tumbleRotation(createRandom(Math.floor(rolls[7] * 2 ** 32)), settings.rotation);+ candidates.push({ translation, rotation, size, radius });+ break;+ }+ }+ return candidates;+}++/** Listed props start where they are given; the ones that start inside a collider or each other are skipped. */+function listedCandidates(settings, skipped) {+ const candidates = [];+ for (const instance of settings.instances) {+ const radius = boundingRadius(settings.shape, instance.size);+ const inside = settings.colliders.some(collider => clearanceFrom(collider, instance.translation) < radius)+ || candidates.some(other => vec3.distance(other.translation, instance.translation) < other.radius + radius);+ if (inside) {+ skipped.overlap++;+ continue;+ }+ candidates.push({ ...instance, radius });+ }+ return candidates;+}++function rounded(values) {+ return Array.from(values, value => Math.round(value * ROUNDING) / ROUNDING);+}++function physicsDefinition(settings, props) {+ const bodies = [];+ const colliders = [];+ settings.colliders.forEach((collider, index) => {+ bodies.push({ name: `ground-${index}`, type: 'fixed', translation: collider.translation, rotation: Array.from(collider.rotation) });+ colliders.push(collider.shape === 'ball'+ ? { name: `ground-${index}`, body: `ground-${index}`, shape: 'ball', radius: collider.radius, friction: settings.friction }+ : { name: `ground-${index}`, body: `ground-${index}`, shape: 'cuboid', halfExtents: collider.halfExtents, friction: settings.friction });+ });+ props.forEach((prop, index) => {+ bodies.push({ name: `prop-${index}`, type: 'dynamic', translation: prop.translation, rotation: Array.from(prop.rotation), ccd: true });+ colliders.push(settings.shape === 'ball'+ ? { name: `prop-${index}`, body: `prop-${index}`, shape: 'ball', radius: prop.size[0] / 2, friction: settings.friction, restitution: settings.restitution }+ : { name: `prop-${index}`, body: `prop-${index}`, shape: 'cuboid', halfExtents: prop.size.map(edge => edge / 2), friction: settings.friction, restitution: settings.restitution });+ });+ return { bodies, colliders };+}++/**+ * Drops props onto the colliders and returns where they come to rest. The solver must be loaded first+ * (await `loadPhysicsEngine()`, or call `settleProps`). Settings are as in `normalizeSettle`.+ * Returns `{ instances: [{ translation, rotation, size }], report }`; `report.skipped` counts rejected placement+ * attempts (no ground below, ground steeper than maxSlope, overlap), not props. A prop that fell off the world is left out and+ * counted in `report.fellOff`, one that still moved at the end is kept and counted in `report.unsettled`.+ */+export function settleInstances(input) {+ const settings = normalizeSettle(input);+ const skipped = { noGround: 0, tooSteep: 0, overlap: 0 };+ const props = settings.instances ? listedCandidates(settings, skipped) : scatterCandidates(settings, skipped);+ const report = { requested: settings.instances?.length ?? settings.count, placed: props.length, skipped, fellOff: 0, unsettled: 0, duration: settings.duration };+ if (!props.length) return { instances: [], report };+ const frameCount = Math.round(settings.duration * FRAMES_PER_SECOND) + 1;+ const scene = bakePhysicsScene(physicsDefinition(settings, props), { frameCount, timestep: 1 / FRAMES_PER_SECOND });+ const finalPose = scene.sample(scene.duration);+ const lowestSurface = Math.min(...settings.colliders.map(collider => (collider.shape === 'ball' ? collider.translation[1] - collider.radius : collider.translation[1] - Math.hypot(...collider.halfExtents))));+ const instances = [];+ props.forEach((prop, index) => {+ const offset = scene.bodyIndex(`prop-${index}`) * 7;+ const translation = finalPose.subarray(offset, offset + 3);+ if (translation[1] < lowestSurface - 1) {+ report.fellOff++;+ return;+ }+ if (scene.restFrames[scene.bodyIndex(`prop-${index}`)] < 0) report.unsettled++;+ instances.push({ translation: rounded(translation), rotation: rounded(finalPose.subarray(offset + 3, offset + 7)), size: rounded(prop.size) });+ });+ scene.dispose();+ report.placed = instances.length;+ return { instances, report };+}++/** Loads the solver if needed, then settles. */+export async function settleProps(input) {+ await loadPhysicsEngine();+ return settleInstances(input);+}diff --git a/tests/agent-settle.test.js b/tests/agent-settle.test.jsnew file mode 100644index 00000000..420a2a7a--- /dev/null+++ b/tests/agent-settle.test.js@@ -0,0 +1,71 @@+import './support/load-agent-scene-modules.mjs';+import test from 'node:test';+import assert from 'node:assert/strict';+import { createAgentScene, loadPhysicsEngine, needsPhysics } from '../src/agent-scene.js';+import { AGENT_SCENE_CAPABILITIES } from '../src/agent-scene-capabilities.js';++await loadPhysicsEngine();++function wallRecipe() {+ return {+ format: '67js.scene', schemaVersion: 1,+ geometries: [{ id: 'slab', type: 'box' }, { id: 'ball', type: 'sphere' }],+ materials: [{ id: 'stone', color: [0.5, 0.5, 0.5] }, { id: 'rust', color: [0.6, 0.3, 0.2] }],+ nodes: [+ { id: 'floor', geometry: 'slab', material: 'stone', translation: [0, -0.1, 0], scale: [8, 0.2, 8] },+ { id: 'wall', geometry: 'slab', material: 'stone', translation: [0, 1, -2], scale: [8, 2, 0.4] },+ ],+ };+}++const rubble = {+ id: 'rubble', geometry: 'slab', material: ['stone', 'rust'], colliders: ['floor', 'wall'],+ area: { min: [-2, -1.7], max: [2, -0.5] }, count: 40, size: [0.1, 0.25], seed: 5,+};++test('a settle operation adds static parts that rest on the floor and against the wall', () => {+ const scene = createAgentScene(wallRecipe());+ scene.apply([{ type: 'settle', settle: rubble }], { expectedRevision: 0 });+ const recipe = scene.exportRecipe();+ const props = recipe.nodes.filter(node => node.parent === 'rubble');+ assert.ok(props.length >= 30, `settled ${props.length} of 40`);+ assert.equal(recipe.nodes.find(node => node.id === 'rubble').geometry, undefined, 'a group node holds the props');+ assert.equal(recipe.physics, undefined, 'the result is static: no physics section is added');+ for (const node of props) {+ assert.ok(node.translation[1] > 0.04, `a prop rests on the floor, got y ${node.translation[1]}`);+ assert.ok(node.translation[2] > -1.8, 'a prop lies in front of the wall');+ }+});++test('a second settle stacks on the first because a group node stands for its children', () => {+ const scene = createAgentScene(wallRecipe());+ scene.apply([{ type: 'settle', settle: rubble }], { expectedRevision: 0 });+ scene.apply([{ type: 'settle', settle: { ...rubble, id: 'more', colliders: ['floor', 'wall', 'rubble'], seed: 6 } }], { expectedRevision: 1 });+ const nodes = scene.inspect({ limit: 200 }).nodes;+ assert.ok(nodes.filter(node => node.id.startsWith('more-')).length > 20);+});++test('the same seed gives the same recipe nodes', () => {+ const first = createAgentScene(wallRecipe());+ const second = createAgentScene(wallRecipe());+ first.apply([{ type: 'settle', settle: rubble }], { expectedRevision: 0 });+ second.apply([{ type: 'settle', settle: rubble }], { expectedRevision: 0 });+ assert.equal(JSON.stringify(first.inspect({ limit: 200 })), JSON.stringify(second.inspect({ limit: 200 })));+});++test('settle operation errors name the field and what to pass', () => {+ const scene = createAgentScene(wallRecipe());+ const attempt = settle => () => scene.apply([{ type: 'settle', settle: { ...rubble, ...settle } }], { expectedRevision: 0 });+ assert.throws(attempt({ geometry: 'missing' }), /settle\.geometry/);+ assert.throws(attempt({ material: 'missing' }), /settle\.material/);+ assert.throws(attempt({ colliders: ['nowhere'] }), /settle\.colliders\[0\]/);+ assert.throws(attempt({ id: 'floor' }), /settle\.id/);+ assert.throws(attempt({ count: 999 }), /settle\.count/);+ assert.throws(() => scene.apply([{ type: 'settle', id: 'x' }], { expectedRevision: 0 }), /put the settle fields inside "settle"/);+});++test('a settle operation asks the host to load the physics engine and is listed in the capabilities', () => {+ assert.equal(needsPhysics([{ type: 'settle', settle: rubble }]), true);+ assert.ok(AGENT_SCENE_CAPABILITIES.operations.includes('settle'));+ assert.match(AGENT_SCENE_CAPABILITIES.settle, /scene_apply settle/);+});diff --git a/tests/settle.test.js b/tests/settle.test.jsnew file mode 100644index 00000000..4af98736--- /dev/null+++ b/tests/settle.test.js@@ -0,0 +1,112 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import { quat, vec3 } from 'gl-matrix';+import { SETTLE_LIMITS, normalizeSettle, settleInstances, settleProps } from '../src/settle.js';++await settleProps({ colliders: [{ shape: 'box', halfExtents: [1, 1, 1] }], area: { min: [-0.5, -0.5], max: [0.5, 0.5] }, count: 1 });++const BIN_WALLS = [+ { shape: 'box', translation: [0, -0.1, 0], halfExtents: [1.2, 0.1, 1.2] },+ { shape: 'box', translation: [-1.1, 0.5, 0], halfExtents: [0.1, 0.6, 1.2] },+ { shape: 'box', translation: [1.1, 0.5, 0], halfExtents: [0.1, 0.6, 1.2] },+ { shape: 'box', translation: [0, 0.5, -1.1], halfExtents: [1.2, 0.6, 0.1] },+ { shape: 'box', translation: [0, 0.5, 1.1], halfExtents: [1.2, 0.6, 0.1] },+];++function corners(instance, shift = [0, 0, 0]) {+ const axes = [[1, 0, 0], [0, 1, 0], [0, 0, 1]].map(axis => vec3.transformQuat(vec3.create(), axis, instance.rotation));+ return { center: vec3.add(vec3.create(), instance.translation, shift), axes, half: instance.size.map(edge => edge / 2) };+}++function oriented(collider) {+ return { center: collider.translation, axes: [[1, 0, 0], [0, 1, 0], [0, 0, 1]].map(axis => vec3.transformQuat(vec3.create(), axis, collider.rotation ?? quat.create())), half: collider.halfExtents };+}++/** Largest penetration depth of two oriented boxes by the separating axis test; zero or less means they do not overlap. */+function penetration(first, second) {+ const axes = [...first.axes, ...second.axes];+ for (const a of first.axes) for (const b of second.axes) axes.push(vec3.cross(vec3.create(), a, b));+ const between = vec3.sub(vec3.create(), second.center, first.center);+ let shallowest = Infinity;+ for (const axis of axes) {+ const length = vec3.length(axis);+ if (length < 1e-6) continue;+ const direction = vec3.scale(vec3.create(), axis, 1 / length);+ const radius = box => box.axes.reduce((sum, boxAxis, index) => sum + Math.abs(vec3.dot(boxAxis, direction)) * box.half[index], 0);+ shallowest = Math.min(shallowest, radius(first) + radius(second) - Math.abs(vec3.dot(between, direction)));+ }+ return shallowest;+}++const bin = settings => ({ colliders: BIN_WALLS, area: { min: [-1, -1], max: [1, 1] }, size: [0.1, 0.2], seed: 1, ...settings });++test('200 boxes settle into a bin without overlap or floating', () => {+ const { instances, report } = settleInstances(bin({ count: 200, duration: 5 }));+ assert.equal(instances.length, 200, JSON.stringify(report));+ assert.equal(report.fellOff, 0);+ assert.equal(report.unsettled, 0);+ const boxes = instances.map(instance => corners({ ...instance, rotation: instance.rotation }));+ const walls = BIN_WALLS.map(oriented);+ boxes.forEach((box, index) => {+ for (let other = index + 1; other < boxes.length; other++) {+ assert.ok(penetration(box, boxes[other]) < 0.02, `boxes ${index} and ${other} overlap`);+ }+ for (const wall of walls) assert.ok(penetration(box, wall) < 0.02, `box ${index} sinks into a wall`);+ // Resting under gravity means touching something: moved down a little, the box must meet a neighbour or the floor.+ const lowered = corners(instances[index], [0, -0.03, 0]);+ const supported = walls.some(wall => penetration(lowered, wall) > 0) || boxes.some((other, otherIndex) => otherIndex !== index && penetration(lowered, other) > 0);+ assert.ok(supported, `box ${index} floats`);+ });+});++test('the same seed gives the same transforms byte for byte, another seed does not', () => {+ const first = settleInstances(bin({ count: 40 }));+ const second = settleInstances(bin({ count: 40 }));+ assert.equal(JSON.stringify(first), JSON.stringify(second));+ const other = settleInstances(bin({ count: 40, seed: 8 }));+ assert.notEqual(JSON.stringify(first.instances), JSON.stringify(other.instances));+});++test('props never start inside each other or the colliders', () => {+ const { report } = settleInstances(bin({ count: 60, spacing: 0.05 }));+ assert.equal(report.placed + report.fellOff, 60);+});++test('max slope keeps props off steep ground and density sets the count', () => {+ const ramp = { shape: 'box', translation: [0, 0, 0], rotation: Array.from(quat.fromEuler(quat.create(), 0, 0, 40)), halfExtents: [3, 0.1, 3] };+ const gentle = { ...ramp, rotation: Array.from(quat.fromEuler(quat.create(), 0, 0, 15)) };+ const steep = settleInstances({ colliders: [ramp], area: { min: [-1, -1], max: [1, 1] }, count: 10, maxSlope: 30 });+ assert.equal(steep.instances.length, 0);+ assert.ok(steep.report.skipped.tooSteep > 0);+ const allowed = settleInstances({ colliders: [gentle], area: { min: [-1, -1], max: [1, 1] }, count: 5, maxSlope: 30, friction: 2 });+ assert.equal(allowed.instances.length, 5);+ const dense = normalizeSettle({ colliders: BIN_WALLS, area: { min: [0, 0], max: [2, 2] }, density: 10 });+ assert.equal(dense.count, 40);+});++test('props stack on earlier settled props listed as colliders', () => {+ const first = settleInstances({ colliders: [BIN_WALLS[0]], area: { min: [-0.3, -0.3], max: [0.3, 0.3] }, count: 6, size: [0.2, 0.25], seed: 3 });+ const earlier = first.instances.map(instance => ({ shape: 'box', translation: instance.translation, rotation: instance.rotation, halfExtents: instance.size.map(edge => edge / 2) }));+ const second = settleInstances({ colliders: [BIN_WALLS[0], ...earlier], area: { min: [-0.3, -0.3], max: [0.3, 0.3] }, count: 6, size: [0.2, 0.25], seed: 4 });+ const topOfFirst = Math.max(...first.instances.map(instance => instance.translation[1]));+ assert.ok(second.instances.some(instance => instance.translation[1] > topOfFirst), 'some props rest on the earlier layer');+});++test('listed instances skip the ones that start overlapping and balls settle too', () => {+ const result = settleInstances({+ colliders: [BIN_WALLS[0]], shape: 'ball',+ instances: [{ translation: [0, 0.5, 0], size: 0.2 }, { translation: [0, 0.55, 0], size: 0.2 }, { translation: [0.5, 0.5, 0.5], size: 0.2 }],+ });+ assert.equal(result.report.skipped.overlap, 1);+ assert.equal(result.instances.length, 2);+ for (const instance of result.instances) assert.ok(Math.abs(instance.translation[1] - 0.1) < 0.02, `ball rests on the floor top, got ${instance.translation[1]}`);+});++test('bad settings fail with the field and what to pass', () => {+ assert.throws(() => normalizeSettle({ colliders: [], area: { min: [0, 0], max: [1, 1] }, count: 1 }), /settle\.colliders/);+ assert.throws(() => normalizeSettle({ colliders: BIN_WALLS, area: { min: [0, 0], max: [1, 1] }, count: SETTLE_LIMITS.maxProps + 1 }), /settle\.count.*256/);+ assert.throws(() => normalizeSettle({ colliders: BIN_WALLS, area: { min: [0, 0], max: [1, 1] } }), /count \(props\) or density/);+ assert.throws(() => normalizeSettle({ colliders: BIN_WALLS, area: { min: [0, 0], max: [1, 1] }, count: 3, duration: 60 }), /settle\.duration/);+ 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/);+});diff --git a/vite.lib.config.js b/vite.lib.config.jsindex d08bede4..727961bc 100644--- a/vite.lib.config.js+++ b/vite.lib.config.js@@ -58,6 +58,7 @@ export default defineConfig({shrinkwrap: 'src/shrinkwrap.js','surface-attachment': 'src/surface-attachment.js',physics: 'src/physics.js',+ settle: 'src/settle.js',spume: 'src/spume.js',retarget: 'src/retarget.js','crowd-skinning': 'src/crowd-skinning.js',