Skip to content

armgit / 67.js

Public Imported from GitHub
0

3D engine that AI agents drive

feat: add cylinder, cone, compound colliders, spring joints, motors, events, and fields (#692) (#737)

Nguyen Xuan Anac5fa95af1cc
diff --git a/changes/692.md b/changes/692.md
new file mode 100644
index 00000000..4af754cf
--- /dev/null
+++ b/changes/692.md
@@ -0,0 +1 @@
+- Add `cylinder`, `cone` and `compound` collider shapes, `spring` joints, joint `motor` controls, timed `events` (`impulse`, `kinematicPose`, `jointMotor`) and `fields` (force fields on dynamic rigid bodies) to physics definitions and recipe `physics` sections (#692).
diff --git a/changes/692.size.md b/changes/692.size.md
new file mode 100644
index 00000000..1ed8f2da
--- /dev/null
+++ b/changes/692.size.md
@@ -0,0 +1,2 @@
+- entry:physics: `cylinder` and `cone` colliders, `spring` joints and force-field evaluation on dynamic rigid bodies in `src/physics.js` (#692).
+- scene:agent-scene+lazy: `cylinder`, `cone` and `compound` colliders, `spring` joints, joint motors, timed events and force fields in `src/agent-physics.js` (#692).
diff --git a/docs/parity.md b/docs/parity.md
index 8190e42c..474190e7 100644
--- a/docs/parity.md
+++ b/docs/parity.md
@@ -174,16 +174,16 @@ To move to a new Blender release, run `node scripts/parity-manual-snapshot.mjs`.
| Animation & Rigging > Shape Keys | partial | Morph targets import, render and animate, and clip layers drive imported morph weights (`createAssetPose`, MCP `motion.layers`). Recipes can not author them. | [morph](../tests/morph.test.js), [agent-asset-layers](../tests/agent-asset-layers.test.js) | #59 |
| Animation & Rigging > Motion Paths | out of scope | Viewport display for hand work. `scene_inspect` reports motion as numbers. | | |
| Animation & Rigging > In-Betweens | out of scope | Pose tools for a hand. Agents write keyframes and IK targets. | | |
-| Physics > Rigid Body > Rigid Body Properties | partial | Dynamic, fixed and kinematic bodies with mass, density, friction, restitution and velocity, in code and in recipes. Trimesh and convex colliders, no bone-bound bodies yet. | [physics-colliders](../tests/physics-colliders.test.js) | #61 |
+| Physics > Rigid Body > Rigid Body Properties | partial | Dynamic, fixed and kinematic bodies with mass, density, friction, restitution and velocity, in code and in recipes (`box`, `ball`, `capsule`, `cylinder`, `cone`, `convex`, `trimesh` and `compound` colliders, plus ragdoll bone capsules). | [physics-colliders](../tests/physics-colliders.test.js), [agent-physics](../tests/agent-physics.test.js) | #61, #692 |
| Physics > Rigid Body > Rigid Body World | partial | Recorded simulation with deterministic seeks, in code and in a recipe `physics` section (MCP, a seek back repeats the PNG). | [agent-physics](../tests/agent-physics.test.js) | #61 |
-| Physics > Rigid Body > Rigid Body Constraints | partial | Fixed, spherical, revolute and prismatic joints, with limits and motors, in code. | [physics](../tests/physics.test.js) | #61 |
+| Physics > Rigid Body > Rigid Body Constraints | partial | Fixed, spherical, revolute, prismatic and spring joints, with limits, motors and timed impulse/kinematicPose/jointMotor events, in code and in recipes. | [physics](../tests/physics.test.js), [agent-physics](../tests/agent-physics.test.js) | #61, #692 |
| Physics > Cloth | partial | Same solver as the Cloth Modifier row: gravity, wind, pins (static, or riding a moving node with a weight), ball, capsule and box collisions (moving ones follow a skinned character), thickness and friction, and a `scene_inspect` report. Blender's tension, compression, shear and bending stiffness map to one `stiffness` and one `bend`. | [cloth](../tests/cloth.test.js) | #62 |
| Physics > Soft Body | missing | No soft bodies. | | #62 |
| Physics > Fluid | partial | `addons/spume` plays back a liquid baked outside the browser. There is no smoke or fire, by decision (#63): docs/physics.md "Decision" has the measured grid cost. | [spume](../tests/spume.test.js) | #63 |
| Physics > Particle System | partial | Recipe `particles` emitters and hair: see the Particle System Modifier row. Sparks, dust (drag, grow) and fur work from a recipe and seek deterministically. | [particles](../tests/particles.test.js) | #63 |
| Physics > Dynamic Paint | missing | No equivalent. | | |
| Physics > Forces > Gravity | partial | Physics definitions and recipe `physics.gravity` set gravity. | [physics](../tests/physics.test.js) | #61 |
-| Physics > Forces > Force Fields | partial | Wind, turbulence (seeded value noise), vortex, drag and magnet with `strength`, `falloff`, `radius` and `seed`, as the recipe `fields` list of the `particles` and `cloth` sections, one shared evaluation: particles are integrated at 1/120 s from their birth, cloth adds the acceleration at each substep and hair leans at the root. Each type is checked against a known particle path and the same seed gives the same frames. No force field object in the scene, no Blender noise basis, curl or texture fields, no effector on rigid bodies. | [force fields](../tests/force-fields.test.js) | #63, #598 |
+| Physics > Forces > Force Fields | partial | Wind, turbulence (seeded value noise), vortex, drag and magnet with `strength`, `falloff`, `radius` and `seed`, as the `fields` list of `particles`, `cloth` and `physics` (in code and recipes), one shared evaluation: particles are integrated at 1/120 s from their birth, cloth and dynamic rigid bodies add the acceleration at each step and hair leans at the root. Each type is checked against a known path and the same seed gives the same frames. No force field object in the scene, no Blender noise basis, curl or texture fields. | [force fields](../tests/force-fields.test.js), [agent-physics](../tests/agent-physics.test.js) | #63, #598, #692 |
| Physics > Collision | partial | Rapier collisions with sensors (enter and leave events) and 16 collision layers with masks, in code and recipes. `scene_inspect` reports contacts and resting state. | [physics-colliders](../tests/physics-colliders.test.js) | #61 |
| Physics > Baking Physics Simulations | partial | Physics records to a timeline in code or when a recipe scene is created, on the main thread. | [film-physics](../tests/film-physics.test.js) | #61 |
| Physics > Simulation Nodes | missing | No node graph. | | #43 |
diff --git a/docs/physics.md b/docs/physics.md
index cdcaaa81..0a6bb335 100644
--- a/docs/physics.md
+++ b/docs/physics.md
@@ -75,6 +75,8 @@ Collider scales come from their dimensions, independently of visual part scales.
| `ball` | Positive `radius`. |
| `cuboid` | Three positive `halfExtents`. |
| `capsule` | Positive `radius` and `halfHeight` for its cylindrical segment along local Y. |
+| `cylinder` | Positive `radius` and `halfHeight` along local Y. |
+| `cone` | Positive `radius` and `halfHeight` along local Y, apex at `+halfHeight`. |
Each collider accepts either positive `mass` or positive `density`.
The default density is `1`.
@@ -92,6 +94,7 @@ Connected bodies do not collide unless `contactsEnabled` is `true`.
| `revolute` | Required unit `axis` expressed in both bodies' local frames. Optional `limits` and `motor`. |
| `prismatic` | Required unit `axis` expressed in both bodies' local frames. Optional `limits` and `motor`. |
| `fixed` | Optional unit `frameA` and `frameB` quaternions. Both default to identity. |
+| `spring` | `restLength` (default `0`), positive `stiffness` and nonnegative `damping` (default `0`). |
An articulated ragdoll is a graph of dynamic bodies, colliders, and joints.
This example connects two capsule bodies named `upperArm` and `forearm`.
@@ -372,7 +375,8 @@ A scene recipe takes a `physics` section, and `set-physics` edits it (`null` cle
}
```
-Each body is a root node with a geometry. Its collider is fitted to that geometry at the node scale: `box`, `ball` and `capsule` from the bounds, `convex` from at most 2048 distinct vertices, `trimesh` from every triangle.
+Each body is a root node with a geometry. Its collider is fitted to that geometry at the node scale: `box`, `ball`, `capsule`, `cylinder` and `cone` from the bounds, `convex` from at most 2048 distinct vertices, `trimesh` from every triangle, or `compound` with a `shapes` list of up to 16 sub-colliders (`box`, `ball`, `capsule`, `cylinder`, `cone` with optional `translation` and `rotation`).
+Recipe joints also accept `spring` (`restLength`, `stiffness`, `damping`), `motor` (`{ mode: "position" | "velocity", target, stiffness?, damping, maxForce }`) and `contactsEnabled`. Recipe `physics.events` schedules up to 128 `impulse`, `kinematicPose` and `jointMotor` events by `time` in seconds (or `tick`), and `physics.fields` applies up to 8 force fields (`wind`, `turbulence`, `vortex`, `drag`, `magnet`) to dynamic bodies at every step.
Defaults are `box` for dynamic bodies and sensors, `trimesh` for fixed ones.
`layer` (0 to 15) and `collidesWith` replace raw bit masks.
A node cannot have both a physics body and a motion `translation` or `rotation` track.
diff --git a/src/agent-physics.js b/src/agent-physics.js
index bb0ca952..77ffdf2b 100644
--- a/src/agent-physics.js
+++ b/src/agent-physics.js
@@ -3,6 +3,7 @@ import { invalidField } from './field-error.js';
import { restWorldMatrix, boneTails, boneNodeId } from './rig.js';
import { createRagdoll, ragdollPatches, ragdollReport } from './ragdoll.js';
import { bakePhysicsScene, loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader } from './physics.js';
+import { normalizeForceFields } from './force-fields.js';
export { loadPhysicsEngine, physicsEngineLoaded, setPhysicsModuleLoader };
export { needsPhysics } from './agent-scene-modules.js';
@@ -17,12 +18,18 @@ const MAX_HULL_POINTS = 2048;
const MAX_SOURCE_VERTICES = 65536;
const MAX_REPORTED_CONTACTS = 64;
const MAX_REPORTED_SENSOR_EVENTS = 128;
+const MAX_EVENTS = 128;
+const MAX_COMPOUND_SHAPES = 16;
const BODY_TYPES = ['dynamic', 'fixed', 'kinematic'];
-const SHAPES = ['box', 'ball', 'capsule', 'convex', 'trimesh'];
-const JOINT_TYPES = ['spherical', 'revolute', 'prismatic', 'fixed'];
-const BODY_FIELDS = ['node', 'type', 'shape', 'mass', 'density', 'friction', 'restitution', 'sensor', 'velocity', 'angularVelocity', 'layer', 'collidesWith'];
-const JOINT_FIELDS = ['type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'limits'];
-const PHYSICS_FIELDS = ['duration', 'gravity', 'bodies', 'joints', 'ragdoll'];
+const SHAPES = ['box', 'ball', 'capsule', 'cylinder', 'cone', 'convex', 'trimesh', 'compound'];
+const COMPOUND_PART_SHAPES = ['box', 'ball', 'capsule', 'cylinder', 'cone'];
+const JOINT_TYPES = ['spherical', 'revolute', 'prismatic', 'fixed', 'spring'];
+const BODY_FIELDS = ['node', 'type', 'shape', 'shapes', 'mass', 'density', 'friction', 'restitution', 'sensor', 'velocity', 'angularVelocity', 'layer', 'collidesWith'];
+const COMPOUND_PART_FIELDS = ['shape', 'translation', 'rotation', 'halfExtents', 'radius', 'halfHeight'];
+const JOINT_FIELDS = ['name', 'type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'limits', 'motor', 'restLength', 'stiffness', 'damping', 'contactsEnabled'];
+const MOTOR_FIELDS = ['mode', 'target', 'stiffness', 'damping', 'maxForce'];
+const EVENT_FIELDS = ['time', 'tick', 'type', 'body', 'joint', 'impulse', 'torqueImpulse', 'point', 'translation', 'rotation', 'motor'];
+const PHYSICS_FIELDS = ['duration', 'gravity', 'bodies', 'joints', 'events', 'fields', 'ragdoll'];
const RAGDOLL_FIELDS = ['armature', 'density', 'friction', 'restitution', 'layer'];
function knownKeys(value, fields, path) {
@@ -118,6 +125,15 @@ function normalizeBody(input, recipeNodes, motionNodeIds, claimedNodes, path) {
if (input.velocity !== undefined) body.velocity = numberList(input.velocity, 3, `${path}.velocity`);
if (input.angularVelocity !== undefined) body.angularVelocity = numberList(input.angularVelocity, 3, `${path}.angularVelocity`);
if (input.layer !== undefined) body.layer = Math.trunc(finiteNumber(input.layer, `${path}.layer`, 0, MAX_LAYER));
+ if (shape === 'compound') {
+ const parts = boundedArray(input.shapes, MAX_COMPOUND_SHAPES, `${path}.shapes`);
+ if (!parts.length) {
+ throw invalidField(`${path}.shapes`, parts, 'at least one sub-collider when shape is "compound", such as [{ "shape": "box", "halfExtents": [0.5, 0.5, 0.5] }]');
+ }
+ body.shapes = parts.map((part, index) => normalizeCompoundPart(part, `${path}.shapes[${index}]`));
+ } else if (input.shapes !== undefined) {
+ throw invalidField(`${path}.shapes`, input.shapes, 'a field left out unless shape is "compound"', TypeError);
+ }
if (input.collidesWith !== undefined) {
const layers = boundedArray(input.collidesWith, MAX_LAYER + 1, `${path}.collidesWith`);
body.collidesWith = [...new Set(layers.map((layer, index) => Math.trunc(finiteNumber(layer, `${path}.collidesWith[${index}]`, 0, MAX_LAYER))))].sort((first, second) => first - second);
@@ -125,7 +141,46 @@ function normalizeBody(input, recipeNodes, motionNodeIds, claimedNodes, path) {
return body;
}
-function normalizeJoint(input, bodyNodeIds, path) {
+function normalizeCompoundPart(input, path) {
+ knownKeys(input, COMPOUND_PART_FIELDS, path);
+ if (!COMPOUND_PART_SHAPES.includes(input.shape)) {
+ throw invalidField(`${path}.shape`, input.shape, `one of ${COMPOUND_PART_SHAPES.join(', ')}`);
+ }
+ const part = { shape: input.shape };
+ if (input.translation !== undefined) part.translation = numberList(input.translation, 3, `${path}.translation`);
+ if (input.rotation !== undefined) part.rotation = numberList(input.rotation, 4, `${path}.rotation`);
+ if (input.shape === 'box') {
+ part.halfExtents = numberList(input.halfExtents, 3, `${path}.halfExtents`).map((extent, index) => finiteNumber(extent, `${path}.halfExtents[${index}]`, 1e-4, 1e6));
+ } else if (input.shape === 'ball') {
+ part.radius = finiteNumber(input.radius, `${path}.radius`, 1e-4, 1e6);
+ } else {
+ part.radius = finiteNumber(input.radius, `${path}.radius`, 1e-4, 1e6);
+ part.halfHeight = finiteNumber(input.halfHeight, `${path}.halfHeight`, 1e-4, 1e6);
+ }
+ return part;
+}
+
+function normalizeMotor(input, path) {
+ if (input === null) return null;
+ knownKeys(input, MOTOR_FIELDS, path);
+ if (!['position', 'velocity'].includes(input.mode)) {
+ throw invalidField(`${path}.mode`, input.mode, 'one of position, velocity');
+ }
+ const motor = {
+ mode: input.mode,
+ target: finiteNumber(input.target, `${path}.target`, -1e4, 1e4),
+ damping: finiteNumber(input.damping ?? (input.mode === 'velocity' ? 10 : 0), `${path}.damping`, 0, 1e6),
+ maxForce: finiteNumber(input.maxForce ?? 1e4, `${path}.maxForce`, 1e-6, 1e8),
+ };
+ if (input.mode === 'position') {
+ motor.stiffness = finiteNumber(input.stiffness ?? 100, `${path}.stiffness`, 1e-6, 1e6);
+ } else if (input.stiffness !== undefined) {
+ throw invalidField(`${path}.stiffness`, input.stiffness, 'a field left out for velocity motors', TypeError);
+ }
+ return motor;
+}
+
+function normalizeJoint(input, bodyNodeIds, jointNames, path) {
knownKeys(input, JOINT_FIELDS, path);
if (!JOINT_TYPES.includes(input.type)) {
throw invalidField(`${path}.type`, input.type, `one of ${JOINT_TYPES.join(', ')}`);
@@ -136,13 +191,82 @@ function normalizeJoint(input, bodyNodeIds, path) {
}
}
const joint = { type: input.type, bodyA: input.bodyA, bodyB: input.bodyB };
+ if (input.name !== undefined) {
+ const name = nodeIdentifier(input.name, `${path}.name`);
+ if (jointNames.has(name)) {
+ throw invalidField(`${path}.name`, name, 'a unique joint name');
+ }
+ jointNames.add(name);
+ joint.name = name;
+ }
for (const field of ['anchorA', 'anchorB', 'axis']) {
if (input[field] !== undefined) joint[field] = numberList(input[field], 3, `${path}.${field}`);
}
+ if (input.contactsEnabled !== undefined) {
+ if (typeof input.contactsEnabled !== 'boolean') {
+ throw invalidField(`${path}.contactsEnabled`, input.contactsEnabled, 'true or false', TypeError);
+ }
+ joint.contactsEnabled = input.contactsEnabled;
+ }
if (input.limits !== undefined) joint.limits = numberList(input.limits, 2, `${path}.limits`);
+ if (input.motor !== undefined) joint.motor = normalizeMotor(input.motor, `${path}.motor`);
+ if (input.type === 'spring') {
+ joint.restLength = finiteNumber(input.restLength ?? 0, `${path}.restLength`, 0, 1e6);
+ joint.stiffness = finiteNumber(input.stiffness, `${path}.stiffness`, 1e-6, 1e6);
+ if (input.damping !== undefined) joint.damping = finiteNumber(input.damping, `${path}.damping`, 0, 1e6);
+ } else if (input.restLength !== undefined || input.stiffness !== undefined || input.damping !== undefined) {
+ throw invalidField(`${path}.stiffness`, input.stiffness ?? input.restLength ?? input.damping, 'a field left out unless joint type is "spring"', TypeError);
+ }
return joint;
}
+function normalizeEvent(input, duration, bodyTypes, jointNames, path) {
+ knownKeys(input, EVENT_FIELDS, path);
+ const type = input.type ?? 'impulse';
+ if (!['impulse', 'kinematicPose', 'jointMotor'].includes(type)) {
+ throw invalidField(`${path}.type`, type, 'one of impulse, kinematicPose, jointMotor');
+ }
+ const maxTick = Math.max(0, Math.round(duration * FRAMES_PER_SECOND) - 1);
+ let tick;
+ if (input.tick !== undefined) {
+ tick = Math.trunc(finiteNumber(input.tick, `${path}.tick`, 0, maxTick));
+ } else {
+ const time = finiteNumber(input.time ?? 0, `${path}.time`, 0, duration);
+ tick = Math.min(maxTick, Math.max(0, Math.round(time * FRAMES_PER_SECOND)));
+ }
+ if (type === 'jointMotor') {
+ if (!jointNames.has(input.joint)) {
+ throw invalidField(`${path}.joint`, input.joint, `the name of a physics joint, one of ${[...jointNames].slice(0, 5).join(', ') || 'none yet'}`);
+ }
+ return { tick, type, joint: input.joint, motor: normalizeMotor(input.motor, `${path}.motor`) };
+ }
+ if (!bodyTypes.has(input.body)) {
+ throw invalidField(`${path}.body`, input.body, `the node of a physics body, one of ${[...bodyTypes.keys()].slice(0, 5).join(', ') || 'none yet'}`);
+ }
+ const event = { tick, type, body: input.body };
+ if (type === 'impulse') {
+ if (bodyTypes.get(input.body) !== 'dynamic') {
+ throw invalidField(`${path}.body`, input.body, 'a dynamic body for an impulse event');
+ }
+ if (input.impulse === undefined && input.torqueImpulse === undefined) {
+ throw invalidField(`${path}.impulse`, undefined, 'impulse or torqueImpulse on an impulse event, such as [0, 5, 0]');
+ }
+ if (input.impulse !== undefined) event.impulse = numberList(input.impulse, 3, `${path}.impulse`);
+ if (input.torqueImpulse !== undefined) event.torqueImpulse = numberList(input.torqueImpulse, 3, `${path}.torqueImpulse`);
+ if (input.point !== undefined) event.point = numberList(input.point, 3, `${path}.point`);
+ return event;
+ }
+ if (bodyTypes.get(input.body) !== 'kinematic') {
+ throw invalidField(`${path}.body`, input.body, 'a kinematic body for a kinematicPose event');
+ }
+ if (input.translation === undefined && input.rotation === undefined) {
+ throw invalidField(`${path}.translation`, undefined, 'translation or rotation on a kinematicPose event, such as [1, 0, 0]');
+ }
+ if (input.translation !== undefined) event.translation = numberList(input.translation, 3, `${path}.translation`);
+ if (input.rotation !== undefined) event.rotation = numberList(input.rotation, 4, `${path}.rotation`);
+ return event;
+}
+
function normalizeRagdoll(input, recipe, motionNodeIds) {
knownKeys(input, RAGDOLL_FIELDS, 'physics.ragdoll');
const armature = (recipe.armatures ?? []).find(candidate => candidate.id === input.armature);
@@ -201,8 +325,20 @@ export function normalizeAgentPhysics(input, recipe) {
const result = { duration, bodies };
if (input.ragdoll !== undefined) result.ragdoll = normalizeRagdoll(input.ragdoll, recipe, motionNodeIds);
if (input.gravity !== undefined) result.gravity = numberList(input.gravity, 3, 'physics.gravity');
+ const jointNames = new Set();
if (input.joints !== undefined) {
- result.joints = boundedArray(input.joints, MAX_JOINTS, 'physics.joints').map((joint, index) => normalizeJoint(joint, claimedNodes, `physics.joints[${index}]`));
+ result.joints = boundedArray(input.joints, MAX_JOINTS, 'physics.joints').map((joint, index) => {
+ const normalized = normalizeJoint(joint, claimedNodes, jointNames, `physics.joints[${index}]`);
+ jointNames.add(normalized.name ?? `joint-${index}`);
+ return normalized;
+ });
+ }
+ if (input.events !== undefined) {
+ const bodyTypes = new Map(bodies.map(body => [body.node, body.type]));
+ result.events = boundedArray(input.events, MAX_EVENTS, 'physics.events').map((event, index) => normalizeEvent(event, duration, bodyTypes, jointNames, `physics.events[${index}]`));
+ }
+ if (input.fields !== undefined) {
+ result.fields = normalizeForceFields(input.fields, 'physics.fields');
}
return result;
}
@@ -261,6 +397,10 @@ function colliderFromGeometry(body, node, geometry) {
const radius = Math.max(halfExtents[0], halfExtents[2]);
return { shape: 'capsule', radius, halfHeight: Math.max(halfExtents[1] - radius, radius * 0.01), translation: center };
}
+ if (body.shape === 'cylinder' || body.shape === 'cone') {
+ const radius = Math.max(halfExtents[0], halfExtents[2]);
+ return { shape: body.shape, radius, halfHeight: halfExtents[1], translation: center };
+ }
if (body.shape === 'convex') {
return { shape: 'convexHull', points: convexPoints(geometry.positions, node.scale, node.id) };
}
@@ -282,27 +422,48 @@ function physicsDefinition(physics, recipe, geometries, ragdoll) {
...(body.velocity ? { linearVelocity: body.velocity } : {}),
...(body.angularVelocity ? { angularVelocity: body.angularVelocity } : {}),
});
- const collider = {
- name: node.id, body: node.id,
- ...colliderFromGeometry(body, node, geometries.get(node.geometry)),
+ const commonCollider = {
+ body: node.id,
...(body.sensor ? { sensor: true } : {}),
...(body.friction !== undefined ? { friction: body.friction } : {}),
...(body.restitution !== undefined ? { restitution: body.restitution } : {}),
groups: 1 << (body.layer ?? 0),
mask: body.collidesWith ? layerBits(body.collidesWith) : 0xffff,
};
- if (collider.shape !== 'trimesh') {
- if (body.mass !== undefined) collider.mass = body.mass;
- else collider.density = body.density ?? 1;
+ if (body.shape === 'compound') {
+ body.shapes.forEach((part, partIndex) => {
+ const mappedShape = part.shape === 'box' ? 'cuboid' : part.shape;
+ const collider = {
+ name: partIndex === 0 ? node.id : `${node.id}#${partIndex}`,
+ ...commonCollider,
+ ...part,
+ shape: mappedShape,
+ };
+ if (body.mass !== undefined) collider.mass = body.mass / body.shapes.length;
+ else collider.density = body.density ?? 1;
+ definition.colliders.push(collider);
+ });
+ } else {
+ const collider = {
+ name: node.id,
+ ...commonCollider,
+ ...colliderFromGeometry(body, node, geometries.get(node.geometry)),
+ };
+ if (collider.shape !== 'trimesh') {
+ if (body.mass !== undefined) collider.mass = body.mass;
+ else collider.density = body.density ?? 1;
+ }
+ definition.colliders.push(collider);
}
- definition.colliders.push(collider);
}
if (ragdoll) {
definition.bodies.push(...ragdoll.definition.bodies);
definition.colliders.push(...ragdoll.definition.colliders);
definition.joints.push(...ragdoll.definition.joints);
}
- (physics.joints ?? []).forEach((joint, index) => definition.joints.push({ name: `joint-${index}`, ...joint }));
+ (physics.joints ?? []).forEach((joint, index) => definition.joints.push({ name: joint.name ?? `joint-${index}`, ...joint }));
+ if (physics.events) definition.events = physics.events;
+ if (physics.fields) definition.fields = physics.fields;
return definition;
}
diff --git a/src/physics.js b/src/physics.js
index b0fe4950..ae656bef 100644
--- a/src/physics.js
+++ b/src/physics.js
@@ -1,4 +1,5 @@
import { mat4, quat, vec3 } from 'gl-matrix';
+import { evaluateForceFields, normalizeForceFields } from './force-fields.js';
let rapierPromise;
let rapierEngine;
@@ -257,7 +258,7 @@ function meshCollider(collider, body, limits, budget) {
}
function prepare(definition, options) {
- fields(definition, ['bodies', 'colliders', 'joints', 'events', 'gravity'], 'definition');
+ fields(definition, ['bodies', 'colliders', 'joints', 'events', 'fields', 'gravity'], 'definition');
fields(options, ['frameCount', 'timestep', 'solverIterations', 'maxMemoryBytes', ...Object.keys(LIMITS)], 'options');
const limits = {};
for (const [key, [fallback, cap]] of Object.entries(LIMITS)) {
@@ -370,6 +371,14 @@ function prepare(definition, options) {
halfHeight = positive(collider.halfHeight, 'halfHeight');
volume = Math.PI * radius ** 2 * 2 * halfHeight + 4 * Math.PI * radius ** 3 / 3;
smallestExtent = radius;
+ } else if (collider.shape === 'cylinder' || collider.shape === 'cone') {
+ if (collider.halfExtents !== undefined) {
+ throw new TypeError(`${collider.shape} only accepts radius and halfHeight`);
+ }
+ radius = positive(collider.radius, 'radius');
+ halfHeight = positive(collider.halfHeight, 'halfHeight');
+ volume = Math.PI * radius ** 2 * 2 * halfHeight / (collider.shape === 'cone' ? 3 : 1);
+ smallestExtent = Math.min(radius, halfHeight);
} else if (mesh) {
volume = mesh.volume;
smallestExtent = mesh.smallestExtent;
@@ -424,8 +433,8 @@ function prepare(definition, options) {
}
}
const joints = rawJoints.map(joint => {
- fields(joint, ['name', 'type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'frameA', 'frameB', 'contactsEnabled', 'limits', 'motor'], `joint ${joint.name}`);
- if (!['spherical', 'revolute', 'prismatic', 'fixed'].includes(joint.type)) {
+ fields(joint, ['name', 'type', 'bodyA', 'bodyB', 'anchorA', 'anchorB', 'axis', 'frameA', 'frameB', 'contactsEnabled', 'limits', 'motor', 'restLength', 'stiffness', 'damping'], `joint ${joint.name}`);
+ if (!['spherical', 'revolute', 'prismatic', 'fixed', 'spring'].includes(joint.type)) {
throw new TypeError('unsupported joint type');
}
const bodyA = bodyIndex(joint.bodyA);
@@ -444,6 +453,9 @@ function prepare(definition, options) {
if (joint.type !== 'fixed' && (joint.frameA !== undefined || joint.frameB !== undefined)) {
throw new TypeError('joint frames require a fixed joint');
}
+ if (joint.type !== 'spring' && (joint.restLength !== undefined || joint.stiffness !== undefined || joint.damping !== undefined)) {
+ throw new TypeError('restLength, stiffness and damping require a spring joint');
+ }
const axis = unitJoint ? vector(joint.axis, 3, 'axis') : undefined;
if (axis && Math.abs(Math.hypot(...axis) - 1) > 1e-4) {
throw new RangeError('axis must be a unit vector');
@@ -465,6 +477,12 @@ function prepare(definition, options) {
frameB: rotation(joint.frameB, 'frameB'),
contactsEnabled: joint.contactsEnabled ?? false,
};
+ if (joint.type === 'spring') {
+ result.restLength = scalar(joint.restLength ?? 0, 'restLength', 0, MAX_JOINT_DISTANCE);
+ result.stiffness = positive(joint.stiffness, 'stiffness');
+ if (result.stiffness > MAX_MOTOR_GAIN) throw new RangeError('spring stiffness exceeds the supported gain bound');
+ result.damping = scalar(joint.damping ?? 0, 'damping', 0, MAX_MOTOR_GAIN);
+ }
if (joint.limits !== undefined) result.limits = jointLimits(joint.limits, joint.type);
if (joint.motor !== undefined) result.motor = jointMotor(joint.motor, result);
if (joint.type === 'prismatic' || joint.limits !== undefined || joint.motor !== undefined) initialJointCoordinate(result, bodies);
@@ -516,8 +534,9 @@ function prepare(definition, options) {
rotation: event.rotation === undefined ? undefined : rotation(event.rotation, 'event rotation'),
};
}).sort((firstEvent, secondEvent) => firstEvent.tick - secondEvent.tick || firstEvent.order - secondEvent.order);
+ const forceFields = normalizeForceFields(definition.fields ?? [], 'fields');
const gravity = vector(definition.gravity, 3, 'gravity', [0, -9.81, 0]);
- validateMotionBounds(bodies, events, gravity, timestep, frameCount, massTotals, minimumInertiaTotals, maximumColliderOffsets, joints, inertiaTotals);
+ validateMotionBounds(bodies, events, gravity, forceFields, timestep, frameCount, massTotals, minimumInertiaTotals, maximumColliderOffsets, joints, inertiaTotals);
const memoryPlan = Object.freeze({
timelineBytes,
solverReserveBytes,
@@ -534,6 +553,7 @@ function prepare(definition, options) {
colliders,
joints,
events,
+ fields: forceFields,
gravity,
frameCount,
timestep,
@@ -602,9 +622,10 @@ function validateMotorBounds(bodies, joints, events, timestep, duration, massTot
}
}
-function validateMotionBounds(bodies, events, gravity, timestep, frameCount, massTotals, minimumInertiaTotals, maximumColliderOffsets, joints, maximumInertiaTotals) {
+function validateMotionBounds(bodies, events, gravity, forceFields, timestep, frameCount, massTotals, minimumInertiaTotals, maximumColliderOffsets, joints, maximumInertiaTotals) {
const duration = (frameCount - 1) * timestep;
- const gravityMagnitude = vectorLength(gravity, 'gravity');
+ const fieldMagnitude = forceFields.reduce((total, field) => total + (field.type === 'drag' ? 0 : Math.abs(field.strength)), 0);
+ const gravityMagnitude = vectorLength(gravity, 'gravity') + fieldMagnitude;
const linearSpeedBounds = bodies.map(body => {
const initialSpeed = vectorLength(body.linearVelocity, 'linearVelocity');
const speedBound = initialSpeed + (body.type === 'dynamic' ? gravityMagnitude * duration : 0);
@@ -707,6 +728,10 @@ function colliderDescriptor(rapier, collider) {
descriptor = rapier.ColliderDesc.cuboid(...collider.halfExtents);
} else if (collider.shape === 'capsule') {
descriptor = rapier.ColliderDesc.capsule(collider.halfHeight, collider.radius);
+ } else if (collider.shape === 'cylinder') {
+ descriptor = rapier.ColliderDesc.cylinder(collider.halfHeight, collider.radius);
+ } else if (collider.shape === 'cone') {
+ descriptor = rapier.ColliderDesc.cone(collider.halfHeight, collider.radius);
} else if (collider.shape === 'convexHull') {
descriptor = rapier.ColliderDesc.convexHull(collider.points);
if (!descriptor) {
@@ -778,6 +803,8 @@ function bakePrepared(preparedScene) {
descriptor = rapier.JointData.revolute(anchorA, anchorB, xyz(joint.axis));
} else if (joint.type === 'prismatic') {
descriptor = rapier.JointData.prismatic(anchorA, anchorB, xyz(joint.axis));
+ } else if (joint.type === 'spring') {
+ descriptor = rapier.JointData.spring(joint.restLength, joint.stiffness, joint.damping, anchorA, anchorB);
} else {
descriptor = rapier.JointData.fixed(anchorA, xyzw(joint.frameA), anchorB, xyzw(joint.frameB));
}
@@ -819,6 +846,21 @@ function bakePrepared(preparedScene) {
}
}
}
+ if (preparedScene.fields.length) {
+ const fieldTime = (frame - 1) * preparedScene.timestep;
+ const fieldAccel = [0, 0, 0];
+ for (let bodyIndex = 0; bodyIndex < bodies.length; bodyIndex++) {
+ if (preparedScene.bodies[bodyIndex].type !== 'dynamic') continue;
+ const body = bodies[bodyIndex];
+ const pos = body.translation();
+ const vel = body.linvel();
+ evaluateForceFields(preparedScene.fields, [pos.x, pos.y, pos.z], [vel.x, vel.y, vel.z], fieldTime, fieldAccel);
+ const scale = body.mass() * preparedScene.timestep;
+ if (fieldAccel[0] || fieldAccel[1] || fieldAccel[2]) {
+ body.applyImpulse({ x: fieldAccel[0] * scale, y: fieldAccel[1] * scale, z: fieldAccel[2] * scale }, true);
+ }
+ }
+ }
world.step(eventQueue);
eventQueue.drainCollisionEvents((firstHandle, secondHandle, started) => {
if (contactEvents.length >= preparedScene.maxContactEvents) {
diff --git a/tests/agent-physics.test.js b/tests/agent-physics.test.js
index e1179ab4..d213cb39 100644
--- a/tests/agent-physics.test.js
+++ b/tests/agent-physics.test.js
@@ -117,3 +117,47 @@ test('capabilities name the physics surface and the detector finds a section', (
assert.equal(needsPhysics(recipe(undefined)), false);
assert.equal(needsPhysics([{ type: 'set-physics', physics: null }]), false);
});
+
+test('recipe physics supports cylinder, cone, compound shapes, spring joints, motors, events and force fields', () => {
+ const scene = createAgentScene(recipe({
+ duration: 1,
+ gravity: [0, 0, 0],
+ fields: [{ type: 'wind', direction: [0, 0, 1], strength: 6 }],
+ bodies: [
+ { node: 'floor', type: 'fixed', shape: 'cylinder' },
+ { node: 'ball', shape: 'cone', mass: 1 },
+ { node: 'slider', shape: 'compound', shapes: [
+ { shape: 'box', halfExtents: [0.2, 0.2, 0.2], translation: [-0.2, 0, 0] },
+ { shape: 'ball', radius: 0.2, translation: [0.2, 0, 0] },
+ { shape: 'cylinder', radius: 0.1, halfHeight: 0.2 },
+ ] },
+ { node: 'bob', shape: 'capsule' },
+ ],
+ joints: [
+ { name: 'track', type: 'prismatic', bodyA: 'floor', bodyB: 'slider', anchorA: [0, 2, 0], anchorB: [0, 0, 0], axis: [1, 0, 0], limits: [-2, 2], motor: { mode: 'position', target: 0.8, stiffness: 60, damping: 10, maxForce: 100 }, contactsEnabled: false },
+ { type: 'spring', bodyA: 'floor', bodyB: 'bob', anchorA: [0, 2, 0], anchorB: [0, 0, 0], restLength: 0.5, stiffness: 30, damping: 3 },
+ ],
+ events: [
+ { time: 0.2, type: 'impulse', body: 'ball', impulse: [3, 0, 0], torqueImpulse: [0, 1, 0], point: [0, 2, 0] },
+ { tick: 30, type: 'jointMotor', joint: 'track', motor: { mode: 'velocity', target: -0.5, damping: 10, maxForce: 50 } },
+ ],
+ }, [
+ { id: 'slider', geometry: 'slab', material: 'paint', translation: [0, 1.75, 0], rotation: [0, 0, 0, 1], scale: [0.4, 0.4, 0.4] },
+ { id: 'bob', geometry: 'ball', material: 'paint', translation: [0, 0.5, 0], scale: [0.3, 0.3, 0.3] },
+ ]));
+ scene.sampleMotion(1);
+ const { physics } = scene.inspect({});
+ const ball = physics.bodies.find(body => body.node === 'ball');
+ const bob = physics.bodies.find(body => body.node === 'bob');
+ assert.ok(ball.finalPosition[0] > 1.5, `impulse pushes ball along +X, got ${ball.finalPosition[0]}`);
+ assert.ok(ball.finalPosition[2] > 2, `wind field pushes ball along +Z, got ${ball.finalPosition[2]}`);
+ assert.ok(bob.finalPosition[1] > 0.8, `spring pulls bob upward, got ${bob.finalPosition[1]}`);
+
+ const kinScene = createAgentScene(recipe({ duration: 1, bodies: [{ node: 'floor', type: 'kinematic', shape: 'box' }], events: [{ time: 0.1, type: 'kinematicPose', body: 'floor', translation: [0, 1, 0], rotation: [0, 0, 0, 1] }] }));
+ kinScene.sampleMotion(0.5);
+ assert.equal(kinScene.parts[0].matrix[13], 1);
+ assert.throws(() => createAgentScene(recipe({ duration: 1, bodies: [{ node: 'ball', shape: 'compound', shapes: [] }] })), /at least one sub-collider/);
+ assert.throws(() => createAgentScene(recipe({ duration: 1, bodies: [{ node: 'ball', shapes: [{ shape: 'box', halfExtents: [1, 1, 1] }] }] })), /compound/);
+ assert.throws(() => createAgentScene(recipe({ duration: 1, bodies: [{ node: 'ball' }], events: [{ time: 0.1, type: 'impulse', body: 'ball' }] })), /impulse or torqueImpulse/);
+ assert.throws(() => createAgentScene(recipe({ duration: 1, bodies: [{ node: 'floor', type: 'kinematic', shape: 'box' }], events: [{ time: 0.1, type: 'kinematicPose', body: 'floor' }] })), /translation or rotation/);
+});
diff --git a/tests/physics.test.js b/tests/physics.test.js
index aa7e2758..d48afcc6 100644
--- a/tests/physics.test.js
+++ b/tests/physics.test.js
@@ -637,3 +637,39 @@ test('explicit initial and tick motor disable can be no-ops without changing the
assert.deepEqual(scene.sample(scene.duration), scene.sample(0));
scene.dispose();
});
+
+test('cylinder and cone colliders, spring joints and force fields bake deterministically', async () => {
+ const definition = {
+ gravity: [0, 0, 0],
+ fields: [{ type: 'wind', direction: [1, 0, 0], strength: 4 }],
+ bodies: [
+ { name: 'anchor', type: 'fixed', translation: [0, 0, 0] },
+ { name: 'cyl', type: 'dynamic', translation: [0, -2, 0] },
+ { name: 'cone', type: 'dynamic', translation: [2, 0, 0] },
+ ],
+ colliders: [
+ { name: 'anchor', body: 'anchor', shape: 'cylinder', radius: 0.5, halfHeight: 0.5 },
+ { name: 'cyl', body: 'cyl', shape: 'cylinder', radius: 0.4, halfHeight: 0.6, mass: 1 },
+ { name: 'cone', body: 'cone', shape: 'cone', radius: 0.5, halfHeight: 0.8, mass: 1 },
+ ],
+ joints: [
+ { name: 'spring', type: 'spring', bodyA: 'anchor', bodyB: 'cyl', restLength: 1, stiffness: 20, damping: 2 },
+ ],
+ };
+ const scene = await createPhysicsScene(definition, { frameCount: 61 });
+ const cylEnd = bodyPose(scene, 1, 'cyl');
+ const coneEnd = bodyPose(scene, 1, 'cone');
+ assert.ok(cylEnd[1] > -1.8, `spring pulls cylinder toward restLength, got ${cylEnd[1]}`);
+ assert.ok(coneEnd[0] > 3.5, `wind field accelerates cone along +X, got ${coneEnd[0]}`);
+ scene.dispose();
+
+ assert.throws(() => planPhysicsScene({
+ bodies: [{ name: 'a', type: 'dynamic' }],
+ colliders: [{ name: 'a', body: 'a', shape: 'cylinder', radius: 0.5, halfHeight: 0.5, halfExtents: [1, 1, 1] }],
+ }), /cylinder only accepts radius and halfHeight/);
+ assert.throws(() => planPhysicsScene({
+ bodies: [{ name: 'a', type: 'fixed' }, { name: 'b', type: 'dynamic' }],
+ colliders: [{ name: 'b', body: 'b', shape: 'cone', radius: 0.5, halfHeight: 0.5 }],
+ joints: [{ name: 'j', type: 'fixed', bodyA: 'a', bodyB: 'b', stiffness: 10 }],
+ }), /spring joint/);
+});