@threenative/core 0.3.4 → 0.3.5

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Bj8G1wmD.d.ts} +102 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12423 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +47 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2390 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +564 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +839 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,564 @@
1
+ import {
2
+ CompressedArrayTexture,
3
+ type CompressedTexture,
4
+ DataArrayTexture,
5
+ LinearFilter,
6
+ LinearMipmapLinearFilter,
7
+ type Material,
8
+ NoColorSpace,
9
+ RGBAFormat,
10
+ RepeatWrapping,
11
+ type Texture,
12
+ UnsignedByteType,
13
+ Vector3,
14
+ } from "three";
15
+ import {
16
+ cameraPosition,
17
+ cameraViewMatrix,
18
+ clamp,
19
+ dot,
20
+ float,
21
+ int,
22
+ mix,
23
+ mx_noise_float,
24
+ normalWorld,
25
+ positionWorld,
26
+ smoothstep,
27
+ texture,
28
+ vec2,
29
+ vec3,
30
+ vec4,
31
+ } from "three/tsl";
32
+ import type { Node } from "three/webgpu";
33
+ import { MeshStandardNodeMaterial } from "three/webgpu";
34
+ import type { IAssetLoader } from "./assets.js";
35
+ import type { IRendererLike } from "./renderer.js";
36
+ import type { IWorldExtent } from "./world-package.js";
37
+
38
+ type Channel = "r" | "g" | "b" | "a";
39
+
40
+ /** What a layer that states no surface response at all answers with: the matte dielectric surface
41
+ * this material carried before the table carried roughness and metalness. */
42
+ const DEFAULT_ROUGHNESS = 0.92;
43
+
44
+ /** One texture set: albedo (and optionally a normal and ORM map) tiled in metres, tinted in linear. */
45
+ export interface ITerrainSplatLayer {
46
+ readonly id: string;
47
+ readonly tile: number;
48
+ readonly tint: readonly [number, number, number];
49
+ readonly normal?: boolean;
50
+ /** `<id>_orm.jpg`: occlusion in r, roughness in g, metalness in b, read as linear data. */
51
+ readonly orm?: boolean;
52
+ /** Without an ORM map, how this layer answers light. Defaults to `DEFAULT_ROUGHNESS` and 0. */
53
+ readonly metalness?: number;
54
+ readonly roughness?: number;
55
+ readonly saturation?: number;
56
+ /** Box-projected, for cliffs a top-down projection smears. */
57
+ readonly triplanar?: boolean;
58
+ /**
59
+ * `<id>_h.jpg`: the layer's own height in r, read as linear data and handed to `layerWeight`.
60
+ * Read only on a masked layer; the base has no weight to bend.
61
+ */
62
+ readonly height?: boolean;
63
+ /**
64
+ * The same map again at a larger `tile`, mixed in by up to `amount` as camera distance goes from
65
+ * `from` to `to` metres, so a repeated pattern stops reading as a grid at grazing angles.
66
+ * Top-down layers only; every value is the game's.
67
+ */
68
+ readonly far?: {
69
+ readonly tile: number;
70
+ readonly from: number;
71
+ readonly to: number;
72
+ readonly amount: number;
73
+ };
74
+ }
75
+
76
+ /** A layer blended over what is below it by one mask channel, remapped from `lo..hi`. */
77
+ export interface ITerrainSplatMaskedLayer extends ITerrainSplatLayer {
78
+ readonly mask: string;
79
+ /** The component of a `rgb` mask; ignored by a single-component mask. */
80
+ readonly channel: "r" | "g" | "b";
81
+ readonly lo: number;
82
+ readonly hi: number;
83
+ }
84
+
85
+ /**
86
+ * The package's terrain table (`terrain.layers.table`). Written by the export recipe
87
+ * `export_terrain_layers.py` from the game's own table; every value is the game's.
88
+ */
89
+ export interface ITerrainSplatTable {
90
+ readonly base: ITerrainSplatLayer;
91
+ /** Noise (0..1 at `scale` per metre) that pushes every mask edge by +-`push`. */
92
+ readonly breakup: { readonly scale: number; readonly push: number };
93
+ /** Large-scale brightness variation against visible tiling, mapped to `min..max`. */
94
+ readonly macro: { readonly scale: number; readonly min: number; readonly max: number };
95
+ readonly layers: readonly ITerrainSplatMaskedLayer[];
96
+ /**
97
+ * `terrain.layers.splat`: `planes` RGBA8 planes of `size`², rows bottom-up, covering the
98
+ * package extent. `masks` names each mask's plane and component (`rgb` = pick by the layer's
99
+ * `channel`).
100
+ */
101
+ readonly splat: {
102
+ readonly size: number;
103
+ readonly planes: number;
104
+ readonly masks: Readonly<Record<string, readonly [number, Channel | "rgb"]>>;
105
+ };
106
+ /** Package-relative folder of `<id>_diff.jpg`, `<id>_nrm.jpg`, `<id>_orm.jpg` and `<id>_h.jpg`. */
107
+ readonly textures: string;
108
+ }
109
+
110
+ /** What `ILoadTerrainSplatOptions.layerWeight` is told about the layer whose weight it returns. */
111
+ export interface ITerrainSplatWeightContext {
112
+ readonly layer: ITerrainSplatMaskedLayer;
113
+ /** The layer's height sample, projected as its albedo is; `undefined` when it ships no `height`. */
114
+ readonly height: Node<"float"> | undefined;
115
+ /** The layer's index in `table.layers`. */
116
+ readonly index: number;
117
+ }
118
+
119
+ export interface ILoadTerrainSplatOptions {
120
+ readonly assets: IAssetLoader;
121
+ /**
122
+ * The live renderer. Uncompressed layers stack into one array texture per set through GPU copies,
123
+ * which need one; without it every layer keeps its own sampler and the marker says so.
124
+ */
125
+ readonly renderer?: IRendererLike;
126
+ /**
127
+ * Replaces each layer's blend weight, given the mask's own (remapped, 0..1) and the layer's
128
+ * height sample. The game owns the curve, for example a height blend; the package mixes colour,
129
+ * normal and ORM by whatever this returns. Absent, the mask weight is used unchanged.
130
+ */
131
+ readonly layerWeight?: (
132
+ weight: Node<"float">,
133
+ context: ITerrainSplatWeightContext,
134
+ ) => Node<"float">;
135
+ /** The world package's `world.json`, as `WorldCells.load` takes it. */
136
+ readonly url: string;
137
+ }
138
+
139
+ /**
140
+ * The two things this surface needs from world.json: its extent and its terrain layer paths.
141
+ * `WorldCells.load` validates the whole package; this only refuses a shape it cannot read.
142
+ */
143
+ function worldLayers(raw: unknown): {
144
+ extent: IWorldExtent;
145
+ layers: Readonly<Record<string, string>>;
146
+ } {
147
+ const record = raw as { extent?: Partial<IWorldExtent>; terrain?: { layers?: unknown } };
148
+ const extent = record.extent;
149
+ const numbers = [extent?.minX, extent?.minZ, extent?.sizeX, extent?.sizeZ];
150
+ if (
151
+ extent === undefined ||
152
+ !numbers.every((value) => typeof value === "number" && Number.isFinite(value))
153
+ )
154
+ throw new Error("loadTerrainSplat: world.json has no numeric extent.");
155
+ const layers = record.terrain?.layers;
156
+ const paths: Record<string, string> = {};
157
+ if (typeof layers === "object" && layers !== null)
158
+ for (const [name, value] of Object.entries(layers))
159
+ if (typeof value === "string") paths[name] = value;
160
+ return { extent: extent as IWorldExtent, layers: paths };
161
+ }
162
+
163
+ function packageDir(url: string): string {
164
+ const slash = url.lastIndexOf("/");
165
+ return slash === -1 ? "" : url.slice(0, slash + 1);
166
+ }
167
+
168
+ async function fetchResolved(assets: IAssetLoader, path: string): Promise<Response> {
169
+ for (const candidate of await assets.resolve(path)) {
170
+ const response = await fetch(candidate);
171
+ if (response.ok) return response;
172
+ }
173
+ throw new Error(`loadTerrainSplat: '${path}' is not served.`);
174
+ }
175
+
176
+ /** Every splat plane in one array texture: one sampler, whatever the plane count. */
177
+ function splatArray(bytes: Uint8Array, size: number, planes: number): Texture {
178
+ if (bytes.byteLength < planes * size * size * 4)
179
+ throw new Error(`loadTerrainSplat: splat data is shorter than plane ${String(planes - 1)}.`);
180
+ const map = new DataArrayTexture(bytes.subarray(0, planes * size * size * 4), size, size, planes);
181
+ map.format = RGBAFormat;
182
+ map.type = UnsignedByteType;
183
+ map.colorSpace = NoColorSpace;
184
+ map.magFilter = LinearFilter;
185
+ map.minFilter = LinearMipmapLinearFilter;
186
+ map.generateMipmaps = true;
187
+ map.needsUpdate = true;
188
+ return map;
189
+ }
190
+
191
+ /** The two texture-copy calls `stackUncompressed` needs, as the live renderer exposes them. */
192
+ interface IRawTextureCopier {
193
+ readonly copyTextureToTexture?: (
194
+ source: Texture,
195
+ destination: Texture,
196
+ sourceRegion?: unknown,
197
+ destinationPosition?: unknown,
198
+ ) => void;
199
+ readonly initTexture?: (texture: Texture) => void;
200
+ }
201
+
202
+ /** A loaded layer's texel size on the GPU, whatever its pixels are held in. */
203
+ function gpuSize(map: Texture): { readonly width: number; readonly height: number } | undefined {
204
+ const image = map.image as { width?: number; height?: number } | undefined;
205
+ const { width, height } = image ?? {};
206
+ return typeof width === "number" && typeof height === "number" && width > 0 && height > 0
207
+ ? { width, height }
208
+ : undefined;
209
+ }
210
+
211
+ /**
212
+ * Same-size uncompressed layers as one `DataArrayTexture`: one sampler, whatever the layer count.
213
+ * Every layer arrives as a GPU copy out of its own texture, so the pixels never come back to the
214
+ * CPU — and the array itself is created with no CPU data to upload, its layers written instead.
215
+ *
216
+ * `undefined` when they cannot stack (a size the others do not share) or when the host has no
217
+ * initialised renderer to copy with.
218
+ */
219
+ function stackUncompressed(
220
+ maps: readonly Texture[],
221
+ renderer: IRendererLike | undefined,
222
+ ): Texture | undefined {
223
+ const raw = renderer?.raw as IRawTextureCopier | undefined;
224
+ if (raw === undefined || raw.initTexture === undefined || raw.copyTextureToTexture === undefined)
225
+ return undefined;
226
+ const size = gpuSize(maps[0] as Texture);
227
+ if (size === undefined) return undefined;
228
+ const sameSize = maps.every((map) => {
229
+ const other = gpuSize(map);
230
+ return other !== undefined && other.width === size.width && other.height === size.height;
231
+ });
232
+ if (!sameSize) return undefined;
233
+
234
+ const first = maps[0] as Texture;
235
+ const array = new DataArrayTexture(
236
+ new Uint8Array(size.width * size.height * 4 * maps.length),
237
+ size.width,
238
+ size.height,
239
+ maps.length,
240
+ );
241
+ array.format = first.format;
242
+ array.type = first.type;
243
+ array.colorSpace = first.colorSpace;
244
+ array.minFilter = first.minFilter;
245
+ array.magFilter = first.magFilter;
246
+ array.wrapS = RepeatWrapping;
247
+ array.wrapT = RepeatWrapping;
248
+ array.anisotropy = 8;
249
+ array.flipY = false;
250
+ try {
251
+ // One creation of the GPU texture, with every mip level it will ever have, and nothing to
252
+ // upload: `dataReady` false is how three is told a texture's texels are already on the GPU.
253
+ array.needsUpdate = true;
254
+ array.source.dataReady = false;
255
+ raw.initTexture(array);
256
+ maps.forEach((map, layer) => {
257
+ raw.initTexture?.(map);
258
+ raw.copyTextureToTexture?.(map, array, null, new Vector3(0, 0, layer));
259
+ });
260
+ } catch (error) {
261
+ // An array nothing finished writing would draw whatever the copy left behind: fall back.
262
+ array.dispose();
263
+ console.warn(
264
+ `TN_TERRAIN_SPLAT: GPU stacking failed (${String(error)}); these layers bind their own samplers.`,
265
+ );
266
+ return undefined;
267
+ }
268
+ array.image.data = new Uint8Array(0);
269
+ for (const map of maps) map.dispose();
270
+ return array;
271
+ }
272
+
273
+ /**
274
+ * Same-format, same-size compressed layers as one `CompressedArrayTexture`, and same-size
275
+ * uncompressed ones as one `DataArrayTexture`, or `undefined` when they cannot stack (a mixed
276
+ * codec, a size the cap did not equalise, no renderer to copy uncompressed layers with).
277
+ *
278
+ * WebGPU guarantees 16 samplers a stage and three binds one per texture; a splat terrain's albedos
279
+ * and normals as separate textures plus an open-world shadow's maps passes 16 and the pipeline is
280
+ * invalid. Stacked, a surface costs one sampler per array however many layers it blends.
281
+ */
282
+ export function stackLayers(
283
+ maps: readonly Texture[],
284
+ renderer?: IRendererLike,
285
+ ): Texture | undefined {
286
+ const first = maps[0] as CompressedTexture | undefined;
287
+ if (first === undefined) return undefined;
288
+ if (first.isCompressedTexture !== true) return stackUncompressed(maps, renderer);
289
+ const width = (first.image as { width: number }).width;
290
+ const height = (first.image as { height: number }).height;
291
+ const stackable = maps.every((map) => {
292
+ const layer = map as CompressedTexture;
293
+ const image = layer.image as { width: number; height: number };
294
+ return (
295
+ layer.isCompressedTexture === true &&
296
+ layer.format === first.format &&
297
+ image.width === width &&
298
+ image.height === height &&
299
+ layer.mipmaps.length === first.mipmaps.length
300
+ );
301
+ });
302
+ if (!stackable) return undefined;
303
+ const mipmaps = first.mipmaps.map((mip, level) => {
304
+ const parts = maps.map((map) => {
305
+ const data = (map as CompressedTexture).mipmaps[level]?.data as ArrayBufferView;
306
+ return new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
307
+ });
308
+ const data = new Uint8Array(parts.reduce((total, part) => total + part.byteLength, 0));
309
+ let offset = 0;
310
+ for (const part of parts) {
311
+ data.set(part, offset);
312
+ offset += part.byteLength;
313
+ }
314
+ return { data, height: mip.height, width: mip.width };
315
+ });
316
+ const array = new CompressedArrayTexture(
317
+ mipmaps as never,
318
+ width,
319
+ height,
320
+ maps.length,
321
+ first.format,
322
+ first.type,
323
+ );
324
+ array.colorSpace = first.colorSpace;
325
+ array.minFilter = first.minFilter;
326
+ array.magFilter = first.magFilter;
327
+ array.wrapS = RepeatWrapping;
328
+ array.wrapT = RepeatWrapping;
329
+ array.anisotropy = 8;
330
+ array.needsUpdate = true;
331
+ for (const map of maps) map.dispose();
332
+ return array;
333
+ }
334
+
335
+ /**
336
+ * The splat terrain surface a world package describes, for `WorldCells.load({ surface })`.
337
+ *
338
+ * Layers blend over a base by mask channels read as linear data (the masks ship raw, beside the
339
+ * heightmap, so no cook moves a blend threshold), with noise-broken edges and macro brightness
340
+ * variation. Texture sets tile in world metres on the package's ground plane (x, -z: a Z-up
341
+ * authoring tool's x and y), cliffs can be triplanar, and the base plus any layer that asks carries
342
+ * a normal map. Each layer answers light from its own ORM map where the table ships one and from
343
+ * the table's own roughness and metalness where it does not; a layer that states neither is matte
344
+ * and dielectric, and named in a warning. Nothing here is a look choice:
345
+ * textures, tiles, tints, thresholds, surface response and noise scales all come from the package's
346
+ * table, which the game authors once and its DCC shares.
347
+ *
348
+ * @situation terrain textured by splat masks exported from Blender with the world package
349
+ * @situation the game's terrain should match the DCC's terrain material without a second copy
350
+ * @constraint the package's world.json must carry `terrain.layers.table` and `terrain.layers.splat`, written by `export_terrain_layers` in the `export_world.py` recipe
351
+ * @constraint WebGPU allows 16 sampled textures per stage: same-size layers stack into one array texture per set, and `TN_TERRAIN_SPLAT samplers=<n>` reports what is left
352
+ * @override every value comes from the package's table; the returned material is the game's to adjust
353
+ * @example
354
+ * const surface = await loadTerrainSplat({ assets: ctx.assets, renderer: ctx.renderer, url: "world/world.json" });
355
+ * const world = await WorldCells.load({ assets: ctx.assets, url: "world/world.json", surface, follow, ring: 2 });
356
+ */
357
+ export async function loadTerrainSplat(options: ILoadTerrainSplatOptions): Promise<Material> {
358
+ const { assets, url } = options;
359
+ const world = worldLayers(await (await fetchResolved(assets, url)).json());
360
+ const layerPaths = world.layers;
361
+ if (layerPaths.table === undefined || layerPaths.splat === undefined)
362
+ throw new Error(
363
+ "loadTerrainSplat: world.json has no terrain.layers.table/splat; export them with the export_world.py recipe.",
364
+ );
365
+ const dir = packageDir(url);
366
+ const table = (await (
367
+ await fetchResolved(assets, dir + layerPaths.table)
368
+ ).json()) as ITerrainSplatTable;
369
+ const bytes = new Uint8Array(
370
+ await (await fetchResolved(assets, dir + layerPaths.splat)).arrayBuffer(),
371
+ );
372
+
373
+ const { minX, minZ, sizeX, sizeZ } = world.extent;
374
+ // Rows are bottom-up in the authoring tool's ground plane, whose +y is three's -z.
375
+ const maskUv = vec2(
376
+ positionWorld.x.sub(minX).div(sizeX),
377
+ float(minZ + sizeZ)
378
+ .sub(positionWorld.z)
379
+ .div(sizeZ),
380
+ );
381
+ const splat = splatArray(bytes, table.splat.size, table.splat.planes);
382
+ const planes: Node<"vec4">[] = [];
383
+ for (let plane = 0; plane < table.splat.planes; plane += 1)
384
+ planes.push(texture(splat, maskUv).depth(int(plane)));
385
+
386
+ const all: ITerrainSplatLayer[] = [table.base, ...table.layers];
387
+ // A table exported before the orm column states no surface response at all, which is a package
388
+ // the recipe wrote, not a malformed one: it loads, matte and dielectric, with the gap named. A
389
+ // throw here fails the world's `load()` instead, and the game waits on its loading gate forever.
390
+ const unstated = all
391
+ .filter(
392
+ (layer) =>
393
+ layer.orm !== true &&
394
+ typeof layer.roughness !== "number" &&
395
+ typeof layer.metalness !== "number",
396
+ )
397
+ .map((layer) => layer.id);
398
+ if (unstated.length > 0)
399
+ console.warn(
400
+ `TN_TERRAIN_SPLAT: ${unstated.join(", ")} states no orm map and no roughness/metalness, so they answer light as roughness ${String(DEFAULT_ROUGHNESS)} and metalness 0; re-export the package to author them.`,
401
+ );
402
+
403
+ const load = async (
404
+ layer: ITerrainSplatLayer,
405
+ kind: "diff" | "nrm" | "orm" | "h",
406
+ ): Promise<Texture> => {
407
+ const map = await assets.texture(`${dir}${table.textures}/${layer.id}_${kind}.jpg`, {
408
+ data: kind !== "diff",
409
+ });
410
+ map.wrapS = RepeatWrapping;
411
+ map.wrapT = RepeatWrapping;
412
+ map.anisotropy = 8;
413
+ map.needsUpdate = true;
414
+ return map;
415
+ };
416
+ const withNormals = all.filter((layer) => layer.normal === true);
417
+ const withOrm = all.filter((layer) => layer.orm === true);
418
+ const diffuseMaps = await Promise.all(all.map((layer) => load(layer, "diff")));
419
+ const normalMaps = await Promise.all(withNormals.map((layer) => load(layer, "nrm")));
420
+ const ormMaps = await Promise.all(withOrm.map((layer) => load(layer, "orm")));
421
+ const withHeight = table.layers.filter((layer) => layer.height === true);
422
+ const heightMaps = await Promise.all(withHeight.map((layer) => load(layer, "h")));
423
+
424
+ // One sampler per set when the layers stack; separate textures (and a warning) when they do not.
425
+ let samplers = 1;
426
+ let stackedSets = 0;
427
+ const sampler = (
428
+ maps: readonly Texture[],
429
+ what: string,
430
+ ): ((layer: number, uv: Node<"vec2">) => Node<"vec3">) => {
431
+ const stacked = stackLayers(maps, options.renderer);
432
+ if (stacked !== undefined) {
433
+ samplers += 1;
434
+ stackedSets += 1;
435
+ return (layer, uv) => texture(stacked, uv).depth(int(layer)).rgb;
436
+ }
437
+ samplers += maps.length;
438
+ if (maps.length > 1)
439
+ console.warn(
440
+ `TN_TERRAIN_SPLAT: ${what} layers could not stack into one array (mixed format or size, or no renderer to copy them with); they bind ${String(maps.length)} samplers, and WebGPU guarantees 16 a stage.`,
441
+ );
442
+ return (layer, uv) => texture(maps[layer] as Texture, uv).rgb;
443
+ };
444
+ const diffuseAt = sampler(diffuseMaps, "albedo");
445
+ const normalAt = withNormals.length === 0 ? undefined : sampler(normalMaps, "normal");
446
+ const ormAt = withOrm.length === 0 ? undefined : sampler(ormMaps, "ORM");
447
+ const heightAt = withHeight.length === 0 ? undefined : sampler(heightMaps, "height");
448
+
449
+ const ground = vec2(positionWorld.x, positionWorld.z.negate());
450
+ const maskOf = (layer: ITerrainSplatMaskedLayer): Node<"float"> => {
451
+ const where = table.splat.masks[layer.mask];
452
+ if (where === undefined) throw new Error(`loadTerrainSplat: unknown mask '${layer.mask}'.`);
453
+ const source = planes[where[0]];
454
+ if (source === undefined)
455
+ throw new Error(`loadTerrainSplat: mask '${layer.mask}' names a missing plane.`);
456
+ return source[where[1] === "rgb" ? layer.channel : where[1]];
457
+ };
458
+ const breakup = mx_noise_float(vec3(ground.mul(table.breakup.scale), 0))
459
+ .mul(0.5)
460
+ .add(0.5);
461
+ const push = breakup.mul(2 * table.breakup.push).sub(table.breakup.push);
462
+
463
+ // Box projection for cliffs: three axis-aligned samples blended by the surface normal.
464
+ const triplanar = (at: (uv: Node<"vec2">) => Node<"vec3">, tile: number): Node<"vec3"> => {
465
+ const weights = normalWorld.abs();
466
+ const w = weights.div(weights.x.add(weights.y).add(weights.z));
467
+ const p = positionWorld.div(tile);
468
+ return at(p.zy).mul(w.x).add(at(p.xz).mul(w.y)).add(at(p.xy).mul(w.z));
469
+ };
470
+
471
+ const albedo = (layer: ITerrainSplatLayer, index: number): Node<"vec3"> => {
472
+ let sample: Node<"vec3"> =
473
+ layer.triplanar === true
474
+ ? triplanar((uv) => diffuseAt(index, uv), layer.tile)
475
+ : diffuseAt(index, ground.div(layer.tile));
476
+ const far = layer.far;
477
+ if (far !== undefined && layer.triplanar !== true) {
478
+ if (!(far.tile > 0 && far.from < far.to && far.amount >= 0 && far.amount <= 1))
479
+ throw new Error(
480
+ `loadTerrainSplat: layer '${layer.id}' far needs tile > 0, from < to and amount in 0..1.`,
481
+ );
482
+ const reach = smoothstep(far.from, far.to, positionWorld.distance(cameraPosition));
483
+ sample = mix(sample, diffuseAt(index, ground.div(far.tile)), reach.mul(far.amount));
484
+ }
485
+ if (layer.saturation !== undefined) {
486
+ const luma = dot(sample, vec3(0.2126, 0.7152, 0.0722));
487
+ sample = mix(vec3(luma), sample, layer.saturation);
488
+ }
489
+ return sample.mul(vec3(...layer.tint));
490
+ };
491
+ const normalOf = (layer: ITerrainSplatLayer): Node<"vec3"> | undefined => {
492
+ const slot = withNormals.indexOf(layer);
493
+ return slot === -1 || normalAt === undefined
494
+ ? undefined
495
+ : normalAt(slot, ground.div(layer.tile));
496
+ };
497
+ /**
498
+ * A layer's answer to light, as occlusion in r, roughness in g and metalness in b: its ORM map
499
+ * where it ships one, else the two numbers the table states (and no occlusion to apply).
500
+ */
501
+ const ormOf = (layer: ITerrainSplatLayer): Node<"vec3"> => {
502
+ const slot = withOrm.indexOf(layer);
503
+ if (slot !== -1 && ormAt !== undefined) return ormAt(slot, ground.div(layer.tile));
504
+ return vec3(1, layer.roughness ?? DEFAULT_ROUGHNESS, layer.metalness ?? 0);
505
+ };
506
+
507
+ /** A height-carrying layer's own height, on the projection its albedo uses. */
508
+ const heightOf = (layer: ITerrainSplatMaskedLayer): Node<"float"> | undefined => {
509
+ const slot = withHeight.indexOf(layer);
510
+ if (slot === -1 || heightAt === undefined) return undefined;
511
+ const at = (uv: Node<"vec2">): Node<"vec3"> => heightAt(slot, uv);
512
+ return (layer.triplanar === true ? triplanar(at, layer.tile) : at(ground.div(layer.tile))).r;
513
+ };
514
+
515
+ let color = albedo(table.base, 0);
516
+ let normalSample: Node<"vec3"> = normalOf(table.base) ?? vec3(0.5, 0.5, 1);
517
+ let ormSample: Node<"vec3"> = ormOf(table.base);
518
+ table.layers.forEach((layer, offset) => {
519
+ const masked = clamp(
520
+ maskOf(layer)
521
+ .add(push)
522
+ .sub(layer.lo)
523
+ .div(layer.hi - layer.lo),
524
+ 0,
525
+ 1,
526
+ );
527
+ const weight =
528
+ options.layerWeight === undefined
529
+ ? masked
530
+ : options.layerWeight(masked, { height: heightOf(layer), index: offset, layer });
531
+ color = mix(color, albedo(layer, offset + 1), weight);
532
+ const nrm = normalOf(layer);
533
+ if (nrm !== undefined) normalSample = mix(normalSample, nrm, weight);
534
+ ormSample = mix(ormSample, ormOf(layer), weight);
535
+ });
536
+ const macro = mx_noise_float(vec3(ground.mul(table.macro.scale), 0))
537
+ .mul(0.5)
538
+ .add(0.5)
539
+ .mul(table.macro.max - table.macro.min)
540
+ .add(table.macro.min);
541
+
542
+ // Every layer's own light response, blended by the same weights as its colour: the material
543
+ // holds no scalar of its own, and `DEFAULT_ROUGHNESS` only answers for a layer that states
544
+ // nothing at all.
545
+ const material = new MeshStandardNodeMaterial();
546
+ material.name = "terrain-splat";
547
+ material.colorNode = color.mul(macro);
548
+ // A top-down projection's tangent frame: +x along u, ground +y (three -z) along v, OpenGL green
549
+ // up v, re-orthogonalised against the tile's own normal.
550
+ const n = normalWorld;
551
+ const tangent = vec3(1, 0, 0).sub(n.mul(n.x)).normalize();
552
+ const bitangent = n.cross(tangent).normalize();
553
+ const t = normalSample.mul(2).sub(1);
554
+ const perturbed = tangent.mul(t.x).add(bitangent.mul(t.y)).add(n.mul(t.z)).normalize();
555
+ material.normalNode = cameraViewMatrix.mul(vec4(perturbed, 0)).xyz.normalize();
556
+ material.aoNode = ormSample.r;
557
+ material.roughnessNode = ormSample.g;
558
+ material.metalnessNode = ormSample.b;
559
+ // One line, printed and kept on the material: what this surface costs, readable by a game that
560
+ // wants to assert it rather than scrape a console.
561
+ material.userData.TN_TERRAIN_SPLAT = `layers=${String(all.length)} samplers=${String(samplers)} stacked=${String(stackedSets)}`;
562
+ console.info(`TN_TERRAIN_SPLAT ${material.userData.TN_TERRAIN_SPLAT as string}`);
563
+ return material;
564
+ }