pngine 4.3.0 → 4.3.2

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.
@@ -0,0 +1,1893 @@
1
+ /**
2
+ * Texture write-layout contract — host (JS) binding.
3
+ *
4
+ * Plan 01's pure model, the JS half of the shared contract. It proves a
5
+ * raw-byte write fits its source and destination before the host emits a
6
+ * WebGPU call. Nothing here imports WebGPU globals, touches GPU state, reads
7
+ * IO, allocates a result owned elsewhere, or holds mutable module state: every
8
+ * call is a pure function of its arguments.
9
+ *
10
+ * The same `tests/fixtures/texture-layout.json` corpus drives this binding and
11
+ * the Zig binding (`src/types/texture_layout.zig`). Refusal codes, fields and
12
+ * the normalized layout values are the contract's, not this language's.
13
+ *
14
+ * JS arithmetic guard: the contract is u64/u32 integer arithmetic. Every
15
+ * numeric input must be a nonnegative safe integer within its field bound
16
+ * before it is used; every product and sum is checked before it is performed
17
+ * (and again against u32 before it can become a returned value). A refused
18
+ * value is data, `{ refuse: { code, field, actual, limit } }`, never a thrown
19
+ * TypeError substitute.
20
+ *
21
+ * Plan 03/04 call `calculateWrite` and pass absence through unchanged: an
22
+ * omitted `bytesPerRow`/`rowsPerImage` is `undefined`/`null`, not 0. An
23
+ * authored 0 stays 0 and is judged by the stride-presence and minimum rules.
24
+ */
25
+
26
+ const U32_MAX = 0xffffffff;
27
+ const MAX_SAFE = Number.MAX_SAFE_INTEGER;
28
+
29
+ /**
30
+ * @typedef {"invalid-format" | "invalid-texture-descriptor" | "unsupported-dimension" |
31
+ * "missing-copy-dst" | "missing-copy-src" | "multisampled-destination" |
32
+ * "sample-count-mismatch" | "overlapping-subresources" | "invalid-aspect" |
33
+ * "aspect-not-writable" | "partial-depth-stencil-write" | "partial-subresource-copy" |
34
+ * "mip-out-of-range" |
35
+ * "origin-out-of-bounds" | "extent-out-of-bounds" | "unaligned-block-origin" |
36
+ * "unaligned-block-extent" | "missing-bytes-per-row" | "missing-rows-per-image" |
37
+ * "bytes-per-row-too-small" | "rows-per-image-too-small" |
38
+ * "bytes-per-row-alignment" | "buffer-offset-alignment" |
39
+ * "buffer-out-of-bounds" | "insufficient-data" |
40
+ * "arithmetic-overflow"} Code
41
+ */
42
+
43
+ /**
44
+ * @typedef {"none" | "format" | "aspect" | "dimension" | "usage" | "sample-count" |
45
+ * "mip-level" | "mip-level-count" | "size-width" | "size-height" |
46
+ * "size-depth-or-array-layers" | "origin-x" | "origin-y" | "origin-z" |
47
+ * "bytes-per-row" | "rows-per-image" | "offset" | "data"} Field
48
+ */
49
+
50
+ /**
51
+ * @typedef {{ code: Code, field: Field, actual: number, limit: number }} Refusal
52
+ * @typedef {{ width: number, height: number, depthOrArrayLayers: number }} Extent
53
+ * @typedef {{ x: number, y: number, z: number }} Origin
54
+ * @typedef {"1d" | "2d" | "3d"} Dimension
55
+ * @typedef {"all" | "stencil-only" | "depth-only"} AspectName
56
+ *
57
+ * @typedef {{
58
+ * width: number,
59
+ * height?: number | null,
60
+ * depthOrArrayLayers?: number | null,
61
+ * }} ExtentInput
62
+ *
63
+ * @typedef {{ x?: number | null, y?: number | null, z?: number | null }} OriginInput
64
+ *
65
+ * @typedef {{
66
+ * size: ExtentInput,
67
+ * dimension: Dimension | string,
68
+ * format: string | number,
69
+ * usage: number,
70
+ * sampleCount: number,
71
+ * mipLevelCount: number,
72
+ * extentSource?: "explicit" | "canvas" | "image-bitmap" | string,
73
+ * }} TextureDescriptorInput
74
+ *
75
+ * @typedef {{
76
+ * offset?: number | null,
77
+ * bytesPerRow?: number | null,
78
+ * rowsPerImage?: number | null,
79
+ * origin?: OriginInput | null,
80
+ * mipLevel?: number | null,
81
+ * aspect?: AspectName | number | string | null,
82
+ * size?: ExtentInput | null,
83
+ * }} WriteLayoutInput
84
+ *
85
+ * @typedef {{
86
+ * blockWidth: number,
87
+ * blockHeight: number,
88
+ * bytesPerBlock: number,
89
+ * hasDepth: boolean,
90
+ * hasStencil: boolean,
91
+ * writeDestination: boolean,
92
+ * }} FormatInfo
93
+ *
94
+ * @typedef {{ logical: Extent, physical: Extent }} MipExtent
95
+ *
96
+ * @typedef {{
97
+ * logicalMipExtent: Extent,
98
+ * physicalMipExtent: Extent,
99
+ * copyExtent: Extent,
100
+ * widthInBlocks: number,
101
+ * heightInBlocks: number,
102
+ * bytesInLastRow: number,
103
+ * bytesPerRow: number,
104
+ * rowsPerImage: number,
105
+ * imageStride: number,
106
+ * requiredBytesInCopy: number,
107
+ * endOffset: number,
108
+ * }} Layout
109
+ *
110
+ * @typedef {{ ok: FormatInfo } | { refuse: Refusal }} FormatInfoResult
111
+ * @typedef {{ ok: MipExtent } | { refuse: Refusal }} MipExtentResult
112
+ * @typedef {{ ok: Layout } | { refuse: Refusal }} Result
113
+ * @typedef {{ value: number } | { refuse: Refusal }} NumberRead
114
+ * @typedef {{ value: Extent } | { refuse: Refusal }} ExtentRead
115
+ * @typedef {{ value: Origin } | { refuse: Refusal }} OriginRead
116
+ * @typedef {{ value: number } | { refuse: Refusal }} CheckedValue
117
+ * @typedef {{ value: FormatRow } | { refuse: Refusal }} RowRead
118
+ */
119
+
120
+ /**
121
+ * Operation policy for the shared calculator. `queueWrite` is `writeTexture`
122
+ * and sets `aligned = false`; the GPUCommandEncoder buffer↔texture copies set
123
+ * it true AND name the direction their texture endpoint occupies. Only the
124
+ * aligned policies acquire the bytes-per-row and buffer-offset rules, so a
125
+ * queue write can never reach them.
126
+ *
127
+ * The objects are frozen identity constants: `calculateCopy` rejects any other
128
+ * value with a TypeError rather than silently reinterpreting a typo as "no
129
+ * alignment" or as the other direction.
130
+ *
131
+ * @typedef {{ readonly aligned: boolean, readonly direction: "buffer-to-texture" | "texture-to-buffer" }} CopyPolicyValue
132
+ * @type {{ readonly queueWrite: CopyPolicyValue, readonly bufferToTexture: CopyPolicyValue, readonly textureToBuffer: CopyPolicyValue }}
133
+ */
134
+ export const CopyPolicy = Object.freeze({
135
+ queueWrite: Object.freeze({ aligned: false, direction: "buffer-to-texture" }),
136
+ bufferToTexture: Object.freeze({ aligned: true, direction: "buffer-to-texture" }),
137
+ textureToBuffer: Object.freeze({ aligned: true, direction: "texture-to-buffer" }),
138
+ });
139
+
140
+ /**
141
+ * One row of WebGPU's texel-block facts for a named format, in the same shape
142
+ * as the Zig binding's `FormatRow`. A zero footprint with a false destination
143
+ * flag means the CRD publishes none for that aspect (depth24plus), never an
144
+ * invented size. Writability is a separate verdict from the footprint.
145
+ *
146
+ * @typedef {{
147
+ * name: string,
148
+ * byte: number,
149
+ * blockWidth: number,
150
+ * blockHeight: number,
151
+ * colorBytesPerBlock: number,
152
+ * hasDepth: boolean,
153
+ * hasStencil: boolean,
154
+ * depthBytesPerBlock: number,
155
+ * depthWriteDestination: boolean,
156
+ * stencilBytesPerBlock: number,
157
+ * stencilWriteDestination: boolean,
158
+ * family?: "bc" | "etc2" | "astc",
159
+ * sliced3d?: boolean,
160
+ * }} FormatRow
161
+ */
162
+
163
+ /**
164
+ * @param {string} name
165
+ * @param {number} byte
166
+ * @param {number} bytesPerBlock
167
+ * @returns {FormatRow}
168
+ */
169
+ function colorFormat(name, byte, bytesPerBlock) {
170
+ return {
171
+ name,
172
+ byte,
173
+ blockWidth: 1,
174
+ blockHeight: 1,
175
+ colorBytesPerBlock: bytesPerBlock,
176
+ hasDepth: false,
177
+ hasStencil: false,
178
+ depthBytesPerBlock: 0,
179
+ depthWriteDestination: false,
180
+ stencilBytesPerBlock: 0,
181
+ stencilWriteDestination: false,
182
+ };
183
+ }
184
+
185
+ /**
186
+ * @param {string} name
187
+ * @param {number} byte
188
+ * @param {Partial<FormatRow>} fields
189
+ * @returns {FormatRow}
190
+ */
191
+ function depthStencilFormat(name, byte, fields) {
192
+ return {
193
+ name,
194
+ byte,
195
+ blockWidth: 1,
196
+ blockHeight: 1,
197
+ colorBytesPerBlock: 0,
198
+ hasDepth: false,
199
+ hasStencil: false,
200
+ depthBytesPerBlock: 0,
201
+ depthWriteDestination: false,
202
+ stencilBytesPerBlock: 0,
203
+ stencilWriteDestination: false,
204
+ ...fields,
205
+ };
206
+ }
207
+
208
+ /** BC names in plan/CRD byte order; `0x80 + index` is the ABI byte. */
209
+ const BC_NAMES = [
210
+ "bc1-rgba-unorm", "bc1-rgba-unorm-srgb",
211
+ "bc2-rgba-unorm", "bc2-rgba-unorm-srgb",
212
+ "bc3-rgba-unorm", "bc3-rgba-unorm-srgb",
213
+ "bc4-r-unorm", "bc4-r-snorm",
214
+ "bc5-rg-unorm", "bc5-rg-snorm",
215
+ "bc6h-rgb-ufloat", "bc6h-rgb-float",
216
+ "bc7-rgba-unorm", "bc7-rgba-unorm-srgb",
217
+ ];
218
+
219
+ /** ETC2/EAC names in plan/CRD byte order; `0x90 + index` is the ABI byte. */
220
+ const ETC2_NAMES = [
221
+ "etc2-rgb8unorm", "etc2-rgb8unorm-srgb",
222
+ "etc2-rgb8a1unorm", "etc2-rgb8a1unorm-srgb",
223
+ "etc2-rgba8unorm", "etc2-rgba8unorm-srgb",
224
+ "eac-r11unorm", "eac-r11snorm",
225
+ "eac-rg11unorm", "eac-rg11snorm",
226
+ ];
227
+
228
+ /** ASTC shapes in plan/CRD order: low nibble width, high nibble height. */
229
+ const ASTC_SHAPES = [
230
+ 0x44, 0x45, 0x55, 0x56, 0x66, 0x58, 0x68,
231
+ 0x88, 0x5a, 0x6a, 0x8a, 0xaa, 0xac, 0xcc,
232
+ ];
233
+
234
+ /**
235
+ * ASTC names in plan/CRD byte order, derived from the packed shape table:
236
+ * `0xa0 + index*2` is linear and `0xa1 + index*2` sRGB. Deriving the 28
237
+ * spellings from the fourteen shapes keeps one table instead of two.
238
+ */
239
+ const ASTC_NAMES = ASTC_SHAPES.flatMap((shape) => {
240
+ const suffix = `${shape & 0x0f}x${shape >> 4}-unorm`;
241
+ return [`astc-${suffix}`, `astc-${suffix}-srgb`];
242
+ });
243
+
244
+ /**
245
+ * One compressed format's facts, from a name or ABI byte. Plan 07's tranche A
246
+ * fills all 52 rows now (slim codes + one packed ASTC shape table) so the later
247
+ * tranches add schema names and decoders only, never arithmetic. All 52 names
248
+ * now resolve as strings, ASTC's from the shape table above.
249
+ *
250
+ * @param {string | number} format
251
+ * @returns {{byte: number, blockWidth: number, blockHeight: number, bytesPerBlock: number, family: "bc" | "etc2" | "astc", sliced3d: boolean} | null}
252
+ */
253
+ function compressedFacts(format) {
254
+ let code = format;
255
+ if (typeof code === "string") {
256
+ const bc = BC_NAMES.indexOf(code);
257
+ if (bc >= 0) {
258
+ code = 0x80 + bc;
259
+ } else {
260
+ const etc2 = ETC2_NAMES.indexOf(code);
261
+ if (etc2 >= 0) {
262
+ code = 0x90 + etc2;
263
+ } else {
264
+ const astc = ASTC_NAMES.indexOf(code);
265
+ if (astc < 0) return null;
266
+ code = 0xa0 + astc;
267
+ }
268
+ }
269
+ }
270
+ if (!Number.isSafeInteger(code) || code < 0 || code > 255) return null;
271
+ if (code >= 0x80 && code <= 0x8d) {
272
+ const index = code - 0x80;
273
+ return {
274
+ byte: code,
275
+ blockWidth: 4,
276
+ blockHeight: 4,
277
+ bytesPerBlock: index === 0 || index === 1 || index === 6 || index === 7 ? 8 : 16,
278
+ family: "bc",
279
+ sliced3d: true,
280
+ };
281
+ }
282
+ if (code >= 0x90 && code <= 0x99) {
283
+ const index = code - 0x90;
284
+ return {
285
+ byte: code,
286
+ blockWidth: 4,
287
+ blockHeight: 4,
288
+ bytesPerBlock: index <= 3 || index === 6 || index === 7 ? 8 : 16,
289
+ family: "etc2",
290
+ sliced3d: false,
291
+ };
292
+ }
293
+ if (code >= 0xa0 && code <= 0xbb) {
294
+ const shape = ASTC_SHAPES[(code - 0xa0) >> 1];
295
+ return {
296
+ byte: code,
297
+ blockWidth: shape & 0x0f,
298
+ blockHeight: shape >> 4,
299
+ bytesPerBlock: 16,
300
+ family: "astc",
301
+ sliced3d: true,
302
+ };
303
+ }
304
+ return null;
305
+ }
306
+
307
+ /**
308
+ * Every named ordinary format, in the Zig enum's own declaration order. The
309
+ * two sentinels (`preferredCanvasFormat`, unknown bytes) and compressed names
310
+ * deliberately have no row here: a compressed name/byte resolves through
311
+ * `compressedFacts`, which is also the single block/byte table.
312
+ *
313
+ * @type {FormatRow[]}
314
+ */
315
+ const FORMAT_ROWS = [
316
+ // 8-bit RGBA/BGRA and wide RGBA/sRGB (0x0x).
317
+ colorFormat("rgba8unorm", 0x00, 4),
318
+ colorFormat("rgba8snorm", 0x01, 4),
319
+ colorFormat("rgba8uint", 0x02, 4),
320
+ colorFormat("rgba8sint", 0x03, 4),
321
+ colorFormat("bgra8unorm", 0x04, 4),
322
+ colorFormat("rgba16float", 0x05, 8),
323
+ colorFormat("rgba32float", 0x06, 16),
324
+ colorFormat("rgba8unorm-srgb", 0x07, 4),
325
+ colorFormat("bgra8unorm-srgb", 0x08, 4),
326
+
327
+ // Depth / stencil (0x1x). depth24plus has no copy footprint; the
328
+ // depth32float family's depth aspect is a validated copy source but not a
329
+ // destination. stencil8 and depth16unorm are both.
330
+ depthStencilFormat("depth24plus", 0x10, { hasDepth: true }),
331
+ depthStencilFormat("depth24plus-stencil8", 0x11, {
332
+ hasDepth: true,
333
+ hasStencil: true,
334
+ stencilBytesPerBlock: 1,
335
+ stencilWriteDestination: true,
336
+ }),
337
+ depthStencilFormat("depth32float", 0x12, {
338
+ hasDepth: true,
339
+ depthBytesPerBlock: 4,
340
+ }),
341
+ depthStencilFormat("stencil8", 0x13, {
342
+ hasStencil: true,
343
+ stencilBytesPerBlock: 1,
344
+ stencilWriteDestination: true,
345
+ }),
346
+ depthStencilFormat("depth16unorm", 0x14, {
347
+ hasDepth: true,
348
+ depthBytesPerBlock: 2,
349
+ depthWriteDestination: true,
350
+ }),
351
+ depthStencilFormat("depth32float-stencil8", 0x15, {
352
+ hasDepth: true,
353
+ hasStencil: true,
354
+ depthBytesPerBlock: 4,
355
+ stencilBytesPerBlock: 1,
356
+ stencilWriteDestination: true,
357
+ }),
358
+
359
+ // 32-bit-per-channel r/rg (0x2x).
360
+ colorFormat("r32float", 0x20, 4),
361
+ colorFormat("rg32float", 0x21, 8),
362
+ colorFormat("r32uint", 0x22, 4),
363
+ colorFormat("r32sint", 0x23, 4),
364
+ colorFormat("rg32uint", 0x24, 8),
365
+ colorFormat("rg32sint", 0x25, 8),
366
+
367
+ // 8-bit & 16-bit-float r/rg (0x3x).
368
+ colorFormat("r8unorm", 0x30, 1),
369
+ colorFormat("rg8unorm", 0x31, 2),
370
+ colorFormat("r16float", 0x32, 2),
371
+ colorFormat("rg16float", 0x33, 4),
372
+ colorFormat("r8snorm", 0x34, 1),
373
+ colorFormat("r8uint", 0x35, 1),
374
+ colorFormat("r8sint", 0x36, 1),
375
+ colorFormat("rg8snorm", 0x37, 2),
376
+ colorFormat("rg8uint", 0x38, 2),
377
+ colorFormat("rg8sint", 0x39, 2),
378
+
379
+ // 16-bit int/unorm r/rg (0x4x).
380
+ colorFormat("r16uint", 0x40, 2),
381
+ colorFormat("r16sint", 0x41, 2),
382
+ colorFormat("rg16uint", 0x42, 4),
383
+ colorFormat("rg16sint", 0x43, 4),
384
+ colorFormat("r16unorm", 0x44, 2),
385
+ colorFormat("r16snorm", 0x45, 2),
386
+ colorFormat("rg16unorm", 0x46, 4),
387
+ colorFormat("rg16snorm", 0x47, 4),
388
+
389
+ // 16-bit int/unorm rgba (0x5x).
390
+ colorFormat("rgba16uint", 0x50, 8),
391
+ colorFormat("rgba16sint", 0x51, 8),
392
+ colorFormat("rgba16unorm", 0x52, 8),
393
+ colorFormat("rgba16snorm", 0x53, 8),
394
+
395
+ // 32-bit int rgba (0x6x).
396
+ colorFormat("rgba32uint", 0x60, 16),
397
+ colorFormat("rgba32sint", 0x61, 16),
398
+
399
+ // Packed 32-bit (0x7x).
400
+ colorFormat("rgb10a2unorm", 0x70, 4),
401
+ colorFormat("rgb10a2uint", 0x71, 4),
402
+ colorFormat("rg11b10ufloat", 0x72, 4),
403
+ colorFormat("rgb9e5ufloat", 0x73, 4),
404
+ ];
405
+
406
+ /** @type {Map<string, FormatRow>} */
407
+ const FORMAT_BY_NAME = new Map(FORMAT_ROWS.map((row) => [row.name, row]));
408
+ /** @type {Map<number, FormatRow>} */
409
+ const FORMAT_BY_BYTE = new Map(FORMAT_ROWS.map((row) => [row.byte, row]));
410
+
411
+ /** @type {Map<string, number>} */
412
+ const ASPECT_TAGS = new Map([
413
+ ["all", 0],
414
+ ["stencil-only", 1],
415
+ ["depth-only", 2],
416
+ ]);
417
+
418
+ /**
419
+ * @param {Code} code
420
+ * @param {Field} field
421
+ * @param {number} [actual]
422
+ * @param {number} [limit]
423
+ * @returns {Refusal}
424
+ */
425
+ function refusal(code, field, actual = 0, limit = 0) {
426
+ return { code, field, actual, limit };
427
+ }
428
+
429
+ /**
430
+ * Refuse a numeric value that cannot enter the contract's checked arithmetic.
431
+ * The JS host has no u64; a non-safe, negative, nonnumeric or above-bound
432
+ * value is not an integer the calculator can prove. The refusal is data and
433
+ * happens before any product or sum touches the value.
434
+ *
435
+ * `actual` carries the value only when it is itself a nonnegative safe integer
436
+ * (so an above-u32 field bound is reported exactly); otherwise it is 0, the
437
+ * same convention the catalogue uses for a nonnumeric aspect/format.
438
+ *
439
+ * @param {Field} field
440
+ * @param {number} actual
441
+ * @param {number} limit
442
+ * @returns {Refusal}
443
+ */
444
+ function hostRefusal(field, actual, limit) {
445
+ return refusal("arithmetic-overflow", field, actual, limit);
446
+ }
447
+
448
+ /**
449
+ * Read a numeric input and prove it is a nonnegative safe integer within
450
+ * `limit` before any arithmetic uses it.
451
+ *
452
+ * @param {Field} field
453
+ * @param {unknown} value
454
+ * @param {number} limit
455
+ * @returns {NumberRead}
456
+ */
457
+ function readBounded(field, value, limit) {
458
+ if (
459
+ typeof value !== "number" ||
460
+ !Number.isSafeInteger(value) ||
461
+ value < 0
462
+ ) {
463
+ return { refuse: hostRefusal(field, 0, limit) };
464
+ }
465
+ if (value > limit) {
466
+ return { refuse: hostRefusal(field, value, limit) };
467
+ }
468
+ return { value };
469
+ }
470
+
471
+ /**
472
+ * Read an optional u32 field. `undefined` and `null` are absence, not 0.
473
+ *
474
+ * @param {Field} field
475
+ * @param {unknown} value
476
+ * @returns {{ present: false } | { present: true, value: number } | { refuse: Refusal }}
477
+ */
478
+ function readOptionalU32(field, value) {
479
+ if (value === undefined || value === null) return { present: false };
480
+ const read = readBounded(field, value, U32_MAX);
481
+ if ("refuse" in read) return { refuse: read.refuse };
482
+ return { present: true, value: read.value };
483
+ }
484
+
485
+ /**
486
+ * @param {unknown} value
487
+ * @returns {ExtentRead}
488
+ */
489
+ function readExtent(value) {
490
+ if (value === null || typeof value !== "object") {
491
+ return { refuse: hostRefusal("size-width", 0, U32_MAX) };
492
+ }
493
+ const source = /** @type {ExtentInput} */ (value);
494
+ const width = readBounded("size-width", source.width, U32_MAX);
495
+ if ("refuse" in width) return { refuse: width.refuse };
496
+ const height =
497
+ source.height === undefined || source.height === null
498
+ ? { value: 1 }
499
+ : readBounded("size-height", source.height, U32_MAX);
500
+ if ("refuse" in height) return { refuse: height.refuse };
501
+ const depth =
502
+ source.depthOrArrayLayers === undefined ||
503
+ source.depthOrArrayLayers === null
504
+ ? { value: 1 }
505
+ : readBounded("size-depth-or-array-layers", source.depthOrArrayLayers, U32_MAX);
506
+ if ("refuse" in depth) return { refuse: depth.refuse };
507
+ return {
508
+ value: { width: width.value, height: height.value, depthOrArrayLayers: depth.value },
509
+ };
510
+ }
511
+
512
+ /**
513
+ * @param {unknown} value
514
+ * @returns {OriginRead}
515
+ */
516
+ function readOrigin(value) {
517
+ if (value === undefined || value === null) {
518
+ return { value: { x: 0, y: 0, z: 0 } };
519
+ }
520
+ if (typeof value !== "object") {
521
+ return { refuse: hostRefusal("origin-x", 0, U32_MAX) };
522
+ }
523
+ const source = /** @type {OriginInput} */ (value);
524
+ const x =
525
+ source.x === undefined || source.x === null
526
+ ? { value: 0 }
527
+ : readBounded("origin-x", source.x, U32_MAX);
528
+ if ("refuse" in x) return { refuse: x.refuse };
529
+ const y =
530
+ source.y === undefined || source.y === null
531
+ ? { value: 0 }
532
+ : readBounded("origin-y", source.y, U32_MAX);
533
+ if ("refuse" in y) return { refuse: y.refuse };
534
+ const z =
535
+ source.z === undefined || source.z === null
536
+ ? { value: 0 }
537
+ : readBounded("origin-z", source.z, U32_MAX);
538
+ if ("refuse" in z) return { refuse: z.refuse };
539
+ return { value: { x: x.value, y: y.value, z: z.value } };
540
+ }
541
+
542
+ /**
543
+ * Resolve a format name or its ABI byte to the format row. Sentinels,
544
+ * undeclared bytes and unknown names resolve to no row (never a fallback).
545
+ *
546
+ * @param {unknown} format
547
+ * @returns {FormatRow | null}
548
+ */
549
+ function resolveFormat(format) {
550
+ if (typeof format === "string") return FORMAT_BY_NAME.get(format) ?? null;
551
+ if (
552
+ typeof format === "number" &&
553
+ Number.isSafeInteger(format) &&
554
+ format >= 0 &&
555
+ format <= 255
556
+ ) {
557
+ return FORMAT_BY_BYTE.get(format) ?? null;
558
+ }
559
+ return null;
560
+ }
561
+
562
+ /**
563
+ * Resolve an aspect name or numeric tag to its wire tag. Anything that is not
564
+ * a known name or an integer tag in 0..255 stays an unknown tag; the format
565
+ * row decides whether that is `invalid-aspect`.
566
+ *
567
+ * @param {unknown} aspect
568
+ * @returns {number}
569
+ */
570
+ function aspectTag(aspect) {
571
+ if (aspect === undefined || aspect === null) return 0;
572
+ if (typeof aspect === "string") return ASPECT_TAGS.get(aspect) ?? 0xff;
573
+ if (
574
+ typeof aspect === "number" &&
575
+ Number.isSafeInteger(aspect) &&
576
+ aspect >= 0 &&
577
+ aspect <= 255
578
+ ) {
579
+ return aspect;
580
+ }
581
+ return 0xff;
582
+ }
583
+
584
+ /**
585
+ * Resolve a format and the selected aspect to its copy footprint. Unknown
586
+ * formats, sentinels and absent aspect rows refuse with `invalid-format`
587
+ * instead of falling back to any format. Depth/stencil rows resolve exactly
588
+ * one legal aspect and apply the destination policy before exposing a
589
+ * footprint; plain colour formats accept only the `all` tag.
590
+ *
591
+ * @param {string | number} format
592
+ * @param {AspectName | number | string | null} [aspect]
593
+ * @returns {FormatInfoResult}
594
+ */
595
+ export function formatInfo(format, aspect = "all") {
596
+ const row = resolveFormat(format);
597
+ if (row === null) {
598
+ const compressed = compressedFacts(format);
599
+ if (compressed === null) return { refuse: refusal("invalid-format", "format") };
600
+ if (aspectTag(aspect) !== 0) return { refuse: refusal("invalid-aspect", "aspect") };
601
+ return {
602
+ ok: {
603
+ blockWidth: compressed.blockWidth,
604
+ blockHeight: compressed.blockHeight,
605
+ bytesPerBlock: compressed.bytesPerBlock,
606
+ hasDepth: false,
607
+ hasStencil: false,
608
+ writeDestination: true,
609
+ },
610
+ };
611
+ }
612
+ const tag = aspectTag(aspect);
613
+
614
+ if (row.hasDepth || row.hasStencil) {
615
+ /** @type {number} */
616
+ let bytesPerBlock;
617
+ switch (tag) {
618
+ case 2: {
619
+ if (!row.hasDepth) return { refuse: refusal("invalid-aspect", "aspect") };
620
+ if (!row.depthWriteDestination) {
621
+ return { refuse: refusal("aspect-not-writable", "aspect") };
622
+ }
623
+ bytesPerBlock = row.depthBytesPerBlock;
624
+ break;
625
+ }
626
+ case 1: {
627
+ if (!row.hasStencil) return { refuse: refusal("invalid-aspect", "aspect") };
628
+ if (!row.stencilWriteDestination) {
629
+ return { refuse: refusal("aspect-not-writable", "aspect") };
630
+ }
631
+ bytesPerBlock = row.stencilBytesPerBlock;
632
+ break;
633
+ }
634
+ default:
635
+ // `.all` is not singular, and an undeclared aspect tag is unknown.
636
+ return { refuse: refusal("invalid-aspect", "aspect") };
637
+ }
638
+ if (bytesPerBlock === 0) {
639
+ return { refuse: refusal("invalid-format", "format") };
640
+ }
641
+ return {
642
+ ok: {
643
+ blockWidth: row.blockWidth,
644
+ blockHeight: row.blockHeight,
645
+ bytesPerBlock,
646
+ hasDepth: row.hasDepth,
647
+ hasStencil: row.hasStencil,
648
+ writeDestination: true,
649
+ },
650
+ };
651
+ }
652
+
653
+ if (tag !== 0) return { refuse: refusal("invalid-aspect", "aspect") };
654
+ if (row.colorBytesPerBlock === 0) {
655
+ return { refuse: refusal("invalid-format", "format") };
656
+ }
657
+ return {
658
+ ok: {
659
+ blockWidth: row.blockWidth,
660
+ blockHeight: row.blockHeight,
661
+ bytesPerBlock: row.colorBytesPerBlock,
662
+ hasDepth: false,
663
+ hasStencil: false,
664
+ writeDestination: true,
665
+ },
666
+ };
667
+ }
668
+
669
+ /** Compressed family → the device feature that admits it. */
670
+ const FAMILY_FEATURE = {
671
+ bc: "texture-compression-bc",
672
+ etc2: "texture-compression-etc2",
673
+ astc: "texture-compression-astc",
674
+ };
675
+ /** Compressed family → the feature that admits 3D. ETC2 has none. */
676
+ const FAMILY_SLICED_FEATURE = {
677
+ bc: "texture-compression-bc-sliced-3d",
678
+ astc: "texture-compression-astc-sliced-3d",
679
+ };
680
+
681
+ /**
682
+ * The first device feature a format/dimension pair requires but `features`
683
+ * lacks, or null. Ordinary formats need none; a compressed format needs its
684
+ * family feature and, for 3D, the family's sliced feature. ETC2/EAC 3D is
685
+ * refused by the descriptor rule below, not by a feature (the CRD defines no
686
+ * ETC2 sliced feature), so this never invents one.
687
+ *
688
+ * @param {string | number} format
689
+ * @param {Dimension | string} dimension
690
+ * @param {Set<string> | { has(f: string): boolean }} features
691
+ * @returns {string | null}
692
+ */
693
+ export function missingFormatFeature(format, dimension, features) {
694
+ const row = compressedFacts(format);
695
+ if (row === null) return null;
696
+ const base = FAMILY_FEATURE[row.family];
697
+ if (!features.has(base)) return base;
698
+ if (dimension === "3d" && row.sliced3d) {
699
+ const sliced = FAMILY_SLICED_FEATURE[row.family];
700
+ if (!features.has(sliced)) return sliced;
701
+ }
702
+ return null;
703
+ }
704
+
705
+ /**
706
+ * The complete create-time refusal reason for a compressed format, or null.
707
+ * Feature absence is checked before the descriptor shape, matching the plan's
708
+ * order, and the caller prefixes the public texture name.
709
+ *
710
+ * @param {string | number} format
711
+ * @param {Dimension | string} dimension
712
+ * @param {Extent} size
713
+ * @param {Set<string> | { has(f: string): boolean }} features
714
+ * @returns {string | null}
715
+ */
716
+ export function formatCreationRefusal(format, dimension, size, features) {
717
+ const missing = missingFormatFeature(format, dimension, features);
718
+ if (missing !== null) {
719
+ return `format '${format}' requires '${missing}'; this adapter does not support it`;
720
+ }
721
+ const refusal = formatDescriptorRefusal(format, dimension, size);
722
+ if (refusal === null) return null;
723
+ if (refusal.field === "format") return `format '${format}' cannot be ${dimension}`;
724
+ const block = compressedFacts(format);
725
+ if (block === null) return null;
726
+ return `format '${format}' size ${size.width}x${size.height} is not a multiple of its ${block.blockWidth}x${block.blockHeight} texel block`;
727
+ }
728
+
729
+ /**
730
+ * The creation-side compressed descriptor rule, device-independent: 1D is
731
+ * never compressed, a 3D descriptor needs a sliced-3d family, and the BASE
732
+ * width/height must be whole texel blocks. This tranche does not request
733
+ * `texture-compression-unaligned`, so the strict rule is the contract's rule.
734
+ *
735
+ * @param {string | number} format
736
+ * @param {Dimension | string} dimension
737
+ * @param {Extent} size
738
+ * @returns {Refusal | null}
739
+ */
740
+ export function formatDescriptorRefusal(format, dimension, size) {
741
+ const row = compressedFacts(format);
742
+ if (row === null) return null;
743
+ if (dimension === "1d") {
744
+ return refusal("invalid-texture-descriptor", "format", row.byte, 0);
745
+ }
746
+ if (dimension === "3d" && !row.sliced3d) {
747
+ return refusal("invalid-texture-descriptor", "format", row.byte, 0);
748
+ }
749
+ if (size.width % row.blockWidth !== 0) {
750
+ return refusal("invalid-texture-descriptor", "size-width", size.width, row.blockWidth);
751
+ }
752
+ if (size.height % row.blockHeight !== 0) {
753
+ return refusal("invalid-texture-descriptor", "size-height", size.height, row.blockHeight);
754
+ }
755
+ return null;
756
+ }
757
+
758
+ /**
759
+ * WebGPU's `maximum mipLevel count`: floor(log2(maxDimension)) + 1, with 1D
760
+ * fixed at one level. `Math.clz32` gives the same bit length for a u32.
761
+ *
762
+ * @param {Dimension} dimension
763
+ * @param {Extent} size
764
+ * @returns {number}
765
+ */
766
+ function maximumMipLevelCount(dimension, size) {
767
+ if (dimension === "1d") return 1;
768
+ const maxDimension =
769
+ dimension === "2d"
770
+ ? Math.max(size.width, size.height)
771
+ : Math.max(size.width, size.height, size.depthOrArrayLayers);
772
+ return 32 - Math.clz32(maxDimension);
773
+ }
774
+
775
+ /**
776
+ * Logical and physical (block-rounded) extents at `mipLevel` for a concrete
777
+ * base size. 2D array layers are not reduced by the mip; 3D depth is. Every
778
+ * division is a shift after proving the index is below 32, and rounding is
779
+ * computed in Number space only after the operands are proven safe integers.
780
+ *
781
+ * @param {ExtentInput} size
782
+ * @param {Dimension | string} dimension
783
+ * @param {number} mipLevel
784
+ * @param {number} blockWidth
785
+ * @param {number} blockHeight
786
+ * @returns {MipExtentResult}
787
+ */
788
+ export function mipExtent(size, dimension, mipLevel, blockWidth, blockHeight) {
789
+ const extent = readExtent(size);
790
+ if ("refuse" in extent) return { refuse: extent.refuse };
791
+ const base = extent.value;
792
+
793
+ if (dimension !== "1d" && dimension !== "2d" && dimension !== "3d") {
794
+ return { refuse: refusal("invalid-texture-descriptor", "dimension") };
795
+ }
796
+ // `blockWidth`/`blockHeight` are format facts: without a usable block there
797
+ // is no format row to resolve, matching `invalid-format`.
798
+ if (
799
+ !Number.isSafeInteger(blockWidth) ||
800
+ !Number.isSafeInteger(blockHeight) ||
801
+ blockWidth <= 0 ||
802
+ blockHeight <= 0 ||
803
+ blockWidth > U32_MAX ||
804
+ blockHeight > U32_MAX
805
+ ) {
806
+ return { refuse: refusal("invalid-format", "format") };
807
+ }
808
+
809
+ const level = readBounded("mip-level", mipLevel, U32_MAX);
810
+ if ("refuse" in level) return { refuse: level.refuse };
811
+ if (level.value >= 32) {
812
+ return {
813
+ refuse: refusal("mip-out-of-range", "mip-level", level.value, 32),
814
+ };
815
+ }
816
+
817
+ /** @type {Extent} */
818
+ let logical;
819
+ switch (dimension) {
820
+ case "1d":
821
+ logical = {
822
+ width: Math.max(1, base.width >>> level.value),
823
+ height: 1,
824
+ depthOrArrayLayers: 1,
825
+ };
826
+ break;
827
+ case "3d":
828
+ logical = {
829
+ width: Math.max(1, base.width >>> level.value),
830
+ height: Math.max(1, base.height >>> level.value),
831
+ depthOrArrayLayers: Math.max(1, base.depthOrArrayLayers >>> level.value),
832
+ };
833
+ break;
834
+ default:
835
+ logical = {
836
+ width: Math.max(1, base.width >>> level.value),
837
+ height: Math.max(1, base.height >>> level.value),
838
+ depthOrArrayLayers: base.depthOrArrayLayers,
839
+ };
840
+ break;
841
+ }
842
+
843
+ // Round the logical axes up to whole texel blocks with exact integer
844
+ // remainder arithmetic; the +block sum is at most 2^33, which Number
845
+ // carries exactly. Avoid floating division here so no rounding mode can
846
+ // change the rounded extent.
847
+ const widthRemainder = logical.width % blockWidth;
848
+ const paddedWidth =
849
+ widthRemainder === 0 ? logical.width : logical.width + (blockWidth - widthRemainder);
850
+ if (paddedWidth > U32_MAX) {
851
+ return {
852
+ refuse: refusal("arithmetic-overflow", "size-width", paddedWidth, U32_MAX),
853
+ };
854
+ }
855
+ /** @type {number} */
856
+ let physicalHeight = 1;
857
+ if (dimension !== "1d") {
858
+ const heightRemainder = logical.height % blockHeight;
859
+ const paddedHeight =
860
+ heightRemainder === 0
861
+ ? logical.height
862
+ : logical.height + (blockHeight - heightRemainder);
863
+ if (paddedHeight > U32_MAX) {
864
+ return {
865
+ refuse: refusal("arithmetic-overflow", "size-height", paddedHeight, U32_MAX),
866
+ };
867
+ }
868
+ physicalHeight = paddedHeight;
869
+ }
870
+
871
+ return {
872
+ ok: {
873
+ logical,
874
+ physical: {
875
+ width: paddedWidth,
876
+ height: physicalHeight,
877
+ depthOrArrayLayers: logical.depthOrArrayLayers,
878
+ },
879
+ },
880
+ };
881
+ }
882
+
883
+ /**
884
+ * @param {unknown} descriptor
885
+ * @returns {{ value: TextureDescriptorInput } | { refuse: Refusal }}
886
+ */
887
+ function normalizeDescriptor(descriptor) {
888
+ if (descriptor === null || typeof descriptor !== "object") {
889
+ return { refuse: refusal("invalid-texture-descriptor", "none") };
890
+ }
891
+ const source = /** @type {TextureDescriptorInput} */ (descriptor);
892
+ const size = readExtent(source.size);
893
+ if ("refuse" in size) return { refuse: size.refuse };
894
+ if (
895
+ source.dimension !== "1d" &&
896
+ source.dimension !== "2d" &&
897
+ source.dimension !== "3d"
898
+ ) {
899
+ return { refuse: refusal("invalid-texture-descriptor", "dimension") };
900
+ }
901
+ return {
902
+ value: {
903
+ size: size.value,
904
+ dimension: source.dimension,
905
+ format: source.format,
906
+ usage: source.usage,
907
+ sampleCount: source.sampleCount,
908
+ mipLevelCount: source.mipLevelCount,
909
+ extentSource: source.extentSource,
910
+ },
911
+ };
912
+ }
913
+
914
+ /**
915
+ * @param {TextureDescriptorInput} descriptor
916
+ * @returns {Refusal | null}
917
+ */
918
+ function validateDescriptor(descriptor) {
919
+ const size = /** @type {Extent} */ (descriptor.size);
920
+ if (size.width === 0) {
921
+ return refusal("invalid-texture-descriptor", "size-width", 0, 1);
922
+ }
923
+ if (size.height === 0) {
924
+ return refusal("invalid-texture-descriptor", "size-height", 0, 1);
925
+ }
926
+ if (size.depthOrArrayLayers === 0) {
927
+ return refusal("invalid-texture-descriptor", "size-depth-or-array-layers", 0, 1);
928
+ }
929
+
930
+ const mipCount = readBounded("mip-level-count", descriptor.mipLevelCount, U32_MAX);
931
+ if ("refuse" in mipCount) return mipCount.refuse;
932
+ if (mipCount.value === 0) {
933
+ return refusal("invalid-texture-descriptor", "mip-level-count", 0, 1);
934
+ }
935
+
936
+ const dimension = /** @type {Dimension} */ (descriptor.dimension);
937
+ if (dimension === "1d") {
938
+ if (size.height !== 1) {
939
+ return refusal("invalid-texture-descriptor", "size-height", size.height, 1);
940
+ }
941
+ if (size.depthOrArrayLayers !== 1) {
942
+ return refusal(
943
+ "invalid-texture-descriptor",
944
+ "size-depth-or-array-layers",
945
+ size.depthOrArrayLayers,
946
+ 1,
947
+ );
948
+ }
949
+ }
950
+
951
+ const maxMips = maximumMipLevelCount(dimension, size);
952
+ if (mipCount.value > maxMips) {
953
+ return refusal(
954
+ "invalid-texture-descriptor",
955
+ "mip-level-count",
956
+ mipCount.value,
957
+ maxMips,
958
+ );
959
+ }
960
+
961
+ // Compressed creation rules before the ordinary format/dimension rules:
962
+ // 1D is never compressed, 3D needs a sliced-3d family, and the base extent
963
+ // is block-aligned.
964
+ const compressed = formatDescriptorRefusal(descriptor.format, dimension, size);
965
+ if (compressed !== null) return compressed;
966
+
967
+ // Plain colour formats support 1D, 2D and 3D; depth/stencil formats do not
968
+ // support 1D or 3D. Unknown formats fall through to `formatInfo`.
969
+ const row = resolveFormat(descriptor.format);
970
+ if (
971
+ row !== null &&
972
+ (row.hasDepth || row.hasStencil) &&
973
+ (dimension === "1d" || dimension === "3d")
974
+ ) {
975
+ return refusal("invalid-texture-descriptor", "format", row.byte, 0);
976
+ }
977
+ return null;
978
+ }
979
+
980
+ /**
981
+ * The texture half of WebGPU's `validating texture buffer copy`: the texture
982
+ * endpoint must carry the usage bit the copy direction requires (COPY_DST for
983
+ * a destination, COPY_SRC for a source) and exactly one sample. Usage is the
984
+ * outer check, so a texture that is the wrong endpoint never reaches aspect
985
+ * parsing. `actual` is the usage byte (or sample count); `limit` is the
986
+ * required usage bit (or 1).
987
+ *
988
+ * @param {TextureDescriptorInput} descriptor
989
+ * @param {CopyPolicyValue} policy
990
+ * @returns {Refusal | null}
991
+ */
992
+ function textureEndpointRefusal(descriptor, policy) {
993
+ const usage = readBounded("usage", descriptor.usage, 0xff);
994
+ if ("refuse" in usage) return usage.refuse;
995
+ const isSource = policy.direction === "texture-to-buffer";
996
+ const required = isSource ? 1 : 2;
997
+ if ((usage.value & required) === 0) {
998
+ return refusal(
999
+ isSource ? "missing-copy-src" : "missing-copy-dst",
1000
+ "usage",
1001
+ usage.value,
1002
+ required,
1003
+ );
1004
+ }
1005
+ const sampleCount = readBounded("sample-count", descriptor.sampleCount, U32_MAX);
1006
+ if ("refuse" in sampleCount) return sampleCount.refuse;
1007
+ if (sampleCount.value !== 1) {
1008
+ return refusal("multisampled-destination", "sample-count", sampleCount.value, 1);
1009
+ }
1010
+ return null;
1011
+ }
1012
+
1013
+ /**
1014
+ * @param {Origin} origin
1015
+ * @param {Extent} physical
1016
+ * @returns {Refusal | null}
1017
+ */
1018
+ function originRefusal(origin, physical) {
1019
+ if (origin.x > physical.width) {
1020
+ return refusal("origin-out-of-bounds", "origin-x", origin.x, physical.width);
1021
+ }
1022
+ if (origin.y > physical.height) {
1023
+ return refusal("origin-out-of-bounds", "origin-y", origin.y, physical.height);
1024
+ }
1025
+ if (origin.z > physical.depthOrArrayLayers) {
1026
+ return refusal(
1027
+ "origin-out-of-bounds",
1028
+ "origin-z",
1029
+ origin.z,
1030
+ physical.depthOrArrayLayers,
1031
+ );
1032
+ }
1033
+ return null;
1034
+ }
1035
+
1036
+ /**
1037
+ * WebGPU requires a depth/stencil texel copy to cover the full physical
1038
+ * subresource: the copy extent must equal the physical mip extent, which also
1039
+ * forces every origin component to zero. A reduced extent or a nonzero origin
1040
+ * is a partial write, named per axis in x, y, z, width, height, depth order.
1041
+ *
1042
+ * @param {Origin} origin
1043
+ * @param {Extent} copy
1044
+ * @param {Extent} physical
1045
+ * @param {Code} [code] - the path's code; a texture→texture copy names
1046
+ * `partial-subresource-copy` because it also covers multisampled endpoints.
1047
+ * @returns {Refusal | null}
1048
+ */
1049
+ function fullSubresourceRefusal(origin, copy, physical, code = "partial-depth-stencil-write") {
1050
+ if (origin.x !== 0) {
1051
+ return refusal(code, "origin-x", origin.x, 0);
1052
+ }
1053
+ if (origin.y !== 0) {
1054
+ return refusal(code, "origin-y", origin.y, 0);
1055
+ }
1056
+ if (origin.z !== 0) {
1057
+ return refusal(code, "origin-z", origin.z, 0);
1058
+ }
1059
+ if (copy.width !== physical.width) {
1060
+ return refusal(code, "size-width", copy.width, physical.width);
1061
+ }
1062
+ if (copy.height !== physical.height) {
1063
+ return refusal(code, "size-height", copy.height, physical.height);
1064
+ }
1065
+ if (copy.depthOrArrayLayers !== physical.depthOrArrayLayers) {
1066
+ return refusal(
1067
+ code,
1068
+ "size-depth-or-array-layers",
1069
+ copy.depthOrArrayLayers,
1070
+ physical.depthOrArrayLayers,
1071
+ );
1072
+ }
1073
+ return null;
1074
+ }
1075
+
1076
+ /**
1077
+ * Default an omitted size to the remaining physical extent at the origin, or
1078
+ * prove an explicit size fits. A sum of two u32 values is at most 2^33, which
1079
+ * Number carries exactly, so no wrapping can occur here.
1080
+ *
1081
+ * @param {Extent} physical
1082
+ * @param {Origin} origin
1083
+ * @param {WriteLayoutInput} write
1084
+ * @returns {{ value: Extent } | { refuse: Refusal }}
1085
+ */
1086
+ function resolveCopyExtent(physical, origin, write) {
1087
+ if (write.size !== undefined && write.size !== null) {
1088
+ const size = readExtent(write.size);
1089
+ if ("refuse" in size) return size;
1090
+ const endX = origin.x + size.value.width;
1091
+ if (endX > physical.width) {
1092
+ return {
1093
+ refuse: refusal("extent-out-of-bounds", "size-width", endX, physical.width),
1094
+ };
1095
+ }
1096
+ const endY = origin.y + size.value.height;
1097
+ if (endY > physical.height) {
1098
+ return {
1099
+ refuse: refusal("extent-out-of-bounds", "size-height", endY, physical.height),
1100
+ };
1101
+ }
1102
+ const endZ = origin.z + size.value.depthOrArrayLayers;
1103
+ if (endZ > physical.depthOrArrayLayers) {
1104
+ return {
1105
+ refuse: refusal(
1106
+ "extent-out-of-bounds",
1107
+ "size-depth-or-array-layers",
1108
+ endZ,
1109
+ physical.depthOrArrayLayers,
1110
+ ),
1111
+ };
1112
+ }
1113
+ return { value: size.value };
1114
+ }
1115
+ return {
1116
+ value: {
1117
+ width: physical.width - origin.x,
1118
+ height: physical.height - origin.y,
1119
+ depthOrArrayLayers: physical.depthOrArrayLayers - origin.z,
1120
+ },
1121
+ };
1122
+ }
1123
+
1124
+ /**
1125
+ * Check a copy origin and extent against a format's texel-block dimensions.
1126
+ * Plan 01 has no block larger than 1x1, so `calculateWrite` always passes; the
1127
+ * pure rule exists for plan 07's compressed rows.
1128
+ *
1129
+ * @param {Origin} origin
1130
+ * @param {Extent} size
1131
+ * @param {number} blockWidth
1132
+ * @param {number} blockHeight
1133
+ * @returns {Refusal | null}
1134
+ */
1135
+ function blockAlignmentRefusal(origin, size, blockWidth, blockHeight) {
1136
+ if (origin.x % blockWidth !== 0) {
1137
+ return refusal("unaligned-block-origin", "origin-x", origin.x, blockWidth);
1138
+ }
1139
+ if (origin.y % blockHeight !== 0) {
1140
+ return refusal("unaligned-block-origin", "origin-y", origin.y, blockHeight);
1141
+ }
1142
+ if (size.width % blockWidth !== 0) {
1143
+ return refusal("unaligned-block-extent", "size-width", size.width, blockWidth);
1144
+ }
1145
+ if (size.height % blockHeight !== 0) {
1146
+ return refusal("unaligned-block-extent", "size-height", size.height, blockHeight);
1147
+ }
1148
+ return null;
1149
+ }
1150
+
1151
+ /**
1152
+ * The two buffer-copy alignment rules, applied only under the aligned policy.
1153
+ * `validating GPUTexelCopyBufferInfo` requires a supplied `bytesPerRow` to be
1154
+ * a multiple of 256; `validating texture buffer copy` requires the buffer
1155
+ * offset to be a multiple of the texel block copy footprint, except that a
1156
+ * depth-stencil texture endpoint — source or destination — sets it to 4.
1157
+ * `writeTexture` passes `aligned = false` and acquires neither.
1158
+ *
1159
+ * @param {WriteLayoutInput} write
1160
+ * @param {FormatInfo} info
1161
+ * @returns {Refusal | null}
1162
+ */
1163
+ function copyAlignmentRefusal(write, info) {
1164
+ if (write.bytesPerRow !== undefined && write.bytesPerRow !== null) {
1165
+ const supplied = readBounded("bytes-per-row", write.bytesPerRow, U32_MAX);
1166
+ if ("refuse" in supplied) return supplied.refuse;
1167
+ if (supplied.value % 256 !== 0) {
1168
+ return refusal(
1169
+ "bytes-per-row-alignment",
1170
+ "bytes-per-row",
1171
+ supplied.value,
1172
+ 256,
1173
+ );
1174
+ }
1175
+ }
1176
+
1177
+ const offsetAlignment =
1178
+ info.hasDepth || info.hasStencil ? 4 : info.bytesPerBlock;
1179
+ // `formatInfo` never exposes a zero footprint, but keep the rule total.
1180
+ if (offsetAlignment === 0) return refusal("invalid-format", "format");
1181
+ const offset = readBounded("offset", write.offset ?? 0, U32_MAX);
1182
+ if ("refuse" in offset) return offset.refuse;
1183
+ if (offset.value % offsetAlignment !== 0) {
1184
+ return refusal(
1185
+ "buffer-offset-alignment",
1186
+ "offset",
1187
+ offset.value,
1188
+ offsetAlignment,
1189
+ );
1190
+ }
1191
+ return null;
1192
+ }
1193
+
1194
+ /**
1195
+ * Multiply two nonnegative values, proving the exact product is a safe
1196
+ * integer BEFORE the multiplication and a legal returned u32 after it. A
1197
+ * Number product outside the safe range would otherwise round silently.
1198
+ *
1199
+ * When the exact product is beyond `Number.MAX_SAFE_INTEGER`, the refusal
1200
+ * reports `actual = Number.MAX_SAFE_INTEGER`; JS cannot carry the exact u64
1201
+ * the Zig binding would report. The code, field and limit are identical.
1202
+ *
1203
+ * @param {Field} field
1204
+ * @param {number} a
1205
+ * @param {number} b
1206
+ * @returns {CheckedValue}
1207
+ */
1208
+ function checkedMul(field, a, b) {
1209
+ if (a !== 0 && b > Math.floor(MAX_SAFE / a)) {
1210
+ return { refuse: refusal("arithmetic-overflow", field, MAX_SAFE, U32_MAX) };
1211
+ }
1212
+ const product = a * b;
1213
+ if (product > U32_MAX) {
1214
+ return { refuse: refusal("arithmetic-overflow", field, product, U32_MAX) };
1215
+ }
1216
+ return { value: product };
1217
+ }
1218
+
1219
+ /**
1220
+ * Add two nonnegative values, proving the exact sum is a safe integer BEFORE
1221
+ * the addition and a legal returned u32 after it.
1222
+ *
1223
+ * @param {Field} field
1224
+ * @param {number} a
1225
+ * @param {number} b
1226
+ * @returns {CheckedValue}
1227
+ */
1228
+ function checkedAdd(field, a, b) {
1229
+ if (a > MAX_SAFE - b) {
1230
+ return { refuse: refusal("arithmetic-overflow", field, MAX_SAFE, U32_MAX) };
1231
+ }
1232
+ const sum = a + b;
1233
+ if (sum > U32_MAX) {
1234
+ return { refuse: refusal("arithmetic-overflow", field, sum, U32_MAX) };
1235
+ }
1236
+ return { value: sum };
1237
+ }
1238
+
1239
+ /**
1240
+ * @typedef {{
1241
+ * widthInBlocks: number,
1242
+ * heightInBlocks: number,
1243
+ * bytesInLastRow: number,
1244
+ * bytesPerRow: number,
1245
+ * rowsPerImage: number,
1246
+ * imageStride: number,
1247
+ * requiredBytesInCopy: number,
1248
+ * endOffset: number,
1249
+ * }} LinearLayout
1250
+ * @typedef {{ value: LinearLayout } | { refuse: Refusal }} LinearResult
1251
+ */
1252
+
1253
+ /**
1254
+ * The arithmetic specification's steps 5-9: block counts, stride presence and
1255
+ * minima, normalized strides, the required span with final-row and
1256
+ * final-image padding excluded, and the offset-inclusive end. Every product
1257
+ * and sum is checked and must fit u32 before it becomes a returned value.
1258
+ *
1259
+ * @param {WriteLayoutInput} write
1260
+ * @param {Extent} copy
1261
+ * @param {FormatInfo} info
1262
+ * @returns {LinearResult}
1263
+ */
1264
+ function resolveLinearLayout(write, copy, info) {
1265
+ const widthInBlocks = Math.trunc(copy.width / info.blockWidth);
1266
+ const heightInBlocks = Math.trunc(copy.height / info.blockHeight);
1267
+
1268
+ const bytesInLastRow = checkedMul("size-width", widthInBlocks, info.bytesPerBlock);
1269
+ if ("refuse" in bytesInLastRow) return { refuse: bytesInLastRow.refuse };
1270
+
1271
+ const depth = copy.depthOrArrayLayers;
1272
+ const bytesPerRowPresent =
1273
+ write.bytesPerRow !== undefined && write.bytesPerRow !== null;
1274
+ const rowsPerImagePresent =
1275
+ write.rowsPerImage !== undefined && write.rowsPerImage !== null;
1276
+
1277
+ // Presence is decided before any value is read, exactly like Zig's `?u32`.
1278
+ if ((heightInBlocks > 1 || depth > 1) && !bytesPerRowPresent) {
1279
+ return {
1280
+ refuse: refusal("missing-bytes-per-row", "bytes-per-row", 0, bytesInLastRow.value),
1281
+ };
1282
+ }
1283
+ if (depth > 1 && !rowsPerImagePresent) {
1284
+ return {
1285
+ refuse: refusal("missing-rows-per-image", "rows-per-image", 0, heightInBlocks),
1286
+ };
1287
+ }
1288
+
1289
+ const bytesPerRow = readOptionalU32("bytes-per-row", write.bytesPerRow);
1290
+ const rowsPerImage = readOptionalU32("rows-per-image", write.rowsPerImage);
1291
+ if ("refuse" in bytesPerRow) return { refuse: bytesPerRow.refuse };
1292
+ if ("refuse" in rowsPerImage) return { refuse: rowsPerImage.refuse };
1293
+
1294
+ // Supplied minima apply even when the field was not required.
1295
+ if (bytesPerRow.present && bytesPerRow.value < bytesInLastRow.value) {
1296
+ return {
1297
+ refuse: refusal(
1298
+ "bytes-per-row-too-small",
1299
+ "bytes-per-row",
1300
+ bytesPerRow.value,
1301
+ bytesInLastRow.value,
1302
+ ),
1303
+ };
1304
+ }
1305
+ if (rowsPerImage.present && rowsPerImage.value < heightInBlocks) {
1306
+ return {
1307
+ refuse: refusal(
1308
+ "rows-per-image-too-small",
1309
+ "rows-per-image",
1310
+ rowsPerImage.value,
1311
+ heightInBlocks,
1312
+ ),
1313
+ };
1314
+ }
1315
+
1316
+ // Presence is decided above; only now may an omitted stride take its
1317
+ // normalized minimum. An authored zero never becomes a minimum.
1318
+ const normalizedBytesPerRow = bytesPerRow.present
1319
+ ? bytesPerRow.value
1320
+ : bytesInLastRow.value;
1321
+ const normalizedRowsPerImage = rowsPerImage.present
1322
+ ? rowsPerImage.value
1323
+ : heightInBlocks;
1324
+ const imageStride = checkedMul(
1325
+ "bytes-per-row",
1326
+ normalizedBytesPerRow,
1327
+ normalizedRowsPerImage,
1328
+ );
1329
+ if ("refuse" in imageStride) return { refuse: imageStride.refuse };
1330
+
1331
+ let requiredBytes = 0;
1332
+ if (depth > 0) {
1333
+ // One full image stride per gap before the final image. This term exists
1334
+ // even when the copy height is zero.
1335
+ const imageGap = checkedMul(
1336
+ "size-depth-or-array-layers",
1337
+ imageStride.value,
1338
+ depth - 1,
1339
+ );
1340
+ if ("refuse" in imageGap) return { refuse: imageGap.refuse };
1341
+ const withGap = checkedAdd("data", requiredBytes, imageGap.value);
1342
+ if ("refuse" in withGap) return { refuse: withGap.refuse };
1343
+ requiredBytes = withGap.value;
1344
+
1345
+ if (heightInBlocks > 0) {
1346
+ // The final row contributes bytesInLastRow, never a full stride.
1347
+ const rowGap = checkedMul(
1348
+ "bytes-per-row",
1349
+ normalizedBytesPerRow,
1350
+ heightInBlocks - 1,
1351
+ );
1352
+ if ("refuse" in rowGap) return { refuse: rowGap.refuse };
1353
+ const rowsAndLast = checkedAdd(
1354
+ "bytes-per-row",
1355
+ rowGap.value,
1356
+ bytesInLastRow.value,
1357
+ );
1358
+ if ("refuse" in rowsAndLast) return { refuse: rowsAndLast.refuse };
1359
+ const withRows = checkedAdd("data", requiredBytes, rowsAndLast.value);
1360
+ if ("refuse" in withRows) return { refuse: withRows.refuse };
1361
+ requiredBytes = withRows.value;
1362
+ }
1363
+ }
1364
+
1365
+ // `offset` is counted once, outside the span.
1366
+ const offset = readBounded("offset", write.offset ?? 0, U32_MAX);
1367
+ if ("refuse" in offset) return { refuse: offset.refuse };
1368
+ const endOffset = checkedAdd("offset", offset.value, requiredBytes);
1369
+ if ("refuse" in endOffset) return { refuse: endOffset.refuse };
1370
+
1371
+ return {
1372
+ value: {
1373
+ widthInBlocks,
1374
+ heightInBlocks,
1375
+ bytesInLastRow: bytesInLastRow.value,
1376
+ bytesPerRow: normalizedBytesPerRow,
1377
+ rowsPerImage: normalizedRowsPerImage,
1378
+ imageStride: imageStride.value,
1379
+ requiredBytesInCopy: requiredBytes,
1380
+ endOffset: endOffset.value,
1381
+ },
1382
+ };
1383
+ }
1384
+
1385
+ /**
1386
+ * The shared texel-copy calculator. Stages, in order, so the first refusal is
1387
+ * stable and identical to the Zig binding: descriptor, the texture endpoint's
1388
+ * usage/sample count for the policy's direction, format/aspect, mip range, mip
1389
+ * extent, origin, default/explicit copy extent and range, depth/stencil full
1390
+ * subresource, block alignment, the policy's buffer-copy alignment, then the
1391
+ * linear-data rules (stride presence and minima, normalized strides, required
1392
+ * span, source/buffer length). A short aligned buffer reports
1393
+ * `buffer-out-of-bounds`; the queue write keeps plan 01's `insufficient-data`.
1394
+ *
1395
+ * `descriptor` and `write` use the shared corpus's camelCase object shapes.
1396
+ * `bytesPerRow`, `rowsPerImage` and `size` are optional; absence is
1397
+ * `undefined`/`null` and is never treated as an authored zero.
1398
+ *
1399
+ * `policy` is REQUIRED and must be one of the `CopyPolicy` identity constants:
1400
+ * a missing policy is a caller-shape error, never a silent queue write.
1401
+ *
1402
+ * @param {TextureDescriptorInput} descriptor
1403
+ * @param {WriteLayoutInput} write
1404
+ * @param {number} dataLength
1405
+ * @param {CopyPolicyValue} policy
1406
+ * @returns {Result}
1407
+ */
1408
+ export function calculateCopy(
1409
+ descriptor,
1410
+ write,
1411
+ dataLength,
1412
+ policy,
1413
+ ) {
1414
+ if (
1415
+ policy !== CopyPolicy.queueWrite &&
1416
+ policy !== CopyPolicy.bufferToTexture &&
1417
+ policy !== CopyPolicy.textureToBuffer
1418
+ ) {
1419
+ throw new TypeError(
1420
+ "copy policy must be CopyPolicy.queueWrite, CopyPolicy.bufferToTexture or CopyPolicy.textureToBuffer",
1421
+ );
1422
+ }
1423
+ const aligned = policy.aligned;
1424
+
1425
+ const writable =
1426
+ write !== null && typeof write === "object" ? write : {};
1427
+
1428
+ const normalized = normalizeDescriptor(descriptor);
1429
+ if ("refuse" in normalized) return { refuse: normalized.refuse };
1430
+ const descriptorValue = normalized.value;
1431
+
1432
+ const descriptorRefusal = validateDescriptor(descriptorValue);
1433
+ if (descriptorRefusal !== null) return { refuse: descriptorRefusal };
1434
+
1435
+ const endpoint = textureEndpointRefusal(descriptorValue, policy);
1436
+ if (endpoint !== null) return { refuse: endpoint };
1437
+
1438
+ const infoResult = formatInfo(descriptorValue.format, writable.aspect);
1439
+ if ("refuse" in infoResult) return { refuse: infoResult.refuse };
1440
+ const info = infoResult.ok;
1441
+
1442
+ const mipLevel = readBounded("mip-level", writable.mipLevel ?? 0, U32_MAX);
1443
+ if ("refuse" in mipLevel) return { refuse: mipLevel.refuse };
1444
+ const mipCount = /** @type {number} */ (descriptorValue.mipLevelCount);
1445
+ if (mipLevel.value >= mipCount) {
1446
+ return {
1447
+ refuse: refusal("mip-out-of-range", "mip-level", mipLevel.value, mipCount),
1448
+ };
1449
+ }
1450
+
1451
+ const mip = mipExtent(
1452
+ /** @type {Extent} */ (descriptorValue.size),
1453
+ /** @type {Dimension} */ (descriptorValue.dimension),
1454
+ mipLevel.value,
1455
+ info.blockWidth,
1456
+ info.blockHeight,
1457
+ );
1458
+ if ("refuse" in mip) return { refuse: mip.refuse };
1459
+
1460
+ const originRead = readOrigin(writable.origin);
1461
+ if ("refuse" in originRead) return { refuse: originRead.refuse };
1462
+ const origin = originRead.value;
1463
+
1464
+ const physical = mip.ok.physical;
1465
+
1466
+ const originProblem = originRefusal(origin, physical);
1467
+ if (originProblem !== null) return { refuse: originProblem };
1468
+
1469
+ const copyResult = resolveCopyExtent(physical, origin, writable);
1470
+ if ("refuse" in copyResult) return { refuse: copyResult.refuse };
1471
+ const copy = copyResult.value;
1472
+
1473
+ // The CRD's range stage requires depth/stencil copies to cover the full
1474
+ // physical subresource; a subregion or nonzero origin is never a partial
1475
+ // aspect write. Plain colour formats keep their subregions.
1476
+ if (info.hasDepth || info.hasStencil) {
1477
+ const partial = fullSubresourceRefusal(origin, copy, physical);
1478
+ if (partial !== null) return { refuse: partial };
1479
+ }
1480
+
1481
+ const blockProblem = blockAlignmentRefusal(
1482
+ origin,
1483
+ copy,
1484
+ info.blockWidth,
1485
+ info.blockHeight,
1486
+ );
1487
+ if (blockProblem !== null) return { refuse: blockProblem };
1488
+
1489
+ if (aligned) {
1490
+ const alignmentProblem = copyAlignmentRefusal(writable, info);
1491
+ if (alignmentProblem !== null) return { refuse: alignmentProblem };
1492
+ }
1493
+
1494
+ const linear = resolveLinearLayout(writable, copy, info);
1495
+ if ("refuse" in linear) return { refuse: linear.refuse };
1496
+
1497
+ const source = readBounded("data", dataLength, MAX_SAFE);
1498
+ if ("refuse" in source) return { refuse: source.refuse };
1499
+
1500
+ if (linear.value.endOffset > source.value) {
1501
+ return {
1502
+ refuse: refusal(
1503
+ aligned ? "buffer-out-of-bounds" : "insufficient-data",
1504
+ "data",
1505
+ linear.value.endOffset,
1506
+ source.value,
1507
+ ),
1508
+ };
1509
+ }
1510
+
1511
+ return {
1512
+ ok: {
1513
+ logicalMipExtent: mip.ok.logical,
1514
+ physicalMipExtent: physical,
1515
+ copyExtent: copy,
1516
+ widthInBlocks: linear.value.widthInBlocks,
1517
+ heightInBlocks: linear.value.heightInBlocks,
1518
+ bytesInLastRow: linear.value.bytesInLastRow,
1519
+ bytesPerRow: linear.value.bytesPerRow,
1520
+ rowsPerImage: linear.value.rowsPerImage,
1521
+ imageStride: linear.value.imageStride,
1522
+ requiredBytesInCopy: linear.value.requiredBytesInCopy,
1523
+ endOffset: linear.value.endOffset,
1524
+ },
1525
+ };
1526
+ }
1527
+
1528
+ /**
1529
+ * `GPUQueue.writeTexture`'s calculator: plan 01 exactly, with the aligned
1530
+ * policy's two buffer-copy rules permanently off.
1531
+ *
1532
+ * @param {TextureDescriptorInput} descriptor
1533
+ * @param {WriteLayoutInput} write
1534
+ * @param {number} dataLength
1535
+ * @returns {Result}
1536
+ */
1537
+ export function calculateWrite(descriptor, write, dataLength) {
1538
+ return calculateCopy(descriptor, write, dataLength, CopyPolicy.queueWrite);
1539
+ }
1540
+
1541
+ // ── texture→texture subresource copies (plan 06) ─────────────────────────────
1542
+
1543
+ /**
1544
+ * @typedef {{ textureId: number, mipLevel?: number, origin?: OriginInput,
1545
+ * aspect?: AspectName | number | string }} SubresourceEndpointInput
1546
+ * @typedef {{ source: SubresourceEndpointInput, destination: SubresourceEndpointInput,
1547
+ * size?: ExtentInput | null }} SubresourceCopyInput
1548
+ * @typedef {{ mip: MipExtent, copyExtent: Extent }} EndpointLayout
1549
+ * @typedef {{ ok: { source: EndpointLayout, destination: EndpointLayout,
1550
+ * copyExtent: Extent } } | { refuse: Refusal }} SubresourceCopyResult
1551
+ */
1552
+
1553
+ /**
1554
+ * A format's texel-block size, independent of aspect. `null` for a sentinel or
1555
+ * an unknown format byte — the copy refuses rather than inventing a footprint.
1556
+ * @param {string | number} format
1557
+ * @returns {{ width: number, height: number } | null}
1558
+ */
1559
+ function copyBlock(format) {
1560
+ const row = resolveFormat(format);
1561
+ if (row !== null) return { width: row.blockWidth, height: row.blockHeight };
1562
+ const compressed = compressedFacts(format);
1563
+ return compressed === null
1564
+ ? null
1565
+ : { width: compressed.blockWidth, height: compressed.blockHeight };
1566
+ }
1567
+
1568
+ /**
1569
+ * @param {string | number} format
1570
+ * @returns {boolean}
1571
+ */
1572
+ function formatHasDepthOrStencil(format) {
1573
+ const row = resolveFormat(format);
1574
+ return row !== null && (row.hasDepth || row.hasStencil);
1575
+ }
1576
+
1577
+ /**
1578
+ * `copyTextureToTexture`'s aspect rule: both endpoints carry `all`. For a
1579
+ * depth-stencil format that means all aspects on both sides (CRD
1580
+ * `index.bs:11192-11195`) — deliberately the opposite of plan 02's write path,
1581
+ * which requires one aspect. A colour format accepts only `all` too.
1582
+ *
1583
+ * @param {string | number} format
1584
+ * @param {AspectName | number | string | null | undefined} aspect
1585
+ * @returns {Refusal | null}
1586
+ */
1587
+ function copyAspectRefusal(format, aspect) {
1588
+ if (resolveFormat(format) === null && compressedFacts(format) === null) {
1589
+ return refusal("invalid-format", "format");
1590
+ }
1591
+ const tag = aspectTag(aspect);
1592
+ if (tag !== 0) return refusal("invalid-aspect", "aspect", tag, 0);
1593
+ return null;
1594
+ }
1595
+
1596
+ /**
1597
+ * WebGPU `copy-compatible`: equal, or equal except for the `-srgb` suffix.
1598
+ * @param {string | number} source
1599
+ * @param {string | number} destination
1600
+ * @returns {boolean}
1601
+ */
1602
+ function copyCompatible(source, destination) {
1603
+ const src = resolveFormat(source);
1604
+ const dst = resolveFormat(destination);
1605
+ if (src === null || dst === null) {
1606
+ // Compressed rows alternate linear then sRGB in adjacent bytes (plan 07's
1607
+ // order), so a pair sharing `byte & 0xfe` is the same format modulo sRGB.
1608
+ const srcCompressed = compressedFacts(source);
1609
+ const dstCompressed = compressedFacts(destination);
1610
+ return srcCompressed !== null && dstCompressed !== null &&
1611
+ srcCompressed.family === dstCompressed.family &&
1612
+ (srcCompressed.byte | 1) === (dstCompressed.byte | 1);
1613
+ }
1614
+ if (src.byte === dst.byte) return true;
1615
+ const sibling = {
1616
+ "rgba8unorm": "rgba8unorm-srgb",
1617
+ "rgba8unorm-srgb": "rgba8unorm",
1618
+ "bgra8unorm": "bgra8unorm-srgb",
1619
+ "bgra8unorm-srgb": "bgra8unorm",
1620
+ };
1621
+ return sibling[src.name] === dst.name;
1622
+ }
1623
+
1624
+ /**
1625
+ * `copyTextureToTexture`'s aspect-COPYABILITY rule, named before any range
1626
+ * arithmetic. Every aspect the format actually has must be copyable on this
1627
+ * side:
1628
+ * - `depth24plus` (and the depth aspect of `depth24plus-stencil8`) has no
1629
+ * copy footprint, so it is never a valid copy source (`invalid-format`);
1630
+ * - `depth32float` (and the depth aspect of `depth32float-stencil8`) is a
1631
+ * valid copy source but not a copy destination (`aspect-not-writable`).
1632
+ * A depth-only aspect on a stencil-only texture, or the reverse, is refused by
1633
+ * `copyAspectRefusal`'s `invalid-aspect` before reaching a footprint lookup.
1634
+ *
1635
+ * @param {string | number} format
1636
+ * @param {"source" | "destination"} role
1637
+ * @returns {Refusal | null}
1638
+ */
1639
+ function copyFormatRefusal(format, role) {
1640
+ const row = resolveFormat(format);
1641
+ if (row === null) {
1642
+ return compressedFacts(format) === null ? refusal("invalid-format", "format") : null;
1643
+ }
1644
+
1645
+ if (row.hasDepth) {
1646
+ if (role === "source") {
1647
+ if (row.depthBytesPerBlock === 0) return refusal("invalid-format", "format");
1648
+ } else if (!row.depthWriteDestination) {
1649
+ return refusal("aspect-not-writable", "aspect");
1650
+ }
1651
+ }
1652
+ if (row.hasStencil) {
1653
+ if (role === "source") {
1654
+ if (row.stencilBytesPerBlock === 0) return refusal("invalid-format", "format");
1655
+ } else if (!row.stencilWriteDestination) {
1656
+ return refusal("aspect-not-writable", "aspect");
1657
+ }
1658
+ }
1659
+ if (!row.hasDepth && !row.hasStencil && row.colorBytesPerBlock === 0) {
1660
+ return refusal("invalid-format", "format");
1661
+ }
1662
+ return null;
1663
+ }
1664
+
1665
+ /**
1666
+ * Resolve one `GPUTexelCopyTextureInfo` against its concrete descriptor:
1667
+ * aspect, mip range, physical mip extent, origin, explicit-or-remaining copy
1668
+ * extent and block alignment. `size === undefined/null` is the source's
1669
+ * omission rule (the remaining physical extent at the origin) and the same
1670
+ * `resolveCopyExtent` plan 01's write/buffer-copy paths use.
1671
+ *
1672
+ * @param {TextureDescriptorInput} descriptor
1673
+ * @param {{ mipLevel: number, origin: Origin, aspect: AspectName | number }} endpoint
1674
+ * @param {ExtentInput | null | undefined} size
1675
+ * @returns {{ ok: EndpointLayout } | { refuse: Refusal }}
1676
+ */
1677
+ function calculateCopyEndpoint(descriptor, endpoint, size) {
1678
+ const descriptorRefusal = validateDescriptor(descriptor);
1679
+ if (descriptorRefusal !== null) return { refuse: descriptorRefusal };
1680
+
1681
+ const block = copyBlock(descriptor.format);
1682
+ if (block === null) return { refuse: refusal("invalid-format", "format") };
1683
+ const aspectProblem = copyAspectRefusal(descriptor.format, endpoint.aspect);
1684
+ if (aspectProblem !== null) return { refuse: aspectProblem };
1685
+ if (endpoint.mipLevel >= descriptor.mipLevelCount) {
1686
+ return {
1687
+ refuse: refusal(
1688
+ "mip-out-of-range",
1689
+ "mip-level",
1690
+ endpoint.mipLevel,
1691
+ descriptor.mipLevelCount,
1692
+ ),
1693
+ };
1694
+ }
1695
+
1696
+ const mip = mipExtent(
1697
+ /** @type {Extent} */ (descriptor.size),
1698
+ /** @type {Dimension} */ (descriptor.dimension),
1699
+ endpoint.mipLevel,
1700
+ block.width,
1701
+ block.height,
1702
+ );
1703
+ if ("refuse" in mip) return { refuse: mip.refuse };
1704
+ const physical = mip.ok.physical;
1705
+
1706
+ const originProblem = originRefusal(endpoint.origin, physical);
1707
+ if (originProblem !== null) return { refuse: originProblem };
1708
+
1709
+ const copyResult = resolveCopyExtent(physical, endpoint.origin, { size: size ?? null });
1710
+ if ("refuse" in copyResult) return { refuse: copyResult.refuse };
1711
+ const copy = copyResult.value;
1712
+
1713
+ const blockProblem = blockAlignmentRefusal(
1714
+ endpoint.origin,
1715
+ copy,
1716
+ block.width,
1717
+ block.height,
1718
+ );
1719
+ if (blockProblem !== null) return { refuse: blockProblem };
1720
+
1721
+ return { ok: { mip: mip.ok, copyExtent: copy } };
1722
+ }
1723
+
1724
+ /**
1725
+ * Normalize one endpoint's optional fields without inventing a resource:
1726
+ * a missing object is malformed, and absent mip/origin/aspect take the IDL
1727
+ * defaults. `textureId` is carried for the same-texture disjoint rule.
1728
+ *
1729
+ * @param {unknown} value
1730
+ * @returns {{ textureId: number, mipLevel: number, origin: Origin,
1731
+ * aspect: AspectName | number } | null}
1732
+ */
1733
+ function normalizeCopyEndpoint(value) {
1734
+ if (value === null || typeof value !== "object") return null;
1735
+ const endpoint = /** @type {SubresourceEndpointInput} */ (value);
1736
+ const origin = readOrigin(endpoint.origin);
1737
+ if ("refuse" in origin) return null;
1738
+ return {
1739
+ textureId: typeof endpoint.textureId === "number" ? endpoint.textureId : 0,
1740
+ mipLevel: endpoint.mipLevel ?? 0,
1741
+ origin: origin.value,
1742
+ aspect: /** @type {AspectName | number} */ (endpoint.aspect ?? "all"),
1743
+ };
1744
+ }
1745
+
1746
+ /**
1747
+ * Plan 06's `copyTextureToTexture` calculator. Stages, first refusal stable:
1748
+ * both descriptors, usage (COPY_SRC / COPY_DST), sample-count equality,
1749
+ * copy-compatible formats, each endpoint's per-role aspect copyability, the
1750
+ * source endpoint (aspect/mip/origin/extent/block), the destination endpoint
1751
+ * against the RESOLVED source extent, the depth-stencil/MSAA full-subresource
1752
+ * rule, then the same-texture disjoint-subresource rule (`index.bs:11196`).
1753
+ * The default size is plan 01's remaining physical source extent — one
1754
+ * calculation, no second formula.
1755
+ *
1756
+ * @param {TextureDescriptorInput} sourceDescriptor
1757
+ * @param {TextureDescriptorInput} destinationDescriptor
1758
+ * @param {SubresourceCopyInput} copy
1759
+ * @returns {SubresourceCopyResult}
1760
+ */
1761
+ export function calculateTextureCopy(sourceDescriptor, destinationDescriptor, copy) {
1762
+ const normalizedSource = normalizeDescriptor(sourceDescriptor);
1763
+ if ("refuse" in normalizedSource) return { refuse: normalizedSource.refuse };
1764
+ const normalizedDestination = normalizeDescriptor(destinationDescriptor);
1765
+ if ("refuse" in normalizedDestination) return { refuse: normalizedDestination.refuse };
1766
+ const source = normalizedSource.value;
1767
+ const destination = normalizedDestination.value;
1768
+
1769
+ const sourceDescriptorRefusal = validateDescriptor(source);
1770
+ if (sourceDescriptorRefusal !== null) return { refuse: sourceDescriptorRefusal };
1771
+ const destinationDescriptorRefusal = validateDescriptor(destination);
1772
+ if (destinationDescriptorRefusal !== null) return { refuse: destinationDescriptorRefusal };
1773
+
1774
+ const sourceUsage = readBounded("usage", source.usage, 0xff);
1775
+ if ("refuse" in sourceUsage) return { refuse: sourceUsage.refuse };
1776
+ if ((sourceUsage.value & 1) === 0) {
1777
+ return {
1778
+ refuse: refusal("missing-copy-src", "usage", sourceUsage.value, 1),
1779
+ };
1780
+ }
1781
+ const destinationUsage = readBounded("usage", destination.usage, 0xff);
1782
+ if ("refuse" in destinationUsage) return { refuse: destinationUsage.refuse };
1783
+ if ((destinationUsage.value & 2) === 0) {
1784
+ return {
1785
+ refuse: refusal("missing-copy-dst", "usage", destinationUsage.value, 2),
1786
+ };
1787
+ }
1788
+
1789
+ const sourceSamples = readBounded("sample-count", source.sampleCount, U32_MAX);
1790
+ if ("refuse" in sourceSamples) return { refuse: sourceSamples.refuse };
1791
+ const destinationSamples = readBounded("sample-count", destination.sampleCount, U32_MAX);
1792
+ if ("refuse" in destinationSamples) return { refuse: destinationSamples.refuse };
1793
+ if (sourceSamples.value !== destinationSamples.value) {
1794
+ return {
1795
+ refuse: refusal(
1796
+ "sample-count-mismatch",
1797
+ "sample-count",
1798
+ sourceSamples.value,
1799
+ destinationSamples.value,
1800
+ ),
1801
+ };
1802
+ }
1803
+
1804
+ if (!copyCompatible(source.format, destination.format)) {
1805
+ const src = resolveFormat(source.format);
1806
+ const dst = resolveFormat(destination.format);
1807
+ return {
1808
+ refuse: refusal(
1809
+ "invalid-format",
1810
+ "format",
1811
+ src === null ? 0 : src.byte,
1812
+ dst === null ? 0 : dst.byte,
1813
+ ),
1814
+ };
1815
+ }
1816
+ // Each endpoint's format must be copyable on its side BEFORE any extent is
1817
+ // resolved: an absent aspect footprint would otherwise read as a zero-size
1818
+ // range and surface as a downstream range error.
1819
+ const sourceFormatRefusal = copyFormatRefusal(source.format, "source");
1820
+ if (sourceFormatRefusal !== null) return { refuse: sourceFormatRefusal };
1821
+ const destinationFormatRefusal = copyFormatRefusal(destination.format, "destination");
1822
+ if (destinationFormatRefusal !== null) return { refuse: destinationFormatRefusal };
1823
+
1824
+ const copyInput = copy !== null && typeof copy === "object" ? copy : {};
1825
+ const sourceEndpoint = normalizeCopyEndpoint(copyInput.source);
1826
+ const destinationEndpoint = normalizeCopyEndpoint(copyInput.destination);
1827
+ if (sourceEndpoint === null || destinationEndpoint === null) {
1828
+ return { refuse: refusal("invalid-texture-descriptor", "none") };
1829
+ }
1830
+
1831
+ const sourceLayout = calculateCopyEndpoint(source, sourceEndpoint, copyInput.size);
1832
+ if ("refuse" in sourceLayout) return { refuse: sourceLayout.refuse };
1833
+ const destinationLayout = calculateCopyEndpoint(
1834
+ destination,
1835
+ destinationEndpoint,
1836
+ sourceLayout.ok.copyExtent,
1837
+ );
1838
+ if ("refuse" in destinationLayout) return { refuse: destinationLayout.refuse };
1839
+
1840
+ // For a depth-stencil or multisampled endpoint the copy must cover the
1841
+ // ENTIRE physical subresource (CRD `sections/copies.bs:263-266`). Extent
1842
+ // equality also forces the origin to zero through the range checks above.
1843
+ if (formatHasDepthOrStencil(source.format) || sourceSamples.value > 1) {
1844
+ const partial = fullSubresourceRefusal(
1845
+ sourceEndpoint.origin,
1846
+ sourceLayout.ok.copyExtent,
1847
+ sourceLayout.ok.mip.physical,
1848
+ "partial-subresource-copy",
1849
+ );
1850
+ if (partial !== null) return { refuse: partial };
1851
+ }
1852
+ if (formatHasDepthOrStencil(destination.format) || destinationSamples.value > 1) {
1853
+ const partial = fullSubresourceRefusal(
1854
+ destinationEndpoint.origin,
1855
+ destinationLayout.ok.copyExtent,
1856
+ destinationLayout.ok.mip.physical,
1857
+ "partial-subresource-copy",
1858
+ );
1859
+ if (partial !== null) return { refuse: partial };
1860
+ }
1861
+
1862
+ // A copy within one texture may not share a subresource (mip + aspect +
1863
+ // layer/slice), even when the texel ranges inside it would not overlap.
1864
+ // Both endpoints carry `all` aspects, so only the mip and z ranges differ.
1865
+ if (
1866
+ sourceEndpoint.textureId === destinationEndpoint.textureId &&
1867
+ sourceEndpoint.mipLevel === destinationEndpoint.mipLevel &&
1868
+ sourceLayout.ok.copyExtent.depthOrArrayLayers > 0
1869
+ ) {
1870
+ const srcStart = sourceEndpoint.origin.z;
1871
+ const dstStart = destinationEndpoint.origin.z;
1872
+ const srcEnd = srcStart + sourceLayout.ok.copyExtent.depthOrArrayLayers;
1873
+ const dstEnd = dstStart + sourceLayout.ok.copyExtent.depthOrArrayLayers;
1874
+ if (srcStart < dstEnd && dstStart < srcEnd) {
1875
+ return {
1876
+ refuse: refusal(
1877
+ "overlapping-subresources",
1878
+ "mip-level",
1879
+ sourceEndpoint.mipLevel,
1880
+ destinationEndpoint.mipLevel,
1881
+ ),
1882
+ };
1883
+ }
1884
+ }
1885
+
1886
+ return {
1887
+ ok: {
1888
+ source: sourceLayout.ok,
1889
+ destination: destinationLayout.ok,
1890
+ copyExtent: sourceLayout.ok.copyExtent,
1891
+ },
1892
+ };
1893
+ }