@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.mjs DELETED
@@ -1,3977 +0,0 @@
1
- var __create = Object.create;
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __getProtoOf = Object.getPrototypeOf;
6
- var __hasOwnProp = Object.prototype.hasOwnProperty;
7
- var __esm = (fn, res) => function __init() {
8
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
- };
10
- var __commonJS = (cb, mod2) => function __require() {
11
- return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
12
- };
13
- var __export = (target, all) => {
14
- for (var name in all)
15
- __defProp(target, name, { get: all[name], enumerable: true });
16
- };
17
- var __copyProps = (to, from, except, desc) => {
18
- if (from && typeof from === "object" || typeof from === "function") {
19
- for (let key of __getOwnPropNames(from))
20
- if (!__hasOwnProp.call(to, key) && key !== except)
21
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
22
- }
23
- return to;
24
- };
25
- var __reExport = (target, mod2, secondTarget) => (__copyProps(target, mod2, "default"), secondTarget && __copyProps(secondTarget, mod2, "default"));
26
- var __toESM = (mod2, isNodeMode, target) => (target = mod2 != null ? __create(__getProtoOf(mod2)) : {}, __copyProps(
27
- // If the importer is in node compatibility mode or this is not an ESM
28
- // file that has been converted to a CommonJS file using a Babel-
29
- // compatible transform (i.e. "__esModule" has not been set), then set
30
- // "default" to the CommonJS "module.exports" for node compatibility.
31
- isNodeMode || !mod2 || !mod2.__esModule ? __defProp(target, "default", { value: mod2, enumerable: true }) : target,
32
- mod2
33
- ));
34
-
35
- // src/css/main.css
36
- var init_main = __esm({
37
- "src/css/main.css"() {
38
- }
39
- });
40
-
41
- // src/css/index.ts
42
- var require_css = __commonJS({
43
- "src/css/index.ts"() {
44
- "use strict";
45
- init_main();
46
- }
47
- });
48
-
49
- // src/index.ts
50
- var index_exports = {};
51
- __export(index_exports, {
52
- AStar: () => AStar,
53
- AddThreeComponent: () => AddThreeComponent,
54
- AsteroidMesh: () => AsteroidMesh,
55
- AtlasTextureMaterial: () => AtlasTextureMaterial,
56
- BuildDefaultPalette: () => BuildDefaultPalette,
57
- BuildVoxelGeometry: () => BuildVoxelGeometry,
58
- CameraRig: () => CameraRig,
59
- CanvasRenderer: () => CanvasRenderer,
60
- Clock: () => Clock,
61
- Color: () => Color,
62
- Colors: () => Colors2,
63
- CompileShader: () => CompileShader,
64
- CreatePaletteController: () => CreatePaletteController,
65
- CreateProgram: () => CreateProgram,
66
- CreateProgramInfo: () => CreateProgramInfo,
67
- CreateStarfield: () => CreateStarfield,
68
- CreateSubTexture: () => CreateSubTexture,
69
- CreateSystemStar: () => CreateSystemStar,
70
- CreateThreeEntity: () => CreateThreeEntity,
71
- CreateWebGlContext: () => CreateWebGlContext,
72
- CubeSphereGeometry: () => CubeSphereGeometry,
73
- DEFAULT_COLOR: () => DEFAULT_COLOR,
74
- DEFAULT_FONT: () => DEFAULT_FONT,
75
- DEFAULT_FONT_NAME: () => DEFAULT_FONT_NAME,
76
- DEFAULT_FONT_SIZE: () => DEFAULT_FONT_SIZE,
77
- DEFAULT_MAP_2D_VALUE: () => DEFAULT_MAP_2D_VALUE,
78
- DEFAULT_MAP_3D_VALUE: () => DEFAULT_MAP_3D_VALUE,
79
- DEFAULT_PIXEL_SIZE: () => DEFAULT_PIXEL_SIZE,
80
- DEFAULT_TEXTALIGN: () => DEFAULT_TEXTALIGN,
81
- DEFAULT_TEXTBASELINE: () => DEFAULT_TEXTBASELINE,
82
- DEG2RAD: () => DEG2RAD,
83
- Disposable: () => Disposable,
84
- E: () => E,
85
- ECS: () => ECS,
86
- EPSILON: () => EPSILON,
87
- Emitter: () => Emitter,
88
- EventQueue: () => EventQueue,
89
- GenerateDoors: () => GenerateDoors,
90
- GenerateEntityId: () => GenerateEntityId,
91
- GenerateRooms: () => GenerateRooms,
92
- GenerateWalls: () => GenerateWalls,
93
- GetProgramLocations: () => GetProgramLocations,
94
- GetThreeComponent: () => GetThreeComponent,
95
- GetUrlParams: () => GetUrlParams,
96
- HALF_PI: () => HALF_PI,
97
- Input: () => Input,
98
- IsThreeEntity: () => IsThreeEntity,
99
- LN10: () => LN10,
100
- LN2: () => LN2,
101
- LOG10E: () => LOG10E,
102
- LOG2E: () => LOG2E,
103
- LoadTexture: () => LoadTexture,
104
- Map2D: () => Map2D,
105
- Map3D: () => Map3D,
106
- Noise: () => Noise,
107
- ONE_SECOND: () => ONE_SECOND,
108
- Observable: () => Observable,
109
- PI: () => PI,
110
- ParticleRenderer: () => ParticleRenderer,
111
- ParticleSystem2d: () => ParticleSystem2d,
112
- ParticleSystem3d: () => ParticleSystem3d,
113
- PoissonDiskSampler: () => PoissonDiskSampler,
114
- QUARTER_PI: () => QUARTER_PI,
115
- RAD2DEG: () => RAD2DEG,
116
- Random: () => Random,
117
- Rectangle: () => Rectangle,
118
- RemoveThreeComponent: () => RemoveThreeComponent,
119
- Renderer: () => Renderer,
120
- ResizeWebGlContext: () => ResizeWebGlContext,
121
- Rng: () => Rng,
122
- SQRT1_2: () => SQRT1_2,
123
- SQRT2: () => SQRT2,
124
- ShaderType: () => ShaderType,
125
- Signal: () => Signal,
126
- SimplexNoise: () => SimplexNoise,
127
- SpatialPartition2d: () => SpatialPartition2d,
128
- SpatialPartition3d: () => SpatialPartition3d,
129
- TAU: () => TAU,
130
- TILE_EMPTY: () => TILE_EMPTY,
131
- TILE_FLOOR: () => TILE_FLOOR,
132
- TILE_PATH: () => TILE_PATH,
133
- TextureAtlas: () => TextureAtlas,
134
- ThreeJsCameraRig: () => ThreeJsCameraRig,
135
- ThreeJsPlayerController: () => ThreeJsPlayerController,
136
- Tilemap: () => Tilemap,
137
- VOXEL_FACES: () => VOXEL_FACES,
138
- Vector: () => Vector,
139
- VoxelFaces: () => VoxelFaces,
140
- VoxelGeometry: () => VoxelGeometry,
141
- VoxelMesh: () => VoxelMesh,
142
- WebGlRenderer: () => WebGlRenderer,
143
- WorkerInterface: () => WorkerInterface,
144
- buildColorPalette: () => buildColorPalette,
145
- clamp: () => clamp,
146
- degrees: () => degrees,
147
- distance2d: () => distance2d,
148
- distance3d: () => distance3d,
149
- fract: () => fract,
150
- getRedYellowGreenGradientHex: () => getRedYellowGreenGradientHex,
151
- hash32: () => hash32,
152
- hash32mix: () => hash32mix,
153
- inverseLerp: () => inverseLerp,
154
- isNullOrUndefined: () => isNullOrUndefined,
155
- isPositiveString: () => isPositiveString,
156
- k2xy: () => k2xy,
157
- k2xyz: () => k2xyz,
158
- lerp: () => lerp,
159
- log: () => log,
160
- manhattanDistance: () => manhattanDistance,
161
- mod: () => mod,
162
- nearlyEqual: () => nearlyEqual,
163
- normalizeRadians: () => normalizeRadians,
164
- radians: () => radians,
165
- randomMatrix: () => randomMatrix,
166
- rng: () => rng,
167
- roundTo: () => roundTo,
168
- saturate: () => saturate,
169
- smoothstep: () => smoothstep,
170
- squaredDistance: () => squaredDistance,
171
- wrap: () => wrap,
172
- xy2k: () => xy2k,
173
- xyz2k: () => xyz2k
174
- });
175
-
176
- // src/astar.ts
177
- var DIRECTIONS_4_WAY = [
178
- { x: 0, y: -1 },
179
- { x: 1, y: 0 },
180
- { x: 0, y: 1 },
181
- { x: -1, y: 0 }
182
- ];
183
- var AStar = class {
184
- map;
185
- constructor(map) {
186
- this.map = map;
187
- }
188
- _manhattan(a, b) {
189
- return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
190
- }
191
- _isWalkable(point, walkable = [0]) {
192
- const value = this.map.get(point.x, point.y);
193
- return walkable.includes(value);
194
- }
195
- _key(x, y) {
196
- return `${x},${y}`;
197
- }
198
- findPath(a, b, params = {}) {
199
- const walkable = params.walkableValues ?? [0];
200
- const openSet = [];
201
- const closedSet = /* @__PURE__ */ new Set();
202
- const nodeMap = /* @__PURE__ */ new Map();
203
- const startNode = {
204
- pos: a,
205
- g: 0,
206
- h: this._manhattan(a, b),
207
- f: this._manhattan(a, b)
208
- };
209
- openSet.push(startNode);
210
- nodeMap.set(this._key(a.x, a.y), startNode);
211
- const targetKeys = /* @__PURE__ */ new Set();
212
- targetKeys.add(this._key(b.x, b.y));
213
- for (const dir of DIRECTIONS_4_WAY) {
214
- const nx = b.x + dir.x;
215
- const ny = b.y + dir.y;
216
- targetKeys.add(this._key(nx, ny));
217
- }
218
- while (openSet.length > 0) {
219
- openSet.sort((a2, b2) => a2.f - b2.f);
220
- const current = openSet.shift();
221
- const currentKey = this._key(current.pos.x, current.pos.y);
222
- if (targetKeys.has(currentKey)) {
223
- const path = [];
224
- let curr = current;
225
- while (curr) {
226
- path.push(curr.pos);
227
- curr = curr.parent;
228
- }
229
- path.pop();
230
- return path.reverse();
231
- }
232
- closedSet.add(currentKey);
233
- for (const dir of DIRECTIONS_4_WAY) {
234
- const neighborPos = {
235
- x: current.pos.x + dir.x,
236
- y: current.pos.y + dir.y
237
- };
238
- const key = this._key(neighborPos.x, neighborPos.y);
239
- if (!this._isWalkable(neighborPos, walkable) || closedSet.has(key)) {
240
- continue;
241
- }
242
- const g = current.g + 1;
243
- let neighbor = nodeMap.get(key);
244
- if (!neighbor) {
245
- neighbor = {
246
- pos: neighborPos,
247
- g,
248
- h: this._manhattan(neighborPos, b),
249
- f: g + this._manhattan(neighborPos, b),
250
- parent: current
251
- };
252
- nodeMap.set(key, neighbor);
253
- openSet.push(neighbor);
254
- } else if (g < neighbor.g) {
255
- neighbor.g = g;
256
- neighbor.f = g + neighbor.h;
257
- neighbor.parent = current;
258
- }
259
- }
260
- }
261
- return [];
262
- }
263
- };
264
-
265
- // src/math.ts
266
- var PI = Math.PI;
267
- var TAU = Math.PI * 2;
268
- var HALF_PI = Math.PI / 2;
269
- var QUARTER_PI = Math.PI / 4;
270
- var E = Math.E;
271
- var DEG2RAD = PI / 180;
272
- var RAD2DEG = 180 / PI;
273
- var LN2 = Math.LN2;
274
- var LN10 = Math.LN10;
275
- var LOG2E = Math.LOG2E;
276
- var LOG10E = Math.LOG10E;
277
- var SQRT2 = Math.SQRT2;
278
- var SQRT1_2 = Math.SQRT1_2;
279
- var EPSILON = Number.EPSILON;
280
- var clamp = (value, minValue, maxValue) => Math.min(Math.max(value, minValue), maxValue);
281
- var saturate = (value) => clamp(value, 0, 1);
282
- var lerp = (start, end, t) => start + (end - start) * t;
283
- var inverseLerp = (start, end, value) => (value - start) / (end - start);
284
- var smoothstep = (edge0, edge1, value) => {
285
- const t = saturate((value - edge0) / (edge1 - edge0));
286
- return t * t * (3 - 2 * t);
287
- };
288
- var fract = (value) => value - Math.floor(value);
289
- var mod = (value, divisor) => (value % divisor + divisor) % divisor;
290
- var wrap = (value, minValue, maxValue) => {
291
- const range = maxValue - minValue;
292
- return minValue + mod(value - minValue, range);
293
- };
294
- var radians = (degrees2) => degrees2 * DEG2RAD;
295
- var degrees = (radians2) => radians2 * RAD2DEG;
296
- var normalizeRadians = (radians2) => wrap(radians2, -PI, PI);
297
- var distance2d = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);
298
- var distance3d = (x1, y1, z1, x2, y2, z2) => Math.hypot(x2 - x1, y2 - y1, z2 - z1);
299
- var squaredDistance = (x1, y1, x2, y2) => {
300
- const dx = x2 - x1;
301
- const dy = y2 - y1;
302
- return dx * dx + dy * dy;
303
- };
304
- var manhattanDistance = (x1, y1, x2, y2) => Math.abs(x2 - x1) + Math.abs(y2 - y1);
305
- var nearlyEqual = (a, b, epsilon = EPSILON) => Math.abs(a - b) <= epsilon;
306
- var roundTo = (value, digits = 0) => {
307
- const factor = 10 ** digits;
308
- return Math.round(value * factor) / factor;
309
- };
310
- var hash32 = (n) => {
311
- n |= 0;
312
- n ^= n >>> 16;
313
- n = Math.imul(n, 2246822507);
314
- n ^= n >>> 13;
315
- n = Math.imul(n, 3266489909);
316
- n ^= n >>> 16;
317
- return n >>> 0;
318
- };
319
- var hash32mix = (...values) => {
320
- let n = 0;
321
- for (const value of values) {
322
- n ^= value | 0;
323
- n = hash32(n);
324
- }
325
- return n;
326
- };
327
-
328
- // src/canvas-renderer.ts
329
- var DEFAULT_COLOR = "white";
330
- var DEFAULT_PIXEL_SIZE = 1;
331
- var DEFAULT_FONT_SIZE = 14;
332
- var DEFAULT_FONT_NAME = "monospace";
333
- var DEFAULT_FONT = `${DEFAULT_FONT_SIZE}px ${DEFAULT_FONT_NAME}`;
334
- var DEFAULT_TEXTALIGN = "left";
335
- var DEFAULT_TEXTBASELINE = "alphabetic";
336
- var CanvasRenderer = class {
337
- context;
338
- get canvas() {
339
- return this.context.canvas;
340
- }
341
- get width() {
342
- return this.canvas.width;
343
- }
344
- get height() {
345
- return this.canvas.height;
346
- }
347
- constructor(canvas) {
348
- this.context = (canvas ?? document.createElement("canvas")).getContext("2d");
349
- this.context.font = DEFAULT_FONT;
350
- this.context.textAlign = DEFAULT_TEXTALIGN;
351
- this.context.textBaseline = DEFAULT_TEXTBASELINE;
352
- }
353
- resize(width, height) {
354
- let resized = false;
355
- width = width ?? this.canvas.parentElement?.clientWidth ?? this.width;
356
- height = height ?? this.canvas.parentElement?.clientHeight ?? this.height;
357
- if (this.canvas.width != width || this.canvas.height != height) {
358
- this.canvas.width = width;
359
- this.canvas.height = height;
360
- resized = true;
361
- }
362
- return resized;
363
- }
364
- clear() {
365
- this.context.clearRect(0, 0, this.width, this.height);
366
- }
367
- drawPath(buildPath, params = {}) {
368
- this.context.fillStyle = params.color ?? DEFAULT_COLOR;
369
- this.context.strokeStyle = params.color ?? DEFAULT_COLOR;
370
- this.context.lineWidth = params.size ?? 1;
371
- if (params.lineDash) {
372
- this.context.setLineDash(params.lineDash);
373
- }
374
- this.context.beginPath();
375
- buildPath();
376
- this.context.stroke();
377
- if (params.filled) {
378
- this.context.fill();
379
- }
380
- if (params.lineDash) {
381
- this.context.setLineDash([]);
382
- }
383
- }
384
- drawRect(x, y, width, height, params = {}) {
385
- x -= width / 2;
386
- y -= height / 2;
387
- this.context.fillStyle = params.color ?? DEFAULT_COLOR;
388
- this.context.strokeStyle = params.color ?? DEFAULT_COLOR;
389
- this.context.lineWidth = params.size ?? 1;
390
- if (params.lineDash) {
391
- this.context.setLineDash(params.lineDash);
392
- }
393
- this.context.beginPath();
394
- this.context.strokeRect(x, y, width, height);
395
- if (params.filled) {
396
- this.context.fillRect(x, y, width, height);
397
- }
398
- if (params.lineDash) {
399
- this.context.setLineDash([]);
400
- }
401
- }
402
- drawPixel(x, y, params = {}) {
403
- const size = Math.abs(params.size || DEFAULT_PIXEL_SIZE);
404
- this.drawRect(x, y, size, size, {
405
- ...params,
406
- filled: true
407
- });
408
- }
409
- drawLine(x1, y1, x2, y2, params = {}) {
410
- this.context.strokeStyle = params.color ?? DEFAULT_COLOR;
411
- this.context.lineWidth = params.size ?? 1;
412
- if (params.lineDash) {
413
- this.context.setLineDash(params.lineDash);
414
- }
415
- this.context.beginPath();
416
- this.context.moveTo(x1, y1);
417
- this.context.lineTo(x2, y2);
418
- this.context.stroke();
419
- if (params.lineDash) {
420
- this.context.setLineDash([]);
421
- }
422
- }
423
- drawCircle(x, y, radius, params = {}) {
424
- this.drawPath(() => {
425
- this.context.arc(x, y, radius, 0, TAU);
426
- }, params);
427
- }
428
- drawPolygon(x, y, radius, sides, params = {}) {
429
- sides = Math.floor(clamp(sides, 3, 36));
430
- this.drawPath(() => {
431
- for (let i = 0; i < sides; i++) {
432
- const angle = i / sides * TAU - PI / 2;
433
- const px = x + Math.cos(angle) * radius;
434
- const py = y + Math.sin(angle) * radius;
435
- if (i === 0) {
436
- this.context.moveTo(px, py);
437
- } else {
438
- this.context.lineTo(px, py);
439
- }
440
- }
441
- this.context.closePath();
442
- }, params);
443
- }
444
- drawText(x, y, text, params = {}) {
445
- this.context.font = params.font ?? `${params.size ?? DEFAULT_FONT_SIZE}px ${params.fontName ?? DEFAULT_FONT_NAME}`;
446
- this.context.textAlign = params.textAlign ?? DEFAULT_TEXTALIGN;
447
- this.context.textBaseline = params.textBaseline ?? DEFAULT_TEXTBASELINE;
448
- this.context.fillStyle = params.color ?? DEFAULT_COLOR;
449
- this.context.fillText(text, x, y);
450
- }
451
- drawSprite(x, y, image, width, height, params = {}) {
452
- x -= width / 2;
453
- y -= height / 2;
454
- if (params.sourceWidth !== void 0 && params.sourceHeight !== void 0) {
455
- this.context.drawImage(
456
- image,
457
- params.sourceX ?? 0,
458
- params.sourceY ?? 0,
459
- params.sourceWidth,
460
- params.sourceHeight,
461
- x,
462
- y,
463
- width,
464
- height
465
- );
466
- } else {
467
- this.context.drawImage(image, x, y, width, height);
468
- }
469
- }
470
- };
471
-
472
- // src/observable.ts
473
- var Observable = class {
474
- observers = /* @__PURE__ */ new Set();
475
- subscribe(observer) {
476
- this.observers.add(observer);
477
- return () => this.observers.delete(observer);
478
- }
479
- once(observer, ...args) {
480
- const unsubscribe = this.subscribe((value) => {
481
- unsubscribe();
482
- observer(value, ...args);
483
- });
484
- return unsubscribe;
485
- }
486
- notify(value, ...args) {
487
- for (const observer of [...this.observers]) {
488
- observer(value, ...args);
489
- }
490
- }
491
- clear() {
492
- this.observers.clear();
493
- }
494
- get size() {
495
- return this.observers.size;
496
- }
497
- };
498
-
499
- // src/clock.ts
500
- var ONE_SECOND = 1e3;
501
- var Clock = class {
502
- _fps = 0;
503
- _frameCount = 0;
504
- _frameTime = 0;
505
- _isRunning = false;
506
- _lastTime = 0;
507
- onFpsUpdate = new Observable();
508
- onFrame = new Observable();
509
- startTime = performance.now();
510
- get elapsedTime() {
511
- return performance.now() - this.startTime;
512
- }
513
- get fps() {
514
- return this._fps;
515
- }
516
- get isRunning() {
517
- return this._isRunning;
518
- }
519
- update(time) {
520
- const deltaTime = (time - this._lastTime) / ONE_SECOND;
521
- this._lastTime = time;
522
- if (this._frameTime + ONE_SECOND >= time) {
523
- this._frameCount++;
524
- } else {
525
- this._frameTime = time;
526
- this._fps = this._frameCount;
527
- this._frameCount = 0;
528
- this.onFpsUpdate.notify(this.fps);
529
- }
530
- return deltaTime;
531
- }
532
- start() {
533
- if (!this._isRunning) {
534
- const animate = (time) => {
535
- this.onFrame.notify(this.update(time));
536
- if (this._isRunning)
537
- requestAnimationFrame(animate);
538
- };
539
- this._isRunning = true;
540
- requestAnimationFrame(animate);
541
- }
542
- }
543
- stop() {
544
- this._isRunning = false;
545
- }
546
- };
547
-
548
- // src/color-palette.ts
549
- var DEFAULT_COLORS = [
550
- [237, 28, 36],
551
- // red
552
- [255, 127, 39],
553
- // orange
554
- [255, 242, 0],
555
- // yellow
556
- [34, 177, 76],
557
- // green
558
- [0, 183, 239],
559
- // cyan
560
- [63, 72, 204],
561
- // blue
562
- [163, 73, 164],
563
- // purple
564
- [236, 0, 140],
565
- // magenta
566
- [255, 174, 201],
567
- // pink
568
- [139, 90, 43],
569
- // brown
570
- [214, 181, 129],
571
- // tan
572
- [128, 128, 0],
573
- // olive
574
- [0, 128, 128],
575
- // teal
576
- [128, 0, 32]
577
- // maroon
578
- ];
579
- function packRGB(r, g, b) {
580
- r = Math.min(255, Math.max(0, Math.round(r)));
581
- g = Math.min(255, Math.max(0, Math.round(g)));
582
- b = Math.min(255, Math.max(0, Math.round(b)));
583
- return r << 16 | g << 8 | b;
584
- }
585
- var DARK_FLOOR = 0.28;
586
- function colorRamp(rgb, steps) {
587
- const [r, g, b] = rgb;
588
- const out = [];
589
- for (let i = 0; i < steps; i++) {
590
- const t = steps === 1 ? 0 : i / (steps - 1);
591
- const scale = 1 - t * (1 - DARK_FLOOR);
592
- out.push(packRGB(r * scale, g * scale, b * scale));
593
- }
594
- return out;
595
- }
596
- function buildColorPalette(grayscaleSteps = 8, colorSteps = 4, ...colors2) {
597
- const palette = [];
598
- for (let i = 0; i < grayscaleSteps; i++) {
599
- const v = grayscaleSteps === 1 ? 0 : i / (grayscaleSteps - 1) * 255;
600
- palette.push(packRGB(v, v, v));
601
- }
602
- const colorList = colors2.length > 0 ? colors2 : DEFAULT_COLORS;
603
- for (const rgb of colorList) {
604
- palette.push(...colorRamp(rgb, colorSteps));
605
- }
606
- return palette;
607
- }
608
-
609
- // src/log.ts
610
- var log = console.debug.bind(
611
- console,
612
- "%c[dev]",
613
- "font-weight: bold; color: #888;"
614
- );
615
-
616
- // src/color.ts
617
- var Color = class _Color {
618
- _hex = "#ffffffff";
619
- _r = 255;
620
- _g = 255;
621
- _b = 255;
622
- _a = 255;
623
- get r() {
624
- return this._r;
625
- }
626
- set r(value) {
627
- this._r = clamp(value, 0, 255);
628
- this._hex = this._to_hex();
629
- }
630
- get g() {
631
- return this._g;
632
- }
633
- set g(value) {
634
- this._g = clamp(value, 0, 255);
635
- this._hex = this._to_hex();
636
- }
637
- get b() {
638
- return this._b;
639
- }
640
- set b(value) {
641
- this._b = clamp(value, 0, 255);
642
- this._hex = this._to_hex();
643
- }
644
- get a() {
645
- return this._a;
646
- }
647
- set a(value) {
648
- this._a = clamp(value, 0, 255);
649
- this._hex = this._to_hex();
650
- }
651
- get hexStr() {
652
- return this._hex;
653
- }
654
- set hexStr(value) {
655
- if (value.startsWith("#")) {
656
- [this._r, this._g, this._b, this._a] = this._parse_hex_color_string(value);
657
- this._hex = value;
658
- } else {
659
- log(`Color: invalid color string: ${value}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Keeping the current color.`);
660
- }
661
- }
662
- get rgba() {
663
- return [this._r, this._g, this._b, this._a];
664
- }
665
- constructor(r = 255, g = 255, b = 255, a = 255) {
666
- if (typeof r === "string") {
667
- if (r.startsWith("#")) {
668
- [r, g, b, a] = this._parse_hex_color_string(r);
669
- } else {
670
- log(`Color: invalid color string: ${r}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Defaulting to opaque white.`);
671
- r = g = b = a = 255;
672
- }
673
- } else {
674
- [r, g, b, a] = [r, g, b, a].map((n) => _Color._normalize(n));
675
- }
676
- this.r = r;
677
- this.g = g;
678
- this.b = b;
679
- this.a = a;
680
- }
681
- static _normalize(value) {
682
- return clamp(0 | (value > 0 && value < 1 ? value * 255 : value), 0, 255);
683
- }
684
- _to_hex() {
685
- return `#${this.r.toString(16).padStart(2, "0")}${this.g.toString(16).padStart(2, "0")}${this.b.toString(16).padStart(2, "0")}${this.a.toString(16).padStart(2, "0")}`;
686
- }
687
- _parse_hex_color_string(hex) {
688
- const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex);
689
- return result ? [
690
- parseInt(result[1], 16),
691
- parseInt(result[2], 16),
692
- parseInt(result[3], 16),
693
- result[4] ? parseInt(result[4], 16) : 255
694
- ] : [255, 255, 255, 255];
695
- }
696
- static fromHsv(h, s, v, a = 255) {
697
- let r = 0;
698
- let g = 0;
699
- let b = 0;
700
- let i = Math.floor(h * 6);
701
- let f = h * 6 - i;
702
- let p = v * (1 - s);
703
- let q = v * (1 - f * s);
704
- let t = v * (1 - (1 - f) * s);
705
- switch (i % 6) {
706
- case 0:
707
- r = v, g = t, b = p;
708
- break;
709
- case 1:
710
- r = q, g = v, b = p;
711
- break;
712
- case 2:
713
- r = p, g = v, b = t;
714
- break;
715
- case 3:
716
- r = p, g = q, b = v;
717
- break;
718
- case 4:
719
- r = t, g = p, b = v;
720
- break;
721
- case 5:
722
- r = v, g = p, b = q;
723
- break;
724
- }
725
- return new _Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
726
- }
727
- static get BLACK() {
728
- return new _Color(0, 0, 0, 255);
729
- }
730
- static get GRAY() {
731
- return new _Color(128, 128, 128, 255);
732
- }
733
- static get WHITE() {
734
- return new _Color(255, 255, 255, 255);
735
- }
736
- static get RED() {
737
- return new _Color(255, 0, 0, 255);
738
- }
739
- static get GREEN() {
740
- return new _Color(0, 255, 0, 255);
741
- }
742
- static get BLUE() {
743
- return new _Color(0, 0, 255, 255);
744
- }
745
- static get YELLOW() {
746
- return new _Color(255, 255, 0, 255);
747
- }
748
- static get ORANGE() {
749
- return new _Color(255, 128, 0, 255);
750
- }
751
- static get PURPLE() {
752
- return new _Color(128, 0, 128, 255);
753
- }
754
- static get CYAN() {
755
- return new _Color(0, 255, 255, 255);
756
- }
757
- static get MAGENTA() {
758
- return new _Color(255, 0, 255, 255);
759
- }
760
- static fromName(name) {
761
- const element = document.createElement("div");
762
- element.style.color = name;
763
- document.body.appendChild(element);
764
- const computedColor = getComputedStyle(element).color;
765
- document.body.removeChild(element);
766
- const rgba = computedColor.match(/\d+/g);
767
- if (rgba && rgba.length === 4) {
768
- const [r, g, b, a] = rgba.map(Number);
769
- return new _Color(r, g, b, a);
770
- } else {
771
- log(`Color: invalid CSS color name: ${name}. Defaulting to transparent.`);
772
- return _Color.TRANSPARENT;
773
- }
774
- }
775
- static get TRANSPARENT() {
776
- return new _Color(0, 0, 0, 0);
777
- }
778
- };
779
-
780
- // src/index.ts
781
- __reExport(index_exports, __toESM(require_css()));
782
-
783
- // src/disposable.ts
784
- var Disposable = class {
785
- disposers = [];
786
- add(disposer) {
787
- this.disposers.push(disposer);
788
- }
789
- dispose() {
790
- while (this.disposers.length) {
791
- this.disposers.pop()?.();
792
- }
793
- }
794
- };
795
-
796
- // src/dungeon-generator.ts
797
- import { Heap } from "heap-js";
798
-
799
- // src/map2d.ts
800
- var DEFAULT_MAP_2D_VALUE = -1;
801
- var BASE_2D = 2097152;
802
- var OFFSET_2D = 1048576;
803
- var Map2D = class {
804
- defaultValue;
805
- _data;
806
- get data() {
807
- return this._data;
808
- }
809
- get size() {
810
- return this._data.size;
811
- }
812
- constructor(defaultValue = DEFAULT_MAP_2D_VALUE, mapData) {
813
- this.defaultValue = defaultValue;
814
- this._data = mapData ?? /* @__PURE__ */ new Map();
815
- }
816
- _floor(x, y) {
817
- return [Math.floor(x), Math.floor(y)];
818
- }
819
- _key(x, y) {
820
- const X = x + OFFSET_2D & BASE_2D - 1;
821
- const Y = y + OFFSET_2D & BASE_2D - 1;
822
- return X * BASE_2D + Y;
823
- }
824
- _pos(key) {
825
- const Y = key % BASE_2D;
826
- const X = Math.floor(key / BASE_2D);
827
- return [X - OFFSET_2D, Y - OFFSET_2D];
828
- }
829
- clear() {
830
- this._data.clear();
831
- }
832
- get(x, y, defaultValue = this.defaultValue) {
833
- [x, y] = this._floor(x, y);
834
- return this._data.get(this._key(x, y)) ?? defaultValue;
835
- }
836
- set(x, y, value = this.defaultValue) {
837
- [x, y] = this._floor(x, y);
838
- const key = this._key(x, y);
839
- if (value === this.defaultValue) {
840
- this._data.delete(key);
841
- } else {
842
- this._data.set(key, value);
843
- }
844
- }
845
- forEach(callback) {
846
- let i = 0;
847
- this._data.forEach((v, key) => {
848
- const [x, y] = this._pos(key);
849
- callback(x, y, v, i++);
850
- });
851
- }
852
- forEachInArea(x1, y1, x2, y2, callback) {
853
- this.forEach((x, y, n) => {
854
- if (x >= x1 && x < x2 && y >= y1 && y < y2) {
855
- callback(x, y, n);
856
- }
857
- });
858
- }
859
- };
860
-
861
- // src/random.ts
862
- var Random = class _Random {
863
- _seed;
864
- constructor(seed = Date.now()) {
865
- this._seed = seed | 0;
866
- }
867
- get seed() {
868
- return this._seed;
869
- }
870
- set seed(value) {
871
- this._seed = value | 0;
872
- }
873
- static hash(...values) {
874
- return hash32mix(...values);
875
- }
876
- static uint(...values) {
877
- return hash32mix(...values);
878
- }
879
- static float(...values) {
880
- return hash32mix(...values) / 4294967296;
881
- }
882
- static bool(...values) {
883
- return (hash32mix(...values) & 1) !== 0;
884
- }
885
- static sign(...values) {
886
- return this.bool(...values) ? 1 : -1;
887
- }
888
- static angle(...values) {
889
- return this.float(...values) * TAU;
890
- }
891
- uint() {
892
- return _Random.uint(this._seed++);
893
- }
894
- float() {
895
- return _Random.float(this._seed++);
896
- }
897
- bool() {
898
- return _Random.bool(this._seed++);
899
- }
900
- sign() {
901
- return _Random.sign(this._seed++);
902
- }
903
- angle() {
904
- return _Random.angle(this._seed++);
905
- }
906
- };
907
-
908
- // src/rng.ts
909
- var Rng = class {
910
- random;
911
- get seed() {
912
- return this.random.seed;
913
- }
914
- set seed(seed) {
915
- this.random.seed = seed;
916
- }
917
- constructor(seed) {
918
- this.random = seed instanceof Random ? seed : new Random(seed);
919
- }
920
- nextFloat() {
921
- return this.random.float();
922
- }
923
- nextUint() {
924
- return this.random.uint();
925
- }
926
- floatRange(min, max) {
927
- if (typeof max !== "number") {
928
- max = min;
929
- min = 0;
930
- }
931
- return min + this.random.float() * (max - min);
932
- }
933
- range(min, max) {
934
- if (typeof max !== "number") {
935
- max = min;
936
- min = 0;
937
- }
938
- return Math.floor(this.floatRange(min, max));
939
- }
940
- pick(array) {
941
- return array[this.range(0, array.length - 1)];
942
- }
943
- sample(array, count) {
944
- return this.shuffle(array).slice(0, count);
945
- }
946
- shuffle(array) {
947
- const result = [...array];
948
- for (let i = result.length - 1; i > 0; --i) {
949
- const j = this.range(0, i);
950
- [result[i], result[j]] = [result[j], result[i]];
951
- }
952
- return result;
953
- }
954
- chance(probability) {
955
- return this.random.float() < probability;
956
- }
957
- vector2() {
958
- const \u03B8 = this.random.angle();
959
- return [
960
- Math.cos(\u03B8),
961
- Math.sin(\u03B8)
962
- ];
963
- }
964
- pointOnCircle(radius = 1) {
965
- const \u03B8 = this.random.angle();
966
- return [
967
- radius * Math.cos(\u03B8),
968
- radius * Math.sin(\u03B8)
969
- ];
970
- }
971
- pointInCircle(radius = 1) {
972
- const \u03B8 = this.random.angle();
973
- const r = Math.sqrt(this.random.float()) * radius;
974
- return [
975
- r * Math.cos(\u03B8),
976
- r * Math.sin(\u03B8)
977
- ];
978
- }
979
- pointOnSphere(radius = 1) {
980
- const u = this.random.float();
981
- const v = this.random.float();
982
- const \u03B8 = TAU * u;
983
- const \u03C6 = Math.acos(2 * v - 1);
984
- const s = Math.sin(\u03C6);
985
- return [
986
- radius * s * Math.cos(\u03B8),
987
- radius * s * Math.sin(\u03B8),
988
- radius * Math.cos(\u03C6)
989
- ];
990
- }
991
- pointInSphere(radius = 1) {
992
- const u = this.random.float();
993
- const v = this.random.float();
994
- const \u03B8 = TAU * u;
995
- const \u03C6 = Math.acos(2 * v - 1);
996
- const r = radius * Math.cbrt(this.random.float());
997
- const s = Math.sin(\u03C6);
998
- return [
999
- r * s * Math.cos(\u03B8),
1000
- r * s * Math.sin(\u03B8),
1001
- r * Math.cos(\u03C6)
1002
- ];
1003
- }
1004
- gaussian(mean = 0, standardDeviation = 1) {
1005
- let u = 0;
1006
- let v = 0;
1007
- while (u === 0) u = this.random.float();
1008
- while (v === 0) v = this.random.float();
1009
- const z = Math.sqrt(-2 * Math.log(u)) * Math.cos(TAU * v);
1010
- return mean + z * standardDeviation;
1011
- }
1012
- matrix(rows, columns = rows, min = 0, max = 1) {
1013
- return Array.from(
1014
- { length: rows },
1015
- () => Array.from(
1016
- { length: columns },
1017
- () => this.floatRange(min, max)
1018
- )
1019
- );
1020
- }
1021
- transformMatrix(rows, columns = rows) {
1022
- return this.matrix(rows, columns, -1, 1);
1023
- }
1024
- rgb() {
1025
- return [this.range(256), this.range(256), this.range(256)];
1026
- }
1027
- };
1028
- var rng = new Rng();
1029
-
1030
- // src/vector.ts
1031
- var Vector = class _Vector {
1032
- x;
1033
- y;
1034
- constructor(x = 0, y = 0) {
1035
- this.x = x;
1036
- this.y = y;
1037
- }
1038
- clone() {
1039
- return new _Vector(this.x, this.y);
1040
- }
1041
- copy(that) {
1042
- this.x = that.x;
1043
- this.y = that.y;
1044
- return this;
1045
- }
1046
- copyTo(target) {
1047
- target.x = this.x;
1048
- target.y = this.y;
1049
- return this;
1050
- }
1051
- set(x, y) {
1052
- this.x = x;
1053
- this.y = y;
1054
- return this;
1055
- }
1056
- equals(that) {
1057
- return this.x === that.x && this.y === that.y;
1058
- }
1059
- distanceTo(that) {
1060
- return distance2d(
1061
- this.x,
1062
- this.y,
1063
- that.x,
1064
- that.y
1065
- );
1066
- }
1067
- length() {
1068
- return Math.hypot(this.x, this.y);
1069
- }
1070
- normalize() {
1071
- const length = this.length();
1072
- if (length > 0) {
1073
- this.dividedBy(length);
1074
- }
1075
- return this;
1076
- }
1077
- setLength(length) {
1078
- return this.normalize().times(length);
1079
- }
1080
- dot(that) {
1081
- return this.x * that.x + this.y * that.y;
1082
- }
1083
- angle() {
1084
- return Math.atan2(this.y, this.x);
1085
- }
1086
- angleTo(that) {
1087
- const denominator = this.length() * that.length();
1088
- if (denominator === 0) {
1089
- return 0;
1090
- }
1091
- const theta = this.dot(that) / denominator;
1092
- return Math.acos(Math.min(1, Math.max(-1, theta)));
1093
- }
1094
- rotate(radians2) {
1095
- const cos = Math.cos(radians2);
1096
- const sin = Math.sin(radians2);
1097
- const { x, y } = this;
1098
- this.x = x * cos - y * sin;
1099
- this.y = x * sin + y * cos;
1100
- return this;
1101
- }
1102
- rotateAround(origin, radians2) {
1103
- return this.minus(origin).rotate(radians2).plus(origin);
1104
- }
1105
- floored() {
1106
- return new _Vector(
1107
- Math.floor(this.x),
1108
- Math.floor(this.y)
1109
- );
1110
- }
1111
- plus(x, y) {
1112
- if (x instanceof _Vector) {
1113
- y = x.y;
1114
- x = x.x;
1115
- } else if (y === void 0) {
1116
- y = x;
1117
- }
1118
- this.x += x;
1119
- this.y += y;
1120
- return this;
1121
- }
1122
- minus(x, y) {
1123
- if (x instanceof _Vector) {
1124
- y = x.y;
1125
- x = x.x;
1126
- } else if (y === void 0) {
1127
- y = x;
1128
- }
1129
- this.x -= x;
1130
- this.y -= y;
1131
- return this;
1132
- }
1133
- times(x, y) {
1134
- if (x instanceof _Vector) {
1135
- y = x.y;
1136
- x = x.x;
1137
- } else if (y === void 0) {
1138
- y = x;
1139
- }
1140
- this.x *= x;
1141
- this.y *= y;
1142
- return this;
1143
- }
1144
- dividedBy(x, y) {
1145
- if (x instanceof _Vector) {
1146
- y = x.y;
1147
- x = x.x;
1148
- } else if (y === void 0) {
1149
- y = x;
1150
- }
1151
- this.x /= x || 1;
1152
- this.y /= y || 1;
1153
- return this;
1154
- }
1155
- static from(value) {
1156
- return new _Vector(value.x, value.y);
1157
- }
1158
- static get ZERO() {
1159
- return new _Vector(0, 0);
1160
- }
1161
- static get NORTH() {
1162
- return new _Vector(0, -1);
1163
- }
1164
- static get SOUTH() {
1165
- return new _Vector(0, 1);
1166
- }
1167
- static get EAST() {
1168
- return new _Vector(1, 0);
1169
- }
1170
- static get WEST() {
1171
- return new _Vector(-1, 0);
1172
- }
1173
- };
1174
-
1175
- // src/rectangle.ts
1176
- var Rectangle = class _Rectangle {
1177
- x;
1178
- y;
1179
- width;
1180
- height;
1181
- constructor(x = 0, y = 0, width = 1, height = 1) {
1182
- this.x = x;
1183
- this.y = y;
1184
- this.width = width;
1185
- this.height = height;
1186
- }
1187
- area() {
1188
- return this.width * this.height;
1189
- }
1190
- contains(target, padding = 0) {
1191
- return target instanceof Vector ? target.x >= this.x - padding && target.x <= this.x + this.width + padding && target.y >= this.y - padding && target.y <= this.y + this.height + padding : target.x >= this.x + padding && target.y >= this.y + padding && target.x + target.width <= this.x + this.width - padding && target.y + target.height <= this.y + this.height - padding;
1192
- }
1193
- intersects(other, padding = 0) {
1194
- return !(other.x - padding > this.x + this.width + padding || other.x + other.width + padding < this.x - padding || other.y - padding > this.y + this.height + padding || other.y + other.height + padding < this.y - padding);
1195
- }
1196
- center() {
1197
- return new Vector(
1198
- this.x + this.width / 2,
1199
- this.y + this.height / 2
1200
- );
1201
- }
1202
- distanceTo(other) {
1203
- return this.center().distanceTo(other.center());
1204
- }
1205
- clone() {
1206
- return new _Rectangle(this.x, this.y, this.width, this.height);
1207
- }
1208
- equals(other) {
1209
- return this.x === other.x && this.y === other.y && this.width === other.width && this.height === other.height;
1210
- }
1211
- grow(padding) {
1212
- return new _Rectangle(
1213
- this.x - padding,
1214
- this.y - padding,
1215
- this.width + padding * 2,
1216
- this.height + padding * 2
1217
- );
1218
- }
1219
- vectorInside(vec, padding = 0) {
1220
- return vec.x >= this.x - padding && vec.x <= this.x + this.width + padding && vec.y >= this.y - padding && vec.y <= this.y + this.height + padding;
1221
- }
1222
- };
1223
-
1224
- // src/dungeon-generator.ts
1225
- var TILE_EMPTY = 0;
1226
- var TILE_FLOOR = 1;
1227
- var TILE_PATH = 2;
1228
- var DEFAULT_LEVEL_SIZE = 64;
1229
- var DEFAULT_ROOM_MIN_SIZE = 3;
1230
- var DEFAULT_ROOM_MAX_SIZE = 9;
1231
- var DEFAULT_ROOM_PADDING = 1;
1232
- var DEFAULT_ROOM_MAX_ITERATIONS = 1e3;
1233
- var DEFAULT_PATH_TIMEOUT = 1e4;
1234
- var DEFAULT_PATH_EXTRA_PATHS = 0;
1235
- var DEFAULT_PATH_EXTRA_PATH_DENSITY = 0.1;
1236
- var DEFAULT_DOOR_CHANCE_EXISTS = 0.5;
1237
- var DIRECTIONS_8_WAY = [
1238
- { x: -1, y: 0 },
1239
- // left
1240
- { x: -1, y: -1 },
1241
- // left-up
1242
- { x: 0, y: -1 },
1243
- // up
1244
- { x: 1, y: -1 },
1245
- // up-right
1246
- { x: 1, y: 0 },
1247
- // right
1248
- { x: 1, y: 1 },
1249
- // right-down
1250
- { x: 0, y: 1 },
1251
- // down
1252
- { x: -1, y: 1 }
1253
- // down-left
1254
- ];
1255
- function _plot(map, data, tile) {
1256
- data.forEach((element) => {
1257
- if (element instanceof Rectangle) {
1258
- for (let y = 0; y < element.height; y++) {
1259
- for (let x = 0; x < element.width; x++) {
1260
- map.set(element.x + x, element.y + y, tile);
1261
- }
1262
- }
1263
- } else if (Array.isArray(element)) {
1264
- element.forEach((point) => {
1265
- map.set(point.x, point.y, tile);
1266
- });
1267
- } else {
1268
- map.set(element.x, element.y, tile);
1269
- }
1270
- });
1271
- }
1272
- function _generateRooms(params = {}) {
1273
- const size = params.size ?? DEFAULT_LEVEL_SIZE;
1274
- const minRoomSize = params.minSize ?? DEFAULT_ROOM_MIN_SIZE;
1275
- const maxRoomSize = params.maxSize ?? DEFAULT_ROOM_MAX_SIZE;
1276
- const padding = params.padding ?? DEFAULT_ROOM_PADDING;
1277
- const maxIterations = params.maxIterations ?? DEFAULT_ROOM_MAX_ITERATIONS;
1278
- const rooms = [];
1279
- let iterations = 0;
1280
- while (iterations < maxIterations) {
1281
- const baseSize = rng.range(minRoomSize, maxRoomSize);
1282
- const aspectRatio = 0.75 + rng.gaussian() * 0.5;
1283
- const width = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize * aspectRatio)));
1284
- const height = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize / aspectRatio)));
1285
- const x = Math.floor(rng.range(1 + padding, size - width - padding));
1286
- const y = Math.floor(rng.range(1 + padding, size - height - padding));
1287
- const room = new Rectangle(x, y, width, height);
1288
- if (!rooms.some((existing) => room.intersects(existing, padding))) {
1289
- rooms.push(room);
1290
- iterations = 0;
1291
- } else {
1292
- iterations += 1;
1293
- }
1294
- }
1295
- return rooms;
1296
- }
1297
- function _generateMST(rooms, params = {}) {
1298
- const timeout = params.timeout ?? DEFAULT_PATH_TIMEOUT;
1299
- const extraPathLevels = params.extraPaths ?? DEFAULT_PATH_EXTRA_PATHS;
1300
- const extraPathDensity = params.extraPathDensity ?? DEFAULT_PATH_EXTRA_PATH_DENSITY;
1301
- const startTime = Date.now();
1302
- const mst = [];
1303
- const extraPaths = [];
1304
- const visited = /* @__PURE__ */ new Set();
1305
- const heap = new Heap((a, b) => a.cost - b.cost);
1306
- visited.add(0);
1307
- const zeroCenter = rooms[0].center();
1308
- for (let i = 1; i < rooms.length; i++) {
1309
- const iCenter = rooms[i].center();
1310
- heap.push({
1311
- from: 0,
1312
- to: i,
1313
- cost: squaredDistance(
1314
- zeroCenter.x,
1315
- zeroCenter.y,
1316
- iCenter.x,
1317
- iCenter.y
1318
- )
1319
- });
1320
- }
1321
- while (visited.size < rooms.length && Date.now() - startTime < timeout) {
1322
- let edge = heap.pop();
1323
- while (edge && visited.has(edge.to)) {
1324
- edge = heap.pop();
1325
- }
1326
- if (!edge) break;
1327
- const { from, to } = edge;
1328
- visited.add(to);
1329
- mst.push({ a: rooms[from], b: rooms[to] });
1330
- const toCenter = rooms[to].center();
1331
- for (let i = 0; i < rooms.length; i++) {
1332
- if (!visited.has(i)) {
1333
- const iCenter = rooms[i].center();
1334
- heap.push({
1335
- from: to,
1336
- to: i,
1337
- cost: squaredDistance(
1338
- toCenter.x,
1339
- toCenter.y,
1340
- iCenter.x,
1341
- iCenter.y
1342
- )
1343
- });
1344
- }
1345
- }
1346
- }
1347
- const remainingEdges = heap.toArray().sort((a, b) => a.cost - b.cost);
1348
- for (let i = 0; i < extraPathLevels && i < remainingEdges.length; i++) {
1349
- const e = remainingEdges[i];
1350
- if (rng.nextFloat() < extraPathDensity) {
1351
- extraPaths.push({
1352
- a: rooms[e.from],
1353
- b: rooms[e.to]
1354
- });
1355
- }
1356
- }
1357
- return mst.concat(extraPaths);
1358
- }
1359
- function _getRectEdgePoints(rect) {
1360
- const points = [];
1361
- const x2 = rect.x + rect.width - 1;
1362
- const y2 = rect.y + rect.height - 1;
1363
- for (let x1 = rect.x; x1 < x2; x1++) {
1364
- points.push({ x: x1, y: rect.y });
1365
- points.push({ x: x1, y: y2 });
1366
- }
1367
- for (let y1 = rect.y; y1 < y2; y1++) {
1368
- points.push({ x: rect.x, y: y1 });
1369
- points.push({ x: x2, y: y1 });
1370
- }
1371
- return points;
1372
- }
1373
- function _getShortestPathBetweenRects(rectA, rectB) {
1374
- const edgeA = _getRectEdgePoints(rectA);
1375
- const edgeB = _getRectEdgePoints(rectB);
1376
- let paths = { a: edgeA[0], b: edgeB[0], distance: Infinity };
1377
- for (const a of edgeA) {
1378
- for (const b of edgeB) {
1379
- const d = distance2d(a.x, a.y, b.x, b.y);
1380
- if (d < paths.distance) {
1381
- paths = { a, b, distance: d };
1382
- }
1383
- }
1384
- }
1385
- return { a: paths.a, b: paths.b };
1386
- }
1387
- function _generatePaths(map, rooms, params = {}) {
1388
- const aStar = new AStar(map);
1389
- const paths = [];
1390
- _generateMST(rooms, params).forEach((rects) => {
1391
- const { a, b } = _getShortestPathBetweenRects(rects.a, rects.b);
1392
- paths.push(aStar.findPath(a, b, params.astarFindPathParams));
1393
- });
1394
- return paths;
1395
- }
1396
- function GenerateRooms(params = {}) {
1397
- const startTime = Date.now();
1398
- const map = params.map ?? new Map2D(TILE_EMPTY);
1399
- const rooms = _generateRooms(params.rooms);
1400
- _plot(map, rooms, TILE_FLOOR);
1401
- const paths = _generatePaths(map, rooms, params.paths);
1402
- _plot(map, paths, TILE_PATH);
1403
- log("GenerateRooms: done:", Date.now() - startTime, "ms");
1404
- return { map, rooms, paths };
1405
- }
1406
- function GenerateDoors(map, paths, params = {}) {
1407
- const chanceExists = params.chanceExists ?? DEFAULT_DOOR_CHANCE_EXISTS;
1408
- const possibleDoorPoints = [];
1409
- paths.forEach((points) => {
1410
- if (points.length > 1) {
1411
- possibleDoorPoints.push(points[0]);
1412
- possibleDoorPoints.push(points[points.length - 1]);
1413
- }
1414
- });
1415
- const doors = [];
1416
- possibleDoorPoints.forEach((doorPoint) => {
1417
- if (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)) {
1418
- doors.push(doorPoint);
1419
- }
1420
- });
1421
- return doors;
1422
- }
1423
- function GenerateWalls(map) {
1424
- const walls = [];
1425
- map.forEach((x, y, _v) => {
1426
- DIRECTIONS_8_WAY.forEach((dir) => {
1427
- const nx = dir.x + x;
1428
- const ny = dir.y + y;
1429
- if (map.get(nx, ny) === map.defaultValue) {
1430
- walls.push({ x: nx, y: ny });
1431
- }
1432
- });
1433
- });
1434
- return walls;
1435
- }
1436
-
1437
- // src/ecs.ts
1438
- var ECS = class _ECS {
1439
- static #nextEntity = 0;
1440
- components = /* @__PURE__ */ new Map();
1441
- createEntity() {
1442
- return _ECS.#nextEntity++;
1443
- }
1444
- addComponent(entity, component) {
1445
- const type = component.constructor;
1446
- let map = this.components.get(type);
1447
- if (!map) {
1448
- map = /* @__PURE__ */ new Map();
1449
- this.components.set(type, map);
1450
- }
1451
- map.set(entity, component);
1452
- }
1453
- getComponent(entity, type) {
1454
- const map = this.components.get(type);
1455
- return map?.get(entity);
1456
- }
1457
- hasComponent(entity, type) {
1458
- return this.components.get(type)?.has(entity) ?? false;
1459
- }
1460
- removeComponent(entity, type) {
1461
- this.components.get(type)?.delete(entity);
1462
- }
1463
- *query(...types) {
1464
- if (types.length === 0) {
1465
- return;
1466
- }
1467
- let smallest;
1468
- const maps = [];
1469
- for (const type of types) {
1470
- const map = this.components.get(type);
1471
- if (!map) {
1472
- return;
1473
- }
1474
- maps.push(map);
1475
- if (!smallest || map.size < smallest.size) {
1476
- smallest = map;
1477
- }
1478
- }
1479
- if (!smallest) {
1480
- return;
1481
- }
1482
- for (const entity of smallest.keys()) {
1483
- const components = [];
1484
- let matches = true;
1485
- for (const map of maps) {
1486
- const component = map.get(entity);
1487
- if (!component) {
1488
- matches = false;
1489
- break;
1490
- }
1491
- components.push(component);
1492
- }
1493
- if (matches) {
1494
- yield [entity, ...components];
1495
- }
1496
- }
1497
- }
1498
- destroyEntity(entity) {
1499
- for (const map of this.components.values()) {
1500
- map.delete(entity);
1501
- }
1502
- }
1503
- clear() {
1504
- this.components.clear();
1505
- _ECS.#nextEntity = 0;
1506
- }
1507
- };
1508
-
1509
- // src/emitter.ts
1510
- var Emitter = class {
1511
- listeners = /* @__PURE__ */ new Map();
1512
- constructor() {
1513
- }
1514
- on(...eventName) {
1515
- const listener = eventName.pop();
1516
- const events = eventName.filter((ev) => typeof ev === "string");
1517
- events.forEach((event) => {
1518
- if (!this.listeners.has(event)) {
1519
- this.listeners.set(event, new Array());
1520
- }
1521
- this.listeners.get(event)?.push(listener);
1522
- });
1523
- return this;
1524
- }
1525
- emit(eventName, ...args) {
1526
- this.listeners.get(eventName)?.forEach((listener) => listener(...args, eventName));
1527
- return this;
1528
- }
1529
- };
1530
-
1531
- // src/event-queue.ts
1532
- var EventQueue = class {
1533
- events = [];
1534
- emit(event) {
1535
- this.events.push(event);
1536
- }
1537
- consume() {
1538
- return this.events;
1539
- }
1540
- clear() {
1541
- this.events.length = 0;
1542
- }
1543
- drain() {
1544
- return this.events.splice(0);
1545
- }
1546
- get size() {
1547
- return this.events.length;
1548
- }
1549
- };
1550
-
1551
- // src/input.ts
1552
- var Input = class _Input extends Emitter {
1553
- static _instance;
1554
- static get instance() {
1555
- if (!_Input._instance) {
1556
- _Input._instance = new _Input();
1557
- }
1558
- return _Input._instance;
1559
- }
1560
- _keyStates = {};
1561
- _mouseButtonStates = {};
1562
- _mousePosition = new Vector();
1563
- _mousePosition2 = new Vector();
1564
- get mousePosition() {
1565
- return this._mousePosition;
1566
- }
1567
- get mousePosition2() {
1568
- return this._mousePosition2;
1569
- }
1570
- inputThreshold = 200;
1571
- constructor() {
1572
- super();
1573
- window.addEventListener("keydown", this._onKeyDown.bind(this));
1574
- window.addEventListener("keyup", this._onKeyUp.bind(this));
1575
- window.addEventListener("pointerdown", this._onPointerButtonDown.bind(this));
1576
- window.addEventListener("pointerup", this._onPointerButtonUp.bind(this));
1577
- window.addEventListener("mousemove", this._onMouseMove.bind(this));
1578
- window.addEventListener("wheel", this._onWheel.bind(this));
1579
- }
1580
- _getCommonEventProps(event) {
1581
- const props = {
1582
- timeStamp: event.timeStamp,
1583
- altKey: event.altKey,
1584
- ctrlKey: event.ctrlKey,
1585
- metaKey: event.metaKey,
1586
- shiftKey: event.shiftKey,
1587
- event
1588
- };
1589
- return props;
1590
- }
1591
- // private _onContextMenu(ev: MouseEvent) {
1592
- // ev.preventDefault();
1593
- // this.emit('contextmenu');
1594
- // return false;
1595
- // }
1596
- _onKeyDown(ev) {
1597
- const props = this._getCommonEventProps(ev);
1598
- const { code, key } = ev;
1599
- if (!ev.repeat) {
1600
- this._keyStates[code] = { state: 1, timeStamp: props.timeStamp };
1601
- this.emit("key_down", { ...props, code, key });
1602
- this.emit(`${code.toLowerCase()}_down`, props);
1603
- }
1604
- }
1605
- _onKeyUp(ev) {
1606
- const props = this._getCommonEventProps(ev);
1607
- const { code, key } = ev;
1608
- const deltaStamp = props.timeStamp - (this._keyStates[code]?.timeStamp ?? 0);
1609
- this._keyStates[code] = { state: 0, timeStamp: props.timeStamp };
1610
- this.emit("key_up", { ...props, code, key });
1611
- this.emit(`${code.toLowerCase()}_up`, props);
1612
- if (deltaStamp < this.inputThreshold) {
1613
- this.emit("key_pressed", { ...props, code, key });
1614
- this.emit(`${code.toLowerCase()}_pressed`, props);
1615
- }
1616
- }
1617
- _onPointerButtonDown(ev) {
1618
- const props = this._getCommonEventProps(ev);
1619
- const { button } = ev;
1620
- if (!this._mouseButtonStates[button]?.state) {
1621
- this._mouseButtonStates[button] = { state: 1, timeStamp: props.timeStamp };
1622
- switch (ev.pointerType) {
1623
- case "touch":
1624
- this.emit("touch_down", { ...props, button });
1625
- break;
1626
- default:
1627
- this.emit("mouse_button_down", { ...props, button });
1628
- this.emit(`mouse_button${button}_down`, props);
1629
- break;
1630
- }
1631
- }
1632
- }
1633
- _onPointerButtonUp(ev) {
1634
- const props = this._getCommonEventProps(ev);
1635
- const { button } = ev;
1636
- const deltaStamp = props.timeStamp - (this._mouseButtonStates[button]?.timeStamp ?? 0);
1637
- this._mouseButtonStates[button] = { state: 0, timeStamp: props.timeStamp };
1638
- switch (ev.pointerType) {
1639
- case "touch":
1640
- this.emit("touch_up", { ...props, button });
1641
- break;
1642
- default:
1643
- this.emit("mouse_button_up", { ...props, button });
1644
- this.emit(`mouse_button${button}_up`, props);
1645
- break;
1646
- }
1647
- if (deltaStamp < this.inputThreshold) {
1648
- switch (ev.pointerType) {
1649
- case "touch":
1650
- this.emit("tapped", { ...props, button });
1651
- break;
1652
- default:
1653
- this.emit("mouse_button_clicked", { ...props, button });
1654
- this.emit(`mouse_button${button}_clicked`, props);
1655
- break;
1656
- }
1657
- }
1658
- }
1659
- _onMouseMove(ev) {
1660
- const props = this._getCommonEventProps(ev);
1661
- const { buttons, offsetX, offsetY, movementX, movementY } = ev;
1662
- this._mousePosition = new Vector(offsetX, offsetY);
1663
- const width = window.innerWidth;
1664
- const height = window.innerHeight;
1665
- this._mousePosition2 = new Vector(
1666
- ev.clientX / width * 2 - 1,
1667
- -(ev.clientY / height) * 2 + 1
1668
- );
1669
- this.emit("mouse_move", {
1670
- ...props,
1671
- buttons,
1672
- x: offsetX,
1673
- y: offsetY,
1674
- deltaX: movementX,
1675
- deltaY: movementY
1676
- });
1677
- }
1678
- _onWheel(ev) {
1679
- const props = this._getCommonEventProps(ev);
1680
- const { deltaX, deltaY, deltaZ } = ev;
1681
- this.emit("mouse_wheel", {
1682
- ...props,
1683
- deltaX,
1684
- deltaY,
1685
- deltaZ
1686
- });
1687
- }
1688
- isKeyDown(keyCode) {
1689
- return this._keyStates[keyCode]?.state === 1 ? true : false;
1690
- }
1691
- getKeyState(keyCode) {
1692
- return this._keyStates[keyCode]?.state ?? 0;
1693
- }
1694
- isMouseButtonDown(mouseButton) {
1695
- return this._mouseButtonStates[mouseButton]?.state === 1 ? true : false;
1696
- }
1697
- getMouseButtonState(button) {
1698
- return this._mouseButtonStates[button]?.state ?? 0;
1699
- }
1700
- };
1701
-
1702
- // src/map3d.ts
1703
- var DEFAULT_MAP_3D_VALUE = -1;
1704
- var BASE_3D = 131072;
1705
- var OFFSET_3D = 65536;
1706
- var Map3D = class _Map3D {
1707
- defaultValue;
1708
- _data;
1709
- get data() {
1710
- return this._data;
1711
- }
1712
- get size() {
1713
- return this._data.size;
1714
- }
1715
- constructor(defaultValue = DEFAULT_MAP_3D_VALUE, mapData) {
1716
- this.defaultValue = defaultValue;
1717
- this._data = mapData ?? /* @__PURE__ */ new Map();
1718
- }
1719
- _floor(x, y, z) {
1720
- return [Math.floor(x), Math.floor(y), Math.floor(z)];
1721
- }
1722
- _key(x, y, z) {
1723
- const X = x + OFFSET_3D & BASE_3D - 1;
1724
- const Y = y + OFFSET_3D & BASE_3D - 1;
1725
- const Z = z + OFFSET_3D & BASE_3D - 1;
1726
- return X * BASE_3D * BASE_3D + Y * BASE_3D + Z;
1727
- }
1728
- _pos(key) {
1729
- const Z = key % BASE_3D;
1730
- const Y = Math.floor(key / BASE_3D) % BASE_3D;
1731
- const X = Math.floor(key / (BASE_3D * BASE_3D));
1732
- return [X - OFFSET_3D, Y - OFFSET_3D, Z - OFFSET_3D];
1733
- }
1734
- clear() {
1735
- this._data.clear();
1736
- }
1737
- get(x, y, z = 0) {
1738
- [x, y, z] = this._floor(x, y, z);
1739
- return this._data.get(this._key(x, y, z)) ?? this.defaultValue;
1740
- }
1741
- set(x, y, z, n = this.defaultValue) {
1742
- [x, y, z] = this._floor(x, y, z);
1743
- const key = this._key(x, y, z);
1744
- if (n === this.defaultValue) {
1745
- this._data.delete(key);
1746
- } else {
1747
- this._data.set(key, n);
1748
- }
1749
- }
1750
- setArea(x1, y1, z1, x2, y2, z2, n) {
1751
- for (let z = z1; z <= z2; z++) {
1752
- for (let y = y1; y <= y2; y++) {
1753
- for (let x = x1; x <= x2; x++) {
1754
- this.set(x, y, z, n);
1755
- }
1756
- }
1757
- }
1758
- }
1759
- forEach(callback) {
1760
- this._data.forEach((n, key) => {
1761
- const [x, y, z] = this._pos(key);
1762
- callback(x, y, z, n);
1763
- });
1764
- }
1765
- export() {
1766
- const data = [];
1767
- this.forEach((x, y, z, n) => {
1768
- data.push({ x, y, z, n });
1769
- });
1770
- return data;
1771
- }
1772
- import(data) {
1773
- this.clear();
1774
- data.forEach(({ x, y, z, n }) => {
1775
- this.set(x, y, z, n);
1776
- });
1777
- }
1778
- static fromMap2D(map2d, defaultValue = DEFAULT_MAP_3D_VALUE) {
1779
- const map3d = new _Map3D(defaultValue);
1780
- map2d.forEach((x, y, n) => map3d.set(x, y, 0, n));
1781
- return map3d;
1782
- }
1783
- };
1784
-
1785
- // src/misc.ts
1786
- function isNullOrUndefined(target) {
1787
- return target === null || target === void 0;
1788
- }
1789
- function isPositiveString(target) {
1790
- return target.length > 0;
1791
- }
1792
- var getRedYellowGreenGradientHex = (min, max) => {
1793
- if (max === void 0) {
1794
- max = min;
1795
- min = 0;
1796
- }
1797
- if (max < 1) {
1798
- max = 1;
1799
- }
1800
- const percent = min / max;
1801
- const index = clamp(Math.floor(percent * 10), 0, 10);
1802
- return [
1803
- "#ff0000",
1804
- "#ff3300",
1805
- "#ff6600",
1806
- "#ff9900",
1807
- "#ffcc00",
1808
- "#ffff00",
1809
- "#ccff00",
1810
- "#99ff00",
1811
- "#66ff00",
1812
- "#33ff00",
1813
- "#00ff00"
1814
- ][index];
1815
- };
1816
- function GetUrlParams() {
1817
- const params = {};
1818
- const url = new URLSearchParams(location.search);
1819
- for (const [key, value] of url.entries()) {
1820
- params[key] = value;
1821
- }
1822
- return params;
1823
- }
1824
- var xy2k = (x, y, delimiter = ",") => `${x}${delimiter}${y}`;
1825
- var k2xy = (key, delimiter = ",") => key.split(delimiter).map(parseFloat);
1826
- var xyz2k = (x, y, z, delimiter = ",") => `${x}${delimiter},${y},${delimiter},${z}`;
1827
- var k2xyz = (key, delimiter = ",") => key.split(delimiter).map(parseFloat);
1828
-
1829
- // src/noise.ts
1830
- import { createNoise2D, createNoise3D, createNoise4D } from "simplex-noise";
1831
- var Noise = class _Noise {
1832
- static _n2d;
1833
- static _n3d;
1834
- static _n4d;
1835
- static noise2d(x, y) {
1836
- if (!_Noise._n2d) {
1837
- _Noise._n2d = createNoise2D(() => rng.nextFloat());
1838
- }
1839
- return _Noise._n2d(x, y);
1840
- }
1841
- static noise3d(x, y, z) {
1842
- if (!_Noise._n3d) {
1843
- _Noise._n3d = createNoise3D(() => rng.nextFloat());
1844
- }
1845
- return _Noise._n3d(x, y, z);
1846
- }
1847
- static noise4d(x, y, z, w) {
1848
- if (!_Noise._n4d) {
1849
- _Noise._n4d = createNoise4D(() => rng.nextFloat());
1850
- }
1851
- return _Noise._n4d(x, y, z, w);
1852
- }
1853
- static fractal2d(x, y, fractalParams) {
1854
- const octaves = fractalParams.octaves;
1855
- const lacunarity = fractalParams.lacunarity;
1856
- const gain = 0.5;
1857
- let amplitude = fractalParams.amplitude;
1858
- let frequency = fractalParams.frequency;
1859
- let value = 0;
1860
- for (let i = 0; i < octaves; i++) {
1861
- value += amplitude * _Noise.noise2d(
1862
- frequency * x,
1863
- frequency * y
1864
- );
1865
- frequency *= lacunarity;
1866
- amplitude *= gain;
1867
- }
1868
- return value;
1869
- }
1870
- static fractal3d(x, y, z, fractalParams) {
1871
- const octaves = fractalParams.octaves;
1872
- const lacunarity = fractalParams.lacunarity;
1873
- const gain = 0.5;
1874
- let amplitude = fractalParams.amplitude;
1875
- let frequency = fractalParams.frequency;
1876
- let value = 0;
1877
- for (let i = 0; i < octaves; i++) {
1878
- value += amplitude * _Noise.noise3d(
1879
- frequency * x,
1880
- frequency * y,
1881
- frequency * z
1882
- );
1883
- frequency *= lacunarity;
1884
- amplitude *= gain;
1885
- }
1886
- return value;
1887
- }
1888
- };
1889
-
1890
- // src/particle-renderer.ts
1891
- var ParticleRenderer = class {
1892
- _screenCanvas;
1893
- _bufferCanvas;
1894
- screenContext;
1895
- bufferContext;
1896
- get width() {
1897
- return this._screenCanvas.width;
1898
- }
1899
- get height() {
1900
- return this._screenCanvas.height;
1901
- }
1902
- constructor(canvas) {
1903
- this._screenCanvas = canvas ?? document.createElement("canvas");
1904
- this._bufferCanvas = new OffscreenCanvas(this._screenCanvas.width, this._screenCanvas.height);
1905
- this.screenContext = this._screenCanvas.getContext("2d");
1906
- this.bufferContext = this._bufferCanvas.getContext("2d");
1907
- if (!this.screenContext || !this.bufferContext) {
1908
- throw "Failed to create CanvasRenderingContext2D";
1909
- }
1910
- }
1911
- appendTo(target, autoResize = true) {
1912
- if (this._screenCanvas.parentNode) {
1913
- this._screenCanvas.parentNode.removeChild(this._screenCanvas);
1914
- }
1915
- target.appendChild(this._screenCanvas);
1916
- if (autoResize) {
1917
- this.resize();
1918
- }
1919
- }
1920
- resize(displayWidth, displayHeight) {
1921
- const { width, height } = this._screenCanvas.parentElement?.getBoundingClientRect() ?? this._screenCanvas.getBoundingClientRect();
1922
- displayWidth = 0 | (displayWidth ?? width);
1923
- displayHeight = 0 | (displayHeight ?? height);
1924
- if (this._screenCanvas.width !== displayWidth || this._screenCanvas.height !== displayHeight) {
1925
- this._screenCanvas.width = displayWidth;
1926
- this._screenCanvas.height = displayHeight;
1927
- this._bufferCanvas.width = displayWidth;
1928
- this._bufferCanvas.height = displayHeight;
1929
- return true;
1930
- }
1931
- return false;
1932
- }
1933
- setPixel(x, y, color, size = 2) {
1934
- this.bufferContext.fillStyle = color.hexStr;
1935
- this.bufferContext.fillRect(x - size / 2, y - size / 2, size, size);
1936
- }
1937
- render() {
1938
- this.screenContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
1939
- this.screenContext.drawImage(this._bufferCanvas, 0, 0);
1940
- this.bufferContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
1941
- }
1942
- };
1943
-
1944
- // src/spatial-partition-2d.ts
1945
- var SpatialPartition2d = class {
1946
- cells;
1947
- cellSize;
1948
- entities;
1949
- constructor(cellSize, entities) {
1950
- this.cellSize = cellSize;
1951
- this.entities = entities;
1952
- this.cells = Array.from(
1953
- { length: Math.ceil(1 / cellSize) },
1954
- () => Array.from({ length: Math.ceil(1 / cellSize) }, () => [])
1955
- );
1956
- for (const entity of this.entities) {
1957
- this.addEntity(entity);
1958
- }
1959
- }
1960
- addEntity(entity) {
1961
- const cell = this.getCell(entity.x, entity.y);
1962
- cell.push(entity);
1963
- }
1964
- getCell(x, y) {
1965
- const cellX = Math.floor(x / this.cellSize);
1966
- const cellY = Math.floor(y / this.cellSize);
1967
- return this.cells[cellY][cellX];
1968
- }
1969
- getCellNeighbors(x, y) {
1970
- const neighbors = [];
1971
- for (let dy = -1; dy <= 1; dy++) {
1972
- for (let dx = -1; dx <= 1; dx++) {
1973
- let nx = x + dx;
1974
- let ny = y + dy;
1975
- if (nx < 0) nx = this.cells[0].length - 1;
1976
- else if (nx >= this.cells[0].length) nx = 0;
1977
- if (ny < 0) ny = this.cells.length - 1;
1978
- else if (ny >= this.cells.length) ny = 0;
1979
- neighbors.push(this.cells[ny][nx]);
1980
- }
1981
- }
1982
- return neighbors;
1983
- }
1984
- };
1985
-
1986
- // src/particle-system-2d.ts
1987
- function randomMatrix(size) {
1988
- const rows = [];
1989
- for (let i = 0; i < size; i++) {
1990
- const row = [];
1991
- for (let j = 0; j < size; j++) {
1992
- row.push(Random.float(i, j) * 2 - 1);
1993
- }
1994
- rows.push(row);
1995
- }
1996
- return rows;
1997
- }
1998
- var colors = [
1999
- Color.RED,
2000
- Color.GREEN,
2001
- Color.BLUE,
2002
- Color.YELLOW,
2003
- Color.MAGENTA
2004
- ];
2005
- var ParticleSystem2d = class {
2006
- particleCount = 2e3;
2007
- _particleSize = 2;
2008
- _frictionHalfLife = 0.04;
2009
- _range = 0.1;
2010
- _rangeFactor = 0.1;
2011
- _attractionMatrix = randomMatrix(colors.length);
2012
- _particles = [];
2013
- _spatialPartition;
2014
- constructor() {
2015
- for (let i = 0; i < this.particleCount; i++) {
2016
- this._particles.push({
2017
- x: Random.float(i),
2018
- y: Random.float(i + 1),
2019
- vx: 0,
2020
- vy: 0,
2021
- color: rng.range(colors.length)
2022
- });
2023
- }
2024
- this._spatialPartition = new SpatialPartition2d(this._range, this._particles);
2025
- }
2026
- _calcForce(r, a, beta = 0.3) {
2027
- let f = 0;
2028
- if (r < beta) {
2029
- f = r / beta - 1;
2030
- } else if (beta < r && r < 1) {
2031
- f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
2032
- }
2033
- return f;
2034
- }
2035
- _updateVelocities(deltaTimeSeconds) {
2036
- const frictionFactor = Math.pow(
2037
- 0.5,
2038
- deltaTimeSeconds / this._frictionHalfLife
2039
- );
2040
- for (let y = 0; y < this._spatialPartition.cells.length; y++) {
2041
- for (let x = 0; x < this._spatialPartition.cells[y].length; x++) {
2042
- const cell = this._spatialPartition.cells[y][x];
2043
- for (let i = 0; i < cell.length; i++) {
2044
- let fx = 0;
2045
- let fy = 0;
2046
- const p1 = cell[i];
2047
- const neighborCells = this._spatialPartition.getCellNeighbors(x, y);
2048
- for (const neighborCell of neighborCells) {
2049
- for (let j = 0; j < neighborCell.length; j++) {
2050
- if (cell === neighborCell && i === j) continue;
2051
- const p2 = neighborCell[j];
2052
- let rx = p2.x - p1.x;
2053
- if (Math.abs(rx) > 0.5) rx = rx > 0 ? rx - 1 : rx + 1;
2054
- let ry = p2.y - p1.y;
2055
- if (Math.abs(ry) > 0.5) ry = ry > 0 ? ry - 1 : ry + 1;
2056
- const d = Math.hypot(rx, ry);
2057
- if (d > 0 && d < this._range) {
2058
- const f = this._calcForce(
2059
- d / this._range,
2060
- this._attractionMatrix[p1.color][p2.color]
2061
- );
2062
- fx += rx / d * f;
2063
- fy += ry / d * f;
2064
- }
2065
- }
2066
- }
2067
- fx *= this._range * this._rangeFactor;
2068
- fy *= this._range * this._rangeFactor;
2069
- p1.vx *= frictionFactor;
2070
- p1.vy *= frictionFactor;
2071
- p1.vx += fx;
2072
- p1.vy += fy;
2073
- }
2074
- }
2075
- }
2076
- }
2077
- _updatePositions(deltaTimeSeconds, renderer) {
2078
- for (let i = 0; i < this.particleCount; i++) {
2079
- const particle = this._particles[i];
2080
- const oldCell = this._spatialPartition.getCell(particle.x, particle.y);
2081
- particle.x += particle.vx * deltaTimeSeconds;
2082
- particle.y += particle.vy * deltaTimeSeconds;
2083
- if (particle.x < 0) particle.x = 1 + particle.x % 1;
2084
- if (particle.x > 1) particle.x = particle.x % 1;
2085
- if (particle.y < 0) particle.y = 1 + particle.y % 1;
2086
- if (particle.y > 1) particle.y = particle.y % 1;
2087
- renderer.setPixel(
2088
- particle.x * renderer.width,
2089
- particle.y * renderer.height,
2090
- colors[particle.color],
2091
- this._particleSize
2092
- );
2093
- const newCell = this._spatialPartition.getCell(particle.x, particle.y);
2094
- if (newCell !== oldCell) {
2095
- const index = oldCell.indexOf(particle);
2096
- if (index !== -1) {
2097
- oldCell.splice(index, 1);
2098
- }
2099
- newCell.push(particle);
2100
- }
2101
- }
2102
- }
2103
- update(renderer, dt) {
2104
- this._updateVelocities(dt);
2105
- this._updatePositions(dt, renderer);
2106
- }
2107
- };
2108
-
2109
- // src/poisson-disk-sampler.ts
2110
- function PoissonDiskSampler(width, height, minDist, maxPoints = 30) {
2111
- const k = maxPoints;
2112
- const cellSize = minDist / SQRT2;
2113
- const gridWidth = Math.ceil(width / cellSize);
2114
- const gridHeight = Math.ceil(height / cellSize);
2115
- const grid = Array.from(
2116
- { length: gridWidth },
2117
- () => Array(gridHeight).fill(null)
2118
- );
2119
- const samples = [];
2120
- const active = [];
2121
- function gridIndex(p) {
2122
- return {
2123
- i: Math.floor(p.x / cellSize),
2124
- j: Math.floor(p.y / cellSize)
2125
- };
2126
- }
2127
- function isFarEnough(p) {
2128
- const { i, j } = gridIndex(p);
2129
- for (let x = i - 2; x <= i + 2; x++) {
2130
- for (let y = j - 2; y <= j + 2; y++) {
2131
- if (x < 0 || y < 0 || x >= gridWidth || y >= gridHeight) continue;
2132
- const neighbor = grid[x][y];
2133
- if (!neighbor) continue;
2134
- const dx = neighbor.x - p.x;
2135
- const dy = neighbor.y - p.y;
2136
- if (dx * dx + dy * dy < minDist * minDist) {
2137
- return false;
2138
- }
2139
- }
2140
- }
2141
- return true;
2142
- }
2143
- const initial = {
2144
- x: rng.range(0, width),
2145
- y: rng.range(0, height)
2146
- };
2147
- const { i: i0, j: j0 } = gridIndex(initial);
2148
- grid[i0][j0] = initial;
2149
- samples.push(initial);
2150
- active.push(initial);
2151
- while (active.length) {
2152
- const index = Math.floor(rng.range(0, active.length));
2153
- const point = active[index];
2154
- let found = false;
2155
- for (let n = 0; n < k; n++) {
2156
- const angle = rng.range(0, PI * 2);
2157
- const dist = rng.range(minDist, 2 * minDist);
2158
- const newPoint = {
2159
- x: point.x + Math.cos(angle) * dist,
2160
- y: point.y + Math.sin(angle) * dist
2161
- };
2162
- if (newPoint.x >= 0 && newPoint.y >= 0 && newPoint.x < width && newPoint.y < height && isFarEnough(newPoint)) {
2163
- const { i, j } = gridIndex(newPoint);
2164
- grid[i][j] = newPoint;
2165
- samples.push(newPoint);
2166
- active.push(newPoint);
2167
- found = true;
2168
- break;
2169
- }
2170
- }
2171
- if (!found) {
2172
- active.splice(index, 1);
2173
- }
2174
- }
2175
- return samples;
2176
- }
2177
-
2178
- // src/signal.ts
2179
- var Signal = class {
2180
- value;
2181
- subscribers = /* @__PURE__ */ new Set();
2182
- constructor(initialValue) {
2183
- this.value = initialValue;
2184
- }
2185
- get() {
2186
- return this.value;
2187
- }
2188
- set(value) {
2189
- if (Object.is(this.value, value)) return;
2190
- this.value = value;
2191
- for (const subscriber of [...this.subscribers]) {
2192
- subscriber(value);
2193
- }
2194
- }
2195
- subscribe(subscriber) {
2196
- this.subscribers.add(subscriber);
2197
- subscriber(this.value);
2198
- return () => this.subscribers.delete(subscriber);
2199
- }
2200
- };
2201
-
2202
- // src/simplex-noise.ts
2203
- var SimplexNoise = class {
2204
- grad3;
2205
- p;
2206
- perm;
2207
- constructor() {
2208
- this.grad3 = [
2209
- [1, 1, 0],
2210
- [-1, 1, 0],
2211
- [1, -1, 0],
2212
- [-1, -1, 0],
2213
- [1, 0, 1],
2214
- [-1, 0, 1],
2215
- [1, 0, -1],
2216
- [-1, 0, -1],
2217
- [0, 1, 1],
2218
- [0, -1, 1],
2219
- [0, 1, -1],
2220
- [0, -1, -1]
2221
- ];
2222
- this.p = [];
2223
- for (let i = 0; i < 256; i++) {
2224
- this.p.push(Math.floor(rng.nextFloat() * 256));
2225
- }
2226
- this.perm = [];
2227
- for (let i = 0; i < 512; i++) {
2228
- this.perm.push(this.p[i & 255]);
2229
- }
2230
- }
2231
- dot(g, x, y, z) {
2232
- return g[0] * x + g[1] * y + (typeof z === "number" ? g[2] * z : 0);
2233
- }
2234
- noise2d(xin, yin) {
2235
- let n0, n1, n2;
2236
- const F2 = 0.5 * (Math.sqrt(3) - 1);
2237
- const s = (xin + yin) * F2;
2238
- let i = Math.floor(xin + s);
2239
- let j = Math.floor(yin + s);
2240
- const G2 = (3 - Math.sqrt(3)) / 6;
2241
- const t = (i + j) * G2;
2242
- const X0 = i - t;
2243
- const Y0 = j - t;
2244
- const x0 = xin - X0;
2245
- const y0 = yin - Y0;
2246
- let i1, j1;
2247
- if (x0 > y0) {
2248
- i1 = 1;
2249
- j1 = 0;
2250
- } else {
2251
- i1 = 0;
2252
- j1 = 1;
2253
- }
2254
- const x1 = x0 - i1 + G2;
2255
- const y1 = y0 - j1 + G2;
2256
- const x2 = x0 - 1 + 2 * G2;
2257
- const y2 = y0 - 1 + 2 * G2;
2258
- const ii = i & 255;
2259
- const jj = j & 255;
2260
- const gi0 = this.perm[ii + this.perm[jj]] % 12;
2261
- const gi1 = this.perm[ii + i1 + this.perm[jj + j1]] % 12;
2262
- const gi2 = this.perm[ii + 1 + this.perm[jj + 1]] % 12;
2263
- let t0 = 0.5 - x0 * x0 - y0 * y0;
2264
- if (t0 < 0) {
2265
- n0 = 0;
2266
- } else {
2267
- t0 *= t0;
2268
- n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0);
2269
- }
2270
- let t1 = 0.5 - x1 * x1 - y1 * y1;
2271
- if (t1 < 0) {
2272
- n1 = 0;
2273
- } else {
2274
- t1 *= t1;
2275
- n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1);
2276
- }
2277
- let t2 = 0.5 - x2 * x2 - y2 * y2;
2278
- if (t2 < 0) {
2279
- n2 = 0;
2280
- } else {
2281
- t2 *= t2;
2282
- n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2);
2283
- }
2284
- return 70 * (n0 + n1 + n2);
2285
- }
2286
- noise3d(xin, yin, zin) {
2287
- let n0, n1, n2, n3;
2288
- const F3 = 1 / 3;
2289
- const s = (xin + yin + zin) * F3;
2290
- const i = Math.floor(xin + s);
2291
- const j = Math.floor(yin + s);
2292
- const k = Math.floor(zin + s);
2293
- const G3 = 1 / 6;
2294
- const t = (i + j + k) * G3;
2295
- const X0 = i - t;
2296
- const Y0 = j - t;
2297
- const Z0 = k - t;
2298
- const x0 = xin - X0;
2299
- const y0 = yin - Y0;
2300
- const z0 = zin - Z0;
2301
- let i1, j1, k1;
2302
- let i2, j2, k2;
2303
- if (x0 >= y0) {
2304
- if (y0 >= z0) {
2305
- i1 = 1;
2306
- j1 = 0;
2307
- k1 = 0;
2308
- i2 = 1;
2309
- j2 = 1;
2310
- k2 = 0;
2311
- } else if (x0 >= z0) {
2312
- i1 = 1;
2313
- j1 = 0;
2314
- k1 = 0;
2315
- i2 = 1;
2316
- j2 = 0;
2317
- k2 = 1;
2318
- } else {
2319
- i1 = 0;
2320
- j1 = 0;
2321
- k1 = 1;
2322
- i2 = 1;
2323
- j2 = 0;
2324
- k2 = 1;
2325
- }
2326
- } else {
2327
- if (y0 < z0) {
2328
- i1 = 0;
2329
- j1 = 0;
2330
- k1 = 1;
2331
- i2 = 0;
2332
- j2 = 1;
2333
- k2 = 1;
2334
- } else if (x0 < z0) {
2335
- i1 = 0;
2336
- j1 = 1;
2337
- k1 = 0;
2338
- i2 = 0;
2339
- j2 = 1;
2340
- k2 = 1;
2341
- } else {
2342
- i1 = 0;
2343
- j1 = 1;
2344
- k1 = 0;
2345
- i2 = 1;
2346
- j2 = 1;
2347
- k2 = 0;
2348
- }
2349
- }
2350
- const x1 = x0 - i1 + G3;
2351
- const y1 = y0 - j1 + G3;
2352
- const z1 = z0 - k1 + G3;
2353
- const x2 = x0 - i2 + 2 * G3;
2354
- const y2 = y0 - j2 + 2 * G3;
2355
- const z2 = z0 - k2 + 2 * G3;
2356
- const x3 = x0 - 1 + 3 * G3;
2357
- const y3 = y0 - 1 + 3 * G3;
2358
- const z3 = z0 - 1 + 3 * G3;
2359
- const ii = i & 255;
2360
- const jj = j & 255;
2361
- const kk = k & 255;
2362
- const gi0 = this.perm[ii + this.perm[jj + this.perm[kk]]] % 12;
2363
- const gi1 = this.perm[ii + i1 + this.perm[jj + j1 + this.perm[kk + k1]]] % 12;
2364
- const gi2 = this.perm[ii + i2 + this.perm[jj + j2 + this.perm[kk + k2]]] % 12;
2365
- const gi3 = this.perm[ii + 1 + this.perm[jj + 1 + this.perm[kk + 1]]] % 12;
2366
- let t0 = 0.6 - x0 * x0 - y0 * y0 - z0 * z0;
2367
- if (t0 < 0) {
2368
- n0 = 0;
2369
- } else {
2370
- t0 *= t0;
2371
- n0 = t0 * t0 * this.dot(this.grad3[gi0], x0, y0, z0);
2372
- }
2373
- let t1 = 0.6 - x1 * x1 - y1 * y1 - z1 * z1;
2374
- if (t1 < 0) {
2375
- n1 = 0;
2376
- } else {
2377
- t1 *= t1;
2378
- n1 = t1 * t1 * this.dot(this.grad3[gi1], x1, y1, z1);
2379
- }
2380
- let t2 = 0.6 - x2 * x2 - y2 * y2 - z2 * z2;
2381
- if (t2 < 0) {
2382
- n2 = 0;
2383
- } else {
2384
- t2 *= t2;
2385
- n2 = t2 * t2 * this.dot(this.grad3[gi2], x2, y2, z2);
2386
- }
2387
- let t3 = 0.6 - x3 * x3 - y3 * y3 - z3 * z3;
2388
- if (t3 < 0) {
2389
- n3 = 0;
2390
- } else {
2391
- t3 *= t3;
2392
- n3 = t3 * t3 * this.dot(this.grad3[gi3], x3, y3, z3);
2393
- }
2394
- return 32 * (n0 + n1 + n2 + n3);
2395
- }
2396
- };
2397
-
2398
- // src/spatial-partition-3d.ts
2399
- var SpatialPartition3d = class {
2400
- cells;
2401
- cellSize;
2402
- entities;
2403
- constructor(cellSize, entities) {
2404
- this.cellSize = cellSize;
2405
- this.entities = entities;
2406
- const gridSize = Math.ceil(1 / cellSize);
2407
- this.cells = Array.from(
2408
- { length: gridSize },
2409
- () => Array.from(
2410
- { length: gridSize },
2411
- () => Array.from({ length: gridSize }, () => [])
2412
- )
2413
- );
2414
- for (const entity of this.entities) {
2415
- this.addEntity(entity);
2416
- }
2417
- }
2418
- getCell(x, y, z) {
2419
- const cx = Math.floor(x / this.cellSize);
2420
- const cy = Math.floor(y / this.cellSize);
2421
- const cz = Math.floor(z / this.cellSize);
2422
- return this.cells[cz][cy][cx];
2423
- }
2424
- getCellNeighbors(cx, cy, cz) {
2425
- const neighbors = [];
2426
- const gridSize = this.cells.length;
2427
- for (let dz = -1; dz <= 1; dz++) {
2428
- for (let dy = -1; dy <= 1; dy++) {
2429
- for (let dx = -1; dx <= 1; dx++) {
2430
- let nx = (cx + dx + gridSize) % gridSize;
2431
- let ny = (cy + dy + gridSize) % gridSize;
2432
- let nz = (cz + dz + gridSize) % gridSize;
2433
- neighbors.push(this.cells[nz][ny][nx]);
2434
- }
2435
- }
2436
- }
2437
- return neighbors;
2438
- }
2439
- addEntity(entity) {
2440
- const cell = this.getCell(entity.x, entity.y, entity.z);
2441
- cell.push(entity);
2442
- }
2443
- };
2444
-
2445
- // src/three/asteroid-mesh.ts
2446
- import { IcosahedronGeometry, Mesh, MeshStandardMaterial } from "three";
2447
- import { createNoise3D as createNoise3D2 } from "simplex-noise";
2448
- var AsteroidMesh = class extends Mesh {
2449
- constructor(options = {}) {
2450
- const radius = options.radius ?? 1;
2451
- const detail = options.detail ?? 1;
2452
- const noiseScale = options.noiseScale ?? 1;
2453
- const displacement = options.displacement ?? 0.1;
2454
- const secondaryNoise = options.secondaryNoise ?? false;
2455
- const color = options.color ?? 8947848;
2456
- const geometry = new IcosahedronGeometry(radius, detail);
2457
- const material = new MeshStandardMaterial({ color });
2458
- super(geometry, material);
2459
- const noise3d = createNoise3D2(rng.nextFloat);
2460
- const noise3d2 = secondaryNoise ? createNoise3D2(rng.nextFloat) : null;
2461
- const position = this.geometry.attributes.position;
2462
- const vertices = position.array;
2463
- for (let i = 0; i < vertices.length; i += 3) {
2464
- const x = vertices[i];
2465
- const y = vertices[i + 1];
2466
- const z = vertices[i + 2];
2467
- const n1 = noise3d(x * noiseScale, y * noiseScale, z * noiseScale);
2468
- const n2 = secondaryNoise ? 0.5 * noise3d2(x * noiseScale * 2, y * noiseScale * 2, z * noiseScale * 2) : 0;
2469
- const noiseValue = n1 + n2;
2470
- const displacementValue = 1 + noiseValue * displacement;
2471
- vertices[i] = x * displacementValue;
2472
- vertices[i + 1] = y * displacementValue;
2473
- vertices[i + 2] = z * displacementValue;
2474
- }
2475
- position.needsUpdate = true;
2476
- this.geometry.computeVertexNormals();
2477
- }
2478
- };
2479
-
2480
- // src/three/atlas-texture-material.ts
2481
- import { MeshLambertMaterial, NearestFilter as NearestFilter2 } from "three";
2482
-
2483
- // src/three/texture-utils.ts
2484
- import { NearestFilter, RepeatWrapping, TextureLoader } from "three";
2485
- function LoadTexture(url) {
2486
- return new Promise((res, rej) => {
2487
- new TextureLoader().load(
2488
- url,
2489
- (texture) => {
2490
- const width = texture.source.data.width;
2491
- const height = texture.source.data.height;
2492
- res({ width, height, texture });
2493
- },
2494
- (_ev) => {
2495
- },
2496
- (err) => rej(err)
2497
- );
2498
- });
2499
- }
2500
- function CreateSubTexture(texture, x, y, w, h) {
2501
- const subTexture = texture.clone();
2502
- subTexture.magFilter = NearestFilter;
2503
- subTexture.wrapS = RepeatWrapping;
2504
- w /= subTexture.width;
2505
- h /= subTexture.height;
2506
- x /= subTexture.width;
2507
- y = 1 - h - y / subTexture.height;
2508
- subTexture.offset.set(x, y);
2509
- subTexture.repeat.set(w, h);
2510
- subTexture.needsUpdate = true;
2511
- return subTexture;
2512
- }
2513
-
2514
- // src/three/atlas-texture-material.ts
2515
- var AtlasTextureMaterial = class _AtlasTextureMaterial extends MeshLambertMaterial {
2516
- textureData;
2517
- tilePixelWidth;
2518
- tilePixelHeight;
2519
- _tileCount;
2520
- _uvWidth;
2521
- _uvHeight;
2522
- _textureOffsetWidth;
2523
- _textureOffsetHeight;
2524
- constructor(textureData, atlasParams = {}, materialParams = {}) {
2525
- super({
2526
- map: textureData.texture,
2527
- alphaTest: 0.1,
2528
- transparent: true,
2529
- name: "AtlasTextureMaterial",
2530
- ...materialParams
2531
- });
2532
- this.textureData = textureData;
2533
- this.textureData.texture.magFilter = NearestFilter2;
2534
- this.tilePixelWidth = atlasParams.tilePixelWidth ?? 16;
2535
- this.tilePixelHeight = atlasParams.tilePixelHeight ?? 16;
2536
- this._textureOffsetWidth = atlasParams.tilePixelOffsetWidth ?? 0;
2537
- this._textureOffsetHeight = atlasParams.tilePixelOffsetHeight ?? 0;
2538
- this._tileCount = Math.floor(this.textureData.width / this.tilePixelWidth);
2539
- this._uvWidth = this.tilePixelWidth / (this.textureData.width - this._textureOffsetWidth);
2540
- this._uvHeight = this.tilePixelHeight / (this.textureData.height - this._textureOffsetHeight);
2541
- }
2542
- getTileUVs(tileIndex, vertexIndex) {
2543
- const col = tileIndex % this._tileCount;
2544
- const row = Math.floor(tileIndex / this._tileCount);
2545
- const baseU = this._textureOffsetWidth / this.textureData.width + col * this._uvWidth;
2546
- const baseV = this._textureOffsetHeight / this.textureData.height + row * this._uvHeight;
2547
- const uvCorners = [
2548
- [0, 0],
2549
- // bottom-left
2550
- [1, 0],
2551
- // bottom-right
2552
- [0, 1],
2553
- // top-left
2554
- [1, 1]
2555
- // top-right
2556
- ];
2557
- const [u, v] = uvCorners[vertexIndex];
2558
- const uvx = baseU + u * this._uvWidth;
2559
- const uvy = 1 - (baseV + v * this._uvHeight);
2560
- return [uvx, uvy];
2561
- }
2562
- static fromUrl(url, atlasParams = {}, materialParams = {}) {
2563
- return LoadTexture(url).then((textureData) => new _AtlasTextureMaterial(
2564
- textureData,
2565
- atlasParams,
2566
- materialParams
2567
- ));
2568
- }
2569
- };
2570
-
2571
- // src/three/camera-rig.ts
2572
- import { PerspectiveCamera, Group } from "three";
2573
- var DEFAULT_CAMERA_ASPECT = 2;
2574
- var DEFAULT_CAMERA_DISTANCE = 5;
2575
- var DEFAULT_CAMERA_FAR = 1e3;
2576
- var DEFAULT_CAMERA_FOV = 70;
2577
- var DEFAULT_CAMERA_MAX_DISTANCE = 50;
2578
- var DEFAULT_CAMERA_MIN_DISTANCE = 1.5;
2579
- var DEFAULT_CAMERA_NEAR = 0.1;
2580
- var DEFAULT_GIMBLE_CLAMP_ANGLE = false;
2581
- var DEFAULT_GIMBLE_MAX_ANGLE = 0;
2582
- var DEFAULT_GIMBLE_MIN_ANGLE = radians(-90);
2583
- var DEFAULT_MOUSE_SENSITIVITY = 0.01;
2584
- var DEFAULT_WHEEL_SENSITIVITY = 0.02;
2585
- var CameraRig = class extends Group {
2586
- gimbal;
2587
- camera;
2588
- _target;
2589
- clampTiltAngle = DEFAULT_GIMBLE_CLAMP_ANGLE;
2590
- maxDistance = DEFAULT_CAMERA_MAX_DISTANCE;
2591
- maxTiltAngle = DEFAULT_GIMBLE_MAX_ANGLE;
2592
- minDistance = DEFAULT_CAMERA_MIN_DISTANCE;
2593
- minTiltAngle = DEFAULT_GIMBLE_MIN_ANGLE;
2594
- mouseSensitivity = DEFAULT_MOUSE_SENSITIVITY;
2595
- wheelSensitivity = DEFAULT_WHEEL_SENSITIVITY;
2596
- constructor(params) {
2597
- super();
2598
- this.gimbal = new Group();
2599
- this.add(this.gimbal);
2600
- this.camera = new PerspectiveCamera(
2601
- params?.fov ?? DEFAULT_CAMERA_FOV,
2602
- params?.aspect ?? DEFAULT_CAMERA_ASPECT,
2603
- params?.near ?? DEFAULT_CAMERA_NEAR,
2604
- params?.far ?? DEFAULT_CAMERA_FAR
2605
- );
2606
- this.gimbal.add(this.camera);
2607
- this.camera.position.z = DEFAULT_CAMERA_DISTANCE;
2608
- this.gimbal.rotateX(radians(-45));
2609
- this.rotateY(radians(45));
2610
- }
2611
- setTarget(target) {
2612
- if (target) {
2613
- this.rotation.set(0, 0, 0);
2614
- this.position.set(0, 0, 0);
2615
- target.add(this);
2616
- }
2617
- this._target = target;
2618
- }
2619
- orbit(deltaX, deltaY) {
2620
- (this._target ?? this).rotateY(-deltaX * this.mouseSensitivity);
2621
- this.gimbal.rotation.x = this.clampTiltAngle ? clamp(
2622
- this.gimbal.rotation.x + -deltaY * this.mouseSensitivity,
2623
- this.minTiltAngle,
2624
- this.maxTiltAngle
2625
- ) : this.gimbal.rotation.x + -deltaY * this.mouseSensitivity;
2626
- }
2627
- dolly(deltaY) {
2628
- this.camera.position.z = clamp(
2629
- this.camera.position.z + deltaY * this.wheelSensitivity,
2630
- this.minDistance,
2631
- this.maxDistance
2632
- );
2633
- }
2634
- };
2635
-
2636
- // src/three/cube-sphere-geometry.ts
2637
- import { BoxGeometry, Vector3 } from "three";
2638
- var CubeSphereGeometry = class extends BoxGeometry {
2639
- constructor(size, segments) {
2640
- size = Math.floor(size);
2641
- segments = Math.floor(segments);
2642
- super(size, size, size, segments, segments, segments);
2643
- this.size = size;
2644
- this.segments = segments;
2645
- this._halfSize = this.size / 2;
2646
- const attrPositions = this.attributes.position;
2647
- const position = new Vector3();
2648
- for (let i = 0; i < attrPositions.count; i++) {
2649
- position.fromBufferAttribute(attrPositions, i);
2650
- position.normalize().multiplyScalar(this._halfSize);
2651
- attrPositions.setXYZ(i, position.x, position.y, position.z);
2652
- }
2653
- attrPositions.needsUpdate = true;
2654
- }
2655
- _halfSize;
2656
- applyFractalBrownianMotion(octaves, persistence, scale, amplitude) {
2657
- const attrPositions = this.attributes.position;
2658
- const position = new Vector3();
2659
- for (let i = 0; i < attrPositions.count; i++) {
2660
- position.fromBufferAttribute(attrPositions, i);
2661
- position.normalize().multiplyScalar(this._halfSize);
2662
- const noiseValue = this.fBm(position.x * scale, position.y * scale, position.z * scale, octaves, persistence);
2663
- position.addScaledVector(position.clone().normalize(), noiseValue * amplitude);
2664
- attrPositions.setXYZ(i, position.x, position.y, position.z);
2665
- }
2666
- attrPositions.needsUpdate = true;
2667
- }
2668
- fBm(x, y, z, octaves, persistence) {
2669
- let total = 0;
2670
- let frequency = 1;
2671
- let amplitude = 1;
2672
- let maxValue = 0;
2673
- for (let i = 0; i < octaves; i++) {
2674
- total += Noise.noise3d(x * frequency, y * frequency, z * frequency) * amplitude;
2675
- maxValue += amplitude;
2676
- amplitude *= persistence;
2677
- frequency *= 2;
2678
- }
2679
- return total / maxValue;
2680
- }
2681
- };
2682
-
2683
- // src/three/ecs.ts
2684
- import { Group as Group2 } from "three";
2685
- var entityCounter = 0;
2686
- function GenerateEntityId() {
2687
- return `entity_${entityCounter++}`;
2688
- }
2689
- function CreateThreeEntity(obj) {
2690
- const entity = obj ?? new Group2();
2691
- entity.userData.entityId = GenerateEntityId();
2692
- entity.userData.components = {};
2693
- return entity;
2694
- }
2695
- function AddThreeComponent(entity, name, component) {
2696
- entity.userData.components[name] = component;
2697
- }
2698
- function GetThreeComponent(entity, name) {
2699
- return entity.userData.components[name];
2700
- }
2701
- function RemoveThreeComponent(entity, name) {
2702
- delete entity.userData.components[name];
2703
- }
2704
- function IsThreeEntity(obj) {
2705
- return obj.userData.entityId !== void 0;
2706
- }
2707
-
2708
- // src/three/palette-controller.ts
2709
- import { Color as Color2, Vector3 as Vector32 } from "three";
2710
- async function CreatePaletteController(parentGui, colorPalette, onChange, folderName = "palette") {
2711
- const { Controller } = await import("three/examples/jsm/libs/lil-gui.module.min.js");
2712
- class PaletteControllerImpl extends Controller {
2713
- $innerDiv;
2714
- colorButtons = [];
2715
- colorButtonSize = 20;
2716
- selectedBorderStyle = "2px dashed black";
2717
- currentColorIndex = 0;
2718
- eyedropperButton;
2719
- colorPalette;
2720
- _onColorChange;
2721
- constructor() {
2722
- const parent = parentGui.addFolder(folderName);
2723
- super(parent, {}, "", "function");
2724
- this.colorPalette = colorPalette;
2725
- this._onColorChange = onChange;
2726
- this.$widget.style.setProperty("display", "flex");
2727
- this.$widget.style.setProperty("justify-content", "center");
2728
- this.$innerDiv = document.createElement("div");
2729
- this.$innerDiv.style.setProperty("display", "flex");
2730
- this.$innerDiv.style.setProperty("flex-wrap", "wrap");
2731
- this.$innerDiv.style.setProperty("width", `${this.colorButtonSize * Math.floor(Math.sqrt(this.colorPalette.length)) + 2}px`);
2732
- this.$innerDiv.appendChild(this.$name);
2733
- this.$widget.appendChild(this.$innerDiv);
2734
- this.colorPalette.forEach((color) => this._createColorButton(color));
2735
- if (window.EyeDropper) {
2736
- this.eyedropperButton = parent.add({
2737
- eyedropper: () => {
2738
- this.eyedropperButton?.disable(true);
2739
- new window.EyeDropper().open().then(({ sRGBHex }) => {
2740
- const i = this.findClosestColorMatchIndex(sRGBHex);
2741
- this.setSelectedColor(i);
2742
- this._onColorChange?.(i);
2743
- }).finally(() => this.eyedropperButton?.disable(false)).catch(() => {
2744
- });
2745
- }
2746
- }, "eyedropper").name("findClosestColor");
2747
- }
2748
- this.name("");
2749
- this.updateDisplay();
2750
- }
2751
- _onColorButtonClicked(i, button) {
2752
- if (button === 0) {
2753
- this.setSelectedColor(i);
2754
- this._onColorChange?.(i);
2755
- this.colorButtons[i].blur();
2756
- } else if (button === 2 && window.EyeDropper) {
2757
- new window.EyeDropper().open().then(({ sRGBHex }) => {
2758
- this.colorPalette[i] = sRGBHex;
2759
- this.colorButtons[i].setAttribute("title", `${sRGBHex}`);
2760
- this.colorButtons[i].style.setProperty("background", sRGBHex);
2761
- this.setSelectedColor(i);
2762
- this._onColorChange?.(i);
2763
- this.colorButtons[i].blur();
2764
- }).finally(() => this.eyedropperButton?.disable(false)).catch(() => {
2765
- });
2766
- }
2767
- }
2768
- _createColorButton(color) {
2769
- const i = this.colorButtons.length;
2770
- const colorButton = document.createElement("div");
2771
- colorButton.setAttribute("id", `colorButton${i}`);
2772
- colorButton.setAttribute("title", `${color}`);
2773
- colorButton.style.setProperty("width", `${this.colorButtonSize}px`);
2774
- colorButton.style.setProperty("height", `${this.colorButtonSize}px`);
2775
- colorButton.style.setProperty("background", color);
2776
- colorButton.addEventListener("pointerup", (ev) => this._onColorButtonClicked(i, ev.button));
2777
- this.colorButtons.push(colorButton);
2778
- this.$innerDiv.appendChild(colorButton);
2779
- }
2780
- updatePaletteColors() {
2781
- this.colorPalette.forEach((color, i) => {
2782
- if (i < this.colorButtons.length) {
2783
- this.colorButtons[i].setAttribute("title", `${color}`);
2784
- this.colorButtons[i].style.setProperty("background", color);
2785
- } else {
2786
- this._createColorButton(color);
2787
- }
2788
- });
2789
- }
2790
- setSelectedColor(colorIndex = 0) {
2791
- this.colorButtons[this.currentColorIndex].style.removeProperty("border");
2792
- this.currentColorIndex = clamp(colorIndex, 0, this.colorPalette.length);
2793
- this.colorButtons[this.currentColorIndex].style.setProperty("border", this.selectedBorderStyle);
2794
- }
2795
- findClosestColorMatchIndex(color) {
2796
- const pickedColor = new Color2(color);
2797
- const pickedVector = new Vector32().setFromColor(pickedColor);
2798
- const list = [];
2799
- this.colorPalette.forEach((paletteColorString, i) => {
2800
- const paletteColor = new Color2(paletteColorString);
2801
- const paletteVector = new Vector32().setFromColor(paletteColor);
2802
- const d = paletteVector.distanceTo(pickedVector);
2803
- list.push({ i, d });
2804
- });
2805
- list.sort((a, b) => a.d - b.d);
2806
- const closest = list.shift();
2807
- return closest?.i ?? 0;
2808
- }
2809
- }
2810
- return new PaletteControllerImpl();
2811
- }
2812
-
2813
- // src/three/particle-system-3d.ts
2814
- import { BufferGeometry, Float32BufferAttribute, Group as Group3, Points, ShaderMaterial, Vector3 as Vector33 } from "three";
2815
- var vertexShader = `
2816
- uniform float pointSize;
2817
-
2818
- varying vec4 vColor;
2819
-
2820
- void main() {
2821
- vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
2822
-
2823
- gl_Position = projectionMatrix * mvPosition;
2824
- gl_PointSize = pointSize;
2825
-
2826
- vColor = color;
2827
- }`;
2828
- var fragmentShader = `
2829
- varying vec4 vColor;
2830
-
2831
- void main() {
2832
- gl_FragColor = vColor;
2833
- }`;
2834
- var Colors = [
2835
- [1, 0, 0, 1],
2836
- // red
2837
- [0, 1, 0, 1],
2838
- // green,
2839
- [0, 0, 1, 1],
2840
- // blue,
2841
- [1, 1, 0, 1],
2842
- // yellow,
2843
- [1, 0, 1, 1]
2844
- // magenta,
2845
- ];
2846
- var ParticleSystem3d = class extends Group3 {
2847
- particleCount = 1e3;
2848
- _geometry;
2849
- _particles = [];
2850
- _frictionHalfLife = 0.04;
2851
- _range = 0.2;
2852
- _rangeFactor = 0.1;
2853
- _attractionMatrix;
2854
- _spatialPartition;
2855
- constructor() {
2856
- super();
2857
- const uniforms = {
2858
- pointSize: { value: 4 }
2859
- };
2860
- this.position.x = -0.5;
2861
- this.position.y = -0.5;
2862
- this.position.z = -0.5;
2863
- this._geometry = new BufferGeometry();
2864
- this._geometry.setAttribute("position", new Float32BufferAttribute([], 3));
2865
- this._geometry.setAttribute("color", new Float32BufferAttribute([], 4));
2866
- const material = new ShaderMaterial({
2867
- uniforms,
2868
- vertexShader,
2869
- fragmentShader,
2870
- depthTest: true,
2871
- depthWrite: false,
2872
- vertexColors: true
2873
- });
2874
- const pointsMesh = new Points(this._geometry, material);
2875
- this.add(pointsMesh);
2876
- for (let i = 0; i < this.particleCount; i++) {
2877
- this._particles.push({
2878
- x: rng.nextFloat(),
2879
- y: rng.nextFloat(),
2880
- z: rng.nextFloat(),
2881
- vx: 0,
2882
- vy: 0,
2883
- vz: 0,
2884
- color: rng.range(Colors.length)
2885
- });
2886
- }
2887
- this._attractionMatrix = randomMatrix(Colors.length);
2888
- this._spatialPartition = new SpatialPartition3d(this._range, this._particles);
2889
- }
2890
- _calcForce(r, a, beta = 0.3) {
2891
- let f = 0;
2892
- if (r < beta) {
2893
- f = r / beta - 1;
2894
- } else if (beta < r && r < 1) {
2895
- f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
2896
- }
2897
- return f;
2898
- }
2899
- _updateVelocities(dt) {
2900
- const frictionFactor = Math.pow(
2901
- 0.5,
2902
- dt / this._frictionHalfLife
2903
- );
2904
- for (let z = 0; z < this._spatialPartition.cells.length; z++) {
2905
- for (let y = 0; y < this._spatialPartition.cells[z].length; y++) {
2906
- for (let x = 0; x < this._spatialPartition.cells[z][y].length; x++) {
2907
- const cell = this._spatialPartition.cells[z][y][x];
2908
- for (let i = 0; i < cell.length; i++) {
2909
- let fx = 0, fy = 0, fz = 0;
2910
- const p1 = cell[i];
2911
- const neighbors = this._spatialPartition.getCellNeighbors(x, y, z);
2912
- for (const neighborCell of neighbors) {
2913
- for (let j = 0; j < neighborCell.length; j++) {
2914
- if (cell === neighborCell && i === j) continue;
2915
- const p2 = neighborCell[j];
2916
- let dx = p2.x - p1.x;
2917
- let dy = p2.y - p1.y;
2918
- let dz = p2.z - p1.z;
2919
- if (Math.abs(dx) > 0.5) dx = dx > 0 ? dx - 1 : dx + 1;
2920
- if (Math.abs(dy) > 0.5) dy = dy > 0 ? dy - 1 : dy + 1;
2921
- if (Math.abs(dz) > 0.5) dz = dz > 0 ? dz - 1 : dz + 1;
2922
- const dist = Math.hypot(dx, dy, dz);
2923
- if (dist > 0 && dist < this._range) {
2924
- const f = this._calcForce(dist / this._range, this._attractionMatrix[p1.color][p2.color]);
2925
- fx += dx / dist * f;
2926
- fy += dy / dist * f;
2927
- fz += dz / dist * f;
2928
- }
2929
- }
2930
- }
2931
- fx *= this._range * this._rangeFactor;
2932
- fy *= this._range * this._rangeFactor;
2933
- fz *= this._range * this._rangeFactor;
2934
- p1.vx *= frictionFactor;
2935
- p1.vy *= frictionFactor;
2936
- p1.vz *= frictionFactor;
2937
- p1.vx += fx;
2938
- p1.vy += fy;
2939
- p1.vz += fz;
2940
- }
2941
- }
2942
- }
2943
- }
2944
- }
2945
- _updatePositions(dt) {
2946
- for (let i = 0; i < this._particles.length; i++) {
2947
- const particle = this._particles[i];
2948
- const oldCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
2949
- particle.x += particle.vx * dt;
2950
- particle.y += particle.vy * dt;
2951
- particle.z += particle.vz * dt;
2952
- if (particle.x < 0) particle.x = (particle.x + 1) % 1;
2953
- if (particle.x > 1) particle.x = particle.x % 1;
2954
- if (particle.y < 0) particle.y = (particle.y + 1) % 1;
2955
- if (particle.y > 1) particle.y = particle.y % 1;
2956
- if (particle.z < 0) particle.z = (particle.z + 1) % 1;
2957
- if (particle.z > 1) particle.z = particle.z % 1;
2958
- const newCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
2959
- if (newCell !== oldCell) {
2960
- const index = oldCell.indexOf(particle);
2961
- if (index !== -1) {
2962
- oldCell.splice(index, 1);
2963
- }
2964
- newCell.push(particle);
2965
- }
2966
- }
2967
- }
2968
- _sortParticles(camera) {
2969
- this._particles.sort((a, b) => {
2970
- const d1 = camera.position.distanceTo(new Vector33(a.x, a.y, a.z));
2971
- const d2 = camera.position.distanceTo(new Vector33(b.x, b.y, b.z));
2972
- return d1 > d2 ? -1 : d1 > d1 ? 1 : 0;
2973
- });
2974
- }
2975
- _updateGeometry() {
2976
- const positions = [];
2977
- const colors2 = [];
2978
- for (const particle of this._particles) {
2979
- positions.push(
2980
- particle.x,
2981
- particle.y,
2982
- particle.z
2983
- );
2984
- colors2.push(
2985
- Colors[particle.color][0],
2986
- Colors[particle.color][1],
2987
- Colors[particle.color][2],
2988
- Colors[particle.color][3]
2989
- );
2990
- }
2991
- this._geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
2992
- this._geometry.setAttribute("color", new Float32BufferAttribute(colors2, 4));
2993
- this._geometry.attributes.position.needsUpdate = true;
2994
- }
2995
- update(camera, dt) {
2996
- this._updateVelocities(dt);
2997
- this._updatePositions(dt);
2998
- this._sortParticles(camera);
2999
- this._updateGeometry();
3000
- }
3001
- };
3002
-
3003
- // src/three/renderer.ts
3004
- import { WebGLRenderer } from "three";
3005
- var Renderer = class extends WebGLRenderer {
3006
- get width() {
3007
- return this.domElement.width;
3008
- }
3009
- get height() {
3010
- return this.domElement.height;
3011
- }
3012
- get aspectRatio() {
3013
- return this.width / this.height;
3014
- }
3015
- constructor(parameters) {
3016
- super(parameters);
3017
- this.setPixelRatio(window.devicePixelRatio);
3018
- }
3019
- resize(width, height) {
3020
- let resized = false;
3021
- width = width ?? this.domElement.parentElement?.clientWidth ?? this.width;
3022
- height = height ?? this.domElement.parentElement?.clientHeight ?? this.height;
3023
- if (this.width !== width || this.height !== height) {
3024
- this.setSize(width, height);
3025
- resized = true;
3026
- }
3027
- return resized;
3028
- }
3029
- };
3030
-
3031
- // src/three/starfield.ts
3032
- import { BufferAttribute, BufferGeometry as BufferGeometry2, Group as Group4, Mesh as Mesh2, MeshBasicMaterial, PointLight, Points as Points2, PointsMaterial, SphereGeometry, Vector3 as Vector34 } from "three";
3033
- function CreateStarfield(radius = 1e3, count = 5e3, color = 16777215) {
3034
- const geometry = new BufferGeometry2();
3035
- const positions = new Float32Array(count * 3);
3036
- for (let i = 0; i < count; i++) {
3037
- const theta = rng.nextFloat() * Math.PI * 2;
3038
- const phi = Math.acos(rng.nextFloat() * 2 - 1);
3039
- const x = radius * Math.sin(phi) * Math.cos(theta);
3040
- const y = radius * Math.sin(phi) * Math.sin(theta);
3041
- const z = radius * Math.cos(phi);
3042
- positions.set([x, y, z], i * 3);
3043
- }
3044
- geometry.setAttribute("position", new BufferAttribute(positions, 3));
3045
- const material = new PointsMaterial({
3046
- color,
3047
- size: 5,
3048
- sizeAttenuation: true,
3049
- transparent: true,
3050
- opacity: 0.9
3051
- });
3052
- const stars = new Points2(geometry, material);
3053
- stars.name = "Starfield";
3054
- return stars;
3055
- }
3056
- function CreateSystemStar(position) {
3057
- const star = new Group4();
3058
- const starPos = position ?? new Vector34();
3059
- const starGeo = new SphereGeometry(50, 32, 32);
3060
- const starMat = new MeshBasicMaterial({ color: 16768426 });
3061
- const starMesh = new Mesh2(starGeo, starMat);
3062
- starMesh.position.copy(starPos);
3063
- star.add(starMesh);
3064
- const starLight = new PointLight(16777215, 10, 0, 0);
3065
- starLight.position.copy(starPos);
3066
- star.add(starLight);
3067
- return star;
3068
- }
3069
-
3070
- // src/three/texture-atlas.ts
3071
- import { MeshLambertMaterial as MeshLambertMaterial2, NearestFilter as NearestFilter3 } from "three";
3072
- var TextureAtlas = class _TextureAtlas extends MeshLambertMaterial2 {
3073
- constructor(textureData, textureWidth, textureHeight = textureWidth, params) {
3074
- super({
3075
- map: textureData.texture,
3076
- alphaTest: 0.1,
3077
- transparent: true,
3078
- ...params ?? {}
3079
- });
3080
- this.textureData = textureData;
3081
- this.textureWidth = textureWidth;
3082
- this.textureHeight = textureHeight;
3083
- this._uw = this.textureWidth / this.textureData.width;
3084
- this._uh = this.textureHeight / this.textureData.height;
3085
- this.textureData.texture.magFilter = NearestFilter3;
3086
- }
3087
- _uw;
3088
- _uh;
3089
- getUv(voxel, ux, uy) {
3090
- return [
3091
- (voxel + ux) * this._uw,
3092
- 1 - (1 - uy) * this._uh
3093
- ];
3094
- }
3095
- static CreateFromUrl(url, textureWidth, textureHeight = textureWidth, params) {
3096
- return LoadTexture(url).then((textureData) => new _TextureAtlas(
3097
- textureData,
3098
- textureWidth,
3099
- textureHeight,
3100
- params
3101
- ));
3102
- }
3103
- };
3104
-
3105
- // src/three/threejs-camera-rig.ts
3106
- import { PerspectiveCamera as PerspectiveCamera3, Group as Group5 } from "three";
3107
- var ThreeJsCameraRig = class extends Group5 {
3108
- gimbal;
3109
- camera;
3110
- target;
3111
- mouseSensitivity = 0.01;
3112
- wheelSensitivity = 0.02;
3113
- minCameraDistance = 2;
3114
- maxCameraDistance = 100;
3115
- minTiltAngle = degrees(-90);
3116
- maxTiltAngle = degrees(0);
3117
- clampTiltAngle = false;
3118
- constructor(params) {
3119
- super();
3120
- this.gimbal = new Group5();
3121
- this.add(this.gimbal);
3122
- this.camera = params?.camera ?? new PerspectiveCamera3(
3123
- params?.fov ?? 75,
3124
- params?.aspect ?? 2,
3125
- params?.near ?? 0.1,
3126
- params?.far ?? 1e3
3127
- );
3128
- this.gimbal.add(this.camera);
3129
- }
3130
- orbit(deltaX, deltaY) {
3131
- (this.target || this).rotateY(-deltaX * this.mouseSensitivity);
3132
- this.gimbal.rotation.x = this.clampTiltAngle ? clamp(
3133
- this.gimbal.rotation.x + -deltaY * this.mouseSensitivity,
3134
- this.minTiltAngle,
3135
- this.maxTiltAngle
3136
- ) : this.gimbal.rotation.x + -deltaY * this.mouseSensitivity;
3137
- }
3138
- dolly(deltaY) {
3139
- this.camera.position.z = clamp(
3140
- this.camera.position.z + deltaY * this.wheelSensitivity,
3141
- this.minCameraDistance,
3142
- this.maxCameraDistance
3143
- );
3144
- }
3145
- };
3146
-
3147
- // src/three/threejs-player-controller.ts
3148
- import { Group as Group6, Vector3 as Vector35 } from "three";
3149
- var ThreeJsPlayerController = class extends Group6 {
3150
- moveSpeed = 1;
3151
- cameraRig;
3152
- velocity;
3153
- constructor(camera) {
3154
- super();
3155
- this.velocity = new Vector35();
3156
- this.cameraRig = new ThreeJsCameraRig({ camera });
3157
- this.add(this.cameraRig);
3158
- }
3159
- update(deltaTime) {
3160
- if (this.velocity.length()) {
3161
- this.translateOnAxis(this.velocity.normalize(), this.moveSpeed * deltaTime);
3162
- }
3163
- }
3164
- };
3165
-
3166
- // src/three/voxel-geometry.ts
3167
- import { BufferGeometry as BufferGeometry3, Float32BufferAttribute as Float32BufferAttribute2 } from "three";
3168
- var VoxelGeometry = class extends BufferGeometry3 {
3169
- type = "VoxelGeometry";
3170
- voxels = new Map3D();
3171
- voxelBuildParams = {};
3172
- updateGeometry(params) {
3173
- BuildVoxelGeometry(this.voxels, {
3174
- ...params ?? this.voxelBuildParams,
3175
- voxelGeometry: this
3176
- });
3177
- }
3178
- };
3179
- function BuildVoxelGeometry(voxelMap, params) {
3180
- const includeHiddenFaces = params.includeHiddenFaces ?? false;
3181
- const smoothNormals = params.smoothNormals ?? false;
3182
- const palette = params.palette ?? [];
3183
- const positions = [];
3184
- const normals = [];
3185
- const colors2 = [];
3186
- const indices = [];
3187
- function pushColor(hex) {
3188
- colors2.push(
3189
- (hex >> 16 & 255) / 255,
3190
- (hex >> 8 & 255) / 255,
3191
- (hex & 255) / 255
3192
- );
3193
- }
3194
- function emitFace(face, x, y, z, color) {
3195
- const index = positions.length / 3;
3196
- const vertices = face.vertices;
3197
- for (let i = 0; i < vertices.length; i += 3) {
3198
- positions.push(
3199
- x + vertices[i],
3200
- y + vertices[i + 1],
3201
- z + vertices[i + 2]
3202
- );
3203
- normals.push(
3204
- face.normal[0],
3205
- face.normal[1],
3206
- face.normal[2]
3207
- );
3208
- pushColor(color);
3209
- }
3210
- indices.push(
3211
- index,
3212
- index + 1,
3213
- index + 2,
3214
- index,
3215
- index + 2,
3216
- index + 3
3217
- );
3218
- }
3219
- function randomColor() {
3220
- return rng.range(256 ** 3);
3221
- }
3222
- voxelMap.forEach((x, y, z, n) => {
3223
- const color = palette[n] ?? randomColor();
3224
- for (const face of VOXEL_FACES) {
3225
- const neighbor = voxelMap.get(
3226
- x + face.normal[0],
3227
- y + face.normal[1],
3228
- z + face.normal[2]
3229
- );
3230
- if (neighbor !== voxelMap.defaultValue && !includeHiddenFaces) continue;
3231
- emitFace(face, x, y, z, color);
3232
- }
3233
- });
3234
- const geometry = params.voxelGeometry ?? new VoxelGeometry();
3235
- geometry.setAttribute("position", new Float32BufferAttribute2(positions, 3));
3236
- geometry.setAttribute("normal", new Float32BufferAttribute2(normals, 3));
3237
- geometry.setAttribute("color", new Float32BufferAttribute2(colors2, 3));
3238
- geometry.setIndex(indices);
3239
- if (smoothNormals) geometry.computeVertexNormals();
3240
- geometry.computeBoundingBox();
3241
- geometry.computeBoundingSphere();
3242
- return geometry;
3243
- }
3244
- var VOXEL_FACES = [
3245
- // +X
3246
- {
3247
- normal: [1, 0, 0],
3248
- vertices: [
3249
- 1,
3250
- 0,
3251
- 0,
3252
- 1,
3253
- 1,
3254
- 0,
3255
- 1,
3256
- 1,
3257
- 1,
3258
- 1,
3259
- 0,
3260
- 1
3261
- ]
3262
- },
3263
- // -X
3264
- {
3265
- normal: [-1, 0, 0],
3266
- vertices: [
3267
- 0,
3268
- 0,
3269
- 1,
3270
- 0,
3271
- 1,
3272
- 1,
3273
- 0,
3274
- 1,
3275
- 0,
3276
- 0,
3277
- 0,
3278
- 0
3279
- ]
3280
- },
3281
- // +Y
3282
- {
3283
- normal: [0, 1, 0],
3284
- vertices: [
3285
- 0,
3286
- 1,
3287
- 0,
3288
- 0,
3289
- 1,
3290
- 1,
3291
- 1,
3292
- 1,
3293
- 1,
3294
- 1,
3295
- 1,
3296
- 0
3297
- ]
3298
- },
3299
- // -Y
3300
- {
3301
- normal: [0, -1, 0],
3302
- vertices: [
3303
- 1,
3304
- 0,
3305
- 0,
3306
- 1,
3307
- 0,
3308
- 1,
3309
- 0,
3310
- 0,
3311
- 1,
3312
- 0,
3313
- 0,
3314
- 0
3315
- ]
3316
- },
3317
- // +Z
3318
- {
3319
- normal: [0, 0, 1],
3320
- vertices: [
3321
- 1,
3322
- 0,
3323
- 1,
3324
- 1,
3325
- 1,
3326
- 1,
3327
- 0,
3328
- 1,
3329
- 1,
3330
- 0,
3331
- 0,
3332
- 1
3333
- ]
3334
- },
3335
- // -Z
3336
- {
3337
- normal: [0, 0, -1],
3338
- vertices: [
3339
- 0,
3340
- 0,
3341
- 0,
3342
- 0,
3343
- 1,
3344
- 0,
3345
- 1,
3346
- 1,
3347
- 0,
3348
- 1,
3349
- 0,
3350
- 0
3351
- ]
3352
- }
3353
- ];
3354
-
3355
- // src/three/voxel-mesh.ts
3356
- import { BufferAttribute as BufferAttribute2, BufferGeometry as BufferGeometry4, Color as Color3, Mesh as Mesh3 } from "three";
3357
- var VoxelMesh = class extends Mesh3 {
3358
- type = "VoxelMesh";
3359
- width;
3360
- depth;
3361
- height;
3362
- colorPalette;
3363
- voxels;
3364
- needsGeometryUpdate = true;
3365
- constructor(width, depth, height, material, name) {
3366
- super();
3367
- this.width = width;
3368
- this.depth = depth;
3369
- this.height = height;
3370
- this.material = material;
3371
- this.material.vertexColors = true;
3372
- this.name = name ?? "VoxelMesh";
3373
- this.colorPalette = BuildDefaultPalette();
3374
- this.voxels = /* @__PURE__ */ new Map();
3375
- this.geometry = new BufferGeometry4();
3376
- this.updateGeometry();
3377
- }
3378
- _xyz2k(x, y, z) {
3379
- x = Math.abs(Math.floor(x));
3380
- y = Math.abs(Math.floor(y));
3381
- z = Math.abs(Math.floor(z));
3382
- return `${x},${y},${z}`;
3383
- }
3384
- _k2xyz(k) {
3385
- const [x, y, z] = k.split(",").map((s) => parseInt(s));
3386
- return { x, y, z };
3387
- }
3388
- get(x, y, z) {
3389
- let n = -1;
3390
- if (x >= 0 && y >= 0 && z >= 0 && x < this.width && y < this.height && z < this.depth) {
3391
- n = this.voxels.get(this._xyz2k(x, y, z)) ?? -1;
3392
- }
3393
- return n;
3394
- }
3395
- set(x, y, z, n) {
3396
- if (x >= 0 && y >= 0 && z >= 0 && x < this.width && y < this.height && z < this.depth) {
3397
- if (n === void 0) this.voxels.delete(this._xyz2k(x, y, z));
3398
- else this.voxels.set(this._xyz2k(x, y, z), n);
3399
- this.needsGeometryUpdate = true;
3400
- }
3401
- }
3402
- clearVoxels() {
3403
- this.voxels.clear();
3404
- }
3405
- setSize(width, depth, height) {
3406
- this.forEachVoxel((x, y, z) => {
3407
- if (x >= width || y >= height || z >= depth) this.set(x, y, z);
3408
- });
3409
- this.width = width;
3410
- this.depth = depth;
3411
- this.height = height;
3412
- this.needsGeometryUpdate = true;
3413
- }
3414
- forEachVoxel(callback) {
3415
- this.voxels.forEach((n, k) => {
3416
- const { x, y, z } = this._k2xyz(k);
3417
- callback(x, y, z, n);
3418
- });
3419
- }
3420
- importVoxelData(voxelData) {
3421
- this.clearVoxels();
3422
- this.name = voxelData.name;
3423
- this.setSize(voxelData.width, voxelData.depth, voxelData.height);
3424
- voxelData.palette.forEach((color, i) => {
3425
- if (i < this.colorPalette.length) {
3426
- this.colorPalette[i] = color;
3427
- } else {
3428
- this.colorPalette.push(color);
3429
- }
3430
- });
3431
- voxelData.voxels.forEach((voxel) => {
3432
- const { x, y, z, color } = voxel;
3433
- this.set(x, y, z, color);
3434
- });
3435
- this.updateGeometry();
3436
- }
3437
- updateGeometry() {
3438
- if (this.needsGeometryUpdate) {
3439
- const positions = [];
3440
- const normals = [];
3441
- const colors2 = [];
3442
- const indices = [];
3443
- this.forEachVoxel((x, y, z, n) => {
3444
- VoxelFaces.forEach((faces) => {
3445
- const [dx, dy, dz] = faces[0];
3446
- const neighborVoxel = this.get(x + dx, y + dy, z + dz);
3447
- if (neighborVoxel < 0) {
3448
- const positionIndex = positions.length / 3;
3449
- faces.forEach((face) => {
3450
- const [nx, ny, nz, px, py, pz] = face;
3451
- positions.push(x + px, y + py, z + pz);
3452
- normals.push(nx, ny, nz);
3453
- const { r, g, b } = new Color3(this.colorPalette[n]);
3454
- colors2.push(r, g, b, 1);
3455
- });
3456
- indices.push(
3457
- positionIndex,
3458
- positionIndex + 1,
3459
- positionIndex + 2,
3460
- positionIndex + 2,
3461
- positionIndex + 1,
3462
- positionIndex + 3
3463
- );
3464
- }
3465
- });
3466
- });
3467
- this.geometry.setAttribute("position", new BufferAttribute2(new Float32Array(positions), 3));
3468
- this.geometry.setAttribute("normal", new BufferAttribute2(new Float32Array(normals), 3));
3469
- this.geometry.setAttribute("color", new BufferAttribute2(new Float32Array(colors2), 4));
3470
- this.geometry.setIndex(indices);
3471
- this.geometry.computeBoundingSphere();
3472
- this.updateMatrixWorld();
3473
- }
3474
- this.needsGeometryUpdate = false;
3475
- }
3476
- exportData() {
3477
- const voxelData = {
3478
- name: this.name,
3479
- width: this.width,
3480
- depth: this.depth,
3481
- height: this.height,
3482
- palette: [...this.colorPalette],
3483
- voxels: []
3484
- };
3485
- this.forEachVoxel((x, y, z, color) => {
3486
- voxelData.voxels.push({ x, y, z, color });
3487
- });
3488
- return voxelData;
3489
- }
3490
- };
3491
- var VoxelFaces = [
3492
- // [nx, ny, nz, px, py, pz]
3493
- [
3494
- //left
3495
- [-1, 0, 0, 0, 1, 0],
3496
- [-1, 0, 0, 0, 0, 0],
3497
- [-1, 0, 0, 0, 1, 1],
3498
- [-1, 0, 0, 0, 0, 1]
3499
- ],
3500
- [
3501
- //right
3502
- [1, 0, 0, 1, 1, 1],
3503
- [1, 0, 0, 1, 0, 1],
3504
- [1, 0, 0, 1, 1, 0],
3505
- [1, 0, 0, 1, 0, 0]
3506
- ],
3507
- [
3508
- //bottom
3509
- [0, -1, 0, 1, 0, 1],
3510
- [0, -1, 0, 0, 0, 1],
3511
- [0, -1, 0, 1, 0, 0],
3512
- [0, -1, 0, 0, 0, 0]
3513
- ],
3514
- [
3515
- //top
3516
- [0, 1, 0, 0, 1, 1],
3517
- [0, 1, 0, 1, 1, 1],
3518
- [0, 1, 0, 0, 1, 0],
3519
- [0, 1, 0, 1, 1, 0]
3520
- ],
3521
- [
3522
- //back
3523
- [0, 0, -1, 1, 0, 0],
3524
- [0, 0, -1, 0, 0, 0],
3525
- [0, 0, -1, 1, 1, 0],
3526
- [0, 0, -1, 0, 1, 0]
3527
- ],
3528
- [
3529
- //front
3530
- [0, 0, 1, 0, 0, 1],
3531
- [0, 0, 1, 1, 0, 1],
3532
- [0, 0, 1, 0, 1, 1],
3533
- [0, 0, 1, 1, 1, 1]
3534
- ]
3535
- ];
3536
- function BuildDefaultPalette(palette) {
3537
- palette = palette ?? Colors2.rgb48;
3538
- const grayscale = [];
3539
- const count = 16;
3540
- for (let i = 0; i < count; i++) {
3541
- const grey = Math.floor(i / count * 255);
3542
- grayscale.push(`rgb(${grey}, ${grey}, ${grey})`);
3543
- }
3544
- return [...palette, ...grayscale];
3545
- }
3546
- var Colors2 = {
3547
- rgb12: [
3548
- "#FF0000",
3549
- "#FF8800",
3550
- "#FFFF00",
3551
- "#88FF00",
3552
- "#00FF00",
3553
- "#00FF88",
3554
- "#00FFFF",
3555
- "#0088FF",
3556
- "#0000FF",
3557
- "#8800FF",
3558
- "#FF00FF",
3559
- "#FF0080"
3560
- ],
3561
- rgb24: [
3562
- "#FF0000",
3563
- "#FF4000",
3564
- "#FF8000",
3565
- "#FFBF00",
3566
- "#FFFF00",
3567
- "#CCFF00",
3568
- "#80FF00",
3569
- "#40FF00",
3570
- "#00FF00",
3571
- "#00FF40",
3572
- "#00FF80",
3573
- "#00FFCC",
3574
- "#00FFFF",
3575
- "#00CCFF",
3576
- "#0080FF",
3577
- "#0040FF",
3578
- "#0000FF",
3579
- "#4000FF",
3580
- "#8000FF",
3581
- "#CC00FF",
3582
- "#FF00FF",
3583
- "#FF00CC",
3584
- "#FF0080",
3585
- "#FF0040"
3586
- ],
3587
- rgb48: [
3588
- "#FF0000",
3589
- "#FF2000",
3590
- "#FF4000",
3591
- "#FF6000",
3592
- "#FF8000",
3593
- "#FFAA00",
3594
- "#FFCC00",
3595
- "#FFEE00",
3596
- "#FFFF00",
3597
- "#DDFF00",
3598
- "#CCFF00",
3599
- "#AAFF00",
3600
- "#80FF00",
3601
- "#60FF00",
3602
- "#40FF00",
3603
- "#20FF00",
3604
- "#00FF00",
3605
- "#00FF20",
3606
- "#00FF40",
3607
- "#00FF60",
3608
- "#00FF80",
3609
- "#00FFAA",
3610
- "#00FFCC",
3611
- "#00FFDD",
3612
- "#00FFFF",
3613
- "#00DDFF",
3614
- "#00CCFF",
3615
- "#0099FF",
3616
- "#0080FF",
3617
- "#0060FF",
3618
- "#0040FF",
3619
- "#0020FF",
3620
- "#0000FF",
3621
- "#2000FF",
3622
- "#4000FF",
3623
- "#6000FF",
3624
- "#8000FF",
3625
- "#AA00FF",
3626
- "#CC00FF",
3627
- "#DD00FF",
3628
- "#FF00FF",
3629
- "#FF00EE",
3630
- "#FF00CC",
3631
- "#FF00AA",
3632
- "#FF0080",
3633
- "#FF0060",
3634
- "#FF0040",
3635
- "#FF0020"
3636
- ],
3637
- rgb64: [
3638
- "#000000",
3639
- "#000055",
3640
- "#0000AA",
3641
- "#0000FF",
3642
- "#005500",
3643
- "#005555",
3644
- "#0055AA",
3645
- "#0055FF",
3646
- "#00AA00",
3647
- "#00AA55",
3648
- "#00AAAA",
3649
- "#00AAFF",
3650
- "#00FF00",
3651
- "#00FF55",
3652
- "#00FFAA",
3653
- "#00FFFF",
3654
- "#550000",
3655
- "#550055",
3656
- "#5500AA",
3657
- "#5500FF",
3658
- "#555500",
3659
- "#555555",
3660
- "#5555AA",
3661
- "#5555FF",
3662
- "#55AA00",
3663
- "#55AA55",
3664
- "#55AAAA",
3665
- "#55AAFF",
3666
- "#55FF00",
3667
- "#55FF55",
3668
- "#55FFAA",
3669
- "#55FFFF",
3670
- "#AA0000",
3671
- "#AA0055",
3672
- "#AA00AA",
3673
- "#AA00FF",
3674
- "#AA5500",
3675
- "#AA5555",
3676
- "#AA55AA",
3677
- "#AA55FF",
3678
- "#AAAA00",
3679
- "#AAAA55",
3680
- "#AAAAAA",
3681
- "#AAAAFF",
3682
- "#AAFF00",
3683
- "#AAFF55",
3684
- "#AAFFAA",
3685
- "#AAFFFF",
3686
- "#FF0000",
3687
- "#FF0055",
3688
- "#FF00AA",
3689
- "#FF00FF",
3690
- "#FF5500",
3691
- "#FF5555",
3692
- "#FF55AA",
3693
- "#FF55FF",
3694
- "#FFAA00",
3695
- "#FFAA55",
3696
- "#FFAAAA",
3697
- "#FFAAFF",
3698
- "#FFFF00",
3699
- "#FFFF55",
3700
- "#FFFFAA",
3701
- "#FFFFFF"
3702
- ]
3703
- };
3704
-
3705
- // src/tilemap.ts
3706
- var Tilemap = class {
3707
- map = /* @__PURE__ */ new Map();
3708
- _key(x, y) {
3709
- x = Math.floor(x);
3710
- y = Math.floor(y);
3711
- return `${x}x${y}`;
3712
- }
3713
- get(x, y) {
3714
- return this.map.get(this._key(x, y));
3715
- }
3716
- set(x, y, v) {
3717
- this.map.set(this._key(x, y), v);
3718
- }
3719
- };
3720
-
3721
- // src/webgl.ts
3722
- var ShaderType = ((ShaderType2) => {
3723
- ShaderType2[ShaderType2["VERTEX"] = WebGL2RenderingContext.VERTEX_SHADER] = "VERTEX";
3724
- ShaderType2[ShaderType2["FRAGMENT"] = WebGL2RenderingContext.FRAGMENT_SHADER] = "FRAGMENT";
3725
- return ShaderType2;
3726
- })(ShaderType || {});
3727
- function CreateWebGlContext(canvas) {
3728
- return (canvas ?? document.createElement("canvas")).getContext("webgl2");
3729
- }
3730
- function ResizeWebGlContext(gl, displayWidth, displayHeight) {
3731
- const canvas = gl.canvas;
3732
- const { width, height } = canvas.parentElement?.getBoundingClientRect() ?? canvas.getBoundingClientRect();
3733
- displayWidth = 0 | (displayWidth ?? width);
3734
- displayHeight = 0 | (displayHeight ?? height);
3735
- if (canvas.width !== displayWidth || canvas.height !== displayHeight) {
3736
- gl.canvas.width = displayWidth;
3737
- gl.canvas.height = displayHeight;
3738
- gl.viewport(0, 0, displayWidth, displayHeight);
3739
- return true;
3740
- }
3741
- return false;
3742
- }
3743
- function CompileShader(gl, type, source) {
3744
- const shader = gl.createShader(type);
3745
- gl.shaderSource(shader, source);
3746
- gl.compileShader(shader);
3747
- if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
3748
- throw `CompileShader: failed to compile shader: ${gl.getShaderInfoLog(shader)}`;
3749
- }
3750
- return shader;
3751
- }
3752
- function CreateProgram(gl, vertexShader2, fragmentShader2) {
3753
- if (typeof vertexShader2 === "string") {
3754
- vertexShader2 = CompileShader(gl, ShaderType.VERTEX, vertexShader2);
3755
- }
3756
- if (typeof fragmentShader2 === "string") {
3757
- fragmentShader2 = CompileShader(gl, ShaderType.FRAGMENT, fragmentShader2);
3758
- }
3759
- const program = gl.createProgram();
3760
- gl.attachShader(program, vertexShader2);
3761
- gl.attachShader(program, fragmentShader2);
3762
- gl.linkProgram(program);
3763
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
3764
- throw `CreateProgram: failed to link program: ${gl.getProgramInfoLog(program)}`;
3765
- }
3766
- return program;
3767
- }
3768
- function GetProgramLocations(gl, program) {
3769
- const attributes = {};
3770
- const attributeCount = gl.getProgramParameter(program, gl.ACTIVE_ATTRIBUTES);
3771
- for (let i = 0; i < attributeCount; i++) {
3772
- const info = gl.getActiveAttrib(program, i);
3773
- attributes[info.name] = gl.getAttribLocation(program, info.name);
3774
- }
3775
- const uniforms = {};
3776
- const uniformCount = gl.getProgramParameter(program, gl.ACTIVE_UNIFORMS);
3777
- for (let i = 0; i < uniformCount; i++) {
3778
- const info = gl.getActiveUniform(program, i);
3779
- uniforms[info.name] = gl.getUniformLocation(program, info.name);
3780
- }
3781
- return { attributes, uniforms };
3782
- }
3783
- function CreateProgramInfo(gl, vertexShaderSource, fragmentShaderSource) {
3784
- const program = CreateProgram(
3785
- gl,
3786
- vertexShaderSource,
3787
- fragmentShaderSource
3788
- );
3789
- const locations = GetProgramLocations(gl, program);
3790
- return { program, ...locations };
3791
- }
3792
-
3793
- // src/webgl-renderer.ts
3794
- var WebGlRenderer = class {
3795
- gl;
3796
- programInfo;
3797
- get canvas() {
3798
- return this.gl.canvas;
3799
- }
3800
- get width() {
3801
- return this.gl.canvas.width;
3802
- }
3803
- get height() {
3804
- return this.gl.canvas.height;
3805
- }
3806
- constructor() {
3807
- this.gl = CreateWebGlContext();
3808
- this.gl.enable(this.gl.DEPTH_TEST);
3809
- }
3810
- appendTo(htmlElement) {
3811
- if (this.canvas.parentElement) {
3812
- this.canvas.parentElement.removeChild(this.canvas);
3813
- }
3814
- if (htmlElement) {
3815
- htmlElement.appendChild(this.canvas);
3816
- this.resize();
3817
- }
3818
- }
3819
- resize(displayWidth, displayHeight) {
3820
- const { width, height } = this.canvas.parentElement?.getBoundingClientRect() ?? this.canvas.getBoundingClientRect();
3821
- displayWidth = 0 | (displayWidth ?? width);
3822
- displayHeight = 0 | (displayHeight ?? height);
3823
- if (this.width !== displayWidth || this.height !== displayHeight) {
3824
- this.gl.canvas.width = displayWidth;
3825
- this.gl.canvas.height = displayHeight;
3826
- this.gl.viewport(0, 0, displayWidth, displayHeight);
3827
- return true;
3828
- }
3829
- return false;
3830
- }
3831
- render(_deltaTime) {
3832
- if (this.programInfo) {
3833
- }
3834
- }
3835
- };
3836
-
3837
- // src/worker-interface.ts
3838
- var WorkerInterface = class {
3839
- _worker;
3840
- onError = new Observable();
3841
- onMessage = new Observable();
3842
- constructor(url) {
3843
- this._worker = new Worker(url, { type: "module" });
3844
- this._worker.onerror = (error) => this.onError.notify(error);
3845
- this._worker.onmessage = (message) => this.onMessage.notify(message);
3846
- }
3847
- postMessage(message, options) {
3848
- this._worker.postMessage(message, options);
3849
- }
3850
- terminate() {
3851
- this._worker.terminate();
3852
- }
3853
- };
3854
- export {
3855
- AStar,
3856
- AddThreeComponent,
3857
- AsteroidMesh,
3858
- AtlasTextureMaterial,
3859
- BuildDefaultPalette,
3860
- BuildVoxelGeometry,
3861
- CameraRig,
3862
- CanvasRenderer,
3863
- Clock,
3864
- Color,
3865
- Colors2 as Colors,
3866
- CompileShader,
3867
- CreatePaletteController,
3868
- CreateProgram,
3869
- CreateProgramInfo,
3870
- CreateStarfield,
3871
- CreateSubTexture,
3872
- CreateSystemStar,
3873
- CreateThreeEntity,
3874
- CreateWebGlContext,
3875
- CubeSphereGeometry,
3876
- DEFAULT_COLOR,
3877
- DEFAULT_FONT,
3878
- DEFAULT_FONT_NAME,
3879
- DEFAULT_FONT_SIZE,
3880
- DEFAULT_MAP_2D_VALUE,
3881
- DEFAULT_MAP_3D_VALUE,
3882
- DEFAULT_PIXEL_SIZE,
3883
- DEFAULT_TEXTALIGN,
3884
- DEFAULT_TEXTBASELINE,
3885
- DEG2RAD,
3886
- Disposable,
3887
- E,
3888
- ECS,
3889
- EPSILON,
3890
- Emitter,
3891
- EventQueue,
3892
- GenerateDoors,
3893
- GenerateEntityId,
3894
- GenerateRooms,
3895
- GenerateWalls,
3896
- GetProgramLocations,
3897
- GetThreeComponent,
3898
- GetUrlParams,
3899
- HALF_PI,
3900
- Input,
3901
- IsThreeEntity,
3902
- LN10,
3903
- LN2,
3904
- LOG10E,
3905
- LOG2E,
3906
- LoadTexture,
3907
- Map2D,
3908
- Map3D,
3909
- Noise,
3910
- ONE_SECOND,
3911
- Observable,
3912
- PI,
3913
- ParticleRenderer,
3914
- ParticleSystem2d,
3915
- ParticleSystem3d,
3916
- PoissonDiskSampler,
3917
- QUARTER_PI,
3918
- RAD2DEG,
3919
- Random,
3920
- Rectangle,
3921
- RemoveThreeComponent,
3922
- Renderer,
3923
- ResizeWebGlContext,
3924
- Rng,
3925
- SQRT1_2,
3926
- SQRT2,
3927
- ShaderType,
3928
- Signal,
3929
- SimplexNoise,
3930
- SpatialPartition2d,
3931
- SpatialPartition3d,
3932
- TAU,
3933
- TILE_EMPTY,
3934
- TILE_FLOOR,
3935
- TILE_PATH,
3936
- TextureAtlas,
3937
- ThreeJsCameraRig,
3938
- ThreeJsPlayerController,
3939
- Tilemap,
3940
- VOXEL_FACES,
3941
- Vector,
3942
- VoxelFaces,
3943
- VoxelGeometry,
3944
- VoxelMesh,
3945
- WebGlRenderer,
3946
- WorkerInterface,
3947
- buildColorPalette,
3948
- clamp,
3949
- degrees,
3950
- distance2d,
3951
- distance3d,
3952
- fract,
3953
- getRedYellowGreenGradientHex,
3954
- hash32,
3955
- hash32mix,
3956
- inverseLerp,
3957
- isNullOrUndefined,
3958
- isPositiveString,
3959
- k2xy,
3960
- k2xyz,
3961
- lerp,
3962
- log,
3963
- manhattanDistance,
3964
- mod,
3965
- nearlyEqual,
3966
- normalizeRadians,
3967
- radians,
3968
- randomMatrix,
3969
- rng,
3970
- roundTo,
3971
- saturate,
3972
- smoothstep,
3973
- squaredDistance,
3974
- wrap,
3975
- xy2k,
3976
- xyz2k
3977
- };