@margoengine/input 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.
@@ -0,0 +1,183 @@
1
+ import { MargoError as e } from "@margoengine/math/errors";
2
+ //#region src/landmarks.ts
3
+ var t = "; see https://margoengine.com/errors#webcam-landmarks", n = (e) => {
4
+ if (!e || typeof e != "object" || !Number.isFinite(e.time)) throw TypeError("A landmark frame needs a finite time in ms and faces, hands and poses arrays" + t);
5
+ for (let t of [
6
+ "faces",
7
+ "hands",
8
+ "poses"
9
+ ]) if (!Array.isArray(e[t])) throw TypeError(`A landmark frame needs a ${t} array; pass [] for none; see https://margoengine.com/errors#webcam-landmarks`);
10
+ return e;
11
+ };
12
+ function r({ buffer: r = 1, signal: i } = {}) {
13
+ if (!Number.isInteger(r) || r < 1) throw RangeError("landmarkStream buffer must be a whole number >= 1" + t);
14
+ let a = [], o, s = !1, c = !1, l = () => {
15
+ c = s = !0, a.length = 0, i?.removeEventListener("abort", l), o?.({
16
+ done: !0,
17
+ value: void 0
18
+ }), o = void 0;
19
+ };
20
+ return i?.aborted ? c = s = !0 : i?.addEventListener("abort", l, { once: !0 }), {
21
+ push(i) {
22
+ if (s) throw new e("disposed", "The landmark stream has ended; create a new landmarkStream" + t);
23
+ n(i), o ? (o({
24
+ done: !1,
25
+ value: i
26
+ }), o = void 0) : (a.push(i), a.length > r && a.shift());
27
+ },
28
+ close() {
29
+ s = !0, a.length || l();
30
+ },
31
+ dispose: l,
32
+ [Symbol.dispose]: l,
33
+ [Symbol.asyncIterator]() {
34
+ return {
35
+ next: () => {
36
+ if (a.length) {
37
+ let e = a.shift();
38
+ return s && !a.length && l(), Promise.resolve({
39
+ done: !1,
40
+ value: e
41
+ });
42
+ }
43
+ if (c || s) return Promise.resolve({
44
+ done: !0,
45
+ value: void 0
46
+ });
47
+ if (o) throw new e("state", "A landmark stream has one reader; await each next() in turn" + t);
48
+ return new Promise((e) => o = e);
49
+ },
50
+ return: () => (l(), Promise.resolve({
51
+ done: !0,
52
+ value: void 0
53
+ }))
54
+ };
55
+ }
56
+ };
57
+ }
58
+ function i(e, t, { mirroredHandedness: r = !0 } = {}) {
59
+ let { face: i, hands: a, pose: o } = e ?? {}, s = (e, t) => {
60
+ if (!Array.isArray(e)) throw TypeError(`MediaPipe ${t} result has no landmark arrays; pass the object the ${t} landmarker returned; see https://margoengine.com/errors#webcam-landmarks`);
61
+ return e;
62
+ }, c = {
63
+ time: t,
64
+ faces: [],
65
+ hands: [],
66
+ poses: []
67
+ };
68
+ if (i && s(i.faceLandmarks, "face").forEach((e, t) => {
69
+ let n = i.faceBlendshapes?.[t]?.categories, r = { landmarks: e };
70
+ if (n) {
71
+ let e = {};
72
+ for (let t of n) t.categoryName && t.categoryName !== "_neutral" && (e[t.categoryName] = t.score ?? 0);
73
+ r.blendshapes = e;
74
+ }
75
+ let a = i.facialTransformationMatrixes?.[t]?.data;
76
+ a && (r.transform = a), c.faces.push(r);
77
+ }), a) {
78
+ let e = a.handedness ?? a.handednesses ?? [];
79
+ s(a.landmarks, "hand").forEach((t, n) => {
80
+ let i = e[n]?.[0], o = {
81
+ landmarks: t,
82
+ handedness: /left/i.test(i?.categoryName ?? "") === r ? "right" : "left",
83
+ score: i?.score ?? 1
84
+ };
85
+ a.worldLandmarks?.[n] && (o.worldLandmarks = a.worldLandmarks[n]), c.hands.push(o);
86
+ });
87
+ }
88
+ return o && s(o.landmarks, "pose").forEach((e, t) => {
89
+ let n = { landmarks: e };
90
+ o.worldLandmarks?.[t] && (n.worldLandmarks = o.worldLandmarks[t]), c.poses.push(n);
91
+ }), n(c);
92
+ }
93
+ async function a({ onFrame: n, video: r, constraints: i = {
94
+ facingMode: "user",
95
+ width: 640,
96
+ height: 480
97
+ }, signal: a, mediaDevices: o = globalThis.navigator?.mediaDevices } = {}) {
98
+ if (a?.throwIfAborted(), typeof o?.getUserMedia != "function") throw new e("unsupported", "This page has no camera access (getUserMedia); serve it over https" + t);
99
+ let s = await o.getUserMedia({
100
+ video: i,
101
+ audio: !1
102
+ }), c = () => s.getTracks().forEach((e) => e.stop());
103
+ if (a?.aborted) throw c(), a.reason;
104
+ let l = r ?? document.createElement("video");
105
+ l.muted = !0, l.playsInline = !0, l.srcObject = s;
106
+ try {
107
+ await l.play(), a?.throwIfAborted();
108
+ } catch (e) {
109
+ throw c(), l.srcObject = null, e;
110
+ }
111
+ let u = !1, d = 0, f = -1, p = typeof l.requestVideoFrameCallback == "function", m = (e) => {
112
+ u || (h(), l.currentTime !== f && (f = l.currentTime, n?.(l, e)));
113
+ }, h = () => {
114
+ d = p ? l.requestVideoFrameCallback(m) : requestAnimationFrame(m);
115
+ }, g = () => {
116
+ u || (u = !0, a?.removeEventListener("abort", g), p ? l.cancelVideoFrameCallback?.(d) : cancelAnimationFrame(d), c(), l.pause(), l.srcObject = null);
117
+ };
118
+ return a?.addEventListener("abort", g, { once: !0 }), n && h(), {
119
+ video: l,
120
+ stream: s,
121
+ stop: g,
122
+ [Symbol.dispose]: g
123
+ };
124
+ }
125
+ async function o({ detect: e, buffer: n, ...i }) {
126
+ if (typeof e != "function") throw TypeError("webcamLandmarks needs a detect(video, time) function" + t);
127
+ let o = r({
128
+ buffer: n,
129
+ signal: i.signal
130
+ }), s, c;
131
+ function l() {
132
+ c?.stop(), o.dispose();
133
+ }
134
+ return c = await a({
135
+ ...i,
136
+ onFrame(t, n) {
137
+ try {
138
+ let r = e(t, n);
139
+ r && o.push(r);
140
+ } catch (e) {
141
+ s = e, l();
142
+ }
143
+ }
144
+ }), {
145
+ webcam: c,
146
+ dispose: l,
147
+ [Symbol.dispose]: l,
148
+ [Symbol.asyncIterator]() {
149
+ let e = o[Symbol.asyncIterator]();
150
+ return {
151
+ next: async () => {
152
+ let t = await e.next();
153
+ if (t.done && s !== void 0) {
154
+ let e = s;
155
+ throw s = void 0, e;
156
+ }
157
+ return t;
158
+ },
159
+ return: () => (l(), Promise.resolve({
160
+ done: !0,
161
+ value: void 0
162
+ }))
163
+ };
164
+ }
165
+ };
166
+ }
167
+ var s = (e, t) => 1 / (1 + 1 / (2 * Math.PI * e * t)), c = class {
168
+ constructor({ minCutoff: e = 1, beta: n = .007, dCutoff: r = 1 } = {}) {
169
+ if (this.x = NaN, this.dx = 0, this.t = NaN, !(e > 0) || !(r > 0) || !Number.isFinite(e + r)) throw RangeError("OneEuroFilter cutoffs must be finite and above 0 Hz" + t);
170
+ if (!(n >= 0) || !Number.isFinite(n)) throw RangeError("OneEuroFilter beta must be finite and >= 0" + t);
171
+ this.minCutoff = e, this.beta = n, this.dCutoff = r;
172
+ }
173
+ filter(e, n) {
174
+ if (!Number.isFinite(e) || !Number.isFinite(n)) throw RangeError("OneEuroFilter needs a finite value and time" + t);
175
+ let r = n - this.t;
176
+ return r > 0 ? (this.dx += s(this.dCutoff, r) * ((e - this.x) / r - this.dx), this.x += s(this.minCutoff + this.beta * Math.abs(this.dx), r) * (e - this.x), this.t = n, this.x) : (Number.isNaN(this.x) && (this.x = e), this.t = Number.isNaN(this.t) ? n : this.t, this.x);
177
+ }
178
+ reset() {
179
+ this.x = this.t = NaN, this.dx = 0;
180
+ }
181
+ };
182
+ //#endregion
183
+ export { c as OneEuroFilter, i as fromMediaPipe, r as landmarkStream, a as startWebcam, o as webcamLandmarks };
@@ -0,0 +1,62 @@
1
+ import type { Binding } from './index.js';
2
+ import { type GlyphLayout } from './labels.js';
3
+ /** Structural navigator.keyboard surface. No browser permission or map is read until refresh. */
4
+ export interface InputKeyboardMapSource {
5
+ getLayoutMap(): Promise<Iterable<readonly [string, string]>>;
6
+ /** Draft layoutchange events are not exposed by every implementation of getLayoutMap. */
7
+ addEventListener?: EventTarget['addEventListener'];
8
+ /** Paired with addEventListener when draft layoutchange events are supported. */
9
+ removeEventListener?: EventTarget['removeEventListener'];
10
+ }
11
+ /** Options for KeyboardLabels. */
12
+ export interface KeyboardLabelsOptions {
13
+ /** Native navigator.keyboard by default. Null explicitly disables map lookup. */
14
+ keyboard?: InputKeyboardMapSource | null;
15
+ /** Bound on each map request, including automatic layoutchange refreshes. Default 5000 ms. */
16
+ timeout?: number;
17
+ }
18
+ /**
19
+ * Format a prompt with an already loaded native Keyboard Map; never changes the binding's physical code.
20
+ * ASCII letters are capitalized for keycap prompts. Unicode glyphs and punctuation are preserved.
21
+ * Missing/blank/control-character labels use the standard bindingLabel. Chords and gamepad glyphs are retained.
22
+ */
23
+ export declare function layoutBindingLabel(binding: Binding, map?: ReadonlyMap<string, string> | null, layout?: GlyphLayout): string;
24
+ /**
25
+ * Layout-aware key prompts with automatic native layoutchange refreshes and standard fallback labels.
26
+ * Await refresh once, then call label synchronously. Listen for 'change' to redraw prompts.
27
+ * Automatic failures are observable as lastError plus an 'error' event; explicit refresh rejects unexpected errors.
28
+ */
29
+ export declare class KeyboardLabels extends EventTarget {
30
+ /** Most recent automatic/explicit refresh error, or null after success or an expected capability denial. */
31
+ lastError: unknown;
32
+ private current;
33
+ private readonly keyboard;
34
+ private readonly timeout;
35
+ private readonly lifetime;
36
+ private generation;
37
+ private disposed;
38
+ /** @throws RangeError for an invalid timeout; use finite positive milliseconds. */
39
+ constructor({ keyboard, timeout, }?: KeyboardLabelsOptions);
40
+ /** Whether the browser exposes Keyboard Map, independent of permissions policy. */
41
+ get supported(): boolean;
42
+ /** Whether a map was obtained, including a valid empty map. */
43
+ get available(): boolean;
44
+ /** Current read-only snapshot, or null when unavailable/denied. */
45
+ get map(): ReadonlyMap<string, string> | null;
46
+ private check;
47
+ private readonly onLayoutChange;
48
+ /** Synchronous prompt using the latest map, or the standard fallback. @throws MargoError after disposal. */
49
+ label(binding: Binding, layout?: GlyphLayout): string;
50
+ /**
51
+ * Load the map with a bounded abortable wait. Last-started request wins; stale results never replace a newer map.
52
+ * Returns false when unsupported, denied or superseded. Known policy/permission/unsupported denials use fallback.
53
+ * @throws DOMException on abort/timeout; unexpected native errors are propagated, with lastError retained.
54
+ */
55
+ refresh({ signal }?: {
56
+ signal?: AbortSignal;
57
+ }): Promise<boolean>;
58
+ /** Cancel pending refreshes and remove the layout listener. Safe to repeat. */
59
+ dispose(): void;
60
+ /** Deterministic disposal for using declarations. */
61
+ [Symbol.dispose](): void;
62
+ }
package/dist/layout.js ADDED
@@ -0,0 +1,76 @@
1
+ import { t as e } from "./labels-DZOEJBkX.js";
2
+ import { MargoError as t } from "@margoengine/math/errors";
3
+ //#region src/layout.ts
4
+ function n(t, n, r = "xbox") {
5
+ let i = e(t, r);
6
+ if (t.type !== "key") return i;
7
+ let a = n?.get(t.code);
8
+ if (!a?.trim() || /[\u0000-\u001f\u007f]/.test(a)) return i;
9
+ let o = e({
10
+ ...t,
11
+ modifiers: void 0
12
+ }, r);
13
+ return i.slice(0, -o.length) + (/^[a-z]$/.test(a) ? a.toUpperCase() : a);
14
+ }
15
+ var r = class extends EventTarget {
16
+ constructor({ keyboard: e = globalThis.navigator?.keyboard, timeout: t = 5e3 } = {}) {
17
+ if (super(), this.lastError = null, this.current = null, this.lifetime = new AbortController(), this.generation = 0, this.disposed = !1, this.onLayoutChange = () => {
18
+ this.refresh().catch((e) => {
19
+ this.disposed || (this.lastError = e, this.dispatchEvent(new Event("error")));
20
+ });
21
+ }, !Number.isFinite(t) || t <= 0) throw RangeError("Invalid keyboard-map timeout; use positive finite milliseconds");
22
+ this.keyboard = e, this.timeout = t, e?.addEventListener && e.removeEventListener && e.addEventListener("layoutchange", this.onLayoutChange);
23
+ }
24
+ get supported() {
25
+ return typeof this.keyboard?.getLayoutMap == "function";
26
+ }
27
+ get available() {
28
+ return this.current !== null;
29
+ }
30
+ get map() {
31
+ return this.current;
32
+ }
33
+ check() {
34
+ if (this.disposed) throw new t("disposed", "Keyboard labels are disposed; create new KeyboardLabels");
35
+ }
36
+ label(e, t = "xbox") {
37
+ return this.check(), n(e, this.current, t);
38
+ }
39
+ async refresh({ signal: e } = {}) {
40
+ this.check(), e?.throwIfAborted();
41
+ let t = ++this.generation;
42
+ if (!this.supported) return this.current = null, !1;
43
+ let n = new AbortController(), r = setTimeout(() => n.abort(new DOMException("Keyboard map timed out; refresh again when the browser is ready", "TimeoutError")), this.timeout), i = AbortSignal.any([
44
+ this.lifetime.signal,
45
+ n.signal,
46
+ ...e ? [e] : []
47
+ ]);
48
+ try {
49
+ let e = await new Promise((e, t) => {
50
+ let n = () => t(i.reason);
51
+ i.addEventListener("abort", n, { once: !0 }), i.aborted ? n() : Promise.resolve().then(() => this.keyboard.getLayoutMap()).then(e, t).finally(() => i.removeEventListener("abort", n));
52
+ }), n = new Map(e);
53
+ for (let [e, t] of n) if (typeof e != "string" || typeof t != "string") throw TypeError("Invalid keyboard map; provide string key codes and glyphs");
54
+ return this.disposed || t !== this.generation ? !1 : (this.current = n, this.lastError = null, this.dispatchEvent(new Event("change")), !0);
55
+ } catch (e) {
56
+ if (i.aborted) throw i.reason;
57
+ if (this.disposed || t !== this.generation) return !1;
58
+ if ([
59
+ "SecurityError",
60
+ "NotAllowedError",
61
+ "NotSupportedError"
62
+ ].includes(e?.name ?? "")) return this.current = null, this.lastError = null, this.dispatchEvent(new Event("change")), !1;
63
+ throw this.lastError = e, e;
64
+ } finally {
65
+ clearTimeout(r);
66
+ }
67
+ }
68
+ dispose() {
69
+ this.disposed || (this.disposed = !0, this.generation++, this.keyboard?.removeEventListener?.("layoutchange", this.onLayoutChange), this.lifetime.abort(new t("disposed", "Keyboard labels are disposed; create new KeyboardLabels")), this.current = null);
70
+ }
71
+ [Symbol.dispose]() {
72
+ this.dispose();
73
+ }
74
+ };
75
+ //#endregion
76
+ export { r as KeyboardLabels, n as layoutBindingLabel };
package/dist/lock.d.ts ADDED
@@ -0,0 +1,72 @@
1
+ import type { ControlHost } from './motion.js';
2
+ /** Minimal native document surface used by PointerLock, also usable in deterministic tests. */
3
+ export interface InputLockDocument extends EventTarget {
4
+ readonly pointerLockElement?: object | null;
5
+ exitPointerLock?(): void;
6
+ }
7
+ /** A native HTMLElement is a compatible lock target. */
8
+ export interface InputLockTarget {
9
+ readonly ownerDocument: InputLockDocument;
10
+ requestPointerLock?(options?: {
11
+ unadjustedMovement?: boolean;
12
+ }): Promise<void> | void;
13
+ }
14
+ /** Options for one lock request. Call request from a user activation. */
15
+ export interface InputLockOptions {
16
+ /** Request movement without OS acceleration. Default true. */
17
+ unadjustedMovement?: boolean;
18
+ /** Fall back to adjusted movement only on NotSupportedError. Default true. */
19
+ fallback?: boolean;
20
+ /** Cancels the wait and releases a late native acquisition while this object is alive. */
21
+ signal?: AbortSignal;
22
+ /** Hard bound on the complete request, including fallback. Default 5000 ms. */
23
+ timeout?: number;
24
+ }
25
+ /**
26
+ * Pointer lock and per-tick relative mouse counts, independent of camera controls.
27
+ * Attach to Input and bind control id 'lock', axes 'x' and 'y'. Call update before Input.update.
28
+ * x/y retain unbounded mouse counts; Input actions apply their usual scale and scalar clamp.
29
+ */
30
+ export declare class PointerLock {
31
+ private readonly element;
32
+ /** Mouse counts sampled by the most recent update. */
33
+ x: number;
34
+ /** Mouse counts sampled by the most recent update. */
35
+ y: number;
36
+ /** True for confirmed raw movement, false for adjusted, null if a legacy void API cannot confirm options. */
37
+ raw: boolean | null;
38
+ private dx;
39
+ private dy;
40
+ private disposed;
41
+ private requesting;
42
+ private canceled;
43
+ private cancelPending?;
44
+ private readonly doc;
45
+ private readonly hosts;
46
+ /** Listen only on the target's document. The constructor does not request a lock. */
47
+ constructor(element: InputLockTarget);
48
+ /** Whether this element currently owns the lock. */
49
+ get locked(): boolean;
50
+ /** Whether the target and document expose pointer lock. */
51
+ get supported(): boolean;
52
+ private check;
53
+ private readonly onMove;
54
+ private readonly onChange;
55
+ /**
56
+ * Acquire lock, negotiating raw movement where supported. Modern promise and legacy event APIs both work.
57
+ * @throws RangeError for invalid timeout; DOMException on rejection, abort, unsupported API or a concurrent request.
58
+ */
59
+ request({ unadjustedMovement, fallback, signal, timeout, }?: InputLockOptions): Promise<void>;
60
+ private attempt;
61
+ /** Exit only this object's lock, cancel a pending request and discard accumulated counts. */
62
+ release(): void;
63
+ /** Publish per-tick counts to an Input (default control id 'lock'). Returns an idempotent detach function. */
64
+ attach(host: ControlHost, id?: string): () => void;
65
+ /** Sample and consume movement once per tick. @throws MargoError after disposal. */
66
+ update(): void;
67
+ private clear;
68
+ /** Release lock, cancel waits, remove listeners and remove published controls. Safe to repeat. */
69
+ dispose(): void;
70
+ /** Deterministic disposal for using declarations. */
71
+ [Symbol.dispose](): void;
72
+ }
package/dist/lock.js ADDED
@@ -0,0 +1,91 @@
1
+ import { MargoError as e } from "@margoengine/math/errors";
2
+ //#region src/lock.ts
3
+ var t = class {
4
+ constructor(e) {
5
+ this.element = e, this.x = 0, this.y = 0, this.raw = !1, this.dx = 0, this.dy = 0, this.disposed = !1, this.requesting = !1, this.canceled = !1, this.hosts = /* @__PURE__ */ new Map(), this.onMove = (e) => {
6
+ if (!this.locked) return;
7
+ let { movementX: t, movementY: n } = e;
8
+ Number.isFinite(t) && (this.dx += t), Number.isFinite(n) && (this.dy += n);
9
+ }, this.onChange = () => {
10
+ this.canceled && this.locked && this.doc.exitPointerLock?.(), this.locked || (this.clear(), this.raw = !1);
11
+ }, this.doc = e.ownerDocument, this.doc.addEventListener("mousemove", this.onMove), this.doc.addEventListener("pointerlockchange", this.onChange);
12
+ }
13
+ get locked() {
14
+ return this.doc.pointerLockElement === this.element;
15
+ }
16
+ get supported() {
17
+ return typeof this.element.requestPointerLock == "function" && typeof this.doc.exitPointerLock == "function";
18
+ }
19
+ check() {
20
+ if (this.disposed) throw new e("disposed", "Pointer lock is disposed; create a new PointerLock");
21
+ }
22
+ async request({ unadjustedMovement: e = !0, fallback: t = !0, signal: n, timeout: r = 5e3 } = {}) {
23
+ if (this.check(), !Number.isFinite(r) || r <= 0) throw RangeError("Invalid pointer lock timeout; use positive finite milliseconds");
24
+ if (n?.throwIfAborted(), !this.supported) throw new DOMException("Pointer lock is unavailable; use a browser with the Pointer Lock API", "NotSupportedError");
25
+ if (this.requesting) throw new DOMException("Pointer lock request already pending; await it before requesting again", "InvalidStateError");
26
+ this.requesting = !0, this.canceled = !1;
27
+ let i = new AbortController(), a = setTimeout(() => i.abort(new DOMException("Pointer lock timed out; request again from a user gesture", "TimeoutError")), r), o = n ? AbortSignal.any([n, i.signal]) : i.signal;
28
+ try {
29
+ try {
30
+ await this.attempt(e, o);
31
+ } catch (n) {
32
+ if (e && t && n?.name === "NotSupportedError" && !o.aborted) await this.attempt(!1, o);
33
+ else throw n;
34
+ }
35
+ } catch (e) {
36
+ throw this.canceled = !0, this.release(), e;
37
+ } finally {
38
+ clearTimeout(a), this.requesting = !1;
39
+ }
40
+ }
41
+ attempt(e, t) {
42
+ return new Promise((n, r) => {
43
+ let i = !1, a = (e) => {
44
+ i || (i = !0, this.doc.removeEventListener("pointerlockchange", o), this.doc.removeEventListener("pointerlockerror", s), t.removeEventListener("abort", c), this.cancelPending = void 0, e === void 0 ? n() : r(e));
45
+ }, o = () => {
46
+ this.locked && a();
47
+ }, s = () => a(new DOMException("Pointer lock refused; request from a user gesture and allow pointer lock", "OperationError")), c = () => a(t.reason);
48
+ if (this.cancelPending = a, this.doc.addEventListener("pointerlockchange", o), this.doc.addEventListener("pointerlockerror", s), t.addEventListener("abort", c, { once: !0 }), t.aborted) c();
49
+ else try {
50
+ let n = this.element.requestPointerLock({ unadjustedMovement: e });
51
+ this.raw = n ? e : null, n ? n.then(() => {
52
+ this.disposed || this.canceled || t.aborted ? this.locked && this.doc.exitPointerLock?.() : this.locked && a();
53
+ }, a) : o();
54
+ } catch (e) {
55
+ a(e);
56
+ }
57
+ });
58
+ }
59
+ release() {
60
+ this.canceled = !0, this.cancelPending?.(new DOMException("Pointer lock released; request again from a user gesture", "AbortError")), this.locked && this.doc.exitPointerLock?.(), this.raw = !1, this.clear();
61
+ }
62
+ attach(e, t = "lock") {
63
+ if (this.check(), !t || this.hosts.has(e)) throw TypeError("Invalid pointer lock host; use a nonempty id and attach each host once");
64
+ return this.hosts.set(e, {
65
+ id: t,
66
+ values: e.control(t)
67
+ }), () => {
68
+ this.hosts.delete(e) && e.removeControl(t);
69
+ };
70
+ }
71
+ update() {
72
+ this.check(), this.x = this.dx, this.y = this.dy, this.dx = this.dy = 0;
73
+ for (let { values: e } of this.hosts.values()) e.x = this.x, e.y = this.y;
74
+ }
75
+ clear() {
76
+ this.x = this.y = this.dx = this.dy = 0;
77
+ for (let { values: e } of this.hosts.values()) e.x = e.y = 0;
78
+ }
79
+ dispose() {
80
+ if (!this.disposed) {
81
+ this.release(), this.disposed = !0, this.doc.removeEventListener("mousemove", this.onMove), this.doc.removeEventListener("pointerlockchange", this.onChange);
82
+ for (let [e, { id: t }] of this.hosts) e.removeControl(t);
83
+ this.hosts.clear();
84
+ }
85
+ }
86
+ [Symbol.dispose]() {
87
+ this.dispose();
88
+ }
89
+ };
90
+ //#endregion
91
+ export { t as PointerLock };
@@ -0,0 +1,97 @@
1
+ /** What {@link Gyro.attach} writes to: an `Input`, or anything with the same two methods. */
2
+ export interface ControlHost {
3
+ control(id: string): Record<string, number>;
4
+ removeControl(id: string): void;
5
+ }
6
+ /** Options for {@link Gyro}. */
7
+ export interface GyroOptions {
8
+ /** Where `devicemotion` and `deviceorientation` arrive. Default `window`. */
9
+ target?: EventTarget;
10
+ /** Turn rate in degrees per second that reads as 1 on the `yaw`, `pitch` and `roll` actions. Default 180. */
11
+ maxRate?: number;
12
+ /** Tilt from the neutral position in degrees that reads as 1 on the `steer` action. Default 45. */
13
+ maxTilt?: number;
14
+ /** Turn rates under this many degrees per second read 0, so a resting hand does not drift the aim. Default 1. */
15
+ deadzone?: number;
16
+ /** Screen rotation in degrees, 0, 90, 180 or 270. Default `screen.orientation.angle`. */
17
+ screenAngle?: () => number;
18
+ /** Clock in milliseconds. Default `performance.now`. */
19
+ now?: () => number;
20
+ }
21
+ /**
22
+ * The device's gyroscope and tilt as aim and steering, in the screen's frame, so landscape and portrait read alike.
23
+ * Read `yaw` and `pitch` for aiming: the radians turned since the last update, which add straight onto a camera. Or
24
+ * attach it to an `Input` and bind actions to `{ type: 'control', id: 'gyro', axis: 'yaw' }`, and likewise `pitch`,
25
+ * `roll` and `steer`, where rates read as a share of `maxRate`.
26
+ *
27
+ * ```ts
28
+ * const gyro = new Gyro();
29
+ * button.onclick = () => Gyro.requestPermission(); // iOS asks only from a tap
30
+ * gyro.attach(input);
31
+ * gyro.update(); // once per tick, before input.update()
32
+ * input.update();
33
+ * ```
34
+ */
35
+ export declare class Gyro {
36
+ /** Radians turned since the last update, positive to the right. */
37
+ yaw: number;
38
+ /** Radians turned since the last update, positive upward. */
39
+ pitch: number;
40
+ /** Radians turned since the last update, positive clockwise as the player sees the screen. */
41
+ roll: number;
42
+ /** Tilt like a steering wheel, -1 to 1, positive clockwise. Reads 0 while the device lies flat. */
43
+ steer: number;
44
+ /** False ignores the sensors and reads 0, for aiming only while a button is held. Default true. */
45
+ enabled: boolean;
46
+ /** True once the device has sent a real gyroscope reading. Desktops send events with none, or no events. */
47
+ available: boolean;
48
+ private readonly target;
49
+ private readonly maxRate;
50
+ private readonly maxTilt;
51
+ private readonly deadzone;
52
+ private readonly screenAngle;
53
+ private readonly now;
54
+ private readonly hosts;
55
+ private readonly bias;
56
+ private calibration;
57
+ private pending;
58
+ private neutral;
59
+ private tilt;
60
+ private lastEvent;
61
+ private lastUpdate;
62
+ private disposed;
63
+ private stopCalibration;
64
+ /** @throws RangeError for a `maxRate` or `maxTilt` not above 0, or a `deadzone` below 0. */
65
+ constructor({ target, maxRate, maxTilt, deadzone, screenAngle, now, }?: GyroOptions);
66
+ /** Whether this browser has motion events at all. A device can still lack the sensor: see {@link Gyro.available}. */
67
+ static supported(): boolean;
68
+ /**
69
+ * Ask for the sensors where the browser needs it (iOS Safari), which it allows only from a tap or click. Resolves
70
+ * true when allowed or when no permission is needed, and false when refused or unsupported.
71
+ */
72
+ static requestPermission(): Promise<boolean>;
73
+ /** Publish to `input` as control `id`, for `{ type: 'control', id, axis }` bindings. Default id `'gyro'`. */
74
+ attach(input: ControlHost, id?: string): void;
75
+ /** Stop publishing to `input` and remove the control. */
76
+ detach(input: ControlHost): void;
77
+ /** Take the turns since the last update into `yaw`, `pitch` and `roll`, and publish. Call once per tick. */
78
+ update(): void;
79
+ /** Take the device's present tilt as straight ahead for `steer`. */
80
+ recenter(): void;
81
+ /**
82
+ * Measure the gyroscope's resting error over `duration` milliseconds (default 1000) and subtract it from now on. The
83
+ * device should lie still. Resolves false, changing nothing, when no reading arrived.
84
+ * @throws DOMException `AbortError` when `signal` aborts.
85
+ * @throws RangeError for a `duration` below 0.
86
+ */
87
+ calibrate({ duration, signal }?: {
88
+ duration?: number;
89
+ signal?: AbortSignal;
90
+ }): Promise<boolean>;
91
+ /** Stop listening and remove the controls. Idempotent. */
92
+ dispose(): void;
93
+ [Symbol.dispose]: () => void;
94
+ private readonly onMotion;
95
+ private readonly onOrientation;
96
+ private gated;
97
+ }