@margoengine/input 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/motion.js ADDED
@@ -0,0 +1,98 @@
1
+ //#region src/motion.ts
2
+ var e = Math.PI / 180, t = .1, n = .2, r = (e) => Math.max(-1, Math.min(1, e)), i = (e) => Math.atan2(Math.sin(e), Math.cos(e)), a = class {
3
+ constructor({ target: r = window, maxRate: i = 180, maxTilt: a = 45, deadzone: o = 1, screenAngle: s = () => globalThis.screen?.orientation?.angle ?? 0, now: c = () => performance.now() } = {}) {
4
+ if (this.yaw = 0, this.pitch = 0, this.roll = 0, this.steer = 0, this.enabled = !0, this.available = !1, this.hosts = /* @__PURE__ */ new Map(), this.bias = {
5
+ alpha: 0,
6
+ beta: 0,
7
+ gamma: 0
8
+ }, this.pending = {
9
+ yaw: 0,
10
+ pitch: 0,
11
+ roll: 0
12
+ }, this.neutral = 0, this.tilt = 0, this.disposed = !1, this.onMotion = (n) => {
13
+ let r = n.rotationRate, i = this.now(), a = this.lastEvent;
14
+ if (this.lastEvent = i, !r || r.alpha === null && r.beta === null && r.gamma === null) return;
15
+ this.available = !0;
16
+ let o = {
17
+ alpha: r.alpha ?? 0,
18
+ beta: r.beta ?? 0,
19
+ gamma: r.gamma ?? 0
20
+ };
21
+ if (this.calibration && (this.calibration.alpha += o.alpha, this.calibration.beta += o.beta, this.calibration.gamma += o.gamma, this.calibration.count++), !this.enabled) return;
22
+ let s = a === void 0 ? 1 / 60 : Math.min((i - a) / 1e3, t), c = this.screenAngle() * e, l = Math.sin(c), u = Math.cos(c), d = o.alpha - this.bias.alpha, f = o.beta - this.bias.beta, p = o.gamma - this.bias.gamma;
23
+ this.pending.yaw -= this.gated(l * d + u * f) * s * e, this.pending.pitch += this.gated(u * d - l * f) * s * e, this.pending.roll -= this.gated(p) * s * e;
24
+ }, this.onOrientation = (t) => {
25
+ let { beta: r, gamma: i } = t;
26
+ if (r === null || i === null || r === void 0 || i === void 0) return;
27
+ let a = r * e, o = i * e, s = -Math.cos(a) * Math.sin(o), c = Math.sin(a), l = this.screenAngle() * e, u = Math.cos(l) * s - Math.sin(l) * c, d = Math.sin(l) * s + Math.cos(l) * c;
28
+ this.tilt = Math.hypot(u, d) < n ? this.neutral : -Math.atan2(u, d);
29
+ }, !(i > 0) || !(a > 0) || !(o >= 0) || !Number.isFinite(i + a + o)) throw RangeError("Invalid Gyro options; maxRate and maxTilt are above 0 and deadzone is at least 0");
30
+ this.target = r, this.maxRate = i, this.maxTilt = a * e, this.deadzone = o, this.screenAngle = s, this.now = c, this.lastUpdate = c(), r.addEventListener("devicemotion", this.onMotion), r.addEventListener("deviceorientation", this.onOrientation);
31
+ }
32
+ static supported() {
33
+ return typeof globalThis.DeviceMotionEvent == "function";
34
+ }
35
+ static async requestPermission() {
36
+ let e = globalThis.DeviceMotionEvent, t = globalThis.DeviceOrientationEvent;
37
+ return e ? (await Promise.all([e.requestPermission?.(), t?.requestPermission?.()])).every((e) => e === void 0 || e === "granted") : !1;
38
+ }
39
+ attach(e, t = "gyro") {
40
+ this.detach(e), this.hosts.set(e, {
41
+ id: t,
42
+ values: e.control(t)
43
+ });
44
+ }
45
+ detach(e) {
46
+ let t = this.hosts.get(e);
47
+ t && e.removeControl(t.id), this.hosts.delete(e);
48
+ }
49
+ update() {
50
+ let t = this.now(), n = (t - this.lastUpdate) / 1e3, { yaw: a, pitch: o, roll: s } = this.pending;
51
+ this.lastUpdate = t, this.pending = {
52
+ yaw: 0,
53
+ pitch: 0,
54
+ roll: 0
55
+ }, this.yaw = a, this.pitch = o, this.roll = s, this.steer = this.enabled ? r(i(this.tilt - this.neutral) / this.maxTilt) : 0;
56
+ let c = n > 0 ? 1 / (n * this.maxRate * e) : 0;
57
+ for (let { values: e } of this.hosts.values()) e.yaw = r(a * c), e.pitch = r(o * c), e.roll = r(s * c), e.steer = this.steer;
58
+ }
59
+ recenter() {
60
+ this.neutral = this.tilt;
61
+ }
62
+ calibrate({ duration: e = 1e3, signal: t } = {}) {
63
+ return new Promise((n, r) => {
64
+ if (!(e >= 0)) return r(/* @__PURE__ */ RangeError("Gyro calibrate duration must be in milliseconds, at least 0"));
65
+ if (t?.aborted) return r(t.reason ?? new DOMException("Aborted", "AbortError"));
66
+ let i = this.calibration = {
67
+ alpha: 0,
68
+ beta: 0,
69
+ gamma: 0,
70
+ count: 0
71
+ }, a = () => {
72
+ clearTimeout(o), this.stopCalibration = void 0, this.calibration === i && (this.calibration = void 0), r(t?.reason ?? new DOMException("Aborted", "AbortError"));
73
+ };
74
+ this.stopCalibration = () => {
75
+ clearTimeout(o), t?.removeEventListener("abort", a), this.stopCalibration = void 0, this.calibration === i && (this.calibration = void 0), n(!1);
76
+ };
77
+ let o = setTimeout(() => {
78
+ if (this.stopCalibration = void 0, t?.removeEventListener("abort", a), this.calibration !== i || (this.calibration = void 0, !i.count)) return n(!1);
79
+ this.bias.alpha += i.alpha / i.count, this.bias.beta += i.beta / i.count, this.bias.gamma += i.gamma / i.count, n(!0);
80
+ }, e);
81
+ t?.addEventListener("abort", a, { once: !0 });
82
+ });
83
+ }
84
+ dispose() {
85
+ if (!this.disposed) {
86
+ this.disposed = !0, this.stopCalibration?.(), this.target.removeEventListener("devicemotion", this.onMotion), this.target.removeEventListener("deviceorientation", this.onOrientation);
87
+ for (let e of [...this.hosts.keys()]) this.detach(e);
88
+ }
89
+ }
90
+ [Symbol.dispose ?? Symbol()]() {
91
+ this.dispose();
92
+ }
93
+ gated(e) {
94
+ return Math.abs(e) < this.deadzone ? 0 : e;
95
+ }
96
+ };
97
+ //#endregion
98
+ export { a as Gyro };
package/dist/pen.d.ts ADDED
@@ -0,0 +1,86 @@
1
+ import type { ControlHost } from './motion.js';
2
+ /** One reading of the pen. */
3
+ export interface PenSample {
4
+ /** Position in CSS pixels, relative to the viewport. */
5
+ x: number;
6
+ y: number;
7
+ /** Tip pressure, 0 to 1, after `curve`. 0 while hovering. */
8
+ pressure: number;
9
+ /** Lean toward the right and toward the user, in degrees, -90 to 90. */
10
+ tiltX: number;
11
+ tiltY: number;
12
+ /** Radians above the surface: pi / 2 upright, 0 lying flat. */
13
+ altitude: number;
14
+ /** Radians around the surface from the positive x axis, clockwise on screen, 0 to 2 pi. */
15
+ azimuth: number;
16
+ /** Turn about the pen's own axis in degrees, 0 to 359. */
17
+ twist: number;
18
+ /** Barrel wheel or finger pressure, -1 to 1, on the pens that have one. */
19
+ tangential: number;
20
+ /** True while the tip or the eraser touches. */
21
+ down: boolean;
22
+ /** True while the barrel button is held. */
23
+ barrel: boolean;
24
+ /** True while the pen is turned over to its eraser. */
25
+ eraser: boolean;
26
+ /** Event time in milliseconds, on the clock of `performance.now`. */
27
+ time: number;
28
+ }
29
+ /** Options for {@link Pen}. */
30
+ export interface PenOptions {
31
+ /** Shapes pressure, from 0 to 1 and back into 0 to 1, for a softer or firmer feel. Default none. */
32
+ curve?: (pressure: number) => number;
33
+ /** Most samples kept between {@link Pen.take} calls; the oldest go first. Default 4096. */
34
+ maxSamples?: number;
35
+ }
36
+ /**
37
+ * Pen pressure and tilt, as action values and as a full-rate sample stream for painting and sculpting. Mouse and touch
38
+ * are ignored. Attach it to an `Input` and bind actions to `{ type: 'control', id: 'pen', axis: 'pressure' }`, and
39
+ * likewise `tiltX`, `tiltY` (-1 to 1), `altitude` (0 flat to 1 upright), `azimuth` and `twist` (share of a full turn,
40
+ * 0 to 1), `tangential` (-1 to 1), `down`, `barrel`, `eraser` and `hover` (0 or 1).
41
+ *
42
+ * ```ts
43
+ * const pen = new Pen(canvas);
44
+ * pen.attach(input);
45
+ * pen.update(); // once per tick, before input.update()
46
+ * input.update();
47
+ * for (const sample of pen.take()) brush(sample.x, sample.y, sample.pressure);
48
+ * ```
49
+ *
50
+ * Set `touch-action: none` on the element so the browser does not claim the stroke.
51
+ */
52
+ export declare class Pen {
53
+ /** The latest reading, or undefined before the pen has been seen. */
54
+ latest: PenSample | undefined;
55
+ /** True while the pen is within reach of the element, touching or hovering. */
56
+ inRange: boolean;
57
+ private readonly element;
58
+ private readonly curve;
59
+ private readonly maxSamples;
60
+ private readonly hosts;
61
+ private samples;
62
+ /** Touched since the last update, so a dab between two updates still counts for one update. */
63
+ private dabbed;
64
+ private disposed;
65
+ /** @throws RangeError for a `maxSamples` that is not an integer >= 1. */
66
+ constructor(element: EventTarget, { curve, maxSamples }?: PenOptions);
67
+ /** Publish to `input` as control `id`, for `{ type: 'control', id, axis }` bindings. Default id `'pen'`. */
68
+ attach(input: ControlHost, id?: string): void;
69
+ /** Stop publishing to `input` and remove the control. */
70
+ detach(input: ControlHost): void;
71
+ /** Publish the latest reading to every attached `Input`. Call once per tick, before `input.update()`. */
72
+ update(): void;
73
+ /**
74
+ * Every reading since the last call, oldest first, at the pen's own rate: the browser's coalesced events are
75
+ * unpacked, so a stroke keeps the points between two frames. A sample with `down` false after true ends a stroke.
76
+ */
77
+ take(): PenSample[];
78
+ /** Stop listening and remove the controls. Idempotent. */
79
+ dispose(): void;
80
+ [Symbol.dispose]: () => void;
81
+ private push;
82
+ private read;
83
+ private readonly onPointer;
84
+ private readonly onEnd;
85
+ private readonly onLeave;
86
+ }
package/dist/pen.js ADDED
@@ -0,0 +1,111 @@
1
+ //#region src/pen.ts
2
+ var e = Math.PI / 2, t = Math.PI * 2, n = Math.PI / 180;
3
+ function r(r, i) {
4
+ if (Math.abs(r) >= 90 || Math.abs(i) >= 90) {
5
+ if (r !== 0 && i !== 0) return [0, 0];
6
+ let e = Math.atan2(Math.abs(i) >= 90 ? Math.sign(i) : 0, Math.abs(r) >= 90 ? Math.sign(r) : 0);
7
+ return [0, e < 0 ? e + t : e];
8
+ }
9
+ let a = Math.tan(r * n), o = Math.tan(i * n), s = Math.hypot(a, o);
10
+ if (!s) return [e, 0];
11
+ let c = Math.atan2(o, a);
12
+ return [Math.atan2(1, s), c < 0 ? c + t : c];
13
+ }
14
+ function i(r, i) {
15
+ if (r === 0) {
16
+ let n = i >= t ? i - t : i, r = 3 * Math.PI / 2;
17
+ return [n === e || n === r ? 0 : n < e || n > r ? 90 : -90, n === 0 || n === Math.PI ? 0 : n < Math.PI ? 90 : -90];
18
+ }
19
+ let a = 1 / Math.tan(r);
20
+ return [Math.atan(Math.cos(i) * a) / n, Math.atan(Math.sin(i) * a) / n];
21
+ }
22
+ var a = class {
23
+ constructor(e, { curve: t, maxSamples: n = 4096 } = {}) {
24
+ if (this.inRange = !1, this.hosts = /* @__PURE__ */ new Map(), this.samples = [], this.dabbed = !1, this.disposed = !1, this.onPointer = (e) => {
25
+ let t = e;
26
+ if (t.pointerType !== "pen") return;
27
+ this.inRange = !0, t.type === "pointerdown" && t.target?.setPointerCapture?.(t.pointerId);
28
+ let n = t.type === "pointermove" ? t.getCoalescedEvents?.() : void 0;
29
+ for (let e of n?.length ? n : [t]) this.push(this.read(e));
30
+ this.latest?.down && (this.dabbed = !0);
31
+ }, this.onEnd = (e) => {
32
+ e.pointerType === "pen" && (this.latest?.down && this.push({
33
+ ...this.latest,
34
+ pressure: 0,
35
+ down: !1,
36
+ barrel: !1,
37
+ tangential: 0
38
+ }), this.inRange = !1);
39
+ }, this.onLeave = (e) => {
40
+ e.pointerType === "pen" && !this.latest?.down && (this.inRange = !1);
41
+ }, !Number.isInteger(n) || n < 1) throw RangeError("Pen maxSamples must be an integer of at least 1");
42
+ if (t !== void 0 && typeof t != "function") throw TypeError("Pen curve must be a function");
43
+ this.element = e, this.curve = t, this.maxSamples = n;
44
+ for (let t of [
45
+ "pointerdown",
46
+ "pointermove",
47
+ "pointerup"
48
+ ]) e.addEventListener(t, this.onPointer);
49
+ e.addEventListener("pointercancel", this.onEnd), e.addEventListener("pointerleave", this.onLeave);
50
+ }
51
+ attach(e, t = "pen") {
52
+ this.detach(e), this.hosts.set(e, {
53
+ id: t,
54
+ values: e.control(t)
55
+ });
56
+ }
57
+ detach(e) {
58
+ let t = this.hosts.get(e);
59
+ t && e.removeControl(t.id), this.hosts.delete(e);
60
+ }
61
+ update() {
62
+ let n = this.latest, r = this.inRange ? n : void 0, i = !!r?.down || this.dabbed;
63
+ this.dabbed = !1;
64
+ for (let { values: n } of this.hosts.values()) n.pressure = r?.pressure ?? 0, n.tiltX = (r?.tiltX ?? 0) / 90, n.tiltY = (r?.tiltY ?? 0) / 90, n.altitude = r ? r.altitude / e : 0, n.azimuth = (r?.azimuth ?? 0) / t, n.twist = (r?.twist ?? 0) / 360, n.tangential = r?.tangential ?? 0, n.down = +i, n.barrel = +!!r?.barrel, n.eraser = +!!r?.eraser, n.hover = +(this.inRange && !r?.down);
65
+ }
66
+ take() {
67
+ let e = this.samples;
68
+ return this.samples = [], e;
69
+ }
70
+ dispose() {
71
+ if (!this.disposed) {
72
+ this.disposed = !0;
73
+ for (let e of [
74
+ "pointerdown",
75
+ "pointermove",
76
+ "pointerup"
77
+ ]) this.element.removeEventListener(e, this.onPointer);
78
+ this.element.removeEventListener("pointercancel", this.onEnd), this.element.removeEventListener("pointerleave", this.onLeave);
79
+ for (let e of [...this.hosts.keys()]) this.detach(e);
80
+ this.inRange = !1;
81
+ }
82
+ }
83
+ [Symbol.dispose ?? Symbol()]() {
84
+ this.dispose();
85
+ }
86
+ push(e) {
87
+ this.latest = e, this.samples.push(e), this.samples.length > this.maxSamples && this.samples.shift();
88
+ }
89
+ read(e) {
90
+ let t = e.tiltX || 0, n = e.tiltY || 0, a = e.altitudeAngle, o = e.azimuthAngle;
91
+ a === void 0 || o === void 0 ? [a, o] = r(t, n) : !t && !n && ([t, n] = i(a, o));
92
+ let s = Math.max(0, Math.min(1, e.pressure || 0)), c = s > 0 && this.curve ? this.curve(s) : s, l = !!(e.buttons & 32) || e.button === 5;
93
+ return {
94
+ x: e.clientX,
95
+ y: e.clientY,
96
+ pressure: Number.isFinite(c) ? Math.max(0, Math.min(1, c)) : s,
97
+ tiltX: t,
98
+ tiltY: n,
99
+ altitude: a,
100
+ azimuth: o,
101
+ twist: e.twist || 0,
102
+ tangential: e.tangentialPressure || 0,
103
+ down: !!(e.buttons & 33),
104
+ barrel: !!(e.buttons & 2),
105
+ eraser: l,
106
+ time: e.timeStamp
107
+ };
108
+ }
109
+ };
110
+ //#endregion
111
+ export { a as Pen };
@@ -0,0 +1,129 @@
1
+ import { Input, type Binding, type InputOptions } from './index.js';
2
+ /**
3
+ * A device a player can own, and one player at a time does:
4
+ * - `'keyboard'`: the key, mouse and pointer bindings of the actions.
5
+ * - `'keyboard:<scheme>'`: the bindings of that entry of the `schemes` option, for two players on one keyboard.
6
+ * - `'gamepad:<n>'`: the gamepad bindings of the actions, pointed at gamepad `n`.
7
+ * - `'touch'`: the touch bindings of the actions.
8
+ * - `'control:<id>'`: the bindings of the actions to that control, such as a `Gyro` attached to this player's `Input`.
9
+ */
10
+ export type PlayerDevice = 'keyboard' | 'touch' | `keyboard:${string}` | `gamepad:${number}` | `control:${string}`;
11
+ /** What a {@link LocalPlayers} handler hears. */
12
+ export type PlayerEventType = 'join' | 'leave' | 'lost' | 'regained';
13
+ /** One event of {@link LocalPlayers}. */
14
+ export interface PlayerEvent {
15
+ type: PlayerEventType;
16
+ player: Player;
17
+ /** The device that joined, or that was lost or came back. Absent when `add` had no device, and on `leave`. */
18
+ device?: PlayerDevice;
19
+ }
20
+ /** Options for {@link LocalPlayers}. `target`, `gamepads`, `deadzone` and `contexts` go to every player's `Input`. */
21
+ export interface LocalPlayersOptions extends InputOptions {
22
+ /** Most players at once, an integer >= 1. Default 4. */
23
+ maxPlayers?: number;
24
+ /**
25
+ * Keyboard layouts for players sharing a keyboard, by name: action to bindings. Device `'keyboard:<name>'` uses them
26
+ * in place of the actions' own key bindings. Default none.
27
+ */
28
+ schemes?: Readonly<Record<string, Readonly<Record<string, readonly Binding[]>>>>;
29
+ /**
30
+ * An action whose press on a device nobody owns adds a player on that device, for a "press Start to join" screen.
31
+ * Default none: only {@link LocalPlayers.add} adds players.
32
+ */
33
+ joinAction?: string;
34
+ /** Gamepad indices `joinAction` watches, from 0. An integer >= 1. Default 4. */
35
+ gamepadSlots?: number;
36
+ }
37
+ /** One local player. Read `input` as any `Input`: state, contexts, rebinding and touch controls are this player's own. */
38
+ export declare class Player {
39
+ /** Slot number from 0, kept for as long as the player stays: player 1 is still 1 when player 0 leaves. */
40
+ readonly index: number;
41
+ /** This player's actions, reading only this player's devices. */
42
+ readonly input: Input;
43
+ /** @internal */
44
+ readonly owned: Set<PlayerDevice>;
45
+ /** @internal */
46
+ readonly missing: Set<PlayerDevice>;
47
+ /** @internal */
48
+ constructor(
49
+ /** Slot number from 0, kept for as long as the player stays: player 1 is still 1 when player 0 leaves. */
50
+ index: number,
51
+ /** This player's actions, reading only this player's devices. */
52
+ input: Input);
53
+ /** The devices this player owns. */
54
+ get devices(): readonly PlayerDevice[];
55
+ /** False while a gamepad of this player is unplugged. */
56
+ get connected(): boolean;
57
+ /**
58
+ * Rumble this player's gamepads. Resolves false when none has a vibration actuator.
59
+ * @param duration Milliseconds, in [0, 10000].
60
+ * @param strength Magnitude in [0, 1]. Default 1.
61
+ */
62
+ rumble(duration: number, strength?: number): Promise<boolean>;
63
+ }
64
+ /**
65
+ * Local multiplayer: each player owns devices and has an `Input` of their own, made from one shared action map.
66
+ *
67
+ * ```ts
68
+ * const party = new LocalPlayers(actions, { joinAction: 'start' });
69
+ * party.on('join', ({ player }) => spawn(player));
70
+ * party.update(); // once per tick
71
+ * for (const player of party.players) move(player.index, player.input.state('move').value);
72
+ * ```
73
+ */
74
+ export declare class LocalPlayers {
75
+ private readonly actions;
76
+ private readonly schemes;
77
+ private readonly options;
78
+ private readonly maxPlayers;
79
+ private readonly slots;
80
+ private readonly owners;
81
+ private readonly handlers;
82
+ private readonly gamepads;
83
+ private lobby;
84
+ private disposed;
85
+ /**
86
+ * @throws RangeError for a `maxPlayers` or `gamepadSlots` that is not an integer >= 1.
87
+ * @throws TypeError for a `joinAction` or scheme action that is not an action, or an invalid binding.
88
+ */
89
+ constructor(actions: Readonly<Record<string, readonly Binding[]>>, { maxPlayers, schemes, joinAction, gamepadSlots, target, gamepads, deadzone, contexts, }?: LocalPlayersOptions);
90
+ /** Current players, in slot order. */
91
+ get players(): readonly Player[];
92
+ /** The player who owns `device`, if any. */
93
+ owner(device: PlayerDevice): Player | undefined;
94
+ /** Listen for `join`, `leave`, `lost` or `regained`; returns the function that stops listening. */
95
+ on(type: PlayerEventType, handler: (event: PlayerEvent) => void): () => void;
96
+ /**
97
+ * Add a player in the lowest free slot, with `device` if given. The press that made them join does not read as
98
+ * `pressed`, so a Start button that is also an action does nothing on arrival.
99
+ * @throws RangeError when `maxPlayers` are already playing.
100
+ * @throws TypeError for an unknown device or one another player owns.
101
+ * @throws MargoError `'disposed'` after {@link LocalPlayers.dispose}.
102
+ */
103
+ add(device?: PlayerDevice): Player;
104
+ /** Remove a player, free their devices and dispose their `Input`. Does nothing for a player no longer here. */
105
+ remove(player: Player): void;
106
+ /**
107
+ * Give `device` to `player` as well as what they own. Rebuilds their bindings from the shared actions, so changes
108
+ * made with `player.input.rebind` end here; apply saved bindings after it.
109
+ * @throws TypeError for an unknown device, one another player owns, or a player no longer here.
110
+ */
111
+ assign(player: Player, device: PlayerDevice): void;
112
+ /** Take `device` from its owner, who stays in the game. Does nothing for a device nobody owns. */
113
+ unassign(device: PlayerDevice): void;
114
+ /**
115
+ * Add players from `joinAction`, notice gamepads coming and going, and update every player's `Input`. Call once per
116
+ * tick, in place of `input.update()`.
117
+ * @throws MargoError `'disposed'` after {@link LocalPlayers.dispose}.
118
+ */
119
+ update(): void;
120
+ /** Dispose every player's `Input`. Idempotent. */
121
+ dispose(): void;
122
+ [Symbol.dispose]: () => void;
123
+ private alive;
124
+ private emit;
125
+ private check;
126
+ private rebuild;
127
+ /** Bindings of `action` on these devices, or {@link UNBOUND}, compared by identity, when there are none. */
128
+ private bindings;
129
+ }
@@ -0,0 +1,161 @@
1
+ import { t as e } from "./src-eYqyrCA7.js";
2
+ import { MargoError as t } from "@margoengine/math/errors";
3
+ //#region src/players.ts
4
+ var n = [{
5
+ type: "touch",
6
+ id: "unbound"
7
+ }], r = /* @__PURE__ */ new Set([
8
+ "key",
9
+ "mouse",
10
+ "pointer"
11
+ ]), i = class {
12
+ constructor(e, t) {
13
+ this.index = e, this.input = t, this.owned = /* @__PURE__ */ new Set(), this.missing = /* @__PURE__ */ new Set();
14
+ }
15
+ get devices() {
16
+ return [...this.owned];
17
+ }
18
+ get connected() {
19
+ return this.missing.size === 0;
20
+ }
21
+ async rumble(e, t = 1) {
22
+ let n = this.devices.filter((e) => e.startsWith("gamepad:"));
23
+ return (await Promise.all(n.map((n) => this.input.rumble(e, t, +n.slice(8))))).includes(!0);
24
+ }
25
+ }, a = class {
26
+ constructor(t, { maxPlayers: r = 4, schemes: i = {}, joinAction: a, gamepadSlots: o = 4, target: s = window, gamepads: c = () => navigator.getGamepads?.() ?? [], deadzone: l, contexts: u } = {}) {
27
+ if (this.slots = [], this.owners = /* @__PURE__ */ new Map(), this.handlers = /* @__PURE__ */ new Map(), this.disposed = !1, !Number.isInteger(r) || r < 1 || !Number.isInteger(o) || o < 1) throw RangeError("LocalPlayers maxPlayers and gamepadSlots must be integers of at least 1");
28
+ if (a !== void 0 && !Object.hasOwn(t, a)) throw TypeError("LocalPlayers joinAction must be one of the actions");
29
+ this.actions = t, this.schemes = i, this.maxPlayers = r, this.gamepads = c, this.options = {
30
+ target: s,
31
+ gamepads: c,
32
+ deadzone: l,
33
+ contexts: u
34
+ }, new e(t, this.options).dispose();
35
+ for (let [n, r] of Object.entries(i)) {
36
+ for (let e of Object.keys(r)) if (!Object.hasOwn(t, e)) throw TypeError(`Scheme ${n} binds an unknown action, ${e}; add it to the actions`);
37
+ new e(r, {
38
+ target: s,
39
+ gamepads: c
40
+ }).dispose();
41
+ }
42
+ if (a !== void 0) {
43
+ let t = {}, r = [
44
+ "keyboard",
45
+ "touch",
46
+ ...Object.keys(i).map((e) => `keyboard:${e}`)
47
+ ];
48
+ for (let e = 0; e < o; e++) r.push(`gamepad:${e}`);
49
+ for (let e of r) {
50
+ let r = this.bindings(a, [e]);
51
+ r !== n && (t[e] = r);
52
+ }
53
+ this.lobby = new e(t, {
54
+ target: s,
55
+ gamepads: c,
56
+ deadzone: l
57
+ });
58
+ }
59
+ }
60
+ get players() {
61
+ return this.slots.filter((e) => e !== void 0);
62
+ }
63
+ owner(e) {
64
+ return this.owners.get(e);
65
+ }
66
+ on(e, t) {
67
+ let n = this.handlers.get(e) ?? /* @__PURE__ */ new Set();
68
+ return this.handlers.set(e, n), n.add(t), () => n.delete(t);
69
+ }
70
+ add(t) {
71
+ this.alive();
72
+ let r = 0;
73
+ for (; this.slots[r];) r++;
74
+ if (r >= this.maxPlayers) throw RangeError("The party is full; raise maxPlayers or remove a player");
75
+ t !== void 0 && this.check(t);
76
+ let a = {};
77
+ for (let e of Object.keys(this.actions)) a[e] = n;
78
+ let o = new i(r, new e(a, this.options));
79
+ return this.slots[r] = o, t !== void 0 && this.assign(o, t), o.input.update(), this.emit({
80
+ type: "join",
81
+ player: o,
82
+ ...t === void 0 ? {} : { device: t }
83
+ }), o;
84
+ }
85
+ remove(e) {
86
+ if (this.slots[e.index] === e) {
87
+ for (let t of e.owned) this.owners.delete(t);
88
+ this.slots[e.index] = void 0, e.input.dispose(), this.emit({
89
+ type: "leave",
90
+ player: e
91
+ });
92
+ }
93
+ }
94
+ assign(e, t) {
95
+ if (this.alive(), this.slots[e.index] !== e) throw TypeError("That player has left; add a new one");
96
+ this.check(t, e), e.owned.add(t), this.owners.set(t, e), this.rebuild(e);
97
+ }
98
+ unassign(e) {
99
+ let t = this.owners.get(e);
100
+ t && (this.owners.delete(e), t.owned.delete(e), t.missing.delete(e), this.rebuild(t));
101
+ }
102
+ update() {
103
+ this.alive();
104
+ let e = this.lobby;
105
+ if (e) {
106
+ e.update();
107
+ for (let t of Object.keys(e.actions)) e.state(t).pressed && !this.owners.has(t) && this.players.length < this.maxPlayers && this.add(t);
108
+ }
109
+ let t = this.gamepads();
110
+ for (let [e, n] of [...this.owners]) {
111
+ if (!e.startsWith("gamepad:")) continue;
112
+ let r = t[+e.slice(8)], i = !!r && r.connected !== !1;
113
+ i !== !n.missing.has(e) && (i ? n.missing.delete(e) : n.missing.add(e), this.emit({
114
+ type: i ? "regained" : "lost",
115
+ player: n,
116
+ device: e
117
+ }));
118
+ }
119
+ for (let e of this.players) e.input.update();
120
+ }
121
+ dispose() {
122
+ if (!this.disposed) {
123
+ this.disposed = !0;
124
+ for (let e of this.players) e.input.dispose();
125
+ this.slots.length = 0, this.owners.clear(), this.lobby?.dispose(), this.handlers.clear();
126
+ }
127
+ }
128
+ [Symbol.dispose ?? Symbol()]() {
129
+ this.dispose();
130
+ }
131
+ alive() {
132
+ if (this.disposed) throw new t("disposed", "LocalPlayers is disposed; create a new one");
133
+ }
134
+ emit(e) {
135
+ for (let t of [...this.handlers.get(e.type) ?? []]) t(e);
136
+ }
137
+ check(e, t) {
138
+ let n = /^keyboard:(.+)$/.exec(e)?.[1];
139
+ if (!(n === void 0 ? /^(keyboard|touch|gamepad:\d+|control:.+)$/.test(e) : Object.hasOwn(this.schemes, n))) throw TypeError(`Unknown device ${e}; use keyboard, keyboard:<scheme>, gamepad:<n>, control:<id> or touch`);
140
+ let r = this.owners.get(e);
141
+ if (r && r !== t) throw TypeError(`Player ${r.index} already owns ${e}; unassign it first`);
142
+ }
143
+ rebuild(e) {
144
+ let t = e.devices;
145
+ for (let n of Object.keys(this.actions)) e.input.rebind(n, this.bindings(n, t));
146
+ }
147
+ bindings(e, t) {
148
+ let i = this.actions[e], a = [];
149
+ for (let n of t) if (n === "keyboard") a.push(...i.filter((e) => r.has(e.type)));
150
+ else if (n === "touch") a.push(...i.filter((e) => e.type === "touch"));
151
+ else if (n.startsWith("control:")) a.push(...i.filter((e) => e.type === "control" && e.id === n.slice(8)));
152
+ else if (n.startsWith("keyboard:")) a.push(...this.schemes[n.slice(9)][e] ?? []);
153
+ else for (let e of i) (e.type === "gamepad-axis" || e.type === "gamepad-button") && a.push({
154
+ ...e,
155
+ gamepad: +n.slice(8)
156
+ });
157
+ return a.length ? a : n;
158
+ }
159
+ };
160
+ //#endregion
161
+ export { a as LocalPlayers, i as Player };