@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,222 @@
1
+ import type { Texture } from "three";
2
+
3
+ export type SpritePlaybackMode = "loop" | "pingPong" | "once";
4
+
5
+ export interface ISpriteFrame3D {
6
+ /** Pixels from the left edge of the atlas. */
7
+ readonly x: number;
8
+ /** Pixels from the top edge when `origin` is `"top-left"`. */
9
+ readonly y: number;
10
+ readonly width: number;
11
+ readonly height: number;
12
+ /** Seconds this frame is held; every frame must provide its own authored timing. */
13
+ readonly duration: number;
14
+ }
15
+
16
+ export interface ISpriteAnimator3DOptions {
17
+ /** The game-owned atlas texture. Its filters, wrapping and surface remain untouched. */
18
+ readonly texture: Texture;
19
+ /** Pixel-space atlas rectangles with per-frame durations. */
20
+ readonly frames: readonly ISpriteFrame3D[];
21
+ readonly mode?: SpritePlaybackMode;
22
+ /** Atlas coordinate origin; top-left is conventional for exported sprite sheets. */
23
+ readonly origin?: "top-left" | "bottom-left";
24
+ /** Start advancing immediately unless the game explicitly opts out. */
25
+ readonly autoPlay?: boolean;
26
+ }
27
+
28
+ /**
29
+ * Advance a game-owned atlas texture on the fixed step supplied by its owner.
30
+ *
31
+ * This helper changes only `texture.offset` and `texture.repeat`. The game still chooses the
32
+ * texture, filters, wrapping, surface, geometry and every frame's duration. Call {@link update}
33
+ * from the scene's fixed-step update; no wall clock or global animation loop is consulted.
34
+ */
35
+ export class SpriteAnimator3D {
36
+ readonly texture: Texture;
37
+ readonly frames: readonly ISpriteFrame3D[];
38
+ readonly mode: SpritePlaybackMode;
39
+ readonly origin: "top-left" | "bottom-left";
40
+ #elapsed = 0;
41
+ #finished = false;
42
+ #frameIndex = 0;
43
+ #playing: boolean;
44
+ #direction = 1;
45
+ readonly #atlasHeight: number;
46
+ readonly #atlasWidth: number;
47
+
48
+ constructor(options: ISpriteAnimator3DOptions) {
49
+ if (options === undefined || options === null || options.texture === undefined)
50
+ throw new Error("SpriteAnimator3D.texture is required.");
51
+ const image = options.texture.image as { height?: unknown; width?: unknown } | null | undefined;
52
+ if (
53
+ image === undefined ||
54
+ image === null ||
55
+ typeof image.width !== "number" ||
56
+ typeof image.height !== "number" ||
57
+ !Number.isFinite(image.width) ||
58
+ !Number.isFinite(image.height) ||
59
+ image.width <= 0 ||
60
+ image.height <= 0
61
+ )
62
+ throw new Error("SpriteAnimator3D.texture must have a positive atlas width and height.");
63
+ if (options.frames === undefined || options.frames === null || options.frames.length === 0)
64
+ throw new Error("SpriteAnimator3D.frames must contain at least one frame.");
65
+ const mode = options.mode ?? "loop";
66
+ if (mode !== "loop" && mode !== "pingPong" && mode !== "once")
67
+ throw new Error("SpriteAnimator3D.mode must be 'loop', 'pingPong', or 'once'.");
68
+ const origin = options.origin ?? "top-left";
69
+ if (origin !== "top-left" && origin !== "bottom-left")
70
+ throw new Error("SpriteAnimator3D.origin must be 'top-left' or 'bottom-left'.");
71
+
72
+ this.#atlasWidth = image.width;
73
+ this.#atlasHeight = image.height;
74
+ this.texture = options.texture;
75
+ this.frames = options.frames.map((frame, index) => {
76
+ if (
77
+ frame === undefined ||
78
+ !Number.isFinite(frame.x) ||
79
+ !Number.isFinite(frame.y) ||
80
+ !Number.isFinite(frame.width) ||
81
+ !Number.isFinite(frame.height) ||
82
+ frame.x < 0 ||
83
+ frame.y < 0 ||
84
+ frame.width <= 0 ||
85
+ frame.height <= 0 ||
86
+ frame.x + frame.width > this.#atlasWidth ||
87
+ frame.y + frame.height > this.#atlasHeight
88
+ )
89
+ throw new Error(`SpriteAnimator3D frame ${index} is outside the texture atlas.`);
90
+ if (!Number.isFinite(frame.duration) || frame.duration <= 0)
91
+ throw new Error(`SpriteAnimator3D frame duration ${index} must be positive and finite.`);
92
+ return { ...frame };
93
+ });
94
+ this.mode = mode;
95
+ this.origin = origin;
96
+ this.#playing = options.autoPlay ?? true;
97
+ this.#applyFrame();
98
+ }
99
+
100
+ get frameIndex(): number {
101
+ return this.#frameIndex;
102
+ }
103
+
104
+ get elapsed(): number {
105
+ return this.#elapsed;
106
+ }
107
+
108
+ get finished(): boolean {
109
+ return this.#finished;
110
+ }
111
+
112
+ get playing(): boolean {
113
+ return this.#playing;
114
+ }
115
+
116
+ /** Advance by one caller-supplied fixed-step delta. */
117
+ update(dt: number): this {
118
+ if (!Number.isFinite(dt) || dt < 0)
119
+ throw new Error("SpriteAnimator3D.update delta must be finite and non-negative.");
120
+ if (!this.#playing || this.#finished || dt === 0) return this;
121
+ if (this.frames.length === 1 && this.mode !== "once") {
122
+ const frame = this.frames[0];
123
+ if (frame === undefined) throw new Error("SpriteAnimator3D current frame is missing.");
124
+ this.#elapsed = (this.#elapsed + dt) % frame.duration;
125
+ return this;
126
+ }
127
+
128
+ let remaining = dt;
129
+ while (remaining > 0 && this.#playing && !this.#finished) {
130
+ const frame = this.frames[this.#frameIndex];
131
+ if (frame === undefined) throw new Error("SpriteAnimator3D current frame is missing.");
132
+ const untilNext = frame.duration - this.#elapsed;
133
+ if (remaining + Number.EPSILON < untilNext) {
134
+ this.#elapsed += remaining;
135
+ break;
136
+ }
137
+ remaining = Math.max(0, remaining - untilNext);
138
+ this.#elapsed = 0;
139
+ this.#advanceFrame();
140
+ }
141
+ return this;
142
+ }
143
+
144
+ /** Pause fixed-step advancement while leaving the selected frame visible. */
145
+ pause(): this {
146
+ this.#playing = false;
147
+ return this;
148
+ }
149
+
150
+ /** Resume, restarting a completed one-shot from frame zero. */
151
+ play(): this {
152
+ if (this.#finished) {
153
+ this.#frameIndex = 0;
154
+ this.#direction = 1;
155
+ this.#elapsed = 0;
156
+ this.#finished = false;
157
+ this.#applyFrame();
158
+ }
159
+ this.#playing = true;
160
+ return this;
161
+ }
162
+
163
+ /** Stop and reset to the first authored frame. */
164
+ stop(): this {
165
+ this.#playing = false;
166
+ this.#finished = false;
167
+ this.#frameIndex = 0;
168
+ this.#direction = 1;
169
+ this.#elapsed = 0;
170
+ this.#applyFrame();
171
+ return this;
172
+ }
173
+
174
+ /** Select a frame without advancing time. */
175
+ setFrame(index: number): this {
176
+ if (!Number.isInteger(index) || index < 0 || index >= this.frames.length)
177
+ throw new Error("SpriteAnimator3D frame index must be an in-range integer.");
178
+ this.#frameIndex = index;
179
+ this.#direction = index === this.frames.length - 1 ? -1 : 1;
180
+ this.#elapsed = 0;
181
+ this.#finished = false;
182
+ this.#applyFrame();
183
+ return this;
184
+ }
185
+
186
+ #advanceFrame(): void {
187
+ if (this.mode === "once") {
188
+ if (this.#frameIndex === this.frames.length - 1) {
189
+ this.#finished = true;
190
+ this.#playing = false;
191
+ this.#applyFrame();
192
+ return;
193
+ }
194
+ this.#frameIndex += 1;
195
+ } else if (this.mode === "loop") {
196
+ this.#frameIndex = (this.#frameIndex + 1) % this.frames.length;
197
+ } else if (this.frames.length > 1) {
198
+ if (this.#direction > 0) {
199
+ if (this.#frameIndex === this.frames.length - 1) {
200
+ this.#direction = -1;
201
+ this.#frameIndex -= 1;
202
+ } else this.#frameIndex += 1;
203
+ } else if (this.#frameIndex === 0) {
204
+ this.#direction = 1;
205
+ this.#frameIndex += 1;
206
+ } else this.#frameIndex -= 1;
207
+ }
208
+ this.#applyFrame();
209
+ }
210
+
211
+ #applyFrame(): void {
212
+ const frame = this.frames[this.#frameIndex];
213
+ if (frame === undefined) throw new Error("SpriteAnimator3D current frame is missing.");
214
+ this.texture.repeat.set(frame.width / this.#atlasWidth, frame.height / this.#atlasHeight);
215
+ const y =
216
+ this.origin === "top-left"
217
+ ? (this.#atlasHeight - frame.y - frame.height) / this.#atlasHeight
218
+ : frame.y / this.#atlasHeight;
219
+ this.texture.offset.set(frame.x / this.#atlasWidth, y);
220
+ this.texture.updateMatrix();
221
+ }
222
+ }
@@ -0,0 +1,386 @@
1
+ export type StartupCompile = () => Promise<void> | void;
2
+
3
+ export interface IStartupReadinessOptions {
4
+ /** Maximum wall-clock time spent waiting for first-use compilation. */
5
+ readonly compileBudgetMs?: number;
6
+ /** Maximum measured callback duration for a stable startup frame. */
7
+ readonly frameBudgetMs?: number;
8
+ /** Number of consecutive in-budget frames required after compilation settles. */
9
+ readonly stableFrames?: number;
10
+ /**
11
+ * How long after first-use work settles the readiness still waits for sustained in-budget
12
+ * frames before resolving anyway. Default 10 000 ms.
13
+ *
14
+ * A host whose steady state runs entirely above `frameBudgetMs` would otherwise hold a loading
15
+ * screen open for as long as the game ran — the frame window must be bounded like every other
16
+ * launch-path wait, because a launch that is slower than it could be is a disappointment and a
17
+ * launch that never finishes is a bug.
18
+ */
19
+ readonly stableWindowMs?: number;
20
+ /** Default ceiling on a single `hold()`, when the caller does not give one. */
21
+ readonly holdBudgetMs?: number;
22
+ /**
23
+ * Run after every hold settles and before readiness resolves.
24
+ *
25
+ * This is where a second warm-up belongs. The framework's own compile pass runs when the
26
+ * *framework* is ready, which for a game that streams a second asset tier is before most of the
27
+ * world exists — so the pass sees the critical scene and nothing else, and every material the
28
+ * game attaches afterwards compiles the first time the player walks into view of it. Measured on
29
+ * a forest of 46,190 instances: `TN_STARTUP_WARMUP` reported **8 pipelines**, and the session
30
+ * then hit 28 main-thread tasks over 40 ms, the worst 267 ms, dominated by TSL graph `build` and
31
+ * by the main thread idling on GPU pipeline creation.
32
+ *
33
+ * Rejections are swallowed: a warm-up that fails must cost hitches, never a game that will not
34
+ * start.
35
+ */
36
+ readonly afterHolds?: () => Promise<void> | void;
37
+ }
38
+
39
+ /**
40
+ * The startup contract shared by the loading screen and the native/web render loop.
41
+ *
42
+ * The 50 ms frame budget is above the observed steady-state windows (20.9 ms and 33.5 ms) while
43
+ * rejecting the 76 ms startup window that preceded the reported stall. Five consecutive frames
44
+ * keep a loading screen up through recurring first-use work instead of treating one quiet frame as
45
+ * readiness. Compilation is bounded because the native host has shipped renderers whose
46
+ * `compileAsync()` promise never settles.
47
+ */
48
+ export const STARTUP_COMPILE_BUDGET_MS = 15_000;
49
+ /**
50
+ * How long both display progress and measured startup work may stand still before a stall report.
51
+ * Generous on purpose: one large model legitimately holds the main thread for tens of seconds
52
+ * while it decodes (43 s for one measured aircraft), the bar only moves as assets settle, and a
53
+ * false stall report is worse than none. It is not a timeout — nothing is cancelled.
54
+ */
55
+ export const STARTUP_STALL_MS = 45_000;
56
+ export const STARTUP_FRAME_BUDGET_MS = 50;
57
+ export const STARTUP_STABLE_FRAMES = 5;
58
+ /**
59
+ * How long the sustained-frame window may wait past compile settlement before resolving anyway.
60
+ * Above every observed healthy startup (five sub-50 ms frames inside one second) but short enough
61
+ * that a device running above budget forever still reaches its game in seconds, not never.
62
+ */
63
+ export const STARTUP_STABLE_WINDOW_MS = 10_000;
64
+ /**
65
+ * Default ceiling on one game-registered `hold()`.
66
+ *
67
+ * Longer than the other launch budgets because what it bounds is a game's own asset tier over a
68
+ * network rather than local compilation — 70 model files on a cold cache is seconds, and cutting a
69
+ * cold first launch off at ten would ship a thinner world to exactly the players who waited. Still
70
+ * bounded, for the same reason everything else here is: a hold that never settles must cost a
71
+ * poorer-looking game and never a game that does not start.
72
+ */
73
+ export const STARTUP_HOLD_BUDGET_MS = 45_000;
74
+
75
+ /** One registered hold: the game's own launch work, and the bounded wait for it. */
76
+ interface IHold {
77
+ readonly label: string;
78
+ /** Polled once per rendered frame for a predicate hold; absent for a promise hold. */
79
+ readonly ready?: () => boolean;
80
+ release?: (expired: boolean) => void;
81
+ settled: boolean;
82
+ timer: ReturnType<typeof setTimeout> | undefined;
83
+ expired: boolean;
84
+ progress: (() => number) | undefined;
85
+ completed: number;
86
+ }
87
+
88
+ export class StartupReadiness {
89
+ #compileBudgetMs: number;
90
+ #frameBudgetMs: number;
91
+ #stableFrameLimit: number;
92
+ #stableWindowMs: number;
93
+ #compileSettled = false;
94
+ #stableFrameCount = 0;
95
+ #started = false;
96
+ #ready = false;
97
+ #frameWindowDone = false;
98
+ readonly #holds = new Map<string, IHold>();
99
+ #holdBudgetMs: number;
100
+ #afterHolds: (() => Promise<void> | void) | undefined;
101
+ #compileTimer: ReturnType<typeof setTimeout> | undefined;
102
+ #windowTimer: ReturnType<typeof setTimeout> | undefined;
103
+ #resolveReady: () => void = () => undefined;
104
+ #resolveFrameworkReady: () => void = () => undefined;
105
+ readonly #readyPromise: Promise<void>;
106
+ readonly #frameworkReadyPromise: Promise<void>;
107
+
108
+ constructor(options: IStartupReadinessOptions = {}) {
109
+ this.#compileBudgetMs = positiveNumber(
110
+ options.compileBudgetMs ?? STARTUP_COMPILE_BUDGET_MS,
111
+ "compileBudgetMs",
112
+ );
113
+ this.#frameBudgetMs = positiveNumber(
114
+ options.frameBudgetMs ?? STARTUP_FRAME_BUDGET_MS,
115
+ "frameBudgetMs",
116
+ );
117
+ this.#stableFrameLimit = positiveInteger(
118
+ options.stableFrames ?? STARTUP_STABLE_FRAMES,
119
+ "stableFrames",
120
+ );
121
+ this.#stableWindowMs = positiveNumber(
122
+ options.stableWindowMs ?? STARTUP_STABLE_WINDOW_MS,
123
+ "stableWindowMs",
124
+ );
125
+ this.#holdBudgetMs = positiveNumber(
126
+ options.holdBudgetMs ?? STARTUP_HOLD_BUDGET_MS,
127
+ "holdBudgetMs",
128
+ );
129
+ this.#afterHolds = options.afterHolds;
130
+ this.#readyPromise = new Promise<void>((resolve) => {
131
+ this.#resolveReady = resolve;
132
+ });
133
+ this.#frameworkReadyPromise = new Promise<void>((resolve) => {
134
+ this.#resolveFrameworkReady = resolve;
135
+ });
136
+ }
137
+
138
+ whenReady(): Promise<void> {
139
+ return this.#readyPromise;
140
+ }
141
+
142
+ /**
143
+ * Resolves when the framework's own launch work is done, before any game `hold()`.
144
+ *
145
+ * The host needs this separately from `whenReady()`: it is the moment the framework's cost can
146
+ * be stamped, and it is also when the loop may start presenting the game's own progress.
147
+ */
148
+ whenFrameworkReady(): Promise<void> {
149
+ return this.#frameworkReadyPromise;
150
+ }
151
+
152
+ /** True once first-use compilation settled or its bounded wait expired. */
153
+ get compileSettled(): boolean {
154
+ return this.#compileSettled;
155
+ }
156
+
157
+ /** True after the sustained in-budget frame window has completed. */
158
+ get ready(): boolean {
159
+ return this.#ready;
160
+ }
161
+
162
+ /**
163
+ * True once the framework's own launch work is done: compilation settled and the frame window
164
+ * held. Earlier than `ready` whenever the game has registered a hold.
165
+ *
166
+ * Kept separate and kept observable because making `ready` mean "the player can see the world"
167
+ * would otherwise delete the only measurement of how long the *framework* took, and a game with
168
+ * a slow asset tier would hide a framework regression inside its own loading time.
169
+ */
170
+ get frameworkReady(): boolean {
171
+ return this.#frameWindowDone;
172
+ }
173
+
174
+ /** Labels of holds that have not settled yet, in registration order. */
175
+ get pendingHolds(): readonly string[] {
176
+ return [...this.#holds.values()].filter((hold) => !hold.settled).map((hold) => hold.label);
177
+ }
178
+
179
+ /** Completed units from active holds; settled holds freeze their count. Display progress is separate. */
180
+ get workProgress(): number {
181
+ let completed = 0;
182
+ for (const hold of this.#holds.values()) {
183
+ if (!hold.settled) this.#sampleHold(hold);
184
+ completed += hold.completed;
185
+ }
186
+ return completed;
187
+ }
188
+
189
+ /** Every hold's label paired with whether it settled inside its budget. */
190
+ get holdReport(): readonly { readonly expired: boolean; readonly label: string }[] {
191
+ return [...this.#holds.values()].map((hold) => ({ expired: hold.expired, label: hold.label }));
192
+ }
193
+
194
+ /**
195
+ * Add the game's own launch work to the readiness gate.
196
+ *
197
+ * The framework's readiness covers the framework's work — first-use compilation and a sustained
198
+ * frame window — and knows nothing about a second asset tier the game streams after it. Without
199
+ * this, a game that streams one has two bad options: show a half-built world, or hold its own
200
+ * curtain past `whenReady()` and leave every framework-owned observation describing a moment the
201
+ * player never experienced. `timeline.readyMs` reported 1.5 s on a valley that took 8.8 s to
202
+ * appear, and `assert.startup`'s `maxReadyMs` passed on it, because both measure this gate.
203
+ *
204
+ * So the gate takes the game's work too, and then the numbers are about the player again.
205
+ *
206
+ * Fails open, deliberately, twice over: a hold that rejects is treated as settled, and
207
+ * `budgetMs` bounds how long it may delay the world. A launch that is slower than it could be is
208
+ * a disappointment; a launch that never finishes because one texture 404'd is a bug. `expired`
209
+ * on the report says which happened, so a hold that timed out is visible rather than silent.
210
+ *
211
+ * Throws on a duplicate label, and on a hold registered after the gate has already resolved —
212
+ * both mean the caller believes it is gating something it is not, which is the failure this
213
+ * whole seam exists to remove.
214
+ */
215
+ hold(
216
+ label: string,
217
+ work: Promise<unknown> | (() => boolean),
218
+ budgetMs: number = this.#holdBudgetMs,
219
+ progress?: () => number,
220
+ ): void {
221
+ if (typeof label !== "string" || label.trim() === "")
222
+ throw new Error("TN_STARTUP_HOLD_LABEL_INVALID: a hold needs a non-empty label.");
223
+ if (this.#holds.has(label))
224
+ throw new Error(`TN_STARTUP_HOLD_DUPLICATE: '${label}' is already holding startup.`);
225
+ if (this.#ready)
226
+ throw new Error(
227
+ `TN_STARTUP_HOLD_TOO_LATE: '${label}' was registered after startup already resolved.`,
228
+ );
229
+ const bounded = positiveNumber(budgetMs, "holdBudgetMs");
230
+ const hold: IHold = {
231
+ completed: 0,
232
+ expired: false,
233
+ label,
234
+ progress,
235
+ settled: false,
236
+ timer: undefined,
237
+ ...(typeof work === "function" ? { ready: work } : {}),
238
+ };
239
+ this.#holds.set(label, hold);
240
+ const release = (expired: boolean): void => {
241
+ if (hold.settled) return;
242
+ this.#sampleHold(hold);
243
+ hold.progress = undefined;
244
+ hold.settled = true;
245
+ hold.expired = expired;
246
+ if (hold.timer !== undefined) clearTimeout(hold.timer);
247
+ hold.timer = undefined;
248
+ this.#resolveIfComplete();
249
+ };
250
+ hold.timer = setTimeout(() => release(true), bounded);
251
+ hold.release = release;
252
+ if (typeof work === "function") return;
253
+ void Promise.resolve(work).then(
254
+ () => release(false),
255
+ () => release(false),
256
+ );
257
+ }
258
+
259
+ #sampleHold(hold: IHold): void {
260
+ try {
261
+ const measured = hold.progress?.();
262
+ // Invalid or regressing observations cannot buy more time for a stalled launch.
263
+ if (measured !== undefined && Number.isFinite(measured))
264
+ hold.completed = Math.max(hold.completed, measured);
265
+ } catch {
266
+ // Observation cannot block settlement or disable stall detection; failed reads get no credit.
267
+ }
268
+ }
269
+
270
+ /**
271
+ * Predicate holds settle on rendered frames, not simulation steps: a deterministic playtest clock
272
+ * advances no fixed step while startup is held, so a gate read only in `afterPhysics` waited on
273
+ * itself until its deadline. A throwing predicate fails open, like a rejected promise.
274
+ */
275
+ #pollHolds(): void {
276
+ for (const hold of this.#holds.values()) {
277
+ if (hold.settled || hold.ready === undefined) continue;
278
+ let done: boolean;
279
+ try {
280
+ done = hold.ready();
281
+ } catch {
282
+ done = true;
283
+ }
284
+ if (done) hold.release?.(false);
285
+ }
286
+ }
287
+
288
+ /** Begin the one-time first-use gate after the entered scene has been built. */
289
+ start(compile?: StartupCompile): void {
290
+ if (this.#started) return;
291
+ this.#started = true;
292
+ if (compile === undefined) {
293
+ this.#finishCompile();
294
+ return;
295
+ }
296
+
297
+ this.#compileTimer = setTimeout(() => this.#finishCompile(), this.#compileBudgetMs);
298
+ // Defer the call one microtask so the already-visible loading layer gets a present before a
299
+ // renderer that performs synchronous first-use work starts compiling.
300
+ void Promise.resolve()
301
+ .then(() => compile())
302
+ .then(
303
+ () => this.#finishCompile(),
304
+ () => this.#finishCompile(),
305
+ );
306
+ }
307
+
308
+ /** Feed actual callback wall time, not requestAnimationFrame timestamp spacing. */
309
+ observe(frameMs: number): void {
310
+ if (!this.#ready) this.#pollHolds();
311
+ if (!this.#started || this.#ready) return;
312
+ if (
313
+ this.#compileSettled &&
314
+ Number.isFinite(frameMs) &&
315
+ frameMs >= 0 &&
316
+ frameMs <= this.#frameBudgetMs
317
+ ) {
318
+ this.#stableFrameCount += 1;
319
+ } else {
320
+ this.#stableFrameCount = 0;
321
+ }
322
+ if (this.#stableFrameCount >= this.#stableFrameLimit) {
323
+ this.#finishFrameWindow();
324
+ }
325
+ }
326
+
327
+ #finishCompile(): void {
328
+ if (this.#compileSettled) return;
329
+ this.#compileSettled = true;
330
+ if (this.#compileTimer !== undefined) clearTimeout(this.#compileTimer);
331
+ this.#compileTimer = undefined;
332
+ // The frame window is the last launch-path wait left, so it is bounded too: a host that never
333
+ // produces an in-budget frame still gets its world within `stableWindowMs`.
334
+ this.#windowTimer = setTimeout(() => {
335
+ this.#windowTimer = undefined;
336
+ this.#finishFrameWindow();
337
+ }, this.#stableWindowMs);
338
+ }
339
+
340
+ /** The framework's own work is done. Whether the *world* is ready also depends on the holds. */
341
+ #finishFrameWindow(): void {
342
+ if (this.#frameWindowDone) return;
343
+ this.#frameWindowDone = true;
344
+ if (this.#windowTimer !== undefined) clearTimeout(this.#windowTimer);
345
+ this.#windowTimer = undefined;
346
+ this.#resolveFrameworkReady();
347
+ this.#resolveIfComplete();
348
+ }
349
+
350
+ #resolveIfComplete(): void {
351
+ if (this.#ready || !this.#frameWindowDone) return;
352
+ for (const hold of this.#holds.values()) if (!hold.settled) return;
353
+ // Claim readiness before awaiting, so a hold that settles during `afterHolds` cannot re-enter
354
+ // and run it twice.
355
+ this.#ready = true;
356
+ const afterHolds = this.#afterHolds;
357
+ // No holds means no second tier, which means the framework's own pass already saw the whole
358
+ // scene. Resolving synchronously there keeps every game that does not stream exactly as it was.
359
+ if (afterHolds === undefined || this.#holds.size === 0) {
360
+ this.#resolveReady();
361
+ return;
362
+ }
363
+ void (async () => {
364
+ try {
365
+ await afterHolds();
366
+ } catch {
367
+ // Swallowed on purpose: a warm-up that fails costs hitches, not a game that never starts.
368
+ }
369
+ this.#resolveReady();
370
+ })();
371
+ }
372
+ }
373
+
374
+ function positiveNumber(value: number, name: string): number {
375
+ if (!Number.isFinite(value) || value <= 0)
376
+ throw new Error(`TN_STARTUP_${name.toUpperCase()}_INVALID: ${name} must be positive.`);
377
+ return value;
378
+ }
379
+
380
+ function positiveInteger(value: number, name: string): number {
381
+ if (!Number.isInteger(value) || value < 1)
382
+ throw new Error(
383
+ `TN_STARTUP_${name.toUpperCase()}_INVALID: ${name} must be a positive integer.`,
384
+ );
385
+ return value;
386
+ }
package/src/state.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { type StoreApi, createStore } from "zustand/vanilla";
2
+
3
+ export type StatePatch<T extends Record<string, unknown>> = Partial<T> | ((state: T) => Partial<T>);
4
+
5
+ export type GameStore<T extends Record<string, unknown>> = StoreApi<T> & {
6
+ getPublishedState(): T;
7
+ set(patch: StatePatch<T>): void;
8
+ flush(): void;
9
+ start(): void;
10
+ stop(): void;
11
+ };
12
+
13
+ /**
14
+ * A store the UI reads, coalesced to one publication per frame unless a game names an interval.
15
+ *
16
+ * `intervalMs` is an override, not the rule. A fixed 100 ms default published the HUD ten times a
17
+ * second whatever the frame rate was, which reads as a HUD that is not live — the number a player
18
+ * watches moves in visible steps while the scene beside it runs smoothly. Left unset, `flush` is
19
+ * called once per frame by the loop that draws that frame, so a HUD updates at the rate the game
20
+ * actually runs at, and a slower interval is available to a game that measured a reason for one.
21
+ */
22
+ export function createGameStore<T extends Record<string, unknown>>(
23
+ initial: T,
24
+ intervalMs?: number,
25
+ ): GameStore<T> {
26
+ const store = createStore<T>(() => ({ ...initial }));
27
+ const getPublishedState = store.getState;
28
+ const current = { ...initial };
29
+ const pending: Partial<T> = {};
30
+ let hasPending = false;
31
+ let timer: ReturnType<typeof setInterval> | undefined;
32
+ store.subscribe((state) => {
33
+ for (const key in current) {
34
+ if (!(key in state)) Reflect.deleteProperty(current, key);
35
+ }
36
+ Object.assign(current, state);
37
+ });
38
+ const flush = () => {
39
+ if (!hasPending) return;
40
+ hasPending = false;
41
+ const patch = { ...pending };
42
+ for (const key in pending) Reflect.deleteProperty(pending, key);
43
+ store.setState(patch);
44
+ };
45
+ const gameStore = store as GameStore<T>;
46
+ gameStore.getPublishedState = getPublishedState;
47
+ gameStore.getState = () => current;
48
+ gameStore.set = (patch: StatePatch<T>) => {
49
+ const next = typeof patch === "function" ? patch(current) : patch;
50
+ Object.assign(pending, next);
51
+ Object.assign(current, next);
52
+ hasPending = true;
53
+ };
54
+ gameStore.flush = flush;
55
+ gameStore.start = () => {
56
+ // No interval means the frame drives the flush; only a game that named one gets a timer.
57
+ if (intervalMs === undefined || timer !== undefined) return;
58
+ timer = setInterval(flush, intervalMs);
59
+ };
60
+ gameStore.stop = () => {
61
+ if (timer !== undefined) clearInterval(timer);
62
+ timer = undefined;
63
+ flush();
64
+ };
65
+ return gameStore;
66
+ }