@n3rdw1z4rd/core 0.18.5 → 0.19.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 (109) hide show
  1. package/README.md +72 -10
  2. package/dist/astar.d.ts +44 -0
  3. package/dist/astar.js +118 -0
  4. package/dist/canvas-renderer.d.ts +154 -0
  5. package/dist/canvas-renderer.js +200 -0
  6. package/dist/clock.d.ts +69 -0
  7. package/dist/clock.js +108 -0
  8. package/dist/color-palette.d.ts +25 -0
  9. package/dist/color-palette.js +112 -0
  10. package/dist/color.d.ts +90 -0
  11. package/dist/color.js +224 -0
  12. package/dist/css/main.css +1 -3
  13. package/dist/disposable.d.ts +27 -0
  14. package/dist/disposable.js +32 -0
  15. package/dist/dungeon-generator.d.ts +142 -0
  16. package/dist/dungeon-generator.js +288 -0
  17. package/dist/ecs.d.ts +87 -0
  18. package/dist/ecs.js +101 -0
  19. package/dist/emitter.d.ts +40 -0
  20. package/dist/emitter.js +54 -0
  21. package/dist/event-queue.d.ts +29 -0
  22. package/dist/event-queue.js +40 -0
  23. package/dist/index.cjs +3813 -0
  24. package/dist/index.d.cts +2655 -0
  25. package/dist/index.d.ts +35 -873
  26. package/dist/index.js +34 -3981
  27. package/dist/input/action-map.d.ts +79 -0
  28. package/dist/input/action-map.js +131 -0
  29. package/dist/input/bindings.d.ts +273 -0
  30. package/dist/input/bindings.js +250 -0
  31. package/dist/input/gestures.d.ts +108 -0
  32. package/dist/input/gestures.js +159 -0
  33. package/dist/input/index.d.ts +5 -0
  34. package/dist/input/index.js +5 -0
  35. package/dist/input/input.d.ts +297 -0
  36. package/dist/input/input.js +695 -0
  37. package/dist/log.d.ts +8 -0
  38. package/dist/log.js +9 -0
  39. package/dist/map2d.d.ts +83 -0
  40. package/dist/map2d.js +120 -0
  41. package/dist/map3d-CHDJiq5T.d.cts +236 -0
  42. package/dist/map3d.d.ts +94 -0
  43. package/dist/map3d.js +148 -0
  44. package/dist/math.d.ts +176 -0
  45. package/dist/math.js +206 -0
  46. package/dist/misc.d.ts +46 -0
  47. package/dist/misc.js +71 -0
  48. package/dist/observable.d.ts +43 -0
  49. package/dist/observable.js +53 -0
  50. package/dist/particle-renderer.d.ts +47 -0
  51. package/dist/particle-renderer.js +82 -0
  52. package/dist/particle-system-2d.d.ts +60 -0
  53. package/dist/particle-system-2d.js +147 -0
  54. package/dist/random.d.ts +46 -0
  55. package/dist/random.js +74 -0
  56. package/dist/rectangle.d.ts +44 -0
  57. package/dist/rectangle.js +69 -0
  58. package/dist/rng.d.ts +72 -0
  59. package/dist/rng.js +152 -0
  60. package/dist/signal.d.ts +34 -0
  61. package/dist/signal.js +41 -0
  62. package/dist/spatial-partition-2d.d.ts +42 -0
  63. package/dist/spatial-partition-2d.js +52 -0
  64. package/dist/spatial-partition-3d-Ba-VBveM.cjs +1324 -0
  65. package/dist/spatial-partition-3d.d.ts +44 -0
  66. package/dist/spatial-partition-3d.js +57 -0
  67. package/dist/three/asteroid-mesh.d.ts +41 -0
  68. package/dist/three/asteroid-mesh.js +44 -0
  69. package/dist/three/camera-rig.d.ts +140 -0
  70. package/dist/three/camera-rig.js +197 -0
  71. package/dist/three/cube-sphere-geometry.d.ts +55 -0
  72. package/dist/three/cube-sphere-geometry.js +239 -0
  73. package/dist/three/ecs.d.ts +75 -0
  74. package/dist/three/ecs.js +64 -0
  75. package/dist/three/index.d.ts +12 -0
  76. package/dist/three/index.js +12 -0
  77. package/dist/three/particle-system-3d.d.ts +53 -0
  78. package/dist/three/particle-system-3d.js +224 -0
  79. package/dist/three/renderer.d.ts +38 -0
  80. package/dist/three/renderer.js +57 -0
  81. package/dist/three/starfield.d.ts +23 -0
  82. package/dist/three/starfield.js +64 -0
  83. package/dist/three/texture-atlas.d.ts +76 -0
  84. package/dist/three/texture-atlas.js +84 -0
  85. package/dist/three/texture-utils.d.ts +31 -0
  86. package/dist/three/texture-utils.js +44 -0
  87. package/dist/three/voxel-geometry.d.ts +72 -0
  88. package/dist/three/voxel-geometry.js +231 -0
  89. package/dist/three/voxel-mesh.d.ts +67 -0
  90. package/dist/three/voxel-mesh.js +71 -0
  91. package/dist/three.cjs +1307 -0
  92. package/dist/three.d.cts +655 -0
  93. package/dist/tilemap.d.ts +17 -0
  94. package/dist/tilemap.js +26 -0
  95. package/dist/types.d.ts +34 -0
  96. package/dist/types.js +0 -0
  97. package/dist/vector.d.ts +78 -0
  98. package/dist/vector.js +169 -0
  99. package/dist/webgl-renderer.d.ts +89 -0
  100. package/dist/webgl-renderer.js +140 -0
  101. package/dist/webgl.d.ts +357 -0
  102. package/dist/webgl.js +628 -0
  103. package/dist/worker-interface.d.ts +30 -0
  104. package/dist/worker-interface.js +39 -0
  105. package/package.json +55 -13
  106. package/dist/css/index.ts +0 -1
  107. package/dist/index.css +0 -104
  108. package/dist/index.d.mts +0 -873
  109. package/dist/index.mjs +0 -3977
package/dist/index.cjs ADDED
@@ -0,0 +1,3813 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_spatial_partition_3d = require("./spatial-partition-3d-Ba-VBveM.cjs");
3
+ let heap_js = require("heap-js");
4
+ //#region src/astar.ts
5
+ const DEFAULT_MAX_NODES = 1e4;
6
+ const DIRECTIONS = [
7
+ [0, -1],
8
+ [1, 0],
9
+ [0, 1],
10
+ [-1, 0],
11
+ [1, -1],
12
+ [1, 1],
13
+ [-1, 1],
14
+ [-1, -1]
15
+ ];
16
+ const KEY_OFFSET = 33554432;
17
+ const KEY_BASE = 67108864;
18
+ const key$1 = (x, y) => (x + KEY_OFFSET) * KEY_BASE + (y + KEY_OFFSET);
19
+ /**
20
+ * Finds a lowest-cost path on an unbounded grid with A*.
21
+ *
22
+ * The returned path excludes `start` and ends on the goal (or, with `adjacent`, on a tile next to
23
+ * it). Returns [] if `start` already satisfies the goal, or if no path is found (unless `partial`).
24
+ * The same inputs always produce the same path.
25
+ *
26
+ * ```ts
27
+ * const walls = new Set(['2,0', '2,1', '2,2']);
28
+ * const cost: StepCost = (x, y) => walls.has(`${x},${y}`) ? Infinity : 1;
29
+ *
30
+ * const path = findPath({ x: 0, y: 1 }, { x: 4, y: 1 }, cost, { diagonal: true });
31
+ * ```
32
+ *
33
+ * @category Pathfinding & Procedural
34
+ */
35
+ function findPath(start, goal, cost, options = {}) {
36
+ const diagonal = options.diagonal ?? false;
37
+ const cutCorners = options.cutCorners ?? false;
38
+ const adjacent = options.adjacent ?? false;
39
+ const maxNodes = options.maxNodes ?? DEFAULT_MAX_NODES;
40
+ const partial = options.partial ?? false;
41
+ const directions = diagonal ? DIRECTIONS : DIRECTIONS.slice(0, 4);
42
+ const heuristic = (x, y) => {
43
+ const dx = Math.abs(x - goal.x);
44
+ 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
+ };
47
+ const isGoal = (x, y) => {
48
+ if (x === goal.x && y === goal.y) return true;
49
+ if (!adjacent) return false;
50
+ const dx = Math.abs(x - goal.x);
51
+ const dy = Math.abs(y - goal.y);
52
+ return diagonal ? Math.max(dx, dy) === 1 : dx + dy === 1;
53
+ };
54
+ const passable = (x, y) => cost(x, y) < Infinity;
55
+ if (!adjacent && !partial && !passable(goal.x, goal.y) && !(start.x === goal.x && start.y === goal.y)) return [];
56
+ let seq = 0;
57
+ const open = new heap_js.Heap((a, b) => a.f - b.f || a.h - b.h || a.seq - b.seq);
58
+ const best = /* @__PURE__ */ new Map();
59
+ const closed = /* @__PURE__ */ new Set();
60
+ const startNode = {
61
+ x: start.x,
62
+ y: start.y,
63
+ g: 0,
64
+ h: heuristic(start.x, start.y),
65
+ f: 0,
66
+ seq: seq++
67
+ };
68
+ startNode.f = startNode.h;
69
+ open.push(startNode);
70
+ best.set(key$1(start.x, start.y), startNode);
71
+ let closest = startNode;
72
+ let expanded = 0;
73
+ while (open.length > 0 && expanded < maxNodes) {
74
+ const current = open.pop();
75
+ const currentKey = key$1(current.x, current.y);
76
+ if (closed.has(currentKey)) continue;
77
+ if (isGoal(current.x, current.y)) return buildPath(current);
78
+ closed.add(currentKey);
79
+ expanded++;
80
+ if (current.h < closest.h || current.h === closest.h && current.g < closest.g) closest = current;
81
+ for (let d = 0; d < directions.length; d++) {
82
+ const [dx, dy] = directions[d];
83
+ const x = current.x + dx;
84
+ const y = current.y + dy;
85
+ const k = key$1(x, y);
86
+ if (closed.has(k)) continue;
87
+ const stepCost = cost(x, y);
88
+ if (!(stepCost < Infinity)) continue;
89
+ const isDiagonal = dx !== 0 && dy !== 0;
90
+ 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 known = best.get(k);
93
+ if (known && known.g <= g) continue;
94
+ const h = known?.h ?? heuristic(x, y);
95
+ const node = {
96
+ x,
97
+ y,
98
+ g,
99
+ h,
100
+ f: g + h,
101
+ seq: seq++,
102
+ parent: current
103
+ };
104
+ best.set(k, node);
105
+ open.push(node);
106
+ }
107
+ }
108
+ return partial ? buildPath(closest) : [];
109
+ }
110
+ function buildPath(end) {
111
+ const path = [];
112
+ for (let node = end; node?.parent; node = node.parent) path.push({
113
+ x: node.x,
114
+ y: node.y
115
+ });
116
+ return path.reverse();
117
+ }
118
+ //#endregion
119
+ //#region src/canvas-renderer.ts
120
+ /**
121
+ * Fill / stroke color used when {@link DrawParams.color} is not given.
122
+ *
123
+ * @category Canvas 2D
124
+ */
125
+ const DEFAULT_COLOR = "white";
126
+ /**
127
+ * Side length in pixels of {@link CanvasRenderer.drawPixel} when {@link DrawParams.size} is not given.
128
+ *
129
+ * @category Canvas 2D
130
+ */
131
+ const DEFAULT_PIXEL_SIZE = 1;
132
+ /**
133
+ * Font size in pixels for {@link CanvasRenderer.drawText}.
134
+ *
135
+ * @category Canvas 2D
136
+ */
137
+ const DEFAULT_FONT_SIZE = 14;
138
+ /**
139
+ * Font family for {@link CanvasRenderer.drawText}.
140
+ *
141
+ * @category Canvas 2D
142
+ */
143
+ const DEFAULT_FONT_NAME = "monospace";
144
+ /**
145
+ * CSS font built from {@link DEFAULT_FONT_SIZE} and {@link DEFAULT_FONT_NAME} (`'14px monospace'`).
146
+ *
147
+ * @category Canvas 2D
148
+ */
149
+ const DEFAULT_FONT = `14px ${DEFAULT_FONT_NAME}`;
150
+ /**
151
+ * Default `textAlign` for {@link CanvasRenderer.drawText}.
152
+ *
153
+ * @category Canvas 2D
154
+ */
155
+ const DEFAULT_TEXTALIGN = "left";
156
+ /**
157
+ * Default `textBaseline` for {@link CanvasRenderer.drawText}.
158
+ *
159
+ * @category Canvas 2D
160
+ */
161
+ const DEFAULT_TEXTBASELINE = "alphabetic";
162
+ /**
163
+ * Immediate-mode drawing of simple shapes, text and sprites on a 2D canvas. Rectangles, pixels and
164
+ * sprites are positioned by their center; circles and polygons by their center and radius.
165
+ *
166
+ * ```ts
167
+ * const renderer = new CanvasRenderer();
168
+ * document.body.appendChild(renderer.canvas);
169
+ * renderer.resize(); // to the parent's size
170
+ *
171
+ * renderer.clear();
172
+ * renderer.drawCircle(100, 100, 20, { color: 'red', filled: true });
173
+ * renderer.drawText(10, 20, 'hello', { size: 16 });
174
+ * ```
175
+ *
176
+ * @category Canvas 2D
177
+ */
178
+ var CanvasRenderer = class {
179
+ /** the 2D context all drawing goes through */
180
+ context;
181
+ /** the canvas being drawn on */
182
+ get canvas() {
183
+ return this.context.canvas;
184
+ }
185
+ /** canvas width in pixels */
186
+ get width() {
187
+ return this.canvas.width;
188
+ }
189
+ /** canvas height in pixels */
190
+ get height() {
191
+ return this.canvas.height;
192
+ }
193
+ /**
194
+ * @param canvas defaults to a new canvas element, not attached to the page (append {@link CanvasRenderer.canvas} yourself)
195
+ */
196
+ constructor(canvas) {
197
+ this.context = (canvas ?? document.createElement("canvas")).getContext("2d");
198
+ this._applyDefaults();
199
+ }
200
+ _applyDefaults() {
201
+ this.context.font = DEFAULT_FONT;
202
+ this.context.textAlign = DEFAULT_TEXTALIGN;
203
+ this.context.textBaseline = DEFAULT_TEXTBASELINE;
204
+ }
205
+ /**
206
+ * Sets the canvas size in pixels; a missing dimension defaults to the parent element's client
207
+ * size (or the current size without a parent, or while the parent has no size). Resizing clears
208
+ * the canvas and resets the context state; the renderer's default font and alignment are
209
+ * applied again. Returns whether the size changed.
210
+ */
211
+ resize(width, height) {
212
+ let resized = false;
213
+ width = width ?? (this.canvas.parentElement?.clientWidth || this.width);
214
+ height = height ?? (this.canvas.parentElement?.clientHeight || this.height);
215
+ if (this.canvas.width != width || this.canvas.height != height) {
216
+ this.canvas.width = width;
217
+ this.canvas.height = height;
218
+ this._applyDefaults();
219
+ resized = true;
220
+ }
221
+ return resized;
222
+ }
223
+ /** Clears the whole canvas to transparent. */
224
+ clear() {
225
+ this.context.clearRect(0, 0, this.width, this.height);
226
+ }
227
+ drawPath(buildPath, params = {}) {
228
+ this.context.fillStyle = params.color ?? "white";
229
+ this.context.strokeStyle = params.color ?? "white";
230
+ this.context.lineWidth = params.size ?? 1;
231
+ if (params.lineDash) this.context.setLineDash(params.lineDash);
232
+ this.context.beginPath();
233
+ buildPath();
234
+ if (params.filled) this.context.fill();
235
+ else this.context.stroke();
236
+ if (params.lineDash) this.context.setLineDash([]);
237
+ }
238
+ /** Draws a `width` x `height` rectangle centered on (`x`, `y`): its outline, or filled with `filled`. */
239
+ drawRect(x, y, width, height, params = {}) {
240
+ x -= width / 2;
241
+ y -= height / 2;
242
+ this.context.fillStyle = params.color ?? "white";
243
+ this.context.strokeStyle = params.color ?? "white";
244
+ this.context.lineWidth = params.size ?? 1;
245
+ if (params.lineDash) this.context.setLineDash(params.lineDash);
246
+ if (params.filled) this.context.fillRect(x, y, width, height);
247
+ else this.context.strokeRect(x, y, width, height);
248
+ if (params.lineDash) this.context.setLineDash([]);
249
+ }
250
+ /** Draws a filled square of side `params.size` (default {@link DEFAULT_PIXEL_SIZE}) centered on (`x`, `y`). */
251
+ drawPixel(x, y, params = {}) {
252
+ const size = Math.abs(params.size ?? 1);
253
+ this.drawRect(x, y, size, size, {
254
+ ...params,
255
+ filled: true
256
+ });
257
+ }
258
+ /** Draws a line segment from (`x1`, `y1`) to (`x2`, `y2`); `params.size` is the line width. */
259
+ drawLine(x1, y1, x2, y2, params = {}) {
260
+ this.context.strokeStyle = params.color ?? "white";
261
+ this.context.lineWidth = params.size ?? 1;
262
+ if (params.lineDash) this.context.setLineDash(params.lineDash);
263
+ this.context.beginPath();
264
+ this.context.moveTo(x1, y1);
265
+ this.context.lineTo(x2, y2);
266
+ this.context.stroke();
267
+ if (params.lineDash) this.context.setLineDash([]);
268
+ }
269
+ /** Draws a circle centered on (`x`, `y`). */
270
+ drawCircle(x, y, radius, params = {}) {
271
+ this.drawPath(() => {
272
+ this.context.arc(x, y, radius, 0, require_spatial_partition_3d.TAU);
273
+ }, params);
274
+ }
275
+ /**
276
+ * Draws a regular polygon centered on (`x`, `y`) with its first vertex straight up.
277
+ *
278
+ * @param radius distance from the center to each vertex
279
+ * @param sides floored and clamped to 3..36
280
+ */
281
+ drawPolygon(x, y, radius, sides, params = {}) {
282
+ sides = Math.floor(require_spatial_partition_3d.clamp(sides, 3, 36));
283
+ this.drawPath(() => {
284
+ for (let i = 0; i < sides; i++) {
285
+ const angle = i / sides * require_spatial_partition_3d.TAU - require_spatial_partition_3d.PI / 2;
286
+ const px = x + Math.cos(angle) * radius;
287
+ const py = y + Math.sin(angle) * radius;
288
+ if (i === 0) this.context.moveTo(px, py);
289
+ else this.context.lineTo(px, py);
290
+ }
291
+ this.context.closePath();
292
+ }, params);
293
+ }
294
+ /**
295
+ * Fills `text` at (`x`, `y`), aligned by `params.textAlign` / `params.textBaseline` (default
296
+ * left / alphabetic). The font is `params.font`, or `params.size` px `params.fontName`.
297
+ */
298
+ drawText(x, y, text, params = {}) {
299
+ this.context.font = params.font ?? `${params.size ?? 14}px ${params.fontName ?? "monospace"}`;
300
+ this.context.textAlign = params.textAlign ?? "left";
301
+ this.context.textBaseline = params.textBaseline ?? "alphabetic";
302
+ this.context.fillStyle = params.color ?? "white";
303
+ this.context.fillText(text, x, y);
304
+ }
305
+ /**
306
+ * Draws `image` (or the `params` source rectangle of it) scaled to `width` x `height`, centered
307
+ * on (`x`, `y`).
308
+ */
309
+ drawSprite(x, y, image, width, height, params = {}) {
310
+ x -= width / 2;
311
+ y -= height / 2;
312
+ if (params.sourceWidth !== void 0 && params.sourceHeight !== void 0) this.context.drawImage(image, params.sourceX ?? 0, params.sourceY ?? 0, params.sourceWidth, params.sourceHeight, x, y, width, height);
313
+ else this.context.drawImage(image, x, y, width, height);
314
+ }
315
+ };
316
+ //#endregion
317
+ //#region src/clock.ts
318
+ /**
319
+ * Milliseconds in one second.
320
+ *
321
+ * @category Events & Timing
322
+ */
323
+ const ONE_SECOND = 1e3;
324
+ /**
325
+ * Frame timing: delta time, elapsed time and FPS.
326
+ *
327
+ * Either let the clock run the loop:
328
+ *
329
+ * clock.start((dt) => { update(dt); render(); });
330
+ *
331
+ * or advance it from a loop something else drives (three.js, WebXR):
332
+ *
333
+ * renderer.setAnimationLoop((time) => { const dt = clock.tick(time); ... });
334
+ *
335
+ * @category Events & Timing
336
+ */
337
+ var Clock = class {
338
+ /**
339
+ * seconds; caps the delta time after a stall or a hidden tab (browsers pause the frame loop
340
+ * in background tabs, so the first frame back would otherwise cover the whole absence)
341
+ */
342
+ maxDeltaTime = .1;
343
+ _callback;
344
+ _rafId = 0;
345
+ _isRunning = false;
346
+ _lastTime = -1;
347
+ _deltaTime = 0;
348
+ _elapsedTime = 0;
349
+ _fps = 0;
350
+ _fpsFrames = 0;
351
+ _fpsTime = 0;
352
+ /** seconds since the previous tick, capped at `maxDeltaTime`; 0 on the first tick */
353
+ get deltaTime() {
354
+ return this._deltaTime;
355
+ }
356
+ /**
357
+ * seconds since start() (or the first tick), summed from the capped delta times,
358
+ * so it stays in step with the simulation rather than wall-clock time
359
+ */
360
+ get elapsedTime() {
361
+ return this._elapsedTime;
362
+ }
363
+ /** frames per second, rounded; recomputed about once a second, 0 until the first second has passed */
364
+ get fps() {
365
+ return this._fps;
366
+ }
367
+ /** whether {@link Clock.start} is driving the loop (manual {@link Clock.tick} calls don't count) */
368
+ get isRunning() {
369
+ return this._isRunning;
370
+ }
371
+ /**
372
+ * Advances the clock and returns the delta time in seconds. The first tick returns 0.
373
+ *
374
+ * @param time timestamp in milliseconds, e.g. from requestAnimationFrame or setAnimationLoop
375
+ */
376
+ tick(time = performance.now()) {
377
+ if (this._lastTime < 0) {
378
+ this._lastTime = time;
379
+ this._fpsTime = time;
380
+ this._deltaTime = 0;
381
+ return 0;
382
+ }
383
+ this._deltaTime = Math.min(Math.max(0, (time - this._lastTime) / ONE_SECOND), this.maxDeltaTime);
384
+ this._elapsedTime += this._deltaTime;
385
+ this._lastTime = time;
386
+ this._fpsFrames++;
387
+ if (time - this._fpsTime >= 1e3) {
388
+ this._fps = Math.round(this._fpsFrames * ONE_SECOND / (time - this._fpsTime));
389
+ this._fpsFrames = 0;
390
+ this._fpsTime = time;
391
+ }
392
+ return this._deltaTime;
393
+ }
394
+ /**
395
+ * Runs `callback` every animation frame with the delta and elapsed time in seconds.
396
+ * Restarts timing from zero; calling it while running just swaps the callback.
397
+ */
398
+ start(callback) {
399
+ this._callback = callback;
400
+ if (this._isRunning) return;
401
+ this._isRunning = true;
402
+ this._reset();
403
+ const frame = (time) => {
404
+ this.tick(time);
405
+ this._callback?.(this._deltaTime, this._elapsedTime);
406
+ if (this._isRunning) this._rafId = requestAnimationFrame(frame);
407
+ };
408
+ this._rafId = requestAnimationFrame(frame);
409
+ }
410
+ /** Stops the loop started by {@link Clock.start}. Timing state is kept until the next `start()`. */
411
+ stop() {
412
+ this._isRunning = false;
413
+ cancelAnimationFrame(this._rafId);
414
+ }
415
+ _reset() {
416
+ this._lastTime = -1;
417
+ this._deltaTime = 0;
418
+ this._elapsedTime = 0;
419
+ this._fps = 0;
420
+ this._fpsFrames = 0;
421
+ }
422
+ };
423
+ //#endregion
424
+ //#region src/color-palette.ts
425
+ const DEFAULT_COLORS = [
426
+ [
427
+ 237,
428
+ 28,
429
+ 36
430
+ ],
431
+ [
432
+ 255,
433
+ 127,
434
+ 39
435
+ ],
436
+ [
437
+ 255,
438
+ 242,
439
+ 0
440
+ ],
441
+ [
442
+ 34,
443
+ 177,
444
+ 76
445
+ ],
446
+ [
447
+ 0,
448
+ 183,
449
+ 239
450
+ ],
451
+ [
452
+ 63,
453
+ 72,
454
+ 204
455
+ ],
456
+ [
457
+ 163,
458
+ 73,
459
+ 164
460
+ ],
461
+ [
462
+ 236,
463
+ 0,
464
+ 140
465
+ ],
466
+ [
467
+ 255,
468
+ 174,
469
+ 201
470
+ ],
471
+ [
472
+ 139,
473
+ 90,
474
+ 43
475
+ ],
476
+ [
477
+ 214,
478
+ 181,
479
+ 129
480
+ ],
481
+ [
482
+ 128,
483
+ 128,
484
+ 0
485
+ ],
486
+ [
487
+ 0,
488
+ 128,
489
+ 128
490
+ ],
491
+ [
492
+ 128,
493
+ 0,
494
+ 32
495
+ ]
496
+ ];
497
+ function packRGB(r, g, b) {
498
+ r = Math.min(255, Math.max(0, Math.round(r)));
499
+ g = Math.min(255, Math.max(0, Math.round(g)));
500
+ b = Math.min(255, Math.max(0, Math.round(b)));
501
+ return r << 16 | g << 8 | b;
502
+ }
503
+ function colorRamp(rgb, steps) {
504
+ const [r, g, b] = rgb;
505
+ const out = [];
506
+ for (let i = 0; i < steps; i++) {
507
+ const scale = 1 - (steps === 1 ? 0 : i / (steps - 1)) * .72;
508
+ out.push(packRGB(r * scale, g * scale, b * scale));
509
+ }
510
+ return out;
511
+ }
512
+ /**
513
+ * Builds a flat color palette of packed `0xRRGGBB` integers: a grayscale ramp (black -> white)
514
+ * followed by a light -> dark ramp for each supplied color. Length is
515
+ * `grayscaleSteps + colors.length * colorSteps`.
516
+ *
517
+ * @param grayscaleSteps number of grayscale entries, black -> white (a single step is black)
518
+ * @param colorSteps number of steps per color, from the full color down to 28% of it (never black)
519
+ * @param colors base RGB colors to ramp; defaults to 14 common colors (red, orange, yellow,
520
+ * green, cyan, blue, purple, magenta, pink, brown, tan, olive, teal, maroon).
521
+ * White is always included via the grayscale ramp.
522
+ * @category Color
523
+ */
524
+ function buildColorPalette(grayscaleSteps = 8, colorSteps = 4, ...colors) {
525
+ const palette = [];
526
+ for (let i = 0; i < grayscaleSteps; i++) {
527
+ const v = grayscaleSteps === 1 ? 0 : i / (grayscaleSteps - 1) * 255;
528
+ palette.push(packRGB(v, v, v));
529
+ }
530
+ const colorList = colors.length > 0 ? colors : DEFAULT_COLORS;
531
+ for (const rgb of colorList) palette.push(...colorRamp(rgb, colorSteps));
532
+ return palette;
533
+ }
534
+ //#endregion
535
+ //#region src/disposable.ts
536
+ /**
537
+ * Collects cleanup functions (e.g. the unsubscribe functions returned by {@link Observable.subscribe}
538
+ * and {@link Signal.subscribe}) and runs them all at once.
539
+ *
540
+ * ```ts
541
+ * const subscriptions = new Disposable();
542
+ *
543
+ * subscriptions.add(health.subscribe(updateHealthBar));
544
+ * subscriptions.add(onLoaded.subscribe(uploadToGpu));
545
+ *
546
+ * subscriptions.dispose(); // later
547
+ * ```
548
+ *
549
+ * @category Events & Timing
550
+ */
551
+ var Disposable = class {
552
+ disposers = [];
553
+ /** Adds a cleanup function to run on {@link Disposable.dispose}. */
554
+ add(disposer) {
555
+ this.disposers.push(disposer);
556
+ }
557
+ /**
558
+ * Runs and removes every cleanup function, in reverse order of adding. The instance can be
559
+ * reused afterwards.
560
+ */
561
+ dispose() {
562
+ while (this.disposers.length) this.disposers.pop()?.();
563
+ }
564
+ };
565
+ //#endregion
566
+ //#region src/map2d.ts
567
+ /**
568
+ * Default "empty" value of a {@link Map2D}: cells holding it are not stored.
569
+ *
570
+ * @category Maps & Spatial
571
+ */
572
+ const DEFAULT_MAP_2D_VALUE = -1;
573
+ const BASE_2D = 2097152;
574
+ const OFFSET_2D = 1048576;
575
+ /**
576
+ * Lowest supported coordinate on each axis of a {@link Map2D} (inclusive, -1,048,576); anything
577
+ * outside the range wraps around and collides with other coordinates.
578
+ *
579
+ * @category Maps & Spatial
580
+ */
581
+ const MAP_2D_MIN_COORD = -1048576;
582
+ /**
583
+ * Highest supported coordinate on each axis of a {@link Map2D} (inclusive, 1,048,575).
584
+ *
585
+ * @category Maps & Spatial
586
+ */
587
+ const MAP_2D_MAX_COORD = 1048575;
588
+ /**
589
+ * Sparse 2D grid of numbers keyed by integer coordinates. Coordinates are floored, so any point
590
+ * inside a cell addresses that cell. Cells holding `defaultValue` are not stored: setting a cell to
591
+ * it removes the cell, and reading a missing cell returns it.
592
+ *
593
+ * Supports coordinates in [{@link MAP_2D_MIN_COORD}, {@link MAP_2D_MAX_COORD}] per axis; outside
594
+ * that range keys wrap around (a one-time `console.warn` per map reports it).
595
+ *
596
+ * ```ts
597
+ * const map = new Map2D(); // empty = -1
598
+ * map.set(3, -2, 7);
599
+ * map.get(3.9, -1.5); // 7 (floored to 3, -2)
600
+ * map.get(0, 0); // -1
601
+ * map.set(3, -2); // back to empty: removed
602
+ * ```
603
+ *
604
+ * @category Maps & Spatial
605
+ */
606
+ var Map2D = class {
607
+ /** value of every cell that hasn't been set; default {@link DEFAULT_MAP_2D_VALUE} */
608
+ defaultValue;
609
+ _data;
610
+ _warnedOutOfRange = false;
611
+ /** the backing map (packed keys), shared, not a copy */
612
+ get data() {
613
+ return this._data;
614
+ }
615
+ /** number of stored (non-default) cells */
616
+ get size() {
617
+ return this._data.size;
618
+ }
619
+ /**
620
+ * @param mapData existing backing data to use as is (not copied), e.g. another map's `data`
621
+ */
622
+ constructor(defaultValue = -1, mapData) {
623
+ this.defaultValue = defaultValue;
624
+ this._data = mapData ?? /* @__PURE__ */ new Map();
625
+ }
626
+ _floor(x, y) {
627
+ return [Math.floor(x), Math.floor(y)];
628
+ }
629
+ _key(x, y) {
630
+ if (!this._warnedOutOfRange && (x < -1048576 || x > 1048575 || y < -1048576 || y > 1048575)) {
631
+ this._warnedOutOfRange = true;
632
+ console.warn(`Map2D: (${x}, ${y}) is outside the supported range [${MAP_2D_MIN_COORD}, ${MAP_2D_MAX_COORD}] per axis; it wraps around and collides with other coordinates. Further warnings for this map are suppressed.`);
633
+ }
634
+ const X = x + OFFSET_2D & 2097151;
635
+ const Y = y + OFFSET_2D & 2097151;
636
+ return X * BASE_2D + Y;
637
+ }
638
+ _pos(key) {
639
+ const Y = key % BASE_2D;
640
+ return [Math.floor(key / BASE_2D) - OFFSET_2D, Y - OFFSET_2D];
641
+ }
642
+ /** Removes every stored cell. */
643
+ clear() {
644
+ this._data.clear();
645
+ }
646
+ /**
647
+ * Value of the cell containing (x, y) (coordinates are floored).
648
+ *
649
+ * @param defaultValue returned when the cell isn't stored; defaults to the map's `defaultValue`
650
+ */
651
+ get(x, y, defaultValue = this.defaultValue) {
652
+ [x, y] = this._floor(x, y);
653
+ return this._data.get(this._key(x, y)) ?? defaultValue;
654
+ }
655
+ /** Sets the cell containing (x, y); leave out `value` (or pass `defaultValue`) to remove it. */
656
+ set(x, y, value = this.defaultValue) {
657
+ [x, y] = this._floor(x, y);
658
+ const key = this._key(x, y);
659
+ if (value === this.defaultValue) this._data.delete(key);
660
+ else this._data.set(key, value);
661
+ }
662
+ /**
663
+ * Calls `callback` for every stored cell, in insertion order, with its coordinates, value `n`
664
+ * and running index `i`. Cells holding the default value are not visited.
665
+ */
666
+ forEach(callback) {
667
+ let i = 0;
668
+ this._data.forEach((v, key) => {
669
+ const [x, y] = this._pos(key);
670
+ callback(x, y, v, i++);
671
+ });
672
+ }
673
+ /**
674
+ * Like {@link Map2D.forEach}, limited to stored cells with `x1 <= x <= x2` and `y1 <= y <= y2`
675
+ * (both corners inclusive, as in {@link Map3D.setArea}). Scans every stored cell, so it costs
676
+ * O(size), not O(area).
677
+ */
678
+ forEachInArea(x1, y1, x2, y2, callback) {
679
+ this.forEach((x, y, n) => {
680
+ if (x >= x1 && x <= x2 && y >= y1 && y <= y2) callback(x, y, n);
681
+ });
682
+ }
683
+ };
684
+ //#endregion
685
+ //#region src/vector.ts
686
+ /**
687
+ * Mutable 2D vector. Most methods modify the vector in place and return `this` for chaining;
688
+ * {@link Vector.clone} and {@link Vector.floored} return new vectors.
689
+ *
690
+ * ```ts
691
+ * const v = new Vector(3, 4);
692
+ * v.length(); // 5
693
+ * v.clone().normalize().times(10); // (6, 8), v unchanged
694
+ * v.plus(1).minus(new Vector(0, 2)); // v is now (4, 3)
695
+ * ```
696
+ * @category Math & Random
697
+ */
698
+ var Vector = class Vector {
699
+ /** horizontal component */
700
+ x;
701
+ /** vertical component (down in screen coordinates) */
702
+ y;
703
+ constructor(x = 0, y = 0) {
704
+ this.x = x;
705
+ this.y = y;
706
+ }
707
+ /** A new vector with the same components. */
708
+ clone() {
709
+ return new Vector(this.x, this.y);
710
+ }
711
+ /** Copies `that`'s components into this vector. */
712
+ copy(that) {
713
+ this.x = that.x;
714
+ this.y = that.y;
715
+ return this;
716
+ }
717
+ /** Writes this vector's components into `target`; returns this vector, not `target`. */
718
+ copyTo(target) {
719
+ target.x = this.x;
720
+ target.y = this.y;
721
+ return this;
722
+ }
723
+ /** Sets both components. */
724
+ set(x, y) {
725
+ this.x = x;
726
+ this.y = y;
727
+ return this;
728
+ }
729
+ /** Exact (`===`) component-wise equality. */
730
+ equals(that) {
731
+ return this.x === that.x && this.y === that.y;
732
+ }
733
+ /** Euclidean distance to `that`. */
734
+ distanceTo(that) {
735
+ return require_spatial_partition_3d.distance2d(this.x, this.y, that.x, that.y);
736
+ }
737
+ /** Euclidean length (magnitude). */
738
+ length() {
739
+ return Math.hypot(this.x, this.y);
740
+ }
741
+ /** Scales to unit length in place; a zero vector is left unchanged. */
742
+ normalize() {
743
+ const length = this.length();
744
+ if (length > 0) this.dividedBy(length);
745
+ return this;
746
+ }
747
+ /** Scales to the given length in place, keeping the direction; a zero vector stays zero. */
748
+ setLength(length) {
749
+ return this.normalize().times(length);
750
+ }
751
+ /** Dot product with `that`. */
752
+ dot(that) {
753
+ return this.x * that.x + this.y * that.y;
754
+ }
755
+ /** Direction in radians, `Math.atan2(y, x)`, in (-π, π]. */
756
+ angle() {
757
+ return Math.atan2(this.y, this.x);
758
+ }
759
+ /** Unsigned angle between this vector and `that`, in radians in [0, π]; 0 if either is a zero vector. */
760
+ angleTo(that) {
761
+ const denominator = this.length() * that.length();
762
+ if (denominator === 0) return 0;
763
+ const theta = this.dot(that) / denominator;
764
+ return Math.acos(Math.min(1, Math.max(-1, theta)));
765
+ }
766
+ /** Rotates in place about the origin by `radians` (counter-clockwise with y up, clockwise on screen with y down). */
767
+ rotate(radians) {
768
+ const cos = Math.cos(radians);
769
+ const sin = Math.sin(radians);
770
+ const { x, y } = this;
771
+ this.x = x * cos - y * sin;
772
+ this.y = x * sin + y * cos;
773
+ return this;
774
+ }
775
+ /** Rotates in place about `origin` by `radians`. */
776
+ rotateAround(origin, radians) {
777
+ return this.minus(origin).rotate(radians).plus(origin);
778
+ }
779
+ /** A new vector with both components floored; this vector is unchanged. */
780
+ floored() {
781
+ return new Vector(Math.floor(this.x), Math.floor(this.y));
782
+ }
783
+ /** Adds in place: another vector, a scalar to both components (`plus(n)`), or separate `x` and `y` amounts. */
784
+ plus(x, y) {
785
+ if (x instanceof Vector) {
786
+ y = x.y;
787
+ x = x.x;
788
+ } else if (y === void 0) y = x;
789
+ this.x += x;
790
+ this.y += y;
791
+ return this;
792
+ }
793
+ /** Subtracts in place; arguments as for {@link Vector.plus}. */
794
+ minus(x, y) {
795
+ if (x instanceof Vector) {
796
+ y = x.y;
797
+ x = x.x;
798
+ } else if (y === void 0) y = x;
799
+ this.x -= x;
800
+ this.y -= y;
801
+ return this;
802
+ }
803
+ /** Multiplies component-wise in place; arguments as for {@link Vector.plus}. */
804
+ times(x, y) {
805
+ if (x instanceof Vector) {
806
+ y = x.y;
807
+ x = x.x;
808
+ } else if (y === void 0) y = x;
809
+ this.x *= x;
810
+ this.y *= y;
811
+ return this;
812
+ }
813
+ /**
814
+ * Divides component-wise in place; arguments as for {@link Vector.plus}. Plain division: a zero
815
+ * divisor gives `Infinity` (or `NaN` for 0 / 0), as with numbers.
816
+ */
817
+ dividedBy(x, y) {
818
+ if (x instanceof Vector) {
819
+ y = x.y;
820
+ x = x.x;
821
+ } else if (y === void 0) y = x;
822
+ this.x /= x;
823
+ this.y /= y;
824
+ return this;
825
+ }
826
+ /** A new vector from any `{ x, y }` object. */
827
+ static from(value) {
828
+ return new Vector(value.x, value.y);
829
+ }
830
+ /** new (0, 0) */
831
+ static get ZERO() {
832
+ return new Vector(0, 0);
833
+ }
834
+ /** new (0, -1): up in screen coordinates (y down) */
835
+ static get NORTH() {
836
+ return new Vector(0, -1);
837
+ }
838
+ /** new (0, 1): down in screen coordinates */
839
+ static get SOUTH() {
840
+ return new Vector(0, 1);
841
+ }
842
+ /** new (1, 0) */
843
+ static get EAST() {
844
+ return new Vector(1, 0);
845
+ }
846
+ /** new (-1, 0) */
847
+ static get WEST() {
848
+ return new Vector(-1, 0);
849
+ }
850
+ };
851
+ //#endregion
852
+ //#region src/rectangle.ts
853
+ /**
854
+ * Axis-aligned rectangle given by its top-left corner (`x`, `y`) and size. Edges are inclusive
855
+ * in the containment and intersection tests.
856
+ * @category Math & Random
857
+ */
858
+ var Rectangle = class Rectangle {
859
+ /** left edge */
860
+ x;
861
+ /** top edge (minimum y; y points down) */
862
+ y;
863
+ /** extent along x from `x` */
864
+ width;
865
+ /** extent along y from `y` */
866
+ height;
867
+ /** Defaults to a 1 x 1 rectangle at the origin. */
868
+ constructor(x = 0, y = 0, width = 1, height = 1) {
869
+ this.x = x;
870
+ this.y = y;
871
+ this.width = width;
872
+ this.height = height;
873
+ }
874
+ /** `width * height`. */
875
+ area() {
876
+ return this.width * this.height;
877
+ }
878
+ /**
879
+ * True if `target` (a point, or a whole rectangle) is inside or on the edge, with this rectangle
880
+ * grown by `padding` on every side (negative shrinks).
881
+ */
882
+ contains(target, padding = 0) {
883
+ const [width, height] = target instanceof Vector ? [0, 0] : [target.width, target.height];
884
+ return target.x >= this.x - padding && target.y >= this.y - padding && target.x + width <= this.x + this.width + padding && target.y + height <= this.y + this.height + padding;
885
+ }
886
+ /**
887
+ * True if the rectangles overlap or touch, or are at most `padding` apart (negative requires
888
+ * that much overlap).
889
+ */
890
+ intersects(other, padding = 0) {
891
+ return !(other.x > this.x + this.width + padding || other.x + other.width < this.x - padding || other.y > this.y + this.height + padding || other.y + other.height < this.y - padding);
892
+ }
893
+ /** A new vector at the rectangle's centre. */
894
+ center() {
895
+ return new Vector(this.x + this.width / 2, this.y + this.height / 2);
896
+ }
897
+ /** Distance between the two rectangles' centres. */
898
+ distanceTo(other) {
899
+ return this.center().distanceTo(other.center());
900
+ }
901
+ /** A new rectangle with the same position and size. */
902
+ clone() {
903
+ return new Rectangle(this.x, this.y, this.width, this.height);
904
+ }
905
+ /** Exact (`===`) equality of position and size. */
906
+ equals(other) {
907
+ return this.x === other.x && this.y === other.y && this.width === other.width && this.height === other.height;
908
+ }
909
+ /** A new rectangle expanded by `padding` on every side (negative shrinks); this one is unchanged. */
910
+ grow(padding) {
911
+ return new Rectangle(this.x - padding, this.y - padding, this.width + padding * 2, this.height + padding * 2);
912
+ }
913
+ /** Same as {@link Rectangle.contains} with a point. */
914
+ vectorInside(vec, padding = 0) {
915
+ return this.contains(vec, padding);
916
+ }
917
+ };
918
+ //#endregion
919
+ //#region src/dungeon-generator.ts
920
+ /**
921
+ * Tile value for empty (unused) space.
922
+ *
923
+ * @category Pathfinding & Procedural
924
+ */
925
+ const TILE_EMPTY = 0;
926
+ /**
927
+ * Tile value for room floor.
928
+ *
929
+ * @category Pathfinding & Procedural
930
+ */
931
+ const TILE_FLOOR = 1;
932
+ /**
933
+ * Tile value for corridor floor.
934
+ *
935
+ * @category Pathfinding & Procedural
936
+ */
937
+ const TILE_PATH = 2;
938
+ const DEFAULT_LEVEL_SIZE = 64;
939
+ const DEFAULT_ROOM_MIN_SIZE = 3;
940
+ const DEFAULT_ROOM_MAX_SIZE = 9;
941
+ const DEFAULT_ROOM_PADDING = 1;
942
+ const DEFAULT_ROOM_MAX_ITERATIONS = 1e3;
943
+ const DEFAULT_PATH_EXTRA_PATHS = 0;
944
+ const DEFAULT_PATH_EXTRA_PATH_DENSITY = .1;
945
+ const DEFAULT_DOOR_CHANCE_EXISTS = .5;
946
+ const DIRECTIONS_8_WAY = [
947
+ {
948
+ x: -1,
949
+ y: 0
950
+ },
951
+ {
952
+ x: -1,
953
+ y: -1
954
+ },
955
+ {
956
+ x: 0,
957
+ y: -1
958
+ },
959
+ {
960
+ x: 1,
961
+ y: -1
962
+ },
963
+ {
964
+ x: 1,
965
+ y: 0
966
+ },
967
+ {
968
+ x: 1,
969
+ y: 1
970
+ },
971
+ {
972
+ x: 0,
973
+ y: 1
974
+ },
975
+ {
976
+ x: -1,
977
+ y: 1
978
+ }
979
+ ];
980
+ function _plot(map, data, tile) {
981
+ data.forEach((element) => {
982
+ if (element instanceof Rectangle) for (let y = 0; y < element.height; y++) for (let x = 0; x < element.width; x++) map.set(element.x + x, element.y + y, tile);
983
+ else if (Array.isArray(element)) element.forEach((point) => {
984
+ map.set(point.x, point.y, tile);
985
+ });
986
+ else map.set(element.x, element.y, tile);
987
+ });
988
+ }
989
+ function _generateRooms(params = {}) {
990
+ const size = params.size ?? DEFAULT_LEVEL_SIZE;
991
+ const minRoomSize = params.minSize ?? DEFAULT_ROOM_MIN_SIZE;
992
+ const maxRoomSize = params.maxSize ?? DEFAULT_ROOM_MAX_SIZE;
993
+ const padding = params.padding ?? DEFAULT_ROOM_PADDING;
994
+ const maxIterations = params.maxIterations ?? DEFAULT_ROOM_MAX_ITERATIONS;
995
+ const rooms = [];
996
+ let iterations = 0;
997
+ while (iterations < maxIterations) {
998
+ const baseSize = require_spatial_partition_3d.rng.range(minRoomSize, maxRoomSize);
999
+ const aspectRatio = .75 + require_spatial_partition_3d.rng.gaussian() * .5;
1000
+ const width = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize * aspectRatio)));
1001
+ const height = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize / aspectRatio)));
1002
+ 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);
1003
+ if (!rooms.some((existing) => room.intersects(existing, padding * 2))) {
1004
+ rooms.push(room);
1005
+ iterations = 0;
1006
+ } else iterations += 1;
1007
+ }
1008
+ return rooms;
1009
+ }
1010
+ function _generateMST(rooms, params = {}) {
1011
+ const extraPathLevels = params.extraPaths ?? DEFAULT_PATH_EXTRA_PATHS;
1012
+ const extraPathDensity = params.extraPathDensity ?? DEFAULT_PATH_EXTRA_PATH_DENSITY;
1013
+ const mst = [];
1014
+ const extraPaths = [];
1015
+ if (rooms.length < 2) return [];
1016
+ const visited = /* @__PURE__ */ new Set();
1017
+ const heap = new heap_js.Heap((a, b) => a.cost - b.cost);
1018
+ visited.add(0);
1019
+ const zeroCenter = rooms[0].center();
1020
+ for (let i = 1; i < rooms.length; i++) {
1021
+ const iCenter = rooms[i].center();
1022
+ heap.push({
1023
+ from: 0,
1024
+ to: i,
1025
+ cost: require_spatial_partition_3d.squaredDistance(zeroCenter.x, zeroCenter.y, iCenter.x, iCenter.y)
1026
+ });
1027
+ }
1028
+ while (visited.size < rooms.length) {
1029
+ let edge = heap.pop();
1030
+ while (edge && visited.has(edge.to)) edge = heap.pop();
1031
+ if (!edge) break;
1032
+ const { from, to } = edge;
1033
+ visited.add(to);
1034
+ mst.push({
1035
+ a: rooms[from],
1036
+ b: rooms[to]
1037
+ });
1038
+ const toCenter = rooms[to].center();
1039
+ for (let i = 0; i < rooms.length; i++) if (!visited.has(i)) {
1040
+ const iCenter = rooms[i].center();
1041
+ heap.push({
1042
+ from: to,
1043
+ to: i,
1044
+ cost: require_spatial_partition_3d.squaredDistance(toCenter.x, toCenter.y, iCenter.x, iCenter.y)
1045
+ });
1046
+ }
1047
+ }
1048
+ const remainingEdges = heap.toArray().sort((a, b) => a.cost - b.cost);
1049
+ for (let i = 0; i < extraPathLevels && i < remainingEdges.length; i++) {
1050
+ const e = remainingEdges[i];
1051
+ if (require_spatial_partition_3d.rng.nextFloat() < extraPathDensity) extraPaths.push({
1052
+ a: rooms[e.from],
1053
+ b: rooms[e.to]
1054
+ });
1055
+ }
1056
+ return mst.concat(extraPaths);
1057
+ }
1058
+ function _getRectEdgePoints(rect) {
1059
+ const points = [];
1060
+ const x2 = rect.x + rect.width - 1;
1061
+ const y2 = rect.y + rect.height - 1;
1062
+ for (let x1 = rect.x; x1 <= x2; x1++) {
1063
+ points.push({
1064
+ x: x1,
1065
+ y: rect.y
1066
+ });
1067
+ points.push({
1068
+ x: x1,
1069
+ y: y2
1070
+ });
1071
+ }
1072
+ for (let y1 = rect.y; y1 <= y2; y1++) {
1073
+ points.push({
1074
+ x: rect.x,
1075
+ y: y1
1076
+ });
1077
+ points.push({
1078
+ x: x2,
1079
+ y: y1
1080
+ });
1081
+ }
1082
+ return points;
1083
+ }
1084
+ function _getShortestPathBetweenRects(rectA, rectB) {
1085
+ const edgeA = _getRectEdgePoints(rectA);
1086
+ const edgeB = _getRectEdgePoints(rectB);
1087
+ let paths = {
1088
+ a: edgeA[0],
1089
+ b: edgeB[0],
1090
+ distance: Infinity
1091
+ };
1092
+ for (const a of edgeA) for (const b of edgeB) {
1093
+ const d = require_spatial_partition_3d.distance2d(a.x, a.y, b.x, b.y);
1094
+ if (d < paths.distance) paths = {
1095
+ a,
1096
+ b,
1097
+ distance: d
1098
+ };
1099
+ }
1100
+ return {
1101
+ a: paths.a,
1102
+ b: paths.b
1103
+ };
1104
+ }
1105
+ function _generatePaths(map, rooms, params = {}) {
1106
+ const walkable = params.walkableValues ?? [map.defaultValue];
1107
+ const cost = (x, y) => walkable.includes(map.get(x, y)) ? 1 : Infinity;
1108
+ const paths = [];
1109
+ _generateMST(rooms, params).forEach((rects) => {
1110
+ const { a, b } = _getShortestPathBetweenRects(rects.a, rects.b);
1111
+ paths.push(findPath(a, b, cost, {
1112
+ adjacent: true,
1113
+ maxNodes: Infinity
1114
+ }));
1115
+ });
1116
+ return paths;
1117
+ }
1118
+ /**
1119
+ * Generates a dungeon level: scatters non-overlapping rectangular rooms, joins them with a minimum
1120
+ * spanning tree of A* corridors (plus optional extra ones) and plots both into the map as
1121
+ * {@link TILE_FLOOR} and {@link TILE_PATH}.
1122
+ *
1123
+ * Rooms are placed at random until {@link RoomsParams.maxIterations} placements in a row fail.
1124
+ * Corridors are carved only through {@link PathsParams.walkableValues} tiles; each runs from next to
1125
+ * one room's edge to next to the other's, and is empty if no route exists. Randomness comes from the
1126
+ * shared {@link rng}, so set `rng.seed` first for a reproducible level. Logs its duration.
1127
+ *
1128
+ * ```ts
1129
+ * rng.seed = 1234;
1130
+ * const { map, rooms, paths } = GenerateRooms({ rooms: { size: 48 } });
1131
+ * const doors = GenerateDoors(map, paths);
1132
+ * const walls = GenerateWalls(map);
1133
+ * ```
1134
+ *
1135
+ * @category Pathfinding & Procedural
1136
+ */
1137
+ function GenerateRooms(params = {}) {
1138
+ const startTime = Date.now();
1139
+ const map = params.map ?? new Map2D(0);
1140
+ const rooms = _generateRooms(params.rooms);
1141
+ _plot(map, rooms, 1);
1142
+ const paths = _generatePaths(map, rooms, params.paths);
1143
+ _plot(map, paths, 2);
1144
+ require_spatial_partition_3d.log("GenerateRooms: done:", Date.now() - startTime, "ms");
1145
+ return {
1146
+ map,
1147
+ rooms,
1148
+ paths
1149
+ };
1150
+ }
1151
+ /**
1152
+ * Picks door tiles from the two end tiles of each corridor (corridors shorter than 2 tiles are
1153
+ * skipped). An end qualifies when both its up/down or both its left/right neighbours hold the map's
1154
+ * default value, i.e. it sits in a 1-wide gap; each qualifying end becomes a door with probability
1155
+ * {@link DoorsParams.chanceExists}, using the shared {@link rng}. Does not modify the map.
1156
+ *
1157
+ * @param paths corridors as returned by {@link GenerateRooms}
1158
+ * @returns the door tiles
1159
+ * @category Pathfinding & Procedural
1160
+ */
1161
+ function GenerateDoors(map, paths, params = {}) {
1162
+ const chanceExists = params.chanceExists ?? DEFAULT_DOOR_CHANCE_EXISTS;
1163
+ const possibleDoorPoints = [];
1164
+ paths.forEach((points) => {
1165
+ if (points.length > 1) {
1166
+ possibleDoorPoints.push(points[0]);
1167
+ possibleDoorPoints.push(points[points.length - 1]);
1168
+ }
1169
+ });
1170
+ const doors = [];
1171
+ possibleDoorPoints.forEach((doorPoint) => {
1172
+ 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);
1173
+ });
1174
+ return doors;
1175
+ }
1176
+ /**
1177
+ * Returns every tile holding the map's default value that touches (8-way) a non-default tile, each
1178
+ * once: the walls around all rooms and corridors. Does not modify the map.
1179
+ *
1180
+ * @category Pathfinding & Procedural
1181
+ */
1182
+ function GenerateWalls(map) {
1183
+ const walls = /* @__PURE__ */ new Map();
1184
+ map.forEach((x, y, _v) => {
1185
+ DIRECTIONS_8_WAY.forEach((dir) => {
1186
+ const nx = dir.x + x;
1187
+ const ny = dir.y + y;
1188
+ if (map.get(nx, ny) === map.defaultValue) walls.set(`${nx},${ny}`, {
1189
+ x: nx,
1190
+ y: ny
1191
+ });
1192
+ });
1193
+ });
1194
+ return [...walls.values()];
1195
+ }
1196
+ //#endregion
1197
+ //#region src/ecs.ts
1198
+ /**
1199
+ * A minimal entity-component store. Entities are integers; components are class instances stored
1200
+ * per class, and {@link ECS.query} iterates the entities that have every requested component.
1201
+ *
1202
+ * ```ts
1203
+ * class Position { constructor(public x = 0, public y = 0) {} }
1204
+ * class Velocity { constructor(public x = 0, public y = 0) {} }
1205
+ *
1206
+ * const world = new ECS();
1207
+ * const e = world.createEntity();
1208
+ * world.addComponent(e, new Position());
1209
+ * world.addComponent(e, new Velocity(1, 0));
1210
+ *
1211
+ * for (const [entity, pos, vel] of world.query(Position, Velocity)) {
1212
+ * pos.x += vel.x;
1213
+ * }
1214
+ * ```
1215
+ *
1216
+ * @category ECS
1217
+ */
1218
+ var ECS = class {
1219
+ #nextEntity = 0;
1220
+ components = /* @__PURE__ */ new Map();
1221
+ /** Returns a new entity id (0, 1, 2, ...). Ids are never reused until {@link ECS.clear}. */
1222
+ createEntity() {
1223
+ return this.#nextEntity++;
1224
+ }
1225
+ /**
1226
+ * Attaches `component` to `entity`, keyed by `component.constructor`; replaces any existing
1227
+ * component of the same class.
1228
+ */
1229
+ addComponent(entity, component) {
1230
+ const type = component.constructor;
1231
+ let map = this.components.get(type);
1232
+ if (!map) {
1233
+ map = /* @__PURE__ */ new Map();
1234
+ this.components.set(type, map);
1235
+ }
1236
+ map.set(entity, component);
1237
+ }
1238
+ /** The entity's component of class `type`, or `undefined` if it has none. */
1239
+ getComponent(entity, type) {
1240
+ return this.components.get(type)?.get(entity);
1241
+ }
1242
+ /** Whether the entity has a component of class `type`. */
1243
+ hasComponent(entity, type) {
1244
+ return this.components.get(type)?.has(entity) ?? false;
1245
+ }
1246
+ /** Removes the entity's component of class `type`, if any. */
1247
+ removeComponent(entity, type) {
1248
+ this.components.get(type)?.delete(entity);
1249
+ }
1250
+ /**
1251
+ * Iterates `[entity, ...components]` for every entity that has all of `types`, with the
1252
+ * components in the same order as `types`. Yields nothing when `types` is empty or any type has
1253
+ * never been added. Order follows insertion into the least-populated component type.
1254
+ */
1255
+ *query(...types) {
1256
+ if (types.length === 0) return;
1257
+ let smallest;
1258
+ const maps = [];
1259
+ for (const type of types) {
1260
+ const map = this.components.get(type);
1261
+ if (!map) return;
1262
+ maps.push(map);
1263
+ if (!smallest || map.size < smallest.size) smallest = map;
1264
+ }
1265
+ if (!smallest) return;
1266
+ for (const entity of smallest.keys()) {
1267
+ const components = [];
1268
+ let matches = true;
1269
+ for (const map of maps) {
1270
+ const component = map.get(entity);
1271
+ if (!component) {
1272
+ matches = false;
1273
+ break;
1274
+ }
1275
+ components.push(component);
1276
+ }
1277
+ if (matches) yield [entity, ...components];
1278
+ }
1279
+ }
1280
+ /** Removes all of the entity's components. The id is not recycled. */
1281
+ destroyEntity(entity) {
1282
+ for (const map of this.components.values()) map.delete(entity);
1283
+ }
1284
+ /** Removes every component and resets entity ids to start from 0 again. */
1285
+ clear() {
1286
+ this.components.clear();
1287
+ this.#nextEntity = 0;
1288
+ }
1289
+ };
1290
+ /**
1291
+ * A shared {@link ECS} instance.
1292
+ *
1293
+ * @category ECS
1294
+ */
1295
+ const ecs = new ECS();
1296
+ //#endregion
1297
+ //#region src/emitter.ts
1298
+ /**
1299
+ * A string-keyed event emitter. Listeners get the emitted arguments followed by the event name,
1300
+ * so one listener can tell apart the events it was added to.
1301
+ *
1302
+ * ```ts
1303
+ * const events = new Emitter();
1304
+ *
1305
+ * events.on('hit', 'miss', (target, eventName) => console.log(eventName, target));
1306
+ * events.emit('hit', enemy); // logs 'hit', enemy
1307
+ * ```
1308
+ *
1309
+ * @category Events & Timing
1310
+ */
1311
+ var Emitter = class {
1312
+ listeners = /* @__PURE__ */ new Map();
1313
+ constructor() {}
1314
+ /**
1315
+ * Adds a listener (the last argument) to one or more event names (the arguments before it).
1316
+ * Adding the same listener twice makes it fire twice. Returns `this` for chaining.
1317
+ */
1318
+ on(...eventName) {
1319
+ const listener = eventName.pop();
1320
+ eventName.filter((ev) => typeof ev === "string").forEach((event) => {
1321
+ if (!this.listeners.has(event)) this.listeners.set(event, new Array());
1322
+ this.listeners.get(event)?.push(listener);
1323
+ });
1324
+ return this;
1325
+ }
1326
+ /**
1327
+ * Calls the listeners of `eventName` in the order they were added, with `args` followed by
1328
+ * `eventName`. Returns `this` for chaining.
1329
+ */
1330
+ emit(eventName, ...args) {
1331
+ [...this.listeners.get(eventName) ?? []].forEach((listener) => listener(...args, eventName));
1332
+ return this;
1333
+ }
1334
+ /**
1335
+ * Removes `listener` from `eventName` (one registration of it, if it was added more than
1336
+ * once), or every listener of `eventName` when `listener` is left out. Returns `this`.
1337
+ */
1338
+ off(eventName, listener) {
1339
+ const listeners = this.listeners.get(eventName);
1340
+ if (!listeners) return this;
1341
+ if (listener) {
1342
+ const index = listeners.indexOf(listener);
1343
+ if (index >= 0) listeners.splice(index, 1);
1344
+ }
1345
+ if (!listener || listeners.length === 0) this.listeners.delete(eventName);
1346
+ return this;
1347
+ }
1348
+ };
1349
+ //#endregion
1350
+ //#region src/event-queue.ts
1351
+ /**
1352
+ * A buffered queue of events: producers `emit()` events, and a consumer reads them later (e.g.
1353
+ * once per frame) with `drain()`, or with `consume()` followed by `clear()`.
1354
+ *
1355
+ * ```ts
1356
+ * const collisions = new EventQueue<{ a: number, b: number }>();
1357
+ *
1358
+ * collisions.emit({ a: 1, b: 2 }); // physics system
1359
+ *
1360
+ * for (const { a, b } of collisions.drain()) { } // gameplay system; the queue is now empty
1361
+ * ```
1362
+ *
1363
+ * @category Events & Timing
1364
+ */
1365
+ var EventQueue = class {
1366
+ events = [];
1367
+ /** Appends an event to the queue. */
1368
+ emit(event) {
1369
+ this.events.push(event);
1370
+ }
1371
+ /** Returns a copy of the queued events, oldest first, without removing them. */
1372
+ consume() {
1373
+ return this.events.slice();
1374
+ }
1375
+ /** Removes all queued events. */
1376
+ clear() {
1377
+ this.events.length = 0;
1378
+ }
1379
+ /** Removes and returns all queued events, oldest first. */
1380
+ drain() {
1381
+ return this.events.splice(0);
1382
+ }
1383
+ /** number of queued events */
1384
+ get size() {
1385
+ return this.events.length;
1386
+ }
1387
+ };
1388
+ //#endregion
1389
+ //#region src/input/bindings.ts
1390
+ /**
1391
+ * W3C "standard" gamepad mapping, in button-index order (Xbox names; on PlayStation A = Cross,
1392
+ * B = Circle, X = Square, Y = Triangle).
1393
+ *
1394
+ * @category Input
1395
+ */
1396
+ const GAMEPAD_BUTTONS = [
1397
+ "A",
1398
+ "B",
1399
+ "X",
1400
+ "Y",
1401
+ "LB",
1402
+ "RB",
1403
+ "LT",
1404
+ "RT",
1405
+ "Select",
1406
+ "Start",
1407
+ "LS",
1408
+ "RS",
1409
+ "DpadUp",
1410
+ "DpadDown",
1411
+ "DpadLeft",
1412
+ "DpadRight",
1413
+ "Home"
1414
+ ];
1415
+ /**
1416
+ * Standard-mapping gamepad stick axes, in axis-index order; Y is positive downwards.
1417
+ *
1418
+ * @category Input
1419
+ */
1420
+ const GAMEPAD_AXES = [
1421
+ "leftX",
1422
+ "leftY",
1423
+ "rightX",
1424
+ "rightY"
1425
+ ];
1426
+ /**
1427
+ * The touch gestures recognized by {@link GestureRecognizer}.
1428
+ *
1429
+ * @category Input
1430
+ */
1431
+ const GESTURES = [
1432
+ "tap",
1433
+ "doubleTap",
1434
+ "longPress",
1435
+ "swipeLeft",
1436
+ "swipeRight",
1437
+ "swipeUp",
1438
+ "swipeDown",
1439
+ "pinchIn",
1440
+ "pinchOut"
1441
+ ];
1442
+ /**
1443
+ * WebXR "xr-standard" controller buttons, in button-index order; A/X and B/Y are the
1444
+ * primary/secondary face buttons of each hand.
1445
+ *
1446
+ * @category Input
1447
+ */
1448
+ const XR_BUTTONS = [
1449
+ "trigger",
1450
+ "squeeze",
1451
+ "touchpad",
1452
+ "thumbstick",
1453
+ "primary",
1454
+ "secondary"
1455
+ ];
1456
+ /**
1457
+ * WebXR "xr-standard" controller axes (touchpad, thumbstick), in axis-index order; Y is positive downwards.
1458
+ *
1459
+ * @category Input
1460
+ */
1461
+ const XR_AXES = [
1462
+ "padX",
1463
+ "padY",
1464
+ "thumbX",
1465
+ "thumbY"
1466
+ ];
1467
+ /**
1468
+ * A physical key, by `KeyboardEvent.code` (layout independent: 'KeyW' is W on QWERTY, Z on AZERTY).
1469
+ *
1470
+ * @category Input
1471
+ */
1472
+ const key = (code, modifiers) => modifiers ? {
1473
+ type: "key",
1474
+ code,
1475
+ modifiers
1476
+ } : {
1477
+ type: "key",
1478
+ code
1479
+ };
1480
+ /**
1481
+ * A mouse (or pen) button.
1482
+ *
1483
+ * @category Input
1484
+ */
1485
+ const mouse = (button) => ({
1486
+ type: "mouse",
1487
+ button
1488
+ });
1489
+ /**
1490
+ * A wheel direction: pressed for one frame whenever the wheel moves that way.
1491
+ *
1492
+ * @category Input
1493
+ */
1494
+ const wheel = (direction) => ({
1495
+ type: "wheel",
1496
+ direction
1497
+ });
1498
+ /**
1499
+ * A gamepad button (standard mapping).
1500
+ *
1501
+ * @category Input
1502
+ */
1503
+ const pad = (button) => ({
1504
+ type: "pad",
1505
+ button
1506
+ });
1507
+ /**
1508
+ * One direction of a gamepad stick axis, e.g. padAxis('leftX', -1) for "left stick left".
1509
+ *
1510
+ * @category Input
1511
+ */
1512
+ const padAxis = (axis, direction) => ({
1513
+ type: "padAxis",
1514
+ axis,
1515
+ direction
1516
+ });
1517
+ /**
1518
+ * A touch gesture.
1519
+ *
1520
+ * @category Input
1521
+ */
1522
+ const gesture = (name) => ({
1523
+ type: "gesture",
1524
+ gesture: name
1525
+ });
1526
+ /**
1527
+ * A VR controller button.
1528
+ *
1529
+ * @category Input
1530
+ */
1531
+ const xr = (hand, button) => ({
1532
+ type: "xr",
1533
+ hand,
1534
+ button
1535
+ });
1536
+ /**
1537
+ * One direction of a VR controller axis.
1538
+ *
1539
+ * @category Input
1540
+ */
1541
+ const xrAxis = (hand, axis, direction) => ({
1542
+ type: "xrAxis",
1543
+ hand,
1544
+ axis,
1545
+ direction
1546
+ });
1547
+ /**
1548
+ * Identifies the physical control behind a binding (modifiers aside), e.g. `'key:KeyW'` or
1549
+ * `'padAxis:leftX:-1'`.
1550
+ *
1551
+ * @category Input
1552
+ */
1553
+ function controlId(binding) {
1554
+ switch (binding.type) {
1555
+ case "key": return `key:${binding.code}`;
1556
+ case "mouse": return `mouse:${binding.button}`;
1557
+ case "wheel": return `wheel:${binding.direction}`;
1558
+ case "pad": return `pad:${binding.button}`;
1559
+ case "padAxis": return `padAxis:${binding.axis}:${binding.direction}`;
1560
+ case "gesture": return `gesture:${binding.gesture}`;
1561
+ case "xr": return `xr:${binding.hand}:${binding.button}`;
1562
+ case "xrAxis": return `xrAxis:${binding.hand}:${binding.axis}:${binding.direction}`;
1563
+ }
1564
+ }
1565
+ /**
1566
+ * Whether two bindings refer to the same control; key bindings must also require the same modifiers
1567
+ * (a missing modifier counts as `false`).
1568
+ *
1569
+ * @category Input
1570
+ */
1571
+ function bindingsEqual(a, b) {
1572
+ if (controlId(a) !== controlId(b)) return false;
1573
+ if (a.type !== "key" || b.type !== "key") return true;
1574
+ const ma = a.modifiers ?? {};
1575
+ const mb = b.modifiers ?? {};
1576
+ return !!ma.shift === !!mb.shift && !!ma.ctrl === !!mb.ctrl && !!ma.alt === !!mb.alt && !!ma.meta === !!mb.meta;
1577
+ }
1578
+ const KEY_NAMES = {
1579
+ Space: "Space",
1580
+ Enter: "Enter",
1581
+ NumpadEnter: "Numpad Enter",
1582
+ Escape: "Esc",
1583
+ Tab: "Tab",
1584
+ Backspace: "Backspace",
1585
+ ArrowUp: "↑",
1586
+ ArrowDown: "↓",
1587
+ ArrowLeft: "←",
1588
+ ArrowRight: "→",
1589
+ ShiftLeft: "Left Shift",
1590
+ ShiftRight: "Right Shift",
1591
+ ControlLeft: "Left Ctrl",
1592
+ ControlRight: "Right Ctrl",
1593
+ AltLeft: "Left Alt",
1594
+ AltRight: "Right Alt",
1595
+ MetaLeft: "Left Meta",
1596
+ MetaRight: "Right Meta"
1597
+ };
1598
+ const AXIS_NAMES = {
1599
+ leftX: ["Left Stick Left", "Left Stick Right"],
1600
+ leftY: ["Left Stick Up", "Left Stick Down"],
1601
+ rightX: ["Right Stick Left", "Right Stick Right"],
1602
+ rightY: ["Right Stick Up", "Right Stick Down"],
1603
+ padX: ["Touchpad Left", "Touchpad Right"],
1604
+ padY: ["Touchpad Up", "Touchpad Down"],
1605
+ thumbX: ["Thumbstick Left", "Thumbstick Right"],
1606
+ thumbY: ["Thumbstick Up", "Thumbstick Down"]
1607
+ };
1608
+ const capitalize = (s) => s.charAt(0).toUpperCase() + s.slice(1);
1609
+ /**
1610
+ * A readable name for a binding, e.g. for "Press Space to jump" prompts. Pass `keyLabels` (from
1611
+ * {@link Input.loadKeyboardLayout}) to name keys as printed on the player's keyboard.
1612
+ *
1613
+ * @category Input
1614
+ */
1615
+ function bindingLabel(binding, keyLabels) {
1616
+ switch (binding.type) {
1617
+ case "key": {
1618
+ const m = binding.modifiers ?? {};
1619
+ const name = keyLabels?.get(binding.code)?.toUpperCase() ?? KEY_NAMES[binding.code] ?? binding.code.replace(/^Key|^Digit/, "").replace(/^Numpad(.+)/, "Numpad $1");
1620
+ return [
1621
+ m.ctrl && "Ctrl",
1622
+ m.alt && "Alt",
1623
+ m.shift && "Shift",
1624
+ m.meta && "Meta",
1625
+ name
1626
+ ].filter(Boolean).join("+");
1627
+ }
1628
+ case "mouse": return `Mouse ${capitalize(binding.button)}`;
1629
+ case "wheel": return `Wheel ${capitalize(binding.direction)}`;
1630
+ case "pad": return `Gamepad ${binding.button}`;
1631
+ case "padAxis": return AXIS_NAMES[binding.axis][binding.direction > 0 ? 1 : 0];
1632
+ case "gesture": return capitalize(binding.gesture.replace(/([A-Z])/g, " $1").toLowerCase());
1633
+ case "xr": return `${capitalize(binding.hand)} ${capitalize(binding.button)}`;
1634
+ case "xrAxis": return `${capitalize(binding.hand)} ${AXIS_NAMES[binding.axis][binding.direction > 0 ? 1 : 0]}`;
1635
+ }
1636
+ }
1637
+ //#endregion
1638
+ //#region src/input/action-map.ts
1639
+ /**
1640
+ * Deadzone given to new actions when none is specified.
1641
+ *
1642
+ * @category Input
1643
+ */
1644
+ const DEFAULT_DEADZONE = .2;
1645
+ /**
1646
+ * Named actions and the inputs bound to them, like Godot's InputMap. Every {@link Input} has one as
1647
+ * {@link Input.actions}; the methods that change it return `this` for chaining.
1648
+ *
1649
+ * ```ts
1650
+ * input.actions
1651
+ * .add('jump', [key('Space'), pad('A')])
1652
+ * .bind('jump', gesture('tap'));
1653
+ *
1654
+ * localStorage.setItem('bindings', JSON.stringify(input.actions));
1655
+ * ```
1656
+ *
1657
+ * @category Input
1658
+ */
1659
+ var ActionMap = class {
1660
+ _actions = /* @__PURE__ */ new Map();
1661
+ /** action names, in the order they were added */
1662
+ get names() {
1663
+ return [...this._actions.keys()];
1664
+ }
1665
+ /** Whether an action with this name exists. */
1666
+ has(name) {
1667
+ return this._actions.has(name);
1668
+ }
1669
+ /** The action with this name, or `undefined`. */
1670
+ get(name) {
1671
+ return this._actions.get(name);
1672
+ }
1673
+ /** Adds an action, or replaces its bindings (and deadzone, if given) if it exists. */
1674
+ add(name, bindings = [], options = {}) {
1675
+ const existing = this._actions.get(name);
1676
+ this._actions.set(name, {
1677
+ name,
1678
+ deadzone: options.deadzone ?? existing?.deadzone ?? .2,
1679
+ bindings: [...bindings]
1680
+ });
1681
+ return this;
1682
+ }
1683
+ /** Removes an action, if it exists. */
1684
+ remove(name) {
1685
+ this._actions.delete(name);
1686
+ return this;
1687
+ }
1688
+ /** Adds a binding to an action (creating the action if needed); duplicates are ignored. */
1689
+ bind(name, binding) {
1690
+ if (!this._actions.has(name)) this.add(name);
1691
+ const action = this._actions.get(name);
1692
+ if (!action.bindings.some((b) => bindingsEqual(b, binding))) action.bindings.push(binding);
1693
+ return this;
1694
+ }
1695
+ /** Removes a binding (compared with {@link bindingsEqual}) from an action, if present. */
1696
+ unbind(name, binding) {
1697
+ const action = this._actions.get(name);
1698
+ if (action) {
1699
+ const i = action.bindings.findIndex((b) => bindingsEqual(b, binding));
1700
+ if (i >= 0) action.bindings.splice(i, 1);
1701
+ }
1702
+ return this;
1703
+ }
1704
+ /** Actions that already use this binding, e.g. to warn about conflicts when rebinding. */
1705
+ findBinding(binding) {
1706
+ return this.names.filter((name) => this._actions.get(name).bindings.some((b) => bindingsEqual(b, binding)));
1707
+ }
1708
+ /** Removes all actions. */
1709
+ clear() {
1710
+ this._actions.clear();
1711
+ return this;
1712
+ }
1713
+ /** A JSON-serializable copy of all actions, for saving rebinds; see {@link ActionMap.load}. */
1714
+ toJSON() {
1715
+ const json = {};
1716
+ for (const action of this._actions.values()) json[action.name] = {
1717
+ deadzone: action.deadzone,
1718
+ bindings: action.bindings.map((b) => ({ ...b }))
1719
+ };
1720
+ return json;
1721
+ }
1722
+ /** Replaces all actions with the saved ones (e.g. a player's rebinds). */
1723
+ load(json) {
1724
+ this.clear();
1725
+ for (const [name, action] of Object.entries(json)) this.add(name, action.bindings, { deadzone: action.deadzone });
1726
+ return this;
1727
+ }
1728
+ /**
1729
+ * Godot-style `ui_*` actions for menus and dialogs (`ui_accept`, `ui_cancel`, `ui_left`, `ui_right`,
1730
+ * `ui_up`, `ui_down`, `ui_page_up`, `ui_page_down`), with a 0.5 deadzone; replaces existing ones.
1731
+ */
1732
+ addDefaults() {
1733
+ const ui = { deadzone: .5 };
1734
+ this.add("ui_accept", [
1735
+ key("Enter"),
1736
+ key("NumpadEnter"),
1737
+ key("Space"),
1738
+ pad("A")
1739
+ ], ui);
1740
+ this.add("ui_cancel", [key("Escape"), pad("B")], ui);
1741
+ this.add("ui_left", [
1742
+ key("ArrowLeft"),
1743
+ pad("DpadLeft"),
1744
+ padAxis("leftX", -1)
1745
+ ], ui);
1746
+ this.add("ui_right", [
1747
+ key("ArrowRight"),
1748
+ pad("DpadRight"),
1749
+ padAxis("leftX", 1)
1750
+ ], ui);
1751
+ this.add("ui_up", [
1752
+ key("ArrowUp"),
1753
+ pad("DpadUp"),
1754
+ padAxis("leftY", -1)
1755
+ ], ui);
1756
+ this.add("ui_down", [
1757
+ key("ArrowDown"),
1758
+ pad("DpadDown"),
1759
+ padAxis("leftY", 1)
1760
+ ], ui);
1761
+ this.add("ui_page_up", [key("PageUp"), pad("LB")], ui);
1762
+ this.add("ui_page_down", [key("PageDown"), pad("RB")], ui);
1763
+ return this;
1764
+ }
1765
+ };
1766
+ //#endregion
1767
+ //#region src/input/gestures.ts
1768
+ const DEFAULT_THRESHOLDS = {
1769
+ tapMaxDuration: 250,
1770
+ tapMaxMovement: 10,
1771
+ doubleTapMaxDelay: 300,
1772
+ doubleTapMaxDistance: 30,
1773
+ longPressDuration: 500,
1774
+ swipeMinDistance: 50,
1775
+ swipeMaxDuration: 500,
1776
+ pinchMinChange: .005
1777
+ };
1778
+ /**
1779
+ * Turns touch points into gestures: tap, double tap, long press, swipes (one finger) and
1780
+ * pinch / pan / rotate (two fingers). Feed it with down / move / up, call update() once per frame.
1781
+ * Times are in ms and positions in pixels, from any consistent clock and origin. {@link Input} drives
1782
+ * one for you; use this class directly only for custom touch handling.
1783
+ *
1784
+ * Tap, double tap and swipe are reported when the finger lifts, long press while it is still held;
1785
+ * a finger that was ever down together with another one never produces one-finger gestures.
1786
+ *
1787
+ * ```ts
1788
+ * const recognizer = new GestureRecognizer({ longPressDuration: 400 });
1789
+ * el.addEventListener('pointerdown', e => recognizer.down(e.pointerId, e.offsetX, e.offsetY, performance.now()));
1790
+ * // ... move / up / cancel likewise
1791
+ *
1792
+ * const { gestures, pinch } = recognizer.update(performance.now());
1793
+ * ```
1794
+ *
1795
+ * @category Input
1796
+ */
1797
+ var GestureRecognizer = class {
1798
+ /** current thresholds; may be changed at any time */
1799
+ thresholds = { ...DEFAULT_THRESHOLDS };
1800
+ _touches = /* @__PURE__ */ new Map();
1801
+ _pending = [];
1802
+ _lastTap;
1803
+ _pair;
1804
+ /** Copies of the fingers currently down. */
1805
+ get touches() {
1806
+ return [...this._touches.values()].map(({ id, x, y, startX, startY, startTime }) => ({
1807
+ id,
1808
+ x,
1809
+ y,
1810
+ startX,
1811
+ startY,
1812
+ startTime
1813
+ }));
1814
+ }
1815
+ /** @param thresholds overrides for the default thresholds */
1816
+ constructor(thresholds = {}) {
1817
+ Object.assign(this.thresholds, thresholds);
1818
+ }
1819
+ /** A finger touched down. */
1820
+ down(id, x, y, time) {
1821
+ const multi = this._touches.size > 0;
1822
+ for (const touch of this._touches.values()) touch.multi = true;
1823
+ this._touches.set(id, {
1824
+ id,
1825
+ x,
1826
+ y,
1827
+ startX: x,
1828
+ startY: y,
1829
+ startTime: time,
1830
+ maxMovement: 0,
1831
+ multi,
1832
+ longPressed: false
1833
+ });
1834
+ }
1835
+ /** A finger moved; unknown ids are ignored. */
1836
+ move(id, x, y) {
1837
+ const touch = this._touches.get(id);
1838
+ if (!touch) return;
1839
+ touch.x = x;
1840
+ touch.y = y;
1841
+ touch.maxMovement = Math.max(touch.maxMovement, Math.hypot(x - touch.startX, y - touch.startY));
1842
+ }
1843
+ /** A finger lifted; may queue a tap, double tap or swipe for the next update. */
1844
+ up(id, x, y, time) {
1845
+ const touch = this._touches.get(id);
1846
+ if (!touch) return;
1847
+ this.move(id, x, y);
1848
+ this._touches.delete(id);
1849
+ if (touch.multi || touch.longPressed) return;
1850
+ const t = this.thresholds;
1851
+ const duration = time - touch.startTime;
1852
+ const dx = x - touch.startX;
1853
+ const dy = y - touch.startY;
1854
+ const distance = Math.hypot(dx, dy);
1855
+ if (duration <= t.tapMaxDuration && touch.maxMovement <= t.tapMaxMovement) {
1856
+ this._pending.push("tap");
1857
+ const last = this._lastTap;
1858
+ if (last && time - last.time <= t.doubleTapMaxDelay && Math.hypot(x - last.x, y - last.y) <= t.doubleTapMaxDistance) {
1859
+ this._pending.push("doubleTap");
1860
+ this._lastTap = void 0;
1861
+ } else this._lastTap = {
1862
+ x,
1863
+ y,
1864
+ time
1865
+ };
1866
+ } 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");
1867
+ }
1868
+ /** Forgets a finger without recognizing anything (e.g. on `pointercancel`). */
1869
+ cancel(id) {
1870
+ this._touches.delete(id);
1871
+ }
1872
+ /** Forgets all fingers, gestures not yet reported, and the first tap of a pending double tap (e.g. on blur). */
1873
+ clear() {
1874
+ this._touches.clear();
1875
+ this._pair = void 0;
1876
+ this._pending = [];
1877
+ this._lastTap = void 0;
1878
+ }
1879
+ /** Returns what happened since the last update. `time` is the current time in ms. */
1880
+ update(time) {
1881
+ const frame = {
1882
+ gestures: [],
1883
+ pinch: 1,
1884
+ pan: {
1885
+ x: 0,
1886
+ y: 0
1887
+ },
1888
+ rotate: 0
1889
+ };
1890
+ for (const touch of this._touches.values()) if (!touch.multi && !touch.longPressed && touch.maxMovement <= this.thresholds.tapMaxMovement && time - touch.startTime >= this.thresholds.longPressDuration) {
1891
+ touch.longPressed = true;
1892
+ this._pending.push("longPress");
1893
+ }
1894
+ const [a, b] = [...this._touches.values()];
1895
+ if (a && b) {
1896
+ const distance = Math.hypot(b.x - a.x, b.y - a.y);
1897
+ const angle = Math.atan2(b.y - a.y, b.x - a.x);
1898
+ const cx = (a.x + b.x) / 2;
1899
+ const cy = (a.y + b.y) / 2;
1900
+ const pair = this._pair;
1901
+ if (pair && pair.a === a.id && pair.b === b.id) {
1902
+ frame.pinch = pair.distance > 0 ? distance / pair.distance : 1;
1903
+ frame.pan = {
1904
+ x: cx - pair.cx,
1905
+ y: cy - pair.cy
1906
+ };
1907
+ frame.rotate = Math.atan2(Math.sin(angle - pair.angle), Math.cos(angle - pair.angle));
1908
+ if (Math.abs(frame.pinch - 1) >= this.thresholds.pinchMinChange) this._pending.push(frame.pinch > 1 ? "pinchOut" : "pinchIn");
1909
+ }
1910
+ this._pair = {
1911
+ a: a.id,
1912
+ b: b.id,
1913
+ distance,
1914
+ angle,
1915
+ cx,
1916
+ cy
1917
+ };
1918
+ } else this._pair = void 0;
1919
+ frame.gestures = this._pending;
1920
+ this._pending = [];
1921
+ return frame;
1922
+ }
1923
+ };
1924
+ //#endregion
1925
+ //#region src/observable.ts
1926
+ /**
1927
+ * A set of observers notified with a value (plus optional extra arguments). Observers are
1928
+ * called in subscription order; subscribing the same function twice has no effect.
1929
+ *
1930
+ * ```ts
1931
+ * const onLoaded = new Observable<string>();
1932
+ * const unsubscribe = onLoaded.subscribe(url => console.log('loaded', url));
1933
+ *
1934
+ * onLoaded.notify('a.png');
1935
+ * unsubscribe();
1936
+ * ```
1937
+ *
1938
+ * @category Events & Timing
1939
+ */
1940
+ var Observable = class {
1941
+ observers = /* @__PURE__ */ new Set();
1942
+ /** Adds an observer; returns a function that removes it. */
1943
+ subscribe(observer) {
1944
+ this.observers.add(observer);
1945
+ return () => this.observers.delete(observer);
1946
+ }
1947
+ /**
1948
+ * Subscribes for the next notification only; the observer gets the same arguments as with
1949
+ * {@link Observable.subscribe}.
1950
+ *
1951
+ * @returns a function that removes the observer before it fires
1952
+ */
1953
+ once(observer) {
1954
+ const unsubscribe = this.subscribe((value, ...args) => {
1955
+ unsubscribe();
1956
+ observer(value, ...args);
1957
+ });
1958
+ return unsubscribe;
1959
+ }
1960
+ /**
1961
+ * Calls every observer with `value` and `args`. Iterates over a snapshot, so observers may
1962
+ * subscribe or unsubscribe during the call.
1963
+ */
1964
+ notify(value, ...args) {
1965
+ for (const observer of [...this.observers]) observer(value, ...args);
1966
+ }
1967
+ /** Removes all observers. */
1968
+ clear() {
1969
+ this.observers.clear();
1970
+ }
1971
+ /** number of observers */
1972
+ get size() {
1973
+ return this.observers.size;
1974
+ }
1975
+ };
1976
+ //#endregion
1977
+ //#region src/input/input.ts
1978
+ const ANY = -1;
1979
+ const now = () => performance.now();
1980
+ const MOUSE_BUTTONS = [
1981
+ "left",
1982
+ "middle",
1983
+ "right",
1984
+ "back",
1985
+ "forward"
1986
+ ];
1987
+ const BUTTON_BITS = [
1988
+ 1,
1989
+ 4,
1990
+ 2,
1991
+ 8,
1992
+ 16
1993
+ ];
1994
+ const isEditable = (target) => {
1995
+ const element = target;
1996
+ const tag = element?.tagName;
1997
+ return !!element && (tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || element.isContentEditable === true);
1998
+ };
1999
+ /**
2000
+ * Game input with a Godot-style action map: bind keys, buttons, sticks, gestures and VR controls
2001
+ * to named actions, then query actions instead of devices.
2002
+ *
2003
+ * const input = new Input(canvas);
2004
+ * input.actions.add('jump', [key('Space'), pad('A')]);
2005
+ *
2006
+ * // every frame, before game logic:
2007
+ * input.update();
2008
+ * if (input.isActionJustPressed('jump')) player.jump();
2009
+ *
2010
+ * Call `dispose()` to remove all listeners.
2011
+ *
2012
+ * @category Input
2013
+ */
2014
+ var Input = class {
2015
+ /** the actions to query; holds the `ui_*` defaults unless {@link InputOptions.defaults} is false */
2016
+ actions = new ActionMap();
2017
+ /** Thresholds for taps, swipes etc. can be tuned via `gestureRecognizer.thresholds`. */
2018
+ gestureRecognizer = new GestureRecognizer();
2019
+ /** Two-finger gesture values for the last frame (pinch 1 / pan 0 / rotate 0 when not gesturing). */
2020
+ gestures = {
2021
+ pinch: 1,
2022
+ pan: {
2023
+ x: 0,
2024
+ y: 0
2025
+ },
2026
+ rotate: 0
2027
+ };
2028
+ /** Fingers currently on the target. */
2029
+ get touches() {
2030
+ return this.gestureRecognizer.touches;
2031
+ }
2032
+ /** the mouse or pen; not updated by touch */
2033
+ pointer = {
2034
+ type: "mouse",
2035
+ x: 0,
2036
+ y: 0,
2037
+ ndcX: 0,
2038
+ ndcY: 0,
2039
+ deltaX: 0,
2040
+ deltaY: 0,
2041
+ wheelX: 0,
2042
+ wheelY: 0,
2043
+ pressure: 0,
2044
+ tiltX: 0,
2045
+ tiltY: 0
2046
+ };
2047
+ /** notified when {@link Input.lastDevice} changes, e.g. to switch on-screen button prompts */
2048
+ onDeviceChange = new Observable();
2049
+ /** notified from update() when a gamepad is first seen */
2050
+ onGamepadConnected = new Observable();
2051
+ /** notified from update() when a gamepad goes away; its held controls are released */
2052
+ onGamepadDisconnected = new Observable();
2053
+ _gamepads = /* @__PURE__ */ new Map();
2054
+ /** Connected gamepads, as found by the last update(). */
2055
+ get gamepads() {
2056
+ return [...this._gamepads].map(([device, gamepad]) => ({
2057
+ device,
2058
+ id: gamepad.id,
2059
+ standard: gamepad.mapping === "standard"
2060
+ }));
2061
+ }
2062
+ _lastDevice = "keyboard";
2063
+ _keyLabels;
2064
+ _target;
2065
+ _options;
2066
+ _listeners = [];
2067
+ _controls = /* @__PURE__ */ new Map([[0, /* @__PURE__ */ new Map()]]);
2068
+ _actionStates = /* @__PURE__ */ new Map();
2069
+ _actionListeners = [];
2070
+ _warned = /* @__PURE__ */ new Set();
2071
+ _pending = {
2072
+ deltaX: 0,
2073
+ deltaY: 0,
2074
+ wheelX: 0,
2075
+ wheelY: 0
2076
+ };
2077
+ _capture;
2078
+ /** The kind of device that produced the most recent input (initially `'keyboard'`). */
2079
+ get lastDevice() {
2080
+ return this._lastDevice;
2081
+ }
2082
+ /** Whether the pointer is locked to the target, see {@link Input.lockPointer}. */
2083
+ get isPointerLocked() {
2084
+ return typeof document !== "undefined" && !!this._target && document.pointerLockElement === this._target;
2085
+ }
2086
+ /**
2087
+ * @param target element that receives pointer, wheel and touch input (usually the canvas)
2088
+ */
2089
+ constructor(target, options = {}) {
2090
+ this._target = target;
2091
+ this._options = {
2092
+ defaults: options.defaults ?? true,
2093
+ preventDefault: options.preventDefault ?? true,
2094
+ preventContextMenu: options.preventContextMenu ?? true
2095
+ };
2096
+ if (this._options.defaults) this.actions.addDefaults();
2097
+ const keyboard = options.keyboardTarget ?? (typeof window !== "undefined" ? window : void 0);
2098
+ if (keyboard) {
2099
+ this._listen(keyboard, "keydown", (e) => this._onKeyDown(e));
2100
+ this._listen(keyboard, "keyup", (e) => this._onKeyUp(e));
2101
+ this._listen(keyboard, "blur", () => this.releaseAll(0));
2102
+ }
2103
+ if (typeof document !== "undefined") this._listen(document, "visibilitychange", () => {
2104
+ if (document.hidden) this.releaseAll(0);
2105
+ });
2106
+ if (target) {
2107
+ const style = target.style;
2108
+ if (this._options.preventDefault && style) style.touchAction = "none";
2109
+ this._listen(target, "pointerdown", (e) => this._onPointerDown(e));
2110
+ this._listen(target, "pointerup", (e) => this._onPointerUp(e));
2111
+ this._listen(target, "pointercancel", (e) => this._onPointerCancel(e));
2112
+ this._listen(target, "pointermove", (e) => this._onPointerMove(e));
2113
+ this._listen(target, "wheel", (e) => this._onWheel(e), { passive: false });
2114
+ this._listen(target, "contextmenu", (e) => {
2115
+ if (this._options.preventContextMenu) e.preventDefault();
2116
+ });
2117
+ }
2118
+ }
2119
+ /**
2120
+ * Call once per frame, before reading input: polls devices and advances "just pressed" /
2121
+ * "just released" by one frame. Action callbacks fire from here.
2122
+ */
2123
+ update() {
2124
+ this.pointer.deltaX = this._pending.deltaX;
2125
+ this.pointer.deltaY = this._pending.deltaY;
2126
+ this.pointer.wheelX = this._pending.wheelX;
2127
+ this.pointer.wheelY = this._pending.wheelY;
2128
+ this._pending.deltaX = this._pending.deltaY = this._pending.wheelX = this._pending.wheelY = 0;
2129
+ this._pollGamepads();
2130
+ this._pollXR();
2131
+ this._updateGestures();
2132
+ const devices = [...this._controls.keys()];
2133
+ const fired = [];
2134
+ for (const name of this.actions.names) {
2135
+ const action = this.actions.get(name);
2136
+ let states = this._actionStates.get(name);
2137
+ if (!states) this._actionStates.set(name, states = /* @__PURE__ */ new Map());
2138
+ let anyRaw = 0;
2139
+ for (const device of devices) {
2140
+ let raw = 0;
2141
+ for (const binding of action.bindings) raw = Math.max(raw, this._bindingValue(binding, device));
2142
+ anyRaw = Math.max(anyRaw, raw);
2143
+ if (this._advance(states, device, raw, action.deadzone)) fired.push({
2144
+ action: name,
2145
+ phase: states.get(device).pressed ? "pressed" : "released",
2146
+ device
2147
+ });
2148
+ }
2149
+ if (this._advance(states, ANY, anyRaw, action.deadzone)) fired.push({
2150
+ action: name,
2151
+ phase: states.get(ANY).pressed ? "pressed" : "released",
2152
+ device: ANY
2153
+ });
2154
+ }
2155
+ for (const controls of this._controls.values()) for (const state of controls.values()) state.pressed = false;
2156
+ 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();
2157
+ }
2158
+ /** Whether the action is held past its deadzone. Unknown actions return false (and warn once). */
2159
+ isActionPressed(action, query) {
2160
+ return this._state(action, query)?.pressed ?? false;
2161
+ }
2162
+ /** Whether the action became pressed in the last update(). */
2163
+ isActionJustPressed(action, query) {
2164
+ const state = this._state(action, query);
2165
+ return !!state && state.pressed && !state.wasPressed;
2166
+ }
2167
+ /** Whether the action was released in the last update(). */
2168
+ isActionJustReleased(action, query) {
2169
+ const state = this._state(action, query);
2170
+ return !!state && !state.pressed && state.wasPressed;
2171
+ }
2172
+ /** 0..1, rescaled past the action's deadzone (analog triggers and sticks give values in between). */
2173
+ getActionStrength(action, query) {
2174
+ return this._state(action, query)?.strength ?? 0;
2175
+ }
2176
+ /** 0..1 before the deadzone is applied. */
2177
+ getActionRawStrength(action, query) {
2178
+ return this._state(action, query)?.raw ?? 0;
2179
+ }
2180
+ /** -1..1: `positive` minus `negative`. */
2181
+ getAxis(negative, positive, query) {
2182
+ return this.getActionStrength(positive, query) - this.getActionStrength(negative, query);
2183
+ }
2184
+ /**
2185
+ * A 2D direction from four actions, with a circular deadzone and length at most 1 (diagonals
2186
+ * aren't faster). Y is positive towards `positiveY`, as in Godot's get_vector("left", "right", "up", "down").
2187
+ *
2188
+ * @param options.deadzone default: the average of the four actions' deadzones
2189
+ * @returns `x` and `y` in -1..1; `{ x: 0, y: 0 }` inside the deadzone
2190
+ */
2191
+ getVector(negativeX, positiveX, negativeY, positiveY, options = {}) {
2192
+ const names = [
2193
+ negativeX,
2194
+ positiveX,
2195
+ negativeY,
2196
+ positiveY
2197
+ ];
2198
+ const raw = names.map((name) => this.getActionRawStrength(name, options));
2199
+ const deadzone = options.deadzone ?? names.reduce((sum, name) => sum + (this.actions.get(name)?.deadzone ?? 0), 0) / 4;
2200
+ let x = raw[1] - raw[0];
2201
+ let y = raw[3] - raw[2];
2202
+ const length = Math.hypot(x, y);
2203
+ if (length <= deadzone) return {
2204
+ x: 0,
2205
+ y: 0
2206
+ };
2207
+ const scale = (Math.min(length, 1) - deadzone) / (1 - deadzone) / length;
2208
+ x *= scale;
2209
+ y *= scale;
2210
+ return {
2211
+ x,
2212
+ y
2213
+ };
2214
+ }
2215
+ /** Calls `callback` when the action is pressed or released (during update()). Returns an unsubscribe function. */
2216
+ onAction(action, phase, callback, query = {}) {
2217
+ const listener = {
2218
+ action,
2219
+ phase,
2220
+ device: query.device ?? ANY,
2221
+ callback
2222
+ };
2223
+ this._actionListeners.push(listener);
2224
+ return () => {
2225
+ const i = this._actionListeners.indexOf(listener);
2226
+ if (i >= 0) this._actionListeners.splice(i, 1);
2227
+ };
2228
+ }
2229
+ /** Whether a key (by `KeyboardEvent.code`) is held right now, regardless of actions. */
2230
+ isKeyPressed(code) {
2231
+ return (this._controls.get(0).get(`key:${code}`)?.value ?? 0) > 0;
2232
+ }
2233
+ /** Whether a mouse or pen button is held right now, regardless of actions. */
2234
+ isMouseButtonPressed(button) {
2235
+ return (this._controls.get(0).get(`mouse:${button}`)?.value ?? 0) > 0;
2236
+ }
2237
+ /**
2238
+ * Releases every held key and button, on one device or all. Keyboard, mouse and touch (device 0)
2239
+ * are released automatically when the window loses focus, since their release events get lost.
2240
+ */
2241
+ releaseAll(device) {
2242
+ if (device === void 0 || device === 0) this.gestureRecognizer.clear();
2243
+ for (const [d, controls] of this._controls) {
2244
+ if (device !== void 0 && d !== device) continue;
2245
+ for (const state of controls.values()) {
2246
+ state.value = 0;
2247
+ state.suppressed = false;
2248
+ }
2249
+ }
2250
+ }
2251
+ /** Requests pointer lock on the target (browsers only allow it from a user gesture, e.g. a click). */
2252
+ lockPointer() {
2253
+ this._target?.requestPointerLock?.();
2254
+ }
2255
+ /** Exits pointer lock if the target holds it. */
2256
+ unlockPointer() {
2257
+ if (this.isPointerLocked) document.exitPointerLock();
2258
+ }
2259
+ /**
2260
+ * Waits for the player's next input and resolves with a binding for it, for rebinding menus.
2261
+ * Resolves `null` if the cancel key is pressed or another capture starts. The captured press
2262
+ * doesn't trigger any actions.
2263
+ */
2264
+ captureBinding(options = {}) {
2265
+ this.cancelCapture();
2266
+ return new Promise((resolve) => {
2267
+ this._capture = {
2268
+ options,
2269
+ resolve
2270
+ };
2271
+ });
2272
+ }
2273
+ /** Ends a pending {@link Input.captureBinding}, resolving it with `null`. */
2274
+ cancelCapture() {
2275
+ const capture = this._capture;
2276
+ this._capture = void 0;
2277
+ capture?.resolve(null);
2278
+ }
2279
+ /**
2280
+ * Loads the keyboard layout (where supported, e.g. Chromium) so {@link bindingLabel} names keys
2281
+ * as printed on the player's keyboard: KeyW is "Z" on AZERTY.
2282
+ */
2283
+ async loadKeyboardLayout() {
2284
+ const keyboard = globalThis.navigator?.keyboard;
2285
+ try {
2286
+ this._keyLabels = await keyboard?.getLayoutMap?.();
2287
+ } catch {
2288
+ this._keyLabels = void 0;
2289
+ }
2290
+ return this._keyLabels;
2291
+ }
2292
+ /** The layout loaded by {@link Input.loadKeyboardLayout}, if any: `KeyboardEvent.code` to printed key. */
2293
+ get keyLabels() {
2294
+ return this._keyLabels;
2295
+ }
2296
+ /** Removes all event listeners and action callbacks, cancels any capture and detaches XR. */
2297
+ dispose() {
2298
+ for (const [target, type, listener, options] of this._listeners) target.removeEventListener(type, listener, options);
2299
+ this._listeners.length = 0;
2300
+ this._actionListeners.length = 0;
2301
+ this.cancelCapture();
2302
+ this.detachXR();
2303
+ }
2304
+ _listen(target, type, listener, options) {
2305
+ target.addEventListener(type, listener, options);
2306
+ this._listeners.push([
2307
+ target,
2308
+ type,
2309
+ listener,
2310
+ options
2311
+ ]);
2312
+ }
2313
+ _state(action, query) {
2314
+ if (!this.actions.has(action)) {
2315
+ if (!this._warned.has(action)) {
2316
+ this._warned.add(action);
2317
+ console.warn(`Input: unknown action "${action}"`);
2318
+ }
2319
+ return;
2320
+ }
2321
+ return this._actionStates.get(action)?.get(query?.device ?? ANY);
2322
+ }
2323
+ _advance(states, device, raw, deadzone) {
2324
+ let state = states.get(device);
2325
+ if (!state) states.set(device, state = {
2326
+ raw: 0,
2327
+ strength: 0,
2328
+ pressed: false,
2329
+ wasPressed: false
2330
+ });
2331
+ state.wasPressed = state.pressed;
2332
+ state.raw = raw;
2333
+ state.pressed = raw > 0 && raw >= deadzone;
2334
+ state.strength = !state.pressed ? 0 : deadzone >= 1 ? 1 : Math.min(1, (raw - deadzone) / (1 - deadzone));
2335
+ if (state.pressed && raw >= 1) state.strength = 1;
2336
+ return state.pressed !== state.wasPressed;
2337
+ }
2338
+ _controlValue(device, id) {
2339
+ const state = this._controls.get(device)?.get(id);
2340
+ if (!state || state.suppressed) return 0;
2341
+ return state.pressed && state.value < .5 ? 1 : state.value;
2342
+ }
2343
+ _bindingValue(binding, device) {
2344
+ const value = this._controlValue(device, controlId(binding));
2345
+ if (value === 0 || binding.type !== "key" || !binding.modifiers) return value;
2346
+ const held = (left, right) => this._controlValue(device, `key:${left}`) > 0 || this._controlValue(device, `key:${right}`) > 0;
2347
+ const m = binding.modifiers;
2348
+ if (m.shift && !held("ShiftLeft", "ShiftRight")) return 0;
2349
+ if (m.ctrl && !held("ControlLeft", "ControlRight")) return 0;
2350
+ if (m.alt && !held("AltLeft", "AltRight")) return 0;
2351
+ if (m.meta && !held("MetaLeft", "MetaRight")) return 0;
2352
+ return value;
2353
+ }
2354
+ _control(device, binding) {
2355
+ let controls = this._controls.get(device);
2356
+ if (!controls) this._controls.set(device, controls = /* @__PURE__ */ new Map());
2357
+ const id = controlId(binding);
2358
+ let state = controls.get(id);
2359
+ if (!state) controls.set(id, state = {
2360
+ value: 0,
2361
+ pressed: false,
2362
+ suppressed: false
2363
+ });
2364
+ return state;
2365
+ }
2366
+ /** Updates a held control (key, button, axis direction: 0..1); `binding` describes it for captureBinding(). */
2367
+ _setControl(device, binding, value) {
2368
+ const state = this._control(device, binding);
2369
+ const wasDown = state.value >= .5;
2370
+ state.value = value;
2371
+ if (value >= .5 && !wasDown) {
2372
+ if (this._tryCapture(binding)) state.suppressed = true;
2373
+ else state.pressed = true;
2374
+ }
2375
+ if (value === 0) state.suppressed = false;
2376
+ }
2377
+ /** A one-frame press with no held state: wheel steps, gestures. */
2378
+ _pulse(device, binding) {
2379
+ const state = this._control(device, binding);
2380
+ if (!this._tryCapture(binding)) state.pressed = true;
2381
+ }
2382
+ _tryCapture(binding) {
2383
+ const capture = this._capture;
2384
+ if (!capture) return false;
2385
+ const types = capture.options.types;
2386
+ const cancelKey = capture.options.cancelKey === void 0 ? "Escape" : capture.options.cancelKey;
2387
+ const cancelled = binding.type === "key" && binding.code === cancelKey;
2388
+ if (!cancelled && types && !types.includes(binding.type)) return false;
2389
+ this._capture = void 0;
2390
+ capture.resolve(cancelled ? null : binding);
2391
+ return true;
2392
+ }
2393
+ _setLastDevice(type) {
2394
+ if (type === this._lastDevice) return;
2395
+ this._lastDevice = type;
2396
+ this.onDeviceChange.notify(type);
2397
+ }
2398
+ /**
2399
+ * Vibrates a gamepad (where supported). Magnitudes are 0..1; `strong` defaults to 1, `weak` to
2400
+ * `strong`, `duration` to 200 ms.
2401
+ */
2402
+ rumble(device, options = {}) {
2403
+ (this._gamepads.get(device)?.vibrationActuator)?.playEffect?.("dual-rumble", {
2404
+ startDelay: 0,
2405
+ duration: options.duration ?? 200,
2406
+ strongMagnitude: options.strong ?? 1,
2407
+ weakMagnitude: options.weak ?? options.strong ?? 1
2408
+ })?.catch(() => {});
2409
+ }
2410
+ _pollGamepads() {
2411
+ const pads = globalThis.navigator?.getGamepads?.() ?? [];
2412
+ const seen = /* @__PURE__ */ new Set();
2413
+ for (const gamepad of pads) {
2414
+ if (!gamepad || !gamepad.connected) continue;
2415
+ const device = gamepad.index + 1;
2416
+ const isNew = !this._gamepads.has(device);
2417
+ seen.add(device);
2418
+ this._gamepads.set(device, gamepad);
2419
+ if (isNew) this.onGamepadConnected.notify({
2420
+ device,
2421
+ id: gamepad.id,
2422
+ standard: gamepad.mapping === "standard"
2423
+ });
2424
+ let active = false;
2425
+ for (let i = 0; i < GAMEPAD_BUTTONS.length && i < gamepad.buttons.length; i++) {
2426
+ const button = gamepad.buttons[i];
2427
+ const value = button.value > 0 ? button.value : button.pressed ? 1 : 0;
2428
+ this._setControl(device, {
2429
+ type: "pad",
2430
+ button: GAMEPAD_BUTTONS[i]
2431
+ }, value);
2432
+ active ||= value >= .5;
2433
+ }
2434
+ for (let i = 0; i < GAMEPAD_AXES.length && i < gamepad.axes.length; i++) {
2435
+ const value = gamepad.axes[i];
2436
+ this._setControl(device, {
2437
+ type: "padAxis",
2438
+ axis: GAMEPAD_AXES[i],
2439
+ direction: 1
2440
+ }, Math.max(0, value));
2441
+ this._setControl(device, {
2442
+ type: "padAxis",
2443
+ axis: GAMEPAD_AXES[i],
2444
+ direction: -1
2445
+ }, Math.max(0, -value));
2446
+ active ||= Math.abs(value) >= .5;
2447
+ }
2448
+ if (active) this._setLastDevice("gamepad");
2449
+ }
2450
+ for (const [device, gamepad] of this._gamepads) {
2451
+ if (seen.has(device)) continue;
2452
+ for (const state of this._controls.get(device)?.values() ?? []) state.value = 0;
2453
+ this._gamepads.delete(device);
2454
+ this.onGamepadDisconnected.notify({
2455
+ device,
2456
+ id: gamepad.id,
2457
+ standard: gamepad.mapping === "standard"
2458
+ });
2459
+ }
2460
+ }
2461
+ _updateGestures() {
2462
+ const frame = this.gestureRecognizer.update(now());
2463
+ this.gestures.pinch = frame.pinch;
2464
+ this.gestures.pan = frame.pan;
2465
+ this.gestures.rotate = frame.rotate;
2466
+ for (const name of frame.gestures) this._pulse(0, {
2467
+ type: "gesture",
2468
+ gesture: name
2469
+ });
2470
+ }
2471
+ _xrSession;
2472
+ _xrEnd;
2473
+ _xrHeld = /* @__PURE__ */ new Set();
2474
+ /** The session set by {@link Input.attachXR}, until detached or ended. */
2475
+ get xrSession() {
2476
+ return this._xrSession;
2477
+ }
2478
+ /**
2479
+ * Reads VR controller buttons and sticks from a WebXR session (e.g. `renderer.xr.getSession()`)
2480
+ * into the action map. Controller poses stay with three.js (`renderer.xr.getController(i)`).
2481
+ * XR controller state only updates during XR frames, so call update() from the XR animation
2482
+ * loop (`renderer.setAnimationLoop`). Detaches automatically when the session ends.
2483
+ */
2484
+ attachXR(session) {
2485
+ this.detachXR();
2486
+ this._xrSession = session;
2487
+ this._xrEnd = () => this.detachXR();
2488
+ session.addEventListener("end", this._xrEnd);
2489
+ }
2490
+ /** Stops reading the XR session and releases its controls. */
2491
+ detachXR() {
2492
+ if (this._xrSession && this._xrEnd) this._xrSession.removeEventListener("end", this._xrEnd);
2493
+ this._xrSession = void 0;
2494
+ this._xrEnd = void 0;
2495
+ this._releaseXR(/* @__PURE__ */ new Set());
2496
+ }
2497
+ _pollXR() {
2498
+ const session = this._xrSession;
2499
+ if (!session) return;
2500
+ const held = /* @__PURE__ */ new Set();
2501
+ let active = false;
2502
+ for (const source of session.inputSources) {
2503
+ const hand = source.handedness;
2504
+ const gamepad = source.gamepad;
2505
+ if (hand !== "left" && hand !== "right" || !gamepad) continue;
2506
+ for (let i = 0; i < XR_BUTTONS.length && i < gamepad.buttons.length; i++) {
2507
+ const button = gamepad.buttons[i];
2508
+ const value = button.value > 0 ? button.value : button.pressed ? 1 : 0;
2509
+ const binding = {
2510
+ type: "xr",
2511
+ hand,
2512
+ button: XR_BUTTONS[i]
2513
+ };
2514
+ this._setControl(0, binding, value);
2515
+ held.add(controlId(binding));
2516
+ active ||= value >= .5;
2517
+ }
2518
+ for (let i = 0; i < XR_AXES.length && i < gamepad.axes.length; i++) {
2519
+ const value = gamepad.axes[i];
2520
+ for (const direction of [1, -1]) {
2521
+ const binding = {
2522
+ type: "xrAxis",
2523
+ hand,
2524
+ axis: XR_AXES[i],
2525
+ direction
2526
+ };
2527
+ this._setControl(0, binding, Math.max(0, value * direction));
2528
+ held.add(controlId(binding));
2529
+ }
2530
+ active ||= Math.abs(value) >= .5;
2531
+ }
2532
+ }
2533
+ this._releaseXR(held);
2534
+ for (const id of held) this._xrHeld.add(id);
2535
+ if (active) this._setLastDevice("xr");
2536
+ }
2537
+ _releaseXR(keep) {
2538
+ const controls = this._controls.get(0);
2539
+ for (const id of this._xrHeld) {
2540
+ if (keep.has(id)) continue;
2541
+ const state = controls.get(id);
2542
+ if (state) state.value = 0;
2543
+ this._xrHeld.delete(id);
2544
+ }
2545
+ }
2546
+ _isBound(type, predicate) {
2547
+ for (const name of this.actions.names) if (this.actions.get(name).bindings.some((b) => b.type === type && predicate(b))) return true;
2548
+ return false;
2549
+ }
2550
+ _onKeyDown(event) {
2551
+ if (isEditable(event.target)) return;
2552
+ if (this._options.preventDefault && this._isBound("key", (b) => b.type === "key" && b.code === event.code)) event.preventDefault();
2553
+ this._setLastDevice("keyboard");
2554
+ if (event.repeat) return;
2555
+ this._setControl(0, {
2556
+ type: "key",
2557
+ code: event.code
2558
+ }, 1);
2559
+ }
2560
+ _onKeyUp(event) {
2561
+ this._setControl(0, {
2562
+ type: "key",
2563
+ code: event.code
2564
+ }, 0);
2565
+ }
2566
+ _updatePointer(event) {
2567
+ const rect = this._target?.getBoundingClientRect?.();
2568
+ const left = rect?.left ?? 0;
2569
+ const top = rect?.top ?? 0;
2570
+ const width = rect?.width || 1;
2571
+ const height = rect?.height || 1;
2572
+ this.pointer.type = event.pointerType === "pen" ? "pen" : "mouse";
2573
+ this.pointer.x = event.clientX - left;
2574
+ this.pointer.y = event.clientY - top;
2575
+ this.pointer.ndcX = this.pointer.x / width * 2 - 1;
2576
+ this.pointer.ndcY = -(this.pointer.y / height * 2 - 1);
2577
+ this.pointer.pressure = event.pressure ?? 0;
2578
+ this.pointer.tiltX = event.tiltX ?? 0;
2579
+ this.pointer.tiltY = event.tiltY ?? 0;
2580
+ }
2581
+ _local(event) {
2582
+ const rect = this._target?.getBoundingClientRect?.();
2583
+ return {
2584
+ x: event.clientX - (rect?.left ?? 0),
2585
+ y: event.clientY - (rect?.top ?? 0)
2586
+ };
2587
+ }
2588
+ _onPointerDown(event) {
2589
+ if (event.pointerType === "touch") {
2590
+ const { x, y } = this._local(event);
2591
+ this.gestureRecognizer.down(event.pointerId, x, y, now());
2592
+ this._setLastDevice("touch");
2593
+ this._target?.setPointerCapture?.(event.pointerId);
2594
+ return;
2595
+ }
2596
+ this._updatePointer(event);
2597
+ this._setLastDevice(event.pointerType === "pen" ? "pen" : "mouse");
2598
+ const button = MOUSE_BUTTONS[event.button];
2599
+ if (button) this._setControl(0, {
2600
+ type: "mouse",
2601
+ button
2602
+ }, 1);
2603
+ this._target?.setPointerCapture?.(event.pointerId);
2604
+ }
2605
+ _onPointerUp(event) {
2606
+ if (event.pointerType === "touch") {
2607
+ const { x, y } = this._local(event);
2608
+ this.gestureRecognizer.up(event.pointerId, x, y, now());
2609
+ return;
2610
+ }
2611
+ this._updatePointer(event);
2612
+ const button = MOUSE_BUTTONS[event.button];
2613
+ if (button) this._setControl(0, {
2614
+ type: "mouse",
2615
+ button
2616
+ }, 0);
2617
+ }
2618
+ _onPointerCancel(event) {
2619
+ if (event.pointerType === "touch") this.gestureRecognizer.cancel(event.pointerId);
2620
+ else this._onPointerUp(event);
2621
+ }
2622
+ _onPointerMove(event) {
2623
+ if (event.pointerType === "touch") {
2624
+ const { x, y } = this._local(event);
2625
+ this.gestureRecognizer.move(event.pointerId, x, y);
2626
+ return;
2627
+ }
2628
+ this._updatePointer(event);
2629
+ this._setLastDevice(event.pointerType === "pen" ? "pen" : "mouse");
2630
+ this._pending.deltaX += event.movementX ?? 0;
2631
+ this._pending.deltaY += event.movementY ?? 0;
2632
+ const button = MOUSE_BUTTONS[event.button];
2633
+ if (button) {
2634
+ const down = ((event.buttons ?? 0) & BUTTON_BITS[event.button]) !== 0;
2635
+ this._setControl(0, {
2636
+ type: "mouse",
2637
+ button
2638
+ }, down ? 1 : 0);
2639
+ }
2640
+ }
2641
+ _onWheel(event) {
2642
+ const scale = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 800 : 1;
2643
+ const dx = event.deltaX * scale;
2644
+ const dy = event.deltaY * scale;
2645
+ this._pending.wheelX += dx;
2646
+ this._pending.wheelY += dy;
2647
+ if (this._options.preventDefault && this._isBound("wheel", () => true)) event.preventDefault();
2648
+ if (dy < 0) this._pulse(0, {
2649
+ type: "wheel",
2650
+ direction: "up"
2651
+ });
2652
+ if (dy > 0) this._pulse(0, {
2653
+ type: "wheel",
2654
+ direction: "down"
2655
+ });
2656
+ if (dx < 0) this._pulse(0, {
2657
+ type: "wheel",
2658
+ direction: "left"
2659
+ });
2660
+ if (dx > 0) this._pulse(0, {
2661
+ type: "wheel",
2662
+ direction: "right"
2663
+ });
2664
+ }
2665
+ };
2666
+ //#endregion
2667
+ //#region src/misc.ts
2668
+ /**
2669
+ * True if `target` is `null` or `undefined`.
2670
+ * @category Utilities
2671
+ */
2672
+ function isNullOrUndefined(target) {
2673
+ return target === null || target === void 0;
2674
+ }
2675
+ /**
2676
+ * True if `target` is a non-empty string.
2677
+ * @category Utilities
2678
+ */
2679
+ function isPositiveString(target) {
2680
+ return target.length > 0;
2681
+ }
2682
+ /**
2683
+ * Maps `value / max` onto an 11-step red -> yellow -> green gradient and returns its `'#rrggbb'`
2684
+ * color; ratios at or below 0 (or a `max` at or below 0) are red, ratios at or above 1 are green.
2685
+ * `max` defaults to 1, so a single argument is rated as a 0-1 fraction.
2686
+ * @category Utilities
2687
+ */
2688
+ const getRedYellowGreenGradientHex = (value, max = 1) => {
2689
+ const percent = max > 0 ? value / max : 0;
2690
+ return [
2691
+ "#ff0000",
2692
+ "#ff3300",
2693
+ "#ff6600",
2694
+ "#ff9900",
2695
+ "#ffcc00",
2696
+ "#ffff00",
2697
+ "#ccff00",
2698
+ "#99ff00",
2699
+ "#66ff00",
2700
+ "#33ff00",
2701
+ "#00ff00"
2702
+ ][require_spatial_partition_3d.clamp(Math.floor(percent * 10), 0, 10)];
2703
+ };
2704
+ /**
2705
+ * The current page's query-string parameters as a plain object of strings (the last value wins
2706
+ * for repeated keys). Needs `location`, so browser only.
2707
+ * @category Utilities
2708
+ */
2709
+ function GetUrlParams() {
2710
+ const params = {};
2711
+ const url = new URLSearchParams(location.search);
2712
+ for (const [key, value] of url.entries()) params[key] = value;
2713
+ return params;
2714
+ }
2715
+ /**
2716
+ * Joins `x` and `y` into a string key such as `'3,4'`, e.g. for use in a `Map` or `Set`.
2717
+ * @category Utilities
2718
+ */
2719
+ const xy2k = (x, y, delimiter = ",") => `${x}${delimiter}${y}`;
2720
+ /**
2721
+ * Splits a key made by {@link xy2k} back into `[x, y]` (parsed with `parseFloat`).
2722
+ * @category Utilities
2723
+ */
2724
+ const k2xy = (key, delimiter = ",") => key.split(delimiter).map(parseFloat);
2725
+ /**
2726
+ * Joins `x`, `y` and `z` into a string key such as `'1,2,3'`.
2727
+ * @category Utilities
2728
+ */
2729
+ const xyz2k = (x, y, z, delimiter = ",") => `${x}${delimiter}${y}${delimiter}${z}`;
2730
+ /**
2731
+ * Splits a key made by {@link xyz2k} back into `[x, y, z]` (parsed with `parseFloat`).
2732
+ * @category Utilities
2733
+ */
2734
+ const k2xyz = (key, delimiter = ",") => key.split(delimiter).map(parseFloat);
2735
+ //#endregion
2736
+ //#region src/particle-renderer.ts
2737
+ /**
2738
+ * Double-buffered square-pixel renderer for particle effects: draw with `setPixel()` into an
2739
+ * offscreen buffer, then `render()` copies the buffer to the visible canvas and clears it.
2740
+ * Requires `OffscreenCanvas`. Used by {@link ParticleSystem2d}.
2741
+ *
2742
+ * ```ts
2743
+ * const renderer = new ParticleRenderer();
2744
+ * renderer.appendTo(document.body);
2745
+ *
2746
+ * renderer.setPixel(10, 10, Color.RED);
2747
+ * renderer.render();
2748
+ * ```
2749
+ *
2750
+ * @category Canvas 2D
2751
+ */
2752
+ var ParticleRenderer = class {
2753
+ _screenCanvas;
2754
+ _bufferCanvas;
2755
+ /** context of the visible canvas */
2756
+ screenContext;
2757
+ /** context of the offscreen buffer that `setPixel()` draws into */
2758
+ bufferContext;
2759
+ /** canvas width in pixels */
2760
+ get width() {
2761
+ return this._screenCanvas.width;
2762
+ }
2763
+ /** canvas height in pixels */
2764
+ get height() {
2765
+ return this._screenCanvas.height;
2766
+ }
2767
+ /**
2768
+ * @param canvas the visible canvas; defaults to a new canvas element, not attached to the page
2769
+ * @throws an `Error` if a 2D context can't be created
2770
+ */
2771
+ constructor(canvas) {
2772
+ this._screenCanvas = canvas ?? document.createElement("canvas");
2773
+ this._bufferCanvas = new OffscreenCanvas(this._screenCanvas.width, this._screenCanvas.height);
2774
+ const screenContext = this._screenCanvas.getContext("2d");
2775
+ const bufferContext = this._bufferCanvas.getContext("2d");
2776
+ if (!screenContext || !bufferContext) throw new Error("ParticleRenderer: failed to create CanvasRenderingContext2D");
2777
+ this.screenContext = screenContext;
2778
+ this.bufferContext = bufferContext;
2779
+ }
2780
+ /** Moves the canvas into `target` and, with `autoResize` (default true), resizes it to fit. */
2781
+ appendTo(target, autoResize = true) {
2782
+ if (this._screenCanvas.parentNode) this._screenCanvas.parentNode.removeChild(this._screenCanvas);
2783
+ target.appendChild(this._screenCanvas);
2784
+ if (autoResize) this.resize();
2785
+ }
2786
+ /**
2787
+ * Sets the canvas and buffer size in pixels (truncated to integers). A missing dimension
2788
+ * defaults to the parent element's size (or the canvas's own size on the page). Resizing
2789
+ * clears the buffer. Returns whether the size changed.
2790
+ */
2791
+ resize(displayWidth, displayHeight) {
2792
+ const { width, height } = this._screenCanvas.parentElement?.getBoundingClientRect() ?? this._screenCanvas.getBoundingClientRect();
2793
+ displayWidth = 0 | (displayWidth ?? width);
2794
+ displayHeight = 0 | (displayHeight ?? height);
2795
+ if (this._screenCanvas.width !== displayWidth || this._screenCanvas.height !== displayHeight) {
2796
+ this._screenCanvas.width = displayWidth;
2797
+ this._screenCanvas.height = displayHeight;
2798
+ this._bufferCanvas.width = displayWidth;
2799
+ this._bufferCanvas.height = displayHeight;
2800
+ return true;
2801
+ }
2802
+ return false;
2803
+ }
2804
+ /** Draws a filled `size` x `size` square (pixels, default 2) centered on (`x`, `y`) into the buffer. */
2805
+ setPixel(x, y, color, size = 2) {
2806
+ this.bufferContext.fillStyle = color.hexStr;
2807
+ this.bufferContext.fillRect(x - size / 2, y - size / 2, size, size);
2808
+ }
2809
+ /** Replaces the visible canvas with the buffer's contents, then clears the buffer for the next frame. */
2810
+ render() {
2811
+ this.screenContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
2812
+ this.screenContext.drawImage(this._bufferCanvas, 0, 0);
2813
+ this.bufferContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
2814
+ }
2815
+ };
2816
+ //#endregion
2817
+ //#region src/signal.ts
2818
+ /**
2819
+ * A value holder that notifies subscribers when the value changes (compared with `Object.is`).
2820
+ * Subscribers are called immediately with the current value when they subscribe.
2821
+ *
2822
+ * ```ts
2823
+ * const health = new Signal(100);
2824
+ * const unsubscribe = health.subscribe(value => console.log(value)); // logs 100
2825
+ *
2826
+ * health.set(80); // logs 80
2827
+ * health.set(80); // unchanged: nothing logged
2828
+ * unsubscribe();
2829
+ * ```
2830
+ *
2831
+ * @category Events & Timing
2832
+ */
2833
+ var Signal = class {
2834
+ value;
2835
+ subscribers = /* @__PURE__ */ new Set();
2836
+ constructor(initialValue) {
2837
+ this.value = initialValue;
2838
+ }
2839
+ /** Returns the current value. */
2840
+ get() {
2841
+ return this.value;
2842
+ }
2843
+ /** Sets the value and notifies subscribers; does nothing if it is the same (`Object.is`). */
2844
+ set(value) {
2845
+ if (Object.is(this.value, value)) return;
2846
+ this.value = value;
2847
+ for (const subscriber of [...this.subscribers]) subscriber(value);
2848
+ }
2849
+ /** Adds a subscriber and calls it right away with the current value; returns a function that removes it. */
2850
+ subscribe(subscriber) {
2851
+ this.subscribers.add(subscriber);
2852
+ subscriber(this.value);
2853
+ return () => this.subscribers.delete(subscriber);
2854
+ }
2855
+ };
2856
+ //#endregion
2857
+ //#region src/tilemap.ts
2858
+ /**
2859
+ * Sparse 2D grid of arbitrary values, keyed by floored integer coordinates. Simpler than
2860
+ * {@link Map2D} (string keys, any value type, no default value or range limit).
2861
+ *
2862
+ * @category Maps & Spatial
2863
+ */
2864
+ var Tilemap = class {
2865
+ /** backing store, keyed `"<x>x<y>"` (floored) */
2866
+ map = /* @__PURE__ */ new Map();
2867
+ _key(x, y) {
2868
+ x = Math.floor(x);
2869
+ y = Math.floor(y);
2870
+ return `${x}x${y}`;
2871
+ }
2872
+ /** Value of the tile containing (x, y), or `undefined` if none was set. */
2873
+ get(x, y) {
2874
+ return this.map.get(this._key(x, y));
2875
+ }
2876
+ /** Sets the tile containing (x, y). */
2877
+ set(x, y, v) {
2878
+ this.map.set(this._key(x, y), v);
2879
+ }
2880
+ };
2881
+ //#endregion
2882
+ //#region src/webgl.ts
2883
+ /**
2884
+ * Literal GLenum values, so importing this module doesn't require `WebGL2RenderingContext` to exist.
2885
+ *
2886
+ * @category WebGL
2887
+ */
2888
+ let ShaderType = /* @__PURE__ */ function(ShaderType) {
2889
+ /** gl.VERTEX_SHADER */
2890
+ ShaderType[ShaderType["VERTEX"] = 35633] = "VERTEX";
2891
+ /** gl.FRAGMENT_SHADER */
2892
+ ShaderType[ShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
2893
+ return ShaderType;
2894
+ }({});
2895
+ /**
2896
+ * Creates a WebGL2 context. Throws (instead of returning null) when WebGL2 isn't available.
2897
+ *
2898
+ * @param canvas defaults to a new canvas element
2899
+ *
2900
+ * @category WebGL
2901
+ */
2902
+ function CreateWebGlContext(canvas, attributes) {
2903
+ const gl = (canvas ?? document.createElement("canvas")).getContext("webgl2", attributes);
2904
+ if (!gl) throw new Error("WebGL2 is not available (unsupported browser or GPU, or the context was lost)");
2905
+ return gl;
2906
+ }
2907
+ /**
2908
+ * Sizes the drawing buffer to `width` x `height` CSS pixels times the pixel ratio (sharp on
2909
+ * high-DPI screens) and sets the viewport. Without a size, uses the canvas's parent (or its own)
2910
+ * size on the page. Returns whether the size changed.
2911
+ *
2912
+ * @category WebGL
2913
+ */
2914
+ function ResizeWebGlContext(gl, width, height, pixelRatio = globalThis.devicePixelRatio ?? 1) {
2915
+ const canvas = gl.canvas;
2916
+ if (width === void 0 || height === void 0) {
2917
+ const element = canvas;
2918
+ const rect = element.parentElement?.getBoundingClientRect?.() ?? element.getBoundingClientRect?.();
2919
+ width ??= rect?.width ?? canvas.width;
2920
+ height ??= rect?.height ?? canvas.height;
2921
+ }
2922
+ const bufferWidth = Math.max(1, Math.round(width * pixelRatio));
2923
+ const bufferHeight = Math.max(1, Math.round(height * pixelRatio));
2924
+ if (canvas.width === bufferWidth && canvas.height === bufferHeight) return false;
2925
+ canvas.width = bufferWidth;
2926
+ canvas.height = bufferHeight;
2927
+ gl.viewport(0, 0, bufferWidth, bufferHeight);
2928
+ return true;
2929
+ }
2930
+ function describeShaderError(log, source) {
2931
+ const lines = source.split("\n");
2932
+ const errorLines = new Set([...log.matchAll(/ERROR:\s*\d+:(\d+):/g)].map((m) => Number(m[1])));
2933
+ const excerpt = [];
2934
+ for (const line of [...errorLines].sort((a, b) => a - b)) {
2935
+ for (let n = Math.max(1, line - 2); n <= Math.min(lines.length, line + 2); n++) excerpt.push(`${n === line ? ">" : " "} ${String(n).padStart(4)} | ${lines[n - 1]}`);
2936
+ excerpt.push("");
2937
+ }
2938
+ return [
2939
+ log.trim(),
2940
+ "",
2941
+ ...excerpt
2942
+ ].join("\n").trimEnd();
2943
+ }
2944
+ /**
2945
+ * Compiles a shader; throws an Error quoting the failing source lines.
2946
+ *
2947
+ * @category WebGL
2948
+ */
2949
+ function CompileShader(gl, type, source) {
2950
+ const shader = gl.createShader(type);
2951
+ if (!shader) throw new Error("CompileShader: could not create a shader (context lost?)");
2952
+ gl.shaderSource(shader, source);
2953
+ gl.compileShader(shader);
2954
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
2955
+ const log = gl.getShaderInfoLog(shader) ?? "";
2956
+ const kind = type === 35633 ? "vertex" : "fragment";
2957
+ gl.deleteShader(shader);
2958
+ throw new Error(`CompileShader: ${kind} shader failed to compile:\n${describeShaderError(log, source)}`);
2959
+ }
2960
+ return shader;
2961
+ }
2962
+ /**
2963
+ * Links a program from shader sources (or compiled shaders). Shaders compiled here are deleted
2964
+ * after linking; ones passed in are left to the caller.
2965
+ *
2966
+ * @category WebGL
2967
+ */
2968
+ function CreateProgram(gl, vertexShader, fragmentShader) {
2969
+ const vs = typeof vertexShader === "string" ? CompileShader(gl, 35633, vertexShader) : vertexShader;
2970
+ let fs;
2971
+ try {
2972
+ fs = typeof fragmentShader === "string" ? CompileShader(gl, 35632, fragmentShader) : fragmentShader;
2973
+ } catch (error) {
2974
+ if (typeof vertexShader === "string") gl.deleteShader(vs);
2975
+ throw error;
2976
+ }
2977
+ const program = gl.createProgram();
2978
+ if (!program) throw new Error("CreateProgram: could not create a program (context lost?)");
2979
+ gl.attachShader(program, vs);
2980
+ gl.attachShader(program, fs);
2981
+ gl.linkProgram(program);
2982
+ const linked = gl.getProgramParameter(program, gl.LINK_STATUS);
2983
+ const log = linked ? "" : gl.getProgramInfoLog(program) ?? "";
2984
+ for (const [shader, owned] of [[vs, typeof vertexShader === "string"], [fs, typeof fragmentShader === "string"]]) {
2985
+ gl.detachShader(program, shader);
2986
+ if (owned) gl.deleteShader(shader);
2987
+ }
2988
+ if (!linked) {
2989
+ gl.deleteProgram(program);
2990
+ throw new Error(`CreateProgram: failed to link:\n${log.trim()}`);
2991
+ }
2992
+ return program;
2993
+ }
2994
+ function isSamplerType(gl, type) {
2995
+ return samplerTarget(gl, type) !== void 0;
2996
+ }
2997
+ /** The texture target a sampler type binds to (TEXTURE_2D, TEXTURE_3D, ...), or undefined if it isn't a sampler. */
2998
+ function samplerTarget(gl, type) {
2999
+ switch (type) {
3000
+ case gl.SAMPLER_2D:
3001
+ case gl.SAMPLER_2D_SHADOW:
3002
+ case gl.INT_SAMPLER_2D:
3003
+ case gl.UNSIGNED_INT_SAMPLER_2D: return gl.TEXTURE_2D;
3004
+ case gl.SAMPLER_3D:
3005
+ case gl.INT_SAMPLER_3D:
3006
+ case gl.UNSIGNED_INT_SAMPLER_3D: return gl.TEXTURE_3D;
3007
+ case gl.SAMPLER_CUBE:
3008
+ case gl.SAMPLER_CUBE_SHADOW:
3009
+ case gl.INT_SAMPLER_CUBE:
3010
+ case gl.UNSIGNED_INT_SAMPLER_CUBE: return gl.TEXTURE_CUBE_MAP;
3011
+ case gl.SAMPLER_2D_ARRAY:
3012
+ case gl.SAMPLER_2D_ARRAY_SHADOW:
3013
+ case gl.INT_SAMPLER_2D_ARRAY:
3014
+ case gl.UNSIGNED_INT_SAMPLER_2D_ARRAY: return gl.TEXTURE_2D_ARRAY;
3015
+ }
3016
+ }
3017
+ /**
3018
+ * Active attributes and uniforms of a linked program. Array uniforms are listed by their base
3019
+ * name (`uLights[0]` -> `uLights`); samplers are given consecutive texture units.
3020
+ *
3021
+ * @category WebGL
3022
+ */
3023
+ function GetProgramLocations(gl, program) {
3024
+ const attributes = {};
3025
+ const uniforms = {};
3026
+ const attributeCount = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
3027
+ for (let i = 0; i < attributeCount; i++) {
3028
+ const info = gl.getActiveAttrib(program, i);
3029
+ if (info.name.startsWith("gl_")) continue;
3030
+ attributes[info.name] = {
3031
+ location: gl.getAttribLocation(program, info.name),
3032
+ type: info.type,
3033
+ size: info.size
3034
+ };
3035
+ }
3036
+ const uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
3037
+ let textureUnit = 0;
3038
+ for (let i = 0; i < uniformCount; i++) {
3039
+ const info = gl.getActiveUniform(program, i);
3040
+ const location = gl.getUniformLocation(program, info.name);
3041
+ if (!location) continue;
3042
+ const name = info.name.endsWith("[0]") ? info.name.slice(0, -3) : info.name;
3043
+ const uniform = {
3044
+ location,
3045
+ type: info.type,
3046
+ size: info.size
3047
+ };
3048
+ if (isSamplerType(gl, info.type)) {
3049
+ uniform.textureUnit = textureUnit;
3050
+ textureUnit += info.size;
3051
+ }
3052
+ uniforms[name] = uniform;
3053
+ }
3054
+ return {
3055
+ attributes,
3056
+ uniforms
3057
+ };
3058
+ }
3059
+ /**
3060
+ * Links a program and collects its attribute and uniform info.
3061
+ *
3062
+ * @category WebGL
3063
+ */
3064
+ function CreateProgramInfo(gl, vertexShaderSource, fragmentShaderSource) {
3065
+ const program = CreateProgram(gl, vertexShaderSource, fragmentShaderSource);
3066
+ return {
3067
+ program,
3068
+ ...GetProgramLocations(gl, program)
3069
+ };
3070
+ }
3071
+ /**
3072
+ * Deletes the program.
3073
+ *
3074
+ * @category WebGL
3075
+ */
3076
+ function DeleteProgramInfo(gl, info) {
3077
+ gl.deleteProgram(info.program);
3078
+ }
3079
+ const textureOf = (value) => {
3080
+ if (value && typeof value === "object" && "texture" in value) return value.texture;
3081
+ if (typeof WebGLTexture !== "undefined" && value instanceof WebGLTexture) return value;
3082
+ };
3083
+ /**
3084
+ * Sets uniforms by name; the right `gl.uniform*` call comes from each uniform's declared type.
3085
+ * Textures are bound to the sampler's texture unit. Names the program doesn't use (e.g. optimized
3086
+ * away by the compiler) are ignored. Makes the program current.
3087
+ *
3088
+ * @category WebGL
3089
+ */
3090
+ function SetUniforms(gl, info, values) {
3091
+ gl.useProgram(info.program);
3092
+ for (const name in values) {
3093
+ const uniform = info.uniforms[name];
3094
+ if (uniform) SetUniform(gl, uniform, values[name]);
3095
+ }
3096
+ }
3097
+ function SetUniform(gl, uniform, value) {
3098
+ const { location, type } = uniform;
3099
+ const target = samplerTarget(gl, type);
3100
+ if (target !== void 0) {
3101
+ const textures = Array.isArray(value) && value.length > 0 && typeof value[0] !== "number" ? value : [value];
3102
+ const units = [];
3103
+ textures.forEach((texture, i) => {
3104
+ const unit = (uniform.textureUnit ?? 0) + i;
3105
+ gl.activeTexture(gl.TEXTURE0 + unit);
3106
+ gl.bindTexture(target, textureOf(texture) ?? null);
3107
+ units.push(unit);
3108
+ });
3109
+ gl.uniform1iv(location, units);
3110
+ return;
3111
+ }
3112
+ const data = typeof value === "number" ? [value] : typeof value === "boolean" ? [value ? 1 : 0] : value;
3113
+ const f = data instanceof Float32Array ? data : new Float32Array(data);
3114
+ switch (type) {
3115
+ case gl.FLOAT:
3116
+ gl.uniform1fv(location, f);
3117
+ break;
3118
+ case gl.FLOAT_VEC2:
3119
+ gl.uniform2fv(location, f);
3120
+ break;
3121
+ case gl.FLOAT_VEC3:
3122
+ gl.uniform3fv(location, f);
3123
+ break;
3124
+ case gl.FLOAT_VEC4:
3125
+ gl.uniform4fv(location, f);
3126
+ break;
3127
+ case gl.INT:
3128
+ case gl.BOOL:
3129
+ gl.uniform1iv(location, Int32Array.from(data));
3130
+ break;
3131
+ case gl.INT_VEC2:
3132
+ case gl.BOOL_VEC2:
3133
+ gl.uniform2iv(location, Int32Array.from(data));
3134
+ break;
3135
+ case gl.INT_VEC3:
3136
+ case gl.BOOL_VEC3:
3137
+ gl.uniform3iv(location, Int32Array.from(data));
3138
+ break;
3139
+ case gl.INT_VEC4:
3140
+ case gl.BOOL_VEC4:
3141
+ gl.uniform4iv(location, Int32Array.from(data));
3142
+ break;
3143
+ case gl.UNSIGNED_INT:
3144
+ gl.uniform1uiv(location, Uint32Array.from(data));
3145
+ break;
3146
+ case gl.UNSIGNED_INT_VEC2:
3147
+ gl.uniform2uiv(location, Uint32Array.from(data));
3148
+ break;
3149
+ case gl.UNSIGNED_INT_VEC3:
3150
+ gl.uniform3uiv(location, Uint32Array.from(data));
3151
+ break;
3152
+ case gl.UNSIGNED_INT_VEC4:
3153
+ gl.uniform4uiv(location, Uint32Array.from(data));
3154
+ break;
3155
+ case gl.FLOAT_MAT2:
3156
+ gl.uniformMatrix2fv(location, false, f);
3157
+ break;
3158
+ case gl.FLOAT_MAT3:
3159
+ gl.uniformMatrix3fv(location, false, f);
3160
+ break;
3161
+ case gl.FLOAT_MAT4:
3162
+ gl.uniformMatrix4fv(location, false, f);
3163
+ break;
3164
+ case gl.FLOAT_MAT2x3:
3165
+ gl.uniformMatrix2x3fv(location, false, f);
3166
+ break;
3167
+ case gl.FLOAT_MAT2x4:
3168
+ gl.uniformMatrix2x4fv(location, false, f);
3169
+ break;
3170
+ case gl.FLOAT_MAT3x2:
3171
+ gl.uniformMatrix3x2fv(location, false, f);
3172
+ break;
3173
+ case gl.FLOAT_MAT3x4:
3174
+ gl.uniformMatrix3x4fv(location, false, f);
3175
+ break;
3176
+ case gl.FLOAT_MAT4x2:
3177
+ gl.uniformMatrix4x2fv(location, false, f);
3178
+ break;
3179
+ case gl.FLOAT_MAT4x3:
3180
+ gl.uniformMatrix4x3fv(location, false, f);
3181
+ break;
3182
+ default: throw new Error(`SetUniforms: unsupported uniform type 0x${type.toString(16)}`);
3183
+ }
3184
+ }
3185
+ /**
3186
+ * Creates a buffer from data (a plain number array becomes a Float32Array) or with a byte size
3187
+ * to fill later with UpdateBuffer.
3188
+ *
3189
+ * @category WebGL
3190
+ */
3191
+ function CreateBuffer(gl, data, options = {}) {
3192
+ const target = options.target ?? gl.ARRAY_BUFFER;
3193
+ const usage = options.usage ?? gl.STATIC_DRAW;
3194
+ const buffer = gl.createBuffer();
3195
+ if (!buffer) throw new Error("CreateBuffer: could not create a buffer (context lost?)");
3196
+ gl.bindBuffer(target, buffer);
3197
+ if (typeof data === "number") gl.bufferData(target, data, usage);
3198
+ else gl.bufferData(target, Array.isArray(data) ? new Float32Array(data) : data, usage);
3199
+ gl.bindBuffer(target, null);
3200
+ return buffer;
3201
+ }
3202
+ /**
3203
+ * Writes data into an existing buffer, starting at `byteOffset`.
3204
+ *
3205
+ * @category WebGL
3206
+ */
3207
+ function UpdateBuffer(gl, buffer, data, byteOffset = 0, target) {
3208
+ const t = target ?? gl.ARRAY_BUFFER;
3209
+ gl.bindBuffer(t, buffer);
3210
+ gl.bufferSubData(t, byteOffset, Array.isArray(data) ? new Float32Array(data) : data);
3211
+ gl.bindBuffer(t, null);
3212
+ }
3213
+ const BYTES = {
3214
+ 5120: 1,
3215
+ 5121: 1,
3216
+ 5122: 2,
3217
+ 5123: 2,
3218
+ 5124: 4,
3219
+ 5125: 4,
3220
+ 5126: 4,
3221
+ 5131: 2
3222
+ };
3223
+ function matrixColumns(gl, type) {
3224
+ switch (type) {
3225
+ case gl.FLOAT_MAT2:
3226
+ case gl.FLOAT_MAT2x3:
3227
+ case gl.FLOAT_MAT2x4: return 2;
3228
+ case gl.FLOAT_MAT3:
3229
+ case gl.FLOAT_MAT3x2:
3230
+ case gl.FLOAT_MAT3x4: return 3;
3231
+ case gl.FLOAT_MAT4:
3232
+ case gl.FLOAT_MAT4x2:
3233
+ case gl.FLOAT_MAT4x3: return 4;
3234
+ }
3235
+ return 1;
3236
+ }
3237
+ function isIntegerAttribute(gl, type) {
3238
+ switch (type) {
3239
+ case gl.INT:
3240
+ case gl.INT_VEC2:
3241
+ case gl.INT_VEC3:
3242
+ case gl.INT_VEC4:
3243
+ case gl.UNSIGNED_INT:
3244
+ case gl.UNSIGNED_INT_VEC2:
3245
+ case gl.UNSIGNED_INT_VEC3:
3246
+ case gl.UNSIGNED_INT_VEC4: return true;
3247
+ }
3248
+ return false;
3249
+ }
3250
+ /**
3251
+ * Records how the program's attributes read from buffers (and the index buffer) into a vertex
3252
+ * array object. Integer attributes (int / uint / ivec / uvec) use vertexAttribIPointer
3253
+ * automatically; matrix attributes (e.g. per-instance mat4) are spread over their columns.
3254
+ * Attributes the program doesn't use are skipped.
3255
+ *
3256
+ * @param indices an index array (Uint16Array / Uint32Array / Uint8Array), or an existing buffer and its type
3257
+ *
3258
+ * @category WebGL
3259
+ */
3260
+ function CreateVertexArray(gl, info, attributes, indices) {
3261
+ const vao = gl.createVertexArray();
3262
+ if (!vao) throw new Error("CreateVertexArray: could not create a vertex array (context lost?)");
3263
+ const result = {
3264
+ vao,
3265
+ buffers: []
3266
+ };
3267
+ let vertexCount = Infinity;
3268
+ gl.bindVertexArray(vao);
3269
+ for (const name in attributes) {
3270
+ const attribute = info.attributes[name];
3271
+ if (!attribute) continue;
3272
+ const source = attributes[name];
3273
+ const type = source.type ?? gl.FLOAT;
3274
+ const columns = matrixColumns(gl, attribute.type);
3275
+ const columnBytes = source.size * (BYTES[type] ?? 4);
3276
+ const stride = source.stride ?? (columns > 1 ? columnBytes * columns : 0);
3277
+ gl.bindBuffer(gl.ARRAY_BUFFER, source.buffer);
3278
+ if (!result.buffers.includes(source.buffer)) result.buffers.push(source.buffer);
3279
+ if (!source.divisor) {
3280
+ const bytes = gl.getBufferParameter(gl.ARRAY_BUFFER, gl.BUFFER_SIZE);
3281
+ const vertexBytes = columnBytes * columns;
3282
+ const available = bytes - (source.offset ?? 0) - vertexBytes;
3283
+ vertexCount = Math.min(vertexCount, available < 0 ? 0 : Math.floor(available / (stride || vertexBytes)) + 1);
3284
+ }
3285
+ for (let column = 0; column < columns; column++) {
3286
+ const location = attribute.location + column;
3287
+ const offset = (source.offset ?? 0) + column * columnBytes;
3288
+ gl.enableVertexAttribArray(location);
3289
+ if (isIntegerAttribute(gl, attribute.type)) gl.vertexAttribIPointer(location, source.size, type, stride, offset);
3290
+ else gl.vertexAttribPointer(location, source.size, type, source.normalized ?? false, stride, offset);
3291
+ if (source.divisor) gl.vertexAttribDivisor(location, source.divisor);
3292
+ }
3293
+ }
3294
+ if (indices) {
3295
+ if (ArrayBuffer.isView(indices)) {
3296
+ result.indexBuffer = CreateBuffer(gl, indices, { target: gl.ELEMENT_ARRAY_BUFFER });
3297
+ result.indexType = indices instanceof Uint32Array ? gl.UNSIGNED_INT : indices instanceof Uint8Array ? gl.UNSIGNED_BYTE : gl.UNSIGNED_SHORT;
3298
+ result.count = indices.length;
3299
+ result.buffers.push(result.indexBuffer);
3300
+ } else {
3301
+ result.indexBuffer = indices.buffer;
3302
+ result.indexType = indices.type;
3303
+ result.count = indices.count;
3304
+ if (!result.buffers.includes(indices.buffer)) result.buffers.push(indices.buffer);
3305
+ }
3306
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, result.indexBuffer);
3307
+ } else if (vertexCount < Infinity) result.count = vertexCount;
3308
+ gl.bindVertexArray(null);
3309
+ gl.bindBuffer(gl.ARRAY_BUFFER, null);
3310
+ gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
3311
+ return result;
3312
+ }
3313
+ /**
3314
+ * Deletes the vertex array; with `buffers`, also the buffers it reads from.
3315
+ *
3316
+ * @category WebGL
3317
+ */
3318
+ function DeleteVertexArray(gl, info, options = {}) {
3319
+ gl.deleteVertexArray(info.vao);
3320
+ if (options.buffers) for (const buffer of info.buffers) gl.deleteBuffer(buffer);
3321
+ }
3322
+ const sourceSize = (source) => {
3323
+ const s = source;
3324
+ return [s.naturalWidth || s.videoWidth || s.width, s.naturalHeight || s.videoHeight || s.height];
3325
+ };
3326
+ function uploadTexture(gl, info, source) {
3327
+ const o = info.options;
3328
+ gl.bindTexture(gl.TEXTURE_2D, info.texture);
3329
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, o.flipY ?? false);
3330
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, o.premultiplyAlpha ?? false);
3331
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
3332
+ if (!isImageSource(source)) {
3333
+ const data = source;
3334
+ info.width = data.width;
3335
+ info.height = data.height;
3336
+ gl.texImage2D(gl.TEXTURE_2D, 0, o.internalFormat ?? gl.RGBA8, data.width, data.height, 0, o.format ?? gl.RGBA, o.type ?? gl.UNSIGNED_BYTE, data.data ?? null);
3337
+ } else {
3338
+ [info.width, info.height] = sourceSize(source);
3339
+ gl.texImage2D(gl.TEXTURE_2D, 0, o.internalFormat ?? gl.RGBA8, o.format ?? gl.RGBA, o.type ?? gl.UNSIGNED_BYTE, source);
3340
+ }
3341
+ if (o.mipmaps) gl.generateMipmap(gl.TEXTURE_2D);
3342
+ gl.bindTexture(gl.TEXTURE_2D, null);
3343
+ }
3344
+ function isImageSource(source) {
3345
+ for (const name of [
3346
+ "HTMLImageElement",
3347
+ "HTMLCanvasElement",
3348
+ "HTMLVideoElement",
3349
+ "ImageBitmap",
3350
+ "ImageData",
3351
+ "OffscreenCanvas",
3352
+ "VideoFrame"
3353
+ ]) {
3354
+ const type = globalThis[name];
3355
+ if (type && source instanceof type) return true;
3356
+ }
3357
+ return false;
3358
+ }
3359
+ /**
3360
+ * Creates a 2D texture from an image / canvas / video / bitmap, or from raw data.
3361
+ *
3362
+ * @category WebGL
3363
+ */
3364
+ function CreateTexture(gl, source, options = {}) {
3365
+ const texture = gl.createTexture();
3366
+ if (!texture) throw new Error("CreateTexture: could not create a texture (context lost?)");
3367
+ const info = {
3368
+ texture,
3369
+ width: 0,
3370
+ height: 0,
3371
+ options: { ...options }
3372
+ };
3373
+ const nearest = options.filter === "nearest";
3374
+ const wrap = options.wrap === "repeat" ? gl.REPEAT : options.wrap === "mirror" ? gl.MIRRORED_REPEAT : gl.CLAMP_TO_EDGE;
3375
+ const minFilter = options.mipmaps ? nearest ? gl.NEAREST_MIPMAP_NEAREST : gl.LINEAR_MIPMAP_LINEAR : nearest ? gl.NEAREST : gl.LINEAR;
3376
+ gl.bindTexture(gl.TEXTURE_2D, texture);
3377
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
3378
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, nearest ? gl.NEAREST : gl.LINEAR);
3379
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, wrap);
3380
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, wrap);
3381
+ uploadTexture(gl, info, source);
3382
+ return info;
3383
+ }
3384
+ /**
3385
+ * Re-uploads a texture's contents (the size may change); regenerates mipmaps if it has them.
3386
+ *
3387
+ * @category WebGL
3388
+ */
3389
+ function UpdateTexture(gl, info, source) {
3390
+ uploadTexture(gl, info, source);
3391
+ }
3392
+ /**
3393
+ * Loads an image from a URL into a texture.
3394
+ *
3395
+ * @category WebGL
3396
+ */
3397
+ function LoadWebGlTexture(gl, url, options = {}) {
3398
+ const image = new Image();
3399
+ image.crossOrigin = "anonymous";
3400
+ image.src = url;
3401
+ return image.decode().then(() => CreateTexture(gl, image, options));
3402
+ }
3403
+ /**
3404
+ * Deletes the texture.
3405
+ *
3406
+ * @category WebGL
3407
+ */
3408
+ function DeleteTexture(gl, info) {
3409
+ gl.deleteTexture(info.texture);
3410
+ }
3411
+ /**
3412
+ * An offscreen framebuffer with a color texture (and depth), for render-to-texture and post-processing.
3413
+ *
3414
+ * @category WebGL
3415
+ */
3416
+ function CreateRenderTarget(gl, width, height, options = {}) {
3417
+ const texture = CreateTexture(gl, {
3418
+ width,
3419
+ height
3420
+ }, options);
3421
+ const framebuffer = gl.createFramebuffer();
3422
+ if (!framebuffer) throw new Error("CreateRenderTarget: could not create a framebuffer (context lost?)");
3423
+ const target = {
3424
+ framebuffer,
3425
+ texture,
3426
+ width,
3427
+ height
3428
+ };
3429
+ const previous = gl.getParameter(gl.FRAMEBUFFER_BINDING);
3430
+ gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
3431
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture.texture, 0);
3432
+ if (options.depth ?? true) {
3433
+ target.depth = gl.createRenderbuffer() ?? void 0;
3434
+ gl.bindRenderbuffer(gl.RENDERBUFFER, target.depth ?? null);
3435
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH24_STENCIL8, width, height);
3436
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, target.depth ?? null);
3437
+ gl.bindRenderbuffer(gl.RENDERBUFFER, null);
3438
+ }
3439
+ const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
3440
+ gl.bindFramebuffer(gl.FRAMEBUFFER, previous);
3441
+ if (status !== gl.FRAMEBUFFER_COMPLETE) {
3442
+ DeleteRenderTarget(gl, target);
3443
+ throw new Error(`CreateRenderTarget: framebuffer incomplete (0x${status.toString(16)}); is this format renderable?`);
3444
+ }
3445
+ return target;
3446
+ }
3447
+ /**
3448
+ * Reallocates the target's color texture (and depth buffer) at a new size, discarding their contents. Does nothing if the size is unchanged.
3449
+ *
3450
+ * @category WebGL
3451
+ */
3452
+ function ResizeRenderTarget(gl, target, width, height) {
3453
+ if (target.width === width && target.height === height) return;
3454
+ target.width = width;
3455
+ target.height = height;
3456
+ UpdateTexture(gl, target.texture, {
3457
+ width,
3458
+ height
3459
+ });
3460
+ if (target.depth) {
3461
+ gl.bindRenderbuffer(gl.RENDERBUFFER, target.depth);
3462
+ gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH24_STENCIL8, width, height);
3463
+ gl.bindRenderbuffer(gl.RENDERBUFFER, null);
3464
+ }
3465
+ }
3466
+ /**
3467
+ * Draws into `target` (or the canvas, with null) and sets the viewport to match.
3468
+ *
3469
+ * @category WebGL
3470
+ */
3471
+ function BindRenderTarget(gl, target) {
3472
+ gl.bindFramebuffer(gl.FRAMEBUFFER, target?.framebuffer ?? null);
3473
+ gl.viewport(0, 0, target?.width ?? gl.drawingBufferWidth, target?.height ?? gl.drawingBufferHeight);
3474
+ }
3475
+ /**
3476
+ * Deletes the framebuffer, its color texture and its depth buffer.
3477
+ *
3478
+ * @category WebGL
3479
+ */
3480
+ function DeleteRenderTarget(gl, target) {
3481
+ gl.deleteFramebuffer(target.framebuffer);
3482
+ DeleteTexture(gl, target.texture);
3483
+ if (target.depth) gl.deleteRenderbuffer(target.depth);
3484
+ }
3485
+ /**
3486
+ * Draws a vertex array with a program; indexed and instanced draws are picked automatically.
3487
+ *
3488
+ * @category WebGL
3489
+ */
3490
+ function Draw(gl, info, vertexArray, options = {}) {
3491
+ const mode = options.mode ?? gl.TRIANGLES;
3492
+ const count = options.count ?? vertexArray.count;
3493
+ const offset = options.offset ?? 0;
3494
+ const instances = options.instances ?? 0;
3495
+ if (count === void 0) throw new Error("Draw: no count given and the vertex array has none");
3496
+ gl.useProgram(info.program);
3497
+ if (options.uniforms) SetUniforms(gl, info, options.uniforms);
3498
+ gl.bindVertexArray(vertexArray.vao);
3499
+ if (vertexArray.indexBuffer !== void 0) {
3500
+ const type = vertexArray.indexType ?? gl.UNSIGNED_SHORT;
3501
+ const byteOffset = offset * (type === gl.UNSIGNED_INT ? 4 : type === gl.UNSIGNED_BYTE ? 1 : 2);
3502
+ if (instances > 0) gl.drawElementsInstanced(mode, count, type, byteOffset, instances);
3503
+ else gl.drawElements(mode, count, type, byteOffset);
3504
+ } else if (instances > 0) gl.drawArraysInstanced(mode, offset, count, instances);
3505
+ else gl.drawArrays(mode, offset, count);
3506
+ gl.bindVertexArray(null);
3507
+ }
3508
+ //#endregion
3509
+ //#region src/webgl-renderer.ts
3510
+ /**
3511
+ * A thin owner of a WebGL2 context: sizing (CSS pixels x pixel ratio), clearing, render targets,
3512
+ * drawing, and context-loss notifications. Everything else is the webgl.ts wrappers on `gl`.
3513
+ * There is no render loop and no resource tracking: run your own loop (e.g. with Clock) and
3514
+ * delete what you create.
3515
+ *
3516
+ * ```ts
3517
+ * const renderer = new WebGlRenderer({ parent: document.body });
3518
+ * const program = renderer.createProgram(vertexSource, fragmentSource);
3519
+ * const quad = CreateVertexArray(renderer.gl, program, {
3520
+ * aPosition: { buffer: CreateBuffer(renderer.gl, [-1, -1, 1, -1, -1, 1, 1, 1]), size: 2 },
3521
+ * });
3522
+ *
3523
+ * new Clock().start((dt, time) => {
3524
+ * renderer.clear();
3525
+ * renderer.draw(program, quad, { mode: renderer.gl.TRIANGLE_STRIP, count: 4, uniforms: { uTime: time } });
3526
+ * });
3527
+ * ```
3528
+ *
3529
+ * @category WebGL
3530
+ */
3531
+ var WebGlRenderer = class {
3532
+ /** the WebGL2 context; use it with the {@link CreateBuffer}, {@link CreateTexture}, ... helpers */
3533
+ gl;
3534
+ /** drawing buffer pixels per CSS pixel; applied on the next `resize()` */
3535
+ pixelRatio;
3536
+ /**
3537
+ * The GPU context was lost (driver reset, too many contexts, ...): every program, buffer and
3538
+ * texture is gone. Stop drawing until onContextRestored, then recreate your resources.
3539
+ */
3540
+ onContextLost = new Observable();
3541
+ /** The GPU context is back after {@link WebGlRenderer.onContextLost}: recreate programs, buffers and textures. */
3542
+ onContextRestored = new Observable();
3543
+ _width = 0;
3544
+ _height = 0;
3545
+ _listeners = [];
3546
+ /** the canvas the context draws on */
3547
+ get canvas() {
3548
+ return this.gl.canvas;
3549
+ }
3550
+ /** Size in CSS pixels (the drawing buffer is this times `pixelRatio`). */
3551
+ get width() {
3552
+ return this._width;
3553
+ }
3554
+ /** Height in CSS pixels. */
3555
+ get height() {
3556
+ return this._height;
3557
+ }
3558
+ /** `width / height`, or 1 while the height is 0 */
3559
+ get aspectRatio() {
3560
+ return this._height > 0 ? this._width / this._height : 1;
3561
+ }
3562
+ /** whether the GPU context is currently lost (`draw()` does nothing meanwhile) */
3563
+ get isContextLost() {
3564
+ return this.gl.isContextLost();
3565
+ }
3566
+ /** Creates the context (throws without WebGL2), enables depth testing, and appends to `params.parent` if given. */
3567
+ constructor(params = {}) {
3568
+ this.gl = CreateWebGlContext(params.canvas, params.attributes);
3569
+ this.pixelRatio = params.pixelRatio ?? globalThis.devicePixelRatio ?? 1;
3570
+ this._width = this.canvas.width / this.pixelRatio;
3571
+ this._height = this.canvas.height / this.pixelRatio;
3572
+ this.gl.enable(this.gl.DEPTH_TEST);
3573
+ this._listen("webglcontextlost", (event) => {
3574
+ event.preventDefault();
3575
+ this.onContextLost.notify();
3576
+ });
3577
+ this._listen("webglcontextrestored", () => {
3578
+ this.gl.enable(this.gl.DEPTH_TEST);
3579
+ this.onContextRestored.notify();
3580
+ });
3581
+ if (params.parent) this.appendTo(params.parent);
3582
+ }
3583
+ /** Moves the canvas into `element` (or out of the page, without one) and resizes to fit. */
3584
+ appendTo(element) {
3585
+ this.canvas.remove();
3586
+ if (element) {
3587
+ element.appendChild(this.canvas);
3588
+ this.resize();
3589
+ }
3590
+ }
3591
+ /**
3592
+ * Sizes the canvas to `width` x `height` CSS pixels (default: its parent's size); the drawing
3593
+ * buffer gets the pixel ratio applied. Returns whether anything changed.
3594
+ */
3595
+ resize(width, height) {
3596
+ if (width === void 0 || height === void 0) {
3597
+ const rect = this.canvas.parentElement?.getBoundingClientRect() ?? this.canvas.getBoundingClientRect();
3598
+ width ??= rect.width;
3599
+ height ??= rect.height;
3600
+ }
3601
+ const changed = width !== this._width || height !== this._height;
3602
+ this._width = width;
3603
+ this._height = height;
3604
+ this.canvas.style.width = `${width}px`;
3605
+ this.canvas.style.height = `${height}px`;
3606
+ return ResizeWebGlContext(this.gl, width, height, this.pixelRatio) || changed;
3607
+ }
3608
+ /**
3609
+ * Clears the bound target to `color` (RGBA in 0..1, alpha default 1) and, with `depth`
3610
+ * (default true), also the depth and stencil buffers.
3611
+ */
3612
+ clear(color = [
3613
+ 0,
3614
+ 0,
3615
+ 0,
3616
+ 1
3617
+ ], depth = true) {
3618
+ const gl = this.gl;
3619
+ gl.clearColor(color[0], color[1], color[2], color[3] ?? 1);
3620
+ gl.clear(gl.COLOR_BUFFER_BIT | (depth ? gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT : 0));
3621
+ }
3622
+ /** Draws into `target`, or the canvas with null. */
3623
+ setRenderTarget(target) {
3624
+ BindRenderTarget(this.gl, target);
3625
+ }
3626
+ /** Compiles and links a program and collects its attributes and uniforms ({@link CreateProgramInfo}). Throws on errors. */
3627
+ createProgram(vertexShaderSource, fragmentShaderSource) {
3628
+ return CreateProgramInfo(this.gl, vertexShaderSource, fragmentShaderSource);
3629
+ }
3630
+ /** Draws with {@link Draw}; skipped while the context is lost. */
3631
+ draw(info, vertexArray, options) {
3632
+ if (this.isContextLost) return;
3633
+ Draw(this.gl, info, vertexArray, options);
3634
+ }
3635
+ /** Removes the renderer's event listeners. GPU resources you created are yours to delete. */
3636
+ dispose() {
3637
+ for (const [type, listener] of this._listeners) this.canvas.removeEventListener(type, listener);
3638
+ this._listeners.length = 0;
3639
+ }
3640
+ _listen(type, listener) {
3641
+ this.canvas.addEventListener(type, listener);
3642
+ this._listeners.push([type, listener]);
3643
+ }
3644
+ };
3645
+ //#endregion
3646
+ //#region src/worker-interface.ts
3647
+ /**
3648
+ * Thin wrapper around a module `Worker` that exposes its errors and messages as
3649
+ * {@link Observable}s.
3650
+ *
3651
+ * ```ts
3652
+ * const worker = new WorkerInterface<Result, Job>(new URL('./worker.ts', import.meta.url));
3653
+ * worker.onMessage.subscribe((event) => console.log(event.data));
3654
+ * worker.postMessage(job);
3655
+ * ```
3656
+ *
3657
+ * @typeParam TReceive data the worker posts back (the type of `onMessage` events' `data`)
3658
+ * @typeParam TSend data posted to the worker with `postMessage`
3659
+ * @category Utilities
3660
+ */
3661
+ var WorkerInterface = class {
3662
+ _worker;
3663
+ /** notified with the worker's `error` events */
3664
+ onError = new Observable();
3665
+ /** notified with every message the worker posts back */
3666
+ onMessage = new Observable();
3667
+ /** Starts a module worker (`{ type: 'module' }`) from `url`. */
3668
+ constructor(url) {
3669
+ this._worker = new Worker(url, { type: "module" });
3670
+ this._worker.onerror = (error) => this.onError.notify(error);
3671
+ this._worker.onmessage = (message) => this.onMessage.notify(message);
3672
+ }
3673
+ /** Sends `message` to the worker (structured-cloned; `options.transfer` lists objects to transfer). */
3674
+ postMessage(message, options) {
3675
+ this._worker.postMessage(message, options);
3676
+ }
3677
+ /** Stops the worker immediately. */
3678
+ terminate() {
3679
+ this._worker.terminate();
3680
+ }
3681
+ };
3682
+ //#endregion
3683
+ exports.ActionMap = ActionMap;
3684
+ exports.BindRenderTarget = BindRenderTarget;
3685
+ exports.CanvasRenderer = CanvasRenderer;
3686
+ exports.Clock = Clock;
3687
+ exports.Color = require_spatial_partition_3d.Color;
3688
+ exports.CompileShader = CompileShader;
3689
+ exports.CreateBuffer = CreateBuffer;
3690
+ exports.CreateProgram = CreateProgram;
3691
+ exports.CreateProgramInfo = CreateProgramInfo;
3692
+ exports.CreateRenderTarget = CreateRenderTarget;
3693
+ exports.CreateTexture = CreateTexture;
3694
+ exports.CreateVertexArray = CreateVertexArray;
3695
+ exports.CreateWebGlContext = CreateWebGlContext;
3696
+ exports.DEFAULT_COLOR = DEFAULT_COLOR;
3697
+ exports.DEFAULT_DEADZONE = DEFAULT_DEADZONE;
3698
+ exports.DEFAULT_FONT = DEFAULT_FONT;
3699
+ exports.DEFAULT_FONT_NAME = DEFAULT_FONT_NAME;
3700
+ exports.DEFAULT_FONT_SIZE = DEFAULT_FONT_SIZE;
3701
+ exports.DEFAULT_MAP_2D_VALUE = DEFAULT_MAP_2D_VALUE;
3702
+ exports.DEFAULT_MAP_3D_VALUE = require_spatial_partition_3d.DEFAULT_MAP_3D_VALUE;
3703
+ exports.DEFAULT_PIXEL_SIZE = DEFAULT_PIXEL_SIZE;
3704
+ exports.DEFAULT_TEXTALIGN = DEFAULT_TEXTALIGN;
3705
+ exports.DEFAULT_TEXTBASELINE = DEFAULT_TEXTBASELINE;
3706
+ exports.DEG2RAD = require_spatial_partition_3d.DEG2RAD;
3707
+ exports.DeleteProgramInfo = DeleteProgramInfo;
3708
+ exports.DeleteRenderTarget = DeleteRenderTarget;
3709
+ exports.DeleteTexture = DeleteTexture;
3710
+ exports.DeleteVertexArray = DeleteVertexArray;
3711
+ exports.Disposable = Disposable;
3712
+ exports.Draw = Draw;
3713
+ exports.E = require_spatial_partition_3d.E;
3714
+ exports.ECS = ECS;
3715
+ exports.EPSILON = require_spatial_partition_3d.EPSILON;
3716
+ exports.Emitter = Emitter;
3717
+ exports.EventQueue = EventQueue;
3718
+ exports.GAMEPAD_AXES = GAMEPAD_AXES;
3719
+ exports.GAMEPAD_BUTTONS = GAMEPAD_BUTTONS;
3720
+ exports.GESTURES = GESTURES;
3721
+ exports.GenerateDoors = GenerateDoors;
3722
+ exports.GenerateRooms = GenerateRooms;
3723
+ exports.GenerateWalls = GenerateWalls;
3724
+ exports.GestureRecognizer = GestureRecognizer;
3725
+ exports.GetProgramLocations = GetProgramLocations;
3726
+ exports.GetUrlParams = GetUrlParams;
3727
+ exports.HALF_PI = require_spatial_partition_3d.HALF_PI;
3728
+ exports.Input = Input;
3729
+ exports.LN10 = require_spatial_partition_3d.LN10;
3730
+ exports.LN2 = require_spatial_partition_3d.LN2;
3731
+ exports.LOG10E = require_spatial_partition_3d.LOG10E;
3732
+ exports.LOG2E = require_spatial_partition_3d.LOG2E;
3733
+ exports.LoadWebGlTexture = LoadWebGlTexture;
3734
+ exports.MAP_2D_MAX_COORD = MAP_2D_MAX_COORD;
3735
+ exports.MAP_2D_MIN_COORD = MAP_2D_MIN_COORD;
3736
+ exports.MAP_3D_MAX_COORD = require_spatial_partition_3d.MAP_3D_MAX_COORD;
3737
+ exports.MAP_3D_MIN_COORD = require_spatial_partition_3d.MAP_3D_MIN_COORD;
3738
+ exports.Map2D = Map2D;
3739
+ exports.Map3D = require_spatial_partition_3d.Map3D;
3740
+ exports.ONE_SECOND = ONE_SECOND;
3741
+ exports.Observable = Observable;
3742
+ exports.PI = require_spatial_partition_3d.PI;
3743
+ exports.ParticleRenderer = ParticleRenderer;
3744
+ exports.ParticleSystem2d = require_spatial_partition_3d.ParticleSystem2d;
3745
+ exports.QUARTER_PI = require_spatial_partition_3d.QUARTER_PI;
3746
+ exports.RAD2DEG = require_spatial_partition_3d.RAD2DEG;
3747
+ exports.Random = require_spatial_partition_3d.Random;
3748
+ exports.Rectangle = Rectangle;
3749
+ exports.ResizeRenderTarget = ResizeRenderTarget;
3750
+ exports.ResizeWebGlContext = ResizeWebGlContext;
3751
+ exports.Rng = require_spatial_partition_3d.Rng;
3752
+ exports.SQRT1_2 = require_spatial_partition_3d.SQRT1_2;
3753
+ exports.SQRT2 = require_spatial_partition_3d.SQRT2;
3754
+ exports.SetUniforms = SetUniforms;
3755
+ exports.ShaderType = ShaderType;
3756
+ exports.Signal = Signal;
3757
+ exports.SpatialPartition2d = require_spatial_partition_3d.SpatialPartition2d;
3758
+ exports.SpatialPartition3d = require_spatial_partition_3d.SpatialPartition3d;
3759
+ exports.TAU = require_spatial_partition_3d.TAU;
3760
+ exports.TILE_EMPTY = TILE_EMPTY;
3761
+ exports.TILE_FLOOR = TILE_FLOOR;
3762
+ exports.TILE_PATH = TILE_PATH;
3763
+ exports.Tilemap = Tilemap;
3764
+ exports.UpdateBuffer = UpdateBuffer;
3765
+ exports.UpdateTexture = UpdateTexture;
3766
+ exports.Vector = Vector;
3767
+ exports.WebGlRenderer = WebGlRenderer;
3768
+ exports.WorkerInterface = WorkerInterface;
3769
+ exports.XR_AXES = XR_AXES;
3770
+ exports.XR_BUTTONS = XR_BUTTONS;
3771
+ exports.bindingLabel = bindingLabel;
3772
+ exports.bindingsEqual = bindingsEqual;
3773
+ exports.buildColorPalette = buildColorPalette;
3774
+ exports.clamp = require_spatial_partition_3d.clamp;
3775
+ exports.controlId = controlId;
3776
+ exports.degrees = require_spatial_partition_3d.degrees;
3777
+ exports.distance2d = require_spatial_partition_3d.distance2d;
3778
+ exports.distance3d = require_spatial_partition_3d.distance3d;
3779
+ exports.ecs = ecs;
3780
+ exports.findPath = findPath;
3781
+ exports.fract = require_spatial_partition_3d.fract;
3782
+ exports.gesture = gesture;
3783
+ exports.getRedYellowGreenGradientHex = getRedYellowGreenGradientHex;
3784
+ exports.hash32 = require_spatial_partition_3d.hash32;
3785
+ exports.hash32mix = require_spatial_partition_3d.hash32mix;
3786
+ exports.inverseLerp = require_spatial_partition_3d.inverseLerp;
3787
+ exports.isNullOrUndefined = isNullOrUndefined;
3788
+ exports.isPositiveString = isPositiveString;
3789
+ exports.k2xy = k2xy;
3790
+ exports.k2xyz = k2xyz;
3791
+ exports.key = key;
3792
+ exports.lerp = require_spatial_partition_3d.lerp;
3793
+ exports.log = require_spatial_partition_3d.log;
3794
+ exports.manhattanDistance = require_spatial_partition_3d.manhattanDistance;
3795
+ exports.mod = require_spatial_partition_3d.mod;
3796
+ exports.mouse = mouse;
3797
+ exports.nearlyEqual = require_spatial_partition_3d.nearlyEqual;
3798
+ exports.normalizeRadians = require_spatial_partition_3d.normalizeRadians;
3799
+ exports.pad = pad;
3800
+ exports.padAxis = padAxis;
3801
+ exports.radians = require_spatial_partition_3d.radians;
3802
+ exports.randomMatrix = require_spatial_partition_3d.randomMatrix;
3803
+ exports.rng = require_spatial_partition_3d.rng;
3804
+ exports.roundTo = require_spatial_partition_3d.roundTo;
3805
+ exports.saturate = require_spatial_partition_3d.saturate;
3806
+ exports.smoothstep = require_spatial_partition_3d.smoothstep;
3807
+ exports.squaredDistance = require_spatial_partition_3d.squaredDistance;
3808
+ exports.wheel = wheel;
3809
+ exports.wrap = require_spatial_partition_3d.wrap;
3810
+ exports.xr = xr;
3811
+ exports.xrAxis = xrAxis;
3812
+ exports.xy2k = xy2k;
3813
+ exports.xyz2k = xyz2k;