@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.
@@ -0,0 +1,548 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { EngineKernel, EnginePlugin } from '@margoengine/core';
3
+ import type { Kernel, KernelWasmSource } from './kernel.js';
4
+ import { Body2D, Collider2D, type BodyOptions2D, type BodyOwner2D, type BodyType2D, type SpriteLike } from './body.js';
5
+ import { Articulation2D, type ArticulationLink2D } from './articulation.js';
6
+ import { CharacterController2D, type CharacterOptions2D } from './character.js';
7
+ import { Joint2D, type JointOptions2D } from './joint.js';
8
+ import { type ColliderOptions2D, type Described, type ShapeOptions2D, type Vec2D } from './shapes.js';
9
+ import { type TileMapBodyOptions, type TileMapSource } from './tilemap.js';
10
+ /** Options of {@link Physics2D.load}. */
11
+ export interface Physics2DLoadOptions {
12
+ /**
13
+ * Stops this call's wait. When no other call is waiting on the same load, it also cancels the download, and the next
14
+ * call starts again.
15
+ */
16
+ signal?: AbortSignal;
17
+ /**
18
+ * Where the kernel's Wasm comes from: a URL (a CDN or your own server), a fetched `Response`, its bytes or a compiled
19
+ * `WebAssembly.Module`. Default: `dist/physics2d.wasm` beside this package, which bundlers emit as its own file. It must
20
+ * be the build this package bundles. Calls made while a load runs share that load.
21
+ */
22
+ wasm?: KernelWasmSource;
23
+ /**
24
+ * Which build of the kernel to load: `true` the one with Wasm SIMD (`dist/physics2d.wasm`), `false` the scalar one
25
+ * (`dist/physics2d-scalar.wasm`), left out the SIMD one when this engine compiles it and the scalar one when it does not.
26
+ * Both step a world to the same bits. Ignored when `wasm` is given.
27
+ */
28
+ simd?: boolean;
29
+ }
30
+ export type { KernelWasmSource };
31
+ /** Options for creating a Physics2D world; every field has a default. */
32
+ export interface Physics2DOptions {
33
+ /**
34
+ * World units per metre (default 32). The solver works best with bodies between 0.1 and 10 metres, so a 16 pixel tile
35
+ * is half a metre. Positions, sizes, velocities and gravity are in world units; mass, density, force and impulse stay
36
+ * in kernel units (kilograms, metres, seconds).
37
+ */
38
+ pixelsPerMeter?: number;
39
+ /** World2D units per second squared, y down. Default [0, 9.81 * pixelsPerMeter]. */
40
+ gravity?: Vec2D;
41
+ /** Seconds per physics step (default 1/60). */
42
+ fixedTimestep?: number;
43
+ /** Most steps per frame; extra time is dropped so a slow frame cannot snowball (default 4). */
44
+ maxSubsteps?: number;
45
+ /** Interpolate sprite poses between the last two steps (default true). */
46
+ interpolate?: boolean;
47
+ /** Multiplies frame time, for slow motion (default 1). */
48
+ timeScale?: number;
49
+ /** Start paused (default false). */
50
+ paused?: boolean;
51
+ /** Plugin name (default 'physics2d'). */
52
+ name?: string;
53
+ }
54
+ /** Kind of collision event: contacts between solids, intersections for sensors. */
55
+ export type CollisionEventType2D = 'contactstart' | 'contactend' | 'intersectionstart' | 'intersectionend';
56
+ /** Two colliders began or stopped touching. */
57
+ export interface CollisionEvent2D {
58
+ type: CollisionEventType2D;
59
+ bodyA: Body2D;
60
+ bodyB: Body2D;
61
+ colliderA: Collider2D;
62
+ colliderB: Collider2D;
63
+ /** True when either collider is a sensor. */
64
+ sensor: boolean;
65
+ }
66
+ /** A contact pushed with more total force than a collider's `contactForceThreshold` in the last step. */
67
+ export interface ContactForceEvent2D {
68
+ bodyA: Body2D;
69
+ bodyB: Body2D;
70
+ colliderA: Collider2D;
71
+ colliderB: Collider2D;
72
+ /** Total force over the step, newtons. */
73
+ force: number;
74
+ /** Contact normal from A to B. */
75
+ normal: [number, number];
76
+ }
77
+ /** Events a Physics2D world emits, keyed by event name. */
78
+ export interface Physics2DEventMap {
79
+ contactstart: CollisionEvent2D;
80
+ contactend: CollisionEvent2D;
81
+ intersectionstart: CollisionEvent2D;
82
+ intersectionend: CollisionEvent2D;
83
+ /** A contact pushed past a force threshold (see `contactForceThreshold`). */
84
+ contactforce: ContactForceEvent2D;
85
+ /** Before each fixed step, with the step length. Drive character controllers and kinematic bodies here. */
86
+ beforestep: number;
87
+ afterstep: number;
88
+ }
89
+ /** A closest point of a collider to a point. */
90
+ export interface ProjectedPoint2D extends Hit2D {
91
+ /** The closest point of the collider (the query point itself when it is inside, unless the projection was not solid). */
92
+ point: [number, number];
93
+ inside: boolean;
94
+ /** World units; 0 inside, unless the projection was not solid, then the way to the surface. */
95
+ distance: number;
96
+ }
97
+ /** One contact of a collider as the world holds it. */
98
+ export interface ContactPair2D {
99
+ collider: Collider2D;
100
+ other: Collider2D;
101
+ /** From `collider` to `other`. */
102
+ normal: [number, number];
103
+ points: Array<{
104
+ point: [number, number];
105
+ distance: number;
106
+ }>;
107
+ impulse: number;
108
+ solverActive: boolean;
109
+ touching: boolean;
110
+ }
111
+ /** What a `modifyContact` hook sees of a touching contact and may change for the step. */
112
+ export interface ContactChange2D {
113
+ readonly colliderA: Collider2D;
114
+ readonly colliderB: Collider2D;
115
+ /** The contact normal from A to B. */
116
+ readonly normal: [number, number];
117
+ /** Contact points in the manifold (1 or 2). */
118
+ readonly points: number;
119
+ /** Set false to let the bodies through each other this step (events still fire). Default true. */
120
+ solverActive: boolean;
121
+ /** Replaces the colliders' combined friction. */
122
+ friction?: number;
123
+ /** Replaces the colliders' combined restitution. */
124
+ restitution?: number;
125
+ /** A direction the contact lets bodies through from: it pushes only while the normal has a positive part along it. */
126
+ oneWay?: Vec2D;
127
+ /** The unit direction `tangentVelocity` is along: the normal turned a quarter turn, [normal.y, -normal.x]. */
128
+ readonly tangent: [number, number];
129
+ /**
130
+ * A conveyor: friction drives collider B's surface to this speed (world units per second) relative to collider A along
131
+ * `tangent`, so a body resting on a belt is carried at the belt's speed. Default 0.
132
+ */
133
+ tangentVelocity?: number;
134
+ }
135
+ /** Code the world asks about pairs of colliders that have `hooks` set; it must be fast and must not change the world. */
136
+ export interface Physics2DHooks {
137
+ /** Whether a pair of solid colliders may meet at all; false removes the contact and its events. */
138
+ filterPair?(colliderA: Collider2D, colliderB: Collider2D): boolean;
139
+ /**
140
+ * Whether a pair with a sensor in it may intersect (Rapier's intersection pair filter); false removes the intersection and its
141
+ * events. Asked, instead of `filterPair`, of the pairs where either collider is a sensor, for colliders with `hooks.filterIntersection`.
142
+ */
143
+ filterIntersection?(colliderA: Collider2D, colliderB: Collider2D): boolean;
144
+ /** Changes a touching contact for this step: one-way platforms, conveyors' friction, sticky or slippery pairs. */
145
+ modifyContact?(change: ContactChange2D): void;
146
+ }
147
+ /** Lines that draw a world: four numbers a line, a colour code a line, and the colour of each line as red, green, blue and alpha from 0 to 1. */
148
+ export interface DebugLines2D {
149
+ vertices: Float32Array;
150
+ colors: Uint8Array;
151
+ /** Four numbers a line: the colour its code has in the style, or the default one (see {@link DebugStyle2D}). */
152
+ rgba: Float32Array;
153
+ }
154
+ /** What a debug line draws, the names of the colour codes of {@link DebugLines2D.colors} in order. */
155
+ export type DebugColour2D = 'fixed' | 'awake' | 'sleeping' | 'kinematic' | 'sensor' | 'joint' | 'contactPoint' | 'contactNormal' | 'box' | 'axisX' | 'axisY' | 'solverPoint' | 'solverNormal';
156
+ /** Colours for the lines of `debugRender`: red, green, blue and alpha from 0 to 1 for any of the kinds; the others keep the defaults. */
157
+ export type DebugStyle2D = Partial<Record<DebugColour2D, readonly [number, number, number, number]>>;
158
+ /** Limits which colliders a scene query can hit. */
159
+ export interface QueryFilter2D {
160
+ /** Packed interaction groups of the query, see `interactionGroups`. */
161
+ groups?: number;
162
+ /** Ignore this body. */
163
+ exclude?: Body2D;
164
+ /** Ignore this one collider, not the body's others (Rapier's `exclude_collider`). */
165
+ excludeCollider?: Collider2D;
166
+ excludeSensors?: boolean;
167
+ excludeFixed?: boolean;
168
+ excludeKinematic?: boolean;
169
+ excludeDynamic?: boolean;
170
+ /** Return false to skip a body. */
171
+ predicate?: (body: Body2D, collider: Collider2D) => boolean;
172
+ }
173
+ /** Options of `raycast`: the filter plus a distance limit. */
174
+ export interface RaycastOptions2D extends QueryFilter2D {
175
+ /** World2D units. Default unbounded. */
176
+ maxDistance?: number;
177
+ /** A ray that starts inside a solid hits at distance 0 (default true). */
178
+ solid?: boolean;
179
+ }
180
+ /** A scene query hit. */
181
+ export interface Hit2D {
182
+ body: Body2D;
183
+ sprite: SpriteLike | null;
184
+ collider: Collider2D;
185
+ }
186
+ /** A ray or shape-cast hit with its point, normal and travelled distance (world units). */
187
+ export interface CastHit2D extends Hit2D {
188
+ distance: number;
189
+ point: [number, number];
190
+ normal: [number, number];
191
+ }
192
+ /** What a shape cast stops for (Rapier's `ShapeCastOptions`). */
193
+ export interface ShapeCastOptions2D {
194
+ /** The cast meets a collider when the distance to it falls to this much, in world units (default 0: when they touch). */
195
+ targetDistance?: number;
196
+ /** Colliders already overlapping the cast shape are met at distance 0 (default true); off, one that overlaps and is moving apart is not met at all. */
197
+ stopAtPenetration?: boolean;
198
+ }
199
+ /** A shape cast's hit: the hit's closest points on both shapes and how it ended. */
200
+ export interface ShapeCastHit2D extends CastHit2D {
201
+ /** World-space points where the cast shape and the collider it met are closest at the hit (`point` is `witnessB`). */
202
+ witnessA: [number, number];
203
+ witnessB: [number, number];
204
+ /** World-space unit normals at the witness points: `normalA` on the cast shape's surface and `normalB` on the collider's, each pointing out toward the other (`normal` is `normalB`). */
205
+ normalA: [number, number];
206
+ normalB: [number, number];
207
+ /** The distance between the two shapes at the hit: `targetDistance` when the cast stopped short, below 0 when they overlap. */
208
+ gap: number;
209
+ /** `'converged'` for a hit found along the cast, `'penetrating'` for one at distance 0 with the shapes overlapping or within the target distance already. */
210
+ status: 'converged' | 'penetrating';
211
+ }
212
+ /** The settings of the solver that {@link Physics2D.setSolver} changes. */
213
+ export interface Physics2DSolverOptions {
214
+ /** Substeps a step (default 4). */
215
+ substeps?: number;
216
+ /** Pushing passes in a substep, each followed by as many relaxing ones (default 1). */
217
+ iterations?: number;
218
+ /** The contact spring's frequency in hertz, held to a quarter of the substep rate, and its damping ratio. */
219
+ contactHertz?: number;
220
+ contactDamping?: number;
221
+ /** How fast a depth is pushed out at most, in world units a second. */
222
+ contactMaxPush?: number;
223
+ /** Under this approach speed, in world units a second, a contact does not bounce. */
224
+ restitutionThreshold?: number;
225
+ /** A body slower than this, in world units a second, for `sleepTime` seconds may sleep with its island. */
226
+ sleepThreshold?: number;
227
+ sleepTime?: number;
228
+ /** Whether bodies may sleep at all (default true). */
229
+ canSleep?: boolean;
230
+ /** Two-point manifolds solved as one 2 by 2 problem, Rapier's block solver (default true); off, one point at a time. */
231
+ blockSolver?: boolean;
232
+ /** The joint spring's frequency, damping ratio and the fastest a joint's error is pulled out, in world units a second. */
233
+ jointHertz?: number;
234
+ jointDamping?: number;
235
+ jointMaxPush?: number;
236
+ /** Joints solve with each body's turning stiffened by the pull of its taut point joints (default true); off, the plain inertia. */
237
+ jointGeometricStiffness?: boolean;
238
+ /**
239
+ * Impacts continuous collision handles in a step (default 1; 0 turns it off for the world). The first stops a body that has `ccd` where
240
+ * it touches, with its velocity, for the next step's contact to answer. Each more answers the touch as a collision (the pair's
241
+ * restitution and friction, momentum shared with a body that moves) and sweeps the rest of the step with the velocity that leaves,
242
+ * so a fast ball bouncing between two walls keeps bouncing inside one step. Rapier's `maxCcdSubsteps`.
243
+ */
244
+ maxCcdSubsteps?: number;
245
+ /**
246
+ * The least time, in seconds, a continuous-collision advance is worth (default 0: every advance is taken); a sweep whose next advance is
247
+ * shorter stops the body at the time it has reached, before any touch. The name and meaning of the 3D world's `minCcdDt`.
248
+ */
249
+ minCcdDt?: number;
250
+ /** How close, in world units, the sweep brings a body to what it meets before it stops (default 5 mm; at least 1e-7 m), as the 3D `ccdTolerance`. */
251
+ ccdTolerance?: number;
252
+ /** The most advances the sweep takes for a pair of colliders (default 32, 0 to 4096); the time reached after them is before any touch, as the 3D `ccdMaxAdvances`. */
253
+ ccdMaxAdvances?: number;
254
+ /**
255
+ * The share of last step's contact impulses a step starts from, 0 to 1 (default 1), as Rapier's `warmstartCoefficient`. Less than 1
256
+ * trades the stiffness of stacks for less carried overshoot.
257
+ */
258
+ warmStart?: number;
259
+ /**
260
+ * How deep, in world units, a contact may overlap before it is pushed apart (default 0), as Rapier's `allowedLinearError`. A small
261
+ * depth keeps resting contacts touching from step to step, so they do not flicker; the solver's own slop is kept on top of it.
262
+ */
263
+ allowedPenetration?: number;
264
+ /**
265
+ * How far apart, in world units, two colliders get contact points before they touch (default 0.02 m), as Rapier's
266
+ * `predictionDistance`. Longer catches faster bodies without continuous collision and costs more contacts.
267
+ */
268
+ predictionDistance?: number;
269
+ /**
270
+ * The contact spring for contacts with a fixed or kinematic body (`null`, the default: the same as `contactHertz` and
271
+ * `contactDamping`). A softer one lets bodies settle into the ground while stacks keep the stiff spring between them.
272
+ */
273
+ staticContactHertz?: number | null;
274
+ staticContactDamping?: number | null;
275
+ }
276
+ /**
277
+ * 2D rigid-body physics on Margo's own 2D kernel as a Margo Engine plugin. Steps a fixed timestep with an accumulator
278
+ * and writes interpolated poses to sprites. Y is down, like sprites; angles are radians, clockwise on screen.
279
+ */
280
+ export declare class Physics2D implements EnginePlugin, BodyOwner2D {
281
+ readonly name: string;
282
+ /** Metres per world unit. */
283
+ readonly scale: number;
284
+ fixedTimestep: number;
285
+ maxSubsteps: number;
286
+ interpolate: boolean;
287
+ timeScale: number;
288
+ paused: boolean;
289
+ /** Fixed steps taken since creation. */
290
+ stepCount: number;
291
+ /** The kernel and this world's handle in it. @internal */
292
+ readonly kernel: Kernel;
293
+ /** @internal */
294
+ handle: number;
295
+ private engine;
296
+ private accumulator;
297
+ private lastAlpha;
298
+ private disposed;
299
+ private readonly bodies;
300
+ private movers;
301
+ private readonly byShape;
302
+ private readonly joints;
303
+ private readonly controllers;
304
+ private readonly listeners;
305
+ private readonly events;
306
+ private dispatching;
307
+ private syncAlpha;
308
+ private gravityValue;
309
+ /**
310
+ * Gets the kernel ready, once per app: compiling it is asynchronous, so `new Physics2D(engine)` can stay synchronous.
311
+ * Later calls resolve at once, calls made during a load share it, and a failed load is tried again by the next call.
312
+ * The kernel's Wasm is a file of its own (`dist/physics2d.wasm`), fetched and compiled while it downloads; `wasm`
313
+ * points at another copy.
314
+ * @example await Physics2D.load();
315
+ * const physics = new Physics2D(engine);
316
+ * @throws AbortError (the signal's reason) when `signal` aborts first.
317
+ * @throws MargoError (`failed`) when the Wasm cannot be fetched or is not this package's build.
318
+ */
319
+ static load({ signal, wasm, simd }?: Physics2DLoadOptions): Promise<void>;
320
+ /** Creates the Physics2D on `engine` (preferred over the constructor). */
321
+ static attach(engine: EngineKernel, options?: Physics2DOptions): Physics2D;
322
+ /** @throws MargoError (`state`) before {@link Physics2D.load} has finished. */
323
+ constructor(engine: EngineKernel | null, options?: Physics2DOptions);
324
+ private checkVec;
325
+ private live;
326
+ get isDisposed(): boolean;
327
+ /** World units per second squared. */
328
+ get gravity(): [number, number];
329
+ set gravity(value: Vec2D);
330
+ /** Interpolation factor used by the last `update`: leftover time over the step length, 0..1. */
331
+ get alpha(): number;
332
+ get bodyCount(): number;
333
+ /**
334
+ * How long the phases of the last step took, in milliseconds, as Rapier's `timingStep` and its siblings do: `step` is the whole of
335
+ * it, then `begin` (kinematic targets are read), `broad` phase, `narrow` phase, `islands`, `solver`, `ccd` and `events`. The phases
336
+ * add up to `step`, bar the clock's own calls. `assembly` (contact rows built), `resolution` (warm start and passes), `update`
337
+ * (velocities and poses moved) and `writeback` (results put in the bodies) split `solver`, and `ccdBroad`, `ccdToi` and
338
+ * `ccdSolver` split `ccd`; those seven are sums over the substeps and the bodies. All zero before the first step. A reading is
339
+ * no part of the world: a snapshot and the replay hash leave it out.
340
+ */
341
+ get timing(): {
342
+ step: number;
343
+ begin: number;
344
+ broad: number;
345
+ narrow: number;
346
+ islands: number;
347
+ solver: number;
348
+ ccd: number;
349
+ events: number;
350
+ assembly: number;
351
+ resolution: number;
352
+ update: number;
353
+ writeback: number;
354
+ ccdBroad: number;
355
+ ccdToi: number;
356
+ ccdSolver: number;
357
+ };
358
+ /**
359
+ * How much work the last step did, as whole numbers: the awake bodies, the islands with an awake body in them (a fixed body is
360
+ * no island, and a sleeping one is no work), the broad phase's boxes compared and pairs kept, the manifolds built, the manifold
361
+ * points that started cold, the contacts solved and how many of their two-point solves took the block or went one point at a
362
+ * time, the colours the contacts took and the contacts in none, the joints solved as trees, the events, and the steps taken in
363
+ * all. They are counts of work, not of time, so they are the same on every machine for the same inputs.
364
+ */
365
+ get counts(): {
366
+ awake: number;
367
+ islands: number;
368
+ boxesCompared: number;
369
+ pairs: number;
370
+ manifolds: number;
371
+ coldPoints: number;
372
+ contactsSolved: number;
373
+ blockSolves: number;
374
+ sequentialSolves: number;
375
+ colours: number;
376
+ uncoloured: number;
377
+ treeJoints: number;
378
+ events: number;
379
+ steps: number;
380
+ };
381
+ /**
382
+ * The solver's settings, with the names `Physics.setSolver` has in 3D: `substeps` a step, `iterations` (pushing passes,
383
+ * each followed by as many relaxing ones) a substep, the contact spring `contactHertz` and `contactDamping`, how fast a depth is
384
+ * pushed out at most (`contactMaxPush`), the approach speed under which a contact does not bounce (`restitutionThreshold`), the
385
+ * speed and time under which a body may sleep (`sleepThreshold`, `sleepTime`) and whether it may (`canSleep`), `blockSolver`,
386
+ * the joint spring (`jointHertz`, `jointDamping`, `jointMaxPush`) and `jointGeometricStiffness`, the continuous-collision
387
+ * settings, `warmStart`, `allowedPenetration`, `predictionDistance` and the contact spring for fixed bodies
388
+ * (`staticContactHertz`, `staticContactDamping`, null when it follows the contact spring). Speeds are in world units a second.
389
+ * Defaults are what a new world reads.
390
+ */
391
+ get solver(): Required<Physics2DSolverOptions>;
392
+ /**
393
+ * Changes the solver's settings; a name left out keeps its value, and nothing changes when one is refused.
394
+ * @throws RangeError for a count that is not a whole number from 1 to 65535, or a number that is negative or not finite.
395
+ */
396
+ setSolver(options: Physics2DSolverOptions): this;
397
+ /** Every body in the world, in the order they were added. */
398
+ getBodies(): Body2D[];
399
+ /** Every collider in the world, in the order their kernel shapes were made. */
400
+ getColliders(): Collider2D[];
401
+ /** How many colliders the world holds. */
402
+ get colliderCount(): number;
403
+ /** Every joint in the world, in the order they were added. */
404
+ getJoints(): Joint2D[];
405
+ /** How many joints the world holds. */
406
+ get jointCount(): number;
407
+ setup(engine: EngineKernel): void;
408
+ onPreUpdate(delta: number): void;
409
+ /** Advances the accumulator by `delta` seconds, runs whole fixed steps, then writes interpolated poses to sprites. Returns the number of steps. */
410
+ update(delta: number): number;
411
+ /** Runs exactly one fixed step and dispatches its events. Does not touch sprites; call `sync()` to write them. */
412
+ step(): void;
413
+ /** Reads every moving body's pose in one call. */
414
+ private readPoses;
415
+ private collectEvents;
416
+ /** Writes body poses to their sprites, interpolated by `alpha` between the last two steps. */
417
+ sync(alpha?: number): void;
418
+ /**
419
+ * Creates a rigid body, optionally driving `sprite`: each frame the interpolated pose is written to the sprite's
420
+ * `x`, `y` and `rotation`. The body starts at the sprite's position.
421
+ */
422
+ addBody(sprite: SpriteLike | null, options?: BodyOptions2D): Body2D;
423
+ /**
424
+ * One fixed body holding the collision of a tile map: tiles with collision shapes (or a `solid: true` property) in
425
+ * the chosen layers. Whole-cell squares merge into outline loops, so a body slides over neighbouring tiles without
426
+ * catching on the seams. The map's top left sits at `options.position`.
427
+ */
428
+ addTileMap(map: TileMapSource, options?: TileMapBodyOptions): Body2D;
429
+ /** @internal */
430
+ addCollider(body: Body2D, options: ColliderOptions2D): Collider2D;
431
+ private createShapes;
432
+ /** @internal */
433
+ removeCollider(collider: Collider2D): void;
434
+ removeBody(body: Body2D): void;
435
+ /** The hooks asked about colliders that set `hooks` (see {@link Physics2DHooks}); null for none. */
436
+ get hooks(): Physics2DHooks | null;
437
+ set hooks(value: Physics2DHooks | null);
438
+ private hookSet;
439
+ /** Points the kernel's page hooks at this world, for the length of a step. */
440
+ private installHooks;
441
+ /** @internal */
442
+ retype(body: Body2D, type: BodyType2D): void;
443
+ /**
444
+ * The closest collider to `point`, its closest point and whether `point` is inside it, or null. With `solid` (the default) a point inside
445
+ * a collider projects to itself at distance 0; with `solid` false it projects to the collider's nearest surface point, `inside` still
446
+ * true and `distance` the way to that point (Rapier's `projectPoint(point, solid)`).
447
+ */
448
+ projectPoint(point: Vec2D, filter?: QueryFilter2D, solid?: boolean): ProjectedPoint2D | null;
449
+ /** The bodies with a collider whose bounds meet the box from `min` to `max` (world units). */
450
+ intersectionsWithBox(min: Vec2D, max: Vec2D, filter?: QueryFilter2D): Body2D[];
451
+ /**
452
+ * The contacts the world holds for a collider as of the last step: each with the other collider, the contact normal
453
+ * from `collider` to it, up to two points with their separation (negative: overlapping), the normal impulse of the
454
+ * last substep and whether it pushes (`solverActive`; false for sensors and ignored solver groups) and touches.
455
+ */
456
+ contactPairs(collider: Collider2D): ContactPair2D[];
457
+ /**
458
+ * The contact between two colliders as of the last step, or null when the world holds none (Rapier's `contact_pair`): the normal
459
+ * from `a` to `b`, up to two points with their separation (negative: overlapping) and the normal impulse. A sensor's overlap is not a
460
+ * contact, so a sensor and what it senses have an {@link Physics2D.intersectionPair} and no contact pair with `solverActive`.
461
+ * @throws MargoError (`state`) for a collider that was removed.
462
+ */
463
+ contactPair(a: Collider2D, b: Collider2D): ContactPair2D | null;
464
+ /**
465
+ * Whether two colliders overlap with at least one a sensor, as of the last step (Rapier's `intersection_pair`): the overlap that raises
466
+ * `intersectionstart` and `intersectionend`. Two solid colliders never have one, and a sensor and what it senses overlapping is not a contact.
467
+ * @throws MargoError (`state`) for a collider that was removed.
468
+ */
469
+ intersectionPair(a: Collider2D, b: Collider2D): boolean;
470
+ /**
471
+ * The colliders that overlap `collider` with one of the two a sensor, as of the last step: what a sensor currently senses, or the sensors
472
+ * a solid collider is inside (Rapier's `intersection_pairs_with`).
473
+ * @throws MargoError (`state`) for a collider that was removed.
474
+ */
475
+ intersectionPairsWith(collider: Collider2D): Collider2D[];
476
+ /** @internal Holds `body` at its position on the axes picked, with a generic joint to a fixed body no one sees. */
477
+ lockTranslation(body: Body2D, x: boolean, y: boolean): void;
478
+ private anchor;
479
+ /** Joins two bodies. Anchors are in each body's local space, world units. */
480
+ addJoint(bodyA: Body2D, bodyB: Body2D, options: JointOptions2D): Joint2D;
481
+ removeJoint(joint: Joint2D): void;
482
+ /**
483
+ * Joins bodies into a tree of one-degree-of-freedom joints hanging from `root` and gives the whole its joint space: see
484
+ * {@link Articulation2D}. `links` come parent before child.
485
+ */
486
+ addArticulation(root: Body2D, links: readonly ArticulationLink2D[]): Articulation2D;
487
+ /** A character controller for a kinematic position body that has a collider. */
488
+ createCharacterController(body: Body2D, options?: CharacterOptions2D): CharacterController2D;
489
+ /** @internal The kernel's query filter words for `filter`, written at word 0 of the buffer. */
490
+ writeFilter(f?: QueryFilter2D): void;
491
+ private hitOf;
492
+ /** First collider along a ray from `origin` in `direction` (any length), or null. */
493
+ raycast(origin: Vec2D, direction: Vec2D, options?: RaycastOptions2D): CastHit2D | null;
494
+ /**
495
+ * Every collider a ray meets, nearest first (ties by collider order), each with its point, normal and distance: Rapier's
496
+ * `intersections_with_ray`. A collider of several shapes appears once per shape the ray meets.
497
+ * @throws RangeError for an origin or direction that is not two finite numbers, or a zero direction.
498
+ */
499
+ raycastAll(origin: Vec2D, direction: Vec2D, options?: RaycastOptions2D): CastHit2D[];
500
+ private rayHits;
501
+ /** The bodies with a collider containing `point`. */
502
+ overlapPoint(point: Vec2D, filter?: QueryFilter2D): Body2D[];
503
+ private bodiesOf;
504
+ /** The bodies with a collider overlapping `shape` (a box, circle, capsule or convex polygon) placed at `position`. */
505
+ overlapShape(shape: ShapeOptions2D, position: Vec2D, rotation?: number, filter?: QueryFilter2D): Body2D[];
506
+ private queryShape;
507
+ /** Slides `shape` from `position` along `direction` for up to `maxDistance` and reports the first collider it meets. */
508
+ castShape(shape: ShapeOptions2D, position: Vec2D, direction: Vec2D, maxDistance: number, filter?: QueryFilter2D, rotation?: number, options?: ShapeCastOptions2D): ShapeCastHit2D | null;
509
+ /** @internal A shape cast in metres; the hit is in world units. */
510
+ cast(d: Described, x: number, y: number, angle: number, dx: number, dy: number, max: number, filter?: QueryFilter2D, options?: ShapeCastOptions2D): ShapeCastHit2D | null;
511
+ /**
512
+ * The world as bytes: bodies, colliders and joints with their velocities, contacts and sleep timers. `restore` puts a
513
+ * world back to it, and a restored world steps bit for bit as the original would have, so it serves rollback netcode,
514
+ * replays and save games. The bytes are only good for this world's own bodies: see {@link Physics2D.restore}.
515
+ */
516
+ snapshot(): Uint8Array;
517
+ /**
518
+ * Puts the world back to a {@link Physics2D.snapshot}. The bodies, colliders and joints must be the ones that existed
519
+ * when it was taken (none added or removed since; moving, waking and changing them is fine); the interpolation
520
+ * history of every body restarts at the restored pose, and listeners and sprites stay as they are.
521
+ * @throws MargoError (`state`) when bodies, colliders or joints were added or removed since the snapshot.
522
+ * @throws RangeError when `bytes` is not a snapshot of this package.
523
+ */
524
+ restore(bytes: Uint8Array): void;
525
+ /**
526
+ * Lines that draw the world, in world units: `vertices` holds x1, y1, x2, y2 for each line, `colors` its colour code (0 fixed, 1 awake,
527
+ * 2 sleeping, 3 kinematic, 4 sensor, 5 joint, 6 contact point, 7 contact normal, 8 broad phase box, 9 and 10 a body's x and y axes,
528
+ * 11 and 12 a solver contact's point and normal) and `rgba` its colour. Shapes, joints, contacts and boxes are drawn unless `options` picks
529
+ * parts; `axes` draws each body's two axes at its centre of mass, `solverContacts` the contacts the solver acts on apart from the touching
530
+ * ones. `style` sets colours (red, green, blue, alpha from 0 to 1) by kind, and `filter` leaves out every line of a body it returns false for
531
+ * (its shapes, boxes, axes, joints and contacts).
532
+ */
533
+ debugRender(options?: {
534
+ shapes?: boolean;
535
+ joints?: boolean;
536
+ contacts?: boolean;
537
+ boxes?: boolean;
538
+ axes?: boolean;
539
+ solverContacts?: boolean;
540
+ style?: DebugStyle2D;
541
+ filter?: (body: Body2D) => boolean;
542
+ }): DebugLines2D;
543
+ /** Adds a listener; returns a function that removes it. */
544
+ on<K extends keyof Physics2DEventMap>(type: K, listener: (event: Physics2DEventMap[K]) => void): () => void;
545
+ private emit;
546
+ dispose(): void;
547
+ [Symbol.dispose]: () => void;
548
+ }
Binary file
Binary file
package/dist/pid.d.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { Body2D } from './body.js';
2
+ import type { Vec2D } from './shapes.js';
3
+ /**
4
+ * A proportional-integral-derivative regulator that steers a body to a target position, angle or velocity by changing its
5
+ * velocity: the correction is `kp` times the error plus `ki` times the error summed over time plus `kd` times the
6
+ * velocity error. Pass the fixed step length each time; call `reset` when the target jumps so the sum starts again.
7
+ * @example const pid = new PidController2D({ kp: 8, ki: 0, kd: 1 });
8
+ * physics.on('beforestep', (dt) => pid.applyLinear(dt, body, [200, 80]));
9
+ */
10
+ export declare class PidController2D {
11
+ kp: number;
12
+ ki: number;
13
+ kd: number;
14
+ /** Which axes the linear correction acts on (default both). */
15
+ axes: [boolean, boolean];
16
+ private sum;
17
+ private angleSum;
18
+ constructor({ kp, ki, kd }?: {
19
+ kp?: number;
20
+ ki?: number;
21
+ kd?: number;
22
+ });
23
+ /** Forgets the summed error. */
24
+ reset(): this;
25
+ /**
26
+ * The change of velocity (world units per second) that moves `body` toward `target` while matching `targetVelocity`,
27
+ * for a step of `dt` seconds. Add it to the body's velocity, or call `applyLinear`.
28
+ */
29
+ linearCorrection(dt: number, body: Body2D, target: Vec2D, targetVelocity?: Vec2D): [number, number];
30
+ /** Adds the correction of {@link PidController2D.linearCorrection} to the body's velocity. */
31
+ applyLinear(dt: number, body: Body2D, target: Vec2D, targetVelocity?: Vec2D): this;
32
+ /** The change of angular velocity (radians per second) toward `target` radians, by the shortest turn. */
33
+ angularCorrection(dt: number, body: Body2D, target: number, targetVelocity?: number): number;
34
+ /** Adds the correction of {@link PidController2D.angularCorrection} to the body's angular velocity. */
35
+ applyAngular(dt: number, body: Body2D, target: number, targetVelocity?: number): this;
36
+ }