@margoengine/physics2d 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,521 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @margoengine/physics2d
2
+
3
+ Import `margoengine/physics2d` from the `margoengine` package, or `@margoengine/physics2d` from this package alone; the two are the same module. Neither is on npm yet: the [Install](../../README.md#install) section lists the two routes that work today (run in a clone, or install local tarballs).
4
+
5
+ 2D rigid-body physics for Margo Engine on its own 2D kernel (Rust compiled to Wasm with SIMD): a fixed-step engine plugin with interpolation, bodies that drive sprites, box, circle, capsule, polygon (convex or concave) and polyline colliders, joints, scene queries, collision and contact force events, sensors, collision groups, continuous collision, a character controller and tile map colliders in one call. Nothing else to install: the kernel's WebAssembly is a file of this package, `dist/physics2d.wasm`.
6
+
7
+ World units are sprite pixels, y points down and angles are radians, clockwise on screen. `pixelsPerMeter` (default 32) maps them to the kernel's metres, so a 16 pixel tile is half a metre. Mass, density, force and impulse use kernel units (kilograms, metres, seconds).
8
+
9
+ ```ts
10
+ import {Physics2D} from 'margoengine/physics2d';
11
+
12
+ await Physics2D.load();
13
+ const physics = new Physics2D(null); // or new Physics2D(engine, ...) to step with the engine
14
+
15
+ // A tile map: tiles with collision shapes (or a `solid: true` property) become one fixed body.
16
+ physics.addTileMap({
17
+ tileWidth: 16, tileHeight: 16,
18
+ tilesets: [{firstGid: 1, tileCount: 1, tileWidth: 16, tileHeight: 16, tiles: [{id: 0, properties: {solid: true}}]}],
19
+ layers: [{type: 'tile', name: 'ground', width: 8, height: 4, data: new Uint32Array(32).fill(1, 24)}],
20
+ });
21
+
22
+ // A body that drives a sprite: each frame the interpolated pose is written to sprite.x, sprite.y and sprite.rotation.
23
+ const sprite = {x: 64, y: 0, rotation: 0};
24
+ const crate = physics.addBody(sprite, {colliders: {shape: 'box', width: 16, height: 16, restitution: 0.2}});
25
+ physics.on('contactstart', ({bodyA, bodyB}) => {});
26
+ physics.update(1 / 60); // or let the engine call it every frame
27
+ crate.applyImpulse([0, -2]);
28
+ physics.raycast([64, 0], [0, 1])?.point;
29
+
30
+ // A hinge with limits, and a character on a kinematic body.
31
+ const pole = physics.addBody(null, {type: 'fixed', position: [32, 8], colliders: []});
32
+ physics.addJoint(pole, crate, {type: 'revolute', anchorB: [-8, 0], limits: [-1, 1]});
33
+ const hero = physics.addBody({x: 20, y: 40, rotation: 0}, {type: 'kinematicPosition', colliders: {shape: 'capsule', radius: 5, height: 20}});
34
+ const controller = physics.createCharacterController(hero, {snapToGround: 2});
35
+ physics.on('beforestep', dt => controller.move([60 * dt, 200 * dt]));
36
+ ```
37
+
38
+ It exports `Physics2D`, `Body2D`, `Joint2D`, `CharacterController2D`, `interactionGroups` and `tileMapColliders`, the collider list `addTileMap` builds. `addTileMap` accepts a `TileMapData` from `@margoengine/tilemap`, or any object of the `TileMapSource` shape. Whole-cell solid tiles merge into outline loops so bodies slide across tile seams without catching; other collision shapes (rectangles, ellipses, polygons, polylines), tile flips and layer offsets are kept. Very fast bodies on a tile map need `ccd: true`, because outlines have no thickness.
39
+
40
+ **One load per app.** `await Physics2D.load()` compiles the kernel, then `new Physics2D(engine)` stays synchronous. Later calls resolve at once, calls during a load share it, a failed load is tried again by the next call, and `{signal}` stops one caller's wait; when no other call waits on the load, it also cancels the download. The loader is a dynamic import and the Wasm a separate file (`dist/physics2d.wasm`) that bundlers emit as an asset and the browser compiles while it downloads when served as `application/wasm`. `{wasm}` points at another copy: a URL (your server or a CDN), a fetched `Response`, its bytes or a compiled `WebAssembly.Module`. It must be the bundled build; any other Wasm rejects with a `MargoError` of code `failed`, as does a missing file, and nothing is loaded. The package carries two builds of the kernel, each a file of its own: `dist/physics2d.wasm` with Wasm SIMD and `dist/physics2d-scalar.wasm` for engines that cannot compile it. `Physics2D.load()` probes the engine and fetches the one it can run (`load({simd: false})` forces the scalar one, to test it; `wasm` still names any file yourself, and a page then loads whichever you name). They are one kernel and step a world to the same bits, which a test holds on the hash of a 600-step world's snapshot; the scalar build takes its square roots from integer arithmetic that matches the hardware instruction bit for bit, and is larger and slower, never different.
41
+
42
+ ```ts
43
+ import {Physics2D} from '@margoengine/physics2d';
44
+
45
+ // The package's own copy found through Node's resolver; in a page, pass the URL your server or CDN serves it from.
46
+ const wasm = new URL('physics2d.wasm', import.meta.resolve('@margoengine/physics2d'));
47
+ await Physics2D.load({wasm, signal: AbortSignal.timeout(30_000)});
48
+ const physics = new Physics2D(null, {gravity: [0, 320]});
49
+ physics.dispose();
50
+ ```
51
+
52
+ `body.maxAngularSpeed` caps a body's spin (default 0, none: Rapier's default cap, which its `allowFastRotation` lifts, is not needed because a fast spinner with `ccd` is swept along its turn). `physics.setSolver({ maxCcdSubsteps: n })` lets a `ccd` body keep going after an impact inside one step, up to `n` impacts (default 1: it stops where it touches; 0 turns continuous collision off). `body.additionalSolverIterations = n` gives the body's island `n` more substeps each step (Rapier's `additional_solver_iterations`: solved as a world at that substep count would solve it, the other islands untouched). `body.additionalPgsIterations = n` gives the body's island `n` more solver passes each substep over its own contacts and joints (Rapier's `additional_pgs_iterations`; the island runs the most any of its awake bodies asks for, no other island is touched, and with none asking the step is unchanged). `body.enabled = false` takes a body out of the simulation (it keeps its pose and velocity, touches nothing, no query finds it, its joints rest) and `true` puts it back. `body.setAdditionalMassProperties(mass, centre, inertia)` adds a solid to what the colliders weigh by the parallel axis theorem (the older `additionalMass` adds in proportion), and `raycastAll(origin, direction)` lists every collider a ray meets, nearest first, and a filter's `excludeCollider` leaves one collider out where `exclude` leaves a body. Queries (`raycast`, `overlapPoint`, `overlapShape`, `castShape`) see every collider added or moved since the last step, and a `teleport` or `moveTo` at once. `castShape` and `overlapShape` take a box, circle, capsule, segment or a convex polygon of at most 8 points.
53
+
54
+ Apache-2.0. Optional, tree-shakable package; core peer: ^1.0.0. The kernel is Margo's own, written from papers (`docs/clean-room.md`); it holds no third-party code.
55
+
56
+ Build and unit tests: npm test --workspace @margoengine/physics2d
57
+
58
+ ## Parity with Rapier 2D
59
+
60
+ `Physics2D` runs on Margo's own 2D kernel (`kernel/`, Rust to Wasm); it no longer uses Rapier. The capabilities below are listed from Rapier 2D's public user guide (rapier.rs/docs), never from its source. Status: **full** (kernel, facade and a test), **partial** (what is missing is named), **missing**. Docs: [limits](../../docs/limits.md), [known bugs](../../docs/known-bugs.md).
61
+
62
+ | Area | Rapier 2D capability | Where in Margo | Status |
63
+ | --- | --- | --- | --- |
64
+ | Shapes | ball, cuboid, capsule, segment | `box`, `circle`, `capsule`, `segment` colliders | full |
65
+ | Shapes | convex polygon, convex decomposition of concave or large input | `polygon` (convex hull to 8 corners; concave or larger split by ear clipping and Hertel-Mehlhorn) | full |
66
+ | Shapes | polyline | `polyline` (chains with ghost vertices: bodies slide over the joins) | full |
67
+ | Shapes | triangle, round (border radius) cuboid, triangle and convex polygon, trimesh with its flags | `triangle`, `borderRadius` on `box`, `polygon` and `triangle`, `trimesh` (triangles by index, `fixInternalEdges` and the clean-up flags) | full |
68
+ | Shapes | heightfield, halfspace, compound, voxels, shared shapes | `heightfield` (a smooth chain), `halfspace` (a polygon 200,000 units across), `compound` (parts with their own placement), `voxels` (merged outlines for contact, the cells themselves for queries); shape options are plain values, so one can be reused on any number of colliders | full, with the accepted differences in limits |
69
+ | Shapes | oriented (one-sided) polyline | `polyline` with `oneSided: true` | full |
70
+ | Collision | broad phase, narrow phase, manifolds, islands, sleeping | kernel box tree, SAT and clipping, SIMD solver | full |
71
+ | Collision | continuous collision detection | `ccd` against fixed, kinematic and dynamic bodies (a dynamic one it meets is put back to the same time) | full |
72
+ | Collision | soft CCD (a prediction distance per body) | `softCcd` (world units a body's contacts reach ahead) | full |
73
+ | Collision | sensors | `sensor: true` (senses fixed and kinematic bodies too) | full |
74
+ | Collision | collision groups, solver groups, active collision types | `collisionGroups`, `solverGroups`, `activeCollisionTypes` | full |
75
+ | Collision | collision events, contact force events | `contactstart`, `contactend`, `intersectionstart`, `intersectionend`, `contactforce` (`contactForceThreshold`) | full |
76
+ | Collision | physics hooks (filter and modify contact pairs, one-way platforms) | `physics.hooks = {filterPair, filterIntersection, modifyContact}` for colliders with `hooks` set (`filterPair` for a pair of solids, `filterIntersection` for a pair with a sensor in it; `collider.setActiveHooks` changes what a collider asks); `oneWay`, `friction`, `restitution`, `tangentVelocity` (conveyors), `solverActive` per contact | full |
77
+ | Queries | ray cast with normal (solid or not), every hit along a ray (`raycastAll`, nearest first), point, shape intersection, shape cast, project point, box intersection, filters | `raycast`, `overlapPoint`, `overlapShape`, `castShape`, `projectPoint`, `intersectionsWithBox`, `QueryFilter2D` | full |
78
+ | Queries | contact pairs of a collider, the contact between two colliders, intersection pairs of sensors | `contactPairs(collider)`, `contactPair(a, b)`, `intersectionPair(a, b)`, `intersectionPairsWith(collider)` | full |
79
+ | Bodies | dynamic, fixed, kinematic position, kinematic velocity | `type` | full |
80
+ | Bodies | damping, gravity scale, locked rotation, can sleep, dominance, body type changes | `BodyOptions2D`, the same names as setters on `Body2D`, `setType` | full |
81
+ | Bodies | forces, torques, impulses (at the centre or a point), forces at a point, resetting the torque or both, velocities, wake and sleep | `applyForce`, `applyForceAtPoint`, `applyTorque`, `applyImpulse`, `applyImpulseAtPoint`, `applyTorqueImpulse`, `resetForces`, `resetTorques`, and the velocity setters | full |
82
+ | Bodies | additional mass | `additionalMass` | full |
83
+ | Bodies | locked translation axes, locked rotation after creation | `lockTranslation` (an exact joint constraint that follows teleports), `lockRotation(locked)` | full |
84
+ | Colliders | collision types, events and the contact force threshold, changed after creation | `setActiveCollisionTypes`, `setActiveEvents`, `setContactForceEventThreshold` and their readers | full |
85
+ | Bodies | soft CCD | none | missing |
86
+ | Joints | fixed, revolute, prismatic, rope, spring, limits, motors in the force or the acceleration model (`motor: {model}`; the force model is the default, the acceleration model per unit of effective mass so a light body and a heavy one follow it alike), contacts between jointed bodies | `addJoint` | full |
87
+ | Joints | generic joint (any mix of the x, y and angle locks, in turned frames), pin-slot | `type: 'generic'`, `type: 'slot'` | full |
88
+ | Joints | multibody joints: joint space, joint motors and limits, kinematics, inverse kinematics | `addArticulation` (`Articulation2D`: positions and velocities, motors, limits, forward and inverse kinematics, Jacobian) over exact maximal-coordinate trees: chains and branched trees solve in one sweep, so a 1000:1 mass ratio across a branch keeps every joint closed | full, see limits |
89
+ | Tools | PID controller | `PidController2D` | full |
90
+ | Character | kinematic character controller: slide, autostep (`maxHeight`, `minWidth`, `includeDynamic`), snap to ground, slope climb and slide, push dynamic bodies, up vector, a query filter (`filter` option, `move(delta, filter)`) | `createCharacterController` | full |
91
+ | World | fixed timestep, interpolation, determinism (bit-identical native and Wasm) | `Physics2D`, kernel tests | full |
92
+ | World | snapshots (serialise and restore the world) | `snapshot()`, `restore()`: a restored world steps bit for bit as the original | full |
93
+ | World | debug render data: shapes, joints, contacts, boxes, body axes, solver contacts, a colour style (`rgba` a line) and a body filter | `debugRender({axes, solverContacts, style, filter})` | full |
94
+ | Tools | tile map and sprite outline colliders | `addTileMap`, `outlineColliders` | full |
95
+
96
+ ## Lists of what a world holds
97
+
98
+ `physics.getBodies()`, `getColliders()` and `getJoints()` list what the world holds (bodies and joints in the order they were added, colliders in the order their shapes were made), and `bodyCount`, `colliderCount` and `jointCount` count them; a removed body leaves the lists with its colliders and joints. Any number of worlds run side by side in the one Wasm instance, each with its own `name` and nothing shared:
99
+
100
+ ```ts
101
+ import {Physics2D} from 'margoengine/physics2d';
102
+
103
+ await Physics2D.load();
104
+ const earth = new Physics2D(null, {gravity: [0, 400]});
105
+ const moon = new Physics2D(null, {gravity: [0, 40], name: 'moon'});
106
+ const stone = earth.addBody(null, {colliders: {shape: 'circle', radius: 1}});
107
+ moon.addBody(null, {colliders: {shape: 'circle', radius: 1}});
108
+ earth.step();
109
+ moon.step();
110
+ console.log(earth.bodyCount, moon.bodyCount, earth.getColliders().length, stone.position[1] > 0); // 1 1 1 true
111
+ earth.dispose();
112
+ moon.dispose();
113
+ ```
114
+
115
+ ## Solver settings
116
+
117
+ `physics.setSolver(options)` changes the solver and `physics.solver` reads it, with the names the 3D world uses: `substeps` a step (default 4), `iterations` (pushing passes a substep, each followed by as many relaxing ones, default 1), the contact spring `contactHertz` and `contactDamping`, `contactMaxPush` (the fastest a depth is pushed out), `restitutionThreshold` (under this approach speed a contact does not bounce), `sleepThreshold` and `sleepTime` with `canSleep`, `blockSolver` (Rapier's block solver: the two points of a contact solved together as one 2 by 2 problem, on by default; off, one point at a time), the joint spring `jointHertz`, `jointDamping`, `jointMaxPush` with `jointGeometricStiffness`, `maxCcdSubsteps` (how many impacts continuous collision handles in a step: default 1, 0 for off; see below), the sweep's `minCcdDt`, `ccdTolerance` and `ccdMaxAdvances` with the 3D world's names and meanings, `warmStart` (the share of last step's contact impulses a step starts from, 0 to 1, default 1), `allowedPenetration` (how deep a contact may overlap before it is pushed apart, default 0), `predictionDistance` (how far apart two colliders get contact points, default 2 cm) and a contact spring for contacts with fixed and kinematic bodies, `staticContactHertz` and `staticContactDamping` (default `null`: the contact spring; a softer one lets bodies settle into the ground while stacks keep the stiff spring). Speeds and distances are in world units. A name left out keeps its value, and a refused one (a count that is not a whole number from 1 to 65535 (0 to 65535 for `maxCcdSubsteps`), a negative or non-finite number, a `warmStart` outside 0 to 1) throws a `RangeError` and changes nothing. The settings are part of a snapshot.
118
+
119
+ ```ts
120
+ import {Physics2D} from 'margoengine/physics2d';
121
+
122
+ await Physics2D.load();
123
+ const physics = new Physics2D(null);
124
+ physics.addBody(null, {type: 'fixed', position: [0, 100], colliders: {shape: 'box', width: 1000, height: 20}});
125
+ physics.addBody(null, {position: [0, 80], colliders: {shape: 'box', width: 20, height: 20}});
126
+ physics.setSolver({substeps: 8, blockSolver: false, allowedPenetration: 0.5, staticContactHertz: 10});
127
+ for (let i = 0; i < 30; i++) physics.step();
128
+ const {substeps, blockSolver, staticContactDamping} = physics.solver;
129
+ console.log(substeps, blockSolver, staticContactDamping, physics.counts.blockSolves); // 8 false null 0
130
+ physics.dispose();
131
+ ```
132
+
133
+ ## Casts, projections and continuous collision
134
+
135
+ `castShape(shape, position, direction, maxDistance, filter, rotation, {targetDistance, stopAtPenetration})` slides a shape until it is `targetDistance` from a collider (default 0: touching) and returns the hit with the closest points of both shapes (`witnessA`, `witnessB`), their normals, the `gap` between them and a `status`; with `stopAtPenetration` false, a collider the shape already overlaps and is leaving is not a hit. `projectPoint(point, filter, solid)` puts a point inside a collider on its own spot (`solid`, the default) or on the nearest point of its surface. A body with `ccd` is stopped by what it would pass through in a step; `setSolver({maxCcdSubsteps: n})` lets it bounce off up to `n` impacts inside one step.
136
+
137
+ ```ts
138
+ import {Physics2D} from 'margoengine/physics2d';
139
+
140
+ await Physics2D.load();
141
+ const physics = new Physics2D(null, {gravity: [0, 0], pixelsPerMeter: 1});
142
+ physics.addBody(null, {type: 'fixed', position: [0, 0], colliders: {shape: 'box', width: 20, height: 2}});
143
+ const hit = physics.castShape({shape: 'circle', radius: 0.5}, [0, 5], [0, -1], 20, undefined, 0, {targetDistance: 0.25});
144
+ console.log(hit?.distance, hit?.gap); // 3.25 0.25: stopped a quarter above the box's top face
145
+ console.log(physics.projectPoint([0.5, 0.2], undefined, false)?.point); // [0.5, 1]: the top face, not the point itself
146
+ physics.dispose();
147
+
148
+ // A ball at 1000 m/s between two thin walls 6 m apart: with 4 impacts a step it bounces three times inside the one step.
149
+ const corridor = new Physics2D(null, {gravity: [0, 0], pixelsPerMeter: 1});
150
+ for (const x of [-3, 3]) corridor.addBody(null, {type: 'fixed', position: [x, 0], colliders: {shape: 'box', width: 0.1, height: 10, restitution: 1}});
151
+ corridor.setSolver({maxCcdSubsteps: 4});
152
+ const ball = corridor.addBody(null, {ccd: true, linearVelocity: [1000, 0], colliders: {shape: 'circle', radius: 0.1, restitution: 1}});
153
+ corridor.step();
154
+ console.log(Math.round(ball.position[0] * 10) / 10, ball.linearVelocity[0]); // 0.4 -1000: now going left
155
+ corridor.dispose();
156
+ ```
157
+
158
+ ## What a step did and how long it took
159
+
160
+ `physics.counts` reads the work the last step did as whole numbers that do not depend on the machine: `awake` bodies, `islands` (groups of dynamic bodies with an awake body in them; a fixed body is no island and a sleeping group is no work), `boxesCompared`, `pairs`, `manifolds`, `coldPoints` (manifold points that found no point in the last manifold and start with no impulse), `contactsSolved`, `blockSolves` and `sequentialSolves` (two-point contacts solved together or one point at a time), `colours` and `uncoloured`, `treeJoints`, `events` and `steps`. `physics.timing` reads how long the phases took in milliseconds, Rapier's `timingStep` and its siblings: `step` is the whole of it, then `begin`, `broad`, `narrow`, `islands`, `solver`, `ccd` and `events`, which add up to it; `assembly`, `resolution`, `update` and `writeback` split `solver` and `ccdBroad`, `ccdToi` and `ccdSolver` split `ccd`, as sums over the substeps and the bodies. Everything reads zero before the first step. The clock is not part of the world: a snapshot and the replay hash leave timings out, and two worlds built the same way give the same counts.
161
+
162
+ ```ts
163
+ import {Physics2D} from 'margoengine/physics2d';
164
+
165
+ await Physics2D.load();
166
+ const physics = new Physics2D(null);
167
+ physics.addBody(null, {type: 'fixed', position: [0, 100], colliders: {shape: 'box', width: 1000, height: 20}});
168
+ for (let i = 0; i < 4; i++) {
169
+ physics.addBody(null, {position: [0, 70 - i * 21], colliders: {shape: 'box', width: 20, height: 20}});
170
+ }
171
+ for (let i = 0; i < 30; i++) physics.step();
172
+ const {awake, islands, contactsSolved, steps} = physics.counts;
173
+ console.log(awake, islands, contactsSolved > 0, steps); // 4 1 true 30
174
+ console.log(physics.timing.step >= physics.timing.solver); // true
175
+ physics.dispose();
176
+ ```
177
+
178
+ ## Triangle meshes
179
+
180
+ A `trimesh` collider takes triangles by index into its vertices. Each triangle collides alone, so a body sliding over the
181
+ edge two triangles share can catch on it; `fixInternalEdges: true` joins them into one solid for contacts (Rapier's
182
+ `TriMeshFlags.FIX_INTERNAL_EDGES`, which in Rapier 2D changes nothing: its box catches on the same strip with the flag or
183
+ without it). A shared edge then makes no contact, and a contact on a triangle takes only the normals the mesh's outline has
184
+ there, so boxes and balls slide across the joins and still meet the mesh's real corners. Shared edges are found by exact
185
+ positions. The clean-up flags run first, in Rapier's order: `mergeDuplicateVertices`, `deleteDegenerateTriangles` (a flat
186
+ triangle otherwise collides along its line, as in Rapier), `deleteDuplicateTriangles` and `deleteBadTopologyTriangles`.
187
+ All are off by default.
188
+
189
+ ```ts
190
+ import { Physics2D } from '@margoengine/physics2d';
191
+
192
+ await Physics2D.load();
193
+ const physics = new Physics2D(null, { pixelsPerMeter: 100 });
194
+ const vertices: [number, number][] = [],
195
+ indices: number[] = [];
196
+ for (let i = 0; i <= 20; i++) vertices.push([i * 50, 0], [i * 50, 100]);
197
+ for (let i = 0; i < 20; i++) indices.push(2 * i, 2 * i + 1, 2 * i + 2, 2 * i + 1, 2 * i + 3, 2 * i + 2);
198
+ physics.addBody(null, { type: 'fixed', colliders: { shape: 'trimesh', vertices, indices, friction: 0, fixInternalEdges: true } });
199
+ const box = physics.addBody(null, {
200
+ position: [30, -10],
201
+ linearVelocity: [200, 0],
202
+ colliders: { shape: 'box', width: 20, height: 20, friction: 0 },
203
+ });
204
+ for (let i = 0; i < 120; i++) physics.step();
205
+ console.log(Math.round(box.linearVelocity[0]), Math.abs(box.rotation) < 0.05); // 200 true
206
+ physics.dispose();
207
+ ```
208
+
209
+ ## Vehicles (`@margoengine/physics2d/vehicle`)
210
+
211
+ `new Vehicle2D(physics, chassis, { wheels })` is Rapier's ray cast vehicle seen from the side: a hill-climb car, a cart or
212
+ a truck. Each wheel casts a ray from its `position` on the chassis along its `direction` (default down on screen); a
213
+ spring (`suspensionStiffness`, default 5.88 as Rapier's) and dampers (`suspensionCompression` 0.83, `suspensionRelaxation`
214
+ 0.88) on the suspension (`suspensionRestLength` default 0.3 m, `maxSuspensionTravel` 5 m, `maxSuspensionForce` 6000 N) hold
215
+ the chassis up, and the tyre drives and brakes along the ground inside what its load can hold (`frictionSlip`, default
216
+ 10.5). `engineForce` and `brake` (newtons per wheel, or `setInput({ throttle, brake })` against `maxEngineForce` and
217
+ `maxBrakeForce`) drive it; `speed` is the chassis's speed along `forward` (Rapier's `currentVehicleSpeed`), and
218
+ `vehicle.wheel(i)` gives `inContact`, `contactPoint`, `contactNormal`, `ground`, `hardPoint`, `suspensionLength`,
219
+ `suspensionForce`, `forwardImpulse` and the wheel's `rotation`; `wheelCenter(i)` is where to draw it. The pushes are held on
220
+ the chassis (and on a dynamic body under a wheel, unless `groundReaction: false`) as forces over each step, so they act in
221
+ every substep as gravity does. There is no steering and no sideways grip: in a side view the axle points out of the screen.
222
+ `body.inertia` reads a body's moment of inertia (Rapier's `principalInertia`).
223
+
224
+ ```ts
225
+ import { Physics2D } from '@margoengine/physics2d';
226
+ import { Vehicle2D } from '@margoengine/physics2d/vehicle';
227
+
228
+ await Physics2D.load();
229
+ const physics = new Physics2D(null, { pixelsPerMeter: 1 });
230
+ physics.addBody(null, { type: 'fixed', position: [0, 1], colliders: { shape: 'box', width: 400, height: 1 } });
231
+ const chassis = physics.addBody(null, {
232
+ position: [0, -0.2],
233
+ colliders: { shape: 'box', width: 2, height: 0.5, mass: 800 },
234
+ });
235
+ const wheel = (x: number) => ({
236
+ position: [x, 0.25] as [number, number],
237
+ radius: 0.3,
238
+ suspensionStiffness: 40,
239
+ suspensionCompression: 4,
240
+ suspensionRelaxation: 4,
241
+ });
242
+ using car = new Vehicle2D(physics, chassis, { wheels: [wheel(-0.8), wheel(0.8)] });
243
+ for (let i = 0; i < 60; i++) physics.step(); // settles on its springs
244
+ car.setInput({ throttle: 1 });
245
+ for (let i = 0; i < 120; i++) physics.step();
246
+ console.log(car.speed > 2, car.wheel(0).inContact); // true true
247
+ physics.dispose();
248
+ ```
249
+
250
+ ## Forces at a point, locked rotation and collider settings
251
+
252
+ `body.applyForceAtPoint(force, point)` holds a force that acts every step and turns the body by the arm from its centre of mass, as Rapier's `addForceAtPoint` does; `resetTorques()` clears the turning and keeps the push, `resetForces()` clears both. `body.lockRotation(locked = true)` holds the angle and takes the spin away until `lockRotation(false)`. A collider's `setActiveCollisionTypes(bits)` chooses the pairs it meets (1 dynamic with dynamic, 2 dynamic with kinematic, 4 dynamic with fixed, 8 kinematic with kinematic, 16 kinematic with fixed, 32 fixed with fixed; the default is 7), `setActiveEvents({collision, contactForce})` the events it asks for, and `setContactForceEventThreshold(newtons)` how hard a contact must press to raise `contactforce`.
253
+
254
+ ```ts
255
+ import { Physics2D } from '@margoengine/physics2d';
256
+
257
+ await Physics2D.load();
258
+ const physics = new Physics2D(null, { pixelsPerMeter: 1, gravity: [0, 0] });
259
+ const disc = physics.addBody(null, { colliders: { shape: 'circle', radius: 1, mass: 2 } });
260
+ disc.applyForceAtPoint([0, 4], [1, 0]); // pushes at 2 m/s^2 and turns at 4 rad/s^2
261
+ physics.step();
262
+ disc.resetTorques(); // the push goes on, nothing turns it any more
263
+ disc.lockRotation(); // and the angle is held whatever pushes at it
264
+ console.log(disc.linearVelocity, disc.angularVelocity);
265
+ physics.dispose();
266
+ ```
267
+
268
+ A collider's outline can change after it is made: `collider.setShape(shape)` takes any one convex outline a collider is
269
+ made with (`circle`, `box`, `capsule`, `segment`, `triangle`, a convex `polygon`), at the collider's own offset and turn.
270
+ Its material, density and filtering stay, the body's mass follows the new area, and the next step builds its contacts
271
+ from the new outline, as Rapier's `setShape` does. An outline of several kernel shapes (a concave polygon, a polyline,
272
+ a trimesh) is refused: remove the collider and add a new one.
273
+
274
+ ```ts
275
+ import { Physics2D } from '@margoengine/physics2d';
276
+
277
+ await Physics2D.load();
278
+ const physics = new Physics2D(null, { pixelsPerMeter: 1 });
279
+ const body = physics.addBody(null, { colliders: { shape: 'box', width: 0.5, height: 0.5, density: 2 } });
280
+ body.colliders[0].setShape({ shape: 'circle', radius: 0.6 });
281
+ console.log(body.mass.toFixed(3)); // '2.262': 2 kg/m^2 over a disc of 0.6 m
282
+ physics.dispose();
283
+ ```
284
+
285
+ A contact combines two colliders' friction and restitution by their combine rules, as Rapier's do:
286
+ `CoefficientCombineRule2D.Average` by default, or `Min`, `Multiply`, `Max`, `ClampedSum` (the sum held to 0 to 1) or
287
+ `GeometricMean`; of two colliders' rules the later in that list wins. Set them with the `frictionCombineRule` and
288
+ `restitutionCombineRule` options or `setFrictionCombineRule` and `setRestitutionCombineRule`. A ball of restitution
289
+ 0.8 on a floor of 0 bounces at 0.4 by the average; give the ball `Max` to bounce at 0.8.
290
+
291
+ ```ts
292
+ import { CoefficientCombineRule2D, Physics2D } from '@margoengine/physics2d';
293
+
294
+ await Physics2D.load();
295
+ const physics = new Physics2D(null, { pixelsPerMeter: 1 });
296
+ const ball = physics.addBody(null, {
297
+ colliders: { shape: 'circle', radius: 0.25, restitution: 0.8, restitutionCombineRule: CoefficientCombineRule2D.Max },
298
+ });
299
+ console.log(ball.colliders[0].restitutionCombineRule() === CoefficientCombineRule2D.Max); // true
300
+ physics.dispose();
301
+ ```
302
+
303
+ `contactSkin` (or `setContactSkin`) is Rapier's contact skin: the collider's contacts start that much farther out and
304
+ the solver holds it that far off what it touches, so two colliders rest the sum of their skins apart. It is in world
305
+ units, and queries still meet the outline itself.
306
+
307
+ ```ts
308
+ import { Physics2D } from '@margoengine/physics2d';
309
+
310
+ await Physics2D.load();
311
+ const physics = new Physics2D(null, { pixelsPerMeter: 1 });
312
+ const crate = physics.addBody(null, { colliders: { shape: 'box', width: 1, height: 1, contactSkin: 0.02 } });
313
+ crate.colliders[0].setContactSkin(0.05); // rests 5 cm off what it lands on
314
+ console.log(crate.colliders[0].contactSkin().toFixed(2)); // '0.05'
315
+ physics.dispose();
316
+ ```
317
+
318
+ A collider moves on its body after it is made: `setTranslationWrtParent([x, y])` and `setRotationWrtParent(angle)`, in
319
+ the body's frame, as Rapier's; the body's mass and centre of mass follow. `translationWrtParent()` and
320
+ `rotationWrtParent()` read the place back.
321
+
322
+ ```ts
323
+ import { Physics2D } from '@margoengine/physics2d';
324
+
325
+ await Physics2D.load();
326
+ const physics = new Physics2D(null, { pixelsPerMeter: 1 });
327
+ const door = physics.addBody(null, { type: 'fixed', colliders: { shape: 'box', width: 2, height: 0.2 } });
328
+ door.colliders[0].setRotationWrtParent(Math.PI / 2); // the bar now stands
329
+ console.log(door.colliders[0].rotationWrtParent().toFixed(3)); // '1.571'
330
+ physics.dispose();
331
+ ```
332
+
333
+ A collider's mass can be its own rather than its density's: `setMass(kilograms)` (or the `mass` option) holds whatever
334
+ the outline, its centre and inertia the outline's at that mass; `setMassProperties(mass, centre, inertia)` gives them
335
+ outright, the centre in the collider's frame; `setDensity` goes back; `mass()` reads it. As Rapier's.
336
+
337
+ ```ts
338
+ import { Physics2D } from '@margoengine/physics2d';
339
+
340
+ await Physics2D.load();
341
+ const physics = new Physics2D(null, { pixelsPerMeter: 1 });
342
+ const crate = physics.addBody(null, { colliders: { shape: 'box', width: 1, height: 1 } });
343
+ crate.colliders[0].setMass(12);
344
+ crate.colliders[0].setShape({ shape: 'circle', radius: 2 }); // still 12 kg
345
+ console.log(crate.mass.toFixed(1)); // '12.0'
346
+ physics.dispose();
347
+ ```
348
+
349
+ ## Articulations
350
+
351
+ `physics.addArticulation(root, links)` joins bodies into a tree of revolute and prismatic joints and gives it a joint space: positions, velocities, motors, limits, forward and inverse kinematics.
352
+
353
+ ```ts
354
+ import { Physics2D } from '@margoengine/physics2d';
355
+
356
+ await Physics2D.load();
357
+ const physics = new Physics2D(null, { gravity: [0, 0] });
358
+ const base = physics.addBody(null, { type: 'fixed', colliders: [] });
359
+ const link = (x: number) => physics.addBody(null, { position: [x, 0], colliders: { shape: 'box', width: 40, height: 6, collisionGroups: 0 } });
360
+ const [upper, lower] = [link(20), link(60)];
361
+ const arm = physics.addArticulation(base, [
362
+ { body: upper, joint: { type: 'revolute', anchorChild: [-20, 0], limits: [-2.5, 2.5] } },
363
+ { body: lower, parent: 0, joint: { type: 'revolute', anchorParent: [20, 0], anchorChild: [-20, 0], limits: [-2.5, 2.5] } },
364
+ ]);
365
+ // Joint positions that put the lower arm's tip on a point, then let the motors take the arm there.
366
+ const { q, reached } = arm.solveIK(1, [20, 0], [50, 40]);
367
+ arm.driveTo(q);
368
+ for (let i = 0; i < 240; i++) physics.step();
369
+ console.log(reached, arm.pointAt(1, [20, 0]));
370
+ physics.dispose();
371
+ ```
372
+
373
+ The links stay ordinary bodies and the kernel's joints hold them together, solved exactly in one sweep over the whole tree (Baraff 1996: sparse block elimination over the tree), so a 1000:1 mass ratio across a branch keeps every joint closed and contacts of any link act on the whole arm. Margo uses exact maximal-coordinate trees rather than reduced coordinates so that contacts stay in the one solver; [limits](../../docs/limits.md) has the measured accuracy against the closed forms and against Rapier 2D.
374
+
375
+ ## Colliders from a sprite's alpha (`@margoengine/physics2d/outline`)
376
+
377
+ `outlineColliders(image, options)` turns the alpha of an image into colliders that follow what is drawn, holes and hollows included, so a ball can rest in a cup. `image` is RGBA8 straight alpha, row by row from the top: `ImageData` fits.
378
+
379
+ ```ts
380
+ import { Physics2D } from '@margoengine/physics2d';
381
+ import { outlineColliders } from '@margoengine/physics2d/outline';
382
+
383
+ // Any drawing works; drawImage a sprite here.
384
+ const context = new OffscreenCanvas(64, 64).getContext('2d')!;
385
+ context.arc(32, 32, 24, 0, Math.PI * 2);
386
+ context.fill();
387
+ const imageData = context.getImageData(0, 0, 64, 64);
388
+
389
+ await Physics2D.load();
390
+ const physics = new Physics2D(null, { gravity: [0, 980] });
391
+ const colliders = outlineColliders(imageData, { friction: 0.4 });
392
+ physics.addBody(null, { type: 'fixed', colliders });
393
+ ```
394
+
395
+ Pass `sprite` and the colliders land on the sprite's pivot and scale, and its `rect` picks the frame of an atlas: `physics.addBody(sprite, {colliders: outlineColliders(imageData, {sprite})})`. `traceOutlines(image, options)` gives the outlines alone, in pixels from the top left of the traced area, each with its holes.
396
+
397
+ | Option | Default | What it does |
398
+ | --- | --- | --- |
399
+ | `threshold` | 128 | Alpha from 1 to 255 that counts as solid; the edge is placed between pixels by their alpha |
400
+ | `tolerance` | 1 | Farthest the thinned outline may stray from the traced one, in pixels; 0 keeps every point off a straight line |
401
+ | `minArea` | 4 | Outlines and holes under this many square pixels are left out |
402
+ | `rect` | whole image | `[x, y, width, height]` in pixels |
403
+ | `sprite` | none | Places the colliders, as `addBody(sprite)` places a fitted box |
404
+ | `edges` | false | False gives filled convex `polygon` colliders; true gives one closed `polyline` per outline and hole, for fixed terrain |
405
+
406
+ Any other collider setting (`friction`, `restitution`, `sensor`, `density` and the rest) goes on every collider. Limits are in [docs/limits.md](../../docs/limits.md).
407
+
408
+ ## Kernel development
409
+
410
+ The Rust kernel under `kernel/` is what the TypeScript facade above calls through `dist/physics2d.wasm` (its C interface is `kernel/src/api.rs`; rebuild the committed Wasm with `node scripts/wasm-blueprints.mjs --rebuild --only=physics2d-kernel`). Its world batches four
411
+ awake quad contacts through exact SIMD SAT and clipping. A rectangle certified from its current vertices and normals
412
+ uses support corners for SAT; separated cores can certify the original preferred clipped face from conservative
413
+ distance bounds. Uncertified cases use the complete closest-distance path. The
414
+ [floating-point proof](../../docs/architecture/physics2d-manifold-proof.md) describes the guards and fallback.
415
+ Other shapes, chains and short tails retain their collision paths. `manifold::collide_four` has a runnable Rust
416
+ example in [its API documentation](kernel/src/manifold/four.rs); every lane's manifold is bit-identical to the
417
+ scalar call, including signed zeros and unused point slots. Run the native and shipped Wasm checks from the root:
418
+
419
+ ```sh
420
+ npm run test:physics2d-kernel
421
+ npm run check:rust-kernels -- --packages=physics2d
422
+ ```
423
+
424
+ [Performance history](../../docs/whitepaper/perf-history.md) records the modest paired gain and the remaining Box2D
425
+ loss; the 0.35 ms narrow-phase target has not been met. Browser evidence covers Edge WebGPU/WebGL2 and Firefox
426
+ WebGL2; Firefox WebGPU has no adapter on the test installation.
427
+
428
+ Rapier 2D is not a dependency of this package. `tests/oracle-rapier.test.js` compares scenes with it live when `RAPIER2D_MODULE` names the `rapier.mjs` of a `@dimforge/rapier2d-compat` 0.21 you installed outside the repository (a black box, for comparison only); without it those tests are listed as not run.
429
+
430
+ ### Checked Rust input
431
+
432
+ The raw Rust world and collision APIs return `Result<_, PhysicsError>`. Handle errors with `?` or inspect
433
+ `error.code()` and `error.help()`; the [input contract](../../docs/limits.md#own-2d-input-validation) lists the
434
+ codes and representability rules. This API belongs to `kernel/`; the TypeScript facade above
435
+ keeps its existing API and units.
436
+
437
+ ```rust
438
+ use margoengine_physics2d_kernel::{
439
+ error::PhysicsError,
440
+ math::{V2, v2},
441
+ shape::Core,
442
+ world::{BodyDef, ShapeDef, World},
443
+ };
444
+
445
+ fn main() -> Result<(), PhysicsError> {
446
+ let mut world = World::default();
447
+ let body = world.create_body(&BodyDef {
448
+ position: v2(0.0, 0.5),
449
+ ..BodyDef::default()
450
+ })?;
451
+ let core = Core::rect(0.5, 0.5, V2::ZERO, 1.0, 0.0, 0.0)?;
452
+ world.create_shape(body, core, &ShapeDef::default())?;
453
+ world.step(1.0 / 60.0)?;
454
+
455
+ let error = world.create_shape(body, core, &ShapeDef {
456
+ density: f32::INFINITY,
457
+ ..ShapeDef::default()
458
+ }).unwrap_err();
459
+ assert_eq!(error.code(), "PHYSICS2D_NOT_FINITE");
460
+ assert_eq!(world.shapes.len(), 1); // The refused shape was never published.
461
+ Ok(())
462
+ }
463
+ ```
464
+
465
+ Body, shape and whole-chain creation refuse invalid input before publishing a partial result. Finite positive
466
+ density alone is insufficient: derived mass, inertia, centres and reciprocals must also remain representable.
467
+ The inverse metric's reciprocal and the reconstructed rounded origin are checked too. Finite friction coefficients
468
+ use an overflow-safe geometric mean; used cached normal impulses cannot be negative.
469
+ Contact normal/tangent metrics are checked before inversion, including sums of individually valid inverse masses.
470
+ Rotation normalization scales exceptional finite pairs to preserve their direction across overflow/underflow;
471
+ nonfinite integration arithmetic returns the coded error. A directly mutated zero body rotation is refused.
472
+ Genuine zero density or zero area retains its documented zero-mass behavior; positive mass or inertia rounded
473
+ to zero is refused. Before stepping, the world checks current public data and handles, including edits made
474
+ after creation. A reported arithmetic error during simulation does not promise rollback of the whole step.
475
+
476
+ Direct Rust `solver::solve` calls check the same current inputs and derived solver outputs. `World::step`
477
+ uses the private already-checked solver entry after its preflight, so a normal step checks each boundary once.
478
+ Unlike the world's nonpositive-step no-op, the direct solver requires a positive representable substep.
479
+
480
+ Collision calls (`collide`, `collide_coherent`, `collide_four` and `collide_smooth`) refuse nonfinite poses or
481
+ cutoffs and invalid current core data instead of indexing a missing face or returning an invented contact.
482
+ The existing [four-pair Rust doctest](kernel/src/manifold/four.rs) demonstrates the checked collision call.
483
+ Run `cargo test --locked --manifest-path packages/physics2d/kernel/Cargo.toml --doc` for both examples. Native
484
+ input/manifold regression commands are in [reproduce.md](../../docs/whitepaper/reproduce.md#own-2d-input-validation).
485
+ Input validation preserves the retained manifold reference and the prior valid hashes. The separate support
486
+ correction below intentionally re-pins the mixed scene. Owned-2D CCD is separate T-11 / 127.y work.
487
+
488
+ ### Sustained contact support in the owned kernel
489
+
490
+ The default 3 m/s recovery cap limits recovery demand independently of sustained elastic support. The spring
491
+ root, four substeps, one pass and all accuracy thresholds remain unchanged. A certified supported contact path
492
+ uses a coupled equilibrium correction with physical masses; general graphs retain capped contact dynamics.
493
+ Sleep also observes the motion actually integrated, so relaxation cannot hide continuing correction.
494
+
495
+ The required 1:1000 centered contact stack now holds the same 3% spring-sag, 0.1 mm top drift, 10 mm post-one-second
496
+ creep and sleep predicates as 1:100. Run `cargo test --locked --manifest-path packages/physics2d/kernel/Cargo.toml --test world`.
497
+ All original physical bars remain required. The mixed-scene hash is deliberately re-pinned for this correction;
498
+ pyramid and joint-grid hashes stay unchanged. The [proof and method domain](../../docs/architecture/physics2d-support-proof.md)
499
+ distinguish axial support from the preserved soft model's [lateral bending limit](../../docs/architecture/physics2d-support-bending.md).
500
+ This is a correctness change; Box2D browser speed parity remains unproven.
501
+
502
+ The support planner rebuilds its current graph each frame and retains flat scratch buffers between steps.
503
+ It preserves contact order, eligibility decisions and floating arithmetic. Retained planner capacity follows
504
+ the largest body/contact counts seen by the world; changing component order cannot accumulate a separate
505
+ high-water allocation for every component. Accepted components still allocate local solve buffers.
506
+ The native `planner_allocations` example measures whole-step allocation requests on the unchanged 100-row
507
+ scene; [reproduce.md](../../docs/whitepaper/reproduce.md) records its paired-control procedure and timing limits.
508
+
509
+ The four-lane normal solver also omits finite predicates already implied by its exact caller expressions.
510
+ Its [IEEE proof](../../docs/architecture/physics2d-finite-certificates.md) states that contract and the checks
511
+ retained for mutable arithmetic, cap membership and scalar fallback. The compiled finite-predicate count
512
+ falls while all current hashes and physical bars remain unchanged; a browser speed gain is unproven.
513
+
514
+ Private broad-phase refits reuse the same call-stack input preflight while public bounds and every step
515
+ remain checked. The planner also skips pure eligibility predicates after rejecting a component, retaining
516
+ its entire traversal. The [frame-preparation proof](../../docs/architecture/physics2d-frame-preparation.md)
517
+ records exact work, accuracy and measurement limits; the Box2D browser loss remains open.
518
+
519
+ ## Content Security Policy
520
+
521
+ Wasm initialization needs `'wasm-unsafe-eval'` in `script-src` on restricted pages and worker responses. Blocked compilation rejects with MargoError code `failed` and a help link. See [the exact header and package requirements](../../docs/csp.md).
@@ -0,0 +1,103 @@
1
+ import type { Body2D } from './body.js';
2
+ import type { Joint2D, MotorOptions2D } from './joint.js';
3
+ import type { Physics2D } from './physics.js';
4
+ import type { Vec2D } from './shapes.js';
5
+ /** One link of an articulation: a body joined to its parent by a revolute or prismatic joint. */
6
+ export interface ArticulationLink2D {
7
+ body: Body2D;
8
+ /** Index in the list of the link this one hangs from; -1 or left out for the root. Must come before this link. */
9
+ parent?: number;
10
+ joint: {
11
+ type: 'revolute' | 'prismatic';
12
+ /** The joint's anchor in the parent's frame, world units (default the parent's origin). */
13
+ anchorParent?: Vec2D;
14
+ /** The joint's anchor in this link's frame (default its origin). */
15
+ anchorChild?: Vec2D;
16
+ /** The slide axis in the parent's frame (prismatic only). */
17
+ axis?: Vec2D;
18
+ /** Radians (revolute) or world units (prismatic). */
19
+ limits?: readonly [number, number];
20
+ motor?: MotorOptions2D;
21
+ };
22
+ }
23
+ /** Where a link is, in world units and radians. */
24
+ export interface LinkPose2D {
25
+ position: [number, number];
26
+ rotation: number;
27
+ }
28
+ /** Options of {@link Articulation2D.solveIK}. */
29
+ export interface IKOptions2D {
30
+ /** Most iterations (default 64). */
31
+ iterations?: number;
32
+ /** Stop when the point is this close to the target, world units (default 0.01). */
33
+ tolerance?: number;
34
+ /** Damping of the least-squares step: larger is steadier near a straight arm and slower (default 0.5). */
35
+ damping?: number;
36
+ }
37
+ /**
38
+ * A tree of bodies joined by one-degree-of-freedom joints, with the joint space of the whole made explicit: the joint
39
+ * positions and velocities, motors and limits on each joint, forward kinematics and inverse kinematics. The bodies stay
40
+ * ordinary bodies of the world, and the kernel's joints keep them together: a chain solves exactly (block elimination, the
41
+ * constraint form of Featherstone's articulated-body result: "Rigid Body Dynamics Algorithms", Springer 2008, chapter 7) so a
42
+ * heavy end does not stretch it, and contacts of any link act on the whole.
43
+ * @example
44
+ * const arm = physics.addArticulation(base, [
45
+ * { body: upper, joint: { type: 'revolute', anchorParent: [0, 0], anchorChild: [-20, 0], limits: [-2, 2] } },
46
+ * { body: lower, parent: 0, joint: { type: 'revolute', anchorParent: [20, 0], anchorChild: [-20, 0] } },
47
+ * ]);
48
+ * arm.solveIK(1, [20, 0], [60, 10]); // joint positions that put the lower arm's tip there
49
+ */
50
+ export declare class Articulation2D {
51
+ private readonly physics;
52
+ readonly root: Body2D;
53
+ /** The joints, one per link, in link order. */
54
+ readonly joints: Joint2D[];
55
+ private readonly links;
56
+ private removed;
57
+ /** @internal */
58
+ constructor(physics: Physics2D, root: Body2D, links: readonly ArticulationLink2D[]);
59
+ /** The number of joints, which is the number of degrees of freedom. */
60
+ get dof(): number;
61
+ private bodyOf;
62
+ private check;
63
+ /** The joint positions now, in link order: radians for a revolute joint (child turn less parent turn), world units along the axis for a prismatic one. */
64
+ positions(): number[];
65
+ /** The joint velocities now: the relative angular speed, or the speed along the axis. */
66
+ velocities(): number[];
67
+ private world;
68
+ private pointVelocity;
69
+ /** Where every link is when the joints are at `q`, from the root's pose now. */
70
+ forwardKinematics(q?: readonly number[]): LinkPose2D[];
71
+ /** The world position of `local` (a point in link `link`'s frame) when the joints are at `q`. */
72
+ pointAt(link: number, local: Vec2D, q?: readonly number[]): [number, number];
73
+ private checkLink;
74
+ /** The 2 by dof Jacobian of the point `local` of link `link`: how it moves, in world units per unit of each joint, at `q`. */
75
+ jacobian(link: number, local: Vec2D, q?: readonly number[]): [number[], number[]];
76
+ /**
77
+ * Joint positions that put the point `local` of link `link` on `target`, by damped least squares from the joints' present
78
+ * positions (Wampler 1986, Nakamura and Hanafusa 1986), kept inside the joints' limits. Returns the positions and whether
79
+ * the point got within `tolerance`; nothing moves until you `setPositions` or `driveTo`.
80
+ */
81
+ solveIK(link: number, local: Vec2D, target: Vec2D, options?: IKOptions2D): {
82
+ q: number[];
83
+ reached: boolean;
84
+ error: number;
85
+ };
86
+ /**
87
+ * Puts the links where the joints at `q` would, now: each body is moved (as `teleport` does) and keeps its velocity. The
88
+ * root stays where it is. Joint limits are not applied; give positions inside them.
89
+ */
90
+ setPositions(q: readonly number[]): this;
91
+ /** Sets the position motor of every joint toward `q`, with the stiffness and damping given (defaults 200 and 20), so the arm moves there under the physics. */
92
+ driveTo(q: readonly number[], { stiffness, damping, maxForce }?: {
93
+ stiffness?: number;
94
+ damping?: number;
95
+ maxForce?: number;
96
+ }): this;
97
+ /** Sets one joint's motor. */
98
+ setMotor(joint: number, motor: MotorOptions2D): this;
99
+ /** Sets one joint's limits (radians or world units). */
100
+ setLimits(joint: number, min: number, max: number): this;
101
+ /** Removes the articulation's joints; the bodies stay. */
102
+ remove(): void;
103
+ }