@threenative/core 0.3.11 → 0.3.13

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 (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
@@ -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
+ }
@@ -0,0 +1,359 @@
1
+ import type { Heightfield } from "./world-heightfield.js";
2
+
3
+ /**
4
+ * Metres a river's water reaches sideways per metre of its channel width.
5
+ *
6
+ * The water stands on its bed, not on the spline: the bake measures a channel's wet reach at 2.5
7
+ * widths either side of its centreline. The drawn ribbon and the query below read this one number,
8
+ * so a swimmer cannot leave the surface they see.
9
+ */
10
+ export const WATER_RIBBON_REACH = 2.5;
11
+
12
+ /** One river as the bake records it: stations along its centreline, its width and its flow. */
13
+ export interface IWaterRibbon {
14
+ /** Stations `[x, y, z]` in world metres; `y` is the surface height at the station. */
15
+ readonly points: readonly (readonly number[])[];
16
+ /** Metres of water across the channel. The surface reaches `2.5 * width` m either side. */
17
+ readonly width: number;
18
+ /** Downstream speed in m/s, the flow that carries a swimmer along the tangent. */
19
+ readonly flow: number;
20
+ }
21
+
22
+ /** One lake as the bake records it: where its flood fill was seeded, its level and its cap. */
23
+ export interface IWaterLake {
24
+ /** Where the flood fill was seeded, `[x, z]` in world metres. */
25
+ readonly at: readonly number[];
26
+ /** The surface's height, in metres. */
27
+ readonly level: number;
28
+ /** The furthest the game lets this water reach, in metres, whatever its basin measures. */
29
+ readonly radius: number;
30
+ /** How far past the measured waterline the water reaches, so the shore stands inside it. */
31
+ readonly margin: number;
32
+ }
33
+
34
+ /** A sea: one level and the square of ground it floods. */
35
+ export interface IWaterOcean {
36
+ /** The surface's height, in metres. */
37
+ readonly level: number;
38
+ /** Metres from the origin the surface covers, either side of it. */
39
+ readonly extent: number;
40
+ }
41
+
42
+ /** Which water stands at a point. */
43
+ export type WaterBodyKind = "river" | "lake" | "ocean";
44
+
45
+ /** The water standing at one (x, z): which body it is and how high its surface is. */
46
+ export interface IWaterFootprint {
47
+ readonly kind: WaterBodyKind;
48
+ /** Surface height there, in metres. */
49
+ readonly level: number;
50
+ }
51
+
52
+ /** A flow in m/s along x and z; the caller may pass one to reuse instead of allocating. */
53
+ export interface IWaterCurrent {
54
+ x: number;
55
+ z: number;
56
+ }
57
+
58
+ /** The baked water of one world: the arrays a game's biome file names, and the ground they flood. */
59
+ export interface IWaterBodiesOptions {
60
+ readonly ribbons?: readonly IWaterRibbon[];
61
+ readonly lakes?: readonly IWaterLake[];
62
+ readonly ocean?: IWaterOcean;
63
+ /** The canonical terrain. A lake's footprint is measured on it, so any lake needs it. */
64
+ readonly field?: Heightfield;
65
+ }
66
+
67
+ /** One straight piece of a river's centreline: its ends, surface heights, reach and flow. */
68
+ interface IReach {
69
+ readonly ax: number;
70
+ readonly az: number;
71
+ readonly dx: number;
72
+ readonly dz: number;
73
+ readonly length2: number;
74
+ readonly ha: number;
75
+ readonly hb: number;
76
+ readonly reach: number;
77
+ readonly flow: number;
78
+ }
79
+
80
+ /** One lake as the surface sees it: where it stands, how far it reaches and how high it is. */
81
+ interface IPool {
82
+ readonly x: number;
83
+ readonly z: number;
84
+ readonly radius2: number;
85
+ readonly level: number;
86
+ }
87
+
88
+ /** What stands at one (x, z): the water body covering it, its surface, and the river piece carrying it. */
89
+ interface ISample {
90
+ readonly kind: WaterBodyKind;
91
+ readonly level: number;
92
+ readonly river: IReach | undefined;
93
+ }
94
+
95
+ const NO_REACHES: readonly IReach[] = [];
96
+ const NO_LAKES: readonly IWaterLake[] = [];
97
+
98
+ function finite(value: unknown, name: string): number {
99
+ if (typeof value !== "number" || !Number.isFinite(value))
100
+ throw new Error(`TN_WATER_BODIES_INVALID: ${name} must be a finite number.`);
101
+ return value;
102
+ }
103
+
104
+ function positive(value: unknown, name: string): number {
105
+ const number = finite(value, name);
106
+ if (!(number > 0)) throw new Error(`TN_WATER_BODIES_INVALID: ${name} must be above zero.`);
107
+ return number;
108
+ }
109
+
110
+ /**
111
+ * The furthest a lake's basin reaches on a bearing: where the drawn ground crosses its level.
112
+ *
113
+ * Twenty-four bearings step outwards and stop at the first bank, because binary-searching the whole
114
+ * ray can jump a dry ridge into another pond. Eighteen halvings land inside two centimetres at this
115
+ * scale, well under the ground's own sample spacing.
116
+ *
117
+ * @situation measure where a lake's water meets the ground it floods
118
+ * @situation size a lake's drawn surface or the footprint a swimmer may enter
119
+ * @constraint returns metres on the furthest bearing; the caller applies its own cap
120
+ * @example const reach = waterlineRadius(field, lake.at, lake.level) * 1.12;
121
+ */
122
+ export function waterlineRadius(
123
+ field: Heightfield,
124
+ centre: readonly number[],
125
+ level: number,
126
+ ): number {
127
+ const [cx = 0, cz = 0] = centre;
128
+ if (field.heightAt(cx, cz) >= level) return 0;
129
+ const bearings = 24;
130
+ let furthest = 0;
131
+ for (let index = 0; index < bearings; index += 1) {
132
+ const angle = (index / bearings) * Math.PI * 2;
133
+ const dx = Math.cos(angle);
134
+ const dz = Math.sin(angle);
135
+ let wet = 0;
136
+ let dry = Math.min(
137
+ (field.width / 2 - Math.sign(dx) * (cx - field.origin.x)) / Math.max(Math.abs(dx), 1e-6),
138
+ (field.depth / 2 - Math.sign(dz) * (cz - field.origin.z)) / Math.max(Math.abs(dz), 1e-6),
139
+ );
140
+ const cell = Math.max(field.width / (field.columns - 1), field.depth / (field.rows - 1));
141
+ for (let distance = cell; distance < dry; distance += cell) {
142
+ if (field.heightAt(cx + dx * distance, cz + dz * distance) >= level) {
143
+ dry = distance;
144
+ break;
145
+ }
146
+ wet = distance;
147
+ }
148
+ for (let halving = 0; halving < 18; halving += 1) {
149
+ const mid = (wet + dry) / 2;
150
+ if (field.heightAt(cx + dx * mid, cz + dz * mid) < level) wet = mid;
151
+ else dry = mid;
152
+ }
153
+ furthest = Math.max(furthest, (wet + dry) / 2);
154
+ }
155
+ return furthest;
156
+ }
157
+
158
+ /**
159
+ * How far a lake's water reaches: the waterline its basin measures, `margin` times out, capped.
160
+ *
161
+ * The drawn surface and the swim footprint both size themselves here, so the shore a player sees is
162
+ * the shore they stop at.
163
+ *
164
+ * @situation size a lake's footprint from its basin and the cap its biome row names
165
+ * @constraint reads the heightfield at every bearing, once per lake, never per frame
166
+ * @example const reach = lakeReach(field, { ...lake, margin: 1.12 });
167
+ */
168
+ export function lakeReach(field: Heightfield, lake: IWaterLake): number {
169
+ return Math.min(waterlineRadius(field, lake.at, lake.level) * lake.margin, lake.radius);
170
+ }
171
+
172
+ /**
173
+ * One world's water, queried: surface height, current and footprint from the baked arrays.
174
+ *
175
+ * Rendering and physics read the same store, as they do for `Heightfield`, so the surface a player
176
+ * sees and the surface a swimmer rests on cannot disagree. Every station, level, extent and speed
177
+ * comes from the game, and the shading stays in the game's own `src/render/`.
178
+ *
179
+ * A river's segments sit in a uniform grid, so a query tests the few that can reach its cell
180
+ * instead of every station of every river.
181
+ *
182
+ * @situation ask how high the water is where a player swims
183
+ * @situation ask which way a current carries a body
184
+ * @situation ask which water body covers a point, and how high its surface is
185
+ * @situation share one water store between rendering and physics
186
+ * @constraint every station, level, extent and speed comes from the game's own bake; a lake is measured on the field passed in
187
+ * @example const water = new WaterBodies({ ribbons, lakes, field }); const height = water.surfaceAt(x, z);
188
+ */
189
+ export class WaterBodies {
190
+ readonly #cells: ReadonlyMap<string, readonly IReach[]>;
191
+ readonly #cellSize: number;
192
+ readonly #pools: readonly IPool[];
193
+ readonly #ocean: IWaterOcean | undefined;
194
+
195
+ constructor(options: IWaterBodiesOptions) {
196
+ const field = options.field;
197
+ const reaches: IReach[] = [];
198
+ for (const ribbon of options.ribbons ?? []) buildReaches(ribbon, reaches);
199
+ this.#cellSize = Math.max(1, ...reaches.map((piece) => piece.reach));
200
+ this.#cells = indexReaches(reaches, this.#cellSize);
201
+ this.#pools = (options.lakes ?? NO_LAKES).map((lake) => poolOf(field, lake));
202
+ const ocean = options.ocean;
203
+ this.#ocean =
204
+ ocean === undefined
205
+ ? undefined
206
+ : {
207
+ extent: positive(ocean.extent, "ocean extent"),
208
+ level: finite(ocean.level, "ocean level"),
209
+ };
210
+ }
211
+
212
+ /** The height of the water at (x, z), or `undefined` where none is drawn. */
213
+ surfaceAt(x: number, z: number): number | undefined {
214
+ return this.#sample(x, z)?.level;
215
+ }
216
+
217
+ /**
218
+ * The flow that carries a body at (x, z), in m/s, or `undefined` where there is no water.
219
+ *
220
+ * A river carries a swimmer along its tangent at the ribbon's flow; a lake and the sea stand still
221
+ * and report a zero vector. The result is written into `out` when one is passed, so a caller in a
222
+ * hot loop owns no allocation.
223
+ */
224
+ currentAt(x: number, z: number, out: IWaterCurrent = { x: 0, z: 0 }): IWaterCurrent | undefined {
225
+ const water = this.#sample(x, z);
226
+ if (water === undefined) return undefined;
227
+ const piece = water.river;
228
+ if (piece === undefined) {
229
+ out.x = 0;
230
+ out.z = 0;
231
+ return out;
232
+ }
233
+ const length = Math.sqrt(piece.length2);
234
+ out.x = (piece.dx / length) * piece.flow;
235
+ out.z = (piece.dz / length) * piece.flow;
236
+ return out;
237
+ }
238
+
239
+ /** Which water body covers (x, z) and how high its surface is, or `undefined` where none is. */
240
+ footprintAt(x: number, z: number): IWaterFootprint | undefined {
241
+ const water = this.#sample(x, z);
242
+ return water === undefined ? undefined : { kind: water.kind, level: water.level };
243
+ }
244
+
245
+ /**
246
+ * The water at (x, z): the nearest river segment within its reach, unless a lake's or the sea's
247
+ * higher level stands over it. Where two bodies overlap, the higher surface wins and the river
248
+ * stops carrying anything, so a mouth or a flooded station reads as standing water.
249
+ */
250
+ #sample(x: number, z: number): ISample | undefined {
251
+ finite(x, "query x");
252
+ finite(z, "query z");
253
+ let nearest = Number.POSITIVE_INFINITY;
254
+ let river: IReach | undefined;
255
+ let along = 0;
256
+ const candidates =
257
+ this.#cells.get(`${Math.floor(x / this.#cellSize)}:${Math.floor(z / this.#cellSize)}`) ??
258
+ NO_REACHES;
259
+ for (const piece of candidates) {
260
+ const t = Math.max(
261
+ 0,
262
+ Math.min(1, ((x - piece.ax) * piece.dx + (z - piece.az) * piece.dz) / piece.length2),
263
+ );
264
+ const distance = Math.hypot(x - piece.ax - piece.dx * t, z - piece.az - piece.dz * t);
265
+ if (distance <= piece.reach && distance < nearest) {
266
+ nearest = distance;
267
+ river = piece;
268
+ along = t;
269
+ }
270
+ }
271
+ let level =
272
+ river === undefined ? Number.NEGATIVE_INFINITY : river.ha + (river.hb - river.ha) * along;
273
+ let kind: WaterBodyKind | undefined = river === undefined ? undefined : "river";
274
+ for (const pool of this.#pools)
275
+ if ((x - pool.x) ** 2 + (z - pool.z) ** 2 <= pool.radius2 && pool.level > level) {
276
+ level = pool.level;
277
+ river = undefined;
278
+ kind = "lake";
279
+ }
280
+ const ocean = this.#ocean;
281
+ if (
282
+ ocean !== undefined &&
283
+ Math.abs(x) <= ocean.extent &&
284
+ Math.abs(z) <= ocean.extent &&
285
+ ocean.level > level
286
+ ) {
287
+ level = ocean.level;
288
+ river = undefined;
289
+ kind = "ocean";
290
+ }
291
+ return kind === undefined ? undefined : { kind, level, river };
292
+ }
293
+ }
294
+
295
+ /** One row of river stations as straight pieces, each as wide as the channel stands over. */
296
+ function buildReaches(ribbon: IWaterRibbon, into: IReach[]): void {
297
+ const width = positive(ribbon.width, "ribbon width");
298
+ const flow = finite(ribbon.flow, "ribbon flow");
299
+ const points = ribbon.points;
300
+ if (!Array.isArray(points) || points.length < 2)
301
+ throw new Error(
302
+ `TN_WATER_BODIES_INVALID: a ribbon needs at least two stations, received ${String(points?.length)}.`,
303
+ );
304
+ const reach = width * WATER_RIBBON_REACH;
305
+ for (let k = 1; k < points.length; k += 1) {
306
+ const before = points[k - 1] as readonly number[];
307
+ const after = points[k] as readonly number[];
308
+ const ax = finite(before[0], `ribbon station ${k - 1} x`);
309
+ const az = finite(before[2], `ribbon station ${k - 1} z`);
310
+ const bx = finite(after[0], `ribbon station ${k} x`);
311
+ const bz = finite(after[2], `ribbon station ${k} z`);
312
+ const ha = finite(before[1], `ribbon station ${k - 1} y`);
313
+ const hb = finite(after[1], `ribbon station ${k} y`);
314
+ const dx = bx - ax;
315
+ const dz = bz - az;
316
+ into.push({ ax, az, dx, dz, flow, ha, hb, length2: dx * dx + dz * dz || 1, reach });
317
+ }
318
+ }
319
+
320
+ /** One lake row as the query scans it: measured against the ground, capped at the row's radius. */
321
+ function poolOf(field: Heightfield | undefined, lake: IWaterLake): IPool {
322
+ if (field === undefined)
323
+ throw new Error(
324
+ "TN_WATER_BODIES_INVALID: a lake's footprint is measured on the ground; pass `field`.",
325
+ );
326
+ finite(lake.level, "lake level");
327
+ positive(lake.radius, "lake radius");
328
+ positive(lake.margin, "lake margin");
329
+ const [x = 0, z = 0] = lake.at;
330
+ finite(x, "lake x");
331
+ finite(z, "lake z");
332
+ const radius = lakeReach(field, lake);
333
+ return { level: lake.level, radius2: radius * radius, x, z };
334
+ }
335
+
336
+ /**
337
+ * Every reach registered in every cell its own reach can touch, so a query's cell holds a superset
338
+ * of the pieces that can answer it. Each cell's list keeps the row order, so the nearest piece of
339
+ * equal distance is the one the first row names.
340
+ */
341
+ function indexReaches(reaches: readonly IReach[], cellSize: number): ReadonlyMap<string, IReach[]> {
342
+ const cells = new Map<string, IReach[]>();
343
+ for (const piece of reaches) {
344
+ const bx = piece.ax + piece.dx;
345
+ const bz = piece.az + piece.dz;
346
+ const fromX = Math.floor((Math.min(piece.ax, bx) - piece.reach) / cellSize);
347
+ const toX = Math.floor((Math.max(piece.ax, bx) + piece.reach) / cellSize);
348
+ const fromZ = Math.floor((Math.min(piece.az, bz) - piece.reach) / cellSize);
349
+ const toZ = Math.floor((Math.max(piece.az, bz) + piece.reach) / cellSize);
350
+ for (let cx = fromX; cx <= toX; cx += 1)
351
+ for (let cz = fromZ; cz <= toZ; cz += 1) {
352
+ const key = `${cx}:${cz}`;
353
+ const list = cells.get(key);
354
+ if (list) list.push(piece);
355
+ else cells.set(key, [piece]);
356
+ }
357
+ }
358
+ return cells;
359
+ }