@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
package/dist/index.cjs CHANGED
@@ -1,5 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_spatial_partition_3d = require("./spatial-partition-3d-Ba-VBveM.cjs");
2
+ const require_rng = require("./rng-Dhqq7owV.cjs");
3
+ const require_spatial_partition_3d = require("./spatial-partition-3d-CmSCL87Z.cjs");
3
4
  let heap_js = require("heap-js");
4
5
  //#region src/astar.ts
5
6
  const DEFAULT_MAX_NODES = 1e4;
@@ -42,7 +43,7 @@ function findPath(start, goal, cost, options = {}) {
42
43
  const heuristic = (x, y) => {
43
44
  const dx = Math.abs(x - goal.x);
44
45
  const dy = Math.abs(y - goal.y);
45
- return diagonal ? Math.max(dx, dy) + (require_spatial_partition_3d.SQRT2 - 1) * Math.min(dx, dy) : dx + dy;
46
+ return diagonal ? Math.max(dx, dy) + (require_rng.SQRT2 - 1) * Math.min(dx, dy) : dx + dy;
46
47
  };
47
48
  const isGoal = (x, y) => {
48
49
  if (x === goal.x && y === goal.y) return true;
@@ -88,7 +89,7 @@ function findPath(start, goal, cost, options = {}) {
88
89
  if (!(stepCost < Infinity)) continue;
89
90
  const isDiagonal = dx !== 0 && dy !== 0;
90
91
  if (isDiagonal && !cutCorners && (!passable(current.x + dx, current.y) || !passable(current.x, current.y + dy))) continue;
91
- const g = current.g + (isDiagonal ? stepCost * require_spatial_partition_3d.SQRT2 : stepCost);
92
+ const g = current.g + (isDiagonal ? stepCost * require_rng.SQRT2 : stepCost);
92
93
  const known = best.get(k);
93
94
  if (known && known.g <= g) continue;
94
95
  const h = known?.h ?? heuristic(x, y);
@@ -276,7 +277,7 @@ var CanvasRenderer = class {
276
277
  /** Draws a circle centered on (`x`, `y`). */
277
278
  drawCircle(x, y, radius, params = {}) {
278
279
  this.drawPath(() => {
279
- this.context.arc(x, y, radius, 0, require_spatial_partition_3d.TAU);
280
+ this.context.arc(x, y, radius, 0, require_rng.TAU);
280
281
  }, params);
281
282
  }
282
283
  /**
@@ -286,10 +287,10 @@ var CanvasRenderer = class {
286
287
  * @param sides floored and clamped to 3..36
287
288
  */
288
289
  drawPolygon(x, y, radius, sides, params = {}) {
289
- sides = Math.floor(require_spatial_partition_3d.clamp(sides, 3, 36));
290
+ sides = Math.floor(require_rng.clamp(sides, 3, 36));
290
291
  this.drawPath(() => {
291
292
  for (let i = 0; i < sides; i++) {
292
- const angle = i / sides * require_spatial_partition_3d.TAU - require_spatial_partition_3d.PI / 2;
293
+ const angle = i / sides * require_rng.TAU - require_rng.PI / 2;
293
294
  const px = x + Math.cos(angle) * radius;
294
295
  const py = y + Math.sin(angle) * radius;
295
296
  if (i === 0) this.context.moveTo(px, py);
@@ -739,7 +740,7 @@ var Vector = class Vector {
739
740
  }
740
741
  /** Euclidean distance to `that`. */
741
742
  distanceTo(that) {
742
- return require_spatial_partition_3d.distance2d(this.x, this.y, that.x, that.y);
743
+ return require_rng.distance2d(this.x, this.y, that.x, that.y);
743
744
  }
744
745
  /** Euclidean length (magnitude). */
745
746
  length() {
@@ -1002,11 +1003,11 @@ function _generateRooms(params = {}) {
1002
1003
  const rooms = [];
1003
1004
  let iterations = 0;
1004
1005
  while (iterations < maxIterations) {
1005
- const baseSize = require_spatial_partition_3d.rng.range(minRoomSize, maxRoomSize);
1006
- const aspectRatio = .75 + require_spatial_partition_3d.rng.gaussian() * .5;
1006
+ const baseSize = require_rng.rng.range(minRoomSize, maxRoomSize);
1007
+ const aspectRatio = .75 + require_rng.rng.gaussian() * .5;
1007
1008
  const width = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize * aspectRatio)));
1008
1009
  const height = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize / aspectRatio)));
1009
- const room = new Rectangle(require_spatial_partition_3d.rng.range(1 + padding, size - width - padding), require_spatial_partition_3d.rng.range(1 + padding, size - height - padding), width, height);
1010
+ const room = new Rectangle(require_rng.rng.range(1 + padding, size - width - padding), require_rng.rng.range(1 + padding, size - height - padding), width, height);
1010
1011
  if (!rooms.some((existing) => room.intersects(existing, padding * 2))) {
1011
1012
  rooms.push(room);
1012
1013
  iterations = 0;
@@ -1029,7 +1030,7 @@ function _generateMST(rooms, params = {}) {
1029
1030
  heap.push({
1030
1031
  from: 0,
1031
1032
  to: i,
1032
- cost: require_spatial_partition_3d.squaredDistance(zeroCenter.x, zeroCenter.y, iCenter.x, iCenter.y)
1033
+ cost: require_rng.squaredDistance(zeroCenter.x, zeroCenter.y, iCenter.x, iCenter.y)
1033
1034
  });
1034
1035
  }
1035
1036
  while (visited.size < rooms.length) {
@@ -1048,14 +1049,14 @@ function _generateMST(rooms, params = {}) {
1048
1049
  heap.push({
1049
1050
  from: to,
1050
1051
  to: i,
1051
- cost: require_spatial_partition_3d.squaredDistance(toCenter.x, toCenter.y, iCenter.x, iCenter.y)
1052
+ cost: require_rng.squaredDistance(toCenter.x, toCenter.y, iCenter.x, iCenter.y)
1052
1053
  });
1053
1054
  }
1054
1055
  }
1055
1056
  const remainingEdges = heap.toArray().sort((a, b) => a.cost - b.cost);
1056
1057
  for (let i = 0; i < extraPathLevels && i < remainingEdges.length; i++) {
1057
1058
  const e = remainingEdges[i];
1058
- if (require_spatial_partition_3d.rng.nextFloat() < extraPathDensity) extraPaths.push({
1059
+ if (require_rng.rng.nextFloat() < extraPathDensity) extraPaths.push({
1059
1060
  a: rooms[e.from],
1060
1061
  b: rooms[e.to]
1061
1062
  });
@@ -1097,7 +1098,7 @@ function _getShortestPathBetweenRects(rectA, rectB) {
1097
1098
  distance: Infinity
1098
1099
  };
1099
1100
  for (const a of edgeA) for (const b of edgeB) {
1100
- const d = require_spatial_partition_3d.distance2d(a.x, a.y, b.x, b.y);
1101
+ const d = require_rng.distance2d(a.x, a.y, b.x, b.y);
1101
1102
  if (d < paths.distance) paths = {
1102
1103
  a,
1103
1104
  b,
@@ -1176,7 +1177,7 @@ function GenerateDoors(map, paths, params = {}) {
1176
1177
  });
1177
1178
  const doors = [];
1178
1179
  possibleDoorPoints.forEach((doorPoint) => {
1179
- if (require_spatial_partition_3d.rng.nextFloat() < chanceExists && (map.get(doorPoint.x, doorPoint.y - 1) === map.defaultValue && map.get(doorPoint.x, doorPoint.y + 1) === map.defaultValue || map.get(doorPoint.x - 1, doorPoint.y) === map.defaultValue && map.get(doorPoint.x + 1, doorPoint.y) === map.defaultValue)) doors.push(doorPoint);
1180
+ if (require_rng.rng.nextFloat() < chanceExists && (map.get(doorPoint.x, doorPoint.y - 1) === map.defaultValue && map.get(doorPoint.x, doorPoint.y + 1) === map.defaultValue || map.get(doorPoint.x - 1, doorPoint.y) === map.defaultValue && map.get(doorPoint.x + 1, doorPoint.y) === map.defaultValue)) doors.push(doorPoint);
1180
1181
  });
1181
1182
  return doors;
1182
1183
  }
@@ -1615,7 +1616,7 @@ const AXIS_NAMES = {
1615
1616
  const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
1616
1617
  /**
1617
1618
  * A readable name for a binding, e.g. for "Press Space to jump" prompts. Pass `keyLabels` (from
1618
- * {@link Input.loadKeyboardLayout}) to name keys as printed on the player's keyboard.
1619
+ * {@link InputActionMap.loadKeyboardLayout}) to name keys as printed on the player's keyboard.
1619
1620
  *
1620
1621
  * @category Input
1621
1622
  */
@@ -1650,8 +1651,17 @@ function bindingLabel(binding, keyLabels) {
1650
1651
  */
1651
1652
  const DEFAULT_DEADZONE = .2;
1652
1653
  /**
1653
- * Named actions and the inputs bound to them, like Godot's InputMap. Every {@link Input} has one as
1654
- * {@link Input.actions}; the methods that change it return `this` for chaining.
1654
+ * Repeat timing used by `repeat: true`: first repeat after 400 ms, then every 100 ms.
1655
+ *
1656
+ * @category Input
1657
+ */
1658
+ const DEFAULT_REPEAT = {
1659
+ delay: 400,
1660
+ interval: 100
1661
+ };
1662
+ /**
1663
+ * Named actions and the inputs bound to them, like Godot's InputMap. Every {@link InputActionMap} has one as
1664
+ * {@link InputActionMap.actions}; the methods that change it return `this` for chaining.
1655
1665
  *
1656
1666
  * ```ts
1657
1667
  * input.actions
@@ -1677,14 +1687,20 @@ var ActionMap = class {
1677
1687
  get(name) {
1678
1688
  return this._actions.get(name);
1679
1689
  }
1680
- /** Adds an action, or replaces its bindings (and deadzone, if given) if it exists. */
1690
+ /** Adds an action, or replaces its bindings (and deadzone / repeat, if given) if it exists. */
1681
1691
  add(name, bindings = [], options = {}) {
1682
1692
  const existing = this._actions.get(name);
1683
- this._actions.set(name, {
1693
+ const repeat = options.repeat === void 0 ? existing?.repeat : options.repeat === false ? void 0 : {
1694
+ ...DEFAULT_REPEAT,
1695
+ ...options.repeat === true ? {} : options.repeat
1696
+ };
1697
+ const action = {
1684
1698
  name,
1685
1699
  deadzone: options.deadzone ?? existing?.deadzone ?? .2,
1686
1700
  bindings: [...bindings]
1687
- });
1701
+ };
1702
+ if (repeat) action.repeat = repeat;
1703
+ this._actions.set(name, action);
1688
1704
  return this;
1689
1705
  }
1690
1706
  /** Removes an action, if it exists. */
@@ -1720,24 +1736,35 @@ var ActionMap = class {
1720
1736
  /** A JSON-serializable copy of all actions, for saving rebinds; see {@link ActionMap.load}. */
1721
1737
  toJSON() {
1722
1738
  const json = {};
1723
- for (const action of this._actions.values()) json[action.name] = {
1724
- deadzone: action.deadzone,
1725
- bindings: action.bindings.map((b) => ({ ...b }))
1726
- };
1739
+ for (const action of this._actions.values()) {
1740
+ json[action.name] = {
1741
+ deadzone: action.deadzone,
1742
+ bindings: action.bindings.map((b) => ({ ...b }))
1743
+ };
1744
+ if (action.repeat) json[action.name].repeat = { ...action.repeat };
1745
+ }
1727
1746
  return json;
1728
1747
  }
1729
1748
  /** Replaces all actions with the saved ones (e.g. a player's rebinds). */
1730
1749
  load(json) {
1731
1750
  this.clear();
1732
- for (const [name, action] of Object.entries(json)) this.add(name, action.bindings, { deadzone: action.deadzone });
1751
+ for (const [name, action] of Object.entries(json)) this.add(name, action.bindings, {
1752
+ deadzone: action.deadzone,
1753
+ repeat: action.repeat ?? false
1754
+ });
1733
1755
  return this;
1734
1756
  }
1735
1757
  /**
1736
1758
  * Godot-style `ui_*` actions for menus and dialogs (`ui_accept`, `ui_cancel`, `ui_left`, `ui_right`,
1737
- * `ui_up`, `ui_down`, `ui_page_up`, `ui_page_down`), with a 0.5 deadzone; replaces existing ones.
1759
+ * `ui_up`, `ui_down`, `ui_page_up`, `ui_page_down`), with a 0.5 deadzone; the directions and
1760
+ * page actions auto-repeat ({@link DEFAULT_REPEAT}). Replaces existing ones.
1738
1761
  */
1739
1762
  addDefaults() {
1740
1763
  const ui = { deadzone: .5 };
1764
+ const nav = {
1765
+ deadzone: .5,
1766
+ repeat: true
1767
+ };
1741
1768
  this.add("ui_accept", [
1742
1769
  key("Enter"),
1743
1770
  key("NumpadEnter"),
@@ -1749,24 +1776,24 @@ var ActionMap = class {
1749
1776
  key("ArrowLeft"),
1750
1777
  pad("DpadLeft"),
1751
1778
  padAxis("leftX", -1)
1752
- ], ui);
1779
+ ], nav);
1753
1780
  this.add("ui_right", [
1754
1781
  key("ArrowRight"),
1755
1782
  pad("DpadRight"),
1756
1783
  padAxis("leftX", 1)
1757
- ], ui);
1784
+ ], nav);
1758
1785
  this.add("ui_up", [
1759
1786
  key("ArrowUp"),
1760
1787
  pad("DpadUp"),
1761
1788
  padAxis("leftY", -1)
1762
- ], ui);
1789
+ ], nav);
1763
1790
  this.add("ui_down", [
1764
1791
  key("ArrowDown"),
1765
1792
  pad("DpadDown"),
1766
1793
  padAxis("leftY", 1)
1767
- ], ui);
1768
- this.add("ui_page_up", [key("PageUp"), pad("LB")], ui);
1769
- this.add("ui_page_down", [key("PageDown"), pad("RB")], ui);
1794
+ ], nav);
1795
+ this.add("ui_page_up", [key("PageUp"), pad("LB")], nav);
1796
+ this.add("ui_page_down", [key("PageDown"), pad("RB")], nav);
1770
1797
  return this;
1771
1798
  }
1772
1799
  };
@@ -1785,7 +1812,7 @@ const DEFAULT_THRESHOLDS = {
1785
1812
  /**
1786
1813
  * Turns touch points into gestures: tap, double tap, long press, swipes (one finger) and
1787
1814
  * pinch / pan / rotate (two fingers). Feed it with down / move / up, call update() once per frame.
1788
- * Times are in ms and positions in pixels, from any consistent clock and origin. {@link Input} drives
1815
+ * Times are in ms and positions in pixels, from any consistent clock and origin. {@link InputActionMap} drives
1789
1816
  * one for you; use this class directly only for custom touch handling.
1790
1817
  *
1791
1818
  * Tap, double tap and swipe are reported when the finger lifts, long press while it is still held;
@@ -1796,7 +1823,8 @@ const DEFAULT_THRESHOLDS = {
1796
1823
  * el.addEventListener('pointerdown', e => recognizer.down(e.pointerId, e.offsetX, e.offsetY, performance.now()));
1797
1824
  * // ... move / up / cancel likewise
1798
1825
  *
1799
- * const { gestures, pinch } = recognizer.update(performance.now());
1826
+ * const { gestures, events, pinch } = recognizer.update(performance.now());
1827
+ * const tap = events.find(e => e.gesture === 'tap'); // { gesture, x, y }
1800
1828
  * ```
1801
1829
  *
1802
1830
  * @category Input
@@ -1860,17 +1888,32 @@ var GestureRecognizer = class {
1860
1888
  const dy = y - touch.startY;
1861
1889
  const distance = Math.hypot(dx, dy);
1862
1890
  if (duration <= t.tapMaxDuration && touch.maxMovement <= t.tapMaxMovement) {
1863
- this._pending.push("tap");
1891
+ this._pending.push({
1892
+ gesture: "tap",
1893
+ x,
1894
+ y
1895
+ });
1864
1896
  const last = this._lastTap;
1865
1897
  if (last && time - last.time <= t.doubleTapMaxDelay && Math.hypot(x - last.x, y - last.y) <= t.doubleTapMaxDistance) {
1866
- this._pending.push("doubleTap");
1898
+ this._pending.push({
1899
+ gesture: "doubleTap",
1900
+ x,
1901
+ y
1902
+ });
1867
1903
  this._lastTap = void 0;
1868
1904
  } else this._lastTap = {
1869
1905
  x,
1870
1906
  y,
1871
1907
  time
1872
1908
  };
1873
- } else if (distance >= t.swipeMinDistance && duration <= t.swipeMaxDuration) this._pending.push(Math.abs(dx) >= Math.abs(dy) ? dx > 0 ? "swipeRight" : "swipeLeft" : dy > 0 ? "swipeDown" : "swipeUp");
1909
+ } else if (distance >= t.swipeMinDistance && duration <= t.swipeMaxDuration) {
1910
+ const gesture = Math.abs(dx) >= Math.abs(dy) ? dx > 0 ? "swipeRight" : "swipeLeft" : dy > 0 ? "swipeDown" : "swipeUp";
1911
+ this._pending.push({
1912
+ gesture,
1913
+ x: touch.startX,
1914
+ y: touch.startY
1915
+ });
1916
+ }
1874
1917
  }
1875
1918
  /** Forgets a finger without recognizing anything (e.g. on `pointercancel`). */
1876
1919
  cancel(id) {
@@ -1887,6 +1930,7 @@ var GestureRecognizer = class {
1887
1930
  update(time) {
1888
1931
  const frame = {
1889
1932
  gestures: [],
1933
+ events: [],
1890
1934
  pinch: 1,
1891
1935
  pan: {
1892
1936
  x: 0,
@@ -1896,7 +1940,11 @@ var GestureRecognizer = class {
1896
1940
  };
1897
1941
  for (const touch of this._touches.values()) if (!touch.multi && !touch.longPressed && touch.maxMovement <= this.thresholds.tapMaxMovement && time - touch.startTime >= this.thresholds.longPressDuration) {
1898
1942
  touch.longPressed = true;
1899
- this._pending.push("longPress");
1943
+ this._pending.push({
1944
+ gesture: "longPress",
1945
+ x: touch.x,
1946
+ y: touch.y
1947
+ });
1900
1948
  }
1901
1949
  const [a, b] = [...this._touches.values()];
1902
1950
  if (a && b) {
@@ -1912,7 +1960,11 @@ var GestureRecognizer = class {
1912
1960
  y: cy - pair.cy
1913
1961
  };
1914
1962
  frame.rotate = Math.atan2(Math.sin(angle - pair.angle), Math.cos(angle - pair.angle));
1915
- if (Math.abs(frame.pinch - 1) >= this.thresholds.pinchMinChange) this._pending.push(frame.pinch > 1 ? "pinchOut" : "pinchIn");
1963
+ if (Math.abs(frame.pinch - 1) >= this.thresholds.pinchMinChange) this._pending.push({
1964
+ gesture: frame.pinch > 1 ? "pinchOut" : "pinchIn",
1965
+ x: cx,
1966
+ y: cy
1967
+ });
1916
1968
  }
1917
1969
  this._pair = {
1918
1970
  a: a.id,
@@ -1923,12 +1975,253 @@ var GestureRecognizer = class {
1923
1975
  cy
1924
1976
  };
1925
1977
  } else this._pair = void 0;
1926
- frame.gestures = this._pending;
1978
+ frame.events = this._pending;
1979
+ frame.gestures = frame.events.map((e) => e.gesture);
1927
1980
  this._pending = [];
1928
1981
  return frame;
1929
1982
  }
1930
1983
  };
1931
1984
  //#endregion
1985
+ //#region src/input/input.ts
1986
+ const BUTTON_BITS = [
1987
+ 1,
1988
+ 4,
1989
+ 2,
1990
+ 8,
1991
+ 16
1992
+ ];
1993
+ /**
1994
+ * Event-based input for keyboard, mouse, pen and touch: subscribe with `on()` and query state
1995
+ * at any time; no frame loop needed. One shared instance, {@link Input.instance}.
1996
+ *
1997
+ * Events (listeners get the DOM event):
1998
+ * - keys, by lowercased `KeyboardEvent.code`: `key_down`, `key_up`, `key_repeat`, `key_pressed`
1999
+ * (released within `inputThreshold` ms), and per key `keyw_down`, `keyw_up`, `keyw_pressed`, ...
2000
+ * - buttons (mouse buttons; the primary finger or pen is button 0): `button_down`, `button_up`,
2001
+ * `button_clicked`, and per button `button0_down`, `button0_up`, `button0_clicked`, ...
2002
+ * No click after a drag.
2003
+ * - pointer: `pointer_move`; `drag_start`, `drag`, `drag_end` (moved `dragThreshold` px with a
2004
+ * button down); `mouse_wheel`; `contextmenu` (see `disableContextMenu()`)
2005
+ * - every finger: `touch_down`, `touch_move`, `touch_up`, `touch_cancel`
2006
+ * - `blur`: the window lost focus or the tab was hidden; every key and button is released
2007
+ *
2008
+ * ```ts
2009
+ * const input = Input.instance;
2010
+ * input.target = canvas;
2011
+ *
2012
+ * input.on('keyw_down', 'arrowup_down', () => move(0, -1));
2013
+ * input.on('button0_clicked', () => select(input.pointerPosition));
2014
+ * input.on('pointer_move', () => {
2015
+ * if (input.isButtonDown(0)) pan(input.pointerDelta.x, input.pointerDelta.y);
2016
+ * });
2017
+ * ```
2018
+ *
2019
+ * @category Input
2020
+ */
2021
+ var Input = class Input extends Emitter {
2022
+ static _instance;
2023
+ /** the shared instance, created on first use */
2024
+ static get instance() {
2025
+ if (!Input._instance) Input._instance = new Input();
2026
+ return Input._instance;
2027
+ }
2028
+ _state = {};
2029
+ _windowListeners = [];
2030
+ _targetListeners = [];
2031
+ _target = window;
2032
+ _contextMenuDisabled = false;
2033
+ _dragStart;
2034
+ _dragging = false;
2035
+ /** pixels from the target's top-left */
2036
+ pointerPosition = new Vector();
2037
+ /** -1..1 across the target, y up */
2038
+ pointerPositionNdc = new Vector();
2039
+ /** pixels moved by the last pointer event (mouse, pen and touch alike) */
2040
+ pointerDelta = new Vector();
2041
+ /** ms; a key or button released within this is also `_pressed` / `_clicked` */
2042
+ inputThreshold = 200;
2043
+ /** px; moving further than this with a button down starts a drag */
2044
+ dragThreshold = 5;
2045
+ /**
2046
+ * Where pointer, wheel and context-menu events are read and positions are measured, default
2047
+ * `window`; usually the canvas. Keys are always read from `window`.
2048
+ */
2049
+ get target() {
2050
+ return this._target;
2051
+ }
2052
+ /** moves the pointer, wheel and context-menu listeners to `target` */
2053
+ set target(target) {
2054
+ this._targetListeners.forEach(([type, listener]) => this._target.removeEventListener(type, listener));
2055
+ this._targetListeners = [];
2056
+ this._target = target;
2057
+ this._listenToTarget();
2058
+ }
2059
+ /** a drag is in progress */
2060
+ get isDragging() {
2061
+ return this._dragging;
2062
+ }
2063
+ constructor() {
2064
+ super();
2065
+ this._listen(this._windowListeners, window, "keydown", this._onKeyDown);
2066
+ this._listen(this._windowListeners, window, "keyup", this._onKeyUp);
2067
+ this._listen(this._windowListeners, window, "blur", this._onBlur);
2068
+ if (typeof document !== "undefined") this._listen(this._windowListeners, document, "visibilitychange", () => {
2069
+ if (document.hidden) this._onBlur(new Event("blur"));
2070
+ });
2071
+ this._listenToTarget();
2072
+ }
2073
+ /** Stops the right-click menu on the target; `contextmenu` is still emitted. */
2074
+ disableContextMenu() {
2075
+ if (this._contextMenuDisabled) return;
2076
+ this._contextMenuDisabled = true;
2077
+ this._listen(this._targetListeners, this._target, "contextmenu", this._onContextMenu);
2078
+ }
2079
+ /** Removes every DOM listener; the next {@link Input.instance} is a new one. */
2080
+ dispose() {
2081
+ this._windowListeners.forEach(([type, listener]) => {
2082
+ window.removeEventListener(type, listener);
2083
+ if (typeof document !== "undefined") document.removeEventListener(type, listener);
2084
+ });
2085
+ this._targetListeners.forEach(([type, listener]) => this._target.removeEventListener(type, listener));
2086
+ this._windowListeners = [];
2087
+ this._targetListeners = [];
2088
+ Input._instance = void 0;
2089
+ }
2090
+ _listenToTarget() {
2091
+ const listeners = this._targetListeners;
2092
+ this._listen(listeners, this._target, "pointerdown", this._onPointerDown);
2093
+ this._listen(listeners, this._target, "pointerup", this._onPointerUp);
2094
+ this._listen(listeners, this._target, "pointercancel", this._onPointerUp);
2095
+ this._listen(listeners, this._target, "pointermove", this._onPointerMove);
2096
+ this._listen(listeners, this._target, "wheel", this._onWheel, { passive: false });
2097
+ if (this._contextMenuDisabled) this._listen(listeners, this._target, "contextmenu", this._onContextMenu);
2098
+ const style = this._target.style;
2099
+ if (style) style.touchAction = "none";
2100
+ }
2101
+ _listen(listeners, target, type, handler, options) {
2102
+ const listener = handler.bind(this);
2103
+ target.addEventListener(type, listener, options);
2104
+ listeners.push([type, listener]);
2105
+ }
2106
+ _down(id, group, name, ev) {
2107
+ if (this._state[id]?.state) return;
2108
+ this._state[id] = {
2109
+ state: 1,
2110
+ timeStamp: ev.timeStamp
2111
+ };
2112
+ this.emit(`${group}_down`, ev);
2113
+ this.emit(`${name}_down`, ev);
2114
+ }
2115
+ _up(id, group, name, quick, ev) {
2116
+ const down = this._state[id];
2117
+ if (!down?.state) return;
2118
+ this._state[id] = {
2119
+ state: 0,
2120
+ timeStamp: ev.timeStamp
2121
+ };
2122
+ this.emit(`${group}_up`, ev);
2123
+ this.emit(`${name}_up`, ev);
2124
+ if (!this._dragging && ev.timeStamp - down.timeStamp <= this.inputThreshold) {
2125
+ this.emit(`${group}_${quick}`, ev);
2126
+ this.emit(`${name}_${quick}`, ev);
2127
+ }
2128
+ }
2129
+ _anyButtonDown() {
2130
+ return BUTTON_BITS.some((_, button) => this.isButtonDown(button));
2131
+ }
2132
+ _updatePointer(ev) {
2133
+ const rect = this._target.getBoundingClientRect?.() ?? {
2134
+ left: 0,
2135
+ top: 0,
2136
+ width: window.innerWidth,
2137
+ height: window.innerHeight
2138
+ };
2139
+ const x = ev.clientX - rect.left;
2140
+ const y = ev.clientY - rect.top;
2141
+ if (ev.pointerType === "touch") this.pointerDelta.set(x - this.pointerPosition.x, y - this.pointerPosition.y);
2142
+ else this.pointerDelta.set(ev.movementX ?? 0, ev.movementY ?? 0);
2143
+ this.pointerPosition.set(x, y);
2144
+ this.pointerPositionNdc.set(x / (rect.width || 1) * 2 - 1, -(y / (rect.height || 1)) * 2 + 1);
2145
+ }
2146
+ _onContextMenu(ev) {
2147
+ ev.preventDefault();
2148
+ this.emit("contextmenu", ev);
2149
+ }
2150
+ _onKeyDown(ev) {
2151
+ if (ev.repeat) this.emit("key_repeat", ev);
2152
+ else this._down(ev.code, "key", ev.code.toLowerCase(), ev);
2153
+ }
2154
+ _onKeyUp(ev) {
2155
+ this._up(ev.code, "key", ev.code.toLowerCase(), "pressed", ev);
2156
+ }
2157
+ _onPointerDown(ev) {
2158
+ if (ev.pointerType === "touch") this.emit("touch_down", ev);
2159
+ if (!ev.isPrimary) return;
2160
+ this._target.setPointerCapture?.(ev.pointerId);
2161
+ this._updatePointer(ev);
2162
+ this.pointerDelta.set(0, 0);
2163
+ if (!this._anyButtonDown()) {
2164
+ this._dragStart = this.pointerPosition.clone();
2165
+ this._dragging = false;
2166
+ }
2167
+ this._down(`button${ev.button}`, "button", `button${ev.button}`, ev);
2168
+ }
2169
+ _onPointerUp(ev) {
2170
+ if (ev.pointerType === "touch") this.emit(ev.type === "pointercancel" ? "touch_cancel" : "touch_up", ev);
2171
+ if (!ev.isPrimary) return;
2172
+ this._updatePointer(ev);
2173
+ this._up(`button${ev.button}`, "button", `button${ev.button}`, "clicked", ev);
2174
+ if (!this._anyButtonDown()) this._endDrag(ev);
2175
+ }
2176
+ _onPointerMove(ev) {
2177
+ if (ev.pointerType === "touch") this.emit("touch_move", ev);
2178
+ if (!ev.isPrimary) return;
2179
+ this._updatePointer(ev);
2180
+ if (ev.pointerType === "mouse" && ev.button >= 0) {
2181
+ const id = `button${ev.button}`;
2182
+ if (ev.buttons & BUTTON_BITS[ev.button]) this._down(id, "button", id, ev);
2183
+ else this._up(id, "button", id, "clicked", ev);
2184
+ }
2185
+ if (this._dragStart && this._anyButtonDown()) {
2186
+ if (!this._dragging && this.pointerPosition.distanceTo(this._dragStart) > this.dragThreshold) {
2187
+ this._dragging = true;
2188
+ this.emit("drag_start", ev);
2189
+ }
2190
+ if (this._dragging) this.emit("drag", ev);
2191
+ }
2192
+ this.emit("pointer_move", ev);
2193
+ }
2194
+ _endDrag(ev) {
2195
+ if (this._dragging) this.emit("drag_end", ev);
2196
+ this._dragStart = void 0;
2197
+ this._dragging = false;
2198
+ }
2199
+ _onWheel(ev) {
2200
+ this.emit("mouse_wheel", ev);
2201
+ }
2202
+ _onBlur(ev) {
2203
+ Object.values(this._state).forEach((s) => s.state = 0);
2204
+ this._endDrag(ev);
2205
+ this.emit("blur", ev);
2206
+ }
2207
+ /** Whether a key (by `KeyboardEvent.code`, e.g. 'KeyW') is down. */
2208
+ isKeyDown(keyCode) {
2209
+ return this._state[keyCode]?.state === 1;
2210
+ }
2211
+ /** 1 if the key is down, else 0. */
2212
+ getKeyState(keyCode) {
2213
+ return this._state[keyCode]?.state ?? 0;
2214
+ }
2215
+ /** Whether a button (`PointerEvent.button`: 0 left / primary finger, 1 middle, 2 right, ...) is down. */
2216
+ isButtonDown(buttonNumber) {
2217
+ return this._state[`button${buttonNumber}`]?.state === 1;
2218
+ }
2219
+ /** 1 if the button is down, else 0. */
2220
+ getButtonState(buttonNumber) {
2221
+ return this._state[`button${buttonNumber}`]?.state ?? 0;
2222
+ }
2223
+ };
2224
+ //#endregion
1932
2225
  //#region src/observable.ts
1933
2226
  /**
1934
2227
  * A set of observers notified with a value (plus optional extra arguments). Observers are
@@ -1981,7 +2274,7 @@ var Observable = class {
1981
2274
  }
1982
2275
  };
1983
2276
  //#endregion
1984
- //#region src/input/input.ts
2277
+ //#region src/input/input-action-map.ts
1985
2278
  const ANY = -1;
1986
2279
  const now = () => performance.now();
1987
2280
  const MOUSE_BUTTONS = [
@@ -1991,40 +2284,41 @@ const MOUSE_BUTTONS = [
1991
2284
  "back",
1992
2285
  "forward"
1993
2286
  ];
1994
- const BUTTON_BITS = [
1995
- 1,
1996
- 4,
1997
- 2,
1998
- 8,
1999
- 16
2000
- ];
2001
2287
  const isEditable = (target) => {
2002
2288
  const element = target;
2003
2289
  const tag = element?.tagName;
2004
2290
  return !!element && (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || element.isContentEditable === true);
2005
2291
  };
2006
2292
  /**
2007
- * Game input with a Godot-style action map: bind keys, buttons, sticks, gestures and VR controls
2008
- * to named actions, then query actions instead of devices.
2293
+ * Game input with a Godot-style action map, built on {@link Input}'s events: bind keys, buttons,
2294
+ * sticks, gestures and VR controls to named actions, then query actions instead of devices once
2295
+ * per frame. Gamepads and VR controllers are polled by `update()`.
2009
2296
  *
2010
- * const input = new Input(canvas);
2011
- * input.actions.add('jump', [key('Space'), pad('A')]);
2297
+ * Input.instance.target = canvas;
2298
+ *
2299
+ * const controls = new InputActionMap();
2300
+ * controls.actions.add('jump', [key('Space'), pad('A')]);
2012
2301
  *
2013
2302
  * // every frame, before game logic:
2014
- * input.update();
2015
- * if (input.isActionJustPressed('jump')) player.jump();
2303
+ * controls.update();
2304
+ * if (controls.isActionJustPressed('jump')) player.jump();
2016
2305
  *
2017
- * Call `dispose()` to remove all listeners.
2306
+ * Call `dispose()` to stop listening.
2018
2307
  *
2019
2308
  * @category Input
2020
2309
  */
2021
- var Input = class {
2022
- /** the actions to query; holds the `ui_*` defaults unless {@link InputOptions.defaults} is false */
2310
+ var InputActionMap = class {
2311
+ /** the actions to query; holds the `ui_*` defaults unless {@link InputActionMapOptions.defaults} is false */
2023
2312
  actions = new ActionMap();
2024
2313
  /** Thresholds for taps, swipes etc. can be tuned via `gestureRecognizer.thresholds`. */
2025
2314
  gestureRecognizer = new GestureRecognizer();
2026
- /** Two-finger gesture values for the last frame (pinch 1 / pan 0 / rotate 0 when not gesturing). */
2315
+ /**
2316
+ * Touch gestures from the last frame: `events` (each recognized gesture and where it happened,
2317
+ * e.g. the tap that triggered an action) and the two-finger values (pinch 1 / pan 0 / rotate 0
2318
+ * when not gesturing).
2319
+ */
2027
2320
  gestures = {
2321
+ events: [],
2028
2322
  pinch: 1,
2029
2323
  pan: {
2030
2324
  x: 0,
@@ -2032,6 +2326,8 @@ var Input = class {
2032
2326
  },
2033
2327
  rotate: 0
2034
2328
  };
2329
+ /** the {@link Input} events are read from */
2330
+ input;
2035
2331
  /** Fingers currently on the target. */
2036
2332
  get touches() {
2037
2333
  return this.gestureRecognizer.touches;
@@ -2051,7 +2347,7 @@ var Input = class {
2051
2347
  tiltX: 0,
2052
2348
  tiltY: 0
2053
2349
  };
2054
- /** notified when {@link Input.lastDevice} changes, e.g. to switch on-screen button prompts */
2350
+ /** notified when {@link InputActionMap.lastDevice} changes, e.g. to switch on-screen button prompts */
2055
2351
  onDeviceChange = new Observable();
2056
2352
  /** notified from update() when a gamepad is first seen */
2057
2353
  onGamepadConnected = new Observable();
@@ -2068,7 +2364,6 @@ var Input = class {
2068
2364
  }
2069
2365
  _lastDevice = "keyboard";
2070
2366
  _keyLabels;
2071
- _target;
2072
2367
  _options;
2073
2368
  _listeners = [];
2074
2369
  _controls = /* @__PURE__ */ new Map([[0, /* @__PURE__ */ new Map()]]);
@@ -2086,48 +2381,40 @@ var Input = class {
2086
2381
  get lastDevice() {
2087
2382
  return this._lastDevice;
2088
2383
  }
2089
- /** Whether the pointer is locked to the target, see {@link Input.lockPointer}. */
2384
+ /** Whether the pointer is locked to the target, see {@link InputActionMap.lockPointer}. */
2090
2385
  get isPointerLocked() {
2091
- return typeof document !== "undefined" && !!this._target && document.pointerLockElement === this._target;
2386
+ return typeof document !== "undefined" && document.pointerLockElement === this.input.target;
2092
2387
  }
2093
- /**
2094
- * @param target element that receives pointer, wheel and touch input (usually the canvas)
2095
- */
2096
- constructor(target, options = {}) {
2097
- this._target = target;
2388
+ constructor(options = {}) {
2389
+ this.input = options.input ?? Input.instance;
2098
2390
  this._options = {
2099
2391
  defaults: options.defaults ?? true,
2100
2392
  preventDefault: options.preventDefault ?? true,
2101
2393
  preventContextMenu: options.preventContextMenu ?? true
2102
2394
  };
2103
2395
  if (this._options.defaults) this.actions.addDefaults();
2104
- const keyboard = options.keyboardTarget ?? (typeof window !== "undefined" ? window : void 0);
2105
- if (keyboard) {
2106
- this._listen(keyboard, "keydown", (e) => this._onKeyDown(e));
2107
- this._listen(keyboard, "keyup", (e) => this._onKeyUp(e));
2108
- this._listen(keyboard, "blur", () => this.releaseAll(0));
2109
- }
2110
- if (typeof document !== "undefined") this._listen(document, "visibilitychange", () => {
2111
- if (document.hidden) this.releaseAll(0);
2112
- });
2113
- if (target) {
2114
- const style = target.style;
2115
- if (this._options.preventDefault && style) style.touchAction = "none";
2116
- this._listen(target, "pointerdown", (e) => this._onPointerDown(e));
2117
- this._listen(target, "pointerup", (e) => this._onPointerUp(e));
2118
- this._listen(target, "pointercancel", (e) => this._onPointerCancel(e));
2119
- this._listen(target, "pointermove", (e) => this._onPointerMove(e));
2120
- this._listen(target, "wheel", (e) => this._onWheel(e), { passive: false });
2121
- this._listen(target, "contextmenu", (e) => {
2122
- if (this._options.preventContextMenu) e.preventDefault();
2123
- });
2124
- }
2396
+ if (this._options.preventContextMenu) this.input.disableContextMenu();
2397
+ this._listen("key_down", (e) => this._onKeyDown(e));
2398
+ this._listen("key_repeat", (e) => this._onKeyDown(e));
2399
+ this._listen("key_up", (e) => this._onKeyUp(e));
2400
+ this._listen("button_down", (e) => this._onButton(e, 1));
2401
+ this._listen("button_up", (e) => this._onButton(e, 0));
2402
+ this._listen("pointer_move", (e) => this._onPointerMove(e));
2403
+ this._listen("touch_down", (e) => this._onTouchDown(e));
2404
+ this._listen("touch_move", (e) => this._onTouchMove(e));
2405
+ this._listen("touch_up", (e) => this._onTouchUp(e));
2406
+ this._listen("touch_cancel", (e) => this.gestureRecognizer.cancel(e.pointerId));
2407
+ this._listen("mouse_wheel", (e) => this._onWheel(e));
2408
+ this._listen("blur", () => this.releaseAll(0));
2125
2409
  }
2126
2410
  /**
2127
2411
  * Call once per frame, before reading input: polls devices and advances "just pressed" /
2128
2412
  * "just released" by one frame. Action callbacks fire from here.
2413
+ *
2414
+ * @param time current time in ms (e.g. the `requestAnimationFrame` timestamp), used for
2415
+ * gesture timing and auto-repeat; default `performance.now()`
2129
2416
  */
2130
- update() {
2417
+ update(time = now()) {
2131
2418
  this.pointer.deltaX = this._pending.deltaX;
2132
2419
  this.pointer.deltaY = this._pending.deltaY;
2133
2420
  this.pointer.wheelX = this._pending.wheelX;
@@ -2135,7 +2422,7 @@ var Input = class {
2135
2422
  this._pending.deltaX = this._pending.deltaY = this._pending.wheelX = this._pending.wheelY = 0;
2136
2423
  this._pollGamepads();
2137
2424
  this._pollXR();
2138
- this._updateGestures();
2425
+ this._updateGestures(time);
2139
2426
  const devices = [...this._controls.keys()];
2140
2427
  const fired = [];
2141
2428
  for (const name of this.actions.names) {
@@ -2147,29 +2434,43 @@ var Input = class {
2147
2434
  let raw = 0;
2148
2435
  for (const binding of action.bindings) raw = Math.max(raw, this._bindingValue(binding, device));
2149
2436
  anyRaw = Math.max(anyRaw, raw);
2150
- if (this._advance(states, device, raw, action.deadzone)) fired.push({
2437
+ const phase = this._advance(states, device, raw, action, time);
2438
+ if (phase) fired.push({
2151
2439
  action: name,
2152
- phase: states.get(device).pressed ? "pressed" : "released",
2153
- device
2440
+ phase,
2441
+ device,
2442
+ repeat: states.get(device).repeated
2154
2443
  });
2155
2444
  }
2156
- if (this._advance(states, ANY, anyRaw, action.deadzone)) fired.push({
2445
+ const phase = this._advance(states, ANY, anyRaw, action, time);
2446
+ if (phase) fired.push({
2157
2447
  action: name,
2158
- phase: states.get(ANY).pressed ? "pressed" : "released",
2159
- device: ANY
2448
+ phase,
2449
+ device: ANY,
2450
+ repeat: states.get(ANY).repeated
2160
2451
  });
2161
2452
  }
2162
2453
  for (const controls of this._controls.values()) for (const state of controls.values()) state.pressed = false;
2163
- 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();
2454
+ for (const { action, phase, device, repeat } of fired) for (const listener of [...this._actionListeners]) if (listener.action === action && listener.phase === phase && listener.device === device) listener.callback({
2455
+ action,
2456
+ repeat
2457
+ });
2164
2458
  }
2165
2459
  /** Whether the action is held past its deadzone. Unknown actions return false (and warn once). */
2166
2460
  isActionPressed(action, query) {
2167
2461
  return this._state(action, query)?.pressed ?? false;
2168
2462
  }
2169
- /** Whether the action became pressed in the last update(). */
2463
+ /**
2464
+ * Whether the action became pressed in the last update(), or auto-repeated while held if the
2465
+ * action has {@link Action.repeat} (e.g. to keep walking while a direction is held).
2466
+ */
2170
2467
  isActionJustPressed(action, query) {
2171
2468
  const state = this._state(action, query);
2172
- return !!state && state.pressed && !state.wasPressed;
2469
+ return !!state && state.pressed && (!state.wasPressed || state.repeated);
2470
+ }
2471
+ /** Whether the last update()'s press of the action was an auto-repeat rather than a new press. */
2472
+ isActionRepeated(action, query) {
2473
+ return this._state(action, query)?.repeated ?? false;
2173
2474
  }
2174
2475
  /** Whether the action was released in the last update(). */
2175
2476
  isActionJustReleased(action, query) {
@@ -2219,7 +2520,11 @@ var Input = class {
2219
2520
  y
2220
2521
  };
2221
2522
  }
2222
- /** Calls `callback` when the action is pressed or released (during update()). Returns an unsubscribe function. */
2523
+ /**
2524
+ * Calls `callback` when the action is pressed or released (during update()). With
2525
+ * {@link Action.repeat}, `'pressed'` also fires on each auto-repeat, with `event.repeat` set.
2526
+ * Returns an unsubscribe function.
2527
+ */
2223
2528
  onAction(action, phase, callback, query = {}) {
2224
2529
  const listener = {
2225
2530
  action,
@@ -2257,7 +2562,7 @@ var Input = class {
2257
2562
  }
2258
2563
  /** Requests pointer lock on the target (browsers only allow it from a user gesture, e.g. a click). */
2259
2564
  lockPointer() {
2260
- this._target?.requestPointerLock?.();
2565
+ this.input.target.requestPointerLock?.();
2261
2566
  }
2262
2567
  /** Exits pointer lock if the target holds it. */
2263
2568
  unlockPointer() {
@@ -2277,7 +2582,7 @@ var Input = class {
2277
2582
  };
2278
2583
  });
2279
2584
  }
2280
- /** Ends a pending {@link Input.captureBinding}, resolving it with `null`. */
2585
+ /** Ends a pending {@link InputActionMap.captureBinding}, resolving it with `null`. */
2281
2586
  cancelCapture() {
2282
2587
  const capture = this._capture;
2283
2588
  this._capture = void 0;
@@ -2296,51 +2601,59 @@ var Input = class {
2296
2601
  }
2297
2602
  return this._keyLabels;
2298
2603
  }
2299
- /** The layout loaded by {@link Input.loadKeyboardLayout}, if any: `KeyboardEvent.code` to printed key. */
2604
+ /** The layout loaded by {@link InputActionMap.loadKeyboardLayout}, if any: `KeyboardEvent.code` to printed key. */
2300
2605
  get keyLabels() {
2301
2606
  return this._keyLabels;
2302
2607
  }
2303
2608
  /** Removes all event listeners and action callbacks, cancels any capture and detaches XR. */
2304
2609
  dispose() {
2305
- for (const [target, type, listener, options] of this._listeners) target.removeEventListener(type, listener, options);
2610
+ for (const [type, listener] of this._listeners) this.input.off(type, listener);
2306
2611
  this._listeners.length = 0;
2307
2612
  this._actionListeners.length = 0;
2308
2613
  this.cancelCapture();
2309
2614
  this.detachXR();
2310
2615
  }
2311
- _listen(target, type, listener, options) {
2312
- target.addEventListener(type, listener, options);
2313
- this._listeners.push([
2314
- target,
2315
- type,
2316
- listener,
2317
- options
2318
- ]);
2616
+ _listen(type, listener) {
2617
+ this.input.on(type, listener);
2618
+ this._listeners.push([type, listener]);
2319
2619
  }
2320
2620
  _state(action, query) {
2321
2621
  if (!this.actions.has(action)) {
2322
2622
  if (!this._warned.has(action)) {
2323
2623
  this._warned.add(action);
2324
- console.warn(`Input: unknown action "${action}"`);
2624
+ console.warn(`InputActionMap: unknown action "${action}"`);
2325
2625
  }
2326
2626
  return;
2327
2627
  }
2328
2628
  return this._actionStates.get(action)?.get(query?.device ?? ANY);
2329
2629
  }
2330
- _advance(states, device, raw, deadzone) {
2630
+ _advance(states, device, raw, action, time) {
2631
+ const deadzone = action.deadzone;
2331
2632
  let state = states.get(device);
2332
2633
  if (!state) states.set(device, state = {
2333
2634
  raw: 0,
2334
2635
  strength: 0,
2335
2636
  pressed: false,
2336
- wasPressed: false
2637
+ wasPressed: false,
2638
+ repeated: false,
2639
+ nextRepeat: 0
2337
2640
  });
2338
2641
  state.wasPressed = state.pressed;
2642
+ state.repeated = false;
2339
2643
  state.raw = raw;
2340
2644
  state.pressed = raw > 0 && raw >= deadzone;
2341
2645
  state.strength = !state.pressed ? 0 : deadzone >= 1 ? 1 : Math.min(1, (raw - deadzone) / (1 - deadzone));
2342
2646
  if (state.pressed && raw >= 1) state.strength = 1;
2343
- return state.pressed !== state.wasPressed;
2647
+ if (state.pressed !== state.wasPressed) {
2648
+ if (state.pressed && action.repeat) state.nextRepeat = time + action.repeat.delay;
2649
+ return state.pressed ? "pressed" : "released";
2650
+ }
2651
+ if (state.pressed && action.repeat && time >= state.nextRepeat) {
2652
+ const next = state.nextRepeat + action.repeat.interval;
2653
+ state.repeated = true;
2654
+ state.nextRepeat = next > time ? next : time + action.repeat.interval;
2655
+ return "pressed";
2656
+ }
2344
2657
  }
2345
2658
  _controlValue(device, id) {
2346
2659
  const state = this._controls.get(device)?.get(id);
@@ -2465,8 +2778,9 @@ var Input = class {
2465
2778
  });
2466
2779
  }
2467
2780
  }
2468
- _updateGestures() {
2469
- const frame = this.gestureRecognizer.update(now());
2781
+ _updateGestures(time) {
2782
+ const frame = this.gestureRecognizer.update(time);
2783
+ this.gestures.events = frame.events;
2470
2784
  this.gestures.pinch = frame.pinch;
2471
2785
  this.gestures.pan = frame.pan;
2472
2786
  this.gestures.rotate = frame.rotate;
@@ -2478,7 +2792,7 @@ var Input = class {
2478
2792
  _xrSession;
2479
2793
  _xrEnd;
2480
2794
  _xrHeld = /* @__PURE__ */ new Set();
2481
- /** The session set by {@link Input.attachXR}, until detached or ended. */
2795
+ /** The session set by {@link InputActionMap.attachXR}, until detached or ended. */
2482
2796
  get xrSession() {
2483
2797
  return this._xrSession;
2484
2798
  }
@@ -2571,79 +2885,51 @@ var Input = class {
2571
2885
  }, 0);
2572
2886
  }
2573
2887
  _updatePointer(event) {
2574
- const rect = this._target?.getBoundingClientRect?.();
2575
- const left = rect?.left ?? 0;
2576
- const top = rect?.top ?? 0;
2577
- const width = rect?.width || 1;
2578
- const height = rect?.height || 1;
2579
2888
  this.pointer.type = event.pointerType === "pen" ? "pen" : "mouse";
2580
- this.pointer.x = event.clientX - left;
2581
- this.pointer.y = event.clientY - top;
2582
- this.pointer.ndcX = this.pointer.x / width * 2 - 1;
2583
- this.pointer.ndcY = -(this.pointer.y / height * 2 - 1);
2889
+ this.pointer.x = this.input.pointerPosition.x;
2890
+ this.pointer.y = this.input.pointerPosition.y;
2891
+ this.pointer.ndcX = this.input.pointerPositionNdc.x;
2892
+ this.pointer.ndcY = this.input.pointerPositionNdc.y;
2584
2893
  this.pointer.pressure = event.pressure ?? 0;
2585
2894
  this.pointer.tiltX = event.tiltX ?? 0;
2586
2895
  this.pointer.tiltY = event.tiltY ?? 0;
2587
2896
  }
2588
2897
  _local(event) {
2589
- const rect = this._target?.getBoundingClientRect?.();
2898
+ const rect = this.input.target.getBoundingClientRect?.();
2590
2899
  return {
2591
2900
  x: event.clientX - (rect?.left ?? 0),
2592
2901
  y: event.clientY - (rect?.top ?? 0)
2593
2902
  };
2594
2903
  }
2595
- _onPointerDown(event) {
2596
- if (event.pointerType === "touch") {
2597
- const { x, y } = this._local(event);
2598
- this.gestureRecognizer.down(event.pointerId, x, y, now());
2599
- this._setLastDevice("touch");
2600
- this._target?.setPointerCapture?.(event.pointerId);
2601
- return;
2602
- }
2904
+ _onButton(event, value) {
2905
+ if (event.pointerType === "touch") return;
2603
2906
  this._updatePointer(event);
2604
2907
  this._setLastDevice(event.pointerType === "pen" ? "pen" : "mouse");
2605
2908
  const button = MOUSE_BUTTONS[event.button];
2606
2909
  if (button) this._setControl(0, {
2607
2910
  type: "mouse",
2608
2911
  button
2609
- }, 1);
2610
- this._target?.setPointerCapture?.(event.pointerId);
2611
- }
2612
- _onPointerUp(event) {
2613
- if (event.pointerType === "touch") {
2614
- const { x, y } = this._local(event);
2615
- this.gestureRecognizer.up(event.pointerId, x, y, now());
2616
- return;
2617
- }
2618
- this._updatePointer(event);
2619
- const button = MOUSE_BUTTONS[event.button];
2620
- if (button) this._setControl(0, {
2621
- type: "mouse",
2622
- button
2623
- }, 0);
2624
- }
2625
- _onPointerCancel(event) {
2626
- if (event.pointerType === "touch") this.gestureRecognizer.cancel(event.pointerId);
2627
- else this._onPointerUp(event);
2912
+ }, value);
2628
2913
  }
2629
2914
  _onPointerMove(event) {
2630
- if (event.pointerType === "touch") {
2631
- const { x, y } = this._local(event);
2632
- this.gestureRecognizer.move(event.pointerId, x, y);
2633
- return;
2634
- }
2915
+ if (event.pointerType === "touch") return;
2635
2916
  this._updatePointer(event);
2636
2917
  this._setLastDevice(event.pointerType === "pen" ? "pen" : "mouse");
2637
2918
  this._pending.deltaX += event.movementX ?? 0;
2638
2919
  this._pending.deltaY += event.movementY ?? 0;
2639
- const button = MOUSE_BUTTONS[event.button];
2640
- if (button) {
2641
- const down = ((event.buttons ?? 0) & BUTTON_BITS[event.button]) !== 0;
2642
- this._setControl(0, {
2643
- type: "mouse",
2644
- button
2645
- }, down ? 1 : 0);
2646
- }
2920
+ }
2921
+ _onTouchDown(event) {
2922
+ const { x, y } = this._local(event);
2923
+ this.gestureRecognizer.down(event.pointerId, x, y, now());
2924
+ this._setLastDevice("touch");
2925
+ }
2926
+ _onTouchMove(event) {
2927
+ const { x, y } = this._local(event);
2928
+ this.gestureRecognizer.move(event.pointerId, x, y);
2929
+ }
2930
+ _onTouchUp(event) {
2931
+ const { x, y } = this._local(event);
2932
+ this.gestureRecognizer.up(event.pointerId, x, y, now());
2647
2933
  }
2648
2934
  _onWheel(event) {
2649
2935
  const scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 800 : 1;
@@ -2706,7 +2992,7 @@ const getRedYellowGreenGradientHex = (value, max = 1) => {
2706
2992
  "#66ff00",
2707
2993
  "#33ff00",
2708
2994
  "#00ff00"
2709
- ][require_spatial_partition_3d.clamp(Math.floor(percent * 10), 0, 10)];
2995
+ ][require_rng.clamp(Math.floor(percent * 10), 0, 10)];
2710
2996
  };
2711
2997
  /**
2712
2998
  * The current page's query-string parameters as a plain object of strings (the last value wins
@@ -3708,18 +3994,19 @@ exports.DEFAULT_FONT_SIZE = DEFAULT_FONT_SIZE;
3708
3994
  exports.DEFAULT_MAP_2D_VALUE = DEFAULT_MAP_2D_VALUE;
3709
3995
  exports.DEFAULT_MAP_3D_VALUE = require_spatial_partition_3d.DEFAULT_MAP_3D_VALUE;
3710
3996
  exports.DEFAULT_PIXEL_SIZE = DEFAULT_PIXEL_SIZE;
3997
+ exports.DEFAULT_REPEAT = DEFAULT_REPEAT;
3711
3998
  exports.DEFAULT_TEXTALIGN = DEFAULT_TEXTALIGN;
3712
3999
  exports.DEFAULT_TEXTBASELINE = DEFAULT_TEXTBASELINE;
3713
- exports.DEG2RAD = require_spatial_partition_3d.DEG2RAD;
4000
+ exports.DEG2RAD = require_rng.DEG2RAD;
3714
4001
  exports.DeleteProgramInfo = DeleteProgramInfo;
3715
4002
  exports.DeleteRenderTarget = DeleteRenderTarget;
3716
4003
  exports.DeleteTexture = DeleteTexture;
3717
4004
  exports.DeleteVertexArray = DeleteVertexArray;
3718
4005
  exports.Disposable = Disposable;
3719
4006
  exports.Draw = Draw;
3720
- exports.E = require_spatial_partition_3d.E;
4007
+ exports.E = require_rng.E;
3721
4008
  exports.ECS = ECS;
3722
- exports.EPSILON = require_spatial_partition_3d.EPSILON;
4009
+ exports.EPSILON = require_rng.EPSILON;
3723
4010
  exports.Emitter = Emitter;
3724
4011
  exports.EventQueue = EventQueue;
3725
4012
  exports.GAMEPAD_AXES = GAMEPAD_AXES;
@@ -3731,12 +4018,13 @@ exports.GenerateWalls = GenerateWalls;
3731
4018
  exports.GestureRecognizer = GestureRecognizer;
3732
4019
  exports.GetProgramLocations = GetProgramLocations;
3733
4020
  exports.GetUrlParams = GetUrlParams;
3734
- exports.HALF_PI = require_spatial_partition_3d.HALF_PI;
4021
+ exports.HALF_PI = require_rng.HALF_PI;
3735
4022
  exports.Input = Input;
3736
- exports.LN10 = require_spatial_partition_3d.LN10;
3737
- exports.LN2 = require_spatial_partition_3d.LN2;
3738
- exports.LOG10E = require_spatial_partition_3d.LOG10E;
3739
- exports.LOG2E = require_spatial_partition_3d.LOG2E;
4023
+ exports.InputActionMap = InputActionMap;
4024
+ exports.LN10 = require_rng.LN10;
4025
+ exports.LN2 = require_rng.LN2;
4026
+ exports.LOG10E = require_rng.LOG10E;
4027
+ exports.LOG2E = require_rng.LOG2E;
3740
4028
  exports.LoadWebGlTexture = LoadWebGlTexture;
3741
4029
  exports.MAP_2D_MAX_COORD = MAP_2D_MAX_COORD;
3742
4030
  exports.MAP_2D_MIN_COORD = MAP_2D_MIN_COORD;
@@ -3746,24 +4034,24 @@ exports.Map2D = Map2D;
3746
4034
  exports.Map3D = require_spatial_partition_3d.Map3D;
3747
4035
  exports.ONE_SECOND = ONE_SECOND;
3748
4036
  exports.Observable = Observable;
3749
- exports.PI = require_spatial_partition_3d.PI;
4037
+ exports.PI = require_rng.PI;
3750
4038
  exports.ParticleRenderer = ParticleRenderer;
3751
4039
  exports.ParticleSystem2d = require_spatial_partition_3d.ParticleSystem2d;
3752
- exports.QUARTER_PI = require_spatial_partition_3d.QUARTER_PI;
3753
- exports.RAD2DEG = require_spatial_partition_3d.RAD2DEG;
3754
- exports.Random = require_spatial_partition_3d.Random;
4040
+ exports.QUARTER_PI = require_rng.QUARTER_PI;
4041
+ exports.RAD2DEG = require_rng.RAD2DEG;
4042
+ exports.Random = require_rng.Random;
3755
4043
  exports.Rectangle = Rectangle;
3756
4044
  exports.ResizeRenderTarget = ResizeRenderTarget;
3757
4045
  exports.ResizeWebGlContext = ResizeWebGlContext;
3758
- exports.Rng = require_spatial_partition_3d.Rng;
3759
- exports.SQRT1_2 = require_spatial_partition_3d.SQRT1_2;
3760
- exports.SQRT2 = require_spatial_partition_3d.SQRT2;
4046
+ exports.Rng = require_rng.Rng;
4047
+ exports.SQRT1_2 = require_rng.SQRT1_2;
4048
+ exports.SQRT2 = require_rng.SQRT2;
3761
4049
  exports.SetUniforms = SetUniforms;
3762
4050
  exports.ShaderType = ShaderType;
3763
4051
  exports.Signal = Signal;
3764
4052
  exports.SpatialPartition2d = require_spatial_partition_3d.SpatialPartition2d;
3765
4053
  exports.SpatialPartition3d = require_spatial_partition_3d.SpatialPartition3d;
3766
- exports.TAU = require_spatial_partition_3d.TAU;
4054
+ exports.TAU = require_rng.TAU;
3767
4055
  exports.TILE_EMPTY = TILE_EMPTY;
3768
4056
  exports.TILE_FLOOR = TILE_FLOOR;
3769
4057
  exports.TILE_PATH = TILE_PATH;
@@ -3778,42 +4066,42 @@ exports.XR_BUTTONS = XR_BUTTONS;
3778
4066
  exports.bindingLabel = bindingLabel;
3779
4067
  exports.bindingsEqual = bindingsEqual;
3780
4068
  exports.buildColorPalette = buildColorPalette;
3781
- exports.clamp = require_spatial_partition_3d.clamp;
4069
+ exports.clamp = require_rng.clamp;
3782
4070
  exports.controlId = controlId;
3783
- exports.degrees = require_spatial_partition_3d.degrees;
3784
- exports.distance2d = require_spatial_partition_3d.distance2d;
3785
- exports.distance3d = require_spatial_partition_3d.distance3d;
4071
+ exports.degrees = require_rng.degrees;
4072
+ exports.distance2d = require_rng.distance2d;
4073
+ exports.distance3d = require_rng.distance3d;
3786
4074
  exports.ecs = ecs;
3787
4075
  exports.findPath = findPath;
3788
- exports.fract = require_spatial_partition_3d.fract;
4076
+ exports.fract = require_rng.fract;
3789
4077
  exports.gesture = gesture;
3790
4078
  exports.getRedYellowGreenGradientHex = getRedYellowGreenGradientHex;
3791
- exports.hash32 = require_spatial_partition_3d.hash32;
3792
- exports.hash32mix = require_spatial_partition_3d.hash32mix;
3793
- exports.inverseLerp = require_spatial_partition_3d.inverseLerp;
4079
+ exports.hash32 = require_rng.hash32;
4080
+ exports.hash32mix = require_rng.hash32mix;
4081
+ exports.inverseLerp = require_rng.inverseLerp;
3794
4082
  exports.isNullOrUndefined = isNullOrUndefined;
3795
4083
  exports.isPositiveString = isPositiveString;
3796
4084
  exports.k2xy = k2xy;
3797
4085
  exports.k2xyz = k2xyz;
3798
4086
  exports.key = key;
3799
- exports.lerp = require_spatial_partition_3d.lerp;
4087
+ exports.lerp = require_rng.lerp;
3800
4088
  exports.log = require_spatial_partition_3d.log;
3801
- exports.manhattanDistance = require_spatial_partition_3d.manhattanDistance;
3802
- exports.mod = require_spatial_partition_3d.mod;
4089
+ exports.manhattanDistance = require_rng.manhattanDistance;
4090
+ exports.mod = require_rng.mod;
3803
4091
  exports.mouse = mouse;
3804
- exports.nearlyEqual = require_spatial_partition_3d.nearlyEqual;
3805
- exports.normalizeRadians = require_spatial_partition_3d.normalizeRadians;
4092
+ exports.nearlyEqual = require_rng.nearlyEqual;
4093
+ exports.normalizeRadians = require_rng.normalizeRadians;
3806
4094
  exports.pad = pad;
3807
4095
  exports.padAxis = padAxis;
3808
- exports.radians = require_spatial_partition_3d.radians;
4096
+ exports.radians = require_rng.radians;
3809
4097
  exports.randomMatrix = require_spatial_partition_3d.randomMatrix;
3810
- exports.rng = require_spatial_partition_3d.rng;
3811
- exports.roundTo = require_spatial_partition_3d.roundTo;
3812
- exports.saturate = require_spatial_partition_3d.saturate;
3813
- exports.smoothstep = require_spatial_partition_3d.smoothstep;
3814
- exports.squaredDistance = require_spatial_partition_3d.squaredDistance;
4098
+ exports.rng = require_rng.rng;
4099
+ exports.roundTo = require_rng.roundTo;
4100
+ exports.saturate = require_rng.saturate;
4101
+ exports.smoothstep = require_rng.smoothstep;
4102
+ exports.squaredDistance = require_rng.squaredDistance;
3815
4103
  exports.wheel = wheel;
3816
- exports.wrap = require_spatial_partition_3d.wrap;
4104
+ exports.wrap = require_rng.wrap;
3817
4105
  exports.xr = xr;
3818
4106
  exports.xrAxis = xrAxis;
3819
4107
  exports.xy2k = xy2k;