@threenative/core 0.3.12 → 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 (150) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +746 -32
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/{canvas-layer-CWuFRT7G.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  5. package/dist/{chunk-7UUT3TY5.js → chunk-4SRAQFTU.js} +1 -1
  6. package/dist/{chunk-GMHATRPW.js → chunk-DIPIJICH.js} +1590 -375
  7. package/dist/{chunk-OKXUCASC.js → chunk-EEABDLUC.js} +3 -4
  8. package/dist/{chunk-5O73CDMR.js → chunk-EFWZWLPY.js} +62 -16
  9. package/dist/{chunk-N5LRP4BR.js → chunk-GYUZJQ7U.js} +63 -3
  10. package/dist/{chunk-VAZM36TV.js → chunk-H4J6IAJE.js} +17 -10
  11. package/dist/{chunk-2Z44XSI2.js → chunk-SV4QVUTQ.js} +3 -7
  12. package/dist/{chunk-DBELTTTM.js → chunk-U4YHUKKL.js} +1 -1
  13. package/dist/chunk-VP43GIWW.js +18 -0
  14. package/dist/{chunk-6KLNISRJ.js → chunk-XDTZ4QMO.js} +11 -4
  15. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  16. package/dist/{game-D7pAzZUY.d.ts → game-k8K3hZai.d.ts} +72 -8
  17. package/dist/hot.d.ts +5 -4
  18. package/dist/hot.js +5 -8
  19. package/dist/index.d.ts +289 -1034
  20. package/dist/index.js +3096 -1305
  21. package/dist/{model-lod-B6BMqS1r.d.ts → model-lod-DPTzeCcD.d.ts} +4 -2
  22. package/dist/playtest.d.ts +5 -4
  23. package/dist/playtest.js +6 -5
  24. package/dist/quality-BYqKGAwo.d.ts +868 -0
  25. package/dist/react.d.ts +3 -2
  26. package/dist/render-environment.d.ts +170 -0
  27. package/dist/render-environment.js +352 -0
  28. package/dist/{renderer-DvFVoAgj.d.ts → renderer-BtOSseYf.d.ts} +29 -31
  29. package/dist/spells/index.js +1 -1
  30. package/dist/ui-layer.js +3 -2
  31. package/dist/worker.js +12 -5
  32. package/dist/world.d.ts +269 -15
  33. package/dist/world.js +1372 -628
  34. package/mcp/animation-server.mjs +1 -1
  35. package/mcp/engine-server.mjs +105 -7
  36. package/mcp/servers.mjs +4 -4
  37. package/package.json +10 -6
  38. package/src/animation-batch.ts +193 -0
  39. package/src/animation-layers.ts +7 -3
  40. package/src/animation.ts +209 -29
  41. package/src/asset-cache.ts +3 -3
  42. package/src/asset-memo.ts +202 -0
  43. package/src/assets.ts +436 -131
  44. package/src/auto-batch.ts +190 -44
  45. package/src/compute-driven.ts +1 -1
  46. package/src/config.ts +8 -0
  47. package/src/debug.ts +103 -22
  48. package/src/dev-global.ts +54 -0
  49. package/src/engine-hooks.ts +37 -0
  50. package/src/frame-budget.ts +19 -3
  51. package/src/game-boot-phase.ts +269 -0
  52. package/src/game-dev-tools.ts +7 -14
  53. package/src/game-frame-loop.ts +45 -82
  54. package/src/game-startup.ts +145 -70
  55. package/src/game-ui.ts +84 -0
  56. package/src/game.ts +168 -552
  57. package/src/gamepad-mappings.ts +269 -0
  58. package/src/generated/console-markers.ts +13 -0
  59. package/src/geometry-capture.ts +28 -4
  60. package/src/gpu-readings.ts +98 -0
  61. package/src/gpu-scene-bvh.ts +149 -36
  62. package/src/hot.ts +4 -7
  63. package/src/index.ts +115 -8
  64. package/src/input.ts +237 -25
  65. package/src/instanced-batch-lod.ts +3 -8
  66. package/src/interpolation.ts +171 -40
  67. package/src/look/ao-admission.ts +4 -3
  68. package/src/look/auto-exposure.ts +5 -16
  69. package/src/look/default-tone-mapping.ts +41 -5
  70. package/src/look/local-exposure.ts +2 -7
  71. package/src/look/quad-pass.ts +21 -0
  72. package/src/look/quality.ts +4 -0
  73. package/src/look/unreal-bloom.ts +4 -13
  74. package/src/look/world-environment.ts +58 -115
  75. package/src/merge-parts.ts +20 -24
  76. package/src/model-lod.ts +97 -14
  77. package/src/particle-significance.ts +12 -0
  78. package/src/particles.ts +19 -10
  79. package/src/platform.ts +23 -4
  80. package/src/profiling/FrameStages.ts +5 -6
  81. package/src/profiling/Spans.ts +3 -17
  82. package/src/profiling/debug-telemetry.ts +2 -6
  83. package/src/profiling/render-list-validate.ts +6 -15
  84. package/src/projection-marker.ts +2 -1
  85. package/src/quiet-markers.ts +3 -10
  86. package/src/render/cpu-bvh.ts +100 -0
  87. package/src/render/depth-pyramid.ts +6 -14
  88. package/src/render/environment/environmentContribution.ts +202 -0
  89. package/src/render/environment/environmentRadiance.ts +44 -0
  90. package/src/render/environment/environmentSampleCache.ts +56 -0
  91. package/src/render/environment/environmentSampling.ts +201 -0
  92. package/src/render/environment/environmentSnapshot.ts +71 -0
  93. package/src/render/environment/gate.ts +57 -0
  94. package/src/render/mesh-pool.ts +3 -19
  95. package/src/render/probe-trace.ts +872 -0
  96. package/src/render/probe-volume.ts +780 -34
  97. package/src/render/radiance-cache.ts +17 -0
  98. package/src/render/virtual-shadow-partial.ts +13 -0
  99. package/src/render/virtual-shadow.ts +18 -16
  100. package/src/render/world-impostor-surface.ts +109 -6
  101. package/src/render/world-impostor.ts +5 -2
  102. package/src/render-camera-cull.ts +98 -3
  103. package/src/render-environment.ts +41 -0
  104. package/src/renderer-config.ts +36 -0
  105. package/src/renderer-facts.ts +37 -0
  106. package/src/renderer.ts +52 -28
  107. package/src/resolution-scaler.ts +3 -2
  108. package/src/scene-entry-inspectors.ts +61 -0
  109. package/src/snow-field.ts +1 -0
  110. package/src/startup-offscreen-bytes.ts +78 -0
  111. package/src/static-transform.ts +25 -19
  112. package/src/streamed-textures.ts +112 -0
  113. package/src/streaming.ts +68 -4
  114. package/src/texture-streaming.ts +331 -0
  115. package/src/version.ts +1 -1
  116. package/src/worker.ts +12 -2
  117. package/src/world-bundle-safety.ts +55 -10
  118. package/src/world-cell-batches.ts +162 -200
  119. package/src/world-cell-chunks.ts +3 -7
  120. package/src/world-cell-impostors.ts +20 -8
  121. package/src/world-cell-options.ts +2 -14
  122. package/src/world-cell-placements.ts +194 -90
  123. package/src/world-cell-prewarm.ts +39 -4
  124. package/src/world-cell-records.ts +401 -0
  125. package/src/world-cell-render-bundles.ts +2 -2
  126. package/src/world-cell-render-gpu-dress.ts +13 -17
  127. package/src/world-cell-render-main-cull.ts +73 -17
  128. package/src/world-cell-render-util.ts +17 -4
  129. package/src/world-cell-render.ts +13 -5
  130. package/src/world-cell-residency.ts +15 -6
  131. package/src/world-cell-stale.ts +238 -0
  132. package/src/world-cells.ts +22 -5
  133. package/src/world-gpu-flags.ts +18 -50
  134. package/src/world-gpu-reference.ts +22 -8
  135. package/src/world-gpu-scene.ts +44 -24
  136. package/src/world-gpu-shadow.ts +21 -8
  137. package/src/world-gpu-types.ts +41 -13
  138. package/src/world-load-limiter.ts +5 -0
  139. package/src/world-model-sections.ts +80 -0
  140. package/src/world-river-ribbon.ts +282 -0
  141. package/src/world-root-frame.ts +39 -0
  142. package/src/world-shore-field.ts +91 -0
  143. package/src/world-static-pose.ts +163 -0
  144. package/src/world-surface-sampler.ts +48 -0
  145. package/src/world-terrain-splat.ts +10 -18
  146. package/src/world-tile-budget.ts +4 -11
  147. package/src/world-tiles.ts +79 -12
  148. package/src/world-validate.ts +6 -14
  149. package/src/world-warm.ts +51 -0
  150. package/src/world.ts +13 -0
@@ -3,6 +3,7 @@ import {
3
3
  BufferGeometry,
4
4
  Group,
5
5
  InstancedMesh,
6
+ type Material,
6
7
  Matrix3,
7
8
  Matrix4,
8
9
  Mesh,
@@ -14,6 +15,8 @@ import * as upstreamWebGPU from "three-mesh-bvh/webgpu";
14
15
  import { storage } from "three/tsl";
15
16
  import { StorageBufferAttribute, type StorageBufferNode, type StructTypeNode } from "three/webgpu";
16
17
  import type { IComputeDriven } from "./compute-driven.js";
18
+ import { buildCpuBvh } from "./render/cpu-bvh.js";
19
+ import type { IProbeTraceScene } from "./render/probe-trace.js";
17
20
  import type { IRendererLike } from "./renderer.js";
18
21
 
19
22
  /** Selects the meshes that become part of a GPU trace set. */
@@ -50,21 +53,26 @@ interface IPackedScene {
50
53
  readonly geometry: BufferGeometry;
51
54
  readonly indices: Uint32Array;
52
55
  readonly materialGroups: readonly IGPUSceneBVHMaterialGroup[];
56
+ readonly materials: readonly Material[];
53
57
  readonly nodes: Uint32Array;
54
58
  readonly normals: Float32Array;
55
59
  readonly objectCount: number;
56
60
  readonly positions: Float32Array;
57
61
  readonly triangleCount: number;
62
+ readonly triangleMaterials: Uint32Array;
58
63
  readonly vertexCount: number;
59
64
  }
60
65
 
61
66
  interface IBuildState {
62
67
  indices: number[];
68
+ /** One slot per distinct Material, in first-seen order: the trace's material table. */
69
+ materialSlots: Map<Material, number>;
63
70
  normals: number[];
64
71
  objectCount: number;
65
72
  positions: number[];
66
73
  triangleCount: number;
67
74
  triangleMaterials: number[];
75
+ triangleSlots: number[];
68
76
  }
69
77
 
70
78
  interface IRange {
@@ -207,7 +215,19 @@ function padVec3(array: Float32Array): Float32Array {
207
215
  return padded;
208
216
  }
209
217
 
218
+ function materialSlot(mesh: Mesh, materialIndex: number, state: IBuildState): number {
219
+ const material = Array.isArray(mesh.material) ? mesh.material[materialIndex] : mesh.material;
220
+ if (material === undefined) return 0;
221
+ let slot = state.materialSlots.get(material);
222
+ if (slot === undefined) {
223
+ slot = state.materialSlots.size;
224
+ state.materialSlots.set(material, slot);
225
+ }
226
+ return slot;
227
+ }
228
+
210
229
  function appendTriangles(
230
+ mesh: Mesh,
211
231
  index: ReturnType<BufferGeometry["getIndex"]>,
212
232
  ranges: readonly IRange[],
213
233
  vertexOffset: number,
@@ -219,8 +239,10 @@ function appendTriangles(
219
239
  state.indices.push(vertexOffset + sourceIndex);
220
240
  }
221
241
  const triangles = range.count / 3;
242
+ const slot = materialSlot(mesh, range.materialIndex, state);
222
243
  for (let triangle = 0; triangle < triangles; triangle += 1) {
223
244
  state.triangleMaterials.push(range.materialIndex);
245
+ state.triangleSlots.push(slot);
224
246
  }
225
247
  state.triangleCount += triangles;
226
248
  }
@@ -242,7 +264,7 @@ function appendMesh(mesh: Mesh, state: IBuildState): void {
242
264
  matrixFor(mesh, instance, matrix);
243
265
  normalMatrix.getNormalMatrix(matrix);
244
266
  appendVertices(mesh, position, normal, matrix, normalMatrix, state);
245
- appendTriangles(index, ranges, vertexOffset, state);
267
+ appendTriangles(mesh, index, ranges, vertexOffset, state);
246
268
  }
247
269
  }
248
270
 
@@ -267,32 +289,66 @@ function materialGroupsFor(materials: Uint32Array): IGPUSceneBVHMaterialGroup[]
267
289
  * it, so a leaf's triangle offset and the material ranges address the same layout.
268
290
  */
269
291
  function permuteToLeafOrder(
270
- bvh: MeshBVH,
292
+ resolveTriangleIndex: (slot: number) => number,
271
293
  sourceIndices: Uint32Array,
272
294
  sourceMaterials: readonly number[],
273
- ): { indices: Uint32Array; materialGroups: IGPUSceneBVHMaterialGroup[] } {
295
+ sourceSlots: readonly number[],
296
+ ): { indices: Uint32Array; materialGroups: IGPUSceneBVHMaterialGroup[]; slots: Uint32Array } {
274
297
  const triangleCount = sourceIndices.length / 3;
275
298
  const indices = new Uint32Array(sourceIndices.length);
276
299
  const materials = new Uint32Array(triangleCount);
300
+ const slots = new Uint32Array(triangleCount);
277
301
  for (let slot = 0; slot < triangleCount; slot += 1) {
278
- const triangle = bvh.resolveTriangleIndex(slot);
302
+ const triangle = resolveTriangleIndex(slot);
279
303
  indices[slot * 3] = sourceIndices[triangle * 3] ?? 0;
280
304
  indices[slot * 3 + 1] = sourceIndices[triangle * 3 + 1] ?? 0;
281
305
  indices[slot * 3 + 2] = sourceIndices[triangle * 3 + 2] ?? 0;
282
306
  materials[slot] = sourceMaterials[triangle] ?? 0;
307
+ slots[slot] = sourceSlots[triangle] ?? 0;
308
+ }
309
+ return { indices, materialGroups: materialGroupsFor(materials), slots };
310
+ }
311
+
312
+ /**
313
+ * The BVH nodes and leaf order. Upstream `MeshBVH` builds them where it builds a tree; the owned engine's
314
+ * `MeshBVH` refuses the build options and holds no tree, so a CPU build (`render/cpu-bvh.ts`) stands in.
315
+ */
316
+ function buildNodes(
317
+ geometry: BufferGeometry,
318
+ positions: Float32Array,
319
+ indices: Uint32Array,
320
+ ): { nodes: Uint32Array; resolveTriangleIndex: (slot: number) => number } {
321
+ try {
322
+ const bvh = new MeshBVH(geometry, {
323
+ indirect: true,
324
+ strategy: SAH,
325
+ targetLeafSize: 10,
326
+ verbose: false,
327
+ });
328
+ const root = MeshBVH.serialize(bvh, { cloneBuffers: false }).roots[0];
329
+ if (root === undefined) throw new Error("GPUSceneBVH could not serialize its root node.");
330
+ return {
331
+ nodes: new Uint32Array(root),
332
+ resolveTriangleIndex: (slot) => bvh.resolveTriangleIndex(slot),
333
+ };
334
+ } catch (error) {
335
+ if (!String((error as Error).message).includes("TN_NATIVE_MESH_BVH")) throw error;
336
+ const built = buildCpuBvh(positions, indices);
337
+ return { nodes: built.nodes, resolveTriangleIndex: (slot) => built.order[slot] as number };
283
338
  }
284
- return { indices, materialGroups: materialGroupsFor(materials) };
285
339
  }
286
340
 
287
341
  function packScene(scene: Object3D, include: (object: Mesh) => boolean): IPackedScene {
288
342
  scene.updateMatrixWorld(true);
289
343
  const state: IBuildState = {
290
344
  indices: [],
345
+ materialSlots: new Map(),
291
346
  normals: [],
292
347
  objectCount: 0,
293
348
  positions: [],
294
349
  triangleCount: 0,
295
350
  triangleMaterials: [],
351
+ triangleSlots: [],
296
352
  };
297
353
  scene.traverse((candidate) => {
298
354
  if (!(candidate instanceof Mesh) || candidate.visible === false || !include(candidate)) return;
@@ -313,32 +369,33 @@ function packScene(scene: Object3D, include: (object: Mesh) => boolean): IPacked
313
369
  let nodes = emptyNodes();
314
370
  let indices: Uint32Array = sourceIndices;
315
371
  let materialGroups: readonly IGPUSceneBVHMaterialGroup[] = [];
372
+ let triangleMaterials: Uint32Array = new Uint32Array(state.triangleSlots);
316
373
  if (state.indices.length > 0) {
317
374
  // Indirect keeps `geometry.index` in source order, so the material assignment collected above
318
375
  // still lines up with it; the leaf order is then applied to both at once below.
319
- const bvh = new MeshBVH(geometry, {
320
- indirect: true,
321
- strategy: SAH,
322
- targetLeafSize: 10,
323
- verbose: false,
324
- });
325
- const serialized = MeshBVH.serialize(bvh, { cloneBuffers: false });
326
- const root = serialized.roots[0];
327
- if (root === undefined) throw new Error("GPUSceneBVH could not serialize its root node.");
328
- nodes = new Uint32Array(root);
329
- const permuted = permuteToLeafOrder(bvh, sourceIndices, state.triangleMaterials);
376
+ const built = buildNodes(geometry, tightPositions, sourceIndices);
377
+ nodes = built.nodes;
378
+ const permuted = permuteToLeafOrder(
379
+ built.resolveTriangleIndex,
380
+ sourceIndices,
381
+ state.triangleMaterials,
382
+ state.triangleSlots,
383
+ );
330
384
  indices = permuted.indices;
331
385
  materialGroups = permuted.materialGroups;
386
+ triangleMaterials = permuted.slots;
332
387
  }
333
388
  return {
334
389
  geometry,
335
390
  indices,
336
391
  materialGroups,
392
+ materials: [...state.materialSlots.keys()],
337
393
  nodes,
338
394
  normals,
339
395
  objectCount: state.objectCount,
340
396
  positions,
341
397
  triangleCount: state.triangleCount,
398
+ triangleMaterials,
342
399
  vertexCount: tightPositions.length / 3,
343
400
  };
344
401
  }
@@ -353,17 +410,23 @@ function packScene(scene: Object3D, include: (object: Mesh) => boolean): IPacked
353
410
  */
354
411
  export class GPUSceneBVH extends Group implements IComputeDriven {
355
412
  #backings: INodeBackings = {
356
- indices: readStorage(new Uint32Array([0, 0, 0]), "uvec3", 3),
357
- nodes: readNodeStorage(emptyNodes()),
358
- normals: readStorage(new Float32Array([0, 1, 0, 0]), "vec3", 4),
359
- positions: readStorage(new Float32Array([0, 0, 0, 0]), "vec3", 4),
413
+ // Each backing is built on first read: the owned engine refuses the upstream node struct and
414
+ // freezes storage nodes, and the probe trace (`traceScene`) needs none of them.
415
+ indices: null,
416
+ nodes: null,
417
+ normals: null,
418
+ positions: null,
419
+ };
420
+ #packedStorage: { indices: Uint32Array; normals: Float32Array; positions: Float32Array } = {
421
+ indices: new Uint32Array([0, 0, 0]),
422
+ normals: new Float32Array([0, 1, 0, 0]),
423
+ positions: new Float32Array([0, 0, 0, 0]),
360
424
  };
361
- readonly indices: StorageBufferNode<"uvec3">;
362
- readonly nodes: StorageBufferNode<"struct">;
363
- readonly normals: StorageBufferNode<"vec3">;
364
- readonly positions: StorageBufferNode<"vec3">;
365
425
  readonly warmupNodes: readonly unknown[] = [];
366
426
  #buildMs = 0;
427
+ #packedNodes: Uint32Array = emptyNodes();
428
+ #traceScene: IProbeTraceScene | undefined;
429
+ #version = 0;
367
430
  #include: (object: Mesh) => boolean;
368
431
  #materialGroups: readonly IGPUSceneBVHMaterialGroup[] = [];
369
432
  #objectCount = 0;
@@ -381,14 +444,50 @@ export class GPUSceneBVH extends Group implements IComputeDriven {
381
444
  }
382
445
  this.#scene = scene;
383
446
  this.#include = options.include ?? (() => true);
384
- this.nodes = this.#backings.nodes as StorageBufferNode<"struct">;
385
- this.positions = this.#backings.positions as StorageBufferNode<"vec3">;
386
- this.indices = this.#backings.indices as StorageBufferNode<"uvec3">;
387
- this.normals = this.#backings.normals as StorageBufferNode<"vec3">;
388
447
  this.addEventListener("removed", this.#onRemoved);
389
448
  this.rebuild();
390
449
  }
391
450
 
451
+ /** Packed triangle indices as a storage node, built on first read. */
452
+ get indices(): StorageBufferNode<"uvec3"> {
453
+ if (this.#released) throw new Error("GPUSceneBVH indices were read after release.");
454
+ this.#backings.indices ??= readStorage(this.#packedStorage.indices, "uvec3", 3);
455
+ return this.#backings.indices;
456
+ }
457
+
458
+ /** Packed vertex normals as a storage node, built on first read. */
459
+ get normals(): StorageBufferNode<"vec3"> {
460
+ if (this.#released) throw new Error("GPUSceneBVH normals were read after release.");
461
+ this.#backings.normals ??= readStorage(this.#packedStorage.normals, "vec3", 4);
462
+ return this.#backings.normals;
463
+ }
464
+
465
+ /** Packed world-space vertex positions as a storage node, built on first read. */
466
+ get positions(): StorageBufferNode<"vec3"> {
467
+ if (this.#released) throw new Error("GPUSceneBVH positions were read after release.");
468
+ this.#backings.positions ??= readStorage(this.#packedStorage.positions, "vec3", 4);
469
+ return this.#backings.positions;
470
+ }
471
+
472
+ /** The upstream TSL query's node table, built on first read. */
473
+ get nodes(): StorageBufferNode<"struct"> {
474
+ if (this.#released) throw new Error("GPUSceneBVH nodes were read after release.");
475
+ this.#backings.nodes ??= readNodeStorage(this.#packedNodes);
476
+ return this.#backings.nodes;
477
+ }
478
+
479
+ /** The CPU snapshot in leaf order, with one material slot per triangle: what `RadianceCache` traces. */
480
+ get traceScene(): IProbeTraceScene {
481
+ if (this.#traceScene === undefined)
482
+ throw new Error("GPUSceneBVH has no snapshot after release.");
483
+ return this.#traceScene;
484
+ }
485
+
486
+ /** Increments on every rebuild, so a consumer of `traceScene` knows to re-upload. */
487
+ get version(): number {
488
+ return this.#version;
489
+ }
490
+
392
491
  get buildMs(): number {
393
492
  return this.#buildMs;
394
493
  }
@@ -426,14 +525,27 @@ export class GPUSceneBVH extends Group implements IComputeDriven {
426
525
  if (this.#released) throw new Error("GPUSceneBVH cannot rebuild after release.");
427
526
  const started = now();
428
527
  const packed = packScene(this.#scene, this.#include);
429
- const nextNodes = readNodeStorage(packed.nodes);
430
- const nextPositions = readStorage(packed.positions, "vec3", 4);
431
- const nextIndices = readStorage(packed.indices, "uvec3", 3);
432
- const nextNormals = readStorage(packed.normals, "vec3", 4);
433
- replaceStorage(this.#backings.nodes as StorageBufferNode<"struct">, nextNodes);
434
- replaceStorage(this.#backings.positions as StorageBufferNode<"vec3">, nextPositions);
435
- replaceStorage(this.#backings.indices as StorageBufferNode<"uvec3">, nextIndices);
436
- replaceStorage(this.#backings.normals as StorageBufferNode<"vec3">, nextNormals);
528
+ this.#packedNodes = packed.nodes;
529
+ if (this.#backings.nodes !== null) {
530
+ replaceStorage(this.#backings.nodes, readNodeStorage(packed.nodes));
531
+ }
532
+ this.#traceScene = {
533
+ indices: packed.indices,
534
+ materials: packed.materials,
535
+ nodes: packed.nodes,
536
+ positions: packed.positions,
537
+ triangleMaterials: packed.triangleMaterials,
538
+ };
539
+ this.#version += 1;
540
+ this.#packedStorage = {
541
+ indices: packed.indices,
542
+ normals: packed.normals,
543
+ positions: packed.positions,
544
+ };
545
+ const { positions, indices, normals } = this.#backings;
546
+ if (positions !== null) replaceStorage(positions, readStorage(packed.positions, "vec3", 4));
547
+ if (indices !== null) replaceStorage(indices, readStorage(packed.indices, "uvec3", 3));
548
+ if (normals !== null) replaceStorage(normals, readStorage(packed.normals, "vec3", 4));
437
549
  this.#packedGeometry?.dispose();
438
550
  this.#packedGeometry = packed.geometry;
439
551
  this.#materialGroups = packed.materialGroups;
@@ -457,6 +569,7 @@ export class GPUSceneBVH extends Group implements IComputeDriven {
457
569
  this.#backings.normals = null;
458
570
  this.#packedGeometry?.dispose();
459
571
  this.#packedGeometry = undefined;
572
+ this.#traceScene = undefined;
460
573
  this.#released = true;
461
574
  }
462
575
 
package/src/hot.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /// <reference path="./import-meta.d.ts" />
2
2
 
3
3
  import { audioRuntimeSnapshot } from "./audio.js";
4
+ import { devGlobal, publishDevGlobal } from "./dev-global.js";
4
5
  import type { IGame } from "./game.js";
5
6
  import { hostDocument, hostWindow } from "./platform.js";
6
7
  export interface IHotDiagnostics {
@@ -66,13 +67,9 @@ export function acceptHotUpdate<TState extends Record<string, unknown>, TPhysics
66
67
  }
67
68
  const page = hostWindow();
68
69
  if (isDev && page !== undefined) {
69
- const host = page as unknown as Record<string, unknown> &
70
- Partial<Record<"__THREENATIVE__", Record<string, unknown> & { hot?: () => IHotDiagnostics }>>;
71
- host.__THREENATIVE__ = {
72
- ...host.__THREENATIVE__,
73
- hot: () => diagnostics(game, reloads),
74
- snapshot: host.__THREENATIVE__?.snapshot ?? (() => ({})),
75
- };
70
+ publishDevGlobal("hot", () => diagnostics(game, reloads), page);
71
+ // The overlay reads a snapshot even before the game has one: an empty object, never undefined.
72
+ if (devGlobal(page)?.snapshot === undefined) publishDevGlobal("snapshot", () => ({}), page);
76
73
  }
77
74
  let disposed = false;
78
75
  hot.dispose((data) => {
package/src/index.ts CHANGED
@@ -1,12 +1,15 @@
1
1
  /**
2
2
  * The version this library reports.
3
3
  *
4
- * It read `0.1.0` while the package published `0.2.0`, and `__tests__/build.spec.ts` asserted the
5
- * stale literal, so the test held the bug in place rather than catching it. A literal is
6
- * unavoidable here — core is bundled for browsers and cannot read `package.json` at runtime — so
7
- * the spec now asserts this equals the manifest instead of asserting a number somebody typed.
4
+ * `version.ts` is the one owner, generated from `package.json` at build time. Declared here rather
5
+ * than re-exported under another name: the native engine's bundler reads this barrel for the
6
+ * bindings a game may import, and `export { CORE_VERSION as version } from …` gave it a name the
7
+ * module does not export, refusing every game that stamps the version into its HUD
8
+ * (`TN_NATIVE_ENGINE_UNBOUND`).
8
9
  */
9
- export const version = "0.3.12";
10
+ import { CORE_VERSION } from "./version.js";
11
+
12
+ export const version = CORE_VERSION;
10
13
 
11
14
  /**
12
15
  * Play a skinned or sprite animation from game code.
@@ -144,16 +147,48 @@ export type { CameraShakeCurve, ICameraShakeOffset, ICameraShakeOptions } from "
144
147
  * @situation free the disk cache from a settings menu
145
148
  * @situation prefetch assets into the Cache Storage disk cache of a large web game
146
149
  * @situation load assets from a nonstandard base path or a compiled asset manifest
150
+ * @situation stream a large game: boot on the spawn bytes and prefetch the rest
151
+ * @situation make the first scene play before the whole game finishes downloading
152
+ * @situation draw a heavy model's coarsest level first and its full detail when the file lands
153
+ * @situation draw a model's textures at their resident mips first and the whole files later
147
154
  * @alias different area props
155
+ * @situation coarse first model streaming
156
+ * @situation streamMeshes and streamTextures: stream the meshes and textures of a model
157
+ * @situation mip streaming textures
158
+ * @situation TN_STREAMING_POOL
159
+ * @situation TN_ASSET_LATE
148
160
  * @alias first playable screen external assets
161
+ * @situation an asset pops in after the reveal and the game needs to count it
162
+ * @situation a model texture looks blurry or low resolution right after load, then sharpens
163
+ * @situation build a collider or navmesh from a streamed model only once its full file landed
149
164
  * @constraint reuse the loader handed to scenes as `ctx.assets` instead of building parallel caches
150
165
  * @constraint await everything the spawn camera sees before the reveal; `ctx.assets.prefetch` and the background fill are for content out of view, or the player spawns into a half-built world
166
+ * @constraint a whole-file load requested after the reveal that the game had not `prefetch`ed logs one `TN_ASSET_LATE` line with its bytes, so a pop-in is countable from a playtest
151
167
  * @constraint web only: a native host reads installed files, so `ctx.assets.cache` reports `enabled: false` with the reason and `prefetch` resolves at once
168
+ * @constraint streaming is engine-owned and on by default: a cooked LOD-chained model loads its `.coarse.<digest>.glb` companion first, then the full file at "soon" priority, and the full geometry replaces the coarse in place (clones and the projection mirror included); a failed coarse load falls back to the whole file and logs `TN_ASSETS_STREAM_FAILED`
169
+ * @constraint texture streaming rides on the coarse parse: each shared `.ktx2` of that model is read by `Range` as its resident mips (the header and the tail), and the whole files replace them when the full model lands; a host without `Range` sends the whole file and keeps it whole. `TN_STREAMING_POOL` reports `files`, `residentBytes`, `fullBytes`, `deferredBytes` and `upgraded` once, two seconds after the last change
152
170
  * @override `assets.cache: false` turns the disk cache off and `assets.backgroundFill: false` turns the post-reveal fill off; both are reported on `ctx.assets.cache`
171
+ * @constraint the whole texture keeps what the game set on the resident one (`anisotropy`, wrap, filters, offset, repeat, `userData`), so the swap changes the mips and nothing else
172
+ * @override `ctx.assets.model(path, { whole: true })` resolves only once the full file has replaced the coarse companion, for a collider or navmesh that copies vertices once
173
+ * @override `assets.streamMeshes: false` loads every model whole (reported once as `TN_ASSETS_STREAM_MESHES_OFF`); `assets.streamTextures: false` loads every model texture whole (`TN_ASSETS_STREAM_TEXTURES_OFF`)
174
+ * @situation compressed texture upload on the owned engine (KTX2 to BC7 or ETC2 on the GPU)
175
+ * @situation load a model with KHR_texture_basisu or EXT_meshopt_compression on the owned engine
176
+ * @situation stream a finer mip level into a CompressedTexture that already draws
177
+ * @situation KTX2Loader on the owned engine
178
+ * @situation CompressedTexture upload
179
+ * @situation TN_TEXTURE_TRANSCODE_TARGET
180
+ * @situation TN_NATIVE_TEXTURE_UNSUPPORTED
181
+ * @situation webRuntimeDecoders meshopt ktx2
182
+ * @constraint every web build cooks meshopt geometry and KTX2 textures for both engines (`webRuntimeDecoders` in create-threenative answers `{ ktx2: true, meshopt: true }`); the owned engine's glTF loader decodes both itself, with no JS decoder
183
+ * @constraint the owned engine transcodes a KTX2 image to BC7 on a device with `texture-compression-bc`, else ETC2, else RGBA8 with an engine mip chain, and prints `TN_TEXTURE_TRANSCODE_TARGET <target>` once; a block format needs a width and height that are multiples of 4, so any other size stays RGBA8 and the same line names it
184
+ * @constraint a three `CompressedTexture` (format plus `mipmaps`) uploads one GPU write per level; a block format the device lacks throws `TN_NATIVE_TEXTURE_UNSUPPORTED` by name instead of drawing garbage
185
+ * @constraint levels are coarse-first: a level whose `mipmaps[i].data` is null is not resident and the texture samples its finest resident level; set `mipmaps[i].data` and `needsUpdate = true` to write that one finer level in place, without re-creating the texture or rewriting the other levels
186
+ * @override `engine: "threejs"` runs three's own `KTX2Loader` and `MeshoptDecoder` in JS instead of the owned engine's decoders
153
187
  * @example const assets = createAssetLoader({ basePath: "/assets" });
154
188
  * const rock = await assets.texture("rock.png");
155
189
  */
156
- export { createAssetLoader } from "./assets.js";
190
+ export { ASSET_LATE_MARKER, createAssetLoader } from "./assets.js";
191
+ export { fetchAsset } from "./assets.js";
157
192
  export { onLaunchFailure } from "./launch-diagnostics.js";
158
193
  export { resetAudioCueLedger } from "./audio.js";
159
194
  export type { ILaunchFailure, LaunchFailureKind } from "./launch-diagnostics.js";
@@ -414,7 +449,7 @@ export { mergeByMaterial } from "./merge-parts.js";
414
449
  export type { IMergeByMaterialOptions } from "./merge-parts.js";
415
450
  /**
416
451
  * Read a debug switch from the URL, or from `TN_DEBUG_*` in the environment on a native launch.
417
- * @situation read a debug toggle from the URL or an environment variable
452
+ * @situation read a debug toggle from the URL, an environment variable or a harness global
418
453
  * @constraint a name in camelCase becomes UPPER_SNAKE: `debugFlag("freeCam")` reads `?freeCam` or `TN_DEBUG_FREE_CAM`
419
454
  * @constraint `0` and `false` are off, so a saved URL cannot turn a switch back on
420
455
  * @example import { debugFlag } from "@threenative/core";
@@ -430,6 +465,20 @@ export { debugFlag } from "./debug.js";
430
465
  * // then from the console: __THREENATIVE__.debug.player
431
466
  */
432
467
  export { exposeDebug } from "./debug.js";
468
+ /**
469
+ * The one name every dev surface publishes under, and the reader/writer for it.
470
+ * @situation read or extend the `__THREENATIVE__` object a dev launch publishes
471
+ * @constraint every dev surface publishes under this key; the worker's typed mirror tuple names it too
472
+ * @example import { DEV_GLOBAL_KEY, devGlobal } from "@threenative/core";
473
+ * const tools = devGlobal(globalThis);
474
+ */
475
+ export {
476
+ DEV_GLOBAL_KEY,
477
+ type DevGlobal,
478
+ type IDevTools,
479
+ devGlobal,
480
+ publishDevGlobal,
481
+ } from "./dev-global.js";
433
482
  /**
434
483
  * Draw a model too detailed for the screen to resolve, without submitting the part it cannot.
435
484
  *
@@ -536,6 +585,19 @@ export {
536
585
  * @example const geometry = baseGeometryOf(mesh);
537
586
  */
538
587
  export { baseGeometryOf } from "./model-lod.js";
588
+ /**
589
+ * True while a geometry is the coarse companion a streamed model draws first (PRD-860), before its
590
+ * full file replaces it in place. A caller that copies vertices (a trimesh collider, a navmesh bake,
591
+ * a merge) waits with `ctx.assets.model(path, { whole: true })` instead of copying the coarse ones.
592
+ *
593
+ * @situation collider or navmesh built from a model is coarser than what is drawn
594
+ * @situation wait for the full model before copying its vertices
595
+ * @situation whole model before collision
596
+ * @situation TN_COLLIDER_COARSE
597
+ * @constraint `CollisionShape3D.fromMesh` with "trimesh" or "convexHull" on a streamed geometry warns `TN_COLLIDER_COARSE` naming the mesh and the `{ whole: true }` override, and still builds
598
+ * @example const coarse = isStreamedGeometry(mesh.geometry);
599
+ */
600
+ export { isStreamedGeometry } from "./model-lod.js";
539
601
  /**
540
602
  * The cooked automatic LOD chain (`TN_discrete_lod`) a loaded geometry carries, or `undefined`.
541
603
  *
@@ -1041,6 +1103,26 @@ export {
1041
1103
  PROBE_VOLUME_MARKER,
1042
1104
  ProbeVolume,
1043
1105
  } from "./render/probe-volume.js";
1106
+ /**
1107
+ * A probe field of diffuse irradiance that refreshes by tracing the packed scene, with no scene draw: the
1108
+ * radiance cache of a dynamic global-illumination pass. Probes in view refresh first, oldest first, within
1109
+ * `numProbesToTraceBudget` a frame; a lamp toggled in game code or a sun that steps more than one degree
1110
+ * re-traces them while the old values keep lighting the frame.
1111
+ * @situation light follows a lamp that switches on and off in a room
1112
+ * @situation bounce light that updates when the sun moves, with no baked lightmap
1113
+ * @situation global illumination that refreshes fast enough to read as dynamic
1114
+ * @alias lumen radiance cache
1115
+ * @alias radiance cache
1116
+ * @alias irradiance field
1117
+ * @alias dynamic probe gi
1118
+ * @constraint build a GPUSceneBVH of the static meshes first and pass it as trace.bvh; the cache reads colour and emissive from each material, a texture or a node is counted as ignored
1119
+ * @constraint add the cache with ctx.add() so its refresh is measured in the render phase, and read it with sampleNode(position, normal) from a game-owned material
1120
+ * @constraint a one-sided material is not seen from behind, as a cube capture would not draw it
1121
+ * @override numProbesToTraceBudget (100), probeResolution (8, so 64 rays a probe; 32 for a small emitter), bounds, density, bounces and the sun and sky values are game-owned
1122
+ * @example const bvh = new GPUSceneBVH(ctx.scene); ctx.add(bvh); const cache = new RadianceCache({ bounds, density: 0.5, trace: { bvh, sun, sky, camera: ctx.camera } }); ctx.add(cache);
1123
+ */
1124
+ export { RadianceCache } from "./render/radiance-cache.js";
1125
+ export type { IRadianceCacheOptions } from "./render/radiance-cache.js";
1044
1126
  /**
1045
1127
  * The Surface Cache: what a traced global-illumination ray reads where it hits a surface. A material atlas
1046
1128
  * (base colour and emissive maps reduced to small tiles) answers the albedo and the glow at the hit UV; a flat
@@ -1657,9 +1739,19 @@ export type {
1657
1739
  * @constraint image ray tracing is unavailable on native until buffer-to-texture copy-out interop exists; `mystralRT.traceRays` refuses instead of resolving success without a readable result
1658
1740
  * @constraint a native desktop host with ray tracing hardware traces ray batches with `mystralRT.traceRayBatch`, which writes hit records into a typed array you own; read `mystralRT.capabilities().rayBatch` first, and keep the software BVH trace for the web and every other host
1659
1741
  * @constraint when `mystralRT.capabilities().sharedTransport` is true, `mystralRT.traceRayBatchGpu({ tlas, rays, hits, rayCount })` traces between two GPUBuffers with no copy through CPU memory; `rays` needs the CopySrc usage and `hits` the CopyDst usage, and each call costs CPU time, so measure it against the software trace for your batch size
1742
+ * @situation show gamepad prompts and bind pad buttons on a games console such as the PS4
1660
1743
  * @example if (isMobile()) showTouchControls();
1744
+ * @example if (isConsole()) showPadPrompts(isPs4() ? "dualshock" : "generic");
1661
1745
  */
1662
- export { getPlatform, isMobile, isNative, isTouchscreenAvailable, isWeb } from "./platform.js";
1746
+ export {
1747
+ getPlatform,
1748
+ isConsole,
1749
+ isMobile,
1750
+ isNative,
1751
+ isPs4,
1752
+ isTouchscreenAvailable,
1753
+ isWeb,
1754
+ } from "./platform.js";
1663
1755
  export type {
1664
1756
  IPlatformInfo,
1665
1757
  PlatformFormFactor,
@@ -1896,6 +1988,7 @@ export type {
1896
1988
  ContextMenuPolicy,
1897
1989
  IInputAction,
1898
1990
  IInputGamepad,
1991
+ IInputMapOptions,
1899
1992
  InputBindings,
1900
1993
  InputPlatformSource,
1901
1994
  IRawInputPointer,
@@ -1913,8 +2006,22 @@ export type {
1913
2006
  * @situation map WASD keys to a movement axis instead of reading the held key set in the update loop
1914
2007
  * @situation read a jump, a fire or a reload as one named action bound to key, gamepad button and mouse button together
1915
2008
  * @situation read mouse look, wheel zoom or a two-finger pinch as an axis the frame loop already ticks
2009
+ * @situation support an Xbox pad, a generic XInput clone, an 8BitDo or a Steam Deck controller
2010
+ * @situation the character drifts while the controller stick is idle
2011
+ * @situation the controller does nothing in Firefox on Linux
2012
+ * @situation a second controller or a wheel steals the input from the pad the player holds
2013
+ * @alias gamepad
2014
+ * @alias controller
2015
+ * @alias joypad
2016
+ * @alias xbox
2017
+ * @alias 8bitdo
2018
+ * @alias steam deck
1916
2019
  * @constraint `buttons` is the gamepad and `mouseButtons` the mouse; `up`/`down`/`left`/`right` are the directions of `vector(name)`, not the keys that press it
1917
2020
  * @constraint scroll, pinch and pointer-relative sources are declared on the binding and read through `axis(name)`; a game adds no window listener of its own
2021
+ * @constraint gamepad buttons are W3C standard indices on every pad: 0 south (A/Cross), 1 east, 2 west, 3 north, 4/5 shoulders, 6/7 triggers, 8 select, 9 start, 10/11 stick clicks; axes 0..3 are the sticks
2022
+ * @constraint both sticks carry a radial dead zone, `0.2` by default, reported per connected pad as `TN_GAMEPAD`; a pad the browser reports unmapped and the table does not know is ignored, never read with raw indices
2023
+ * @constraint a pad claims the input when a button goes down or a stick travels past half tilt, and keeps it while idle so its releases read; a stick resting past the dead zone or jittering across it claims nothing, so an idle pad in the first slot cannot steal input
2024
+ * @override defineGame({ gamepadDeadZone: 0 }) publishes raw axes
1918
2025
  * @example const game = defineGame({ input: { move: { up: ["KeyW"], down: ["KeyS"], left: ["KeyA"], right: ["KeyD"] } }, scenes: { Play } });
1919
2026
  * // inside the scene, per frame: ctx.input.axis("move") is 0 at rest and 1 at full tilt
1920
2027
  */