pngine 2.2.0 → 3.0.1

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/core.js CHANGED
@@ -34,11 +34,16 @@ export function createCoreDispatcher(device, ctx) {
34
34
  },
35
35
 
36
36
  /**
37
- * Execute a command buffer at the given pointer.
37
+ * Execute a command buffer at the given pointer. Returns the
38
+ * dispatcher's promise, so a host can sequence an init stream that
39
+ * carries an async create (image bitmap, wasm module) before its first
40
+ * frame, and a rejection reaches the caller instead of becoming an
41
+ * unhandled rejection.
38
42
  * @param {number} ptr - Command buffer pointer in WASM memory
43
+ * @returns {Promise<void>|void}
39
44
  */
40
45
  execute(ptr) {
41
- dispatcher.execute(ptr);
46
+ return dispatcher.execute(ptr);
42
47
  },
43
48
 
44
49
  /**
@@ -127,11 +132,11 @@ export async function getDevice(adapter) {
127
132
  * @param {HTMLCanvasElement} canvas
128
133
  * @param {GPUDevice} device
129
134
  * @param {"opaque"|"premultiplied"} [alphaMode] - pass canvasAlphaMode(bytecode)
130
- * to honor an authored `(canvas :alpha-mode …)`; defaults to the historical
131
- * premultiplied (spec/04).
135
+ * to honor an authored `(canvas :alpha-mode …)`; defaults to the
136
+ * GPUCanvasConfiguration default, opaque (spec/04, spec/09 D).
132
137
  * @returns {GPUCanvasContext}
133
138
  */
134
- export function configureCanvas(canvas, device, alphaMode = 'premultiplied') {
139
+ export function configureCanvas(canvas, device, alphaMode = 'opaque') {
135
140
  const ctx = canvas.getContext('webgpu');
136
141
  if (!ctx) {
137
142
  throw new Error('Failed to get WebGPU context');
@@ -96,7 +96,11 @@ export function decodeTextureViewDescriptor(bytes) {
96
96
  * @returns {object} - GPUSamplerDescriptor-shaped object
97
97
  */
98
98
  export function decodeSamplerDescriptor(bytes) {
99
- const desc = /** @type {Record<string, string|number>} */ ({ magFilter: "linear", minFilter: "linear", addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge" });
99
+ // Seeded with the GPUSamplerDescriptor defaults (spec/09 step D flipped the
100
+ // filters from linear). The encoder always writes all four fields, so this
101
+ // seed only shows through for a descriptor that omits one — which is to say,
102
+ // never from this compiler.
103
+ const desc = /** @type {Record<string, string|number>} */ ({ magFilter: "nearest", minFilter: "nearest", addressModeU: "clamp-to-edge", addressModeV: "clamp-to-edge" });
100
104
  const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
101
105
  let off = 2;
102
106
  const fc = bytes[1];
@@ -146,7 +146,14 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
146
146
  const dv = new DataView(d.buffer, d.byteOffset, d.byteLength);
147
147
  let off = 0;
148
148
 
149
- // Parse colorFormats
149
+ // Parse colorFormats. Count 0 is a LEGACY sentinel, not a live default:
150
+ // `:color-formats` became required in spec/09 step F, so no payload minted
151
+ // since then can reach the branch below. It stays because a count-0
152
+ // descriptor is frozen wire (docs/abi.md §6.5, change policy clause 2) and
153
+ // this runtime has to keep decoding every executor ever shipped — but it
154
+ // is the guess that made the key worth requiring: a bundle recorded for an
155
+ // offscreen target replayed here as if it had been recorded for the
156
+ // canvas, and only the GPU disagreed.
150
157
  const cfCount = d[off++];
151
158
  /** @type {GPUTextureFormat[]} */
152
159
  const colorFormats = [];
@@ -206,12 +213,22 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
206
213
  }
207
214
 
208
215
  // === Pass Operations (0x10-0x1A) ===
209
- case 0x10: { // begin_render_pass (with optional resolveTarget)
216
+ case 0x10: { // begin_render_pass — LEGACY 4×u8 clear (see 0x53)
217
+ // `/255` here rather than in ops.colorAttachment: this opcode is the only
218
+ // place a quantized clear enters, and no payload minted since spec/09
219
+ // step D carries one. Kept because the JS side decodes every executor
220
+ // ever shipped (docs/abi.md clause 1).
210
221
  const resolveId = view.getUint16(pos + 10, true);
211
222
  ops.curPip = -1;
212
- ops.beginRenderPass(view.getUint16(pos, true), view.getUint8(pos + 2), view.getUint8(pos + 3), view.getUint16(pos + 4, true), view.getUint8(pos + 6), view.getUint8(pos + 7), view.getUint8(pos + 8), view.getUint8(pos + 9), resolveId);
223
+ ops.beginRenderPass(view.getUint16(pos, true), view.getUint8(pos + 2), view.getUint8(pos + 3), view.getUint16(pos + 4, true), view.getUint8(pos + 6) / 255, view.getUint8(pos + 7) / 255, view.getUint8(pos + 8) / 255, view.getUint8(pos + 9) / 255, resolveId);
213
224
  return pos + 12;
214
225
  }
226
+ case 0x53: { // begin_render_pass_f32 (with optional resolveTarget)
227
+ const resolveId = view.getUint16(pos + 22, true);
228
+ ops.curPip = -1;
229
+ ops.beginRenderPass(view.getUint16(pos, true), view.getUint8(pos + 2), view.getUint8(pos + 3), view.getUint16(pos + 4, true), view.getFloat32(pos + 6, true), view.getFloat32(pos + 10, true), view.getFloat32(pos + 14, true), view.getFloat32(pos + 18, true), resolveId);
230
+ return pos + 24;
231
+ }
215
232
  case 0x11: { // begin_compute_pass
216
233
  ops.curPip = -1;
217
234
  ops.beginComputePass();
@@ -300,7 +317,24 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
300
317
  if (bundles.length > 0) requirePass(ops, "executeBundles")?.executeBundles(bundles);
301
318
  return pos + 1 + count * 2;
302
319
  }
303
- case 0x1B: { // begin_render_pass_mrt
320
+ case 0x1B: { // begin_render_pass_mrt — LEGACY 4×u8 clear (see 0x54)
321
+ ops.curPip = -1;
322
+ let off = pos;
323
+ const count = view.getUint8(off++);
324
+ const attachments = [];
325
+ for (let i = 0; i < count; i++) {
326
+ const tid = view.getUint16(off, true); off += 2;
327
+ const load = view.getUint8(off++);
328
+ const store = view.getUint8(off++);
329
+ const r = view.getUint8(off++) / 255, g = view.getUint8(off++) / 255;
330
+ const b = view.getUint8(off++) / 255, a = view.getUint8(off++) / 255;
331
+ attachments.push({ tid, load, store, r, g, b, a });
332
+ }
333
+ const depthId = view.getUint16(off, true); off += 2;
334
+ ops.beginRenderPassMRT(attachments, depthId);
335
+ return off;
336
+ }
337
+ case 0x54: { // begin_render_pass_mrt_f32
304
338
  ops.curPip = -1;
305
339
  let off = pos;
306
340
  const count = view.getUint8(off++);
@@ -309,8 +343,10 @@ export function dispatchResourcePassCommand(cmd, view, pos, ops) {
309
343
  const tid = view.getUint16(off, true); off += 2;
310
344
  const load = view.getUint8(off++);
311
345
  const store = view.getUint8(off++);
312
- const r = view.getUint8(off++), g = view.getUint8(off++);
313
- const b = view.getUint8(off++), a = view.getUint8(off++);
346
+ const r = view.getFloat32(off, true); off += 4;
347
+ const g = view.getFloat32(off, true); off += 4;
348
+ const b = view.getFloat32(off, true); off += 4;
349
+ const a = view.getFloat32(off, true); off += 4;
314
350
  attachments.push({ tid, load, store, r, g, b, a });
315
351
  }
316
352
  const depthId = view.getUint16(off, true); off += 2;
package/src/gpu.js CHANGED
@@ -77,21 +77,24 @@ const PNGB_MAGIC = 0x42474e50; // "PNGB" little-endian
77
77
  // flags bit 2 — payload carries an authored device-limits table appended after
78
78
  // the animation table; its byte offset lives in the 3 reserved header bytes.
79
79
  const PNGB_FLAG_DEVICE_LIMITS = 0x04;
80
- // flags bit 3 — the author requested an OPAQUE canvas ((canvas :alpha-mode
81
- // opaque)); clear = the historical premultiplied configure. (spec/04)
82
- const PNGB_FLAG_OPAQUE_CANVAS = 0x08;
80
+ // flags bit 3 — the author requested a PREMULTIPLIED canvas ((canvas
81
+ // :alpha-mode premultiplied)); clear = "opaque", the GPUCanvasConfiguration
82
+ // default. The bit used to mean the opposite, back when this runtime's own
83
+ // default was premultiplied. (spec/04, spec/09 D)
84
+ const PNGB_FLAG_PREMULTIPLIED_CANVAS = 0x08;
83
85
 
84
86
  /**
85
- * Canvas alphaMode the payload requests: "opaque" when header flag bit 3 is
86
- * set, else the historical "premultiplied" (also for non-PNGB/short buffers).
87
+ * Canvas alphaMode the payload requests: "premultiplied" when header flag bit 3
88
+ * is set, else "opaque" — which is also what a non-PNGB or short buffer gets,
89
+ * since the spec default is the right answer when the payload says nothing.
87
90
  * @param {Uint8Array|null|undefined} bytecode
88
91
  * @returns {"opaque"|"premultiplied"}
89
92
  */
90
93
  export function canvasAlphaMode(bytecode) {
91
- if (!bytecode || bytecode.length < PNGB_HEADER_SIZE) return "premultiplied";
94
+ if (!bytecode || bytecode.length < PNGB_HEADER_SIZE) return "opaque";
92
95
  const view = new DataView(bytecode.buffer, bytecode.byteOffset, bytecode.byteLength);
93
- if (view.getUint32(0, true) !== PNGB_MAGIC) return "premultiplied";
94
- return (view.getUint16(6, true) & PNGB_FLAG_OPAQUE_CANVAS) ? "opaque" : "premultiplied";
96
+ if (view.getUint32(0, true) !== PNGB_MAGIC) return "opaque";
97
+ return (view.getUint16(6, true) & PNGB_FLAG_PREMULTIPLIED_CANVAS) ? "premultiplied" : "opaque";
95
98
  }
96
99
 
97
100
  /**
@@ -381,14 +384,21 @@ export function createCommandDispatcher(device, ctx) {
381
384
  // Skipped entirely when no host is listening, and that is correctness rather
382
385
  // than thrift: pushing a scope SUPPRESSES onuncapturederror for the enclosed
383
386
  // call, so scoping without reporting would lose the error altogether.
387
+ //
388
+ // The pop is in a `finally`: a create that THROWS (a TypeError from a missing
389
+ // required member on a desynced stream) used to leave the scope pushed, and
390
+ // a pushed scope captures every later validation error on the device —
391
+ // onuncapturederror never fired again.
384
392
  function scoped(kind, id, make) {
385
393
  if (!onError) return make();
386
394
  device.pushErrorScope("validation");
387
- const resource = make();
388
- device.popErrorScope().then((e) => {
389
- if (e) onError({ message: `${kind}(${id}) failed validation: ${e.message}`, source: "validation" });
390
- });
391
- return resource;
395
+ try {
396
+ return make();
397
+ } finally {
398
+ device.popErrorScope().then((e) => {
399
+ if (e) onError({ message: `${kind}(${id}) failed validation: ${e.message}`, source: "validation" });
400
+ });
401
+ }
392
402
  }
393
403
 
394
404
  // Decode texture format enum - uses centralized lookup from enums.js
@@ -441,7 +451,12 @@ export function createCommandDispatcher(device, ctx) {
441
451
  layout: (desc.layoutId !== undefined && ppl[desc.layoutId]) ? ppl[desc.layoutId] : "auto",
442
452
  vertex: {
443
453
  module: shd[desc.vertex?.shader ?? 0],
444
- entryPoint: desc.vertex?.entryPoint ?? "vs_main",
454
+ // No `?? "vs_main"` fallback: the compiler resolves every stage's entry
455
+ // point (explicit `:entry`, else the module's sole entry for the
456
+ // stage) and always writes a real name. A fabricated one here could only
457
+ // hide a compiler bug behind a driver-level abort. Same below and in
458
+ // createComputePipeline.
459
+ entryPoint: desc.vertex.entryPoint,
445
460
  buffers: desc.vertex?.buffers ?? [],
446
461
  },
447
462
  primitive: desc.primitive ?? { topology: "triangle-list" },
@@ -461,7 +476,7 @@ export function createCommandDispatcher(device, ctx) {
461
476
  DEBUG && dbg && console.log(`[GPU] targets:`, JSON.stringify(targets));
462
477
  pipeDesc.fragment = {
463
478
  module: shd[desc.fragment.shader ?? desc.vertex?.shader ?? 0],
464
- entryPoint: desc.fragment.entryPoint ?? "fs_main",
479
+ entryPoint: desc.fragment.entryPoint,
465
480
  targets,
466
481
  };
467
482
  } else {
@@ -479,7 +494,10 @@ export function createCommandDispatcher(device, ctx) {
479
494
  const v = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
480
495
  const shaderId = v.getUint16(1, true); // bytes 1-2, little endian
481
496
  const entryLen = bytes[3];
482
- const entryPoint = entryLen > 0 ? new TextDecoder().decode(bytes.slice(4, 4 + entryLen)) : "main";
497
+ // A zero-length entry is a malformed descriptor, not a request for "main":
498
+ // the compiler resolves the sole compute entry when `:entry` is omitted.
499
+ if (entryLen === 0) return emptyDescriptor("createComputePipeline", id);
500
+ const entryPoint = new TextDecoder().decode(bytes.slice(4, 4 + entryLen));
483
501
  DEBUG && dbg && console.log(`[GPU] createComputePipeline(${id}) shader=${shaderId} entry=${entryPoint}`);
484
502
  // Check for optional layout ID after entry point bytes
485
503
  const layoutOff = 4 + entryLen;
@@ -526,11 +544,15 @@ export function createCommandDispatcher(device, ctx) {
526
544
  // rebuilt textures would otherwise leave every cached entry holding a view
527
545
  // of a destroyed texture. An explicit-BGL group never rebuilds (see below),
528
546
  // so its `alt` stays null.
529
- bgd[id] = { layoutId, gi, entries, alt: null };
530
547
  DEBUG && dbg && console.log(`[GPU] createBindGroup(${id}) layoutId=${fmtLayoutId(layoutId)} entries=[${entries.map(e => `{b=${e.binding} rt=${e.rt} rid=${e.rid}}`).join(',')}]`);
531
548
  const layout = resolveBindGroupLayout(layoutId, gi);
532
549
  if (!layout) return;
550
+ // `bgd` (the rebuild recipe set_bind_group reads) is written only once the
551
+ // group EXISTS: written first, a throwing createBindGroup left a recipe
552
+ // with no group behind it, and every later set_bind_group re-threw from
553
+ // the rebuild — once per frame, an undeduped error post at 60 Hz.
533
554
  bg[id] = scoped("createBindGroup", id, () => device.createBindGroup({ layout, entries: buildBindGroupEntries(entries) }));
555
+ bgd[id] = { layoutId, gi, entries, alt: null };
534
556
  }
535
557
 
536
558
  // `layout_id` names one of two id spaces, discriminated by BGL_TAG: tagged is a
@@ -593,11 +615,14 @@ export function createCommandDispatcher(device, ctx) {
593
615
  });
594
616
  }
595
617
 
596
- // Build one color attachment. r/g/b/a are 0-255 bytes; load 1=clear else load,
597
- // store 0=store else discard.
618
+ // Build one color attachment. r/g/b/a are GPUColor channels — plain numbers,
619
+ // not clamped and not 0-255 bytes. They WERE bytes decoding `/255` until
620
+ // spec/09 step D; the `/255` now lives in the two legacy opcode cases
621
+ // (0x10/0x1B), which is where the lossy wire actually is. load 1=clear else
622
+ // load, store 0=store else discard.
598
623
  function colorAttachment(view, load, store, r, g, b, a) {
599
624
  return { view, loadOp: load === 1 ? "clear" : "load", storeOp: store === 0 ? "store" : "discard",
600
- clearValue: { r: (r || 0) / 255, g: (g || 0) / 255, b: (b || 0) / 255, a: (a || 0) / 255 } };
625
+ clearValue: { r: r || 0, g: g || 0, b: b || 0, a: a || 0 } };
601
626
  }
602
627
 
603
628
  // Apply pending pass-scoped state (depth-stencil attachment, occlusion query
package/src/init-core.js CHANGED
@@ -344,6 +344,12 @@ export function destroy(p) {
344
344
  worker.postMessage({ type: "destroy" });
345
345
  }
346
346
 
347
+ // A placeholder canvas initFromImage created is removed from the DOM, not
348
+ // merely forgotten: each `pngine("#img")`/destroy cycle used to stack one
349
+ // more absolutely-positioned canvas over the image, holding its last frame.
350
+ if (i.createdCanvas) i.canvas?.remove?.();
351
+ i.createdCanvas = false;
352
+
347
353
  // Empty the bag the getters read through — this is what actually releases the
348
354
  // instance, however long the host holds `p`.
349
355
  i.worker = null;
package/src/init.js CHANGED
@@ -28,11 +28,18 @@ let workerUrl = null;
28
28
  * @param {(err: Error) => void} [options.onError] - Receives worker errors,
29
29
  * WGSL compilation errors (name "PngineShaderError", with lineNum/linePos/context),
30
30
  * and WebGPU uncaptured errors (name "PngineGPUError")
31
+ * @param {(values: number[]) => void} [options.onQueryResult] - Receives the
32
+ * contents of every `map-read` buffer the frame copies into, once per submit,
33
+ * as one number per 64-bit lane. Written for timestamp and occlusion query
34
+ * results; a compute readback has to write 64-bit lanes to survive it.
31
35
  * @returns {Promise<Pngine>}
32
36
  */
33
37
  export async function pngine(source, options = {}) {
34
38
  // Resolve source to canvas + bytecode + raw PNG data
35
39
  let canvas, bytecode, rawData;
40
+ // True when initFromImage created the placeholder canvas itself — then it is
41
+ // ours to remove on destroy (a host-supplied canvas is the host's).
42
+ let createdCanvas = false;
36
43
 
37
44
  if (typeof source === "string") {
38
45
  // Check for CSS selector (# or . but not relative paths like ./ or ../)
@@ -42,7 +49,7 @@ export async function pngine(source, options = {}) {
42
49
  if (!el) throw new Error(`Element not found: ${source}`);
43
50
 
44
51
  if (el instanceof HTMLImageElement) {
45
- ({ canvas, bytecode, rawData } = await initFromImage(el, options));
52
+ ({ canvas, bytecode, rawData, createdCanvas } = await initFromImage(el, options));
46
53
  } else if (el instanceof HTMLCanvasElement) {
47
54
  canvas = el;
48
55
  throw new Error("Canvas source requires URL or data");
@@ -58,7 +65,7 @@ export async function pngine(source, options = {}) {
58
65
  bytecode = await extractBytecode(rawData);
59
66
  }
60
67
  } else if (source instanceof HTMLImageElement) {
61
- ({ canvas, bytecode, rawData } = await initFromImage(source, options));
68
+ ({ canvas, bytecode, rawData, createdCanvas } = await initFromImage(source, options));
62
69
  } else if (
63
70
  source instanceof ArrayBuffer ||
64
71
  source instanceof Uint8Array ||
@@ -78,34 +85,47 @@ export async function pngine(source, options = {}) {
78
85
  // Pointer/keyboard tracking — must attach before transferControlToOffscreen.
79
86
  const { pointer: ptr, detach: detachListeners } = attachPointerTracking(canvas);
80
87
 
81
- // Get OffscreenCanvas
82
- const offscreen = canvas.transferControlToOffscreen();
83
-
84
- // Spawn worker
85
- const worker = new Worker(getWorkerUrl(), { type: "module" });
86
-
87
- // Compute WASM URL - must be absolute for worker blob context.
88
- // ../wasm/ resolves from both src/ (repo dev) and dist/ (published bundle)
89
- // to the package's wasm/pngine.wasm fallback.
90
- const wasmUrl = options.wasmUrl
91
- ? new URL(options.wasmUrl, window.location.href).href
92
- : new URL("../wasm/pngine.wasm", import.meta.url).href;
93
-
94
- // Wait for ready — slice bytecode so the original buffer stays alive for
95
- // extractAudio below.
96
- const bc = bytecode.slice();
97
- const result = await awaitWorkerReady(
98
- worker,
99
- {
100
- type: "init",
101
- canvas: offscreen,
102
- bytecode: bc,
103
- wasmUrl,
104
- debug: options.debug || false,
105
- },
106
- [offscreen, bc.buffer],
107
- options
108
- );
88
+ // From here until the handle exists, the listeners are ours to release: a
89
+ // worker that fails to come up (WebGPU unsupported, a refused payload, the
90
+ // 15 s timeout, `new Worker` throwing under CSP) rejects from inside this
91
+ // block, and the seven listeners — two of them on `document` — used to
92
+ // outlive the rejection for the page's life. LEAK-06-C closed the audio
93
+ // phase one await later; this is the await before it.
94
+ let worker, result;
95
+ try {
96
+ // Get OffscreenCanvas
97
+ const offscreen = canvas.transferControlToOffscreen();
98
+
99
+ // Spawn worker
100
+ worker = new Worker(getWorkerUrl(), { type: "module" });
101
+
102
+ // Compute WASM URL - must be absolute for worker blob context.
103
+ // ../wasm/ resolves from both src/ (repo dev) and dist/ (published bundle)
104
+ // to the package's wasm/pngine.wasm fallback.
105
+ const wasmUrl = options.wasmUrl
106
+ ? new URL(options.wasmUrl, window.location.href).href
107
+ : new URL("../wasm/pngine.wasm", import.meta.url).href;
108
+
109
+ // Wait for ready — slice bytecode so the original buffer stays alive for
110
+ // extractAudio below.
111
+ const bc = bytecode.slice();
112
+ result = await awaitWorkerReady(
113
+ worker,
114
+ {
115
+ type: "init",
116
+ canvas: offscreen,
117
+ bytecode: bc,
118
+ wasmUrl,
119
+ debug: options.debug || false,
120
+ },
121
+ [offscreen, bc.buffer],
122
+ options
123
+ );
124
+ } catch (err) {
125
+ detachListeners();
126
+ if (createdCanvas) canvas.remove?.();
127
+ throw err;
128
+ }
109
129
 
110
130
  // The instance exists BEFORE the audio phase, because the audio phase is the
111
131
  // first thing that can fail after the worker reports ready — and by then the
@@ -118,6 +138,7 @@ export async function pngine(source, options = {}) {
118
138
  // (Report logical/CSS dimensions, not physical.)
119
139
  const p = createPngine({
120
140
  canvas,
141
+ createdCanvas,
121
142
  worker,
122
143
  pointer: ptr,
123
144
  detachListeners,
@@ -205,7 +226,7 @@ async function initFromImage(img, options) {
205
226
  const rawData = await resp.arrayBuffer();
206
227
  const bytecode = await extractBytecode(rawData);
207
228
 
208
- return { canvas, bytecode, rawData };
229
+ return { canvas, bytecode, rawData, createdCanvas: !options.canvas };
209
230
  }
210
231
 
211
232
  // createPngine + destroy are shared with the viewer profile (init-core.js).
package/src/mini.js CHANGED
@@ -50,7 +50,7 @@ async function D(d) {
50
50
  // every frame call got an empty one and case 19's rebuild branch could never
51
51
  // run (see there).
52
52
  function X(d, ds, p, e, V, dv, ctx, fm, bf, sh, pp, cp, bg, tm, W, H, pt, bd, ti) {
53
- const R=o=>V.getUint16(o,!0),G=o=>V.getUint32(o,!0);
53
+ const R=o=>V.getUint16(o,!0),G=o=>V.getUint32(o,!0),F=o=>V.getFloat32(o,!0);
54
54
  const rs = (o, l) => new TextDecoder().decode(d.subarray(ds + o, ds + o + l));
55
55
  e = p + e; let ps, en, cP = -1;
56
56
  while (p < e) {
@@ -75,7 +75,7 @@ function X(d, ds, p, e, V, dv, ctx, fm, bf, sh, pp, cp, bg, tm, W, H, pt, bd, ti
75
75
  const id = R(p);
76
76
  if (!pp[id]) {
77
77
  const dd = JSON.parse(rs(G(p+2), G(p+6)));
78
- pp[id] = dv.createRenderPipeline({layout:'auto', vertex:{module:sh[dd.vertex?.shader??0],entryPoint:dd.vertex?.entryPoint??'vs',buffers:dd.vertex?.buffers??[]}, fragment:{module:sh[dd.fragment?.shader??0],entryPoint:dd.fragment?.entryPoint??'fs',targets:[{format:fm}]}, primitive:dd.primitive??{topology:'triangle-list'}});
78
+ pp[id] = dv.createRenderPipeline({layout:'auto', vertex:{module:sh[dd.vertex?.shader??0],entryPoint:dd.vertex?.entryPoint,buffers:dd.vertex?.buffers??[]}, fragment:{module:sh[dd.fragment?.shader??0],entryPoint:dd.fragment?.entryPoint,targets:[{format:fm}]}, primitive:dd.primitive??{topology:'triangle-list'}});
79
79
  }
80
80
  p += 10; break;
81
81
  }
@@ -83,7 +83,7 @@ function X(d, ds, p, e, V, dv, ctx, fm, bf, sh, pp, cp, bg, tm, W, H, pt, bd, ti
83
83
  const id = R(p);
84
84
  if (!cp[id]) {
85
85
  const dd = JSON.parse(rs(G(p+2), G(p+6)));
86
- cp[id] = dv.createComputePipeline({layout:'auto', compute:{module:sh[dd.compute?.shader??0],entryPoint:dd.compute?.entryPoint??'main'}});
86
+ cp[id] = dv.createComputePipeline({layout:'auto', compute:{module:sh[dd.compute?.shader??0],entryPoint:dd.compute?.entryPoint}});
87
87
  }
88
88
  p += 10; break;
89
89
  }
@@ -113,7 +113,16 @@ function X(d, ds, p, e, V, dv, ctx, fm, bf, sh, pp, cp, bg, tm, W, H, pt, bd, ti
113
113
  // `a` caches the per-pipeline auto-layout rebuilds case 19 makes.
114
114
  bd[id] = {pl, gi, es, a: /** @type {Record<number, GPUBindGroup>|null} */ (null)}; bg[id] = dv.createBindGroup({layout:(pp[pl]||cp[pl]).getBindGroupLayout(gi),entries:es}); p += 12; break;
115
115
  }
116
- case 16: cP = -1; en = dv.createCommandEncoder(); ps = en.beginRenderPass({colorAttachments:[{view:ctx.getCurrentTexture().createView(),loadOp:'clear',storeOp:'store',clearValue:[d[p+6]/255,d[p+7]/255,d[p+8]/255,d[p+9]/255]}]}); p += 10; break;
116
+ // 0x53 begin_render_pass_f32 — the clear value is four f32s, not four
117
+ // bytes decoding /255 (spec/09 step D). pNGf v1's 0x10 is refused at the
118
+ // chunk header, so there is no second decoder here.
119
+ // One encoder per frame, like case 17: an unconditional
120
+ // createCommandEncoder here REPLACED the encoder a preceding compute
121
+ // pass was recording into, unfinished and unsubmitted — the compute
122
+ // pass never reached the GPU and one abandoned encoder was garbage per
123
+ // frame. The load op honours the wire byte (1 = clear, else load), as
124
+ // gpu.js does; a two-render-pass frame must not clear twice.
125
+ case 83: cP = -1; if (!en) en = dv.createCommandEncoder(); ps = en.beginRenderPass({colorAttachments:[{view:ctx.getCurrentTexture().createView(),loadOp:d[p+2]===1?'clear':'load',storeOp:'store',clearValue:[F(p+6),F(p+10),F(p+14),F(p+18)]}]}); p += 22; break;
117
126
  case 17: cP = -1; if (!en) en = dv.createCommandEncoder(); ps = en.beginComputePass(); break;
118
127
  case 18: { const pid = R(p); cP = pid; ps.setPipeline(pp[pid]||cp[pid]); p += 2; break; }
119
128
  // Auto-layout rebuild, cached per (bind group, pipeline) in `dd.a` —
@@ -213,7 +222,7 @@ export async function miniPngine(canvas, source, opts) {
213
222
  // and dv.destroy() twice — and it is also what keeps play() from resurrecting
214
223
  // the loop, since WebGPU calls on a destroyed device do not throw
215
224
  // synchronously and frame()'s try/catch would never have fired.
216
- let on = 0, t0 = 0, tm = 0, raf = 0, dead = 0;
225
+ let on = 0, t0 = 0, tm = 0, raf = 0, dead = 0, lost = 0;
217
226
  let ax, ab2, sr, ctx;
218
227
  const teardown = () => {
219
228
  if (dead) return; dead = 1;
@@ -231,10 +240,18 @@ export async function miniPngine(canvas, source, opts) {
231
240
  };
232
241
 
233
242
  try {
243
+ // pNGf version (fl[0], the payload's own header — the chunk wrapper's two
244
+ // bytes are already stripped). mini follows flat.zig's command set exactly
245
+ // and carries no legacy decoders, so an unrecognised version has to be
246
+ // refused: a v1 payload's begin_render_pass (0x10) would otherwise fall
247
+ // through the switch mid-stream and desync everything after it. Nothing
248
+ // read this byte before spec/09 step D.
249
+ if (fl[0] !== 2) throw new Error(`pngine/mini: pNGf version ${fl[0]} is not supported by this player (expected 2)`);
234
250
  ctx = /** @type {GPUCanvasContext} */ (canvas.getContext('webgpu'));
235
251
  const fm = navigator.gpu.getPreferredCanvasFormat();
236
- // pNGf flags bit 0 = opaque canvas (mirrors the PNGB header flag; spec/04).
237
- ctx.configure({device: dv, format: fm, alphaMode: fl[1] & 1 ? 'opaque' : 'premultiplied'});
252
+ // pNGf flags bit 0 = premultiplied canvas (mirrors the PNGB header flag).
253
+ // Clear = 'opaque', the GPUCanvasConfiguration default. (spec/04, spec/09 D)
254
+ ctx.configure({device: dv, format: fm, alphaMode: fl[1] & 1 ? 'premultiplied' : 'opaque'});
238
255
 
239
256
  const W = canvas.width, H = canvas.height;
240
257
  const V = new DataView(fl.buffer, fl.byteOffset, fl.byteLength);
@@ -269,9 +286,13 @@ export async function miniPngine(canvas, source, opts) {
269
286
  // teardown — ignore it, and so is anything arriving after `dead` (a device can
270
287
  // be lost for another reason in the same turn we tear it down). mini keeps no
271
288
  // self-recovery (size play); the host decides whether to re-create the player.
289
+ // `lost` goes up too: play() checks it, and without it a host play button
290
+ // after the device-lost error restarted the rAF chain at 60 Hz on a lost
291
+ // device for the page's life (LEAK-05-D's other trigger). Not `dead` —
292
+ // that is teardown's own latch, and destroy() after a loss must still run.
272
293
  dv.lost.then(info => {
273
294
  if (dead || info.reason === 'destroyed') return;
274
- on = 0; cancelAnimationFrame(raf);
295
+ on = 0; lost = 1; cancelAnimationFrame(raf);
275
296
  report(gpuError('pngine/mini: WebGPU device lost — ' + (info.message || info.reason || 'unknown'), 'device-lost'));
276
297
  });
277
298
 
@@ -309,7 +330,7 @@ export async function miniPngine(canvas, source, opts) {
309
330
  // reschedules at 60Hz for the page's life, retaining the canvas, the payload
310
331
  // and every closure in this function.
311
332
  play() {
312
- if (on || dead) return;
333
+ if (on || dead || lost) return;
313
334
  on = 1; t0 = performance.now() - tm * 1e3;
314
335
  if (AUDIO && ax) { if (ax.state === 'suspended') ax.resume(); sr = ax.createBufferSource(); sr.buffer = ab2; sr.connect(ax.destination); sr.start(0, tm); }
315
336
  frame();
@@ -43,6 +43,10 @@ let workerUrl = null;
43
43
  * @param {(err: Error) => void} [options.onError] - Receives worker errors,
44
44
  * WGSL compilation errors (name "PngineShaderError", with lineNum/linePos/context),
45
45
  * and WebGPU uncaptured errors (name "PngineGPUError")
46
+ * @param {(values: number[]) => void} [options.onQueryResult] - Receives the
47
+ * contents of every `map-read` buffer the frame copies into, once per submit,
48
+ * as one number per 64-bit lane. Written for timestamp and occlusion query
49
+ * results; a compute readback has to write 64-bit lanes to survive it.
46
50
  * @returns {Promise<Pngine>}
47
51
  */
48
52
  export async function pngine(source, options = {}) {
@@ -90,22 +94,30 @@ export async function pngine(source, options = {}) {
90
94
  // Pointer/keyboard tracking — must attach before transferControlToOffscreen.
91
95
  const { pointer: ptr, detach: detachListeners } = attachPointerTracking(canvas);
92
96
 
93
- const offscreen = canvas.transferControlToOffscreen();
94
- const worker = new Worker(getWorkerUrl(), { type: "module" });
95
-
96
- // Slice bytecode so the original buffer stays alive for extractAudio below.
97
- const bc = bytecode.slice();
98
- const result = await awaitWorkerReady(
99
- worker,
100
- {
101
- type: "init",
102
- canvas: offscreen,
103
- bytecode: bc,
104
- debug: options.debug || false,
105
- },
106
- [offscreen, bc.buffer],
107
- options
108
- );
97
+ // Until the handle exists the listeners are ours to release — a worker that
98
+ // fails to come up rejects from this block (see init.js for the full note).
99
+ let worker, result;
100
+ try {
101
+ const offscreen = canvas.transferControlToOffscreen();
102
+ worker = new Worker(getWorkerUrl(), { type: "module" });
103
+
104
+ // Slice bytecode so the original buffer stays alive for extractAudio below.
105
+ const bc = bytecode.slice();
106
+ result = await awaitWorkerReady(
107
+ worker,
108
+ {
109
+ type: "init",
110
+ canvas: offscreen,
111
+ bytecode: bc,
112
+ debug: options.debug || false,
113
+ },
114
+ [offscreen, bc.buffer],
115
+ options
116
+ );
117
+ } catch (err) {
118
+ detachListeners();
119
+ throw err;
120
+ }
109
121
 
110
122
  // Built BEFORE the audio phase — see init.js for why: by this point the
111
123
  // device, the transferred canvas and seven listeners are all committed, and