pngine 4.3.1 → 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.
package/src/gpu.js CHANGED
@@ -9,12 +9,14 @@
9
9
  * 5. Short internal names (but readable - minifier handles the rest)
10
10
  */
11
11
 
12
- import { dispatchResourcePassCommand } from "./gpu-resource-pass-commands.js";
12
+ import { dispatchResourcePassCommand, ABORT } from "./gpu-resource-pass-commands.js";
13
13
  import { dispatchQueueCommand } from "./gpu-queue-commands.js";
14
14
  import { listBuffers, setBufferNames as setHostBufferNames, writeBuffers as hostWriteBuffers } from "./gpu-host-write.js";
15
+ import { listTextures, setTextureNames as setHostTextureNames, writeTextures as hostWriteTextures } from "./gpu-host-texture.js";
15
16
  import { countCachedBindGroups, countLive } from "./gpu-stats.js";
16
17
  import { uniformToTypedArray, uniformTypeName } from "./uniform-convert.js";
17
18
  import { decodeTextureFormat } from "./enums.js";
19
+ import { formatCreationRefusal } from "./texture-layout.js";
18
20
  import {
19
21
  decodeTextureDescriptor,
20
22
  decodeSamplerDescriptor,
@@ -40,6 +42,17 @@ export const OPTIONAL_DEVICE_FEATURES = [
40
42
  "dual-source-blending",
41
43
  // Powers (primitive :unclipped-depth true) → GPUPrimitiveState.unclippedDepth.
42
44
  "depth-clip-control",
45
+ // Plan 07's BC family: the format names are legal only when the base feature
46
+ // is on the device; BC 3D additionally needs the sliced-3d sibling.
47
+ "texture-compression-bc",
48
+ "texture-compression-bc-sliced-3d",
49
+ // Plan 07's ETC2/EAC family: no sliced-3d sibling exists, so 3D is refused
50
+ // by the format table rather than given an imaginary feature.
51
+ "texture-compression-etc2",
52
+ // Plan 07's ASTC family: the base feature covers 2D; ASTC 3D additionally
53
+ // needs the sliced-3d sibling.
54
+ "texture-compression-astc",
55
+ "texture-compression-astc-sliced-3d",
43
56
  ];
44
57
 
45
58
  // The optional features this adapter actually supports, in
@@ -87,6 +100,9 @@ const PNGB_FLAG_BUFFER_NAMES = 0x10;
87
100
  // payload uses frame-program instructions (§9's load-time handshake).
88
101
  const PNGB_FLAG_CONTROL_NAMES = 0x20;
89
102
  const PNGB_FLAG_HAS_GUARDS = 0x40;
103
+ // Header flag bit 7: the uniform-table section carries a texture-name block
104
+ // after the control-name block (plan 04 D14).
105
+ const PNGB_FLAG_TEXTURE_NAMES = 0x80;
90
106
  // flags bit 3 — the author requested a PREMULTIPLIED canvas ((canvas
91
107
  // :alpha-mode premultiplied)); clear = "opaque", the GPUCanvasConfiguration
92
108
  // default. The bit used to mean the opposite, back when this runtime's own
@@ -127,7 +143,8 @@ export function payloadHasGuards(bytecode) {
127
143
  * Parse uniform table from PNGB bytecode.
128
144
  * Returns: { uniforms: Map<string, {bufferId, offset, size, type, elemCount}>,
129
145
  * strings: string[],
130
- * buffers: Map<string, {id, pool, frameWritten}> }
146
+ * buffers: Map<string, {id, pool, frameWritten}>,
147
+ * textures: Map<string, {id, pool, frameWritten}> }
131
148
  * For a fixed-size array field, `type` is the ELEMENT's UT_* tag and
132
149
  * `elemCount` its element count; elemCount 0 = not an array (the byte was
133
150
  * padding in older payloads, so they parse identically).
@@ -142,14 +159,21 @@ export function payloadHasGuards(bytecode) {
142
159
  * document's declared controls; each joins `uniforms` marked
143
160
  * `{ control: true, slot }` — slot is 1-based, slot 0 being `time`. See the
144
161
  * block's reader below for the reserved-empty-slot rule.
162
+ *
163
+ * `textures` is the third tail block (header flag bit 7): every declared
164
+ * `(texture :name …)` by its SJON name, with its pool's base id/member count
165
+ * and whether a frame's own queue ops write it. Like `buffers`, it is read
166
+ * only behind its flag and bounded by the section end; an entry whose name is
167
+ * the reserved empty string stays unnamed and exposes no map key.
145
168
  */
146
169
  export function parseUniformTable(bytecode) {
147
170
  const view = new DataView(bytecode.buffer, bytecode.byteOffset, bytecode.byteLength);
148
171
  const buffers = new Map();
172
+ const textures = new Map();
149
173
 
150
174
  // Validate PNGB magic
151
175
  if (bytecode.length < PNGB_HEADER_SIZE || view.getUint32(0, true) !== PNGB_MAGIC) {
152
- return { uniforms: new Map(), strings: [], buffers };
176
+ return { uniforms: new Map(), strings: [], buffers, textures };
153
177
  }
154
178
 
155
179
  // Read header offsets
@@ -163,7 +187,7 @@ export function parseUniformTable(bytecode) {
163
187
  // Parse uniform table
164
188
  const uniforms = new Map();
165
189
  if (uniformTableOffset === 0 || uniformTableOffset >= bytecode.length) {
166
- return { uniforms, strings, buffers };
190
+ return { uniforms, strings, buffers, textures };
167
191
  }
168
192
 
169
193
  let pos = uniformTableOffset;
@@ -241,7 +265,26 @@ export function parseUniformTable(bytecode) {
241
265
  }
242
266
  }
243
267
 
244
- return { uniforms, strings, buffers };
268
+ // The texture-name block, after the control-name block (plan 04 D14):
269
+ // [count u16] then six bytes per entry — base id, name string id, pool,
270
+ // flags (bit 0 = frameWritten). Bounded by the section end like the blocks
271
+ // above. A reserved empty-string row consumes its record but joins no map,
272
+ // and later rows keep their own ids (never compacted).
273
+ if ((view.getUint16(6, true) & PNGB_FLAG_TEXTURE_NAMES) && pos + 2 <= sectionEnd) {
274
+ const textureCount = view.getUint16(pos, true);
275
+ pos += 2;
276
+ for (let i = 0; i < textureCount && pos + 6 <= sectionEnd; i++, pos += 6) {
277
+ const name = strings[view.getUint16(pos + 2, true)];
278
+ if (!name) continue; // a reserved slot: unnamed, unexposed
279
+ textures.set(name, {
280
+ id: view.getUint16(pos, true),
281
+ pool: view.getUint8(pos + 4),
282
+ frameWritten: (view.getUint8(pos + 5) & 1) === 1,
283
+ });
284
+ }
285
+ }
286
+
287
+ return { uniforms, strings, buffers, textures };
245
288
  }
246
289
 
247
290
  /**
@@ -437,12 +480,20 @@ export function createCommandDispatcher(device, ctx) {
437
480
  // create_bind_group's layout_id id-space tag; mirrors
438
481
  // src/types/opcodes.zig BIND_GROUP_LAYOUT_TAG. Set ⇒ standalone bgl id.
439
482
  const BGL_TAG = 0x8000;
483
+ // begin_render_pass_views' shared attachment-target encoding, mirroring
484
+ // src/types/opcodes.zig. A tagged value names txv (explicit (texture-view …));
485
+ // an untagged value names dfv (the texture's default view). The two sentinels
486
+ // carry the high bit too, so they are tested before the tag.
487
+ const ATTACH_VIEW = 0x8000;
488
+ const ATTACH_NONE = 0xffff;
489
+ const ATTACH_CANVAS = 0xfffe;
440
490
  const txd = []; // texture descriptors
441
491
  const bun = []; // render bundles
442
492
  const qs = []; // query sets
443
493
  const bufUsage = []; // buffer usage flags (for MAP_READ detection, host-write refusal)
444
494
  const bufSize = []; // buffer byte sizes (host-write range check)
445
495
  const bufNames = new Map(); // SJON buffer name → {id, pool, frameWritten} (host writes)
496
+ const texNames = new Map(); // SJON texture name → {id, pool, frameWritten} (host writes/reflection)
446
497
  let pendingOcclusionQS = null;
447
498
  let pendingTimestampWrites = null;
448
499
  let pendingDepthStencilOps = null;
@@ -450,9 +501,10 @@ export function createCommandDispatcher(device, ctx) {
450
501
  // Const, and cleared with .length = 0 rather than reassigned: the array is
451
502
  // handed to the queue-command module by reference, so a fresh array here
452
503
  // would leave that module writing into an orphan.
453
- /** @type {{id: number, offset: number, size: number}[]} */
504
+ /** @type {PendingReadback[]} */
454
505
  const pendingReadbacks = [];
455
506
  let onQueryResult = null;
507
+ let onTextureReadback = null;
456
508
 
457
509
  // Helper: read string from WASM memory
458
510
  function rs(ptr, len) {
@@ -611,17 +663,57 @@ export function createCommandDispatcher(device, ctx) {
611
663
  }
612
664
 
613
665
 
666
+ // The public name for an id, from the payload's texture-name block; raw ids
667
+ // are an emission-order artefact, so they are the fallback only.
668
+ function texturePublicName(id) {
669
+ for (const [name, r] of texNames) {
670
+ if (id >= r.id && id < r.id + (r.pool || 1)) return name;
671
+ }
672
+ return String(id);
673
+ }
674
+
675
+ // Format-driven creation policy (plan 07). A compressed format's device
676
+ // feature is checked BEFORE createTexture: WebGPU's own later validation
677
+ // reports a missing feature as an opaque device error with neither the
678
+ // texture nor the feature named. The same message shape is used by the host
679
+ // write path, so an unsupported adapter can never fall through to a default
680
+ // format or a blank success.
681
+ function reportTextureCreationRefusal(id, desc) {
682
+ const why = formatCreationRefusal(
683
+ desc.format,
684
+ desc.dimension || "2d",
685
+ { width: desc.size[0], height: desc.size[1], depthOrArrayLayers: desc.size[2] || 1 },
686
+ device.features,
687
+ );
688
+ if (why === null) return false;
689
+ onError && onError({ message: `texture '${texturePublicName(id)}' ${why}`, source: "create-texture" });
690
+ return true;
691
+ }
692
+
614
693
  function createTexture(id, ptr, len) {
615
694
  if (tex[id]) return;
616
695
  if (len === 0) return emptyDescriptor("createTexture", id);
617
- const { desc, canvasBound, canvasScale } = decodeTextureDescriptor(
696
+ const { desc, canvasBound, canvasScale, extentSource } = decodeTextureDescriptor(
618
697
  new Uint8Array(mem.buffer, ptr, len), navigator.gpu.getPreferredCanvasFormat(), cw, ch, bmp);
698
+ if (reportTextureCreationRefusal(id, desc)) return;
619
699
  // Canvas-bound: bytecode omitted width/height, so size tracks canvas dims.
620
- // Remember the static fields so the resize path can rebuild at new cw/ch —
621
- // `canvasScale` among them, or a half-resolution target would come back
622
- // full-size after the first resize.
623
- txd[id] = { format: desc.format, usage: desc.usage, canvasBound, canvasScale,
624
- dimension: desc.dimension, sampleCount: desc.sampleCount, depth: desc.size[2] };
700
+ // Keep the COMPLETE plan-01 descriptor, not a projection of it: a later
701
+ // write_texture re-runs the calculator against these facts, and a field
702
+ // dropped here is a field the runtime can only guess. The resize path
703
+ // rebuilds from the same record, `canvasScale` among them, or a
704
+ // half-resolution target would come back full-size after the first resize.
705
+ txd[id] = {
706
+ id,
707
+ size: { width: desc.size[0], height: desc.size[1], depthOrArrayLayers: desc.size[2] || 1 },
708
+ dimension: desc.dimension || "2d",
709
+ format: desc.format,
710
+ usage: desc.usage,
711
+ sampleCount: desc.sampleCount || 1,
712
+ mipLevelCount: desc.mipLevelCount || 1,
713
+ extentSource,
714
+ canvasBound,
715
+ canvasScale,
716
+ };
625
717
  DEBUG && dbg && console.log(`[GPU] createTexture(${id}) ${desc.size[0]}x${desc.size[1]} ${desc.format} usage=0x${desc.usage.toString(16)}${canvasBound ? ' [canvas]' : ''}`);
626
718
  installTexture(id, scoped("createTexture", id, () => device.createTexture(desc)));
627
719
  }
@@ -725,17 +817,62 @@ export function createCommandDispatcher(device, ctx) {
725
817
  clearValue: { r: r || 0, g: g || 0, b: b || 0, a: a || 0 } };
726
818
  }
727
819
 
820
+ // One depth-stencil attachment from an ALREADY-RESOLVED view. Shared by the
821
+ // legacy begin-passes (which resolve dfv[depthId]) and 0x55 (which may have
822
+ // resolved an explicit view), so pending depth/stencil state has one consumer.
823
+ function depthAttachment(view, format) {
824
+ const pds = pendingDepthStencilOps;
825
+ const pcv = pendingClearValues;
826
+ const dsa = { view, depthLoadOp: pds ? pds.dl : "clear", depthStoreOp: pds ? pds.ds : "store", depthClearValue: pcv ? pcv.depth : 1.0 };
827
+ if (format?.includes("stencil")) {
828
+ dsa.stencilLoadOp = pds ? pds.sl : "clear";
829
+ dsa.stencilStoreOp = pds ? pds.ss : "store";
830
+ dsa.stencilClearValue = pcv ? pcv.stencil : 0;
831
+ }
832
+ pendingDepthStencilOps = null;
833
+ pendingClearValues = null;
834
+ return dsa;
835
+ }
836
+
837
+ // The ONE target resolver for begin_render_pass_views' colour, resolve and
838
+ // depth positions: canvas → the current canvas view; tagged → txv[id & 0x7fff];
839
+ // otherwise → dfv[id]. A missing or wrong-kind entry is a NAMED failure and
840
+ // null; the caller must not fall back to another table or open an empty pass.
841
+ function attachmentFailure(role, index, why) {
842
+ onError && onError({ message: `begin_render_pass_views: ${role} attachment ${index} ${why}`, source: "command" });
843
+ return null;
844
+ }
845
+
846
+ function attachmentView(target, role, index) {
847
+ if (target === ATTACH_CANVAS) {
848
+ if (role === "depth") return attachmentFailure(role, index, "cannot be the canvas");
849
+ return targetCtx.getCurrentTexture().createView();
850
+ }
851
+ if (target === ATTACH_NONE) return attachmentFailure(role, index, "is missing");
852
+ if ((target & ATTACH_VIEW) !== 0) {
853
+ const id = target & ~ATTACH_VIEW;
854
+ const view = txv[id];
855
+ return view || attachmentFailure(role, index, `references missing texture view ${id}`);
856
+ }
857
+ const view = dfv[target];
858
+ return view || attachmentFailure(role, index, `references missing texture ${target}`);
859
+ }
860
+
861
+ // The resolved view's format, for the stencil-op decision. An explicit view's
862
+ // source texture is remembered in txs; a plain target IS the texture id. The
863
+ // canvas is never a depth attachment (attachmentView refuses it), so this is
864
+ // only called for depth targets.
865
+ function attachmentFormat(target) {
866
+ if (target === ATTACH_CANVAS) return undefined;
867
+ const tid = (target & ATTACH_VIEW) !== 0 ? txs[target & ~ATTACH_VIEW]?.tid : target;
868
+ return txd[tid]?.format;
869
+ }
870
+
728
871
  // Apply pending pass-scoped state (depth-stencil attachment, occlusion query
729
872
  // set, timestamp writes) to a render-pass descriptor. Shared by begin*Pass.
730
873
  function applyPendingPassState(pd, depthId) {
731
- if (depthId !== 0xffff && tex[depthId]) {
732
- const pds = pendingDepthStencilOps;
733
- const pcv = pendingClearValues;
734
- const dsa = { view: dfv[depthId], depthLoadOp: pds ? pds.dl : "clear", depthStoreOp: pds ? pds.ds : "store", depthClearValue: pcv ? pcv.depth : 1.0 };
735
- if (txd[depthId]?.format?.includes("stencil")) { dsa.stencilLoadOp = pds ? pds.sl : "clear"; dsa.stencilStoreOp = pds ? pds.ss : "store"; dsa.stencilClearValue = pcv ? pcv.stencil : 0; }
736
- pd.depthStencilAttachment = dsa;
737
- pendingDepthStencilOps = null;
738
- pendingClearValues = null;
874
+ if (depthId !== undefined && depthId !== 0xffff && tex[depthId]) {
875
+ pd.depthStencilAttachment = depthAttachment(dfv[depthId], txd[depthId]?.format);
739
876
  }
740
877
  if (pendingOcclusionQS) { pd.occlusionQuerySet = pendingOcclusionQS; pendingOcclusionQS = null; }
741
878
  if (pendingTimestampWrites) { pd.timestampWrites = pendingTimestampWrites; pendingTimestampWrites = null; }
@@ -780,6 +917,37 @@ export function createCommandDispatcher(device, ctx) {
780
917
  pass = enc.beginRenderPass(pd);
781
918
  }
782
919
 
920
+ // 0x55: every target is resolved through the one helper above, so colour,
921
+ // resolve and depth share the canvas/tagged-view/texture split. Any resolution
922
+ // failure reports by name and returns false BEFORE beginRenderPass — the
923
+ // decoder then aborts the buffer, never opening a pass over a missing view.
924
+ function beginRenderPassViews(attachments, depthTarget) {
925
+ if (!enc) enc = device.createCommandEncoder();
926
+ const colorAttachments = [];
927
+ for (let i = 0; i < attachments.length; i++) {
928
+ const a = attachments[i];
929
+ const view = attachmentView(a.target, "colour", i);
930
+ if (!view) return false;
931
+ const att = colorAttachment(view, a.load, a.store, a.r, a.g, a.b, a.a);
932
+ if (a.resolve !== ATTACH_NONE) {
933
+ const resolve = attachmentView(a.resolve, "resolve", i);
934
+ if (!resolve) return false;
935
+ att.resolveTarget = resolve;
936
+ }
937
+ colorAttachments.push(att);
938
+ }
939
+ const pd = { colorAttachments };
940
+ if (depthTarget !== ATTACH_NONE) {
941
+ const view = attachmentView(depthTarget, "depth", 0);
942
+ if (!view) return false;
943
+ pd.depthStencilAttachment = depthAttachment(view, attachmentFormat(depthTarget));
944
+ }
945
+ applyPendingPassState(pd);
946
+ DEBUG && dbg && console.log(`[GPU] beginRenderPassViews count=${attachments.length} depth=${depthTarget}`);
947
+ pass = enc.beginRenderPass(pd);
948
+ return true;
949
+ }
950
+
783
951
  function beginComputePass() {
784
952
  if (!enc) enc = device.createCommandEncoder();
785
953
  pass = enc.beginComputePass();
@@ -802,6 +970,7 @@ export function createCommandDispatcher(device, ctx) {
802
970
  createBindGroup,
803
971
  txv,
804
972
  txs,
973
+ txd,
805
974
  tex,
806
975
  bgl,
807
976
  device,
@@ -813,6 +982,7 @@ export function createCommandDispatcher(device, ctx) {
813
982
  ppl,
814
983
  beginRenderPass,
815
984
  beginRenderPassMRT,
985
+ beginRenderPassViews,
816
986
  beginComputePass,
817
987
  getPass: () => pass,
818
988
  setPass: (v) => {
@@ -857,6 +1027,7 @@ export function createCommandDispatcher(device, ctx) {
857
1027
  scratch,
858
1028
  decodeWasmArgs: (ab) => decodeWasmArgs(ab, { cw, ch, time, tdelta }),
859
1029
  getOnQueryResult: () => onQueryResult,
1030
+ getOnTextureReadback: () => onTextureReadback,
860
1031
  debug: () => dbg,
861
1032
  reportError: (e) => { onError && onError(e); },
862
1033
  alive: () => alive,
@@ -864,6 +1035,7 @@ export function createCommandDispatcher(device, ctx) {
864
1035
  // --- host writes (gpu-host-write.js) ---
865
1036
  bufSize,
866
1037
  bufNames,
1038
+ texNames,
867
1039
  };
868
1040
 
869
1041
  // Main dispatch - inline command constants for minification
@@ -873,8 +1045,8 @@ export function createCommandDispatcher(device, ctx) {
873
1045
  // Each handler returns the position AFTER its operands; a module returns null
874
1046
  // for an opcode it does not own. Operand widths are pinned against the Zig
875
1047
  // emitter by tests/npm/command-buffer-widths.test.js.
876
- function dispatch(cmd, view, pos) {
877
- const resourcePassResult = dispatchResourcePassCommand(cmd, view, pos, gpuOps);
1048
+ function dispatch(cmd, view, pos, end) {
1049
+ const resourcePassResult = dispatchResourcePassCommand(cmd, view, pos, gpuOps, end);
878
1050
  if (resourcePassResult !== null) return resourcePassResult;
879
1051
 
880
1052
  const queueResult = dispatchQueueCommand(cmd, view, pos, gpuOps);
@@ -920,7 +1092,12 @@ export function createCommandDispatcher(device, ctx) {
920
1092
  const end = ptr + totalLen;
921
1093
  for (let i = 0; i < cmdCount && pos < end; i++) {
922
1094
  const cmd = view.getUint8(pos++);
923
- const result = dispatch(cmd, view, pos);
1095
+ const result = dispatch(cmd, view, pos, end);
1096
+ if (result === ABORT) {
1097
+ // A known opcode whose record is malformed has already reported why;
1098
+ // the operand length is untrustworthy, so stop rather than desync.
1099
+ break;
1100
+ }
924
1101
  if (result === UNKNOWN_CMD) {
925
1102
  // Operand length unknown → advancing would re-read operand bytes as
926
1103
  // opcodes (a desync). Abort the buffer and tell the host, loudly.
@@ -966,6 +1143,7 @@ export function createCommandDispatcher(device, ctx) {
966
1143
  wcr.length = bgd.length = txd.length = txs.length = bufUsage.length = bufSize.length = 0;
967
1144
  qs.length = bun.length = 0;
968
1145
  bufNames.clear();
1146
+ texNames.clear();
969
1147
  curPip = -1;
970
1148
  pendingReadbacks.length = 0;
971
1149
  pendingOcclusionQS = pendingTimestampWrites = null;
@@ -975,7 +1153,7 @@ export function createCommandDispatcher(device, ctx) {
975
1153
  // between the device teardown and the terminate — so a dispatcher can
976
1154
  // genuinely outlive its device, and `mem` in particular pins the executor's
977
1155
  // whole WASM memory.
978
- onQueryResult = onError = onShaderError = null;
1156
+ onQueryResult = onTextureReadback = onError = onShaderError = null;
979
1157
  uniformMap = null;
980
1158
  controlTable = null;
981
1159
  mem = null;
@@ -1103,8 +1281,19 @@ export function createCommandDispatcher(device, ctx) {
1103
1281
  const d = txd[id];
1104
1282
  if (!d || !d.canvasBound || !tex[id]) continue;
1105
1283
  tex[id].destroy?.();
1106
- const desc = { size: [scaleExtent(w, d.canvasScale || 1), scaleExtent(h, d.canvasScale || 1), d.depth || 1], format: d.format, usage: d.usage, sampleCount: d.sampleCount || 1 };
1107
- if (d.dimension) desc.dimension = d.dimension;
1284
+ // The descriptor record is what a later write_texture validates against;
1285
+ // a resized canvas-bound texture must not keep its creation-time extent.
1286
+ d.size.width = scaleExtent(w, d.canvasScale || 1);
1287
+ d.size.height = scaleExtent(h, d.canvasScale || 1);
1288
+ const size = [d.size.width, d.size.height, d.size.depthOrArrayLayers];
1289
+ const desc = {
1290
+ size,
1291
+ format: d.format,
1292
+ usage: d.usage,
1293
+ sampleCount: d.sampleCount,
1294
+ mipLevelCount: d.mipLevelCount,
1295
+ dimension: d.dimension,
1296
+ };
1108
1297
  installTexture(id, device.createTexture(desc));
1109
1298
  }
1110
1299
  // Explicit (texture-view …) resources of a recreated texture, remade from
@@ -1151,6 +1340,7 @@ export function createCommandDispatcher(device, ctx) {
1151
1340
  setOnShaderError(fn) { onShaderError = fn; },
1152
1341
  setOnError(fn) { onError = fn; },
1153
1342
  setOnQueryResult(fn) { onQueryResult = fn; },
1343
+ setOnTextureReadback(fn) { onTextureReadback = fn; },
1154
1344
  setUniformTable,
1155
1345
  setControlTable,
1156
1346
  setUniform,
@@ -1159,6 +1349,14 @@ export function createCommandDispatcher(device, ctx) {
1159
1349
  setBufferNames: (names) => setHostBufferNames(gpuOps, names),
1160
1350
  writeBuffers: (buffers, counter) => hostWriteBuffers(gpuOps, buffers, counter),
1161
1351
  getBuffers: () => listBuffers(gpuOps),
1352
+ // Host texture writes and reflection by SJON texture name; bodies in
1353
+ // gpu-host-texture.js.
1354
+ setTextureNames: (names) => setHostTextureNames(gpuOps, names),
1355
+ writeTextures: (textures, counter) => hostWriteTextures(gpuOps, textures, counter),
1356
+ getTextures: () => listTextures(gpuOps),
1357
+ // Current write-validation descriptor for a created texture, or null. The
1358
+ // reflection surfaces read this record rather than re-decoding bindings.
1359
+ getTextureDescriptor: (id) => txd[id] ?? null,
1162
1360
  getStats,
1163
1361
  execute,
1164
1362
  destroy,
package/src/init-core.js CHANGED
@@ -75,6 +75,9 @@ export function routeWorkerMessages(worker, options) {
75
75
  if (e.data.type === "queryResult" && options.onQueryResult) {
76
76
  options.onQueryResult(e.data.data);
77
77
  }
78
+ if (e.data.type === "textureReadback" && options.onTextureReadback) {
79
+ options.onTextureReadback(e.data.data);
80
+ }
78
81
  };
79
82
  worker.onerror = (e) => {
80
83
  if (options.onError) options.onError(new Error(e.message || "Worker error"));
@@ -297,6 +300,24 @@ export function createPngine(internal) {
297
300
  // anyway. A wedged or already-dead agent must never strand the thread.
298
301
  const DESTROY_ACK_TIMEOUT_MS = 250;
299
302
 
303
+ /**
304
+ * The byte-readback event `onTextureReadback` receives (plan 05, "Readback
305
+ * contract").
306
+ *
307
+ * @typedef {object} TextureReadback
308
+ * @property {string|null} texture - public `(texture :name …)`, or null for an old/unnamed payload
309
+ * @property {string|null} buffer - public `(buffer :name …)`, or null for an old/unnamed payload
310
+ * @property {number} offset - destination layout offset
311
+ * @property {number} size - copied window in bytes, row padding included (final padding excluded)
312
+ * @property {Uint8Array} bytes - owned copy; the caller may retain or mutate it
313
+ * @property {number} bytesPerRow - stride the bytes use
314
+ * @property {number} rowsPerImage - rows per image the bytes use
315
+ * @property {number} mipLevel
316
+ * @property {[number, number, number]} origin
317
+ * @property {"all"|"depth-only"|"stencil-only"} aspect
318
+ * @property {[number, number, number]} copySize
319
+ */
320
+
300
321
  // Destroy a pngine instance: stop the RAF loop, tear down audio, detach every
301
322
  // listener, let the worker release its GPU device, and terminate it.
302
323
  //
package/src/init.js CHANGED
@@ -32,6 +32,10 @@ let workerUrl = null;
32
32
  * contents of every `map-read` buffer the frame copies into, once per submit,
33
33
  * as one number per 64-bit lane. Written for timestamp and occlusion query
34
34
  * results; a compute readback has to write 64-bit lanes to survive it.
35
+ * @param {(readback: import("./init-core.js").TextureReadback) => void} [options.onTextureReadback] -
36
+ * Receives the bytes of every `copy-texture-to-buffer` into a MAP_READ|COPY_DST
37
+ * buffer, once per submit, as an owned Uint8Array plus the padded layout and
38
+ * subresource metadata that describe exactly what those bytes contain.
35
39
  * @returns {Promise<Pngine>}
36
40
  */
37
41
  export async function pngine(source, options = {}) {