@margoengine/physics2d 0.0.0-stage → 1.0.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,215 @@
1
+ /** A 2D point or vector [x, y]. */
2
+ export type Vec2D = readonly [number, number];
3
+ /** How a collider is shaped. Sizes are in world units (sprite pixels). */
4
+ export type ShapeOptions2D = {
5
+ /** A box centred on the body (move it with `offset`). */
6
+ shape: 'box';
7
+ width: number;
8
+ height: number;
9
+ /** Rounds the corners: the box grows by this radius on every side, as Rapier's round cuboid does (default 0). */
10
+ borderRadius?: number;
11
+ } | {
12
+ shape: 'circle';
13
+ radius: number;
14
+ } | {
15
+ /** A vertical pill: `height` is the whole length including both round ends. */
16
+ shape: 'capsule';
17
+ radius: number;
18
+ height: number;
19
+ } | {
20
+ /** A filled polygon, convex or concave (concave ones are split into convex pieces). */
21
+ shape: 'polygon';
22
+ points: readonly Vec2D[];
23
+ /** Grows the polygon by this radius, with round corners (default 0). */
24
+ borderRadius?: number;
25
+ } | {
26
+ /** Edges with no area: terrain outlines. Close the loop by repeating the first point. */
27
+ shape: 'polyline';
28
+ points: readonly Vec2D[];
29
+ /**
30
+ * Only one side is solid: the one an edge's right-hand normal points to when you walk the points in order (left to
31
+ * right is up on screen). A body on the other side passes through: a one-way platform (default false).
32
+ */
33
+ oneSided?: boolean;
34
+ } | {
35
+ shape: 'segment';
36
+ from: Vec2D;
37
+ to: Vec2D;
38
+ } | {
39
+ /** Three points; the same as a polygon of three. */
40
+ shape: 'triangle';
41
+ a: Vec2D;
42
+ b: Vec2D;
43
+ c: Vec2D;
44
+ borderRadius?: number;
45
+ } | {
46
+ /** Several shapes, each with its own `offset` and `rotation`, as one collider that shares its settings. */
47
+ shape: 'compound';
48
+ shapes: readonly CompoundPart2D[];
49
+ } | {
50
+ /**
51
+ * Triangles from `indices` (three to a triangle) into `vertices`: a mesh as one collider. A flat triangle collides along
52
+ * its line, as Rapier's does; one whose three corners are one point is left out.
53
+ */
54
+ shape: 'trimesh';
55
+ vertices: readonly Vec2D[];
56
+ indices: ArrayLike<number>;
57
+ /**
58
+ * Joins the triangles into one solid for contacts, so shapes slide over the edges they share without catching on them
59
+ * (Rapier's `TriMeshFlags.FIX_INTERNAL_EDGES`; in Rapier 2D the flag changes nothing, here it does). Shared edges are found
60
+ * by exact positions, so it needs no `mergeDuplicateVertices`. Default false, as in Rapier.
61
+ */
62
+ fixInternalEdges?: boolean;
63
+ /** Joins vertices at the same position into one before anything else (Rapier's `MERGE_DUPLICATE_VERTICES`). Default false. */
64
+ mergeDuplicateVertices?: boolean;
65
+ /** Leaves out flat triangles and those with a repeated vertex (Rapier's `DELETE_DEGENERATE_TRIANGLES`). Default false. */
66
+ deleteDegenerateTriangles?: boolean;
67
+ /** Leaves out a triangle whose three vertices another already has, in any order (`DELETE_DUPLICATE_TRIANGLES`). Default false. */
68
+ deleteDuplicateTriangles?: boolean;
69
+ /** Leaves out triangles that would give an edge a third triangle, later ones first (`DELETE_BAD_TOPOLOGY_TRIANGLES`). Default false. */
70
+ deleteBadTopologyTriangles?: boolean;
71
+ } | {
72
+ /**
73
+ * Terrain from evenly spaced heights: `heights[i]` is the y of the surface at x = -width / 2 + i width / (n - 1),
74
+ * a chain with smooth joins. The solid side is up on screen.
75
+ */
76
+ shape: 'heightfield';
77
+ heights: ArrayLike<number>;
78
+ width: number;
79
+ } | {
80
+ /**
81
+ * Everything behind a plane through the collider's position, `normal` pointing out of the solid (default [0, -1],
82
+ * up on screen). The plane is a polygon 200,000 world units across and deep: a body never reaches its edge.
83
+ */
84
+ shape: 'halfspace';
85
+ normal?: Vec2D;
86
+ } | {
87
+ /**
88
+ * A grid of solid cells, `columns` by `rows`, row by row from the top; `solid[i]` non-zero is a filled cell.
89
+ * Neighbouring cells merge into outlines, so bodies slide across their seams. The grid's top left is the offset.
90
+ * Contact is by the merged outlines, which have no thickness, so a very fast body needs `ccd: true`; scene queries meet
91
+ * the filled cells themselves, so a point inside a cell is found. The collider cannot be rotated (turn the body).
92
+ */
93
+ shape: 'voxels';
94
+ cellWidth: number;
95
+ cellHeight: number;
96
+ columns: number;
97
+ rows: number;
98
+ solid: ArrayLike<number | boolean>;
99
+ };
100
+ /** A part of a compound shape: any shape with its own placement. */
101
+ export type CompoundPart2D = ShapeOptions2D & {
102
+ offset?: Vec2D;
103
+ rotation?: number;
104
+ };
105
+ /** The questions a collider asks `Physics2D.hooks` about its pairs (Rapier's `ActiveHooks`). */
106
+ export interface ActiveHooks2D {
107
+ /** The hook's `filterPair` decides whether a pair of solid colliders meets. */
108
+ filterPair?: boolean;
109
+ /** The hook's `filterIntersection` decides whether a pair with a sensor in it intersects. */
110
+ filterIntersection?: boolean;
111
+ /** The hook's `modifyContact` may change a touching contact for the step. */
112
+ modifyContact?: boolean;
113
+ }
114
+ /** Material, sensor and filtering settings of a collider. */
115
+ export interface ColliderSettings2D {
116
+ /** Position of the collider relative to its body, world units. Default [0, 0]. */
117
+ offset?: Vec2D;
118
+ /** Rotation relative to its body, radians. Default 0. */
119
+ rotation?: number;
120
+ friction?: number;
121
+ restitution?: number;
122
+ /**
123
+ * Coefficient of rolling resistance, 0 or more (default 0, none; Box2D's rolling resistance): a contact resists the
124
+ * two bodies' relative turn with a torque of up to this times its normal force times the rolling radius (the larger
125
+ * of the two shapes' core radii: a circle's or capsule's radius), so a rolling ball slows and stops. Of two colliders
126
+ * the larger applies. Car tyres on tarmac are about 0.01, a steel wheel on rail 0.001, a ball on grass 0.05 to 0.1.
127
+ */
128
+ rollingResistance?: number;
129
+ /**
130
+ * How a contact combines this collider's friction with the other's (default `CoefficientCombineRule2D.Average`): of two
131
+ * colliders' rules the later of Average, Min, Multiply, Max, ClampedSum, GeometricMean wins, as in Rapier.
132
+ */
133
+ frictionCombineRule?: CoefficientCombineRule2D;
134
+ /** The same for restitution (default `CoefficientCombineRule2D.Average`). */
135
+ restitutionCombineRule?: CoefficientCombineRule2D;
136
+ /** Mass per square metre (Rapier units). Default 1. */
137
+ density?: number;
138
+ /** Overrides density with a total mass in Rapier units. */
139
+ mass?: number;
140
+ /** Sensors report overlaps (`intersectionstart`) and push nothing. */
141
+ sensor?: boolean;
142
+ /** Packed interaction groups, see `interactionGroups`. */
143
+ collisionGroups?: number;
144
+ /** Emit contact or intersection events (default true). */
145
+ events?: boolean;
146
+ /**
147
+ * Solver groups, packed as `collisionGroups` is: a pair whose solver groups do not meet still reports contacts but
148
+ * pushes nothing. Default: meets everything.
149
+ */
150
+ solverGroups?: number;
151
+ /**
152
+ * Which pairs of body types this collider meets, as `ActiveCollisionTypes` bits: 1 dynamic-dynamic, 2 dynamic-kinematic,
153
+ * 4 dynamic-fixed, 8 kinematic-kinematic, 16 kinematic-fixed, 32 fixed-fixed. Default 7; sensors default to all (63).
154
+ */
155
+ activeCollisionTypes?: number;
156
+ /** Report `contactforce` events when the contact's total force passes this many newtons. Default: no force events. */
157
+ contactForceThreshold?: number;
158
+ /**
159
+ * Rapier's contact skin, world units (default 0): contacts start this much farther out, and the solver holds the
160
+ * collider this far off what it touches, so two colliders rest the sum of their skins apart. Queries meet the outline.
161
+ */
162
+ contactSkin?: number;
163
+ /**
164
+ * Which questions `Physics2D.hooks` is asked about this collider's pairs: `filterPair` (may a pair of solids meet at all),
165
+ * `filterIntersection` (may a pair with a sensor in it intersect: Rapier's intersection pair filter) and `modifyContact` (change a
166
+ * touching contact). Default: none; a hook is only called for colliders that ask.
167
+ */
168
+ hooks?: ActiveHooks2D;
169
+ }
170
+ /** Options for a collider: shape plus settings. */
171
+ export type ColliderOptions2D = ShapeOptions2D & ColliderSettings2D;
172
+ /**
173
+ * Packs Rapier interaction groups into one number. `memberships` are the groups a collider belongs to and `filter` the
174
+ * groups it interacts with, each as an array of group indices 0..15 or a 16-bit mask. Two colliders interact when each
175
+ * one's filter includes a group of the other's memberships.
176
+ */
177
+ export declare function interactionGroups(memberships: number | readonly number[], filter?: number | readonly number[]): number;
178
+ /**
179
+ * How a contact combines two colliders' friction or restitution, as Rapier's `CoefficientCombineRule`: the mean, the smaller,
180
+ * the product, the larger, the sum held to 0 to 1, or the square root of the product. Of two colliders' rules the later in
181
+ * that order wins.
182
+ */
183
+ export declare const CoefficientCombineRule2D: {
184
+ readonly Average: 0;
185
+ readonly Min: 1;
186
+ readonly Multiply: 2;
187
+ readonly Max: 3;
188
+ readonly ClampedSum: 4;
189
+ readonly GeometricMean: 5;
190
+ };
191
+ export type CoefficientCombineRule2D = (typeof CoefficientCombineRule2D)[keyof typeof CoefficientCombineRule2D];
192
+ /** A combine rule checked, as its kernel number (0 to 5); the average when none is given. @internal */
193
+ export declare function combineRule(rule: number | undefined, what: string): number;
194
+ /** A collider ready for the kernel: its shape kind, the eight settings words and the geometry words, in metres. */
195
+ export interface Described {
196
+ kind: number;
197
+ settings: Uint32Array;
198
+ geometry: Uint32Array;
199
+ /** Area in square metres (0 for edges): a collider given a `mass` takes its density from it. */
200
+ area: number;
201
+ /** Whether a query can use it: the kernel's convex shapes only. */
202
+ convex: boolean;
203
+ /** A triangle of a trimesh joined with `fixInternalEdges`: the kernel joins these into one solid for contacts. */
204
+ seam?: boolean;
205
+ }
206
+ /**
207
+ * Describes a collider for the kernel; `scale` is metres per world unit. The collider's own offset and rotation are
208
+ * applied to its points here, so the kernel gets every shape in the body's frame.
209
+ */
210
+ export declare function describeShape(options: ColliderOptions2D, scale: number): Described;
211
+ /**
212
+ * Describes a collider for the kernel as one or more shapes: a compound, a mesh, a height field, a half space or a grid
213
+ * of cells becomes several, every other shape one. All of them share the collider's settings.
214
+ */
215
+ export declare function describeShapes(options: ColliderOptions2D, scale: number): Described[];
@@ -0,0 +1,84 @@
1
+ import type { ColliderOptions2D, Vec2D } from './shapes.js';
2
+ interface TileBox {
3
+ readonly x: number;
4
+ readonly y: number;
5
+ readonly width: number;
6
+ readonly height: number;
7
+ /** Clockwise degrees about (x, y). */
8
+ readonly rotation?: number;
9
+ }
10
+ interface TilePoints {
11
+ readonly x: number;
12
+ readonly y: number;
13
+ readonly points: readonly Vec2D[];
14
+ readonly rotation?: number;
15
+ }
16
+ /** A tile collision shape in tile pixels, from the tile's top left. Same fields as a Tiled collision object. */
17
+ export type TileShape = (TileBox & {
18
+ readonly kind: 'rect';
19
+ }) | (TileBox & {
20
+ readonly kind: 'ellipse';
21
+ }) | (TilePoints & {
22
+ readonly kind: 'polygon';
23
+ }) | (TilePoints & {
24
+ readonly kind: 'polyline';
25
+ }) | {
26
+ readonly kind: 'point';
27
+ readonly x: number;
28
+ readonly y: number;
29
+ };
30
+ /** The part of a tile map that collision needs. A `TileMapData` from `@margoengine/tilemap` fits as is. */
31
+ export interface TileMapSource {
32
+ /** Cell size in pixels. */
33
+ readonly tileWidth: number;
34
+ readonly tileHeight: number;
35
+ readonly tilesets: readonly {
36
+ readonly firstGid: number;
37
+ readonly tileCount: number;
38
+ readonly tileWidth: number;
39
+ readonly tileHeight: number;
40
+ readonly tileOffset?: Vec2D;
41
+ readonly tiles?: readonly {
42
+ readonly id: number;
43
+ readonly properties?: {
44
+ readonly [name: string]: unknown;
45
+ };
46
+ readonly collision?: readonly TileShape[];
47
+ }[];
48
+ }[];
49
+ readonly layers: readonly ({
50
+ readonly type: 'tile';
51
+ readonly name: string;
52
+ readonly width: number;
53
+ readonly height: number;
54
+ /** Row by row from the top left; low 28 bits are the global tile id, the top three bits are flips. */
55
+ readonly data: Uint32Array;
56
+ readonly offset?: Vec2D;
57
+ } | {
58
+ readonly type: 'object';
59
+ readonly name: string;
60
+ })[];
61
+ }
62
+ /** Options for `Physics2D.addTileMap`. */
63
+ export interface TileMapBodyOptions {
64
+ /** World2D position of the map's top left corner. Default [0, 0]. */
65
+ position?: Vec2D;
66
+ /** Which tile layers collide: names, or a test. Default every tile layer. */
67
+ layers?: readonly string[] | ((layer: {
68
+ readonly name: string;
69
+ }) => boolean);
70
+ friction?: number;
71
+ restitution?: number;
72
+ collisionGroups?: number;
73
+ userData?: unknown;
74
+ }
75
+ type Pt = [number, number];
76
+ /** Outlines of the filled cells as closed point loops in cell units: shared edges vanish, straight runs merge. */
77
+ /** @internal Closed outlines (in cells) of the solid cells of a grid, row by row from the top. */
78
+ export declare function cellOutlines(solid: Uint8Array, width: number, height: number): Pt[][];
79
+ /**
80
+ * Collider2D descriptions for a tile map's solid tiles. Whole-cell squares merge into outline loops (no seams for a body
81
+ * to catch on); every other shape becomes its own collider. Coordinates are world units.
82
+ */
83
+ export declare function tileMapColliders(map: TileMapSource, options?: TileMapBodyOptions): ColliderOptions2D[];
84
+ export {};
@@ -0,0 +1,121 @@
1
+ /// <reference lib="esnext.disposable" preserve="true" />
2
+ import type { Body2D, Collider2D } from './body.js';
3
+ import type { Physics2D } from './physics.js';
4
+ import type { Vec2D } from './shapes.js';
5
+ /** One wheel of a {@link Vehicle2D}. Positions and directions are in the chassis body's frame, in world units. */
6
+ export interface WheelOptions2D {
7
+ /** Where the suspension is mounted on the chassis (the top of its travel). */
8
+ position: Vec2D;
9
+ /** Wheel radius, world units. */
10
+ radius: number;
11
+ /** Direction the suspension extends (default [0, 1], down on screen). */
12
+ direction?: Vec2D;
13
+ /** Suspension length at rest, world units (default 0.3 m). */
14
+ suspensionRestLength?: number;
15
+ /** Spring stiffness of the suspension, per second squared of the chassis's mass (default 5.88, as Rapier's). */
16
+ suspensionStiffness?: number;
17
+ /** Damping while the suspension compresses (default 0.83). */
18
+ suspensionCompression?: number;
19
+ /** Damping while the suspension extends (default 0.88). */
20
+ suspensionRelaxation?: number;
21
+ /** Longest suspension travel, world units (default 5 m). */
22
+ maxSuspensionTravel?: number;
23
+ /** Strongest suspension force, newtons (default 6000). */
24
+ maxSuspensionForce?: number;
25
+ /** Tyre grip along the ground (default 10.5); lower slides more. */
26
+ frictionSlip?: number;
27
+ /** This wheel receives the engine force (default true). */
28
+ drive?: boolean;
29
+ /** This wheel receives the brake (default true). */
30
+ brake?: boolean;
31
+ }
32
+ /** Options of `new Vehicle2D(physics, chassis, options)`. Every field but `wheels` has a default. */
33
+ export interface VehicleOptions2D {
34
+ /** The wheels, at least one. */
35
+ wheels: readonly WheelOptions2D[];
36
+ /** The way the chassis faces, in its own frame (default [1, 0]): forward speed and drive are along it. */
37
+ forward?: Vec2D;
38
+ /** Engine force per driven wheel at full throttle, newtons (default the chassis mass in kg times 2, so two driven wheels give 0.4 g). */
39
+ maxEngineForce?: number;
40
+ /** Brake force per braking wheel at full brake, newtons (default 6 times the chassis mass). */
41
+ maxBrakeForce?: number;
42
+ /** Packed interaction groups of the wheel rays (default all). */
43
+ groups?: number;
44
+ /** Return false to make the wheels ignore a collider (the chassis's own are always ignored). */
45
+ predicate?: (collider: Collider2D) => boolean;
46
+ /** Apply each wheel's push back on a dynamic body it stands on, and drive relative to it (default true). */
47
+ groundReaction?: boolean;
48
+ }
49
+ /** Driver input for {@link Vehicle2D.setInput}, each axis normalized. */
50
+ export interface VehicleInput2D {
51
+ /** -1 (full reverse) to 1 (full throttle). */
52
+ throttle?: number;
53
+ /** 0 (off) to 1 (full brake). */
54
+ brake?: number;
55
+ }
56
+ /** The state of one wheel after the last step. Lengths and points are in world units. */
57
+ export interface WheelState2D {
58
+ /** The wheel touches the ground. */
59
+ inContact: boolean;
60
+ /** Current suspension length. */
61
+ suspensionLength: number;
62
+ /** Suspension force, newtons. */
63
+ suspensionForce: number;
64
+ /** Spin angle, radians, clockwise on screen as the wheel rolls forward. */
65
+ rotation: number;
66
+ /** Contact point, or null in the air. */
67
+ contactPoint: [number, number] | null;
68
+ /** Contact normal, or null in the air. */
69
+ contactNormal: [number, number] | null;
70
+ /** The collider the wheel stands on, or null in the air. */
71
+ ground: Collider2D | null;
72
+ /** Where the suspension is mounted, in world space. */
73
+ hardPoint: [number, number];
74
+ /** What the tyre pushed the chassis with along the ground in the last step (drive and brake), newton seconds. */
75
+ forwardImpulse: number;
76
+ }
77
+ /**
78
+ * A ray cast vehicle in 2D (Rapier's `DynamicRayCastVehicleController`, seen from the side). Steps itself before every
79
+ * fixed step of its world; `engineForce` and `brake` (or `setInput`) drive it. Its pushes are held on the chassis (and on a
80
+ * dynamic body under a wheel) as forces for the step, beside the body's own: `resetForces` on the chassis clears them until
81
+ * the next step. `dispose()` (or `using`) detaches it and takes them back.
82
+ */
83
+ export declare class Vehicle2D {
84
+ private readonly physics;
85
+ readonly chassis: Body2D;
86
+ /** Engine force on each driven wheel this step, newtons; negative drives backward. */
87
+ engineForce: number;
88
+ /** Brake force on each braking wheel this step, newtons. */
89
+ brake: number;
90
+ private readonly wheels;
91
+ private readonly forward;
92
+ private readonly maxEngine;
93
+ private readonly maxBrake;
94
+ private readonly groups;
95
+ private readonly predicate;
96
+ private readonly groundReaction;
97
+ private readonly detach;
98
+ private disposed;
99
+ /** The force (newtons) and torque (newton metres) this vehicle holds on each body for the step, so the next step changes only its own share. */
100
+ private held;
101
+ /** @throws RangeError for no wheels or a wheel setting that is not finite or below 0. */
102
+ constructor(physics: Physics2D, chassis: Body2D, options: VehicleOptions2D);
103
+ /** Sets `engineForce` and `brake` from normalized input. @returns this vehicle. */
104
+ setInput(input: VehicleInput2D): this;
105
+ /** The chassis's speed along the way it faces, world units a second (Rapier's `currentVehicleSpeed`). */
106
+ get speed(): number;
107
+ /** How many wheels the vehicle has. */
108
+ get wheelCount(): number;
109
+ /** The state of wheel `index` after the last step. @throws RangeError for an index out of range. */
110
+ wheel(index: number): WheelState2D;
111
+ /** Where wheel `index`'s centre is, in world units, from its mount down its suspension. */
112
+ wheelCenter(index: number): [number, number];
113
+ /** Detaches the vehicle from its world; the chassis stays. */
114
+ dispose(): void;
115
+ [Symbol.dispose](): void;
116
+ private turn;
117
+ private facing;
118
+ private update;
119
+ /** Holds `next` on its bodies in place of what the vehicle held before, changing each body by the difference only. */
120
+ private hold;
121
+ }
@@ -0,0 +1,178 @@
1
+ //#region src/vehicle.ts
2
+ var e = (e, t) => {
3
+ let n = Math.hypot(e[0], e[1]);
4
+ if (!(n > 0) || !Number.isFinite(n)) throw RangeError(`Vehicle2D ${t} must be a finite vector that is not zero; got [${e[0]}, ${e[1]}].`);
5
+ return [e[0] / n, e[1] / n];
6
+ }, t = (e, t, n, r = !1) => {
7
+ let i = e ?? t;
8
+ if (!Number.isFinite(i) || i < 0 || r && i === 0) throw RangeError(`Vehicle2D ${n} must be a finite number ${r ? "above" : "of"} 0${r ? "" : " or more"}; got ${i}.`);
9
+ return i;
10
+ }, n = class {
11
+ constructor(n, r, i) {
12
+ if (this.physics = n, this.chassis = r, this.engineForce = 0, this.brake = 0, this.disposed = !1, this.held = /* @__PURE__ */ new Map(), !i?.wheels?.length) throw RangeError("A Vehicle2D needs at least one wheel; pass wheels: [{ position, radius }].");
13
+ let a = 1 / n.scale;
14
+ this.wheels = i.wheels.map((n, r) => {
15
+ let i = `wheel ${r}`;
16
+ if (!Number.isFinite(n.position?.[0]) || !Number.isFinite(n.position?.[1])) throw RangeError(`Vehicle2D ${i} position must be two finite numbers; got ${n.position}.`);
17
+ return {
18
+ position: [n.position[0], n.position[1]],
19
+ direction: e(n.direction ?? [0, 1], `${i} direction`),
20
+ radius: t(n.radius, NaN, `${i} radius`, !0),
21
+ rest: t(n.suspensionRestLength, .3 * a, `${i} suspensionRestLength`),
22
+ travel: t(n.maxSuspensionTravel, 5 * a, `${i} maxSuspensionTravel`),
23
+ stiffness: t(n.suspensionStiffness, 5.88, `${i} suspensionStiffness`),
24
+ compression: t(n.suspensionCompression, .83, `${i} suspensionCompression`),
25
+ relaxation: t(n.suspensionRelaxation, .88, `${i} suspensionRelaxation`),
26
+ maxForce: t(n.maxSuspensionForce, 6e3, `${i} maxSuspensionForce`),
27
+ slip: t(n.frictionSlip, 10.5, `${i} frictionSlip`),
28
+ drive: n.drive ?? !0,
29
+ brake: n.brake ?? !0,
30
+ contact: !1,
31
+ length: 0,
32
+ force: 0,
33
+ rotation: 0,
34
+ point: [0, 0],
35
+ normal: [0, 0],
36
+ ground: null,
37
+ hard: [0, 0],
38
+ forwardImpulse: 0
39
+ };
40
+ });
41
+ for (let e of this.wheels) e.length = e.rest;
42
+ this.forward = e(i.forward ?? [1, 0], "forward"), this.maxEngine = t(i.maxEngineForce, 2 * r.mass, "maxEngineForce"), this.maxBrake = t(i.maxBrakeForce, 6 * r.mass, "maxBrakeForce"), this.groups = i.groups, this.predicate = i.predicate, this.groundReaction = i.groundReaction ?? !0, this.detach = n.on("beforestep", (e) => this.update(e));
43
+ }
44
+ setInput(e) {
45
+ let t = Math.max(-1, Math.min(1, e.throttle ?? 0)), n = Math.max(0, Math.min(1, e.brake ?? 0));
46
+ return this.engineForce = t * this.maxEngine, this.brake = n * this.maxBrake, this;
47
+ }
48
+ get speed() {
49
+ let e = this.chassis.linearVelocity, t = this.facing();
50
+ return e[0] * t[0] + e[1] * t[1];
51
+ }
52
+ get wheelCount() {
53
+ return this.wheels.length;
54
+ }
55
+ wheel(e) {
56
+ let t = this.wheels[e];
57
+ if (!t) throw RangeError(`Vehicle2D has wheels 0 to ${this.wheels.length - 1}; got ${e}.`);
58
+ return {
59
+ inContact: t.contact,
60
+ suspensionLength: t.length,
61
+ suspensionForce: t.force,
62
+ rotation: t.rotation,
63
+ contactPoint: t.contact ? [t.point[0], t.point[1]] : null,
64
+ contactNormal: t.contact ? [t.normal[0], t.normal[1]] : null,
65
+ ground: t.ground,
66
+ hardPoint: [t.hard[0], t.hard[1]],
67
+ forwardImpulse: t.forwardImpulse
68
+ };
69
+ }
70
+ wheelCenter(e) {
71
+ let t = this.wheels[e];
72
+ if (!t) throw RangeError(`Vehicle2D has wheels 0 to ${this.wheels.length - 1}; got ${e}.`);
73
+ let n = this.turn(t.direction);
74
+ return [t.hard[0] + n[0] * t.length, t.hard[1] + n[1] * t.length];
75
+ }
76
+ dispose() {
77
+ this.disposed || (this.disposed = !0, this.detach(), this.hold(/* @__PURE__ */ new Map()));
78
+ }
79
+ [Symbol.dispose]() {
80
+ this.dispose();
81
+ }
82
+ turn(e) {
83
+ let t = this.chassis.rotation, n = Math.cos(t), r = Math.sin(t);
84
+ return [n * e[0] - r * e[1], r * e[0] + n * e[1]];
85
+ }
86
+ facing() {
87
+ return this.turn(this.forward);
88
+ }
89
+ update(e) {
90
+ let t = this.chassis;
91
+ if (this.disposed || t.isRemoved) return;
92
+ if (t.sleeping) {
93
+ if (this.engineForce === 0 && this.brake === 0) return this.hold(/* @__PURE__ */ new Map());
94
+ t.wakeUp();
95
+ }
96
+ let n = this.physics.scale, r = t.position, i = t.centerOfMass, a = t.linearVelocity, o = t.angularVelocity, s = t.mass, c = (e, n) => {
97
+ let r = e === t ? a : e.linearVelocity, s = e === t ? o : e.angularVelocity, c = e === t ? i : e.centerOfMass;
98
+ return [r[0] - s * (n[1] - c[1]), r[1] + s * (n[0] - c[0])];
99
+ }, l = (e, t, r) => {
100
+ if (!e) return 0;
101
+ let i = e.centerOfMass, a = ((t[0] - i[0]) * r[1] - (t[1] - i[1]) * r[0]) * n, o = e.mass, s = e.rotationLocked ? 0 : e.inertia * n * n;
102
+ return (o > 0 ? 1 / o : 0) + (s > 0 ? a * a / s : 0);
103
+ }, u = (e) => {
104
+ let t = this.groundReaction ? e.ground?.body : void 0;
105
+ return t && t.type === "dynamic" ? t : null;
106
+ }, d = (e, n) => {
107
+ let r = c(t, n), i = this.groundReaction && e.ground ? c(e.ground.body, n) : [0, 0];
108
+ return [r[0] - i[0], r[1] - i[1]];
109
+ }, f = /* @__PURE__ */ new Map(), p = (r, a, o) => {
110
+ let s = [a[0] / e, a[1] / e], c = r === t ? i : r.centerOfMass, l = f.get(r) ?? {
111
+ force: [0, 0],
112
+ torque: 0
113
+ };
114
+ l.force[0] += s[0], l.force[1] += s[1], l.torque += ((o[0] - c[0]) * s[1] - (o[1] - c[1]) * s[0]) * n, f.set(r, l);
115
+ }, m = (e, n, r) => {
116
+ if (n[0] === 0 && n[1] === 0) return;
117
+ p(t, n, r);
118
+ let i = u(e);
119
+ i && p(i, [-n[0], -n[1]], r);
120
+ }, h = this.predicate && ((e, t) => this.predicate(t));
121
+ for (let i of this.wheels) {
122
+ let a = this.turn(i.position), o = [r[0] + a[0], r[1] + a[1]], c = this.turn(i.direction);
123
+ i.hard = o, i.forwardImpulse = 0;
124
+ let l = this.physics.raycast(o, c, {
125
+ maxDistance: i.rest + i.radius,
126
+ exclude: t,
127
+ excludeSensors: !0,
128
+ groups: this.groups,
129
+ predicate: h
130
+ });
131
+ if (!l) {
132
+ i.contact = !1, i.ground = null, i.length = i.rest, i.force = 0;
133
+ continue;
134
+ }
135
+ i.contact = !0, i.ground = l.collider, i.point = l.point, i.normal = l.normal;
136
+ let u = Math.max(0, i.rest - i.travel);
137
+ i.length = Math.min(i.rest, Math.max(u, l.distance - i.radius));
138
+ let f = -(l.normal[0] * c[0] + l.normal[1] * c[1]), p = 10, g = 0;
139
+ if (f > .1) {
140
+ p = 1 / f;
141
+ let e = d(i, l.point);
142
+ g = (l.normal[0] * e[0] + l.normal[1] * e[1]) * n * p;
143
+ }
144
+ let _ = i.stiffness * (i.rest - i.length) * n * p;
145
+ _ -= (g < 0 ? i.compression : i.relaxation) * g, _ = Math.min(i.maxForce, Math.max(0, _ * s)), i.force = _, m(i, [l.normal[0] * _ * e, l.normal[1] * _ * e], l.point);
146
+ }
147
+ let g = this.wheels.filter((e) => e.contact).length, _ = this.facing();
148
+ for (let r of this.wheels) {
149
+ if (!r.contact) continue;
150
+ let i = r.normal, a = [-i[1], i[0]];
151
+ a[0] * _[0] + a[1] * _[1] < 0 && (a = [i[1], -i[0]]);
152
+ let o = d(r, r.point), s = (a[0] * o[0] + a[1] * o[1]) * n, c = l(t, r.point, a) + l(u(r), r.point, a), f = r.drive ? this.engineForce * e : 0;
153
+ if (r.brake && this.brake > 0 && c > 0) {
154
+ let t = -s / c / g, n = this.brake * e;
155
+ f += Math.max(-n, Math.min(n, t));
156
+ }
157
+ let p = r.slip * r.force * e;
158
+ f = Math.max(-p, Math.min(p, f)), r.forwardImpulse = f, m(r, [a[0] * f, a[1] * f], r.point), r.rotation += s / n / r.radius * e;
159
+ }
160
+ this.hold(f);
161
+ }
162
+ hold(e) {
163
+ for (let t of /* @__PURE__ */ new Set([...this.held.keys(), ...e.keys()])) {
164
+ if (t.isRemoved) continue;
165
+ let n = this.held.get(t) ?? {
166
+ force: [0, 0],
167
+ torque: 0
168
+ }, r = e.get(t) ?? {
169
+ force: [0, 0],
170
+ torque: 0
171
+ }, i = [r.force[0] - n.force[0], r.force[1] - n.force[1]], a = r.torque - n.torque;
172
+ (i[0] !== 0 || i[1] !== 0) && t.applyForce(i), a !== 0 && t.applyTorque(a);
173
+ }
174
+ this.held = e;
175
+ }
176
+ };
177
+ //#endregion
178
+ export { n as Vehicle2D };
@@ -0,0 +1,21 @@
1
+ /** Where the kernel's Wasm comes from: a URL, a fetched `Response`, its bytes or a compiled `WebAssembly.Module`. */
2
+ export type KernelWasmSource = string | URL | Response | ArrayBuffer | ArrayBufferView | WebAssembly.Module;
3
+ /** What the loader knows of the build it expects. */
4
+ export interface KernelBuild {
5
+ file: string;
6
+ /** The interface version `api_version()` reports. */
7
+ version: string;
8
+ /** A hash of the module's exports and imports. */
9
+ interface: number;
10
+ /** What the module imports: the page's hook functions. */
11
+ imports: WebAssembly.Imports;
12
+ }
13
+ /** FNV-1a over the module's exports and imports. */
14
+ export declare function interfaceHash(module: WebAssembly.Module): number;
15
+ /**
16
+ * Compiles the kernel's Wasm from `source`, checks it is the bundled build and returns the instance's exports. Any valid
17
+ * Wasm instantiates, so a foreign module (a wrong URL that serves some other Wasm, an older kernel) would otherwise
18
+ * reach the typed calls: its exports and imports must match the bundled build's, and the version it reports must be the
19
+ * bundled one. `signal` cancels the download and the wait.
20
+ */
21
+ export declare function instantiateKernel(source: KernelWasmSource, signal: AbortSignal, build: KernelBuild): Promise<WebAssembly.Exports>;