@threenative/core 0.3.4 → 0.3.6

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 (176) hide show
  1. package/capabilities.json +1505 -79
  2. package/dist/{audio-7i3Xl0l3.d.ts → audio-DIJE5HTr.d.ts} +43 -3
  3. package/dist/{canvas-layer-DDmC_VVF.d.ts → canvas-layer-C1-5CviZ.d.ts} +5 -1
  4. package/dist/{game-CljaDv4D.d.ts → game-Jz4Fdoeb.d.ts} +114 -11
  5. package/dist/hot.d.ts +4 -4
  6. package/dist/index.d.ts +712 -118
  7. package/dist/index.js +12437 -4955
  8. package/dist/{gpu-readback-CqJEfWNQ.d.ts → model-lod-BDAUYgsS.d.ts} +80 -5
  9. package/dist/playtest.d.ts +6 -10
  10. package/dist/playtest.js +57 -24
  11. package/dist/react-css.d.ts +62 -0
  12. package/dist/react-css.js +591 -0
  13. package/dist/react.d.ts +2 -2
  14. package/dist/{renderer-CfsS2hxi.d.ts → renderer-9yEo9hPa.d.ts} +489 -22
  15. package/dist/terrain-jobs-worker.d.ts +2 -0
  16. package/dist/terrain-jobs-worker.js +130 -0
  17. package/dist/ui-layer.js +59 -8
  18. package/dist/world.d.ts +766 -73
  19. package/dist/world.js +9307 -3543
  20. package/gpl/recipes/export_world.py +18 -1
  21. package/mcp/blender-server.mjs +7 -4
  22. package/mcp/blender.mjs +3 -4
  23. package/mcp/engine-server.mjs +2 -2
  24. package/mcp/servers.mjs +4 -4
  25. package/package.json +15 -9
  26. package/patches/three@0.185.1-prd269-upgrade.patch +22418 -0
  27. package/patches/three@0.185.1.patch +6594 -700
  28. package/scripts/apply-three-patch.mjs +62 -4
  29. package/src/animation-blend.ts +264 -0
  30. package/src/animation-composition.ts +362 -0
  31. package/src/animation-layers.ts +260 -0
  32. package/src/animation-root-motion.ts +283 -0
  33. package/src/animation.ts +896 -0
  34. package/src/assets.ts +1303 -0
  35. package/src/atmosphere/index.ts +335 -0
  36. package/src/atmosphere/luts.ts +298 -0
  37. package/src/atmosphere/params.ts +323 -0
  38. package/src/audio.ts +912 -0
  39. package/src/billboard.ts +124 -0
  40. package/src/bone-lengths.ts +157 -0
  41. package/src/camera-shake.ts +116 -0
  42. package/src/canvas-layer.ts +47 -0
  43. package/src/clip-audit.ts +401 -0
  44. package/src/clustered-batch.ts +492 -0
  45. package/src/clustered-mesh.ts +638 -0
  46. package/src/compute-driven.ts +176 -0
  47. package/src/compute-timing.ts +318 -0
  48. package/src/config.ts +593 -0
  49. package/src/debug.ts +82 -0
  50. package/src/engine-render-hook.ts +25 -0
  51. package/src/entities.ts +79 -0
  52. package/src/entity-snapshot.ts +53 -0
  53. package/src/flight.ts +683 -0
  54. package/src/fluid-field.ts +748 -0
  55. package/src/fluid-particles.ts +1253 -0
  56. package/src/frame-budget.ts +1368 -0
  57. package/src/game.ts +2408 -0
  58. package/src/geometry-capture.ts +1098 -0
  59. package/src/gpu-class.ts +160 -0
  60. package/src/gpu-frame-observation.ts +424 -0
  61. package/src/gpu-readback.ts +143 -0
  62. package/src/gpu-scene-bvh.ts +464 -0
  63. package/src/grounding.ts +100 -0
  64. package/src/hot.ts +161 -0
  65. package/src/import-meta.d.ts +13 -0
  66. package/src/index.ts +1536 -0
  67. package/src/input.ts +690 -0
  68. package/src/instanced-batch-lod.ts +283 -0
  69. package/src/instanced-batch.ts +274 -0
  70. package/src/interpolation.ts +129 -0
  71. package/src/launch-diagnostics.ts +161 -0
  72. package/src/loop.ts +574 -0
  73. package/src/matrix-world.ts +245 -0
  74. package/src/merge-parts.ts +812 -0
  75. package/src/model-lod.ts +1315 -0
  76. package/src/net-protocol.ts +333 -0
  77. package/src/net-session.ts +477 -0
  78. package/src/net.ts +80 -0
  79. package/src/ocean/fft.ts +72 -0
  80. package/src/ocean/spectral.ts +728 -0
  81. package/src/particle-significance.ts +102 -0
  82. package/src/particles.ts +648 -0
  83. package/src/path-follow.ts +175 -0
  84. package/src/picking.ts +250 -0
  85. package/src/pipeline-census.ts +1566 -0
  86. package/src/platform.ts +210 -0
  87. package/src/playtest.ts +850 -0
  88. package/src/pointer-events.ts +411 -0
  89. package/src/pose-measure.ts +435 -0
  90. package/src/profiling/FrameCounters.ts +231 -0
  91. package/src/profiling/Spans.ts +548 -0
  92. package/src/profiling/opacity-convention.ts +21 -0
  93. package/src/profiling/render-list-validate.ts +175 -0
  94. package/src/profiling/render-trap-audit.ts +84 -0
  95. package/src/profiling/scene-warning.ts +190 -0
  96. package/src/profiling/span-probes.ts +191 -0
  97. package/src/profiling/unlit-foliage-warning.ts +149 -0
  98. package/src/projection-apply.ts +1529 -0
  99. package/src/projection-marker.ts +142 -0
  100. package/src/projection-plan.ts +1258 -0
  101. package/src/projection-skinned.ts +419 -0
  102. package/src/projection-stability.ts +409 -0
  103. package/src/projection-uniform.ts +328 -0
  104. package/src/random.ts +41 -0
  105. package/src/react-css.ts +604 -0
  106. package/src/react-glyphs.ts +114 -0
  107. package/src/react-host.ts +576 -0
  108. package/src/react-layout.ts +265 -0
  109. package/src/react.ts +60 -0
  110. package/src/render/alpha-antialiasing.ts +159 -0
  111. package/src/render/batched-velocity.ts +126 -0
  112. package/src/render/chain.ts +1021 -0
  113. package/src/render/daylight.ts +189 -0
  114. package/src/render/depth-pyramid.ts +596 -0
  115. package/src/render/foliage-alpha.ts +166 -0
  116. package/src/render/material-key.ts +60 -0
  117. package/src/render/mesh-pool.ts +144 -0
  118. package/src/render/probe-volume.ts +1668 -0
  119. package/src/render/resolution-subrect.ts +253 -0
  120. package/src/render/velocity.ts +442 -0
  121. package/src/render/virtual-shadow-pages.ts +827 -0
  122. package/src/render/virtual-shadow-partial.ts +174 -0
  123. package/src/render/virtual-shadow.ts +3330 -0
  124. package/src/render/world-impostor-surface.ts +722 -0
  125. package/src/render/world-impostor.ts +558 -0
  126. package/src/render-camera-cull.ts +441 -0
  127. package/src/render-pass-budget.ts +501 -0
  128. package/src/renderProjection.ts +758 -0
  129. package/src/renderer-config.ts +127 -0
  130. package/src/renderer.ts +1847 -0
  131. package/src/replay-protocol.ts +85 -0
  132. package/src/replay.ts +205 -0
  133. package/src/resolution-scaler.ts +819 -0
  134. package/src/rig-preparation.ts +271 -0
  135. package/src/ripple-field.ts +432 -0
  136. package/src/scale.ts +109 -0
  137. package/src/scene.ts +239 -0
  138. package/src/schedule.ts +155 -0
  139. package/src/skeletal-mesh.ts +61 -0
  140. package/src/skeleton.ts +100 -0
  141. package/src/snow-field.ts +744 -0
  142. package/src/softbody-topology.ts +269 -0
  143. package/src/softbody.ts +516 -0
  144. package/src/sprite-animator.ts +222 -0
  145. package/src/startup-readiness.ts +386 -0
  146. package/src/state.ts +66 -0
  147. package/src/static-transform.ts +274 -0
  148. package/src/storage-buffer.ts +253 -0
  149. package/src/streaming.ts +308 -0
  150. package/src/target-fps.ts +92 -0
  151. package/src/terrain-jobs-worker.ts +17 -0
  152. package/src/terrain-jobs.ts +353 -0
  153. package/src/textures.ts +39 -0
  154. package/src/tracers.ts +237 -0
  155. package/src/ui-bridge.ts +368 -0
  156. package/src/ui-hit-regions.ts +380 -0
  157. package/src/ui-layer.ts +83 -0
  158. package/src/ui-state.ts +220 -0
  159. package/src/version.ts +2 -0
  160. package/src/viewport.ts +253 -0
  161. package/src/warmup.ts +1357 -0
  162. package/src/water-surface.ts +384 -0
  163. package/src/wave-field.ts +524 -0
  164. package/src/world-capabilities.ts +131 -0
  165. package/src/world-cell-proxy.ts +392 -0
  166. package/src/world-cells.ts +10564 -0
  167. package/src/world-gpu-scene.ts +3354 -0
  168. package/src/world-heightmap.ts +82 -0
  169. package/src/world-package.ts +469 -0
  170. package/src/world-passes.ts +582 -0
  171. package/src/world-region.ts +17 -0
  172. package/src/world-terrain-splat.ts +564 -0
  173. package/src/world-tiles.ts +3826 -0
  174. package/src/world-topology.ts +370 -0
  175. package/src/world-validate.ts +48 -0
  176. package/src/world.ts +805 -0
@@ -0,0 +1,758 @@
1
+ import type { Camera, Material, Matrix4, Object3D, Scene } from "three";
2
+
3
+ import type { IGeometryOwnership } from "./geometry-capture.js";
4
+ import type { MatrixWorldPass } from "./matrix-world.js";
5
+ import { ProjectionMirror } from "./projection-apply.js";
6
+ import {
7
+ type IProjectionProjectPlan,
8
+ createProjectionScanWorkspace,
9
+ isRenderable,
10
+ releaseProjectionScanWorkspace,
11
+ scanProjection,
12
+ } from "./projection-plan.js";
13
+ import { ProjectionStability } from "./projection-stability.js";
14
+ import { VelocityTracker } from "./render/velocity.js";
15
+
16
+ /**
17
+ * An optimizer that the game never has to know about.
18
+ *
19
+ * The pass this replaces reached its draw count by consuming the scene: it merged what it judged
20
+ * static into one buffer and lifted the sources out of the graph. That is only correct while the
21
+ * judgement holds, and the judgement is a guess made from eight frames about arbitrary JavaScript
22
+ * that has not run yet. When it was wrong the game did not get a slow frame, it got a wrong one —
23
+ * a mesh that stopped moving, a hidden prop that drew anyway, two of three instances gone — and
24
+ * the pass still reported success.
25
+ *
26
+ * So the ownership is inverted here. **Correct rendering is unconditional; optimization is
27
+ * opportunistic.** The game's scene stays exactly as the game authored it — same objects, same
28
+ * parents, same names, same traversal, same `raycast` results — and the renderer is handed a
29
+ * private mirror of it instead. Eligible meshes reach that mirror as instances of an
30
+ * `InstancedMesh`, so thousands of them cost one draw each group; everything else reaches it as an
31
+ * exact proxy. When the mirror cannot reproduce something faithfully, the mirror is abandoned for
32
+ * that frame and the authored scene is rendered directly. That fallback is a correct slow path, not
33
+ * an error, and nothing about it is configurable.
34
+ *
35
+ * `InstancedMesh` is stock `three`, and using it rather than a bespoke merge is the point:
36
+ * per-object matrices and instance reuse are things it already does, and it points at the game's
37
+ * own geometry rather than copying it. Reconciling a moved object is a matrix write, not a rebuild,
38
+ * which is what makes "the game may change anything at any time" affordable rather than
39
+ * aspirational.
40
+ *
41
+ * Since P2-3 the class composes two seams instead of owning every concern itself: the pure scan
42
+ * and plan (`projection-plan.ts`) decides what a frame will do, and the mirror
43
+ * (`projection-apply.ts`) applies it and owns every mutation and restoration path. This file keeps
44
+ * the public API, the reconciliation loop, the report assembly and the deoptimization verdict.
45
+ */
46
+
47
+ /**
48
+ * Why the projection gave a frame back to the authored scene, or declined an object.
49
+ *
50
+ * `hostProjected` is the verdict where the host renderer batches the authored scene itself and no
51
+ * mirror exists (see {@link SceneRenderProjection}); `projected` is the JS mirror's.
52
+ */
53
+ export type ProjectionReasonCode =
54
+ | "projected"
55
+ | "hostProjected"
56
+ | "belowMeshFloor"
57
+ | "renderHook"
58
+ | "unsupportedLight"
59
+ | "unsupportedObject"
60
+ | "notWorthwhile"
61
+ | "disabled";
62
+
63
+ export type ProjectionExactReason =
64
+ | "instanced"
65
+ | "skinned"
66
+ | "morph"
67
+ | "multiMaterial"
68
+ | "drawRange"
69
+ | "indirect"
70
+ | "customDepthMaterial"
71
+ | "lod"
72
+ | "sprite"
73
+ | "points"
74
+ | "transparent"
75
+ | "vertexDisplaced"
76
+ | "renderOrder"
77
+ | "tooFewToBatch"
78
+ | "batchOverflow"
79
+ | "batchVelocityPatchMissing"
80
+ | "materialChanged"
81
+ | "negativeScale"
82
+ | "nonUniformScale"
83
+ | "unsupportedGeometry";
84
+
85
+ /**
86
+ * How often a uniform-batch member's material is proved still matching its group's shared draw.
87
+ *
88
+ * - `"spread"` — the default. A bounded slice of the members a frame, resuming where the last frame
89
+ * stopped, so a frame proves `materialChecksPerFrame` materials rather than all of them. A
90
+ * non-colour edit is still caught and the member still leaves the group; it is caught up to
91
+ * `materialCheckStaleFrames` frames later, which the report states. A colour edit is never
92
+ * involved: the per-instance colour write is O(1) per member and always exact.
93
+ * - `"everyFrame"` — every material, every frame, for a game that would rather pay the per-frame
94
+ * cost than accept the bound. This is the check as it shipped before the sweep existed.
95
+ */
96
+ export type ProjectionMaterialChecks = "spread" | "everyFrame";
97
+
98
+ export interface IRenderProjectionReport {
99
+ readonly schemaVersion: 1;
100
+ /** True while the renderer is being handed the mirror rather than the authored scene. */
101
+ readonly projecting: boolean;
102
+ readonly reasonCode: ProjectionReasonCode;
103
+ readonly reason?: string;
104
+ /** Renderables the authored scene holds — what an unoptimized frame would walk and draw. */
105
+ readonly sourceRenderables: number;
106
+ /**
107
+ * Objects the renderer will actually walk, counted from the scene it is handed rather than from
108
+ * what this class believes it built. A count taken from intent rather than from the renderer's
109
+ * input is how an optimizer reports a win it did not deliver.
110
+ */
111
+ readonly resultDrawCandidates: number;
112
+ /** Sources folded into batched draws, and the number of draws they became. */
113
+ readonly projectedObjects: number;
114
+ readonly batches: number;
115
+ /** The batch split by lane, so a report reader can tell which grouping did the folding. */
116
+ readonly instancedBatches: number;
117
+ readonly materialBatches: number;
118
+ /** Palette draws on the skinned lane: rigs sharing geometry and material, one draw per pass. */
119
+ readonly skinnedBatches: number;
120
+ /** Sources that kept a draw of their own, with the reason each one did. */
121
+ readonly exactObjects: number;
122
+ readonly exact: Partial<Record<ProjectionExactReason, number>>;
123
+ /**
124
+ * What the plan believes this frame costs: one draw per batch plus one per exact-lane object.
125
+ *
126
+ * **A plan, not a measurement.** On WebGPU a `BatchedMesh` is one render object that issues one
127
+ * `drawIndexed` per visible member, so a batch is not reliably one draw and this number can be
128
+ * optimistic. The measured count comes from the renderer and is reported beside this one; a
129
+ * divergence between them is a finding, not a rounding error.
130
+ */
131
+ readonly drawsPlanned: number;
132
+ /**
133
+ * The colour lane's per-frame material proof: which mode, what it costs a frame, and the worst
134
+ * staleness it accepts.
135
+ *
136
+ * `materialChecks` is the mode in force, `materialChecksPerFrame` the ceiling on checks a frame
137
+ * (`0` in `everyFrame`, which is not bounded because it is not spread), and
138
+ * `materialCheckStaleFrames` the frames a non-colour material edit can sit unproved for — `0`
139
+ * under `everyFrame`, so the number is never read as a bound that does not exist.
140
+ * `materialChecksOverridden` says the author chose a mode other than the default.
141
+ */
142
+ readonly materialChecks: ProjectionMaterialChecks;
143
+ readonly materialChecksPerFrame: number;
144
+ readonly materialCheckStaleFrames: number;
145
+ readonly materialChecksOverridden: boolean;
146
+ /**
147
+ * Who batched the frame: `"host"` where the native renderer batches the authored scene itself and
148
+ * core builds no mirror, `"js"` where core's mirror does (every web frame, and an engine frame
149
+ * under `renderer.projection: "js"`). `pathOverridden` says the game forced `"js"` on a host that
150
+ * would have batched, so a measurement taken under the override says so.
151
+ */
152
+ readonly path: "host" | "js";
153
+ readonly pathOverridden: boolean;
154
+ readonly timings: {
155
+ readonly compileMs: number;
156
+ readonly reconcileMs: number;
157
+ readonly lastReconcileMs: number;
158
+ readonly maxReconcileMs: number;
159
+ };
160
+ }
161
+
162
+ export interface IRenderProjectionOptions {
163
+ /**
164
+ * Below this many eligible meshes the mirror costs more to maintain than the draws it saves, so
165
+ * the authored scene is rendered directly and nothing is built.
166
+ */
167
+ readonly minMeshes?: number;
168
+ /**
169
+ * The game's `renderer.projection` value, verbatim: `false` declines the projection, and an
170
+ * object names the material check on top of accepting it. `undefined` and `true` are the shipping
171
+ * behaviour, the projection runs.
172
+ *
173
+ * `materialChecks` defaults to `"spread"` — a bounded slice of the batched materials proved per
174
+ * frame, with the staleness it accepts reported — and `"everyFrame"` restores the per-member,
175
+ * per-frame proof exactly as it shipped. Any other value throws at construction rather than being
176
+ * coerced to a default, because a silently ignored mode is a measurement nobody can trust.
177
+ *
178
+ * A declined projection builds no mirror and runs no eligibility scan — the authored scene is
179
+ * handed to the renderer every frame — so declining costs nothing rather than being re-judged
180
+ * each frame. The verdict is reported as `disabled`, not as one of the measured declines.
181
+ *
182
+ * `"js"` forces core's JS mirror on a host whose renderer would batch the authored scene itself
183
+ * (the native engine player). It changes nothing on three, which always has the mirror.
184
+ */
185
+ readonly projection?: boolean | "js" | { readonly materialChecks?: ProjectionMaterialChecks };
186
+ /** Retains drawn-object history for temporal stages, independently of projection opt-out. */
187
+ readonly velocity?: boolean | (() => boolean);
188
+ /**
189
+ * The engine's world-matrix walk, when the frame owns one. The authored scene is refreshed here
190
+ * rather than by three's renderer, because the renderer is handed the mirror: without this the
191
+ * authored scene would never be walked and every proxy would be one frame stale.
192
+ */
193
+ readonly matrixWorld?: MatrixWorldPass;
194
+ readonly onReport?: (report: IRenderProjectionReport) => void;
195
+ }
196
+
197
+ export { exactLaneReason } from "./projection-plan.js";
198
+
199
+ /**
200
+ * How many settled-declined frames pass between classification re-walks.
201
+ *
202
+ * Growth past the mesh floor is noticed within this window; a scene that never changes pays one
203
+ * walk per window instead of one per frame. Sub-second at frame rate, and invisible — the
204
+ * alternative state it delays is "the optimizer has not engaged yet", not a wrong frame.
205
+ */
206
+ const DECLINE_RESCAN_FRAMES = 60;
207
+
208
+ /**
209
+ * What a host renderer that batches the authored scene itself answers: the verdict and counts its own
210
+ * batching gives the scene, in the shape of the report's fields. `reasonCode` is the host's, with
211
+ * `"projected"` meaning it batched.
212
+ */
213
+ interface IHostProjectionVerdict {
214
+ readonly projecting: boolean;
215
+ readonly reasonCode: ProjectionReasonCode;
216
+ readonly sourceRenderables: number;
217
+ readonly projectedObjects: number;
218
+ readonly instancedBatches: number;
219
+ readonly materialBatches: number;
220
+ readonly skinnedBatches: number;
221
+ readonly exactObjects: number;
222
+ readonly exact: Partial<Record<ProjectionExactReason, number>>;
223
+ }
224
+
225
+ /**
226
+ * A scene root whose host renderer batches it (the native engine's `RenderDatabase`), so core builds
227
+ * no mirror: one call per frame answers what that batching made of the scene, where the mirror reads
228
+ * `geometry`, `material`, visibility and a matrix of every object across the boundary. Optional: a
229
+ * root without it (three) takes the JS mirror, unchanged.
230
+ */
231
+ interface IHostProjectionRoot {
232
+ __tnProjectionReport(minMeshes: number): IHostProjectionVerdict;
233
+ }
234
+
235
+ /** The host has not been asked yet: nothing is projected and the scene has not been counted. */
236
+ const NO_HOST_VERDICT: IHostProjectionVerdict = {
237
+ projecting: false,
238
+ reasonCode: "belowMeshFloor",
239
+ sourceRenderables: 0,
240
+ projectedObjects: 0,
241
+ instancedBatches: 0,
242
+ materialBatches: 0,
243
+ skinnedBatches: 0,
244
+ exactObjects: 0,
245
+ exact: {},
246
+ };
247
+
248
+ function hostProjectionRoot(source: unknown): IHostProjectionRoot | undefined {
249
+ const candidate = source as Partial<IHostProjectionRoot> | null;
250
+ return typeof candidate?.__tnProjectionReport === "function"
251
+ ? (candidate as IHostProjectionRoot)
252
+ : undefined;
253
+ }
254
+
255
+ export class SceneRenderProjection {
256
+ readonly #source: Scene;
257
+ readonly #minMeshes: number;
258
+ readonly #enabled: boolean;
259
+ readonly #materialChecks: ProjectionMaterialChecks;
260
+ readonly #onReport: ((report: IRenderProjectionReport) => void) | undefined;
261
+ /** Absent when the game opted out or the host batches the scene itself: either way none is built. */
262
+ readonly #mirror: ProjectionMirror | undefined;
263
+ /** The host that batches the authored scene, when it has the seam and the game did not force `"js"`. */
264
+ readonly #host: IHostProjectionRoot | undefined;
265
+ /** The game forced `"js"` on a host that would have batched. */
266
+ readonly #hostOverridden: boolean;
267
+ /** The host's verdict for the last reconcile, which `report` reads. */
268
+ #hostVerdict: IHostProjectionVerdict | undefined;
269
+ readonly #velocity: boolean | (() => boolean);
270
+ readonly #matrixWorld: MatrixWorldPass | undefined;
271
+ readonly #velocityTracker = new VelocityTracker();
272
+ readonly #scanWorkspace = createProjectionScanWorkspace();
273
+ /**
274
+ * What the last projecting scan classified, kept so a frame that can prove the structure unchanged
275
+ * can skip re-deriving it, and the proof itself.
276
+ *
277
+ * The plan points into the scan workspace, which is only rewritten by the next scan — and a scan
278
+ * only runs when the proof has failed, so a retained plan is never read after the arrays behind
279
+ * it move. Any decline, release or velocity change drops it: the mirror it described is gone.
280
+ */
281
+ readonly #stability = new ProjectionStability();
282
+ #retainedPlan: IProjectionProjectPlan | undefined;
283
+ #deoptimized = true;
284
+ #reasonCode: ProjectionReasonCode = "belowMeshFloor";
285
+ #reason: string | undefined;
286
+ #sourceRenderables = 0;
287
+ #reconcileMs = 0;
288
+ #lastReconcileMs = 0;
289
+ #maxReconcileMs = 0;
290
+ #reported = false;
291
+ #lastAnnounced: ProjectionReasonCode | undefined;
292
+ #framesSinceDeclineScan = DECLINE_RESCAN_FRAMES;
293
+ #velocityActive: boolean;
294
+
295
+ constructor(source: Scene, options: IRenderProjectionOptions = {}) {
296
+ const minMeshes = options.minMeshes ?? 200;
297
+ if (!Number.isInteger(minMeshes) || minMeshes < 1)
298
+ throw new Error("SceneRenderProjection.minMeshes must be a positive integer.");
299
+ this.#source = source;
300
+ this.#minMeshes = minMeshes;
301
+ this.#enabled = options.projection !== false;
302
+ this.#materialChecks = resolveMaterialChecks(
303
+ typeof options.projection === "object" ? options.projection.materialChecks : undefined,
304
+ );
305
+ this.#velocity = options.velocity ?? false;
306
+ this.#velocityActive = resolveVelocityEnabled(this.#velocity);
307
+ this.#matrixWorld = options.matrixWorld;
308
+ const hostRoot = this.#enabled ? hostProjectionRoot(source) : undefined;
309
+ this.#hostOverridden = hostRoot !== undefined && options.projection === "js";
310
+ this.#host = this.#hostOverridden ? undefined : hostRoot;
311
+ this.#mirror =
312
+ this.#enabled && this.#host === undefined
313
+ ? new ProjectionMirror(this.#velocityActive, this.#materialChecks)
314
+ : undefined;
315
+ this.#onReport = options.onReport;
316
+ }
317
+
318
+ /** True while the renderer is being handed the authored scene rather than the mirror. */
319
+ get deoptimized(): boolean {
320
+ return this.#deoptimized;
321
+ }
322
+
323
+ /**
324
+ * The scene to draw this frame — the mirror when it is faithful, the authored scene when it is
325
+ * not. Callers render whatever this returns and never branch on which one it was.
326
+ */
327
+ /**
328
+ * Who owns each object the renderer is handed, for a per-object diagnostic. Empty when the
329
+ * mirror is off or deoptimized — the authored scene is then what rendered, and every object
330
+ * already is its own source. Built on demand and retained by nobody.
331
+ */
332
+ describeOwnership(): ReadonlyMap<Object3D, IGeometryOwnership> {
333
+ if (this.#deoptimized || this.#mirror === undefined) return new Map();
334
+ return this.#mirror.describeOwnership();
335
+ }
336
+
337
+ get root(): Scene {
338
+ if (this.#deoptimized || this.#mirror === undefined) return this.#source;
339
+ return this.#mirror.scene;
340
+ }
341
+
342
+ /**
343
+ * Brings the mirror up to date with the authored scene, and must run before the frame draws.
344
+ *
345
+ * Everything the mirror asserts about a source is re-derived here rather than remembered from
346
+ * startup: where it is, whether it is visible, what geometry and material it has, and whether it
347
+ * is still in the scene at all. A source that did not change costs a compare.
348
+ *
349
+ * What is re-derived *every* frame is the maintenance — the matrix, the visibility, the batch
350
+ * slot, the stand-in, the mirrored light. What may be re-derived only when it changed is the
351
+ * classification, because it is a pure function of the scene's structure and reads no world
352
+ * matrix: a scene where every transform animates would otherwise re-decide an unchangeable answer
353
+ * per frame. `ProjectionStability` holds what the last scan read and compares it, so the skip
354
+ * happens only when nothing it reads has moved, and only the scan, the plan's re-derivation and
355
+ * the retirement sweep are skipped — a wrong comparison costs one scan, never a wrong frame.
356
+ *
357
+ * A settled decline costs almost nothing: the classification walk re-runs on a bounded cadence
358
+ * rather than every frame, and the whole-scene matrix pass does not run at all — the frames the
359
+ * authored scene draws are exactly the frames three's renderer refreshes its world matrices
360
+ * anyway. The pass stays mandatory on any frame this class projects, because then the authored
361
+ * scene is not what renders and nothing else refreshes it.
362
+ */
363
+ reconcile(): void {
364
+ const velocityEnabled = resolveVelocityEnabled(this.#velocity);
365
+ if (this.#velocityActive !== velocityEnabled) {
366
+ this.#velocityTracker.clear();
367
+ this.#velocityActive = velocityEnabled;
368
+ }
369
+ if (!this.#enabled) {
370
+ // Temporal history belongs to the authored draw even when its optimization is declined.
371
+ // No mirror or eligibility scan runs; without a temporal consumer no history work runs.
372
+ if (velocityEnabled) this.#velocityTracker.update(this.#source);
373
+ this.#deoptimize("disabled", "the game set renderer.projection to false");
374
+ this.#publish();
375
+ return;
376
+ }
377
+ const host = this.#host;
378
+ if (host !== undefined) {
379
+ this.#reconcileHost(host, velocityEnabled);
380
+ return;
381
+ }
382
+ const mirror = this.#mirror;
383
+ if (mirror === undefined) return;
384
+ const startedAt = globalThis.performance?.now() ?? 0;
385
+ if (mirror.setVelocityEnabled(velocityEnabled)) {
386
+ this.#deoptimized = true;
387
+ this.#framesSinceDeclineScan = DECLINE_RESCAN_FRAMES;
388
+ this.#forgetPlan();
389
+ }
390
+ // Re-read every frame, not once at construction: a game that swaps its sky or turns fog on
391
+ // mid-level would otherwise keep the look it happened to have when the mirror was built.
392
+ const mirrorScene = mirror.scene;
393
+ mirrorScene.background = this.#source.background;
394
+ mirrorScene.environment = this.#source.environment;
395
+ mirrorScene.fog = this.#source.fog;
396
+ mirrorScene.backgroundBlurriness = this.#source.backgroundBlurriness;
397
+ mirrorScene.backgroundIntensity = this.#source.backgroundIntensity;
398
+ mirrorScene.environmentIntensity = this.#source.environmentIntensity;
399
+ mirrorScene.overrideMaterial = this.#source.overrideMaterial;
400
+ // A fresh `Scene` defaults both rotations to zero, so a game that turns its sky or its
401
+ // environment lighting had that yaw snap back to zero the moment the mirror drew it — a
402
+ // whole-image change with no frame where the game did anything. Copy value and order, into the
403
+ // mirror's own Euler, so the source the game still mutates is never aliased.
404
+ mirrorScene.backgroundRotation.copy(this.#source.backgroundRotation);
405
+ mirrorScene.environmentRotation.copy(this.#source.environmentRotation);
406
+
407
+ // A settled decline re-judges on a cadence, not per frame: most agent-built scenes sit below
408
+ // the floor forever, and re-walking one every frame bought nothing. The counter starts at the
409
+ // interval so the first reconcile always scans, and a deoptimization resets it.
410
+ if (this.#deoptimized) {
411
+ this.#framesSinceDeclineScan += 1;
412
+ if (this.#framesSinceDeclineScan < DECLINE_RESCAN_FRAMES) {
413
+ if (velocityEnabled) this.#velocityTracker.update(this.#source);
414
+ return;
415
+ }
416
+ }
417
+
418
+ // Scan and decide without touching the mirror; then either build the plan or decline whole.
419
+ // The scan reads no world matrices, so it runs before the forced pass and the pass only runs
420
+ // when its result is actually needed.
421
+ let plan: IProjectionProjectPlan | undefined;
422
+ let exactLane: IProjectionProjectPlan["exactLane"] = [];
423
+ let exactLaneCount = 0;
424
+ // Only a proven-unchanged structure can skip the retirement sweep: it walks every instance the
425
+ // mirror holds to find the ones that left, and nothing left if the membership is the same.
426
+ let retireSources = true;
427
+ const retained = this.#deoptimized ? undefined : this.#retainedPlan;
428
+ if (retained !== undefined && this.#stability.holds(this.#source)) {
429
+ // Every input the classification reads is the value the last scan read, so this frame's plan
430
+ // is the one already built. The apply below still runs in full: this skips the *decision*,
431
+ // never the maintenance, which is why an object that moved, hid or was reparented since is
432
+ // still written into the mirror this frame.
433
+ plan = retained;
434
+ const exact = this.#stability.exactLane();
435
+ exactLane = exact.entries;
436
+ exactLaneCount = exact.count;
437
+ retireSources = false;
438
+ this.#refreshMatrices();
439
+ } else {
440
+ // The scan releases its own workspace on entry, which is also what releases the previous
441
+ // plan's members: this frame's plan is what the apply below consumes, and a retained one is
442
+ // what the next frame re-uses, so releasing it here would empty the arrays it points into.
443
+ // What that costs is one frame of reach on the objects the last scan saw — which the mirror
444
+ // holds anyway while they are in the scene, and which the next scan drops either way.
445
+ const scan = scanProjection(this.#source, this.#minMeshes, this.#scanWorkspace);
446
+ this.#sourceRenderables = scan.renderables;
447
+ this.#framesSinceDeclineScan = 0;
448
+ if (scan.plan.action === "decline") {
449
+ this.#forgetPlan();
450
+ mirror.releaseAll();
451
+ this.#deoptimize(scan.plan.reasonCode, scan.plan.reason);
452
+ // A scene with nothing in it yet is still loading, and walking it costs nothing: look
453
+ // again next frame rather than drawing the first second of the level unprojected.
454
+ if (scan.renderables === 0) this.#framesSinceDeclineScan = DECLINE_RESCAN_FRAMES;
455
+ } else {
456
+ this.#refreshMatrices();
457
+ this.#stability.record(this.#source, scan);
458
+ this.#retainedPlan = scan.plan;
459
+ plan = scan.plan;
460
+ exactLane = scan.exactLane;
461
+ exactLaneCount = scan.exactLaneCount;
462
+ }
463
+ }
464
+
465
+ if (plan !== undefined) {
466
+ mirror.prepare(exactLane, exactLaneCount);
467
+ const lightFailure = mirror.apply(plan, retireSources);
468
+ if (lightFailure !== undefined) {
469
+ this.#deoptimize("unsupportedLight", lightFailure);
470
+ this.#forgetPlan();
471
+ } else {
472
+ // A member whose material stopped matching the group it was an instance of is drawn exactly
473
+ // this frame, and the classification that put it there is now stale: nothing structural
474
+ // changed, so the structure proof would happily re-use it. Dropping the retained plan is
475
+ // what makes the next frame re-derive the grouping from the materials as they now stand.
476
+ if (mirror.reclassified) this.#forgetPlan();
477
+ this.#deoptimized = false;
478
+ this.#reasonCode = "projected";
479
+ this.#reason = undefined;
480
+ }
481
+ }
482
+
483
+ if (velocityEnabled)
484
+ this.#velocityTracker.update(this.#deoptimized ? this.#source : mirror.scene);
485
+ else this.#velocityTracker.clear();
486
+
487
+ this.#recordReconcile(startedAt);
488
+ this.#publish();
489
+ }
490
+
491
+ /**
492
+ * The host renderer batches the authored scene, so there is nothing to mirror, scan or refresh
493
+ * here: one call reports what its batching made of the frame. The world-matrix pass stays the
494
+ * frame loop's (it runs on the root the renderer is handed, which is this scene).
495
+ */
496
+ #reconcileHost(host: IHostProjectionRoot, velocityEnabled: boolean): void {
497
+ const startedAt = globalThis.performance?.now() ?? 0;
498
+ if (velocityEnabled) this.#velocityTracker.update(this.#source);
499
+ else this.#velocityTracker.clear();
500
+ const verdict = host.__tnProjectionReport(this.#minMeshes);
501
+ this.#hostVerdict = verdict;
502
+ this.#sourceRenderables = verdict.sourceRenderables;
503
+ this.#reasonCode = verdict.reasonCode === "projected" ? "hostProjected" : verdict.reasonCode;
504
+ this.#reason = verdict.projecting
505
+ ? undefined
506
+ : `the host renderer declined this scene (${verdict.reasonCode})`;
507
+ this.#recordReconcile(startedAt);
508
+ this.#publish();
509
+ }
510
+
511
+ #recordReconcile(startedAt: number): void {
512
+ const elapsed = (globalThis.performance?.now() ?? 0) - startedAt;
513
+ this.#reconcileMs += elapsed;
514
+ this.#lastReconcileMs = elapsed;
515
+ this.#maxReconcileMs = Math.max(this.#maxReconcileMs, elapsed);
516
+ }
517
+
518
+ /** Commits the rendered transform snapshot after the colour and velocity passes consume it. */
519
+ commit(): void {
520
+ if (!this.#velocityActive) return;
521
+ this.#velocityTracker.commit(this.root);
522
+ }
523
+
524
+ /**
525
+ * The renderer is handed the mirror, so the authored scene's world matrices are refreshed here.
526
+ *
527
+ * With the engine's walk installed that is the visible-only pass, which mirrors three for every
528
+ * visible node and defers a hidden subtree until it shows; without it, honouring
529
+ * `matrixWorldAutoUpdate` and Three's own `matrixWorldNeedsUpdate` propagation is the contract
530
+ * every Three renderer uses. A game that turns the flag off has promised to update the scene
531
+ * itself, and a subtree marked `matrixWorldAutoUpdate = false` under a still parent is skipped
532
+ * instead of walked.
533
+ */
534
+ #refreshMatrices(): void {
535
+ if (this.#matrixWorld !== undefined) {
536
+ this.#matrixWorld.apply(this.#source);
537
+ } else if (this.#source.matrixWorldAutoUpdate === true) {
538
+ this.#source.updateMatrixWorld();
539
+ }
540
+ }
541
+
542
+ /** Drops the retained plan, for any frame the mirror it described no longer holds. */
543
+ #forgetPlan(): void {
544
+ this.#retainedPlan = undefined;
545
+ this.#stability.clear();
546
+ }
547
+
548
+ #publish(): void {
549
+ // Re-announced when the verdict changes. A scene that projects at startup and gives up ten
550
+ // minutes later has changed the thing worth knowing, and reporting only the first frame hides
551
+ // exactly the transition a player would notice.
552
+ if (this.#lastAnnounced !== this.#reasonCode) {
553
+ this.#lastAnnounced = this.#reasonCode;
554
+ this.#reported = false;
555
+ }
556
+ if (this.#reported) return;
557
+ if (this.#onReport === undefined) {
558
+ // Reported by default, exactly as the pass this replaced did, and for the reason that pass
559
+ // did it: an optimizer that decides silently is one nobody can debug. The frame rate is
560
+ // simply bad, or the screen is simply black, and the reason never leaves the process. A game
561
+ // that had already merged its own scene was re-expanded into a thousand single-member draws
562
+ // and stalled on its loading screen; the first person to know was the person holding the
563
+ // phone, which is the wrong person.
564
+ this.#reported = true;
565
+ const r = this.report;
566
+ console.info(
567
+ `TN_RENDER_PROJECTION:${JSON.stringify({
568
+ projecting: r.projecting,
569
+ reasonCode: r.reasonCode,
570
+ ...(r.reason === undefined ? {} : { reason: r.reason }),
571
+ sourceRenderables: r.sourceRenderables,
572
+ resultDrawCandidates: r.resultDrawCandidates,
573
+ batches: r.batches,
574
+ instancedBatches: r.instancedBatches,
575
+ materialBatches: r.materialBatches,
576
+ skinnedBatches: r.skinnedBatches,
577
+ projectedObjects: r.projectedObjects,
578
+ exactObjects: r.exactObjects,
579
+ exact: r.exact,
580
+ // The colour lane's per-frame material proof, named with the bound it accepts: a spread
581
+ // check is a trade, and a trade nobody can read off the line is an invisible one.
582
+ materialChecks: r.materialChecks,
583
+ materialChecksPerFrame: r.materialChecksPerFrame,
584
+ materialCheckStaleFrames: r.materialCheckStaleFrames,
585
+ ...(r.materialChecksOverridden ? { materialChecksOverridden: true } : {}),
586
+ // Who batched the frame, so a measurement taken under `renderer.projection: "js"` says so.
587
+ path: r.path,
588
+ ...(r.pathOverridden ? { pathOverridden: true } : {}),
589
+ })}`,
590
+ );
591
+ return;
592
+ }
593
+ // Reported once the verdict is first reached, so a game waiting on startup is not woken by a
594
+ // frame counter. Deoptimization after that is visible through `report`, which is live.
595
+ this.#reported = true;
596
+ this.#onReport(this.report);
597
+ }
598
+
599
+ get report(): IRenderProjectionReport {
600
+ if (this.#host !== undefined) return this.#hostReport(this.#hostVerdict ?? NO_HOST_VERDICT);
601
+ const exact: Partial<Record<ProjectionExactReason, number>> = {};
602
+ for (const [reason, count] of this.#mirror?.exactCounts ?? []) exact[reason] = count;
603
+ let resultDrawCandidates = 0;
604
+ // Counted from the scene the renderer is actually handed. Anything else is this class marking
605
+ // its own homework.
606
+ this.root.traverse((object) => {
607
+ if (isRenderable(object)) resultDrawCandidates += 1;
608
+ });
609
+ const batches = this.#deoptimized ? 0 : (this.#mirror?.batchCount ?? 0);
610
+ const exactObjects = this.#deoptimized ? 0 : (this.#mirror?.proxyCount ?? 0);
611
+ return {
612
+ schemaVersion: 1,
613
+ projecting: !this.#deoptimized,
614
+ reasonCode: this.#reasonCode,
615
+ ...(this.#reason === undefined ? {} : { reason: this.#reason }),
616
+ sourceRenderables: this.#sourceRenderables,
617
+ resultDrawCandidates,
618
+ projectedObjects: this.#deoptimized ? 0 : (this.#mirror?.projectedObjects ?? 0),
619
+ batches,
620
+ instancedBatches: this.#deoptimized ? 0 : (this.#mirror?.instancedBatchCount ?? 0),
621
+ materialBatches: this.#deoptimized ? 0 : (this.#mirror?.materialBatchCount ?? 0),
622
+ skinnedBatches: this.#deoptimized ? 0 : (this.#mirror?.skinnedBatchCount ?? 0),
623
+ exactObjects,
624
+ // A declined frame renders the authored scene, so its plan is one draw per authored
625
+ // renderable — the number the projection is trying to beat, not zero.
626
+ drawsPlanned: this.#deoptimized ? this.#sourceRenderables : batches + exactObjects,
627
+ // Stated whether or not anything projected: the mode is a frame's cost, and a scene that
628
+ // declined still has no uniform members to spread the check over.
629
+ materialChecks: this.#materialChecks,
630
+ materialChecksPerFrame: this.#mirror?.materialChecksPerFrame ?? 0,
631
+ materialCheckStaleFrames: this.#mirror?.materialCheckStaleFrames ?? 0,
632
+ materialChecksOverridden: this.#materialChecks !== "spread",
633
+ path: "js",
634
+ pathOverridden: this.#hostOverridden,
635
+ exact,
636
+ timings: {
637
+ compileMs: this.#mirror?.compileMs ?? 0,
638
+ reconcileMs: this.#reconcileMs,
639
+ lastReconcileMs: this.#lastReconcileMs,
640
+ maxReconcileMs: this.#maxReconcileMs,
641
+ },
642
+ };
643
+ }
644
+
645
+ /**
646
+ * The report where the host batches the scene. The renderer is handed the authored scene, so the
647
+ * draw candidates are its renderables, and nothing here walks the scene to count them: that walk
648
+ * is the per-object boundary traffic this path exists to remove. `materialChecks*` describe the
649
+ * mirror's colour lane, which does not exist here, so they read as the unspent defaults.
650
+ */
651
+ #hostReport(verdict: IHostProjectionVerdict): IRenderProjectionReport {
652
+ const projecting = verdict.projecting;
653
+ const batches = projecting
654
+ ? verdict.instancedBatches + verdict.materialBatches + verdict.skinnedBatches
655
+ : 0;
656
+ const exactObjects = projecting ? verdict.exactObjects : 0;
657
+ return {
658
+ schemaVersion: 1,
659
+ projecting,
660
+ reasonCode: this.#reasonCode,
661
+ ...(this.#reason === undefined ? {} : { reason: this.#reason }),
662
+ sourceRenderables: verdict.sourceRenderables,
663
+ resultDrawCandidates: verdict.sourceRenderables,
664
+ projectedObjects: projecting ? verdict.projectedObjects : 0,
665
+ batches,
666
+ instancedBatches: projecting ? verdict.instancedBatches : 0,
667
+ materialBatches: projecting ? verdict.materialBatches : 0,
668
+ skinnedBatches: projecting ? verdict.skinnedBatches : 0,
669
+ exactObjects,
670
+ drawsPlanned: projecting ? batches + exactObjects : verdict.sourceRenderables,
671
+ materialChecks: this.#materialChecks,
672
+ materialChecksPerFrame: 0,
673
+ materialCheckStaleFrames: 0,
674
+ materialChecksOverridden: this.#materialChecks !== "spread",
675
+ path: "host",
676
+ pathOverridden: false,
677
+ exact: projecting ? verdict.exact : {},
678
+ timings: {
679
+ compileMs: 0,
680
+ reconcileMs: this.#reconcileMs,
681
+ lastReconcileMs: this.#lastReconcileMs,
682
+ maxReconcileMs: this.#maxReconcileMs,
683
+ },
684
+ };
685
+ }
686
+
687
+ /**
688
+ * What the mirror currently holds for one source object, or `undefined` if it holds nothing.
689
+ *
690
+ * Bounded diagnostics, for the load test and the unit tests: it answers "is this object being
691
+ * drawn, on which lane, and with what transform and visibility" without exposing the batches or
692
+ * the reconciliation state. Games never call this — there is no optimizer API in generated
693
+ * source, and this class is not part of the package's public surface — but a benchmark that
694
+ * cannot ask what the renderer was given can only report intent, and intent is not evidence.
695
+ */
696
+ inspect(
697
+ object: Object3D,
698
+ ): { lane: "batched" | "exact"; matrixWorld: Matrix4; visible: boolean } | undefined {
699
+ return this.#mirror?.inspect(object);
700
+ }
701
+
702
+ /** True when some batch in the mirror draws with this exact material instance. */
703
+ drawsWith(material: Material): boolean {
704
+ return this.#mirror?.drawsWith(material) ?? false;
705
+ }
706
+
707
+ /** Hands this frame back to the authored scene, naming why. */
708
+ #deoptimize(reasonCode: ProjectionReasonCode, reason: string): void {
709
+ this.#deoptimized = true;
710
+ this.#reasonCode = reasonCode;
711
+ this.#reason = reason;
712
+ }
713
+
714
+ /**
715
+ * Releases everything the mirror owns.
716
+ *
717
+ * Only the batches are disposed. Every geometry and material in here came from the game and is
718
+ * still the game's — disposing those would take a scene change down with it.
719
+ */
720
+ dispose(): void {
721
+ this.#mirror?.releaseAll();
722
+ this.#hostVerdict = undefined;
723
+ this.#velocityTracker.clear();
724
+ this.#forgetPlan();
725
+ releaseProjectionScanWorkspace(this.#scanWorkspace);
726
+ this.#deoptimized = true;
727
+ this.#reasonCode = "belowMeshFloor";
728
+ this.#reason = "the projection was disposed";
729
+ this.#reported = false;
730
+ this.#framesSinceDeclineScan = DECLINE_RESCAN_FRAMES;
731
+ }
732
+ }
733
+
734
+ export type ProjectionCamera = Camera;
735
+
736
+ function resolveVelocityEnabled(value: boolean | (() => boolean)): boolean {
737
+ const enabled = typeof value === "function" ? value() : value;
738
+ if (typeof enabled !== "boolean")
739
+ throw new Error(
740
+ `SceneRenderProjection.velocity must resolve to a boolean, received ${String(enabled)}.`,
741
+ );
742
+ return enabled;
743
+ }
744
+
745
+ /**
746
+ * Fail closed on a mode that is not one of the two: a game that wrote `"everyframe"` or
747
+ * `"sometimes"` gets a named throw at construction rather than a default nobody asked for.
748
+ */
749
+ function resolveMaterialChecks(
750
+ value: ProjectionMaterialChecks | undefined,
751
+ ): ProjectionMaterialChecks {
752
+ if (value === undefined) return "spread";
753
+ if (value !== "spread" && value !== "everyFrame")
754
+ throw new Error(
755
+ `SceneRenderProjection.materialChecks must be "spread" or "everyFrame", received ${JSON.stringify(value)}.`,
756
+ );
757
+ return value;
758
+ }