pngine 2.2.0 → 3.0.0
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/README.md +7 -0
- package/dist/core.mjs +4 -4
- package/dist/dev.mjs +1 -1
- package/dist/mini-no-audio.mjs +1 -1
- package/dist/mini.mjs +1 -1
- package/dist/viewer.mjs +1 -1
- package/package.json +7 -7
- package/schema/pngine.sjon +921 -413
- package/src/core.js +10 -5
- package/src/descriptor-decode.js +5 -1
- package/src/gpu-resource-pass-commands.js +42 -6
- package/src/gpu.js +45 -20
- package/src/init-core.js +6 -0
- package/src/init.js +48 -31
- package/src/mini.js +30 -9
- package/src/viewer-init.js +24 -16
- package/src/worker-core.js +47 -15
- package/src/worker-prefetch.js +7 -2
- package/wasm/pngine-compiler.wasm +0 -0
- package/wasm/pngine.wasm +0 -0
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
|
|
131
|
-
*
|
|
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 = '
|
|
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');
|
package/src/descriptor-decode.js
CHANGED
|
@@ -96,7 +96,11 @@ export function decodeTextureViewDescriptor(bytes) {
|
|
|
96
96
|
* @returns {object} - GPUSamplerDescriptor-shaped object
|
|
97
97
|
*/
|
|
98
98
|
export function decodeSamplerDescriptor(bytes) {
|
|
99
|
-
|
|
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 (
|
|
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.
|
|
313
|
-
const
|
|
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
|
|
81
|
-
//
|
|
82
|
-
|
|
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: "
|
|
86
|
-
* set, else
|
|
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 "
|
|
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 "
|
|
94
|
-
return (view.getUint16(6, true) &
|
|
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
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|
597
|
-
//
|
|
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:
|
|
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
|
@@ -33,6 +33,9 @@ let workerUrl = null;
|
|
|
33
33
|
export async function pngine(source, options = {}) {
|
|
34
34
|
// Resolve source to canvas + bytecode + raw PNG data
|
|
35
35
|
let canvas, bytecode, rawData;
|
|
36
|
+
// True when initFromImage created the placeholder canvas itself — then it is
|
|
37
|
+
// ours to remove on destroy (a host-supplied canvas is the host's).
|
|
38
|
+
let createdCanvas = false;
|
|
36
39
|
|
|
37
40
|
if (typeof source === "string") {
|
|
38
41
|
// Check for CSS selector (# or . but not relative paths like ./ or ../)
|
|
@@ -42,7 +45,7 @@ export async function pngine(source, options = {}) {
|
|
|
42
45
|
if (!el) throw new Error(`Element not found: ${source}`);
|
|
43
46
|
|
|
44
47
|
if (el instanceof HTMLImageElement) {
|
|
45
|
-
({ canvas, bytecode, rawData } = await initFromImage(el, options));
|
|
48
|
+
({ canvas, bytecode, rawData, createdCanvas } = await initFromImage(el, options));
|
|
46
49
|
} else if (el instanceof HTMLCanvasElement) {
|
|
47
50
|
canvas = el;
|
|
48
51
|
throw new Error("Canvas source requires URL or data");
|
|
@@ -58,7 +61,7 @@ export async function pngine(source, options = {}) {
|
|
|
58
61
|
bytecode = await extractBytecode(rawData);
|
|
59
62
|
}
|
|
60
63
|
} else if (source instanceof HTMLImageElement) {
|
|
61
|
-
({ canvas, bytecode, rawData } = await initFromImage(source, options));
|
|
64
|
+
({ canvas, bytecode, rawData, createdCanvas } = await initFromImage(source, options));
|
|
62
65
|
} else if (
|
|
63
66
|
source instanceof ArrayBuffer ||
|
|
64
67
|
source instanceof Uint8Array ||
|
|
@@ -78,34 +81,47 @@ export async function pngine(source, options = {}) {
|
|
|
78
81
|
// Pointer/keyboard tracking — must attach before transferControlToOffscreen.
|
|
79
82
|
const { pointer: ptr, detach: detachListeners } = attachPointerTracking(canvas);
|
|
80
83
|
|
|
81
|
-
//
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
//
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
84
|
+
// From here until the handle exists, the listeners are ours to release: a
|
|
85
|
+
// worker that fails to come up (WebGPU unsupported, a refused payload, the
|
|
86
|
+
// 15 s timeout, `new Worker` throwing under CSP) rejects from inside this
|
|
87
|
+
// block, and the seven listeners — two of them on `document` — used to
|
|
88
|
+
// outlive the rejection for the page's life. LEAK-06-C closed the audio
|
|
89
|
+
// phase one await later; this is the await before it.
|
|
90
|
+
let worker, result;
|
|
91
|
+
try {
|
|
92
|
+
// Get OffscreenCanvas
|
|
93
|
+
const offscreen = canvas.transferControlToOffscreen();
|
|
94
|
+
|
|
95
|
+
// Spawn worker
|
|
96
|
+
worker = new Worker(getWorkerUrl(), { type: "module" });
|
|
97
|
+
|
|
98
|
+
// Compute WASM URL - must be absolute for worker blob context.
|
|
99
|
+
// ../wasm/ resolves from both src/ (repo dev) and dist/ (published bundle)
|
|
100
|
+
// to the package's wasm/pngine.wasm fallback.
|
|
101
|
+
const wasmUrl = options.wasmUrl
|
|
102
|
+
? new URL(options.wasmUrl, window.location.href).href
|
|
103
|
+
: new URL("../wasm/pngine.wasm", import.meta.url).href;
|
|
104
|
+
|
|
105
|
+
// Wait for ready — slice bytecode so the original buffer stays alive for
|
|
106
|
+
// extractAudio below.
|
|
107
|
+
const bc = bytecode.slice();
|
|
108
|
+
result = await awaitWorkerReady(
|
|
109
|
+
worker,
|
|
110
|
+
{
|
|
111
|
+
type: "init",
|
|
112
|
+
canvas: offscreen,
|
|
113
|
+
bytecode: bc,
|
|
114
|
+
wasmUrl,
|
|
115
|
+
debug: options.debug || false,
|
|
116
|
+
},
|
|
117
|
+
[offscreen, bc.buffer],
|
|
118
|
+
options
|
|
119
|
+
);
|
|
120
|
+
} catch (err) {
|
|
121
|
+
detachListeners();
|
|
122
|
+
if (createdCanvas) canvas.remove?.();
|
|
123
|
+
throw err;
|
|
124
|
+
}
|
|
109
125
|
|
|
110
126
|
// The instance exists BEFORE the audio phase, because the audio phase is the
|
|
111
127
|
// first thing that can fail after the worker reports ready — and by then the
|
|
@@ -118,6 +134,7 @@ export async function pngine(source, options = {}) {
|
|
|
118
134
|
// (Report logical/CSS dimensions, not physical.)
|
|
119
135
|
const p = createPngine({
|
|
120
136
|
canvas,
|
|
137
|
+
createdCanvas,
|
|
121
138
|
worker,
|
|
122
139
|
pointer: ptr,
|
|
123
140
|
detachListeners,
|
|
@@ -205,7 +222,7 @@ async function initFromImage(img, options) {
|
|
|
205
222
|
const rawData = await resp.arrayBuffer();
|
|
206
223
|
const bytecode = await extractBytecode(rawData);
|
|
207
224
|
|
|
208
|
-
return { canvas, bytecode, rawData };
|
|
225
|
+
return { canvas, bytecode, rawData, createdCanvas: !options.canvas };
|
|
209
226
|
}
|
|
210
227
|
|
|
211
228
|
// 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
|
|
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
|
|
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
|
-
|
|
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 =
|
|
237
|
-
|
|
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();
|
package/src/viewer-init.js
CHANGED
|
@@ -90,22 +90,30 @@ export async function pngine(source, options = {}) {
|
|
|
90
90
|
// Pointer/keyboard tracking — must attach before transferControlToOffscreen.
|
|
91
91
|
const { pointer: ptr, detach: detachListeners } = attachPointerTracking(canvas);
|
|
92
92
|
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
93
|
+
// Until the handle exists the listeners are ours to release — a worker that
|
|
94
|
+
// fails to come up rejects from this block (see init.js for the full note).
|
|
95
|
+
let worker, result;
|
|
96
|
+
try {
|
|
97
|
+
const offscreen = canvas.transferControlToOffscreen();
|
|
98
|
+
worker = new Worker(getWorkerUrl(), { type: "module" });
|
|
99
|
+
|
|
100
|
+
// Slice bytecode so the original buffer stays alive for extractAudio below.
|
|
101
|
+
const bc = bytecode.slice();
|
|
102
|
+
result = await awaitWorkerReady(
|
|
103
|
+
worker,
|
|
104
|
+
{
|
|
105
|
+
type: "init",
|
|
106
|
+
canvas: offscreen,
|
|
107
|
+
bytecode: bc,
|
|
108
|
+
debug: options.debug || false,
|
|
109
|
+
},
|
|
110
|
+
[offscreen, bc.buffer],
|
|
111
|
+
options
|
|
112
|
+
);
|
|
113
|
+
} catch (err) {
|
|
114
|
+
detachListeners();
|
|
115
|
+
throw err;
|
|
116
|
+
}
|
|
109
117
|
|
|
110
118
|
// Built BEFORE the audio phase — see init.js for why: by this point the
|
|
111
119
|
// device, the transferred canvas and seven listeners are all committed, and
|