@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,229 @@
1
+ import type { Kernel } from './kernel.js';
2
+ import type { Body2D } from './body.js';
3
+ import type { Vec2D } from './shapes.js';
4
+ /** Motor of a revolute or prismatic joint. Give a target velocity, a target position, or both. */
5
+ export interface MotorOptions2D {
6
+ /** Radians per second (revolute) or world units per second (prismatic). */
7
+ targetVelocity?: number;
8
+ /** How hard it chases the velocity. Default 1. */
9
+ factor?: number;
10
+ /** Radians (revolute) or world units (prismatic). */
11
+ targetPosition?: number;
12
+ stiffness?: number;
13
+ damping?: number;
14
+ maxForce?: number;
15
+ /**
16
+ * `'force'` (default): `stiffness` and `damping` are forces, per unit of error and of speed, so a heavy body follows the motor
17
+ * slowly. `'acceleration'`: they are per unit of the joint's effective mass, so a light body and a heavy one follow it alike
18
+ * (Rapier's default model).
19
+ */
20
+ model?: 'force' | 'acceleration';
21
+ }
22
+ /** Options for a joint between two bodies. Anchors are in each body's local space, world units. */
23
+ export type JointOptions2D = {
24
+ anchorA?: Vec2D;
25
+ anchorB?: Vec2D;
26
+ /**
27
+ * Break the joint when it holds body B by more than this force, N (default none: it never breaks). It goes once a step is
28
+ * done, with a `jointbreak` event (Box2D's joint force threshold).
29
+ */
30
+ breakForce?: number;
31
+ /** Break it when it holds body B by more than this torque, N m (default none). */
32
+ breakTorque?: number;
33
+ /** Let the two bodies collide with each other (default false). */
34
+ collide?: boolean;
35
+ /**
36
+ * Accepted for code written for Rapier's multibody joints and ignored: every chain of joints solves exactly (block
37
+ * elimination along the chain), so a long chain under a heavy end does not stretch. For joint-space control and inverse
38
+ * kinematics use `Physics2D.addArticulation`.
39
+ */
40
+ multibody?: boolean;
41
+ } & ({
42
+ type: 'revolute';
43
+ limits?: readonly [number, number];
44
+ motor?: MotorOptions2D;
45
+ } | {
46
+ type: 'prismatic';
47
+ axis: Vec2D;
48
+ limits?: readonly [number, number];
49
+ motor?: MotorOptions2D;
50
+ } | {
51
+ /**
52
+ * Welds B to A. `linearHertz` and `angularHertz` (default 0, rigid) make the weld a spring on the point and on the
53
+ * angle with damping ratios `linearDampingRatio` and `angularDampingRatio` (default 1): Box2D's soft weld, Planck's
54
+ * `frequencyHz`, for a bending plank or a wobbly stack of parts.
55
+ */
56
+ type: 'fixed';
57
+ angleA?: number;
58
+ angleB?: number;
59
+ linearHertz?: number;
60
+ angularHertz?: number;
61
+ linearDampingRatio?: number;
62
+ angularDampingRatio?: number;
63
+ } | {
64
+ /**
65
+ * Any mix of the three locks of a plane joint: `lockX` and `lockY` hold the anchors' offset along the first and the
66
+ * second axis of body A's frame (both together pin a point, one alone is a pin-slot that slides along the other
67
+ * axis), `lockAngle` holds the turn between the frames. `frameA` and `frameB` (radians, default 0) turn the frames;
68
+ * the joint holds B's frame turned by `frameB` against A's turned by `frameA`.
69
+ */
70
+ type: 'generic';
71
+ lockX?: boolean;
72
+ lockY?: boolean;
73
+ lockAngle?: boolean;
74
+ frameA?: number;
75
+ frameB?: number;
76
+ } | {
77
+ /** A pin-slot: the anchors slide along `axis` (in body A's frame) and the bodies turn freely. */
78
+ type: 'slot';
79
+ axis: Vec2D;
80
+ } | {
81
+ type: 'rope';
82
+ length: number;
83
+ } | {
84
+ type: 'spring';
85
+ restLength: number;
86
+ stiffness: number;
87
+ damping?: number;
88
+ } | {
89
+ /**
90
+ * Pulls body B's anchor to `target` (world units, a point in the world) by a spring of `hertz` (default 5) and damping
91
+ * ratio `damping` (default 0.7), its pull capped at `maxForce` N (default no cap): Box2D's and Planck's mouse joint,
92
+ * Matter's mouse constraint, for dragging a body. Body A only holds the target (a fixed body); move it with
93
+ * `joint.setTarget`. `anchorA` is ignored.
94
+ */
95
+ type: 'target';
96
+ target: Vec2D;
97
+ hertz?: number;
98
+ damping?: number;
99
+ maxForce?: number;
100
+ } | {
101
+ /**
102
+ * Drives body B to sit `linearOffset` (world units, in A's frame, default [0, 0]) from A and turned `angularOffset`
103
+ * (radians, default 0) from it, at most `maxForce` N and `maxTorque` N m, taking back `correctionFactor` (0 to 1,
104
+ * default 0.3) of the error each substep: Box2D's and Planck.js's motor joint, to move a body by force (a platform, a
105
+ * character's body). The anchors are not used.
106
+ */
107
+ type: 'motor';
108
+ linearOffset?: Vec2D;
109
+ angularOffset?: number;
110
+ maxForce: number;
111
+ maxTorque: number;
112
+ correctionFactor?: number;
113
+ } | {
114
+ /**
115
+ * Holds the relative speed at the anchors and the relative spin at zero, with at most `maxForce` N and `maxTorque` N m:
116
+ * Box2D's and Planck.js's friction joint, a top-down game's ground friction (body A the ground).
117
+ */
118
+ type: 'friction';
119
+ maxForce: number;
120
+ maxTorque: number;
121
+ } | {
122
+ /**
123
+ * A wheel on a suspension (Box2D's and Planck.js's wheel joint): B's anchor rides the line through A's anchor along
124
+ * `axis` (A's frame), B turns freely, a spring of `hertz` (default 1; 0 for none) and damping ratio `damping` (default
125
+ * 0.7) pulls it back along the line whatever the load, `limits` bound the travel (world units) and `motor` drives the
126
+ * wheel's turn (radians).
127
+ */
128
+ type: 'wheel';
129
+ axis: Vec2D;
130
+ hertz?: number;
131
+ damping?: number;
132
+ limits?: readonly [number, number];
133
+ motor?: MotorOptions2D;
134
+ } | {
135
+ /**
136
+ * A rope over two pulleys fixed in the world (Box2D's and Planck.js's pulley joint): A's anchor hangs from
137
+ * `groundA` and B's from `groundB` (world units), and A's strand plus `ratio` (default 1) times B's stays at
138
+ * `length` (world units, default the two strands' lengths when the joint is made). A ratio of 2 is a block and
139
+ * tackle: B moves half as far as A.
140
+ */
141
+ type: 'pulley';
142
+ groundA: Vec2D;
143
+ groundB: Vec2D;
144
+ ratio?: number;
145
+ length?: number;
146
+ } | {
147
+ /**
148
+ * Box2D's distance joint: the anchors held `length` apart (world units, default their distance when the joint is
149
+ * made), rigidly, or by a `spring` of `hertz` and damping ratio `damping` (default 0.7) on the line's own
150
+ * effective mass (hertz 0 lets the length go free), kept within `limits` [min, max] (world units), with a `motor`
151
+ * on the length (world units). A rope is a distance joint with a spring of 0 Hz and an upper limit.
152
+ */
153
+ type: 'distance';
154
+ length?: number;
155
+ spring?: {
156
+ hertz: number;
157
+ damping?: number;
158
+ };
159
+ limits?: readonly [number, number];
160
+ motor?: MotorOptions2D;
161
+ } | {
162
+ /**
163
+ * Gears two joints together (Planck.js's gear joint): `jointA`'s coordinate plus `ratio` (default 1, below 0 to turn
164
+ * the same way) times `jointB`'s stays as it was when the gear was made. Each is a revolute joint (its coordinate
165
+ * the turn, radians, past any number of turns) or a prismatic joint (its travel, world units) from its carrier (its
166
+ * body A, which may move: gears on a car's body) to this joint's body: `jointA` holds body A, `jointB` body B. Two
167
+ * gears of radii rA and rB mesh at ratio rB / rA; a pinion of radius r on a rack at ratio 1 / r or -1 / r, the sign
168
+ * setting which way the rack runs. Removing either joint removes the gear. The anchors are not used.
169
+ */
170
+ type: 'gear';
171
+ jointA: Joint2D;
172
+ jointB: Joint2D;
173
+ ratio?: number;
174
+ });
175
+ /** @internal Writes a joint's buffer words (kernel/src/api.rs, `joint_create`) and returns the unit of its limits. */
176
+ export declare function writeJoint(kernel: Kernel, o: JointOptions2D, k: number): number;
177
+ /** A joint between two bodies. */
178
+ export declare class Joint2D {
179
+ private readonly kernel;
180
+ private readonly world;
181
+ /** The kernel's handle. @internal */
182
+ readonly handle: number;
183
+ readonly bodyA: Body2D;
184
+ readonly bodyB: Body2D;
185
+ private readonly type;
186
+ private readonly unit;
187
+ private readonly onRemove;
188
+ /** Kernel metres a world unit. @internal */
189
+ private readonly scale;
190
+ /** The options it was made with (a gear reads its joints' carriers from them). @internal */
191
+ readonly spec?: JointOptions2D | undefined;
192
+ private removed;
193
+ /** @internal */
194
+ constructor(kernel: Kernel, world: number,
195
+ /** The kernel's handle. @internal */
196
+ handle: number, bodyA: Body2D, bodyB: Body2D, type: JointOptions2D['type'], unit: number, onRemove: (joint: Joint2D) => void,
197
+ /** Kernel metres a world unit. @internal */
198
+ scale?: number,
199
+ /** The options it was made with (a gear reads its joints' carriers from them). @internal */
200
+ spec?: JointOptions2D | undefined);
201
+ /** A target joint's target: moves where it pulls body B's anchor to (world units), and wakes the bodies. */
202
+ setTarget(target: Vec2D): this;
203
+ private get limited();
204
+ /** Revolute: radians. Prismatic and wheel: world units along the line. */
205
+ setLimits(min: number, max: number): this;
206
+ /** Removes the limits. */
207
+ clearLimits(): this;
208
+ setMotor(motor: MotorOptions2D): this;
209
+ /** Turns the motor off. */
210
+ clearMotor(): this;
211
+ /**
212
+ * The force this joint put on body B in its last step's last substep, N (kernel units, y down): how hard it holds B. Zero
213
+ * before its first step and, after a `restore`, until the next step.
214
+ */
215
+ get force(): [number, number];
216
+ /** The torque this joint put on body B about B's centre of mass in its last substep, N m. */
217
+ get torque(): number;
218
+ /** @internal */
219
+ reaction(): [number, number, number];
220
+ /** Whether the joint was removed (by `remove`, its bodies' removal, or breaking). */
221
+ get isRemoved(): boolean;
222
+ remove(): void;
223
+ /** @internal */
224
+ free(): void;
225
+ }
226
+ /** A world point in `body`'s own frame, from its origin (world units). */
227
+ /** @internal A point in `body`'s frame, in the world. */
228
+ export declare function worldOf(body: Body2D, x: number, y: number): [number, number];
229
+ export declare function localTo(body: Body2D, x: number, y: number): [number, number];
@@ -0,0 +1,159 @@
1
+ import { MargoError as e } from "@margoengine/math/errors";
2
+ //#region src/wasm-load.ts
3
+ var t = (e) => import(
4
+ /* @vite-ignore */
5
+ /* webpackIgnore: true */
6
+ e
7
+ );
8
+ function n(e) {
9
+ let t = WebAssembly.Module.exports(e).map((e) => `${e.kind}:${e.name}`).join(",") + "|" + WebAssembly.Module.imports(e).map((e) => `${e.kind}:${e.module}:${e.name}`).join(","), n = 2166136261;
10
+ for (let e = 0; e < t.length; e++) n = Math.imul(n ^ t.charCodeAt(e), 16777619);
11
+ return n >>> 0;
12
+ }
13
+ var r = (t, n, r) => Object.assign(new e("failed", `Physics2D kernel's Wasm ${n}; serve dist/${t.file} from @margoengine/physics2d, or pass Physics2D.load({wasm}) a URL that serves it`), r === void 0 ? {} : { cause: r });
14
+ async function i(e, t) {
15
+ let { module: n, instance: r } = await WebAssembly.instantiate(e, t.imports);
16
+ return {
17
+ module: n,
18
+ instance: r
19
+ };
20
+ }
21
+ async function a(e, t, n) {
22
+ if (!e.ok) throw r(n, `could not be fetched from ${e.url || "the response"} (${e.status} ${e.statusText})`.trimEnd());
23
+ if (typeof WebAssembly.instantiateStreaming == "function" && /^application\/wasm\b/i.test(e.headers.get("content-type") ?? "")) return WebAssembly.instantiateStreaming(e, n.imports).then(({ module: e, instance: t }) => ({
24
+ module: e,
25
+ instance: t
26
+ }));
27
+ let a = await e.arrayBuffer();
28
+ return t.throwIfAborted(), i(a, n);
29
+ }
30
+ async function o(e, n, o) {
31
+ if (e instanceof WebAssembly.Module) return {
32
+ module: e,
33
+ instance: await WebAssembly.instantiate(e, o.imports)
34
+ };
35
+ if (typeof Response == "function" && e instanceof Response) return a(e, n, o);
36
+ if (e instanceof ArrayBuffer || ArrayBuffer.isView(e)) return i(e, o);
37
+ let s;
38
+ try {
39
+ s = new URL(e, globalThis.location?.href);
40
+ } catch (t) {
41
+ throw TypeError(`Physics2D.load wasm must be a URL, a Response, bytes or a WebAssembly.Module; got ${String(e)}`, { cause: t });
42
+ }
43
+ if (s.protocol === "file:") {
44
+ let { readFile: e } = await t("node:fs/promises"), a;
45
+ try {
46
+ a = await e(s, { signal: n });
47
+ } catch (e) {
48
+ throw n.aborted ? n.reason : r(o, `could not be read from ${s.href}`, e);
49
+ }
50
+ return i(a, o);
51
+ }
52
+ let c;
53
+ try {
54
+ c = await fetch(s, { signal: n });
55
+ } catch (e) {
56
+ throw n.aborted ? n.reason : r(o, `could not be fetched from ${s.href}`, e);
57
+ }
58
+ return a(c, n, o);
59
+ }
60
+ async function s(e, t, i) {
61
+ t.throwIfAborted();
62
+ let a;
63
+ try {
64
+ a = await o(e, t, i);
65
+ } catch (e) {
66
+ throw t.aborted ? t.reason : e instanceof WebAssembly.CompileError || e instanceof WebAssembly.LinkError ? /wasm-unsafe-eval|content security policy|\bCSP\b|disallowed by embedder/i.test(e.message) ? e : r(i, "is not the Physics2D kernel build this package bundles", e) : e;
67
+ }
68
+ if (t.throwIfAborted(), n(a.module) !== i.interface) throw r(i, "is not the Physics2D kernel build this package bundles (its exports and imports differ)");
69
+ let s = String(a.instance.exports.api_version());
70
+ if (s !== i.version) throw r(i, `is Physics2D kernel ${s}, not the ${i.version} build this package bundles`);
71
+ return a.instance.exports;
72
+ }
73
+ //#endregion
74
+ //#region src/kernel.ts
75
+ var c = (e = !1) => e ? new URL("./physics2d-scalar.wasm?no-inline", import.meta.url) : new URL("./physics2d.wasm?no-inline", import.meta.url), l = () => WebAssembly.validate(new Uint8Array([
76
+ 0,
77
+ 97,
78
+ 115,
79
+ 109,
80
+ 1,
81
+ 0,
82
+ 0,
83
+ 0,
84
+ 1,
85
+ 5,
86
+ 1,
87
+ 96,
88
+ 0,
89
+ 1,
90
+ 123,
91
+ 3,
92
+ 2,
93
+ 1,
94
+ 0,
95
+ 10,
96
+ 10,
97
+ 1,
98
+ 8,
99
+ 0,
100
+ 65,
101
+ 0,
102
+ 253,
103
+ 15,
104
+ 253,
105
+ 98,
106
+ 11
107
+ ])), u = [
108
+ ["PHYSICS2D_NOT_FINITE", "a number is not finite; fix the value"],
109
+ ["PHYSICS2D_INVALID_CORE", "the shape is not a valid collider; check its size and points"],
110
+ ["PHYSICS2D_DEGENERATE", "the shape has no area or length, or its outline crosses itself; fix the points"],
111
+ ["PHYSICS2D_ARITHMETIC_OVERFLOW", "a value is too large to simulate; use smaller sizes, densities and speeds"],
112
+ ["PHYSICS2D_INVALID_HANDLE", "the body, collider or joint was removed or never existed"],
113
+ ["PHYSICS2D_INVALID_PARAMETER", "a value is outside its range"]
114
+ ];
115
+ function d(t) {
116
+ let [n, r] = u[-t - 1] ?? ["PHYSICS2D_UNKNOWN", "the kernel refused the call"];
117
+ return n === "PHYSICS2D_INVALID_HANDLE" ? new e("state", `Physics2D: ${r}. (${n})`) : Object.assign(/* @__PURE__ */ RangeError(`Physics2D: ${r}. (${n})`), { code: n });
118
+ }
119
+ var f = class {
120
+ constructor(e) {
121
+ this.x = e, this.at = 0, this.hooks = null;
122
+ }
123
+ io(e) {
124
+ let t = this.at = this.x.io_reserve(e), n = this.x.memory.buffer;
125
+ return {
126
+ f: new Float32Array(n, t, e),
127
+ u: new Uint32Array(n, t, e)
128
+ };
129
+ }
130
+ current(e) {
131
+ let t = this.x.memory.buffer;
132
+ return {
133
+ f: new Float32Array(t, this.at, e),
134
+ u: new Uint32Array(t, this.at, e)
135
+ };
136
+ }
137
+ ok(e) {
138
+ if (e < 0) throw d(e);
139
+ return e;
140
+ }
141
+ get exports() {
142
+ return this.x;
143
+ }
144
+ };
145
+ async function p(e, t) {
146
+ let n = null;
147
+ return n = new f(await s(e, t, {
148
+ file: "physics2d.wasm",
149
+ version: "1",
150
+ interface: 3796861126,
151
+ imports: { env: {
152
+ clock: () => performance.now(),
153
+ hook_filter: (e, t) => n?.hooks ? +!!n.hooks.filter(e, t) : 1,
154
+ hook_contact: (e, t, r, i, a) => n?.hooks ? n.hooks.contact(e, t, r, i, a) : 0
155
+ } }
156
+ })), n;
157
+ }
158
+ //#endregion
159
+ export { c as defaultWasm, l as hasSimd, p as startKernel };
@@ -0,0 +1,107 @@
1
+ import { type KernelWasmSource } from './wasm-load.js';
2
+ export type { KernelWasmSource };
3
+ /**
4
+ * The Wasm this package ships, beside this chunk in dist. The literal reaches the app's bundler unchanged, which emits
5
+ * the file as an asset; `?no-inline` keeps Vite (in library mode too) from inlining it as base64.
6
+ */
7
+ export declare const defaultWasm: (scalar?: boolean) => URL;
8
+ /** Whether this engine compiles Wasm SIMD: a module with one 128-bit instruction (the probe of the wasm-feature-detect project). */
9
+ export declare const hasSimd: () => boolean;
10
+ interface Exports {
11
+ memory: WebAssembly.Memory;
12
+ api_version(): number;
13
+ io_reserve(words: number): number;
14
+ world_create(gx: number, gy: number): number;
15
+ world_destroy(world: number): number;
16
+ world_set_gravity(world: number, gx: number, gy: number): number;
17
+ world_step(world: number, dt: number): number;
18
+ world_timing(world: number, phase: number): number;
19
+ world_counts(world: number): number;
20
+ world_set_setting(world: number, which: number, value: number): number;
21
+ world_settings(world: number): number;
22
+ body_create(world: number, kind: number, flags: number): number;
23
+ body_remove(world: number, body: number): number;
24
+ body_read(world: number, body: number): number;
25
+ body_read_poses(world: number, count: number): number;
26
+ body_set_transform(world: number, body: number, x: number, y: number, c: number, s: number): number;
27
+ body_set_velocity(world: number, body: number, vx: number, vy: number, av: number): number;
28
+ body_impulse(world: number, body: number, jx: number, jy: number, has: number, px: number, py: number): number;
29
+ body_torque_impulse(world: number, body: number, torque: number): number;
30
+ body_add_force(world: number, body: number, fx: number, fy: number, torque: number): number;
31
+ body_reset_forces(world: number, body: number): number;
32
+ body_reset_torques(world: number, body: number): number;
33
+ body_add_force_at(world: number, body: number, fx: number, fy: number, px: number, py: number): number;
34
+ body_set_params(world: number, body: number, ld: number, ad: number, gs: number, flags: number, dominance: number): number;
35
+ body_set_fixed_rotation(world: number, body: number, fixed: number): number;
36
+ body_set_next(world: number, body: number, x: number, y: number, c: number, s: number): number;
37
+ body_wake(world: number, body: number): number;
38
+ body_sleep(world: number, body: number): number;
39
+ body_set_additional_mass(world: number, body: number, mass: number): number;
40
+ body_set_enabled(world: number, body: number, enabled: number): number;
41
+ body_set_max_angular_speed(world: number, body: number, speed: number): number;
42
+ body_set_extra_passes(world: number, body: number, passes: number): number;
43
+ body_set_extra_substeps(world: number, body: number, substeps: number): number;
44
+ body_set_additional_mass_properties(world: number, body: number, mass: number, x: number, y: number, inertia: number): number;
45
+ body_set_kind(world: number, body: number, kind: number): number;
46
+ body_set_soft_ccd(world: number, body: number, distance: number): number;
47
+ project_point(world: number): number;
48
+ aabb_query(world: number): number;
49
+ explosion(world: number): number;
50
+ contacts_of(world: number, shape: number): number;
51
+ world_set_hooks(world: number, on: number): number;
52
+ world_snapshot(world: number): number;
53
+ world_restore(world: number, bytes: number): number;
54
+ debug_lines(world: number, what: number, skipping: number): number;
55
+ shape_create(world: number, body: number, kind: number): number;
56
+ shape_remove(world: number, shape: number): number;
57
+ shape_set(world: number, shape: number): number;
58
+ shape_set_core(world: number, shape: number, kind: number): number;
59
+ shape_move(world: number, shape: number): number;
60
+ shapes_join_seams(world: number, count: number): number;
61
+ shape_set_mass(world: number, shape: number, mode: number): number;
62
+ shape_set_rolling_resistance(world: number, shape: number, value: number): number;
63
+ shape_rolling_resistance(world: number, shape: number): number;
64
+ shape_mass(world: number, shape: number): number;
65
+ shape_read(world: number, shape: number): number;
66
+ joint_create(world: number, a: number, b: number, collide: number): number;
67
+ joint_remove(world: number, joint: number): number;
68
+ joint_set_limits(world: number, joint: number, has: number, lo: number, hi: number): number;
69
+ joint_set_motor(world: number, joint: number, has: number): number;
70
+ joint_force(world: number, joint: number): number;
71
+ joint_set_anchor_a(world: number, joint: number, x: number, y: number): number;
72
+ events_read(world: number): number;
73
+ force_events_read(world: number): number;
74
+ ray_cast(world: number): number;
75
+ point_query(world: number): number;
76
+ shape_overlap(world: number, kind: number): number;
77
+ shape_cast(world: number, kind: number): number;
78
+ }
79
+ /** The two questions the kernel puts to the page while it steps (see `Physics2D.hooks`). @internal */
80
+ export interface KernelHooks {
81
+ filter(a: number, b: number): boolean;
82
+ /** Answers through the buffer: friction, restitution, a one-way direction; returns the bits of what it set. */
83
+ contact(a: number, b: number, nx: number, ny: number, points: number): number;
84
+ }
85
+ /** One word of the buffer as a float or as an integer. */
86
+ export interface Words {
87
+ readonly f: Float32Array;
88
+ readonly u: Uint32Array;
89
+ }
90
+ /** The kernel's exports with their errors thrown. One per app; worlds are handles into it. */
91
+ export declare class Kernel {
92
+ private readonly x;
93
+ private at;
94
+ /** What the kernel asks of the page while it steps: whether a pair may meet, and how to change a contact. @internal */
95
+ hooks: KernelHooks | null;
96
+ /** @internal */
97
+ constructor(x: Exports);
98
+ /** The buffer's words, at least `words` long. Read it again after any call: memory may have grown. */
99
+ io(words: number): Words;
100
+ /** @internal The buffer as it was last given out, for a hook that runs inside a call (no call into the kernel). */
101
+ current(words: number): Words;
102
+ /** The checked result of a call: its non-negative value, or the kernel's error thrown. */
103
+ ok(result: number): number;
104
+ get exports(): Exports;
105
+ }
106
+ /** Compiles the kernel's Wasm from `source` and returns the ready kernel. `signal` cancels the download and the wait. */
107
+ export declare function startKernel(source: KernelWasmSource, signal: AbortSignal): Promise<Kernel>;
@@ -0,0 +1,17 @@
1
+ import type { Vec2D } from './shapes.js';
2
+ /** Which clean-up steps to run. */
3
+ export interface MeshClean2D {
4
+ /** Joins vertices at the same position into one, so triangles that met at a seam share it. */
5
+ mergeDuplicateVertices?: boolean;
6
+ /** Drops triangles with a repeated vertex or no area (kept, they collide along their line, as in Rapier). */
7
+ deleteDegenerateTriangles?: boolean;
8
+ /** Drops a triangle whose three vertices another triangle already has, whatever its winding. */
9
+ deleteDuplicateTriangles?: boolean;
10
+ /** Drops triangles that would make an edge belong to more than two triangles, later ones first. */
11
+ deleteBadTopologyTriangles?: boolean;
12
+ }
13
+ /** The triangles (three indices each) after the steps asked for, as indices into the returned vertices. */
14
+ export declare function cleanTrimesh2D(vertices: readonly Vec2D[], indices: ArrayLike<number>, options: MeshClean2D): {
15
+ vertices: Vec2D[];
16
+ triangles: number[];
17
+ };
@@ -0,0 +1,55 @@
1
+ import type { SpriteLike } from './body.js';
2
+ import type { ColliderOptions2D, ColliderSettings2D, Vec2D } from './shapes.js';
3
+ /** Straight-alpha RGBA8 pixels, row by row from the top: `ImageData` fits. */
4
+ export interface AlphaImage {
5
+ readonly width: number;
6
+ readonly height: number;
7
+ readonly data: ArrayLike<number>;
8
+ }
9
+ /** Options of {@link traceOutlines}. */
10
+ export interface TraceOptions {
11
+ /** Alpha from 1 to 255 that counts as solid (default 128). The edge is placed between pixels by their alpha. */
12
+ threshold?: number;
13
+ /** Farthest the simplified outline may stray from the traced one, in pixels (default 1). 0 keeps every point on a line out. */
14
+ tolerance?: number;
15
+ /** Outlines and holes enclosing less than this many square pixels are left out: specks of noise (default 4). */
16
+ minArea?: number;
17
+ /** The part of the image to trace, [x, y, width, height] in pixels: one frame of an atlas. Default the whole image. */
18
+ rect?: readonly [number, number, number, number];
19
+ }
20
+ /** One solid island of the image. Points run in pixels from the top left of the traced area. */
21
+ export interface Outline {
22
+ /** The island's edge. */
23
+ outer: Vec2D[];
24
+ /** Its holes, each a closed loop. */
25
+ holes: Vec2D[][];
26
+ }
27
+ /** Options of {@link outlineColliders}: the trace, where it sits on the body, and the settings of every collider. */
28
+ export interface OutlineColliderOptions extends TraceOptions, Omit<ColliderSettings2D, 'offset' | 'rotation'> {
29
+ /**
30
+ * The sprite the colliders are for: its `rect` is traced unless `rect` is given, and its pivot and scale place them
31
+ * on the body, as `physics.addBody(sprite)` places a fitted box. Without it, the body sits at the top left of the
32
+ * traced area at scale 1.
33
+ */
34
+ sprite?: SpriteLike;
35
+ /**
36
+ * False (default) gives filled convex `polygon` colliders, for bodies that move. True gives one closed `polyline` per
37
+ * outline and hole: edges with no area, for fixed terrain, with fewer colliders.
38
+ */
39
+ edges?: boolean;
40
+ }
41
+ /**
42
+ * The outlines of an image's solid parts, in pixels from the top left of the traced area: the alpha at each pixel centre
43
+ * is contoured at `threshold`, so a hard edge lands on the pixel boundary and a soft one between pixels by its alpha.
44
+ * @example const [island] = traceOutlines(imageData, {threshold: 64, tolerance: 0.5});
45
+ * @throws TypeError or RangeError for an image that is not RGBA8 or options out of range.
46
+ */
47
+ export declare function traceOutlines(image: AlphaImage, options?: TraceOptions): Outline[];
48
+ /**
49
+ * Colliders that follow a sprite's alpha, for `physics.addBody(sprite, {colliders})`. By default filled convex polygons
50
+ * that keep a sprite's holes and hollows, so a ball can rest in a cup; `edges: true` gives closed polylines for terrain.
51
+ * An image with nothing solid gives an empty array.
52
+ * @example physics.addBody(sprite, {colliders: outlineColliders(imageData, {sprite, friction: 0.4})});
53
+ * @throws TypeError or RangeError for an image that is not RGBA8 or options out of range.
54
+ */
55
+ export declare function outlineColliders(image: AlphaImage, options?: OutlineColliderOptions): ColliderOptions2D[];