@threenative/core 0.3.11 → 0.3.12

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 (157) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10566 -22552
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-pass-budget.ts +34 -7
  84. package/src/renderProjection.ts +22 -0
  85. package/src/renderer.ts +92 -37
  86. package/src/snow-field.ts +1 -1
  87. package/src/spells/cast-pool.ts +361 -0
  88. package/src/spells/index.ts +177 -0
  89. package/src/spells/mechanisms.ts +295 -0
  90. package/src/spells/reaction-field.ts +415 -0
  91. package/src/spells/spell-lights.ts +139 -0
  92. package/src/spells/spell-world.ts +187 -0
  93. package/src/spells/spell.ts +397 -0
  94. package/src/spells/spells.ts +283 -0
  95. package/src/spells/ultra/engine/camera.ts +184 -0
  96. package/src/spells/ultra/engine/quality.ts +96 -0
  97. package/src/spells/ultra/index.ts +52 -0
  98. package/src/spells/ultra/main.ts +305 -0
  99. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  100. package/src/spells/ultra/spells/cast.ts +233 -0
  101. package/src/spells/ultra/spells/fire.ts +1267 -0
  102. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  103. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  104. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  105. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  106. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  107. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  108. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  109. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  110. package/src/spells/ultra/vfx/common.ts +1195 -0
  111. package/src/spells/ultra/vfx/noise.ts +441 -0
  112. package/src/startup-readiness.ts +128 -34
  113. package/src/version.ts +1 -1
  114. package/src/warmup.ts +56 -8
  115. package/src/water-surface.ts +9 -3
  116. package/src/world-bundle-safety.ts +401 -0
  117. package/src/world-cell-batches.ts +1216 -0
  118. package/src/world-cell-chunks.ts +1132 -0
  119. package/src/world-cell-data.ts +995 -0
  120. package/src/world-cell-impostors.ts +1449 -0
  121. package/src/world-cell-lod-bias.ts +151 -0
  122. package/src/world-cell-models.ts +1074 -0
  123. package/src/world-cell-options.ts +189 -0
  124. package/src/world-cell-placements.ts +694 -0
  125. package/src/world-cell-prewarm.ts +557 -0
  126. package/src/world-cell-readiness.ts +357 -0
  127. package/src/world-cell-render-bundles.ts +459 -0
  128. package/src/world-cell-render-gpu-dress.ts +714 -0
  129. package/src/world-cell-render-main-cull.ts +484 -0
  130. package/src/world-cell-render-shadow-claims.ts +198 -0
  131. package/src/world-cell-render-util.ts +246 -0
  132. package/src/world-cell-render.ts +1493 -0
  133. package/src/world-cell-residency.ts +745 -0
  134. package/src/world-cells.ts +1318 -10418
  135. package/src/world-chunk-shadow.ts +308 -0
  136. package/src/world-collar.ts +315 -0
  137. package/src/world-gpu-flags.ts +163 -0
  138. package/src/world-gpu-readback.ts +881 -0
  139. package/src/world-gpu-reference.ts +510 -0
  140. package/src/world-gpu-scene.ts +214 -2264
  141. package/src/world-gpu-shadow.ts +190 -0
  142. package/src/world-gpu-types.ts +381 -0
  143. package/src/world-gpu-validation.ts +518 -0
  144. package/src/world-heightfield.ts +802 -0
  145. package/src/world-load-limiter.ts +106 -0
  146. package/src/world-noise.ts +241 -0
  147. package/src/world-package.ts +42 -0
  148. package/src/world-region.ts +1 -1
  149. package/src/world-terrain-splat.ts +365 -149
  150. package/src/world-tile-budget.ts +256 -0
  151. package/src/world-tile-geometry.ts +469 -0
  152. package/src/world-tile-lod.ts +408 -0
  153. package/src/world-tile-observation.ts +566 -0
  154. package/src/world-tile-stitch.ts +166 -0
  155. package/src/world-tiles.ts +170 -1745
  156. package/src/world-water-bodies.ts +359 -0
  157. package/src/world.ts +35 -741
@@ -5,7 +5,9 @@ import {
5
5
  LinearFilter,
6
6
  LinearMipmapLinearFilter,
7
7
  type Material,
8
+ Mesh,
8
9
  NoColorSpace,
10
+ type Object3D,
9
11
  RGBAFormat,
10
12
  RepeatWrapping,
11
13
  type Texture,
@@ -46,6 +48,14 @@ export interface ITerrainSplatLayer {
46
48
  readonly id: string;
47
49
  readonly tile: number;
48
50
  readonly tint: readonly [number, number, number];
51
+ /** Package-relative image paths; omitted entries retain `<textures>/<id>_<kind>.jpg`.
52
+ * Normal, ORM and height maps are still loaded only when their flags request them. */
53
+ readonly maps?: {
54
+ readonly diffuse?: string;
55
+ readonly normal?: string;
56
+ readonly orm?: string;
57
+ readonly height?: string;
58
+ };
49
59
  readonly normal?: boolean;
50
60
  /** `<id>_orm.jpg`: occlusion in r, roughness in g, metalness in b, read as linear data. */
51
61
  readonly orm?: boolean;
@@ -116,13 +126,48 @@ export interface ITerrainSplatWeightContext {
116
126
  readonly index: number;
117
127
  }
118
128
 
129
+ /** Loaded images for one game-authored sample; index 0 is the base, then table.layers in order.
130
+ * The loader owns these images until the returned material is disposed; do not dispose them. */
131
+ export interface ITerrainSplatSampleContext {
132
+ readonly layer: ITerrainSplatLayer;
133
+ readonly index: number;
134
+ readonly diffuse: Texture;
135
+ readonly normal: Texture | undefined;
136
+ readonly orm: Texture | undefined;
137
+ readonly height: Texture | undefined;
138
+ }
139
+
140
+ /** A game's projected layer. An absent normal leaves the accumulated normal unchanged.
141
+ * Normals are encoded OpenGL for the default factory; a custom factory owns their encoding.
142
+ * An absent ORM uses the layer's existing map or scalar response. */
143
+ export interface ITerrainSplatSample {
144
+ readonly color: Node<"vec3">;
145
+ readonly normal?: Node<"vec3">;
146
+ readonly orm?: Node<"vec3">;
147
+ }
148
+
149
+ /** Engine-blended channels; color includes the table's macro variation. */
150
+ export interface ITerrainSplatMaterialContext {
151
+ readonly color: Node<"vec3">;
152
+ readonly normal: Node<"vec3">;
153
+ readonly orm: Node<"vec3">;
154
+ }
155
+
119
156
  export interface ILoadTerrainSplatOptions {
120
157
  readonly assets: IAssetLoader;
158
+ /** Game-authored appearance. The baked splat mask descriptor and texture folder remain in the package. */
159
+ readonly table?: Pick<ITerrainSplatTable, "base" | "breakup" | "macro" | "layers">;
121
160
  /**
122
161
  * The live renderer. Uncompressed layers stack into one array texture per set through GPU copies,
123
162
  * which need one; without it every layer keeps its own sampler and the marker says so.
124
163
  */
125
164
  readonly renderer?: IRendererLike;
165
+ /** Precomputed for every layer before layerWeight runs; replaces the package's projection.
166
+ * Custom sampling retains the loaded images and skips texture-array stacking. */
167
+ readonly layerSample?: (context: ITerrainSplatSampleContext) => ITerrainSplatSample;
168
+ /** Replaces final material assembly, retaining the engine's ordered channel blend.
169
+ * Loader-owned textures are released with the returned material, including composition errors. */
170
+ readonly materialFactory?: (context: ITerrainSplatMaterialContext) => Material;
126
171
  /**
127
172
  * Replaces each layer's blend weight, given the mask's own (remapped, 0..1) and the layer's
128
173
  * height sample. The game owns the curve, for example a height blend; the package mixes colour,
@@ -165,11 +210,42 @@ function packageDir(url: string): string {
165
210
  return slash === -1 ? "" : url.slice(0, slash + 1);
166
211
  }
167
212
 
213
+ function packageAssetPath(directory: string, path: string): string {
214
+ const joined = `${directory}${path}`;
215
+ // The host may be empty: a `file:///` package keeps its triple slash.
216
+ const prefix = /^(?:(?:[a-z][a-z\d+.-]*:)?\/\/[^/]*\/|\/)?/iu.exec(joined)?.[0] ?? "";
217
+ const segments: string[] = [];
218
+ for (const segment of joined.slice(prefix.length).split("/")) {
219
+ if (segment === "" || segment === ".") continue;
220
+ if (segment === "..") {
221
+ if (segments.length === 0)
222
+ throw new Error(`loadTerrainSplat: map path '${path}' escapes the package asset root.`);
223
+ segments.pop();
224
+ } else {
225
+ segments.push(segment);
226
+ }
227
+ }
228
+ return `${prefix}${segments.join("/")}`;
229
+ }
230
+
168
231
  async function fetchResolved(assets: IAssetLoader, path: string): Promise<Response> {
232
+ let attempted = false;
233
+ let everyFetchRejected = true;
234
+ let lastFetchError: unknown;
169
235
  for (const candidate of await assets.resolve(path)) {
170
- const response = await fetch(candidate);
236
+ attempted = true;
237
+ let response: Response;
238
+ try {
239
+ response = await fetch(candidate);
240
+ } catch (error) {
241
+ lastFetchError = error;
242
+ continue;
243
+ }
244
+ everyFetchRejected = false;
171
245
  if (response.ok) return response;
172
246
  }
247
+ if (attempted && everyFetchRejected)
248
+ throw new Error(`loadTerrainSplat: '${path}' is not served.`, { cause: lastFetchError });
173
249
  throw new Error(`loadTerrainSplat: '${path}' is not served.`);
174
250
  }
175
251
 
@@ -225,13 +301,22 @@ function stackUncompressed(
225
301
  return undefined;
226
302
  const size = gpuSize(maps[0] as Texture);
227
303
  if (size === undefined) return undefined;
304
+ const first = maps[0] as Texture;
305
+ // A copy needs copy-compatible formats: a layer a dev server already cooked to a compressed
306
+ // codec cannot land in an uncompressed array, and WebGPU rejects the whole command buffer.
228
307
  const sameSize = maps.every((map) => {
229
308
  const other = gpuSize(map);
230
- return other !== undefined && other.width === size.width && other.height === size.height;
309
+ return (
310
+ other !== undefined &&
311
+ other.width === size.width &&
312
+ other.height === size.height &&
313
+ (map as CompressedTexture).isCompressedTexture !== true &&
314
+ map.format === first.format &&
315
+ map.type === first.type
316
+ );
231
317
  });
232
318
  if (!sameSize) return undefined;
233
319
 
234
- const first = maps[0] as Texture;
235
320
  const array = new DataArrayTexture(
236
321
  new Uint8Array(size.width * size.height * 4 * maps.length),
237
322
  size.width,
@@ -349,7 +434,7 @@ export function stackLayers(
349
434
  * @situation the game's terrain should match the DCC's terrain material without a second copy
350
435
  * @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
436
  * @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
437
+ * @override `table` may replace `base`, `breakup`, `macro` and `layers` from game source; baked `splat` and `textures` stay package-owned
353
438
  * @example
354
439
  * const surface = await loadTerrainSplat({ assets: ctx.assets, renderer: ctx.renderer, url: "world/world.json" });
355
440
  * const world = await WorldCells.load({ assets: ctx.assets, url: "world/world.json", surface, follow, ring: 2 });
@@ -363,9 +448,13 @@ export async function loadTerrainSplat(options: ILoadTerrainSplatOptions): Promi
363
448
  "loadTerrainSplat: world.json has no terrain.layers.table/splat; export them with the export_world.py recipe.",
364
449
  );
365
450
  const dir = packageDir(url);
366
- const table = (await (
451
+ const bakedTable = (await (
367
452
  await fetchResolved(assets, dir + layerPaths.table)
368
453
  ).json()) as ITerrainSplatTable;
454
+ const table: ITerrainSplatTable =
455
+ options.table === undefined
456
+ ? bakedTable
457
+ : { ...options.table, splat: bakedTable.splat, textures: bakedTable.textures };
369
458
  const bytes = new Uint8Array(
370
459
  await (await fetchResolved(assets, dir + layerPaths.splat)).arrayBuffer(),
371
460
  );
@@ -400,165 +489,292 @@ export async function loadTerrainSplat(options: ILoadTerrainSplatOptions): Promi
400
489
  `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
490
  );
402
491
 
492
+ const owned =
493
+ options.layerSample !== undefined || options.materialFactory !== undefined
494
+ ? new Set<Texture>([splat])
495
+ : undefined;
496
+ let released = false;
497
+ const release = () => {
498
+ if (released) return;
499
+ released = true;
500
+ for (const map of owned ?? []) map.dispose();
501
+ };
502
+
403
503
  const load = async (
404
504
  layer: ITerrainSplatLayer,
405
505
  kind: "diff" | "nrm" | "orm" | "h",
406
506
  ): Promise<Texture> => {
407
- const map = await assets.texture(`${dir}${table.textures}/${layer.id}_${kind}.jpg`, {
408
- data: kind !== "diff",
409
- });
507
+ if (
508
+ layer.maps !== undefined &&
509
+ (layer.maps === null || typeof layer.maps !== "object" || Array.isArray(layer.maps))
510
+ )
511
+ throw new Error(`loadTerrainSplat: layer '${layer.id}' maps needs a path object.`);
512
+ const paths = {
513
+ diff: layer.maps?.diffuse,
514
+ nrm: layer.maps?.normal,
515
+ orm: layer.maps?.orm,
516
+ h: layer.maps?.height,
517
+ };
518
+ const explicitPath = paths[kind];
519
+ if (
520
+ explicitPath !== undefined &&
521
+ (typeof explicitPath !== "string" ||
522
+ explicitPath.trim() === "" ||
523
+ /^(?:[/\\]|[a-z][a-z0-9+.-]*:)/iu.test(explicitPath))
524
+ )
525
+ throw new Error(
526
+ `loadTerrainSplat: layer '${layer.id}' ${kind} map needs a package-relative path.`,
527
+ );
528
+ const path =
529
+ explicitPath === undefined ? `${table.textures}/${layer.id}_${kind}.jpg` : explicitPath;
530
+ const map = await assets.texture(packageAssetPath(dir, path), { data: kind !== "diff" });
410
531
  map.wrapS = RepeatWrapping;
411
532
  map.wrapT = RepeatWrapping;
412
533
  map.anisotropy = 8;
413
534
  map.needsUpdate = true;
535
+ if (released && owned?.has(map) === false) map.dispose();
536
+ owned?.add(map);
414
537
  return map;
415
538
  };
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
- };
539
+ try {
540
+ const withNormals = all.filter((layer) => layer.normal === true);
541
+ const withOrm = all.filter((layer) => layer.orm === true);
542
+ const diffuseMaps = await Promise.all(all.map((layer) => load(layer, "diff")));
543
+ const normalMaps = await Promise.all(withNormals.map((layer) => load(layer, "nrm")));
544
+ const ormMaps = await Promise.all(withOrm.map((layer) => load(layer, "orm")));
545
+ const withHeight = table.layers.filter((layer) => layer.height === true);
546
+ const heightMaps = await Promise.all(withHeight.map((layer) => load(layer, "h")));
470
547
 
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))
548
+ // One sampler per set when the layers stack; separate textures (and a warning) when they do not.
549
+ let samplers = 1;
550
+ let stackedSets = 0;
551
+ const sampler = (
552
+ maps: readonly Texture[],
553
+ what: string,
554
+ ): ((layer: number, uv: Node<"vec2">) => Node<"vec3">) => {
555
+ if (options.layerSample !== undefined) {
556
+ samplers += maps.length;
557
+ return (layer, uv) => texture(maps[layer] as Texture, uv).rgb;
558
+ }
559
+ const stacked = stackLayers(maps, options.renderer);
560
+ if (stacked !== undefined) {
561
+ samplers += 1;
562
+ stackedSets += 1;
563
+ for (const map of maps) owned?.delete(map);
564
+ owned?.add(stacked);
565
+ return (layer, uv) => texture(stacked, uv).depth(int(layer)).rgb;
566
+ }
567
+ samplers += maps.length;
568
+ if (maps.length > 1)
569
+ console.warn(
570
+ `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.`,
571
+ );
572
+ return (layer, uv) => texture(maps[layer] as Texture, uv).rgb;
573
+ };
574
+ const diffuseAt = sampler(diffuseMaps, "albedo");
575
+ const normalAt = withNormals.length === 0 ? undefined : sampler(normalMaps, "normal");
576
+ const ormAt = withOrm.length === 0 ? undefined : sampler(ormMaps, "ORM");
577
+ const heightAt = withHeight.length === 0 ? undefined : sampler(heightMaps, "height");
578
+
579
+ const ground = vec2(positionWorld.x, positionWorld.z.negate());
580
+ const maskOf = (layer: ITerrainSplatMaskedLayer): Node<"float"> => {
581
+ const where = table.splat.masks[layer.mask];
582
+ if (where === undefined)
479
583
  throw new Error(
480
- `loadTerrainSplat: layer '${layer.id}' far needs tile > 0, from < to and amount in 0..1.`,
584
+ `loadTerrainSplat: layer '${layer.id}' names missing mask '${layer.mask}'.`,
481
585
  );
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
- };
586
+ const source = planes[where[0]];
587
+ if (source === undefined)
588
+ throw new Error(`loadTerrainSplat: mask '${layer.mask}' names a missing plane.`);
589
+ return source[where[1] === "rgb" ? layer.channel : where[1]];
590
+ };
591
+ const breakup = mx_noise_float(vec3(ground.mul(table.breakup.scale), 0))
592
+ .mul(0.5)
593
+ .add(0.5);
594
+ const push = breakup.mul(2 * table.breakup.push).sub(table.breakup.push);
506
595
 
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
- };
596
+ // Box projection for cliffs: three axis-aligned samples blended by the surface normal.
597
+ const triplanar = (at: (uv: Node<"vec2">) => Node<"vec3">, tile: number): Node<"vec3"> => {
598
+ const weights = normalWorld.abs();
599
+ const w = weights.div(weights.x.add(weights.y).add(weights.z));
600
+ const p = positionWorld.div(tile);
601
+ return at(p.zy).mul(w.x).add(at(p.xz).mul(w.y)).add(at(p.xy).mul(w.z));
602
+ };
603
+
604
+ const albedo = (layer: ITerrainSplatLayer, index: number): Node<"vec3"> => {
605
+ let sample: Node<"vec3"> =
606
+ layer.triplanar === true
607
+ ? triplanar((uv) => diffuseAt(index, uv), layer.tile)
608
+ : diffuseAt(index, ground.div(layer.tile));
609
+ const far = layer.far;
610
+ if (far !== undefined && layer.triplanar !== true) {
611
+ if (!(far.tile > 0 && far.from < far.to && far.amount >= 0 && far.amount <= 1))
612
+ throw new Error(
613
+ `loadTerrainSplat: layer '${layer.id}' far needs tile > 0, from < to and amount in 0..1.`,
614
+ );
615
+ const reach = smoothstep(far.from, far.to, positionWorld.distance(cameraPosition));
616
+ sample = mix(sample, diffuseAt(index, ground.div(far.tile)), reach.mul(far.amount));
617
+ }
618
+ if (layer.saturation !== undefined) {
619
+ const luma = dot(sample, vec3(0.2126, 0.7152, 0.0722));
620
+ sample = mix(vec3(luma), sample, layer.saturation);
621
+ }
622
+ return sample.mul(vec3(...layer.tint));
623
+ };
624
+ const normalOf = (layer: ITerrainSplatLayer): Node<"vec3"> | undefined => {
625
+ const slot = withNormals.indexOf(layer);
626
+ return slot === -1 || normalAt === undefined
627
+ ? undefined
628
+ : normalAt(slot, ground.div(layer.tile));
629
+ };
630
+ /**
631
+ * A layer's answer to light, as occlusion in r, roughness in g and metalness in b: its ORM map
632
+ * where it ships one, else the two numbers the table states (and no occlusion to apply).
633
+ */
634
+ const ormOf = (layer: ITerrainSplatLayer): Node<"vec3"> => {
635
+ const slot = withOrm.indexOf(layer);
636
+ if (slot !== -1 && ormAt !== undefined) return ormAt(slot, ground.div(layer.tile));
637
+ return vec3(1, layer.roughness ?? DEFAULT_ROUGHNESS, layer.metalness ?? 0);
638
+ };
639
+
640
+ /** A height-carrying layer's own height, on the projection its albedo uses. */
641
+ const heightOf = (layer: ITerrainSplatMaskedLayer): Node<"float"> | undefined => {
642
+ const slot = withHeight.indexOf(layer);
643
+ if (slot === -1 || heightAt === undefined) return undefined;
644
+ const at = (uv: Node<"vec2">): Node<"vec3"> => heightAt(slot, uv);
645
+ return (layer.triplanar === true ? triplanar(at, layer.tile) : at(ground.div(layer.tile))).r;
646
+ };
514
647
 
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,
648
+ const samples = all.map(
649
+ (layer, index): ITerrainSplatSample =>
650
+ options.layerSample === undefined
651
+ ? { color: albedo(layer, index), normal: normalOf(layer), orm: ormOf(layer) }
652
+ : options.layerSample({
653
+ layer,
654
+ index,
655
+ diffuse: diffuseMaps[index] as Texture,
656
+ normal: normalMaps[withNormals.indexOf(layer)],
657
+ orm: ormMaps[withOrm.indexOf(layer)],
658
+ height: heightMaps[withHeight.indexOf(layer as ITerrainSplatMaskedLayer)],
659
+ }),
526
660
  );
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);
661
+ let color = (samples[0] as ITerrainSplatSample).color;
662
+ let normalSample: Node<"vec3"> = samples[0]?.normal ?? vec3(0.5, 0.5, 1);
663
+ let ormSample: Node<"vec3"> = samples[0]?.orm ?? ormOf(table.base);
664
+ table.layers.forEach((layer, offset) => {
665
+ const masked = clamp(
666
+ maskOf(layer)
667
+ .add(push)
668
+ .sub(layer.lo)
669
+ .div(layer.hi - layer.lo),
670
+ 0,
671
+ 1,
672
+ );
673
+ const weight =
674
+ options.layerWeight === undefined
675
+ ? masked
676
+ : options.layerWeight(masked, { height: heightOf(layer), index: offset, layer });
677
+ const sample = samples[offset + 1] as ITerrainSplatSample;
678
+ color = mix(color, sample.color, weight);
679
+ const nrm = sample.normal;
680
+ if (nrm !== undefined) normalSample = mix(normalSample, nrm, weight);
681
+ ormSample = mix(ormSample, sample.orm ?? ormOf(layer), weight);
682
+ });
683
+ const macro = mx_noise_float(vec3(ground.mul(table.macro.scale), 0))
684
+ .mul(0.5)
685
+ .add(0.5)
686
+ .mul(table.macro.max - table.macro.min)
687
+ .add(table.macro.min);
688
+
689
+ // Every layer's own light response, blended by the same weights as its colour: the material
690
+ // holds no scalar of its own, and `DEFAULT_ROUGHNESS` only answers for a layer that states
691
+ // nothing at all.
692
+ let material: Material;
693
+ if (options.materialFactory === undefined) {
694
+ const standard = new MeshStandardNodeMaterial();
695
+ standard.name = "terrain-splat";
696
+ standard.colorNode = color.mul(macro);
697
+ // A top-down projection's tangent frame: +x along u, ground +y (three -z) along v, OpenGL green
698
+ // up v, re-orthogonalised against the tile's own normal.
699
+ const n = normalWorld;
700
+ const tangent = vec3(1, 0, 0).sub(n.mul(n.x)).normalize();
701
+ const bitangent = n.cross(tangent).normalize();
702
+ const t = normalSample.mul(2).sub(1);
703
+ const perturbed = tangent.mul(t.x).add(bitangent.mul(t.y)).add(n.mul(t.z)).normalize();
704
+ standard.normalNode = cameraViewMatrix.mul(vec4(perturbed, 0)).xyz.normalize();
705
+ standard.aoNode = ormSample.r;
706
+ standard.roughnessNode = ormSample.g;
707
+ standard.metalnessNode = ormSample.b;
708
+ material = standard;
709
+ } else {
710
+ material = options.materialFactory({
711
+ color: color.mul(macro),
712
+ normal: normalSample,
713
+ orm: ormSample,
714
+ });
715
+ }
716
+ if (owned !== undefined) material.addEventListener("dispose", release);
717
+ // One line, printed and kept on the material: what this surface costs, readable by a game that
718
+ // wants to assert it rather than scrape a console.
719
+ material.userData.TN_TERRAIN_SPLAT =
720
+ options.layerSample === undefined
721
+ ? `layers=${String(all.length)} samplers=${String(samplers)} stacked=${String(stackedSets)}`
722
+ : `layers=${String(all.length)} loadedSamplerUpperBound=${String(samplers)} stacked=0 sampling=custom`;
723
+ console.info(`TN_TERRAIN_SPLAT ${material.userData.TN_TERRAIN_SPLAT as string}`);
724
+ return material;
725
+ } catch (error) {
726
+ if (owned !== undefined) release();
727
+ throw error;
728
+ }
729
+ }
730
+
731
+ /**
732
+ * Apply a cooked GLB's package-authored layered surface to its marked terrain meshes.
733
+ * `url` is the loaded GLB URL; extras pointers are relative to it. Uses the same asset/fetch
734
+ * path as loadTerrainSplat on web and native. The caller owns the assigned materials' lifetime.
735
+ * @situation apply the authored layered terrain surface after loading a cooked world GLB
736
+ * @constraint url names the loaded GLB; tnTerrainSurface extras name a relative world package JSON
737
+ * @override `table` may replace `base`, `breakup`, `macro` and `layers`; baked `splat` and `textures` stay package-owned
738
+ * @example
739
+ * await applyTerrainSurface(world.scene, { assets: ctx.assets, renderer: ctx.renderer, url: "world/world.glb" });
740
+ */
741
+ export async function applyTerrainSurface(
742
+ root: Object3D,
743
+ options: ILoadTerrainSplatOptions,
744
+ ): Promise<void> {
745
+ const targets = new Map<Mesh, string>();
746
+ const retained = new Set<Material>();
747
+ root.traverse((object) => {
748
+ if (!(object instanceof Mesh)) return;
749
+ let owner: Object3D | null = object;
750
+ while (owner !== null && owner.userData.tnTerrainSurface === undefined && owner !== root)
751
+ owner = owner.parent;
752
+ const pointer: unknown = owner?.userData.tnTerrainSurface;
753
+ if (pointer === undefined) {
754
+ for (const material of Array.isArray(object.material) ? object.material : [object.material])
755
+ retained.add(material);
756
+ return;
757
+ }
758
+ if (
759
+ typeof pointer !== "string" ||
760
+ !/^(?:[a-zA-Z0-9_-]+\/)*[a-zA-Z0-9_.-]+\.json$/u.test(pointer)
761
+ )
762
+ throw new Error(`applyTerrainSurface: invalid terrain surface pointer '${String(pointer)}'.`);
763
+ targets.set(object, packageDir(options.url) + pointer);
535
764
  });
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;
765
+ const surfaces = new Map<string, Material>();
766
+ try {
767
+ for (const url of new Set(targets.values()))
768
+ surfaces.set(url, await loadTerrainSplat({ ...options, url }));
769
+ } catch (error) {
770
+ for (const surface of surfaces.values()) surface.dispose();
771
+ throw error;
772
+ }
773
+ const replaced = new Set<Material>();
774
+ for (const [mesh, url] of targets) {
775
+ for (const material of Array.isArray(mesh.material) ? mesh.material : [mesh.material])
776
+ replaced.add(material);
777
+ mesh.material = surfaces.get(url) as Material;
778
+ }
779
+ for (const material of replaced) if (!retained.has(material)) material.dispose();
564
780
  }