@threenative/core 0.3.10 → 0.3.12

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 (158) hide show
  1. package/capabilities.json +1096 -26
  2. package/dist/camera-shake-CZKOfGn4.d.ts +46 -0
  3. package/dist/{canvas-layer-vCtanIeB.d.ts → canvas-layer-CWuFRT7G.d.ts} +1 -1
  4. package/dist/chunk-2Z44XSI2.js +35 -0
  5. package/dist/chunk-5O73CDMR.js +1849 -0
  6. package/dist/chunk-6KLNISRJ.js +153 -0
  7. package/dist/chunk-7UUT3TY5.js +133 -0
  8. package/dist/chunk-CFGTPFUH.js +231 -0
  9. package/dist/chunk-DBELTTTM.js +615 -0
  10. package/dist/chunk-GMHATRPW.js +7701 -0
  11. package/dist/chunk-GXY7B3JG.js +46 -0
  12. package/dist/chunk-KIRUKTBQ.js +187 -0
  13. package/dist/chunk-N5LRP4BR.js +220 -0
  14. package/dist/chunk-OKXUCASC.js +2238 -0
  15. package/dist/chunk-QWJEMUUT.js +94 -0
  16. package/dist/chunk-VAZM36TV.js +497 -0
  17. package/dist/{game-DzMcitDO.d.ts → game-D7pAzZUY.d.ts} +15 -3
  18. package/dist/hot.d.ts +3 -3
  19. package/dist/hot.js +2 -46
  20. package/dist/index.d.ts +329 -302
  21. package/dist/index.js +10565 -22533
  22. package/dist/{model-lod-CTpZ6imz.d.ts → model-lod-B6BMqS1r.d.ts} +33 -3
  23. package/dist/playtest.d.ts +3 -3
  24. package/dist/playtest.js +24 -75
  25. package/dist/react-css.js +1 -215
  26. package/dist/react.d.ts +2 -2
  27. package/dist/{renderer-rZm0hVqq.d.ts → renderer-DvFVoAgj.d.ts} +13 -4
  28. package/dist/spells/index.d.ts +643 -0
  29. package/dist/spells/index.js +1558 -0
  30. package/dist/spells/ultra/index.d.ts +1600 -0
  31. package/dist/spells/ultra/index.js +6804 -0
  32. package/dist/terrain-jobs-worker.js +1 -123
  33. package/dist/two-sided-foliage-W523J3UM.js +1 -0
  34. package/dist/ui-layer.js +5 -384
  35. package/dist/worker.js +4 -41
  36. package/dist/world.d.ts +725 -259
  37. package/dist/world.js +16714 -18284
  38. package/mcp/animation-server.mjs +1 -1
  39. package/mcp/animation.mjs +2 -3
  40. package/mcp/engine-server.mjs +142 -47
  41. package/mcp/servers.mjs +9 -2
  42. package/mcp/terrain.mjs +8 -0
  43. package/package.json +14 -6
  44. package/patches/three@0.187.0-prd269-upgrade.patch +2102 -0
  45. package/patches/three@0.187.0.patch +2004 -407
  46. package/src/assets.ts +9 -2
  47. package/src/card-lod.ts +152 -0
  48. package/src/compressed-texture-preparation.ts +1008 -0
  49. package/src/frame-budget.ts +31 -20
  50. package/src/game-dev-tools.ts +93 -0
  51. package/src/game-frame-loop.ts +995 -0
  52. package/src/game-renderer-metrics.ts +77 -0
  53. package/src/game-startup.ts +1001 -0
  54. package/src/game-validate.ts +70 -0
  55. package/src/game.ts +253 -1935
  56. package/src/index.ts +27 -2
  57. package/src/launch-diagnostics.ts +22 -12
  58. package/src/look/ao-admission.ts +24 -0
  59. package/src/look/filmic-tone-mapping.ts +15 -13
  60. package/src/look/look-diagnostics.ts +3 -3
  61. package/src/look/quality.ts +10 -5
  62. package/src/look/world-environment.ts +76 -9
  63. package/src/loop.ts +29 -0
  64. package/src/model-lod.ts +42 -3
  65. package/src/particle-kinds.ts +515 -0
  66. package/src/picking.ts +17 -3
  67. package/src/playtest.ts +27 -1
  68. package/src/projection-apply.ts +4 -1
  69. package/src/projection-plan.ts +9 -6
  70. package/src/render/mesh-pool.ts +1 -1
  71. package/src/render/resolution-subrect.ts +2 -0
  72. package/src/render/rough-diffuse.ts +46 -12
  73. package/src/render/soft-shadow.ts +27 -12
  74. package/src/render/virtual-shadow-adaptive.ts +55 -0
  75. package/src/render/virtual-shadow-casters.ts +175 -0
  76. package/src/render/virtual-shadow-layers.ts +76 -0
  77. package/src/render/virtual-shadow-level.ts +224 -0
  78. package/src/render/virtual-shadow-markers.ts +193 -0
  79. package/src/render/virtual-shadow-options.ts +370 -0
  80. package/src/render/virtual-shadow-pages.ts +5 -0
  81. package/src/render/virtual-shadow.ts +213 -992
  82. package/src/render/world-impostor-surface.ts +293 -34
  83. package/src/render-camera-cull.ts +32 -1
  84. package/src/render-pass-budget.ts +34 -7
  85. package/src/renderProjection.ts +22 -0
  86. package/src/renderer.ts +92 -37
  87. package/src/snow-field.ts +1 -1
  88. package/src/spells/cast-pool.ts +361 -0
  89. package/src/spells/index.ts +177 -0
  90. package/src/spells/mechanisms.ts +295 -0
  91. package/src/spells/reaction-field.ts +415 -0
  92. package/src/spells/spell-lights.ts +139 -0
  93. package/src/spells/spell-world.ts +187 -0
  94. package/src/spells/spell.ts +397 -0
  95. package/src/spells/spells.ts +283 -0
  96. package/src/spells/ultra/engine/camera.ts +184 -0
  97. package/src/spells/ultra/engine/quality.ts +96 -0
  98. package/src/spells/ultra/index.ts +52 -0
  99. package/src/spells/ultra/main.ts +305 -0
  100. package/src/spells/ultra/scene/arenaMaterial.ts +325 -0
  101. package/src/spells/ultra/spells/cast.ts +233 -0
  102. package/src/spells/ultra/spells/fire.ts +1267 -0
  103. package/src/spells/ultra/vfx/FluidVolume.ts +816 -0
  104. package/src/spells/ultra/vfx/FluidVolume.tsl.ts +855 -0
  105. package/src/spells/ultra/vfx/FxTarget.ts +61 -0
  106. package/src/spells/ultra/vfx/GroundField.ts +1399 -0
  107. package/src/spells/ultra/vfx/Particles.ts +1475 -0
  108. package/src/spells/ultra/vfx/Ribbons.ts +645 -0
  109. package/src/spells/ultra/vfx/Shockwaves.ts +286 -0
  110. package/src/spells/ultra/vfx/Volumes.ts +489 -0
  111. package/src/spells/ultra/vfx/common.ts +1195 -0
  112. package/src/spells/ultra/vfx/noise.ts +441 -0
  113. package/src/startup-readiness.ts +128 -34
  114. package/src/version.ts +1 -1
  115. package/src/warmup.ts +56 -8
  116. package/src/water-surface.ts +9 -3
  117. package/src/world-bundle-safety.ts +401 -0
  118. package/src/world-cell-batches.ts +1216 -0
  119. package/src/world-cell-chunks.ts +1132 -0
  120. package/src/world-cell-data.ts +995 -0
  121. package/src/world-cell-impostors.ts +1449 -0
  122. package/src/world-cell-lod-bias.ts +151 -0
  123. package/src/world-cell-models.ts +1074 -0
  124. package/src/world-cell-options.ts +189 -0
  125. package/src/world-cell-placements.ts +694 -0
  126. package/src/world-cell-prewarm.ts +557 -0
  127. package/src/world-cell-readiness.ts +357 -0
  128. package/src/world-cell-render-bundles.ts +459 -0
  129. package/src/world-cell-render-gpu-dress.ts +714 -0
  130. package/src/world-cell-render-main-cull.ts +484 -0
  131. package/src/world-cell-render-shadow-claims.ts +198 -0
  132. package/src/world-cell-render-util.ts +246 -0
  133. package/src/world-cell-render.ts +1493 -0
  134. package/src/world-cell-residency.ts +745 -0
  135. package/src/world-cells.ts +1318 -10418
  136. package/src/world-chunk-shadow.ts +308 -0
  137. package/src/world-collar.ts +315 -0
  138. package/src/world-gpu-flags.ts +163 -0
  139. package/src/world-gpu-readback.ts +881 -0
  140. package/src/world-gpu-reference.ts +510 -0
  141. package/src/world-gpu-scene.ts +214 -2264
  142. package/src/world-gpu-shadow.ts +190 -0
  143. package/src/world-gpu-types.ts +381 -0
  144. package/src/world-gpu-validation.ts +518 -0
  145. package/src/world-heightfield.ts +802 -0
  146. package/src/world-load-limiter.ts +106 -0
  147. package/src/world-noise.ts +241 -0
  148. package/src/world-package.ts +42 -0
  149. package/src/world-region.ts +1 -1
  150. package/src/world-terrain-splat.ts +365 -149
  151. package/src/world-tile-budget.ts +256 -0
  152. package/src/world-tile-geometry.ts +469 -0
  153. package/src/world-tile-lod.ts +408 -0
  154. package/src/world-tile-observation.ts +566 -0
  155. package/src/world-tile-stitch.ts +166 -0
  156. package/src/world-tiles.ts +170 -1745
  157. package/src/world-water-bodies.ts +359 -0
  158. package/src/world.ts +35 -741
@@ -0,0 +1,1008 @@
1
+ import {
2
+ ColorManagement,
3
+ type CompressedArrayTexture,
4
+ type CompressedTexture,
5
+ ExternalTexture,
6
+ R11_EAC_Format,
7
+ RED_GREEN_RGTC2_Format,
8
+ RED_RGTC1_Format,
9
+ RG11_EAC_Format,
10
+ RGBA_ASTC_4x4_Format,
11
+ RGBA_ASTC_5x4_Format,
12
+ RGBA_ASTC_5x5_Format,
13
+ RGBA_ASTC_6x5_Format,
14
+ RGBA_ASTC_6x6_Format,
15
+ RGBA_ASTC_8x5_Format,
16
+ RGBA_ASTC_8x6_Format,
17
+ RGBA_ASTC_8x8_Format,
18
+ RGBA_ASTC_10x5_Format,
19
+ RGBA_ASTC_10x6_Format,
20
+ RGBA_ASTC_10x8_Format,
21
+ RGBA_ASTC_10x10_Format,
22
+ RGBA_ASTC_12x10_Format,
23
+ RGBA_ASTC_12x12_Format,
24
+ RGBA_BPTC_Format,
25
+ RGBA_ETC2_EAC_Format,
26
+ RGBA_S3TC_DXT1_Format,
27
+ RGBA_S3TC_DXT3_Format,
28
+ RGBA_S3TC_DXT5_Format,
29
+ RGB_BPTC_SIGNED_Format,
30
+ RGB_BPTC_UNSIGNED_Format,
31
+ RGB_ETC1_Format,
32
+ RGB_ETC2_Format,
33
+ RGB_S3TC_DXT1_Format,
34
+ SIGNED_R11_EAC_Format,
35
+ SIGNED_RED_GREEN_RGTC2_Format,
36
+ SIGNED_RED_RGTC1_Format,
37
+ SIGNED_RG11_EAC_Format,
38
+ SRGBTransfer,
39
+ Source,
40
+ type Texture,
41
+ } from "three";
42
+
43
+ /**
44
+ * One compressed GPU format and the block geometry a bounded write must respect. The table is
45
+ * pinned to the installed Three release (see `patches/three@0.187.0.patch`); the GPU format strings are
46
+ * the WebGPU enum values Three maps its public texture constants to. `feature` is the WebGPU
47
+ * `device.features` name the format needs, checked before any allocation.
48
+ */
49
+ export interface ICompressedFormatEntry {
50
+ readonly gpuFormat: string;
51
+ readonly feature: string;
52
+ readonly blockWidth: number;
53
+ readonly blockHeight: number;
54
+ readonly blockBytes: number;
55
+ }
56
+
57
+ type IFormatRow = Omit<ICompressedFormatEntry, "gpuFormat"> & {
58
+ readonly base: string;
59
+ readonly srgb?: true;
60
+ };
61
+
62
+ const BC = "texture-compression-bc";
63
+ const ETC2 = "texture-compression-etc2";
64
+ const ASTC = "texture-compression-astc";
65
+
66
+ // Public Three constants -> WebGPU compressed format, required device feature, block size and
67
+ // bytes per block. Kept local so the framework never imports Three's internal texture utils.
68
+ const FORMAT_ROWS: ReadonlyArray<readonly [number, IFormatRow]> = [
69
+ [
70
+ RGB_S3TC_DXT1_Format,
71
+ {
72
+ base: "bc1-rgba-unorm",
73
+ srgb: true,
74
+ feature: BC,
75
+ blockWidth: 4,
76
+ blockHeight: 4,
77
+ blockBytes: 8,
78
+ },
79
+ ],
80
+ [
81
+ RGBA_S3TC_DXT1_Format,
82
+ {
83
+ base: "bc1-rgba-unorm",
84
+ srgb: true,
85
+ feature: BC,
86
+ blockWidth: 4,
87
+ blockHeight: 4,
88
+ blockBytes: 8,
89
+ },
90
+ ],
91
+ [
92
+ RGBA_S3TC_DXT3_Format,
93
+ {
94
+ base: "bc2-rgba-unorm",
95
+ srgb: true,
96
+ feature: BC,
97
+ blockWidth: 4,
98
+ blockHeight: 4,
99
+ blockBytes: 16,
100
+ },
101
+ ],
102
+ [
103
+ RGBA_S3TC_DXT5_Format,
104
+ {
105
+ base: "bc3-rgba-unorm",
106
+ srgb: true,
107
+ feature: BC,
108
+ blockWidth: 4,
109
+ blockHeight: 4,
110
+ blockBytes: 16,
111
+ },
112
+ ],
113
+ [
114
+ RED_RGTC1_Format,
115
+ { base: "bc4-r-unorm", feature: BC, blockWidth: 4, blockHeight: 4, blockBytes: 8 },
116
+ ],
117
+ [
118
+ SIGNED_RED_RGTC1_Format,
119
+ { base: "bc4-r-snorm", feature: BC, blockWidth: 4, blockHeight: 4, blockBytes: 8 },
120
+ ],
121
+ [
122
+ RED_GREEN_RGTC2_Format,
123
+ { base: "bc5-rg-unorm", feature: BC, blockWidth: 4, blockHeight: 4, blockBytes: 16 },
124
+ ],
125
+ [
126
+ SIGNED_RED_GREEN_RGTC2_Format,
127
+ { base: "bc5-rg-snorm", feature: BC, blockWidth: 4, blockHeight: 4, blockBytes: 16 },
128
+ ],
129
+ [
130
+ RGBA_BPTC_Format,
131
+ {
132
+ base: "bc7-rgba-unorm",
133
+ srgb: true,
134
+ feature: BC,
135
+ blockWidth: 4,
136
+ blockHeight: 4,
137
+ blockBytes: 16,
138
+ },
139
+ ],
140
+ [
141
+ RGB_BPTC_SIGNED_Format,
142
+ { base: "bc6h-rgb-float", feature: BC, blockWidth: 4, blockHeight: 4, blockBytes: 16 },
143
+ ],
144
+ [
145
+ RGB_BPTC_UNSIGNED_Format,
146
+ { base: "bc6h-rgb-ufloat", feature: BC, blockWidth: 4, blockHeight: 4, blockBytes: 16 },
147
+ ],
148
+ [
149
+ RGB_ETC2_Format,
150
+ {
151
+ base: "etc2-rgb8unorm",
152
+ srgb: true,
153
+ feature: ETC2,
154
+ blockWidth: 4,
155
+ blockHeight: 4,
156
+ blockBytes: 8,
157
+ },
158
+ ],
159
+ [
160
+ RGB_ETC1_Format,
161
+ {
162
+ base: "etc2-rgb8unorm",
163
+ srgb: true,
164
+ feature: ETC2,
165
+ blockWidth: 4,
166
+ blockHeight: 4,
167
+ blockBytes: 8,
168
+ },
169
+ ],
170
+ [
171
+ RGBA_ETC2_EAC_Format,
172
+ {
173
+ base: "etc2-rgba8unorm",
174
+ srgb: true,
175
+ feature: ETC2,
176
+ blockWidth: 4,
177
+ blockHeight: 4,
178
+ blockBytes: 16,
179
+ },
180
+ ],
181
+ [
182
+ R11_EAC_Format,
183
+ { base: "eac-r11unorm", feature: ETC2, blockWidth: 4, blockHeight: 4, blockBytes: 8 },
184
+ ],
185
+ [
186
+ SIGNED_R11_EAC_Format,
187
+ { base: "eac-r11snorm", feature: ETC2, blockWidth: 4, blockHeight: 4, blockBytes: 8 },
188
+ ],
189
+ [
190
+ RG11_EAC_Format,
191
+ { base: "eac-rg11unorm", feature: ETC2, blockWidth: 4, blockHeight: 4, blockBytes: 16 },
192
+ ],
193
+ [
194
+ SIGNED_RG11_EAC_Format,
195
+ { base: "eac-rg11snorm", feature: ETC2, blockWidth: 4, blockHeight: 4, blockBytes: 16 },
196
+ ],
197
+ [
198
+ RGBA_ASTC_4x4_Format,
199
+ {
200
+ base: "astc-4x4-unorm",
201
+ srgb: true,
202
+ feature: ASTC,
203
+ blockWidth: 4,
204
+ blockHeight: 4,
205
+ blockBytes: 16,
206
+ },
207
+ ],
208
+ [
209
+ RGBA_ASTC_5x4_Format,
210
+ {
211
+ base: "astc-5x4-unorm",
212
+ srgb: true,
213
+ feature: ASTC,
214
+ blockWidth: 5,
215
+ blockHeight: 4,
216
+ blockBytes: 16,
217
+ },
218
+ ],
219
+ [
220
+ RGBA_ASTC_5x5_Format,
221
+ {
222
+ base: "astc-5x5-unorm",
223
+ srgb: true,
224
+ feature: ASTC,
225
+ blockWidth: 5,
226
+ blockHeight: 5,
227
+ blockBytes: 16,
228
+ },
229
+ ],
230
+ [
231
+ RGBA_ASTC_6x5_Format,
232
+ {
233
+ base: "astc-6x5-unorm",
234
+ srgb: true,
235
+ feature: ASTC,
236
+ blockWidth: 6,
237
+ blockHeight: 5,
238
+ blockBytes: 16,
239
+ },
240
+ ],
241
+ [
242
+ RGBA_ASTC_6x6_Format,
243
+ {
244
+ base: "astc-6x6-unorm",
245
+ srgb: true,
246
+ feature: ASTC,
247
+ blockWidth: 6,
248
+ blockHeight: 6,
249
+ blockBytes: 16,
250
+ },
251
+ ],
252
+ [
253
+ RGBA_ASTC_8x5_Format,
254
+ {
255
+ base: "astc-8x5-unorm",
256
+ srgb: true,
257
+ feature: ASTC,
258
+ blockWidth: 8,
259
+ blockHeight: 5,
260
+ blockBytes: 16,
261
+ },
262
+ ],
263
+ [
264
+ RGBA_ASTC_8x6_Format,
265
+ {
266
+ base: "astc-8x6-unorm",
267
+ srgb: true,
268
+ feature: ASTC,
269
+ blockWidth: 8,
270
+ blockHeight: 6,
271
+ blockBytes: 16,
272
+ },
273
+ ],
274
+ [
275
+ RGBA_ASTC_8x8_Format,
276
+ {
277
+ base: "astc-8x8-unorm",
278
+ srgb: true,
279
+ feature: ASTC,
280
+ blockWidth: 8,
281
+ blockHeight: 8,
282
+ blockBytes: 16,
283
+ },
284
+ ],
285
+ [
286
+ RGBA_ASTC_10x5_Format,
287
+ {
288
+ base: "astc-10x5-unorm",
289
+ srgb: true,
290
+ feature: ASTC,
291
+ blockWidth: 10,
292
+ blockHeight: 5,
293
+ blockBytes: 16,
294
+ },
295
+ ],
296
+ [
297
+ RGBA_ASTC_10x6_Format,
298
+ {
299
+ base: "astc-10x6-unorm",
300
+ srgb: true,
301
+ feature: ASTC,
302
+ blockWidth: 10,
303
+ blockHeight: 6,
304
+ blockBytes: 16,
305
+ },
306
+ ],
307
+ [
308
+ RGBA_ASTC_10x8_Format,
309
+ {
310
+ base: "astc-10x8-unorm",
311
+ srgb: true,
312
+ feature: ASTC,
313
+ blockWidth: 10,
314
+ blockHeight: 8,
315
+ blockBytes: 16,
316
+ },
317
+ ],
318
+ [
319
+ RGBA_ASTC_10x10_Format,
320
+ {
321
+ base: "astc-10x10-unorm",
322
+ srgb: true,
323
+ feature: ASTC,
324
+ blockWidth: 10,
325
+ blockHeight: 10,
326
+ blockBytes: 16,
327
+ },
328
+ ],
329
+ [
330
+ RGBA_ASTC_12x10_Format,
331
+ {
332
+ base: "astc-12x10-unorm",
333
+ srgb: true,
334
+ feature: ASTC,
335
+ blockWidth: 12,
336
+ blockHeight: 10,
337
+ blockBytes: 16,
338
+ },
339
+ ],
340
+ [
341
+ RGBA_ASTC_12x12_Format,
342
+ {
343
+ base: "astc-12x12-unorm",
344
+ srgb: true,
345
+ feature: ASTC,
346
+ blockWidth: 12,
347
+ blockHeight: 12,
348
+ blockBytes: 16,
349
+ },
350
+ ],
351
+ ];
352
+
353
+ const FORMATS = new Map<number, IFormatRow>(FORMAT_ROWS);
354
+
355
+ /**
356
+ * Resolves the GPU format for a compressed texture, or `undefined` when it is unsupported. The
357
+ * sRGB suffix follows the texture's color-space transfer, so any transfer that maps to sRGB is
358
+ * treated as sRGB rather than only the literal `SRGBColorSpace` string.
359
+ */
360
+ export function compressedFormatFor(texture: Texture): ICompressedFormatEntry | undefined {
361
+ const row = FORMATS.get(texture.format);
362
+ if (row === undefined) return undefined;
363
+ const srgb =
364
+ row.srgb === true && ColorManagement.getTransfer(texture.colorSpace) === SRGBTransfer;
365
+ return {
366
+ gpuFormat: srgb ? `${row.base}-srgb` : row.base,
367
+ feature: row.feature,
368
+ blockWidth: row.blockWidth,
369
+ blockHeight: row.blockHeight,
370
+ blockBytes: row.blockBytes,
371
+ };
372
+ }
373
+
374
+ type CompressedLike = Texture &
375
+ Pick<CompressedTexture, "mipmaps"> & {
376
+ isCompressedTexture?: boolean;
377
+ isCompressedArrayTexture?: boolean;
378
+ };
379
+
380
+ /** One bounded GPU write: at most `maxBytesPerWrite` payload bytes, block-aligned. */
381
+ export interface ICompressedUploadTile {
382
+ readonly mipLevel: number;
383
+ readonly origin: { readonly x: number; readonly y: number; readonly z: number };
384
+ readonly data: Uint8Array;
385
+ readonly layout: {
386
+ readonly offset: number;
387
+ readonly bytesPerRow: number;
388
+ readonly rowsPerImage: number;
389
+ };
390
+ readonly extent: {
391
+ readonly width: number;
392
+ readonly height: number;
393
+ readonly depthOrArrayLayers: number;
394
+ };
395
+ }
396
+
397
+ export interface ICompressedUploadPlan {
398
+ readonly tiles: ReadonlyArray<ICompressedUploadTile>;
399
+ readonly totalBytes: number;
400
+ readonly layers: number;
401
+ readonly width: number;
402
+ readonly height: number;
403
+ }
404
+
405
+ function compressedLayers(source: CompressedLike): number {
406
+ const depth = (source.image as { depth?: number } | null)?.depth;
407
+ if (!source.isCompressedArrayTexture) {
408
+ // A 2D texture has one layer. Reject any other declared depth instead of dropping layers.
409
+ if (depth !== undefined && depth !== 1) {
410
+ if (depth > 1)
411
+ throw new Error(
412
+ "Compressed 2D texture cannot carry image depth above 1. Use CompressedArrayTexture.",
413
+ );
414
+ throw new Error("Invalid compressed 2D texture depth. Only undefined or 1 is valid.");
415
+ }
416
+ return 1;
417
+ }
418
+ if (!Number.isSafeInteger(depth) || (depth ?? 0) <= 0)
419
+ throw new Error("Invalid compressed texture layer count.");
420
+ return depth as number;
421
+ }
422
+
423
+ /**
424
+ * Validates a compressed source and plans whole-texture coverage as block-aligned writes that
425
+ * never exceed `maxBytesPerWrite` and never exceed one mip tail or one array layer per write.
426
+ * Fails closed on a block budget smaller than one block, an invalid dimension, a base mip that
427
+ * differs from the image, or data too short for the declared layers. Each mip must match the
428
+ * halved base size, and the chain cannot be longer than the base allows. Called before any GPU
429
+ * allocation.
430
+ */
431
+ export function planCompressedUpload(
432
+ source: CompressedLike,
433
+ block: ICompressedFormatEntry,
434
+ maxBytesPerWrite: number,
435
+ ): ICompressedUploadPlan {
436
+ const mipmaps = source.mipmaps;
437
+ if (!Number.isSafeInteger(maxBytesPerWrite) || maxBytesPerWrite < block.blockBytes)
438
+ throw new Error("Compressed texture block budget is unsupported.");
439
+ if (!Array.isArray(mipmaps) || mipmaps.length === 0)
440
+ throw new Error("Bounded texture preparation requires ready compressed mip data.");
441
+ const image = source.image as { width?: number; height?: number } | null;
442
+ const width = image?.width;
443
+ const height = image?.height;
444
+ if (
445
+ !Number.isSafeInteger(width) ||
446
+ !Number.isSafeInteger(height) ||
447
+ (width ?? 0) <= 0 ||
448
+ (height ?? 0) <= 0
449
+ )
450
+ throw new Error("Invalid compressed texture dimensions.");
451
+ if (mipmaps[0]?.width !== width || mipmaps[0]?.height !== height)
452
+ throw new Error("Invalid compressed texture dimensions.");
453
+ const baseWidth = width as number;
454
+ const baseHeight = height as number;
455
+ const maxLevels = Math.floor(Math.log2(Math.max(baseWidth, baseHeight))) + 1;
456
+ if (mipmaps.length > maxLevels) throw new Error("Invalid compressed texture mip chain.");
457
+ const layers = compressedLayers(source);
458
+ const tiles: ICompressedUploadTile[] = [];
459
+ let totalBytes = 0;
460
+ for (let mipLevel = 0; mipLevel < mipmaps.length; mipLevel++) {
461
+ const mip = mipmaps[mipLevel];
462
+ if (mip === undefined) throw new Error("Compressed texture mip map is missing.");
463
+ const expectedWidth = Math.max(1, Math.floor(baseWidth / 2 ** mipLevel));
464
+ const expectedHeight = Math.max(1, Math.floor(baseHeight / 2 ** mipLevel));
465
+ if (mip.width !== expectedWidth || mip.height !== expectedHeight)
466
+ throw new Error("Invalid compressed texture dimensions.");
467
+ const columns = Math.ceil(mip.width / block.blockWidth);
468
+ const rows = Math.ceil(mip.height / block.blockHeight);
469
+ const stride = columns * block.blockBytes;
470
+ const imageBytes = stride * rows;
471
+ if (!Number.isSafeInteger(imageBytes))
472
+ throw new Error("Invalid compressed texture layer data.");
473
+ const bytes = new Uint8Array(mip.data.buffer, mip.data.byteOffset, mip.data.byteLength);
474
+ const tileColumns = Math.min(columns, Math.floor(maxBytesPerWrite / block.blockBytes));
475
+ const tileRows =
476
+ stride <= maxBytesPerWrite ? Math.max(1, Math.floor(maxBytesPerWrite / stride)) : 1;
477
+ for (let layer = 0; layer < layers; layer++) {
478
+ if ((layer + 1) * imageBytes > bytes.byteLength)
479
+ throw new Error("Invalid compressed texture layer data.");
480
+ for (let y = 0; y < rows; y += tileRows) {
481
+ for (let x = 0; x < columns; x += tileColumns) {
482
+ const tileWidth = Math.min(tileColumns, columns - x);
483
+ const tileHeight = Math.min(tileRows, rows - y);
484
+ const offset = layer * imageBytes + y * stride + x * block.blockBytes;
485
+ const length = (tileHeight - 1) * stride + tileWidth * block.blockBytes;
486
+ tiles.push({
487
+ mipLevel,
488
+ origin: { x: x * block.blockWidth, y: y * block.blockHeight, z: layer },
489
+ data: bytes.subarray(offset, offset + length),
490
+ layout: { offset: 0, bytesPerRow: stride, rowsPerImage: rows },
491
+ extent: {
492
+ width: tileWidth * block.blockWidth,
493
+ height: tileHeight * block.blockHeight,
494
+ depthOrArrayLayers: 1,
495
+ },
496
+ });
497
+ totalBytes += length;
498
+ }
499
+ }
500
+ }
501
+ }
502
+ return { tiles, totalBytes, layers, width: width as number, height: height as number };
503
+ }
504
+
505
+ /** The public slice of a WebGPU device this lane needs; the rest of `GPUDevice` is unused. */
506
+ export interface ICompressedUploadDevice {
507
+ readonly queue: {
508
+ writeTexture(
509
+ destination: {
510
+ readonly texture: unknown;
511
+ readonly mipLevel: number;
512
+ readonly origin: { readonly x: number; readonly y: number; readonly z: number };
513
+ },
514
+ data: Uint8Array,
515
+ layout: ICompressedUploadTile["layout"],
516
+ extent: ICompressedUploadTile["extent"],
517
+ ): void;
518
+ };
519
+ readonly features?: { has(name: string): boolean };
520
+ createTexture(descriptor: {
521
+ readonly size: {
522
+ readonly width: number;
523
+ readonly height: number;
524
+ readonly depthOrArrayLayers: number;
525
+ };
526
+ readonly format: string;
527
+ readonly mipLevelCount: number;
528
+ readonly dimension?: string;
529
+ readonly usage?: number;
530
+ }): { destroy(): void };
531
+ readonly lost?: Promise<unknown>;
532
+ pushErrorScope?(filter: "validation" | "out-of-memory"): void;
533
+ popErrorScope?(): Promise<unknown>;
534
+ }
535
+
536
+ interface ICacheEntry {
537
+ device: ICompressedUploadDevice;
538
+ snapshot: readonly unknown[];
539
+ prepared: ExternalTexture;
540
+ listener: () => void;
541
+ }
542
+
543
+ function destroyPrepared(prepared: ExternalTexture): void {
544
+ (prepared.sourceTexture as { destroy?: () => void } | null)?.destroy?.();
545
+ }
546
+
547
+ interface IUploadJob {
548
+ readonly controller: AbortController;
549
+ readonly version: number;
550
+ readonly device: ICompressedUploadDevice;
551
+ readonly snapshot: readonly unknown[];
552
+ users: number;
553
+ promise: Promise<ExternalTexture>;
554
+ }
555
+
556
+ /**
557
+ * What a prepared texture depends on, in a fixed order: identities for objects and copied values
558
+ * for scalars. A mutable object cannot show that an old width changed, so each scalar is copied.
559
+ * The binding fields are the ones `Texture.copy` carries, except the `name` and `userData`
560
+ * metadata, plus the optional `wrapR` and `compareFunction`. Matrix elements are spread so their
561
+ * numbers, not the mutable array, are compared.
562
+ */
563
+ function snapshotOf(texture: CompressedLike): unknown[] {
564
+ const image = texture.image as { width?: unknown; height?: unknown; depth?: unknown } | null;
565
+ const fields: unknown[] = [
566
+ texture.version,
567
+ texture.source,
568
+ texture.source.version,
569
+ texture.source.data,
570
+ texture.source.dataReady,
571
+ texture.mipmaps,
572
+ image?.width,
573
+ image?.height,
574
+ image?.depth,
575
+ texture.mapping,
576
+ texture.channel,
577
+ texture.format,
578
+ texture.type,
579
+ texture.internalFormat,
580
+ texture.normalized,
581
+ texture.colorSpace,
582
+ texture.wrapS,
583
+ texture.wrapT,
584
+ "wrapR" in texture ? texture.wrapR : undefined,
585
+ texture.magFilter,
586
+ texture.minFilter,
587
+ texture.anisotropy,
588
+ "compareFunction" in texture ? texture.compareFunction : undefined,
589
+ texture.flipY,
590
+ texture.premultiplyAlpha,
591
+ texture.unpackAlignment,
592
+ texture.generateMipmaps,
593
+ texture.matrixAutoUpdate,
594
+ texture.offset.x,
595
+ texture.offset.y,
596
+ texture.repeat.x,
597
+ texture.repeat.y,
598
+ texture.center.x,
599
+ texture.center.y,
600
+ texture.rotation,
601
+ ...texture.matrix.elements,
602
+ texture.renderTarget,
603
+ texture.isRenderTargetTexture,
604
+ texture.isArrayTexture,
605
+ ];
606
+ for (const mip of texture.mipmaps) {
607
+ const depth = "depth" in mip ? mip.depth : undefined;
608
+ fields.push(mip, mip.data, mip.width, mip.height, depth);
609
+ }
610
+ return fields;
611
+ }
612
+
613
+ function sameSnapshot(expected: readonly unknown[], actual: readonly unknown[]): boolean {
614
+ if (expected.length !== actual.length) return false;
615
+ return expected.every((value, index) => Object.is(value, actual[index]));
616
+ }
617
+
618
+ const TEXTURE_BINDING = 4;
619
+ const COPY_DST = 2;
620
+
621
+ /**
622
+ * One serialized upload lane for cold compressed textures. The lane keys work by `Texture`
623
+ * identity, deduplicates concurrent callers of the same texture, keeps a caller's abort from
624
+ * cancelling another caller, and owns every `GPUTexture` it allocates until the original is
625
+ * disposed, the renderer disposes it, or the device is lost. It never mutates or disposes the
626
+ * borrowed original.
627
+ */
628
+ export class CompressedTextureUploads {
629
+ private readonly jobs = new Map<Texture, IUploadJob>();
630
+ private readonly cache = new Map<Texture, ICacheEntry>();
631
+ private readonly owned = new Set<ExternalTexture>();
632
+ private readonly reverse = new Map<ExternalTexture, Texture>();
633
+ private tail: Promise<unknown> = Promise.resolve();
634
+ private disposed = false;
635
+ private readonly observedDevices = new WeakSet<ICompressedUploadDevice>();
636
+ private deviceLost: Error | undefined;
637
+
638
+ constructor(
639
+ private readonly getDevice: () => ICompressedUploadDevice | undefined,
640
+ private readonly options: { readonly budgetMs: number; readonly maxBytesPerWrite: number } = {
641
+ budgetMs: 2,
642
+ maxBytesPerWrite: 65_536,
643
+ },
644
+ ) {}
645
+
646
+ /**
647
+ * Resolves a texture this lane owns back to the original it was prepared from. A repeated call
648
+ * that hands back a previously published replacement keeps its identity instead of looking like
649
+ * an unrelated texture.
650
+ */
651
+ resolveOriginal(texture: Texture): Texture {
652
+ return this.reverse.get(texture as ExternalTexture) ?? texture;
653
+ }
654
+
655
+ /** Uploads one compressed texture and resolves the prepared `Texture`, or the original if it is not compressed. */
656
+ upload(texture: Texture, signal?: AbortSignal): Promise<Texture> {
657
+ if (this.disposed)
658
+ return Promise.reject(new Error("Renderer disposed during texture preparation."));
659
+ if (this.deviceLost) return Promise.reject(this.deviceLost);
660
+ const device = this.getDevice();
661
+ if (device === undefined)
662
+ return Promise.reject(
663
+ new Error("WebGPU renderer lacks bounded compressed texture preparation."),
664
+ );
665
+ this.subscribeLoss(device);
666
+ if (signal?.aborted) return Promise.reject(signal.reason);
667
+
668
+ const original = this.resolveOriginal(texture);
669
+ const job = this.jobs.get(original);
670
+ if (job !== undefined) {
671
+ if (job.version !== original.version)
672
+ return Promise.reject(new Error("Texture changed during preparation."));
673
+ // A pending job serves only the device and source snapshot it captured when it started.
674
+ if (job.device !== device)
675
+ return Promise.reject(new Error("Texture preparation is pending on another device."));
676
+ if (!sameSnapshot(job.snapshot, snapshotOf(original as CompressedLike)))
677
+ return Promise.reject(new Error("Texture changed during preparation."));
678
+ return this.wait(job, signal);
679
+ }
680
+
681
+ const cached = this.cache.get(original);
682
+ if (cached !== undefined && this.matches(cached, device, original as CompressedLike))
683
+ return Promise.resolve(cached.prepared);
684
+
685
+ if (
686
+ !(
687
+ ("isCompressedTexture" in original && original.isCompressedTexture === true) ||
688
+ ("isCompressedArrayTexture" in original && original.isCompressedArrayTexture === true)
689
+ )
690
+ )
691
+ return Promise.resolve(original);
692
+ if (
693
+ original.version <= 0 ||
694
+ original.mipmaps.length === 0 ||
695
+ original.source.dataReady !== true
696
+ )
697
+ return Promise.reject(
698
+ new Error("Bounded texture preparation requires ready compressed mip data."),
699
+ );
700
+ const block = compressedFormatFor(original);
701
+ if (block === undefined)
702
+ return Promise.reject(new Error("Unsupported compressed texture format."));
703
+ if (device.features?.has(block.feature) !== true)
704
+ return Promise.reject(new Error(`Compressed texture format requires ${block.feature}.`));
705
+
706
+ const started = this.start(original as CompressedLike, device, block);
707
+ return this.wait(started, signal);
708
+ }
709
+
710
+ private matches(
711
+ entry: ICacheEntry,
712
+ device: ICompressedUploadDevice,
713
+ texture: CompressedLike,
714
+ ): boolean {
715
+ return entry.device === device && sameSnapshot(entry.snapshot, snapshotOf(texture));
716
+ }
717
+
718
+ private start(
719
+ texture: CompressedLike,
720
+ device: ICompressedUploadDevice,
721
+ block: ICompressedFormatEntry,
722
+ ): IUploadJob {
723
+ const controller = new AbortController();
724
+ const version = texture.version;
725
+ // The job reads its snapshot before it queues. A source edit made while the job waits rejects
726
+ // its write.
727
+ const snapshot = snapshotOf(texture);
728
+ // Queued and in-flight work needs its own dispose hook until commit adds the cache listener.
729
+ // The job removes this hook when it settles.
730
+ const transient = () => this.releaseOriginal(texture);
731
+ texture.addEventListener("dispose", transient);
732
+ const cancelled = new Promise<never>((_resolve, reject) =>
733
+ controller.signal.addEventListener("abort", () => reject(controller.signal.reason), {
734
+ once: true,
735
+ }),
736
+ );
737
+ const work = this.tail.then(() => {
738
+ if (controller.signal.aborted) throw controller.signal.reason;
739
+ return this.write(texture, device, block, controller.signal, snapshot);
740
+ });
741
+ const job: IUploadJob = {
742
+ controller,
743
+ device,
744
+ promise: Promise.resolve(undefined as never),
745
+ snapshot,
746
+ users: 0,
747
+ version,
748
+ };
749
+ // Owning this job's outcome on `work` (not on the raced promise) means a late write that
750
+ // loses the race to cancellation still releases its allocation instead of leaking it.
751
+ const settle = work.then((prepared) => {
752
+ if (
753
+ controller.signal.aborted ||
754
+ this.getDevice() !== device ||
755
+ !sameSnapshot(snapshot, snapshotOf(texture))
756
+ ) {
757
+ this.destroyOwned(prepared);
758
+ throw new Error("Texture preparation invalidated.");
759
+ }
760
+ this.commit(texture, device, prepared, snapshot);
761
+ return prepared;
762
+ });
763
+ job.promise = Promise.race([settle, cancelled]).finally(() => {
764
+ texture.removeEventListener("dispose", transient);
765
+ if (this.jobs.get(texture) === job) this.jobs.delete(texture);
766
+ });
767
+ this.jobs.set(texture, job);
768
+ // Keep the lane serialized until the backend work and validation settle.
769
+ this.tail = Promise.allSettled([work, job.promise]).then(() => undefined);
770
+ return job;
771
+ }
772
+
773
+ /**
774
+ * Registers a prepared replacement and keeps the original's dispose listener alive while any
775
+ * cache entry or owned version for it survives. A version refresh publishes a new replacement
776
+ * and leaves the previous one valid until its lifetime ends.
777
+ */
778
+ private commit(
779
+ texture: CompressedLike,
780
+ device: ICompressedUploadDevice,
781
+ prepared: ExternalTexture,
782
+ snapshot: readonly unknown[],
783
+ ): void {
784
+ const existing = this.cache.get(texture);
785
+ if (existing === undefined) {
786
+ const listener = () => this.releaseOriginal(texture);
787
+ texture.addEventListener("dispose", listener);
788
+ this.cache.set(texture, { device, snapshot, prepared, listener });
789
+ } else {
790
+ existing.device = device;
791
+ existing.prepared = prepared;
792
+ existing.snapshot = snapshot;
793
+ }
794
+ this.owned.add(prepared);
795
+ this.reverse.set(prepared, texture);
796
+ }
797
+
798
+ private releaseOriginal(texture: Texture): void {
799
+ const entry = this.cache.get(texture);
800
+ if (entry !== undefined) {
801
+ texture.removeEventListener("dispose", entry.listener);
802
+ this.cache.delete(texture);
803
+ }
804
+ for (const prepared of [...this.owned]) {
805
+ if (this.reverse.get(prepared) === texture) {
806
+ this.owned.delete(prepared);
807
+ this.reverse.delete(prepared);
808
+ destroyPrepared(prepared);
809
+ }
810
+ }
811
+ this.jobs.get(texture)?.controller.abort(new Error("Texture disposed during preparation."));
812
+ }
813
+
814
+ private destroyOwned(prepared: ExternalTexture): void {
815
+ if (this.owned.delete(prepared)) {
816
+ this.reverse.delete(prepared);
817
+ destroyPrepared(prepared);
818
+ }
819
+ }
820
+
821
+ private wait(job: IUploadJob, signal?: AbortSignal): Promise<Texture> {
822
+ job.users += 1;
823
+ return new Promise<Texture>((resolve, reject) => {
824
+ let settled = false;
825
+ const finish = (error: unknown, value?: ExternalTexture) => {
826
+ if (settled) return;
827
+ settled = true;
828
+ signal?.removeEventListener("abort", abort);
829
+ job.users -= 1;
830
+ if (error !== undefined && error !== null) reject(error);
831
+ else resolve(value as ExternalTexture);
832
+ if (job.users === 0 && !job.controller.signal.aborted)
833
+ job.controller.abort(new Error("Texture preparation has no remaining caller."));
834
+ };
835
+ const abort = () => finish(signal?.reason ?? new Error("Texture preparation cancelled."));
836
+ signal?.addEventListener("abort", abort, { once: true });
837
+ job.promise.then(
838
+ (value) => finish(undefined, value),
839
+ (error: unknown) => finish(error),
840
+ );
841
+ });
842
+ }
843
+
844
+ private async write(
845
+ texture: CompressedLike,
846
+ device: ICompressedUploadDevice,
847
+ block: ICompressedFormatEntry,
848
+ signal: AbortSignal,
849
+ snapshot: readonly unknown[],
850
+ ): Promise<ExternalTexture> {
851
+ const mipmaps = texture.mipmaps;
852
+ const check = () => {
853
+ if (signal.aborted) throw signal.reason ?? new Error("Compressed texture upload cancelled.");
854
+ // A replaced device invalidates the job the same way a changed source does.
855
+ if (this.getDevice() !== device || !sameSnapshot(snapshot, snapshotOf(texture)))
856
+ throw new Error("Texture preparation invalidated.");
857
+ };
858
+ check();
859
+ // Validate every dimension, layer, mip size and data bound before any GPU allocation.
860
+ const plan = planCompressedUpload(texture, block, this.options.maxBytesPerWrite);
861
+ check();
862
+ if (
863
+ (plan.width % block.blockWidth !== 0 || plan.height % block.blockHeight !== 0) &&
864
+ device.features?.has("texture-compression-unaligned") !== true
865
+ )
866
+ throw new Error(
867
+ "Compressed texture base must be block-aligned without texture-compression-unaligned.",
868
+ );
869
+ const gpuTexture = device.createTexture({
870
+ size: { width: plan.width, height: plan.height, depthOrArrayLayers: plan.layers },
871
+ format: block.gpuFormat,
872
+ mipLevelCount: Math.max(1, mipmaps.length),
873
+ dimension: "2d",
874
+ usage: TEXTURE_BINDING | COPY_DST,
875
+ });
876
+ const prepared = new ExternalTexture(gpuTexture);
877
+ // Own the replacement from creation, before `.copy` and any await, so a throwing copy, an
878
+ // invalidation or `dispose` releases the allocation immediately and exactly once; `Set.delete`
879
+ // in `destroyOwned` keeps that from double-destroying a committed version.
880
+ this.owned.add(prepared);
881
+ this.reverse.set(prepared, texture);
882
+ try {
883
+ // `ExternalTexture.copy` shares the original's `source` and increments its version.
884
+ // Copy from a view whose `source` is a new `Source` over the same data. The original keeps
885
+ // its own `source` and version.
886
+ const isolatedSource = new Source(texture.source.data);
887
+ const view = new Proxy(texture, {
888
+ get(target, key, receiver) {
889
+ return key === "source" ? isolatedSource : Reflect.get(target, key, receiver);
890
+ },
891
+ });
892
+ // `ExternalTexture.copy` copies the original's `sourceTexture` (undefined for a cold texture),
893
+ // so reassign the public GPU backing the frame binds after the copy.
894
+ prepared.copy(view as never);
895
+ prepared.sourceTexture = gpuTexture;
896
+ prepared.needsUpdate = true;
897
+ await this.writeTiles(device, gpuTexture, plan, signal, check);
898
+ } catch (error) {
899
+ // `.copy` can reset the public backing before it throws; restore it so the owned release
900
+ // destroys the freshly allocated GPU texture exactly once.
901
+ prepared.sourceTexture = gpuTexture;
902
+ this.destroyOwned(prepared);
903
+ throw error;
904
+ }
905
+ return prepared;
906
+ }
907
+
908
+ private async writeTiles(
909
+ device: ICompressedUploadDevice,
910
+ gpuTexture: { destroy(): void },
911
+ plan: ICompressedUploadPlan,
912
+ signal: AbortSignal,
913
+ check: () => void,
914
+ ): Promise<void> {
915
+ const budgetMs = this.options.budgetMs;
916
+ const scoped =
917
+ typeof device.pushErrorScope === "function" && typeof device.popErrorScope === "function";
918
+ const failures: unknown[] = [];
919
+ const validations: Promise<void>[] = [];
920
+ let started: number | null = null;
921
+ let index = 0;
922
+ try {
923
+ while (index < plan.tiles.length && failures.length === 0) {
924
+ check();
925
+ if (started === null) started = performance.now();
926
+ if (performance.now() - started >= budgetMs) {
927
+ await new Promise((resolve) => setTimeout(resolve, 0));
928
+ started = performance.now();
929
+ check();
930
+ }
931
+ if (scoped) {
932
+ device.pushErrorScope?.("out-of-memory");
933
+ device.pushErrorScope?.("validation");
934
+ }
935
+ try {
936
+ do {
937
+ check();
938
+ const tile = plan.tiles[index];
939
+ if (tile === undefined) break;
940
+ device.queue.writeTexture(
941
+ { texture: gpuTexture, mipLevel: tile.mipLevel, origin: tile.origin },
942
+ tile.data,
943
+ tile.layout,
944
+ tile.extent,
945
+ );
946
+ index += 1;
947
+ } while (index < plan.tiles.length && performance.now() - started < budgetMs);
948
+ } finally {
949
+ if (scoped) {
950
+ validations.push(
951
+ Promise.allSettled([device.popErrorScope?.(), device.popErrorScope?.()]).then(
952
+ (results) => {
953
+ for (const result of results) {
954
+ if (result.status === "rejected") failures.push(result.reason);
955
+ else if (result.value !== null && result.value !== undefined)
956
+ failures.push(new Error((result.value as { message?: string }).message));
957
+ }
958
+ },
959
+ ),
960
+ );
961
+ }
962
+ }
963
+ if (validations.length === 4) await validations.shift();
964
+ check();
965
+ if (index < plan.tiles.length && failures.length === 0)
966
+ await new Promise((resolve) => setTimeout(resolve, 0));
967
+ }
968
+ } finally {
969
+ // A `check` or `writeTexture` throw exits the loop early. Settle every popped scope before
970
+ // the lane advances. `allSettled` keeps the original failure as the propagated error.
971
+ await Promise.allSettled(validations);
972
+ }
973
+ if (failures.length > 0)
974
+ throw new AggregateError(
975
+ failures,
976
+ `Compressed texture upload failed: ${failures
977
+ .map((error) => (error as Error)?.message ?? String(error))
978
+ .join("; ")}`,
979
+ );
980
+ check();
981
+ }
982
+
983
+ private subscribeLoss(device: ICompressedUploadDevice): void {
984
+ if (this.observedDevices.has(device) || device.lost === undefined) return;
985
+ this.observedDevices.add(device);
986
+ const lost = (error: unknown) => {
987
+ this.deviceLost =
988
+ error instanceof Error ? error : new Error("Device lost during texture preparation.");
989
+ for (const job of this.jobs.values()) job.controller.abort(this.deviceLost);
990
+ for (const prepared of [...this.owned]) this.destroyOwned(prepared);
991
+ };
992
+ device.lost.then(lost, lost);
993
+ }
994
+
995
+ /** Releases every GPU allocation and listener the lane owns. Originals are untouched. */
996
+ dispose(): void {
997
+ this.disposed = true;
998
+ for (const job of this.jobs.values())
999
+ job.controller.abort(new Error("Renderer disposed during texture preparation."));
1000
+ this.jobs.clear();
1001
+ for (const [texture, entry] of this.cache)
1002
+ texture.removeEventListener("dispose", entry.listener);
1003
+ this.cache.clear();
1004
+ for (const prepared of [...this.owned]) this.destroyOwned(prepared);
1005
+ this.owned.clear();
1006
+ this.reverse.clear();
1007
+ }
1008
+ }