@n3rdw1z4rd/core 0.18.5 → 0.19.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +72 -10
  2. package/dist/astar.d.ts +44 -0
  3. package/dist/astar.js +118 -0
  4. package/dist/canvas-renderer.d.ts +157 -0
  5. package/dist/canvas-renderer.js +207 -0
  6. package/dist/clock.d.ts +69 -0
  7. package/dist/clock.js +108 -0
  8. package/dist/color-palette.d.ts +25 -0
  9. package/dist/color-palette.js +112 -0
  10. package/dist/color.d.ts +90 -0
  11. package/dist/color.js +224 -0
  12. package/dist/css/main.css +1 -3
  13. package/dist/disposable.d.ts +27 -0
  14. package/dist/disposable.js +32 -0
  15. package/dist/dungeon-generator.d.ts +142 -0
  16. package/dist/dungeon-generator.js +288 -0
  17. package/dist/ecs.d.ts +87 -0
  18. package/dist/ecs.js +101 -0
  19. package/dist/emitter.d.ts +40 -0
  20. package/dist/emitter.js +54 -0
  21. package/dist/event-queue.d.ts +29 -0
  22. package/dist/event-queue.js +40 -0
  23. package/dist/index.cjs +3820 -0
  24. package/dist/index.d.cts +2657 -0
  25. package/dist/index.d.ts +35 -873
  26. package/dist/index.js +34 -3981
  27. package/dist/input/action-map.d.ts +79 -0
  28. package/dist/input/action-map.js +131 -0
  29. package/dist/input/bindings.d.ts +273 -0
  30. package/dist/input/bindings.js +250 -0
  31. package/dist/input/gestures.d.ts +108 -0
  32. package/dist/input/gestures.js +159 -0
  33. package/dist/input/index.d.ts +5 -0
  34. package/dist/input/index.js +5 -0
  35. package/dist/input/input.d.ts +297 -0
  36. package/dist/input/input.js +695 -0
  37. package/dist/log.d.ts +8 -0
  38. package/dist/log.js +9 -0
  39. package/dist/map2d.d.ts +83 -0
  40. package/dist/map2d.js +120 -0
  41. package/dist/map3d-CHDJiq5T.d.cts +236 -0
  42. package/dist/map3d.d.ts +94 -0
  43. package/dist/map3d.js +148 -0
  44. package/dist/math.d.ts +176 -0
  45. package/dist/math.js +206 -0
  46. package/dist/misc.d.ts +46 -0
  47. package/dist/misc.js +71 -0
  48. package/dist/observable.d.ts +43 -0
  49. package/dist/observable.js +53 -0
  50. package/dist/particle-renderer.d.ts +47 -0
  51. package/dist/particle-renderer.js +82 -0
  52. package/dist/particle-system-2d.d.ts +60 -0
  53. package/dist/particle-system-2d.js +147 -0
  54. package/dist/random.d.ts +46 -0
  55. package/dist/random.js +74 -0
  56. package/dist/rectangle.d.ts +44 -0
  57. package/dist/rectangle.js +69 -0
  58. package/dist/rng.d.ts +72 -0
  59. package/dist/rng.js +152 -0
  60. package/dist/signal.d.ts +34 -0
  61. package/dist/signal.js +41 -0
  62. package/dist/spatial-partition-2d.d.ts +42 -0
  63. package/dist/spatial-partition-2d.js +52 -0
  64. package/dist/spatial-partition-3d-Ba-VBveM.cjs +1324 -0
  65. package/dist/spatial-partition-3d.d.ts +44 -0
  66. package/dist/spatial-partition-3d.js +57 -0
  67. package/dist/three/asteroid-mesh.d.ts +41 -0
  68. package/dist/three/asteroid-mesh.js +44 -0
  69. package/dist/three/camera-rig.d.ts +140 -0
  70. package/dist/three/camera-rig.js +197 -0
  71. package/dist/three/cube-sphere-geometry.d.ts +55 -0
  72. package/dist/three/cube-sphere-geometry.js +239 -0
  73. package/dist/three/ecs.d.ts +75 -0
  74. package/dist/three/ecs.js +64 -0
  75. package/dist/three/index.d.ts +12 -0
  76. package/dist/three/index.js +12 -0
  77. package/dist/three/particle-system-3d.d.ts +53 -0
  78. package/dist/three/particle-system-3d.js +224 -0
  79. package/dist/three/renderer.d.ts +38 -0
  80. package/dist/three/renderer.js +57 -0
  81. package/dist/three/starfield.d.ts +23 -0
  82. package/dist/three/starfield.js +64 -0
  83. package/dist/three/texture-atlas.d.ts +76 -0
  84. package/dist/three/texture-atlas.js +84 -0
  85. package/dist/three/texture-utils.d.ts +31 -0
  86. package/dist/three/texture-utils.js +44 -0
  87. package/dist/three/voxel-geometry.d.ts +72 -0
  88. package/dist/three/voxel-geometry.js +231 -0
  89. package/dist/three/voxel-mesh.d.ts +67 -0
  90. package/dist/three/voxel-mesh.js +71 -0
  91. package/dist/three.cjs +1307 -0
  92. package/dist/three.d.cts +655 -0
  93. package/dist/tilemap.d.ts +17 -0
  94. package/dist/tilemap.js +26 -0
  95. package/dist/types.d.ts +34 -0
  96. package/dist/types.js +0 -0
  97. package/dist/vector.d.ts +78 -0
  98. package/dist/vector.js +169 -0
  99. package/dist/webgl-renderer.d.ts +89 -0
  100. package/dist/webgl-renderer.js +140 -0
  101. package/dist/webgl.d.ts +357 -0
  102. package/dist/webgl.js +628 -0
  103. package/dist/worker-interface.d.ts +30 -0
  104. package/dist/worker-interface.js +39 -0
  105. package/package.json +55 -13
  106. package/dist/css/index.ts +0 -1
  107. package/dist/index.css +0 -104
  108. package/dist/index.d.mts +0 -873
  109. package/dist/index.mjs +0 -3977
package/dist/three.cjs ADDED
@@ -0,0 +1,1307 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_spatial_partition_3d = require("./spatial-partition-3d-Ba-VBveM.cjs");
3
+ let three = require("three");
4
+ //#region src/three/asteroid-mesh.ts
5
+ /**
6
+ * Lumpy rock: an icosphere whose vertices are pushed in and out by 3D noise, with a
7
+ * `MeshStandardMaterial`. The geometry is non-indexed, so normals are per face (a faceted look).
8
+ * Deterministic for a deterministic noise function.
9
+ *
10
+ * ```ts
11
+ * import { createNoise3D } from 'simplex-noise';
12
+ *
13
+ * const rock = new AsteroidMesh({ noise3d: createNoise3D(() => rng.nextFloat()), radius: 2, detail: 3, displacement: 0.25 });
14
+ * ```
15
+ *
16
+ * @category Geometry & Meshes
17
+ */
18
+ var AsteroidMesh = class extends three.Mesh {
19
+ constructor(options) {
20
+ const radius = options.radius ?? 1;
21
+ const detail = options.detail ?? 1;
22
+ const noiseScale = options.noiseScale ?? 1;
23
+ const displacement = options.displacement ?? .1;
24
+ const noise3d = options.noise3d;
25
+ const noise3d2 = options.secondaryNoise;
26
+ const color = options.color ?? 8947848;
27
+ const geometry = new three.IcosahedronGeometry(radius, detail);
28
+ const material = new three.MeshStandardMaterial({ color });
29
+ super(geometry, material);
30
+ const position = this.geometry.attributes.position;
31
+ const vertices = position.array;
32
+ for (let i = 0; i < vertices.length; i += 3) {
33
+ const x = vertices[i];
34
+ const y = vertices[i + 1];
35
+ const z = vertices[i + 2];
36
+ const displacementValue = 1 + (noise3d(x * noiseScale, y * noiseScale, z * noiseScale) + (noise3d2 ? .5 * noise3d2(x * noiseScale * 2, y * noiseScale * 2, z * noiseScale * 2) : 0)) * displacement;
37
+ vertices[i] = x * displacementValue;
38
+ vertices[i + 1] = y * displacementValue;
39
+ vertices[i + 2] = z * displacementValue;
40
+ }
41
+ position.needsUpdate = true;
42
+ this.geometry.computeVertexNormals();
43
+ }
44
+ };
45
+ //#endregion
46
+ //#region src/three/camera-rig.ts
47
+ const DEFAULT_DISTANCE = 5;
48
+ const damp = (current, target, damping, deltaTime) => damping > 0 ? require_spatial_partition_3d.lerp(current, target, 1 - Math.exp(-damping * deltaTime)) : target;
49
+ /**
50
+ * Third-person camera that orbits a target and zooms seamlessly into first person.
51
+ *
52
+ * The orbit pivot sits at the target's eye height (`targetOffset`); the camera sits `distance`
53
+ * behind it. Zooming below `firstPersonThreshold` goes to distance 0, which puts the camera at the
54
+ * eyes: first person, with the same yaw and pitch.
55
+ *
56
+ * Add the rig to the scene (not to the target), feed it input with `orbit()` / `dolly()`, and call
57
+ * `update(deltaTime)` once per frame.
58
+ *
59
+ * ```ts
60
+ * const rig = new CameraRig({ target: player, distance: 6 });
61
+ * scene.add(rig);
62
+ *
63
+ * addEventListener('mousemove', (e) => rig.orbit(e.movementX, e.movementY));
64
+ * addEventListener('wheel', (e) => rig.dolly(e.deltaY));
65
+ *
66
+ * // each frame
67
+ * rig.update(deltaTime);
68
+ * renderer.render(scene, rig.camera);
69
+ * ```
70
+ *
71
+ * @category Camera
72
+ */
73
+ var CameraRig = class extends three.Group {
74
+ /** the camera to render with; a child of `gimbal` */
75
+ camera;
76
+ /** pitch */
77
+ gimbal = new three.Group();
78
+ /** followed by position, not parented */
79
+ target;
80
+ /** pivot (eye height) above the target's origin, world space */
81
+ targetOffset = new three.Vector3(0, 1.6, 0);
82
+ /** radians, around world up */
83
+ yaw = 0;
84
+ /** radians, negative looks down */
85
+ pitch = 0;
86
+ /** > 0 disables first person */
87
+ minDistance = 0;
88
+ /** furthest zoom distance */
89
+ maxDistance = 20;
90
+ /** zooming in below this goes all the way to first person */
91
+ firstPersonThreshold = .5;
92
+ /** pitch range in third person; default -80° to 30° */
93
+ pitchLimits = {
94
+ min: require_spatial_partition_3d.radians(-80),
95
+ max: require_spatial_partition_3d.radians(30)
96
+ };
97
+ /** pitch range in first person; the range blends between the two while zooming */
98
+ firstPersonPitchLimits = {
99
+ min: require_spatial_partition_3d.radians(-89),
100
+ max: require_spatial_partition_3d.radians(89)
101
+ };
102
+ /** sideways camera shift in third person (over-the-shoulder) */
103
+ shoulderOffset = 0;
104
+ /** the shift fades out as distance goes from this to 0 */
105
+ shoulderFadeDistance = 2;
106
+ /** set `target.visible = false` while in first person */
107
+ hideTargetInFirstPerson = true;
108
+ /** the camera pulls in rather than passing through these */
109
+ collisionObjects = [];
110
+ /** distance kept between the camera and a surface */
111
+ collisionPadding = .2;
112
+ /** radians per pixel */
113
+ orbitSensitivity = .005;
114
+ /** per wheel delta unit (multiplicative zoom) */
115
+ zoomSensitivity = .001;
116
+ /** higher = snappier; 0 = instant */
117
+ zoomDamping = 12;
118
+ /** 0 = locked to the target */
119
+ followDamping = 0;
120
+ /** called from `update()` when the camera switches between first and third person */
121
+ onModeChange;
122
+ _targetDistance;
123
+ _distance;
124
+ _cameraDistance;
125
+ _recovering = false;
126
+ _firstPerson = false;
127
+ _initialized = false;
128
+ _raycaster = new three.Raycaster();
129
+ _pivot = new three.Vector3();
130
+ _desired = new three.Vector3();
131
+ _direction = new three.Vector3();
132
+ /** Zoom distance the rig is easing towards; 0 = first person. */
133
+ get distance() {
134
+ return this._targetDistance;
135
+ }
136
+ /**
137
+ * Jumps to a zoom distance without easing, clamped to [`minDistance`, `maxDistance`]; below
138
+ * `firstPersonThreshold` becomes 0 (first person) unless `minDistance > 0`.
139
+ */
140
+ set distance(value) {
141
+ this._targetDistance = this._distance = this._cameraDistance = this._clampDistance(value);
142
+ }
143
+ /** Current distance of the camera from the pivot, after smoothing and collision. */
144
+ get cameraDistance() {
145
+ return this._cameraDistance;
146
+ }
147
+ /** whether the camera is currently closer than `firstPersonThreshold` (as of the last `update()`) */
148
+ get isFirstPerson() {
149
+ return this._firstPerson;
150
+ }
151
+ constructor(params = {}) {
152
+ super();
153
+ this.camera = params.camera ?? new three.PerspectiveCamera(params.fov ?? 70, params.aspect ?? 2, params.near ?? .1, params.far ?? 1e3);
154
+ this.add(this.gimbal);
155
+ this.gimbal.add(this.camera);
156
+ this.target = params.target;
157
+ const distance = this._clampDistance(params.distance ?? DEFAULT_DISTANCE);
158
+ this._targetDistance = this._distance = this._cameraDistance = distance;
159
+ }
160
+ /** Rotate from pointer movement in pixels (e.g. movementX / movementY). */
161
+ orbit(deltaX, deltaY) {
162
+ this.yaw -= deltaX * this.orbitSensitivity;
163
+ this.pitch -= deltaY * this.orbitSensitivity;
164
+ this._clampPitch();
165
+ }
166
+ /** Zoom from wheel movement (e.g. WheelEvent.deltaY); positive zooms out. */
167
+ dolly(delta) {
168
+ if (this._targetDistance === 0 && delta > 0) this._targetDistance = this.firstPersonThreshold;
169
+ else this._targetDistance *= Math.exp(delta * this.zoomSensitivity);
170
+ this._targetDistance = this._clampDistance(this._targetDistance);
171
+ }
172
+ /**
173
+ * Follows the target, eases zoom, applies yaw / pitch and collision, and positions the camera.
174
+ * Call once per frame.
175
+ *
176
+ * @param deltaTime seconds since the last update
177
+ */
178
+ update(deltaTime) {
179
+ if (this.target) {
180
+ this.target.getWorldPosition(this._pivot).add(this.targetOffset);
181
+ if (this.parent) this.parent.worldToLocal(this._pivot);
182
+ if (!this._initialized || this.followDamping <= 0) this.position.copy(this._pivot);
183
+ else {
184
+ const t = 1 - Math.exp(-this.followDamping * deltaTime);
185
+ this.position.lerp(this._pivot, t);
186
+ }
187
+ }
188
+ this._initialized = true;
189
+ this._targetDistance = this._clampDistance(this._targetDistance);
190
+ this._distance = damp(this._distance, this._targetDistance, this.zoomDamping, deltaTime);
191
+ if (Math.abs(this._distance - this._targetDistance) < 1e-4) this._distance = this._targetDistance;
192
+ this._clampPitch();
193
+ this.rotation.set(0, this.yaw, 0);
194
+ this.gimbal.rotation.set(this.pitch, 0, 0);
195
+ const shoulder = this.shoulderOffset * require_spatial_partition_3d.saturate(this._distance / this.shoulderFadeDistance);
196
+ this._cameraDistance = this._collide(shoulder, this._distance, deltaTime);
197
+ const scale = this._distance > 0 ? this._cameraDistance / this._distance : 0;
198
+ this.camera.position.set(shoulder * scale, 0, this._cameraDistance);
199
+ this._setFirstPerson(this._cameraDistance < this.firstPersonThreshold);
200
+ }
201
+ _collide(shoulder, distance, deltaTime) {
202
+ let allowed = distance;
203
+ if (this.collisionObjects.length > 0 && distance > 0) {
204
+ this.updateMatrixWorld(true);
205
+ const pivot = this.gimbal.getWorldPosition(this._pivot);
206
+ const desired = this.gimbal.localToWorld(this._desired.set(shoulder, 0, distance));
207
+ const length = this._direction.subVectors(desired, pivot).length();
208
+ this._raycaster.set(pivot, this._direction.normalize());
209
+ this._raycaster.far = length;
210
+ const hit = this._raycaster.intersectObjects(this.collisionObjects, true)[0];
211
+ if (hit) allowed = Math.max(0, (hit.distance - this.collisionPadding) / length * distance);
212
+ }
213
+ if (allowed < distance) {
214
+ this._recovering = true;
215
+ return allowed < this._cameraDistance ? allowed : damp(this._cameraDistance, allowed, this.zoomDamping, deltaTime);
216
+ }
217
+ if (this._recovering) {
218
+ const eased = damp(this._cameraDistance, distance, this.zoomDamping, deltaTime);
219
+ if (Math.abs(eased - distance) > .001) return eased;
220
+ this._recovering = false;
221
+ }
222
+ return distance;
223
+ }
224
+ _clampDistance(distance) {
225
+ distance = require_spatial_partition_3d.clamp(distance, this.minDistance, this.maxDistance);
226
+ return this.minDistance <= 0 && distance < this.firstPersonThreshold ? 0 : distance;
227
+ }
228
+ _clampPitch() {
229
+ const t = require_spatial_partition_3d.saturate(this._distance / Math.max(this.firstPersonThreshold, 1e-6));
230
+ this.pitch = require_spatial_partition_3d.clamp(this.pitch, require_spatial_partition_3d.lerp(this.firstPersonPitchLimits.min, this.pitchLimits.min, t), require_spatial_partition_3d.lerp(this.firstPersonPitchLimits.max, this.pitchLimits.max, t));
231
+ }
232
+ _setFirstPerson(firstPerson) {
233
+ if (firstPerson === this._firstPerson) return;
234
+ this._firstPerson = firstPerson;
235
+ if (this.hideTargetInFirstPerson && this.target) this.target.visible = !firstPerson;
236
+ this.onModeChange?.(firstPerson);
237
+ }
238
+ };
239
+ //#endregion
240
+ //#region src/three/cube-sphere-geometry.ts
241
+ const FACES = [
242
+ {
243
+ n: [
244
+ 1,
245
+ 0,
246
+ 0
247
+ ],
248
+ u: [
249
+ 0,
250
+ 0,
251
+ -1
252
+ ],
253
+ v: [
254
+ 0,
255
+ 1,
256
+ 0
257
+ ]
258
+ },
259
+ {
260
+ n: [
261
+ -1,
262
+ 0,
263
+ 0
264
+ ],
265
+ u: [
266
+ 0,
267
+ 0,
268
+ 1
269
+ ],
270
+ v: [
271
+ 0,
272
+ 1,
273
+ 0
274
+ ]
275
+ },
276
+ {
277
+ n: [
278
+ 0,
279
+ 1,
280
+ 0
281
+ ],
282
+ u: [
283
+ 1,
284
+ 0,
285
+ 0
286
+ ],
287
+ v: [
288
+ 0,
289
+ 0,
290
+ -1
291
+ ]
292
+ },
293
+ {
294
+ n: [
295
+ 0,
296
+ -1,
297
+ 0
298
+ ],
299
+ u: [
300
+ 1,
301
+ 0,
302
+ 0
303
+ ],
304
+ v: [
305
+ 0,
306
+ 0,
307
+ 1
308
+ ]
309
+ },
310
+ {
311
+ n: [
312
+ 0,
313
+ 0,
314
+ 1
315
+ ],
316
+ u: [
317
+ 1,
318
+ 0,
319
+ 0
320
+ ],
321
+ v: [
322
+ 0,
323
+ 1,
324
+ 0
325
+ ]
326
+ },
327
+ {
328
+ n: [
329
+ 0,
330
+ 0,
331
+ -1
332
+ ],
333
+ u: [
334
+ -1,
335
+ 0,
336
+ 0
337
+ ],
338
+ v: [
339
+ 0,
340
+ 1,
341
+ 0
342
+ ]
343
+ }
344
+ ];
345
+ /**
346
+ * A sphere built from a subdivided cube, for planets and other displaced spheres.
347
+ *
348
+ * Vertices on the cube's edges and corners are shared between faces, so there are no seams:
349
+ * displacement and computed normals are continuous across the whole surface. Points are
350
+ * mapped from cube to sphere with the "spherified cube" mapping, which spaces vertices far
351
+ * more evenly than normalizing (no bunching at the face corners).
352
+ *
353
+ * The geometry has positions, normals and an index; it has no UVs, since one set of UVs can't
354
+ * wrap a sphere without seams (use triplanar mapping or vertex colors for surfaces).
355
+ *
356
+ * ```ts
357
+ * const planet = new CubeSphereGeometry(10, 64) // radius 5
358
+ * .applyFractalBrownianMotion(noise3d, 5, 0.5, 0.3, 0.4); // up to ±0.4 height
359
+ * ```
360
+ *
361
+ * @category Geometry & Meshes
362
+ */
363
+ var CubeSphereGeometry = class CubeSphereGeometry extends three.BufferGeometry {
364
+ size;
365
+ segments;
366
+ type = "CubeSphereGeometry";
367
+ /** `size / 2`: the undisplaced radius */
368
+ radius;
369
+ _directions;
370
+ /**
371
+ * @param size diameter of the sphere
372
+ * @param segments subdivisions along each cube edge
373
+ */
374
+ constructor(size, segments) {
375
+ super();
376
+ this.size = size;
377
+ this.segments = segments;
378
+ segments = Math.max(1, Math.floor(segments));
379
+ this.segments = segments;
380
+ this.radius = size / 2;
381
+ const directions = [];
382
+ const indices = [];
383
+ const shared = /* @__PURE__ */ new Map();
384
+ for (const { n, u, v } of FACES) {
385
+ const faceIndices = [];
386
+ for (let j = 0; j <= segments; j++) for (let i = 0; i <= segments; i++) {
387
+ const s = 2 * i - segments;
388
+ const t = 2 * j - segments;
389
+ const X = n[0] * segments + u[0] * s + v[0] * t;
390
+ const Y = n[1] * segments + u[1] * s + v[1] * t;
391
+ const Z = n[2] * segments + u[2] * s + v[2] * t;
392
+ const key = `${X},${Y},${Z}`;
393
+ let index = shared.get(key);
394
+ if (index === void 0) {
395
+ index = directions.length / 3;
396
+ shared.set(key, index);
397
+ directions.push(...CubeSphereGeometry.spherify(X / segments, Y / segments, Z / segments));
398
+ }
399
+ faceIndices.push(index);
400
+ }
401
+ const row = segments + 1;
402
+ for (let j = 0; j < segments; j++) for (let i = 0; i < segments; i++) {
403
+ const a = faceIndices[j * row + i];
404
+ const b = faceIndices[j * row + i + 1];
405
+ const c = faceIndices[(j + 1) * row + i + 1];
406
+ const d = faceIndices[(j + 1) * row + i];
407
+ indices.push(a, b, c, a, c, d);
408
+ }
409
+ }
410
+ this._directions = new Float32Array(directions);
411
+ this.setIndex(indices);
412
+ this.setAttribute("position", new three.BufferAttribute(new Float32Array(directions.length), 3));
413
+ this.setAttribute("normal", new three.BufferAttribute(new Float32Array(directions.length), 3));
414
+ this.displace(() => 0);
415
+ this.attributes.normal.array.set(this._directions);
416
+ }
417
+ /**
418
+ * Sets each vertex to `radius + height(direction)` along its direction from the center,
419
+ * then recomputes normals and bounds. Always starts from the undisplaced sphere, so calling
420
+ * it again replaces the previous displacement rather than adding to it.
421
+ *
422
+ * @param height offset in world units for the unit direction (x, y, z)
423
+ */
424
+ displace(height) {
425
+ const positions = this.attributes.position.array;
426
+ const d = this._directions;
427
+ for (let i = 0; i < d.length; i += 3) {
428
+ const r = this.radius + height(d[i], d[i + 1], d[i + 2]);
429
+ positions[i] = d[i] * r;
430
+ positions[i + 1] = d[i + 1] * r;
431
+ positions[i + 2] = d[i + 2] * r;
432
+ }
433
+ this.attributes.position.needsUpdate = true;
434
+ this.computeVertexNormals();
435
+ this.computeBoundingSphere();
436
+ if (this.boundingBox) this.computeBoundingBox();
437
+ return this;
438
+ }
439
+ /**
440
+ * Displaces the surface with fractal Brownian motion. Noise is sampled at the undisplaced
441
+ * surface point times `scale`; the summed octaves are normalized to the noise's range and
442
+ * multiplied by `amplitude`.
443
+ */
444
+ applyFractalBrownianMotion(noise3d, octaves, persistence, scale, amplitude) {
445
+ const r = this.radius * scale;
446
+ return this.displace((x, y, z) => CubeSphereGeometry.fBm(noise3d, x * r, y * r, z * r, octaves, persistence) * amplitude);
447
+ }
448
+ static fBm(noise3d, x, y, z, octaves, persistence) {
449
+ let total = 0;
450
+ let frequency = 1;
451
+ let amplitude = 1;
452
+ let maxValue = 0;
453
+ for (let i = 0; i < octaves; i++) {
454
+ total += noise3d(x * frequency, y * frequency, z * frequency) * amplitude;
455
+ maxValue += amplitude;
456
+ amplitude *= persistence;
457
+ frequency *= 2;
458
+ }
459
+ return total / maxValue;
460
+ }
461
+ /**
462
+ * maps a point on the [-1, 1] cube onto the unit sphere with even spacing
463
+ * (https://mathproofs.blogspot.com/2005/07/mapping-cube-to-sphere.html)
464
+ */
465
+ static spherify(x, y, z) {
466
+ const x2 = x * x;
467
+ const y2 = y * y;
468
+ const z2 = z * z;
469
+ return [
470
+ x * Math.sqrt(1 - y2 / 2 - z2 / 2 + y2 * z2 / 3),
471
+ y * Math.sqrt(1 - z2 / 2 - x2 / 2 + z2 * x2 / 3),
472
+ z * Math.sqrt(1 - x2 / 2 - y2 / 2 + x2 * y2 / 3)
473
+ ];
474
+ }
475
+ };
476
+ //#endregion
477
+ //#region src/three/ecs.ts
478
+ let entityCounter = 0;
479
+ /**
480
+ * Returns a new id `"entity_<n>"` from a module-level counter (unique per page load, not random).
481
+ *
482
+ * @category ECS
483
+ */
484
+ function GenerateEntityId() {
485
+ return `entity_${entityCounter++}`;
486
+ }
487
+ /**
488
+ * Turns `obj` (default: a new `Group`) into an entity in place: gives it a new id and an empty
489
+ * component set, replacing any it had.
490
+ *
491
+ * ```ts
492
+ * const ship = CreateThreeEntity(shipMesh);
493
+ * AddThreeComponent(ship, 'velocity', { x: 0, y: 0, z: 1 });
494
+ * GetThreeComponent<{ x: number, y: number, z: number }>(ship, 'velocity')!.z; // 1
495
+ * ```
496
+ *
497
+ * @returns the same object, typed as a {@link ThreeEntity}
498
+ * @category ECS
499
+ */
500
+ function CreateThreeEntity(obj) {
501
+ const entity = obj ?? new three.Group();
502
+ entity.userData.entityId = GenerateEntityId();
503
+ entity.userData.components = {};
504
+ return entity;
505
+ }
506
+ /**
507
+ * Stores `component` on `entity` under `name`, replacing any component with that name.
508
+ *
509
+ * @category ECS
510
+ */
511
+ function AddThreeComponent(entity, name, component) {
512
+ entity.userData.components[name] = component;
513
+ }
514
+ /**
515
+ * The component named `name`, or `undefined` if the entity has none. `T` is not checked.
516
+ *
517
+ * @category ECS
518
+ */
519
+ function GetThreeComponent(entity, name) {
520
+ return entity.userData.components[name];
521
+ }
522
+ /**
523
+ * Removes the component named `name`, if any.
524
+ *
525
+ * @category ECS
526
+ */
527
+ function RemoveThreeComponent(entity, name) {
528
+ delete entity.userData.components[name];
529
+ }
530
+ /**
531
+ * Whether `obj` has been made an entity (has a `userData.entityId`).
532
+ *
533
+ * @category ECS
534
+ */
535
+ function IsThreeEntity(obj) {
536
+ return obj.userData.entityId !== void 0;
537
+ }
538
+ //#endregion
539
+ //#region src/three/particle-system-3d.ts
540
+ const vertexShader = `
541
+ uniform float pointSize;
542
+
543
+ varying vec4 vColor;
544
+
545
+ void main() {
546
+ vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
547
+
548
+ gl_Position = projectionMatrix * mvPosition;
549
+ gl_PointSize = pointSize;
550
+
551
+ vColor = color;
552
+ }`;
553
+ const fragmentShader = `
554
+ varying vec4 vColor;
555
+
556
+ void main() {
557
+ gl_FragColor = vColor;
558
+ }`;
559
+ const Colors = [
560
+ [
561
+ 1,
562
+ 0,
563
+ 0,
564
+ 1
565
+ ],
566
+ [
567
+ 0,
568
+ 1,
569
+ 0,
570
+ 1
571
+ ],
572
+ [
573
+ 0,
574
+ 0,
575
+ 1,
576
+ 1
577
+ ],
578
+ [
579
+ 1,
580
+ 1,
581
+ 0,
582
+ 1
583
+ ],
584
+ [
585
+ 1,
586
+ 0,
587
+ 1,
588
+ 1
589
+ ]
590
+ ];
591
+ /**
592
+ * "Particle life" simulation in 3D: 1000 colored points in five species that attract or repel each
593
+ * other according to a random species-by-species matrix, forming moving clusters. Particles live in
594
+ * a wrapping unit cube; the group is offset by -0.5 so the cube is centred on its origin (scale it
595
+ * to resize).
596
+ *
597
+ * Neighbours are found with a {@link SpatialPartition3d}. Points are drawn at a fixed 4 pixels and
598
+ * sorted back to front each update.
599
+ *
600
+ * ```ts
601
+ * const life = new ParticleSystem3d(42);
602
+ * life.scale.setScalar(10);
603
+ * scene.add(life);
604
+ *
605
+ * // each frame
606
+ * life.update(camera, deltaTime);
607
+ * ```
608
+ *
609
+ * @category Particles
610
+ */
611
+ var ParticleSystem3d = class extends three.Group {
612
+ /** number of particles; fixed */
613
+ particleCount = 1e3;
614
+ /** the seed the starting state came from */
615
+ seed;
616
+ /** seconds; larger `dt` values passed to `update()` are capped to this so a stall can't blow the simulation up */
617
+ maxDeltaTime = .1;
618
+ _geometry;
619
+ _particles = [];
620
+ _frictionHalfLife = .04;
621
+ _range = .2;
622
+ _forceFactor = 6;
623
+ _positions;
624
+ _colors;
625
+ _cameraLocal = new three.Vector3();
626
+ _attractionMatrix;
627
+ _spatialPartition;
628
+ /** the same seed always produces the same starting state (positions, colors, attraction matrix) */
629
+ constructor(seed = require_spatial_partition_3d.rng.nextUint()) {
630
+ super();
631
+ this.seed = seed;
632
+ const uniforms = { pointSize: { value: 4 } };
633
+ this.position.x = -.5;
634
+ this.position.y = -.5;
635
+ this.position.z = -.5;
636
+ this._positions = new Float32Array(this.particleCount * 3);
637
+ this._colors = new Float32Array(this.particleCount * 4);
638
+ this._geometry = new three.BufferGeometry();
639
+ this._geometry.setAttribute("position", new three.BufferAttribute(this._positions, 3).setUsage(three.DynamicDrawUsage));
640
+ this._geometry.setAttribute("color", new three.BufferAttribute(this._colors, 4).setUsage(three.DynamicDrawUsage));
641
+ this._geometry.boundingSphere = new three.Sphere(new three.Vector3(.5, .5, .5), Math.sqrt(3) / 2);
642
+ const material = new three.ShaderMaterial({
643
+ uniforms,
644
+ vertexShader,
645
+ fragmentShader,
646
+ depthTest: true,
647
+ depthWrite: false,
648
+ vertexColors: true
649
+ });
650
+ const pointsMesh = new three.Points(this._geometry, material);
651
+ this.add(pointsMesh);
652
+ for (let i = 0; i < this.particleCount; i++) this._particles.push({
653
+ x: require_spatial_partition_3d.Random.float(seed, i, 0),
654
+ y: require_spatial_partition_3d.Random.float(seed, i, 1),
655
+ z: require_spatial_partition_3d.Random.float(seed, i, 2),
656
+ vx: 0,
657
+ vy: 0,
658
+ vz: 0,
659
+ color: Math.floor(require_spatial_partition_3d.Random.float(seed, i, 3) * Colors.length)
660
+ });
661
+ this._attractionMatrix = require_spatial_partition_3d.randomMatrix(Colors.length, seed);
662
+ this._spatialPartition = new require_spatial_partition_3d.SpatialPartition3d(this._range, this._particles);
663
+ }
664
+ _calcForce(r, a, beta = .3) {
665
+ let f = 0;
666
+ if (r < beta) f = r / beta - 1;
667
+ else if (beta < r && r < 1) f = a * (1 - Math.abs(2 * r - 1 - beta) / (1 - beta));
668
+ return f;
669
+ }
670
+ _updateVelocities(dt) {
671
+ const frictionFactor = Math.pow(.5, dt / this._frictionHalfLife);
672
+ for (let z = 0; z < this._spatialPartition.cells.length; z++) for (let y = 0; y < this._spatialPartition.cells[z].length; y++) for (let x = 0; x < this._spatialPartition.cells[z][y].length; x++) {
673
+ const cell = this._spatialPartition.cells[z][y][x];
674
+ const neighbors = this._spatialPartition.getCellNeighbors(x, y, z);
675
+ for (let i = 0; i < cell.length; i++) {
676
+ let fx = 0, fy = 0, fz = 0;
677
+ const p1 = cell[i];
678
+ for (const neighborCell of neighbors) for (let j = 0; j < neighborCell.length; j++) {
679
+ if (cell === neighborCell && i === j) continue;
680
+ const p2 = neighborCell[j];
681
+ let dx = p2.x - p1.x;
682
+ let dy = p2.y - p1.y;
683
+ let dz = p2.z - p1.z;
684
+ if (Math.abs(dx) > .5) dx = dx > 0 ? dx - 1 : dx + 1;
685
+ if (Math.abs(dy) > .5) dy = dy > 0 ? dy - 1 : dy + 1;
686
+ if (Math.abs(dz) > .5) dz = dz > 0 ? dz - 1 : dz + 1;
687
+ const dist = Math.hypot(dx, dy, dz);
688
+ if (dist > 0 && dist < this._range) {
689
+ const f = this._calcForce(dist / this._range, this._attractionMatrix[p1.color][p2.color]);
690
+ fx += dx / dist * f;
691
+ fy += dy / dist * f;
692
+ fz += dz / dist * f;
693
+ }
694
+ }
695
+ const scale = this._range * this._forceFactor * dt;
696
+ fx *= scale;
697
+ fy *= scale;
698
+ fz *= scale;
699
+ p1.vx *= frictionFactor;
700
+ p1.vy *= frictionFactor;
701
+ p1.vz *= frictionFactor;
702
+ p1.vx += fx;
703
+ p1.vy += fy;
704
+ p1.vz += fz;
705
+ }
706
+ }
707
+ }
708
+ _updatePositions(dt) {
709
+ for (let i = 0; i < this._particles.length; i++) {
710
+ const particle = this._particles[i];
711
+ const oldCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
712
+ particle.x += particle.vx * dt;
713
+ particle.y += particle.vy * dt;
714
+ particle.z += particle.vz * dt;
715
+ particle.x = require_spatial_partition_3d.fract(particle.x);
716
+ particle.y = require_spatial_partition_3d.fract(particle.y);
717
+ particle.z = require_spatial_partition_3d.fract(particle.z);
718
+ const newCell = this._spatialPartition.getCell(particle.x, particle.y, particle.z);
719
+ if (newCell !== oldCell) {
720
+ const index = oldCell.indexOf(particle);
721
+ if (index !== -1) oldCell.splice(index, 1);
722
+ newCell.push(particle);
723
+ }
724
+ }
725
+ }
726
+ _sortParticles(camera) {
727
+ const c = this.worldToLocal(camera.getWorldPosition(this._cameraLocal));
728
+ const distanceSq = (p) => (p.x - c.x) ** 2 + (p.y - c.y) ** 2 + (p.z - c.z) ** 2;
729
+ this._particles.sort((a, b) => distanceSq(b) - distanceSq(a));
730
+ }
731
+ _updateGeometry() {
732
+ for (let i = 0; i < this._particles.length; i++) {
733
+ const particle = this._particles[i];
734
+ const color = Colors[particle.color];
735
+ this._positions[i * 3] = particle.x;
736
+ this._positions[i * 3 + 1] = particle.y;
737
+ this._positions[i * 3 + 2] = particle.z;
738
+ this._colors.set(color, i * 4);
739
+ }
740
+ this._geometry.attributes.position.needsUpdate = true;
741
+ this._geometry.attributes.color.needsUpdate = true;
742
+ }
743
+ /**
744
+ * Advances the simulation by `dt` seconds and refreshes the points, sorted back to front as
745
+ * seen from `camera`. `dt` is capped to {@link ParticleSystem3d.maxDeltaTime}.
746
+ */
747
+ update(camera, dt) {
748
+ dt = Math.min(dt, this.maxDeltaTime);
749
+ this._updateVelocities(dt);
750
+ this._updatePositions(dt);
751
+ this._sortParticles(camera);
752
+ this._updateGeometry();
753
+ }
754
+ };
755
+ //#endregion
756
+ //#region src/three/renderer.ts
757
+ /**
758
+ * `WebGLRenderer` that uses the device pixel ratio and can size itself to its parent element.
759
+ *
760
+ * ```ts
761
+ * const renderer = new Renderer({ antialias: true });
762
+ * container.appendChild(renderer.domElement);
763
+ *
764
+ * // each frame
765
+ * if (renderer.resize()) {
766
+ * camera.aspect = renderer.aspectRatio;
767
+ * camera.updateProjectionMatrix();
768
+ * }
769
+ * renderer.render(scene, camera);
770
+ * ```
771
+ *
772
+ * @category Rendering
773
+ */
774
+ var Renderer = class extends three.WebGLRenderer {
775
+ _size = new three.Vector2();
776
+ /** CSS pixels, same as setSize() and resize(); domElement.width/height are CSS pixels * pixel ratio */
777
+ get width() {
778
+ return this.getSize(this._size).width;
779
+ }
780
+ /** CSS pixels */
781
+ get height() {
782
+ return this.getSize(this._size).height;
783
+ }
784
+ /** width / height (1 while the height is 0) */
785
+ get aspectRatio() {
786
+ return this.height > 0 ? this.width / this.height : 1;
787
+ }
788
+ constructor(parameters) {
789
+ super(parameters);
790
+ this.setPixelRatio(window.devicePixelRatio);
791
+ }
792
+ /**
793
+ * Sets the size in CSS pixels, if it differs from the current one. A missing `width` / `height`
794
+ * defaults to the parent element's client size (or the current size when there is no parent, or
795
+ * the parent has no size yet, e.g. before layout or while hidden).
796
+ *
797
+ * @returns whether the size changed
798
+ */
799
+ resize(width, height) {
800
+ let resized = false;
801
+ width = width ?? (this.domElement.parentElement?.clientWidth || this.width);
802
+ height = height ?? (this.domElement.parentElement?.clientHeight || this.height);
803
+ if (this.width !== width || this.height !== height) {
804
+ this.setSize(width, height);
805
+ resized = true;
806
+ }
807
+ return resized;
808
+ }
809
+ };
810
+ //#endregion
811
+ //#region src/three/starfield.ts
812
+ /**
813
+ * Points spread uniformly over a sphere's surface, for a distant star backdrop (point size 5 with
814
+ * size attenuation, 0.9 opacity). The same `seed` always gives the same stars; without one,
815
+ * positions come from the shared {@link rng}.
816
+ *
817
+ * @param radius sphere radius in world units
818
+ * @param count number of stars
819
+ * @param color 0xRRGGBB
820
+ * @param seed seeds a private {@link Rng} for a reproducible starfield
821
+ * @category Geometry & Meshes
822
+ */
823
+ function CreateStarfield(radius = 1e3, count = 5e3, color = 16777215, seed) {
824
+ const random = seed === void 0 ? require_spatial_partition_3d.rng : new require_spatial_partition_3d.Rng(seed);
825
+ const geometry = new three.BufferGeometry();
826
+ const positions = new Float32Array(count * 3);
827
+ for (let i = 0; i < count; i++) {
828
+ const theta = random.nextFloat() * Math.PI * 2;
829
+ const phi = Math.acos(random.nextFloat() * 2 - 1);
830
+ const x = radius * Math.sin(phi) * Math.cos(theta);
831
+ const y = radius * Math.sin(phi) * Math.sin(theta);
832
+ const z = radius * Math.cos(phi);
833
+ positions.set([
834
+ x,
835
+ y,
836
+ z
837
+ ], i * 3);
838
+ }
839
+ geometry.setAttribute("position", new three.BufferAttribute(positions, 3));
840
+ const material = new three.PointsMaterial({
841
+ color,
842
+ size: 5,
843
+ sizeAttenuation: true,
844
+ transparent: true,
845
+ opacity: .9
846
+ });
847
+ const stars = new three.Points(geometry, material);
848
+ stars.name = "Starfield";
849
+ return stars;
850
+ }
851
+ /**
852
+ * A sun: a bright unlit sphere (radius 50, color 0xffddaa) plus a white `PointLight` (intensity
853
+ * 10, no distance falloff) at the same spot.
854
+ *
855
+ * @param position where to put both, in the group's space; default the origin
856
+ * @category Geometry & Meshes
857
+ */
858
+ function CreateSystemStar(position) {
859
+ const star = new three.Group();
860
+ const starPos = position ?? new three.Vector3();
861
+ const starGeo = new three.SphereGeometry(50, 32, 32);
862
+ const starMat = new three.MeshBasicMaterial({ color: 16768426 });
863
+ const starMesh = new three.Mesh(starGeo, starMat);
864
+ starMesh.position.copy(starPos);
865
+ star.add(starMesh);
866
+ const starLight = new three.PointLight(16777215, 10, 0, 0);
867
+ starLight.position.copy(starPos);
868
+ star.add(starLight);
869
+ return star;
870
+ }
871
+ //#endregion
872
+ //#region src/three/texture-utils.ts
873
+ /**
874
+ * Loads an image into a `Texture` with three's `TextureLoader`.
875
+ *
876
+ * @returns resolves once the image has loaded; rejects with the loader's error
877
+ * @category Textures
878
+ */
879
+ function LoadTexture(url) {
880
+ return new Promise((res, rej) => {
881
+ new three.TextureLoader().load(url, (texture) => {
882
+ const width = texture.source.data.width;
883
+ const height = texture.source.data.height;
884
+ res({
885
+ width,
886
+ height,
887
+ texture
888
+ });
889
+ }, (_ev) => {}, (err) => rej(err));
890
+ });
891
+ }
892
+ /**
893
+ * A clone of `texture` showing only the rectangle at (x, y) of size w x h, in pixels with y measured
894
+ * from the image's top, via `offset` / `repeat`. Sets `magFilter` to `NearestFilter` and `wrapS` / `wrapT`
895
+ * to `RepeatWrapping`. The clone shares the source image, so no pixels are copied.
896
+ *
897
+ * @category Textures
898
+ */
899
+ function CreateSubTexture(texture, x, y, w, h) {
900
+ const subTexture = texture.clone();
901
+ subTexture.magFilter = three.NearestFilter;
902
+ subTexture.wrapS = three.RepeatWrapping;
903
+ subTexture.wrapT = three.RepeatWrapping;
904
+ w /= subTexture.width;
905
+ h /= subTexture.height;
906
+ x /= subTexture.width;
907
+ y = 1 - h - y / subTexture.height;
908
+ subTexture.offset.set(x, y);
909
+ subTexture.repeat.set(w, h);
910
+ subTexture.needsUpdate = true;
911
+ return subTexture;
912
+ }
913
+ //#endregion
914
+ //#region src/three/texture-atlas.ts
915
+ /**
916
+ * Tile layout and UV lookup for a texture atlas (tile sheet). Tiles are numbered left to
917
+ * right, top to bottom, starting at 0.
918
+ *
919
+ * Not a material: use `atlas.texture` as the `map` of any material, or `createMaterial()`
920
+ * for the common Lambert setup. The texture's `magFilter` is set to `NearestFilter`.
921
+ *
922
+ * ```ts
923
+ * const atlas = await TextureAtlas.load('tiles.png', { tileWidth: 16 });
924
+ * const material = atlas.createMaterial();
925
+ * const [u, v] = atlas.getUV(5, 0, 0); // bottom-left of tile 5
926
+ * ```
927
+ *
928
+ * @category Textures
929
+ */
930
+ var TextureAtlas = class TextureAtlas {
931
+ /** the whole sheet */
932
+ texture;
933
+ /** texture size in pixels */
934
+ width;
935
+ /** texture size in pixels */
936
+ height;
937
+ /** pixels */
938
+ tileWidth;
939
+ /** pixels */
940
+ tileHeight;
941
+ /** pixels from the left edge before the first column */
942
+ offsetX;
943
+ /** pixels from the top edge before the first row */
944
+ offsetY;
945
+ /** pixels between neighbouring tiles */
946
+ spacing;
947
+ /** tiles per row */
948
+ columns;
949
+ /** tiles per column (only whole tiles count) */
950
+ rows;
951
+ /** `columns * rows` */
952
+ get tileCount() {
953
+ return this.columns * this.rows;
954
+ }
955
+ constructor(textureData, params = {}) {
956
+ this.texture = textureData.texture;
957
+ this.texture.magFilter = three.NearestFilter;
958
+ this.width = textureData.width;
959
+ this.height = textureData.height;
960
+ this.tileWidth = params.tileWidth ?? 16;
961
+ this.tileHeight = params.tileHeight ?? this.tileWidth;
962
+ this.offsetX = params.offsetX ?? 0;
963
+ this.offsetY = params.offsetY ?? 0;
964
+ this.spacing = params.spacing ?? 0;
965
+ this.columns = Math.floor((this.width - this.offsetX + this.spacing) / (this.tileWidth + this.spacing));
966
+ this.rows = Math.floor((this.height - this.offsetY + this.spacing) / (this.tileHeight + this.spacing));
967
+ }
968
+ /** Loads the image at `url` (see {@link LoadTexture}) and builds an atlas from it. */
969
+ static load(url, params) {
970
+ return LoadTexture(url).then((textureData) => new TextureAtlas(textureData, params));
971
+ }
972
+ /**
973
+ * UV of a point inside a tile. `u` and `v` are in [0, 1] across the tile, with (0, 0) at the
974
+ * tile's bottom-left and (1, 1) at its top-right, matching three.js (v = 1 is the image's top).
975
+ */
976
+ getUV(tile, u, v) {
977
+ const column = tile % this.columns;
978
+ const row = Math.floor(tile / this.columns);
979
+ const x = this.offsetX + column * (this.tileWidth + this.spacing) + u * this.tileWidth;
980
+ const y = this.offsetY + row * (this.tileHeight + this.spacing) + (1 - v) * this.tileHeight;
981
+ return [x / this.width, 1 - y / this.height];
982
+ }
983
+ /** a Lambert material using this atlas, set up for pixel-art tiles with transparency */
984
+ createMaterial(params = {}) {
985
+ return new three.MeshLambertMaterial({
986
+ map: this.texture,
987
+ alphaTest: .1,
988
+ transparent: true,
989
+ name: "TextureAtlas",
990
+ ...params
991
+ });
992
+ }
993
+ };
994
+ //#endregion
995
+ //#region src/three/voxel-geometry.ts
996
+ const cellKey = (u, v) => (u + 33554432) * 67108864 + (v + 33554432);
997
+ const planeKey = (d, side, slice) => (slice + 33554432) * 8 + d * 2 + (side > 0 ? 1 : 0);
998
+ /**
999
+ * Builds a mesh for the voxels in `voxels`: one quad per visible face, merged into larger quads
1000
+ * (`greedy`) and shaded with per-vertex ambient occlusion. A voxel's value is its palette index;
1001
+ * the map's default value means empty.
1002
+ *
1003
+ * Positions are in the map's own coordinates, so a chunk stored in chunk-local coordinates is
1004
+ * placed by positioning its mesh. Pass `neighbor` so faces against neighbouring chunks are culled
1005
+ * and their voxels count for ambient occlusion.
1006
+ *
1007
+ * The geometry has position, normal and color attributes and an index; use a material with
1008
+ * `vertexColors: true`. The output is deterministic: the same voxels and options always produce
1009
+ * the same buffers.
1010
+ *
1011
+ * ```ts
1012
+ * const voxels = new Map3D();
1013
+ * voxels.setArea(0, 0, 0, 7, 0, 7, 0); // 8x1x8 slab of palette index 0
1014
+ * voxels.set(3, 1, 3, 1);
1015
+ *
1016
+ * const geometry = buildVoxelGeometry(voxels, { palette: [0x55aa33, 0x8b5a2b] });
1017
+ * scene.add(new Mesh(geometry, new MeshLambertMaterial({ vertexColors: true })));
1018
+ * ```
1019
+ *
1020
+ * @returns `options.target` if given, otherwise a new geometry
1021
+ * @category Voxels
1022
+ */
1023
+ function buildVoxelGeometry(voxels, options = {}) {
1024
+ const palette = options.palette ?? [];
1025
+ const neighbor = options.neighbor;
1026
+ const includeHiddenFaces = options.includeHiddenFaces ?? false;
1027
+ const greedy = options.greedy ?? true;
1028
+ const ambientOcclusion = options.ambientOcclusion ?? true;
1029
+ const aoStrength = options.aoStrength ?? .5;
1030
+ const empty = voxels.defaultValue;
1031
+ const solid = (x, y, z) => {
1032
+ let value = voxels.get(x, y, z);
1033
+ if (value === empty && neighbor) value = neighbor(x, y, z);
1034
+ return value !== empty;
1035
+ };
1036
+ const colorOf = (value) => palette[value] ?? options.missingColor ?? require_spatial_partition_3d.Random.uint(value, 1) & 16777215;
1037
+ const planes = /* @__PURE__ */ new Map();
1038
+ const p = [
1039
+ 0,
1040
+ 0,
1041
+ 0
1042
+ ];
1043
+ voxels.forEach((x, y, z, value) => {
1044
+ const color = colorOf(value);
1045
+ for (let d = 0; d < 3; d++) {
1046
+ const ud = (d + 1) % 3;
1047
+ const vd = (d + 2) % 3;
1048
+ for (const side of [1, -1]) {
1049
+ p[0] = x;
1050
+ p[1] = y;
1051
+ p[2] = z;
1052
+ p[d] += side;
1053
+ if (!includeHiddenFaces && solid(p[0], p[1], p[2])) continue;
1054
+ const ao = ambientOcclusion ? cornerOcclusion(solid, p, ud, vd) : [
1055
+ 3,
1056
+ 3,
1057
+ 3,
1058
+ 3
1059
+ ];
1060
+ const slice = (d === 0 ? x : d === 1 ? y : z) + (side > 0 ? 1 : 0);
1061
+ const key = planeKey(d, side, slice);
1062
+ let plane = planes.get(key);
1063
+ if (!plane) {
1064
+ plane = /* @__PURE__ */ new Map();
1065
+ planes.set(key, plane);
1066
+ }
1067
+ const u = d === 0 ? y : d === 1 ? z : x;
1068
+ const v = d === 0 ? z : d === 1 ? x : y;
1069
+ const sig = color * 256 + ao[0] * 64 + ao[1] * 16 + ao[2] * 4 + ao[3];
1070
+ plane.set(cellKey(u, v), {
1071
+ u,
1072
+ v,
1073
+ color,
1074
+ ao,
1075
+ sig
1076
+ });
1077
+ }
1078
+ }
1079
+ });
1080
+ const positions = [];
1081
+ const normals = [];
1082
+ const colors = [];
1083
+ const indices = [];
1084
+ const linear = new three.Color();
1085
+ const corner = [
1086
+ 0,
1087
+ 0,
1088
+ 0
1089
+ ];
1090
+ const emitQuad = (d, side, slice, face, width, height) => {
1091
+ const ud = (d + 1) % 3;
1092
+ const vd = (d + 2) % 3;
1093
+ const base = positions.length / 3;
1094
+ linear.setHex(face.color);
1095
+ const cornerOffsets = [
1096
+ [0, 0],
1097
+ [width, 0],
1098
+ [width, height],
1099
+ [0, height]
1100
+ ];
1101
+ for (let c = 0; c < 4; c++) {
1102
+ corner[d] = slice;
1103
+ corner[ud] = face.u + cornerOffsets[c][0];
1104
+ corner[vd] = face.v + cornerOffsets[c][1];
1105
+ positions.push(corner[0], corner[1], corner[2]);
1106
+ normals.push(d === 0 ? side : 0, d === 1 ? side : 0, d === 2 ? side : 0);
1107
+ const shade = 1 - aoStrength * (3 - face.ao[c]) / 3;
1108
+ colors.push(linear.r * shade, linear.g * shade, linear.b * shade);
1109
+ }
1110
+ const ao = face.ao;
1111
+ const tris = ao[0] + ao[2] >= ao[1] + ao[3] ? [
1112
+ 0,
1113
+ 1,
1114
+ 2,
1115
+ 0,
1116
+ 2,
1117
+ 3
1118
+ ] : [
1119
+ 0,
1120
+ 1,
1121
+ 3,
1122
+ 1,
1123
+ 2,
1124
+ 3
1125
+ ];
1126
+ for (let t = 0; t < 6; t += 3) if (side > 0) indices.push(base + tris[t], base + tris[t + 1], base + tris[t + 2]);
1127
+ else indices.push(base + tris[t], base + tris[t + 2], base + tris[t + 1]);
1128
+ };
1129
+ const keys = [...planes.keys()].sort((a, b) => a - b);
1130
+ for (const key of keys) {
1131
+ const d = Math.floor(key / 2) % 4;
1132
+ const side = key % 2 ? 1 : -1;
1133
+ const slice = Math.floor(key / 8) - 33554432;
1134
+ const plane = planes.get(key);
1135
+ const faces = [...plane.values()].sort((a, b) => a.v - b.v || a.u - b.u);
1136
+ const used = /* @__PURE__ */ new Set();
1137
+ const free = (u, v, sig) => {
1138
+ const k = cellKey(u, v);
1139
+ return !used.has(k) && plane.get(k)?.sig === sig;
1140
+ };
1141
+ for (const face of faces) {
1142
+ if (used.has(cellKey(face.u, face.v))) continue;
1143
+ let width = 1;
1144
+ let height = 1;
1145
+ if (greedy) {
1146
+ while (free(face.u + width, face.v, face.sig)) width++;
1147
+ grow: while (true) {
1148
+ for (let du = 0; du < width; du++) if (!free(face.u + du, face.v + height, face.sig)) break grow;
1149
+ height++;
1150
+ }
1151
+ }
1152
+ for (let dv = 0; dv < height; dv++) for (let du = 0; du < width; du++) used.add(cellKey(face.u + du, face.v + dv));
1153
+ emitQuad(d, side, slice, face, width, height);
1154
+ }
1155
+ }
1156
+ const geometry = options.target ?? new three.BufferGeometry();
1157
+ geometry.setAttribute("position", new three.Float32BufferAttribute(positions, 3));
1158
+ geometry.setAttribute("normal", new three.Float32BufferAttribute(normals, 3));
1159
+ geometry.setAttribute("color", new three.Float32BufferAttribute(colors, 3));
1160
+ geometry.setIndex(indices);
1161
+ geometry.computeBoundingBox();
1162
+ geometry.computeBoundingSphere();
1163
+ return geometry;
1164
+ }
1165
+ function cornerOcclusion(solid, front, ud, vd) {
1166
+ const q = [
1167
+ 0,
1168
+ 0,
1169
+ 0
1170
+ ];
1171
+ const at = (du, dv) => {
1172
+ q[0] = front[0];
1173
+ q[1] = front[1];
1174
+ q[2] = front[2];
1175
+ q[ud] += du;
1176
+ q[vd] += dv;
1177
+ return solid(q[0], q[1], q[2]);
1178
+ };
1179
+ const occlusion = (su, sv) => {
1180
+ const side1 = at(su, 0);
1181
+ const side2 = at(0, sv);
1182
+ if (side1 && side2) return 0;
1183
+ return 3 - (+side1 + +side2 + +at(su, sv));
1184
+ };
1185
+ return [
1186
+ occlusion(-1, -1),
1187
+ occlusion(1, -1),
1188
+ occlusion(1, 1),
1189
+ occlusion(-1, 1)
1190
+ ];
1191
+ }
1192
+ /**
1193
+ * Geometry that owns its voxels; call `update()` after changing them. See
1194
+ * {@link buildVoxelGeometry} for how voxels are meshed, and {@link VoxelMesh} for an editable mesh
1195
+ * that tracks changes for you.
1196
+ *
1197
+ * @category Voxels
1198
+ */
1199
+ var VoxelGeometry = class extends three.BufferGeometry {
1200
+ type = "VoxelGeometry";
1201
+ /** voxel data (palette indices); the map's default value is empty */
1202
+ voxels;
1203
+ /** meshing options used by every `update()` */
1204
+ options;
1205
+ /** Builds the geometry right away. */
1206
+ constructor(voxels = new require_spatial_partition_3d.Map3D(), options = {}) {
1207
+ super();
1208
+ this.voxels = voxels;
1209
+ this.options = options;
1210
+ this.update();
1211
+ }
1212
+ /** Rebuilds the geometry from `voxels` and `options`. */
1213
+ update() {
1214
+ buildVoxelGeometry(this.voxels, {
1215
+ ...this.options,
1216
+ target: this
1217
+ });
1218
+ return this;
1219
+ }
1220
+ };
1221
+ //#endregion
1222
+ //#region src/three/voxel-mesh.ts
1223
+ /**
1224
+ * Editable voxel model: `set()` voxels, then `update()` rebuilds the geometry if anything changed.
1225
+ * Voxel values are palette indices; `Map3D`'s default value (-1) means empty.
1226
+ *
1227
+ * ```ts
1228
+ * const model = new VoxelMesh({ palette: [0xff0000, 0x00ff00], bounds: { width: 16, height: 16, depth: 16 } });
1229
+ * scene.add(model);
1230
+ *
1231
+ * model.set(0, 0, 0, 1);
1232
+ * model.update(); // rebuilds once, however many voxels changed
1233
+ * ```
1234
+ *
1235
+ * @category Voxels
1236
+ */
1237
+ var VoxelMesh = class extends three.Mesh {
1238
+ /** `set()` ignores voxels outside these; undefined = unbounded */
1239
+ bounds;
1240
+ _dirty = false;
1241
+ /** the geometry's voxel data; call `invalidate()` after changing it directly */
1242
+ get voxels() {
1243
+ return this.geometry.voxels;
1244
+ }
1245
+ /** geometry is out of date with the voxels */
1246
+ get needsUpdate() {
1247
+ return this._dirty;
1248
+ }
1249
+ constructor(options = {}) {
1250
+ const { material, bounds, voxels, ...buildOptions } = options;
1251
+ super(new VoxelGeometry(voxels ?? new require_spatial_partition_3d.Map3D(), buildOptions), material ?? new three.MeshLambertMaterial());
1252
+ for (const m of Array.isArray(this.material) ? this.material : [this.material]) m.vertexColors = true;
1253
+ this.bounds = bounds;
1254
+ }
1255
+ /** Whether (x, y, z) is inside `bounds` (always true without bounds). */
1256
+ inBounds(x, y, z) {
1257
+ if (!this.bounds) return true;
1258
+ return x >= 0 && y >= 0 && z >= 0 && x < this.bounds.width && y < this.bounds.height && z < this.bounds.depth;
1259
+ }
1260
+ /** Voxel value at (x, y, z); the map's default value (-1 unless you passed your own map) if empty. */
1261
+ get(x, y, z) {
1262
+ return this.voxels.get(x, y, z);
1263
+ }
1264
+ /** Sets a voxel; leave out `value` (or pass the default value) to remove it. Ignored outside the bounds. */
1265
+ set(x, y, z, value = this.voxels.defaultValue) {
1266
+ if (!this.inBounds(x, y, z) || this.voxels.get(x, y, z) === value) return;
1267
+ this.voxels.set(x, y, z, value);
1268
+ this._dirty = true;
1269
+ }
1270
+ /** (not `clear()`: that's Object3D's "remove all children") */
1271
+ clearVoxels() {
1272
+ if (this.voxels.size === 0) return;
1273
+ this.voxels.clear();
1274
+ this._dirty = true;
1275
+ }
1276
+ /** Call after changing `voxels` directly (or the geometry's options) to force a rebuild. */
1277
+ invalidate() {
1278
+ this._dirty = true;
1279
+ }
1280
+ /** Rebuilds the geometry if the voxels changed; returns whether it did. */
1281
+ update() {
1282
+ if (!this._dirty) return false;
1283
+ this.geometry.update();
1284
+ this._dirty = false;
1285
+ return true;
1286
+ }
1287
+ };
1288
+ //#endregion
1289
+ exports.AddThreeComponent = AddThreeComponent;
1290
+ exports.AsteroidMesh = AsteroidMesh;
1291
+ exports.CameraRig = CameraRig;
1292
+ exports.CreateStarfield = CreateStarfield;
1293
+ exports.CreateSubTexture = CreateSubTexture;
1294
+ exports.CreateSystemStar = CreateSystemStar;
1295
+ exports.CreateThreeEntity = CreateThreeEntity;
1296
+ exports.CubeSphereGeometry = CubeSphereGeometry;
1297
+ exports.GenerateEntityId = GenerateEntityId;
1298
+ exports.GetThreeComponent = GetThreeComponent;
1299
+ exports.IsThreeEntity = IsThreeEntity;
1300
+ exports.LoadTexture = LoadTexture;
1301
+ exports.ParticleSystem3d = ParticleSystem3d;
1302
+ exports.RemoveThreeComponent = RemoveThreeComponent;
1303
+ exports.Renderer = Renderer;
1304
+ exports.TextureAtlas = TextureAtlas;
1305
+ exports.VoxelGeometry = VoxelGeometry;
1306
+ exports.VoxelMesh = VoxelMesh;
1307
+ exports.buildVoxelGeometry = buildVoxelGeometry;