@threenative/core 0.3.12 → 0.3.15

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 (165) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1047 -44
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-2GPHICV6.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-GEMQJBY4.js} +1650 -383
  7. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  8. package/dist/{chunk-5O73CDMR.js → chunk-QAMSM3Z5.js} +415 -27
  9. package/dist/{chunk-2Z44XSI2.js → chunk-QAQHYOWY.js} +3 -7
  10. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  11. package/dist/{chunk-OKXUCASC.js → chunk-VBBYWGAT.js} +3 -4
  12. package/dist/chunk-VP43GIWW.js +18 -0
  13. package/dist/{chunk-N5LRP4BR.js → chunk-VQRPEOKY.js} +66 -3
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +871 -1018
  20. package/dist/index.js +4786 -1631
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BADStsTn.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +280 -16
  33. package/dist/world.js +1529 -642
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +135 -11
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/scripts/ensure-mcp.mjs +6 -1
  39. package/src/animation-batch.ts +193 -0
  40. package/src/animation-layers.ts +7 -3
  41. package/src/animation.ts +209 -29
  42. package/src/asset-cache.ts +3 -3
  43. package/src/asset-memo.ts +202 -0
  44. package/src/assets.ts +436 -131
  45. package/src/auto-batch.ts +190 -44
  46. package/src/clustered-batch.ts +146 -3
  47. package/src/clustered-mesh.ts +548 -20
  48. package/src/compute-driven.ts +1 -1
  49. package/src/config.ts +8 -0
  50. package/src/debug.ts +119 -22
  51. package/src/dev-global.ts +54 -0
  52. package/src/displaced-surface.ts +428 -0
  53. package/src/engine-hooks.ts +37 -0
  54. package/src/frame-budget.ts +35 -3
  55. package/src/game-boot-phase.ts +269 -0
  56. package/src/game-dev-tools.ts +7 -14
  57. package/src/game-frame-loop.ts +45 -82
  58. package/src/game-startup.ts +145 -70
  59. package/src/game-ui.ts +84 -0
  60. package/src/game.ts +168 -552
  61. package/src/gamepad-mappings.ts +269 -0
  62. package/src/generated/console-markers.ts +14 -0
  63. package/src/geometry-capture.ts +28 -4
  64. package/src/gpu-readings.ts +98 -0
  65. package/src/gpu-scene-bvh.ts +149 -36
  66. package/src/grass-field.ts +628 -0
  67. package/src/hot.ts +4 -7
  68. package/src/index.ts +227 -8
  69. package/src/input.ts +237 -25
  70. package/src/instanced-batch-lod.ts +3 -8
  71. package/src/interpolation.ts +171 -40
  72. package/src/look/ao-admission.ts +4 -3
  73. package/src/look/auto-exposure.ts +5 -16
  74. package/src/look/default-tone-mapping.ts +41 -5
  75. package/src/look/local-exposure.ts +2 -7
  76. package/src/look/quad-pass.ts +21 -0
  77. package/src/look/quality.ts +4 -0
  78. package/src/look/unreal-bloom.ts +4 -13
  79. package/src/look/world-environment.ts +58 -115
  80. package/src/merge-parts.ts +20 -24
  81. package/src/model-lod.ts +97 -14
  82. package/src/particle-significance.ts +12 -0
  83. package/src/particles.ts +19 -10
  84. package/src/platform.ts +23 -4
  85. package/src/profiling/FrameStages.ts +5 -6
  86. package/src/profiling/Spans.ts +3 -17
  87. package/src/profiling/debug-telemetry.ts +2 -6
  88. package/src/profiling/render-list-validate.ts +6 -15
  89. package/src/projection-marker.ts +2 -1
  90. package/src/quiet-markers.ts +3 -10
  91. package/src/render/cpu-bvh.ts +100 -0
  92. package/src/render/depth-pyramid.ts +6 -14
  93. package/src/render/environment/environmentContribution.ts +202 -0
  94. package/src/render/environment/environmentRadiance.ts +44 -0
  95. package/src/render/environment/environmentSampleCache.ts +56 -0
  96. package/src/render/environment/environmentSampling.ts +201 -0
  97. package/src/render/environment/environmentSnapshot.ts +71 -0
  98. package/src/render/environment/gate.ts +57 -0
  99. package/src/render/material-key.ts +21 -1
  100. package/src/render/mesh-pool.ts +3 -19
  101. package/src/render/probe-trace.ts +872 -0
  102. package/src/render/probe-volume.ts +780 -34
  103. package/src/render/radiance-cache.ts +17 -0
  104. package/src/render/screen-probe-gather.ts +303 -0
  105. package/src/render/short-range-ao.ts +274 -0
  106. package/src/render/virtual-shadow-partial.ts +13 -0
  107. package/src/render/virtual-shadow.ts +18 -16
  108. package/src/render/world-impostor-surface.ts +207 -9
  109. package/src/render/world-impostor.ts +5 -2
  110. package/src/render-camera-cull.ts +105 -4
  111. package/src/render-environment.ts +41 -0
  112. package/src/renderer-config.ts +36 -0
  113. package/src/renderer-facts.ts +37 -0
  114. package/src/renderer.ts +78 -32
  115. package/src/resolution-scaler.ts +3 -2
  116. package/src/scatter-field.ts +496 -0
  117. package/src/scene-entry-inspectors.ts +61 -0
  118. package/src/snow-field.ts +1 -0
  119. package/src/startup-offscreen-bytes.ts +84 -0
  120. package/src/state.ts +16 -3
  121. package/src/static-transform.ts +100 -25
  122. package/src/streamed-textures.ts +112 -0
  123. package/src/streaming.ts +68 -4
  124. package/src/texture-streaming.ts +331 -0
  125. package/src/tile-ring.ts +294 -0
  126. package/src/version.ts +1 -1
  127. package/src/warmup.ts +15 -2
  128. package/src/worker.ts +12 -2
  129. package/src/world-bundle-safety.ts +55 -10
  130. package/src/world-cell-batches.ts +166 -200
  131. package/src/world-cell-chunks.ts +3 -7
  132. package/src/world-cell-data.ts +7 -0
  133. package/src/world-cell-impostors.ts +20 -8
  134. package/src/world-cell-models.ts +36 -8
  135. package/src/world-cell-options.ts +2 -14
  136. package/src/world-cell-placements.ts +194 -90
  137. package/src/world-cell-prewarm.ts +39 -4
  138. package/src/world-cell-records.ts +401 -0
  139. package/src/world-cell-render-bundles.ts +2 -2
  140. package/src/world-cell-render-gpu-dress.ts +17 -19
  141. package/src/world-cell-render-main-cull.ts +73 -17
  142. package/src/world-cell-render-util.ts +18 -5
  143. package/src/world-cell-render.ts +13 -5
  144. package/src/world-cell-residency.ts +15 -6
  145. package/src/world-cell-stale.ts +238 -0
  146. package/src/world-cells.ts +23 -6
  147. package/src/world-gpu-flags.ts +18 -50
  148. package/src/world-gpu-reference.ts +22 -8
  149. package/src/world-gpu-scene.ts +44 -24
  150. package/src/world-gpu-shadow.ts +21 -8
  151. package/src/world-gpu-types.ts +41 -13
  152. package/src/world-load-limiter.ts +5 -0
  153. package/src/world-model-sections.ts +80 -0
  154. package/src/world-river-ribbon.ts +273 -0
  155. package/src/world-root-frame.ts +39 -0
  156. package/src/world-shore-field.ts +91 -0
  157. package/src/world-static-pose.ts +163 -0
  158. package/src/world-surface-sampler.ts +48 -0
  159. package/src/world-terrain-splat.ts +10 -18
  160. package/src/world-tile-budget.ts +4 -11
  161. package/src/world-tiles.ts +79 -12
  162. package/src/world-validate.ts +6 -14
  163. package/src/world-warm.ts +51 -0
  164. package/src/world-water-bodies.ts +113 -3
  165. package/src/world.ts +13 -0
@@ -2,6 +2,7 @@
2
2
  * TerrainTiles' constants, admission byte estimates and the input guards they share. Split out of
3
3
  `world-tiles.ts` verbatim (PRD-797), so the estimator can be read and tested without the class.
4
4
  */
5
+ import { readLaunchFlag } from "./debug.js";
5
6
 
6
7
  import { type SpanId, addSpan, spanNow, spanRecorder } from "./profiling/Spans.js";
7
8
  import type { IHeightfieldWorldPassOptions } from "./world-heightfield.js";
@@ -29,17 +30,9 @@ export const TERRAIN_TILE_MARKER_MS = 5_000;
29
30
  * switch — or one that still carries the `=1` that used to ask for the merge — stays on.
30
31
  */
31
32
  export function terrainMergeOptedOut(): boolean {
32
- const host = globalThis as { process?: { env?: Record<string, unknown> } } & Record<
33
- string,
34
- unknown
35
- >;
36
- const fromEnv = host.process?.env?.[TERRAIN_MERGE_FLAG];
37
- if (fromEnv === "0" || fromEnv === "false") return true;
38
- const query = globalThis.location?.search;
39
- if (typeof query === "string" && /[?&]tnTerrainMerge=(?:0|false)(?:&|$)/u.test(query))
40
- return true;
41
- return (
42
- host.__tnTerrainMerge === false || host.__tnTerrainMerge === 0 || host.__tnTerrainMerge === "0"
33
+ return readLaunchFlag(
34
+ { environment: TERRAIN_MERGE_FLAG, global: "__tnTerrainMerge", query: "tnTerrainMerge" },
35
+ "off",
43
36
  );
44
37
  }
45
38
 
@@ -31,8 +31,8 @@ import type { IComputeDriven } from "./compute-driven.js";
31
31
  import {
32
32
  type ILodView,
33
33
  type IModelLodPolicy,
34
- conservativeViewDepth,
35
34
  projectedLodError,
35
+ selectLodFor,
36
36
  selectLodLevel,
37
37
  worldSphere,
38
38
  } from "./model-lod.js";
@@ -212,6 +212,17 @@ export interface IWorldTilesOptions {
212
212
  readonly minX: number;
213
213
  readonly minZ: number;
214
214
  };
215
+ /**
216
+ * A region another surface already draws and collides, in tile-local metres: a tile wholly inside
217
+ * it is never meshed and gets no collider. A tile that only overlaps it is meshed whole; the game
218
+ * hides the overlap in its own surface.
219
+ */
220
+ readonly hole?: {
221
+ readonly maxX: number;
222
+ readonly maxZ: number;
223
+ readonly minX: number;
224
+ readonly minZ: number;
225
+ };
215
226
  /** How deep each edge skirt extends below its surface. Defaults to one tile width. */
216
227
  readonly skirtDepth?: number;
217
228
  /** Square tile neighborhood to consider around the followed point. Defaults to 1. */
@@ -332,6 +343,8 @@ export type NeighborPair = readonly [IResidentTile, IResidentTile];
332
343
  * @situation stream terrain without cracks
333
344
  * @situation keep generated terrain resident around a moving player
334
345
  * @situation put a generated terrain tile into a game-owned physics world
346
+ * @situation a hole or a flicker where streamed terrain tiles are still building (`settledHalf`)
347
+ * @situation split the ground between streamed tiles and a far mesh around the player (`settledHalf`)
335
348
  * @alias stream terrain across chunks
336
349
  * @constraint sampleHeight and surface are required game choices; no landform or surface preset is installed
337
350
  * @constraint residentTileBudget and residentByteBudget are hard caps; a tile that cannot fit throws
@@ -359,6 +372,7 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
359
372
  readonly #sampleHeight: IWorldTilesOptions["sampleHeight"];
360
373
  readonly #streamRadius: number;
361
374
  readonly #extent: IWorldTilesOptions["extent"];
375
+ readonly #hole: IWorldTilesOptions["hole"];
362
376
  /** Diagnostics outlive construction; their canonical field is never used by resident tiles. */
363
377
  #topology:
364
378
  | (Pick<Heightfield, "columns" | "depth" | "origin" | "rows" | "width"> & {
@@ -462,6 +476,7 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
462
476
  this.skirtDepth = positive(options.skirtDepth ?? this.tileSize, "skirtDepth");
463
477
  this.#streamRadius = integerAtLeast(options.streamRadius ?? 1, 0, "streamRadius");
464
478
  this.#extent = options.extent;
479
+ this.#hole = options.hole;
465
480
  this.#receiveShadow = options.receiveShadow === true;
466
481
  this.#colliderRadius = integerAtLeast(
467
482
  options.colliderRadius ?? this.#streamRadius,
@@ -724,6 +739,42 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
724
739
  return this.#resident.get(key);
725
740
  }
726
741
 
742
+ /**
743
+ * Half-width, in metres, of the largest square of tiles around `position`'s tile that is fully
744
+ * settled: each tile in it is resident, or is one the stream never draws (wholly inside `hole` or
745
+ * past `extent`). Zero while the tile under `position` is still building. A game that draws other
746
+ * ground where the tiles have not arrived (a collar, a far mesh) clips it to this square, so a tile
747
+ * still building shows that ground, never a hole.
748
+ *
749
+ * @situation a hole or a flicker where streamed terrain tiles are still building
750
+ * @situation split the ground between streamed tiles and a far mesh around the player
751
+ * @constraint reads residency only; call it after `follow` in the same frame
752
+ * @example split.half.value = tiles.settledHalf(player.position);
753
+ */
754
+ settledHalf(position: Pick<Vector3, "x" | "z">): number {
755
+ const centerX = Math.floor(
756
+ (finite(position.x, "settled x") + this.tileSize / 2) / this.tileSize,
757
+ );
758
+ const centerZ = Math.floor(
759
+ (finite(position.z, "settled z") + this.tileSize / 2) / this.tileSize,
760
+ );
761
+ const settled = (tileX: number, tileZ: number): boolean =>
762
+ this.#resident.has(keyFor(tileX, tileZ)) || !this.#touchesExtent(tileX, tileZ);
763
+ let ring = -1;
764
+ for (let k = 0; k <= this.#streamRadius; k += 1) {
765
+ for (let d = -k; d <= k; d += 1)
766
+ if (
767
+ !settled(centerX + d, centerZ - k) ||
768
+ !settled(centerX + d, centerZ + k) ||
769
+ !settled(centerX - k, centerZ + d) ||
770
+ !settled(centerX + k, centerZ + d)
771
+ )
772
+ return ring < 0 ? 0 : (ring + 0.5) * this.tileSize;
773
+ ring = k;
774
+ }
775
+ return (ring + 0.5) * this.tileSize;
776
+ }
777
+
727
778
  /**
728
779
  * Move residency to the followed point: admit, evict and re-level every tile.
729
780
  *
@@ -995,19 +1046,22 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
995
1046
  if (view !== undefined && next !== undefined && finest !== undefined && bounds != null) {
996
1047
  finest.mesh.updateWorldMatrix(true, false);
997
1048
  const sphere = worldSphere(bounds, finest.mesh);
998
- const depth = conservativeViewDepth(
1049
+ const { degenerate, depth } = selectLodFor(
999
1050
  view.camera,
1000
- sphere.center,
1001
- sphere.radius,
1051
+ sphere,
1002
1052
  (view.camera as Camera & { near?: number }).near ?? 0,
1003
1053
  );
1004
1054
  const errorPixels = projectedLodError(
1005
1055
  next.surfaceError * finest.mesh.matrixWorld.getMaxScaleOnAxis(),
1006
1056
  view.camera,
1007
1057
  view.viewportHeight,
1008
- depth.depth,
1058
+ depth,
1009
1059
  );
1010
- projection = { ...depth, ...(Number.isFinite(errorPixels) ? { errorPixels } : {}) };
1060
+ projection = {
1061
+ degenerate,
1062
+ depth,
1063
+ ...(Number.isFinite(errorPixels) ? { errorPixels } : {}),
1064
+ };
1011
1065
  }
1012
1066
  return {
1013
1067
  key: tile.key,
@@ -1379,11 +1433,23 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
1379
1433
  this.#setLodLevel(tile, this.#targetLod(tile, distance), countTransition);
1380
1434
  }
1381
1435
 
1382
- /** Whether the tile's square overlaps the ground at all; always true when no extent was given. */
1436
+ /**
1437
+ * Whether the tile's square overlaps the ground at all and is not wholly inside the hole; always
1438
+ * true when neither was given.
1439
+ */
1383
1440
  #touchesExtent(tileX: number, tileZ: number): boolean {
1441
+ const half = this.tileSize / 2;
1442
+ const hole = this.#hole;
1443
+ if (
1444
+ hole !== undefined &&
1445
+ tileX * this.tileSize - half >= hole.minX &&
1446
+ tileX * this.tileSize + half <= hole.maxX &&
1447
+ tileZ * this.tileSize - half >= hole.minZ &&
1448
+ tileZ * this.tileSize + half <= hole.maxZ
1449
+ )
1450
+ return false;
1384
1451
  const extent = this.#extent;
1385
1452
  if (extent === undefined) return true;
1386
- const half = this.tileSize / 2;
1387
1453
  return (
1388
1454
  tileX * this.tileSize + half > extent.minX &&
1389
1455
  tileX * this.tileSize - half < extent.maxX &&
@@ -1419,10 +1485,11 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
1419
1485
  if (finest === undefined || bounds == null) return 0;
1420
1486
  finest.mesh.updateWorldMatrix(true, false);
1421
1487
  const sphere = worldSphere(bounds, finest.mesh);
1422
- const depth = conservativeViewDepth(
1488
+ // The raw depth, deliberately: terrain selection never took the adaptive LOD bias, and passing
1489
+ // `biased` here moved a tile's level whenever `setLodBias` raised it.
1490
+ const { depth, degenerate } = selectLodFor(
1423
1491
  view.camera,
1424
- sphere.center,
1425
- sphere.radius,
1492
+ sphere,
1426
1493
  (view.camera as Camera & { near?: number }).near ?? 0,
1427
1494
  );
1428
1495
  const scale = finest.mesh.matrixWorld.getMaxScaleOnAxis();
@@ -1431,7 +1498,7 @@ export class TerrainTiles extends Object3D implements IComputeDriven {
1431
1498
  this.#lodErrors[index] = (tile.levels[index] as ILevelGeometry).surfaceError * scale;
1432
1499
  this.#lodErrors.length = floor + 1;
1433
1500
  return selectLodLevel(this.#lodErrors, tile.lodLevel, view.maxPixelError, view.hysteresis, [
1434
- { ...view, ...depth },
1501
+ { ...view, degenerate, depth },
1435
1502
  ]);
1436
1503
  }
1437
1504
 
@@ -12,6 +12,7 @@
12
12
  * loops back and every assertion with them. It is a validation mode, not a proof: it proves the
13
13
  * frames it ran on.
14
14
  */
15
+ import { readLaunchFlag } from "./debug.js";
15
16
 
16
17
  /** Marker printed when terrain validation is on, so a log says which mode produced it. */
17
18
  export const TERRAIN_VALIDATE_MARKER = "TN_TERRAIN_VALIDATE";
@@ -31,18 +32,9 @@ export const TERRAIN_VALIDATE_FLAG = "TN_TERRAIN_VALIDATE";
31
32
  * const tiles = new TerrainTiles({ ...options, validate: terrainValidationRequested() });
32
33
  */
33
34
  export function terrainValidationRequested(): boolean {
34
- const host = globalThis as {
35
- process?: { env?: Record<string, unknown> };
36
- __tnTerrainValidate?: unknown;
37
- };
38
- const fromEnv = host.process?.env?.[TERRAIN_VALIDATE_FLAG];
39
- if (typeof fromEnv === "string" && fromEnv !== "" && fromEnv !== "0" && fromEnv !== "false")
40
- return true;
41
- const query = globalThis.location?.search;
42
- if (
43
- typeof query === "string" &&
44
- /[?&]tnTerrainValidate=(?!0(?:&|$))(?!false(?:&|$))[^&]/u.test(query)
45
- )
46
- return true;
47
- return host.__tnTerrainValidate === true || host.__tnTerrainValidate === "1";
35
+ return readLaunchFlag({
36
+ environment: TERRAIN_VALIDATE_FLAG,
37
+ global: "__tnTerrainValidate",
38
+ query: "tnTerrainValidate",
39
+ });
48
40
  }
@@ -0,0 +1,51 @@
1
+ import type { Object3D } from "three";
2
+
3
+ /** How long `warmUnculled` keeps a subtree drawing whole. */
4
+ export interface IWarmUnculledOptions {
5
+ /** World draws to spend once `when` holds before the subtree is culled again. Default 2. */
6
+ readonly draws?: number;
7
+ /** Counts a draw only while this holds, such as "every tile around the spawn is resident". */
8
+ readonly when?: () => boolean;
9
+ }
10
+
11
+ /**
12
+ * Draw `root` with frustum culling off until it has drawn `draws` times, then cull it again and
13
+ * resolve. A pipeline is built by its first real draw (a startup warm-up compiles a different pass),
14
+ * so content the spawn view does not see — streamed tiles behind the player, a mirror that draws only
15
+ * when its water does — builds its pipelines after the reveal and hitches the first frames that see
16
+ * it. Join the promise to the loading curtain to build them behind it. Objects that join `root`
17
+ * while it warms draw unculled too.
18
+ *
19
+ * @situation the first frames after the loading curtain hitch on pipeline builds for content behind the camera
20
+ * @situation streamed terrain or a lake compiles its pipelines after the reveal
21
+ * @constraint `ctx.beforeRender` runs on every world draw, also behind the curtain; join the promise to the curtain's hold
22
+ * @example const warm = warmUnculled(ctx, lake.mesh); ctx.startup.hold("lake", () => warm);
23
+ */
24
+ export function warmUnculled(
25
+ ctx: { beforeRender(callback: () => void): void },
26
+ root: Object3D,
27
+ options: IWarmUnculledOptions = {},
28
+ ): Promise<void> {
29
+ const draws = options.draws ?? 2;
30
+ if (!Number.isInteger(draws) || draws < 1)
31
+ throw new Error(
32
+ `TN_WARM_UNCULLED_INVALID: draws must be a positive integer, received ${draws}.`,
33
+ );
34
+ const when = options.when ?? (() => true);
35
+ const cull = (culled: boolean): void =>
36
+ root.traverse((object) => {
37
+ object.frustumCulled = culled;
38
+ });
39
+ return new Promise((resolve) => {
40
+ let counted = 0; // -1 once warm
41
+ ctx.beforeRender(() => {
42
+ if (counted < 0) return;
43
+ cull(false);
44
+ if (when()) counted += 1;
45
+ if (counted <= draws) return;
46
+ counted = -1;
47
+ cull(true);
48
+ resolve();
49
+ });
50
+ });
51
+ }
@@ -83,6 +83,8 @@ interface IPool {
83
83
  readonly z: number;
84
84
  readonly radius2: number;
85
85
  readonly level: number;
86
+ readonly disc: ILakeDisc | undefined;
87
+ readonly field: Heightfield;
86
88
  }
87
89
 
88
90
  /** What stands at one (x, z): the water body covering it, its surface, and the river piece carrying it. */
@@ -155,6 +157,95 @@ export function waterlineRadius(
155
157
  return furthest;
156
158
  }
157
159
 
160
+ /**
161
+ * A lake's disc: `rings` rings of `spokes` vertices around its seed, out to `lakeReach`, packed towards
162
+ * the middle. Vertex 0 is the seed; ring `r` (1 to `rings - 1`) spoke `s` is `1 + (r - 1) * spokes + s`.
163
+ *
164
+ * `depths` is the water over the ground at each vertex, and it is zero where dry ground cuts the vertex
165
+ * off from the seed: a hollow beyond the basin's rim sits under the level too, but the lake does not
166
+ * reach it (a river valley past the dam would otherwise stand under a sheet of lake water that stops
167
+ * where the reach does, in a straight edge). Neighbours are the next spoke on a ring and the next ring
168
+ * on a spoke, so water crosses a ridge only where the ridge falls below the level.
169
+ */
170
+ export interface ILakeDisc {
171
+ readonly x: number;
172
+ readonly z: number;
173
+ readonly reach: number;
174
+ readonly rings: number;
175
+ readonly spokes: number;
176
+ readonly packing: number;
177
+ /** `[x, z]` per vertex, clamped to the field. */
178
+ readonly positions: Float32Array;
179
+ readonly depths: Float32Array;
180
+ }
181
+
182
+ export function lakeDisc(
183
+ field: Heightfield,
184
+ lake: IWaterLake,
185
+ rings = 44,
186
+ spokes = 88,
187
+ packing = 1.7,
188
+ ): ILakeDisc | undefined {
189
+ const reach = lakeReach(field, lake);
190
+ if (!(reach > 0)) return undefined;
191
+ const [cx = 0, cz = 0] = lake.at;
192
+ const minX = field.origin.x - field.width / 2;
193
+ const minZ = field.origin.z - field.depth / 2;
194
+ const count = (rings - 1) * spokes + 1;
195
+ const positions = new Float32Array(count * 2);
196
+ const raw = new Float32Array(count);
197
+ for (let index = 0; index < count; index += 1) {
198
+ const ring = index === 0 ? 0 : Math.floor((index - 1) / spokes) + 1;
199
+ const angle = (((index - 1) % spokes) / spokes) * Math.PI * 2;
200
+ const radius = index === 0 ? 0 : reach * (ring / (rings - 1)) ** packing;
201
+ const x = Math.max(minX, Math.min(minX + field.width, cx + Math.cos(angle) * radius));
202
+ const z = Math.max(minZ, Math.min(minZ + field.depth, cz + Math.sin(angle) * radius));
203
+ positions[index * 2] = x;
204
+ positions[index * 2 + 1] = z;
205
+ raw[index] = Math.max(0, lake.level - field.heightAt(x, z));
206
+ }
207
+ // Flood from the seed through wet vertices only.
208
+ const depths = new Float32Array(count);
209
+ const stack = [0];
210
+ depths[0] = raw[0] as number;
211
+ const visit = (index: number): void => {
212
+ if ((raw[index] as number) > 0 && depths[index] === 0) {
213
+ depths[index] = raw[index] as number;
214
+ stack.push(index);
215
+ }
216
+ };
217
+ while (stack.length > 0) {
218
+ const index = stack.pop() as number;
219
+ if (index === 0) {
220
+ for (let spoke = 0; spoke < spokes; spoke += 1) visit(1 + spoke);
221
+ continue;
222
+ }
223
+ const ring = Math.floor((index - 1) / spokes) + 1;
224
+ const spoke = (index - 1) % spokes;
225
+ const at = (r: number, s: number): number => (r === 0 ? 0 : 1 + (r - 1) * spokes + s);
226
+ visit(at(ring, (spoke + 1) % spokes));
227
+ visit(at(ring, (spoke + spokes - 1) % spokes));
228
+ visit(at(ring - 1, spoke));
229
+ if (ring + 1 < rings) visit(at(ring + 1, spoke));
230
+ }
231
+ return { x: cx, z: cz, reach, rings, spokes, packing, positions, depths };
232
+ }
233
+
234
+ /** Whether the disc cell holding (x, z) has a corner the seed's water reaches. */
235
+ function discReaches(disc: ILakeDisc, x: number, z: number): boolean {
236
+ const dx = x - disc.x;
237
+ const dz = z - disc.z;
238
+ const t = (Math.hypot(dx, dz) / disc.reach) ** (1 / disc.packing) * (disc.rings - 1);
239
+ const ring = Math.min(disc.rings - 2, Math.floor(t));
240
+ const turn = (Math.atan2(dz, dx) / (Math.PI * 2) + 1) % 1;
241
+ const spoke = Math.floor(turn * disc.spokes) % disc.spokes;
242
+ const at = (r: number, s: number): number => (r === 0 ? 0 : 1 + (r - 1) * disc.spokes + s);
243
+ const next = (spoke + 1) % disc.spokes;
244
+ return [at(ring, spoke), at(ring, next), at(ring + 1, spoke), at(ring + 1, next)].some(
245
+ (index) => (disc.depths[index] as number) > 0,
246
+ );
247
+ }
248
+
158
249
  /**
159
250
  * How far a lake's water reaches: the waterline its basin measures, `margin` times out, capped.
160
251
  *
@@ -272,7 +363,11 @@ export class WaterBodies {
272
363
  river === undefined ? Number.NEGATIVE_INFINITY : river.ha + (river.hb - river.ha) * along;
273
364
  let kind: WaterBodyKind | undefined = river === undefined ? undefined : "river";
274
365
  for (const pool of this.#pools)
275
- if ((x - pool.x) ** 2 + (z - pool.z) ** 2 <= pool.radius2 && pool.level > level) {
366
+ if (
367
+ (x - pool.x) ** 2 + (z - pool.z) ** 2 <= pool.radius2 &&
368
+ pool.level > level &&
369
+ !isolated(pool, x, z)
370
+ ) {
276
371
  level = pool.level;
277
372
  river = undefined;
278
373
  kind = "lake";
@@ -292,6 +387,20 @@ export class WaterBodies {
292
387
  }
293
388
  }
294
389
 
390
+ /** Ground under a lake's level that its water does not reach: a hollow past the basin's rim. */
391
+ function isolated(pool: IPool, x: number, z: number): boolean {
392
+ const disc = pool.disc;
393
+ if (disc === undefined || discReaches(disc, x, z)) return false;
394
+ const field = pool.field;
395
+ const minX = field.origin.x - field.width / 2;
396
+ const minZ = field.origin.z - field.depth / 2;
397
+ const ground = field.heightAt(
398
+ Math.max(minX, Math.min(minX + field.width, x)),
399
+ Math.max(minZ, Math.min(minZ + field.depth, z)),
400
+ );
401
+ return ground < pool.level;
402
+ }
403
+
295
404
  /** One row of river stations as straight pieces, each as wide as the channel stands over. */
296
405
  function buildReaches(ribbon: IWaterRibbon, into: IReach[]): void {
297
406
  const width = positive(ribbon.width, "ribbon width");
@@ -329,8 +438,9 @@ function poolOf(field: Heightfield | undefined, lake: IWaterLake): IPool {
329
438
  const [x = 0, z = 0] = lake.at;
330
439
  finite(x, "lake x");
331
440
  finite(z, "lake z");
332
- const radius = lakeReach(field, lake);
333
- return { level: lake.level, radius2: radius * radius, x, z };
441
+ const disc = lakeDisc(field, lake);
442
+ const radius = disc?.reach ?? 0;
443
+ return { level: lake.level, radius2: radius * radius, x, z, disc, field };
334
444
  }
335
445
 
336
446
  /**
package/src/world.ts CHANGED
@@ -23,6 +23,19 @@ export type {
23
23
  IWaterRibbon,
24
24
  WaterBodyKind,
25
25
  } from "./world-water-bodies.js";
26
+ export { lakeSurfaceGeometry, riverRibbonGeometry } from "./world-river-ribbon.js";
27
+ export type { ILakeSurfaceOptions, IRiverRibbonOptions } from "./world-river-ribbon.js";
28
+ export { AdmissionBudget } from "./world-load-limiter.js";
29
+ export { shoreField } from "./world-shore-field.js";
30
+ export { surfaceSampler } from "./world-surface-sampler.js";
31
+ export { baseRingGap, footprintGap, staticLowestY } from "./world-static-pose.js";
32
+ export { meshSections, repairZeroNormals, sectionGeometry } from "./world-model-sections.js";
33
+ export type { IMeshSection } from "./world-model-sections.js";
34
+ export type { IBaseRing, StaticGroundQuery } from "./world-static-pose.js";
35
+ export type { SurfaceSampler } from "./world-surface-sampler.js";
36
+ export { warmUnculled } from "./world-warm.js";
37
+ export type { IWarmUnculledOptions } from "./world-warm.js";
38
+ export type { IShoreField, IShoreFieldOptions } from "./world-shore-field.js";
26
39
 
27
40
  export { TerrainTiles } from "./world-tiles.js";
28
41
  export type {