@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.
package/dist/index.js ADDED
@@ -0,0 +1,2640 @@
1
+ // @margo/core-built 1.0.0
2
+ import {coreRequirement as __margoCoreRequirement,assertCore as __margoAssertCore} from '@margoengine/core/extension';
3
+
4
+ import { MargoError as e } from "@margoengine/math/errors";
5
+ //#region ../shared/errors.js
6
+ var t = (e, t) => Object.assign(Error(t), {
7
+ name: "MargoError",
8
+ code: e
9
+ });
10
+ function n(e) {
11
+ return !/^(Compile|Eval|Runtime)Error$/.test(e?.name) || !/wasm-unsafe-eval|content security policy|\bCSP\b|disallowed by embedder/i.test(e.message) ? e : Object.assign(t("failed", "Wasm compilation blocked by CSP; add 'wasm-unsafe-eval' to script-src; see https://margoengine.com/llms/docs/csp.md"), { cause: e });
12
+ }
13
+ //#endregion
14
+ //#region ../shared/shared-load.js
15
+ var r = () => {}, i = class {
16
+ value = null;
17
+ #e;
18
+ #t = null;
19
+ constructor(e) {
20
+ this.#e = e;
21
+ }
22
+ #n(e) {
23
+ let t = new AbortController(), i = this.#e(e, t.signal).then((e) => this.value = e, (e) => {
24
+ throw n(e);
25
+ }).finally(() => {
26
+ this.#t?.promise === i && (this.#t = null);
27
+ });
28
+ return i.catch(r), {
29
+ promise: i,
30
+ controller: t,
31
+ waiting: 0
32
+ };
33
+ }
34
+ async load(e, t) {
35
+ if (t?.throwIfAborted(), this.value !== null) return this.value;
36
+ let n = this.#t ??= this.#n(e);
37
+ if (!t) return n.waiting = Infinity, n.promise;
38
+ n.waiting++;
39
+ let r, i = new Promise((e, i) => {
40
+ r = () => {
41
+ --n.waiting === 0 && n.controller.abort(t.reason), i(t.reason);
42
+ }, t.addEventListener("abort", r, { once: !0 });
43
+ });
44
+ try {
45
+ return await Promise.race([n.promise, i]);
46
+ } finally {
47
+ t.aborted || n.waiting--, t.removeEventListener("abort", r);
48
+ }
49
+ }
50
+ };
51
+ //#endregion
52
+ //#region src/mesh-clean.ts
53
+ function a(e, t, n) {
54
+ let r = e.map((e) => [e[0], e[1]]), i = Array.from(t);
55
+ if (n.mergeDuplicateVertices) {
56
+ let e = /* @__PURE__ */ new Map(), t = [], n = [];
57
+ for (let [i, a] of r) {
58
+ let r = `${i + 0},${a + 0}`, o = Number.isNaN(i) || Number.isNaN(a) ? void 0 : e.get(r);
59
+ o === void 0 && (o = n.length, e.set(r, o), n.push([i + 0, a + 0])), t.push(o);
60
+ }
61
+ r = n, i = i.map((e) => t[e]);
62
+ }
63
+ let a = (e, t, n) => {
64
+ let [i, a, o] = [
65
+ r[e],
66
+ r[t],
67
+ r[n]
68
+ ];
69
+ return (a[0] - i[0]) * (o[1] - i[1]) - (o[0] - i[0]) * (a[1] - i[1]);
70
+ }, o = (e) => {
71
+ let t = [];
72
+ for (let n = 0; n < i.length; n += 3) {
73
+ let [r, a, o] = [
74
+ i[n],
75
+ i[n + 1],
76
+ i[n + 2]
77
+ ];
78
+ e(r, a, o) && t.push(r, a, o);
79
+ }
80
+ i = t;
81
+ };
82
+ if (n.deleteDegenerateTriangles && o((e, t, n) => e !== t && t !== n && e !== n && a(e, t, n) !== 0), n.deleteDuplicateTriangles) {
83
+ let e = /* @__PURE__ */ new Set();
84
+ o((t, n, r) => {
85
+ let i = [
86
+ t,
87
+ n,
88
+ r
89
+ ].sort((e, t) => e - t).join(",");
90
+ return !e.has(i) && (e.add(i), !0);
91
+ });
92
+ }
93
+ if (n.deleteBadTopologyTriangles) {
94
+ let e = /* @__PURE__ */ new Map(), t = (e, t) => e < t ? `${e},${t}` : `${t},${e}`;
95
+ o((n, r, i) => {
96
+ let a = [
97
+ t(n, r),
98
+ t(r, i),
99
+ t(i, n)
100
+ ];
101
+ if (a.some((t) => (e.get(t) ?? 0) >= 2)) return !1;
102
+ for (let t of a) e.set(t, (e.get(t) ?? 0) + 1);
103
+ return !0;
104
+ });
105
+ }
106
+ return {
107
+ vertices: r,
108
+ triangles: i
109
+ };
110
+ }
111
+ //#endregion
112
+ //#region src/tilemap.ts
113
+ var o = 2147483648, s = 1073741824, c = 536870912, l = 268435455;
114
+ function u(e, t, n) {
115
+ let r = (r, i) => r >= 0 && i >= 0 && r < t && i < n && e[i * t + r] === 1, i = /* @__PURE__ */ new Map(), a = t + 1, o = (e, t, n, r) => {
116
+ let o = t * a + e, s = i.get(o);
117
+ s ? s.push(r * a + n) : i.set(o, [r * a + n]);
118
+ };
119
+ for (let e = 0; e < n; e++) for (let n = 0; n < t; n++) r(n, e) && (r(n, e - 1) || o(n, e, n + 1, e), r(n + 1, e) || o(n + 1, e, n + 1, e + 1), r(n, e + 1) || o(n + 1, e + 1, n, e + 1), r(n - 1, e) || o(n, e + 1, n, e));
120
+ let s = [], c = (e) => [e % a, Math.floor(e / a)];
121
+ for (let [e] of i) for (; i.get(e)?.length;) {
122
+ let t = [e], n = e;
123
+ for (;;) {
124
+ let r = i.get(n);
125
+ if (!r?.length || (n = r.pop(), t.push(n), n === e && !i.get(n)?.length)) break;
126
+ }
127
+ let r = t.slice(0, -1).map(c), a = [];
128
+ for (let e = 0; e < r.length; e++) {
129
+ let t = r[(e + r.length - 1) % r.length], n = r[e], i = r[(e + 1) % r.length];
130
+ (n[0] - t[0]) * (i[1] - n[1]) !== (n[1] - t[1]) * (i[0] - n[0]) && a.push(n);
131
+ }
132
+ s.push(a);
133
+ }
134
+ return s;
135
+ }
136
+ function d(e) {
137
+ if (e.kind === "point") return null;
138
+ let t = (e.rotation ?? 0) * Math.PI / 180, n = Math.cos(t), r = Math.sin(t), i = (t, i) => [e.x + t * n - i * r, e.y + t * r + i * n];
139
+ if (e.kind === "rect") {
140
+ let { width: t, height: n } = e;
141
+ return {
142
+ points: [
143
+ i(0, 0),
144
+ i(t, 0),
145
+ i(t, n),
146
+ i(0, n)
147
+ ],
148
+ box: !0
149
+ };
150
+ }
151
+ if (e.kind === "ellipse") {
152
+ let { width: t, height: n } = e;
153
+ if (t === n) return {
154
+ points: [],
155
+ box: !1,
156
+ circle: {
157
+ c: i(t / 2, n / 2),
158
+ r: t / 2
159
+ }
160
+ };
161
+ let r = [];
162
+ for (let e = 0; e < 16; e++) {
163
+ let a = e / 16 * Math.PI * 2;
164
+ r.push(i(t / 2 + t / 2 * Math.cos(a), n / 2 + n / 2 * Math.sin(a)));
165
+ }
166
+ return {
167
+ points: r,
168
+ box: !1
169
+ };
170
+ }
171
+ return {
172
+ points: e.points.map((e) => i(e[0], e[1])),
173
+ box: !1
174
+ };
175
+ }
176
+ function f(e, t = {}) {
177
+ let { tileWidth: n, tileHeight: r } = e;
178
+ if (!(n > 0 && r > 0)) throw RangeError(`map tile size must be above 0, got ${n} x ${r}; fix tileWidth and tileHeight.`);
179
+ let [i, a] = t.position ?? [0, 0], f = t.layers, p = (e) => f ? typeof f == "function" ? f(e) : f.includes(e.name) : !0, m = {
180
+ friction: t.friction,
181
+ restitution: t.restitution,
182
+ collisionGroups: t.collisionGroups
183
+ }, h = [], g = /* @__PURE__ */ new Map(), _ = /* @__PURE__ */ new Map(), v = (t) => {
184
+ let n = _.get(t);
185
+ if (n) return n;
186
+ let r;
187
+ for (let n of e.tilesets) n.firstGid <= t && t < n.firstGid + n.tileCount && (!r || n.firstGid > r.firstGid) && (r = n);
188
+ if (!r) return null;
189
+ let i = r.tiles?.find((e) => e.id === t - r.firstGid), a = i?.collision?.length ? i.collision : i?.properties?.solid === !0 ? [{
190
+ kind: "rect",
191
+ x: 0,
192
+ y: 0,
193
+ width: r.tileWidth,
194
+ height: r.tileHeight
195
+ }] : null;
196
+ return _.set(t, n = {
197
+ set: r,
198
+ shapes: a
199
+ }), n;
200
+ };
201
+ for (let t of e.layers) {
202
+ if (t.type !== "tile" || !p(t)) continue;
203
+ if (t.data.length !== t.width * t.height) throw RangeError(`layer "${t.name}" has ${t.data.length} values for ${t.width} x ${t.height} tiles; resize it to width * height.`);
204
+ let [u, f] = t.offset ?? [0, 0], _ = `${u},${f}`, y = g.get(_);
205
+ if (!y) {
206
+ let t = Math.max(0, ...e.layers.map((e) => e.type === "tile" ? e.width : 0)), n = Math.max(0, ...e.layers.map((e) => e.type === "tile" ? e.height : 0));
207
+ g.set(_, y = {
208
+ solid: new Uint8Array(t * n),
209
+ width: t,
210
+ height: n,
211
+ ox: u,
212
+ oy: f
213
+ });
214
+ }
215
+ for (let e = 0; e < t.height; e++) for (let p = 0; p < t.width; p++) {
216
+ let g = t.data[e * t.width + p], _ = g & l;
217
+ if (!_) continue;
218
+ let b = v(_);
219
+ if (!b?.shapes) continue;
220
+ let { set: x } = b, S = x.tileWidth, C = x.tileHeight, w = i + u + p * n + (x.tileOffset?.[0] ?? 0), T = a + f + (e + 1) * r - C + (x.tileOffset?.[1] ?? 0), E = (e) => {
221
+ let [t, n] = e;
222
+ return g & c && ([t, n] = [n * S / C, t * C / S]), g & o && (t = S - t), g & s && (n = C - n), [t, n];
223
+ };
224
+ for (let t of b.shapes) {
225
+ let o = d(t);
226
+ if (!o) continue;
227
+ if (o.circle) {
228
+ let [e, t] = E(o.circle.c);
229
+ h.push({
230
+ shape: "circle",
231
+ radius: o.circle.r,
232
+ offset: [w + e, T + t],
233
+ ...m
234
+ });
235
+ continue;
236
+ }
237
+ let s = o.points.map(E);
238
+ if (o.box) {
239
+ let t = s.map((e) => e[0]), o = s.map((e) => e[1]), c = Math.min(...t), l = Math.max(...t), d = Math.min(...o), g = Math.max(...o);
240
+ if (s.every((e) => (e[0] === c || e[0] === l) && (e[1] === d || e[1] === g))) {
241
+ c === 0 && d === 0 && l === n && g === r && S === n && C === r && T === a + f + e * r && w === i + u + p * n ? y.solid[e * y.width + p] = 1 : h.push({
242
+ shape: "box",
243
+ width: l - c,
244
+ height: g - d,
245
+ offset: [w + (c + l) / 2, T + (d + g) / 2],
246
+ ...m
247
+ });
248
+ continue;
249
+ }
250
+ }
251
+ let c = s.map((e) => [w + e[0], T + e[1]]);
252
+ t.kind === "polyline" ? h.push({
253
+ shape: "polyline",
254
+ points: c,
255
+ ...m
256
+ }) : h.push({
257
+ shape: "polygon",
258
+ points: c,
259
+ ...m
260
+ });
261
+ }
262
+ }
263
+ }
264
+ for (let e of g.values()) for (let t of u(e.solid, e.width, e.height)) {
265
+ let o = t.map((t) => [i + e.ox + t[0] * n, a + e.oy + t[1] * r]);
266
+ o.push(o[0]), h.push({
267
+ shape: "polyline",
268
+ points: o,
269
+ ...m
270
+ });
271
+ }
272
+ return h;
273
+ }
274
+ //#endregion
275
+ //#region src/shapes.ts
276
+ var p = (e) => {
277
+ if (typeof e == "number") {
278
+ if (!Number.isInteger(e) || e < 0 || e > 65535) throw RangeError(`A group mask must be an integer 0..65535, got ${e}; or pass an array of group indices.`);
279
+ return e;
280
+ }
281
+ return e.reduce((e, t) => {
282
+ if (!Number.isInteger(t) || t < 0 || t > 15) throw RangeError(`A group index must be an integer 0..15, got ${t}; there are 16 groups.`);
283
+ return e | 1 << t;
284
+ }, 0);
285
+ };
286
+ function m(e, t = 65535) {
287
+ return (p(e) << 16 | p(t)) >>> 0;
288
+ }
289
+ var h = (e, t, n = !1) => {
290
+ if (!Number.isFinite(e) || n && e <= 0) throw RangeError(`${t} must be a finite number${n ? " above 0" : ""}, got ${e}; fix the value.`);
291
+ return e;
292
+ }, g = (e) => {
293
+ if (e === void 0) return 0;
294
+ if (!Number.isFinite(e) || e < 0) throw RangeError(`borderRadius must be a finite number of 0 or more, got ${e}.`);
295
+ return e;
296
+ }, _ = {
297
+ circle: 0,
298
+ capsule: 1,
299
+ segment: 2,
300
+ rect: 3,
301
+ polygon: 4,
302
+ chain: 5,
303
+ decomposed: 6,
304
+ voxels: 7
305
+ }, v = {
306
+ Average: 0,
307
+ Min: 1,
308
+ Multiply: 2,
309
+ Max: 3,
310
+ ClampedSum: 4,
311
+ GeometricMean: 5
312
+ };
313
+ function y(e, t) {
314
+ if (e === void 0) return 0;
315
+ if (!(Number.isInteger(e) && e >= 0 && e <= 5)) throw RangeError(`A collider's ${t} combine rule is a CoefficientCombineRule2D (Average, Min, Multiply, Max, ClampedSum or GeometricMean; got ${e}); pass one.`);
316
+ return e;
317
+ }
318
+ var b = class {
319
+ constructor(e) {
320
+ let t = /* @__PURE__ */ new ArrayBuffer(e * 4);
321
+ this.u = new Uint32Array(t), this.f = new Float32Array(t);
322
+ }
323
+ };
324
+ function x(e) {
325
+ let t = 0, n = e.length / 2;
326
+ for (let r = 0; r < n; r++) {
327
+ let i = (r + 1) % n;
328
+ t += e[2 * r] * e[2 * i + 1] - e[2 * i] * e[2 * r + 1];
329
+ }
330
+ return Math.abs(t) / 2;
331
+ }
332
+ function S(e, t) {
333
+ let [n, r] = e.offset ?? [0, 0], i = e.rotation ?? 0;
334
+ h(n, "collider offset x"), h(r, "collider offset y"), h(i, "collider rotation");
335
+ let a = Math.cos(i), o = Math.sin(i), s = (e, i) => [(a * e - o * i + n) * t, (o * e + a * i + r) * t], c, l, u = 0, d = !1, f = !0;
336
+ switch (e.shape) {
337
+ case "box": {
338
+ let i = h(e.width, "box width", !0) * t / 2, s = h(e.height, "box height", !0) * t / 2, d = g(e.borderRadius) * t;
339
+ c = _.rect, l = new b(7), l.f.set([
340
+ i,
341
+ s,
342
+ n * t,
343
+ r * t,
344
+ a,
345
+ o,
346
+ d
347
+ ]), u = 4 * i * s + 2 * d * (2 * i + 2 * s) + Math.PI * d * d;
348
+ break;
349
+ }
350
+ case "circle": {
351
+ let i = h(e.radius, "circle radius", !0) * t;
352
+ c = _.circle, l = new b(3), l.f.set([
353
+ n * t,
354
+ r * t,
355
+ i
356
+ ]), u = Math.PI * i * i;
357
+ break;
358
+ }
359
+ case "capsule": {
360
+ let n = h(e.radius, "capsule radius", !0), r = Math.max(0, h(e.height, "capsule height", !0) / 2 - n), i = s(0, -r), a = s(0, r);
361
+ c = _.capsule, l = new b(5), l.f.set([
362
+ i[0],
363
+ i[1],
364
+ a[0],
365
+ a[1],
366
+ n * t
367
+ ]), u = Math.PI * n * n * t * t + 4 * r * n * t * t;
368
+ break;
369
+ }
370
+ case "segment": {
371
+ let t = s(h(e.from[0], "segment from"), h(e.from[1], "segment from")), n = s(h(e.to[0], "segment to"), h(e.to[1], "segment to"));
372
+ c = _.segment, l = new b(4), l.f.set([
373
+ t[0],
374
+ t[1],
375
+ n[0],
376
+ n[1]
377
+ ]);
378
+ break;
379
+ }
380
+ case "polyline": {
381
+ let t = C(e.points, 1, 2, "polyline"), n = t.length / 2, r = n >= 4 && t[0] === t[2 * n - 2] && t[1] === t[2 * n - 1], i = r ? n - 1 : n;
382
+ c = _.chain, d = e.oneSided === !0, l = new b(2 + 2 * i), l.u[0] = +!!r, l.u[1] = i;
383
+ for (let e = 0; e < i; e++) l.f.set(s(t[2 * e], t[2 * e + 1]), 2 + 2 * e);
384
+ break;
385
+ }
386
+ case "polygon": {
387
+ let n = C(e.points, 1, 3, "polygon"), r = n.length / 2, i = new Float32Array(2 * r);
388
+ for (let e = 0; e < r; e++) i.set(s(n[2 * e], n[2 * e + 1]), 2 * e);
389
+ let a = g(e.borderRadius) * t, o = 0;
390
+ for (let e = 0; e < r; e++) o += Math.hypot(i[2 * e] - i[2 * ((e + 1) % r)], i[2 * e + 1] - i[2 * ((e + 1) % r) + 1]);
391
+ if (u = x(i) + o * a + Math.PI * a * a, !(x(n) > 1e-9)) throw RangeError("polygon points are degenerate (no area); give at least three points not on a line.");
392
+ f = r <= 8 && w(e.points), c = f ? _.polygon : _.decomposed, l = new b(2 + 2 * r), l.f[0] = a, l.u[1] = r, l.f.set(i, 2);
393
+ break;
394
+ }
395
+ default: throw TypeError(`Unknown collider shape "${e.shape}"; use box, circle, capsule, segment, triangle, polygon, polyline, compound, trimesh, heightfield, halfspace or voxels.`);
396
+ }
397
+ let p = new b(8), m = e.sensor === !0, v = (e.events === !1 ? 0 : 1) | (e.contactForceThreshold === void 0 ? 0 : 2), S = e.density ?? 1;
398
+ e.mass !== void 0 && (S = u > 0 ? h(e.mass, "collider mass") / u : 0), p.f[0] = h(S, "collider density"), p.f[1] = h(e.friction ?? .5, "collider friction"), p.f[2] = h(e.restitution ?? 0, "collider restitution"), p.u[3] = e.collisionGroups ?? 4294967295, p.u[4] = e.solverGroups ?? 4294967295;
399
+ let T = e.activeCollisionTypes ?? (m ? 63 : 7);
400
+ p.u[5] = v | (T & 255) << 8 | (m ? 65536 : 0) | (d ? 1 << 17 : 0) | (e.hooks?.filterPair ? 1 << 18 : 0) | (e.hooks?.modifyContact ? 1 << 19 : 0) | (e.hooks?.filterIntersection ? 1 << 20 : 0) | y(e.frictionCombineRule, "friction") << 21 | y(e.restitutionCombineRule, "restitution") << 24, p.f[6] = e.contactForceThreshold ?? 0;
401
+ let E = e.contactSkin ?? 0;
402
+ if (!(E >= 0 && Number.isFinite(E))) throw RangeError(`A collider's contact skin is a finite distance of 0 or more (got ${E}); pass one.`);
403
+ return p.f[7] = E * t, {
404
+ kind: c,
405
+ settings: p.u,
406
+ geometry: l.u,
407
+ area: u,
408
+ convex: f
409
+ };
410
+ }
411
+ function C(e, t, n, r) {
412
+ if (!Array.isArray(e) || e.length < n) throw TypeError(`${r} needs at least ${n} points as [x, y] pairs; pass more points.`);
413
+ let i = new Float32Array(e.length * 2);
414
+ return e.forEach((e, n) => {
415
+ i[2 * n] = h(e[0], `${r} x`) * t, i[2 * n + 1] = h(e[1], `${r} y`) * t;
416
+ }), i;
417
+ }
418
+ function w(e) {
419
+ let t = 0, n = e.length;
420
+ for (let r = 0; r < n; r++) {
421
+ let i = e[r], a = e[(r + 1) % n], o = e[(r + 2) % n], s = (a[0] - i[0]) * (o[1] - a[1]) - (a[1] - i[1]) * (o[0] - a[0]);
422
+ if (s !== 0) {
423
+ if (t !== 0 && Math.sign(s) !== t) return !1;
424
+ t = Math.sign(s);
425
+ }
426
+ }
427
+ return !0;
428
+ }
429
+ var T = 1e5;
430
+ function E(e, t) {
431
+ let n = D(e, t);
432
+ if (e.mass !== void 0 && n.length > 1) {
433
+ let t = n.reduce((e, t) => e + t.area, 0);
434
+ for (let r of n) new Float32Array(r.settings.buffer)[0] = t > 0 ? e.mass / t : 0;
435
+ }
436
+ return n;
437
+ }
438
+ function D(e, t) {
439
+ let [n, r] = e.offset ?? [0, 0], i = e.rotation ?? 0, o = (t, a = [n, r], o = i) => ({
440
+ ...e,
441
+ ...t,
442
+ offset: a,
443
+ rotation: o
444
+ });
445
+ switch (e.shape) {
446
+ case "triangle": return [S(o({
447
+ shape: "polygon",
448
+ points: [
449
+ e.a,
450
+ e.b,
451
+ e.c
452
+ ],
453
+ borderRadius: e.borderRadius
454
+ }), t)];
455
+ case "compound": {
456
+ if (!Array.isArray(e.shapes) || e.shapes.length === 0) throw TypeError("A compound shape needs a non-empty shapes list; pass at least one part.");
457
+ let a = Math.cos(i), s = Math.sin(i), c = [];
458
+ for (let l of e.shapes) {
459
+ let [e, u] = l.offset ?? [0, 0];
460
+ c.push(...D(o(l, [n + a * e - s * u, r + s * e + a * u], i + (l.rotation ?? 0)), t));
461
+ }
462
+ return c;
463
+ }
464
+ case "trimesh": {
465
+ let { vertices: n, indices: r } = e;
466
+ if (!Array.isArray(n) || !r || r.length === 0 || r.length % 3 != 0) throw TypeError("A trimesh needs vertices and an index list with three indices to a triangle.");
467
+ for (let e = 0; e < r.length; e++) {
468
+ let t = r[e];
469
+ if (!Number.isInteger(t) || t < 0 || t >= n.length) throw RangeError(`trimesh index ${t} is outside its ${n.length} vertices; fix the indices.`);
470
+ }
471
+ let { vertices: i, triangles: s } = a(n, r, e), c = [];
472
+ for (let n = 0; n < s.length; n += 3) {
473
+ let r = [
474
+ i[s[n]],
475
+ i[s[n + 1]],
476
+ i[s[n + 2]]
477
+ ];
478
+ if (Math.abs((r[1][0] - r[0][0]) * (r[2][1] - r[0][1]) - (r[2][0] - r[0][0]) * (r[1][1] - r[0][1])) > 1e-9) {
479
+ let n = S(o({
480
+ shape: "polygon",
481
+ points: r
482
+ }), t);
483
+ e.fixInternalEdges && (n.seam = !0), c.push(n);
484
+ } else if (!e.deleteDegenerateTriangles) {
485
+ let [e, n, i] = [
486
+ r[0],
487
+ r[1],
488
+ -1
489
+ ];
490
+ for (let [t, a] of [
491
+ [r[0], r[1]],
492
+ [r[1], r[2]],
493
+ [r[2], r[0]]
494
+ ]) {
495
+ let r = Math.hypot(a[0] - t[0], a[1] - t[1]);
496
+ r > i && ([e, n, i] = [
497
+ t,
498
+ a,
499
+ r
500
+ ]);
501
+ }
502
+ i > 0 && c.push(S(o({
503
+ shape: "segment",
504
+ from: e,
505
+ to: n
506
+ }), t));
507
+ }
508
+ }
509
+ if (!c.length) throw RangeError("trimesh has no triangle left with an area or a length; give it triangles whose corners are not all one point.");
510
+ return c;
511
+ }
512
+ case "heightfield": {
513
+ let { heights: n, width: r } = e, i = n?.length ?? 0;
514
+ if (i < 2) throw TypeError("A heightfield needs at least two heights.");
515
+ h(r, "heightfield width", !0);
516
+ let a = [];
517
+ for (let e = 0; e < i; e++) a.push([-r / 2 + e * r / (i - 1), h(n[e], "heightfield height")]);
518
+ return [S(o({
519
+ shape: "polyline",
520
+ points: a,
521
+ oneSided: !1
522
+ }), t)];
523
+ }
524
+ case "halfspace": {
525
+ let [n, r] = e.normal ?? [0, -1], i = Math.hypot(n, r);
526
+ if (!(i > 0) || !Number.isFinite(i)) throw RangeError("halfspace normal must be a finite vector that is not zero.");
527
+ let a = [n / i, r / i], s = [-a[1], a[0]], c = T, l = (e, t) => [s[0] * e + a[0] * t, s[1] * e + a[1] * t];
528
+ return [S(o({
529
+ shape: "polygon",
530
+ points: [
531
+ l(c, 0),
532
+ l(-1e5, 0),
533
+ l(-1e5, -2 * c),
534
+ l(c, -2 * c)
535
+ ]
536
+ }), t)];
537
+ }
538
+ case "voxels": {
539
+ let { cellWidth: a, cellHeight: s, columns: c, rows: l, solid: d } = e;
540
+ if (h(a, "voxels cellWidth", !0), h(s, "voxels cellHeight", !0), !Number.isInteger(c) || !Number.isInteger(l) || c < 1 || l < 1) throw RangeError(`voxels columns and rows must be positive integers, got ${c} x ${l}.`);
541
+ if (!d || d.length !== c * l) throw RangeError(`voxels has ${d?.length} values for ${c} x ${l} cells; give columns * rows values.`);
542
+ let f = new Uint8Array(c * l);
543
+ for (let e = 0; e < f.length; e++) f[e] = +!!d[e];
544
+ let p = u(f, c, l);
545
+ if (!p.length) throw RangeError("voxels has no solid cell; fill at least one.");
546
+ let m = p.map((e) => {
547
+ let n = e.map((e) => [e[0] * a, e[1] * s]);
548
+ return n.push(n[0]), S(o({
549
+ shape: "polyline",
550
+ points: n
551
+ }), t);
552
+ });
553
+ if (i !== 0) throw RangeError("A voxels collider cannot be rotated; turn the body instead.");
554
+ let g = Math.ceil(c * l / 32), v = new b(15 + g);
555
+ v.u[0] = c, v.u[1] = l, v.f.set([
556
+ a * t,
557
+ s * t,
558
+ n * t,
559
+ r * t
560
+ ], 2), v.u[6] = g;
561
+ for (let e = 0; e < f.length; e++) f[e] && (v.u[7 + (e >> 5)] |= 1 << (e & 31));
562
+ let y = S(o({
563
+ shape: "box",
564
+ width: 1,
565
+ height: 1
566
+ }), t);
567
+ return m.push({
568
+ ...y,
569
+ kind: _.voxels,
570
+ geometry: v.u.subarray(0, 7 + g),
571
+ area: 0,
572
+ convex: !1
573
+ }), m;
574
+ }
575
+ default: return [S(e, t)];
576
+ }
577
+ }
578
+ //#endregion
579
+ //#region src/body.ts
580
+ var O = (e, t) => {
581
+ if (!Number.isFinite(e)) throw RangeError(`${t} must be a finite number, got ${e}; fix the value.`);
582
+ return e;
583
+ }, k = class {
584
+ constructor(e, t, n, r, i, a, o = 0) {
585
+ this.owner = e, this.body = t, this.settings = r, this.offset = i, this.turn = a, this.described = null, this.options = null, this.removed = !1, this.enabled = !0, this.savedGroups = 0, this.explicitMass = null, this.massProps = null, this.shapes = n, this.uid = o;
586
+ }
587
+ get rawSettings() {
588
+ return this.settings;
589
+ }
590
+ reapplyMass() {
591
+ this.massProps ? this.setMassProperties(this.massProps.mass, this.massProps.centre, this.massProps.inertia) : this.explicitMass !== null && this.setMass(this.explicitMass);
592
+ }
593
+ get handle() {
594
+ return this.shapes[0];
595
+ }
596
+ parent() {
597
+ return this.body;
598
+ }
599
+ get isRemoved() {
600
+ return this.removed;
601
+ }
602
+ markRemoved() {
603
+ this.removed = !0;
604
+ }
605
+ push() {
606
+ if (this.removed) throw new e("state", "Collider2D was removed; add a new collider with Body2D.addCollider.");
607
+ let { kernel: t, handle: n } = this.owner;
608
+ for (let e of this.shapes) t.io(8).u.set(this.settings), t.ok(t.exports.shape_set(n, e));
609
+ }
610
+ setShape(t) {
611
+ if (this.removed) throw new e("state", "Collider2D was removed; add a new collider with Body2D.addCollider.");
612
+ let { kernel: n, handle: r, scale: i } = this.owner, a = E({
613
+ ...t,
614
+ offset: this.offset,
615
+ rotation: this.turn
616
+ }, i);
617
+ this.shapes.length === 1 && a.length === 1 && a[0].kind <= 4 ? (n.io(a[0].geometry.length).u.set(a[0].geometry, 0), n.ok(n.exports.shape_set_core(r, this.shapes[0], a[0].kind)), this.described = {
618
+ ...a[0],
619
+ settings: this.settings
620
+ }, this.options &&= {
621
+ ...this.options,
622
+ ...t
623
+ }) : this.owner.replaceColliderShapes(this, t, a);
624
+ }
625
+ isSensor() {
626
+ return !!(this.settings[5] & 65536);
627
+ }
628
+ setSensor(e) {
629
+ e !== this.isSensor() && (this.settings[5] = e ? this.settings[5] | 65536 : this.settings[5] & -65537, this.settings[5] = this.settings[5] & -65281 | (e ? 63 : 7) << 8, this.push());
630
+ }
631
+ setActiveHooks(e) {
632
+ let t = (e.filterPair ? 1 << 18 : 0) | (e.modifyContact ? 1 << 19 : 0) | (e.filterIntersection ? 1 << 20 : 0);
633
+ this.settings[5] = this.settings[5] & -1835009 | t, this.push();
634
+ }
635
+ get activeHooks() {
636
+ let e = this.settings[5];
637
+ return {
638
+ filterPair: !!(e & 1 << 18),
639
+ filterIntersection: !!(e & 1 << 20),
640
+ modifyContact: !!(e & 1 << 19)
641
+ };
642
+ }
643
+ setFriction(e) {
644
+ new Float32Array(this.settings.buffer)[1] = O(e, "friction"), this.push();
645
+ }
646
+ setRollingResistance(e) {
647
+ if (!(e >= 0 && e < Infinity)) throw RangeError(`A collider's rolling resistance is a finite number of 0 or more (got ${e}); pass one.`);
648
+ let { kernel: t, handle: n } = this.owner;
649
+ for (let r of this.shapes) t.ok(t.exports.shape_set_rolling_resistance(n, r, e));
650
+ }
651
+ rollingResistance() {
652
+ let { kernel: e, handle: t } = this.owner;
653
+ return e.ok(e.exports.shape_rolling_resistance(t, this.shapes[0])), e.io(1).f[0];
654
+ }
655
+ setRestitution(e) {
656
+ new Float32Array(this.settings.buffer)[2] = O(e, "restitution"), this.push();
657
+ }
658
+ setFrictionCombineRule(e) {
659
+ this.settings[5] = this.settings[5] & -14680065 | y(e, "friction") << 21, this.push();
660
+ }
661
+ frictionCombineRule() {
662
+ return this.settings[5] >>> 21 & 7;
663
+ }
664
+ setRestitutionCombineRule(e) {
665
+ this.settings[5] = this.settings[5] & -117440513 | y(e, "restitution") << 24, this.push();
666
+ }
667
+ restitutionCombineRule() {
668
+ return this.settings[5] >>> 24 & 7;
669
+ }
670
+ setDensity(e) {
671
+ new Float32Array(this.settings.buffer)[0] = O(e, "density"), this.push(), this.massProps = null, this.explicitMass = null;
672
+ let { kernel: t, handle: n } = this.owner;
673
+ for (let e of this.shapes) t.ok(t.exports.shape_set_mass(n, e, 0));
674
+ }
675
+ setMass(e) {
676
+ if (this.live(), !(e >= 0) || !Number.isFinite(e)) throw RangeError(`A collider's mass is a finite number of kilograms, 0 or more (got ${e}); pass one.`);
677
+ let { kernel: t, handle: n } = this.owner, r = this.shapes.map((e) => (t.ok(t.exports.shape_mass(n, e)), t.io(5).f[4])), i = r.reduce((e, t) => e + t, 0);
678
+ this.massProps = null, this.explicitMass = e, this.shapes.forEach((a, o) => {
679
+ let s = t.io(1);
680
+ s.f[0] = i > 0 ? e * r[o] / i : e / this.shapes.length, t.ok(t.exports.shape_set_mass(n, a, 1));
681
+ });
682
+ }
683
+ setMassProperties(e, t = [0, 0], n = 0) {
684
+ this.live();
685
+ for (let [r, i] of [
686
+ [e, "mass"],
687
+ [n, "inertia"],
688
+ [t?.[0], "centre x"],
689
+ [t?.[1], "centre y"]
690
+ ]) if (!Number.isFinite(r)) throw RangeError(`A collider's ${i} is a finite number (got ${r}); pass one.`);
691
+ if (e < 0 || n < 0) throw RangeError(`A collider's mass and inertia are 0 or more (got ${e}, ${n}); pass them.`);
692
+ let { kernel: r, handle: i, scale: a } = this.owner, o = Math.cos(this.turn), s = Math.sin(this.turn);
693
+ this.explicitMass = null, this.massProps = {
694
+ mass: e,
695
+ centre: [t[0], t[1]],
696
+ inertia: n
697
+ }, this.shapes.forEach((c, l) => {
698
+ let u = r.io(4);
699
+ u.f[0] = l === 0 ? e : 0, u.f[1] = (this.offset[0] + o * t[0] - s * t[1]) * a, u.f[2] = (this.offset[1] + s * t[0] + o * t[1]) * a, u.f[3] = l === 0 ? n * a * a : 0, r.ok(r.exports.shape_set_mass(i, c, 2));
700
+ });
701
+ }
702
+ mass() {
703
+ this.live();
704
+ let { kernel: e, handle: t } = this.owner, n = 0;
705
+ for (let r of this.shapes) e.ok(e.exports.shape_mass(t, r)), n += e.io(5).f[0];
706
+ return n;
707
+ }
708
+ live() {
709
+ if (this.removed) throw new e("state", "Collider2D was removed; add a new collider with Body2D.addCollider.");
710
+ }
711
+ setActiveCollisionTypes(e) {
712
+ if (!Number.isInteger(e) || e < 0 || e > 63) throw RangeError(`activeCollisionTypes must be a whole number from 0 to 63, the six pair kinds as bits (got ${e}); use 7 for the default.`);
713
+ this.settings[5] = this.settings[5] & -65281 | e << 8, this.push();
714
+ }
715
+ activeCollisionTypes() {
716
+ return this.settings[5] >>> 8 & 255;
717
+ }
718
+ setActiveEvents(e) {
719
+ let t = this.settings[5];
720
+ e.collision !== void 0 && (t = e.collision ? t | 1 : t & -2), e.contactForce !== void 0 && (t = e.contactForce ? t | 2 : t & -3), this.settings[5] = t, this.push();
721
+ }
722
+ activeEvents() {
723
+ return {
724
+ collision: !!(this.settings[5] & 1),
725
+ contactForce: !!(this.settings[5] & 2)
726
+ };
727
+ }
728
+ setContactSkin(e) {
729
+ if (!(e >= 0) || !Number.isFinite(e)) throw RangeError(`A collider's contact skin is a finite distance of 0 or more (got ${e}); pass one.`);
730
+ new Float32Array(this.settings.buffer)[7] = e * this.owner.scale, this.push();
731
+ }
732
+ contactSkin() {
733
+ return new Float32Array(this.settings.buffer)[7] / this.owner.scale;
734
+ }
735
+ setContactForceEventThreshold(e) {
736
+ if (!(e >= 0) || !Number.isFinite(e)) throw RangeError(`The contact force threshold must be a finite number of newtons, 0 or more (got ${e}).`);
737
+ new Float32Array(this.settings.buffer)[6] = e, this.settings[5] |= 2, this.push();
738
+ }
739
+ setCollisionGroups(e) {
740
+ this.enabled ? this.settings[3] = e >>> 0 : this.savedGroups = e >>> 0, this.push();
741
+ }
742
+ setSolverGroups(e) {
743
+ this.settings[4] = e >>> 0, this.push();
744
+ }
745
+ setEnabled(e) {
746
+ e !== this.enabled && (this.enabled = e, e ? this.settings[3] = this.savedGroups : (this.savedGroups = this.settings[3], this.settings[3] = 0), this.push());
747
+ }
748
+ get isEnabled() {
749
+ return this.enabled && this.body.enabled;
750
+ }
751
+ translation() {
752
+ let [e, t] = this.body.position, n = this.body.rotation, r = Math.cos(n), i = Math.sin(n);
753
+ return [e + r * this.offset[0] - i * this.offset[1], t + i * this.offset[0] + r * this.offset[1]];
754
+ }
755
+ rotation() {
756
+ return this.body.rotation + this.turn;
757
+ }
758
+ translationWrtParent() {
759
+ return [this.offset[0], this.offset[1]];
760
+ }
761
+ rotationWrtParent() {
762
+ return this.turn;
763
+ }
764
+ setTranslationWrtParent(e) {
765
+ this.place(e, this.turn);
766
+ }
767
+ setRotationWrtParent(e) {
768
+ this.place(this.offset, e);
769
+ }
770
+ place(t, n) {
771
+ if (this.removed) throw new e("state", "Collider2D was removed; add a new collider with Body2D.addCollider.");
772
+ if (!(t?.length === 2 && Number.isFinite(t[0]) && Number.isFinite(t[1]) && Number.isFinite(n))) throw RangeError(`A collider's place on its body is a finite [x, y] and angle (got ${String(t)}, ${n}); pass them.`);
773
+ let { kernel: r, handle: i, scale: a } = this.owner, o = n - this.turn, s = Math.cos(o), c = Math.sin(o), [l, u] = this.offset, d = (t[0] - (s * l - c * u)) * a, f = (t[1] - (c * l + s * u)) * a;
774
+ for (let e of this.shapes) {
775
+ let t = r.io(3);
776
+ t.f[0] = d, t.f[1] = f, t.f[2] = o, r.ok(r.exports.shape_move(i, e));
777
+ }
778
+ this.offset = [t[0], t[1]], this.turn = n, this.massProps && this.setMassProperties(this.massProps.mass, this.massProps.centre, this.massProps.inertia), this.options && (this.options = {
779
+ ...this.options,
780
+ offset: this.offset,
781
+ rotation: n
782
+ }, this.described = {
783
+ ...E(this.options, a)[0],
784
+ settings: this.settings
785
+ });
786
+ }
787
+ remove() {
788
+ this.owner.removeCollider(this);
789
+ }
790
+ }, A = class {
791
+ constructor(e, t, n, r) {
792
+ this.owner = e, this.handle = t, this.sprite = n, this.kind = r, this.colliders = [], this.pose = /* @__PURE__ */ new Float64Array(6), this.dirty = !0, this.removed = !1, this.extraMass = 0, this.params = {
793
+ linearDamping: 0,
794
+ angularDamping: 0,
795
+ gravityScale: 1,
796
+ canSleep: !0,
797
+ ccd: !1,
798
+ dominance: 0
799
+ }, this.soft = 0, this.turnLocked = !1, this.lockJoint = -1, this.locked = [!1, !1], this.snapshot(), this.pose.copyWithin(0, 3, 6);
800
+ }
801
+ snapshot() {
802
+ let { kernel: e, handle: t, scale: n } = this.owner;
803
+ e.ok(e.exports.body_read(t, this.handle));
804
+ let r = e.io(4);
805
+ this.store(r.f[0], r.f[1], r.f[2], r.f[3], 1 / n);
806
+ }
807
+ store(e, t, n, r, i) {
808
+ let a = this.pose;
809
+ a.copyWithin(0, 3, 6), a[3] = e * i, a[4] = t * i, a[5] = Math.atan2(r, n);
810
+ }
811
+ get type() {
812
+ return this.kind;
813
+ }
814
+ setType(e) {
815
+ return this.check(), this.owner.retype(this, e), this.kind = e, this;
816
+ }
817
+ setParams(e) {
818
+ let { x: t, h: n, kernel: r } = this.k, i = {
819
+ ...this.params,
820
+ ...e
821
+ }, a = +!!i.canSleep | (i.ccd ? 4 : 0);
822
+ if (!Number.isInteger(i.dominance) || i.dominance < -127 || i.dominance > 127) throw RangeError(`dominance must be an integer from -127 to 127, got ${i.dominance}.`);
823
+ r.ok(t.body_set_params(n, this.handle, O(i.linearDamping, "damping"), O(i.angularDamping, "damping"), O(i.gravityScale, "gravity scale"), a, i.dominance)), this.params = i;
824
+ }
825
+ get linearDamping() {
826
+ return this.params.linearDamping;
827
+ }
828
+ set linearDamping(e) {
829
+ this.setParams({ linearDamping: e });
830
+ }
831
+ get angularDamping() {
832
+ return this.params.angularDamping;
833
+ }
834
+ set angularDamping(e) {
835
+ this.setParams({ angularDamping: e });
836
+ }
837
+ get gravityScale() {
838
+ return this.params.gravityScale;
839
+ }
840
+ set gravityScale(e) {
841
+ this.setParams({ gravityScale: e });
842
+ }
843
+ get canSleep() {
844
+ return this.params.canSleep;
845
+ }
846
+ set canSleep(e) {
847
+ this.setParams({ canSleep: e });
848
+ }
849
+ get ccd() {
850
+ return this.params.ccd;
851
+ }
852
+ set ccd(e) {
853
+ this.setParams({ ccd: e });
854
+ }
855
+ get softCcd() {
856
+ return this.soft;
857
+ }
858
+ set softCcd(e) {
859
+ let { x: t, h: n, kernel: r, scale: i } = this.k;
860
+ r.ok(t.body_set_soft_ccd(n, this.handle, O(e, "softCcd") * i)), this.soft = e;
861
+ }
862
+ get dominance() {
863
+ return this.params.dominance;
864
+ }
865
+ set dominance(e) {
866
+ this.setParams({ dominance: e });
867
+ }
868
+ check() {
869
+ if (this.removed) throw new e("state", "Body2D was removed; add a new body with Physics2D.addBody.");
870
+ }
871
+ get k() {
872
+ this.check();
873
+ let { kernel: e, handle: t, scale: n } = this.owner;
874
+ return {
875
+ x: e.exports,
876
+ h: t,
877
+ kernel: e,
878
+ scale: n
879
+ };
880
+ }
881
+ get isRemoved() {
882
+ return this.removed;
883
+ }
884
+ markRemoved() {
885
+ this.removed = !0;
886
+ }
887
+ get position() {
888
+ return this.check(), [this.pose[3], this.pose[4]];
889
+ }
890
+ get rotation() {
891
+ return this.check(), this.pose[5];
892
+ }
893
+ teleport(e, t) {
894
+ let { x: n, h: r, kernel: i, scale: a } = this.k, o = t ?? this.pose[5];
895
+ return O(e[0], "position x"), O(e[1], "position y"), O(o, "rotation"), i.ok(n.body_set_transform(r, this.handle, e[0] * a, e[1] * a, Math.cos(o), Math.sin(o))), this.snapshot(), this.pose.copyWithin(0, 3, 6), this.dirty = !0, (this.locked[0] || this.locked[1]) && this.owner.lockTranslation(this, this.locked[0], this.locked[1]), this;
896
+ }
897
+ moveTo(e, t) {
898
+ let { x: n, h: r, kernel: i, scale: a } = this.k, o = t ?? this.pose[5];
899
+ return i.ok(n.body_set_next(r, this.handle, e[0] * a, e[1] * a, Math.cos(o), Math.sin(o))), this;
900
+ }
901
+ read() {
902
+ let { x: e, h: t, kernel: n } = this.k;
903
+ return n.ok(e.body_read(t, this.handle)), n.io(16);
904
+ }
905
+ get linearVelocity() {
906
+ let { f: e } = this.read(), t = 1 / this.owner.scale;
907
+ return [e[4] * t, e[5] * t];
908
+ }
909
+ set linearVelocity(e) {
910
+ let { x: t, h: n, kernel: r, scale: i } = this.k, a = this.read().f[6];
911
+ r.ok(t.body_set_velocity(n, this.handle, O(e[0], "velocity x") * i, O(e[1], "velocity y") * i, a));
912
+ }
913
+ get angularVelocity() {
914
+ return this.read().f[6];
915
+ }
916
+ set angularVelocity(e) {
917
+ let { x: t, h: n, kernel: r } = this.k, { f: i } = this.read();
918
+ r.ok(t.body_set_velocity(n, this.handle, i[4], i[5], O(e, "angular velocity")));
919
+ }
920
+ applyImpulse(e) {
921
+ let { x: t, h: n, kernel: r } = this.k;
922
+ return r.ok(t.body_impulse(n, this.handle, O(e[0], "impulse x"), O(e[1], "impulse y"), 0, 0, 0)), this;
923
+ }
924
+ applyImpulseAtPoint(e, t) {
925
+ let { x: n, h: r, kernel: i, scale: a } = this.k;
926
+ return i.ok(n.body_impulse(r, this.handle, O(e[0], "impulse x"), O(e[1], "impulse y"), 1, t[0] * a, t[1] * a)), this;
927
+ }
928
+ applyTorqueImpulse(e) {
929
+ let { x: t, h: n, kernel: r } = this.k;
930
+ return r.ok(t.body_torque_impulse(n, this.handle, O(e, "torque impulse"))), this;
931
+ }
932
+ applyForce(e) {
933
+ let { x: t, h: n, kernel: r } = this.k;
934
+ return r.ok(t.body_add_force(n, this.handle, O(e[0], "force x"), O(e[1], "force y"), 0)), this;
935
+ }
936
+ applyTorque(e) {
937
+ let { x: t, h: n, kernel: r } = this.k;
938
+ return r.ok(t.body_add_force(n, this.handle, 0, 0, O(e, "torque"))), this;
939
+ }
940
+ applyForceAtPoint(e, t) {
941
+ let { x: n, h: r, kernel: i, scale: a } = this.k;
942
+ return O(e[0], "force x"), O(e[1], "force y"), O(t[0], "point x"), O(t[1], "point y"), i.ok(n.body_add_force_at(r, this.handle, e[0], e[1], t[0] * a, t[1] * a)), this;
943
+ }
944
+ resetTorques() {
945
+ let { x: e, h: t, kernel: n } = this.k;
946
+ return n.ok(e.body_reset_torques(t, this.handle)), this;
947
+ }
948
+ resetForces() {
949
+ let { x: e, h: t, kernel: n } = this.k;
950
+ return n.ok(e.body_reset_forces(t, this.handle)), this;
951
+ }
952
+ get mass() {
953
+ return this.read().f[7];
954
+ }
955
+ get inertia() {
956
+ let e = this.owner.scale;
957
+ return this.read().f[15] / (e * e);
958
+ }
959
+ restoreAdditionalMass(e) {
960
+ this.extraMass = e;
961
+ }
962
+ get additionalMass() {
963
+ return this.extraMass;
964
+ }
965
+ set additionalMass(e) {
966
+ let { x: t, h: n, kernel: r } = this.k;
967
+ r.ok(t.body_set_additional_mass(n, this.handle, O(e, "additional mass"))), this.extraMass = e;
968
+ }
969
+ get enabled() {
970
+ return this.read().u[11] !== 0;
971
+ }
972
+ set enabled(e) {
973
+ let { x: t, h: n, kernel: r } = this.k;
974
+ r.ok(t.body_set_enabled(n, this.handle, +!!e));
975
+ }
976
+ set maxAngularSpeed(e) {
977
+ let { x: t, h: n, kernel: r } = this.k;
978
+ O(e, "max angular speed"), r.ok(t.body_set_max_angular_speed(n, this.handle, e));
979
+ }
980
+ get maxAngularSpeed() {
981
+ return this.read().f[12];
982
+ }
983
+ set additionalPgsIterations(e) {
984
+ let { x: t, h: n, kernel: r } = this.k;
985
+ if (!Number.isInteger(e) || e < 0 || e > 4294967295) throw RangeError(`additionalPgsIterations must be a whole number of 0 or more; got ${e}.`);
986
+ r.ok(t.body_set_extra_passes(n, this.handle, e));
987
+ }
988
+ get additionalPgsIterations() {
989
+ return this.read().u[13];
990
+ }
991
+ set additionalSolverIterations(e) {
992
+ let { x: t, h: n, kernel: r } = this.k;
993
+ if (!Number.isInteger(e) || e < 0 || e > 4294967295) throw RangeError(`additionalSolverIterations must be a whole number of 0 or more; got ${e}.`);
994
+ r.ok(t.body_set_extra_substeps(n, this.handle, e));
995
+ }
996
+ get additionalSolverIterations() {
997
+ return this.read().u[14];
998
+ }
999
+ get centerOfMass() {
1000
+ let { f: e } = this.read(), { scale: t } = this.k;
1001
+ return [e[9] / t, e[10] / t];
1002
+ }
1003
+ setAdditionalMassProperties(e, t = [0, 0], n = 0) {
1004
+ let { x: r, h: i, kernel: a, scale: o } = this.k;
1005
+ return O(e, "additional mass"), O(n, "additional inertia"), O(t[0], "additional mass centre x"), O(t[1], "additional mass centre y"), a.ok(r.body_set_additional_mass_properties(i, this.handle, e, t[0] * o, t[1] * o, n * o * o)), this;
1006
+ }
1007
+ get sleeping() {
1008
+ return this.read().u[8] === 0;
1009
+ }
1010
+ wakeUp() {
1011
+ let { x: e, h: t, kernel: n } = this.k;
1012
+ return n.ok(e.body_wake(t, this.handle)), this;
1013
+ }
1014
+ sleep() {
1015
+ let { x: e, h: t, kernel: n } = this.k;
1016
+ return n.ok(e.body_sleep(t, this.handle)), this;
1017
+ }
1018
+ lockTranslation(e = !0, t = e) {
1019
+ if (this.check(), this.type === "fixed") throw TypeError("A fixed body does not move; lock the translation of a dynamic or kinematic body.");
1020
+ return this.owner.lockTranslation(this, e, t), this.locked = [e, t], this;
1021
+ }
1022
+ lockRotation(e = !0) {
1023
+ let { x: t, h: n, kernel: r } = this.k;
1024
+ if (this.type === "fixed") throw TypeError("A fixed body does not turn; lock the rotation of a dynamic or kinematic body.");
1025
+ return r.ok(t.body_set_fixed_rotation(n, this.handle, +!!e)), this.turnLocked = e, this;
1026
+ }
1027
+ get rotationLocked() {
1028
+ return this.turnLocked;
1029
+ }
1030
+ get translationLocked() {
1031
+ return [this.locked[0], this.locked[1]];
1032
+ }
1033
+ addCollider(e) {
1034
+ return this.check(), this.owner.addCollider(this, e);
1035
+ }
1036
+ remove() {
1037
+ this.owner.removeBody(this);
1038
+ }
1039
+ }, j = (e) => {
1040
+ let t = e % (2 * Math.PI);
1041
+ return t > Math.PI ? t - 2 * Math.PI : t < -Math.PI ? t + 2 * Math.PI : t;
1042
+ }, M = class {
1043
+ constructor(e, t, n) {
1044
+ if (this.physics = e, this.root = t, this.joints = [], this.removed = !1, !n.length) throw TypeError("An articulation needs at least one link; pass the bodies hanging from the root.");
1045
+ this.links = n.map((e, t) => {
1046
+ let n = e.parent ?? -1;
1047
+ if (!Number.isInteger(n) || n < -1 || n >= t) throw RangeError(`link ${t}: parent must be -1 (the root) or the index of an earlier link, got ${n}; list parents before children.`);
1048
+ let r = e.joint;
1049
+ if (r.type !== "revolute" && r.type !== "prismatic") throw TypeError(`link ${t}: an articulation joint is revolute or prismatic, got "${r.type}"; use one of those types.`);
1050
+ let i = r.axis ?? [1, 0], a = Math.hypot(i[0], i[1]);
1051
+ if (!(a > 0) || !Number.isFinite(a)) throw RangeError(`link ${t}: the joint axis must be a finite vector that is not zero; try [1, 0].`);
1052
+ let o = [i[0] / a, i[1] / a];
1053
+ return {
1054
+ link: e,
1055
+ parent: n,
1056
+ anchorParent: r.anchorParent ?? [0, 0],
1057
+ anchorChild: r.anchorChild ?? [0, 0],
1058
+ axis: o
1059
+ };
1060
+ });
1061
+ try {
1062
+ this.links.forEach(({ link: n, parent: r, anchorParent: i, anchorChild: a, axis: o }) => {
1063
+ let s = n.joint, c = {
1064
+ type: s.type,
1065
+ anchorA: i,
1066
+ anchorB: a,
1067
+ ...s.type === "prismatic" ? { axis: o } : {},
1068
+ ...s.limits ? { limits: s.limits } : {},
1069
+ ...s.motor ? { motor: s.motor } : {},
1070
+ collide: !1
1071
+ };
1072
+ this.joints.push(e.addJoint(r < 0 ? t : this.links[r].link.body, n.body, c));
1073
+ });
1074
+ } catch (e) {
1075
+ for (let e of this.joints) e.remove();
1076
+ throw e;
1077
+ }
1078
+ }
1079
+ get dof() {
1080
+ return this.links.length;
1081
+ }
1082
+ bodyOf(e) {
1083
+ return e < 0 ? this.root : this.links[e].link.body;
1084
+ }
1085
+ check() {
1086
+ if (this.removed) throw new e("state", "Articulation2D was removed; add a new one with Physics2D.addArticulation.");
1087
+ }
1088
+ positions() {
1089
+ return this.check(), this.links.map(({ link: e, parent: t, anchorParent: n, anchorChild: r, axis: i }) => {
1090
+ let a = this.bodyOf(t), o = e.body;
1091
+ if (e.joint.type === "revolute") return j(o.rotation - a.rotation);
1092
+ let [s, c] = [this.world(a, n), this.world(o, r)], l = N(i, a.rotation);
1093
+ return l[0] * (c[0] - s[0]) + l[1] * (c[1] - s[1]);
1094
+ });
1095
+ }
1096
+ velocities() {
1097
+ return this.check(), this.links.map(({ link: e, parent: t, anchorParent: n, anchorChild: r, axis: i }) => {
1098
+ let a = this.bodyOf(t), o = e.body;
1099
+ if (e.joint.type === "revolute") return o.angularVelocity - a.angularVelocity;
1100
+ let s = this.pointVelocity(a, n), c = this.pointVelocity(o, r), l = N(i, a.rotation);
1101
+ return l[0] * (c[0] - s[0]) + l[1] * (c[1] - s[1]);
1102
+ });
1103
+ }
1104
+ world(e, t) {
1105
+ let n = N(t, e.rotation);
1106
+ return [e.position[0] + n[0], e.position[1] + n[1]];
1107
+ }
1108
+ pointVelocity(e, t) {
1109
+ let n = N(t, e.rotation), r = e.linearVelocity, i = e.angularVelocity;
1110
+ return [r[0] - i * n[1], r[1] + i * n[0]];
1111
+ }
1112
+ forwardKinematics(e = this.positions()) {
1113
+ if (this.check(), e.length !== this.dof) throw RangeError(`q has ${e.length} values for ${this.dof} joints; pass one value per joint.`);
1114
+ let t = [], n = {
1115
+ position: [...this.root.position],
1116
+ rotation: this.root.rotation
1117
+ };
1118
+ return this.links.forEach(({ link: r, parent: i, anchorParent: a, anchorChild: o, axis: s }, c) => {
1119
+ let l = i < 0 ? n : t[i], u = N(a, l.rotation), d = [l.position[0] + u[0], l.position[1] + u[1]];
1120
+ if (r.joint.type === "revolute") {
1121
+ let n = l.rotation + e[c], r = N(o, n);
1122
+ t.push({
1123
+ position: [d[0] - r[0], d[1] - r[1]],
1124
+ rotation: n
1125
+ });
1126
+ } else {
1127
+ let n = N(s, l.rotation), r = N(o, l.rotation);
1128
+ t.push({
1129
+ position: [d[0] + n[0] * e[c] - r[0], d[1] + n[1] * e[c] - r[1]],
1130
+ rotation: l.rotation
1131
+ });
1132
+ }
1133
+ }), t;
1134
+ }
1135
+ pointAt(e, t, n = this.positions()) {
1136
+ this.checkLink(e);
1137
+ let r = this.forwardKinematics(n)[e], i = N(t, r.rotation);
1138
+ return [r.position[0] + i[0], r.position[1] + i[1]];
1139
+ }
1140
+ checkLink(e) {
1141
+ if (!Number.isInteger(e) || e < 0 || e >= this.dof) throw RangeError(`link must be 0 to ${this.dof - 1}, got ${e}; pass an index of this articulation.`);
1142
+ }
1143
+ jacobian(e, t, n = this.positions()) {
1144
+ this.checkLink(e);
1145
+ let r = [], i = [];
1146
+ for (let a = 0; a < this.dof; a++) {
1147
+ let o = this.links[a].link.joint.type === "revolute" ? 1e-5 : 1e-4 * (1 + Math.abs(n[a])), [s, c] = [n.slice(), n.slice()];
1148
+ s[a] -= o, c[a] += o;
1149
+ let [l, u] = [this.pointAt(e, t, s), this.pointAt(e, t, c)];
1150
+ r.push((u[0] - l[0]) / (2 * o)), i.push((u[1] - l[1]) / (2 * o));
1151
+ }
1152
+ return [r, i];
1153
+ }
1154
+ solveIK(e, t, n, r = {}) {
1155
+ this.checkLink(e);
1156
+ let { iterations: i = 64, tolerance: a = .01, damping: o = .5 } = r, s = this.positions(), c = this.links.map(({ link: e }) => e.joint.limits), l = Infinity;
1157
+ for (let r = 0; r < i; r++) {
1158
+ let r = this.pointAt(e, t, s), i = [n[0] - r[0], n[1] - r[1]];
1159
+ if (l = Math.hypot(i[0], i[1]), l <= a) break;
1160
+ let [u, d] = this.jacobian(e, t, s), f = o * o, p = 0, m = o * o;
1161
+ for (let e = 0; e < this.dof; e++) f += u[e] * u[e], p += u[e] * d[e], m += d[e] * d[e];
1162
+ let h = f * m - p * p, g = [(m * i[0] - p * i[1]) / h, (f * i[1] - p * i[0]) / h], _ = u.map((e, t) => e * g[0] + d[t] * g[1]), v = 0;
1163
+ _.forEach((e, t) => {
1164
+ this.links[t].link.joint.type === "revolute" && (v = Math.max(v, Math.abs(e)));
1165
+ });
1166
+ let y = v > .3 ? .3 / v : 1;
1167
+ for (let e = 0; e < this.dof; e++) {
1168
+ s[e] += _[e] * y;
1169
+ let t = c[e];
1170
+ t && (s[e] = Math.max(t[0], Math.min(t[1], s[e])));
1171
+ }
1172
+ }
1173
+ let u = this.pointAt(e, t, s);
1174
+ return l = Math.hypot(n[0] - u[0], n[1] - u[1]), {
1175
+ q: s,
1176
+ reached: l <= a,
1177
+ error: l
1178
+ };
1179
+ }
1180
+ setPositions(e) {
1181
+ this.check();
1182
+ let t = this.forwardKinematics(e);
1183
+ return this.links.forEach(({ link: e }, n) => e.body.teleport(t[n].position, t[n].rotation)), this;
1184
+ }
1185
+ driveTo(e, { stiffness: t = 200, damping: n = 20, maxForce: r } = {}) {
1186
+ if (this.check(), e.length !== this.dof) throw RangeError(`q has ${e.length} values for ${this.dof} joints; pass one value per joint.`);
1187
+ return this.joints.forEach((i, a) => i.setMotor({
1188
+ targetPosition: e[a],
1189
+ stiffness: t,
1190
+ damping: n,
1191
+ ...r === void 0 ? {} : { maxForce: r }
1192
+ })), this;
1193
+ }
1194
+ setMotor(e, t) {
1195
+ return this.check(), this.checkLink(e), this.joints[e].setMotor(t), this;
1196
+ }
1197
+ setLimits(e, t, n) {
1198
+ return this.check(), this.checkLink(e), this.joints[e].setLimits(t, n), this.links[e].link.joint.limits = [t, n], this;
1199
+ }
1200
+ remove() {
1201
+ if (!this.removed) {
1202
+ this.removed = !0;
1203
+ for (let e of this.joints) e.remove();
1204
+ }
1205
+ }
1206
+ };
1207
+ function N(e, t) {
1208
+ let n = Math.cos(t), r = Math.sin(t);
1209
+ return [n * e[0] - r * e[1], r * e[0] + n * e[1]];
1210
+ }
1211
+ //#endregion
1212
+ //#region src/character.ts
1213
+ var P = 1e-5, ee = 8, F = class {
1214
+ constructor(e, t, n, r) {
1215
+ this.physics = e, this.body = t, this.options = n, this.onDispose = r, this.disposed = !1, this.filter = {};
1216
+ let i = n.up ?? [0, -1], a = Math.hypot(i[0], i[1]);
1217
+ if (!(a > 0) || !Number.isFinite(a)) throw RangeError("The up vector must be finite and not zero; try [0, -1].");
1218
+ this.up = [i[0] / a, i[1] / a], this.offset = (n.offset ?? .5) * e.scale, this.climb = Math.cos(n.maxSlopeClimbAngle ?? Math.PI / 4), this.slideAngle = Math.cos(n.minSlopeSlideAngle ?? Math.PI / 6);
1219
+ }
1220
+ cast(e, t, n) {
1221
+ let r = this.body.colliders[0];
1222
+ if (!r?.described) throw TypeError("The character body has no collider; add one with body.addCollider.");
1223
+ let i = this.body.rotation;
1224
+ return this.physics.cast(r.described, e[0], e[1], i, t[0], t[1], n, this.filter);
1225
+ }
1226
+ filterFor(e) {
1227
+ let t = e ?? this.options.filter ?? {}, n = t.exclude;
1228
+ return {
1229
+ ...t,
1230
+ exclude: this.body,
1231
+ excludeSensors: t.excludeSensors ?? !0,
1232
+ predicate: n ? (e, r) => e !== n && (!t.predicate || t.predicate(e, r)) : t.predicate
1233
+ };
1234
+ }
1235
+ move(e, t) {
1236
+ if (this.disposed) throw TypeError("This character controller was disposed; create a new one.");
1237
+ if (!Number.isFinite(e[0]) || !Number.isFinite(e[1])) throw TypeError("delta must be two finite numbers [x, y].");
1238
+ this.filter = this.filterFor(t);
1239
+ let n = this.physics.scale, r = 1 / n, i = [this.body.position[0] * n, this.body.position[1] * n], a = [i[0], i[1]], o = [e[0] * n, e[1] * n], s = o, c = !1, l = 0, u = [], d = this.up, f = (e, t) => e[0] * t[0] + e[1] * t[1];
1240
+ for (let e = 0; e < ee; e++) {
1241
+ let e = Math.hypot(o[0], o[1]);
1242
+ if (e < P) break;
1243
+ let t = [o[0] / e, o[1] / e], r = this.cast(a, t, e + this.offset);
1244
+ if (!r) {
1245
+ a[0] += o[0], a[1] += o[1], o = [0, 0];
1246
+ break;
1247
+ }
1248
+ let i = r.normal, s = Math.max(-f(t, i), .1), p = Math.max(0, Math.min(e, r.distance * n - this.offset / s));
1249
+ a[0] += t[0] * p, a[1] += t[1] * p, l++, u.push({
1250
+ collider: r.collider,
1251
+ body: r.body,
1252
+ normal: [i[0], i[1]],
1253
+ point: [r.point[0], r.point[1]]
1254
+ });
1255
+ let m = e - p, h = [t[0] * m, t[1] * m], g = f(i, d), _ = g >= this.climb - 1e-6;
1256
+ if (_ && (c = !0), this.pushDynamic(r.body, i, h), this.options.slide === !1) {
1257
+ o = [0, 0];
1258
+ break;
1259
+ }
1260
+ if (!_ && this.options.autostep && g > -.5 && (this.options.autostep.includeDynamic !== !1 || r.body.type !== "dynamic")) {
1261
+ let e = this.step(a, h);
1262
+ if (e) {
1263
+ a[0] = e.pos[0], a[1] = e.pos[1], o = e.remaining, c = !0;
1264
+ continue;
1265
+ }
1266
+ }
1267
+ if (_ && g < this.slideAngle - 1e-6) o = [h[0] - i[0] * f(h, i), h[1] - i[1] * f(h, i)];
1268
+ else if (_) {
1269
+ let e = [h[0] - d[0] * f(h, d), h[1] - d[1] * f(h, d)], t = -f(e, i) / Math.max(g, .001);
1270
+ o = [e[0] + d[0] * t, e[1] + d[1] * t], f(h, d) < 0 && Math.abs(f(e, e)) < P * P && (o = [0, 0]);
1271
+ } else {
1272
+ o = [h[0] - i[0] * f(h, i), h[1] - i[1] * f(h, i)];
1273
+ let e = f(o, d);
1274
+ e > 0 && (o = [o[0] - d[0] * e, o[1] - d[1] * e]);
1275
+ }
1276
+ if (f(o, o) < P * P) break;
1277
+ }
1278
+ if (this.options.snapToGround !== void 0 && !c && f(s, d) <= P) {
1279
+ let e = this.options.snapToGround * n, t = this.cast(a, [-d[0], -d[1]], e + this.offset);
1280
+ if (t && f(t.normal, d) >= this.climb - 1e-6) {
1281
+ let e = Math.max(0, t.distance * n - this.offset);
1282
+ a[0] -= d[0] * e, a[1] -= d[1] * e, c = !0;
1283
+ }
1284
+ }
1285
+ let p = [(a[0] - i[0]) * r, (a[1] - i[1]) * r];
1286
+ return this.body.moveTo([this.body.position[0] + p[0], this.body.position[1] + p[1]]), {
1287
+ movement: p,
1288
+ grounded: c,
1289
+ collisions: l,
1290
+ hits: u
1291
+ };
1292
+ }
1293
+ step(e, t) {
1294
+ let n = this.options.autostep;
1295
+ if (!n) return null;
1296
+ let r = this.physics.scale, i = this.up, a = t[0] * i[0] + t[1] * i[1], o = [t[0] - i[0] * a, t[1] - i[1] * a], s = Math.hypot(o[0], o[1]);
1297
+ if (s < P) return null;
1298
+ let c = [o[0] / s, o[1] / s], l = n.maxHeight * r, u = n.minWidth * r, d = this.cast(e, i, l + this.offset), f = d ? Math.max(0, d.distance * r - this.offset) : l;
1299
+ if (f < P) return null;
1300
+ let p = [e[0] + i[0] * f, e[1] + i[1] * f], m = Math.max(s, u), h = this.cast(p, c, m + this.offset), g = h ? Math.max(0, h.distance * r - this.offset) : m;
1301
+ if (g < u - P) return null;
1302
+ let _ = [p[0] + c[0] * g, p[1] + c[1] * g], v = this.cast(_, [-i[0], -i[1]], f + this.offset);
1303
+ if (!v || v.normal[0] * i[0] + v.normal[1] * i[1] < this.climb - 1e-6 || n.includeDynamic === !1 && v.body.type === "dynamic") return null;
1304
+ let y = Math.max(0, v.distance * r - this.offset), b = [_[0] - i[0] * y, _[1] - i[1] * y];
1305
+ if (f - y < P) return null;
1306
+ let x = Math.max(0, s - Math.min(g, s));
1307
+ return {
1308
+ pos: b,
1309
+ remaining: [c[0] * x, c[1] * x]
1310
+ };
1311
+ }
1312
+ pushDynamic(e, t, n) {
1313
+ if (!this.options.pushDynamic || e.type !== "dynamic") return;
1314
+ let r = -(n[0] * t[0] + n[1] * t[1]);
1315
+ if (r <= 0) return;
1316
+ let i = (this.options.mass ?? (this.body.mass || 1)) * r / this.physics.fixedTimestep;
1317
+ e.applyImpulse([-t[0] * i, -t[1] * i]);
1318
+ }
1319
+ dispose() {
1320
+ this.disposed || (this.disposed = !0, this.onDispose(this));
1321
+ }
1322
+ };
1323
+ F.prototype[Symbol.dispose] = F.prototype.dispose;
1324
+ //#endregion
1325
+ //#region src/joint.ts
1326
+ var I = (e, t) => {
1327
+ if (!Number.isFinite(e)) throw RangeError(`${t} must be a finite number, got ${e}; fix the value.`);
1328
+ return e;
1329
+ };
1330
+ function L(e, t, n) {
1331
+ let r = e.io(32);
1332
+ r.u.fill(0, 0, 32);
1333
+ let i = t.anchorA ?? [0, 0], a = t.anchorB ?? [0, 0];
1334
+ r.f.set([
1335
+ I(i[0], "anchorA x") * n,
1336
+ I(i[1], "anchorA y") * n,
1337
+ I(a[0], "anchorB x") * n,
1338
+ I(a[1], "anchorB y") * n
1339
+ ], 1);
1340
+ let o = t.limits, s = t.type === "prismatic" || t.type === "distance" ? n : 1, c = t.type === "wheel" ? n : s;
1341
+ o && (r.u[5] = 1, r.f[6] = I(o[0], "joint limit") * c, r.f[7] = I(o[1], "joint limit") * c);
1342
+ let l = t.motor;
1343
+ switch (l && (R(r.f, r.u, 8, l, s), r.u[25] = +(l.model === "acceleration")), t.type) {
1344
+ case "revolute":
1345
+ r.u[0] = 0;
1346
+ break;
1347
+ case "prismatic":
1348
+ r.u[0] = 1, r.f[14] = I(t.axis[0], "axis x"), r.f[15] = I(t.axis[1], "axis y");
1349
+ break;
1350
+ case "fixed": {
1351
+ let [e, n] = [t.angleA ?? 0, t.angleB ?? 0];
1352
+ r.f.set([
1353
+ Math.cos(e),
1354
+ Math.sin(e),
1355
+ Math.cos(n),
1356
+ Math.sin(n)
1357
+ ], 16);
1358
+ let i = [
1359
+ I(t.linearHertz ?? 0, "linearHertz"),
1360
+ I(t.linearDampingRatio ?? 1, "linearDampingRatio"),
1361
+ I(t.angularHertz ?? 0, "angularHertz"),
1362
+ I(t.angularDampingRatio ?? 1, "angularDampingRatio")
1363
+ ];
1364
+ if (i.some((e) => e < 0)) throw RangeError("A weld has hertz and damping ratios of 0 or more.");
1365
+ r.u[0] = i[0] > 0 || i[2] > 0 ? 11 : 2, r.f.set(i, 20);
1366
+ break;
1367
+ }
1368
+ case "generic": {
1369
+ r.u[0] = 5, r.u[24] = +!!t.lockX | (t.lockY ? 2 : 0) | (t.lockAngle ? 4 : 0);
1370
+ let [e, n] = [I(t.frameA ?? 0, "frameA"), I(t.frameB ?? 0, "frameB")];
1371
+ r.f.set([
1372
+ Math.cos(e),
1373
+ Math.sin(e),
1374
+ Math.cos(n),
1375
+ Math.sin(n)
1376
+ ], 16);
1377
+ break;
1378
+ }
1379
+ case "slot": {
1380
+ r.u[0] = 5, r.u[24] = 2;
1381
+ let e = Math.atan2(I(t.axis[1], "axis y"), I(t.axis[0], "axis x"));
1382
+ r.f.set([
1383
+ Math.cos(e),
1384
+ Math.sin(e),
1385
+ 1,
1386
+ 0
1387
+ ], 16);
1388
+ break;
1389
+ }
1390
+ case "rope":
1391
+ r.u[0] = 3, r.f[20] = I(t.length, "rope length") * n;
1392
+ break;
1393
+ case "spring":
1394
+ r.u[0] = 4, r.f[20] = I(t.restLength, "spring restLength") * n, r.f[21] = I(t.stiffness, "spring stiffness"), r.f[22] = I(t.damping ?? 0, "spring damping");
1395
+ break;
1396
+ case "target": {
1397
+ r.u[0] = 6;
1398
+ let e = I(t.hertz ?? 5, "target hertz"), n = I(t.damping ?? .7, "target damping"), i = t.maxForce ?? Infinity;
1399
+ if (!(e > 0) || n < 0 || !(i > 0)) throw RangeError("A target joint has hertz above 0, damping of 0 or more and maxForce above 0.");
1400
+ r.f.set([
1401
+ e,
1402
+ n,
1403
+ i
1404
+ ], 20);
1405
+ break;
1406
+ }
1407
+ case "wheel": {
1408
+ r.u[0] = 8;
1409
+ let e = I(t.hertz ?? 1, "wheel hertz"), n = I(t.damping ?? .7, "wheel damping");
1410
+ if (e < 0 || n < 0) throw RangeError("A wheel joint has hertz and damping of 0 or more.");
1411
+ r.f[14] = I(t.axis[0], "axis x"), r.f[15] = I(t.axis[1], "axis y"), r.f.set([e, n], 20);
1412
+ break;
1413
+ }
1414
+ case "pulley": {
1415
+ r.u[0] = 9;
1416
+ let e = I(t.ratio ?? 1, "pulley ratio"), i = I(t.length ?? NaN, "pulley length");
1417
+ if (!(e > 0) || !(i > 0)) throw RangeError("A pulley joint has a ratio and a length above 0.");
1418
+ r.f.set([
1419
+ I(t.groundA[0], "groundA x") * n,
1420
+ I(t.groundA[1], "groundA y") * n,
1421
+ I(t.groundB[0], "groundB x") * n,
1422
+ I(t.groundB[1], "groundB y") * n
1423
+ ], 14), r.f.set([i * n, e], 20);
1424
+ break;
1425
+ }
1426
+ case "distance": {
1427
+ r.u[0] = 12;
1428
+ let e = I(t.length ?? NaN, "distance length");
1429
+ if (!(e > 0)) throw RangeError(`A distance joint's length is above 0 (world units); got ${t.length}.`);
1430
+ if (r.f[20] = e * n, t.spring) {
1431
+ let e = I(t.spring.hertz, "spring hertz"), n = I(t.spring.damping ?? .7, "spring damping");
1432
+ if (e < 0 || n < 0) throw RangeError("A distance spring has hertz and damping of 0 or more.");
1433
+ r.u[24] = 1, r.f.set([e, n], 21);
1434
+ }
1435
+ break;
1436
+ }
1437
+ case "gear":
1438
+ r.u[0] = 10;
1439
+ break;
1440
+ case "motor":
1441
+ case "friction": {
1442
+ r.u[0] = 7;
1443
+ let e = t.maxForce, i = t.maxTorque, a = t.type === "motor" ? t.correctionFactor ?? .3 : 0;
1444
+ if (!(e >= 0) || !(i >= 0) || !(a >= 0 && a <= 1)) throw RangeError(`A ${t.type} joint has maxForce and maxTorque of 0 or more and a correctionFactor from 0 to 1.`);
1445
+ if (t.type === "motor") {
1446
+ let [e, i] = t.linearOffset ?? [0, 0];
1447
+ r.f.set([
1448
+ I(e, "linearOffset x") * n,
1449
+ I(i, "linearOffset y") * n,
1450
+ 0,
1451
+ 0
1452
+ ], 1);
1453
+ }
1454
+ r.f.set([
1455
+ t.type === "motor" ? I(t.angularOffset ?? 0, "angularOffset") : 0,
1456
+ e,
1457
+ i,
1458
+ a
1459
+ ], 20);
1460
+ break;
1461
+ }
1462
+ default: throw TypeError(`Unknown joint type "${t.type}"; use revolute, prismatic, fixed, generic, slot, rope, spring, distance, target, motor, friction, wheel, pulley or gear.`);
1463
+ }
1464
+ return s;
1465
+ }
1466
+ function R(e, t, n, r, i) {
1467
+ if (r.model !== void 0 && r.model !== "force" && r.model !== "acceleration") throw RangeError(`Motor model must be 'force' or 'acceleration', got ${String(r.model)}; pass one of them.`);
1468
+ t[n] = 1;
1469
+ let a = r.targetVelocity !== void 0, o = r.targetPosition !== void 0;
1470
+ e[n + 1] = o ? I(r.targetPosition, "motor targetPosition") * i : 0, e[n + 2] = a ? I(r.targetVelocity, "motor targetVelocity") * i : 0, e[n + 3] = o ? I(r.stiffness ?? 1, "motor stiffness") : 0, e[n + 4] = o ? I(r.damping ?? 0, "motor damping") : I(r.factor ?? 1, "motor factor"), o && a && r.damping === void 0 && (e[n + 4] = I(r.factor ?? 1, "motor factor")), e[n + 5] = r.maxForce === void 0 ? Infinity : I(r.maxForce, "motor maxForce");
1471
+ }
1472
+ var z = class {
1473
+ constructor(e, t, n, r, i, a, o, s, c = 1, l) {
1474
+ this.kernel = e, this.world = t, this.handle = n, this.bodyA = r, this.bodyB = i, this.type = a, this.unit = o, this.onRemove = s, this.scale = c, this.spec = l, this.removed = !1;
1475
+ }
1476
+ setTarget(t) {
1477
+ if (this.type !== "target") throw TypeError("Only a target joint has a target; add one with {type: \"target\"}.");
1478
+ if (this.removed) throw new e("state", "Joint2D was removed; add a new joint with Physics2D.addJoint.");
1479
+ let [n, r] = V(this.bodyA, I(t[0], "target x"), I(t[1], "target y"));
1480
+ return this.kernel.ok(this.kernel.exports.joint_set_anchor_a(this.world, this.handle, n * this.scale, r * this.scale)), this;
1481
+ }
1482
+ get limited() {
1483
+ if (this.type !== "revolute" && this.type !== "prismatic" && this.type !== "wheel" && this.type !== "distance") throw TypeError("Only revolute, prismatic, wheel and distance joints have limits and motors; use one of those types.");
1484
+ if (this.removed) throw new e("state", "Joint2D was removed; add a new joint with Physics2D.addJoint.");
1485
+ return !0;
1486
+ }
1487
+ setLimits(e, t) {
1488
+ this.limited;
1489
+ let n = this.type === "wheel" ? this.scale : this.unit;
1490
+ return this.kernel.ok(this.kernel.exports.joint_set_limits(this.world, this.handle, 1, I(e, "limit") * n, I(t, "limit") * n)), this;
1491
+ }
1492
+ clearLimits() {
1493
+ return this.limited, this.kernel.ok(this.kernel.exports.joint_set_limits(this.world, this.handle, 0, 0, 0)), this;
1494
+ }
1495
+ setMotor(e) {
1496
+ this.limited;
1497
+ let t = this.kernel.io(8);
1498
+ return R(t.f, t.u, 0, e, this.unit), t.f.copyWithin(0, 1, 6), t.f[5] = +(e.model === "acceleration"), this.kernel.ok(this.kernel.exports.joint_set_motor(this.world, this.handle, 1)), this;
1499
+ }
1500
+ clearMotor() {
1501
+ return this.limited, this.kernel.ok(this.kernel.exports.joint_set_motor(this.world, this.handle, 0)), this;
1502
+ }
1503
+ get force() {
1504
+ let [e, t] = this.reaction();
1505
+ return [e, t];
1506
+ }
1507
+ get torque() {
1508
+ return this.reaction()[2];
1509
+ }
1510
+ reaction() {
1511
+ if (this.removed) throw new e("state", "Joint2D was removed; add a new joint with Physics2D.addJoint.");
1512
+ this.kernel.ok(this.kernel.exports.joint_force(this.world, this.handle));
1513
+ let t = this.kernel.io(3);
1514
+ return [
1515
+ t.f[0],
1516
+ t.f[1],
1517
+ t.f[2]
1518
+ ];
1519
+ }
1520
+ get isRemoved() {
1521
+ return this.removed;
1522
+ }
1523
+ remove() {
1524
+ this.onRemove(this);
1525
+ }
1526
+ free() {
1527
+ this.removed || (this.removed = !0, this.kernel.exports.joint_remove(this.world, this.handle));
1528
+ }
1529
+ };
1530
+ function B(e, t, n) {
1531
+ let [r, i] = e.position, a = e.rotation;
1532
+ return [r + Math.cos(a) * t - Math.sin(a) * n, i + Math.sin(a) * t + Math.cos(a) * n];
1533
+ }
1534
+ function V(e, t, n) {
1535
+ let [r, i] = e.position, a = e.rotation, o = t - r, s = n - i;
1536
+ return [Math.cos(a) * o + Math.sin(a) * s, -Math.sin(a) * o + Math.cos(a) * s];
1537
+ }
1538
+ //#endregion
1539
+ //#region src/physics.ts
1540
+ var H = [
1541
+ "fixed",
1542
+ "awake",
1543
+ "sleeping",
1544
+ "kinematic",
1545
+ "sensor",
1546
+ "joint",
1547
+ "contactPoint",
1548
+ "contactNormal",
1549
+ "box",
1550
+ "axisX",
1551
+ "axisY",
1552
+ "solverPoint",
1553
+ "solverNormal"
1554
+ ], U = {
1555
+ fixed: [
1556
+ .5,
1557
+ .5,
1558
+ .5,
1559
+ 1
1560
+ ],
1561
+ awake: [
1562
+ .2,
1563
+ .9,
1564
+ .3,
1565
+ 1
1566
+ ],
1567
+ sleeping: [
1568
+ .15,
1569
+ .5,
1570
+ .2,
1571
+ 1
1572
+ ],
1573
+ kinematic: [
1574
+ .3,
1575
+ .5,
1576
+ 1,
1577
+ 1
1578
+ ],
1579
+ sensor: [
1580
+ 1,
1581
+ .9,
1582
+ .2,
1583
+ 1
1584
+ ],
1585
+ joint: [
1586
+ 1,
1587
+ .2,
1588
+ .2,
1589
+ 1
1590
+ ],
1591
+ contactPoint: [
1592
+ 1,
1593
+ .2,
1594
+ 1,
1595
+ 1
1596
+ ],
1597
+ contactNormal: [
1598
+ 1,
1599
+ .6,
1600
+ 1,
1601
+ 1
1602
+ ],
1603
+ box: [
1604
+ .2,
1605
+ .9,
1606
+ .9,
1607
+ .4
1608
+ ],
1609
+ axisX: [
1610
+ .9,
1611
+ .1,
1612
+ .1,
1613
+ 1
1614
+ ],
1615
+ axisY: [
1616
+ .1,
1617
+ .8,
1618
+ .1,
1619
+ 1
1620
+ ],
1621
+ solverPoint: [
1622
+ 1,
1623
+ .5,
1624
+ 0,
1625
+ 1
1626
+ ],
1627
+ solverNormal: [
1628
+ 1,
1629
+ .75,
1630
+ .3,
1631
+ 1
1632
+ ]
1633
+ }, W = () => {};
1634
+ function te(e) {
1635
+ e(this);
1636
+ }
1637
+ var G = Math.PI * 2, K = 12, q = 4294967295, J = new i(({ wasm: e, simd: t }, n) => import("./kernel-DkjP8dvA.js").then((r) => r.startKernel(e ?? r.defaultWasm(!(t ?? r.hasSimd())), n))), Y = {
1638
+ dynamic: 0,
1639
+ fixed: 1,
1640
+ kinematicPosition: 2,
1641
+ kinematicVelocity: 2
1642
+ }, X = [
1643
+ ["substeps", "count"],
1644
+ ["iterations", "count"],
1645
+ ["contactHertz", "amount"],
1646
+ ["contactDamping", "amount"],
1647
+ ["contactMaxPush", "speed"],
1648
+ ["restitutionThreshold", "speed"],
1649
+ ["sleepThreshold", "speed"],
1650
+ ["sleepTime", "amount"],
1651
+ ["canSleep", "flag"],
1652
+ ["blockSolver", "flag"],
1653
+ ["jointHertz", "amount"],
1654
+ ["jointDamping", "amount"],
1655
+ ["jointMaxPush", "speed"],
1656
+ ["jointGeometricStiffness", "flag"],
1657
+ ["maxCcdSubsteps", "whole"],
1658
+ ["minCcdDt", "amount"],
1659
+ ["ccdTolerance", "length"],
1660
+ ["ccdMaxAdvances", "advances"],
1661
+ ["warmStart", "share"],
1662
+ ["allowedPenetration", "depth"],
1663
+ ["predictionDistance", "depth"],
1664
+ ["staticContactHertz", "spring"],
1665
+ ["staticContactDamping", "spring"]
1666
+ ], Z = (e) => e === "speed" || e === "length" || e === "depth", Q = class t {coreRequirement=__margoCoreRequirement("1.0.0",import.meta.url);
1667
+ static async load({ signal: e, wasm: t, simd: n } = {}) {
1668
+ await J.load({
1669
+ wasm: t,
1670
+ simd: n
1671
+ }, e);
1672
+ }
1673
+ static attach(e, n = {}) {__margoAssertCore(e,__margoCoreRequirement("1.0.0",import.meta.url));
1674
+ return new t(e, n);
1675
+ }
1676
+ constructor(t, n = {}) {
1677
+ this.stepCount = 0, this.engine = null, this.accumulator = 0, this.lastAlpha = 1, this.disposed = !1, this.bodies = /* @__PURE__ */ new Set(), this.movers = null, this.byShape = /* @__PURE__ */ new Map(), this.nextColliderUid = 1, this.touchingPairs = /* @__PURE__ */ new Map(), this.carriedPairs = /* @__PURE__ */ new Map(), this.joints = /* @__PURE__ */ new Set(), this.controllers = /* @__PURE__ */ new Set(), this.listeners = /* @__PURE__ */ new Map(), this.events = [], this.breakable = /* @__PURE__ */ new Map(), this.gears = [], this.dispatching = !1, this.syncAlpha = 1, this.hookSet = null, this.anchor = -1, this.asleep = null;
1678
+ let r = J.value;
1679
+ if (!r) throw new e("state", "Physics2D is not loaded; call await Physics2D.load() once before new Physics2D().");
1680
+ this.kernel = r, this.name = n.name ?? "physics2d";
1681
+ let i = n.pixelsPerMeter ?? 32;
1682
+ if (!(i > 0) || !Number.isFinite(i)) throw RangeError("pixelsPerMeter must be a finite number above 0");
1683
+ this.scale = 1 / i;
1684
+ let { fixedTimestep: a = 1 / 60, maxSubsteps: o = 4 } = n;
1685
+ if (!(a > 0 && a <= 1)) throw RangeError(`fixedTimestep must be in (0, 1] seconds, got ${a}; try 1/60.`);
1686
+ if (!Number.isInteger(o) || o < 1) throw RangeError(`maxSubsteps must be a positive integer, got ${o}; try 4.`);
1687
+ this.fixedTimestep = a, this.maxSubsteps = o, this.interpolate = n.interpolate ?? !0, this.timeScale = n.timeScale ?? 1, this.paused = n.paused ?? !1;
1688
+ let s = n.gravity ?? [0, 9.81 * i];
1689
+ if (this.checkVec(s, "Gravity"), this.gravityValue = [s[0], s[1]], this.handle = r.ok(r.exports.world_create(s[0] * this.scale, s[1] * this.scale)), t) try {
1690
+ t.use(this);
1691
+ } catch (e) {
1692
+ throw this.dispose(), e;
1693
+ }
1694
+ }
1695
+ checkVec(e, t) {
1696
+ let n = e;
1697
+ if (!n || n.length !== 2 || !Number.isFinite(n[0]) || !Number.isFinite(n[1])) throw TypeError(`${t} must be two finite numbers [x, y]; fix the value.`);
1698
+ }
1699
+ live() {
1700
+ if (this.disposed) throw new e("disposed", "Physics2D is disposed; create a new Physics2D.");
1701
+ }
1702
+ get isDisposed() {
1703
+ return this.disposed;
1704
+ }
1705
+ get gravity() {
1706
+ return [this.gravityValue[0], this.gravityValue[1]];
1707
+ }
1708
+ set gravity(e) {
1709
+ this.live(), this.checkVec(e, "Gravity"), this.kernel.ok(this.kernel.exports.world_set_gravity(this.handle, e[0] * this.scale, e[1] * this.scale)), this.gravityValue = [e[0], e[1]];
1710
+ }
1711
+ get alpha() {
1712
+ return this.lastAlpha;
1713
+ }
1714
+ get bodyCount() {
1715
+ return this.bodies.size;
1716
+ }
1717
+ get timing() {
1718
+ this.live();
1719
+ let { kernel: e, handle: t } = this, n = (n) => e.exports.world_timing(t, n);
1720
+ return {
1721
+ step: n(0),
1722
+ begin: n(1),
1723
+ broad: n(2),
1724
+ narrow: n(3),
1725
+ islands: n(4),
1726
+ solver: n(5),
1727
+ ccd: n(6),
1728
+ events: n(7),
1729
+ assembly: n(8),
1730
+ resolution: n(9),
1731
+ update: n(10),
1732
+ writeback: n(11),
1733
+ ccdBroad: n(12),
1734
+ ccdToi: n(13),
1735
+ ccdSolver: n(14)
1736
+ };
1737
+ }
1738
+ get counts() {
1739
+ this.live();
1740
+ let { kernel: e } = this, t = e.ok(e.exports.world_counts(this.handle)), n = e.io(t).u;
1741
+ return {
1742
+ awake: n[0],
1743
+ islands: n[1],
1744
+ boxesCompared: n[2],
1745
+ pairs: n[3],
1746
+ manifolds: n[4],
1747
+ coldPoints: n[5],
1748
+ contactsSolved: n[6],
1749
+ blockSolves: n[7],
1750
+ sequentialSolves: n[8],
1751
+ colours: n[9],
1752
+ uncoloured: n[10],
1753
+ treeJoints: n[11],
1754
+ events: n[12],
1755
+ steps: n[13]
1756
+ };
1757
+ }
1758
+ get solver() {
1759
+ this.live();
1760
+ let { kernel: e } = this, t = e.io(e.ok(e.exports.world_settings(this.handle))).f, n = {};
1761
+ return X.forEach(([e, r], i) => {
1762
+ n[e] = r === "flag" ? t[i] !== 0 : r === "spring" && t[i] === -1 ? null : Z(r) ? t[i] / this.scale : t[i];
1763
+ }), n;
1764
+ }
1765
+ setSolver(e) {
1766
+ this.live();
1767
+ let { kernel: t } = this;
1768
+ for (let [t, n] of X) {
1769
+ let r = e[t];
1770
+ if (n === "flag" || r === void 0) continue;
1771
+ if (r === null) {
1772
+ if (n === "spring") continue;
1773
+ throw RangeError(`Solver ${t} must be a number; got null.`);
1774
+ }
1775
+ let i = Number.isInteger(r), [a, o, s] = n === "count" ? [
1776
+ i && r >= 1 && r <= 65535,
1777
+ "a whole number from 1 to 65535",
1778
+ "a count such as 4"
1779
+ ] : n === "whole" ? [
1780
+ i && r >= 0 && r <= 65535,
1781
+ "a whole number from 0 to 65535",
1782
+ "0 for none"
1783
+ ] : n === "advances" ? [
1784
+ i && r >= 0 && r <= 4096,
1785
+ "a whole number from 0 to 4096",
1786
+ "a count such as 32"
1787
+ ] : n === "length" ? [
1788
+ r * this.scale >= 1e-7 && r < Infinity,
1789
+ "a finite number of 1e-7 metres or more",
1790
+ "a distance such as 0.005"
1791
+ ] : n === "share" ? [
1792
+ r >= 0 && r <= 1,
1793
+ "a number from 0 to 1",
1794
+ "1 for the whole impulse"
1795
+ ] : n === "spring" ? [
1796
+ r >= 0 && r < Infinity,
1797
+ "a finite number of 0 or more, or null",
1798
+ "null for the contact spring"
1799
+ ] : [
1800
+ r >= 0 && r < Infinity,
1801
+ "a finite number of 0 or more",
1802
+ "0 for none"
1803
+ ];
1804
+ if (!a) throw RangeError(`Solver ${t} must be ${o}; got ${r}. Give ${s}.`);
1805
+ }
1806
+ return X.forEach(([n, r], i) => {
1807
+ let a = e[n];
1808
+ a !== void 0 && t.ok(t.exports.world_set_setting(this.handle, i, a === null ? -1 : Number(a) * (Z(r) ? this.scale : 1)));
1809
+ }), this;
1810
+ }
1811
+ getBodies() {
1812
+ return [...this.bodies];
1813
+ }
1814
+ getColliders() {
1815
+ return [...new Set(this.byShape.values())].sort((e, t) => e.shapes[0] - t.shapes[0]);
1816
+ }
1817
+ get colliderCount() {
1818
+ return new Set(this.byShape.values()).size;
1819
+ }
1820
+ getJoints() {
1821
+ return [...this.joints];
1822
+ }
1823
+ get jointCount() {
1824
+ return this.joints.size;
1825
+ }
1826
+ setup(t) {
1827
+ if (this.live(), this.engine && this.engine !== t) throw new e("attached", "Physics2D is attached to another engine; create one Physics2D per engine.");
1828
+ this.engine = t;
1829
+ }
1830
+ onPreUpdate(e) {
1831
+ this.update(e);
1832
+ }
1833
+ update(e) {
1834
+ if (this.disposed) return 0;
1835
+ if (!Number.isFinite(e) || e < 0) throw RangeError(`delta must be a finite, non-negative number of seconds, got ${e}.`);
1836
+ let t = 0;
1837
+ if (!this.paused) {
1838
+ let n = this.fixedTimestep;
1839
+ this.accumulator += e * this.timeScale, t = Math.min(this.maxSubsteps, Math.floor(this.accumulator / n + 1e-6));
1840
+ for (let e = 0; e < t; e++) this.step();
1841
+ this.accumulator = Math.max(0, this.accumulator - t * n) % n, this.lastAlpha = this.interpolate ? this.accumulator / n : 1;
1842
+ }
1843
+ return this.sync(), t;
1844
+ }
1845
+ step() {
1846
+ this.live();
1847
+ let e = this.fixedTimestep;
1848
+ if (this.emit("beforestep", e), this.disposed) return;
1849
+ let { kernel: t } = this;
1850
+ this.hookSet && this.installHooks();
1851
+ try {
1852
+ t.ok(t.exports.world_step(this.handle, e));
1853
+ } finally {
1854
+ t.hooks = null;
1855
+ }
1856
+ this.stepCount++, this.readPoses();
1857
+ let n = this.dispatching, r = n ? [] : this.events;
1858
+ this.collectEvents(r), this.breakJoints(r), this.asleep && this.sleepEvents(r), this.dispatching = !0;
1859
+ try {
1860
+ for (let [e, t] of r) this.emit(e, t);
1861
+ } finally {
1862
+ this.dispatching = n, r.length = 0;
1863
+ }
1864
+ this.emit("afterstep", e);
1865
+ }
1866
+ readPoses() {
1867
+ let e = this.movers ??= [...this.bodies].filter((e) => e.type !== "fixed"), t = e.length;
1868
+ if (!t) return;
1869
+ let { kernel: n } = this, r = n.io(5 * t);
1870
+ for (let n = 0; n < t; n++) r.u[n] = e[n].handle;
1871
+ n.ok(n.exports.body_read_poses(this.handle, t));
1872
+ let i = n.io(5 * t).f, a = 1 / this.scale;
1873
+ for (let n = 0; n < t; n++) e[n].store(i[t + 4 * n], i[t + 4 * n + 1], i[t + 4 * n + 2], i[t + 4 * n + 3], a);
1874
+ }
1875
+ pairKey(e, t) {
1876
+ return e.uid < t.uid ? `${e.uid}:${t.uid}` : `${t.uid}:${e.uid}`;
1877
+ }
1878
+ pushCollisionEvent(e, t, n, r, i) {
1879
+ let a = i ? r ? "intersectionstart" : "intersectionend" : r ? "contactstart" : "contactend", o = a === "contactstart" ? this.contactPair(t, n) ?? void 0 : void 0;
1880
+ e.push([a, {
1881
+ type: a,
1882
+ bodyA: t.body,
1883
+ bodyB: n.body,
1884
+ colliderA: t,
1885
+ colliderB: n,
1886
+ sensor: i,
1887
+ ...o ? { contact: o } : {}
1888
+ }]);
1889
+ }
1890
+ collectEvents(e) {
1891
+ let { kernel: t } = this, n = t.ok(t.exports.events_read(this.handle));
1892
+ if (n) {
1893
+ let r = t.io(3 * n).u.slice(0, 3 * n);
1894
+ for (let t = 0; t < n; t++) {
1895
+ let n = this.byShape.get(r[3 * t]), i = this.byShape.get(r[3 * t + 1]);
1896
+ if (!n || !i || n === i) continue;
1897
+ let a = r[3 * t + 2], o = (a & 3) == 1, s = !!(a & 4), c = this.pairKey(n, i);
1898
+ if (o) {
1899
+ if (this.carriedPairs.delete(c)) {
1900
+ this.touchingPairs.set(c, {
1901
+ count: 1,
1902
+ sensor: s,
1903
+ a: n,
1904
+ b: i
1905
+ });
1906
+ continue;
1907
+ }
1908
+ let t = this.touchingPairs.get(c);
1909
+ t ? t.count++ : (this.touchingPairs.set(c, {
1910
+ count: 1,
1911
+ sensor: s,
1912
+ a: n,
1913
+ b: i
1914
+ }), this.pushCollisionEvent(e, n, i, !0, s));
1915
+ } else {
1916
+ let t = this.touchingPairs.get(c);
1917
+ t ? (t.count--, t.count <= 0 && (this.touchingPairs.delete(c), this.pushCollisionEvent(e, n, i, !1, s))) : this.carriedPairs.has(c) || this.pushCollisionEvent(e, n, i, !1, s);
1918
+ }
1919
+ }
1920
+ }
1921
+ if (this.carriedPairs.size) {
1922
+ for (let t of this.carriedPairs.values()) this.pushCollisionEvent(e, t.a, t.b, !1, t.sensor);
1923
+ this.carriedPairs.clear();
1924
+ }
1925
+ let r = t.ok(t.exports.force_events_read(this.handle));
1926
+ if (r) {
1927
+ let n = t.io(5 * r);
1928
+ for (let t = 0; t < r; t++) {
1929
+ let r = this.byShape.get(n.u[5 * t]), i = this.byShape.get(n.u[5 * t + 1]);
1930
+ r && i && e.push(["contactforce", {
1931
+ bodyA: r.body,
1932
+ bodyB: i.body,
1933
+ colliderA: r,
1934
+ colliderB: i,
1935
+ force: n.f[5 * t + 2],
1936
+ normal: [n.f[5 * t + 3], n.f[5 * t + 4]]
1937
+ }]);
1938
+ }
1939
+ }
1940
+ }
1941
+ sync(e = this.lastAlpha) {
1942
+ if (!this.disposed) {
1943
+ if (!Number.isFinite(e)) throw RangeError("Interpolation alpha must be a finite number; pass a value from 0 to 1.");
1944
+ this.syncAlpha = this.interpolate ? Math.min(1, Math.max(0, e)) : 1;
1945
+ for (let e of this.bodies) {
1946
+ let t = e.sprite;
1947
+ if (!t || e.type === "fixed" && !e.dirty) continue;
1948
+ let n = e.pose, r = this.syncAlpha;
1949
+ t.x = n[0] + (n[3] - n[0]) * r, t.y = n[1] + (n[4] - n[1]) * r;
1950
+ let i = (n[5] - n[2]) % G;
1951
+ i > Math.PI ? i -= G : i < -Math.PI && (i += G), t.rotation = n[2] + i * r, e.dirty = !1;
1952
+ }
1953
+ }
1954
+ }
1955
+ addBody(e, t = {}) {
1956
+ this.live();
1957
+ let n = t.type ?? "dynamic", r = this.scale;
1958
+ if (!(n in Y)) throw TypeError(`Unknown body type "${n}"; use dynamic, fixed, kinematicPosition or kinematicVelocity.`);
1959
+ let i = t.position ?? [e?.x ?? 0, e?.y ?? 0];
1960
+ this.checkVec(i, "Body position");
1961
+ let a = t.rotation ?? e?.rotation ?? 0;
1962
+ if (!Number.isFinite(a)) throw RangeError("Body rotation must be a finite number of radians");
1963
+ let o = t.linearVelocity ?? [0, 0];
1964
+ this.checkVec(o, "linearVelocity");
1965
+ let s = t.dominance ?? 0;
1966
+ if (!Number.isInteger(s) || s < -127 || s > 127) throw RangeError(`dominance must be an integer from -127 to 127, got ${s}.`);
1967
+ let c = this.kernel.io(16);
1968
+ c.f.set([
1969
+ i[0] * r,
1970
+ i[1] * r,
1971
+ Math.cos(a),
1972
+ Math.sin(a),
1973
+ o[0] * r,
1974
+ o[1] * r,
1975
+ t.angularVelocity ?? 0,
1976
+ t.linearDamping ?? 0,
1977
+ t.angularDamping ?? 0,
1978
+ t.gravityScale ?? 1
1979
+ ], 0), new Int32Array(c.u.buffer, c.u.byteOffset, 16)[10] = s;
1980
+ let l = (t.canSleep ?? !0 ? 1 : 0) | (t.lockRotation ? 2 : 0) | (t.ccd ? 4 : 0), u = this.kernel.ok(this.kernel.exports.body_create(this.handle, Y[n], l)), d = new A(this, u, e, n);
1981
+ if (d.userData = t.userData, d.turnLocked = t.lockRotation === !0, d.params = {
1982
+ linearDamping: t.linearDamping ?? 0,
1983
+ angularDamping: t.angularDamping ?? 0,
1984
+ gravityScale: t.gravityScale ?? 1,
1985
+ canSleep: t.canSleep ?? !0,
1986
+ ccd: t.ccd === !0,
1987
+ dominance: s
1988
+ }, t.lockTranslation) {
1989
+ let e = t.lockTranslation === !0 ? [!0, !0] : t.lockTranslation;
1990
+ try {
1991
+ d.lockTranslation(e[0], e[1]);
1992
+ } catch (e) {
1993
+ throw this.kernel.exports.body_remove(this.handle, u), this.bodies.delete(d), e;
1994
+ }
1995
+ }
1996
+ if (t.softCcd) try {
1997
+ d.softCcd = t.softCcd;
1998
+ } catch (e) {
1999
+ throw this.removeBody(d), e;
2000
+ }
2001
+ if (t.additionalMass) try {
2002
+ d.additionalMass = t.additionalMass;
2003
+ } catch (e) {
2004
+ throw this.kernel.exports.body_remove(this.handle, u), e;
2005
+ }
2006
+ this.bodies.add(d), this.movers = null;
2007
+ try {
2008
+ let n = t.colliders;
2009
+ n === void 0 && (n = ne(e));
2010
+ for (let e of Array.isArray(n) ? n : n ? [n] : []) this.addCollider(d, e);
2011
+ } catch (e) {
2012
+ throw this.removeBody(d), e;
2013
+ }
2014
+ return d;
2015
+ }
2016
+ addTileMap(e, t = {}) {
2017
+ let n = this.addBody(null, {
2018
+ type: "fixed",
2019
+ colliders: [],
2020
+ userData: t.userData
2021
+ });
2022
+ try {
2023
+ for (let r of f(e, t)) this.addCollider(n, r);
2024
+ } catch (e) {
2025
+ throw this.removeBody(n), e;
2026
+ }
2027
+ return n;
2028
+ }
2029
+ addCollider(e, t) {
2030
+ this.live();
2031
+ let n = E(t, this.scale), r = [];
2032
+ try {
2033
+ let t = [];
2034
+ for (let i of n) {
2035
+ let n = this.createShapes(e, i);
2036
+ r.push(...n), i.seam && t.push(...n);
2037
+ }
2038
+ if (t.length > 1) {
2039
+ let { kernel: e } = this;
2040
+ e.io(t.length).u.set(t, 0), e.ok(e.exports.shapes_join_seams(this.handle, t.length));
2041
+ }
2042
+ } catch (e) {
2043
+ for (let e of r) this.kernel.exports.shape_remove(this.handle, e);
2044
+ throw e;
2045
+ }
2046
+ let i = Uint32Array.from(n[0].settings), a = new k(this, e, r, i, t.offset ?? [0, 0], t.rotation ?? 0, this.nextColliderUid++);
2047
+ a.described = n[0], a.options = t, t.mass !== void 0 && a.setMass(t.mass), t.rollingResistance !== void 0 && a.setRollingResistance(t.rollingResistance);
2048
+ for (let e of r) this.byShape.set(e, a);
2049
+ return e.colliders.push(a), a;
2050
+ }
2051
+ replaceColliderShapes(e, t, n) {
2052
+ this.live();
2053
+ let { body: r } = e, i = e.rawSettings, a = [];
2054
+ try {
2055
+ let e = [];
2056
+ for (let t of n) {
2057
+ let n = this.createShapes(r, {
2058
+ ...t,
2059
+ settings: i
2060
+ });
2061
+ a.push(...n), t.seam && e.push(...n);
2062
+ }
2063
+ if (e.length > 1) {
2064
+ let { kernel: t } = this;
2065
+ t.io(e.length).u.set(e, 0), t.ok(t.exports.shapes_join_seams(this.handle, e.length));
2066
+ }
2067
+ } catch (e) {
2068
+ for (let e of a) this.kernel.exports.shape_remove(this.handle, e);
2069
+ throw e;
2070
+ }
2071
+ for (let [t, n] of this.touchingPairs) (n.a === e || n.b === e) && (this.carriedPairs.set(t, {
2072
+ a: n.a,
2073
+ b: n.b,
2074
+ sensor: n.sensor
2075
+ }), this.touchingPairs.delete(t));
2076
+ let o = e.rollingResistance();
2077
+ if (o > 0) for (let e of a) this.kernel.ok(this.kernel.exports.shape_set_rolling_resistance(this.handle, e, o));
2078
+ for (let t of e.shapes) this.byShape.delete(t), this.kernel.exports.shape_remove(this.handle, t);
2079
+ e.shapes.splice(0, e.shapes.length, ...a);
2080
+ for (let t of a) this.byShape.set(t, e);
2081
+ e.described = {
2082
+ ...n[0],
2083
+ settings: i
2084
+ }, e.options &&= {
2085
+ ...e.options,
2086
+ ...t
2087
+ }, e.reapplyMass();
2088
+ }
2089
+ createShapes(e, t) {
2090
+ let { kernel: n } = this, r = n.io(8 + t.geometry.length);
2091
+ r.u.set(t.settings, 0), r.u.set(t.geometry, 8);
2092
+ let i = n.ok(n.exports.shape_create(this.handle, e.handle, t.kind));
2093
+ return Array.from(n.io(i).u.subarray(0, i));
2094
+ }
2095
+ removeCollider(e) {
2096
+ if (e.isRemoved) return;
2097
+ for (let [t, n] of this.touchingPairs) (n.a === e || n.b === e) && this.touchingPairs.delete(t);
2098
+ for (let [t, n] of this.carriedPairs) (n.a === e || n.b === e) && this.carriedPairs.delete(t);
2099
+ for (let t of e.shapes) this.byShape.delete(t), this.kernel.exports.shape_remove(this.handle, t);
2100
+ e.markRemoved();
2101
+ let t = e.body.colliders;
2102
+ t.splice(t.indexOf(e), 1);
2103
+ }
2104
+ removeBody(e) {
2105
+ if (this.bodies.has(e)) {
2106
+ for (let t of [...this.joints]) (t.bodyA === e || t.bodyB === e) && this.removeJoint(t);
2107
+ for (let t of [...this.controllers]) t.body === e && t.dispose();
2108
+ for (let t of e.colliders) {
2109
+ for (let [e, n] of this.touchingPairs) (n.a === t || n.b === t) && this.touchingPairs.delete(e);
2110
+ for (let [e, n] of this.carriedPairs) (n.a === t || n.b === t) && this.carriedPairs.delete(e);
2111
+ for (let e of t.shapes) this.byShape.delete(e);
2112
+ t.markRemoved();
2113
+ }
2114
+ e.colliders.length = 0, this.bodies.delete(e), this.movers = null, this.kernel.exports.body_remove(this.handle, e.handle), e.markRemoved();
2115
+ }
2116
+ }
2117
+ get hooks() {
2118
+ return this.hookSet;
2119
+ }
2120
+ set hooks(e) {
2121
+ this.live(), this.hookSet = e;
2122
+ let { kernel: t } = this;
2123
+ t.ok(t.exports.world_set_hooks(this.handle, +!!e)), this.installHooks();
2124
+ }
2125
+ installHooks() {
2126
+ this.kernel.hooks = this.hookSet ? {
2127
+ filter: (e, t) => {
2128
+ let n = this.byShape.get(e), r = this.byShape.get(t);
2129
+ if (!n || !r || !this.hookSet) return !0;
2130
+ let i = n.isSensor() || r.isSensor() ? this.hookSet.filterIntersection : this.hookSet.filterPair;
2131
+ return !i || i.call(this.hookSet, n, r) !== !1;
2132
+ },
2133
+ contact: (e, t, n, r, i) => {
2134
+ let a = this.byShape.get(e), o = this.byShape.get(t);
2135
+ if (!a || !o || !this.hookSet?.modifyContact) return 0;
2136
+ let s = {
2137
+ colliderA: a,
2138
+ colliderB: o,
2139
+ normal: [n, r],
2140
+ tangent: [r, -n],
2141
+ points: i,
2142
+ solverActive: !0
2143
+ };
2144
+ this.hookSet.modifyContact(s);
2145
+ let c = +!s.solverActive, l = this.kernel.current(5);
2146
+ return s.tangentVelocity && (l.f[4] = s.tangentVelocity * this.scale, c |= 16), s.friction !== void 0 && (l.f[0] = s.friction, c |= 2), s.restitution !== void 0 && (l.f[1] = s.restitution, c |= 4), s.oneWay && (l.f[2] = s.oneWay[0], l.f[3] = s.oneWay[1], c |= 8), c;
2147
+ }
2148
+ } : null;
2149
+ }
2150
+ retype(e, t) {
2151
+ if (this.live(), !(t in Y)) throw TypeError(`Unknown body type "${t}"; use dynamic, fixed, kinematicPosition or kinematicVelocity.`);
2152
+ this.kernel.ok(this.kernel.exports.body_set_kind(this.handle, e.handle, Y[t])), this.movers = null, e.snapshot(), e.pose.copyWithin(0, 3, 6);
2153
+ }
2154
+ projectPoint(e, t, n = !0) {
2155
+ this.live(), this.checkVec(e, "Point");
2156
+ let r = this.scale;
2157
+ this.writeFilter(t);
2158
+ let i = this.kernel.io(8);
2159
+ i.f.set([e[0] * r, e[1] * r], 4), i.u[6] = +!!n;
2160
+ let a = this.kernel.ok(this.kernel.exports.project_point(this.handle)), o = this.kernel.io(5 * a);
2161
+ for (let e = 0; e < a; e++) {
2162
+ let n = this.hitOf(o.u[5 * e], t);
2163
+ if (n) return {
2164
+ ...n,
2165
+ point: [o.f[5 * e + 1] / r, o.f[5 * e + 2] / r],
2166
+ inside: o.u[5 * e + 4] !== 0,
2167
+ distance: o.f[5 * e + 3] / r
2168
+ };
2169
+ }
2170
+ return null;
2171
+ }
2172
+ explode(e) {
2173
+ this.live(), this.checkVec(e.position, "Explosion position");
2174
+ let t = e.falloff ?? 0;
2175
+ for (let [n, r] of [[e.radius, "radius"], [t, "falloff"]]) if (!(n >= 0 && n < Infinity)) throw RangeError(`An explosion's ${r} is a finite number of 0 or more; got ${n}.`);
2176
+ if (!Number.isFinite(e.impulsePerLength)) throw RangeError(`impulsePerLength must be a finite number; got ${e.impulsePerLength}.`);
2177
+ this.writeFilter(e.filter);
2178
+ let n = this.scale;
2179
+ this.kernel.io(9).f.set([
2180
+ e.position[0] * n,
2181
+ e.position[1] * n,
2182
+ e.radius * n,
2183
+ t * n,
2184
+ e.impulsePerLength
2185
+ ], 4);
2186
+ let r = this.kernel.ok(this.kernel.exports.explosion(this.handle)), i = this.kernel.io(5 * r), a = Array.from({ length: r }, (e, t) => [i.u[5 * t], ...i.f.subarray(5 * t + 1, 5 * t + 5)]), o = [];
2187
+ for (let [t, n, r, i, s] of a) {
2188
+ let a = this.hitOf(t, e.filter);
2189
+ a?.collider && (this.kernel.ok(this.kernel.exports.body_impulse(this.handle, a.body.handle, n, r, 1, i, s)), o.push(a.collider));
2190
+ }
2191
+ return o;
2192
+ }
2193
+ intersectionsWithBox(e, t, n) {
2194
+ this.live(), this.checkVec(e, "Box min"), this.checkVec(t, "Box max"), this.writeFilter(n);
2195
+ let r = this.scale;
2196
+ this.kernel.io(8).f.set([
2197
+ e[0] * r,
2198
+ e[1] * r,
2199
+ t[0] * r,
2200
+ t[1] * r
2201
+ ], 4);
2202
+ let i = this.kernel.ok(this.kernel.exports.aabb_query(this.handle));
2203
+ return this.bodiesOf(this.kernel.io(i).u, i, n);
2204
+ }
2205
+ contactPairs(t) {
2206
+ if (this.live(), t.isRemoved) throw new e("state", "Collider2D was removed; ask for the contacts of a live collider.");
2207
+ let n = /* @__PURE__ */ new Map(), r = 1 / this.scale;
2208
+ for (let e of t.shapes) {
2209
+ let i = this.kernel.ok(this.kernel.exports.contacts_of(this.handle, e)), { f: a, u: o } = this.kernel.io(K * i);
2210
+ for (let e = 0; e < i; e++) {
2211
+ let i = this.byShape.get(o[K * e]);
2212
+ if (!i || i === t) continue;
2213
+ let s = o[K * e + 1], c = s >> 2, l = !!(s & 1), u = !!(s & 2), d = a[K * e + 10], f = a[K * e + 11] * r, p = [a[K * e + 2], a[K * e + 3]], m = [];
2214
+ for (let t = 0; t < c; t++) m.push({
2215
+ point: [a[K * e + 4 + 3 * t] * r, a[K * e + 5 + 3 * t] * r],
2216
+ distance: a[K * e + 6 + 3 * t] * r
2217
+ });
2218
+ let h = n.get(i);
2219
+ h ? (h.points.push(...m), h.approachSpeed = Math.max(h.approachSpeed, f), (!h.touching && u || u && d > h.impulse) && (h.normal = p), h.impulse += d, h.solverActive = h.solverActive || l, h.touching = h.touching || u) : n.set(i, {
2220
+ collider: t,
2221
+ other: i,
2222
+ normal: p,
2223
+ points: m,
2224
+ impulse: d,
2225
+ approachSpeed: f,
2226
+ solverActive: l,
2227
+ touching: u
2228
+ });
2229
+ }
2230
+ }
2231
+ return [...n.values()];
2232
+ }
2233
+ contactPair(e, t) {
2234
+ return this.contactPairs(e).find((e) => e.other === t) ?? null;
2235
+ }
2236
+ intersectionPair(e, t) {
2237
+ return !e.isSensor() && !t.isSensor() ? !1 : this.contactPair(e, t)?.touching ?? !1;
2238
+ }
2239
+ intersectionPairsWith(e) {
2240
+ return this.contactPairs(e).filter((t) => t.touching && (e.isSensor() || t.other.isSensor())).map((e) => e.other);
2241
+ }
2242
+ lockTranslation(e, t, n) {
2243
+ this.live();
2244
+ let { kernel: r } = this;
2245
+ if (e.lockJoint >= 0 && (r.exports.joint_remove(this.handle, e.lockJoint), e.lockJoint = -1), !t && !n) return;
2246
+ if (this.anchor < 0) {
2247
+ let e = r.io(16);
2248
+ e.u.fill(0, 0, 16), e.f.set([
2249
+ 0,
2250
+ 0,
2251
+ 1,
2252
+ 0
2253
+ ], 0), e.f[9] = 1, this.anchor = r.ok(r.exports.body_create(this.handle, 1, 1));
2254
+ }
2255
+ r.ok(r.exports.body_read(this.handle, e.handle));
2256
+ let i = r.io(11).f, [a, o] = [i[0], i[1]], s = r.io(32);
2257
+ s.u.fill(0, 0, 32), s.u[0] = 5, s.f.set([
2258
+ a,
2259
+ o,
2260
+ 0,
2261
+ 0
2262
+ ], 1), s.f.set([
2263
+ 1,
2264
+ 0,
2265
+ 1,
2266
+ 0
2267
+ ], 16), s.u[24] = !!t | (n ? 2 : 0), e.lockJoint = r.ok(r.exports.joint_create(this.handle, this.anchor, e.handle, 0));
2268
+ }
2269
+ addJoint(t, n, r) {
2270
+ if (this.live(), !this.bodies.has(t) || !this.bodies.has(n)) throw new e("state", "Both joint bodies must belong to this Physics2D and not be removed.");
2271
+ let i = (e, t, n) => {
2272
+ let [r, i] = B(e, t?.[0] ?? 0, t?.[1] ?? 0);
2273
+ return Math.hypot(r - n[0], i - n[1]);
2274
+ }, a = r.type === "gear" ? this.gearSides(t, n, r.jointA, r.jointB) : void 0, o = a === void 0 ? r.type === "target" ? {
2275
+ ...r,
2276
+ anchorA: V(t, r.target[0], r.target[1])
2277
+ } : r.type === "distance" && r.length === void 0 ? (() => {
2278
+ let [e, i] = B(t, r.anchorA?.[0] ?? 0, r.anchorA?.[1] ?? 0), [a, o] = B(n, r.anchorB?.[0] ?? 0, r.anchorB?.[1] ?? 0);
2279
+ return {
2280
+ ...r,
2281
+ length: Math.hypot(a - e, o - i)
2282
+ };
2283
+ })() : r.type === "pulley" && r.length === void 0 ? {
2284
+ ...r,
2285
+ length: i(t, r.anchorA, r.groundA) + (r.ratio ?? 1) * i(n, r.anchorB, r.groundB)
2286
+ } : r : {
2287
+ ...r,
2288
+ anchorA: a.a.anchor,
2289
+ anchorB: a.b.anchor
2290
+ }, s = L(this.kernel, o, this.scale);
2291
+ if (a !== void 0 && r.type === "gear") {
2292
+ let e = r.ratio ?? 1;
2293
+ if (!Number.isFinite(e) || e === 0) throw RangeError(`A gear ratio is a finite number other than 0; got ${e}.`);
2294
+ let t = this.kernel.io(32);
2295
+ t.f.set([
2296
+ ...a.a.axis,
2297
+ ...a.b.axis,
2298
+ ...a.a.anchorC,
2299
+ e * a.a.unit / a.b.unit,
2300
+ ...a.b.anchorC
2301
+ ], 14), t.u[23] = a.a.carrier.handle, t.u[24] = a.b.carrier.handle;
2302
+ }
2303
+ let c = this.kernel.ok(this.kernel.exports.joint_create(this.handle, t.handle, n.handle, +(r.collide === !0))), l = new z(this.kernel, this.handle, c, t, n, r.type, s, (e) => this.removeJoint(e), this.scale, o);
2304
+ this.joints.add(l), r.type === "gear" && this.gears.push([
2305
+ l,
2306
+ r.jointA,
2307
+ r.jointB
2308
+ ]);
2309
+ let u = r.breakForce ?? Infinity, d = r.breakTorque ?? Infinity;
2310
+ if (!(u > 0) || !(d > 0)) throw RangeError("breakForce and breakTorque are above 0 (N, N m); leave them out for a joint that holds.");
2311
+ return (u < Infinity || d < Infinity) && this.breakable.set(l, [u, d]), l;
2312
+ }
2313
+ breakJoints(e) {
2314
+ for (let [t, [n, r]] of this.breakable) {
2315
+ if (t.isRemoved) {
2316
+ this.breakable.delete(t);
2317
+ continue;
2318
+ }
2319
+ let [i, a, o] = t.reaction();
2320
+ Math.hypot(i, a) <= n && Math.abs(o) <= r || (this.breakable.delete(t), this.removeJoint(t), e.push(["jointbreak", {
2321
+ joint: t,
2322
+ force: [i, a],
2323
+ torque: o
2324
+ }]));
2325
+ }
2326
+ }
2327
+ removeJoint(e) {
2328
+ if (!this.joints.delete(e)) return;
2329
+ e.free();
2330
+ let t = this.gears.filter(([t, n, r]) => t === e || n === e || r === e);
2331
+ if (t.length !== 0) {
2332
+ this.gears = this.gears.filter((e) => !t.includes(e));
2333
+ for (let [e] of t) this.removeJoint(e);
2334
+ }
2335
+ }
2336
+ gearSides(t, n, r, i) {
2337
+ let a = (t, n, r) => {
2338
+ let i = t.spec;
2339
+ if (!this.joints.has(t) || i === void 0) throw new e("state", `${r} must be a joint of this Physics2D and not removed.`);
2340
+ if (i.type !== "revolute" && i.type !== "prismatic") throw TypeError(`${r} is a ${i.type} joint; a gear gears revolute and prismatic joints.`);
2341
+ if (t.bodyB !== n) throw TypeError(`${r}'s body B must be the gear's own body ${r === "jointA" ? "A" : "B"}.`);
2342
+ let a = this.scale, o = i.anchorB ?? [0, 0], [s, c] = i.anchorA ?? [0, 0];
2343
+ if (i.type === "revolute") return {
2344
+ anchor: o,
2345
+ carrier: t.bodyA,
2346
+ axis: [0, 0],
2347
+ anchorC: [s * a, c * a],
2348
+ unit: 1
2349
+ };
2350
+ let [l, u] = i.axis, d = Math.hypot(l, u);
2351
+ return {
2352
+ anchor: o,
2353
+ carrier: t.bodyA,
2354
+ axis: [l / d, u / d],
2355
+ anchorC: [s * a, c * a],
2356
+ unit: a
2357
+ };
2358
+ };
2359
+ return {
2360
+ a: a(r, t, "jointA"),
2361
+ b: a(i, n, "jointB")
2362
+ };
2363
+ }
2364
+ addArticulation(t, n) {
2365
+ if (this.live(), !this.bodies.has(t)) throw new e("state", "The root must be a body of this Physics2D and not removed.");
2366
+ for (let t of n) if (!this.bodies.has(t.body)) throw new e("state", "Every link body must belong to this Physics2D and not be removed.");
2367
+ return new M(this, t, n);
2368
+ }
2369
+ createCharacterController(e, t = {}) {
2370
+ if (this.live(), e.type !== "kinematicPosition") throw TypeError("Character bodies must be 'kinematicPosition'; add the body with {type: 'kinematicPosition'}.");
2371
+ let n = new F(this, e, t, (e) => this.controllers.delete(e));
2372
+ return this.controllers.add(n), n;
2373
+ }
2374
+ writeFilter(e = {}) {
2375
+ let t = this.kernel.io(4);
2376
+ t.u[0] = e.groups ?? 4294967295, t.u[1] = +!!e.excludeSensors | (e.excludeFixed ? 2 : 0) | (e.excludeKinematic ? 4 : 0) | (e.excludeDynamic ? 8 : 0), t.u[2] = q, t.u[3] = e.exclude && this.bodies.has(e.exclude) ? e.exclude.handle : q;
2377
+ }
2378
+ hitOf(e, t) {
2379
+ let n = this.byShape.get(e);
2380
+ if (!n || n === t?.excludeCollider) return null;
2381
+ let r = n.body;
2382
+ return t?.predicate && t.predicate(r, n) === !1 ? null : {
2383
+ body: r,
2384
+ sprite: r.sprite,
2385
+ collider: n
2386
+ };
2387
+ }
2388
+ raycast(e, t, n = {}) {
2389
+ return this.rayHits(e, t, n, !0)[0] ?? null;
2390
+ }
2391
+ raycastAll(e, t, n = {}) {
2392
+ return this.rayHits(e, t, n, !1);
2393
+ }
2394
+ rayHits(e, t, n, r) {
2395
+ this.live(), this.checkVec(e, "Ray2D origin"), this.checkVec(t, "Ray2D direction");
2396
+ let i = Math.hypot(t[0], t[1]);
2397
+ if (!(i > 0)) throw RangeError("Ray2D direction must not be zero; pass a direction such as [0, 1].");
2398
+ let a = this.scale, o = t[0] / i, s = t[1] / i;
2399
+ this.writeFilter(n);
2400
+ let c = this.kernel.io(16);
2401
+ c.f.set([
2402
+ e[0] * a,
2403
+ e[1] * a,
2404
+ o,
2405
+ s,
2406
+ Math.min((n.maxDistance ?? 1e9) * a, 3e38)
2407
+ ], 4), c.u[9] = n.solid ?? !0 ? 1 : 0;
2408
+ let l = this.kernel.ok(this.kernel.exports.ray_cast(this.handle)), u = this.kernel.io(4 * l), d = [];
2409
+ for (let t = 0; t < l; t++) {
2410
+ let i = this.hitOf(u.u[4 * t], n);
2411
+ if (!i) continue;
2412
+ let c = u.f[4 * t + 1] / a;
2413
+ if (d.push({
2414
+ ...i,
2415
+ distance: c,
2416
+ point: [e[0] + o * c, e[1] + s * c],
2417
+ normal: [u.f[4 * t + 2] + 0, u.f[4 * t + 3] + 0]
2418
+ }), r) break;
2419
+ }
2420
+ return d;
2421
+ }
2422
+ overlapPoint(e, t) {
2423
+ this.live(), this.checkVec(e, "Point"), this.writeFilter(t), this.kernel.io(8).f.set([e[0] * this.scale, e[1] * this.scale], 4);
2424
+ let n = this.kernel.ok(this.kernel.exports.point_query(this.handle));
2425
+ return this.bodiesOf(this.kernel.io(n).u, n, t);
2426
+ }
2427
+ bodiesOf(e, t, n) {
2428
+ let r = /* @__PURE__ */ new Set();
2429
+ for (let i = 0; i < t; i++) {
2430
+ let t = this.hitOf(e[i], n);
2431
+ t && r.add(t.body);
2432
+ }
2433
+ return [...r];
2434
+ }
2435
+ overlapShape(e, t, n = 0, r) {
2436
+ this.live(), this.checkVec(t, "Shape2D position");
2437
+ let i = this.queryShape(e);
2438
+ this.writeFilter(r);
2439
+ let a = this.kernel.io(8 + i.geometry.length);
2440
+ a.f.set([
2441
+ t[0] * this.scale,
2442
+ t[1] * this.scale,
2443
+ Math.cos(n),
2444
+ Math.sin(n)
2445
+ ], 4), a.u.set(i.geometry, 8);
2446
+ let o = this.kernel.ok(this.kernel.exports.shape_overlap(this.handle, i.kind));
2447
+ return this.bodiesOf(this.kernel.io(o).u, o, r);
2448
+ }
2449
+ queryShape(e) {
2450
+ let t = S(e, this.scale);
2451
+ if (t.kind > 4 || !t.convex) throw RangeError("A query shape must be a box, circle, capsule, segment or a convex polygon of at most 8 points.");
2452
+ return t;
2453
+ }
2454
+ castShape(e, t, n, r, i, a = 0, o = {}) {
2455
+ if (this.live(), this.checkVec(t, "Shape2D position"), this.checkVec(n, "Shape2D direction"), o.targetDistance !== void 0 && !(o.targetDistance >= 0 && o.targetDistance < Infinity)) throw RangeError(`targetDistance must be a finite number of 0 or more; got ${o.targetDistance}.`);
2456
+ let s = Math.hypot(n[0], n[1]);
2457
+ if (!(s > 0)) throw RangeError("Shape2D direction must not be zero; pass a direction such as [0, 1].");
2458
+ let c = this.queryShape(e);
2459
+ return this.cast(c, t[0] * this.scale, t[1] * this.scale, a, n[0] / s, n[1] / s, r * this.scale, i, o);
2460
+ }
2461
+ cast(e, t, n, r, i, a, o, s, c = {}) {
2462
+ this.writeFilter(s);
2463
+ let l = this.kernel.io(13 + e.geometry.length);
2464
+ l.f.set([
2465
+ t,
2466
+ n,
2467
+ Math.cos(r),
2468
+ Math.sin(r),
2469
+ i,
2470
+ a,
2471
+ Math.min(o, 3e38),
2472
+ (c.targetDistance ?? 0) * this.scale
2473
+ ], 4), l.u[12] = c.stopAtPenetration === !1 ? 0 : 1, l.u.set(e.geometry, 13);
2474
+ let u = this.kernel.ok(this.kernel.exports.shape_cast(this.handle, e.kind)), d = this.kernel.io(9 * u), f = 1 / this.scale;
2475
+ for (let e = 0; e < u; e++) {
2476
+ let t = this.hitOf(d.u[9 * e], s);
2477
+ if (!t) continue;
2478
+ let n = d.f, r = n[9 * e + 8] * f, i = n[9 * e + 1] * f;
2479
+ return {
2480
+ ...t,
2481
+ distance: i,
2482
+ point: [n[9 * e + 4] * f, n[9 * e + 5] * f],
2483
+ normal: [0 - n[9 * e + 6], 0 - n[9 * e + 7]],
2484
+ witnessA: [n[9 * e + 2] * f, n[9 * e + 3] * f],
2485
+ witnessB: [n[9 * e + 4] * f, n[9 * e + 5] * f],
2486
+ normalA: [n[9 * e + 6], n[9 * e + 7]],
2487
+ normalB: [0 - n[9 * e + 6], 0 - n[9 * e + 7]],
2488
+ gap: r,
2489
+ status: i === 0 ? "penetrating" : "converged"
2490
+ };
2491
+ }
2492
+ return null;
2493
+ }
2494
+ snapshot() {
2495
+ this.live();
2496
+ let { kernel: e } = this, t = e.ok(e.exports.world_snapshot(this.handle)), n = e.io(Math.ceil(t / 4)).u, r = new Uint8Array(n.buffer.slice(n.byteOffset, n.byteOffset + t)), i = [...this.bodies].map((e) => [e.handle, e.colliders.map((e) => e.shapes)]), a = new TextEncoder().encode(JSON.stringify({
2497
+ gravity: this.gravityValue,
2498
+ bodies: i,
2499
+ joints: [...this.joints].map((e) => e.handle),
2500
+ extra: [...this.bodies].map((e) => e.additionalMass)
2501
+ })), o = new Uint8Array(8 + a.length + r.length);
2502
+ return new DataView(o.buffer).setUint32(0, 1346646611, !0), new DataView(o.buffer).setUint32(4, a.length, !0), o.set(a, 8), o.set(r, 8 + a.length), o;
2503
+ }
2504
+ restore(t) {
2505
+ this.live();
2506
+ let n = new DataView(t.buffer, t.byteOffset, t.byteLength);
2507
+ if (t.byteLength < 8 || n.getUint32(0, !0) !== 1346646611 || 8 + n.getUint32(4, !0) > t.byteLength) throw RangeError("Physics2D.restore needs the bytes Physics2D.snapshot returned.");
2508
+ let r = n.getUint32(4, !0), i = JSON.parse(new TextDecoder().decode(t.subarray(8, 8 + r)));
2509
+ if (JSON.stringify([...this.bodies].map((e) => [e.handle, e.colliders.map((e) => e.shapes)])) !== JSON.stringify(i.bodies) || JSON.stringify([...this.joints].map((e) => e.handle)) !== JSON.stringify(i.joints)) throw new e("state", "Physics2D.restore: bodies, colliders or joints were added or removed since the snapshot; restore it before changing them, or take a new snapshot.");
2510
+ let a = t.subarray(8 + r), { kernel: o } = this, s = o.io(Math.ceil(a.length / 4));
2511
+ new Uint8Array(s.u.buffer, s.u.byteOffset, a.length).set(a), o.ok(o.exports.world_restore(this.handle, a.length)), this.gravityValue = [i.gravity[0], i.gravity[1]], this.accumulator = 0;
2512
+ let c = 0;
2513
+ for (let e of this.bodies) e.snapshot(), e.pose.copyWithin(0, 3, 6), e.dirty = !0, e.restoreAdditionalMass(i.extra[c++] ?? 0);
2514
+ this.resyncTouchingPairs();
2515
+ }
2516
+ resyncTouchingPairs() {
2517
+ this.touchingPairs.clear(), this.carriedPairs.clear();
2518
+ for (let [e, t] of this.byShape) {
2519
+ let n = this.kernel.ok(this.kernel.exports.contacts_of(this.handle, e)), { u: r } = this.kernel.io(K * n);
2520
+ for (let i = 0; i < n; i++) {
2521
+ let n = r[K * i];
2522
+ if (e >= n || !(r[K * i + 1] & 2)) continue;
2523
+ let a = this.byShape.get(n);
2524
+ if (!a || a === t) continue;
2525
+ let o = this.pairKey(t, a), s = this.touchingPairs.get(o);
2526
+ s ? s.count++ : this.touchingPairs.set(o, {
2527
+ count: 1,
2528
+ sensor: t.isSensor() || a.isSensor(),
2529
+ a: t,
2530
+ b: a
2531
+ });
2532
+ }
2533
+ }
2534
+ }
2535
+ debugRender(e = {}) {
2536
+ this.live();
2537
+ let { style: t, filter: n, ...r } = e, i = Object.keys(r).length === 0, a = (i || r.shapes ? 1 : 0) | (i || r.joints ? 2 : 0) | (i || r.contacts ? 4 : 0) | (i || r.boxes ? 8 : 0) | (r.axes ? 16 : 0) | (r.solverContacts ? 32 : 0), { kernel: o } = this, s = [];
2538
+ if (n) for (let e of this.bodies) n(e) || s.push(e.handle);
2539
+ o.io(Math.max(s.length, 1)).u.set(s, 0);
2540
+ let c = o.ok(o.exports.debug_lines(this.handle, a, s.length)), l = o.io(5 * c).f, u = 1 / this.scale, d = new Float32Array(4 * c), f = new Uint8Array(c), p = new Float32Array(4 * c);
2541
+ for (let e = 0; e < c; e++) {
2542
+ for (let t = 0; t < 4; t++) d[4 * e + t] = l[5 * e + t] * u;
2543
+ f[e] = l[5 * e + 4], p.set(t?.[H[f[e]]] ?? U[H[f[e]]], 4 * e);
2544
+ }
2545
+ return {
2546
+ vertices: d,
2547
+ colors: f,
2548
+ rgba: p
2549
+ };
2550
+ }
2551
+ on(e, t) {
2552
+ if (this.disposed) return W;
2553
+ let n = this.listeners.get(e);
2554
+ n || this.listeners.set(e, n = /* @__PURE__ */ new Set());
2555
+ let r = n;
2556
+ if (r.add(t), (e === "sleep" || e === "wake") && !this.asleep) {
2557
+ this.asleep = /* @__PURE__ */ new Map();
2558
+ for (let e of this.bodies) e.type === "dynamic" && this.asleep.set(e, e.sleeping);
2559
+ }
2560
+ return () => {
2561
+ r.delete(t);
2562
+ };
2563
+ }
2564
+ sleepEvents(e) {
2565
+ if (!this.listeners.get("sleep")?.size && !this.listeners.get("wake")?.size) {
2566
+ this.asleep = null;
2567
+ return;
2568
+ }
2569
+ let t = this.asleep;
2570
+ for (let n of this.bodies) {
2571
+ if (n.type !== "dynamic") continue;
2572
+ let r = n.sleeping, i = t.get(n);
2573
+ i !== void 0 && i !== r && e.push([r ? "sleep" : "wake", { body: n }]), t.set(n, r);
2574
+ }
2575
+ for (let e of t.keys()) this.bodies.has(e) || t.delete(e);
2576
+ }
2577
+ emit(e, t) {
2578
+ this.listeners.get(e)?.forEach(te, t);
2579
+ }
2580
+ dispose() {
2581
+ if (this.disposed) return;
2582
+ let e = this.engine, t = e && !e.disposed ? e.sceneOf(this) : void 0;
2583
+ if (t) try {
2584
+ t.removePlugin(this.name);
2585
+ return;
2586
+ } catch {}
2587
+ for (let e of [...this.controllers]) e.dispose();
2588
+ for (let e of [...this.joints]) this.removeJoint(e);
2589
+ for (let e of [...this.bodies]) this.removeBody(e);
2590
+ this.listeners.clear(), this.kernel.exports.world_destroy(this.handle), this.disposed = !0, this.engine = null;
2591
+ }
2592
+ };
2593
+ Q.prototype[Symbol.dispose] = Q.prototype.dispose;
2594
+ function ne(e) {
2595
+ if (!e?.rect) return;
2596
+ let t = Math.abs(e.rect[2] * (e.scaleX ?? 1)), n = Math.abs(e.rect[3] * (e.scaleY ?? 1));
2597
+ if (t > 0 && n > 0) return {
2598
+ shape: "box",
2599
+ width: t,
2600
+ height: n,
2601
+ offset: [(.5 - (e.pivotX ?? 0)) * t, (.5 - (e.pivotY ?? 0)) * n]
2602
+ };
2603
+ }
2604
+ //#endregion
2605
+ //#region src/pid.ts
2606
+ var $ = (e, t) => {
2607
+ if (!Number.isFinite(e)) throw RangeError(`${t} must be a finite number, got ${e}; fix the value.`);
2608
+ return e;
2609
+ }, re = class {
2610
+ constructor({ kp: e = 1, ki: t = 0, kd: n = 0 } = {}) {
2611
+ this.axes = [!0, !0], this.sum = [0, 0], this.angleSum = 0, this.kp = $(e, "kp"), this.ki = $(t, "ki"), this.kd = $(n, "kd");
2612
+ }
2613
+ reset() {
2614
+ return this.sum = [0, 0], this.angleSum = 0, this;
2615
+ }
2616
+ linearCorrection(e, t, n, r = [0, 0]) {
2617
+ if (!(e > 0) || !Number.isFinite(e)) throw RangeError(`dt must be a finite number of seconds above 0, got ${e}.`);
2618
+ let i = t.position, a = t.linearVelocity, o = [0, 0];
2619
+ for (let t = 0; t < 2; t++) {
2620
+ if (!this.axes[t]) continue;
2621
+ let s = $(n[t], "target") - i[t];
2622
+ this.sum[t] += s * e, o[t] = this.kp * s + this.ki * this.sum[t] + this.kd * ($(r[t], "targetVelocity") - a[t]);
2623
+ }
2624
+ return o;
2625
+ }
2626
+ applyLinear(e, t, n, r = [0, 0]) {
2627
+ let i = this.linearCorrection(e, t, n, r), a = t.linearVelocity;
2628
+ return t.linearVelocity = [a[0] + i[0] * e, a[1] + i[1] * e], this;
2629
+ }
2630
+ angularCorrection(e, t, n, r = 0) {
2631
+ if (!(e > 0) || !Number.isFinite(e)) throw RangeError(`dt must be a finite number of seconds above 0, got ${e}.`);
2632
+ let i = ($(n, "target") - t.rotation) % (2 * Math.PI);
2633
+ return i > Math.PI ? i -= 2 * Math.PI : i < -Math.PI && (i += 2 * Math.PI), this.angleSum += i * e, this.kp * i + this.ki * this.angleSum + this.kd * ($(r, "targetVelocity") - t.angularVelocity);
2634
+ }
2635
+ applyAngular(e, t, n, r = 0) {
2636
+ return t.angularVelocity += this.angularCorrection(e, t, n, r) * e, this;
2637
+ }
2638
+ };
2639
+ //#endregion
2640
+ export { M as Articulation2D, A as Body2D, F as CharacterController2D, v as CoefficientCombineRule2D, k as Collider2D, z as Joint2D, Q as Physics2D, re as PidController2D, m as interactionGroups, f as tileMapColliders };