@threenative/core 0.3.3 → 0.3.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/capabilities.json +2019 -59
  2. package/dist/{assets-CYKk2WTu.d.ts → assets-CqvE429w.d.ts} +45 -3
  3. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  4. package/dist/{canvas-layer-C1SnMoJ-.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  5. package/dist/{game-D_6r-k4Y.d.ts → game-Bj8G1wmD.d.ts} +242 -17
  6. package/dist/hot.d.ts +5 -5
  7. package/dist/index.d.ts +1131 -105
  8. package/dist/index.js +15201 -4782
  9. package/dist/model-lod-BDAUYgsS.d.ts +197 -0
  10. package/dist/playtest.d.ts +6 -4
  11. package/dist/playtest.js +84 -11
  12. package/dist/react-css.d.ts +62 -0
  13. package/dist/react-css.js +591 -0
  14. package/dist/react.d.ts +2 -2
  15. package/dist/{renderer-Cy4qeBOA.d.ts → renderer-9yEo9hPa.d.ts} +676 -21
  16. package/dist/terrain-jobs-worker.d.ts +2 -0
  17. package/dist/terrain-jobs-worker.js +130 -0
  18. package/dist/ui-layer.d.ts +5 -3
  19. package/dist/ui-layer.js +59 -8
  20. package/dist/world.d.ts +1596 -17
  21. package/dist/world.js +17035 -521
  22. package/gpl/fixtures/make_world_fixture.py +184 -0
  23. package/gpl/recipes/_common.py +11 -0
  24. package/gpl/recipes/decimate.py +11 -5
  25. package/gpl/recipes/export_world.py +699 -0
  26. package/mcp/blender-server.mjs +61 -4
  27. package/mcp/blender.mjs +3 -4
  28. package/mcp/engine-server.mjs +55 -21
  29. package/mcp/servers.mjs +4 -4
  30. package/package.json +15 -9
  31. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  32. package/patches/three@0.185.1.patch +8246 -389
  33. package/scripts/apply-three-patch.mjs +123 -41
  34. package/src/animation-blend.ts +264 -0
  35. package/src/animation-composition.ts +362 -0
  36. package/src/animation-layers.ts +260 -0
  37. package/src/animation-root-motion.ts +283 -0
  38. package/src/animation.ts +896 -0
  39. package/src/assets.ts +1303 -0
  40. package/src/atmosphere/index.ts +335 -0
  41. package/src/atmosphere/luts.ts +298 -0
  42. package/src/atmosphere/params.ts +323 -0
  43. package/src/audio.ts +912 -0
  44. package/src/billboard.ts +124 -0
  45. package/src/bone-lengths.ts +157 -0
  46. package/src/camera-shake.ts +116 -0
  47. package/src/canvas-layer.ts +47 -0
  48. package/src/clip-audit.ts +401 -0
  49. package/src/clustered-batch.ts +492 -0
  50. package/src/clustered-mesh.ts +638 -0
  51. package/src/compute-driven.ts +176 -0
  52. package/src/compute-timing.ts +318 -0
  53. package/src/config.ts +593 -0
  54. package/src/debug.ts +82 -0
  55. package/src/engine-render-hook.ts +25 -0
  56. package/src/entities.ts +79 -0
  57. package/src/entity-snapshot.ts +53 -0
  58. package/src/flight.ts +683 -0
  59. package/src/fluid-field.ts +748 -0
  60. package/src/fluid-particles.ts +1253 -0
  61. package/src/frame-budget.ts +1368 -0
  62. package/src/game.ts +2390 -0
  63. package/src/geometry-capture.ts +1098 -0
  64. package/src/gpu-class.ts +160 -0
  65. package/src/gpu-frame-observation.ts +424 -0
  66. package/src/gpu-readback.ts +143 -0
  67. package/src/gpu-scene-bvh.ts +464 -0
  68. package/src/grounding.ts +100 -0
  69. package/src/hot.ts +161 -0
  70. package/src/import-meta.d.ts +13 -0
  71. package/src/index.ts +1536 -0
  72. package/src/input.ts +690 -0
  73. package/src/instanced-batch-lod.ts +283 -0
  74. package/src/instanced-batch.ts +274 -0
  75. package/src/interpolation.ts +129 -0
  76. package/src/launch-diagnostics.ts +161 -0
  77. package/src/loop.ts +564 -0
  78. package/src/matrix-world.ts +245 -0
  79. package/src/merge-parts.ts +812 -0
  80. package/src/model-lod.ts +1315 -0
  81. package/src/net-protocol.ts +333 -0
  82. package/src/net-session.ts +477 -0
  83. package/src/net.ts +80 -0
  84. package/src/ocean/fft.ts +72 -0
  85. package/src/ocean/spectral.ts +728 -0
  86. package/src/particle-significance.ts +102 -0
  87. package/src/particles.ts +648 -0
  88. package/src/path-follow.ts +175 -0
  89. package/src/picking.ts +250 -0
  90. package/src/pipeline-census.ts +1566 -0
  91. package/src/platform.ts +210 -0
  92. package/src/playtest.ts +839 -0
  93. package/src/pointer-events.ts +411 -0
  94. package/src/pose-measure.ts +435 -0
  95. package/src/profiling/FrameCounters.ts +231 -0
  96. package/src/profiling/Spans.ts +548 -0
  97. package/src/profiling/opacity-convention.ts +21 -0
  98. package/src/profiling/render-list-validate.ts +175 -0
  99. package/src/profiling/render-trap-audit.ts +84 -0
  100. package/src/profiling/scene-warning.ts +190 -0
  101. package/src/profiling/span-probes.ts +191 -0
  102. package/src/profiling/unlit-foliage-warning.ts +149 -0
  103. package/src/projection-apply.ts +1529 -0
  104. package/src/projection-marker.ts +142 -0
  105. package/src/projection-plan.ts +1258 -0
  106. package/src/projection-skinned.ts +419 -0
  107. package/src/projection-stability.ts +409 -0
  108. package/src/projection-uniform.ts +328 -0
  109. package/src/random.ts +41 -0
  110. package/src/react-css.ts +604 -0
  111. package/src/react-glyphs.ts +114 -0
  112. package/src/react-host.ts +576 -0
  113. package/src/react-layout.ts +265 -0
  114. package/src/react.ts +60 -0
  115. package/src/render/alpha-antialiasing.ts +159 -0
  116. package/src/render/batched-velocity.ts +126 -0
  117. package/src/render/chain.ts +1021 -0
  118. package/src/render/daylight.ts +189 -0
  119. package/src/render/depth-pyramid.ts +596 -0
  120. package/src/render/foliage-alpha.ts +166 -0
  121. package/src/render/material-key.ts +60 -0
  122. package/src/render/mesh-pool.ts +144 -0
  123. package/src/render/probe-volume.ts +1668 -0
  124. package/src/render/resolution-subrect.ts +253 -0
  125. package/src/render/velocity.ts +442 -0
  126. package/src/render/virtual-shadow-pages.ts +827 -0
  127. package/src/render/virtual-shadow-partial.ts +174 -0
  128. package/src/render/virtual-shadow.ts +3330 -0
  129. package/src/render/world-impostor-surface.ts +722 -0
  130. package/src/render/world-impostor.ts +558 -0
  131. package/src/render-camera-cull.ts +441 -0
  132. package/src/render-pass-budget.ts +501 -0
  133. package/src/renderProjection.ts +758 -0
  134. package/src/renderer-config.ts +127 -0
  135. package/src/renderer.ts +1847 -0
  136. package/src/replay-protocol.ts +85 -0
  137. package/src/replay.ts +205 -0
  138. package/src/resolution-scaler.ts +819 -0
  139. package/src/rig-preparation.ts +271 -0
  140. package/src/ripple-field.ts +432 -0
  141. package/src/scale.ts +109 -0
  142. package/src/scene.ts +239 -0
  143. package/src/schedule.ts +155 -0
  144. package/src/skeletal-mesh.ts +61 -0
  145. package/src/skeleton.ts +100 -0
  146. package/src/snow-field.ts +744 -0
  147. package/src/softbody-topology.ts +269 -0
  148. package/src/softbody.ts +516 -0
  149. package/src/sprite-animator.ts +222 -0
  150. package/src/startup-readiness.ts +386 -0
  151. package/src/state.ts +66 -0
  152. package/src/static-transform.ts +274 -0
  153. package/src/storage-buffer.ts +253 -0
  154. package/src/streaming.ts +308 -0
  155. package/src/target-fps.ts +92 -0
  156. package/src/terrain-jobs-worker.ts +17 -0
  157. package/src/terrain-jobs.ts +353 -0
  158. package/src/textures.ts +39 -0
  159. package/src/tracers.ts +237 -0
  160. package/src/ui-bridge.ts +368 -0
  161. package/src/ui-hit-regions.ts +380 -0
  162. package/src/ui-layer.ts +83 -0
  163. package/src/ui-state.ts +220 -0
  164. package/src/version.ts +2 -0
  165. package/src/viewport.ts +253 -0
  166. package/src/warmup.ts +1357 -0
  167. package/src/water-surface.ts +384 -0
  168. package/src/wave-field.ts +524 -0
  169. package/src/world-capabilities.ts +131 -0
  170. package/src/world-cell-proxy.ts +392 -0
  171. package/src/world-cells.ts +10564 -0
  172. package/src/world-gpu-scene.ts +3354 -0
  173. package/src/world-heightmap.ts +82 -0
  174. package/src/world-package.ts +469 -0
  175. package/src/world-passes.ts +582 -0
  176. package/src/world-region.ts +17 -0
  177. package/src/world-terrain-splat.ts +564 -0
  178. package/src/world-tiles.ts +3826 -0
  179. package/src/world-topology.ts +370 -0
  180. package/src/world-validate.ts +48 -0
  181. package/src/world.ts +805 -0
  182. package/dist/gpu-readback-CMklJs6r.d.ts +0 -112
package/src/warmup.ts ADDED
@@ -0,0 +1,1357 @@
1
+ import type { Camera, Object3D, Texture } from "three";
2
+ import { pmremTexture } from "three/tsl";
3
+
4
+ import type { IPipelineCensus } from "./pipeline-census.js";
5
+ import { STARTUP_HOLD_BUDGET_MS } from "./startup-readiness.js";
6
+
7
+ /**
8
+ * Compiles a scene's pipelines before the first frame, in slices, yielding between them.
9
+ *
10
+ * On a phone every distinct pipeline is built the first time something using it is drawn. Nothing
11
+ * spreads that cost: the first `render()` of a fully built scene compiles all of it, on the main
12
+ * loop, inside one frame. Measured on a Pixel 8, `sandbox/fps-framework` spent **24.5 seconds
13
+ * across 107 pipeline compiles** inside a single frame — 92 % of everything the launch-stall
14
+ * budget could attribute (`TN_STALL_SEGMENTS`, PRD-218). For that whole span the loop presented
15
+ * nothing, drained no UI messages and ran no callback, so the loading screen froze mid-animation
16
+ * and the game read as hung. The player's report was "the loading screen takes thirty seconds".
17
+ *
18
+ * This does not make the compiling cheaper — the same pipelines are built either way, and a claim
19
+ * otherwise would be a lie the next measurement catches. What it changes is **who waits and
20
+ * whether anything moves**: the work is cut into slices with a frame between them, so the loop
21
+ * presents, the loading screen animates, the UI bridge delivers, and progress is a number the game
22
+ * can show instead of a static label. A cost that cannot be removed must at least be visible; that
23
+ * is the whole of what this buys, and it is worth saying plainly.
24
+ *
25
+ * The slices are compiled through the renderer's own `compileAsync`, which is stock `three`.
26
+ * Nothing here mutates the scene: no reparenting, no temporary groups, no visibility flipping. A
27
+ * warm-up that edited the graph to compile it would be a correctness risk taken for a progress
28
+ * bar, and the object it handed back would not be the one the game authored.
29
+ */
30
+
31
+ /** One renderable's worth of progress, reported as the warm-up advances. */
32
+ export interface IWarmUpProgress {
33
+ /** Renderable candidates handed to the renderer so far. */
34
+ readonly done: number;
35
+ /** Renderable candidates the warm-up will hand to the renderer in total. */
36
+ readonly total: number;
37
+ }
38
+
39
+ /** The result of the optional persistent warm-up hint. */
40
+ export type WarmUpCacheStatus = "disabled" | "unavailable" | "miss" | "hit" | "stored";
41
+
42
+ export interface IWarmUpCacheOptions {
43
+ /**
44
+ * A game-owned revision for the scene's materials, shaders and renderer settings.
45
+ *
46
+ * The value is a hint that the native driver's own pipeline cache survived a relaunch; it is
47
+ * not a serialized WebGPU pipeline. Change it whenever those inputs change. A missing or
48
+ * unavailable localStorage implementation never prevents the warm-up from running.
49
+ */
50
+ readonly key: string;
51
+ }
52
+
53
+ export interface IWarmUpOptions {
54
+ /** Compute kernels to compile in the same bounded startup window as draw pipelines. */
55
+ readonly computeNodes?: readonly unknown[];
56
+ /**
57
+ * Renderable candidates handed to the renderer between yields. Default 24.
58
+ *
59
+ * The trade is presented frames against total warm-up time: every yield costs one frame's
60
+ * present, and a slice of one would spend more time presenting than compiling. 24 puts a frame
61
+ * on the screen roughly every 30 objects' worth of work while adding a handful of presents to
62
+ * the launch.
63
+ */
64
+ readonly sliceSize?: number;
65
+ /** Called after each slice. Never called with `done` greater than `total`. */
66
+ readonly onProgress?: (progress: IWarmUpProgress) => void;
67
+ /**
68
+ * How the warm-up lets the host present between slices. Defaults to yielding one macrotask,
69
+ * which is one native-runtime loop iteration and therefore one presented frame. A caller that
70
+ * knows its host wants a different signal passes one; a test passes a resolved promise.
71
+ */
72
+ readonly yieldFrame?: () => Promise<void>;
73
+ /**
74
+ * How long one pipeline may take before the warm-up gives up on it. Default 2000 ms.
75
+ *
76
+ * A real compile on a Pixel 8 measured ~77 ms; two seconds is a compile that is not coming back.
77
+ */
78
+ readonly compileTimeoutMs?: number;
79
+ /**
80
+ * How long the whole warm-up may take before it stops and lets the game start. Default 15000 ms.
81
+ *
82
+ * The launch must never be *worse* for having tried to optimize it.
83
+ *
84
+ * It bounds compilation only, and starts once the scene's environment is prepared: a
85
+ * full-quality PMREM bake is lighting the first frame needs, not compile work, and on a software
86
+ * adapter it alone outlasts this budget (about 20 s on 3-CPU SwiftShader).
87
+ */
88
+ readonly budgetMs?: number;
89
+ /**
90
+ * How long the scene environment's PMREM preparation may take before warm-up gives up on it and
91
+ * compiles anyway. Default `STARTUP_HOLD_BUDGET_MS` (45000 ms), the startup bound for a game's own
92
+ * launch work.
93
+ */
94
+ readonly environmentBudgetMs?: number;
95
+ /**
96
+ * How the scene is handed to the renderer. Default `"scene"`.
97
+ *
98
+ * `"scene"` makes one `compileAsync(scene, camera)` call, which is the shape `three` is built
99
+ * for and the only one measured to be affordable: on a Pixel 8 the renderer builds all 107 of
100
+ * this game's pipelines in **8.1 s** that way.
101
+ *
102
+ * `"object"` walks every renderable candidate and yields between slices, which is the only way
103
+ * to show candidate progress. The renderer owns cache reuse and actual pipeline identity, so the
104
+ * warm-up never drops an object based on a material or geometry guess.
105
+ */
106
+ readonly granularity?: "scene" | "object";
107
+ /**
108
+ * Remember a completed warm-up so a later launch can trust the driver's persistent cache.
109
+ * This is opt-in because WebGPU does not expose a portable pipeline-serialization API.
110
+ */
111
+ readonly cache?: IWarmUpCacheOptions;
112
+ /**
113
+ * Render the warm scene once after compiling, so every pass's pipelines exist before the first
114
+ * frame. Default `true`.
115
+ *
116
+ * `compileAsync` builds only the main-pass pipelines. A shadow-casting light's shadow map and a
117
+ * reflection pass each need their own variants, created synchronously on first use — on a native
118
+ * Midway launch that was **44–107 pipelines after "ready"**, with freezes up to 615 ms. One
119
+ * hidden render of the warm scene, with the shadow map forced to update, builds them while the
120
+ * startup cover is still up. The render is invisible (it does not clear, and its output is
121
+ * behind the loading layer) and restores every renderer and scene state it touches.
122
+ *
123
+ * Set `false` to skip it. The warm-up still reports `passes: []` and `passPipelines: 0`, because
124
+ * turning a convention off must not turn its measurement off.
125
+ */
126
+ readonly renderPasses?: boolean;
127
+ /**
128
+ * Also render objects the scene has hidden for that one covered render. Default `false`.
129
+ *
130
+ * `renderPasses` already disables frustum culling, so every caster is submitted to the shadow
131
+ * pass and every reflected object to the reflection pass even when the startup camera cannot see
132
+ * it. A hidden LOD level or a parked model is still skipped, though: three never draws a subtree
133
+ * whose ancestor's `visible` is false, so its shadow and reflection pipelines stay unbuilt. With
134
+ * this on, the warm-up forces every hidden object visible for that one render — ancestors
135
+ * included — and restores every original `visible` exactly afterwards. The count is reported as
136
+ * `visibilityForced`, so a game can see how much of its scene the render had to un-hide.
137
+ */
138
+ readonly includeHidden?: boolean;
139
+ /** The scene that supplies lights and environment when `scene` is an unattached object. */
140
+ readonly targetScene?: Object3D;
141
+ }
142
+
143
+ /** What the warm-up did, so a caller can report it rather than assume it. */
144
+ export type WarmUpObservationStatus = "complete" | "incomplete" | "unavailable";
145
+
146
+ export interface IWarmUpObservation {
147
+ /** Pipeline creations observed between the census snapshots. */
148
+ readonly created: number;
149
+ /** Pipeline creations that failed between the census snapshots. */
150
+ readonly failed: number;
151
+ /** Pipeline creations still pending at the ending census snapshot, delta-adjusted. */
152
+ readonly pending: number;
153
+ /** New shader-program identities observed between the census snapshots. */
154
+ readonly uniquePrograms: number;
155
+ /** New backend pipeline identities observed between the census snapshots. */
156
+ readonly uniquePipelines: number;
157
+ /** Whether the renderer supplied a complete observation for this warm-up. */
158
+ readonly status: WarmUpObservationStatus;
159
+ }
160
+
161
+ export interface IWarmUpReport {
162
+ /** Compile calls that settled successfully; retained for compatibility with existing callers. */
163
+ readonly compiled: number;
164
+ /**
165
+ * @deprecated Candidate count retained under the old public name. Use `candidates` for its
166
+ * actual unit and `observed` for backend-created pipelines.
167
+ */
168
+ readonly pipelines: number;
169
+ /** Renderable objects selected for warm-up, before backend cache identity is known. */
170
+ readonly candidates: number;
171
+ /** Number of compileAsync calls attempted, including rejected and timed-out calls. */
172
+ readonly attempted: number;
173
+ /** Backend creation counts observed between the warm-up's start and end snapshots. */
174
+ readonly observed: IWarmUpObservation;
175
+ /** Slices the work was cut into, and therefore the frames the loop got to present. */
176
+ readonly slices: number;
177
+ /** Wall-clock milliseconds the warm-up took, compiling and yielding together. */
178
+ readonly elapsedMs: number;
179
+ /**
180
+ * True when the renderer had no `compileAsync` to call — a WebGL renderer, or a stub.
181
+ *
182
+ * Reported rather than silently skipped: "the warm-up ran and found nothing to do" and "this
183
+ * renderer cannot warm up" produce the same zero, and only one of them is a reason a launch
184
+ * still stalls.
185
+ */
186
+ readonly unsupported: boolean;
187
+ /**
188
+ * Pipelines whose compile never came back inside `compileTimeoutMs`, and pipelines never
189
+ * reached because the whole warm-up ran out of budget.
190
+ *
191
+ * Reported, never thrown. A warm-up is an optimization on the launch path: the one thing it must
192
+ * never do is stop the game from starting, and the first version of this did exactly that — a
193
+ * `compileAsync` that never resolved on the device left `#boot` awaiting forever, so the loop
194
+ * stayed held, the simulation never advanced and the game sat on its loading screen. A launch
195
+ * that is slower than it could be is a disappointment; a launch that never finishes is a bug.
196
+ */
197
+ readonly abandoned: number;
198
+ /** True when the overall budget ran out before every pipeline was warmed. */
199
+ readonly timedOut: boolean;
200
+ /** Compute kernels compiled before the scene pipelines. Present only when computeNodes was set. */
201
+ readonly computeCompiled?: number;
202
+ /** Compute kernels that rejected or exceeded their bound. Present only when computeNodes was set. */
203
+ readonly computeAbandoned?: number;
204
+ /** True when the renderer exposed no computeAsync seam. Present only when computeNodes was set. */
205
+ readonly computeUnsupported?: boolean;
206
+ /** True when compute warm-up consumed the startup budget. Present only when computeNodes was set. */
207
+ readonly computeTimedOut?: boolean;
208
+ /** The optional persistent warm-up hint's outcome. */
209
+ readonly cache?: WarmUpCacheStatus;
210
+ /**
211
+ * The passes the hidden warm render exercised: `main` always, plus `shadow` when a shadow-casting
212
+ * light is present and `reflection` when a reflector node is reachable from a material. Empty when
213
+ * `renderPasses` was off, so an overridden convention still reports what it did. Absent when the
214
+ * renderer exposes no `render` at all.
215
+ */
216
+ readonly passes?: readonly string[];
217
+ /** Backend pipelines observed created by the hidden warm render alone. Absent with `passes`. */
218
+ readonly passPipelines?: number;
219
+ /** Objects whose `frustumCulled` the warm render turned off, so off-screen casters were submitted. */
220
+ readonly cullingForced?: number;
221
+ /** Hidden objects the warm render forced visible (`includeHidden`); zero when it was off. */
222
+ readonly visibilityForced?: number;
223
+ }
224
+
225
+ /** The narrow slice of the renderer this needs. Structural so a test needs no renderer. */
226
+ export interface IWarmUpRenderer {
227
+ compileAsync?: (scene: Object3D, camera: Camera, targetScene?: Object3D) => Promise<void>;
228
+ computeAsync?: (node: unknown) => Promise<void>;
229
+ pipelineCensus?: () => IPipelineCensus;
230
+ /**
231
+ * Performs one covered output-pipeline render without marking first present.
232
+ *
233
+ * May settle later than it returns: a renderer whose pipeline creation is asynchronous
234
+ * (Three's `createRenderPipelineAsync` with its pending/skip draw check) starts the work here
235
+ * and resolves once every requested pipeline exists, so the warm-up can wait instead of
236
+ * compiling on the main thread.
237
+ */
238
+ warmUpWorldPass?: (
239
+ scene: Object3D,
240
+ camera: Camera,
241
+ targetScene?: Object3D,
242
+ ) => void | Promise<void>;
243
+ /** The renderer's own render path, used to build every pass's pipelines once. */
244
+ render?: (scene: Object3D, camera: Camera) => void;
245
+ raw?: unknown;
246
+ }
247
+
248
+ /** The patched static on PMREMNode, reached through a node instance because the native catalog binds no PMREMNode class. */
249
+ interface IPMREMNodeClass {
250
+ prepareTextureAsync?(renderer: unknown, texture: Texture): Promise<boolean>;
251
+ }
252
+
253
+ /** The native engine's facade bakes the environment itself; warm-up draws the held scene until it is done. */
254
+ interface INativeEnvironmentPreparer {
255
+ prepareEnvironmentAsync(scene: Object3D, camera: Camera, deadlineMs: number): Promise<boolean>;
256
+ }
257
+
258
+ function nativeEnvironmentPreparer(raw: unknown): INativeEnvironmentPreparer | undefined {
259
+ return typeof (raw as Partial<INativeEnvironmentPreparer> | null)?.prepareEnvironmentAsync ===
260
+ "function"
261
+ ? (raw as INativeEnvironmentPreparer)
262
+ : undefined;
263
+ }
264
+
265
+ function sceneNeedsEnvironmentPreparation(renderer: IWarmUpRenderer, scene: Object3D): boolean {
266
+ const environment = (scene as Object3D & { environment?: Texture }).environment;
267
+ if (environment?.isTexture !== true) return false;
268
+
269
+ const raw = renderer.raw;
270
+ if (typeof raw !== "object" || raw === null) return false;
271
+ if (nativeEnvironmentPreparer(raw) !== undefined) return true;
272
+ const backend = (raw as { backend?: { isWebGPUBackend?: boolean } }).backend;
273
+ return backend?.isWebGPUBackend === true;
274
+ }
275
+
276
+ async function prepareSceneEnvironment(
277
+ renderer: IWarmUpRenderer,
278
+ scene: Object3D,
279
+ camera: Camera,
280
+ deadlineMs: number,
281
+ ): Promise<boolean> {
282
+ const environment = (scene as Object3D & { environment?: Texture }).environment;
283
+ if (environment?.isTexture !== true) return true;
284
+
285
+ const raw = renderer.raw;
286
+ if (typeof raw !== "object" || raw === null) return true;
287
+ const native = nativeEnvironmentPreparer(raw);
288
+ if (native !== undefined) return native.prepareEnvironmentAsync(scene, camera, deadlineMs);
289
+ const backend = (raw as { backend?: { isWebGPUBackend?: boolean } }).backend;
290
+ if (backend?.isWebGPUBackend !== true) return true;
291
+
292
+ const PMREMNode = pmremTexture(environment).constructor as IPMREMNodeClass;
293
+ const prepare = PMREMNode.prepareTextureAsync;
294
+ if (typeof prepare !== "function") {
295
+ throw new Error(
296
+ "TN_PMREM_ASYNC_PREPARER_UNAVAILABLE: patched Three.js has no PMREM cache preparer.",
297
+ );
298
+ }
299
+ return prepare.call(PMREMNode, raw, environment);
300
+ }
301
+
302
+ const DEFAULT_SLICE_SIZE = 24;
303
+ const DEFAULT_COMPILE_TIMEOUT_MS = 2000;
304
+ const DEFAULT_BUDGET_MS = 15000;
305
+ const WARM_UP_CACHE_SCHEMA = 2;
306
+ const WARM_UP_CACHE_PREFIX = "threenative:warm-up:";
307
+
308
+ interface IWarmUpCacheIdentity {
309
+ readonly key: string;
310
+ readonly storageKey: string;
311
+ }
312
+
313
+ interface IWarmUpCacheRecord {
314
+ readonly schema: number;
315
+ readonly key: string;
316
+ readonly pipelines: number;
317
+ readonly computeNodes: number;
318
+ }
319
+
320
+ function warmUpCacheIdentity(
321
+ cache: IWarmUpCacheOptions | undefined,
322
+ ): IWarmUpCacheIdentity | undefined {
323
+ if (cache === undefined) return undefined;
324
+ if (
325
+ typeof cache !== "object" ||
326
+ cache === null ||
327
+ typeof cache.key !== "string" ||
328
+ cache.key.trim() === ""
329
+ ) {
330
+ throw new Error(
331
+ "TN_WARMUP_CACHE_INVALID: cache.key must be a non-empty string that changes with the game's render inputs.",
332
+ );
333
+ }
334
+ return { key: cache.key, storageKey: `${WARM_UP_CACHE_PREFIX}${cache.key}` };
335
+ }
336
+
337
+ function warmUpStorage(): Storage | undefined {
338
+ try {
339
+ return typeof globalThis.localStorage === "object" ? globalThis.localStorage : undefined;
340
+ } catch {
341
+ return undefined;
342
+ }
343
+ }
344
+
345
+ function readWarmUpCache(
346
+ identity: IWarmUpCacheIdentity | undefined,
347
+ pipelines: number,
348
+ computeNodes: number,
349
+ ): WarmUpCacheStatus {
350
+ if (identity === undefined) return "disabled";
351
+ const storage = warmUpStorage();
352
+ if (storage === undefined) return "unavailable";
353
+ try {
354
+ const raw = storage.getItem(identity.storageKey);
355
+ if (raw === null) return "miss";
356
+ const value: unknown = JSON.parse(raw);
357
+ if (
358
+ typeof value !== "object" ||
359
+ value === null ||
360
+ (value as Partial<IWarmUpCacheRecord>).schema !== WARM_UP_CACHE_SCHEMA ||
361
+ (value as Partial<IWarmUpCacheRecord>).key !== identity.key ||
362
+ (value as Partial<IWarmUpCacheRecord>).pipelines !== pipelines ||
363
+ (value as Partial<IWarmUpCacheRecord>).computeNodes !== computeNodes
364
+ ) {
365
+ storage.removeItem(identity.storageKey);
366
+ return "miss";
367
+ }
368
+ return "hit";
369
+ } catch {
370
+ return "unavailable";
371
+ }
372
+ }
373
+
374
+ function storeWarmUpCache(
375
+ identity: IWarmUpCacheIdentity | undefined,
376
+ pipelines: number,
377
+ computeNodes: number,
378
+ ): WarmUpCacheStatus {
379
+ if (identity === undefined) return "disabled";
380
+ const storage = warmUpStorage();
381
+ if (storage === undefined) return "unavailable";
382
+ try {
383
+ storage.setItem(
384
+ identity.storageKey,
385
+ JSON.stringify({
386
+ schema: WARM_UP_CACHE_SCHEMA,
387
+ key: identity.key,
388
+ pipelines,
389
+ computeNodes,
390
+ } satisfies IWarmUpCacheRecord),
391
+ );
392
+ return "stored";
393
+ } catch {
394
+ return "unavailable";
395
+ }
396
+ }
397
+
398
+ export interface IComputeWarmUpReport {
399
+ readonly compiled: number;
400
+ readonly abandoned: number;
401
+ readonly unsupported: boolean;
402
+ readonly timedOut: boolean;
403
+ }
404
+
405
+ function computeAsyncOf(renderer: IWarmUpRenderer): ((node: unknown) => Promise<void>) | undefined {
406
+ const receiver = typeof renderer.computeAsync === "function" ? renderer : renderer.raw;
407
+ if (typeof receiver !== "object" || receiver === null) return undefined;
408
+ const { backend, computeAsync } = receiver as {
409
+ backend?: { isWebGPUBackend?: boolean };
410
+ computeAsync?: (node: unknown, dispatchSize?: number) => Promise<void>;
411
+ };
412
+ if (typeof computeAsync !== "function") return undefined;
413
+ // WebGPU compiles zero workgroups without running a solver against its live storage buffers.
414
+ return backend?.isWebGPUBackend === true
415
+ ? (node) => computeAsync.call(receiver, node, 0)
416
+ : computeAsync.bind(receiver);
417
+ }
418
+
419
+ /**
420
+ * Resolves when `work` settles or when `limitMs` elapses, whichever comes first.
421
+ *
422
+ * Returns whether the work actually finished, because "compiled" and "gave up waiting" are
423
+ * different facts and the report has to be able to tell them apart.
424
+ */
425
+ async function yieldThroughHost(yieldFrame: () => Promise<void>): Promise<void> {
426
+ // Native async pipeline promises are settled from pollEvents(), so awaiting only the compile
427
+ // promise from inside a timer or rAF callback can deadlock the host: the callback cannot return
428
+ // to pollEvents() until the promise settles. Keep the caller's yield signal, and also force one
429
+ // macrotask so tests and browser shims that resolve their signal immediately cannot starve the
430
+ // host timer queue while a compile is still pending.
431
+ await Promise.all([
432
+ Promise.resolve()
433
+ .then(yieldFrame)
434
+ .catch(() => undefined),
435
+ new Promise<void>((resolve) => setTimeout(resolve, 0)),
436
+ ]);
437
+ }
438
+
439
+ /**
440
+ * @internal Shared with `world-cells.ts`, whose streamed chunks warm up on the same bound: a
441
+ * compile that never settles must not hold an object out of the world for the rest of the session.
442
+ */
443
+ export async function within(
444
+ work: Promise<unknown>,
445
+ limitMs: number,
446
+ yieldFrame: () => Promise<void>,
447
+ now: () => number,
448
+ ): Promise<boolean> {
449
+ return withinDeadline(now() + limitMs, work, yieldFrame, now);
450
+ }
451
+
452
+ // Keep the deadline established before invoking a compiler's synchronous prefix. This does not
453
+ // interrupt that work; it prevents the promise wait or cached completion granting extra budget.
454
+ async function withinDeadline(
455
+ deadline: number,
456
+ work: Promise<unknown>,
457
+ yieldFrame: () => Promise<void>,
458
+ now: () => number,
459
+ ): Promise<boolean> {
460
+ // A rejected compile is a pipeline this warm-up could not build, not a reason to fail the
461
+ // launch: the frame that needs it will try again and fail there, where the error belongs.
462
+ let settled: boolean | undefined;
463
+ const completion = work.then(
464
+ () => {
465
+ settled = true;
466
+ return true;
467
+ },
468
+ () => {
469
+ settled = false;
470
+ return false;
471
+ },
472
+ );
473
+ // Do not ask the host for a turn when a normal synchronous or already-cached compile has
474
+ // settled. This preserves the existing slice cadence for fakes and desktop renderers.
475
+ await Promise.resolve();
476
+ if (now() >= deadline) return false;
477
+ if (settled !== undefined) return settled;
478
+ while (now() < deadline) {
479
+ if (settled !== undefined) return settled;
480
+ let timer: ReturnType<typeof setTimeout> | undefined;
481
+ const remaining = Math.max(0, deadline - now());
482
+ const expiry = new Promise<"timeout">((resolve) => {
483
+ timer = setTimeout(() => resolve("timeout"), remaining);
484
+ });
485
+ const result = await Promise.race([
486
+ completion.then((value) => ({ kind: "complete" as const, value })),
487
+ yieldThroughHost(yieldFrame).then(() => ({ kind: "yield" as const })),
488
+ expiry,
489
+ ]);
490
+ if (timer !== undefined) clearTimeout(timer);
491
+ if (result === "timeout") return false;
492
+ if (result.kind === "complete") return now() < deadline && result.value;
493
+ }
494
+ return false;
495
+ }
496
+
497
+ async function runComputeWarmUp(
498
+ renderer: IWarmUpRenderer,
499
+ nodes: readonly unknown[],
500
+ compileTimeoutMs: number,
501
+ deadline: number,
502
+ now: () => number,
503
+ yieldFrame: () => Promise<void>,
504
+ ): Promise<IComputeWarmUpReport> {
505
+ const computeAsync = computeAsyncOf(renderer);
506
+ if (computeAsync === undefined) {
507
+ return { compiled: 0, abandoned: 0, unsupported: true, timedOut: false };
508
+ }
509
+
510
+ let compiled = 0;
511
+ let abandoned = 0;
512
+ let timedOut = false;
513
+ for (let index = 0; index < nodes.length; index += 1) {
514
+ const remaining = deadline - now();
515
+ if (remaining <= 0) {
516
+ timedOut = true;
517
+ abandoned += nodes.length - index;
518
+ break;
519
+ }
520
+ const finished = await withinDeadline(
521
+ Math.min(deadline, now() + compileTimeoutMs),
522
+ Promise.resolve().then(() => computeAsync(nodes[index])),
523
+ yieldFrame,
524
+ now,
525
+ );
526
+ if (finished) compiled += 1;
527
+ else abandoned += 1;
528
+ if (now() >= deadline && (!finished || index + 1 < nodes.length)) {
529
+ timedOut = true;
530
+ abandoned += nodes.length - index - 1;
531
+ break;
532
+ }
533
+ }
534
+ return { compiled, abandoned, unsupported: false, timedOut };
535
+ }
536
+
537
+ /** @internal Compile compute kernels without also compiling a scene's render pipelines. */
538
+ export async function warmUpComputeNodes(
539
+ renderer: IWarmUpRenderer,
540
+ nodes: readonly unknown[],
541
+ options: Pick<IWarmUpOptions, "budgetMs" | "compileTimeoutMs" | "yieldFrame"> = {},
542
+ ): Promise<IComputeWarmUpReport> {
543
+ const compileTimeoutMs = options.compileTimeoutMs ?? DEFAULT_COMPILE_TIMEOUT_MS;
544
+ const budgetMs = options.budgetMs ?? DEFAULT_BUDGET_MS;
545
+ for (const [name, value] of [
546
+ ["compileTimeoutMs", compileTimeoutMs],
547
+ ["budgetMs", budgetMs],
548
+ ] as const) {
549
+ if (!Number.isFinite(value) || value <= 0) {
550
+ throw new Error(
551
+ `TN_WARMUP_TIMEOUT_INVALID: ${name} must be a positive number of milliseconds, received ${String(value)}.`,
552
+ );
553
+ }
554
+ }
555
+ const now = (): number => globalThis.performance?.now() ?? Date.now();
556
+ return runComputeWarmUp(
557
+ renderer,
558
+ nodes,
559
+ compileTimeoutMs,
560
+ now() + budgetMs,
561
+ now,
562
+ options.yieldFrame ?? yieldToHost,
563
+ );
564
+ }
565
+
566
+ function withComputeReport(report: IWarmUpReport, compute: IComputeWarmUpReport): IWarmUpReport {
567
+ return {
568
+ ...report,
569
+ computeCompiled: compute.compiled,
570
+ computeAbandoned: compute.abandoned,
571
+ computeUnsupported: compute.unsupported,
572
+ computeTimedOut: compute.timedOut,
573
+ };
574
+ }
575
+
576
+ /**
577
+ * Hands the host one loop iteration, so it can present a frame, and never waits on anything.
578
+ *
579
+ * Two wrong versions came before this one, and both are worth keeping written down.
580
+ *
581
+ * Awaiting `requestAnimationFrame` **deadlocks**. Boot is what schedules frames, so on a host
582
+ * where frames are pumped by the same code waiting for boot to finish, the warm-up waits for a
583
+ * callback that cannot run until it stops waiting. The playtest harness is exactly that: its
584
+ * `requestAnimationFrame` pushes the callback onto an array the test drains *after* `start()`
585
+ * resolves. Two suite tests hung for their full timeout.
586
+ *
587
+ * Racing `requestAnimationFrame` against a timer fixes the hang but **registers a frame callback
588
+ * that is not the loop's**, which reorders the frame sequence any harness driving rAF by hand
589
+ * observes. It turned a 16 ms frame into a 32 ms one in the performance suite.
590
+ *
591
+ * So the warm-up asks for no frame at all: it yields the thread and lets the host's own loop do
592
+ * what it was already going to do. On the native runtime — the platform where the 24.5 second
593
+ * stall this exists for actually lives — the host drains `scheduler.yield` continuations in a
594
+ * bounded slice between frames, so frames keep presenting. Nothing is registered, nothing is
595
+ * waited on, and the loop's frame sequence is the one the loop authored.
596
+ */
597
+ /**
598
+ * `scheduler.yield` first, where the host has it. A nested `setTimeout(0)` is clamped to 4 ms in
599
+ * Chrome (4.56 ms measured, against 0.009 ms), which left an 8 ms slice idle a third of the time.
600
+ * The native host installs `scheduler.yield` and drains it between frames, while its timer queue
601
+ * is frame-coupled, so a timer yield there costs one whole frame per slice.
602
+ *
603
+ * @internal Shared with `streaming.ts`, whose slices and lanes want the same yield.
604
+ */
605
+ export const yieldToHost = (): Promise<void> => {
606
+ const host = (globalThis as { scheduler?: { yield?: () => Promise<void> } }).scheduler;
607
+ if (typeof host?.yield === "function") return host.yield();
608
+ return new Promise((resolve) => {
609
+ setTimeout(resolve, 0);
610
+ });
611
+ };
612
+
613
+ /**
614
+ * Collects every renderable object in traversal order.
615
+ *
616
+ * Only renderables: a `Group` or a `Bone` carries no material, and compiling it would walk its
617
+ * whole subtree again, turning a linear pass into a quadratic one on a deep scene.
618
+ */
619
+ function collectRenderables(root: Object3D): Object3D[] {
620
+ const found: Object3D[] = [];
621
+ const stack: Object3D[] = [root];
622
+ while (stack.length > 0) {
623
+ const object = stack.pop() as Object3D;
624
+ if ((object as Object3D & { material?: unknown }).material !== undefined) found.push(object);
625
+ // A structural stand-in for a scene may carry no children at all; count what is there.
626
+ const children = object.children ?? [];
627
+ for (let index = children.length - 1; index >= 0; index -= 1) {
628
+ stack.push(children[index] as Object3D);
629
+ }
630
+ }
631
+ return found;
632
+ }
633
+
634
+ function readPipelineCensus(renderer: IWarmUpRenderer): IPipelineCensus | undefined {
635
+ if (typeof renderer.pipelineCensus !== "function") return undefined;
636
+ try {
637
+ return renderer.pipelineCensus();
638
+ } catch {
639
+ return undefined;
640
+ }
641
+ }
642
+
643
+ function censusDelta(
644
+ before: IPipelineCensus | undefined,
645
+ after: IPipelineCensus | undefined,
646
+ key: "creations" | "failures" | "pending" | "uniquePrograms" | "uniquePipelines",
647
+ ): number {
648
+ if (after === undefined) return 0;
649
+ return Math.max(0, after.counts[key] - (before?.counts[key] ?? 0));
650
+ }
651
+
652
+ function observePipelineCensus(
653
+ before: IPipelineCensus | undefined,
654
+ after: IPipelineCensus | undefined,
655
+ ): IWarmUpObservation {
656
+ const status: WarmUpObservationStatus =
657
+ after === undefined || after.unsupported
658
+ ? "unavailable"
659
+ : after.complete
660
+ ? "complete"
661
+ : "incomplete";
662
+ return {
663
+ created: censusDelta(before, after, "creations"),
664
+ failed: censusDelta(before, after, "failures"),
665
+ pending: censusDelta(before, after, "pending"),
666
+ uniquePrograms: censusDelta(before, after, "uniquePrograms"),
667
+ uniquePipelines: censusDelta(before, after, "uniquePipelines"),
668
+ status,
669
+ };
670
+ }
671
+
672
+ function reconcileWarmUpObservation(report: IWarmUpReport): IWarmUpReport {
673
+ const unavailable = report.unsupported || report.computeUnsupported === true;
674
+ const incomplete =
675
+ report.abandoned > 0 ||
676
+ report.timedOut ||
677
+ report.computeTimedOut === true ||
678
+ (report.computeAbandoned ?? 0) > 0;
679
+ const status = unavailable
680
+ ? "unavailable"
681
+ : incomplete && report.observed.status === "complete"
682
+ ? "incomplete"
683
+ : report.observed.status;
684
+ return status === report.observed.status
685
+ ? report
686
+ : { ...report, observed: { ...report.observed, status } };
687
+ }
688
+
689
+ /**
690
+ * The renderer state the hidden warm render touches, read structurally so a fake needs no renderer.
691
+ *
692
+ * `autoClear`, `shadowMap.needsUpdate` and the current render target are the three things a render
693
+ * can leave changed; every one of them is restored in a `finally`, so a warm-up can never alter
694
+ * what the game's first real frame draws.
695
+ */
696
+ interface IWarmRenderHost {
697
+ autoClear?: boolean;
698
+ shadowMap?: { enabled?: boolean; needsUpdate?: boolean };
699
+ getRenderTarget?: () => unknown;
700
+ setRenderTarget?: (target: unknown) => void;
701
+ }
702
+
703
+ interface IWarmPassRender {
704
+ readonly passes: readonly string[];
705
+ readonly created: number;
706
+ readonly elapsedMs: number;
707
+ readonly cullingForced: number;
708
+ readonly visibilityForced: number;
709
+ }
710
+
711
+ /** The scene-graph state the warm render turns off and must put back exactly. */
712
+ interface IWarmVisibilityHost {
713
+ frustumCulled?: boolean;
714
+ visible?: boolean;
715
+ }
716
+
717
+ interface IRestoredVisibility {
718
+ readonly object: IWarmVisibilityHost;
719
+ /** Set only when this warm render turned the object's culling off. */
720
+ readonly frustumCulled?: boolean;
721
+ /** Set only when this warm render forced the object visible. */
722
+ readonly visible?: boolean;
723
+ }
724
+
725
+ /** A shadow map is rendered for every shadow-casting light; nothing else triggers that pass. */
726
+ function hasShadowCaster(scene: Object3D): boolean {
727
+ const stack: Object3D[] = [scene];
728
+ while (stack.length > 0) {
729
+ const object = stack.pop() as Object3D & { isLight?: boolean; castShadow?: boolean };
730
+ if (object.isLight === true && object.castShadow === true) return true;
731
+ const children = object.children ?? [];
732
+ for (const child of children) stack.push(child as Object3D);
733
+ }
734
+ return false;
735
+ }
736
+
737
+ interface IReflectorNodeLike {
738
+ readonly isNode?: boolean;
739
+ readonly _reflectorBaseNode?: unknown;
740
+ getChildren?: () => Iterable<unknown>;
741
+ }
742
+
743
+ /**
744
+ * Whether a TSL node graph contains a reflector.
745
+ *
746
+ * Three's `reflector()` hangs a `_reflectorBaseNode` off a `ReflectorNode` that a material's
747
+ * `colorNode` (or a node composed around it) references. The walk is bounded and only descends
748
+ * real nodes, so a material with no reflector costs one shallow pass.
749
+ */
750
+ function nodeHasReflector(root: unknown, depth: number): boolean {
751
+ if (depth > 64 || typeof root !== "object" || root === null) return false;
752
+ const node = root as IReflectorNodeLike;
753
+ if (node._reflectorBaseNode !== undefined) return true;
754
+ if (node.isNode !== true || typeof node.getChildren !== "function") return false;
755
+ try {
756
+ for (const child of node.getChildren()) {
757
+ if (nodeHasReflector(child, depth + 1)) return true;
758
+ }
759
+ } catch {
760
+ return false;
761
+ }
762
+ return false;
763
+ }
764
+
765
+ function hasReflector(scene: Object3D): boolean {
766
+ const stack: Object3D[] = [scene];
767
+ while (stack.length > 0) {
768
+ const object = stack.pop() as Object3D & { material?: unknown };
769
+ const material = object.material;
770
+ if (
771
+ typeof material === "object" &&
772
+ material !== null &&
773
+ (material as { isNodeMaterial?: boolean }).isNodeMaterial === true
774
+ ) {
775
+ for (const value of Object.values(material as Record<string, unknown>)) {
776
+ if (nodeHasReflector(value, 0)) return true;
777
+ }
778
+ }
779
+ const children = object.children ?? [];
780
+ for (const child of children) stack.push(child as Object3D);
781
+ }
782
+ return false;
783
+ }
784
+
785
+ /**
786
+ * One hidden render of the warm scene, so every pass three will run builds its pipelines now.
787
+ *
788
+ * `compileAsync` covers the main pass only. The shadow map for each shadow-casting light and each
789
+ * reflection pass are created synchronously the first time the scene is drawn — mid-game, on the
790
+ * main thread, inside a frame the player watches. Rendering the scene once here moves that cost
791
+ * behind the startup cover. The render is invisible: `autoClear` is turned off so it cannot wipe a
792
+ * loading frame, and the output stays behind the opaque cover. `shadowMap.needsUpdate` is forced
793
+ * so a game that renders its shadows once (`autoUpdate = false`) still builds them.
794
+ *
795
+ * Frustum culling is turned off for that one render: an object the startup camera cannot see is
796
+ * exactly the object whose shadow and reflection pipelines are missing at startup, so every caster
797
+ * must be submitted. With `includeHidden`, every hidden object is also forced visible, because
798
+ * three never draws a subtree behind a hidden ancestor. Both are restored exactly in a `finally`.
799
+ *
800
+ * Returns `undefined` when the renderer exposes no `render`, so a stub renderer is skipped rather
801
+ * than reported as a pass render that did nothing.
802
+ */
803
+ async function renderWarmPasses(
804
+ renderer: IWarmUpRenderer,
805
+ scene: Object3D,
806
+ camera: Camera,
807
+ enabled: boolean,
808
+ includeHidden: boolean,
809
+ targetScene?: Object3D,
810
+ ): Promise<IWarmPassRender | undefined> {
811
+ const coveredWorldPass = renderer.warmUpWorldPass;
812
+ const render =
813
+ coveredWorldPass === undefined
814
+ ? renderer.render === undefined
815
+ ? undefined
816
+ : () => renderer.render?.(scene, camera)
817
+ : () => coveredWorldPass(scene, camera, targetScene);
818
+ if (render === undefined) return undefined;
819
+ const skipped: IWarmPassRender = {
820
+ passes: [],
821
+ created: 0,
822
+ elapsedMs: 0,
823
+ cullingForced: 0,
824
+ visibilityForced: 0,
825
+ };
826
+ // `renderPasses: false` disables optional shadow/reflection work, but an output pipeline's world
827
+ // pass is the shared fallback for a chunk/cell compile and must still be covered once.
828
+ if (!enabled && coveredWorldPass === undefined) return skipped;
829
+ const raw =
830
+ typeof renderer.raw === "object" && renderer.raw !== null
831
+ ? (renderer.raw as IWarmRenderHost)
832
+ : undefined;
833
+ const shadowMap = raw?.shadowMap;
834
+ const passes: string[] = ["main"];
835
+ if (enabled && shadowMap?.enabled !== false && hasShadowCaster(scene)) passes.push("shadow");
836
+ if (enabled && hasReflector(scene)) passes.push("reflection");
837
+ // `compileAsync` already built the main pass. A scene with neither a shadow map nor a reflection
838
+ // has no second pass to build, so rendering it again would only draw a frame the cover hides for
839
+ // nothing. Skip the draw and report the one pass that was compiled.
840
+ if (passes.length === 1 && renderer.warmUpWorldPass === undefined) return { ...skipped, passes };
841
+
842
+ const censusBefore = readPipelineCensus(renderer);
843
+ const sceneVisible = (scene as IWarmVisibilityHost).visible;
844
+ const hadOwnAutoClear = raw !== undefined && Object.hasOwn(raw, "autoClear");
845
+ const autoClear = raw?.autoClear;
846
+ const shadowNeedsUpdate = shadowMap?.needsUpdate;
847
+ const previousTarget = raw?.getRenderTarget?.();
848
+ // One walk remembers every original value, so the restore is exact and covers hidden ancestors.
849
+ const restored: IRestoredVisibility[] = [];
850
+ let cullingForced = 0;
851
+ let visibilityForced = 0;
852
+ const stack: Object3D[] = [scene];
853
+ while (stack.length > 0) {
854
+ const object = stack.pop() as Object3D & IWarmVisibilityHost;
855
+ const children = object.children ?? [];
856
+ for (const child of children) stack.push(child as Object3D);
857
+ const entry: { object: IWarmVisibilityHost; frustumCulled?: boolean; visible?: boolean } = {
858
+ object,
859
+ };
860
+ if (object.frustumCulled === true) {
861
+ entry.frustumCulled = true;
862
+ object.frustumCulled = false;
863
+ cullingForced += 1;
864
+ }
865
+ // The root's own visibility is forced below whether or not hidden objects are included, so it
866
+ // is not counted here; a hidden child or group is.
867
+ if (includeHidden && object !== scene && object.visible === false) {
868
+ entry.visible = false;
869
+ object.visible = true;
870
+ visibilityForced += 1;
871
+ }
872
+ if (entry.frustumCulled !== undefined || entry.visible !== undefined) restored.push(entry);
873
+ }
874
+
875
+ const startedAt = globalThis.performance?.now() ?? Date.now();
876
+ try {
877
+ // The render is the mechanism; nothing about the frame it would have drawn is kept.
878
+ if (sceneVisible === false) (scene as IWarmVisibilityHost).visible = true;
879
+ if (raw !== undefined) raw.autoClear = false;
880
+ if (shadowMap !== undefined) shadowMap.needsUpdate = true;
881
+ await render();
882
+ } finally {
883
+ if (raw !== undefined) {
884
+ if (hadOwnAutoClear) raw.autoClear = autoClear;
885
+ else Reflect.deleteProperty(raw, "autoClear");
886
+ if (
887
+ raw.setRenderTarget !== undefined &&
888
+ previousTarget !== undefined &&
889
+ previousTarget !== null
890
+ )
891
+ raw.setRenderTarget(previousTarget);
892
+ }
893
+ if (shadowMap !== undefined) shadowMap.needsUpdate = shadowNeedsUpdate;
894
+ if (sceneVisible === false) (scene as IWarmVisibilityHost).visible = false;
895
+ for (const entry of restored) {
896
+ if (entry.frustumCulled !== undefined) entry.object.frustumCulled = entry.frustumCulled;
897
+ if (entry.visible !== undefined) entry.object.visible = entry.visible;
898
+ }
899
+ }
900
+ return {
901
+ passes,
902
+ created: censusDelta(censusBefore, readPipelineCensus(renderer), "creations"),
903
+ elapsedMs: (globalThis.performance?.now() ?? Date.now()) - startedAt,
904
+ cullingForced,
905
+ visibilityForced,
906
+ };
907
+ }
908
+
909
+ /**
910
+ * Warms up `scene` for `camera`, in slices, presenting a frame between each.
911
+ *
912
+ * Fail closed on a nonsensical slice size rather than quietly choosing one: a zero or negative
913
+ * slice would loop forever, and a caller that passed it has a bug worth seeing now.
914
+ * @situation compile a scene's shaders during the loading screen instead of on the first frame
915
+ * @situation stop a native launch freezing for seconds inside its first rendered frame
916
+ * @example await warmUpScene(renderer, scene, camera, { onProgress: (p) => setLoading(p) });
917
+ */
918
+ export async function warmUpScene(
919
+ renderer: IWarmUpRenderer,
920
+ scene: Object3D,
921
+ camera: Camera,
922
+ options: IWarmUpOptions = {},
923
+ ): Promise<IWarmUpReport> {
924
+ const sliceSize = options.sliceSize ?? DEFAULT_SLICE_SIZE;
925
+ if (!Number.isInteger(sliceSize) || sliceSize < 1) {
926
+ throw new Error(
927
+ `TN_WARMUP_SLICE_INVALID: sliceSize must be a whole number of objects of at least one, received ${String(
928
+ options.sliceSize,
929
+ )}.`,
930
+ );
931
+ }
932
+ const compileTimeoutMs = options.compileTimeoutMs ?? DEFAULT_COMPILE_TIMEOUT_MS;
933
+ const budgetMs = options.budgetMs ?? DEFAULT_BUDGET_MS;
934
+ const environmentBudgetMs = options.environmentBudgetMs ?? STARTUP_HOLD_BUDGET_MS;
935
+ for (const [name, value] of [
936
+ ["compileTimeoutMs", compileTimeoutMs],
937
+ ["budgetMs", budgetMs],
938
+ ["environmentBudgetMs", environmentBudgetMs],
939
+ ] as const) {
940
+ if (!Number.isFinite(value) || value <= 0) {
941
+ throw new Error(
942
+ `TN_WARMUP_TIMEOUT_INVALID: ${name} must be a positive number of milliseconds, received ${String(value)}.`,
943
+ );
944
+ }
945
+ }
946
+ const now = (): number => globalThis.performance?.now() ?? Date.now();
947
+ const yieldFrame = options.yieldFrame ?? yieldToHost;
948
+ const environmentDeadline = now() + environmentBudgetMs;
949
+ // The compile budget's clock; it restarts once the environment is prepared (see `budgetMs`).
950
+ let startedAt = now();
951
+ let environmentPreparationStarted = false;
952
+ let environmentPrepared = false;
953
+ let environmentPreparation: Promise<void> | undefined;
954
+ const ensureEnvironmentPreparation = (
955
+ targetScene: Object3D = options.targetScene ?? scene,
956
+ ): Promise<void> | undefined => {
957
+ if (!sceneNeedsEnvironmentPreparation(renderer, targetScene)) return undefined;
958
+ if (environmentPreparation === undefined) {
959
+ environmentPreparationStarted = true;
960
+ environmentPreparation = prepareSceneEnvironment(
961
+ renderer,
962
+ targetScene,
963
+ camera,
964
+ environmentDeadline,
965
+ ).then((prepared) => {
966
+ environmentPrepared = prepared;
967
+ if (!prepared) {
968
+ throw new Error(
969
+ "TN_PMREM_PREPARATION_INCOMPLETE: the scene environment was not prepared.",
970
+ );
971
+ }
972
+ });
973
+ }
974
+ return environmentPreparation;
975
+ };
976
+ const computeNodes = options.computeNodes ?? [];
977
+ const renderables = collectRenderables(scene);
978
+ const candidates = renderables.length;
979
+ const censusBefore = readPipelineCensus(renderer);
980
+ const cacheIdentity = warmUpCacheIdentity(options.cache);
981
+ let cacheStatus = readWarmUpCache(cacheIdentity, candidates, computeNodes.length);
982
+
983
+ // Lighting first, on its own budget: every compile below waits on this same preparation, so a
984
+ // bake that outlasts the compile budget must not spend it. Settled or given up, the compile
985
+ // budget starts now.
986
+ const upfront = ensureEnvironmentPreparation();
987
+ if (upfront !== undefined) {
988
+ if (!(await withinDeadline(environmentDeadline, upfront, yieldFrame, now))) {
989
+ // Every compile would wait on this same preparation, so none is started.
990
+ return reconcileWarmUpObservation({
991
+ compiled: 0,
992
+ pipelines: candidates,
993
+ candidates,
994
+ attempted: 0,
995
+ observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
996
+ slices: 0,
997
+ elapsedMs: now() - startedAt,
998
+ unsupported: false,
999
+ abandoned: 1,
1000
+ timedOut: now() >= environmentDeadline,
1001
+ cache: cacheStatus,
1002
+ });
1003
+ }
1004
+ startedAt = now();
1005
+ }
1006
+
1007
+ // A hit means the previous complete warm-up gave the platform a chance to populate its own
1008
+ // persistent driver cache. WebGPU has no portable serialized pipeline to restore, so the marker
1009
+ // only skips the redundant compile walk; a changed game-owned key is a deliberate invalidation.
1010
+ if (cacheStatus === "hit" && typeof renderer.compileAsync === "function") {
1011
+ const computeSupported = computeNodes.length === 0 || computeAsyncOf(renderer) !== undefined;
1012
+ if (computeSupported) {
1013
+ const preparation = ensureEnvironmentPreparation();
1014
+ if (
1015
+ preparation !== undefined &&
1016
+ !(await withinDeadline(startedAt + budgetMs, preparation, yieldFrame, now))
1017
+ ) {
1018
+ return reconcileWarmUpObservation({
1019
+ compiled: 0,
1020
+ pipelines: candidates,
1021
+ candidates,
1022
+ attempted: 0,
1023
+ observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
1024
+ slices: 0,
1025
+ elapsedMs: now() - startedAt,
1026
+ unsupported: false,
1027
+ abandoned: 1,
1028
+ timedOut: now() >= startedAt + budgetMs,
1029
+ cache: "hit",
1030
+ });
1031
+ }
1032
+ const report: IWarmUpReport = {
1033
+ compiled: 0,
1034
+ pipelines: candidates,
1035
+ candidates,
1036
+ attempted: 0,
1037
+ observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
1038
+ slices: 0,
1039
+ elapsedMs: now() - startedAt,
1040
+ unsupported: false,
1041
+ abandoned: 0,
1042
+ timedOut: false,
1043
+ cache: "hit",
1044
+ ...(computeNodes.length === 0
1045
+ ? {}
1046
+ : {
1047
+ computeCompiled: 0,
1048
+ computeAbandoned: 0,
1049
+ computeUnsupported: false,
1050
+ computeTimedOut: false,
1051
+ }),
1052
+ };
1053
+ return report;
1054
+ }
1055
+ cacheStatus = "miss";
1056
+ }
1057
+ const compute =
1058
+ computeNodes.length === 0
1059
+ ? undefined
1060
+ : await runComputeWarmUp(
1061
+ renderer,
1062
+ computeNodes,
1063
+ compileTimeoutMs,
1064
+ startedAt + budgetMs,
1065
+ now,
1066
+ yieldFrame,
1067
+ );
1068
+
1069
+ if (typeof renderer.compileAsync !== "function") {
1070
+ const report = reconcileWarmUpObservation({
1071
+ compiled: 0,
1072
+ pipelines: candidates,
1073
+ candidates,
1074
+ attempted: 0,
1075
+ observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
1076
+ slices: 0,
1077
+ elapsedMs: now() - startedAt,
1078
+ unsupported: true,
1079
+ abandoned: 0,
1080
+ timedOut: false,
1081
+ cache: cacheStatus,
1082
+ });
1083
+ return compute === undefined
1084
+ ? report
1085
+ : reconcileWarmUpObservation(withComputeReport(report, compute));
1086
+ }
1087
+ const compileAsync = renderer.compileAsync.bind(renderer);
1088
+ let attempted = 0;
1089
+ const invokeCompile = (object: Object3D, targetScene?: Object3D): Promise<void> => {
1090
+ const compileDeadline =
1091
+ (options.granularity ?? "scene") === "scene"
1092
+ ? startedAt + budgetMs
1093
+ : Math.min(startedAt + budgetMs, now() + compileTimeoutMs);
1094
+ const preparation = ensureEnvironmentPreparation(targetScene ?? scene);
1095
+ const compile = (): Promise<void> => {
1096
+ if (now() >= compileDeadline) {
1097
+ return Promise.reject(
1098
+ new Error("TN_WARMUP_COMPILE_DEADLINE: PMREM preparation consumed this compile slice."),
1099
+ );
1100
+ }
1101
+ attempted += 1;
1102
+ try {
1103
+ return compileAsync(object, camera, targetScene);
1104
+ } catch (error) {
1105
+ return Promise.reject(error);
1106
+ }
1107
+ };
1108
+ return preparation === undefined ? compile() : preparation.then(compile);
1109
+ };
1110
+ const invokeSceneCompile = (): Promise<void> => {
1111
+ const compile = invokeCompile(scene, options.targetScene);
1112
+ // Stock Three compileAsync has no render-depth input, so an output pipeline's covered render
1113
+ // is the only path that can build the world graph against the target the first frame draws.
1114
+ // Its own compile path is still worth running first: it builds every pipeline it can reach
1115
+ // asynchronously and yields while it does, so the covered render that follows finds them in
1116
+ // the cache. A compile failure here is not fatal: the covered render is the fallback, and the
1117
+ // first frame that needs a pipeline will try again where the error belongs.
1118
+ if (renderer.warmUpWorldPass === undefined) return compile;
1119
+ return compile
1120
+ .catch(() => undefined)
1121
+ .then(async () => {
1122
+ const pass = await renderWarmPassesOnce();
1123
+ if (pass === undefined) {
1124
+ throw passError ?? new Error("covered world warm render did not settle");
1125
+ }
1126
+ });
1127
+ };
1128
+
1129
+ let gpuDrainSettled = true;
1130
+ const finish = (report: IWarmUpReport): IWarmUpReport => {
1131
+ const coveredPassIncomplete =
1132
+ renderer.warmUpWorldPass !== undefined && passResult === undefined;
1133
+ const drainNormalized = gpuDrainSettled
1134
+ ? report
1135
+ : {
1136
+ ...report,
1137
+ timedOut: true,
1138
+ };
1139
+ const normalized = coveredPassIncomplete
1140
+ ? {
1141
+ ...drainNormalized,
1142
+ abandoned: Math.max(1, drainNormalized.abandoned),
1143
+ timedOut: drainNormalized.timedOut || now() >= startedAt + budgetMs,
1144
+ }
1145
+ : drainNormalized;
1146
+ const complete =
1147
+ gpuDrainSettled &&
1148
+ !normalized.unsupported &&
1149
+ !normalized.timedOut &&
1150
+ normalized.abandoned === 0 &&
1151
+ normalized.computeUnsupported !== true &&
1152
+ normalized.computeTimedOut !== true &&
1153
+ (normalized.computeAbandoned ?? 0) === 0;
1154
+ const finalCache =
1155
+ complete && cacheIdentity !== undefined
1156
+ ? storeWarmUpCache(cacheIdentity, candidates, computeNodes.length)
1157
+ : cacheStatus;
1158
+ return reconcileWarmUpObservation({ ...normalized, cache: finalCache });
1159
+ };
1160
+
1161
+ // The hidden pass render runs once, after the compile and before the ending census snapshot, so
1162
+ // the pipelines it builds are counted in `observed` and named beside them. A warm-up that is out
1163
+ // of budget does not start it: a render cannot be sliced, and one that overran the launch would
1164
+ // be worse than the stall it exists to prevent.
1165
+ let passResult: IWarmPassRender | undefined;
1166
+ let passRendered = false;
1167
+ let passError: unknown;
1168
+ const renderWarmPassesOnce = async (): Promise<IWarmPassRender | undefined> => {
1169
+ if (passRendered) return passResult;
1170
+ passRendered = true;
1171
+ if (environmentPreparationStarted && !environmentPrepared) return undefined;
1172
+ if (now() >= startedAt + budgetMs) return undefined;
1173
+ try {
1174
+ passResult = await renderWarmPasses(
1175
+ renderer,
1176
+ scene,
1177
+ camera,
1178
+ options.renderPasses !== false,
1179
+ options.includeHidden === true,
1180
+ options.targetScene,
1181
+ );
1182
+ } catch (error) {
1183
+ passError = error;
1184
+ passResult = undefined;
1185
+ }
1186
+ return passResult;
1187
+ };
1188
+ // `render()` only submits the hidden frame. A driver compiles a pipeline the first time the GPU
1189
+ // executes it, so returning here handed that compile to the first frame the player sees: 150 ms
1190
+ // for one template's post chain. Wait for the queue to drain, inside the same budget as the rest.
1191
+ const settleGpu = async (): Promise<void> => {
1192
+ if (passResult === undefined) return;
1193
+ const queue = (
1194
+ renderer.raw as
1195
+ | { backend?: { device?: { queue?: { onSubmittedWorkDone?: () => Promise<unknown> } } } }
1196
+ | undefined
1197
+ )?.backend?.device?.queue;
1198
+ if (typeof queue?.onSubmittedWorkDone !== "function") return;
1199
+ const drained = Promise.resolve().then(() => queue.onSubmittedWorkDone?.());
1200
+ gpuDrainSettled = await withinDeadline(startedAt + budgetMs, drained, yieldFrame, now);
1201
+ };
1202
+ const withPasses = (report: IWarmUpReport): IWarmUpReport =>
1203
+ passResult === undefined
1204
+ ? report
1205
+ : {
1206
+ ...report,
1207
+ passes: passResult.passes,
1208
+ passPipelines: passResult.created,
1209
+ cullingForced: passResult.cullingForced,
1210
+ visibilityForced: passResult.visibilityForced,
1211
+ elapsedMs: report.elapsedMs + passResult.elapsedMs,
1212
+ };
1213
+
1214
+ // One call, the whole scene: the default, and the only granularity measured to be affordable.
1215
+ // It buys no per-pipeline progress reporting because the renderer does not surface any, but an
1216
+ // unresolved native promise still yields through `within()` so pollEvents() can settle it. The
1217
+ // cost is paid before the loop is released rather than inside the first frame the player sees.
1218
+ if ((options.granularity ?? "scene") === "scene") {
1219
+ if (compute === undefined) {
1220
+ const deadline = startedAt + budgetMs;
1221
+ const finished =
1222
+ now() < deadline
1223
+ ? await withinDeadline(deadline, invokeSceneCompile(), yieldFrame, now)
1224
+ : false;
1225
+ options.onProgress?.({ done: finished ? 1 : 0, total: 1 });
1226
+ await renderWarmPassesOnce();
1227
+ await settleGpu();
1228
+ return finish(
1229
+ withPasses({
1230
+ compiled: finished ? 1 : 0,
1231
+ pipelines: candidates,
1232
+ candidates,
1233
+ attempted,
1234
+ observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
1235
+ slices: 1,
1236
+ elapsedMs: now() - startedAt,
1237
+ unsupported: false,
1238
+ abandoned: finished ? 0 : 1,
1239
+ timedOut: !finished && (passError === undefined || now() >= deadline),
1240
+ }),
1241
+ );
1242
+ }
1243
+ const remaining = Math.max(0, startedAt + budgetMs - now());
1244
+ const finished =
1245
+ remaining > 0
1246
+ ? await withinDeadline(startedAt + budgetMs, invokeSceneCompile(), yieldFrame, now)
1247
+ : false;
1248
+ options.onProgress?.({ done: finished ? 1 : 0, total: 1 });
1249
+ await renderWarmPassesOnce();
1250
+ await settleGpu();
1251
+ return finish(
1252
+ withPasses(
1253
+ withComputeReport(
1254
+ {
1255
+ compiled: finished ? 1 : 0,
1256
+ pipelines: candidates,
1257
+ candidates,
1258
+ attempted,
1259
+ observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
1260
+ slices: 1,
1261
+ elapsedMs: now() - startedAt,
1262
+ unsupported: false,
1263
+ abandoned: finished ? 0 : 1,
1264
+ timedOut: compute.timedOut || (!finished && now() >= startedAt + budgetMs),
1265
+ },
1266
+ compute,
1267
+ ),
1268
+ ),
1269
+ );
1270
+ }
1271
+
1272
+ const total = renderables.length;
1273
+ // Nothing to warm up is a real answer, not a reason to skip the report.
1274
+ if (total === 0) {
1275
+ options.onProgress?.({ done: 0, total: 0 });
1276
+ const report = reconcileWarmUpObservation({
1277
+ compiled: 0,
1278
+ pipelines: candidates,
1279
+ candidates,
1280
+ attempted,
1281
+ observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
1282
+ slices: 0,
1283
+ elapsedMs: now() - startedAt,
1284
+ unsupported: false,
1285
+ abandoned: 0,
1286
+ timedOut: false,
1287
+ });
1288
+ return compute === undefined ? finish(report) : finish(withComputeReport(report, compute));
1289
+ }
1290
+
1291
+ let slices = 0;
1292
+ let compiled = 0;
1293
+ let abandoned = 0;
1294
+ let timedOut = false;
1295
+ const deadline = startedAt + budgetMs;
1296
+
1297
+ for (let index = 0; index < total; index += 1) {
1298
+ if (now() >= deadline) {
1299
+ // Out of budget. Everything still unwarmed is abandoned, and says so.
1300
+ timedOut = true;
1301
+ abandoned += total - index;
1302
+ break;
1303
+ }
1304
+ // Compile every candidate against the real scene so lights, fog and environment resolve
1305
+ // exactly as they will when the frame draws. The renderer owns cache reuse and backend
1306
+ // identity; this layer must not guess which objects are safe to drop before it observes them.
1307
+ //
1308
+ // Bounded, because an unbounded await here is what held a real launch open forever.
1309
+ const finished = await withinDeadline(
1310
+ Math.min(deadline, now() + compileTimeoutMs),
1311
+ invokeCompile(renderables[index] as Object3D, options.targetScene ?? scene),
1312
+ yieldFrame,
1313
+ now,
1314
+ );
1315
+ if (finished) compiled += 1;
1316
+ else {
1317
+ abandoned += 1;
1318
+ if (now() >= deadline) timedOut = true;
1319
+ }
1320
+
1321
+ const done = index + 1;
1322
+ if (done % sliceSize === 0 || done === total) {
1323
+ slices += 1;
1324
+ options.onProgress?.({ done, total });
1325
+ // The frame the player actually sees. Skipped after the final slice: the caller is about to
1326
+ // render anyway, and one more empty frame would only add to the launch.
1327
+ if (done !== total) await yieldFrame();
1328
+ }
1329
+ }
1330
+
1331
+ // The covered pass can now settle asynchronously too (the post/reflection pipelines it requests
1332
+ // are compiled by the device). Bound it by the same budget as every other compile here; the
1333
+ // render-only fallback stays a direct call so it costs no extra frame. The pass is always
1334
+ // issued, as before; past the budget only the wait is skipped, and its compiles keep landing.
1335
+ if (renderer.warmUpWorldPass === undefined) await renderWarmPassesOnce();
1336
+ else await withinDeadline(startedAt + budgetMs, renderWarmPassesOnce(), yieldFrame, now);
1337
+ await settleGpu();
1338
+ const report: IWarmUpReport = {
1339
+ compiled,
1340
+ pipelines: candidates,
1341
+ candidates,
1342
+ attempted,
1343
+ observed: observePipelineCensus(censusBefore, readPipelineCensus(renderer)),
1344
+ slices,
1345
+ elapsedMs: now() - startedAt,
1346
+ unsupported: false,
1347
+ abandoned,
1348
+ timedOut,
1349
+ };
1350
+ return compute === undefined
1351
+ ? finish(withPasses(report))
1352
+ : finish(
1353
+ withPasses(
1354
+ withComputeReport({ ...report, timedOut: compute.timedOut || timedOut }, compute),
1355
+ ),
1356
+ );
1357
+ }