@threenative/core 0.3.13 → 0.3.16

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 (60) hide show
  1. package/capabilities.json +1008 -83
  2. package/dist/{chunk-4SRAQFTU.js → chunk-2GPHICV6.js} +1 -1
  3. package/dist/{chunk-EEABDLUC.js → chunk-5C4TCWI3.js} +2 -2
  4. package/dist/{chunk-DIPIJICH.js → chunk-FQURMC2F.js} +122 -18
  5. package/dist/{chunk-EFWZWLPY.js → chunk-OMGIYWW7.js} +400 -13
  6. package/dist/{chunk-SV4QVUTQ.js → chunk-QAQHYOWY.js} +1 -1
  7. package/dist/{chunk-GYUZJQ7U.js → chunk-VQRPEOKY.js} +4 -1
  8. package/dist/hot.js +10 -2
  9. package/dist/index.d.ts +608 -16
  10. package/dist/index.js +2037 -633
  11. package/dist/{model-lod-DPTzeCcD.d.ts → model-lod-B921F6kQ.d.ts} +0 -10
  12. package/dist/playtest.js +3 -3
  13. package/dist/{quality-BYqKGAwo.d.ts → quality-BADStsTn.d.ts} +2 -2
  14. package/dist/render-environment.d.ts +1 -1
  15. package/dist/ui-layer.js +2 -2
  16. package/dist/worker.js +2 -2
  17. package/dist/world.d.ts +14 -4
  18. package/dist/world.js +179 -36
  19. package/mcp/animation-server.mjs +1 -1
  20. package/mcp/engine-server.mjs +44 -17
  21. package/mcp/servers.mjs +4 -4
  22. package/package.json +6 -6
  23. package/patches/three@0.187.0-prd269-upgrade.patch +126 -2
  24. package/patches/three@0.187.0.patch +108 -21
  25. package/scripts/ensure-mcp.mjs +6 -1
  26. package/src/clustered-batch.ts +146 -3
  27. package/src/clustered-mesh.ts +548 -20
  28. package/src/debug.ts +16 -0
  29. package/src/displaced-surface.ts +428 -0
  30. package/src/engine-hooks.ts +29 -0
  31. package/src/frame-budget.ts +16 -0
  32. package/src/generated/console-markers.ts +1 -0
  33. package/src/grass-field.ts +628 -0
  34. package/src/grounding.ts +19 -10
  35. package/src/hot.ts +18 -2
  36. package/src/index.ts +112 -0
  37. package/src/instanced-batch-lod.ts +54 -0
  38. package/src/model-lod.ts +77 -1
  39. package/src/pose-measure.ts +27 -2
  40. package/src/render/material-key.ts +21 -1
  41. package/src/render/screen-probe-gather.ts +303 -0
  42. package/src/render/short-range-ao.ts +274 -0
  43. package/src/render/world-impostor-surface.ts +98 -3
  44. package/src/render-camera-cull.ts +9 -3
  45. package/src/renderer.ts +26 -4
  46. package/src/scatter-field.ts +497 -0
  47. package/src/startup-offscreen-bytes.ts +11 -5
  48. package/src/state.ts +16 -3
  49. package/src/static-transform.ts +109 -6
  50. package/src/tile-ring.ts +294 -0
  51. package/src/version.ts +1 -1
  52. package/src/warmup.ts +15 -2
  53. package/src/world-cell-batches.ts +4 -0
  54. package/src/world-cell-data.ts +7 -0
  55. package/src/world-cell-models.ts +36 -8
  56. package/src/world-cell-render-gpu-dress.ts +4 -2
  57. package/src/world-cell-render-util.ts +2 -2
  58. package/src/world-cells.ts +1 -1
  59. package/src/world-river-ribbon.ts +13 -22
  60. package/src/world-water-bodies.ts +113 -3
@@ -41,6 +41,7 @@ import {
41
41
  modelWorldMatrix,
42
42
  normalize,
43
43
  positionGeometry,
44
+ renderGroup,
44
45
  screenCoordinate,
45
46
  select,
46
47
  sin,
@@ -64,6 +65,7 @@ import {
64
65
  type NodeBuilder,
65
66
  type NodeMaterial,
66
67
  } from "three/webgpu";
68
+ import { readLaunchFlag } from "../debug.js";
67
69
  import { IMPOSTOR_VIEW_GRID, type WorldImpostorAtlas } from "./world-impostor.js";
68
70
 
69
71
  type InstanceMatrixFn = () => Node<"mat4">;
@@ -967,6 +969,82 @@ export function advanceTemporalLod(
967
969
  state.alpha = window > 0 ? Math.min(1, Math.max(0, (now - lag - state.fromTime) / window)) : 1;
968
970
  }
969
971
 
972
+ /**
973
+ * The distance past which `level`'s gate discards every fragment at the worst per-instance random
974
+ * draw: `worldLodMaterial`'s fade-out mix reaches 1 at `gate + 0.75 * span` (0.5 of the ramp plus
975
+ * the 0.25 random swing). `undefined` for the last level, which has no coarser level to fade into.
976
+ */
977
+ export function lodFadedPast(
978
+ distances: readonly number[],
979
+ level: number,
980
+ width: number,
981
+ ): number | undefined {
982
+ const gate = level + 1;
983
+ const at = distances[gate];
984
+ if (at === undefined) return undefined;
985
+ let span = Math.min(at * width, (at - (distances[gate - 1] as number)) * width);
986
+ const next = distances[gate + 1];
987
+ if (next !== undefined) span = Math.min(span, (next - at) * width);
988
+ return at + 0.75 * span;
989
+ }
990
+
991
+ // `?lodCollapse=1` (TN_LOD_COLLAPSE, `__tnLodCollapse`) is read once per page; while it is on,
992
+ // `globalThis.__tnLodCollapse = false` turns the collapse off live for a paired A/B.
993
+ let lodCollapseArmed: boolean | undefined;
994
+ // Render group, as the LOD clock: an object-group uniform freezes on settled static batches.
995
+ const makeLodCollapseSwitch = () => uniform(1).setGroup(renderGroup);
996
+ let lodCollapseSwitch: ReturnType<typeof makeLodCollapseSwitch> | undefined;
997
+ function lodCollapseNode(): ReturnType<typeof makeLodCollapseSwitch> | undefined {
998
+ lodCollapseArmed ??= readLaunchFlag({
999
+ environment: "TN_LOD_COLLAPSE",
1000
+ query: "lodCollapse",
1001
+ global: "__tnLodCollapse",
1002
+ });
1003
+ if (!lodCollapseArmed) return undefined;
1004
+ lodCollapseSwitch ??= makeLodCollapseSwitch();
1005
+ return lodCollapseSwitch;
1006
+ }
1007
+
1008
+ /** Per frame: follow `globalThis.__tnLodCollapse` when the collapse was armed at boot. */
1009
+ export function syncLodCollapse(): void {
1010
+ if (lodCollapseSwitch === undefined) return;
1011
+ const live: unknown = Reflect.get(globalThis, "__tnLodCollapse");
1012
+ if (typeof live === "boolean") lodCollapseSwitch.value = live ? 1 : 0;
1013
+ }
1014
+
1015
+ /**
1016
+ * Collapse to one point the vertices of an instance whose every fragment the LOD gate discards:
1017
+ * past `past` from every eye the masks read, and not held whole by its published range or a swap.
1018
+ */
1019
+ function collapseFadedVertices(
1020
+ material: NodeMaterial,
1021
+ on: Node<"float">,
1022
+ gate: {
1023
+ readonly past: Node<"float">;
1024
+ readonly distances: readonly Node<"float">[];
1025
+ readonly lod: Node<"float">;
1026
+ readonly publishedRanges: boolean;
1027
+ readonly clock: Node<"float"> | undefined;
1028
+ },
1029
+ ): void {
1030
+ let faded = on.greaterThan(0.5);
1031
+ for (const distance of gate.distances) faded = faded.and(distance.greaterThanEqual(gate.past));
1032
+ if (gate.publishedRanges) {
1033
+ // A record whole at this level (`.y <= lod`) or still holding it after a swap draws anyway.
1034
+ const range = attribute("tnPublishedLodRange", "vec4") as Node<"vec4">;
1035
+ faded = faded.and(range.y.greaterThan(gate.lod));
1036
+ if (gate.clock !== undefined)
1037
+ faded = faded.and(
1038
+ range.z
1039
+ .lessThan(0)
1040
+ .or(gate.clock.sub(range.w).div(LOD_TEMPORAL_LAG).greaterThanEqual(1))
1041
+ .or(range.z.sub(gate.lod).abs().greaterThanEqual(0.5)),
1042
+ );
1043
+ }
1044
+ const position = (material.positionNode ?? positionGeometry) as Node<"vec3">;
1045
+ material.positionNode = select(faded, vec3(0, 0, 0), position);
1046
+ }
1047
+
970
1048
  /** Complementary LOD masks over the caller's distance bands, shared by colour and shadow passes. */
971
1049
  export function worldLodMaterial(
972
1050
  source: Material,
@@ -995,9 +1073,11 @@ export function worldLodMaterial(
995
1073
  .mul(vec4(0, 0, 0, 1)).xyz,
996
1074
  )();
997
1075
  // Quantise recovered roots so part-local float rounding cannot change the instance hash.
998
- const origin = varying(floor(root.mul(16).add(0.5)).div(16));
999
- const distanceTo = (at: Node<"vec3">) =>
1000
- (spatial ? length(origin.sub(at)) : length(origin.xz.sub(at.xz))).mul(distanceBias);
1076
+ const quantised = floor(root.mul(16).add(0.5)).div(16);
1077
+ const origin = varying(quantised);
1078
+ const distanceFrom = (point: Node<"vec3">, at: Node<"vec3">) =>
1079
+ (spatial ? length(point.sub(at)) : length(point.xz.sub(at.xz))).mul(distanceBias);
1080
+ const distanceTo = (at: Node<"vec3">) => distanceFrom(origin, at);
1001
1081
  const distance = distanceTo(eye);
1002
1082
  const random = fract(sin(dot(origin.xz, vec2(12.9898, 78.233))).mul(43758.5453));
1003
1083
  const noise = fract(sin(dot(floor(screenCoordinate.xy), vec2(12.9898, 78.233))).mul(43758.5453));
@@ -1079,6 +1159,21 @@ export function worldLodMaterial(
1079
1159
  material.maskShadowNode = material.maskShadowNode
1080
1160
  ? (material.maskShadowNode as Node<"bool">).and(shadow)
1081
1161
  : shadow;
1162
+ // PRD-888 lever 2: an instance past `lodFadedPast` has every colour and shadow fragment of this
1163
+ // level discarded, so its vertices collapse to one point and the rasteriser drops the triangles.
1164
+ // Read per instance in the vertex stage with the worst random draw and a 0.1 % margin, so the
1165
+ // varying's rounding cannot flip a fragment the gate would have drawn.
1166
+ const collapseOn = lodCollapseNode();
1167
+ if (collapseOn !== undefined)
1168
+ collapseFadedVertices(material, collapseOn, {
1169
+ past: uniform((lodFadedPast(distances, level, width) ?? 1e30) * 1.001),
1170
+ distances: (temporal === undefined ? [eye] : [eye, temporal.from, temporal.to]).map((at) =>
1171
+ distanceFrom(quantised, at),
1172
+ ),
1173
+ lod,
1174
+ publishedRanges,
1175
+ clock,
1176
+ });
1082
1177
  if (publishedRanges) material.userData.tnPublishedLodRange = true;
1083
1178
  return material;
1084
1179
  }
@@ -269,10 +269,10 @@ function hierarchyRevision(object: Object3D): number | undefined {
269
269
  * Counts one costly step by name in `globalThis.__tnEngineCost`, the bag a playtest reads per frame
270
270
  * (core reports it per frame in TN_FRAME_BUDGET.counters.engine), so a kit that brings back a per-frame walk fails its bound.
271
271
  */
272
- function countEngineCost(name: string): void {
272
+ function countEngineCost(name: string, count = 1): void {
273
273
  const host = globalThis as { __tnEngineCost?: Record<string, number> };
274
274
  host.__tnEngineCost ??= {};
275
- host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + 1;
275
+ host.__tnEngineCost[name] = (host.__tnEngineCost[name] ?? 0) + count;
276
276
  }
277
277
 
278
278
  /**
@@ -473,7 +473,13 @@ export class RenderCameraCull {
473
473
  this.#animationFrame += 1;
474
474
  this.#animationPrepared = true;
475
475
  this.#prepareCamera(camera, viewportHeight);
476
- if (this.#bandOnEngine(root, camera) || !this.#prepareAnimated()) return;
476
+ if (this.#bandOnEngine(root, camera)) {
477
+ // The engine bands every rig, so the JS rig cache rebuilds nothing: a measured 0, which the kit
478
+ // contract's per-window bound needs, never a missing counter.
479
+ countEngineCost("cullRigRebuilds", 0);
480
+ return;
481
+ }
482
+ if (!this.#prepareAnimated()) return;
477
483
  // Start at each rig and each stand-in that observes one, never at the scene: the walk then visits
478
484
  // the same objects a scene walk would have acted on, and nothing else.
479
485
  const rootShown = this.#isVisibleInWorld(root as Object3D);
package/src/renderer.ts CHANGED
@@ -1340,6 +1340,9 @@ function wrapRenderer(
1340
1340
  prepareTextures: async (textures, signal, onProgress, replacements) => {
1341
1341
  if (disposed) throw new Error("Renderer disposed during texture preparation.");
1342
1342
  if (kind !== "webgpu") return 0;
1343
+ // The owned engine keeps compressed mip bytes in its own heap and uploads them itself: its
1344
+ // texture facade shows no CPU mips, so there is nothing here to stage, and no work to report.
1345
+ if ((raw.info as { engine?: unknown } | undefined)?.engine !== undefined) return 0;
1343
1346
  // Snapshot the caller's iterable once. An owned replacement resolves back to its original,
1344
1347
  // so a repeated call that hands back a published replacement keeps a stable identity instead
1345
1348
  // of looking like an unrelated texture and returning stale work.
@@ -2110,6 +2113,9 @@ export async function createRenderer(options: IRendererOptions = {}): Promise<IR
2110
2113
  // Why WebGPU did not start, when it was tried: the boot failure must name it, or a fault in the
2111
2114
  // WebGPU path (PRD-752: a DOM-only canvas call in a worker) reads as a device without WebGPU.
2112
2115
  let webgpuFailure: string | undefined;
2116
+ // The instance the WebGPU attempt built, held outside the try: a start that failed in `init()`
2117
+ // keeps it, and a facade that failed still holds the page's one renderer slot until it is released.
2118
+ let opening: RendererInstance | undefined;
2113
2119
 
2114
2120
  if (preferWebGPU && (source?.hasWebGPU() ?? "gpu" in (globalThis.navigator ?? {}))) {
2115
2121
  try {
@@ -2125,6 +2131,7 @@ export async function createRenderer(options: IRendererOptions = {}): Promise<IR
2125
2131
  });
2126
2132
  });
2127
2133
  const instance = raw as RendererInstance;
2134
+ opening = instance;
2128
2135
  await instance.init?.();
2129
2136
  // A game that sets `toneMapping` on the renderer later (WorldEnvironment, Daylight) replaces this.
2130
2137
  applyRendererToneMapping(instance, options.toneMapping ?? "filmic", report);
@@ -2149,10 +2156,25 @@ export async function createRenderer(options: IRendererOptions = {}): Promise<IR
2149
2156
  if (adapter.gpuClass !== undefined)
2150
2157
  report(`${GPU_CLASS_MARKER}:${JSON.stringify(adapter.gpuClass)}`);
2151
2158
  } catch (error) {
2152
- // A facade and Wasm engine from two builds is an install fault, not a device without
2153
- // WebGPU: falling back would report TN_NO_RENDERER and hide the fix.
2154
- if (error instanceof Error && error.message.startsWith("TN_WASM_ABI_MISMATCH")) throw error;
2155
- webgpuFailure = error instanceof Error ? error.message : String(error);
2159
+ // Release the page's one slot before anything else: a renderer that failed to start still
2160
+ // holds it, so the next start in this page (a hot reload) threw TN_WASM_RENDERER_SINGLE and
2161
+ // hid this failure.
2162
+ try {
2163
+ opening?.dispose?.();
2164
+ } catch {
2165
+ // A half-started renderer may refuse to release; the fallback still has to be built.
2166
+ }
2167
+ // The engine names its own refusals: a TN_WASM_, TN_NATIVE_ or TN_ABI_ code is a fault in the
2168
+ // game's own code or its install (a background it cannot draw, a facade and Wasm engine from
2169
+ // two builds), and reporting it as a device without WebGPU hides the fix. A device that cannot
2170
+ // start is the one case TN_NO_RENDERER is for, and its reason already rides along in that
2171
+ // message, so the adapter, device, lost device, surface and init codes keep the fallback. The
2172
+ // code ends where its message does, so TN_WASM_INIT_TEXTURE and TN_WASM_DEVICE_ERROR stay the
2173
+ // content faults they are.
2174
+ const message = error instanceof Error ? error.message : String(error);
2175
+ const deviceFault = /^TN_WASM_(?:DEVICE_LOST|DEVICE|ADAPTER|SURFACE|INIT):/u;
2176
+ if (/^TN_(?:WASM|NATIVE|ABI)_/u.test(message) && !deviceFault.test(message)) throw error;
2177
+ webgpuFailure = message;
2156
2178
  renderer = undefined;
2157
2179
  }
2158
2180
  }