Skip to content
AI-Ready Docs
/llms.txt/llms-mcp.txt

Physics profiles and lifecycle ​

Choose the numerical profile before creating a world. A larger body-count limit does not enable all smaller-profile features. Admission limits describe allowed inputs; numerical evidence covers the named cases only. This page describes the current unreleased branch, without a publication or active CAD adoption claim. Start with the package overview and unit contract.

Rigid world profiles ​

All rigid-world profiles use createPhysicsWorld(model, options) from @barocss/physics. Unless a narrower profile fixes the step, fixedStepSeconds is in [1/240, 1/30] s. step(commands?) uses the configured value and takes no time argument. The limit is 3600 accepted steps. At least one dynamic body is required.

SelectionCapacity and combinationsNumerical scope and evidence route
profile:'rigid-discrete-v1'1–32 spheres, oriented boxes or capsules; optional broadPhase:'aabb'One contact point per pair and eight solver passes. Primitive contacts are not exact CAD collision. See verification.
profile:'rigid-persistent-box-v1'At most four bodies; no large-v1 or box-pair CCDAwake, unfiltered dynamic/static boxes with zero restitution/friction and no joints/sensors/CCD use one global normal and all-pair position solve, with broadPhase:'direct' required and no failure fallback. Other material/role combinations retain their bounded manifold/contact laws. Minimum material restitution applies above the strict 0.5 m/s closing-speed switch. Selected centered and offset fixtures do not qualify arbitrary stacks.
profile:'rigid-stationary-cube-stack-v1'Exactly eight1kg half0.25m cubes and the original static floor;1200steps; direct broad phase, dt1/120, g=[0,-9.81,0], yaw-only poses, zero motion, original materials and empty commandsExact32-point stationary witness; no fallback. Original three equilibrium scenes pass independent1200-step checks, public Source/compiled paths and actual desktop body-word parity. Unsupported contact chains refuse. This maintains equilibrium; falling, bounce, frictional settling and collapse are outside this profile.
profile:'rigid-large-v1'1–64 bodies; requires broadPhase:'aabb'; requires an empty joints array; excludes CCD and persistent-box contactFixed collision filters and contact-island sleep. The named 63-sphere floor probe is a capacity case, not a general 64-body stack certificate.
Anchored fixed or hinge jointsAt most eight records. Each static/kinematic A connects to a uniquely jointed dynamic BBody-local initial anchors must coincide within 1e-6 m. A hinge uses unit axisWorld and limits within ±π/2 that include zero. Connected bodies do not collide.
One dynamic fixed jointExactly two dynamic spheres, no other bodies or jointsInverse mass/inertia distribute corrections. The recorded equal-mass impulse fixture does not qualify general joint networks.
One concentric dynamic hingeExactly two dynamic spheres at the same centre; zero gravity, zero initial motion, identity orientation, zero local anchorsPlanar angular commands along the hinge axis only. An optional motor drives relative B/A speed with equal and opposite impulses.
One offset dynamic hingeExactly two 1 kg spheres of radius 0.1 m; centres at ±0.1 m on X; opposing 0.1 m local X anchorsFixed +Z hinge, limits [-0.8,0.8], zero gravity and 1/120 s step. Motor target 0.5 rad/s, impulse cap 0.0001 N·m·s and reaction cap 0.01 N·m·s. This is one fixture.
Two disjoint dynamic hingesExactly four 1 kg spheres of radius 0.1 m, forming the offset pair at Z=0 and Z=1 mrigid-discrete-v1, direct broad phase, zero gravity, exact identity initial quaternions, zero initial motion, restitution 0, friction 1/0.7. Both hinges use the offset limits/motor above. Only empty commands; cross-component contact refuses. See the bounded evidence below.
Sphere/static-box CCDOne CCD dynamic sphere and 1–8 static nonsensor oriented boxes; no joints or other bodiesEuclidean rounded-box sweep with selected independent face/edge/vertex/grazing evidence. Initial touch/overlap remains discrete-owned; arbitrary numerical scales and rotating fixtures are not qualified.
Dynamic-sphere-pair CCDExactly two nonsensor dynamic spheres, exactly one with ccd:true; zero gravity, no jointsExact represented endpoint/radius predicates with finite independent head-on/grazing/miss/initial/endpoint evidence. Both 5e-10 m inward biases remain. Extreme output accuracy and remaining-time integration are separate. colliderId denotes the other dynamic sphere's collider.
Axis-aligned-box-pair CCDOne CCD dynamic box and one static nonsensor box, both axis-aligned; no joints or persistent boxesBoth signs of the identity quaternion are admitted with the same orientation/angular thresholds. Finite centered face-event boundaries have separate numerical and desktop proof. Nonzero angular commands refuse. Contact-induced rotation refuses the candidate. General rotation and tied-axis/corner events remain unqualified.

CCD stops at the earliest admitted hit with a 1e-9 m inward offset. It does not integrate the remaining fraction of that step. Initial overlap/touch uses the discrete path. Capsule CCD, general oriented-box CCD and arbitrary moving-body networks are outside these profiles.

An anchored hinge motor uses motor:{targetSpeedRadps,maxImpulseNms,maxReactionNms}. Target speed is within ±2 rad/s. Its positive motor impulse cap is at most 0.05 N·m·s and its positive reaction cap is at most 1 N·m·s. It stops pushing outward at a hinge limit. Exceeding the reaction cap gives NUMERIC_LIMIT; it is not a material break-strength model. The offset profile fixes narrower values.

Discrete static friction now solves both tangent constraints. Centered anisotropic cuboid impacts and original sphere/static-box branch inputs have separate numerical and desktop proof. The persistent manifold friction solver has its own cache/iteration law and is not qualified by those discrete results. General off-center normal/tangent coupling remains unqualified.

The public persistent-box limit remains four bodies. The separate stationary cube profile uses the sole common World API and qualifies only the named equilibrium cases. It does not extend moving persistent-box dynamics. The disjoint-hinge profile has a separate qualification; it does not admit connected two-link mechanisms. Keep historical NO_GO results and unresolved causes alongside later bounded results in Physics verification.

The changing-normal persistent friction qualification currently has a public NO_GO: its accepted aggregate tangent is not in the reported normal plane, and the accepted paired contact witness fails independent native geometry. Existing centered impact and support results remain bounded proofs. No general tilted contact, contact-cache accuracy or stable-stack claim follows from admission.

Two cubes and a floor ​

The zero-friction island shares the common World, clock and recorder. Supply only initial conditions and commands. Render the accepted body state after a step. The renderer does not solve contacts or advance time.

mjs
const initial = positionM => ({ positionM, orientationXYZW: [0, 0, 0, 1],
  velocityMps: [0, 0, 0], angularVelocityRadps: [0, 0, 0] });
const cube = (id, y) => ({ id, kind: 'dynamic', massKg: 2,
  inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' },
  initial: initial([0, y, 0]) });
const model = {
  format: 'barocss-physics-model', version: 1, revision: 'docsCoupledCubes1',
  frame: { id: 'world', basis: 'right-handed-xyz', rotation: 'local-to-world-xyzw' },
  units: { length: 'm', mass: 'kg', time: 's', angle: 'rad' },
  gravityMps2: [0, -9.81, 0],
  bodies: [cube('lower', 0.5), cube('upper', 1.75),
    { id: 'floor', kind: 'static', initial: { positionM: [0, -0.5, 0], orientationXYZW: [0, 0, 0, 1] } }],
  colliders: ['lower', 'upper', 'floor'].map(bodyId => ({
    id: `hull:${bodyId}`, bodyId,
    geometry: { kind: 'box', halfExtentsM: bodyId === 'floor' ? [2, 0.5, 2] : [0.5, 0.5, 0.5] },
    local: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1] },
    material: { restitution: 0, friction: { static: 0, dynamic: 0 } },
    sensor: false, ccd: false, filter: { categoryBits: 1, maskBits: 65535 },
  })),
  joints: [], cloths: [], fluids: [], sourceBindings: [],
};
const options = { profile: 'rigid-persistent-box-v1', fixedStepSeconds: 1 / 120, broadPhase: 'direct' };
mjs
const world = createPhysicsWorld(model, options);
try {
  for (let i = 0; i < 32; i++) world.step([]);
  const state = world.getState();
  // Render state.bodies; rendering does not advance the World.
  assert.equal(state.stepIndex, 32);
  assert.equal(state.timeSeconds, 32 / 120);
  assert.equal(state.contacts.length, 2);
  for (const [id, height] of [['lower', 0.5], ['upper', 1.5]]) {
    const body = state.bodies.find(value => value.id === id);
    assert.ok(Math.abs(body.positionM[1] - height) <= 1e-10);
    assert.ok(Math.abs(body.velocityMps[1]) <= 1e-10);
  }
} finally { world.dispose(); }

This executable example covers two aligned2kg cubes, a prescribed static floor, gravity−9.81m/s², zero restitution/friction and a1/120s step. The32/256-step Source and actual compiled World checks pass the unchanged independent global projection and1e-12m representative-geometry gates. The original step27 failure is preserved. Actual restore/continuation, failure recovery and same-Native desktop rendering also pass, with separate receipts in Physics verification. Admission alone does not qualify arbitrary mass ratios, tilted boxes, friction, simultaneous elastic impact or moving eight-body stacks. The island prepares every body's tensor. Its historical rotated-anisotropic precontact refusal is preserved. The later symmetric tensor construction passes the bounded precontact cases below; this does not qualify general tilted contact. The isolated rotor example further below uses rigid-discrete-v1 and has separate G1 evidence.

The same World also passes the aligned three-cube/floor case within the existing four-body cap. Lower and middle supports start at step1; the falling top joins the chain at27. Source/compiled256-step results pass an independent3DOF global reference and actual same-Native desktop state/word/pixel checks. This extends the stated equal2kg, zero-friction/restitution120Hz family only.

mjs
const chain = structuredClone(model);
chain.revision = 'docsThreeCubes1';
chain.bodies.find(body => body.id === 'upper').initial.positionM[1] = 2.75;
chain.bodies.push(cube('middle', 1.5));
chain.colliders.push({ ...structuredClone(chain.colliders[0]),
  id: 'hull:middle', bodyId: 'middle' });
const world = createPhysicsWorld(chain, options);
try {
  for (let i = 0; i < 32; i++) world.step([]);
  const state = world.getState();
  assert.equal(state.stepIndex, 32);
  assert.equal(state.contacts.length, 3);
  for (const [id, height] of [['lower', 0.5], ['middle', 1.5], ['upper', 2.5]]) {
    const body = state.bodies.find(value => value.id === id);
    assert.ok(Math.abs(body.positionM[1] - height) <= 1e-10);
    assert.ok(Math.abs(body.velocityMps[1]) <= 1e-10);
  }
} finally { world.dispose(); }

The numerical case has0 restore calls; earlier two-cube recorder restoration is separate evidence. General four-body topology and moving8 remain unqualified.

Rotated noncubic box before contact ​

The same rigid-persistent-box-v1 World now advances the original rotated 2 kg box without its old precontact tensor-symmetry refusal. Primitive COM, direct broad phase and existing limits remain. This executable example runs a single noncubic box for 12 contact-free steps:

mjs
const model = orientationXYZW => ({
  format: 'barocss-physics-model', version: 1, revision: 'docsAnisotropic1',
  frame: { id: 'world', basis: 'right-handed-xyz', rotation: 'local-to-world-xyzw' },
  units: { length: 'm', mass: 'kg', time: 's', angle: 'rad' },
  gravityMps2: [0, -9.81, 0],
  bodies: [{ id: 'box', kind: 'dynamic', massKg: 2,
    inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' },
    initial: { positionM: [0, 5, 0], orientationXYZW,
      velocityMps: [0, 0, 0], angularVelocityRadps: [0, 0, 0] } }],
  colliders: [{ id: 'boxHull', bodyId: 'box',
    geometry: { kind: 'box', halfExtentsM: [0.25, 0.5, 0.75] },
    local: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1] },
    material: { restitution: 0, friction: { static: 0, dynamic: 0 } },
    sensor: false, ccd: false, filter: { categoryBits: 1, maskBits: 65535 } }],
  joints: [], cloths: [], fluids: [], sourceBindings: [],
});
const options = { profile: 'rigid-persistent-box-v1', fixedStepSeconds: 1 / 120, broadPhase: 'direct' };

A world-frame angular impulse acts once. The example maps body X to world Y and checks the analytic principal-axis speed of 3/13 rad/s:

mjs
const world = createPhysicsWorld(model([0, 0, Math.SQRT1_2, Math.SQRT1_2]), options);
try {
  world.step([{ kind: 'angularImpulse', bodyId: 'box', angularImpulseNms: [0, 1 / 8, 0] }]);
  for (let n = 1; n < 12; n++) world.step([]);
  const state = world.getState(), body = state.bodies[0];
  // Body X is world Y in this initial pose. I_x = 13/24 kg·m².
  assert.ok(Math.abs(body.angularVelocityRadps[1] - 3 / 13) <= 1e-10);
  assert.equal(state.stepIndex, 12);
  assert.equal(state.contacts.length, 0);
} finally { world.dispose(); }

Separate Source/actual compiled verification uses a lower cube and floor as well: 64-step natural and principal-spin cases, both at three matched-time step sizes, rollback/restore and actual desktop state-word/GPU checks pass. Upper clearance stays positive. This proves precontact motion and selected lower-floor support, not anisotropic impact, general contact or friction. Continuous gravity position error at 64/120 s is 0.0218 m; dt refinement confirms first-order kick-drift. See verification.

Isolated noncubic rotor ​

The common World accepts primitive-COM noncubic boxes within the existing mass, dimension, pose and fixed-step ranges. There is no literal rotor whitelist or one-step horizon. Sphere, cube and capsule inertia use the same angular flow; capsules now use uniform-volume cylinder and hemisphere moments about their COM. Existing contact, joint and CCD admission limits remain separate.

Use freeModel() and worldOptions from the overview with this example. Its mass, half extents and loads are sample values, not required constants:

mjs
const isolatedRotorModel = () => ({
  ...freeModel([0, 0, 0]), revision: 'docsRotor1',
  bodies: [{ id: 'rotor', kind: 'dynamic', massKg: 1,
    inertia: { kind: 'primitive-com', about: 'com', frame: 'body-local' },
    initial: { positionM: [0, 0, 0], orientationXYZW: [0, 0, 0, 1],
      velocityMps: [0, 0, 0], angularVelocityRadps: [1, 1, 1] } }],
  colliders: [{ ...freeModel().colliders[0], id: 'rotorHull', bodyId: 'rotor',
    geometry: { kind: 'box', halfExtentsM: [0.1, 0.2, 0.3] } }],
});

J acts once at step start. World-frame torque acts continuously during that step and expires. The next call advances the same World and configured clock:

mjs
const world = createPhysicsWorld(isolatedRotorModel(), worldOptions);
try {
  const accepted = world.step([
    { kind: 'angularImpulse', bodyId: 'rotor', angularImpulseNms: [1 / 1024, -1 / 2048, 1 / 4096] },
    { kind: 'torque', bodyId: 'rotor', torqueNm: [1 / 128, -1 / 256, 1 / 512] },
  ]);
  assert.equal(accepted.stepIndex, 1);
  const continued = world.step();
  assert.equal(continued.stepIndex, 2);
  near(continued.timeSeconds, 2 * dt);
  assert.notDeepEqual(continued.bodies[0].orientationXYZW, accepted.bodies[0].orientationXYZW);
  near(continued.bodies[0].orientationXYZW.reduce((sum, x) => sum + x * x, 0), 1);
  assert.ok(continued.bodies[0].angularVelocityRadps.every(Number.isFinite));
  assert.deepEqual(world.getState(), continued);
} finally { world.dispose(); }

The free solver uses eighth-order geometric composition. Constant-torque integration uses eighth-order modified-midpoint extrapolation. A priori subdivisions are capped at64; finite-arithmetic, movement or conditioning failures return NUMERIC_LIMIT without committing state or recording. This cap is not a change to contact iterations or physical tolerances.

See Physics verification for the measured profiles and preserved initial failures. Long-time conservation does not prove long-time phase accuracy. No integrator option or compatibility World exists.

Use the selected disjoint-hinge model ​

Both directed pairs have local anchors [0.1,0,0] and [-0.1,0,0] m. The centres are [-0.1,0,0], [0.1,0,0], [-0.1,0,1] and [0.1,0,1] m. Initial quaternions must be exactly [+0,+0,+0,1]; normalization aliases and negative-zero quaternion components refuse. No body is shared between joints. The existing common World owns both pairs and one accepted clock.

mjs
const disjointHingeModel = () => {
  const model = freeModel([0, 0, 0]);
  model.revision = 'docsHinge2';
  const ids = ['pairA0', 'pairB0', 'pairA1', 'pairB1'];
  model.bodies = ids.map((id, index) => ({ ...freeBody(), id, massKg: 1,
    initial: { positionM: [index % 2 === 0 ? -0.1 : 0.1, 0, Math.floor(index / 2)],
      orientationXYZW: [0, 0, 0, 1], velocityMps: [0, 0, 0], angularVelocityRadps: [0, 0, 0] } }));
  model.colliders = ids.map(id => ({ ...freeModel().colliders[0], id: `collider:${id}`, bodyId: id,
    material: { restitution: 0, friction: { static: 1, dynamic: 0.7 } } }));
  model.joints = [0, 1].map(index => ({ id: `hinge${index}`, kind: 'hinge',
    bodyAId: ids[index * 2], bodyBId: ids[index * 2 + 1],
    anchorALocalM: [0.1, 0, 0], anchorBLocalM: [-0.1, 0, 0], axisWorld: [0, 0, 1],
    limitRad: [-0.8, 0.8],
    motor: { targetSpeedRadps: 0.5, maxImpulseNms: 0.0001, maxReactionNms: 0.01 } }));
  return model;
};

Use the imports and worldOptions from the overview. The helper above also uses its freeModel() and freeBody() data builders. Empty arrays are the supported command input for this profile. Nonempty angular commands along the axis also refuse. Do not substitute a prescribed motion path.

mjs
const world = createPhysicsWorld(disjointHingeModel(), worldOptions);
try {
  world.step([]);
  const state = world.step([]);
  assert.equal(state.stepIndex, 2);
  assert.equal(state.timeSeconds, 2 / 120);
  assert.equal(state.joints.length, 2);
  assert.equal(state.contacts.length, 0);
} finally { world.dispose(); }

This short example verifies API use. The separate original 1,200-step campaign and its precise source/emitted boundaries are in verification. It does not establish arbitrary joint networks, contact coupling, a convergence order, cross-runtime equality or measured machine accuracy.

Rigid input bounds ​

The model declares all entity arrays, including empty joints, cloths, fluids and sourceBindings. Rigid profiles refuse nonempty cloth/fluid arrays. Each rigid body has exactly one collider with an identity local transform. ccd, sensor flags, geometry, material and collision filters belong to the collider. The body declares mass/inertia for dynamics and its explicit initial state. State carries numerical motion; read copied getModel() data for initial conditions, collider geometry and source bindings.

Body IDs are unique ASCII identifiers with at most 64 characters and a starting letter. Each position component is within ±10000 m. Velocity components are within ±1000 m/s and gravity components within ±1000 m/s². Mass is 1e-6–1e6 kg. Sphere radius, box half extents and capsule length parameters are 1e-4–1000 m. Restitution is 0–1. Explicit material friction satisfies 0 <= dynamic <= static <= 2; supply both coefficients, including zero values.

A step accepts at most 64 dense plain-object commands. Each body can receive one command of each applicable kind. Force and torque components are bounded by ±1e6 N or N·m; linear and angular impulse components by ±1e5 N·s or N·m·s. Angular velocity components are within ±1000 rad/s. A candidate refuses movement or measured penetration above 10 m, or angular displacement above 10 rad per step. Limits are numerical guards, not recommended physical operating conditions.

Visual domains, recording and independent helpers ​

Cloth and fluid use the root common World. They share its fixed clock, candidate commit and idempotent disposal. Their selected profiles admit one domain plus fixed static colliders. They refuse dynamic mixtures and do not exchange forces with moving rigid bodies or with each other. The old domain factory subpaths are removed. CAD data admission is not another simulation owner.

Entry and selectionStep and capacityBoundary
Root World, fluid-basin-visual-v1 or fluid-basin-xsph-visual-v1Exactly256 particles in a0.7 ×1.3 ×0.5m basin;1/120s;3600-step admission capQualified horizon720steps. XSPH coefficient0.15 is a visual parameter. No calibrated viscosity, emitters or moving obstacles.
Root World, cloth-pinned-sphere-visual-v1Fixed289vertices and512triangles;1/120s;240host stepsTwo pinned corners and one static sphere. No fabric calibration, self-collision, tearing or arbitrary mesh admission.
admitCadFluidStaticData, then root fluid-static-box-visual-v1Version1 water and one static axis-aligned CAD box proxyQualified horizon240steps. Caller checks exact current source/revision before stepping. No XSPH combination or moving CAD obstacle.
/replay512frames,4096total commands,128KiB canonical model and1MiB binary recording including8-byte magicBounded accepted rigid command log. Cloth attach refuses WORLD_LIMIT; fluid attach refuses INVALID_SNAPSHOT. No domain restore is qualified.
Independent example createPlanarPendulum, outside the public rootStep1e-6–1/30s; dt × natural frequency ≤0.05;1–1000000stepsOne reduced angle, velocity Verlet, no contacts, motors or damping. Pivot+Z, gravity−Y.
Root createUprightCapsuleQuery, upright-capsule-box-v10–32immutable static boxes; query displacement norm≤2mFixed upright capsule: radius0.15m, half segment0.35m. Scene box centres±10m, half extents0.0001–5m; query centres±5m. Query does not advance a World.
Root createUprightCapsuleController, upright-capsule-controller-v1Exactly1/120s; at most240stepsBounded capsule query,−Y gravity,0.002m skin,0.1m step limit and10°walkable slope. No general dynamic obstacles.

See the fixed visual model example and verification. An admission cap is separate from the executed horizon.

Own the clock and retain accepted state ​

PhysicsWorld.step(commands?) advances one configured step. It does not read wall time or change the step size to match display refresh. The host can accumulate elapsed display time and request whole fixed steps, subject to its own work budget. A dropped display frame does not authorize a larger Physics step.

getState() and successful step() return independent copies, including nested body vectors, contacts, events, joints, CCD hits and pair counts. Editing returned arrays does not edit the world. The world commits only an accepted candidate. An invalid command or numerical candidate leaves the last accepted state available. Do not hide refusal with an automatic retry or a changed gate.

mjs
const world = createPhysicsWorld(freeModel([0, 0, 0]), worldOptions);
const accepted = world.step();
assert.throws(() => world.step(dt / 2), hasCode('INVALID_COMMAND'));
assert.deepEqual(world.getState(), accepted);
accepted.bodies[0].positionM[0] = 999;
accepted.bodies[0].orientationXYZW[3] = 0;
const copied = world.getState();
const modelCopy = world.getModel();
modelCopy.bodies[0].initial.positionM[1] = 999;
near(world.getModel().bodies[0].initial.positionM[1], 2);
const hit = world.query({ kind: 'overlap-sphere', centerM: copied.bodies[0].positionM,
  radiusM: 0.01, includeSensors: false });
assert.deepEqual(hit, { kind: 'overlap-sphere', colliderIds: ['collider:ball'] });
assert.throws(() => world.query({ kind: 'overlap-sphere', centerM: [NaN, 0, 0],
  radiusM: 0.01, includeSensors: false }), hasCode('INVALID_QUERY'));
assert.deepEqual(world.getState(), copied);
near(copied.bodies[0].positionM[0], dt);
assert.deepEqual(copied.bodies[0].orientationXYZW, [0, 0, 0, 1]);
world.dispose();
world.dispose(); // Idempotent.
assert.throws(() => world.getState(), hasCode('DISPOSED'));
assert.throws(() => world.step(), hasCode('DISPOSED'));

This sample uses the imports, dt, worldOptions and freeModel() fixture shown on the overview. Its hasCode(code) helper accepts only error instanceof PhysicsError && error.code === code. The test checks refusal after one accepted step, edits returned data, then checks the retained world. dispose() is idempotent. Later reads, queries and steps give DISPOSED. The rigid world has no public reset or arbitrary state setter. Create a new world for a new initial condition.

Handle typed refusals ​

CodeCaller action
INVALID_CONFIGCorrect the input model or select a supported profile before creating another instance.
INVALID_STEPFor numerical helpers and independent reference APIs that take dt, supply their configured step. A numeric argument to common World step gives INVALID_COMMAND.
INVALID_COMMAND / INVALID_QUERYCorrect the command or query; do not alter accepted state to conceal the refusal.
WORLD_LIMITThe admitted step, frame or command budget is exhausted. Choose an explicit new session.
NUMERIC_LIMITStop advancing this model. Record the first failed input and the retained state before investigating.
STALE_SOURCERe-admit the CAD source/revision explicitly before replacing the binding.
WORLD_OWNEDAdvance through the attached recorder; reads and queries remain available.
STALE_SNAPSHOTModel, source, configuration or provider identity differs. Restore only against the intended matching identity.
INVALID_SNAPSHOTReject malformed, unsupported or damaged replay data.
INITIAL_OVERLAP / ITERATION_LIMITCapsule-query refusal: initial penetration or unresolved bounded search. This is not a partial valid sweep.
DISPOSEDCreate a new instance. A disposed object cannot resume.

State has identity, tagged query results use collider IDs, and bodies report orientationXYZW. Contacts use bodyAId, bodyBId, colliderAId, colliderBId, normalImpulseNs and tangentImpulseOnBNs. Joint reactions use linearImpulseOnBNs and angularImpulseOnBNms. PhysicsError.details identifies the operation, phase, domain, entity IDs and last accepted step/time.

Use PhysicsError.code for branching. Error messages supply context and are not a stable protocol. The root and its replay/CAD adapter entries share the error constructor within one installed package instance. Do not assume instanceof identity across versions, realms or separate source/compiled bundles.

Restore a command log, not arbitrary state ​

Attach createPhysicsRecorder(world) at step0, before any World step. The recorder supplies step(commands?), getState(), copied saveRecording() and dispose(). The configured dt owns time; step takes no step-size argument. A direct or cached world.step call and a second attachment refuse with WORLD_OWNED. World reads and queries remain available.

Recorder disposal detaches it without disposing the World. Dispose both objects when finished. World disposal invalidates its recorder. Disposal releases recording/options references; no garbage-collection timing or out-of-memory recovery guarantee follows. An advanced World cannot acquire a new recording history.

restorePhysicsRecording(recording,{model,options,providerDigest}) validates complete recording shape and bounds before expected model, configuration and provider identity. Source revisions are model sourceBindings data. Use the intended current World's getState().identity.providerDigest as the external expected provider digest. Restore reconstructs an isolated World, replays indexed accepted commands and compares final state at 1e-12 absolute/relative numeric tolerance. It returns {world,recorder} only on success. Dispose both objects. The command frame and log budgets are checked before candidate calculation. Final state, returned copy and complete bounded encoding are prepared before the nonthrowing shared physical/log commit. Changed identity gives STALE_SNAPSHOT; damaged data gives INVALID_SNAPSHOT.

Persist with serializePhysicsRecording(recording):Uint8Array and read with deserializePhysicsRecording(bytes). The wire format is ASCII BCPHREC1 followed by bounded canonical typed encoding. It preserves binary64 number bits, including -0. The decoder refuses JSON, unknown tags, nonfinite numbers, truncated/trailing bytes and unsupported versions. Record keys use canonical ASCII order; arrays retain their order. There is no old-version migration, arbitrary body-state import or bitwise cross-platform trajectory promise.

mjs
import { createPhysicsRecorder, restorePhysicsRecording,
  serializePhysicsRecording, deserializePhysicsRecording } from '@barocss/physics/replay';
mjs
const model = freeModel([-0, 0, 0]);
const world = createPhysicsWorld(model, worldOptions);
const session = createPhysicsRecorder(world);
const expected = { model, options: worldOptions, providerDigest: world.getState().identity.providerDigest };
let restored;
try {
  session.step([{ kind: 'impulse', bodyId: 'part:ball', impulseNs: [2, 0, 0] }]);
  const recording = session.saveRecording();
  const bytes = serializePhysicsRecording(recording);
  assert.equal(Buffer.from(bytes.subarray(0, 8)).toString('ascii'), 'BCPHREC1');
  const decoded = deserializePhysicsRecording(bytes);
  assert.ok(Object.is(decoded.model.gravityMps2[0], -0));
  restored = restorePhysicsRecording(decoded, expected);
  assert.deepEqual(restored.recorder.getState(), session.getState());
  assert.deepEqual(restored.recorder.step(), session.step());
  recording.frames[0].commands[0].impulseNs[0] = 999;
  near(session.saveRecording().frames[0].commands[0].impulseNs[0], 2);
  assert.throws(() => deserializePhysicsRecording(bytes.subarray(0, -1)), hasCode('INVALID_SNAPSHOT'));
} finally { restored?.recorder.dispose(); restored?.world.dispose(); session.dispose(); world.dispose(); }

P2_DONE_LOCALSELECTED: public source05/emitted05 pass11/11 each; test-only preparation faults pass15/15 each across four step preparation points plus attach output preparation, each in three rigid profiles. Native03 passes staged published maps, strict positive/negative declarations, shared ownership registry, CAD release consumer and four README blocks. Ordinary probes and foundation checks pass21 per source/emitted graph; documentation samples pass174/174 in run03. Final recording callers pass3 per graph; documentation build/site/link receipts are docs-check/build/links-01. Historical P1b receipts apply only to their original providers. Whole-engine acceptance remains NO_GO.

Keep a source-run receipt separate from a compiled-consumer receipt. Workspace aliases can resolve source even after a build. A compiled check must resolve each transitive package through its published entry map; the compiled root also needs sibling dist/types.js. See Physics verification for provenance and the accepted evidence stages. Neither replay equality nor a plausible animation validates contact loads, control hardware or manufacturing.