@threenative/core 0.3.5 → 0.3.8

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 (137) hide show
  1. package/README.md +3 -5
  2. package/capabilities.json +739 -50
  3. package/dist/{assets-CqvE429w.d.ts → assets-YUbXa3-Y.d.ts} +101 -2
  4. package/dist/{canvas-layer-C1-5CviZ.d.ts → canvas-layer-vCtanIeB.d.ts} +1 -1
  5. package/dist/{game-Bj8G1wmD.d.ts → game-cb99J-YE.d.ts} +112 -31
  6. package/dist/hot.d.ts +4 -4
  7. package/dist/hot.js +23 -5
  8. package/dist/index.d.ts +1742 -29
  9. package/dist/index.js +22445 -12411
  10. package/dist/{model-lod-BDAUYgsS.d.ts → model-lod-CTpZ6imz.d.ts} +1 -1
  11. package/dist/net.js +39 -12
  12. package/dist/playtest.d.ts +4 -4
  13. package/dist/playtest.js +59 -10
  14. package/dist/react-css.js +23 -0
  15. package/dist/react.d.ts +2 -2
  16. package/dist/{renderer-9yEo9hPa.d.ts → renderer-rZm0hVqq.d.ts} +178 -5
  17. package/dist/ui-layer.d.ts +11 -2
  18. package/dist/ui-layer.js +76 -4
  19. package/dist/worker.d.ts +36 -0
  20. package/dist/worker.js +1088 -0
  21. package/dist/world.d.ts +11 -3
  22. package/dist/world.js +1117 -197
  23. package/mcp/animation-server.mjs +265 -0
  24. package/mcp/animation.mjs +22 -0
  25. package/mcp/call.mjs +105 -0
  26. package/mcp/devtools.mjs +5 -0
  27. package/mcp/engine-server.mjs +713 -37
  28. package/mcp/launch.mjs +3 -2
  29. package/mcp/servers.d.mts +2 -0
  30. package/mcp/servers.mjs +33 -8
  31. package/package.json +12 -8
  32. package/patches/three@0.185.1-prd269-upgrade.patch +308 -0
  33. package/patches/three@0.185.1.patch +481 -272
  34. package/src/animation-packet-state.ts +88 -0
  35. package/src/animation-pose-packet.ts +537 -0
  36. package/src/animation.ts +779 -31
  37. package/src/asset-cache.ts +719 -0
  38. package/src/assets.ts +521 -152
  39. package/src/audio.ts +29 -3
  40. package/src/auto-batch.ts +792 -0
  41. package/src/config.ts +2 -0
  42. package/src/frame-budget.ts +268 -2
  43. package/src/game.ts +544 -106
  44. package/src/grounding.ts +7 -6
  45. package/src/hot.ts +19 -5
  46. package/src/index.ts +381 -6
  47. package/src/input.ts +21 -2
  48. package/src/interpolation.ts +19 -1
  49. package/src/launch-diagnostics.ts +7 -2
  50. package/src/look/ao-multibounce.ts +29 -0
  51. package/src/look/ao-reach.ts +39 -0
  52. package/src/look/auto-exposure.ts +264 -0
  53. package/src/look/default-tone-mapping.ts +44 -0
  54. package/src/look/exposure-graph.ts +208 -0
  55. package/src/look/exposure-readback.ts +97 -0
  56. package/src/look/exposure-settings.ts +132 -0
  57. package/src/look/filmic-tone-mapping.ts +852 -0
  58. package/src/look/gi-registry.ts +55 -0
  59. package/src/look/local-exposure.ts +507 -0
  60. package/src/look/look-diagnostics.ts +24 -0
  61. package/src/look/motion-blur.ts +42 -0
  62. package/src/look/quality.ts +309 -0
  63. package/src/look/reflection-trace.ts +344 -0
  64. package/src/look/unreal-bloom.ts +295 -0
  65. package/src/look/vignette.ts +14 -0
  66. package/src/look/world-environment.ts +2033 -0
  67. package/src/loop.ts +40 -6
  68. package/src/merge-parts.ts +25 -10
  69. package/src/model-lod.ts +14 -0
  70. package/src/net-session.ts +58 -14
  71. package/src/ocean/spectral.ts +41 -7
  72. package/src/picking.ts +72 -5
  73. package/src/platform.ts +29 -1
  74. package/src/playtest.ts +69 -12
  75. package/src/profiling/FrameCounters.ts +166 -5
  76. package/src/profiling/FrameStages.ts +289 -0
  77. package/src/profiling/Spans.ts +39 -25
  78. package/src/profiling/debug-telemetry.ts +312 -0
  79. package/src/profiling/scene-warning.ts +42 -6
  80. package/src/projection-apply.ts +11 -3
  81. package/src/projection-content.ts +189 -0
  82. package/src/projection-marker.ts +6 -2
  83. package/src/projection-plan.ts +279 -28
  84. package/src/projection-skinned.ts +620 -5
  85. package/src/projection-stability.ts +16 -0
  86. package/src/projection-uniform.ts +5 -1
  87. package/src/quiet-markers.ts +56 -0
  88. package/src/render/budget-ladder.ts +256 -0
  89. package/src/render/chain.ts +89 -7
  90. package/src/render/exposure-units.ts +59 -0
  91. package/src/render/frame-time-budget.ts +162 -0
  92. package/src/render/gi-budget.ts +231 -0
  93. package/src/render/gi-visualize.ts +49 -0
  94. package/src/render/material-key.ts +1 -0
  95. package/src/render/probe-volume.ts +196 -36
  96. package/src/render/rough-diffuse.ts +177 -0
  97. package/src/render/scene-trace.ts +532 -0
  98. package/src/render/shadow-filter-budget.ts +237 -0
  99. package/src/render/sky-capture.ts +194 -0
  100. package/src/render/soft-shadow.ts +607 -0
  101. package/src/render/surface-cache.ts +418 -0
  102. package/src/render/traced-reflections.ts +408 -0
  103. package/src/render/two-sided-foliage.ts +120 -0
  104. package/src/render/virtual-shadow-pages.ts +112 -12
  105. package/src/render/virtual-shadow.ts +386 -38
  106. package/src/render-camera-cull.ts +536 -31
  107. package/src/render-pass-budget.ts +140 -22
  108. package/src/renderProjection.ts +65 -9
  109. package/src/renderer-config.ts +3 -2
  110. package/src/renderer.ts +289 -14
  111. package/src/resolution-scaler.ts +65 -7
  112. package/src/skeletal-mesh.ts +4 -0
  113. package/src/snow-field.ts +46 -0
  114. package/src/softbody.ts +6 -5
  115. package/src/startup-offscreen-bytes.ts +168 -0
  116. package/src/startup-readiness.ts +137 -2
  117. package/src/ui-bridge.ts +38 -0
  118. package/src/ui-hit-regions.ts +6 -2
  119. package/src/ui-layer.ts +1 -0
  120. package/src/ui-state.ts +32 -3
  121. package/src/version.ts +1 -1
  122. package/src/viewport.ts +8 -5
  123. package/src/warmup.ts +76 -10
  124. package/src/worker-audio.ts +579 -0
  125. package/src/worker.ts +842 -0
  126. package/src/world-cells.ts +4 -1
  127. package/gpl/LICENSE.GPL +0 -117
  128. package/gpl/convert.py +0 -192
  129. package/gpl/fixtures/make_world_fixture.py +0 -184
  130. package/gpl/recipes/_common.py +0 -180
  131. package/gpl/recipes/bake_ao.py +0 -111
  132. package/gpl/recipes/decimate.py +0 -70
  133. package/gpl/recipes/export_world.py +0 -699
  134. package/gpl/recipes/retarget.py +0 -131
  135. package/gpl/recipes/unwrap.py +0 -71
  136. package/mcp/blender-server.mjs +0 -689
  137. package/mcp/blender.mjs +0 -26
@@ -0,0 +1,719 @@
1
+ import { isNative } from "./platform.js";
2
+
3
+ /**
4
+ * What a request is worth relative to the rest of the queue.
5
+ *
6
+ * `now` is a file the running scene awaits, `soon` is a `WorldCells` prefetch, and `idle` is the
7
+ * background fill. A `now` request starts at once and pauses new `soon` and `idle` starts until it
8
+ * settles, so a fill can never sit in front of the file the frame needs.
9
+ */
10
+ export type AssetPriority = "now" | "soon" | "idle";
11
+
12
+ export interface IAssetCacheEntry {
13
+ /** The compiled size the manifest records, when it records one. */
14
+ readonly bytes?: number;
15
+ readonly url: string;
16
+ }
17
+
18
+ export interface IAssetCacheReport {
19
+ /** False on a native host, with `reason`, or when the game passed `assets.cache: false`. */
20
+ readonly enabled: boolean;
21
+ /** Whether the browser granted persistent storage. False when it refused or could not answer. */
22
+ readonly persisted: boolean;
23
+ readonly hits: number;
24
+ readonly misses: number;
25
+ readonly bytesOnDisk: number;
26
+ readonly bytesTotal: number;
27
+ readonly filling: boolean;
28
+ /** True when the post-reveal fill is allowed (`assets.backgroundFill` and no `saveData`). */
29
+ readonly backgroundFill: boolean;
30
+ readonly reason?: string;
31
+ }
32
+
33
+ export interface IAssetCacheOptions {
34
+ /** `assets.cache: false` — the named override. */
35
+ readonly enabled?: boolean;
36
+ /** `assets.backgroundFill: false` — the named override. */
37
+ readonly backgroundFill?: boolean;
38
+ /** Requests running at once. Defaults to six, the same as the streaming loader. */
39
+ readonly concurrency?: number;
40
+ /** Retry delays in milliseconds. Defaults to 500, 1000 and 2000. */
41
+ readonly retryDelaysMs?: readonly number[];
42
+ /** A stable game identity, so two games on one origin do not delete each other's cache. */
43
+ readonly namespace?: string;
44
+ }
45
+
46
+ export interface IAssetCache {
47
+ readonly enabled: boolean;
48
+ readonly report: IAssetCacheReport;
49
+ /** Bytes for `url`, from disk when present and from the network otherwise. */
50
+ fetchBytes(url: string, priority?: AssetPriority, expectedBytes?: number): Promise<ArrayBuffer>;
51
+ /** Raise a download still in flight to `priority`. A url with no download in flight is a no-op. */
52
+ promote(url: string, priority: AssetPriority): void;
53
+ /** Warm the disk with these files. Resolves when every request settles. */
54
+ prefetch(entries: readonly IAssetCacheEntry[]): Promise<void>;
55
+ /** Name the release and the files it publishes. Called once, when the manifest lands. */
56
+ setManifest(entries: readonly IAssetCacheEntry[]): void;
57
+ /** Start the post-reveal fill of everything not on disk yet. Idempotent. */
58
+ startFill(): Promise<void>;
59
+ /** Delete the whole cache. */
60
+ clear(): Promise<void>;
61
+ /** Remove the disk-first fetch bridge. Idempotent. */
62
+ dispose(): void;
63
+ }
64
+
65
+ const CACHE_NAME = "threenative-assets";
66
+ const DEFAULT_CONCURRENCY = 6;
67
+ const DEFAULT_RETRY_DELAYS_MS = [500, 1000, 2000] as const;
68
+ const BYTES_HEADER = "x-tn-bytes";
69
+ const ACCESS_HEADER = "x-tn-access";
70
+ /** How often a read refreshes an entry's access stamp. Unreal purges at the same granularity. */
71
+ const ACCESS_REFRESH_MS = 3_600_000;
72
+
73
+ /** Lower is more urgent. */
74
+ export const PRIORITY_ORDER: Record<AssetPriority, number> = { now: 0, soon: 1, idle: 2 };
75
+
76
+ type CacheStorageLike = {
77
+ delete(name: string): Promise<boolean>;
78
+ keys(): Promise<readonly string[]>;
79
+ open(name: string): Promise<CacheLike>;
80
+ };
81
+
82
+ type CacheLike = {
83
+ delete(request: string): Promise<boolean>;
84
+ keys(): Promise<readonly Request[]>;
85
+ match(request: string): Promise<Response | undefined>;
86
+ put(request: string, response: Response): Promise<void>;
87
+ };
88
+
89
+ interface IJob {
90
+ readonly expectedBytes: number | undefined;
91
+ readonly reject: (error: unknown) => void;
92
+ readonly resolve: (buffer: ArrayBuffer) => void;
93
+ readonly url: string;
94
+ priority: AssetPriority;
95
+ }
96
+
97
+ function cacheStorage(): CacheStorageLike | undefined {
98
+ return (globalThis as { caches?: CacheStorageLike }).caches;
99
+ }
100
+
101
+ function storageManager():
102
+ | {
103
+ persist?: () => Promise<boolean>;
104
+ persisted?: () => Promise<boolean>;
105
+ }
106
+ | undefined {
107
+ return (
108
+ globalThis as {
109
+ navigator?: {
110
+ storage?: {
111
+ persist?: () => Promise<boolean>;
112
+ persisted?: () => Promise<boolean>;
113
+ };
114
+ };
115
+ }
116
+ ).navigator?.storage;
117
+ }
118
+
119
+ function saveDataEnabled(): boolean {
120
+ return (
121
+ (globalThis as { navigator?: { connection?: { saveData?: boolean } } }).navigator?.connection
122
+ ?.saveData === true
123
+ );
124
+ }
125
+
126
+ function delay(ms: number): Promise<void> {
127
+ return new Promise((resolve) => setTimeout(resolve, ms));
128
+ }
129
+
130
+ /** Cache keys are compared as absolute urls; a `Request.url` always is one. */
131
+ /** The absolute url the Cache API stores `url` under. */
132
+ export function canonicalUrl(url: string): string {
133
+ try {
134
+ const base = (globalThis as { location?: { href?: string } }).location?.href;
135
+ return new URL(url, base ?? "http://localhost/").href;
136
+ } catch {
137
+ return url;
138
+ }
139
+ }
140
+
141
+ function errorMessage(error: unknown): string {
142
+ if (error instanceof Error) return error.message;
143
+ return String(error);
144
+ }
145
+
146
+ /** FNV-1a over the release's own file names and sizes: stable, cheap and not a security claim. */
147
+ export function manifestFingerprint(entries: readonly IAssetCacheEntry[]): string {
148
+ let hash = 0x811c9dc5;
149
+ for (const entry of entries) {
150
+ const text = `${entry.url}:${entry.bytes ?? 0};`;
151
+ for (let index = 0; index < text.length; index += 1) {
152
+ hash ^= text.charCodeAt(index);
153
+ hash = Math.imul(hash, 0x01000193) >>> 0;
154
+ }
155
+ }
156
+ return hash.toString(16).padStart(8, "0");
157
+ }
158
+
159
+ /**
160
+ * The disk and network layer under the asset loader.
161
+ *
162
+ * Content-addressed outputs never go stale, so an entry needs no revalidation. Each game keeps one
163
+ * cache across releases: a new build deletes only the files its manifest no longer lists, so a
164
+ * one-file patch downloads one file. Only a complete body reaches the disk, and a `now` request
165
+ * starts ahead of every fill.
166
+ */
167
+ export function createAssetCache(options: IAssetCacheOptions = {}): IAssetCache {
168
+ const storage = cacheStorage();
169
+ const reason =
170
+ options.enabled === false
171
+ ? "assets.cache is false"
172
+ : storage === undefined
173
+ ? isNative()
174
+ ? "native host reads installed files"
175
+ : "cache API unavailable"
176
+ : undefined;
177
+ const enabled = reason === undefined;
178
+ const backgroundFill = options.backgroundFill !== false;
179
+ const concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY);
180
+ const retryDelays = options.retryDelaysMs ?? DEFAULT_RETRY_DELAYS_MS;
181
+
182
+ let cacheName: string | undefined;
183
+ const gameCacheName =
184
+ options.namespace === undefined || options.namespace === ""
185
+ ? CACHE_NAME
186
+ : `${CACHE_NAME}-${manifestFingerprint([{ url: options.namespace }]).slice(0, 8)}`;
187
+ let entries: readonly IAssetCacheEntry[] = [];
188
+ /** Every manifest output and its compiled size, for the fetch bridge's hit and write checks. */
189
+ const known = new Map<string, number | undefined>();
190
+ let resolveManifest: (() => void) | undefined;
191
+ const manifestReady = new Promise<void>((resolve) => {
192
+ resolveManifest = resolve;
193
+ });
194
+
195
+ let persisted = false;
196
+ let persistAsked = false;
197
+ let hits = 0;
198
+ let misses = 0;
199
+ let bytesOnDisk = 0;
200
+ let measured = false;
201
+ let bytesTotal = 0;
202
+ let filling = false;
203
+ let fillStarted = false;
204
+ let cleared = false;
205
+ let storageFull = false;
206
+ let cacheGeneration = 0;
207
+ let restoreFetch: (() => void) | undefined;
208
+ /** The fetch before the disk-first bridge: the loader's own downloads must not re-enter it. */
209
+ let nativeFetch: typeof fetch = globalThis.fetch.bind(globalThis);
210
+
211
+ /** Every url this session read or wrote. Those are the entries a quota error must not evict. */
212
+ const touched = new Set<string>();
213
+ /** The whole lookup, cache read included, keyed by url so two callers share one download. */
214
+ const requests = new Map<string, { priority: AssetPriority; promise: Promise<ArrayBuffer> }>();
215
+ /** Disk writes a `now` or `soon` caller did not wait for, keyed by url. */
216
+ const writes = new Map<string, Promise<void>>();
217
+ const queues: Record<AssetPriority, IJob[]> = { now: [], soon: [], idle: [] };
218
+ let active = 0;
219
+ let activeNow = 0;
220
+
221
+ const openCache = async (): Promise<CacheLike | undefined> => {
222
+ if (!enabled || cacheName === undefined || storage === undefined) return undefined;
223
+ return storage.open(cacheName);
224
+ };
225
+
226
+ /** Delete the files this release no longer lists and sum the ones it keeps. */
227
+ const pruneAndMeasure = async (cache: CacheLike): Promise<void> => {
228
+ let total = 0;
229
+ for (const request of await cache.keys()) {
230
+ if (!known.has(canonicalUrl(request.url))) {
231
+ await cache.delete(request.url);
232
+ continue;
233
+ }
234
+ const response = await cache.match(request.url);
235
+ const size = Number(response?.headers.get(BYTES_HEADER) ?? "0");
236
+ if (Number.isFinite(size) && size > 0) total += size;
237
+ }
238
+ bytesOnDisk = total;
239
+ measured = true;
240
+ };
241
+
242
+ const askToPersist = async (): Promise<void> => {
243
+ if (persistAsked) return;
244
+ persistAsked = true;
245
+ try {
246
+ persisted = (await storageManager()?.persist?.()) === true;
247
+ } catch {
248
+ persisted = false;
249
+ }
250
+ };
251
+
252
+ /** Read the stored entries' sizes and access stamps, unsorted. */
253
+ const readCandidates = async (
254
+ cache: CacheLike,
255
+ ): Promise<{ access: number; size: number; url: string }[]> => {
256
+ const candidates: { access: number; size: number; url: string }[] = [];
257
+ for (const request of await cache.keys()) {
258
+ const response = await cache.match(request.url);
259
+ candidates.push({
260
+ access: Number(response?.headers.get(ACCESS_HEADER) ?? "0"),
261
+ size: Number(response?.headers.get(BYTES_HEADER) ?? "0"),
262
+ url: request.url,
263
+ });
264
+ }
265
+ return candidates;
266
+ };
267
+
268
+ const isQuotaError = (error: unknown): boolean =>
269
+ error instanceof Error &&
270
+ (error.name === "QuotaExceededError" || /quota/iu.test(error.message));
271
+
272
+ /**
273
+ * Write one complete body. The browser's own quota is the only limit consulted: a refused write
274
+ * gives up the least recently accessed entry this session has not touched, one at a time, and
275
+ * retries, so a write that fits costs no quota query and no index scan.
276
+ */
277
+ const store = async (
278
+ cache: CacheLike,
279
+ url: string,
280
+ buffer: ArrayBuffer,
281
+ generation: number,
282
+ ): Promise<void> => {
283
+ if (generation !== cacheGeneration) return;
284
+ const put = (): Promise<void> =>
285
+ cache.put(
286
+ url,
287
+ new Response(buffer, {
288
+ headers: {
289
+ [ACCESS_HEADER]: String(Date.now()),
290
+ [BYTES_HEADER]: String(buffer.byteLength),
291
+ },
292
+ }),
293
+ );
294
+ try {
295
+ await put();
296
+ if (measured) bytesOnDisk += buffer.byteLength;
297
+ return;
298
+ } catch (error) {
299
+ if (!isQuotaError(error)) return;
300
+ }
301
+ try {
302
+ const candidates = await readCandidates(cache);
303
+ candidates.sort((left, right) => left.access - right.access);
304
+ for (const candidate of candidates) {
305
+ if (touched.has(canonicalUrl(candidate.url))) continue;
306
+ if (!(await cache.delete(candidate.url))) continue;
307
+ bytesOnDisk = Math.max(0, bytesOnDisk - candidate.size);
308
+ try {
309
+ await put();
310
+ if (measured) bytesOnDisk += buffer.byteLength;
311
+ return;
312
+ } catch (error) {
313
+ if (!isQuotaError(error)) return;
314
+ }
315
+ }
316
+ } catch {
317
+ // A storage failure while evicting is the same outcome as nothing left to evict.
318
+ }
319
+ // The bytes are in hand and the game still gets them; only the disk write failed. Stop the
320
+ // fill: every later file would be downloaded again on the next visit.
321
+ storageFull = true;
322
+ };
323
+
324
+ const download = async (
325
+ url: string,
326
+ priority: AssetPriority,
327
+ expectedBytes: number | undefined,
328
+ ): Promise<ArrayBuffer> => {
329
+ let last: unknown;
330
+ for (let attempt = 0; attempt <= retryDelays.length; attempt += 1) {
331
+ try {
332
+ const init = priority === "idle" ? ({ priority: "low" } satisfies RequestInit) : undefined;
333
+ const response = await (init === undefined ? nativeFetch(url) : nativeFetch(url, init));
334
+ if (!response.ok) {
335
+ const status = response.status;
336
+ const error = new Error(`status ${String(status)}`);
337
+ // A 404 or a 403 will answer the same on every attempt. Retrying it only adds the
338
+ // backoff to a startup that could already be trying its next candidate url.
339
+ const retryable = status === 408 || status === 425 || status === 429 || status >= 500;
340
+ if (!retryable) throw Object.assign(error, { retryable: false });
341
+ throw error;
342
+ }
343
+ const buffer = await response.arrayBuffer();
344
+ if (expectedBytes !== undefined && buffer.byteLength !== expectedBytes) {
345
+ throw new Error(
346
+ `incomplete download (${String(buffer.byteLength)} of ${String(expectedBytes)} bytes)`,
347
+ );
348
+ }
349
+ return buffer;
350
+ } catch (error) {
351
+ last = error;
352
+ if ((error as { retryable?: boolean }).retryable === false) break;
353
+ const wait = retryDelays[attempt];
354
+ if (wait === undefined) break;
355
+ await delay(wait);
356
+ }
357
+ }
358
+ throw new Error(errorMessage(last));
359
+ };
360
+
361
+ const load = async (
362
+ url: string,
363
+ request: { readonly priority: AssetPriority },
364
+ expectedBytes: number | undefined,
365
+ ): Promise<ArrayBuffer> => {
366
+ if (!enabled) {
367
+ const response = await nativeFetch(url);
368
+ if (!response.ok) throw new Error(`status ${String(response.status)}`);
369
+ return response.arrayBuffer();
370
+ }
371
+ const generation = cacheGeneration;
372
+ const key = canonicalUrl(url);
373
+ // A write still on its way to disk finishes first, so the read after it is a hit. No await
374
+ // otherwise: a `now` request must reach the queue in the tick it was made.
375
+ const pendingWrite = writes.get(key);
376
+ if (pendingWrite !== undefined) await pendingWrite;
377
+ let cache = expectedBytes === undefined ? undefined : await openCache().catch(() => undefined);
378
+ if (cache !== undefined) {
379
+ try {
380
+ const hit = await cache.match(url);
381
+ if (hit !== undefined) {
382
+ const access = Number(hit.headers.get(ACCESS_HEADER) ?? "0");
383
+ const cached = await hit.arrayBuffer();
384
+ // A truncated entry is not a hit: drop it and download the file again, so one bad write
385
+ // cannot leave a game permanently broken on that file.
386
+ if (expectedBytes === undefined || cached.byteLength === expectedBytes) {
387
+ hits += 1;
388
+ touched.add(canonicalUrl(url));
389
+ // One write per hour at most keeps the eviction order honest without paying for a
390
+ // metadata write on every asset the game reads.
391
+ if (Date.now() - access > ACCESS_REFRESH_MS) {
392
+ void cache
393
+ .put(
394
+ url,
395
+ new Response(cached, {
396
+ headers: {
397
+ [ACCESS_HEADER]: String(Date.now()),
398
+ [BYTES_HEADER]: String(cached.byteLength),
399
+ },
400
+ }),
401
+ )
402
+ .catch(() => undefined);
403
+ }
404
+ return cached;
405
+ }
406
+ console.warn(
407
+ `TN_ASSETS_CACHE_TRUNCATED '${url}': stored ${String(cached.byteLength)} of ${String(expectedBytes)} bytes; fetching again.`,
408
+ );
409
+ bytesOnDisk = Math.max(0, bytesOnDisk - cached.byteLength);
410
+ await cache.delete(url);
411
+ }
412
+ } catch {
413
+ // A storage read that fails is a cache miss, never a failed asset: the network can serve
414
+ // the bytes the player is waiting for.
415
+ cache = undefined;
416
+ }
417
+ }
418
+ misses += 1;
419
+ // Read at enqueue time, not at call time: a `now` caller may have promoted this request while
420
+ // it was still reading the disk.
421
+ const buffer = await enqueue(url, request.priority, expectedBytes);
422
+ if (cache !== undefined) {
423
+ touched.add(key);
424
+ // Never awaited: Firefox resolves `persist()` only after the player answers its prompt.
425
+ void askToPersist();
426
+ const write = store(cache, url, buffer, generation);
427
+ // The fill waits for its own write, so it never holds more downloaded bytes than the disk
428
+ // took. A file the frame waits on goes to the caller first.
429
+ if (request.priority === "idle") {
430
+ await write;
431
+ } else {
432
+ writes.set(key, write);
433
+ void write.then(() => {
434
+ if (writes.get(key) === write) writes.delete(key);
435
+ });
436
+ }
437
+ }
438
+ return buffer;
439
+ };
440
+
441
+ const take = (): IJob | undefined => {
442
+ if (queues.now.length > 0) return queues.now.shift();
443
+ // A `now` starts at once and holds every new `soon` and `idle` start until it settles.
444
+ if (activeNow > 0) return undefined;
445
+ if (queues.soon.length > 0) return queues.soon.shift();
446
+ return queues.idle.shift();
447
+ };
448
+
449
+ const pump = (): void => {
450
+ // A `now` file starts at once even when every lane is busy with the fill. Only `soon` and
451
+ // `idle` respect the concurrency cap, so a large idle download can never sit in front of the
452
+ // file the frame is waiting on.
453
+ while (queues.now.length > 0 || active < concurrency) {
454
+ const job = take();
455
+ if (job === undefined) return;
456
+ active += 1;
457
+ if (job.priority === "now") activeNow += 1;
458
+ void download(job.url, job.priority, job.expectedBytes)
459
+ .then(
460
+ (buffer) => {
461
+ job.resolve(buffer);
462
+ },
463
+ (error: unknown) => {
464
+ job.reject(error);
465
+ },
466
+ )
467
+ .then(() => {
468
+ active -= 1;
469
+ if (job.priority === "now") activeNow -= 1;
470
+ pump();
471
+ });
472
+ }
473
+ };
474
+
475
+ const enqueue = (
476
+ url: string,
477
+ priority: AssetPriority,
478
+ expectedBytes: number | undefined,
479
+ ): Promise<ArrayBuffer> =>
480
+ new Promise((resolve, reject) => {
481
+ queues[priority].push({ expectedBytes, priority, reject, resolve, url });
482
+ pump();
483
+ });
484
+
485
+ const fetchBytes = (
486
+ url: string,
487
+ priority: AssetPriority = "now",
488
+ expectedBytes?: number,
489
+ ): Promise<ArrayBuffer> => {
490
+ const key = canonicalUrl(url);
491
+ const existing = requests.get(key);
492
+ if (existing !== undefined) {
493
+ if (PRIORITY_ORDER[priority] < PRIORITY_ORDER[existing.priority]) {
494
+ existing.priority = priority;
495
+ // A queued request is already in a queue; move it so the new priority is honoured.
496
+ for (const queue of Object.values(queues)) {
497
+ const job = queue.find((candidate) => canonicalUrl(candidate.url) === key);
498
+ if (job === undefined) continue;
499
+ queue.splice(queue.indexOf(job), 1);
500
+ job.priority = priority;
501
+ queues[priority].push(job);
502
+ break;
503
+ }
504
+ }
505
+ // A promoted job must start now if a lane is free; otherwise it waits for the next settle.
506
+ pump();
507
+ return existing.promise;
508
+ }
509
+ const request = { priority } as { priority: AssetPriority; promise: Promise<ArrayBuffer> };
510
+ request.promise = load(url, request, expectedBytes);
511
+ requests.set(key, request);
512
+ const promise = request.promise;
513
+ void promise.then(
514
+ () => requests.delete(key),
515
+ () => requests.delete(key),
516
+ );
517
+ return promise;
518
+ };
519
+
520
+ const prefetch = async (
521
+ targets: readonly IAssetCacheEntry[],
522
+ priority: AssetPriority,
523
+ ): Promise<void> => {
524
+ if (!enabled) return;
525
+ await Promise.allSettled(targets.map((entry) => fetchBytes(entry.url, priority, entry.bytes)));
526
+ };
527
+
528
+ /**
529
+ * Serve a cache hit for any GET the page makes, so a loader core does not wrap — three's
530
+ * `KTX2Loader`, `RGBELoader`, `AudioLoader` — also reads the bytes the fill already stored.
531
+ * Only a manifest output with a recorded size is ever on disk, so every other request goes
532
+ * straight to the original fetch without a storage lookup. Web-only, like the cache itself.
533
+ */
534
+ const installFetchBridge = (name: string): void => {
535
+ if (typeof globalThis.fetch !== "function" || storage === undefined) return;
536
+ const original = globalThis.fetch;
537
+ nativeFetch = original.bind(globalThis);
538
+ const wrapped = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
539
+ const method = init?.method ?? (input instanceof Request ? input.method : "GET");
540
+ const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
541
+ const key = canonicalUrl(url);
542
+ const expected = known.get(key);
543
+ if (method.toUpperCase() !== "GET" || expected === undefined) return original(input, init);
544
+ // A core download for the same url is already in flight: wait for it instead of fetching
545
+ // the same bytes a second time. The loader asking is on the frame's path, so a queued
546
+ // `soon` or `idle` download is raised to `now` rather than left behind the queue.
547
+ if (requests.has(key)) {
548
+ const buffer = await fetchBytes(url, "now", expected);
549
+ return new Response(buffer, {
550
+ headers: { [BYTES_HEADER]: String(buffer.byteLength) },
551
+ });
552
+ }
553
+ // A download that settled before its disk write landed: the read after the write is a hit.
554
+ const pendingWrite = writes.get(key);
555
+ if (pendingWrite !== undefined) await pendingWrite;
556
+ try {
557
+ const cache = await storage.open(name);
558
+ const hit = await cache.match(url);
559
+ if (hit !== undefined) {
560
+ const access = Number(hit.headers.get(ACCESS_HEADER) ?? "0");
561
+ const cached = await hit.arrayBuffer();
562
+ if (cached.byteLength === expected) {
563
+ touched.add(key);
564
+ if (Date.now() - access > ACCESS_REFRESH_MS) {
565
+ void cache
566
+ .put(
567
+ url,
568
+ new Response(cached, {
569
+ headers: {
570
+ [ACCESS_HEADER]: String(Date.now()),
571
+ [BYTES_HEADER]: String(cached.byteLength),
572
+ },
573
+ }),
574
+ )
575
+ .catch(() => undefined);
576
+ }
577
+ return new Response(cached, {
578
+ headers: {
579
+ [ACCESS_HEADER]: String(Date.now()),
580
+ [BYTES_HEADER]: String(cached.byteLength),
581
+ },
582
+ });
583
+ }
584
+ console.warn(
585
+ `TN_ASSETS_CACHE_TRUNCATED '${url}': stored ${String(cached.byteLength)} of ${String(expected)} bytes; fetching again.`,
586
+ );
587
+ await cache.delete(url).catch(() => undefined);
588
+ }
589
+ } catch {
590
+ // A storage failure falls through to the network; the game still loads.
591
+ }
592
+ const response = await original(input, init);
593
+ // The bridge normally only reads. When a loader core does not wrap fetches a manifest
594
+ // output the fill has not reached yet, keep it: otherwise the first visit downloads that
595
+ // file twice, once here and once in the fill.
596
+ if (response.ok && !requests.has(key)) {
597
+ try {
598
+ const cache = await storage.open(name);
599
+ const copy = response.clone();
600
+ void copy
601
+ .arrayBuffer()
602
+ .then((buffer) => {
603
+ if (buffer.byteLength !== expected) return undefined;
604
+ // This session read it, so a later quota eviction must not take it.
605
+ touched.add(key);
606
+ return store(cache, url, buffer, cacheGeneration);
607
+ })
608
+ .catch(() => undefined);
609
+ } catch {
610
+ // The clone is an optimisation; the caller's response is already on its way.
611
+ }
612
+ }
613
+ return response;
614
+ };
615
+ globalThis.fetch = wrapped as typeof fetch;
616
+ restoreFetch = () => {
617
+ if (globalThis.fetch === wrapped) globalThis.fetch = original;
618
+ };
619
+ };
620
+
621
+ const runFill = async (): Promise<void> => {
622
+ await manifestReady;
623
+ if (!enabled || !backgroundFill || entries.length === 0) return;
624
+ filling = true;
625
+ try {
626
+ const chunk = Math.max(1, concurrency);
627
+ for (let index = 0; index < entries.length; index += chunk) {
628
+ // Checked between chunks, not once: a player who turns on data saving or frees the cache
629
+ // mid-fill stops it at the next file boundary instead of paying for the rest of the
630
+ // release.
631
+ if (cleared || storageFull || saveDataEnabled()) break;
632
+ await prefetch(entries.slice(index, index + chunk), "idle");
633
+ }
634
+ } finally {
635
+ filling = false;
636
+ }
637
+ };
638
+
639
+ return {
640
+ get enabled() {
641
+ return enabled;
642
+ },
643
+ get report(): IAssetCacheReport {
644
+ return {
645
+ enabled,
646
+ persisted,
647
+ hits,
648
+ misses,
649
+ bytesOnDisk,
650
+ bytesTotal,
651
+ filling,
652
+ backgroundFill: enabled && backgroundFill && !saveDataEnabled(),
653
+ ...(reason === undefined ? {} : { reason }),
654
+ };
655
+ },
656
+ fetchBytes,
657
+ promote: (url, priority) => {
658
+ if (requests.has(canonicalUrl(url))) void fetchBytes(url, priority).catch(() => undefined);
659
+ },
660
+ prefetch: async (targets) => prefetch(targets, "soon"),
661
+ setManifest: (manifestEntries) => {
662
+ if (cacheName !== undefined) return;
663
+ // Nothing content-addressed to store: a project with no manifest keeps the web path it had.
664
+ if (manifestEntries.length === 0) {
665
+ resolveManifest?.();
666
+ return;
667
+ }
668
+ entries = manifestEntries;
669
+ known.clear();
670
+ for (const entry of manifestEntries) known.set(canonicalUrl(entry.url), entry.bytes);
671
+ bytesTotal = manifestEntries.reduce((sum, entry) => sum + (entry.bytes ?? 0), 0);
672
+ void storageManager()
673
+ ?.persisted?.()
674
+ .then((granted) => {
675
+ persisted = granted === true;
676
+ })
677
+ .catch(() => undefined);
678
+ if (!enabled) {
679
+ resolveManifest?.();
680
+ return;
681
+ }
682
+ cacheName = gameCacheName;
683
+ installFetchBridge(gameCacheName);
684
+ // Without the prune every build adds its changed files to the player's disk and nothing
685
+ // ever removes the old ones.
686
+ void (async () => {
687
+ try {
688
+ const cache = await openCache();
689
+ if (cache !== undefined) await pruneAndMeasure(cache);
690
+ } catch {
691
+ // A storage failure must not stop a game from starting.
692
+ }
693
+ resolveManifest?.();
694
+ })();
695
+ },
696
+ startFill: () => {
697
+ if (fillStarted || cleared) return Promise.resolve();
698
+ fillStarted = true;
699
+ return runFill().catch(() => undefined);
700
+ },
701
+ clear: async () => {
702
+ cleared = true;
703
+ fillStarted = true;
704
+ cacheGeneration += 1;
705
+ storageFull = false;
706
+ if (cacheName === undefined || storage === undefined) {
707
+ bytesOnDisk = 0;
708
+ return;
709
+ }
710
+ await storage.delete(cacheName);
711
+ bytesOnDisk = 0;
712
+ touched.clear();
713
+ },
714
+ dispose: () => {
715
+ restoreFetch?.();
716
+ restoreFetch = undefined;
717
+ },
718
+ };
719
+ }