@threenative/core 0.3.11 → 0.3.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (236) hide show
  1. package/README.md +1 -1
  2. package/capabilities.json +1988 -204
  3. package/dist/{assets-YUbXa3-Y.d.ts → assets-CfMKnOsK.d.ts} +78 -1
  4. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  5. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-G7ttVy7y.d.ts} +1 -1
  6. package/dist/chunk-4SRAQFTU.js +133 -0
  7. package/dist/chunk-CFGTPFUH.js +231 -0
  8. package/dist/chunk-DIPIJICH.js +8916 -0
  9. package/dist/chunk-EEABDLUC.js +2237 -0
  10. package/dist/chunk-EFWZWLPY.js +1895 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-GYUZJQ7U.js +280 -0
  13. package/dist/chunk-H4J6IAJE.js +504 -0
  14. package/dist/chunk-KIRUKTBQ.js +187 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-SV4QVUTQ.js +31 -0
  17. package/dist/chunk-U4YHUKKL.js +615 -0
  18. package/dist/chunk-VP43GIWW.js +18 -0
  19. package/dist/chunk-XDTZ4QMO.js +160 -0
  20. package/dist/default-tone-mapping-GgKPTiBP.d.ts +4 -0
  21. package/dist/{game-DzMcitDO.d.ts → game-k8K3hZai.d.ts} +85 -9
  22. package/dist/hot.d.ts +5 -4
  23. package/dist/hot.js +5 -52
  24. package/dist/index.d.ts +633 -1351
  25. package/dist/index.js +12873 -23068
  26. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-DPTzeCcD.d.ts} +35 -3
  27. package/dist/playtest.d.ts +5 -4
  28. package/dist/playtest.js +25 -75
  29. package/dist/quality-BYqKGAwo.d.ts +868 -0
  30. package/dist/react-css.js +1 -215
  31. package/dist/react.d.ts +3 -2
  32. package/dist/render-environment.d.ts +170 -0
  33. package/dist/render-environment.js +352 -0
  34. package/dist/{renderer-rZm0hVqq.d.ts → renderer-BtOSseYf.d.ts} +42 -35
  35. package/dist/spells/index.d.ts +643 -0
  36. package/dist/spells/index.js +1558 -0
  37. package/dist/spells/ultra/index.d.ts +1600 -0
  38. package/dist/spells/ultra/index.js +6804 -0
  39. package/dist/terrain-jobs-worker.js +1 -123
  40. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  41. package/dist/ui-layer.js +6 -384
  42. package/dist/worker.js +13 -43
  43. package/dist/world.d.ts +988 -268
  44. package/dist/world.js +17464 -18290
  45. package/mcp/animation-server.mjs +1 -1
  46. package/mcp/animation.mjs +2 -3
  47. package/mcp/engine-server.mjs +245 -52
  48. package/mcp/servers.mjs +10 -3
  49. package/mcp/terrain.mjs +8 -0
  50. package/package.json +19 -7
  51. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  52. package/patches/three@0.187.0.patch +2004 -407
  53. package/src/animation-batch.ts +193 -0
  54. package/src/animation-layers.ts +7 -3
  55. package/src/animation.ts +209 -29
  56. package/src/asset-cache.ts +3 -3
  57. package/src/asset-memo.ts +202 -0
  58. package/src/assets.ts +437 -125
  59. package/src/auto-batch.ts +190 -44
  60. package/src/card-lod.ts +152 -0
  61. package/src/compressed-texture-preparation.ts +1008 -0
  62. package/src/compute-driven.ts +1 -1
  63. package/src/config.ts +8 -0
  64. package/src/debug.ts +103 -22
  65. package/src/dev-global.ts +54 -0
  66. package/src/engine-hooks.ts +37 -0
  67. package/src/frame-budget.ts +50 -23
  68. package/src/game-boot-phase.ts +269 -0
  69. package/src/game-dev-tools.ts +86 -0
  70. package/src/game-frame-loop.ts +958 -0
  71. package/src/game-renderer-metrics.ts +77 -0
  72. package/src/game-startup.ts +1076 -0
  73. package/src/game-ui.ts +84 -0
  74. package/src/game-validate.ts +70 -0
  75. package/src/game.ts +198 -2264
  76. package/src/gamepad-mappings.ts +269 -0
  77. package/src/generated/console-markers.ts +13 -0
  78. package/src/geometry-capture.ts +28 -4
  79. package/src/gpu-readings.ts +98 -0
  80. package/src/gpu-scene-bvh.ts +149 -36
  81. package/src/hot.ts +4 -7
  82. package/src/index.ts +141 -9
  83. package/src/input.ts +237 -25
  84. package/src/instanced-batch-lod.ts +3 -8
  85. package/src/interpolation.ts +171 -40
  86. package/src/launch-diagnostics.ts +22 -12
  87. package/src/look/ao-admission.ts +25 -0
  88. package/src/look/auto-exposure.ts +5 -16
  89. package/src/look/default-tone-mapping.ts +41 -5
  90. package/src/look/filmic-tone-mapping.ts +15 -13
  91. package/src/look/local-exposure.ts +2 -7
  92. package/src/look/look-diagnostics.ts +3 -3
  93. package/src/look/quad-pass.ts +21 -0
  94. package/src/look/quality.ts +14 -5
  95. package/src/look/unreal-bloom.ts +4 -13
  96. package/src/look/world-environment.ts +113 -103
  97. package/src/loop.ts +29 -0
  98. package/src/merge-parts.ts +20 -24
  99. package/src/model-lod.ts +139 -17
  100. package/src/particle-kinds.ts +515 -0
  101. package/src/particle-significance.ts +12 -0
  102. package/src/particles.ts +19 -10
  103. package/src/picking.ts +17 -3
  104. package/src/platform.ts +23 -4
  105. package/src/playtest.ts +27 -1
  106. package/src/profiling/FrameStages.ts +5 -6
  107. package/src/profiling/Spans.ts +3 -17
  108. package/src/profiling/debug-telemetry.ts +2 -6
  109. package/src/profiling/render-list-validate.ts +6 -15
  110. package/src/projection-apply.ts +4 -1
  111. package/src/projection-marker.ts +2 -1
  112. package/src/projection-plan.ts +9 -6
  113. package/src/quiet-markers.ts +3 -10
  114. package/src/render/cpu-bvh.ts +100 -0
  115. package/src/render/depth-pyramid.ts +6 -14
  116. package/src/render/environment/environmentContribution.ts +202 -0
  117. package/src/render/environment/environmentRadiance.ts +44 -0
  118. package/src/render/environment/environmentSampleCache.ts +56 -0
  119. package/src/render/environment/environmentSampling.ts +201 -0
  120. package/src/render/environment/environmentSnapshot.ts +71 -0
  121. package/src/render/environment/gate.ts +57 -0
  122. package/src/render/mesh-pool.ts +4 -20
  123. package/src/render/probe-trace.ts +872 -0
  124. package/src/render/probe-volume.ts +780 -34
  125. package/src/render/radiance-cache.ts +17 -0
  126. package/src/render/resolution-subrect.ts +2 -0
  127. package/src/render/rough-diffuse.ts +46 -12
  128. package/src/render/soft-shadow.ts +27 -12
  129. package/src/render/virtual-shadow-adaptive.ts +55 -0
  130. package/src/render/virtual-shadow-casters.ts +175 -0
  131. package/src/render/virtual-shadow-layers.ts +76 -0
  132. package/src/render/virtual-shadow-level.ts +224 -0
  133. package/src/render/virtual-shadow-markers.ts +193 -0
  134. package/src/render/virtual-shadow-options.ts +370 -0
  135. package/src/render/virtual-shadow-pages.ts +5 -0
  136. package/src/render/virtual-shadow-partial.ts +13 -0
  137. package/src/render/virtual-shadow.ts +231 -1008
  138. package/src/render/world-impostor-surface.ts +402 -40
  139. package/src/render/world-impostor.ts +5 -2
  140. package/src/render-camera-cull.ts +98 -3
  141. package/src/render-environment.ts +41 -0
  142. package/src/render-pass-budget.ts +34 -7
  143. package/src/renderProjection.ts +22 -0
  144. package/src/renderer-config.ts +36 -0
  145. package/src/renderer-facts.ts +37 -0
  146. package/src/renderer.ts +144 -65
  147. package/src/resolution-scaler.ts +3 -2
  148. package/src/scene-entry-inspectors.ts +61 -0
  149. package/src/snow-field.ts +2 -1
  150. package/src/spells/cast-pool.ts +361 -0
  151. package/src/spells/index.ts +177 -0
  152. package/src/spells/mechanisms.ts +295 -0
  153. package/src/spells/reaction-field.ts +415 -0
  154. package/src/spells/spell-lights.ts +139 -0
  155. package/src/spells/spell-world.ts +187 -0
  156. package/src/spells/spell.ts +397 -0
  157. package/src/spells/spells.ts +283 -0
  158. package/src/spells/ultra/engine/camera.ts +184 -0
  159. package/src/spells/ultra/engine/quality.ts +96 -0
  160. package/src/spells/ultra/index.ts +52 -0
  161. package/src/spells/ultra/main.ts +305 -0
  162. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  163. package/src/spells/ultra/spells/cast.ts +233 -0
  164. package/src/spells/ultra/spells/fire.ts +1267 -0
  165. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  166. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  167. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  168. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  169. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  170. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  171. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  172. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  173. package/src/spells/ultra/vfx/common.ts +1195 -0
  174. package/src/spells/ultra/vfx/noise.ts +441 -0
  175. package/src/startup-offscreen-bytes.ts +78 -0
  176. package/src/startup-readiness.ts +128 -34
  177. package/src/static-transform.ts +25 -19
  178. package/src/streamed-textures.ts +112 -0
  179. package/src/streaming.ts +68 -4
  180. package/src/texture-streaming.ts +331 -0
  181. package/src/version.ts +1 -1
  182. package/src/warmup.ts +56 -8
  183. package/src/water-surface.ts +9 -3
  184. package/src/worker.ts +12 -2
  185. package/src/world-bundle-safety.ts +446 -0
  186. package/src/world-cell-batches.ts +1178 -0
  187. package/src/world-cell-chunks.ts +1128 -0
  188. package/src/world-cell-data.ts +995 -0
  189. package/src/world-cell-impostors.ts +1461 -0
  190. package/src/world-cell-lod-bias.ts +151 -0
  191. package/src/world-cell-models.ts +1074 -0
  192. package/src/world-cell-options.ts +177 -0
  193. package/src/world-cell-placements.ts +798 -0
  194. package/src/world-cell-prewarm.ts +592 -0
  195. package/src/world-cell-readiness.ts +357 -0
  196. package/src/world-cell-records.ts +401 -0
  197. package/src/world-cell-render-bundles.ts +459 -0
  198. package/src/world-cell-render-gpu-dress.ts +710 -0
  199. package/src/world-cell-render-main-cull.ts +540 -0
  200. package/src/world-cell-render-shadow-claims.ts +198 -0
  201. package/src/world-cell-render-util.ts +259 -0
  202. package/src/world-cell-render.ts +1501 -0
  203. package/src/world-cell-residency.ts +754 -0
  204. package/src/world-cell-stale.ts +238 -0
  205. package/src/world-cells.ts +1335 -10418
  206. package/src/world-chunk-shadow.ts +308 -0
  207. package/src/world-collar.ts +315 -0
  208. package/src/world-gpu-flags.ts +131 -0
  209. package/src/world-gpu-readback.ts +881 -0
  210. package/src/world-gpu-reference.ts +524 -0
  211. package/src/world-gpu-scene.ts +256 -2286
  212. package/src/world-gpu-shadow.ts +203 -0
  213. package/src/world-gpu-types.ts +409 -0
  214. package/src/world-gpu-validation.ts +518 -0
  215. package/src/world-heightfield.ts +802 -0
  216. package/src/world-load-limiter.ts +111 -0
  217. package/src/world-model-sections.ts +80 -0
  218. package/src/world-noise.ts +241 -0
  219. package/src/world-package.ts +42 -0
  220. package/src/world-region.ts +1 -1
  221. package/src/world-river-ribbon.ts +282 -0
  222. package/src/world-root-frame.ts +39 -0
  223. package/src/world-shore-field.ts +91 -0
  224. package/src/world-static-pose.ts +163 -0
  225. package/src/world-surface-sampler.ts +48 -0
  226. package/src/world-terrain-splat.ts +361 -153
  227. package/src/world-tile-budget.ts +249 -0
  228. package/src/world-tile-geometry.ts +469 -0
  229. package/src/world-tile-lod.ts +408 -0
  230. package/src/world-tile-observation.ts +566 -0
  231. package/src/world-tile-stitch.ts +166 -0
  232. package/src/world-tiles.ts +247 -1755
  233. package/src/world-validate.ts +6 -14
  234. package/src/world-warm.ts +51 -0
  235. package/src/world-water-bodies.ts +359 -0
  236. package/src/world.ts +48 -741
package/src/renderer.ts CHANGED
@@ -9,6 +9,10 @@ import {
9
9
  type StorageBufferAttribute,
10
10
  type Renderer as ThreeRenderer,
11
11
  } from "three/webgpu";
12
+ import {
13
+ CompressedTextureUploads,
14
+ type ICompressedUploadDevice,
15
+ } from "./compressed-texture-preparation.js";
12
16
  import { ComputeTimingScopes, type IComputeTimingReceipt } from "./compute-timing.js";
13
17
  import type { IFrameSurfaceState } from "./frame-budget.js";
14
18
  import {
@@ -30,7 +34,7 @@ import {
30
34
  createPipelineCensus,
31
35
  } from "./pipeline-census.js";
32
36
  import { hostDocument, hostResizeObserver } from "./platform.js";
33
- import type { ITimestampQueryPool } from "./render-pass-budget.js";
37
+ import { type ITimestampQueryPool, RenderPassBudget } from "./render-pass-budget.js";
34
38
  import { AlphaAntialiasing, type IAlphaAntialiasingReport } from "./render/alpha-antialiasing.js";
35
39
  import {
36
40
  type IRenderChainBudgetWindow,
@@ -39,6 +43,7 @@ import {
39
43
  } from "./render/chain.js";
40
44
  import { type IResolutionSubrect, ResolutionSubrect } from "./render/resolution-subrect.js";
41
45
 
46
+ import { GPU_STALE_FRAME_LIMIT, GpuReadings } from "./gpu-readings.js";
42
47
  import type { IStartupImageState } from "./startup-readiness.js";
43
48
  import {
44
49
  type IStorageBufferLease,
@@ -151,6 +156,22 @@ export function prewarm(object: Object3D | readonly Object3D[]): void {
151
156
  }
152
157
  }
153
158
 
159
+ /** Where one resolved frame's GPU time went, when the renderer times its own passes (the owned engine). */
160
+ export interface IGpuFrameSplit {
161
+ /** The scene (main colour) pass. */
162
+ readonly main: number;
163
+ /** Every shadow map the frame drew: the sun's and the lamps'. */
164
+ readonly shadow: number;
165
+ /** Everything else: post chain, output, global illumination gather. */
166
+ readonly other: number;
167
+ }
168
+
169
+ /** One resolved GPU frame: its duration, the Three.js frame id it belongs to, and its pass split when known. */
170
+ export interface IGpuFrameSample extends Partial<IGpuFrameSplit> {
171
+ readonly frame: number;
172
+ readonly ms: number;
173
+ }
174
+
154
175
  export interface IRendererLike {
155
176
  readonly domElement: HTMLCanvasElement;
156
177
  readonly kind: RendererKind;
@@ -289,11 +310,18 @@ export interface IRendererLike {
289
310
  * Ordinary textures and the WebGL fallback retain their existing paths and report no work.
290
311
  * `onProgress` receives the completed unique compressed texture count after each preparation
291
312
  * promise resolves; queued textures and writes that have not settled receive no credit.
313
+ *
314
+ * Pass `replacements` to receive caller-owned `original -> prepared` pairs. The renderer owns
315
+ * the prepared GPU textures and publishes the map only after the whole call succeeds; an abort
316
+ * or failure leaves the caller's map unchanged. Without it the call keeps the numeric contract
317
+ * and prepared compressed replacements stay unpublished, so a material that samples the
318
+ * original keeps its borrowed identity.
292
319
  */
293
320
  prepareTextures?(
294
321
  textures: Iterable<Texture>,
295
322
  signal?: AbortSignal,
296
323
  onProgress?: (completed: number) => void,
324
+ replacements?: Map<Texture, Texture>,
297
325
  ): Promise<number>;
298
326
  /**
299
327
  * Copies one GPU storage attribute back to the CPU, asynchronously.
@@ -364,7 +392,7 @@ export interface IRendererLike {
364
392
  * resolve twice. Optional like `gpuFrameAge`, for stubs that implement only the drawing
365
393
  * contract. `createRenderer` always provides it.
366
394
  */
367
- gpuFrameSample?(): { readonly frame: number; readonly ms: number } | undefined;
395
+ gpuFrameSample?(): IGpuFrameSample | undefined;
368
396
  /**
369
397
  * Observes complete allocated render-query groups without changing ordinary sampling.
370
398
  * Frame IDs are Three query IDs, including any overlay draws; callers map world callbacks.
@@ -520,10 +548,6 @@ type RendererInstance = IStorageBufferSource & {
520
548
  domElement: HTMLCanvasElement;
521
549
  init?: () => Promise<void>;
522
550
  compileAsync?: (scene: Object3D, camera: Camera, targetScene?: Object3D) => Promise<void>;
523
- prepareTextureAsync?: (
524
- texture: Texture,
525
- options: { budgetMs: number; maxBytesPerWrite: number; signal: AbortSignal },
526
- ) => Promise<void>;
527
551
  compute?: (node: unknown) => void;
528
552
  getArrayBufferAsync?: (
529
553
  attribute: unknown,
@@ -682,8 +706,14 @@ function wrapRenderer(
682
706
  let renderChainUsesPerObjectVelocity = false;
683
707
  let activeCompiles = 0;
684
708
  let compileCount = 0;
709
+ // Compiles that overlap while drawing to the screen share three's one frame-buffer target. Only
710
+ // the first claim captures the name it found, and only the last one out puts it back; without
711
+ // that, a second claim captures the first one's temporary name and leaves it on the target.
712
+ const frameBufferNames = new WeakMap<object, { depth: number; saved: string }>();
685
713
  let disposed = false;
686
- const texturePreparations = new Set<AbortController>();
714
+ const texturePreparations = new CompressedTextureUploads(
715
+ () => (raw.backend as { device?: ICompressedUploadDevice } | undefined)?.device,
716
+ );
687
717
  const storageBuffers = new StorageBufferLeases(() => raw);
688
718
  let computeTimings: ComputeTimingScopes | undefined;
689
719
  let pendingScale: { scale: number; source: "auto" | "auto-pinned" } | undefined;
@@ -722,7 +752,7 @@ function wrapRenderer(
722
752
  */
723
753
  const currentFrame = (): number | undefined =>
724
754
  timestampFrame >= 0 ? timestampFrame : raw.info?.frame;
725
- const gpuFrameSample = (): { frame: number; ms: number } | undefined => {
755
+ const gpuFrameSample = (): IGpuFrameSample | undefined => {
726
756
  const frame = currentFrame();
727
757
  const frames = raw.backend?.getTimestampFrames?.("render");
728
758
  const sampled = frames?.[frames.length - 1];
@@ -739,7 +769,19 @@ function wrapRenderer(
739
769
  timestamp <= 0
740
770
  )
741
771
  return undefined;
742
- return { frame: sampled, ms: timestamp };
772
+ // The owned engine times its own passes (`info.engine.gpuSplit`); the split joins the sample
773
+ // only while it describes that same frame.
774
+ const split = (
775
+ raw.info as { engine?: { gpuSplit?: IGpuFrameSplit & { frame: number } } } | undefined
776
+ )?.engine?.gpuSplit;
777
+ if (split?.frame !== sampled) return { frame: sampled, ms: timestamp };
778
+ return {
779
+ frame: sampled,
780
+ ms: timestamp,
781
+ main: split.main,
782
+ shadow: split.shadow,
783
+ other: split.other,
784
+ };
743
785
  };
744
786
 
745
787
  /**
@@ -755,6 +797,20 @@ function wrapRenderer(
755
797
  };
756
798
 
757
799
  let renderingFrame = 0;
800
+ // three's `compileAsync` runs a viewport texture's `updateBefore`, which copies the framebuffer from
801
+ // a render context the compile never bound to a target, so the backend reads the canvas
802
+ // (rgba8unorm) into the scene copy (rgba16float) and logs a format error per refracting material.
803
+ // A compile draws no pixels: the copy it triggers outside a real frame is skipped, and a frame the
804
+ // compile yields to still copies.
805
+ const copyingBackend = raw.backend as
806
+ | { copyFramebufferToTexture?: (...args: unknown[]) => unknown }
807
+ | undefined;
808
+ const stockFramebufferCopy = copyingBackend?.copyFramebufferToTexture;
809
+ if (copyingBackend !== undefined && typeof stockFramebufferCopy === "function")
810
+ copyingBackend.copyFramebufferToTexture = (...args: unknown[]) =>
811
+ activeCompiles > 0 && renderingFrame === 0
812
+ ? undefined
813
+ : stockFramebufferCopy.apply(copyingBackend, args);
758
814
  let temporalUpscaleActive = false;
759
815
  const renderFrame = (scene: Object3D, camera: Camera): void => {
760
816
  const temporal = wrapped.temporalUpscale?.() === true;
@@ -821,32 +877,13 @@ function wrapRenderer(
821
877
  }
822
878
  };
823
879
  // The main pass's own GPU series, fed a frame at a time by `game.ts` because only the pass
824
- // recorder can attribute the render pool to its main call. Half/half smoothing, and a short
825
- // freshness window: the adaptive LOD loop reads this every half second and must not act on a
826
- // resolve that stopped landing.
827
- const mainSmoothing = 0.5;
828
- const mainStaleLimit = 8;
829
- let gpuMainEma: number | undefined;
880
+ // recorder can attribute the render pool to its main call. Half/half smoothing, and the engine's
881
+ // stale limit: the adaptive LOD loop reads this every half second and must not act on a resolve
882
+ // that stopped landing.
883
+ const mainReadings = new GpuReadings({ smoothing: 0.5, staleLimit: GPU_STALE_FRAME_LIMIT });
830
884
  let targetFps: number | undefined;
831
- let gpuMainStaleFrames = 0;
832
- let gpuMainLastFrame: number | undefined;
833
885
  const noteGpuMainMs = (ms: number | undefined, frame?: number): void => {
834
- const stale = (): void => {
835
- gpuMainStaleFrames += 1;
836
- if (gpuMainStaleFrames >= mainStaleLimit) gpuMainEma = undefined;
837
- };
838
- if (ms === undefined || !Number.isFinite(ms) || ms < 0) {
839
- stale();
840
- return;
841
- }
842
- // A repeated frame id is the previous resolve still in flight, not a new reading.
843
- if (frame !== undefined && frame === gpuMainLastFrame) {
844
- stale();
845
- return;
846
- }
847
- if (frame !== undefined) gpuMainLastFrame = frame;
848
- gpuMainStaleFrames = 0;
849
- gpuMainEma = gpuMainEma === undefined ? ms : gpuMainEma + (ms - gpuMainEma) * mainSmoothing;
886
+ mainReadings.note(ms, frame);
850
887
  };
851
888
  const wrapped: IRendererLike = {
852
889
  get compileCount() {
@@ -866,7 +903,9 @@ function wrapRenderer(
866
903
  pipelineCensus.warmUpScopeSettled(label, target),
867
904
  }),
868
905
  get warmUpWorldPass() {
869
- if (outputPipeline === undefined) return undefined;
906
+ // The ThreeNative engine refuses RendererUtils, so the pass could not restore the renderer
907
+ // state it changes there; the engine compiles the output pass at its first frame instead.
908
+ if (outputPipeline === undefined || !restoresRendererState()) return undefined;
870
909
  const drawOnce = (
871
910
  scene: Object3D,
872
911
  camera: Camera,
@@ -1036,7 +1075,7 @@ function wrapRenderer(
1036
1075
  );
1037
1076
  return gpuObservation;
1038
1077
  },
1039
- gpuMainMs: () => gpuMainEma,
1078
+ gpuMainMs: () => mainReadings.ema,
1040
1079
  noteGpuMainMs,
1041
1080
  targetFps: () => targetFps,
1042
1081
  noteTargetFps: (fps: number) => {
@@ -1178,6 +1217,24 @@ function wrapRenderer(
1178
1217
  (previousGetRenderTarget as () => unknown).call(raw) ??
1179
1218
  (renderingFrame > 0 ? null : overrideTarget);
1180
1219
  }
1220
+ // Three's frame-buffer target carries one unnamed texture. An MRT node resolves its outputs by
1221
+ // name, so a material with an `mrtNode` (a transparent sea, say) compiled against it builds an
1222
+ // empty output struct and its pipeline fails. Name that texture after the pass's first output
1223
+ // for this compile only. ponytail: first output only; a material needing a later output still
1224
+ // warms up empty.
1225
+ const frameBufferTexture = (overrideTarget as { textures?: { name: string }[] } | undefined)
1226
+ ?.textures?.[0];
1227
+ const firstOutputName = outputPass?.renderTarget?.textures[0]?.name;
1228
+ let frameBufferClaim: { depth: number; saved: string } | undefined;
1229
+ if (frameBufferTexture !== undefined) {
1230
+ frameBufferClaim = frameBufferNames.get(frameBufferTexture);
1231
+ if (frameBufferClaim === undefined) {
1232
+ frameBufferClaim = { depth: 0, saved: frameBufferTexture.name };
1233
+ frameBufferNames.set(frameBufferTexture, frameBufferClaim);
1234
+ }
1235
+ frameBufferClaim.depth += 1;
1236
+ if (firstOutputName) frameBufferTexture.name = firstOutputName;
1237
+ }
1181
1238
  activeCompiles += 1;
1182
1239
  compileCount += 1;
1183
1240
  try {
@@ -1191,6 +1248,13 @@ function wrapRenderer(
1191
1248
  else await raw.compileAsync(scene, camera, targetScene);
1192
1249
  }
1193
1250
  } finally {
1251
+ if (frameBufferTexture !== undefined && frameBufferClaim !== undefined) {
1252
+ frameBufferClaim.depth -= 1;
1253
+ if (frameBufferClaim.depth === 0) {
1254
+ frameBufferTexture.name = frameBufferClaim.saved;
1255
+ frameBufferNames.delete(frameBufferTexture);
1256
+ }
1257
+ }
1194
1258
  if (overrideTarget !== undefined) {
1195
1259
  if (hadOwnGetRenderTarget) raw.getRenderTarget = previousGetRenderTarget;
1196
1260
  else Reflect.deleteProperty(raw as object, "getRenderTarget");
@@ -1273,39 +1337,47 @@ function wrapRenderer(
1273
1337
  }
1274
1338
  return created;
1275
1339
  },
1276
- prepareTextures: async (textures, signal, onProgress) => {
1340
+ prepareTextures: async (textures, signal, onProgress, replacements) => {
1277
1341
  if (disposed) throw new Error("Renderer disposed during texture preparation.");
1278
1342
  if (kind !== "webgpu") return 0;
1279
- const unique = new Set(
1280
- [...textures].filter(
1281
- (texture) => "isCompressedTexture" in texture && texture.isCompressedTexture === true,
1282
- ),
1283
- );
1284
- if (unique.size === 0) return 0;
1285
- if (typeof raw.prepareTextureAsync !== "function")
1286
- throw new Error("WebGPU renderer lacks bounded compressed texture preparation.");
1287
- const controller = new AbortController();
1288
- const abort = () => controller.abort(signal?.reason);
1289
- if (signal?.aborted) abort();
1290
- else signal?.addEventListener("abort", abort, { once: true });
1291
- texturePreparations.add(controller);
1343
+ // Snapshot the caller's iterable once. An owned replacement resolves back to its original,
1344
+ // so a repeated call that hands back a published replacement keeps a stable identity instead
1345
+ // of looking like an unrelated texture and returning stale work.
1346
+ const inputs: Texture[] = [];
1347
+ const originals = new Set<Texture>();
1348
+ for (const texture of textures) {
1349
+ inputs.push(texture);
1350
+ const original = texturePreparations.resolveOriginal(texture);
1351
+ const compressed =
1352
+ "isCompressedTexture" in original && original.isCompressedTexture === true;
1353
+ const compressedArray =
1354
+ "isCompressedArrayTexture" in original && original.isCompressedArrayTexture === true;
1355
+ if (original !== texture || compressed || compressedArray) originals.add(original);
1356
+ }
1357
+ if (originals.size === 0) return 0;
1358
+ const preparedReplacements = new Map<Texture, Texture>();
1292
1359
  let completed = 0;
1293
- try {
1294
- for (const texture of unique) {
1295
- if (controller.signal.aborted) throw controller.signal.reason;
1296
- await raw.prepareTextureAsync(texture, {
1297
- budgetMs: 2,
1298
- maxBytesPerWrite: 65_536,
1299
- signal: controller.signal,
1300
- });
1360
+ for (const original of originals) {
1361
+ if (signal?.aborted) throw signal.reason;
1362
+ const prepared = await texturePreparations.upload(original, signal);
1363
+ if (prepared !== original) {
1364
+ preparedReplacements.set(original, prepared);
1301
1365
  completed += 1;
1302
1366
  onProgress?.(completed);
1303
1367
  }
1304
- return unique.size;
1305
- } finally {
1306
- texturePreparations.delete(controller);
1307
- signal?.removeEventListener("abort", abort);
1308
1368
  }
1369
+ if (disposed) throw new Error("Renderer disposed during texture preparation.");
1370
+ if (signal?.aborted) throw signal.reason;
1371
+ // Publish only after every texture in this call succeeded; abort or failure left this local.
1372
+ if (replacements !== undefined) {
1373
+ for (const [original, prepared] of preparedReplacements) {
1374
+ replacements.set(original, prepared);
1375
+ for (const input of inputs)
1376
+ if (texturePreparations.resolveOriginal(input) === original)
1377
+ replacements.set(input, prepared);
1378
+ }
1379
+ }
1380
+ return completed;
1309
1381
  },
1310
1382
  scenePassDepth: () => {
1311
1383
  // Three's implicit depth is in Textures.updateRenderTarget's data, not target.depthTexture.
@@ -1411,9 +1483,7 @@ function wrapRenderer(
1411
1483
  disposed = true;
1412
1484
  state.resolutionSubrect?.deactivate?.();
1413
1485
  state.resolutionSubrect = undefined;
1414
- for (const preparation of texturePreparations)
1415
- preparation.abort(new Error("Renderer disposed during texture preparation."));
1416
- texturePreparations.clear();
1486
+ texturePreparations.dispose();
1417
1487
  gpuObservation?.dispose();
1418
1488
  gpuObservation = undefined;
1419
1489
  pendingScale = undefined;
@@ -1442,7 +1512,7 @@ function wrapRenderer(
1442
1512
  if (!timestampFramesManaged) setTimestampTracking();
1443
1513
  renderingFrame += 1;
1444
1514
  try {
1445
- renderFrame(scene, camera);
1515
+ RenderPassBudget.renderWorld(raw, scene, camera, () => renderFrame(scene, camera));
1446
1516
  } finally {
1447
1517
  renderingFrame -= 1;
1448
1518
  }
@@ -1974,6 +2044,15 @@ export async function adapterTextureLimits(): Promise<{ requiredLimits?: Record<
1974
2044
  }
1975
2045
  }
1976
2046
 
2047
+ /** False on the ThreeNative engine, whose RendererUtils throws its catalog diagnostic on access. */
2048
+ function restoresRendererState(): boolean {
2049
+ try {
2050
+ return typeof RendererUtils.restoreRendererState === "function";
2051
+ } catch {
2052
+ return false;
2053
+ }
2054
+ }
2055
+
1977
2056
  function newPageCanvas(): HTMLCanvasElement {
1978
2057
  const page = hostDocument();
1979
2058
  if (page === undefined)
@@ -15,6 +15,7 @@
15
15
  */
16
16
 
17
17
  import type { GpuClass } from "./gpu-class.js";
18
+ import { GPU_READING_MAX_AGE_FRAMES, GPU_WINDOW_MIN_SAMPLES } from "./gpu-readings.js";
18
19
 
19
20
  /** How the active scale was arrived at, reported beside every fps number. */
20
21
  export type ScaleSource = "pinned" | "auto" | "auto-pinned";
@@ -104,9 +105,9 @@ export const RESOLUTION_SCALER = {
104
105
  downWindows: 1,
105
106
  upWindows: 4,
106
107
  /** Eight frames for the sampled GPU reading plus eight for asynchronous query resolution. */
107
- maxGpuAgeFrames: 16,
108
+ maxGpuAgeFrames: GPU_READING_MAX_AGE_FRAMES,
108
109
  /** Window GPU samples that make the window's own median fresh evidence; see `IScalerWindow.gpu`. */
109
- minWindowGpuSamples: 4,
110
+ minWindowGpuSamples: GPU_WINDOW_MIN_SAMPLES,
110
111
  /** The resize frame is itself a hitch and must never feed the controller. */
111
112
  cooldownWindows: 1,
112
113
  /** Continuous sub-rectangle changes are separated by this many rendered frames. */
@@ -0,0 +1,61 @@
1
+ /**
2
+ * What a scene entry checks, in one ordered list.
3
+ *
4
+ * Every audit a scene entry runs used to be welded into `Game.#enterScene` — the opacity
5
+ * convention, the render trap audit, the unlit foliage warning — so a fourth one meant editing the
6
+ * lifecycle file that every other feature already edits. A kit or a game can add its own here, and
7
+ * the order the list states is the order the warnings appear in.
8
+ *
9
+ * Nothing here decides how anything looks: each inspector reads the scene the game just entered and
10
+ * returns what a reader should be told about it.
11
+ */
12
+ import type { Object3D } from "three";
13
+ import { applyOpacityConvention } from "./profiling/opacity-convention.js";
14
+ import { renderTrapAudit } from "./profiling/render-trap-audit.js";
15
+ import {
16
+ UNLIT_FOLIAGE_FIX,
17
+ formatUnlitFoliageWarning,
18
+ unlitFoliageWarning,
19
+ } from "./profiling/unlit-foliage-warning.js";
20
+
21
+ /** One line a scene entry reports, and the console level it belongs at. */
22
+ export interface ISceneEntryFinding {
23
+ readonly level: "error" | "warn";
24
+ readonly line: string;
25
+ }
26
+
27
+ /** A check that runs once per scene entry, after the game's `enter()` has built the scene. */
28
+ export type SceneEntryInspector = (scene: Object3D) => readonly ISceneEntryFinding[];
29
+
30
+ /**
31
+ * The engine's own inspectors, in the order their findings must appear.
32
+ *
33
+ * The opacity convention runs first: it makes an author's opacity take effect, and the render trap
34
+ * audit then reports what that effect is — the other order reports the state before the convention.
35
+ */
36
+ export const SCENE_ENTRY_INSPECTORS: readonly SceneEntryInspector[] = [
37
+ (scene) => {
38
+ const line = applyOpacityConvention(scene);
39
+ return line === undefined ? [] : [{ level: "warn", line }];
40
+ },
41
+ (scene) => renderTrapAudit(scene).map((line) => ({ level: "error", line })),
42
+ (scene) => {
43
+ const warning = unlitFoliageWarning(scene);
44
+ return warning === undefined
45
+ ? []
46
+ : [{ level: "warn", line: `${formatUnlitFoliageWarning(warning)} ${UNLIT_FOLIAGE_FIX}` }];
47
+ },
48
+ ];
49
+
50
+ /** Runs every inspector against a scene the game has just entered, reporting each finding once. */
51
+ export function inspectSceneEntry(
52
+ scene: Object3D,
53
+ inspectors: readonly SceneEntryInspector[] = SCENE_ENTRY_INSPECTORS,
54
+ ): void {
55
+ for (const inspector of inspectors) {
56
+ for (const finding of inspector(scene)) {
57
+ if (finding.level === "error") console.error(finding.line);
58
+ else console.warn(finding.line);
59
+ }
60
+ }
61
+ }
package/src/snow-field.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Vector3 } from "three";
2
+ import type { Heightfield, IHeightfieldRegionBounds } from "./world-heightfield.js";
2
3
  import { unionBounds } from "./world-region.js";
3
- import type { Heightfield, IHeightfieldRegionBounds } from "./world.js";
4
4
 
5
5
  /**
6
6
  * What one contact footprint wants at a local offset, sampled in the contact's own frame.
@@ -213,6 +213,7 @@ export function snowDiscFootprint(
213
213
  * recovery. It is a heightfield approximation — not granular snow, displaced-volume
214
214
  * conservation, avalanches, melting or a calibrated material law.
215
215
  * @situation leave footprints, tracks and tyre ruts in snow that persist and fill in over time
216
+ * @situation let a fresh snowfall slowly fill older tracks back in as the field recovers
216
217
  * @situation let a pushed sphere carve a connected track and a dropped one settle into a crater
217
218
  * @situation store snow deformation that rendered geometry and collision both read
218
219
  * @situation reset a snowfield between rounds or change its depth at runtime