@n3rdw1z4rd/core 0.19.1 → 0.21.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.
Files changed (62) hide show
  1. package/README.md +27 -10
  2. package/dist/graph/doc.d.ts +141 -0
  3. package/dist/graph/doc.js +173 -0
  4. package/dist/graph/evaluate.d.ts +114 -0
  5. package/dist/graph/evaluate.js +319 -0
  6. package/dist/graph/index.d.ts +9 -0
  7. package/dist/graph/index.js +9 -0
  8. package/dist/graph/node.d.ts +153 -0
  9. package/dist/graph/node.js +94 -0
  10. package/dist/graph/nodes.d.ts +11 -0
  11. package/dist/graph/nodes.js +399 -0
  12. package/dist/graph/script.d.ts +56 -0
  13. package/dist/graph/script.js +98 -0
  14. package/dist/graph/sources.d.ts +11 -0
  15. package/dist/graph/sources.js +263 -0
  16. package/dist/graph/subgraph.d.ts +36 -0
  17. package/dist/graph/subgraph.js +280 -0
  18. package/dist/graph/types.d.ts +56 -0
  19. package/dist/graph/types.js +67 -0
  20. package/dist/graph.cjs +1709 -0
  21. package/dist/graph.d.cts +568 -0
  22. package/dist/index.cjs +495 -207
  23. package/dist/index.d.cts +231 -49
  24. package/dist/index.d.ts +5 -4
  25. package/dist/index.js +4 -3
  26. package/dist/input/_input.d.ts +25 -0
  27. package/dist/input/_input.js +97 -0
  28. package/dist/input/action-map.d.ts +42 -7
  29. package/dist/input/action-map.js +44 -18
  30. package/dist/input/bindings.d.ts +1 -1
  31. package/dist/input/bindings.js +1 -1
  32. package/dist/input/gestures.d.ts +20 -2
  33. package/dist/input/gestures.js +34 -8
  34. package/dist/input/index.d.ts +5 -4
  35. package/dist/input/index.js +3 -2
  36. package/dist/input/input-action-map.d.ts +327 -0
  37. package/dist/input/input-action-map.js +689 -0
  38. package/dist/input/input.d.ts +77 -272
  39. package/dist/input/input.js +201 -653
  40. package/dist/rng-Dhqq7owV.cjs +642 -0
  41. package/dist/{spatial-partition-3d-Ba-VBveM.cjs → spatial-partition-3d-CmSCL87Z.cjs} +19 -660
  42. package/dist/three/adaptive-grid.d.ts +43 -0
  43. package/dist/three/adaptive-grid.js +127 -0
  44. package/dist/three/ecs.d.ts +5 -3
  45. package/dist/three/ecs.js +5 -3
  46. package/dist/three/editor-camera.d.ts +93 -0
  47. package/dist/three/editor-camera.js +174 -0
  48. package/dist/three/index.d.ts +6 -1
  49. package/dist/three/index.js +6 -1
  50. package/dist/three/picking.d.ts +34 -0
  51. package/dist/three/picking.js +59 -0
  52. package/dist/three/schema.d.ts +139 -0
  53. package/dist/three/schema.js +214 -0
  54. package/dist/three/world.d.ts +192 -0
  55. package/dist/three/world.js +363 -0
  56. package/dist/three.cjs +970 -23
  57. package/dist/three.d.cts +497 -5
  58. package/dist/vite.cjs +40 -0
  59. package/dist/vite.d.cts +35 -0
  60. package/dist/vite.d.ts +35 -0
  61. package/dist/vite.js +39 -0
  62. package/package.json +21 -1
@@ -1,17 +1,6 @@
1
- import { GAMEPAD_AXES, GAMEPAD_BUTTONS, XR_AXES, XR_BUTTONS, controlId } from "./bindings.js";
2
- import { ActionMap } from "./action-map.js";
3
- import { GestureRecognizer } from "./gestures.js";
4
- import { Observable } from "../observable.js";
1
+ import { Vector } from "../vector.js";
2
+ import { Emitter } from "../emitter.js";
5
3
  //#region src/input/input.ts
6
- const ANY = -1;
7
- const now = () => performance.now();
8
- const MOUSE_BUTTONS = [
9
- "left",
10
- "middle",
11
- "right",
12
- "back",
13
- "forward"
14
- ];
15
4
  const BUTTON_BITS = [
16
5
  1,
17
6
  4,
@@ -19,676 +8,235 @@ const BUTTON_BITS = [
19
8
  8,
20
9
  16
21
10
  ];
22
- const isEditable = (target) => {
23
- const element = target;
24
- const tag = element?.tagName;
25
- return !!element && (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || element.isContentEditable === true);
26
- };
27
11
  /**
28
- * Game input with a Godot-style action map: bind keys, buttons, sticks, gestures and VR controls
29
- * to named actions, then query actions instead of devices.
12
+ * Event-based input for keyboard, mouse, pen and touch: subscribe with `on()` and query state
13
+ * at any time; no frame loop needed. One shared instance, {@link Input.instance}.
30
14
  *
31
- * const input = new Input(canvas);
32
- * input.actions.add('jump', [key('Space'), pad('A')]);
15
+ * Events (listeners get the DOM event):
16
+ * - keys, by lowercased `KeyboardEvent.code`: `key_down`, `key_up`, `key_repeat`, `key_pressed`
17
+ * (released within `inputThreshold` ms), and per key `keyw_down`, `keyw_up`, `keyw_pressed`, ...
18
+ * - buttons (mouse buttons; the primary finger or pen is button 0): `button_down`, `button_up`,
19
+ * `button_clicked`, and per button `button0_down`, `button0_up`, `button0_clicked`, ...
20
+ * No click after a drag.
21
+ * - pointer: `pointer_move`; `drag_start`, `drag`, `drag_end` (moved `dragThreshold` px with a
22
+ * button down); `mouse_wheel`; `contextmenu` (see `disableContextMenu()`)
23
+ * - every finger: `touch_down`, `touch_move`, `touch_up`, `touch_cancel`
24
+ * - `blur`: the window lost focus or the tab was hidden; every key and button is released
33
25
  *
34
- * // every frame, before game logic:
35
- * input.update();
36
- * if (input.isActionJustPressed('jump')) player.jump();
26
+ * ```ts
27
+ * const input = Input.instance;
28
+ * input.target = canvas;
37
29
  *
38
- * Call `dispose()` to remove all listeners.
30
+ * input.on('keyw_down', 'arrowup_down', () => move(0, -1));
31
+ * input.on('button0_clicked', () => select(input.pointerPosition));
32
+ * input.on('pointer_move', () => {
33
+ * if (input.isButtonDown(0)) pan(input.pointerDelta.x, input.pointerDelta.y);
34
+ * });
35
+ * ```
39
36
  *
40
37
  * @category Input
41
38
  */
42
- var Input = class {
43
- /** the actions to query; holds the `ui_*` defaults unless {@link InputOptions.defaults} is false */
44
- actions = new ActionMap();
45
- /** Thresholds for taps, swipes etc. can be tuned via `gestureRecognizer.thresholds`. */
46
- gestureRecognizer = new GestureRecognizer();
47
- /** Two-finger gesture values for the last frame (pinch 1 / pan 0 / rotate 0 when not gesturing). */
48
- gestures = {
49
- pinch: 1,
50
- pan: {
51
- x: 0,
52
- y: 0
53
- },
54
- rotate: 0
55
- };
56
- /** Fingers currently on the target. */
57
- get touches() {
58
- return this.gestureRecognizer.touches;
59
- }
60
- /** the mouse or pen; not updated by touch */
61
- pointer = {
62
- type: "mouse",
63
- x: 0,
64
- y: 0,
65
- ndcX: 0,
66
- ndcY: 0,
67
- deltaX: 0,
68
- deltaY: 0,
69
- wheelX: 0,
70
- wheelY: 0,
71
- pressure: 0,
72
- tiltX: 0,
73
- tiltY: 0
74
- };
75
- /** notified when {@link Input.lastDevice} changes, e.g. to switch on-screen button prompts */
76
- onDeviceChange = new Observable();
77
- /** notified from update() when a gamepad is first seen */
78
- onGamepadConnected = new Observable();
79
- /** notified from update() when a gamepad goes away; its held controls are released */
80
- onGamepadDisconnected = new Observable();
81
- _gamepads = /* @__PURE__ */ new Map();
82
- /** Connected gamepads, as found by the last update(). */
83
- get gamepads() {
84
- return [...this._gamepads].map(([device, gamepad]) => ({
85
- device,
86
- id: gamepad.id,
87
- standard: gamepad.mapping === "standard"
88
- }));
89
- }
90
- _lastDevice = "keyboard";
91
- _keyLabels;
92
- _target;
93
- _options;
94
- _listeners = [];
95
- _controls = /* @__PURE__ */ new Map([[0, /* @__PURE__ */ new Map()]]);
96
- _actionStates = /* @__PURE__ */ new Map();
97
- _actionListeners = [];
98
- _warned = /* @__PURE__ */ new Set();
99
- _pending = {
100
- deltaX: 0,
101
- deltaY: 0,
102
- wheelX: 0,
103
- wheelY: 0
104
- };
105
- _capture;
106
- /** The kind of device that produced the most recent input (initially `'keyboard'`). */
107
- get lastDevice() {
108
- return this._lastDevice;
109
- }
110
- /** Whether the pointer is locked to the target, see {@link Input.lockPointer}. */
111
- get isPointerLocked() {
112
- return typeof document !== "undefined" && !!this._target && document.pointerLockElement === this._target;
113
- }
114
- /**
115
- * @param target element that receives pointer, wheel and touch input (usually the canvas)
116
- */
117
- constructor(target, options = {}) {
118
- this._target = target;
119
- this._options = {
120
- defaults: options.defaults ?? true,
121
- preventDefault: options.preventDefault ?? true,
122
- preventContextMenu: options.preventContextMenu ?? true
123
- };
124
- if (this._options.defaults) this.actions.addDefaults();
125
- const keyboard = options.keyboardTarget ?? (typeof window !== "undefined" ? window : void 0);
126
- if (keyboard) {
127
- this._listen(keyboard, "keydown", (e) => this._onKeyDown(e));
128
- this._listen(keyboard, "keyup", (e) => this._onKeyUp(e));
129
- this._listen(keyboard, "blur", () => this.releaseAll(0));
130
- }
131
- if (typeof document !== "undefined") this._listen(document, "visibilitychange", () => {
132
- if (document.hidden) this.releaseAll(0);
133
- });
134
- if (target) {
135
- const style = target.style;
136
- if (this._options.preventDefault && style) style.touchAction = "none";
137
- this._listen(target, "pointerdown", (e) => this._onPointerDown(e));
138
- this._listen(target, "pointerup", (e) => this._onPointerUp(e));
139
- this._listen(target, "pointercancel", (e) => this._onPointerCancel(e));
140
- this._listen(target, "pointermove", (e) => this._onPointerMove(e));
141
- this._listen(target, "wheel", (e) => this._onWheel(e), { passive: false });
142
- this._listen(target, "contextmenu", (e) => {
143
- if (this._options.preventContextMenu) e.preventDefault();
144
- });
145
- }
146
- }
147
- /**
148
- * Call once per frame, before reading input: polls devices and advances "just pressed" /
149
- * "just released" by one frame. Action callbacks fire from here.
150
- */
151
- update() {
152
- this.pointer.deltaX = this._pending.deltaX;
153
- this.pointer.deltaY = this._pending.deltaY;
154
- this.pointer.wheelX = this._pending.wheelX;
155
- this.pointer.wheelY = this._pending.wheelY;
156
- this._pending.deltaX = this._pending.deltaY = this._pending.wheelX = this._pending.wheelY = 0;
157
- this._pollGamepads();
158
- this._pollXR();
159
- this._updateGestures();
160
- const devices = [...this._controls.keys()];
161
- const fired = [];
162
- for (const name of this.actions.names) {
163
- const action = this.actions.get(name);
164
- let states = this._actionStates.get(name);
165
- if (!states) this._actionStates.set(name, states = /* @__PURE__ */ new Map());
166
- let anyRaw = 0;
167
- for (const device of devices) {
168
- let raw = 0;
169
- for (const binding of action.bindings) raw = Math.max(raw, this._bindingValue(binding, device));
170
- anyRaw = Math.max(anyRaw, raw);
171
- if (this._advance(states, device, raw, action.deadzone)) fired.push({
172
- action: name,
173
- phase: states.get(device).pressed ? "pressed" : "released",
174
- device
175
- });
176
- }
177
- if (this._advance(states, ANY, anyRaw, action.deadzone)) fired.push({
178
- action: name,
179
- phase: states.get(ANY).pressed ? "pressed" : "released",
180
- device: ANY
181
- });
182
- }
183
- for (const controls of this._controls.values()) for (const state of controls.values()) state.pressed = false;
184
- for (const { action, phase, device } of fired) for (const listener of [...this._actionListeners]) if (listener.action === action && listener.phase === phase && listener.device === device) listener.callback();
185
- }
186
- /** Whether the action is held past its deadzone. Unknown actions return false (and warn once). */
187
- isActionPressed(action, query) {
188
- return this._state(action, query)?.pressed ?? false;
189
- }
190
- /** Whether the action became pressed in the last update(). */
191
- isActionJustPressed(action, query) {
192
- const state = this._state(action, query);
193
- return !!state && state.pressed && !state.wasPressed;
194
- }
195
- /** Whether the action was released in the last update(). */
196
- isActionJustReleased(action, query) {
197
- const state = this._state(action, query);
198
- return !!state && !state.pressed && state.wasPressed;
199
- }
200
- /** 0..1, rescaled past the action's deadzone (analog triggers and sticks give values in between). */
201
- getActionStrength(action, query) {
202
- return this._state(action, query)?.strength ?? 0;
203
- }
204
- /** 0..1 before the deadzone is applied. */
205
- getActionRawStrength(action, query) {
206
- return this._state(action, query)?.raw ?? 0;
207
- }
208
- /** -1..1: `positive` minus `negative`. */
209
- getAxis(negative, positive, query) {
210
- return this.getActionStrength(positive, query) - this.getActionStrength(negative, query);
211
- }
39
+ var Input = class Input extends Emitter {
40
+ static _instance;
41
+ /** the shared instance, created on first use */
42
+ static get instance() {
43
+ if (!Input._instance) Input._instance = new Input();
44
+ return Input._instance;
45
+ }
46
+ _state = {};
47
+ _windowListeners = [];
48
+ _targetListeners = [];
49
+ _target = window;
50
+ _contextMenuDisabled = false;
51
+ _dragStart;
52
+ _dragging = false;
53
+ /** pixels from the target's top-left */
54
+ pointerPosition = new Vector();
55
+ /** -1..1 across the target, y up */
56
+ pointerPositionNdc = new Vector();
57
+ /** pixels moved by the last pointer event (mouse, pen and touch alike) */
58
+ pointerDelta = new Vector();
59
+ /** ms; a key or button released within this is also `_pressed` / `_clicked` */
60
+ inputThreshold = 200;
61
+ /** px; moving further than this with a button down starts a drag */
62
+ dragThreshold = 5;
212
63
  /**
213
- * A 2D direction from four actions, with a circular deadzone and length at most 1 (diagonals
214
- * aren't faster). Y is positive towards `positiveY`, as in Godot's get_vector("left", "right", "up", "down").
215
- *
216
- * @param options.deadzone default: the average of the four actions' deadzones
217
- * @returns `x` and `y` in -1..1; `{ x: 0, y: 0 }` inside the deadzone
64
+ * Where pointer, wheel and context-menu events are read and positions are measured, default
65
+ * `window`; usually the canvas. Keys are always read from `window`.
218
66
  */
219
- getVector(negativeX, positiveX, negativeY, positiveY, options = {}) {
220
- const names = [
221
- negativeX,
222
- positiveX,
223
- negativeY,
224
- positiveY
225
- ];
226
- const raw = names.map((name) => this.getActionRawStrength(name, options));
227
- const deadzone = options.deadzone ?? names.reduce((sum, name) => sum + (this.actions.get(name)?.deadzone ?? 0), 0) / 4;
228
- let x = raw[1] - raw[0];
229
- let y = raw[3] - raw[2];
230
- const length = Math.hypot(x, y);
231
- if (length <= deadzone) return {
232
- x: 0,
233
- y: 0
234
- };
235
- const scale = (Math.min(length, 1) - deadzone) / (1 - deadzone) / length;
236
- x *= scale;
237
- y *= scale;
238
- return {
239
- x,
240
- y
241
- };
242
- }
243
- /** Calls `callback` when the action is pressed or released (during update()). Returns an unsubscribe function. */
244
- onAction(action, phase, callback, query = {}) {
245
- const listener = {
246
- action,
247
- phase,
248
- device: query.device ?? ANY,
249
- callback
250
- };
251
- this._actionListeners.push(listener);
252
- return () => {
253
- const i = this._actionListeners.indexOf(listener);
254
- if (i >= 0) this._actionListeners.splice(i, 1);
255
- };
256
- }
257
- /** Whether a key (by `KeyboardEvent.code`) is held right now, regardless of actions. */
258
- isKeyPressed(code) {
259
- return (this._controls.get(0).get(`key:${code}`)?.value ?? 0) > 0;
260
- }
261
- /** Whether a mouse or pen button is held right now, regardless of actions. */
262
- isMouseButtonPressed(button) {
263
- return (this._controls.get(0).get(`mouse:${button}`)?.value ?? 0) > 0;
67
+ get target() {
68
+ return this._target;
264
69
  }
265
- /**
266
- * Releases every held key and button, on one device or all. Keyboard, mouse and touch (device 0)
267
- * are released automatically when the window loses focus, since their release events get lost.
268
- */
269
- releaseAll(device) {
270
- if (device === void 0 || device === 0) this.gestureRecognizer.clear();
271
- for (const [d, controls] of this._controls) {
272
- if (device !== void 0 && d !== device) continue;
273
- for (const state of controls.values()) {
274
- state.value = 0;
275
- state.suppressed = false;
276
- }
277
- }
278
- }
279
- /** Requests pointer lock on the target (browsers only allow it from a user gesture, e.g. a click). */
280
- lockPointer() {
281
- this._target?.requestPointerLock?.();
282
- }
283
- /** Exits pointer lock if the target holds it. */
284
- unlockPointer() {
285
- if (this.isPointerLocked) document.exitPointerLock();
286
- }
287
- /**
288
- * Waits for the player's next input and resolves with a binding for it, for rebinding menus.
289
- * Resolves `null` if the cancel key is pressed or another capture starts. The captured press
290
- * doesn't trigger any actions.
291
- */
292
- captureBinding(options = {}) {
293
- this.cancelCapture();
294
- return new Promise((resolve) => {
295
- this._capture = {
296
- options,
297
- resolve
298
- };
70
+ /** moves the pointer, wheel and context-menu listeners to `target` */
71
+ set target(target) {
72
+ this._targetListeners.forEach(([type, listener]) => this._target.removeEventListener(type, listener));
73
+ this._targetListeners = [];
74
+ this._target = target;
75
+ this._listenToTarget();
76
+ }
77
+ /** a drag is in progress */
78
+ get isDragging() {
79
+ return this._dragging;
80
+ }
81
+ constructor() {
82
+ super();
83
+ this._listen(this._windowListeners, window, "keydown", this._onKeyDown);
84
+ this._listen(this._windowListeners, window, "keyup", this._onKeyUp);
85
+ this._listen(this._windowListeners, window, "blur", this._onBlur);
86
+ if (typeof document !== "undefined") this._listen(this._windowListeners, document, "visibilitychange", () => {
87
+ if (document.hidden) this._onBlur(new Event("blur"));
299
88
  });
89
+ this._listenToTarget();
300
90
  }
301
- /** Ends a pending {@link Input.captureBinding}, resolving it with `null`. */
302
- cancelCapture() {
303
- const capture = this._capture;
304
- this._capture = void 0;
305
- capture?.resolve(null);
306
- }
307
- /**
308
- * Loads the keyboard layout (where supported, e.g. Chromium) so {@link bindingLabel} names keys
309
- * as printed on the player's keyboard: KeyW is "Z" on AZERTY.
310
- */
311
- async loadKeyboardLayout() {
312
- const keyboard = globalThis.navigator?.keyboard;
313
- try {
314
- this._keyLabels = await keyboard?.getLayoutMap?.();
315
- } catch {
316
- this._keyLabels = void 0;
317
- }
318
- return this._keyLabels;
91
+ /** Stops the right-click menu on the target; `contextmenu` is still emitted. */
92
+ disableContextMenu() {
93
+ if (this._contextMenuDisabled) return;
94
+ this._contextMenuDisabled = true;
95
+ this._listen(this._targetListeners, this._target, "contextmenu", this._onContextMenu);
319
96
  }
320
- /** The layout loaded by {@link Input.loadKeyboardLayout}, if any: `KeyboardEvent.code` to printed key. */
321
- get keyLabels() {
322
- return this._keyLabels;
323
- }
324
- /** Removes all event listeners and action callbacks, cancels any capture and detaches XR. */
97
+ /** Removes every DOM listener; the next {@link Input.instance} is a new one. */
325
98
  dispose() {
326
- for (const [target, type, listener, options] of this._listeners) target.removeEventListener(type, listener, options);
327
- this._listeners.length = 0;
328
- this._actionListeners.length = 0;
329
- this.cancelCapture();
330
- this.detachXR();
331
- }
332
- _listen(target, type, listener, options) {
333
- target.addEventListener(type, listener, options);
334
- this._listeners.push([
335
- target,
336
- type,
337
- listener,
338
- options
339
- ]);
340
- }
341
- _state(action, query) {
342
- if (!this.actions.has(action)) {
343
- if (!this._warned.has(action)) {
344
- this._warned.add(action);
345
- console.warn(`Input: unknown action "${action}"`);
346
- }
347
- return;
348
- }
349
- return this._actionStates.get(action)?.get(query?.device ?? ANY);
350
- }
351
- _advance(states, device, raw, deadzone) {
352
- let state = states.get(device);
353
- if (!state) states.set(device, state = {
354
- raw: 0,
355
- strength: 0,
356
- pressed: false,
357
- wasPressed: false
358
- });
359
- state.wasPressed = state.pressed;
360
- state.raw = raw;
361
- state.pressed = raw > 0 && raw >= deadzone;
362
- state.strength = !state.pressed ? 0 : deadzone >= 1 ? 1 : Math.min(1, (raw - deadzone) / (1 - deadzone));
363
- if (state.pressed && raw >= 1) state.strength = 1;
364
- return state.pressed !== state.wasPressed;
365
- }
366
- _controlValue(device, id) {
367
- const state = this._controls.get(device)?.get(id);
368
- if (!state || state.suppressed) return 0;
369
- return state.pressed && state.value < .5 ? 1 : state.value;
370
- }
371
- _bindingValue(binding, device) {
372
- const value = this._controlValue(device, controlId(binding));
373
- if (value === 0 || binding.type !== "key" || !binding.modifiers) return value;
374
- const held = (left, right) => this._controlValue(device, `key:${left}`) > 0 || this._controlValue(device, `key:${right}`) > 0;
375
- const m = binding.modifiers;
376
- if (m.shift && !held("ShiftLeft", "ShiftRight")) return 0;
377
- if (m.ctrl && !held("ControlLeft", "ControlRight")) return 0;
378
- if (m.alt && !held("AltLeft", "AltRight")) return 0;
379
- if (m.meta && !held("MetaLeft", "MetaRight")) return 0;
380
- return value;
381
- }
382
- _control(device, binding) {
383
- let controls = this._controls.get(device);
384
- if (!controls) this._controls.set(device, controls = /* @__PURE__ */ new Map());
385
- const id = controlId(binding);
386
- let state = controls.get(id);
387
- if (!state) controls.set(id, state = {
388
- value: 0,
389
- pressed: false,
390
- suppressed: false
99
+ this._windowListeners.forEach(([type, listener]) => {
100
+ window.removeEventListener(type, listener);
101
+ if (typeof document !== "undefined") document.removeEventListener(type, listener);
391
102
  });
392
- return state;
103
+ this._targetListeners.forEach(([type, listener]) => this._target.removeEventListener(type, listener));
104
+ this._windowListeners = [];
105
+ this._targetListeners = [];
106
+ Input._instance = void 0;
107
+ }
108
+ _listenToTarget() {
109
+ const listeners = this._targetListeners;
110
+ this._listen(listeners, this._target, "pointerdown", this._onPointerDown);
111
+ this._listen(listeners, this._target, "pointerup", this._onPointerUp);
112
+ this._listen(listeners, this._target, "pointercancel", this._onPointerUp);
113
+ this._listen(listeners, this._target, "pointermove", this._onPointerMove);
114
+ this._listen(listeners, this._target, "wheel", this._onWheel, { passive: false });
115
+ if (this._contextMenuDisabled) this._listen(listeners, this._target, "contextmenu", this._onContextMenu);
116
+ const style = this._target.style;
117
+ if (style) style.touchAction = "none";
118
+ }
119
+ _listen(listeners, target, type, handler, options) {
120
+ const listener = handler.bind(this);
121
+ target.addEventListener(type, listener, options);
122
+ listeners.push([type, listener]);
393
123
  }
394
- /** Updates a held control (key, button, axis direction: 0..1); `binding` describes it for captureBinding(). */
395
- _setControl(device, binding, value) {
396
- const state = this._control(device, binding);
397
- const wasDown = state.value >= .5;
398
- state.value = value;
399
- if (value >= .5 && !wasDown) {
400
- if (this._tryCapture(binding)) state.suppressed = true;
401
- else state.pressed = true;
124
+ _down(id, group, name, ev) {
125
+ if (this._state[id]?.state) return;
126
+ this._state[id] = {
127
+ state: 1,
128
+ timeStamp: ev.timeStamp
129
+ };
130
+ this.emit(`${group}_down`, ev);
131
+ this.emit(`${name}_down`, ev);
132
+ }
133
+ _up(id, group, name, quick, ev) {
134
+ const down = this._state[id];
135
+ if (!down?.state) return;
136
+ this._state[id] = {
137
+ state: 0,
138
+ timeStamp: ev.timeStamp
139
+ };
140
+ this.emit(`${group}_up`, ev);
141
+ this.emit(`${name}_up`, ev);
142
+ if (!this._dragging && ev.timeStamp - down.timeStamp <= this.inputThreshold) {
143
+ this.emit(`${group}_${quick}`, ev);
144
+ this.emit(`${name}_${quick}`, ev);
402
145
  }
403
- if (value === 0) state.suppressed = false;
404
- }
405
- /** A one-frame press with no held state: wheel steps, gestures. */
406
- _pulse(device, binding) {
407
- const state = this._control(device, binding);
408
- if (!this._tryCapture(binding)) state.pressed = true;
409
146
  }
410
- _tryCapture(binding) {
411
- const capture = this._capture;
412
- if (!capture) return false;
413
- const types = capture.options.types;
414
- const cancelKey = capture.options.cancelKey === void 0 ? "Escape" : capture.options.cancelKey;
415
- const cancelled = binding.type === "key" && binding.code === cancelKey;
416
- if (!cancelled && types && !types.includes(binding.type)) return false;
417
- this._capture = void 0;
418
- capture.resolve(cancelled ? null : binding);
419
- return true;
147
+ _anyButtonDown() {
148
+ return BUTTON_BITS.some((_, button) => this.isButtonDown(button));
420
149
  }
421
- _setLastDevice(type) {
422
- if (type === this._lastDevice) return;
423
- this._lastDevice = type;
424
- this.onDeviceChange.notify(type);
425
- }
426
- /**
427
- * Vibrates a gamepad (where supported). Magnitudes are 0..1; `strong` defaults to 1, `weak` to
428
- * `strong`, `duration` to 200 ms.
429
- */
430
- rumble(device, options = {}) {
431
- (this._gamepads.get(device)?.vibrationActuator)?.playEffect?.("dual-rumble", {
432
- startDelay: 0,
433
- duration: options.duration ?? 200,
434
- strongMagnitude: options.strong ?? 1,
435
- weakMagnitude: options.weak ?? options.strong ?? 1
436
- })?.catch(() => {});
437
- }
438
- _pollGamepads() {
439
- const pads = globalThis.navigator?.getGamepads?.() ?? [];
440
- const seen = /* @__PURE__ */ new Set();
441
- for (const gamepad of pads) {
442
- if (!gamepad || !gamepad.connected) continue;
443
- const device = gamepad.index + 1;
444
- const isNew = !this._gamepads.has(device);
445
- seen.add(device);
446
- this._gamepads.set(device, gamepad);
447
- if (isNew) this.onGamepadConnected.notify({
448
- device,
449
- id: gamepad.id,
450
- standard: gamepad.mapping === "standard"
451
- });
452
- let active = false;
453
- for (let i = 0; i < GAMEPAD_BUTTONS.length && i < gamepad.buttons.length; i++) {
454
- const button = gamepad.buttons[i];
455
- const value = button.value > 0 ? button.value : button.pressed ? 1 : 0;
456
- this._setControl(device, {
457
- type: "pad",
458
- button: GAMEPAD_BUTTONS[i]
459
- }, value);
460
- active ||= value >= .5;
461
- }
462
- for (let i = 0; i < GAMEPAD_AXES.length && i < gamepad.axes.length; i++) {
463
- const value = gamepad.axes[i];
464
- this._setControl(device, {
465
- type: "padAxis",
466
- axis: GAMEPAD_AXES[i],
467
- direction: 1
468
- }, Math.max(0, value));
469
- this._setControl(device, {
470
- type: "padAxis",
471
- axis: GAMEPAD_AXES[i],
472
- direction: -1
473
- }, Math.max(0, -value));
474
- active ||= Math.abs(value) >= .5;
475
- }
476
- if (active) this._setLastDevice("gamepad");
150
+ _updatePointer(ev) {
151
+ const rect = this._target.getBoundingClientRect?.() ?? {
152
+ left: 0,
153
+ top: 0,
154
+ width: window.innerWidth,
155
+ height: window.innerHeight
156
+ };
157
+ const x = ev.clientX - rect.left;
158
+ const y = ev.clientY - rect.top;
159
+ if (ev.pointerType === "touch") this.pointerDelta.set(x - this.pointerPosition.x, y - this.pointerPosition.y);
160
+ else this.pointerDelta.set(ev.movementX ?? 0, ev.movementY ?? 0);
161
+ this.pointerPosition.set(x, y);
162
+ this.pointerPositionNdc.set(x / (rect.width || 1) * 2 - 1, -(y / (rect.height || 1)) * 2 + 1);
163
+ }
164
+ _onContextMenu(ev) {
165
+ ev.preventDefault();
166
+ this.emit("contextmenu", ev);
167
+ }
168
+ _onKeyDown(ev) {
169
+ if (ev.repeat) this.emit("key_repeat", ev);
170
+ else this._down(ev.code, "key", ev.code.toLowerCase(), ev);
171
+ }
172
+ _onKeyUp(ev) {
173
+ this._up(ev.code, "key", ev.code.toLowerCase(), "pressed", ev);
174
+ }
175
+ _onPointerDown(ev) {
176
+ if (ev.pointerType === "touch") this.emit("touch_down", ev);
177
+ if (!ev.isPrimary) return;
178
+ this._target.setPointerCapture?.(ev.pointerId);
179
+ this._updatePointer(ev);
180
+ this.pointerDelta.set(0, 0);
181
+ if (!this._anyButtonDown()) {
182
+ this._dragStart = this.pointerPosition.clone();
183
+ this._dragging = false;
477
184
  }
478
- for (const [device, gamepad] of this._gamepads) {
479
- if (seen.has(device)) continue;
480
- for (const state of this._controls.get(device)?.values() ?? []) state.value = 0;
481
- this._gamepads.delete(device);
482
- this.onGamepadDisconnected.notify({
483
- device,
484
- id: gamepad.id,
485
- standard: gamepad.mapping === "standard"
486
- });
185
+ this._down(`button${ev.button}`, "button", `button${ev.button}`, ev);
186
+ }
187
+ _onPointerUp(ev) {
188
+ if (ev.pointerType === "touch") this.emit(ev.type === "pointercancel" ? "touch_cancel" : "touch_up", ev);
189
+ if (!ev.isPrimary) return;
190
+ this._updatePointer(ev);
191
+ this._up(`button${ev.button}`, "button", `button${ev.button}`, "clicked", ev);
192
+ if (!this._anyButtonDown()) this._endDrag(ev);
193
+ }
194
+ _onPointerMove(ev) {
195
+ if (ev.pointerType === "touch") this.emit("touch_move", ev);
196
+ if (!ev.isPrimary) return;
197
+ this._updatePointer(ev);
198
+ if (ev.pointerType === "mouse" && ev.button >= 0) {
199
+ const id = `button${ev.button}`;
200
+ if (ev.buttons & BUTTON_BITS[ev.button]) this._down(id, "button", id, ev);
201
+ else this._up(id, "button", id, "clicked", ev);
487
202
  }
488
- }
489
- _updateGestures() {
490
- const frame = this.gestureRecognizer.update(now());
491
- this.gestures.pinch = frame.pinch;
492
- this.gestures.pan = frame.pan;
493
- this.gestures.rotate = frame.rotate;
494
- for (const name of frame.gestures) this._pulse(0, {
495
- type: "gesture",
496
- gesture: name
497
- });
498
- }
499
- _xrSession;
500
- _xrEnd;
501
- _xrHeld = /* @__PURE__ */ new Set();
502
- /** The session set by {@link Input.attachXR}, until detached or ended. */
503
- get xrSession() {
504
- return this._xrSession;
505
- }
506
- /**
507
- * Reads VR controller buttons and sticks from a WebXR session (e.g. `renderer.xr.getSession()`)
508
- * into the action map. Controller poses stay with three.js (`renderer.xr.getController(i)`).
509
- * XR controller state only updates during XR frames, so call update() from the XR animation
510
- * loop (`renderer.setAnimationLoop`). Detaches automatically when the session ends.
511
- */
512
- attachXR(session) {
513
- this.detachXR();
514
- this._xrSession = session;
515
- this._xrEnd = () => this.detachXR();
516
- session.addEventListener("end", this._xrEnd);
517
- }
518
- /** Stops reading the XR session and releases its controls. */
519
- detachXR() {
520
- if (this._xrSession && this._xrEnd) this._xrSession.removeEventListener("end", this._xrEnd);
521
- this._xrSession = void 0;
522
- this._xrEnd = void 0;
523
- this._releaseXR(/* @__PURE__ */ new Set());
524
- }
525
- _pollXR() {
526
- const session = this._xrSession;
527
- if (!session) return;
528
- const held = /* @__PURE__ */ new Set();
529
- let active = false;
530
- for (const source of session.inputSources) {
531
- const hand = source.handedness;
532
- const gamepad = source.gamepad;
533
- if (hand !== "left" && hand !== "right" || !gamepad) continue;
534
- for (let i = 0; i < XR_BUTTONS.length && i < gamepad.buttons.length; i++) {
535
- const button = gamepad.buttons[i];
536
- const value = button.value > 0 ? button.value : button.pressed ? 1 : 0;
537
- const binding = {
538
- type: "xr",
539
- hand,
540
- button: XR_BUTTONS[i]
541
- };
542
- this._setControl(0, binding, value);
543
- held.add(controlId(binding));
544
- active ||= value >= .5;
545
- }
546
- for (let i = 0; i < XR_AXES.length && i < gamepad.axes.length; i++) {
547
- const value = gamepad.axes[i];
548
- for (const direction of [1, -1]) {
549
- const binding = {
550
- type: "xrAxis",
551
- hand,
552
- axis: XR_AXES[i],
553
- direction
554
- };
555
- this._setControl(0, binding, Math.max(0, value * direction));
556
- held.add(controlId(binding));
557
- }
558
- active ||= Math.abs(value) >= .5;
203
+ if (this._dragStart && this._anyButtonDown()) {
204
+ if (!this._dragging && this.pointerPosition.distanceTo(this._dragStart) > this.dragThreshold) {
205
+ this._dragging = true;
206
+ this.emit("drag_start", ev);
559
207
  }
208
+ if (this._dragging) this.emit("drag", ev);
560
209
  }
561
- this._releaseXR(held);
562
- for (const id of held) this._xrHeld.add(id);
563
- if (active) this._setLastDevice("xr");
564
- }
565
- _releaseXR(keep) {
566
- const controls = this._controls.get(0);
567
- for (const id of this._xrHeld) {
568
- if (keep.has(id)) continue;
569
- const state = controls.get(id);
570
- if (state) state.value = 0;
571
- this._xrHeld.delete(id);
572
- }
573
- }
574
- _isBound(type, predicate) {
575
- for (const name of this.actions.names) if (this.actions.get(name).bindings.some((b) => b.type === type && predicate(b))) return true;
576
- return false;
210
+ this.emit("pointer_move", ev);
577
211
  }
578
- _onKeyDown(event) {
579
- if (isEditable(event.target)) return;
580
- if (this._options.preventDefault && this._isBound("key", (b) => b.type === "key" && b.code === event.code)) event.preventDefault();
581
- this._setLastDevice("keyboard");
582
- if (event.repeat) return;
583
- this._setControl(0, {
584
- type: "key",
585
- code: event.code
586
- }, 1);
212
+ _endDrag(ev) {
213
+ if (this._dragging) this.emit("drag_end", ev);
214
+ this._dragStart = void 0;
215
+ this._dragging = false;
587
216
  }
588
- _onKeyUp(event) {
589
- this._setControl(0, {
590
- type: "key",
591
- code: event.code
592
- }, 0);
217
+ _onWheel(ev) {
218
+ this.emit("mouse_wheel", ev);
593
219
  }
594
- _updatePointer(event) {
595
- const rect = this._target?.getBoundingClientRect?.();
596
- const left = rect?.left ?? 0;
597
- const top = rect?.top ?? 0;
598
- const width = rect?.width || 1;
599
- const height = rect?.height || 1;
600
- this.pointer.type = event.pointerType === "pen" ? "pen" : "mouse";
601
- this.pointer.x = event.clientX - left;
602
- this.pointer.y = event.clientY - top;
603
- this.pointer.ndcX = this.pointer.x / width * 2 - 1;
604
- this.pointer.ndcY = -(this.pointer.y / height * 2 - 1);
605
- this.pointer.pressure = event.pressure ?? 0;
606
- this.pointer.tiltX = event.tiltX ?? 0;
607
- this.pointer.tiltY = event.tiltY ?? 0;
220
+ _onBlur(ev) {
221
+ Object.values(this._state).forEach((s) => s.state = 0);
222
+ this._endDrag(ev);
223
+ this.emit("blur", ev);
608
224
  }
609
- _local(event) {
610
- const rect = this._target?.getBoundingClientRect?.();
611
- return {
612
- x: event.clientX - (rect?.left ?? 0),
613
- y: event.clientY - (rect?.top ?? 0)
614
- };
615
- }
616
- _onPointerDown(event) {
617
- if (event.pointerType === "touch") {
618
- const { x, y } = this._local(event);
619
- this.gestureRecognizer.down(event.pointerId, x, y, now());
620
- this._setLastDevice("touch");
621
- this._target?.setPointerCapture?.(event.pointerId);
622
- return;
623
- }
624
- this._updatePointer(event);
625
- this._setLastDevice(event.pointerType === "pen" ? "pen" : "mouse");
626
- const button = MOUSE_BUTTONS[event.button];
627
- if (button) this._setControl(0, {
628
- type: "mouse",
629
- button
630
- }, 1);
631
- this._target?.setPointerCapture?.(event.pointerId);
225
+ /** Whether a key (by `KeyboardEvent.code`, e.g. 'KeyW') is down. */
226
+ isKeyDown(keyCode) {
227
+ return this._state[keyCode]?.state === 1;
632
228
  }
633
- _onPointerUp(event) {
634
- if (event.pointerType === "touch") {
635
- const { x, y } = this._local(event);
636
- this.gestureRecognizer.up(event.pointerId, x, y, now());
637
- return;
638
- }
639
- this._updatePointer(event);
640
- const button = MOUSE_BUTTONS[event.button];
641
- if (button) this._setControl(0, {
642
- type: "mouse",
643
- button
644
- }, 0);
229
+ /** 1 if the key is down, else 0. */
230
+ getKeyState(keyCode) {
231
+ return this._state[keyCode]?.state ?? 0;
645
232
  }
646
- _onPointerCancel(event) {
647
- if (event.pointerType === "touch") this.gestureRecognizer.cancel(event.pointerId);
648
- else this._onPointerUp(event);
233
+ /** Whether a button (`PointerEvent.button`: 0 left / primary finger, 1 middle, 2 right, ...) is down. */
234
+ isButtonDown(buttonNumber) {
235
+ return this._state[`button${buttonNumber}`]?.state === 1;
649
236
  }
650
- _onPointerMove(event) {
651
- if (event.pointerType === "touch") {
652
- const { x, y } = this._local(event);
653
- this.gestureRecognizer.move(event.pointerId, x, y);
654
- return;
655
- }
656
- this._updatePointer(event);
657
- this._setLastDevice(event.pointerType === "pen" ? "pen" : "mouse");
658
- this._pending.deltaX += event.movementX ?? 0;
659
- this._pending.deltaY += event.movementY ?? 0;
660
- const button = MOUSE_BUTTONS[event.button];
661
- if (button) {
662
- const down = ((event.buttons ?? 0) & BUTTON_BITS[event.button]) !== 0;
663
- this._setControl(0, {
664
- type: "mouse",
665
- button
666
- }, down ? 1 : 0);
667
- }
668
- }
669
- _onWheel(event) {
670
- const scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 800 : 1;
671
- const dx = event.deltaX * scale;
672
- const dy = event.deltaY * scale;
673
- this._pending.wheelX += dx;
674
- this._pending.wheelY += dy;
675
- if (this._options.preventDefault && this._isBound("wheel", () => true)) event.preventDefault();
676
- if (dy < 0) this._pulse(0, {
677
- type: "wheel",
678
- direction: "up"
679
- });
680
- if (dy > 0) this._pulse(0, {
681
- type: "wheel",
682
- direction: "down"
683
- });
684
- if (dx < 0) this._pulse(0, {
685
- type: "wheel",
686
- direction: "left"
687
- });
688
- if (dx > 0) this._pulse(0, {
689
- type: "wheel",
690
- direction: "right"
691
- });
237
+ /** 1 if the button is down, else 0. */
238
+ getButtonState(buttonNumber) {
239
+ return this._state[`button${buttonNumber}`]?.state ?? 0;
692
240
  }
693
241
  };
694
242
  //#endregion