@n3rdw1z4rd/core 0.18.5 → 0.19.1

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