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.
@@ -1,5 +1,5 @@
1
1
  // Queue / WASM / control command handlers for the GPU dispatcher.
2
- // Handles opcodes 0x20-0x27 (queue), 0x30-0x31 (WASM), 0xF0-0xFF (control).
2
+ // Handles opcodes 0x20-0x2B (queue), 0x30-0x31 (WASM), 0xF0-0xFF (control).
3
3
  //
4
4
  // Split out of gpu.js alongside gpu-resource-pass-commands.js (0x01-0x52). The
5
5
  // two modules share one `ops` bag — see types/gpu-ops.d.ts for its shape and
@@ -9,6 +9,13 @@
9
9
  // tests/npm/command-buffer-widths.test.js. A wrong `return pos + N` desyncs
10
10
  // every LATER command in the buffer, so treat those numbers as wire format.
11
11
 
12
+ import {
13
+ calculateCopy,
14
+ calculateTextureCopy,
15
+ calculateWrite,
16
+ CopyPolicy,
17
+ } from "./texture-layout.js";
18
+
12
19
  // Same build-flag fallback gpu.js installs (esbuild --define:DEBUG=false strips
13
20
  // the debug paths in production). Declared locally rather than relying on
14
21
  // gpu.js's copy having run first: that import-side-effect coupling is what left
@@ -18,6 +25,368 @@ if (typeof DEBUG === "undefined") globalThis.DEBUG = false;
18
25
  /** Sentinel texture id meaning "the canvas", not an entry in the texture table. */
19
26
  const CANVAS = 0xfffe;
20
27
 
28
+ /**
29
+ * Wire aspect tags, in the contract's fixed byte order.
30
+ * @type {GPUTextureAspect[]}
31
+ */
32
+ const ASPECT_NAMES = ["all", "stencil-only", "depth-only"];
33
+
34
+ /**
35
+ * The public SJON name for a resource id, or null when the payload carries no
36
+ * name block for it (an old payload, an unnamed resource). A pool member is
37
+ * addressed by its declared base name.
38
+ * @param {Map<string, {id: number, pool: number}>} names
39
+ * @param {number} id
40
+ * @returns {string|null}
41
+ */
42
+ function nameFor(names, id) {
43
+ for (const [name, r] of names) {
44
+ if (id >= r.id && id < r.id + (r.pool || 1)) return name;
45
+ }
46
+ return null;
47
+ }
48
+
49
+ /**
50
+ * One failed byte readback, through the existing command-error route. Every
51
+ * failure — a rejected map, a range the mapping does not cover, a throwing
52
+ * host callback — names the buffer and the `readback-unavailable` code.
53
+ * @param {GpuOps} ops
54
+ * @param {object} rb
55
+ * @param {unknown} e
56
+ */
57
+ function readbackFailed(ops, rb, e) {
58
+ ops.reportError({
59
+ message: `texture readback failed for buffer ${rb.id}: ${/** @type {any} */ (e)?.message || e} (readback-unavailable)`,
60
+ source: "readback",
61
+ });
62
+ }
63
+
64
+ /**
65
+ * Map one scheduled texture→buffer destination and hand its bytes to the host.
66
+ *
67
+ * mapAsync requires an 8-byte-aligned offset and a 4-byte-multiple size, which
68
+ * a legal texel-copy layout need not satisfy (a depth-stencil copy allows a
69
+ * 4-byte offset; a stencil row can end on an odd byte). Map the enclosing
70
+ * aligned window and slice exactly the copied span — final row padding
71
+ * excluded — out of it.
72
+ *
73
+ * The byte array is an OWNED copy: the mapping is released in `finally` before
74
+ * the host is called, so a retained or mutated array can never alias driver
75
+ * memory, and a throwing callback cannot leave the buffer mapped (the 0x22 skip
76
+ * would then poison every later copy to it). A destroyed dispatcher (a stale
77
+ * generation) releases a late mapping and delivers nothing, including no error.
78
+ *
79
+ * @param {GpuOps} ops
80
+ * @param {object} rb
81
+ * @param {(readback: object) => void} onTextureReadback
82
+ */
83
+ function deliverTextureReadback(ops, rb, onTextureReadback) {
84
+ const b = ops.buf[rb.id];
85
+ if (!b || b.mapState !== "unmapped") {
86
+ readbackFailed(ops, rb, new Error(b ? `buffer is ${b.mapState}` : "buffer is gone"));
87
+ return;
88
+ }
89
+ const mapOffset = rb.offset & ~7;
90
+ const mapSize = Math.ceil((rb.offset - mapOffset + rb.size) / 4) * 4;
91
+ b.mapAsync(GPUMapMode.READ, mapOffset, mapSize).then(() => {
92
+ let bytes = null;
93
+ try {
94
+ if (ops.alive()) {
95
+ const mapped = new Uint8Array(b.getMappedRange(mapOffset, mapSize));
96
+ bytes = mapped.slice(rb.offset - mapOffset, rb.offset - mapOffset + rb.size);
97
+ }
98
+ } catch (e) {
99
+ readbackFailed(ops, rb, e);
100
+ } finally {
101
+ if (b.mapState === "mapped") {
102
+ try { b.unmap(); } catch { /* raced a teardown */ }
103
+ }
104
+ }
105
+ if (!bytes || !ops.alive()) return;
106
+ try {
107
+ onTextureReadback({
108
+ texture: rb.textureName,
109
+ buffer: rb.bufferName,
110
+ offset: rb.offset,
111
+ size: rb.size,
112
+ bytes,
113
+ bytesPerRow: rb.bytesPerRow,
114
+ rowsPerImage: rb.rowsPerImage,
115
+ mipLevel: rb.mipLevel,
116
+ origin: rb.origin,
117
+ aspect: rb.aspect,
118
+ copySize: rb.copySize,
119
+ });
120
+ } catch (e) {
121
+ readbackFailed(ops, rb, e);
122
+ }
123
+ }).catch((e) => readbackFailed(ops, rb, e));
124
+ }
125
+
126
+ /**
127
+ * Execute a buffer↔texture encoder copy (0x29 / 0x2A).
128
+ *
129
+ * The record is 46 fixed operand bytes:
130
+ * `[texture_id:u16][buffer_id:u16][offset:u32][bytes_per_row:u32]
131
+ * [rows_per_image:u32][mip_level:u32][origin_x/y/z:u32][aspect:u8]
132
+ * [size_width:u32][size_height:u32][size_depth:u32][flags:u8]`.
133
+ * No WASM pointer appears: the linear side is a GPUBuffer.
134
+ *
135
+ * The opcode is the direction. It selects the calculator policy, so the
136
+ * texture endpoint is validated as a destination (`copy-dst`) for 0x29 and as
137
+ * a source (`copy-src`) for 0x2A — two different usage checks. A refusal
138
+ * reaches the host through onError and records no encoder call.
139
+ *
140
+ * @param {number} cmd
141
+ * @param {DataView} view
142
+ * @param {number} pos
143
+ * @param {GpuOps} ops
144
+ * @returns {number}
145
+ */
146
+ function copyTextureBuffer(cmd, view, pos, ops) {
147
+ const bufferToTexture = cmd === 0x29;
148
+ const textureId = view.getUint16(pos, true);
149
+ const bufferId = view.getUint16(pos + 2, true);
150
+ const offset = view.getUint32(pos + 4, true);
151
+ const bytesPerRow = view.getUint32(pos + 8, true);
152
+ const rowsPerImage = view.getUint32(pos + 12, true);
153
+ const mipLevel = view.getUint32(pos + 16, true);
154
+ const ox = view.getUint32(pos + 20, true);
155
+ const oy = view.getUint32(pos + 24, true);
156
+ const oz = view.getUint32(pos + 28, true);
157
+ const aspect = view.getUint8(pos + 32);
158
+ const sizeWidth = view.getUint32(pos + 33, true);
159
+ const sizeHeight = view.getUint32(pos + 37, true);
160
+ const sizeDepth = view.getUint32(pos + 41, true);
161
+ const flags = view.getUint8(pos + 45);
162
+
163
+ // Presence is the flags byte's only job: an absent stride/size and an
164
+ // authored zero carry the same value. Keep absence as undefined through the
165
+ // calculator AND the WebGPU layout — passing the normalized minimum here
166
+ // would silently turn omission into an explicit stride.
167
+ const hasBytesPerRow = (flags & 1) !== 0;
168
+ const hasRowsPerImage = (flags & 2) !== 0;
169
+ const hasSize = (flags & 4) !== 0;
170
+ const write = {
171
+ offset,
172
+ mipLevel,
173
+ origin: { x: ox, y: oy, z: oz },
174
+ aspect,
175
+ bytesPerRow: hasBytesPerRow ? bytesPerRow : undefined,
176
+ rowsPerImage: hasRowsPerImage ? rowsPerImage : undefined,
177
+ size: hasSize
178
+ ? { width: sizeWidth, height: sizeHeight, depthOrArrayLayers: sizeDepth }
179
+ : undefined,
180
+ };
181
+
182
+ const label = bufferToTexture ? "copyBufferToTexture" : "copyTextureToBuffer";
183
+ const source = bufferToTexture ? "copy-buffer-to-texture" : "copy-texture-to-buffer";
184
+ const refuse = (code, field, actual, limit) =>
185
+ ops.reportError({ message: `${label}: ${code} — ${field}/${actual}/${limit}`, source });
186
+
187
+ const texture = ops.tex[textureId];
188
+ const descriptor = ops.txd[textureId];
189
+ if (!texture || !descriptor) {
190
+ refuse("missing-texture", "texture", textureId, 0);
191
+ return pos + 46;
192
+ }
193
+ const buffer = ops.buf[bufferId];
194
+ const bufferSize = ops.bufSize[bufferId];
195
+ if (!buffer || bufferSize === undefined) {
196
+ refuse("missing-buffer", "buffer", bufferId, 0);
197
+ return pos + 46;
198
+ }
199
+
200
+ const calc = calculateCopy(
201
+ descriptor,
202
+ write,
203
+ bufferSize,
204
+ bufferToTexture ? CopyPolicy.bufferToTexture : CopyPolicy.textureToBuffer,
205
+ );
206
+ if ("refuse" in calc) {
207
+ refuse(calc.refuse.code, calc.refuse.field, calc.refuse.actual, calc.refuse.limit);
208
+ return pos + 46;
209
+ }
210
+
211
+ const copy = calc.ok.copyExtent;
212
+ const size = /** @type {[number, number, number]} */ ([copy.width, copy.height, copy.depthOrArrayLayers]);
213
+ const textureInfo = { texture, mipLevel, origin: [ox, oy, oz], aspect: ASPECT_NAMES[aspect] };
214
+ const bufferInfo = {
215
+ buffer,
216
+ offset,
217
+ bytesPerRow: write.bytesPerRow,
218
+ rowsPerImage: write.rowsPerImage,
219
+ };
220
+ // A texture→buffer copy into MAP_READ|COPY_DST is a byte readback, not a
221
+ // query resolution. A destination already mapped (a host-held mapping, or a
222
+ // prior delivery that has not released yet) makes the copy invalid; report
223
+ // it rather than skipping silently, which is what 0x22's query path does.
224
+ const usage = ops.bufUsage[bufferId] || 0;
225
+ const readbackDestination = !bufferToTexture && (usage & 0x0001) !== 0 && (usage & 0x0008) !== 0;
226
+ if (readbackDestination && buffer.mapState !== "unmapped") {
227
+ refuse("buffer-mapped", "buffer", bufferId, 0);
228
+ return pos + 46;
229
+ }
230
+ const enc = ops.encoder();
231
+ if (bufferToTexture) enc.copyBufferToTexture(bufferInfo, textureInfo, size);
232
+ else enc.copyTextureToBuffer(textureInfo, bufferInfo, size);
233
+ if (readbackDestination && calc.ok.requiredBytesInCopy > 0) {
234
+ ops.pendingReadbacks.push({
235
+ kind: "texture",
236
+ id: bufferId,
237
+ offset,
238
+ size: calc.ok.requiredBytesInCopy,
239
+ bytesPerRow: calc.ok.bytesPerRow,
240
+ rowsPerImage: calc.ok.rowsPerImage,
241
+ mipLevel,
242
+ origin: [ox, oy, oz],
243
+ aspect: ASPECT_NAMES[aspect],
244
+ copySize: size,
245
+ textureName: nameFor(ops.texNames, textureId),
246
+ bufferName: nameFor(ops.bufNames, bufferId),
247
+ });
248
+ }
249
+ return pos + 46;
250
+ }
251
+
252
+ /**
253
+ * The canvas as a copy endpoint. The configured canvas is
254
+ * RENDER_ATTACHMENT|COPY_SRC (`core.js`/`worker-core.js` configure it that
255
+ * way), so a canvas SOURCE can be validated while a canvas DESTINATION is
256
+ * refused by the shared calculator's missing-copy-dst stage.
257
+ *
258
+ * @param {GpuOps} ops
259
+ * @returns {object}
260
+ */
261
+ function canvasCopyDescriptor(ops) {
262
+ const { cw, ch } = ops.clock();
263
+ return {
264
+ size: { width: cw, height: ch, depthOrArrayLayers: 1 },
265
+ dimension: "2d",
266
+ format: navigator.gpu.getPreferredCanvasFormat(),
267
+ usage: 0x10 | 0x01, // RENDER_ATTACHMENT | COPY_SRC
268
+ sampleCount: 1,
269
+ mipLevelCount: 1,
270
+ extentSource: "canvas",
271
+ };
272
+ }
273
+
274
+ /**
275
+ * Execute a subresource texture→texture copy (0x2B).
276
+ *
277
+ * The record is 51 fixed operand bytes:
278
+ * `[src_id:u16][dst_id:u16] [src_mip:u32][src_origin_x/y/z:u32][src_aspect:u8]
279
+ * [dst_mip:u32][dst_origin_x/y/z:u32][dst_aspect:u8]
280
+ * [size_width:u32][size_height:u32][size_depth:u32][flags:u8]`.
281
+ * No WASM pointer appears: both sides are GPUTextures the runtime holds.
282
+ *
283
+ * `flags` bit 0 records whether a size was authored. An absent size defers to
284
+ * `calculateTextureCopy`'s remaining-physical-source-extent rule. The opcode
285
+ * executes ONLY after that calculator accepts both endpoints — a refusal
286
+ * reaches onError and records no encoder call.
287
+ *
288
+ * @param {DataView} view
289
+ * @param {number} pos
290
+ * @param {GpuOps} ops
291
+ * @returns {number}
292
+ */
293
+ function copyTextureSubresource(view, pos, ops) {
294
+ const sourceId = view.getUint16(pos, true);
295
+ const destinationId = view.getUint16(pos + 2, true);
296
+ const sourceMip = view.getUint32(pos + 4, true);
297
+ const sourceX = view.getUint32(pos + 8, true);
298
+ const sourceY = view.getUint32(pos + 12, true);
299
+ const sourceZ = view.getUint32(pos + 16, true);
300
+ const sourceAspect = view.getUint8(pos + 20);
301
+ const destinationMip = view.getUint32(pos + 21, true);
302
+ const destinationX = view.getUint32(pos + 25, true);
303
+ const destinationY = view.getUint32(pos + 29, true);
304
+ const destinationZ = view.getUint32(pos + 33, true);
305
+ const destinationAspect = view.getUint8(pos + 37);
306
+ const sizeWidth = view.getUint32(pos + 38, true);
307
+ const sizeHeight = view.getUint32(pos + 42, true);
308
+ const sizeDepth = view.getUint32(pos + 46, true);
309
+ const flags = view.getUint8(pos + 50);
310
+
311
+ const label = "copyTextureToTexture";
312
+ const source = "copy-texture-subresource";
313
+ const refuse = (code, field, actual, limit) =>
314
+ ops.reportError({ message: `${label}: ${code} — ${field}/${actual}/${limit}`, source });
315
+
316
+ // Only bit 0 is defined. Any other bit makes the record uninterpretable, so
317
+ // this is a refusal rather than a silently ignored feature bit.
318
+ if ((flags & ~1) !== 0) {
319
+ refuse("invalid-flags", "flags", flags, 1);
320
+ return pos + 51;
321
+ }
322
+ const hasSize = (flags & 1) !== 0;
323
+
324
+ const descriptorOf = (id) =>
325
+ id === CANVAS ? canvasCopyDescriptor(ops) : ops.txd[id];
326
+ const sourceDescriptor = descriptorOf(sourceId);
327
+ const destinationDescriptor = descriptorOf(destinationId);
328
+ if (!sourceDescriptor) {
329
+ refuse("missing-texture", "texture", sourceId, 0);
330
+ return pos + 51;
331
+ }
332
+ if (!destinationDescriptor) {
333
+ refuse("missing-texture", "texture", destinationId, 0);
334
+ return pos + 51;
335
+ }
336
+
337
+ const calc = calculateTextureCopy(sourceDescriptor, destinationDescriptor, {
338
+ source: {
339
+ textureId: sourceId,
340
+ mipLevel: sourceMip,
341
+ origin: { x: sourceX, y: sourceY, z: sourceZ },
342
+ aspect: sourceAspect,
343
+ },
344
+ destination: {
345
+ textureId: destinationId,
346
+ mipLevel: destinationMip,
347
+ origin: { x: destinationX, y: destinationY, z: destinationZ },
348
+ aspect: destinationAspect,
349
+ },
350
+ size: hasSize
351
+ ? { width: sizeWidth, height: sizeHeight, depthOrArrayLayers: sizeDepth }
352
+ : undefined,
353
+ });
354
+ if ("refuse" in calc) {
355
+ refuse(calc.refuse.code, calc.refuse.field, calc.refuse.actual, calc.refuse.limit);
356
+ return pos + 51;
357
+ }
358
+
359
+ // Resolve the live handles only after validation: a canvas destination never
360
+ // acquires a swapchain texture it is about to be refused.
361
+ const sourceTexture =
362
+ sourceId === CANVAS ? ops.targetCtx().getCurrentTexture() : ops.tex[sourceId];
363
+ const destinationTexture =
364
+ destinationId === CANVAS ? ops.targetCtx().getCurrentTexture() : ops.tex[destinationId];
365
+ if (!sourceTexture || !destinationTexture) {
366
+ refuse("missing-texture", "texture", sourceTexture ? destinationId : sourceId, 0);
367
+ return pos + 51;
368
+ }
369
+
370
+ const extent = calc.ok.copyExtent;
371
+ const enc = ops.encoder();
372
+ enc.copyTextureToTexture(
373
+ {
374
+ texture: sourceTexture,
375
+ mipLevel: sourceMip,
376
+ origin: [sourceX, sourceY, sourceZ],
377
+ aspect: ASPECT_NAMES[sourceAspect],
378
+ },
379
+ {
380
+ texture: destinationTexture,
381
+ mipLevel: destinationMip,
382
+ origin: [destinationX, destinationY, destinationZ],
383
+ aspect: ASPECT_NAMES[destinationAspect],
384
+ },
385
+ [extent.width, extent.height, extent.depthOrArrayLayers],
386
+ );
387
+ return pos + 51;
388
+ }
389
+
21
390
  /**
22
391
  * Dispatch queue / WASM / control commands.
23
392
  *
@@ -74,6 +443,88 @@ export function dispatchQueueCommand(cmd, view, pos, ops) {
74
443
  if (ops.qs[qsId] && ops.buf[destBuf]) enc.resolveQuerySet(ops.qs[qsId], first, count, ops.buf[destBuf], destOff);
75
444
  return pos + 16;
76
445
  }
446
+ case 0x28: { // write_texture
447
+ const id = view.getUint16(pos, true);
448
+ const dataPtr = view.getUint32(pos + 2, true);
449
+ const dataLen = view.getUint32(pos + 6, true);
450
+ const offset = view.getUint32(pos + 10, true);
451
+ const bytesPerRow = view.getUint32(pos + 14, true);
452
+ const rowsPerImage = view.getUint32(pos + 18, true);
453
+ const mipLevel = view.getUint32(pos + 22, true);
454
+ const ox = view.getUint32(pos + 26, true);
455
+ const oy = view.getUint32(pos + 30, true);
456
+ const oz = view.getUint32(pos + 34, true);
457
+ const aspect = view.getUint8(pos + 38);
458
+ const sizeWidth = view.getUint32(pos + 39, true);
459
+ const sizeHeight = view.getUint32(pos + 43, true);
460
+ const sizeDepth = view.getUint32(pos + 47, true);
461
+ const flags = view.getUint8(pos + 51);
462
+
463
+ // Presence is the flags byte's only job: an absent stride/size and an
464
+ // authored zero carry the same value. Keep absence as undefined through
465
+ // the calculator AND the WebGPU layout — passing the normalized minimum
466
+ // here would silently turn omission into an explicit stride.
467
+ const hasBytesPerRow = (flags & 1) !== 0;
468
+ const hasRowsPerImage = (flags & 2) !== 0;
469
+ const hasSize = (flags & 4) !== 0;
470
+ const write = {
471
+ offset,
472
+ mipLevel,
473
+ origin: { x: ox, y: oy, z: oz },
474
+ aspect,
475
+ bytesPerRow: hasBytesPerRow ? bytesPerRow : undefined,
476
+ rowsPerImage: hasRowsPerImage ? rowsPerImage : undefined,
477
+ size: hasSize
478
+ ? { width: sizeWidth, height: sizeHeight, depthOrArrayLayers: sizeDepth }
479
+ : undefined,
480
+ };
481
+
482
+ const refuse = (code, field, actual, limit) =>
483
+ ops.reportError({
484
+ message: `writeTexture: ${code} — ${field}/${actual}/${limit}`,
485
+ source: "write-texture",
486
+ });
487
+
488
+ const texture = ops.tex[id];
489
+ const descriptor = ops.txd[id];
490
+ if (!texture || !descriptor) {
491
+ refuse("missing-texture", "texture", id, 0);
492
+ return pos + 52;
493
+ }
494
+ // The window is referenced straight out of executor memory, so its u64
495
+ // end is bounded before the view is constructed. Two u32 operands sum to
496
+ // at most 2^33, which a JS Number carries exactly; equality is legal (a
497
+ // zero-length window at the very end), one byte past is not.
498
+ const memBytes = ops.mem.buffer.byteLength;
499
+ const end = dataPtr + dataLen;
500
+ if (dataPtr > memBytes || end > memBytes) {
501
+ refuse("invalid-data-window", "data", end, memBytes);
502
+ return pos + 52;
503
+ }
504
+
505
+ // The retained record IS the calculator descriptor: concrete extent,
506
+ // resolved format, destination usage, sample count and mip count, all
507
+ // kept current by create/resize. Nothing is re-derived from bindings.
508
+ const calc = calculateWrite(descriptor, write, dataLen);
509
+ if ("refuse" in calc) {
510
+ refuse(calc.refuse.code, calc.refuse.field, calc.refuse.actual, calc.refuse.limit);
511
+ return pos + 52;
512
+ }
513
+
514
+ const copy = calc.ok.copyExtent;
515
+ ops.device.queue.writeTexture(
516
+ { texture, mipLevel, origin: [ox, oy, oz], aspect: ASPECT_NAMES[aspect] },
517
+ new Uint8Array(ops.mem.buffer, dataPtr, dataLen),
518
+ { offset, bytesPerRow: write.bytesPerRow, rowsPerImage: write.rowsPerImage },
519
+ [copy.width, copy.height, copy.depthOrArrayLayers],
520
+ );
521
+ return pos + 52;
522
+ }
523
+ case 0x29: // copy_buffer_to_texture
524
+ case 0x2a: // copy_texture_to_buffer
525
+ return copyTextureBuffer(cmd, view, pos, ops);
526
+ case 0x2b: // copy_texture_subresource
527
+ return copyTextureSubresource(view, pos, ops);
77
528
  case 0x22: { // copy_buffer_to_buffer
78
529
  const sid = view.getUint16(pos, true), so = view.getUint32(pos + 2, true);
79
530
  const did = view.getUint16(pos + 6, true), dof = view.getUint32(pos + 8, true);
@@ -92,7 +543,7 @@ export function dispatchQueueCommand(cmd, view, pos, ops) {
92
543
  enc.copyBufferToBuffer(ops.buf[sid], so, ops.buf[did], dof, sz);
93
544
  // Schedule readback for MAP_READ destination buffers
94
545
  if (isMapRead) {
95
- ops.pendingReadbacks.push({ id: did, offset: dof, size: sz });
546
+ ops.pendingReadbacks.push({ kind: "query", id: did, offset: dof, size: sz });
96
547
  }
97
548
  return pos + 16;
98
549
  }
@@ -190,11 +641,18 @@ export function dispatchQueueCommand(cmd, view, pos, ops) {
190
641
  const enc = ops.takeEnc();
191
642
  DEBUG && ops.debug() && console.log(`[GPU] submit enc=${!!enc}`);
192
643
  if (enc) ops.device.queue.submit([enc.finish()]);
193
- // Readback MAP_READ buffers after submit (for occlusion query results etc.)
644
+ // Readback MAP_READ buffers after submit (query numbers and texture
645
+ // bytes are distinct consumers; the record's `kind` keeps them apart).
194
646
  const onQueryResult = ops.getOnQueryResult();
195
- if (ops.pendingReadbacks.length > 0 && onQueryResult) {
647
+ const onTextureReadback = ops.getOnTextureReadback();
648
+ if (ops.pendingReadbacks.length > 0 && (onQueryResult || onTextureReadback)) {
196
649
  const rbs = ops.pendingReadbacks.splice(0);
197
650
  for (const rb of rbs) {
651
+ if (rb.kind === "texture") {
652
+ if (onTextureReadback) deliverTextureReadback(ops, rb, onTextureReadback);
653
+ continue;
654
+ }
655
+ if (!onQueryResult) continue;
198
656
  const b = ops.buf[rb.id];
199
657
  if (b?.mapState === 'unmapped') {
200
658
  b.mapAsync(GPUMapMode.READ, rb.offset, rb.size).then(() => {
@@ -3,6 +3,13 @@
3
3
 
4
4
  import { decodeTextureViewDescriptor } from "./descriptor-decode.js";
5
5
 
6
+ /**
7
+ * Returned when a decoded record is malformed. `execute` aborts the buffer:
8
+ * the operand length is no longer trustworthy, and continuing would re-read
9
+ * operand bytes as opcodes. The handler has already reported why.
10
+ */
11
+ export const ABORT = -1;
12
+
6
13
  /**
7
14
  * A pass-scoped command outside an open pass is a dropped command — and a
8
15
  * missing begin_*_pass drops its ENTIRE pass this way, silently (an executor
@@ -31,9 +38,12 @@ function requirePass(ops, opName) {
31
38
  * @param {DataView} view
32
39
  * @param {number} pos - offset of this command's first OPERAND byte
33
40
  * @param {GpuOps} ops - see types/gpu-ops.d.ts
34
- * @returns {number|Promise<number>|null} next position, or null if unhandled
41
+ * @param {number} [end] - offset one past the command frame. 0x55 uses it to
42
+ * refuse a record that claims more bytes than the frame contains, BEFORE
43
+ * reading them out of unrelated memory.
44
+ * @returns {number|Promise<number>|null} next position, ABORT, or null if unhandled
35
45
  */
36
- export function dispatchResourcePassCommand(cmd, view, pos, ops) {
46
+ export function dispatchResourcePassCommand(cmd, view, pos, ops, end) {
37
47
  switch (cmd) {
38
48
  // === Resource Creation (0x01-0x0D) ===
39
49
  case 0x01: { // create_buffer
@@ -353,6 +363,52 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
353
363
  ops.beginRenderPassMRT(attachments, depthId);
354
364
  return off;
355
365
  }
366
+ case 0x55: { // begin_render_pass_views
367
+ // [color_count:u8] then 22 bytes per attachment ([target:u16][load][store]
368
+ // [rgba:f32×4][resolve:u16]) then [depth_target:u16]. Plan 09 slice 2.
369
+ // The count is bounded and the whole record is checked against the FRAME
370
+ // before any field is read: this buffer has no per-command length, so a
371
+ // lying count would otherwise read the next command's bytes as a clear
372
+ // colour and desync the rest of the stream.
373
+ ops.curPip = -1;
374
+ const limit = end ?? view.byteLength;
375
+ if (pos >= limit) {
376
+ ops.reportError({ message: `begin_render_pass_views: truncated record at ${pos}`, source: "command" });
377
+ return ABORT;
378
+ }
379
+ const count = view.getUint8(pos);
380
+ if (count > 8) {
381
+ ops.reportError({ message: `begin_render_pass_views: color_count ${count} exceeds 8`, source: "command" });
382
+ return ABORT;
383
+ }
384
+ const off0 = pos + 1;
385
+ const nextPos = off0 + 22 * count + 2;
386
+ if (nextPos > limit) {
387
+ ops.reportError({ message: `begin_render_pass_views: truncated record (needs ${nextPos - pos} bytes, frame has ${limit - pos})`, source: "command" });
388
+ return ABORT;
389
+ }
390
+ let off = off0;
391
+ const attachments = [];
392
+ for (let i = 0; i < count; i++) {
393
+ const target = view.getUint16(off, true); off += 2;
394
+ const load = view.getUint8(off++);
395
+ const store = view.getUint8(off++);
396
+ const r = view.getFloat32(off, true); off += 4;
397
+ const g = view.getFloat32(off, true); off += 4;
398
+ const b = view.getFloat32(off, true); off += 4;
399
+ const a = view.getFloat32(off, true); off += 4;
400
+ const resolve = view.getUint16(off, true); off += 2;
401
+ attachments.push({ target, load, store, r, g, b, a, resolve });
402
+ }
403
+ const depth = view.getUint16(off, true); off += 2;
404
+ // Zero colour is a depth-only pass; no depth makes it no pass at all.
405
+ if (count === 0 && depth === 0xffff) {
406
+ ops.reportError({ message: "begin_render_pass_views: zero colour attachments require a depth target", source: "command" });
407
+ return ABORT;
408
+ }
409
+ if (ops.beginRenderPassViews(attachments, depth) === false) return ABORT;
410
+ return off;
411
+ }
356
412
  case 0x1F: { // set_viewport
357
413
  const x = view.getUint32(pos, true);
358
414
  const y = view.getUint32(pos + 4, true);