@n3rdw1z4rd/core 0.11.0 → 0.14.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
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,52 +17,209 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
21
31
  var index_exports = {};
22
32
  __export(index_exports, {
33
+ AStar: () => AStar,
34
+ AddThreeComponent: () => AddThreeComponent,
35
+ AsteroidMesh: () => AsteroidMesh,
36
+ AtlasTextureMaterial: () => AtlasTextureMaterial,
37
+ BuildDefaultPalette: () => BuildDefaultPalette,
23
38
  CanvasRenderer: () => CanvasRenderer,
24
39
  Clock: () => Clock,
25
40
  ClockStats: () => ClockStats,
41
+ Color: () => Color,
42
+ Colors: () => Colors,
26
43
  CompileShader: () => CompileShader,
44
+ CreatePaletteController: () => CreatePaletteController,
27
45
  CreateProgram: () => CreateProgram,
28
46
  CreateProgramInfo: () => CreateProgramInfo,
47
+ CreateStarfield: () => CreateStarfield,
48
+ CreateSubTexture: () => CreateSubTexture,
49
+ CreateSystemStar: () => CreateSystemStar,
50
+ CreateThreeEntity: () => CreateThreeEntity,
29
51
  CreateWebGlContext: () => CreateWebGlContext,
30
52
  CubeSphereGeometry: () => CubeSphereGeometry,
31
53
  ECS: () => ECS,
32
54
  Emitter: () => Emitter,
55
+ EventBus: () => EventBus,
56
+ GenerateDoors: () => GenerateDoors,
57
+ GenerateEntityId: () => GenerateEntityId,
58
+ GenerateRooms: () => GenerateRooms,
59
+ GenerateWalls: () => GenerateWalls,
33
60
  GetProgramLocations: () => GetProgramLocations,
61
+ GetThreeComponent: () => GetThreeComponent,
34
62
  GlobalEmitter: () => GlobalEmitter,
35
63
  Input: () => Input,
64
+ IsThreeEntity: () => IsThreeEntity,
36
65
  LoadTexture: () => LoadTexture,
66
+ Map2D: () => Map2D,
67
+ Map3D: () => Map3D,
37
68
  Noise: () => Noise,
69
+ PI: () => PI,
70
+ ParticleSystem2d: () => ParticleSystem2d,
71
+ ParticleSystem3d: () => ParticleSystem3d,
72
+ PoissonDiskSampler: () => PoissonDiskSampler,
73
+ Rectangle: () => Rectangle,
74
+ RemoveThreeComponent: () => RemoveThreeComponent,
75
+ Renderer: () => Renderer,
38
76
  ResizeWebGlContext: () => ResizeWebGlContext,
39
77
  Rng: () => Rng,
40
78
  ShaderType: () => ShaderType,
41
79
  SimplexNoise: () => SimplexNoise,
80
+ SpatialPartition2d: () => SpatialPartition2d,
81
+ SpatialPartition3d: () => SpatialPartition3d,
82
+ TILE_EMPTY: () => TILE_EMPTY,
83
+ TILE_FLOOR: () => TILE_FLOOR,
84
+ TILE_PATH: () => TILE_PATH,
42
85
  TextureAtlas: () => TextureAtlas,
43
86
  ThreeJsBoilerPlate: () => ThreeJsBoilerPlate,
44
87
  ThreeJsCameraRig: () => ThreeJsCameraRig,
45
88
  ThreeJsPlayerController: () => ThreeJsPlayerController,
46
- VoxelGeometry: () => VoxelGeometry,
89
+ Tilemap: () => Tilemap,
90
+ Vector: () => Vector,
91
+ VoxelFaces: () => VoxelFaces,
92
+ VoxelMesh: () => VoxelMesh,
47
93
  WebGlRenderer: () => WebGlRenderer,
94
+ WorkerInterface: () => WorkerInterface,
95
+ abs: () => abs,
96
+ ceil: () => ceil,
48
97
  clamp: () => clamp,
98
+ cos: () => cos,
49
99
  deg2rad: () => deg2rad,
100
+ distance: () => distance,
101
+ eventBus: () => eventBus,
102
+ floor: () => floor,
50
103
  getRedYellowGreenGradientHex: () => getRedYellowGreenGradientHex,
104
+ hypot2: () => hypot2,
105
+ hypot3: () => hypot3,
106
+ imul: () => imul,
51
107
  isNullOrUndefined: () => isNullOrUndefined,
52
- key2xyz: () => key2xyz,
53
108
  lerp: () => lerp,
54
109
  log: () => log,
55
110
  logdev: () => logdev,
56
111
  logerr: () => logerr,
57
112
  loginf: () => loginf,
58
113
  logwrn: () => logwrn,
114
+ manhattanDistance: () => manhattanDistance,
115
+ max: () => max,
116
+ min: () => min,
117
+ pow: () => pow,
59
118
  rng: () => rng,
60
- xyz2key: () => xyz2key
119
+ round: () => round,
120
+ roundTo: () => roundTo,
121
+ sin: () => sin,
122
+ sqrt: () => sqrt,
123
+ squaredDistance: () => squaredDistance
61
124
  });
62
125
  module.exports = __toCommonJS(index_exports);
63
126
 
127
+ // src/astar.ts
128
+ var DIRECTIONS_4_WAY = [
129
+ { x: 0, y: -1 },
130
+ { x: 1, y: 0 },
131
+ { x: 0, y: 1 },
132
+ { x: -1, y: 0 }
133
+ ];
134
+ var AStar = class {
135
+ map;
136
+ constructor(map) {
137
+ this.map = map;
138
+ }
139
+ _manhattan(a, b) {
140
+ return Math.abs(a.x - b.x) + Math.abs(a.y - b.y);
141
+ }
142
+ _isWalkable(point, walkable = [0]) {
143
+ const value = this.map.get(point.x, point.y);
144
+ return walkable.includes(value);
145
+ }
146
+ _key(x, y) {
147
+ return `${x},${y}`;
148
+ }
149
+ // NOTE: ported as-is from rogue-craft. useAdjacent is currently hard-coded
150
+ // to true below - the original had a known unresolved bug where setting it
151
+ // to false via params caused an infinite loop, so that path is disabled
152
+ // rather than exposed broken.
153
+ findPath(a, b, params = {}) {
154
+ const useAdjacent = true;
155
+ const walkable = params.walkableValues ?? [0];
156
+ const openSet = [];
157
+ const closedSet = /* @__PURE__ */ new Set();
158
+ const nodeMap = /* @__PURE__ */ new Map();
159
+ const startNode = {
160
+ pos: a,
161
+ g: 0,
162
+ h: this._manhattan(a, b),
163
+ f: this._manhattan(a, b)
164
+ };
165
+ openSet.push(startNode);
166
+ nodeMap.set(this._key(a.x, a.y), startNode);
167
+ const targetKeys = /* @__PURE__ */ new Set();
168
+ targetKeys.add(this._key(b.x, b.y));
169
+ if (useAdjacent) {
170
+ for (const dir of DIRECTIONS_4_WAY) {
171
+ const nx = b.x + dir.x;
172
+ const ny = b.y + dir.y;
173
+ targetKeys.add(this._key(nx, ny));
174
+ }
175
+ }
176
+ while (openSet.length > 0) {
177
+ openSet.sort((a2, b2) => a2.f - b2.f);
178
+ const current = openSet.shift();
179
+ const currentKey = this._key(current.pos.x, current.pos.y);
180
+ if (targetKeys.has(currentKey)) {
181
+ const path = [];
182
+ let curr = current;
183
+ while (curr) {
184
+ path.push(curr.pos);
185
+ curr = curr.parent;
186
+ }
187
+ path.pop();
188
+ return path.reverse();
189
+ }
190
+ closedSet.add(currentKey);
191
+ for (const dir of DIRECTIONS_4_WAY) {
192
+ const neighborPos = {
193
+ x: current.pos.x + dir.x,
194
+ y: current.pos.y + dir.y
195
+ };
196
+ const key = this._key(neighborPos.x, neighborPos.y);
197
+ if (!this._isWalkable(neighborPos, walkable) || closedSet.has(key)) {
198
+ continue;
199
+ }
200
+ const g = current.g + 1;
201
+ let neighbor = nodeMap.get(key);
202
+ if (!neighbor) {
203
+ neighbor = {
204
+ pos: neighborPos,
205
+ g,
206
+ h: this._manhattan(neighborPos, b),
207
+ f: g + this._manhattan(neighborPos, b),
208
+ parent: current
209
+ };
210
+ nodeMap.set(key, neighbor);
211
+ openSet.push(neighbor);
212
+ } else if (g < neighbor.g) {
213
+ neighbor.g = g;
214
+ neighbor.f = g + neighbor.h;
215
+ neighbor.parent = current;
216
+ }
217
+ }
218
+ }
219
+ return [];
220
+ }
221
+ };
222
+
64
223
  // src/clock-stats.ts
65
224
  var ClockStats = class {
66
225
  divElement;
@@ -194,6 +353,767 @@ var loginf = console.log.bind(console, "%c[inf]", "font-weight: bold;");
194
353
  var logwrn = console.log.bind(console, "%c[wrn]", "font-weight: bold; color: orange;");
195
354
  var logerr = console.log.bind(console, "%c[err]", "font-weight: bold; color: red;");
196
355
 
356
+ // src/math.ts
357
+ var DEG2RAD = 0.01745329;
358
+ var PI = 3.141592653589793;
359
+ var TWO_PI = PI * 2;
360
+ var HALF_PI = PI / 2;
361
+ function abs(n) {
362
+ return n < 0 ? -n : n;
363
+ }
364
+ function min(a, b) {
365
+ return a < b ? a : b;
366
+ }
367
+ function max(a, b) {
368
+ return a > b ? a : b;
369
+ }
370
+ function floor(n) {
371
+ const t = n | 0;
372
+ return n < 0 && t !== n ? t - 1 : t;
373
+ }
374
+ function ceil(n) {
375
+ const t = n | 0;
376
+ return n > 0 && t !== n ? t + 1 : t;
377
+ }
378
+ function round(n) {
379
+ return floor(n + 0.5);
380
+ }
381
+ function sqrt(n) {
382
+ return n ** 0.5;
383
+ }
384
+ function pow(base, exp) {
385
+ return base ** exp;
386
+ }
387
+ function hypot2(x, y) {
388
+ return (x * x + y * y) ** 0.5;
389
+ }
390
+ function hypot3(x, y, z) {
391
+ return (x * x + y * y + z * z) ** 0.5;
392
+ }
393
+ function imul(a, b) {
394
+ b |= 0;
395
+ let result = (a & 4194303) * b;
396
+ if (a & 4290772992) result += (a & 4290772992) * b | 0;
397
+ return result | 0;
398
+ }
399
+ function wrapAngle(n) {
400
+ n = n % TWO_PI;
401
+ if (n > PI) n -= TWO_PI;
402
+ else if (n < -PI) n += TWO_PI;
403
+ return n;
404
+ }
405
+ function sinSeries(n) {
406
+ const n2 = n * n;
407
+ return n * (1 + n2 * (-1 / 6 + n2 * (1 / 120 + n2 * (-1 / 5040 + n2 * (1 / 362880 + n2 * (-1 / 39916800))))));
408
+ }
409
+ function cosSeries(n) {
410
+ const n2 = n * n;
411
+ return 1 + n2 * (-1 / 2 + n2 * (1 / 24 + n2 * (-1 / 720 + n2 * (1 / 40320 + n2 * (-1 / 3628800)))));
412
+ }
413
+ function reduceAngle(n) {
414
+ let x = wrapAngle(n);
415
+ let sinSign = 1;
416
+ if (x < 0) {
417
+ x = -x;
418
+ sinSign = -1;
419
+ }
420
+ let cosSign = 1;
421
+ if (x > HALF_PI) {
422
+ x = PI - x;
423
+ cosSign = -1;
424
+ }
425
+ return [x, sinSign, cosSign];
426
+ }
427
+ function sin(n) {
428
+ const [x, sinSign] = reduceAngle(n);
429
+ return sinSign * sinSeries(x);
430
+ }
431
+ function cos(n) {
432
+ const [x, , cosSign] = reduceAngle(n);
433
+ return cosSign * cosSeries(x);
434
+ }
435
+ function clamp(value, lo, hi) {
436
+ return max(lo, min(hi, value));
437
+ }
438
+ function deg2rad(value) {
439
+ return value * DEG2RAD;
440
+ }
441
+ function lerp(start, end, scale) {
442
+ return start * (1 - scale) + end * scale;
443
+ }
444
+ function distance(x1, y1, x2, y2) {
445
+ return hypot2(x2 - x1, y2 - y1);
446
+ }
447
+ function squaredDistance(x1, y1, x2, y2) {
448
+ const dx = x1 - x2;
449
+ const dy = y1 - y2;
450
+ return dx * dx + dy * dy;
451
+ }
452
+ function manhattanDistance(x1, y1, x2, y2) {
453
+ return abs(x1 - x2) + abs(y1 - y2);
454
+ }
455
+ function roundTo(value, digits, base = 10) {
456
+ const p = pow(base, digits);
457
+ return round(value * p) / p;
458
+ }
459
+
460
+ // src/color.ts
461
+ var Color = class _Color {
462
+ _hex = "#ffffffff";
463
+ _r = 255;
464
+ _g = 255;
465
+ _b = 255;
466
+ _a = 255;
467
+ get r() {
468
+ return this._r;
469
+ }
470
+ set r(value) {
471
+ this._r = clamp(value, 0, 255);
472
+ this._hex = this._to_hex();
473
+ }
474
+ get g() {
475
+ return this._g;
476
+ }
477
+ set g(value) {
478
+ this._g = clamp(value, 0, 255);
479
+ this._hex = this._to_hex();
480
+ }
481
+ get b() {
482
+ return this._b;
483
+ }
484
+ set b(value) {
485
+ this._b = clamp(value, 0, 255);
486
+ this._hex = this._to_hex();
487
+ }
488
+ get a() {
489
+ return this._a;
490
+ }
491
+ set a(value) {
492
+ this._a = clamp(value, 0, 255);
493
+ this._hex = this._to_hex();
494
+ }
495
+ get hexStr() {
496
+ return this._hex;
497
+ }
498
+ set hexStr(value) {
499
+ if (value.startsWith("#")) {
500
+ [this._r, this._g, this._b, this._a] = this._parse_hex_color_string(value);
501
+ this._hex = value;
502
+ } else {
503
+ logwrn(`Color: invalid color string: ${value}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Keeping the current color.`);
504
+ }
505
+ }
506
+ get rgba() {
507
+ return [this._r, this._g, this._b, this._a];
508
+ }
509
+ constructor(r = 255, g = 255, b = 255, a = 255) {
510
+ if (typeof r === "string") {
511
+ if (r.startsWith("#")) {
512
+ [r, g, b, a] = this._parse_hex_color_string(r);
513
+ } else {
514
+ logwrn(`Color: invalid color string: ${r}. Should be a hexadecimal color string (i.e.: '#ffffff' or '#ffffffff'). Defaulting to opaque white.`);
515
+ r = g = b = a = 255;
516
+ }
517
+ } else {
518
+ [r, g, b, a] = [r, g, b, a].map((n) => _Color._normalize(n));
519
+ }
520
+ this.r = r;
521
+ this.g = g;
522
+ this.b = b;
523
+ this.a = a;
524
+ }
525
+ static _normalize(value) {
526
+ return clamp(0 | (value > 0 && value < 1 ? value * 255 : value), 0, 255);
527
+ }
528
+ _to_hex() {
529
+ 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")}`;
530
+ }
531
+ _parse_hex_color_string(hex) {
532
+ const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})?$/i.exec(hex);
533
+ return result ? [
534
+ parseInt(result[1], 16),
535
+ parseInt(result[2], 16),
536
+ parseInt(result[3], 16),
537
+ result[4] ? parseInt(result[4], 16) : 255
538
+ ] : [255, 255, 255, 255];
539
+ }
540
+ static fromHsv(h, s, v, a = 255) {
541
+ let r = 0;
542
+ let g = 0;
543
+ let b = 0;
544
+ let i = Math.floor(h * 6);
545
+ let f = h * 6 - i;
546
+ let p = v * (1 - s);
547
+ let q = v * (1 - f * s);
548
+ let t = v * (1 - (1 - f) * s);
549
+ switch (i % 6) {
550
+ case 0:
551
+ r = v, g = t, b = p;
552
+ break;
553
+ case 1:
554
+ r = q, g = v, b = p;
555
+ break;
556
+ case 2:
557
+ r = p, g = v, b = t;
558
+ break;
559
+ case 3:
560
+ r = p, g = q, b = v;
561
+ break;
562
+ case 4:
563
+ r = t, g = p, b = v;
564
+ break;
565
+ case 5:
566
+ r = v, g = p, b = q;
567
+ break;
568
+ }
569
+ return new _Color(Math.round(r * 255), Math.round(g * 255), Math.round(b * 255), a);
570
+ }
571
+ static get BLACK() {
572
+ return new _Color(0, 0, 0, 255);
573
+ }
574
+ static get GRAY() {
575
+ return new _Color(128, 128, 128, 255);
576
+ }
577
+ static get WHITE() {
578
+ return new _Color(255, 255, 255, 255);
579
+ }
580
+ static get RED() {
581
+ return new _Color(255, 0, 0, 255);
582
+ }
583
+ static get GREEN() {
584
+ return new _Color(0, 255, 0, 255);
585
+ }
586
+ static get BLUE() {
587
+ return new _Color(0, 0, 255, 255);
588
+ }
589
+ static get YELLOW() {
590
+ return new _Color(255, 255, 0, 255);
591
+ }
592
+ static get ORANGE() {
593
+ return new _Color(255, 128, 0, 255);
594
+ }
595
+ static get PURPLE() {
596
+ return new _Color(128, 0, 128, 255);
597
+ }
598
+ static get CYAN() {
599
+ return new _Color(0, 255, 255, 255);
600
+ }
601
+ static get MAGENTA() {
602
+ return new _Color(255, 0, 255, 255);
603
+ }
604
+ static fromName(name) {
605
+ const element = document.createElement("div");
606
+ element.style.color = name;
607
+ document.body.appendChild(element);
608
+ const computedColor = getComputedStyle(element).color;
609
+ document.body.removeChild(element);
610
+ const rgba = computedColor.match(/\d+/g);
611
+ if (rgba && rgba.length === 4) {
612
+ const [r, g, b, a] = rgba.map(Number);
613
+ return new _Color(r, g, b, a);
614
+ } else {
615
+ logwrn(`Color: invalid CSS color name: ${name}. Defaulting to transparent.`);
616
+ return _Color.TRANSPARENT;
617
+ }
618
+ }
619
+ static get TRANSPARENT() {
620
+ return new _Color(0, 0, 0, 0);
621
+ }
622
+ };
623
+
624
+ // src/dungeon-generator.ts
625
+ var import_heap_js = require("heap-js");
626
+
627
+ // src/map2d.ts
628
+ var DEFAULT_VALUE = -1;
629
+ var Map2D = class {
630
+ defaultValue;
631
+ _data;
632
+ get size() {
633
+ return this._data.size;
634
+ }
635
+ constructor(defaultValue = DEFAULT_VALUE) {
636
+ this.defaultValue = defaultValue;
637
+ this._data = /* @__PURE__ */ new Map();
638
+ }
639
+ _floor(x, y) {
640
+ return [floor(x), floor(y)];
641
+ }
642
+ _key(x, y) {
643
+ return `${x},${y}`;
644
+ }
645
+ _pos(key) {
646
+ return key.split(",").map((v) => parseInt(v));
647
+ }
648
+ clear() {
649
+ this._data.clear();
650
+ }
651
+ get(x, y, defaultValue = this.defaultValue) {
652
+ [x, y] = this._floor(x, y);
653
+ return this._data.get(this._key(x, y)) ?? defaultValue;
654
+ }
655
+ set(x, y, value = this.defaultValue) {
656
+ [x, y] = this._floor(x, y);
657
+ const key = this._key(x, y);
658
+ if (value === this.defaultValue) {
659
+ this._data.delete(key);
660
+ } else {
661
+ this._data.set(key, value);
662
+ }
663
+ }
664
+ forEach(callback) {
665
+ this._data.forEach((v, key) => {
666
+ const [x, y] = this._pos(key);
667
+ callback(x, y, v);
668
+ });
669
+ }
670
+ };
671
+
672
+ // src/vector.ts
673
+ var Vector = class _Vector {
674
+ x;
675
+ y;
676
+ constructor(x = 0, y = 0) {
677
+ this.x = x;
678
+ this.y = y;
679
+ }
680
+ clone() {
681
+ return new _Vector(this.x, this.y);
682
+ }
683
+ distanceTo(that) {
684
+ return distance(
685
+ this.x,
686
+ this.y,
687
+ that.x,
688
+ that.y
689
+ );
690
+ }
691
+ floored() {
692
+ return new _Vector(
693
+ Math.floor(this.x),
694
+ Math.floor(this.y)
695
+ );
696
+ }
697
+ plus(x, y) {
698
+ if (x instanceof _Vector) {
699
+ y = x.y;
700
+ x = x.x;
701
+ } else if (y === void 0) {
702
+ y = x;
703
+ }
704
+ this.x += x;
705
+ this.y += y;
706
+ return this;
707
+ }
708
+ minus(x, y) {
709
+ if (x instanceof _Vector) {
710
+ y = x.y;
711
+ x = x.x;
712
+ } else if (y === void 0) {
713
+ y = x;
714
+ }
715
+ this.x -= x;
716
+ this.y -= y;
717
+ return this;
718
+ }
719
+ times(x, y) {
720
+ if (x instanceof _Vector) {
721
+ y = x.y;
722
+ x = x.x;
723
+ } else if (y === void 0) {
724
+ y = x;
725
+ }
726
+ this.x *= x;
727
+ this.y *= y;
728
+ return this;
729
+ }
730
+ dividedBy(x, y) {
731
+ if (x instanceof _Vector) {
732
+ y = x.y;
733
+ x = x.x;
734
+ } else if (y === void 0) {
735
+ y = x;
736
+ }
737
+ this.x /= x || 1;
738
+ this.y /= y || 1;
739
+ return this;
740
+ }
741
+ static get NORTH() {
742
+ return new _Vector(0, -1);
743
+ }
744
+ static get SOUTH() {
745
+ return new _Vector(0, 1);
746
+ }
747
+ static get EAST() {
748
+ return new _Vector(1, 0);
749
+ }
750
+ static get WEST() {
751
+ return new _Vector(-1, 0);
752
+ }
753
+ };
754
+
755
+ // src/rectangle.ts
756
+ var Rectangle = class _Rectangle {
757
+ x;
758
+ y;
759
+ width;
760
+ height;
761
+ constructor(x = 0, y = 0, width = 1, height = 1) {
762
+ this.x = x;
763
+ this.y = y;
764
+ this.width = width;
765
+ this.height = height;
766
+ }
767
+ area() {
768
+ return this.width * this.height;
769
+ }
770
+ contains(target, padding = 0) {
771
+ return target instanceof Vector ? target.x >= this.x - padding && target.x <= this.x + this.width + padding && target.y >= this.y - padding && target.y <= this.y + this.height + padding : target.x >= this.x + padding && target.y >= this.y + padding && target.x + target.width <= this.x + this.width - padding && target.y + target.height <= this.y + this.height - padding;
772
+ }
773
+ intersects(other, padding = 0) {
774
+ return !(other.x - padding > this.x + this.width + padding || other.x + other.width + padding < this.x - padding || other.y - padding > this.y + this.height + padding || other.y + other.height + padding < this.y - padding);
775
+ }
776
+ center() {
777
+ return new Vector(
778
+ this.x + this.width / 2,
779
+ this.y + this.height / 2
780
+ );
781
+ }
782
+ distanceTo(other) {
783
+ return this.center().distanceTo(other.center());
784
+ }
785
+ clone() {
786
+ return new _Rectangle(this.x, this.y, this.width, this.height);
787
+ }
788
+ equals(other) {
789
+ return this.x === other.x && this.y === other.y && this.width === other.width && this.height === other.height;
790
+ }
791
+ grow(padding) {
792
+ return new _Rectangle(
793
+ this.x - padding,
794
+ this.y - padding,
795
+ this.width + padding * 2,
796
+ this.height + padding * 2
797
+ );
798
+ }
799
+ vectorInside(vec, padding = 0) {
800
+ return vec.x >= this.x - padding && vec.x <= this.x + this.width + padding && vec.y >= this.y - padding && vec.y <= this.y + this.height + padding;
801
+ }
802
+ };
803
+
804
+ // src/rng.ts
805
+ var Rng = class {
806
+ __seed;
807
+ _seed;
808
+ _uid_characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
809
+ constructor() {
810
+ this._seed = Date.now();
811
+ this.__seed = this._seed;
812
+ this._uid_characters = this.shuffle(this._uid_characters);
813
+ this.seed = this.nexti;
814
+ }
815
+ get seed() {
816
+ return this._seed;
817
+ }
818
+ set seed(value) {
819
+ this._seed = value;
820
+ this.__seed = this._seed;
821
+ }
822
+ get startingSeed() {
823
+ return this.__seed;
824
+ }
825
+ get nextf() {
826
+ this._seed |= 0;
827
+ this._seed = this._seed + 2654435769 | 0;
828
+ let t = this._seed ^ this._seed >>> 16;
829
+ t = imul(t, 569420461);
830
+ t = t ^ t >>> 15;
831
+ t = imul(t, 1935289751);
832
+ return ((t = t ^ t >>> 15) >>> 0) / 4294967296;
833
+ }
834
+ get nexti() {
835
+ return this.nextf * Number.MAX_SAFE_INTEGER | 0;
836
+ }
837
+ // NOTE: as of the core/apparatus consolidation, range(min, max) treats
838
+ // max as EXCLUSIVE (previous published versions of this package treated
839
+ // it as inclusive - if you're upgrading from an older @n3rdw1z4rd/core,
840
+ // range(0, 10) now returns [0, 10) instead of [0, 10]).
841
+ range(min2, max2) {
842
+ if (max2 === void 0) {
843
+ max2 = min2;
844
+ min2 = 0;
845
+ }
846
+ return min2 + this.nextf * (max2 - min2) | 0;
847
+ }
848
+ randomUnitVector() {
849
+ const theta = this.nextf * 2 * PI;
850
+ return [cos(theta), sin(theta)];
851
+ }
852
+ // Box-Muller-ish gaussian sample, mean 0.5 stddev 1/6 (so ~99.7% of
853
+ // samples land in [0, 1]). Uses native Math.log since a pure natural-log
854
+ // implementation isn't part of math.ts yet.
855
+ parkMillerNormal() {
856
+ const mean = 1 / 2;
857
+ const stddev = 1 / 6;
858
+ let u = 0;
859
+ let v = 0;
860
+ while (u === 0) u = this.nextf;
861
+ while (v === 0) v = this.nextf;
862
+ const n = sqrt(-2 * Math.log(u)) * cos(2 * PI * v);
863
+ return n * stddev + mean;
864
+ }
865
+ choose(...args) {
866
+ if (args.length === 1) {
867
+ if (Array.isArray(args[0])) {
868
+ return args[0][this.range(args[0].length - 1)];
869
+ } else if (typeof args[0] === "string") {
870
+ return args[0].charAt(this.range(args[0].length - 1));
871
+ } else {
872
+ return args[0];
873
+ }
874
+ } else {
875
+ return args[this.range(args.length - 1)];
876
+ }
877
+ }
878
+ shuffle(value) {
879
+ if (Array.isArray(value)) {
880
+ return value.sort(() => 0.5 - this.nextf);
881
+ } else {
882
+ return value.split("").sort(() => 0.5 - this.nextf).join("");
883
+ }
884
+ }
885
+ uid(length = 16) {
886
+ const uid = [];
887
+ for (let i = 0; i < length; i++) uid.push(this.choose(this._uid_characters));
888
+ return uid.join("");
889
+ }
890
+ randomMatrix(size) {
891
+ const rows = [];
892
+ for (let i = 0; i < size; i++) {
893
+ const row = [];
894
+ for (let j = 0; j < size; j++) {
895
+ row.push(this.nextf * 2 - 1);
896
+ }
897
+ rows.push(row);
898
+ }
899
+ return rows;
900
+ }
901
+ };
902
+ var rng = new Rng();
903
+
904
+ // src/dungeon-generator.ts
905
+ var TILE_EMPTY = 0;
906
+ var TILE_FLOOR = 1;
907
+ var TILE_PATH = 2;
908
+ var DEFAULT_LEVEL_SIZE = 64;
909
+ var DEFAULT_ROOM_MIN_SIZE = 3;
910
+ var DEFAULT_ROOM_MAX_SIZE = 9;
911
+ var DEFAULT_ROOM_PADDING = 1;
912
+ var DEFAULT_ROOM_MAX_ITERATIONS = 1e3;
913
+ var DEFAULT_PATH_TIMEOUT = 1e4;
914
+ var DEFAULT_PATH_EXTRA_PATHS = 0;
915
+ var DEFAULT_PATH_EXTRA_PATH_DENSITY = 0.1;
916
+ var DEFAULT_DOOR_CHANCE_EXISTS = 0.5;
917
+ var DIRECTIONS_8_WAY = [
918
+ { x: -1, y: 0 },
919
+ // left
920
+ { x: -1, y: -1 },
921
+ // left-up
922
+ { x: 0, y: -1 },
923
+ // up
924
+ { x: 1, y: -1 },
925
+ // up-right
926
+ { x: 1, y: 0 },
927
+ // right
928
+ { x: 1, y: 1 },
929
+ // right-down
930
+ { x: 0, y: 1 },
931
+ // down
932
+ { x: -1, y: 1 }
933
+ // down-left
934
+ ];
935
+ function _plot(map, data, tile) {
936
+ data.forEach((element) => {
937
+ if (element instanceof Rectangle) {
938
+ for (let y = 0; y < element.height; y++) {
939
+ for (let x = 0; x < element.width; x++) {
940
+ map.set(element.x + x, element.y + y, tile);
941
+ }
942
+ }
943
+ } else if (Array.isArray(element)) {
944
+ element.forEach((point) => {
945
+ map.set(point.x, point.y, tile);
946
+ });
947
+ } else {
948
+ map.set(element.x, element.y, tile);
949
+ }
950
+ });
951
+ }
952
+ function _generateRooms(params = {}) {
953
+ const size = params.size ?? DEFAULT_LEVEL_SIZE;
954
+ const minRoomSize = params.minSize ?? DEFAULT_ROOM_MIN_SIZE;
955
+ const maxRoomSize = params.maxSize ?? DEFAULT_ROOM_MAX_SIZE;
956
+ const padding = params.padding ?? DEFAULT_ROOM_PADDING;
957
+ const maxIterations = params.maxIterations ?? DEFAULT_ROOM_MAX_ITERATIONS;
958
+ const rooms = [];
959
+ let iterations = 0;
960
+ while (iterations < maxIterations) {
961
+ const baseSize = rng.range(minRoomSize, maxRoomSize);
962
+ const aspectRatio = 0.75 + rng.parkMillerNormal() * 0.5;
963
+ const width = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize * aspectRatio)));
964
+ const height = Math.min(maxRoomSize, Math.max(minRoomSize, Math.round(baseSize / aspectRatio)));
965
+ const x = Math.floor(rng.range(1 + padding, size - width - padding));
966
+ const y = Math.floor(rng.range(1 + padding, size - height - padding));
967
+ const room = new Rectangle(x, y, width, height);
968
+ if (!rooms.some((existing) => room.intersects(existing, padding))) {
969
+ rooms.push(room);
970
+ iterations = 0;
971
+ } else {
972
+ iterations += 1;
973
+ }
974
+ }
975
+ return rooms;
976
+ }
977
+ function _generateMST(rooms, params = {}) {
978
+ const timeout = params.timeout ?? DEFAULT_PATH_TIMEOUT;
979
+ const extraPathLevels = params.extraPaths ?? DEFAULT_PATH_EXTRA_PATHS;
980
+ const extraPathDensity = params.extraPathDensity ?? DEFAULT_PATH_EXTRA_PATH_DENSITY;
981
+ const startTime = Date.now();
982
+ const mst = [];
983
+ const extraPaths = [];
984
+ const visited = /* @__PURE__ */ new Set();
985
+ const heap = new import_heap_js.Heap((a, b) => a.cost - b.cost);
986
+ visited.add(0);
987
+ const zeroCenter = rooms[0].center();
988
+ for (let i = 1; i < rooms.length; i++) {
989
+ const iCenter = rooms[i].center();
990
+ heap.push({
991
+ from: 0,
992
+ to: i,
993
+ cost: squaredDistance(
994
+ zeroCenter.x,
995
+ zeroCenter.y,
996
+ iCenter.x,
997
+ iCenter.y
998
+ )
999
+ });
1000
+ }
1001
+ while (visited.size < rooms.length && Date.now() - startTime < timeout) {
1002
+ let edge = heap.pop();
1003
+ while (edge && visited.has(edge.to)) {
1004
+ edge = heap.pop();
1005
+ }
1006
+ if (!edge) break;
1007
+ const { from, to } = edge;
1008
+ visited.add(to);
1009
+ mst.push({ a: rooms[from], b: rooms[to] });
1010
+ const toCenter = rooms[to].center();
1011
+ for (let i = 0; i < rooms.length; i++) {
1012
+ if (!visited.has(i)) {
1013
+ const iCenter = rooms[i].center();
1014
+ heap.push({
1015
+ from: to,
1016
+ to: i,
1017
+ cost: squaredDistance(
1018
+ toCenter.x,
1019
+ toCenter.y,
1020
+ iCenter.x,
1021
+ iCenter.y
1022
+ )
1023
+ });
1024
+ }
1025
+ }
1026
+ }
1027
+ const remainingEdges = heap.toArray().sort((a, b) => a.cost - b.cost);
1028
+ for (let i = 0; i < extraPathLevels && i < remainingEdges.length; i++) {
1029
+ const e = remainingEdges[i];
1030
+ if (rng.nextf < extraPathDensity) {
1031
+ extraPaths.push({
1032
+ a: rooms[e.from],
1033
+ b: rooms[e.to]
1034
+ });
1035
+ }
1036
+ }
1037
+ return mst.concat(extraPaths);
1038
+ }
1039
+ function _getRectEdgePoints(rect) {
1040
+ const points = [];
1041
+ const x2 = rect.x + rect.width - 1;
1042
+ const y2 = rect.y + rect.height - 1;
1043
+ for (let x1 = rect.x; x1 < x2; x1++) {
1044
+ points.push({ x: x1, y: rect.y });
1045
+ points.push({ x: x1, y: y2 });
1046
+ }
1047
+ for (let y1 = rect.y; y1 < y2; y1++) {
1048
+ points.push({ x: rect.x, y: y1 });
1049
+ points.push({ x: x2, y: y1 });
1050
+ }
1051
+ return points;
1052
+ }
1053
+ function _getShortestPathBetweenRects(rectA, rectB) {
1054
+ const edgeA = _getRectEdgePoints(rectA);
1055
+ const edgeB = _getRectEdgePoints(rectB);
1056
+ let paths = { a: edgeA[0], b: edgeB[0], distance: Infinity };
1057
+ for (const a of edgeA) {
1058
+ for (const b of edgeB) {
1059
+ const d = distance(a.x, a.y, b.x, b.y);
1060
+ if (d < paths.distance) {
1061
+ paths = { a, b, distance: d };
1062
+ }
1063
+ }
1064
+ }
1065
+ return { a: paths.a, b: paths.b };
1066
+ }
1067
+ function _generatePaths(map, rooms, params = {}) {
1068
+ const aStar = new AStar(map);
1069
+ const paths = [];
1070
+ _generateMST(rooms, params).forEach((rects) => {
1071
+ const { a, b } = _getShortestPathBetweenRects(rects.a, rects.b);
1072
+ paths.push(aStar.findPath(a, b, params.astarFindPathParams));
1073
+ });
1074
+ return paths;
1075
+ }
1076
+ function GenerateRooms(params = {}) {
1077
+ const startTime = Date.now();
1078
+ const map = params.map ?? new Map2D(TILE_EMPTY);
1079
+ const rooms = _generateRooms(params.rooms);
1080
+ _plot(map, rooms, TILE_FLOOR);
1081
+ const paths = _generatePaths(map, rooms, params.paths);
1082
+ _plot(map, paths, TILE_PATH);
1083
+ log("GenerateRooms: done:", Date.now() - startTime, "ms");
1084
+ return { map, rooms, paths };
1085
+ }
1086
+ function GenerateDoors(map, paths, params = {}) {
1087
+ const chanceExists = params.chanceExists ?? DEFAULT_DOOR_CHANCE_EXISTS;
1088
+ const possibleDoorPoints = [];
1089
+ paths.forEach((points) => {
1090
+ if (points.length > 1) {
1091
+ possibleDoorPoints.push(points[0]);
1092
+ possibleDoorPoints.push(points[points.length - 1]);
1093
+ }
1094
+ });
1095
+ const doors = [];
1096
+ possibleDoorPoints.forEach((doorPoint) => {
1097
+ if (rng.nextf < 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)) {
1098
+ doors.push(doorPoint);
1099
+ }
1100
+ });
1101
+ return doors;
1102
+ }
1103
+ function GenerateWalls(map) {
1104
+ const walls = [];
1105
+ map.forEach((x, y, _v) => {
1106
+ DIRECTIONS_8_WAY.forEach((dir) => {
1107
+ const nx = dir.x + x;
1108
+ const ny = dir.y + y;
1109
+ if (map.get(nx, ny) === map.defaultValue) {
1110
+ walls.push({ x: nx, y: ny });
1111
+ }
1112
+ });
1113
+ });
1114
+ return walls;
1115
+ }
1116
+
197
1117
  // src/ecs.ts
198
1118
  var ECS = class _ECS {
199
1119
  _globals = /* @__PURE__ */ new Map();
@@ -434,17 +1354,33 @@ var Emitter = class {
434
1354
  this.listeners.get(eventName)?.forEach((listener) => listener(...args, eventName));
435
1355
  return this;
436
1356
  }
1357
+ clear(eventName) {
1358
+ if (eventName) {
1359
+ this.listeners.delete(eventName);
1360
+ } else {
1361
+ this.listeners.clear();
1362
+ }
1363
+ return this;
1364
+ }
437
1365
  };
438
1366
  var GlobalEmitter = new Emitter();
1367
+ var EventBus = class extends EventTarget {
1368
+ emit(type, detail) {
1369
+ this.dispatchEvent(new CustomEvent(type, { detail }));
1370
+ }
1371
+ on(type, cb) {
1372
+ this.addEventListener(type, cb);
1373
+ }
1374
+ };
1375
+ var eventBus = new EventBus();
439
1376
 
440
1377
  // src/input.ts
441
- var import_gl_matrix = require("gl-matrix");
442
1378
  var Input = class extends Emitter {
443
1379
  inputThreshold = 200;
444
1380
  _keyStates = {};
445
1381
  _mouseButtonStates = {};
446
- _mousePosition = import_gl_matrix.vec2.create();
447
- _mousePosition2 = import_gl_matrix.vec2.create();
1382
+ _mousePosition = [0, 0];
1383
+ _mousePosition2 = [0, 0];
448
1384
  get mousePosition() {
449
1385
  return this._mousePosition;
450
1386
  }
@@ -520,13 +1456,13 @@ var Input = class extends Emitter {
520
1456
  _onMouseMove(ev) {
521
1457
  const props = this._getCommonEventProps(ev);
522
1458
  const { buttons, offsetX, offsetY, movementX, movementY } = ev;
523
- this._mousePosition = import_gl_matrix.vec2.fromValues(offsetX, offsetY);
1459
+ this._mousePosition = [offsetX, offsetY];
524
1460
  const width = window.innerWidth;
525
1461
  const height = window.innerHeight;
526
- this._mousePosition2 = import_gl_matrix.vec2.fromValues(
1462
+ this._mousePosition2 = [
527
1463
  ev.clientX / width * 2 - 1,
528
1464
  -(ev.clientY / height) * 2 + 1
529
- );
1465
+ ];
530
1466
  this.emit("mouse_move", {
531
1467
  ...props,
532
1468
  buttons,
@@ -560,132 +1496,82 @@ var Input = class extends Emitter {
560
1496
  }
561
1497
  };
562
1498
 
563
- // src/math.ts
564
- var DEG2RAD = 0.01745329;
565
- function clamp(value, min, max) {
566
- return Math.max(min, Math.min(max, value));
567
- }
568
- function deg2rad(value) {
569
- return value * DEG2RAD;
570
- }
571
- function lerp(start, end, scale) {
572
- return start * (1 - scale) + end * scale;
573
- }
574
-
575
- // src/misc.ts
576
- function isNullOrUndefined(target) {
577
- return target === null || target === void 0;
578
- }
579
- var getRedYellowGreenGradientHex = (min, max) => {
580
- if (max === void 0) {
581
- max = min;
582
- min = 0;
1499
+ // src/map3d.ts
1500
+ var DEFAULT_VALUE2 = -1;
1501
+ var Map3D = class {
1502
+ defaultValue;
1503
+ _data;
1504
+ get data() {
1505
+ return this._data;
583
1506
  }
584
- if (max < 1) {
585
- max = 1;
1507
+ constructor(defaultValue = DEFAULT_VALUE2) {
1508
+ this.defaultValue = defaultValue;
1509
+ this._data = /* @__PURE__ */ new Map();
586
1510
  }
587
- const percent = min / max;
588
- const index = clamp(Math.floor(percent * 10), 0, 10);
589
- return [
590
- "#ff0000",
591
- "#ff3300",
592
- "#ff6600",
593
- "#ff9900",
594
- "#ffcc00",
595
- "#ffff00",
596
- "#ccff00",
597
- "#99ff00",
598
- "#66ff00",
599
- "#33ff00",
600
- "#00ff00"
601
- ][index];
602
- };
603
-
604
- // src/noise.ts
605
- var import_simplex_noise = require("simplex-noise");
606
-
607
- // src/rng.ts
608
- var import_gl_matrix2 = require("gl-matrix");
609
- var Rng = class {
610
- _seed = Date.now();
611
- _uid_characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
612
- constructor() {
613
- this._uid_characters = this.shuffle(this._uid_characters);
614
- this.seed = this.nexti;
1511
+ _floor(x, y, z) {
1512
+ return [floor(x), floor(y), floor(z)];
615
1513
  }
616
- get seed() {
617
- return this._seed;
1514
+ _key(x, y, z) {
1515
+ return `${x},${y},${z}`;
618
1516
  }
619
- set seed(value) {
620
- this._seed = value;
1517
+ _pos(key) {
1518
+ return key.split(",").map((v) => parseInt(v));
621
1519
  }
622
- get nextf() {
623
- this._seed |= 0;
624
- this._seed = this._seed + 2654435769 | 0;
625
- let t = this._seed ^ this._seed >>> 16;
626
- t = Math.imul(t, 569420461);
627
- t = t ^ t >>> 15;
628
- t = Math.imul(t, 1935289751);
629
- return ((t = t ^ t >>> 15) >>> 0) / 4294967296;
630
- }
631
- get nexti() {
632
- return this.nextf * Number.MAX_SAFE_INTEGER | 0;
633
- }
634
- range(min, max) {
635
- if (max === void 0) {
636
- if (min !== 0) {
637
- max = min;
638
- min = 0;
639
- } else {
640
- max = Number.MAX_SAFE_INTEGER;
641
- }
642
- }
643
- return this.nextf * (max - min + 1) + min | 0;
1520
+ clear() {
1521
+ this._data.clear();
644
1522
  }
645
- choose(...args) {
646
- if (args.length === 1) {
647
- if (Array.isArray(args[0])) {
648
- return args[0][this.range(args[0].length - 1)];
649
- } else if (typeof args[0] === "string") {
650
- return args[0].charAt(this.range(args[0].length - 1));
651
- } else {
652
- return args[0];
653
- }
654
- } else {
655
- return args[this.range(args.length - 1)];
656
- }
1523
+ get(x, y, z, defaultValue = this.defaultValue) {
1524
+ [x, y, z] = this._floor(x, y, z);
1525
+ return this._data.get(this._key(x, y, z)) ?? defaultValue;
657
1526
  }
658
- shuffle(value) {
659
- if (Array.isArray(value)) {
660
- return value.sort(() => 0.5 - this.nextf);
1527
+ set(x, y, z, value = this.defaultValue) {
1528
+ [x, y, z] = this._floor(x, y, z);
1529
+ const key = this._key(x, y, z);
1530
+ if (value === this.defaultValue) {
1531
+ this._data.delete(key);
661
1532
  } else {
662
- return value.split("").sort(() => 0.5 - this.nextf).join("");
1533
+ this._data.set(key, value);
663
1534
  }
664
1535
  }
665
- uid(length = 16) {
666
- const uid = [];
667
- for (let i = 0; i < length; i++) uid.push(this.choose(this._uid_characters));
668
- return uid.join("");
1536
+ forEach(callback) {
1537
+ this._data.forEach((v, key) => {
1538
+ const [x, y, z] = this._pos(key);
1539
+ callback(x, y, z, v);
1540
+ });
669
1541
  }
670
- randomMatrix(size) {
671
- const rows = [];
672
- for (let i = 0; i < size; i++) {
673
- const row = [];
674
- for (let j = 0; j < size; j++) {
675
- row.push(this.nextf * 2 - 1);
676
- }
677
- rows.push(row);
678
- }
679
- return rows;
1542
+ };
1543
+
1544
+ // src/misc.ts
1545
+ function isNullOrUndefined(target) {
1546
+ return target === null || target === void 0;
1547
+ }
1548
+ var getRedYellowGreenGradientHex = (min2, max2) => {
1549
+ if (max2 === void 0) {
1550
+ max2 = min2;
1551
+ min2 = 0;
680
1552
  }
681
- randomUnitVector() {
682
- const theta = rng.nextf * 2 * Math.PI;
683
- return import_gl_matrix2.vec2.fromValues(Math.cos(theta), Math.sin(theta));
1553
+ if (max2 < 1) {
1554
+ max2 = 1;
684
1555
  }
1556
+ const percent = min2 / max2;
1557
+ const index = clamp(Math.floor(percent * 10), 0, 10);
1558
+ return [
1559
+ "#ff0000",
1560
+ "#ff3300",
1561
+ "#ff6600",
1562
+ "#ff9900",
1563
+ "#ffcc00",
1564
+ "#ffff00",
1565
+ "#ccff00",
1566
+ "#99ff00",
1567
+ "#66ff00",
1568
+ "#33ff00",
1569
+ "#00ff00"
1570
+ ][index];
685
1571
  };
686
- var rng = new Rng();
687
1572
 
688
1573
  // src/noise.ts
1574
+ var import_simplex_noise = require("simplex-noise");
689
1575
  var Noise = class _Noise {
690
1576
  static _n2d;
691
1577
  static _n3d;
@@ -745,8 +1631,284 @@ var Noise = class _Noise {
745
1631
  }
746
1632
  };
747
1633
 
1634
+ // src/particle-renderer.ts
1635
+ var Renderer = class {
1636
+ _screenCanvas;
1637
+ _bufferCanvas;
1638
+ screenContext;
1639
+ bufferContext;
1640
+ get width() {
1641
+ return this._screenCanvas.width;
1642
+ }
1643
+ get height() {
1644
+ return this._screenCanvas.height;
1645
+ }
1646
+ constructor(canvas) {
1647
+ this._screenCanvas = canvas ?? document.createElement("canvas");
1648
+ this._bufferCanvas = new OffscreenCanvas(this._screenCanvas.width, this._screenCanvas.height);
1649
+ this.screenContext = this._screenCanvas.getContext("2d");
1650
+ this.bufferContext = this._bufferCanvas.getContext("2d");
1651
+ if (!this.screenContext || !this.bufferContext) {
1652
+ throw "Failed to create CanvasRenderingContext2D";
1653
+ }
1654
+ }
1655
+ appendTo(target, autoResize = true) {
1656
+ if (this._screenCanvas.parentNode) {
1657
+ this._screenCanvas.parentNode.removeChild(this._screenCanvas);
1658
+ }
1659
+ target.appendChild(this._screenCanvas);
1660
+ if (autoResize) {
1661
+ this.resize();
1662
+ }
1663
+ }
1664
+ resize(displayWidth, displayHeight) {
1665
+ const { width, height } = this._screenCanvas.parentElement?.getBoundingClientRect() ?? this._screenCanvas.getBoundingClientRect();
1666
+ displayWidth = 0 | (displayWidth ?? width);
1667
+ displayHeight = 0 | (displayHeight ?? height);
1668
+ if (this._screenCanvas.width !== displayWidth || this._screenCanvas.height !== displayHeight) {
1669
+ this._screenCanvas.width = displayWidth;
1670
+ this._screenCanvas.height = displayHeight;
1671
+ this._bufferCanvas.width = displayWidth;
1672
+ this._bufferCanvas.height = displayHeight;
1673
+ return true;
1674
+ }
1675
+ return false;
1676
+ }
1677
+ setPixel(x, y, color, size = 2) {
1678
+ this.bufferContext.fillStyle = color.hexStr;
1679
+ this.bufferContext.fillRect(x - size / 2, y - size / 2, size, size);
1680
+ }
1681
+ render() {
1682
+ this.screenContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
1683
+ this.screenContext.drawImage(this._bufferCanvas, 0, 0);
1684
+ this.bufferContext.clearRect(0, 0, this._screenCanvas.width, this._screenCanvas.height);
1685
+ }
1686
+ };
1687
+
1688
+ // src/spatial-partition-2d.ts
1689
+ var SpatialPartition2d = class {
1690
+ cells;
1691
+ cellSize;
1692
+ entities;
1693
+ constructor(cellSize, entities) {
1694
+ this.cellSize = cellSize;
1695
+ this.entities = entities;
1696
+ this.cells = Array.from(
1697
+ { length: Math.ceil(1 / cellSize) },
1698
+ () => Array.from({ length: Math.ceil(1 / cellSize) }, () => [])
1699
+ );
1700
+ for (const entity of this.entities) {
1701
+ this.addEntity(entity);
1702
+ }
1703
+ }
1704
+ addEntity(entity) {
1705
+ const cell = this.getCell(entity.x, entity.y);
1706
+ cell.push(entity);
1707
+ }
1708
+ getCell(x, y) {
1709
+ const cellX = Math.floor(x / this.cellSize);
1710
+ const cellY = Math.floor(y / this.cellSize);
1711
+ return this.cells[cellY][cellX];
1712
+ }
1713
+ getCellNeighbors(x, y) {
1714
+ const neighbors = [];
1715
+ for (let dy = -1; dy <= 1; dy++) {
1716
+ for (let dx = -1; dx <= 1; dx++) {
1717
+ let nx = x + dx;
1718
+ let ny = y + dy;
1719
+ if (nx < 0) nx = this.cells[0].length - 1;
1720
+ else if (nx >= this.cells[0].length) nx = 0;
1721
+ if (ny < 0) ny = this.cells.length - 1;
1722
+ else if (ny >= this.cells.length) ny = 0;
1723
+ neighbors.push(this.cells[ny][nx]);
1724
+ }
1725
+ }
1726
+ return neighbors;
1727
+ }
1728
+ };
1729
+
1730
+ // src/particle-system-2d.ts
1731
+ var colors = [
1732
+ Color.RED,
1733
+ Color.GREEN,
1734
+ Color.BLUE,
1735
+ Color.YELLOW,
1736
+ Color.MAGENTA
1737
+ ];
1738
+ var ParticleSystem2d = class {
1739
+ particleCount = 2e3;
1740
+ _particleSize = 2;
1741
+ _frictionHalfLife = 0.04;
1742
+ _range = 0.1;
1743
+ _rangeFactor = 0.1;
1744
+ _attractionMatrix = rng.randomMatrix(colors.length);
1745
+ _particles = [];
1746
+ _spatialPartition;
1747
+ constructor() {
1748
+ for (let i = 0; i < this.particleCount; i++) {
1749
+ this._particles.push({
1750
+ x: rng.nextf,
1751
+ y: rng.nextf,
1752
+ vx: 0,
1753
+ vy: 0,
1754
+ color: rng.range(colors.length)
1755
+ });
1756
+ }
1757
+ this._spatialPartition = new SpatialPartition2d(this._range, this._particles);
1758
+ }
1759
+ _calcForce(r, a, beta = 0.3) {
1760
+ let f = 0;
1761
+ if (r < beta) {
1762
+ f = r / beta - 1;
1763
+ } else if (beta < r && r < 1) {
1764
+ f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
1765
+ }
1766
+ return f;
1767
+ }
1768
+ _updateVelocities(deltaTimeSeconds) {
1769
+ const frictionFactor = Math.pow(
1770
+ 0.5,
1771
+ deltaTimeSeconds / this._frictionHalfLife
1772
+ );
1773
+ for (let y = 0; y < this._spatialPartition.cells.length; y++) {
1774
+ for (let x = 0; x < this._spatialPartition.cells[y].length; x++) {
1775
+ const cell = this._spatialPartition.cells[y][x];
1776
+ for (let i = 0; i < cell.length; i++) {
1777
+ let fx = 0;
1778
+ let fy = 0;
1779
+ const p1 = cell[i];
1780
+ const neighborCells = this._spatialPartition.getCellNeighbors(x, y);
1781
+ for (const neighborCell of neighborCells) {
1782
+ for (let j = 0; j < neighborCell.length; j++) {
1783
+ if (cell === neighborCell && i === j) continue;
1784
+ const p2 = neighborCell[j];
1785
+ let rx = p2.x - p1.x;
1786
+ if (Math.abs(rx) > 0.5) rx = rx > 0 ? rx - 1 : rx + 1;
1787
+ let ry = p2.y - p1.y;
1788
+ if (Math.abs(ry) > 0.5) ry = ry > 0 ? ry - 1 : ry + 1;
1789
+ const d = Math.hypot(rx, ry);
1790
+ if (d > 0 && d < this._range) {
1791
+ const f = this._calcForce(
1792
+ d / this._range,
1793
+ this._attractionMatrix[p1.color][p2.color]
1794
+ );
1795
+ fx += rx / d * f;
1796
+ fy += ry / d * f;
1797
+ }
1798
+ }
1799
+ }
1800
+ fx *= this._range * this._rangeFactor;
1801
+ fy *= this._range * this._rangeFactor;
1802
+ p1.vx *= frictionFactor;
1803
+ p1.vy *= frictionFactor;
1804
+ p1.vx += fx;
1805
+ p1.vy += fy;
1806
+ }
1807
+ }
1808
+ }
1809
+ }
1810
+ _updatePositions(deltaTimeSeconds, renderer) {
1811
+ for (let i = 0; i < this.particleCount; i++) {
1812
+ const particle = this._particles[i];
1813
+ const oldCell = this._spatialPartition.getCell(particle.x, particle.y);
1814
+ particle.x += particle.vx * deltaTimeSeconds;
1815
+ particle.y += particle.vy * deltaTimeSeconds;
1816
+ if (particle.x < 0) particle.x = 1 + particle.x % 1;
1817
+ if (particle.x > 1) particle.x = particle.x % 1;
1818
+ if (particle.y < 0) particle.y = 1 + particle.y % 1;
1819
+ if (particle.y > 1) particle.y = particle.y % 1;
1820
+ renderer.setPixel(
1821
+ particle.x * renderer.width,
1822
+ particle.y * renderer.height,
1823
+ colors[particle.color],
1824
+ this._particleSize
1825
+ );
1826
+ const newCell = this._spatialPartition.getCell(particle.x, particle.y);
1827
+ if (newCell !== oldCell) {
1828
+ const index = oldCell.indexOf(particle);
1829
+ if (index !== -1) {
1830
+ oldCell.splice(index, 1);
1831
+ }
1832
+ newCell.push(particle);
1833
+ }
1834
+ }
1835
+ }
1836
+ update(renderer, dt) {
1837
+ this._updateVelocities(dt);
1838
+ this._updatePositions(dt, renderer);
1839
+ }
1840
+ };
1841
+
1842
+ // src/poisson-disk-sampler.ts
1843
+ function PoissonDiskSampler(width, height, minDist, maxPoints = 30) {
1844
+ const k = maxPoints;
1845
+ const cellSize = minDist / Math.SQRT2;
1846
+ const gridWidth = Math.ceil(width / cellSize);
1847
+ const gridHeight = Math.ceil(height / cellSize);
1848
+ const grid = Array.from(
1849
+ { length: gridWidth },
1850
+ () => Array(gridHeight).fill(null)
1851
+ );
1852
+ const samples = [];
1853
+ const active = [];
1854
+ function gridIndex(p) {
1855
+ return {
1856
+ i: Math.floor(p.x / cellSize),
1857
+ j: Math.floor(p.y / cellSize)
1858
+ };
1859
+ }
1860
+ function isFarEnough(p) {
1861
+ const { i, j } = gridIndex(p);
1862
+ for (let x = i - 2; x <= i + 2; x++) {
1863
+ for (let y = j - 2; y <= j + 2; y++) {
1864
+ if (x < 0 || y < 0 || x >= gridWidth || y >= gridHeight) continue;
1865
+ const neighbor = grid[x][y];
1866
+ if (!neighbor) continue;
1867
+ const dx = neighbor.x - p.x;
1868
+ const dy = neighbor.y - p.y;
1869
+ if (dx * dx + dy * dy < minDist * minDist) {
1870
+ return false;
1871
+ }
1872
+ }
1873
+ }
1874
+ return true;
1875
+ }
1876
+ const initial = {
1877
+ x: rng.range(0, width),
1878
+ y: rng.range(0, height)
1879
+ };
1880
+ const { i: i0, j: j0 } = gridIndex(initial);
1881
+ grid[i0][j0] = initial;
1882
+ samples.push(initial);
1883
+ active.push(initial);
1884
+ while (active.length) {
1885
+ const index = Math.floor(rng.range(0, active.length));
1886
+ const point = active[index];
1887
+ let found = false;
1888
+ for (let n = 0; n < k; n++) {
1889
+ const angle = rng.range(0, Math.PI * 2);
1890
+ const dist = rng.range(minDist, 2 * minDist);
1891
+ const newPoint = {
1892
+ x: point.x + Math.cos(angle) * dist,
1893
+ y: point.y + Math.sin(angle) * dist
1894
+ };
1895
+ if (newPoint.x >= 0 && newPoint.y >= 0 && newPoint.x < width && newPoint.y < height && isFarEnough(newPoint)) {
1896
+ const { i, j } = gridIndex(newPoint);
1897
+ grid[i][j] = newPoint;
1898
+ samples.push(newPoint);
1899
+ active.push(newPoint);
1900
+ found = true;
1901
+ break;
1902
+ }
1903
+ }
1904
+ if (!found) {
1905
+ active.splice(index, 1);
1906
+ }
1907
+ }
1908
+ return samples;
1909
+ }
1910
+
748
1911
  // src/renderer/canvas-renderer.ts
749
- var import_gl_matrix3 = require("gl-matrix");
750
1912
  var CanvasRenderer = class {
751
1913
  ctx;
752
1914
  clearColor = "#000000";
@@ -761,7 +1923,7 @@ var CanvasRenderer = class {
761
1923
  return this.ctx?.canvas.height ?? 0;
762
1924
  }
763
1925
  get center() {
764
- return import_gl_matrix3.vec2.fromValues(this.width / 2, this.height / 2);
1926
+ return [this.width / 2, this.height / 2];
765
1927
  }
766
1928
  constructor(canvas) {
767
1929
  this.ctx = (canvas ?? document.createElement("canvas")).getContext("2d");
@@ -892,16 +2054,16 @@ function CompileShader(gl, type, source) {
892
2054
  }
893
2055
  return shader;
894
2056
  }
895
- function CreateProgram(gl, vertexShader, fragmentShader) {
896
- if (typeof vertexShader === "string") {
897
- vertexShader = CompileShader(gl, ShaderType.VERTEX, vertexShader);
2057
+ function CreateProgram(gl, vertexShader2, fragmentShader2) {
2058
+ if (typeof vertexShader2 === "string") {
2059
+ vertexShader2 = CompileShader(gl, ShaderType.VERTEX, vertexShader2);
898
2060
  }
899
- if (typeof fragmentShader === "string") {
900
- fragmentShader = CompileShader(gl, ShaderType.FRAGMENT, fragmentShader);
2061
+ if (typeof fragmentShader2 === "string") {
2062
+ fragmentShader2 = CompileShader(gl, ShaderType.FRAGMENT, fragmentShader2);
901
2063
  }
902
2064
  const program = gl.createProgram();
903
- gl.attachShader(program, vertexShader);
904
- gl.attachShader(program, fragmentShader);
2065
+ gl.attachShader(program, vertexShader2);
2066
+ gl.attachShader(program, fragmentShader2);
905
2067
  gl.linkProgram(program);
906
2068
  if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
907
2069
  throw `CreateProgram: failed to link program: ${gl.getProgramInfoLog(program)}`;
@@ -1174,6 +2336,69 @@ var SimplexNoise = class {
1174
2336
  }
1175
2337
  };
1176
2338
 
2339
+ // src/spatial-partition-3d.ts
2340
+ var SpatialPartition3d = class {
2341
+ cells;
2342
+ cellSize;
2343
+ entities;
2344
+ constructor(cellSize, entities) {
2345
+ this.cellSize = cellSize;
2346
+ this.entities = entities;
2347
+ const gridSize = Math.ceil(1 / cellSize);
2348
+ this.cells = Array.from(
2349
+ { length: gridSize },
2350
+ () => Array.from(
2351
+ { length: gridSize },
2352
+ () => Array.from({ length: gridSize }, () => [])
2353
+ )
2354
+ );
2355
+ for (const entity of this.entities) {
2356
+ this.addEntity(entity);
2357
+ }
2358
+ }
2359
+ getCell(x, y, z) {
2360
+ const cx = Math.floor(x / this.cellSize);
2361
+ const cy = Math.floor(y / this.cellSize);
2362
+ const cz = Math.floor(z / this.cellSize);
2363
+ return this.cells[cz][cy][cx];
2364
+ }
2365
+ getCellNeighbors(cx, cy, cz) {
2366
+ const neighbors = [];
2367
+ const gridSize = this.cells.length;
2368
+ for (let dz = -1; dz <= 1; dz++) {
2369
+ for (let dy = -1; dy <= 1; dy++) {
2370
+ for (let dx = -1; dx <= 1; dx++) {
2371
+ let nx = (cx + dx + gridSize) % gridSize;
2372
+ let ny = (cy + dy + gridSize) % gridSize;
2373
+ let nz = (cz + dz + gridSize) % gridSize;
2374
+ neighbors.push(this.cells[nz][ny][nx]);
2375
+ }
2376
+ }
2377
+ }
2378
+ return neighbors;
2379
+ }
2380
+ addEntity(entity) {
2381
+ const cell = this.getCell(entity.x, entity.y, entity.z);
2382
+ cell.push(entity);
2383
+ }
2384
+ };
2385
+
2386
+ // src/tilemap.ts
2387
+ var Tilemap = class {
2388
+ map = /* @__PURE__ */ new Map();
2389
+ _key(x, y) {
2390
+ x = floor(x);
2391
+ y = floor(y);
2392
+ return `${x}x${y}`;
2393
+ }
2394
+ get(x, y) {
2395
+ return this.map.get(this._key(x, y));
2396
+ }
2397
+ set(x, y, v) {
2398
+ this.map.set(this._key(x, y), v);
2399
+ }
2400
+ };
2401
+
1177
2402
  // src/three/cube-sphere-geometry.ts
1178
2403
  var import_three = require("three");
1179
2404
  var CubeSphereGeometry = class extends import_three.BoxGeometry {
@@ -1193,6 +2418,8 @@ var CubeSphereGeometry = class extends import_three.BoxGeometry {
1193
2418
  }
1194
2419
  attrPositions.needsUpdate = true;
1195
2420
  }
2421
+ size;
2422
+ segments;
1196
2423
  _halfSize;
1197
2424
  applyFractalBrownianMotion(octaves, persistence, scale, amplitude) {
1198
2425
  const attrPositions = this.attributes.position;
@@ -1222,15 +2449,15 @@ var CubeSphereGeometry = class extends import_three.BoxGeometry {
1222
2449
  };
1223
2450
 
1224
2451
  // src/three/texture-atlas.ts
1225
- var import_gl_matrix4 = require("gl-matrix");
1226
2452
  var import_three2 = require("three");
1227
2453
  function LoadTexture(url) {
1228
2454
  return new Promise((res, rej) => {
1229
2455
  new import_three2.TextureLoader().load(
1230
2456
  url,
1231
2457
  (texture) => {
1232
- const width = texture.source.data.width;
1233
- const height = texture.source.data.height;
2458
+ const data = texture.source.data;
2459
+ const width = data.width;
2460
+ const height = data.height;
1234
2461
  res({ width, height, texture });
1235
2462
  },
1236
2463
  (_ev) => {
@@ -1239,6 +2466,22 @@ function LoadTexture(url) {
1239
2466
  );
1240
2467
  });
1241
2468
  }
2469
+ function CreateSubTexture(texture, x, y, w, h) {
2470
+ texture = texture.clone();
2471
+ texture.magFilter = import_three2.NearestFilter;
2472
+ texture.wrapS = import_three2.RepeatWrapping;
2473
+ const data = texture.source.data;
2474
+ const textureWidth = data.width;
2475
+ const textureHeight = data.height;
2476
+ w /= textureWidth;
2477
+ h /= textureHeight;
2478
+ x /= textureWidth;
2479
+ y = 1 - h - y / textureHeight;
2480
+ texture.offset.set(x, y);
2481
+ texture.repeat.set(w, h);
2482
+ texture.needsUpdate = true;
2483
+ return texture;
2484
+ }
1242
2485
  var TextureAtlas = class _TextureAtlas extends import_three2.MeshLambertMaterial {
1243
2486
  constructor(textureData, textureWidth, textureHeight = textureWidth, params) {
1244
2487
  super({
@@ -1254,13 +2497,16 @@ var TextureAtlas = class _TextureAtlas extends import_three2.MeshLambertMaterial
1254
2497
  this._uh = this.textureHeight / this.textureData.height;
1255
2498
  this.textureData.texture.magFilter = import_three2.NearestFilter;
1256
2499
  }
2500
+ textureData;
2501
+ textureWidth;
2502
+ textureHeight;
1257
2503
  _uw;
1258
2504
  _uh;
1259
2505
  getUv(voxel, ux, uy) {
1260
- return import_gl_matrix4.vec2.fromValues(
2506
+ return [
1261
2507
  (voxel + ux) * this._uw,
1262
2508
  1 - (1 - uy) * this._uh
1263
- );
2509
+ ];
1264
2510
  }
1265
2511
  static CreateFromUrl(url, textureWidth, textureHeight = textureWidth, params) {
1266
2512
  return LoadTexture(url).then((textureData) => new _TextureAtlas(
@@ -1271,6 +2517,61 @@ var TextureAtlas = class _TextureAtlas extends import_three2.MeshLambertMaterial
1271
2517
  ));
1272
2518
  }
1273
2519
  };
2520
+ var AtlasTextureMaterial = class _AtlasTextureMaterial extends import_three2.MeshLambertMaterial {
2521
+ textureData;
2522
+ tilePixelWidth;
2523
+ tilePixelHeight;
2524
+ _tileCount;
2525
+ _uvWidth;
2526
+ _uvHeight;
2527
+ _textureOffsetWidth;
2528
+ _textureOffsetHeight;
2529
+ constructor(textureData, atlasParams = {}, materialParams = {}) {
2530
+ super({
2531
+ map: textureData.texture,
2532
+ alphaTest: 0.1,
2533
+ transparent: true,
2534
+ name: "AtlasTextureMaterial",
2535
+ ...materialParams
2536
+ });
2537
+ this.textureData = textureData;
2538
+ this.textureData.texture.magFilter = import_three2.NearestFilter;
2539
+ this.tilePixelWidth = atlasParams.tilePixelWidth ?? 16;
2540
+ this.tilePixelHeight = atlasParams.tilePixelHeight ?? 16;
2541
+ this._textureOffsetWidth = atlasParams.tilePixelOffsetWidth ?? 0;
2542
+ this._textureOffsetHeight = atlasParams.tilePixelOffsetHeight ?? 0;
2543
+ this._tileCount = Math.floor(this.textureData.width / this.tilePixelWidth);
2544
+ this._uvWidth = this.tilePixelWidth / (this.textureData.width - this._textureOffsetWidth);
2545
+ this._uvHeight = this.tilePixelHeight / (this.textureData.height - this._textureOffsetHeight);
2546
+ }
2547
+ getTileUVs(tileIndex, vertexIndex) {
2548
+ const col = tileIndex % this._tileCount;
2549
+ const row = Math.floor(tileIndex / this._tileCount);
2550
+ const baseU = this._textureOffsetWidth / this.textureData.width + col * this._uvWidth;
2551
+ const baseV = this._textureOffsetHeight / this.textureData.height + row * this._uvHeight;
2552
+ const uvCorners = [
2553
+ [0, 0],
2554
+ // bottom-left
2555
+ [1, 0],
2556
+ // bottom-right
2557
+ [0, 1],
2558
+ // top-left
2559
+ [1, 1]
2560
+ // top-right
2561
+ ];
2562
+ const [u, v] = uvCorners[vertexIndex];
2563
+ const uvx = baseU + u * this._uvWidth;
2564
+ const uvy = 1 - (baseV + v * this._uvHeight);
2565
+ return [uvx, uvy];
2566
+ }
2567
+ static fromUrl(url, atlasParams = {}, materialParams = {}) {
2568
+ return LoadTexture(url).then((textureData) => new _AtlasTextureMaterial(
2569
+ textureData,
2570
+ atlasParams,
2571
+ materialParams
2572
+ ));
2573
+ }
2574
+ };
1274
2575
 
1275
2576
  // src/three/threejs-boiler-plate.ts
1276
2577
  var import_three4 = require("three");
@@ -1292,7 +2593,7 @@ var ThreeJsCameraRig = class extends import_three3.Group {
1292
2593
  super();
1293
2594
  this.gimbal = new import_three3.Group();
1294
2595
  this.add(this.gimbal);
1295
- this.camera = new import_three3.PerspectiveCamera(
2596
+ this.camera = params?.camera ?? new import_three3.PerspectiveCamera(
1296
2597
  params?.fov ?? 75,
1297
2598
  params?.aspect ?? 2,
1298
2599
  params?.near ?? 0.1,
@@ -1325,6 +2626,7 @@ var ThreeJsBoilerPlate = class {
1325
2626
  raycaster = new import_three4.Raycaster();
1326
2627
  renderer;
1327
2628
  cameraRig;
2629
+ orbitControls;
1328
2630
  get canvas() {
1329
2631
  return this.renderer.domElement;
1330
2632
  }
@@ -1337,14 +2639,38 @@ var ThreeJsBoilerPlate = class {
1337
2639
  this.renderer = new import_three4.WebGLRenderer(params?.renderer);
1338
2640
  this.cameraRig = new ThreeJsCameraRig(params?.camera);
1339
2641
  this.scene.add(this.cameraRig);
1340
- GlobalEmitter.on("mouse_move", ({ deltaX, deltaY }) => {
2642
+ if (params?.parentElement) {
2643
+ this.appendTo(params.parentElement);
2644
+ }
2645
+ }
2646
+ // Mutually exclusive with enableOrbitControls() - pick one. Gives you
2647
+ // manual orbit()/dolly() with tilt clamping and target-following, driven
2648
+ // by this.input's mouse events.
2649
+ enableCameraRigControls() {
2650
+ this.orbitControls?.dispose();
2651
+ this.orbitControls = void 0;
2652
+ this.input.on("mouse_move", ({ deltaX, deltaY }) => {
1341
2653
  if (this.input.isMouseButtonDown(0)) {
1342
2654
  this.cameraRig.orbit(deltaX, deltaY);
1343
2655
  }
1344
2656
  }).on("mouse_wheel", ({ deltaY }) => this.cameraRig.dolly(deltaY));
1345
- if (params?.parentElement) {
1346
- this.appendTo(params.parentElement);
1347
- }
2657
+ }
2658
+ // Mutually exclusive with enableCameraRigControls() - pick one. Uses
2659
+ // Three's own OrbitControls instead of the hand-rolled rig math; call
2660
+ // update() once per frame in your render loop while this is active.
2661
+ // Async because OrbitControls only ships as an ESM-only addon module -
2662
+ // a dynamic import avoids forcing this whole package (built as both
2663
+ // CJS and ESM) to statically import an ESM-only file.
2664
+ async enableOrbitControls() {
2665
+ const { OrbitControls } = await import("three/examples/jsm/Addons.js");
2666
+ this.orbitControls = new OrbitControls(this.camera, this.canvas);
2667
+ this.orbitControls.minDistance = 0.5;
2668
+ this.orbitControls.maxDistance = 100;
2669
+ this.orbitControls.update();
2670
+ }
2671
+ // Call once per frame if enableOrbitControls() is active - no-op otherwise.
2672
+ update() {
2673
+ this.orbitControls?.update();
1348
2674
  }
1349
2675
  appendTo(htmlElement) {
1350
2676
  if (this.canvas.parentElement) {
@@ -1373,6 +2699,9 @@ var ThreeJsBoilerPlate = class {
1373
2699
  if (params.ambientLight !== false) this.scene.add(new import_three4.AmbientLight());
1374
2700
  if (params.directionalLight !== false) this.scene.add(new import_three4.DirectionalLight());
1375
2701
  if (params.gridHelper !== false) this.scene.add(new import_three4.GridHelper(100, 100, 16711680));
2702
+ if (params.enableControls === true) {
2703
+ this.enableCameraRigControls();
2704
+ }
1376
2705
  }
1377
2706
  pick() {
1378
2707
  const pickX = this.input.mousePosition[0] / this.renderer.domElement.width * 2 - 1;
@@ -1406,7 +2735,7 @@ var ThreeJsPlayerController = class extends import_three5.Group {
1406
2735
  constructor(camera) {
1407
2736
  super();
1408
2737
  this.velocity = new import_three5.Vector3();
1409
- this.cameraRig = new ThreeJsCameraRig(camera);
2738
+ this.cameraRig = new ThreeJsCameraRig({ camera });
1410
2739
  this.add(this.cameraRig);
1411
2740
  }
1412
2741
  update(deltaTime) {
@@ -1416,93 +2745,106 @@ var ThreeJsPlayerController = class extends import_three5.Group {
1416
2745
  }
1417
2746
  };
1418
2747
 
1419
- // src/three/voxel-geometry.ts
2748
+ // src/three/voxel-mesh.ts
1420
2749
  var import_three6 = require("three");
1421
- var import_gl_matrix5 = require("gl-matrix");
1422
- function xyz2key(x, y, z) {
1423
- return `${x},${y},${z}`;
1424
- }
1425
- function key2xyz(key) {
1426
- return key.split(",").map((v) => parseFloat(v));
1427
- }
1428
- var VoxelGeometry = class extends import_three6.BufferGeometry {
1429
- _voxels = /* @__PURE__ */ new Map();
1430
- colors = [
1431
- [1, 0, 0, 1],
1432
- // Red
1433
- [0, 1, 0, 1],
1434
- // Green
1435
- [0, 0, 1, 1]
1436
- // Blue
1437
- ];
1438
- constructor() {
2750
+ var VoxelMesh = class extends import_three6.Mesh {
2751
+ type = "VoxelMesh";
2752
+ width;
2753
+ depth;
2754
+ height;
2755
+ colorPalette;
2756
+ voxels;
2757
+ needsGeometryUpdate = true;
2758
+ constructor(width, depth, height, material, name) {
1439
2759
  super();
1440
- const size = 1;
1441
- for (let x = -size; x <= size; x++) {
1442
- for (let y = -size; y <= size; y++) {
1443
- for (let z = -size; z <= size; z++) {
1444
- this._voxels.set(xyz2key(x, y, z), 2);
1445
- }
1446
- }
1447
- }
2760
+ this.width = width;
2761
+ this.depth = depth;
2762
+ this.height = height;
2763
+ this.material = material;
2764
+ this.material.vertexColors = true;
2765
+ this.name = name ?? "VoxelMesh";
2766
+ this.colorPalette = BuildDefaultPalette();
2767
+ this.voxels = /* @__PURE__ */ new Map();
2768
+ this.geometry = new import_three6.BufferGeometry();
1448
2769
  this.updateGeometry();
1449
2770
  }
2771
+ _xyz2k(x, y, z) {
2772
+ x = Math.abs(Math.floor(x));
2773
+ y = Math.abs(Math.floor(y));
2774
+ z = Math.abs(Math.floor(z));
2775
+ return `${x},${y},${z}`;
2776
+ }
2777
+ _k2xyz(k) {
2778
+ const [x, y, z] = k.split(",").map((s) => parseInt(s));
2779
+ return { x, y, z };
2780
+ }
1450
2781
  get(x, y, z) {
1451
- return this._voxels.get(xyz2key(x, y, z));
1452
- }
1453
- set(x, y, z, value) {
1454
- this._voxels.set(xyz2key(x, y, z), value);
1455
- }
1456
- getVoxelCoordsFromFaceIndex(faceIndex, size, height) {
1457
- const facePerVoxel = 6;
1458
- const triangleIndex = Math.floor(faceIndex / 2);
1459
- const voxelIndex = Math.floor(triangleIndex / facePerVoxel);
1460
- const x = voxelIndex % size;
1461
- const y = Math.floor(voxelIndex / size % height);
1462
- const z = Math.floor(voxelIndex / (size * height));
1463
- return import_gl_matrix5.vec3.fromValues(x, y, z);
1464
- }
1465
- // public changeVoxelColor(faceIndex: number, newColor: THREE.Color) {
1466
- // const colorAttr = voxelMesh.geometry.getAttribute("color") as THREE.BufferAttribute;
1467
- // if (!colorAttr) return; // Ensure the color attribute exists
1468
- // const colors = colorAttr.array as Float32Array;
1469
- // // Each face has 3 vertices, each vertex has 4 components (RGBA)
1470
- // const vertexIndex = faceIndex * 3 * 4; // Multiply by 4 because each vertex has RGBA
1471
- // for (let i = 0; i < 3; i++) { // Update all three vertices of the face
1472
- // colors[vertexIndex + i * 4] = newColor.r;
1473
- // colors[vertexIndex + i * 4 + 1] = newColor.g;
1474
- // colors[vertexIndex + i * 4 + 2] = newColor.b;
1475
- // colors[vertexIndex + i * 4 + 3] = 1; // Ensure full opacity
1476
- // }
1477
- // colorAttr.needsUpdate = true; // Tell Three.js to update the buffer
1478
- // }
2782
+ let n = -1;
2783
+ if (x >= 0 && y >= 0 && z >= 0 && x < this.width && y < this.height && z < this.depth) {
2784
+ n = this.voxels.get(this._xyz2k(x, y, z)) ?? -1;
2785
+ }
2786
+ return n;
2787
+ }
2788
+ set(x, y, z, n) {
2789
+ if (x >= 0 && y >= 0 && z >= 0 && x < this.width && y < this.height && z < this.depth) {
2790
+ if (n === void 0) this.voxels.delete(this._xyz2k(x, y, z));
2791
+ else this.voxels.set(this._xyz2k(x, y, z), n);
2792
+ this.needsGeometryUpdate = true;
2793
+ }
2794
+ }
2795
+ clearVoxels() {
2796
+ this.voxels.clear();
2797
+ }
2798
+ setSize(width, depth, height) {
2799
+ this.forEachVoxel((x, y, z) => {
2800
+ if (x >= width || y >= height || z >= depth) this.set(x, y, z);
2801
+ });
2802
+ this.width = width;
2803
+ this.depth = depth;
2804
+ this.height = height;
2805
+ this.needsGeometryUpdate = true;
2806
+ }
2807
+ forEachVoxel(callback) {
2808
+ this.voxels.forEach((n, k) => {
2809
+ const { x, y, z } = this._k2xyz(k);
2810
+ callback(x, y, z, n);
2811
+ });
2812
+ }
2813
+ importVoxelData(voxelData) {
2814
+ this.clearVoxels();
2815
+ this.name = voxelData.name;
2816
+ this.setSize(voxelData.width, voxelData.depth, voxelData.height);
2817
+ voxelData.palette.forEach((color, i) => {
2818
+ if (i < this.colorPalette.length) {
2819
+ this.colorPalette[i] = color;
2820
+ } else {
2821
+ this.colorPalette.push(color);
2822
+ }
2823
+ });
2824
+ voxelData.voxels.forEach((voxel) => {
2825
+ const { x, y, z, color } = voxel;
2826
+ this.set(x, y, z, color);
2827
+ });
2828
+ this.updateGeometry();
2829
+ }
1479
2830
  updateGeometry() {
1480
- const positions = [];
1481
- const normals = [];
1482
- const colors = [];
1483
- const indices = [];
1484
- let needsUpdate = false;
1485
- this._voxels.forEach((voxel, key) => {
1486
- if (voxel) {
1487
- const [x, y, z] = key2xyz(key);
2831
+ if (this.needsGeometryUpdate) {
2832
+ const positions = [];
2833
+ const normals = [];
2834
+ const colors2 = [];
2835
+ const indices = [];
2836
+ this.forEachVoxel((x, y, z, n) => {
1488
2837
  VoxelFaces.forEach((faces) => {
1489
2838
  const [dx, dy, dz] = faces[0];
1490
- const neighborVoxel = this.get(x + dx, y + dy, z + dz) ?? 0;
1491
- if (!neighborVoxel) {
2839
+ const neighborVoxel = this.get(x + dx, y + dy, z + dz);
2840
+ if (neighborVoxel < 0) {
1492
2841
  const positionIndex = positions.length / 3;
1493
- faces.forEach((faceVerts) => {
1494
- const [
1495
- nx,
1496
- ny,
1497
- nz,
1498
- px,
1499
- py,
1500
- pz
1501
- /*ux, uy*/
1502
- ] = faceVerts;
2842
+ faces.forEach((face) => {
2843
+ const [nx, ny, nz, px, py, pz] = face;
1503
2844
  positions.push(x + px, y + py, z + pz);
1504
2845
  normals.push(nx, ny, nz);
1505
- colors.push(...this.colors[voxel - 1]);
2846
+ const { r, g, b } = new import_three6.Color(this.colorPalette[n]);
2847
+ colors2.push(r, g, b, 1);
1506
2848
  });
1507
2849
  indices.push(
1508
2850
  positionIndex,
@@ -1512,106 +2854,748 @@ var VoxelGeometry = class extends import_three6.BufferGeometry {
1512
2854
  positionIndex + 1,
1513
2855
  positionIndex + 3
1514
2856
  );
1515
- needsUpdate = true;
1516
2857
  }
1517
2858
  });
1518
- this.setAttribute("position", new import_three6.BufferAttribute(new Float32Array(positions), 3));
1519
- this.setAttribute("normal", new import_three6.BufferAttribute(new Float32Array(normals), 3));
1520
- this.setAttribute("color", new import_three6.BufferAttribute(new Float32Array(colors), 4));
1521
- this.setIndex(indices);
1522
- }
1523
- });
1524
- if (needsUpdate) {
1525
- this.attributes.position.needsUpdate = true;
1526
- this.computeVertexNormals();
2859
+ });
2860
+ this.geometry.setAttribute("position", new import_three6.BufferAttribute(new Float32Array(positions), 3));
2861
+ this.geometry.setAttribute("normal", new import_three6.BufferAttribute(new Float32Array(normals), 3));
2862
+ this.geometry.setAttribute("color", new import_three6.BufferAttribute(new Float32Array(colors2), 4));
2863
+ this.geometry.setIndex(indices);
2864
+ this.geometry.computeBoundingSphere();
2865
+ this.updateMatrixWorld();
1527
2866
  }
2867
+ this.needsGeometryUpdate = false;
2868
+ }
2869
+ exportData() {
2870
+ const voxelData = {
2871
+ name: this.name,
2872
+ width: this.width,
2873
+ depth: this.depth,
2874
+ height: this.height,
2875
+ palette: [...this.colorPalette],
2876
+ voxels: []
2877
+ };
2878
+ this.forEachVoxel((x, y, z, color) => {
2879
+ voxelData.voxels.push({ x, y, z, color });
2880
+ });
2881
+ return voxelData;
1528
2882
  }
1529
2883
  };
1530
- var lo = -0.5;
1531
- var hi = 0.5;
1532
2884
  var VoxelFaces = [
1533
- // [nx, ny, nz, px, py, pz, ux, uy]
2885
+ // [nx, ny, nz, px, py, pz]
1534
2886
  [
1535
2887
  //left
1536
- [-1, 0, 0, lo, hi, lo, 0, 1],
1537
- [-1, 0, 0, lo, lo, lo, 0, 0],
1538
- [-1, 0, 0, lo, hi, hi, 1, 1],
1539
- [-1, 0, 0, lo, lo, hi, 1, 0]
2888
+ [-1, 0, 0, 0, 1, 0],
2889
+ [-1, 0, 0, 0, 0, 0],
2890
+ [-1, 0, 0, 0, 1, 1],
2891
+ [-1, 0, 0, 0, 0, 1]
1540
2892
  ],
1541
2893
  [
1542
2894
  //right
1543
- [1, 0, 0, hi, hi, hi, 0, 1],
1544
- [1, 0, 0, hi, lo, hi, 0, 0],
1545
- [1, 0, 0, hi, hi, lo, 1, 1],
1546
- [1, 0, 0, hi, lo, lo, 1, 0]
2895
+ [1, 0, 0, 1, 1, 1],
2896
+ [1, 0, 0, 1, 0, 1],
2897
+ [1, 0, 0, 1, 1, 0],
2898
+ [1, 0, 0, 1, 0, 0]
1547
2899
  ],
1548
2900
  [
1549
2901
  //bottom
1550
- [0, -1, 0, hi, lo, hi, 1, 0],
1551
- [0, -1, 0, lo, lo, hi, 0, 0],
1552
- [0, -1, 0, hi, lo, lo, 1, 1],
1553
- [0, -1, 0, lo, lo, lo, 0, 1]
2902
+ [0, -1, 0, 1, 0, 1],
2903
+ [0, -1, 0, 0, 0, 1],
2904
+ [0, -1, 0, 1, 0, 0],
2905
+ [0, -1, 0, 0, 0, 0]
1554
2906
  ],
1555
2907
  [
1556
2908
  //top
1557
- [0, 1, 0, lo, hi, hi, 1, 1],
1558
- [0, 1, 0, hi, hi, hi, 0, 1],
1559
- [0, 1, 0, lo, hi, lo, 1, 0],
1560
- [0, 1, 0, hi, hi, lo, 0, 0]
2909
+ [0, 1, 0, 0, 1, 1],
2910
+ [0, 1, 0, 1, 1, 1],
2911
+ [0, 1, 0, 0, 1, 0],
2912
+ [0, 1, 0, 1, 1, 0]
1561
2913
  ],
1562
2914
  [
1563
2915
  //back
1564
- [0, 0, -1, hi, lo, lo, 0, 0],
1565
- [0, 0, -1, lo, lo, lo, 1, 0],
1566
- [0, 0, -1, hi, hi, lo, 0, 1],
1567
- [0, 0, -1, lo, hi, lo, 1, 1]
2916
+ [0, 0, -1, 1, 0, 0],
2917
+ [0, 0, -1, 0, 0, 0],
2918
+ [0, 0, -1, 1, 1, 0],
2919
+ [0, 0, -1, 0, 1, 0]
1568
2920
  ],
1569
2921
  [
1570
2922
  //front
1571
- [0, 0, 1, lo, lo, hi, 0, 0],
1572
- [0, 0, 1, hi, lo, hi, 1, 0],
1573
- [0, 0, 1, lo, hi, hi, 0, 1],
1574
- [0, 0, 1, hi, hi, hi, 1, 1]
2923
+ [0, 0, 1, 0, 0, 1],
2924
+ [0, 0, 1, 1, 0, 1],
2925
+ [0, 0, 1, 0, 1, 1],
2926
+ [0, 0, 1, 1, 1, 1]
1575
2927
  ]
1576
2928
  ];
2929
+ function BuildDefaultPalette(palette) {
2930
+ palette = palette ?? Colors.rgb48;
2931
+ const grayscale = [];
2932
+ const count = 16;
2933
+ for (let i = 0; i < count; i++) {
2934
+ const grey = Math.floor(i / count * 255);
2935
+ grayscale.push(`rgb(${grey}, ${grey}, ${grey})`);
2936
+ }
2937
+ return [...palette, ...grayscale];
2938
+ }
2939
+ var Colors = {
2940
+ rgb12: [
2941
+ "#FF0000",
2942
+ "#FF8800",
2943
+ "#FFFF00",
2944
+ "#88FF00",
2945
+ "#00FF00",
2946
+ "#00FF88",
2947
+ "#00FFFF",
2948
+ "#0088FF",
2949
+ "#0000FF",
2950
+ "#8800FF",
2951
+ "#FF00FF",
2952
+ "#FF0080"
2953
+ ],
2954
+ rgb24: [
2955
+ "#FF0000",
2956
+ "#FF4000",
2957
+ "#FF8000",
2958
+ "#FFBF00",
2959
+ "#FFFF00",
2960
+ "#CCFF00",
2961
+ "#80FF00",
2962
+ "#40FF00",
2963
+ "#00FF00",
2964
+ "#00FF40",
2965
+ "#00FF80",
2966
+ "#00FFCC",
2967
+ "#00FFFF",
2968
+ "#00CCFF",
2969
+ "#0080FF",
2970
+ "#0040FF",
2971
+ "#0000FF",
2972
+ "#4000FF",
2973
+ "#8000FF",
2974
+ "#CC00FF",
2975
+ "#FF00FF",
2976
+ "#FF00CC",
2977
+ "#FF0080",
2978
+ "#FF0040"
2979
+ ],
2980
+ rgb48: [
2981
+ "#FF0000",
2982
+ "#FF2000",
2983
+ "#FF4000",
2984
+ "#FF6000",
2985
+ "#FF8000",
2986
+ "#FFAA00",
2987
+ "#FFCC00",
2988
+ "#FFEE00",
2989
+ "#FFFF00",
2990
+ "#DDFF00",
2991
+ "#CCFF00",
2992
+ "#AAFF00",
2993
+ "#80FF00",
2994
+ "#60FF00",
2995
+ "#40FF00",
2996
+ "#20FF00",
2997
+ "#00FF00",
2998
+ "#00FF20",
2999
+ "#00FF40",
3000
+ "#00FF60",
3001
+ "#00FF80",
3002
+ "#00FFAA",
3003
+ "#00FFCC",
3004
+ "#00FFDD",
3005
+ "#00FFFF",
3006
+ "#00DDFF",
3007
+ "#00CCFF",
3008
+ "#0099FF",
3009
+ "#0080FF",
3010
+ "#0060FF",
3011
+ "#0040FF",
3012
+ "#0020FF",
3013
+ "#0000FF",
3014
+ "#2000FF",
3015
+ "#4000FF",
3016
+ "#6000FF",
3017
+ "#8000FF",
3018
+ "#AA00FF",
3019
+ "#CC00FF",
3020
+ "#DD00FF",
3021
+ "#FF00FF",
3022
+ "#FF00EE",
3023
+ "#FF00CC",
3024
+ "#FF00AA",
3025
+ "#FF0080",
3026
+ "#FF0060",
3027
+ "#FF0040",
3028
+ "#FF0020"
3029
+ ],
3030
+ rgb64: [
3031
+ "#000000",
3032
+ "#000055",
3033
+ "#0000AA",
3034
+ "#0000FF",
3035
+ "#005500",
3036
+ "#005555",
3037
+ "#0055AA",
3038
+ "#0055FF",
3039
+ "#00AA00",
3040
+ "#00AA55",
3041
+ "#00AAAA",
3042
+ "#00AAFF",
3043
+ "#00FF00",
3044
+ "#00FF55",
3045
+ "#00FFAA",
3046
+ "#00FFFF",
3047
+ "#550000",
3048
+ "#550055",
3049
+ "#5500AA",
3050
+ "#5500FF",
3051
+ "#555500",
3052
+ "#555555",
3053
+ "#5555AA",
3054
+ "#5555FF",
3055
+ "#55AA00",
3056
+ "#55AA55",
3057
+ "#55AAAA",
3058
+ "#55AAFF",
3059
+ "#55FF00",
3060
+ "#55FF55",
3061
+ "#55FFAA",
3062
+ "#55FFFF",
3063
+ "#AA0000",
3064
+ "#AA0055",
3065
+ "#AA00AA",
3066
+ "#AA00FF",
3067
+ "#AA5500",
3068
+ "#AA5555",
3069
+ "#AA55AA",
3070
+ "#AA55FF",
3071
+ "#AAAA00",
3072
+ "#AAAA55",
3073
+ "#AAAAAA",
3074
+ "#AAAAFF",
3075
+ "#AAFF00",
3076
+ "#AAFF55",
3077
+ "#AAFFAA",
3078
+ "#AAFFFF",
3079
+ "#FF0000",
3080
+ "#FF0055",
3081
+ "#FF00AA",
3082
+ "#FF00FF",
3083
+ "#FF5500",
3084
+ "#FF5555",
3085
+ "#FF55AA",
3086
+ "#FF55FF",
3087
+ "#FFAA00",
3088
+ "#FFAA55",
3089
+ "#FFAAAA",
3090
+ "#FFAAFF",
3091
+ "#FFFF00",
3092
+ "#FFFF55",
3093
+ "#FFFFAA",
3094
+ "#FFFFFF"
3095
+ ]
3096
+ };
3097
+
3098
+ // src/three/particle-system-3d.ts
3099
+ var import_three7 = require("three");
3100
+ var vertexShader = `
3101
+ uniform float pointSize;
3102
+
3103
+ varying vec4 vColor;
3104
+
3105
+ void main() {
3106
+ vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
3107
+
3108
+ gl_Position = projectionMatrix * mvPosition;
3109
+ gl_PointSize = pointSize;
3110
+
3111
+ vColor = color;
3112
+ }`;
3113
+ var fragmentShader = `
3114
+ varying vec4 vColor;
3115
+
3116
+ void main() {
3117
+ gl_FragColor = vColor;
3118
+ }`;
3119
+ var Colors2 = [
3120
+ [1, 0, 0, 1],
3121
+ // red
3122
+ [0, 1, 0, 1],
3123
+ // green,
3124
+ [0, 0, 1, 1],
3125
+ // blue,
3126
+ [1, 1, 0, 1],
3127
+ // yellow,
3128
+ [1, 0, 1, 1]
3129
+ // magenta,
3130
+ ];
3131
+ var ParticleSystem3d = class extends import_three7.Group {
3132
+ particleCount = 1e3;
3133
+ _geometry;
3134
+ _particles = [];
3135
+ _frictionHalfLife = 0.04;
3136
+ _range = 0.2;
3137
+ _rangeFactor = 0.1;
3138
+ _attractionMatrix;
3139
+ _spatialPartition;
3140
+ constructor() {
3141
+ super();
3142
+ const uniforms = {
3143
+ pointSize: { value: 4 }
3144
+ };
3145
+ this.position.x = -0.5;
3146
+ this.position.y = -0.5;
3147
+ this.position.z = -0.5;
3148
+ this._geometry = new import_three7.BufferGeometry();
3149
+ this._geometry.setAttribute("position", new import_three7.Float32BufferAttribute([], 3));
3150
+ this._geometry.setAttribute("color", new import_three7.Float32BufferAttribute([], 4));
3151
+ const material = new import_three7.ShaderMaterial({
3152
+ uniforms,
3153
+ vertexShader,
3154
+ fragmentShader,
3155
+ depthTest: true,
3156
+ depthWrite: false,
3157
+ vertexColors: true
3158
+ });
3159
+ const pointsMesh = new import_three7.Points(this._geometry, material);
3160
+ this.add(pointsMesh);
3161
+ for (let i = 0; i < this.particleCount; i++) {
3162
+ this._particles.push({
3163
+ x: rng.nextf,
3164
+ y: rng.nextf,
3165
+ z: rng.nextf,
3166
+ vx: 0,
3167
+ vy: 0,
3168
+ vz: 0,
3169
+ color: rng.range(Colors2.length)
3170
+ });
3171
+ }
3172
+ this._attractionMatrix = rng.randomMatrix(Colors2.length);
3173
+ this._spatialPartition = new SpatialPartition3d(this._range, this._particles);
3174
+ }
3175
+ _calcForce(r, a, beta = 0.3) {
3176
+ let f = 0;
3177
+ if (r < beta) {
3178
+ f = r / beta - 1;
3179
+ } else if (beta < r && r < 1) {
3180
+ f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
3181
+ }
3182
+ return f;
3183
+ }
3184
+ _updateVelocities(dt) {
3185
+ const frictionFactor = Math.pow(
3186
+ 0.5,
3187
+ dt / this._frictionHalfLife
3188
+ );
3189
+ for (let z = 0; z < this._spatialPartition.cells.length; z++) {
3190
+ for (let y = 0; y < this._spatialPartition.cells[z].length; y++) {
3191
+ for (let x = 0; x < this._spatialPartition.cells[z][y].length; x++) {
3192
+ const cell = this._spatialPartition.cells[z][y][x];
3193
+ for (let i = 0; i < cell.length; i++) {
3194
+ let fx = 0, fy = 0, fz = 0;
3195
+ const p1 = cell[i];
3196
+ const neighbors = this._spatialPartition.getCellNeighbors(x, y, z);
3197
+ for (const neighborCell of neighbors) {
3198
+ for (let j = 0; j < neighborCell.length; j++) {
3199
+ if (cell === neighborCell && i === j) continue;
3200
+ const p2 = neighborCell[j];
3201
+ let dx = p2.x - p1.x;
3202
+ let dy = p2.y - p1.y;
3203
+ let dz = p2.z - p1.z;
3204
+ if (Math.abs(dx) > 0.5) dx = dx > 0 ? dx - 1 : dx + 1;
3205
+ if (Math.abs(dy) > 0.5) dy = dy > 0 ? dy - 1 : dy + 1;
3206
+ if (Math.abs(dz) > 0.5) dz = dz > 0 ? dz - 1 : dz + 1;
3207
+ const dist = Math.hypot(dx, dy, dz);
3208
+ if (dist > 0 && dist < this._range) {
3209
+ const f = this._calcForce(dist / this._range, this._attractionMatrix[p1.color][p2.color]);
3210
+ fx += dx / dist * f;
3211
+ fy += dy / dist * f;
3212
+ fz += dz / dist * f;
3213
+ }
3214
+ }
3215
+ }
3216
+ fx *= this._range * this._rangeFactor;
3217
+ fy *= this._range * this._rangeFactor;
3218
+ fz *= this._range * this._rangeFactor;
3219
+ p1.vx *= frictionFactor;
3220
+ p1.vy *= frictionFactor;
3221
+ p1.vz *= frictionFactor;
3222
+ p1.vx += fx;
3223
+ p1.vy += fy;
3224
+ p1.vz += fz;
3225
+ }
3226
+ }
3227
+ }
3228
+ }
3229
+ }
3230
+ _updatePositions(dt) {
3231
+ for (let i = 0; i < this._particles.length; i++) {
3232
+ const particle = this._particles[i];
3233
+ const oldCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
3234
+ particle.x += particle.vx * dt;
3235
+ particle.y += particle.vy * dt;
3236
+ particle.z += particle.vz * dt;
3237
+ if (particle.x < 0) particle.x = (particle.x + 1) % 1;
3238
+ if (particle.x > 1) particle.x = particle.x % 1;
3239
+ if (particle.y < 0) particle.y = (particle.y + 1) % 1;
3240
+ if (particle.y > 1) particle.y = particle.y % 1;
3241
+ if (particle.z < 0) particle.z = (particle.z + 1) % 1;
3242
+ if (particle.z > 1) particle.z = particle.z % 1;
3243
+ const newCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
3244
+ if (newCell !== oldCell) {
3245
+ const index = oldCell.indexOf(particle);
3246
+ if (index !== -1) {
3247
+ oldCell.splice(index, 1);
3248
+ }
3249
+ newCell.push(particle);
3250
+ }
3251
+ }
3252
+ }
3253
+ _sortParticles(camera) {
3254
+ this._particles.sort((a, b) => {
3255
+ const d1 = camera.position.distanceTo(new import_three7.Vector3(a.x, a.y, a.z));
3256
+ const d2 = camera.position.distanceTo(new import_three7.Vector3(b.x, b.y, b.z));
3257
+ return d1 > d2 ? -1 : d1 > d1 ? 1 : 0;
3258
+ });
3259
+ }
3260
+ _updateGeometry() {
3261
+ const positions = [];
3262
+ const colors2 = [];
3263
+ for (const particle of this._particles) {
3264
+ positions.push(
3265
+ particle.x,
3266
+ particle.y,
3267
+ particle.z
3268
+ );
3269
+ colors2.push(
3270
+ Colors2[particle.color][0],
3271
+ Colors2[particle.color][1],
3272
+ Colors2[particle.color][2],
3273
+ Colors2[particle.color][3]
3274
+ );
3275
+ }
3276
+ this._geometry.setAttribute("position", new import_three7.Float32BufferAttribute(positions, 3));
3277
+ this._geometry.setAttribute("color", new import_three7.Float32BufferAttribute(colors2, 4));
3278
+ this._geometry.attributes.position.needsUpdate = true;
3279
+ }
3280
+ update(camera, dt) {
3281
+ this._updateVelocities(dt);
3282
+ this._updatePositions(dt);
3283
+ this._sortParticles(camera);
3284
+ this._updateGeometry();
3285
+ }
3286
+ };
3287
+
3288
+ // src/three/asteroid-mesh.ts
3289
+ var import_three8 = require("three");
3290
+ var import_simplex_noise2 = require("simplex-noise");
3291
+ var AsteroidMesh = class extends import_three8.Mesh {
3292
+ constructor(options = {}) {
3293
+ const radius = options.radius ?? 1;
3294
+ const detail = options.detail ?? 1;
3295
+ const noiseScale = options.noiseScale ?? 1;
3296
+ const displacement = options.displacement ?? 0.1;
3297
+ const secondaryNoise = options.secondaryNoise ?? false;
3298
+ const color = options.color ?? 8947848;
3299
+ const geometry = new import_three8.IcosahedronGeometry(radius, detail);
3300
+ const material = new import_three8.MeshStandardMaterial({ color });
3301
+ super(geometry, material);
3302
+ const noise3d = (0, import_simplex_noise2.createNoise3D)(() => rng.nextf);
3303
+ const noise3d2 = secondaryNoise ? (0, import_simplex_noise2.createNoise3D)(() => rng.nextf) : null;
3304
+ const position = this.geometry.attributes.position;
3305
+ const vertices = position.array;
3306
+ for (let i = 0; i < vertices.length; i += 3) {
3307
+ const x = vertices[i];
3308
+ const y = vertices[i + 1];
3309
+ const z = vertices[i + 2];
3310
+ const n1 = noise3d(x * noiseScale, y * noiseScale, z * noiseScale);
3311
+ const n2 = secondaryNoise ? 0.5 * noise3d2(x * noiseScale * 2, y * noiseScale * 2, z * noiseScale * 2) : 0;
3312
+ const noiseValue = n1 + n2;
3313
+ const displacementValue = 1 + noiseValue * displacement;
3314
+ vertices[i] = x * displacementValue;
3315
+ vertices[i + 1] = y * displacementValue;
3316
+ vertices[i + 2] = z * displacementValue;
3317
+ }
3318
+ position.needsUpdate = true;
3319
+ this.geometry.computeVertexNormals();
3320
+ }
3321
+ };
3322
+
3323
+ // src/three/starfield.ts
3324
+ var import_three9 = require("three");
3325
+ function CreateStarfield(radius = 1e3, count = 5e3, color = 16777215) {
3326
+ const geometry = new import_three9.BufferGeometry();
3327
+ const positions = new Float32Array(count * 3);
3328
+ for (let i = 0; i < count; i++) {
3329
+ const theta = rng.nextf * Math.PI * 2;
3330
+ const phi = Math.acos(rng.nextf * 2 - 1);
3331
+ const x = radius * Math.sin(phi) * Math.cos(theta);
3332
+ const y = radius * Math.sin(phi) * Math.sin(theta);
3333
+ const z = radius * Math.cos(phi);
3334
+ positions.set([x, y, z], i * 3);
3335
+ }
3336
+ geometry.setAttribute("position", new import_three9.BufferAttribute(positions, 3));
3337
+ const material = new import_three9.PointsMaterial({
3338
+ color,
3339
+ size: 5,
3340
+ sizeAttenuation: true,
3341
+ transparent: true,
3342
+ opacity: 0.9
3343
+ });
3344
+ const stars = new import_three9.Points(geometry, material);
3345
+ stars.name = "Starfield";
3346
+ return stars;
3347
+ }
3348
+ function CreateSystemStar(position) {
3349
+ const star = new import_three9.Group();
3350
+ const starPos = position ?? new import_three9.Vector3();
3351
+ const starGeo = new import_three9.SphereGeometry(50, 32, 32);
3352
+ const starMat = new import_three9.MeshBasicMaterial({ color: 16768426 });
3353
+ const starMesh = new import_three9.Mesh(starGeo, starMat);
3354
+ starMesh.position.copy(starPos);
3355
+ star.add(starMesh);
3356
+ const starLight = new import_three9.PointLight(16777215, 10, 0, 0);
3357
+ starLight.position.copy(starPos);
3358
+ star.add(starLight);
3359
+ return star;
3360
+ }
3361
+
3362
+ // src/three/palette-controller.ts
3363
+ var import_three10 = require("three");
3364
+ async function CreatePaletteController(parentGui, colorPalette, onChange, folderName = "palette") {
3365
+ const { Controller } = await import("three/examples/jsm/libs/lil-gui.module.min.js");
3366
+ class PaletteControllerImpl extends Controller {
3367
+ $innerDiv;
3368
+ colorButtons = [];
3369
+ colorButtonSize = 20;
3370
+ selectedBorderStyle = "2px dashed black";
3371
+ currentColorIndex = 0;
3372
+ eyedropperButton;
3373
+ colorPalette;
3374
+ _onColorChange;
3375
+ constructor() {
3376
+ const parent = parentGui.addFolder(folderName);
3377
+ super(parent, {}, "", "function");
3378
+ this.colorPalette = colorPalette;
3379
+ this._onColorChange = onChange;
3380
+ this.$widget.style.setProperty("display", "flex");
3381
+ this.$widget.style.setProperty("justify-content", "center");
3382
+ this.$innerDiv = document.createElement("div");
3383
+ this.$innerDiv.style.setProperty("display", "flex");
3384
+ this.$innerDiv.style.setProperty("flex-wrap", "wrap");
3385
+ this.$innerDiv.style.setProperty("width", `${this.colorButtonSize * Math.floor(Math.sqrt(this.colorPalette.length)) + 2}px`);
3386
+ this.$innerDiv.appendChild(this.$name);
3387
+ this.$widget.appendChild(this.$innerDiv);
3388
+ this.colorPalette.forEach((color) => this._createColorButton(color));
3389
+ if (window.EyeDropper) {
3390
+ this.eyedropperButton = parent.add({
3391
+ eyedropper: () => {
3392
+ this.eyedropperButton?.disable(true);
3393
+ new window.EyeDropper().open().then(({ sRGBHex }) => {
3394
+ const i = this.findClosestColorMatchIndex(sRGBHex);
3395
+ this.setSelectedColor(i);
3396
+ this._onColorChange?.(i);
3397
+ }).finally(() => this.eyedropperButton?.disable(false)).catch(() => {
3398
+ });
3399
+ }
3400
+ }, "eyedropper").name("findClosestColor");
3401
+ }
3402
+ this.name("");
3403
+ this.updateDisplay();
3404
+ }
3405
+ _onColorButtonClicked(i, button) {
3406
+ if (button === 0) {
3407
+ this.setSelectedColor(i);
3408
+ this._onColorChange?.(i);
3409
+ this.colorButtons[i].blur();
3410
+ } else if (button === 2 && window.EyeDropper) {
3411
+ new window.EyeDropper().open().then(({ sRGBHex }) => {
3412
+ this.colorPalette[i] = sRGBHex;
3413
+ this.colorButtons[i].setAttribute("title", `${sRGBHex}`);
3414
+ this.colorButtons[i].style.setProperty("background", sRGBHex);
3415
+ this.setSelectedColor(i);
3416
+ this._onColorChange?.(i);
3417
+ this.colorButtons[i].blur();
3418
+ }).finally(() => this.eyedropperButton?.disable(false)).catch(() => {
3419
+ });
3420
+ }
3421
+ }
3422
+ _createColorButton(color) {
3423
+ const i = this.colorButtons.length;
3424
+ const colorButton = document.createElement("div");
3425
+ colorButton.setAttribute("id", `colorButton${i}`);
3426
+ colorButton.setAttribute("title", `${color}`);
3427
+ colorButton.style.setProperty("width", `${this.colorButtonSize}px`);
3428
+ colorButton.style.setProperty("height", `${this.colorButtonSize}px`);
3429
+ colorButton.style.setProperty("background", color);
3430
+ colorButton.addEventListener("pointerup", (ev) => this._onColorButtonClicked(i, ev.button));
3431
+ this.colorButtons.push(colorButton);
3432
+ this.$innerDiv.appendChild(colorButton);
3433
+ }
3434
+ updatePaletteColors() {
3435
+ this.colorPalette.forEach((color, i) => {
3436
+ if (i < this.colorButtons.length) {
3437
+ this.colorButtons[i].setAttribute("title", `${color}`);
3438
+ this.colorButtons[i].style.setProperty("background", color);
3439
+ } else {
3440
+ this._createColorButton(color);
3441
+ }
3442
+ });
3443
+ }
3444
+ setSelectedColor(colorIndex = 0) {
3445
+ this.colorButtons[this.currentColorIndex].style.removeProperty("border");
3446
+ this.currentColorIndex = clamp(colorIndex, 0, this.colorPalette.length);
3447
+ this.colorButtons[this.currentColorIndex].style.setProperty("border", this.selectedBorderStyle);
3448
+ }
3449
+ findClosestColorMatchIndex(color) {
3450
+ const pickedColor = new import_three10.Color(color);
3451
+ const pickedVector = new import_three10.Vector3().setFromColor(pickedColor);
3452
+ const list = [];
3453
+ this.colorPalette.forEach((paletteColorString, i) => {
3454
+ const paletteColor = new import_three10.Color(paletteColorString);
3455
+ const paletteVector = new import_three10.Vector3().setFromColor(paletteColor);
3456
+ const d = paletteVector.distanceTo(pickedVector);
3457
+ list.push({ i, d });
3458
+ });
3459
+ list.sort((a, b) => a.d - b.d);
3460
+ const closest = list.shift();
3461
+ return closest?.i ?? 0;
3462
+ }
3463
+ }
3464
+ return new PaletteControllerImpl();
3465
+ }
3466
+
3467
+ // src/three/ecs.ts
3468
+ var import_three11 = require("three");
3469
+ var entityCounter = 0;
3470
+ function GenerateEntityId() {
3471
+ return `entity_${entityCounter++}`;
3472
+ }
3473
+ function CreateThreeEntity(obj) {
3474
+ const entity = obj ?? new import_three11.Group();
3475
+ entity.userData.entityId = GenerateEntityId();
3476
+ entity.userData.components = {};
3477
+ return entity;
3478
+ }
3479
+ function AddThreeComponent(entity, name, component) {
3480
+ entity.userData.components[name] = component;
3481
+ }
3482
+ function GetThreeComponent(entity, name) {
3483
+ return entity.userData.components[name];
3484
+ }
3485
+ function RemoveThreeComponent(entity, name) {
3486
+ delete entity.userData.components[name];
3487
+ }
3488
+ function IsThreeEntity(obj) {
3489
+ return obj.userData.entityId !== void 0;
3490
+ }
3491
+
3492
+ // src/worker-interface.ts
3493
+ var WorkerInterface = class extends Emitter {
3494
+ _worker;
3495
+ constructor(url) {
3496
+ super();
3497
+ this._worker = new Worker(url, { type: "module" });
3498
+ this._worker.onerror = (error) => this.emit("error", error);
3499
+ this._worker.onmessage = (message) => this.emit("message", message);
3500
+ }
3501
+ postMessage(message, options) {
3502
+ this._worker.postMessage(message, options);
3503
+ }
3504
+ terminate() {
3505
+ this._worker.terminate();
3506
+ }
3507
+ };
1577
3508
  // Annotate the CommonJS export names for ESM import in node:
1578
3509
  0 && (module.exports = {
3510
+ AStar,
3511
+ AddThreeComponent,
3512
+ AsteroidMesh,
3513
+ AtlasTextureMaterial,
3514
+ BuildDefaultPalette,
1579
3515
  CanvasRenderer,
1580
3516
  Clock,
1581
3517
  ClockStats,
3518
+ Color,
3519
+ Colors,
1582
3520
  CompileShader,
3521
+ CreatePaletteController,
1583
3522
  CreateProgram,
1584
3523
  CreateProgramInfo,
3524
+ CreateStarfield,
3525
+ CreateSubTexture,
3526
+ CreateSystemStar,
3527
+ CreateThreeEntity,
1585
3528
  CreateWebGlContext,
1586
3529
  CubeSphereGeometry,
1587
3530
  ECS,
1588
3531
  Emitter,
3532
+ EventBus,
3533
+ GenerateDoors,
3534
+ GenerateEntityId,
3535
+ GenerateRooms,
3536
+ GenerateWalls,
1589
3537
  GetProgramLocations,
3538
+ GetThreeComponent,
1590
3539
  GlobalEmitter,
1591
3540
  Input,
3541
+ IsThreeEntity,
1592
3542
  LoadTexture,
3543
+ Map2D,
3544
+ Map3D,
1593
3545
  Noise,
3546
+ PI,
3547
+ ParticleSystem2d,
3548
+ ParticleSystem3d,
3549
+ PoissonDiskSampler,
3550
+ Rectangle,
3551
+ RemoveThreeComponent,
3552
+ Renderer,
1594
3553
  ResizeWebGlContext,
1595
3554
  Rng,
1596
3555
  ShaderType,
1597
3556
  SimplexNoise,
3557
+ SpatialPartition2d,
3558
+ SpatialPartition3d,
3559
+ TILE_EMPTY,
3560
+ TILE_FLOOR,
3561
+ TILE_PATH,
1598
3562
  TextureAtlas,
1599
3563
  ThreeJsBoilerPlate,
1600
3564
  ThreeJsCameraRig,
1601
3565
  ThreeJsPlayerController,
1602
- VoxelGeometry,
3566
+ Tilemap,
3567
+ Vector,
3568
+ VoxelFaces,
3569
+ VoxelMesh,
1603
3570
  WebGlRenderer,
3571
+ WorkerInterface,
3572
+ abs,
3573
+ ceil,
1604
3574
  clamp,
3575
+ cos,
1605
3576
  deg2rad,
3577
+ distance,
3578
+ eventBus,
3579
+ floor,
1606
3580
  getRedYellowGreenGradientHex,
3581
+ hypot2,
3582
+ hypot3,
3583
+ imul,
1607
3584
  isNullOrUndefined,
1608
- key2xyz,
1609
3585
  lerp,
1610
3586
  log,
1611
3587
  logdev,
1612
3588
  logerr,
1613
3589
  loginf,
1614
3590
  logwrn,
3591
+ manhattanDistance,
3592
+ max,
3593
+ min,
3594
+ pow,
1615
3595
  rng,
1616
- xyz2key
3596
+ round,
3597
+ roundTo,
3598
+ sin,
3599
+ sqrt,
3600
+ squaredDistance
1617
3601
  });