@n3rdw1z4rd/core 0.19.1 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.cts CHANGED
@@ -1066,7 +1066,7 @@ export declare function controlId(binding: Binding): string;
1066
1066
  export declare function bindingsEqual(a: Binding, b: Binding): boolean;
1067
1067
  /**
1068
1068
  * A readable name for a binding, e.g. for "Press Space to jump" prompts. Pass `keyLabels` (from
1069
- * {@link Input.loadKeyboardLayout}) to name keys as printed on the player's keyboard.
1069
+ * {@link InputActionMap.loadKeyboardLayout}) to name keys as printed on the player's keyboard.
1070
1070
  *
1071
1071
  * @category Input
1072
1072
  */
@@ -1079,6 +1079,38 @@ export declare function bindingLabel(binding: Binding, keyLabels?: ReadonlyMap<s
1079
1079
  * @category Input
1080
1080
  */
1081
1081
  export declare const DEFAULT_DEADZONE = 0.2;
1082
+ /**
1083
+ * Auto-repeat timing for a held action, in ms: like a held key in a text field, the action
1084
+ * presses again after `delay`, then every `interval`.
1085
+ *
1086
+ * @category Input
1087
+ */
1088
+ export interface ActionRepeat {
1089
+ /** ms held before the first repeat */
1090
+ delay: number;
1091
+ /** ms between repeats after that */
1092
+ interval: number;
1093
+ }
1094
+ /**
1095
+ * Repeat timing used by `repeat: true`: first repeat after 400 ms, then every 100 ms.
1096
+ *
1097
+ * @category Input
1098
+ */
1099
+ export declare const DEFAULT_REPEAT: Readonly<ActionRepeat>;
1100
+ /**
1101
+ * Options for {@link ActionMap.add}.
1102
+ *
1103
+ * @category Input
1104
+ */
1105
+ export interface ActionOptions {
1106
+ /** default {@link DEFAULT_DEADZONE} */
1107
+ deadzone?: number;
1108
+ /**
1109
+ * auto-repeat while held: `true` for {@link DEFAULT_REPEAT}, timings to override it, or `false`
1110
+ * for none (the default)
1111
+ */
1112
+ repeat?: boolean | Partial<ActionRepeat>;
1113
+ }
1082
1114
  /**
1083
1115
  * A named action in an {@link ActionMap}.
1084
1116
  *
@@ -1091,6 +1123,8 @@ export interface Action {
1091
1123
  deadzone: number;
1092
1124
  /** inputs that trigger the action; the strongest one wins */
1093
1125
  readonly bindings: Binding[];
1126
+ /** auto-repeat while held, see {@link InputActionMap.isActionJustPressed}; none if unset */
1127
+ repeat?: ActionRepeat;
1094
1128
  }
1095
1129
  /**
1096
1130
  * The serialized form of an {@link ActionMap} (from {@link ActionMap.toJSON}), keyed by action name.
@@ -1102,10 +1136,12 @@ export type ActionMapJSON = Record<string, {
1102
1136
  deadzone: number;
1103
1137
  /** the action's bindings, in order */
1104
1138
  bindings: Binding[];
1139
+ /** see {@link Action.repeat} */
1140
+ repeat?: ActionRepeat;
1105
1141
  }>;
1106
1142
  /**
1107
- * Named actions and the inputs bound to them, like Godot's InputMap. Every {@link Input} has one as
1108
- * {@link Input.actions}; the methods that change it return `this` for chaining.
1143
+ * Named actions and the inputs bound to them, like Godot's InputMap. Every {@link InputActionMap} has one as
1144
+ * {@link InputActionMap.actions}; the methods that change it return `this` for chaining.
1109
1145
  *
1110
1146
  * ```ts
1111
1147
  * input.actions
@@ -1125,10 +1161,8 @@ export declare class ActionMap {
1125
1161
  has(name: string): boolean;
1126
1162
  /** The action with this name, or `undefined`. */
1127
1163
  get(name: string): Action | undefined;
1128
- /** Adds an action, or replaces its bindings (and deadzone, if given) if it exists. */
1129
- add(name: string, bindings?: Binding[], options?: {
1130
- deadzone?: number;
1131
- }): this;
1164
+ /** Adds an action, or replaces its bindings (and deadzone / repeat, if given) if it exists. */
1165
+ add(name: string, bindings?: Binding[], options?: ActionOptions): this;
1132
1166
  /** Removes an action, if it exists. */
1133
1167
  remove(name: string): this;
1134
1168
  /** Adds a binding to an action (creating the action if needed); duplicates are ignored. */
@@ -1145,7 +1179,8 @@ export declare class ActionMap {
1145
1179
  load(json: ActionMapJSON): this;
1146
1180
  /**
1147
1181
  * Godot-style `ui_*` actions for menus and dialogs (`ui_accept`, `ui_cancel`, `ui_left`, `ui_right`,
1148
- * `ui_up`, `ui_down`, `ui_page_up`, `ui_page_down`), with a 0.5 deadzone; replaces existing ones.
1182
+ * `ui_up`, `ui_down`, `ui_page_up`, `ui_page_down`), with a 0.5 deadzone; the directions and
1183
+ * page actions auto-repeat ({@link DEFAULT_REPEAT}). Replaces existing ones.
1149
1184
  */
1150
1185
  addDefaults(): this;
1151
1186
  }
@@ -1193,6 +1228,21 @@ export interface GestureThresholds {
1193
1228
  /** relative scale change per frame that counts as pinching (0.005 = 0.5%, the default) */
1194
1229
  pinchMinChange: number;
1195
1230
  }
1231
+ /**
1232
+ * A recognized gesture and where it happened, in pixels: where the finger lifted for a tap or
1233
+ * double tap, where it is held for a long press, where it started for a swipe, and the midpoint
1234
+ * of the two fingers for a pinch.
1235
+ *
1236
+ * @category Input
1237
+ */
1238
+ export interface GestureEvent {
1239
+ /** which gesture */
1240
+ gesture: Gesture;
1241
+ /** px */
1242
+ x: number;
1243
+ /** px */
1244
+ y: number;
1245
+ }
1196
1246
  /**
1197
1247
  * What {@link GestureRecognizer.update} recognized since the previous update.
1198
1248
  *
@@ -1201,6 +1251,8 @@ export interface GestureThresholds {
1201
1251
  export interface GestureFrame {
1202
1252
  /** recognized since the last update */
1203
1253
  gestures: Gesture[];
1254
+ /** the same gestures, with positions */
1255
+ events: GestureEvent[];
1204
1256
  /** two-finger scale change this frame (1 = none, > 1 = fingers apart) */
1205
1257
  pinch: number;
1206
1258
  /** two-finger movement this frame, px */
@@ -1216,7 +1268,7 @@ export interface GestureFrame {
1216
1268
  /**
1217
1269
  * Turns touch points into gestures: tap, double tap, long press, swipes (one finger) and
1218
1270
  * pinch / pan / rotate (two fingers). Feed it with down / move / up, call update() once per frame.
1219
- * Times are in ms and positions in pixels, from any consistent clock and origin. {@link Input} drives
1271
+ * Times are in ms and positions in pixels, from any consistent clock and origin. {@link InputActionMap} drives
1220
1272
  * one for you; use this class directly only for custom touch handling.
1221
1273
  *
1222
1274
  * Tap, double tap and swipe are reported when the finger lifts, long press while it is still held;
@@ -1227,7 +1279,8 @@ export interface GestureFrame {
1227
1279
  * el.addEventListener('pointerdown', e => recognizer.down(e.pointerId, e.offsetX, e.offsetY, performance.now()));
1228
1280
  * // ... move / up / cancel likewise
1229
1281
  *
1230
- * const { gestures, pinch } = recognizer.update(performance.now());
1282
+ * const { gestures, events, pinch } = recognizer.update(performance.now());
1283
+ * const tap = events.find(e => e.gesture === 'tap'); // { gesture, x, y }
1231
1284
  * ```
1232
1285
  *
1233
1286
  * @category Input
@@ -1257,6 +1310,106 @@ export declare class GestureRecognizer {
1257
1310
  update(time: number): GestureFrame;
1258
1311
  }
1259
1312
  //#endregion
1313
+ //#region src/input/input.d.ts
1314
+ /**
1315
+ * Whether a key or button is down (`state` 1) or up (0), and when that last changed.
1316
+ *
1317
+ * @category Input
1318
+ */
1319
+ export interface InputState {
1320
+ /** 1 = down, 0 = up */
1321
+ state: number;
1322
+ /** `Event.timeStamp` of the last change, ms */
1323
+ timeStamp: number;
1324
+ }
1325
+ /**
1326
+ * Event-based input for keyboard, mouse, pen and touch: subscribe with `on()` and query state
1327
+ * at any time; no frame loop needed. One shared instance, {@link Input.instance}.
1328
+ *
1329
+ * Events (listeners get the DOM event):
1330
+ * - keys, by lowercased `KeyboardEvent.code`: `key_down`, `key_up`, `key_repeat`, `key_pressed`
1331
+ * (released within `inputThreshold` ms), and per key `keyw_down`, `keyw_up`, `keyw_pressed`, ...
1332
+ * - buttons (mouse buttons; the primary finger or pen is button 0): `button_down`, `button_up`,
1333
+ * `button_clicked`, and per button `button0_down`, `button0_up`, `button0_clicked`, ...
1334
+ * No click after a drag.
1335
+ * - pointer: `pointer_move`; `drag_start`, `drag`, `drag_end` (moved `dragThreshold` px with a
1336
+ * button down); `mouse_wheel`; `contextmenu` (see `disableContextMenu()`)
1337
+ * - every finger: `touch_down`, `touch_move`, `touch_up`, `touch_cancel`
1338
+ * - `blur`: the window lost focus or the tab was hidden; every key and button is released
1339
+ *
1340
+ * ```ts
1341
+ * const input = Input.instance;
1342
+ * input.target = canvas;
1343
+ *
1344
+ * input.on('keyw_down', 'arrowup_down', () => move(0, -1));
1345
+ * input.on('button0_clicked', () => select(input.pointerPosition));
1346
+ * input.on('pointer_move', () => {
1347
+ * if (input.isButtonDown(0)) pan(input.pointerDelta.x, input.pointerDelta.y);
1348
+ * });
1349
+ * ```
1350
+ *
1351
+ * @category Input
1352
+ */
1353
+ export declare class Input extends Emitter {
1354
+ private static _instance?;
1355
+ /** the shared instance, created on first use */
1356
+ static get instance(): Input;
1357
+ private _state;
1358
+ private _windowListeners;
1359
+ private _targetListeners;
1360
+ private _target;
1361
+ private _contextMenuDisabled;
1362
+ private _dragStart?;
1363
+ private _dragging;
1364
+ /** pixels from the target's top-left */
1365
+ readonly pointerPosition: Vector;
1366
+ /** -1..1 across the target, y up */
1367
+ readonly pointerPositionNdc: Vector;
1368
+ /** pixels moved by the last pointer event (mouse, pen and touch alike) */
1369
+ readonly pointerDelta: Vector;
1370
+ /** ms; a key or button released within this is also `_pressed` / `_clicked` */
1371
+ inputThreshold: number;
1372
+ /** px; moving further than this with a button down starts a drag */
1373
+ dragThreshold: number;
1374
+ /**
1375
+ * Where pointer, wheel and context-menu events are read and positions are measured, default
1376
+ * `window`; usually the canvas. Keys are always read from `window`.
1377
+ */
1378
+ get target(): EventTarget;
1379
+ /** moves the pointer, wheel and context-menu listeners to `target` */
1380
+ set target(target: EventTarget);
1381
+ /** a drag is in progress */
1382
+ get isDragging(): boolean;
1383
+ private constructor();
1384
+ /** Stops the right-click menu on the target; `contextmenu` is still emitted. */
1385
+ disableContextMenu(): void;
1386
+ /** Removes every DOM listener; the next {@link Input.instance} is a new one. */
1387
+ dispose(): void;
1388
+ private _listenToTarget;
1389
+ private _listen;
1390
+ private _down;
1391
+ private _up;
1392
+ private _anyButtonDown;
1393
+ private _updatePointer;
1394
+ private _onContextMenu;
1395
+ private _onKeyDown;
1396
+ private _onKeyUp;
1397
+ private _onPointerDown;
1398
+ private _onPointerUp;
1399
+ private _onPointerMove;
1400
+ private _endDrag;
1401
+ private _onWheel;
1402
+ private _onBlur;
1403
+ /** Whether a key (by `KeyboardEvent.code`, e.g. 'KeyW') is down. */
1404
+ isKeyDown(keyCode: string): boolean;
1405
+ /** 1 if the key is down, else 0. */
1406
+ getKeyState(keyCode: string): number;
1407
+ /** Whether a button (`PointerEvent.button`: 0 left / primary finger, 1 middle, 2 right, ...) is down. */
1408
+ isButtonDown(buttonNumber: number): boolean;
1409
+ /** 1 if the button is down, else 0. */
1410
+ getButtonState(buttonNumber: number): number;
1411
+ }
1412
+ //#endregion
1260
1413
  //#region src/observable.d.ts
1261
1414
  /**
1262
1415
  * An {@link Observable} observer: called with the notified value (and any extra arguments).
@@ -1300,7 +1453,7 @@ export declare class Observable<T> {
1300
1453
  get size(): number;
1301
1454
  }
1302
1455
  //#endregion
1303
- //#region src/input/input.d.ts
1456
+ //#region src/input/input-action-map.d.ts
1304
1457
  /**
1305
1458
  * 0 = keyboard, mouse, pen, touch and VR; 1, 2, ... = gamepads.
1306
1459
  *
@@ -1308,25 +1461,36 @@ export declare class Observable<T> {
1308
1461
  */
1309
1462
  export type InputDevice = number;
1310
1463
  /**
1311
- * The kind of device the player last used, see {@link Input.lastDevice}.
1464
+ * The kind of device the player last used, see {@link InputActionMap.lastDevice}.
1312
1465
  *
1313
1466
  * @category Input
1314
1467
  */
1315
1468
  export type InputDeviceType = 'keyboard' | 'mouse' | 'pen' | 'touch' | 'gamepad' | 'xr';
1316
1469
  /**
1317
- * When an {@link Input.onAction} callback fires: as the action becomes pressed, or released.
1470
+ * When an {@link InputActionMap.onAction} callback fires: as the action becomes pressed, or released.
1318
1471
  *
1319
1472
  * @category Input
1320
1473
  */
1321
1474
  export type ActionPhase = 'pressed' | 'released';
1322
1475
  /**
1323
- * Options for the {@link Input} constructor.
1476
+ * Passed to {@link InputActionMap.onAction} callbacks.
1477
+ *
1478
+ * @category Input
1479
+ */
1480
+ export interface ActionEvent {
1481
+ /** the action's name */
1482
+ action: string;
1483
+ /** an auto-repeat of a held action (see {@link ActionRepeat}), not a new press */
1484
+ repeat: boolean;
1485
+ }
1486
+ /**
1487
+ * Options for the {@link InputActionMap} constructor.
1324
1488
  *
1325
1489
  * @category Input
1326
1490
  */
1327
- export interface InputOptions {
1328
- /** where key events are read; default: window */
1329
- keyboardTarget?: EventTarget;
1491
+ export interface InputActionMapOptions {
1492
+ /** where events come from, default {@link Input.instance}; set `input.target` to the canvas */
1493
+ input?: Input;
1330
1494
  /** add the ui_* actions. Default true. */
1331
1495
  defaults?: boolean;
1332
1496
  /** stop bound keys / the wheel from scrolling the page. Default true. */
@@ -1344,7 +1508,7 @@ export interface DeviceQuery {
1344
1508
  device?: InputDevice;
1345
1509
  }
1346
1510
  /**
1347
- * A connected gamepad, see {@link Input.gamepads}.
1511
+ * A connected gamepad, see {@link InputActionMap.gamepads}.
1348
1512
  *
1349
1513
  * @category Input
1350
1514
  */
@@ -1357,7 +1521,7 @@ export interface GamepadInfo {
1357
1521
  standard: boolean;
1358
1522
  }
1359
1523
  /**
1360
- * The parts of a WebXR XRSession that Input reads (structural, so no WebXR typings are required).
1524
+ * The parts of a WebXR XRSession that InputActionMap reads (structural, so no WebXR typings are required).
1361
1525
  *
1362
1526
  * @category Input
1363
1527
  */
@@ -1381,8 +1545,8 @@ export interface XRSessionLike extends EventTarget {
1381
1545
  }>;
1382
1546
  }
1383
1547
  /**
1384
- * Mouse or pen state, see {@link Input.pointer}. Positions update on pointer events; deltas and
1385
- * wheel totals on each {@link Input.update}.
1548
+ * Mouse or pen state, see {@link InputActionMap.pointer}. Positions update on pointer events; deltas and
1549
+ * wheel totals on each {@link InputActionMap.update}.
1386
1550
  *
1387
1551
  * @property y pixels, relative to the target's top-left, y down
1388
1552
  * @property ndcY -1..1, y up
@@ -1414,7 +1578,7 @@ export interface PointerState {
1414
1578
  tiltY: number;
1415
1579
  }
1416
1580
  /**
1417
- * Options for {@link Input.captureBinding}.
1581
+ * Options for {@link InputActionMap.captureBinding}.
1418
1582
  *
1419
1583
  * @category Input
1420
1584
  */
@@ -1425,32 +1589,41 @@ export interface CaptureOptions {
1425
1589
  types?: Binding['type'][];
1426
1590
  }
1427
1591
  /**
1428
- * Game input with a Godot-style action map: bind keys, buttons, sticks, gestures and VR controls
1429
- * to named actions, then query actions instead of devices.
1592
+ * Game input with a Godot-style action map, built on {@link Input}'s events: bind keys, buttons,
1593
+ * sticks, gestures and VR controls to named actions, then query actions instead of devices once
1594
+ * per frame. Gamepads and VR controllers are polled by `update()`.
1595
+ *
1596
+ * Input.instance.target = canvas;
1430
1597
  *
1431
- * const input = new Input(canvas);
1432
- * input.actions.add('jump', [key('Space'), pad('A')]);
1598
+ * const controls = new InputActionMap();
1599
+ * controls.actions.add('jump', [key('Space'), pad('A')]);
1433
1600
  *
1434
1601
  * // every frame, before game logic:
1435
- * input.update();
1436
- * if (input.isActionJustPressed('jump')) player.jump();
1602
+ * controls.update();
1603
+ * if (controls.isActionJustPressed('jump')) player.jump();
1437
1604
  *
1438
- * Call `dispose()` to remove all listeners.
1605
+ * Call `dispose()` to stop listening.
1439
1606
  *
1440
1607
  * @category Input
1441
1608
  */
1442
- export declare class Input {
1443
- /** the actions to query; holds the `ui_*` defaults unless {@link InputOptions.defaults} is false */
1609
+ export declare class InputActionMap {
1610
+ /** the actions to query; holds the `ui_*` defaults unless {@link InputActionMapOptions.defaults} is false */
1444
1611
  readonly actions: ActionMap;
1445
1612
  /** Thresholds for taps, swipes etc. can be tuned via `gestureRecognizer.thresholds`. */
1446
1613
  readonly gestureRecognizer: GestureRecognizer;
1447
- /** Two-finger gesture values for the last frame (pinch 1 / pan 0 / rotate 0 when not gesturing). */
1614
+ /**
1615
+ * Touch gestures from the last frame: `events` (each recognized gesture and where it happened,
1616
+ * e.g. the tap that triggered an action) and the two-finger values (pinch 1 / pan 0 / rotate 0
1617
+ * when not gesturing).
1618
+ */
1448
1619
  readonly gestures: Omit<GestureFrame, 'gestures'>;
1620
+ /** the {@link Input} events are read from */
1621
+ readonly input: Input;
1449
1622
  /** Fingers currently on the target. */
1450
1623
  get touches(): TouchPoint[];
1451
1624
  /** the mouse or pen; not updated by touch */
1452
1625
  readonly pointer: PointerState;
1453
- /** notified when {@link Input.lastDevice} changes, e.g. to switch on-screen button prompts */
1626
+ /** notified when {@link InputActionMap.lastDevice} changes, e.g. to switch on-screen button prompts */
1454
1627
  readonly onDeviceChange: Observable<InputDeviceType>;
1455
1628
  /** notified from update() when a gamepad is first seen */
1456
1629
  readonly onGamepadConnected: Observable<GamepadInfo>;
@@ -1461,7 +1634,6 @@ export declare class Input {
1461
1634
  get gamepads(): GamepadInfo[];
1462
1635
  private _lastDevice;
1463
1636
  private _keyLabels?;
1464
- private readonly _target?;
1465
1637
  private readonly _options;
1466
1638
  private readonly _listeners;
1467
1639
  private readonly _controls;
@@ -1472,21 +1644,26 @@ export declare class Input {
1472
1644
  private _capture?;
1473
1645
  /** The kind of device that produced the most recent input (initially `'keyboard'`). */
1474
1646
  get lastDevice(): InputDeviceType;
1475
- /** Whether the pointer is locked to the target, see {@link Input.lockPointer}. */
1647
+ /** Whether the pointer is locked to the target, see {@link InputActionMap.lockPointer}. */
1476
1648
  get isPointerLocked(): boolean;
1477
- /**
1478
- * @param target element that receives pointer, wheel and touch input (usually the canvas)
1479
- */
1480
- constructor(target?: EventTarget, options?: InputOptions);
1649
+ constructor(options?: InputActionMapOptions);
1481
1650
  /**
1482
1651
  * Call once per frame, before reading input: polls devices and advances "just pressed" /
1483
1652
  * "just released" by one frame. Action callbacks fire from here.
1653
+ *
1654
+ * @param time current time in ms (e.g. the `requestAnimationFrame` timestamp), used for
1655
+ * gesture timing and auto-repeat; default `performance.now()`
1484
1656
  */
1485
- update(): void;
1657
+ update(time?: number): void;
1486
1658
  /** Whether the action is held past its deadzone. Unknown actions return false (and warn once). */
1487
1659
  isActionPressed(action: string, query?: DeviceQuery): boolean;
1488
- /** Whether the action became pressed in the last update(). */
1660
+ /**
1661
+ * Whether the action became pressed in the last update(), or auto-repeated while held if the
1662
+ * action has {@link Action.repeat} (e.g. to keep walking while a direction is held).
1663
+ */
1489
1664
  isActionJustPressed(action: string, query?: DeviceQuery): boolean;
1665
+ /** Whether the last update()'s press of the action was an auto-repeat rather than a new press. */
1666
+ isActionRepeated(action: string, query?: DeviceQuery): boolean;
1490
1667
  /** Whether the action was released in the last update(). */
1491
1668
  isActionJustReleased(action: string, query?: DeviceQuery): boolean;
1492
1669
  /** 0..1, rescaled past the action's deadzone (analog triggers and sticks give values in between). */
@@ -1510,8 +1687,12 @@ export declare class Input {
1510
1687
  /** -1..1, positive towards `positiveY` */
1511
1688
  y: number;
1512
1689
  };
1513
- /** Calls `callback` when the action is pressed or released (during update()). Returns an unsubscribe function. */
1514
- onAction(action: string, phase: ActionPhase, callback: () => void, query?: DeviceQuery): () => void;
1690
+ /**
1691
+ * Calls `callback` when the action is pressed or released (during update()). With
1692
+ * {@link Action.repeat}, `'pressed'` also fires on each auto-repeat, with `event.repeat` set.
1693
+ * Returns an unsubscribe function.
1694
+ */
1695
+ onAction(action: string, phase: ActionPhase, callback: (event: ActionEvent) => void, query?: DeviceQuery): () => void;
1515
1696
  /** Whether a key (by `KeyboardEvent.code`) is held right now, regardless of actions. */
1516
1697
  isKeyPressed(code: string): boolean;
1517
1698
  /** Whether a mouse or pen button is held right now, regardless of actions. */
@@ -1531,14 +1712,14 @@ export declare class Input {
1531
1712
  * doesn't trigger any actions.
1532
1713
  */
1533
1714
  captureBinding(options?: CaptureOptions): Promise<Binding | null>;
1534
- /** Ends a pending {@link Input.captureBinding}, resolving it with `null`. */
1715
+ /** Ends a pending {@link InputActionMap.captureBinding}, resolving it with `null`. */
1535
1716
  cancelCapture(): void;
1536
1717
  /**
1537
1718
  * Loads the keyboard layout (where supported, e.g. Chromium) so {@link bindingLabel} names keys
1538
1719
  * as printed on the player's keyboard: KeyW is "Z" on AZERTY.
1539
1720
  */
1540
1721
  loadKeyboardLayout(): Promise<ReadonlyMap<string, string> | undefined>;
1541
- /** The layout loaded by {@link Input.loadKeyboardLayout}, if any: `KeyboardEvent.code` to printed key. */
1722
+ /** The layout loaded by {@link InputActionMap.loadKeyboardLayout}, if any: `KeyboardEvent.code` to printed key. */
1542
1723
  get keyLabels(): ReadonlyMap<string, string> | undefined;
1543
1724
  /** Removes all event listeners and action callbacks, cancels any capture and detaches XR. */
1544
1725
  dispose(): void;
@@ -1568,7 +1749,7 @@ export declare class Input {
1568
1749
  private _xrSession?;
1569
1750
  private _xrEnd?;
1570
1751
  private readonly _xrHeld;
1571
- /** The session set by {@link Input.attachXR}, until detached or ended. */
1752
+ /** The session set by {@link InputActionMap.attachXR}, until detached or ended. */
1572
1753
  get xrSession(): XRSessionLike | undefined;
1573
1754
  /**
1574
1755
  * Reads VR controller buttons and sticks from a WebXR session (e.g. `renderer.xr.getSession()`)
@@ -1586,10 +1767,11 @@ export declare class Input {
1586
1767
  private _onKeyUp;
1587
1768
  private _updatePointer;
1588
1769
  private _local;
1589
- private _onPointerDown;
1590
- private _onPointerUp;
1591
- private _onPointerCancel;
1770
+ private _onButton;
1592
1771
  private _onPointerMove;
1772
+ private _onTouchDown;
1773
+ private _onTouchMove;
1774
+ private _onTouchUp;
1593
1775
  private _onWheel;
1594
1776
  }
1595
1777
  //#endregion
package/dist/index.d.ts CHANGED
@@ -13,10 +13,11 @@ import { Component, ComponentInstances, ComponentType, ECS, Entity, System, ecs
13
13
  import { Emitter, Listener } from "./emitter.js";
14
14
  import { EventQueue } from "./event-queue.js";
15
15
  import { Binding, GAMEPAD_AXES, GAMEPAD_BUTTONS, GESTURES, GamepadAxis, GamepadButton, Gesture, GestureBinding, KeyBinding, KeyModifiers, MouseBinding, MouseButton, PadAxisBinding, PadBinding, WheelBinding, WheelDirection, XRAxis, XRAxisBinding, XRBinding, XRButton, XRHand, XR_AXES, XR_BUTTONS, bindingLabel, bindingsEqual, controlId, gesture, key, mouse, pad, padAxis, wheel, xr, xrAxis } from "./input/bindings.js";
16
- import { Action, ActionMap, ActionMapJSON, DEFAULT_DEADZONE } from "./input/action-map.js";
17
- import { GestureFrame, GestureRecognizer, GestureThresholds, TouchPoint } from "./input/gestures.js";
16
+ import { Action, ActionMap, ActionMapJSON, ActionOptions, ActionRepeat, DEFAULT_DEADZONE, DEFAULT_REPEAT } from "./input/action-map.js";
17
+ import { GestureEvent, GestureFrame, GestureRecognizer, GestureThresholds, TouchPoint } from "./input/gestures.js";
18
+ import { Input, InputState } from "./input/input.js";
18
19
  import { Observable, Observer } from "./observable.js";
19
- import { ActionPhase, CaptureOptions, DeviceQuery, GamepadInfo, Input, InputDevice, InputDeviceType, InputOptions, PointerState, XRSessionLike } from "./input/input.js";
20
+ import { ActionEvent, ActionPhase, CaptureOptions, DeviceQuery, GamepadInfo, InputActionMap, InputActionMapOptions, InputDevice, InputDeviceType, PointerState, XRSessionLike } from "./input/input-action-map.js";
20
21
  import { log } from "./log.js";
21
22
  import { DEFAULT_MAP_3D_VALUE, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map3D, Map3DCell } from "./map3d.js";
22
23
  import { DEG2RAD, E, EPSILON, HALF_PI, LN10, LN2, LOG10E, LOG2E, PI, QUARTER_PI, RAD2DEG, SQRT1_2, SQRT2, TAU, clamp, degrees, distance2d, distance3d, fract, hash32, hash32mix, inverseLerp, lerp, manhattanDistance, mod, nearlyEqual, normalizeRadians, radians, roundTo, saturate, smoothstep, squaredDistance, wrap } from "./math.js";
@@ -32,4 +33,4 @@ import { Tilemap } from "./tilemap.js";
32
33
  import { AttributeInfo, AttributeSource, BindRenderTarget, BufferOptions, CompileShader, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, Draw, DrawOptions, GetProgramLocations, LoadWebGlTexture, ProgramInfo, ProgramLocations, RenderTarget, RenderTargetOptions, ResizeRenderTarget, ResizeWebGlContext, SetUniforms, ShaderType, TextureData, TextureInfo, TextureOptions, UniformInfo, UniformValue, UpdateBuffer, UpdateTexture, VertexArrayInfo } from "./webgl.js";
33
34
  import { RendererParams, WebGlRenderer } from "./webgl-renderer.js";
34
35
  import { WorkerInterface } from "./worker-interface.js";
35
- export { Action, ActionMap, ActionMapJSON, ActionPhase, AttributeInfo, AttributeSource, BindRenderTarget, Binding, BufferOptions, CanvasColor, CanvasRenderer, CaptureOptions, Clock, ClockCallback, Color, ColorPalette, CompileShader, Component, ComponentInstances, ComponentType, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DEFAULT_COLOR, DEFAULT_DEADZONE, DEFAULT_FONT, DEFAULT_FONT_NAME, DEFAULT_FONT_SIZE, DEFAULT_MAP_2D_VALUE, DEFAULT_MAP_3D_VALUE, DEFAULT_PIXEL_SIZE, DEFAULT_TEXTALIGN, DEFAULT_TEXTBASELINE, DEG2RAD, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, DeviceQuery, Disposable, DoorsParams, Draw, DrawOptions, DrawParams, E, ECS, EPSILON, Emitter, Entity, EventQueue, GAMEPAD_AXES, GAMEPAD_BUTTONS, GESTURES, GamepadAxis, GamepadButton, GamepadInfo, GenerateDoors, GenerateRooms, GenerateRoomsParams, GenerateWalls, Gesture, GestureBinding, GestureFrame, GestureRecognizer, GestureThresholds, GetProgramLocations, GetUrlParams, HALF_PI, Input, InputDevice, InputDeviceType, InputOptions, KeyBinding, KeyModifiers, KeyValue, LN10, LN2, LOG10E, LOG2E, Listener, LoadWebGlTexture, MAP_2D_MAX_COORD, MAP_2D_MIN_COORD, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map2D, Map2DData, Map3D, Map3DCell, MouseBinding, MouseButton, NoiseFunction3D, ONE_SECOND, Observable, Observer, PI, PadAxisBinding, PadBinding, ParticleRenderer, ParticleSystem2d, PathOptions, PathsParams, PointPair, PointerState, ProgramInfo, ProgramLocations, QUARTER_PI, RAD2DEG, RGB, Random, RectPair, Rectangle, RenderTarget, RenderTargetOptions, RendererParams, ResizeRenderTarget, ResizeWebGlContext, Rng, RoomsParams, SQRT1_2, SQRT2, SetUniforms, ShaderType, Signal, SpatialPartition2d, SpatialPartition3d, SpatialPartitionEntity2d, SpatialPartitionEntity3d, SpriteParams, StepCost, Subscriber, System, TAU, TILE_EMPTY, TILE_FLOOR, TILE_PATH, TextureData, TextureInfo, TextureOptions, Tilemap, TouchPoint, UniformInfo, UniformValue, UpdateBuffer, UpdateTexture, Vector, VertexArrayInfo, WebGlRenderer, WheelBinding, WheelDirection, WorkerInterface, XRAxis, XRAxisBinding, XRBinding, XRButton, XRHand, XRSessionLike, XR_AXES, XR_BUTTONS, XY, XYZ, bindingLabel, bindingsEqual, buildColorPalette, clamp, controlId, degrees, distance2d, distance3d, ecs, findPath, fract, gesture, getRedYellowGreenGradientHex, hash32, hash32mix, inverseLerp, isNullOrUndefined, isPositiveString, k2xy, k2xyz, key, lerp, log, manhattanDistance, mod, mouse, nearlyEqual, normalizeRadians, pad, padAxis, radians, randomMatrix, rng, roundTo, saturate, smoothstep, squaredDistance, wheel, wrap, xr, xrAxis, xy2k, xyz2k };
36
+ export { Action, ActionEvent, ActionMap, ActionMapJSON, ActionOptions, ActionPhase, ActionRepeat, AttributeInfo, AttributeSource, BindRenderTarget, Binding, BufferOptions, CanvasColor, CanvasRenderer, CaptureOptions, Clock, ClockCallback, Color, ColorPalette, CompileShader, Component, ComponentInstances, ComponentType, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DEFAULT_COLOR, DEFAULT_DEADZONE, DEFAULT_FONT, DEFAULT_FONT_NAME, DEFAULT_FONT_SIZE, DEFAULT_MAP_2D_VALUE, DEFAULT_MAP_3D_VALUE, DEFAULT_PIXEL_SIZE, DEFAULT_REPEAT, DEFAULT_TEXTALIGN, DEFAULT_TEXTBASELINE, DEG2RAD, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, DeviceQuery, Disposable, DoorsParams, Draw, DrawOptions, DrawParams, E, ECS, EPSILON, Emitter, Entity, EventQueue, GAMEPAD_AXES, GAMEPAD_BUTTONS, GESTURES, GamepadAxis, GamepadButton, GamepadInfo, GenerateDoors, GenerateRooms, GenerateRoomsParams, GenerateWalls, Gesture, GestureBinding, GestureEvent, GestureFrame, GestureRecognizer, GestureThresholds, GetProgramLocations, GetUrlParams, HALF_PI, Input, InputActionMap, InputActionMapOptions, InputDevice, InputDeviceType, InputState, KeyBinding, KeyModifiers, KeyValue, LN10, LN2, LOG10E, LOG2E, Listener, LoadWebGlTexture, MAP_2D_MAX_COORD, MAP_2D_MIN_COORD, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map2D, Map2DData, Map3D, Map3DCell, MouseBinding, MouseButton, NoiseFunction3D, ONE_SECOND, Observable, Observer, PI, PadAxisBinding, PadBinding, ParticleRenderer, ParticleSystem2d, PathOptions, PathsParams, PointPair, PointerState, ProgramInfo, ProgramLocations, QUARTER_PI, RAD2DEG, RGB, Random, RectPair, Rectangle, RenderTarget, RenderTargetOptions, RendererParams, ResizeRenderTarget, ResizeWebGlContext, Rng, RoomsParams, SQRT1_2, SQRT2, SetUniforms, ShaderType, Signal, SpatialPartition2d, SpatialPartition3d, SpatialPartitionEntity2d, SpatialPartitionEntity3d, SpriteParams, StepCost, Subscriber, System, TAU, TILE_EMPTY, TILE_FLOOR, TILE_PATH, TextureData, TextureInfo, TextureOptions, Tilemap, TouchPoint, UniformInfo, UniformValue, UpdateBuffer, UpdateTexture, Vector, VertexArrayInfo, WebGlRenderer, WheelBinding, WheelDirection, WorkerInterface, XRAxis, XRAxisBinding, XRBinding, XRButton, XRHand, XRSessionLike, XR_AXES, XR_BUTTONS, XY, XYZ, bindingLabel, bindingsEqual, buildColorPalette, clamp, controlId, degrees, distance2d, distance3d, ecs, findPath, fract, gesture, getRedYellowGreenGradientHex, hash32, hash32mix, inverseLerp, isNullOrUndefined, isPositiveString, k2xy, k2xyz, key, lerp, log, manhattanDistance, mod, mouse, nearlyEqual, normalizeRadians, pad, padAxis, radians, randomMatrix, rng, roundTo, saturate, smoothstep, squaredDistance, wheel, wrap, xr, xrAxis, xy2k, xyz2k };
package/dist/index.js CHANGED
@@ -16,10 +16,11 @@ import { ECS, ecs } from "./ecs.js";
16
16
  import { Emitter } from "./emitter.js";
17
17
  import { EventQueue } from "./event-queue.js";
18
18
  import { GAMEPAD_AXES, GAMEPAD_BUTTONS, GESTURES, XR_AXES, XR_BUTTONS, bindingLabel, bindingsEqual, controlId, gesture, key, mouse, pad, padAxis, wheel, xr, xrAxis } from "./input/bindings.js";
19
- import { ActionMap, DEFAULT_DEADZONE } from "./input/action-map.js";
19
+ import { ActionMap, DEFAULT_DEADZONE, DEFAULT_REPEAT } from "./input/action-map.js";
20
20
  import { GestureRecognizer } from "./input/gestures.js";
21
- import { Observable } from "./observable.js";
22
21
  import { Input } from "./input/input.js";
22
+ import { Observable } from "./observable.js";
23
+ import { InputActionMap } from "./input/input-action-map.js";
23
24
  import { DEFAULT_MAP_3D_VALUE, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map3D } from "./map3d.js";
24
25
  import { GetUrlParams, getRedYellowGreenGradientHex, isNullOrUndefined, isPositiveString, k2xy, k2xyz, xy2k, xyz2k } from "./misc.js";
25
26
  import { ParticleRenderer } from "./particle-renderer.js";
@@ -31,4 +32,4 @@ import { Tilemap } from "./tilemap.js";
31
32
  import { BindRenderTarget, CompileShader, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, Draw, GetProgramLocations, LoadWebGlTexture, ResizeRenderTarget, ResizeWebGlContext, SetUniforms, ShaderType, UpdateBuffer, UpdateTexture } from "./webgl.js";
32
33
  import { WebGlRenderer } from "./webgl-renderer.js";
33
34
  import { WorkerInterface } from "./worker-interface.js";
34
- export { ActionMap, BindRenderTarget, CanvasRenderer, Clock, Color, CompileShader, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DEFAULT_COLOR, DEFAULT_DEADZONE, DEFAULT_FONT, DEFAULT_FONT_NAME, DEFAULT_FONT_SIZE, DEFAULT_MAP_2D_VALUE, DEFAULT_MAP_3D_VALUE, DEFAULT_PIXEL_SIZE, DEFAULT_TEXTALIGN, DEFAULT_TEXTBASELINE, DEG2RAD, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, Disposable, Draw, E, ECS, EPSILON, Emitter, EventQueue, GAMEPAD_AXES, GAMEPAD_BUTTONS, GESTURES, GenerateDoors, GenerateRooms, GenerateWalls, GestureRecognizer, GetProgramLocations, GetUrlParams, HALF_PI, Input, LN10, LN2, LOG10E, LOG2E, LoadWebGlTexture, MAP_2D_MAX_COORD, MAP_2D_MIN_COORD, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map2D, Map3D, ONE_SECOND, Observable, PI, ParticleRenderer, ParticleSystem2d, QUARTER_PI, RAD2DEG, Random, Rectangle, ResizeRenderTarget, ResizeWebGlContext, Rng, SQRT1_2, SQRT2, SetUniforms, ShaderType, Signal, SpatialPartition2d, SpatialPartition3d, TAU, TILE_EMPTY, TILE_FLOOR, TILE_PATH, Tilemap, UpdateBuffer, UpdateTexture, Vector, WebGlRenderer, WorkerInterface, XR_AXES, XR_BUTTONS, bindingLabel, bindingsEqual, buildColorPalette, clamp, controlId, degrees, distance2d, distance3d, ecs, findPath, fract, gesture, getRedYellowGreenGradientHex, hash32, hash32mix, inverseLerp, isNullOrUndefined, isPositiveString, k2xy, k2xyz, key, lerp, log, manhattanDistance, mod, mouse, nearlyEqual, normalizeRadians, pad, padAxis, radians, randomMatrix, rng, roundTo, saturate, smoothstep, squaredDistance, wheel, wrap, xr, xrAxis, xy2k, xyz2k };
35
+ export { ActionMap, BindRenderTarget, CanvasRenderer, Clock, Color, CompileShader, CreateBuffer, CreateProgram, CreateProgramInfo, CreateRenderTarget, CreateTexture, CreateVertexArray, CreateWebGlContext, DEFAULT_COLOR, DEFAULT_DEADZONE, DEFAULT_FONT, DEFAULT_FONT_NAME, DEFAULT_FONT_SIZE, DEFAULT_MAP_2D_VALUE, DEFAULT_MAP_3D_VALUE, DEFAULT_PIXEL_SIZE, DEFAULT_REPEAT, DEFAULT_TEXTALIGN, DEFAULT_TEXTBASELINE, DEG2RAD, DeleteProgramInfo, DeleteRenderTarget, DeleteTexture, DeleteVertexArray, Disposable, Draw, E, ECS, EPSILON, Emitter, EventQueue, GAMEPAD_AXES, GAMEPAD_BUTTONS, GESTURES, GenerateDoors, GenerateRooms, GenerateWalls, GestureRecognizer, GetProgramLocations, GetUrlParams, HALF_PI, Input, InputActionMap, LN10, LN2, LOG10E, LOG2E, LoadWebGlTexture, MAP_2D_MAX_COORD, MAP_2D_MIN_COORD, MAP_3D_MAX_COORD, MAP_3D_MIN_COORD, Map2D, Map3D, ONE_SECOND, Observable, PI, ParticleRenderer, ParticleSystem2d, QUARTER_PI, RAD2DEG, Random, Rectangle, ResizeRenderTarget, ResizeWebGlContext, Rng, SQRT1_2, SQRT2, SetUniforms, ShaderType, Signal, SpatialPartition2d, SpatialPartition3d, TAU, TILE_EMPTY, TILE_FLOOR, TILE_PATH, Tilemap, UpdateBuffer, UpdateTexture, Vector, WebGlRenderer, WorkerInterface, XR_AXES, XR_BUTTONS, bindingLabel, bindingsEqual, buildColorPalette, clamp, controlId, degrees, distance2d, distance3d, ecs, findPath, fract, gesture, getRedYellowGreenGradientHex, hash32, hash32mix, inverseLerp, isNullOrUndefined, isPositiveString, k2xy, k2xyz, key, lerp, log, manhattanDistance, mod, mouse, nearlyEqual, normalizeRadians, pad, padAxis, radians, randomMatrix, rng, roundTo, saturate, smoothstep, squaredDistance, wheel, wrap, xr, xrAxis, xy2k, xyz2k };
@@ -0,0 +1,25 @@
1
+ import { Emitter } from "../emitter.js";
2
+ //#region src/input/_input.d.ts
3
+ export interface InputState {
4
+ state: number;
5
+ timeStamp: number;
6
+ }
7
+ export declare class Input extends Emitter {
8
+ private static _instance;
9
+ static get instance(): Input;
10
+ private _state;
11
+ inputThreshold: number;
12
+ private constructor();
13
+ disableContextMenu(): void;
14
+ private _onKeyDown;
15
+ private _onKeyUp;
16
+ private _onPointerDown;
17
+ private _onPointerUp;
18
+ private _onPointerMove;
19
+ private _onWheel;
20
+ isKeyDown(keyCode: string): boolean;
21
+ getKeyState(keyCode: string): number;
22
+ isButtonDown(buttonNumber: number): boolean;
23
+ getButtonState(buttonNumber: number): number;
24
+ }
25
+ //#endregion
@@ -0,0 +1,97 @@
1
+ import { Emitter } from "../emitter.js";
2
+ //#region src/input/_input.ts
3
+ var Input = class Input extends Emitter {
4
+ static _instance;
5
+ static get instance() {
6
+ if (!Input._instance) Input._instance = new Input();
7
+ return Input._instance;
8
+ }
9
+ _state = {};
10
+ inputThreshold = 200;
11
+ constructor() {
12
+ super();
13
+ window.addEventListener("keydown", this._onKeyDown.bind(this));
14
+ window.addEventListener("keyup", this._onKeyUp.bind(this));
15
+ window.addEventListener("pointerdown", this._onPointerDown.bind(this));
16
+ window.addEventListener("pointerup", this._onPointerUp.bind(this));
17
+ window.addEventListener("mousemove", this._onPointerMove.bind(this));
18
+ window.addEventListener("wheel", this._onWheel.bind(this));
19
+ }
20
+ disableContextMenu() {
21
+ window.addEventListener("contextmenu", (ev) => {
22
+ ev.preventDefault();
23
+ this.emit("contextmenu");
24
+ return false;
25
+ });
26
+ }
27
+ _onKeyDown(ev) {
28
+ const { code, timeStamp } = ev;
29
+ if (!ev.repeat) {
30
+ this._state[code] = {
31
+ state: 1,
32
+ timeStamp
33
+ };
34
+ this.emit("key_down", ev);
35
+ this.emit(`${code.toLowerCase()}_down`, ev);
36
+ }
37
+ }
38
+ _onKeyUp(ev) {
39
+ const { code, timeStamp } = ev;
40
+ this._state[code] = {
41
+ state: 0,
42
+ timeStamp
43
+ };
44
+ this.emit("key_up", ev);
45
+ this.emit(`${code.toLowerCase()}_up`, ev);
46
+ if (timeStamp - (this._state[code]?.timeStamp ?? 0) <= this.inputThreshold) {
47
+ this.emit("key_pressed", ev);
48
+ this.emit(`${code.toLowerCase()}_pressed`, ev);
49
+ }
50
+ }
51
+ _onPointerDown(ev) {
52
+ const { button, timeStamp } = ev;
53
+ const code = `button${button}`;
54
+ if (!this._state[code]?.state) {
55
+ this._state[code] = {
56
+ state: 1,
57
+ timeStamp
58
+ };
59
+ this.emit("button_down", ev);
60
+ this.emit(`${code}_down`, ev);
61
+ }
62
+ }
63
+ _onPointerUp(ev) {
64
+ const { button, timeStamp } = ev;
65
+ const code = `button${button}`;
66
+ this._state[code] = {
67
+ state: 0,
68
+ timeStamp
69
+ };
70
+ this.emit("button_up", ev);
71
+ this.emit(`${code}_up`, ev);
72
+ if (timeStamp - (this._state[button]?.timeStamp ?? 0) < this.inputThreshold) {
73
+ this.emit("button_clicked", ev);
74
+ this.emit(`${code}_clicked`, ev);
75
+ }
76
+ }
77
+ _onPointerMove(ev) {
78
+ this.emit("pointer_move", ev);
79
+ }
80
+ _onWheel(ev) {
81
+ this.emit("mouse_wheel", ev);
82
+ }
83
+ isKeyDown(keyCode) {
84
+ return this._state[keyCode]?.state === 1 ? true : false;
85
+ }
86
+ getKeyState(keyCode) {
87
+ return this._state[keyCode]?.state ?? 0;
88
+ }
89
+ isButtonDown(buttonNumber) {
90
+ return this._state[`button${buttonNumber}`]?.state === 1 ? true : false;
91
+ }
92
+ getButtonState(buttonNumber) {
93
+ return this._state[`button${buttonNumber}`]?.state ?? 0;
94
+ }
95
+ };
96
+ //#endregion
97
+ export { Input };