@n3rdw1z4rd/core 0.17.1 → 0.18.0

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