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